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
22use broadcast_common::error::OutputBufferTooSmall;
23use broadcast_common::len::{fit_u24, fit_u32, need_in, need_out};
24use broadcast_common::{Parse, Serialize};
25
26use crate::RtmpError;
27use crate::chunk::Message;
28use crate::message::MessageTypeId;
29use alloc::string::ToString;
30use alloc::vec::Vec;
31
32type FlvResult<T> = core::result::Result<T, RtmpError>;
33
34/// The `OutputBufferTooSmall` a serializer returns when a buffer that passed
35/// its pre-check still cannot be sliced to the needed length.
36fn make_output_too_small(need: usize, have: usize) -> OutputBufferTooSmall {
37    OutputBufferTooSmall { need, have }
38}
39
40// ── Aggregate message consts (§7.1.6 / Adobe FLV v10.1 Annex E.5) ───────
41
42/// Byte width of an Aggregate (22) sub-message header (§7.1.6, FLV
43/// Annex E.5): `Type`(1) + `DataSize`(3) + `Timestamp`(3) +
44/// `TimestampExtended`(1) + `StreamID`(3).
45pub(crate) const AGG_SUB_MESSAGE_HEADER_LEN: usize = 11;
46/// Byte width of the `Back Pointer` field following each Aggregate
47/// sub-message (§7.1.6): "size of the previous message including its
48/// header" — the same value the enclosing FLV `PreviousTagSize` convention
49/// describes (FLV Annex E.4.1's tag-header field + 24-bit `DataSize`).
50pub(crate) const AGG_BACK_POINTER_LEN: usize = 4;
51/// `TimestampExtended`'s shift into the top byte of a 32-bit timestamp:
52/// same layout the top-level `flv_tag` writes (FLV Annex E.4.1) — the
53/// 24-bit `Timestamp` field holds the low 24 bits, `TimestampExtended` the
54/// top 8.
55pub(crate) const AGG_TIMESTAMP_EXTENDED_SHIFT: u32 = 24;
56
57/// Unpack an Aggregate Message (22, §7.1.6), calling `deliver(tag_type, timestamp, payload)` for
58/// each contained sub-message as an ordinary Audio/Video/Data-AMF0 message would be delivered.
59///
60/// Sub-message layout (§7.1.6, identical to the FLV tag layout of Adobe FLV v10.1 Annex
61/// E.4.1/E.5): `Type`(1) + `DataSize`(3) + `Timestamp`(3) + `TimestampExtended`(1) + `StreamID`(3,
62/// always 0) + `Data` + `Back Pointer`(4). Per §7.1.6 the aggregate's own message stream id
63/// overrides every sub-message's, and sub-message timestamps are renormalized by `offset =
64/// aggregate ts - first sub-message ts` added to each sub-message timestamp.
65///
66/// A sub-message header or `DataSize`-claimed data run reaching past the end of the aggregate
67/// body, or a `Back Pointer` that disagrees with the sub-message's actual size, is rejected with
68/// `Malformed`; sub-messages before the malformed one were already delivered.
69///
70/// # Errors
71/// [`RtmpError::Malformed`] as above, or whatever `deliver` returns.
72pub(crate) fn unpack_aggregate(
73    msg: &Message,
74    mut deliver: impl FnMut(MessageTypeId, u32, &[u8]) -> FlvResult<()>,
75) -> FlvResult<()> {
76    let body = &msg.payload;
77    let mut first_ts: Option<u32> = None;
78    let mut offset = 0usize;
79    while offset < body.len() {
80        if body.len() - offset < AGG_SUB_MESSAGE_HEADER_LEN {
81            return Err(RtmpError::Malformed {
82                what: "aggregate sub-message header truncated",
83            });
84        }
85        let header = &body[offset..offset + AGG_SUB_MESSAGE_HEADER_LEN];
86        let tag_type = MessageTypeId::from_u8(header[0]);
87        let data_size = u32::from_be_bytes([0, header[1], header[2], header[3]]) as usize;
88        let ts_low24 = u32::from_be_bytes([0, header[4], header[5], header[6]]);
89        // Same layout `flv_tag` writes (Annex E.4.1): the 24-bit
90        // `Timestamp` field holds bits 0..=23, `TimestampExtended`
91        // holds the top 8.
92        let raw_ts = ts_low24 | (u32::from(header[7]) << AGG_TIMESTAMP_EXTENDED_SHIFT);
93        // header[8..11] is the sub-message `StreamID` (always 0):
94        // §7.1.6 says the aggregate's own message stream id overrides
95        // every sub-message's stream id anyway, so it is ignored.
96        let data_start = offset + AGG_SUB_MESSAGE_HEADER_LEN;
97        let Some(data_end) = data_size.checked_add(data_start) else {
98            return Err(RtmpError::Malformed {
99                what: "aggregate sub-message DataSize overflows",
100            });
101        };
102        let back_end = match data_end.checked_add(AGG_BACK_POINTER_LEN) {
103            Some(end) if end <= body.len() => end,
104            _ => {
105                return Err(RtmpError::Malformed {
106                    what: "aggregate sub-message data or Back Pointer runs past the end",
107                });
108            }
109        };
110        let back_pointer = u32::from_be_bytes([
111            body[back_end - AGG_BACK_POINTER_LEN],
112            body[back_end - AGG_BACK_POINTER_LEN + 1],
113            body[back_end - AGG_BACK_POINTER_LEN + 2],
114            body[back_end - AGG_BACK_POINTER_LEN + 3],
115        ]);
116        let expected_back_pointer = match broadcast_common::len::fit_u32(
117            AGG_SUB_MESSAGE_HEADER_LEN + data_size,
118            "Back Pointer",
119        ) {
120            Ok(v) => v,
121            Err(_) => {
122                return Err(RtmpError::Malformed {
123                    what: "aggregate sub-message exceeds the 32-bit Back Pointer field",
124                });
125            }
126        };
127        if back_pointer != expected_back_pointer {
128            return Err(RtmpError::Malformed {
129                what: "aggregate sub-message Back Pointer disagrees with its actual size",
130            });
131        }
132
133        let ts_offset = *first_ts.get_or_insert(raw_ts);
134        // §7.1.6: offset = (aggregate ts − first sub-message ts), added
135        // to each sub-message ts.
136        let adjusted = raw_ts.wrapping_add(msg.timestamp.millis().wrapping_sub(ts_offset));
137        deliver(tag_type, adjusted, &body[data_start..data_end])?;
138        offset = back_end;
139    }
140    Ok(())
141}
142
143// ── File header (§E.2) ──────────────────────────────────────────────────
144
145/// FLV file header `Signature` field (§E.2): `"FLV"`.
146pub const FLV_SIGNATURE: [u8; 3] = *b"FLV";
147/// FLV file header `Version` field this crate writes (§E.2).
148pub const FLV_VERSION: u8 = 1;
149/// `TypeFlags` bit 0 — audio tags present (§E.2).
150pub const FLV_FLAG_AUDIO: u8 = 0x04;
151/// `TypeFlags` bit 2 — video tags present (§E.2).
152pub const FLV_FLAG_VIDEO: u8 = 0x01;
153/// Byte width of the file header's fixed part (§E.2): `Signature`(3) +
154/// `Version`(1) + `TypeFlags`(1) + `DataOffset`(4).
155pub const FLV_HEADER_LEN: usize = 9;
156/// Offset of the file header's `TypeFlags` byte (§E.2).
157const FLV_FLAGS_OFFSET: usize = 4;
158/// Offset of the file header's 4-byte `DataOffset` field (§E.2).
159const FLV_DATA_OFFSET_FIELD: usize = 5;
160/// Byte width of the `PreviousTagSize0` field that follows the file header
161/// (§E.2) and of the `PreviousTagSize` field after every tag (§E.4.1).
162pub const FLV_PREV_TAG_SIZE_LEN: usize = 4;
163/// Byte width of one tag's fixed header (§E.4.1): `TagType`(1) +
164/// `DataSize`(3) + `Timestamp`(3) + `TimestampExtended`(1) + `StreamID`(3).
165pub const FLV_TAG_HEADER_LEN: usize = 11;
166/// The `DataOffset` this crate writes: the header is exactly
167/// [`FLV_HEADER_LEN`] bytes (§E.2).
168pub const FLV_DATA_OFFSET: u32 = 9;
169/// Bit position of `TimestampExtended`, which carries the top 8 bits of the
170/// tag's 32-bit millisecond `Timestamp` (§E.4.1).
171pub const FLV_TIMESTAMP_EXTENDED_SHIFT: u32 = 24;
172/// `StreamID` value of every tag this crate writes (§E.4.1).
173pub const FLV_STREAM_ID: u32 = 0;
174
175/// The FLV file header (§E.2), including the `PreviousTagSize0` that always
176/// follows it.
177#[non_exhaustive]
178#[derive(Debug, Clone, Copy, PartialEq, Eq)]
179#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
180pub struct FlvHeader<'a> {
181    /// `TypeFlags` bit 0 (§E.2): the file carries audio tags.
182    pub has_audio: bool,
183    /// `TypeFlags` bit 2 (§E.2): the file carries video tags.
184    pub has_video: bool,
185    /// The `DataOffset - 9` extra header bytes between the fixed 9-byte
186    /// header and the `PreviousTagSize0` that the parser skipped (§E.2).
187    /// Empty on every header this crate writes. The `DataOffset` field itself
188    /// is derived from this length ([`FlvHeader::data_offset`]), never stored
189    /// beside it, so a serialized header always declares exactly the bytes it
190    /// carries.
191    pub extra: &'a [u8],
192}
193
194impl<'a> FlvHeader<'a> {
195    /// A header declaring the given track kinds, with the standard
196    /// `DataOffset`.
197    pub fn new(has_audio: bool, has_video: bool) -> Self {
198        Self {
199            has_audio,
200            has_video,
201            extra: &[],
202        }
203    }
204
205    /// The `TypeFlags` byte (§E.2) this header puts on the wire.
206    pub fn type_flags(&self) -> u8 {
207        let mut flags = 0u8;
208        if self.has_audio {
209            flags |= FLV_FLAG_AUDIO;
210        }
211        if self.has_video {
212            flags |= FLV_FLAG_VIDEO;
213        }
214        flags
215    }
216
217    /// The `DataOffset` (§E.2) this header declares: [`FLV_HEADER_LEN`] plus
218    /// the length of [`FlvHeader::extra`].
219    pub fn data_offset(&self) -> usize {
220        FLV_HEADER_LEN.saturating_add(self.extra.len())
221    }
222
223    /// Offset of the first tag's header: past the `DataOffset` the header
224    /// declares and its `PreviousTagSize0` (§E.2).
225    pub fn first_tag_offset(&self) -> usize {
226        self.data_offset().saturating_add(FLV_PREV_TAG_SIZE_LEN)
227    }
228}
229
230impl FlvHeader<'_> {
231    /// The `DataOffset` the fixed 9-byte header declares (FLV §E.2), after
232    /// checking the signature, without requiring the bytes it points past.
233    /// A streaming reader uses it to bound how much it buffers before the
234    /// whole header has arrived.
235    pub fn declared_data_offset(bytes: &[u8]) -> FlvResult<u32> {
236        need_in(bytes, FLV_HEADER_LEN, "FLV header")?;
237        if bytes.get(..FLV_SIGNATURE.len()) != Some(FLV_SIGNATURE.as_slice()) {
238            return Err(RtmpError::Malformed {
239                what: "FLV header signature",
240            });
241        }
242        let field = bytes
243            .get(FLV_DATA_OFFSET_FIELD..FLV_HEADER_LEN)
244            .and_then(|b| <[u8; 4]>::try_from(b).ok())
245            .ok_or(RtmpError::Malformed {
246                what: "FLV header DataOffset",
247            })?;
248        Ok(u32::from_be_bytes(field))
249    }
250}
251
252impl<'a> Parse<'a> for FlvHeader<'a> {
253    type Error = RtmpError;
254
255    fn parse(bytes: &'a [u8]) -> FlvResult<Self> {
256        let declared = FlvHeader::declared_data_offset(bytes)?;
257        let flags = bytes[FLV_FLAGS_OFFSET];
258        let data_offset = usize::try_from(declared).map_err(|_| RtmpError::Malformed {
259            what: "FLV header DataOffset",
260        })?;
261        if data_offset < FLV_HEADER_LEN {
262            return Err(RtmpError::Malformed {
263                what: "FLV header DataOffset",
264            });
265        }
266        need_in(bytes, data_offset, "FLV header")?;
267        let extra = &bytes[FLV_HEADER_LEN..data_offset];
268        Ok(Self {
269            has_audio: flags & FLV_FLAG_AUDIO != 0,
270            has_video: flags & FLV_FLAG_VIDEO != 0,
271            extra,
272        })
273    }
274}
275
276impl<'a> Serialize for FlvHeader<'a> {
277    type Error = RtmpError;
278
279    fn serialized_len(&self) -> usize {
280        FLV_HEADER_LEN + self.extra.len() + FLV_PREV_TAG_SIZE_LEN
281    }
282
283    fn serialize_into(&self, buf: &mut [u8]) -> FlvResult<usize> {
284        let len = self.serialized_len();
285        need_out(buf, len)?;
286        let Some(out) = buf.get_mut(..len) else {
287            return Err(RtmpError::from(make_output_too_small(len, buf.len())));
288        };
289        out.get_mut(..FLV_SIGNATURE.len())
290            .unwrap_or_default()
291            .copy_from_slice(&FLV_SIGNATURE);
292        if let Some(b) = out.get_mut(FLV_SIGNATURE.len()) {
293            *b = FLV_VERSION;
294        }
295        if let Some(b) = out.get_mut(FLV_SIGNATURE.len() + 1) {
296            *b = self.type_flags();
297        }
298        let offset = fit_u32(self.data_offset(), "DataOffset")?;
299        out.get_mut(5..FLV_HEADER_LEN)
300            .unwrap_or_default()
301            .copy_from_slice(&offset.to_be_bytes());
302        let extra_start = FLV_HEADER_LEN;
303        let extra_end = extra_start + self.extra.len();
304        if let Some(dst) = out.get_mut(extra_start..extra_end) {
305            dst.copy_from_slice(self.extra);
306        }
307        out.get_mut(extra_end..len)
308            .unwrap_or_default()
309            .copy_from_slice(&0u32.to_be_bytes());
310        Ok(len)
311    }
312}
313
314// ── Tag (§E.4.1) ────────────────────────────────────────────────────────
315
316/// FLV tag `TagType` (§E.4.1), carrying the RTMP message type ids of a media
317/// tag: Audio (8), Video (9) and Data-AMF0 (18) are the same three values in
318/// both formats (RTMP §7.1.4, §7.1.5, §7.1.2).
319#[non_exhaustive]
320#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
321#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
322pub enum TagType {
323    /// Audio tag (8): `AudioTagHeader` + `AACAUDIODATA` (§E.4.2).
324    Audio,
325    /// Video tag (9): `VideoTagHeader` + `AVCVIDEOPACKET` (§E.4.3).
326    Video,
327    /// Script-data tag (18): AMF0 `onMetaData` and friends (§E.4.1).
328    Script,
329    /// Any other tag type byte: legal on the wire, opaque to this codec.
330    Reserved(u8),
331}
332
333impl TagType {
334    /// The wire byte this tag type carries (§E.4.1).
335    pub fn to_byte(self) -> u8 {
336        match self {
337            Self::Audio => MessageTypeId::Audio.to_u8(),
338            Self::Video => MessageTypeId::Video.to_u8(),
339            Self::Script => MessageTypeId::DataAmf0.to_u8(),
340            Self::Reserved(v) => v,
341        }
342    }
343
344    /// The tag type for a wire byte: the three known types, anything else
345    /// [`TagType::Reserved`].
346    pub fn from_byte(byte: u8) -> Self {
347        match byte {
348            byte if byte == MessageTypeId::Audio.to_u8() => Self::Audio,
349            byte if byte == MessageTypeId::Video.to_u8() => Self::Video,
350            byte if byte == MessageTypeId::DataAmf0.to_u8() => Self::Script,
351            other => Self::Reserved(other),
352        }
353    }
354
355    /// The spec token for the known tag types, `"reserved"` otherwise.
356    pub fn name(&self) -> &'static str {
357        match self {
358            Self::Audio => "audio",
359            Self::Video => "video",
360            Self::Script => "script",
361            Self::Reserved(_) => "reserved",
362        }
363    }
364}
365
366broadcast_common::impl_spec_display!(TagType, Reserved);
367
368/// One FLV tag (§E.4.1): its header fields, body, and the `PreviousTagSize`
369/// that follows it, so a single value is a self-contained slice of an FLV
370/// stream.
371#[derive(Debug, Clone, PartialEq, Eq)]
372#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
373pub struct FlvTag<'a> {
374    /// `TagType` byte (§E.4.1).
375    pub tag_type: TagType,
376    /// Millisecond timestamp: the UI24 `Timestamp` field plus the UI8
377    /// `TimestampExtended` as its top byte (§E.4.1).
378    pub timestamp: u32,
379    /// `StreamID` (§E.4.1), zero for every tag this crate writes.
380    pub stream_id: u32,
381    /// The tag's `Data` bytes (`DataSize` long).
382    pub body: &'a [u8],
383}
384
385impl<'a> FlvTag<'a> {
386    /// A tag on the stream every FLV stream uses (`StreamID` 0).
387    pub fn new(tag_type: TagType, timestamp: u32, body: &'a [u8]) -> Self {
388        Self {
389            tag_type,
390            timestamp,
391            stream_id: FLV_STREAM_ID,
392            body,
393        }
394    }
395
396    /// The value of the `PreviousTagSize` field following this tag (§E.4.1):
397    /// the tag's header and body, excluding that field itself.
398    pub fn previous_tag_size(&self) -> FlvResult<u32> {
399        fit_u32(
400            FLV_TAG_HEADER_LEN.saturating_add(self.body.len()),
401            "PreviousTagSize",
402        )
403        .map_err(Into::into)
404    }
405
406    /// The tag's declared `DataSize` (§E.4.1), read from `bytes`' first
407    /// [`FLV_TAG_HEADER_LEN`] bytes — how many body bytes the tag claims,
408    /// whether or not they have all arrived yet.
409    ///
410    /// # Errors
411    /// [`RtmpError::BufferTooShort`] if `bytes` does not hold a full header.
412    pub fn data_size(bytes: &'a [u8]) -> FlvResult<usize> {
413        need_in(bytes, FLV_TAG_HEADER_LEN, "FLV tag header")?;
414        let field = |at: usize| bytes.get(at).copied().unwrap_or_default();
415        let data_size = u32::from_be_bytes([0, field(1), field(2), field(3)]);
416        usize::try_from(data_size).map_err(|_| RtmpError::Malformed {
417            what: "FLV tag DataSize",
418        })
419    }
420}
421
422impl<'a> Parse<'a> for FlvTag<'a> {
423    type Error = RtmpError;
424
425    fn parse(bytes: &'a [u8]) -> FlvResult<Self> {
426        let FlvTagHeader {
427            tag_type,
428            data_size,
429            timestamp,
430            stream_id,
431        } = FlvTagHeader::parse(bytes)?;
432        let body_end = FLV_TAG_HEADER_LEN
433            .checked_add(
434                usize::try_from(data_size).map_err(|_| RtmpError::Malformed {
435                    what: "FLV tag DataSize",
436                })?,
437            )
438            .ok_or(RtmpError::Malformed {
439                what: "FLV tag DataSize",
440            })?;
441        // `PreviousTagSize` may be cut off a final tag: §E.4.1 makes it
442        // redundant (it repeats this tag's size), so the body is what this
443        // decode needs and the trailer is not checked.
444        let body = bytes.get(FLV_TAG_HEADER_LEN..body_end).ok_or_else(|| {
445            broadcast_common::error::BufferTooShort {
446                need: body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN),
447                have: bytes.len(),
448                what: "FLV tag",
449            }
450        })?;
451        if bytes.len() >= body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN) {
452            let trailing_bytes = bytes
453                .get(body_end..body_end + FLV_PREV_TAG_SIZE_LEN)
454                .ok_or(RtmpError::Malformed {
455                    what: "FLV tag PreviousTagSize",
456                })?;
457            let trailing = u32::from_be_bytes(trailing_bytes.try_into().map_err(|_| {
458                RtmpError::Malformed {
459                    what: "FLV tag PreviousTagSize",
460                }
461            })?);
462            let expected = u32::try_from(FLV_TAG_HEADER_LEN.saturating_add(
463                usize::try_from(data_size).map_err(|_| RtmpError::Malformed {
464                    what: "FLV tag DataSize",
465                })?,
466            ))
467            .map_err(|_| RtmpError::Malformed {
468                what: "FLV tag PreviousTagSize",
469            })?;
470            if trailing != expected {
471                return Err(RtmpError::Malformed {
472                    what: "FLV tag PreviousTagSize",
473                });
474            }
475        }
476        Ok(Self {
477            tag_type,
478            timestamp,
479            stream_id,
480            body,
481        })
482    }
483}
484
485/// The 11-byte tag header of a tag whose body may not have arrived yet
486/// (§E.4.1): `TagType`, `DataSize`, `Timestamp` + `TimestampExtended` and
487/// `StreamID`, without the body — what an incremental reader needs to know how
488/// many bytes the whole tag takes before it can decode one.
489///
490/// `FlvTag::parse` and the tolerant walk both read the header through here.
491#[derive(Debug, Clone, Copy, PartialEq, Eq)]
492pub struct FlvTagHeader {
493    /// `TagType` byte (§E.4.1).
494    pub tag_type: TagType,
495    /// `DataSize` (§E.4.1): the body length that follows the header.
496    pub data_size: u32,
497    /// Millisecond timestamp: the UI24 `Timestamp` plus the UI8
498    /// `TimestampExtended` as its top byte (§E.4.1).
499    pub timestamp: u32,
500    /// `StreamID` (§E.4.1).
501    pub stream_id: u32,
502}
503
504impl FlvTagHeader {
505    /// The header of the tag starting at the front of `bytes`.
506    ///
507    /// # Errors
508    /// [`RtmpError::BufferTooShort`] when fewer than [`FLV_TAG_HEADER_LEN`]
509    /// bytes are present.
510    pub fn parse(bytes: &[u8]) -> FlvResult<Self> {
511        need_in(bytes, FLV_TAG_HEADER_LEN, "FLV tag header")?;
512        let field = |at: usize| bytes.get(at).copied().unwrap_or_default();
513        let data_size = u32::from_be_bytes([0, field(1), field(2), field(3)]);
514        let ts_low24 = u32::from_be_bytes([0, field(4), field(5), field(6)]);
515        let ts_extended = u32::from(field(7));
516        let stream_id = u32::from_be_bytes([0, field(8), field(9), field(10)]);
517        Ok(Self {
518            tag_type: TagType::from_byte(field(0)),
519            data_size,
520            timestamp: ts_low24 | (ts_extended << FLV_TIMESTAMP_EXTENDED_SHIFT),
521            stream_id,
522        })
523    }
524
525    /// Bytes of the whole tag this header announces: header, body and the
526    /// trailing `PreviousTagSize` (§E.4.1).
527    #[must_use]
528    pub fn total_len(&self) -> usize {
529        let body = usize::try_from(self.data_size).unwrap_or(usize::MAX);
530        FLV_TAG_HEADER_LEN
531            .saturating_add(body)
532            .saturating_add(FLV_PREV_TAG_SIZE_LEN)
533    }
534}
535
536impl Serialize for FlvTagHeader {
537    type Error = RtmpError;
538
539    fn serialized_len(&self) -> usize {
540        FLV_TAG_HEADER_LEN
541    }
542
543    fn serialize_into(&self, buf: &mut [u8]) -> FlvResult<usize> {
544        need_out(buf, FLV_TAG_HEADER_LEN)?;
545        let size = ui24(self.data_size, "FLV tag DataSize")?;
546        let low = ui24(self.timestamp & TIMESTAMP_LOW24_MASK, "FLV tag Timestamp")?;
547        let extended = self.timestamp >> FLV_TIMESTAMP_EXTENDED_SHIFT;
548        let Some(extended) = u8::try_from(extended).ok() else {
549            return Err(RtmpError::Malformed {
550                what: "FLV tag TimestampExtended",
551            });
552        };
553        let stream_id = ui24(self.stream_id, "FLV tag StreamID")?;
554        let Some(header) = buf.get_mut(..FLV_TAG_HEADER_LEN) else {
555            return Err(RtmpError::Malformed {
556                what: "FLV tag header",
557            });
558        };
559        header[0] = self.tag_type.to_byte();
560        header[TAG_DATA_SIZE_AT..TAG_TIMESTAMP_AT].copy_from_slice(&size);
561        header[TAG_TIMESTAMP_AT..TAG_TIMESTAMP_EXTENDED_AT].copy_from_slice(&low);
562        header[TAG_TIMESTAMP_EXTENDED_AT] = extended;
563        header[TAG_STREAM_ID_AT..FLV_TAG_HEADER_LEN].copy_from_slice(&stream_id);
564        Ok(FLV_TAG_HEADER_LEN)
565    }
566}
567
568impl Serialize for FlvTag<'_> {
569    type Error = RtmpError;
570
571    fn serialized_len(&self) -> usize {
572        FLV_TAG_HEADER_LEN
573            .saturating_add(self.body.len())
574            .saturating_add(FLV_PREV_TAG_SIZE_LEN)
575    }
576
577    fn serialize_into(&self, buf: &mut [u8]) -> FlvResult<usize> {
578        let len = self.serialized_len();
579        need_out(buf, len)?;
580        let data_size = ui24(fit_u24(self.body.len(), "DataSize")?, "FLV tag DataSize")?;
581        let timestamp_low = ui24(self.timestamp & TIMESTAMP_LOW24_MASK, "FLV tag Timestamp")?;
582        let timestamp_extended = self.timestamp >> FLV_TIMESTAMP_EXTENDED_SHIFT;
583        let Some(extended) = u8::try_from(timestamp_extended).ok() else {
584            return Err(RtmpError::Malformed {
585                what: "FLV tag TimestampExtended",
586            });
587        };
588        let stream_id = ui24(self.stream_id, "FLV tag StreamID")?;
589        let previous_tag_size = self.previous_tag_size()?.to_be_bytes();
590        let Some(out) = buf.get_mut(..len) else {
591            return Err(RtmpError::Malformed {
592                what: "FLV tag output buffer",
593            });
594        };
595        let (header, rest) = out.split_at_mut(FLV_TAG_HEADER_LEN);
596        let Some(tag_type) = header.first_mut() else {
597            return Err(RtmpError::Malformed {
598                what: "FLV tag header",
599            });
600        };
601        *tag_type = self.tag_type.to_byte();
602        let mut write = |at: usize, bytes: &[u8]| {
603            if let Some(slot) = header.get_mut(at..at.saturating_add(bytes.len())) {
604                slot.copy_from_slice(bytes);
605            }
606        };
607        write(TAG_DATA_SIZE_AT, &data_size);
608        write(TAG_TIMESTAMP_AT, &timestamp_low);
609        write(TAG_TIMESTAMP_EXTENDED_AT, &[extended]);
610        write(TAG_STREAM_ID_AT, &stream_id);
611        let (body, trailer) = rest.split_at_mut(self.body.len());
612        body.copy_from_slice(self.body);
613        if let Some(slot) = trailer.get_mut(..FLV_PREV_TAG_SIZE_LEN) {
614            slot.copy_from_slice(&previous_tag_size);
615        }
616        Ok(len)
617    }
618}
619
620/// Offset of `DataSize` inside a tag header (§E.4.1).
621const TAG_DATA_SIZE_AT: usize = 1;
622/// Offset of the UI24 low `Timestamp` inside a tag header (§E.4.1).
623const TAG_TIMESTAMP_AT: usize = 4;
624/// Offset of `TimestampExtended` inside a tag header (§E.4.1).
625const TAG_TIMESTAMP_EXTENDED_AT: usize = 7;
626/// Offset of `StreamID` inside a tag header (§E.4.1).
627const TAG_STREAM_ID_AT: usize = 8;
628/// Byte width of a UI24 field.
629const U24_LEN: usize = 3;
630/// The low 24 bits of a tag's `Timestamp` (§E.4.1), the part the UI24 field
631/// carries.
632const TIMESTAMP_LOW24_MASK: u32 = 0x00FF_FFFF;
633
634/// The three low big-endian bytes of a value that must fit a UI24 field.
635fn ui24(value: u32, field: &'static str) -> FlvResult<[u8; U24_LEN]> {
636    let widened = fit_u24(usize::try_from(value).unwrap_or(usize::MAX), field)?;
637    let bytes = widened.to_be_bytes();
638    let Some(low) = bytes.get(1..) else {
639        return Err(RtmpError::Malformed { what: field });
640    };
641    <[u8; U24_LEN]>::try_from(low).map_err(|_| RtmpError::Malformed { what: field })
642}
643
644// ── Tag walk ────────────────────────────────────────────────────────────
645
646/// The tags of an FLV stream, in order, starting at `header`'s first tag.
647///
648/// Strict: no resynchronisation. Every item is exactly one tag (header, body
649/// and `PreviousTagSize`); a trailing run too short to be a complete tag is
650/// yielded as an error item and ends the walk.
651pub fn tags<'a>(input: &'a [u8], header: &FlvHeader<'a>) -> Tags<'a> {
652    Tags {
653        input,
654        offset: header.first_tag_offset(),
655    }
656}
657
658/// Iterator over an FLV stream's tags — see [`tags`].
659#[derive(Debug, Clone)]
660pub struct Tags<'a> {
661    input: &'a [u8],
662    offset: usize,
663}
664
665impl<'a> Iterator for Tags<'a> {
666    type Item = FlvResult<FlvTag<'a>>;
667
668    fn next(&mut self) -> Option<Self::Item> {
669        let rest = self.input.get(self.offset..)?;
670        if rest.is_empty() {
671            return None;
672        }
673        let tag = match FlvTag::parse(rest) {
674            Ok(tag) => tag,
675            Err(err) => {
676                self.offset = self.input.len();
677                return Some(Err(err));
678            }
679        };
680        self.offset = self.offset.saturating_add(tag.serialized_len());
681        Some(Ok(tag))
682    }
683}
684
685// ── Tolerant walk (resynchronising) ─────────────────────────────────────
686
687/// A tag header at `off` that is structurally plausible: a readable header,
688/// the always-zero 24-bit `StreamID` (§E.4.1) and, when `known_type`, one of
689/// the tag types a media demuxer reads. Unknown types are legal (a walker
690/// skips them leniently), so the chain check along the stream accepts them;
691/// only a *resync candidate*, picked out of arbitrary bytes, is held to a
692/// known type.
693fn plausible_tag_header(input: &[u8], off: usize, known_type: bool) -> bool {
694    off.saturating_add(FLV_TAG_HEADER_LEN) <= input.len()
695        && (!known_type
696            || [
697                MessageTypeId::Audio,
698                MessageTypeId::Video,
699                MessageTypeId::DataAmf0,
700            ]
701            .contains(&MessageTypeId::from_u8(input[off])))
702        && input[off + TAG_STREAM_ID_AT..off + FLV_TAG_HEADER_LEN] == [0, 0, 0]
703}
704
705/// The `DataSize` of the tag whose header starts at `off` (the caller has
706/// checked that the header is readable).
707fn tag_data_size(input: &[u8], off: usize) -> usize {
708    FlvTagHeader::parse(&input[off..])
709        .ok()
710        .and_then(|header| usize::try_from(header.data_size).ok())
711        .unwrap_or_default()
712}
713
714/// Whether the tag starting at `off` is followed by a consistent chain: its
715/// body fits, and what follows it is the end of the buffer or another
716/// plausible tag header.
717fn tag_chain_holds(input: &[u8], off: usize, known_type: bool) -> bool {
718    if !plausible_tag_header(input, off, known_type) {
719        return false;
720    }
721    let Some(body_end) = off
722        .saturating_add(FLV_TAG_HEADER_LEN)
723        .checked_add(tag_data_size(input, off))
724    else {
725        return false;
726    };
727    if body_end > input.len() {
728        return false;
729    }
730    let next = body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN);
731    next.saturating_add(FLV_TAG_HEADER_LEN) > input.len()
732        || plausible_tag_header(input, next, false)
733}
734
735/// First offset at or after `from` where a consistent chain of known-type tags
736/// starts.
737fn resync_tag(input: &[u8], from: usize) -> Option<usize> {
738    (from..input.len()).find(|&at| tag_chain_holds(input, at, true))
739}
740
741/// An FLV stream walked tolerantly: every tag, the damaged spans skipped, and
742/// whether the input ended on a short tail — see [`tags_resync`].
743#[derive(Debug, Clone, PartialEq, Eq)]
744pub struct ResyncWalk<'a> {
745    /// The complete tags, in order, with their offsets.
746    pub tags: Vec<(usize, FlvTag<'a>)>,
747    /// Offsets of the spans whose tag framing was damaged and skipped.
748    pub damaged: 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
754/// Walk an FLV stream's tags tolerantly, from `header`'s first tag.
755///
756/// Unlike the strict [`tags`], a stream whose framing is damaged part-way
757/// still yields the tags after the damage: a span whose tag chain does not hold
758/// is skipped to the next consistent chain of known-type tags and reported in
759/// [`ResyncWalk::damaged`], and a final tag whose body overruns the input stops
760/// the walk (reported in [`ResyncWalk::truncated_tail`]) rather than losing the
761/// good prefix. Two shapes are not truncation: a final tag whose body is
762/// complete but whose 4-byte `PreviousTagSize` is missing (§E.4.1 makes that
763/// field redundant — it repeats the tag's own size) is kept and the walk ends
764/// cleanly, and a header too short to read at the very end of the input is
765/// simply the end of the walk.
766///
767/// # Errors
768/// [`RtmpError::BufferTooShort`] when `input` is shorter than the header and
769/// its `PreviousTagSize0`, and when the *first* tag is already incomplete (that
770/// is not a recoverable tail: there is nothing complete to return).
771pub fn tags_resync<'a>(input: &'a [u8], header: &FlvHeader<'a>) -> FlvResult<ResyncWalk<'a>> {
772    need_in(
773        input,
774        FLV_HEADER_LEN.saturating_add(FLV_PREV_TAG_SIZE_LEN),
775        "FLV header",
776    )?;
777    let mut off = header.first_tag_offset();
778    let mut walk = ResyncWalk {
779        tags: Vec::new(),
780        damaged: Vec::new(),
781        truncated_tail: None,
782    };
783    while off.saturating_add(FLV_TAG_HEADER_LEN) <= input.len() {
784        if !tag_chain_holds(input, off, false)
785            && let Some(next) = resync_tag(input, off + 1)
786        {
787            walk.damaged.push(off);
788            off = next;
789            continue;
790        }
791        let Some(body_end) = off
792            .saturating_add(FLV_TAG_HEADER_LEN)
793            .checked_add(tag_data_size(input, off))
794        else {
795            return Err(RtmpError::Malformed {
796                what: "FLV tag DataSize",
797            });
798        };
799        if body_end > input.len() {
800            let need = body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN);
801            if walk.tags.is_empty() && walk.damaged.is_empty() {
802                return Err(RtmpError::BufferTooShort(
803                    broadcast_common::error::BufferTooShort {
804                        need,
805                        have: input.len(),
806                        what: "FLV tag body",
807                    },
808                ));
809            }
810            walk.truncated_tail = Some((off, need, input.len().saturating_sub(off)));
811            return Ok(walk);
812        }
813        let codec_end = body_end
814            .saturating_add(FLV_PREV_TAG_SIZE_LEN)
815            .min(input.len());
816        let tag = FlvTag::parse(input.get(off..codec_end).unwrap_or_default())?;
817        walk.tags.push((off, tag));
818        if body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN) > input.len() {
819            return Ok(walk);
820        }
821        off = body_end.saturating_add(FLV_PREV_TAG_SIZE_LEN);
822    }
823    Ok(walk)
824}
825
826// ── Session writer ──────────────────────────────────────────────────────
827
828/// Builds the FLV byte stream of one RTMP session: the first tag is prefixed
829/// with the file header ([`FlvHeader`] + `PreviousTagSize0`), every tag carries
830/// its own header and `PreviousTagSize`, so concatenating every returned chunk
831/// in order yields a valid FLV stream.
832#[derive(Debug, Default)]
833pub(crate) struct FlvTagWriter {
834    header_sent: bool,
835}
836
837impl FlvTagWriter {
838    /// One FLV tag for a media or script message body (file header first time).
839    ///
840    /// # Errors
841    /// [`RtmpError::FieldOverflow`] if `payload` does not fit the tag's 24-bit
842    /// `DataSize`, or the session's FLV bytes cannot be built.
843    pub(crate) fn tag(
844        &mut self,
845        tag_type: MessageTypeId,
846        timestamp: u32,
847        payload: &[u8],
848    ) -> FlvResult<Vec<u8>> {
849        let payload = if tag_type == MessageTypeId::DataAmf0 {
850            strip_set_data_frame(payload)
851        } else {
852            payload
853        };
854        let mut flv = if self.header_sent {
855            Vec::new()
856        } else {
857            self.header_sent = true;
858            FlvHeader::new(true, true).try_to_bytes()?
859        };
860        let tag = FlvTag::new(TagType::from_byte(tag_type.to_u8()), timestamp, payload);
861        flv.extend_from_slice(&tag.try_to_bytes()?);
862        Ok(flv)
863    }
864}
865
866/// The AMF0 handler name a publisher puts in front of `onMetaData` (the FMLE
867/// `@setDataFrame` convention); it addresses the server, not the FLV script tag.
868const SET_DATA_FRAME: &str = "@setDataFrame";
869
870/// `payload` without a leading AMF0 `@setDataFrame` string, so the FLV script tag
871/// begins with `onMetaData` as Adobe FLV v10.1 Annex E.4.1 defines it.
872fn strip_set_data_frame(payload: &[u8]) -> &[u8] {
873    let Ok(name) = crate::amf0::Amf0Value::String(SET_DATA_FRAME.to_string()).try_to_bytes() else {
874        return payload;
875    };
876    payload.strip_prefix(name.as_slice()).unwrap_or(payload)
877}