moq-mux 0.10.13

Media muxers and demuxers for MoQ
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
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
use std::marker::PhantomData;
use std::time::Duration;

use super::Estimate;
use super::Producer;
use super::hang::{Catalog, CatalogExt};

/// A catalog config that can be published as a named rendition.
///
/// Implement it on your own config type to get the full catalog lifecycle: reservation gating,
/// removal on drop, and optional jitter/bitrate detection. [`VideoConfig`](hang::catalog::VideoConfig)
/// and [`AudioConfig`](hang::catalog::AudioConfig) implement it for every extension; a custom
/// config implements it for the one [`CatalogExt`] that holds it. Publish a media track under it
/// with [`Reserved::track`], or a data track with [`Producer::binary_stream`] and the like when it
/// embeds a data config (see [`IntoRendition`](super::IntoRendition)):
///
/// ```
/// # use std::collections::BTreeMap;
/// # use hang::catalog::{BinaryConfig, Mode};
/// # use moq_mux::catalog::{Estimate, RenditionConfig};
/// # use moq_mux::catalog::hang::{Catalog, CatalogExt};
/// # use serde::{Deserialize, Serialize};
/// #[derive(Serialize, Deserialize, Clone, Default)]
/// struct Ext {
///     #[serde(rename = "com.example.mavlink", default)]
///     mavlink: BTreeMap<String, Mavlink>,
/// }
/// impl CatalogExt for Ext {}
///
/// #[derive(Serialize, Deserialize, Clone)]
/// struct Mavlink {
///     #[serde(flatten)]
///     binary: BinaryConfig,
///     sysid: u8,
/// }
///
/// impl AsMut<BinaryConfig> for Mavlink {
///     fn as_mut(&mut self) -> &mut BinaryConfig {
///         &mut self.binary
///     }
/// }
///
/// impl RenditionConfig<Ext> for Mavlink {
///     fn insert(self, catalog: &mut Catalog<Ext>, name: &str) {
///         catalog.ext.mavlink.insert(name.to_string(), self);
///     }
///     fn get_mut<'a>(catalog: &'a mut Catalog<Ext>, name: &str) -> Option<&'a mut Self> {
///         catalog.ext.mavlink.get_mut(name)
///     }
///     fn remove(catalog: &mut Catalog<Ext>, name: &str) {
///         catalog.ext.mavlink.remove(name);
///     }
///
///     // Opt into detection through the embedded config.
///     fn detects() -> bool {
///         true
///     }
///     fn estimate(&self) -> Estimate {
///         Estimate::default()
///             .with_bitrate(self.binary.bitrate)
///             .with_jitter(self.binary.jitter)
///             .with_delay(self.binary.delay)
///     }
///     fn set_estimate(&mut self, estimate: Estimate) {
///         self.binary.bitrate = estimate.bitrate;
///         self.binary.jitter = estimate.jitter;
///         self.binary.delay = estimate.delay;
///     }
/// }
///
/// # fn example(
/// #     broadcast: &mut moq_net::broadcast::Producer,
/// #     catalog: &moq_mux::catalog::Producer<Ext>,
/// # ) -> moq_mux::Result<()> {
/// let track = broadcast.create_track("telemetry", None)?;
/// // The producer fixes the mode, so the one passed here is only a placeholder.
/// let entry = Mavlink { binary: BinaryConfig::new(Mode::Stream), sysid: 1 };
/// let mut telemetry = catalog.binary_stream(track, entry)?;
/// telemetry.append(&b"\xfd..."[..])?;
/// # Ok(())
/// # }
/// ```
///
/// Note that `insert` takes the whole [`Catalog`], not just the extension, so the built-in media
/// configs use the same trait. Writing to `catalog.video` / `catalog.audio` / `catalog.text` from a
/// custom config fights the media pipeline for those sections; stay in your own.
///
/// [`Reserved::track`] and [`Producer::track`](super::Producer::track) enroll the track in the
/// broadcast timeline, measure it, and keep its estimate current automatically.
pub trait RenditionConfig<E: CatalogExt>: Clone + Send + 'static {
	/// Whether container or data-track writes should update this config's estimate fields.
	fn detects() -> bool {
		false
	}

	/// Insert or replace this config under `name`.
	fn insert(self, catalog: &mut Catalog<E>, name: &str);

	/// Borrow the config stored under `name`, if it's present.
	fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self>;

	/// Remove the config stored under `name`.
	fn remove(catalog: &mut Catalog<E>, name: &str);

	/// The config's current [`Estimate`] fields. Defaults to none, disabling detection.
	fn estimate(&self) -> Estimate {
		Estimate::default()
	}

	/// Replace the config's [`Estimate`] fields. Defaults to discarding them.
	fn set_estimate(&mut self, _estimate: Estimate) {}
}

impl<E: CatalogExt> RenditionConfig<E> for hang::catalog::JsonConfig {
	fn insert(self, catalog: &mut Catalog<E>, name: &str) {
		catalog.json.tracks.insert(name.to_string(), self);
	}
	fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self> {
		catalog.json.tracks.get_mut(name)
	}
	fn remove(catalog: &mut Catalog<E>, name: &str) {
		catalog.json.tracks.remove(name);
	}

	fn detects() -> bool {
		true
	}
	fn estimate(&self) -> Estimate {
		Estimate::default()
			.with_jitter(self.jitter)
			.with_bitrate(self.bitrate)
			.with_delay(self.delay)
	}
	fn set_estimate(&mut self, estimate: Estimate) {
		self.jitter = estimate.jitter;
		self.bitrate = estimate.bitrate;
		self.delay = estimate.delay;
	}
}

impl<E: CatalogExt> RenditionConfig<E> for hang::catalog::BinaryConfig {
	fn insert(self, catalog: &mut Catalog<E>, name: &str) {
		catalog.binary.tracks.insert(name.to_string(), self);
	}
	fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self> {
		catalog.binary.tracks.get_mut(name)
	}
	fn remove(catalog: &mut Catalog<E>, name: &str) {
		catalog.binary.tracks.remove(name);
	}

	fn detects() -> bool {
		true
	}
	fn estimate(&self) -> Estimate {
		Estimate::default()
			.with_jitter(self.jitter)
			.with_bitrate(self.bitrate)
			.with_delay(self.delay)
	}
	fn set_estimate(&mut self, estimate: Estimate) {
		self.jitter = estimate.jitter;
		self.bitrate = estimate.bitrate;
		self.delay = estimate.delay;
	}
}

/// Caller-provided catalog fields for a video track: a starting point for what the importer detects.
///
/// Every field is optional and fills only a gap the stream leaves; a value the stream reveals (the
/// dimensions from an SPS, ...) always wins, so a detected change just updates the catalog. A
/// [`codec`](Self::codec) alone is enough to publish the catalog before the first keyframe (the
/// decoder config then arrives in band). Use it for fields the stream can't reveal (bitrate) or to
/// skip that wait.
///
/// Video importers take one because they build the [`VideoConfig`](hang::catalog::VideoConfig)
/// themselves, out of the bitstream, so the caller never holds the config to set these on. An audio
/// importer publishes a complete config from its init bytes, so audio has no equivalent.
#[derive(Clone, Default, Debug, PartialEq)]
#[non_exhaustive]
pub struct VideoHint {
	/// Human-readable rendition name, plumbed through from [`Init::label`](crate::import::Init::label).
	///
	/// Not a hint: every other field here seeds something the stream may also reveal, while a label
	/// can only ever come from the caller. It rides along so one `apply` writes the whole config.
	pub(crate) label: Option<String>,
	/// The video codec.
	pub codec: Option<hang::catalog::VideoCodec>,
	/// The encoded width in pixels.
	pub coded_width: Option<u32>,
	/// The encoded height in pixels.
	pub coded_height: Option<u32>,
	/// The display aspect ratio width.
	pub display_aspect_width: Option<u32>,
	/// The display aspect ratio height.
	pub display_aspect_height: Option<u32>,
	/// The maximum bitrate in bits per second.
	pub bitrate: Option<u64>,
	/// The frame rate in frames per second.
	pub framerate: Option<f64>,
	/// If true, the decoder optimizes for latency.
	pub optimize_for_latency: Option<bool>,
	/// The maximum jitter before the next frame is emitted.
	pub jitter: Option<Duration>,
	/// How far this rendition trails the broadcast's earliest rendition.
	pub delay: Option<Duration>,
	/// The container wrapping each frame on the wire.
	///
	/// Unlike the other fields this is a choice, not a hint: the bitstream never reveals a
	/// container, so it is applied to every config the importer publishes rather than filling a gap.
	pub container: hang::catalog::Container,
}

/// Fill `slot` from `value` only when the slot is still empty, so a value the stream detected always
/// wins over the caller's hint.
fn fill<T>(slot: &mut Option<T>, value: Option<T>) {
	if slot.is_none() {
		*slot = value;
	}
}

impl From<hang::catalog::VideoConfig> for VideoHint {
	/// Carry a whole rendition across as hints, for a caller that already knows what its encoder
	/// emits (moq-video probes its encoder for exactly this).
	///
	/// Total by construction: every field the hint can hold is taken from the config, so there is no
	/// per-field copy for a caller to forget. Fields with no hint slot (`broadcast`, `description`,
	/// `stalled`) are set through the catalog directly.
	fn from(config: hang::catalog::VideoConfig) -> Self {
		Self {
			label: config.label,
			codec: Some(config.codec),
			coded_width: config.coded_width,
			coded_height: config.coded_height,
			display_aspect_width: config.display_aspect_width,
			display_aspect_height: config.display_aspect_height,
			bitrate: config.bitrate,
			framerate: config.framerate,
			optimize_for_latency: config.optimize_for_latency,
			jitter: config.jitter,
			delay: config.delay,
			container: config.container,
		}
	}
}

impl VideoHint {
	/// Fill a detected video config's absent optional fields from these hints.
	///
	/// Only the gaps: a value the stream detects (e.g. the dimensions from an SPS) is left untouched,
	/// so a resolution change updates the catalog instead of conflicting with the hint. An importer
	/// calls this on every config it publishes, before handing it to
	/// [`container::Producer::set`](crate::container::Producer::set), so a hinted field counts as
	/// supplied and is never overwritten by detection.
	pub fn apply(&self, config: &mut hang::catalog::VideoConfig) {
		fill(&mut config.label, self.label.clone());
		fill(&mut config.coded_width, self.coded_width);
		fill(&mut config.coded_height, self.coded_height);
		fill(&mut config.display_aspect_width, self.display_aspect_width);
		fill(&mut config.display_aspect_height, self.display_aspect_height);
		fill(&mut config.bitrate, self.bitrate);
		fill(&mut config.framerate, self.framerate);
		fill(&mut config.optimize_for_latency, self.optimize_for_latency);
		fill(&mut config.jitter, self.jitter);
		fill(&mut config.delay, self.delay);
		config.container = self.container.clone();
	}

	/// Build a config from these fields alone, or `None` if the codec is missing. Used to publish
	/// the catalog before the stream is parsed.
	pub fn to_config(&self) -> Option<hang::catalog::VideoConfig> {
		let codec = self.codec.clone()?;
		let mut config = hang::catalog::VideoConfig::new(codec);
		self.apply(&mut config);
		Some(config)
	}
}

impl<E: CatalogExt> RenditionConfig<E> for hang::catalog::VideoConfig {
	fn detects() -> bool {
		true
	}

	fn insert(self, catalog: &mut Catalog<E>, name: &str) {
		catalog.video.renditions.insert(name.to_string(), self);
	}
	fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self> {
		catalog.video.renditions.get_mut(name)
	}
	fn remove(catalog: &mut Catalog<E>, name: &str) {
		catalog.video.renditions.remove(name);
	}

	fn estimate(&self) -> Estimate {
		Estimate::default()
			.with_jitter(self.jitter)
			.with_bitrate(self.bitrate)
			.with_delay(self.delay)
			.with_framerate(self.framerate)
	}
	fn set_estimate(&mut self, estimate: Estimate) {
		self.jitter = estimate.jitter;
		self.bitrate = estimate.bitrate;
		self.delay = estimate.delay;
		self.framerate = estimate.framerate;
	}
}

impl<E: CatalogExt> RenditionConfig<E> for hang::catalog::AudioConfig {
	fn detects() -> bool {
		true
	}

	fn insert(self, catalog: &mut Catalog<E>, name: &str) {
		catalog.audio.renditions.insert(name.to_string(), self);
	}
	fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self> {
		catalog.audio.renditions.get_mut(name)
	}
	fn remove(catalog: &mut Catalog<E>, name: &str) {
		catalog.audio.renditions.remove(name);
	}

	fn estimate(&self) -> Estimate {
		Estimate::default()
			.with_jitter(self.jitter)
			.with_bitrate(self.bitrate)
			.with_delay(self.delay)
	}
	fn set_estimate(&mut self, estimate: Estimate) {
		self.jitter = estimate.jitter;
		self.bitrate = estimate.bitrate;
		self.delay = estimate.delay;
	}
}

impl<E: CatalogExt> RenditionConfig<E> for hang::catalog::TextConfig {
	fn insert(self, catalog: &mut Catalog<E>, name: &str) {
		catalog.text.renditions.insert(name.to_string(), self);
	}
	fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self> {
		catalog.text.renditions.get_mut(name)
	}
	fn remove(catalog: &mut Catalog<E>, name: &str) {
		catalog.text.renditions.remove(name);
	}
	fn estimate(&self) -> Estimate {
		Estimate::default().with_jitter(self.jitter).with_delay(self.delay)
	}
	fn set_estimate(&mut self, estimate: Estimate) {
		self.jitter = estimate.jitter;
		self.delay = estimate.delay;
	}
}

/// A clonable reservation context handed to importers so they declare their tracks up front.
///
/// Made via [`Producer::reserve`]. While any `Reserved` clone is alive the track set may still
/// grow, so the catalog is withheld from the broadcast. Each track constructor reserves a
/// rendition by name and counts as outstanding until its returned producer publishes a config or
/// is dropped. Once every clone is dropped *and* every reservation resolves, the first catalog
/// snapshot is published atomically with the complete track list, so a one-shot muxer (fMP4,
/// MPEG-TS) never sees a half-converged catalog.
pub struct Reserved<E: CatalogExt = ()> {
	catalog: Producer<E>,
}

impl<E: CatalogExt> Reserved<E> {
	pub(super) fn new(catalog: Producer<E>) -> Self {
		catalog.add_reserver();
		Self { catalog }
	}

	/// Track properties for a media track under this catalog, carrying any retention it declares.
	/// See [`Producer::track_info`](super::Producer::track_info).
	pub fn track_info(&self, priority: u8) -> moq_net::track::Info {
		self.catalog.track_info(priority)
	}

	/// Reserve a rendition of config type `C` under `name`, returning its internal owner.
	///
	/// The owner holds its own `Reserved` clone, so the catalog stays withheld until its config is
	/// published (or it is dropped). Prefer [`video`](Self::video) / [`audio`](Self::audio) for the
	/// built-in media configs.
	///
	/// Errors if the name is already taken in this section, whether by a live rendition or by an
	/// entry in the catalog. Sections are independent, so the same name in `video` and `audio` is
	/// two unrelated renditions.
	pub(crate) fn init<C: RenditionConfig<E>>(&self, name: impl Into<String>) -> crate::Result<Rendition<E, C>> {
		Rendition::new(self.clone(), name.into())
	}

	/// Publish a reserved video track and own its catalog rendition.
	pub fn video<C: crate::container::Container>(
		&self,
		track: moq_net::track::Producer,
		container: C,
		config: impl Into<Option<hang::catalog::VideoConfig>>,
	) -> crate::Result<crate::container::Producer<C, hang::catalog::VideoConfig>>
	where
		crate::Error: From<C::Error>,
	{
		self.track(track, container, config)
	}

	/// Publish a reserved audio track and own its catalog rendition.
	pub fn audio<C: crate::container::Container>(
		&self,
		track: moq_net::track::Producer,
		container: C,
		config: impl Into<Option<hang::catalog::AudioConfig>>,
	) -> crate::Result<crate::container::Producer<C, hang::catalog::AudioConfig>>
	where
		crate::Error: From<C::Error>,
	{
		self.track(track, container, config)
	}

	/// Publish a reserved text track and own its catalog rendition.
	pub fn text<C: crate::container::Container>(
		&self,
		track: moq_net::track::Producer,
		container: C,
		config: impl Into<Option<hang::catalog::TextConfig>>,
	) -> crate::Result<crate::container::Producer<C, hang::catalog::TextConfig>>
	where
		crate::Error: From<C::Error>,
	{
		self.track(track, container, config)
	}

	/// Publish a reserved track using a custom catalog config.
	pub fn track<C, R>(
		&self,
		track: moq_net::track::Producer,
		container: C,
		config: impl Into<Option<R>>,
	) -> crate::Result<crate::container::Producer<C, R>>
	where
		C: crate::container::Container,
		R: RenditionConfig<E>,
		crate::Error: From<C::Error>,
	{
		let rendition = self.init(track.name())?;
		self.catalog.media(track, container, rendition, config.into())
	}

	/// Resolve a timestamp on the broadcast's shared clock (see [`Producer::timestamp`]).
	pub fn timestamp(&self, hint: Option<moq_net::Timestamp>) -> crate::Result<moq_net::Timestamp> {
		self.catalog.timestamp(hint)
	}

	/// The underlying catalog [`Producer`], for edits that outlive this reservation.
	///
	/// A container importer holds one to edit the catalog directly (e.g. its per-frame reconcile, or
	/// track removals after its initial set is declared) while the reservation itself is dropped to
	/// open the gate. The returned handle does not gate: only live `Reserved`s do.
	pub(crate) fn producer(&self) -> Producer<E> {
		self.catalog.clone()
	}
}

impl<E: CatalogExt> Clone for Reserved<E> {
	fn clone(&self) -> Self {
		self.catalog.add_reserver();
		Self {
			catalog: self.catalog.clone(),
		}
	}
}

impl<E: CatalogExt> Drop for Reserved<E> {
	fn drop(&mut self) {
		self.catalog.release_reserver();
	}
}

/// A reserved rendition of config type `C`, retired from the catalog on drop.
///
/// Made via [`Reserved::init`] (or [`video`](Reserved::video) / [`audio`](Reserved::audio)). Fill
/// it in with [`set`](Self::set) and refine it in place with [`update`](Self::update). Until it's
/// set (or dropped) it holds a [`Reserved`] clone, so an unresolved rendition keeps the initial
/// catalog publish gated. On drop the rendition is removed from the shared catalog.
///
/// It owns its name for its whole lifetime, from reservation rather than from `set`, so nothing
/// else can reserve that name in the same section meanwhile. That's what a lazily-configured
/// importer needs: an H.264 track publishes no config until its first SPS, and the name has to be
/// unavailable through that window or an entry written into it is overwritten by `set` and then
/// deleted by this `Drop`. Author a rendition by holding one of these, not by writing to
/// `catalog.video` / `catalog.audio` through a [`Guard`](super::Guard), which is raw access to the
/// catalog document and enforces nothing.
pub(crate) struct Rendition<E: CatalogExt, C: RenditionConfig<E>> {
	catalog: Producer<E>,
	name: String,
	/// The reservation this rendition holds until its config is set (or it's dropped unfulfilled).
	/// `Some` gates the initial publish; cleared by [`set`](Self::set).
	gate: Option<Reserved<E>>,
	/// Whether a config has been published, so a lazily-configured importer (e.g. H.264 before its
	/// SPS) holds the handle without a catalog entry, and drops without a spurious removal.
	present: bool,
	/// The fields the config carried at [`set`](Self::set): authoritative, never overwritten by
	/// detection. Whatever is absent here is what detection fills.
	supplied: Estimate,
	/// The last estimate handed to [`estimate`](Self::estimate), kept so a config set afterwards
	/// starts from whatever was already measured.
	detected: Estimate,
	/// The last estimate written to the config, so an unchanged one doesn't republish the catalog.
	published: Option<Estimate>,
	_config: PhantomData<fn() -> C>,
}

/// A single video track's catalog rendition. See [`Rendition`].
pub(crate) type VideoTrack<E = ()> = Rendition<E, hang::catalog::VideoConfig>;
/// A single audio track's catalog rendition. See [`Rendition`].
pub(crate) type AudioTrack<E = ()> = Rendition<E, hang::catalog::AudioConfig>;
/// A single text (caption/subtitle) track's catalog rendition. See [`Rendition`].
impl<E: CatalogExt, C: RenditionConfig<E>> Rendition<E, C> {
	fn new(reserved: Reserved<E>, name: String) -> crate::Result<Self> {
		Self::owned(reserved.catalog.clone(), Some(reserved), name)
	}

	pub(super) fn live(catalog: Producer<E>, name: String) -> crate::Result<Self> {
		Self::owned(catalog, None, name)
	}

	fn owned(catalog: Producer<E>, gate: Option<Reserved<E>>, name: String) -> crate::Result<Self> {
		// Take the name now, not at `set`: a lazily-configured importer (H.264 before its first SPS)
		// has no catalog entry until much later, and the name has to be ours for that whole window.
		catalog.acquire::<C>(&name)?;

		Ok(Self {
			catalog,
			gate,
			name,
			present: false,
			supplied: Estimate::default(),
			detected: Estimate::default(),
			published: None,
			_config: PhantomData,
		})
	}

	/// The track name this rendition is keyed by.
	pub fn name(&self) -> &str {
		&self.name
	}

	/// A fresh estimator measuring `delay` against the catalog's other renditions.
	pub(crate) fn estimator(&self) -> super::Estimator {
		self.catalog.estimator()
	}

	/// The broadcast clock the catalog stamps its tracks on.
	pub(crate) fn clock(&self) -> crate::Clock {
		self.catalog.clock()
	}

	/// Resolve a timestamp on the broadcast's shared clock (see [`Producer::timestamp`]).
	pub fn timestamp(&self, hint: Option<moq_net::Timestamp>) -> crate::Result<moq_net::Timestamp> {
		self.catalog.timestamp(hint)
	}

	/// Validate and publish the rendition, fulfilling its reservation only after the edit succeeds.
	///
	/// Whatever [`Estimate`] fields `config` already carries are authoritative and left alone; the
	/// rest are filled by [`estimate`](Self::estimate), seeded with anything already measured before
	/// the rendition existed (a dirty start or a B-frame reorder). A caller who wants to pre-empt
	/// detection sets the field on the config, or (for a config an importer builds out of the
	/// bitstream) hands the importer a hint like [`VideoHint`].
	pub(crate) fn set(&mut self, mut config: C) -> crate::Result<()> {
		let supplied = config.estimate();
		let resolved = Self::resolved(&supplied, &self.detected);
		self.check_decrease(&resolved)?;
		config.set_estimate(resolved.clone());
		{
			let mut guard = self.catalog.modify()?;
			let mut next = (*guard).clone();
			config.insert(&mut next, &self.name);
			// Serialization must succeed before the reserved snapshot retains the edit.
			serde_json::to_writer(std::io::sink(), &next).map_err(moq_json::Error::from)?;
			self.present = true;
			*guard = next;
			guard.commit()?;
		}
		self.supplied = supplied;
		self.published = Some(resolved);
		self.gate = None;
		Ok(())
	}

	/// The supplied fields, with anything absent filled from what was detected.
	fn resolved(supplied: &Estimate, detected: &Estimate) -> Estimate {
		let mut estimate = supplied.clone();
		if estimate.jitter.is_none() {
			estimate.jitter = detected.jitter;
		}
		if estimate.bitrate.is_none() {
			estimate.bitrate = detected.bitrate;
		}
		if estimate.delay.is_none() {
			estimate.delay = detected.delay;
		}
		if estimate.framerate.is_none() {
			estimate.framerate = detected.framerate;
		}
		estimate
	}

	/// Publish a measured [`Estimate`], filling only the fields the config didn't supply at
	/// [`set`](Self::set).
	///
	/// Mint the estimate from an [`Estimator`](super::Estimator), usually the one owned by a
	/// [`container::Producer`](crate::container::Producer). Cheap to call after every write, since an
	/// estimate that resolves to what the catalog already carries doesn't republish it.
	///
	/// Calling this before [`set`](Self::set) is not wasted: the measurement is remembered and seeds
	/// the config once it lands.
	pub(crate) fn estimate(&mut self, estimate: Estimate) -> crate::Result<()> {
		if !C::detects() {
			return Ok(());
		}
		if !self.present {
			self.detected = estimate;
			return Ok(());
		}
		let mut resolved = Self::resolved(&self.supplied, &estimate);
		// A measurement never lowers the published jitter or delay, including one raised through
		// `modify`.
		let published = self.config()?.estimate();
		resolved.jitter = resolved.jitter.max(published.jitter);
		resolved.delay = resolved.delay.max(published.delay);
		self.detected = estimate;
		if self.published.as_ref() != Some(&resolved) {
			let mut config = self.config()?;
			config.set_estimate(resolved.clone());
			self.replace(config)?;
			self.published = Some(resolved);
		}
		Ok(())
	}

	/// Refuse a config that lowers the jitter or delay already advertised to subscribers.
	fn check_decrease(&self, next: &Estimate) -> crate::Result<()> {
		if !self.present {
			return Ok(());
		}
		let previous = self.config()?.estimate();
		if next.jitter < previous.jitter {
			return Err(crate::Error::JitterDecreased);
		}
		if next.delay < previous.delay {
			return Err(crate::Error::DelayDecreased);
		}
		Ok(())
	}

	/// Refine the rendition, refusing an unserializable edit before retaining it.
	pub(crate) fn config(&self) -> crate::Result<C> {
		if !self.present {
			return Err(crate::Error::NotPublished);
		}
		let mut catalog = self.catalog.snapshot();
		C::get_mut(&mut catalog, &self.name)
			.cloned()
			.ok_or(crate::Error::NotPublished)
	}

	pub(crate) fn replace(&mut self, config: C) -> crate::Result<()> {
		if !self.present {
			return Err(crate::Error::NotPublished);
		}
		self.check_decrease(&config.estimate())?;
		let mut guard = self.catalog.modify()?;
		let mut next = (*guard).clone();
		config.insert(&mut next, &self.name);
		serde_json::to_writer(std::io::sink(), &next).map_err(moq_json::Error::from)?;
		*guard = next;
		guard.commit()
	}
}

// Manual so a config that isn't `Debug` doesn't cost the handle its own, and because the interesting
// state is the name and whether it has published yet, not the estimate bookkeeping.
impl<E: CatalogExt, C: RenditionConfig<E>> std::fmt::Debug for Rendition<E, C> {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		f.debug_struct("Rendition")
			.field("name", &self.name)
			.field("published", &self.present)
			.finish_non_exhaustive()
	}
}

impl<E: CatalogExt, C: RenditionConfig<E>> Drop for Rendition<E, C> {
	fn drop(&mut self) {
		// The entry and the name it holds are released together under one lock. Removing mutates the
		// catalog, so the guard publishes it (immediately if live, else it accumulates until the gate
		// opens). A closed catalog has nothing left to release from.
		if let Ok(mut catalog) = self.catalog.modify() {
			catalog.release::<C>(&self.name, self.present);
		}
		// Our reservation (`gate`) drops here. If still held (never set), its release flushes any
		// staged change; if already released by `set`, this is a no-op.
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	fn video_track() -> (moq_net::broadcast::Producer, super::super::Producer, VideoTrack) {
		let mut broadcast = moq_net::broadcast::Info::new().produce();
		let catalog = super::super::Producer::new(&mut broadcast, super::super::Config::default()).unwrap();
		let reserved = catalog.reserve();
		let rendition = reserved.init::<hang::catalog::VideoConfig>("v").unwrap();
		// Drop the standalone reservation so only the rendition's own gate remains, which `set`
		// clears; the broadcast handle is returned so the produced tracks outlive the catalog.
		drop(reserved);
		(broadcast, catalog, rendition)
	}

	fn config(bitrate: Option<u64>, jitter: Option<Duration>) -> hang::catalog::VideoConfig {
		let mut config = hang::catalog::VideoConfig::new(hang::catalog::VideoCodec::VP8);
		config.bitrate = bitrate;
		config.jitter = jitter;
		config
	}

	#[test]
	fn rejected_jitter_is_not_retained() {
		let (_broadcast, catalog, mut rendition) = video_track();
		for jitter in [Duration::ZERO, Duration::MAX] {
			assert!(rendition.set(config(None, Some(jitter))).is_err());
			assert!(catalog.snapshot().video.renditions.is_empty());
		}
		rendition.set(config(None, Some(Duration::from_millis(100)))).unwrap();
		let mut invalid = rendition.config().unwrap();
		invalid.jitter = Some(Duration::ZERO);
		assert!(rendition.replace(invalid).is_err());
		assert_eq!(
			catalog.snapshot().video.renditions.values().next().unwrap().jitter,
			Some(Duration::from_millis(100))
		);
	}

	#[test]
	fn published_jitter_never_decreases() {
		let (_broadcast, catalog, mut rendition) = video_track();
		rendition.set(config(None, Some(Duration::from_millis(100)))).unwrap();
		let smaller = config(None, Some(Duration::from_millis(50)));
		assert!(matches!(
			rendition.set(smaller.clone()),
			Err(crate::Error::JitterDecreased)
		));
		assert!(matches!(rendition.replace(smaller), Err(crate::Error::JitterDecreased)));
		assert_eq!(
			catalog.snapshot().video.renditions["v"].jitter,
			Some(Duration::from_millis(100))
		);

		let (_broadcast, catalog, mut detected) = video_track();
		detected.set(config(None, None)).unwrap();
		detected
			.estimate(Estimate::default().with_jitter(Duration::from_millis(100)))
			.unwrap();
		// A lower measurement holds the published value rather than failing the write path.
		detected
			.estimate(Estimate::default().with_jitter(Duration::from_millis(50)))
			.unwrap();
		assert_eq!(
			catalog.snapshot().video.renditions["v"].jitter,
			Some(Duration::from_millis(100))
		);
	}

	#[test]
	fn published_delay_never_decreases() {
		let (_broadcast, catalog, mut rendition) = video_track();
		let delayed = |delay| {
			let mut config = config(None, None);
			config.delay = delay;
			config
		};
		rendition.set(delayed(Some(Duration::from_millis(200)))).unwrap();
		for smaller in [Some(Duration::from_millis(100)), None] {
			assert!(matches!(
				rendition.set(delayed(smaller)),
				Err(crate::Error::DelayDecreased)
			));
			assert!(matches!(
				rendition.replace(delayed(smaller)),
				Err(crate::Error::DelayDecreased)
			));
		}
		assert_eq!(
			catalog.snapshot().video.renditions["v"].delay,
			Some(Duration::from_millis(200))
		);

		let (_broadcast, catalog, mut detected) = video_track();
		detected.set(config(None, None)).unwrap();
		detected
			.estimate(Estimate::default().with_delay(Duration::from_millis(200)))
			.unwrap();
		// A lower measurement holds the published value rather than failing the write path.
		detected
			.estimate(Estimate::default().with_delay(Duration::from_millis(100)))
			.unwrap();
		assert_eq!(
			catalog.snapshot().video.renditions["v"].delay,
			Some(Duration::from_millis(200))
		);
	}

	#[test]
	fn measurement_keeps_a_jitter_raised_by_modify() {
		let (_broadcast, catalog, mut rendition) = video_track();
		rendition.set(config(None, None)).unwrap();
		rendition
			.estimate(Estimate::default().with_jitter(Duration::from_millis(60)))
			.unwrap();
		let mut raised = rendition.config().unwrap();
		raised.jitter = Some(Duration::from_millis(200));
		rendition.replace(raised).unwrap();

		rendition
			.estimate(Estimate::default().with_jitter(Duration::from_millis(80)))
			.unwrap();
		assert_eq!(
			catalog.snapshot().video.renditions["v"].jitter,
			Some(Duration::from_millis(200))
		);
		rendition
			.estimate(Estimate::default().with_jitter(Duration::from_millis(300)))
			.unwrap();
		assert_eq!(
			catalog.snapshot().video.renditions["v"].jitter,
			Some(Duration::from_millis(300))
		);
	}

	#[test]
	fn published_text_jitter_never_decreases() {
		let mut broadcast = moq_net::broadcast::Info::new().produce();
		let catalog = super::super::Producer::new(&mut broadcast, super::super::Config::default()).unwrap();
		let reserved = catalog.reserve();
		let mut rendition = reserved.init::<hang::catalog::TextConfig>("t").unwrap();
		drop(reserved);

		let text = |jitter| {
			let mut config = hang::catalog::TextConfig::new(hang::catalog::TextFormat::Utf8);
			config.jitter = jitter;
			config
		};
		rendition.set(text(Some(Duration::from_millis(100)))).unwrap();
		for smaller in [Some(Duration::from_millis(50)), None] {
			assert!(matches!(
				rendition.set(text(smaller)),
				Err(crate::Error::JitterDecreased)
			));
		}
		assert_eq!(
			catalog.snapshot().text.renditions["t"].jitter,
			Some(Duration::from_millis(100))
		);
	}

	#[test]
	fn importer_returns_rejected_jitter() {
		let mut broadcast = moq_net::broadcast::Info::new().produce();
		let catalog = super::super::Producer::new(&mut broadcast, super::super::Config::default()).unwrap();
		let reserved = catalog.reserve();
		let track = broadcast
			.create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
			.unwrap();
		let mut config: hang::catalog::AudioConfig = crate::codec::aac::Config {
			profile: 2,
			sample_rate: 48_000,
			channel_count: 2,
		}
		.into();
		config.jitter = Some(Duration::ZERO);
		assert!(crate::codec::aac::Import::new(track, reserved, config).is_err());
		assert!(catalog.snapshot().audio.renditions.is_empty());
	}

	fn ts(micros: u64) -> moq_net::Timestamp {
		moq_net::Timestamp::from_micros(micros).unwrap()
	}

	// Legacy unless selected, and a clone (what an importer is handed) carries the selection.
	#[test]
	fn a_video_hint_applies_its_container_to_every_config() {
		let mut config = hang::catalog::VideoConfig::new(hang::catalog::VideoCodec::VP8);
		VideoHint::default().apply(&mut config);
		assert_eq!(config.container, hang::catalog::Container::Legacy);

		let hint = VideoHint {
			container: hang::catalog::Container::Loc,
			..Default::default()
		};
		hint.apply(&mut config);
		assert_eq!(config.container, hang::catalog::Container::Loc);
	}

	/// Feed ~40ms 100 kB frames over more than the bitrate window, with a measured
	/// 40ms container batch span. PTS spacing alone says nothing about flush delay.
	fn feed<E: CatalogExt, C: RenditionConfig<E>>(rendition: &mut Rendition<E, C>) {
		let mut estimator = super::super::Estimator::new();
		estimator.burst(Duration::from_millis(40));
		for i in 0..60u64 {
			let t = ts(i * 40_000);
			estimator.cut(Some(t));
			estimator.write(t, 100_000);
			rendition.estimate(estimator.estimate()).unwrap();
		}
	}

	#[test]
	fn detects_absent_jitter_and_bitrate() {
		let (_broadcast, catalog, mut rendition) = video_track();
		rendition.set(config(None, None)).unwrap();
		feed(&mut rendition);

		let snapshot = catalog.snapshot();
		let config = snapshot.video.renditions.get("v").unwrap();
		assert!(config.jitter.is_some(), "absent jitter should be auto-detected");
		assert!(config.bitrate.is_some(), "absent bitrate should be auto-detected");
		assert_eq!(config.framerate, Some(25.0), "absent framerate should be auto-detected");
	}

	#[test]
	fn keeps_provided_jitter_and_bitrate() {
		let (_broadcast, catalog, mut rendition) = video_track();
		rendition
			.set(config(Some(123), Some(Duration::from_millis(50))))
			.unwrap();
		feed(&mut rendition);

		let snapshot = catalog.snapshot();
		let config = snapshot.video.renditions.get("v").unwrap();
		assert_eq!(config.bitrate, Some(123), "a provided bitrate must not be overwritten");
		assert_eq!(
			config.jitter,
			Some(Duration::from_millis(50)),
			"a provided jitter must not be overwritten"
		);
	}

	/// A caller hands moq-video a whole `VideoConfig`, so the conversion into hints must be total.
	/// Hand-copying it field by field is what dropped the label on that path.
	#[test]
	fn a_config_converts_into_hints_without_losing_the_label() {
		let (_broadcast, catalog, mut rendition) = video_track();

		let mut source = config(Some(456), None);
		source.label = Some("Main camera".to_string());
		source.coded_width = Some(1920);
		source.coded_height = Some(1080);
		let hint = VideoHint::from(source);

		// The importer applies the hint to each config it publishes, so check the label survives
		// both the up-front publish and a later one the stream resolved.
		let mut first = config(None, None);
		hint.apply(&mut first);
		rendition.set(first).unwrap();
		feed(&mut rendition);
		assert_eq!(
			catalog.snapshot().video.renditions.get("v").unwrap().label.as_deref(),
			Some("Main camera"),
			"the label must survive the config the importer publishes up front"
		);

		let mut resolved = config(None, None);
		resolved.coded_width = Some(1280);
		resolved.coded_height = Some(720);
		hint.apply(&mut resolved);
		rendition.set(resolved).unwrap();
		feed(&mut rendition);

		let snapshot = catalog.snapshot();
		let published = snapshot.video.renditions.get("v").unwrap();
		assert_eq!(
			published.label.as_deref(),
			Some("Main camera"),
			"the label must survive a config the stream resolved later"
		);
		assert_eq!(published.bitrate, Some(456), "the rest of the config converts too");
	}

	/// A hint is applied by the importer before `set`, so a hinted field is indistinguishable from
	/// one the stream revealed: supplied, and never overwritten by detection.
	#[test]
	fn hinted_fields_count_as_supplied() {
		let (_broadcast, catalog, mut rendition) = video_track();

		let hint = VideoHint {
			bitrate: Some(456),
			framerate: Some(30.0),
			..Default::default()
		};
		let mut config = config(None, None);
		hint.apply(&mut config);

		rendition.set(config).unwrap();
		feed(&mut rendition);

		let snapshot = catalog.snapshot();
		let config = snapshot.video.renditions.get("v").unwrap();
		assert_eq!(config.bitrate, Some(456), "a hinted bitrate must not be overwritten");
		assert_eq!(
			config.framerate,
			Some(30.0),
			"a hinted framerate must not be overwritten"
		);
		assert!(config.jitter.is_some(), "the unhinted jitter should still be detected");
	}

	/// Frames flow before the config resolves (H.264 publishes until its first SPS), so a
	/// measurement taken while the rendition is still empty has to seed the config once it lands.
	#[test]
	fn measurements_before_set_seed_the_config() {
		let (_broadcast, catalog, mut rendition) = video_track();
		feed(&mut rendition);
		rendition.set(config(None, None)).unwrap();

		let snapshot = catalog.snapshot();
		let config = snapshot.video.renditions.get("v").unwrap();
		assert!(
			config.jitter.is_some(),
			"the jitter measured before `set` should carry over"
		);
		assert!(
			config.bitrate.is_some(),
			"the bitrate measured before `set` should carry over"
		);
	}

	/// A detected value the stream later reveals wins: `set` recaptures what the new config carries.
	#[test]
	fn resetting_recaptures_supplied() {
		let (_broadcast, catalog, mut rendition) = video_track();
		rendition.set(config(None, None)).unwrap();
		feed(&mut rendition);
		assert!(catalog.snapshot().video.renditions.get("v").unwrap().bitrate.is_some());

		rendition.set(config(Some(789), None)).unwrap();
		feed(&mut rendition);

		let snapshot = catalog.snapshot();
		let config = snapshot.video.renditions.get("v").unwrap();
		assert_eq!(config.bitrate, Some(789), "the re-set bitrate is now authoritative");
	}

	/// A rendition owns its name from the moment it's reserved, not from `set`. H.264 publishes
	/// frames before its first SPS resolves the config, and the name has to be unavailable through
	/// that window: an entry written into the gap used to be overwritten by `set` and then deleted
	/// by the importer's `Drop`, taking the caller's rendition with it.
	#[test]
	fn an_unresolved_rendition_still_owns_its_name() {
		let (_broadcast, catalog, mut rendition) = video_track();
		assert!(
			catalog.snapshot().video.renditions.is_empty(),
			"nothing is published until the config resolves"
		);

		let err = catalog
			.reserve()
			.init::<hang::catalog::VideoConfig>("v")
			.expect_err("an unresolved rendition still owns its name");
		assert!(matches!(err, crate::Error::Hang(hang::Error::Duplicate(name)) if name == "v"));

		// The refusal left nothing behind, so the importer's own config is what lands.
		rendition.set(config(Some(123), None)).unwrap();
		assert_eq!(
			catalog.snapshot().video.renditions.get("v").unwrap().bitrate,
			Some(123),
			"the importer's config owns the rendition"
		);
	}

	/// A resolved rendition still owns its name, now backed by a catalog entry.
	#[test]
	fn a_resolved_rendition_still_owns_its_name() {
		let (_broadcast, catalog, mut rendition) = video_track();
		rendition.set(config(Some(789), None)).unwrap();

		assert!(
			catalog.reserve().init::<hang::catalog::VideoConfig>("v").is_err(),
			"owned by the live rendition"
		);
		assert_eq!(
			catalog.snapshot().video.renditions.get("v").unwrap().bitrate,
			Some(789),
			"the refused reservation left the rendition intact"
		);
	}

	/// Ownership lasts exactly as long as the rendition, so the name is free again once it drops
	/// and the entry it published goes with it.
	#[test]
	fn dropping_a_rendition_frees_its_name() {
		let (_broadcast, catalog, mut rendition) = video_track();
		rendition.set(config(None, None)).unwrap();
		drop(rendition);
		assert!(
			catalog.snapshot().video.renditions.is_empty(),
			"the entry is retired with its owner"
		);

		let mut replacement = catalog
			.reserve()
			.init::<hang::catalog::VideoConfig>("v")
			.expect("the name is free once the rendition drops");
		replacement.set(config(Some(456), None)).unwrap();
		assert_eq!(catalog.snapshot().video.renditions.get("v").unwrap().bitrate, Some(456));
	}

	/// Sections are independent maps, so a video rendition says nothing about the same name in
	/// audio.
	#[test]
	fn a_name_is_owned_per_section() {
		let (_broadcast, catalog, _video) = video_track();
		catalog
			.reserve()
			.init::<hang::catalog::AudioConfig>("v")
			.expect("an audio rendition is a different section from a video one");
	}

	/// An entry already in the catalog is taken too, even with no rendition behind it: a caller
	/// that hand-wrote one through the guard still gets to keep it.
	#[test]
	fn an_existing_entry_owns_its_name() {
		let mut broadcast = moq_net::broadcast::Info::new().produce();
		let mut catalog = super::super::Producer::new(&mut broadcast, super::super::Config::default()).unwrap();
		catalog.modify().unwrap().video.insert("v", config(None, None)).unwrap();

		assert!(
			catalog.reserve().init::<hang::catalog::VideoConfig>("v").is_err(),
			"the catalog already carries it"
		);
	}

	/// The broadcast has one timeline: every rendition's groups index into the same track, so
	/// an aligned ladder (source + rung) shares it by construction.
	#[test]
	fn renditions_share_the_broadcast_timeline() {
		let mut broadcast = moq_net::broadcast::Info::new().produce();
		let mut catalog = super::super::Producer::new(&mut broadcast, super::super::Config::default()).unwrap();

		let _recorder = catalog.enroll("video0").unwrap();
		let timeline = catalog.timeline();
		assert_eq!(timeline.section().track, hang::timeline::DEFAULT_NAME);
		assert_eq!(
			catalog.snapshot().archive,
			Some(timeline.section()),
			"the one timeline is advertised at the catalog root"
		);
	}

	mod custom {
		use std::collections::BTreeMap;

		use serde::{Deserialize, Serialize};

		use super::*;

		#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq)]
		struct TelemetryExt {
			#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
			telemetry: BTreeMap<String, Telemetry>,
			#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
			exploding: BTreeMap<String, Exploding>,
			#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
			stubborn: BTreeMap<String, Stubborn>,
		}

		impl CatalogExt for TelemetryExt {}

		#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq)]
		struct Telemetry {
			schema: String,
			#[serde(default, skip_serializing_if = "Option::is_none")]
			bitrate: Option<u64>,
		}

		impl RenditionConfig<TelemetryExt> for Telemetry {
			fn detects() -> bool {
				true
			}

			fn insert(self, catalog: &mut Catalog<TelemetryExt>, name: &str) {
				catalog.ext.telemetry.insert(name.to_string(), self);
			}
			fn get_mut<'a>(catalog: &'a mut Catalog<TelemetryExt>, name: &str) -> Option<&'a mut Self> {
				catalog.ext.telemetry.get_mut(name)
			}
			fn remove(catalog: &mut Catalog<TelemetryExt>, name: &str) {
				catalog.ext.telemetry.remove(name);
			}

			// Opts into bitrate detection only; jitter is left undetected.
			fn estimate(&self) -> Estimate {
				Estimate::default().with_bitrate(self.bitrate)
			}
			fn set_estimate(&mut self, estimate: Estimate) {
				self.bitrate = estimate.bitrate;
			}
		}

		fn telemetry(bitrate: Option<u64>) -> Telemetry {
			Telemetry {
				schema: "gps/v1".to_string(),
				bitrate,
			}
		}

		fn produce() -> (moq_net::broadcast::Producer, crate::catalog::Producer<TelemetryExt>) {
			let mut broadcast = moq_net::broadcast::Info::new().produce();
			let config = crate::catalog::Config::default().with_catalog(Catalog::<TelemetryExt>::default());
			let catalog = crate::catalog::Producer::new(&mut broadcast, config).unwrap();
			(broadcast, catalog)
		}

		/// A config whose `insert` panics, to poison the catalog lock the way any third-party
		/// [`RenditionConfig`] can: `set` runs it while holding that lock.
		#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq)]
		struct Exploding {
			/// Write the entry before panicking, leaving a partially applied config behind.
			wrote: bool,
		}

		impl RenditionConfig<TelemetryExt> for Exploding {
			fn insert(self, catalog: &mut Catalog<TelemetryExt>, name: &str) {
				if self.wrote {
					catalog.ext.exploding.insert(name.to_string(), self);
				}
				panic!("insert exploded");
			}
			fn get_mut<'a>(catalog: &'a mut Catalog<TelemetryExt>, name: &str) -> Option<&'a mut Self> {
				catalog.ext.exploding.get_mut(name)
			}
			fn remove(catalog: &mut Catalog<TelemetryExt>, name: &str) {
				catalog.ext.exploding.remove(name);
			}
		}

		/// A panicking `insert` poisons the catalog lock while `set` holds it. The producer has to
		/// survive that: an unwinding `Rendition::drop` takes the same lock to release its name, and
		/// a panic there would be a panic during a panic, which aborts the process rather than
		/// failing a test.
		#[test]
		fn a_poisoned_lock_does_not_take_the_producer_down() {
			let (_broadcast, catalog) = produce();
			let reserved = catalog.reserve();

			let err = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
				let mut boom = reserved.init::<Exploding>("gps").unwrap();
				boom.set(Exploding { wrote: false }).unwrap();
			}))
			.expect_err("the config's insert panics");
			assert!(
				err.downcast_ref::<&str>().is_some_and(|msg| *msg == "insert exploded"),
				"the panic is the one the config raised, not a lock failure"
			);

			// The rendition unwound, so it released its name and the catalog is still usable.
			assert!(catalog.snapshot().ext.telemetry.is_empty());
			reserved
				.init::<Exploding>("gps")
				.expect("the unwound rendition released its name");
		}

		/// A config whose cleanup hook panics after mutating, the other half of untrusted caller code:
		/// `Drop` runs `remove` while holding the catalog lock.
		#[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq)]
		struct Stubborn;

		impl RenditionConfig<TelemetryExt> for Stubborn {
			fn insert(self, catalog: &mut Catalog<TelemetryExt>, name: &str) {
				catalog.ext.stubborn.insert(name.to_string(), self);
			}
			fn get_mut<'a>(catalog: &'a mut Catalog<TelemetryExt>, name: &str) -> Option<&'a mut Self> {
				catalog.ext.stubborn.get_mut(name)
			}
			fn remove(catalog: &mut Catalog<TelemetryExt>, name: &str) {
				catalog.ext.stubborn.remove(name);
				panic!("remove exploded");
			}
		}

		/// A panicking `remove` must not cost the rendition its name. The name is released before any
		/// caller code runs, so the slot is reservable again even though the hook blew up on the way
		/// out.
		#[test]
		fn a_panicking_remove_still_frees_the_name() {
			let (_broadcast, catalog) = produce();
			let reserved = catalog.reserve();

			let mut rendition = reserved.init::<Stubborn>("gps").unwrap();
			rendition.set(Stubborn).unwrap();

			std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(rendition)))
				.expect_err("the config's remove panics");

			reserved
				.init::<Stubborn>("gps")
				.expect("a name held by a blown-up cleanup hook would be lost forever");
		}

		/// An insert that writes and then panics must leave no entry behind or strand its name.
		#[test]
		fn an_unwinding_rendition_retires_a_partially_written_entry() {
			let (_broadcast, catalog) = produce();
			let reserved = catalog.reserve();

			std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
				let mut boom = reserved.init::<Exploding>("gps").unwrap();
				boom.set(Exploding { wrote: true }).unwrap();
			}))
			.expect_err("the config's insert panics after writing");

			assert!(
				catalog.snapshot().ext.exploding.is_empty(),
				"the entry the panicking insert wrote is retired with its owner"
			);
			reserved
				.init::<Exploding>("gps")
				.expect("a stranded entry would refuse this forever");
		}

		/// A custom kind gets the same detection and drop-removal as video/audio.
		#[test]
		fn detects_and_advertises() {
			let (_broadcast, catalog) = produce();
			let reserved = catalog.reserve();
			let mut rendition = reserved.init::<Telemetry>("gps").unwrap();
			drop(reserved);

			rendition.set(telemetry(None)).unwrap();
			feed(&mut rendition);

			let snapshot = catalog.snapshot();
			let config = snapshot.ext.telemetry.get("gps").unwrap();
			assert!(config.bitrate.is_some(), "absent bitrate should be auto-detected");

			drop(rendition);
			assert!(
				!catalog.snapshot().ext.telemetry.contains_key("gps"),
				"the rendition should be removed on drop"
			);
		}

		/// The whole point of opting in: write a custom track through a
		/// [`container::Producer`](crate::container::Producer) and its catalog bitrate/jitter keep
		/// themselves current, with no per-frame bookkeeping in the caller.
		#[test]
		fn measures_a_custom_track() {
			let (broadcast, catalog) = produce();
			let reserved = catalog.reserve();
			let net = broadcast.create_track("gps", None).unwrap();
			let mut track = reserved
				.track(
					net,
					crate::catalog::hang::Container::Legacy(crate::container::Kind::Data),
					None,
				)
				.unwrap();
			drop(reserved);
			assert!(matches!(track.modify(), Err(crate::Error::NotPublished)));
			track.set(telemetry(None)).unwrap();

			// 40ms records of 5 kB: 1 Mbps, over more than the bitrate window.
			for i in 0..60u64 {
				track
					.write(crate::container::Frame {
						timestamp: ts(i * 40_000),
						duration: None,
						payload: bytes::Bytes::from(vec![0u8; 5_000]),
						keyframe: true,
					})
					.unwrap();
			}

			let snapshot = catalog.snapshot();
			let config = snapshot.ext.telemetry.get("gps").unwrap();
			assert_eq!(config.bitrate, Some(1_000_000));
		}

		/// A field the config supplies is authoritative even though the kind opts into detection.
		#[test]
		fn keeps_supplied_bitrate() {
			let (_broadcast, catalog) = produce();
			let reserved = catalog.reserve();
			let mut rendition = reserved.init::<Telemetry>("gps").unwrap();
			drop(reserved);

			rendition.set(telemetry(Some(4_200))).unwrap();
			feed(&mut rendition);

			let snapshot = catalog.snapshot();
			assert_eq!(snapshot.ext.telemetry.get("gps").unwrap().bitrate, Some(4_200));
		}

		/// Custom and media renditions share one reservation gate, so the first snapshot carries both.
		#[test]
		fn gates_with_media_tracks() {
			let (_broadcast, catalog) = produce();
			let mut consumer = catalog.consume().unwrap();

			let reserved = catalog.reserve();
			let mut video = reserved.init::<hang::catalog::VideoConfig>("v").unwrap();
			let mut gps = reserved.init::<Telemetry>("gps").unwrap();
			drop(reserved);

			let waiter = kio::Waiter::noop();
			video.set(config(None, None)).unwrap();
			assert!(
				matches!(consumer.poll_next(&waiter), std::task::Poll::Pending),
				"the catalog stays withheld while the telemetry rendition is unresolved"
			);

			gps.set(telemetry(None)).unwrap();

			let mut latest = None;
			while let std::task::Poll::Ready(Ok(Some(catalog))) = consumer.poll_next(&waiter) {
				latest = Some(catalog);
			}
			let published = latest.expect("catalog published");
			assert!(published.video.renditions.contains_key("v"));
			assert!(published.ext.telemetry.contains_key("gps"));
		}
	}
}