fui_controls_media 0.19.0

Media controls for FUI UI Framework
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
use anyhow::{format_err, Result};
use fui_core::*;
use gl::types::*;
use gstreamer::prelude::*;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::mpsc::*;
use std::sync::{Arc, Mutex};

//#[cfg(target_os = "linux")]
//use self::glutin::os::unix::RawHandle::Glx;
//#[cfg(target_os = "linux")]
//use self::winit::platform::unix::x11::XConnection;
//#[cfg(target_os = "linux")]
//use self::winit::platform::unix::EventsLoopExt;

//#[cfg(target_os = "linux")]
//use winit::platform::unix::WindowExtUnix;

pub struct PlayerGl {
    //pub texture: PlayerTexture,
    //drawing_context: Rc<RefCell<FuiDrawingContext>>,
    //window_manager: Rc<RefCell<WindowManager>>,
    pipeline: Option<gstreamer::Pipeline>,
    //dispatcher: Arc<Mutex<dyn Dispatcher>>,
    receiver: Option<Receiver<GLuint>>,
    event_loop_proxy: winit::event_loop::EventLoopProxy<()>,
}

impl PlayerGl {
    #[cfg(target_os = "linux")]
    pub fn new(
        //drawing_context: &Rc<RefCell<FuiDrawingContext>>,
        //window_manager: &Rc<RefCell<WindowManager>>,
        event_loop: &winit::event_loop::EventLoop<()>,
    ) -> Result<Self> {
        gstreamer::init()?;

        Ok(PlayerGl {
            //texture: PlayerTexture::new(drawing_context.clone()),
            //drawing_context: drawing_context.clone(),
            //window_manager: window_manager.clone(),
            pipeline: None,
            //dispatcher: Arc::new(Mutex::new(Dispatcher::for_current_thread())),
            receiver: None,
            event_loop_proxy: event_loop.create_proxy(),
        })
    }

    #[cfg(target_os = "windows")]
    pub fn new(
        drawing_context: &Rc<RefCell<fui_app::DrawingContext>>,
        window_manager: &Rc<RefCell<WindowManager>>,
        event_loop: &winit::event_loop::EventLoop<()>,
    ) -> Result<Self> {
        gstreamer::init()?;

        Ok(PlayerGl {
            texture: PlayerTexture::new(drawing_context.clone()),
            drawing_context: drawing_context.clone(),
            window_manager: window_manager.clone(),
            pipeline: None,
            dispatcher: Arc::new(Mutex::new(Dispatcher::for_current_thread())),
            receiver: None,
            event_loop_proxy: event_loop.create_proxy(),
        })
    }

    #[cfg(target_os = "linux")]
    pub fn open(&mut self) -> Result<()> {
        println!("Main thread id: {:?}", std::thread::current().id());

        let (sender, receiver) = channel();
        self.receiver = Some(receiver);
        let _sender = Arc::new(Mutex::new(sender));

        /*let main_window_id = self.window_manager.borrow().get_main_window_id();
        if let Some(main_window_id) = main_window_id {
            if let Some(main_window) = self
                .window_manager
                .borrow_mut()
                .get_windows_mut()
                .get(&main_window_id)
            {
                let window = &main_window.borrow().native_window;
                let window_drawing_target = &window.drawing_target;
                let context = window_drawing_target.get_context();

                let window = window_drawing_target.get_window();
                let xconnection = window.xlib_xconnection().unwrap();

                // Create the elements
                //let (pipeline, video_app_sink) = pipeline_factory::create_pipeline_videotest();
                //self.texture.set_size(320, 240);
                let (pipeline, video_sink) = media_gstreamer::create_opengl_pipeline_url(
                    "http://ftp.nluug.nl/pub/graphics/blender/demo/movies/Sintel.2010.720p.mkv",
                    &context,
                    &xconnection,
                );
                self.texture.set_size(1280, 544);

                video_sink
                    .connect("client-reshape", false, move |args| {
                        println!("client-reshape! {:?}", args);
                        Some(Value::from(&true))
                    })
                    .unwrap();

                let dispatcher_clone = self.dispatcher.clone();
                let event_loop_proxy_clone = self.event_loop_proxy.clone();

                video_sink
                    .connect("client-draw", false, move |args| {
                        println!("client-draw! {:?}", args);
                        let sample = args[2]
                            .get::<gstreamer::Sample>()
                            .unwrap()
                            .expect("Invalid argument - GstSample expected.");
                        if let (Some(buffer), Some(caps)) = (sample.get_buffer(), sample.get_caps())
                        {
                            println!("caps: {}", caps.to_string());
                            if let Ok(video_info) = gstreamer_video::VideoInfo::from_caps(&caps) {
                                println!("video_info: {:?}", video_info);

                                let texture_id = unsafe {
                                    use glib::translate::from_glib;
                                    use glib::translate::ToGlibPtr;
                                    use std::mem;
                                    const GST_MAP_GL: u32 = 131072u32;

                                    // TODO: can we use from_buffer_readable_gl() instead?
                                    // https://gitlab.freedesktop.org/sjakthol/gstreamer-rs/commit/43f5a10f9c75c69fadccdf9d88e0102bd0ecaa5b
                                    let mut frame: gstreamer_video_sys::GstVideoFrame =
                                        mem::zeroed();
                                    let res: bool =
                                        from_glib(gstreamer_video_sys::gst_video_frame_map(
                                            &mut frame,
                                            video_info.to_glib_none().0 as *mut _,
                                            buffer.as_mut_ptr(),
                                            mem::transmute(
                                                gstreamer_video_sys::GST_VIDEO_FRAME_MAP_FLAG_NO_REF
                                                    | gstreamer_sys::GST_MAP_READ
                                                    | GST_MAP_GL,
                                            ),
                                        ));

                                    if !res {
                                        Err(buffer)
                                    } else {
                                        let texture_id = *(frame.data[0] as *const GLuint);
                                        gstreamer_video_sys::gst_video_frame_unmap(&mut frame);
                                        Ok(texture_id)
                                    }
                                };

                                if let Ok(texture_id) = texture_id {
                                    println!("texture_id: {}", texture_id);

                                    sender.lock().unwrap().send(texture_id).unwrap();

                                    // TODO: why send_event() doesn't compile?!!
                                    //event_loop_proxy_clone.send_event(()).unwrap();
                                    //dispatcher_clone.lock().unwrap().send_async(|| {});
                                }
                            }
                            /*let map = buffer.into_mapped_buffer_readable().unwrap();
                            let data = map.as_slice();
                            //println!("data {:?}", data);
                            let texture_id = unsafe { *(data.as_ptr() as *const i64) };
                            println!("texture_id {}", texture_id);*/
                        }
                        Some(Value::from(&true))
                    })
                    .unwrap();

                /*video_app_sink.set_callbacks(gst_app::AppSinkCallbacks::new()
                    .new_sample(move |app_sink| {
                        let timespec = time::get_time();
                        let mills: f64 = timespec.sec as f64 + (timespec.nsec as f64 / 1000.0 / 1000.0 / 1000.0);
                        println!("New sample thread id: {:?}, time: {:?}", std::thread::current().id(), mills);

                        let sample = match app_sink.pull_sample() {
                            None => return gst::FlowReturn::Eos,
                            Some(sample) => sample,
                        };

                        let caps = sample.get_caps().unwrap();
                        let s = caps.get_structure(0).unwrap();
                        let width: i32 = s.get("width").unwrap();
                        let height: i32 = s.get("height").unwrap();
                        let buffer = sample.get_buffer().unwrap();
                        let map = buffer.map_readable().unwrap();
                        let data = map.as_slice();

                        //print!("AppSink: New sample ({}x{}, size: {})\n", width, height, data.len());

                        sender.lock().unwrap().send(Vec::from(data)).unwrap();

                        dispatcher_clone.lock().unwrap().send_async(|| {
                            //texture_clone.lock().unwrap().update_texture();
                        });

                        gst::FlowReturn::Ok
                    })
                    .build()
                );*/

                self.pipeline = Some(pipeline);

                Ok(())
            } else {
                Err(format_err!("Cannot find GL Context for the main window!",))
            }
        } else {
            Err(format_err!("Cannot find GL Context. There is no window!",))
        }*/

        Err(format_err!("Method not implemented yet"))
    }

    #[cfg(target_os = "windows")]
    pub fn open(&mut self) -> Result<()> {
        println!("Main thread id: {:?}", std::thread::current().id());

        let (sender, receiver) = channel();
        self.receiver = Some(receiver);
        let sender = Arc::new(Mutex::new(sender));

        let main_window_id = self.window_manager.borrow().get_main_window_id();
        if let Some(main_window_id) = main_window_id {
            if let Some(main_window) = self
                .window_manager
                .borrow_mut()
                .get_windows_mut()
                .get(&main_window_id)
            {
                let window_drawing_target = main_window.get_drawing_target();
                let context = window_drawing_target.get_context();

                // Create the elements
                //let (pipeline, video_app_sink) = pipeline_factory::create_pipeline_videotest();
                //self.texture.set_size(320, 240);
                let (pipeline, video_sink) = gstreamer_media::create_opengl_pipeline_url(
                    "http://ftp.nluug.nl/pub/graphics/blender/demo/movies/Sintel.2010.720p.mkv",
                    &context,
                );
                self.texture.set_size(1280, 544);

                let dispatcher_clone = self.dispatcher.clone();
                let event_loop_proxy_clone = self.event_loop_proxy.clone();

                video_sink
                    .connect("client-reshape", false, move |args| {
                        println!("client-reshape! {:?}", args);
                        //Some(Value::from(&true))
                        Some(Value::from(&false))
                    })
                    .unwrap();

                video_sink
                    .connect("client-draw", false, move |args| {
                        println!("client-draw! {:?}", args);
                        let sample = args[2]
                            .get::<gstreamer::Sample>()
                            .unwrap()
                            .expect("Invalid argument - GstSample expected.");
                        if let (Some(buffer), Some(caps)) = (sample.get_buffer(), sample.get_caps())
                        {
                            println!("caps: {}", caps.to_string());
                            if let Ok(video_info) = gstreamer_video::VideoInfo::from_caps(&caps) {
                                println!("video_info: {:?}", video_info);

                                let texture_id = unsafe {
                                    use glib::translate::from_glib;
                                    use glib::translate::ToGlibPtr;
                                    use std::mem;
                                    const GST_MAP_GL: u32 = 131072u32;

                                    // TODO: can we use from_buffer_readable_gl() instead?
                                    // https://gitlab.freedesktop.org/sjakthol/gstreamer-rs/commit/43f5a10f9c75c69fadccdf9d88e0102bd0ecaa5b
                                    let mut frame: gstreamer_video_sys::GstVideoFrame =
                                        mem::zeroed();
                                    let res: bool =
                                        from_glib(gstreamer_video_sys::gst_video_frame_map(
                                            &mut frame,
                                            video_info.to_glib_none().0 as *mut _,
                                            buffer.as_mut_ptr(),
                                            mem::transmute(
                                                gstreamer_video_sys::GST_VIDEO_FRAME_MAP_FLAG_NO_REF
                                                    | gstreamer_sys::GST_MAP_READ
                                                    | GST_MAP_GL,
                                            ),
                                        ));

                                    if !res {
                                        Err(buffer)
                                    } else {
                                        let texture_id = *(frame.data[0] as *const GLuint);
                                        gstreamer_video_sys::gst_video_frame_unmap(&mut frame);
                                        Ok(texture_id)
                                    }
                                };

                                if let Ok(texture_id) = texture_id {
                                    println!("texture_id: {}", texture_id);

                                    sender.lock().unwrap().send(texture_id).unwrap();

                                    // TODO: why send_event() doesn't compile?!!
                                    //event_loop_proxy_clone.send_event(()).unwrap();
                                    //dispatcher_clone.lock().unwrap().send_async(|| {});
                                }
                            }
                            /*let map = buffer.into_mapped_buffer_readable().unwrap();
                            let data = map.as_slice();
                            //println!("data {:?}", data);
                            let texture_id = unsafe { *(data.as_ptr() as *const i64) };
                            println!("texture_id {}", texture_id);*/
                        }
                        //Some(Value::from(&true))
                        Some(Value::from(&false))
                    })
                    .unwrap();

                /*video_app_sink.set_callbacks(gst_app::AppSinkCallbacks::new()
                    .new_sample(move |app_sink| {
                        let timespec = time::get_time();
                        let mills: f64 = timespec.sec as f64 + (timespec.nsec as f64 / 1000.0 / 1000.0 / 1000.0);
                        println!("New sample thread id: {:?}, time: {:?}", std::thread::current().id(), mills);

                        let sample = match app_sink.pull_sample() {
                            None => return gst::FlowReturn::Eos,
                            Some(sample) => sample,
                        };

                        let caps = sample.get_caps().unwrap();
                        let s = caps.get_structure(0).unwrap();
                        let width: i32 = s.get("width").unwrap();
                        let height: i32 = s.get("height").unwrap();
                        let buffer = sample.get_buffer().unwrap();
                        let map = buffer.map_readable().unwrap();
                        let data = map.as_slice();

                        //print!("AppSink: New sample ({}x{}, size: {})\n", width, height, data.len());

                        sender.lock().unwrap().send(Vec::from(data)).unwrap();

                        dispatcher_clone.lock().unwrap().send_async(|| {
                            //texture_clone.lock().unwrap().update_texture();
                        });

                        gst::FlowReturn::Ok
                    })
                    .build()
                );*/

                self.pipeline = Some(pipeline);

                Ok(())
            } else {
                Err(format_err!("Cannot find GL Context for the main window!",))
            }
        } else {
            Err(format_err!("Cannot find GL Context. There is no window!",))
        }
    }

    pub fn play(&mut self) {
        // Start playing
        if let Some(ref pipeline) = self.pipeline {
            let ret = pipeline.set_state(gstreamer::State::Playing);
            assert_ne!(ret, Err(gstreamer::StateChangeError));
        }
    }

    pub fn on_loop_interation(&mut self) -> Result<()> {
        if let Some(ref receiver) = self.receiver {
            while let Ok(_texture_id) = receiver.try_recv() {
                let timespec = time::OffsetDateTime::now_utc();
                let _mills: f64 = timespec.second() as f64
                    + (timespec.nanosecond() as f64 / 1000.0 / 1000.0 / 1000.0);
                //println!("buffer size: {}, thread id: {:?}, time: {:?}", buffer.len(), std::thread::current().id(), mills);
                //self.texture.update_texture(texture_id)?
            }
        }
        Ok(())
    }

    pub fn stop(&mut self) {
        // Shutdown pipeline
        if let Some(ref pipeline) = self.pipeline {
            let ret = pipeline.set_state(gstreamer::State::Null);
            assert_ne!(ret, Err(gstreamer::StateChangeError));
        }
    }
}

pub struct PlayerTexture {
    pub updated: Callback<i32>,
    texture_id: i32,
    width: u16,
    height: u16,
    //drawing_context: Rc<RefCell<FuiDrawingContext>>,
}

impl PlayerTexture {
    pub fn new(_drawing_context: Rc<RefCell<FuiDrawingContext>>) -> Self {
        PlayerTexture {
            updated: Callback::empty(),
            texture_id: -1,
            width: 0,
            height: 0,
            //drawing_context,
        }
    }

    pub fn set_size(&mut self, width: u16, height: u16) {
        self.width = width;
        self.height = height;
    }

    fn update_texture(&mut self, _texture_id: GLuint) -> Result<()> {
        let timespec = time::OffsetDateTime::now_utc();
        let mills: f64 =
            timespec.second() as f64 + (timespec.nanosecond() as f64 / 1000.0 / 1000.0 / 1000.0);
        println!(
            "Dispatcher, thread id: {:?}, time: {:?}",
            std::thread::current().id(),
            mills
        );

        /*{
            let texture = drawing_gl::GlTexture::from_external(
                texture_id,
                self.width,
                self.height,
                ColorFormat::RGBA,
            );
            let mut drawing_context = self.drawing_context.borrow_mut();
            let resources = drawing_context.get_resources_mut();
            if self.texture_id == -1 {
                self.texture_id = resources.get_next_texture_id();
            }

            resources.textures_mut().insert(self.texture_id, texture);
        }
        self.updated.emit(self.texture_id);*/

        Ok(())
    }
}