1use std::{fmt, str::FromStr};
2
3use serde::{Deserialize, Serialize};
4
5use crate::Error;
6
7#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
14pub struct H265 {
15 pub in_band: bool,
18
19 pub profile_space: u8,
22 pub profile_idc: u8,
24
25 pub profile_compatibility_flags: [u8; 4],
31
32 pub tier_flag: bool,
35 pub level_idc: u8,
37
38 pub constraint_flags: [u8; 6],
41}
42
43impl fmt::Display for H265 {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 let compatibility = format!(
48 "{:X}",
49 u32::from_be_bytes(self.profile_compatibility_flags).reverse_bits()
50 );
51
52 let significant = self.constraint_flags.iter().rev().skip_while(|b| **b == 0).count();
59 let constraints = if significant == 0 {
60 String::new()
61 } else {
62 let body = self
63 .constraint_flags
64 .iter()
65 .take(significant)
66 .map(|b| format!("{b:X}"))
67 .collect::<Vec<_>>()
68 .join(".");
69 format!(".{body}")
70 };
71
72 write!(
73 f,
74 "{}.{}{}.{}.{}{}{}",
75 match self.in_band {
76 true => "hev1",
77 false => "hvc1",
78 },
79 match self.profile_space {
80 0 => "".to_string(),
81 n => (b'A'.saturating_add(n).saturating_sub(1) as char).to_string(),
82 },
83 self.profile_idc,
84 compatibility,
85 match self.tier_flag {
86 true => "H",
87 false => "L",
88 },
89 self.level_idc,
90 constraints,
91 )
92 }
93}
94
95impl FromStr for H265 {
96 type Err = Error;
97
98 fn from_str(s: &str) -> Result<Self, Self::Err> {
99 let mut parts = s.split('.');
100
101 let in_band = match parts.next() {
102 Some("hev1") => true,
103 Some("hvc1") => false,
104 _ => return Err(Error::InvalidCodec),
105 };
106
107 let profile = parts.next().ok_or(Error::InvalidCodec)?;
108 let (profile_space, profile_idc) = match profile.as_bytes().first().ok_or(Error::InvalidCodec)? {
109 space @ b'A'..=b'C' => (1 + space - b'A', &profile[1..]),
111 _ => (0, profile),
112 };
113 let profile_idc = crate::catalog::codec_number(profile_idc, 10)?;
114
115 let compatibility = parts.next().ok_or(Error::InvalidCodec)?;
116 let profile_compatibility_flags = crate::catalog::codec_number::<u32>(compatibility, 16)?
117 .reverse_bits()
118 .to_be_bytes();
119
120 let level = parts.next().ok_or(Error::InvalidCodec)?;
121
122 let tier_flag = match level.as_bytes().first() {
123 Some(b'H') => true,
124 Some(b'L') => false,
125 _ => return Err(Error::InvalidCodec),
126 };
127
128 let level_idc = crate::catalog::codec_number(&level[1..], 10)?;
129
130 let mut constraints: Vec<&str> = parts.collect();
131 if constraints.last() == Some(&"") {
133 constraints.pop();
134 }
135 if constraints.len() > 6 {
136 return Err(Error::InvalidCodec);
137 }
138
139 let mut constraint_flags = [0u8; 6];
140 for (flags, constraint) in constraint_flags.iter_mut().zip(constraints) {
141 *flags = crate::catalog::codec_number(constraint, 16)?;
142 }
143
144 Ok(Self {
145 in_band,
146 profile_space,
147 profile_idc,
148 profile_compatibility_flags,
149 tier_flag,
150 level_idc,
151 constraint_flags,
152 })
153 }
154}
155
156#[cfg(test)]
157mod tests {
158 use crate::catalog::VideoCodec;
159
160 use super::*;
161
162 #[test]
163 fn test_h265() {
164 let encoded = "hev1.1.6.L93.B0";
166 let decoded = H265 {
167 in_band: true,
168 profile_space: 0,
169 profile_idc: 1,
170 profile_compatibility_flags: [0x60, 0, 0, 0],
171 tier_flag: false,
172 level_idc: 93,
173 constraint_flags: [0xB0, 0, 0, 0, 0, 0],
174 }
175 .into();
176
177 let output = VideoCodec::from_str(encoded).expect("failed to parse");
178 assert_eq!(output, decoded);
179
180 let output = decoded.to_string();
181 assert_eq!(output, encoded);
182 }
183
184 #[test]
185 fn test_h265_long() {
186 let encoded = "hev1.A4.41.H120.B0.23";
187 let decoded = H265 {
188 in_band: true,
189 profile_space: 1,
190 profile_idc: 4,
191 profile_compatibility_flags: [0x82, 0, 0, 0],
193 tier_flag: true,
194 level_idc: 120,
195 constraint_flags: [0xB0, 0x23, 0, 0, 0, 0],
196 };
197
198 let output = H265::from_str(encoded).expect("failed to parse");
199 assert_eq!(output, decoded);
200
201 let output = decoded.to_string();
202 assert_eq!(output, encoded);
203 }
204
205 #[test]
206 fn test_h265_out_of_band() {
207 let encoded = "hvc1.A1.6.H93.B0";
208 let output = H265::from_str(encoded).unwrap();
209 assert!(!output.in_band);
210 assert_eq!(output.profile_compatibility_flags, [0x60, 0, 0, 0]);
211
212 let output = output.to_string();
213 assert_eq!(output, encoded);
214 }
215
216 #[test]
217 fn test_h265_zero_constraints() {
218 let decoded = H265 {
222 in_band: false,
223 profile_space: 0,
224 profile_idc: 1,
225 profile_compatibility_flags: [0x60, 0, 0, 0],
226 tier_flag: false,
227 level_idc: 150,
228 constraint_flags: [0, 0, 0, 0, 0, 0],
229 };
230 assert_eq!(decoded.to_string(), "hvc1.1.6.L150");
231 assert_eq!(H265::from_str("hvc1.1.6.L150").unwrap(), decoded);
232 assert_eq!(H265::from_str("hvc1.1.6.L150.").unwrap(), decoded);
234 }
235
236 #[test]
237 fn all_zero_compatibility_round_trips() {
238 let decoded = H265 {
241 in_band: false,
242 profile_space: 0,
243 profile_idc: 1,
244 profile_compatibility_flags: [0, 0, 0, 0],
245 tier_flag: false,
246 level_idc: 93,
247 constraint_flags: [0, 0, 0, 0, 0, 0],
248 };
249 assert_eq!(decoded.to_string(), "hvc1.1.0.L93");
250 assert_eq!(H265::from_str("hvc1.1.0.L93").unwrap(), decoded);
251 }
252
253 #[test]
254 fn multi_byte_compatibility_round_trips() {
255 let decoded = H265 {
258 in_band: false,
259 profile_space: 0,
260 profile_idc: 1,
261 profile_compatibility_flags: [0x60, 0x80, 0, 0],
262 tier_flag: false,
263 level_idc: 93,
264 constraint_flags: [0, 0, 0, 0, 0, 0],
265 };
266 assert_eq!(decoded.to_string(), "hvc1.1.106.L93");
267 assert_eq!(H265::from_str("hvc1.1.106.L93").unwrap(), decoded);
268 }
269}