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
44 changes: 36 additions & 8 deletions backend/src/blocks/builtin/mediaplayer/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use super::normalize_uri;
use super::state::{MediaPlayerKey, MediaPlayerState, MEDIA_PLAYER_REGISTRY};
use super::timing::{self, Timing};
use crate::blocks::{
BlockBuildContext, BlockBuildError, BlockBuildResult, BlockBuilder, BusMessageConnectFn,
APPSRC_MAX_BYTES_AUDIO, APPSRC_MAX_BYTES_VIDEO, APPSRC_MAX_TIME,
live_bridge_appsrc, BlockBuildContext, BlockBuildError, BlockBuildResult, BlockBuilder,
BusMessageConnectFn, APPSRC_MAX_BYTES_AUDIO, APPSRC_MAX_BYTES_VIDEO,
};
use crate::events::EventBroadcaster;
use gstreamer as gst;
Expand Down Expand Up @@ -255,13 +255,8 @@ fn build_media_player(
let queue_id = format!("{}:queue_{}{}", instance_id, kind, sfx);
let out_id = format!("{}:{}_out{}", instance_id, kind, sfx);

let appsrc = gst_app::AppSrc::builder()
let appsrc = live_bridge_appsrc(max_bytes)
.name(&appsrc_id)
.format(gst::Format::Time)
.is_live(true)
.automatic_eos(false)
.max_bytes(max_bytes)
.max_time(APPSRC_MAX_TIME)
.leaky_type(gst_app::AppLeakyType::Upstream)
.build();
let queue = gst::ElementFactory::make("queue")
Expand Down Expand Up @@ -617,6 +612,39 @@ mod tests {
}
}

/// Each output's appsrc queues up to `APPSRC_MAX_TIME` of the player's
/// media, and has to report that as its maximum latency. At the appsrc
/// default of 0, a mixer that also takes an input with more latency than
/// the queue after the appsrc can absorb fails its latency configuration
/// on every cycle.
#[test]
fn every_output_appsrc_reports_the_latency_its_queue_can_hold() {
let props: HashMap<String, PropertyValue> =
[("num_audio_tracks".to_string(), PropertyValue::UInt(2))].into();
let _ = gst::init();
let built = MediaPlayerBuilder
.build(
"mp",
&props,
&crate::blocks::BlockBuildContext::new(Vec::new(), "all".to_string()),
)
.unwrap();
let appsrcs: Vec<gst_app::AppSrc> = built
.elements
.iter()
.filter_map(|(_, e)| e.clone().downcast::<gst_app::AppSrc>().ok())
.collect();
assert_eq!(appsrcs.len(), 3, "one video and two audio outputs");
for appsrc in appsrcs {
assert_eq!(
appsrc.latency().1,
Some(crate::blocks::APPSRC_MAX_TIME),
"{} reports a maximum latency its queue does not match",
appsrc.name()
);
}
}

/// A Media Player built by the real builder, its elements in a flow of
/// their own (`video_out` into a fakesink), and its flow handler connected
/// the way `start_flow` connects it. The handler's signal watches, on the
Expand Down
102 changes: 102 additions & 0 deletions backend/src/blocks/builtin/mixer/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1545,3 +1545,105 @@ fn test_channel_keeps_feeding_aux_while_monitor_waits_for_its_consumer() {
Duration::from_millis(4500),
);
}

/// Run the mixer with channel 1 fed through `bridge` and channel 0 through an
/// input that holds 2 s, as an SRT input at `latency: 2000` does. Returns how
/// many "Impossible to configure latency" warnings the mixer posted.
fn latency_warnings_next_to_a_two_second_input(bridge: gstreamer_app::AppSrc) -> usize {
let m = assemble(&small_mixer_props(&[
("latency", PropertyValue::UInt(100)),
("min_upstream_latency", PropertyValue::UInt(2000)),
]));

let slow = gst::parse::bin_from_description(
"audiotestsrc is-live=true ! audioconvert ! rtpL16pay ! rtpjitterbuffer latency=2000 \
! rtpL16depay",
true,
)
.unwrap();
bridge.set_caps(Some(
&"audio/x-raw,format=S16LE,rate=48000,channels=2,layout=interleaved"
.parse::<gst::Caps>()
.unwrap(),
));
bridge.set_do_timestamp(true);
let sink = gst::ElementFactory::make("fakesink")
.property("sync", true)
.build()
.unwrap();
m.pipeline
.add_many([slow.upcast_ref(), bridge.upcast_ref(), &sink])
.unwrap();
slow.link_pads(None, m.element("convert_0"), Some("sink"))
.unwrap();
bridge
.link_pads(None, m.element("convert_1"), Some("sink"))
.unwrap();
m.element("main_out_tee")
.link_pads(Some("src_%u"), &sink, None)
.unwrap();

let feeding = Arc::new(std::sync::atomic::AtomicBool::new(true));
let feeder = {
let feeding = feeding.clone();
let bridge = bridge.clone();
std::thread::spawn(move || {
// 10 ms of silence at a time, the way a bridge forwards media.
while feeding.load(Ordering::Relaxed) {
let _ = bridge.push_buffer(gst::Buffer::from_slice(vec![0u8; 480 * 4]));
std::thread::sleep(Duration::from_millis(10));
}
})
};

m.pipeline.set_state(gst::State::Playing).unwrap();
let bus = m.pipeline.bus().unwrap();
let mut warnings = 0;
let deadline = Instant::now() + Duration::from_secs(4);
while Instant::now() < deadline {
let Some(msg) = bus.timed_pop_filtered(
gst::ClockTime::from_mseconds(50),
&[gst::MessageType::Error, gst::MessageType::Warning],
) else {
continue;
};
match msg.view() {
gst::MessageView::Error(e) => panic!("pipeline error: {e:?}"),
gst::MessageView::Warning(w)
if format!("{:?}", w.debug()).contains("Impossible to configure latency") =>
{
warnings += 1;
}
_ => {}
}
}
feeding.store(false, Ordering::Relaxed);
let _ = m.pipeline.set_state(gst::State::Null);
feeder.join().unwrap();
warnings
}

/// A WHIP Input or a Media Player hands its media into the flow through a
/// live appsrc. Next to an input that holds 2 s, the mixer has to hold the
/// bridge's media for 2 s too, which the appsrc's queue can. A live appsrc at
/// its defaults reports that it can hold nothing, and the mixer then fails its
/// latency configuration on every cycle, as it did on a production flow with
/// an SRT input at 2000 ms and a WHIP guest.
#[test]
fn test_a_bridge_input_next_to_a_two_second_input_configures_latency() {
init_gst();
let bridge = crate::blocks::live_bridge_appsrc(crate::blocks::APPSRC_MAX_BYTES_AUDIO).build();
assert_eq!(latency_warnings_next_to_a_two_second_input(bridge), 0);

// The same input from an appsrc at its defaults, to show the setup above
// is one where the reported maximum decides.
let default = gstreamer_app::AppSrc::builder()
.format(gst::Format::Time)
.is_live(true)
.build();
assert!(
latency_warnings_next_to_a_two_second_input(default) > 0,
"a live appsrc at its defaults no longer fails the mixer's latency; \
this test no longer shows what it guards"
);
}
51 changes: 37 additions & 14 deletions backend/src/blocks/builtin/whip/input/slots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

use crate::blocks::builtin::webrtc_props::{parse_do_retransmission, parse_drop_on_latency};
use crate::blocks::{
BlockBuildContext, BlockBuildError, BlockBuildResult, APPSRC_MAX_BYTES_AUDIO,
APPSRC_MAX_BYTES_VIDEO, APPSRC_MAX_TIME,
live_bridge_appsrc, BlockBuildContext, BlockBuildError, BlockBuildResult,
APPSRC_MAX_BYTES_AUDIO, APPSRC_MAX_BYTES_VIDEO,
};
use crate::gst::keyframe_request::VideoDamage;
use crate::whip_session_manager::{
Expand Down Expand Up @@ -288,15 +288,10 @@ pub fn build_whipserversrc(
let appsrc_id = format!("{}:appsrc_audio_{}", instance_id, slot);
let audio_out_tee_id = format!("{}:audio_out_tee_{}", instance_id, slot);

let appsrc = gst_app::AppSrc::builder()
let appsrc = live_bridge_appsrc(APPSRC_MAX_BYTES_AUDIO)
.name(&appsrc_id)
.format(gst::Format::Time)
.is_live(true)
.handle_segment_change(true)
.max_bytes(APPSRC_MAX_BYTES_AUDIO)
.max_time(APPSRC_MAX_TIME)
.leaky_type(gst_app::AppLeakyType::Downstream)
.automatic_eos(false)
.build();

let audio_out_tee = gst::ElementFactory::make("tee")
Expand Down Expand Up @@ -419,15 +414,10 @@ pub fn build_whipserversrc(
let appsrc_id = format!("{}:appsrc_video_{}", instance_id, slot);
let video_out_tee_id = format!("{}:video_out_tee_{}", instance_id, slot);

let appsrc = gst_app::AppSrc::builder()
let appsrc = live_bridge_appsrc(APPSRC_MAX_BYTES_VIDEO)
.name(&appsrc_id)
.format(gst::Format::Time)
.is_live(true)
.handle_segment_change(true)
.max_bytes(APPSRC_MAX_BYTES_VIDEO)
.max_time(APPSRC_MAX_TIME)
.leaky_type(gst_app::AppLeakyType::Downstream)
.automatic_eos(false)
.build();

let video_out_tee = gst::ElementFactory::make("tee")
Expand Down Expand Up @@ -953,4 +943,37 @@ mod tests {
assert_eq!(configs[0].1.drop_on_latency, expected);
}
}

/// A slot's appsrc hands a session's media into the flow and queues up to
/// `APPSRC_MAX_TIME` of it. It has to report that queue as its maximum
/// latency: at the appsrc default of 0, a mixer that also takes an input
/// with more latency than the queues after the slot can absorb fails its
/// latency configuration on every cycle.
#[test]
fn slot_appsrcs_report_the_latency_their_queue_can_hold() {
let _ = gst::init();
let ctx = BlockBuildContext::new(Vec::new(), "all".to_string());
build_whipserversrc(
"whip-latency-test",
&props(&[("max_sessions", PropertyValue::Int(2))]),
&ctx,
)
.expect("build_whipserversrc failed");
let configs = ctx.take_whip_endpoint_configs();
let config = &configs[0].1;
let appsrcs: Vec<_> = config
.slot_audio_appsrcs
.iter()
.chain(&config.slot_video_appsrcs)
.collect();
assert_eq!(appsrcs.len(), 4, "audio and video for two slots");
for appsrc in appsrcs {
assert_eq!(
appsrc.latency().1,
Some(crate::blocks::APPSRC_MAX_TIME),
"{} reports a maximum latency its queue does not match",
appsrc.name()
);
}
}
}
24 changes: 24 additions & 0 deletions backend/src/blocks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,27 @@ pub const APPSRC_MAX_BYTES_VIDEO: u64 = 20 * 1024 * 1024;
pub const APPSRC_MAX_BYTES_AUDIO: u64 = 2 * 1024 * 1024;
/// Maximum time buffered in an appsrc queue before dropping old buffers.
pub const APPSRC_MAX_TIME: gst::ClockTime = gst::ClockTime::from_seconds(10);

/// Builder for a live appsrc that hands buffers from a pipeline of its own
/// into a flow (WHIP Input, Media Player). It queues up to `max_bytes` or
/// [`APPSRC_MAX_TIME`], whichever is reached first; the caller picks which end
/// leaks.
///
/// It reports that queue as its maximum latency. A live appsrc left at its
/// defaults reports a maximum of 0, as if it could not hold a single buffer.
/// An aggregator downstream takes the smallest maximum among its inputs, so
/// one such input caps the whole mixer at whatever queue sits after it (1 s
/// for a default queue). An input with more latency than that, such as an SRT
/// input at 2000 ms, then fails the mixer's latency configuration. The mixer
/// retries on every aggregation cycle and posts a warning each time,
/// thousands per second. The minimum stays 0, as before.
pub fn live_bridge_appsrc<'a>(max_bytes: u64) -> gstreamer_app::app_src::AppSrcBuilder<'a> {
gstreamer_app::AppSrc::builder()
.format(gst::Format::Time)
.is_live(true)
.automatic_eos(false)
.max_bytes(max_bytes)
.max_time(APPSRC_MAX_TIME)
.min_latency(0)
.max_latency(APPSRC_MAX_TIME.nseconds() as i64)
}
27 changes: 27 additions & 0 deletions backend/src/gst/pipeline/bus.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use super::warning_gate::{mask_digits, WarningGate, WARNING_REPEAT_INTERVAL};
use super::PipelineManager;
use gstreamer as gst;
use gstreamer::prelude::*;
use std::sync::Mutex;
use std::time::Instant;
use strom_types::{PipelineState, StromEvent};
use tracing::{debug, error, info, trace, warn};

Expand Down Expand Up @@ -62,6 +65,7 @@ impl PipelineManager {
let events = self.events.clone();
let cached_state = self.cached_state.clone();
let qos_aggregator = self.qos_aggregator.clone();
let warning_gate = Mutex::new(WarningGate::default());

let main_handler_id = bus.connect_message(None, move |_bus, msg| {
use gst::MessageView;
Expand Down Expand Up @@ -120,6 +124,29 @@ impl PipelineManager {
let debug_info = warn.debug();
let source = warn.src().map(|s| s.name().to_string());

// The source name is kept as it is: queue3 and queue4 are
// different elements. Only the debug text carries values.
let key = format!(
"{:?}\n{}\n{:?}",
source,
warning_msg,
debug_info.as_deref().map(mask_digits)
);
let Some(suppressed) = warning_gate.lock().unwrap().check(key, Instant::now())
else {
return;
};
let warning_msg = if suppressed > 0 {
format!(
"{} (repeated {} times in the last {} s)",
warning_msg,
suppressed,
WARNING_REPEAT_INTERVAL.as_secs()
)
} else {
warning_msg
};

warn!(
"Pipeline warning in flow '{}': {} (debug: {:?}, source: {:?})",
flow_name, warning_msg, debug_info, source
Expand Down
1 change: 1 addition & 0 deletions backend/src/gst/pipeline/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ mod linking;
pub(crate) mod properties;
mod srt;
mod state;
mod warning_gate;
mod webrtc;

use crate::events::EventBroadcaster;
Expand Down
Loading
Loading