From 3e4cac87ea1f755c95213d054f22f1c7a1ac2e1c Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Tue, 6 Oct 2026 14:16:21 -0700 Subject: [PATCH 01/15] refactor(stinger): plan a take from a start reported at runtime A clip take knows where its first frame lands before it starts: the Media Player pins it. A source that starts on a trigger only says when it started afterwards, so its take is programmed late, with the graphic pad already up. - `PipelineManager::raise_stinger_fill` stages the pads as a take does and raises the graphic pad. `program_stinger` with `StingerTake::fill_raised` skips the staging and keeps the pad up until the take's end. - `stinger_take_claimed` builds its take with `take_on_grid` and hands it to `announce_stinger_take`, which reports and finishes any take. The re-park after a take is skipped when there is no clip to park. The clip path does the same thing in the same order as before. Co-Authored-By: Claude Opus 5.5 --- backend/src/gst/pipeline/effects/stinger.rs | 189 +++++++++++++++----- backend/src/state/stinger.rs | 186 ++++++++++++++----- 2 files changed, 281 insertions(+), 94 deletions(-) diff --git a/backend/src/gst/pipeline/effects/stinger.rs b/backend/src/gst/pipeline/effects/stinger.rs index fc9e4880f..fba0d7355 100644 --- a/backend/src/gst/pipeline/effects/stinger.rs +++ b/backend/src/gst/pipeline/effects/stinger.rs @@ -60,6 +60,10 @@ pub struct StingerTake { /// Spacing of the clip's frames, so the take knows which one is due at /// the cut point. pub clip_frame_ns: u64, + /// The graphic pad was raised ahead of the take + /// ([`PipelineManager::raise_stinger_fill`]), because the take's start + /// is only known once its source has started. It stays up until `end`. + pub fill_raised: bool, } /// Flows whose stinger programming fails once all its pad changes are made. @@ -88,6 +92,27 @@ pub struct StingerProgramError { pub ftb_cancelled: bool, } +impl StingerProgramError { + /// A failure before the take changed anything. + fn unchanged(error: PipelineError) -> Self { + Self { + error, + ftb_cancelled: false, + } + } +} + +/// The mixer, pads and state one take programs. +struct StingerTarget<'a> { + mixer: &'a gst::Element, + pads: StingerPads, + /// The outgoing source's pad. + a: gst::Pad, + /// The incoming source's pad. + b: gst::Pad, + state: Arc, +} + /// The stinger pads of one mixer. pub struct StingerPads { pub fill: gst::Pad, @@ -287,40 +312,29 @@ impl PipelineManager { .map(|t| t.nseconds()) } - /// Program a whole stinger take, and start counting the clip's frames. - /// Also returns whether it cancelled a fade-to-black, as any take does. - /// - /// A failure once it has started changing pads aborts the take (the old - /// source alone on air, the stinger pads down) before it returns; the - /// error then says whether a fade-to-black was cancelled on the way. - pub fn program_stinger( + /// What a take changes on the mixer, checked before it changes any of it. + fn stinger_target( &self, block_instance_id: &str, take: &StingerTake, - ) -> Result<(StingerWatch, bool), StingerProgramError> { - let unchanged = |error| StingerProgramError { - error, - ftb_cancelled: false, - }; - let mixer = self.dist_mixer(block_instance_id).map_err(unchanged)?; - let pads = self - .stinger_pads(block_instance_id) - .ok_or_else(|| PipelineError::InvalidProperty { - element: block_instance_id.to_string(), - property: strom_types::stinger::ENABLE_STINGER_PROPERTY.to_string(), - reason: "this vision mixer has no stinger input".to_string(), - }) - .map_err(unchanged)?; + ) -> Result, PipelineError> { + let mixer = self.dist_mixer(block_instance_id)?; + let pads = + self.stinger_pads(block_instance_id) + .ok_or_else(|| PipelineError::InvalidProperty { + element: block_instance_id.to_string(), + property: strom_types::stinger::ENABLE_STINGER_PROPERTY.to_string(), + reason: "this vision mixer has no stinger input".to_string(), + })?; if take.plan.variant.uses_matte() && pads.matte.is_none() { - return Err(unchanged(PipelineError::TransitionError( + return Err(PipelineError::TransitionError( "a matte stinger needs the GPU mixer".to_string(), - ))); + )); } - let state = overlay::get_overlay_state(&self.flow_id, block_instance_id) - .ok_or_else(|| { + let state = + overlay::get_overlay_state(&self.flow_id, block_instance_id).ok_or_else(|| { PipelineError::ElementNotFound(format!("overlay state of {}", block_instance_id)) - }) - .map_err(unchanged)?; + })?; let pad = |idx: usize| { mixer .static_pad(&format!("sink_{}", idx)) @@ -329,16 +343,80 @@ impl PipelineManager { pad: format!("sink_{}", idx), }) }; - let a = pad(take.from_input).map_err(unchanged)?; - let b = pad(take.to_input).map_err(unchanged)?; + Ok(StingerTarget { + mixer, + a: pad(take.from_input)?, + b: pad(take.to_input)?, + pads, + state, + }) + } - // Start from the resting state of a classic take: A alone on air, - // the stinger pads down, no shader take left running. That also - // ends a fade-to-black. - let ftb_cancelled = state + /// Stage a take and raise its graphic pad before its start is known. For + /// a source that starts on a trigger and only then says when it started; + /// `program_stinger` with `fill_raised` programs the rest from that. The + /// source must be transparent until it starts. Returns whether this + /// cancelled a fade-to-black. + /// + /// A failure part way through aborts the take, as `program_stinger` does. + pub fn raise_stinger_fill( + &self, + block_instance_id: &str, + take: &StingerTake, + ) -> Result { + let t = self + .stinger_target(block_instance_id, take) + .map_err(StingerProgramError::unchanged)?; + let ftb_cancelled = t + .state .ftb_active .swap(false, std::sync::atomic::Ordering::Relaxed); - match self.program_stinger_pads(block_instance_id, take, mixer, &pads, &a, &b, &state) { + match self.stage_stinger_pads(block_instance_id, take, &t) { + Ok(()) => { + crate::gst::control_bindings::wipe_control_bindings( + t.pads.fill.upcast_ref(), + &["alpha"], + ); + t.pads.fill.set_property("alpha", 1.0f64); + Ok(ftb_cancelled) + } + Err(error) => { + self.abort_stinger(block_instance_id, take); + Err(StingerProgramError { + error, + ftb_cancelled, + }) + } + } + } + + /// Program a whole stinger take, and start counting the clip's frames. + /// Also returns whether it cancelled a fade-to-black, as any take does. + /// + /// A failure once it has started changing pads aborts the take (the old + /// source alone on air, the stinger pads down) before it returns; the + /// error then says whether a fade-to-black was cancelled on the way. + pub fn program_stinger( + &self, + block_instance_id: &str, + take: &StingerTake, + ) -> Result<(StingerWatch, bool), StingerProgramError> { + let t = self + .stinger_target(block_instance_id, take) + .map_err(StingerProgramError::unchanged)?; + // A raised graphic pad was staged by `raise_stinger_fill`, which also + // ended any fade-to-black, and the source may already be on it: + // staging again would drop it. + let ftb_cancelled = !take.fill_raised + && t.state + .ftb_active + .swap(false, std::sync::atomic::Ordering::Relaxed); + let staged = if take.fill_raised { + Ok(()) + } else { + self.stage_stinger_pads(block_instance_id, take, &t) + }; + match staged.and_then(|()| self.program_stinger_pads(block_instance_id, take, &t)) { Ok(watch) => Ok((watch, ftb_cancelled)), Err(error) => { self.abort_stinger(block_instance_id, take); @@ -350,27 +428,29 @@ impl PipelineManager { } } - /// The pad changes of [`Self::program_stinger`], from the resting state - /// on. Any of them may have run when this fails. - #[allow(clippy::too_many_arguments)] - fn program_stinger_pads( + /// Put the mixer in a take's resting state, A alone on air and the + /// stinger pads down, and set the graphic pad up for the take's clip. + /// Any of it may have run when this fails. + fn stage_stinger_pads( &self, block_instance_id: &str, take: &StingerTake, - mixer: &gst::Element, - pads: &StingerPads, - a: &gst::Pad, - b: &gst::Pad, - state: &overlay::VisionMixerOverlayState, - ) -> Result { - let variant = take.plan.variant; + t: &StingerTarget<'_>, + ) -> Result<(), PipelineError> { + let StingerTarget { + mixer, + pads, + b, + state, + .. + } = t; let gpu = pads.matte.is_some(); self.reset_take_fx(block_instance_id); let (cw, ch) = self.dist_canvas_size(block_instance_id); self.reset_classic_take_pads( block_instance_id, mixer, - Some(state), + Some(state.as_ref()), Some(take.from_input), state.num_inputs, cw, @@ -427,6 +507,21 @@ impl PipelineManager { } } pads.fill.set_property("zorder", DIST_STINGER_FILL_ZORDER); + Ok(()) + } + + /// The keyframes of [`Self::program_stinger`], from a staged take on. + /// Any of them may have run when this fails. + fn program_stinger_pads( + &self, + block_instance_id: &str, + take: &StingerTake, + t: &StingerTarget<'_>, + ) -> Result { + let StingerTarget { + mixer, pads, a, b, .. + } = t; + let variant = take.plan.variant; // A step key sits half a frame before the output frame it acts on. // The mixer stamps its frames from a rounded origin, so a frame's // timestamp can be a nanosecond either side of the grid's: a key @@ -437,6 +532,8 @@ impl PipelineManager { let has_graphic = take.plan.layout != StingerLayout::MaskOnly; let fill_keys: &[(u64, f64)] = if !has_graphic { &[(0, 0.0)] + } else if take.fill_raised { + &[(0, 1.0), (step(take.end), 0.0)] } else { &[(0, 0.0), (step(take.start), 1.0), (step(take.end), 0.0)] }; diff --git a/backend/src/state/stinger.rs b/backend/src/state/stinger.rs index 37908efcc..b776e0780 100644 --- a/backend/src/state/stinger.rs +++ b/backend/src/state/stinger.rs @@ -26,7 +26,7 @@ use crate::blocks::builtin::mediaplayer::{ }; use crate::gst::pipeline::effects::stinger::{StingerTake, StingerWatch}; use crate::gst::pipeline::PipelineError; -use crate::stinger::{analysis, examples, plan_clip}; +use crate::stinger::{analysis, examples, plan_clip, ClipPlan, FrameGrid}; /// How long after the clip's end a take waits for the mixer to get past it /// before giving up on a stalled mixer. @@ -259,6 +259,53 @@ impl Context { } } +/// A take programmed into the mixer, for [`AppState::announce_stinger_take`]. +struct Started { + token: u64, + index: usize, + file: String, + plan: ClipPlan, + take: StingerTake, + watch: StingerWatch, + ftb_cancelled: bool, + take_to_air_ms: f64, + cue_ms: Option, + frames_expected: u32, + /// The clip's player, to park the clip again afterwards. + player: Option>, +} + +/// A take on the mixer's frame grid whose source's first frame lands on the +/// first output frame at or after `earliest` and lasts `length_ns`, one +/// source frame every `clip_frame_ns`. +#[allow(clippy::too_many_arguments)] +fn take_on_grid( + grid: &FrameGrid, + earliest: u64, + length_ns: u64, + plan: &ClipPlan, + from: usize, + to: usize, + clip_size: Option<(u32, u32)>, + clip_frame_ns: u64, + fill_raised: bool, +) -> StingerTake { + let times = crate::stinger::take_times(grid, earliest, length_ns, plan); + StingerTake { + frame_ns: grid.frame_ns(), + from_input: from, + to_input: to, + start: times.start, + end: times.end, + cut_at: times.cut_at, + mix_ns: times.mix_ns, + plan: plan.clone(), + clip_size, + clip_frame_ns, + fill_raised, + } +} + impl AppState { /// Find the mixer's stinger source and settings. Errors say what is /// missing in terms an operator can fix. @@ -989,7 +1036,6 @@ impl AppState { false, ) })?; - let frame_ns = grid.frame_ns(); let now = manager .running_time_ns() .ok_or_else(|| ("the flow has no running time".to_string(), false))?; @@ -1002,24 +1048,20 @@ impl AppState { / i.framerate_num as u64 }) .unwrap_or(plan.duration_ms * 1_000_000); - let times = - crate::stinger::take_times(&grid, now + ctx.preroll_ms * 1_000_000, clip_ns, &plan); - let take = StingerTake { - frame_ns, - from_input: from, - to_input: to, - start: times.start, - end: times.end, - cut_at: times.cut_at, - mix_ns: times.mix_ns, - plan: plan.clone(), - clip_size: info.as_ref().map(|i| (i.width, i.height)), - clip_frame_ns: info - .as_ref() + let take = take_on_grid( + &grid, + now + ctx.preroll_ms * 1_000_000, + clip_ns, + &plan, + from, + to, + info.as_ref().map(|i| (i.width, i.height)), + info.as_ref() .filter(|i| i.framerate_num > 0) .map(|i| 1_000_000_000 * i.framerate_den as u64 / i.framerate_num as u64) - .unwrap_or(frame_ns), - }; + .unwrap_or(grid.frame_ns()), + false, + ); // A failure part way through has already put the old source // back alone on air; a fade-to-black it ended stays ended. let (watch, ftb_cancelled) = match manager.program_stinger(block, &take) { @@ -1063,6 +1105,53 @@ impl AppState { let take_to_air_ms = (now_at - requested).as_secs_f64() * 1000.0 + (take.start - now) as f64 / 1e6; + let frames_expected = info + .as_ref() + .map(|i| i.frames) + .unwrap_or_else(|| (plan.duration_ms * 30 / 1000) as u32); + Ok(self + .announce_stinger_take( + flow_id, + block, + Started { + token, + index, + file: file.to_string(), + plan, + take, + watch, + ftb_cancelled, + take_to_air_ms, + cue_ms, + frames_expected, + player: Some(Arc::clone(&ctx.player)), + }, + ) + .await) + } + + /// Tell everyone a programmed take is on its way to air, and hand it to + /// a task that finishes it once its source has played out. + async fn announce_stinger_take( + &self, + flow_id: &FlowId, + block: &str, + started: Started, + ) -> StingerTakeResponse { + let Started { + token, + index, + file, + plan, + take, + watch, + ftb_cancelled, + take_to_air_ms, + cue_ms, + frames_expected, + player, + } = started; + let (from, to) = (take.from_input, take.to_input); self.after_vision_mixer_take( flow_id, block, @@ -1080,7 +1169,7 @@ impl AppState { block_id: block.to_string(), take_id: token, index, - file: file.to_string(), + file: file.clone(), variant: plan.variant, downgraded_from: plan.downgraded_from, from_input: from, @@ -1089,14 +1178,10 @@ impl AppState { duration_ms: plan.duration_ms, }); - let frames_expected = info - .as_ref() - .map(|i| i.frames) - .unwrap_or_else(|| (plan.duration_ms * 30 / 1000) as u32); let report = StingerTakeReport { take_id: token, index, - file: file.to_string(), + file: file.clone(), variant: plan.variant, downgraded_from: plan.downgraded_from, from_input: from, @@ -1114,22 +1199,21 @@ impl AppState { let state = self.clone(); let flow = *flow_id; let mixer = block.to_string(); - let player = Arc::clone(&ctx.player); tokio::spawn(async move { state .finish_stinger_take(flow, mixer, token, take, watch, report, player) .await; }); - Ok(StingerTakeResponse { + StingerTakeResponse { take_id: token, index, - file: file.to_string(), + file, variant: plan.variant, downgraded_from: plan.downgraded_from, take_to_air_ms, duration_ms: plan.duration_ms, - }) + } } /// Wait for the mixer to get past the clip, settle the pads, report what @@ -1143,7 +1227,7 @@ impl AppState { take: StingerTake, watch: StingerWatch, mut report: StingerTakeReport, - player: Arc, + player: Option>, ) { // Two output frames past the end, so the last keyframes have run. let target = take.end + 2 * take.frame_ns; @@ -1215,18 +1299,22 @@ impl AppState { // Park the clip again, so the next take is instant. let index = report.index; - let cue_player = Arc::clone(&player); - let cued = tokio::task::spawn_blocking(move || cue_player.cue(index)).await; - let (ready, cue_ms) = match cued { - Ok(Ok(took)) => (true, took.as_millis() as u64), - Ok(Err(e)) => { - warn!( - "Stinger on {}: could not park clip {} again: {}", - mixer, index, e - ); - (false, 0) + let parked = match player { + Some(player) => { + let cued = tokio::task::spawn_blocking(move || player.cue(index)).await; + Some(match cued { + Ok(Ok(took)) => (true, took.as_millis() as u64), + Ok(Err(e)) => { + warn!( + "Stinger on {}: could not park clip {} again: {}", + mixer, index, e + ); + (false, 0) + } + Err(_) => (false, 0), + }) } - Err(_) => (false, 0), + None => None, }; with_mixer(flow, &mixer, |s| { @@ -1235,17 +1323,19 @@ impl AppState { s.source = None; } s.last_take = Some(report.clone()); - if ready { + if let Some((true, cue_ms)) = parked { s.last_cue_ms = Some(cue_ms); } }); - self.inner.events.broadcast(StromEvent::StingerCued { - flow_id: flow, - block_id: mixer.clone(), - index, - ready, - cue_ms, - }); + if let Some((ready, cue_ms)) = parked { + self.inner.events.broadcast(StromEvent::StingerCued { + flow_id: flow, + block_id: mixer.clone(), + index, + ready, + cue_ms, + }); + } self.inner.events.broadcast(StromEvent::StingerCompleted { flow_id: flow, block_id: mixer, From 9913a157db3107638c4c130e0aa12d7e9adc04de Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Tue, 6 Oct 2026 15:10:44 -0700 Subject: [PATCH 02/15] feat(stinger): find where a stinger page starts from its first frame A page starts its animation on a trigger, and Chromium paints its first frame some time later. `stinger::web` holds what a page take needs to time itself from that frame: - `WebAnchor`: a probe on the page's cefsrc output that records the first frame of new content after the take. A GAP repeat, or a fixed-rate gstcefsrc re-sending its frame, shares the previous buffer's memory and does not count. Atomics only, removed once the take is planned. - `web_stinger_start`: the first frame if it came within 100 ms of the take, otherwise the take plus the plugin's delivery delay: 30 ms on the fixed-rate production gstcefsrc (measured on cefsrc's own output), 20 ms on one that emits as it paints. - `web_first_output_frame`: the output frame that page frame first goes on air in. The mixer drops queued buffers that end before an output frame and takes the oldest left, so a page at or below the mixer's rate is on air in the frame its timestamp falls in, and a faster one from the next frame boundary. Neither is the nearest frame: cefsrc's phase against the mixer's grid is fixed per run, and nearest is a frame out whenever that phase is in the second half of a frame. - `WebStingerSettings`: duration, cut point and mix from the HTML Input block. A cut point earlier than the grace period plus two frames (167 ms at 30 fps) cannot be programmed in time and is refused, as is one at or past the end. Co-Authored-By: Claude Opus 5.5 --- backend/src/stinger/mod.rs | 1 + backend/src/stinger/web.rs | 500 +++++++++++++++++++++++++++++++++++++ types/src/stinger.rs | 15 +- 3 files changed, 515 insertions(+), 1 deletion(-) create mode 100644 backend/src/stinger/web.rs diff --git a/backend/src/stinger/mod.rs b/backend/src/stinger/mod.rs index f81696002..01f708390 100644 --- a/backend/src/stinger/mod.rs +++ b/backend/src/stinger/mod.rs @@ -11,6 +11,7 @@ pub mod analysis; pub mod examples; +pub mod web; use strom_types::stinger::{ StingerBeneath, StingerClipInfo, StingerClipSettings, StingerLayout, StingerVariant, diff --git a/backend/src/stinger/web.rs b/backend/src/stinger/web.rs new file mode 100644 index 000000000..122cec594 --- /dev/null +++ b/backend/src/stinger/web.rs @@ -0,0 +1,500 @@ +//! Page stingers: an HTML Input whose page plays the stinger. +//! +//! A clip's first frame lands where the take pins it. A page starts its +//! animation when the take changes its URL fragment (`hashchange`), and +//! Chromium paints its first frame some time after that. So a page take +//! raises the graphic pad first (the page is transparent at rest), triggers +//! the page, watches the page's own output for its first new frame, and +//! plans the take from there ([`WebAnchor`], [`web_stinger_start`]). + +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::Arc; +use std::time::Duration; + +use gstreamer as gst; +use gstreamer::prelude::*; +use strom_types::stinger::{ + StingerLayout, StingerVariant, WEB_STINGER_CUT_POINT_PROPERTY, WEB_STINGER_DURATION_PROPERTY, + WEB_STINGER_MIX_PROPERTY, +}; +use strom_types::PropertyValue; + +use super::{ClipPlan, FrameGrid}; + +/// How soon after a take a page's first frame must arrive to be trusted as +/// the start of its animation. See [`web_stinger_start`]. +pub const PAGE_FIRST_FRAME_GRACE: Duration = Duration::from_millis(100); + +/// Delay from a take to the timestamp a page's first animation frame would +/// carry, used when the page paints nothing prompt to time from. Measured on +/// cefsrc's own output: a page that opens on unchanged pixels cut 91-93 ms +/// late by its own clock with 120 ms on the fixed-rate production gstcefsrc +/// (Linux, software CEF), so its animation starts about 28 ms after the +/// take. A gstcefsrc that emits frames as Chromium paints was measured at +/// about 20 ms on the earlier web stinger branch. +pub const PAGE_FIRST_FRAME_DELAY_PAINTED: Duration = Duration::from_millis(20); +pub const PAGE_FIRST_FRAME_DELAY_FIXED_RATE: Duration = Duration::from_millis(30); + +/// gstcefsrc property present only on builds that emit frames as Chromium +/// paints, rather than at a fixed rate. +pub const VARIABLE_RATE_PROPERTY: &str = "max-video-framerate"; + +/// The URL fragment a take sets to trigger a page. +pub fn take_fragment(token: u64) -> String { + format!("strom-take-{token}") +} + +/// A page stinger's settings, from its HTML Input block. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct WebStingerSettings { + pub duration_ms: u64, + /// 0 = the middle of the duration. + pub cut_point_ms: u64, + pub mix_ms: u64, +} + +impl WebStingerSettings { + pub fn from_properties(props: &HashMap) -> Self { + let ms = |name: &str| match props.get(name) { + Some(PropertyValue::UInt(v)) => *v, + Some(PropertyValue::Int(v)) if *v > 0 => *v as u64, + _ => 0, + }; + Self { + duration_ms: ms(WEB_STINGER_DURATION_PROPERTY), + cut_point_ms: ms(WEB_STINGER_CUT_POINT_PROPERTY), + mix_ms: ms(WEB_STINGER_MIX_PROPERTY), + } + } + + /// The earliest cut point a page take can program in time on a mixer + /// with frames of `frame_ns`: the take waits up to the grace period for + /// the page's first frame, and needs a couple of frames to program the + /// mixer after that. + pub fn min_cut_point_ms(frame_ns: u64) -> u64 { + (PAGE_FIRST_FRAME_GRACE.as_nanos() as u64 + 2 * frame_ns).div_ceil(1_000_000) + } + + /// How a take plays this page on a mixer with frames of `frame_ns`. A + /// page is a classic stinger, premultiplied as Chromium renders it. + pub fn plan(&self, frame_ns: u64) -> Result { + if self.duration_ms == 0 { + return Err("the stinger page has no duration (set Stinger Duration)".to_string()); + } + let cut = if self.cut_point_ms == 0 { + self.duration_ms / 2 + } else { + self.cut_point_ms + }; + if cut >= self.duration_ms { + return Err(format!( + "the stinger page's cut point ({} ms) must come before its end ({} ms)", + cut, self.duration_ms + )); + } + let min = Self::min_cut_point_ms(frame_ns); + if cut < min { + return Err(format!( + "the stinger page's cut point ({} ms) is too early: a page take needs at \ + least {} ms to find the page's first frame and program the cut", + cut, min + )); + } + Ok(ClipPlan { + variant: StingerVariant::Classic, + downgraded_from: None, + layout: StingerLayout::Classic, + duration_ms: self.duration_ms, + cut_point_ms: Some(cut), + mix_ms: self.mix_ms.min(self.duration_ms - cut), + premultiplied: true, + invert_matte: false, + }) + } +} + +/// Where a page stinger's animation starts, in the mixer's timeline. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WebStart { + /// Too soon to tell: keep waiting for the page's first frame. + Waiting, + /// The page's first frame arrived promptly, and its timestamp is the + /// start. + FirstFrame(u64), + /// No prompt frame, so the start is estimated from when the take changed + /// the URL. The page may have painted nothing visible at first, or be + /// slow. + FromTake(u64), +} + +/// Decide where a page stinger's animation starts. +/// +/// Chromium paints only when pixels change, so a page's first frame marks +/// the start of its animation only if the animation changes something on +/// screen straight away. One that opens on invisible frames (an element +/// moving in from off frame, a fade from nothing, a delayed start) delivers +/// its first frame late, and anchoring on it would cut late by as much. Its +/// own clock started at `hashchange`, so a frame stamped more than +/// `grace_ns` after the take is ignored in favour of the take plus the usual +/// delivery delay. +/// +/// All times are running times in ns. `first_frame_ns` is the first frame +/// of new content stamped at or after `taken_at_ns`. `output_ns` is the +/// newest timestamp seen on the output, repeats included: the grace period +/// ends when the output has moved past it, not when wall time has, because +/// a frame can be held between being painted and reaching the output. +pub fn web_stinger_start( + first_frame_ns: Option, + taken_at_ns: u64, + output_ns: Option, + grace_ns: u64, + delay_ns: u64, +) -> WebStart { + let deadline = taken_at_ns.saturating_add(grace_ns); + match first_frame_ns { + Some(frame) if frame <= deadline => WebStart::FirstFrame(frame), + _ if output_ns.is_some_and(|out| out > deadline) => { + WebStart::FromTake(taken_at_ns.saturating_add(delay_ns)) + } + _ => WebStart::Waiting, + } +} + +/// The output frame a page frame stamped `first_frame_ns` first goes on +/// air in, for page frames `page_frame_ns` long. +/// +/// For each output frame the mixer drops the queued buffers that end before +/// the frame starts and takes the oldest one left. Page frames at least an +/// output frame long are taken in the output frame their timestamp falls +/// in. Shorter ones (a page faster than the mixer) are taken from the first +/// output frame that starts inside them, so a page frame that starts and +/// ends within one output frame is dropped and its successor goes on air on +/// the next one. Which side of an output frame a page frame lands on is a +/// phase fixed when gstcefsrc starts, and differs from run to run. +pub fn web_first_output_frame(first_frame_ns: u64, page_frame_ns: u64, grid: FrameGrid) -> u64 { + let unit = 1_000_000_000u128 * grid.den as u128; + let mut n = (first_frame_ns as u128 * grid.num as u128 / unit) as u64; + // `pts` rounds to the nanosecond, so step to the exact frame either side. + while n > 0 && grid.pts(n) > first_frame_ns { + n -= 1; + } + while grid.pts(n + 1) <= first_frame_ns { + n += 1; + } + if page_frame_ns < grid.frame_ns() && grid.pts(n) < first_frame_ns { + n += 1; + } + grid.pts(n) +} + +/// Watches a page's output for its first new frame after a take. +/// +/// Wait for [`WebAnchor::ready`] before changing the URL, then call +/// [`WebAnchor::taken`]. Dropping it removes the probe. +pub struct WebAnchor { + /// Weak, so a take in flight never keeps a stopped flow's pipeline alive. + pad: gst::glib::WeakRef, + probe: Option, + /// Whether a baseline buffer has passed, so the next can be judged new. + baseline: Arc, + /// Running time at which the take changed the URL; `u64::MAX` before. + taken_at_ns: Arc, + /// Newest timestamp seen on the output, repeats included. + output_pts: Arc, + /// Timestamp of the first frame of new content after the take. + first_pts: Arc, + /// Assumed take-to-paint delay when the page paints nothing promptly. + pub delay: Duration, +} + +impl WebAnchor { + /// Watch `pad`, a `cefsrc` src pad. cefsrc stamps its frames with the + /// running time it makes them at, which every element down to the mixer + /// keeps. + pub fn watch(pad: &gst::Pad, delay: Duration) -> Option { + let baseline = Arc::new(AtomicBool::new(false)); + let taken_at_ns = Arc::new(AtomicU64::new(u64::MAX)); + let output_pts = Arc::new(AtomicU64::new(u64::MAX)); + let first_pts = Arc::new(AtomicU64::new(u64::MAX)); + let last_memory = AtomicUsize::new(0); + let (p_baseline, p_taken, p_output, p_first) = ( + Arc::clone(&baseline), + Arc::clone(&taken_at_ns), + Arc::clone(&output_pts), + Arc::clone(&first_pts), + ); + // A per-buffer probe for one take, removed once the take is planned: + // a few atomic loads, stores and compares per buffer. The first + // buffer only sets the baseline. After the take only new content + // counts: a GAP-flagged repeat, or a fixed-rate gstcefsrc re-sending + // its current frame, shares that frame's memory; a fresh paint is a + // new allocation. + let probe = pad.add_probe(gst::PadProbeType::BUFFER, move |_, info| { + let Some(buffer) = info.buffer() else { + return gst::PadProbeReturn::Ok; + }; + let memory = if buffer.n_memory() > 0 { + buffer.peek_memory(0).as_ptr() as usize + } else { + 0 + }; + let previous = last_memory.swap(memory, Ordering::Relaxed); + let Some(pts) = buffer.pts().map(|t| t.nseconds()) else { + return gst::PadProbeReturn::Ok; + }; + if !p_baseline.swap(true, Ordering::Relaxed) { + return gst::PadProbeReturn::Ok; + } + let taken_at = p_taken.load(Ordering::Relaxed); + if taken_at == u64::MAX { + return gst::PadProbeReturn::Ok; + } + p_output.store(pts, Ordering::Relaxed); + if pts >= taken_at + && memory != previous + && !buffer.flags().contains(gst::BufferFlags::GAP) + { + let _ = + p_first.compare_exchange(u64::MAX, pts, Ordering::Relaxed, Ordering::Relaxed); + } + gst::PadProbeReturn::Ok + })?; + Some(Self { + pad: pad.downgrade(), + probe: Some(probe), + baseline, + taken_at_ns, + output_pts, + first_pts, + delay, + }) + } + + /// Wait, up to `limit`, for the baseline buffer, so a page frame painted + /// just after the take is never mistaken for it. + pub async fn ready(&self, limit: Duration) { + let until = std::time::Instant::now() + limit; + while !self.baseline.load(Ordering::Relaxed) && std::time::Instant::now() < until { + tokio::time::sleep(Duration::from_millis(2)).await; + } + } + + /// Record that the take changed the page's URL at running time `now_ns`. + pub fn taken(&self, now_ns: u64) { + self.taken_at_ns.store(now_ns, Ordering::Relaxed); + } + + pub fn taken_at_ns(&self) -> Option { + load(&self.taken_at_ns) + } + + /// The first new frame's timestamp, once one has arrived. + pub fn first_frame_ns(&self) -> Option { + load(&self.first_pts) + } + + /// Where the page's animation started, once that can be told. + pub fn start(&self) -> WebStart { + let Some(taken_at) = self.taken_at_ns() else { + return WebStart::Waiting; + }; + web_stinger_start( + self.first_frame_ns(), + taken_at, + load(&self.output_pts), + PAGE_FIRST_FRAME_GRACE.as_nanos() as u64, + self.delay.as_nanos() as u64, + ) + } +} + +fn load(a: &AtomicU64) -> Option { + match a.load(Ordering::Relaxed) { + u64::MAX => None, + v => Some(v), + } +} + +impl Drop for WebAnchor { + fn drop(&mut self) { + if let (Some(probe), Some(pad)) = (self.probe.take(), self.pad.upgrade()) { + pad.remove_probe(probe); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const MS: u64 = 1_000_000; + + #[test] + fn a_prompt_first_frame_is_the_start() { + assert_eq!( + web_stinger_start( + Some(1_030 * MS), + 1_000 * MS, + Some(1_030 * MS), + 100 * MS, + 20 * MS + ), + WebStart::FirstFrame(1_030 * MS) + ); + // On the deadline still counts. + assert_eq!( + web_stinger_start( + Some(1_100 * MS), + 1_000 * MS, + Some(1_200 * MS), + 100 * MS, + 20 * MS + ), + WebStart::FirstFrame(1_100 * MS) + ); + } + + #[test] + fn a_late_first_frame_falls_back_to_the_take() { + assert_eq!( + web_stinger_start( + Some(1_300 * MS), + 1_000 * MS, + Some(1_300 * MS), + 100 * MS, + 20 * MS + ), + WebStart::FromTake(1_020 * MS) + ); + // No frame at all, once the output has moved past the grace period. + assert_eq!( + web_stinger_start(None, 1_000 * MS, Some(1_101 * MS), 100 * MS, 120 * MS), + WebStart::FromTake(1_120 * MS) + ); + } + + #[test] + fn it_waits_while_the_output_is_inside_the_grace_period() { + assert_eq!( + web_stinger_start(None, 1_000 * MS, Some(1_050 * MS), 100 * MS, 20 * MS), + WebStart::Waiting + ); + assert_eq!( + web_stinger_start(None, 1_000 * MS, None, 100 * MS, 20 * MS), + WebStart::Waiting + ); + } + + #[test] + fn a_page_frame_goes_on_air_in_the_output_frame_it_falls_in() { + let grid = FrameGrid::new(30, 1).unwrap(); + let f = grid.frame_ns(); + let on_air = |t| web_first_output_frame(t, f, grid); + assert_eq!(on_air(grid.pts(10) + f / 3), grid.pts(10)); + assert_eq!(on_air(grid.pts(10) + 2 * f / 3), grid.pts(10)); + assert_eq!(on_air(grid.pts(10)), grid.pts(10)); + assert_eq!(on_air(grid.pts(11) - 1), grid.pts(10)); + // Frame 2 of 1/30 s is stamped 66_666_667: a buffer a nanosecond + // before it starts inside frame 1. + assert_eq!(grid.pts(2), 66_666_667); + assert_eq!(on_air(66_666_666), grid.pts(1)); + // An hour in, the grid's own frame is still the one returned. + let n = 30 * 3600; + assert_eq!(on_air(grid.pts(n) + 1), grid.pts(n)); + // A slower page too: its frames span more than one output frame. + assert_eq!( + web_first_output_frame(grid.pts(10) + 2 * f / 3, 2 * f, grid), + grid.pts(10) + ); + let ntsc = FrameGrid::new(30000, 1001).unwrap(); + let nf = ntsc.frame_ns(); + assert_eq!( + web_first_output_frame(ntsc.pts(7) - 5, nf, ntsc), + ntsc.pts(6) + ); + assert_eq!(web_first_output_frame(ntsc.pts(7), nf, ntsc), ntsc.pts(7)); + } + + #[test] + fn a_page_faster_than_the_mixer_goes_on_air_from_the_next_output_frame() { + // Measured: a 60 fps page on a 30 fps mixer, stamped 8.3 or 24.6 ms + // into an output frame, first showed on the next one. + let grid = FrameGrid::new(30, 1).unwrap(); + let half = 16_666_667; + for into in [8_300_000, 24_600_000] { + assert_eq!( + web_first_output_frame(grid.pts(60) + into, half, grid), + grid.pts(61) + ); + } + // Stamped on an output frame, it is taken there. + assert_eq!( + web_first_output_frame(grid.pts(60), half, grid), + grid.pts(60) + ); + } + + fn settings(duration_ms: u64, cut_point_ms: u64, mix_ms: u64) -> WebStingerSettings { + WebStingerSettings { + duration_ms, + cut_point_ms, + mix_ms, + } + } + + const FRAME_30: u64 = 33_333_333; + + #[test] + fn the_cut_point_must_leave_time_to_find_the_page_and_program_the_cut() { + assert_eq!(WebStingerSettings::min_cut_point_ms(FRAME_30), 167); + let err = settings(1_000, 150, 0).plan(FRAME_30).unwrap_err(); + assert!(err.contains("too early") && err.contains("167 ms"), "{err}"); + assert!(settings(1_000, 167, 0).plan(FRAME_30).is_ok()); + // At 60 fps the frames are shorter, so the floor is lower. + assert_eq!(WebStingerSettings::min_cut_point_ms(16_666_667), 134); + } + + #[test] + fn the_cut_point_must_come_before_the_end() { + let err = settings(1_000, 1_000, 0).plan(FRAME_30).unwrap_err(); + assert!(err.contains("before its end"), "{err}"); + assert!(settings(1_000, 1_500, 0).plan(FRAME_30).is_err()); + assert!(settings(1_000, 999, 0).plan(FRAME_30).is_ok()); + } + + #[test] + fn a_page_needs_a_duration() { + let err = settings(0, 500, 0).plan(FRAME_30).unwrap_err(); + assert!(err.contains("no duration"), "{err}"); + } + + #[test] + fn a_page_plans_as_a_premultiplied_classic_stinger() { + let plan = settings(1_200, 0, 0).plan(FRAME_30).unwrap(); + assert_eq!(plan.variant, StingerVariant::Classic); + assert_eq!(plan.layout, StingerLayout::Classic); + assert!(plan.premultiplied); + assert_eq!(plan.cut_point_ms, Some(600), "0 takes the middle"); + assert_eq!(plan.mix_ms, 0); + // A mix runs out with the page, not past it. + let plan = settings(1_000, 700, 500).plan(FRAME_30).unwrap(); + assert_eq!(plan.mix_ms, 300); + } + + #[test] + fn settings_read_from_the_block() { + let props: HashMap = [ + (WEB_STINGER_DURATION_PROPERTY, PropertyValue::UInt(1_000)), + (WEB_STINGER_CUT_POINT_PROPERTY, PropertyValue::Int(400)), + (WEB_STINGER_MIX_PROPERTY, PropertyValue::String("x".into())), + ] + .into_iter() + .map(|(k, v)| (k.to_string(), v)) + .collect(); + assert_eq!( + WebStingerSettings::from_properties(&props), + settings(1_000, 400, 0) + ); + } +} diff --git a/types/src/stinger.rs b/types/src/stinger.rs index f90f28b18..599409fdb 100644 --- a/types/src/stinger.rs +++ b/types/src/stinger.rs @@ -18,9 +18,22 @@ use serde::{Deserialize, Serialize}; #[cfg(feature = "openapi")] use utoipa::ToSchema; -/// Block property on a Media Player that makes it a stinger clip source. +/// Block property on a Media Player that makes it a stinger clip source, +/// and on an HTML Input that makes its page a stinger. pub const STINGER_MODE_PROPERTY: &str = "stinger_mode"; +/// HTML Input property: how long a stinger page covers the program, from +/// the trigger. Required for a page stinger. +pub const WEB_STINGER_DURATION_PROPERTY: &str = "stinger_duration_ms"; + +/// HTML Input property: how far into a stinger page the program changes. +/// 0 takes the middle of the duration. +pub const WEB_STINGER_CUT_POINT_PROPERTY: &str = "stinger_cut_point_ms"; + +/// HTML Input property: how long the program mixes at the cut point +/// (0 = cut). +pub const WEB_STINGER_MIX_PROPERTY: &str = "stinger_mix_ms"; + /// Block property on a Media Player holding per-clip stinger settings, as a /// JSON object keyed by playlist entry. Managed through the stinger API. pub const STINGER_CLIPS_PROPERTY: &str = "stinger_clips"; From bcaf776b556b30a8b0457a51abde78d704beb8af Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Tue, 6 Oct 2026 15:11:02 -0700 Subject: [PATCH 03/15] feat(stinger): take a stinger from an HTML Input page An HTML Input in stinger mode on the mixer's stinger input is a page stinger. Its settings are properties of the block, and it is the one entry of its library. A take raises the graphic pad (the page is transparent at rest), triggers the page by setting its URL fragment to #strom-take- through `cef_pages::load_url`, waits for the page's first frame, and programs the take from the output frame that frame goes on air in. Reporting and finishing are a clip take's: StingerStarted, StingerCompleted, StingerFailed and the take report. A take that cannot program cuts instead, as a clip take does. The graphic pad goes up before the trigger because the take is programmed after the page has started: a fill keyframe at the page's start would already be behind the mixer, and the page's first frame would not show. - A page is a classic stinger with premultiplied alpha: the GPU mixer blends it correctly, the software mixer warns that edges come out dark. - On a gstcefsrc that emits only as the page paints, the take warns: the stinger pads let a held frame go after two frames. - Under remote control the trigger loads asynchronously; the take still anchors on the first frame, and logs that the fallback may be late. - Library operations (add, remove, settings, examples) are refused for a page, so a page cannot ask for a matte variant. Cue is a no-op. - The take report expects the page frames from when its frame count starts, which is after the page's first frame has reached the mixer. `StingerState` gains `source_kind`, so a client can tell a clip library from a page. Co-Authored-By: Claude Opus 5.5 --- backend/src/openapi.rs | 1 + backend/src/state/stinger.rs | 183 ++++++++++--- backend/src/state/stinger/web.rs | 424 +++++++++++++++++++++++++++++++ openapi.json | 21 +- types/src/stinger.rs | 17 +- 5 files changed, 604 insertions(+), 42 deletions(-) create mode 100644 backend/src/state/stinger/web.rs diff --git a/backend/src/openapi.rs b/backend/src/openapi.rs index 047354c22..d8a9392d1 100644 --- a/backend/src/openapi.rs +++ b/backend/src/openapi.rs @@ -332,6 +332,7 @@ use utoipa::OpenApi; strom_types::stinger::StingerVariant, strom_types::stinger::StingerBeneath, strom_types::stinger::StingerClipSettings, + strom_types::stinger::StingerSourceKind, strom_types::stinger::StingerClipInfo, strom_types::stinger::StingerClip, strom_types::stinger::StingerTakeReport, diff --git a/backend/src/state/stinger.rs b/backend/src/state/stinger.rs index b776e0780..d6dfdaa70 100644 --- a/backend/src/state/stinger.rs +++ b/backend/src/state/stinger.rs @@ -14,13 +14,15 @@ use std::sync::{Arc, LazyLock, Mutex}; use std::time::{Duration, Instant}; use strom_types::stinger::{ - StingerClip, StingerClipSettings, StingerExamplesResponse, StingerState, StingerTakeReport, - StingerTakeResponse, STINGER_CLIPS_PROPERTY, STINGER_INPUT_PAD, STINGER_MODE_PROPERTY, + StingerClip, StingerClipSettings, StingerExamplesResponse, StingerSourceKind, StingerState, + StingerTakeReport, StingerTakeResponse, STINGER_CLIPS_PROPERTY, STINGER_INPUT_PAD, + STINGER_MODE_PROPERTY, }; use strom_types::{FlowId, PropertyValue, StromEvent}; use tracing::{debug, error, info, warn}; use super::AppState; +use crate::blocks::builtin::html_input; use crate::blocks::builtin::mediaplayer::{ normalize_uri, MediaPlayerKey, MediaPlayerState, MEDIA_PLAYER_REGISTRY, }; @@ -28,6 +30,8 @@ use crate::gst::pipeline::effects::stinger::{StingerTake, StingerWatch}; use crate::gst::pipeline::PipelineError; use crate::stinger::{analysis, examples, plan_clip, ClipPlan, FrameGrid}; +mod web; + /// How long after the clip's end a take waits for the mixer to get past it /// before giving up on a stalled mixer. const FINISH_GRACE: Duration = Duration::from_secs(5); @@ -38,8 +42,7 @@ struct MixerStinger { /// The token of the take on air, or of a classic take or fade-to-black /// programming the pads now (see [`claim_for_classic`]). running: Option, - /// The clip source of the stinger take on air; `None` for a classic - /// claim. + /// The stinger source of the take on air; `None` for a classic claim. source: Option, last_take: Option, last_cue_ms: Option, @@ -221,7 +224,42 @@ fn err(reason: impl Into) -> PipelineError { PipelineError::TransitionError(reason.into()) } -/// What a stinger operation needs to know about a mixer and its source. +/// A mixer's stinger source. +enum Source { + Clips(Context), + Page(PageContext), +} + +impl Source { + fn block_id(&self) -> &str { + match self { + Source::Clips(ctx) => &ctx.source_block_id, + Source::Page(page) => &page.source_block_id, + } + } +} + +/// What one take plays. +enum Plays<'a> { + Clip(&'a Context, usize, String), + Page(&'a PageContext), +} + +enum SourceSettings { + Clips(HashMap), + Page(HashMap), +} + +/// A stinger page: an HTML Input in stinger mode. +struct PageContext { + source_block_id: String, + /// The block's properties, which carry the page's stinger settings. + properties: HashMap, + preroll_ms: u64, + matte_supported: bool, +} + +/// What a stinger operation needs to know about a mixer and its clip source. struct Context { source_block_id: String, player: Arc, @@ -307,9 +345,22 @@ fn take_on_grid( } impl AppState { + /// Find the mixer's clip source and settings. A page source has no clip + /// library, so library operations fail on it. + async fn stinger_context(&self, flow_id: &FlowId, block: &str) -> Result { + match self.stinger_source(flow_id, block).await? { + Source::Clips(ctx) => Ok(ctx), + Source::Page(page) => Err(format!( + "HTML Input {} is a stinger page and has no clip library; its stinger \ + settings are properties of the block", + page.source_block_id + )), + } + } + /// Find the mixer's stinger source and settings. Errors say what is /// missing in terms an operator can fix. - async fn stinger_context(&self, flow_id: &FlowId, block: &str) -> Result { + async fn stinger_source(&self, flow_id: &FlowId, block: &str) -> Result { let (source_block_id, settings, preroll_ms) = { let flows = self.inner.flows.read().await; let flow = flows.get(flow_id).ok_or("no such flow")?; @@ -341,37 +392,46 @@ impl AppState { .find(|l| l.to == to) .and_then(|l| l.from.strip_suffix(":video_out")) .ok_or("nothing is wired to the stinger input")?; + const NOT_A_SOURCE: &str = + "the stinger input is not fed by a Media Player or an HTML Input"; let source_block = flow .blocks .iter() .find(|b| b.id == source) - .ok_or("the stinger input is not fed by a Media Player")?; - if source_block.block_definition_id != "builtin.media_player" { - return Err("the stinger input is not fed by a Media Player".into()); - } + .ok_or(NOT_A_SOURCE)?; + let kind = match source_block.block_definition_id.as_str() { + "builtin.media_player" => StingerSourceKind::Clips, + html_input::BLOCK_ID => StingerSourceKind::Page, + _ => return Err(NOT_A_SOURCE.into()), + }; if !matches!( source_block.properties.get(STINGER_MODE_PROPERTY), Some(PropertyValue::Bool(true)) ) { - return Err(format!( - "Media Player {} is not a stinger clip source (turn on Stinger Clip Source)", - source - )); + return Err(match kind { + StingerSourceKind::Clips => format!( + "Media Player {} is not a stinger clip source (turn on Stinger Clip Source)", + source + ), + StingerSourceKind::Page => format!( + "HTML Input {} is not a stinger page (turn on Stinger Page)", + source + ), + }); } - let settings = match source_block.properties.get(STINGER_CLIPS_PROPERTY) { - Some(PropertyValue::String(json)) => { - strom_types::stinger::parse_clip_settings(json) - } - _ => HashMap::new(), + let settings = match kind { + StingerSourceKind::Page => SourceSettings::Page(source_block.properties.clone()), + StingerSourceKind::Clips => SourceSettings::Clips( + match source_block.properties.get(STINGER_CLIPS_PROPERTY) { + Some(PropertyValue::String(json)) => { + strom_types::stinger::parse_clip_settings(json) + } + _ => HashMap::new(), + }, + ), }; (source.to_string(), settings, preroll_ms) }; - let player = MEDIA_PLAYER_REGISTRY - .get(&MediaPlayerKey { - flow_id: *flow_id, - block_id: source_block_id.clone(), - }) - .ok_or("the flow is not running")?; let matte_supported = self .inner .pipelines @@ -380,13 +440,30 @@ impl AppState { .get(flow_id) .and_then(|m| m.stinger_pads(block)) .is_some_and(|p| p.matte.is_some()); - Ok(Context { + let settings = match settings { + SourceSettings::Page(properties) => { + return Ok(Source::Page(PageContext { + source_block_id, + properties, + preroll_ms, + matte_supported, + })); + } + SourceSettings::Clips(settings) => settings, + }; + let player = MEDIA_PLAYER_REGISTRY + .get(&MediaPlayerKey { + flow_id: *flow_id, + block_id: source_block_id.clone(), + }) + .ok_or("the flow is not running")?; + Ok(Source::Clips(Context { source_block_id, player, settings, preroll_ms, matte_supported, - }) + })) } /// Analyse a clip off the request path, once at a time per clip. @@ -449,11 +526,17 @@ impl AppState { let (last_take, last_cue_ms, running) = with_mixer(*flow_id, block, |s| { (s.last_take.clone(), s.last_cue_ms, s.running) }); - let ctx = match self.stinger_context(flow_id, block).await { - Ok(ctx) => ctx, + let ctx = match self.stinger_source(flow_id, block).await { + Ok(Source::Clips(ctx)) => ctx, + Ok(Source::Page(page)) => { + return Ok(self + .page_stinger_state(flow_id, block, &page, last_take, running.is_some()) + .await) + } Err(problem) => { return Ok(StingerState { source_block_id: None, + source_kind: None, problem: Some(problem), matte_supported: false, preroll_ms: strom_types::stinger::DEFAULT_STINGER_PREROLL_MS, @@ -480,6 +563,7 @@ impl AppState { } Ok(StingerState { source_block_id: Some(ctx.source_block_id.clone()), + source_kind: Some(StingerSourceKind::Clips), problem: files .is_empty() .then(|| "the stinger source's playlist is empty".to_string()), @@ -556,7 +640,10 @@ impl AppState { if is_running(flow_id, block) { return Err(err("a stinger is on air; cue when it has finished")); } - let ctx = self.stinger_context(flow_id, block).await.map_err(err)?; + let ctx = match self.stinger_source(flow_id, block).await.map_err(err)? { + Source::Clips(ctx) => ctx, + Source::Page(_) => return self.page_stinger_cue(flow_id, block, index), + }; let file = ctx.clip_at(index, expected_file)?; Self::analyse_in_background(ctx.uri(&file)); let player = Arc::clone(&ctx.player); @@ -897,7 +984,7 @@ impl AppState { expected_file: Option<&str>, ) -> Result { let requested = Instant::now(); - let ctx = self.stinger_context(flow_id, block).await.map_err(err)?; + let source = self.stinger_source(flow_id, block).await.map_err(err)?; let state = crate::blocks::builtin::vision_mixer::overlay::get_overlay_state(flow_id, block) .ok_or_else(|| err("the vision mixer is not running"))?; @@ -909,8 +996,17 @@ impl AppState { if from == to { return Err(err("PGM and PVW are the same input")); } - let index = index.unwrap_or_else(|| ctx.player.current_index()); - let file = ctx.clip_at(index, expected_file)?; + // What the take plays: a clip from the library, or the page. + let plays = match &source { + Source::Clips(ctx) => { + let index = index.unwrap_or_else(|| ctx.player.current_index()); + Plays::Clip(ctx, index, ctx.clip_at(index, expected_file)?) + } + Source::Page(page) => { + page.check_take(index, expected_file)?; + Plays::Page(page) + } + }; let token = NEXT_TOKEN.fetch_add(1, Ordering::Relaxed); let claimed = with_mixer(*flow_id, block, |s| { @@ -918,7 +1014,7 @@ impl AppState { false } else { s.running = Some(token); - s.source = Some(ctx.source_block_id.clone()); + s.source = Some(source.block_id().to_string()); true } }); @@ -926,12 +1022,19 @@ impl AppState { return Err(err("a stinger is already on air on this mixer")); } - match self - .stinger_take_claimed( - flow_id, block, &ctx, token, index, &file, from, to, requested, - ) - .await - { + let taken = match plays { + Plays::Clip(ctx, index, file) => { + self.stinger_take_claimed( + flow_id, block, ctx, token, index, &file, from, to, requested, + ) + .await + } + Plays::Page(page) => { + self.page_stinger_take(flow_id, block, page, token, from, to, requested) + .await + } + }; + match taken { Ok(response) => Ok(response), Err((reason, cut_instead)) => { release(*flow_id, block, token); diff --git a/backend/src/state/stinger/web.rs b/backend/src/state/stinger/web.rs new file mode 100644 index 000000000..5d6a5aef4 --- /dev/null +++ b/backend/src/state/stinger/web.rs @@ -0,0 +1,424 @@ +//! Page stinger takes: an HTML Input in stinger mode on the stinger input. +//! +//! The page's start is not known until it paints, so a take raises the +//! graphic pad, triggers the page, finds the page's first frame +//! ([`crate::stinger::web`]) and only then programs the take, from that +//! frame. Reporting and finishing are a clip take's. + +use std::time::{Duration, Instant}; + +use gstreamer as gst; +use gstreamer::prelude::*; +use strom_types::stinger::{ + StingerBeneath, StingerClip, StingerClipSettings, StingerSourceKind, StingerState, + StingerTakeReport, StingerTakeResponse, StingerVariant, +}; +use strom_types::{FlowId, PropertyValue, StromEvent}; +use tracing::{debug, warn}; + +use super::{err, take_on_grid, AppState, PageContext, Started}; +use crate::blocks::builtin::html_input; +use crate::gst::pipeline::PipelineError; +use crate::stinger::web::{ + take_fragment, web_first_output_frame, WebAnchor, WebStart, WebStingerSettings, + PAGE_FIRST_FRAME_DELAY_FIXED_RATE, PAGE_FIRST_FRAME_DELAY_PAINTED, PAGE_FIRST_FRAME_GRACE, + VARIABLE_RATE_PROPERTY, +}; +use crate::stinger::FrameGrid; + +/// How long past the grace period a take waits for the page's output to +/// move before it times the page from the take anyway. A paint-only page +/// that paints nothing leaves the output still. +const SILENT_PAGE_LIMIT: Duration = Duration::from_millis(400); + +/// A 30 fps grid, to judge a page's settings while its flow is stopped. +const NOMINAL_GRID: FrameGrid = FrameGrid { num: 30, den: 1 }; + +/// How many page frames, stamped every `page_frame_ns` from `first_ns`, fall +/// in `[from, to)`. +fn page_frames_between(first_ns: u64, page_frame_ns: u64, from: u64, to: u64) -> u32 { + let index_at = |t: u64| t.saturating_sub(first_ns).div_ceil(page_frame_ns.max(1)); + index_at(to).saturating_sub(index_at(from)) as u32 +} + +impl PageContext { + fn settings(&self) -> WebStingerSettings { + WebStingerSettings::from_properties(&self.properties) + } + + fn configured_url(&self) -> String { + html_input::url(&self.properties) + } + + /// How long one page frame lasts, from the rate cefsrc negotiated, or + /// the block's when that is variable or not known yet. + fn frame_ns(&self, cefsrc_src: &gst::Pad) -> u64 { + cefsrc_src + .current_caps() + .and_then(|c| c.structure(0)?.get::("framerate").ok()) + .filter(|f| f.numer() > 0 && f.denom() > 0) + .map(|f| 1_000_000_000 * f.denom() as u64 / f.numer() as u64) + .unwrap_or_else(|| 1_000_000_000 / self.framerate()) + } + + fn framerate(&self) -> u64 { + match self.properties.get("framerate") { + Some(PropertyValue::UInt(f)) if *f > 0 => *f, + Some(PropertyValue::Int(f)) if *f > 0 => *f as u64, + _ => 30, + } + } + + /// A page is the one entry of its library: index 0, named by its URL. + pub(super) fn check_take( + &self, + index: Option, + expected_file: Option<&str>, + ) -> Result<(), PipelineError> { + if index.is_some_and(|i| i != 0) { + return Err(err(format!( + "HTML Input {} is a stinger page: its only entry is 0", + self.source_block_id + ))); + } + match expected_file { + Some(want) if want != self.configured_url() => Err(PipelineError::Conflict(format!( + "the stinger page is now '{}', not '{}'", + self.configured_url(), + want + ))), + _ => Ok(()), + } + } + + /// The page as a library entry, for the operator panel. + fn describe(&self, grid: FrameGrid) -> (StingerClip, Option) { + let settings = self.settings(); + let plan = settings.plan(grid.frame_ns()); + let cut = plan.as_ref().ok().and_then(|p| p.cut_point_ms); + let clip = StingerClip { + index: 0, + file: self.configured_url(), + settings: StingerClipSettings { + layout: strom_types::stinger::StingerLayout::Classic, + cut_point_ms: cut, + beneath: if settings.mix_ms > 0 { + StingerBeneath::Mix + } else { + StingerBeneath::Cut + }, + mix_ms: plan.as_ref().map(|p| p.mix_ms).unwrap_or(settings.mix_ms), + premultiplied: true, + invert_matte: false, + }, + info: None, + variant: Some(StingerVariant::Classic), + downgraded_from: None, + cut_point_ms: cut, + missing: false, + analysis_error: None, + }; + (clip, plan.err()) + } +} + +impl AppState { + /// The stinger state of a mixer whose stinger input is a page. + pub(super) async fn page_stinger_state( + &self, + flow_id: &FlowId, + mixer: &str, + page: &PageContext, + last_take: Option, + running: bool, + ) -> StingerState { + let (grid, playing) = { + let pipelines = self.inner.pipelines.read().await; + let manager = pipelines.get(flow_id); + let grid = manager.and_then(|m| m.mixer_frame_grid(mixer)); + let playing = manager + .and_then(|m| m.find_gst_element(&format!("{}:cefsrc", page.source_block_id))) + .is_some_and(|c| c.current_state() == gst::State::Playing); + (grid, playing) + }; + let (clip, invalid) = page.describe(grid.unwrap_or(NOMINAL_GRID)); + let problem = invalid.or_else(|| { + (!playing).then(|| format!("HTML Input {} is not running", page.source_block_id)) + }); + StingerState { + source_block_id: Some(page.source_block_id.clone()), + source_kind: Some(StingerSourceKind::Page), + problem, + matte_supported: page.matte_supported, + preroll_ms: page.preroll_ms, + clips: vec![clip], + cued_index: Some(0), + ready: playing, + last_cue_ms: None, + running, + last_take, + } + } + + /// A page is always ready: cueing it does nothing. + pub(super) fn page_stinger_cue( + &self, + flow_id: &FlowId, + block: &str, + index: usize, + ) -> Result { + if index != 0 { + return Err(err("a stinger page's only entry is 0")); + } + self.inner.events.broadcast(StromEvent::StingerCued { + flow_id: *flow_id, + block_id: block.to_string(), + index, + ready: true, + cue_ms: 0, + }); + Ok(0) + } + + /// The take, once the mixer is claimed. On failure says whether the + /// program should cut instead (the page will not play). + #[allow(clippy::too_many_arguments)] + pub(super) async fn page_stinger_take( + &self, + flow_id: &FlowId, + block: &str, + page: &PageContext, + token: u64, + from: usize, + to: usize, + requested: Instant, + ) -> Result { + let source = &page.source_block_id; + let (cefsrc, grid) = { + let pipelines = self.inner.pipelines.read().await; + let manager = pipelines + .get(flow_id) + .ok_or_else(|| ("the flow is not running".to_string(), false))?; + let grid = manager.mixer_frame_grid(block).ok_or_else(|| { + ( + "the mixer has not negotiated a frame rate".to_string(), + false, + ) + })?; + let cefsrc = manager + .find_gst_element(&format!("{}:cefsrc", source)) + .cloned() + .ok_or_else(|| (format!("HTML Input {} is not running", source), true))?; + (cefsrc, grid) + }; + let settings = page.settings(); + let plan = settings.plan(grid.frame_ns()).map_err(|e| (e, false))?; + let duration_ns = plan.duration_ms * 1_000_000; + + let fixed_rate = cefsrc.find_property(VARIABLE_RATE_PROPERTY).is_none(); + if !fixed_rate { + warn!( + "Stinger page {}: this gstcefsrc emits frames only as the page paints, and the \ + mixer's stinger input lets a held frame go after two frames: a page that holds \ + a still frame across the cut can drop off air", + source + ); + } + if html_input::remote_control_enabled(&page.properties) { + debug!( + "Stinger page {}: under remote control the page loads its trigger \ + asynchronously, so a page that paints late is timed from before it started", + source + ); + } + let pad = cefsrc + .static_pad("src") + .ok_or_else(|| ("the stinger page has no output".to_string(), true))?; + + // Stage the take and raise the graphic: the page is transparent at + // rest, so nothing shows until it starts. Its start is not known + // yet; the times are filled in once it is. + let staged = take_on_grid( + &grid, + 0, + duration_ns, + &plan, + from, + to, + None, + grid.frame_ns(), + true, + ); + let ftb_cancelled = { + let pipelines = self.inner.pipelines.read().await; + let manager = pipelines + .get(flow_id) + .ok_or_else(|| ("the flow is not running".to_string(), false))?; + // A failure has already put the old source back alone on air. + manager.raise_stinger_fill(block, &staged).map_err(|e| { + if e.ftb_cancelled { + self.broadcast_ftb_ended(flow_id, block); + } + (e.error.to_string(), true) + })? + }; + let staged = &staged; + let abort = |reason: String| async move { + if let Some(manager) = self.inner.pipelines.read().await.get(flow_id) { + manager.abort_stinger(block, staged); + } + if ftb_cancelled { + self.broadcast_ftb_ended(flow_id, block); + } + (reason, true) + }; + + let delay = if fixed_rate { + PAGE_FIRST_FRAME_DELAY_FIXED_RATE + } else { + PAGE_FIRST_FRAME_DELAY_PAINTED + }; + let Some(anchor) = WebAnchor::watch(&pad, delay) else { + return Err(abort("could not watch the stinger page's output".to_string()).await); + }; + anchor.ready(Duration::from_millis(100)).await; + + // A new fragment is a same-document navigation: the loaded page gets + // `hashchange` and starts its animation, rather than reloading. + let shown: Option = cefsrc.property(html_input::URL_PROPERTY); + let shown = crate::cef_pages::shown_url( + cefsrc.upcast_ref(), + shown.unwrap_or_else(|| page.configured_url()), + ); + let base = shown.split('#').next().unwrap_or_default().to_string(); + crate::cef_pages::load_url(&cefsrc, &format!("{}#{}", base, take_fragment(token))); + let taken_at = Instant::now(); + let Some(taken_rt) = cefsrc.current_running_time().map(|t| t.nseconds()) else { + return Err(abort("the flow has no running time".to_string()).await); + }; + anchor.taken(taken_rt); + + let give_up = taken_at + PAGE_FIRST_FRAME_GRACE + SILENT_PAGE_LIMIT; + // The page's start: its first frame, or the take plus the delivery + // delay when it painted nothing promptly. + let (anchor_ns, prompt) = loop { + match anchor.start() { + WebStart::FirstFrame(ns) => break (ns, true), + WebStart::FromTake(ns) => break (ns, false), + WebStart::Waiting if Instant::now() < give_up => { + tokio::time::sleep(Duration::from_millis(2)).await; + } + WebStart::Waiting => break (taken_rt + delay.as_nanos() as u64, false), + } + }; + let first = anchor.first_frame_ns(); + drop(anchor); + let after_take = |ns: u64| ns.saturating_sub(taken_rt) / 1_000_000; + if prompt { + debug!( + "Stinger page {}: first frame {} ms after the take", + source, + after_take(anchor_ns) + ); + } else { + warn!( + "Stinger page {}: no frame within {} ms of the take{}, so the cut is timed \ + from the take and may be a frame out. A stinger page should change \ + something visible on its first frame", + source, + PAGE_FIRST_FRAME_GRACE.as_millis(), + first + .map(|f| format!(" (first came after {} ms)", after_take(f))) + .unwrap_or_default() + ); + } + + // Program the take from the output frame the page goes on air in. + let page_frame_ns = page.frame_ns(&pad); + let start = web_first_output_frame(anchor_ns, page_frame_ns, grid); + let take = take_on_grid( + &grid, + start, + duration_ns, + &plan, + from, + to, + None, + page_frame_ns, + true, + ); + debug!( + "Stinger page {}: page started at {} ns, on air from output frame {} ns, cut at {:?} ns", + source, anchor_ns, take.start, take.cut_at + ); + // The frame count starts when the take is programmed, after the + // page's first frames have reached the mixer, so only the frames from + // then on are expected. + let counted_from = cefsrc + .current_running_time() + .map_or(take.start, |t| t.nseconds().max(take.start)); + let programmed = { + let pipelines = self.inner.pipelines.read().await; + match pipelines.get(flow_id) { + Some(manager) => manager + .program_stinger(block, &take) + .map_err(|e| e.error.to_string()), + None => Err("the flow is not running".to_string()), + } + }; + let watch = match programmed { + Ok((watch, _)) => watch, + Err(e) => return Err(abort(e).await), + }; + + let take_to_air_ms = + (taken_at - requested).as_secs_f64() * 1000.0 + (start as f64 - taken_rt as f64) / 1e6; + let frames_expected = page_frames_between(anchor_ns, page_frame_ns, counted_from, take.end); + Ok(self + .announce_stinger_take( + flow_id, + block, + Started { + token, + index: 0, + file: base, + plan, + take, + watch, + ftb_cancelled, + take_to_air_ms, + cue_ms: None, + frames_expected, + player: None, + }, + ) + .await) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn expected_page_frames_count_from_when_counting_starts() { + let f = 33_333_333; + // Page frames every frame from 1_008 ms; on air from 1_000 ms for a + // second: 30 frames. + let first = 1_008_000_000; + assert_eq!( + page_frames_between(first, f, 1_000_000_000, 2_000_000_000), + 30 + ); + // Counting started 12 ms after the first frame: it missed that one. + assert_eq!( + page_frames_between(first, f, 1_020_000_000, 2_000_000_000), + 29 + ); + // A 60 fps page. + assert_eq!( + page_frames_between(first, 16_666_667, 1_033_333_333, 2_033_333_333), + 60 + ); + } +} diff --git a/openapi.json b/openapi.json index 7fdb2f2e7..8d9cb8a1d 100644 --- a/openapi.json +++ b/openapi.json @@ -11131,6 +11131,14 @@ "mask_only" ] }, + "StingerSourceKind": { + "type": "string", + "description": "What feeds a vision mixer's stinger input.", + "enum": [ + "clips", + "page" + ] + }, "StingerState": { "type": "object", "description": "Stinger state of one vision mixer.", @@ -11205,7 +11213,18 @@ "string", "null" ], - "description": "The Media Player wired to the stinger input." + "description": "The block wired to the stinger input." + }, + "source_kind": { + "oneOf": [ + { + "type": "null" + }, + { + "$ref": "#/components/schemas/StingerSourceKind", + "description": "What kind of block that is." + } + ] } } }, diff --git a/types/src/stinger.rs b/types/src/stinger.rs index 599409fdb..10c761516 100644 --- a/types/src/stinger.rs +++ b/types/src/stinger.rs @@ -247,12 +247,27 @@ pub struct StingerTakeReport { pub warning: Option, } +/// What feeds a vision mixer's stinger input. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[cfg_attr(feature = "openapi", derive(ToSchema))] +#[serde(rename_all = "snake_case")] +pub enum StingerSourceKind { + /// A Media Player whose playlist is the clip library. + Clips, + /// An HTML Input whose page plays the stinger on a trigger. Its settings + /// are properties of the block, and it is the only entry in `clips`. + Page, +} + /// Stinger state of one vision mixer. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[cfg_attr(feature = "openapi", derive(ToSchema))] pub struct StingerState { - /// The Media Player wired to the stinger input. + /// The block wired to the stinger input. pub source_block_id: Option, + /// What kind of block that is. + #[serde(default)] + pub source_kind: Option, /// Why stingers cannot run, when they cannot. pub problem: Option, /// Whether the matte variants run here (GPU mixer). From bb71ada4ab78506ae3cb7150cf2be6a75a48a57b Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Tue, 6 Oct 2026 15:11:02 -0700 Subject: [PATCH 04/15] feat(html_input): stinger page settings, and the panel's page source The HTML Input block gains Stinger Page, Stinger Duration, Stinger Cut Point and Stinger Mix. The vision mixer panel shows a page source as its one entry, hides the clip tools for it, and stops polling for an analysis a page never gets. Co-Authored-By: Claude Opus 5.5 --- backend/src/blocks/builtin/html_input.rs | 74 ++++++++++++++++++++++++ backend/static/vision-mixer.html | 37 +++++++++--- 2 files changed, 102 insertions(+), 9 deletions(-) diff --git a/backend/src/blocks/builtin/html_input.rs b/backend/src/blocks/builtin/html_input.rs index 5c16f15a2..8ea3b0ff3 100644 --- a/backend/src/blocks/builtin/html_input.rs +++ b/backend/src/blocks/builtin/html_input.rs @@ -906,6 +906,80 @@ fn html_input_definition() -> BlockDefinition { persist: None, visible_when: None, }, + ExposedProperty { + name: strom_types::stinger::STINGER_MODE_PROPERTY.to_string(), + label: "Stinger Page".to_string(), + description: "Play this page as a Vision Mixer stinger: wire video_out to the mixer's stinger \ + input, and a take triggers the page by setting its URL fragment to \ + #strom-take- (listen for hashchange). The page must be \ + transparent at rest and change something visible on the first \ + frame of its animation; the cut is timed from that frame. Plays as \ + a classic stinger with premultiplied alpha." + .to_string(), + property_type: PropertyType::Bool, + default_value: Some(PropertyValue::Bool(false)), + mapping: PropertyMapping { + element_id: "_block".to_string(), + property_name: strom_types::stinger::STINGER_MODE_PROPERTY.to_string(), + transform: None, + }, + live: false, + persist: None, + visible_when: None, + }, + ExposedProperty { + name: strom_types::stinger::WEB_STINGER_DURATION_PROPERTY.to_string(), + label: "Stinger Duration (ms)".to_string(), + description: "How long the stinger page covers the program after a take. Required for a \ + stinger page." + .to_string(), + property_type: PropertyType::UInt, + default_value: Some(PropertyValue::UInt(0)), + mapping: PropertyMapping { + element_id: "_block".to_string(), + property_name: strom_types::stinger::WEB_STINGER_DURATION_PROPERTY.to_string(), + transform: None, + }, + live: false, + persist: None, + visible_when: None, + }, + ExposedProperty { + name: strom_types::stinger::WEB_STINGER_CUT_POINT_PROPERTY.to_string(), + label: "Stinger Cut Point (ms)".to_string(), + description: "How far into the page's animation the program changes beneath it, while the \ + page covers the frame. 0 takes the middle of the duration. Must be \ + at least about 170 ms (the take finds the page's first frame \ + first) and before the end." + .to_string(), + property_type: PropertyType::UInt, + default_value: Some(PropertyValue::UInt(0)), + mapping: PropertyMapping { + element_id: "_block".to_string(), + property_name: strom_types::stinger::WEB_STINGER_CUT_POINT_PROPERTY.to_string(), + transform: None, + }, + live: false, + persist: None, + visible_when: None, + }, + ExposedProperty { + name: strom_types::stinger::WEB_STINGER_MIX_PROPERTY.to_string(), + label: "Stinger Mix (ms)".to_string(), + description: "How long the program mixes from the old source to the new one at the cut \ + point. 0 cuts." + .to_string(), + property_type: PropertyType::UInt, + default_value: Some(PropertyValue::UInt(0)), + mapping: PropertyMapping { + element_id: "_block".to_string(), + property_name: strom_types::stinger::WEB_STINGER_MIX_PROPERTY.to_string(), + transform: None, + }, + live: false, + persist: None, + visible_when: None, + }, ], external_pads: ExternalPads { inputs: vec![], diff --git a/backend/static/vision-mixer.html b/backend/static/vision-mixer.html index c659e3fce..b229fe4cc 100644 --- a/backend/static/vision-mixer.html +++ b/backend/static/vision-mixer.html @@ -1385,7 +1385,7 @@ WS Connecting... - v2.48-take-note | 1-9,0 = PVW | Space = AUTO | X = CUT | F = FTB | M = Hide + v2.47-stinger | 1-9,0 = PVW | Space = AUTO | X = CUT | F = FTB | M = Hide @@ -1978,27 +1978,44 @@ // Analysis runs in the background; look again until it is in. A // missing file has none coming, nor does a clip whose analysis failed. + // A page is not analysed. function pollWhileAnalysing() { - if (stingerState && stingerState.clips.some(c => !c.info && !c.missing && !c.analysis_error)) { + if (stingerState && !isStingerPage() + && stingerState.clips.some(c => !c.info && !c.missing && !c.analysis_error)) { clearTimeout(fetchStingerState._t); fetchStingerState._t = setTimeout(fetchStingerState, 1000); } } + // A stinger page (an HTML Input) is the one entry of its library; its + // settings are properties of that block. + function isStingerPage() { + return !!stingerState && stingerState.source_kind === 'page'; + } + function stingerName(file) { + if (!isStingerPage()) return clipName(file); + try { return 'Page ' + (new URL(file).hostname || 'data'); } catch { return 'Page'; } + } + function renderStingers() { const s = stingerState; if (!s) return; + const page = isStingerPage(); + document.querySelectorAll('.stinger-tools .type-btn').forEach(b => { b.style.display = page ? 'none' : ''; }); + if (page && stingerSettingsOpen) toggleStingerSettings(); const clips = document.getElementById('stingerClips'); const scrollTop = clips.scrollTop; clips.innerHTML = s.clips.map(c => { const cued = c.index === s.cued_index; const cls = ['stinger-clip', cued ? 'cued' : '', cued && s.ready ? 'ready' : '', stingerOnAir === c.index ? 'on-air' : '', c.missing ? 'missing' : ''].join(' '); - const info = c.missing ? 'file missing' + const info = page + ? 'cut at ' + (c.cut_point_ms != null ? c.cut_point_ms + ' ms' : '?') + : c.missing ? 'file missing' : c.info ? (c.info.duration_ms / 1000).toFixed(1) + 's ' + c.info.width + 'x' + c.info.height : 'analysing...'; return ''; }).join(''); clips.scrollTop = scrollTop; @@ -2018,7 +2035,7 @@ } const missing = s.clips.filter(c => c.missing).length; const more = clips.scrollHeight > clips.clientHeight + 1; - document.getElementById('stingerCount').textContent = s.clips.length + document.getElementById('stingerCount').textContent = !page && s.clips.length ? s.clips.length + (s.clips.length === 1 ? ' clip' : ' clips') + (missing ? ', ' + missing + ' missing' : '') + (more ? ' \u2195' : '') : ''; @@ -2030,7 +2047,9 @@ } else if (s.running) { html = 'On air...'; } else if (s.cued_index != null) { - html = s.ready + html = page + ? 'Ready: AUTO triggers the page; settings are on HTML Input ' + escapeHtml(s.source_block_id) + : s.ready ? 'Ready: on air ' + s.preroll_ms + ' ms after AUTO' : 'Loading clip ' + (s.cued_index + 1) + '...'; if (s.last_cue_ms != null) html += ' (cued in ' + s.last_cue_ms + ' ms)'; @@ -2038,13 +2057,13 @@ const t = s.last_take; if (t) { const late = t.frames_late > 0 || t.frames_arrived < t.frames_expected; - html += '
Last: ' + escapeHtml(clipName(t.file)) + ', ' + html += '
Last: ' + escapeHtml(stingerName(t.file)) + ', ' + '' + t.frames_arrived + '/' + t.frames_expected + ' frames' + (t.frames_late ? ', ' + t.frames_late + ' late' : '') + '' + (t.worst_margin_ms != null ? ', margin ' + Math.round(t.worst_margin_ms) + ' ms' : '') + ', on air ' + Math.round(t.take_to_air_ms) + ' ms after the take'; } - if (!s.matte_supported && s.source_block_id) { + if (!s.matte_supported && s.source_block_id && !page) { html += '
Software mixer: matte stingers play as classic.'; } status.innerHTML = html; @@ -4033,7 +4052,7 @@ if (d.flow_id === FLOW_ID && d.block_id === BLOCK_ID) { if (event.type === 'StingerStarted') { stingerOnAir = d.index; - setStatus('Stinger ' + clipName(d.file) + ' (' + d.variant.replace('_', ' ') + setStatus('Stinger ' + stingerName(d.file) + ' (' + d.variant.replace('_', ' ') + (d.downgraded_from ? ', as classic' : '') + ') on air in ' + Math.round(d.take_to_air_ms) + ' ms'); } else if (event.type === 'StingerCompleted') { From c83bafb207e600f5a97533b62bbdd0618530bc57 Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Tue, 6 Oct 2026 15:11:02 -0700 Subject: [PATCH 05/15] test(stinger): page stingers against a real cefsrc Gated by STROM_REQUIRE_CEF and run on Linux only, each over STINGER_WEB_TAKES takes (default 10), with live sources on the mixer: - the program cuts 15 frames (500 ms) after the page's first frame on air: on the software mixer, on the GPU mixer, and for a 60 fps page on a 30 fps mixer, whose takes start on both halves of an output frame; - every page frame of a take reaches the mixer in time; - a page that opens on 300 ms of unchanged pixels is timed from the take, and cuts within two frames of 500 ms by its own clock. Co-Authored-By: Claude Opus 5.5 --- backend/tests/stinger_web_test.rs | 534 ++++++++++++++++++++++++++++++ 1 file changed, 534 insertions(+) create mode 100644 backend/tests/stinger_web_test.rs diff --git a/backend/tests/stinger_web_test.rs b/backend/tests/stinger_web_test.rs new file mode 100644 index 000000000..8e1d51227 --- /dev/null +++ b/backend/tests/stinger_web_test.rs @@ -0,0 +1,534 @@ +//! Page stingers against a real `cefsrc`: an HTML Input in stinger mode on +//! the vision mixer's stinger input, with live sources on the mixer's inputs. +//! +//! `cefsrc` is not in the distro GStreamer packages, so these skip wherever +//! it is missing. `STROM_REQUIRE_CEF=1` turns the skip into a failure. On +//! macOS CEF needs a Cocoa run loop on the main thread, which the test +//! harness does not have, so these run on Linux only. +//! +//! Each test takes `STINGER_WEB_TAKES` stingers (default 10), alternating +//! PGM and PVW as every take swaps them, and prints the distribution. +//! +//! CEF initialises once per process and is slow the first time, so every +//! wait polls against a generous deadline, and the tests run serially. + +pub mod common; +#[path = "common/stinger.rs"] +pub mod rig; + +use base64::Engine; +use gstreamer as gst; +use gstreamer::prelude::*; +use gstreamer_app as gst_app; +use serial_test::serial; +use std::collections::HashMap; +use std::time::{Duration, Instant}; +use strom::state::AppState; +use strom::storage::JsonFileStorage; +use strom_types::stinger::{ + STINGER_MODE_PROPERTY, WEB_STINGER_CUT_POINT_PROPERTY, WEB_STINGER_DURATION_PROPERTY, +}; +use strom_types::{Flow, FlowId, Link, PropertyValue as PV, StromEvent}; +use tempfile::NamedTempFile; + +const W: usize = 640; +const H: usize = 360; +const FRAME_NS: u64 = 33_333_333; +const CUT_MS: u64 = 500; +const VM: &str = "vm"; + +/// Budget for the page's first frame. CEF's first initialisation in a +/// process takes several seconds. +const FIRST_FRAME_TIMEOUT: Duration = Duration::from_secs(60); + +fn takes() -> usize { + std::env::var("STINGER_WEB_TAKES") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(10) +} + +fn cefsrc_available() -> bool { + gst::init().unwrap(); + let required = strom_types::env::var_opt("STROM_REQUIRE_CEF").is_some(); + if !cfg!(target_os = "linux") { + assert!( + !required, + "STROM_REQUIRE_CEF is set, but these tests run on Linux only" + ); + eprintln!("SKIP: cefsrc tests run on Linux only"); + return false; + } + if gst::ElementFactory::find("cefsrc").is_some() { + return true; + } + assert!( + !required, + "STROM_REQUIRE_CEF is set but the cefsrc element is not installed (check GST_PLUGIN_PATH)" + ); + eprintln!("SKIP: cefsrc not installed (set STROM_REQUIRE_CEF=1 to fail instead)"); + false +} + +fn data_url(html: &str) -> String { + format!( + "data:text/html;base64,{}", + base64::engine::general_purpose::STANDARD.encode(html) + ) +} + +/// Transparent at rest. For one second after every `hashchange` it covers +/// the frame in yellow from its first animation frame, with a hole in the +/// bottom-right corner that shows the program and a blue marker top left. +fn covering_page() -> String { + data_url( + "\ + \ + ", + ) +} + +/// Opens on 300 ms that change no pixel (its panel moves in from off +/// frame), then covers the frame with a hole showing the program. A marker +/// top left carries the page's own elapsed ms: R = ms >> 4, +/// G = (ms & 15) * 16, B = 255. +fn late_painting_page() -> String { + data_url( + "\ +
\ +
\ + ", + ) +} + +fn block(id: &str, definition: &str, props: &[(&str, PV)]) -> strom_types::BlockInstance { + strom_types::BlockInstance { + id: id.to_string(), + block_definition_id: definition.to_string(), + name: None, + properties: props + .iter() + .map(|(k, v)| (k.to_string(), v.clone())) + .collect(), + position: strom_types::block::Position { x: 0.0, y: 0.0 }, + runtime_data: None, + computed_external_pads: None, + } +} + +fn element(id: &str, element_type: &str, props: &[(&str, PV)]) -> strom_types::Element { + strom_types::Element { + id: id.to_string(), + element_type: element_type.to_string(), + properties: props + .iter() + .map(|(k, v)| (k.to_string(), v.clone())) + .collect(), + position: [0.0, 0.0].into(), + pad_properties: HashMap::new(), + } +} + +fn link(from: &str, to: &str) -> Link { + Link { + from: from.to_string(), + to: to.to_string(), + } +} + +struct Running { + state: AppState, + flow_id: FlowId, + tap: gst_app::AppSink, + _storage: NamedTempFile, + _blocks: NamedTempFile, +} + +/// Red on input 0 and green on input 1 (live), the page on the stinger +/// input, and every program frame in order on an RGBA appsink. +async fn start(name: &str, backend: &str, url: &str, duration_ms: u64, page_fps: u64) -> Running { + if std::env::var("STINGER_TEST_LOG").is_ok() { + let _ = tracing_subscriber::fmt() + .with_env_filter(std::env::var("STINGER_TEST_LOG").unwrap()) + .with_test_writer() + .try_init(); + } + strom::gpu::detect_gpu_capabilities(); + let mut flow = Flow::new(name); + for (id, colour) in [("red", 0xffff0000u64), ("green", 0xff00ff00u64)] { + flow.elements.push(element( + id, + "videotestsrc", + &[ + ("pattern", PV::String("solid-color".into())), + ("foreground-color", PV::UInt(colour)), + ("is-live", PV::Bool(true)), + ], + )); + flow.elements.push(element( + &format!("{id}_caps"), + "capsfilter", + &[( + "caps", + PV::String(format!("video/x-raw,width={W},height={H},framerate=30/1")), + )], + )); + flow.links + .push(link(&format!("{id}:src"), &format!("{id}_caps:sink"))); + } + flow.blocks.push(block( + "web", + strom::blocks::builtin::html_input::BLOCK_ID, + &[ + ("url", PV::String(url.to_string())), + ("width", PV::UInt(W as u64)), + ("height", PV::UInt(H as u64)), + ("framerate", PV::UInt(page_fps)), + (STINGER_MODE_PROPERTY, PV::Bool(true)), + (WEB_STINGER_DURATION_PROPERTY, PV::UInt(duration_ms)), + (WEB_STINGER_CUT_POINT_PROPERTY, PV::UInt(CUT_MS)), + ], + )); + flow.blocks.push(block( + VM, + "builtin.vision_mixer", + &[ + ("compositor_preference", PV::String(backend.into())), + ("num_inputs", PV::UInt(2)), + ("pgm_resolution", PV::String(format!("{W}x{H}"))), + ("multiview_resolution", PV::String(format!("{W}x{H}"))), + ("pgm_framerate", PV::String("30/1".into())), + ("enable_stinger", PV::Bool(true)), + ], + )); + flow.elements + .push(element("pgm_convert", "videoconvert", &[])); + flow.elements.push(element( + "pgm_tap", + "appsink", + &[ + ("caps", PV::String("video/x-raw,format=RGBA".into())), + ("sync", PV::Bool(false)), + // Every frame, in order: dropping would renumber what is counted. + ("max-buffers", PV::UInt(400)), + ("drop", PV::Bool(false)), + ], + )); + flow.links.push(link("red_caps:src", "vm:video_in_0")); + flow.links.push(link("green_caps:src", "vm:video_in_1")); + flow.links.push(link("web:video_out", "vm:stinger_in")); + flow.links.push(link("vm:pgm_out", "pgm_convert:sink")); + flow.links.push(link("pgm_convert:src", "pgm_tap:sink")); + + let storage = NamedTempFile::new().unwrap(); + let blocks = NamedTempFile::new().unwrap(); + let state = AppState::new( + JsonFileStorage::new(storage.path()), + blocks.path(), + std::env::temp_dir(), + vec![], + "all".to_string(), + vec![], + false, + false, + ); + let flow_id = flow.id; + state.upsert_flow(flow).await.expect("upsert_flow"); + state.start_flow(&flow_id).await.expect("start_flow"); + let tap = { + let pipelines = state.pipelines_read().await; + pipelines + .get(&flow_id) + .and_then(|m| m.pipeline().by_name("pgm_tap")) + .and_then(|e| e.downcast::().ok()) + .expect("pgm_tap") + }; + let running = Running { + state, + flow_id, + tap, + _storage: storage, + _blocks: blocks, + }; + // Let CEF start and the page load before the first take. + let deadline = Instant::now() + FIRST_FRAME_TIMEOUT; + loop { + let s = running + .state + .stinger_state(&running.flow_id, VM) + .await + .unwrap(); + if s.ready && s.problem.is_none() { + break; + } + assert!( + Instant::now() < deadline, + "the stinger page never became ready: {:?}", + s.problem + ); + tokio::time::sleep(Duration::from_millis(100)).await; + } + tokio::time::sleep(Duration::from_secs(2)).await; + running +} + +/// One program frame: its timestamp, the marker pixel and the hole pixel. +struct Frame { + pts: u64, + marker: [u8; 4], + hole: [u8; 4], +} + +fn rgba(sample: &gst::Sample, x: usize, y: usize) -> [u8; 4] { + let info = gstreamer_video::VideoInfo::from_caps(sample.caps().unwrap()).unwrap(); + let buffer = sample.buffer().unwrap(); + let map = buffer.map_readable().unwrap(); + let offset = info.offset()[0] + y * info.stride()[0] as usize + x * 4; + map[offset..offset + 4].try_into().unwrap() +} + +fn program(hole: [u8; 4]) -> Option { + match hole { + [r, g, b, _] if r > 200 && g < 60 && b < 60 => Some(0), + [r, g, b, _] if r < 60 && g > 200 && b < 60 => Some(1), + _ => None, + } +} + +/// Take a stinger and return the program frames from the take to the first +/// one whose source changed, then wait for the take to finish. +async fn take(r: &Running) -> (Vec, strom_types::stinger::StingerTakeReport) { + while r + .tap + .try_pull_sample(gst::ClockTime::from_mseconds(1)) + .is_some() + {} + let mut events = r.state.events().subscribe(); + let response = r + .state + .stinger_take(&r.flow_id, VM, None, None) + .await + .expect("stinger take"); + let tap = r.tap.clone(); + let frames = tokio::task::spawn_blocking(move || { + let mut frames = Vec::new(); + let mut was = None; + let deadline = Instant::now() + Duration::from_secs(10); + while Instant::now() < deadline { + let Some(sample) = tap.try_pull_sample(gst::ClockTime::from_mseconds(500)) else { + continue; + }; + let frame = Frame { + pts: sample.buffer().unwrap().pts().unwrap().nseconds(), + marker: rgba(&sample, 20, 11), + hole: rgba(&sample, 630, 350), + }; + let now = program(frame.hole); + frames.push(frame); + if let Some(now) = now { + if was.is_some_and(|w| w != now) { + break; + } + was = Some(now); + } + } + frames + }) + .await + .unwrap(); + + let deadline = Instant::now() + Duration::from_secs(10); + let report = loop { + match tokio::time::timeout_at(deadline.into(), events.recv()).await { + Ok(Ok(StromEvent::StingerCompleted { report, .. })) + if report.take_id == response.take_id => + { + break report + } + Ok(Ok(StromEvent::StingerFailed { reason, .. })) => panic!("take failed: {reason}"), + Ok(_) => continue, + Err(_) => panic!("the stinger never completed"), + } + }; + tokio::time::sleep(Duration::from_millis(300)).await; + (frames, report) +} + +fn histogram(values: &[T]) -> String { + let mut counts = std::collections::BTreeMap::new(); + for v in values { + *counts.entry(*v).or_insert(0usize) += 1; + } + counts + .iter() + .map(|(v, n)| format!("{v:?}: {n}")) + .collect::>() + .join(", ") +} + +/// The program changes on the frame the cut point names, counted from the +/// page's first frame on air: 500 ms at 30 fps is 15 frames. +async fn cuts_on_the_frame_its_cut_point_names(backend: &str, page_fps: u64) { + const EXPECTED: i64 = 15; + let r = start( + &format!("web_stinger_cut_{backend}_{page_fps}"), + backend, + &covering_page(), + 1000, + page_fps, + ) + .await; + let blue = |p: [u8; 4]| p[2] > 200 && p[0] < 60 && p[1] < 60; + let mut landed = Vec::new(); + let mut reports = Vec::new(); + for _ in 0..takes() { + let (frames, report) = take(&r).await; + let first = frames.iter().position(|f| blue(f.marker)); + let cut = frames.len().checked_sub(1); + let n = first.zip(cut).map(|(f, c)| { + let n = c as i64 - f as i64; + // Frames are pulled in order, so a gap in timestamps would mean + // a dropped frame, which would miscount. + assert_eq!( + ((frames[c].pts - frames[f].pts + FRAME_NS / 2) / FRAME_NS) as i64, + n, + "program frames were dropped" + ); + eprintln!( + " page first on air at {} ns, cut at {} ns", + frames[f].pts, frames[c].pts + ); + n + }); + landed.push(n); + reports.push(report); + } + r.state.stop_flow(&r.flow_id).await.expect("stop_flow"); + eprintln!( + "{backend}: frames from the page's first frame on air to the cut, per take: {landed:?} \ + ({})", + histogram(&landed) + ); + for rep in &reports { + eprintln!( + " take {}: on air {:.0} ms after the take, {}/{} frames, {} late, worst margin {:?} ms", + rep.take_id, + rep.take_to_air_ms, + rep.frames_arrived, + rep.frames_expected, + rep.frames_late, + rep.worst_margin_ms.map(|m| m.round()) + ); + } + assert!( + reports + .iter() + .all(|rep| rep.frames_arrived >= rep.frames_expected && rep.frames_late == 0), + "every page frame of a take must reach the mixer, in time" + ); + assert!( + landed.iter().all(|n| n.is_some_and(|n| n == EXPECTED)), + "every take must cut {EXPECTED} frames after the page's first frame on air; got {landed:?}" + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[serial] +async fn cpu_page_stinger_cuts_on_the_frame_its_cut_point_names() { + if !cefsrc_available() { + return; + } + cuts_on_the_frame_its_cut_point_names("cpu", 30).await; +} + +/// A 60 fps page on a 30 fps mixer paints at two phases half an output frame +/// apart, so about half its takes start in the second half of an output +/// frame. A page frame goes on air in the output frame it starts in, so a +/// take planned from the nearest output frame would cut a frame late on +/// those. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[serial] +async fn cpu_page_stinger_faster_than_the_mixer_cuts_on_the_frame_its_cut_point_names() { + if !cefsrc_available() { + return; + } + cuts_on_the_frame_its_cut_point_names("cpu", 60).await; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[serial] +async fn gpu_page_stinger_cuts_on_the_frame_its_cut_point_names() { + if !cefsrc_available() || !common::gl_available(rig::GL_ELEMENTS) { + return; + } + cuts_on_the_frame_its_cut_point_names("gpu", 30).await; +} + +/// A page whose animation opens without changing a pixel paints its first +/// frame 300 ms in. Anchored on that frame the cut would land 300 ms late, +/// so the take is timed from the trigger instead. The page stamps its own +/// elapsed time, so the frame the program changes on says where by the +/// page's clock the cut landed. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[serial] +async fn a_late_painting_page_is_timed_from_the_take() { + if !cefsrc_available() { + return; + } + const TOLERANCE_MS: i64 = 67; + let r = start("web_stinger_late", "cpu", &late_painting_page(), 1300, 30).await; + let page_ms = |p: [u8; 4]| { + let [red, g, b, _] = p; + (b == 255 && g % 16 == 0).then(|| ((red as i64) << 4) + (g as i64) / 16) + }; + let mut landed = Vec::new(); + for _ in 0..takes() { + let (frames, _) = take(&r).await; + landed.push(frames.last().and_then(|f| page_ms(f.marker))); + } + r.state.stop_flow(&r.flow_id).await.expect("stop_flow"); + let off: Vec> = landed + .iter() + .map(|l| l.map(|ms| ms - CUT_MS as i64)) + .collect(); + eprintln!( + "late page: cut landed at page ms {landed:?}; off by {off:?} ms ({})", + histogram(&off) + ); + assert!( + off.iter() + .all(|o| o.is_some_and(|o| o.abs() <= TOLERANCE_MS)), + "every take must cut within {TOLERANCE_MS} ms of {CUT_MS} ms by the page's clock; \ + off by {off:?}" + ); +} From 960288e9aceaf27d800480735f48dcbc3232aae5 Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Tue, 6 Oct 2026 15:58:58 -0700 Subject: [PATCH 06/15] fix(stinger): finish a take whose request is dropped A take claims the mixer, and only its own ending releases the claim. A page take waits for the page between the two, so a request dropped then (the client went away, a proxy timed out) left the mixer claimed: every later stinger and every cut was refused until the flow restarted, with the graphic pad up. The take now runs in a task of its own that the request awaits. Co-Authored-By: Claude Opus 5.5 --- backend/src/state/stinger.rs | 23 ++++++++++++++++++++ backend/tests/stinger_web_test.rs | 36 +++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+) diff --git a/backend/src/state/stinger.rs b/backend/src/state/stinger.rs index d6dfdaa70..1c6c081da 100644 --- a/backend/src/state/stinger.rs +++ b/backend/src/state/stinger.rs @@ -976,12 +976,35 @@ impl AppState { } /// Take a stinger from PGM to PVW, playing clip `index` or the cued one. + /// + /// The take runs in a task of its own: once it has claimed the mixer it + /// must run to the end that releases the claim, even if the caller stops + /// waiting (a request whose client went away). pub async fn stinger_take( &self, flow_id: &FlowId, block: &str, index: Option, expected_file: Option<&str>, + ) -> Result { + let state = self.clone(); + let (flow_id, block) = (*flow_id, block.to_string()); + let expected_file = expected_file.map(str::to_string); + tokio::spawn(async move { + state + .stinger_take_now(&flow_id, &block, index, expected_file.as_deref()) + .await + }) + .await + .map_err(|e| err(format!("the take did not finish: {e}")))? + } + + async fn stinger_take_now( + &self, + flow_id: &FlowId, + block: &str, + index: Option, + expected_file: Option<&str>, ) -> Result { let requested = Instant::now(); let source = self.stinger_source(flow_id, block).await.map_err(err)?; diff --git a/backend/tests/stinger_web_test.rs b/backend/tests/stinger_web_test.rs index 8e1d51227..fdaa7cf11 100644 --- a/backend/tests/stinger_web_test.rs +++ b/backend/tests/stinger_web_test.rs @@ -494,6 +494,42 @@ async fn gpu_page_stinger_cuts_on_the_frame_its_cut_point_names() { cuts_on_the_frame_its_cut_point_names("gpu", 30).await; } +/// A take whose request is dropped while it waits for the page (the client +/// went away) still finishes and frees the mixer: the next take runs, and so +/// does an ordinary cut. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[serial] +async fn a_dropped_take_request_still_frees_the_mixer() { + if !cefsrc_available() { + return; + } + let r = start("web_stinger_dropped", "cpu", &covering_page(), 1000, 30).await; + let mut events = r.state.events().subscribe(); + let dropped = tokio::time::timeout( + Duration::from_millis(20), + r.state.stinger_take(&r.flow_id, VM, None, None), + ) + .await; + assert!( + dropped.is_err(), + "the take must still be waiting for the page at 20 ms" + ); + let deadline = Instant::now() + Duration::from_secs(10); + loop { + match tokio::time::timeout_at(deadline.into(), events.recv()).await { + Ok(Ok(StromEvent::StingerCompleted { .. })) => break, + Ok(Ok(StromEvent::StingerFailed { reason, .. })) => panic!("take failed: {reason}"), + Ok(_) => continue, + Err(_) => panic!("the dropped take never finished"), + } + } + let (frames, _) = take(&r).await; + assert!(!frames.is_empty(), "the next take must run"); + let s = r.state.stinger_state(&r.flow_id, VM).await.unwrap(); + assert!(!s.running); + r.state.stop_flow(&r.flow_id).await.expect("stop_flow"); +} + /// A page whose animation opens without changing a pixel paints its first /// frame 300 ms in. Anchored on that frame the cut would land 300 ms late, /// so the take is timed from the trigger instead. The page stamps its own From b1e5b50a75e39dbc4ec3bf441aa8749e2a84b462 Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Tue, 6 Oct 2026 15:59:14 -0700 Subject: [PATCH 07/15] fix(stinger): guard a stinger page's URL and first frame - A page URL with a fragment of its own is refused: the take replaces the fragment, which moves a page that routes by it off its route. - On a gstcefsrc that sends only paints, the first buffer after the take is the page's start. It was spent as the baseline instead, which put every cut a frame late after a 100 ms wait for a buffer that never comes. - A page that paints while at rest is noticed before the take and warned about: its first frame after the take can be a paint of its rest state, which puts the cut a frame or two early. The block's help says a stinger page must stop drawing at rest. Co-Authored-By: Claude Opus 5.5 --- backend/src/blocks/builtin/html_input.rs | 5 +- backend/src/state/stinger/web.rs | 20 ++- backend/src/stinger/web.rs | 161 +++++++++++++++++++---- 3 files changed, 152 insertions(+), 34 deletions(-) diff --git a/backend/src/blocks/builtin/html_input.rs b/backend/src/blocks/builtin/html_input.rs index 8ea3b0ff3..90b8c93f6 100644 --- a/backend/src/blocks/builtin/html_input.rs +++ b/backend/src/blocks/builtin/html_input.rs @@ -911,8 +911,9 @@ fn html_input_definition() -> BlockDefinition { label: "Stinger Page".to_string(), description: "Play this page as a Vision Mixer stinger: wire video_out to the mixer's stinger \ input, and a take triggers the page by setting its URL fragment to \ - #strom-take- (listen for hashchange). The page must be \ - transparent at rest and change something visible on the first \ + #strom-take- (listen for hashchange), so its URL cannot \ + have a fragment of its own. The page must be transparent and \ + stop drawing at rest, and change something visible on the first \ frame of its animation; the cut is timed from that frame. Plays as \ a classic stinger with premultiplied alpha." .to_string(), diff --git a/backend/src/state/stinger/web.rs b/backend/src/state/stinger/web.rs index 5d6a5aef4..9fa44798e 100644 --- a/backend/src/state/stinger/web.rs +++ b/backend/src/state/stinger/web.rs @@ -20,7 +20,7 @@ use super::{err, take_on_grid, AppState, PageContext, Started}; use crate::blocks::builtin::html_input; use crate::gst::pipeline::PipelineError; use crate::stinger::web::{ - take_fragment, web_first_output_frame, WebAnchor, WebStart, WebStingerSettings, + check_page_url, take_fragment, web_first_output_frame, WebAnchor, WebStart, WebStingerSettings, PAGE_FIRST_FRAME_DELAY_FIXED_RATE, PAGE_FIRST_FRAME_DELAY_PAINTED, PAGE_FIRST_FRAME_GRACE, VARIABLE_RATE_PROPERTY, }; @@ -94,7 +94,8 @@ impl PageContext { /// The page as a library entry, for the operator panel. fn describe(&self, grid: FrameGrid) -> (StingerClip, Option) { let settings = self.settings(); - let plan = settings.plan(grid.frame_ns()); + let plan = + check_page_url(&self.configured_url()).and_then(|()| settings.plan(grid.frame_ns())); let cut = plan.as_ref().ok().and_then(|p| p.cut_point_ms); let clip = StingerClip { index: 0, @@ -211,6 +212,7 @@ impl AppState { .ok_or_else(|| (format!("HTML Input {} is not running", source), true))?; (cefsrc, grid) }; + check_page_url(&page.configured_url()).map_err(|e| (e, false))?; let settings = page.settings(); let plan = settings.plan(grid.frame_ns()).map_err(|e| (e, false))?; let duration_ns = plan.duration_ms * 1_000_000; @@ -281,7 +283,19 @@ impl AppState { let Some(anchor) = WebAnchor::watch(&pad, delay) else { return Err(abort("could not watch the stinger page's output".to_string()).await); }; - anchor.ready(Duration::from_millis(100)).await; + // A paint-only gstcefsrc sends nothing while the page rests, so + // there is nothing to wait for. + if fixed_rate { + anchor.ready(Duration::from_millis(100)).await; + } + if anchor.paints_at_rest() { + warn!( + "Stinger page {}: the page paints while at rest, so its first frame after the take \ + may be a paint of its rest state and the cut may land a frame or two early. A \ + stinger page should stop drawing until the take", + source + ); + } // A new fragment is a same-document navigation: the loaded page gets // `hashchange` and starts its animation, rather than reloading. diff --git a/backend/src/stinger/web.rs b/backend/src/stinger/web.rs index 122cec594..2654b0dd3 100644 --- a/backend/src/stinger/web.rs +++ b/backend/src/stinger/web.rs @@ -8,7 +8,7 @@ //! plans the take from there ([`WebAnchor`], [`web_stinger_start`]). use std::collections::HashMap; -use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicU32, AtomicU64, AtomicUsize, Ordering}; use std::sync::Arc; use std::time::Duration; @@ -28,11 +28,9 @@ pub const PAGE_FIRST_FRAME_GRACE: Duration = Duration::from_millis(100); /// Delay from a take to the timestamp a page's first animation frame would /// carry, used when the page paints nothing prompt to time from. Measured on -/// cefsrc's own output: a page that opens on unchanged pixels cut 91-93 ms -/// late by its own clock with 120 ms on the fixed-rate production gstcefsrc -/// (Linux, software CEF), so its animation starts about 28 ms after the -/// take. A gstcefsrc that emits frames as Chromium paints was measured at -/// about 20 ms on the earlier web stinger branch. +/// cefsrc's own output: about 28 ms on the fixed-rate production gstcefsrc +/// (Linux, software CEF). About 20 ms on one that emits frames as Chromium +/// paints, not measured on this probe. pub const PAGE_FIRST_FRAME_DELAY_PAINTED: Duration = Duration::from_millis(20); pub const PAGE_FIRST_FRAME_DELAY_FIXED_RATE: Duration = Duration::from_millis(30); @@ -45,6 +43,19 @@ pub fn take_fragment(token: u64) -> String { format!("strom-take-{token}") } +/// A stinger page's URL cannot carry a fragment of its own: a take replaces +/// it, which would move a page that routes by its fragment off its route. +pub fn check_page_url(url: &str) -> Result<(), String> { + match url.split_once('#') { + Some((_, fragment)) if !fragment.is_empty() => Err(format!( + "a stinger page's URL cannot have a #fragment ('#{}'): a take sets the fragment \ + to trigger the page", + fragment + )), + _ => Ok(()), + } +} + /// A page stinger's settings, from its HTML Input block. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct WebStingerSettings { @@ -190,14 +201,16 @@ pub fn web_first_output_frame(first_frame_ns: u64, page_frame_ns: u64, grid: Fra /// Watches a page's output for its first new frame after a take. /// -/// Wait for [`WebAnchor::ready`] before changing the URL, then call -/// [`WebAnchor::taken`]. Dropping it removes the probe. +/// On a fixed-rate gstcefsrc, wait for [`WebAnchor::ready`] before changing +/// the URL, then call [`WebAnchor::taken`]. Dropping it removes the probe. pub struct WebAnchor { /// Weak, so a take in flight never keeps a stopped flow's pipeline alive. pad: gst::glib::WeakRef, probe: Option, - /// Whether a baseline buffer has passed, so the next can be judged new. - baseline: Arc, + /// Buffers seen before the take. + before_take: Arc, + /// Fresh paints seen before the take, after the first buffer. + idle_paints: Arc, /// Running time at which the take changed the URL; `u64::MAX` before. taken_at_ns: Arc, /// Newest timestamp seen on the output, repeats included. @@ -213,23 +226,25 @@ impl WebAnchor { /// running time it makes them at, which every element down to the mixer /// keeps. pub fn watch(pad: &gst::Pad, delay: Duration) -> Option { - let baseline = Arc::new(AtomicBool::new(false)); + let before_take = Arc::new(AtomicU32::new(0)); + let idle_paints = Arc::new(AtomicU32::new(0)); let taken_at_ns = Arc::new(AtomicU64::new(u64::MAX)); let output_pts = Arc::new(AtomicU64::new(u64::MAX)); let first_pts = Arc::new(AtomicU64::new(u64::MAX)); let last_memory = AtomicUsize::new(0); - let (p_baseline, p_taken, p_output, p_first) = ( - Arc::clone(&baseline), + let (p_before, p_idle, p_taken, p_output, p_first) = ( + Arc::clone(&before_take), + Arc::clone(&idle_paints), Arc::clone(&taken_at_ns), Arc::clone(&output_pts), Arc::clone(&first_pts), ); // A per-buffer probe for one take, removed once the take is planned: - // a few atomic loads, stores and compares per buffer. The first - // buffer only sets the baseline. After the take only new content - // counts: a GAP-flagged repeat, or a fixed-rate gstcefsrc re-sending - // its current frame, shares that frame's memory; a fresh paint is a - // new allocation. + // a few atomic loads, stores and compares per buffer. Only new + // content counts: a GAP-flagged repeat, or a fixed-rate gstcefsrc + // re-sending its current frame, shares the previous buffer's memory; + // a fresh paint is a new allocation. With no buffer before it, as + // from a gstcefsrc that sends only paints, a buffer is new. let probe = pad.add_probe(gst::PadProbeType::BUFFER, move |_, info| { let Some(buffer) = info.buffer() else { return gst::PadProbeReturn::Ok; @@ -243,18 +258,16 @@ impl WebAnchor { let Some(pts) = buffer.pts().map(|t| t.nseconds()) else { return gst::PadProbeReturn::Ok; }; - if !p_baseline.swap(true, Ordering::Relaxed) { - return gst::PadProbeReturn::Ok; - } + let fresh = memory != previous && !buffer.flags().contains(gst::BufferFlags::GAP); let taken_at = p_taken.load(Ordering::Relaxed); if taken_at == u64::MAX { + if p_before.fetch_add(1, Ordering::Relaxed) > 0 && fresh { + p_idle.fetch_add(1, Ordering::Relaxed); + } return gst::PadProbeReturn::Ok; } p_output.store(pts, Ordering::Relaxed); - if pts >= taken_at - && memory != previous - && !buffer.flags().contains(gst::BufferFlags::GAP) - { + if pts >= taken_at && fresh { let _ = p_first.compare_exchange(u64::MAX, pts, Ordering::Relaxed, Ordering::Relaxed); } @@ -263,7 +276,8 @@ impl WebAnchor { Some(Self { pad: pad.downgrade(), probe: Some(probe), - baseline, + before_take, + idle_paints, taken_at_ns, output_pts, first_pts, @@ -271,15 +285,23 @@ impl WebAnchor { }) } - /// Wait, up to `limit`, for the baseline buffer, so a page frame painted - /// just after the take is never mistaken for it. + /// Wait, up to `limit`, for two buffers from a fixed-rate gstcefsrc: the + /// first, so a repeat of it after the take is not taken for a paint, and + /// a second, to tell whether the page paints while at rest. pub async fn ready(&self, limit: Duration) { let until = std::time::Instant::now() + limit; - while !self.baseline.load(Ordering::Relaxed) && std::time::Instant::now() < until { + while self.before_take.load(Ordering::Relaxed) < 2 && std::time::Instant::now() < until { tokio::time::sleep(Duration::from_millis(2)).await; } } + /// Whether the page painted new content while at rest, before the take. + /// Such a page's first frame after the take may be a paint of its rest + /// state rather than of its animation. + pub fn paints_at_rest(&self) -> bool { + self.idle_paints.load(Ordering::Relaxed) > 0 + } + /// Record that the take changed the page's URL at running time `now_ns`. pub fn taken(&self, now_ns: u64) { self.taken_at_ns.store(now_ns, Ordering::Relaxed); @@ -482,6 +504,87 @@ mod tests { assert_eq!(plan.mix_ms, 300); } + /// A src pad linked to a sink that takes anything, to drive the probe. + fn pads() -> (gst::Pad, gst::Pad) { + gst::init().unwrap(); + let src = gst::Pad::builder(gst::PadDirection::Src).build(); + let sink = gst::Pad::builder(gst::PadDirection::Sink) + .chain_function(|_, _, _| Ok(gst::FlowSuccess::Ok)) + .build(); + src.link(&sink).unwrap(); + sink.set_active(true).unwrap(); + src.set_active(true).unwrap(); + (src, sink) + } + + fn buffer(pts_ms: u64) -> gst::Buffer { + let mut b = gst::Buffer::with_size(16).unwrap(); + b.get_mut() + .unwrap() + .set_pts(gst::ClockTime::from_mseconds(pts_ms)); + b + } + + /// The same frame again, as a fixed-rate gstcefsrc re-sends it. + fn repeat(of: &gst::Buffer, pts_ms: u64) -> gst::Buffer { + let mut b = of.copy(); + b.get_mut() + .unwrap() + .set_pts(gst::ClockTime::from_mseconds(pts_ms)); + b + } + + #[test] + fn a_repeat_after_the_take_is_not_the_first_frame() { + let (src, _sink) = pads(); + let anchor = WebAnchor::watch(&src, PAGE_FIRST_FRAME_DELAY_FIXED_RATE).unwrap(); + let rest = buffer(0); + let _ = src.push(rest.clone()); + let _ = src.push(repeat(&rest, 33)); + assert!(!anchor.paints_at_rest()); + anchor.taken(50 * MS); + let _ = src.push(repeat(&rest, 66)); + assert_eq!(anchor.first_frame_ns(), None); + let paint = buffer(100); + let _ = src.push(paint.clone()); + assert_eq!(anchor.first_frame_ns(), Some(100 * MS)); + drop((rest, paint)); + } + + #[test] + fn a_paint_only_page_starts_on_its_first_buffer() { + // A gstcefsrc that sends only paints sends nothing while the page + // rests, so the first buffer after the take is the page's start. + let (src, _sink) = pads(); + let anchor = WebAnchor::watch(&src, PAGE_FIRST_FRAME_DELAY_PAINTED).unwrap(); + anchor.taken(50 * MS); + let _ = src.push(buffer(70)); + assert_eq!(anchor.first_frame_ns(), Some(70 * MS)); + } + + #[test] + fn a_page_painting_at_rest_is_noticed() { + let (src, _sink) = pads(); + let anchor = WebAnchor::watch(&src, PAGE_FIRST_FRAME_DELAY_FIXED_RATE).unwrap(); + // Kept alive, as gstcefsrc keeps its current frame while it makes + // the next: a freed frame's memory could be handed out again. + let first = buffer(0); + let _ = src.push(first.clone()); + assert!(!anchor.paints_at_rest(), "the first buffer cannot tell"); + let second = buffer(33); + let _ = src.push(second.clone()); + assert!(anchor.paints_at_rest()); + drop((first, second)); + } + + #[test] + fn a_page_url_with_a_fragment_is_refused() { + let err = check_page_url("https://example.com/graphics/#/stinger").unwrap_err(); + assert!(err.contains("#/stinger"), "{err}"); + assert!(check_page_url("https://example.com/graphics/").is_ok()); + assert!(check_page_url("https://example.com/graphics/#").is_ok()); + } + #[test] fn settings_read_from_the_block() { let props: HashMap = [ From bdf5507385da35a71686eb353db79d692fedf8a8 Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Tue, 6 Oct 2026 16:47:23 -0700 Subject: [PATCH 08/15] fix(stinger): wait for one page frame; check paints at rest after a take - A take waits for one frame from a fixed-rate gstcefsrc again, not two, which cost about a page frame on every take. - "A buffer with nothing before it is new" applies to a paint-only gstcefsrc only. On a fixed-rate one that sent nothing until the take, its first buffer is a repeat of the rest frame, and counting it as the page's start put the cut a frame or two early. - Whether a page paints at rest is judged after the take instead. The probe stays on and counts the page's new frames from a page frame past its duration until the earliest the next take could trigger it (the mixer's latency past the take's finish point). Two or more warn; one is the page clearing itself as it ends. Co-Authored-By: Claude Opus 5.5 --- backend/src/gst/pipeline/effects/stinger.rs | 8 ++ backend/src/state/stinger/web.rs | 56 +++++--- backend/src/stinger/web.rs | 140 ++++++++++++++------ 3 files changed, 149 insertions(+), 55 deletions(-) diff --git a/backend/src/gst/pipeline/effects/stinger.rs b/backend/src/gst/pipeline/effects/stinger.rs index fba0d7355..e6fd1456b 100644 --- a/backend/src/gst/pipeline/effects/stinger.rs +++ b/backend/src/gst/pipeline/effects/stinger.rs @@ -299,6 +299,14 @@ impl PipelineManager { crate::stinger::FrameGrid::new(fps.numer(), fps.denom()) } + /// How far behind running time the mixer's output runs: what a latency + /// query on its output answers. + pub fn mixer_latency_ns(&self, block_instance_id: &str) -> Option { + let mut query = gst::query::Latency::new(); + let pad = self.dist_mixer(block_instance_id).ok()?.static_pad("src")?; + pad.query(&mut query).then(|| query.result().1.nseconds()) + } + /// The flow's running time now. pub fn running_time_ns(&self) -> Option { self.pipeline.current_running_time().map(|t| t.nseconds()) diff --git a/backend/src/state/stinger/web.rs b/backend/src/state/stinger/web.rs index 9fa44798e..3b8140dd0 100644 --- a/backend/src/state/stinger/web.rs +++ b/backend/src/state/stinger/web.rs @@ -31,6 +31,10 @@ use crate::stinger::FrameGrid; /// that paints nothing leaves the output still. const SILENT_PAGE_LIMIT: Duration = Duration::from_millis(400); +/// How long past the rest window the check waits for its last frames to +/// arrive. +const REST_CHECK_SLACK: Duration = Duration::from_millis(50); + /// A 30 fps grid, to judge a page's settings while its flow is stopped. const NOMINAL_GRID: FrameGrid = FrameGrid { num: 30, den: 1 }; @@ -280,7 +284,7 @@ impl AppState { } else { PAGE_FIRST_FRAME_DELAY_PAINTED }; - let Some(anchor) = WebAnchor::watch(&pad, delay) else { + let Some(anchor) = WebAnchor::watch(&pad, delay, !fixed_rate) else { return Err(abort("could not watch the stinger page's output".to_string()).await); }; // A paint-only gstcefsrc sends nothing while the page rests, so @@ -288,15 +292,6 @@ impl AppState { if fixed_rate { anchor.ready(Duration::from_millis(100)).await; } - if anchor.paints_at_rest() { - warn!( - "Stinger page {}: the page paints while at rest, so its first frame after the take \ - may be a paint of its rest state and the cut may land a frame or two early. A \ - stinger page should stop drawing until the take", - source - ); - } - // A new fragment is a same-document navigation: the loaded page gets // `hashchange` and starts its animation, rather than reloading. let shown: Option = cefsrc.property(html_input::URL_PROPERTY); @@ -326,7 +321,6 @@ impl AppState { } }; let first = anchor.first_frame_ns(); - drop(anchor); let after_take = |ns: u64| ns.saturating_sub(taken_rt) / 1_000_000; if prompt { debug!( @@ -371,13 +365,16 @@ impl AppState { let counted_from = cefsrc .current_running_time() .map_or(take.start, |t| t.nseconds().max(take.start)); - let programmed = { + let (programmed, mixer_latency_ns) = { let pipelines = self.inner.pipelines.read().await; match pipelines.get(flow_id) { - Some(manager) => manager - .program_stinger(block, &take) - .map_err(|e| e.error.to_string()), - None => Err("the flow is not running".to_string()), + Some(manager) => ( + manager + .program_stinger(block, &take) + .map_err(|e| e.error.to_string()), + manager.mixer_latency_ns(block).unwrap_or(0), + ), + None => (Err("the flow is not running".to_string()), 0), } }; let watch = match programmed { @@ -385,6 +382,33 @@ impl AppState { Err(e) => return Err(abort(e).await), }; + // A page that paints at rest makes its rest paints look like its + // animation's start, which puts the cut early. Past its duration the + // page should be at rest, after at most one paint that clears it. + // Count what it paints from a page frame past the end until the + // earliest the next take could trigger it: the take finishes once the + // mixer's output is two frames past the end, which is the mixer's + // latency later in running time. + let rest_from = take.end + page_frame_ns; + let rest_until = take.end + 2 * take.frame_ns + mixer_latency_ns; + anchor.expect_rest(rest_from, rest_until); + let wait = Duration::from_nanos(rest_until.saturating_sub(taken_rt)) + .saturating_add(REST_CHECK_SLACK) + .saturating_sub(taken_at.elapsed()); + let source_id = source.clone(); + tokio::spawn(async move { + tokio::time::sleep(wait).await; + if anchor.paints_at_rest() { + warn!( + "Stinger page {}: the page kept drawing after its stinger duration, so on a \ + take its rest paints can look like its animation starting and the cut may land \ + a frame or two early. A stinger page should stop drawing at rest, within its \ + Stinger Duration", + source_id + ); + } + }); + let take_to_air_ms = (taken_at - requested).as_secs_f64() * 1000.0 + (start as f64 - taken_rt as f64) / 1e6; let frames_expected = page_frames_between(anchor_ns, page_frame_ns, counted_from, take.end); diff --git a/backend/src/stinger/web.rs b/backend/src/stinger/web.rs index 2654b0dd3..e1dc689b3 100644 --- a/backend/src/stinger/web.rs +++ b/backend/src/stinger/web.rs @@ -199,7 +199,8 @@ pub fn web_first_output_frame(first_frame_ns: u64, page_frame_ns: u64, grid: Fra grid.pts(n) } -/// Watches a page's output for its first new frame after a take. +/// Watches a page's output for its first new frame after a take, and for +/// paints once the take's page has gone back to rest. /// /// On a fixed-rate gstcefsrc, wait for [`WebAnchor::ready`] before changing /// the URL, then call [`WebAnchor::taken`]. Dropping it removes the probe. @@ -209,14 +210,19 @@ pub struct WebAnchor { probe: Option, /// Buffers seen before the take. before_take: Arc, - /// Fresh paints seen before the take, after the first buffer. - idle_paints: Arc, /// Running time at which the take changed the URL; `u64::MAX` before. taken_at_ns: Arc, /// Newest timestamp seen on the output, repeats included. output_pts: Arc, /// Timestamp of the first frame of new content after the take. first_pts: Arc, + /// From this timestamp the page should be at rest; `u64::MAX` before + /// it is known. + rest_from: Arc, + /// The window ends here, before anything the next take paints. + rest_until: Arc, + /// Fresh paints stamped in `[rest_from, rest_until)`. + rest_paints: Arc, /// Assumed take-to-paint delay when the page paints nothing promptly. pub delay: Duration, } @@ -224,27 +230,35 @@ pub struct WebAnchor { impl WebAnchor { /// Watch `pad`, a `cefsrc` src pad. cefsrc stamps its frames with the /// running time it makes them at, which every element down to the mixer - /// keeps. - pub fn watch(pad: &gst::Pad, delay: Duration) -> Option { + /// keeps. `paint_only` is a gstcefsrc that sends a buffer only when the + /// page paints. + pub fn watch(pad: &gst::Pad, delay: Duration, paint_only: bool) -> Option { let before_take = Arc::new(AtomicU32::new(0)); - let idle_paints = Arc::new(AtomicU32::new(0)); let taken_at_ns = Arc::new(AtomicU64::new(u64::MAX)); let output_pts = Arc::new(AtomicU64::new(u64::MAX)); let first_pts = Arc::new(AtomicU64::new(u64::MAX)); + let rest_from = Arc::new(AtomicU64::new(u64::MAX)); + let rest_until = Arc::new(AtomicU64::new(u64::MAX)); + let rest_paints = Arc::new(AtomicU32::new(0)); let last_memory = AtomicUsize::new(0); - let (p_before, p_idle, p_taken, p_output, p_first) = ( + let (p_before, p_taken, p_output, p_first) = ( Arc::clone(&before_take), - Arc::clone(&idle_paints), Arc::clone(&taken_at_ns), Arc::clone(&output_pts), Arc::clone(&first_pts), ); - // A per-buffer probe for one take, removed once the take is planned: - // a few atomic loads, stores and compares per buffer. Only new - // content counts: a GAP-flagged repeat, or a fixed-rate gstcefsrc - // re-sending its current frame, shares the previous buffer's memory; - // a fresh paint is a new allocation. With no buffer before it, as - // from a gstcefsrc that sends only paints, a buffer is new. + let (p_rest_from, p_rest_until, p_rest) = ( + Arc::clone(&rest_from), + Arc::clone(&rest_until), + Arc::clone(&rest_paints), + ); + // A per-buffer probe for the length of one take: a few atomic loads, + // stores and compares per buffer. Only new content counts: a + // GAP-flagged repeat, or a fixed-rate gstcefsrc re-sending its + // current frame, shares the previous buffer's memory; a fresh paint + // is a new allocation. A fixed-rate gstcefsrc's first buffer is only + // the baseline, whenever it comes; a paint-only one sends nothing at + // rest, so its first buffer is new. let probe = pad.add_probe(gst::PadProbeType::BUFFER, move |_, info| { let Some(buffer) = info.buffer() else { return gst::PadProbeReturn::Ok; @@ -258,12 +272,12 @@ impl WebAnchor { let Some(pts) = buffer.pts().map(|t| t.nseconds()) else { return gst::PadProbeReturn::Ok; }; - let fresh = memory != previous && !buffer.flags().contains(gst::BufferFlags::GAP); + let fresh = memory != previous + && (previous != 0 || paint_only) + && !buffer.flags().contains(gst::BufferFlags::GAP); let taken_at = p_taken.load(Ordering::Relaxed); if taken_at == u64::MAX { - if p_before.fetch_add(1, Ordering::Relaxed) > 0 && fresh { - p_idle.fetch_add(1, Ordering::Relaxed); - } + p_before.fetch_add(1, Ordering::Relaxed); return gst::PadProbeReturn::Ok; } p_output.store(pts, Ordering::Relaxed); @@ -271,35 +285,50 @@ impl WebAnchor { let _ = p_first.compare_exchange(u64::MAX, pts, Ordering::Relaxed, Ordering::Relaxed); } + if fresh + && pts >= p_rest_from.load(Ordering::Relaxed) + && pts < p_rest_until.load(Ordering::Relaxed) + { + p_rest.fetch_add(1, Ordering::Relaxed); + } gst::PadProbeReturn::Ok })?; Some(Self { pad: pad.downgrade(), probe: Some(probe), before_take, - idle_paints, taken_at_ns, output_pts, first_pts, + rest_from, + rest_until, + rest_paints, delay, }) } - /// Wait, up to `limit`, for two buffers from a fixed-rate gstcefsrc: the - /// first, so a repeat of it after the take is not taken for a paint, and - /// a second, to tell whether the page paints while at rest. + /// Wait, up to `limit`, for a fixed-rate gstcefsrc's first buffer, so a + /// repeat of it after the take is not taken for a paint. pub async fn ready(&self, limit: Duration) { let until = std::time::Instant::now() + limit; - while self.before_take.load(Ordering::Relaxed) < 2 && std::time::Instant::now() < until { + while self.before_take.load(Ordering::Relaxed) == 0 && std::time::Instant::now() < until { tokio::time::sleep(Duration::from_millis(2)).await; } } - /// Whether the page painted new content while at rest, before the take. - /// Such a page's first frame after the take may be a paint of its rest - /// state rather than of its animation. + /// Count paints stamped in `[from_ns, until_ns)`, when the page should + /// be at rest again. An empty window counts nothing. + pub fn expect_rest(&self, from_ns: u64, until_ns: u64) { + self.rest_until.store(until_ns, Ordering::Relaxed); + self.rest_from.store(from_ns, Ordering::Relaxed); + } + + /// Whether the page kept painting in the [`Self::expect_rest`] window: + /// two new frames or more. A page that keeps painting at rest makes its + /// own rest paints look like the start of the next take's animation. A + /// single paint is a page clearing itself as it ends. pub fn paints_at_rest(&self) -> bool { - self.idle_paints.load(Ordering::Relaxed) > 0 + self.rest_paints.load(Ordering::Relaxed) > 1 } /// Record that the take changed the page's URL at running time `now_ns`. @@ -537,11 +566,10 @@ mod tests { #[test] fn a_repeat_after_the_take_is_not_the_first_frame() { let (src, _sink) = pads(); - let anchor = WebAnchor::watch(&src, PAGE_FIRST_FRAME_DELAY_FIXED_RATE).unwrap(); + let anchor = WebAnchor::watch(&src, PAGE_FIRST_FRAME_DELAY_FIXED_RATE, false).unwrap(); let rest = buffer(0); let _ = src.push(rest.clone()); let _ = src.push(repeat(&rest, 33)); - assert!(!anchor.paints_at_rest()); anchor.taken(50 * MS); let _ = src.push(repeat(&rest, 66)); assert_eq!(anchor.first_frame_ns(), None); @@ -551,30 +579,64 @@ mod tests { drop((rest, paint)); } + #[test] + fn a_fixed_rate_page_silent_until_the_take_starts_on_its_first_paint() { + // A fixed-rate gstcefsrc that sent nothing before the take resumes + // with a repeat of its rest frame: that is the baseline, not a paint. + let (src, _sink) = pads(); + let anchor = WebAnchor::watch(&src, PAGE_FIRST_FRAME_DELAY_FIXED_RATE, false).unwrap(); + anchor.taken(50 * MS); + let rest = buffer(60); + let _ = src.push(rest.clone()); + assert_eq!(anchor.first_frame_ns(), None); + let paint = buffer(93); + let _ = src.push(paint.clone()); + assert_eq!(anchor.first_frame_ns(), Some(93 * MS)); + drop((rest, paint)); + } + #[test] fn a_paint_only_page_starts_on_its_first_buffer() { // A gstcefsrc that sends only paints sends nothing while the page // rests, so the first buffer after the take is the page's start. let (src, _sink) = pads(); - let anchor = WebAnchor::watch(&src, PAGE_FIRST_FRAME_DELAY_PAINTED).unwrap(); + let anchor = WebAnchor::watch(&src, PAGE_FIRST_FRAME_DELAY_PAINTED, true).unwrap(); anchor.taken(50 * MS); let _ = src.push(buffer(70)); assert_eq!(anchor.first_frame_ns(), Some(70 * MS)); } #[test] - fn a_page_painting_at_rest_is_noticed() { - let (src, _sink) = pads(); - let anchor = WebAnchor::watch(&src, PAGE_FIRST_FRAME_DELAY_FIXED_RATE).unwrap(); + fn a_page_painting_after_its_take_is_noticed() { // Kept alive, as gstcefsrc keeps its current frame while it makes // the next: a freed frame's memory could be handed out again. - let first = buffer(0); - let _ = src.push(first.clone()); - assert!(!anchor.paints_at_rest(), "the first buffer cannot tell"); - let second = buffer(33); - let _ = src.push(second.clone()); + let mut kept = Vec::new(); + let (src, _sink) = pads(); + let anchor = WebAnchor::watch(&src, PAGE_FIRST_FRAME_DELAY_FIXED_RATE, false).unwrap(); + kept.push(buffer(0)); + let _ = src.push(kept[0].clone()); + anchor.taken(50 * MS); + anchor.expect_rest(1_100 * MS, 1_300 * MS); + // Painting during the animation is expected. + kept.push(buffer(100)); + let _ = src.push(kept[1].clone()); + kept.push(buffer(1_000)); + let _ = src.push(kept[2].clone()); + // Back at rest: a closing paint, then repeats. + kept.push(buffer(1_133)); + let _ = src.push(kept[3].clone()); + let _ = src.push(repeat(&kept[3], 1_166)); + assert!( + !anchor.paints_at_rest(), + "one closing paint is not painting at rest" + ); + // The next take's paints are past the window. + kept.push(buffer(1_300)); + let _ = src.push(kept[4].clone()); + assert!(!anchor.paints_at_rest()); + kept.push(buffer(1_200)); + let _ = src.push(kept[5].clone()); assert!(anchor.paints_at_rest()); - drop((first, second)); } #[test] From 0a421e803bf07d73292b147676393beef4f76dfb Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Tue, 6 Oct 2026 17:15:10 -0700 Subject: [PATCH 09/15] fix(stinger): refuse a take on a page showing a #fragment of its own The URL check covered only the URL stored on the block. A page moved live through the element endpoint or MCP to a URL with a fragment still lost it to the take. The take now checks the URL the page shows, which is what it rewrites. A take's own fragment from an earlier take is accepted, and surrounding space is trimmed first, as it is before the page loads. Co-Authored-By: Claude Opus 5.5 --- backend/src/state/stinger/web.rs | 14 +++++++++----- backend/src/stinger/web.rs | 26 +++++++++++++++++++------- 2 files changed, 28 insertions(+), 12 deletions(-) diff --git a/backend/src/state/stinger/web.rs b/backend/src/state/stinger/web.rs index 3b8140dd0..32740ba32 100644 --- a/backend/src/state/stinger/web.rs +++ b/backend/src/state/stinger/web.rs @@ -240,6 +240,15 @@ impl AppState { let pad = cefsrc .static_pad("src") .ok_or_else(|| ("the stinger page has no output".to_string(), true))?; + // The page may have been moved since the block's URL was stored (a + // live write through the element endpoint or MCP): check what it + // shows, since that is what the take rewrites. + let shown: Option = cefsrc.property(html_input::URL_PROPERTY); + let shown = crate::cef_pages::shown_url( + cefsrc.upcast_ref(), + shown.unwrap_or_else(|| page.configured_url()), + ); + check_page_url(&shown).map_err(|e| (e, false))?; // Stage the take and raise the graphic: the page is transparent at // rest, so nothing shows until it starts. Its start is not known @@ -294,11 +303,6 @@ impl AppState { } // A new fragment is a same-document navigation: the loaded page gets // `hashchange` and starts its animation, rather than reloading. - let shown: Option = cefsrc.property(html_input::URL_PROPERTY); - let shown = crate::cef_pages::shown_url( - cefsrc.upcast_ref(), - shown.unwrap_or_else(|| page.configured_url()), - ); let base = shown.split('#').next().unwrap_or_default().to_string(); crate::cef_pages::load_url(&cefsrc, &format!("{}#{}", base, take_fragment(token))); let taken_at = Instant::now(); diff --git a/backend/src/stinger/web.rs b/backend/src/stinger/web.rs index e1dc689b3..e82366b6c 100644 --- a/backend/src/stinger/web.rs +++ b/backend/src/stinger/web.rs @@ -38,20 +38,27 @@ pub const PAGE_FIRST_FRAME_DELAY_FIXED_RATE: Duration = Duration::from_millis(30 /// paints, rather than at a fixed rate. pub const VARIABLE_RATE_PROPERTY: &str = "max-video-framerate"; +const TAKE_FRAGMENT_PREFIX: &str = "strom-take-"; + /// The URL fragment a take sets to trigger a page. pub fn take_fragment(token: u64) -> String { - format!("strom-take-{token}") + format!("{TAKE_FRAGMENT_PREFIX}{token}") } /// A stinger page's URL cannot carry a fragment of its own: a take replaces /// it, which would move a page that routes by its fragment off its route. +/// The fragment an earlier take set is the take's own, not the page's. pub fn check_page_url(url: &str) -> Result<(), String> { - match url.split_once('#') { - Some((_, fragment)) if !fragment.is_empty() => Err(format!( - "a stinger page's URL cannot have a #fragment ('#{}'): a take sets the fragment \ - to trigger the page", - fragment - )), + match url.trim().split_once('#') { + Some((_, fragment)) + if !fragment.is_empty() && !fragment.starts_with(TAKE_FRAGMENT_PREFIX) => + { + Err(format!( + "a stinger page's URL cannot have a #fragment ('#{}'): a take sets the \ + fragment to trigger the page", + fragment + )) + } _ => Ok(()), } } @@ -645,6 +652,11 @@ mod tests { assert!(err.contains("#/stinger"), "{err}"); assert!(check_page_url("https://example.com/graphics/").is_ok()); assert!(check_page_url("https://example.com/graphics/#").is_ok()); + // Trailing space is trimmed before the page loads, so it is not a + // fragment. + assert!(check_page_url(" https://example.com/# ").is_ok()); + // A page an earlier take triggered shows the take's fragment. + assert!(check_page_url(&format!("https://example.com/#{}", take_fragment(7))).is_ok()); } #[test] From 12da236852fb043a74288d6ddee5625dff201e35 Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Tue, 6 Oct 2026 17:57:04 -0700 Subject: [PATCH 10/15] refactor(stinger): drop the paints-at-rest warning The check guessed when the next take could start, and a take chained straight after the last one beat the guess, so a well-behaved page was warned about. For a log line, that is not worth a probe that outlives the take and a mixer latency query. The block's help says a stinger page must stop drawing at rest; a page that does not cuts a frame or two early. Co-Authored-By: Claude Opus 5.5 --- backend/src/gst/pipeline/effects/stinger.rs | 8 --- backend/src/state/stinger/web.rs | 45 ++---------- backend/src/stinger/web.rs | 77 +-------------------- 3 files changed, 8 insertions(+), 122 deletions(-) diff --git a/backend/src/gst/pipeline/effects/stinger.rs b/backend/src/gst/pipeline/effects/stinger.rs index e6fd1456b..fba0d7355 100644 --- a/backend/src/gst/pipeline/effects/stinger.rs +++ b/backend/src/gst/pipeline/effects/stinger.rs @@ -299,14 +299,6 @@ impl PipelineManager { crate::stinger::FrameGrid::new(fps.numer(), fps.denom()) } - /// How far behind running time the mixer's output runs: what a latency - /// query on its output answers. - pub fn mixer_latency_ns(&self, block_instance_id: &str) -> Option { - let mut query = gst::query::Latency::new(); - let pad = self.dist_mixer(block_instance_id).ok()?.static_pad("src")?; - pad.query(&mut query).then(|| query.result().1.nseconds()) - } - /// The flow's running time now. pub fn running_time_ns(&self) -> Option { self.pipeline.current_running_time().map(|t| t.nseconds()) diff --git a/backend/src/state/stinger/web.rs b/backend/src/state/stinger/web.rs index 32740ba32..2fa6dbdef 100644 --- a/backend/src/state/stinger/web.rs +++ b/backend/src/state/stinger/web.rs @@ -31,10 +31,6 @@ use crate::stinger::FrameGrid; /// that paints nothing leaves the output still. const SILENT_PAGE_LIMIT: Duration = Duration::from_millis(400); -/// How long past the rest window the check waits for its last frames to -/// arrive. -const REST_CHECK_SLACK: Duration = Duration::from_millis(50); - /// A 30 fps grid, to judge a page's settings while its flow is stopped. const NOMINAL_GRID: FrameGrid = FrameGrid { num: 30, den: 1 }; @@ -325,6 +321,7 @@ impl AppState { } }; let first = anchor.first_frame_ns(); + drop(anchor); let after_take = |ns: u64| ns.saturating_sub(taken_rt) / 1_000_000; if prompt { debug!( @@ -369,16 +366,13 @@ impl AppState { let counted_from = cefsrc .current_running_time() .map_or(take.start, |t| t.nseconds().max(take.start)); - let (programmed, mixer_latency_ns) = { + let programmed = { let pipelines = self.inner.pipelines.read().await; match pipelines.get(flow_id) { - Some(manager) => ( - manager - .program_stinger(block, &take) - .map_err(|e| e.error.to_string()), - manager.mixer_latency_ns(block).unwrap_or(0), - ), - None => (Err("the flow is not running".to_string()), 0), + Some(manager) => manager + .program_stinger(block, &take) + .map_err(|e| e.error.to_string()), + None => Err("the flow is not running".to_string()), } }; let watch = match programmed { @@ -386,33 +380,6 @@ impl AppState { Err(e) => return Err(abort(e).await), }; - // A page that paints at rest makes its rest paints look like its - // animation's start, which puts the cut early. Past its duration the - // page should be at rest, after at most one paint that clears it. - // Count what it paints from a page frame past the end until the - // earliest the next take could trigger it: the take finishes once the - // mixer's output is two frames past the end, which is the mixer's - // latency later in running time. - let rest_from = take.end + page_frame_ns; - let rest_until = take.end + 2 * take.frame_ns + mixer_latency_ns; - anchor.expect_rest(rest_from, rest_until); - let wait = Duration::from_nanos(rest_until.saturating_sub(taken_rt)) - .saturating_add(REST_CHECK_SLACK) - .saturating_sub(taken_at.elapsed()); - let source_id = source.clone(); - tokio::spawn(async move { - tokio::time::sleep(wait).await; - if anchor.paints_at_rest() { - warn!( - "Stinger page {}: the page kept drawing after its stinger duration, so on a \ - take its rest paints can look like its animation starting and the cut may land \ - a frame or two early. A stinger page should stop drawing at rest, within its \ - Stinger Duration", - source_id - ); - } - }); - let take_to_air_ms = (taken_at - requested).as_secs_f64() * 1000.0 + (start as f64 - taken_rt as f64) / 1e6; let frames_expected = page_frames_between(anchor_ns, page_frame_ns, counted_from, take.end); diff --git a/backend/src/stinger/web.rs b/backend/src/stinger/web.rs index e82366b6c..b4ede199c 100644 --- a/backend/src/stinger/web.rs +++ b/backend/src/stinger/web.rs @@ -206,8 +206,7 @@ pub fn web_first_output_frame(first_frame_ns: u64, page_frame_ns: u64, grid: Fra grid.pts(n) } -/// Watches a page's output for its first new frame after a take, and for -/// paints once the take's page has gone back to rest. +/// Watches a page's output for its first new frame after a take. /// /// On a fixed-rate gstcefsrc, wait for [`WebAnchor::ready`] before changing /// the URL, then call [`WebAnchor::taken`]. Dropping it removes the probe. @@ -223,13 +222,6 @@ pub struct WebAnchor { output_pts: Arc, /// Timestamp of the first frame of new content after the take. first_pts: Arc, - /// From this timestamp the page should be at rest; `u64::MAX` before - /// it is known. - rest_from: Arc, - /// The window ends here, before anything the next take paints. - rest_until: Arc, - /// Fresh paints stamped in `[rest_from, rest_until)`. - rest_paints: Arc, /// Assumed take-to-paint delay when the page paints nothing promptly. pub delay: Duration, } @@ -244,9 +236,6 @@ impl WebAnchor { let taken_at_ns = Arc::new(AtomicU64::new(u64::MAX)); let output_pts = Arc::new(AtomicU64::new(u64::MAX)); let first_pts = Arc::new(AtomicU64::new(u64::MAX)); - let rest_from = Arc::new(AtomicU64::new(u64::MAX)); - let rest_until = Arc::new(AtomicU64::new(u64::MAX)); - let rest_paints = Arc::new(AtomicU32::new(0)); let last_memory = AtomicUsize::new(0); let (p_before, p_taken, p_output, p_first) = ( Arc::clone(&before_take), @@ -254,12 +243,7 @@ impl WebAnchor { Arc::clone(&output_pts), Arc::clone(&first_pts), ); - let (p_rest_from, p_rest_until, p_rest) = ( - Arc::clone(&rest_from), - Arc::clone(&rest_until), - Arc::clone(&rest_paints), - ); - // A per-buffer probe for the length of one take: a few atomic loads, + // A per-buffer probe for one take, removed once the take is planned: a few atomic loads, // stores and compares per buffer. Only new content counts: a // GAP-flagged repeat, or a fixed-rate gstcefsrc re-sending its // current frame, shares the previous buffer's memory; a fresh paint @@ -292,12 +276,6 @@ impl WebAnchor { let _ = p_first.compare_exchange(u64::MAX, pts, Ordering::Relaxed, Ordering::Relaxed); } - if fresh - && pts >= p_rest_from.load(Ordering::Relaxed) - && pts < p_rest_until.load(Ordering::Relaxed) - { - p_rest.fetch_add(1, Ordering::Relaxed); - } gst::PadProbeReturn::Ok })?; Some(Self { @@ -307,9 +285,6 @@ impl WebAnchor { taken_at_ns, output_pts, first_pts, - rest_from, - rest_until, - rest_paints, delay, }) } @@ -323,21 +298,6 @@ impl WebAnchor { } } - /// Count paints stamped in `[from_ns, until_ns)`, when the page should - /// be at rest again. An empty window counts nothing. - pub fn expect_rest(&self, from_ns: u64, until_ns: u64) { - self.rest_until.store(until_ns, Ordering::Relaxed); - self.rest_from.store(from_ns, Ordering::Relaxed); - } - - /// Whether the page kept painting in the [`Self::expect_rest`] window: - /// two new frames or more. A page that keeps painting at rest makes its - /// own rest paints look like the start of the next take's animation. A - /// single paint is a page clearing itself as it ends. - pub fn paints_at_rest(&self) -> bool { - self.rest_paints.load(Ordering::Relaxed) > 1 - } - /// Record that the take changed the page's URL at running time `now_ns`. pub fn taken(&self, now_ns: u64) { self.taken_at_ns.store(now_ns, Ordering::Relaxed); @@ -613,39 +573,6 @@ mod tests { assert_eq!(anchor.first_frame_ns(), Some(70 * MS)); } - #[test] - fn a_page_painting_after_its_take_is_noticed() { - // Kept alive, as gstcefsrc keeps its current frame while it makes - // the next: a freed frame's memory could be handed out again. - let mut kept = Vec::new(); - let (src, _sink) = pads(); - let anchor = WebAnchor::watch(&src, PAGE_FIRST_FRAME_DELAY_FIXED_RATE, false).unwrap(); - kept.push(buffer(0)); - let _ = src.push(kept[0].clone()); - anchor.taken(50 * MS); - anchor.expect_rest(1_100 * MS, 1_300 * MS); - // Painting during the animation is expected. - kept.push(buffer(100)); - let _ = src.push(kept[1].clone()); - kept.push(buffer(1_000)); - let _ = src.push(kept[2].clone()); - // Back at rest: a closing paint, then repeats. - kept.push(buffer(1_133)); - let _ = src.push(kept[3].clone()); - let _ = src.push(repeat(&kept[3], 1_166)); - assert!( - !anchor.paints_at_rest(), - "one closing paint is not painting at rest" - ); - // The next take's paints are past the window. - kept.push(buffer(1_300)); - let _ = src.push(kept[4].clone()); - assert!(!anchor.paints_at_rest()); - kept.push(buffer(1_200)); - let _ = src.push(kept[5].clone()); - assert!(anchor.paints_at_rest()); - } - #[test] fn a_page_url_with_a_fragment_is_refused() { let err = check_page_url("https://example.com/graphics/#/stinger").unwrap_err(); From 5b85b7694715726617bc70a160556b39abfca0f6 Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Tue, 6 Oct 2026 18:43:00 -0700 Subject: [PATCH 11/15] test(stinger): the API on a page stinger source A page is the library's one entry (classic, premultiplied, its cut point), cueing it succeeds and does nothing, the clip-library operations are refused with the reason, and a page URL with a #fragment of its own is reported. Runs without cefsrc, so CI runs it. Co-Authored-By: Claude Opus 5.5 --- backend/tests/stinger_page_api_test.rs | 181 +++++++++++++++++++++++++ 1 file changed, 181 insertions(+) create mode 100644 backend/tests/stinger_page_api_test.rs diff --git a/backend/tests/stinger_page_api_test.rs b/backend/tests/stinger_page_api_test.rs new file mode 100644 index 000000000..281bd725d --- /dev/null +++ b/backend/tests/stinger_page_api_test.rs @@ -0,0 +1,181 @@ +//! The stinger API on a mixer whose stinger input is a page (an HTML Input in +//! stinger mode): the page is the library's one entry, cue does nothing, and +//! the clip-library operations are refused. None of it needs the flow running, +//! so this runs without cefsrc. + +use axum::body::Body; +use axum::http::{Request, StatusCode}; +use serde_json::{json, Value}; +use std::collections::HashMap; +use strom::state::AppState; +use strom::storage::JsonFileStorage; +use strom_types::stinger::{ + STINGER_MODE_PROPERTY, WEB_STINGER_CUT_POINT_PROPERTY, WEB_STINGER_DURATION_PROPERTY, +}; +use strom_types::{Flow, Link, PropertyValue as PV}; +use tempfile::NamedTempFile; +use tower::ServiceExt; + +const URL: &str = "https://example.com/stinger.html"; + +async fn call( + app: &axum::Router, + method: &str, + uri: &str, + body: Option, +) -> (StatusCode, Value) { + let request = Request::builder() + .method(method) + .uri(uri) + .header("content-type", "application/json") + .body(match body { + Some(b) => Body::from(b.to_string()), + None => Body::empty(), + }) + .unwrap(); + let response = app.clone().oneshot(request).await.unwrap(); + let status = response.status(); + let bytes = axum::body::to_bytes(response.into_body(), usize::MAX) + .await + .unwrap(); + ( + status, + serde_json::from_slice(&bytes).unwrap_or(Value::Null), + ) +} + +fn block(id: &str, definition: &str, props: &[(&str, PV)]) -> strom_types::BlockInstance { + strom_types::BlockInstance { + id: id.to_string(), + block_definition_id: definition.to_string(), + name: None, + properties: props + .iter() + .map(|(k, v)| (k.to_string(), v.clone())) + .collect::>(), + position: strom_types::block::Position { x: 0.0, y: 0.0 }, + runtime_data: None, + computed_external_pads: None, + } +} + +/// A stopped flow: a vision mixer with its stinger input fed by a page. +async fn page_flow(url: &str) -> (AppState, strom_types::FlowId, NamedTempFile, NamedTempFile) { + gstreamer::init().unwrap(); + let mut flow = Flow::new("stinger_page_api"); + flow.blocks.push(block( + "web", + strom::blocks::builtin::html_input::BLOCK_ID, + &[ + ("url", PV::String(url.to_string())), + (STINGER_MODE_PROPERTY, PV::Bool(true)), + (WEB_STINGER_DURATION_PROPERTY, PV::UInt(1000)), + (WEB_STINGER_CUT_POINT_PROPERTY, PV::UInt(500)), + ], + )); + flow.blocks.push(block( + "vm", + "builtin.vision_mixer", + &[ + ("num_inputs", PV::UInt(2)), + ("enable_stinger", PV::Bool(true)), + ], + )); + flow.links.push(Link { + from: "web:video_out".to_string(), + to: "vm:stinger_in".to_string(), + }); + let storage = NamedTempFile::new().unwrap(); + let blocks = NamedTempFile::new().unwrap(); + let state = AppState::new( + JsonFileStorage::new(storage.path()), + blocks.path(), + std::env::temp_dir(), + vec![], + "all".to_string(), + vec![], + false, + false, + ); + let flow_id = flow.id; + state.upsert_flow(flow).await.unwrap(); + (state, flow_id, storage, blocks) +} + +#[tokio::test] +async fn a_page_is_the_one_entry_and_the_library_is_refused() { + let (state, flow_id, _s, _b) = page_flow(URL).await; + let app = strom::create_app_with_state(state).await; + let base = format!("/api/flows/{}/blocks/vm/stinger", flow_id); + + let (status, s) = call(&app, "GET", &base, None).await; + assert_eq!(status, StatusCode::OK, "{s}"); + assert_eq!(s["source_kind"], "page", "{s}"); + assert_eq!(s["source_block_id"], "web"); + let clips = s["clips"].as_array().unwrap(); + assert_eq!(clips.len(), 1); + assert_eq!(clips[0]["file"], URL); + assert_eq!(clips[0]["variant"], "classic"); + assert_eq!(clips[0]["cut_point_ms"], 500); + assert_eq!(clips[0]["settings"]["premultiplied"], true); + assert!( + s["problem"].as_str().unwrap().contains("not running"), + "a stopped page is not ready: {s}" + ); + + let (status, _) = call( + &app, + "POST", + &format!("{base}/cue"), + Some(json!({"index": 0})), + ) + .await; + assert_eq!( + status, + StatusCode::OK, + "cueing the page does nothing, successfully" + ); + let (status, _) = call( + &app, + "POST", + &format!("{base}/cue"), + Some(json!({"index": 1})), + ) + .await; + assert_eq!(status, StatusCode::BAD_REQUEST, "a page has no entry 1"); + + let refused = [ + ( + "POST", + format!("{base}/clips"), + Some(json!({"file": "a.mov"})), + ), + ( + "PUT", + format!("{base}/clips/0"), + Some(json!({"layout": "side_by_side"})), + ), + ("DELETE", format!("{base}/clips/0"), None), + ("POST", format!("{base}/examples"), Some(json!({}))), + ]; + for (method, uri, body) in refused { + let (status, e) = call(&app, method, &uri, body).await; + assert_eq!(status, StatusCode::BAD_REQUEST, "{method} {uri}: {e}"); + assert!( + e.to_string() + .contains("stinger page and has no clip library"), + "{method} {uri} must say why: {e}" + ); + } +} + +#[tokio::test] +async fn a_page_url_with_its_own_fragment_is_reported() { + let (state, flow_id, _s, _b) = page_flow("https://example.com/graphics/#/stinger").await; + let s = state.stinger_state(&flow_id, "vm").await.unwrap(); + assert!( + s.problem.as_deref().unwrap_or("").contains("#fragment"), + "{:?}", + s.problem + ); +} From f5d1a9b587a41fbe5ad894ef52be3085b90af917 Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Mon, 19 Oct 2026 09:48:03 -0700 Subject: [PATCH 12/15] test(stinger): build the page tests' AppState through the shared helper Co-Authored-By: Claude Sonnet 5.5 --- backend/tests/stinger_page_api_test.rs | 28 ++++++++------------------ backend/tests/stinger_web_test.rs | 22 ++------------------ 2 files changed, 10 insertions(+), 40 deletions(-) diff --git a/backend/tests/stinger_page_api_test.rs b/backend/tests/stinger_page_api_test.rs index 281bd725d..b7528564a 100644 --- a/backend/tests/stinger_page_api_test.rs +++ b/backend/tests/stinger_page_api_test.rs @@ -7,15 +7,14 @@ use axum::body::Body; use axum::http::{Request, StatusCode}; use serde_json::{json, Value}; use std::collections::HashMap; -use strom::state::AppState; -use strom::storage::JsonFileStorage; use strom_types::stinger::{ STINGER_MODE_PROPERTY, WEB_STINGER_CUT_POINT_PROPERTY, WEB_STINGER_DURATION_PROPERTY, }; use strom_types::{Flow, Link, PropertyValue as PV}; -use tempfile::NamedTempFile; use tower::ServiceExt; +pub mod common; + const URL: &str = "https://example.com/stinger.html"; async fn call( @@ -60,7 +59,7 @@ fn block(id: &str, definition: &str, props: &[(&str, PV)]) -> strom_types::Block } /// A stopped flow: a vision mixer with its stinger input fed by a page. -async fn page_flow(url: &str) -> (AppState, strom_types::FlowId, NamedTempFile, NamedTempFile) { +async fn page_flow(url: &str) -> (common::state::TestState, strom_types::FlowId) { gstreamer::init().unwrap(); let mut flow = Flow::new("stinger_page_api"); flow.blocks.push(block( @@ -85,27 +84,16 @@ async fn page_flow(url: &str) -> (AppState, strom_types::FlowId, NamedTempFile, from: "web:video_out".to_string(), to: "vm:stinger_in".to_string(), }); - let storage = NamedTempFile::new().unwrap(); - let blocks = NamedTempFile::new().unwrap(); - let state = AppState::new( - JsonFileStorage::new(storage.path()), - blocks.path(), - std::env::temp_dir(), - vec![], - "all".to_string(), - vec![], - false, - false, - ); + let state = common::state::new(); let flow_id = flow.id; state.upsert_flow(flow).await.unwrap(); - (state, flow_id, storage, blocks) + (state, flow_id) } #[tokio::test] async fn a_page_is_the_one_entry_and_the_library_is_refused() { - let (state, flow_id, _s, _b) = page_flow(URL).await; - let app = strom::create_app_with_state(state).await; + let (state, flow_id) = page_flow(URL).await; + let app = strom::create_app_with_state(state.app()).await; let base = format!("/api/flows/{}/blocks/vm/stinger", flow_id); let (status, s) = call(&app, "GET", &base, None).await; @@ -171,7 +159,7 @@ async fn a_page_is_the_one_entry_and_the_library_is_refused() { #[tokio::test] async fn a_page_url_with_its_own_fragment_is_reported() { - let (state, flow_id, _s, _b) = page_flow("https://example.com/graphics/#/stinger").await; + let (state, flow_id) = page_flow("https://example.com/graphics/#/stinger").await; let s = state.stinger_state(&flow_id, "vm").await.unwrap(); assert!( s.problem.as_deref().unwrap_or("").contains("#fragment"), diff --git a/backend/tests/stinger_web_test.rs b/backend/tests/stinger_web_test.rs index fdaa7cf11..b2a82dab9 100644 --- a/backend/tests/stinger_web_test.rs +++ b/backend/tests/stinger_web_test.rs @@ -23,13 +23,10 @@ use gstreamer_app as gst_app; use serial_test::serial; use std::collections::HashMap; use std::time::{Duration, Instant}; -use strom::state::AppState; -use strom::storage::JsonFileStorage; use strom_types::stinger::{ STINGER_MODE_PROPERTY, WEB_STINGER_CUT_POINT_PROPERTY, WEB_STINGER_DURATION_PROPERTY, }; use strom_types::{Flow, FlowId, Link, PropertyValue as PV, StromEvent}; -use tempfile::NamedTempFile; const W: usize = 640; const H: usize = 360; @@ -167,11 +164,9 @@ fn link(from: &str, to: &str) -> Link { } struct Running { - state: AppState, + state: common::state::TestState, flow_id: FlowId, tap: gst_app::AppSink, - _storage: NamedTempFile, - _blocks: NamedTempFile, } /// Red on input 0 and green on input 1 (live), the page on the stinger @@ -250,18 +245,7 @@ async fn start(name: &str, backend: &str, url: &str, duration_ms: u64, page_fps: flow.links.push(link("vm:pgm_out", "pgm_convert:sink")); flow.links.push(link("pgm_convert:src", "pgm_tap:sink")); - let storage = NamedTempFile::new().unwrap(); - let blocks = NamedTempFile::new().unwrap(); - let state = AppState::new( - JsonFileStorage::new(storage.path()), - blocks.path(), - std::env::temp_dir(), - vec![], - "all".to_string(), - vec![], - false, - false, - ); + let state = common::state::new(); let flow_id = flow.id; state.upsert_flow(flow).await.expect("upsert_flow"); state.start_flow(&flow_id).await.expect("start_flow"); @@ -277,8 +261,6 @@ async fn start(name: &str, backend: &str, url: &str, duration_ms: u64, page_fps: state, flow_id, tap, - _storage: storage, - _blocks: blocks, }; // Let CEF start and the page load before the first take. let deadline = Instant::now() + FIRST_FRAME_TIMEOUT; From 3bc8f2c0edd1c73e8f35d7869aaaf271325bb48d Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Tue, 20 Oct 2026 16:29:10 -0700 Subject: [PATCH 13/15] test(stinger): guard the detached take with a clip version; bump the panel version A clip take dropped while it cues still completes and frees the mixer. This runs in stinger_test, which Check (Linux) runs, so the spawn in stinger_take no longer rests on the cefsrc-only page test. The rebase had moved the vision mixer panel version back to v2.47; main is at v2.48, so this is v2.49. Co-Authored-By: Claude Sonnet 5.5 --- backend/static/vision-mixer.html | 2 +- backend/tests/it/stinger_test.rs | 50 ++++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/backend/static/vision-mixer.html b/backend/static/vision-mixer.html index b229fe4cc..f0a140a47 100644 --- a/backend/static/vision-mixer.html +++ b/backend/static/vision-mixer.html @@ -1385,7 +1385,7 @@ WS Connecting... - v2.47-stinger | 1-9,0 = PVW | Space = AUTO | X = CUT | F = FTB | M = Hide + v2.49-stinger | 1-9,0 = PVW | Space = AUTO | X = CUT | F = FTB | M = Hide diff --git a/backend/tests/it/stinger_test.rs b/backend/tests/it/stinger_test.rs index fe3485bb4..0b0694575 100644 --- a/backend/tests/it/stinger_test.rs +++ b/backend/tests/it/stinger_test.rs @@ -459,6 +459,56 @@ async fn stopping_mid_take_releases_the_pipeline() { r.state.stop_flow(&r.flow_id).await.unwrap(); } +/// A take whose request is dropped while it cues its clip (the client went +/// away) still finishes and frees the mixer: it completes, and the next take +/// runs. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +#[serial_test::serial(stinger)] +async fn a_dropped_take_request_still_frees_the_mixer() { + if common::skip_known_ci_failure(&["macos"], "the stinger suite fails on the macOS runner") { + return; + } + if !common::plugins_available(CODEC_ELEMENTS) { + return; + } + let r = start("dropped", "cpu").await; + let mut events = r.state.events().subscribe(); + // Clip 1 is not the parked one, so its take cues it first. + let dropped = tokio::time::timeout( + std::time::Duration::from_millis(1), + r.state.stinger_take(&r.flow_id, &r.mixer(), Some(1), None), + ) + .await; + assert!( + dropped.is_err(), + "the take must still be cueing its clip at 1 ms" + ); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + loop { + match tokio::time::timeout_at(deadline.into(), events.recv()).await { + Ok(Ok(strom_types::StromEvent::StingerCompleted { .. })) => break, + Ok(Ok(strom_types::StromEvent::StingerFailed { reason, .. })) => { + panic!("take failed: {reason}") + } + Ok(_) => continue, + Err(_) => panic!("the dropped take never finished"), + } + } + assert!( + !r.state + .stinger_state(&r.flow_id, &r.mixer()) + .await + .unwrap() + .running + ); + r.state + .stinger_take(&r.flow_id, &r.mixer(), Some(0), None) + .await + .expect("the next take runs"); + r.wait_for_report(0).await; + r.state.stop_flow(&r.flow_id).await.unwrap(); +} + /// A take whose flow restarts while it cues and analyses its clip gives up /// without touching the new run: it neither programs the new mixer nor cuts /// its program, and the next take on the new run lands as usual. From 557e130991f860ba06f670c394f9d2a8e572a875 Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Thu, 19 Nov 2026 10:09:37 -0800 Subject: [PATCH 14/15] fix(stinger): regenerate the OpenAPI snapshot The committed snapshot listed the null variant of source_kind first. The generated spec lists it last, so openapi_spec_snapshot failed. Co-Authored-By: Claude Sonnet 5.5 --- backend/tests/{ => it}/stinger_page_api_test.rs | 0 backend/tests/{ => it}/stinger_web_test.rs | 0 openapi.json | 6 +++--- 3 files changed, 3 insertions(+), 3 deletions(-) rename backend/tests/{ => it}/stinger_page_api_test.rs (100%) rename backend/tests/{ => it}/stinger_web_test.rs (100%) diff --git a/backend/tests/stinger_page_api_test.rs b/backend/tests/it/stinger_page_api_test.rs similarity index 100% rename from backend/tests/stinger_page_api_test.rs rename to backend/tests/it/stinger_page_api_test.rs diff --git a/backend/tests/stinger_web_test.rs b/backend/tests/it/stinger_web_test.rs similarity index 100% rename from backend/tests/stinger_web_test.rs rename to backend/tests/it/stinger_web_test.rs diff --git a/openapi.json b/openapi.json index 8d9cb8a1d..1fe161f0e 100644 --- a/openapi.json +++ b/openapi.json @@ -11217,12 +11217,12 @@ }, "source_kind": { "oneOf": [ - { - "type": "null" - }, { "$ref": "#/components/schemas/StingerSourceKind", "description": "What kind of block that is." + }, + { + "type": "null" } ] } From 99aa136eb770f22b42624eae4d5483cf699ec311 Mon Sep 17 00:00:00 2001 From: Peter Wagenet Date: Thu, 19 Nov 2026 10:10:07 -0800 Subject: [PATCH 15/15] test(stinger): build the page tests in the shared it binary stinger_page_api_test and stinger_web_test sat in backend/tests/ with no target, so they were never built and test_layout_test failed. Neither changes process-global state, so they join tests/it/. Co-Authored-By: Claude Sonnet 5.5 --- backend/tests/it/main.rs | 2 ++ backend/tests/it/stinger_page_api_test.rs | 2 +- backend/tests/it/stinger_web_test.rs | 6 ++---- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/backend/tests/it/main.rs b/backend/tests/it/main.rs index 10f8c1ae0..c397e2016 100644 --- a/backend/tests/it/main.rs +++ b/backend/tests/it/main.rs @@ -89,8 +89,10 @@ pub mod srt_uri_validation_test; pub mod stinger_api_test; pub mod stinger_bench; pub mod stinger_clip_test; +pub mod stinger_page_api_test; pub mod stinger_prores_test; pub mod stinger_test; +pub mod stinger_web_test; pub mod tams_output_test; pub mod test_layout_test; pub mod thread_port_lifetime_test; diff --git a/backend/tests/it/stinger_page_api_test.rs b/backend/tests/it/stinger_page_api_test.rs index b7528564a..502ab7ffc 100644 --- a/backend/tests/it/stinger_page_api_test.rs +++ b/backend/tests/it/stinger_page_api_test.rs @@ -13,7 +13,7 @@ use strom_types::stinger::{ use strom_types::{Flow, Link, PropertyValue as PV}; use tower::ServiceExt; -pub mod common; +use crate::common; const URL: &str = "https://example.com/stinger.html"; diff --git a/backend/tests/it/stinger_web_test.rs b/backend/tests/it/stinger_web_test.rs index b2a82dab9..f82684b4b 100644 --- a/backend/tests/it/stinger_web_test.rs +++ b/backend/tests/it/stinger_web_test.rs @@ -12,10 +12,8 @@ //! CEF initialises once per process and is slow the first time, so every //! wait polls against a generous deadline, and the tests run serially. -pub mod common; -#[path = "common/stinger.rs"] -pub mod rig; - +use crate::common; +use crate::stinger as rig; use base64::Engine; use gstreamer as gst; use gstreamer::prelude::*;