hang/catalog/video/
h264.rs1use std::{fmt, str::FromStr};
2
3use serde::{Deserialize, Serialize};
4
5use crate::Error;
6
7#[serde_with::serde_as]
13#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
14pub struct H264 {
15 #[serde(default)]
21 pub inline: bool,
22 pub profile: u8,
24 pub constraints: u8,
26 pub level: u8,
28}
29
30impl fmt::Display for H264 {
31 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32 let prefix = if self.inline { "avc3" } else { "avc1" };
33 write!(
34 f,
35 "{}.{:02x}{:02x}{:02x}",
36 prefix, self.profile, self.constraints, self.level
37 )
38 }
39}
40
41impl FromStr for H264 {
42 type Err = Error;
43
44 fn from_str(s: &str) -> Result<Self, Self::Err> {
45 let mut parts = s.split('.');
46 let inline = match parts.next() {
47 Some("avc1") => false,
48 Some("avc3") => true,
49 _ => return Err(Error::InvalidCodec),
50 };
51
52 let part = parts.next().ok_or(Error::InvalidCodec)?;
53 if part.len() != 6 || !part.bytes().all(|byte| byte.is_ascii_hexdigit()) || parts.next().is_some() {
54 return Err(Error::InvalidCodec);
55 }
56
57 Ok(Self {
58 profile: u8::from_str_radix(&part[0..2], 16)?,
59 constraints: u8::from_str_radix(&part[2..4], 16)?,
60 level: u8::from_str_radix(&part[4..6], 16)?,
61 inline,
62 })
63 }
64}
65
66#[cfg(test)]
67mod tests {
68 use std::str::FromStr;
69
70 use crate::catalog::VideoCodec;
71
72 use super::*;
73
74 #[test]
75 fn malformed_hex_fields_are_invalid() {
76 for prefix in ["avc1", "avc3"] {
77 for part in [
78 "aé123",
79 "12aé3",
80 "123aé",
81 "+12345",
82 "12+345",
83 "1234+5",
84 "12gg56",
85 "64001f.00",
86 ] {
87 let encoded = format!("{prefix}.{part}");
88 assert!(
89 matches!(VideoCodec::from_str(&encoded), Err(Error::InvalidCodec)),
90 "{encoded}"
91 );
92 }
93 }
94 }
95
96 #[test]
97 fn test_h264_avc1() {
98 let encoded = "avc1.42c01e";
99 let decoded = H264 {
100 profile: 0x42,
101 constraints: 0xc0,
102 level: 0x1e,
103 inline: false,
104 };
105
106 let output = VideoCodec::from_str(encoded).expect("failed to parse");
107 assert_eq!(output, VideoCodec::H264(decoded.clone()));
108
109 let output = decoded.to_string();
110 assert_eq!(output, encoded);
111 }
112
113 #[test]
114 fn test_h264_avc3() {
115 let encoded = "avc3.42c01e";
116 let decoded = H264 {
117 profile: 0x42,
118 constraints: 0xc0,
119 level: 0x1e,
120 inline: true,
121 };
122
123 let output = VideoCodec::from_str(encoded).expect("failed to parse");
124 assert_eq!(output, VideoCodec::H264(decoded.clone()));
125
126 let output = decoded.to_string();
127 assert_eq!(output, encoded);
128 }
129}