Skip to main content

oa/video/codec/
h265.rs

1//! Backend-neutral H.265 parameter-set parsing.
2
3use crate::{Error, Result};
4
5use super::bitstream::{BitReader, remove_emulation_prevention};
6pub use crate::video::types::H265TimingInfo;
7
8const MAX_SUB_LAYERS: usize = 7;
9const MAX_SHORT_TERM_REFERENCE_SETS: usize = 64;
10
11const H265_DIAGONAL_SCAN_4X4_X: [usize; 16] = [0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 1, 2, 3, 2, 3, 3];
12const H265_DIAGONAL_SCAN_4X4_Y: [usize; 16] = [0, 1, 0, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 3, 2, 3];
13const H265_DIAGONAL_SCAN_8X8_X: [usize; 64] = [
14	0, 0, 1, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6, 0, 1, 2, 3,
15	4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 2, 3, 4, 5, 6, 7, 3, 4, 5, 6, 7, 4, 5, 6, 7, 5, 6, 7, 6, 7, 7,
16];
17const H265_DIAGONAL_SCAN_8X8_Y: [usize; 64] = [
18	0, 1, 0, 2, 1, 0, 3, 2, 1, 0, 4, 3, 2, 1, 0, 5, 4, 3, 2, 1, 0, 6, 5, 4, 3, 2, 1, 0, 7, 6, 5, 4,
19	3, 2, 1, 0, 7, 6, 5, 4, 3, 2, 1, 7, 6, 5, 4, 3, 2, 7, 6, 5, 4, 3, 7, 6, 5, 4, 7, 6, 5, 7, 6, 7,
20];
21const H265_DEFAULT_SCALING_LIST_INTRA: [u8; 64] = [
22	16, 16, 16, 16, 17, 18, 21, 24, 16, 16, 16, 16, 17, 19, 22, 25, 16, 16, 17, 18, 20, 22, 25, 29,
23	16, 16, 18, 21, 24, 27, 31, 36, 17, 17, 20, 24, 30, 35, 41, 47, 18, 19, 22, 27, 35, 44, 54, 65,
24	21, 22, 25, 31, 41, 54, 70, 88, 24, 25, 29, 36, 47, 65, 88, 115,
25];
26const H265_DEFAULT_SCALING_LIST_INTER: [u8; 64] = [
27	16, 16, 16, 16, 17, 18, 20, 24, 16, 16, 16, 17, 18, 20, 24, 25, 16, 16, 17, 18, 20, 24, 25, 28,
28	16, 17, 18, 20, 24, 25, 28, 33, 17, 18, 20, 24, 25, 28, 33, 41, 18, 20, 24, 25, 28, 33, 41, 54,
29	20, 24, 25, 28, 33, 41, 54, 71, 24, 25, 28, 33, 41, 54, 71, 91,
30];
31
32/// General H.265 profile-tier-level fields carried by a VPS.
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
34pub struct H265ProfileTierLevel {
35	pub profile_idc: u32,
36	pub level_idc: u32,
37	pub high_tier: bool,
38	pub progressive_source: bool,
39	pub interlaced_source: bool,
40	pub non_packed_constraint: bool,
41	pub frame_only_constraint: bool,
42}
43
44/// H.265 decoded-picture-buffer limits for every temporal sub-layer.
45#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
46pub struct H265DecodedPictureBuffer {
47	pub max_decoded_picture_buffering_minus_1: [u32; MAX_SUB_LAYERS],
48	pub max_num_reorder_pictures: [u32; MAX_SUB_LAYERS],
49	pub max_latency_increase_plus_1: [u32; MAX_SUB_LAYERS],
50}
51
52/// One coded-picture-buffer entry in an H.265 HRD sub-layer.
53#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
54pub struct H265CpbEntry {
55	pub bit_rate_value_minus_1: u32,
56	pub cpb_size_value_minus_1: u32,
57	pub cpb_size_du_value_minus_1: u32,
58	pub bit_rate_du_value_minus_1: u32,
59	pub constant_bit_rate: bool,
60}
61
62/// H.265 HRD syntax for one temporal sub-layer.
63#[derive(Clone, Debug, Default, PartialEq, Eq)]
64pub struct H265SubLayerHrdParameters {
65	pub fixed_picture_rate_general: bool,
66	pub fixed_picture_rate_within_cvs: bool,
67	pub low_delay: bool,
68	pub elemental_duration_in_tc_minus_1: u32,
69	pub nal_entries: Vec<H265CpbEntry>,
70	pub vcl_entries: Vec<H265CpbEntry>,
71}
72
73/// H.265 hypothetical-reference-decoder parameters.
74#[derive(Clone, Debug, Default, PartialEq, Eq)]
75pub struct H265HrdParameters {
76	pub nal_parameters_present: bool,
77	pub vcl_parameters_present: bool,
78	pub sub_picture_parameters_present: bool,
79	pub sub_picture_cpb_parameters_in_picture_timing_sei: bool,
80	pub tick_divisor_minus_2: u8,
81	pub du_cpb_removal_delay_increment_length_minus_1: u8,
82	pub dpb_output_delay_du_length_minus_1: u8,
83	pub bit_rate_scale: u8,
84	pub cpb_size_scale: u8,
85	pub cpb_size_du_scale: u8,
86	pub initial_cpb_removal_delay_length_minus_1: u8,
87	pub au_cpb_removal_delay_length_minus_1: u8,
88	pub dpb_output_delay_length_minus_1: u8,
89	pub sub_layers: Vec<H265SubLayerHrdParameters>,
90}
91
92/// One VPS HRD table and the layer set to which it applies.
93#[derive(Clone, Debug, Default, PartialEq, Eq)]
94pub struct H265VpsHrdParameters {
95	pub layer_set_index: u32,
96	pub parameters: H265HrdParameters,
97}
98
99/// H.265 pulse-code-modulation syntax retained by an SPS.
100#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
101pub struct H265PcmParameters {
102	pub sample_bit_depth_luma_minus_1: u8,
103	pub sample_bit_depth_chroma_minus_1: u8,
104	pub log2_min_luma_coding_block_size_minus_3: u32,
105	pub log2_diff_max_min_luma_coding_block_size: u32,
106	pub loop_filter_disabled: bool,
107}
108
109/// H.265 sample-aspect-ratio syntax.
110#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
111pub struct H265AspectRatio {
112	pub idc: u8,
113	pub sar_width: u16,
114	pub sar_height: u16,
115}
116
117/// H.265 colour-description syntax.
118#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
119pub struct H265ColourDescription {
120	pub colour_primaries: u8,
121	pub transfer_characteristics: u8,
122	pub matrix_coefficients: u8,
123}
124
125/// H.265 video-signal syntax.
126#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
127pub struct H265VideoSignal {
128	pub video_format: u8,
129	pub full_range: bool,
130	pub colour_description: Option<H265ColourDescription>,
131}
132
133/// H.265 chroma-sample-location syntax.
134#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
135pub struct H265ChromaLocation {
136	pub top_field: u32,
137	pub bottom_field: u32,
138}
139
140/// H.265 VUI bitstream restrictions.
141#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
142pub struct H265BitstreamRestriction {
143	pub tiles_fixed_structure: bool,
144	pub motion_vectors_over_picture_boundaries: bool,
145	pub restricted_reference_picture_lists: bool,
146	pub min_spatial_segmentation_idc: u32,
147	pub max_bytes_per_picture_denom: u32,
148	pub max_bits_per_min_coding_unit_denom: u32,
149	pub log2_max_motion_vector_length_horizontal: u32,
150	pub log2_max_motion_vector_length_vertical: u32,
151}
152
153/// H.265 video-usability information retained by an SPS.
154#[derive(Clone, Debug, Default, PartialEq, Eq)]
155pub struct H265VuiParameters {
156	pub aspect_ratio: Option<H265AspectRatio>,
157	pub overscan_appropriate: Option<bool>,
158	pub video_signal: Option<H265VideoSignal>,
159	pub chroma_location: Option<H265ChromaLocation>,
160	pub neutral_chroma_indication: bool,
161	pub field_sequence: bool,
162	pub frame_field_info_present: bool,
163	pub default_display_window: Option<[u32; 4]>,
164	pub timing: Option<H265TimingInfo>,
165	pub hrd: Option<H265HrdParameters>,
166	pub bitstream_restriction: Option<H265BitstreamRestriction>,
167}
168
169/// Fully resolved H.265 scaling matrices in raster order.
170///
171/// Prediction-mode references and diagonal coefficient walks are resolved by
172/// the parser, so backend lowering can copy these arrays without retaining
173/// bitstream-local prediction state.
174#[derive(Clone, Debug, PartialEq, Eq)]
175pub struct H265ScalingLists {
176	pub list_4x4: [[u8; 16]; 6],
177	pub list_8x8: [[u8; 64]; 6],
178	pub list_16x16: [[u8; 64]; 6],
179	pub list_32x32: [[u8; 64]; 2],
180	pub dc_16x16: [u8; 6],
181	pub dc_32x32: [u8; 2],
182}
183
184/// One fully parsed H.265 short-term reference-picture set.
185///
186/// Syntax masks are retained for standard-video lowering while `delta_pocs`
187/// contains the resolved candidate order required to parse a following
188/// inter-predicted set.
189#[derive(Clone, Debug, Default, PartialEq, Eq)]
190pub struct H265ShortTermReferencePictureSet {
191	pub inter_ref_pic_set_prediction: bool,
192	pub delta_index_minus_1: u32,
193	pub delta_rps_sign: bool,
194	pub abs_delta_rps_minus_1: u32,
195	pub used_by_current_mask: u32,
196	pub use_delta_mask: u32,
197	pub negative_delta_poc_minus_1: Vec<u32>,
198	pub positive_delta_poc_minus_1: Vec<u32>,
199	pub used_by_current_negative_mask: u32,
200	pub used_by_current_positive_mask: u32,
201	pub delta_pocs: Vec<i32>,
202}
203
204/// One long-term H.265 reference picture declared by an SPS.
205#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
206pub struct H265LongTermReferencePicture {
207	pub picture_order_count_lsb: u32,
208	pub used_by_current: bool,
209}
210
211impl Default for H265ScalingLists {
212	fn default() -> Self {
213		let mut lists = Self {
214			list_4x4: [[16; 16]; 6],
215			list_8x8: [[0; 64]; 6],
216			list_16x16: [[0; 64]; 6],
217			list_32x32: [
218				H265_DEFAULT_SCALING_LIST_INTRA,
219				H265_DEFAULT_SCALING_LIST_INTER,
220			],
221			dc_16x16: [16; 6],
222			dc_32x32: [16; 2],
223		};
224		for matrix in 0..6 {
225			let default = if matrix < 3 {
226				H265_DEFAULT_SCALING_LIST_INTRA
227			} else {
228				H265_DEFAULT_SCALING_LIST_INTER
229			};
230			lists.list_8x8[matrix] = default;
231			lists.list_16x16[matrix] = default;
232		}
233		lists
234	}
235}
236
237/// Parsed H.265 video parameter set.
238#[derive(Clone, Debug, PartialEq, Eq)]
239pub struct H265VideoParameterSet {
240	pub id: u32,
241	pub max_sub_layers_minus_1: u32,
242	pub temporal_id_nesting: bool,
243	pub profile_tier_level: H265ProfileTierLevel,
244	pub sub_layer_ordering_info_present: bool,
245	pub decoded_picture_buffer: H265DecodedPictureBuffer,
246	pub max_layer_id: u8,
247	pub layer_id_included: Vec<Vec<bool>>,
248	pub timing: Option<H265TimingInfo>,
249	pub hrd_parameters: Vec<H265VpsHrdParameters>,
250}
251
252/// Parsed H.265 sequence parameter set required by decode-session setup.
253#[derive(Clone, Debug, PartialEq, Eq)]
254pub struct H265SequenceParameterSet {
255	pub id: u32,
256	pub video_parameter_set_id: u32,
257	pub max_sub_layers_minus_1: u32,
258	pub profile_tier_level: H265ProfileTierLevel,
259	pub chroma_format_idc: u32,
260	pub width: u32,
261	pub height: u32,
262	pub coded_width: u32,
263	pub coded_height: u32,
264	pub conformance_window: [u32; 4],
265	pub bit_depth_luma_minus_8: u32,
266	pub bit_depth_chroma_minus_8: u32,
267	pub log2_max_pic_order_count_lsb_minus_4: u32,
268	pub log2_min_luma_coding_block_size_minus_3: u32,
269	pub log2_diff_max_min_luma_coding_block_size: u32,
270	pub log2_min_luma_transform_block_size_minus_2: u32,
271	pub log2_diff_max_min_luma_transform_block_size: u32,
272	pub max_transform_hierarchy_depth_inter: u32,
273	pub max_transform_hierarchy_depth_intra: u32,
274	pub short_term_reference_picture_sets: Vec<H265ShortTermReferencePictureSet>,
275	pub temporal_id_nesting: bool,
276	pub separate_colour_plane: bool,
277	pub sub_layer_ordering_info_present: bool,
278	pub scaling_list_enabled: bool,
279	pub scaling_lists: Option<H265ScalingLists>,
280	pub asymmetric_motion_partitions_enabled: bool,
281	pub sample_adaptive_offset_enabled: bool,
282	/// Compatibility summary; equivalent to `pcm.is_some()`.
283	pub pcm_enabled: bool,
284	pub pcm: Option<H265PcmParameters>,
285	pub long_term_reference_pictures: Vec<H265LongTermReferencePicture>,
286	pub temporal_mvp_enabled: bool,
287	pub strong_intra_smoothing_enabled: bool,
288	pub max_decoded_picture_buffering_minus_1: [u32; MAX_SUB_LAYERS],
289	pub max_num_reorder_pictures: [u32; MAX_SUB_LAYERS],
290	pub max_latency_increase_plus_1: [u32; MAX_SUB_LAYERS],
291	pub vui: Option<H265VuiParameters>,
292}
293
294/// Parsed H.265 picture parameter set required by decode-session setup.
295#[derive(Clone, Debug, PartialEq, Eq)]
296pub struct H265PictureParameterSet {
297	pub id: u32,
298	pub sequence_parameter_set_id: u32,
299	pub num_extra_slice_header_bits: u32,
300	pub num_ref_idx_l0_default_active_minus_1: u32,
301	pub num_ref_idx_l1_default_active_minus_1: u32,
302	pub init_qp_minus_26: i32,
303	pub diff_cu_qp_delta_depth: u32,
304	pub cb_qp_offset: i32,
305	pub cr_qp_offset: i32,
306	pub beta_offset_div_2: i32,
307	pub tc_offset_div_2: i32,
308	pub log2_parallel_merge_level_minus_2: u32,
309	pub num_tile_columns_minus_1: u32,
310	pub num_tile_rows_minus_1: u32,
311	pub column_width_minus_1: Vec<u32>,
312	pub row_height_minus_1: Vec<u32>,
313	pub dependent_slice_segments_enabled: bool,
314	pub output_flag_present: bool,
315	pub sign_data_hiding_enabled: bool,
316	pub cabac_init_present: bool,
317	pub constrained_intra_pred: bool,
318	pub transform_skip_enabled: bool,
319	pub cu_qp_delta_enabled: bool,
320	pub slice_chroma_qp_offsets_present: bool,
321	pub weighted_pred: bool,
322	pub weighted_bipred: bool,
323	pub transquant_bypass_enabled: bool,
324	pub tiles_enabled: bool,
325	pub entropy_coding_sync_enabled: bool,
326	pub uniform_spacing: bool,
327	pub loop_filter_across_tiles_enabled: bool,
328	pub loop_filter_across_slices_enabled: bool,
329	pub deblocking_filter_control_present: bool,
330	pub deblocking_filter_override_enabled: bool,
331	pub deblocking_filter_disabled: bool,
332	pub scaling_lists: Option<H265ScalingLists>,
333	pub lists_modification_present: bool,
334	pub slice_segment_header_extension_present: bool,
335	pub extension_present: bool,
336}
337
338/// H.265 primary slice type.
339#[derive(Clone, Copy, Debug, PartialEq, Eq)]
340pub enum H265SliceType {
341	B,
342	P,
343	I,
344}
345
346/// Parsed H.265 slice fields required by picture submission and DPB updates.
347#[derive(Clone, Debug, PartialEq, Eq)]
348pub struct H265SliceHeader {
349	pub picture_parameter_set_id: u32,
350	pub sequence_parameter_set_id: u32,
351	pub video_parameter_set_id: u32,
352	pub slice_type: H265SliceType,
353	pub slice_segment_address: u32,
354	pub picture_order_count_lsb: Option<u32>,
355	pub short_term_reference_picture_set_sps: bool,
356	pub short_term_reference_picture_set_index: Option<u32>,
357	pub short_term_reference_picture_set_bits: u16,
358	pub short_term_current_before_delta_pocs: Vec<i32>,
359	pub short_term_current_after_delta_pocs: Vec<i32>,
360	pub short_term_following_delta_pocs: Vec<i32>,
361	pub nal_unit_type: u8,
362	pub temporal_id: u8,
363	pub first_slice_segment_in_picture: bool,
364	pub is_irap: bool,
365	pub is_idr: bool,
366	pub no_output_of_prior_pictures: bool,
367	pub is_reference: bool,
368	pub picture_output: bool,
369	pub colour_plane_id: Option<u8>,
370}
371
372/// Parse one raw H.265 VPS NAL unit without an Annex-B start code.
373pub fn parse_h265_vps(nal: &[u8]) -> Result<H265VideoParameterSet> {
374	validate_nal(nal, 32, "VPS")?;
375	let rbsp = remove_emulation_prevention(nal);
376	let mut bits = BitReader::new(&rbsp);
377	bits.skip_bits(16)?;
378	let id = bits.read_bits(4)?;
379	bits.skip_bits(8)?;
380	let max_sub_layers_minus_1 = bits.read_bits(3)?;
381	validate_sub_layers(max_sub_layers_minus_1)?;
382	let temporal_id_nesting = bits.read_bits(1)? != 0;
383	bits.skip_bits(16)?;
384	let profile_tier_level = read_profile_tier_level(&mut bits, max_sub_layers_minus_1)?;
385	let sub_layer_ordering_info_present = bits.read_bits(1)? != 0;
386	let decoded_picture_buffer = parse_decoded_picture_buffer(
387		&mut bits,
388		max_sub_layers_minus_1,
389		sub_layer_ordering_info_present,
390	)?;
391	let max_layer_id = bits.read_bits(6)? as u8;
392	let num_layer_sets_minus_1 = bits.read_ue()?;
393	if num_layer_sets_minus_1 > 1023 {
394		return Err(Error::data_loss("H.265 VPS layer-set count exceeds 1024"));
395	}
396	let mut layer_id_included = Vec::new();
397	for _ in 0..num_layer_sets_minus_1 {
398		let mut layer_set = Vec::with_capacity(usize::from(max_layer_id) + 1);
399		for _ in 0..=max_layer_id {
400			layer_set.push(bits.read_bits(1)? != 0);
401		}
402		layer_id_included.push(layer_set);
403	}
404	let timing = if bits.read_bits(1)? != 0 {
405		Some(parse_h265_timing(&mut bits)?)
406	} else {
407		None
408	};
409	let mut hrd_parameters = Vec::new();
410	if timing.is_some() {
411		let count = bits.read_ue()?;
412		if count > 1024 {
413			return Err(Error::data_loss("H.265 VPS HRD count exceeds 1024"));
414		}
415		for index in 0..count {
416			let layer_set_index = bits.read_ue()?;
417			if layer_set_index > num_layer_sets_minus_1 {
418				return Err(Error::data_loss(
419					"H.265 VPS HRD references an absent layer set",
420				));
421			}
422			let common_present = index == 0 || bits.read_bits(1)? != 0;
423			let inherited = hrd_parameters
424				.last()
425				.map(|previous: &H265VpsHrdParameters| &previous.parameters);
426			hrd_parameters.push(H265VpsHrdParameters {
427				layer_set_index,
428				parameters: parse_h265_hrd(&mut bits, common_present, max_sub_layers_minus_1, inherited)?,
429			});
430		}
431	}
432	if bits.read_bits(1)? != 0 {
433		return Err(Error::missing_capability(
434			"H.265 multi-layer VPS extensions are not supported",
435		));
436	}
437	Ok(H265VideoParameterSet {
438		id,
439		max_sub_layers_minus_1,
440		temporal_id_nesting,
441		profile_tier_level,
442		sub_layer_ordering_info_present,
443		decoded_picture_buffer,
444		max_layer_id,
445		layer_id_included,
446		timing,
447		hrd_parameters,
448	})
449}
450
451/// Parse one raw H.265 SPS NAL unit without an Annex-B start code.
452pub fn parse_h265_sps(nal: &[u8]) -> Result<H265SequenceParameterSet> {
453	validate_nal(nal, 33, "SPS")?;
454	let rbsp = remove_emulation_prevention(nal);
455	let mut bits = BitReader::new(&rbsp);
456	bits.skip_bits(16)?;
457	let video_parameter_set_id = bits.read_bits(4)?;
458	let max_sub_layers_minus_1 = bits.read_bits(3)?;
459	validate_sub_layers(max_sub_layers_minus_1)?;
460	let temporal_id_nesting = bits.read_bits(1)? != 0;
461	let profile_tier_level = read_profile_tier_level(&mut bits, max_sub_layers_minus_1)?;
462	let id = bits.read_ue()?;
463	if id > 15 {
464		return Err(Error::data_loss("H.265 SPS identifier exceeds 15"));
465	}
466	let chroma_format_idc = bits.read_ue()?;
467	if chroma_format_idc > 3 {
468		return Err(Error::data_loss("H.265 SPS chroma format exceeds 3"));
469	}
470	let separate_colour_plane = chroma_format_idc == 3 && bits.read_bits(1)? != 0;
471	let coded_width = bits.read_ue()?;
472	let coded_height = bits.read_ue()?;
473	if coded_width == 0 || coded_height == 0 {
474		return Err(Error::data_loss("H.265 SPS has zero coded extent"));
475	}
476	let mut width = coded_width;
477	let mut height = coded_height;
478	let mut conformance_window = [0; 4];
479	if bits.read_bits(1)? != 0 {
480		for value in &mut conformance_window {
481			*value = bits.read_ue()?;
482		}
483		let (crop_unit_x, crop_unit_y) = match chroma_format_idc {
484			0 | 3 => (1, 1),
485			1 => (2, 2),
486			2 => (2, 1),
487			_ => unreachable!(),
488		};
489		let crop_width = conformance_window[0]
490			.checked_add(conformance_window[1])
491			.and_then(|value| value.checked_mul(crop_unit_x))
492			.ok_or_else(|| Error::data_loss("H.265 conformance width overflows"))?;
493		let crop_height = conformance_window[2]
494			.checked_add(conformance_window[3])
495			.and_then(|value| value.checked_mul(crop_unit_y))
496			.ok_or_else(|| Error::data_loss("H.265 conformance height overflows"))?;
497		width = width
498			.checked_sub(crop_width)
499			.ok_or_else(|| Error::data_loss("H.265 crop exceeds coded width"))?;
500		height = height
501			.checked_sub(crop_height)
502			.ok_or_else(|| Error::data_loss("H.265 crop exceeds coded height"))?;
503	}
504	let bit_depth_luma_minus_8 = bits.read_ue()?;
505	let bit_depth_chroma_minus_8 = bits.read_ue()?;
506	let log2_max_pic_order_count_lsb_minus_4 = bits.read_ue()?;
507	let sub_layer_ordering_info_present = bits.read_bits(1)? != 0;
508	let decoded_picture_buffer = parse_decoded_picture_buffer(
509		&mut bits,
510		max_sub_layers_minus_1,
511		sub_layer_ordering_info_present,
512	)?;
513	let H265DecodedPictureBuffer {
514		max_decoded_picture_buffering_minus_1,
515		max_num_reorder_pictures,
516		max_latency_increase_plus_1,
517	} = decoded_picture_buffer;
518	let log2_min_luma_coding_block_size_minus_3 = bits.read_ue()?;
519	let log2_diff_max_min_luma_coding_block_size = bits.read_ue()?;
520	let log2_min_luma_transform_block_size_minus_2 = bits.read_ue()?;
521	let log2_diff_max_min_luma_transform_block_size = bits.read_ue()?;
522	let max_transform_hierarchy_depth_inter = bits.read_ue()?;
523	let max_transform_hierarchy_depth_intra = bits.read_ue()?;
524	let scaling_list_enabled = bits.read_bits(1)? != 0;
525	let scaling_list_data_present = scaling_list_enabled && bits.read_bits(1)? != 0;
526	let scaling_lists = scaling_list_data_present
527		.then(|| parse_h265_scaling_lists(&mut bits))
528		.transpose()?;
529	let asymmetric_motion_partitions_enabled = bits.read_bits(1)? != 0;
530	let sample_adaptive_offset_enabled = bits.read_bits(1)? != 0;
531	let pcm = if bits.read_bits(1)? != 0 {
532		Some(H265PcmParameters {
533			sample_bit_depth_luma_minus_1: bits.read_bits(4)? as u8,
534			sample_bit_depth_chroma_minus_1: bits.read_bits(4)? as u8,
535			log2_min_luma_coding_block_size_minus_3: bits.read_ue()?,
536			log2_diff_max_min_luma_coding_block_size: bits.read_ue()?,
537			loop_filter_disabled: bits.read_bits(1)? != 0,
538		})
539	} else {
540		None
541	};
542	let num_short_term_reference_picture_sets = bits.read_ue()?;
543	let count = num_short_term_reference_picture_sets as usize;
544	if count > MAX_SHORT_TERM_REFERENCE_SETS {
545		return Err(Error::data_loss(
546			"H.265 short-term RPS count exceeds safety bound",
547		));
548	}
549	let mut short_term_reference_picture_sets = Vec::new();
550	short_term_reference_picture_sets
551		.try_reserve_exact(count)
552		.map_err(|_| Error::resource_exhausted("H.265 reference-set allocation failed"))?;
553	for index in 0..count {
554		let set =
555			parse_short_term_reference_picture_set(&mut bits, index, &short_term_reference_picture_sets)?;
556		if set.delta_pocs.len()
557			> max_decoded_picture_buffering_minus_1[max_sub_layers_minus_1 as usize] as usize
558		{
559			return Err(Error::data_loss(
560				"H.265 reference set exceeds the SPS decoded-picture buffer",
561			));
562		}
563		short_term_reference_picture_sets.push(set);
564	}
565	let long_term_reference_pictures_present = bits.read_bits(1)? != 0;
566	let mut long_term_reference_pictures = Vec::new();
567	if long_term_reference_pictures_present {
568		let count = bits.read_ue()?;
569		if count > 32 {
570			return Err(Error::data_loss(
571				"H.265 long-term reference count exceeds safety bound",
572			));
573		}
574		long_term_reference_pictures
575			.try_reserve_exact(count as usize)
576			.map_err(|_| Error::resource_exhausted("H.265 long-term reference allocation failed"))?;
577		let poc_bits = log2_max_pic_order_count_lsb_minus_4
578			.checked_add(4)
579			.ok_or_else(|| Error::data_loss("H.265 long-term POC width overflows"))?;
580		if !(4..=32).contains(&poc_bits) {
581			return Err(Error::data_loss(
582				"H.265 long-term POC width is outside 4..=32",
583			));
584		}
585		for _ in 0..count {
586			long_term_reference_pictures.push(H265LongTermReferencePicture {
587				picture_order_count_lsb: bits.read_bits(poc_bits as usize)?,
588				used_by_current: bits.read_bits(1)? != 0,
589			});
590		}
591	}
592	let temporal_mvp_enabled = bits.read_bits(1)? != 0;
593	let strong_intra_smoothing_enabled = bits.read_bits(1)? != 0;
594	let vui = if bits.read_bits(1)? != 0 {
595		Some(parse_h265_vui(&mut bits, max_sub_layers_minus_1)?)
596	} else {
597		None
598	};
599	if bits.read_bits(1)? != 0 {
600		let range_extension = bits.read_bits(1)? != 0;
601		let multilayer_extension = bits.read_bits(1)? != 0;
602		let three_d_extension = bits.read_bits(1)? != 0;
603		let scc_extension = bits.read_bits(1)? != 0;
604		bits.skip_bits(4)?;
605		if range_extension || multilayer_extension || three_d_extension || scc_extension {
606			return Err(Error::missing_capability(
607				"H.265 SPS range, multilayer, 3D, and SCC extensions are not supported",
608			));
609		}
610		while bits.more_rbsp_data() {
611			bits.read_bits(1)?;
612		}
613	}
614	Ok(H265SequenceParameterSet {
615		id,
616		video_parameter_set_id,
617		max_sub_layers_minus_1,
618		profile_tier_level,
619		chroma_format_idc,
620		width,
621		height,
622		coded_width,
623		coded_height,
624		conformance_window,
625		bit_depth_luma_minus_8,
626		bit_depth_chroma_minus_8,
627		log2_max_pic_order_count_lsb_minus_4,
628		log2_min_luma_coding_block_size_minus_3,
629		log2_diff_max_min_luma_coding_block_size,
630		log2_min_luma_transform_block_size_minus_2,
631		log2_diff_max_min_luma_transform_block_size,
632		max_transform_hierarchy_depth_inter,
633		max_transform_hierarchy_depth_intra,
634		short_term_reference_picture_sets,
635		temporal_id_nesting,
636		separate_colour_plane,
637		sub_layer_ordering_info_present,
638		scaling_list_enabled,
639		scaling_lists,
640		asymmetric_motion_partitions_enabled,
641		sample_adaptive_offset_enabled,
642		pcm_enabled: pcm.is_some(),
643		pcm,
644		long_term_reference_pictures,
645		temporal_mvp_enabled,
646		strong_intra_smoothing_enabled,
647		max_decoded_picture_buffering_minus_1,
648		max_num_reorder_pictures,
649		max_latency_increase_plus_1,
650		vui,
651	})
652}
653
654/// Parse one raw H.265 PPS NAL unit without an Annex-B start code.
655pub fn parse_h265_pps(nal: &[u8]) -> Result<H265PictureParameterSet> {
656	validate_nal(nal, 34, "PPS")?;
657	let rbsp = remove_emulation_prevention(nal);
658	let mut bits = BitReader::new(&rbsp);
659	bits.skip_bits(16)?;
660	let id = bits.read_ue()?;
661	let sequence_parameter_set_id = bits.read_ue()?;
662	if id > 63 || sequence_parameter_set_id > 15 {
663		return Err(Error::data_loss("H.265 PPS identifier is out of range"));
664	}
665	let dependent_slice_segments_enabled = bits.read_bits(1)? != 0;
666	let output_flag_present = bits.read_bits(1)? != 0;
667	let num_extra_slice_header_bits = bits.read_bits(3)?;
668	let sign_data_hiding_enabled = bits.read_bits(1)? != 0;
669	let cabac_init_present = bits.read_bits(1)? != 0;
670	let num_ref_idx_l0_default_active_minus_1 = bits.read_ue()?;
671	let num_ref_idx_l1_default_active_minus_1 = bits.read_ue()?;
672	let init_qp_minus_26 = bits.read_se()?;
673	let constrained_intra_pred = bits.read_bits(1)? != 0;
674	let transform_skip_enabled = bits.read_bits(1)? != 0;
675	let cu_qp_delta_enabled = bits.read_bits(1)? != 0;
676	let diff_cu_qp_delta_depth = if cu_qp_delta_enabled {
677		bits.read_ue()?
678	} else {
679		0
680	};
681	let cb_qp_offset = bits.read_se()?;
682	let cr_qp_offset = bits.read_se()?;
683	let slice_chroma_qp_offsets_present = bits.read_bits(1)? != 0;
684	let weighted_pred = bits.read_bits(1)? != 0;
685	let weighted_bipred = bits.read_bits(1)? != 0;
686	let transquant_bypass_enabled = bits.read_bits(1)? != 0;
687	let tiles_enabled = bits.read_bits(1)? != 0;
688	let entropy_coding_sync_enabled = bits.read_bits(1)? != 0;
689	let (mut num_tile_columns_minus_1, mut num_tile_rows_minus_1) = (0, 0);
690	let mut uniform_spacing = true;
691	let mut loop_filter_across_tiles_enabled = false;
692	let mut column_width_minus_1 = Vec::new();
693	let mut row_height_minus_1 = Vec::new();
694	if tiles_enabled {
695		num_tile_columns_minus_1 = bits.read_ue()?;
696		num_tile_rows_minus_1 = bits.read_ue()?;
697		if num_tile_columns_minus_1 > 19 || num_tile_rows_minus_1 > 21 {
698			return Err(Error::data_loss(
699				"H.265 PPS tile count exceeds safety bound",
700			));
701		}
702		uniform_spacing = bits.read_bits(1)? != 0;
703		if !uniform_spacing {
704			for _ in 0..num_tile_columns_minus_1 {
705				column_width_minus_1.push(bits.read_ue()?);
706			}
707			for _ in 0..num_tile_rows_minus_1 {
708				row_height_minus_1.push(bits.read_ue()?);
709			}
710		}
711		loop_filter_across_tiles_enabled = bits.read_bits(1)? != 0;
712	}
713	let loop_filter_across_slices_enabled = bits.read_bits(1)? != 0;
714	let deblocking_filter_control_present = bits.read_bits(1)? != 0;
715	let (mut deblocking_filter_override_enabled, mut deblocking_filter_disabled) = (false, false);
716	let (mut beta_offset_div_2, mut tc_offset_div_2) = (0, 0);
717	if deblocking_filter_control_present {
718		deblocking_filter_override_enabled = bits.read_bits(1)? != 0;
719		deblocking_filter_disabled = bits.read_bits(1)? != 0;
720		if !deblocking_filter_disabled {
721			beta_offset_div_2 = bits.read_se()?;
722			tc_offset_div_2 = bits.read_se()?;
723		}
724	}
725	let scaling_list_data_present = bits.read_bits(1)? != 0;
726	let scaling_lists = scaling_list_data_present
727		.then(|| parse_h265_scaling_lists(&mut bits))
728		.transpose()?;
729	let lists_modification_present = bits.read_bits(1)? != 0;
730	let log2_parallel_merge_level_minus_2 = bits.read_ue()?;
731	let slice_segment_header_extension_present = bits.read_bits(1)? != 0;
732	let extension_present = bits.read_bits(1)? != 0;
733	if extension_present {
734		return Err(Error::missing_capability(
735			"H.265 PPS range, multilayer, 3D, and SCC extensions are not supported",
736		));
737	}
738	Ok(H265PictureParameterSet {
739		id,
740		sequence_parameter_set_id,
741		num_extra_slice_header_bits,
742		num_ref_idx_l0_default_active_minus_1,
743		num_ref_idx_l1_default_active_minus_1,
744		init_qp_minus_26,
745		diff_cu_qp_delta_depth,
746		cb_qp_offset,
747		cr_qp_offset,
748		beta_offset_div_2,
749		tc_offset_div_2,
750		log2_parallel_merge_level_minus_2,
751		num_tile_columns_minus_1,
752		num_tile_rows_minus_1,
753		column_width_minus_1,
754		row_height_minus_1,
755		dependent_slice_segments_enabled,
756		output_flag_present,
757		sign_data_hiding_enabled,
758		cabac_init_present,
759		constrained_intra_pred,
760		transform_skip_enabled,
761		cu_qp_delta_enabled,
762		slice_chroma_qp_offsets_present,
763		weighted_pred,
764		weighted_bipred,
765		transquant_bypass_enabled,
766		tiles_enabled,
767		entropy_coding_sync_enabled,
768		uniform_spacing,
769		loop_filter_across_tiles_enabled,
770		loop_filter_across_slices_enabled,
771		deblocking_filter_control_present,
772		deblocking_filter_override_enabled,
773		deblocking_filter_disabled,
774		scaling_lists,
775		lists_modification_present,
776		slice_segment_header_extension_present,
777		extension_present,
778	})
779}
780
781/// Parse one raw H.265 coded-slice NAL using its resolved SPS and PPS.
782///
783/// Dependent slice segments and inline inter-predicted short-term reference
784/// sets require additional retained state and fail with `MissingCapability`.
785pub fn parse_h265_slice_header(
786	nal: &[u8],
787	sps: &H265SequenceParameterSet,
788	pps: &H265PictureParameterSet,
789) -> Result<H265SliceHeader> {
790	if nal.len() < 2 {
791		return Err(Error::data_loss("truncated H.265 slice NAL"));
792	}
793	let nal_unit_type = (nal[0] >> 1) & 0x3f;
794	let temporal_id_plus_1 = nal[1] & 7;
795	if nal[0] & 0x80 != 0 || nal_unit_type >= 32 || temporal_id_plus_1 == 0 {
796		return Err(Error::invalid_argument(
797			"input is not a valid H.265 coded-slice NAL",
798		));
799	}
800	if pps.sequence_parameter_set_id != sps.id {
801		return Err(Error::invalid_argument(
802			"H.265 PPS does not reference the supplied SPS",
803		));
804	}
805	let rbsp = remove_emulation_prevention(nal);
806	let mut bits = BitReader::new(&rbsp);
807	bits.skip_bits(16)?;
808	let first_slice_segment_in_picture = bits.read_bits(1)? != 0;
809	let is_irap = (16..=23).contains(&nal_unit_type);
810	let is_idr = matches!(nal_unit_type, 19 | 20);
811	let is_reference = is_irap || nal_unit_type & 1 != 0;
812	let no_output_of_prior_pictures = is_irap && bits.read_bits(1)? != 0;
813	let picture_parameter_set_id = bits.read_ue()?;
814	if picture_parameter_set_id != pps.id {
815		return Err(Error::invalid_argument(
816			"H.265 slice references a different PPS",
817		));
818	}
819	let mut slice_segment_address = 0;
820	if !first_slice_segment_in_picture {
821		let dependent = pps.dependent_slice_segments_enabled && bits.read_bits(1)? != 0;
822		let ctb_log2 = sps
823			.log2_min_luma_coding_block_size_minus_3
824			.checked_add(3)
825			.and_then(|value| value.checked_add(sps.log2_diff_max_min_luma_coding_block_size))
826			.ok_or_else(|| Error::data_loss("H.265 CTB exponent overflows"))?;
827		let ctb_size = 1_u32
828			.checked_shl(ctb_log2)
829			.ok_or_else(|| Error::data_loss("H.265 CTB size exceeds u32"))?;
830		let ctb_width = sps
831			.coded_width
832			.checked_add(ctb_size - 1)
833			.ok_or_else(|| Error::data_loss("H.265 CTB width rounds past u32"))?
834			/ ctb_size;
835		let ctb_height = sps
836			.coded_height
837			.checked_add(ctb_size - 1)
838			.ok_or_else(|| Error::data_loss("H.265 CTB height rounds past u32"))?
839			/ ctb_size;
840		let picture_ctbs = ctb_width
841			.checked_mul(ctb_height)
842			.ok_or_else(|| Error::data_loss("H.265 CTB count overflows"))?;
843		let address_bits = ceil_log2(picture_ctbs);
844		slice_segment_address = bits.read_bits(address_bits as usize)?;
845		if dependent {
846			return Err(Error::missing_capability(
847				"H.265 dependent slice segments are not implemented",
848			));
849		}
850	}
851	bits.skip_bits(pps.num_extra_slice_header_bits as usize)?;
852	let slice_type = match bits.read_ue()? {
853		0 => H265SliceType::B,
854		1 => H265SliceType::P,
855		2 => H265SliceType::I,
856		_ => return Err(Error::data_loss("H.265 slice type exceeds 2")),
857	};
858	let picture_output = !pps.output_flag_present || bits.read_bits(1)? != 0;
859	let colour_plane_id = sps
860		.separate_colour_plane
861		.then(|| bits.read_bits(2).map(|value| value as u8))
862		.transpose()?;
863	let mut picture_order_count_lsb = None;
864	let mut short_term_reference_picture_set_sps = false;
865	let mut short_term_reference_picture_set_index = None;
866	let mut short_term_reference_picture_set_bits = 0;
867	let mut short_term_current_before_delta_pocs = Vec::new();
868	let mut short_term_current_after_delta_pocs = Vec::new();
869	let mut short_term_following_delta_pocs = Vec::new();
870	if !is_idr {
871		let poc_bits = sps
872			.log2_max_pic_order_count_lsb_minus_4
873			.checked_add(4)
874			.ok_or_else(|| Error::data_loss("H.265 POC width overflows"))?;
875		if !(4..=32).contains(&poc_bits) {
876			return Err(Error::data_loss("H.265 POC width is outside 4..=32"));
877		}
878		picture_order_count_lsb = Some(bits.read_bits(poc_bits as usize)?);
879		let reference_set_count = u32::try_from(sps.short_term_reference_picture_sets.len())
880			.map_err(|_| Error::data_loss("H.265 SPS reference-set count exceeds u32"))?;
881		// `short_term_ref_pic_set_sps_flag` is present for every non-IDR
882		// picture. A zero SPS-set count only makes its true value invalid; it does
883		// not remove the flag bit from the slice header.
884		short_term_reference_picture_set_sps = bits.read_bits(1)? != 0;
885		if short_term_reference_picture_set_sps {
886			if reference_set_count == 0 {
887				return Err(Error::data_loss(
888					"H.265 slice selects an SPS reference set but the SPS has none",
889				));
890			}
891			let index_bits = ceil_log2(reference_set_count);
892			short_term_reference_picture_set_index = Some(if index_bits == 0 {
893				0
894			} else {
895				bits.read_bits(index_bits as usize)?
896			});
897			if short_term_reference_picture_set_index.is_some_and(|index| index >= reference_set_count) {
898				return Err(Error::data_loss(
899					"H.265 short-term reference-set index is out of range",
900				));
901			}
902		} else {
903			if reference_set_count != 0 {
904				return Err(Error::missing_capability(
905					"H.265 inline inter-predicted short-term reference sets require retained SPS RPS state",
906				));
907			}
908			let start = bits.position();
909			let negative_count = bits.read_ue()?;
910			let positive_count = bits.read_ue()?;
911			if negative_count > 16 || positive_count > 16 {
912				return Err(Error::data_loss(
913					"H.265 inline short-term reference set exceeds 16 entries per direction",
914				));
915			}
916			let mut delta_poc = 0_i32;
917			for _ in 0..negative_count {
918				let delta = i32::try_from(bits.read_ue()?)
919					.map_err(|_| Error::data_loss("H.265 negative delta POC exceeds i32"))?
920					.checked_add(1)
921					.ok_or_else(|| Error::data_loss("H.265 negative delta POC overflows"))?;
922				delta_poc = delta_poc
923					.checked_sub(delta)
924					.ok_or_else(|| Error::data_loss("H.265 negative delta POC sum overflows"))?;
925				if bits.read_bits(1)? != 0 {
926					short_term_current_before_delta_pocs.push(delta_poc);
927				} else {
928					short_term_following_delta_pocs.push(delta_poc);
929				}
930			}
931			delta_poc = 0;
932			for _ in 0..positive_count {
933				let delta = i32::try_from(bits.read_ue()?)
934					.map_err(|_| Error::data_loss("H.265 positive delta POC exceeds i32"))?
935					.checked_add(1)
936					.ok_or_else(|| Error::data_loss("H.265 positive delta POC overflows"))?;
937				delta_poc = delta_poc
938					.checked_add(delta)
939					.ok_or_else(|| Error::data_loss("H.265 positive delta POC sum overflows"))?;
940				if bits.read_bits(1)? != 0 {
941					short_term_current_after_delta_pocs.push(delta_poc);
942				} else {
943					short_term_following_delta_pocs.push(delta_poc);
944				}
945			}
946			short_term_reference_picture_set_bits = u16::try_from(bits.position() - start)
947				.map_err(|_| Error::data_loss("H.265 inline reference set exceeds 65535 bits"))?;
948		}
949	}
950	Ok(H265SliceHeader {
951		picture_parameter_set_id,
952		sequence_parameter_set_id: sps.id,
953		video_parameter_set_id: sps.video_parameter_set_id,
954		slice_type,
955		slice_segment_address,
956		picture_order_count_lsb,
957		short_term_reference_picture_set_sps,
958		short_term_reference_picture_set_index,
959		short_term_reference_picture_set_bits,
960		short_term_current_before_delta_pocs,
961		short_term_current_after_delta_pocs,
962		short_term_following_delta_pocs,
963		nal_unit_type,
964		temporal_id: temporal_id_plus_1 - 1,
965		first_slice_segment_in_picture,
966		is_irap,
967		is_idr,
968		no_output_of_prior_pictures,
969		is_reference,
970		picture_output,
971		colour_plane_id,
972	})
973}
974
975const fn ceil_log2(value: u32) -> u32 {
976	if value <= 1 {
977		0
978	} else {
979		u32::BITS - (value - 1).leading_zeros()
980	}
981}
982
983fn parse_decoded_picture_buffer(
984	bits: &mut BitReader<'_>,
985	max_sub_layers_minus_1: u32,
986	ordering_info_present: bool,
987) -> Result<H265DecodedPictureBuffer> {
988	let start = if ordering_info_present {
989		0
990	} else {
991		max_sub_layers_minus_1 as usize
992	};
993	let mut result = H265DecodedPictureBuffer::default();
994	for index in start..=max_sub_layers_minus_1 as usize {
995		result.max_decoded_picture_buffering_minus_1[index] = bits.read_ue()?;
996		result.max_num_reorder_pictures[index] = bits.read_ue()?;
997		result.max_latency_increase_plus_1[index] = bits.read_ue()?;
998		if result.max_decoded_picture_buffering_minus_1[index] >= 16
999			|| result.max_num_reorder_pictures[index]
1000				> result.max_decoded_picture_buffering_minus_1[index]
1001		{
1002			return Err(Error::data_loss(
1003				"H.265 sub-layer buffering or reorder count exceeds DPB capacity",
1004			));
1005		}
1006	}
1007	if !ordering_info_present {
1008		for index in 0..start {
1009			result.max_decoded_picture_buffering_minus_1[index] =
1010				result.max_decoded_picture_buffering_minus_1[start];
1011			result.max_num_reorder_pictures[index] = result.max_num_reorder_pictures[start];
1012			result.max_latency_increase_plus_1[index] = result.max_latency_increase_plus_1[start];
1013		}
1014	}
1015	Ok(result)
1016}
1017
1018fn parse_h265_timing(bits: &mut BitReader<'_>) -> Result<H265TimingInfo> {
1019	let num_units_in_tick = bits.read_bits(32)?;
1020	let time_scale = bits.read_bits(32)?;
1021	let num_ticks_poc_diff_one_minus_1 = if bits.read_bits(1)? != 0 {
1022		Some(bits.read_ue()?)
1023	} else {
1024		None
1025	};
1026	Ok(H265TimingInfo {
1027		num_units_in_tick,
1028		time_scale,
1029		num_ticks_poc_diff_one_minus_1,
1030	})
1031}
1032
1033fn parse_h265_hrd(
1034	bits: &mut BitReader<'_>,
1035	common_present: bool,
1036	max_sub_layers_minus_1: u32,
1037	inherited: Option<&H265HrdParameters>,
1038) -> Result<H265HrdParameters> {
1039	let mut result = if common_present {
1040		H265HrdParameters::default()
1041	} else {
1042		let mut inherited = inherited
1043			.cloned()
1044			.ok_or_else(|| Error::data_loss("H.265 HRD omits common syntax without a preceding table"))?;
1045		inherited.sub_layers.clear();
1046		inherited
1047	};
1048	if common_present {
1049		result.nal_parameters_present = bits.read_bits(1)? != 0;
1050		result.vcl_parameters_present = bits.read_bits(1)? != 0;
1051		if result.nal_parameters_present || result.vcl_parameters_present {
1052			result.sub_picture_parameters_present = bits.read_bits(1)? != 0;
1053			if result.sub_picture_parameters_present {
1054				result.tick_divisor_minus_2 = bits.read_bits(8)? as u8;
1055				result.du_cpb_removal_delay_increment_length_minus_1 = bits.read_bits(5)? as u8;
1056				result.sub_picture_cpb_parameters_in_picture_timing_sei = bits.read_bits(1)? != 0;
1057				result.dpb_output_delay_du_length_minus_1 = bits.read_bits(5)? as u8;
1058			}
1059			result.bit_rate_scale = bits.read_bits(4)? as u8;
1060			result.cpb_size_scale = bits.read_bits(4)? as u8;
1061			if result.sub_picture_parameters_present {
1062				result.cpb_size_du_scale = bits.read_bits(4)? as u8;
1063			}
1064			result.initial_cpb_removal_delay_length_minus_1 = bits.read_bits(5)? as u8;
1065			result.au_cpb_removal_delay_length_minus_1 = bits.read_bits(5)? as u8;
1066			result.dpb_output_delay_length_minus_1 = bits.read_bits(5)? as u8;
1067		}
1068	}
1069	for _ in 0..=max_sub_layers_minus_1 {
1070		let fixed_picture_rate_general = bits.read_bits(1)? != 0;
1071		let fixed_picture_rate_within_cvs = fixed_picture_rate_general || bits.read_bits(1)? != 0;
1072		let elemental_duration_in_tc_minus_1 = if fixed_picture_rate_within_cvs {
1073			bits.read_ue()?
1074		} else {
1075			0
1076		};
1077		let low_delay = !fixed_picture_rate_within_cvs && bits.read_bits(1)? != 0;
1078		let cpb_count_minus_1 = if low_delay { 0 } else { bits.read_ue()? };
1079		if cpb_count_minus_1 > 31 {
1080			return Err(Error::data_loss("H.265 HRD CPB count exceeds 32"));
1081		}
1082		let nal_entries = if result.nal_parameters_present {
1083			parse_h265_cpb_entries(
1084				bits,
1085				cpb_count_minus_1,
1086				result.sub_picture_parameters_present,
1087			)?
1088		} else {
1089			Vec::new()
1090		};
1091		let vcl_entries = if result.vcl_parameters_present {
1092			parse_h265_cpb_entries(
1093				bits,
1094				cpb_count_minus_1,
1095				result.sub_picture_parameters_present,
1096			)?
1097		} else {
1098			Vec::new()
1099		};
1100		result.sub_layers.push(H265SubLayerHrdParameters {
1101			fixed_picture_rate_general,
1102			fixed_picture_rate_within_cvs,
1103			low_delay,
1104			elemental_duration_in_tc_minus_1,
1105			nal_entries,
1106			vcl_entries,
1107		});
1108	}
1109	Ok(result)
1110}
1111
1112fn parse_h265_cpb_entries(
1113	bits: &mut BitReader<'_>,
1114	cpb_count_minus_1: u32,
1115	sub_picture_parameters_present: bool,
1116) -> Result<Vec<H265CpbEntry>> {
1117	let mut entries = Vec::with_capacity(cpb_count_minus_1 as usize + 1);
1118	for _ in 0..=cpb_count_minus_1 {
1119		let bit_rate_value_minus_1 = bits.read_ue()?;
1120		let cpb_size_value_minus_1 = bits.read_ue()?;
1121		let (cpb_size_du_value_minus_1, bit_rate_du_value_minus_1) = if sub_picture_parameters_present {
1122			(bits.read_ue()?, bits.read_ue()?)
1123		} else {
1124			(0, 0)
1125		};
1126		entries.push(H265CpbEntry {
1127			bit_rate_value_minus_1,
1128			cpb_size_value_minus_1,
1129			cpb_size_du_value_minus_1,
1130			bit_rate_du_value_minus_1,
1131			constant_bit_rate: bits.read_bits(1)? != 0,
1132		});
1133	}
1134	Ok(entries)
1135}
1136
1137fn parse_h265_vui(
1138	bits: &mut BitReader<'_>,
1139	max_sub_layers_minus_1: u32,
1140) -> Result<H265VuiParameters> {
1141	let aspect_ratio = if bits.read_bits(1)? != 0 {
1142		let idc = bits.read_bits(8)? as u8;
1143		let (sar_width, sar_height) = if idc == 255 {
1144			(bits.read_bits(16)? as u16, bits.read_bits(16)? as u16)
1145		} else {
1146			(0, 0)
1147		};
1148		Some(H265AspectRatio {
1149			idc,
1150			sar_width,
1151			sar_height,
1152		})
1153	} else {
1154		None
1155	};
1156	let overscan_appropriate = if bits.read_bits(1)? != 0 {
1157		Some(bits.read_bits(1)? != 0)
1158	} else {
1159		None
1160	};
1161	let video_signal = if bits.read_bits(1)? != 0 {
1162		let video_format = bits.read_bits(3)? as u8;
1163		let full_range = bits.read_bits(1)? != 0;
1164		let colour_description = if bits.read_bits(1)? != 0 {
1165			Some(H265ColourDescription {
1166				colour_primaries: bits.read_bits(8)? as u8,
1167				transfer_characteristics: bits.read_bits(8)? as u8,
1168				matrix_coefficients: bits.read_bits(8)? as u8,
1169			})
1170		} else {
1171			None
1172		};
1173		Some(H265VideoSignal {
1174			video_format,
1175			full_range,
1176			colour_description,
1177		})
1178	} else {
1179		None
1180	};
1181	let chroma_location = if bits.read_bits(1)? != 0 {
1182		Some(H265ChromaLocation {
1183			top_field: bits.read_ue()?,
1184			bottom_field: bits.read_ue()?,
1185		})
1186	} else {
1187		None
1188	};
1189	let neutral_chroma_indication = bits.read_bits(1)? != 0;
1190	let field_sequence = bits.read_bits(1)? != 0;
1191	let frame_field_info_present = bits.read_bits(1)? != 0;
1192	let default_display_window = if bits.read_bits(1)? != 0 {
1193		Some([
1194			bits.read_ue()?,
1195			bits.read_ue()?,
1196			bits.read_ue()?,
1197			bits.read_ue()?,
1198		])
1199	} else {
1200		None
1201	};
1202	let timing = if bits.read_bits(1)? != 0 {
1203		Some(parse_h265_timing(bits)?)
1204	} else {
1205		None
1206	};
1207	let hrd = if timing.is_some() && bits.read_bits(1)? != 0 {
1208		Some(parse_h265_hrd(bits, true, max_sub_layers_minus_1, None)?)
1209	} else {
1210		None
1211	};
1212	let bitstream_restriction = if bits.read_bits(1)? != 0 {
1213		Some(H265BitstreamRestriction {
1214			tiles_fixed_structure: bits.read_bits(1)? != 0,
1215			motion_vectors_over_picture_boundaries: bits.read_bits(1)? != 0,
1216			restricted_reference_picture_lists: bits.read_bits(1)? != 0,
1217			min_spatial_segmentation_idc: bits.read_ue()?,
1218			max_bytes_per_picture_denom: bits.read_ue()?,
1219			max_bits_per_min_coding_unit_denom: bits.read_ue()?,
1220			log2_max_motion_vector_length_horizontal: bits.read_ue()?,
1221			log2_max_motion_vector_length_vertical: bits.read_ue()?,
1222		})
1223	} else {
1224		None
1225	};
1226	Ok(H265VuiParameters {
1227		aspect_ratio,
1228		overscan_appropriate,
1229		video_signal,
1230		chroma_location,
1231		neutral_chroma_indication,
1232		field_sequence,
1233		frame_field_info_present,
1234		default_display_window,
1235		timing,
1236		hrd,
1237		bitstream_restriction,
1238	})
1239}
1240
1241fn read_profile_tier_level(bits: &mut BitReader<'_>, layers: u32) -> Result<H265ProfileTierLevel> {
1242	bits.skip_bits(2)?;
1243	let high_tier = bits.read_bits(1)? != 0;
1244	let profile_idc = bits.read_bits(5)?;
1245	bits.skip_bits(32)?;
1246	let progressive_source = bits.read_bits(1)? != 0;
1247	let interlaced_source = bits.read_bits(1)? != 0;
1248	let non_packed_constraint = bits.read_bits(1)? != 0;
1249	let frame_only_constraint = bits.read_bits(1)? != 0;
1250	bits.skip_bits(32)?;
1251	bits.skip_bits(12)?;
1252	let level_idc = bits.read_bits(8)?;
1253	let count = layers as usize;
1254	let mut profile_present = [false; 8];
1255	let mut level_present = [false; 8];
1256	for index in 0..count {
1257		profile_present[index] = bits.read_bits(1)? != 0;
1258		level_present[index] = bits.read_bits(1)? != 0;
1259	}
1260	if count > 0 {
1261		for _ in count..8 {
1262			bits.skip_bits(2)?;
1263		}
1264	}
1265	for index in 0..count {
1266		if profile_present[index] {
1267			bits.skip_bits(88)?;
1268		}
1269		if level_present[index] {
1270			bits.skip_bits(8)?;
1271		}
1272	}
1273	Ok(H265ProfileTierLevel {
1274		profile_idc,
1275		level_idc,
1276		high_tier,
1277		progressive_source,
1278		interlaced_source,
1279		non_packed_constraint,
1280		frame_only_constraint,
1281	})
1282}
1283
1284fn parse_h265_scaling_lists(bits: &mut BitReader<'_>) -> Result<H265ScalingLists> {
1285	let mut lists = H265ScalingLists::default();
1286	for size_id in 0..4 {
1287		let matrix_step = if size_id == 3 { 3 } else { 1 };
1288		for matrix_id in (0..6).step_by(matrix_step) {
1289			let dense_matrix_id = matrix_id / matrix_step;
1290			if bits.read_bits(1)? == 0 {
1291				let delta = usize::try_from(bits.read_ue()?)
1292					.map_err(|_| Error::data_loss("H.265 scaling-list predictor delta exceeds usize"))?;
1293				if delta > dense_matrix_id {
1294					return Err(Error::data_loss(
1295						"H.265 scaling-list predictor precedes the first matrix",
1296					));
1297				}
1298				if delta != 0 {
1299					copy_h265_scaling_list(
1300						&mut lists,
1301						size_id,
1302						dense_matrix_id,
1303						dense_matrix_id - delta,
1304					);
1305				}
1306				continue;
1307			}
1308
1309			let mut next_coefficient = 8_u8;
1310			if size_id > 1 {
1311				let dc_minus_8 = bits.read_se()?;
1312				if !(-7..=247).contains(&dc_minus_8) {
1313					return Err(Error::data_loss(
1314						"H.265 scaling-list DC coefficient is outside 1..=255",
1315					));
1316				}
1317				next_coefficient = (dc_minus_8 + 8) as u8;
1318				set_h265_scaling_dc(&mut lists, size_id, dense_matrix_id, next_coefficient);
1319			}
1320			let coefficient_count = if size_id == 0 { 16 } else { 64 };
1321			for coefficient in 0..coefficient_count {
1322				let delta = bits.read_se()?;
1323				next_coefficient = (i64::from(next_coefficient) + i64::from(delta)).rem_euclid(256) as u8;
1324				let position = if size_id == 0 {
1325					4 * H265_DIAGONAL_SCAN_4X4_Y[coefficient] + H265_DIAGONAL_SCAN_4X4_X[coefficient]
1326				} else {
1327					8 * H265_DIAGONAL_SCAN_8X8_Y[coefficient] + H265_DIAGONAL_SCAN_8X8_X[coefficient]
1328				};
1329				set_h265_scaling_value(
1330					&mut lists,
1331					size_id,
1332					dense_matrix_id,
1333					position,
1334					next_coefficient,
1335				);
1336			}
1337		}
1338	}
1339	Ok(lists)
1340}
1341
1342fn copy_h265_scaling_list(
1343	lists: &mut H265ScalingLists,
1344	size_id: usize,
1345	destination: usize,
1346	source: usize,
1347) {
1348	match size_id {
1349		0 => lists.list_4x4[destination] = lists.list_4x4[source],
1350		1 => lists.list_8x8[destination] = lists.list_8x8[source],
1351		2 => {
1352			lists.list_16x16[destination] = lists.list_16x16[source];
1353			lists.dc_16x16[destination] = lists.dc_16x16[source];
1354		}
1355		3 => {
1356			lists.list_32x32[destination] = lists.list_32x32[source];
1357			lists.dc_32x32[destination] = lists.dc_32x32[source];
1358		}
1359		_ => unreachable!(),
1360	}
1361}
1362
1363fn set_h265_scaling_dc(lists: &mut H265ScalingLists, size_id: usize, matrix_id: usize, value: u8) {
1364	match size_id {
1365		2 => lists.dc_16x16[matrix_id] = value,
1366		3 => lists.dc_32x32[matrix_id] = value,
1367		_ => unreachable!(),
1368	}
1369}
1370
1371fn set_h265_scaling_value(
1372	lists: &mut H265ScalingLists,
1373	size_id: usize,
1374	matrix_id: usize,
1375	position: usize,
1376	value: u8,
1377) {
1378	match size_id {
1379		0 => lists.list_4x4[matrix_id][position] = value,
1380		1 => lists.list_8x8[matrix_id][position] = value,
1381		2 => lists.list_16x16[matrix_id][position] = value,
1382		3 => lists.list_32x32[matrix_id][position] = value,
1383		_ => unreachable!(),
1384	}
1385}
1386
1387fn parse_short_term_reference_picture_set(
1388	bits: &mut BitReader<'_>,
1389	index: usize,
1390	previous: &[H265ShortTermReferencePictureSet],
1391) -> Result<H265ShortTermReferencePictureSet> {
1392	let inter_ref_pic_set_prediction = index != 0 && bits.read_bits(1)? != 0;
1393	if inter_ref_pic_set_prediction {
1394		let reference = previous
1395			.get(index - 1)
1396			.ok_or_else(|| Error::data_loss("H.265 predicted reference set has no predecessor"))?;
1397		if reference.delta_pocs.len() >= u32::BITS as usize {
1398			return Err(Error::data_loss(
1399				"H.265 predicted reference set exceeds syntax-mask storage",
1400			));
1401		}
1402		let delta_rps_sign = bits.read_bits(1)? != 0;
1403		let abs_delta_rps_minus_1 = bits.read_ue()?;
1404		if abs_delta_rps_minus_1 > 32_767 {
1405			return Err(Error::data_loss(
1406				"H.265 reference delta exceeds the 15-bit syntax range",
1407			));
1408		}
1409		let delta_rps_magnitude = i32::try_from(abs_delta_rps_minus_1)
1410			.map_err(|_| Error::data_loss("H.265 reference delta exceeds i32"))?
1411			.checked_add(1)
1412			.ok_or_else(|| Error::data_loss("H.265 reference delta overflows"))?;
1413		let delta_rps = if delta_rps_sign {
1414			-delta_rps_magnitude
1415		} else {
1416			delta_rps_magnitude
1417		};
1418		let mut used_by_current_mask = 0_u32;
1419		let mut use_delta_mask = 0_u32;
1420		let mut included = Vec::new();
1421		included
1422			.try_reserve_exact(reference.delta_pocs.len() + 1)
1423			.map_err(|_| Error::resource_exhausted("H.265 predicted reference allocation failed"))?;
1424		for candidate in 0..=reference.delta_pocs.len() {
1425			let used_by_current = bits.read_bits(1)? != 0;
1426			let use_delta = used_by_current || bits.read_bits(1)? != 0;
1427			if used_by_current {
1428				used_by_current_mask |= 1 << candidate;
1429			}
1430			if use_delta {
1431				use_delta_mask |= 1 << candidate;
1432				let reference_delta = reference.delta_pocs.get(candidate).copied().unwrap_or(0);
1433				let delta = delta_rps
1434					.checked_add(reference_delta)
1435					.ok_or_else(|| Error::data_loss("H.265 predicted picture-order delta overflows"))?;
1436				if delta != 0 {
1437					included.push((delta, used_by_current));
1438				}
1439			}
1440		}
1441		included.sort_by_key(|(delta, _)| *delta);
1442		let negative_count = included.partition_point(|(delta, _)| *delta < 0);
1443		included[..negative_count].reverse();
1444		let (used_by_current_negative_mask, used_by_current_positive_mask) =
1445			derived_reference_masks(&included, negative_count);
1446		return Ok(H265ShortTermReferencePictureSet {
1447			inter_ref_pic_set_prediction,
1448			delta_index_minus_1: 0,
1449			delta_rps_sign,
1450			abs_delta_rps_minus_1,
1451			used_by_current_mask,
1452			use_delta_mask,
1453			negative_delta_poc_minus_1: Vec::new(),
1454			positive_delta_poc_minus_1: Vec::new(),
1455			used_by_current_negative_mask,
1456			used_by_current_positive_mask,
1457			delta_pocs: included.into_iter().map(|(delta, _)| delta).collect(),
1458		});
1459	}
1460
1461	let negative_count = usize::try_from(bits.read_ue()?)
1462		.map_err(|_| Error::data_loss("H.265 negative RPS count exceeds usize"))?;
1463	let positive_count = usize::try_from(bits.read_ue()?)
1464		.map_err(|_| Error::data_loss("H.265 positive RPS count exceeds usize"))?;
1465	if negative_count > 16 || positive_count > 16 {
1466		return Err(Error::data_loss(
1467			"H.265 RPS exceeds 16 entries in one direction",
1468		));
1469	}
1470	let total = negative_count
1471		.checked_add(positive_count)
1472		.ok_or_else(|| Error::data_loss("H.265 RPS entry count overflows"))?;
1473	let mut set = H265ShortTermReferencePictureSet::default();
1474	set
1475		.negative_delta_poc_minus_1
1476		.try_reserve_exact(negative_count)
1477		.map_err(|_| Error::resource_exhausted("H.265 negative RPS allocation failed"))?;
1478	set
1479		.positive_delta_poc_minus_1
1480		.try_reserve_exact(positive_count)
1481		.map_err(|_| Error::resource_exhausted("H.265 positive RPS allocation failed"))?;
1482	set
1483		.delta_pocs
1484		.try_reserve_exact(total)
1485		.map_err(|_| Error::resource_exhausted("H.265 RPS delta allocation failed"))?;
1486	let mut delta_poc = 0_i32;
1487	for entry in 0..negative_count {
1488		let delta_minus_1 = bits.read_ue()?;
1489		if delta_minus_1 > 32_767 {
1490			return Err(Error::data_loss(
1491				"H.265 negative RPS delta exceeds the 15-bit syntax range",
1492			));
1493		}
1494		let delta = i32::try_from(delta_minus_1)
1495			.map_err(|_| Error::data_loss("H.265 negative RPS delta exceeds i32"))?
1496			.checked_add(1)
1497			.ok_or_else(|| Error::data_loss("H.265 negative RPS delta overflows"))?;
1498		delta_poc = delta_poc
1499			.checked_sub(delta)
1500			.ok_or_else(|| Error::data_loss("H.265 negative RPS sum overflows"))?;
1501		set.negative_delta_poc_minus_1.push(delta_minus_1);
1502		set.delta_pocs.push(delta_poc);
1503		if bits.read_bits(1)? != 0 {
1504			set.used_by_current_negative_mask |= 1 << entry;
1505		}
1506	}
1507	delta_poc = 0;
1508	for entry in 0..positive_count {
1509		let delta_minus_1 = bits.read_ue()?;
1510		if delta_minus_1 > 32_767 {
1511			return Err(Error::data_loss(
1512				"H.265 positive RPS delta exceeds the 15-bit syntax range",
1513			));
1514		}
1515		let delta = i32::try_from(delta_minus_1)
1516			.map_err(|_| Error::data_loss("H.265 positive RPS delta exceeds i32"))?
1517			.checked_add(1)
1518			.ok_or_else(|| Error::data_loss("H.265 positive RPS delta overflows"))?;
1519		delta_poc = delta_poc
1520			.checked_add(delta)
1521			.ok_or_else(|| Error::data_loss("H.265 positive RPS sum overflows"))?;
1522		set.positive_delta_poc_minus_1.push(delta_minus_1);
1523		set.delta_pocs.push(delta_poc);
1524		if bits.read_bits(1)? != 0 {
1525			set.used_by_current_positive_mask |= 1 << entry;
1526		}
1527	}
1528	Ok(set)
1529}
1530
1531fn derived_reference_masks(included: &[(i32, bool)], negative_count: usize) -> (u32, u32) {
1532	let mut negative = 0_u32;
1533	let mut positive = 0_u32;
1534	for (index, (_, used)) in included.iter().copied().enumerate() {
1535		if !used {
1536			continue;
1537		}
1538		if index < negative_count {
1539			negative |= 1 << index;
1540		} else {
1541			positive |= 1 << (index - negative_count);
1542		}
1543	}
1544	(negative, positive)
1545}
1546
1547fn validate_nal(nal: &[u8], expected_type: u8, label: &str) -> Result<()> {
1548	if nal.len() < 2 {
1549		return Err(Error::data_loss(format!("truncated H.265 {label} NAL")));
1550	}
1551	if nal[0] & 0x80 != 0 || (nal[0] >> 1) & 0x3f != expected_type || nal[1] & 7 == 0 {
1552		return Err(Error::invalid_argument(format!(
1553			"input is not a valid H.265 {label} NAL"
1554		)));
1555	}
1556	Ok(())
1557}
1558
1559fn validate_sub_layers(value: u32) -> Result<()> {
1560	if value >= MAX_SUB_LAYERS as u32 {
1561		return Err(Error::data_loss("H.265 sub-layer count exceeds seven"));
1562	}
1563	Ok(())
1564}