Skip to main content

oa/video/codec/
h264.rs

1//! Backend-neutral H.264 parameter-set parsing.
2
3use crate::{Error, Result};
4
5use super::bitstream::{BitReader, remove_emulation_prevention};
6pub use crate::video::types::H264TimingInfo;
7
8const MAX_H264_POC_CYCLE: usize = 256;
9
10/// Parsed H.264 sequence parameter set required by decode-session setup.
11#[derive(Clone, Debug, PartialEq, Eq)]
12pub struct H264SequenceParameterSet {
13	pub id: u32,
14	pub profile_idc: u32,
15	pub level_idc: u32,
16	pub constraint_flags: u32,
17	pub chroma_format_idc: u32,
18	pub bit_depth_luma_minus_8: u32,
19	pub bit_depth_chroma_minus_8: u32,
20	pub log2_max_frame_num_minus_4: u32,
21	pub pic_order_count_type: u32,
22	pub offset_for_non_ref_pic: i32,
23	pub offset_for_top_to_bottom_field: i32,
24	pub log2_max_pic_order_count_lsb_minus_4: u32,
25	pub offset_for_ref_frame: Vec<i32>,
26	pub width_in_macroblocks: u32,
27	pub height_in_map_units: u32,
28	pub max_num_ref_frames: u32,
29	pub delta_pic_order_always_zero: bool,
30	pub separate_colour_plane: bool,
31	pub qpprime_y_zero_transform_bypass: bool,
32	pub scaling_lists: Option<H264ScalingLists>,
33	pub gaps_in_frame_num_value_allowed: bool,
34	pub frame_mbs_only: bool,
35	pub mb_adaptive_frame_field: bool,
36	pub direct_8x8_inference: bool,
37	pub frame_crop_left_offset: u32,
38	pub frame_crop_right_offset: u32,
39	pub frame_crop_top_offset: u32,
40	pub frame_crop_bottom_offset: u32,
41	pub vui: Option<H264VuiParameters>,
42}
43
44/// H.264 sequence- or picture-level scaling-list syntax in scan order.
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct H264ScalingLists {
47	pub present_mask: u16,
48	pub use_default_mask: u16,
49	pub list_4x4: [[u8; 16]; 6],
50	pub list_8x8: [[u8; 64]; 6],
51}
52
53/// H.264 VUI aspect-ratio syntax retained with an optional extended SAR.
54#[derive(Clone, Copy, Debug, PartialEq, Eq)]
55pub struct H264AspectRatio {
56	pub idc: u8,
57	pub sar_width: u16,
58	pub sar_height: u16,
59}
60
61/// Optional H.264 VUI colour-description triplet.
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub struct H264ColourDescription {
64	pub colour_primaries: u8,
65	pub transfer_characteristics: u8,
66	pub matrix_coefficients: u8,
67}
68
69/// H.264 VUI video-signal syntax.
70#[derive(Clone, Copy, Debug, PartialEq, Eq)]
71pub struct H264VideoSignal {
72	pub video_format: u8,
73	pub full_range: bool,
74	pub colour_description: Option<H264ColourDescription>,
75}
76
77/// H.264 VUI chroma sample locations for top and bottom fields.
78#[derive(Clone, Copy, Debug, PartialEq, Eq)]
79pub struct H264ChromaLocation {
80	pub top_field: u32,
81	pub bottom_field: u32,
82}
83
84/// One H.264 hypothetical-reference-decoder CPB schedule entry.
85#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub struct H264CpbEntry {
87	pub bit_rate_value_minus_1: u32,
88	pub cpb_size_value_minus_1: u32,
89	pub constant_bit_rate: bool,
90}
91
92/// H.264 hypothetical-reference-decoder parameters.
93#[derive(Clone, Debug, PartialEq, Eq)]
94pub struct H264HrdParameters {
95	pub bit_rate_scale: u8,
96	pub cpb_size_scale: u8,
97	pub entries: Vec<H264CpbEntry>,
98	pub initial_cpb_removal_delay_length_minus_1: u8,
99	pub cpb_removal_delay_length_minus_1: u8,
100	pub dpb_output_delay_length_minus_1: u8,
101	pub time_offset_length: u8,
102}
103
104/// H.264 VUI bitstream-restriction syntax.
105#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub struct H264BitstreamRestriction {
107	pub motion_vectors_over_picture_boundaries: bool,
108	pub max_bytes_per_picture_denom: u32,
109	pub max_bits_per_macroblock_denom: u32,
110	pub log2_max_motion_vector_length_horizontal: u32,
111	pub log2_max_motion_vector_length_vertical: u32,
112	pub max_num_reorder_frames: u32,
113	pub max_dec_frame_buffering: u32,
114}
115
116/// Parsed H.264 video-usability information required by decoder backends.
117#[derive(Clone, Debug, PartialEq, Eq)]
118pub struct H264VuiParameters {
119	pub aspect_ratio: Option<H264AspectRatio>,
120	pub overscan_appropriate: Option<bool>,
121	pub video_signal: Option<H264VideoSignal>,
122	pub chroma_location: Option<H264ChromaLocation>,
123	pub timing: Option<H264TimingInfo>,
124	pub nal_hrd: Option<H264HrdParameters>,
125	pub vcl_hrd: Option<H264HrdParameters>,
126	pub low_delay_hrd: Option<bool>,
127	pub picture_structure_present: bool,
128	pub bitstream_restriction: Option<H264BitstreamRestriction>,
129}
130
131impl H264SequenceParameterSet {
132	/// Return the coded width in luma samples before cropping.
133	pub fn coded_width(&self) -> Result<u32> {
134		self
135			.width_in_macroblocks
136			.checked_mul(16)
137			.ok_or_else(|| Error::data_loss("H.264 coded width overflows u32"))
138	}
139
140	/// Return the coded height in luma samples before cropping.
141	pub fn coded_height(&self) -> Result<u32> {
142		self
143			.height_in_map_units
144			.checked_mul(if self.frame_mbs_only { 16 } else { 32 })
145			.ok_or_else(|| Error::data_loss("H.264 coded height overflows u32"))
146	}
147	/// Visible rectangle for the progressively coded 4:2:0 decode route.
148	pub(crate) fn progressive_420_crop(&self) -> Result<([u32; 2], crate::video::VideoExtent)> {
149		if !self.frame_mbs_only || self.chroma_format_idc != 1 {
150			return Err(Error::missing_capability(
151				"H.264 visible output requires progressive 4:2:0",
152			));
153		}
154		let dimension = |coded: u32, start: u32, end: u32| -> Result<(u32, u32)> {
155			let crop = start
156				.checked_add(end)
157				.and_then(|sum| sum.checked_mul(2))
158				.ok_or_else(|| Error::data_loss("H.264 crop overflows u32"))?;
159			let visible = coded
160				.checked_sub(crop)
161				.filter(|&visible| visible > 0)
162				.ok_or_else(|| Error::data_loss("H.264 crop exceeds coded extent"))?;
163			Ok((start * 2, visible))
164		};
165		let (x, width) = dimension(
166			self.coded_width()?,
167			self.frame_crop_left_offset,
168			self.frame_crop_right_offset,
169		)?;
170		let (y, height) = dimension(
171			self.coded_height()?,
172			self.frame_crop_top_offset,
173			self.frame_crop_bottom_offset,
174		)?;
175		Ok(([x, y], crate::video::VideoExtent { width, height }))
176	}
177}
178
179/// Parsed H.264 picture parameter set required by decode-session setup.
180#[derive(Clone, Debug, PartialEq, Eq)]
181pub struct H264PictureParameterSet {
182	pub id: u32,
183	pub sequence_parameter_set_id: u32,
184	pub num_ref_idx_l0_default_active_minus_1: u32,
185	pub num_ref_idx_l1_default_active_minus_1: u32,
186	pub weighted_bipred_idc: u32,
187	pub pic_init_qp_minus_26: i32,
188	pub pic_init_qs_minus_26: i32,
189	pub chroma_qp_index_offset: i32,
190	pub second_chroma_qp_index_offset: i32,
191	pub entropy_coding_mode: bool,
192	pub bottom_field_pic_order_in_frame_present: bool,
193	pub weighted_pred: bool,
194	pub deblocking_filter_control_present: bool,
195	pub constrained_intra_pred: bool,
196	pub redundant_pic_count_present: bool,
197	pub transform_8x8_mode: bool,
198	pub scaling_lists: Option<H264ScalingLists>,
199}
200
201/// Normalized H.264 primary slice type.
202#[derive(Clone, Copy, Debug, PartialEq, Eq)]
203pub enum H264SliceType {
204	P,
205	B,
206	I,
207	Sp,
208	Si,
209}
210
211/// One decoded-reference-picture marking command from an H.264 slice header.
212#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
213pub struct H264MemoryManagementControl {
214	pub operation: u32,
215	pub difference_of_picture_numbers_minus_1: u32,
216	pub long_term_picture_number: u32,
217	pub long_term_frame_index: u32,
218	pub max_long_term_frame_index_plus_1: u32,
219}
220
221/// Parsed H.264 slice fields required by picture submission and DPB updates.
222#[derive(Clone, Debug, PartialEq, Eq)]
223pub struct H264SliceHeader {
224	pub first_macroblock_in_slice: u32,
225	pub slice_type: H264SliceType,
226	pub picture_parameter_set_id: u32,
227	pub frame_number: u32,
228	pub idr_picture_id: Option<u32>,
229	pub picture_order_count_lsb: Option<u32>,
230	pub field_picture: bool,
231	pub bottom_field: bool,
232	pub is_idr: bool,
233	pub is_reference: bool,
234	pub no_output_of_prior_pictures: bool,
235	pub long_term_reference: bool,
236	pub adaptive_reference_picture_marking: bool,
237	pub memory_management: Vec<H264MemoryManagementControl>,
238}
239
240/// Parse one raw H.264 SPS NAL unit without an Annex-B start code.
241pub fn parse_h264_sps(nal: &[u8]) -> Result<H264SequenceParameterSet> {
242	validate_nal(nal, 7, "SPS")?;
243	let rbsp = remove_emulation_prevention(&nal[1..]);
244	let mut bits = BitReader::new(&rbsp);
245	let profile_idc = bits.read_bits(8)?;
246	let constraint_flags = bits.read_bits(8)?;
247	let level_idc = bits.read_bits(8)?;
248	let id = bits.read_ue()?;
249	if id > 31 {
250		return Err(Error::data_loss("H.264 SPS id exceeds 31"));
251	}
252	let mut chroma_format_idc = 1;
253	let mut bit_depth_luma_minus_8 = 0;
254	let mut bit_depth_chroma_minus_8 = 0;
255	let mut separate_colour_plane = false;
256	let mut qpprime_y_zero_transform_bypass = false;
257	let mut scaling_lists = None;
258	if high_profile(profile_idc) {
259		chroma_format_idc = bits.read_ue()?;
260		if chroma_format_idc > 3 {
261			return Err(Error::data_loss("H.264 SPS chroma format exceeds 3"));
262		}
263		if chroma_format_idc == 3 {
264			separate_colour_plane = bits.read_bits(1)? != 0;
265		}
266		bit_depth_luma_minus_8 = bits.read_ue()?;
267		bit_depth_chroma_minus_8 = bits.read_ue()?;
268		qpprime_y_zero_transform_bypass = bits.read_bits(1)? != 0;
269		if bits.read_bits(1)? != 0 {
270			scaling_lists = Some(parse_h264_scaling_lists(
271				&mut bits,
272				if chroma_format_idc == 3 { 12 } else { 8 },
273			)?);
274		}
275	}
276	let log2_max_frame_num_minus_4 = bits.read_ue()?;
277	let pic_order_count_type = bits.read_ue()?;
278	let mut log2_max_pic_order_count_lsb_minus_4 = 0;
279	let mut delta_pic_order_always_zero = false;
280	let mut offset_for_non_ref_pic = 0;
281	let mut offset_for_top_to_bottom_field = 0;
282	let mut offset_for_ref_frame = Vec::new();
283	if pic_order_count_type == 0 {
284		log2_max_pic_order_count_lsb_minus_4 = bits.read_ue()?;
285	} else if pic_order_count_type == 1 {
286		delta_pic_order_always_zero = bits.read_bits(1)? != 0;
287		offset_for_non_ref_pic = bits.read_se()?;
288		offset_for_top_to_bottom_field = bits.read_se()?;
289		let count = usize::try_from(bits.read_ue()?)
290			.map_err(|_| Error::data_loss("H.264 POC cycle count exceeds usize"))?;
291		if count > MAX_H264_POC_CYCLE {
292			return Err(Error::data_loss("H.264 POC cycle exceeds safety bound"));
293		}
294		offset_for_ref_frame
295			.try_reserve_exact(count)
296			.map_err(|_| Error::resource_exhausted("H.264 POC cycle allocation failed"))?;
297		for _ in 0..count {
298			offset_for_ref_frame.push(bits.read_se()?);
299		}
300	} else if pic_order_count_type > 2 {
301		return Err(Error::data_loss(
302			"H.264 SPS picture-order-count type exceeds 2",
303		));
304	}
305	let max_num_ref_frames = bits.read_ue()?;
306	if max_num_ref_frames > 16 {
307		return Err(Error::data_loss(
308			"H.264 reference frame count exceeds DPB capacity",
309		));
310	}
311	let gaps_in_frame_num_value_allowed = bits.read_bits(1)? != 0;
312	let width_in_macroblocks = bits
313		.read_ue()?
314		.checked_add(1)
315		.ok_or_else(|| Error::data_loss("H.264 macroblock width overflows"))?;
316	let height_in_map_units = bits
317		.read_ue()?
318		.checked_add(1)
319		.ok_or_else(|| Error::data_loss("H.264 map-unit height overflows"))?;
320	let frame_mbs_only = bits.read_bits(1)? != 0;
321	let mb_adaptive_frame_field = !frame_mbs_only && bits.read_bits(1)? != 0;
322	let direct_8x8_inference = bits.read_bits(1)? != 0;
323	let frame_cropping = bits.read_bits(1)? != 0;
324	let (
325		frame_crop_left_offset,
326		frame_crop_right_offset,
327		frame_crop_top_offset,
328		frame_crop_bottom_offset,
329	) = if frame_cropping {
330		(
331			bits.read_ue()?,
332			bits.read_ue()?,
333			bits.read_ue()?,
334			bits.read_ue()?,
335		)
336	} else {
337		(0, 0, 0, 0)
338	};
339	let vui = if bits.read_bits(1)? != 0 {
340		Some(parse_h264_vui(&mut bits)?)
341	} else {
342		None
343	};
344	let parsed = H264SequenceParameterSet {
345		id,
346		profile_idc,
347		level_idc,
348		constraint_flags,
349		chroma_format_idc,
350		bit_depth_luma_minus_8,
351		bit_depth_chroma_minus_8,
352		log2_max_frame_num_minus_4,
353		pic_order_count_type,
354		offset_for_non_ref_pic,
355		offset_for_top_to_bottom_field,
356		log2_max_pic_order_count_lsb_minus_4,
357		offset_for_ref_frame,
358		width_in_macroblocks,
359		height_in_map_units,
360		max_num_ref_frames,
361		delta_pic_order_always_zero,
362		separate_colour_plane,
363		qpprime_y_zero_transform_bypass,
364		scaling_lists,
365		gaps_in_frame_num_value_allowed,
366		frame_mbs_only,
367		mb_adaptive_frame_field,
368		direct_8x8_inference,
369		frame_crop_left_offset,
370		frame_crop_right_offset,
371		frame_crop_top_offset,
372		frame_crop_bottom_offset,
373		vui,
374	};
375	parsed.coded_width()?;
376	parsed.coded_height()?;
377	Ok(parsed)
378}
379
380/// Parse one raw H.264 PPS NAL unit without an Annex-B start code.
381pub fn parse_h264_pps(
382	nal: &[u8],
383	sps: &H264SequenceParameterSet,
384) -> Result<H264PictureParameterSet> {
385	validate_nal(nal, 8, "PPS")?;
386	let rbsp = remove_emulation_prevention(&nal[1..]);
387	let mut bits = BitReader::new(&rbsp);
388	let id = bits.read_ue()?;
389	let sequence_parameter_set_id = bits.read_ue()?;
390	if id > 255 || sequence_parameter_set_id > 31 {
391		return Err(Error::data_loss(
392			"H.264 PPS or referenced SPS id is out of range",
393		));
394	}
395	if sequence_parameter_set_id != sps.id {
396		return Err(Error::invalid_argument(
397			"H.264 PPS does not reference the supplied SPS",
398		));
399	}
400	let entropy_coding_mode = bits.read_bits(1)? != 0;
401	let bottom_field_pic_order_in_frame_present = bits.read_bits(1)? != 0;
402	if bits.read_ue()? != 0 {
403		return Err(Error::missing_capability(
404			"H.264 slice groups are not implemented",
405		));
406	}
407	let num_ref_idx_l0_default_active_minus_1 = bits.read_ue()?;
408	let num_ref_idx_l1_default_active_minus_1 = bits.read_ue()?;
409	if num_ref_idx_l0_default_active_minus_1 >= 32 || num_ref_idx_l1_default_active_minus_1 >= 32 {
410		return Err(Error::data_loss(
411			"H.264 PPS reference-list count exceeds 32",
412		));
413	}
414	let weighted_pred = bits.read_bits(1)? != 0;
415	let weighted_bipred_idc = bits.read_bits(2)?;
416	let pic_init_qp_minus_26 = bits.read_se()?;
417	let pic_init_qs_minus_26 = bits.read_se()?;
418	let chroma_qp_index_offset = bits.read_se()?;
419	let deblocking_filter_control_present = bits.read_bits(1)? != 0;
420	let constrained_intra_pred = bits.read_bits(1)? != 0;
421	let redundant_pic_count_present = bits.read_bits(1)? != 0;
422	let mut transform_8x8_mode = false;
423	let mut scaling_lists = None;
424	let mut second_chroma_qp_index_offset = chroma_qp_index_offset;
425	if bits.more_rbsp_data() {
426		transform_8x8_mode = bits.read_bits(1)? != 0;
427		if bits.read_bits(1)? != 0 {
428			let eight_by_eight_lists = if sps.chroma_format_idc == 3 { 6 } else { 2 };
429			scaling_lists = Some(parse_h264_scaling_lists(
430				&mut bits,
431				6 + usize::from(transform_8x8_mode) * eight_by_eight_lists,
432			)?);
433		}
434		second_chroma_qp_index_offset = bits.read_se()?;
435	}
436	Ok(H264PictureParameterSet {
437		id,
438		sequence_parameter_set_id,
439		num_ref_idx_l0_default_active_minus_1,
440		num_ref_idx_l1_default_active_minus_1,
441		weighted_bipred_idc,
442		pic_init_qp_minus_26,
443		pic_init_qs_minus_26,
444		chroma_qp_index_offset,
445		second_chroma_qp_index_offset,
446		entropy_coding_mode,
447		bottom_field_pic_order_in_frame_present,
448		weighted_pred,
449		deblocking_filter_control_present,
450		constrained_intra_pred,
451		redundant_pic_count_present,
452		transform_8x8_mode,
453		scaling_lists,
454	})
455}
456
457/// Parse one raw H.264 coded-slice NAL using its resolved SPS and PPS.
458///
459/// The returned picture-order-count field contains the coded LSB for POC type
460/// zero. POC types one and two require prior-picture state and therefore return
461/// `None`; the decoder session must derive the final POC rather than inventing
462/// a stateless approximation.
463pub fn parse_h264_slice_header(
464	nal: &[u8],
465	sps: &H264SequenceParameterSet,
466	pps: &H264PictureParameterSet,
467) -> Result<H264SliceHeader> {
468	let Some(&nal_header) = nal.first() else {
469		return Err(Error::data_loss("empty H.264 slice NAL"));
470	};
471	let nal_type = nal_header & 0x1f;
472	if nal_header & 0x80 != 0 || !matches!(nal_type, 1 | 5) {
473		return Err(Error::invalid_argument(
474			"input is not an H.264 coded-slice NAL",
475		));
476	}
477	if pps.sequence_parameter_set_id != sps.id {
478		return Err(Error::invalid_argument(
479			"H.264 PPS does not reference the supplied SPS",
480		));
481	}
482	let rbsp = remove_emulation_prevention(nal);
483	let mut bits = BitReader::new(&rbsp);
484	bits.skip_bits(8)?;
485	let first_macroblock_in_slice = bits.read_ue()?;
486	let raw_slice_type = bits.read_ue()?;
487	if raw_slice_type > 9 {
488		return Err(Error::data_loss("H.264 slice type exceeds 9"));
489	}
490	let slice_type = match raw_slice_type % 5 {
491		0 => H264SliceType::P,
492		1 => H264SliceType::B,
493		2 => H264SliceType::I,
494		3 => H264SliceType::Sp,
495		4 => H264SliceType::Si,
496		_ => unreachable!(),
497	};
498	let picture_parameter_set_id = bits.read_ue()?;
499	if picture_parameter_set_id != pps.id {
500		return Err(Error::invalid_argument(
501			"H.264 slice references a different PPS",
502		));
503	}
504	let frame_number_bits = sps
505		.log2_max_frame_num_minus_4
506		.checked_add(4)
507		.ok_or_else(|| Error::data_loss("H.264 frame-number width overflows"))?;
508	if !(4..=16).contains(&frame_number_bits) {
509		return Err(Error::data_loss(
510			"H.264 frame-number width is outside 4..=16",
511		));
512	}
513	let frame_number = bits.read_bits(frame_number_bits as usize)?;
514	let mut field_picture = false;
515	let mut bottom_field = false;
516	if !sps.frame_mbs_only {
517		field_picture = bits.read_bits(1)? != 0;
518		if field_picture {
519			bottom_field = bits.read_bits(1)? != 0;
520		}
521	}
522	let is_idr = nal_type == 5;
523	let idr_picture_id = is_idr.then(|| bits.read_ue()).transpose()?;
524	let picture_order_count_lsb = if sps.pic_order_count_type == 0 {
525		let count = sps
526			.log2_max_pic_order_count_lsb_minus_4
527			.checked_add(4)
528			.ok_or_else(|| Error::data_loss("H.264 POC width overflows"))?;
529		if !(4..=16).contains(&count) {
530			return Err(Error::data_loss("H.264 POC width is outside 4..=16"));
531		}
532		let value = bits.read_bits(count as usize)?;
533		if pps.bottom_field_pic_order_in_frame_present && !field_picture {
534			bits.read_se()?;
535		}
536		Some(value)
537	} else {
538		if sps.pic_order_count_type == 1 && !sps.delta_pic_order_always_zero {
539			bits.read_se()?;
540			if pps.bottom_field_pic_order_in_frame_present && !field_picture {
541				bits.read_se()?;
542			}
543		}
544		None
545	};
546	if pps.redundant_pic_count_present {
547		bits.read_ue()?;
548	}
549	let is_b = slice_type == H264SliceType::B;
550	let has_list_0 = matches!(
551		slice_type,
552		H264SliceType::P | H264SliceType::Sp | H264SliceType::B
553	);
554	if is_b {
555		bits.skip_bits(1)?;
556	}
557	let mut list_0_count = pps.num_ref_idx_l0_default_active_minus_1;
558	let mut list_1_count = pps.num_ref_idx_l1_default_active_minus_1;
559	if has_list_0 && bits.read_bits(1)? != 0 {
560		list_0_count = bits.read_ue()?;
561		if is_b {
562			list_1_count = bits.read_ue()?;
563		}
564	}
565	validate_reference_count(list_0_count)?;
566	if is_b {
567		validate_reference_count(list_1_count)?;
568	}
569	if has_list_0 {
570		skip_reference_list_modification(&mut bits)?;
571	}
572	if is_b {
573		skip_reference_list_modification(&mut bits)?;
574	}
575	if (matches!(slice_type, H264SliceType::P | H264SliceType::Sp) && pps.weighted_pred)
576		|| (is_b && pps.weighted_bipred_idc == 1)
577	{
578		skip_prediction_weight_table(&mut bits, sps, list_0_count, list_1_count, is_b)?;
579	}
580	let is_reference = (nal_header >> 5) & 3 != 0;
581	let mut no_output_of_prior_pictures = false;
582	let mut long_term_reference = false;
583	let mut adaptive_reference_picture_marking = false;
584	let mut memory_management = Vec::new();
585	if is_reference {
586		if is_idr {
587			no_output_of_prior_pictures = bits.read_bits(1)? != 0;
588			long_term_reference = bits.read_bits(1)? != 0;
589		} else {
590			adaptive_reference_picture_marking = bits.read_bits(1)? != 0;
591			if adaptive_reference_picture_marking {
592				for _ in 0..64 {
593					let operation = bits.read_ue()?;
594					if operation == 0 {
595						return Ok(H264SliceHeader {
596							first_macroblock_in_slice,
597							slice_type,
598							picture_parameter_set_id,
599							frame_number,
600							idr_picture_id,
601							picture_order_count_lsb,
602							field_picture,
603							bottom_field,
604							is_idr,
605							is_reference,
606							no_output_of_prior_pictures,
607							long_term_reference,
608							adaptive_reference_picture_marking,
609							memory_management,
610						});
611					}
612					memory_management.push(read_memory_management_control(&mut bits, operation)?);
613				}
614				return Err(Error::data_loss(
615					"H.264 memory-management command list exceeds 64 entries",
616				));
617			}
618		}
619	}
620	Ok(H264SliceHeader {
621		first_macroblock_in_slice,
622		slice_type,
623		picture_parameter_set_id,
624		frame_number,
625		idr_picture_id,
626		picture_order_count_lsb,
627		field_picture,
628		bottom_field,
629		is_idr,
630		is_reference,
631		no_output_of_prior_pictures,
632		long_term_reference,
633		adaptive_reference_picture_marking,
634		memory_management,
635	})
636}
637
638fn validate_reference_count(count_minus_1: u32) -> Result<()> {
639	if count_minus_1 >= 32 {
640		return Err(Error::data_loss(
641			"H.264 active reference-list count exceeds 32",
642		));
643	}
644	Ok(())
645}
646
647fn parse_h264_vui(bits: &mut BitReader<'_>) -> Result<H264VuiParameters> {
648	let aspect_ratio = if bits.read_bits(1)? != 0 {
649		let idc = bits.read_bits(8)? as u8;
650		let (sar_width, sar_height) = if idc == 255 {
651			(bits.read_bits(16)? as u16, bits.read_bits(16)? as u16)
652		} else {
653			(0, 0)
654		};
655		Some(H264AspectRatio {
656			idc,
657			sar_width,
658			sar_height,
659		})
660	} else {
661		None
662	};
663	let overscan_appropriate = if bits.read_bits(1)? != 0 {
664		Some(bits.read_bits(1)? != 0)
665	} else {
666		None
667	};
668	let video_signal = if bits.read_bits(1)? != 0 {
669		let video_format = bits.read_bits(3)? as u8;
670		let full_range = bits.read_bits(1)? != 0;
671		let colour_description = if bits.read_bits(1)? != 0 {
672			Some(H264ColourDescription {
673				colour_primaries: bits.read_bits(8)? as u8,
674				transfer_characteristics: bits.read_bits(8)? as u8,
675				matrix_coefficients: bits.read_bits(8)? as u8,
676			})
677		} else {
678			None
679		};
680		Some(H264VideoSignal {
681			video_format,
682			full_range,
683			colour_description,
684		})
685	} else {
686		None
687	};
688	let chroma_location = if bits.read_bits(1)? != 0 {
689		let top_field = bits.read_ue()?;
690		let bottom_field = bits.read_ue()?;
691		if top_field > 5 || bottom_field > 5 {
692			return Err(Error::data_loss(
693				"H.264 VUI chroma sample location exceeds 5",
694			));
695		}
696		Some(H264ChromaLocation {
697			top_field,
698			bottom_field,
699		})
700	} else {
701		None
702	};
703	let timing = if bits.read_bits(1)? != 0 {
704		Some(H264TimingInfo {
705			num_units_in_tick: bits.read_bits(32)?,
706			time_scale: bits.read_bits(32)?,
707			fixed_frame_rate: bits.read_bits(1)? != 0,
708		})
709	} else {
710		None
711	};
712	let nal_hrd = if bits.read_bits(1)? != 0 {
713		Some(parse_h264_hrd(bits)?)
714	} else {
715		None
716	};
717	let vcl_hrd = if bits.read_bits(1)? != 0 {
718		Some(parse_h264_hrd(bits)?)
719	} else {
720		None
721	};
722	let low_delay_hrd = if nal_hrd.is_some() || vcl_hrd.is_some() {
723		Some(bits.read_bits(1)? != 0)
724	} else {
725		None
726	};
727	let picture_structure_present = bits.read_bits(1)? != 0;
728	let bitstream_restriction = if bits.read_bits(1)? != 0 {
729		let restriction = H264BitstreamRestriction {
730			motion_vectors_over_picture_boundaries: bits.read_bits(1)? != 0,
731			max_bytes_per_picture_denom: bits.read_ue()?,
732			max_bits_per_macroblock_denom: bits.read_ue()?,
733			log2_max_motion_vector_length_horizontal: bits.read_ue()?,
734			log2_max_motion_vector_length_vertical: bits.read_ue()?,
735			max_num_reorder_frames: bits.read_ue()?,
736			max_dec_frame_buffering: bits.read_ue()?,
737		};
738		if restriction.max_dec_frame_buffering > 16
739			|| restriction.max_num_reorder_frames > restriction.max_dec_frame_buffering
740		{
741			return Err(Error::data_loss(
742				"H.264 VUI reorder or buffering count exceeds DPB capacity",
743			));
744		}
745		Some(restriction)
746	} else {
747		None
748	};
749	Ok(H264VuiParameters {
750		aspect_ratio,
751		overscan_appropriate,
752		video_signal,
753		chroma_location,
754		timing,
755		nal_hrd,
756		vcl_hrd,
757		low_delay_hrd,
758		picture_structure_present,
759		bitstream_restriction,
760	})
761}
762
763fn parse_h264_scaling_lists(
764	bits: &mut BitReader<'_>,
765	list_count: usize,
766) -> Result<H264ScalingLists> {
767	if list_count > 12 {
768		return Err(Error::data_loss("H.264 scaling-list count exceeds 12"));
769	}
770	let mut parsed = H264ScalingLists {
771		present_mask: 0,
772		use_default_mask: 0,
773		list_4x4: [[0; 16]; 6],
774		list_8x8: [[0; 64]; 6],
775	};
776	for index in 0..list_count {
777		if bits.read_bits(1)? == 0 {
778			continue;
779		}
780		parsed.present_mask |= 1_u16 << index;
781		let use_default = if index < 6 {
782			read_h264_scaling_list(bits, &mut parsed.list_4x4[index])?
783		} else {
784			read_h264_scaling_list(bits, &mut parsed.list_8x8[index - 6])?
785		};
786		if use_default {
787			parsed.use_default_mask |= 1_u16 << index;
788		}
789	}
790	Ok(parsed)
791}
792
793fn read_h264_scaling_list(bits: &mut BitReader<'_>, output: &mut [u8]) -> Result<bool> {
794	let mut last_scale = 8_i32;
795	let mut next_scale = 8_i32;
796	let mut use_default = false;
797	for (index, value) in output.iter_mut().enumerate() {
798		if next_scale != 0 {
799			let delta = i8::try_from(bits.read_se()?)
800				.map_err(|_| Error::data_loss("H.264 scaling-list delta exceeds signed byte range"))?;
801			next_scale = (last_scale + i32::from(delta)).rem_euclid(256);
802			use_default = index == 0 && next_scale == 0;
803		}
804		let scale = if next_scale == 0 {
805			last_scale
806		} else {
807			next_scale
808		};
809		*value =
810			u8::try_from(scale).map_err(|_| Error::data_loss("H.264 scaling-list value exceeds u8"))?;
811		last_scale = scale;
812	}
813	Ok(use_default)
814}
815
816fn parse_h264_hrd(bits: &mut BitReader<'_>) -> Result<H264HrdParameters> {
817	let entry_count = bits
818		.read_ue()?
819		.checked_add(1)
820		.ok_or_else(|| Error::data_loss("H.264 HRD CPB count overflows"))?;
821	if entry_count > 32 {
822		return Err(Error::data_loss("H.264 HRD CPB count exceeds 32"));
823	}
824	let bit_rate_scale = bits.read_bits(4)? as u8;
825	let cpb_size_scale = bits.read_bits(4)? as u8;
826	let mut entries = Vec::new();
827	entries
828		.try_reserve_exact(entry_count as usize)
829		.map_err(|_| Error::resource_exhausted("H.264 HRD entry allocation failed"))?;
830	for _ in 0..entry_count {
831		entries.push(H264CpbEntry {
832			bit_rate_value_minus_1: bits.read_ue()?,
833			cpb_size_value_minus_1: bits.read_ue()?,
834			constant_bit_rate: bits.read_bits(1)? != 0,
835		});
836	}
837	Ok(H264HrdParameters {
838		bit_rate_scale,
839		cpb_size_scale,
840		entries,
841		initial_cpb_removal_delay_length_minus_1: bits.read_bits(5)? as u8,
842		cpb_removal_delay_length_minus_1: bits.read_bits(5)? as u8,
843		dpb_output_delay_length_minus_1: bits.read_bits(5)? as u8,
844		time_offset_length: bits.read_bits(5)? as u8,
845	})
846}
847
848fn skip_reference_list_modification(bits: &mut BitReader<'_>) -> Result<()> {
849	if bits.read_bits(1)? == 0 {
850		return Ok(());
851	}
852	for _ in 0..256 {
853		match bits.read_ue()? {
854			3 => return Ok(()),
855			0..=2 => {
856				bits.read_ue()?;
857			}
858			_ => {
859				return Err(Error::data_loss(
860					"invalid H.264 reference-list modification",
861				));
862			}
863		}
864	}
865	Err(Error::data_loss(
866		"H.264 reference-list modification exceeds 256 entries",
867	))
868}
869
870fn skip_prediction_weight_table(
871	bits: &mut BitReader<'_>,
872	sps: &H264SequenceParameterSet,
873	list_0_count_minus_1: u32,
874	list_1_count_minus_1: u32,
875	has_list_1: bool,
876) -> Result<()> {
877	bits.read_ue()?;
878	let chroma_array_type = if sps.separate_colour_plane {
879		0
880	} else {
881		sps.chroma_format_idc
882	};
883	if chroma_array_type != 0 {
884		bits.read_ue()?;
885	}
886	let mut skip_list = |count_minus_1| -> Result<()> {
887		for _ in 0..=count_minus_1 {
888			if bits.read_bits(1)? != 0 {
889				bits.read_se()?;
890				bits.read_se()?;
891			}
892			if chroma_array_type != 0 && bits.read_bits(1)? != 0 {
893				for _ in 0..2 {
894					bits.read_se()?;
895					bits.read_se()?;
896				}
897			}
898		}
899		Ok(())
900	};
901	skip_list(list_0_count_minus_1)?;
902	if has_list_1 {
903		skip_list(list_1_count_minus_1)?;
904	}
905	Ok(())
906}
907
908fn read_memory_management_control(
909	bits: &mut BitReader<'_>,
910	operation: u32,
911) -> Result<H264MemoryManagementControl> {
912	let mut command = H264MemoryManagementControl {
913		operation,
914		..H264MemoryManagementControl::default()
915	};
916	match operation {
917		1 => command.difference_of_picture_numbers_minus_1 = bits.read_ue()?,
918		2 => command.long_term_picture_number = bits.read_ue()?,
919		3 => {
920			command.difference_of_picture_numbers_minus_1 = bits.read_ue()?;
921			command.long_term_frame_index = bits.read_ue()?;
922		}
923		4 => command.max_long_term_frame_index_plus_1 = bits.read_ue()?,
924		5 => {}
925		6 => command.long_term_frame_index = bits.read_ue()?,
926		_ => {
927			return Err(Error::data_loss(
928				"invalid H.264 memory-management operation",
929			));
930		}
931	}
932	Ok(command)
933}
934
935fn validate_nal(nal: &[u8], expected_type: u8, label: &str) -> Result<()> {
936	let Some(&header) = nal.first() else {
937		return Err(Error::data_loss(format!("empty H.264 {label} NAL")));
938	};
939	if header & 0x80 != 0 || header & 0x1f != expected_type {
940		return Err(Error::invalid_argument(format!(
941			"input is not a valid H.264 {label} NAL"
942		)));
943	}
944	Ok(())
945}
946
947const fn high_profile(profile_idc: u32) -> bool {
948	matches!(
949		profile_idc,
950		100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
951	)
952}