Skip to content

Decoding

This page covers AC-3 and E-AC-3. AC-4 has a decoder of its own, iclforge::ac4::Decoder, with its own controls, presentations and objects, and none of iclforge::ac3::io reads it: see AC-4. TrueHD and MLP have iclforge::truehd::Decoder, which is lossless and has none of the output stage, concealment or programme controls below: see TrueHD and MLP.

Reading a stream: iclforge::ac3::io::scan

iclforge/ac3/io/elementary.hpp. Finds access-unit boundaries in raw bytes and reports what the stream carries, without being told. This is what a muxer needs, and deriving it from the bitstream beats asking a caller who can be wrong.

// Spans in the result point into `stream`, so it has to outlive them.
const auto scanned = iclforge::ac3::io::scan(stream);
if (!scanned) {
    fmt::printf("scan failed: %.*s\n",
                static_cast<int>(iclforge::ac3::io::describe(scanned.error()).size()),
                iclforge::ac3::io::describe(scanned.error()).data());
    return 1;
}
fmt::printf("%s, %u Hz, %d channels, %zu access units\n",
            scanned->kind == iclforge::ac3::io::StreamKind::kAc3 ? "AC-3" : "E-AC-3",
            iclforge::ac3::sample_rate_hz(scanned->sample_rate), scanned->channels,
            scanned->access_units.size());

ScannedStream::channels is what the stream renders, which for E-AC-3 folds in every dependent substream's chanmap — it is not the bed's channel count. access_units holds one span per AC-3 syncframe, or per E-AC-3 independent substream together with the dependents following it.

Both formats put bsid at bit 40 deliberately, so a reader can tell them apart before committing to a layout. iclforge::ac3::stream_bsid exposes that on its own.

A stream that arrives in pieces: iclforge::ac3::io::AccessUnitAccumulator

iclforge/ac3/io/stream_accumulator.hpp. scan, split_frames and split_access_units take the whole stream as one span. AccessUnitAccumulator applies the same boundary rule incrementally, for an HTTP body, a file read a block at a time or a flash partition read a page at a time. The caller owns the storage, appends through writable() and commit(), and takes each whole access unit from next(); nothing is allocated.

std::array<std::byte, iclforge::ac3::io::kRecommendedBuffer> storage;
iclforge::ac3::io::AccessUnitAccumulator accumulator{storage};
for (;;) {
    const auto next = accumulator.next();
    if (next.status == iclforge::ac3::io::AccessUnitAccumulator::Status::kNeedMoreInput) {
        const std::size_t got = read_from_somewhere(accumulator.writable());
        if (got == 0) {
            accumulator.finish();
        } else {
            accumulator.commit(got);
        }
        continue;
    }
    if (next.status != iclforge::ac3::io::AccessUnitAccumulator::Status::kUnit) {
        break;  // kEndOfStream, kBufferTooSmall or kError
    }
    // next.bytes is one access unit, valid until the next call
}

A unit ends where the next begins, so finish() is what closes the last one. The storage has to hold the largest access unit and the start of the frame after it: kMinimumBuffer (4 160 bytes) suits a stream whose access units are one syncframe, and kRecommendedBuffer (16 384) an independent substream with three dependents. A buffer that is too small gives kBufferTooSmall, and error() says which ScanError a kError was. resynchronised_bytes() counts the bytes skipped looking for a sync word. iclforge::ac4::SyncFrameSplitter is the AC-4 counterpart (AC-4).

Where access unit i starts: iclforge::ac3::io::access_unit_timing

Same header. ScannedStream::access_unit_samples records how many samples each access unit codes, parallel to access_units. That is always 1536 for AC-3 (§5.3.1: six blocks of 256, no other option), but E-AC-3's numblkscod lets an independent substream code 1, 2, 3 or 6 blocks (§E2.3.1.4), so an E-AC-3 access unit is 256, 512, 768 or 1536 samples long — and a stream may mix lengths.

const auto at = iclforge::ac3::io::access_unit_timing(*scanned, index);
at->start_sample;                     // samples from the start of the stream
at->duration_samples;
at->start_seconds();
at->start_in_timescale(90'000);       // MPEG-2 systems clock
at->duration_in_timescale(90'000);

Every value is computed from the absolute sample position rather than by summing per-frame increments. A frame duration is very often not a whole number of ticks in whatever timescale a container uses (1536 samples at 44.1 kHz is 34.83 ms), so a running sum drifts; computing from the absolute position keeps the error under one tick however long the stream runs. duration_in_timescale is the difference between this unit's converted start and the next one's, not the duration converted on its own — otherwise a run of durations would not add up to the start times they are supposed to.

Three lookups go with it:

Call Answers
stream_duration_samples / stream_duration_seconds How long the whole thing is
access_unit_at_sample / access_unit_at_seconds Which unit covers a position — i.e. where a frame-aligned cut lands. A position inside a unit names that whole unit; a cut is never a split
uniform_access_unit_samples The one length every unit shares, or nothing when they differ

That last one is exactly the question a fixed-duration container track can answer and a variable one cannot: iclforge::containers::mp4::AudioTrack, iclforge::containers::mpegts::AudioTrack and iclforge::containers::matroska::AudioTrack each hold a single samples_per_frame, so a stream it returns nothing for cannot be described to them without per-sample durations they do not model. forge's mkv/mp4/fmp4/ts take the figure from here and refuse such a stream rather than muxing it to a silently wrong timeline.

Changing metadata without re-encoding: iclforge::ac3::io::metadata_edit

iclforge/ac3/io/metadata_edit.hpp. dialnorm, compr, bsmod and dsurmod are delivery decisions — what a receiver is told the dialogue level is, how hard to compress on an RF output, what kind of service this is, whether the surrounds were matrixed. All four live in bsi, ahead of the first audblk, and none of them changes a coded coefficient. Re-encoding a programme to correct one costs a whole generation of lossy coding for nothing.

std::vector<std::byte> stream = /* an AC-3 or E-AC-3 elementary stream */;
const auto summary = iclforge::ac3::io::edit_stream_metadata(stream, {.dialnorm = 24, .bsmod = 2});
// summary->syncframes visited, summary->changed actually different afterwards

read_frame_metadata reports what one syncframe carries — including E-AC-3's whole mixmdate group and AC-3's two bsi downmix levels — and which of the rewritable fields it transmits at all.

A field the stream does not transmit (compr behind a clear compre, bsmod and dsurmod behind a clear infomdate) is kFieldAbsent to edit_stream_metadata, which only overwrites. insert_stream_metadata adds it, for E-AC-3:

const auto grown = iclforge::ac3::io::insert_stream_metadata(stream, {.compr = 0x40, .bsmod = 2});
// grown->bytes is a new stream; grown->grown syncframes got longer, by grown->added_bytes

Putting bits into the front of a syncframe moves every later bit, so the frame gets longer: E-AC-3's frmsiz is a free 11-bit length, and the padding that makes up the last whole 16-bit word is auxbits ahead of an auxdatae of zero, which is how the encoder pads. The audio blocks are copied bit for bit and the frame's CRC is re-stamped, so a decoder produces the same samples; what changes is each lengthened frame's size, by one or two words. Three things refuse the insert by name (kCannotInsert) rather than guess: block start information (blkstrtinfo holds each block's offset from the frame start, so every one would be wrong), auxiliary data (it is found by walking back from the tail, and padding must not come between the two), and a substream that is not independent. AC-3 cannot take it at all: its frame size is a code (frmsizecod) that fixes the bit rate, and room inside it would have to be found by walking all six audio blocks to where the audio ends. An AC-3 frame lacking the field stays kFieldAbsent.

The CRCs are the part that is not obvious. crc2 is an ordinary trailing CRC. crc1 is not: A/52 §7.10.1 puts it before the region it protects and requires the register to read zero once the first 5/8 of the syncframe has been shifted through, so it has to be solved rather than computed — iclforge::ac3::solve_leading_crc (iclforge/ac3/core/crc16.hpp) does that with a GF(2) polynomial inverse, and is the same function the encoder itself uses. restamp_crc is public for a caller doing its own bsi surgery (iclforge::ac3::signing::sign_atmos_frame is the in-project precedent) so nobody has to reimplement that solve.

Stated as limits rather than left to be discovered:

  • Only fields already on the wire can change. compr lives behind compre, and E-AC-3's bsmod/dsurmod behind infomdate; a frame that did not transmit one has no bits to overwrite, and inserting them would move every bit after it and re-frame the syncframe — which is a re-encode by another name. That is kFieldAbsent, and the answer is to encode (or transcode) with the field enabled — on this project's own E-AC-3 encoder, that means setting eac3::FrameConfig::info, which is what writes infomdate; a stream encoded with it unset carries no bsmod/dsurmod to rewrite.
  • A dependent E-AC-3 substream reports no compr whatever its compre bit says: §E3.8.5 repurposes that bit to mark the last dependent of the programme. Its eight bits are still skipped correctly; they are simply not a compr word.
  • strmtyp 2 (a convertible substream, §E2.3.1.1: previously coded in AC-3) is edited as an independent substream is. Its bsi swaps convsync for blkid and frmsizecod, which are walked and left as they are, and it sends neither the programme-mixing group nor the converter elements Table E1.2 and E1.3 gate on strmtyp 0. strmtyp 3 is reserved and refused.

A field named in an edit that no syncframe in the stream carries fails before anything is written, so the stream is either fully rewritten or left byte-for-byte alone — a metadata option that silently did nothing is indistinguishable from one that does not work.

ScannedStream also carries the raw syntax values a container writer needs but cannot re-derive: bsid, bsmod (with bsmod_present, since Annex E carries it only inside infomdate), bit_rate_code, dsurmod, mix_metadata, oba_complexity_index, and — for E-AC-3 — independent_substreams plus a SubstreamService for substreams 1–3. Those feed iclforge::ac3::io::build_codec_config_box's dac3/dec3 payload and the MPEG-TS PMT descriptors of both broadcast profiles (see Muxing & sinks). independent_substreams is an observation of which substream ids appear; it deliberately does not change how scan groups access units, which stays one-programme.

Object-layer strip

iclforge/ac3/io/object_strip.hpp. The inverse of the object encoder, at the bitstream level: it takes the EMDF/JOC object layer out of a Dolby Digital Plus stream without decoding anything.

const auto stripped = iclforge::ac3::io::strip_objects(joc_stream);
if (!stripped) {
    // describe(stripped.error()) says why
}
// stripped->bytes is a plain DD+ 5.1 stream; the bed decodes identically.

A DD+ JOC stream is an ordinary 5.1 E-AC-3 stream that happens to carry an EMDF container — OAMD positions plus JOC side information — inside the per-block skip fields the standard already requires a decoder to step over. The bed underneath is the full mix, every object already panned into it, which is exactly why an Atmos-unaware decoder can play the stream at all. So the 5.1 rendition of a JOC stream does not need re-encoding; it needs the container taken out:

  • every exponent and mantissa is copied bit for bit, so the result decodes to sample-identical PCM (the tests assert exactly that, and FFmpeg's own decode of both streams agrees);
  • the skip fields go entirely, along with TS 103 420 §8.3.1's addbsi object-audio marker, so nothing downstream — a dec3 box's Atmos extension, an HLS CHANNELS="<N>/JOC" attribute — still claims an object layer;
  • frmsiz is re-derived for the shorter frame, the auxdata padding is re-laid, and crc2 is re-stamped. Unlike an AC-3 syncframe an E-AC-3 one has no crc1 (Annex E dropped it, leaving syncinfo as the syncword alone), and crc2 is the frame's last field covering everything before it, so re-stamping is a plain forward recompute.

A rewritten frame is sized to the content it actually holds — §E2.3.1.3 makes frmsiz an arbitrary per-frame word count, unlike AC-3's index into Table 5.18. So the output is smaller than the input, which is the point for a delivery rendition, but a constant-rate input does not stay constant-rate: alongside the container, whatever auxdata padding the encoder used to hit its target rate goes too. A frame with nothing to remove is copied byte for byte.

The container is removed, not emptied: an EMDF container with no payloads would still signal an object layer for a stream that no longer has one, and this project's rule is that a stream carries objects or omits the container entirely (see Atmos & JOC).

Frames with no object layer pass through byte for byte — including frames of a bitstream shape this build cannot rewrite, since a frame with neither the addbsi marker nor a skip field has nothing to strip whatever its shape. A frame that does carry an object layer in a shape the frame walker (iclforge/ac3/emdf/frame_layout.hpp) does not map is refused with kUnsupportedFrame rather than passed through, because passing it through would hand back a stream still carrying the objects this function promises to remove. An AC-3 stream is refused outright (kNotEac3): Annex E is where substreams and skip fields live.

This is the inverse of iclforge::ac3::signing's in-place EMDF rewrite and, like it, needs no key — taking a container out is not authenticating one. Both share one bit-accurate frame walk (iclforge::ac3::emdf::walk_frame) so the two cannot drift apart.

forge strip-objects in.ec3 out.ec3 is the command-line front end, and forge fmp4 … fallback-51 uses it to write the paired 5.1 HLS rendition Apple's authoring requirements ask for beside an Atmos one.

Decoding

iclforge/ac3/decoder/decoder.hpp. Two classes, one per generation.

// AC-3: one syncframe per access unit. For E-AC-3 use iclforge::ac3::Eac3Decoder and
// decode_access_unit, which applies the §E3.8.2 render across substreams.
iclforge::ac3::FrameDecoder decoder;
for (const auto unit : scanned->access_units) {
    const auto decoded = decoder.decode_frame(unit);
    if (!decoded) {
        fmt::printf("decode failed: %.*s\n",
                    static_cast<int>(iclforge::ac3::describe(decoded.error()).size()),
                    iclforge::ac3::describe(decoded.error()).data());
        return 1;
    }
    samples += decoded->channels.front().size();
}

Full program: examples/decode_stream.cpp.

Both decoders keep overlap-add state, so feed frames in order. Eac3Decoder keys its state on strmtyp and substreamid together, because a dependent's id lives in its own numbering space — stepping through syncframes by hand with decode_substream gives the same audio as calling decode_access_unit.

DecodedFrame reports the metadata separately from applying it, which is the point of the decoder as a check on the encoder: a test can assert on the dynrng words the encoder chose and on the level change they cause, and those are two different claims.

DecoderConfig Default Notes
drc_scale 0.0 §7.7.1 partial compression. 0 ignores dynrng; 1 applies it as encoded. A/52 says a consumer decoder should default to applying it — this one defaults to 0 because a reference that silently rescales its output is not a reference.
drc_boost_scale none std::optional<double>: the same scaling for boost alone (a dynrng word above unity), where it should differ from the cut's. For example, boost 0 keeps quiet passages quiet while drc_scale 1 still brings loud ones down. Unset, boost is scaled by drc_scale too. Like drc_scale, it applies under OperatingMode::kCustom only.
fast_imdct true The fast inverse MDCT — the same fold the encoder's forward fast path uses — instead of the pseudocode's direct O(N²) sum against a 320 KiB tabulated matrix. Covers every inverse a decode runs: both decoders' PCM reconstruction, the three per-block inverses inside eac3::ecpl_channel_spectrum, and oba::joc::reconstruct's per-object synthesis. Decodes 4.5–4.7× faster, agreeing with the direct form to 214.9 dB SNR (AC-3) / 284.7 dB (E-AC-3) over 180 s of stream. It never reaches an encoder — the encoder-internal inverses read eac3::FrameConfig's own fast_mdct — so nothing about encoded output depends on it. false selects the direct reference form, the oracle the fast path's tests validate against; forge exposes the pair as mode=performance / mode=reference.
heavy_compression false §7.7.2: prefer compr where it exists, falling back on dynrng for syncframes that carry none.
output all off The §7.8 output stage — dialnorm, downmix, operating mode. See below.
concealment kNone §7.10: what to do with a frame that will not decode. See below.
fast_mdct true The §7.9.4 forward MDCT fold, for JOC bed analysis under oba::joc::Domain::kMdctBand only — the one place a decode runs a forward transform, since §6.6.6's matrix combines the transmitted coefficients against the bed re-expressed in the domain the matrix was estimated in. No effect under the default kQmf, whose filterbank has only the one evaluation. false selects the direct §8.2.3.2 form, which is oba::joc::reconstruct's own default and what its fast-path tests validate against.
joc_domain oba::joc::Domain::kQmf Which domain JOC object reconstruction (above) runs §6.6.6's matrix in: kQmf is §7.1's 64-band complex filterbank, what the clause describes and what a licensed decoder runs; kMdctBand is the cheaper 512-sample-MDCT approximation this project used before the filterbank existed, correct only against a matrix estimated the same way (AtmosConfig::joc_domain on the encode side). The two have different algorithmic delay — oba::joc::reconstruction_delay(domain) — so a caller comparing object_audio against a known source has to shift by it.
trace nullptr AC-3 self-check (FrameDecoder): where the decoder records what it derived per block, for iclforge::ac3::verify to diff against the encoder's own model. See below.
eac3_trace nullptr The E-AC-3 counterpart (Eac3Decoder), one whole access unit rather than one frame. See below.
programme none std::optional<int> (§E2.3.1.2). Which independent substream's programme decode_access_unit renders when a stream carries several — they are alternatives, not layers. std::nullopt renders whichever programme each call's access unit belongs to; set to an id and an access unit belonging to any other is skipped without being decoded at all. Ignored by decode_substream, which sits below the programme layer. See below.
syntax nullptr FrameSyntax* (iclforge/ac3/decoder/syntax_trace.hpp): which coding tools each block used and what exponent strategy each stream carried, recorded on the way past. Written by both decoders, unlike trace/eac3_trace — the Annex E tools are most of what makes it worth having. Filled incrementally, so a refused frame still leaves behind everything read before the refusal.
skip_reconstruction false Parse every field exactly as a full decode does, but stop short of turning the coefficients into audio: no inverse transform, no overlap-add, no JOC object reconstruction, and no per-access-unit channel combination. The metadata (and any trace above) is identical to a full decode's; channels and object_audio come back empty. What forge probe runs a whole file through. Note what it does not skip: the mantissas are still read, because the bit position of every field after them depends on it.
skip_object_reconstruction false Decode the bed and leave the objects alone: no JOC reconstruction, object_audio and object_indices come back empty, and everything else (the bed's PCM, object_metadata, the trace) is what a full decode gives. Unlike skip_reconstruction it still renders audio, the 5.1 downmix the objects were coded against. It exists for memory: the reconstruction state is 147,504 bytes on a 32-bit target, more than the largest contiguous block an ESP32-S3 decode leaves free.
diagnostics, diagnostics_context nullptr, nullptr A plain function pointer and the pointer passed to it, called for the recoverable events the return value does not carry: a CRC that failed, and an EMDF payload id the decoder does not interpret. One branch per occurrence when unset.

Block-granular output

Both decoders have three output forms. decode_frame / decode_access_unit return the PCM in vectors of their own; decode_frame_into / decode_access_unit_into write it through spans the caller owns, a frame per channel; and decode_frame_by_block / decode_access_unit_by_block hand it to a BlockSink — a non-owning reference to any callable, so passing one allocates nothing — one PcmBlock at a time: kSamplesPerBlock (256) samples of every output slot, in the order the _into form writes, delivered once the whole frame or unit has decoded and the output stage has run. The samples are the _into form's exactly, and a downmix arrives as one or two slots. The spans view the decoder's own storage and are valid only inside the call that hands them over.

iclforge::ac3::Eac3Decoder decoder;
const auto sink = [&](const iclforge::ac3::PcmBlock& block) {
    // block.index of block.blocks; block.channels[slot] is 256 samples of
    // the rendered layout's slot. Interleave it into a DMA ring one block deep.
    ring.push(block.channels);
};
for (const auto unit : scanned->access_units) {
    const auto decoded = decoder.decode_access_unit_by_block(unit, sink);
    if (!decoded) { /* as above */ }
}

What the form is for is a caller that cannot afford a frame: on an ESP32-S3 a 7.1.4 programme's frame is 73,728 bytes of the part's free SRAM, and a DMA ring needs a block. For E-AC-3 nothing is copied on the way out — each slot is a view onto the substream vector that supplies it, a dependent's over the bed's where §E3.8.2 says it replaces it — so the assembly copy the _into form pays goes as well. AC-3 has no per-substream storage to hand out views of, so its form keeps one frame of its own (six channels, sized once); the saving there is the caller's. The §3.7 hold-back's std::nullopt, a skipped programme and skip_reconstruction leave the sink uncalled; a concealed frame is delivered through it like any other. The bare-metal probe decodes every fixture through these forms and holds no PCM at all.

An access unit's objects come through the same block. PcmBlock::objects is a view per JOC output onto the unit's own reconstruction, cut to the block, and object_indices and object_metadata mean what DecodedAccessUnit's do; all three are empty for an AC-3 frame, for a bed-only decode (skip_object_reconstruction) and for a unit with no object layer. A sink placing objects on loudspeakers therefore needs no frame of anything - the value form's object_audio is a frame of copies per object, and this is none. The probe's eac3_atmos_render row is that sink: iclforge::spatial::pan_direction for the gains, once per object per unit, and a block of float sums per target.

The output stage

iclforge/ac3/decoder/output.hpp. Everything between "the coded channels have been reconstructed" and "these are the samples a listener hears": dialnorm normalisation, the §7.8 downmix, and §7.7's two named operating modes. It is off by default — a decoder configured the way the examples above configure it emits the coded channels untouched, sample for sample — because the decoders exist first as a check on the encoder, and a stage that silently re-levelled or re-folded their output would destroy that.

iclforge::ac3::FrameDecoder decoder{{
    .output = {.target = iclforge::ac3::DownmixTarget::kLoRo, .mode = iclforge::ac3::OperatingMode::kLine},
}};
// decoded->channels now holds two channels, Lo then Ro, at the -31 dBFS
// reference. acmod/lfe still describe what was CODED.

The stage's per-sample arithmetic runs in the decoder's scalar type - double in every ordinary build, float under the minimum-footprint profile, whose targets have a single-precision FPU at best - and its gains and mix coefficients are double everywhere. That profile's probe holds two folded fixtures to their levels on the target.

OutputConfig Default Notes
target kAsCoded kLoRo (§7.8.1's plain stereo fold), kLtRt (§7.8.2's Dolby Surround compatible fold), kMono (§7.8's output_mode == 1/0 branch), or no fold at all.
mode kCustom kLine (§7.7.1: dialnorm plus the full transmitted dynrng) or kRf (§7.7.2: compr with RF mode's 11 dB, falling back on dynrng per §7.7.2.1, plus downmix overload protection — see RF mode's level). Both override drc_scale/heavy_compression rather than composing with them — that is what makes them modes rather than two more switches.
apply_dialnorm false §5.4.2.8 normalisation onto the −31 dBFS reference. Both named modes imply it, so this only has to be set for kCustom.
mix_lfe false §7.8 makes the LFE's contribution optional and this decoder drops it by default.
ltrt_phase_shift true Whether Lt/Rt's surround sum is really phase shifted 90°, or only polarity-inverted.
rf_ceiling 1.0 What kRf holds the fold under, as a linear sample magnitude.
mix_override all unset MixLevelOverride: levels to fold with in place of the stream's, one field at a time, in MixLevels' fields and units. A set field replaces what the stream carried, or the default that stood in for it. An LFE level is honoured only where the stream allows LFE mixing at all.

The matrix comes from the stream's own mix levels unless mix_override replaces them, and never from constants chosen here. AC-3 carries two coarse levels in bsi (cmixlev, surmixlev; §5.4.2.4/§5.4.2.5) and E-AC-3 carries a richer group inside mixmdate — separate Lt/Rt and Lo/Ro centre and surround levels plus an LFE mix level. Both decoders now keep those and report them (DecodedFrame::cmixlev/surmixlev, DecodedSubstream::mixing), distinguishing "absent" from "present, and says the default"; iclforge::ac3::mix_levels() turns either into the coefficients the stage needs, applying §7.8's own fallbacks where a field is simply not there: -4.5 dB and -6 dB for an AC-3 stream whose bsi has no level to read, and -3 dB and -3 dB for an E-AC-3 stream that sends no mixmdate, which is what Dolby's decoder folds such a stream at.

MixLevels::preferred passes on dmixmod, the fold the content was mixed for (Table D2.2) — E-AC-3's mixmdate, or an Annex D stream's xbsi1 (see below) — without acting on it: target is always what the caller asked for. A caller that wants to follow the stream uses iclforge::ac3::automatic_stereo_target(acmod, preferred), A/52 §D3.1.1's automatic selection: kLtRt when the stream prefers Lt/Rt, kLoRo for every other code — kNotIndicated, and kReserved (Table D2.2's 11, which A/52:2018 and ETSI TS 102 366 V1.4.1 both leave reserved for AC-3 and E-AC-3 alike, and which §D2.3.1.2 allows a decoder to read as "not indicated"). acmod gates the whole field the same way: Table D2.2's own note leaves dmixmod's meaning reserved below 3/0 — at 1+1, 1/0 and 2/0 — whatever code it carries, so those acmods get kLoRo regardless of preferred. forge's downmix=auto is built on it.

§7.8.1's normalisation — "attenuating all downmix coefficients equally, such that the sum of coefficients used to create any single output channel never exceeds 1" — means a fold of plain coefficients can never be louder than the loudest coded sample. That is why there is no soft-clip anywhere in this path.

The one exception is Lt/Rt with its phase shift: a phase shifter preserves energy, not peak, so that fold can come out louder than its inputs were even though every coefficient is normalised. That follows from what §7.8.2 asks for rather than from anything decided here — ltrt_phase_shift = false and kRf are the two ways to get a bounded output, and the second is the one that guarantees it.

Lt/Rt's surround sum is phase shifted, through a 127-tap Hilbert transformer, with the direct path delayed to match; OutputStage::latency_samples() reports the resulting 63 samples of output delay, and is zero for every other configuration. ltrt_phase_shift = false selects the sign-only matrix a lot of hardware implements instead — no latency, at the cost of the surround sum no longer being in quadrature.

RF mode's overload protection. §7.7.2's compr guarantees a ceiling for the mono downmix, not for whichever fold was actually asked for, and §7.8.1's normalisation does not cover the LFE (§7.8 treats its contribution as an addition, at up to +10 dB). kRf closes that: a per-frame gain, ramped across the frame rather than stepped at its boundary so it cannot click, backed by a clamp so the ceiling is true and not merely likely. OutputStage::rf_protection_db() reports the attenuation currently being held, so a test can assert the limiter engaged rather than only that the output stayed under the ceiling — which silence also satisfies.

RF mode's level

A/52 describes what RF mode is for (§7.7.2.1) and how to read compr (§5.4.2.10, §7.7.2.2), but gives no output level for the mode and no offset anywhere; dialnorm itself is described only as the level a reproduction system uses to set its volume (§5.4.2.8, §7.6). The level decoders use comes from Dolby's own practice: line mode puts dialogue at −31 dBFS and RF mode at −20 dBFS, 11 dB higher.

The 11 dB are the decoder's. kRf normalises dialnorm onto −31 dBFS as kLine does, then applies each compr word with 11 dB on top of the word's own gain (meta::kRfModeGainDb). A syncframe with no compr word falls back on dynrng and gets no 11 dB, so a stream that carries no compr at all takes the same gains in kRf as in kLine. kCustom with heavy_compression applies the word's §7.7.2 gain alone, which is what FFmpeg's heavy_compr does too. For an E-AC-3 program with dependent substreams the compr word is the last dependent's, applied to every substream of the program (§E3.8.5); an §E2.3.1.2 AC-3 core keeps its own.

All of this was measured against the Dolby Reference Player's decoder (dlbac3dec, drc-mode=rf against drc-mode=line):

Stream Reference Player line / RF this decoder line / RF
DEE AC-3 2.0 music, 192 kbit/s, dialnorm 19, compr 0xFF −30.70 / −19.70 LUFS −30.70 / −19.90 LUFS
DEE E-AC-3 2.0 music, 96 kbit/s, dialnorm 19, compr 0xFF −30.70 / −19.70 LUFS −30.70 / −19.90 LUFS
DEE AC-3 5.1, 448 kbit/s, dialnorm 11, compr 0xFF −30.80 / −19.80 LUFS −30.70 / −20.00 LUFS
DEE E-AC-3 5.1, 256 kbit/s, dialnorm 11, compr 0xFF −30.80 / −19.80 LUFS −30.70 / −20.00 LUFS

Before RF mode carried the 11 dB this decoder's RF column read −30.90 and −31.00 LUFS. What the Reference Player showed besides:

  • Its RF output is line output plus 11 dB plus the word, in every syncframe that carries one, and line output in every syncframe that does not; a stream spliced from the two switched between +11.29 dB and 0.00 dB at the splice.
  • Dolby's encoder writes its words on that basis. With its RF profile set to none, DEE writes 0xFF (−0.28 dB) for dialogue-level material at dialnorm 31 and at dialnorm 20, and cuts only where dialnorm normalisation plus 11 dB would put the mono downmix over full scale — by 6.6–7.2 dB for clicks peaking at −1.4 dBFS at dialnorm 28. A named RF profile adds its own boost and cut around that. meta::HeavyCompressor writes its words the same way.
  • For a 7.1 stream it applied the last dependent substream's word to all eight channels, as §E3.8.5 says, and the independent substream's word when asked for 5.1 or 2.0 output.
  • Its arithmetic lands within 0.3 dB of an exact 11 dB, depending on the word: the gains it applies fit 2N·(1 + f), with N + f the word read as a signed 4.4 number of octaves plus 11/6. That is 11.29 dB over line mode for a word of 0x00 and 10.98 dB for 0xFF, where this decoder applies 11.00 and 10.72 dB.
  • Its dialnorm normalisation divides by 2n/6 for a dialnorm n dB above the reference, where this decoder divides by 10n/20, the dB A/52 states: −11.04 dB against −11.00 dB for dialnorm 20.
  • Its Lo/Ro fold in line and RF mode leaves out §7.8.1's normalisation, so for a 3/2 stream with −3 dB centre and surround levels it sits 7.66 dB above this decoder's fold in both modes.

Wide E-AC-3 layouts. §7.8 defines folds from the eight AC-3 acmods and says nothing about the layouts Annex E's chanmap can express: a 7.1.4 programme has no §7.8 fold, because §7.8 predates anything that could code one. OutputStage's layout-aware overload therefore reduces a rendered Table E2.5 layout to the nearest acmod layout first — each extra location seated where it obviously belongs (a wide left is a left, a rear surround is a surround, a top front left is a left), at −3 dB where it shares a seat — and then applies §7.8 proper. That reduction is an extension beyond the spec and is labelled as one in the source; it is an exact identity for every plain acmod bed, which is the case that must not change.

Verified against FFmpeg's -ac 2 decode of the same stream: at 3/2 with cmixlev −3 dB and surmixlev −6 dB the two agree to 119–121 dB SNR at zero lag, differing only by a single scalar of 1/2.20711 — exactly §7.8.1's normalisation divisor for those levels (1 + 0.7071 + 0.5), which this decoder applies and FFmpeg does not.

Annex D streams (bsid 6). An AC-3 stream written with Annex D's alternate syntax can carry an xbsi1 group: separate Lt/Rt and Lo/Ro centre and surround levels (Tables D2.3–D2.6) and a preferred stereo downmix, dmixmod (Table D2.2). A/52 §D3 makes decoding them optional, and FrameDecoder does. Following §D3.1.2 (ETSI TS 102 366 clause D.2.1.2), the Lt/Rt fold uses ltrtcmixlev/ltrtsurmixlev, and the Lo/Ro and mono folds use lorocmixlev/lorosurmixlev, in place of bsi's cmixlev/surmixlev; mono takes the Lo/Ro pair because §7.8.2 defines it as Lo/Ro summed. A bsid-6 stream still carries the two bsi levels, for decoders that do not read xbsi1 (§D4.2.1). A stream with no xbsi1 group, whether bsid 8 or bsid 6 with xbsi1e clear, still folds with cmixlev/surmixlev. MixLevels::preferred takes dmixmod for 3/0 and wider only, the acmods Table D2.2 defines it for. A surround level Tables D2.4/D2.6 reserve reads as −1.5 dB, as §D2.3.1.4/§D2.3.1.6 direct, and DecodedFrame::alternate_bsi reports it that way. Annex D adds no LFE mix level, so mix_lfe folds the LFE in at §7.8's +10 dB for either bsid. A caller folding a DecodedFrame itself gets the same levels from iclforge::ac3::mix_levels(acmod, cmixlev, surmixlev, alternate_bsi).

Karaoke streams (Annex C, informative). bsmod 7 with an acmod above 1/0 marks a karaoke programme (iclforge::ac3::meta::is_karaoke; DecodedFrame::bsmod and acmod say it). Its channels are L and R, a guide melody M where a centre would be, and one or two vocals V1 and V2 where the surrounds would be (Table C.2.1), with cmixlev/surmixlev re-purposed as their levels. A karaoke-aware two-channel decoder is the Lo/Ro downmix, which this output stage is already - Table C.2.2's 2/0 column is §7.8.1's matrix cell for cell. The three-channel reproduction is OutputConfig::karaoke = KaraokeReproduction::kAware (off by default, like everything here) at DownmixTarget::kAsCoded: for a karaoke stream with something to reproduce - 2/1, 3/1, 2/2 or 3/2 - FrameDecoder returns L, C, R and then the LFE when there is one, where

coded Lk Ck Rk
3/2 (L M R V1 V2) L + slev V1 M R + slev V2
3/1 (L M R V1) L M + slev V1 R
2/2 (L R V1 V2) L + slev V1 - R + slev V2
2/1 (L R V1) L slev V1 R

slev is the stream's Lo/Ro surround level (mix_levels().loro_slev, so MixLevelOverride and Annex D's lorosurmixlev apply as they do to a fold), and every coefficient is scaled down by the largest output's sum when that exceeds 1 - §7.8.1's way, one factor for all three outputs and the LFE, so the melody keeps its level against the music and the LFE its level against the three (the LFE is in none of Annex C's equations, and Dolby's decoder, which scales nothing, keeps it where the mix put it too). DecodedFrame::acmod and lfe still describe what was coded; output_channel_count(config, acmod, lfe, karaoke) says how many channels come back, and output_mode(config, acmod, lfe, karaoke) which layout they are in, as an OutputMode (a coding mode and whether the LFE follows): 3/0, with the LFE after R, for this reproduction, 2/0 or 1/0 for a fold, and the coded mode otherwise. A caller that lays the channels out from acmod, as a renderer does, asks it, so that the three channels are not placed as the coded 3/2. MixLevels::karaoke is how the decoder tells the stage, and is set from the frame's own bsmod by FrameDecoder, and by Eac3Decoder from a programme's (is_karaoke_programme() in decoder.hpp: one independent substream flagged karaoke, no dependent substream, no object layer; A/52 defines no E-AC-3 reproduction, and Dolby's decoder applies Annex C's to it, as does this one, at mixmdate's Lo/Ro levels or -3 dB without it). For E-AC-3, DecodedAccessUnit::layout still names the coded bed, as under a fold, and the channels are the reproduction's. 3/0 (L M R) and 2/0 are returned as coded, kLtRt is left as the Lt/Rt fold it is (Annex C defines none), and RF mode's ceiling holds over all three outputs. The forge decode form is karaoke.

The karaoke-capable decoder (C.2.3.2) lets the listener choose none, one or both vocals: KaraokeReproduction::kCapable with OutputConfig::karaoke_vocals set to a KaraokeVocals (kNone, kV1, kV2, or kBoth for Table C.2.3's V1+V2). The coefficients are the table's defaults, applied and scaled down together exactly as the aware ones are:

choice 3/0 reproduction (kAsCoded) 2/0 reproduction (kLoRo, kMono)
none L, M in the centre, R L + clev M, R + clev M
V1 V1 in the centre with M V1 at 0.7 in both, with M at clev
V2 V2 in the centre with M V2 at 0.7 in both, with M at clev
V1+V2 V1 into L, V2 into R, at unity, M in the centre V1 into L, V2 into R, at unity, with M at clev

The 2/0 column takes the place of the Lo/Ro fold for a karaoke stream with an acmod above 2/0 (a listener who chose no vocals is not handed them by a downmix), and mono is that column's left and right summed (C.2.3.1). "0,7" is §7.8's 0.7071, the same factor Table C.2.2 writes as "0,7 x slev", which has to be for Annex C's remark that a Lo/Ro downmix is the aware 2/0 reproduction to hold; clev is mix_levels().loro_clev, so MixLevelOverride applies. The capable vocals are at the listener's levels and not the stream's surmixlev, so the stream's own surround level is not read. A choice of a vocal the stream does not code (V2 of a 3/1 stream) reproduces none of it, and V1+V2 over a stream with one vocal puts V1 into the left alone, as the table's column does. kLtRt is left as the Lt/Rt fold in both modes. No stream from anyone else exists to check any of this against, so it is held to the annex's tables - by impulse for every coefficient, transcribed from the PDF into the tests, and over real coded streams sample for sample.

The annex's "additional flexibility" is the capable decoder's re-levelling of M, V1 and V2: OutputConfig::karaoke_melody_gain, karaoke_vocal1_gain and karaoke_vocal2_gain, linear gains that multiply the table's coefficients for that part, 1.0 each by default (the table as it stands, bit for bit) and 0.0 a mute. They are read under kCapable alone - at the 3/0 and at the 2/0 reproductions - and the aware column (Table C.2.2) ignores them, whatever they hold. They come before the scale-down above, so raising one part lowers the rest, the music included, by the same factor, and a muted part is out of the sums as an absent one is; L and R are not moved, a part the stream does not code has nothing for its gain to act on, and the LFE is never touched. A value that is not a finite number of 0 or more is a mute. What to do with the surround outputs, and moving (not re-levelling) a part, are left to the implementation and are not offered.

A control for a person (Hearth's Karaoke page and settings, the Sendspin extension's karaoke_melody_db, karaoke_vocal1_db and karaoke_vocal2_db, a sink's decoder) speaks dB against the table and not these linear gains. karaoke_gain_from_db() is the one conversion: kKaraokeMinLevelDb (-24) to kKaraokeMaxLevelDb (+12), the bottom of which is off (0.0), 0 dB exactly 1.0, and a value that is not a number 0 dB, the table's, where the gains themselves would mute it. karaoke_level_db() holds a level to that span.

A §E2.3.1.2 legacy core inside Eac3Decoder. An AC-3 syncframe (bsid <= 8) present in an E-AC-3 stream is processed as independent substream 0, and its channels become the bed §E3.8.2 assembles a wider programme from. That core has no mixmdate to carry — mixing metadata is Annex E syntax an AC-3 syncframe cannot express — so apply_output() folds the ASSEMBLED programme with exactly the levels described above: the core's own bsi cmixlev/surmixlev, and Annex D's xbsi1 group in place of them where a bsid-6 core sent one. DecodedSubstream and DecodedAccessUnit carry bsid alongside cmixlev/surmixlev/alternate_bsi for exactly this — bsid says which of that trio or mixing the fold should read, since a bed only ever populates one or the other. A dependent's own mixmdate, if it sent one, is not consulted either way; only the bed's ever describes the programme, the same rule a non-legacy-core stream already followed.

The E-AC-3 decoder reads every Annex E coding tool — standard coupling (§E3.3), enhanced coupling (§E3.5), spectral extension (§E3.6), the adaptive hybrid transform with GAQ (§E3.4), and transient pre-noise processing (§3.7) — individually or stacked together, at every channel layout including 7.1.4. That includes Annex E's default coupling band structures: a block that transmits no band structure of its own falls back to Table E2.12 (standard coupling) or Table E2.13 (enhanced coupling) and decodes normally. Enhanced coupling's ecplangleintrp (§3.5.5.3's linear interpolation between band-centre angles) decodes too — the encoder decides per frame whether it reconstructs closer to the real content than direct per-band application.

A transient pre-noise correction is counted from the first sample of the frame's PCM as A/52 counts it — block 0's new samples, one block (256 samples) into the frame's decoded output — and reaches up to 1528 samples back from its transient, which a frame may place in a later frame: up to 4092 samples past that origin. The Dolby Encoding Engine does exactly that at its lower stereo and 5.1 rates, putting most of its transients in the next frame; Dolby's own decoder corrects them on the same origin, which is how the origin was settled (see iclforge/ac3/decoder/transient_prenoise.hpp). This decoder applies each correction once the frame its transient falls in has decoded, so every reach the syntax can express decodes.

Transient pre-noise processing has one API consequence worth knowing: once a stream turns it on, Eac3Decoder::decode_substream holds 1536 samples back — one frame at six blocks a syncframe, six at one block — and returns each frame once no correction still to come can reach it, returning std::nullopt while that first 1536 samples builds up. Call Eac3Decoder::flush() once at end-of-stream to collect whatever is still held back; the corrections whose transient the stream ended before are applied to what did arrive, and an identity holding several short syncframes gets them back as one substream. A stream that never uses the tool is completely unaffected: every call returns immediately as before.

Eac3Decoder::decode_access_unit builds on the same convention rather than refusing it: an access unit needs every one of its substreams ready in the same call, and the tool is a per-substream flag, so one substream turning it on does not have to stall the others. Whichever substreams already released this call are queued (per substream identity, oldest first) until the lagging one catches up, so nothing already-decoded is discarded or, worse, silently paired with the wrong instant in time — a dependent that never uses the tool can keep releasing every call while an independent that does falls one frame behind, and each call still assembles the correct pairing once every identity has something waiting. flush() drains both caches, one substream per identity: whatever decode_substream itself is still holding, and whatever substream results are still queued waiting for a sibling.

Block switching (§8.2.2/§7.9) decodes on both, and is reported back: DecodedFrame::blksw / DecodedSubstream::blksw gives, per full-bandwidth channel per block, whether that block used the short transform — the same tier of diagnostic as dynrng, exposing what the encoder decided rather than only applying it.

Dual mono (acmod 0, "1+1") decodes on both: it's two independent single-channel programmes sharing one syncframe rather than a channel layout, so DecodedFrame/DecodedSubstream carry a second dialnorm2/compr2 alongside the usual fields, and each channel's §7.7 gain is applied from its own words — Ch2 is never affected by Ch1's compression or vice versa. Eac3Decoder::decode_access_unit's layout comes back empty for it (DecodedAccessUnit::acmod == kDualMono), since there's no Table E2.5 location for "the second programme" to render onto — the two channels come back in coded order (Ch1, Ch2) instead.

The output stage's own §5.4.2.8 normalisation follows the same rule: OutputStage::apply's optional dialnorm2 parameter, threaded through from DecodedFrame/DecodedSubstream/ DecodedAccessUnit, levels Ch2 by its own reference under kLine/kRf/apply_dialnorm rather than by Ch1's dialnorm — the two programmes are unrelated, and an encoder sizes Ch2's compr2 on the assumption Ch2 is normalised by dialnorm2.

Delta bit allocation (§7.2.2.6) is decoded like any other transmitted parameter: both decoders carry per-channel state across a syncframe's blocks and apply it to the masking curve before computing bap, on the coupling channel as well as the full-bandwidth ones. Both encoders emit coupling-channel delta (cpldeltbae, whenever the coupling channel has segments to send) — E-AC-3 no longer skips it under coupling either. How corrections are chosen, and when they are dropped, is covered in Encoding AC-3.

Dither substitution (§7.3.4) decodes on both as well: a bin allocated zero bits (bap 0) reconstructs as a true zero when its channel's dithflag is clear, and as a dither sample when it is set. A coupled channel's shared bap-0 bins are dithered independently per receiving channel, after decoupling — §7.3.4's own uncorrelated-noise requirement — never by dithering the shared coupling-channel coefficient itself. The generator's state persists across frames, like the overlap-add state, so a long stream's substituted noise does not repeat every syncframe.

fscod2 (the Annex E half sample rates — 24, 22.05, 16 kHz) is decoded like any other rate: the reduced rate reuses the same bit-allocation tables as its double-rate parent (§E2.3.1.4), so nothing else about decoding changes.

The object layer

An Atmos-in-DD+ stream carries OAMD and JOC payloads in an EMDF container tucked into a block skip field. Eac3Decoder reads it whenever it is there: DecodedSubstream::object_metadata is the decoded programme (std::nullopt for plain E-AC-3, and equally for a container that was found but could not be read — a failure there never fails the surrounding frame, which is the whole point of EMDF), and object_audio is JOC's reconstructed per-object waveforms.

object_indices says what each object_audio entry is: an index into the payload's own object order (bed channels, then ISF, then dynamic objects), which is what oba::joc_object_indices() computes for the programme. For a dynamic-object-only programme — what this project's own encoder writes — entry i is object_metadata->objects[i]; for a bed programme it names the bed channel instead, which oba::bed_labels() turns into a speaker label. forge decode <in> <out.wav> <objects_dir> writes one WAV per entry.

What the parsers read is deliberately much wider than what the encoder writes, because real streams are wider. On the OAMD side: any number of metadata update blocks at any sample offset and ramp duration; object size, zone constraints, elevation gating, snap, screen reference, distance, explicit priority and Table 18's gain-reuse; positions coded differentially against the previous block; inactive objects; several bed instances, standard or non-standard; programmes carrying an intermediate spatial format; the trim_element and the extended_object_element - object divergence, and the extended precision positions that refine x and y by up to two fifths of the standard 1/62 step and z by two fifths of 1/15 (§5.6.1.1.8-.14, Tables 43-46). A refinement belongs to the update block that carries it and is not what the next block's differential coding builds on, which the standard says is the standard-precision value; an object that is not active sends none. The extended precision positions are decoded from the text alone: no outside stream carries one (DEE's channel-based-immersive streams have no dynamic objects), so which axis a presence bit names follows the convention the other arrays of this payload were checked against, not a stream of its own. An oa_element with an id this decoder does not know is skipped by its own oa_element_size and named in DecodedProgram::skipped_elements, rather than costing the payload — which is exactly what that size field is for. On the JOC side: all five of Table 47's downmix configurations, any clip gain, and per-object band count, quantizer, sparse mode, interpolation slope and data-point count. The EMDF reader parses the whole of §H.2.1.3's payload configuration and reports it on DecodedPayload::config rather than insisting on the one shape TS 103 420 Table 56 mandates — real Dolby streams do not restrict themselves to it even for their own object payloads.

What is still refused, and why each one has to be:

Refused Reason
oa_md_version_bits other than 0 §5.6.0.1 defines no field layout for another version, so every offset after it would be a guess.
intermediate_spatial_format_idx 6 or 7 Table 11b reserves them and gives them no object count, so the bed/ISF/dynamic split cannot be worked out.
joc_dmx_config_idx 5–7 Table 48 gives them no channel count, so joc_data has no loop bound.
joc_ext_config_idx ≠ 0 Table 49 reserves every value and §6.2.1 gives joc_ext_data() no syntax and no length — there is nothing to read and nothing to skip.
emdf_version ≠ 0 §H.2.2.2 defines the container's fields only for version 0.
protection_length_primary = 0b00 Table H.2.5 reserves it, so it names no width to skip.

joc_clipgain (§6.3.3.2) is computed onto FrameParameters::clip_gain and applied — correctly: the published equation reads as ambiguous only through plain text extraction, which drops a "-4" bias the exponent actually carries; rendering the PDF page as an image (both the 2016 and 2018 editions) shows 1 + (y/32) * 2^(x-4), which matches the clause's own stated [1; 8,75] range exactly at both ends. No clause in TS 103 420 says where in the decode chain the gain belongs, but that was confirmed empirically (2026-09-22, Dolby Reference Player oracle): it multiplies reconstructed object PCM, never the bed — the player's raw bed output matched this project's own bed decode at correlation 1.0000 regardless of clip gain, while its object output tracked the formula's prediction to within ~0.03 dB with the OAR's own limiter disabled. The multiply happens once in reconstruct()'s own dispatcher, on the per-object PCM it gets back from whichever domain function it calls — every caller already passes FrameParameters through unchanged, so one post-multiply there covers all of them with no duplication.

Separately, and permanently rather than as a gap: Table 47's two "90 degree phase shift" downmix configurations reconstruct like their unshifted siblings — the shift is a property of how the downmix was built, and §6.6.6 says nothing about undoing it before matrixing (the text mentions it only in the configurations' names), so nothing is undone. A DEE stream of configuration 3 (testdata/object-fixture/dee_joc_514.ec3) reconstructs each object as its own channel through exactly this path.

Reconstruction needs the downmix JOC asks for. Table 47's three widest configurations need a dependent substream's extra channel pair before they can reconstruct at all — kDmxConfig7X wants Lb/Rb, and kDmxConfig5XPlus2/kDmxConfig5XPlus2PhaseShift want Tfl/Tfr instead — which decode_substream does not have in hand on its own. It parses the payload and defers: once decode_access_unit has unioned every substream's channels into the programme's full layout, reconstruction runs there instead, in Domain::kMdctBand (the QMF pair's own state stays hardcoded to the five-channel case). Called one substream at a time rather than through decode_access_unit, these three configurations still parse but leave object_audio empty; the metadata still decodes and is still reported either way.

The mirror self-check

iclforge/ac3/verify/mirror.hpp and iclforge/ac3/verify/eac3_mirror.hpp. Both decoders can record what they derived from the wire, so it can be diffed against the encoder's own model of the same frame — per block, per coded stream, and for E-AC-3 per substream. It exists because a desync is invisible at the field that causes it: every mantissa's width comes out of that model, so the moment the two sides disagree each goes on reading confidently at its own idea of where it is, and the failure surfaces some blocks later as whatever §7.10.2 guard the misaligned bits happen to trip first.

// The driver most callers want: a drop-in for eac3::AccessUnitEncoder that also
// decodes every access unit it emits and diffs the two models.
iclforge::ac3::verify::Eac3MirrorEncoder encoder{config};
const auto checked = encoder.encode_access_unit(channels);
if (checked && !checked->ok()) {
    std::puts(encoder.last_report().c_str());
    // "frame 12 substream 1 block 3 channel 1: bap[87] encoder=5 decoder=4"
}

iclforge::ac3::verify::MirrorEncoder is the AC-3 sibling, over FrameEncoder. What each compares is in its own header; the E-AC-3 side adds what Annex E adds — per-substream and per-block bit offsets across an independent substream and its dependents, AHT gain mode and per-bin gains, and the coupling, enhanced-coupling and spectral-extension coordinates. forge eac3-encode … verify is the same check over a whole file.

Both trace pointers are null by default and cost one branch per block when they are: attaching one never changes what the encoder emits, which is what makes a checked build the same encoder as the shipped one. The decoder fills its side incrementally, so a frame it ends up refusing still leaves behind everything it read before the refusal — the case the comparison is most useful in, since the mismatch typically names an earlier block than the refusal does.

Transient pre-noise processing's hold-back (above) is invisible to the check: the trace is written while a frame is parsed, not when its audio is released, so a held-back frame is compared in the call that decoded it like any other.

Recovering from a damaged frame

iclforge::ac3::split_frames delimits syncframes by sync word and declared size alone — it does not validate a frame's CRC, so it still finds every boundary correctly even when one frame's payload is corrupt. That means a caller can decode frame by frame, catch the one bad decode_frame call, and keep going rather than losing the rest of the stream over a single damaged frame — the shape real capture/transport corruption takes, since a torn or bit-flipped frame does not usually take its neighbours down with it.

const auto frames = iclforge::ac3::split_frames(stream);

iclforge::ac3::FrameDecoder decoder;
int recovered = 0;
int failed = 0;
for (std::size_t i = 0; i < frames->size(); ++i) {
    const auto decoded = decoder.decode_frame((*frames)[i]);
    if (!decoded) {
        const auto message = iclforge::ac3::describe(decoded.error());
        fmt::printf("frame %zu: decode failed (%.*s) - skipping\n", i,
                    static_cast<int>(message.size()), message.data());
        ++failed;
        continue;
    }
    ++recovered;
}

Full program: examples/decode_robustness.cpp — corrupts one frame in the middle of an otherwise-good eight-frame stream and confirms the other seven still decode.

Concealing it instead: DecoderConfig::concealment

Skipping a frame keeps the rest of the stream, but it still leaves a hard discontinuity in the PCM where that frame should have been. §7.10's answer is to substitute something, and DecoderConfig::concealment opts into it:

iclforge::ac3::FrameDecoder decoder{{.concealment = iclforge::ac3::ConcealmentPolicy::kRepeatFade}};
for (const auto unit : scanned->access_units) {
    const auto decoded = decoder.decode_frame(unit);
    if (!decoded) { /* only at the head of a stream - see below */ }
    if (decoded->concealed) {
        ++concealed;  // decoded->concealed->error says what went wrong
    }
}
ConcealmentPolicy What it does
kNone Returns the error. The default, and what every caller got before this existed — a decoder used as a verification tool has to report a damaged frame, not paper over it.
kRepeatFade Repeats the last good block, decaying about 20 dB across the frame and on into any further consecutive losses. Keeps the programme's texture across a short dropout.
kMute Substitutes silence. The last good block's own overlap tail still plays out through the first block, so this fades rather than cuts.

Both work in the overlap-add domain rather than on finished PCM, which is what keeps them coherent with the frames either side: the decoders retain the last successfully decoded block's windowed transform output and synthesise the concealed frame's blocks from it through the same overlap-add a real frame goes through. So a concealed frame leaves the delay state in exactly the shape the next good frame expects — recovery is a normal decode, not a second artefact — and the fade at each end is the codec's own window rather than a ramp invented for the purpose.

A concealed frame comes back as a successful result carrying DecodedFrame::concealed (or DecodedSubstream::concealed / DecodedAccessUnit::concealed), which is what lets a test assert on the concealment itself rather than only on "the decode did not fail". Everything else on it describes the last frame that did decode — a damaged frame's own bsi cannot be trusted — and dynrng reads unity throughout, because no word arrived. A concealed E-AC-3 substream never carries an object layer: OAMD and JOC describe the frame that went missing, and repeating the previous frame's positions would put moving objects somewhere they demonstrably are not.

One case still returns the error with concealment on: a failure before any frame has decoded. Concealment reconstructs from what came before it, and at the head of a stream there is nothing to reconstruct from; inventing something there would be substituting audio rather than concealing a gap in it.

For E-AC-3 there is a third outcome. Assembling an access unit needs every one of its substreams in the one call, so a damaged dependent used to take the whole programme down with it. With concealment on it does not: the bed is rendered on its own — real channels, just a narrower layout than the stream promised — and the result reports ConcealmentAction::kBedOnly. A damaged independent substream is a different matter, and is concealed (or refused) like any other frame, because without it there is no programme at all.

forge decode and forge monitor expose all of this as conceal=repeat|mute, and report how many frames or access units were concealed.

split_access_units is the E-AC-3 sibling for Eac3Decoder::decode_access_unit, delimiting by independent-substream boundaries the same way. Losing an entire access unit — every substream of it, not one substream within it — is still not recoverable here: a transport that can drop whole units needs its own redundancy or retransmission above this layer. What this API guarantees is that finding the next good boundary never depends on the previous one having decoded cleanly, and, with concealment on, that a unit missing only some of its substreams still renders.

Latency, from the decoder's side

The chain's whole budget is on the AC-3 encoding page. What matters here is the part a decoder controls, which is smaller than it looks:

Adds
iclforge::ac3::FrameDecoder::latency_samples() 0, always.
iclforge::ac3::Eac3Decoder::latency_samples() 0, or 1536 once §3.7 engages, whatever the syncframe length.

FrameDecoder's zero is structural rather than lucky: decode_frame returns a frame's full 1536 samples per channel from the same call that supplies that frame's bytes. The IMDCT overlap those samples came out of is real, but it is already charged as the chain's transform term — the samples the decoder hands back are simply 256 samples older than the newest input the encoder had consumed, not samples it is still waiting for.

Eac3Decoder's exception is transient pre-noise processing. A §3.7 correction reaches across frame boundaries — back up to 1528 samples from a transient that may lie in a later frame — so the decoder holds 1536 samples back: at six blocks a syncframe it returns frame N−1 from the call that supplies frame N, at one block it returns six syncframes late. decode_substream/ decode_access_unit return std::nullopt on the calls where nothing is ready yet, and flush() collects whatever is still pending at end of stream. That is a release delay, not a sample-domain shift — the audio comes out in the same place in the stream, later — so a caller that honours the std::nullopt convention and calls flush() gets exactly the same samples in exactly the same order either way.

latency_samples() reports what has actually happened so far, so it reads 0 until some substream's frame sets transproce. To size buffers before a stream starts, ask the encoder (eac3::eac3_latency), which knows from its configuration whether the tool will ever be used.

Atmos objects lag the bed

One number an object-aware receiver needs and would not guess: a JOC-reconstructed object waveform lags its original input by 832 samples, not 256. JOC does not code objects — it codes a matrix that pulls them back out of the decoded bed, and TS 103 420 §7.1 puts that reconstruction in a 64-band complex QMF filterbank rather than the MDCT domain — a critically sampled real transform relies on time-domain alias cancellation between neighbouring blocks, an assumption a per-frame matrix breaks (see iclforge/dsp/qmf.hpp). Analysis plus synthesis costs the filterbank's own dsp::kQmfDelay (576 samples) on top of the bed's 256, for 832 total. The bed in the same DecodedAccessUnit still lags by 256, so objects and bed are not aligned with each other — anything mixing the two has to delay the bed by 576 samples. oba::AtmosEncoder::latency() reports the object path's budget and bed_latency() the bed's; the 832 is measured end to end in libs/ac3/tests/decoder/test_latency.cpp.

With DecoderConfig::joc_domain set to kMdctBand, the reconstruction costs 256 samples rather than 576, so objects lag their input by 512 and the bed has to be delayed by 256. iclforge::render::LayoutRenderer does this delaying for the one bed channel it plays beside placed objects, the LFE, once set_joc_domain() has told it the decoder's domain; libs/render/tests/test_object_lfe_timing.cpp measures the rendered feeds.

Streams with more than one programme

§E2.3.1.2 allows eight independent substreams (I0–I7) in one elementary stream, and broadcast DD+ uses them for multi-language and associated services. They are alternatives, not layers: unlike a dependent substream, a second independent one is a complete programme of its own, and a decoder renders one of them.

That matters to the framing, because the programmes interleave one frame period at a time. split_access_units(stream) delimits but does not select, so on a two-programme stream consecutive entries are consecutive programmes, not consecutive frames — feeding them straight through would splice two unrelated pieces of audio together.

const auto ids = iclforge::ac3::programme_ids(stream);          // e.g. {0, 1}
const auto units = iclforge::ac3::split_access_units(stream, ids->front());

split_access_units(stream, programme) keeps only that programme's units, and an empty result means the stream does not carry it — asking is how you find out, so it is not an error.

The decoder can do the selecting instead, which is what a caller already walking every unit wants:

iclforge::ac3::Eac3Decoder decoder{{.programme = 1}};
// A unit belonging to another programme returns std::nullopt, skipped before
// any decoding — no per-substream state advances for a programme you did not
// ask for. (std::nullopt also means the §3.7 hold-back; both call for the
// same thing from a caller: take nothing and go on to the next unit.)

Leaving DecoderConfig::programme unset renders whatever arrives, which is what every caller got before the field existed and is right for the single-programme case; DecodedAccessUnit::programme then says which programme each result came from.

iclforge::ac3::io::scan reports the same thing for a muxer: ScannedStream::programmes describes each programme's layout, channel count, bsmod and access units, and ScannedStream::access_units is the first programme's units alone rather than all of them spliced into one track.

Mixing an associated service: iclforge::ac3::AssociatedServiceMixer

iclforge/ac3/decoder/associated_service.hpp. A main programme and an associated service — a visually impaired description, a commentary, a voice-over — are made to be heard together, and §E3.10 says what the stream controls about that: levels, per-channel trims and, for a mono service, where it sits among the main's speakers. Annex E leaves the mixing itself to the receiver, and this class is that receiver. It sits after the decoders rather than inside one: each programme is its own Eac3Decoder, the associated one chosen with DecoderConfig::programme, and what joins them is their PCM and the mixing group each DecodedAccessUnit reports.

iclforge::ac3::Eac3Decoder main_decoder{{.programme = 0}};
iclforge::ac3::Eac3Decoder description_decoder{{.programme = 1}};
iclforge::ac3::AssociatedServiceMixer mixer;  // one per pair of programmes

// For each frame period, once both programmes have produced their unit:
auto main = main_decoder.decode_access_unit(main_unit);
auto description = description_decoder.decode_access_unit(description_unit);
const auto applied = mixer.mix(**main, **description);  // the description joins the main, in place
// applied->main_gain_db, applied->associated_gain_db and applied->panmean say what was done

What the stream's metadata does, and the clause it comes from:

Field Applied to Clause
pgmscl, and pgmscl2 for the second channel of a 1+1 service the programme that carries it §E3.10.1
extpgmscl the other programme: the description's is how a broadcaster ducks the main under it; the main's scales the description §E3.10.2
extpgmlscl, extpgmcscl, extpgmrscl, extpgmlsscl, extpgmrsscl, extpgmlfescl, extpgmaux1scl, extpgmaux2scl one channel of the other programme, on top of extpgmscl (the gains add in dB) §E3.10.6
dmixscl the other programme instead of the per-channel scales, when it reached the mixer already folded to two channels §E3.10.7
panmean, panmean2 a mono associated service, over a stereo main by Table E3.15 and over a 5.1 main by Tables E3.16 and E3.17; no pan is "centre" §E3.10.8

The two programmes' gains are in MixMetadata as codes; meta::pgm_scale_gain() and meta::external_scale_gain() turn them into linear gains, mute (pgmscl 0, Table E2.8's code 15) included. A change of gain from one access unit to the next ramps over the first block of the unit rather than stepping, which is what an audio description's fade needs.

What is not applied, because Annex E gives it nothing to apply: premixcmpsel, drcsrc and premixcmpscl (§E2.3.1.21: "decoders are not required to use them", and §E3.10.3 says the compression model they were written for "is not supported by the E-AC-3 mixing model"); the speech enhancement words (§E2.3.1.45: "placeholders for as yet undefined data"); blkmixcfginfo; and the reserved paninfo bits. They are all still decoded and reported in DecodedAccessUnit::mixing, and a test holds that setting them changes no sample.

Three things go beyond the text, and are the mixer's own choices:

  • Layouts the pan tables do not cover. Tables E3.15 to E3.17 are for a stereo main and a 5.1 main. A 3.0, quad or 7.1 main is served by the 5.1 tables with the seats it lacks folded into the nearest it has, by power; channels sharing a seat (Ls and Lrs) split its power; heights and the LFEs receive none of the service; a main with a lone centre takes it unpanned. pan_weights(panmean, locations) is the function, and it is constant power throughout.
  • A stereo or wider associated service is not panned, since it has a soundfield of its own. Each of its channels goes to the main's channel at the same location, folded to the nearest seat where the main has none.
  • The level is the decoders'. The mixer applies the metadata's gains and nothing else, so dialnorm normalisation, dynrng/compr and the §7.8 fold are whatever each decoder was configured with, and the sum is not limited. AssociatedServiceMixConfig says which fold each programme's decoder made, because a folded unit's channels are L and R (or C) while its layout still names the programme it was folded from; the associated programme is best decoded as coded, so that a mono description reaches the mixer as the one channel its pan places. associated_trim_db is the listener's own control of the description's volume.

Two programmes of one stream always share a sample rate and a block count (§E2.3.1.2), which is what lets the units pair frame for frame; mix() refuses units of different lengths or rates (MixError) rather than mixing them misaligned.

Nothing outside this project decodes two programmes at once, so there is no external oracle for the mix: FFmpeg refuses a second independent substream and ignores mixmdate's scales. What is checked is the spec's own arithmetic — Tables E3.15 to E3.17 written out independently of the implementation and compared at every panmean — and an encode, decode and mix of a 5.1 main with a mono description through this project's own encoder, measured tone by tone (tests/decoder/test_associated_service*.cpp). forge decode ... associated= and forge monitor ... associated= apply it from the command line; see Programme options.

One thing a caller of the mixer has to do for itself is pair the two decoders' units. They are not released in step: an Eac3Decoder holding frames back for transient pre-noise (§3.7) releases its first unit a frame or more late, and a main and a service need not hold the same number back. Count the units each decoder releases rather than the calls made to it, queue each side's until its partner has one, and when the service ends play what is left of the main as it is. forge decode and forge monitor do this through one piece of code (apps/shared/media/src/associated_mix.hpp, which also resolves a service name against each programme's bsmod), whose iclforge-app-media-tests cases compare it, sample for sample, with decoding both programmes and mixing the k-th unit of each by hand.

Decoding bytes you do not control

If the stream comes from the network or from a user, read Threat model before wiring this up. In short:

  • scan, split_frames and split_access_units take the whole stream as one span and return one span per access unit, so peak memory is O(input) and the library imposes no upper bound. Bound the input yourself, drive decode_frame/decode_substream one unit at a time, or feed an AccessUnitAccumulator, whose memory is the storage you hand it.
  • Every per-access-unit allocation is bounded by a bitstream field of fixed width — a single frame cannot be made to consume an unbounded amount of memory or time — and a hostile frmsiz is refused (kTruncated if it overruns the input, kInvalidStream if it is shorter than the header it was read from) rather than becoming a short span something reads past.
  • A refused frame produces no audio, but it is not a rollback: the decoder's overlap-add, dither and JOC state have advanced as far as the parse got, and an _into form's spans are left unspecified. Construct a fresh decoder if you need a clean state after an error.
  • The _into forms check their span sizes with assert, so a release build does not check them at all.

Testing a decoder of your own

The conformance vector set published with each release is the inverse of this page: streams this project produces, with the PCM they were encoded from and a manifest of what each exercises, for checking an independent implementation.


See also: Encoding AC-3 and Encoding E-AC-3 — what decode_frame/decode_access_unit are undoing, and the full latency budget; Muxing & sinks — pairing iclforge::ac3::io::scan with iclforge::containers::matroska::mux is what keeps a container's track header accurate; Building — the minimum-footprint decoder profile for set-top and DSP targets.