1use std::fmt;
13use std::str::FromStr;
14
15use crate::VideoCodec;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
20pub enum Tier {
21 Main,
22 High,
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27pub enum CodecString {
28 Avc {
31 in_band: bool,
32 profile: u8,
33 constraints: u8,
34 level: u8,
35 },
36 Hevc {
42 in_band: bool,
43 profile_space: u8,
44 profile: u8,
45 compatibility: u32,
46 tier: Tier,
47 level: u8,
48 constraints: [u8; 6],
49 },
50 Av1 {
54 profile: u8,
55 level: u8,
56 tier: Tier,
57 bit_depth: u8,
58 },
59 DolbyVision {
62 base: VideoCodec,
63 in_band: bool,
64 profile: u8,
65 level: u8,
66 },
67}
68
69#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
71#[error("not a video codec string: {0}")]
72pub struct CodecStringError(String);
73
74impl CodecString {
75 pub fn covers(&self, source: &CodecString) -> bool {
84 use CodecString::*;
85 match (*self, *source) {
86 (
87 Avc { profile, level, .. },
88 Avc {
89 profile: theirs,
90 constraints,
91 level: their_level,
92 ..
93 },
94 ) => avc_decodes(profile, theirs, constraints) && their_level <= level,
95 (
96 Hevc {
97 profile_space,
98 profile,
99 tier,
100 level,
101 ..
102 },
103 Hevc {
104 profile_space: their_space,
105 profile: theirs,
106 tier: their_tier,
107 level: their_level,
108 ..
109 },
110 ) => {
111 profile_space == their_space
112 && (profile == theirs || (profile == HEVC_MAIN_10 && theirs == HEVC_MAIN))
113 && their_tier <= tier
114 && their_level <= level
115 }
116 (
117 Av1 {
118 profile,
119 level,
120 tier,
121 bit_depth,
122 },
123 Av1 {
124 profile: theirs,
125 level: their_level,
126 tier: their_tier,
127 bit_depth: their_depth,
128 },
129 ) => {
130 profile == theirs
131 && bit_depth == their_depth
132 && their_tier <= tier
133 && their_level <= level
134 }
135 (
136 DolbyVision {
137 base,
138 profile,
139 level,
140 ..
141 },
142 DolbyVision {
143 base: their_base,
144 profile: theirs,
145 level: their_level,
146 ..
147 },
148 ) => base == their_base && profile == theirs && their_level <= level,
149 _ => false,
150 }
151 }
152
153 pub fn codec(&self) -> VideoCodec {
155 match self {
156 Self::Avc { .. } => VideoCodec::H264,
157 Self::Hevc { .. } => VideoCodec::Hevc,
158 Self::Av1 { .. } => VideoCodec::Av1,
159 Self::DolbyVision { base, .. } => *base,
160 }
161 }
162}
163
164const HEVC_MAIN: u8 = 1;
165const HEVC_MAIN_10: u8 = 2;
166
167const AVC_MAIN: u8 = 77;
169const AVC_HIGH: [u8; 4] = [100, 110, 122, 244];
172const AVC_MAIN_CONSTRAINED: u8 = 0x40;
175
176fn avc_decodes(profile: u8, source: u8, constraints: u8) -> bool {
179 let high = |p: u8| AVC_HIGH.iter().position(|&h| h == p);
180 if profile == source {
181 return true;
182 }
183 let main_or_above = profile == AVC_MAIN || high(profile).is_some();
184 if main_or_above && constraints & AVC_MAIN_CONSTRAINED != 0 {
185 return true;
186 }
187 match (high(profile), high(source)) {
188 (Some(ours), Some(theirs)) => theirs <= ours,
189 (Some(_), None) => source == AVC_MAIN,
190 _ => false,
191 }
192}
193
194impl FromStr for CodecString {
195 type Err = CodecStringError;
196
197 fn from_str(s: &str) -> Result<Self, Self::Err> {
198 let bad = || CodecStringError(s.to_owned());
199 let mut parts = s.split('.');
200 let fourcc = parts.next().ok_or_else(bad)?;
201 let parts: Vec<&str> = parts.collect();
202 let parsed = match fourcc {
203 "avc1" | "avc3" => avc(fourcc == "avc3", &parts),
204 "hvc1" | "hev1" => hevc(fourcc == "hev1", &parts),
205 "av01" => av1(&parts),
206 "dvh1" | "dvhe" => dolby_vision(VideoCodec::Hevc, fourcc == "dvhe", &parts),
207 "dva1" | "dvav" => dolby_vision(VideoCodec::H264, fourcc == "dvav", &parts),
208 "dav1" => dolby_vision(VideoCodec::Av1, false, &parts),
209 _ => None,
210 };
211 parsed.ok_or_else(bad)
212 }
213}
214
215fn avc(in_band: bool, parts: &[&str]) -> Option<CodecString> {
217 let [hex] = parts else { return None };
218 if hex.len() != 6 {
219 return None;
220 }
221 let byte = |at: usize| hex_byte(hex.get(at..at + 2)?);
222 Some(CodecString::Avc {
223 in_band,
224 profile: byte(0)?,
225 constraints: byte(2)?,
226 level: byte(4)?,
227 })
228}
229
230fn hevc(in_band: bool, parts: &[&str]) -> Option<CodecString> {
231 let [profile, compatibility, tier_level, constraints @ ..] = parts else {
232 return None;
233 };
234 if constraints.len() > 6 {
235 return None;
236 }
237 let (profile_space, profile) = match profile.as_bytes().first()? {
238 b'A' => (1, &profile[1..]),
239 b'B' => (2, &profile[1..]),
240 b'C' => (3, &profile[1..]),
241 _ => (0, *profile),
242 };
243 let tier = match tier_level.as_bytes().first()? {
244 b'L' => Tier::Main,
245 b'H' => Tier::High,
246 _ => return None,
247 };
248 let mut bytes = [0; 6];
249 for (byte, hex) in bytes.iter_mut().zip(constraints) {
250 *byte = hex_byte(hex)?;
251 }
252 if compatibility.is_empty() || compatibility.len() > 8 {
253 return None;
254 }
255 Some(CodecString::Hevc {
256 in_band,
257 profile_space,
258 profile: decimal(profile)?,
259 compatibility: u32::from_str_radix(compatibility, 16).ok()?,
260 tier,
261 level: decimal(&tier_level[1..])?,
262 constraints: bytes,
263 })
264}
265
266fn av1(parts: &[&str]) -> Option<CodecString> {
268 let [profile, level_tier, depth, rest @ ..] = parts else {
269 return None;
270 };
271 if rest.len() > 6 || profile.len() != 1 || level_tier.len() != 3 || depth.len() != 2 {
272 return None;
273 }
274 let tier = match level_tier.as_bytes()[2] {
275 b'M' => Tier::Main,
276 b'H' => Tier::High,
277 _ => return None,
278 };
279 Some(CodecString::Av1 {
280 profile: decimal(profile)?,
281 level: decimal(&level_tier[..2])?,
282 tier,
283 bit_depth: decimal(depth)?,
284 })
285}
286
287fn dolby_vision(base: VideoCodec, in_band: bool, parts: &[&str]) -> Option<CodecString> {
289 let [profile, level] = parts else { return None };
290 if profile.len() != 2 || level.len() != 2 {
291 return None;
292 }
293 Some(CodecString::DolbyVision {
294 base,
295 in_band,
296 profile: decimal(profile)?,
297 level: decimal(level)?,
298 })
299}
300
301fn decimal(digits: &str) -> Option<u8> {
303 if digits.is_empty() || !digits.bytes().all(|b| b.is_ascii_digit()) {
304 return None;
305 }
306 digits.parse().ok()
307}
308
309fn hex_byte(digits: &str) -> Option<u8> {
311 if digits.is_empty() || digits.len() > 2 || !digits.bytes().all(|b| b.is_ascii_hexdigit()) {
312 return None;
313 }
314 u8::from_str_radix(digits, 16).ok()
315}
316
317impl fmt::Display for CodecString {
318 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320 let tier = |tier: Tier| match tier {
321 Tier::Main => 'L',
322 Tier::High => 'H',
323 };
324 match *self {
325 Self::Avc {
326 in_band,
327 profile,
328 constraints,
329 level,
330 } => write!(
331 f,
332 "{}.{profile:02X}{constraints:02X}{level:02X}",
333 if in_band { "avc3" } else { "avc1" }
334 ),
335 Self::Hevc {
336 in_band,
337 profile_space,
338 profile,
339 compatibility,
340 tier: t,
341 level,
342 constraints,
343 } => {
344 let space = match profile_space {
345 1 => "A",
346 2 => "B",
347 3 => "C",
348 _ => "",
349 };
350 write!(
351 f,
352 "{}.{space}{profile}.{compatibility:X}.{}{level}",
353 if in_band { "hev1" } else { "hvc1" },
354 tier(t)
355 )?;
356 let kept = constraints
357 .iter()
358 .rposition(|&b| b != 0)
359 .map_or(0, |i| i + 1);
360 for byte in &constraints[..kept] {
361 write!(f, ".{byte:X}")?;
362 }
363 Ok(())
364 }
365 Self::Av1 {
366 profile,
367 level,
368 tier: t,
369 bit_depth,
370 } => {
371 let t = match t {
372 Tier::Main => 'M',
373 Tier::High => 'H',
374 };
375 write!(f, "av01.{profile}.{level:02}{t}.{bit_depth:02}")
376 }
377 Self::DolbyVision {
378 base,
379 in_band,
380 profile,
381 level,
382 } => {
383 let fourcc = match (base, in_band) {
384 (VideoCodec::H264, false) => "dva1",
385 (VideoCodec::H264, true) => "dvav",
386 (VideoCodec::Av1, _) => "dav1",
387 (_, false) => "dvh1",
388 (_, true) => "dvhe",
389 };
390 write!(f, "{fourcc}.{profile:02}.{level:02}")
391 }
392 }
393 }
394}
395
396impl serde::Serialize for CodecString {
398 fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
399 s.collect_str(self)
400 }
401}
402
403impl<'de> serde::Deserialize<'de> for CodecString {
404 fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
405 let s = String::deserialize(d)?;
406 s.parse().map_err(serde::de::Error::custom)
407 }
408}
409
410#[cfg(test)]
411mod tests {
412 use super::*;
413
414 fn read(s: &str) -> CodecString {
415 s.parse().unwrap_or_else(|e| panic!("{e}"))
416 }
417
418 const APPLE_TV_4K_A10X: [(&str, bool); 9] = [
423 ("hvc1.2.4.L153.B0", true),
424 ("hvc1.2.4.L186.B0", true),
425 ("hvc1.2.4.L999.B0", false),
426 ("dvh1.05.06", true),
427 ("dvh1.08.06", true),
428 ("dvh1.07.06", false),
429 ("dvhe.07.06", false),
430 ("av01.0.13M.10", true),
431 ("hvc1.2.4.L189.B0", false),
433 ];
434
435 fn played(list: &[CodecString], s: &str) -> bool {
436 s.parse::<CodecString>()
437 .is_ok_and(|source| list.iter().any(|listed| listed.covers(&source)))
438 }
439
440 #[test]
441 fn the_apple_tv_s_answers_are_its_list_s() {
442 let list: Vec<CodecString> = APPLE_TV_4K_A10X
443 .iter()
444 .filter(|(_, yes)| *yes)
445 .map(|(s, _)| read(s))
446 .collect();
447 for (s, yes) in APPLE_TV_4K_A10X {
448 assert_eq!(played(&list, s), yes, "{s}");
449 }
450 }
451
452 #[test]
455 fn hevc_level_999_is_no_string() {
456 assert!("hvc1.2.4.L999.B0".parse::<CodecString>().is_err());
457 }
458
459 #[test]
460 fn a_list_at_level_5_1_does_not_play_6_2_and_one_at_6_2_does() {
461 let at_153 = [read("hvc1.2.4.L153.B0")];
462 assert!(!played(&at_153, "hvc1.2.4.L186.B0"));
463 assert!(played(&at_153, "hvc1.2.4.L150.B0"));
464 let at_186 = [read("hvc1.2.4.L186.B0")];
465 assert!(played(&at_186, "hvc1.2.4.L153.B0"));
466 }
467
468 #[test]
471 fn dolby_vision_7_is_its_own_profile() {
472 let list = [read("dvh1.05.06"), read("dvh1.08.06")];
473 assert!(!played(&list, "dvh1.07.06"));
474 assert!(!played(&list, "dvhe.07.06"));
475 assert!(played(&list, "dvhe.08.06"), "dvhe is dvh1's decoder");
476 assert!(played(&list, "dvh1.08.05"));
477 assert!(!played(&list, "dvh1.08.09"));
478 assert!(!played(&list, "dav1.10.06"));
480 }
481
482 #[test]
483 fn a_high_tier_stream_needs_a_high_tier_decoder() {
484 let main = [read("hvc1.2.4.L153.B0")];
485 assert!(!played(&main, "hvc1.2.4.H153.B0"));
486 let high = [read("hvc1.2.4.H153.B0")];
487 assert!(played(&high, "hvc1.2.4.L153.B0"));
488 assert!(played(&high, "hvc1.2.4.H150.90"));
489 }
490
491 #[test]
495 fn an_in_band_source_is_judged_by_an_out_of_band_list() {
496 let list = [read("hvc1.2.4.L153.B0"), read("dvh1.08.06")];
497 assert!(played(&list, "hev1.2.4.L153.B0"));
498 assert!(!played(&list, "hev1.2.4.H120.B0"), "high tier");
499 assert!(played(&list, "dvhe.08.06"));
500 assert!(!played(&list, "hev1.2.4.L186.B0"));
501 }
502
503 #[test]
507 fn hevc_compatibility_flags_are_not_compared() {
508 let list = [read("hvc1.2.4.L153.B0")];
509 assert!(played(&list, "hvc1.2.6.L153.B0"));
510 assert!(played(&list, "hvc1.2.0.L153.B0"));
511 assert!(played(&list, "hvc1.2.4.L153.90"), "constraint bytes");
512 assert!(played(&[read("hvc1.1.6.L153.B0")], "hvc1.1.2.L120.B0"));
513 }
514
515 #[test]
518 fn dolby_vision_levels_past_the_list_are_not_played() {
519 let list = [read("dvh1.05.09"), read("dvh1.08.09")];
520 for level in 1..=9 {
521 assert!(played(&list, &format!("dvh1.08.{level:02}")), "{level}");
522 assert!(played(&list, &format!("dvh1.05.{level:02}")), "{level}");
523 }
524 for level in 10..=13 {
525 assert!(!played(&list, &format!("dvh1.08.{level:02}")), "{level}");
526 }
527 assert!(!played(&list, "dvh1.07.06"));
528 }
529
530 #[test]
532 fn hevc_main_10_plays_main() {
533 assert!(played(&[read("hvc1.2.4.L153.B0")], "hvc1.1.6.L120.90"));
534 assert!(!played(&[read("hvc1.1.6.L153.B0")], "hvc1.2.4.L120.B0"));
535 assert!(!played(&[read("hvc1.2.4.L153.B0")], "hvc1.4.10.L153.B0"));
537 assert!(!played(&[read("hvc1.2.4.L153.B0")], "hvc1.A2.4.L153.B0"));
539 assert!(played(&[read("hev1.2.4.L153.B0")], "hvc1.2.4.L153.B0"));
541 }
542
543 #[test]
546 fn h264_high_plays_main_and_constrained_baseline() {
547 let high = [read("avc1.640034")];
548 assert!(played(&high, "avc1.640028"));
549 assert!(played(&high, "avc1.4D401F"), "Main 3.1");
550 assert!(played(&high, "avc1.42E01E"), "constrained baseline 3.0");
551 assert!(!played(&high, "avc1.42001E"), "baseline 3.0");
552 assert!(!played(&high, "avc1.6E0028"), "High 10 4.0");
553 assert!(!played(&high, "avc1.640035"), "High 5.3");
554 assert!(played(&[read("avc1.6E0033")], "avc1.640028"));
555 assert!(played(&[read("avc1.42001E")], "avc1.42001E"));
556 }
557
558 #[test]
559 fn av1_is_judged_at_its_own_bit_depth() {
560 let list = [read("av01.0.13M.10")];
561 assert!(played(&list, "av01.0.12M.10"));
562 assert!(!played(&list, "av01.0.12M.08"), "8-bit is listed apart");
563 assert!(!played(&list, "av01.0.16M.10"));
564 assert!(!played(&list, "av01.0.13H.10"));
565 assert!(!played(&list, "av01.1.13M.10"), "High profile");
566 assert!(played(&list, "av01.0.08M.10.0.110.09.16.09.0"));
568 }
569
570 #[test]
571 fn no_codec_covers_another() {
572 assert!(!read("hvc1.2.4.L186.B0").covers(&read("av01.0.08M.10")));
573 assert!(!read("dvh1.08.06").covers(&read("hvc1.2.4.L153.B0")));
574 assert!(!read("hvc1.2.4.L186.B0").covers(&read("dvh1.08.06")));
575 }
576
577 #[test]
578 fn strings_read_back_as_they_are_written() {
579 for s in [
580 "hvc1.2.4.L153.B0",
581 "hvc1.1.6.L93.B0",
582 "hev1.A1.60000000.H120.B0.23",
583 "hvc1.2.4.L120",
584 "avc1.640028",
585 "avc3.4D401F",
586 "av01.0.13M.10",
587 "dvh1.08.06",
588 "dvhe.05.09",
589 "dva1.09.05",
590 "dav1.10.04",
591 ] {
592 assert_eq!(read(s).to_string(), s);
593 }
594 }
595
596 #[test]
597 fn a_codec_string_is_its_string_in_json() {
598 let s = read("dvh1.08.06");
599 assert_eq!(serde_json::to_string(&s).unwrap(), r#""dvh1.08.06""#);
600 assert_eq!(
601 serde_json::from_str::<CodecString>(r#""dvh1.08.06""#).unwrap(),
602 s
603 );
604 assert!(serde_json::from_str::<CodecString>(r#""dvh1""#).is_err());
605 }
606
607 #[test]
608 fn what_is_not_a_codec_string_is_refused() {
609 for s in [
610 "",
611 "hevc",
612 "hvc1",
613 "hvc1.2.4",
614 "hvc1.2.4.153.B0",
615 "hvc1.2.4.X153.B0",
616 "hvc1.2.4.L153.B0.0.0.0.0.0.0",
617 "hvc1.2.123456789.L153",
618 "hvc1.2.4.L-1",
619 "avc1.6400",
620 "avc1.64002G",
621 "avc1.66.30",
622 "av01.0.13.10",
623 "av01.0.13X.10",
624 "dvh1.8.6",
625 "dvh1.08",
626 "mp4a.40.2",
627 ] {
628 assert!(s.parse::<CodecString>().is_err(), "{s}");
629 }
630 }
631}