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            height: None,
53            frame_rate: None,
54        }
55    }
56}
57
58impl ClientCapabilities {
59    /// What `decoders` play on `display`: PCM is always played (every
60    /// player outputs it), hardware decoders are only those it plays, no
61    /// delivery said is range reads then a progressive stream, and the
62    /// screen's HDR and bit depth are the video limits. No height, frame
63    /// rate or bitrate limit: these are the decoders' limits, and the
64    /// screen's mode goes with each plan ([`ClientCapabilities::with_display`]);
65    /// the bitrate is the app's setting.
66    pub fn from_decoders(decoders: Decoders, display: &DisplayCapabilities) -> Self {
67        let Decoders {
68            video,
69            hardware_video,
70            mut audio,
71            containers,
72            subtitles,
73            delivery,
74            max_audio_channels,
75            video_codecs,
76        } = decoders;
77        audio.insert(AudioCodec::Pcm);
78        let hardware_video =
79            hardware_video.map(|hw| hw.intersection(&video).copied().collect::<BTreeSet<_>>());
80        let delivery = match delivery.is_empty() {
81            true => vec![Delivery::Range, Delivery::Progressive],
82            false => delivery,
83        };
84        Self {
85            video,
86            audio,
87            containers,
88            subtitles,
89            delivery,
90            max_video: Some(VideoLimits {
91                height: None,
92                frame_rate: None,
93                bit_depth: display.bit_depth,
94                hdr: display.hdr.clone(),
95            }),
96            max_audio_channels,
97            max_bitrate: None,
98            hardware_video,
99            video_codecs: display.video_codecs.clone().or(video_codecs),
100        }
101    }
102
103    /// The iOS app's probe, for any platform: `player`'s fixed lists (its
104    /// audio, containers, subtitles, delivery, and the video it plays in
105    /// software), plus each codec of its `hardware_video` (what decodes
106    /// in hardware, as the platform says), on `display`. `probe_codec` is
107    /// asked about each of [`candidate_codec_strings`]. The bit depth is
108    /// 10 where HEVC decodes in hardware (Main 10), else 8, unless
109    /// `display` says its own.
110    pub fn probe(
111        probe_codec: &dyn CodecProbe,
112        display: &DisplayCapabilities,
113        player: Decoders,
114    ) -> Self {
115        let hardware = player.hardware_video.clone().unwrap_or_default();
116        let mut video = player.video;
117        video.extend(hardware.iter().copied());
118        let video_codecs = candidate_codec_strings()
119            .into_iter()
120            .filter(|s| probe_codec.plays(s))
121            .collect();
122        let bit_depth = match hardware.contains(&VideoCodec::Hevc) {
123            true => 10,
124            false => 8,
125        };
126        let display = DisplayCapabilities {
127            bit_depth: display.bit_depth.or(Some(bit_depth)),
128            ..display.clone()
129        };
130        Self::from_decoders(
131            Decoders {
132                video,
133                hardware_video: Some(hardware),
134                video_codecs: Some(video_codecs),
135                ..player
136            },
137            &display,
138        )
139    }
140}
141
142/// A device's player, asked about an RFC 6381 codec string
143/// ([`ClientCapabilities::probe`]): VideoToolbox and AVURLAsset,
144/// MediaCodecList, GStreamer. Any `Fn(&str) -> bool` is one.
145pub trait CodecProbe {
146    /// Whether it plays MP4 video of codec string `codec`.
147    fn plays(&self, codec: &str) -> bool;
148}
149
150impl<F: Fn(&str) -> bool> CodecProbe for F {
151    fn plays(&self, codec: &str) -> bool {
152        self(codec)
153    }
154}
155
156/// The codec strings a probe asks about (the iOS app's list): H.264 High
157/// at levels 4.1 to 5.2; HEVC Main and Main 10, both tiers, levels 4.1 to
158/// 6.2; Dolby Vision profiles 5, 7 and 8, levels 1 to 13; AV1 Main, both
159/// tiers, 8- and 10-bit, levels 4.0 to 6.1.
160pub fn candidate_codec_strings() -> Vec<String> {
161    let mut out = Vec::new();
162    for level in ["29", "2A", "32", "33", "34"] {
163        out.push(format!("avc1.6400{level}"));
164    }
165    for tag in ["hvc1", "hev1"] {
166        for profile in ["1.6", "2.4"] {
167            for tier in ["L", "H"] {
168                for level in [123, 150, 153, 156, 180, 183, 186] {
169                    out.push(format!("{tag}.{profile}.{tier}{level}.B0"));
170                }
171            }
172        }
173    }
174    for tag in ["dvh1", "dvhe"] {
175        for profile in ["05", "07", "08"] {
176            for level in 1..=13 {
177                out.push(format!("{tag}.{profile}.{level:02}"));
178            }
179        }
180    }
181    for tier in ["M", "H"] {
182        for level in ["08", "09", "12", "13", "14", "16", "17"] {
183            for depth in ["08", "10"] {
184                out.push(format!("av01.0.{level}{tier}.{depth}"));
185            }
186        }
187    }
188    out
189}
190
191impl VideoCodec {
192    /// The codec of an Android `MediaCodec` MIME type (`video/hevc`), as
193    /// `MediaCodecList` names its decoders; `None` for one Spoolframe has
194    /// no name for.
195    pub fn for_mime(mime: &str) -> Option<Self> {
196        Some(match mime {
197            "video/avc" => Self::H264,
198            "video/hevc" => Self::Hevc,
199            "video/av01" => Self::Av1,
200            "video/x-vnd.on2.vp9" => Self::Vp9,
201            "video/x-vnd.on2.vp8" => Self::Vp8,
202            "video/mpeg2" => Self::Mpeg2,
203            "video/mp4v-es" => Self::Mpeg4,
204            "video/wvc1" => Self::Vc1,
205            _ => return None,
206        })
207    }
208}
209
210impl AudioCodec {
211    /// The codec of an Android `MediaCodec` MIME type (`audio/eac3`), as
212    /// `MediaCodecList` names its decoders; `None` for one Spoolframe has
213    /// no name for. E-AC-3 with Atmos (JOC) is E-AC-3, and DTS-HD is DTS:
214    /// the core is what plays.
215    pub fn for_mime(mime: &str) -> Option<Self> {
216        Some(match mime {
217            "audio/mp4a-latm" => Self::Aac,
218            "audio/ac3" => Self::Ac3,
219            "audio/eac3" | "audio/eac3-joc" => Self::Eac3,
220            "audio/vnd.dts" | "audio/vnd.dts.hd" => Self::Dts,
221            "audio/true-hd" => Self::TrueHd,
222            "audio/flac" => Self::Flac,
223            "audio/alac" => Self::Alac,
224            "audio/opus" => Self::Opus,
225            "audio/vorbis" => Self::Vorbis,
226            "audio/mpeg" => Self::Mp3,
227            "audio/raw" => Self::Pcm,
228            _ => return None,
229        })
230    }
231}
232
233#[cfg(test)]
234mod tests {
235    use super::*;
236
237    #[test]
238    fn android_s_decoder_types_name_their_codecs() {
239        assert_eq!(
240            (
241                VideoCodec::for_mime("video/hevc"),
242                VideoCodec::for_mime("video/dolby-vision"),
243                AudioCodec::for_mime("audio/eac3-joc"),
244                AudioCodec::for_mime("audio/vnd.dts.hd"),
245                AudioCodec::for_mime("audio/3gpp"),
246            ),
247            (
248                Some(VideoCodec::Hevc),
249                None,
250                Some(AudioCodec::Eac3),
251                Some(AudioCodec::Dts),
252                None
253            )
254        );
255    }
256
257    /// The probe says the decoders' limits only: the screen's mode is
258    /// not Hello's, so a TV that signs in at 1080p is not held there.
259    #[test]
260    fn a_probe_leaves_the_screen_s_mode_to_each_plan() {
261        let display = DisplayCapabilities {
262            height: Some(1080),
263            frame_rate: Some(60),
264            ..DisplayCapabilities::for_hdr(false, false)
265        };
266        let limits = ClientCapabilities::probe(&|_: &str| true, &display, apple_tv())
267            .max_video
268            .unwrap();
269        assert_eq!((limits.height, limits.frame_rate), (None, None));
270    }
271
272    /// Signed in on a 1080p screen, switched to 2160p since: a decoder
273    /// that plays 2160 gets 2160 at the next plan.
274    #[test]
275    fn a_screen_switched_up_since_the_sign_in_plays_its_new_mode() {
276        let hello = ClientCapabilities::probe(
277            &|_: &str| true,
278            &DisplayCapabilities {
279                height: Some(1080),
280                ..DisplayCapabilities::for_hdr(false, false)
281            },
282            apple_tv(),
283        );
284        let at_2160 = DisplayCapabilities {
285            height: Some(2160),
286            ..DisplayCapabilities::for_hdr(false, false)
287        };
288        let limits = hello.with_display(Some(&at_2160)).max_video.unwrap();
289        assert_eq!(limits.height, Some(2160));
290    }
291
292    #[test]
293    fn a_display_without_a_mode_keeps_hello_s_height_and_frame_rate() {
294        let mut hello = ClientCapabilities::from_decoders(
295            apple_tv(),
296            &DisplayCapabilities::for_hdr(false, false),
297        );
298        hello.max_video.as_mut().unwrap().height = Some(2160);
299        let at_1080 = DisplayCapabilities {
300            height: Some(1080),
301            ..DisplayCapabilities::for_hdr(true, false)
302        };
303        let heights = [&DisplayCapabilities::for_hdr(true, false), &at_1080]
304            .map(|display| hello.with_display(Some(display)).max_video.unwrap().height);
305        assert_eq!(heights, [Some(2160), Some(1080)]);
306    }
307
308    /// A 4K screen does not raise a 1080p decoder's limit: the lower of
309    /// the two holds.
310    #[test]
311    fn a_display_s_mode_never_raises_hello_s_limits() {
312        let mut hello = ClientCapabilities::from_decoders(
313            apple_tv(),
314            &DisplayCapabilities::for_hdr(false, false),
315        );
316        let limits = hello.max_video.as_mut().unwrap();
317        limits.height = Some(1080);
318        limits.frame_rate = Some(30);
319        let at_2160_60 = DisplayCapabilities {
320            height: Some(2160),
321            frame_rate: Some(60),
322            ..DisplayCapabilities::for_hdr(true, false)
323        };
324        let limits = hello.with_display(Some(&at_2160_60)).max_video.unwrap();
325        assert_eq!((limits.height, limits.frame_rate), (Some(1080), Some(30)));
326    }
327
328    #[test]
329    fn hdr_on_is_hdr10_and_hlg_and_dolby_vision_only_when_asked() {
330        assert_eq!(
331            DisplayCapabilities::for_hdr(false, true).hdr,
332            Some(BTreeSet::new())
333        );
334        assert_eq!(
335            DisplayCapabilities::for_hdr(true, false).hdr,
336            Some([HdrFormat::Hdr10, HdrFormat::Hlg].into())
337        );
338        assert_eq!(
339            DisplayCapabilities::for_hdr(true, true).hdr,
340            Some([HdrFormat::Hdr10, HdrFormat::Hlg, HdrFormat::DolbyVision].into())
341        );
342    }
343
344    #[test]
345    fn decoders_always_play_pcm_and_default_to_range_then_progressive() {
346        let caps = ClientCapabilities::from_decoders(
347            Decoders {
348                video: [VideoCodec::H264].into(),
349                hardware_video: Some([VideoCodec::H264, VideoCodec::Av1].into()),
350                audio: [AudioCodec::Aac].into(),
351                ..Decoders::default()
352            },
353            &DisplayCapabilities::for_hdr(false, false),
354        );
355        assert!(caps.audio.contains(&AudioCodec::Pcm));
356        assert_eq!(caps.deliveries(), [Delivery::Range, Delivery::Progressive]);
357        assert_eq!(
358            caps.hardware_video,
359            Some([VideoCodec::H264].into()),
360            "only what it plays"
361        );
362        let limits = caps.max_video.unwrap();
363        assert_eq!(
364            (limits.height, limits.bit_depth, limits.hdr),
365            (None, None, Some(BTreeSet::new()))
366        );
367        assert_eq!(caps.max_bitrate, None);
368    }
369
370    /// `player`, decoding `codecs` in hardware.
371    fn hardware(player: Decoders, codecs: &[VideoCodec]) -> Decoders {
372        Decoders {
373            hardware_video: Some(codecs.iter().copied().collect()),
374            ..player
375        }
376    }
377
378    /// An Apple TV's lists: AAC, E-AC-3 and the rest, MP4, WebVTT, HLS.
379    fn apple_tv() -> Decoders {
380        Decoders {
381            video: [VideoCodec::H264, VideoCodec::Hevc].into(),
382            audio: [AudioCodec::Aac, AudioCodec::Eac3].into(),
383            containers: [Container::Mp4].into(),
384            subtitles: [SubtitleFormat::WebVtt].into(),
385            delivery: vec![Delivery::Hls, Delivery::Range],
386            max_audio_channels: Some(8),
387            ..Decoders::default()
388        }
389    }
390
391    #[test]
392    fn a_probe_asks_the_player_for_each_codec_string() {
393        let caps = ClientCapabilities::probe(
394            &|codec: &str| codec.starts_with("hvc1.2.4.L"),
395            &DisplayCapabilities::for_hdr(true, false),
396            hardware(
397                apple_tv(),
398                &[VideoCodec::H264, VideoCodec::Hevc, VideoCodec::Av1],
399            ),
400        );
401        assert_eq!(
402            caps.video,
403            [VideoCodec::H264, VideoCodec::Hevc, VideoCodec::Av1].into(),
404            "AV1 is played where it decodes in hardware"
405        );
406        assert!(caps.decodes_in_hardware(VideoCodec::Av1));
407        assert_eq!(
408            caps.audio,
409            [AudioCodec::Aac, AudioCodec::Eac3, AudioCodec::Pcm].into()
410        );
411        assert_eq!(caps.deliveries(), [Delivery::Hls, Delivery::Range]);
412        let strings = caps.video_codecs.unwrap();
413        assert_eq!(strings.len(), 7);
414        assert!(strings.contains("hvc1.2.4.L153.B0"));
415        assert_eq!(caps.max_audio_channels, Some(8));
416    }
417
418    #[test]
419    fn a_probe_is_10_bit_only_where_hevc_decodes_in_hardware() {
420        let depth = |decoded: &[VideoCodec]| {
421            ClientCapabilities::probe(
422                &|_: &str| true,
423                &DisplayCapabilities::for_hdr(true, false),
424                hardware(apple_tv(), decoded),
425            )
426            .max_video
427            .unwrap()
428            .bit_depth
429        };
430        assert_eq!(depth(&[VideoCodec::H264, VideoCodec::Hevc]), Some(10));
431        assert_eq!(depth(&[VideoCodec::H264]), Some(8));
432        assert!(
433            !ClientCapabilities::probe(
434                &|_: &str| true,
435                &DisplayCapabilities::for_hdr(true, false),
436                hardware(apple_tv(), &[VideoCodec::H264]),
437            )
438            .decodes_in_hardware(VideoCodec::Hevc)
439        );
440    }
441
442    #[test]
443    fn the_candidates_are_the_ios_list() {
444        let all = candidate_codec_strings();
445        assert_eq!(all.len(), 5 + 56 + 78 + 28);
446        assert!(all.contains(&"dvh1.08.06".to_owned()));
447        assert!(all.contains(&"av01.0.12M.10".to_owned()));
448    }
449}