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
use std::sync::mpsc::{TryRecvError,RecvError};
use std::rc::Rc;
use std::mem;
use std::ptr;
use std::cell::RefCell;
use std::ops::{Deref, DerefMut};

use gst::ffi::*;
use util;
use gst::AppSink;
use gst::Pipeline;
use gst::appsink;
use gst::Sample;
use gst;
use gl;

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

pub struct VideoInfo{
    width: i32,
    height: i32,
    fps_d: i32,
    fps_n: i32,
}

pub struct VideoAppSink{
    appsink: AppSink,
    pipeline: Pipeline,
    last_frame: Option<Rc<::Frame>>,
    info: RefCell<Option<VideoInfo>>,
    out_format: RefCell<String>,
    is_stream: bool,
    context_id: usize,
    creation_proxy: gl::CreationProxy,
}

impl VideoAppSink{
    pub fn new(pipeline: gst::Pipeline, mut appsink: AppSink, is_stream: bool, out_format: Option<&str>, gl: &mut gl::Renderer) -> VideoAppSink{
		gst::init();
		gst::mainloop::spawn();
		appsink.set("emit-signals",0i32);
		appsink.set("sync",1i32);
		VideoAppSink{
		  appsink: appsink,
		  pipeline: pipeline,
		  last_frame: None,
		  info: RefCell::new(None),
		  is_stream: is_stream,
		  out_format: RefCell::new(out_format.map_or("".to_string(), |out_format| { out_format.to_string() })),
          context_id: gl.id(),
          creation_proxy: gl.creation_proxy(),
		}
    }

    pub fn new_from_str(pipeline_str: &str, is_stream: bool, out_format: Option<&str>, gl: &mut gl::Renderer) -> util::Result<VideoAppSink>{
		gst::init();
		gst::mainloop::spawn();
		let pipeline_with_sink_str =
			if out_format.is_some(){
				vec!(pipeline_str.to_string(),
					" ! appsink enable-last-sample=0 name=".to_string(), APPSINK_ELEMENT_NAME.to_string(),
					" caps=\"video/x-raw, format=".to_string(), out_format.unwrap().to_string(), "\"".to_string())
			}else{
				vec!(pipeline_str.to_string(),
					" ! appsink enable-last-sample=0 name=".to_string(), APPSINK_ELEMENT_NAME.to_string(),
					" caps=\"video/x-raw\"".to_string())
			}.concat();

		match Pipeline::new_from_str(&pipeline_with_sink_str[..]){
			Ok(pipeline) => {
				let appsink_element = pipeline.get_by_name(APPSINK_ELEMENT_NAME).unwrap();
				let appsink = AppSink::new_from_element(appsink_element);
				Ok(VideoAppSink::new(pipeline, appsink, is_stream, out_format, gl))
			}
			Err(err) => {
				Err(util::Error::with_cause(&format!("videoappsink: couldn't create pipeline from string:\n{}", pipeline_with_sink_str), err))
			}
		}
    }

    pub fn start_pipeline(&mut self){
        //self.with_mut_appsink(|a| a.spawn_samples_loop());
		self.pipeline.set_ready_state();
		if !self.is_stream(){
			self.pipeline.is_ready_state();
			self.pause();
			if self.is_paused(){
				match self.get_info(){
					Some((info,format)) => {
						*self.info.borrow_mut() = Some(info);
						*self.out_format.borrow_mut() = format;
					}
					_ => {}
				}
			}
		}
    }

    fn get_info(&self) -> Option<(VideoInfo,String)>{
        unsafe{
			let pad = gst_element_get_static_pad(self.gst_appsink() as *mut GstElement, to_c_str!("sink"));
			let info_format = gst::Caps::new(gst_pad_get_current_caps(pad))
				.and_then(|caps| caps.video_info())
				.and_then(|videoinfo| {
					Some((VideoInfo{
						width: videoinfo.width,
						height: videoinfo.height,
						fps_n: videoinfo.fps_n,
						fps_d: videoinfo.fps_d,
					},from_c_str!((*videoinfo.finfo).name).to_string()))
				});
			gst_object_unref(mem::transmute(pad));
			info_format
        }
    }

    pub fn recv_appsink_msg(&self) -> Result<gst::appsink::Message,RecvError>{
        let message = self.appsink.recv();

		match self.get_info(){
			Some((info,format)) => {
				*self.info.borrow_mut() = Some(info);
				*self.out_format.borrow_mut() = format;
			}
			_ => {}
		}

		message
    }

    pub fn try_recv_appsink_msg(&self) -> Result<gst::appsink::Message,TryRecvError>{
        let message = self.appsink.try_recv();
		match message{
			Ok(s) => {
				match self.get_info(){
					Some((info,format)) => {
						*self.info.borrow_mut() = Some(info);
						*self.out_format.borrow_mut() = format;
					}
					_ => {}
				}
				Ok(s)
			}

			_ => {message}
		}
    }

    fn try_recv_sample(&self) -> Result<Sample,TryRecvError>{
        match self.try_recv_appsink_msg() {
            Ok(msg) => {
                match msg{
                    appsink::Message::NewSample(s) => Ok(s),
                    appsink::Message::NewPreroll(s) => Ok(s),
                    _ => Err(TryRecvError::Empty)
                }
            },
            Err(err) => Err(err)
        }
    }

    fn try_recv_last_sample(&self) -> Result<Sample,TryRecvError>{
        let mut sample_result = self.try_recv_sample();
        let mut prev_result = Err(TryRecvError::Empty);
        while sample_result.is_ok(){
            prev_result = sample_result;
            sample_result = self.try_recv_sample();
        }
        prev_result
    }

    pub fn out_format(&self) -> String{
		self.out_format.borrow().clone()
	}

    pub fn is_stream(&self) -> bool {
        self.is_stream
    }

    pub fn frames(&self) -> i64{
		self.pipeline.duration_ns()
			.map_or(0, |t| {
				let fps = (self as &::Video).fps();
				if fps > 0.0 {
					(util::ns_to_s(t as u64) as f64 / fps) as i64
				} else {
					0
				}
			})
    }

    pub unsafe fn gst_appsink(&self) -> *const GstAppSink{
        self.appsink.gst_appsink()
    }

    pub unsafe fn gst_appsink_mut(&mut self) -> *mut GstAppSink{
        self.appsink.gst_appsink_mut()
    }

    pub fn set<T>(&self, name: &str, value: T){
        unsafe{
            g_object_set(mem::transmute(self.gst_pipeline()), to_c_str!(name), value, ptr::null::<gchar>());
        }
    }
}

impl ::Video for VideoAppSink{
    fn recv_frame(&self) -> Result<Rc<::Frame>,RecvError>{
        let msg = self.recv_appsink_msg();
        match msg{
            Ok(appsink::Message::NewSample(s)) | Ok(appsink::Message::NewPreroll(s)) =>
				match ::Frame::new(self.context_id, &self.creation_proxy, s){
					Ok(frame) => Ok(Rc::new(frame)),
					Err(_) => Err(RecvError) //TODO: shouldn't this return RecvError, wait?
				},
			Ok(appsink::Message::Eos) => self.recv_frame(),
            Err(err) => Err(err)
        }
    }

    fn try_recv_frame(&self) -> Result<Rc<::Frame>,TryRecvError>{
        self.try_recv_appsink_msg().and_then(|msg|
			match msg{
				appsink::Message::NewSample(s) => match ::Frame::new(self.context_id, &self.creation_proxy, s){
						Ok(f)	=> Ok(Rc::new(f)),
						_	=> Err(TryRecvError::Empty)
					},
				appsink::Message::NewPreroll(s) => match ::Frame::new(self.context_id, &self.creation_proxy, s){
						Ok(f)	=> Ok(Rc::new(f)),
						_	=> Err(TryRecvError::Empty)
					},
				_ => Err(TryRecvError::Empty)
			}
        )
    }

    fn recv_last_frame(&self) -> Result<Rc<::Frame>,RecvError>{
        match self.try_recv_last_frame(){
			Ok(frame) => Ok(frame),
			Err(TryRecvError::Empty) => self.recv_frame(),
			Err(TryRecvError::Disconnected) => Err(RecvError)
        }
    }

    fn try_recv_last_frame(&self) -> Result<Rc<::Frame>,TryRecvError>{
        self.try_recv_last_sample().and_then(|s|
			match ::Frame::new(self.context_id, &self.creation_proxy, s){
				Ok(frame) => Ok(Rc::new(frame)),
				Err(_) => Err(TryRecvError::Empty)
			}
        )
    }

    fn update(&mut self){
        let sample = self.try_recv_last_sample();
		match sample{
			Ok(s) => {
				match ::Frame::new(self.context_id, &self.creation_proxy, s){
					Ok(f) => self.last_frame = Some(Rc::new(f)),
					Err(_)	=> {}
				}
			}
			_ => {}
		}
    }

    fn last_frame(&self) -> Option<&Rc<::Frame>>{
		match self.last_frame {
			Some(ref f)	=> Some(&f),
			None	=> None
		}
    }

    fn width(&self) -> i32{
        self.info.borrow().as_ref().map_or(0, |info| info.width)
    }

    fn height(&self) -> i32{
        self.info.borrow().as_ref().map_or(0, |info| info.height)
    }

    fn fps(&self) -> f64{
        self.info.borrow().as_ref().map_or(0.0, |info| info.fps_n as f64 / info.fps_d as f64)
    }

    // TODO: calculate the real fps
    fn real_fps(&self) -> f64{
        self.fps()
    }
}

impl gst::Transfer for VideoAppSink{
    unsafe fn transfer(self) -> *mut GstElement{
        self.pipeline.transfer()
    }
}



impl AsRef<gst::Pipeline> for VideoAppSink{
    fn as_ref(&self) -> &gst::Pipeline{
        &self.pipeline
    }
}

impl AsMut<gst::Pipeline> for VideoAppSink{
    fn as_mut(&mut self) -> &mut gst::Pipeline{
        &mut self.pipeline
    }
}

impl From<VideoAppSink> for gst::Pipeline{
    fn from(b: VideoAppSink) -> gst::Pipeline{
        b.pipeline
    }
}

impl Deref for VideoAppSink{
    type Target = gst::Pipeline;
    fn deref(&self) -> &gst::Pipeline{
        &self.pipeline
    }
}

impl DerefMut for VideoAppSink{
    fn deref_mut(&mut self) -> &mut gst::Pipeline{
        &mut self.pipeline
    }
}