Skip to main content

threers_codec/decode/av1/
obu.rs

1//! AV1 OBU headers (dav1d `src/obu.c`, `src/getbits.c`): the sequence
2//! header, the uncompressed frame header and tile group headers.
3
4use std::sync::Arc;
5
6use super::msac::{inv_recenter, ulog2};
7
8pub type Res<T> = Result<T, String>;
9
10fn err<T>(m: &str) -> Res<T> {
11    Err(m.to_string())
12}
13
14// ---------------------------------------------------------------- bits
15
16pub struct GetBits<'a> {
17    data: &'a [u8],
18    pub pos: usize, // bit position
19    pub end: usize, // bit end
20    pub error: bool,
21}
22
23impl<'a> GetBits<'a> {
24    pub fn new(data: &'a [u8]) -> Self {
25        GetBits {
26            data,
27            pos: 0,
28            end: data.len() * 8,
29            error: false,
30        }
31    }
32
33    pub fn bit(&mut self) -> u32 {
34        if self.pos >= self.end {
35            self.error = true;
36            return 0;
37        }
38        let b = (self.data[self.pos >> 3] >> (7 - (self.pos & 7))) & 1;
39        self.pos += 1;
40        b as u32
41    }
42
43    pub fn bits(&mut self, n: u32) -> u32 {
44        let mut v = 0u64;
45        for _ in 0..n {
46            v = (v << 1) | self.bit() as u64;
47        }
48        v as u32
49    }
50
51    pub fn sbits(&mut self, n: u32) -> i32 {
52        let v = self.bits(n) as i64;
53        ((v << (64 - n)) >> (64 - n)) as i32
54    }
55
56    pub fn flag(&mut self) -> bool {
57        self.bit() != 0
58    }
59
60    pub fn uleb128(&mut self) -> u32 {
61        let mut val = 0u64;
62        let mut i = 0;
63        loop {
64            let v = self.bits(8);
65            val |= ((v & 0x7f) as u64) << i;
66            i += 7;
67            if v & 0x80 == 0 {
68                break;
69            }
70            if i >= 56 {
71                self.error = true;
72                return 0;
73            }
74        }
75        if val > u32::MAX as u64 {
76            self.error = true;
77            return 0;
78        }
79        val as u32
80    }
81
82    pub fn uniform(&mut self, max: u32) -> u32 {
83        let l = ulog2(max) + 1;
84        let m = (1u32 << l) - max;
85        let v = self.bits(l as u32 - 1);
86        if v < m {
87            v
88        } else {
89            (v << 1) - m + self.bit()
90        }
91    }
92
93    pub fn vlc(&mut self) -> u32 {
94        if self.bit() != 0 {
95            return 0;
96        }
97        let mut n_bits = 0;
98        loop {
99            n_bits += 1;
100            if n_bits == 32 {
101                return u32::MAX;
102            }
103            if self.bit() != 0 {
104                break;
105            }
106        }
107        ((1u32 << n_bits) - 1) + self.bits(n_bits)
108    }
109
110    fn subexp_u(&mut self, r: u32, n: u32) -> u32 {
111        let mut v = 0u32;
112        let mut i = 0;
113        loop {
114            let b = if i != 0 { 3 + i - 1 } else { 3 };
115            if n < v + 3 * (1 << b) {
116                v += self.uniform(n - v + 1);
117                break;
118            }
119            if self.bit() == 0 {
120                v += self.bits(b);
121                break;
122            }
123            v += 1 << b;
124            i += 1;
125        }
126        if r * 2 <= n {
127            inv_recenter(r, v)
128        } else {
129            n - inv_recenter(n - r, v)
130        }
131    }
132
133    pub fn bits_subexp(&mut self, r: i32, n: u32) -> i32 {
134        self.subexp_u((r + (1 << n)) as u32, 2 << n) as i32 - (1 << n)
135    }
136
137    pub fn byte_align(&mut self) {
138        self.pos = (self.pos + 7) & !7;
139    }
140
141    pub fn byte_pos(&self) -> usize {
142        self.pos >> 3
143    }
144}
145
146// ---------------------------------------------------------------- types
147
148#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)]
149pub enum Layout {
150    I400,
151    #[default]
152    I420,
153    I422,
154    I444,
155}
156
157pub const FRAME_KEY: u8 = 0;
158pub const FRAME_INTER: u8 = 1;
159pub const FRAME_INTRA: u8 = 2;
160pub const FRAME_SWITCH: u8 = 3;
161
162pub const ADAPTIVE: u8 = 2;
163pub const PRIMARY_REF_NONE: u8 = 7;
164
165pub const TX_4X4_ONLY: u8 = 0;
166pub const TX_LARGEST: u8 = 1;
167pub const TX_SWITCHABLE: u8 = 2;
168
169pub const WM_IDENTITY: u8 = 0;
170pub const WM_TRANSLATION: u8 = 1;
171pub const WM_ROT_ZOOM: u8 = 2;
172pub const WM_AFFINE: u8 = 3;
173
174pub const RESTORATION_NONE: u8 = 0;
175pub const RESTORATION_SWITCHABLE: u8 = 1;
176pub const RESTORATION_WIENER: u8 = 2;
177pub const RESTORATION_SGRPROJ: u8 = 3;
178
179#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
180pub struct OperatingPoint {
181    pub major_level: u8,
182    pub minor_level: u8,
183    pub initial_display_delay: u8,
184    pub idc: u16,
185    pub tier: u8,
186    pub decoder_model_param_present: bool,
187    pub display_model_param_present: bool,
188}
189
190#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
191pub struct OperatingParameterInfo {
192    pub decoder_buffer_delay: u32,
193    pub encoder_buffer_delay: u32,
194    pub low_delay_mode: bool,
195}
196
197#[derive(Clone, Default, PartialEq, Eq, Debug)]
198pub struct SeqHeader {
199    pub profile: u8,
200    pub max_width: i32,
201    pub max_height: i32,
202    pub layout: Layout,
203    pub pri: u8,
204    pub trc: u8,
205    pub mtrx: u8,
206    pub chr: u8,
207    pub hbd: u8,
208    pub color_range: bool,
209    pub num_operating_points: u8,
210    pub operating_points: Vec<OperatingPoint>,
211    pub still_picture: bool,
212    pub reduced_still_picture_header: bool,
213    pub timing_info_present: bool,
214    pub num_units_in_tick: u32,
215    pub time_scale: u32,
216    pub equal_picture_interval: bool,
217    pub num_ticks_per_picture: u32,
218    pub decoder_model_info_present: bool,
219    pub encoder_decoder_buffer_delay_length: u8,
220    pub num_units_in_decoding_tick: u32,
221    pub buffer_removal_delay_length: u8,
222    pub frame_presentation_delay_length: u8,
223    pub display_model_info_present: bool,
224    pub width_n_bits: u8,
225    pub height_n_bits: u8,
226    pub frame_id_numbers_present: bool,
227    pub delta_frame_id_n_bits: u8,
228    pub frame_id_n_bits: u8,
229    pub sb128: bool,
230    pub filter_intra: bool,
231    pub intra_edge_filter: bool,
232    pub inter_intra: bool,
233    pub masked_compound: bool,
234    pub warped_motion: bool,
235    pub dual_filter: bool,
236    pub order_hint: bool,
237    pub jnt_comp: bool,
238    pub ref_frame_mvs: bool,
239    pub screen_content_tools: u8,
240    pub force_integer_mv: u8,
241    pub order_hint_n_bits: u8,
242    pub super_res: bool,
243    pub cdef: bool,
244    pub restoration: bool,
245    pub ss_hor: u8,
246    pub ss_ver: u8,
247    pub monochrome: bool,
248    pub color_description_present: bool,
249    pub separate_uv_delta_q: bool,
250    pub film_grain_present: bool,
251    pub operating_parameter_info: Vec<OperatingParameterInfo>,
252}
253
254impl SeqHeader {
255    /// Everything but `operating_parameter_info` (dav1d's memcmp).
256    pub fn same_sequence(&self, o: &SeqHeader) -> bool {
257        let mut a = self.clone();
258        a.operating_parameter_info = o.operating_parameter_info.clone();
259        a == *o
260    }
261}
262
263#[derive(Clone, Copy, Debug, PartialEq, Eq)]
264pub struct WarpedMotionParams {
265    pub typ: u8,
266    pub matrix: [i32; 6],
267    /// alpha, beta, gamma, delta.
268    pub abcd: [i16; 4],
269}
270
271pub const DEFAULT_WM_PARAMS: WarpedMotionParams = WarpedMotionParams {
272    typ: WM_IDENTITY,
273    matrix: [0, 0, 1 << 16, 0, 0, 1 << 16],
274    abcd: [0; 4],
275};
276
277impl Default for WarpedMotionParams {
278    fn default() -> Self {
279        DEFAULT_WM_PARAMS
280    }
281}
282
283#[derive(Clone, Copy, Default, Debug)]
284pub struct SegmentationData {
285    pub delta_q: i16,
286    pub delta_lf_y_v: i8,
287    pub delta_lf_y_h: i8,
288    pub delta_lf_u: i8,
289    pub delta_lf_v: i8,
290    pub r#ref: i8,
291    pub skip: bool,
292    pub globalmv: bool,
293    /// Which features the segment enables, `FeatureEnabled[i][j]` as bit `j`:
294    /// 0 alt Q, 1–4 the loop filter deltas, 5 reference, 6 skip, 7 global MV.
295    /// Values alone cannot say: a feature can be enabled with value 0.
296    pub enabled: u8,
297}
298
299#[derive(Clone, Copy, Default, Debug)]
300pub struct SegmentationDataSet {
301    pub d: [SegmentationData; 8],
302    pub preskip: bool,
303    pub last_active_segid: i8,
304}
305
306#[derive(Clone, Copy, Default, Debug)]
307pub struct LoopfilterModeRefDeltas {
308    pub mode_delta: [i8; 2],
309    pub ref_delta: [i8; 8],
310}
311
312pub const DEFAULT_MODE_REF_DELTAS: LoopfilterModeRefDeltas = LoopfilterModeRefDeltas {
313    mode_delta: [0, 0],
314    ref_delta: [1, 0, 0, 0, -1, 0, -1, -1],
315};
316
317#[derive(Clone, Copy, Default, Debug)]
318pub struct FilmGrainData {
319    pub seed: u32,
320    pub num_y_points: i32,
321    pub y_points: [[u8; 2]; 14],
322    pub chroma_scaling_from_luma: bool,
323    pub num_uv_points: [i32; 2],
324    pub uv_points: [[[u8; 2]; 10]; 2],
325    pub scaling_shift: i32,
326    pub ar_coeff_lag: i32,
327    pub ar_coeffs_y: [i8; 24],
328    pub ar_coeffs_uv: [[i8; 28]; 2],
329    pub ar_coeff_shift: u64,
330    pub grain_scale_shift: i32,
331    pub uv_mult: [i32; 2],
332    pub uv_luma_mult: [i32; 2],
333    pub uv_offset: [i32; 2],
334    pub overlap_flag: bool,
335    pub clip_to_restricted_range: bool,
336}
337
338#[derive(Clone, Debug)]
339pub struct Tiling {
340    pub uniform: bool,
341    pub n_bytes: u8,
342    pub min_log2_cols: u8,
343    pub max_log2_cols: u8,
344    pub log2_cols: u8,
345    pub cols: u8,
346    pub min_log2_rows: u8,
347    pub max_log2_rows: u8,
348    pub log2_rows: u8,
349    pub rows: u8,
350    pub col_start_sb: [u16; 65],
351    pub row_start_sb: [u16; 65],
352    pub update: u16,
353}
354
355impl Default for Tiling {
356    fn default() -> Self {
357        Tiling {
358            uniform: false,
359            n_bytes: 0,
360            min_log2_cols: 0,
361            max_log2_cols: 0,
362            log2_cols: 0,
363            cols: 0,
364            min_log2_rows: 0,
365            max_log2_rows: 0,
366            log2_rows: 0,
367            rows: 0,
368            col_start_sb: [0; 65],
369            row_start_sb: [0; 65],
370            update: 0,
371        }
372    }
373}
374
375#[derive(Clone, Copy, Default, Debug)]
376pub struct Quant {
377    pub yac: u8,
378    pub ydc_delta: i8,
379    pub udc_delta: i8,
380    pub uac_delta: i8,
381    pub vdc_delta: i8,
382    pub vac_delta: i8,
383    pub qm: bool,
384    pub qm_y: u8,
385    pub qm_u: u8,
386    pub qm_v: u8,
387}
388
389#[derive(Clone, Copy, Default, Debug)]
390pub struct Segmentation {
391    pub enabled: bool,
392    pub update_map: bool,
393    pub temporal: bool,
394    pub update_data: bool,
395    pub seg_data: SegmentationDataSet,
396    pub lossless: [bool; 8],
397    pub qidx: [u8; 8],
398}
399
400#[derive(Clone, Copy, Default, Debug)]
401pub struct Delta {
402    pub q_present: bool,
403    pub q_res_log2: u8,
404    pub lf_present: bool,
405    pub lf_res_log2: u8,
406    pub lf_multi: bool,
407}
408
409#[derive(Clone, Copy, Default, Debug)]
410pub struct Loopfilter {
411    pub level_y: [u8; 2],
412    pub level_u: u8,
413    pub level_v: u8,
414    pub mode_ref_delta_enabled: bool,
415    pub mode_ref_delta_update: bool,
416    pub mode_ref_deltas: LoopfilterModeRefDeltas,
417    pub sharpness: u8,
418}
419
420#[derive(Clone, Copy, Default, Debug)]
421pub struct Cdef {
422    pub damping: u8,
423    pub n_bits: u8,
424    pub y_strength: [u8; 8],
425    pub uv_strength: [u8; 8],
426}
427
428#[derive(Clone, Copy, Default, Debug)]
429pub struct Restoration {
430    pub typ: [u8; 3],
431    pub unit_size: [u8; 2],
432}
433
434#[derive(Clone, Default, Debug)]
435pub struct FrameHeader {
436    pub film_grain: FilmGrainData,
437    pub film_grain_present: bool,
438    pub film_grain_update: bool,
439    pub frame_type: u8,
440    /// coded width, superres-upscaled width.
441    pub width: [i32; 2],
442    pub height: i32,
443    pub frame_offset: u8,
444    pub temporal_id: u8,
445    pub spatial_id: u8,
446    pub show_existing_frame: bool,
447    pub existing_frame_idx: u8,
448    pub frame_id: u32,
449    pub frame_presentation_delay: u32,
450    pub show_frame: bool,
451    pub showable_frame: bool,
452    pub error_resilient_mode: bool,
453    pub disable_cdf_update: bool,
454    pub allow_screen_content_tools: bool,
455    pub force_integer_mv: bool,
456    pub frame_size_override: bool,
457    pub primary_ref_frame: u8,
458    pub buffer_removal_time_present: bool,
459    pub refresh_frame_flags: u8,
460    pub render_width: i32,
461    pub render_height: i32,
462    pub super_res_width_scale_denominator: u8,
463    pub super_res_enabled: bool,
464    pub have_render_size: bool,
465    pub allow_intrabc: bool,
466    pub frame_ref_short_signaling: bool,
467    pub refidx: [i8; 7],
468    pub hp: bool,
469    pub subpel_filter_mode: u8,
470    pub switchable_motion_mode: bool,
471    pub use_ref_frame_mvs: bool,
472    pub refresh_context: bool,
473    pub tiling: Tiling,
474    pub quant: Quant,
475    pub segmentation: Segmentation,
476    pub delta: Delta,
477    pub all_lossless: bool,
478    pub loopfilter: Loopfilter,
479    pub cdef: Cdef,
480    pub restoration: Restoration,
481    pub txfm_mode: u8,
482    pub switchable_comp_refs: bool,
483    pub skip_mode_allowed: bool,
484    pub skip_mode_enabled: bool,
485    pub skip_mode_refs: [i8; 2],
486    pub warp_motion: bool,
487    pub reduced_txtp_set: bool,
488    pub gmv: [WarpedMotionParams; 7],
489}
490
491impl FrameHeader {
492    pub fn is_key_or_intra(&self) -> bool {
493        self.frame_type & 1 == 0
494    }
495    pub fn is_inter_or_switch(&self) -> bool {
496        self.frame_type & 1 != 0
497    }
498}
499
500pub fn get_poc_diff(order_hint_n_bits: u8, poc0: i32, poc1: i32) -> i32 {
501    if order_hint_n_bits == 0 {
502        return 0;
503    }
504    let mask = 1 << (order_hint_n_bits - 1);
505    let diff = poc0 - poc1;
506    (diff & (mask - 1)) - (diff & mask)
507}
508
509fn check_trailing_bits(gb: &mut GetBits) -> Res<()> {
510    gb.bit();
511    if gb.error {
512        return err("trailing bits overrun");
513    }
514    Ok(())
515}
516
517// ---------------------------------------------------------------- sequence header
518
519pub fn parse_seq_hdr(gb: &mut GetBits) -> Res<SeqHeader> {
520    let mut h = SeqHeader {
521        operating_points: vec![OperatingPoint::default(); 32],
522        operating_parameter_info: vec![OperatingParameterInfo::default(); 32],
523        ..Default::default()
524    };
525    h.profile = gb.bits(3) as u8;
526    if h.profile > 2 {
527        return err("bad profile");
528    }
529    h.still_picture = gb.flag();
530    h.reduced_still_picture_header = gb.flag();
531    if h.reduced_still_picture_header && !h.still_picture {
532        return err("bad still picture flags");
533    }
534    if h.reduced_still_picture_header {
535        h.num_operating_points = 1;
536        h.operating_points[0].major_level = gb.bits(3) as u8;
537        h.operating_points[0].minor_level = gb.bits(2) as u8;
538        h.operating_points[0].initial_display_delay = 10;
539    } else {
540        h.timing_info_present = gb.flag();
541        if h.timing_info_present {
542            h.num_units_in_tick = gb.bits(32);
543            h.time_scale = gb.bits(32);
544            h.equal_picture_interval = gb.flag();
545            if h.equal_picture_interval {
546                let n = gb.vlc();
547                if n == u32::MAX {
548                    return err("bad num_ticks_per_picture");
549                }
550                h.num_ticks_per_picture = n + 1;
551            }
552            h.decoder_model_info_present = gb.flag();
553            if h.decoder_model_info_present {
554                h.encoder_decoder_buffer_delay_length = gb.bits(5) as u8 + 1;
555                h.num_units_in_decoding_tick = gb.bits(32);
556                h.buffer_removal_delay_length = gb.bits(5) as u8 + 1;
557                h.frame_presentation_delay_length = gb.bits(5) as u8 + 1;
558            }
559        }
560        h.display_model_info_present = gb.flag();
561        h.num_operating_points = gb.bits(5) as u8 + 1;
562        for i in 0..h.num_operating_points as usize {
563            let mut op = OperatingPoint {
564                idc: gb.bits(12) as u16,
565                ..Default::default()
566            };
567            if op.idc != 0 && (op.idc & 0xff == 0 || op.idc & 0xf00 == 0) {
568                return err("bad operating point idc");
569            }
570            op.major_level = 2 + gb.bits(3) as u8;
571            op.minor_level = gb.bits(2) as u8;
572            if op.major_level > 3 {
573                op.tier = gb.bit() as u8;
574            }
575            if h.decoder_model_info_present {
576                op.decoder_model_param_present = gb.flag();
577                if op.decoder_model_param_present {
578                    let n = h.encoder_decoder_buffer_delay_length as u32;
579                    let opi = &mut h.operating_parameter_info[i];
580                    opi.decoder_buffer_delay = gb.bits(n);
581                    opi.encoder_buffer_delay = gb.bits(n);
582                    opi.low_delay_mode = gb.flag();
583                }
584            }
585            if h.display_model_info_present {
586                op.display_model_param_present = gb.flag();
587            }
588            op.initial_display_delay = if op.display_model_param_present {
589                gb.bits(4) as u8 + 1
590            } else {
591                10
592            };
593            h.operating_points[i] = op;
594        }
595    }
596    h.width_n_bits = gb.bits(4) as u8 + 1;
597    h.height_n_bits = gb.bits(4) as u8 + 1;
598    h.max_width = gb.bits(h.width_n_bits as u32) as i32 + 1;
599    h.max_height = gb.bits(h.height_n_bits as u32) as i32 + 1;
600    if !h.reduced_still_picture_header {
601        h.frame_id_numbers_present = gb.flag();
602        if h.frame_id_numbers_present {
603            h.delta_frame_id_n_bits = gb.bits(4) as u8 + 2;
604            h.frame_id_n_bits = gb.bits(3) as u8 + h.delta_frame_id_n_bits + 1;
605        }
606    }
607    h.sb128 = gb.flag();
608    h.filter_intra = gb.flag();
609    h.intra_edge_filter = gb.flag();
610    if h.reduced_still_picture_header {
611        h.screen_content_tools = ADAPTIVE;
612        h.force_integer_mv = ADAPTIVE;
613    } else {
614        h.inter_intra = gb.flag();
615        h.masked_compound = gb.flag();
616        h.warped_motion = gb.flag();
617        h.dual_filter = gb.flag();
618        h.order_hint = gb.flag();
619        if h.order_hint {
620            h.jnt_comp = gb.flag();
621            h.ref_frame_mvs = gb.flag();
622        }
623        h.screen_content_tools = if gb.flag() { ADAPTIVE } else { gb.bit() as u8 };
624        h.force_integer_mv = if h.screen_content_tools != 0 {
625            if gb.flag() {
626                ADAPTIVE
627            } else {
628                gb.bit() as u8
629            }
630        } else {
631            2
632        };
633        if h.order_hint {
634            h.order_hint_n_bits = gb.bits(3) as u8 + 1;
635        }
636    }
637    h.super_res = gb.flag();
638    h.cdef = gb.flag();
639    h.restoration = gb.flag();
640
641    h.hbd = gb.bit() as u8;
642    if h.profile == 2 && h.hbd != 0 {
643        h.hbd += gb.bit() as u8;
644    }
645    if h.profile != 1 {
646        h.monochrome = gb.flag();
647    }
648    h.color_description_present = gb.flag();
649    if h.color_description_present {
650        h.pri = gb.bits(8) as u8;
651        h.trc = gb.bits(8) as u8;
652        h.mtrx = gb.bits(8) as u8;
653    } else {
654        h.pri = 2;
655        h.trc = 2;
656        h.mtrx = 2;
657    }
658    if h.monochrome {
659        h.color_range = gb.flag();
660        h.layout = Layout::I400;
661        h.ss_hor = 1;
662        h.ss_ver = 1;
663        h.chr = 0;
664    } else if h.pri == 1 && h.trc == 13 && h.mtrx == 0 {
665        h.layout = Layout::I444;
666        h.color_range = true;
667        if h.profile != 1 && !(h.profile == 2 && h.hbd == 2) {
668            return err("sRGB needs 4:4:4 profile");
669        }
670    } else {
671        h.color_range = gb.flag();
672        match h.profile {
673            0 => {
674                h.layout = Layout::I420;
675                h.ss_hor = 1;
676                h.ss_ver = 1;
677            }
678            1 => h.layout = Layout::I444,
679            _ => {
680                if h.hbd == 2 {
681                    h.ss_hor = gb.bit() as u8;
682                    if h.ss_hor != 0 {
683                        h.ss_ver = gb.bit() as u8;
684                    }
685                } else {
686                    h.ss_hor = 1;
687                }
688                h.layout = if h.ss_hor != 0 {
689                    if h.ss_ver != 0 {
690                        Layout::I420
691                    } else {
692                        Layout::I422
693                    }
694                } else {
695                    Layout::I444
696                };
697            }
698        }
699        h.chr = if h.ss_hor & h.ss_ver != 0 {
700            gb.bits(2) as u8
701        } else {
702            0
703        };
704    }
705    if !h.monochrome {
706        h.separate_uv_delta_q = gb.flag();
707    }
708    h.film_grain_present = gb.flag();
709    check_trailing_bits(gb)?;
710    Ok(h)
711}
712
713// ---------------------------------------------------------------- frame header
714
715/// The reference slots' headers, as the parser needs them.
716pub type RefHeaders = [Option<Arc<FrameHeader>>; 8];
717
718fn tile_log2(sz: i32, tgt: i32) -> u8 {
719    let mut k = 0;
720    while (sz << k) < tgt {
721        k += 1;
722    }
723    k
724}
725
726fn read_frame_size(
727    seq: &SeqHeader,
728    refs: &RefHeaders,
729    h: &mut FrameHeader,
730    gb: &mut GetBits,
731    use_ref: bool,
732) -> Res<()> {
733    if use_ref {
734        for i in 0..7 {
735            if gb.flag() {
736                let r = refs[h.refidx[i] as usize]
737                    .as_ref()
738                    .ok_or("missing reference")?;
739                h.width[1] = r.width[1];
740                h.height = r.height;
741                h.render_width = r.render_width;
742                h.render_height = r.render_height;
743                h.super_res_enabled = seq.super_res && gb.flag();
744                if h.super_res_enabled {
745                    let d = 9 + gb.bits(3) as i32;
746                    h.super_res_width_scale_denominator = d as u8;
747                    h.width[0] = ((h.width[1] * 8 + (d >> 1)) / d).max(16.min(h.width[1]));
748                } else {
749                    h.super_res_width_scale_denominator = 8;
750                    h.width[0] = h.width[1];
751                }
752                return Ok(());
753            }
754        }
755    }
756    if h.frame_size_override {
757        h.width[1] = gb.bits(seq.width_n_bits as u32) as i32 + 1;
758        h.height = gb.bits(seq.height_n_bits as u32) as i32 + 1;
759    } else {
760        h.width[1] = seq.max_width;
761        h.height = seq.max_height;
762    }
763    h.super_res_enabled = seq.super_res && gb.flag();
764    if h.super_res_enabled {
765        let d = 9 + gb.bits(3) as i32;
766        h.super_res_width_scale_denominator = d as u8;
767        h.width[0] = ((h.width[1] * 8 + (d >> 1)) / d).max(16.min(h.width[1]));
768    } else {
769        h.super_res_width_scale_denominator = 8;
770        h.width[0] = h.width[1];
771    }
772    h.have_render_size = gb.flag();
773    if h.have_render_size {
774        h.render_width = gb.bits(16) as i32 + 1;
775        h.render_height = gb.bits(16) as i32 + 1;
776    } else {
777        h.render_width = h.width[1];
778        h.render_height = h.height;
779    }
780    Ok(())
781}
782
783pub fn parse_frame_hdr(
784    seq: &SeqHeader,
785    refs: &RefHeaders,
786    gb: &mut GetBits,
787    temporal_id: u8,
788    spatial_id: u8,
789) -> Res<FrameHeader> {
790    let mut h = FrameHeader {
791        temporal_id,
792        spatial_id,
793        ..Default::default()
794    };
795    let rf = |i: usize| -> Res<&Arc<FrameHeader>> {
796        refs[i]
797            .as_ref()
798            .ok_or_else(|| "missing reference".to_string())
799    };
800
801    h.show_existing_frame = !seq.reduced_still_picture_header && gb.flag();
802    if h.show_existing_frame {
803        h.existing_frame_idx = gb.bits(3) as u8;
804        if seq.decoder_model_info_present && !seq.equal_picture_interval {
805            h.frame_presentation_delay = gb.bits(seq.frame_presentation_delay_length as u32);
806        }
807        if seq.frame_id_numbers_present {
808            h.frame_id = gb.bits(seq.frame_id_n_bits as u32);
809            let r = rf(h.existing_frame_idx as usize)?;
810            if r.frame_id != h.frame_id {
811                return err("frame id mismatch");
812            }
813        }
814        return Ok(h);
815    }
816
817    h.frame_type = if seq.reduced_still_picture_header {
818        FRAME_KEY
819    } else {
820        gb.bits(2) as u8
821    };
822    h.show_frame = seq.reduced_still_picture_header || gb.flag();
823    if h.show_frame {
824        if seq.decoder_model_info_present && !seq.equal_picture_interval {
825            h.frame_presentation_delay = gb.bits(seq.frame_presentation_delay_length as u32);
826        }
827        h.showable_frame = h.frame_type != FRAME_KEY;
828    } else {
829        h.showable_frame = gb.flag();
830    }
831    h.error_resilient_mode = (h.frame_type == FRAME_KEY && h.show_frame)
832        || h.frame_type == FRAME_SWITCH
833        || seq.reduced_still_picture_header
834        || gb.flag();
835    h.disable_cdf_update = gb.flag();
836    h.allow_screen_content_tools = if seq.screen_content_tools == ADAPTIVE {
837        gb.flag()
838    } else {
839        seq.screen_content_tools != 0
840    };
841    h.force_integer_mv = if h.allow_screen_content_tools {
842        if seq.force_integer_mv == ADAPTIVE {
843            gb.flag()
844        } else {
845            seq.force_integer_mv != 0
846        }
847    } else {
848        false
849    };
850    if h.is_key_or_intra() {
851        h.force_integer_mv = true;
852    }
853    if seq.frame_id_numbers_present {
854        h.frame_id = gb.bits(seq.frame_id_n_bits as u32);
855    }
856    h.frame_size_override = if seq.reduced_still_picture_header {
857        false
858    } else if h.frame_type == FRAME_SWITCH {
859        true
860    } else {
861        gb.flag()
862    };
863    h.frame_offset = if seq.order_hint {
864        gb.bits(seq.order_hint_n_bits as u32) as u8
865    } else {
866        0
867    };
868    h.primary_ref_frame = if !h.error_resilient_mode && h.is_inter_or_switch() {
869        gb.bits(3) as u8
870    } else {
871        PRIMARY_REF_NONE
872    };
873
874    if seq.decoder_model_info_present {
875        h.buffer_removal_time_present = gb.flag();
876        if h.buffer_removal_time_present {
877            for i in 0..seq.num_operating_points as usize {
878                let sop = &seq.operating_points[i];
879                if sop.decoder_model_param_present {
880                    let in_t = (sop.idc >> h.temporal_id) & 1;
881                    let in_s = (sop.idc >> (h.spatial_id + 8)) & 1;
882                    if sop.idc == 0 || (in_t != 0 && in_s != 0) {
883                        gb.bits(seq.buffer_removal_delay_length as u32);
884                    }
885                }
886            }
887        }
888    }
889
890    if h.is_key_or_intra() {
891        h.refresh_frame_flags = if h.frame_type == FRAME_KEY && h.show_frame {
892            0xff
893        } else {
894            gb.bits(8) as u8
895        };
896        if h.refresh_frame_flags != 0xff && h.error_resilient_mode && seq.order_hint {
897            for _ in 0..8 {
898                gb.bits(seq.order_hint_n_bits as u32);
899            }
900        }
901        read_frame_size(seq, refs, &mut h, gb, false)?;
902        h.allow_intrabc = h.allow_screen_content_tools && !h.super_res_enabled && gb.flag();
903        h.use_ref_frame_mvs = false;
904    } else {
905        h.allow_intrabc = false;
906        h.refresh_frame_flags = if h.frame_type == FRAME_SWITCH {
907            0xff
908        } else {
909            gb.bits(8) as u8
910        };
911        if h.error_resilient_mode && seq.order_hint {
912            for _ in 0..8 {
913                gb.bits(seq.order_hint_n_bits as u32);
914            }
915        }
916        h.frame_ref_short_signaling = seq.order_hint && gb.flag();
917        if h.frame_ref_short_signaling {
918            h.refidx[0] = gb.bits(3) as i8;
919            h.refidx[1] = -1;
920            h.refidx[2] = -1;
921            h.refidx[3] = gb.bits(3) as i8;
922            h.refidx[4] = -1;
923            h.refidx[5] = -1;
924            h.refidx[6] = -1;
925            let mut shifted = [0i32; 8];
926            let cur = 1 << (seq.order_hint_n_bits - 1);
927            for (i, s) in shifted.iter_mut().enumerate() {
928                let r = rf(i)?;
929                *s = cur
930                    + get_poc_diff(
931                        seq.order_hint_n_bits,
932                        r.frame_offset as i32,
933                        h.frame_offset as i32,
934                    );
935            }
936            let mut used = [false; 8];
937            used[h.refidx[0] as usize] = true;
938            used[h.refidx[3] as usize] = true;
939            let mut latest = -1;
940            for (i, &hint) in shifted.iter().enumerate() {
941                if !used[i] && hint >= cur && hint >= latest {
942                    h.refidx[6] = i as i8;
943                    latest = hint;
944                }
945            }
946            if latest != -1 {
947                used[h.refidx[6] as usize] = true;
948            }
949            let mut earliest = i32::MAX;
950            for (i, &hint) in shifted.iter().enumerate() {
951                if !used[i] && hint >= cur && hint < earliest {
952                    h.refidx[4] = i as i8;
953                    earliest = hint;
954                }
955            }
956            if earliest != i32::MAX {
957                used[h.refidx[4] as usize] = true;
958            }
959            earliest = i32::MAX;
960            for (i, &hint) in shifted.iter().enumerate() {
961                if !used[i] && hint >= cur && hint < earliest {
962                    h.refidx[5] = i as i8;
963                    earliest = hint;
964                }
965            }
966            if earliest != i32::MAX {
967                used[h.refidx[5] as usize] = true;
968            }
969            for i in 1..7 {
970                if h.refidx[i] < 0 {
971                    latest = -1;
972                    for (j, &hint) in shifted.iter().enumerate() {
973                        if !used[j] && hint < cur && hint >= latest {
974                            h.refidx[i] = j as i8;
975                            latest = hint;
976                        }
977                    }
978                    if latest != -1 {
979                        used[h.refidx[i] as usize] = true;
980                    }
981                }
982            }
983            earliest = i32::MAX;
984            let mut r = -1i8;
985            for (i, &hint) in shifted.iter().enumerate() {
986                if hint < earliest {
987                    r = i as i8;
988                    earliest = hint;
989                }
990            }
991            for x in h.refidx.iter_mut() {
992                if *x < 0 {
993                    *x = r;
994                }
995            }
996        }
997        for i in 0..7 {
998            if !h.frame_ref_short_signaling {
999                h.refidx[i] = gb.bits(3) as i8;
1000            }
1001            if seq.frame_id_numbers_present {
1002                let delta = gb.bits(seq.delta_frame_id_n_bits as u32) + 1;
1003                let n = seq.frame_id_n_bits as u32;
1004                let ref_id = (h.frame_id + (1 << n) - delta) & ((1 << n) - 1);
1005                if rf(h.refidx[i] as usize)?.frame_id != ref_id {
1006                    return err("reference frame id mismatch");
1007                }
1008            }
1009        }
1010        let use_ref = !h.error_resilient_mode && h.frame_size_override;
1011        read_frame_size(seq, refs, &mut h, gb, use_ref)?;
1012        h.hp = !h.force_integer_mv && gb.flag();
1013        h.subpel_filter_mode = if gb.flag() {
1014            super::levels::FILTER_SWITCHABLE
1015        } else {
1016            gb.bits(2) as u8
1017        };
1018        h.switchable_motion_mode = gb.flag();
1019        h.use_ref_frame_mvs = !h.error_resilient_mode
1020            && seq.ref_frame_mvs
1021            && seq.order_hint
1022            && h.is_inter_or_switch()
1023            && gb.flag();
1024    }
1025
1026    h.refresh_context = !seq.reduced_still_picture_header && !h.disable_cdf_update && !gb.flag();
1027
1028    // Tiling.
1029    let t = &mut h.tiling;
1030    t.uniform = gb.flag();
1031    let sbsz_min1 = (64 << seq.sb128 as i32) - 1;
1032    let sbsz_log2 = 6 + seq.sb128 as i32;
1033    let sbw = (h.width[0] + sbsz_min1) >> sbsz_log2;
1034    let sbh = (h.height + sbsz_min1) >> sbsz_log2;
1035    let max_tile_width_sb = 4096 >> sbsz_log2;
1036    let max_tile_area_sb = (4096 * 2304) >> (2 * sbsz_log2);
1037    t.min_log2_cols = tile_log2(max_tile_width_sb, sbw);
1038    t.max_log2_cols = tile_log2(1, sbw.min(64));
1039    t.max_log2_rows = tile_log2(1, sbh.min(64));
1040    let min_log2_tiles =
1041        (tile_log2(max_tile_area_sb, sbw * sbh) as i32).max(t.min_log2_cols as i32);
1042    if t.uniform {
1043        t.log2_cols = t.min_log2_cols;
1044        while t.log2_cols < t.max_log2_cols && gb.flag() {
1045            t.log2_cols += 1;
1046        }
1047        let tile_w = 1 + ((sbw - 1) >> t.log2_cols);
1048        t.cols = 0;
1049        let mut sbx = 0;
1050        while sbx < sbw {
1051            t.col_start_sb[t.cols as usize] = sbx as u16;
1052            sbx += tile_w;
1053            t.cols += 1;
1054        }
1055        t.min_log2_rows = (min_log2_tiles - t.log2_cols as i32).max(0) as u8;
1056        t.log2_rows = t.min_log2_rows;
1057        while t.log2_rows < t.max_log2_rows && gb.flag() {
1058            t.log2_rows += 1;
1059        }
1060        let tile_h = 1 + ((sbh - 1) >> t.log2_rows);
1061        t.rows = 0;
1062        let mut sby = 0;
1063        while sby < sbh {
1064            t.row_start_sb[t.rows as usize] = sby as u16;
1065            sby += tile_h;
1066            t.rows += 1;
1067        }
1068    } else {
1069        t.cols = 0;
1070        let mut widest = 0;
1071        let mut max_area = sbw * sbh;
1072        let mut sbx = 0;
1073        while sbx < sbw && t.cols < 64 {
1074            let tw_sb = (sbw - sbx).min(max_tile_width_sb);
1075            let tile_w = if tw_sb > 1 {
1076                1 + gb.uniform(tw_sb as u32) as i32
1077            } else {
1078                1
1079            };
1080            t.col_start_sb[t.cols as usize] = sbx as u16;
1081            sbx += tile_w;
1082            widest = widest.max(tile_w);
1083            t.cols += 1;
1084        }
1085        t.log2_cols = tile_log2(1, t.cols as i32);
1086        if min_log2_tiles != 0 {
1087            max_area >>= min_log2_tiles + 1;
1088        }
1089        let max_tile_height_sb = (max_area / widest).max(1);
1090        t.rows = 0;
1091        let mut sby = 0;
1092        while sby < sbh && t.rows < 64 {
1093            let th_sb = (sbh - sby).min(max_tile_height_sb);
1094            let tile_h = if th_sb > 1 {
1095                1 + gb.uniform(th_sb as u32) as i32
1096            } else {
1097                1
1098            };
1099            t.row_start_sb[t.rows as usize] = sby as u16;
1100            sby += tile_h;
1101            t.rows += 1;
1102        }
1103        t.log2_rows = tile_log2(1, t.rows as i32);
1104    }
1105    t.col_start_sb[t.cols as usize] = sbw as u16;
1106    t.row_start_sb[t.rows as usize] = sbh as u16;
1107    if t.log2_cols != 0 || t.log2_rows != 0 {
1108        t.update = gb.bits((t.log2_cols + t.log2_rows) as u32) as u16;
1109        if t.update as i32 >= t.cols as i32 * t.rows as i32 {
1110            return err("bad context_update_tile_id");
1111        }
1112        t.n_bytes = gb.bits(2) as u8 + 1;
1113    } else {
1114        t.n_bytes = 0;
1115        t.update = 0;
1116    }
1117
1118    // Quantisation.
1119    let q = &mut h.quant;
1120    q.yac = gb.bits(8) as u8;
1121    q.ydc_delta = if gb.flag() { gb.sbits(7) as i8 } else { 0 };
1122    if !seq.monochrome {
1123        let diff_uv = seq.separate_uv_delta_q && gb.flag();
1124        q.udc_delta = if gb.flag() { gb.sbits(7) as i8 } else { 0 };
1125        q.uac_delta = if gb.flag() { gb.sbits(7) as i8 } else { 0 };
1126        if diff_uv {
1127            q.vdc_delta = if gb.flag() { gb.sbits(7) as i8 } else { 0 };
1128            q.vac_delta = if gb.flag() { gb.sbits(7) as i8 } else { 0 };
1129        } else {
1130            q.vdc_delta = q.udc_delta;
1131            q.vac_delta = q.uac_delta;
1132        }
1133    }
1134    q.qm = gb.flag();
1135    if q.qm {
1136        q.qm_y = gb.bits(4) as u8;
1137        q.qm_u = gb.bits(4) as u8;
1138        q.qm_v = if seq.separate_uv_delta_q {
1139            gb.bits(4) as u8
1140        } else {
1141            q.qm_u
1142        };
1143    }
1144
1145    // Segmentation.
1146    let s = &mut h.segmentation;
1147    s.enabled = gb.flag();
1148    if s.enabled {
1149        if h.primary_ref_frame == PRIMARY_REF_NONE {
1150            s.update_map = true;
1151            s.temporal = false;
1152            s.update_data = true;
1153        } else {
1154            s.update_map = gb.flag();
1155            s.temporal = s.update_map && gb.flag();
1156            s.update_data = gb.flag();
1157        }
1158        if s.update_data {
1159            s.seg_data.preskip = false;
1160            s.seg_data.last_active_segid = -1;
1161            for i in 0..8 {
1162                let seg = &mut s.seg_data.d[i];
1163                seg.enabled = 0;
1164                if gb.flag() {
1165                    seg.enabled |= 1;
1166                    seg.delta_q = gb.sbits(9) as i16;
1167                    s.seg_data.last_active_segid = i as i8;
1168                } else {
1169                    seg.delta_q = 0;
1170                }
1171                for k in 0..4 {
1172                    let v = if gb.flag() {
1173                        seg.enabled |= 2 << k;
1174                        s.seg_data.last_active_segid = i as i8;
1175                        gb.sbits(7) as i8
1176                    } else {
1177                        0
1178                    };
1179                    match k {
1180                        0 => seg.delta_lf_y_v = v,
1181                        1 => seg.delta_lf_y_h = v,
1182                        2 => seg.delta_lf_u = v,
1183                        _ => seg.delta_lf_v = v,
1184                    }
1185                }
1186                if gb.flag() {
1187                    seg.enabled |= 1 << 5;
1188                    seg.r#ref = gb.bits(3) as i8;
1189                    s.seg_data.last_active_segid = i as i8;
1190                    s.seg_data.preskip = true;
1191                } else {
1192                    seg.r#ref = -1;
1193                }
1194                seg.skip = gb.flag();
1195                seg.enabled |= (seg.skip as u8) << 6;
1196                if seg.skip {
1197                    s.seg_data.last_active_segid = i as i8;
1198                    s.seg_data.preskip = true;
1199                }
1200                seg.globalmv = gb.flag();
1201                seg.enabled |= (seg.globalmv as u8) << 7;
1202                if seg.globalmv {
1203                    s.seg_data.last_active_segid = i as i8;
1204                    s.seg_data.preskip = true;
1205                }
1206            }
1207        } else {
1208            let pri = h.refidx[h.primary_ref_frame as usize] as usize;
1209            s.seg_data = rf(pri)?.segmentation.seg_data;
1210        }
1211    } else {
1212        s.seg_data = SegmentationDataSet::default();
1213        for d in s.seg_data.d.iter_mut() {
1214            d.r#ref = -1;
1215        }
1216    }
1217
1218    // Delta q / lf.
1219    h.delta.q_present = h.quant.yac != 0 && gb.flag();
1220    h.delta.q_res_log2 = if h.delta.q_present {
1221        gb.bits(2) as u8
1222    } else {
1223        0
1224    };
1225    h.delta.lf_present = h.delta.q_present && !h.allow_intrabc && gb.flag();
1226    h.delta.lf_res_log2 = if h.delta.lf_present {
1227        gb.bits(2) as u8
1228    } else {
1229        0
1230    };
1231    h.delta.lf_multi = h.delta.lf_present && gb.flag();
1232
1233    let q = &h.quant;
1234    let delta_lossless = q.ydc_delta == 0
1235        && q.udc_delta == 0
1236        && q.uac_delta == 0
1237        && q.vdc_delta == 0
1238        && q.vac_delta == 0;
1239    h.all_lossless = true;
1240    for i in 0..8 {
1241        let s = &mut h.segmentation;
1242        s.qidx[i] = if s.enabled {
1243            (q.yac as i32 + s.seg_data.d[i].delta_q as i32).clamp(0, 255) as u8
1244        } else {
1245            q.yac
1246        };
1247        s.lossless[i] = s.qidx[i] == 0 && delta_lossless;
1248        h.all_lossless &= s.lossless[i];
1249    }
1250
1251    // Loop filter.
1252    let lf = &mut h.loopfilter;
1253    if h.all_lossless || h.allow_intrabc {
1254        lf.level_y = [0, 0];
1255        lf.level_u = 0;
1256        lf.level_v = 0;
1257        lf.sharpness = 0;
1258        lf.mode_ref_delta_enabled = true;
1259        lf.mode_ref_delta_update = true;
1260        lf.mode_ref_deltas = DEFAULT_MODE_REF_DELTAS;
1261    } else {
1262        lf.level_y[0] = gb.bits(6) as u8;
1263        lf.level_y[1] = gb.bits(6) as u8;
1264        if !seq.monochrome && (lf.level_y[0] != 0 || lf.level_y[1] != 0) {
1265            lf.level_u = gb.bits(6) as u8;
1266            lf.level_v = gb.bits(6) as u8;
1267        }
1268        lf.sharpness = gb.bits(3) as u8;
1269        lf.mode_ref_deltas = if h.primary_ref_frame == PRIMARY_REF_NONE {
1270            DEFAULT_MODE_REF_DELTAS
1271        } else {
1272            let r = h.refidx[h.primary_ref_frame as usize] as usize;
1273            refs[r]
1274                .as_ref()
1275                .ok_or("missing reference")?
1276                .loopfilter
1277                .mode_ref_deltas
1278        };
1279        lf.mode_ref_delta_enabled = gb.flag();
1280        if lf.mode_ref_delta_enabled {
1281            lf.mode_ref_delta_update = gb.flag();
1282            if lf.mode_ref_delta_update {
1283                for i in 0..8 {
1284                    if gb.flag() {
1285                        lf.mode_ref_deltas.ref_delta[i] = gb.sbits(7) as i8;
1286                    }
1287                }
1288                for i in 0..2 {
1289                    if gb.flag() {
1290                        lf.mode_ref_deltas.mode_delta[i] = gb.sbits(7) as i8;
1291                    }
1292                }
1293            }
1294        }
1295    }
1296
1297    // CDEF.
1298    if !h.all_lossless && seq.cdef && !h.allow_intrabc {
1299        h.cdef.damping = gb.bits(2) as u8 + 3;
1300        h.cdef.n_bits = gb.bits(2) as u8;
1301        for i in 0..(1usize << h.cdef.n_bits) {
1302            h.cdef.y_strength[i] = gb.bits(6) as u8;
1303            if !seq.monochrome {
1304                h.cdef.uv_strength[i] = gb.bits(6) as u8;
1305            }
1306        }
1307    } else {
1308        h.cdef.n_bits = 0;
1309        h.cdef.y_strength[0] = 0;
1310        h.cdef.uv_strength[0] = 0;
1311    }
1312
1313    // Loop restoration.
1314    let r = &mut h.restoration;
1315    if (!h.all_lossless || h.super_res_enabled) && seq.restoration && !h.allow_intrabc {
1316        r.typ[0] = gb.bits(2) as u8;
1317        if !seq.monochrome {
1318            r.typ[1] = gb.bits(2) as u8;
1319            r.typ[2] = gb.bits(2) as u8;
1320        }
1321        if r.typ[0] != 0 || r.typ[1] != 0 || r.typ[2] != 0 {
1322            r.unit_size[0] = 6 + seq.sb128 as u8;
1323            if gb.flag() {
1324                r.unit_size[0] += 1;
1325                if !seq.sb128 {
1326                    r.unit_size[0] += gb.bit() as u8;
1327                }
1328            }
1329            r.unit_size[1] = r.unit_size[0];
1330            if (r.typ[1] != 0 || r.typ[2] != 0) && seq.ss_hor == 1 && seq.ss_ver == 1 {
1331                r.unit_size[1] -= gb.bit() as u8;
1332            }
1333        } else {
1334            r.unit_size[0] = 8;
1335        }
1336    } else {
1337        r.typ = [RESTORATION_NONE; 3];
1338    }
1339
1340    h.txfm_mode = if h.all_lossless {
1341        TX_4X4_ONLY
1342    } else if gb.flag() {
1343        TX_SWITCHABLE
1344    } else {
1345        TX_LARGEST
1346    };
1347    h.switchable_comp_refs = h.is_inter_or_switch() && gb.flag();
1348    h.skip_mode_allowed = false;
1349    if h.switchable_comp_refs && h.is_inter_or_switch() && seq.order_hint {
1350        let nb = seq.order_hint_n_bits;
1351        let poc = h.frame_offset as i32;
1352        let mut off_before: u32 = u32::MAX;
1353        let mut off_after: i32 = -1;
1354        let (mut before_idx, mut after_idx) = (0i8, 0i8);
1355        for i in 0..7 {
1356            let refpoc = rf(h.refidx[i] as usize)?.frame_offset as i32;
1357            let diff = get_poc_diff(nb, refpoc, poc);
1358            if diff > 0 {
1359                if off_after == -1 || get_poc_diff(nb, off_after, refpoc) > 0 {
1360                    off_after = refpoc;
1361                    after_idx = i as i8;
1362                }
1363            } else if diff < 0
1364                && (off_before == u32::MAX || get_poc_diff(nb, refpoc, off_before as i32) > 0)
1365            {
1366                off_before = refpoc as u32;
1367                before_idx = i as i8;
1368            }
1369        }
1370        if off_before != u32::MAX && off_after != -1 {
1371            h.skip_mode_refs = [before_idx.min(after_idx), before_idx.max(after_idx)];
1372            h.skip_mode_allowed = true;
1373        } else if off_before != u32::MAX {
1374            let mut off_before2: u32 = u32::MAX;
1375            let mut before2_idx = 0i8;
1376            for i in 0..7 {
1377                let refpoc = rf(h.refidx[i] as usize)?.frame_offset as i32;
1378                if get_poc_diff(nb, refpoc, off_before as i32) < 0
1379                    && (off_before2 == u32::MAX || get_poc_diff(nb, refpoc, off_before2 as i32) > 0)
1380                {
1381                    off_before2 = refpoc as u32;
1382                    before2_idx = i as i8;
1383                }
1384            }
1385            if off_before2 != u32::MAX {
1386                h.skip_mode_refs = [before_idx.min(before2_idx), before_idx.max(before2_idx)];
1387                h.skip_mode_allowed = true;
1388            }
1389        }
1390    }
1391    h.skip_mode_enabled = h.skip_mode_allowed && gb.flag();
1392    h.warp_motion =
1393        !h.error_resilient_mode && h.is_inter_or_switch() && seq.warped_motion && gb.flag();
1394    h.reduced_txtp_set = gb.flag();
1395
1396    h.gmv = [DEFAULT_WM_PARAMS; 7];
1397    if h.is_inter_or_switch() {
1398        for i in 0..7 {
1399            h.gmv[i].typ = if !gb.flag() {
1400                WM_IDENTITY
1401            } else if gb.flag() {
1402                WM_ROT_ZOOM
1403            } else if gb.flag() {
1404                WM_TRANSLATION
1405            } else {
1406                WM_AFFINE
1407            };
1408            if h.gmv[i].typ == WM_IDENTITY {
1409                continue;
1410            }
1411            let ref_mat = if h.primary_ref_frame == PRIMARY_REF_NONE {
1412                DEFAULT_WM_PARAMS.matrix
1413            } else {
1414                rf(h.refidx[h.primary_ref_frame as usize] as usize)?.gmv[i].matrix
1415            };
1416            let typ = h.gmv[i].typ;
1417            let mat = &mut h.gmv[i].matrix;
1418            let (bits, shift);
1419            if typ >= WM_ROT_ZOOM {
1420                mat[2] = (1 << 16) + 2 * gb.bits_subexp((ref_mat[2] - (1 << 16)) >> 1, 12);
1421                mat[3] = 2 * gb.bits_subexp(ref_mat[3] >> 1, 12);
1422                bits = 12;
1423                shift = 10;
1424            } else {
1425                bits = 9 - !h.hp as u32;
1426                shift = 13 + !h.hp as u32;
1427            }
1428            if typ == WM_AFFINE {
1429                mat[4] = 2 * gb.bits_subexp(ref_mat[4] >> 1, 12);
1430                mat[5] = (1 << 16) + 2 * gb.bits_subexp((ref_mat[5] - (1 << 16)) >> 1, 12);
1431            } else {
1432                mat[4] = -mat[3];
1433                mat[5] = mat[2];
1434            }
1435            mat[0] = gb.bits_subexp(ref_mat[0] >> shift, bits) * (1 << shift);
1436            mat[1] = gb.bits_subexp(ref_mat[1] >> shift, bits) * (1 << shift);
1437        }
1438    }
1439
1440    h.film_grain_present =
1441        seq.film_grain_present && (h.show_frame || h.showable_frame) && gb.flag();
1442    if h.film_grain_present {
1443        let seed = gb.bits(16);
1444        h.film_grain_update = h.frame_type != FRAME_INTER || gb.flag();
1445        if !h.film_grain_update {
1446            let refidx = gb.bits(3) as i8;
1447            if !h.refidx.contains(&refidx) {
1448                return err("bad film grain reference");
1449            }
1450            h.film_grain = rf(refidx as usize)?.film_grain;
1451            h.film_grain.seed = seed;
1452        } else {
1453            let f = &mut h.film_grain;
1454            f.seed = seed;
1455            f.num_y_points = gb.bits(4) as i32;
1456            if f.num_y_points > 14 {
1457                return err("bad film grain");
1458            }
1459            for i in 0..f.num_y_points as usize {
1460                f.y_points[i][0] = gb.bits(8) as u8;
1461                if i > 0 && f.y_points[i - 1][0] >= f.y_points[i][0] {
1462                    return err("bad film grain");
1463                }
1464                f.y_points[i][1] = gb.bits(8) as u8;
1465            }
1466            f.chroma_scaling_from_luma = !seq.monochrome && gb.flag();
1467            if seq.monochrome
1468                || f.chroma_scaling_from_luma
1469                || (seq.ss_ver == 1 && seq.ss_hor == 1 && f.num_y_points == 0)
1470            {
1471                f.num_uv_points = [0, 0];
1472            } else {
1473                for pl in 0..2 {
1474                    f.num_uv_points[pl] = gb.bits(4) as i32;
1475                    if f.num_uv_points[pl] > 10 {
1476                        return err("bad film grain");
1477                    }
1478                    for i in 0..f.num_uv_points[pl] as usize {
1479                        f.uv_points[pl][i][0] = gb.bits(8) as u8;
1480                        if i > 0 && f.uv_points[pl][i - 1][0] >= f.uv_points[pl][i][0] {
1481                            return err("bad film grain");
1482                        }
1483                        f.uv_points[pl][i][1] = gb.bits(8) as u8;
1484                    }
1485                }
1486            }
1487            if seq.ss_hor == 1
1488                && seq.ss_ver == 1
1489                && (f.num_uv_points[0] != 0) != (f.num_uv_points[1] != 0)
1490            {
1491                return err("bad film grain");
1492            }
1493            f.scaling_shift = gb.bits(2) as i32 + 8;
1494            f.ar_coeff_lag = gb.bits(2) as i32;
1495            let num_y_pos = (2 * f.ar_coeff_lag * (f.ar_coeff_lag + 1)) as usize;
1496            if f.num_y_points != 0 {
1497                for i in 0..num_y_pos {
1498                    f.ar_coeffs_y[i] = (gb.bits(8) as i32 - 128) as i8;
1499                }
1500            }
1501            for pl in 0..2 {
1502                if f.num_uv_points[pl] != 0 || f.chroma_scaling_from_luma {
1503                    let num_uv_pos = num_y_pos + (f.num_y_points != 0) as usize;
1504                    for i in 0..num_uv_pos {
1505                        f.ar_coeffs_uv[pl][i] = (gb.bits(8) as i32 - 128) as i8;
1506                    }
1507                    if f.num_y_points == 0 {
1508                        f.ar_coeffs_uv[pl][num_uv_pos] = 0;
1509                    }
1510                }
1511            }
1512            f.ar_coeff_shift = gb.bits(2) as u64 + 6;
1513            f.grain_scale_shift = gb.bits(2) as i32;
1514            for pl in 0..2 {
1515                if f.num_uv_points[pl] != 0 {
1516                    f.uv_mult[pl] = gb.bits(8) as i32 - 128;
1517                    f.uv_luma_mult[pl] = gb.bits(8) as i32 - 128;
1518                    f.uv_offset[pl] = gb.bits(9) as i32 - 256;
1519                }
1520            }
1521            f.overlap_flag = gb.flag();
1522            f.clip_to_restricted_range = gb.flag();
1523        }
1524    } else {
1525        h.film_grain = FilmGrainData::default();
1526    }
1527    if gb.error {
1528        return err("frame header overrun");
1529    }
1530    Ok(h)
1531}
1532
1533/// `parse_tile_hdr`: (start, end) tile indices of a tile group.
1534pub fn parse_tile_hdr(h: &FrameHeader, gb: &mut GetBits) -> (u32, u32) {
1535    let n_tiles = h.tiling.cols as u32 * h.tiling.rows as u32;
1536    let have_tile_pos = n_tiles > 1 && gb.flag();
1537    if have_tile_pos {
1538        let n = (h.tiling.log2_cols + h.tiling.log2_rows) as u32;
1539        let s = gb.bits(n);
1540        let e = gb.bits(n);
1541        (s, e)
1542    } else {
1543        (0, n_tiles - 1)
1544    }
1545}