mod pipeline;
use std::cell::{Cell, RefCell};
use std::path::PathBuf;
use std::rc::{Rc, Weak};
use std::sync::Arc;
use std::sync::atomic::Ordering;
use std::time::Duration;
use fluxframe_core::OutputInfo;
use gstreamer::prelude::{ElementExt, ElementExtManual};
use gtk::glib;
use gtk::prelude::*;
use tracing::{debug, info, warn};
use pipeline::{Mailbox, RestartFlags};
const PLACEHOLDER_CHILD: &str = "placeholder";
const PICTURE_CHILD: &str = "picture";
const POLL_INTERVAL: Duration = Duration::from_millis(40);
const RETRY_INTERVAL: Duration = Duration::from_secs(5);
pub struct Preview {
pub root: gtk::Stack,
live: Option<Rc<Live>>,
root_handlers: Vec<glib::SignalHandlerId>,
}
struct Live {
stack: gtk::Stack,
picture: gtk::Picture,
pipeline: gstreamer::Pipeline,
flags: Arc<RestartFlags>,
mailbox: Mailbox,
running: RefCell<Option<Running>>,
window: RefCell<Option<(glib::WeakRef<gtk::Window>, glib::SignalHandlerId)>>,
}
struct Running {
polling_source: glib::SourceId,
retry_source: glib::SourceId,
bus_watch: Option<gstreamer::bus::BusWatchGuard>,
}
impl Running {
fn remove(self) {
self.polling_source.remove();
self.retry_source.remove();
drop(self.bus_watch);
}
}
impl Drop for Preview {
fn drop(&mut self) {
let Some(live) = self.live.take() else {
return;
};
for id in self.root_handlers.drain(..) {
self.root.disconnect(id);
}
if let Some((window, id)) = live.window.borrow_mut().take() {
if let Some(window) = window.upgrade() {
window.disconnect(id);
}
}
if let Some(running) = live.running.borrow_mut().take() {
running.remove();
}
live.flags.active.store(false, Ordering::SeqCst);
live.flags.shutting_down.store(true, Ordering::SeqCst);
if let Err(e) = live.pipeline.set_state(gstreamer::State::Null) {
warn!(error = %e, "preview pipeline failed to stop cleanly");
}
}
}
pub const LEGACY_DEVICE: &str = "/dev/video10";
pub const WAITING_FOR_DAEMON: &str = "Waiting for the daemon to report its output.";
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PreviewTarget {
Device(PathBuf),
Unavailable(&'static str),
}
#[must_use]
pub fn target_for(output: Option<&OutputInfo>) -> PreviewTarget {
match output {
None => PreviewTarget::Device(PathBuf::from(LEGACY_DEVICE)),
Some(OutputInfo::V4l2 { device }) => PreviewTarget::Device(device.clone()),
Some(OutputInfo::Pipewire { .. }) => PreviewTarget::Unavailable(
"The daemon publishes to PipeWire; the preview can only read a v4l2loopback device.",
),
Some(OutputInfo::Auto) => {
PreviewTarget::Unavailable("The daemon shows its output in its own window.")
}
Some(OutputInfo::Fakesink) => {
PreviewTarget::Unavailable("The daemon discards its output (fakesink).")
}
Some(_) => {
PreviewTarget::Unavailable("The preview cannot read this kind of daemon output.")
}
}
}
#[must_use]
pub fn build(target: &PreviewTarget, gst_ready: bool) -> Preview {
let picture = gtk::Picture::builder()
.content_fit(gtk::ContentFit::Contain)
.can_shrink(true)
.vexpand(true)
.hexpand(true)
.build();
picture.set_alternative_text(Some("Live output preview"));
let placeholder = adw::StatusPage::builder()
.icon_name("camera-disabled-symbolic")
.title("No Preview Signal")
.vexpand(true)
.hexpand(true)
.build();
let stack = gtk::Stack::builder().vexpand(true).hexpand(true).build();
stack.add_named(&placeholder, Some(PLACEHOLDER_CHILD));
stack.add_named(&picture, Some(PICTURE_CHILD));
stack.set_visible_child_name(PLACEHOLDER_CHILD);
let inert = |description: &str| {
placeholder.set_description(Some(description));
Preview {
root: stack.clone(),
live: None,
root_handlers: Vec::new(),
}
};
if !gst_ready {
return inert("Preview is unavailable: GStreamer failed to initialise.");
}
let device_path = match target {
PreviewTarget::Device(path) => path.as_path(),
PreviewTarget::Unavailable(reason) => return inert(reason),
};
placeholder.set_description(Some(&format!(
"Waiting for frames from {}.",
device_path.display()
)));
let mailbox: Mailbox = Mailbox::default();
let Some(pipeline) = pipeline::build_pipeline(device_path, Arc::clone(&mailbox)) else {
return inert("Preview is unavailable: required GStreamer elements are missing.");
};
info!(device = %device_path.display(), "preview pipeline built");
let live = Rc::new(Live {
stack: stack.clone(),
picture,
pipeline,
flags: Arc::new(RestartFlags::default()),
mailbox,
running: RefCell::new(None),
window: RefCell::new(None),
});
let weak = Rc::downgrade(&live);
let map_handler = stack.connect_map(move |_| {
if let Some(live) = weak.upgrade() {
Live::follow_window(&live);
let suspended = live.window_suspended();
live.set_active(should_be_active(true, suspended));
}
});
let weak = Rc::downgrade(&live);
let unmap_handler = stack.connect_unmap(move |_| {
if let Some(live) = weak.upgrade() {
live.set_active(should_be_active(false, live.window_suspended()));
}
});
Preview {
root: stack,
live: Some(live),
root_handlers: vec![map_handler, unmap_handler],
}
}
fn should_be_active(mapped: bool, window_suspended: bool) -> bool {
mapped && !window_suspended
}
impl Live {
fn follow_window(this: &Rc<Self>) {
let Some(window) = this
.stack
.root()
.and_then(|root| root.downcast::<gtk::Window>().ok())
else {
return;
};
let mut slot = this.window.borrow_mut();
if let Some((current, _)) = slot.as_ref() {
if current.upgrade().as_ref() == Some(&window) {
return;
}
}
if let Some((old, id)) = slot.take() {
if let Some(old) = old.upgrade() {
old.disconnect(id);
}
}
let weak: Weak<Self> = Rc::downgrade(this);
let id = window.connect_suspended_notify(move |window| {
if let Some(live) = weak.upgrade() {
live.set_active(should_be_active(
live.stack.is_mapped(),
window.is_suspended(),
));
}
});
*slot = Some((window.downgrade(), id));
}
fn window_suspended(&self) -> bool {
self.window
.borrow()
.as_ref()
.and_then(|(window, _)| window.upgrade())
.is_some_and(|window| window.is_suspended())
}
fn set_active(&self, active: bool) {
let mut running = self.running.borrow_mut();
match (active, running.is_some()) {
(true, false) => {
debug!("preview activated");
self.flags.needs_restart.store(false, Ordering::SeqCst);
self.flags.active.store(true, Ordering::SeqCst);
pipeline::spawn_restart_worker(&self.pipeline, &self.flags);
*running = Some(Running {
polling_source: install_polling_timer(
&self.stack,
&self.picture,
Arc::clone(&self.mailbox),
Arc::clone(&self.flags),
),
retry_source: install_retry_timer(&self.pipeline, Arc::clone(&self.flags)),
bus_watch: pipeline::install_bus_watch(&self.pipeline, Arc::clone(&self.flags)),
});
}
(false, true) => {
debug!("preview deactivated");
if let Some(r) = running.take() {
r.remove();
}
self.flags.active.store(false, Ordering::SeqCst);
pipeline::spawn_restart_worker(&self.pipeline, &self.flags);
if let Ok(mut slot) = self.mailbox.lock() {
slot.take();
}
self.stack.set_visible_child_name(PLACEHOLDER_CHILD);
}
_ => {}
}
}
}
fn install_polling_timer(
stack: >k::Stack,
picture: >k::Picture,
mailbox: Mailbox,
flags: Arc<RestartFlags>,
) -> glib::SourceId {
let stack = stack.clone();
let picture = picture.clone();
glib::source::timeout_add_local(POLL_INTERVAL, move || {
if flags.needs_restart.load(Ordering::SeqCst) {
if let Ok(mut slot) = mailbox.lock() {
slot.take();
}
if stack.visible_child_name().as_deref() != Some(PLACEHOLDER_CHILD) {
stack.set_visible_child_name(PLACEHOLDER_CHILD);
}
return glib::ControlFlow::Continue;
}
let sample = mailbox.lock().ok().and_then(|mut slot| slot.take());
if let Some(sample) = sample {
let bytes = glib::Bytes::from_owned(sample.bytes);
let texture = gtk::gdk::MemoryTexture::new(
sample.width,
sample.height,
gtk::gdk::MemoryFormat::R8g8b8a8,
&bytes,
sample.stride,
);
picture.set_paintable(Some(&texture));
if stack.visible_child_name().as_deref() != Some(PICTURE_CHILD) {
stack.set_visible_child_name(PICTURE_CHILD);
}
}
glib::ControlFlow::Continue
})
}
fn install_retry_timer(pipeline: &gstreamer::Pipeline, flags: Arc<RestartFlags>) -> glib::SourceId {
let pipeline = pipeline.clone();
let attempts: Rc<Cell<u32>> = Rc::new(Cell::new(0));
glib::source::timeout_add_local(RETRY_INTERVAL, move || {
let current = pipeline.current_state();
let pending = pipeline.pending_state();
let needs_restart = flags.needs_restart.load(Ordering::SeqCst);
let in_flight = flags.restart_in_flight.load(Ordering::SeqCst);
if !pipeline::should_restart(current, pending, needs_restart, in_flight) {
if current == gstreamer::State::Playing && !in_flight {
let prev_attempts = attempts.replace(0);
if prev_attempts > 0 {
info!(state = ?current, "preview pipeline recovered to Playing");
}
} else {
debug!(
current = ?current,
pending = ?pending,
in_flight,
"preview pipeline restart pending — skip retry"
);
}
return glib::ControlFlow::Continue;
}
let n = attempts.get();
let should_log = n == 0 || (n > 0 && n.is_power_of_two());
if should_log {
warn!(
state = ?current,
needs_restart,
attempts = n,
"preview pipeline not streaming — restarting on worker"
);
} else {
debug!(state = ?current, attempts = n, "preview pipeline retry tick");
}
attempts.set(n.saturating_add(1));
if pipeline::spawn_restart_worker(&pipeline, &flags) {
flags.needs_restart.store(false, Ordering::SeqCst);
}
glib::ControlFlow::Continue
})
}
#[cfg(test)]
mod tests {
use super::{LEGACY_DEVICE, OutputInfo, PathBuf, PreviewTarget, should_be_active, target_for};
#[test]
fn preview_reads_the_device_the_daemon_reports() {
let output = OutputInfo::V4l2 {
device: PathBuf::from("/dev/video11"),
};
assert_eq!(
target_for(Some(&output)),
PreviewTarget::Device(PathBuf::from("/dev/video11"))
);
}
#[test]
fn preview_assumes_the_legacy_device_for_an_older_daemon() {
assert_eq!(
target_for(None),
PreviewTarget::Device(PathBuf::from(LEGACY_DEVICE))
);
}
#[test]
fn preview_is_unavailable_for_outputs_without_a_device() {
for output in [
OutputInfo::Pipewire { node: None },
OutputInfo::Auto,
OutputInfo::Fakesink,
] {
assert!(
matches!(target_for(Some(&output)), PreviewTarget::Unavailable(_)),
"{output:?} has no device to read"
);
}
}
#[test]
fn active_only_when_mapped_and_not_suspended() {
assert!(should_be_active(true, false));
assert!(!should_be_active(true, true));
assert!(!should_be_active(false, false));
assert!(!should_be_active(false, true));
}
}