use std::cell::Cell;
use std::path::Path;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use gstreamer::prelude::*;
use gstreamer_app::AppSink;
use tracing::{debug, info, trace, warn};
use gtk::glib as gtkglib;
struct PreviewSample {
bytes: Vec<u8>,
width: i32,
height: i32,
stride: usize,
}
pub struct Preview {
pub root: gtk::Picture,
pipeline: gstreamer::Pipeline,
polling_source: Option<gtkglib::SourceId>,
retry_source: Option<gtkglib::SourceId>,
bus_watch: Option<gstreamer::bus::BusWatchGuard>,
}
impl Drop for Preview {
fn drop(&mut self) {
if let Some(id) = self.polling_source.take() {
id.remove();
}
if let Some(id) = self.retry_source.take() {
id.remove();
}
drop(self.bus_watch.take());
if let Err(e) = self.pipeline.set_state(gstreamer::State::Null) {
warn!(error = %e, "preview pipeline failed to stop cleanly");
}
}
}
const PREVIEW_WIDTH: i32 = 640;
const PREVIEW_HEIGHT: i32 = 360;
const POLL_INTERVAL: Duration = Duration::from_millis(40);
const RETRY_INTERVAL: Duration = Duration::from_secs(5);
#[must_use]
pub fn build(device_path: &Path) -> Preview {
let picture = gtk::Picture::builder()
.content_fit(gtk::ContentFit::Contain)
.can_shrink(true)
.vexpand(true)
.hexpand(true)
.build();
let mailbox: Arc<Mutex<Option<PreviewSample>>> = Arc::new(Mutex::new(None));
let Some(pipeline) = build_pipeline(device_path, Arc::clone(&mailbox)) else {
return Preview {
root: picture,
pipeline: gstreamer::Pipeline::new(),
polling_source: None,
retry_source: None,
bus_watch: None,
};
};
match pipeline.set_state(gstreamer::State::Playing) {
Ok(_) => info!(device = %device_path.display(), "preview pipeline started"),
Err(e) => {
warn!(
device = %device_path.display(),
error = %e,
"preview pipeline failed to enter Playing"
);
}
}
let bus_watch = install_bus_watch(&pipeline);
let polling_source = install_polling_timer(&picture, Arc::clone(&mailbox));
let retry_source = install_retry_timer(&pipeline);
Preview {
root: picture,
pipeline,
polling_source: Some(polling_source),
retry_source: Some(retry_source),
bus_watch,
}
}
fn build_pipeline(
device_path: &Path,
mailbox: Arc<Mutex<Option<PreviewSample>>>,
) -> Option<gstreamer::Pipeline> {
let pipeline = gstreamer::Pipeline::new();
let src = match gstreamer::ElementFactory::make("v4l2src")
.property("device", device_path.display().to_string())
.build()
{
Ok(e) => e,
Err(err) => {
warn!(error = %err, "preview: v4l2src factory missing; preview will be inert");
return None;
}
};
let convert = match gstreamer::ElementFactory::make("videoconvert").build() {
Ok(e) => e,
Err(err) => {
warn!(error = %err, "preview: videoconvert factory missing; preview will be inert");
return None;
}
};
let scale = match gstreamer::ElementFactory::make("videoscale").build() {
Ok(e) => e,
Err(err) => {
warn!(error = %err, "preview: videoscale factory missing; preview will be inert");
return None;
}
};
let caps = gstreamer::Caps::builder("video/x-raw")
.field("format", "RGBA")
.field("width", PREVIEW_WIDTH)
.field("height", PREVIEW_HEIGHT)
.build();
let filter = match gstreamer::ElementFactory::make("capsfilter")
.property("caps", &caps)
.build()
{
Ok(e) => e,
Err(err) => {
warn!(error = %err, "preview: capsfilter factory missing; preview will be inert");
return None;
}
};
let appsink_elem = match gstreamer::ElementFactory::make("appsink")
.name("preview-sink")
.property("sync", false)
.property("max-buffers", 1u32)
.property("drop", true)
.property("emit-signals", false)
.build()
{
Ok(e) => e,
Err(err) => {
warn!(error = %err, "preview: appsink factory missing; preview will be inert");
return None;
}
};
let elements = [&src, &convert, &scale, &filter, &appsink_elem];
if let Err(e) = pipeline.add_many(elements) {
warn!(error = %e, "preview pipeline add_many failed");
return None;
}
if let Err(e) = gstreamer::Element::link_many(elements) {
warn!(error = %e, "preview pipeline link_many failed");
return None;
}
let Ok(appsink): Result<AppSink, _> = appsink_elem.downcast() else {
warn!("preview: appsink element failed to downcast to AppSink; preview will be inert");
return None;
};
attach_appsink_callback(&appsink, mailbox);
Some(pipeline)
}
fn extract_sample(sample: &gstreamer::Sample) -> Option<PreviewSample> {
let Some(buffer) = sample.buffer() else {
trace!(reason = "no buffer", "preview: sample dropped");
return None;
};
let Some(caps) = sample.caps() else {
trace!(reason = "no caps", "preview: sample dropped");
return None;
};
let Ok(info) = gstreamer_video::VideoInfo::from_caps(caps) else {
trace!(
reason = "VideoInfo::from_caps failed",
"preview: sample dropped"
);
return None;
};
let Ok(map) = buffer.map_readable() else {
trace!(reason = "map_readable failed", "preview: sample dropped");
return None;
};
let Ok(width) = i32::try_from(info.width()) else {
trace!("preview: width overflows i32; dropping sample");
return None;
};
let Ok(height) = i32::try_from(info.height()) else {
trace!("preview: height overflows i32; dropping sample");
return None;
};
let raw_stride = info.stride()[0];
let Ok(stride) = usize::try_from(raw_stride) else {
trace!(
stride = raw_stride,
"preview: negative stride; dropping sample"
);
return None;
};
Some(PreviewSample {
bytes: map.as_slice().to_vec(),
width,
height,
stride,
})
}
fn attach_appsink_callback(appsink: &AppSink, mailbox: Arc<Mutex<Option<PreviewSample>>>) {
appsink.set_callbacks(
gstreamer_app::AppSinkCallbacks::builder()
.new_sample(move |sink| {
let sample = match sink.pull_sample() {
Ok(s) => s,
Err(e) => {
trace!(error = %e, "preview appsink pull_sample failed");
return Err(gstreamer::FlowError::Error);
}
};
let Some(sample) = extract_sample(&sample) else {
return Ok(gstreamer::FlowSuccess::Ok);
};
if let Ok(mut slot) = mailbox.lock() {
*slot = Some(sample);
}
Ok(gstreamer::FlowSuccess::Ok)
})
.build(),
);
}
fn install_polling_timer(
picture: >k::Picture,
mailbox: Arc<Mutex<Option<PreviewSample>>>,
) -> gtkglib::SourceId {
let picture = picture.clone();
gtkglib::source::timeout_add_local(POLL_INTERVAL, move || {
let sample = mailbox.lock().ok().and_then(|mut slot| slot.take());
if let Some(sample) = sample {
let bytes = gtkglib::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));
}
gtkglib::ControlFlow::Continue
})
}
fn install_bus_watch(pipeline: &gstreamer::Pipeline) -> Option<gstreamer::bus::BusWatchGuard> {
let bus = pipeline.bus()?;
match bus.add_watch_local(|_, msg| {
match msg.view() {
gstreamer::MessageView::Error(err) => {
warn!(
error = %err.error(),
debug = ?err.debug(),
"preview pipeline bus error (retry timer will recover)"
);
}
gstreamer::MessageView::Eos(_) => {
info!("preview pipeline EOS (retry timer will recover)");
}
_ => {}
}
glib::ControlFlow::Continue
}) {
Ok(guard) => Some(guard),
Err(e) => {
warn!(error = %e, "preview: bus watch install failed");
None
}
}
}
fn install_retry_timer(pipeline: &gstreamer::Pipeline) -> gtkglib::SourceId {
let pipeline = pipeline.clone();
let attempts: Rc<Cell<u32>> = Rc::new(Cell::new(0));
gtkglib::source::timeout_add_local(RETRY_INTERVAL, move || {
let current = pipeline.current_state();
let pending = pipeline.pending_state();
if current == gstreamer::State::Playing {
let prev_attempts = attempts.replace(0);
if prev_attempts > 0 {
info!(state = ?current, "preview pipeline recovered to Playing");
}
return gtkglib::ControlFlow::Continue;
}
if pending == gstreamer::State::Playing {
debug!(
current = ?current,
pending = ?pending,
"preview pipeline transitioning toward Playing — skip retry"
);
return gtkglib::ControlFlow::Continue;
}
let n = attempts.get();
let should_log = n == 0 || (n > 0 && n.is_power_of_two());
if should_log {
warn!(
state = ?current,
attempts = n,
"preview pipeline below Playing — retrying on worker"
);
} else {
debug!(state = ?current, attempts = n, "preview pipeline retry tick");
}
attempts.set(n.saturating_add(1));
let pipeline_for_worker = pipeline.clone();
std::thread::spawn(move || {
if let Err(e) = pipeline_for_worker.set_state(gstreamer::State::Null) {
warn!(error = %e, "preview pipeline reset to Null failed");
}
if let Err(e) = pipeline_for_worker.set_state(gstreamer::State::Playing) {
warn!(error = %e, "preview pipeline retry to Playing failed");
}
});
gtkglib::ControlFlow::Continue
})
}