Skip to content

fix(live recorder): index each MP4 file so browsers start it at once - #1107

Merged
srperens merged 2 commits into
mainfrom
fix/live-recorder-sidx
Oct 27, 2026
Merged

srperens merged 2 commits into
mainfrom
fix/live-recorder-sidx

Conversation

@srperens

Copy link
Copy Markdown
Collaborator

Closes #1105

Problem

Live Recorder's fragmented MP4 files (ftyp + moov, then styp/moof/mdat fragments) have no segment index. FFmpeg's MP4 demuxer, which Chrome's <video> uses for progressive playback, then reads every moof in the file before it reports metadata. Over HTTP that means reading the whole file. Open Live measured 31 s before a Live Recorder file started in Studio from S3, against 0.35 s for a regular Recorder file (#1105).

Change

  • When the fragment sink opens an MP4 file, it leaves room for a sidx right after the init segment, held by a free box.
  • As it writes each fragment, it notes the fragment's offset, start and end.
  • When the file closes (at a split, a new init segment, EOS, or a stop going through PausedToReady), it seeks back and writes the sidx, covering every fragment to the last byte of the file, right before the first fragment. The rest of the room stays a smaller free box.
  • The index goes in first, and the free header is shortened as the last write, so a write that stops short leaves the file as it was.
  • A file that never closes, as after a crash, plays as before: players skip the free box.
  • The room is sized at 5 fragments a second of split duration, plus a margin. A file without a split duration gets room for 16,384 fragments (196 KB): about 9 hours with a 2 s GOP, under an hour at 5 fragments a second.
  • If the index does not fit, or a fragment's times cannot be read, the file closes without an index and the sink logs a warning.

Rejected:

  • An mfra at the end of the file. It is simpler to append, but FFmpeg does not read it by default; measured, it reads the whole file just the same.
  • Rewriting each file with the index first at close. It works for any length, but it copies the whole file, which for a long recording means GBs of disk IO at the stop.

Evidence

  • A fragmented MP4 without a sidx is read in full before metadata; with one, it is not. Measured locally with a 60 s audio+video recording made through the block, served over HTTP at 12 Mbit/s with 100 ms per request. On the 10.5 MB file:
    • Chrome (headless), time to loadedmetadata: 220 ms with the index, 6.8 s with the sidx renamed to free.
    • ffprobe 9.0.1: 0.22 s and 192 KB read with the index, 7.9 s and 10.8 MB read (the whole file) without.
    • The second, 5.2 MB file: 0.22 s with the index, 3.97 s without.
    • Both files decode with ffmpeg -f null without errors.
  • mfra does not help: an ffmpeg -movflags frag_keyframe remux with mfra still read 16.6 MB of 16.6 MB.
  • Every closed file is indexed to its last byte. assert_indexed in split_files_each_play_on_their_own (EOS path, split files) and a_stop_without_eos_still_writes_the_last_fragment (stop path, no split duration) checks that the sidx sits between moov and the first moof, that every entry lands on a fragment, and that the sizes add up to the file length. With index writing turned off, both fail with has no index.
  • An index that does not fit leaves the file untouched: unit test more_fragments_than_room_leaves_the_file_untouched.
  • The trun/tfhd/trex duration parsing works: unit test a_fragment_ends_where_its_longest_track_ends.
  • Not tested against real S3 or in a deployed Strom.

Tests

Ran on macOS (arm64), GStreamer from Homebrew:

  • cargo test --test live_recorder_test: 18 passed.
  • cargo test --lib live_recorder: 10 passed (mp4_boxes, mkv_cluster, fragment_sink).
  • cargo clippy --all-targets and cargo fmt: clean.

Not run: the full workspace test suite.

For the reviewer

  • The sidx refers to the first track in moov and indexes whole multi-track fragments, which is the usual practice (MP4Box does the same).
  • Its times are each fragment's earliest decode time across all tracks, converted to that track's timescale. The spec defines them as presentation times of the reference track; here the difference is a few ms of composition offset. FFmpeg times samples from tfdt and uses the sidx times only to find a fragment when seeking; seek results measured with and without the index were the same. I kept it this way because during a video stall a fragment can carry no video at all, and then the reference track has no time for it.
  • SAP fields are written as 0 ("no information"), since a fragment cut during a video stall does not start on a keyframe.
  • A review found no offset errors. Its four findings are fixed in the second commit: room sizing, write order, recording a fragment only after its write succeeded, and the write_index tests.

Out of scope

  • No test covers a new init segment mid-recording, an operator split while a split is held, or a drain timeout followed by a stop. I checked those paths by reading the code only.
  • Recordings without a split duration that grow past the room get no index, as today.
  • Matroska files still have no cues. Browsers do not play MKV anyway.

🤖 Generated with Claude Code

srperens and others added 2 commits October 27, 2026 08:44
A fragmented MP4 without a sidx makes FFmpeg's demuxer, and so Chrome's
<video>, read every moof before it reports metadata: over HTTP, the whole
file. Live Recorder files on S3 took 20-30 s to start (#1105).

The fragment sink now leaves room for a sidx after the init segment, held
by a free box, notes each fragment's offset and time as it writes it, and
writes the sidx into that room when the file closes: at a split, a new init
segment, EOS or a stop. A file that never closes plays as before. The room
is sized from the split duration, or 16384 fragments without one.

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

Review findings on the MP4 index:
- Room for 5 fragments a second of split duration, not 2: short GOPs,
  audio alone or a video stall give 1.5-2 a second, measured.
- Write the sidx first and shorten the free header last, so a write that
  stops short leaves the file as it was rather than with a broken index.
- Record a fragment in the index only after its write succeeded.
- Unit tests for write_index: layout and coverage, and an index that does
  not fit leaving the file untouched.

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

@srperens srperens left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Area: Live Recorder, MP4 file finalization

The PR leaves a free room after moov and writes a sidx into it when each file closes. The approach looks right: isofmp4mux cannot write a sidx (it is still a TODO upstream in gst-plugins-rs fmp4mux), nothing copies the whole file, and a crash leaves a plain free box. Offsets checked: the first-fragment guard (fragment_sink.rs:749), the 64-bit v1 fields, the 2 GB cap (766-769), and durations taken as timestamp differences so they do not drift (770).

Neighbours: #1057 conflicts in fragment_sink.rs, at the close in PausedToReady (318) and in open_next_file (337). Whichever lands second must keep finish_file at both. assert_indexed in the split and stop tests (live_recorder_test.rs:597, 797) would catch a dropped call. #1075 touches keepalive.rs only. Closes #1105.

  1. An unsplit file past UNSPLIT_INDEX_ENTRIES (16,384, fragment_sink.rs:66) gets no index, and the only sign is a GStreamer warning (416-421). With FRAGMENT_DURATION at 1 s (mod.rs:60), audio-only or a 1 s GOP reaches that in about 4.5 h. The PR says so, but an operator cannot see it.
  2. The new tests use statically registered isofmp4mux and require_elements, so they run in CI and do not skip. Check (Linux) was still pending when I looked.

header.extend_from_slice(b"free");
file.seek(SeekFrom::Start(index.at + free_len as u64))
.and_then(|_| file.write_all(&sidx))
.and_then(|_| file.sync_data())

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sync_data() is the ordering barrier between writing the index and shortening the free header. It runs on the muxer's streaming thread with the sink's state lock held, at every split (open_next_file, 337, reached from handle, which takes the lock at 605) and in the EOS handler (718-722). fdatasync flushes every dirty page of the file, not only the index. On a slow disk or a network mount the muxer can stall at each split, and on stop drain() gives EOS only 3 s (571-575). The ordering matters only for power loss: after a process crash both writes are already in the page cache. Not measured.

String::from_utf8_lossy(kind)
);
assert!(
be32(entry + 4) > 0,

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The end-to-end check asserts only that each duration is > 0. Nothing compares the sidx times (earliest presentation time, summed durations, timescale) with what isofmp4mux actually wrote, and the unit tests use hand-built times. A misread tfdt, trun or trex in real muxer output would still pass. A check that the summed durations match the demuxed duration, to within one fragment, would guard it.

@srperens
srperens merged commit 0746bac into main Oct 27, 2026
8 of 9 checks passed
@srperens
srperens deleted the fix/live-recorder-sidx branch November 3, 2026 17:32
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.

Live Recorder MP4 files take 20-30 s to start in a browser player: could each file get an index?

1 participant