Skip to content

Detect a non-optimized MP4 from the mdat header - #155

Closed
chrizzchrizz wants to merge 1 commit into
dimitris-c:mainfrom
chrizzchrizz:fix/mp4-early-restructure
Closed

chrizzchrizz wants to merge 1 commit into
dimitris-c:mainfrom
chrizzchrizz:fix/mp4-early-restructure

Conversation

@chrizzchrizz

Copy link
Copy Markdown
Contributor

Problem

A non-optimized MP4 (moov after mdat) was only recognized once the whole mdat had been received. checkIsOptimized records an mdat whose header has arrived but whose content is still incomplete, yet in that branch it only decides the optimized case (moov before mdat). The .needsRestructure result is returned only from the complete-atom path, i.e. after the entire mdat is in the buffer.

For a remote stream, RemoteMp4Restructure.optimizeIfNeeded therefore downloads almost the whole file before it fetches the moov, and then streams the file a second time from the mdat offset. Over a slow connection this delays the start by many seconds. Logs from an app (Amperfy) over a VPN at about 0.5 MB/s:

before after
bytes read by the optimize check 4.9–8.7 MB (whole file) 2.4–13 KB
play request to start of the audio stream 3–20 s 1.0–1.4 s

Change

When the mdat header has been read before any moov, the mdat size already gives the moov offset (atomOffset + atomSize), so .needsRestructure is returned right away. The mdat atom is added to atoms first, because restructureMoov looks it up there. FileAudioSource uses the same check, so local files benefit too.

Testing

New Mp4RestructureTests with two small fixtures: a 1 s AAC file from afconvert (moov at the start), and the same file with the moov moved behind the mdat and its chunk offsets adjusted (moov at the end). The tests check that:

  • the non-optimized file is detected from the mdat header alone;
  • no decision is made before the mdat header is complete;
  • an optimized file is still detected as before;
  • the file restructured after the early detection parses without errors.

Without the change, the three tests for the non-optimized file fail. The full test suite passes on macOS.

A non-optimized MP4 (moov after mdat) was only recognized once the whole
mdat had been received, so a remote stream downloaded almost the entire
file before fetching the moov and streaming the file a second time. The
mdat header already gives the moov offset.
@chrizzchrizz

Copy link
Copy Markdown
Contributor Author

Closing as a duplicate of #151, which has the same fix and was opened first. I added my measurements and offered the fixture-based tests there.

@chrizzchrizz
chrizzchrizz deleted the fix/mp4-early-restructure branch November 17, 2026 12:13
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