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 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#[non_exhaustive]
448#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
449#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
450pub enum SoundFormat {
451 LinearPcmPlatformEndian,
453 Adpcm,
455 Mp3,
457 LinearPcmLittleEndian,
459 Nellymoser16KhzMono,
461 Nellymoser8KhzMono,
463 Nellymoser,
465 G711ALaw,
467 G711MuLaw,
469 Aac,
471 Speex,
473 Mp3_8Khz,
475 DeviceSpecific,
477 Reserved(u8),
479 Unknown(u8),
481}
482
483impl SoundFormat {
484 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 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 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#[non_exhaustive]
551#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
552#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
553pub enum SoundRate {
554 Khz5_5_5,
556 Khz11,
558 Khz22,
560 Khz44,
563}
564
565impl SoundRate {
566 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 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 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#[non_exhaustive]
601#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
602#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
603pub enum SoundSize {
604 Bits8,
606 Bits16,
608}
609
610impl SoundSize {
611 pub fn to_code(self) -> u8 {
613 match self {
614 Self::Bits8 => 0,
615 Self::Bits16 => 1,
616 }
617 }
618
619 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 pub fn bits(self) -> u8 {
630 match self {
631 Self::Bits8 => 8,
632 Self::Bits16 => 16,
633 }
634 }
635
636 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#[non_exhaustive]
649#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
650#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
651pub enum SoundType {
652 Mono,
654 Stereo,
656}
657
658impl SoundType {
659 pub fn to_code(self) -> u8 {
661 match self {
662 Self::Mono => 0,
663 Self::Stereo => 1,
664 }
665 }
666
667 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 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#[non_exhaustive]
689#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
690#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
691pub enum AacPacketType {
692 SequenceHeader,
694 Raw,
696 Unknown(u8),
698}
699
700impl AacPacketType {
701 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 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 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#[non_exhaustive]
739#[derive(Clone, Copy, PartialEq, Eq)]
740#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
741pub struct AudioTagHeader<'a> {
742 pub sound_format: SoundFormat,
744 pub sound_rate: SoundRate,
746 pub sound_size: SoundSize,
748 pub sound_type: SoundType,
750 pub aac_packet_type: Option<AacPacketType>,
752 pub data: &'a [u8],
754}
755
756impl<'a> AudioTagHeader<'a> {
757 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 #[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 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 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 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
919pub const ON_METADATA_VIDEO_CODEC_ID_AVC: f64 = 7.0;
923pub const ON_METADATA_AUDIO_CODEC_ID_AAC: f64 = 10.0;
925
926pub(crate) const META_HANDLER_NAME: &str = "onMetaData";
928pub const SET_DATA_FRAME: &str = "@setDataFrame";
932const META_DURATION: &str = "duration";
934const META_WIDTH: &str = "width";
936const META_HEIGHT: &str = "height";
938const META_FRAME_RATE: &str = "framerate";
940const META_VIDEO_CODEC_ID: &str = "videocodecid";
942const META_AUDIO_SAMPLE_RATE: &str = "audiosamplerate";
944const META_AUDIO_SAMPLE_SIZE: &str = "audiosamplesize";
946const META_STEREO: &str = "stereo";
948const META_AUDIO_CODEC_ID: &str = "audiocodecid";
950const META_FILE_SIZE: &str = "filesize";
952const META_ENCODER: &str = "encoder";
954
955#[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 pub fn new(tracks: &[PublishTrack], duration: Option<f64>) -> BodyResult<Self> {
1001 Self::with_session(tracks, duration, None, None)
1002 }
1003
1004 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 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 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 #[must_use]
1111 pub const fn duration(&self) -> Option<f64> {
1112 self.duration
1113 }
1114
1115 #[must_use]
1117 pub const fn width(&self) -> Option<u16> {
1118 self.width
1119 }
1120
1121 #[must_use]
1123 pub const fn height(&self) -> Option<u16> {
1124 self.height
1125 }
1126
1127 #[must_use]
1129 pub const fn frame_rate(&self) -> Option<f64> {
1130 self.frame_rate
1131 }
1132
1133 #[must_use]
1135 pub const fn video_codec_id(&self) -> Option<f64> {
1136 self.video_codec_id
1137 }
1138
1139 #[must_use]
1141 pub const fn audio_sample_rate(&self) -> Option<u32> {
1142 self.audio_sample_rate
1143 }
1144
1145 #[must_use]
1147 pub const fn audio_sample_size(&self) -> Option<u16> {
1148 self.audio_sample_size
1149 }
1150
1151 #[must_use]
1153 pub const fn stereo(&self) -> Option<bool> {
1154 self.stereo
1155 }
1156
1157 #[must_use]
1159 pub const fn audio_codec_id(&self) -> Option<f64> {
1160 self.audio_codec_id
1161 }
1162
1163 #[must_use]
1165 pub const fn file_size(&self) -> Option<u64> {
1166 self.file_size
1167 }
1168
1169 #[must_use]
1171 pub fn encoder(&self) -> Option<&str> {
1172 self.encoder.as_deref()
1173 }
1174
1175 #[must_use]
1180 pub fn raw_body(&self) -> &[u8] {
1181 &self.body
1182 }
1183
1184 #[must_use]
1186 pub fn properties(&self) -> &[(String, Amf0Value)] {
1187 &self.properties
1188 }
1189
1190 #[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 #[must_use]
1205 pub fn parse(body: &[u8], limits: Amf0Limits) -> Option<Self> {
1206 Self::parse_body(body, false, limits).ok()
1207 }
1208
1209 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 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 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 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 pub fn publish_body(&self) -> BodyResult<Vec<u8>> {
1329 set_data_frame_body(&self.properties)
1330 }
1331}
1332
1333pub(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 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
1386fn 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
1396fn 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
1404fn whole_number(value: f64) -> Option<u64> {
1410 const LOWEST: f64 = 0.0;
1411 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#[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;