Skip to main content

hang/catalog/video/
h265.rs

1use std::{fmt, str::FromStr};
2
3use serde::{Deserialize, Serialize};
4
5use crate::Error;
6
7/// H.265/HEVC codec mimetype.
8///
9/// This struct contains the profile, tier, level, and constraint information
10/// needed to identify a specific H.265 variant. The `in_band` flag says whether
11/// parameter sets may ride in band (hev1) or live only in the description (hvc1);
12/// the description, not the flag, decides the NAL framing.
13#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
14pub struct H265 {
15	/// If true (hev1), the VPS/SPS/PPS may also ride in the bitstream ahead of a keyframe.
16	/// If false (hvc1), they live only in the description.
17	pub in_band: bool,
18
19	/// Profile space (0 for main profile space, 1-3 for other spaces)
20	/// If 0, then no character. Otherwise, A for 1, B for 2, C for 3, etc.
21	pub profile_space: u8,
22	/// Profile IDC identifying the profile
23	pub profile_idc: u8,
24
25	/// The raw 32-bit `general_profile_compatibility_flags` in big-endian byte order,
26	/// exactly as the bitstream and the `hvcC` box carry them (`flag[0]` is the most
27	/// significant bit of the first byte).
28	///
29	/// The HEVC codec string renders this bit-reversed, so raw `[0x60, 0, 0, 0]` prints as `6`.
30	pub profile_compatibility_flags: [u8; 4],
31
32	/// Tier flag: false = 'L' (Low), true = 'H' (High)
33	/// 0 = 'L', 1 = 'H'
34	pub tier_flag: bool,
35	/// Level IDC identifying the level
36	pub level_idc: u8,
37
38	/// Constraint indicator flags (hex encoded, trailing zeros may be omitted)
39	/// Hex encoded, trailing zeros may be omitted.
40	pub constraint_flags: [u8; 6],
41}
42
43impl fmt::Display for H265 {
44	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45		// The codec string lists the 32 general_profile_compatibility_flags in reverse
46		// bit order, hex encoded with leading zeros omitted.
47		let compatibility = format!(
48			"{:X}",
49			u32::from_be_bytes(self.profile_compatibility_flags).reverse_bits()
50		);
51
52		// Constraint flags: hex encoded, trailing-zero bytes omitted. When every
53		// byte is zero the component is omitted ENTIRELY (carry its own leading
54		// '.' only when non-empty); otherwise the string ends in a dangling '.'
55		// and an empty final field that `FromStr` rejects ("expected int"). This
56		// happens for streams whose general_constraint_indicator_flags are all
57		// zero (e.g. some IP-camera HEVC encoders).
58		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			// general_profile_space is two bits, and 0 has no letter.
110			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		// Tolerate one empty trailing field (a dangling '.') emitted by older encoders/muxers.
132		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		// Raw 0x60000000 (Main + Main10 compatible) renders bit-reversed as "6".
165		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			// Raw 0x82000000 renders bit-reversed as "41".
192			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		// All-zero general_constraint_indicator_flags (common in live HEVC from
219		// hardware encoders): the constraint component must be omitted entirely.
220		// No trailing '.', and it must round-trip.
221		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		// Parsing accepts an empty trailing constraint field.
233		assert_eq!(H265::from_str("hvc1.1.6.L150.").unwrap(), decoded);
234	}
235
236	#[test]
237	fn all_zero_compatibility_round_trips() {
238		// Placeholder configs carry no flags at all. The component must still be a
239		// parseable "0" rather than empty, or we emit a string we can't read back.
240		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		// Flags spanning more than one byte: the reversal is over the whole 32-bit
256		// value, and intra-value zero nibbles must survive.
257		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}