hang 0.21.19

Media over QUIC
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
//! This module contains the structs and functions for the MoQ catalog format
use crate::Result;
use crate::catalog::{Audio, Binary, Json, PRIORITY, Text, Video};
use serde::de::DeserializeOwned;

/// Maximum number of video, audio, and text renditions accepted in one catalog update.
pub const MAX_RENDITIONS: usize = 64;
use serde::{Deserialize, Serialize};

/// A catalog track, created by a broadcaster to describe the tracks available in a broadcast.
///
/// The base catalog carries the media sections (`video`, `audio`, `text`), the optional
/// `archive` (the segment index and any durable recording), the optional `clock` (the
/// broadcast's one wall-clock mapping), and the data sections
/// (`json`, `binary`) for application tracks that aren't media.
/// Applications extend it with their own root sections (e.g. `scte35`) through `E`. The catalog
/// does not deny unknown fields, so a base consumer ignores the extra sections and an extended
/// catalog stays wire-compatible. See the `extension_roundtrip` test.
///
/// Marked `#[non_exhaustive]` so a future base section can be added without bumping the major
/// version. External callers start from [`Catalog::default`] and fill in the sections they
/// publish; struct-literal construction (with or without `..base`) is not available outside
/// this crate.
#[serde_with::serde_as]
#[serde_with::skip_serializing_none]
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
#[serde(default, rename_all = "camelCase")]
#[serde(bound(serialize = "E: Serialize", deserialize = "E: DeserializeOwned + Default"))]
#[non_exhaustive]
pub struct Catalog<E = ()> {
	/// Video track information with multiple renditions.
	///
	/// Contains a map of video track renditions that the viewer can choose from
	/// based on their preferences (resolution, bitrate, codec, etc).
	#[serde(default)]
	pub video: Video,

	/// Audio track information with multiple renditions.
	///
	/// Contains a map of audio track renditions that the viewer can choose from
	/// based on their preferences (codec, bitrate, language, etc).
	#[serde(default)]
	pub audio: Audio,

	/// The broadcast's segment index and any durable archive, if the publisher offers one.
	/// See [`Archive`](crate::catalog::Archive) and the [`timeline`](crate::timeline) module.
	/// An undecodable entry is absent so incompatible archive metadata cannot reject media.
	#[serde_as(as = "serde_with::DefaultOnError<_>")]
	pub archive: Option<crate::catalog::Archive>,

	/// The broadcast's one continuous clock, if the publisher exposes one.
	///
	/// `wall` is the wall-clock time of PTS zero in `timescale` units since the moq epoch
	/// (2020-01-01); every media track and the archive index refer to this mapping after
	/// timescale conversion. Independent of [`archive`](Self::archive): a live-only publisher
	/// exposes its clock without creating a segment index. See
	/// [`Clock`](crate::catalog::Clock).
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub clock: Option<crate::catalog::Clock>,

	/// Text (caption/subtitle) track information with multiple renditions.
	///
	/// Contains a map of text track renditions that the viewer can choose from
	/// based on their preferences (language, role). Omitted from the wire when empty, so a
	/// broadcast without captions stays byte-identical to before this section existed.
	///
	/// A `text` value that isn't a caption section decodes as empty rather than failing the
	/// catalog, since applications could carry their own `text` key before this was reserved.
	#[serde(
		default,
		skip_serializing_if = "Text::is_empty",
		deserialize_with = "crate::catalog::deserialize_section"
	)]
	pub text: Text,

	/// JSON tracks: application data published as live JSON documents or logs.
	///
	/// Omitted from the wire when empty, so a media-only catalog is unchanged.
	///
	/// A `json` value that isn't a data-track section decodes as empty rather than failing the
	/// catalog, the same as [`text`](Self::text): `json` is a generic enough key that an
	/// application could have been carrying its own before this one was reserved, and losing the
	/// tracks we can't read beats losing the whole catalog.
	#[serde(
		default,
		skip_serializing_if = "Json::is_empty",
		deserialize_with = "crate::catalog::deserialize_section"
	)]
	pub json: Json,

	/// Binary tracks: application data published as opaque payloads.
	///
	/// Omitted from the wire when empty, so a media-only catalog is unchanged. Decoded leniently
	/// for the same reason as [`json`](Self::json).
	#[serde(
		default,
		skip_serializing_if = "Binary::is_empty",
		deserialize_with = "crate::catalog::deserialize_section"
	)]
	pub binary: Binary,

	/// Application-defined root sections, flattened alongside the base catalog sections.
	#[serde(flatten)]
	pub ext: E,
}

impl Catalog<()> {
	/// The default name for the catalog track.
	pub const DEFAULT_NAME: &str = "catalog.json";

	/// The track name for the DEFLATE-compressed catalog: the `.z` sibling of [`DEFAULT_NAME`](Self::DEFAULT_NAME).
	///
	/// Carries the identical catalog JSON, compressed per group (see `moq-json`). A publisher serves
	/// both tracks; a consumer reads whichever it prefers.
	pub const COMPRESSED_NAME: &str = "catalog.json.z";

	/// Track properties for creating the catalog track via
	/// [`create_track`](moq_net::broadcast::Producer::create_track) at
	/// [`DEFAULT_NAME`](Self::DEFAULT_NAME).
	///
	/// Keeps the bare `moq_net` retention rather than the media one: the catalog is
	/// snapshot mode, so the useful value is the live edge, which is always kept.
	pub fn default_track_info() -> moq_net::track::Info {
		moq_net::track::Info::default().with_priority(PRIORITY.catalog)
	}

	/// The subscription preferences used for the catalog track (high priority so
	/// it preempts media tracks).
	pub fn default_subscription() -> moq_net::track::Subscription {
		moq_net::track::Subscription::default().with_priority(PRIORITY.catalog)
	}
}

impl<E> Catalog<E> {
	/// Refuse a catalog with more renditions than a consumer can hold.
	pub fn check_renditions(&self) -> Result<()> {
		let count = self.video.renditions.len() + self.audio.renditions.len() + self.text.renditions.len();
		if count > MAX_RENDITIONS {
			return Err(crate::Error::TooManyRenditions {
				count,
				max: MAX_RENDITIONS,
			});
		}
		Ok(())
	}

	/// Copy the media sections into a catalog with no application extension.
	pub fn media(&self) -> Catalog<()> {
		Catalog {
			video: self.video.clone(),
			audio: self.audio.clone(),
			archive: self.archive.clone(),
			clock: self.clock,
			text: self.text.clone(),
			..Default::default()
		}
	}
}

impl<E: DeserializeOwned + Default> Catalog<E> {
	/// Subscribe to catalog updates on a broadcast.
	pub async fn subscribe(broadcast: &moq_net::broadcast::Consumer) -> Result<super::Consumer<E>> {
		let track = broadcast
			.track(Catalog::DEFAULT_NAME)?
			.subscribe(Catalog::default_subscription())
			.await?;
		Ok(super::Consumer::new(track))
	}

	/// Parse a catalog from a string.
	#[allow(clippy::should_implement_trait)]
	pub fn from_str(s: &str) -> Result<Self> {
		Ok(serde_json::from_str(s)?)
	}

	/// Parse a catalog from a slice of bytes.
	pub fn from_slice(v: &[u8]) -> Result<Self> {
		Ok(serde_json::from_slice(v)?)
	}

	/// Parse a catalog from a reader.
	pub fn from_reader(reader: impl std::io::Read) -> Result<Self> {
		Ok(serde_json::from_reader(reader)?)
	}
}

impl<E: Serialize> Catalog<E> {
	/// Serialize the catalog to a JSON string.
	pub fn to_json(&self) -> Result<String> {
		Ok(serde_json::to_string(self)?)
	}

	/// Serialize the catalog to a pretty-printed JSON string.
	pub fn to_json_pretty(&self) -> Result<String> {
		Ok(serde_json::to_string_pretty(self)?)
	}

	/// Serialize the catalog to a vector of bytes.
	pub fn to_vec(&self) -> Result<Vec<u8>> {
		Ok(serde_json::to_vec(self)?)
	}

	/// Serialize the catalog to a writer.
	pub fn to_writer(&self, writer: impl std::io::Write) -> Result<()> {
		Ok(serde_json::to_writer(writer, self)?)
	}
}

#[cfg(test)]
mod test {
	use std::collections::BTreeMap;

	use crate::catalog::{
		AudioCodec::Opus, AudioConfig, BinaryConfig, Compression, Container, H264, JsonConfig, Mode, VideoConfig,
	};

	use super::*;

	#[test]
	fn too_many_renditions_is_a_typed_refusal() {
		let mut catalog = Catalog::<()>::default();
		for i in 0..MAX_RENDITIONS {
			catalog
				.audio
				.renditions
				.insert(format!("audio{i}"), AudioConfig::new(Opus, 48_000, 2));
		}
		assert!(catalog.check_renditions().is_ok());
		catalog
			.audio
			.renditions
			.insert("one-more".into(), AudioConfig::new(Opus, 48_000, 2));
		assert!(matches!(
			catalog.check_renditions(),
			Err(crate::Error::TooManyRenditions {
				count: 65,
				max: MAX_RENDITIONS
			})
		));
	}

	#[test]
	fn simple() {
		let mut encoded = r#"{
			"video": {
				"renditions": {
					"video": {
						"codec": "avc1.64001f",
						"codedWidth": 1280,
						"codedHeight": 720,
						"bitrate": 6000000,
						"framerate": 30.0,
						"container": {"kind": "legacy"}
					}
				}
			},
			"audio": {
				"renditions": {
					"audio": {
						"codec": "opus",
						"sampleRate": 48000,
						"numberOfChannels": 2,
						"bitrate": 128000,
						"container": {"kind": "legacy"}
					}
				}
			}
		}"#
		.to_string();

		encoded.retain(|c| !c.is_whitespace());

		let mut video_config = VideoConfig::new(H264 {
			profile: 0x64,
			constraints: 0x00,
			level: 0x1f,
			inline: false,
		});
		video_config.coded_width = Some(1280);
		video_config.coded_height = Some(720);
		video_config.bitrate = Some(6_000_000);
		video_config.framerate = Some(30.0);
		video_config.container = Container::Legacy;

		let mut video_renditions = BTreeMap::new();
		video_renditions.insert("video".to_string(), video_config);

		let mut audio_config = AudioConfig::new(Opus, 48_000, 2);
		audio_config.bitrate = Some(128_000);
		audio_config.container = Container::Legacy;

		let mut audio_renditions = BTreeMap::new();
		audio_renditions.insert("audio".to_string(), audio_config);

		let mut decoded = Catalog::<()>::default();
		decoded.video.renditions = video_renditions;
		decoded.audio.renditions = audio_renditions;

		let output = Catalog::<()>::from_str(&encoded).expect("failed to decode");
		assert_eq!(decoded, output, "wrong decoded output");

		let output = decoded.to_json().expect("failed to encode");
		assert_eq!(encoded, output, "wrong encoded output");
	}

	/// Lock in the on-wire shape of the jitter and delay fields: a bare integer number
	/// of milliseconds. If `Option<Duration>` ever loses the `duration_millis`
	/// serde adapter, this regresses to serde's default `{secs, nanos}` shape.
	#[test]
	fn jitter_and_delay_serialized_as_millis() {
		let mut encoded = r#"{
			"video": {
				"renditions": {
					"video": {
						"codec": "avc1.64001f",
						"container": {"kind": "legacy"},
						"jitter": 100,
						"delay": 200
					}
				}
			},
			"audio": {
				"renditions": {
					"audio": {
						"codec": "opus",
						"sampleRate": 48000,
						"numberOfChannels": 2,
						"container": {"kind": "legacy"},
						"jitter": 40
					}
				}
			}
		}"#
		.to_string();
		encoded.retain(|c| !c.is_whitespace());

		let mut video_renditions = BTreeMap::new();
		video_renditions.insert(
			"video".to_string(),
			VideoConfig {
				broadcast: None,
				label: None,
				codec: H264 {
					profile: 0x64,
					constraints: 0x00,
					level: 0x1f,
					inline: false,
				}
				.into(),
				description: None,
				coded_width: None,
				coded_height: None,
				display_aspect_width: None,
				display_aspect_height: None,
				bitrate: None,
				stalled: None,
				framerate: None,
				optimize_for_latency: None,
				container: Container::Legacy,
				jitter: Some(std::time::Duration::from_millis(100)),
				delay: Some(std::time::Duration::from_millis(200)),
			},
		);

		let mut audio_renditions = BTreeMap::new();
		audio_renditions.insert(
			"audio".to_string(),
			AudioConfig {
				broadcast: None,
				label: None,
				codec: Opus,
				sample_rate: 48_000,
				channel_count: 2,
				bitrate: None,
				description: None,
				container: Container::Legacy,
				jitter: Some(std::time::Duration::from_millis(40)),
				delay: None,
			},
		);

		let mut catalog = Catalog::<()>::default();
		catalog.video.renditions = video_renditions;
		catalog.audio.renditions = audio_renditions;

		let decoded = Catalog::<()>::from_str(&encoded).expect("failed to decode");
		assert_eq!(catalog, decoded, "decode mismatch");

		let output = catalog.to_json().expect("failed to encode");
		assert_eq!(encoded, output, "encode mismatch");
	}

	#[test]
	fn rendition_with_broadcast_override() {
		// Decode a catalog where one rendition references a track in a sibling broadcast,
		// and verify the `broadcast` field round-trips through serde.
		let encoded = r#"{
			"video": {
				"renditions": {
					"video": {
						"broadcast": "./source",
						"codec": "avc1.64001f",
						"codedWidth": 1280,
						"codedHeight": 720,
						"container": {"kind": "legacy"}
					}
				}
			}
		}"#;

		let parsed = Catalog::<()>::from_str(encoded).expect("failed to decode");
		let rendition = parsed.video.renditions.get("video").expect("missing rendition");
		assert_eq!(
			rendition.broadcast.as_ref().map(|p| p.as_str()),
			Some("source"),
			"broadcast field did not deserialize"
		);

		// Full encode -> decode -> equality, so the test catches any encoder regression
		// (e.g. wrong key, double-emission, or `null` instead of skip).
		let output = parsed.to_json().expect("failed to encode");
		let reparsed = Catalog::<()>::from_str(&output).expect("failed to re-decode");
		assert_eq!(parsed, reparsed, "re-encoded catalog did not round-trip");
	}

	#[test]
	fn rendition_without_broadcast_omits_field() {
		// `broadcast: None` must NOT serialize as `"broadcast":null`, otherwise the wire
		// format silently changes for every catalog that doesn't use cross-broadcast refs.
		let mut video_config = VideoConfig::new(H264 {
			profile: 0x64,
			constraints: 0x00,
			level: 0x1f,
			inline: false,
		});
		video_config.container = Container::Legacy;

		let mut renditions = BTreeMap::new();
		renditions.insert("video".to_string(), video_config);

		let catalog = Catalog::<()> {
			video: Video {
				renditions,
				..Default::default()
			},
			..Default::default()
		};

		let output = catalog.to_json().expect("failed to encode");
		assert!(
			!output.contains("broadcast"),
			"broadcast field leaked into JSON when None: {output}"
		);
	}

	#[test]
	fn rendition_with_empty_broadcast_normalizes() {
		// An empty-string broadcast field should normalize to an empty `path::Relative` so the
		// consumer can treat it identically to a missing field.
		let encoded = r#"{
			"video": {
				"renditions": {
					"video": {
						"broadcast": "",
						"codec": "avc1.64001f",
						"container": {"kind": "legacy"}
					}
				}
			}
		}"#;

		let parsed = Catalog::<()>::from_str(encoded).expect("failed to decode");
		let rendition = parsed.video.renditions.get("video").expect("missing rendition");
		assert_eq!(
			rendition.broadcast.as_ref().map(|p| p.is_empty()),
			Some(true),
			"empty broadcast should deserialize as Some(empty)"
		);
	}

	#[test]
	fn rendition_with_parent_broadcast_stays_distinct_from_empty() {
		let encoded = r#"{
			"video": {
				"renditions": {
					"video": {
						"broadcast": ".",
						"codec": "avc1.64001f",
						"container": {"kind": "legacy"}
					}
				}
			}
		}"#;

		let parsed = Catalog::<()>::from_str(encoded).expect("failed to decode");
		let rendition = parsed.video.renditions.get("video").expect("missing rendition");
		assert_eq!(
			rendition.broadcast.as_ref().map(|p| p.as_str()),
			Some("."),
			"parent reference should not normalize to empty"
		);
	}

	#[test]
	fn unknown_container_keeps_siblings() {
		// A rendition using a future container must not take down the rest of the catalog.
		let encoded = r#"{
			"video": {
				"renditions": {
					"future": {
						"codec": "avc1.64001f",
						"container": {"kind": "future", "magic": 7}
					},
					"legacy": {
						"codec": "avc1.64001f",
						"codedWidth": 1280,
						"codedHeight": 720,
						"container": {"kind": "legacy"}
					}
				}
			}
		}"#;

		let parsed = Catalog::<()>::from_str(encoded).expect("failed to decode");

		let known = parsed.video.renditions.get("legacy").expect("missing rendition");
		assert_eq!(known.container, Container::Legacy);
		assert_eq!(known.coded_width, Some(1280));

		let future = parsed.video.renditions.get("future").expect("missing rendition");
		let Container::Unknown(unknown) = &future.container else {
			panic!("expected unknown container: {:?}", future.container);
		};
		assert_eq!(unknown.kind(), Some("future"));

		// The unknown rendition survives a republish intact.
		let output = parsed.to_json().expect("failed to encode");
		let reparsed = Catalog::<()>::from_str(&output).expect("failed to re-decode");
		assert_eq!(parsed, reparsed, "re-encoded catalog did not round-trip");
		assert!(output.contains(r#""magic":7"#), "unknown fields dropped: {output}");
	}

	#[test]
	fn empty_text_section_omitted() {
		// A catalog without captions must stay byte-identical to before the text section existed:
		// the empty section is skipped, unlike the always-present video/audio sections.
		let catalog = Catalog::<()>::default();
		let output = catalog.to_json().expect("failed to encode");
		assert!(!output.contains("text"), "empty text section leaked: {output}");
	}

	#[test]
	fn text_section_roundtrip() {
		use crate::catalog::{Text, TextConfig, TextFormat, TextRole};

		let mut config = TextConfig::new(TextFormat::Vtt);
		config.role = TextRole::Caption;
		config.lang = Some("en".to_string());

		let mut text = Text::default();
		text.insert("captions.en", config).expect("insert");

		let catalog = Catalog::<()> {
			text,
			..Default::default()
		};

		let json = catalog.to_json().expect("failed to encode");
		assert!(json.contains("\"text\""), "text section missing: {json}");

		let decoded = Catalog::<()>::from_str(&json).expect("failed to decode");
		assert_eq!(catalog, decoded, "text section did not round-trip");
	}

	#[test]
	fn legacy_text_section_keeps_the_catalog() {
		// `text` was an ordinary application section before captions reserved it, so a value with
		// the wrong shape must cost its captions and nothing else. Audio and video keep playing.
		for legacy in [
			r#""a caption overlay""#,
			r#"["a","b"]"#,
			r#"{"overlay":{"x":1}}"#,
			r#"{"renditions":42}"#,
		] {
			let json = format!(r#"{{"video":{{"renditions":{{}}}},"audio":{{"renditions":{{}}}},"text":{legacy}}}"#);
			let catalog =
				Catalog::<()>::from_str(&json).unwrap_or_else(|e| panic!("legacy text {legacy} broke it: {e}"));
			assert!(catalog.text.is_empty(), "legacy text {legacy} decoded as captions");
		}
	}

	/// The counterpart to the above: the fallback covers someone else's key, not our own bugs. A
	/// value that *is* a text section still has to decode, or a rendition with no format would
	/// silently cost a publisher every caption it advertised.
	#[test]
	fn a_malformed_text_section_still_fails() {
		let json = r#"{"text":{"renditions":{"captions":{"container":{"kind":"legacy"}}}}}"#;
		assert!(
			Catalog::<()>::from_str(json).is_err(),
			"a format-less text rendition decoded instead of failing"
		);
	}

	#[test]
	fn unknown_text_role_keeps_the_catalog() {
		// A future `role` value must not take down the whole catalog: audio and video have to keep
		// playing even when a caption rendition is classified with a vocabulary we don't know yet.
		let json = r#"{"video":{"renditions":{}},"audio":{"renditions":{}},"text":{"renditions":{"subs":{"format":"vtt","role":"commentary"}}}}"#;

		let catalog = Catalog::<()>::from_str(json).expect("unknown role rejected the catalog");
		assert_eq!(catalog.text.renditions.len(), 1);
		let encoded = catalog.to_json().expect("failed to encode unknown role");
		assert!(
			encoded.contains(r#""role":"commentary""#),
			"unknown role was not preserved: {encoded}"
		);
	}

	/// A section name is only reserved from the version that defines it, and `json` and `binary` are
	/// generic enough that an application could already be using one. Dropping the section we can't
	/// read keeps video and audio playable, instead of failing the whole catalog over that key.
	#[test]
	fn a_foreign_data_section_does_not_fail_the_catalog() {
		for section in ["json", "binary"] {
			let wire = format!(r#"{{"video":{{"renditions":{{}}}},"{section}":{{"messages":"chat"}}}}"#);
			let catalog =
				Catalog::<()>::from_str(&wire).unwrap_or_else(|err| panic!("{section} took the catalog down: {err}"));
			assert!(catalog.json.is_empty(), "{section}");
			assert!(catalog.binary.is_empty(), "{section}");
		}
	}

	/// The counterpart to the above: the fallback covers someone else's key, not our own bugs. A
	/// value that *is* a data section still has to decode, or a mode-less track would silently cost
	/// a publisher every data track it advertised.
	#[test]
	fn a_malformed_data_section_still_fails() {
		for section in ["json", "binary"] {
			let wire = format!(r#"{{"{section}":{{"tracks":{{"chat":{{"compression":"deflate"}}}}}}}}"#);
			assert!(
				Catalog::<()>::from_str(&wire).is_err(),
				"a mode-less {section} track decoded instead of failing"
			);
		}
	}

	#[test]
	fn data_sections_stay_off_the_wire_when_empty() {
		// A media-only catalog must serialize exactly as it did before the data sections existed,
		// or every existing publisher's bytes change.
		let output = Catalog::<()>::default().to_json().expect("failed to encode");
		assert_eq!(output, r#"{"video":{"renditions":{}},"audio":{"renditions":{}}}"#);
	}

	#[test]
	fn clock_roundtrips_at_the_root() {
		let clock =
			crate::catalog::Clock::new(moq_net::Timestamp::from_micros(1_751_846_400_000_000).unwrap()).unwrap();
		let catalog = Catalog::<()> {
			clock: Some(clock),
			..Default::default()
		};

		let json = catalog.to_json().expect("failed to encode");
		assert!(json.contains(r#""clock":{"wall":1751846400000000"#), "{json}");
		assert_eq!(
			Catalog::<()>::from_str(&json).expect("failed to decode").clock,
			Some(clock)
		);
	}

	#[test]
	fn clock_stays_off_the_wire_when_absent() {
		// A catalog without a clock serializes exactly as before the section existed.
		let output = Catalog::<()>::default().to_json().expect("failed to encode");
		assert_eq!(output, r#"{"video":{"renditions":{}},"audio":{"renditions":{}}}"#);
	}

	#[test]
	fn packaged_clock_fixture_decodes() {
		// The canonical new shape: the root clock plus an archive without a wall field.
		// A reader maps archive timestamps through the root clock after timescale conversion.
		let json = include_str!("../../fixtures/catalog-clock.json");
		let catalog = Catalog::<()>::from_str(json).expect("the packaged fixture must decode");

		let clock = catalog.clock.expect("the fixture carries a root clock");
		assert_eq!(clock.wall.scale().as_u64(), 1_000_000);

		let archive = catalog.archive.expect("the fixture carries an archive");
		assert_eq!(archive.track, "timeline.z");
		assert_eq!(archive.timescale, 1000);

		// Archive PTS 2000 (ms) lands 2s after the wall epoch, whatever the track timescale.
		let expected = std::time::UNIX_EPOCH
			+ std::time::Duration::from_millis(crate::catalog::MOQ_EPOCH_UNIX_MILLIS + 1_751_846_402_000);
		assert_eq!(
			clock
				.wall_clock(moq_net::Timestamp::from_scale(2000, archive.timescale as u64).unwrap())
				.unwrap(),
			expected
		);
	}

	#[test]
	fn archive_roundtrips_at_the_root() {
		let mut archive = crate::catalog::Archive::new("timeline.z");
		archive.duration_max = Some(2000);
		archive.replay = Some(moq_net::path::RelativeOwned::new("recordings/clip"));
		archive.version = Some(crate::catalog::Archive::VERSION);

		let catalog = Catalog::<()> {
			archive: Some(archive.clone()),
			..Default::default()
		};

		let json = catalog.to_json().expect("failed to encode");
		assert!(json.contains(r#""archive":{"track":"timeline.z""#), "{json}");
		assert!(
			!json.contains(r#""timeline":"#),
			"the old root key must not appear: {json}"
		);
		assert_eq!(
			Catalog::<()>::from_str(&json).expect("failed to decode").archive,
			Some(archive)
		);
	}

	#[test]
	fn an_incompatible_archive_leaves_media_playable() {
		let video = serde_json::json!({
			"renditions": {"video": {"codec": "avc1.64001f", "container": {"kind": "legacy"}}}
		});
		let media = Catalog::<()>::from_str(&serde_json::json!({"video": video}).to_string()).unwrap();
		for archive in [
			serde_json::json!({"timelines": {"video": "video.timeline.z"}, "timescale": 1000}),
			serde_json::json!({"track": "timeline.z", "store": "not a url"}),
			serde_json::json!({"track": 42}),
			serde_json::json!({"future": "archive"}),
			serde_json::json!("archive"),
			serde_json::json!([]),
			serde_json::Value::Null,
		] {
			let json = serde_json::json!({"video": video, "archive": archive}).to_string();
			let catalog = Catalog::<()>::from_str(&json).expect("archive metadata must not reject media");
			assert_eq!(catalog.archive, None);
			assert_eq!(catalog.video, media.video);
			assert!(!catalog.to_json().unwrap().contains("\"archive\""));
		}
	}

	#[test]
	fn an_incompatible_archive_does_not_hide_invalid_media() {
		Catalog::<()>::from_str(
			r#"{"archive":{"timelines":{}},"video":{"renditions":{"video":{"codec":42,"container":{"kind":"legacy"}}}}}"#,
		)
		.expect_err("invalid media must still reject the catalog");
	}

	#[test]
	fn a_legacy_root_timeline_is_not_an_archive() {
		// No alias or fallback: a catalog that still names `timeline` at the root has no archive.
		let catalog =
			Catalog::<()>::from_str(r#"{"timeline":{"track":"timeline.z"}}"#).expect("legacy timeline broke decode");
		assert_eq!(catalog.archive, None);
	}

	#[test]
	fn data_tracks_roundtrip() {
		let mut encoded = r#"{
			"video": {"renditions": {}},
			"audio": {"renditions": {}},
			"json": {
				"tracks": {
					"chat": {
						"mode": "stream",
						"compression": "deflate",
						"schema": "https://example.com/chat.schema.json"
					},
					"status": {
						"broadcast": "source",
						"mode": "snapshot"
					}
				}
			},
			"binary": {
				"tracks": {
					"thumbnail": {
						"mode": "snapshot",
						"mime": "image/jpeg"
					}
				}
			}
		}"#
		.to_string();
		encoded.retain(|c| !c.is_whitespace());

		let mut chat = JsonConfig::new(Mode::Stream);
		chat.compression = Some(Compression::Deflate);
		chat.schema = Some("https://example.com/chat.schema.json".to_string());

		let mut status = JsonConfig::new(Mode::Snapshot);
		status.broadcast = Some(moq_net::path::RelativeOwned::new("source"));

		let mut thumbnail = BinaryConfig::new(Mode::Snapshot);
		thumbnail.mime = Some("image/jpeg".to_string());

		let mut catalog = Catalog::<()>::default();
		catalog.json.insert("chat", chat).unwrap();
		catalog.json.insert("status", status).unwrap();
		catalog.binary.insert("thumbnail", thumbnail).unwrap();

		let decoded = Catalog::<()>::from_str(&encoded).expect("failed to decode");
		assert_eq!(decoded, catalog, "decode mismatch");

		let output = catalog.to_json().expect("failed to encode");
		assert_eq!(output, encoded, "encode mismatch");
	}

	/// Data tracks carry the same optional `bitrate` and whole-millisecond `jitter` and `delay` as
	/// media.
	#[test]
	fn data_track_bitrate_and_jitter() {
		let encoded = r#"{"video":{"renditions":{}},"audio":{"renditions":{}},"json":{"tracks":{"gps":{"mode":"stream","bitrate":8000,"jitter":100,"delay":250}}},"binary":{"tracks":{"frames":{"mode":"snapshot","bitrate":64000,"jitter":34}}}}"#;

		let mut gps = JsonConfig::new(Mode::Stream);
		gps.bitrate = Some(8_000);
		gps.jitter = Some(std::time::Duration::from_millis(100));
		gps.delay = Some(std::time::Duration::from_micros(249_001));

		let mut frames = BinaryConfig::new(Mode::Snapshot);
		frames.bitrate = Some(64_000);
		frames.jitter = Some(std::time::Duration::from_micros(33_334));

		let mut catalog = Catalog::<()>::default();
		catalog.json.insert("gps", gps).unwrap();
		catalog.binary.insert("frames", frames).unwrap();

		assert_eq!(
			catalog.to_json().unwrap(),
			encoded,
			"jitter rounds up to whole milliseconds"
		);

		let decoded = Catalog::<()>::from_str(encoded).unwrap();
		assert_eq!(
			decoded.binary.tracks["frames"].jitter,
			Some(std::time::Duration::from_millis(34))
		);
		assert_eq!(decoded.json.tracks["gps"].bitrate, Some(8_000));
		assert_eq!(
			decoded.json.tracks["gps"].delay,
			Some(std::time::Duration::from_millis(250))
		);
	}

	/// An application lists a data track in its own section by flattening a data config beside its
	/// own fields, so the reading rules and the application's fields share one entry.
	#[test]
	fn a_data_config_flattens_into_an_application_entry() {
		#[derive(Serialize, Deserialize, PartialEq, Debug, Clone)]
		struct Mavlink {
			#[serde(flatten)]
			binary: BinaryConfig,
			sysid: u8,
		}

		#[derive(Serialize, Deserialize, PartialEq, Debug, Default, Clone)]
		struct Ext {
			#[serde(rename = "com.example.mavlink", default)]
			mavlink: BTreeMap<String, Mavlink>,
		}

		let encoded = r#"{"video":{"renditions":{}},"audio":{"renditions":{}},"com.example.mavlink":{"telemetry":{"mode":"stream","compression":"deflate","sysid":1}}}"#;

		let catalog = Catalog::<Ext>::from_str(encoded).unwrap();
		let entry = &catalog.ext.mavlink["telemetry"];
		assert_eq!(entry.sysid, 1);
		assert_eq!(entry.binary.mode, Mode::Stream);
		assert_eq!(entry.binary.compression, Some(Compression::Deflate));
		assert!(
			entry.binary.extra.is_empty(),
			"the application's own fields are not unknown data-track fields"
		);
		assert_eq!(catalog.to_json().unwrap(), encoded);
	}

	/// A track using a future mode or compression must survive a reparse-and-republish intact, so a
	/// relay doesn't corrupt what it can't read. Its siblings stay readable.
	#[test]
	fn unknown_mode_and_compression_keep_siblings() {
		let encoded = r#"{
			"json": {
				"tracks": {
					"future": {"mode": "windowed", "compression": "zstd"},
					"known": {"mode": "stream", "compression": "deflate"}
				}
			}
		}"#;

		let parsed = Catalog::<()>::from_str(encoded).expect("failed to decode");

		let known = parsed.json.tracks.get("known").expect("missing track");
		assert_eq!(known.mode, Mode::Stream);
		assert_eq!(known.compression, Some(Compression::Deflate));

		let future = parsed.json.tracks.get("future").expect("missing track");
		assert_eq!(future.mode, Mode::Unknown("windowed".to_string()));
		assert_eq!(future.compression, Some(Compression::Unknown("zstd".to_string())));

		let output = parsed.to_json().expect("failed to encode");
		assert!(
			output.contains(r#""mode":"windowed""#),
			"unknown mode dropped: {output}"
		);
		let reparsed = Catalog::<()>::from_str(&output).expect("failed to re-decode");
		assert_eq!(parsed, reparsed, "re-encoded catalog did not round-trip");
	}

	/// Preserving the mode string alone is not enough: a future mode comes with fields describing
	/// it, and a relay that reparsed and republished would otherwise strip them, leaving an entry
	/// nothing can act on.
	#[test]
	fn unknown_mode_fields_round_trip() {
		let encoded = r#"{"json":{"tracks":{"future":{"mode":"windowed","window":10}}}}"#;

		let parsed = Catalog::<()>::from_str(encoded).expect("failed to decode");
		let future = parsed.json.tracks.get("future").expect("missing track");
		assert_eq!(future.mode, Mode::Unknown("windowed".to_string()));
		assert_eq!(future.extra.get("window"), Some(&serde_json::json!(10)));

		let output = parsed.to_json().expect("failed to encode");
		assert!(output.contains(r#""window":10"#), "unknown fields dropped: {output}");
		assert_eq!(Catalog::<()>::from_str(&output).expect("re-decode"), parsed);
	}

	/// There is no safe default: reading a stream as a snapshot silently drops every record but the
	/// last, so an entry without a mode is malformed rather than assumed.
	#[test]
	fn a_track_without_a_mode_is_rejected() {
		Catalog::<()>::from_str(r#"{"json":{"tracks":{"chat":{"compression":"deflate"}}}}"#)
			.expect_err("a mode-less track must not decode");
	}

	#[test]
	fn duplicate_data_track_names_are_rejected() {
		let mut catalog = Catalog::<()>::default();
		catalog.json.insert("chat", JsonConfig::new(Mode::Stream)).unwrap();
		assert!(matches!(
			catalog.json.insert("chat", JsonConfig::new(Mode::Snapshot)),
			Err(crate::Error::Duplicate(_))
		));

		// The two sections are separate namespaces on the wire, so the same name in each is fine.
		catalog.binary.insert("chat", BinaryConfig::new(Mode::Stream)).unwrap();
	}

	#[test]
	fn extension_roundtrip() {
		// An application extends the catalog with its own root section by flattening Catalog.
		#[derive(Serialize, Deserialize, PartialEq, Debug)]
		struct AppCatalog {
			#[serde(flatten)]
			base: Catalog,
			#[serde(skip_serializing_if = "Option::is_none")]
			scte35: Option<Scte35>,
		}

		#[derive(Serialize, Deserialize, PartialEq, Debug)]
		struct Scte35 {
			splice_id: u32,
		}

		let app = AppCatalog {
			base: Catalog::<()>::default(),
			scte35: Some(Scte35 { splice_id: 42 }),
		};

		let json = serde_json::to_string(&app).expect("failed to encode");

		// A base consumer ignores the unknown section.
		let base = Catalog::<()>::from_str(&json).expect("failed to decode base");
		assert_eq!(base, Catalog::<()>::default());

		// The extended consumer round-trips its own section.
		let decoded: AppCatalog = serde_json::from_str(&json).expect("failed to decode app");
		assert_eq!(decoded, app);
	}
}