Skip to main content

hang/catalog/video/
mod.rs

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/// Information about a video track in the catalog.
30///
31/// This struct contains a map of renditions (different quality/codec options)
32/// and optional metadata like detection, display settings, rotation, and flip.
33///
34/// Marked `#[non_exhaustive]` so additional optional fields can be added without
35/// bumping the major version. External callers start from [`Video::default`] and
36/// fill in what they need ([`insert`](Self::insert) for renditions); struct-literal
37/// construction (with or without `..base`) is not available outside this crate.
38#[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	/// A map of track name to rendition configuration.
45	/// This is not an array in order for it to work with JSON Merge Patch.
46	/// We use a BTreeMap so keys are sorted alphabetically for *some* deterministic behavior.
47	///
48	/// A malformed rendition refuses the whole catalog when decoding.
49	#[serde(
50		deserialize_with = "crate::catalog::deserialize_entries",
51		serialize_with = "crate::catalog::serialize_entries"
52	)]
53	pub renditions: BTreeMap<String, VideoConfig>,
54
55	/// Render the video at this size in pixels.
56	/// This is separate from the display aspect ratio because it does not require reinitialization.
57	#[serde(default)]
58	#[serde_as(as = "crate::catalog::NotNull")]
59	pub display: Option<Display>,
60
61	/// The clockwise rotation of the video in degrees.
62	/// Default: 0
63	#[serde(default)]
64	#[serde_as(as = "crate::catalog::NotNull")]
65	pub rotation: Option<f64>,
66
67	/// If true, the decoder will flip the video horizontally
68	/// Default: false
69	#[serde(default)]
70	#[serde_as(as = "crate::catalog::NotNull")]
71	pub flip: Option<bool>,
72}
73
74/// Catalog properties shared by every video rendition.
75#[derive(Debug, Clone, PartialEq, Default)]
76#[non_exhaustive]
77pub struct VideoProperties {
78	/// Render the video at this final size after rotation, or clear the explicit size when absent.
79	pub display: Option<Display>,
80
81	/// Apply this clockwise rotation before rendering, or clear it when absent. Values are normalized to the nearest quarter turn.
82	pub rotation: Option<f64>,
83
84	/// Flip horizontally after rotation, or clear the explicit value when absent.
85	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	/// Insert a track config, returning an error if the name already exists.
111	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	/// Remove the track from the catalog and return the configuration if found.
120	pub fn remove(&mut self, name: &str) -> Option<VideoConfig> {
121		self.renditions.remove(name)
122	}
123
124	/// True when there are no renditions, so the section can be omitted from the catalog.
125	///
126	/// Display, rotation, and flip ride this section, so they are omitted too when nothing is published.
127	pub fn is_empty(&self) -> bool {
128		self.renditions.is_empty()
129	}
130
131	/// Iterate enabled renditions in quality order.
132	pub fn enabled(&self) -> impl Iterator<Item = (&String, &VideoConfig)> {
133		self.ranked().filter(|(_, config)| config.enabled)
134	}
135
136	/// Iterate the renditions best first: enabled, then highest [preference](VideoConfig::preference),
137	/// then largest picture, then highest bitrate.
138	///
139	/// A consumer that carries one rendition takes the first it supports, so the
140	/// picture doesn't depend on how the tracks are named, and a lower preference
141	/// is taken only when nothing preferred is supported. Unknown dimensions or
142	/// bitrate rank below known ones, and exact ties keep name order.
143	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	/// Which way `config` is shown once rotated, or `None` when square or of unknown size.
153	///
154	/// The section's display size decides it when set, else the rendition's display aspect
155	/// ratio or coded size, turned by the section's rotation. A player with a viewport keeps
156	/// the renditions shaped like it, so [preference](VideoConfig::preference) ranks within
157	/// an orientation.
158	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		// An odd quarter turn swaps the sides, rounded the way the catalog normalizes it; a
168		// non-finite rotation is ignored.
169		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	/// Normalize and replace the properties shared by every video rendition.
177	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/// Which side of a picture or viewport is longer.
187#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
188pub enum Orientation {
189	/// Wider than tall.
190	Landscape,
191	/// Taller than wide.
192	Portrait,
193}
194
195impl Orientation {
196	/// The orientation of a `width` by `height` picture, or `None` when square.
197	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/// Display size for rendering video
214#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
215#[serde(rename_all = "camelCase")]
216pub struct Display {
217	/// Width in pixels.
218	pub width: u32,
219	/// Height in pixels.
220	pub height: u32,
221}
222
223/// Video decoder configuration based on WebCodecs VideoDecoderConfig.
224///
225/// This struct contains all the information needed to initialize a video decoder,
226/// including codec-specific parameters, resolution, and optional metadata.
227///
228/// Reference: <https://www.w3.org/TR/webcodecs/#video-decoder-config>
229///
230/// Marked `#[non_exhaustive]` so additional optional fields can be added
231/// without bumping the major version. External callers build a config with
232/// [`VideoConfig::new`] and then assign whichever optional fields they need;
233/// struct-literal construction (with or without `..base`) is not available
234/// outside this crate.
235#[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	/// Optional reference to another broadcast that publishes this track, expressed
242	/// relative to the broadcast that served this catalog (e.g. `./source`). If unset,
243	/// the track lives in the same broadcast as the catalog.
244	///
245	/// This allows a transcoder to author a downstream catalog that points unchanged
246	/// renditions at the source broadcast without re-publishing the bytes.
247	///
248	/// Resolve it with [`Path::resolve`](moq_net::Path::resolve): a reference that walks
249	/// above the root names no broadcast, so the catalog is rejected.
250	#[serde(default)]
251	#[serde_as(as = "crate::catalog::NotNull")]
252	pub broadcast: Option<moq_net::path::Relative>,
253
254	/// The track's name in its broadcast, when it differs from this entry's ID: its key in the
255	/// catalog. Absent means the ID is the track name, as in every catalog before this field.
256	///
257	/// Set it only when the ID can't be the name, such as two renditions of same-named tracks
258	/// from different broadcasts. Readers resolve the name with
259	/// [`Reference::track`](crate::catalog::Reference::track); one that predates the
260	/// field subscribes to the ID instead.
261	#[serde(default)]
262	#[serde_as(as = "crate::catalog::NotNull")]
263	pub track: Option<String>,
264
265	/// Human-readable rendition name for track pickers.
266	#[serde(default)]
267	#[serde_as(as = "crate::catalog::NotNull")]
268	pub label: Option<String>,
269
270	/// The codec, see the registry for details:
271	/// <https://w3c.github.io/webcodecs/codec_registry.html>
272	#[serde_as(as = "DisplayFromStr")]
273	pub codec: VideoCodec,
274
275	/// Information used to initialize the decoder on a per-codec basis.
276	///
277	/// One of the best examples is H264, which needs the sps/pps to function.
278	/// If not provided, this information is (automatically) inserted before each key-frame (marginally higher overhead).
279	#[serde(default)]
280	#[serde_as(as = "crate::catalog::NotNull<Hex>")]
281	pub description: Option<Bytes>,
282
283	/// The largest encoded width/height the track carries, fixed for its name, never zero.
284	///
285	/// The picture resizes in band at a keyframe below these ceilings, unless the
286	/// `description` pins it. Absent means unknown; a publisher may fill it once.
287	#[serde_as(as = "crate::catalog::NotNull")]
288	#[serde(default)]
289	pub coded_width: Option<u32>,
290	/// The height counterpart of `coded_width`.
291	#[serde_as(as = "crate::catalog::NotNull")]
292	#[serde(default)]
293	pub coded_height: Option<u32>,
294
295	/// The aspect ratio the whole picture is displayed at, as WebCodecs'
296	/// `VideoDecoderConfig.displayAspectWidth` / `displayAspectHeight`, never zero.
297	///
298	/// Absent means the decoded picture's own shape. A publisher with non-square
299	/// samples sets the picture's aspect here, never the sample aspect.
300	#[serde_as(as = "crate::catalog::NotNull")]
301	#[serde(default)]
302	pub display_aspect_width: Option<u32>,
303	/// The height counterpart of `display_aspect_width`.
304	#[serde_as(as = "crate::catalog::NotNull")]
305	#[serde(default)]
306	pub display_aspect_height: Option<u32>,
307
308	/// The colour the decoded pixels carry, so a renderer need not guess or reparse the bitstream.
309	///
310	/// Live state, not identity: a publisher may fill it in once the bitstream reveals it.
311	#[serde(default)]
312	#[serde_as(as = "crate::catalog::NotNull")]
313	pub color: Option<Color>,
314
315	/// How the picture maps onto the viewer's field of view. Absent means rectilinear.
316	///
317	/// Live state, like [`color`](Self::color).
318	#[serde(default)]
319	#[serde_as(as = "crate::catalog::NotNull")]
320	pub projection: Option<Projection>,
321
322	/// How each eye's view is packed into the frame. Absent means mono.
323	///
324	/// Live state, like [`color`](Self::color).
325	#[serde(default)]
326	#[serde_as(as = "crate::catalog::NotNull<DisplayFromStr>")]
327	pub stereo: Option<Stereo>,
328
329	/// Each picture weaves two fields, so a renderer deinterlaces it. Only written when true.
330	///
331	/// Decides decoder configuration, since some hardware decoders refuse interlaced streams.
332	#[serde(default, skip_serializing_if = "std::ops::Not::not")]
333	pub interlaced: bool,
334
335	/// The maximum bitrate of the video track, if known, at most 2^53 - 1.
336	#[serde(default)]
337	#[serde_as(as = "crate::catalog::NotNull<crate::snapshot::Number>")]
338	pub bitrate: Option<u64>,
339
340	/// Whether this rendition may be selected. When false, no frames are coming and a consumer
341	/// must not select it. Only written when false.
342	#[serde(
343		default = "crate::catalog::enabled_default",
344		skip_serializing_if = "crate::catalog::enabled_skip"
345	)]
346	pub enabled: bool,
347
348	/// Higher is preferred: a consumer selects among the highest preference it can decode,
349	/// then by picture and bitrate within it. A compatibility transcode is `-1` so only a
350	/// consumer that can't decode the source pulls it. A player with a viewport first keeps
351	/// the renditions of its [orientation](Video::orientation), so preference ranks within
352	/// one: a publisher ranks its secondary orientation lower, and a consumer without a
353	/// viewport takes the main one. Only written when nonzero.
354	#[serde(default, skip_serializing_if = "is_zero")]
355	pub preference: i32,
356
357	/// The maximum frame rate of the video track, if known.
358	#[serde(default)]
359	#[serde_as(as = "crate::catalog::NotNull")]
360	pub framerate: Option<f64>,
361
362	/// The most frames that can precede a frame in decode order and follow it in presentation
363	/// order, as H.264 `max_num_reorder_frames` and HEVC `sps_max_num_reorder_pics` count them.
364	///
365	/// `0` declares that presentation order is decode order. Absent declares nothing: a consumer
366	/// that authors decode times infers them from the timestamps instead. A publisher that
367	/// declares it keeps it for the track's life, and never reorders deeper.
368	#[serde(default)]
369	#[serde_as(as = "crate::catalog::NotNull")]
370	pub reorder: Option<u8>,
371
372	/// If true, the decoder will optimize for latency.
373	///
374	/// Default: true
375	#[serde(default)]
376	#[serde_as(as = "crate::catalog::NotNull")]
377	pub optimize_for_latency: Option<bool>,
378
379	/// Container format for frame encoding.
380	/// Defaults to "legacy" for backward compatibility.
381	#[serde(default)]
382	pub container: Container,
383
384	/// The largest media span the publisher hands to the transport behind a frame's presentation
385	/// timestamp: the reorder delay of a frame presented after frames decoded behind it, or the span
386	/// of a batch written together, such as an fMP4 fragment. A consumer's jitter buffer should be at
387	/// least this large. Absent when the publisher measured none.
388	///
389	/// Measured from media timestamps alone, so a frame written in presentation order adds nothing,
390	/// whatever the frame rate; encoder latency and the network don't count. It only ever grows
391	/// over the life of a stream.
392	///
393	/// Serialized as a whole number of milliseconds, rounded up, so an upper bound never
394	/// rounds down into a promise the publisher can't keep.
395	#[serde_as(as = "MillisCeil")]
396	#[serde(default)]
397	pub jitter: Option<std::time::Duration>,
398
399	/// How far this rendition's frames reach the transport behind the broadcast's other
400	/// renditions: a constant offset, either supplied by the publisher or measured as the least
401	/// its frames trailed the others' over a window of a second of media, keeping the largest
402	/// window. Lateness only some frames have, such as B-frame reorder, is left out, since a
403	/// consumer measures it. Absent on a rendition that trails nothing, and on any rendition the
404	/// publisher neither supplied nor measured.
405	///
406	/// A consumer adds a frame duration on top, so a publisher that knows its frames trail by no
407	/// more than their own duration, such as an encoder configured not to reorder or queue, states
408	/// `Some(Duration::ZERO)`. It is never measured, and is omitted on the
409	/// wire like an absent value, which means the same to a consumer. `None` leaves it to
410	/// measurement.
411	///
412	/// A consumer holds `delay + jitter` for this rendition and MUST NOT subtract one rendition's
413	/// `delay` from another's: each is taken against whichever rendition was ahead, so two need not
414	/// share an origin. It only ever grows over the life of a stream, and is serialized like
415	/// [`jitter`](Self::jitter).
416	#[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	/// Construct a config with the required codec set and every optional
423	/// field cleared. `container` defaults to [`Container::default`]. Fields
424	/// are `pub`, so callers set whatever they need by assignment afterwards.
425	///
426	/// This is the only path external crates have to build a `VideoConfig`
427	/// since the type is `#[non_exhaustive]`.
428	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	/// Whether `other` keeps this config's track identity: the fields a consumer cannot change
456	/// without reinitializing its decoder or demuxer (`codec`, `description`, `container`,
457	/// `display_aspect_width`, `display_aspect_height`, and `interlaced`).
458	///
459	/// A track name always means the same content, so a publisher that changes any of them
460	/// publishes under a new name; every other field may update in place. See the draft's
461	/// [Track Identity](https://github.com/moq-dev/moq/blob/main/drafts/draft-lcurley-moq-hang.md#identity).
462	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		// The display aspect ratio, not the coded size, is the picture's shape.
533		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		// Only an odd quarter turn swaps the sides, however the rotation is written.
539		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			// Halfway rounds the same whichever way round the turn is written.
545			(-45.0, Orientation::Landscape),
546			(315.0, Orientation::Landscape),
547			(-135.0, Orientation::Portrait),
548			(225.0, Orientation::Portrait),
549			// Just under halfway stays under it.
550			(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		// The display size is the shape after rotation, shared by every rendition.
558		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		// Names sort worst first, so name order alone would pick the wrong one.
577		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		// Disabled renditions rank last, so catalog transforms can retain their metadata.
594		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		// A disabled source ranks last whatever its preference.
696		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}