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
84const MARKER_LEN: usize = 1;
85const NUMBER_LEN: usize = 8;
86const BOOLEAN_LEN: usize = 1;
87const U16_LEN: usize = 2;
88const U32_LEN: usize = 4;
89const DATE_RESERVED_LEN: usize = 2;
90const OBJECT_END_LEN: usize = 3;
92
93#[non_exhaustive]
105#[derive(Debug, Clone, PartialEq)]
106#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
107pub enum Amf0Value {
108 Number(f64),
110 Boolean(bool),
112 String(String),
114 Object(Vec<(String, Amf0Value)>),
116 Null,
118 Undefined,
120 EcmaArray(Vec<(String, Amf0Value)>),
123 StrictArray(Vec<Amf0Value>),
125 Date(f64),
127 LongString(String),
130}
131
132fn buffer_too_short(need: usize, have: usize, what: &'static str) -> RtmpError {
133 RtmpError::BufferTooShort(BufferTooShort { need, have, what })
134}
135
136fn read_utf8_short(bytes: &[u8], what: &'static str) -> Result<(String, usize)> {
141 if bytes.len() < U16_LEN {
142 return Err(buffer_too_short(U16_LEN, bytes.len(), what));
143 }
144 let len = u16::from_be_bytes([bytes[0], bytes[1]]) as usize;
145 let total = U16_LEN
151 .checked_add(len)
152 .ok_or(RtmpError::Malformed { what })?;
153 if bytes.len() < total {
154 return Err(buffer_too_short(total, bytes.len(), what));
155 }
156 let s = String::from_utf8(bytes[U16_LEN..total].to_vec())
157 .map_err(|_| RtmpError::Malformed { what })?;
158 Ok((s, total))
159}
160
161fn read_utf8_long(bytes: &[u8], what: &'static str) -> Result<(String, usize)> {
163 if bytes.len() < U32_LEN {
164 return Err(buffer_too_short(U32_LEN, bytes.len(), what));
165 }
166 let len = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as usize;
167 let total = U32_LEN
173 .checked_add(len)
174 .ok_or(RtmpError::Malformed { what })?;
175 if bytes.len() < total {
176 return Err(buffer_too_short(total, bytes.len(), what));
177 }
178 let s = String::from_utf8(bytes[U32_LEN..total].to_vec())
179 .map_err(|_| RtmpError::Malformed { what })?;
180 Ok((s, total))
181}
182
183fn parse_pairs(bytes: &[u8], depth: usize) -> Result<(Vec<(String, Amf0Value)>, usize)> {
189 let mut consumed = 0;
190 let mut pairs = Vec::new();
191 loop {
192 let (key, key_len) = read_utf8_short(&bytes[consumed..], "amf0 object key")?;
193 let after_key = consumed + key_len;
194 if key.is_empty() {
195 if bytes.len() < after_key + MARKER_LEN {
196 return Err(buffer_too_short(
197 after_key + MARKER_LEN,
198 bytes.len(),
199 "amf0 object-end marker",
200 ));
201 }
202 if bytes[after_key] == marker::OBJECT_END {
203 return Ok((pairs, after_key + MARKER_LEN));
204 }
205 }
206 let value = parse_value(&bytes[after_key..], depth)?;
207 let value_len = value.serialized_len();
208 pairs.push((key, value));
209 consumed = after_key + value_len;
210 }
211}
212
213fn parse_value(bytes: &[u8], depth: usize) -> Result<Amf0Value> {
220 if bytes.is_empty() {
221 return Err(buffer_too_short(MARKER_LEN, 0, "amf0 value marker"));
222 }
223 let body = &bytes[MARKER_LEN..];
224 match bytes[0] {
225 marker::NUMBER => {
226 if body.len() < NUMBER_LEN {
227 return Err(buffer_too_short(NUMBER_LEN, body.len(), "amf0 number"));
228 }
229 let mut b = [0u8; NUMBER_LEN];
230 b.copy_from_slice(&body[..NUMBER_LEN]);
231 Ok(Amf0Value::Number(f64::from_be_bytes(b)))
232 }
233 marker::BOOLEAN => {
234 if body.is_empty() {
235 return Err(buffer_too_short(BOOLEAN_LEN, 0, "amf0 boolean"));
236 }
237 Ok(Amf0Value::Boolean(body[0] != 0))
238 }
239 marker::STRING => {
240 let (s, _) = read_utf8_short(body, "amf0 string")?;
241 Ok(Amf0Value::String(s))
242 }
243 marker::OBJECT => {
244 if depth >= MAX_AMF0_DEPTH {
245 return Err(RtmpError::Unsupported {
246 what: "amf0 nesting depth exceeded",
247 });
248 }
249 let (pairs, _) = parse_pairs(body, depth + 1)?;
250 Ok(Amf0Value::Object(pairs))
251 }
252 marker::NULL => Ok(Amf0Value::Null),
253 marker::UNDEFINED => Ok(Amf0Value::Undefined),
254 marker::ECMA_ARRAY => {
255 if depth >= MAX_AMF0_DEPTH {
256 return Err(RtmpError::Unsupported {
257 what: "amf0 nesting depth exceeded",
258 });
259 }
260 if body.len() < U32_LEN {
261 return Err(buffer_too_short(
262 U32_LEN,
263 body.len(),
264 "amf0 ecma array count",
265 ));
266 }
267 let (pairs, _) = parse_pairs(&body[U32_LEN..], depth + 1)?;
272 Ok(Amf0Value::EcmaArray(pairs))
273 }
274 marker::STRICT_ARRAY => {
275 if depth >= MAX_AMF0_DEPTH {
276 return Err(RtmpError::Unsupported {
277 what: "amf0 nesting depth exceeded",
278 });
279 }
280 if body.len() < U32_LEN {
281 return Err(buffer_too_short(
282 U32_LEN,
283 body.len(),
284 "amf0 strict array count",
285 ));
286 }
287 let count = u32::from_be_bytes([body[0], body[1], body[2], body[3]]);
288 let mut rest = &body[U32_LEN..];
289 let mut values = Vec::new();
290 for _ in 0..count {
291 let value = parse_value(rest, depth + 1)?;
292 let consumed = value.serialized_len();
293 values.push(value);
294 rest = &rest[consumed..];
295 }
296 Ok(Amf0Value::StrictArray(values))
297 }
298 marker::DATE => {
299 if body.len() < NUMBER_LEN + DATE_RESERVED_LEN {
300 return Err(buffer_too_short(
301 NUMBER_LEN + DATE_RESERVED_LEN,
302 body.len(),
303 "amf0 date",
304 ));
305 }
306 let mut b = [0u8; NUMBER_LEN];
307 b.copy_from_slice(&body[..NUMBER_LEN]);
308 let tz = u16::from_be_bytes([body[NUMBER_LEN], body[NUMBER_LEN + 1]]);
309 if tz != 0 {
310 return Err(RtmpError::Malformed {
311 what: "amf0 date reserved time zone (must be 0x0000)",
312 });
313 }
314 Ok(Amf0Value::Date(f64::from_be_bytes(b)))
315 }
316 marker::LONG_STRING => {
317 let (s, _) = read_utf8_long(body, "amf0 long string")?;
318 Ok(Amf0Value::LongString(s))
319 }
320 _ => Err(RtmpError::Unsupported {
321 what: "amf0 value marker (reserved, legacy, or amf3-switch)",
322 }),
323 }
324}
325
326fn pairs_body_len(pairs: &[(String, Amf0Value)]) -> usize {
327 pairs
328 .iter()
329 .map(|(k, v)| U16_LEN + k.len() + v.serialized_len())
330 .sum::<usize>()
331 + OBJECT_END_LEN
332}
333
334fn write_pairs(pairs: &[(String, Amf0Value)], buf: &mut [u8]) -> Result<usize> {
335 let mut offset = 0;
336 for (k, v) in pairs {
337 let key_total = U16_LEN + k.len();
338 if buf.len() < offset + key_total {
339 return Err(buffer_too_short(
340 offset + key_total,
341 buf.len(),
342 "amf0 object key output",
343 ));
344 }
345 let key_len = broadcast_common::len::fit_u16(k.len(), "amf0 object key length")?;
346 buf[offset..offset + U16_LEN].copy_from_slice(&key_len.to_be_bytes());
347 buf[offset + U16_LEN..offset + key_total].copy_from_slice(k.as_bytes());
348 offset += key_total;
349 offset += v.serialize_into(&mut buf[offset..])?;
350 }
351 if buf.len() < offset + OBJECT_END_LEN {
352 return Err(buffer_too_short(
353 offset + OBJECT_END_LEN,
354 buf.len(),
355 "amf0 object-end output",
356 ));
357 }
358 buf[offset] = 0;
359 buf[offset + 1] = 0;
360 buf[offset + 2] = marker::OBJECT_END;
361 Ok(offset + OBJECT_END_LEN)
362}
363
364impl<'a> Parse<'a> for Amf0Value {
365 type Error = RtmpError;
366
367 fn parse(bytes: &'a [u8]) -> Result<Self> {
368 parse_value(bytes, 0)
369 }
370}
371
372impl Serialize for Amf0Value {
373 type Error = RtmpError;
374
375 fn serialized_len(&self) -> usize {
376 MARKER_LEN
377 + match self {
378 Amf0Value::Number(_) | Amf0Value::Date(_) => NUMBER_LEN,
379 Amf0Value::Boolean(_) => BOOLEAN_LEN,
380 Amf0Value::String(s) => U16_LEN + s.len(),
381 Amf0Value::LongString(s) => U32_LEN + s.len(),
382 Amf0Value::Object(pairs) => pairs_body_len(pairs),
383 Amf0Value::Null | Amf0Value::Undefined => 0,
384 Amf0Value::EcmaArray(pairs) => U32_LEN + pairs_body_len(pairs),
385 Amf0Value::StrictArray(values) => {
386 U32_LEN + values.iter().map(Serialize::serialized_len).sum::<usize>()
387 }
388 }
389 + match self {
390 Amf0Value::Date(_) => DATE_RESERVED_LEN,
391 _ => 0,
392 }
393 }
394
395 fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
396 let written = self.serialized_len();
397 if buf.len() < written {
398 return Err(buffer_too_short(written, buf.len(), "amf0 value output"));
399 }
400 let (marker_byte, body) = buf[..written].split_at_mut(MARKER_LEN);
401 match self {
402 Amf0Value::Number(v) => {
403 marker_byte[0] = marker::NUMBER;
404 body[..NUMBER_LEN].copy_from_slice(&v.to_be_bytes());
405 }
406 Amf0Value::Boolean(v) => {
407 marker_byte[0] = marker::BOOLEAN;
408 body[0] = u8::from(*v);
409 }
410 Amf0Value::String(s) => {
411 if s.len() > usize::from(u16::MAX) {
412 return Err(RtmpError::Unsupported {
413 what: "amf0 string exceeds u16 length (use long string)",
414 });
415 }
416 marker_byte[0] = marker::STRING;
417 body[..U16_LEN].copy_from_slice(&(s.len() as u16).to_be_bytes());
418 body[U16_LEN..].copy_from_slice(s.as_bytes());
419 }
420 Amf0Value::LongString(s) => {
421 marker_byte[0] = marker::LONG_STRING;
422 let len = broadcast_common::len::fit_u32(s.len(), "amf0 long string length")?;
423 body[..U32_LEN].copy_from_slice(&len.to_be_bytes());
424 body[U32_LEN..].copy_from_slice(s.as_bytes());
425 }
426 Amf0Value::Object(pairs) => {
427 marker_byte[0] = marker::OBJECT;
428 write_pairs(pairs, body)?;
429 }
430 Amf0Value::Null => marker_byte[0] = marker::NULL,
431 Amf0Value::Undefined => marker_byte[0] = marker::UNDEFINED,
432 Amf0Value::EcmaArray(pairs) => {
433 marker_byte[0] = marker::ECMA_ARRAY;
434 let count = broadcast_common::len::fit_u32(pairs.len(), "amf0 ECMA array count")?;
435 body[..U32_LEN].copy_from_slice(&count.to_be_bytes());
436 write_pairs(pairs, &mut body[U32_LEN..])?;
437 }
438 Amf0Value::StrictArray(values) => {
439 marker_byte[0] = marker::STRICT_ARRAY;
440 let count =
441 broadcast_common::len::fit_u32(values.len(), "amf0 strict array count")?;
442 body[..U32_LEN].copy_from_slice(&count.to_be_bytes());
443 let mut offset = U32_LEN;
444 for v in values {
445 offset += v.serialize_into(&mut body[offset..])?;
446 }
447 }
448 Amf0Value::Date(v) => {
449 marker_byte[0] = marker::DATE;
450 body[..NUMBER_LEN].copy_from_slice(&v.to_be_bytes());
451 body[NUMBER_LEN..NUMBER_LEN + DATE_RESERVED_LEN].copy_from_slice(&[0, 0]);
452 }
453 }
454 Ok(written)
455 }
456}
457
458#[derive(Debug, Clone, PartialEq)]
467#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
468pub struct Command {
469 pub name: String,
472 pub transaction_id: f64,
475 pub arguments: Vec<Amf0Value>,
478}
479
480impl Command {
481 pub fn parse(payload: &[u8]) -> Result<Self> {
490 let name_value = Amf0Value::parse(payload)?;
491 let mut offset = name_value.serialized_len();
492 let name = match name_value {
493 Amf0Value::String(s) => s,
494 _ => {
495 return Err(RtmpError::Malformed {
496 what: "rtmp command name (expected amf0 string)",
497 });
498 }
499 };
500
501 let txn_value = Amf0Value::parse(&payload[offset..])?;
502 offset += txn_value.serialized_len();
503 let transaction_id = match txn_value {
504 Amf0Value::Number(n) => n,
505 _ => {
506 return Err(RtmpError::Malformed {
507 what: "rtmp command transaction id (expected amf0 number)",
508 });
509 }
510 };
511
512 let mut arguments = Vec::new();
513 while offset < payload.len() {
514 let value = Amf0Value::parse(&payload[offset..])?;
515 offset += value.serialized_len();
516 arguments.push(value);
517 }
518
519 Ok(Command {
520 name,
521 transaction_id,
522 arguments,
523 })
524 }
525
526 pub fn to_body(&self) -> Result<Vec<u8>> {
535 let mut out = Amf0Value::String(self.name.clone()).try_to_bytes()?;
536 out.extend(Amf0Value::Number(self.transaction_id).try_to_bytes()?);
537 for arg in &self.arguments {
538 out.extend(arg.try_to_bytes()?);
539 }
540 Ok(out)
541 }
542}
543
544pub fn amf0_values(values: &[Amf0Value]) -> Result<Vec<u8>> {
553 let len = values.iter().try_fold(0usize, |acc, value| {
554 acc.checked_add(value.serialized_len())
555 .ok_or(RtmpError::FieldOverflow(
556 broadcast_common::len::FieldOverflow {
557 field: "amf0 value sequence length",
558 value: u64::MAX,
559 max: u64::MAX,
560 },
561 ))
562 })?;
563 let mut out = alloc::vec![0u8; len];
564 let mut written = 0usize;
565 for value in values {
566 written += value.serialize_into(&mut out[written..])?;
567 }
568 Ok(out)
569}
570
571#[cfg(test)]
572mod tests {
573 use super::*;
574
575 fn round_trip(v: &Amf0Value) {
576 let bytes = v.try_to_bytes().unwrap();
577 assert_eq!(bytes.len(), v.serialized_len());
578 let parsed = Amf0Value::parse(&bytes).expect("parse");
579 assert_eq!(&parsed, v);
580 assert_eq!(parsed.try_to_bytes().unwrap(), bytes);
582 }
583
584 #[test]
585 fn a_value_sequence_encodes_each_value_in_order() {
586 let values = [
587 Amf0Value::String("onMetaData".to_string()),
588 Amf0Value::EcmaArray(vec![("duration".to_string(), Amf0Value::Number(1.5))]),
589 ];
590 let body = amf0_values(&values).expect("encode");
591 let mut expected = values[0].try_to_bytes().unwrap();
592 expected.extend(values[1].try_to_bytes().unwrap());
593 assert_eq!(body, expected);
594 }
595
596 #[test]
597 fn number_round_trips() {
598 round_trip(&Amf0Value::Number(0.0));
599 round_trip(&Amf0Value::Number(-1.5));
600 round_trip(&Amf0Value::Number(1_000_000.25));
601 }
602
603 #[test]
604 fn boolean_round_trips() {
605 round_trip(&Amf0Value::Boolean(true));
606 round_trip(&Amf0Value::Boolean(false));
607 }
608
609 #[test]
613 fn object_oversized_key_length_errors() {
614 let key = "k".repeat(65536);
615 let value = Amf0Value::Object(vec![(key, Amf0Value::Null)]);
616 let err = value.try_to_bytes().unwrap_err();
617 assert!(
618 matches!(
619 err,
620 RtmpError::FieldOverflow(broadcast_common::len::FieldOverflow {
621 field: "amf0 object key length",
622 ..
623 })
624 ),
625 "expected FieldOverflow for amf0 object key length, got {err:?}"
626 );
627 }
628
629 #[test]
633 fn string_beyond_the_16_bit_prefix_is_rejected() {
634 let value = Amf0Value::String("x".repeat(0x1_0000));
635 let err = value.try_to_bytes().unwrap_err();
636 assert!(
637 matches!(err, RtmpError::Unsupported { .. }),
638 "expected Unsupported for a 65 536-byte string, got {err:?}"
639 );
640 let boundary = Amf0Value::String("x".repeat(usize::from(u16::MAX)));
641 round_trip(&boundary);
642 }
643
644 #[test]
646 fn object_max_key_length_round_trips() {
647 let key = "k".repeat(65535);
648 round_trip(&Amf0Value::Object(vec![(key, Amf0Value::Null)]));
649 }
650
651 #[test]
652 fn string_round_trips_including_empty_and_multibyte() {
653 round_trip(&Amf0Value::String(String::new()));
654 round_trip(&Amf0Value::String("live".to_string()));
655 round_trip(&Amf0Value::String("héllo wörld 日本語".to_string()));
656 }
657
658 #[test]
659 fn null_and_undefined_round_trip() {
660 round_trip(&Amf0Value::Null);
661 round_trip(&Amf0Value::Undefined);
662 }
663
664 #[test]
665 fn date_round_trips() {
666 round_trip(&Amf0Value::Date(1_700_000_000_000.0));
667 }
668
669 #[test]
670 fn long_string_round_trips() {
671 round_trip(&Amf0Value::LongString("x".repeat(70_000)));
672 }
673
674 #[test]
675 fn object_round_trips_including_nested_object() {
676 round_trip(&Amf0Value::Object(vec![]));
677 round_trip(&Amf0Value::Object(vec![
678 ("app".to_string(), Amf0Value::String("live".to_string())),
679 ("audioSampleRate".to_string(), Amf0Value::Number(44100.0)),
680 ("live".to_string(), Amf0Value::Boolean(true)),
681 ]));
682 round_trip(&Amf0Value::Object(vec![(
685 "capabilities".to_string(),
686 Amf0Value::Object(vec![("videoCodecs".to_string(), Amf0Value::Number(252.0))]),
687 )]));
688 }
689
690 #[test]
691 fn ecma_array_round_trips() {
692 round_trip(&Amf0Value::EcmaArray(vec![]));
693 round_trip(&Amf0Value::EcmaArray(vec![
694 ("duration".to_string(), Amf0Value::Number(0.0)),
695 ("width".to_string(), Amf0Value::Number(1920.0)),
696 ]));
697 }
698
699 #[test]
700 fn strict_array_round_trips() {
701 round_trip(&Amf0Value::StrictArray(vec![]));
702 round_trip(&Amf0Value::StrictArray(vec![
703 Amf0Value::Number(1.0),
704 Amf0Value::String("two".to_string()),
705 Amf0Value::Boolean(false),
706 Amf0Value::Object(vec![("k".to_string(), Amf0Value::Null)]),
707 ]));
708 }
709
710 #[test]
711 fn ecma_array_count_is_informational_not_cross_checked() {
712 let mut bytes = vec![marker::ECMA_ARRAY];
716 bytes.extend_from_slice(&999u32.to_be_bytes()); bytes.extend_from_slice(&1u16.to_be_bytes());
718 bytes.extend_from_slice(b"k");
719 bytes.push(marker::NULL);
720 bytes.extend_from_slice(&[0, 0, marker::OBJECT_END]);
721
722 let parsed = Amf0Value::parse(&bytes).expect("parse");
723 assert_eq!(
724 parsed,
725 Amf0Value::EcmaArray(vec![("k".to_string(), Amf0Value::Null)])
726 );
727 }
728
729 #[test]
730 fn depth_guard_rejects_pathological_nesting_without_stack_overflow() {
731 let mut inner = vec![marker::NULL];
736 for _ in 0..(MAX_AMF0_DEPTH * 4) {
737 let mut wrapped = vec![marker::OBJECT];
738 wrapped.extend_from_slice(&1u16.to_be_bytes());
739 wrapped.push(b'a');
740 wrapped.extend_from_slice(&inner);
741 wrapped.extend_from_slice(&[0, 0, marker::OBJECT_END]);
742 inner = wrapped;
743 }
744
745 let result = Amf0Value::parse(&inner);
746 assert!(matches!(result, Err(RtmpError::Unsupported { .. })));
747 }
748
749 #[test]
750 fn depth_guard_allows_nesting_at_the_limit() {
751 let mut inner = vec![marker::NULL];
752 for _ in 0..(MAX_AMF0_DEPTH - 1) {
753 let mut wrapped = vec![marker::OBJECT];
754 wrapped.extend_from_slice(&1u16.to_be_bytes());
755 wrapped.push(b'a');
756 wrapped.extend_from_slice(&inner);
757 wrapped.extend_from_slice(&[0, 0, marker::OBJECT_END]);
758 inner = wrapped;
759 }
760 assert!(Amf0Value::parse(&inner).is_ok());
761 }
762
763 #[test]
764 fn dropping_object_end_marker_is_rejected() {
765 let full = Amf0Value::Object(vec![("k".to_string(), Amf0Value::Null)])
768 .try_to_bytes()
769 .unwrap();
770 let truncated = &full[..full.len() - 3];
771 assert!(matches!(
772 Amf0Value::parse(truncated),
773 Err(RtmpError::BufferTooShort(..))
774 ));
775 }
776
777 #[test]
778 fn mis_sized_string_length_is_rejected() {
779 let mut bytes = vec![marker::STRING];
782 bytes.extend_from_slice(&100u16.to_be_bytes()); bytes.extend_from_slice(b"short"); assert!(matches!(
785 Amf0Value::parse(&bytes),
786 Err(RtmpError::BufferTooShort(..))
787 ));
788 }
789
790 #[test]
791 fn invalid_utf8_string_is_malformed() {
792 let mut bytes = vec![marker::STRING];
793 bytes.extend_from_slice(&2u16.to_be_bytes());
794 bytes.extend_from_slice(&[0xFF, 0xFE]); assert!(matches!(
796 Amf0Value::parse(&bytes),
797 Err(RtmpError::Malformed { .. })
798 ));
799 }
800
801 #[test]
802 fn unsupported_marker_is_rejected_not_panicking() {
803 assert!(matches!(
804 Amf0Value::parse(&[0x11]), Err(RtmpError::Unsupported { .. })
806 ));
807 assert!(matches!(
808 Amf0Value::parse(&[0x07]), Err(RtmpError::Unsupported { .. })
810 ));
811 }
812
813 #[test]
814 fn date_rejects_nonzero_reserved_timezone() {
815 let mut bytes = vec![marker::DATE];
816 bytes.extend_from_slice(&0.0f64.to_be_bytes());
817 bytes.extend_from_slice(&1u16.to_be_bytes()); assert!(matches!(
819 Amf0Value::parse(&bytes),
820 Err(RtmpError::Malformed { .. })
821 ));
822 }
823
824 #[test]
825 fn empty_buffer_and_truncated_marker_are_buffer_too_short_not_panics() {
826 assert!(matches!(
827 Amf0Value::parse(&[]),
828 Err(RtmpError::BufferTooShort(..))
829 ));
830 assert!(matches!(
831 Amf0Value::parse(&[marker::NUMBER, 0, 0, 0]),
832 Err(RtmpError::BufferTooShort(..))
833 ));
834 }
835
836 fn connect_command() -> Command {
839 Command {
840 name: "connect".to_string(),
841 transaction_id: 1.0,
842 arguments: vec![Amf0Value::Object(vec![
843 ("app".to_string(), Amf0Value::String("live".to_string())),
844 (
845 "flashVer".to_string(),
846 Amf0Value::String("FMLE/3.0".to_string()),
847 ),
848 (
849 "tcUrl".to_string(),
850 Amf0Value::String("rtmp://example.test/live".to_string()),
851 ),
852 ("fpad".to_string(), Amf0Value::Boolean(false)),
853 ])],
854 }
855 }
856
857 fn publish_command() -> Command {
858 Command {
859 name: "publish".to_string(),
860 transaction_id: 5.0,
861 arguments: vec![
862 Amf0Value::Null,
863 Amf0Value::String("stream_key_123".to_string()),
864 Amf0Value::String("live".to_string()),
865 ],
866 }
867 }
868
869 #[test]
870 fn connect_command_round_trips_byte_identically() {
871 let cmd = connect_command();
872 let bytes = cmd.to_body().unwrap();
873 let parsed = Command::parse(&bytes).expect("parse connect");
874 assert_eq!(parsed, cmd);
875 assert_eq!(parsed.to_body().unwrap(), bytes);
876 }
877
878 #[test]
879 fn publish_command_round_trips_byte_identically() {
880 let cmd = publish_command();
881 let bytes = cmd.to_body().unwrap();
882 let parsed = Command::parse(&bytes).expect("parse publish");
883 assert_eq!(parsed, cmd);
884 assert_eq!(parsed.to_body().unwrap(), bytes);
885 }
886
887 #[test]
888 fn command_name_must_be_string() {
889 let bytes = Amf0Value::Number(1.0).try_to_bytes().unwrap();
890 assert!(matches!(
891 Command::parse(&bytes),
892 Err(RtmpError::Malformed { .. })
893 ));
894 }
895
896 #[test]
897 fn command_transaction_id_must_be_number() {
898 let mut bytes = Amf0Value::String("connect".to_string())
899 .try_to_bytes()
900 .unwrap();
901 bytes.extend(
902 Amf0Value::String("not a number".to_string())
903 .try_to_bytes()
904 .unwrap(),
905 );
906 assert!(matches!(
907 Command::parse(&bytes),
908 Err(RtmpError::Malformed { .. })
909 ));
910 }
911
912 #[test]
915 fn long_string_length_overflowing_usize_is_rejected_not_wrapped() {
916 let mut bytes = vec![marker::LONG_STRING];
921 bytes.extend_from_slice(&(u32::MAX - 1).to_be_bytes());
922 bytes.extend_from_slice(b"short");
923 let err = Amf0Value::parse(&bytes).unwrap_err();
924 assert!(matches!(
925 err,
926 RtmpError::Malformed { .. } | RtmpError::BufferTooShort(..)
927 ));
928 }
929
930 #[cfg(feature = "serde")]
933 #[test]
934 fn amf0_value_and_command_serde_round_trip() {
935 let value = Amf0Value::Object(vec![
936 ("app".to_string(), Amf0Value::String("live".to_string())),
937 ("live".to_string(), Amf0Value::Boolean(true)),
938 ("duration".to_string(), Amf0Value::Number(0.0)),
939 (
940 "items".to_string(),
941 Amf0Value::StrictArray(vec![Amf0Value::Null, Amf0Value::Undefined]),
942 ),
943 ]);
944 let json = serde_json::to_string(&value).expect("serialize Amf0Value");
945 let back: Amf0Value = serde_json::from_str(&json).expect("deserialize Amf0Value");
946 assert_eq!(back, value);
947
948 let cmd = publish_command();
949 let json = serde_json::to_string(&cmd).expect("serialize Command");
950 let back: Command = serde_json::from_str(&json).expect("deserialize Command");
951 assert_eq!(back, cmd);
952 }
953}