moq_mux/container/flv/mod.rs
1//! FLV (Flash Video / RTMP container).
2//!
3//! An interchange format only, not a wire format: [`Import`] demuxes an FLV byte
4//! stream into a broadcast and [`Export`] muxes a broadcast back into FLV. Two
5//! payload generations are handled:
6//!
7//! - **Legacy FLV/RTMP**: H.264 (AVC) video as length-prefixed NALU with an
8//! out-of-band `AVCDecoderConfigurationRecord` (avcC), and AAC audio with an
9//! out-of-band `AudioSpecificConfig`.
10//! - **Enhanced RTMP (E-RTMP)**: the FourCC payloads for HEVC (`hvc1`), AV1
11//! (`av01`), VP9 (`vp09`), Opus (`Opus`), AC-3 (`ac-3`), and E-AC-3 (`ec-3`).
12//!
13//! MP3 is handled in both generations: the legacy SoundFormat 2 tag and the
14//! E-RTMP `.mp3` FourCC on import, and the legacy SoundFormat 2 tag on export.
15//!
16//! Each codec's config record passes straight through as the catalog
17//! `description` (or, for the in-band codecs VP9 / MP3 / AC-3 / E-AC-3, is read
18//! from the frame), and the sample bytes already match the
19//! [`Legacy`](crate::catalog::hang::Wire) container, so no codec transform is
20//! needed. Other legacy codecs (VP6, Speex, …) and the E-RTMP FLAC audio are
21//! rejected on import and export.
22
23mod export;
24mod import;
25
26pub use export::*;
27pub use import::*;
28
29/// FLV import and export errors.
30#[derive(Debug, Clone, thiserror::Error)]
31#[non_exhaustive]
32pub enum Error {
33 /// A decode or presentation time falls before the stream's origin or past FLV's 32-bit
34 /// millisecond timestamp.
35 #[error("FLV timestamp before the stream's origin or past 32 bits")]
36 TimestampRange,
37
38 /// A composition time offset does not fit FLV's signed 24-bit field.
39 #[error("FLV composition time exceeds signed 24 bits")]
40 CompositionTimeRange,
41
42 /// A tag body exceeds FLV's 24-bit `DataSize` field (16 MiB).
43 #[error("FLV tag body of {0} bytes exceeds the 24-bit DataSize limit")]
44 TagTooLarge(usize),
45
46 /// More renditions of one kind than FLV's 8-bit multitrack id can number.
47 #[error("too many FLV {0} tracks")]
48 TooManyTracks(&'static str),
49
50 /// A codec that needs a sequence-header tag has no config record.
51 #[error("FLV track '{0}' missing its codec config record")]
52 MissingConfigRecord(String),
53
54 /// A rendition moved to a track with another codec after the stream header fixed its tags.
55 #[error("FLV track '{0}' moved to another codec after the stream header")]
56 CodecChanged(String),
57
58 /// A rendition's container is not one whose frames FLV tags carry as is.
59 #[error("FLV export does not support container '{container}' on {kind} track '{name}'")]
60 UnsupportedContainer {
61 /// `video` or `audio`.
62 kind: &'static str,
63 /// The rendition name.
64 name: String,
65 /// The catalog container kind.
66 container: String,
67 },
68
69 /// The video codec has no FLV or enhanced-RTMP mapping.
70 #[error("FLV export does not support video codec {0}")]
71 UnsupportedVideoCodec(String),
72
73 /// The audio codec has no FLV or enhanced-RTMP mapping.
74 #[error("FLV export does not support audio codec {0}")]
75 UnsupportedAudioCodec(String),
76
77 /// The FLV stream an import reads breaks the format, or uses a codec or layout it does not
78 /// carry.
79 #[error("{0}")]
80 Malformed(String),
81}
82
83#[cfg(test)]
84mod export_test;
85#[cfg(test)]
86mod import_test;
87
88/// FLV tag type: audio.
89const TAG_AUDIO: u8 = 8;
90/// FLV tag type: video.
91const TAG_VIDEO: u8 = 9;
92/// FLV tag type: script data (`onMetaData`, etc.).
93const TAG_SCRIPT: u8 = 18;
94
95/// Bytes in an FLV tag header (type, data size, timestamp, stream id).
96const TAG_HEADER_LEN: usize = 11;
97/// Bytes in the `PreviousTagSize` field that trails every tag.
98const PREV_TAG_SIZE_LEN: usize = 4;
99/// Bytes in the FLV file header preceding the first `PreviousTagSize`.
100const FILE_HEADER_LEN: usize = 9;
101
102/// Video CodecID for H.264 (low nibble of a video tag's first byte).
103const VIDEO_CODEC_AVC: u8 = 7;
104/// SoundFormat for AAC (high nibble of an audio tag's first byte).
105const AUDIO_FORMAT_AAC: u8 = 10;
106/// SoundFormat for MP3 (high nibble of an audio tag's first byte).
107const AUDIO_FORMAT_MP3: u8 = 2;
108
109/// Video FrameType for a keyframe.
110const FRAME_TYPE_KEY: u8 = 1;
111/// Video FrameType for an inter frame.
112const FRAME_TYPE_INTER: u8 = 2;
113
114/// AVCPacketType for the `AVCDecoderConfigurationRecord`.
115const AVC_SEQUENCE_HEADER: u8 = 0;
116/// AVCPacketType for a length-prefixed NALU access unit.
117const AVC_NALU: u8 = 1;
118
119/// AACPacketType for the `AudioSpecificConfig`.
120const AAC_SEQUENCE_HEADER: u8 = 0;
121/// AACPacketType for a raw AAC frame.
122const AAC_RAW: u8 = 1;
123
124/// Standard first byte of an AAC audio tag: SoundFormat 10, SoundRate 3
125/// (44 kHz flag), SoundSize 1 (16-bit), SoundType 1 (stereo). The real rate and
126/// channel layout live in the `AudioSpecificConfig`, so these bits are nominal.
127const AAC_AUDIO_TAG_HEADER: u8 = (AUDIO_FORMAT_AAC << 4) | (3 << 2) | (1 << 1) | 1;
128
129/// First byte of an MP3 audio tag: SoundFormat 2, with the same nominal
130/// SoundRate / SoundSize / SoundType bits as AAC. The real rate and channel
131/// layout live in the MP3 frame header that follows, so these bits are nominal.
132const MP3_AUDIO_TAG_HEADER: u8 = (AUDIO_FORMAT_MP3 << 4) | (3 << 2) | (1 << 1) | 1;
133
134/// Enhanced-RTMP (E-RTMP) video signaling: a set high bit on a video tag's
135/// first byte switches from a legacy CodecID to a FourCC codec + packet type.
136const VIDEO_EX_HEADER: u8 = 0x80;
137
138/// Enhanced video `VideoPacketType` (low nibble of an ex-video tag's first byte).
139const VIDEO_PACKET_SEQUENCE_START: u8 = 0;
140const VIDEO_PACKET_CODED_FRAMES: u8 = 1;
141const VIDEO_PACKET_SEQUENCE_END: u8 = 2;
142/// Coded frames with the composition-time offset omitted (always zero).
143const VIDEO_PACKET_CODED_FRAMES_X: u8 = 3;
144const VIDEO_PACKET_METADATA: u8 = 4;
145/// Multitrack framing: the next byte carries the `AvMultitrackType` plus the real
146/// `VideoPacketType`, and each track payload is tagged with its own track id.
147const VIDEO_PACKET_MULTITRACK: u8 = 5;
148
149/// Enhanced-RTMP audio signaling: SoundFormat 9 in the high nibble of an audio
150/// tag's first byte switches to a FourCC codec + packet type.
151const AUDIO_FORMAT_EX: u8 = 9;
152
153/// Enhanced audio `AudioPacketType` (low nibble of an ex-audio tag's first byte).
154const AUDIO_PACKET_SEQUENCE_START: u8 = 0;
155const AUDIO_PACKET_CODED_FRAMES: u8 = 1;
156const AUDIO_PACKET_SEQUENCE_END: u8 = 2;
157const AUDIO_PACKET_MULTICHANNEL_CONFIG: u8 = 4;
158/// Multitrack framing, mirroring [`VIDEO_PACKET_MULTITRACK`] for audio.
159const AUDIO_PACKET_MULTITRACK: u8 = 5;
160
161/// `AvMultitrackType` (high nibble of the multitrack framing byte): how the
162/// per-track payloads that follow are laid out.
163///
164/// - `OneTrack`: a single track, tagged with its id; the payload runs to the end
165/// of the tag (no per-track size).
166/// - `ManyTracks`: several tracks sharing one codec, each length-prefixed.
167/// - `ManyTracksManyCodecs`: several tracks, each carrying its own FourCC and
168/// length prefix.
169const MULTITRACK_ONE_TRACK: u8 = 0;
170const MULTITRACK_MANY_TRACKS: u8 = 1;
171const MULTITRACK_MANY_TRACKS_MANY_CODECS: u8 = 2;
172
173/// Read a 24-bit big-endian unsigned integer.
174fn read_u24(b: &[u8]) -> u32 {
175 ((b[0] as u32) << 16) | ((b[1] as u32) << 8) | (b[2] as u32)
176}
177
178/// Read a 24-bit big-endian signed integer (FLV composition time offset).
179fn read_i24(b: &[u8]) -> i32 {
180 let v = read_u24(b) as i32;
181 if v & 0x80_0000 != 0 { v - 0x100_0000 } else { v }
182}