diff --git a/backend/src/blocks/builtin/html_input.rs b/backend/src/blocks/builtin/html_input.rs
index 5c16f15a2..90b8c93f6 100644
--- a/backend/src/blocks/builtin/html_input.rs
+++ b/backend/src/blocks/builtin/html_input.rs
@@ -906,6 +906,81 @@ 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), 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(),
+ 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/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/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 37908efcc..1c6c081da 100644
--- a/backend/src/state/stinger.rs
+++ b/backend/src/state/stinger.rs
@@ -14,19 +14,23 @@ 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,
};
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};
+
+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.
@@ -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,
@@ -259,10 +297,70 @@ 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 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")?;
@@ -294,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
@@ -333,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.
@@ -402,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,
@@ -433,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()),
@@ -509,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);
@@ -842,15 +976,38 @@ 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 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"))?;
@@ -862,8 +1019,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| {
@@ -871,7 +1037,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
}
});
@@ -879,12 +1045,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);
@@ -989,7 +1162,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 +1174,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 +1231,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 +1295,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 +1304,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 +1325,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 +1353,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 +1425,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 +1449,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,
diff --git a/backend/src/state/stinger/web.rs b/backend/src/state/stinger/web.rs
new file mode 100644
index 000000000..2fa6dbdef
--- /dev/null
+++ b/backend/src/state/stinger/web.rs
@@ -0,0 +1,433 @@
+//! 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::{
+ 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,
+};
+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 =
+ 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,
+ 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)
+ };
+ 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;
+
+ 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))?;
+ // 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
+ // 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, !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
+ // there is nothing to wait for.
+ if fixed_rate {
+ 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 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/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..b4ede199c
--- /dev/null
+++ b/backend/src/stinger/web.rs
@@ -0,0 +1,604 @@
+//! 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::{AtomicU32, 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: 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);
+
+/// 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";
+
+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!("{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.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(()),
+ }
+}
+
+/// 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.
+///
+/// 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,
+ /// Buffers seen before the take.
+ before_take: 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. `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 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_before, p_taken, p_output, p_first) = (
+ Arc::clone(&before_take),
+ 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. 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;
+ };
+ 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;
+ };
+ 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 {
+ p_before.fetch_add(1, Ordering::Relaxed);
+ return gst::PadProbeReturn::Ok;
+ }
+ p_output.store(pts, Ordering::Relaxed);
+ if pts >= taken_at && fresh {
+ let _ =
+ p_first.compare_exchange(u64::MAX, pts, Ordering::Relaxed, Ordering::Relaxed);
+ }
+ gst::PadProbeReturn::Ok
+ })?;
+ Some(Self {
+ pad: pad.downgrade(),
+ probe: Some(probe),
+ before_take,
+ taken_at_ns,
+ output_pts,
+ first_pts,
+ delay,
+ })
+ }
+
+ /// 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) == 0 && 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);
+ }
+
+ /// 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, false).unwrap();
+ let rest = buffer(0);
+ let _ = src.push(rest.clone());
+ let _ = src.push(repeat(&rest, 33));
+ 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_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, true).unwrap();
+ anchor.taken(50 * MS);
+ let _ = src.push(buffer(70));
+ assert_eq!(anchor.first_frame_ns(), Some(70 * MS));
+ }
+
+ #[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());
+ // 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]
+ 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/backend/static/vision-mixer.html b/backend/static/vision-mixer.html
index c659e3fce..f0a140a47 100644
--- a/backend/static/vision-mixer.html
+++ b/backend/static/vision-mixer.html
@@ -1385,7 +1385,7 @@
WSConnecting...
- v2.48-take-note | 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
@@ -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') {
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
new file mode 100644
index 000000000..502ab7ffc
--- /dev/null
+++ b/backend/tests/it/stinger_page_api_test.rs
@@ -0,0 +1,169 @@
+//! 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_types::stinger::{
+ STINGER_MODE_PROPERTY, WEB_STINGER_CUT_POINT_PROPERTY, WEB_STINGER_DURATION_PROPERTY,
+};
+use strom_types::{Flow, Link, PropertyValue as PV};
+use tower::ServiceExt;
+
+use crate::common;
+
+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) -> (common::state::TestState, strom_types::FlowId) {
+ 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 state = common::state::new();
+ let flow_id = flow.id;
+ state.upsert_flow(flow).await.unwrap();
+ (state, flow_id)
+}
+
+#[tokio::test]
+async fn a_page_is_the_one_entry_and_the_library_is_refused() {
+ 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;
+ 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) = 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
+ );
+}
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.
diff --git a/backend/tests/it/stinger_web_test.rs b/backend/tests/it/stinger_web_test.rs
new file mode 100644
index 000000000..f82684b4b
--- /dev/null
+++ b/backend/tests/it/stinger_web_test.rs
@@ -0,0 +1,550 @@
+//! 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.
+
+use crate::common;
+use crate::stinger as 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_types::stinger::{
+ STINGER_MODE_PROPERTY, WEB_STINGER_CUT_POINT_PROPERTY, WEB_STINGER_DURATION_PROPERTY,
+};
+use strom_types::{Flow, FlowId, Link, PropertyValue as PV, StromEvent};
+
+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: common::state::TestState,
+ flow_id: FlowId,
+ tap: gst_app::AppSink,
+}
+
+/// 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 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");
+ 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,
+ };
+ // 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 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
+/// 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