Muxing & sinks¶
Muxing: iclforge::containers::matroska::mux¶
iclforge/containers/matroska/matroska.hpp, iclforge::containers::matroska, a part of iclforge::containers. It links nothing from iclforge::ac3 and
takes frames as opaque bytes. Pairing it with iclforge::ac3::io::scan is what keeps the track header
accurate.
// One Matroska frame per access unit. For E-AC-3 an access unit is the
// independent substream plus its dependents, which is exactly what scan
// groups — a player must receive them together.
std::vector<std::vector<std::byte>> frames;
for (const auto unit : scanned->access_units) {
frames.emplace_back(unit.begin(), unit.end());
}
const iclforge::containers::matroska::AudioTrack track{
.codec_id = std::string{scanned->kind == iclforge::ac3::io::StreamKind::kAc3
? iclforge::containers::matroska::kCodecAc3
: iclforge::containers::matroska::kCodecEac3},
.sample_rate = iclforge::ac3::sample_rate_hz(scanned->sample_rate),
.channels = scanned->channels,
.samples_per_frame = iclforge::ac3::kSamplesPerFrame,
};
const auto file = iclforge::containers::matroska::mux(track, frames);
Full program: examples/mux_mkv.cpp.
mux returns the whole file as bytes and does no file I/O, which keeps it testable without a
disk. It writes one audio track, one SimpleBlock per frame, clusters closed on a time budget,
and Info with TimestampScale and Duration. No SeekHead, no Cues, no chapters, no tags — those
matter for seeking in large files, not for playing back what this project produces. Matroska
registers no CodecID for AC-4, so this module has no constant for one and forge mkv refuses an
AC-4 stream.
Incremental muxing: iclforge::containers::matroska::Writer¶
Same header. The incremental counterpart to mux, for a session whose length is not known up
front — a live capture, where mux cannot help: it needs every frame before it can compute
anything. Writer::create(track, options) validates the track the same way mux does.
header() holds the EBML header through Tracks, written exactly once; each push(frame)
buffers into the current cluster and returns the bytes of whichever cluster just closed (empty
on most calls); finalize() flushes the last partial cluster. Segment is written with EBML's
reserved unknown-size pattern and Duration is omitted — the standard streamed-Matroska shape,
which real players already handle. No more than one cluster's worth of frames is ever held, so
a caller streaming the returned bytes to disk keeps memory bounded for a session of any length.
This is what the GUI's live session records through.
Demuxing: iclforge::containers::matroska::demux, iclforge::containers::matroska::Reader¶
iclforge/containers/matroska/reader.hpp, same library. The read side of the two above, and codec-blind in exactly
the same way: it walks EBML, finds a track, and hands each frame back as opaque bytes. The one
place it names a codec is auto-selection, which takes the first audio TrackEntry whose
CodecID is A_EAC3 or A_AC3; ReadOptions::track_number names any other track explicitly
and accepts whatever CodecID it carries.
Two shapes, mirroring the write side. demux is the batch one, and it is zero-copy — the frames
it returns are spans into the buffer you passed it, the way iclforge::ac3::io::scan already hands back
access units:
const auto out = iclforge::containers::matroska::demux(file_bytes);
if (!out) {
std::println(stderr, "{}", iclforge::containers::matroska::describe(out.error()));
return 1;
}
// out->frames are views into file_bytes, which must outlive them.
const auto scanned = iclforge::ac3::io::scan(/* the elementary stream you write them to */);
Reader is the incremental one — iclforge::containers::matroska::Writer's mirror image, for a file too big to hold.
Frames arrive through a callback rather than a return value, so nothing accumulates: peak memory
is one chunk plus one frame, never the file.
iclforge::containers::matroska::Reader reader{};
const auto on_frame = [&](std::span<const std::byte> frame) { sink.push(frame); };
for (auto chunk = read_next_chunk(); !chunk.empty(); chunk = read_next_chunk()) {
if (!reader.push(chunk, on_frame)) { /* ... */ }
}
if (!reader.finish(on_frame)) { /* ... */ }
The span handed to the callback is valid for that call only — it points into the reader's own
buffer, which the next push reuses. Copy it there if you need to keep it. This is what
forge demux runs on, which is why a multi-gigabyte rip never lands in memory.
What it reads beyond what this project writes, because a file from a disc rip or another muxer
has it: all three lacing forms (Xiph, EBML, fixed-size), BlockGroup-wrapped Blocks as well
as SimpleBlock, several tracks, 32-bit as well as 64-bit SamplingFrequency, and clusters
left at EBML's unknown size rather than only the Segment. A file truncated mid-cluster returns
every whole frame before the cut rather than an error — that is how a live recording ends.
An audio track whose TrackEntry carries a ContentEncodings with a ContentEncryption is
encrypted with Matroska's own scheme. Nothing else in the entry marks its frames as ciphertext, so
the reader never selects it and returns kEncryptedTrack when it was the only candidate; it does
not decrypt. (A ContentEncodings that holds only compression is not applied either, and is read
as before.)
Untrusted input. Every length in an EBML file is self-declared, and a container arrives from
a rip, a capture or a download rather than from this project's own writer. ReadOptions bounds
the element size the reader will hold (16 MiB by default; anything larger that it does not need
is skipped without ever being buffered), the frames one laced block may carry, the number of
TrackEntry elements, and how deep masters may nest — the walker is iterative, so nothing an
input declares can exhaust the call stack. libs/containers/fuzz/fuzz_matroska_demux.cpp drives both entry
points with arbitrary bytes under ASan/UBSan.
Muxing: iclforge::containers::mp4::mux¶
iclforge/containers/mp4/mp4.hpp, iclforge::containers::mp4, a part of iclforge::containers. Same shape as iclforge::containers::matroska: it links nothing from
iclforge::ac3 and takes frames as opaque bytes. The one place MP4 needs codec-specific bytes that
Matroska's plain CodecID string does not is the sample entry's dac3/dec3 configuration box
(ETSI TS 102 366 Annex F) — so iclforge::containers::mp4::AudioTrack::codec_config carries that box's payload as
opaque bytes too, built by iclforge::ac3::io::build_codec_config_box (iclforge/ac3/io/dec3.hpp) straight off
whatever iclforge::ac3::io::scan read out of the bitstream, fscod/bsid/bsmod/acmod/lfeon and, when the
stream carries Dolby Atmos objects, the flag_ec3_extension_type_a/complexity_index_type_a
extension (TS 103 420 §8.3.1/§8.3.2.2) alike.
The same codec-blind contract carries AC-4: codec_id = iclforge::containers::mp4::kCodecAc4
selects TS 103 190-2 Annex E.4's ac-4 sample entry with a dac4 configuration box, whose
payload comes from iclforge::ac4::build_dac4() off the stream's own parsed TOC — the AC-4 twin of
build_codec_config_box, in iclforge::ac4 where the codec knowledge lives. An ISOBMFF ac-4
sample is the raw_ac4_frame alone (no sync word, no CRC), samples_per_frame and
AudioTrack::timescale come from iclforge::ac4::media_timing() (TS 103 190-2 Table E.1: the sample rate,
or 240 000 for the 1000/1001-family rates whose frame length alternates at 48 kHz, where a frame is
8 008, 4 004 or 2 002), a stream whose frames are not all I-frames names its I-frames in
MuxOptions::sync_samples, which writes the Sync Sample Box Annex E.2 asks for, and because AC-4's
RFC 6381 string is not
its fourcc, AudioTrack::rfc6381 carries iclforge::ac4::rfc6381_codec_string()'s dotted form
(ac-4.02.01.00) for the HLS/DASH manifests. MPEG-TS carriage is DVB-only — EN 300 468
Annex D.7's extension descriptor 0x7F/0x15, with an ISO 13818-1 §2.6.8 registration
descriptor (AC-4) beside it for interop — and iclforge::containers::mpegts::AudioCodec::kAc4 under the ATSC
profile is refused rather than given an invented stream_type (A/342-2 is ATSC 3.0's
ROUTE/MMT, not 13818-1).
// One MP4 sample per access unit. For E-AC-3 an access unit is the
// independent substream plus its dependents, which is exactly what scan
// groups — a player must receive them together.
std::vector<std::vector<std::byte>> frames;
frames.reserve(scanned->access_units.size());
for (const auto unit : scanned->access_units) {
frames.emplace_back(unit.begin(), unit.end());
}
const iclforge::containers::mp4::AudioTrack track{
.codec_id = std::string{scanned->kind == iclforge::ac3::io::StreamKind::kAc3 ? iclforge::containers::mp4::kCodecAc3
: iclforge::containers::mp4::kCodecEac3},
.sample_rate = iclforge::ac3::sample_rate_hz(scanned->sample_rate),
.channels = scanned->channels,
.samples_per_frame = iclforge::ac3::kSamplesPerFrame,
// The dac3/dec3 sample-entry box, built from the same scan result -
// see iclforge/ac3/io/dec3.hpp for why this lives in iclforge::ac3::io rather than in
// iclforge::containers::mp4 itself.
.codec_config = iclforge::ac3::io::build_codec_config_box(*scanned),
};
const auto file = iclforge::containers::mp4::mux(track, frames);
Full program: examples/mux_mp4.cpp.
mux returns the whole file as bytes and does no file I/O, the same as iclforge::containers::matroska::mux. It
writes ftyp/moov/mdat for one audio track, one sample per chunk, stts/stsz/stco built
straight off the frame sizes handed in. No multiple tracks: those matter for multi-track muxing,
not for playing back what this project produces.
An edit list is written only when MuxOptions::edit asks for one, and then it has one edit:
start_samples to skip at the start (an encoder's priming) and duration_samples to play after
them (ending before the last frame's padding). The movie and track durations become the edit's;
the media's stays the length of its samples. An edit that runs past the frames, or plays
nothing, is kInvalidOptions.
Getting the dec3/dac3 box right from the spec is the point: FFmpeg's MKV→MP4 remux path used
to silently drop or mis-signal the Atmos extension
(jellyfin-ffmpeg#584, upstream
FFmpeg trac #9996, since fixed) — building it from
iclforge::ac3::io::scan's own read of the bitstream, rather than by copying another tool's output, is
what this module avoided that bug by construction rather than by patching it after the fact, and
still does for any FFmpeg build older than the fix.
Demuxing: iclforge::containers::mp4::demux, iclforge::containers::mp4::Reader, iclforge::containers::mp4::demux_seekable¶
iclforge/containers/mp4/reader.hpp, same library. The read side of both writers above, and the same shape the
Matroska reader has: demux is batch and zero-copy (samples are spans into your buffer),
Reader is incremental (samples arrive through a callback, peak memory is one chunk plus one
sample), and demux_seekable is incremental over a source that can be read at an offset - a file,
a memory map - which is what a moov-last file needs.
It reads both layouts, from either writer and from a real muxer: a plain moov/mdat file,
walking stsc/stsz(or stz2)/stco(or co64) to turn the sample table into byte ranges, and
a fragmented one, taking mvex/trex's defaults plus every moof/traf/tfhd/trun that
follows. A 64-bit largesize box header and an mdat declared to run to end-of-file both read
normally, though neither writer here emits them.
moov before mdat. demux can reach any offset, so it reads a file whose sample table sits
either side of the media data. Reader cannot — locating a sample means seeking backwards, and a
stream has nowhere to go back to — so a moov-last file reports kMoovAfterMdat rather than
silently returning nothing. That is the layout a muxer leaves behind when it never rewrote the
file for "faststart"; mux() and fragment() both write moov first, as does any web-optimised
file.
demux_seekable(read_at, size, on_track, on_sample) is the third way to read it, for a source that
can go back. It walks the boxes through the same parser, which steps over mdat by its declared
length, so the audio is never read to find the table that indexes it, and then reads each sample at
the offset the table gives. Memory is the largest box the table needs, which max_box_bytes
bounds, plus one sample - whichever side of mdat the moov is on, and for a fragmented file too.
on_track is called once, before the first sample, with the track as the container declares it,
so a caller that has to treat samples by codec (AC-4's raw frames need a sync frame put back
around them) knows which it is. A sample whose range runs past size ends delivery there, as
demux does for a truncated file. forge demux uses it for a file path, and keeps the chunked
Reader for a pipe.
A protected track is refused, not read. A track whose sample entry is enca is encrypted with
Common Encryption (ISO/IEC 23001-7) and holds ciphertext. The reader reads its sinf (frma, schm,
tenc), never selects the track, and returns DemuxError::kProtectedTrack when it was the only
candidate; describe_refusal(refused) says which track, with its scheme, original format and default
KID, and Reader::refused_tracks() or list_refused_tracks() supplies the tracks. A protected track
beside a readable one is listed in Demuxed::skipped with its Protection. A track that holds a clear
sample entry beside a protected one, the layout of a clear lead-in, is refused whole: the entry a
sample belongs to is named per chunk or per fragment, and reading only the clear entry would return
a truncated programme as if it were all of it. Nothing here decrypts or reads a key.
The dec3/dac3 box comes back parsed. ReadTrack::codec_config is a CodecConfig, the read
twin of iclforge::ac3::io::build_codec_config_box: fscod, bsid, bsmod, acmod,
lfeon, bit_rate_code or data_rate_kbps, num_ind_sub/num_dep_sub/chan_loc, and —
crucially — TS 103 420's flag_ec3_extension_type_a/complexity_index_type_a as an
optional<int>. That last field is the Atmos/JOC marker an FFmpeg remux is known to drop, and
reading it back is what makes the repair case possible: demux a file, keep the complexity index,
re-mux it with the signalling intact. The values are reported as raw syntax numbers rather than
iclforge:: enums, because this module has no dependency on the codec library and no business
deciding what fscod 0 means. payload keeps the bytes verbatim, so a caller remuxing into
another container can hand them straight back.
A dec3 box that stops before the Atmos extension leaves oba_complexity_index empty rather
than reporting a confident zero — the extension is a trailing addition, and a box written before
TS 103 420 simply has nothing to say about it.
Edit lists come back as stored. ReadTrack::edits holds the track's elst entries in file
order (version 0 or 1), each with its segment_duration in the movie's timescale,
ReadTrack::movie_timescale from mvhd, and its media_time in the track's own timescale, where
-1 marks an empty edit. Nothing here applies them, because what a media time means depends on
the codec. apps/shared/media/src/container_input.hpp turns the shape an audio encoder writes into a
StreamTrim: any empty edits, then one edit at normal speed. The trim is the samples to skip and
the samples to play, and Hearth's player plays only that part. Any other shape leaves the stream
whole, with a note saying why. forge and the GUI do not apply the trim. Neither elst
nor mvhd is needed to find a sample, so one too short to read, one that declares more entries
than it holds, or one longer than ReadOptions::max_edits is left out, and the file still reads.
The other tracks come back listed. Demuxed::skipped holds each track the reader saw and did not
select, in file order and up to 64, as a SkippedTrack: its track_id, a kind from the hdlr
handler (kAudio for soun, kVideo for vide, kText for text, sbtl, subt and clcp,
kOther for the rest), the first sample entry's four characters as codec_id (avc1, mp4a,
tx3g, wvtt) and its language. None of their samples is read. The Matroska reader's
Demuxed::skipped is the same, with the TrackNumber, a kind from the TrackType (1 video, 2
audio, 17 subtitle) and the CodecID. It is what a caller needs to tell a person that a file also
carries a picture or a subtitle track; forge probe prints it.
Untrusted input. An MP4's sample table is an index, which is a wider attack surface than
Matroska's in-line framing: stsc names chunks, stco names absolute file offsets and stsz
names sizes, all self-declared and all resolved against each other before a byte of audio is
touched. ReadOptions bounds the box size the reader will hold, the sample and chunk counts
(max_samples defaults to about 35 hours of access units), and the nesting depth; the walk is
iterative. A chunk offset pointing past the end of the file drops that sample rather than
failing the file — a truncated download is ordinary, and the samples that are present are all
real. libs/containers/fuzz/fuzz_mp4_demux.cpp drives both entry points with arbitrary bytes.
Muxing: iclforge::containers::mpegts::mux¶
iclforge/containers/mpegts/mpegts.hpp, iclforge::containers::mpegts, a part of iclforge::containers. Same shape as iclforge::containers::matroska::mux above — it links
nothing from iclforge::ac3 beyond the AC-3, E-AC-3 or AC-4 choice it is told, and takes access
units as opaque bytes.
// One PES-wrapped access unit per TS access unit. For E-AC-3 an access
// unit is the independent substream plus its dependents, which is
// exactly what scan groups — a player must receive them together.
std::vector<std::vector<std::byte>> frames;
frames.reserve(scanned->access_units.size());
for (const auto unit : scanned->access_units) {
frames.emplace_back(unit.begin(), unit.end());
}
const iclforge::containers::mpegts::AudioTrack track{
.codec = scanned->kind == iclforge::ac3::io::StreamKind::kAc3 ? iclforge::containers::mpegts::AudioCodec::kAc3
: iclforge::containers::mpegts::AudioCodec::kEac3,
.sample_rate = iclforge::ac3::sample_rate_hz(scanned->sample_rate),
.channels = scanned->channels,
.samples_per_frame = iclforge::ac3::kSamplesPerFrame,
// What the PMT descriptor says about the service. Every field is a plain
// A/52 value iclforge::ac3::io::scan already read off the bitstream.
.service = {.bsmod = scanned->bsmod,
.bsmod_present = scanned->bsmod_present,
.acmod = static_cast<int>(scanned->acmod),
.lfe = scanned->lfe,
.channels = scanned->channels,
.bsid = scanned->bsid,
.dsurmod = scanned->dsurmod,
.bit_rate_code = scanned->bit_rate_code,
.sample_rate_code = static_cast<int>(scanned->sample_rate),
.mix_metadata = scanned->mix_metadata,
.independent_substreams = scanned->independent_substreams},
};
const auto file = iclforge::containers::mpegts::mux(track, frames,
{.profile = iclforge::containers::mpegts::BroadcastProfile::kAtsc});
Full program: examples/mux_ts.cpp.
mux returns the whole 188-byte-aligned Transport Stream as bytes, no file I/O, same testability
reasoning as iclforge::containers::matroska::mux. It writes a single program — one PAT, one PMT (repeated
periodically so a receiver tuning in mid-stream doesn't wait for byte zero), and one PES-wrapped
elementary stream carrying PCR every access unit. No video, no other elementary streams, no PID
remapping: a general-purpose multiplexer is out of scope, this is enough for a player or
ffprobe to recognize one AC-3, E-AC-3 or AC-4 programme.
Broadcast profile. Two standards register AC-3/E-AC-3 for MPEG-TS carriage — ATSC and DVB —
with different, non-interoperable signalling, so a stream is written to satisfy one of them,
never a bit of each. MuxOptions::profile picks which:
kDvb (default) |
kAtsc |
|
|---|---|---|
AC-3 stream_type |
0x06, PES private data |
0x81 (A/52 Annex A §A4.1) |
E-AC-3 stream_type |
0x06 |
0x87 (A/52 Annex G §G3.1) |
| AC-3 descriptor | AC3_descriptor, tag 0x6A (EN 300 468 Table D.6) |
AC-3_audio_stream_descriptor, tag 0x81 (A/52 Table A4.1) |
| E-AC-3 descriptor | enhanced_AC-3_descriptor, tag 0x7A (Table D.7) |
E-AC-3_audio_descriptor, tag 0xCC (A/52 Table G.1) |
| What identifies the stream | the descriptor tag — DVB registers no stream_type of its own |
the stream_type — ATSC treats the descriptor as configuration detail |
Both descriptors describe the same service in different bit layouts, so a caller supplies the
underlying A/52 field values once, as iclforge::containers::mpegts::ServiceInfo, and the module maps them onto
whichever registry's tables the profile calls for — EN 300 468 Tables D.1–D.8, A/52 Tables
A4.2–A4.6 and G.2–G.6. That mapping is descriptor syntax, which is this module's job; reading
those values off the bitstream is iclforge::ac3::io::scan's, which is why ServiceInfo is plain
integers and iclforge::containers::mpegts still links nothing from iclforge::ac3.
iclforge::ac3::io::ScannedStream supplies every one of them: bsmod (with bsmod_present, since
Annex E only carries it inside infomdate), acmod, lfe, the rendered channels, bsid,
dsurmod, bit_rate_code, mix_metadata for mixinfoexists, and independent_substreams
with associated_substreams for the substream1–3 fields. Two values are not in any
bitstream, because they describe how services in a multiplex relate rather than what one stream
contains — mainid and asvc — and those stay unset unless the caller supplies them
(forge ts ... mainid=3, asvc=0,2 — a comma-separated list of main-service numbers, or the
raw bitmask directly as asvc=0x05). An unset optional field is omitted rather than
zero-filled: a receiver already handles an absent one, where an invented main-service number
links the wrong services. What is checked is consistency with the stream's own bsmod:
asvc= on a stream Table 5.7 calls a main service, or mainid= on one it calls an associated
service, is a usage error (iclforge::ac3::meta::is_associated_service is the predicate, shared with the
dec3/EC3SpecificBox writer's own asvc bit) — the wire fields exist either way, but which
one describes this stream is not the operator's to override.
Two places where the standards' own tables cannot express something this project can read, and
the field is omitted rather than approximated: A/52 Table G.5 reserves complete-main and
emergency as substream service types, and Table G.6 reserves 1+1 as a substream channel mode,
so an ATSC substream1–3 field for such a substream is left out with its flag clear.
Demuxing: iclforge::containers::mpegts::demux, iclforge::containers::mpegts::Reader¶
iclforge/containers/mpegts/reader.hpp, same library. The read side of iclforge::containers::mpegts::mux/Writer, codec-blind in the
same sense: it locks to the packet grid, follows PAT to PMT to an elementary PID, reassembles
PES, and hands the payloads back as opaque bytes.
What comes back is not the same shape as the sibling readers. A Matroska SimpleBlock and an
MP4 sample each hold exactly one access unit, so iclforge::containers::matroska::demux/iclforge::containers::mp4::demux hand back access
units. A PES packet makes no such promise — it may carry one, several, or (with the unbounded
PES_packet_length form broadcast uses) a run ending only when the next one starts. So this
reader hands back PES payloads, and what they concatenate to is the elementary stream:
const auto out = iclforge::containers::mpegts::demux(file_bytes);
if (!out) {
fmt::println(stderr, "{}", iclforge::containers::mpegts::describe(out.error()));
return 1;
}
std::vector<std::byte> elementary_stream;
for (const auto& payload : out->payloads) {
elementary_stream.insert(elementary_stream.end(), payload.begin(), payload.end());
}
const auto scanned = iclforge::ac3::io::scan(elementary_stream);
This is exactly what iclforge::ac3::io::scan wants, and re-framing PES payloads into access units is its
job, not this module's — doing it here would mean this container-blind module knowing what an
AC-3 syncframe is.
The PMT's own service descriptor comes back too, as ReadStream::service (a
std::optional<ServiceInfo>, std::nullopt when the signalling carried no such descriptor to
read — kRegistrationDescriptor and AC-4 never do). iclforge::containers::mpegts::parse_service_descriptor is the
literal inverse of the four descriptor builders above, so a transport stream this module wrote
reads back byte-for-byte what mux's caller supplied — bsmod, full_service, mainid,
asvc, bsid, mix_metadata and the substream1–3 bytes alike. Not everything survives the
round trip, because the wire format itself cannot express it: acmod/channels/lfe/dsurmod
stay at ServiceInfo's own defaults rather than reconstructed, since channel_flags() is a
many-to-one summary forward (Table D.5/G.3/A4.5's "more than 5.1 channels" row covers a range,
not one value) with no exact acmod to recover backward — a caller that has the elementary stream
already has those exact values from iclforge::ac3::io::scan(), the same source mux's own caller used.
Four signalling forms. For AC-3 and E-AC-3, mux chooses between DVB and ATSC through
MuxOptions::profile (see above), and commits to one of them wholly. A reader has no such luxury:
a third family of files names the codec through neither, using a
registration_descriptor's 'AC-3'/'EAC3' format_identifier instead, and AC-4 is named by
DVB's extension descriptor 0x7F/0x15 beside a stream_type of 0x06. All four are recognised
on read, reported as ReadStream::signalling (CodecSignalling::kAtscStreamType /
kDvbDescriptor / kRegistrationDescriptor / kDvbExtensionDescriptor) so a caller remuxing back
out knows which it was; ReadStream::ac4 says the payload is AC-4, whose PES bytes come back
without framing, for iclforge::ac4::scan or iclforge::ac4::SyncFrameSplitter to split.
Three packet grids, detected rather than assumed: 188 bytes (ISO/IEC 13818-1's own), 192
(M2TS — a Blu-ray/AVCHD rip, each packet prefixed by a 4-byte arrival timestamp), and 204 (a
capture that kept its Reed-Solomon parity). The grid is found by where the 0x47 sync byte
repeats at a consistent stride, several packets in a row — a stray 0x47 in payload cannot fake
that — which also means a capture that starts mid-packet (the normal way a transport stream is
acquired: wherever the tuner happened to be) still locks on.
iclforge::containers::mpegts::Reader reader{};
const auto on_payload = [&](std::span<const std::byte> payload) {
elementary_stream.insert(elementary_stream.end(), payload.begin(), payload.end());
};
for (auto chunk = read_next_chunk(); !chunk.empty(); chunk = read_next_chunk()) {
if (!reader.push(chunk, on_payload)) { /* ... */ }
}
if (!reader.finish(on_payload)) { /* ... */ }
Reader::finish takes the callback — unlike the Matroska and MP4 readers' — because it can
still emit: the unbounded PES form ends only at the next
payload_unit_start_indicator or at end of input, so the last payload of a capture is only
complete here.
A packet of the audio PID whose transport_scrambling_control bits are not 00 carries a scrambled
payload (conditional access, not Common Encryption). The PES parse would take it for audio, so the
reader stops at the first one with kScrambled; payloads delivered before it were clear packets.
The PMT's conditional_access_descriptor is not read: it says a stream may be scrambled, and the
packet bits say whether this one is. Nothing descrambles.
Untrusted input, and more so than the sibling formats. A transport stream is designed to be
tuned into mid-flight and to survive bit errors, so "malformed" is the ordinary case here, not
the exceptional one. Every PSI section's CRC-32 (the non-reflected CRC-32/MPEG-2 variant,
self-checked against the standard test vector) is verified before the PAT/PMT it carries is
believed — a bit-damaged PMT is thrown away rather than locking onto a wrong PID for the rest of
the file. ReadOptions bounds the PES and PSI section sizes the reader will assemble (the
unbounded PES form has no ceiling of its own otherwise) and how far it will search for the packet
grid. libs/containers/fuzz/fuzz_mpegts_demux.cpp drives both entry points with arbitrary bytes — this is also
the container reader most likely to find a hang rather than a crash, since the sync
search, section reassembly and PES reassembly are all loops a hostile stream can try to stall.
Fragmented MP4/CMAF + HLS/DASH: iclforge::containers::mp4::fragment, iclforge/containers/mp4/hls.hpp, iclforge/containers/mp4/dash.hpp¶
The streaming-delivery follow-up iclforge::containers::mp4::mux's own header deliberately left for
later: iclforge::containers::mp4::fragment lays out the same track and frames as mux, but as a fragmented movie
(ISO/IEC 14496-12 §8.8's moof/mfhd/traf/tfhd/tfdt/trun) split into CMAF-shaped pieces
(ISO/IEC 23000-19) — an initialization segment (ftyp+moov, whose one trak carries
mvex/trex instead of a populated sample table, since a fragmented track's own stbl
describes zero samples) plus one or more media segments (styp+moof+mdat, one per fragment).
Same batch shape as mux: every frame is known up front, so real durations/timestamps are
filled in throughout, including the track's total duration in mvhd/tkhd/mdhd.
iclforge::containers::mp4::FragmentWriter below is the incremental form
for a live session, and that total duration is the one thing the two disagree about.
const auto fragmented =
iclforge::containers::mp4::fragment(track, frames, iclforge::containers::mp4::FragmentOptions{.frames_per_fragment = 8});
FragmentedOutput::init_segment and ::media_segments are exactly the files a packager or CDN
origin wants (init.mp4 plus segment1.m4s, segment2.m4s, ...) — see forge fmp4, which
writes them out that way alongside the manifests below.
iclforge/containers/mp4/hls.hpp and iclforge/containers/mp4/dash.hpp build HLS/DASH signaling for those same segments — one CMAF
segment format, two manifest flavors, the entire point of CMAF:
const auto media_playlist =
iclforge::containers::mp4::build_hls_media_playlist(track, fragmented->media_segments, iclforge::containers::mp4::HlsOptions{});
const auto master_playlist = iclforge::containers::mp4::build_hls_master_playlist(
track, fragmented->media_segments, "audio.m3u8", iclforge::containers::mp4::HlsOptions{});
const auto dash_snippet = iclforge::containers::mp4::build_dash_adaptation_set(track, fragmented->media_segments);
const auto mpd = iclforge::containers::mp4::build_dash_mpd(track, fragmented->media_segments, dash_snippet);
A master playlist can carry more than one audio rendition in the same #EXT-X-MEDIA group,
which is what an Atmos asset needs (see the paired-rendition note below):
const std::array<iclforge::containers::mp4::HlsRendition, 2> renditions{
iclforge::containers::mp4::HlsRendition{.track = joc_track,
.segments = joc.media_segments,
.media_playlist_uri = "audio.m3u8",
.name = "Dolby Atmos",
.channels_attribute = "12/JOC",
.is_default = true},
iclforge::containers::mp4::HlsRendition{.track = bed_track,
.segments = bed.media_segments,
.media_playlist_uri = "bed51/audio.m3u8",
.name = "5.1"}};
const auto master_playlist = iclforge::containers::mp4::build_hls_master_playlist(renditions);
Full program: examples/mux_fmp4.cpp.
Both manifest flavors get the CODECS/codecs attribute right: iclforge::containers::mp4::hls_codec_string (and
build_dash_adaptation_set internally) use the bare ac-3/ec-3 sample-entry fourcc unmodified
as the RFC 6381 'Codecs' parameter — neither AC-3 nor E-AC-3 registers any of the
dot-separated profile/level fields RFC 6381 §3 makes room for (unlike e.g. avc1.640028), which
is confirmed against every real HLS manifest example
Apple's HLS Authoring Specification for Apple
Devices
shows. AC-4's string is the dotted one iclforge::ac4::rfc6381_codec_string() gives (ac-4.02.01.00),
which the caller puts in AudioTrack::rfc6381. Dolby Digital Plus with Atmos objects additionally needs CHANNELS="<N>/JOC" on the HLS
media rendition instead of a plain channel count, where N is the decodable object count
(iclforge::ac3::io::ScannedStream::oba_complexity_index, TS 103 420 §8.3.2's complexity_index_type_a)
— reiterated, with a worked example (CHANNELS="12/JOC"), by Dolby's own Online Delivery Kit
documentation
and shown verbatim in a real manifest (CODECS="avc1.64001f,ec-3" / CHANNELS="12/JOC") by
AWS MediaLive's own HLS+Atmos
documentation. iclforge::containers::mp4
itself never reads that TS 103 420 object-layer syntax — HlsOptions::channels_attribute is
opaque to it, the same way AudioTrack::codec_config is; forge fmp4 is the caller that
already has oba_complexity_index (it read it to build the dec3 box) and supplies the string.
The paired 5.1 rendition. Apple's authoring specification also asks that an Atmos rendition
be accompanied by an equivalent 5.1 bitstream carrying CHANNELS="6" in the same
#EXT-X-MEDIA group, so a client that cannot render the object layer selects the bed rather
than the asset failing to play. Because JOC's bed already is the full mix, that companion
needs no re-encode: iclforge::ac3::io::strip_objects removes the
object layer from the same stream and leaves bit-identical bed audio. forge fmp4 …
fallback-51 writes both — the Atmos rendition where it always was, the stripped one under
bed51/, and one master playlist listing both.
The DASH snippet describes exact per-segment durations with a SegmentTemplate/SegmentTimeline
(ISO/IEC 23009-1 §5.3.9.6) built from each segment's own duration, rather than one nominal
duration attribute assumed constant — segments are constant-duration except (as usual) a
possibly shorter final one, and a flat nominal duration is exactly what let a real player
(FFmpeg's own dash demuxer, while writing this module) compute one too many segments from
mediaPresentationDuration and request a segment number past the end.
Atmos/JOC signalling: ceao, and the DASH descriptors¶
iclforge/containers/mp4/dash.hpp used to say there was no established DASH convention to point at for JOC, unlike
HLS's CHANNELS="<N>/JOC". There is: DASH-IF IOP Part 8 v5.0.0 §5.3.2 names, for E-AC-3
carrying JOC, the two SupplementalProperty descriptors
ETSI TS 103 420
clause D.2 defines — tag:dolby.com,2018:dash:EC3_ExtensionType:2018, whose value "shall be the
three character string JOC" (§D.2.2.1), and
tag:dolby.com,2018:dash:EC3_ExtensionComplexityIndex:2018, whose value "shall be decimal
representation of the eight-bit element complexity_index_type_a in the EC3SpecificBox"
(§D.2.2.2). §5.3.3 adds that such a track "shall be constrained according to the CMAF specific
requirements as provided in ETSI TS 103 420 Annex E", where §E.5 requires the ceao compatibility
brand. DashOptions::joc_complexity_index writes the first pair;
FragmentOptions::object_audio_brand adds ceao to the ftyp and every styp alongside the
iso6/cmfc a fragmented CMAF track already declares (added, not substituted — §E.2 requires
ISO/IEC 23000-19 conformance on top of the profile).
The same §5.3.2 offers two AudioChannelConfiguration schemes for E-AC-3. With
DashOptions::dolby_channel_configuration empty, the Representation carries
urn:mpeg:mpegB:cicp:ChannelConfiguration with the track's channel count — what TS 103 420
§D.2.3's own example MPD writes. Set it to the four hex digits TS 102 366 clause I.1.2.1 defines
(the 16-bit channel-assignment word, left channel in the most significant bit, so 5.1 is F801)
and it carries the Dolby scheme instead. iclforge::ac3::io::dash_channel_configuration is the one place
that word is derived, beside build_codec_config_box and for the same reason: which locations a
stream carries is acmod/lfeon/chanmap syntax, and a manifest writer has no business
re-deriving AC-3 semantics. forge fmp4, the GUI and the live paths all supply it.
FragmentOptions::object_audio_brand and DashOptions::joc_complexity_index are caller-supplied
for the same reason HlsOptions::channels_attribute is — iclforge::containers::mp4 never reads TS 103 420's object
layer, and the caller that scanned oba_complexity_index off the bitstream to build the dec3
box already has it.
AC-4 fragments: sync samples, a time scale of its own, brands and descriptors¶
An AC-4 track (iclforge::containers::mp4::kCodecAc4, its dac4 from iclforge::ac4::build_dac4()) fragments with four things an
AC-3 or E-AC-3 track never needs, each supplied by the caller, since iclforge::containers::mp4 reads no AC-4 syntax:
- Sync samples. Only an I-frame decodes on its own, and ETSI TS 103 190-2 Annex E.2 and E.3
make the I-frames the sync samples and start every fragment at one.
FragmentOptions::sync_samplesgivesfragment()one flag a frame (each frame'sb_iframe_global); a fragment then closes once it holdsframes_per_fragmentframes and the next frame is a sync sample, and everytrunthat holds a sample which is not one lists each sample's flags (sample_is_non_sync_sample, andsample_depends_on1 for such a sample, ISO/IEC 14496-12 §8.8.3.1).FragmentWriter::push(frame, sync)takes the same flag frame by frame. A first frame that is not a sync sample iskInvalidOptions. - The time scale.
AudioTrack::timescalesetsmdhd's, which the decode times, the segment durations and both manifests' timelines count in (iclforge::containers::mp4::timescale_of()): Table E.1's 240 000 at 29.97, 59.94 and 119.88 fps, whose frames alternate in length at 48 000 Hz, and the sample rate elsewhere (iclforge::ac4::media_timing()gives both). - Brands.
FragmentOptions::brandslists a CMAF media profile's brands afteriso6andcmfcin theftypand everystyp: Annex H'sca4mandca4sfor an AC-4 track. - DASH descriptors.
DashOptions::channel_configurationreplaces the Representation's AudioChannelConfiguration, andDashOptions::supplemental_propertiesadds SupplementalProperty descriptors, each aiclforge::containers::mp4::Descriptor{scheme_id_uri, value}with its attributes escaped:iclforge::ac4::dash_channel_configuration()gives Annex G's (Table G.1's CICP value, or the Dolby 2015 scheme's word for a layout the table lacks) andiclforge::ac4::dash_supplemental_properties()the frame rate and a pre-virtualized presentation's signal (Annex G.3).
forge fmp4, and record and live with codec=ac4 container=fmp4, fragment AC-4 this way;
iclforge::ac4::cmaf_refusal() and iclforge::ac4::configuration_difference() say which streams Annex H.1.2 keeps out
of a CMAF track.
Incremental fragmenting: iclforge::containers::mp4::FragmentWriter¶
Same header as fragment. The live counterpart, and iclforge::containers::matroska::Writer/iclforge::containers::mpegts::Writer's
sibling: create(track, options) validates exactly what fragment validates and leaves
init_segment() ready to write once; each push(frame) buffers into the current fragment and
returns the media segment that just closed (so one comes back every
frames_per_fragment-th call, std::nullopt otherwise); finalize() flushes the trailing
partial fragment. tfdt comes from a running decode time held on the writer, which is the only
per-fragment state fragment's own loop carries. Nothing beyond one fragment's frames and the
playlist window is ever held.
The contract is byte-equality with the batch form, the same one iclforge::containers::mpegts::Writer holds itself
to: for the same track, options and frames, the media segments this hands back are byte for byte
the ones fragment would have built. The initialization segment differs in exactly one respect —
mvhd/tkhd/mdhd carry duration 0, since a live session does not know its total (ISO/IEC
14496-12 §8.8.2 provides mehd for the fragmented movie that does). That is the same
concession iclforge::containers::matroska::Writer makes with EBML's unknown-size Segment and its omitted Duration.
Both halves are asserted in libs/ac3/tests/test_fmp4.cpp, the init segment by patching the
three duration fields back and then requiring full byte equality.
auto writer = iclforge::containers::mp4::FragmentWriter::create(
track, iclforge::containers::mp4::FragmentOptions{.playlist_window_segments = 20});
write("init.mp4", writer->init_segment());
for (const auto& frame : frames) {
const auto closed = writer->push(frame); // std::optional<MediaSegment>
if (*closed) {
write(std::format("segment{}.m4s", (*closed)->sequence_number), (*closed)->bytes);
// Rebuild the manifests from the rolling window each time a segment closes.
write("audio.m3u8", iclforge::containers::mp4::build_hls_media_playlist(track, writer->window(),
iclforge::containers::mp4::HlsOptions{.vod = false}));
write("manifest.mpd",
iclforge::containers::mp4::build_dash_mpd(track, writer->window(),
iclforge::containers::mp4::build_dash_adaptation_set(track, writer->window()),
iclforge::containers::mp4::MpdOptions{.is_static = false,
.availability_start_time = now_iso8601()}));
}
}
window() hands back SegmentInfo — a MediaSegment's bookkeeping without its bytes, so a
rolling window of hundreds of segments costs nothing to keep.
FragmentOptions::playlist_window_segments bounds it (0, the default, keeps every segment). All
three manifest builders take SegmentInfo spans, with MediaSegment overloads for batch
callers.
Live manifests differ from VOD ones only in what they omit and where they start.
HlsOptions::vod = false drops #EXT-X-PLAYLIST-TYPE:VOD and #EXT-X-ENDLIST, leaving
#EXT-X-MEDIA-SEQUENCE — always the first listed segment's number — to tell a player that
segments have rolled off the front (RFC 8216 §6.2.2). On the DASH side MpdOptions::is_static =
false writes type="dynamic" with availabilityStartTime, minimumUpdatePeriod and
timeShiftBufferDepth and no mediaPresentationDuration — the attribute set TS 103 420 §D.2.3's
own example MPD carries — and the SegmentTemplate's @startNumber and the SegmentTimeline's
first <S t="…"> both come from the window rather than being assumed to be the start of the
track. iclforge::containers::mp4 has no clock (no file I/O, no time), so the caller supplies the timestamp strings;
that is also what keeps the manifests deterministic under test.
This is what forge record/forge live with container=fmp4 and the GUI's live session with
fragmented MP4/CMAF selected write through: the directory is a servable live origin while the
session runs, and a closed VOD one afterwards. Fmp4FolderWriter (apps/shared/media/src) scans an AC-3 or
E-AC-3 take's first frame for its track, and takes an AC-4 take's track, brands and manifest values
from its caller (Fmp4FolderWriter::Track), with each frame's sync flag.
External validation¶
iclforge::containers::mp4::fragment's ISOBMFF output and the HLS media playlist round-trip cleanly through FFmpeg's
own strict decode (ffmpeg -v error -xerror -err_detect crccheck+bitstream+buffer+explode) —
both the fragmented file (init segment concatenated with every media segment) and audio.m3u8
read back the exact original frame count and duration. The same holds for what FragmentWriter
streams, and for the DASH MPD: see Validation
for exactly what was and was not checked externally.
TrueHD in the containers¶
iclforge::containers carries Dolby TrueHD in MP4, Matroska and MPEG-TS, and packs it as MAT for HDMI. As for the
other codecs, the containers read no codec: the caller passes whole access units, each with its 4-byte header and
unmodified (iclforge::truehd::ElementaryReader yields exactly that), and tells the container which units open with a
major sync. TH spec §21 names these formats but gives no layout for any of them, so each is the layout FFmpeg's muxer
writes, with FFmpeg's own demuxer and muxer as the check in both directions. No document was found for the MP4 and MAT
layouts, and no receiver or disc player has read either. libs/containers/ERRATA.md
records each layout, the evidence and the questions that are open.
| Container | How | Notes |
|---|---|---|
| MP4 | mp4::mux and mp4::fragment with AudioTrack::codec_id kCodecTruehd (mlpa), the dmlp payload from mp4::build_dmlp_payload and sync_samples set on the units with a major sync |
One access unit to a sample. The sample entry's rate field is a plain integer, not 16.16, so 96 and 192 kHz fit. An Edit drops the padding samples the last unit's end-of-stream marker counts. mp4::demux and mp4::Reader return the dmlp fields in ReadTrack::codec_config. |
| Matroska | matroska::mux and matroska::Writer with kCodecTruehd (A_TRUEHD), no CodecPrivate, MuxOptions::key_frames (or Writer::push(frame, keyframe)) set on the units with a major sync, and AudioTrack::bit_depth if the caller knows it |
matroska::demux selects an A_TRUEHD track as it does A_AC3 and A_EAC3. |
| MPEG-TS | mpegts::mux and mpegts::Writer with AudioCodec::kTruehd and BroadcastProfile::kBluray: stream_type 0x83 and a program-level HDMV registration descriptor |
mpegts::demux takes 0x83 with or without the registration (ReadStream::signalling says which) and reads 188- and 192-byte packets. There is no M2TS writer. The payloads concatenated are the elementary stream. |
| MAT | iec61937::MatPacker, wrap_mat_stream and unwrap_mat_stream (iclforge/containers/iec61937/mat.hpp) |
24 access units to a 61,440-byte IEC 61937 burst of data type 22, written as 16-bit little-endian words. The last frame is padded; FFmpeg drops it. |
The checks are tools/checks/verify_truehd_containers.py (FFmpeg, over the committed fixtures: 120 legs, 8 skipped
because FFmpeg's spdif demuxer reads no stream from its own MAT) and the cases tagged [truehd] in
iclforge-containers-tests, which hold the MAT bytes to FFmpeg's by SHA-256.
Muxer errors¶
Every muxing entry point above returns std::expected, against a per-module MuxError enum
with its own describe():
| Enum | Values |
|---|---|
iclforge::containers::matroska::MuxError |
kNoFrames; kInvalidTrack (zero/negative channels or sample rate, or an empty codec id); kFrameTooLarge (a single frame beyond what one SimpleBlock can carry). |
iclforge::containers::mp4::MuxError |
kNoFrames; kInvalidTrack (here: an unrecognised codec id — only ac-3/ec-3/ac-4 are legal — or no codec_config payload, besides the zero-channel/rate cases); kFileTooLarge — mdat would need a 64-bit chunk offset (co64), which this module doesn't write, so whole-file offsets are 32-bit; kInvalidOptions (e.g. FragmentOptions::frames_per_fragment == 0, sync_samples of another length than the frames or whose first frame is not a sync sample, a brand that is not four characters, or FragmentWriter::push given a first frame that is not a sync sample). iclforge::containers::mp4::FragmentWriter::create returns the same two refusals as fragment, but never kNoFrames: a live writer stopped before its first frame simply has nothing to flush. |
iclforge::containers::mpegts::MuxError |
kNoFrames and kInvalidTrack as above; kInvalidOptions (PID collisions); kFrameTooLarge — one access unit too large for a PES packet's 16-bit length field. |
Demuxer errors¶
Each module's demux/Reader returns std::expected against its own DemuxError, which has
its own describe() overload beside MuxError's:
| Enum | Values |
|---|---|
iclforge::containers::mp4::DemuxError |
kNotIsobmff; kTruncated; kMalformed (a box, sample table or fragment layout that cannot be parsed); kNoAudioTrack; kLimitExceeded; kMoovAfterMdat (Reader only — the sample table follows the data it indexes; use demux); kProtectedTrack (the audio track has a protected sample entry, see above). |
iclforge::containers::matroska::DemuxError |
kNotMatroska (no EBML header where one has to be); kTruncated (the input ends before any track was described — a cut after one is not an error, see above); kMalformed (a vint, element or block layout that cannot be parsed, including a lace whose declared sizes overrun its block); kNoAudioTrack (Tracks held nothing selectable, or the requested track_number is absent); kLimitExceeded (an element size or nesting depth beyond ReadOptions); kEncryptedTrack (the audio track declares ContentEncryption; see its demuxing section). |
iclforge::containers::mpegts::DemuxError |
kNotTransportStream (no 188/192/204-byte sync grid found within ReadOptions::max_sync_search_bytes); kNoProgramme (no PAT, or no PMT for the programme it named — including one whose CRC failed); kNoAudioStream (the PMT held no AC-3, E-AC-3 or AC-4 elementary stream under any of the four signalling forms); kMalformed (a PES or section layout that cannot be parsed); kLimitExceeded (a PES packet or PSI section beyond ReadOptions); kScrambled (a packet of the audio PID has transport_scrambling_control set). |
Bitstream sinks (iclforge::audio)¶
The pieces below are audio-hardware-facing rather than example-driven, so there's no compiled
examples/ program to excerpt — this is reference prose pointing at the relevant header, plus
the platform and hardware-verification caveats Validation states about
each. All of them are gated by iclforge::audio::audio_backend()
(iclforge/audio/audio_backend.hpp), which reports whether capture, monitor playback and
passthrough are available on this build's platform, and why not when they aren't — this backs
the CLI's UNAVAILABLE HERE messaging for devices, record, monitor, live, outputs
and play.
iclforge::containers::iec61937 — S/PDIF burst packing and de-framing¶
iclforge/containers/iec61937/iec61937.hpp. Packs AC-3 or E-AC-3 elementary-stream frames into IEC 61937 burst
framing — the wrapper a compressed bitstream needs over PCM-shaped hardware/interfaces (S/PDIF,
HDMI) so a receiver recognizes it as AC-3/E-AC-3 rather than treating it as noisy PCM. AC-3
burst packing is byte-exact against FFmpeg's spdif muxer. E-AC-3 packing (Eac3BurstPacker)
— data type 0x15, the 24576-byte/4x-carrier-rate burst, multi-syncframe accumulation, Pd in
bytes not bits — is independently verified against both FFmpeg's spdif_header_eac3 and
Microsoft's own IEC 61937 documentation (both fetched live and cross-checked against each
other, not recalled), plus round-trip and real-audio unit tests. This header only produces the
framed bytes; getting them onto real hardware is PassthroughSink, below.
AC-4 travels in four burst types of its own, from IEC 61937-14: Pc data type 24 with
subdata types 0 to 3, which are AC-4, AC-4 HBR4, AC-4 HBR16 and AC-4 LD. Ac4BurstPacker packs one
sync frame to a burst, and a burst lasts as long as its frame, so the repetition period follows
the stream's frame rate. At 29.97, 59.94 and 119.88 fps a frame is not a whole number of IEC 60958
frames, and the periods of five bursts in a row follow the sequence Part 14's tables give. The type
sets the link: the content rate for AC-4 and AC-4 LD (48 kHz only), four times it for HBR4, and
sixteen times it on eight channels for HBR16. ac4_burst_type_for() picks the smallest type a
stream's largest frame fits. After each burst, last() reports its Pc, Pd, period, place in
its sequence and link rate; wrap_ac4_stream is the batch form. The packer is written from the
standard's text, and iclforge-containers-tests checks its periods, sequences and Pc codes against a second
transcription of the tables. No device here accepts AC-4.
Part 14 leaves two choices, and the header says which reading the packer takes. It numbers the
five bursts of a sequence without saying which frame is data-burst 0: the packer places a frame by
its phase in the five-frame cycle of ETSI TS 103 190-2 clause 5.11, from its sequence_counter,
so a stream packed from any frame gives each frame the same period. And it gives Pd in bits for
AC-4 and AC-4 LD, where IEC 61937-2 Table 2 says bytes: the packer writes bits, and the reader
takes either, since the sync frame states its own length.
From a burst's parts. A receiver of Hearth's Sendspin burst chunk holds a burst's Pc, Pd
and payload in stream order, and none of its sync words, word swap or stuffing. burst_from_parts(pc,
pd, payload, sequence_index) puts them back as the packer wrote them (a packer chooses Pc itself,
so a burst rebuilt with another Pc would be another stream to a receiver), refusing what the
packers refuse: a data type not carried, a payload that is not the length Pd says in its unit, one
that does not open with a syncword, one the period cannot hold. burst_period_bytes(pc,
sequence_index) is the burst's length, which is its repetition period, without building it. For a
link with nothing to send, null_burst(period_bytes) is a null-data burst of that length, which a
reader steps over and which, on the one receiver it was measured on, kept its Dolby lock where PCM
silence lost it in half a second. iclforge-containers-tests rebuilds every burst the packers write
over the Dolby encoder's AC-3, E-AC-3 (JOC included) and AC-4 fixtures and compares the bytes.
De-framing (the other direction) is BurstReader, unwrap_stream and
PassthroughDetector. BurstReader is a streaming Pa/Pb/Pc/Pd parser: data types 0x01
and 0x15 and AC-4's four types, both 16-bit word orders, the stuffing between bursts, Pd's
different units, and E-AC-3's 4× carrier with its multi-syncframe bursts. Feed it carrier bytes in
whatever chunks the source produces and take elementary-stream bytes out; it holds one burst plus
the caller's chunk and nothing more, so a two-hour capture costs what a two-second one does.
unwrap_stream is the batch form, mirroring wrap_stream. last_header() gives each burst's
Pc fields, its Pd as written, and where in the carrier it started, which for AC-4 is how its
period can be measured.
The input is by definition untrusted — a burst carrier comes off a wire or out of a capture
device — so nothing taken from Pd is believed past its data type's repetition period, and a
preamble not backed by a syncframe (0x0B77, or AC-4's 0xAC40 or 0xAC41) is treated as a false
match to resync past rather than a fatal error. An AC-4 burst's Pd also has to agree with the
length its sync frame states. libs/containers/fuzz/fuzz_iec61937_unwrap.cpp keeps that accurate, and feeds the
same bytes to the AC-4 packer.
This is also what closes the loop on the wrap side: bursts written by this project and by
FFmpeg's spdif muxer read back byte-exactly to the streams that went in, AC-3 and E-AC-3,
little-endian and big-endian carriers alike, and AC-4 bursts from Ac4BurstPacker read back to the
sync frames that went in, in all four types and at every frame rate. Backs forge unspdif.
PassthroughDetector answers the capture-side question — is this endpoint delivering PCM, or
somebody's bursts? — from the same interleaved float frames iclforge::audio::Capture delivers,
using carrier_from_capture to recover the PCM16 words exactly (every backend converts int16
to float by dividing by 32768, so nothing is lost). forge record uses it to write the
elementary stream instead of encoding noise; forge live uses it to stop rather than encode a
whole session of it.
iclforge::audio::PassthroughSink — exclusive-mode passthrough¶
iclforge/audio/passthrough.hpp. Exclusive-mode/direct bitstream output, AC-3, E-AC-3 or AC-4 — WASAPI
on Windows, ALSA or PipeWire on Linux, CoreAudio on macOS, a JNI-bridged AudioTrack on Android —
the path an AV receiver needs to see the raw compressed bitstream rather than decoded PCM.
Like MonitorSink below, it reports where the device has got to (position()), and can
flush(), pause() and resume(). The position counts the content's frames, 1536 to a burst in
either format, although an E-AC-3 link runs at four times the content's rate. A pause stops the
link, and a receiver drops its lock when that happens, so the first moments after a resume can
be silent.
AC-4. BitstreamFormat names AC-4's three links: kAc4 for AC-4 and AC-4 LD bursts at the
content rate, kAc4Hbr4 at four times it, and kAc4Hbr16 at sixteen times it on eight channels.
An AC-4 burst is as long as its frame's repetition period, so submit() takes any whole number of
link frames up to the longest (burst_size_fits()). Two platforms can send it: ALSA, and Android
through an ENCODING_IEC61937 track, both of which take IEC 61937 bursts as opaque two-channel
data with the non-audio flag set, whatever codec they hold. WASAPI, PipeWire and Core Audio are
asked for a codec by name (a KSDATAFORMAT_SUBTYPE_IEC61937_* subformat, a SPA IEC 958 codec, an
AudioFormatID), and none of the three has a name for AC-4 in its current SDK, so start()
refuses AC-4 there with kUnsupportedFormat. Every backend refuses kAc4Hbr16 the same way,
since none opens the eight-channel high-bit-rate link it needs.
RenderDeviceInfo::supports_ac4_passthrough says whether an endpoint takes the base link; no
platform reports whether the receiver decodes AC-4, and no receiver found so far does.
TrueHD. None. BitstreamFormat names AC-3, E-AC-3 and AC-4 only, so there is no way to ask a backend for a MAT link, and the
ALSA capability parser files a TrueHD coding type under "other". The library packs MAT bursts
(TrueHD in the containers) and forge spdif writes them to a file; nothing sends one to a device,
and no receiver has been tried with one. This is a gap against E-AC-3 and AC-4 on this page, tracked in the roadmap row
TrueHD and E-AC-3 as equals.
When the device goes away mid-stream (the cable pulled, the receiver switched off, the endpoint
disabled), the sink stops itself. running() turns false, position() reports nothing,
submit() and can_submit() refuse, flush() returns at once, and pause() and resume()
refuse with kNotRunning. A caller that retries submit() while the queue is full has to check
running() as well, because waiting does not bring a lost device back. start() can be called
again without a stop() first. The hidden [passthrough-unplug] case in iclforge-audio-tests takes a
person through this on real hardware.
Stated plainly, because this project's docs don't soften verification gaps: of the desktop
platforms, only Windows has this sink confirmed against real bitstreaming hardware — an
Onkyo TX-RZ740 over an Nvidia GPU's HDMI output locks AC-3, E-AC-3 and signed Atmos through
PassthroughSink itself, not a workaround code path; see
Windows for the full account, including two real
PassthroughSink defects that real hardware surfaced and this project fixed (a cross-thread
WASAPI crash and a stats bug that hung the CLI). Android has the same confirmation independently,
locking a real AV receiver onto real Atmos output over HDMI — see
Android. Linux and macOS remain unconfirmed against real bitstreaming
hardware; see each platform page for its own status.
iclforge::audio::sink_capabilities — reading what a sink says it accepts¶
iclforge/audio/sink_capabilities.hpp. read_sink_capabilities(device_id) reads a
render endpoint's own advertised capabilities — CEA-861 Short Audio Descriptors, the part of
EDID (over HDMI) or ELD (ALSA's own EDID-Like Data, which carries the same SADs) that says which
codecs, how many channels and which sample rates a sink accepts — rather than
enumerate_render_devices()'s own live-probe answer (open the device and try). forge play
uses it, EDID first and the probe as the documented fallback, to decide whether a source format
needs the automatic AC-3/PCM fallback described in
Commands → Following the sink.
Real on two backends today:
- ALSA reads the HD-audio kernel driver's own
/proc/asound/<card>/eld#<dev>.<port>text interface. It is already decoded from the raw CEA-861 bytes, so there is no byte layout for this project to get wrong, only the driver's own field names to read. - PipeWire reads the session manager's reading of the same descriptor: the
iec958.codecsproperty WirePlumber sets on a digital node from the sink's ELD. That gives the codecs (AC-3, E-AC-3, PCM) but no LPCM channel count or rates, which the property does not carry. A node without the property reportskNoEdid.
Neither is verified against real HDMI/ELD hardware. The development environment this shipped from has no Linux box with a bitstream-capable receiver attached; see Linux for the current status.
Every other backend (Windows, macOS, Android, and Linux with neither ALSA nor PipeWire) reports
kNoBackend rather than guessing. None has a documented user-mode API for reading a sink's raw
SADs: Windows' WASAPI and macOS' CoreAudio both answer negotiated-format questions, the kind
enumerate_render_devices() already answers, not the sink's own descriptor.
iclforge::audio::MonitorSink — shared-mode monitor playback¶
iclforge/audio/monitor.hpp. The non-exclusive counterpart to PassthroughSink: shared-mode PCM
playback — WASAPI, ALSA, PipeWire, CoreAudio or AAudio on Android, resampled and mixed like any
other app — that decodes what is being
encoded and plays it back on an ordinary output, for previewing a decode without a
bitstream-capable receiver. Backs forge monitor and live's monitor leg.
It stops itself when its device goes away, in the same way as PassthroughSink, and
[monitor-unplug] is its hidden case. A shared-mode stream that the platform moves to another
output keeps playing; PipeWire's session manager does this when a sink is removed.
start() also distinguishes a device that refused this shared-mode sample rate or channel count
(MonitorError::kFormatRejected) from every other WASAPI/ALSA/Core Audio failure
(kComFailure). Windows and ALSA check for it precisely — the one AUDCLNT_E_UNSUPPORTED_FORMAT
HRESULT, or the channel/rate hw_params calls specifically — while Core Audio groups its
channel-count and nominal-rate checks under the same code, since its property-set calls report
only success or failure and never why. PipeWire and AAudio never return it: both hand format
negotiation to a graph/mixer that converts rather than refuses, so there is no equivalent moment
to report. On Windows the stream asks the engine to resample and re-matrix it
(AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM), so a rate the endpoint's mix format lacks - a 44.1 kHz
stream on a 48 kHz endpoint - plays rather than being refused; without that flag shared mode
takes only the mix format's own rate and width.
Unlike passthrough, this one is confirmed against real hardware. It has actually played
decoded AC-3 and E-AC-3 (including an Atmos stream's 5.1 bed) through real Windows (Realtek)
hardware in real time, and a live microphone capture → encode → monitor session has run
end-to-end. Building this path against real hardware surfaced two bugs that neither
unit tests nor silent/synthetic input would have caught — see
Windows for the details, and
libs/audio/src/backend/windows/monitor.cpp for the fixes.
Capture: iclforge::audio¶
iclforge/audio/capture.hpp, ring_buffer.hpp. Live input/loopback capture — WASAPI on Windows,
ALSA or PipeWire on Linux, CoreAudio on macOS — through the lock-free SPSC ring in ring_buffer.hpp, which
sits between the audio callback and whatever consumes the samples (an encoder, a monitor sink,
or both). On macOS capture is input-only: no loopback endpoint is ever enumerated, and
start() refuses DeviceKind::kLoopback outright rather than silently opening a microphone.
This is what backs forge record/live and the GUI's live-session tab.
A third way in, Capture::start_process_loopback(pid, mode, format), taps what
one process renders and nothing else, whichever endpoint it renders to — and it is the piece the
Crucible is built on. Three backends have one, over three
different mechanisms: Windows 10 build 20348+'s process-loopback activation, a PipeWire capture
stream linked to one application node, and (macOS 14.2+) a Core Audio process tap carried by a
private aggregate device. Only Windows walks the target's children, which is why
ProcessLoopbackMode's "tree" reads literally there and as "this process" elsewhere.
It differs from an endpoint loopback in ways worth knowing before relying on it. The caller states
the format, because there is no endpoint whose mixer format could be asked for — 48 kHz float
stereo is the default, and eight channels is honoured on Windows, where the audio engine
converts; the macOS tap has no converter behind it and refuses anything but mono or stereo, at
its own rate (see macOS). On Windows a muted audio session taps as
silence, because the tap sits after session volume, and a tap outlives its process delivering
zeros, so "the process stopped playing" has to come from the audio session list rather than from
the capture. Refusals are kProcessLoopbackUnavailable (no such tap on this platform, this
Windows build or this macOS version — and, on every macOS since 2026-09-06, because the path
is not entered by default: the one machine to run it never returned from
AudioDeviceCreateIOProcID on the tap's aggregate device, so ICLFORGE_MACOS_PROCESS_TAP is
what turns it back on. process_loopback_available() and audio_backend().process_loopback say
which of those it is, up front) and kProcessNotFound, which the library checks itself because
the OS does not.
iclforge/audio/device_watcher.hpp. DeviceWatcher delivers endpoint
added/removed/state-changed and default-changed events on a callback, so an application that
follows the sink can re-probe when something is plugged or unplugged instead of polling
enumerate_render_devices(). Three backends have one, each over its own mechanism: Windows'
IMMNotificationClient, one event per physical change (the console role only; Windows would
otherwise report every default change three times); PipeWire's registry plus the
default.audio.sink/default.audio.source metadata keys; and Core Audio property listeners on
kAudioObjectSystemObject, which report only that the device list changed and so are diffed
against a kept list of device UIDs. kStateChanged is a Windows event — on the other two an
endpoint that goes away leaves the list, and kRemoved already says so. The callback runs on a
platform thread under the watcher's own lock, which is what lets stop() promise no callback is
in flight when it returns; do the minimum there and never stop the watcher from inside it. ALSA
has no such API and the posix/android backends have no audio backend at all, so those three
refuse start() with kNoBackend.
Metering: iclforge::ac3::analysis¶
iclforge/ac3/analysis/levels.hpp. Peak/RMS metering with console ballistics, plus the Gerzon energy
vector computed over the BS.775 ring — the metering forge and the GUI share so their two
displays never disagree about what a signal contains. One LevelMeter instance drives both: the
moving display (levels(), ballistic) and the exact end-of-run report (summary(),
unweighted), fed by the same pass over the samples.
iclforge::ac3::analysis::LevelMeter meter{acmod, lfe, 48000};
meter.process(decoded_views); // once per frame, planar A/52 order
const auto& stats = meter.summary()[static_cast<std::size_t>(ch)]; // exact, not ballistic
fmt::printf("peak %.1f dBFS rms %.1f dBFS\n", stats.peak_db(), stats.rms_db());
const auto energy = iclforge::ac3::analysis::energy_vector(meter.levels(), acmod);
Full program: examples/level_metering.cpp
— decodes a 5.1 stream and reports both the per-channel peak/RMS and the soundfield's energy
vector.
This is a separate concern from the BS.1770 integrated-loudness measurement in
iclforge::ac3::meta::LoudnessMeter (see Metadata): one is instantaneous display
metering, the other the gated whole-programme measurement dialnorm is derived from.
energy_vector is computed from the integrated RMS of the full-bandwidth channels only — the
LFE has no direction to contribute, and a subwoofer's level would otherwise swamp the sum.
See also: Decoding — iclforge::ac3::io::scan is what feeds both iclforge::containers::matroska::mux and the
sinks above their access units; Header map — every header referenced on this
page in one table.