Skip to main content

rtmp_runtime/flv/
tag_body.rs

1//! FLV tag-body syntax — Adobe Flash Video File Format Specification v10.1
2//! Annex E §E.4.2 (`AudioTagHeader` + `AACAUDIODATA`) and §E.4.3
3//! (`VideoTagHeader` + `AVCVIDEOPACKET`) — and the script-data tag's
4//! `onMetaData` body (§E.4.1).
5//!
6//! The tag *framing* (file header, tag header, `PreviousTagSize`) is
7//! [`crate::flv`]'s; this module is what that framing wraps. An RTMP
8//! Audio(8)/Video(9) message body is exactly one of these tag bodies (Adobe
9//! RTMP 1.0 §7.1.4, §7.1.5), so the publisher and the demuxer share one
10//! definition rather than each spelling the bit layout.
11//!
12//! See `private/specs-verified/mpeg/transmux/codec/flv.md` §E.4.1–§E.4.3.
13
14use alloc::borrow::ToOwned;
15use alloc::string::{String, ToString};
16use alloc::vec::Vec;
17
18use broadcast_core::error::BufferTooShort;
19use broadcast_core::len::fit_mask;
20use broadcast_core::wire::{Reader, Writer};
21use broadcast_core::{Parse, Serialize};
22
23use crate::RtmpError;
24use crate::amf0::{Amf0Limits, Amf0Value, amf0_parse_values_with};
25use crate::flv::PublishTrack;
26
27type BodyResult<T> = core::result::Result<T, RtmpError>;
28
29// ── Shared body constants (§E.4.2, §E.4.3) ──────────────────────────────
30
31/// `FrameType` shift in the first `VideoTagHeader` byte (§E.4.3).
32const FRAME_TYPE_SHIFT: u32 = 4;
33/// `FrameType` mask in the first `VideoTagHeader` byte (§E.4.3).
34const FRAME_TYPE_MASK: u8 = 0x0F;
35/// `CodecID` mask in the first `VideoTagHeader` byte (§E.4.3).
36const CODEC_ID_MASK: u8 = 0x0F;
37/// `SoundFormat` mask in the first `AudioTagHeader` byte (§E.4.2).
38const SOUND_FORMAT_MASK: u8 = 0x0F;
39/// `SoundFormat` shift in the first `AudioTagHeader` byte (§E.4.2).
40const SOUND_FORMAT_SHIFT: u32 = 4;
41/// `SoundRate` shift in the first `AudioTagHeader` byte (§E.4.2).
42const SOUND_RATE_SHIFT: u32 = 2;
43/// `SoundSize` shift in the first `AudioTagHeader` byte (§E.4.2).
44const SOUND_SIZE_SHIFT: u32 = 1;
45/// `SoundType` mask in the first `AudioTagHeader` byte (§E.4.2).
46const SOUND_TYPE_MASK: u8 = 0x01;
47/// `SoundType` narrowing mask before the shift (the field is one bit).
48const SOUND_FIELD_MASK: u8 = 0x03;
49
50/// Byte width of the `VideoTagHeader` (§E.4.3): `FrameType` + `CodecID`.
51pub const VIDEO_TAG_HEADER_LEN: usize = 1;
52/// Byte offset of `AVCPacketType` in an `AVCVIDEOPACKET` (§E.4.3.2).
53const AVC_PACKET_TYPE_AT: usize = 1;
54/// Byte width of `AVCPacketType` (§E.4.3.2).
55const AVC_PACKET_TYPE_LEN: usize = 1;
56/// Byte offset of `CompositionTime` in an `AVCVIDEOPACKET` (§E.4.3.2).
57const COMPOSITION_TIME_AT: usize = AVC_PACKET_TYPE_AT + AVC_PACKET_TYPE_LEN;
58/// `CompositionTime` is a signed 24-bit field (§E.4.3.2).
59const COMPOSITION_TIME_LEN: usize = 3;
60/// Byte offset of the coded data after the `AVCVIDEOPACKET` header (§E.4.3.2).
61pub const AVC_PACKET_DATA_OFFSET: usize = COMPOSITION_TIME_AT + COMPOSITION_TIME_LEN;
62/// Smallest `CompositionTime` representable as the signed 24-bit `SI24`
63/// field (§E.4.3.2).
64pub const COMPOSITION_TIME_MIN: i32 = -(1 << 23);
65/// Largest `CompositionTime` representable as the signed 24-bit `SI24`
66/// field (§E.4.3.2).
67pub const COMPOSITION_TIME_MAX: i32 = (1 << 23) - 1;
68
69/// Byte width of the `AudioTagHeader` (§E.4.2): `SoundFormat` + `SoundRate`
70/// + `SoundSize` + `SoundType`.
71pub const AUDIO_TAG_HEADER_LEN: usize = 1;
72/// Byte offset of `AACPacketType` in an `AACAUDIODATA` (§E.4.2.2).
73const AAC_PACKET_TYPE_AT: usize = AUDIO_TAG_HEADER_LEN;
74/// Byte offset of the raw AAC access unit (§E.4.2.2).
75pub const AAC_PACKET_DATA_OFFSET: usize = AAC_PACKET_TYPE_AT + 1;
76
77// ── VideoTagHeader (§E.4.3) ─────────────────────────────────────────────
78
79/// FLV video `FrameType` (§E.4.3, Table E.4).
80#[non_exhaustive]
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
82#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
83pub enum FrameType {
84    /// 1: a keyframe (for AVC, a seekable frame).
85    Keyframe,
86    /// 2: an inter frame (for AVC, a non-seekable frame).
87    Inter,
88    /// 3: a disposable inter frame (H.263 only).
89    DisposableInter,
90    /// 4: a generated keyframe (reserved for server use only).
91    GeneratedKeyframe,
92    /// 5: video info / command frame.
93    VideoInfo,
94    /// 6, 7: reserved by the specification.
95    Reserved(u8),
96    /// 0, 8–15: outside the table, carried as written.
97    Unknown(u8),
98}
99
100impl FrameType {
101    /// The code this frame type carries in the `VideoTagHeader` nibble.
102    pub fn to_code(self) -> u8 {
103        match self {
104            Self::Keyframe => 1,
105            Self::Inter => 2,
106            Self::DisposableInter => 3,
107            Self::GeneratedKeyframe => 4,
108            Self::VideoInfo => 5,
109            Self::Reserved(code) | Self::Unknown(code) => code,
110        }
111    }
112
113    /// The frame type a wire nibble names.
114    pub fn from_code(code: u8) -> Self {
115        match code {
116            1 => Self::Keyframe,
117            2 => Self::Inter,
118            3 => Self::DisposableInter,
119            4 => Self::GeneratedKeyframe,
120            5 => Self::VideoInfo,
121            6 | 7 => Self::Reserved(code),
122            other => Self::Unknown(other),
123        }
124    }
125
126    /// Whether this frame type is a keyframe (a seekable one) and so marks its
127    /// sample as a sync point.
128    #[must_use]
129    pub fn is_keyframe(self) -> bool {
130        matches!(self, Self::Keyframe | Self::GeneratedKeyframe)
131    }
132
133    /// The specification token for the tabled values (Table E.4).
134    pub fn name(&self) -> &'static str {
135        match self {
136            Self::Keyframe => "keyframe",
137            Self::Inter => "inter frame",
138            Self::DisposableInter => "disposable inter frame",
139            Self::GeneratedKeyframe => "generated keyframe",
140            Self::VideoInfo => "video info/command frame",
141            Self::Reserved(_) => "reserved",
142            Self::Unknown(_) => "unknown",
143        }
144    }
145}
146
147broadcast_core::impl_spec_display!(FrameType, Reserved, Unknown);
148
149/// FLV video `CodecID` (§E.4.3, Table E.5).
150#[non_exhaustive]
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
152#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
153pub enum CodecId {
154    /// 2: Sorenson H.263.
155    SorensonH263,
156    /// 3: Screen video.
157    ScreenVideo,
158    /// 4: On2 VP6.
159    On2Vp6,
160    /// 5: On2 VP6 with alpha channel.
161    On2Vp6Alpha,
162    /// 6: Screen video version 2.
163    ScreenVideoV2,
164    /// 7: AVC (H.264), carried as `AVCVIDEOPACKET` (§E.4.3.2).
165    Avc,
166    /// 12: HEVC (H.265), carried as `HEVCVIDEOPACKET`.
167    Hevc,
168    /// 0, 1, 8, 9 and 13–15: reserved by the specification.
169    Reserved(u8),
170    /// 10, 11: outside the table, carried as written.
171    Unknown(u8),
172}
173
174impl CodecId {
175    /// The code this codec id carries in the `VideoTagHeader` nibble.
176    pub fn to_code(self) -> u8 {
177        match self {
178            Self::SorensonH263 => 2,
179            Self::ScreenVideo => 3,
180            Self::On2Vp6 => 4,
181            Self::On2Vp6Alpha => 5,
182            Self::ScreenVideoV2 => 6,
183            Self::Avc => 7,
184            Self::Hevc => 12,
185            Self::Reserved(code) | Self::Unknown(code) => code,
186        }
187    }
188
189    /// The codec id a wire nibble names.
190    pub fn from_code(code: u8) -> Self {
191        match code {
192            2 => Self::SorensonH263,
193            3 => Self::ScreenVideo,
194            4 => Self::On2Vp6,
195            5 => Self::On2Vp6Alpha,
196            6 => Self::ScreenVideoV2,
197            7 => Self::Avc,
198            12 => Self::Hevc,
199            10 | 11 => Self::Unknown(code),
200            other => Self::Reserved(other),
201        }
202    }
203
204    /// The specification token for the tabled values (Table E.5).
205    pub fn name(&self) -> &'static str {
206        match self {
207            Self::SorensonH263 => "Sorenson H.263",
208            Self::ScreenVideo => "Screen video",
209            Self::On2Vp6 => "On2 VP6",
210            Self::On2Vp6Alpha => "On2 VP6 with alpha channel",
211            Self::ScreenVideoV2 => "Screen video version 2",
212            Self::Avc => "AVC",
213            Self::Hevc => "HEVC",
214            Self::Reserved(_) => "reserved",
215            Self::Unknown(_) => "unknown",
216        }
217    }
218}
219
220broadcast_core::impl_spec_display!(CodecId, Reserved, Unknown);
221
222/// `AVCPacketType` of an AVC `AVCVIDEOPACKET` (§E.4.3.2).
223#[non_exhaustive]
224#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
225#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
226pub enum AvcPacketType {
227    /// 0: AVC sequence header — the `AVCDecoderConfigurationRecord` (`avcC`).
228    SequenceHeader,
229    /// 1: AVC NALU — one or more length-prefixed NAL units.
230    Nalu,
231    /// 2: AVC end of sequence (the body carries no data).
232    EndOfSequence,
233    /// 3 or above: outside the table, carried as written.
234    Unknown(u8),
235}
236
237impl AvcPacketType {
238    /// The code this packet type carries on the wire.
239    pub fn to_code(self) -> u8 {
240        match self {
241            Self::SequenceHeader => 0,
242            Self::Nalu => 1,
243            Self::EndOfSequence => 2,
244            Self::Unknown(code) => code,
245        }
246    }
247
248    /// The packet type a wire byte names.
249    pub fn from_code(code: u8) -> Self {
250        match code {
251            0 => Self::SequenceHeader,
252            1 => Self::Nalu,
253            2 => Self::EndOfSequence,
254            other => Self::Unknown(other),
255        }
256    }
257
258    /// The specification token for the tabled values (§E.4.3.2).
259    pub fn name(&self) -> &'static str {
260        match self {
261            Self::SequenceHeader => "sequence header",
262            Self::Nalu => "NALU",
263            Self::EndOfSequence => "end of sequence",
264            Self::Unknown(_) => "unknown",
265        }
266    }
267}
268
269broadcast_core::impl_spec_display!(AvcPacketType, Unknown);
270
271/// The `VideoTagHeader` (§E.4.3) and, for the codecs that carry one, the
272/// packet header of its `VIDEODATA` body.
273///
274/// `AVCVIDEOPACKET` (§E.4.3.2) is the only packet layout this crate decodes;
275/// any other `CodecID` keeps all the bytes after the first byte as
276/// [`data`](Self::data), because no packet header of that codec is modelled
277/// here.
278#[non_exhaustive]
279#[derive(Clone, Copy, PartialEq, Eq)]
280#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
281pub struct VideoTagHeader<'a> {
282    /// `FrameType` (§E.4.3).
283    pub frame_type: FrameType,
284    /// `CodecID` (§E.4.3).
285    pub codec_id: CodecId,
286    /// `AVCPacketType`: set only for [`CodecId::Avc`] (§E.4.3.2).
287    pub avc_packet_type: Option<AvcPacketType>,
288    /// `CompositionTime`, in milliseconds: set only for [`CodecId::Avc`]
289    /// (§E.4.3.2). `PTS = DTS + CompositionTime`.
290    pub composition_time: Option<i32>,
291    /// The coded bytes after the packet header.
292    pub data: &'a [u8],
293}
294
295impl<'a> VideoTagHeader<'a> {
296    /// The header a publisher sent with no coded data.
297    pub fn new(
298        frame_type: FrameType,
299        codec_id: CodecId,
300        avc_packet_type: Option<AvcPacketType>,
301        composition_time: Option<i32>,
302    ) -> Self {
303        Self {
304            frame_type,
305            codec_id,
306            avc_packet_type,
307            composition_time,
308            data: &[],
309        }
310    }
311
312    /// Whether a `CompositionTime` was stated for a codec that carries none
313    /// (a `VideoTagHeader` from [`Self::parse`] never does).
314    #[must_use]
315    pub fn has_stray_composition_time(&self) -> bool {
316        self.codec_id != CodecId::Avc && self.composition_time.is_some()
317    }
318
319    /// The packet type the wire carries: the stated `AVCPacketType` for an AVC
320    /// body, and none for any other codec.
321    fn avc_packet_type(&self) -> Option<AvcPacketType> {
322        (self.codec_id == CodecId::Avc)
323            .then_some(self.avc_packet_type)
324            .flatten()
325    }
326
327    /// The `CompositionTime` the wire carries: the stated value for an AVC
328    /// body, zero otherwise.
329    fn composition_time(&self) -> i32 {
330        if self.avc_packet_type().is_some() {
331            self.composition_time.unwrap_or(0)
332        } else {
333            0
334        }
335    }
336
337    /// The header's own bytes plus `data`, the whole `VIDEODATA` body.
338    ///
339    /// # Errors
340    /// [`RtmpError::FieldOverflow`] when a `CompositionTime` does not fit the
341    /// signed 24-bit field, and [`RtmpError::Malformed`] when one is stated for
342    /// a codec that carries none.
343    pub fn to_bytes(&self) -> BodyResult<Vec<u8>> {
344        let len = self.serialized_len();
345        let mut out = alloc::vec![0u8; len];
346        let written = self.serialize_into(&mut out)?;
347        debug_assert_eq!(written, len);
348        Ok(out)
349    }
350}
351
352impl<'a> Parse<'a> for VideoTagHeader<'a> {
353    type Error = RtmpError;
354
355    fn parse(bytes: &'a [u8]) -> BodyResult<Self> {
356        let first = *bytes
357            .first()
358            .ok_or(RtmpError::BufferTooShort(BufferTooShort::new(
359                VIDEO_TAG_HEADER_LEN,
360                bytes.len(),
361                "FLV VideoTagHeader",
362            )))?;
363        let frame_type = FrameType::from_code(first >> FRAME_TYPE_SHIFT);
364        let codec_id = CodecId::from_code(first & CODEC_ID_MASK);
365        if codec_id != CodecId::Avc {
366            return Ok(Self {
367                frame_type,
368                codec_id,
369                avc_packet_type: None,
370                composition_time: None,
371                data: &bytes[VIDEO_TAG_HEADER_LEN..],
372            });
373        }
374        if bytes.len() < AVC_PACKET_DATA_OFFSET {
375            return Err(RtmpError::BufferTooShort(BufferTooShort::new(
376                AVC_PACKET_DATA_OFFSET,
377                bytes.len(),
378                "FLV AVCVIDEOPACKET",
379            )));
380        }
381        Ok(Self {
382            frame_type,
383            codec_id,
384            avc_packet_type: Some(AvcPacketType::from_code(bytes[AVC_PACKET_TYPE_AT])),
385            composition_time: Some(
386                Reader::at(bytes, COMPOSITION_TIME_AT).i24("FLV AVCVIDEOPACKET")?,
387            ),
388            data: &bytes[AVC_PACKET_DATA_OFFSET..],
389        })
390    }
391}
392
393impl Serialize for VideoTagHeader<'_> {
394    type Error = RtmpError;
395
396    fn serialized_len(&self) -> usize {
397        let mut len = VIDEO_TAG_HEADER_LEN;
398        if self.codec_id == CodecId::Avc && self.avc_packet_type.is_some() {
399            len += AVC_PACKET_DATA_OFFSET - VIDEO_TAG_HEADER_LEN;
400        }
401        len + self.data.len()
402    }
403
404    fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
405        if self.has_stray_composition_time() {
406            return Err(RtmpError::Malformed {
407                what: "FLV CompositionTime for a codec without AVCVIDEOPACKET",
408            });
409        }
410        let len = self.serialized_len();
411        if buf.len() < len {
412            return Err(RtmpError::OutputBufferTooSmall(
413                broadcast_core::error::OutputBufferTooSmall::new(len, buf.len(), "VideoTagHeader"),
414            ));
415        }
416        let mut w = Writer::new(buf);
417        let frame_type = fit_mask(self.frame_type.to_code(), FRAME_TYPE_MASK, "FrameType")?;
418        let codec_id = fit_mask(self.codec_id.to_code(), CODEC_ID_MASK, "CodecID")?;
419        w.u8(
420            (frame_type << FRAME_TYPE_SHIFT) | codec_id,
421            "FLV video tag frame type",
422        )?;
423        if let Some(packet_type) = self.avc_packet_type() {
424            w.u8(packet_type.to_code(), "FLV video tag packet type")?;
425            w.i24::<RtmpError>(self.composition_time(), "FLV CompositionTime")?;
426        }
427        w.bytes(self.data, "FLV video tag data")?;
428        Ok(len)
429    }
430}
431
432impl core::fmt::Debug for VideoTagHeader<'_> {
433    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
434        f.debug_struct("VideoTagHeader")
435            .field("frame_type", &self.frame_type)
436            .field("codec_id", &self.codec_id)
437            .field("avc_packet_type", &self.avc_packet_type)
438            .field("composition_time", &self.composition_time)
439            .field("data_len", &self.data.len())
440            .finish()
441    }
442}
443
444// ── AudioTagHeader (§E.4.2) ─────────────────────────────────────────────
445
446/// `SoundFormat` of an `AudioTagHeader` (§E.4.2, Table E.6).
447#[non_exhaustive]
448#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
449#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
450pub enum SoundFormat {
451    /// 0: linear PCM, platform endian.
452    LinearPcmPlatformEndian,
453    /// 1: ADPCM.
454    Adpcm,
455    /// 2: MP3.
456    Mp3,
457    /// 3: linear PCM, little endian.
458    LinearPcmLittleEndian,
459    /// 4: Nellymoser 16 kHz mono.
460    Nellymoser16KhzMono,
461    /// 5: Nellymoser 8 kHz mono.
462    Nellymoser8KhzMono,
463    /// 6: Nellymoser.
464    Nellymoser,
465    /// 7: G.711 A-law logarithmic PCM.
466    G711ALaw,
467    /// 8: G.711 mu-law logarithmic PCM.
468    G711MuLaw,
469    /// 10: AAC, carried as `AACAUDIODATA` (§E.4.2.2).
470    Aac,
471    /// 11: Speex.
472    Speex,
473    /// 14: MP3 8 kHz.
474    Mp3_8Khz,
475    /// 15: device-specific sound.
476    DeviceSpecific,
477    /// 9: reserved by the specification.
478    Reserved(u8),
479    /// 12, 13: outside the table, carried as written.
480    Unknown(u8),
481}
482
483impl SoundFormat {
484    /// The code this sound format carries in the `AudioTagHeader` nibble.
485    pub fn to_code(self) -> u8 {
486        match self {
487            Self::LinearPcmPlatformEndian => 0,
488            Self::Adpcm => 1,
489            Self::Mp3 => 2,
490            Self::LinearPcmLittleEndian => 3,
491            Self::Nellymoser16KhzMono => 4,
492            Self::Nellymoser8KhzMono => 5,
493            Self::Nellymoser => 6,
494            Self::G711ALaw => 7,
495            Self::G711MuLaw => 8,
496            Self::Aac => 10,
497            Self::Speex => 11,
498            Self::Mp3_8Khz => 14,
499            Self::DeviceSpecific => 15,
500            Self::Reserved(code) | Self::Unknown(code) => code,
501        }
502    }
503
504    /// The sound format a wire nibble names.
505    pub fn from_code(code: u8) -> Self {
506        match code {
507            0 => Self::LinearPcmPlatformEndian,
508            1 => Self::Adpcm,
509            2 => Self::Mp3,
510            3 => Self::LinearPcmLittleEndian,
511            4 => Self::Nellymoser16KhzMono,
512            5 => Self::Nellymoser8KhzMono,
513            6 => Self::Nellymoser,
514            7 => Self::G711ALaw,
515            8 => Self::G711MuLaw,
516            10 => Self::Aac,
517            11 => Self::Speex,
518            14 => Self::Mp3_8Khz,
519            15 => Self::DeviceSpecific,
520            12 | 13 => Self::Unknown(code),
521            other => Self::Reserved(other),
522        }
523    }
524
525    /// The specification token for the tabled values (Table E.6).
526    pub fn name(&self) -> &'static str {
527        match self {
528            Self::LinearPcmPlatformEndian => "linear PCM, platform endian",
529            Self::Adpcm => "ADPCM",
530            Self::Mp3 => "MP3",
531            Self::LinearPcmLittleEndian => "linear PCM, little endian",
532            Self::Nellymoser16KhzMono => "Nellymoser 16 kHz mono",
533            Self::Nellymoser8KhzMono => "Nellymoser 8 kHz mono",
534            Self::Nellymoser => "Nellymoser",
535            Self::G711ALaw => "G.711 A-law",
536            Self::G711MuLaw => "G.711 mu-law",
537            Self::Aac => "AAC",
538            Self::Speex => "Speex",
539            Self::Mp3_8Khz => "MP3 8 kHz",
540            Self::DeviceSpecific => "device-specific sound",
541            Self::Reserved(_) => "reserved",
542            Self::Unknown(_) => "unknown",
543        }
544    }
545}
546
547broadcast_core::impl_spec_display!(SoundFormat, Reserved, Unknown);
548
549/// `SoundRate` of an `AudioTagHeader` (§E.4.2, Table E.7).
550#[non_exhaustive]
551#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
552#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
553pub enum SoundRate {
554    /// 0: 5.5 kHz.
555    Khz5_5_5,
556    /// 1: 11 kHz.
557    Khz11,
558    /// 2: 22 kHz.
559    Khz22,
560    /// 3: 44 kHz (FLV carries no higher rate here; for AAC it is always 3 and
561    /// the real rate lives in the `AudioSpecificConfig`).
562    Khz44,
563}
564
565impl SoundRate {
566    /// The code this rate carries on the wire.
567    pub fn to_code(self) -> u8 {
568        match self {
569            Self::Khz5_5_5 => 0,
570            Self::Khz11 => 1,
571            Self::Khz22 => 2,
572            Self::Khz44 => 3,
573        }
574    }
575
576    /// The rate a wire code names.
577    pub fn from_code(code: u8) -> Self {
578        match code & SOUND_FIELD_MASK {
579            0 => Self::Khz5_5_5,
580            1 => Self::Khz11,
581            2 => Self::Khz22,
582            _ => Self::Khz44,
583        }
584    }
585
586    /// The specification token for this rate (Table E.7).
587    pub fn name(&self) -> &'static str {
588        match self {
589            Self::Khz5_5_5 => "5.5 kHz",
590            Self::Khz11 => "11 kHz",
591            Self::Khz22 => "22 kHz",
592            Self::Khz44 => "44 kHz",
593        }
594    }
595}
596
597broadcast_core::impl_spec_display!(SoundRate);
598
599/// `SoundSize` of an `AudioTagHeader` (§E.4.2, Table E.8).
600#[non_exhaustive]
601#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
602#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
603pub enum SoundSize {
604    /// 0: 8-bit samples.
605    Bits8,
606    /// 1: 16-bit samples.
607    Bits16,
608}
609
610impl SoundSize {
611    /// The code this size carries on the wire.
612    pub fn to_code(self) -> u8 {
613        match self {
614            Self::Bits8 => 0,
615            Self::Bits16 => 1,
616        }
617    }
618
619    /// The size a wire bit names.
620    pub fn from_code(code: u8) -> Self {
621        if code & SOUND_TYPE_MASK == 0 {
622            Self::Bits8
623        } else {
624            Self::Bits16
625        }
626    }
627
628    /// The sample size in bits.
629    pub fn bits(self) -> u8 {
630        match self {
631            Self::Bits8 => 8,
632            Self::Bits16 => 16,
633        }
634    }
635
636    /// The specification token for this size (Table E.8).
637    pub fn name(&self) -> &'static str {
638        match self {
639            Self::Bits8 => "8-bit",
640            Self::Bits16 => "16-bit",
641        }
642    }
643}
644
645broadcast_core::impl_spec_display!(SoundSize);
646
647/// `SoundType` of an `AudioTagHeader` (§E.4.2, Table E.9).
648#[non_exhaustive]
649#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
650#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
651pub enum SoundType {
652    /// 0: mono.
653    Mono,
654    /// 1: stereo.
655    Stereo,
656}
657
658impl SoundType {
659    /// The code this sound type carries on the wire.
660    pub fn to_code(self) -> u8 {
661        match self {
662            Self::Mono => 0,
663            Self::Stereo => 1,
664        }
665    }
666
667    /// The sound type a wire bit names.
668    pub fn from_code(code: u8) -> Self {
669        if code & SOUND_TYPE_MASK == 0 {
670            Self::Mono
671        } else {
672            Self::Stereo
673        }
674    }
675
676    /// The specification token for this sound type (Table E.9).
677    pub fn name(&self) -> &'static str {
678        match self {
679            Self::Mono => "mono",
680            Self::Stereo => "stereo",
681        }
682    }
683}
684
685broadcast_core::impl_spec_display!(SoundType);
686
687/// `AACPacketType` of an AAC `AACAUDIODATA` (§E.4.2.2).
688#[non_exhaustive]
689#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
690#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
691pub enum AacPacketType {
692    /// 0: AAC sequence header — the `AudioSpecificConfig`.
693    SequenceHeader,
694    /// 1: AAC raw — one raw AAC access unit.
695    Raw,
696    /// 2 or above: outside the table, carried as written.
697    Unknown(u8),
698}
699
700impl AacPacketType {
701    /// The code this packet type carries on the wire.
702    pub fn to_code(self) -> u8 {
703        match self {
704            Self::SequenceHeader => 0,
705            Self::Raw => 1,
706            Self::Unknown(code) => code,
707        }
708    }
709
710    /// The packet type a wire byte names.
711    pub fn from_code(code: u8) -> Self {
712        match code {
713            0 => Self::SequenceHeader,
714            1 => Self::Raw,
715            other => Self::Unknown(other),
716        }
717    }
718
719    /// The specification token for the tabled values (§E.4.2.2).
720    pub fn name(&self) -> &'static str {
721        match self {
722            Self::SequenceHeader => "sequence header",
723            Self::Raw => "raw",
724            Self::Unknown(_) => "unknown",
725        }
726    }
727}
728
729broadcast_core::impl_spec_display!(AacPacketType, Unknown);
730
731/// The `AudioTagHeader` (§E.4.2) and, for AAC, the packet header of its
732/// `AACAUDIODATA` body (§E.4.2.2).
733///
734/// `AACAUDIODATA` is the only audio packet layout this crate decodes; any
735/// other `SoundFormat` keeps all the bytes after the first byte as
736/// [`data`](Self::data), because no packet header of that codec is modelled
737/// here.
738#[non_exhaustive]
739#[derive(Clone, Copy, PartialEq, Eq)]
740#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
741pub struct AudioTagHeader<'a> {
742    /// `SoundFormat` (§E.4.2).
743    pub sound_format: SoundFormat,
744    /// `SoundRate` (§E.4.2).
745    pub sound_rate: SoundRate,
746    /// `SoundSize` (§E.4.2).
747    pub sound_size: SoundSize,
748    /// `SoundType` (§E.4.2).
749    pub sound_type: SoundType,
750    /// `AACPacketType`: set only for [`SoundFormat::Aac`] (§E.4.2.2).
751    pub aac_packet_type: Option<AacPacketType>,
752    /// The coded bytes after the packet header.
753    pub data: &'a [u8],
754}
755
756impl<'a> AudioTagHeader<'a> {
757    /// A header with no packet header and no coded data.
758    pub fn new(
759        sound_format: SoundFormat,
760        sound_rate: SoundRate,
761        sound_size: SoundSize,
762        sound_type: SoundType,
763        aac_packet_type: Option<AacPacketType>,
764    ) -> Self {
765        Self {
766            sound_format,
767            sound_rate,
768            sound_size,
769            sound_type,
770            aac_packet_type,
771            data: &[],
772        }
773    }
774
775    /// The `SoundType` an audio `channel_count` states: one channel or fewer
776    /// is mono, anything above is stereo (§E.5's `stereo` rule).
777    #[must_use]
778    pub fn sound_type_for_channels(channel_count: u16) -> SoundType {
779        const MONO_CHANNELS: u16 = 1;
780        if channel_count <= MONO_CHANNELS {
781            SoundType::Mono
782        } else {
783            SoundType::Stereo
784        }
785    }
786
787    /// The packet type the wire carries: the stated `AACPacketType` for AAC,
788    /// and none for any other format.
789    fn aac_packet_type(&self) -> Option<AacPacketType> {
790        if self.sound_format == SoundFormat::Aac {
791            self.aac_packet_type
792        } else {
793            None
794        }
795    }
796
797    /// The header's own bytes plus `data`, the whole `AUDIODATA` body.
798    ///
799    /// # Errors
800    /// [`RtmpError::Malformed`] when an `AACPacketType` is stated for a
801    /// `SoundFormat` that carries none.
802    pub fn to_bytes(&self) -> BodyResult<Vec<u8>> {
803        if self.sound_format != SoundFormat::Aac && self.aac_packet_type.is_some() {
804            return Err(RtmpError::Malformed {
805                what: "FLV AACPacketType for a non-AAC SoundFormat",
806            });
807        }
808        let len = self.serialized_len();
809        let mut out = alloc::vec![0u8; len];
810        let written = self.serialize_into(&mut out)?;
811        debug_assert_eq!(written, len);
812        Ok(out)
813    }
814
815    /// The `AudioTagHeader` first byte these sound fields make up (§E.4.2).
816    ///
817    /// # Errors
818    /// [`RtmpError::FieldOverflow`] when a field's code does not fit its bits
819    /// (a reserved or unknown code carries any byte).
820    pub fn first_byte(&self) -> BodyResult<u8> {
821        let format = fit_mask(
822            self.sound_format.to_code(),
823            SOUND_FORMAT_MASK,
824            "SoundFormat",
825        )?;
826        let rate = fit_mask(self.sound_rate.to_code(), SOUND_FIELD_MASK, "SoundRate")?;
827        let size = fit_mask(self.sound_size.to_code(), SOUND_TYPE_MASK, "SoundSize")?;
828        let kind = fit_mask(self.sound_type.to_code(), SOUND_TYPE_MASK, "SoundType")?;
829        Ok((format << SOUND_FORMAT_SHIFT)
830            | (rate << SOUND_RATE_SHIFT)
831            | (size << SOUND_SIZE_SHIFT)
832            | kind)
833    }
834}
835
836impl<'a> Parse<'a> for AudioTagHeader<'a> {
837    type Error = RtmpError;
838
839    fn parse(bytes: &'a [u8]) -> BodyResult<Self> {
840        let first = *bytes
841            .first()
842            .ok_or(RtmpError::BufferTooShort(BufferTooShort::new(
843                AUDIO_TAG_HEADER_LEN,
844                bytes.len(),
845                "FLV AudioTagHeader",
846            )))?;
847        let sound_format = SoundFormat::from_code(first >> SOUND_FORMAT_SHIFT);
848        let prefix = Self {
849            sound_format,
850            sound_rate: SoundRate::from_code(first >> SOUND_RATE_SHIFT),
851            sound_size: SoundSize::from_code(first >> SOUND_SIZE_SHIFT),
852            sound_type: SoundType::from_code(first),
853            aac_packet_type: None,
854            data: &[],
855        };
856        if sound_format != SoundFormat::Aac {
857            return Ok(Self {
858                data: &bytes[AUDIO_TAG_HEADER_LEN..],
859                ..prefix
860            });
861        }
862        let packet_type = *bytes
863            .get(AAC_PACKET_TYPE_AT)
864            .ok_or(RtmpError::BufferTooShort(BufferTooShort::new(
865                AAC_PACKET_DATA_OFFSET,
866                bytes.len(),
867                "FLV AACAUDIODATA",
868            )))?;
869        Ok(Self {
870            aac_packet_type: Some(AacPacketType::from_code(packet_type)),
871            data: &bytes[AAC_PACKET_DATA_OFFSET..],
872            ..prefix
873        })
874    }
875}
876
877impl Serialize for AudioTagHeader<'_> {
878    type Error = RtmpError;
879
880    fn serialized_len(&self) -> usize {
881        let mut len = AUDIO_TAG_HEADER_LEN;
882        if self.aac_packet_type().is_some() {
883            len += AAC_PACKET_DATA_OFFSET - AUDIO_TAG_HEADER_LEN;
884        }
885        len + self.data.len()
886    }
887
888    fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
889        let len = self.serialized_len();
890        if buf.len() < len {
891            return Err(RtmpError::OutputBufferTooSmall(
892                broadcast_core::error::OutputBufferTooSmall::new(len, buf.len(), "AudioTagHeader"),
893            ));
894        }
895        buf[0] = self.first_byte()?;
896        let mut offset = AUDIO_TAG_HEADER_LEN;
897        if let Some(packet_type) = self.aac_packet_type() {
898            buf[AAC_PACKET_TYPE_AT] = packet_type.to_code();
899            offset = AAC_PACKET_DATA_OFFSET;
900        }
901        buf[offset..len].copy_from_slice(self.data);
902        Ok(len)
903    }
904}
905
906impl core::fmt::Debug for AudioTagHeader<'_> {
907    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
908        f.debug_struct("AudioTagHeader")
909            .field("sound_format", &self.sound_format)
910            .field("sound_rate", &self.sound_rate)
911            .field("sound_size", &self.sound_size)
912            .field("sound_type", &self.sound_type)
913            .field("aac_packet_type", &self.aac_packet_type)
914            .field("data_len", &self.data.len())
915            .finish()
916    }
917}
918
919// ── onMetaData (§E.4.1, AMF0 §2) ────────────────────────────────────────
920
921/// FLV `videocodecid` for AVC (= [`CodecId::Avc`]'s code, §E.4.3).
922pub const ON_METADATA_VIDEO_CODEC_ID_AVC: f64 = 7.0;
923/// FLV `audiocodecid` for AAC (= [`SoundFormat::Aac`]'s code, §E.4.2).
924pub const ON_METADATA_AUDIO_CODEC_ID_AAC: f64 = 10.0;
925
926/// The handler name an `onMetaData` script body starts with (§E.4.1).
927pub(crate) const META_HANDLER_NAME: &str = "onMetaData";
928/// The handler name RTMP publishers put before `onMetaData` (§E.4.1; the FLV
929/// file form starts with `onMetaData` directly). It addresses the server, not
930/// the FLV script tag.
931pub const SET_DATA_FRAME: &str = "@setDataFrame";
932/// The `duration` property name.
933const META_DURATION: &str = "duration";
934/// The `width` property name.
935const META_WIDTH: &str = "width";
936/// The `height` property name.
937const META_HEIGHT: &str = "height";
938/// The `framerate` property name.
939const META_FRAME_RATE: &str = "framerate";
940/// The `videocodecid` property name.
941const META_VIDEO_CODEC_ID: &str = "videocodecid";
942/// The `audiosamplerate` property name.
943const META_AUDIO_SAMPLE_RATE: &str = "audiosamplerate";
944/// The `audiosamplesize` property name.
945const META_AUDIO_SAMPLE_SIZE: &str = "audiosamplesize";
946/// The `stereo` property name.
947const META_STEREO: &str = "stereo";
948/// The `audiocodecid` property name.
949const META_AUDIO_CODEC_ID: &str = "audiocodecid";
950/// The `filesize` property name.
951const META_FILE_SIZE: &str = "filesize";
952/// The `encoder` property name.
953const META_ENCODER: &str = "encoder";
954
955/// The informational properties an `onMetaData` script tag states, typed.
956///
957/// Adobe FLV v10.1 §E.4.1 defines the script-data tag and the `onMetaData`
958/// handler but not the property list
959/// (`private/specs-verified/mpeg/transmux/codec/flv.md` §E.4.1). The property
960/// names are the de-facto set real FLV writers emit (`duration`, `width`, `height`, `framerate`,
961/// `videocodecid`, `audiosamplerate`, `audiosamplesize`, `stereo`,
962/// `audiocodecid`, `filesize`, `encoder`); a property the writer stated that
963/// this crate does not name stays in [`properties`](Self::properties) as the
964/// AMF0 value the body carried.
965#[derive(Debug, Clone, PartialEq)]
966#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
967pub struct OnMetadata {
968    body: Vec<u8>,
969    properties: Vec<(String, Amf0Value)>,
970    duration: Option<f64>,
971    width: Option<u16>,
972    height: Option<u16>,
973    frame_rate: Option<f64>,
974    video_codec_id: Option<f64>,
975    audio_sample_rate: Option<u32>,
976    audio_sample_size: Option<u16>,
977    stereo: Option<bool>,
978    audio_codec_id: Option<f64>,
979    file_size: Option<u64>,
980    encoder: Option<String>,
981}
982
983impl OnMetadata {
984    /// The `onMetaData` body — the AMF0 `onMetaData` name followed by one ECMA
985    /// array of the informational properties players read, in the order they
986    /// are written (§E.4.1, AMF0 §2) — that every FLV/RTMP writer emits, so a
987    /// file muxed by an FLV muxer and a stream published over RTMP describe
988    /// the same tracks with the same bytes.
989    ///
990    /// `duration` is the only property a caller decides: a file knows its own
991    /// length, a live publisher does not and passes `None`, which omits the
992    /// key rather than claiming a length. At least one of `tracks` must be AVC
993    /// video or AAC audio for a body to be stated at all; every other track
994    /// contributes no property.
995    ///
996    /// # Errors
997    /// [`RtmpError::Malformed`] when `tracks` holds neither an AVC video nor
998    /// an AAC audio track, and [`RtmpError::FieldOverflow`] when a key exceeds
999    /// its AMF0 length prefix.
1000    pub fn new(tracks: &[PublishTrack], duration: Option<f64>) -> BodyResult<Self> {
1001        Self::with_session(tracks, duration, None, None)
1002    }
1003
1004    /// [`Self::new`] plus the two whole-stream properties a demuxer carries
1005    /// across from a source it re-reads: the source's script tag
1006    /// ([`Self::raw_body`], read under the caller's AMF0 limits) and the source's file size in
1007    /// bytes.
1008    ///
1009    /// A `source` whose handler is not `onMetaData` (an
1010    /// [`SET_DATA_FRAME`]-wrapped body is unwrapped first) is
1011    /// [`RtmpError::Malformed`].
1012    ///
1013    /// # Errors
1014    /// As [`Self::new`], plus [`RtmpError::Malformed`] for an unusable source
1015    /// body.
1016    pub fn with_session(
1017        tracks: &[PublishTrack],
1018        duration: Option<f64>,
1019        source: Option<(&[u8], Amf0Limits)>,
1020        file_size: Option<u64>,
1021    ) -> BodyResult<Self> {
1022        let metadata = Self::from_tracks(tracks, duration)?;
1023        if let Some((source, limits)) = source {
1024            let mut reference = Self::parse_body(source, true, limits)?;
1025            if file_size.is_some() {
1026                reference.file_size = file_size;
1027            }
1028            return Ok(reference);
1029        }
1030        let Some(file_size) = file_size else {
1031            return Ok(metadata);
1032        };
1033        let mut properties = metadata.properties;
1034        properties.push((
1035            META_FILE_SIZE.to_string(),
1036            Amf0Value::Number(file_size as f64),
1037        ));
1038        let stated = Self::from_properties(&[], properties);
1039        let body = stated.script_body()?;
1040        Ok(Self::from_properties(&body, stated.properties))
1041    }
1042
1043    /// The properties `tracks` and `duration` state, read back into the typed
1044    /// view.
1045    fn from_tracks(tracks: &[PublishTrack], duration: Option<f64>) -> BodyResult<Self> {
1046        let video = tracks.iter().find_map(|track| match track {
1047            PublishTrack::Video { width, height, .. } => Some((*width, *height)),
1048            PublishTrack::Audio { .. } => None,
1049        });
1050        let audio = tracks.iter().find_map(|track| match track {
1051            PublishTrack::Audio {
1052                sample_rate,
1053                channel_count,
1054                ..
1055            } => Some((*sample_rate, *channel_count)),
1056            PublishTrack::Video { .. } => None,
1057        });
1058        if video.is_none() && audio.is_none() {
1059            return Err(RtmpError::Malformed {
1060                what: "onMetaData without an AVC video or AAC audio track",
1061            });
1062        }
1063        let mut properties: Vec<(String, Amf0Value)> = Vec::new();
1064        if let Some(duration) = duration {
1065            properties.push((META_DURATION.to_string(), Amf0Value::Number(duration)));
1066        }
1067        if let Some((width, height)) = video {
1068            properties.push((META_WIDTH.to_string(), Amf0Value::Number(f64::from(width))));
1069            properties.push((
1070                META_HEIGHT.to_string(),
1071                Amf0Value::Number(f64::from(height)),
1072            ));
1073            properties.push((
1074                META_VIDEO_CODEC_ID.to_string(),
1075                Amf0Value::Number(ON_METADATA_VIDEO_CODEC_ID_AVC),
1076            ));
1077        }
1078        if let Some((sample_rate, channel_count)) = audio {
1079            properties.push((
1080                META_AUDIO_CODEC_ID.to_string(),
1081                Amf0Value::Number(ON_METADATA_AUDIO_CODEC_ID_AAC),
1082            ));
1083            properties.push((
1084                META_AUDIO_SAMPLE_RATE.to_string(),
1085                Amf0Value::Number(f64::from(sample_rate)),
1086            ));
1087            properties.push((
1088                META_STEREO.to_string(),
1089                Amf0Value::Boolean(
1090                    AudioTagHeader::sound_type_for_channels(channel_count) == SoundType::Stereo,
1091                ),
1092            ));
1093        }
1094        Ok(Self::from_properties(&[], properties))
1095    }
1096
1097    /// This value as its wire bytes: the `onMetaData` handler name followed by
1098    /// the properties as one ECMA array.
1099    ///
1100    /// # Errors
1101    /// [`RtmpError::FieldOverflow`] when a key exceeds its AMF0 length prefix.
1102    pub fn serialize_into_vec(&self) -> BodyResult<Vec<u8>> {
1103        let mut out = alloc::vec![0u8; self.serialized_len()];
1104        let written = self.serialize_into(&mut out)?;
1105        out.truncate(written);
1106        Ok(out)
1107    }
1108
1109    /// The whole-stream duration in seconds, when the writer stated it.
1110    #[must_use]
1111    pub const fn duration(&self) -> Option<f64> {
1112        self.duration
1113    }
1114
1115    /// The coded picture width in pixels.
1116    #[must_use]
1117    pub const fn width(&self) -> Option<u16> {
1118        self.width
1119    }
1120
1121    /// The coded picture height in pixels.
1122    #[must_use]
1123    pub const fn height(&self) -> Option<u16> {
1124        self.height
1125    }
1126
1127    /// The frame rate in frames per second.
1128    #[must_use]
1129    pub const fn frame_rate(&self) -> Option<f64> {
1130        self.frame_rate
1131    }
1132
1133    /// The `videocodecid` the writer stated.
1134    #[must_use]
1135    pub const fn video_codec_id(&self) -> Option<f64> {
1136        self.video_codec_id
1137    }
1138
1139    /// The audio sample rate in Hz.
1140    #[must_use]
1141    pub const fn audio_sample_rate(&self) -> Option<u32> {
1142        self.audio_sample_rate
1143    }
1144
1145    /// The audio sample size in bits.
1146    #[must_use]
1147    pub const fn audio_sample_size(&self) -> Option<u16> {
1148        self.audio_sample_size
1149    }
1150
1151    /// Whether the writer stated a two-channel stream.
1152    #[must_use]
1153    pub const fn stereo(&self) -> Option<bool> {
1154        self.stereo
1155    }
1156
1157    /// The `audiocodecid` the writer stated.
1158    #[must_use]
1159    pub const fn audio_codec_id(&self) -> Option<f64> {
1160        self.audio_codec_id
1161    }
1162
1163    /// The file size the writer stated, in bytes.
1164    #[must_use]
1165    pub const fn file_size(&self) -> Option<u64> {
1166        self.file_size
1167    }
1168
1169    /// The encoding application's name.
1170    #[must_use]
1171    pub fn encoder(&self) -> Option<&str> {
1172        self.encoder.as_deref()
1173    }
1174
1175    /// The script-data body this metadata came from — or the properties
1176    /// rendered as a body when it came from tracks
1177    /// ([`Self::with_session`]'s `source`) — so a remux can write the same
1178    /// bytes back rather than re-encoding the properties.
1179    #[must_use]
1180    pub fn raw_body(&self) -> &[u8] {
1181        &self.body
1182    }
1183
1184    /// Every property the script tag carried, in the order it carried them.
1185    #[must_use]
1186    pub fn properties(&self) -> &[(String, Amf0Value)] {
1187        &self.properties
1188    }
1189
1190    /// One property by name, as the body carried it.
1191    #[must_use]
1192    pub fn property(&self, name: &str) -> Option<&Amf0Value> {
1193        self.properties
1194            .iter()
1195            .find(|(key, _)| key == name)
1196            .map(|(_, value)| value)
1197    }
1198
1199    /// Read an `onMetaData` script-data body (§E.4.1, AMF0 §2).
1200    ///
1201    /// The body is the handler name followed by one property object or ECMA
1202    /// array; an [`SET_DATA_FRAME`] wrapper is accepted. Anything else, or a
1203    /// body that does not parse as AMF0, is not interpretation: `None`.
1204    #[must_use]
1205    pub fn parse(body: &[u8], limits: Amf0Limits) -> Option<Self> {
1206        Self::parse_body(body, false, limits).ok()
1207    }
1208
1209    /// [`Self::parse`], reporting why a body was not interpretation.
1210    ///
1211    /// # Errors
1212    /// [`RtmpError::Malformed`] when the handler is not `onMetaData` or no
1213    /// property object follows it, and the AMF0 error when the body does not
1214    /// decode.
1215    pub fn parse_body(body: &[u8], retain_raw: bool, limits: Amf0Limits) -> BodyResult<Self> {
1216        Self::parse_body_with_diagnostics(body, retain_raw, limits).map(|(metadata, _)| metadata)
1217    }
1218
1219    /// [`Self::parse_body`], also returning every AMF0 defect the body carried that did not stop
1220    /// it being usable, as reports the caller can publish.
1221    ///
1222    /// # Errors
1223    /// Exactly as [`Self::parse_body`].
1224    pub fn parse_body_with_diagnostics(
1225        body: &[u8],
1226        retain_raw: bool,
1227        limits: Amf0Limits,
1228    ) -> BodyResult<(Self, Vec<broadcast_core::damage::Damage>)> {
1229        let (values, diagnostics) = amf0_parse_values_with(body, limits)?;
1230        let mut values = values.into_iter();
1231        let handler = handler_name(values.next())?;
1232        let handler = if handler == SET_DATA_FRAME {
1233            handler_name(values.next())?
1234        } else {
1235            handler
1236        };
1237        if handler != META_HANDLER_NAME {
1238            return Err(RtmpError::Malformed {
1239                what: "FLV onMetaData handler name",
1240            });
1241        }
1242        let properties = match values.next() {
1243            Some(Amf0Value::EcmaArray(properties) | Amf0Value::Object(properties)) => properties,
1244            _ => {
1245                return Err(RtmpError::Malformed {
1246                    what: "FLV onMetaData property object",
1247                });
1248            }
1249        };
1250        let retained = if retain_raw { body } else { &[] };
1251        Ok((Self::from_properties(retained, properties), diagnostics))
1252    }
1253
1254    /// Read the typed view out of a property list.
1255    fn from_properties(body: &[u8], properties: Vec<(String, Amf0Value)>) -> Self {
1256        let number = |name: &str| match find_property(&properties, name) {
1257            Some(Amf0Value::Number(value)) => Some(*value),
1258            _ => None,
1259        };
1260        let whole16 = |name: &str| {
1261            number(name)
1262                .and_then(whole_number)
1263                .and_then(|n| u16::try_from(n).ok())
1264        };
1265        let whole32 = |name: &str| {
1266            number(name)
1267                .and_then(whole_number)
1268                .and_then(|n| u32::try_from(n).ok())
1269        };
1270        let whole64 = |name: &str| number(name).and_then(whole_number);
1271        let encoder = match find_property(&properties, META_ENCODER) {
1272            Some(Amf0Value::String(encoder) | Amf0Value::LongString(encoder)) => {
1273                Some(encoder.clone())
1274            }
1275            _ => None,
1276        };
1277        Self {
1278            body: body.to_vec(),
1279            duration: number(META_DURATION),
1280            width: whole16(META_WIDTH),
1281            height: whole16(META_HEIGHT),
1282            frame_rate: number(META_FRAME_RATE),
1283            video_codec_id: number(META_VIDEO_CODEC_ID),
1284            audio_sample_rate: whole32(META_AUDIO_SAMPLE_RATE),
1285            audio_sample_size: whole16(META_AUDIO_SAMPLE_SIZE),
1286            stereo: match find_property(&properties, META_STEREO) {
1287                Some(Amf0Value::Boolean(stereo)) => Some(*stereo),
1288                _ => None,
1289            },
1290            audio_codec_id: number(META_AUDIO_CODEC_ID),
1291            file_size: whole64(META_FILE_SIZE),
1292            encoder,
1293            properties,
1294        }
1295    }
1296}
1297
1298impl OnMetadata {
1299    /// This metadata as the FLV script tag body (§E.4.1): the `onMetaData`
1300    /// handler name followed by the properties as one ECMA array.
1301    ///
1302    /// # Errors
1303    /// [`RtmpError::FieldOverflow`] when a key exceeds its AMF0 length prefix.
1304    pub fn script_body(&self) -> BodyResult<Vec<u8>> {
1305        let name = Amf0Value::String(META_HANDLER_NAME.to_string());
1306        let array = Amf0Value::EcmaArray(self.properties.clone());
1307        let len = name.serialized_len() + array.serialized_len();
1308        let mut body = alloc::vec![0u8; len];
1309        let written = name.serialize_into(&mut body)?;
1310        let rest = written + array.serialize_into(&mut body[written..])?;
1311        debug_assert_eq!(rest, len);
1312        Ok(body)
1313    }
1314}
1315
1316impl OnMetadata {
1317    /// This metadata as the RTMP Data-AMF0 message payload a publisher sends
1318    /// (Adobe RTMP 1.0 §7.1.2): `@setDataFrame`, then the file form
1319    /// (`onMetaData` and the properties as one ECMA array), the form a real
1320    /// publisher sends (`fixtures/rtmp/obs-publish.bin`) and the inverse of
1321    /// [`strip_set_data_frame`].
1322    ///
1323    /// [`script_body`](Self::script_body) is the other wire form of the same
1324    /// properties: the FLV file's script tag.
1325    ///
1326    /// # Errors
1327    /// [`RtmpError::FieldOverflow`] when a key exceeds its AMF0 length prefix.
1328    pub fn publish_body(&self) -> BodyResult<Vec<u8>> {
1329        set_data_frame_body(&self.properties)
1330    }
1331}
1332
1333/// The `@setDataFrame`/`onMetaData` data message payload for `metadata`, held
1334/// as one AMF0 ECMA array after the handler name (Adobe RTMP 1.0 §7.1.2).
1335///
1336/// # Errors
1337/// [`RtmpError::Amf0StringTooLong`] / [`RtmpError::FieldOverflow`] when a
1338/// string or key does not fit its AMF0 length prefix.
1339pub(crate) fn set_data_frame_body(metadata: &[(String, Amf0Value)]) -> BodyResult<Vec<u8>> {
1340    let mut payload = Amf0Value::String(SET_DATA_FRAME.to_string()).try_to_bytes()?;
1341    payload.extend(Amf0Value::String(META_HANDLER_NAME.to_string()).try_to_bytes()?);
1342    payload.extend(Amf0Value::EcmaArray(metadata.to_vec()).try_to_bytes()?);
1343    Ok(payload)
1344}
1345
1346impl Serialize for OnMetadata {
1347    type Error = RtmpError;
1348
1349    fn try_to_bytes(&self) -> core::result::Result<Vec<u8>, Self::Error> {
1350        let mut out = alloc::vec![0u8; self.serialized_len()];
1351        let written = self.serialize_into(&mut out)?;
1352        out.truncate(written);
1353        Ok(out)
1354    }
1355
1356    /// The `onMetaData` handler name followed by the properties as one ECMA
1357    /// array: the file form of the script-data tag body.
1358    fn serialized_len(&self) -> usize {
1359        if !self.body.is_empty() {
1360            return strip_set_data_frame(&self.body).len();
1361        }
1362        let name = Amf0Value::String(META_HANDLER_NAME.to_string());
1363        name.serialized_len() + Amf0Value::EcmaArray(self.properties.clone()).serialized_len()
1364    }
1365
1366    fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
1367        let len = self.serialized_len();
1368        if buf.len() < len {
1369            return Err(RtmpError::OutputBufferTooSmall(
1370                broadcast_core::error::OutputBufferTooSmall::new(len, buf.len(), "OnMetadata"),
1371            ));
1372        }
1373        if !self.body.is_empty() {
1374            buf[..len].copy_from_slice(strip_set_data_frame(&self.body));
1375            return Ok(len);
1376        }
1377        let name = Amf0Value::String(META_HANDLER_NAME.to_string());
1378        let written = name.serialize_into(buf)?;
1379        let array = Amf0Value::EcmaArray(self.properties.clone());
1380        let rest = written + array.serialize_into(&mut buf[written..])?;
1381        debug_assert_eq!(rest, len);
1382        Ok(rest)
1383    }
1384}
1385
1386/// The handler name an AMF0 value states.
1387fn handler_name(value: Option<Amf0Value>) -> BodyResult<String> {
1388    match value {
1389        Some(Amf0Value::String(handler)) => Ok(handler),
1390        _ => Err(RtmpError::Malformed {
1391            what: "FLV onMetaData handler name",
1392        }),
1393    }
1394}
1395
1396/// A property's value by name.
1397fn find_property<'a>(properties: &'a [(String, Amf0Value)], name: &str) -> Option<&'a Amf0Value> {
1398    properties
1399        .iter()
1400        .find(|(key, _)| key == name)
1401        .map(|(_, value)| value)
1402}
1403
1404/// A finite, non-negative number with no fractional part, as an integer.
1405///
1406/// The `f64` methods (`trunc`, `is_finite`) are `std`-only, so the core build
1407/// (no `std`, no `target`/`tokio`) decides the same way through the
1408/// `PartialOrd`/`PartialEq` comparisons the values themselves support.
1409fn whole_number(value: f64) -> Option<u64> {
1410    const LOWEST: f64 = 0.0;
1411    // A NaN fails the comparison, so it is ruled out with every other value
1412    // outside the range.
1413    if value < LOWEST || value > u64::MAX as f64 {
1414        return None;
1415    }
1416    (value as u64 as f64 == value).then_some(value as u64)
1417}
1418
1419/// `body` without a leading AMF0 `@setDataFrame` string, so the FLV script tag
1420/// begins with `onMetaData` as §E.4.1 defines it.
1421#[must_use]
1422pub fn strip_set_data_frame(body: &[u8]) -> &[u8] {
1423    let Ok(name) = Amf0Value::String(SET_DATA_FRAME.to_owned()).try_to_bytes() else {
1424        return body;
1425    };
1426    body.strip_prefix(name.as_slice()).unwrap_or(body)
1427}
1428
1429#[cfg(test)]
1430#[path = "tag_body_tests.rs"]
1431mod tests;