1use std::collections::BTreeSet;
10
11use crate::codec::{
12 AudioCodec, ClientCapabilities, Container, Delivery, DisplayCapabilities, HdrFormat,
13 SubtitleFormat, VideoCodec, VideoLimits,
14};
15
16#[derive(Debug, Clone, Default, PartialEq, Eq)]
18pub struct Decoders {
19 pub video: BTreeSet<VideoCodec>,
20 pub hardware_video: Option<BTreeSet<VideoCodec>>,
23 pub audio: BTreeSet<AudioCodec>,
24 pub containers: BTreeSet<Container>,
25 pub subtitles: BTreeSet<SubtitleFormat>,
26 pub delivery: Vec<Delivery>,
28 pub max_audio_channels: Option<u32>,
29 pub video_codecs: Option<BTreeSet<String>>,
31}
32
33impl DisplayCapabilities {
34 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 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 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
142pub trait CodecProbe {
146 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
156pub 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 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 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 #[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 #[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 #[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 fn hardware(player: Decoders, codecs: &[VideoCodec]) -> Decoders {
372 Decoders {
373 hardware_video: Some(codecs.iter().copied().collect()),
374 ..player
375 }
376 }
377
378 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}