Skip to content

EAC3 first segment with no audio wedges the muxer: cutFragmentForNextSegment lacks the moov guard flushPendingFragment has #222

Open

Description

@brandomoore

What happened?

A 4K HEVC Main10 MKV with E-AC-3 5.1 audio (non-JOC), served over HTTP by Jellyfin, never produces a frame. seg-0.m4s fails to cut, the muxer wedges, and the VOD revive cap is reached — so the session is abandoned and the host app falls all the way back to a server transcode of a file it should have played untouched.

The producer is reading the source fine (packetsRead=98 packetsWritten=96); it is the mp4 muxer that refuses to write the header.

[mp4 @ 0x13f65c280] [error] Cannot write moov atom before EAC3 packets parsed.
[HLSSegmentProducer] seg-0.m4s cut FAILED; muxer is wedged, ending pump
[HLSSegmentProducer] pump finished: reason=muxerFailed packetsRead=98 packetsWritten=96 lastError=0 elapsed=2ms cacheCount=0
[HLSVideoEngine] #99 VOD pump died with muxerFailed; rebuilding producer + muxer at 0.00s -> seg0 (attempt 1/2)
[mp4 @ 0x13f65c280] [error] Cannot write moov atom before EAC3 packets parsed.
[HLSSegmentProducer] seg-0.m4s cut FAILED; muxer is wedged, ending pump
[HLSVideoEngine] #99 VOD pump died with muxerFailed; rebuilding producer + muxer at 0.00s -> seg0 (attempt 2/2)
[mp4 @ 0x13f65c280] [error] Cannot write moov atom before EAC3 packets parsed.
[HLSVideoEngine] #99 VOD muxerFailed revive cap reached (3 failures, cap 2); giving up (source not muxable in this session)

Each rebuild reads exactly the same 98 packets and fails identically, so the retry cannot succeed — the rebuild re-enters the same configuration rather than changing the audio decision that caused the failure.

Downstream, AVPlayer is left waiting on segments that never arrive:

[NativeAVPlayerHost] #1 errorLog code=-12889 domain=CoreMediaErrorDomain uri=<url> 'No response for map in 4.004s'
[HLSLocalServer] send failed for /init.mp4: errno=32

Why this looks distinct from #99

#99 is the same muxer error but a different trigger: bridged mp3 → EAC3 at a non-zero startPosition, where the failure arrives via the seek/re-anchor path. This one is a source E-AC-3 track from an MKV, started at 0.00s, with no seek involved — the first seg-0.m4s cut of a fresh session fails.

HLSVideoEngine+AudioRoute already documents exactly this case in the pre-flight comment:

failure there (EAC3-from-MKV, missing dec3 extradata, -22 "Cannot write moov atom before EAC3 packets parsed")

but that probeWriteHeader pre-flight is gated on if !preferBridge, so it only protects the stream-copy path. No probe warning is emitted in this repro, so the source appears to be taking the other branch, where the equivalent pre-flight and fallback do not exist. #99's closing note makes the same observation ("the bridge path has no equivalent pre-flight/rebuild").

Suggested direction

Run the probeWriteHeader pre-flight (or an equivalent post-failure escalation) on both audio paths, so an E-AC-3 track the mp4 muxer will not accept falls back to the FLAC bridge instead of retrying an identical configuration until the revive cap. A retry that reproduces byte-for-byte is a good signal that the retry itself is not the right recovery.

Environment

  • AetherEngine 5.23.2 (5d48ded48edf746fd329f585421bcb29fed51471)
  • iPadOS, M1 iPad; also reproduces on tvOS (Apple TV 4K 3rd gen)
  • Source: The.Old.Man.S01E01.2160p.HULU.WEB-DL.DDP5.1.H.265 — MKV, HEVC Main10 SDR 3840×2160, E-AC-3 5.1 640 kbps (profile is not JOC/Atmos)
  • Delivery: Jellyfin /Videos/{id}/stream.mkv?static=true (direct file, byte-range)
  • The same file plays instantly with no transcode from Plex and from a plain NFS share, so it is specific to this source/audio configuration reaching the muxer, not the container itself.

Activity

  1. brandomoore commented on Jul 26, 2026

    @brandomoore
    ContributorAuthor

    Dug into this further and found the framing in my original report was wrong in a way that matters. Two things worth recording.

    1. dec3 in extradata does not help. I assumed this was "EAC3-from-MKV lacks dec3", which is what the HLSVideoEngine+AudioRoute pre-flight comment describes. But probeWriteHeader rejects an EAC3 track with a valid dec3 in extradata exactly the same way it rejects one without, once the probe actually writes a moov:

    EAC3 without dec3 extradata -> -22
    EAC3 with    dec3 extradata -> -22
    AAC  with    a valid ASC    ->   0
    

    movenc builds the dec3 box from parsed packets (handle_eac3), not from extradata, so no codecpar alone can satisfy it. Which means the container is a red herring: this is not specific to Matroska.

    2. The real trigger looks like packet ordering, not codec support. I added an audio counter next to packetsWritten (which counts video only) and the failing pump reads:

    pump finished: reason=muxerFailed packetsRead=98 packetsWritten=96 audioWritten=0
    

    Zero audio packets had reached the muxer when the first segment was cut. With +delay_moov the moov is written at that first flush, so movenc had no EAC3 frames to build dec3 from and refused. When the same session runs on the FLAC bridge, audio flows perfectly well (audioWritten=782 over ~30 s) because FLAC's sample entry needs nothing from the packet stream, so the moov can be written at a cut with no audio and audio simply joins after.

    So the failure is not "this source cannot be muxed", it is "the first segment was cut before any audio arrived, and EAC3's sample entry cannot be written until it has". That also explains why the three revive attempts are identical: rebuilding the producer reproduces the same ordering.

    On fixes. I had a working local patch that makes probeWriteHeader drop +delay_moov so it fails up front and the cascade bridges to FLAC. It does fix playback on device (first frame ~700 ms, no muxer failures, no server transcode), but it is the wrong fix and I am not proposing it: since no EAC3 configuration can pass an immediate-moov probe, it would route every EAC3 source to the bridge, including MP4 sources with Atmos that stream-copy correctly today. That trades a black screen for a silent Atmos downgrade.

    The narrower direction, if it matches your read of the producer, is to hold the first segment finalize until at least one audio packet has been written when the audio codec's sample entry is packet-derived (EAC3 / AC3 / TrueHD), with a bound so a genuinely audio-less source still cuts. Happy to attempt that as a PR, though I would want a maintainer's steer on where that guard belongs relative to the video gate.

    Environment unchanged from the first report: AetherEngine 5.23.2 (also reproduced on 5.23.3), M1 iPad and Apple TV 4K, 4K HEVC Main10 MKV with E-AC-3 5.1 640 kbps over Jellyfin direct file.

  2. brandomoore commented on Jul 26, 2026

    @brandomoore
    ContributorAuthor

    Found the actual defect, and it is not where I have been looking. It is a missing guard in MP4SegmentMuxer, and the code already documents the assumption that breaks.

    flushPendingFragment refuses to emit a moov while a packet-derived audio sample entry has nothing to build from:

    // MP4SegmentMuxer.swift:512
    if audioNeedsParsedPacketForMoov, !audioPacketWritten, !moovFlushed { return }

    cutFragmentForNextSegment has no equivalent. It goes straight to:

    // MP4SegmentMuxer.swift:531-537
    _ = av_interleaved_write_frame(ctx, nil)
    _ = av_write_frame(ctx, nil)
    if !moovFlushed {
        moovFlushed = true
        _ = av_write_frame(ctx, nil)
    }

    The guard's own comment says why that was thought to be safe:

    the first audio packet primes moov here or at the first cut (which already holds the audio in the interleaver)

    That holds whenever the first segment contains audio. When it does not, the cut forces mov_write_moov to write a dec3 box it cannot build, the write fails, completedBytes == 0, the function returns nil, and advanceMuxer reads nil as a failed cut and ends the pump. From there the VOD revive path rebuilds the identical producer twice more and gives up, which is exactly the shape of the log in the first post: three attempts, packetsRead=98 every time, then source not muxable in this session.

    So audioWritten=0 is not a red herring, it is the precondition. The asset has enough leading video for the first segment boundary to arrive before any audio packet does.

    Why I am not sending a patch. I tried two and neither is right:

    • Making probeWriteHeader drop +delay_moov so the cascade bridges early. Rejects every EAC3 configuration, including MP4 sources with Atmos that stream-copy correctly today, because movenc builds dec3 from packets and never from extradata (verified: dec3 present in extradata still returns -22). Trades a black screen for a silent Atmos downgrade.
    • Applying the flushPendingFragment guard verbatim to cutFragmentForNextSegment. Its only "not now" return is nil, which the caller already treats as failure, so it wedges the same way by a shorter route.

    The shape that seems right is a third outcome for a cut, something like deferredAwaitingAudio, distinct from both success and failure, with the producer holding the current segment open until the first audio packet lands. That runs into the VOD segment plan, though, since the plan's #EXTINF durations assume the boundary lands where it was planned, and I do not know that part of the code well enough to say whether the plan should absorb the shift or the cut should be allowed to overrun once. That is a call for someone who owns the producer.

    Happy to build and test whichever direction you prefer, on the same hardware and asset as before. The audioWritten counter alongside packetsWritten in the pump summary is worth having either way, since packetsWritten counts video only and this failure is invisible without it. Say the word and I will send that as a standalone PR.

  3. changed the title [-]EAC3-from-MKV wedges the mp4 muxer at seg-0 on a fresh VOD session: probeWriteHeader pre-flight only guards the stream-copy path, so the rebuild retries an identical config to the revive cap[/-] [+]EAC3 first segment with no audio wedges the muxer: cutFragmentForNextSegment lacks the moov guard flushPendingFragment has[/+] on Jul 26, 2026
  4. added a commit that references this issue on Jul 26, 2026
  5. superuser404notfound commented on Jul 26, 2026

    @superuser404notfound
    Owner

    Fixed and released in 5.23.5 (commit 30be35c, PR #224).

    The second and third reports were right on every point, including that the container is a red herring and that audioWritten=0 is the precondition rather than a side effect. The missing guard in cutFragmentForNextSegment is exactly where the defect was, and both discarded patches were discarded for the right reasons: dropping +delay_moov rejects every E-AC-3 configuration because movenc builds dec3 in handle_eac3 from a parsed frame only, and the flushPendingFragment guard applied verbatim wedges by a shorter route, since its only "not now" return is nil and the caller reads nil as a failed cut.

    Reproduced deterministically without the original asset, using a synthetic MKV whose audio starts behind 12 s of video in file order (ffmpeg -f lavfi testsrc2 + -itsoffset 12 sine -c:v libx265 -c:a eac3 -ac 6 -f matroska). That gives the same trace: packetsRead=95 packetsWritten=93, three identical failures, then "source not muxable in this session". Worth adding for the record: the E-AC-3 bridge wedges identically, because its encoder output is also E-AC-3. Only the FLAC bridge played, which is why bridging was not an acceptable fix here.

    What shipped

    A cut now has a third outcome, deferredAwaitingAudioSampleEntry, which is neither success nor failure: nothing is written and the muxer stays intact. That is the missing state the earlier attempts were reaching for.

    Rather than holding the segment open, which would need the VOD plan to absorb a moved boundary, the recovery goes the other way. On a deferral the pump scans forward (bounded at 128 MiB or 30 s, discarding everything else) for one real audio frame and exits carrying it. The session stores that frame and rebuilds, and every muxer from then on, including the ones a seek or an audio switch creates, muxes it right after write_header. That writes moov with a genuine dec3 built from real source audio, so Atmos/JOC signaling comes along, and the primed fragment's bytes are then discarded from the staging file. The delivered segment is therefore exactly what the plan called for: no out-of-place audio sample, no disjoint track ranges, no shifted #EXTINF. The E-AC-3 stream-copy is kept.

    One trap that took a measurement to find, and that matters for anyone touching the muxer's packet order: movenc consumes the +frag_discont flag on the first packet written (mov_write_single_packet), and afterwards rewrites each track's next fragment-opening sample to start_dts + track_duration, with tfdt being cluster[0].dts - start_dts. The prime packet consumes that single opportunity, so without re-arming the flag the first real audio fragment lands at tfdt 0 regardless of where its samples belong. On the fixture, a 12 s audio start rendered 12 s early while every other signal, including a clean VERDICT: OK, looked healthy. Re-armed, fragment timestamps match an unprimed session exactly.

    finalize() picked up the same precondition, so a teardown on a never-primed muxer no longer emits two more -22s for a moov it cannot write.

    On the audioWritten counter: agreed that it is worth having, and the pump now logs the prime scan's own tally instead (prime scan captured a 2560 B audio frame after 196 packet(s) / 3 MiB (srcDts=11995)), which surfaces the same fact at the moment it becomes actionable. If a standalone counter alongside packetsWritten is still useful, a PR for it is welcome.

    Verification on this side

    6 tests in Issue222EAC3MoovPrimeTests, including the tfdt regression (verified to fail without the re-arm). Full suite 1087 green, strict-concurrency clean, CI green on macOS, tvOS and iOS. End to end on the fixture: audioTrack codec='ec-3', first frame at 0.15 s, 20 s with no stall, segments carrying seg0 video-only at 0.000s, seg3 video 11.792s with audio 11.995s, seg4 continuous, and a 40-seek burst settling at 0.00s error with no second deferral. A control fixture with healthy interleave primes nothing and is byte-for-byte unchanged in its fragment timestamps.

    A retest on the original asset would be valuable, since the fixture here is non-JOC: the dec3 box comes from a real source frame, so Atmos signaling should carry through structurally, but that is reasoning rather than a measurement. Sodalite is already pinned to 5.23.5, so a current build of it carries the fix.

    Thanks for the depth of the investigation. Landing this took reading movenc rather than guessing at it, and the reports pointed straight at the right function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions