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