Skip to main content

rtmp_runtime/
flv.rs

1//! FLV (Flash Video) tag framing — Adobe Flash Video File Format Specification
2//! **v10.1, Annex E**: the file header of §E.2 and the tag of §E.4.1.
3//!
4//! This is the one implementation of the FLV tag layer in the workspace (#2342): the
5//! `rtmp-runtime` session engine hands its callers FLV bytes (RTMP Audio(8)/Video(9)/
6//! Data-AMF0(18) message bodies are FLV tag bodies, Adobe RTMP 1.0 §7.1.4, §7.1.5,
7//! §7.1.2), and `transmux` builds its FLV streams from the same values instead of a
8//! second encoder. What a tag *contains* (codec headers, sequence headers, composition
9//! time) is the caller's business; this module only frames it.
10//!
11//! # Layout (Annex E)
12//!
13//! - **Header** (§E.2, 9 bytes) + `PreviousTagSize0` (4 bytes, = 0): `"FLV"`
14//!   signature, `Version`, `TypeFlags` (bit 0 audio, bit 2 video), and the
15//!   `DataOffset`.
16//! - **Tag** (§E.4.1): an 11-byte header (`TagType` UI8, `DataSize` UI24,
17//!   `Timestamp` UI24 + `TimestampExtended` UI8, `StreamID` UI24 = 0), the body,
18//!   and the UI32 `PreviousTagSize` (11 + `DataSize`).
19//!
20//! Spec: `private/specs-verified/rtmp/rtmp-runtime/rtmp.md` sections 6.6 and 9.
21//!
22//! What a tag *body* is — `VideoTagHeader`+`AVCVIDEOPACKET` (§E.4.3),
23//! `AudioTagHeader`+`AACAUDIODATA` (§E.4.2) and the `onMetaData` script body
24//! (§E.4.1) — is defined beside this framing and re-exported here.
25
26mod publish;
27mod tag_body;
28
29#[cfg(test)]
30mod publish_tests;
31
32pub use publish::{PublishMessage, PublishTrack, publish_open};
33pub(crate) use tag_body::set_data_frame_body;
34pub use tag_body::{
35    AAC_PACKET_DATA_OFFSET, AUDIO_TAG_HEADER_LEN, AVC_PACKET_DATA_OFFSET, AacPacketType,
36    AudioTagHeader, AvcPacketType, COMPOSITION_TIME_MAX, COMPOSITION_TIME_MIN, CodecId, FrameType,
37    ON_METADATA_AUDIO_CODEC_ID_AAC, ON_METADATA_VIDEO_CODEC_ID_AVC, OnMetadata, SET_DATA_FRAME,
38    SoundFormat, SoundRate, SoundSize, SoundType, VIDEO_TAG_HEADER_LEN, VideoTagHeader,
39    strip_set_data_frame,
40};
41
42use broadcast_core::error::OutputBufferTooSmall;
43use broadcast_core::len::{fit_u24, fit_u32, need_in, need_out};
44use broadcast_core::wire::{Reader, Writer};
45use broadcast_core::{Parse, Serialize};
46
47use crate::RtmpError;
48use crate::chunk::Message;
49use crate::message::MessageTypeId;
50use alloc::vec::Vec;
51
52type FlvResult<T> = core::result::Result<T, RtmpError>;
53
54/// The `OutputBufferTooSmall` a serializer returns when a buffer that passed
55/// its pre-check still cannot be sliced to the needed length.
56fn make_output_too_small(need: usize, have: usize) -> OutputBufferTooSmall {
57    OutputBufferTooSmall::new(need, have, "FLV")
58}
59
60// ── Aggregate message consts (§7.1.6 / Adobe FLV v10.1 Annex E.5) ───────
61
62/// Byte width of an Aggregate (22) sub-message header (§7.1.6, FLV
63/// Annex E.5): `Type`(1) + `DataSize`(3) + `Timestamp`(3) +
64/// `TimestampExtended`(1) + `StreamID`(3).
65pub(crate) const AGG_SUB_MESSAGE_HEADER_LEN: usize = 11;
66/// Byte width of the `Back Pointer` field following each Aggregate
67/// sub-message (§7.1.6): "size of the previous message including its
68/// header" — the same value the enclosing FLV `PreviousTagSize` convention
69/// describes (FLV Annex E.4.1's tag-header field + 24-bit `DataSize`).
70pub(crate) const AGG_BACK_POINTER_LEN: usize = 4;
71/// `TimestampExtended`'s shift into the top byte of a 32-bit timestamp:
72/// same layout the top-level `flv_tag` writes (FLV Annex E.4.1) — the
73/// 24-bit `Timestamp` field holds the low 24 bits, `TimestampExtended` the
74/// top 8.
75pub(crate) const AGG_TIMESTAMP_EXTENDED_SHIFT: u32 = 24;
76
77/// Unpack an Aggregate Message (22, §7.1.6), calling `deliver(tag_type, timestamp, payload)` for
78/// each contained Audio, Video or Data-AMF0 sub-message as an ordinary one would be delivered
79/// (§7.1.6 allows no other type); a sub-message of any other type is reported on `damage` as
80/// uninterpreted and not delivered.
81///
82/// Sub-message layout (§7.1.6, identical to the FLV tag layout of Adobe FLV v10.1 Annex
83/// E.4.1/E.5): `Type`(1) + `DataSize`(3) + `Timestamp`(3) + `TimestampExtended`(1) + `StreamID`(3,
84/// always 0) + `Data` + `Back Pointer`(4). Per §7.1.6 the aggregate's own message stream id
85/// overrides every sub-message's, and sub-message timestamps are renormalized by `offset =
86/// aggregate ts - first sub-message ts` added to each sub-message timestamp.
87///
88/// A sub-message header or `DataSize`-claimed data run reaching past the end of the aggregate
89/// body, or a `Back Pointer` that disagrees with the sub-message's actual size, ends the
90/// aggregate: the sub-messages before the malformed one were already delivered, and one is
91/// pushed onto `damage` for the rest. The connection itself is unaffected — the aggregate's
92/// own framing arrived intact, so the next message is still locatable.
93///
94/// # Errors
95/// Whatever `deliver` returns.
96pub(crate) fn unpack_aggregate(
97    msg: &Message,
98    damage: &mut Vec<broadcast_core::damage::Damage>,
99    mut deliver: impl FnMut(MessageTypeId, u32, &[u8]) -> FlvResult<()>,
100) -> FlvResult<()> {
101    let body = &msg.payload;
102    let mut first_ts: Option<u32> = None;
103    let mut offset = 0usize;
104    while offset < body.len() {
105        if body.len() - offset < AGG_SUB_MESSAGE_HEADER_LEN {
106            damage.push(crate::damage::message_dropped(msg.timestamp.millis()));
107            return Ok(());
108        }
109        let header = &body[offset..offset + AGG_SUB_MESSAGE_HEADER_LEN];
110        let tag_type = MessageTypeId::from_u8(header[0]);
111        let data_size =
112            Reader::at(header, TAG_DATA_SIZE_AT).u24("FLV aggregate sub-message")? as usize;
113        let ts_low24 = Reader::at(header, TAG_TIMESTAMP_AT).u24("FLV aggregate sub-message")?;
114        // Same layout `flv_tag` writes (Annex E.4.1): the 24-bit
115        // `Timestamp` field holds bits 0..=23, `TimestampExtended`
116        // holds the top 8.
117        let raw_ts = ts_low24
118            | (u32::from(header[TAG_TIMESTAMP_EXTENDED_AT]) << AGG_TIMESTAMP_EXTENDED_SHIFT);
119        // header[8..11] is the sub-message `StreamID` (always 0):
120        // §7.1.6 says the aggregate's own message stream id overrides
121        // every sub-message's stream id anyway, so it is ignored.
122        let data_start = offset + AGG_SUB_MESSAGE_HEADER_LEN;
123        let Some(data_end) = data_size.checked_add(data_start) else {
124            damage.push(crate::damage::message_dropped(msg.timestamp.millis()));
125            return Ok(());
126        };
127        let back_end = match data_end.checked_add(AGG_BACK_POINTER_LEN) {
128            Some(end) if end <= body.len() => end,
129            _ => {
130                damage.push(crate::damage::message_dropped(msg.timestamp.millis()));
131                return Ok(());
132            }
133        };
134        let back_pointer = Reader::at(body, back_end - AGG_BACK_POINTER_LEN).u32("Back Pointer")?;
135        let expected_back_pointer = match broadcast_core::len::fit_u32(
136            AGG_SUB_MESSAGE_HEADER_LEN + data_size,
137            "Back Pointer",
138        ) {
139            Ok(v) => v,
140            Err(_) => {
141                damage.push(crate::damage::message_dropped(msg.timestamp.millis()));
142                return Ok(());
143            }
144        };
145        if back_pointer != expected_back_pointer {
146            damage.push(crate::damage::message_dropped(msg.timestamp.millis()));
147            return Ok(());
148        }
149
150        let ts_offset = *first_ts.get_or_insert(raw_ts);
151        // §7.1.6: offset = (aggregate ts − first sub-message ts), added
152        // to each sub-message ts.
153        let adjusted = raw_ts.wrapping_add(msg.timestamp.millis().wrapping_sub(ts_offset));
154        if matches!(
155            tag_type,
156            MessageTypeId::Audio | MessageTypeId::Video | MessageTypeId::DataAmf0
157        ) {
158            deliver(tag_type, adjusted, &body[data_start..data_end])?;
159        } else {
160            damage.push(crate::damage::uninterpreted(
161                "RTMP aggregate sub-message type",
162            ));
163        }
164        offset = back_end;
165    }
166    Ok(())
167}
168
169// ── File header (§E.2) ──────────────────────────────────────────────────
170
171/// FLV file header `Signature` field (§E.2): `"FLV"`.
172pub const FLV_SIGNATURE: [u8; 3] = *b"FLV";
173/// FLV file header `Version` field this crate writes (§E.2).
174pub const FLV_VERSION: u8 = 1;
175/// `TypeFlags` bit 0 — audio tags present (§E.2).
176pub const FLV_FLAG_AUDIO: u8 = 0x04;
177/// `TypeFlags` bit 2 — video tags present (§E.2).
178pub const FLV_FLAG_VIDEO: u8 = 0x01;
179/// Byte width of the file header's fixed part (§E.2): `Signature`(3) +
180/// `Version`(1) + `TypeFlags`(1) + `DataOffset`(4).
181pub const FLV_HEADER_LEN: usize = 9;
182/// Offset of the file header's `TypeFlags` byte (§E.2).
183const FLV_FLAGS_OFFSET: usize = 4;
184/// Offset of the file header's 4-byte `DataOffset` field (§E.2).
185const FLV_DATA_OFFSET_FIELD: usize = 5;
186/// Byte width of the `PreviousTagSize0` field that follows the file header
187/// (§E.2) and of the `PreviousTagSize` field after every tag (§E.4.1).
188pub const FLV_PREV_TAG_SIZE_LEN: usize = 4;
189/// Byte width of one tag's fixed header (§E.4.1): `TagType`(1) +
190/// `DataSize`(3) + `Timestamp`(3) + `TimestampExtended`(1) + `StreamID`(3).
191pub const FLV_TAG_HEADER_LEN: usize = 11;
192/// The `DataOffset` this crate writes: the header is exactly
193/// [`FLV_HEADER_LEN`] bytes (§E.2).
194pub const FLV_DATA_OFFSET: u32 = 9;
195/// Bit position of `TimestampExtended`, which carries the top 8 bits of the
196/// tag's 32-bit millisecond `Timestamp` (§E.4.1).
197pub const FLV_TIMESTAMP_EXTENDED_SHIFT: u32 = 24;
198/// `StreamID` value of every tag this crate writes (§E.4.1).
199pub const FLV_STREAM_ID: u32 = 0;
200
201/// The FLV file header (§E.2), including the `PreviousTagSize0` that always
202/// follows it.
203#[non_exhaustive]
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
206pub struct FlvHeader<'a> {
207    /// `TypeFlags` bit 0 (§E.2): the file carries audio tags.
208    pub has_audio: bool,
209    /// `TypeFlags` bit 2 (§E.2): the file carries video tags.
210    pub has_video: bool,
211    /// The `DataOffset - 9` extra header bytes between the fixed 9-byte
212    /// header and the `PreviousTagSize0` that the parser skipped (§E.2).
213    /// Empty on every header this crate writes. The `DataOffset` field itself
214    /// is derived from this length ([`FlvHeader::data_offset`]), never stored
215    /// beside it, so a serialized header always declares exactly the bytes it
216    /// carries.
217    pub extra: &'a [u8],
218}
219
220impl<'a> FlvHeader<'a> {
221    /// A header declaring the given track kinds, with the standard
222    /// `DataOffset`.
223    pub fn new(has_audio: bool, has_video: bool) -> Self {
224        Self {
225            has_audio,
226            has_video,
227            extra: &[],
228        }
229    }
230
231    /// The `TypeFlags` byte (§E.2) this header puts on the wire.
232    pub fn type_flags(&self) -> u8 {
233        let mut flags = 0u8;
234        if self.has_audio {
235            flags |= FLV_FLAG_AUDIO;
236        }
237        if self.has_video {
238            flags |= FLV_FLAG_VIDEO;
239        }
240        flags
241    }
242
243    /// The `DataOffset` (§E.2) this header declares: [`FLV_HEADER_LEN`] plus
244    /// the length of [`FlvHeader::extra`].
245    pub fn data_offset(&self) -> usize {
246        FLV_HEADER_LEN.saturating_add(self.extra.len())
247    }
248
249    /// Offset of the first tag's header: past the `DataOffset` the header
250    /// declares and its `PreviousTagSize0` (§E.2).
251    pub fn first_tag_offset(&self) -> usize {
252        self.data_offset().saturating_add(FLV_PREV_TAG_SIZE_LEN)
253    }
254}
255
256impl FlvHeader<'_> {
257    /// The `DataOffset` the fixed 9-byte header declares (FLV §E.2), after
258    /// checking the signature, without requiring the bytes it points past.
259    /// A streaming reader uses it to bound how much it buffers before the
260    /// whole header has arrived.
261    pub fn declared_data_offset(bytes: &[u8]) -> FlvResult<u32> {
262        need_in(bytes, FLV_HEADER_LEN, "FLV header")?;
263        if bytes.get(..FLV_SIGNATURE.len()) != Some(FLV_SIGNATURE.as_slice()) {
264            return Err(RtmpError::Malformed {
265                what: "FLV header signature",
266            });
267        }
268        let field = bytes
269            .get(FLV_DATA_OFFSET_FIELD..FLV_HEADER_LEN)
270            .and_then(|b| <[u8; U32_LEN]>::try_from(b).ok())
271            .ok_or(RtmpError::Malformed {
272                what: "FLV header DataOffset",
273            })?;
274        Ok(u32::from_be_bytes(field))
275    }
276}
277
278impl<'a> Parse<'a> for FlvHeader<'a> {
279    type Error = RtmpError;
280
281    fn parse(bytes: &'a [u8]) -> FlvResult<Self> {
282        let declared = FlvHeader::declared_data_offset(bytes)?;
283        let flags = bytes[FLV_FLAGS_OFFSET];
284        let data_offset = usize::try_from(declared).map_err(|_| RtmpError::Malformed {
285            what: "FLV header DataOffset",
286        })?;
287        if data_offset < FLV_HEADER_LEN {
288            return Err(RtmpError::Malformed {
289                what: "FLV header DataOffset",
290            });
291        }
292        need_in(bytes, data_offset, "FLV header")?;
293        let extra = &bytes[FLV_HEADER_LEN..data_offset];
294        Ok(Self {
295            has_audio: flags & FLV_FLAG_AUDIO != 0,
296            has_video: flags & FLV_FLAG_VIDEO != 0,
297            extra,
298        })
299    }
300}
301
302impl<'a> Serialize for FlvHeader<'a> {
303    type Error = RtmpError;
304
305    fn serialized_len(&self) -> usize {
306        FLV_HEADER_LEN + self.extra.len() + FLV_PREV_TAG_SIZE_LEN
307    }
308
309    fn serialize_into(&self, buf: &mut [u8]) -> FlvResult<usize> {
310        let len = self.serialized_len();
311        need_out(buf, len, "FlvHeader")?;
312        let Some(out) = buf.get_mut(..len) else {
313            return Err(RtmpError::from(make_output_too_small(len, buf.len())));
314        };
315        out.get_mut(..FLV_SIGNATURE.len())
316            .unwrap_or_default()
317            .copy_from_slice(&FLV_SIGNATURE);
318        if let Some(b) = out.get_mut(FLV_SIGNATURE.len()) {
319            *b = FLV_VERSION;
320        }
321        if let Some(b) = out.get_mut(FLV_SIGNATURE.len() + 1) {
322            *b = self.type_flags();
323        }
324        let offset = fit_u32(self.data_offset(), "DataOffset")?;
325        out.get_mut(5..FLV_HEADER_LEN)
326            .unwrap_or_default()
327            .copy_from_slice(&offset.to_be_bytes());
328        let extra_start = FLV_HEADER_LEN;
329        let extra_end = extra_start + self.extra.len();
330        if let Some(dst) = out.get_mut(extra_start..extra_end) {
331            dst.copy_from_slice(self.extra);
332        }
333        out.get_mut(extra_end..len)
334            .unwrap_or_default()
335            .copy_from_slice(&0u32.to_be_bytes());
336        Ok(len)
337    }
338}
339
340// ── Tag (§E.4.1) ────────────────────────────────────────────────────────
341
342/// FLV tag `TagType` (§E.4.1), carrying the RTMP message type ids of a media
343/// tag: Audio (8), Video (9) and Data-AMF0 (18) are the same three values in
344/// both formats (RTMP §7.1.4, §7.1.5, §7.1.2).
345#[non_exhaustive]
346#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
347#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
348pub enum TagType {
349    /// Audio tag (8): `AudioTagHeader` + `AACAUDIODATA` (§E.4.2).
350    Audio,
351    /// Video tag (9): `VideoTagHeader` + `AVCVIDEOPACKET` (§E.4.3).
352    Video,
353    /// Script-data tag (18): AMF0 `onMetaData` and friends (§E.4.1).
354    Script,
355    /// Any other tag type byte: legal on the wire, opaque to this codec.
356    Reserved(u8),
357}
358
359impl TagType {
360    /// The wire byte this tag type carries (§E.4.1).
361    pub fn to_byte(self) -> u8 {
362        match self {
363            Self::Audio => MessageTypeId::Audio.to_u8(),
364            Self::Video => MessageTypeId::Video.to_u8(),
365            Self::Script => MessageTypeId::DataAmf0.to_u8(),
366            Self::Reserved(v) => v,
367        }
368    }
369
370    /// The tag type for a wire byte: the three known types, anything else
371    /// [`TagType::Reserved`].
372    pub fn from_byte(byte: u8) -> Self {
373        match byte {
374            byte if byte == MessageTypeId::Audio.to_u8() => Self::Audio,
375            byte if byte == MessageTypeId::Video.to_u8() => Self::Video,
376            byte if byte == MessageTypeId::DataAmf0.to_u8() => Self::Script,
377            other => Self::Reserved(other),
378        }
379    }
380
381    /// The spec token for the known tag types, `"reserved"` otherwise.
382    pub fn name(&self) -> &'static str {
383        match self {
384            Self::Audio => "audio",
385            Self::Video => "video",
386            Self::Script => "script",
387            Self::Reserved(_) => "reserved",
388        }
389    }
390}
391
392broadcast_core::impl_spec_display!(TagType, Reserved);
393
394/// One FLV tag (§E.4.1): its header fields, body, and the `PreviousTagSize`
395/// that follows it, so a single value is a self-contained slice of an FLV
396/// stream.
397#[derive(Debug, Clone, PartialEq, Eq)]
398#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
399pub struct FlvTag<'a> {
400    /// `TagType` byte (§E.4.1).
401    pub tag_type: TagType,
402    /// Millisecond timestamp: the UI24 `Timestamp` field plus the UI8
403    /// `TimestampExtended` as its top byte (§E.4.1).
404    pub timestamp: u32,
405    /// `StreamID` (§E.4.1), zero for every tag this crate writes.
406    pub stream_id: u32,
407    /// The tag's `Data` bytes (`DataSize` long).
408    pub body: &'a [u8],
409}
410
411impl<'a> FlvTag<'a> {
412    /// A tag on the stream every FLV stream uses (`StreamID` 0).
413    pub fn new(tag_type: TagType, timestamp: u32, body: &'a [u8]) -> Self {
414        Self {
415            tag_type,
416            timestamp,
417            stream_id: FLV_STREAM_ID,
418            body,
419        }
420    }
421
422    /// The value of the `PreviousTagSize` field following this tag (§E.4.1):
423    /// the tag's header and body, excluding that field itself.
424    pub fn previous_tag_size(&self) -> FlvResult<u32> {
425        fit_u32(
426            FLV_TAG_HEADER_LEN.saturating_add(self.body.len()),
427            "PreviousTagSize",
428        )
429        .map_err(Into::into)
430    }
431
432    /// The tag's declared `DataSize` (§E.4.1), read from `bytes`' first
433    /// [`FLV_TAG_HEADER_LEN`] bytes — how many body bytes the tag claims,
434    /// whether or not they have all arrived yet.
435    ///
436    /// # Errors
437    /// [`RtmpError::BufferTooShort`] if `bytes` does not hold a full header.
438    pub fn data_size(bytes: &'a [u8]) -> FlvResult<usize> {
439        need_in(bytes, FLV_TAG_HEADER_LEN, "FLV tag header")?;
440        let data_size = Reader::at(bytes, TAG_DATA_SIZE_AT).u24("FLV tag header")?;
441        usize::try_from(data_size).map_err(|_| RtmpError::Malformed {
442            what: "FLV tag DataSize",
443        })
444    }
445}
446
447impl<'a> FlvTag<'a> {
448    /// Parse one tag, tolerating a wrong `PreviousTagSize` (§E.4.1 makes the field redundant: it
449    /// repeats the tag's own size). The `bool` is `true` when the field was present and
450    /// disagreed with the tag's size; the tag itself is decoded from its header and `DataSize`.
451    ///
452    /// # Errors
453    /// [`RtmpError::BufferTooShort`] when the header or body has not fully arrived and
454    /// [`RtmpError::Malformed`] for an unusable `DataSize`.
455    pub fn parse_tolerant(bytes: &'a [u8]) -> FlvResult<(Self, bool)> {
456        let FlvTagHeader {
457            tag_type,
458            data_size,
459            timestamp,
460            stream_id,
461        } = FlvTagHeader::parse(bytes)?;
462        let body_end = FLV_TAG_HEADER_LEN
463            .checked_add(
464                usize::try_from(data_size).map_err(|_| RtmpError::Malformed {
465                    what: "FLV tag DataSize",
466                })?,
467            )
468            .ok_or(RtmpError::Malformed {
469                what: "FLV tag DataSize",
470            })?;
471        let body = bytes.get(FLV_TAG_HEADER_LEN..body_end).ok_or_else(|| {
472            broadcast_core::error::BufferTooShort::new(
473                body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN),
474                bytes.len(),
475                "FLV tag",
476            )
477        })?;
478        let mismatch = match bytes.get(body_end..body_end + FLV_PREV_TAG_SIZE_LEN) {
479            Some(trailing_bytes) => {
480                let trailing = u32::from_be_bytes(trailing_bytes.try_into().map_err(|_| {
481                    RtmpError::Malformed {
482                        what: "FLV tag PreviousTagSize",
483                    }
484                })?);
485                let expected = u32::try_from(body_end).map_err(|_| RtmpError::Malformed {
486                    what: "FLV tag PreviousTagSize",
487                })?;
488                trailing != expected
489            }
490            None => false,
491        };
492        Ok((
493            Self {
494                tag_type,
495                timestamp,
496                stream_id,
497                body,
498            },
499            mismatch,
500        ))
501    }
502}
503
504impl<'a> Parse<'a> for FlvTag<'a> {
505    type Error = RtmpError;
506
507    fn parse(bytes: &'a [u8]) -> FlvResult<Self> {
508        let (tag, mismatch) = Self::parse_tolerant(bytes)?;
509        if mismatch {
510            return Err(RtmpError::Malformed {
511                what: "FLV tag PreviousTagSize",
512            });
513        }
514        Ok(tag)
515    }
516}
517
518/// The 11-byte tag header of a tag whose body may not have arrived yet
519/// (§E.4.1): `TagType`, `DataSize`, `Timestamp` + `TimestampExtended` and
520/// `StreamID`, without the body — what an incremental reader needs to know how
521/// many bytes the whole tag takes before it can decode one.
522///
523/// `FlvTag::parse` and the tolerant walk both read the header through here.
524#[derive(Debug, Clone, Copy, PartialEq, Eq)]
525pub struct FlvTagHeader {
526    /// `TagType` byte (§E.4.1).
527    pub tag_type: TagType,
528    /// `DataSize` (§E.4.1): the body length that follows the header.
529    pub data_size: u32,
530    /// Millisecond timestamp: the UI24 `Timestamp` plus the UI8
531    /// `TimestampExtended` as its top byte (§E.4.1).
532    pub timestamp: u32,
533    /// `StreamID` (§E.4.1).
534    pub stream_id: u32,
535}
536
537impl FlvTagHeader {
538    /// The header of the tag starting at the front of `bytes`.
539    ///
540    /// # Errors
541    /// [`RtmpError::BufferTooShort`] when fewer than [`FLV_TAG_HEADER_LEN`]
542    /// bytes are present.
543    pub fn parse(bytes: &[u8]) -> FlvResult<Self> {
544        need_in(bytes, FLV_TAG_HEADER_LEN, "FLV tag header")?;
545        let field = |at: usize| bytes.get(at).copied().unwrap_or_default();
546        let data_size = Reader::at(bytes, TAG_DATA_SIZE_AT).u24("FLV tag header")?;
547        let ts_low24 = Reader::at(bytes, TAG_TIMESTAMP_AT).u24("FLV tag header")?;
548        let ts_extended = u32::from(field(TAG_TIMESTAMP_EXTENDED_AT));
549        let stream_id = Reader::at(bytes, TAG_STREAM_ID_AT).u24("FLV tag header")?;
550        Ok(Self {
551            tag_type: TagType::from_byte(field(0)),
552            data_size,
553            timestamp: ts_low24 | (ts_extended << FLV_TIMESTAMP_EXTENDED_SHIFT),
554            stream_id,
555        })
556    }
557
558    /// Bytes of the whole tag this header announces: header, body and the
559    /// trailing `PreviousTagSize` (§E.4.1).
560    #[must_use]
561    pub fn total_len(&self) -> usize {
562        let body = usize::try_from(self.data_size).unwrap_or(usize::MAX);
563        FLV_TAG_HEADER_LEN
564            .saturating_add(body)
565            .saturating_add(FLV_PREV_TAG_SIZE_LEN)
566    }
567}
568
569impl Serialize for FlvTagHeader {
570    type Error = RtmpError;
571
572    fn serialized_len(&self) -> usize {
573        FLV_TAG_HEADER_LEN
574    }
575
576    fn serialize_into(&self, buf: &mut [u8]) -> FlvResult<usize> {
577        need_out(buf, FLV_TAG_HEADER_LEN, "FlvTagHeader")?;
578        let mut w = Writer::new(buf);
579        w.u8(self.tag_type.to_byte(), "FLV tag TagType")?;
580        w.u24::<RtmpError>(self.data_size, "FLV tag DataSize")?;
581        w.u24::<RtmpError>(self.timestamp & TIMESTAMP_LOW24_MASK, "FLV tag Timestamp")?;
582        let extended = self.timestamp >> FLV_TIMESTAMP_EXTENDED_SHIFT;
583        let Some(extended) = u8::try_from(extended).ok() else {
584            return Err(RtmpError::Malformed {
585                what: "FLV tag TimestampExtended",
586            });
587        };
588        w.u8(extended, "FLV tag TimestampExtended")?;
589        w.u24::<RtmpError>(self.stream_id, "FLV tag StreamID")?;
590        Ok(FLV_TAG_HEADER_LEN)
591    }
592}
593
594impl Serialize for FlvTag<'_> {
595    type Error = RtmpError;
596
597    fn serialized_len(&self) -> usize {
598        FLV_TAG_HEADER_LEN
599            .saturating_add(self.body.len())
600            .saturating_add(FLV_PREV_TAG_SIZE_LEN)
601    }
602
603    fn serialize_into(&self, buf: &mut [u8]) -> FlvResult<usize> {
604        let len = self.serialized_len();
605        need_out(buf, len, "FlvTag")?;
606        let data_size = fit_u24(self.body.len(), "DataSize")?;
607        let mut w = Writer::new(buf);
608        w.u8(self.tag_type.to_byte(), "FLV tag TagType")?;
609        w.u24::<RtmpError>(data_size, "FLV tag DataSize")?;
610        w.u24::<RtmpError>(self.timestamp & TIMESTAMP_LOW24_MASK, "FLV tag Timestamp")?;
611        let timestamp_extended = self.timestamp >> FLV_TIMESTAMP_EXTENDED_SHIFT;
612        let Some(extended) = u8::try_from(timestamp_extended).ok() else {
613            return Err(RtmpError::Malformed {
614                what: "FLV tag TimestampExtended",
615            });
616        };
617        w.u8(extended, "FLV tag TimestampExtended")?;
618        w.u24::<RtmpError>(self.stream_id, "FLV tag StreamID")?;
619        let previous_tag_size = self.previous_tag_size()?;
620        w.bytes(self.body, "FLV tag body")?;
621        w.u32(previous_tag_size, "FLV tag PreviousTagSize")?;
622        Ok(len)
623    }
624}
625
626/// Offset of `DataSize` inside a tag header (§E.4.1).
627const TAG_DATA_SIZE_AT: usize = 1;
628/// Offset of the UI24 low `Timestamp` inside a tag header (§E.4.1).
629const TAG_TIMESTAMP_AT: usize = 4;
630/// Offset of `TimestampExtended` inside a tag header (§E.4.1).
631const TAG_TIMESTAMP_EXTENDED_AT: usize = 7;
632/// Offset of `StreamID` inside a tag header (§E.4.1).
633const TAG_STREAM_ID_AT: usize = 8;
634/// Byte width of a u32 field.
635const U32_LEN: usize = core::mem::size_of::<u32>();
636/// The low 24 bits of a tag's `Timestamp` (§E.4.1), the part the UI24 field
637/// carries.
638const TIMESTAMP_LOW24_MASK: u32 = 0x00FF_FFFF;
639
640// ── Tag walk ────────────────────────────────────────────────────────────
641
642/// The tags of an FLV stream, in order, starting at `header`'s first tag.
643///
644/// Strict: no resynchronisation. Every item is exactly one tag (header, body
645/// and `PreviousTagSize`); a trailing run too short to be a complete tag is
646/// yielded as an error item and ends the walk.
647pub fn tags<'a>(input: &'a [u8], header: &FlvHeader<'a>) -> Tags<'a> {
648    Tags {
649        input,
650        offset: header.first_tag_offset(),
651    }
652}
653
654/// Iterator over an FLV stream's tags — see [`tags`].
655#[derive(Debug, Clone)]
656pub struct Tags<'a> {
657    input: &'a [u8],
658    offset: usize,
659}
660
661impl<'a> Iterator for Tags<'a> {
662    type Item = FlvResult<FlvTag<'a>>;
663
664    fn next(&mut self) -> Option<Self::Item> {
665        let rest = self.input.get(self.offset..)?;
666        if rest.is_empty() {
667            return None;
668        }
669        let tag = match FlvTag::parse(rest) {
670            Ok(tag) => tag,
671            Err(err) => {
672                self.offset = self.input.len();
673                return Some(Err(err));
674            }
675        };
676        self.offset = self.offset.saturating_add(tag.serialized_len());
677        Some(Ok(tag))
678    }
679}
680
681// ── Tolerant walk (resynchronising) ─────────────────────────────────────
682
683/// A tag header at `off` that is structurally plausible: a readable header,
684/// the always-zero 24-bit `StreamID` (§E.4.1) and, when `known_type`, one of
685/// the tag types a media demuxer reads. Unknown types are legal (a walker
686/// skips them leniently), so the chain check along the stream accepts them;
687/// only a *resync candidate*, picked out of arbitrary bytes, is held to a
688/// known type.
689fn plausible_tag_header(input: &[u8], off: usize, known_type: bool) -> bool {
690    off.saturating_add(FLV_TAG_HEADER_LEN) <= input.len()
691        && (!known_type
692            || [
693                MessageTypeId::Audio,
694                MessageTypeId::Video,
695                MessageTypeId::DataAmf0,
696            ]
697            .contains(&MessageTypeId::from_u8(input[off])))
698        && input[off + TAG_STREAM_ID_AT..off + FLV_TAG_HEADER_LEN] == [0, 0, 0]
699}
700
701/// The `DataSize` of the tag whose header starts at `off` (the caller has
702/// checked that the header is readable).
703fn tag_data_size(input: &[u8], off: usize) -> usize {
704    FlvTagHeader::parse(&input[off..])
705        .ok()
706        .and_then(|header| usize::try_from(header.data_size).ok())
707        .unwrap_or_default()
708}
709
710/// Whether the tag starting at `off` is followed by a consistent chain: its
711/// body fits, and what follows it is the end of the buffer or another
712/// plausible tag header.
713fn tag_chain_holds(input: &[u8], off: usize, known_type: bool) -> bool {
714    if !plausible_tag_header(input, off, known_type) {
715        return false;
716    }
717    let Some(body_end) = off
718        .saturating_add(FLV_TAG_HEADER_LEN)
719        .checked_add(tag_data_size(input, off))
720    else {
721        return false;
722    };
723    if body_end > input.len() {
724        return false;
725    }
726    let next = body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN);
727    next.saturating_add(FLV_TAG_HEADER_LEN) > input.len()
728        || plausible_tag_header(input, next, false)
729}
730
731/// First offset at or after `from` where a consistent chain of known-type tags
732/// starts.
733fn resync_tag(input: &[u8], from: usize) -> Option<usize> {
734    (from..input.len()).find(|&at| tag_chain_holds(input, at, true))
735}
736
737/// An FLV stream walked tolerantly: every tag, the damaged spans skipped, and
738/// whether the input ended on a short tail — see [`tags_resync`].
739#[derive(Debug, Clone, PartialEq, Eq)]
740pub struct ResyncWalk<'a> {
741    /// The complete tags, in order, with their offsets.
742    pub tags: Vec<(usize, FlvTag<'a>)>,
743    /// Offsets of the spans whose tag framing was damaged and skipped.
744    pub damaged: Vec<usize>,
745    /// Offsets of the tags kept although their `PreviousTagSize` disagreed with their size.
746    pub bad_previous_tag_sizes: Vec<usize>,
747    /// `Some` when the input ends mid-tag: the tag it stopped at, and the
748    /// bytes that tag would need against the bytes actually present.
749    pub truncated_tail: Option<(usize, usize, usize)>,
750}
751
752impl ResyncWalk<'_> {
753    /// One report per skip this walk made: a damaged span
754    /// ([`broadcast_core::damage::DamageKind::Resynchronised`] over the bytes
755    /// jumped) and a truncated tail
756    /// ([`broadcast_core::damage::DamageKind::InputTruncated`]). A caller that
757    /// publishes damage reports hands these on rather than leaving
758    /// [`Self::damaged`] and [`Self::truncated_tail`] unread.
759    #[must_use]
760    pub fn damage(&self) -> Vec<broadcast_core::damage::Damage> {
761        let mut reports =
762            Vec::with_capacity(self.damaged.len() + self.bad_previous_tag_sizes.len() + 1);
763        for (index, start) in self.damaged.iter().enumerate() {
764            let end = self
765                .damaged
766                .get(index + 1)
767                .copied()
768                .or_else(|| self.tags.get(index).map(|(offset, _)| *offset))
769                .unwrap_or(*start);
770            let len = end.saturating_sub(*start) as u64;
771            reports.push(
772                broadcast_core::damage::Damage::new(
773                    broadcast_core::damage::DamageKind::Resynchronised,
774                    broadcast_core::damage::Severity::Degraded,
775                    "FLV tag",
776                )
777                .with_byte_range(broadcast_core::range::ByteRange::new(*start as u64, len)),
778            );
779        }
780        for offset in &self.bad_previous_tag_sizes {
781            reports.push(
782                broadcast_core::damage::Damage::new(
783                    broadcast_core::damage::DamageKind::MetadataSkipped,
784                    broadcast_core::damage::Severity::Informational,
785                    "FLV PreviousTagSize",
786                )
787                .with_byte_range(broadcast_core::range::ByteRange::new(
788                    *offset as u64,
789                    FLV_TAG_HEADER_LEN as u64,
790                )),
791            );
792        }
793        if let Some((start, need, have)) = self.truncated_tail {
794            let missing = need.saturating_sub(have) as u64;
795            reports.push(
796                broadcast_core::damage::Damage::new(
797                    broadcast_core::damage::DamageKind::InputTruncated,
798                    broadcast_core::damage::Severity::Degraded,
799                    "FLV tag",
800                )
801                .with_byte_range(broadcast_core::range::ByteRange::new(start as u64, missing)),
802            );
803        }
804        reports
805    }
806}
807
808/// What an incremental caller should do with the bytes at the front of its
809/// buffer — see [`resync_decision`].
810#[derive(Debug, Clone, Copy, PartialEq, Eq)]
811#[non_exhaustive]
812pub enum ResyncDecision {
813    /// The front is the start of a consistent tag chain: parse it normally.
814    Tag,
815    /// More input is needed before the front can be decided. The buffer must
816    /// hold at least this many bytes in total.
817    Need(usize),
818    /// The front bytes are damaged: skip this many and decide again. The skip
819    /// is one span, reported once by the caller.
820    Skip(usize),
821}
822
823/// Decide what to do with the bytes at the front of a streaming buffer, using
824/// the same consistency rule [`tags_resync`] walks with.
825///
826/// Unlike [`tags_resync`], nothing is retained here: the caller keeps the
827/// buffer and acts on the decision, so a streaming demux can resynchronise
828/// while holding at most the bytes one candidate tag's own header declares.
829#[must_use]
830pub fn resync_decision(input: &[u8], at_eof: bool) -> ResyncDecision {
831    if input.len() < FLV_TAG_HEADER_LEN {
832        return ResyncDecision::Need(FLV_TAG_HEADER_LEN);
833    }
834    // A complete tag whose own trailing `PreviousTagSize` agrees with its
835    // header is whole: it needs no second opinion from the tag after it, so a
836    // streaming caller does not have to wait for that tag's header.
837    if let Ok(header) = FlvTagHeader::parse(input) {
838        let total = header.total_len();
839        if input.len() >= total && FlvTag::parse(&input[..total]).is_ok() {
840            return ResyncDecision::Tag;
841        }
842    }
843    if tag_chain_holds(input, 0, false) {
844        if !at_eof {
845            // The chain "holds" here only because the header after this tag has
846            // not arrived yet. Waiting for it is what tells a real tag from a
847            // damaged one whose declared body runs into the next tag.
848            let next = FLV_TAG_HEADER_LEN
849                .saturating_add(tag_data_size(input, 0))
850                .saturating_add(FLV_PREV_TAG_SIZE_LEN);
851            if next.saturating_add(FLV_TAG_HEADER_LEN) > input.len() {
852                return ResyncDecision::Need(next.saturating_add(FLV_TAG_HEADER_LEN));
853            }
854        }
855        return ResyncDecision::Tag;
856    }
857    // A plausible header whose own body has not fully arrived is a tag still
858    // being read, not damage: wait for exactly that body. At end of input it
859    // cannot arrive, so the front is damaged and the scan below decides.
860    if plausible_tag_header(input, 0, false) {
861        let body_end = FLV_TAG_HEADER_LEN.saturating_add(tag_data_size(input, 0));
862        if body_end > input.len() && !at_eof {
863            return ResyncDecision::Need(body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN));
864        }
865    }
866    for at in 1..input.len() {
867        if !plausible_tag_header(input, at, true) {
868            continue;
869        }
870        let body_end = at
871            .saturating_add(FLV_TAG_HEADER_LEN)
872            .saturating_add(tag_data_size(input, at));
873        if body_end > input.len() {
874            if at_eof {
875                continue;
876            }
877            // An earlier plausible tag may be the resync point; a later
878            // candidate must not preempt it, so wait for this one's body.
879            return ResyncDecision::Need(body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN));
880        }
881        if !at_eof
882            && body_end
883                .saturating_add(FLV_PREV_TAG_SIZE_LEN)
884                .saturating_add(FLV_TAG_HEADER_LEN)
885                > input.len()
886        {
887            // The candidate's body is complete, but the header that would
888            // prove its chain has not fully arrived: accepting it now could
889            // lock onto a stray byte pattern inside a damaged tag, and a LATER
890            // candidate must not preempt this earlier one (a whole-buffer walk
891            // decides the earliest first). Wait for this one.
892            return ResyncDecision::Need(
893                body_end
894                    .saturating_add(FLV_PREV_TAG_SIZE_LEN)
895                    .saturating_add(FLV_TAG_HEADER_LEN),
896            );
897        }
898        if tag_chain_holds(input, at, true) {
899            return ResyncDecision::Skip(at);
900        }
901    }
902    if at_eof {
903        // No consistent tag chain anywhere in what is left: the tail is
904        // damaged. Consume it (keeping less than one tag header so the next
905        // decision terminates) and let the caller report the span.
906        return ResyncDecision::Skip(input.len().saturating_sub(FLV_TAG_HEADER_LEN - 1));
907    }
908    ResyncDecision::Need(input.len().saturating_add(1))
909}
910
911/// Walk an FLV stream's tags tolerantly, from `header`'s first tag.
912///
913/// Unlike the strict [`tags`], a stream whose framing is damaged part-way
914/// still yields the tags after the damage: a span whose tag chain does not hold
915/// is skipped to the next consistent chain of known-type tags and reported in
916/// [`ResyncWalk::damaged`], and a final tag whose body overruns the input stops
917/// the walk (reported in [`ResyncWalk::truncated_tail`]) rather than losing the
918/// good prefix. Two shapes are not truncation: a final tag whose body is
919/// complete but whose 4-byte `PreviousTagSize` is missing (§E.4.1 makes that
920/// field redundant — it repeats the tag's own size) is kept and the walk ends
921/// cleanly, and a header too short to read at the very end of the input is
922/// simply the end of the walk.
923///
924/// # Errors
925/// [`RtmpError::BufferTooShort`] when `input` is shorter than the header and
926/// its `PreviousTagSize0`, and when the *first* tag is already incomplete (that
927/// is not a recoverable tail: there is nothing complete to return).
928pub fn tags_resync<'a>(input: &'a [u8], header: &FlvHeader<'a>) -> FlvResult<ResyncWalk<'a>> {
929    need_in(
930        input,
931        FLV_HEADER_LEN.saturating_add(FLV_PREV_TAG_SIZE_LEN),
932        "FLV header",
933    )?;
934    let mut off = header.first_tag_offset();
935    let mut walk = ResyncWalk {
936        tags: Vec::new(),
937        damaged: Vec::new(),
938        bad_previous_tag_sizes: Vec::new(),
939        truncated_tail: None,
940    };
941    while off.saturating_add(FLV_TAG_HEADER_LEN) <= input.len() {
942        if !tag_chain_holds(input, off, false)
943            && let Some(next) = resync_tag(input, off + 1)
944        {
945            walk.damaged.push(off);
946            off = next;
947            continue;
948        }
949        let Some(body_end) = off
950            .saturating_add(FLV_TAG_HEADER_LEN)
951            .checked_add(tag_data_size(input, off))
952        else {
953            return Err(RtmpError::Malformed {
954                what: "FLV tag DataSize",
955            });
956        };
957        if body_end > input.len() {
958            let need = body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN);
959            if walk.tags.is_empty() && walk.damaged.is_empty() {
960                return Err(RtmpError::BufferTooShort(
961                    broadcast_core::error::BufferTooShort::new(need, input.len(), "FLV tag body"),
962                ));
963            }
964            walk.truncated_tail = Some((off, need, input.len().saturating_sub(off)));
965            return Ok(walk);
966        }
967        let codec_end = body_end
968            .saturating_add(FLV_PREV_TAG_SIZE_LEN)
969            .min(input.len());
970        let (tag, mismatch) =
971            FlvTag::parse_tolerant(input.get(off..codec_end).unwrap_or_default())?;
972        if mismatch {
973            walk.bad_previous_tag_sizes.push(off);
974        }
975        walk.tags.push((off, tag));
976        if body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN) > input.len() {
977            return Ok(walk);
978        }
979        off = body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN);
980    }
981    Ok(walk)
982}
983
984// ── Session writer ──────────────────────────────────────────────────────
985
986/// Builds the FLV byte stream of one RTMP session: the first tag is prefixed
987/// with the file header ([`FlvHeader`] + `PreviousTagSize0`), every tag carries
988/// its own header and `PreviousTagSize`, so concatenating every returned chunk
989/// in order yields a valid FLV stream.
990#[derive(Debug, Default)]
991pub(crate) struct FlvTagWriter {
992    header_sent: bool,
993}
994
995impl FlvTagWriter {
996    /// One FLV tag for a media or script message body (file header first time).
997    ///
998    /// # Errors
999    /// [`RtmpError::FieldOverflow`] if `payload` does not fit the tag's 24-bit
1000    /// `DataSize`, or the session's FLV bytes cannot be built.
1001    pub(crate) fn tag(
1002        &mut self,
1003        tag_type: MessageTypeId,
1004        timestamp: u32,
1005        payload: &[u8],
1006    ) -> FlvResult<Vec<u8>> {
1007        let payload = if tag_type == MessageTypeId::DataAmf0 {
1008            strip_set_data_frame(payload)
1009        } else {
1010            payload
1011        };
1012        let mut flv = if self.header_sent {
1013            Vec::new()
1014        } else {
1015            self.header_sent = true;
1016            FlvHeader::new(true, true).try_to_bytes()?
1017        };
1018        let tag = FlvTag::new(TagType::from_byte(tag_type.to_u8()), timestamp, payload);
1019        flv.extend_from_slice(&tag.try_to_bytes()?);
1020        Ok(flv)
1021    }
1022}
1023
1024#[cfg(test)]
1025mod tests {
1026    use super::*;
1027    use crate::ids::{ChunkStreamId, MessageStreamId, Timestamp};
1028
1029    fn header(tag_type: TagType, timestamp: u32, data_size: u32) -> FlvTagHeader {
1030        FlvTagHeader {
1031            tag_type,
1032            data_size,
1033            timestamp,
1034            stream_id: 0,
1035        }
1036    }
1037
1038    fn tag(tag_type: TagType, timestamp: u32, body: &[u8]) -> Vec<u8> {
1039        let header = header(
1040            tag_type,
1041            timestamp,
1042            u32::try_from(body.len()).expect("fits"),
1043        );
1044        let mut out = vec![0u8; header.total_len()];
1045        header
1046            .serialize_into(&mut out[..FLV_TAG_HEADER_LEN])
1047            .unwrap();
1048        out[FLV_TAG_HEADER_LEN..FLV_TAG_HEADER_LEN + body.len()].copy_from_slice(body);
1049        let previous = u32::try_from(FLV_TAG_HEADER_LEN + body.len()).expect("fits");
1050        out[FLV_TAG_HEADER_LEN + body.len()..].copy_from_slice(&previous.to_be_bytes());
1051        out
1052    }
1053
1054    fn aggregate_msg(timestamp: u32, payload: Vec<u8>) -> Message {
1055        Message {
1056            chunk_stream_id: ChunkStreamId::new(3),
1057            timestamp: Timestamp::from_millis(timestamp),
1058            message_type_id: MessageTypeId::Aggregate,
1059            message_stream_id: MessageStreamId::new(1),
1060            payload,
1061        }
1062    }
1063
1064    fn sub_message(tag_type: MessageTypeId, timestamp: u32, body: &[u8]) -> Vec<u8> {
1065        let mut out = vec![0u8; AGG_SUB_MESSAGE_HEADER_LEN];
1066        out[0] = tag_type.to_u8();
1067        let size = u32::try_from(body.len()).expect("fits");
1068        out[1..4].copy_from_slice(&size.to_be_bytes()[1..]);
1069        out[4..7].copy_from_slice(&timestamp.to_be_bytes()[1..]);
1070        out[7] = u8::try_from(timestamp >> AGG_TIMESTAMP_EXTENDED_SHIFT).expect("fits");
1071        out.extend_from_slice(body);
1072        out.extend_from_slice(
1073            &u32::try_from(AGG_SUB_MESSAGE_HEADER_LEN + body.len())
1074                .expect("fits")
1075                .to_be_bytes(),
1076        );
1077        out
1078    }
1079
1080    #[test]
1081    fn an_aggregate_delivers_only_audio_video_and_data_sub_messages() {
1082        let mut payload = Vec::new();
1083        payload.extend_from_slice(&sub_message(MessageTypeId::Audio, 0, &[1]));
1084        payload.extend_from_slice(&sub_message(MessageTypeId::CommandAmf0, 1, &[2]));
1085        payload.extend_from_slice(&sub_message(MessageTypeId::Aggregate, 2, &[3]));
1086        payload.extend_from_slice(&sub_message(MessageTypeId::SetChunkSize, 3, &[4]));
1087        payload.extend_from_slice(&sub_message(MessageTypeId::Video, 4, &[5]));
1088        let mut delivered = Vec::new();
1089        let mut damage = Vec::new();
1090        unpack_aggregate(&aggregate_msg(0, payload), &mut damage, |tt, ts, _| {
1091            delivered.push((tt, ts));
1092            Ok(())
1093        })
1094        .unwrap();
1095        assert_eq!(
1096            delivered,
1097            [(MessageTypeId::Audio, 0), (MessageTypeId::Video, 4)]
1098        );
1099        assert_eq!(damage.len(), 3);
1100        assert!(
1101            damage
1102                .iter()
1103                .all(|d| d.kind() == broadcast_core::damage::DamageKind::MetadataUninterpreted)
1104        );
1105    }
1106
1107    #[test]
1108    fn aggregate_rebases_extended_sub_message_timestamps() {
1109        let big = vec![0xB0u8; 65_837];
1110        let mut payload = Vec::new();
1111        payload.extend_from_slice(&sub_message(
1112            MessageTypeId::Audio,
1113            0x0000_0010,
1114            &[0xA1, 0xA2],
1115        ));
1116        payload.extend_from_slice(&sub_message(MessageTypeId::Video, 0x0100_0020, &big));
1117        payload.extend_from_slice(&sub_message(MessageTypeId::DataAmf0, 0x0000_0030, &[0xC1]));
1118
1119        let mut delivered = Vec::new();
1120        let mut damage = Vec::new();
1121        unpack_aggregate(
1122            &aggregate_msg(0x0100_0100, payload),
1123            &mut damage,
1124            |tt, ts, body| {
1125                delivered.push((tt, ts, body.to_vec()));
1126                Ok(())
1127            },
1128        )
1129        .expect("well-formed aggregate");
1130        assert!(damage.is_empty(), "a well-formed aggregate reports nothing");
1131        assert_eq!(delivered.len(), 3);
1132        assert_eq!(
1133            delivered[0],
1134            (MessageTypeId::Audio, 0x0100_0100, vec![0xA1, 0xA2])
1135        );
1136        assert_eq!(delivered[1].0, MessageTypeId::Video);
1137        assert_eq!(delivered[1].1, 0x0200_0110);
1138        assert_eq!(delivered[1].2.len(), 65_837);
1139        assert_eq!(delivered[1].2[0], 0xB0);
1140        assert_eq!(
1141            delivered[2],
1142            (MessageTypeId::DataAmf0, 0x0100_0120, vec![0xC1])
1143        );
1144    }
1145
1146    /// The sub-message run past the aggregate's end is malformed, but it no
1147    /// longer ends the session: the good sub-messages before it were already
1148    /// delivered and the rest is reported.
1149    #[test]
1150    fn aggregate_header_exactly_at_the_end_is_malformed_as_data_overrun() {
1151        let mut payload = sub_message(MessageTypeId::Audio, 0, &[1]);
1152        payload.extend_from_slice(&[0u8; AGG_SUB_MESSAGE_HEADER_LEN]);
1153        let mut damage = Vec::new();
1154        let mut delivered = 0usize;
1155        unpack_aggregate(&aggregate_msg(0, payload), &mut damage, |_, _, _| {
1156            delivered += 1;
1157            Ok(())
1158        })
1159        .expect("a malformed sub-message must not end the session");
1160        assert_eq!(delivered, 1, "the good sub-message before it is delivered");
1161        assert_eq!(damage.len(), 1, "the overrunning sub-message is reported");
1162        assert_eq!(
1163            damage[0].kind(),
1164            broadcast_core::damage::DamageKind::MediaUnitDropped
1165        );
1166    }
1167
1168    #[test]
1169    fn aggregate_truncated_into_a_sub_message_is_malformed() {
1170        let mut payload = sub_message(MessageTypeId::Audio, 0, &[1, 2, 3]);
1171        let full_len = payload.len();
1172        payload.truncate(full_len - 1);
1173        let mut damage = Vec::new();
1174        assert!(
1175            unpack_aggregate(&aggregate_msg(0, payload), &mut damage, |_, _, _| Ok(())).is_ok()
1176        );
1177        assert_eq!(damage.len(), 1);
1178
1179        let mut payload = sub_message(MessageTypeId::Audio, 0, &[1, 2, 3]);
1180        payload.extend_from_slice(&[0xFF, 0xFF, 0xFF]);
1181        let mut damage = Vec::new();
1182        assert!(
1183            unpack_aggregate(&aggregate_msg(0, payload), &mut damage, |_, _, _| Ok(())).is_ok()
1184        );
1185        assert_eq!(damage.len(), 1);
1186    }
1187
1188    #[test]
1189    fn tag_type_from_byte_maps_the_three_media_types() {
1190        assert_eq!(TagType::from_byte(8), TagType::Audio);
1191        assert_eq!(TagType::from_byte(9), TagType::Video);
1192        assert_eq!(TagType::from_byte(18), TagType::Script);
1193        assert_eq!(TagType::from_byte(0), TagType::Reserved(0));
1194        assert_eq!(TagType::Audio.name(), "audio");
1195        assert_eq!(TagType::Video.name(), "video");
1196        assert_eq!(TagType::Script.name(), "script");
1197        assert_eq!(TagType::Reserved(0).name(), "reserved");
1198    }
1199
1200    #[test]
1201    fn tag_header_lengths_and_bytes_are_exact() {
1202        let header = header(TagType::Audio, 0x0A0B_0C0D, 0x01_0203);
1203        assert_eq!(header.total_len(), 11 + 0x010203 + 4);
1204        assert_eq!(header.serialized_len(), 11);
1205        let mut bytes = [0u8; 11];
1206        assert_eq!(header.serialize_into(&mut bytes).unwrap(), 11);
1207        assert_eq!(
1208            bytes,
1209            [8, 0x01, 0x02, 0x03, 0x0B, 0x0C, 0x0D, 0x0A, 0, 0, 0]
1210        );
1211    }
1212
1213    #[test]
1214    fn resync_decision_keeps_waits_and_skips_to_the_same_chain() {
1215        // A whole tag at the front is kept, with or without the header that
1216        // follows it.
1217        let good = tag(TagType::Audio, 0, b"abc");
1218        assert_eq!(resync_decision(&good, false), ResyncDecision::Tag);
1219        assert_eq!(resync_decision(&good, true), ResyncDecision::Tag);
1220        // A partial header just asks for the header bytes.
1221        assert_eq!(
1222            resync_decision(&good[..5], false),
1223            ResyncDecision::Need(FLV_TAG_HEADER_LEN)
1224        );
1225        // Garbage before a consistent chain is one span to skip up to it.
1226        let mut damaged = vec![0xFFu8; 7];
1227        damaged.extend_from_slice(&good);
1228        assert_eq!(
1229            resync_decision(&damaged, false),
1230            ResyncDecision::Need(7 + 11 + 3 + FLV_PREV_TAG_SIZE_LEN + FLV_TAG_HEADER_LEN),
1231            "the candidate's chain needs its following header before it is trusted"
1232        );
1233        assert_eq!(resync_decision(&damaged, true), ResyncDecision::Skip(7));
1234        // A plausible header whose declared body has not arrived asks for the
1235        // bytes that body needs, not a skip.
1236        let declared = tag(TagType::Video, 0, &[0u8; 40]);
1237        assert_eq!(
1238            resync_decision(&declared[..FLV_TAG_HEADER_LEN + 4], false),
1239            ResyncDecision::Need(FLV_TAG_HEADER_LEN + 40 + FLV_PREV_TAG_SIZE_LEN)
1240        );
1241    }
1242
1243    #[test]
1244    fn reserved_tag_type_is_plausible_only_inside_a_chain() {
1245        let bytes = tag(TagType::Reserved(200), 0, b"abc");
1246        assert!(
1247            plausible_tag_header(&bytes, 0, false),
1248            "an unknown type is legal in a chain"
1249        );
1250        assert!(
1251            !plausible_tag_header(&bytes, 0, true),
1252            "a resync candidate must be a known media type"
1253        );
1254    }
1255
1256    #[test]
1257    fn a_chain_whose_second_header_is_implausible_does_not_hold() {
1258        let mut bytes = tag(TagType::Audio, 0, b"abc");
1259        bytes.extend_from_slice(&[0xFF; 20]);
1260        assert!(!tag_chain_holds(&bytes, 0, false));
1261        assert!(!tag_chain_holds(&bytes, 0, true));
1262    }
1263
1264    #[test]
1265    fn a_chain_ending_exactly_after_the_body_holds() {
1266        let header = header(TagType::Audio, 0, 3);
1267        let mut bytes = vec![0u8; FLV_TAG_HEADER_LEN];
1268        header.serialize_into(&mut bytes).unwrap();
1269        bytes.extend_from_slice(b"abc");
1270        assert!(tag_chain_holds(&bytes, 0, false));
1271    }
1272
1273    #[test]
1274    fn a_chain_whose_next_header_is_exactly_at_the_end_with_eleven_bytes() {
1275        let mut bytes = tag(TagType::Audio, 0, b"abc");
1276        bytes.extend_from_slice(&[0x12, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0]);
1277        assert_eq!(bytes.len(), 18 + FLV_TAG_HEADER_LEN);
1278        assert!(
1279            !tag_chain_holds(&bytes, 0, false),
1280            "an implausible header at the very end breaks the chain"
1281        );
1282    }
1283
1284    #[test]
1285    fn a_final_tag_body_reaching_the_end_without_previous_size_is_kept() {
1286        let flv_header = FlvHeader::new(true, true);
1287        let mut input = flv_header.try_to_bytes().unwrap();
1288        input.extend_from_slice(&tag(TagType::Audio, 0, b"abc"));
1289        let tail_header = header(TagType::Video, 1, 2);
1290        let mut tail = vec![0u8; FLV_TAG_HEADER_LEN];
1291        tail_header.serialize_into(&mut tail).unwrap();
1292        tail.extend_from_slice(&[0xBB, 0xCC]);
1293        input.extend_from_slice(&tail);
1294
1295        let walk = tags_resync(&input, &flv_header).expect("tolerant walk");
1296        assert_eq!(walk.tags.len(), 2);
1297        assert!(walk.truncated_tail.is_none());
1298    }
1299
1300    #[test]
1301    fn tags_resync_starts_the_search_after_the_damaged_offset() {
1302        let flv_header = FlvHeader::new(true, true);
1303        let mut input = flv_header.try_to_bytes().unwrap();
1304        input.extend_from_slice(&tag(TagType::Audio, 0, &[0u8; 7]));
1305        // The previous tag's PreviousTagSize is 18, whose last byte is the
1306        // Data-AMF0 type id: a plausible tag starts one byte before the
1307        // damaged offset. Only a search that starts at off + 1 skips it.
1308        input.extend_from_slice(&[
1309            0, 0, 1, // DataSize 1
1310            0, 0, 0, // Timestamp 0
1311            0, // TimestampExtended
1312            0, 0, 0, // StreamID
1313            0, // body
1314            0, 0, 0, 12, // PreviousTagSize = 11 + 1
1315        ]);
1316
1317        let walk = tags_resync(&input, &flv_header).expect("tolerant walk");
1318        assert_eq!(walk.tags.len(), 1);
1319        assert!(walk.damaged.is_empty());
1320        assert!(walk.truncated_tail.is_some());
1321    }
1322
1323    #[test]
1324    fn tags_resync_recovers_after_garbage() {
1325        let header = FlvHeader::new(true, true);
1326        let mut input = header.try_to_bytes().unwrap();
1327        let mut offsets = Vec::new();
1328        for i in 0..10u32 {
1329            offsets.push(input.len());
1330            input.extend_from_slice(&tag(
1331                TagType::Audio,
1332                i,
1333                &[u8::try_from(i).expect("fits"), 0xEE],
1334            ));
1335            if i == 3 {
1336                input.extend_from_slice(&[0xFF; 37]);
1337            }
1338        }
1339
1340        let walk = tags_resync(&input, &header).expect("tolerant walk");
1341        // The tag whose chain runs into the damage is skipped too, so the
1342        // three tags before it plus tags 5..10 come back.
1343        assert_eq!(
1344            walk.tags.len(),
1345            9,
1346            "offsets {:?} damaged {:?}",
1347            walk.tags.iter().map(|(o, _)| *o).collect::<Vec<_>>(),
1348            walk.damaged
1349        );
1350        assert_eq!(walk.damaged, vec![offsets[3]]);
1351        assert_eq!(walk.tags[3].0, offsets[4]);
1352        assert_eq!(walk.tags[3].1.timestamp, 4);
1353        assert_eq!(walk.tags[8].0, offsets[9]);
1354        assert_eq!(walk.tags[8].1.timestamp, 9);
1355    }
1356}