//! Video playback with GStreamer, shown through the glass layer: the film is //! the backdrop, so glass controls on top refract it. //! //! - Hardware decoding (VA-API: H.264, HEVC incl. 10-bit, VP9, AV1) when the //! app has the `gpu` permission; FFmpeg software decoders otherwise. //! - `vapostproc` converts on the GPU and tone-maps HDR to SDR. //! - Every audio and subtitle track of the file (MKV, MP4, TS...), with //! embedded ASS/SRT subtitles rendered by GStreamer. //! - HTTP(S) streams with range seeking (a server streaming a file while it //! downloads works). //! //! ```ignore //! sf_ui::video::init()?; //! let player = Player::new("https://example.com/film.mkv", PlayerOptions { start: 754.0, ..Default::default() })?; //! glass.set_video(Some(player.video())); //! // every ~100 ms on the UI thread (slint::Timer): //! for event in player.poll() { /* Ready, Buffering, Eos, Error... */ } //! ``` //! //! Needs GStreamer 1.22+ on the system (the SmartFox TV has it): base, good, //! bad (va, assrender), libav, and pipewire for sound. Apps need the `gpu` //! and `audio` permissions, and `network` for streams. use std::rc::Rc; use std::sync::{Arc, Mutex}; use anyhow::{Context, Result}; use gstreamer as gst; use gstreamer::glib; use gstreamer::prelude::*; use gstreamer_app as gst_app; use gstreamer_video as gst_video; use gstreamer_video::prelude::*; use crate::glass::VideoSource; use crate::render::{Matrix, Nv12Frame}; /// VA-API decoders, preferred over the software ones when present. const HW_DECODERS: [&str; 6] = ["vah264dec", "vah265dec", "vavp9dec", "vaav1dec", "vavp8dec", "vampeg2dec"]; /// Initialises GStreamer once and ranks the hardware decoders first. pub fn init() -> Result<()> { gst::init().context("initialising GStreamer")?; let registry = gst::Registry::get(); for name in HW_DECODERS { if let Some(feature) = registry.lookup_feature(name) { feature.set_rank(gst::Rank::PRIMARY + 1); } } Ok(()) } /// Whether hardware video decoding is available (diagnostics). pub fn hardware_decoding() -> bool { let registry = gst::Registry::get(); HW_DECODERS.iter().any(|n| registry.lookup_feature(n).is_some()) } #[derive(Debug, Clone)] pub struct PlayerOptions { /// Start position in seconds. pub start: f64, /// Audio sync correction in milliseconds (positive: audio later). pub audio_offset_ms: i64, /// Show subtitles (the default track, see [`Player::set_text`]). pub subtitles: bool, /// HTTP user agent for streams. pub user_agent: Option, /// Pango font for text subtitles (scaled with the video). pub subtitle_font: String, } impl Default for PlayerOptions { fn default() -> Self { PlayerOptions { start: 0.0, audio_offset_ms: 0, subtitles: true, user_agent: None, subtitle_font: "Sans Bold 20".into(), } } } /// What happened since the last [`Player::poll`]. #[derive(Debug, Clone, PartialEq)] pub enum Event { /// The stream is open (first frame ready): duration (s, if known) and /// the tracks can be read now. Playback starts right after. Ready { duration: Option }, /// Network buffering, percent (100 = done; playback pauses meanwhile). Buffering(i32), /// Playing or paused (as asked, or because of buffering). Playing(bool), /// A seek finished. Seeked, /// The end of the stream. Eos, /// A fatal error; the player stops. Error(String), } /// One audio or subtitle track of the stream. #[derive(Debug, Clone, Default, PartialEq)] pub struct Track { /// Index for [`Player::set_audio`] / [`Player::set_text`]. pub index: i32, /// ISO 639 code ("hu", "en", "hun"...), if tagged. pub language: Option, /// The track's title in the file ("Commentary", "Forced"...). pub title: Option, pub codec: Option, } /// The newest decoded frame, shared with the appsink thread. #[derive(Default)] struct Feed { latest: Mutex>, } struct FeedSource(Arc); struct GstFrame { frame: gst_video::VideoFrame, aspect: f32, matrix: Matrix, full: bool, } impl Nv12Frame for GstFrame { fn width(&self) -> u32 { self.frame.width() } fn height(&self) -> u32 { self.frame.height() } fn aspect(&self) -> f32 { self.aspect } fn plane(&self, index: usize) -> (&[u8], usize) { let data = self.frame.plane_data(index as u32).unwrap_or(&[]); let stride = self.frame.plane_stride().get(index).copied().unwrap_or(0).max(0) as usize; (data, stride) } fn matrix(&self) -> Matrix { self.matrix } fn full_range(&self) -> bool { self.full } } impl VideoSource for FeedSource { fn take_frame(&self) -> Option> { let sample = self.0.latest.lock().unwrap().take()?; let info = gst_video::VideoInfo::from_caps(sample.caps()?).ok()?; if info.format() != gst_video::VideoFormat::Nv12 { return None; } let par = info.par(); let aspect = info.width() as f32 * par.numer() as f32 / (info.height().max(1) as f32 * par.denom().max(1) as f32); let colorimetry = info.colorimetry(); let matrix = match colorimetry.matrix() { gst_video::VideoColorMatrix::Bt601 | gst_video::VideoColorMatrix::Smpte240m => Matrix::Bt601, gst_video::VideoColorMatrix::Bt2020 => Matrix::Bt2020, gst_video::VideoColorMatrix::Bt709 => Matrix::Bt709, _ if info.height() < 720 => Matrix::Bt601, _ => Matrix::Bt709, }; let full = colorimetry.range() == gst_video::VideoColorRange::Range0_255; let buffer = sample.buffer_owned()?; let frame = gst_video::VideoFrame::from_buffer_readable(buffer, &info).ok()?; Some(Box::new(GstFrame { frame, aspect, matrix, full })) } } /// A playing stream. Dropping it stops playback. pub struct Player { playbin: gst::Element, bus: gst::Bus, feed: Arc, start: f64, /// Playing was asked for (buffering may hold it paused). want_playing: bool, buffering: bool, ready: bool, seeking: bool, failed: bool, } impl Player { /// Opens `uri` (https://, http://, file://) and starts playing as soon /// as it can. Call [`init`] once before. pub fn new(uri: &str, opts: PlayerOptions) -> Result { let feed = Arc::new(Feed::default()); let caps = gst_video::VideoCapsBuilder::new().format(gst_video::VideoFormat::Nv12).build(); let sink = gst_app::AppSink::builder().caps(&caps).sync(true).max_buffers(2).drop(true).build(); sink.set_property("enable-last-sample", false); let shared = feed.clone(); sink.set_callbacks( gst_app::AppSinkCallbacks::builder() .new_sample(move |s| { let sample = s.pull_sample().map_err(|_| gst::FlowError::Eos)?; *shared.latest.lock().unwrap() = Some(sample); Ok(gst::FlowSuccess::Ok) }) .build(), ); let playbin = gst::ElementFactory::make("playbin") .property("uri", uri) .property("video-sink", &sink) .build() .context("GStreamer playbin is missing (gstreamer1.0-plugins-base)")?; // GPU colour conversion and HDR tone mapping, before the subtitle // overlay (which needs system memory) and the sink. if gst::ElementFactory::find("vapostproc").is_some() { match gst::parse::bin_from_description("vapostproc name=pp ! video/x-raw,format=NV12", true) { Ok(bin) => { if let Some(pp) = bin.by_name("pp") { if pp.find_property("hdr-tone-mapping").is_some() { pp.set_property("hdr-tone-mapping", true); } } playbin.set_property("video-filter", &bin); } Err(e) => log::warn!("video: vapostproc: {e}"), } } // Always decoded sound (PCM). When the HDMI sink also offers AC3/E-AC3 // passthrough, pulsesink would take the encoded track as it is: a // 44.1 kHz AC3 track then fails ("Failed to connect stream: No such // entity") and a 48 kHz one goes out as a bitstream that stutters on // the Raspberry Pi. if let Some(sink) = ["pulsesink", "pipewiresink"].into_iter().find(|n| gst::ElementFactory::find(n).is_some()) { match gst::parse::bin_from_description(&format!("audioconvert ! audioresample ! audio/x-raw ! {sink}"), true) { Ok(bin) => playbin.set_property("audio-sink", &bin), Err(e) => log::warn!("video: audio sink: {e}"), } } playbin.set_property("subtitle-font-desc", opts.subtitle_font.as_str()); playbin.set_property("av-offset", opts.audio_offset_ms * 1_000_000); // A few seconds of network buffer: smooth over a torrent that delivers in bursts. playbin.set_property("buffer-duration", 8i64 * 1_000_000_000); if !opts.subtitles { set_flag(&playbin, "text", false); } // FFmpeg decoders: no direct rendering. With it, gst-libav aborts the // whole app (g_error "video meta uses 864x480 instead of 854x480") // when a padded frame meets a renegotiation, e.g. after a seek. playbin.connect("element-setup", false, |args| { if let Some(el) = args.get(1).and_then(|v| v.get::().ok()) { let is_avdec = el.factory().is_some_and(|f| f.name().starts_with("avdec_")); if is_avdec && el.find_property("direct-rendering").is_some() { el.set_property("direct-rendering", false); } } None }); if let Some(ua) = opts.user_agent.clone() { playbin.connect("source-setup", false, move |args| { if let Some(src) = args.get(1).and_then(|v| v.get::().ok()) { if src.find_property("user-agent").is_some() { src.set_property("user-agent", ua.as_str()); } } None }); } let bus = playbin.bus().context("playbin has no bus")?; playbin.set_state(gst::State::Paused).context("opening the stream")?; Ok(Player { playbin, bus, feed, start: opts.start.max(0.0), want_playing: true, buffering: false, ready: false, seeking: false, failed: false, }) } /// The frame source for [`crate::Glass::set_video`]. pub fn video(&self) -> Rc { Rc::new(FeedSource(self.feed.clone())) } /// Handles what GStreamer reported since the last call. Call it often /// (every 50–200 ms) on the UI thread; it also drives buffering and the /// start position. pub fn poll(&mut self) -> Vec { let mut out = Vec::new(); while let Some(msg) = self.bus.pop() { use gst::MessageView; match msg.view() { MessageView::Eos(_) => out.push(Event::Eos), MessageView::Error(e) => { let text = match e.debug() { Some(d) => format!("{} ({d})", e.error()), None => e.error().to_string(), }; log::warn!("video: {text}"); self.failed = true; let _ = self.playbin.set_state(gst::State::Null); out.push(Event::Error(e.error().to_string())); } MessageView::Buffering(b) => { let pct = b.percent(); out.push(Event::Buffering(pct)); if pct < 100 && !self.buffering { self.buffering = true; if self.ready && self.want_playing { let _ = self.playbin.set_state(gst::State::Paused); } } else if pct >= 100 && self.buffering { self.buffering = false; if self.ready && self.want_playing { let _ = self.playbin.set_state(gst::State::Playing); } } } MessageView::AsyncDone(_) => { if !self.ready { if self.start > 0.5 { // First preroll: jump to the start position, then play. let at = gst::ClockTime::from_nseconds((self.start * 1e9) as u64); self.start = 0.0; if self.playbin.seek_simple(gst::SeekFlags::FLUSH | gst::SeekFlags::KEY_UNIT, at).is_ok() { continue; } } self.ready = true; out.push(Event::Ready { duration: self.duration() }); if self.want_playing && !self.buffering { let _ = self.playbin.set_state(gst::State::Playing); } } else if self.seeking { self.seeking = false; out.push(Event::Seeked); } } MessageView::StateChanged(s) => { if s.src().is_some_and(|src| src == &self.playbin) { match s.current() { gst::State::Playing => out.push(Event::Playing(true)), gst::State::Paused if s.old() == gst::State::Playing => out.push(Event::Playing(false)), _ => {} } } } _ => {} } } out } pub fn play(&mut self) { self.want_playing = true; if self.ready && !self.buffering && !self.failed { let _ = self.playbin.set_state(gst::State::Playing); } } pub fn pause(&mut self) { self.want_playing = false; if !self.failed { let _ = self.playbin.set_state(gst::State::Paused); } } /// Play/pause; returns whether it plays now. pub fn toggle(&mut self) -> bool { if self.want_playing { self.pause(); } else { self.play(); } self.want_playing } /// Playing was asked for (it may still wait for the network). pub fn is_playing(&self) -> bool { self.want_playing } pub fn is_ready(&self) -> bool { self.ready } pub fn is_buffering(&self) -> bool { self.buffering || self.seeking || !self.ready } /// Current position in seconds. pub fn position(&self) -> Option { self.playbin.query_position::().map(|t| t.nseconds() as f64 / 1e9) } /// Duration in seconds, when the stream knows it. pub fn duration(&self) -> Option { self.playbin.query_duration::().map(|t| t.nseconds() as f64 / 1e9).filter(|d| *d > 0.0) } /// Jumps to `seconds`. `exact` decodes up to that very frame (slower); /// otherwise it lands on the nearest keyframe before it. pub fn seek(&mut self, seconds: f64, exact: bool) { if !self.ready { self.start = seconds.max(0.0); return; } let flags = gst::SeekFlags::FLUSH | if exact { gst::SeekFlags::ACCURATE } else { gst::SeekFlags::KEY_UNIT }; let at = gst::ClockTime::from_nseconds((seconds.max(0.0) * 1e9) as u64); if self.playbin.seek_simple(flags, at).is_ok() { self.seeking = true; } } pub fn audio_tracks(&self) -> Vec { self.tracks("n-audio", "get-audio-tags", gst::tags::AudioCodec::TAG_NAME) } pub fn text_tracks(&self) -> Vec { self.tracks("n-text", "get-text-tags", gst::tags::SubtitleCodec::TAG_NAME) } pub fn current_audio(&self) -> i32 { self.playbin.property::("current-audio") } /// The subtitle track shown, or `None` when subtitles are off. pub fn current_text(&self) -> Option { get_flag(&self.playbin, "text").then(|| self.playbin.property::("current-text")).filter(|i| *i >= 0) } pub fn set_audio(&self, index: i32) { self.playbin.set_property("current-audio", index); } /// Shows subtitle track `index`, or hides subtitles (`None`). pub fn set_text(&self, index: Option) { match index { Some(i) => { set_flag(&self.playbin, "text", true); self.playbin.set_property("current-text", i); } None => set_flag(&self.playbin, "text", false), } } /// Audio sync correction in milliseconds (positive: audio later). pub fn set_audio_offset_ms(&self, ms: i64) { self.playbin.set_property("av-offset", ms * 1_000_000); } fn tracks(&self, count: &str, signal: &str, codec_tag: &str) -> Vec { let n = self.playbin.property::(count); (0..n) .map(|i| { let tags = self.playbin.emit_by_name::>(signal, &[&i]); let mut t = Track { index: i, ..Track::default() }; if let Some(tags) = tags { t.language = tags.get::().map(|v| v.get().to_string()); t.title = tags.get::().map(|v| v.get().to_string()); t.codec = tags .generic(codec_tag) .and_then(|v| v.get::().ok()) .or_else(|| tags.get::().map(|v| v.get().to_string())); } t }) .collect() } } impl Drop for Player { fn drop(&mut self) { let _ = self.playbin.set_state(gst::State::Null); } } fn get_flag(playbin: &gst::Element, nick: &str) -> bool { let value = playbin.property_value("flags"); let Some(class) = glib::FlagsClass::with_type(value.type_()) else { return false }; class.value_by_nick(nick).is_some_and(|f| class.is_set(&value, f.value())) } fn set_flag(playbin: &gst::Element, nick: &str, on: bool) { let value = playbin.property_value("flags"); let Some(class) = glib::FlagsClass::with_type(value.type_()) else { return }; let Some(builder) = class.builder_with_value(value) else { return }; let builder = if on { builder.set_by_nick(nick) } else { builder.unset_by_nick(nick) }; if let Some(v) = builder.build() { playbin.set_property_from_value("flags", &v); } }