Skip to main content

rusty_h264_decoder/
params.rs

1//! SPS/PPS parsing for Constrained Baseline.
2//!
3//! Parses any conformant Baseline SPS/PPS and **rejects** (never misparses or
4//! panics on) profiles and tools outside Constrained Baseline.
5
6use crate::DecodeError;
7#[allow(unused_imports)]
8use alloc::borrow::ToOwned;
9#[allow(unused_imports)]
10use alloc::boxed::Box;
11#[allow(unused_imports)]
12use alloc::format;
13#[allow(unused_imports)]
14use alloc::string::{String, ToString};
15#[allow(unused_imports)]
16use alloc::vec;
17#[allow(unused_imports)]
18use alloc::vec::Vec;
19use rusty_h264_common::BitReader;
20
21/// Profiles that carry the High-profile SPS prefix (`chroma_format_idc`,
22/// bit-depths, scaling matrices). Decoding their SPS with the Baseline layout
23/// would shift every later field — so we reject them up front rather than
24/// misparse. (Spec Table A-1 / §7.3.2.1.1.)
25const HIGH_PROFILE_IDCS: &[u8] = &[100, 110, 122, 244, 44, 83, 86, 118, 128, 138, 139, 134, 135];
26
27/// Upper bound on the coded frame size, in macroblocks. Above this we reject the
28/// SPS rather than attempt a multi-gigabyte allocation from a hostile header.
29/// (≈ 4× H.264 Level 5.2's MaxFS of 36 864 MBs — generous but finite.)
30const MAX_FRAME_MBS: u64 = 36_864 * 4;
31
32/// Default 4×4 scaling lists in zig-zag order (spec Table 7-3).
33pub(crate) const DEFAULT_4X4_INTRA: [u8; 16] = [
34    6, 13, 13, 20, 20, 20, 28, 28, 28, 28, 32, 32, 32, 37, 37, 42,
35];
36pub(crate) const DEFAULT_4X4_INTER: [u8; 16] = [
37    10, 14, 14, 20, 20, 20, 24, 24, 24, 24, 27, 27, 27, 30, 30, 34,
38];
39/// Default 8×8 scaling lists in zig-zag order (spec Table 7-4).
40pub(crate) const DEFAULT_8X8_INTRA: [u8; 64] = [
41    6, 10, 10, 13, 11, 13, 16, 16, 16, 16, 18, 18, 18, 18, 18, 23, 23, 23, 23, 23, 23, 25, 25, 25,
42    25, 25, 25, 25, 27, 27, 27, 27, 27, 27, 27, 27, 29, 29, 29, 29, 29, 29, 29, 31, 31, 31, 31, 31,
43    31, 33, 33, 33, 33, 33, 36, 36, 36, 36, 38, 38, 38, 40, 40, 42,
44];
45pub(crate) const DEFAULT_8X8_INTER: [u8; 64] = [
46    9, 13, 13, 15, 13, 15, 17, 17, 17, 17, 19, 19, 19, 19, 19, 21, 21, 21, 21, 21, 21, 22, 22, 22,
47    22, 22, 22, 22, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 27, 27, 27, 27, 27,
48    27, 28, 28, 28, 28, 28, 30, 30, 30, 30, 32, 32, 32, 33, 33, 35,
49];
50
51/// Parses a `scaling_list` of `size` coefficients (spec §7.3.2.1.1.1), filling
52/// `out` (zig-zag order) and returning `use_default`. Consumes the exact bits so
53/// the rest of the SPS/PPS stays aligned even when we ignore the weights.
54fn parse_scaling_list(r: &mut BitReader, out: &mut [u8], size: usize) -> Result<bool, DecodeError> {
55    let mut last_scale = 8i32;
56    let mut next_scale = 8i32;
57    let mut use_default = false;
58    for (j, slot) in out.iter_mut().enumerate().take(size) {
59        if next_scale != 0 {
60            let delta = r.read_se()?;
61            next_scale = (last_scale + delta + 256).rem_euclid(256);
62            if j == 0 && next_scale == 0 {
63                use_default = true;
64            }
65        }
66        let v = if next_scale == 0 {
67            last_scale
68        } else {
69            next_scale
70        };
71        *slot = v as u8;
72        last_scale = v;
73    }
74    Ok(use_default)
75}
76
77/// Parsed sequence parameter set fields the decoder needs.
78#[derive(Debug, Clone)]
79pub struct Sps {
80    pub profile_idc: u8,
81    pub level_idc: u8,
82    pub seq_parameter_set_id: u32,
83    pub log2_max_frame_num: u32,
84    pub pic_order_cnt_type: u32,
85    pub log2_max_pic_order_cnt_lsb: u32,
86    /// `delta_pic_order_always_zero_flag` (only meaningful for POC type 1).
87    pub delta_pic_order_always_zero: bool,
88    /// `gaps_in_frame_num_value_allowed_flag`: when set, `frame_num` may skip
89    /// values and the decoder must synthesize placeholder reference frames.
90    pub gaps_in_frame_num_allowed: bool,
91    /// `direct_8x8_inference_flag`: when set, B direct/skip derives one motion per
92    /// 8×8 from the co-located corner 4×4 (vs per-4×4).
93    pub direct_8x8_inference: bool,
94    pub max_num_ref_frames: u32,
95    pub pic_width_in_mbs: usize,
96    pub pic_height_in_mbs: usize,
97    pub frame_crop_left: u32,
98    pub frame_crop_right: u32,
99    pub frame_crop_top: u32,
100    pub frame_crop_bottom: u32,
101    /// `chroma_format_idc` (1 = 4:2:0; the only value we decode).
102    pub chroma_format_idc: u32,
103    /// Sequence scaling lists in zig-zag order (six 4×4, two 8×8); `16`
104    /// everywhere = flat (no weighting). High-profile only.
105    pub scaling_4x4: [[u8; 16]; 6],
106    pub scaling_8x8: [[u8; 64]; 2],
107    /// Whether custom scaling matrices are active (else flat dequant).
108    pub has_scaling: bool,
109    /// `qpprime_y_zero_transform_bypass_flag` (High SPS): with QP'Y == 0 the
110    /// transform+quant are BYPASSED (lossless residual). The decoder refuses
111    /// such macroblocks rather than silently mis-decoding them.
112    pub transform_bypass: bool,
113}
114
115impl Sps {
116    /// Coded luma width/height in samples (MB grid * 16).
117    pub fn coded_width(&self) -> usize {
118        self.pic_width_in_mbs * 16
119    }
120    pub fn coded_height(&self) -> usize {
121        self.pic_height_in_mbs * 16
122    }
123
124    /// Displayed luma width after cropping (CropUnitX = 2 for 4:2:0).
125    pub fn display_width(&self) -> usize {
126        self.coded_width() - 2 * (self.frame_crop_left + self.frame_crop_right) as usize
127    }
128    /// Displayed luma height after cropping (CropUnitY = 2 for 4:2:0, frame-only).
129    pub fn display_height(&self) -> usize {
130        self.coded_height() - 2 * (self.frame_crop_top + self.frame_crop_bottom) as usize
131    }
132
133    /// Parses an SPS RBSP (emulation bytes already removed). Rejects anything
134    /// outside Constrained Baseline cleanly; never panics.
135    pub fn parse(rbsp: &[u8]) -> Result<Self, DecodeError> {
136        let mut r = BitReader::new(rbsp);
137        let profile_idc = r.read_bits(8)? as u8;
138        let _constraints = r.read_bits(8)?;
139        let level_idc = r.read_bits(8)? as u8;
140        let seq_parameter_set_id = r.read_ue()?;
141        // High/Main-prefix profiles add chroma_format_idc, bit-depths, and the
142        // sequence scaling matrices here (spec §7.3.2.1.1, after seq_parameter_set_id).
143        // Parse the 4:2:0 / 8-bit subset; reject the rest cleanly.
144        let mut chroma_format_idc = 1u32;
145        let mut transform_bypass = false;
146        let mut scaling_4x4 = [[16u8; 16]; 6];
147        let mut scaling_8x8 = [[16u8; 64]; 2];
148        let mut has_scaling = false;
149        if HIGH_PROFILE_IDCS.contains(&profile_idc) {
150            chroma_format_idc = r.read_ue()?;
151            if chroma_format_idc == 3 {
152                let _separate_colour_plane = r.read_bit()?;
153            }
154            if chroma_format_idc != 1 {
155                return Err(DecodeError::Unsupported("non-4:2:0 chroma"));
156            }
157            if r.read_ue()? != 0 || r.read_ue()? != 0 {
158                return Err(DecodeError::Unsupported("bit depth > 8"));
159            }
160            transform_bypass = r.read_bit()?;
161            if r.read_bit()? {
162                // seq_scaling_matrix_present_flag — six 4×4 then two 8×8 (4:2:0),
163                // with fall-back rule set A for absent / use-default lists
164                // (spec §8.5.9 Table 8-?, §7.4.2.1.1.1).
165                has_scaling = true;
166                for i in 0..8 {
167                    let present = r.read_bit()?;
168                    if i < 6 {
169                        if present {
170                            let dflt = parse_scaling_list(&mut r, &mut scaling_4x4[i], 16)?;
171                            if dflt {
172                                scaling_4x4[i] = if i < 3 {
173                                    DEFAULT_4X4_INTRA
174                                } else {
175                                    DEFAULT_4X4_INTER
176                                };
177                            }
178                        } else {
179                            scaling_4x4[i] = match i {
180                                0 => DEFAULT_4X4_INTRA,
181                                3 => DEFAULT_4X4_INTER,
182                                // fall back to the previous list
183                                _ => *scaling_4x4.get(i - 1).unwrap_or(&DEFAULT_4X4_INTRA),
184                            };
185                        }
186                    } else if present {
187                        let dflt = parse_scaling_list(&mut r, &mut scaling_8x8[i - 6], 64)?;
188                        if dflt {
189                            scaling_8x8[i - 6] = if i == 6 {
190                                DEFAULT_8X8_INTRA
191                            } else {
192                                DEFAULT_8X8_INTER
193                            };
194                        }
195                    } else {
196                        scaling_8x8[i - 6] = if i == 6 {
197                            DEFAULT_8X8_INTRA
198                        } else {
199                            DEFAULT_8X8_INTER
200                        };
201                    }
202                }
203            }
204        }
205        // CBP/Baseline: no chroma_format_idc / scaling-list section.
206        // Spec §7.4.2.1.1: log2_max_frame_num_minus4 ∈ [0,12] → log2_max_frame_num ≤ 16.
207        // Reject anything larger: an attacker-inflated value makes MaxFrameNum = 1<<n
208        // billions, which would drive the frame-num-gap loop unbounded.
209        let log2_max_frame_num = r.read_ue()? + 4;
210        if log2_max_frame_num > 16 {
211            return Err(DecodeError::Unsupported("invalid log2_max_frame_num"));
212        }
213        let pic_order_cnt_type = r.read_ue()?;
214        let mut log2_max_pic_order_cnt_lsb = 0;
215        let mut delta_pic_order_always_zero = false;
216        if pic_order_cnt_type == 0 {
217            log2_max_pic_order_cnt_lsb = r.read_ue()? + 4;
218            if log2_max_pic_order_cnt_lsb > 16 {
219                return Err(DecodeError::Unsupported(
220                    "invalid log2_max_pic_order_cnt_lsb",
221                ));
222            }
223        } else if pic_order_cnt_type == 1 {
224            // Parse the type-1 cycle so later fields stay aligned; CBP output
225            // order is decode order, so only the always-zero flag is retained
226            // (the slice header needs it to know whether delta_pic_order_cnt is
227            // present).
228            delta_pic_order_always_zero = r.read_bit()?;
229            let _offset_for_non_ref_pic = r.read_se()?;
230            let _offset_for_top_to_bottom = r.read_se()?;
231            let n = r.read_ue()?;
232            if n > 255 {
233                return Err(DecodeError::Unsupported("oversized poc cycle"));
234            }
235            for _ in 0..n {
236                let _offset = r.read_se()?;
237            }
238        } else if pic_order_cnt_type != 2 {
239            return Err(DecodeError::Unsupported("invalid pic_order_cnt_type"));
240        }
241        let max_num_ref_frames = r.read_ue()?;
242        let gaps_in_frame_num_allowed = r.read_bit()?;
243        let pic_width_in_mbs = (r.read_ue()? as u64 + 1) as usize;
244        let pic_height_in_mbs = (r.read_ue()? as u64 + 1) as usize;
245        // Guard against a hostile SPS demanding a giant allocation.
246        if (pic_width_in_mbs as u64) * (pic_height_in_mbs as u64) > MAX_FRAME_MBS {
247            return Err(DecodeError::Unsupported("frame too large"));
248        }
249        let frame_mbs_only_flag = r.read_bit()?;
250        if !frame_mbs_only_flag {
251            return Err(DecodeError::Unsupported("interlace / field coding"));
252        }
253        let direct_8x8_inference = r.read_bit()?;
254        let cropping = r.read_bit()?;
255        let (mut cl, mut cr, mut ct, mut cb) = (0, 0, 0, 0);
256        if cropping {
257            cl = r.read_ue()?;
258            cr = r.read_ue()?;
259            ct = r.read_ue()?;
260            cb = r.read_ue()?;
261            // Reject crop windows that exceed the coded frame (would underflow
262            // the display-size subtraction in into_frame / display_*).
263            if (cl + cr) as usize * 2 >= pic_width_in_mbs * 16
264                || (ct + cb) as usize * 2 >= pic_height_in_mbs * 16
265            {
266                return Err(DecodeError::Unsupported("crop exceeds frame"));
267            }
268        }
269        // vui_parameters_present_flag and trailing bits ignored.
270        Ok(Self {
271            profile_idc,
272            level_idc,
273            seq_parameter_set_id,
274            log2_max_frame_num,
275            pic_order_cnt_type,
276            log2_max_pic_order_cnt_lsb,
277            delta_pic_order_always_zero,
278            gaps_in_frame_num_allowed,
279            direct_8x8_inference,
280            max_num_ref_frames,
281            pic_width_in_mbs,
282            pic_height_in_mbs,
283            frame_crop_left: cl,
284            frame_crop_right: cr,
285            frame_crop_top: ct,
286            frame_crop_bottom: cb,
287            chroma_format_idc,
288            scaling_4x4,
289            scaling_8x8,
290            has_scaling,
291            transform_bypass,
292        })
293    }
294}
295
296/// Parsed picture parameter set fields the decoder needs.
297#[derive(Debug, Clone)]
298pub struct Pps {
299    pub pic_parameter_set_id: u32,
300    pub seq_parameter_set_id: u32,
301    pub entropy_coding_mode_flag: bool,
302    /// `bottom_field_pic_order_in_frame_present_flag` (a.k.a. pic_order_present):
303    /// when set, slice headers carry an extra `delta_pic_order_cnt` value.
304    pub bottom_field_pic_order_present: bool,
305    pub num_ref_idx_l0_default: u32,
306    pub num_ref_idx_l1_default: u32,
307    pub weighted_pred: bool,
308    pub weighted_bipred_idc: u8,
309    pub pic_init_qp: i32,
310    /// Signed offset applied when mapping luma QP to chroma QP (§8.5.8).
311    pub chroma_qp_index_offset: i32,
312    pub deblocking_filter_control_present_flag: bool,
313    pub constrained_intra_pred_flag: bool,
314    pub redundant_pic_cnt_present_flag: bool,
315    /// `transform_8x8_mode_flag` (High PPS extension): when set, macroblocks may
316    /// signal `transform_size_8x8_flag` to use the 8×8 transform.
317    pub transform_8x8_mode_flag: bool,
318    /// `second_chroma_qp_index_offset` (High PPS extension) — the Cr QP offset;
319    /// defaults to `chroma_qp_index_offset` (the Cb offset) when absent.
320    pub second_chroma_qp_index_offset: i32,
321    /// `pic_scaling_matrix_present_flag`: per-picture scaling lists overriding
322    /// the SPS ones (fall-back rule B). When false the SPS lists apply.
323    pub pic_scaling_matrix_present: bool,
324    /// Parsed PPS scaling lists (zig-zag order) and per-list present flags. Only
325    /// meaningful when `pic_scaling_matrix_present`; absent lists resolve against
326    /// the SPS at slice time.
327    pub scaling_4x4: [[u8; 16]; 6],
328    pub scaling_8x8: [[u8; 64]; 2],
329    pub scaling_present_4x4: [bool; 6],
330    pub scaling_present_8x8: [bool; 2],
331}
332
333impl Pps {
334    /// Parses a PPS RBSP. Rejects FMO/slice-groups cleanly; never panics.
335    pub fn parse(rbsp: &[u8]) -> Result<Self, DecodeError> {
336        let mut r = BitReader::new(rbsp);
337        let pic_parameter_set_id = r.read_ue()?;
338        let seq_parameter_set_id = r.read_ue()?;
339        let entropy_coding_mode_flag = r.read_bit()?;
340        let bottom_field_pic_order_present = r.read_bit()?;
341        let num_slice_groups_minus1 = r.read_ue()?;
342        if num_slice_groups_minus1 != 0 {
343            // FMO: a slice_group map follows here that we neither parse nor
344            // support — reject before the syntax shifts under us.
345            return Err(DecodeError::Unsupported("slice groups (FMO)"));
346        }
347        let num_ref_idx_l0_default = r.read_ue()? + 1;
348        let num_ref_idx_l1_default = r.read_ue()? + 1;
349        let weighted_pred = r.read_bit()?;
350        let weighted_bipred_idc = r.read_bits(2)? as u8;
351        let pic_init_qp = 26 + r.read_se()?;
352        let _pic_init_qs = r.read_se()?;
353        let chroma_qp_index_offset = r.read_se()?;
354        let deblocking_filter_control_present_flag = r.read_bit()?;
355        let constrained_intra_pred_flag = r.read_bit()?;
356        let redundant_pic_cnt_present_flag = r.read_bit()?;
357        // High-profile PPS extension (present iff there is more RBSP data).
358        let mut transform_8x8_mode_flag = false;
359        let mut second_chroma_qp_index_offset = chroma_qp_index_offset;
360        let mut pic_scaling_matrix_present = false;
361        let mut scaling_4x4 = [[16u8; 16]; 6];
362        let mut scaling_8x8 = [[16u8; 64]; 2];
363        let mut scaling_present_4x4 = [false; 6];
364        let mut scaling_present_8x8 = [false; 2];
365        if r.more_rbsp_data() {
366            transform_8x8_mode_flag = r.read_bit()?;
367            if r.read_bit()? {
368                // pic_scaling_matrix_present_flag: 6 4×4 lists + (2 8×8 when the
369                // 8×8 transform is enabled, for 4:2:0). Absent lists resolve via
370                // fall-back rule B against the SPS at slice time.
371                pic_scaling_matrix_present = true;
372                let n = 6 + if transform_8x8_mode_flag { 2 } else { 0 };
373                for i in 0..n {
374                    let present = r.read_bit()?;
375                    if i < 6 {
376                        scaling_present_4x4[i] = present;
377                        if present {
378                            let dflt = parse_scaling_list(&mut r, &mut scaling_4x4[i], 16)?;
379                            if dflt {
380                                scaling_4x4[i] = if i < 3 {
381                                    DEFAULT_4X4_INTRA
382                                } else {
383                                    DEFAULT_4X4_INTER
384                                };
385                            }
386                        }
387                    } else {
388                        scaling_present_8x8[i - 6] = present;
389                        if present {
390                            let dflt = parse_scaling_list(&mut r, &mut scaling_8x8[i - 6], 64)?;
391                            if dflt {
392                                scaling_8x8[i - 6] = if i == 6 {
393                                    DEFAULT_8X8_INTRA
394                                } else {
395                                    DEFAULT_8X8_INTER
396                                };
397                            }
398                        }
399                    }
400                }
401            }
402            second_chroma_qp_index_offset = r.read_se()?;
403        }
404        Ok(Self {
405            pic_parameter_set_id,
406            seq_parameter_set_id,
407            entropy_coding_mode_flag,
408            bottom_field_pic_order_present,
409            num_ref_idx_l0_default,
410            num_ref_idx_l1_default,
411            weighted_pred,
412            weighted_bipred_idc,
413            pic_init_qp,
414            chroma_qp_index_offset,
415            deblocking_filter_control_present_flag,
416            constrained_intra_pred_flag,
417            redundant_pic_cnt_present_flag,
418            transform_8x8_mode_flag,
419            second_chroma_qp_index_offset,
420            pic_scaling_matrix_present,
421            scaling_4x4,
422            scaling_8x8,
423            scaling_present_4x4,
424            scaling_present_8x8,
425        })
426    }
427}