1use broadcast_common::error::BufferTooShort;
38use broadcast_common::{Parse, Serialize};
39
40use crate::RtmpError;
41use alloc::string::String;
42use alloc::vec::Vec;
43
44type Result<T> = core::result::Result<T, RtmpError>;
45
46pub mod marker {
48 pub const NUMBER: u8 = 0x00;
50 pub const BOOLEAN: u8 = 0x01;
52 pub const STRING: u8 = 0x02;
54 pub const OBJECT: u8 = 0x03;
56 pub const NULL: u8 = 0x05;
58 pub const UNDEFINED: u8 = 0x06;
60 pub const ECMA_ARRAY: u8 = 0x08;
63 pub const OBJECT_END: u8 = 0x09;
66 pub const STRICT_ARRAY: u8 = 0x0A;
68 pub const DATE: u8 = 0x0B;
71 pub const LONG_STRING: u8 = 0x0C;
74}
75
76pub const MAX_AMF0_DEPTH: usize = 32;
83
84pub const MAX_AMF0_VALUES: usize = 4096;
92
93fn count_value(values: &mut usize) -> Result<()> {
96 *values = values.checked_add(1).ok_or(RtmpError::Amf0TooManyValues {
97 max: MAX_AMF0_VALUES,
98 })?;
99 if *values > MAX_AMF0_VALUES {
100 return Err(RtmpError::Amf0TooManyValues {
101 max: MAX_AMF0_VALUES,
102 });
103 }
104 Ok(())
105}
106
107const MARKER_LEN: usize = 1;
108const NUMBER_LEN: usize = 8;
109const BOOLEAN_LEN: usize = 1;
110const U16_LEN: usize = 2;
111const U32_LEN: usize = 4;
112const DATE_RESERVED_LEN: usize = 2;
113const OBJECT_END_LEN: usize = 3;
115
116#[non_exhaustive]
128#[derive(Debug, Clone, PartialEq)]
129#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
130pub enum Amf0Value {
131 Number(f64),
133 Boolean(bool),
135 String(String),
137 Object(Vec<(String, Amf0Value)>),
139 Null,
141 Undefined,
143 EcmaArray(Vec<(String, Amf0Value)>),
146 StrictArray(Vec<Amf0Value>),
148 Date(f64),
150 LongString(String),
153}
154
155fn buffer_too_short(need: usize, have: usize, what: &'static str) -> RtmpError {
156 RtmpError::BufferTooShort(BufferTooShort { need, have, what })
157}
158
159fn read_utf8_short(bytes: &[u8]) -> Result<(String, usize)> {
164 if bytes.len() < U16_LEN {
165 return Err(buffer_too_short(U16_LEN, bytes.len(), "AMF0 string length"));
166 }
167 let len = u16::from_be_bytes([bytes[0], bytes[1]]) as usize;
168 let total = U16_LEN.checked_add(len).ok_or(RtmpError::FieldOverflow(
174 broadcast_common::len::FieldOverflow {
175 field: "AMF0 string length",
176 value: u64::from(u16::MAX),
177 max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
178 },
179 ))?;
180 if bytes.len() < total {
181 return Err(buffer_too_short(total, bytes.len(), "AMF0 string"));
182 }
183 let s = String::from_utf8(bytes[U16_LEN..total].to_vec())
184 .map_err(|_| RtmpError::Amf0Utf8 { what: "string" })?;
185 Ok((s, total))
186}
187
188fn read_utf8_long(bytes: &[u8]) -> Result<(String, usize)> {
190 if bytes.len() < U32_LEN {
191 return Err(buffer_too_short(
192 U32_LEN,
193 bytes.len(),
194 "AMF0 long string length",
195 ));
196 }
197 let len = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as usize;
198 let total = U32_LEN.checked_add(len).ok_or(RtmpError::FieldOverflow(
204 broadcast_common::len::FieldOverflow {
205 field: "AMF0 long string length",
206 value: u64::from(u32::MAX),
207 max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
208 },
209 ))?;
210 if bytes.len() < total {
211 return Err(buffer_too_short(total, bytes.len(), "AMF0 long string"));
212 }
213 let s = String::from_utf8(bytes[U32_LEN..total].to_vec()).map_err(|_| RtmpError::Amf0Utf8 {
214 what: "long string",
215 })?;
216 Ok((s, total))
217}
218
219fn parse_pairs(
226 bytes: &[u8],
227 depth: usize,
228 values: &mut usize,
229) -> Result<(Vec<(String, Amf0Value)>, usize)> {
230 let mut consumed = 0;
231 let mut pairs = Vec::new();
232 loop {
233 let (key, key_len) = read_utf8_short(&bytes[consumed..])?;
234 let after_key = consumed + key_len;
235 if key.is_empty() {
236 if bytes.len() < after_key + MARKER_LEN {
237 return Err(buffer_too_short(
238 after_key + MARKER_LEN,
239 bytes.len(),
240 "amf0 object-end marker",
241 ));
242 }
243 if bytes[after_key] == marker::OBJECT_END {
244 return Ok((pairs, after_key + MARKER_LEN));
245 }
246 }
247 let (value, value_len) = parse_value(&bytes[after_key..], depth, values)?;
248 pairs.push((key, value));
249 consumed = after_key
250 .checked_add(value_len)
251 .ok_or(RtmpError::FieldOverflow(
252 broadcast_common::len::FieldOverflow {
253 field: "AMF0 object pair length",
254 value: u64::from(u32::try_from(after_key).unwrap_or(u32::MAX))
255 + u64::from(u32::try_from(value_len).unwrap_or(u32::MAX)),
256 max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
257 },
258 ))?;
259 }
260}
261
262fn parse_value(bytes: &[u8], depth: usize, values: &mut usize) -> Result<(Amf0Value, usize)> {
274 if bytes.is_empty() {
275 return Err(buffer_too_short(MARKER_LEN, 0, "amf0 value marker"));
276 }
277 count_value(values)?;
278 let body = &bytes[MARKER_LEN..];
279 match bytes[0] {
280 marker::NUMBER => {
281 if body.len() < NUMBER_LEN {
282 return Err(buffer_too_short(NUMBER_LEN, body.len(), "amf0 number"));
283 }
284 let mut b = [0u8; NUMBER_LEN];
285 b.copy_from_slice(&body[..NUMBER_LEN]);
286 Ok((
287 Amf0Value::Number(f64::from_be_bytes(b)),
288 MARKER_LEN + NUMBER_LEN,
289 ))
290 }
291 marker::BOOLEAN => {
292 if body.is_empty() {
293 return Err(buffer_too_short(BOOLEAN_LEN, 0, "amf0 boolean"));
294 }
295 Ok((Amf0Value::Boolean(body[0] != 0), MARKER_LEN + BOOLEAN_LEN))
296 }
297 marker::STRING => {
298 let (s, len) = read_utf8_short(body)?;
299 Ok((Amf0Value::String(s), MARKER_LEN + len))
300 }
301 marker::OBJECT => {
302 if depth >= MAX_AMF0_DEPTH {
303 return Err(RtmpError::Amf0DepthExceeded {
304 max: MAX_AMF0_DEPTH,
305 });
306 }
307 let (pairs, len) = parse_pairs(body, depth + 1, values)?;
308 Ok((Amf0Value::Object(pairs), MARKER_LEN + len))
309 }
310 marker::NULL => Ok((Amf0Value::Null, MARKER_LEN)),
311 marker::UNDEFINED => Ok((Amf0Value::Undefined, MARKER_LEN)),
312 marker::ECMA_ARRAY => {
313 if depth >= MAX_AMF0_DEPTH {
314 return Err(RtmpError::Amf0DepthExceeded {
315 max: MAX_AMF0_DEPTH,
316 });
317 }
318 if body.len() < U32_LEN {
319 return Err(buffer_too_short(
320 U32_LEN,
321 body.len(),
322 "amf0 ecma array count",
323 ));
324 }
325 let (pairs, len) = parse_pairs(&body[U32_LEN..], depth + 1, values)?;
330 Ok((Amf0Value::EcmaArray(pairs), MARKER_LEN + U32_LEN + len))
331 }
332 marker::STRICT_ARRAY => {
333 if depth >= MAX_AMF0_DEPTH {
334 return Err(RtmpError::Amf0DepthExceeded {
335 max: MAX_AMF0_DEPTH,
336 });
337 }
338 if body.len() < U32_LEN {
339 return Err(buffer_too_short(
340 U32_LEN,
341 body.len(),
342 "amf0 strict array count",
343 ));
344 }
345 let count = u32::from_be_bytes([body[0], body[1], body[2], body[3]]);
346 let mut rest = &body[U32_LEN..];
347 let mut elements = Vec::new();
348 for _ in 0..count {
349 let (value, consumed) = parse_value(rest, depth + 1, values)?;
350 elements.push(value);
351 rest = rest.get(consumed..).ok_or(RtmpError::FieldOverflow(
352 broadcast_common::len::FieldOverflow {
353 field: "AMF0 strict array element length",
354 value: u64::try_from(consumed).unwrap_or(u64::MAX),
355 max: u64::try_from(rest.len()).unwrap_or(u64::MAX),
356 },
357 ))?;
358 }
359 let elements_len =
360 body[U32_LEN..]
361 .len()
362 .checked_sub(rest.len())
363 .ok_or(RtmpError::Malformed {
364 what: "AMF0 strict array body",
365 })?;
366 Ok((
367 Amf0Value::StrictArray(elements),
368 MARKER_LEN + U32_LEN + elements_len,
369 ))
370 }
371 marker::DATE => {
372 if body.len() < NUMBER_LEN + DATE_RESERVED_LEN {
373 return Err(buffer_too_short(
374 NUMBER_LEN + DATE_RESERVED_LEN,
375 body.len(),
376 "amf0 date",
377 ));
378 }
379 let mut b = [0u8; NUMBER_LEN];
380 b.copy_from_slice(&body[..NUMBER_LEN]);
381 let tz = u16::from_be_bytes([body[NUMBER_LEN], body[NUMBER_LEN + 1]]);
382 if tz != 0 {
383 return Err(RtmpError::Amf0DateTimeZone { value: tz });
384 }
385 Ok((
386 Amf0Value::Date(f64::from_be_bytes(b)),
387 MARKER_LEN + NUMBER_LEN + DATE_RESERVED_LEN,
388 ))
389 }
390 marker::LONG_STRING => {
391 let (s, len) = read_utf8_long(body)?;
392 Ok((Amf0Value::LongString(s), MARKER_LEN + len))
393 }
394 other => Err(RtmpError::UnsupportedAmf0Marker { marker: other }),
395 }
396}
397
398fn sequence_length_overflow(so_far: usize, next: usize) -> RtmpError {
401 RtmpError::FieldOverflow(broadcast_common::len::FieldOverflow {
402 field: "amf0 value sequence length",
403 value: u64::from(u32::try_from(so_far).unwrap_or(u32::MAX))
404 + u64::from(u32::try_from(next).unwrap_or(u32::MAX)),
405 max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
406 })
407}
408
409fn pairs_body_len(pairs: &[(String, Amf0Value)]) -> usize {
410 pairs
411 .iter()
412 .map(|(k, v)| U16_LEN + k.len() + v.serialized_len())
413 .sum::<usize>()
414 + OBJECT_END_LEN
415}
416
417fn write_pairs(pairs: &[(String, Amf0Value)], buf: &mut [u8]) -> Result<usize> {
418 let mut offset = 0;
419 for (k, v) in pairs {
420 let key_total = U16_LEN + k.len();
421 if buf.len() < offset + key_total {
422 return Err(buffer_too_short(
423 offset + key_total,
424 buf.len(),
425 "amf0 object key output",
426 ));
427 }
428 let key_len = broadcast_common::len::fit_u16(k.len(), "amf0 object key length")?;
429 buf[offset..offset + U16_LEN].copy_from_slice(&key_len.to_be_bytes());
430 buf[offset + U16_LEN..offset + key_total].copy_from_slice(k.as_bytes());
431 offset += key_total;
432 offset += v.serialize_into(&mut buf[offset..])?;
433 }
434 if buf.len() < offset + OBJECT_END_LEN {
435 return Err(buffer_too_short(
436 offset + OBJECT_END_LEN,
437 buf.len(),
438 "amf0 object-end output",
439 ));
440 }
441 buf[offset] = 0;
442 buf[offset + 1] = 0;
443 buf[offset + 2] = marker::OBJECT_END;
444 Ok(offset + OBJECT_END_LEN)
445}
446
447impl<'a> Parse<'a> for Amf0Value {
448 type Error = RtmpError;
449
450 fn parse(bytes: &'a [u8]) -> Result<Self> {
451 let mut values = 0usize;
452 let (value, _) = parse_value(bytes, 0, &mut values)?;
453 Ok(value)
454 }
455}
456
457impl Serialize for Amf0Value {
458 type Error = RtmpError;
459
460 fn serialized_len(&self) -> usize {
461 MARKER_LEN
462 + match self {
463 Amf0Value::Number(_) | Amf0Value::Date(_) => NUMBER_LEN,
464 Amf0Value::Boolean(_) => BOOLEAN_LEN,
465 Amf0Value::String(s) => U16_LEN + s.len(),
466 Amf0Value::LongString(s) => U32_LEN + s.len(),
467 Amf0Value::Object(pairs) => pairs_body_len(pairs),
468 Amf0Value::Null | Amf0Value::Undefined => 0,
469 Amf0Value::EcmaArray(pairs) => U32_LEN + pairs_body_len(pairs),
470 Amf0Value::StrictArray(values) => {
471 U32_LEN + values.iter().map(Serialize::serialized_len).sum::<usize>()
472 }
473 }
474 + match self {
475 Amf0Value::Date(_) => DATE_RESERVED_LEN,
476 _ => 0,
477 }
478 }
479
480 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
481 let written = self.serialized_len();
482 if buf.len() < written {
483 return Err(buffer_too_short(written, buf.len(), "amf0 value output"));
484 }
485 let (marker_byte, body) = buf[..written].split_at_mut(MARKER_LEN);
486 match self {
487 Amf0Value::Number(v) => {
488 marker_byte[0] = marker::NUMBER;
489 body[..NUMBER_LEN].copy_from_slice(&v.to_be_bytes());
490 }
491 Amf0Value::Boolean(v) => {
492 marker_byte[0] = marker::BOOLEAN;
493 body[0] = u8::from(*v);
494 }
495 Amf0Value::String(s) => {
496 if s.len() > usize::from(u16::MAX) {
497 return Err(RtmpError::Amf0StringTooLong { len: s.len() });
498 }
499 marker_byte[0] = marker::STRING;
500 body[..U16_LEN].copy_from_slice(&(s.len() as u16).to_be_bytes());
501 body[U16_LEN..].copy_from_slice(s.as_bytes());
502 }
503 Amf0Value::LongString(s) => {
504 marker_byte[0] = marker::LONG_STRING;
505 let len = broadcast_common::len::fit_u32(s.len(), "amf0 long string length")?;
506 body[..U32_LEN].copy_from_slice(&len.to_be_bytes());
507 body[U32_LEN..].copy_from_slice(s.as_bytes());
508 }
509 Amf0Value::Object(pairs) => {
510 marker_byte[0] = marker::OBJECT;
511 write_pairs(pairs, body)?;
512 }
513 Amf0Value::Null => marker_byte[0] = marker::NULL,
514 Amf0Value::Undefined => marker_byte[0] = marker::UNDEFINED,
515 Amf0Value::EcmaArray(pairs) => {
516 marker_byte[0] = marker::ECMA_ARRAY;
517 let count = broadcast_common::len::fit_u32(pairs.len(), "amf0 ECMA array count")?;
518 body[..U32_LEN].copy_from_slice(&count.to_be_bytes());
519 write_pairs(pairs, &mut body[U32_LEN..])?;
520 }
521 Amf0Value::StrictArray(values) => {
522 marker_byte[0] = marker::STRICT_ARRAY;
523 let count =
524 broadcast_common::len::fit_u32(values.len(), "amf0 strict array count")?;
525 body[..U32_LEN].copy_from_slice(&count.to_be_bytes());
526 let mut offset = U32_LEN;
527 for v in values {
528 offset += v.serialize_into(&mut body[offset..])?;
529 }
530 }
531 Amf0Value::Date(v) => {
532 marker_byte[0] = marker::DATE;
533 body[..NUMBER_LEN].copy_from_slice(&v.to_be_bytes());
534 body[NUMBER_LEN..NUMBER_LEN + DATE_RESERVED_LEN].copy_from_slice(&[0, 0]);
535 }
536 }
537 Ok(written)
538 }
539}
540
541#[derive(Debug, Clone, PartialEq)]
550#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
551pub struct Command {
552 pub name: String,
555 pub transaction_id: f64,
558 pub arguments: Vec<Amf0Value>,
561}
562
563impl Command {
564 pub fn parse(payload: &[u8]) -> Result<Self> {
574 let mut values = 0usize;
575 let (name_value, name_len) = parse_value(payload, 0, &mut values)?;
576 let mut offset = name_len;
577 let name = match name_value {
578 Amf0Value::String(s) => s,
579 value => return Err(RtmpError::CommandNameNotString { value }),
580 };
581
582 let (txn_value, txn_len) =
583 parse_value(payload.get(offset..).unwrap_or_default(), 0, &mut values)?;
584 offset = offset.checked_add(txn_len).ok_or(RtmpError::FieldOverflow(
585 broadcast_common::len::FieldOverflow {
586 field: "RTMP command transaction id offset",
587 value: u64::try_from(offset).unwrap_or(u64::MAX),
588 max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
589 },
590 ))?;
591 let transaction_id = match txn_value {
592 Amf0Value::Number(n) => n,
593 value => return Err(RtmpError::CommandTransactionIdNotNumber { value }),
594 };
595
596 let mut arguments = Vec::new();
597 while offset < payload.len() {
598 let (value, len) = parse_value(&payload[offset..], 0, &mut values)?;
599 offset = offset.checked_add(len).ok_or(RtmpError::FieldOverflow(
600 broadcast_common::len::FieldOverflow {
601 field: "RTMP command argument offset",
602 value: u64::try_from(offset).unwrap_or(u64::MAX),
603 max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
604 },
605 ))?;
606 arguments.push(value);
607 }
608
609 Ok(Command {
610 name,
611 transaction_id,
612 arguments,
613 })
614 }
615
616 pub fn to_body(&self) -> Result<Vec<u8>> {
625 let mut out = Amf0Value::String(self.name.clone()).try_to_bytes()?;
626 out.extend(Amf0Value::Number(self.transaction_id).try_to_bytes()?);
627 for arg in &self.arguments {
628 out.extend(arg.try_to_bytes()?);
629 }
630 Ok(out)
631 }
632}
633
634pub fn amf0_values(values: &[Amf0Value]) -> Result<Vec<u8>> {
643 let len = values.iter().try_fold(0usize, |acc, value| {
644 let value_len = value.serialized_len();
645 acc.checked_add(value_len)
646 .ok_or_else(|| sequence_length_overflow(acc, value_len))
647 })?;
648 let mut out = alloc::vec![0u8; len];
649 let mut written = 0usize;
650 for value in values {
651 written += value.serialize_into(&mut out[written..])?;
652 }
653 Ok(out)
654}
655
656#[cfg(test)]
657mod tests {
658 use super::*;
659
660 fn round_trip(v: &Amf0Value) {
661 let bytes = v.try_to_bytes().unwrap();
662 assert_eq!(bytes.len(), v.serialized_len());
663 let parsed = Amf0Value::parse(&bytes).expect("parse");
664 assert_eq!(&parsed, v);
665 assert_eq!(parsed.try_to_bytes().unwrap(), bytes);
667 }
668
669 #[test]
670 fn a_value_sequence_encodes_each_value_in_order() {
671 let values = [
672 Amf0Value::String("onMetaData".to_string()),
673 Amf0Value::EcmaArray(vec![("duration".to_string(), Amf0Value::Number(1.5))]),
674 ];
675 let body = amf0_values(&values).expect("encode");
676 let mut expected = values[0].try_to_bytes().unwrap();
677 expected.extend(values[1].try_to_bytes().unwrap());
678 assert_eq!(body, expected);
679 }
680
681 #[test]
685 fn a_sequence_length_overflow_reports_the_real_lengths() {
686 let err = sequence_length_overflow(6, 8);
687 let RtmpError::FieldOverflow(overflow) = err else {
688 panic!("expected FieldOverflow, got {err:?}");
689 };
690 assert_eq!(overflow.value, 14);
691 assert_eq!(
692 overflow.max,
693 u64::try_from(usize::MAX).expect("usize fits u64 on every supported target")
694 );
695 }
696
697 #[test]
703 fn command_argument_boundaries_come_from_the_parse_not_a_re_derived_length() {
704 let mut payload = Amf0Value::String("connect".to_string())
705 .try_to_bytes()
706 .unwrap();
707 payload.extend(Amf0Value::Number(1.0).try_to_bytes().unwrap());
708 for i in 0..8u8 {
709 payload.extend([marker::BOOLEAN, i]);
710 }
711
712 let command = Command::parse(&payload).expect("any boolean byte is legal AMF0");
713 assert_eq!(
714 command.arguments,
715 (0..8u8)
716 .map(|i| Amf0Value::Boolean(i != 0))
717 .collect::<Vec<_>>()
718 );
719 }
720
721 #[test]
722 fn number_round_trips() {
723 round_trip(&Amf0Value::Number(0.0));
724 round_trip(&Amf0Value::Number(-1.5));
725 round_trip(&Amf0Value::Number(1_000_000.25));
726 }
727
728 #[test]
729 fn boolean_round_trips() {
730 round_trip(&Amf0Value::Boolean(true));
731 round_trip(&Amf0Value::Boolean(false));
732 }
733
734 #[test]
738 fn object_oversized_key_length_errors() {
739 let key = "k".repeat(65536);
740 let value = Amf0Value::Object(vec![(key, Amf0Value::Null)]);
741 let err = value.try_to_bytes().unwrap_err();
742 assert!(
743 matches!(
744 err,
745 RtmpError::FieldOverflow(broadcast_common::len::FieldOverflow {
746 field: "amf0 object key length",
747 ..
748 })
749 ),
750 "expected FieldOverflow for amf0 object key length, got {err:?}"
751 );
752 }
753
754 #[test]
757 fn string_beyond_the_16_bit_prefix_is_rejected() {
758 let value = Amf0Value::String("x".repeat(0x1_0000));
759 let err = value.try_to_bytes().unwrap_err();
760 assert!(
761 matches!(err, RtmpError::Amf0StringTooLong { len } if len == 0x1_0000),
762 "expected Amf0StringTooLong for a 65 536-byte string, got {err:?}"
763 );
764 let boundary = Amf0Value::String("x".repeat(usize::from(u16::MAX)));
765 round_trip(&boundary);
766 }
767
768 #[test]
770 fn object_max_key_length_round_trips() {
771 let key = "k".repeat(65535);
772 round_trip(&Amf0Value::Object(vec![(key, Amf0Value::Null)]));
773 }
774
775 #[test]
776 fn string_round_trips_including_empty_and_multibyte() {
777 round_trip(&Amf0Value::String(String::new()));
778 round_trip(&Amf0Value::String("live".to_string()));
779 round_trip(&Amf0Value::String("héllo wörld 日本語".to_string()));
780 }
781
782 #[test]
783 fn null_and_undefined_round_trip() {
784 round_trip(&Amf0Value::Null);
785 round_trip(&Amf0Value::Undefined);
786 }
787
788 #[test]
789 fn date_round_trips() {
790 round_trip(&Amf0Value::Date(1_700_000_000_000.0));
791 }
792
793 #[test]
794 fn long_string_round_trips() {
795 round_trip(&Amf0Value::LongString("x".repeat(70_000)));
796 }
797
798 #[test]
799 fn object_round_trips_including_nested_object() {
800 round_trip(&Amf0Value::Object(vec![]));
801 round_trip(&Amf0Value::Object(vec![
802 ("app".to_string(), Amf0Value::String("live".to_string())),
803 ("audioSampleRate".to_string(), Amf0Value::Number(44100.0)),
804 ("live".to_string(), Amf0Value::Boolean(true)),
805 ]));
806 round_trip(&Amf0Value::Object(vec![(
809 "capabilities".to_string(),
810 Amf0Value::Object(vec![("videoCodecs".to_string(), Amf0Value::Number(252.0))]),
811 )]));
812 }
813
814 #[test]
815 fn ecma_array_round_trips() {
816 round_trip(&Amf0Value::EcmaArray(vec![]));
817 round_trip(&Amf0Value::EcmaArray(vec![
818 ("duration".to_string(), Amf0Value::Number(0.0)),
819 ("width".to_string(), Amf0Value::Number(1920.0)),
820 ]));
821 }
822
823 #[test]
824 fn strict_array_round_trips() {
825 round_trip(&Amf0Value::StrictArray(vec![]));
826 round_trip(&Amf0Value::StrictArray(vec![
827 Amf0Value::Number(1.0),
828 Amf0Value::String("two".to_string()),
829 Amf0Value::Boolean(false),
830 Amf0Value::Object(vec![("k".to_string(), Amf0Value::Null)]),
831 ]));
832 }
833
834 #[test]
835 fn ecma_array_count_is_informational_not_cross_checked() {
836 let mut bytes = vec![marker::ECMA_ARRAY];
840 bytes.extend_from_slice(&999u32.to_be_bytes()); bytes.extend_from_slice(&1u16.to_be_bytes());
842 bytes.extend_from_slice(b"k");
843 bytes.push(marker::NULL);
844 bytes.extend_from_slice(&[0, 0, marker::OBJECT_END]);
845
846 let parsed = Amf0Value::parse(&bytes).expect("parse");
847 assert_eq!(
848 parsed,
849 Amf0Value::EcmaArray(vec![("k".to_string(), Amf0Value::Null)])
850 );
851 }
852
853 #[test]
854 fn depth_guard_rejects_pathological_nesting_without_stack_overflow() {
855 let mut inner = vec![marker::NULL];
860 for _ in 0..(MAX_AMF0_DEPTH * 4) {
861 let mut wrapped = vec![marker::OBJECT];
862 wrapped.extend_from_slice(&1u16.to_be_bytes());
863 wrapped.push(b'a');
864 wrapped.extend_from_slice(&inner);
865 wrapped.extend_from_slice(&[0, 0, marker::OBJECT_END]);
866 inner = wrapped;
867 }
868
869 let result = Amf0Value::parse(&inner);
870 assert!(matches!(
871 result,
872 Err(RtmpError::Amf0DepthExceeded { max }) if max == MAX_AMF0_DEPTH
873 ));
874 }
875
876 #[test]
877 fn depth_guard_allows_nesting_at_the_limit() {
878 let mut inner = vec![marker::NULL];
879 for _ in 0..(MAX_AMF0_DEPTH - 1) {
880 let mut wrapped = vec![marker::OBJECT];
881 wrapped.extend_from_slice(&1u16.to_be_bytes());
882 wrapped.push(b'a');
883 wrapped.extend_from_slice(&inner);
884 wrapped.extend_from_slice(&[0, 0, marker::OBJECT_END]);
885 inner = wrapped;
886 }
887 assert!(Amf0Value::parse(&inner).is_ok());
888 }
889
890 #[test]
896 fn value_count_guard_rejects_wide_containers() {
897 let count = u32::try_from(MAX_AMF0_VALUES + 1).expect("limit fits u32");
898 let mut bytes = vec![marker::STRICT_ARRAY];
899 bytes.extend_from_slice(&count.to_be_bytes());
900 bytes.extend(core::iter::repeat_n(marker::NULL, MAX_AMF0_VALUES + 1));
901
902 let result = Amf0Value::parse(&bytes);
903 assert!(matches!(
904 result,
905 Err(RtmpError::Amf0TooManyValues { max }) if max == MAX_AMF0_VALUES
906 ));
907 }
908
909 #[test]
910 fn value_count_guard_allows_a_container_at_the_limit() {
911 let count = u32::try_from(MAX_AMF0_VALUES - 1).expect("limit fits u32");
912 let mut bytes = vec![marker::STRICT_ARRAY];
913 bytes.extend_from_slice(&count.to_be_bytes());
914 bytes.extend(core::iter::repeat_n(marker::NULL, MAX_AMF0_VALUES - 1));
915
916 let parsed =
917 Amf0Value::parse(&bytes).expect("the array itself plus its elements is the limit");
918 assert_eq!(
919 parsed,
920 Amf0Value::StrictArray(vec![Amf0Value::Null; MAX_AMF0_VALUES - 1])
921 );
922 }
923
924 #[test]
928 fn command_parse_counts_values_across_every_argument() {
929 let mut payload = Amf0Value::String("connect".to_string())
930 .try_to_bytes()
931 .expect("encode name");
932 payload.extend(
933 Amf0Value::Number(1.0)
934 .try_to_bytes()
935 .expect("encode transaction id"),
936 );
937 payload.extend(core::iter::repeat_n(marker::NULL, MAX_AMF0_VALUES));
938
939 let result = Command::parse(&payload);
940 assert!(matches!(
941 result,
942 Err(RtmpError::Amf0TooManyValues { max }) if max == MAX_AMF0_VALUES
943 ));
944 }
945
946 #[test]
947 fn dropping_object_end_marker_is_rejected() {
948 let full = Amf0Value::Object(vec![("k".to_string(), Amf0Value::Null)])
951 .try_to_bytes()
952 .unwrap();
953 let truncated = &full[..full.len() - 3];
954 assert!(matches!(
955 Amf0Value::parse(truncated),
956 Err(RtmpError::BufferTooShort(..))
957 ));
958 }
959
960 #[test]
961 fn mis_sized_string_length_is_rejected() {
962 let mut bytes = vec![marker::STRING];
965 bytes.extend_from_slice(&100u16.to_be_bytes()); bytes.extend_from_slice(b"short"); assert!(matches!(
968 Amf0Value::parse(&bytes),
969 Err(RtmpError::BufferTooShort(..))
970 ));
971 }
972
973 #[test]
974 fn invalid_utf8_string_is_malformed() {
975 let mut bytes = vec![marker::STRING];
976 bytes.extend_from_slice(&2u16.to_be_bytes());
977 bytes.extend_from_slice(&[0xFF, 0xFE]); assert!(matches!(
979 Amf0Value::parse(&bytes),
980 Err(RtmpError::Amf0Utf8 { what: "string" })
981 ));
982 }
983
984 #[test]
985 fn unsupported_marker_is_rejected_not_panicking() {
986 assert!(matches!(
987 Amf0Value::parse(&[0x11]), Err(RtmpError::UnsupportedAmf0Marker { marker: 0x11 })
989 ));
990 assert!(matches!(
991 Amf0Value::parse(&[0x07]), Err(RtmpError::UnsupportedAmf0Marker { marker: 0x07 })
993 ));
994 }
995
996 #[test]
997 fn date_rejects_nonzero_reserved_timezone() {
998 let mut bytes = vec![marker::DATE];
999 bytes.extend_from_slice(&0.0f64.to_be_bytes());
1000 bytes.extend_from_slice(&1u16.to_be_bytes()); assert!(matches!(
1002 Amf0Value::parse(&bytes),
1003 Err(RtmpError::Amf0DateTimeZone { value: 1 })
1004 ));
1005 }
1006
1007 #[test]
1008 fn empty_buffer_and_truncated_marker_are_buffer_too_short_not_panics() {
1009 assert!(matches!(
1010 Amf0Value::parse(&[]),
1011 Err(RtmpError::BufferTooShort(..))
1012 ));
1013 assert!(matches!(
1014 Amf0Value::parse(&[marker::NUMBER, 0, 0, 0]),
1015 Err(RtmpError::BufferTooShort(..))
1016 ));
1017 }
1018
1019 fn connect_command() -> Command {
1022 Command {
1023 name: "connect".to_string(),
1024 transaction_id: 1.0,
1025 arguments: vec![Amf0Value::Object(vec![
1026 ("app".to_string(), Amf0Value::String("live".to_string())),
1027 (
1028 "flashVer".to_string(),
1029 Amf0Value::String("FMLE/3.0".to_string()),
1030 ),
1031 (
1032 "tcUrl".to_string(),
1033 Amf0Value::String("rtmp://example.test/live".to_string()),
1034 ),
1035 ("fpad".to_string(), Amf0Value::Boolean(false)),
1036 ])],
1037 }
1038 }
1039
1040 fn publish_command() -> Command {
1041 Command {
1042 name: "publish".to_string(),
1043 transaction_id: 5.0,
1044 arguments: vec![
1045 Amf0Value::Null,
1046 Amf0Value::String("stream_key_123".to_string()),
1047 Amf0Value::String("live".to_string()),
1048 ],
1049 }
1050 }
1051
1052 #[test]
1053 fn connect_command_round_trips_byte_identically() {
1054 let cmd = connect_command();
1055 let bytes = cmd.to_body().unwrap();
1056 let parsed = Command::parse(&bytes).expect("parse connect");
1057 assert_eq!(parsed, cmd);
1058 assert_eq!(parsed.to_body().unwrap(), bytes);
1059 }
1060
1061 #[test]
1062 fn publish_command_round_trips_byte_identically() {
1063 let cmd = publish_command();
1064 let bytes = cmd.to_body().unwrap();
1065 let parsed = Command::parse(&bytes).expect("parse publish");
1066 assert_eq!(parsed, cmd);
1067 assert_eq!(parsed.to_body().unwrap(), bytes);
1068 }
1069
1070 #[test]
1071 fn command_name_must_be_string() {
1072 let bytes = Amf0Value::Number(1.0).try_to_bytes().unwrap();
1073 assert!(matches!(
1074 Command::parse(&bytes),
1075 Err(RtmpError::CommandNameNotString { .. })
1076 ));
1077 }
1078
1079 #[test]
1080 fn command_transaction_id_must_be_number() {
1081 let mut bytes = Amf0Value::String("connect".to_string())
1082 .try_to_bytes()
1083 .unwrap();
1084 bytes.extend(
1085 Amf0Value::String("not a number".to_string())
1086 .try_to_bytes()
1087 .unwrap(),
1088 );
1089 assert!(matches!(
1090 Command::parse(&bytes),
1091 Err(RtmpError::CommandTransactionIdNotNumber { .. })
1092 ));
1093 }
1094
1095 #[test]
1098 fn long_string_length_overflowing_usize_is_rejected_not_wrapped() {
1099 let mut bytes = vec![marker::LONG_STRING];
1104 bytes.extend_from_slice(&(u32::MAX - 1).to_be_bytes());
1105 bytes.extend_from_slice(b"short");
1106 let err = Amf0Value::parse(&bytes).unwrap_err();
1107 assert!(matches!(
1108 err,
1109 RtmpError::Malformed { .. } | RtmpError::BufferTooShort(..)
1110 ));
1111 }
1112
1113 #[cfg(feature = "serde")]
1116 #[test]
1117 fn amf0_value_and_command_serde_round_trip() {
1118 let value = Amf0Value::Object(vec![
1119 ("app".to_string(), Amf0Value::String("live".to_string())),
1120 ("live".to_string(), Amf0Value::Boolean(true)),
1121 ("duration".to_string(), Amf0Value::Number(0.0)),
1122 (
1123 "items".to_string(),
1124 Amf0Value::StrictArray(vec![Amf0Value::Null, Amf0Value::Undefined]),
1125 ),
1126 ]);
1127 let json = serde_json::to_string(&value).expect("serialize Amf0Value");
1128 let back: Amf0Value = serde_json::from_str(&json).expect("deserialize Amf0Value");
1129 assert_eq!(back, value);
1130
1131 let cmd = publish_command();
1132 let json = serde_json::to_string(&cmd).expect("serialize Command");
1133 let back: Command = serde_json::from_str(&json).expect("deserialize Command");
1134 assert_eq!(back, cmd);
1135 }
1136
1137 #[test]
1141 fn nested_container_offsets_pin_parse_and_serialize() {
1142 let long = "L".repeat(70_000);
1143 let nested = Amf0Value::StrictArray(vec![
1144 Amf0Value::Object(vec![
1145 ("a".to_string(), Amf0Value::Number(1.5)),
1146 (
1147 "b".to_string(),
1148 Amf0Value::EcmaArray(vec![
1149 ("x".to_string(), Amf0Value::LongString(long)),
1150 ("y".to_string(), Amf0Value::Null),
1151 ]),
1152 ),
1153 ]),
1154 Amf0Value::Date(1.0e12),
1155 Amf0Value::Boolean(true),
1156 Amf0Value::Undefined,
1157 ]);
1158 let bytes = nested.try_to_bytes().expect("serialize");
1159 assert_eq!(bytes.len(), nested.serialized_len());
1160
1161 assert_eq!(
1162 &bytes[..10],
1163 &[
1164 marker::STRICT_ARRAY,
1165 0,
1166 0,
1167 0,
1168 4,
1169 marker::OBJECT,
1170 0,
1171 1,
1172 b'a',
1173 marker::NUMBER
1174 ]
1175 );
1176 assert_eq!(&bytes[10..18], &1.5f64.to_be_bytes());
1177 assert_eq!(
1178 &bytes[18..26],
1179 &[0, 1, b'b', marker::ECMA_ARRAY, 0, 0, 0, 2]
1180 );
1181 assert_eq!(&bytes[26..30], &[0, 1, b'x', marker::LONG_STRING]);
1182 assert_eq!(&bytes[30..34], &70_000u32.to_be_bytes());
1183 assert_eq!(&bytes[34..36], b"LL");
1184
1185 let long_end = 34 + 70_000;
1186 assert_eq!(&bytes[long_end..long_end + 4], &[0, 1, b'y', marker::NULL]);
1187 assert_eq!(
1188 &bytes[long_end + 4..long_end + 10],
1189 &[0, 0, marker::OBJECT_END, 0, 0, marker::OBJECT_END]
1190 );
1191 assert_eq!(bytes[long_end + 10], marker::DATE);
1192 assert_eq!(
1193 &bytes[long_end + 11..long_end + 19],
1194 &1.0e12f64.to_be_bytes()
1195 );
1196 assert_eq!(&bytes[long_end + 19..long_end + 21], &[0, 0]);
1197 assert_eq!(
1198 &bytes[long_end + 21..long_end + 24],
1199 &[marker::BOOLEAN, 1, marker::UNDEFINED]
1200 );
1201 assert_eq!(bytes.len(), long_end + 24);
1202
1203 let mut values = 0usize;
1204 let (parsed, consumed) = parse_value(&bytes, 0, &mut values).expect("parse");
1205 assert_eq!(parsed, nested);
1206 assert_eq!(consumed, bytes.len());
1207 }
1208
1209 #[test]
1211 fn every_variant_writes_its_declared_length() {
1212 let variants = vec![
1213 Amf0Value::Number(-1.5),
1214 Amf0Value::Boolean(false),
1215 Amf0Value::String("hello".to_string()),
1216 Amf0Value::Object(vec![("k".to_string(), Amf0Value::Null)]),
1217 Amf0Value::Null,
1218 Amf0Value::Undefined,
1219 Amf0Value::EcmaArray(vec![("k".to_string(), Amf0Value::Date(0.0))]),
1220 Amf0Value::StrictArray(vec![Amf0Value::Boolean(true), Amf0Value::Null]),
1221 Amf0Value::Date(1.0e12),
1222 Amf0Value::LongString("x".repeat(70_000)),
1223 ];
1224 for value in variants {
1225 let mut buf = vec![0u8; value.serialized_len()];
1226 assert_eq!(
1227 value.serialize_into(&mut buf).unwrap(),
1228 value.serialized_len()
1229 );
1230 let mut values = 0usize;
1231 let (parsed, consumed) = parse_value(&buf, 0, &mut values).unwrap();
1232 assert_eq!(consumed, buf.len());
1233 assert_eq!(parsed, value);
1234 }
1235 }
1236
1237 #[test]
1240 fn long_string_length_prefix_boundaries() {
1241 assert_eq!(
1242 Amf0Value::parse(&[marker::LONG_STRING, 0, 0, 0, 0]).unwrap(),
1243 Amf0Value::LongString(String::new())
1244 );
1245 let mut ok = vec![marker::LONG_STRING, 0, 0, 0, 3];
1246 ok.extend_from_slice(b"abc");
1247 assert_eq!(
1248 Amf0Value::parse(&ok).unwrap(),
1249 Amf0Value::LongString("abc".to_string())
1250 );
1251 assert!(matches!(
1252 Amf0Value::parse(&ok[..ok.len() - 1]),
1253 Err(RtmpError::BufferTooShort(_))
1254 ));
1255 }
1256
1257 #[test]
1260 fn truncating_a_nested_encoding_is_always_buffer_too_short() {
1261 let value = Amf0Value::StrictArray(vec![
1262 Amf0Value::Object(vec![("k".to_string(), Amf0Value::Date(1.0e12))]),
1263 Amf0Value::EcmaArray(vec![("s".to_string(), Amf0Value::String("v".to_string()))]),
1264 ]);
1265 let bytes = value.try_to_bytes().unwrap();
1266 for cut in 1..bytes.len() {
1267 assert!(
1268 matches!(
1269 Amf0Value::parse(&bytes[..cut]),
1270 Err(RtmpError::BufferTooShort(_))
1271 ),
1272 "cut at {cut} must be BufferTooShort"
1273 );
1274 }
1275 }
1276
1277 #[test]
1280 fn truncated_containers_report_the_exact_need() {
1281 let bytes = [marker::ECMA_ARRAY, 0, 0, 0, 0];
1282 match Amf0Value::parse(&bytes) {
1283 Err(RtmpError::BufferTooShort(b)) => {
1284 assert_eq!(b.need, 2);
1285 assert_eq!(b.have, 0);
1286 }
1287 other => panic!("expected BufferTooShort, got {other:?}"),
1288 }
1289
1290 let bytes = [marker::DATE, 0, 0, 0, 0, 0, 0];
1291 match Amf0Value::parse(&bytes) {
1292 Err(RtmpError::BufferTooShort(b)) => {
1293 assert_eq!(b.need, 10);
1294 assert_eq!(b.have, 6);
1295 }
1296 other => panic!("expected BufferTooShort, got {other:?}"),
1297 }
1298
1299 let bytes = [marker::OBJECT, 0, 0];
1300 match Amf0Value::parse(&bytes) {
1301 Err(RtmpError::BufferTooShort(b)) => {
1302 assert_eq!(b.need, 3);
1303 assert_eq!(b.have, 2);
1304 }
1305 other => panic!("expected BufferTooShort, got {other:?}"),
1306 }
1307 }
1308
1309 #[test]
1312 fn object_serialize_overwrites_every_byte_of_its_range() {
1313 let value = Amf0Value::Object(vec![("k".to_string(), Amf0Value::Null)]);
1314 let mut buf = vec![0xFFu8; value.serialized_len()];
1315 assert_eq!(
1316 value.serialize_into(&mut buf).unwrap(),
1317 value.serialized_len()
1318 );
1319 assert_eq!(
1320 buf,
1321 vec![
1322 marker::OBJECT,
1323 0,
1324 1,
1325 b'k',
1326 marker::NULL,
1327 0,
1328 0,
1329 marker::OBJECT_END
1330 ]
1331 );
1332 }
1333
1334 #[test]
1336 fn depth_guard_counts_every_container_kind() {
1337 let mut inner = vec![marker::NULL];
1338 for _ in 0..(MAX_AMF0_DEPTH + 1) {
1339 let mut wrapped = vec![marker::ECMA_ARRAY, 0, 0, 0, 1];
1340 wrapped.extend_from_slice(&1u16.to_be_bytes());
1341 wrapped.push(b'a');
1342 wrapped.extend_from_slice(&inner);
1343 wrapped.extend_from_slice(&[0, 0, marker::OBJECT_END]);
1344 inner = wrapped;
1345 }
1346 assert!(matches!(
1347 Amf0Value::parse(&inner),
1348 Err(RtmpError::Amf0DepthExceeded { .. })
1349 ));
1350
1351 let mut inner = vec![marker::NULL];
1352 for _ in 0..(MAX_AMF0_DEPTH + 1) {
1353 let mut wrapped = vec![marker::STRICT_ARRAY, 0, 0, 0, 1];
1354 wrapped.extend_from_slice(&inner);
1355 inner = wrapped;
1356 }
1357 assert!(matches!(
1358 Amf0Value::parse(&inner),
1359 Err(RtmpError::Amf0DepthExceeded { .. })
1360 ));
1361 }
1362}