use broadcast_core::len::need_in;
use broadcast_core::wire::Reader;
use broadcast_core::{Parse, Serialize};
use core::time::Duration;
use crate::RtmpError;
use crate::chunk::Message;
use crate::ids::{ChunkStreamId, MessageStreamId, SequenceNumber, Timestamp};
use alloc::vec::Vec;
type Result<T> = core::result::Result<T, RtmpError>;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum MessageTypeId {
SetChunkSize,
Abort,
Acknowledgement,
UserControl,
WindowAckSize,
SetPeerBandwidth,
Audio,
Video,
DataAmf3,
CommandAmf3,
DataAmf0,
CommandAmf0,
Aggregate,
Other(u8),
}
impl MessageTypeId {
#[must_use]
pub fn from_u8(v: u8) -> Self {
match v {
1 => MessageTypeId::SetChunkSize,
2 => MessageTypeId::Abort,
3 => MessageTypeId::Acknowledgement,
4 => MessageTypeId::UserControl,
5 => MessageTypeId::WindowAckSize,
6 => MessageTypeId::SetPeerBandwidth,
8 => MessageTypeId::Audio,
9 => MessageTypeId::Video,
15 => MessageTypeId::DataAmf3,
17 => MessageTypeId::CommandAmf3,
18 => MessageTypeId::DataAmf0,
20 => MessageTypeId::CommandAmf0,
22 => MessageTypeId::Aggregate,
other => MessageTypeId::Other(other),
}
}
#[must_use]
pub fn to_u8(self) -> u8 {
match self {
MessageTypeId::SetChunkSize => 1,
MessageTypeId::Abort => 2,
MessageTypeId::Acknowledgement => 3,
MessageTypeId::UserControl => 4,
MessageTypeId::WindowAckSize => 5,
MessageTypeId::SetPeerBandwidth => 6,
MessageTypeId::Audio => 8,
MessageTypeId::Video => 9,
MessageTypeId::DataAmf3 => 15,
MessageTypeId::CommandAmf3 => 17,
MessageTypeId::DataAmf0 => 18,
MessageTypeId::CommandAmf0 => 20,
MessageTypeId::Aggregate => 22,
MessageTypeId::Other(v) => v,
}
}
#[must_use]
pub fn name(&self) -> &'static str {
match self {
MessageTypeId::SetChunkSize => "set chunk size",
MessageTypeId::Abort => "abort",
MessageTypeId::Acknowledgement => "acknowledgement",
MessageTypeId::UserControl => "user control",
MessageTypeId::WindowAckSize => "window acknowledgement size",
MessageTypeId::SetPeerBandwidth => "set peer bandwidth",
MessageTypeId::Audio => "audio",
MessageTypeId::Video => "video",
MessageTypeId::DataAmf3 => "data (AMF3)",
MessageTypeId::CommandAmf3 => "command (AMF3)",
MessageTypeId::DataAmf0 => "data (AMF0)",
MessageTypeId::CommandAmf0 => "command (AMF0)",
MessageTypeId::Aggregate => "aggregate",
MessageTypeId::Other(_) => "other",
}
}
}
impl From<u8> for MessageTypeId {
fn from(v: u8) -> Self {
MessageTypeId::from_u8(v)
}
}
impl From<MessageTypeId> for u8 {
fn from(id: MessageTypeId) -> Self {
id.to_u8()
}
}
broadcast_core::impl_spec_display!(MessageTypeId, Other);
pub const CONTROL_CHUNK_STREAM_ID: ChunkStreamId = ChunkStreamId::new(2);
pub const CONTROL_MESSAGE_STREAM_ID: MessageStreamId = MessageStreamId::new(0);
const CONTROL_FIELD_LEN: usize = core::mem::size_of::<u32>();
const SET_PEER_BANDWIDTH_LEN: usize = CONTROL_FIELD_LEN + 1;
const SET_CHUNK_SIZE_RESERVED_MASK: u32 = 0x8000_0000;
const SET_CHUNK_SIZE_VALUE_MASK: u32 = 0x7FFF_FFFF;
const SET_BUFFER_LENGTH_LEN: usize = 2 * CONTROL_FIELD_LEN;
fn need_u32(bytes: &[u8], what: &'static str) -> Result<u32> {
Ok(Reader::new(bytes).u32(what)?)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum LimitType {
Hard,
Soft,
Dynamic,
}
impl LimitType {
#[must_use]
pub fn name(&self) -> &'static str {
match self {
LimitType::Hard => "hard",
LimitType::Soft => "soft",
LimitType::Dynamic => "dynamic",
}
}
pub const fn from_u8(v: u8) -> core::result::Result<Self, RtmpError> {
match v {
0 => Ok(LimitType::Hard),
1 => Ok(LimitType::Soft),
2 => Ok(LimitType::Dynamic),
value => Err(RtmpError::InvalidLimitType { value }),
}
}
#[must_use]
pub const fn to_u8(self) -> u8 {
match self {
LimitType::Hard => 0,
LimitType::Soft => 1,
LimitType::Dynamic => 2,
}
}
}
broadcast_core::impl_spec_display!(LimitType);
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ChunkSize(u32);
impl ChunkSize {
pub const MIN: ChunkSize = ChunkSize(1);
pub(crate) const fn new_unchecked(value: u32) -> Self {
Self(value)
}
pub const MAX: u32 = 0x7FFF_FFFF;
pub fn new(value: u32) -> Result<Self> {
Self::try_new(value)
}
pub const fn try_new(value: u32) -> Result<Self> {
if value == 0 || value & SET_CHUNK_SIZE_RESERVED_MASK != 0 {
return Err(RtmpError::chunk_size_out_of_range(value));
}
Ok(Self(value))
}
#[must_use]
pub const fn value(self) -> u32 {
self.0
}
}
impl TryFrom<u32> for ChunkSize {
type Error = RtmpError;
fn try_from(value: u32) -> Result<Self> {
Self::new(value)
}
}
impl From<ChunkSize> for u32 {
fn from(c: ChunkSize) -> Self {
c.0
}
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProtocolControl {
SetChunkSize(ChunkSize),
Abort {
chunk_stream_id: u32,
},
Acknowledgement(SequenceNumber),
WindowAckSize(u32),
SetPeerBandwidth {
ack_window_size: u32,
limit_type: LimitType,
},
}
impl ProtocolControl {
#[must_use]
pub fn name(&self) -> &'static str {
match self {
ProtocolControl::SetChunkSize(_) => "set chunk size",
ProtocolControl::Abort { .. } => "abort message",
ProtocolControl::Acknowledgement(_) => "acknowledgement",
ProtocolControl::WindowAckSize(_) => "window acknowledgement size",
ProtocolControl::SetPeerBandwidth { .. } => "set peer bandwidth",
}
}
#[must_use]
pub fn message_type_id(&self) -> MessageTypeId {
match self {
ProtocolControl::SetChunkSize(_) => MessageTypeId::SetChunkSize,
ProtocolControl::Abort { .. } => MessageTypeId::Abort,
ProtocolControl::Acknowledgement(_) => MessageTypeId::Acknowledgement,
ProtocolControl::WindowAckSize(_) => MessageTypeId::WindowAckSize,
ProtocolControl::SetPeerBandwidth { .. } => MessageTypeId::SetPeerBandwidth,
}
}
pub fn from_message(message: &Message) -> Result<Option<Self>> {
Self::from_payload(message.message_type_id, &message.payload)
}
pub fn from_payload(message_type_id: MessageTypeId, payload: &[u8]) -> Result<Option<Self>> {
match message_type_id {
MessageTypeId::SetChunkSize => {
let raw = need_u32(payload, "set chunk size payload")?;
if raw & SET_CHUNK_SIZE_RESERVED_MASK != 0 {
return Err(RtmpError::chunk_size_out_of_range(raw));
}
Ok(Some(ProtocolControl::SetChunkSize(ChunkSize::try_new(
raw & SET_CHUNK_SIZE_VALUE_MASK,
)?)))
}
MessageTypeId::Abort => {
let chunk_stream_id = need_u32(payload, "abort message payload")?;
Ok(Some(ProtocolControl::Abort { chunk_stream_id }))
}
MessageTypeId::Acknowledgement => {
let sequence_number = need_u32(payload, "acknowledgement payload")?;
Ok(Some(ProtocolControl::Acknowledgement(SequenceNumber::new(
sequence_number,
))))
}
MessageTypeId::WindowAckSize => {
let window = need_u32(payload, "window acknowledgement size payload")?;
Ok(Some(ProtocolControl::WindowAckSize(window)))
}
MessageTypeId::SetPeerBandwidth => {
need_in(
payload,
SET_PEER_BANDWIDTH_LEN,
"set peer bandwidth payload",
)?;
let ack_window_size = Reader::new(payload).u32("set peer bandwidth payload")?;
let limit_type = LimitType::from_u8(payload[CONTROL_FIELD_LEN])?;
Ok(Some(ProtocolControl::SetPeerBandwidth {
ack_window_size,
limit_type,
}))
}
_ => Ok(None),
}
}
#[must_use]
pub fn to_bytes(&self) -> Vec<u8> {
let mut buf = alloc::vec![0u8; self.serialized_len()];
match *self {
ProtocolControl::SetChunkSize(size) => {
buf[0..CONTROL_FIELD_LEN].copy_from_slice(&size.value().to_be_bytes());
}
ProtocolControl::Abort { chunk_stream_id } => {
buf[0..CONTROL_FIELD_LEN].copy_from_slice(&chunk_stream_id.to_be_bytes());
}
ProtocolControl::Acknowledgement(sequence_number) => {
buf[0..CONTROL_FIELD_LEN].copy_from_slice(&sequence_number.get().to_be_bytes());
}
ProtocolControl::WindowAckSize(window) => {
buf[0..CONTROL_FIELD_LEN].copy_from_slice(&window.to_be_bytes());
}
ProtocolControl::SetPeerBandwidth {
ack_window_size,
limit_type,
} => {
buf[0..CONTROL_FIELD_LEN].copy_from_slice(&ack_window_size.to_be_bytes());
buf[CONTROL_FIELD_LEN] = limit_type.to_u8();
}
}
buf
}
#[must_use]
pub fn to_message(&self) -> Message {
let payload = self.to_bytes();
Message {
chunk_stream_id: CONTROL_CHUNK_STREAM_ID,
timestamp: Timestamp::ZERO,
message_type_id: self.message_type_id(),
message_stream_id: CONTROL_MESSAGE_STREAM_ID,
payload,
}
}
}
broadcast_core::impl_spec_display!(ProtocolControl);
impl Serialize for ProtocolControl {
type Error = RtmpError;
fn serialized_len(&self) -> usize {
match self {
ProtocolControl::SetChunkSize(_)
| ProtocolControl::Abort { .. }
| ProtocolControl::Acknowledgement(_)
| ProtocolControl::WindowAckSize(_) => CONTROL_FIELD_LEN,
ProtocolControl::SetPeerBandwidth { .. } => SET_PEER_BANDWIDTH_LEN,
}
}
fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
let written = self.serialized_len();
need_in(buf, written, "protocol control payload output")?;
match *self {
ProtocolControl::SetChunkSize(size) => {
buf[0..CONTROL_FIELD_LEN].copy_from_slice(&size.value().to_be_bytes());
}
ProtocolControl::Abort { chunk_stream_id } => {
buf[0..CONTROL_FIELD_LEN].copy_from_slice(&chunk_stream_id.to_be_bytes());
}
ProtocolControl::Acknowledgement(sequence_number) => {
buf[0..CONTROL_FIELD_LEN].copy_from_slice(&sequence_number.get().to_be_bytes());
}
ProtocolControl::WindowAckSize(window) => {
buf[0..CONTROL_FIELD_LEN].copy_from_slice(&window.to_be_bytes());
}
ProtocolControl::SetPeerBandwidth {
ack_window_size,
limit_type,
} => {
buf[0..CONTROL_FIELD_LEN].copy_from_slice(&ack_window_size.to_be_bytes());
buf[CONTROL_FIELD_LEN] = limit_type.to_u8();
}
}
Ok(written)
}
}
const EVENT_TYPE_LEN: usize = 2;
mod event_type {
pub const STREAM_BEGIN: u16 = 0;
pub const STREAM_EOF: u16 = 1;
pub const STREAM_DRY: u16 = 2;
pub const SET_BUFFER_LENGTH: u16 = 3;
pub const STREAM_IS_RECORDED: u16 = 4;
pub const PING_REQUEST: u16 = 6;
pub const PING_RESPONSE: u16 = 7;
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UserControl {
StreamBegin(u32),
StreamEof(u32),
StreamDry(u32),
SetBufferLength {
stream_id: u32,
buffer: Duration,
},
StreamIsRecorded(u32),
PingRequest(u32),
PingResponse(u32),
}
impl UserControl {
#[must_use]
pub fn name(&self) -> &'static str {
match self {
UserControl::StreamBegin(_) => "stream begin",
UserControl::StreamEof(_) => "stream eof",
UserControl::StreamDry(_) => "stream dry",
UserControl::SetBufferLength { .. } => "set buffer length",
UserControl::StreamIsRecorded(_) => "stream is recorded",
UserControl::PingRequest(_) => "ping request",
UserControl::PingResponse(_) => "ping response",
}
}
#[must_use]
pub fn event_type(&self) -> u16 {
match self {
UserControl::StreamBegin(_) => event_type::STREAM_BEGIN,
UserControl::StreamEof(_) => event_type::STREAM_EOF,
UserControl::StreamDry(_) => event_type::STREAM_DRY,
UserControl::SetBufferLength { .. } => event_type::SET_BUFFER_LENGTH,
UserControl::StreamIsRecorded(_) => event_type::STREAM_IS_RECORDED,
UserControl::PingRequest(_) => event_type::PING_REQUEST,
UserControl::PingResponse(_) => event_type::PING_RESPONSE,
}
}
pub fn to_bytes(&self) -> Result<Vec<u8>> {
let mut buf = alloc::vec![0u8; self.serialized_len()];
buf[0..EVENT_TYPE_LEN].copy_from_slice(&self.event_type().to_be_bytes());
let data = &mut buf[EVENT_TYPE_LEN..];
match *self {
UserControl::StreamBegin(stream_id)
| UserControl::StreamEof(stream_id)
| UserControl::StreamDry(stream_id)
| UserControl::StreamIsRecorded(stream_id)
| UserControl::PingRequest(stream_id)
| UserControl::PingResponse(stream_id) => {
data[0..CONTROL_FIELD_LEN].copy_from_slice(&stream_id.to_be_bytes());
}
UserControl::SetBufferLength { stream_id, buffer } => {
data[0..CONTROL_FIELD_LEN].copy_from_slice(&stream_id.to_be_bytes());
let millis = u32::try_from(buffer.as_millis()).map_err(|_| {
RtmpError::FieldOverflow(broadcast_core::error::FieldOverflow::new(
"set_buffer_length.buffer",
buffer.as_millis() as u64,
u64::from(u32::MAX),
))
})?;
data[CONTROL_FIELD_LEN..2 * CONTROL_FIELD_LEN]
.copy_from_slice(&millis.to_be_bytes());
}
}
Ok(buf)
}
pub fn to_message(&self) -> Result<Message> {
Ok(Message {
chunk_stream_id: CONTROL_CHUNK_STREAM_ID,
timestamp: Timestamp::ZERO,
message_type_id: MessageTypeId::UserControl,
message_stream_id: CONTROL_MESSAGE_STREAM_ID,
payload: self.to_bytes()?,
})
}
}
broadcast_core::impl_spec_display!(UserControl);
impl<'a> Parse<'a> for UserControl {
type Error = RtmpError;
fn parse(bytes: &'a [u8]) -> Result<Self> {
need_in(bytes, EVENT_TYPE_LEN, "user control event type")?;
let event = u16::from_be_bytes([bytes[0], bytes[1]]);
let data = &bytes[EVENT_TYPE_LEN..];
match event {
event_type::STREAM_BEGIN => Ok(UserControl::StreamBegin(need_u32(
data,
"stream begin event data",
)?)),
event_type::STREAM_EOF => Ok(UserControl::StreamEof(need_u32(
data,
"stream eof event data",
)?)),
event_type::STREAM_DRY => Ok(UserControl::StreamDry(need_u32(
data,
"stream dry event data",
)?)),
event_type::SET_BUFFER_LENGTH => {
need_in(data, SET_BUFFER_LENGTH_LEN, "set buffer length event data")?;
let mut r = Reader::new(data);
let stream_id = r.u32("set buffer length event data")?;
let buffer = r.u32("set buffer length event data")?;
Ok(UserControl::SetBufferLength {
stream_id,
buffer: Duration::from_millis(u64::from(buffer)),
})
}
event_type::STREAM_IS_RECORDED => Ok(UserControl::StreamIsRecorded(need_u32(
data,
"stream is recorded event data",
)?)),
event_type::PING_REQUEST => Ok(UserControl::PingRequest(need_u32(
data,
"ping request event data",
)?)),
event_type::PING_RESPONSE => Ok(UserControl::PingResponse(need_u32(
data,
"ping response event data",
)?)),
other => Err(RtmpError::UnsupportedUserControlEvent { value: other }),
}
}
}
impl Serialize for UserControl {
type Error = RtmpError;
fn serialized_len(&self) -> usize {
let data_len = match self {
UserControl::SetBufferLength { .. } => SET_BUFFER_LENGTH_LEN,
_ => CONTROL_FIELD_LEN,
};
EVENT_TYPE_LEN + data_len
}
fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
let written = self.serialized_len();
need_in(buf, written, "user control event output")?;
buf[0..EVENT_TYPE_LEN].copy_from_slice(&self.event_type().to_be_bytes());
let data = &mut buf[EVENT_TYPE_LEN..written];
match *self {
UserControl::StreamBegin(stream_id)
| UserControl::StreamEof(stream_id)
| UserControl::StreamDry(stream_id)
| UserControl::StreamIsRecorded(stream_id)
| UserControl::PingRequest(stream_id)
| UserControl::PingResponse(stream_id) => {
data[0..CONTROL_FIELD_LEN].copy_from_slice(&stream_id.to_be_bytes());
}
UserControl::SetBufferLength { stream_id, buffer } => {
let millis = u32::try_from(buffer.as_millis()).map_err(|_| {
RtmpError::FieldOverflow(broadcast_core::error::FieldOverflow::new(
"set_buffer_length.buffer",
buffer.as_millis() as u64,
u64::from(u32::MAX),
))
})?;
data[0..CONTROL_FIELD_LEN].copy_from_slice(&stream_id.to_be_bytes());
data[CONTROL_FIELD_LEN..2 * CONTROL_FIELD_LEN]
.copy_from_slice(&millis.to_be_bytes());
}
}
Ok(written)
}
}
#[cfg(test)]
mod tests {
use super::*;
use broadcast_core::error::BufferTooShort;
fn message(message_type_id: MessageTypeId, payload: Vec<u8>) -> Message {
Message {
chunk_stream_id: CONTROL_CHUNK_STREAM_ID,
timestamp: Timestamp::ZERO,
message_type_id,
message_stream_id: CONTROL_MESSAGE_STREAM_ID,
payload,
}
}
#[test]
fn invalid_chunk_size_never_reaches_a_message() {
assert!(matches!(
ChunkSize::try_new(0),
Err(RtmpError::ChunkSizeOutOfRange { value: 0 })
));
assert!(matches!(
ChunkSize::try_new(0x8000_0000),
Err(RtmpError::ChunkSizeOutOfRange { value: 0x8000_0000 })
));
let msg = ProtocolControl::SetChunkSize(ChunkSize::try_new(4096).unwrap()).to_message();
assert_eq!(msg.message_type_id, MessageTypeId::SetChunkSize);
assert_eq!(msg.payload, vec![0x00, 0x00, 0x10, 0x00]);
}
#[test]
fn limit_type_round_trip_and_name() {
for (byte, lt, name) in [
(0u8, LimitType::Hard, "hard"),
(1, LimitType::Soft, "soft"),
(2, LimitType::Dynamic, "dynamic"),
] {
let parsed = LimitType::from_u8(byte).unwrap();
assert_eq!(parsed, lt);
assert_eq!(parsed.to_u8(), byte);
assert_eq!(parsed.name(), name);
assert_eq!(parsed.to_string(), name);
}
}
#[test]
fn limit_type_out_of_range_is_malformed() {
assert!(matches!(
LimitType::from_u8(3),
Err(RtmpError::InvalidLimitType { value: 3 })
));
}
fn protocol_control_round_trip(pc: ProtocolControl) {
let bytes = pc.try_to_bytes().unwrap();
let parsed = ProtocolControl::from_payload(pc.message_type_id(), &bytes)
.unwrap()
.expect("known protocol control type id");
assert_eq!(parsed, pc);
let msg = message(pc.message_type_id(), bytes.clone());
let via_message = ProtocolControl::from_message(&msg).unwrap().unwrap();
assert_eq!(via_message, pc);
assert_eq!(via_message.try_to_bytes().unwrap(), bytes);
}
#[test]
fn set_chunk_size_round_trips() {
protocol_control_round_trip(ProtocolControl::SetChunkSize(
ChunkSize::try_new(4096).unwrap(),
));
}
#[test]
fn abort_round_trips() {
protocol_control_round_trip(ProtocolControl::Abort { chunk_stream_id: 7 });
}
#[test]
fn acknowledgement_round_trips() {
protocol_control_round_trip(ProtocolControl::Acknowledgement(SequenceNumber::new(
1_048_576,
)));
}
#[test]
fn window_ack_size_round_trips() {
protocol_control_round_trip(ProtocolControl::WindowAckSize(2_500_000));
}
#[test]
fn set_peer_bandwidth_round_trips_every_limit_type() {
for limit_type in [LimitType::Hard, LimitType::Soft, LimitType::Dynamic] {
protocol_control_round_trip(ProtocolControl::SetPeerBandwidth {
ack_window_size: 2_500_000,
limit_type,
});
}
}
#[test]
fn protocol_control_to_bytes_matches_the_serializer() {
for pc in [
ProtocolControl::SetChunkSize(ChunkSize::try_new(4096).unwrap()),
ProtocolControl::Abort { chunk_stream_id: 7 },
ProtocolControl::Acknowledgement(SequenceNumber::new(1_048_576)),
ProtocolControl::WindowAckSize(2_500_000),
ProtocolControl::SetPeerBandwidth {
ack_window_size: 2_500_000,
limit_type: LimitType::Hard,
},
ProtocolControl::SetPeerBandwidth {
ack_window_size: 2_500_000,
limit_type: LimitType::Soft,
},
ProtocolControl::SetPeerBandwidth {
ack_window_size: 2_500_000,
limit_type: LimitType::Dynamic,
},
] {
assert_eq!(pc.to_bytes(), pc.try_to_bytes().unwrap());
assert_eq!(pc.to_message().payload, pc.to_bytes());
}
}
#[test]
fn set_chunk_size_reserved_top_bit_rejected_on_parse() {
let bytes = 0x8000_1000u32.to_be_bytes().to_vec();
assert!(matches!(
ProtocolControl::from_payload(MessageTypeId::SetChunkSize, &bytes),
Err(RtmpError::ChunkSizeOutOfRange { value: 0x8000_1000 })
));
}
#[test]
fn set_chunk_size_zero_rejected() {
let bytes = 0u32.to_be_bytes().to_vec();
assert!(matches!(
ProtocolControl::from_payload(MessageTypeId::SetChunkSize, &bytes),
Err(RtmpError::ChunkSizeOutOfRange { value: 0 })
));
assert!(ChunkSize::try_new(0).is_err());
}
#[test]
fn set_chunk_size_serialize_layout_matches_spec() {
let bytes = ProtocolControl::SetChunkSize(ChunkSize::try_new(1).unwrap())
.try_to_bytes()
.unwrap();
assert_eq!(bytes, vec![0x00, 0x00, 0x00, 0x01]);
}
#[test]
fn set_peer_bandwidth_serialize_layout_matches_spec() {
let bytes = ProtocolControl::SetPeerBandwidth {
ack_window_size: 0x0002_5000,
limit_type: LimitType::Dynamic,
}
.try_to_bytes()
.unwrap();
assert_eq!(bytes, vec![0x00, 0x02, 0x50, 0x00, 0x02]);
}
#[test]
fn set_peer_bandwidth_wrong_limit_type_mapping_would_fail() {
assert_eq!(LimitType::Hard.to_u8(), 0);
assert_eq!(LimitType::Dynamic.to_u8(), 2);
assert_ne!(LimitType::Hard.to_u8(), LimitType::Dynamic.to_u8());
}
#[test]
fn from_message_none_for_non_control_type_id() {
let msg = message(MessageTypeId::Audio, vec![0u8; 4]);
assert!(ProtocolControl::from_message(&msg).unwrap().is_none());
}
#[test]
fn from_message_some_for_control_type_id() {
let msg = message(
MessageTypeId::WindowAckSize,
1_000_000u32.to_be_bytes().to_vec(),
);
assert!(ProtocolControl::from_message(&msg).unwrap().is_some());
}
#[test]
fn to_message_uses_control_csid_and_stream_id() {
let msg = ProtocolControl::SetChunkSize(ChunkSize::try_new(4096).unwrap()).to_message();
assert_eq!(msg.chunk_stream_id, CONTROL_CHUNK_STREAM_ID);
assert_eq!(msg.message_stream_id, CONTROL_MESSAGE_STREAM_ID);
assert_eq!(msg.message_type_id, MessageTypeId::SetChunkSize);
}
#[test]
fn protocol_control_display_matches_name() {
assert_eq!(
ProtocolControl::Acknowledgement(SequenceNumber::new(1)).to_string(),
ProtocolControl::Acknowledgement(SequenceNumber::new(1)).name()
);
}
fn user_control_round_trip(uc: UserControl) {
let bytes = uc.try_to_bytes().unwrap();
let parsed = UserControl::parse(&bytes).unwrap();
assert_eq!(parsed, uc);
assert_eq!(parsed.try_to_bytes().unwrap(), bytes);
}
#[test]
fn stream_begin_round_trips() {
user_control_round_trip(UserControl::StreamBegin(1));
}
#[test]
fn stream_begin_serialize_layout_matches_spec() {
let bytes = UserControl::StreamBegin(1).try_to_bytes().unwrap();
assert_eq!(bytes, vec![0x00, 0x00, 0x00, 0x00, 0x00, 0x01]);
}
#[test]
fn user_control_to_bytes_matches_the_serializer() {
for uc in [
UserControl::StreamBegin(1),
UserControl::StreamEof(1),
UserControl::StreamDry(1),
UserControl::StreamIsRecorded(1),
UserControl::PingRequest(1),
UserControl::PingResponse(1),
UserControl::SetBufferLength {
stream_id: 1,
buffer: Duration::from_millis(3_000),
},
] {
assert_eq!(uc.to_bytes().unwrap(), uc.try_to_bytes().unwrap());
assert_eq!(uc.to_message().unwrap().payload, uc.to_bytes().unwrap());
}
}
#[test]
fn stream_eof_round_trips() {
user_control_round_trip(UserControl::StreamEof(1));
}
#[test]
fn stream_dry_round_trips() {
user_control_round_trip(UserControl::StreamDry(1));
}
#[test]
fn set_buffer_length_round_trips() {
user_control_round_trip(UserControl::SetBufferLength {
stream_id: 1,
buffer: Duration::from_millis(3000),
});
}
#[test]
fn stream_is_recorded_round_trips() {
user_control_round_trip(UserControl::StreamIsRecorded(1));
}
#[test]
fn ping_request_round_trips() {
user_control_round_trip(UserControl::PingRequest(0x1234_5678));
}
#[test]
fn ping_response_round_trips() {
user_control_round_trip(UserControl::PingResponse(0x1234_5678));
}
#[test]
fn unrecognised_event_type_is_unsupported() {
let bytes = [0x00, 0x05, 0x00, 0x00, 0x00, 0x01];
assert!(matches!(
UserControl::parse(&bytes),
Err(RtmpError::UnsupportedUserControlEvent { value: 5 })
));
}
#[test]
fn user_control_event_type_wrong_mapping_would_fail() {
assert_eq!(UserControl::StreamBegin(0).event_type(), 0);
assert_eq!(UserControl::StreamEof(0).event_type(), 1);
}
#[test]
fn user_control_display_matches_name() {
assert_eq!(
UserControl::StreamBegin(1).to_string(),
UserControl::StreamBegin(1).name()
);
}
#[test]
fn to_message_uses_control_csid_and_user_control_type_id() {
let msg = UserControl::StreamBegin(1).to_message().unwrap();
assert_eq!(msg.chunk_stream_id, CONTROL_CHUNK_STREAM_ID);
assert_eq!(msg.message_stream_id, CONTROL_MESSAGE_STREAM_ID);
assert_eq!(msg.message_type_id, MessageTypeId::UserControl);
}
#[test]
fn message_type_ids_round_trip_every_defined_value() {
for (id, value) in [
(MessageTypeId::SetChunkSize, 1u8),
(MessageTypeId::Abort, 2),
(MessageTypeId::Acknowledgement, 3),
(MessageTypeId::UserControl, 4),
(MessageTypeId::WindowAckSize, 5),
(MessageTypeId::SetPeerBandwidth, 6),
(MessageTypeId::Audio, 8),
(MessageTypeId::Video, 9),
(MessageTypeId::DataAmf3, 15),
(MessageTypeId::CommandAmf3, 17),
(MessageTypeId::DataAmf0, 18),
(MessageTypeId::CommandAmf0, 20),
(MessageTypeId::Aggregate, 22),
] {
assert_eq!(id.to_u8(), value, "{}", id.name());
assert_eq!(MessageTypeId::from_u8(value), id);
assert_eq!(id.to_string(), id.name());
}
}
#[test]
fn an_undefined_message_type_id_is_kept_as_other_and_displays_its_byte() {
for value in [0u8, 7, 10, 16, 19, 21, 200] {
assert_eq!(
MessageTypeId::from_u8(value),
MessageTypeId::Other(value),
"type id {value}"
);
assert_eq!(MessageTypeId::from_u8(value).to_u8(), value);
}
assert_eq!(MessageTypeId::Other(7).name(), "other");
assert_eq!(MessageTypeId::Other(7).to_string(), "other(0x07)");
}
#[test]
fn truncated_four_byte_user_control_data_is_rejected() {
for event in [
event_type::STREAM_BEGIN,
event_type::STREAM_EOF,
event_type::STREAM_DRY,
event_type::STREAM_IS_RECORDED,
event_type::PING_REQUEST,
event_type::PING_RESPONSE,
] {
for data_len in 0..4usize {
let mut bytes = event.to_be_bytes().to_vec();
bytes.extend(core::iter::repeat_n(0u8, data_len));
assert!(
matches!(
UserControl::parse(&bytes),
Err(RtmpError::BufferTooShort(BufferTooShort {
need: 4,
have,
..
})) if have == data_len
),
"event 0x{event:04X} with {data_len} data bytes must be rejected"
);
}
}
}
#[test]
fn set_buffer_length_requires_both_four_byte_fields() {
for data_len in 0..8usize {
let mut bytes = event_type::SET_BUFFER_LENGTH.to_be_bytes().to_vec();
bytes.extend(core::iter::repeat_n(0u8, data_len));
assert!(
matches!(
UserControl::parse(&bytes),
Err(RtmpError::BufferTooShort(BufferTooShort {
need: 8,
have,
..
})) if have == data_len
),
"set buffer length with {data_len} data bytes must be rejected"
);
}
let bytes = [0x00, 0x03, 0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x03, 0xE8];
assert_eq!(
UserControl::parse(&bytes).unwrap(),
UserControl::SetBufferLength {
stream_id: 9,
buffer: Duration::from_millis(1_000),
}
);
}
#[test]
fn protocol_control_names_are_pinned() {
for (pc, name) in [
(
ProtocolControl::SetChunkSize(ChunkSize::try_new(4096).unwrap()),
"set chunk size",
),
(
ProtocolControl::Abort { chunk_stream_id: 7 },
"abort message",
),
(
ProtocolControl::Acknowledgement(SequenceNumber::new(1)),
"acknowledgement",
),
(
ProtocolControl::WindowAckSize(2_500_000),
"window acknowledgement size",
),
(
ProtocolControl::SetPeerBandwidth {
ack_window_size: 2_500_000,
limit_type: LimitType::Hard,
},
"set peer bandwidth",
),
] {
assert_eq!(pc.name(), name);
assert_eq!(pc.to_string(), name);
}
}
#[test]
fn user_control_names_are_pinned() {
for (uc, name) in [
(UserControl::StreamBegin(1), "stream begin"),
(UserControl::StreamEof(1), "stream eof"),
(UserControl::StreamDry(1), "stream dry"),
(
UserControl::SetBufferLength {
stream_id: 1,
buffer: Duration::from_millis(3_000),
},
"set buffer length",
),
(UserControl::StreamIsRecorded(1), "stream is recorded"),
(UserControl::PingRequest(1), "ping request"),
(UserControl::PingResponse(1), "ping response"),
] {
assert_eq!(uc.name(), name);
assert_eq!(uc.to_string(), name);
}
}
#[test]
fn conversions_expose_the_spec_values() {
assert_eq!(u8::from(MessageTypeId::Audio), 8);
assert_eq!(u8::from(MessageTypeId::Video), 9);
assert_eq!(u32::from(ChunkSize::new(4096).unwrap()), 4096);
}
#[test]
fn a_header_and_a_message_carry_the_undecoded_message_type_id() {
use crate::chunk::{ChunkWriter, MessageHeader};
let header = MessageHeader::Type0 {
timestamp: Timestamp::ZERO,
message_length: 4,
message_type_id: MessageTypeId::Other(99),
message_stream_id: MessageStreamId::new(1),
};
let bytes = header.try_to_bytes().expect("header");
let (back, consumed) =
MessageHeader::parse(crate::chunk::Fmt::Type0, &bytes).expect("parse");
assert_eq!(consumed, bytes.len());
assert_eq!(back, header);
let message = message(MessageTypeId::Other(99), vec![0; 4]);
let wire = ChunkWriter::new().write(&message).expect("write");
assert_eq!(wire[7], 99, "the wire carries the raw message type id");
let mut assembler =
crate::chunk::ChunkAssembler::new(crate::test_support::TEST_CHUNK_LIMITS);
assert_eq!(assembler.push(&wire).expect("push"), vec![message]);
}
}