1use 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
29const FRAME_TYPE_SHIFT: u32 = 4;
33const FRAME_TYPE_MASK: u8 = 0x0F;
35const CODEC_ID_MASK: u8 = 0x0F;
37const SOUND_FORMAT_MASK: u8 = 0x0F;
39const SOUND_FORMAT_SHIFT: u32 = 4;
41const SOUND_RATE_SHIFT: u32 = 2;
43const SOUND_SIZE_SHIFT: u32 = 1;
45const SOUND_TYPE_MASK: u8 = 0x01;
47const SOUND_FIELD_MASK: u8 = 0x03;
49
50pub const VIDEO_TAG_HEADER_LEN: usize = 1;
52const AVC_PACKET_TYPE_AT: usize = 1;
54const AVC_PACKET_TYPE_LEN: usize = 1;
56const COMPOSITION_TIME_AT: usize = AVC_PACKET_TYPE_AT + AVC_PACKET_TYPE_LEN;
58const COMPOSITION_TIME_LEN: usize = 3;
60pub const AVC_PACKET_DATA_OFFSET: usize = COMPOSITION_TIME_AT + COMPOSITION_TIME_LEN;
62pub const COMPOSITION_TIME_MIN: i32 = -(1 << 23);
65pub const COMPOSITION_TIME_MAX: i32 = (1 << 23) - 1;
68
69pub const AUDIO_TAG_HEADER_LEN: usize = 1;
72const AAC_PACKET_TYPE_AT: usize = AUDIO_TAG_HEADER_LEN;
74pub const AAC_PACKET_DATA_OFFSET: usize = AAC_PACKET_TYPE_AT + 1;
76
77#[non_exhaustive]
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
82#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
83pub enum FrameType {
84 Keyframe,
86 Inter,
88 DisposableInter,
90 GeneratedKeyframe,
92 VideoInfo,
94 Reserved(u8),
96 Unknown(u8),
98}
99
100impl FrameType {
101 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 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 #[must_use]
129 pub fn is_keyframe(self) -> bool {
130 matches!(self, Self::Keyframe | Self::GeneratedKeyframe)
131 }
132
133 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#[non_exhaustive]
151#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
152#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
153pub enum CodecId {
154 SorensonH263,
156 ScreenVideo,
158 On2Vp6,
160 On2Vp6Alpha,
162 ScreenVideoV2,
164 Avc,
166 Hevc,
168 Reserved(u8),
170 Unknown(u8),
172}
173
174impl CodecId {
175 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 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 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#[non_exhaustive]
224#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
225#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
226pub enum AvcPacketType {
227 SequenceHeader,
229 Nalu,
231 EndOfSequence,
233 Unknown(u8),
235}
236
237impl AvcPacketType {
238 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 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 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#[non_exhaustive]
279#[derive(Clone, Copy, PartialEq, Eq)]
280#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
281pub struct VideoTagHeader<'a> {
282 pub frame_type: FrameType,
284 pub codec_id: CodecId,
286 pub avc_packet_type: Option<AvcPacketType>,
288 pub composition_time: Option<i32>,
291 pub data: &'a [u8],
293}
294
295impl<'a> VideoTagHeader<'a> {
296 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 #[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 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 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 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#[non_exhaustive]
453#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
454#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
455pub enum SoundFormat {
456 LinearPcmPlatformEndian,
458 Adpcm,
460 Mp3,
462 LinearPcmLittleEndian,
464 Nellymoser16KhzMono,
466 Nellymoser8KhzMono,
468 Nellymoser,
470 G711ALaw,
472 G711MuLaw,
474 Aac,
476 Speex,
478 Mp3_8Khz,
480 DeviceSpecific,
482 Reserved(u8),
484 Unknown(u8),
486}
487
488impl SoundFormat {
489 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 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 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#[non_exhaustive]
556#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
557#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
558pub enum SoundRate {
559 Khz5_5_5,
561 Khz11,
563 Khz22,
565 Khz44,
568}
569
570impl SoundRate {
571 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 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 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#[non_exhaustive]
606#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
607#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
608pub enum SoundSize {
609 Bits8,
611 Bits16,
613}
614
615impl SoundSize {
616 pub fn to_code(self) -> u8 {
618 match self {
619 Self::Bits8 => 0,
620 Self::Bits16 => 1,
621 }
622 }
623
624 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 pub fn bits(self) -> u8 {
635 match self {
636 Self::Bits8 => 8,
637 Self::Bits16 => 16,
638 }
639 }
640
641 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#[non_exhaustive]
654#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
655#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
656pub enum SoundType {
657 Mono,
659 Stereo,
661}
662
663impl SoundType {
664 pub fn to_code(self) -> u8 {
666 match self {
667 Self::Mono => 0,
668 Self::Stereo => 1,
669 }
670 }
671
672 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 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#[non_exhaustive]
694#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
695#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
696pub enum AacPacketType {
697 SequenceHeader,
699 Raw,
701 Unknown(u8),
703}
704
705impl AacPacketType {
706 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 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 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#[non_exhaustive]
744#[derive(Clone, Copy, PartialEq, Eq)]
745#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
746pub struct AudioTagHeader<'a> {
747 pub sound_format: SoundFormat,
749 pub sound_rate: SoundRate,
751 pub sound_size: SoundSize,
753 pub sound_type: SoundType,
755 pub aac_packet_type: Option<AacPacketType>,
757 pub data: &'a [u8],
759}
760
761impl<'a> AudioTagHeader<'a> {
762 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 #[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 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 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 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
929pub const ON_METADATA_VIDEO_CODEC_ID_AVC: f64 = 7.0;
933pub const ON_METADATA_AUDIO_CODEC_ID_AAC: f64 = 10.0;
935
936pub(crate) const META_HANDLER_NAME: &str = "onMetaData";
938pub const SET_DATA_FRAME: &str = "@setDataFrame";
942const META_DURATION: &str = "duration";
944const META_WIDTH: &str = "width";
946const META_HEIGHT: &str = "height";
948const META_FRAME_RATE: &str = "framerate";
950const META_VIDEO_CODEC_ID: &str = "videocodecid";
952const META_AUDIO_SAMPLE_RATE: &str = "audiosamplerate";
954const META_AUDIO_SAMPLE_SIZE: &str = "audiosamplesize";
956const META_STEREO: &str = "stereo";
958const META_AUDIO_CODEC_ID: &str = "audiocodecid";
960const META_FILE_SIZE: &str = "filesize";
962const META_ENCODER: &str = "encoder";
964
965#[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 pub fn new(tracks: &[PublishTrack], duration: Option<f64>) -> BodyResult<Self> {
1011 Self::with_session(tracks, duration, None, None)
1012 }
1013
1014 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 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 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 #[must_use]
1121 pub const fn duration(&self) -> Option<f64> {
1122 self.duration
1123 }
1124
1125 #[must_use]
1127 pub const fn width(&self) -> Option<u16> {
1128 self.width
1129 }
1130
1131 #[must_use]
1133 pub const fn height(&self) -> Option<u16> {
1134 self.height
1135 }
1136
1137 #[must_use]
1139 pub const fn frame_rate(&self) -> Option<f64> {
1140 self.frame_rate
1141 }
1142
1143 #[must_use]
1145 pub const fn video_codec_id(&self) -> Option<f64> {
1146 self.video_codec_id
1147 }
1148
1149 #[must_use]
1151 pub const fn audio_sample_rate(&self) -> Option<u32> {
1152 self.audio_sample_rate
1153 }
1154
1155 #[must_use]
1157 pub const fn audio_sample_size(&self) -> Option<u16> {
1158 self.audio_sample_size
1159 }
1160
1161 #[must_use]
1163 pub const fn stereo(&self) -> Option<bool> {
1164 self.stereo
1165 }
1166
1167 #[must_use]
1169 pub const fn audio_codec_id(&self) -> Option<f64> {
1170 self.audio_codec_id
1171 }
1172
1173 #[must_use]
1175 pub const fn file_size(&self) -> Option<u64> {
1176 self.file_size
1177 }
1178
1179 #[must_use]
1181 pub fn encoder(&self) -> Option<&str> {
1182 self.encoder.as_deref()
1183 }
1184
1185 #[must_use]
1190 pub fn raw_body(&self) -> &[u8] {
1191 &self.body
1192 }
1193
1194 #[must_use]
1196 pub fn properties(&self) -> &[(String, Amf0Value)] {
1197 &self.properties
1198 }
1199
1200 #[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 #[must_use]
1215 pub fn parse(body: &[u8], limits: Amf0Limits) -> Option<Self> {
1216 Self::parse_body(body, false, limits).ok()
1217 }
1218
1219 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 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 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 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 pub fn publish_body(&self) -> BodyResult<Vec<u8>> {
1339 set_data_frame_body(&self.properties)
1340 }
1341}
1342
1343pub(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 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
1396fn 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
1406fn 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
1414fn whole_number(value: f64) -> Option<u64> {
1420 const LOWEST: f64 = 0.0;
1421 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#[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;