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