1use std::marker::PhantomData;
2use std::time::Duration;
3
4use super::Estimate;
5use super::Producer;
6use super::hang::{Catalog, CatalogExt};
7
8pub trait RenditionConfig<E: CatalogExt>: Clone + Send + 'static {
93 fn detects() -> bool {
95 false
96 }
97
98 fn insert(self, catalog: &mut Catalog<E>, name: &str);
100
101 fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self>;
103
104 fn remove(catalog: &mut Catalog<E>, name: &str);
106
107 fn estimate(&self) -> Estimate {
109 Estimate::default()
110 }
111
112 fn set_estimate(&mut self, _estimate: Estimate) {}
114}
115
116impl<E: CatalogExt> RenditionConfig<E> for hang::catalog::JsonConfig {
117 fn insert(self, catalog: &mut Catalog<E>, name: &str) {
118 catalog.json.tracks.insert(name.to_string(), self);
119 }
120 fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self> {
121 catalog.json.tracks.get_mut(name)
122 }
123 fn remove(catalog: &mut Catalog<E>, name: &str) {
124 catalog.json.tracks.remove(name);
125 }
126
127 fn detects() -> bool {
128 true
129 }
130 fn estimate(&self) -> Estimate {
131 Estimate::default()
132 .with_jitter(self.jitter)
133 .with_bitrate(self.bitrate)
134 .with_delay(self.delay)
135 }
136 fn set_estimate(&mut self, estimate: Estimate) {
137 self.jitter = estimate.jitter;
138 self.bitrate = estimate.bitrate;
139 self.delay = estimate.delay;
140 }
141}
142
143impl<E: CatalogExt> RenditionConfig<E> for hang::catalog::BinaryConfig {
144 fn insert(self, catalog: &mut Catalog<E>, name: &str) {
145 catalog.binary.tracks.insert(name.to_string(), self);
146 }
147 fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self> {
148 catalog.binary.tracks.get_mut(name)
149 }
150 fn remove(catalog: &mut Catalog<E>, name: &str) {
151 catalog.binary.tracks.remove(name);
152 }
153
154 fn detects() -> bool {
155 true
156 }
157 fn estimate(&self) -> Estimate {
158 Estimate::default()
159 .with_jitter(self.jitter)
160 .with_bitrate(self.bitrate)
161 .with_delay(self.delay)
162 }
163 fn set_estimate(&mut self, estimate: Estimate) {
164 self.jitter = estimate.jitter;
165 self.bitrate = estimate.bitrate;
166 self.delay = estimate.delay;
167 }
168}
169
170#[derive(Clone, Default, Debug, PartialEq)]
184#[non_exhaustive]
185pub struct VideoHint {
186 pub(crate) label: Option<String>,
191 pub codec: Option<hang::catalog::VideoCodec>,
193 pub coded_width: Option<u32>,
195 pub coded_height: Option<u32>,
197 pub display_aspect_width: Option<u32>,
199 pub display_aspect_height: Option<u32>,
201 pub color: Option<hang::catalog::Color>,
203 pub bitrate: Option<u64>,
205 pub framerate: Option<f64>,
207 pub reorder: Option<u8>,
209 pub optimize_for_latency: Option<bool>,
211 pub jitter: Option<Duration>,
213 pub delay: Option<Duration>,
215 pub container: hang::catalog::Container,
220 pub preference: i32,
224}
225
226fn fill<T>(slot: &mut Option<T>, value: Option<T>) {
229 if slot.is_none() {
230 *slot = value;
231 }
232}
233
234impl From<hang::catalog::VideoConfig> for VideoHint {
235 fn from(config: hang::catalog::VideoConfig) -> Self {
242 Self {
243 label: config.label,
244 codec: Some(config.codec),
245 coded_width: config.coded_width,
246 coded_height: config.coded_height,
247 display_aspect_width: config.display_aspect_width,
248 display_aspect_height: config.display_aspect_height,
249 color: config.color,
250 bitrate: config.bitrate,
251 framerate: config.framerate,
252 reorder: config.reorder,
253 optimize_for_latency: config.optimize_for_latency,
254 jitter: config.jitter,
255 delay: config.delay,
256 container: config.container,
257 preference: config.preference,
258 }
259 }
260}
261
262impl VideoHint {
263 pub fn apply(&self, config: &mut hang::catalog::VideoConfig) {
271 fill(&mut config.label, self.label.clone());
272 fill(&mut config.coded_width, self.coded_width);
273 fill(&mut config.coded_height, self.coded_height);
274 fill(&mut config.display_aspect_width, self.display_aspect_width);
275 fill(&mut config.display_aspect_height, self.display_aspect_height);
276 crate::codec::color::fill(&mut config.color, self.color.as_ref(), "hint");
277 fill(&mut config.bitrate, self.bitrate);
278 fill(&mut config.framerate, self.framerate);
279 fill(&mut config.reorder, self.reorder);
280 fill(&mut config.optimize_for_latency, self.optimize_for_latency);
281 fill(&mut config.jitter, self.jitter);
282 fill(&mut config.delay, self.delay);
283 config.container = self.container.clone();
284 config.preference = self.preference;
285 }
286
287 pub(crate) fn to_config(&self) -> Option<hang::catalog::VideoConfig> {
290 let codec = self.codec.clone()?;
291 let mut config = hang::catalog::VideoConfig::new(codec);
292 self.apply(&mut config);
293 Some(config)
294 }
295}
296
297impl<E: CatalogExt> RenditionConfig<E> for hang::catalog::VideoConfig {
298 fn detects() -> bool {
299 true
300 }
301
302 fn insert(self, catalog: &mut Catalog<E>, name: &str) {
303 catalog.video.renditions.insert(name.to_string(), self);
304 }
305 fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self> {
306 catalog.video.renditions.get_mut(name)
307 }
308 fn remove(catalog: &mut Catalog<E>, name: &str) {
309 catalog.video.renditions.remove(name);
310 }
311
312 fn estimate(&self) -> Estimate {
313 Estimate::default()
314 .with_jitter(self.jitter)
315 .with_bitrate(self.bitrate)
316 .with_delay(self.delay)
317 .with_framerate(self.framerate)
318 }
319 fn set_estimate(&mut self, estimate: Estimate) {
320 self.jitter = estimate.jitter;
321 self.bitrate = estimate.bitrate;
322 self.delay = estimate.delay;
323 self.framerate = estimate.framerate;
324 }
325}
326
327impl<E: CatalogExt> RenditionConfig<E> for hang::catalog::AudioConfig {
328 fn detects() -> bool {
329 true
330 }
331
332 fn insert(self, catalog: &mut Catalog<E>, name: &str) {
333 catalog.audio.renditions.insert(name.to_string(), self);
334 }
335 fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self> {
336 catalog.audio.renditions.get_mut(name)
337 }
338 fn remove(catalog: &mut Catalog<E>, name: &str) {
339 catalog.audio.renditions.remove(name);
340 }
341
342 fn estimate(&self) -> Estimate {
343 Estimate::default()
344 .with_jitter(self.jitter)
345 .with_bitrate(self.bitrate)
346 .with_delay(self.delay)
347 }
348 fn set_estimate(&mut self, estimate: Estimate) {
349 self.jitter = estimate.jitter;
350 self.bitrate = estimate.bitrate;
351 self.delay = estimate.delay;
352 }
353}
354
355impl<E: CatalogExt> RenditionConfig<E> for hang::catalog::TextConfig {
356 fn insert(self, catalog: &mut Catalog<E>, name: &str) {
357 catalog.text.renditions.insert(name.to_string(), self);
358 }
359 fn get_mut<'a>(catalog: &'a mut Catalog<E>, name: &str) -> Option<&'a mut Self> {
360 catalog.text.renditions.get_mut(name)
361 }
362 fn remove(catalog: &mut Catalog<E>, name: &str) {
363 catalog.text.renditions.remove(name);
364 }
365 fn estimate(&self) -> Estimate {
366 Estimate::default().with_jitter(self.jitter).with_delay(self.delay)
367 }
368 fn set_estimate(&mut self, estimate: Estimate) {
369 self.jitter = estimate.jitter;
370 self.delay = estimate.delay;
371 }
372}
373
374const STEP_SLACK: u32 = 100;
377
378fn quantize(published: Option<Duration>, measured: Option<Duration>, period: Duration) -> Option<Duration> {
380 let step =
381 |value: Option<Duration>| value.map_or(0, |value| (value + period / STEP_SLACK).as_nanos() / period.as_nanos());
382 if step(measured) > step(published) {
383 measured
384 } else {
385 published
386 }
387}
388
389fn write<E: CatalogExt, C: RenditionConfig<E>>(catalog: &mut Catalog<E>, name: &str, config: C) -> crate::Result<()> {
397 let mut alone = Catalog::default();
398 alone.ext = catalog.ext.clone();
399 config.clone().insert(&mut alone, name);
400 check_identity(catalog, &alone, name)?;
401 serde_json::to_writer(std::io::sink(), &alone).map_err(moq_json::Error::from)?;
402 config.insert(catalog, name);
403 Ok(())
404}
405
406fn check_identity<E: CatalogExt>(previous: &Catalog<E>, next: &Catalog<E>, name: &str) -> crate::Result<()> {
409 if let (Some(previous), Some(next)) = (previous.video.renditions.get(name), next.video.renditions.get(name))
410 && !previous.same_identity(next)
411 {
412 return Err(crate::Error::IdentityChanged(name.to_string()));
413 }
414 if let (Some(previous), Some(next)) = (previous.audio.renditions.get(name), next.audio.renditions.get(name))
415 && !previous.same_identity(next)
416 {
417 return Err(crate::Error::IdentityChanged(name.to_string()));
418 }
419 Ok(())
420}
421
422pub struct Reserved<E: CatalogExt = ()> {
434 catalog: Producer<E>,
435 interval: Option<std::time::Duration>,
436}
437
438impl<E: CatalogExt> Reserved<E> {
439 pub(super) fn new(catalog: Producer<E>) -> Self {
440 catalog.add_reserver();
441 Self {
442 catalog,
443 interval: None,
444 }
445 }
446
447 pub fn with_interval(mut self, interval: impl Into<Option<std::time::Duration>>) -> Self {
451 self.interval = interval.into();
452 self
453 }
454
455 pub fn track_info(&self, priority: i8) -> moq_net::track::Info {
458 self.catalog.track_info(priority)
459 }
460
461 pub(crate) fn init<C: RenditionConfig<E>>(&self, name: impl Into<String>) -> crate::Result<Rendition<E, C>> {
471 Rendition::new(self.clone(), name.into())
472 }
473
474 pub fn video<C: crate::container::Container>(
476 &self,
477 track: moq_net::track::Producer,
478 container: C,
479 config: impl Into<Option<hang::catalog::VideoConfig>>,
480 ) -> crate::Result<crate::container::Producer<C, hang::catalog::VideoConfig>>
481 where
482 crate::Error: From<C::Error>,
483 {
484 self.track(track, container, config)
485 }
486
487 pub fn audio<C: crate::container::Container>(
489 &self,
490 track: moq_net::track::Producer,
491 container: C,
492 config: impl Into<Option<hang::catalog::AudioConfig>>,
493 ) -> crate::Result<crate::container::Producer<C, hang::catalog::AudioConfig>>
494 where
495 crate::Error: From<C::Error>,
496 {
497 self.track(track, container, config)
498 }
499
500 pub fn text<C: crate::container::Container>(
502 &self,
503 track: moq_net::track::Producer,
504 container: C,
505 config: impl Into<Option<hang::catalog::TextConfig>>,
506 ) -> crate::Result<crate::container::Producer<C, hang::catalog::TextConfig>>
507 where
508 crate::Error: From<C::Error>,
509 {
510 self.track(track, container, config)
511 }
512
513 pub fn track<C, R>(
515 &self,
516 track: moq_net::track::Producer,
517 container: C,
518 config: impl Into<Option<R>>,
519 ) -> crate::Result<crate::container::Producer<C, R>>
520 where
521 C: crate::container::Container,
522 R: RenditionConfig<E>,
523 crate::Error: From<C::Error>,
524 {
525 let rendition = self.init(track.name())?;
526 self.catalog
527 .media(track, container, rendition, config.into(), self.interval)
528 }
529
530 pub fn timestamp(&self, hint: Option<moq_net::Timestamp>) -> crate::Result<moq_net::Timestamp> {
532 self.catalog.timestamp(hint)
533 }
534
535 pub(crate) fn producer(&self) -> Producer<E> {
541 self.catalog.clone()
542 }
543}
544
545impl<E: CatalogExt> Clone for Reserved<E> {
546 fn clone(&self) -> Self {
547 Self::new(self.catalog.clone()).with_interval(self.interval)
548 }
549}
550
551impl<E: CatalogExt> Drop for Reserved<E> {
552 fn drop(&mut self) {
553 self.catalog.release_reserver();
554 }
555}
556
557pub(crate) struct Rendition<E: CatalogExt, C: RenditionConfig<E>> {
572 catalog: Producer<E>,
573 name: String,
574 gate: Option<Reserved<E>>,
577 present: bool,
580 supplied: Estimate,
583 detected: Estimate,
586 published: Option<Estimate>,
588 _config: PhantomData<fn() -> C>,
589}
590
591pub(crate) type VideoTrack<E = ()> = Rendition<E, hang::catalog::VideoConfig>;
593pub(crate) type AudioTrack<E = ()> = Rendition<E, hang::catalog::AudioConfig>;
595impl<E: CatalogExt, C: RenditionConfig<E>> Rendition<E, C> {
597 pub(crate) fn fresh(
600 &self,
601 container: super::hang::Wire,
602 info: moq_net::track::Info,
603 interval: Option<std::time::Duration>,
604 ) -> crate::Result<crate::container::Producer<super::hang::Wire, C>> {
605 let track = self.catalog.fresh_track(&self.name, info);
606 let rendition = self.catalog.rendition(track.name())?;
607 self.catalog.media(track, container, rendition, None, interval)
608 }
609
610 fn new(reserved: Reserved<E>, name: String) -> crate::Result<Self> {
611 Self::owned(reserved.producer(), Some(reserved), name)
612 }
613
614 pub(super) fn live(catalog: Producer<E>, name: String) -> crate::Result<Self> {
615 Self::owned(catalog, None, name)
616 }
617
618 fn owned(catalog: Producer<E>, gate: Option<Reserved<E>>, name: String) -> crate::Result<Self> {
619 catalog.acquire::<C>(&name)?;
622
623 Ok(Self {
624 catalog,
625 gate,
626 name,
627 present: false,
628 supplied: Estimate::default(),
629 detected: Estimate::default(),
630 published: None,
631 _config: PhantomData,
632 })
633 }
634
635 pub fn name(&self) -> &str {
637 &self.name
638 }
639
640 pub(crate) fn estimator(&self) -> super::Estimator {
642 self.catalog.estimator()
643 }
644
645 pub(crate) fn clock(&self) -> crate::Clock {
647 self.catalog.current_clock()
648 }
649
650 pub fn timestamp(&self, hint: Option<moq_net::Timestamp>) -> crate::Result<moq_net::Timestamp> {
652 self.catalog.timestamp(hint)
653 }
654
655 pub(crate) fn set(&mut self, mut config: C) -> crate::Result<()> {
664 let supplied = config.estimate();
665 let mut resolved = Self::resolved(&supplied, &self.detected);
666 if self.present {
667 let published = self.config()?.estimate();
668 if supplied.jitter.is_none() {
669 resolved.jitter = resolved.jitter.max(published.jitter);
670 }
671 if supplied.delay.is_none() {
672 resolved.delay = resolved.delay.max(published.delay);
673 }
674 Self::check_decrease(&published, &resolved)?;
675 }
676 config.set_estimate(resolved.clone());
677 {
678 let mut guard = self.catalog.edit()?;
679 write(&mut guard, &self.name, config)?;
680 self.present = true;
681 guard.list::<C>(&self.name);
682 if C::detects() {
683 guard.hint::<C>(&self.name, supplied.clone());
684 }
685 guard.commit()?;
686 }
687 self.supplied = supplied;
688 self.published = Some(resolved);
689 self.gate = None;
690 Ok(())
691 }
692
693 fn resolved(supplied: &Estimate, detected: &Estimate) -> Estimate {
695 let mut estimate = supplied.clone();
696 if estimate.jitter.is_none() {
697 estimate.jitter = detected.jitter;
698 }
699 if estimate.bitrate.is_none() {
700 estimate.bitrate = detected.bitrate;
701 }
702 if estimate.delay.is_none() {
703 estimate.delay = detected.delay;
704 }
705 if estimate.framerate.is_none() {
706 estimate.framerate = detected.framerate;
707 }
708 estimate
709 }
710
711 pub(crate) fn estimate(&mut self, reading: impl Into<super::Reading>) -> crate::Result<()> {
724 let super::Reading { estimate, period, .. } = reading.into();
725 if !C::detects() {
726 return Ok(());
727 }
728 if !self.present {
729 self.detected = estimate;
730 return Ok(());
731 }
732 let mut resolved = Self::resolved(&self.supplied, &estimate);
733 let mut config = self.config()?;
736 let published = config.estimate();
737 resolved.jitter = resolved.jitter.max(published.jitter);
738 resolved.delay = resolved.delay.max(published.delay);
739 let period = resolved
742 .framerate
743 .filter(|framerate| *framerate > 0.0)
744 .and_then(|framerate| Duration::try_from_secs_f64(framerate.recip()).ok())
745 .or(period)
746 .filter(|period| !period.is_zero());
747 if let Some(period) = period {
748 resolved.jitter = quantize(published.jitter, resolved.jitter, period);
749 resolved.delay = quantize(published.delay, resolved.delay, period);
750 }
751 self.detected = estimate;
752 if self.published.as_ref() == Some(&resolved) {
753 if let Ok(guard) = self.catalog.edit() {
756 guard.commit_estimate(true)?;
757 }
758 return Ok(());
759 }
760
761 let throttled = self.published.as_ref().is_some_and(|published| {
764 published.bitrate == resolved.bitrate && published.framerate == resolved.framerate
765 });
766 config.set_estimate(resolved.clone());
767 self.stage(config)?.commit_estimate(throttled)?;
768 self.published = Some(resolved);
769 Ok(())
770 }
771
772 fn check_decrease(previous: &Estimate, next: &Estimate) -> crate::Result<()> {
774 if next.jitter < previous.jitter {
775 return Err(crate::Error::JitterDecreased);
776 }
777 if next.delay < previous.delay {
778 return Err(crate::Error::DelayDecreased);
779 }
780 Ok(())
781 }
782
783 fn unpublished(&self) -> crate::Error {
786 self.catalog.closed().unwrap_or(crate::Error::NotPublished)
787 }
788
789 pub(crate) fn config(&self) -> crate::Result<C> {
791 if !self.present {
792 return Err(self.unpublished());
793 }
794 self.catalog.config::<C>(&self.name).ok_or(crate::Error::NotPublished)
795 }
796
797 pub(crate) fn replace(&mut self, config: C) -> crate::Result<()> {
798 self.stage(config)?.commit()
799 }
800
801 pub(crate) fn supply_bitrate(&mut self, bitrate: u64) -> crate::Result<()> {
804 let mut config = self.config()?;
805 let mut estimate = config.estimate();
806 estimate.bitrate = Some(bitrate);
807 config.set_estimate(estimate);
808 let mut supplied = self.supplied.clone();
809 supplied.bitrate = Some(bitrate);
810 let name = self.name.clone();
811 let mut guard = self.stage(config)?;
812 if C::detects() {
813 guard.hint::<C>(&name, supplied.clone());
814 }
815 guard.commit()?;
816 self.supplied = supplied;
817 Ok(())
818 }
819
820 fn stage(&mut self, config: C) -> crate::Result<super::Guard<'_, E>> {
822 if !self.present {
823 return Err(self.unpublished());
824 }
825 Self::check_decrease(&self.config()?.estimate(), &config.estimate())?;
826 let mut guard = self.catalog.edit()?;
827 write(&mut guard, &self.name, config)?;
828 Ok(guard)
829 }
830}
831
832impl<E: CatalogExt, C: RenditionConfig<E>> std::fmt::Debug for Rendition<E, C> {
835 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
836 f.debug_struct("Rendition")
837 .field("name", &self.name)
838 .field("published", &self.present)
839 .finish_non_exhaustive()
840 }
841}
842
843impl<E: CatalogExt, C: RenditionConfig<E>> Drop for Rendition<E, C> {
844 fn drop(&mut self) {
845 if let Ok(mut catalog) = self.catalog.edit() {
849 catalog.release::<C>(&self.name, self.present);
850 }
851 }
854}
855
856#[cfg(test)]
857mod tests {
858 use super::*;
859
860 fn timed() -> moq_net::track::Info {
862 moq_net::track::Info::default().with_timescale(moq_net::Timescale::MILLI)
863 }
864
865 fn video_track() -> (moq_net::broadcast::Producer, super::super::Producer, VideoTrack) {
866 let mut broadcast = moq_net::broadcast::Info::new().produce();
867 let catalog = super::super::Producer::new(&mut broadcast, super::super::Config::default()).unwrap();
868 let reserved = catalog.reserve();
869 let rendition = reserved.init::<hang::catalog::VideoConfig>("v").unwrap();
870 drop(reserved);
873 (broadcast, catalog, rendition)
874 }
875
876 fn config(bitrate: Option<u64>, jitter: Option<Duration>) -> hang::catalog::VideoConfig {
877 let mut config = hang::catalog::VideoConfig::new(hang::catalog::VideoCodec::VP8);
878 config.bitrate = bitrate;
879 config.jitter = jitter;
880 config
881 }
882
883 #[test]
884 fn video_identity_edits_are_refused_without_changing_the_catalog() {
885 let original = config(Some(1_000_000), None);
886 let mut changed = Vec::new();
887 let mut codec = original.clone();
888 codec.codec = "avc1.42c01e".parse().unwrap();
889 changed.push(codec);
890 let mut description = original.clone();
891 description.description = Some(bytes::Bytes::from_static(&[1, 2, 3]));
892 changed.push(description);
893 let mut container = original.clone();
894 container.container = hang::catalog::Container::Loc;
895 changed.push(container);
896 let mut width = original.clone();
897 width.display_aspect_width = Some(4);
898 changed.push(width);
899 let mut height = original.clone();
900 height.display_aspect_height = Some(3);
901 changed.push(height);
902 for next in changed {
903 for operation in ["set", "replace", "stage"] {
904 let (_broadcast, catalog, mut rendition) = video_track();
905 rendition.set(original.clone()).unwrap();
906 let refused = match operation {
907 "set" => rendition.set(next.clone()).is_err(),
908 "replace" => rendition.replace(next.clone()).is_err(),
909 "stage" => rendition.stage(next.clone()).is_err(),
910 _ => unreachable!(),
911 };
912 assert!(refused, "{operation} retained identity change {next:?}");
913 assert_eq!(catalog.snapshot().video.renditions["v"], original);
914 }
915 }
916 }
917
918 #[test]
919 fn video_size_and_estimates_can_change_in_place() {
920 let (_broadcast, catalog, mut rendition) = video_track();
921 let mut original = config(Some(1_000_000), None);
922 original.coded_width = Some(1280);
923 original.coded_height = Some(720);
924 original.framerate = Some(60.0);
925 rendition.set(original.clone()).unwrap();
926 let mut next = original;
927 next.coded_width = Some(1920);
928 next.coded_height = Some(1080);
929 next.bitrate = Some(500_000);
930 next.framerate = Some(30.0);
931 rendition.set(next.clone()).unwrap();
932 assert_eq!(catalog.snapshot().video.renditions["v"], next);
933 }
934
935 #[test]
936 fn audio_identity_edits_are_refused_without_changing_the_catalog() {
937 let original = hang::catalog::AudioConfig::new(hang::catalog::AudioCodec::Opus, 48_000, 2);
938 let mut changed = Vec::new();
939 let mut codec = original.clone();
940 codec.codec = hang::catalog::AudioCodec::Flac;
941 changed.push(codec);
942 let mut description = original.clone();
943 description.description = Some(bytes::Bytes::from_static(&[1, 2, 3]));
944 changed.push(description);
945 let mut container = original.clone();
946 container.container = hang::catalog::Container::Loc;
947 changed.push(container);
948 let mut sample_rate = original.clone();
949 sample_rate.sample_rate = 44_100;
950 changed.push(sample_rate);
951 let mut channels = original.clone();
952 channels.channel_count = 1;
953 changed.push(channels);
954 for next in changed {
955 for operation in ["set", "replace", "stage"] {
956 let mut broadcast = moq_net::broadcast::Info::new().produce();
957 let catalog = super::super::Producer::new(&mut broadcast, super::super::Config::default()).unwrap();
958 let reserved = catalog.reserve();
959 let mut rendition = reserved.init::<hang::catalog::AudioConfig>("a").unwrap();
960 drop(reserved);
961 rendition.set(original.clone()).unwrap();
962 let refused = match operation {
963 "set" => rendition.set(next.clone()).is_err(),
964 "replace" => rendition.replace(next.clone()).is_err(),
965 "stage" => rendition.stage(next.clone()).is_err(),
966 _ => unreachable!(),
967 };
968 assert!(refused, "{operation} retained identity change {next:?}");
969 assert_eq!(catalog.snapshot().audio.renditions["a"], original);
970 }
971 }
972 }
973
974 #[test]
975 fn rejected_jitter_is_not_retained() {
976 let (_broadcast, catalog, mut rendition) = video_track();
977 for jitter in [Duration::ZERO, Duration::MAX] {
978 assert!(rendition.set(config(None, Some(jitter))).is_err());
979 assert!(catalog.snapshot().video.renditions.is_empty());
980 }
981 rendition.set(config(None, Some(Duration::from_millis(100)))).unwrap();
982 let mut invalid = rendition.config().unwrap();
983 invalid.jitter = Some(Duration::ZERO);
984 assert!(rendition.replace(invalid).is_err());
985 assert_eq!(
986 catalog.snapshot().video.renditions.values().next().unwrap().jitter,
987 Some(Duration::from_millis(100))
988 );
989 }
990
991 #[test]
992 fn published_jitter_never_decreases() {
993 let (_broadcast, catalog, mut rendition) = video_track();
994 rendition.set(config(None, Some(Duration::from_millis(100)))).unwrap();
995 let smaller = config(None, Some(Duration::from_millis(50)));
996 assert!(matches!(
997 rendition.set(smaller.clone()),
998 Err(crate::Error::JitterDecreased)
999 ));
1000 assert!(matches!(rendition.replace(smaller), Err(crate::Error::JitterDecreased)));
1001 assert_eq!(
1002 catalog.snapshot().video.renditions["v"].jitter,
1003 Some(Duration::from_millis(100))
1004 );
1005
1006 let (_broadcast, catalog, mut detected) = video_track();
1007 detected.set(config(None, None)).unwrap();
1008 detected
1009 .estimate(Estimate::default().with_jitter(Duration::from_millis(100)))
1010 .unwrap();
1011 detected
1013 .estimate(Estimate::default().with_jitter(Duration::from_millis(50)))
1014 .unwrap();
1015 assert_eq!(
1016 catalog.snapshot().video.renditions["v"].jitter,
1017 Some(Duration::from_millis(100))
1018 );
1019 }
1020
1021 #[test]
1022 fn reconfigure_floors_only_unsupplied_fields() {
1023 let ms = Duration::from_millis;
1024 for supplied_jitter in [false, true] {
1025 for supplied_delay in [false, true] {
1026 let (_broadcast, catalog, mut rendition) = video_track();
1027 rendition.set(config(None, None)).unwrap();
1028 rendition
1029 .estimate(Estimate::default().with_jitter(ms(100)).with_delay(ms(200)))
1030 .unwrap();
1031 rendition
1033 .estimate(Estimate::default().with_jitter(ms(50)).with_delay(ms(100)))
1034 .unwrap();
1035 let mut next = config(Some(500_000), supplied_jitter.then_some(ms(150)));
1036 next.delay = supplied_delay.then_some(ms(250));
1037 next.coded_width = Some(1920);
1038 next.coded_height = Some(1080);
1039 next.framerate = Some(30.0);
1040 rendition.set(next.clone()).unwrap();
1041 let expected_jitter = Some(ms(if supplied_jitter { 150 } else { 100 }));
1042 let expected_delay = Some(ms(if supplied_delay { 250 } else { 200 }));
1043 next.jitter = expected_jitter;
1044 next.delay = expected_delay;
1045 assert_eq!(catalog.snapshot().video.renditions["v"], next);
1046
1047 rendition
1049 .estimate(Estimate::default().with_jitter(ms(300)).with_delay(ms(400)))
1050 .unwrap();
1051 let current = rendition.config().unwrap();
1052 assert_eq!(
1053 current.jitter,
1054 if supplied_jitter {
1055 expected_jitter
1056 } else {
1057 Some(ms(300))
1058 }
1059 );
1060 assert_eq!(
1061 current.delay,
1062 if supplied_delay { expected_delay } else { Some(ms(400)) }
1063 );
1064 }
1065 }
1066 }
1067
1068 #[test]
1071 fn a_supplied_zero_delay_is_never_measured() {
1072 let (_broadcast, catalog, mut rendition) = video_track();
1073 let mut supplied = config(None, None);
1074 supplied.delay = Some(Duration::ZERO);
1075 rendition.set(supplied).unwrap();
1076 rendition
1077 .estimate(Estimate::default().with_delay(Duration::from_millis(200)))
1078 .unwrap();
1079 assert_eq!(catalog.snapshot().video.renditions["v"].delay, Some(Duration::ZERO));
1080
1081 let json = catalog.snapshot().to_json().unwrap();
1082 assert!(!json.contains("delay"), "{json}");
1083 let rendered = super::super::producer::to_msf(&catalog.snapshot(), &moq_net::Path::default());
1084 assert!(rendered.tracks.iter().all(|track| track.delay.is_none()));
1085 }
1086
1087 #[test]
1088 fn published_delay_never_decreases() {
1089 let (_broadcast, catalog, mut rendition) = video_track();
1090 let delayed = |delay| {
1091 let mut config = config(None, None);
1092 config.delay = delay;
1093 config
1094 };
1095 rendition.set(delayed(Some(Duration::from_millis(200)))).unwrap();
1096 assert!(matches!(
1097 rendition.set(delayed(Some(Duration::from_millis(100)))),
1098 Err(crate::Error::DelayDecreased)
1099 ));
1100 for smaller in [Some(Duration::from_millis(100)), None] {
1101 assert!(matches!(
1102 rendition.replace(delayed(smaller)),
1103 Err(crate::Error::DelayDecreased)
1104 ));
1105 }
1106 rendition.set(delayed(None)).unwrap();
1107 assert_eq!(
1108 catalog.snapshot().video.renditions["v"].delay,
1109 Some(Duration::from_millis(200))
1110 );
1111
1112 let (_broadcast, catalog, mut detected) = video_track();
1113 detected.set(config(None, None)).unwrap();
1114 detected
1115 .estimate(Estimate::default().with_delay(Duration::from_millis(200)))
1116 .unwrap();
1117 detected
1119 .estimate(Estimate::default().with_delay(Duration::from_millis(100)))
1120 .unwrap();
1121 assert_eq!(
1122 catalog.snapshot().video.renditions["v"].delay,
1123 Some(Duration::from_millis(200))
1124 );
1125 }
1126
1127 #[test]
1128 fn measurement_keeps_a_jitter_raised_by_modify() {
1129 let (_broadcast, catalog, mut rendition) = video_track();
1130 rendition.set(config(None, None)).unwrap();
1131 rendition
1132 .estimate(Estimate::default().with_jitter(Duration::from_millis(60)))
1133 .unwrap();
1134 let mut raised = rendition.config().unwrap();
1135 raised.jitter = Some(Duration::from_millis(200));
1136 rendition.replace(raised).unwrap();
1137
1138 rendition
1139 .estimate(Estimate::default().with_jitter(Duration::from_millis(80)))
1140 .unwrap();
1141 assert_eq!(
1142 catalog.snapshot().video.renditions["v"].jitter,
1143 Some(Duration::from_millis(200))
1144 );
1145 rendition
1146 .estimate(Estimate::default().with_jitter(Duration::from_millis(300)))
1147 .unwrap();
1148 assert_eq!(
1149 catalog.snapshot().video.renditions["v"].jitter,
1150 Some(Duration::from_millis(300))
1151 );
1152 }
1153
1154 #[test]
1155 fn published_text_jitter_never_decreases() {
1156 let mut broadcast = moq_net::broadcast::Info::new().produce();
1157 let catalog = super::super::Producer::new(&mut broadcast, super::super::Config::default()).unwrap();
1158 let reserved = catalog.reserve();
1159 let mut rendition = reserved.init::<hang::catalog::TextConfig>("t").unwrap();
1160 drop(reserved);
1161
1162 let text = |jitter| {
1163 let mut config = hang::catalog::TextConfig::new(hang::catalog::TextFormat::Utf8);
1164 config.jitter = jitter;
1165 config
1166 };
1167 rendition.set(text(Some(Duration::from_millis(100)))).unwrap();
1168 assert!(matches!(
1169 rendition.set(text(Some(Duration::from_millis(50)))),
1170 Err(crate::Error::JitterDecreased)
1171 ));
1172 rendition.set(text(None)).unwrap();
1173 assert_eq!(
1174 catalog.snapshot().text.renditions["t"].jitter,
1175 Some(Duration::from_millis(100))
1176 );
1177 }
1178
1179 #[test]
1180 fn importer_returns_rejected_jitter() {
1181 let mut broadcast = moq_net::broadcast::Info::new().produce();
1182 let catalog = super::super::Producer::new(&mut broadcast, super::super::Config::default()).unwrap();
1183 let reserved = catalog.reserve();
1184 let track = broadcast
1185 .create_track("audio", hang::container::track_info(hang::catalog::PRIORITY.audio))
1186 .unwrap();
1187 let mut config: hang::catalog::AudioConfig = crate::codec::aac::Config {
1188 profile: 2,
1189 sample_rate: 48_000,
1190 channel_count: 2,
1191 }
1192 .try_into()
1193 .unwrap();
1194 config.jitter = Some(Duration::ZERO);
1195 assert!(crate::codec::aac::Import::new(track, reserved, config).is_err());
1196 assert!(catalog.snapshot().audio.renditions.is_empty());
1197 }
1198
1199 fn ts(micros: u64) -> moq_net::Timestamp {
1200 moq_net::Timestamp::from_micros(micros).unwrap()
1201 }
1202
1203 fn feed<E: CatalogExt, C: RenditionConfig<E>>(rendition: &mut Rendition<E, C>) {
1206 let mut estimator = super::super::Estimator::new();
1207 estimator.burst(Duration::from_millis(40));
1208 for i in 0..60u64 {
1209 let t = ts(i * 40_000);
1210 estimator.cut(Some(t));
1211 estimator.write(t, 100_000);
1212 rendition.estimate(estimator.reading()).unwrap();
1213 }
1214 }
1215
1216 #[test]
1217 fn detects_absent_jitter_and_bitrate() {
1218 let (_broadcast, catalog, mut rendition) = video_track();
1219 rendition.set(config(None, None)).unwrap();
1220 feed(&mut rendition);
1221
1222 let snapshot = catalog.snapshot();
1223 let config = snapshot.video.renditions.get("v").unwrap();
1224 assert!(config.jitter.is_some(), "absent jitter should be auto-detected");
1225 assert!(config.bitrate.is_some(), "absent bitrate should be auto-detected");
1226 assert_eq!(config.framerate, Some(25.0), "absent framerate should be auto-detected");
1227 }
1228
1229 #[test]
1230 fn keeps_provided_jitter_and_bitrate() {
1231 let (_broadcast, catalog, mut rendition) = video_track();
1232 rendition
1233 .set(config(Some(123), Some(Duration::from_millis(50))))
1234 .unwrap();
1235 feed(&mut rendition);
1236
1237 let snapshot = catalog.snapshot();
1238 let config = snapshot.video.renditions.get("v").unwrap();
1239 assert_eq!(config.bitrate, Some(123), "a provided bitrate must not be overwritten");
1240 assert_eq!(
1241 config.jitter,
1242 Some(Duration::from_millis(50)),
1243 "a provided jitter must not be overwritten"
1244 );
1245 }
1246
1247 #[test]
1250 fn a_config_converts_into_hints_without_losing_the_label() {
1251 let (_broadcast, catalog, mut rendition) = video_track();
1252
1253 let mut source = config(Some(456), None);
1254 source.label = Some("Main camera".to_string());
1255 source.coded_width = Some(1920);
1256 source.coded_height = Some(1080);
1257 let hint = VideoHint::from(source);
1258
1259 let mut first = config(None, None);
1262 hint.apply(&mut first);
1263 rendition.set(first).unwrap();
1264 feed(&mut rendition);
1265 assert_eq!(
1266 catalog.snapshot().video.renditions.get("v").unwrap().label.as_deref(),
1267 Some("Main camera"),
1268 "the label must survive the config the importer publishes up front"
1269 );
1270
1271 let mut resolved = config(None, None);
1272 resolved.coded_width = Some(1280);
1273 resolved.coded_height = Some(720);
1274 hint.apply(&mut resolved);
1275 rendition.set(resolved).unwrap();
1276 feed(&mut rendition);
1277
1278 let snapshot = catalog.snapshot();
1279 let published = snapshot.video.renditions.get("v").unwrap();
1280 assert_eq!(
1281 published.label.as_deref(),
1282 Some("Main camera"),
1283 "the label must survive a config the stream resolved later"
1284 );
1285 assert_eq!(published.bitrate, Some(456), "the rest of the config converts too");
1286 }
1287
1288 #[test]
1291 fn hinted_fields_count_as_supplied() {
1292 let (_broadcast, catalog, mut rendition) = video_track();
1293
1294 let hint = VideoHint {
1295 bitrate: Some(456),
1296 framerate: Some(30.0),
1297 ..Default::default()
1298 };
1299 let mut config = config(None, None);
1300 hint.apply(&mut config);
1301
1302 rendition.set(config).unwrap();
1303 feed(&mut rendition);
1304
1305 let snapshot = catalog.snapshot();
1306 let config = snapshot.video.renditions.get("v").unwrap();
1307 assert_eq!(config.bitrate, Some(456), "a hinted bitrate must not be overwritten");
1308 assert_eq!(
1309 config.framerate,
1310 Some(30.0),
1311 "a hinted framerate must not be overwritten"
1312 );
1313 assert!(config.jitter.is_some(), "the unhinted jitter should still be detected");
1314 }
1315
1316 #[test]
1319 fn measurements_before_set_seed_the_config() {
1320 let (_broadcast, catalog, mut rendition) = video_track();
1321 feed(&mut rendition);
1322 rendition.set(config(None, None)).unwrap();
1323
1324 let snapshot = catalog.snapshot();
1325 let config = snapshot.video.renditions.get("v").unwrap();
1326 assert!(
1327 config.jitter.is_some(),
1328 "the jitter measured before `set` should carry over"
1329 );
1330 assert!(
1331 config.bitrate.is_some(),
1332 "the bitrate measured before `set` should carry over"
1333 );
1334 }
1335
1336 #[test]
1338 fn resetting_recaptures_supplied() {
1339 let (_broadcast, catalog, mut rendition) = video_track();
1340 rendition.set(config(None, None)).unwrap();
1341 feed(&mut rendition);
1342 assert!(catalog.snapshot().video.renditions.get("v").unwrap().bitrate.is_some());
1343
1344 rendition.set(config(Some(789), None)).unwrap();
1345 feed(&mut rendition);
1346
1347 let snapshot = catalog.snapshot();
1348 let config = snapshot.video.renditions.get("v").unwrap();
1349 assert_eq!(config.bitrate, Some(789), "the re-set bitrate is now authoritative");
1350 }
1351
1352 #[test]
1357 fn an_unresolved_rendition_still_owns_its_name() {
1358 let (_broadcast, catalog, mut rendition) = video_track();
1359 assert!(
1360 catalog.snapshot().video.renditions.is_empty(),
1361 "nothing is published until the config resolves"
1362 );
1363
1364 let err = catalog
1365 .reserve()
1366 .init::<hang::catalog::VideoConfig>("v")
1367 .expect_err("an unresolved rendition still owns its name");
1368 assert!(matches!(err, crate::Error::Hang(hang::Error::Duplicate(name)) if name == "v"));
1369
1370 rendition.set(config(Some(123), None)).unwrap();
1372 assert_eq!(
1373 catalog.snapshot().video.renditions.get("v").unwrap().bitrate,
1374 Some(123),
1375 "the importer's config owns the rendition"
1376 );
1377 }
1378
1379 #[test]
1381 fn a_resolved_rendition_still_owns_its_name() {
1382 let (_broadcast, catalog, mut rendition) = video_track();
1383 rendition.set(config(Some(789), None)).unwrap();
1384
1385 assert!(
1386 catalog.reserve().init::<hang::catalog::VideoConfig>("v").is_err(),
1387 "owned by the live rendition"
1388 );
1389 assert_eq!(
1390 catalog.snapshot().video.renditions.get("v").unwrap().bitrate,
1391 Some(789),
1392 "the refused reservation left the rendition intact"
1393 );
1394 }
1395
1396 #[test]
1399 fn dropping_a_rendition_frees_its_name() {
1400 let (_broadcast, catalog, mut rendition) = video_track();
1401 rendition.set(config(None, None)).unwrap();
1402 drop(rendition);
1403 assert!(
1404 catalog.snapshot().video.renditions.is_empty(),
1405 "the entry is retired with its owner"
1406 );
1407
1408 let mut replacement = catalog
1409 .reserve()
1410 .init::<hang::catalog::VideoConfig>("v")
1411 .expect("the name is free once the rendition drops");
1412 replacement.set(config(Some(456), None)).unwrap();
1413 assert_eq!(catalog.snapshot().video.renditions.get("v").unwrap().bitrate, Some(456));
1414 }
1415
1416 #[test]
1419 fn a_name_is_owned_per_section() {
1420 let (_broadcast, catalog, _video) = video_track();
1421 catalog
1422 .reserve()
1423 .init::<hang::catalog::AudioConfig>("v")
1424 .expect("an audio rendition is a different section from a video one");
1425 }
1426
1427 #[test]
1430 fn an_existing_entry_owns_its_name() {
1431 let mut broadcast = moq_net::broadcast::Info::new().produce();
1432 let mut catalog = super::super::Producer::new(&mut broadcast, super::super::Config::default()).unwrap();
1433 catalog.edit().unwrap().video.insert("v", config(None, None)).unwrap();
1434
1435 assert!(
1436 catalog.reserve().init::<hang::catalog::VideoConfig>("v").is_err(),
1437 "the catalog already carries it"
1438 );
1439 }
1440
1441 mod custom {
1442 use std::collections::BTreeMap;
1443
1444 use serde::{Deserialize, Serialize};
1445
1446 use super::*;
1447
1448 #[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq)]
1449 struct TelemetryExt {
1450 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1451 telemetry: BTreeMap<String, Telemetry>,
1452 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1453 exploding: BTreeMap<String, Exploding>,
1454 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
1455 stubborn: BTreeMap<String, Stubborn>,
1456 #[serde(default, skip_serializing_if = "BTreeMap::is_empty", serialize_with = "at_most_one")]
1457 solo: BTreeMap<String, Solo>,
1458 }
1459
1460 fn at_most_one<S: serde::Serializer>(solo: &BTreeMap<String, Solo>, serializer: S) -> Result<S::Ok, S::Error> {
1463 if solo.len() > 1 {
1464 return Err(serde::ser::Error::custom("only one solo entry"));
1465 }
1466 solo.serialize(serializer)
1467 }
1468
1469 impl CatalogExt for TelemetryExt {}
1470
1471 #[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq)]
1472 struct Telemetry {
1473 schema: String,
1474 #[serde(default, skip_serializing_if = "Option::is_none")]
1475 bitrate: Option<u64>,
1476 }
1477
1478 impl RenditionConfig<TelemetryExt> for Telemetry {
1479 fn detects() -> bool {
1480 true
1481 }
1482
1483 fn insert(self, catalog: &mut Catalog<TelemetryExt>, name: &str) {
1484 catalog.ext.telemetry.insert(name.to_string(), self);
1485 }
1486 fn get_mut<'a>(catalog: &'a mut Catalog<TelemetryExt>, name: &str) -> Option<&'a mut Self> {
1487 catalog.ext.telemetry.get_mut(name)
1488 }
1489 fn remove(catalog: &mut Catalog<TelemetryExt>, name: &str) {
1490 catalog.ext.telemetry.remove(name);
1491 }
1492
1493 fn estimate(&self) -> Estimate {
1495 Estimate::default().with_bitrate(self.bitrate)
1496 }
1497 fn set_estimate(&mut self, estimate: Estimate) {
1498 self.bitrate = estimate.bitrate;
1499 }
1500 }
1501
1502 fn telemetry(bitrate: Option<u64>) -> Telemetry {
1503 Telemetry {
1504 schema: "gps/v1".to_string(),
1505 bitrate,
1506 }
1507 }
1508
1509 fn produce() -> (moq_net::broadcast::Producer, crate::catalog::Producer<TelemetryExt>) {
1510 let mut broadcast = moq_net::broadcast::Info::new().produce();
1511 let config = crate::catalog::Config::default().with_catalog(Catalog::<TelemetryExt>::default());
1512 let catalog = crate::catalog::Producer::new(&mut broadcast, config).unwrap();
1513 (broadcast, catalog)
1514 }
1515
1516 #[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq)]
1519 struct Exploding {
1520 wrote: bool,
1522 }
1523
1524 impl RenditionConfig<TelemetryExt> for Exploding {
1525 fn insert(self, catalog: &mut Catalog<TelemetryExt>, name: &str) {
1526 if self.wrote {
1527 catalog.ext.exploding.insert(name.to_string(), self);
1528 }
1529 panic!("insert exploded");
1530 }
1531 fn get_mut<'a>(catalog: &'a mut Catalog<TelemetryExt>, name: &str) -> Option<&'a mut Self> {
1532 catalog.ext.exploding.get_mut(name)
1533 }
1534 fn remove(catalog: &mut Catalog<TelemetryExt>, name: &str) {
1535 catalog.ext.exploding.remove(name);
1536 }
1537 }
1538
1539 #[test]
1544 fn a_poisoned_lock_does_not_take_the_producer_down() {
1545 let (_broadcast, catalog) = produce();
1546 let reserved = catalog.reserve();
1547
1548 let err = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1549 let mut boom = reserved.init::<Exploding>("gps").unwrap();
1550 boom.set(Exploding { wrote: false }).unwrap();
1551 }))
1552 .expect_err("the config's insert panics");
1553 assert!(
1554 err.downcast_ref::<&str>().is_some_and(|msg| *msg == "insert exploded"),
1555 "the panic is the one the config raised, not a lock failure"
1556 );
1557
1558 assert!(catalog.snapshot().ext.telemetry.is_empty());
1560 reserved
1561 .init::<Exploding>("gps")
1562 .expect("the unwound rendition released its name");
1563 }
1564
1565 #[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq)]
1568 struct Stubborn;
1569
1570 impl RenditionConfig<TelemetryExt> for Stubborn {
1571 fn insert(self, catalog: &mut Catalog<TelemetryExt>, name: &str) {
1572 catalog.ext.stubborn.insert(name.to_string(), self);
1573 }
1574 fn get_mut<'a>(catalog: &'a mut Catalog<TelemetryExt>, name: &str) -> Option<&'a mut Self> {
1575 catalog.ext.stubborn.get_mut(name)
1576 }
1577 fn remove(catalog: &mut Catalog<TelemetryExt>, name: &str) {
1578 catalog.ext.stubborn.remove(name);
1579 panic!("remove exploded");
1580 }
1581 }
1582
1583 #[test]
1587 fn a_panicking_remove_still_frees_the_name() {
1588 let (_broadcast, catalog) = produce();
1589 let reserved = catalog.reserve();
1590
1591 let mut rendition = reserved.init::<Stubborn>("gps").unwrap();
1592 rendition.set(Stubborn).unwrap();
1593
1594 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| drop(rendition)))
1595 .expect_err("the config's remove panics");
1596
1597 reserved
1598 .init::<Stubborn>("gps")
1599 .expect("a name held by a blown-up cleanup hook would be lost forever");
1600 }
1601
1602 #[test]
1604 fn an_unwinding_rendition_retires_a_partially_written_entry() {
1605 let (_broadcast, catalog) = produce();
1606 let reserved = catalog.reserve();
1607
1608 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1609 let mut boom = reserved.init::<Exploding>("gps").unwrap();
1610 boom.set(Exploding { wrote: true }).unwrap();
1611 }))
1612 .expect_err("the config's insert panics after writing");
1613
1614 assert!(
1615 catalog.snapshot().ext.exploding.is_empty(),
1616 "the entry the panicking insert wrote is retired with its owner"
1617 );
1618 reserved
1619 .init::<Exploding>("gps")
1620 .expect("a stranded entry would refuse this forever");
1621 }
1622
1623 #[derive(Serialize, Deserialize, Clone, Default, Debug, PartialEq)]
1625 struct Solo;
1626
1627 impl RenditionConfig<TelemetryExt> for Solo {
1628 fn insert(self, catalog: &mut Catalog<TelemetryExt>, name: &str) {
1629 catalog.ext.solo.insert(name.to_string(), self);
1630 }
1631 fn get_mut<'a>(catalog: &'a mut Catalog<TelemetryExt>, name: &str) -> Option<&'a mut Self> {
1632 catalog.ext.solo.get_mut(name)
1633 }
1634 fn remove(catalog: &mut Catalog<TelemetryExt>, name: &str) {
1635 catalog.ext.solo.remove(name);
1636 }
1637 }
1638
1639 #[test]
1642 fn an_entry_that_breaks_the_extension_is_refused() {
1643 let (_broadcast, catalog) = produce();
1644 let reserved = catalog.reserve();
1645 let mut first = reserved.init::<Solo>("a").unwrap();
1646 let mut second = reserved.init::<Solo>("b").unwrap();
1647
1648 first.set(Solo).unwrap();
1649 assert!(
1650 matches!(second.set(Solo), Err(crate::Error::Json(_))),
1651 "the second entry makes the extension unserializable"
1652 );
1653
1654 let snapshot = catalog.snapshot();
1655 assert_eq!(snapshot.ext.solo.keys().collect::<Vec<_>>(), ["a"]);
1656 serde_json::to_string(&snapshot).expect("the refused edit left the catalog serializable");
1657 }
1658
1659 #[test]
1661 fn detects_and_advertises() {
1662 let (_broadcast, catalog) = produce();
1663 let reserved = catalog.reserve();
1664 let mut rendition = reserved.init::<Telemetry>("gps").unwrap();
1665 drop(reserved);
1666
1667 rendition.set(telemetry(None)).unwrap();
1668 feed(&mut rendition);
1669
1670 let snapshot = catalog.snapshot();
1671 let config = snapshot.ext.telemetry.get("gps").unwrap();
1672 assert!(config.bitrate.is_some(), "absent bitrate should be auto-detected");
1673
1674 drop(rendition);
1675 assert!(
1676 !catalog.snapshot().ext.telemetry.contains_key("gps"),
1677 "the rendition should be removed on drop"
1678 );
1679 }
1680
1681 #[test]
1685 fn measures_a_custom_track() {
1686 let (broadcast, catalog) = produce();
1687 let reserved = catalog.reserve();
1688 let net = broadcast.create_track("gps", timed()).unwrap();
1689 let mut track = reserved
1690 .track(
1691 net,
1692 crate::catalog::hang::Wire::legacy(crate::container::Kind::Data),
1693 None,
1694 )
1695 .unwrap();
1696 drop(reserved);
1697 assert!(matches!(track.modify(), Err(crate::Error::NotPublished)));
1698 track.set(telemetry(None)).unwrap();
1699
1700 for i in 0..60u64 {
1702 track
1703 .write(crate::container::Frame {
1704 timestamp: ts(i * 40_000),
1705 decode: None,
1706 duration: None,
1707 payload: bytes::Bytes::from(vec![0u8; 5_000]),
1708 keyframe: true,
1709 })
1710 .unwrap();
1711 }
1712
1713 let snapshot = catalog.snapshot();
1714 let config = snapshot.ext.telemetry.get("gps").unwrap();
1715 assert_eq!(config.bitrate, Some(1_000_000));
1716 }
1717
1718 #[test]
1720 fn keeps_supplied_bitrate() {
1721 let (_broadcast, catalog) = produce();
1722 let reserved = catalog.reserve();
1723 let mut rendition = reserved.init::<Telemetry>("gps").unwrap();
1724 drop(reserved);
1725
1726 rendition.set(telemetry(Some(4_200))).unwrap();
1727 feed(&mut rendition);
1728
1729 let snapshot = catalog.snapshot();
1730 assert_eq!(snapshot.ext.telemetry.get("gps").unwrap().bitrate, Some(4_200));
1731 }
1732
1733 #[test]
1735 fn gates_with_media_tracks() {
1736 let (_broadcast, catalog) = produce();
1737 let mut consumer = catalog.consume().unwrap();
1738
1739 let reserved = catalog.reserve();
1740 let mut video = reserved.init::<hang::catalog::VideoConfig>("v").unwrap();
1741 let mut gps = reserved.init::<Telemetry>("gps").unwrap();
1742 drop(reserved);
1743
1744 let waiter = kio::Waiter::noop();
1745 video.set(config(None, None)).unwrap();
1746 assert!(
1747 matches!(consumer.poll_next(&waiter), std::task::Poll::Pending),
1748 "the catalog stays withheld while the telemetry rendition is unresolved"
1749 );
1750
1751 gps.set(telemetry(None)).unwrap();
1752
1753 let mut latest = None;
1754 while let std::task::Poll::Ready(Ok(Some(catalog))) = consumer.poll_next(&waiter) {
1755 latest = Some(catalog.value);
1756 }
1757 let published = latest.expect("catalog published");
1758 assert!(published.video.renditions.contains_key("v"));
1759 assert!(published.ext.telemetry.contains_key("gps"));
1760 }
1761 }
1762}