1mod av1;
2mod codec;
3mod color;
4mod h264;
5mod h265;
6mod projection;
7mod stereo;
8mod vp9;
9
10pub use av1::*;
11pub use codec::*;
12pub use color::*;
13pub use h264::*;
14pub use h265::*;
15pub use projection::*;
16pub use stereo::*;
17pub use vp9::*;
18
19use std::collections::{BTreeMap, btree_map};
20
21use bytes::Bytes;
22use serde::{Deserialize, Serialize};
23use serde_with::DisplayFromStr;
24
25use crate::catalog::Container;
26use crate::catalog::hex::Hex;
27use crate::catalog::millis::MillisCeil;
28
29#[serde_with::serde_as]
39#[serde_with::skip_serializing_none]
40#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Default)]
41#[serde(rename_all = "camelCase")]
42#[non_exhaustive]
43pub struct Video {
44 #[serde(
50 deserialize_with = "crate::catalog::deserialize_entries",
51 serialize_with = "crate::catalog::serialize_entries"
52 )]
53 pub renditions: BTreeMap<String, VideoConfig>,
54
55 #[serde(default)]
58 #[serde_as(as = "crate::catalog::NotNull")]
59 pub display: Option<Display>,
60
61 #[serde(default)]
64 #[serde_as(as = "crate::catalog::NotNull")]
65 pub rotation: Option<f64>,
66
67 #[serde(default)]
70 #[serde_as(as = "crate::catalog::NotNull")]
71 pub flip: Option<bool>,
72}
73
74#[derive(Debug, Clone, PartialEq, Default)]
76#[non_exhaustive]
77pub struct VideoProperties {
78 pub display: Option<Display>,
80
81 pub rotation: Option<f64>,
83
84 pub flip: Option<bool>,
86}
87
88impl VideoProperties {
89 fn normalized(mut self) -> crate::Result<Self> {
90 self.rotation = self.rotation.map(normalize_video_rotation).transpose()?;
91 Ok(self)
92 }
93}
94
95const FULL_TURN_DEGREES: f64 = 360.0;
96const QUARTER_TURN_DEGREES: f64 = 90.0;
97const QUARTER_TURNS_PER_FULL_TURN: u16 = 4;
98
99fn normalize_video_rotation(rotation: f64) -> crate::Result<f64> {
100 if !rotation.is_finite() {
101 return Err(crate::Error::InvalidVideoRotation);
102 }
103
104 let normalized = rotation.rem_euclid(FULL_TURN_DEGREES);
105 let quarter_turns = (normalized / QUARTER_TURN_DEGREES).round() as u16 % QUARTER_TURNS_PER_FULL_TURN;
106 Ok(quarter_turns as f64 * QUARTER_TURN_DEGREES)
107}
108
109impl Video {
110 pub fn insert(&mut self, name: &str, config: VideoConfig) -> crate::Result<()> {
112 let btree_map::Entry::Vacant(entry) = self.renditions.entry(name.to_string()) else {
113 return Err(crate::Error::Duplicate(name.to_string()));
114 };
115 entry.insert(config);
116 Ok(())
117 }
118
119 pub fn remove(&mut self, name: &str) -> Option<VideoConfig> {
121 self.renditions.remove(name)
122 }
123
124 pub fn is_empty(&self) -> bool {
128 self.renditions.is_empty()
129 }
130
131 pub fn enabled(&self) -> impl Iterator<Item = (&String, &VideoConfig)> {
133 self.ranked().filter(|(_, config)| config.enabled)
134 }
135
136 pub fn ranked(&self) -> impl Iterator<Item = (&String, &VideoConfig)> {
144 let mut ranked: Vec<_> = self.renditions.iter().collect();
145 ranked.sort_by_key(|(_, config)| {
146 let area = u64::from(config.coded_width.unwrap_or(0)) * u64::from(config.coded_height.unwrap_or(0));
147 std::cmp::Reverse((config.enabled, config.preference, area, config.bitrate))
148 });
149 ranked.into_iter()
150 }
151
152 pub fn orientation(&self, config: &VideoConfig) -> Option<Orientation> {
159 if let Some(display) = &self.display {
160 return Orientation::of(display.width, display.height);
161 }
162 let (width, height) = match (config.display_aspect_width, config.display_aspect_height) {
163 (Some(width), Some(height)) => (width, height),
164 _ => (config.coded_width?, config.coded_height?),
165 };
166 let orientation = Orientation::of(width, height)?;
167 let rotation = self
170 .rotation
171 .and_then(|rotation| normalize_video_rotation(rotation).ok());
172 let turned = (rotation.unwrap_or(0.0) / QUARTER_TURN_DEGREES).rem_euclid(2.0) == 1.0;
173 Some(if turned { orientation.turned() } else { orientation })
174 }
175
176 pub fn set_properties(&mut self, properties: VideoProperties) -> crate::Result<()> {
178 let properties = properties.normalized()?;
179 self.display = properties.display;
180 self.rotation = properties.rotation;
181 self.flip = properties.flip;
182 Ok(())
183 }
184}
185
186#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
188pub enum Orientation {
189 Landscape,
191 Portrait,
193}
194
195impl Orientation {
196 pub fn of(width: u32, height: u32) -> Option<Self> {
198 match width.cmp(&height) {
199 std::cmp::Ordering::Greater => Some(Self::Landscape),
200 std::cmp::Ordering::Less => Some(Self::Portrait),
201 std::cmp::Ordering::Equal => None,
202 }
203 }
204
205 fn turned(self) -> Self {
206 match self {
207 Self::Landscape => Self::Portrait,
208 Self::Portrait => Self::Landscape,
209 }
210 }
211}
212
213#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
215#[serde(rename_all = "camelCase")]
216pub struct Display {
217 pub width: u32,
219 pub height: u32,
221}
222
223#[serde_with::serde_as]
236#[serde_with::skip_serializing_none]
237#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
238#[serde(rename_all = "camelCase")]
239#[non_exhaustive]
240pub struct VideoConfig {
241 #[serde(default)]
251 #[serde_as(as = "crate::catalog::NotNull")]
252 pub broadcast: Option<moq_net::path::Relative>,
253
254 #[serde(default)]
262 #[serde_as(as = "crate::catalog::NotNull")]
263 pub track: Option<String>,
264
265 #[serde(default)]
267 #[serde_as(as = "crate::catalog::NotNull")]
268 pub label: Option<String>,
269
270 #[serde_as(as = "DisplayFromStr")]
273 pub codec: VideoCodec,
274
275 #[serde(default)]
280 #[serde_as(as = "crate::catalog::NotNull<Hex>")]
281 pub description: Option<Bytes>,
282
283 #[serde_as(as = "crate::catalog::NotNull")]
288 #[serde(default)]
289 pub coded_width: Option<u32>,
290 #[serde_as(as = "crate::catalog::NotNull")]
292 #[serde(default)]
293 pub coded_height: Option<u32>,
294
295 #[serde_as(as = "crate::catalog::NotNull")]
301 #[serde(default)]
302 pub display_aspect_width: Option<u32>,
303 #[serde_as(as = "crate::catalog::NotNull")]
305 #[serde(default)]
306 pub display_aspect_height: Option<u32>,
307
308 #[serde(default)]
312 #[serde_as(as = "crate::catalog::NotNull")]
313 pub color: Option<Color>,
314
315 #[serde(default)]
319 #[serde_as(as = "crate::catalog::NotNull")]
320 pub projection: Option<Projection>,
321
322 #[serde(default)]
326 #[serde_as(as = "crate::catalog::NotNull<DisplayFromStr>")]
327 pub stereo: Option<Stereo>,
328
329 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
333 pub interlaced: bool,
334
335 #[serde(default)]
337 #[serde_as(as = "crate::catalog::NotNull<crate::snapshot::Number>")]
338 pub bitrate: Option<u64>,
339
340 #[serde(
343 default = "crate::catalog::enabled_default",
344 skip_serializing_if = "crate::catalog::enabled_skip"
345 )]
346 pub enabled: bool,
347
348 #[serde(default, skip_serializing_if = "is_zero")]
355 pub preference: i32,
356
357 #[serde(default)]
359 #[serde_as(as = "crate::catalog::NotNull")]
360 pub framerate: Option<f64>,
361
362 #[serde(default)]
369 #[serde_as(as = "crate::catalog::NotNull")]
370 pub reorder: Option<u8>,
371
372 #[serde(default)]
376 #[serde_as(as = "crate::catalog::NotNull")]
377 pub optimize_for_latency: Option<bool>,
378
379 #[serde(default)]
382 pub container: Container,
383
384 #[serde_as(as = "MillisCeil")]
396 #[serde(default)]
397 pub jitter: Option<std::time::Duration>,
398
399 #[serde_as(as = "MillisCeil")]
417 #[serde(default, skip_serializing_if = "crate::catalog::millis::no_delay")]
418 pub delay: Option<std::time::Duration>,
419}
420
421impl VideoConfig {
422 pub fn new(codec: impl Into<VideoCodec>) -> Self {
429 Self {
430 broadcast: None,
431 track: None,
432 label: None,
433 codec: codec.into(),
434 description: None,
435 coded_width: None,
436 coded_height: None,
437 display_aspect_width: None,
438 display_aspect_height: None,
439 color: None,
440 projection: None,
441 stereo: None,
442 interlaced: false,
443 bitrate: None,
444 enabled: true,
445 preference: 0,
446 framerate: None,
447 reorder: None,
448 optimize_for_latency: None,
449 container: Container::default(),
450 jitter: None,
451 delay: None,
452 }
453 }
454
455 pub fn same_identity(&self, other: &Self) -> bool {
463 self.codec == other.codec
464 && self.description == other.description
465 && self.container == other.container
466 && self.display_aspect_width == other.display_aspect_width
467 && self.display_aspect_height == other.display_aspect_height
468 && self.interlaced == other.interlaced
469 }
470}
471
472impl crate::catalog::Entry for VideoConfig {
473 fn check(&self) -> crate::Result<()> {
474 for (field, value) in [
475 ("codedWidth", self.coded_width),
476 ("codedHeight", self.coded_height),
477 ("displayAspectWidth", self.display_aspect_width),
478 ("displayAspectHeight", self.display_aspect_height),
479 ] {
480 if value == Some(0) {
481 return Err(crate::Error::Zero(field));
482 }
483 }
484 if let Some(projection) = &self.projection {
485 projection.check()?;
486 }
487 Ok(())
488 }
489
490 fn version(&self, id: &str) -> Option<u64> {
491 crate::catalog::renamed_version(self, id)
492 }
493}
494
495fn is_zero(value: &i32) -> bool {
496 *value == 0
497}
498
499#[cfg(test)]
500mod test {
501 use crate::catalog::{Container, H264};
502
503 use super::*;
504
505 #[test]
506 fn reorder_keeps_zero_distinct_from_absent() {
507 let mut config = VideoConfig::new(VideoCodec::VP8);
508 assert!(serde_json::to_value(&config).unwrap().get("reorder").is_none());
509 for depth in [0, 2] {
510 config.reorder = Some(depth);
511 let encoded = serde_json::to_value(&config).unwrap();
512 assert_eq!(encoded["reorder"], depth);
513 let decoded: VideoConfig = serde_json::from_value(encoded).unwrap();
514 assert_eq!(decoded.reorder, Some(depth));
515 }
516 }
517
518 #[test]
519 fn orientation_follows_the_shown_shape() {
520 let sized = |width, height| {
521 let mut config = VideoConfig::new(VideoCodec::VP8);
522 config.coded_width = Some(width);
523 config.coded_height = Some(height);
524 config
525 };
526 let mut video = Video::default();
527 assert_eq!(video.orientation(&sized(1920, 1080)), Some(Orientation::Landscape));
528 assert_eq!(video.orientation(&sized(1080, 1920)), Some(Orientation::Portrait));
529 assert_eq!(video.orientation(&sized(720, 720)), None);
530 assert_eq!(video.orientation(&VideoConfig::new(VideoCodec::VP8)), None);
531
532 let mut anamorphic = sized(1440, 1080);
534 anamorphic.display_aspect_width = Some(9);
535 anamorphic.display_aspect_height = Some(16);
536 assert_eq!(video.orientation(&anamorphic), Some(Orientation::Portrait));
537
538 for (rotation, expected) in [
540 (90.0, Orientation::Portrait),
541 (-90.0, Orientation::Portrait),
542 (180.0, Orientation::Landscape),
543 (269.0, Orientation::Portrait),
544 (-45.0, Orientation::Landscape),
546 (315.0, Orientation::Landscape),
547 (-135.0, Orientation::Portrait),
548 (225.0, Orientation::Portrait),
549 (44.99999999999999, Orientation::Landscape),
551 (f64::NAN, Orientation::Landscape),
552 ] {
553 video.rotation = Some(rotation);
554 assert_eq!(video.orientation(&sized(1920, 1080)), Some(expected), "{rotation}");
555 }
556
557 video.display = Some(Display {
559 width: 1080,
560 height: 1920,
561 });
562 assert_eq!(video.orientation(&sized(1920, 1080)), Some(Orientation::Portrait));
563 }
564
565 #[test]
566 fn ranked_orders_by_picture_then_bitrate() {
567 fn rendition(size: Option<(u32, u32)>, bitrate: Option<u64>) -> VideoConfig {
568 let mut config = VideoConfig::new(VideoCodec::VP8);
569 config.coded_width = size.map(|(w, _)| w);
570 config.coded_height = size.map(|(_, h)| h);
571 config.bitrate = bitrate;
572 config
573 }
574
575 let mut video = Video::default();
576 video.insert("a", rendition(None, Some(9_000_000))).unwrap();
578 video.insert("b", rendition(Some((640, 360)), Some(1_000_000))).unwrap();
579 video.insert("c", rendition(Some((1280, 720)), None)).unwrap();
580 video
581 .insert("d", rendition(Some((1280, 720)), Some(3_000_000)))
582 .unwrap();
583 video
584 .insert("e", rendition(Some((1280, 720)), Some(3_000_000)))
585 .unwrap();
586 video
587 .insert("f", rendition(Some((1920, 1080)), Some(6_000_000)))
588 .unwrap();
589
590 let names: Vec<_> = video.ranked().map(|(name, _)| name.as_str()).collect();
591 assert_eq!(names, ["f", "d", "e", "c", "b", "a"]);
592
593 video.renditions.get_mut("f").unwrap().enabled = false;
595 let names: Vec<_> = video.ranked().map(|(name, _)| name.as_str()).collect();
596 assert_eq!(names, ["d", "e", "c", "b", "a", "f"]);
597 let names: Vec<_> = video.enabled().map(|(name, _)| name.as_str()).collect();
598 assert_eq!(names, ["d", "e", "c", "b", "a"]);
599 }
600
601 #[test]
602 fn disabled_renditions_are_ineligible_until_reenabled() {
603 let mut catalog = Video::default();
604 let config = VideoConfig::new(VideoCodec::VP8);
605 catalog.renditions.insert("track".into(), config);
606 assert_eq!(catalog.enabled().count(), 1);
607 catalog.renditions.get_mut("track").unwrap().enabled = false;
608 assert_eq!(catalog.enabled().count(), 0);
609 assert_eq!(catalog.ranked().count(), 1);
610 catalog.renditions.get_mut("track").unwrap().enabled = true;
611 assert_eq!(catalog.enabled().count(), 1);
612 }
613
614 #[test]
615 fn display_aspect_uses_canonical_json_names() {
616 let mut config = VideoConfig::new(H264 {
617 profile: 0x64,
618 constraints: 0,
619 level: 0x1f,
620 inline: false,
621 });
622 config.display_aspect_width = Some(4);
623 config.display_aspect_height = Some(3);
624 config.container = Container::Legacy;
625
626 let encoded = serde_json::to_value(config).expect("failed to encode");
627 assert_eq!(encoded["displayAspectWidth"], 4);
628 assert_eq!(encoded["displayAspectHeight"], 3);
629 assert!(encoded.get("displayRatioWidth").is_none());
630 assert!(encoded.get("displayRatioHeight").is_none());
631 }
632
633 #[test]
634 fn enabled_is_written_only_when_false() {
635 let mut config = VideoConfig::new(VideoCodec::VP8);
636 let encoded = serde_json::to_value(&config).expect("failed to encode");
637 assert!(encoded.get("enabled").is_none());
638
639 config.enabled = false;
640 let encoded = serde_json::to_value(&config).expect("failed to encode");
641 assert_eq!(encoded["enabled"], false);
642
643 let decoded: VideoConfig = serde_json::from_value(encoded).expect("failed to decode");
644 assert!(!decoded.enabled);
645 }
646
647 #[test]
648 fn interlaced_is_written_only_when_true() {
649 let mut config = VideoConfig::new(VideoCodec::VP8);
650 let encoded = serde_json::to_value(&config).expect("failed to encode");
651 assert!(encoded.get("interlaced").is_none());
652
653 config.interlaced = true;
654 let encoded = serde_json::to_value(&config).expect("failed to encode");
655 assert_eq!(encoded["interlaced"], true);
656
657 let decoded: VideoConfig = serde_json::from_value(encoded).expect("failed to decode");
658 assert!(decoded.interlaced);
659 }
660
661 #[test]
662 fn preference_is_written_only_when_nonzero() {
663 let mut config = VideoConfig::new(VideoCodec::VP8);
664 let encoded = serde_json::to_value(&config).expect("failed to encode");
665 assert!(encoded.get("preference").is_none());
666
667 config.preference = -1;
668 let encoded = serde_json::to_value(&config).expect("failed to encode");
669 assert_eq!(encoded["preference"], -1);
670
671 let decoded: VideoConfig = serde_json::from_value(encoded).expect("failed to decode");
672 assert_eq!(decoded.preference, -1);
673 }
674
675 #[test]
676 fn ranked_orders_by_preference_before_picture() {
677 let mut source = VideoConfig::new(VideoCodec::VP8);
678 source.coded_width = Some(640);
679 source.coded_height = Some(360);
680 source.bitrate = Some(500_000);
681
682 let mut fallback = VideoConfig::new(VideoCodec::VP8);
683 fallback.coded_width = Some(1920);
684 fallback.coded_height = Some(1080);
685 fallback.bitrate = Some(6_000_000);
686 fallback.preference = -1;
687
688 let mut video = Video::default();
689 video.insert("a", fallback).unwrap();
690 video.insert("b", source).unwrap();
691
692 let names: Vec<_> = video.ranked().map(|(name, _)| name.as_str()).collect();
693 assert_eq!(names, ["b", "a"]);
694
695 video.renditions.get_mut("b").unwrap().enabled = false;
697 let names: Vec<_> = video.ranked().map(|(name, _)| name.as_str()).collect();
698 assert_eq!(names, ["a", "b"]);
699 }
700
701 #[test]
702 fn legacy_stalled_is_ignored() {
703 let json = serde_json::json!({ "codec": "vp8", "stalled": true });
704 let config: VideoConfig = serde_json::from_value(json).expect("failed to decode");
705 assert!(config.enabled);
706 assert!(serde_json::to_value(&config).unwrap().get("stalled").is_none());
707 }
708
709 #[test]
710 fn normalizes_video_rotation_to_quarter_turns() {
711 for (rotation, expected) in [
712 (0.0, 0.0),
713 (44.9, 0.0),
714 (45.0, 90.0),
715 (134.9, 90.0),
716 (135.0, 180.0),
717 (225.0, 270.0),
718 (315.0, 0.0),
719 (360.0, 0.0),
720 (-45.0, 0.0),
721 ] {
722 assert_eq!(normalize_video_rotation(rotation).unwrap(), expected);
723 }
724 }
725
726 #[test]
727 fn rejects_non_finite_video_rotation() {
728 for rotation in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
729 assert!(matches!(
730 normalize_video_rotation(rotation),
731 Err(crate::Error::InvalidVideoRotation)
732 ));
733 }
734 }
735
736 #[test]
737 fn invalid_rotation_does_not_replace_video_properties() {
738 let mut video = Video {
739 display: Some(Display {
740 width: 640,
741 height: 480,
742 }),
743 rotation: Some(90.0),
744 flip: Some(true),
745 ..Default::default()
746 };
747 let expected = video.clone();
748
749 assert!(matches!(
750 video.set_properties(VideoProperties {
751 display: None,
752 rotation: Some(f64::NAN),
753 flip: None,
754 }),
755 Err(crate::Error::InvalidVideoRotation)
756 ));
757 assert_eq!(video, expected);
758 }
759
760 #[test]
761 fn video_properties_replace_shared_fields_without_touching_renditions() {
762 let mut video = Video::default();
763 video
764 .insert(
765 "video",
766 VideoConfig::new(H264 {
767 profile: 0x64,
768 constraints: 0,
769 level: 0x1f,
770 inline: false,
771 }),
772 )
773 .unwrap();
774 video.display = Some(Display {
775 width: 640,
776 height: 480,
777 });
778 video.rotation = Some(90.0);
779 video.flip = Some(true);
780 let renditions = video.renditions.clone();
781
782 video
783 .set_properties(VideoProperties {
784 display: Some(Display {
785 width: 1920,
786 height: 1080,
787 }),
788 rotation: Some(315.0),
789 flip: None,
790 })
791 .unwrap();
792
793 assert_eq!(video.renditions, renditions);
794 assert_eq!(
795 video.display,
796 Some(Display {
797 width: 1920,
798 height: 1080
799 })
800 );
801 assert_eq!(video.rotation, Some(0.0));
802 assert_eq!(video.flip, None);
803 }
804}