Skip to main content

spoolframe_types/
capabilities.rs

1//! Building [`ClientCapabilities`] the same way on every platform: from
2//! the decoders a device found ([`ClientCapabilities::from_decoders`]),
3//! or by asking its player codec string by codec string
4//! ([`ClientCapabilities::probe`]: Apple's VideoToolbox, Android's
5//! MediaCodecList, GStreamer), with the defaults every client set by
6//! hand: PCM always, range reads then progressive when nothing else is
7//! said, no height or bitrate limit, the screen's HDR as the limit.
8
9use std::collections::BTreeSet;
10
11use crate::codec::{
12    AudioCodec, ClientCapabilities, Container, Delivery, DisplayCapabilities, HdrFormat,
13    SubtitleFormat, VideoCodec, VideoLimits,
14};
15
16/// What a device's player decodes, as it found it.
17#[derive(Debug, Clone, Default, PartialEq, Eq)]
18pub struct Decoders {
19    pub video: BTreeSet<VideoCodec>,
20    /// Those of `video` decoded in hardware; `None` when the player does
21    /// not say.
22    pub hardware_video: Option<BTreeSet<VideoCodec>>,
23    pub audio: BTreeSet<AudioCodec>,
24    pub containers: BTreeSet<Container>,
25    pub subtitles: BTreeSet<SubtitleFormat>,
26    /// Preferred first; empty is range reads, then a progressive stream.
27    pub delivery: Vec<Delivery>,
28    pub max_audio_channels: Option<u32>,
29    /// The RFC 6381 strings the player takes; `None` when not asked.
30    pub video_codecs: Option<BTreeSet<String>>,
31}
32
33impl DisplayCapabilities {
34    /// The screen as it is now: with `show` on (the device shows HDR, and
35    /// the user's "Show HDR" is on), HDR10 and HLG; Dolby Vision too only
36    /// with `dolby_vision`, where the player shows it in its own colours.
37    /// Off, none: the server tone maps to SDR. A Dolby Vision profile 5
38    /// film sent to a player that cannot show it has wrong colours, so it
39    /// is never on by default. The bit depth is the device's.
40    pub fn for_hdr(show: bool, dolby_vision: bool) -> Self {
41        let mut hdr = BTreeSet::new();
42        if show {
43            hdr.extend([HdrFormat::Hdr10, HdrFormat::Hlg]);
44            if dolby_vision {
45                hdr.insert(HdrFormat::DolbyVision);
46            }
47        }
48        Self {
49            bit_depth: None,
50            hdr: Some(hdr),
51            video_codecs: None,
52        }
53    }
54}
55
56impl ClientCapabilities {
57    /// What `decoders` play on `display`: PCM is always played (every
58    /// player outputs it), hardware decoders are only those it plays, no
59    /// delivery said is range reads then a progressive stream, and the
60    /// screen's HDR and bit depth are the video limits. No height or
61    /// bitrate limit: the bitrate is the app's setting.
62    pub fn from_decoders(decoders: Decoders, display: &DisplayCapabilities) -> Self {
63        let Decoders {
64            video,
65            hardware_video,
66            mut audio,
67            containers,
68            subtitles,
69            delivery,
70            max_audio_channels,
71            video_codecs,
72        } = decoders;
73        audio.insert(AudioCodec::Pcm);
74        let hardware_video =
75            hardware_video.map(|hw| hw.intersection(&video).copied().collect::<BTreeSet<_>>());
76        let delivery = match delivery.is_empty() {
77            true => vec![Delivery::Range, Delivery::Progressive],
78            false => delivery,
79        };
80        Self {
81            video,
82            audio,
83            containers,
84            subtitles,
85            delivery,
86            max_video: Some(VideoLimits {
87                height: None,
88                frame_rate: None,
89                bit_depth: display.bit_depth,
90                hdr: display.hdr.clone(),
91            }),
92            max_audio_channels,
93            max_bitrate: None,
94            hardware_video,
95            video_codecs: display.video_codecs.clone().or(video_codecs),
96        }
97    }
98
99    /// The iOS app's probe, for any platform: `player`'s fixed lists (its
100    /// audio, containers, subtitles, delivery, and the video it plays in
101    /// software), plus each codec of `hardware` (what decodes in
102    /// hardware, as the platform says), on `display`. `probe_codec` is
103    /// asked about each of [`candidate_codec_strings`]. The bit depth is
104    /// 10 where HEVC decodes in hardware (Main 10), else 8, unless
105    /// `display` says its own.
106    pub fn probe(
107        probe_codec: &dyn CodecProbe,
108        hardware: &[VideoCodec],
109        display: &DisplayCapabilities,
110        player: Decoders,
111    ) -> Self {
112        let hardware: BTreeSet<VideoCodec> = hardware.iter().copied().collect();
113        let mut video = player.video;
114        video.extend(hardware.iter().copied());
115        let video_codecs = candidate_codec_strings()
116            .into_iter()
117            .filter(|s| probe_codec.plays(s))
118            .collect();
119        let bit_depth = match hardware.contains(&VideoCodec::Hevc) {
120            true => 10,
121            false => 8,
122        };
123        let display = DisplayCapabilities {
124            bit_depth: display.bit_depth.or(Some(bit_depth)),
125            ..display.clone()
126        };
127        Self::from_decoders(
128            Decoders {
129                video,
130                hardware_video: Some(hardware),
131                video_codecs: Some(video_codecs),
132                ..player
133            },
134            &display,
135        )
136    }
137}
138
139/// A device's player, asked about an RFC 6381 codec string
140/// ([`ClientCapabilities::probe`]): VideoToolbox and AVURLAsset,
141/// MediaCodecList, GStreamer. Any `Fn(&str) -> bool` is one.
142pub trait CodecProbe {
143    /// Whether it plays MP4 video of codec string `codec`.
144    fn plays(&self, codec: &str) -> bool;
145}
146
147impl<F: Fn(&str) -> bool> CodecProbe for F {
148    fn plays(&self, codec: &str) -> bool {
149        self(codec)
150    }
151}
152
153/// The codec strings a probe asks about (the iOS app's list): H.264 High
154/// at levels 4.1 to 5.2; HEVC Main and Main 10, both tiers, levels 4.1 to
155/// 6.2; Dolby Vision profiles 5, 7 and 8, levels 1 to 13; AV1 Main, both
156/// tiers, 8- and 10-bit, levels 4.0 to 6.1.
157pub fn candidate_codec_strings() -> Vec<String> {
158    let mut out = Vec::new();
159    for level in ["29", "2A", "32", "33", "34"] {
160        out.push(format!("avc1.6400{level}"));
161    }
162    for tag in ["hvc1", "hev1"] {
163        for profile in ["1.6", "2.4"] {
164            for tier in ["L", "H"] {
165                for level in [123, 150, 153, 156, 180, 183, 186] {
166                    out.push(format!("{tag}.{profile}.{tier}{level}.B0"));
167                }
168            }
169        }
170    }
171    for tag in ["dvh1", "dvhe"] {
172        for profile in ["05", "07", "08"] {
173            for level in 1..=13 {
174                out.push(format!("{tag}.{profile}.{level:02}"));
175            }
176        }
177    }
178    for tier in ["M", "H"] {
179        for level in ["08", "09", "12", "13", "14", "16", "17"] {
180            for depth in ["08", "10"] {
181                out.push(format!("av01.0.{level}{tier}.{depth}"));
182            }
183        }
184    }
185    out
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    #[test]
193    fn hdr_on_is_hdr10_and_hlg_and_dolby_vision_only_when_asked() {
194        assert_eq!(
195            DisplayCapabilities::for_hdr(false, true).hdr,
196            Some(BTreeSet::new())
197        );
198        assert_eq!(
199            DisplayCapabilities::for_hdr(true, false).hdr,
200            Some([HdrFormat::Hdr10, HdrFormat::Hlg].into())
201        );
202        assert_eq!(
203            DisplayCapabilities::for_hdr(true, true).hdr,
204            Some([HdrFormat::Hdr10, HdrFormat::Hlg, HdrFormat::DolbyVision].into())
205        );
206    }
207
208    #[test]
209    fn decoders_always_play_pcm_and_default_to_range_then_progressive() {
210        let caps = ClientCapabilities::from_decoders(
211            Decoders {
212                video: [VideoCodec::H264].into(),
213                hardware_video: Some([VideoCodec::H264, VideoCodec::Av1].into()),
214                audio: [AudioCodec::Aac].into(),
215                ..Decoders::default()
216            },
217            &DisplayCapabilities::for_hdr(false, false),
218        );
219        assert!(caps.audio.contains(&AudioCodec::Pcm));
220        assert_eq!(caps.deliveries(), [Delivery::Range, Delivery::Progressive]);
221        assert_eq!(
222            caps.hardware_video,
223            Some([VideoCodec::H264].into()),
224            "only what it plays"
225        );
226        let limits = caps.max_video.unwrap();
227        assert_eq!(
228            (limits.height, limits.bit_depth, limits.hdr),
229            (None, None, Some(BTreeSet::new()))
230        );
231        assert_eq!(caps.max_bitrate, None);
232    }
233
234    /// An Apple TV's lists: AAC, E-AC-3 and the rest, MP4, WebVTT, HLS.
235    fn apple_tv() -> Decoders {
236        Decoders {
237            video: [VideoCodec::H264, VideoCodec::Hevc].into(),
238            audio: [AudioCodec::Aac, AudioCodec::Eac3].into(),
239            containers: [Container::Mp4].into(),
240            subtitles: [SubtitleFormat::WebVtt].into(),
241            delivery: vec![Delivery::Hls, Delivery::Range],
242            max_audio_channels: Some(8),
243            ..Decoders::default()
244        }
245    }
246
247    #[test]
248    fn a_probe_asks_the_player_for_each_codec_string() {
249        let caps = ClientCapabilities::probe(
250            &|codec: &str| codec.starts_with("hvc1.2.4.L"),
251            &[VideoCodec::H264, VideoCodec::Hevc, VideoCodec::Av1],
252            &DisplayCapabilities::for_hdr(true, false),
253            apple_tv(),
254        );
255        assert_eq!(
256            caps.video,
257            [VideoCodec::H264, VideoCodec::Hevc, VideoCodec::Av1].into(),
258            "AV1 is played where it decodes in hardware"
259        );
260        assert!(caps.decodes_in_hardware(VideoCodec::Av1));
261        assert_eq!(
262            caps.audio,
263            [AudioCodec::Aac, AudioCodec::Eac3, AudioCodec::Pcm].into()
264        );
265        assert_eq!(caps.deliveries(), [Delivery::Hls, Delivery::Range]);
266        let strings = caps.video_codecs.unwrap();
267        assert_eq!(strings.len(), 7);
268        assert!(strings.contains("hvc1.2.4.L153.B0"));
269        assert_eq!(caps.max_audio_channels, Some(8));
270    }
271
272    #[test]
273    fn a_probe_is_10_bit_only_where_hevc_decodes_in_hardware() {
274        let depth = |hardware: &[VideoCodec]| {
275            ClientCapabilities::probe(
276                &|_: &str| true,
277                hardware,
278                &DisplayCapabilities::for_hdr(true, false),
279                apple_tv(),
280            )
281            .max_video
282            .unwrap()
283            .bit_depth
284        };
285        assert_eq!(depth(&[VideoCodec::H264, VideoCodec::Hevc]), Some(10));
286        assert_eq!(depth(&[VideoCodec::H264]), Some(8));
287        assert!(
288            !ClientCapabilities::probe(
289                &|_: &str| true,
290                &[VideoCodec::H264],
291                &DisplayCapabilities::for_hdr(true, false),
292                apple_tv(),
293            )
294            .decodes_in_hardware(VideoCodec::Hevc)
295        );
296    }
297
298    #[test]
299    fn the_candidates_are_the_ios_list() {
300        let all = candidate_codec_strings();
301        assert_eq!(all.len(), 5 + 56 + 78 + 28);
302        assert!(all.contains(&"dvh1.08.06".to_owned()));
303        assert!(all.contains(&"av01.0.12M.10".to_owned()));
304    }
305}