Skip to main content

ferroui_media_video_linux/
lib.rs

1//! GStreamer playback using one native pipeline for decoded video and audio.
2#![cfg(target_os = "linux")]
3#![forbid(unsafe_code)]
4#[cfg(feature = "controls")]
5pub use ferroui_media_linux::NativeGlTextureImporter;
6use ferroui_media_linux::{admitted_caps, poll_native, LinuxFrameStream, NativeSession};
7use ferroui_media_opengl::NativeGlFrameProducer;
8use ferroui_media_video::{frames::*, *};
9use std::{path::PathBuf, rc::Rc, task::Poll, time::Duration};
10
11pub struct LinuxVideoProvider {
12    pub frames: NativeGlFrameProducer,
13}
14fn error(message: impl Into<String>) -> MediaError {
15    MediaError::new(MediaErrorKind::InvalidSource, message)
16}
17fn file_uri(path: PathBuf) -> Result<String, MediaError> {
18    use std::os::unix::ffi::OsStrExt;
19    let absolute = if path.is_absolute() {
20        path
21    } else {
22        std::env::current_dir()
23            .map_err(|e| error(e.to_string()))?
24            .join(path)
25    };
26    let mut uri = String::from("file://");
27    for &byte in absolute.as_os_str().as_bytes() {
28        if byte.is_ascii_alphanumeric() || b"/-._~".contains(&byte) {
29            uri.push(byte as char)
30        } else {
31            uri.push_str(&format!("%{byte:02X}"));
32        }
33    }
34    Ok(uri)
35}
36struct Session {
37    stream: LinuxFrameStream,
38    _resource: Option<TemporaryMediaFile>,
39}
40impl MediaPlayerProvider for LinuxVideoProvider {
41    fn open(
42        &self,
43        source: MediaSource,
44        id: u64,
45        generation: u64,
46        _: PresentationPolicy,
47    ) -> MediaFuture<Rc<dyn NativeMediaSession>> {
48        let frames = self.frames.clone();
49        Box::pin(async move {
50            let caps = admitted_caps(&frames, None).await?;
51            let PreparedMediaSource {
52                location,
53                temporary: resource,
54            } = source.prepare_native(None).await?;
55            let url = match location {
56                NativeMediaLocation::Url(url) => url,
57                NativeMediaLocation::File(path) => file_uri(path)?,
58            };
59            let native = NativeSession::open(&url, &caps, 0, -1, 0)?;
60            let mut session = Some(Session {
61                stream: LinuxFrameStream::new(native, frames, id, generation),
62                _resource: resource,
63            });
64            poll_native(
65                move || match session.as_ref().unwrap().stream.native.state() {
66                    Err(e) => Poll::Ready(Err(e)),
67                    Ok(s) if s.state == 0 => Poll::Pending,
68                    Ok(_) => Poll::Ready(Ok(
69                        Rc::new(session.take().unwrap()) as Rc<dyn NativeMediaSession>
70                    )),
71                },
72            )
73            .await
74        })
75    }
76}
77impl NativeMediaSession for Session {
78    fn has_pending_frame_work(&self) -> bool {
79        self.stream.has_pending_frame_work()
80    }
81    fn state(&self) -> Result<MediaPlaybackSession, MediaError> {
82        let s = self.stream.native.state()?;
83        Ok(MediaPlaybackSession {
84            state: if s.buffering != 0 {
85                MediaPlaybackState::Buffering
86            } else {
87                match s.state {
88                    0 => MediaPlaybackState::Opening,
89                    1 => MediaPlaybackState::Paused,
90                    2 => MediaPlaybackState::Playing,
91                    4 => MediaPlaybackState::Ended,
92                    _ => MediaPlaybackState::Failed,
93                }
94            },
95            position: Duration::from_nanos(s.position_ns),
96            duration: (s.duration_ns != u64::MAX).then(|| Duration::from_nanos(s.duration_ns)),
97            natural_size: (s.width > 0 && s.height > 0).then_some((s.width, s.height)),
98            seekable: s.seekable != 0,
99            decode: Acceleration::Unknown,
100            error: None,
101        })
102    }
103    fn play(&self) -> MediaFuture<()> {
104        self.stream.native.intent(1);
105        let native = self.stream.native.clone();
106        poll_native(move || match native.state() {
107            Err(e) => Poll::Ready(Err(e)),
108            Ok(s) if s.state == 2 => Poll::Ready(Ok(())),
109            _ => Poll::Pending,
110        })
111    }
112    fn pause(&self) -> Result<(), MediaError> {
113        self.stream.native.state()?;
114        self.stream.native.intent(0);
115        Ok(())
116    }
117    fn stop(&self) -> Result<(), MediaError> {
118        self.pause()
119    }
120    fn seek(&self, position: Duration) -> MediaFuture<Duration> {
121        let native = self.stream.native.clone();
122        let ns = u64::try_from(position.as_nanos()).unwrap_or(u64::MAX);
123        let epoch = native.seek(ns);
124        self.stream.retire(epoch);
125        poll_native(move || match native.state() {
126            Err(e) => Poll::Ready(Err(e)),
127            Ok(s) if s.seek_done >= epoch => Poll::Ready(Ok(Duration::from_nanos(s.position_ns))),
128            _ => Poll::Pending,
129        })
130    }
131    fn set_audio(&self, volume: f64, muted: bool) -> Result<(), MediaError> {
132        self.stream.native.state()?;
133        self.stream.native.audio(volume, muted);
134        Ok(())
135    }
136    fn take_frame(&self) -> Result<Option<FrameLease>, MediaError> {
137        self.stream.take_frame()
138    }
139}