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        if self.codec_id == CodecId::Avc && self.avc_packet_type.is_none() {
411            return Err(RtmpError::Malformed {
412                what: "FLV AVCVIDEOPACKET without AVCPacketType",
413            });
414        }
415        let len = self.serialized_len();
416        if buf.len() < len {
417            return Err(RtmpError::OutputBufferTooSmall(
418                broadcast_core::error::OutputBufferTooSmall::new(len, buf.len(), "VideoTagHeader"),
419            ));
420        }
421        let mut w = Writer::new(buf);
422        let frame_type = fit_mask(self.frame_type.to_code(), FRAME_TYPE_MASK, "FrameType")?;
423        let codec_id = fit_mask(self.codec_id.to_code(), CODEC_ID_MASK, "CodecID")?;
424        w.u8(
425            (frame_type << FRAME_TYPE_SHIFT) | codec_id,
426            "FLV video tag frame type",
427        )?;
428        if let Some(packet_type) = self.avc_packet_type() {
429            w.u8(packet_type.to_code(), "FLV video tag packet type")?;
430            w.i24::<RtmpError>(self.composition_time(), "FLV CompositionTime")?;
431        }
432        w.bytes(self.data, "FLV video tag data")?;
433        Ok(len)
434    }
435}
436
437impl core::fmt::Debug for VideoTagHeader<'_> {
438    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
439        f.debug_struct("VideoTagHeader")
440            .field("frame_type", &self.frame_type)
441            .field("codec_id", &self.codec_id)
442            .field("avc_packet_type", &self.avc_packet_type)
443            .field("composition_time", &self.composition_time)
444            .field("data_len", &self.data.len())
445            .finish()
446    }
447}
448
449// ── AudioTagHeader (§E.4.2) ─────────────────────────────────────────────
450
451/// `SoundFormat` of an `AudioTagHeader` (§E.4.2, Table E.6).
452#[non_exhaustive]
453#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
454#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
455pub enum SoundFormat {
456    /// 0: linear PCM, platform endian.
457    LinearPcmPlatformEndian,
458    /// 1: ADPCM.
459    Adpcm,
460    /// 2: MP3.
461    Mp3,
462    /// 3: linear PCM, little endian.
463    LinearPcmLittleEndian,
464    /// 4: Nellymoser 16 kHz mono.
465    Nellymoser16KhzMono,
466    /// 5: Nellymoser 8 kHz mono.
467    Nellymoser8KhzMono,
468    /// 6: Nellymoser.
469    Nellymoser,
470    /// 7: G.711 A-law logarithmic PCM.
471    G711ALaw,
472    /// 8: G.711 mu-law logarithmic PCM.
473    G711MuLaw,
474    /// 10: AAC, carried as `AACAUDIODATA` (§E.4.2.2).
475    Aac,
476    /// 11: Speex.
477    Speex,
478    /// 14: MP3 8 kHz.
479    Mp3_8Khz,
480    /// 15: device-specific sound.
481    DeviceSpecific,
482    /// 9: reserved by the specification.
483    Reserved(u8),
484    /// 12, 13: outside the table, carried as written.
485    Unknown(u8),
486}
487
488impl SoundFormat {
489    /// The code this sound format carries in the `AudioTagHeader` nibble.
490    pub fn to_code(self) -> u8 {
491        match self {
492            Self::LinearPcmPlatformEndian => 0,
493            Self::Adpcm => 1,
494            Self::Mp3 => 2,
495            Self::LinearPcmLittleEndian => 3,
496            Self::Nellymoser16KhzMono => 4,
497            Self::Nellymoser8KhzMono => 5,
498            Self::Nellymoser => 6,
499            Self::G711ALaw => 7,
500            Self::G711MuLaw => 8,
501            Self::Aac => 10,
502            Self::Speex => 11,
503            Self::Mp3_8Khz => 14,
504            Self::DeviceSpecific => 15,
505            Self::Reserved(code) | Self::Unknown(code) => code,
506        }
507    }
508
509    /// The sound format a wire nibble names.
510    pub fn from_code(code: u8) -> Self {
511        match code {
512            0 => Self::LinearPcmPlatformEndian,
513            1 => Self::Adpcm,
514            2 => Self::Mp3,
515            3 => Self::LinearPcmLittleEndian,
516            4 => Self::Nellymoser16KhzMono,
517            5 => Self::Nellymoser8KhzMono,
518            6 => Self::Nellymoser,
519            7 => Self::G711ALaw,
520            8 => Self::G711MuLaw,
521            10 => Self::Aac,
522            11 => Self::Speex,
523            14 => Self::Mp3_8Khz,
524            15 => Self::DeviceSpecific,
525            12 | 13 => Self::Unknown(code),
526            other => Self::Reserved(other),
527        }
528    }
529
530    /// The specification token for the tabled values (Table E.6).
531    pub fn name(&self) -> &'static str {
532        match self {
533            Self::LinearPcmPlatformEndian => "linear PCM, platform endian",
534            Self::Adpcm => "ADPCM",
535            Self::Mp3 => "MP3",
536            Self::LinearPcmLittleEndian => "linear PCM, little endian",
537            Self::Nellymoser16KhzMono => "Nellymoser 16 kHz mono",
538            Self::Nellymoser8KhzMono => "Nellymoser 8 kHz mono",
539            Self::Nellymoser => "Nellymoser",
540            Self::G711ALaw => "G.711 A-law",
541            Self::G711MuLaw => "G.711 mu-law",
542            Self::Aac => "AAC",
543            Self::Speex => "Speex",
544            Self::Mp3_8Khz => "MP3 8 kHz",
545            Self::DeviceSpecific => "device-specific sound",
546            Self::Reserved(_) => "reserved",
547            Self::Unknown(_) => "unknown",
548        }
549    }
550}
551
552broadcast_core::impl_spec_display!(SoundFormat, Reserved, Unknown);
553
554/// `SoundRate` of an `AudioTagHeader` (§E.4.2, Table E.7).
555#[non_exhaustive]
556#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
557#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
558pub enum SoundRate {
559    /// 0: 5.5 kHz.
560    Khz5_5_5,
561    /// 1: 11 kHz.
562    Khz11,
563    /// 2: 22 kHz.
564    Khz22,
565    /// 3: 44 kHz (FLV carries no higher rate here; for AAC it is always 3 and
566    /// the real rate lives in the `AudioSpecificConfig`).
567    Khz44,
568}
569
570impl SoundRate {
571    /// The code this rate carries on the wire.
572    pub fn to_code(self) -> u8 {
573        match self {
574            Self::Khz5_5_5 => 0,
575            Self::Khz11 => 1,
576            Self::Khz22 => 2,
577            Self::Khz44 => 3,
578        }
579    }
580
581    /// The rate a wire code names.
582    pub fn from_code(code: u8) -> Self {
583        match code & SOUND_FIELD_MASK {
584            0 => Self::Khz5_5_5,
585            1 => Self::Khz11,
586            2 => Self::Khz22,
587            _ => Self::Khz44,
588        }
589    }
590
591    /// The specification token for this rate (Table E.7).
592    pub fn name(&self) -> &'static str {
593        match self {
594            Self::Khz5_5_5 => "5.5 kHz",
595            Self::Khz11 => "11 kHz",
596            Self::Khz22 => "22 kHz",
597            Self::Khz44 => "44 kHz",
598        }
599    }
600}
601
602broadcast_core::impl_spec_display!(SoundRate);
603
604/// `SoundSize` of an `AudioTagHeader` (§E.4.2, Table E.8).
605#[non_exhaustive]
606#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
607#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
608pub enum SoundSize {
609    /// 0: 8-bit samples.
610    Bits8,
611    /// 1: 16-bit samples.
612    Bits16,
613}
614
615impl SoundSize {
616    /// The code this size carries on the wire.
617    pub fn to_code(self) -> u8 {
618        match self {
619            Self::Bits8 => 0,
620            Self::Bits16 => 1,
621        }
622    }
623
624    /// The size a wire bit names.
625    pub fn from_code(code: u8) -> Self {
626        if code & SOUND_TYPE_MASK == 0 {
627            Self::Bits8
628        } else {
629            Self::Bits16
630        }
631    }
632
633    /// The sample size in bits.
634    pub fn bits(self) -> u8 {
635        match self {
636            Self::Bits8 => 8,
637            Self::Bits16 => 16,
638        }
639    }
640
641    /// The specification token for this size (Table E.8).
642    pub fn name(&self) -> &'static str {
643        match self {
644            Self::Bits8 => "8-bit",
645            Self::Bits16 => "16-bit",
646        }
647    }
648}
649
650broadcast_core::impl_spec_display!(SoundSize);
651
652/// `SoundType` of an `AudioTagHeader` (§E.4.2, Table E.9).
653#[non_exhaustive]
654#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
655#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
656pub enum SoundType {
657    /// 0: mono.
658    Mono,
659    /// 1: stereo.
660    Stereo,
661}
662
663impl SoundType {
664    /// The code this sound type carries on the wire.
665    pub fn to_code(self) -> u8 {
666        match self {
667            Self::Mono => 0,
668            Self::Stereo => 1,
669        }
670    }
671
672    /// The sound type a wire bit names.
673    pub fn from_code(code: u8) -> Self {
674        if code & SOUND_TYPE_MASK == 0 {
675            Self::Mono
676        } else {
677            Self::Stereo
678        }
679    }
680
681    /// The specification token for this sound type (Table E.9).
682    pub fn name(&self) -> &'static str {
683        match self {
684            Self::Mono => "mono",
685            Self::Stereo => "stereo",
686        }
687    }
688}
689
690broadcast_core::impl_spec_display!(SoundType);
691
692/// `AACPacketType` of an AAC `AACAUDIODATA` (§E.4.2.2).
693#[non_exhaustive]
694#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
695#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
696pub enum AacPacketType {
697    /// 0: AAC sequence header — the `AudioSpecificConfig`.
698    SequenceHeader,
699    /// 1: AAC raw — one raw AAC access unit.
700    Raw,
701    /// 2 or above: outside the table, carried as written.
702    Unknown(u8),
703}
704
705impl AacPacketType {
706    /// The code this packet type carries on the wire.
707    pub fn to_code(self) -> u8 {
708        match self {
709            Self::SequenceHeader => 0,
710            Self::Raw => 1,
711            Self::Unknown(code) => code,
712        }
713    }
714
715    /// The packet type a wire byte names.
716    pub fn from_code(code: u8) -> Self {
717        match code {
718            0 => Self::SequenceHeader,
719            1 => Self::Raw,
720            other => Self::Unknown(other),
721        }
722    }
723
724    /// The specification token for the tabled values (§E.4.2.2).
725    pub fn name(&self) -> &'static str {
726        match self {
727            Self::SequenceHeader => "sequence header",
728            Self::Raw => "raw",
729            Self::Unknown(_) => "unknown",
730        }
731    }
732}
733
734broadcast_core::impl_spec_display!(AacPacketType, Unknown);
735
736/// The `AudioTagHeader` (§E.4.2) and, for AAC, the packet header of its
737/// `AACAUDIODATA` body (§E.4.2.2).
738///
739/// `AACAUDIODATA` is the only audio packet layout this crate decodes; any
740/// other `SoundFormat` keeps all the bytes after the first byte as
741/// [`data`](Self::data), because no packet header of that codec is modelled
742/// here.
743#[non_exhaustive]
744#[derive(Clone, Copy, PartialEq, Eq)]
745#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
746pub struct AudioTagHeader<'a> {
747    /// `SoundFormat` (§E.4.2).
748    pub sound_format: SoundFormat,
749    /// `SoundRate` (§E.4.2).
750    pub sound_rate: SoundRate,
751    /// `SoundSize` (§E.4.2).
752    pub sound_size: SoundSize,
753    /// `SoundType` (§E.4.2).
754    pub sound_type: SoundType,
755    /// `AACPacketType`: set only for [`SoundFormat::Aac`] (§E.4.2.2).
756    pub aac_packet_type: Option<AacPacketType>,
757    /// The coded bytes after the packet header.
758    pub data: &'a [u8],
759}
760
761impl<'a> AudioTagHeader<'a> {
762    /// A header with no packet header and no coded data.
763    pub fn new(
764        sound_format: SoundFormat,
765        sound_rate: SoundRate,
766        sound_size: SoundSize,
767        sound_type: SoundType,
768        aac_packet_type: Option<AacPacketType>,
769    ) -> Self {
770        Self {
771            sound_format,
772            sound_rate,
773            sound_size,
774            sound_type,
775            aac_packet_type,
776            data: &[],
777        }
778    }
779
780    /// The `SoundType` an audio `channel_count` states: one channel or fewer
781    /// is mono, anything above is stereo (§E.5's `stereo` rule).
782    #[must_use]
783    pub fn sound_type_for_channels(channel_count: u16) -> SoundType {
784        const MONO_CHANNELS: u16 = 1;
785        if channel_count <= MONO_CHANNELS {
786            SoundType::Mono
787        } else {
788            SoundType::Stereo
789        }
790    }
791
792    /// The packet type the wire carries: the stated `AACPacketType` for AAC,
793    /// and none for any other format.
794    fn aac_packet_type(&self) -> Option<AacPacketType> {
795        if self.sound_format == SoundFormat::Aac {
796            self.aac_packet_type
797        } else {
798            None
799        }
800    }
801
802    /// The header's own bytes plus `data`, the whole `AUDIODATA` body.
803    ///
804    /// # Errors
805    /// [`RtmpError::Malformed`] when an `AACPacketType` is stated for a
806    /// `SoundFormat` that carries none, or when an AAC body states none.
807    pub fn to_bytes(&self) -> BodyResult<Vec<u8>> {
808        if self.sound_format != SoundFormat::Aac && self.aac_packet_type.is_some() {
809            return Err(RtmpError::Malformed {
810                what: "FLV AACPacketType for a non-AAC SoundFormat",
811            });
812        }
813        let len = self.serialized_len();
814        let mut out = alloc::vec![0u8; len];
815        let written = self.serialize_into(&mut out)?;
816        debug_assert_eq!(written, len);
817        Ok(out)
818    }
819
820    /// The `AudioTagHeader` first byte these sound fields make up (§E.4.2).
821    ///
822    /// # Errors
823    /// [`RtmpError::FieldOverflow`] when a field's code does not fit its bits
824    /// (a reserved or unknown code carries any byte).
825    pub fn first_byte(&self) -> BodyResult<u8> {
826        let format = fit_mask(
827            self.sound_format.to_code(),
828            SOUND_FORMAT_MASK,
829            "SoundFormat",
830        )?;
831        let rate = fit_mask(self.sound_rate.to_code(), SOUND_FIELD_MASK, "SoundRate")?;
832        let size = fit_mask(self.sound_size.to_code(), SOUND_TYPE_MASK, "SoundSize")?;
833        let kind = fit_mask(self.sound_type.to_code(), SOUND_TYPE_MASK, "SoundType")?;
834        Ok((format << SOUND_FORMAT_SHIFT)
835            | (rate << SOUND_RATE_SHIFT)
836            | (size << SOUND_SIZE_SHIFT)
837            | kind)
838    }
839}
840
841impl<'a> Parse<'a> for AudioTagHeader<'a> {
842    type Error = RtmpError;
843
844    fn parse(bytes: &'a [u8]) -> BodyResult<Self> {
845        let first = *bytes
846            .first()
847            .ok_or(RtmpError::BufferTooShort(BufferTooShort::new(
848                AUDIO_TAG_HEADER_LEN,
849                bytes.len(),
850                "FLV AudioTagHeader",
851            )))?;
852        let sound_format = SoundFormat::from_code(first >> SOUND_FORMAT_SHIFT);
853        let prefix = Self {
854            sound_format,
855            sound_rate: SoundRate::from_code(first >> SOUND_RATE_SHIFT),
856            sound_size: SoundSize::from_code(first >> SOUND_SIZE_SHIFT),
857            sound_type: SoundType::from_code(first),
858            aac_packet_type: None,
859            data: &[],
860        };
861        if sound_format != SoundFormat::Aac {
862            return Ok(Self {
863                data: &bytes[AUDIO_TAG_HEADER_LEN..],
864                ..prefix
865            });
866        }
867        let packet_type = *bytes
868            .get(AAC_PACKET_TYPE_AT)
869            .ok_or(RtmpError::BufferTooShort(BufferTooShort::new(
870                AAC_PACKET_DATA_OFFSET,
871                bytes.len(),
872                "FLV AACAUDIODATA",
873            )))?;
874        Ok(Self {
875            aac_packet_type: Some(AacPacketType::from_code(packet_type)),
876            data: &bytes[AAC_PACKET_DATA_OFFSET..],
877            ..prefix
878        })
879    }
880}
881
882impl Serialize for AudioTagHeader<'_> {
883    type Error = RtmpError;
884
885    fn serialized_len(&self) -> usize {
886        let mut len = AUDIO_TAG_HEADER_LEN;
887        if self.aac_packet_type().is_some() {
888            len += AAC_PACKET_DATA_OFFSET - AUDIO_TAG_HEADER_LEN;
889        }
890        len + self.data.len()
891    }
892
893    fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
894        if self.sound_format == SoundFormat::Aac && self.aac_packet_type.is_none() {
895            return Err(RtmpError::Malformed {
896                what: "FLV AACAUDIODATA without AACPacketType",
897            });
898        }
899        let len = self.serialized_len();
900        if buf.len() < len {
901            return Err(RtmpError::OutputBufferTooSmall(
902                broadcast_core::error::OutputBufferTooSmall::new(len, buf.len(), "AudioTagHeader"),
903            ));
904        }
905        buf[0] = self.first_byte()?;
906        let mut offset = AUDIO_TAG_HEADER_LEN;
907        if let Some(packet_type) = self.aac_packet_type() {
908            buf[AAC_PACKET_TYPE_AT] = packet_type.to_code();
909            offset = AAC_PACKET_DATA_OFFSET;
910        }
911        buf[offset..len].copy_from_slice(self.data);
912        Ok(len)
913    }
914}
915
916impl core::fmt::Debug for AudioTagHeader<'_> {
917    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
918        f.debug_struct("AudioTagHeader")
919            .field("sound_format", &self.sound_format)
920            .field("sound_rate", &self.sound_rate)
921            .field("sound_size", &self.sound_size)
922            .field("sound_type", &self.sound_type)
923            .field("aac_packet_type", &self.aac_packet_type)
924            .field("data_len", &self.data.len())
925            .finish()
926    }
927}
928
929// ── onMetaData (§E.4.1, AMF0 §2) ────────────────────────────────────────
930
931/// FLV `videocodecid` for AVC (= [`CodecId::Avc`]'s code, §E.4.3).
932pub const ON_METADATA_VIDEO_CODEC_ID_AVC: f64 = 7.0;
933/// FLV `audiocodecid` for AAC (= [`SoundFormat::Aac`]'s code, §E.4.2).
934pub const ON_METADATA_AUDIO_CODEC_ID_AAC: f64 = 10.0;
935
936/// The handler name an `onMetaData` script body starts with (§E.4.1).
937pub(crate) const META_HANDLER_NAME: &str = "onMetaData";
938/// The handler name RTMP publishers put before `onMetaData` (§E.4.1; the FLV
939/// file form starts with `onMetaData` directly). It addresses the server, not
940/// the FLV script tag.
941pub const SET_DATA_FRAME: &str = "@setDataFrame";
942/// The `duration` property name.
943const META_DURATION: &str = "duration";
944/// The `width` property name.
945const META_WIDTH: &str = "width";
946/// The `height` property name.
947const META_HEIGHT: &str = "height";
948/// The `framerate` property name.
949const META_FRAME_RATE: &str = "framerate";
950/// The `videocodecid` property name.
951const META_VIDEO_CODEC_ID: &str = "videocodecid";
952/// The `audiosamplerate` property name.
953const META_AUDIO_SAMPLE_RATE: &str = "audiosamplerate";
954/// The `audiosamplesize` property name.
955const META_AUDIO_SAMPLE_SIZE: &str = "audiosamplesize";
956/// The `stereo` property name.
957const META_STEREO: &str = "stereo";
958/// The `audiocodecid` property name.
959const META_AUDIO_CODEC_ID: &str = "audiocodecid";
960/// The `filesize` property name.
961const META_FILE_SIZE: &str = "filesize";
962/// The `encoder` property name.
963const META_ENCODER: &str = "encoder";
964
965/// The informational properties an `onMetaData` script tag states, typed.
966///
967/// Adobe FLV v10.1 §E.4.1 defines the script-data tag and the `onMetaData`
968/// handler but not the property list
969/// (`private/specs-verified/mpeg/transmux/codec/flv.md` §E.4.1). The property
970/// names are the de-facto set real FLV writers emit (`duration`, `width`, `height`, `framerate`,
971/// `videocodecid`, `audiosamplerate`, `audiosamplesize`, `stereo`,
972/// `audiocodecid`, `filesize`, `encoder`); a property the writer stated that
973/// this crate does not name stays in [`properties`](Self::properties) as the
974/// AMF0 value the body carried.
975#[derive(Debug, Clone, PartialEq)]
976#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
977pub struct OnMetadata {
978    body: Vec<u8>,
979    properties: Vec<(String, Amf0Value)>,
980    duration: Option<f64>,
981    width: Option<u16>,
982    height: Option<u16>,
983    frame_rate: Option<f64>,
984    video_codec_id: Option<f64>,
985    audio_sample_rate: Option<u32>,
986    audio_sample_size: Option<u16>,
987    stereo: Option<bool>,
988    audio_codec_id: Option<f64>,
989    file_size: Option<u64>,
990    encoder: Option<String>,
991}
992
993impl OnMetadata {
994    /// The `onMetaData` body — the AMF0 `onMetaData` name followed by one ECMA
995    /// array of the informational properties players read, in the order they
996    /// are written (§E.4.1, AMF0 §2) — that every FLV/RTMP writer emits, so a
997    /// file muxed by an FLV muxer and a stream published over RTMP describe
998    /// the same tracks with the same bytes.
999    ///
1000    /// `duration` is the only property a caller decides: a file knows its own
1001    /// length, a live publisher does not and passes `None`, which omits the
1002    /// key rather than claiming a length. At least one of `tracks` must be AVC
1003    /// video or AAC audio for a body to be stated at all; every other track
1004    /// contributes no property.
1005    ///
1006    /// # Errors
1007    /// [`RtmpError::Malformed`] when `tracks` holds neither an AVC video nor
1008    /// an AAC audio track, and [`RtmpError::FieldOverflow`] when a key exceeds
1009    /// its AMF0 length prefix.
1010    pub fn new(tracks: &[PublishTrack], duration: Option<f64>) -> BodyResult<Self> {
1011        Self::with_session(tracks, duration, None, None)
1012    }
1013
1014    /// [`Self::new`] plus the two whole-stream properties a demuxer carries
1015    /// across from a source it re-reads: the source's script tag
1016    /// ([`Self::raw_body`], read under the caller's AMF0 limits) and the source's file size in
1017    /// bytes.
1018    ///
1019    /// A `source` whose handler is not `onMetaData` (an
1020    /// [`SET_DATA_FRAME`]-wrapped body is unwrapped first) is
1021    /// [`RtmpError::Malformed`].
1022    ///
1023    /// # Errors
1024    /// As [`Self::new`], plus [`RtmpError::Malformed`] for an unusable source
1025    /// body.
1026    pub fn with_session(
1027        tracks: &[PublishTrack],
1028        duration: Option<f64>,
1029        source: Option<(&[u8], Amf0Limits)>,
1030        file_size: Option<u64>,
1031    ) -> BodyResult<Self> {
1032        let metadata = Self::from_tracks(tracks, duration)?;
1033        if let Some((source, limits)) = source {
1034            let mut reference = Self::parse_body(source, true, limits)?;
1035            if file_size.is_some() {
1036                reference.file_size = file_size;
1037            }
1038            return Ok(reference);
1039        }
1040        let Some(file_size) = file_size else {
1041            return Ok(metadata);
1042        };
1043        let mut properties = metadata.properties;
1044        properties.push((
1045            META_FILE_SIZE.to_string(),
1046            Amf0Value::Number(file_size as f64),
1047        ));
1048        let stated = Self::from_properties(&[], properties);
1049        let body = stated.script_body()?;
1050        Ok(Self::from_properties(&body, stated.properties))
1051    }
1052
1053    /// The properties `tracks` and `duration` state, read back into the typed
1054    /// view.
1055    fn from_tracks(tracks: &[PublishTrack], duration: Option<f64>) -> BodyResult<Self> {
1056        let video = tracks.iter().find_map(|track| match track {
1057            PublishTrack::Video { width, height, .. } => Some((*width, *height)),
1058            PublishTrack::Audio { .. } => None,
1059        });
1060        let audio = tracks.iter().find_map(|track| match track {
1061            PublishTrack::Audio {
1062                sample_rate,
1063                channel_count,
1064                ..
1065            } => Some((*sample_rate, *channel_count)),
1066            PublishTrack::Video { .. } => None,
1067        });
1068        if video.is_none() && audio.is_none() {
1069            return Err(RtmpError::Malformed {
1070                what: "onMetaData without an AVC video or AAC audio track",
1071            });
1072        }
1073        let mut properties: Vec<(String, Amf0Value)> = Vec::new();
1074        if let Some(duration) = duration {
1075            properties.push((META_DURATION.to_string(), Amf0Value::Number(duration)));
1076        }
1077        if let Some((width, height)) = video {
1078            properties.push((META_WIDTH.to_string(), Amf0Value::Number(f64::from(width))));
1079            properties.push((
1080                META_HEIGHT.to_string(),
1081                Amf0Value::Number(f64::from(height)),
1082            ));
1083            properties.push((
1084                META_VIDEO_CODEC_ID.to_string(),
1085                Amf0Value::Number(ON_METADATA_VIDEO_CODEC_ID_AVC),
1086            ));
1087        }
1088        if let Some((sample_rate, channel_count)) = audio {
1089            properties.push((
1090                META_AUDIO_CODEC_ID.to_string(),
1091                Amf0Value::Number(ON_METADATA_AUDIO_CODEC_ID_AAC),
1092            ));
1093            properties.push((
1094                META_AUDIO_SAMPLE_RATE.to_string(),
1095                Amf0Value::Number(f64::from(sample_rate)),
1096            ));
1097            properties.push((
1098                META_STEREO.to_string(),
1099                Amf0Value::Boolean(
1100                    AudioTagHeader::sound_type_for_channels(channel_count) == SoundType::Stereo,
1101                ),
1102            ));
1103        }
1104        Ok(Self::from_properties(&[], properties))
1105    }
1106
1107    /// This value as its wire bytes: the `onMetaData` handler name followed by
1108    /// the properties as one ECMA array.
1109    ///
1110    /// # Errors
1111    /// [`RtmpError::FieldOverflow`] when a key exceeds its AMF0 length prefix.
1112    pub fn serialize_into_vec(&self) -> BodyResult<Vec<u8>> {
1113        let mut out = alloc::vec![0u8; self.serialized_len()];
1114        let written = self.serialize_into(&mut out)?;
1115        out.truncate(written);
1116        Ok(out)
1117    }
1118
1119    /// The whole-stream duration in seconds, when the writer stated it.
1120    #[must_use]
1121    pub const fn duration(&self) -> Option<f64> {
1122        self.duration
1123    }
1124
1125    /// The coded picture width in pixels.
1126    #[must_use]
1127    pub const fn width(&self) -> Option<u16> {
1128        self.width
1129    }
1130
1131    /// The coded picture height in pixels.
1132    #[must_use]
1133    pub const fn height(&self) -> Option<u16> {
1134        self.height
1135    }
1136
1137    /// The frame rate in frames per second.
1138    #[must_use]
1139    pub const fn frame_rate(&self) -> Option<f64> {
1140        self.frame_rate
1141    }
1142
1143    /// The `videocodecid` the writer stated.
1144    #[must_use]
1145    pub const fn video_codec_id(&self) -> Option<f64> {
1146        self.video_codec_id
1147    }
1148
1149    /// The audio sample rate in Hz.
1150    #[must_use]
1151    pub const fn audio_sample_rate(&self) -> Option<u32> {
1152        self.audio_sample_rate
1153    }
1154
1155    /// The audio sample size in bits.
1156    #[must_use]
1157    pub const fn audio_sample_size(&self) -> Option<u16> {
1158        self.audio_sample_size
1159    }
1160
1161    /// Whether the writer stated a two-channel stream.
1162    #[must_use]
1163    pub const fn stereo(&self) -> Option<bool> {
1164        self.stereo
1165    }
1166
1167    /// The `audiocodecid` the writer stated.
1168    #[must_use]
1169    pub const fn audio_codec_id(&self) -> Option<f64> {
1170        self.audio_codec_id
1171    }
1172
1173    /// The file size the writer stated, in bytes.
1174    #[must_use]
1175    pub const fn file_size(&self) -> Option<u64> {
1176        self.file_size
1177    }
1178
1179    /// The encoding application's name.
1180    #[must_use]
1181    pub fn encoder(&self) -> Option<&str> {
1182        self.encoder.as_deref()
1183    }
1184
1185    /// The script-data body this metadata came from — or the properties
1186    /// rendered as a body when it came from tracks
1187    /// ([`Self::with_session`]'s `source`) — so a remux can write the same
1188    /// bytes back rather than re-encoding the properties.
1189    #[must_use]
1190    pub fn raw_body(&self) -> &[u8] {
1191        &self.body
1192    }
1193
1194    /// Every property the script tag carried, in the order it carried them.
1195    #[must_use]
1196    pub fn properties(&self) -> &[(String, Amf0Value)] {
1197        &self.properties
1198    }
1199
1200    /// One property by name, as the body carried it.
1201    #[must_use]
1202    pub fn property(&self, name: &str) -> Option<&Amf0Value> {
1203        self.properties
1204            .iter()
1205            .find(|(key, _)| key == name)
1206            .map(|(_, value)| value)
1207    }
1208
1209    /// Read an `onMetaData` script-data body (§E.4.1, AMF0 §2).
1210    ///
1211    /// The body is the handler name followed by one property object or ECMA
1212    /// array; an [`SET_DATA_FRAME`] wrapper is accepted. Anything else, or a
1213    /// body that does not parse as AMF0, is not interpretation: `None`.
1214    #[must_use]
1215    pub fn parse(body: &[u8], limits: Amf0Limits) -> Option<Self> {
1216        Self::parse_body(body, false, limits).ok()
1217    }
1218
1219    /// [`Self::parse`], reporting why a body was not interpretation.
1220    ///
1221    /// # Errors
1222    /// [`RtmpError::Malformed`] when the handler is not `onMetaData` or no
1223    /// property object follows it, and the AMF0 error when the body does not
1224    /// decode.
1225    pub fn parse_body(body: &[u8], retain_raw: bool, limits: Amf0Limits) -> BodyResult<Self> {
1226        Self::parse_body_with_diagnostics(body, retain_raw, limits).map(|(metadata, _)| metadata)
1227    }
1228
1229    /// [`Self::parse_body`], also returning every AMF0 defect the body carried that did not stop
1230    /// it being usable, as reports the caller can publish.
1231    ///
1232    /// # Errors
1233    /// Exactly as [`Self::parse_body`].
1234    pub fn parse_body_with_diagnostics(
1235        body: &[u8],
1236        retain_raw: bool,
1237        limits: Amf0Limits,
1238    ) -> BodyResult<(Self, Vec<broadcast_core::damage::Damage>)> {
1239        let (values, diagnostics) = amf0_parse_values_with(body, limits)?;
1240        let mut values = values.into_iter();
1241        let handler = handler_name(values.next())?;
1242        let handler = if handler == SET_DATA_FRAME {
1243            handler_name(values.next())?
1244        } else {
1245            handler
1246        };
1247        if handler != META_HANDLER_NAME {
1248            return Err(RtmpError::Malformed {
1249                what: "FLV onMetaData handler name",
1250            });
1251        }
1252        let properties = match values.next() {
1253            Some(Amf0Value::EcmaArray(properties) | Amf0Value::Object(properties)) => properties,
1254            _ => {
1255                return Err(RtmpError::Malformed {
1256                    what: "FLV onMetaData property object",
1257                });
1258            }
1259        };
1260        let retained = if retain_raw { body } else { &[] };
1261        Ok((Self::from_properties(retained, properties), diagnostics))
1262    }
1263
1264    /// Read the typed view out of a property list.
1265    fn from_properties(body: &[u8], properties: Vec<(String, Amf0Value)>) -> Self {
1266        let number = |name: &str| match find_property(&properties, name) {
1267            Some(Amf0Value::Number(value)) => Some(*value),
1268            _ => None,
1269        };
1270        let whole16 = |name: &str| {
1271            number(name)
1272                .and_then(whole_number)
1273                .and_then(|n| u16::try_from(n).ok())
1274        };
1275        let whole32 = |name: &str| {
1276            number(name)
1277                .and_then(whole_number)
1278                .and_then(|n| u32::try_from(n).ok())
1279        };
1280        let whole64 = |name: &str| number(name).and_then(whole_number);
1281        let encoder = match find_property(&properties, META_ENCODER) {
1282            Some(Amf0Value::String(encoder) | Amf0Value::LongString(encoder)) => {
1283                Some(encoder.clone())
1284            }
1285            _ => None,
1286        };
1287        Self {
1288            body: body.to_vec(),
1289            duration: number(META_DURATION),
1290            width: whole16(META_WIDTH),
1291            height: whole16(META_HEIGHT),
1292            frame_rate: number(META_FRAME_RATE),
1293            video_codec_id: number(META_VIDEO_CODEC_ID),
1294            audio_sample_rate: whole32(META_AUDIO_SAMPLE_RATE),
1295            audio_sample_size: whole16(META_AUDIO_SAMPLE_SIZE),
1296            stereo: match find_property(&properties, META_STEREO) {
1297                Some(Amf0Value::Boolean(stereo)) => Some(*stereo),
1298                _ => None,
1299            },
1300            audio_codec_id: number(META_AUDIO_CODEC_ID),
1301            file_size: whole64(META_FILE_SIZE),
1302            encoder,
1303            properties,
1304        }
1305    }
1306}
1307
1308impl OnMetadata {
1309    /// This metadata as the FLV script tag body (§E.4.1): the `onMetaData`
1310    /// handler name followed by the properties as one ECMA array.
1311    ///
1312    /// # Errors
1313    /// [`RtmpError::FieldOverflow`] when a key exceeds its AMF0 length prefix.
1314    pub fn script_body(&self) -> BodyResult<Vec<u8>> {
1315        let name = Amf0Value::String(META_HANDLER_NAME.to_string());
1316        let array = Amf0Value::EcmaArray(self.properties.clone());
1317        let len = name.serialized_len() + array.serialized_len();
1318        let mut body = alloc::vec![0u8; len];
1319        let written = name.serialize_into(&mut body)?;
1320        let rest = written + array.serialize_into(&mut body[written..])?;
1321        debug_assert_eq!(rest, len);
1322        Ok(body)
1323    }
1324}
1325
1326impl OnMetadata {
1327    /// This metadata as the RTMP Data-AMF0 message payload a publisher sends
1328    /// (Adobe RTMP 1.0 §7.1.2): `@setDataFrame`, then the file form
1329    /// (`onMetaData` and the properties as one ECMA array), the form a real
1330    /// publisher sends (`fixtures/rtmp/obs-publish.bin`) and the inverse of
1331    /// [`strip_set_data_frame`].
1332    ///
1333    /// [`script_body`](Self::script_body) is the other wire form of the same
1334    /// properties: the FLV file's script tag.
1335    ///
1336    /// # Errors
1337    /// [`RtmpError::FieldOverflow`] when a key exceeds its AMF0 length prefix.
1338    pub fn publish_body(&self) -> BodyResult<Vec<u8>> {
1339        set_data_frame_body(&self.properties)
1340    }
1341}
1342
1343/// The `@setDataFrame`/`onMetaData` data message payload for `metadata`, held
1344/// as one AMF0 ECMA array after the handler name (Adobe RTMP 1.0 §7.1.2).
1345///
1346/// # Errors
1347/// [`RtmpError::Amf0StringTooLong`] / [`RtmpError::FieldOverflow`] when a
1348/// string or key does not fit its AMF0 length prefix.
1349pub(crate) fn set_data_frame_body(metadata: &[(String, Amf0Value)]) -> BodyResult<Vec<u8>> {
1350    let mut payload = Amf0Value::String(SET_DATA_FRAME.to_string()).try_to_bytes()?;
1351    payload.extend(Amf0Value::String(META_HANDLER_NAME.to_string()).try_to_bytes()?);
1352    payload.extend(Amf0Value::EcmaArray(metadata.to_vec()).try_to_bytes()?);
1353    Ok(payload)
1354}
1355
1356impl Serialize for OnMetadata {
1357    type Error = RtmpError;
1358
1359    fn try_to_bytes(&self) -> core::result::Result<Vec<u8>, Self::Error> {
1360        let mut out = alloc::vec![0u8; self.serialized_len()];
1361        let written = self.serialize_into(&mut out)?;
1362        out.truncate(written);
1363        Ok(out)
1364    }
1365
1366    /// The `onMetaData` handler name followed by the properties as one ECMA
1367    /// array: the file form of the script-data tag body.
1368    fn serialized_len(&self) -> usize {
1369        if !self.body.is_empty() {
1370            return strip_set_data_frame(&self.body).len();
1371        }
1372        let name = Amf0Value::String(META_HANDLER_NAME.to_string());
1373        name.serialized_len() + Amf0Value::EcmaArray(self.properties.clone()).serialized_len()
1374    }
1375
1376    fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
1377        let len = self.serialized_len();
1378        if buf.len() < len {
1379            return Err(RtmpError::OutputBufferTooSmall(
1380                broadcast_core::error::OutputBufferTooSmall::new(len, buf.len(), "OnMetadata"),
1381            ));
1382        }
1383        if !self.body.is_empty() {
1384            buf[..len].copy_from_slice(strip_set_data_frame(&self.body));
1385            return Ok(len);
1386        }
1387        let name = Amf0Value::String(META_HANDLER_NAME.to_string());
1388        let written = name.serialize_into(buf)?;
1389        let array = Amf0Value::EcmaArray(self.properties.clone());
1390        let rest = written + array.serialize_into(&mut buf[written..])?;
1391        debug_assert_eq!(rest, len);
1392        Ok(rest)
1393    }
1394}
1395
1396/// The handler name an AMF0 value states.
1397fn handler_name(value: Option<Amf0Value>) -> BodyResult<String> {
1398    match value {
1399        Some(Amf0Value::String(handler)) => Ok(handler),
1400        _ => Err(RtmpError::Malformed {
1401            what: "FLV onMetaData handler name",
1402        }),
1403    }
1404}
1405
1406/// A property's value by name.
1407fn find_property<'a>(properties: &'a [(String, Amf0Value)], name: &str) -> Option<&'a Amf0Value> {
1408    properties
1409        .iter()
1410        .find(|(key, _)| key == name)
1411        .map(|(_, value)| value)
1412}
1413
1414/// A finite, non-negative number with no fractional part, as an integer.
1415///
1416/// The `f64` methods (`trunc`, `is_finite`) are `std`-only, so the core build
1417/// (no `std`, no `target`/`tokio`) decides the same way through the
1418/// `PartialOrd`/`PartialEq` comparisons the values themselves support.
1419fn whole_number(value: f64) -> Option<u64> {
1420    const LOWEST: f64 = 0.0;
1421    // A NaN fails the comparison, so it is ruled out with every other value
1422    // outside the range.
1423    if value < LOWEST || value > u64::MAX as f64 {
1424        return None;
1425    }
1426    (value as u64 as f64 == value).then_some(value as u64)
1427}
1428
1429/// `body` without a leading AMF0 `@setDataFrame` string, so the FLV script tag
1430/// begins with `onMetaData` as §E.4.1 defines it.
1431#[must_use]
1432pub fn strip_set_data_frame(body: &[u8]) -> &[u8] {
1433    let Ok(name) = Amf0Value::String(SET_DATA_FRAME.to_owned()).try_to_bytes() else {
1434        return body;
1435    };
1436    body.strip_prefix(name.as_slice()).unwrap_or(body)
1437}
1438
1439#[cfg(test)]
1440#[path = "tag_body_tests.rs"]
1441mod tests;