Skip to content

fix(mpegtssrt_input): retime MPEG-TS from SRT arrival against the latency budget - #1272

Merged
srperens merged 3 commits into
mainfrom
fix/ts-arrival-retiming
Nov 18, 2026
Merged

srperens merged 3 commits into
mainfrom
fix/ts-arrival-retiming

Conversation

@srperens

@srperens srperens commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Refs #1265
Supersedes #1088

Problem

With ignore-pcr=true (the default), tsdemux anchors the running time of every stream once, on the first PES it parses. A sender that sends video earlier against its PTS than audio (AAC packed several frames per PES, VBV-paced video) has audio stamped before its arrival for the whole connection. The mixer drops that input without a word: #1265, 300–500 ms late on some starts, a silent programme while the channel meters move.

#1088 replaced the anchor with one taken from SRT arrival, but had two faults of its own, measured here:

  1. The latency budget was paid twice. It stamped the latest stream margin (100 ms) after its arrival. srtsrc stamps at delivery and still reports its configured latency (125 ms) in the latency query, so downstream already waits that long. Measured against a continuous ffmpeg sender: audio +270 ms and video +440 ms over the old anchor.
  2. B-frames went out at the wrong time. Its "never step backwards" rule compared PTS. Video with B-frames goes out in decode order, so each B-frame raised the video offset and the next P-frame lowered it again: B-frames were stamped at the previous P-frame's time, with a new segment each, and video sat 30–120 ms behind audio. feat(mpegtssrt_input): retime tsdemux output from SRT arrival #1088's tests used x264enc tune=zerolatency, which makes no B-frames.

Change

On top of #1088 (rebased onto main, first commit, unchanged apart from conflict resolution and the test moved into tests/it/):

  • Lead is measured against the deadline. The deadline is the arrival minus the latency reported upstream of tsdemux's output (SRT latency + tsdemux_latency). The latest stream is due margin before that deadline. With the defaults: 25 ms before arrival instead of 100 ms after. The budget is the configured SRT latency, not the negotiated one, because the configured value is what srtsrc reports and what the pipeline's deadlines are built from.
  • Arrival is the pipeline clock, not srtsrc's stamp. srtsrc stamps now - (srt_time - srctime). That is close to delivery while data flows evenly, but up to 1.3 s behind the clock for the burst a caller sends on connecting (measured). Reading the pipeline clock takes locks, so the probe uses Instant (vDSO), calibrated against the pipeline clock at most every 500 ms.
  • Decode order, everywhere. Lead, the lateness check and the no-backwards rule use the decode-order running time: DTS where the buffer has one, else PTS. Buffers leave tsdemux in decode order, so that is when each is due, and DTS ≤ PTS, so on time by DTS is on time by PTS.
  • Descriptions: both property descriptions shortened under 200 characters. The margin's reads: "With Retime From Arrival: jitter margin in ms kept inside the SRT latency. Late data moves the timing forward."

Review fixes (second commit on top):

  1. Anchor and lateness on decode order. They used the PTS lead. With B-frames a P-frame's PTS lead is the largest of its group, so when video set the anchor (video-only, or audio sent earlier than video) every B-frame missed its deadline by 20–60 ms, and the on-time P-frames in between kept resetting the lateness so it was never corrected.
  2. Late runs per stream. late_since was one value compared across streams, whose running times differ by up to MAX_STREAM_SPREAD_NS: one late buffer of each could "confirm" 100 ms. Each stream now confirms on its own span. An on-time buffer of any stream still ends every stream's run (the stale-tail rule).
  3. DTS before the segment origin gives a smaller (signed) running time instead of none, so the first frames with B-frames no longer fall back to PTS and raise the offset.
  4. tsdemux latency=-1: the budget counts 700 ms, as tsdemux does (if (latency < 0) latency = 700; in tsdemux.c).
  5. Margin description and the DEFAULT_TS_ARRIVAL_MARGIN_MS doc now say what the margin is measured against.
  6. Caller change before the first buffer. The trust window was set from the last deadline, so with no arrival yet it ended near i64::MIN: the first caller never had it. A caller change now arms a flag, and the window starts at the first calibrated arrival after it.
  7. Calibration by time. Calibrate on the first buffer and then on the first buffer after each 500 ms of Instant time (it was one buffer in 256: an audio-only input at ~12 packets/s calibrated every ~20 s). Reading the running time takes object locks inside the srtsrc buffer probe. That is a deliberate exception to the probe rule in CLAUDE.md, bounded to 2 Hz per input, and the module doc says so. A failed calibration is retried one interval later, not per buffer.
  8. Slot reuse after pad-removed. A slot carries a generation that claim bumps. Probes hold the (slot, generation) they claimed, and calls with an older generation are ignored, so a removed pad's probes cannot write into a slot a new pad took (PMT change).
  9. Integration test measures against the clock. The lead was the buffer's running time minus srtsrc's latest stamp, the very stamp that lags the clock by up to 1.3 s in a connect burst. It is now measured against the pipeline's running time as the buffer leaves the block. No bound needed re-tuning (see Evidence).
  10. on_arrival doc rewritten (duplicate return sentence, the rejected "delivery delay", wrong parameter name).

Rejected:

Evidence

Repro, not committed: real block (MpegTsSrtInputBuilder, caller mode, 1 video + 2 audio outputs) joining a continuous ffmpeg H.264 + 2× AAC stream behind an SRT listener, the way Open Live joins its sources. Lead = buffer running time − pipeline clock, in ms; negative is late. macOS, GStreamer 1.28.6, libsrt 1.5.7.

sender old anchor #1088 as it was this PR
ffmpeg default, passthrough (PES level) audio min −214, video ~0 audio +80, video +350, pad offsets 270 vs 350–390 audio min −67 med −42, video ~+155, offsets equal (150–161)
ffmpeg default, decoded audio med −139, video −165 audio +137, video +270 audio med +12…+26, min −88; video −10
ffmpeg -pes_payload_size 6000 (#1265 case), decoded audio min −380…−425 audio min +30…+70, video +460 audio min −41…−78, video +190

With the defaults, a buffer is late only below −125 (the reported SRT latency). The old anchor put the big-PES audio 250–300 ms past that; this PR keeps every case inside it.

The repro did not reproduce #1265's randomness (3 of 10 starts): with ffmpeg the anchor lands on the same stream every time. The mechanism and the size match. The randomness depends on which PES of a given sender tsdemux parses first.

Guards, each checked by reverting its fix:

  • the_latest_stream_spends_the_reported_budget_not_more (unit) and a_clean_caller_stays_within_the_margin (integration): with the deadline reverted to the raw arrival, "the latest stream waits 91 ms past arrival, more than the margin before its deadline (-25 ms)".
  • b_frames_keep_the_offset_of_the_stream (unit) and b_frames_get_the_offset_of_every_other_stream (integration, x264 with 2 B-frames): with PTS order restored, "36 of 58 video buffers carry another offset than audio (ms off): [67, 34, 67, 34, …]".
  • arrival_follows_the_clock_not_the_stamp (unit): checks the calibration arithmetic. The integration effect showed up as the decoded early-caller test failing with the sampled-delay approach.

Review fixes, each guard checked by reverting its fix (one at a time, the other 19 unit tests stayed green):

  • b_frames_are_on_time_when_video_sets_the_anchor (1, PTS lead restored): "166 buffers missed their deadline by PTS (arrival ms, lead ms): [(40, -100), (80, -100), (160, -100), …]".
  • late_buffers_of_two_streams_do_not_confirm_each_other (2, one shared late_since): "re-anchored on one late buffer from each of two streams; left: Some(445000000), right: None".
  • a_timestamp_before_the_segment_start_has_a_running_time (3, None before the origin): "left: None, right: Some(120000000)".
  • the_first_caller_gets_the_trust_window (6, window from the last deadline): first buffers go out at −1200 ms, "[100, 100, -1200, 60, -1200, 20, -1200, -20, …]".
  • calibration_follows_time_not_buffer_count (7, one buffer in 256): "assertion failed: c.arrive(0, CALIBRATE_INTERVAL_NS + 80 * MS)".
  • a_reclaimed_slot_ignores_the_pad_that_released_it (8, generation check removed): "the old pad's segment replaced the new pad's; left: Some(5040000000), right: Some(40000000)".
  • 4 (tsdemux −1) and 5, 10 (text) have no guard test. 9 is the measurement itself: against the clock, on a quiet host, the passthrough and clean-caller leads sit at −20…−55 ms (bound −125), decoded video at about −125 ms (bound −275), so the bounds were left as they were.

Tests

Ran on macOS (arm64, GStreamer 1.28.6, libsrt 1.5.7):

  • cargo test --lib ts_arrival_clock: 20 pass.
  • STROM_REQUIRE_GST_PLUGINS=1 cargo test --test it -- mpegtssrt pipeline_lifecycle openapi (25 tests), with the review fixes:
    • 15 runs in a row green on a quiet host.
    • Before that, two sets with failures I attribute to the host, not the code:
      • An 8-run set: 7 green, 1 with the receiver failing to reach PLAYING, before any timing assertion. Likely the listener port taken in the 2 s the early-caller test leaves it unbound (a guess, not shown). The test now picks listener ports below the ephemeral range and reports the bus error if the receiver does not start.
      • Runs while the laptop was in maintenance sleep on battery, then just after it woke: runs 20–40 min apart, and failures where every stream of every test went late together by 300 ms to 1.1 s at the same second. That is the process frozen while the clock runs on. Measured against srtsrc's stamp, the old test could not see such a stall.
  • cargo clippy --all-targets -- -D warnings, with and without --features efp; cargo fmt --all.

Not run: Linux (CI will be the first), the rest of the integration suite, the Open Live rig, a real network. Senders like Ateme, which Open Live's sources probably are, were not available. All measurements are on localhost.

Two test changes to #1088's file:

  • The decoded early-caller test looks from 2.5 s, not 1.5 s. Under the parallel suite, the stale head's last decoded frames left the decoder at 1.54 s, late by design (old data). feat(mpegtssrt_input): retime tsdemux output from SRT arrival #1088 passed because the srtsrc stamp lagged the clock in the burst and made them look on time.
  • The tests pause 500 ms between stopping the caller and the receiver. See the srtsrc hang below.

Lesson

  • CLAUDE.md, Tests: a test of code that reads or rewrites video timestamps feeds it B-frames.
  • docs/UPSTREAM_NOTES.md, three entries:
    • tsdemux ignore-pcr anchors once;
    • srtsrc's stamp is not arrival and its reported latency is the configured one;
    • srtsrc with keep-listening can hang for good when stopped right after its caller leaves. Seen once in about 15 runs; the stop's cancel is wiped by the listener restart. This can also hang a flow stop in production.

For the reviewer

  • Default on, and it changes timing on every MPEG-TS/SRT input with ignore_pcr. It adds delay where the old anchor was late beyond the budget (that is the fix), and roughly 150 ms over the old anchor even for a plain ffmpeg stream. The old anchor sat ~90 ms past the budget there and only worked because the mixer had slack.
  • Video waits for the latest audio to keep A/V sync (+190 ms with 400 ms audio PES). That cannot be avoided without breaking sync.
  • One Instant::now() per srtsrc buffer in the probe. The pipeline's running time is read at most every 500 ms, and that takes object locks inside a buffer probe: a deliberate exception to the CLAUDE.md probe rule, bounded to 2 Hz per input and stated in the module doc.
  • The integration timing tests measure against the clock now, so a host that stalls the test process (sleep, heavy load) fails them. That is the honest measurement, and the reason they should not run beside heavy jobs.

Out of scope

🤖 Generated with Claude Code

srperens and others added 2 commits November 17, 2026 18:00
With ignore-pcr, tsdemux anchors its timestamps once, on the first PES it
parses, and keeps any error in that sample for the whole connection. A
caller that encoded before connecting is stamped seconds ahead, a sender
that stalls is stamped late for seconds, and ffmpeg's default muxing adds
its send-ahead (~350 ms audio, ~500 ms video) as latency.

gst::ts_arrival_clock keeps tsdemux's PTS spacing and replaces only its
anchor, from srtsrc's arrival timestamps: per stream the largest lead in a
2 s window, the latest-arriving stream setting one shared pad offset, late
buffers re-anchoring once confirmed (at once after a caller change), and
output never stepping backwards. On by default with ignore_pcr; block
properties arrival_retiming and arrival_margin_ms (100 ms).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_015zM1LedicrqbhDqxh6B5UV
…ecode order

The arrival retiming from #1088 stamped the latest stream a margin after
its arrival, on top of the SRT latency srtsrc reports, so the budget was
paid twice. Measure lead against the deadline instead: the pipeline's
running time at arrival minus the reported SRT + tsdemux latency.

Arrival is the pipeline clock's running time, from Instant calibrated
against the clock every 256 srtsrc buffers. srtsrc's own stamp is up to
1.3 s behind the clock in a caller's connect burst.

The never-step-backwards rule compared PTS. Video with B-frames goes out
in decode order, so every B-frame raised the video offset and the next
P-frame lowered it: B-frames went out at the wrong time and video
drifted 30-120 ms behind audio. Compare DTS where the buffer has one.

Refs #1265

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… fixes

Review findings on #1272:
- Lead and lateness use the decode-order running time (DTS, else PTS).
  Anchored on PTS, every B-frame after a P-frame missed its deadline
  whenever video set the anchor, and the on-time P-frames kept that
  from being confirmed.
- Late runs are kept per stream, so two late buffers of different
  streams cannot confirm 100 ms between them. An on-time buffer of any
  stream still ends every stream's run.
- A DTS before the segment origin gives a smaller running time instead
  of none.
- The budget counts 700 ms for a negative tsdemux latency, as tsdemux
  itself does.
- The trust window after a caller change starts at the first arrival,
  so a caller that connects before any data gets it.
- Calibrate against the pipeline clock by time (500 ms), not one buffer
  in 256: a deliberate, bounded exception to the probe lock rule.
- A per-slot generation stops a removed pad's probes from writing into
  a slot a new pad has claimed.
- The integration test measures lead against the pipeline clock, not
  srtsrc's stamp, and picks listener ports below the ephemeral range.
- Margin description and doc comments corrected.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant