Skip to main content

moq_ext_player/
catalog.rs

1//! Reading a hang catalog the way a player does.
2//!
3//! A broadcast's catalog is [`hang::catalog::Catalog`], shared as an `Arc`
4//! between the watchers of one broadcast. Its `video.ranked()` orders the
5//! renditions by the publisher's preference, the adaptation ladder orders
6//! them by cost, and [`video_rendition`] looks one up with an error that
7//! names the renditions the catalog has.
8
9use std::cmp::Reverse;
10
11use hang::catalog::{Catalog, VideoConfig};
12use moq_ext_adaptive::Rung;
13
14use crate::Error;
15
16/// Returns the video rendition of `catalog` named `name`.
17///
18/// # Errors
19///
20/// Fails with [`Error::UnknownRendition`], which lists the names the catalog
21/// has, best first.
22pub fn video_rendition<'a>(catalog: &'a Catalog, name: &str) -> Result<&'a VideoConfig, Error> {
23    catalog.video.renditions.get(name).ok_or_else(|| {
24        n0_error::e!(Error::UnknownRendition {
25            name: name.to_string(),
26            offered: catalog
27                .video
28                .ranked()
29                .map(|(name, _)| name.clone())
30                .collect(),
31        })
32    })
33}
34
35/// Returns the video renditions as a ladder, most expensive first.
36///
37/// Adaptation steps down this ladder to save bandwidth, so it is ordered by
38/// bitrate, then by picture size. hang's ranking puts a publisher's
39/// preference first, and a preferred rendition can cost more than a less
40/// preferred one, so here it only breaks ties. A rendition without a bitrate
41/// sorts below those with one.
42pub(crate) fn rungs(catalog: &Catalog) -> Vec<Rung> {
43    let mut ladder: Vec<_> = catalog.video.ranked().collect();
44    // Stable, so hang's ranking keeps the order among equals.
45    ladder.sort_by_key(|(_, config)| {
46        let area = u64::from(config.coded_width.unwrap_or(0))
47            * u64::from(config.coded_height.unwrap_or(0));
48        Reverse((config.bitrate, area))
49    });
50    ladder
51        .into_iter()
52        .map(|(name, config)| Rung {
53            name: name.clone(),
54            bitrate: config.bitrate,
55            stalled: !config.enabled,
56        })
57        .collect()
58}
59
60#[cfg(test)]
61mod tests {
62    use std::time::Instant;
63
64    use hang::catalog::{H264, VideoCodec};
65    use moq_ext_adaptive::{
66        Adaptation, Bound, Constraints, NetworkSample, RenditionMode, step_down,
67    };
68
69    use super::*;
70
71    fn rendition(width: u32, height: u32, bitrate: u64) -> VideoConfig {
72        let mut config = VideoConfig::new(VideoCodec::H264(H264 {
73            inline: true,
74            profile: 0x64,
75            constraints: 0,
76            level: 0x1f,
77        }));
78        config.coded_width = Some(width);
79        config.coded_height = Some(height);
80        config.bitrate = Some(bitrate);
81        config
82    }
83
84    fn names(catalog: &Catalog) -> Vec<String> {
85        rungs(catalog).into_iter().map(|rung| rung.name).collect()
86    }
87
88    #[test]
89    fn video_renditions_come_largest_first() {
90        let mut catalog = Catalog::default();
91        let renditions = &mut catalog.video.renditions;
92        renditions.insert("low".into(), rendition(640, 360, 500_000));
93        renditions.insert("high".into(), rendition(1920, 1080, 4_000_000));
94        renditions.insert("720p-cheap".into(), rendition(1280, 720, 800_000));
95        renditions.insert("720p-rich".into(), rendition(1280, 720, 3_000_000));
96        assert_eq!(names(&catalog), ["high", "720p-rich", "720p-cheap", "low"]);
97    }
98
99    #[test]
100    fn preference_only_breaks_a_tie() {
101        let mut catalog = Catalog::default();
102        let renditions = &mut catalog.video.renditions;
103        renditions.insert("a-plain".into(), rendition(1280, 720, 800_000));
104        let mut preferred = rendition(1280, 720, 800_000);
105        preferred.preference = 1;
106        renditions.insert("b-preferred".into(), preferred);
107        let mut cheap = rendition(1280, 720, 500_000);
108        cheap.preference = 2;
109        renditions.insert("c-cheap".into(), cheap);
110        assert_eq!(names(&catalog), ["b-preferred", "a-plain", "c-cheap"]);
111    }
112
113    /// Returns hang's own example of a preferred source and a costlier fallback.
114    ///
115    /// From `ranked_orders_by_preference_before_picture`: a 360p source at
116    /// 500 kb/s is preferred over a 1080p fallback at 6 Mb/s.
117    fn preferred_source() -> Catalog {
118        let mut catalog = Catalog::default();
119        let renditions = &mut catalog.video.renditions;
120        renditions.insert("source".into(), rendition(640, 360, 500_000));
121        let mut fallback = rendition(1920, 1080, 6_000_000);
122        fallback.preference = -1;
123        renditions.insert("fallback".into(), fallback);
124        catalog
125    }
126
127    #[test]
128    fn the_ladder_steps_down_to_the_cheaper_rung_whatever_the_preference() {
129        let catalog = preferred_source();
130        let ranked: Vec<_> = catalog
131            .video
132            .ranked()
133            .map(|(name, _)| name.as_str())
134            .collect();
135        assert_eq!(
136            ranked,
137            ["source", "fallback"],
138            "hang ranks the source first"
139        );
140        let ladder = rungs(&catalog);
141        assert_eq!(names(&catalog), ["fallback", "source"]);
142
143        let now = Instant::now();
144        let constraints = Constraints::default();
145        let short = NetworkSample {
146            loss: Some(0.0),
147            delivery: Some(400_000),
148            ..NetworkSample::default()
149        };
150        let mut bound = Bound::new(Adaptation::default());
151        let chosen = bound.decide(&ladder, None, None, &constraints, &short, now);
152        assert_eq!(
153            chosen.as_deref(),
154            Some("source"),
155            "a shortfall plays the cheaper rung"
156        );
157
158        let emergency = NetworkSample {
159            loss: Some(0.5),
160            ..NetworkSample::default()
161        };
162        let mut bound = Bound::new(Adaptation::default());
163        let chosen = bound.decide(
164            &ladder,
165            Some("fallback"),
166            Some("fallback"),
167            &constraints,
168            &emergency,
169            now,
170        );
171        assert_eq!(
172            chosen.as_deref(),
173            Some("source"),
174            "emergency loss drops to the cheaper rung"
175        );
176
177        assert!(!step_down(
178            &RenditionMode::Auto,
179            &ladder,
180            Some("fallback"),
181            Some("source")
182        ));
183        assert!(step_down(
184            &RenditionMode::Auto,
185            &ladder,
186            Some("source"),
187            Some("fallback")
188        ));
189    }
190
191    #[test]
192    fn an_unknown_rendition_names_the_offered_ones() {
193        let mut catalog = Catalog::default();
194        catalog
195            .video
196            .renditions
197            .insert("hd".into(), rendition(1280, 720, 3_000_000));
198        let err = video_rendition(&catalog, "4k").expect_err("no such rendition");
199        assert!(err.to_string().contains("hd"), "{err}");
200    }
201
202    #[test]
203    fn a_rendition_without_a_bitrate_sorts_last() {
204        let mut catalog = Catalog::default();
205        let renditions = &mut catalog.video.renditions;
206        let mut unknown = rendition(1920, 1080, 0);
207        unknown.bitrate = None;
208        renditions.insert("unknown".into(), unknown);
209        renditions.insert("low".into(), rendition(640, 360, 500_000));
210        assert_eq!(names(&catalog), ["low", "unknown"]);
211        assert_eq!(rungs(&catalog)[1].bitrate, None);
212    }
213
214    #[test]
215    fn a_disabled_rendition_is_a_stalled_rung() {
216        let mut catalog = Catalog::default();
217        let renditions = &mut catalog.video.renditions;
218        let mut off = rendition(1920, 1080, 4_000_000);
219        off.enabled = false;
220        renditions.insert("off".into(), off);
221        renditions.insert("on".into(), rendition(640, 360, 500_000));
222        let ladder = rungs(&catalog);
223        assert_eq!(names(&catalog), ["off", "on"]);
224        assert!(ladder[0].stalled);
225        assert!(!ladder[1].stalled);
226        assert_eq!(
227            moq_ext_adaptive::best(&ladder, &Constraints::default()).as_deref(),
228            Some("on")
229        );
230    }
231}