1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
use std::ptr;
use std::path::{Path, PathBuf};
use std::borrow::ToOwned;
use std::sync::mpsc::{TryRecvError,RecvError};
use std::rc::Rc;

use gst::ffi::*;
use gst::{self, PlayBin, AppSink, Caps, Reference};

use ::VideoAppSink;
use ::Frame;
use ::Video;
use gl;
use na::*;
use gl::{Renderer, traits::Renderer as RendererT, Renderer2d};
use util;
use graphics::{self, CoordinateOrigin};
use gl::RenderSurface;

#[cfg(feature = "events")]
use seitan::{Stream, StreamRc, StreamT};

static PLAYBIN_ELEMENT_NAME: &'static str = "player";
static APPSINK_ELEMENT_NAME: &'static str = "app_sink";

#[cfg(feature = "events")]
#[allow(dead_code)]
pub struct Builder<'a, 'c> where 'c: 'a{
    path: PathBuf,
    format: Option<String>,
    name: String,

    play_stream: Option<StreamRc<'static, bool>>,
    position_stream: Option<StreamRc<'static, f64>>,
    context: &'a mut gl::Renderer<'c>,
}

#[cfg(not(feature = "events"))]
pub struct Builder<'a, 'c>{
    path: PathBuf,
    format: Option<String>,
    name: String,
    context: &'a mut gl::Renderer<'c>,
}

impl<'a, 'c> Builder<'a, 'c> where 'c: 'a{
    pub fn new<P: AsRef<Path>>(path: P, gl: &'a mut gl::Renderer<'c>) -> Builder<'a,'c>{
        Builder{
            path: path.as_ref().to_owned(),
            format: None,
            name: String::new(),
            play_stream: None,
            position_stream: None,
            context: gl,
        }
    }

    pub fn format(&mut self, format: &str) -> &mut Builder<'a, 'c>{
        self.format = Some(format.to_owned());
        self
    }

    pub fn gst_name(&mut self, name: &str) -> &mut Builder<'a, 'c>{
        self.name = name.to_owned();
        self
    }

    #[cfg(feature = "events")]
    pub fn play_stream<S: Into<StreamRc<'static,bool>>>(&mut self, play_stream: S) -> &mut Builder<'a, 'c>{
        self.play_stream = Some(play_stream.into());
        self
    }

    #[cfg(feature = "events")]
    pub fn position_pct_stream<S: Into<StreamRc<'static,f64>>>(&mut self, position_stream: S) -> &mut Builder<'a, 'c>{
        self.position_stream = Some(position_stream.into());
        self
    }

    #[cfg(feature = "events")]
    fn set_event_streams(&self, player: &mut Player){
        if let Some(play_stream) = self.play_stream.clone(){
            let mut appsink = player.appsink.reference();
            player.play_stream = play_stream.on_value(move |play| if play{
                appsink.play();
            }else{
                appsink.pause();
            });
        }

        if let Some(position_stream) = self.position_stream.clone(){
            let mut appsink = player.appsink.reference();
            player.position_stream = position_stream.on_value(move |pos| { appsink.set_position_pct(pos); } );
        }
    }

    #[cfg(not(feature = "events"))]
    fn set_event_streams(&self, player: &mut Player){
    }

    pub fn create(&mut self) -> util::Result<Player>{
        gst::init();
        gst::mainloop::spawn();
        unsafe{
            let playbin = PlayBin::new(&self.name);

            if playbin.is_none() {
                return Err(util::Error::new("failed to create playbin"))
            }

            let mut playbin = playbin.unwrap();

			if self.format.is_none(){
				// no videoconvert or scale
				playbin.set_flags(0x00000053i32);
			}


            let appsink = AppSink::new(APPSINK_ELEMENT_NAME);

            if appsink.is_none(){
				return Err(util::Error::new("failed to create appsink"));
			}

			let mut appsink = appsink.unwrap();


            let uri = match gst::filename_to_uri(self.path.to_str().ok_or("Invalid path")?){
            	Ok(uri) => uri,
            	Err(err) => return Err(util::Error::with_cause("error converting uri to filename", err))
            };

			playbin.set_uri(uri.as_ref());

			let is_stream = match gst::uri_get_protocol(uri.as_ref()){
				Ok(protocol) => protocol == "file",
				_ => false
			};


            let format = self.format.as_ref().map(|f| f.as_str());

            let appsink_caps = if self.format.is_some(){
				Caps::new(gst_caps_new_simple(to_c_str!("video/x-raw"),
							   to_c_str!("format"), 16<<2, to_c_str!(format.unwrap()),
							   ptr::null::<gchar>()))
			}else{
				Some(Caps::new_empty_simple("video/x-raw"))
			};

			match appsink_caps{
            	Some(caps) => appsink.set_caps(caps),
            	None => return Err(util::Error::new("Couldn't create caps for appsink"))
            }

            playbin.set_video_sink(&appsink);

            gst_base_sink_set_sync(appsink.gst_appsink() as *mut GstBaseSink, 1);


            let appsink =  VideoAppSink::new(playbin.into(), appsink, is_stream, format, self.context);

            let mut player = Player{
                appsink,
                speed: 1.0,
                play_stream: Stream::never(),
                position_stream: Stream::never()
            };

            self.set_event_streams(&mut player);

            player.appsink.start_pipeline();

            Ok( player )
        }
    }
}

/// Video player, allows to play a video file using several models like calling
/// update or polling the frames port for available frames both in blocking and
/// non-blocking modes
#[cfg(feature = "events")]
#[allow(dead_code)]
pub struct Player{
    appsink: VideoAppSink,
    speed: f64,

    play_stream: Stream<'static, bool>,
    position_stream: Stream<'static, f64>,
}

#[cfg(not(feature = "events"))]
pub struct Player{
    appsink: VideoAppSink,
    speed: f64
}

impl Player{
    pub fn new<P: AsRef<Path>>(path: P, gl: &mut gl::Renderer) -> util::Result<Player>{
        Builder::new(path, gl)
            .gst_name(PLAYBIN_ELEMENT_NAME)
            .create()
    }

    /// Reference to the internal VideoAppSink
    pub fn appsink(&self) -> &VideoAppSink{
        &self.appsink
    }

    /// Mutable reference to the internal VideoAppSink
    pub fn appsink_mut(&mut self) -> &mut VideoAppSink{
        &mut self.appsink
    }

    /// Sets the player in play state
    pub fn play(&mut self) {
        self.appsink.play();
    }

    /// Total frames of the video
    pub fn frames(&self) -> i64{
        self.appsink.frames()
    }

    /// Frames per second of the video
    pub fn fps(&self) -> f64{
        self.appsink.fps()
    }

    /// Duration of the video in nanoseconds
    pub fn duration_ns(&self) -> Option<i64>{
        self.appsink.duration_ns()
    }

    /// Duration of the video in seconds
    pub fn duration_s(&self) -> Option<f64>{
        self.appsink.duration_s()
    }

    /// Current position in the video in 0..1
    pub fn position_pct(&self) -> Option<f64>{
        self.appsink.position_pct()
    }

    /// Current position in the video in nanoseconds
    pub fn position_ns(&self) -> Option<i64>{
        self.appsink.position_ns()
    }

    /// Current position in the video in seconds
    pub fn position_s(&self) -> Option<f64>{
        self.appsink.position_s()
    }

    #[cfg(feature = "events")]
    pub fn position_pct_stream<'a: 'b,'b,T: Clone + Debug>(&self, update_stream: Stream<'a,T>) -> Stream<'b,f64>{
        let player = self.appsink.reference();
        update_stream.filter_map(move |_| player.position_pct())
    }

    /// Current playback speed of the video in 0..1
    pub fn speed(&self) -> f64{
        self.speed
    }

    /// Sets current position in the video in nanoseconds
    pub fn set_position_ns(&mut self, ns: i64){
        self.appsink.set_position_ns(ns);
    }

    /// Sets current position in the video in seconds
    pub fn set_position_s(&mut self, s: f64){
        self.appsink.set_position_s(s);
    }

    /// Sets current position in the video in 0..1
    pub fn set_position_pct(&mut self, pct: f64){
        self.appsink.set_position_pct(pct);
    }

    /// Sets current playback speed of the video in 0..1
    pub fn set_speed(&mut self, speed: f64){
        self.speed = speed;
        self.appsink.set_speed(speed);
    }

    /// Sets the player in paused state
    pub fn pause(&mut self){
        self.appsink.pause();
    }

    /// Sets the player in stopped state
    pub fn stop(&mut self){
        self.appsink.set_ready_state();
    }

    /// Returns true if the player is in paused state
    pub fn is_paused(&self) -> bool{
        self.appsink.is_paused()
    }

    /// Returns true if the player is in stopped state
    pub fn is_stopped(&self) -> bool{
        self.appsink.is_ready_state()
    }
}

impl Video for Player{
    fn recv_frame(&self) -> Result<Rc<Frame>,RecvError>{
        self.appsink.recv_frame()
    }

    fn try_recv_frame(&self) -> Result<Rc<Frame>,TryRecvError>{
        self.appsink.try_recv_frame()
    }

    fn recv_last_frame(&self) -> Result<Rc<Frame>,RecvError>{
        self.appsink.recv_last_frame()
    }

    fn try_recv_last_frame(&self) -> Result<Rc<Frame>,TryRecvError>{
        self.appsink.try_recv_last_frame()
    }

    fn update(&mut self){
        self.appsink.update();
    }

    fn last_frame(&self) -> Option<&Rc<Frame>>{
        self.appsink.last_frame()
    }

    fn width(&self) -> i32{
        self.appsink.width()
    }

    fn height(&self) -> i32{
        self.appsink.height()
    }

    fn fps(&self) -> f64{
        self.appsink.fps()
    }

    // TODO: calculate the real framerate, probably on the appsink
    fn real_fps(&self) -> f64{
        self.appsink.fps()
    }
}


impl<'a> gl::Render2d for &'a ::Player{
    type Material = ::frame::Material<'a>;
    fn default_material(&self) -> ::frame::Material<'a>{
        // self.last_frame().unwrap().default_material()
        ::frame::Material::new(&self.last_frame().unwrap())
    }

    fn render<R: RenderSurface>(&self, renderer: &Renderer<R>, pos: &Pnt2){
        if let Some(frame) = self.last_frame(){
            self.render_size_with_material(renderer, pos, &convert(frame.size()), &self.default_material());
        }
    }

    fn render_size<R: RenderSurface>(&self, renderer: &Renderer<R>, pos: &Pnt2, size: &Vec2){
        if let Some(_frame) = self.last_frame(){
            self.render_size_with_material(renderer, pos, size, &self.default_material());
        }
    }

    fn render_with_material<R: RenderSurface, M: gl::Material>(&self, renderer: &Renderer<R>, pos: &Pnt2, material: &M){
        if let Some(frame) = self.last_frame(){
            self.render_size_with_material(renderer, pos, &convert(frame.size()), material)
        }
    }

    fn render_size_with_material<R: RenderSurface, M: gl::Material>(&self, renderer: &Renderer<R>, pos: &Pnt2, size: &Vec2, material: &M){
        if let Some(_frame) = self.last_frame(){
            let quad = match renderer.origin() {
                CoordinateOrigin::TopLeft | CoordinateOrigin::CenterDown =>
                    graphics::rectangle_texcoords(pos.x,pos.y,size.x,size.y,0.0,1.0,1.0,0.0),
                CoordinateOrigin::BottomLeft | CoordinateOrigin::CenterUp =>
                    graphics::rectangle_texcoords(pos.x,pos.y,size.x,size.y,0.0,0.0,1.0,1.0),
            };
            renderer.draw_mesh_with_material(&quad, material);
        }
    }
}