Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion backend/src/blocks/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use crate::whip_session_manager::WhipEndpointConfig;
use gstreamer as gst;
use gstreamer::prelude::*;
use std::cell::RefCell;
use std::collections::HashMap;
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
use strom_types::{
block::{ExternalPads, StreamMode},
Expand Down Expand Up @@ -125,6 +125,34 @@ pub struct WhepEndpointInfo {
pub num_video_tracks: usize,
}

/// The elements the flow's links point into, by element ID.
///
/// Block expansion fills it once it has resolved the flow's links, which is
/// after every block has been built and before any setup hook runs. A builder
/// takes a handle from [`BlockBuildContext::flow_link_targets`] and reads it
/// from its setup hook. It answers "does the flow link into this input?" even
/// for a link construction could not make yet, which waits for a sometimes pad
/// in `pending_links` and is not linked in GStreamer when the hooks run.
#[derive(Debug, Clone, Default)]
pub struct FlowLinkTargets(Arc<Mutex<HashSet<String>>>);

impl FlowLinkTargets {
/// Whether a flow link points into the element with this ID.
pub fn contains(&self, element_id: &str) -> bool {
self.0
.lock()
.map(|set| set.contains(element_id))
.unwrap_or(false)
}

/// Record that a flow link points into the element with this ID.
pub fn insert(&self, element_id: impl Into<String>) {
if let Ok(mut set) = self.0.lock() {
set.insert(element_id.into());
}
}
}

/// Context provided to block builders during build.
///
/// Contains methods for blocks to register services, endpoints, or other
Expand Down Expand Up @@ -156,6 +184,8 @@ pub struct BlockBuildContext {
/// starting transient `DeviceMonitor` instances (which crash on
/// macOS — see Local Input block).
local_devices: GstDeviceMap,
/// Elements the flow links into, filled by block expansion after the build.
flow_link_targets: FlowLinkTargets,
}

impl BlockBuildContext {
Expand All @@ -172,6 +202,7 @@ impl BlockBuildContext {
element_setups: RefCell::new(Vec::new()),
session_thread_config: SessionThreadConfig::new(),
local_devices: Arc::new(Mutex::new(HashMap::new())),
flow_link_targets: FlowLinkTargets::default(),
}
}

Expand All @@ -195,9 +226,16 @@ impl BlockBuildContext {
element_setups: RefCell::new(Vec::new()),
session_thread_config,
local_devices,
flow_link_targets: FlowLinkTargets::default(),
}
}

/// The elements the flow links into. Empty while blocks build; block
/// expansion fills it before any setup hook runs. See [`FlowLinkTargets`].
pub fn flow_link_targets(&self) -> FlowLinkTargets {
self.flow_link_targets.clone()
}

/// Look up a live local `gst::Device` (Video/Source or Audio/Source) by
/// the same id that `/api/discovery/devices` returns.
/// Returns `None` if no such device is currently known.
Expand Down
90 changes: 90 additions & 0 deletions backend/src/blocks/builtin/inputs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
//! Helpers for a block's input tracks: how many a block declares, and which of
//! them a flow actually links.

use crate::blocks::FlowLinkTargets;
use gstreamer as gst;
use gstreamer::prelude::*;
use std::collections::HashMap;
use strom_types::PropertyValue;

/// A track-count property (`num_audio_tracks`, `num_video_tracks`, ...) as the
/// block was given it, clamped to 0..=8, or `None` when it is absent.
///
/// Absent is not the same as 0: saved flows leave out properties at their
/// default value, so each block applies its own default to `None`.
pub(crate) fn explicit_track_count(
properties: &HashMap<String, PropertyValue>,
name: &str,
) -> Option<usize> {
properties.get(name).and_then(|v| match v {
PropertyValue::UInt(u) => Some((*u as usize).min(8)),
PropertyValue::Int(i) => Some((*i).clamp(0, 8) as usize),
_ => None,
})
}

/// Whether the flow feeds a block's input element.
///
/// True when the input's sink pad is linked, or when a flow link points into
/// it that construction could not make yet: a link from a sometimes pad (a raw
/// `decodebin` element's, say) waits in `pending_links` and is made when the
/// pad appears, after the setup hooks have run. Without the second half such
/// an input reads as unconnected and its block requests no muxer or sink pad
/// for it, so the late link has nowhere to go.
///
/// Call it from a `register_element_setup` hook, with the handle from
/// `ctx.flow_link_targets()`: the hooks run after construction's linking pass
/// and block expansion has filled the targets by then.
pub(crate) fn input_is_connected(
input: &gst::glib::WeakRef<gst::Element>,
targets: &FlowLinkTargets,
) -> bool {
let Some(input) = input.upgrade() else {
return false;
};
input.static_pad("sink").is_some_and(|p| p.is_linked()) || targets.contains(&input.name())
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn track_count_is_clamped_and_absent_stays_absent() {
let mut p = HashMap::new();
assert_eq!(explicit_track_count(&p, "n"), None);
p.insert("n".to_string(), PropertyValue::UInt(99));
assert_eq!(explicit_track_count(&p, "n"), Some(8));
p.insert("n".to_string(), PropertyValue::Int(-3));
assert_eq!(explicit_track_count(&p, "n"), Some(0));
p.insert("n".to_string(), PropertyValue::Int(2));
assert_eq!(explicit_track_count(&p, "n"), Some(2));
}

#[test]
fn an_input_is_connected_when_linked_or_a_flow_link_targets_it() {
gst::init().expect("gst init");
let src = gst::ElementFactory::make("fakesrc").build().unwrap();
let input = gst::ElementFactory::make("identity")
.name("blk:input")
.build()
.unwrap();
let weak = input.downgrade();
let targets = FlowLinkTargets::default();
assert!(!input_is_connected(&weak, &targets));
src.link(&input).unwrap();
assert!(input_is_connected(&weak, &targets));
src.unlink(&input);
assert!(!input_is_connected(&weak, &targets));

// A flow link that waits for a sometimes pad counts as connected.
targets.insert("blk:input");
assert!(input_is_connected(&weak, &targets));

drop(input);
assert!(
!input_is_connected(&weak, &targets),
"a dropped input is not connected"
);
}
}
2 changes: 1 addition & 1 deletion backend/src/blocks/builtin/mediaplayer/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ pub struct MediaPlayerBuilder;
/// beyond these, and tracks that are neither video nor audio, are discarded
/// rather than left unlinked, which would stop playback.
pub(super) fn track_counts(properties: &HashMap<String, PropertyValue>) -> (usize, usize) {
use crate::blocks::builtin::whep::explicit_track_count;
use crate::blocks::builtin::inputs::explicit_track_count;
(
explicit_track_count(properties, "num_video_tracks").unwrap_or(1),
explicit_track_count(properties, "num_audio_tracks").unwrap_or(1),
Expand Down
2 changes: 2 additions & 0 deletions backend/src/blocks/builtin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ pub mod efpsrt;
#[cfg(feature = "efp")]
pub mod efpsrt_input;
pub mod html_input;
pub(crate) mod inputs;
pub mod inter;
pub mod latency;
pub mod live_recorder;
Expand All @@ -38,6 +39,7 @@ pub mod videoenc;
pub mod videoformat;
pub mod vision_mixer;
pub(crate) mod webrtc_props;
pub(crate) mod webrtcsink_profile_filter;
pub mod whep;
pub mod whip;

Expand Down
20 changes: 4 additions & 16 deletions backend/src/blocks/builtin/recorder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
//!
//! Output files are written to: {media_path}/{output_dir}/{filename_prefix}_%05d.{ext}

use super::inputs::input_is_connected;
use super::refusal::{audio_refusal, refuse_input, video_refusal};
use crate::blocks::{BlockBuildContext, BlockBuildError, BlockBuildResult, BlockBuilder};
use chrono;
Expand Down Expand Up @@ -1263,6 +1264,7 @@ impl BlockBuilder for RecorderBuilder {
{
let splitmuxsink_weak = splitmuxsink.downgrade();
let block_id = instance_id.to_string();
let link_targets = ctx.flow_link_targets();
ctx.register_element_setup(Box::new(move |_flow_id, _events| {
let Some(splitmuxsink) = splitmuxsink_weak.upgrade() else {
return;
Expand All @@ -1279,7 +1281,7 @@ impl BlockBuilder for RecorderBuilder {
.zip(video_activities.iter())
.enumerate()
{
if !input_is_connected(input) {
if !input_is_connected(input, &link_targets) {
info!(
"Recorder {}: video track {} is not connected — requesting no splitmuxsink pad for it",
block_id, vi
Expand Down Expand Up @@ -1324,7 +1326,7 @@ impl BlockBuilder for RecorderBuilder {
.zip(audio_activities.iter())
.enumerate()
{
if !input_is_connected(input) {
if !input_is_connected(input, &link_targets) {
info!(
"Recorder {}: audio track {} is not connected — requesting no splitmuxsink pad for it",
block_id, i
Expand Down Expand Up @@ -1429,20 +1431,6 @@ impl BlockBuilder for RecorderBuilder {
}
}

/// Whether a recorder input identity has something linked to its sink pad.
///
/// Runs after construction's linking pass, so this is exact for links resolved there —
/// every link into a recorder today, since recorder inputs take encoded media and so are
/// fed by encoder src pads. A link deferred to `pending_links` resolves after this and
/// would read as unconnected, losing that track. Nothing enforces that none can be.
fn input_is_connected(input: &gst::glib::WeakRef<gst::Element>) -> bool {
input
.upgrade()
.and_then(|e| e.static_pad("sink"))
.map(|p| p.is_linked())
.unwrap_or(false)
}

/// Build a TS passthrough pipeline: identity -> multifilesink.
///
/// The raw MPEG-TS bitstream is written directly to file without any demux/remux.
Expand Down
17 changes: 3 additions & 14 deletions backend/src/blocks/builtin/rtmp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@
//! refused with a message naming that block. See the audio section above for why
//! the two sides differ.

use super::inputs::input_is_connected;
use super::refusal::refuse_input;
use crate::blocks::{BlockBuildContext, BlockBuildError, BlockBuildResult, BlockBuilder};
use gstreamer as gst;
Expand Down Expand Up @@ -655,6 +656,7 @@ impl BlockBuilder for RtmpOutputBuilder {
let video_slot_for_setup = video_pad_slot.clone();
let audio_slot_for_setup = audio_pad_slot.clone();
let instance_for_setup = instance_id.to_string();
let link_targets = ctx.flow_link_targets();
ctx.register_element_setup(Box::new(move |_flow_id, _events| {
let Some(mux) = mux_for_setup.upgrade() else {
return;
Expand All @@ -663,7 +665,7 @@ impl BlockBuilder for RtmpOutputBuilder {
(&video_input_weak, &video_slot_for_setup, "video"),
(&audio_input_weak, &audio_slot_for_setup, "audio"),
] {
if !input_is_connected(input) {
if !input_is_connected(input, &link_targets) {
debug!(
"RTMP {}: {} input is not connected, reserving no pad",
instance_for_setup, name
Expand Down Expand Up @@ -857,19 +859,6 @@ fn release_reserved_pad(slot: &PadSlot, mux: &gst::Element, name: &str, instance
}
}

/// Whether an input identity has something linked to its sink pad.
///
/// Runs after construction's linking pass, so this is exact for links resolved
/// there. Same helper and same caveat as `recorder.rs`: a link deferred to
/// `pending_links` would resolve after this and read as unconnected.
fn input_is_connected(input: &gst::glib::WeakRef<gst::Element>) -> bool {
input
.upgrade()
.and_then(|e| e.static_pad("sink"))
.map(|p| p.is_linked())
.unwrap_or(false)
}

/// Request one of flvmux's fixed-name sink pads.
///
/// `flvmux` names them `video` and `audio` rather than following a `%u`
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
//! Keeps the profile and level a WHEP viewer offers from blocking pre-encoded
//! video.
//! Keeps the profile and level a WebRTC peer negotiates from blocking
//! pre-encoded video, for the webrtcsink-based sinks: WHEP Output's
//! `whepserversink` and WHIP Output's `whipclientsink`.
//!
//! The text below is written for WHEP Output, where a browser viewer makes the
//! offer. On WHIP Output the block offers and the server answers, and the same
//! filters carry the session's level: a pre-encoded source whose level rises
//! mid-publish (720p to 1080p) would fail them and end the session.
//!
//! webrtcsink copies the viewer's offered profile onto the capsfilters around
//! that viewer's payloader: the one directly upstream (the encoder filter)
Expand Down Expand Up @@ -39,13 +45,13 @@ const PROFILE_FIELDS: &[&str] = &[

/// Strip profile fields from every capsfilter webrtcsink puts around a
/// payloader, for discovery and for each viewer.
pub(super) fn install(whepserversink: &gst::Element) {
pub(crate) fn install(whepserversink: &gst::Element) {
whepserversink.connect("payloader-setup", false, |values| {
let consumer_id = values[1].get::<String>().unwrap_or_default();
let payloader = values[3].get::<gst::Element>().unwrap();

info!(
"WHEP Output: payloader-setup fired: consumer_id={}, payloader={} (factory={})",
"webrtcsink payloader-setup fired: consumer_id={}, payloader={} (factory={})",
consumer_id,
payloader.name(),
payloader
Expand Down Expand Up @@ -110,7 +116,7 @@ fn strip(filter: &gst::Element, consumer_id: &str) {
stripped.merge_structure(s);
}
info!(
"WHEP Output: Stripped profile from capsfilter {} for {}: {:?}",
"Stripped profile from webrtcsink capsfilter {} for {}: {:?}",
filter.name(),
consumer_id,
stripped
Expand Down
1 change: 0 additions & 1 deletion backend/src/blocks/builtin/whep/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ pub mod output;
use strom_types::block::BlockDefinition;

pub use input::WHEPInputBuilder;
pub(crate) use output::explicit_track_count;
pub use output::{migrate_legacy_mode, WHEPOutputBuilder};

/// Get metadata for WHEP blocks (for UI/API).
Expand Down
13 changes: 1 addition & 12 deletions backend/src/blocks/builtin/whep/output/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
//! `whepserversink` hosts the HTTP endpoint; clients connect via WHEP to receive.

pub(crate) mod definition;
mod profile_filter;
mod whepserversink;

use crate::blocks::builtin::inputs::explicit_track_count;
use crate::blocks::{BlockBuildContext, BlockBuildError, BlockBuildResult, BlockBuilder};
use crate::gst::ice_preflight;
use std::collections::HashMap;
Expand Down Expand Up @@ -150,17 +150,6 @@ pub(super) fn resolve_track_counts(properties: &HashMap<String, PropertyValue>)
(num_audio, num_video)
}

pub(crate) fn explicit_track_count(
properties: &HashMap<String, PropertyValue>,
name: &str,
) -> Option<usize> {
properties.get(name).and_then(|v| match v {
PropertyValue::UInt(u) => Some((*u as usize).min(8)),
PropertyValue::Int(i) => Some((*i).clamp(0, 8) as usize),
_ => None,
})
}

/// Migrate a legacy `mode` property on a WHEP Output block to explicit
/// `num_audio_tracks` / `num_video_tracks` counts, and drop `mode`.
///
Expand Down
2 changes: 1 addition & 1 deletion backend/src/blocks/builtin/whep/output/whepserversink.rs
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ pub(super) fn build_whepserversink(
});

// WORKAROUND #2: a viewer's offered profile must not block the stream.
super::profile_filter::install(&whepserversink);
crate::blocks::builtin::webrtcsink_profile_filter::install(&whepserversink);

// Handle consumer-removed to clean up webrtcbin from stats storage
let dynamic_webrtcbin_store_remove = ctx.dynamic_webrtcbin_store();
Expand Down
Loading
Loading