Skip to main content

threers_codec/decode/hevc/
params.rs

1//! HEVC parameter sets and the slice segment header (H.265 §7.3.2, §7.3.6).
2
3use super::tables::{DEFAULT_SCALING, SCAN4, SCAN8X8};
4use crate::decode::bits::BitReader;
5use crate::decode::picture::check_picture_size;
6
7pub type Result<T> = std::result::Result<T, String>;
8
9fn ceil_log2(v: u32) -> u32 {
10    if v <= 1 {
11        0
12    } else {
13        32 - (v - 1).leading_zeros()
14    }
15}
16
17/// Scaling factors per `sizeId` (4, 8, 16, 32) and `matrixId` (`cIdx` +
18/// 3 for inter), expanded to raster order at full block size.
19#[derive(Clone, Debug)]
20pub struct ScalingFactors {
21    /// `[sizeId][matrixId]`, `n * n` entries in raster order (`y * n + x`).
22    pub m: [[Vec<u8>; 6]; 4],
23}
24
25/// Coded scaling lists, before expansion: per `sizeId`/`matrixId` the up to
26/// 64 coefficients in diagonal order, and the DC for 16×16 and 32×32.
27#[derive(Clone, Debug)]
28struct ScalingLists {
29    lists: [[[u8; 64]; 6]; 4],
30    dc: [[u8; 6]; 4],
31}
32
33impl ScalingLists {
34    fn default_lists() -> Self {
35        let mut s = ScalingLists {
36            lists: [[[16; 64]; 6]; 4],
37            dc: [[16; 6]; 4],
38        };
39        for size in 1..4 {
40            for m in 0..6 {
41                s.lists[size][m] = DEFAULT_SCALING[(m >= 3) as usize];
42            }
43        }
44        s
45    }
46
47    fn parse(r: &mut BitReader) -> Result<Self> {
48        let mut s = Self::default_lists();
49        for size in 0..4 {
50            let step = if size == 3 { 3 } else { 1 };
51            let mut m = 0;
52            while m < 6 {
53                if !r.flag() {
54                    let delta = r.ue() as usize;
55                    if delta != 0 {
56                        let d = delta * step;
57                        if d > m {
58                            return Err("scaling_list_pred_matrix_id_delta out of range".into());
59                        }
60                        let rm = m - d;
61                        s.lists[size][m] = s.lists[size][rm];
62                        s.dc[size][m] = s.dc[size][rm];
63                    } else {
64                        // Default list.
65                        s.lists[size][m] = if size == 0 {
66                            [16; 64]
67                        } else {
68                            DEFAULT_SCALING[(m >= 3) as usize]
69                        };
70                        s.dc[size][m] = 16;
71                    }
72                } else {
73                    let mut next = 8i32;
74                    let n = (1usize << (4 + (size << 1))).min(64);
75                    if size > 1 {
76                        let dc = r.se().saturating_add(8);
77                        if !(1..=255).contains(&dc) {
78                            return Err("scaling_list_dc_coef out of range".into());
79                        }
80                        next = dc;
81                        s.dc[size][m] = dc as u8;
82                    }
83                    for i in 0..n {
84                        let delta = r.se();
85                        // (next + delta + 256) % 256 for the legal −128..=127,
86                        // without overflowing on garbage.
87                        next = (next as i64 + delta as i64).rem_euclid(256) as i32;
88                        s.lists[size][m][i] = next as u8;
89                    }
90                    if size <= 1 {
91                        s.dc[size][m] = s.lists[size][m][0];
92                    }
93                }
94                m += step;
95            }
96        }
97        // 32×32 chroma lists (4:4:4 only) copy from 16×16 — keep them sane.
98        for m in [1, 2, 4, 5] {
99            s.lists[3][m] = s.lists[2][m];
100            s.dc[3][m] = s.dc[2][m];
101        }
102        Ok(s)
103    }
104
105    fn expand(&self) -> ScalingFactors {
106        let mut out: [[Vec<u8>; 6]; 4] = Default::default();
107        for size in 0..4 {
108            let n = 4usize << size;
109            for m in 0..6 {
110                let mut f = vec![0u8; n * n];
111                if size == 0 {
112                    for (i, &(x, y)) in SCAN4[0].iter().enumerate() {
113                        f[y as usize * 4 + x as usize] = self.lists[0][m][i];
114                    }
115                } else {
116                    let rep = n / 8;
117                    for (i, &(x, y)) in SCAN8X8.iter().enumerate() {
118                        for j in 0..rep {
119                            for k in 0..rep {
120                                let (xx, yy) = (x as usize * rep + k, y as usize * rep + j);
121                                f[yy * n + xx] = self.lists[size][m][i];
122                            }
123                        }
124                    }
125                    if size >= 2 {
126                        f[0] = self.dc[size][m];
127                    }
128                }
129                out[size][m] = f;
130            }
131        }
132        ScalingFactors { m: out }
133    }
134}
135
136/// A short-term reference picture set (§7.4.8).
137#[derive(Clone, Debug, Default)]
138pub struct StRps {
139    /// Negative deltas, closest first, with `used_by_curr_pic`.
140    pub neg: Vec<(i32, bool)>,
141    /// Positive deltas, closest first.
142    pub pos: Vec<(i32, bool)>,
143}
144
145impl StRps {
146    fn num_delta_pocs(&self) -> usize {
147        self.neg.len() + self.pos.len()
148    }
149
150    /// Parse `st_ref_pic_set(idx)`. `sets` are those already parsed from
151    /// the SPS. `in_slice` marks the set in a slice header (whose `idx` is
152    /// `num_short_term_ref_pic_sets`) — the only one that codes
153    /// `delta_idx_minus1`. While the SPS itself is being parsed `idx` also
154    /// equals the number parsed so far, so the index cannot tell them apart.
155    fn parse(r: &mut BitReader, idx: usize, sets: &[StRps], in_slice: bool) -> Result<StRps> {
156        let inter = idx != 0 && r.flag();
157        if inter {
158            let delta_idx = if in_slice { r.ue() as usize + 1 } else { 1 };
159            if delta_idx > idx {
160                return Err("delta_idx_minus1 out of range".into());
161            }
162            let rref = &sets[idx - delta_idx];
163            let sign = r.flag();
164            let abs = r.ue() as i32 + 1;
165            let delta_rps = if sign { -abs } else { abs };
166            let n = rref.num_delta_pocs();
167            let mut used = vec![false; n + 1];
168            let mut use_delta = vec![true; n + 1];
169            for j in 0..=n {
170                used[j] = r.flag();
171                if !used[j] {
172                    use_delta[j] = r.flag();
173                }
174            }
175            // §7.4.8, equations 7-61 and 7-62. Entries 0..neg are the
176            // reference set's negative pictures, then its positive ones,
177            // then the reference picture itself.
178            let nn = rref.neg.len();
179            let mut out = StRps::default();
180            for j in (0..rref.pos.len()).rev() {
181                let d = rref.pos[j].0 + delta_rps;
182                if d < 0 && use_delta[nn + j] {
183                    out.neg.push((d, used[nn + j]));
184                }
185            }
186            if delta_rps < 0 && use_delta[n] {
187                out.neg.push((delta_rps, used[n]));
188            }
189            for j in 0..nn {
190                let d = rref.neg[j].0 + delta_rps;
191                if d < 0 && use_delta[j] {
192                    out.neg.push((d, used[j]));
193                }
194            }
195            for j in (0..nn).rev() {
196                let d = rref.neg[j].0 + delta_rps;
197                if d > 0 && use_delta[j] {
198                    out.pos.push((d, used[j]));
199                }
200            }
201            if delta_rps > 0 && use_delta[n] {
202                out.pos.push((delta_rps, used[n]));
203            }
204            for j in 0..rref.pos.len() {
205                let d = rref.pos[j].0 + delta_rps;
206                if d > 0 && use_delta[nn + j] {
207                    out.pos.push((d, used[nn + j]));
208                }
209            }
210            Ok(out)
211        } else {
212            let nneg = r.ue() as usize;
213            let npos = r.ue() as usize;
214            if nneg > 16 || npos > 16 {
215                return Err("too many pictures in a reference picture set".into());
216            }
217            let mut out = StRps::default();
218            let mut poc = 0;
219            for _ in 0..nneg {
220                poc -= r.ue() as i32 + 1;
221                out.neg.push((poc, r.flag()));
222            }
223            poc = 0;
224            for _ in 0..npos {
225                poc += r.ue() as i32 + 1;
226                out.pos.push((poc, r.flag()));
227            }
228            Ok(out)
229        }
230    }
231}
232
233fn profile_tier_level(r: &mut BitReader, max_sub_layers_minus1: u32) -> u32 {
234    r.skip(2 + 1);
235    let profile_idc = r.u(5);
236    r.skip(32 + 4 + 43 + 1 + 8);
237    let mut prof = [false; 8];
238    let mut lvl = [false; 8];
239    for i in 0..max_sub_layers_minus1 as usize {
240        prof[i] = r.flag();
241        lvl[i] = r.flag();
242    }
243    if max_sub_layers_minus1 > 0 {
244        for _ in max_sub_layers_minus1..8 {
245            r.skip(2);
246        }
247    }
248    for i in 0..max_sub_layers_minus1 as usize {
249        if prof[i] {
250            r.skip(88);
251        }
252        if lvl[i] {
253            r.skip(8);
254        }
255    }
256    profile_idc
257}
258
259fn sub_layer_hrd(r: &mut BitReader, cpb_cnt: u32, sub_pic: bool) {
260    for _ in 0..=cpb_cnt {
261        r.ue();
262        r.ue();
263        if sub_pic {
264            r.ue();
265            r.ue();
266        }
267        r.skip(1);
268    }
269}
270
271fn hrd_parameters(r: &mut BitReader, common: bool, max_sub_layers_minus1: u32) -> Result<()> {
272    let mut nal = false;
273    let mut vcl = false;
274    let mut sub_pic = false;
275    if common {
276        nal = r.flag();
277        vcl = r.flag();
278        if nal || vcl {
279            sub_pic = r.flag();
280            if sub_pic {
281                r.skip(8 + 5 + 1 + 5);
282            }
283            r.skip(4 + 4);
284            if sub_pic {
285                r.skip(4);
286            }
287            r.skip(5 + 5 + 5);
288        }
289    }
290    for _ in 0..=max_sub_layers_minus1 {
291        let general = r.flag();
292        let within_cvs = if general { true } else { r.flag() };
293        let mut low_delay = false;
294        if within_cvs {
295            r.ue();
296        } else {
297            low_delay = r.flag();
298        }
299        let cpb_cnt = if !low_delay { r.ue() } else { 0 };
300        // Bounded by the spec, and a loop count below: damage here must not
301        // become four billion iterations.
302        if cpb_cnt > 31 {
303            return Err("cpb_cnt_minus1 out of range".into());
304        }
305        if nal {
306            sub_layer_hrd(r, cpb_cnt, sub_pic);
307        }
308        if vcl {
309            sub_layer_hrd(r, cpb_cnt, sub_pic);
310        }
311    }
312    Ok(())
313}
314
315#[derive(Clone, Debug)]
316pub struct Sps {
317    pub id: u32,
318    pub profile_idc: u32,
319    pub chroma_format_idc: u32,
320    pub width: u32,
321    pub height: u32,
322    /// Luma samples cropped: left, right, top, bottom.
323    pub crop: [u32; 4],
324    pub bit_depth_y: u32,
325    pub bit_depth_c: u32,
326    pub log2_max_poc_lsb: u32,
327    pub max_dec_pic_buffering: u32,
328    /// `sps_max_num_reorder_pics` of the highest sub-layer.
329    pub max_num_reorder: u32,
330    /// `sps_max_latency_increase_plus1` of the highest sub-layer.
331    pub max_latency_increase_plus1: u32,
332    pub log2_min_cb: u32,
333    pub log2_ctb: u32,
334    pub log2_min_tb: u32,
335    pub log2_max_tb: u32,
336    pub max_th_depth_inter: u32,
337    pub max_th_depth_intra: u32,
338    pub scaling: Option<ScalingFactors>,
339    pub amp: bool,
340    pub sao: bool,
341    pub pcm: bool,
342    pub pcm_bit_depth_y: u32,
343    pub pcm_bit_depth_c: u32,
344    pub log2_min_pcm: u32,
345    pub log2_max_pcm: u32,
346    pub pcm_loop_filter_disabled: bool,
347    pub st_rps: Vec<StRps>,
348    pub long_term_present: bool,
349    pub lt_ref_pics: Vec<(u32, bool)>,
350    pub temporal_mvp: bool,
351    pub strong_intra_smoothing: bool,
352    /// Range extension: no reference smoothing in intra prediction.
353    pub intra_smoothing_disabled: bool,
354    /// Range extension: 4×4 intra residuals without a transform are
355    /// rotated by 180°.
356    pub transform_skip_rotation: bool,
357    /// Range extension: one significance context for untransformed blocks.
358    pub transform_skip_context: bool,
359    /// Range extension: residual DPCM, implied for intra blocks predicted
360    /// straight across and signalled for inter ones.
361    pub implicit_rdpcm: bool,
362    pub explicit_rdpcm: bool,
363    /// Range extension: weighted-prediction offsets at full bit depth.
364    pub high_precision_offsets: bool,
365    /// Range extension: Rice parameters carried between sub-blocks.
366    pub persistent_rice_adaptation: bool,
367    /// The VUI's colour description, when it has one.
368    pub colour_primaries: Option<u32>,
369    pub transfer_characteristics: Option<u32>,
370    pub matrix_coefficients: Option<u32>,
371    pub full_range: bool,
372}
373
374impl Sps {
375    /// Chroma subsampling as shifts, `(horizontal, vertical)`: (1, 1) for
376    /// 4:2:0, (1, 0) for 4:2:2, (0, 0) for 4:4:4.
377    pub fn chroma_shift(&self) -> (usize, usize) {
378        (
379            (self.chroma_format_idc != 3) as usize,
380            (self.chroma_format_idc == 1) as usize,
381        )
382    }
383
384    pub fn parse(rbsp: &[u8]) -> Result<Sps> {
385        let mut r = BitReader::new(rbsp);
386        r.skip(4);
387        let max_sub_layers_minus1 = r.u(3);
388        r.skip(1);
389        let profile_idc = profile_tier_level(&mut r, max_sub_layers_minus1);
390        let id = r.ue();
391        if id > 15 {
392            return Err("SPS id out of range".into());
393        }
394        let chroma_format_idc = r.ue();
395        if chroma_format_idc == 3 && r.flag() {
396            return Err("separate colour planes are not supported".into());
397        }
398        if !(1..=3).contains(&chroma_format_idc) {
399            return Err(format!(
400                "HEVC chroma_format_idc {chroma_format_idc} is not supported (4:2:0, 4:2:2 and 4:4:4 only)"
401            ));
402        }
403        let width = r.ue();
404        let height = r.ue();
405        let mut crop = [0u32; 4];
406        if r.flag() {
407            // In chroma units: SubWidthC and SubHeightC.
408            let sw = if chroma_format_idc == 3 { 1 } else { 2 };
409            let sh = if chroma_format_idc == 1 { 2 } else { 1 };
410            let c = [r.ue(), r.ue(), r.ue(), r.ue()];
411            crop = [
412                c[0].saturating_mul(sw),
413                c[1].saturating_mul(sw),
414                c[2].saturating_mul(sh),
415                c[3].saturating_mul(sh),
416            ];
417        }
418        // Bounds before anything is sized from these (§7.4.3.2.1): garbage
419        // reads as all-ones Exp-Golomb codes.
420        if width == 0 || height == 0 || width > 1 << 14 || height > 1 << 14 {
421            return Err("SPS picture size out of range".into());
422        }
423        check_picture_size(width, height)?;
424        if crop[0].saturating_add(crop[1]) >= width || crop[2].saturating_add(crop[3]) >= height {
425            return Err("SPS conformance window exceeds the picture".into());
426        }
427        let bit_depth_y = r.ue().saturating_add(8);
428        let bit_depth_c = r.ue().saturating_add(8);
429        if bit_depth_y > 12 || bit_depth_c > 12 {
430            return Err("bit depths above 12 are not supported".into());
431        }
432        let log2_max_poc_lsb = r.ue().saturating_add(4);
433        if log2_max_poc_lsb > 16 {
434            return Err("log2_max_pic_order_cnt_lsb out of range".into());
435        }
436        let ordering_all = r.flag();
437        let mut max_dec_pic_buffering = 1;
438        let mut max_num_reorder = 0;
439        let mut max_latency_increase_plus1 = 0;
440        let start = if ordering_all {
441            0
442        } else {
443            max_sub_layers_minus1
444        };
445        for _ in start..=max_sub_layers_minus1 {
446            max_dec_pic_buffering = r.ue().saturating_add(1);
447            if max_dec_pic_buffering > 16 {
448                return Err("sps_max_dec_pic_buffering out of range".into());
449            }
450            max_num_reorder = r.ue();
451            max_latency_increase_plus1 = r.ue();
452        }
453        let log2_min_cb = r.ue().saturating_add(3);
454        let log2_ctb = log2_min_cb.saturating_add(r.ue());
455        let log2_min_tb = r.ue().saturating_add(2);
456        let log2_max_tb = log2_min_tb.saturating_add(r.ue());
457        // Whole minimum coding blocks: a block past this edge could not be
458        // split back inside the picture, and every per-block array is sized
459        // to the picture.
460        let min_cb = 1u64.checked_shl(log2_min_cb).unwrap_or(u64::MAX);
461        if (width as u64 | height as u64) & (min_cb - 1) != 0 {
462            return Err("picture size is not a multiple of the minimum coding block".into());
463        }
464        if !(4..=6).contains(&log2_ctb)
465            || log2_max_tb > 5
466            || log2_min_tb >= log2_min_cb
467            || log2_max_tb > log2_ctb
468        {
469            return Err("coding/transform block sizes out of range".into());
470        }
471        let max_th_depth_inter = r.ue();
472        let max_th_depth_intra = r.ue();
473        let mut scaling = None;
474        if r.flag() {
475            let lists = if r.flag() {
476                ScalingLists::parse(&mut r)?
477            } else {
478                ScalingLists::default_lists()
479            };
480            scaling = Some(lists.expand());
481        }
482        let amp = r.flag();
483        let sao = r.flag();
484        let pcm = r.flag();
485        let (mut pcm_bit_depth_y, mut pcm_bit_depth_c, mut log2_min_pcm, mut log2_max_pcm) =
486            (8, 8, 0, 0);
487        let mut pcm_loop_filter_disabled = false;
488        if pcm {
489            pcm_bit_depth_y = r.u(4) + 1;
490            pcm_bit_depth_c = r.u(4) + 1;
491            log2_min_pcm = r.ue().saturating_add(3);
492            log2_max_pcm = log2_min_pcm.saturating_add(r.ue());
493            pcm_loop_filter_disabled = r.flag();
494        }
495        let n = r.ue() as usize;
496        if n > 64 {
497            return Err("num_short_term_ref_pic_sets out of range".into());
498        }
499        let mut st_rps = Vec::with_capacity(n);
500        for i in 0..n {
501            let s = StRps::parse(&mut r, i, &st_rps, false)?;
502            st_rps.push(s);
503        }
504        let long_term_present = r.flag();
505        let mut lt_ref_pics = Vec::new();
506        if long_term_present {
507            let n = r.ue();
508            if n > 32 {
509                return Err("num_long_term_ref_pics_sps out of range".into());
510            }
511            for _ in 0..n {
512                lt_ref_pics.push((r.u(log2_max_poc_lsb), r.flag()));
513            }
514        }
515        let temporal_mvp = r.flag();
516        let strong_intra_smoothing = r.flag();
517        let (mut colour_primaries, mut transfer_characteristics) = (None, None);
518        let mut matrix_coefficients = None;
519        let mut full_range = false;
520        if r.flag() {
521            // vui_parameters()
522            if r.flag() && r.u(8) == 255 {
523                r.skip(32);
524            }
525            if r.flag() {
526                r.skip(1);
527            }
528            if r.flag() {
529                r.skip(3);
530                full_range = r.flag();
531                if r.flag() {
532                    colour_primaries = Some(r.u(8));
533                    transfer_characteristics = Some(r.u(8));
534                    matrix_coefficients = Some(r.u(8));
535                }
536            }
537            if r.flag() {
538                r.ue();
539                r.ue();
540            }
541            r.skip(3);
542            if r.flag() {
543                r.ue();
544                r.ue();
545                r.ue();
546                r.ue();
547            }
548            if r.flag() {
549                r.skip(64);
550                if r.flag() {
551                    r.ue();
552                }
553                if r.flag() {
554                    hrd_parameters(&mut r, true, max_sub_layers_minus1)?;
555                }
556            }
557            if r.flag() {
558                r.skip(3);
559                r.ue();
560                r.ue();
561                r.ue();
562                r.ue();
563                r.ue();
564            }
565        }
566        let mut tools = 0;
567        if r.flag() {
568            // As for the PPS: before version 2 these were arbitrary extension
569            // data bits, so only RExt and later profiles have a range
570            // extension. JCT-VC EXT_A_ericsson_3 sets them on a Main stream;
571            // read this way it decodes to exactly what HM makes of its
572            // reissue, EXT_A_ericsson_4. (ffmpeg gates only the PPS one, and
573            // refuses _3.)
574            let range = r.flag() && profile_idc >= 4;
575            let _others = r.u(7);
576            if range {
577                // Nine flags, first to last: transform skip rotation and
578                // context, implicit and explicit RDPCM, extended precision,
579                // intra smoothing disabled, high precision offsets,
580                // persistent Rice adaptation, CABAC bypass alignment.
581                tools = r.u(9);
582                if tools & 0x10 != 0 {
583                    return Err("extended precision processing is not supported".into());
584                }
585                if tools & 0x01 != 0 {
586                    return Err("CABAC bypass alignment is not supported".into());
587                }
588            }
589        }
590        if r.overrun() {
591            return Err("SPS runs past the NAL".into());
592        }
593        if width == 0 || height == 0 || width > 16384 || height > 16384 {
594            return Err("picture size out of range".into());
595        }
596        let _ = profile_idc;
597        Ok(Sps {
598            id,
599            profile_idc,
600            chroma_format_idc,
601            width,
602            height,
603            crop,
604            bit_depth_y,
605            bit_depth_c,
606            log2_max_poc_lsb,
607            max_dec_pic_buffering,
608            max_num_reorder,
609            max_latency_increase_plus1,
610            log2_min_cb,
611            log2_ctb,
612            log2_min_tb,
613            log2_max_tb,
614            max_th_depth_inter,
615            max_th_depth_intra,
616            scaling,
617            amp,
618            sao,
619            pcm,
620            pcm_bit_depth_y,
621            pcm_bit_depth_c,
622            log2_min_pcm,
623            log2_max_pcm,
624            pcm_loop_filter_disabled,
625            st_rps,
626            long_term_present,
627            lt_ref_pics,
628            temporal_mvp,
629            strong_intra_smoothing,
630            intra_smoothing_disabled: tools & 0x08 != 0,
631            transform_skip_rotation: tools & 0x100 != 0,
632            transform_skip_context: tools & 0x80 != 0,
633            implicit_rdpcm: tools & 0x40 != 0,
634            explicit_rdpcm: tools & 0x20 != 0,
635            high_precision_offsets: tools & 0x04 != 0,
636            persistent_rice_adaptation: tools & 0x02 != 0,
637            colour_primaries,
638            transfer_characteristics,
639            matrix_coefficients,
640            full_range,
641        })
642    }
643
644    pub fn ctb_size(&self) -> u32 {
645        1 << self.log2_ctb
646    }
647    pub fn width_ctbs(&self) -> u32 {
648        self.width.div_ceil(self.ctb_size())
649    }
650    pub fn height_ctbs(&self) -> u32 {
651        self.height.div_ceil(self.ctb_size())
652    }
653}
654
655#[derive(Clone, Debug)]
656pub struct Pps {
657    pub id: u32,
658    pub sps_id: u32,
659    pub dependent_slices: bool,
660    pub output_flag_present: bool,
661    pub extra_slice_header_bits: u32,
662    pub sign_data_hiding: bool,
663    pub cabac_init_present: bool,
664    pub num_ref_idx_default: [u32; 2],
665    pub init_qp: i32,
666    pub constrained_intra_pred: bool,
667    pub transform_skip: bool,
668    pub cu_qp_delta: bool,
669    pub diff_cu_qp_delta_depth: u32,
670    pub cb_qp_offset: i32,
671    pub cr_qp_offset: i32,
672    pub slice_chroma_qp_offsets_present: bool,
673    /// Range extension: the (Cb, Cr) QP offsets a coding unit can pick from,
674    /// empty when `chroma_qp_offset_list_enabled_flag` is off.
675    pub chroma_qp_offset_list: Vec<[i32; 2]>,
676    /// Depth below the CTB of the groups that each code one choice.
677    pub diff_cu_chroma_qp_offset_depth: u32,
678    /// Range extension: largest transform-skip block, log2 (2 without it).
679    pub log2_max_transform_skip: u32,
680    /// Range extension: chroma residuals may add a scaled luma residual.
681    pub cross_component_prediction: bool,
682    /// Range extension: SAO offsets are scaled up by these, luma and chroma.
683    pub log2_sao_offset_scale: [u32; 2],
684    pub weighted_pred: bool,
685    pub weighted_bipred: bool,
686    pub transquant_bypass: bool,
687    pub tiles: bool,
688    pub entropy_sync: bool,
689    /// Explicit tile column widths / row heights in CTBs, or `None` for
690    /// uniform spacing with the given count.
691    pub tile_cols: TileSpacing,
692    pub tile_rows: TileSpacing,
693    pub loop_filter_across_tiles: bool,
694    pub loop_filter_across_slices: bool,
695    pub deblocking_override_enabled: bool,
696    pub deblocking_disabled: bool,
697    pub beta_offset: i32,
698    pub tc_offset: i32,
699    pub scaling: Option<ScalingFactors>,
700    pub lists_modification_present: bool,
701    pub log2_parallel_merge_level: u32,
702    pub slice_header_extension_present: bool,
703}
704
705#[derive(Clone, Debug)]
706pub enum TileSpacing {
707    Uniform(u32),
708    Explicit(Vec<u32>),
709}
710
711impl TileSpacing {
712    /// Boundaries in CTBs: `n + 1` entries from 0 to `total`.
713    pub fn boundaries(&self, total: u32) -> Vec<u32> {
714        let mut b = vec![0];
715        match self {
716            TileSpacing::Uniform(n) => {
717                for i in 0..*n {
718                    b.push(((i as u64 + 1) * total as u64 / *n as u64) as u32);
719                }
720            }
721            TileSpacing::Explicit(sizes) => {
722                let mut acc = 0;
723                // Saturating: a damaged parameter set can state sizes that
724                // add up past `u32`.
725                for &s in sizes {
726                    acc = u32::saturating_add(acc, s);
727                    b.push(acc.min(total));
728                }
729                b.push(total);
730            }
731        }
732        b
733    }
734}
735
736impl Pps {
737    /// `spss` are the sequence parameter sets received so far, indexed by id:
738    /// the referenced one's profile decides whether a range extension is read.
739    pub fn parse(rbsp: &[u8], spss: &[Option<Sps>]) -> Result<Pps> {
740        let mut r = BitReader::new(rbsp);
741        let id = r.ue();
742        let sps_id = r.ue();
743        if id > 63 || sps_id > 15 {
744            return Err("PPS id out of range".into());
745        }
746        let dependent_slices = r.flag();
747        let output_flag_present = r.flag();
748        let extra_slice_header_bits = r.u(3);
749        let sign_data_hiding = r.flag();
750        let cabac_init_present = r.flag();
751        let num_ref_idx_default = [r.ue().saturating_add(1), r.ue().saturating_add(1)];
752        if num_ref_idx_default[0] > 15 || num_ref_idx_default[1] > 15 {
753            return Err("num_ref_idx_default out of range".into());
754        }
755        let init_qp = r.se().saturating_add(26);
756        let constrained_intra_pred = r.flag();
757        let transform_skip = r.flag();
758        let cu_qp_delta = r.flag();
759        let diff_cu_qp_delta_depth = if cu_qp_delta { r.ue() } else { 0 };
760        let cb_qp_offset = r.se();
761        let cr_qp_offset = r.se();
762        if !(-12..=12).contains(&cb_qp_offset) || !(-12..=12).contains(&cr_qp_offset) {
763            return Err("pps_cb_qp_offset or pps_cr_qp_offset out of range".into());
764        }
765        let slice_chroma_qp_offsets_present = r.flag();
766        let weighted_pred = r.flag();
767        let weighted_bipred = r.flag();
768        let transquant_bypass = r.flag();
769        let tiles = r.flag();
770        let entropy_sync = r.flag();
771        let mut tile_cols = TileSpacing::Uniform(1);
772        let mut tile_rows = TileSpacing::Uniform(1);
773        let mut loop_filter_across_tiles = true;
774        if tiles {
775            let ncols = r.ue().saturating_add(1);
776            let nrows = r.ue().saturating_add(1);
777            // Level 6.2's limits are 20 × 22; past those it is not a stream.
778            if ncols > 20 || nrows > 22 {
779                return Err("tile counts out of range".into());
780            }
781            if ncols > 64 || nrows > 64 {
782                return Err("too many tiles".into());
783            }
784            if r.flag() {
785                tile_cols = TileSpacing::Uniform(ncols);
786                tile_rows = TileSpacing::Uniform(nrows);
787            } else {
788                tile_cols =
789                    TileSpacing::Explicit((1..ncols).map(|_| r.ue().saturating_add(1)).collect());
790                tile_rows =
791                    TileSpacing::Explicit((1..nrows).map(|_| r.ue().saturating_add(1)).collect());
792            }
793            loop_filter_across_tiles = r.flag();
794        }
795        let loop_filter_across_slices = r.flag();
796        let mut deblocking_override_enabled = false;
797        let mut deblocking_disabled = false;
798        let mut beta_offset = 0;
799        let mut tc_offset = 0;
800        if r.flag() {
801            deblocking_override_enabled = r.flag();
802            deblocking_disabled = r.flag();
803            if !deblocking_disabled {
804                beta_offset = r.se().saturating_mul(2);
805                tc_offset = r.se().saturating_mul(2);
806            }
807        }
808        let mut scaling = None;
809        if r.flag() {
810            scaling = Some(ScalingLists::parse(&mut r)?.expand());
811        }
812        let lists_modification_present = r.flag();
813        let log2_parallel_merge_level = r.ue().saturating_add(2);
814        // At most CtbLog2SizeY, which is at most 6; merge candidates shift by
815        // it, so a damaged value has to stop here.
816        if log2_parallel_merge_level > 6 {
817            return Err("log2_parallel_merge_level_minus2 out of range".into());
818        }
819        let slice_header_extension_present = r.flag();
820        let mut chroma_qp_offset_list = Vec::new();
821        let mut diff_cu_chroma_qp_offset_depth = 0;
822        let mut log2_max_transform_skip = 2;
823        let mut cross_component_prediction = false;
824        let mut log2_sao_offset_scale = [0, 0];
825        if r.flag() {
826            // Streams older than the range extensions (version 2) set
827            // pps_extension_flag and follow it with arbitrary extension data,
828            // which a Main or Main 10 decoder must ignore (JCT-VC PS_A_VIDYO_3
829            // tests exactly that). So, as ffmpeg does, read the range extension
830            // only for RExt and later profiles; without the SPS, assume one.
831            let rext = spss
832                .get(sps_id as usize)
833                .and_then(Option::as_ref)
834                .is_none_or(|s| s.profile_idc >= 4);
835            let range = r.flag() && rext;
836            let _others = r.u(7);
837            if range {
838                if transform_skip {
839                    // Only ever compared with block sizes; HM accepts the
840                    // out-of-range 8 in JCT-VC PERSIST_RPARAM_A_RExt_Sony_1.
841                    log2_max_transform_skip = r.ue().saturating_add(2);
842                }
843                cross_component_prediction = r.flag();
844                if r.flag() {
845                    diff_cu_chroma_qp_offset_depth = r.ue();
846                    let len = r.ue().saturating_add(1);
847                    if len > 6 {
848                        return Err("chroma_qp_offset_list_len_minus1 out of range".into());
849                    }
850                    for _ in 0..len {
851                        let pair = [r.se(), r.se()];
852                        if pair.iter().any(|o| !(-12..=12).contains(o)) {
853                            return Err("chroma QP offset list entry out of range".into());
854                        }
855                        chroma_qp_offset_list.push(pair);
856                    }
857                }
858                log2_sao_offset_scale = [r.ue(), r.ue()];
859                // At most bitDepth − 10, so never above 6 (16-bit).
860                if log2_sao_offset_scale.iter().any(|&v| v > 6) {
861                    return Err("log2_sao_offset_scale out of range".into());
862                }
863            }
864        }
865        Ok(Pps {
866            id,
867            sps_id,
868            dependent_slices,
869            output_flag_present,
870            extra_slice_header_bits,
871            sign_data_hiding,
872            cabac_init_present,
873            num_ref_idx_default,
874            init_qp,
875            constrained_intra_pred,
876            transform_skip,
877            cu_qp_delta,
878            diff_cu_qp_delta_depth,
879            cb_qp_offset,
880            cr_qp_offset,
881            slice_chroma_qp_offsets_present,
882            chroma_qp_offset_list,
883            diff_cu_chroma_qp_offset_depth,
884            log2_max_transform_skip,
885            cross_component_prediction,
886            log2_sao_offset_scale,
887            weighted_pred,
888            weighted_bipred,
889            transquant_bypass,
890            tiles,
891            entropy_sync,
892            tile_cols,
893            tile_rows,
894            loop_filter_across_tiles,
895            loop_filter_across_slices,
896            deblocking_override_enabled,
897            deblocking_disabled,
898            beta_offset,
899            tc_offset,
900            scaling,
901            lists_modification_present,
902            log2_parallel_merge_level,
903            slice_header_extension_present,
904        })
905    }
906}
907
908#[derive(Clone, Copy, Debug, PartialEq, Eq)]
909pub enum SliceType {
910    B,
911    P,
912    I,
913}
914
915/// Explicit weighted prediction: `[list][ref] = [(weight, offset); Y, Cb, Cr]`
916/// with offsets already scaled to the bit depth.
917#[derive(Clone, Debug, Default)]
918pub struct PredWeights {
919    pub luma_log2_denom: u32,
920    pub chroma_log2_denom: u32,
921    pub w: [Vec<[(i32, i32); 3]>; 2],
922}
923
924#[derive(Clone, Debug)]
925pub struct SliceHeader {
926    pub first_slice_in_pic: bool,
927    pub no_output_of_prior_pics: bool,
928    pub pps_id: u32,
929    pub dependent: bool,
930    pub segment_address: u32,
931    pub slice_type: SliceType,
932    pub pic_output: bool,
933    pub poc_lsb: u32,
934    pub st_rps: StRps,
935    /// Long-term entries: `(poc value, msb present, used by current)`.
936    pub lt: Vec<(i32, bool, bool)>,
937    pub temporal_mvp: bool,
938    pub sao_luma: bool,
939    pub sao_chroma: bool,
940    pub num_ref_idx: [u32; 2],
941    pub list_entry: [Option<Vec<u32>>; 2],
942    pub mvd_l1_zero: bool,
943    pub cabac_init_flag: bool,
944    pub collocated_from_l0: bool,
945    pub collocated_ref_idx: u32,
946    pub weights: Option<PredWeights>,
947    pub max_merge_cand: u32,
948    pub qp_delta: i32,
949    pub cb_qp_offset: i32,
950    pub cr_qp_offset: i32,
951    /// `cu_chroma_qp_offset_enabled_flag`: coding units may pick from the
952    /// PPS chroma QP offset list.
953    pub cu_chroma_qp_offset: bool,
954    pub deblocking_disabled: bool,
955    pub beta_offset: i32,
956    pub tc_offset: i32,
957    pub loop_filter_across_slices: bool,
958    /// Byte offset of `slice_segment_data()` in the RBSP.
959    pub data_offset: usize,
960    /// Bits the slice header spent on its own `st_ref_pic_set()`; 0 when it
961    /// named one of the SPS's.
962    pub st_rps_bits: u32,
963    /// `num_entry_point_offsets`.
964    pub num_entry_points: u32,
965}
966
967impl SliceHeader {
968    /// Parse a slice segment header. A dependent segment copies everything
969    /// but its address from `prev`, the last independent one.
970    pub fn parse(
971        rbsp: &[u8],
972        nal_type: u32,
973        spss: &[Option<Sps>],
974        ppss: &[Option<Pps>],
975        prev: Option<&SliceHeader>,
976    ) -> Result<SliceHeader> {
977        let mut r = BitReader::new(rbsp);
978        let first = r.flag();
979        let mut no_output_of_prior_pics = false;
980        if (16..=23).contains(&nal_type) {
981            no_output_of_prior_pics = r.flag();
982        }
983        let pps_id = r.ue();
984        let pps = ppss
985            .get(pps_id as usize)
986            .and_then(|p| p.as_ref())
987            .ok_or_else(|| format!("slice names missing PPS {pps_id}"))?;
988        let sps = spss[pps.sps_id as usize]
989            .as_ref()
990            .ok_or("slice's PPS names a missing SPS")?;
991        let mut dependent = false;
992        let mut segment_address = 0;
993        if !first {
994            if pps.dependent_slices {
995                dependent = r.flag();
996            }
997            let ctbs = sps.width_ctbs() * sps.height_ctbs();
998            segment_address = r.u(ceil_log2(ctbs));
999            if segment_address >= ctbs {
1000                return Err("slice_segment_address out of range".into());
1001            }
1002        }
1003        let mut h = if dependent {
1004            let mut h = prev
1005                .ok_or("dependent slice segment without a preceding slice")?
1006                .clone();
1007            h.first_slice_in_pic = first;
1008            h.dependent = true;
1009            h.segment_address = segment_address;
1010            h
1011        } else {
1012            let mut h = SliceHeader {
1013                first_slice_in_pic: first,
1014                no_output_of_prior_pics,
1015                pps_id,
1016                dependent: false,
1017                segment_address,
1018                slice_type: SliceType::I,
1019                pic_output: true,
1020                poc_lsb: 0,
1021                st_rps: StRps::default(),
1022                lt: Vec::new(),
1023                temporal_mvp: false,
1024                sao_luma: false,
1025                sao_chroma: false,
1026                num_ref_idx: [0, 0],
1027                list_entry: [None, None],
1028                mvd_l1_zero: false,
1029                cabac_init_flag: false,
1030                collocated_from_l0: true,
1031                collocated_ref_idx: 0,
1032                weights: None,
1033                max_merge_cand: 5,
1034                qp_delta: 0,
1035                cb_qp_offset: 0,
1036                cr_qp_offset: 0,
1037                cu_chroma_qp_offset: false,
1038                deblocking_disabled: pps.deblocking_disabled,
1039                beta_offset: pps.beta_offset,
1040                tc_offset: pps.tc_offset,
1041                loop_filter_across_slices: pps.loop_filter_across_slices,
1042                data_offset: 0,
1043                st_rps_bits: 0,
1044                num_entry_points: 0,
1045            };
1046            r.skip(pps.extra_slice_header_bits);
1047            h.slice_type = match r.ue() {
1048                0 => SliceType::B,
1049                1 => SliceType::P,
1050                2 => SliceType::I,
1051                t => return Err(format!("slice_type {t} out of range")),
1052            };
1053            if pps.output_flag_present {
1054                h.pic_output = r.flag();
1055            }
1056            let idr = nal_type == 19 || nal_type == 20;
1057            let mut num_pic_total_curr = 0u32;
1058            if !idr {
1059                h.poc_lsb = r.u(sps.log2_max_poc_lsb);
1060                if !r.flag() {
1061                    let at = r.pos();
1062                    h.st_rps = StRps::parse(&mut r, sps.st_rps.len(), &sps.st_rps, true)?;
1063                    h.st_rps_bits = (r.pos() - at) as u32;
1064                } else {
1065                    if sps.st_rps.is_empty() {
1066                        return Err("slice refers to an SPS RPS but there are none".into());
1067                    }
1068                    let idx = if sps.st_rps.len() > 1 {
1069                        r.u(ceil_log2(sps.st_rps.len() as u32)) as usize
1070                    } else {
1071                        0
1072                    };
1073                    h.st_rps = sps
1074                        .st_rps
1075                        .get(idx)
1076                        .ok_or("short_term_ref_pic_set_idx out of range")?
1077                        .clone();
1078                }
1079                if sps.long_term_present {
1080                    let n_sps = if !sps.lt_ref_pics.is_empty() {
1081                        r.ue()
1082                    } else {
1083                        0
1084                    };
1085                    let n_pics = r.ue();
1086                    if n_sps as usize > sps.lt_ref_pics.len() || n_sps + n_pics > 32 {
1087                        return Err("too many long-term pictures".into());
1088                    }
1089                    let max_lsb = 1i32 << sps.log2_max_poc_lsb;
1090                    let mut msb_cycle = 0i32;
1091                    for i in 0..(n_sps + n_pics) {
1092                        let (lsb, used) = if i < n_sps {
1093                            let idx = if sps.lt_ref_pics.len() > 1 {
1094                                r.u(ceil_log2(sps.lt_ref_pics.len() as u32)) as usize
1095                            } else {
1096                                0
1097                            };
1098                            let e = sps.lt_ref_pics.get(idx).ok_or("lt_idx_sps out of range")?;
1099                            (e.0 as i32, e.1)
1100                        } else {
1101                            (r.u(sps.log2_max_poc_lsb) as i32, r.flag())
1102                        };
1103                        let msb_present = r.flag();
1104                        let mut poc = lsb;
1105                        if msb_present {
1106                            let delta = r.ue() as i32;
1107                            msb_cycle = if i == 0 || i == n_sps {
1108                                delta
1109                            } else {
1110                                delta + msb_cycle
1111                            };
1112                            // The rest of the MSB comes from the current
1113                            // POC, which the caller adds: §7.4.7.1 (7-52).
1114                            poc = lsb - msb_cycle * max_lsb;
1115                        }
1116                        h.lt.push((poc, msb_present, used));
1117                    }
1118                }
1119                if sps.temporal_mvp {
1120                    h.temporal_mvp = r.flag();
1121                }
1122                num_pic_total_curr = h.st_rps.neg.iter().filter(|e| e.1).count() as u32
1123                    + h.st_rps.pos.iter().filter(|e| e.1).count() as u32
1124                    + h.lt.iter().filter(|e| e.2).count() as u32;
1125            }
1126            if sps.sao {
1127                h.sao_luma = r.flag();
1128                h.sao_chroma = r.flag();
1129            }
1130            if h.slice_type != SliceType::I {
1131                h.num_ref_idx = pps.num_ref_idx_default;
1132                if r.flag() {
1133                    h.num_ref_idx[0] = r.ue().saturating_add(1);
1134                    if h.slice_type == SliceType::B {
1135                        h.num_ref_idx[1] = r.ue().saturating_add(1);
1136                    }
1137                }
1138                if h.slice_type != SliceType::B {
1139                    h.num_ref_idx[1] = 0;
1140                }
1141                if h.num_ref_idx[0] > 15 || h.num_ref_idx[1] > 15 {
1142                    return Err("num_ref_idx_active out of range".into());
1143                }
1144                if pps.lists_modification_present && num_pic_total_curr > 1 {
1145                    let bits = ceil_log2(num_pic_total_curr);
1146                    for l in 0..(1 + (h.slice_type == SliceType::B) as usize) {
1147                        if r.flag() {
1148                            h.list_entry[l] =
1149                                Some((0..h.num_ref_idx[l]).map(|_| r.u(bits)).collect());
1150                        }
1151                    }
1152                }
1153                if h.slice_type == SliceType::B {
1154                    h.mvd_l1_zero = r.flag();
1155                }
1156                if pps.cabac_init_present {
1157                    h.cabac_init_flag = r.flag();
1158                }
1159                if h.temporal_mvp {
1160                    if h.slice_type == SliceType::B {
1161                        h.collocated_from_l0 = r.flag();
1162                    }
1163                    let l = if h.collocated_from_l0 { 0 } else { 1 };
1164                    if h.num_ref_idx[l] > 1 {
1165                        h.collocated_ref_idx = r.ue();
1166                        if h.collocated_ref_idx >= h.num_ref_idx[l] {
1167                            return Err("collocated_ref_idx out of range".into());
1168                        }
1169                    }
1170                }
1171                if (pps.weighted_pred && h.slice_type == SliceType::P)
1172                    || (pps.weighted_bipred && h.slice_type == SliceType::B)
1173                {
1174                    h.weights = Some(pred_weight_table(&mut r, sps, &h)?);
1175                }
1176                // Checked before subtracting: a damaged value above 4 would
1177                // underflow.
1178                let five_minus = r.ue();
1179                if five_minus > 4 {
1180                    return Err("five_minus_max_num_merge_cand out of range".into());
1181                }
1182                h.max_merge_cand = 5 - five_minus;
1183            }
1184            h.qp_delta = r.se();
1185            // QP arithmetic below indexes tables by these, and only stays in
1186            // range if the slice starts in range.
1187            let qp_bd_offset = 6 * (sps.bit_depth_y as i32 - 8);
1188            if !(-qp_bd_offset..=51).contains(&pps.init_qp.saturating_add(h.qp_delta)) {
1189                return Err("SliceQpY out of range".into());
1190            }
1191            if pps.slice_chroma_qp_offsets_present {
1192                h.cb_qp_offset = r.se();
1193                h.cr_qp_offset = r.se();
1194                let sum = |a: i32, b: i32| a.saturating_add(b);
1195                if !(-12..=12).contains(&sum(pps.cb_qp_offset, h.cb_qp_offset))
1196                    || !(-12..=12).contains(&sum(pps.cr_qp_offset, h.cr_qp_offset))
1197                {
1198                    return Err("slice chroma QP offset out of range".into());
1199                }
1200            }
1201            if !pps.chroma_qp_offset_list.is_empty() {
1202                h.cu_chroma_qp_offset = r.flag();
1203            }
1204            let mut override_flag = false;
1205            if pps.deblocking_override_enabled {
1206                override_flag = r.flag();
1207            }
1208            if override_flag {
1209                h.deblocking_disabled = r.flag();
1210                if !h.deblocking_disabled {
1211                    h.beta_offset = r.se().saturating_mul(2);
1212                    h.tc_offset = r.se().saturating_mul(2);
1213                }
1214            }
1215            if pps.loop_filter_across_slices
1216                && (h.sao_luma || h.sao_chroma || !h.deblocking_disabled)
1217            {
1218                h.loop_filter_across_slices = r.flag();
1219            }
1220            h
1221        };
1222        h.num_entry_points = 0;
1223        if pps.tiles || pps.entropy_sync {
1224            let n = r.ue();
1225            h.num_entry_points = n;
1226            if n > 0 {
1227                let len = r.ue().saturating_add(1);
1228                if len > 32 {
1229                    return Err("offset_len_minus1 out of range".into());
1230                }
1231                for _ in 0..n {
1232                    r.skip(len);
1233                }
1234            }
1235        }
1236        if pps.slice_header_extension_present {
1237            let len = r.ue();
1238            r.skip(8 * len);
1239        }
1240        // byte_alignment(): a one bit, then zeros.
1241        r.skip(1);
1242        r.byte_align();
1243        if r.overrun() {
1244            return Err("slice header runs past the NAL".into());
1245        }
1246        h.data_offset = r.pos() / 8;
1247        Ok(h)
1248    }
1249}
1250
1251fn pred_weight_table(r: &mut BitReader, sps: &Sps, h: &SliceHeader) -> Result<PredWeights> {
1252    let mut w = PredWeights {
1253        luma_log2_denom: r.ue(),
1254        ..Default::default()
1255    };
1256    if w.luma_log2_denom > 7 {
1257        return Err("luma_log2_weight_denom out of range".into());
1258    }
1259    let cd = (w.luma_log2_denom as i32).saturating_add(r.se());
1260    if !(0..=7).contains(&cd) {
1261        return Err("chroma weight denominator out of range".into());
1262    }
1263    w.chroma_log2_denom = cd as u32;
1264    // Offsets are coded at 8 bits and scaled up, or with
1265    // high_precision_offsets_enabled_flag at the full bit depth.
1266    let (sy, sc, half) = if sps.high_precision_offsets {
1267        (0, 0, 1 << (sps.bit_depth_c - 1))
1268    } else {
1269        (sps.bit_depth_y as i32 - 8, sps.bit_depth_c as i32 - 8, 128)
1270    };
1271    for l in 0..(1 + (h.slice_type == SliceType::B) as usize) {
1272        let n = h.num_ref_idx[l] as usize;
1273        let luma: Vec<bool> = (0..n).map(|_| r.flag()).collect();
1274        let chroma: Vec<bool> = (0..n).map(|_| r.flag()).collect();
1275        for i in 0..n {
1276            let mut e = [
1277                (1 << w.luma_log2_denom, 0),
1278                (1 << w.chroma_log2_denom, 0),
1279                (1 << w.chroma_log2_denom, 0),
1280            ];
1281            if luma[i] {
1282                e[0].0 += r.se();
1283                e[0].1 = r.se() << sy;
1284            }
1285            if chroma[i] {
1286                for ec in e.iter_mut().skip(1).take(2) {
1287                    let dw = r.se();
1288                    let doff = r.se();
1289                    let wc = (1 << w.chroma_log2_denom) + dw;
1290                    let off =
1291                        (half - ((half * wc) >> w.chroma_log2_denom) + doff).clamp(-half, half - 1);
1292                    *ec = (wc, off << sc);
1293                }
1294            }
1295            w.w[l].push(e);
1296        }
1297    }
1298    Ok(w)
1299}
1300
1301#[cfg(test)]
1302mod tests {
1303    use super::*;
1304
1305    /// `cpb_cnt_minus1` is a loop count, so a value past the spec's 31 has
1306    /// to stop parsing: damage can make it four billion.
1307    #[test]
1308    fn hrd_refuses_a_cpb_count_past_the_limit() {
1309        // nal_hrd = 1, vcl_hrd = 0, sub_pic = 0, 23 skipped bits, then
1310        // fixed_pic_rate_general = 1, elemental_duration ue(0) = 1, and
1311        // cpb_cnt_minus1 as ue(v).
1312        fn hrd(cpb_code: &str) -> Result<()> {
1313            let bits = format!("100{}11{cpb_code}{}", "0".repeat(23), "1".repeat(64));
1314            let bytes: Vec<u8> = bits
1315                .as_bytes()
1316                .chunks(8)
1317                .map(|c| c.iter().fold(0, |b, &d| b << 1 | (d - b'0')) << (8 - c.len()))
1318                .collect();
1319            hrd_parameters(&mut BitReader::new(&bytes), true, 0)
1320        }
1321        assert!(hrd("00000100000").is_ok(), "31 is allowed");
1322        assert!(hrd("00000100001").is_err(), "32 is not");
1323    }
1324}