use alloc::borrow::ToOwned;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use broadcast_core::error::BufferTooShort;
use broadcast_core::len::fit_mask;
use broadcast_core::wire::{Reader, Writer};
use broadcast_core::{Parse, Serialize};
use crate::RtmpError;
use crate::amf0::{Amf0Limits, Amf0Value, amf0_parse_values_with};
use crate::flv::PublishTrack;
type BodyResult<T> = core::result::Result<T, RtmpError>;
const FRAME_TYPE_SHIFT: u32 = 4;
const FRAME_TYPE_MASK: u8 = 0x0F;
const CODEC_ID_MASK: u8 = 0x0F;
const SOUND_FORMAT_MASK: u8 = 0x0F;
const SOUND_FORMAT_SHIFT: u32 = 4;
const SOUND_RATE_SHIFT: u32 = 2;
const SOUND_SIZE_SHIFT: u32 = 1;
const SOUND_TYPE_MASK: u8 = 0x01;
const SOUND_FIELD_MASK: u8 = 0x03;
pub const VIDEO_TAG_HEADER_LEN: usize = 1;
const AVC_PACKET_TYPE_AT: usize = 1;
const AVC_PACKET_TYPE_LEN: usize = 1;
const COMPOSITION_TIME_AT: usize = AVC_PACKET_TYPE_AT + AVC_PACKET_TYPE_LEN;
const COMPOSITION_TIME_LEN: usize = 3;
pub const AVC_PACKET_DATA_OFFSET: usize = COMPOSITION_TIME_AT + COMPOSITION_TIME_LEN;
pub const COMPOSITION_TIME_MIN: i32 = -(1 << 23);
pub const COMPOSITION_TIME_MAX: i32 = (1 << 23) - 1;
pub const AUDIO_TAG_HEADER_LEN: usize = 1;
const AAC_PACKET_TYPE_AT: usize = AUDIO_TAG_HEADER_LEN;
pub const AAC_PACKET_DATA_OFFSET: usize = AAC_PACKET_TYPE_AT + 1;
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum FrameType {
Keyframe,
Inter,
DisposableInter,
GeneratedKeyframe,
VideoInfo,
Reserved(u8),
Unknown(u8),
}
impl FrameType {
pub fn to_code(self) -> u8 {
match self {
Self::Keyframe => 1,
Self::Inter => 2,
Self::DisposableInter => 3,
Self::GeneratedKeyframe => 4,
Self::VideoInfo => 5,
Self::Reserved(code) | Self::Unknown(code) => code,
}
}
pub fn from_code(code: u8) -> Self {
match code {
1 => Self::Keyframe,
2 => Self::Inter,
3 => Self::DisposableInter,
4 => Self::GeneratedKeyframe,
5 => Self::VideoInfo,
6 | 7 => Self::Reserved(code),
other => Self::Unknown(other),
}
}
#[must_use]
pub fn is_keyframe(self) -> bool {
matches!(self, Self::Keyframe | Self::GeneratedKeyframe)
}
pub fn name(&self) -> &'static str {
match self {
Self::Keyframe => "keyframe",
Self::Inter => "inter frame",
Self::DisposableInter => "disposable inter frame",
Self::GeneratedKeyframe => "generated keyframe",
Self::VideoInfo => "video info/command frame",
Self::Reserved(_) => "reserved",
Self::Unknown(_) => "unknown",
}
}
}
broadcast_core::impl_spec_display!(FrameType, Reserved, Unknown);
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum CodecId {
SorensonH263,
ScreenVideo,
On2Vp6,
On2Vp6Alpha,
ScreenVideoV2,
Avc,
Hevc,
Reserved(u8),
Unknown(u8),
}
impl CodecId {
pub fn to_code(self) -> u8 {
match self {
Self::SorensonH263 => 2,
Self::ScreenVideo => 3,
Self::On2Vp6 => 4,
Self::On2Vp6Alpha => 5,
Self::ScreenVideoV2 => 6,
Self::Avc => 7,
Self::Hevc => 12,
Self::Reserved(code) | Self::Unknown(code) => code,
}
}
pub fn from_code(code: u8) -> Self {
match code {
2 => Self::SorensonH263,
3 => Self::ScreenVideo,
4 => Self::On2Vp6,
5 => Self::On2Vp6Alpha,
6 => Self::ScreenVideoV2,
7 => Self::Avc,
12 => Self::Hevc,
10 | 11 => Self::Unknown(code),
other => Self::Reserved(other),
}
}
pub fn name(&self) -> &'static str {
match self {
Self::SorensonH263 => "Sorenson H.263",
Self::ScreenVideo => "Screen video",
Self::On2Vp6 => "On2 VP6",
Self::On2Vp6Alpha => "On2 VP6 with alpha channel",
Self::ScreenVideoV2 => "Screen video version 2",
Self::Avc => "AVC",
Self::Hevc => "HEVC",
Self::Reserved(_) => "reserved",
Self::Unknown(_) => "unknown",
}
}
}
broadcast_core::impl_spec_display!(CodecId, Reserved, Unknown);
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AvcPacketType {
SequenceHeader,
Nalu,
EndOfSequence,
Unknown(u8),
}
impl AvcPacketType {
pub fn to_code(self) -> u8 {
match self {
Self::SequenceHeader => 0,
Self::Nalu => 1,
Self::EndOfSequence => 2,
Self::Unknown(code) => code,
}
}
pub fn from_code(code: u8) -> Self {
match code {
0 => Self::SequenceHeader,
1 => Self::Nalu,
2 => Self::EndOfSequence,
other => Self::Unknown(other),
}
}
pub fn name(&self) -> &'static str {
match self {
Self::SequenceHeader => "sequence header",
Self::Nalu => "NALU",
Self::EndOfSequence => "end of sequence",
Self::Unknown(_) => "unknown",
}
}
}
broadcast_core::impl_spec_display!(AvcPacketType, Unknown);
#[non_exhaustive]
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct VideoTagHeader<'a> {
pub frame_type: FrameType,
pub codec_id: CodecId,
pub avc_packet_type: Option<AvcPacketType>,
pub composition_time: Option<i32>,
pub data: &'a [u8],
}
impl<'a> VideoTagHeader<'a> {
pub fn new(
frame_type: FrameType,
codec_id: CodecId,
avc_packet_type: Option<AvcPacketType>,
composition_time: Option<i32>,
) -> Self {
Self {
frame_type,
codec_id,
avc_packet_type,
composition_time,
data: &[],
}
}
#[must_use]
pub fn has_stray_composition_time(&self) -> bool {
self.codec_id != CodecId::Avc && self.composition_time.is_some()
}
fn avc_packet_type(&self) -> Option<AvcPacketType> {
(self.codec_id == CodecId::Avc)
.then_some(self.avc_packet_type)
.flatten()
}
fn composition_time(&self) -> i32 {
if self.avc_packet_type().is_some() {
self.composition_time.unwrap_or(0)
} else {
0
}
}
pub fn to_bytes(&self) -> BodyResult<Vec<u8>> {
let len = self.serialized_len();
let mut out = alloc::vec![0u8; len];
let written = self.serialize_into(&mut out)?;
debug_assert_eq!(written, len);
Ok(out)
}
}
impl<'a> Parse<'a> for VideoTagHeader<'a> {
type Error = RtmpError;
fn parse(bytes: &'a [u8]) -> BodyResult<Self> {
let first = *bytes
.first()
.ok_or(RtmpError::BufferTooShort(BufferTooShort::new(
VIDEO_TAG_HEADER_LEN,
bytes.len(),
"FLV VideoTagHeader",
)))?;
let frame_type = FrameType::from_code(first >> FRAME_TYPE_SHIFT);
let codec_id = CodecId::from_code(first & CODEC_ID_MASK);
if codec_id != CodecId::Avc {
return Ok(Self {
frame_type,
codec_id,
avc_packet_type: None,
composition_time: None,
data: &bytes[VIDEO_TAG_HEADER_LEN..],
});
}
if bytes.len() < AVC_PACKET_DATA_OFFSET {
return Err(RtmpError::BufferTooShort(BufferTooShort::new(
AVC_PACKET_DATA_OFFSET,
bytes.len(),
"FLV AVCVIDEOPACKET",
)));
}
Ok(Self {
frame_type,
codec_id,
avc_packet_type: Some(AvcPacketType::from_code(bytes[AVC_PACKET_TYPE_AT])),
composition_time: Some(
Reader::at(bytes, COMPOSITION_TIME_AT).i24("FLV AVCVIDEOPACKET")?,
),
data: &bytes[AVC_PACKET_DATA_OFFSET..],
})
}
}
impl Serialize for VideoTagHeader<'_> {
type Error = RtmpError;
fn serialized_len(&self) -> usize {
let mut len = VIDEO_TAG_HEADER_LEN;
if self.codec_id == CodecId::Avc && self.avc_packet_type.is_some() {
len += AVC_PACKET_DATA_OFFSET - VIDEO_TAG_HEADER_LEN;
}
len + self.data.len()
}
fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
if self.has_stray_composition_time() {
return Err(RtmpError::Malformed {
what: "FLV CompositionTime for a codec without AVCVIDEOPACKET",
});
}
let len = self.serialized_len();
if buf.len() < len {
return Err(RtmpError::OutputBufferTooSmall(
broadcast_core::error::OutputBufferTooSmall::new(len, buf.len(), "VideoTagHeader"),
));
}
let mut w = Writer::new(buf);
let frame_type = fit_mask(self.frame_type.to_code(), FRAME_TYPE_MASK, "FrameType")?;
let codec_id = fit_mask(self.codec_id.to_code(), CODEC_ID_MASK, "CodecID")?;
w.u8(
(frame_type << FRAME_TYPE_SHIFT) | codec_id,
"FLV video tag frame type",
)?;
if let Some(packet_type) = self.avc_packet_type() {
w.u8(packet_type.to_code(), "FLV video tag packet type")?;
w.i24::<RtmpError>(self.composition_time(), "FLV CompositionTime")?;
}
w.bytes(self.data, "FLV video tag data")?;
Ok(len)
}
}
impl core::fmt::Debug for VideoTagHeader<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("VideoTagHeader")
.field("frame_type", &self.frame_type)
.field("codec_id", &self.codec_id)
.field("avc_packet_type", &self.avc_packet_type)
.field("composition_time", &self.composition_time)
.field("data_len", &self.data.len())
.finish()
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SoundFormat {
LinearPcmPlatformEndian,
Adpcm,
Mp3,
LinearPcmLittleEndian,
Nellymoser16KhzMono,
Nellymoser8KhzMono,
Nellymoser,
G711ALaw,
G711MuLaw,
Aac,
Speex,
Mp3_8Khz,
DeviceSpecific,
Reserved(u8),
Unknown(u8),
}
impl SoundFormat {
pub fn to_code(self) -> u8 {
match self {
Self::LinearPcmPlatformEndian => 0,
Self::Adpcm => 1,
Self::Mp3 => 2,
Self::LinearPcmLittleEndian => 3,
Self::Nellymoser16KhzMono => 4,
Self::Nellymoser8KhzMono => 5,
Self::Nellymoser => 6,
Self::G711ALaw => 7,
Self::G711MuLaw => 8,
Self::Aac => 10,
Self::Speex => 11,
Self::Mp3_8Khz => 14,
Self::DeviceSpecific => 15,
Self::Reserved(code) | Self::Unknown(code) => code,
}
}
pub fn from_code(code: u8) -> Self {
match code {
0 => Self::LinearPcmPlatformEndian,
1 => Self::Adpcm,
2 => Self::Mp3,
3 => Self::LinearPcmLittleEndian,
4 => Self::Nellymoser16KhzMono,
5 => Self::Nellymoser8KhzMono,
6 => Self::Nellymoser,
7 => Self::G711ALaw,
8 => Self::G711MuLaw,
10 => Self::Aac,
11 => Self::Speex,
14 => Self::Mp3_8Khz,
15 => Self::DeviceSpecific,
12 | 13 => Self::Unknown(code),
other => Self::Reserved(other),
}
}
pub fn name(&self) -> &'static str {
match self {
Self::LinearPcmPlatformEndian => "linear PCM, platform endian",
Self::Adpcm => "ADPCM",
Self::Mp3 => "MP3",
Self::LinearPcmLittleEndian => "linear PCM, little endian",
Self::Nellymoser16KhzMono => "Nellymoser 16 kHz mono",
Self::Nellymoser8KhzMono => "Nellymoser 8 kHz mono",
Self::Nellymoser => "Nellymoser",
Self::G711ALaw => "G.711 A-law",
Self::G711MuLaw => "G.711 mu-law",
Self::Aac => "AAC",
Self::Speex => "Speex",
Self::Mp3_8Khz => "MP3 8 kHz",
Self::DeviceSpecific => "device-specific sound",
Self::Reserved(_) => "reserved",
Self::Unknown(_) => "unknown",
}
}
}
broadcast_core::impl_spec_display!(SoundFormat, Reserved, Unknown);
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SoundRate {
Khz5_5_5,
Khz11,
Khz22,
Khz44,
}
impl SoundRate {
pub fn to_code(self) -> u8 {
match self {
Self::Khz5_5_5 => 0,
Self::Khz11 => 1,
Self::Khz22 => 2,
Self::Khz44 => 3,
}
}
pub fn from_code(code: u8) -> Self {
match code & SOUND_FIELD_MASK {
0 => Self::Khz5_5_5,
1 => Self::Khz11,
2 => Self::Khz22,
_ => Self::Khz44,
}
}
pub fn name(&self) -> &'static str {
match self {
Self::Khz5_5_5 => "5.5 kHz",
Self::Khz11 => "11 kHz",
Self::Khz22 => "22 kHz",
Self::Khz44 => "44 kHz",
}
}
}
broadcast_core::impl_spec_display!(SoundRate);
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SoundSize {
Bits8,
Bits16,
}
impl SoundSize {
pub fn to_code(self) -> u8 {
match self {
Self::Bits8 => 0,
Self::Bits16 => 1,
}
}
pub fn from_code(code: u8) -> Self {
if code & SOUND_TYPE_MASK == 0 {
Self::Bits8
} else {
Self::Bits16
}
}
pub fn bits(self) -> u8 {
match self {
Self::Bits8 => 8,
Self::Bits16 => 16,
}
}
pub fn name(&self) -> &'static str {
match self {
Self::Bits8 => "8-bit",
Self::Bits16 => "16-bit",
}
}
}
broadcast_core::impl_spec_display!(SoundSize);
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum SoundType {
Mono,
Stereo,
}
impl SoundType {
pub fn to_code(self) -> u8 {
match self {
Self::Mono => 0,
Self::Stereo => 1,
}
}
pub fn from_code(code: u8) -> Self {
if code & SOUND_TYPE_MASK == 0 {
Self::Mono
} else {
Self::Stereo
}
}
pub fn name(&self) -> &'static str {
match self {
Self::Mono => "mono",
Self::Stereo => "stereo",
}
}
}
broadcast_core::impl_spec_display!(SoundType);
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum AacPacketType {
SequenceHeader,
Raw,
Unknown(u8),
}
impl AacPacketType {
pub fn to_code(self) -> u8 {
match self {
Self::SequenceHeader => 0,
Self::Raw => 1,
Self::Unknown(code) => code,
}
}
pub fn from_code(code: u8) -> Self {
match code {
0 => Self::SequenceHeader,
1 => Self::Raw,
other => Self::Unknown(other),
}
}
pub fn name(&self) -> &'static str {
match self {
Self::SequenceHeader => "sequence header",
Self::Raw => "raw",
Self::Unknown(_) => "unknown",
}
}
}
broadcast_core::impl_spec_display!(AacPacketType, Unknown);
#[non_exhaustive]
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AudioTagHeader<'a> {
pub sound_format: SoundFormat,
pub sound_rate: SoundRate,
pub sound_size: SoundSize,
pub sound_type: SoundType,
pub aac_packet_type: Option<AacPacketType>,
pub data: &'a [u8],
}
impl<'a> AudioTagHeader<'a> {
pub fn new(
sound_format: SoundFormat,
sound_rate: SoundRate,
sound_size: SoundSize,
sound_type: SoundType,
aac_packet_type: Option<AacPacketType>,
) -> Self {
Self {
sound_format,
sound_rate,
sound_size,
sound_type,
aac_packet_type,
data: &[],
}
}
#[must_use]
pub fn sound_type_for_channels(channel_count: u16) -> SoundType {
const MONO_CHANNELS: u16 = 1;
if channel_count <= MONO_CHANNELS {
SoundType::Mono
} else {
SoundType::Stereo
}
}
fn aac_packet_type(&self) -> Option<AacPacketType> {
if self.sound_format == SoundFormat::Aac {
self.aac_packet_type
} else {
None
}
}
pub fn to_bytes(&self) -> BodyResult<Vec<u8>> {
if self.sound_format != SoundFormat::Aac && self.aac_packet_type.is_some() {
return Err(RtmpError::Malformed {
what: "FLV AACPacketType for a non-AAC SoundFormat",
});
}
let len = self.serialized_len();
let mut out = alloc::vec![0u8; len];
let written = self.serialize_into(&mut out)?;
debug_assert_eq!(written, len);
Ok(out)
}
pub fn first_byte(&self) -> BodyResult<u8> {
let format = fit_mask(
self.sound_format.to_code(),
SOUND_FORMAT_MASK,
"SoundFormat",
)?;
let rate = fit_mask(self.sound_rate.to_code(), SOUND_FIELD_MASK, "SoundRate")?;
let size = fit_mask(self.sound_size.to_code(), SOUND_TYPE_MASK, "SoundSize")?;
let kind = fit_mask(self.sound_type.to_code(), SOUND_TYPE_MASK, "SoundType")?;
Ok((format << SOUND_FORMAT_SHIFT)
| (rate << SOUND_RATE_SHIFT)
| (size << SOUND_SIZE_SHIFT)
| kind)
}
}
impl<'a> Parse<'a> for AudioTagHeader<'a> {
type Error = RtmpError;
fn parse(bytes: &'a [u8]) -> BodyResult<Self> {
let first = *bytes
.first()
.ok_or(RtmpError::BufferTooShort(BufferTooShort::new(
AUDIO_TAG_HEADER_LEN,
bytes.len(),
"FLV AudioTagHeader",
)))?;
let sound_format = SoundFormat::from_code(first >> SOUND_FORMAT_SHIFT);
let prefix = Self {
sound_format,
sound_rate: SoundRate::from_code(first >> SOUND_RATE_SHIFT),
sound_size: SoundSize::from_code(first >> SOUND_SIZE_SHIFT),
sound_type: SoundType::from_code(first),
aac_packet_type: None,
data: &[],
};
if sound_format != SoundFormat::Aac {
return Ok(Self {
data: &bytes[AUDIO_TAG_HEADER_LEN..],
..prefix
});
}
let packet_type = *bytes
.get(AAC_PACKET_TYPE_AT)
.ok_or(RtmpError::BufferTooShort(BufferTooShort::new(
AAC_PACKET_DATA_OFFSET,
bytes.len(),
"FLV AACAUDIODATA",
)))?;
Ok(Self {
aac_packet_type: Some(AacPacketType::from_code(packet_type)),
data: &bytes[AAC_PACKET_DATA_OFFSET..],
..prefix
})
}
}
impl Serialize for AudioTagHeader<'_> {
type Error = RtmpError;
fn serialized_len(&self) -> usize {
let mut len = AUDIO_TAG_HEADER_LEN;
if self.aac_packet_type().is_some() {
len += AAC_PACKET_DATA_OFFSET - AUDIO_TAG_HEADER_LEN;
}
len + self.data.len()
}
fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
let len = self.serialized_len();
if buf.len() < len {
return Err(RtmpError::OutputBufferTooSmall(
broadcast_core::error::OutputBufferTooSmall::new(len, buf.len(), "AudioTagHeader"),
));
}
buf[0] = self.first_byte()?;
let mut offset = AUDIO_TAG_HEADER_LEN;
if let Some(packet_type) = self.aac_packet_type() {
buf[AAC_PACKET_TYPE_AT] = packet_type.to_code();
offset = AAC_PACKET_DATA_OFFSET;
}
buf[offset..len].copy_from_slice(self.data);
Ok(len)
}
}
impl core::fmt::Debug for AudioTagHeader<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("AudioTagHeader")
.field("sound_format", &self.sound_format)
.field("sound_rate", &self.sound_rate)
.field("sound_size", &self.sound_size)
.field("sound_type", &self.sound_type)
.field("aac_packet_type", &self.aac_packet_type)
.field("data_len", &self.data.len())
.finish()
}
}
pub const ON_METADATA_VIDEO_CODEC_ID_AVC: f64 = 7.0;
pub const ON_METADATA_AUDIO_CODEC_ID_AAC: f64 = 10.0;
pub(crate) const META_HANDLER_NAME: &str = "onMetaData";
pub const SET_DATA_FRAME: &str = "@setDataFrame";
const META_DURATION: &str = "duration";
const META_WIDTH: &str = "width";
const META_HEIGHT: &str = "height";
const META_FRAME_RATE: &str = "framerate";
const META_VIDEO_CODEC_ID: &str = "videocodecid";
const META_AUDIO_SAMPLE_RATE: &str = "audiosamplerate";
const META_AUDIO_SAMPLE_SIZE: &str = "audiosamplesize";
const META_STEREO: &str = "stereo";
const META_AUDIO_CODEC_ID: &str = "audiocodecid";
const META_FILE_SIZE: &str = "filesize";
const META_ENCODER: &str = "encoder";
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct OnMetadata {
body: Vec<u8>,
properties: Vec<(String, Amf0Value)>,
duration: Option<f64>,
width: Option<u16>,
height: Option<u16>,
frame_rate: Option<f64>,
video_codec_id: Option<f64>,
audio_sample_rate: Option<u32>,
audio_sample_size: Option<u16>,
stereo: Option<bool>,
audio_codec_id: Option<f64>,
file_size: Option<u64>,
encoder: Option<String>,
}
impl OnMetadata {
pub fn new(tracks: &[PublishTrack], duration: Option<f64>) -> BodyResult<Self> {
Self::with_session(tracks, duration, None, None)
}
pub fn with_session(
tracks: &[PublishTrack],
duration: Option<f64>,
source: Option<(&[u8], Amf0Limits)>,
file_size: Option<u64>,
) -> BodyResult<Self> {
let metadata = Self::from_tracks(tracks, duration)?;
if let Some((source, limits)) = source {
let mut reference = Self::parse_body(source, true, limits)?;
if file_size.is_some() {
reference.file_size = file_size;
}
return Ok(reference);
}
let Some(file_size) = file_size else {
return Ok(metadata);
};
let mut properties = metadata.properties;
properties.push((
META_FILE_SIZE.to_string(),
Amf0Value::Number(file_size as f64),
));
let stated = Self::from_properties(&[], properties);
let body = stated.script_body()?;
Ok(Self::from_properties(&body, stated.properties))
}
fn from_tracks(tracks: &[PublishTrack], duration: Option<f64>) -> BodyResult<Self> {
let video = tracks.iter().find_map(|track| match track {
PublishTrack::Video { width, height, .. } => Some((*width, *height)),
PublishTrack::Audio { .. } => None,
});
let audio = tracks.iter().find_map(|track| match track {
PublishTrack::Audio {
sample_rate,
channel_count,
..
} => Some((*sample_rate, *channel_count)),
PublishTrack::Video { .. } => None,
});
if video.is_none() && audio.is_none() {
return Err(RtmpError::Malformed {
what: "onMetaData without an AVC video or AAC audio track",
});
}
let mut properties: Vec<(String, Amf0Value)> = Vec::new();
if let Some(duration) = duration {
properties.push((META_DURATION.to_string(), Amf0Value::Number(duration)));
}
if let Some((width, height)) = video {
properties.push((META_WIDTH.to_string(), Amf0Value::Number(f64::from(width))));
properties.push((
META_HEIGHT.to_string(),
Amf0Value::Number(f64::from(height)),
));
properties.push((
META_VIDEO_CODEC_ID.to_string(),
Amf0Value::Number(ON_METADATA_VIDEO_CODEC_ID_AVC),
));
}
if let Some((sample_rate, channel_count)) = audio {
properties.push((
META_AUDIO_CODEC_ID.to_string(),
Amf0Value::Number(ON_METADATA_AUDIO_CODEC_ID_AAC),
));
properties.push((
META_AUDIO_SAMPLE_RATE.to_string(),
Amf0Value::Number(f64::from(sample_rate)),
));
properties.push((
META_STEREO.to_string(),
Amf0Value::Boolean(
AudioTagHeader::sound_type_for_channels(channel_count) == SoundType::Stereo,
),
));
}
Ok(Self::from_properties(&[], properties))
}
pub fn serialize_into_vec(&self) -> BodyResult<Vec<u8>> {
let mut out = alloc::vec![0u8; self.serialized_len()];
let written = self.serialize_into(&mut out)?;
out.truncate(written);
Ok(out)
}
#[must_use]
pub const fn duration(&self) -> Option<f64> {
self.duration
}
#[must_use]
pub const fn width(&self) -> Option<u16> {
self.width
}
#[must_use]
pub const fn height(&self) -> Option<u16> {
self.height
}
#[must_use]
pub const fn frame_rate(&self) -> Option<f64> {
self.frame_rate
}
#[must_use]
pub const fn video_codec_id(&self) -> Option<f64> {
self.video_codec_id
}
#[must_use]
pub const fn audio_sample_rate(&self) -> Option<u32> {
self.audio_sample_rate
}
#[must_use]
pub const fn audio_sample_size(&self) -> Option<u16> {
self.audio_sample_size
}
#[must_use]
pub const fn stereo(&self) -> Option<bool> {
self.stereo
}
#[must_use]
pub const fn audio_codec_id(&self) -> Option<f64> {
self.audio_codec_id
}
#[must_use]
pub const fn file_size(&self) -> Option<u64> {
self.file_size
}
#[must_use]
pub fn encoder(&self) -> Option<&str> {
self.encoder.as_deref()
}
#[must_use]
pub fn raw_body(&self) -> &[u8] {
&self.body
}
#[must_use]
pub fn properties(&self) -> &[(String, Amf0Value)] {
&self.properties
}
#[must_use]
pub fn property(&self, name: &str) -> Option<&Amf0Value> {
self.properties
.iter()
.find(|(key, _)| key == name)
.map(|(_, value)| value)
}
#[must_use]
pub fn parse(body: &[u8], limits: Amf0Limits) -> Option<Self> {
Self::parse_body(body, false, limits).ok()
}
pub fn parse_body(body: &[u8], retain_raw: bool, limits: Amf0Limits) -> BodyResult<Self> {
Self::parse_body_with_diagnostics(body, retain_raw, limits).map(|(metadata, _)| metadata)
}
pub fn parse_body_with_diagnostics(
body: &[u8],
retain_raw: bool,
limits: Amf0Limits,
) -> BodyResult<(Self, Vec<broadcast_core::damage::Damage>)> {
let (values, diagnostics) = amf0_parse_values_with(body, limits)?;
let mut values = values.into_iter();
let handler = handler_name(values.next())?;
let handler = if handler == SET_DATA_FRAME {
handler_name(values.next())?
} else {
handler
};
if handler != META_HANDLER_NAME {
return Err(RtmpError::Malformed {
what: "FLV onMetaData handler name",
});
}
let properties = match values.next() {
Some(Amf0Value::EcmaArray(properties) | Amf0Value::Object(properties)) => properties,
_ => {
return Err(RtmpError::Malformed {
what: "FLV onMetaData property object",
});
}
};
let retained = if retain_raw { body } else { &[] };
Ok((Self::from_properties(retained, properties), diagnostics))
}
fn from_properties(body: &[u8], properties: Vec<(String, Amf0Value)>) -> Self {
let number = |name: &str| match find_property(&properties, name) {
Some(Amf0Value::Number(value)) => Some(*value),
_ => None,
};
let whole16 = |name: &str| {
number(name)
.and_then(whole_number)
.and_then(|n| u16::try_from(n).ok())
};
let whole32 = |name: &str| {
number(name)
.and_then(whole_number)
.and_then(|n| u32::try_from(n).ok())
};
let whole64 = |name: &str| number(name).and_then(whole_number);
let encoder = match find_property(&properties, META_ENCODER) {
Some(Amf0Value::String(encoder) | Amf0Value::LongString(encoder)) => {
Some(encoder.clone())
}
_ => None,
};
Self {
body: body.to_vec(),
duration: number(META_DURATION),
width: whole16(META_WIDTH),
height: whole16(META_HEIGHT),
frame_rate: number(META_FRAME_RATE),
video_codec_id: number(META_VIDEO_CODEC_ID),
audio_sample_rate: whole32(META_AUDIO_SAMPLE_RATE),
audio_sample_size: whole16(META_AUDIO_SAMPLE_SIZE),
stereo: match find_property(&properties, META_STEREO) {
Some(Amf0Value::Boolean(stereo)) => Some(*stereo),
_ => None,
},
audio_codec_id: number(META_AUDIO_CODEC_ID),
file_size: whole64(META_FILE_SIZE),
encoder,
properties,
}
}
}
impl OnMetadata {
pub fn script_body(&self) -> BodyResult<Vec<u8>> {
let name = Amf0Value::String(META_HANDLER_NAME.to_string());
let array = Amf0Value::EcmaArray(self.properties.clone());
let len = name.serialized_len() + array.serialized_len();
let mut body = alloc::vec![0u8; len];
let written = name.serialize_into(&mut body)?;
let rest = written + array.serialize_into(&mut body[written..])?;
debug_assert_eq!(rest, len);
Ok(body)
}
}
impl OnMetadata {
pub fn publish_body(&self) -> BodyResult<Vec<u8>> {
set_data_frame_body(&self.properties)
}
}
pub(crate) fn set_data_frame_body(metadata: &[(String, Amf0Value)]) -> BodyResult<Vec<u8>> {
let mut payload = Amf0Value::String(SET_DATA_FRAME.to_string()).try_to_bytes()?;
payload.extend(Amf0Value::String(META_HANDLER_NAME.to_string()).try_to_bytes()?);
payload.extend(Amf0Value::EcmaArray(metadata.to_vec()).try_to_bytes()?);
Ok(payload)
}
impl Serialize for OnMetadata {
type Error = RtmpError;
fn try_to_bytes(&self) -> core::result::Result<Vec<u8>, Self::Error> {
let mut out = alloc::vec![0u8; self.serialized_len()];
let written = self.serialize_into(&mut out)?;
out.truncate(written);
Ok(out)
}
fn serialized_len(&self) -> usize {
if !self.body.is_empty() {
return strip_set_data_frame(&self.body).len();
}
let name = Amf0Value::String(META_HANDLER_NAME.to_string());
name.serialized_len() + Amf0Value::EcmaArray(self.properties.clone()).serialized_len()
}
fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
let len = self.serialized_len();
if buf.len() < len {
return Err(RtmpError::OutputBufferTooSmall(
broadcast_core::error::OutputBufferTooSmall::new(len, buf.len(), "OnMetadata"),
));
}
if !self.body.is_empty() {
buf[..len].copy_from_slice(strip_set_data_frame(&self.body));
return Ok(len);
}
let name = Amf0Value::String(META_HANDLER_NAME.to_string());
let written = name.serialize_into(buf)?;
let array = Amf0Value::EcmaArray(self.properties.clone());
let rest = written + array.serialize_into(&mut buf[written..])?;
debug_assert_eq!(rest, len);
Ok(rest)
}
}
fn handler_name(value: Option<Amf0Value>) -> BodyResult<String> {
match value {
Some(Amf0Value::String(handler)) => Ok(handler),
_ => Err(RtmpError::Malformed {
what: "FLV onMetaData handler name",
}),
}
}
fn find_property<'a>(properties: &'a [(String, Amf0Value)], name: &str) -> Option<&'a Amf0Value> {
properties
.iter()
.find(|(key, _)| key == name)
.map(|(_, value)| value)
}
fn whole_number(value: f64) -> Option<u64> {
const LOWEST: f64 = 0.0;
if value < LOWEST || value > u64::MAX as f64 {
return None;
}
(value as u64 as f64 == value).then_some(value as u64)
}
#[must_use]
pub fn strip_set_data_frame(body: &[u8]) -> &[u8] {
let Ok(name) = Amf0Value::String(SET_DATA_FRAME.to_owned()).try_to_bytes() else {
return body;
};
body.strip_prefix(name.as_slice()).unwrap_or(body)
}
#[cfg(test)]
#[path = "tag_body_tests.rs"]
mod tests;