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