Skip to main content

threers_codec/hevc/
params.rs

1//! HEVC high-level syntax: `profile_tier_level`, VPS, SPS, PPS (H.265 §7.3.2).
2//!
3//! Everything here writes the *minimal conformant* configuration the milestone-3
4//! `I_PCM` encoder needs: Main profile, 8-bit 4:2:0, one layer, no temporal
5//! scalability, in-loop filters (deblocking + SAO) disabled, and PCM enabled
6//! with the CTB size pinned to the min CB size so no `split_cu_flag` is ever
7//! coded (every CTB is a single CU).
8//!
9//! These are pure bit-writers over [`BitWriter`]; the structural round-trip test
10//! parses them back, and the end-to-end test decodes the assembled stream with
11//! an external decoder to confirm conformance.
12
13use crate::bitstream::{rbsp_trailing_bits, BitWriter};
14
15/// Fixed configuration for the minimal PCM encoder. Sizes are luma samples.
16#[derive(Clone, Copy, Debug)]
17pub struct HevcConfig {
18    /// Displayed picture width (any positive value; coded size is padded to a
19    /// multiple of the CTB size and cropped back via the conformance window).
20    pub width: u32,
21    /// Displayed picture height.
22    pub height: u32,
23    /// Coded width, padded up to a multiple of [`CTB_SIZE`].
24    pub coded_width: u32,
25    /// Coded height, padded up to a multiple of [`CTB_SIZE`].
26    pub coded_height: u32,
27    /// `chroma_format_idc`: `1` = 4:2:0 (color), `0` = monochrome (4:0:0). The
28    /// alpha auxiliary layer of a transparent video is monochrome.
29    pub chroma_format_idc: u8,
30    /// `general_level_idc` (level × 30). `180` = 6.0 (roomy default); the
31    /// transparent path matches Apple's reference with `30` (level 1.0).
32    pub level_idc: u8,
33    /// Signal `video_full_range_flag = 1` via a minimal VUI. The alpha auxiliary
34    /// layer needs this so its 0..255 luma is read as full-range opacity rather
35    /// than expanded from limited `[16,235]`.
36    pub full_range: bool,
37    /// Enable I_PCM in the SPS. The lossless PCM path needs it; the compressed
38    /// (transform-coded) path disables it.
39    pub pcm_enabled: bool,
40    /// Slice QP: CABAC context init, and (compressed path) the quantization step.
41    pub qp: i32,
42    /// `max_transform_hierarchy_depth_intra`: how many times an intra CU's
43    /// transform tree may split. `0` pins one transform block per CU; `1` allows
44    /// 16x16 to split into four 8x8.
45    ///
46    /// This is not just a transform-size knob. HEVC does intra prediction *per
47    /// transform block* from already-reconstructed neighbours, so splitting also
48    /// shortens the prediction distance — an 8x8 block predicts from the 8x8
49    /// next to it rather than from the CTB edge 16 samples away.
50    pub max_transform_hierarchy_depth_intra: u32,
51    /// `log2` of the coding-tree-block edge.
52    pub ctb_log2: u32,
53    /// `log2` of the smallest coding block the quadtree may reach. Equal to
54    /// [`HevcConfig::ctb_log2`] means no quadtree: one coding unit per CTB.
55    pub min_cb_log2: u32,
56    /// `log2` of the largest transform block. A coding block bigger than this
57    /// has its transform tree split without signalling it.
58    pub max_tb_log2: u32,
59    /// Tile columns and rows. `(1, 1)` means the picture is one tile, which is
60    /// to say untiled.
61    ///
62    /// Tiles break intra prediction and reset the entropy coder at their edges,
63    /// so each one can be coded independently — and therefore concurrently.
64    /// That costs bitrate in proportion to how much tile boundary the picture
65    /// gains: measured on photographic content, 2x2 at 8K costs 0.7%, 2x2 at 4K
66    /// costs 1.0%, and 4x4 at 4K costs 5.1%. Prefer few large tiles.
67    pub tile_grid: (u32, u32),
68}
69
70/// A tile grid chosen from the picture size alone.
71///
72/// Tiles cost bitrate in proportion to how much boundary the picture gains, so
73/// what matters is keeping each tile large. Measured on photographic content:
74/// tiles of four megapixels or more cost under a tenth of a percent, a 2x2 split
75/// of 1080p costs 0.43%, and splitting 360p four ways costs 5%.
76///
77/// Halving the longer side until a tile is at most four megapixels keeps every
78/// tile close to that, which makes the grid `1x1` up to 1440p, `2x1` at 4K and
79/// `4x2` at 8K. Deriving it from the resolution rather than from the core count
80/// matters: the same input has to encode to the same bytes on every machine.
81pub fn auto_tile_grid(width: u32, height: u32) -> (u32, u32) {
82    const TARGET: u64 = 4_200_000; // ~4 megapixels per tile
83    let (mut c, mut r) = (1u32, 1u32);
84    while u64::from(width / c) * u64::from(height / r) > TARGET && c <= 8 && r <= 8 {
85        if width / c >= height / r {
86            c *= 2;
87        } else {
88            r *= 2;
89        }
90    }
91    (c, r)
92}
93
94/// Default coding-tree-block edge in luma samples. The `I_PCM` path pins the
95/// CTB to the min CB size so the quadtree never splits and each CTB carries
96/// exactly one PCM CU; the compressed path overrides all three sizes via
97/// [`HevcConfig::with_coding_tree`].
98pub const CTB_SIZE: u32 = 16;
99/// `log2` of [`CTB_SIZE`].
100pub const CTB_LOG2: u32 = 4;
101
102impl HevcConfig {
103    /// Build a 4:2:0 (color) config for a `width × height` picture, padding the
104    /// coded size up to whole CTBs.
105    pub fn new(width: u32, height: u32) -> Self {
106        Self::with_chroma(width, height, 1)
107    }
108
109    /// Build a monochrome (4:0:0) config — used for the alpha auxiliary layer.
110    pub fn new_monochrome(width: u32, height: u32) -> Self {
111        Self::with_chroma(width, height, 0)
112    }
113
114    fn with_chroma(width: u32, height: u32, chroma_format_idc: u8) -> Self {
115        let coded_width = width.div_ceil(CTB_SIZE) * CTB_SIZE;
116        let coded_height = height.div_ceil(CTB_SIZE) * CTB_SIZE;
117        Self {
118            width,
119            height,
120            coded_width,
121            coded_height,
122            ctb_log2: CTB_LOG2,
123            min_cb_log2: CTB_LOG2,
124            max_tb_log2: CTB_LOG2,
125            tile_grid: (1, 1),
126            chroma_format_idc,
127            level_idc: 180,
128            full_range: false,
129            pcm_enabled: true,
130            qp: 26,
131            max_transform_hierarchy_depth_intra: 0,
132        }
133    }
134
135    /// Enable/disable I_PCM in the SPS (disable for the compressed path).
136    pub fn with_pcm(mut self, enabled: bool) -> Self {
137        self.pcm_enabled = enabled;
138        self
139    }
140
141    /// Set `max_transform_hierarchy_depth_intra` (see the field).
142    pub fn with_transform_depth(mut self, depth: u32) -> Self {
143        self.max_transform_hierarchy_depth_intra = depth;
144        self
145    }
146
147    /// Set `general_level_idc` (level × 30).
148    pub fn with_level(mut self, level_idc: u8) -> Self {
149        self.level_idc = level_idc;
150        self
151    }
152
153    /// Signal full-range luma/chroma (needed for the alpha auxiliary layer).
154    pub fn with_full_range(mut self, full_range: bool) -> Self {
155        self.full_range = full_range;
156        self
157    }
158
159    /// Whether this picture carries chroma planes.
160    pub fn has_chroma(&self) -> bool {
161        self.chroma_format_idc != 0
162    }
163
164    /// `(SubWidthC, SubHeightC)` — chroma subsampling (1,1 for monochrome; 2,2 for 4:2:0).
165    pub fn sub_wh(&self) -> (u32, u32) {
166        if self.has_chroma() {
167            (2, 2)
168        } else {
169            (1, 1)
170        }
171    }
172
173    /// Total tile count.
174    pub fn tiles(&self) -> u32 {
175        self.tile_grid.0 * self.tile_grid.1
176    }
177
178    /// Split the picture into `cols` x `rows` tiles.
179    ///
180    /// The grid is reduced if needed so every tile is at least 256 luma
181    /// samples wide and 64 tall: the Main profiles' minimum tile size
182    /// (Annex A). A narrower tiling decodes in tolerant decoders but the
183    /// reference decoder rejects it.
184    pub fn with_tiles(mut self, cols: u32, rows: u32) -> Self {
185        self.tile_grid = (cols.max(1), rows.max(1));
186        self.clamp_tiles();
187        self
188    }
189
190    /// Fit `tile_grid` to the minimum tile size at the current CTB size.
191    /// Uniform spacing makes the narrowest column `floor(ctbs / cols)` CTBs.
192    fn clamp_tiles(&mut self) {
193        let ctb = 1u32 << self.ctb_log2;
194        let (nx, ny) = self.ctbs();
195        let max_cols = (nx / 256u32.div_ceil(ctb)).max(1);
196        let max_rows = (ny / 64u32.div_ceil(ctb)).max(1);
197        self.tile_grid = (
198            self.tile_grid.0.min(max_cols),
199            self.tile_grid.1.min(max_rows),
200        );
201    }
202
203    /// Tile the picture only if it is large enough for the tiles to be free.
204    pub fn with_auto_tiles(self) -> Self {
205        let (c, r) = auto_tile_grid(self.coded_width, self.coded_height);
206        self.with_tiles(c, r)
207    }
208
209    /// Number of CTBs across / down the coded picture. The last row and column
210    /// may hang off the edge; the quadtree splits them down to blocks that fit.
211    pub fn ctbs(&self) -> (u32, u32) {
212        let ctb = 1 << self.ctb_log2;
213        (
214            self.coded_width.div_ceil(ctb),
215            self.coded_height.div_ceil(ctb),
216        )
217    }
218
219    /// Set the coding-tree sizes and re-pad the coded picture to whole minimum
220    /// coding blocks — which is all HEVC requires, so a bigger CTB costs no
221    /// extra padding.
222    pub fn with_coding_tree(mut self, ctb_log2: u32, min_cb_log2: u32, max_tb_log2: u32) -> Self {
223        assert!(
224            min_cb_log2 >= 3 && min_cb_log2 <= ctb_log2,
225            "MinCb in [8, CTB]"
226        );
227        assert!((2..=5).contains(&max_tb_log2), "max TB in [4, 32]");
228        self.ctb_log2 = ctb_log2;
229        self.min_cb_log2 = min_cb_log2;
230        self.max_tb_log2 = max_tb_log2;
231        let mcb = 1 << min_cb_log2;
232        self.coded_width = self.width.div_ceil(mcb) * mcb;
233        self.coded_height = self.height.div_ceil(mcb) * mcb;
234        self.clamp_tiles();
235        self
236    }
237
238    /// Whether a conformance window is needed to crop padding back to display size.
239    fn needs_conf_window(&self) -> bool {
240        self.coded_width != self.width || self.coded_height != self.height
241    }
242}
243
244/// `profile_tier_level(1, 0)` — one layer, level 6.0, no sub-layers (H.265 §7.3.3).
245///
246/// 96 bits total: 88 bits of profile info + an 8-bit level. `monochrome` selects
247/// the Range-Extensions **Monochrome** profile (`profile_idc = 4` with the
248/// 4:0:0 constraint flags) instead of **Main** (`profile_idc = 1`).
249fn profile_tier_level(w: &mut BitWriter, monochrome: bool, level_idc: u8) {
250    w.write_bits(0, 2); // general_profile_space
251    w.flag(false); // general_tier_flag (Main tier)
252    let profile_idc: u32 = if monochrome { 4 } else { 1 };
253    w.write_bits(profile_idc, 5); // general_profile_idc
254
255    // general_profile_compatibility_flag[32]: the bit for this profile_idc.
256    for j in 0..32u32 {
257        w.flag(j == profile_idc);
258    }
259
260    w.flag(true); // general_progressive_source_flag
261    w.flag(false); // general_interlaced_source_flag
262    w.flag(false); // general_non_packed_constraint_flag
263    w.flag(true); // general_frame_only_constraint_flag
264
265    if monochrome {
266        // Range-Extensions constraint flags for profile_idc 4 (§7.3.3).
267        w.flag(true); // general_max_12bit_constraint_flag
268        w.flag(true); // general_max_10bit_constraint_flag
269        w.flag(true); // general_max_8bit_constraint_flag
270        w.flag(true); // general_max_422chroma_constraint_flag
271        w.flag(true); // general_max_420chroma_constraint_flag
272        w.flag(true); // general_max_monochrome_constraint_flag
273        w.flag(false); // general_intra_constraint_flag
274        w.flag(false); // general_one_picture_only_constraint_flag
275        w.flag(true); // general_lower_bit_rate_constraint_flag
276        w.write_bits(0, 34 - 32); // general_reserved_zero_34bits (upper 2)
277        w.write_bits(0, 32); //                                  (lower 32)
278        w.flag(false); // general_inbld_flag
279    } else {
280        // Main profile: 43 reserved-zero bits + 1 reserved/inbld bit.
281        w.write_bits(0, 43 - 32);
282        w.write_bits(0, 32);
283        w.flag(false); // general_inbld_flag
284    }
285
286    w.write_bits(level_idc as u32, 8); // general_level_idc
287}
288
289/// Sub-layer ordering info (single sub-layer): DPB sizing (H.265 §7.3.2.2/2.1).
290fn sub_layer_ordering(w: &mut BitWriter) {
291    w.flag(false); // *_sub_layer_ordering_info_present_flag = 0
292                   // One iteration (i = max_sub_layers_minus1 = 0).
293    w.write_ue(1); // max_dec_pic_buffering_minus1 = 1 (DPB holds 2)
294    w.write_ue(0); // max_num_reorder_pics = 0
295    w.write_ue(0); // max_latency_increase_plus1 = 0
296}
297
298/// Video Parameter Set RBSP (H.265 §7.3.2.1). Byte-aligned, includes trailing bits.
299///
300/// `monochrome` selects the profile advertised in the VPS's `profile_tier_level`
301/// (kept consistent with the SPS).
302pub fn write_vps(monochrome: bool) -> Vec<u8> {
303    let mut w = BitWriter::new();
304    w.write_bits(0, 4); // vps_video_parameter_set_id
305    w.flag(true); // vps_base_layer_internal_flag
306    w.flag(true); // vps_base_layer_available_flag
307    w.write_bits(0, 6); // vps_max_layers_minus1
308    w.write_bits(0, 3); // vps_max_sub_layers_minus1
309    w.flag(true); // vps_temporal_id_nesting_flag
310    w.write_bits(0xFFFF, 16); // vps_reserved_0xffff_16bits
311    profile_tier_level(&mut w, monochrome, 180);
312    sub_layer_ordering(&mut w);
313    w.write_bits(0, 6); // vps_max_layer_id
314    w.write_ue(0); // vps_num_layer_sets_minus1
315    w.flag(false); // vps_timing_info_present_flag
316    w.flag(false); // vps_extension_flag
317    rbsp_trailing_bits(&mut w);
318    w.finish()
319}
320
321/// Sequence Parameter Set RBSP with `sps_seq_parameter_set_id = 0` (H.265 §7.3.2.2).
322pub fn write_sps(cfg: &HevcConfig) -> Vec<u8> {
323    write_sps_id(cfg, 0)
324}
325
326/// Sequence Parameter Set RBSP with an explicit `sps_seq_parameter_set_id` — the
327/// alpha auxiliary layer uses id 1 alongside the base layer's id 0.
328pub fn write_sps_id(cfg: &HevcConfig, sps_id: u32) -> Vec<u8> {
329    let mut w = BitWriter::new();
330    w.write_bits(0, 4); // sps_video_parameter_set_id
331    w.write_bits(0, 3); // sps_max_sub_layers_minus1
332    w.flag(true); // sps_temporal_id_nesting_flag
333    profile_tier_level(&mut w, !cfg.has_chroma(), cfg.level_idc);
334    w.write_ue(sps_id); // sps_seq_parameter_set_id
335    w.write_ue(cfg.chroma_format_idc as u32); // chroma_format_idc (0 mono, 1 4:2:0)
336    w.write_ue(cfg.coded_width); // pic_width_in_luma_samples
337    w.write_ue(cfg.coded_height); // pic_height_in_luma_samples
338
339    if cfg.needs_conf_window() {
340        w.flag(true); // conformance_window_flag
341                      // Offsets are in units of SubWidthC/SubHeightC (1 mono, 2 for 4:2:0).
342        let (subw, subh) = cfg.sub_wh();
343        w.write_ue(0); // conf_win_left_offset
344        w.write_ue((cfg.coded_width - cfg.width) / subw); // conf_win_right_offset
345        w.write_ue(0); // conf_win_top_offset
346        w.write_ue((cfg.coded_height - cfg.height) / subh); // conf_win_bottom_offset
347    } else {
348        w.flag(false); // conformance_window_flag
349    }
350
351    w.write_ue(0); // bit_depth_luma_minus8
352    w.write_ue(0); // bit_depth_chroma_minus8
353    w.write_ue(0); // log2_max_pic_order_cnt_lsb_minus4 (POC lsb = 4 bits)
354    sub_layer_ordering(&mut w);
355
356    w.write_ue(cfg.min_cb_log2 - 3); // log2_min_luma_coding_block_size_minus3
357    w.write_ue(cfg.ctb_log2 - cfg.min_cb_log2); // log2_diff_max_min_luma_coding_block_size
358    w.write_ue(0); // log2_min_luma_transform_block_size_minus2 (minTU = 4)
359    w.write_ue(cfg.max_tb_log2 - 2); // log2_diff_max_min_luma_transform_block_size
360    w.write_ue(0); // max_transform_hierarchy_depth_inter
361    w.write_ue(cfg.max_transform_hierarchy_depth_intra); // max_transform_hierarchy_depth_intra
362    w.flag(false); // scaling_list_enabled_flag
363    w.flag(false); // amp_enabled_flag
364    w.flag(false); // sample_adaptive_offset_enabled_flag
365
366    w.flag(cfg.pcm_enabled); // pcm_enabled_flag
367    if cfg.pcm_enabled {
368        w.write_bits(7, 4); // pcm_sample_bit_depth_luma_minus1 = 7 (8-bit)
369        w.write_bits(7, 4); // pcm_sample_bit_depth_chroma_minus1 = 7
370        w.write_ue(cfg.min_cb_log2 - 3); // log2_min_pcm_luma_coding_block_size_minus3
371        w.write_ue(0); // log2_diff_max_min_pcm_luma_coding_block_size (IPCM max = min)
372        w.flag(true); // pcm_loop_filter_disabled_flag
373    }
374
375    w.write_ue(0); // num_short_term_ref_pic_sets
376    w.flag(false); // long_term_ref_pics_present_flag
377    w.flag(false); // sps_temporal_mvp_enabled_flag
378    w.flag(false); // strong_intra_smoothing_enabled_flag
379                   // Minimal VUI (§E.2.1). A full-range picture is the alpha auxiliary
380                   // layer, which carries opacity, not colour: only the range is signalled.
381                   // Anything else is colour from `Yuv420Frame::from_rgba`, BT.601 limited
382                   // range — said so, or players assume BT.709 for HD and shift the colours.
383    w.flag(true); // vui_parameters_present_flag
384    w.flag(false); // aspect_ratio_info_present_flag
385    w.flag(false); // overscan_info_present_flag
386    w.flag(true); // video_signal_type_present_flag
387    w.write_bits(5, 3); // video_format = 5 (unspecified)
388    w.flag(cfg.full_range); // video_full_range_flag
389    w.flag(!cfg.full_range); // colour_description_present_flag
390    if !cfg.full_range {
391        w.write_byte(2); // colour_primaries: unspecified
392        w.write_byte(2); // transfer_characteristics: unspecified
393        w.write_byte(6); // matrix_coeffs: BT.601 (SMPTE 170M)
394    }
395    w.flag(false); // chroma_loc_info_present_flag
396    w.flag(false); // neutral_chroma_indication_flag
397    w.flag(false); // field_seq_flag
398    w.flag(false); // frame_field_info_present_flag
399    w.flag(false); // default_display_window_flag
400    w.flag(false); // vui_timing_info_present_flag
401    w.flag(false); // bitstream_restriction_flag
402    w.flag(false); // sps_extension_present_flag
403    rbsp_trailing_bits(&mut w);
404    w.finish()
405}
406
407/// Picture Parameter Set RBSP (H.265 §7.3.2.3). Byte-aligned, includes trailing bits.
408///
409/// Deblocking is disabled here (via `deblocking_filter_control_present_flag = 1`,
410/// `pps_deblocking_filter_disabled_flag = 1`) and SAO is off in the SPS, so PCM
411/// samples reach the output untouched — losslessly.
412pub fn write_pps() -> Vec<u8> {
413    write_pps_ids(0, 0)
414}
415
416/// PPS 0 with `cu_qp_delta_enabled_flag` set and a quantization group the size
417/// of a whole coding tree block (`diff_cu_qp_delta_depth = 0`).
418///
419/// At that granularity both quantizer-prediction neighbours always fall in the
420/// *previous* CTB, so §8.6.1's `qPY_A`/`qPY_B` both collapse to `qPY_PREV` and
421/// the predictor is simply the last coded QP. It is also the granularity a rate
422/// controller wants, which is the other thing per-block QP is for.
423pub fn write_pps_cu_qp_delta() -> Vec<u8> {
424    write_pps_inner(0, 0, true, true)
425}
426
427/// As [`write_pps_cu_qp_delta`], with the deblocking filter switched off.
428pub fn write_pps_cu_qp_delta_no_deblock() -> Vec<u8> {
429    write_pps_inner(0, 0, true, false)
430}
431
432/// Picture Parameter Set RBSP with explicit ids (H.265 §7.3.2.3). The alpha
433/// auxiliary layer uses `pps_id = 1`, `sps_id = 1`.
434pub fn write_pps_ids(pps_id: u32, sps_id: u32) -> Vec<u8> {
435    write_pps_inner(pps_id, sps_id, false, false)
436}
437
438fn write_pps_inner(pps_id: u32, sps_id: u32, cu_qp_delta: bool, deblock: bool) -> Vec<u8> {
439    write_pps_full(pps_id, sps_id, cu_qp_delta, deblock, (1, 1))
440}
441
442/// PPS 0 with `cu_qp_delta` and a tile grid, deblocking on or off.
443///
444/// The flag has to follow the encoder's: its reconstruction is deblocked or
445/// not by its own setting, and a PPS that disagreed would decode to
446/// something else.
447pub fn write_pps_tiled(tile_grid: (u32, u32), deblock: bool) -> Vec<u8> {
448    write_pps_full(0, 0, true, deblock, tile_grid)
449}
450
451fn write_pps_full(
452    pps_id: u32,
453    sps_id: u32,
454    cu_qp_delta: bool,
455    deblock: bool,
456    tile_grid: (u32, u32),
457) -> Vec<u8> {
458    let mut w = BitWriter::new();
459    w.write_ue(pps_id); // pps_pic_parameter_set_id
460    w.write_ue(sps_id); // pps_seq_parameter_set_id
461    w.flag(false); // dependent_slice_segments_enabled_flag
462    w.flag(false); // output_flag_present_flag
463    w.write_bits(0, 3); // num_extra_slice_header_bits
464    w.flag(false); // sign_data_hiding_enabled_flag
465    w.flag(false); // cabac_init_present_flag
466    w.write_ue(0); // num_ref_idx_l0_default_active_minus1
467    w.write_ue(0); // num_ref_idx_l1_default_active_minus1
468    w.write_se(0); // init_qp_minus26
469    w.flag(false); // constrained_intra_pred_flag
470    w.flag(false); // transform_skip_enabled_flag
471    w.flag(cu_qp_delta); // cu_qp_delta_enabled_flag
472    if cu_qp_delta {
473        w.write_ue(0); // diff_cu_qp_delta_depth — quantization group = CTB
474    }
475    w.write_se(0); // pps_cb_qp_offset
476    w.write_se(0); // pps_cr_qp_offset
477    w.flag(false); // pps_slice_chroma_qp_offsets_present_flag
478    w.flag(false); // weighted_pred_flag
479    w.flag(false); // weighted_bipred_flag
480    w.flag(false); // transquant_bypass_enabled_flag
481    let tiled = tile_grid.0 * tile_grid.1 > 1;
482    w.flag(tiled); // tiles_enabled_flag
483    w.flag(false); // entropy_coding_sync_enabled_flag
484    if tiled {
485        w.write_ue(tile_grid.0 - 1); // num_tile_columns_minus1
486        w.write_ue(tile_grid.1 - 1); // num_tile_rows_minus1
487        w.flag(true); // uniform_spacing_flag
488                      // Deblocking still runs across tile edges. The filter is a picture-level
489                      // pass here — intra prediction reads unfiltered samples — so letting it
490                      // cross costs nothing and removes the seams tiling would otherwise leave.
491        w.flag(true); // loop_filter_across_tiles_enabled_flag
492    }
493    w.flag(false); // pps_loop_filter_across_slices_enabled_flag
494    w.flag(true); // deblocking_filter_control_present_flag
495    w.flag(false); // deblocking_filter_override_enabled_flag
496    w.flag(!deblock); // pps_deblocking_filter_disabled_flag
497    if deblock {
498        w.write_se(0); // pps_beta_offset_div2
499        w.write_se(0); // pps_tc_offset_div2
500    }
501    w.flag(false); // pps_scaling_list_data_present_flag
502    w.flag(false); // lists_modification_present_flag
503    w.write_ue(0); // log2_parallel_merge_level_minus2
504    w.flag(false); // slice_segment_header_extension_present_flag
505    w.flag(false); // pps_extension_present_flag
506    rbsp_trailing_bits(&mut w);
507    w.finish()
508}
509
510#[cfg(test)]
511mod tests {
512    use super::*;
513
514    #[test]
515    fn config_pads_to_ctb() {
516        let c = HevcConfig::new(1920, 1080);
517        assert_eq!(c.coded_width, 1920); // already aligned
518        assert_eq!(c.coded_height, 1088); // 1080 → 1088
519        assert_eq!(c.ctbs(), (120, 68));
520        assert!(c.needs_conf_window());
521
522        let a = HevcConfig::new(64, 64);
523        assert_eq!((a.coded_width, a.coded_height), (64, 64));
524        assert!(!a.needs_conf_window());
525    }
526
527    #[test]
528    fn param_sets_are_byte_aligned_and_nonempty() {
529        assert!(!write_vps(false).is_empty());
530        assert!(!write_sps(&HevcConfig::new(64, 64)).is_empty());
531        assert!(!write_pps().is_empty());
532    }
533
534    #[test]
535    fn monochrome_config_and_sps() {
536        let c = HevcConfig::new_monochrome(64, 64);
537        assert_eq!(c.chroma_format_idc, 0);
538        assert!(!c.has_chroma());
539        assert_eq!(c.sub_wh(), (1, 1));
540        // SPS still 12-byte PTL + fields; just check it builds non-empty.
541        assert!(!write_sps(&c).is_empty());
542        assert!(!write_vps(true).is_empty());
543    }
544}