Skip to content
Draft
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
5 changes: 4 additions & 1 deletion doc/bin/ts.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,10 @@ padded multiplex sends audio up to half of `--delay` ahead, spreading it across
slots, and a source that sends its audio only at its decode time adds that much
latency. A frame that cannot arrive in time at the rate fails the export, as
does video whose HRD declares a longer buffer delay than `--delay`; the error
names the delay it needs.
names the delay it needs. So does a rate the import measures only after the
export started, when `--delay` is shorter than the source sends its audio
ahead (FFmpeg's default packs about 186 ms a PES), leaving audio no room to go
out further ahead for it.

## Passthrough mode

Expand Down
35 changes: 18 additions & 17 deletions quest/m1/ts-export-audio-rate.md
Original file line number Diff line number Diff line change
@@ -1,27 +1,28 @@
# [M] A TS export that learns its rate mid-stream keeps its audio on time
# [S] A TS export that learns its rate mid-stream keeps its audio on time

## Goal

`moq export ts` of a source whose multiplex rate the import records only after the export's
first output (a meter slower than the export's rate wait, or a rate that changes) never fails
with "MPEG-TS output missed a decode deadline" for its audio and drops no frame, at any
`--delay`.
first output drops no frame that an export given the rate from the start would keep, at any
`--delay` the source's audio fits in.

## Plan

[moq-dev/moq#9636](https://github.com/moq-dev/moq/pull/9636) sends audio ahead in a padded
multiplex as far as its decoder buffer fills at the multiplex rate (`audio_reach` in
`rs/moq-mux/src/container/ts/export.rs`), within half the delay, which carries every codec at the
recorded rate plus a packet a slot. A rate learned mid-stream grows that send-ahead only by the
jitter buffer's margin over the last second, and the tables carry it only once the frames keyed
for it are due (`Program::rate_from`).
`rs/moq-mux/src/container/ts/export.rs`), within half the delay. A rate learned mid-stream grows
that send-ahead only by the jitter buffer's spare (`jitter::Engine::spare_seen`), less a slot.
[moq-dev/moq#9839](https://github.com/moq-dev/moq/pull/9839) made two changes:
- The send-ahead grows freely until the clock is anchored, then by the spare seen since the anchor.
- At a delay shorter than the source sends its audio ahead, a rate learned mid-stream is refused
with an error naming the delay (maintainer decision, 2026-11-28).

What remains: while the margin is still unknown (the first second of output), the send-ahead does
not grow at all, so a slow multiplex misses. `an_ffmpeg_audio_source_exports_at_its_recorded_rate`
with `Rate::Measured` and a 2 s delay reproduces it on `ffmpeg_ac3.ts`. A frame's jitter key is
fixed when it arrives, so a send-ahead that grows has to come out of what the frames have to
spare or move the clock's anchor.

Decided 2026-11-26 (maintainer, /quest-run): let the send-ahead grow freely until the jitter
buffer releases its first frame, since its clock anchors on the latest track then, and check whether that anchor really stays
open until the first release.
What remains: `ffmpeg_eac3.ts` with `Rate::Measured` at a 300 ms delay drops one frame (decode
4088 ms) that `Rate::Given` keeps. The rate arrives about 1.8 s in, and the spare then (76 ms)
allows 51 ms of growth. The dropped frame shares an export PES with an earlier frame, so it takes
that frame's key (`Track::release_key`) and has less spare than any frame in the second before.
The likely cause is that FFmpeg's 186 ms PES cadence beats against the export's ~160 ms PES span
over more than the spare's one-second window. Taking the least spare over two seconds did not help,
since only one second had passed when the rate arrived. Check that hypothesis first, for example by
bounding growth by the spare less the PES span that `Track::pack_start` gives at the delay.
Reproduce it with a `paced_export` sweep over the `ffmpeg_*.ts` fixtures.
18 changes: 18 additions & 0 deletions quest/m3/cli-identities-ietf22.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# [S] moq-cli's ietf22 identities test reads its group

## Goal

`cargo nextest run -p moq-cli --test integration identities::ietf22` passes on every host
`just check` runs on, like its `lite06` and `lite07` siblings.

## Plan

On an Apple Silicon macOS host, it fails deterministically on `origin/main` 93523cf38c (five runs
of five). `recv_group` in `read` (`rs/moq-cli/tests/integration/identities.rs:64`) returns
`Err(Old)`. The merge queue's runs on main pass, so first find out what differs between the hosts:
the platform, or timing between the relay and the group's write. Reproduce it, then fix the root
cause in `moq-net`'s IETF path or in the test, whichever is wrong.

## Hosts

- macos - where it fails
47 changes: 36 additions & 11 deletions rs/moq-mux/src/container/ts/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2752,26 +2752,37 @@ where
track.kind = kind;
self.refresh(name, track, pid, entry.descriptors.clone());
}
// Every audio track follows the rate, a listed one too. Once the clock runs, a frame keyed
// further ahead has that much less of the delay to arrive in, so the send-ahead grows by
// no more than the frames have had to spare over the last second, less a slot.
// Every audio track follows the rate, a listed one too. Once the clock is anchored, a frame
// keyed further ahead has that much less of the delay to arrive in, so the send-ahead grows
// by no more than the frames have had to spare over the last second (or since the anchor,
// in the first), less a slot. Until then it grows freely, as before the tables: what it
// takes comes out of the delay, and no send-ahead reaches past half of it.
//
// Frames already keyed for less send-ahead would reach the new rate with too little of
// it, so a rate that sends audio further ahead waits twice that send-ahead past the
// newest frame keyed: the frames keyed after it catch up to the new send-ahead within it
// ([`Track::release_key`]), and the frames keyed before it are due by the time the first
// of those goes out.
let window = schedule::slot(self.program.delay.as_nanos());
let spare = match self.program.psi {
// A replacement acquires its own clock beside the one playing, so it reads its own engine.
let engine = match self.program.id == self.active_program {
true => Some(&*self.jitter),
false => self.jitter.replacement_engine(),
};
let engine = engine.filter(|_| self.program.psi.is_some());
let spare = match engine.and_then(|engine| engine.spare_seen()) {
None => self.program.delay,
Some(_) => self
.jitter
.margin()
.and_then(|margin| Duration::try_from_secs_f64(margin).ok())
.map_or(Duration::ZERO, |margin| margin.saturating_sub(PCR_INTERVAL)),
Some(seen) => {
Duration::try_from_secs_f64(seen).map_or(Duration::ZERO, |seen| seen.saturating_sub(PCR_INTERVAL))
}
};
// The least spare over a whole second below a slot: the delay is shorter than the source
// sends its audio ahead, not a moment's late arrival.
let short = engine
.and_then(|engine| engine.margin())
.filter(|&margin| margin < PCR_INTERVAL.as_secs_f64());
let mut grown = Duration::ZERO;
for track in self.program.tracks.values_mut() {
for (name, track) in self.program.tracks.iter_mut() {
if let Some(buffer) = track
.buffer
.as_mut()
Expand All @@ -2784,11 +2795,25 @@ where
}
let before = audio_reach(buffer, previous, self.program.delay).min(buffer.reach);
let reach = audio_reach(buffer, self.program.mux_rate, self.program.delay);
buffer.reach = reach.min(before + spare);
let before = Buffer {
reach: before,
..*buffer
};
// A rate that needs the audio further ahead than such a delay lets it go would miss its
// deadlines.
let wanted = Buffer { reach, ..*buffer };
if let Some(margin) = short.filter(|_| self.program.mux_rate != previous)
&& schedule::ahead(Some(&wanted), window) > schedule::ahead(Some(&before), window)
{
bail_unsupported!(
"MPEG-TS multiplex rate {} b/s arrived mid-stream, but the {:?} delay is shorter than the source sends audio track '{name}' ahead: its frames had {:.0} ms to spare over the last second, less than the {:?} slot sending it ahead for the rate takes; raise the delay",
self.program.mux_rate.unwrap_or_default(),
self.program.delay,
margin * 1e3,
PCR_INTERVAL,
);
}
buffer.reach = reach.min(before.reach + spare);
if schedule::ahead(Some(buffer), window) > schedule::ahead(Some(&before), window) {
grown = grown.max(buffer.reach);
}
Expand Down
55 changes: 53 additions & 2 deletions rs/moq-mux/src/container/ts/export_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13213,6 +13213,52 @@ async fn an_ffmpeg_audio_source_exports_at_its_recorded_rate() {
assert!(Clocked::of(&ts).rate() > Clocked::of(data).rate() + crate::container::ts::schedule::PACKET);
}

/// An FFmpeg TS of audio alone whose rate the import measures only after the export's tables, while
/// its clock is still acquired, keeps its audio on time at the rate with any delay that carries the
/// source: the send-ahead the rate needs grows before anything is due, since the anchor then gives
/// the track sent latest the delay. A delay shorter than the source's PES packing drops frames at any
/// rate, so it is not swept; at 300 ms, `eac3` still drops a frame the given rate keeps
/// (`quest/m1/ts-export-audio-rate.md`).
#[tokio::test(start_paused = true)]
async fn an_ffmpeg_audio_source_measured_while_its_clock_is_acquired_keeps_its_audio_on_time() {
for (name, data) in [
("aac", &include_bytes!("test_data/ffmpeg_aac.ts")[..]),
("aac_pulse", include_bytes!("test_data/ffmpeg_aac_pulse.ts")),
("ac3", include_bytes!("test_data/ffmpeg_ac3.ts")),
("eac3", include_bytes!("test_data/ffmpeg_eac3.ts")),
("mp2", include_bytes!("test_data/ffmpeg_mp2.ts")),
("opus", include_bytes!("test_data/ffmpeg_opus.ts")),
] {
let recorded = Clocked::of(data).rate();
for delay in [500, 2000, 3000].map(Duration::from_millis) {
let (ts, dropped) = paced_export(data, Rate::Measured, delay).await;
assert_eq!(dropped, 0, "{name}, {delay:?}: every frame made its deadline");
let out = Clocked::of(&ts).rate();
assert!(
out > recorded,
"{name}, {delay:?}: padded to {out} b/s, no more than the recorded {recorded}"
);
}
}
}

/// A rate measured mid-stream at a delay shorter than the source sends its audio ahead leaves the
/// send-ahead nowhere to grow, so the export refuses it naming the delay: FFmpeg packs 186 ms of
/// audio a PES, which a 100 ms delay cannot hold.
#[tokio::test(start_paused = true)]
async fn a_rate_measured_at_a_delay_shorter_than_the_source_sends_ahead_names_the_delay() {
let data = include_bytes!("test_data/ffmpeg_ac3.ts");
let err = try_paced_export(data, Rate::Measured, Duration::from_millis(100))
.await
.expect_err("the rate cannot carry the audio")
.to_string();
assert!(
err.contains("the 100ms delay is shorter than the source sends"),
"{err}"
);
assert!(!err.contains("raise the multiplex rate"), "{err}");
}

/// Where [`paced_export`] takes its multiplex rate from.
#[derive(Clone, Copy, Debug)]
enum Rate {
Expand All @@ -13228,6 +13274,11 @@ enum Rate {
/// it at `rate` and `delay` from the first stretch on until 4 s of media. Returns the output and the frames it
/// dropped.
async fn paced_export(data: &[u8], rate: Rate, delay: Duration) -> (BytesMut, u64) {
try_paced_export(data, rate, delay).await.expect("exporter error")
}

/// [`paced_export`], returning the export's error rather than failing on it.
async fn try_paced_export(data: &[u8], rate: Rate, delay: Duration) -> Result<(BytesMut, u64), crate::Error> {
let mut broadcast = moq_net::broadcast::Info::new().produce();
let consumer = broadcast.consume();
let catalog = crate::catalog::Producer::new(
Expand Down Expand Up @@ -13261,13 +13312,13 @@ async fn paced_export(data: &[u8], rate: Rate, delay: Duration) -> (BytesMut, u6
};
let mut ts = BytesMut::new();
// The catalog stays open, so the export pads on: stop with the media.
while let Some(frame) = export.next().await.expect("exporter error") {
while let Some(frame) = export.next().await? {
ts.extend_from_slice(&frame.payload);
if frame.timestamp >= Timestamp::from_secs(4).unwrap() {
break;
}
}
(ts, export.dropped())
Ok((ts, export.dropped()))
}));
}
}
Expand Down
30 changes: 29 additions & 1 deletion rs/moq-mux/src/jitter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,15 @@ impl<K: Ord + Clone, T> Buffer<K, T> {
_ => None,
}
}
/// The engine a replacement's clock runs on: its own while it acquires, the active one once
/// committed. `None` before a replacement starts.
pub fn replacement_engine(&self) -> Option<&Engine<K, T>> {
match self.handoff.as_deref()? {
Handoff::Pending(pending) => Some(&pending.engine),
Handoff::Committed(_) => Some(&self.active),
}
}

fn committed(&self) -> Option<&Committed<K, T>> {
match self.handoff.as_deref() {
Some(Handoff::Committed(committed)) => Some(committed),
Expand Down Expand Up @@ -1669,6 +1678,13 @@ impl<K: Ord + Clone, T> Engine<K, T> {
self.margin
}

/// The least time a frame arrived before its deadline, in seconds: [`Self::margin`], or before
/// a second has passed, so far. `None` until a frame has a deadline, so while the clock is
/// still acquired, which anchors it on whatever the frames hold by then.
pub fn spare_seen(&self) -> Option<f64> {
self.margin.or(self.spare.map(|(_, spare)| spare))
}

/// How far the clock sits off the source's plus the delay, in seconds, as last measured:
/// positive holds the track sent latest longer than the delay, negative shorter. The
/// clock pulls it shut over [`RESPONSE`]. `None` until the clock has measured the source's
Expand Down Expand Up @@ -2177,24 +2193,36 @@ mod tests {
}

/// The margin is the least any frame had to spare over a whole second, a frame that missed
/// its deadline included, and holds until the next second has passed.
/// its deadline included, and holds until the next second has passed. Before a second has
/// passed, the spare seen is the least so far, and nothing while the clock is acquired.
#[tokio::test(start_paused = true)]
async fn the_margin_is_the_least_spare_over_a_second() {
let start = Instant::now();
let at = |ms: u64| start.saturating_add(Duration::from_millis(ms));
let mut acquiring = Buffer::new(DELAY);
assert_eq!(acquiring.push(1, arrival(at(0), 0, "v0")).unwrap(), Push::Queued);
assert_eq!(acquiring.spare_seen(), None, "no frame has a deadline yet");

let mut buffer = Buffer::new(DELAY).replay();
assert_eq!(buffer.push(1, arrival(at(0), 0, "v0")).unwrap(), Push::Queued);
assert_eq!(buffer.push(1, arrival(at(30), 40, "v40")).unwrap(), Push::Queued);
// Due at 180 ms.
assert_eq!(buffer.push(1, arrival(at(200), 80, "v80")).unwrap(), Push::Late);
assert_eq!(buffer.margin(), None, "no second has passed");
let seen = buffer.spare_seen().expect("frames have deadlines");
assert!((seen + 0.020).abs() < 1e-6, "seen {seen} s");

assert_eq!(
buffer.push(1, arrival(at(1_000), 1_000, "v1000")).unwrap(),
Push::Queued
);
let margin = buffer.margin().expect("a second has passed");
assert!((margin + 0.020).abs() < 1e-6, "margin {margin} s");
assert_eq!(
buffer.spare_seen(),
Some(margin),
"the margin, once a second has passed"
);

assert_eq!(
buffer.push(1, arrival(at(1_500), 1_500, "v1500")).unwrap(),
Expand Down