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