Skip to main content

rusty_h264_encoder/
params.rs

1//! Sequence and picture parameter sets (SPS / PPS) generation.
2//!
3//! Follows the H.264 spec syntax (§7.3.2.1.1 / §7.3.2.2) restricted to the
4//! Constrained Baseline feature set: `frame_mbs_only_flag = 1`, no scaling
5//! matrices, CAVLC entropy coding, no chroma/luma bit-depth extensions.
6
7use crate::config::EncoderConfig;
8use rusty_h264_common::{BitWriter, NalUnit, NalUnitType};
9
10/// Sequence parameter set, carrying only the fields a CBP encoder emits.
11#[derive(Debug, Clone)]
12pub struct Sps {
13    pub profile_idc: u8,
14    pub constraint_set1_flag: bool,
15    pub level_idc: u8,
16    pub seq_parameter_set_id: u32,
17    pub log2_max_frame_num_minus4: u32,
18    pub pic_order_cnt_type: u32,
19    pub log2_max_pic_order_cnt_lsb_minus4: u32,
20    pub max_num_ref_frames: u32,
21    pub pic_width_in_mbs_minus1: u32,
22    pub pic_height_in_map_units_minus1: u32,
23    /// Cropping in chroma-sample units (right, bottom) when the coded MB grid
24    /// overshoots the requested luma resolution.
25    pub frame_crop_right: u32,
26    pub frame_crop_bottom: u32,
27}
28
29impl Sps {
30    /// Derives the SPS from an encoder configuration.
31    pub fn from_config(cfg: &EncoderConfig) -> Self {
32        let mb_w = cfg.mb_width();
33        let mb_h = cfg.mb_height();
34        // Crop offsets are expressed in units of CropUnitX/Y. For 4:2:0 and
35        // frame_mbs_only_flag=1, CropUnitX=2, CropUnitY=2.
36        let crop_right = (mb_w * 16 - cfg.width) / 2;
37        let crop_bottom = (mb_h * 16 - cfg.height) / 2;
38        // LEVEL FLOOR from what the stream actually signals (Table A-1):
39        // the frame must fit the level's MaxFS, and `max_num_ref_frames`
40        // frames must fit its MaxDpbMbs — or the stream nominally violates
41        // its own level_idc. Both clauses have real instances here: 720p at
42        // refs 3 exceeds 3.0's DPB (needs 3.1, exactly what x264 signals),
43        // and 1080p exceeds 3.0's MaxFS at ANY ref count (needs 4.0) — the
44        // fixed `level_idc: 30` default had been signalling that violation
45        // on every 1080p encode, surfaced the day this floor was tested.
46        // Only ever RAISES the caller's level, so every already-conformant
47        // configuration is byte-identical.
48        let frame_mbs = (mb_w * mb_h) as u32;
49        let dpb_mbs = frame_mbs * cfg.num_ref_frames.max(1);
50        const LEVEL_CAPS: [(u8, u32, u32); 16] = [
51            // (level_idc, MaxFS, MaxDpbMbs)
52            (10, 99, 396), (11, 396, 900), (12, 396, 2376), (13, 396, 2376),
53            (20, 396, 2376), (21, 792, 4752), (22, 1620, 8100), (30, 1620, 8100),
54            (31, 3600, 18000), (32, 5120, 20480), (40, 8192, 32768),
55            (41, 8192, 32768), (42, 8704, 34816), (50, 22080, 110400),
56            (51, 36864, 184320), (52, 36864, 184320),
57        ];
58        let level_floor = LEVEL_CAPS
59            .iter()
60            .find(|&&(_, max_fs, max_dpb)| max_fs >= frame_mbs && max_dpb >= dpb_mbs)
61            .map(|&(l, _, _)| l)
62            .unwrap_or(52);
63        Self {
64            profile_idc: cfg.profile.profile_idc(),
65            constraint_set1_flag: true, // constrained baseline
66            level_idc: cfg.level_idc.max(level_floor),
67            seq_parameter_set_id: 0,
68            log2_max_frame_num_minus4: 0, // log2_max_frame_num = 4
69            pic_order_cnt_type: 0,
70            log2_max_pic_order_cnt_lsb_minus4: 4, // log2_max_poc_lsb = 8 (256): b-pyramid interleaves reference POCs in coding order, and a 16-value lsb put consecutive-reference steps past the §8.2.1 half-range — ffmpeg (correctly) lost the msb and every list ordering after it
71            max_num_ref_frames: cfg.num_ref_frames.max(1),
72            pic_width_in_mbs_minus1: (mb_w - 1) as u32,
73            pic_height_in_map_units_minus1: (mb_h - 1) as u32,
74            frame_crop_right: crop_right as u32,
75            frame_crop_bottom: crop_bottom as u32,
76        }
77    }
78
79    /// Writes the SPS RBSP (without NAL header) including trailing bits.
80    pub fn write_rbsp(&self, w: &mut BitWriter) {
81        w.write_bits(self.profile_idc as u32, 8);
82        // constraint_set0..5 flags + 2 reserved zero bits = u(8).
83        let mut constraints = 0u32;
84        if self.constraint_set1_flag {
85            constraints |= 1 << 6; // constraint_set1_flag is bit position 6 (MSB-first)
86        }
87        w.write_bits(constraints, 8);
88        w.write_bits(self.level_idc as u32, 8);
89        w.write_ue(self.seq_parameter_set_id);
90        // High-profile prefix (profile_idc >= 100, spec §7.3.2.1.1): chroma_format_idc,
91        // bit-depths, transform-bypass, scaling matrices. Baseline/Main (66/77) omit it.
92        if self.profile_idc >= 100 {
93            w.write_ue(1); // chroma_format_idc = 1 (4:2:0)
94            w.write_ue(0); // bit_depth_luma_minus8
95            w.write_ue(0); // bit_depth_chroma_minus8
96            w.write_bit(false); // qpprime_y_zero_transform_bypass_flag
97            w.write_bit(false); // seq_scaling_matrix_present_flag (flat dequant)
98        }
99        w.write_ue(self.log2_max_frame_num_minus4);
100        w.write_ue(self.pic_order_cnt_type);
101        if self.pic_order_cnt_type == 0 {
102            w.write_ue(self.log2_max_pic_order_cnt_lsb_minus4);
103        }
104        w.write_ue(self.max_num_ref_frames);
105        w.write_bit(false); // gaps_in_frame_num_value_allowed_flag
106        w.write_ue(self.pic_width_in_mbs_minus1);
107        w.write_ue(self.pic_height_in_map_units_minus1);
108        w.write_bit(true); // frame_mbs_only_flag = 1
109        // direct_8x8_inference_flag = 1: REQUIRED by the spec for level_idc >= 30
110        // (every 720p+ stream), and the only value x264/ffmpeg ever emit. The
111        // encoder's direct derivation (b_direct corner colZero) and the
112        // transform_size_8x8_flag conditions (allow_t8 / allow8) are keyed to
113        // this value IN LOCKSTEP — flipping it back without them desyncs B+8x8.
114        w.write_bit(true); // direct_8x8_inference_flag
115        let cropping = self.frame_crop_right != 0 || self.frame_crop_bottom != 0;
116        w.write_bit(cropping); // frame_cropping_flag
117        if cropping {
118            w.write_ue(0); // frame_crop_left_offset
119            w.write_ue(self.frame_crop_right);
120            w.write_ue(0); // frame_crop_top_offset
121            w.write_ue(self.frame_crop_bottom);
122        }
123        w.write_bit(false); // vui_parameters_present_flag
124        w.rbsp_trailing_bits();
125    }
126
127    /// Builds the SPS as a complete NAL unit.
128    pub fn to_nal(&self) -> NalUnit {
129        let mut w = BitWriter::new();
130        self.write_rbsp(&mut w);
131        NalUnit::new(3, NalUnitType::Sps, w.into_bytes())
132    }
133}
134
135/// Picture parameter set for a CAVLC, single-slice-group CBP encoder.
136#[derive(Debug, Clone)]
137pub struct Pps {
138    pub pic_parameter_set_id: u32,
139    pub seq_parameter_set_id: u32,
140    pub num_ref_idx_l0_default_active_minus1: u32,
141    pub pic_init_qp_minus26: i32,
142    pub deblocking_filter_control_present_flag: bool,
143    /// `2` = IMPLICIT weighted bi-prediction (POC-distance weights) — needed so
144    /// unequal-distance B-frames (`bframes > 1`) blend correctly; `0` otherwise
145    /// (keeps the B-less PPS byte-identical, and `bframes == 1`'s equidistant B
146    /// gets 32:32 weights == the plain average anyway).
147    pub weighted_bipred_idc: u8,
148    /// Explicit weighted prediction for P slices (x264 parity — its `weightp`
149    /// default is on). The DECODER side has supported this for months
150    /// (validated against x264 weightp streams); the encoder emits identity
151    /// weights except where the per-slice fade estimator finds a real gain.
152    pub weighted_pred_flag: bool,
153    /// CABAC (`1`) vs CAVLC (`0`). Set from [`EncoderConfig::cabac`].
154    pub entropy_coding_mode_flag: bool,
155    /// `transform_8x8_mode_flag` (High-profile PPS extension). Set from
156    /// [`EncoderConfig::transform_8x8`]; requires profile_idc 100.
157    pub transform_8x8_mode_flag: bool,
158}
159
160impl Pps {
161    /// Derives the PPS from an encoder configuration.
162    pub fn from_config(cfg: &EncoderConfig) -> Self {
163        Self {
164            pic_parameter_set_id: 0,
165            seq_parameter_set_id: 0,
166            num_ref_idx_l0_default_active_minus1: cfg.num_ref_frames.max(1) - 1,
167            pic_init_qp_minus26: cfg.qp as i32 - 26,
168            // We signal deblocking control in the slice so we can disable the
169            // in-loop filter (not yet implemented); this keeps our (non-filtered)
170            // reconstruction bit-identical to a reference decoder's.
171            deblocking_filter_control_present_flag: true,
172            weighted_bipred_idc: if cfg.bframes > 0 { 2 } else { 0 },
173            weighted_pred_flag: cfg.weightp,
174            entropy_coding_mode_flag: cfg.cabac,
175            transform_8x8_mode_flag: cfg.transform_8x8,
176        }
177    }
178
179    /// Writes the PPS RBSP (without NAL header) including trailing bits.
180    pub fn write_rbsp(&self, w: &mut BitWriter) {
181        w.write_ue(self.pic_parameter_set_id);
182        w.write_ue(self.seq_parameter_set_id);
183        w.write_bit(self.entropy_coding_mode_flag); // entropy_coding_mode_flag (0=CAVLC, 1=CABAC)
184        w.write_bit(false); // bottom_field_pic_order_in_frame_present_flag
185        w.write_ue(0); // num_slice_groups_minus1
186        w.write_ue(self.num_ref_idx_l0_default_active_minus1);
187        w.write_ue(0); // num_ref_idx_l1_default_active_minus1
188        w.write_bit(self.weighted_pred_flag); // weighted_pred_flag (explicit P WP)
189        w.write_bits(self.weighted_bipred_idc as u32, 2); // weighted_bipred_idc
190        w.write_se(self.pic_init_qp_minus26);
191        w.write_se(0); // pic_init_qs_minus26
192        w.write_se(0); // chroma_qp_index_offset
193        w.write_bit(self.deblocking_filter_control_present_flag);
194        w.write_bit(false); // constrained_intra_pred_flag
195        w.write_bit(false); // redundant_pic_cnt_present_flag
196        // High-profile PPS extension (present iff more RBSP data). We only emit it to
197        // signal the 8×8 transform; no picture scaling matrices (flat dequant).
198        if self.transform_8x8_mode_flag {
199            w.write_bit(true); // transform_8x8_mode_flag
200            w.write_bit(false); // pic_scaling_matrix_present_flag
201            w.write_se(0); // second_chroma_qp_index_offset
202        }
203        w.rbsp_trailing_bits();
204    }
205
206    /// Builds the PPS as a complete NAL unit.
207    pub fn to_nal(&self) -> NalUnit {
208        let mut w = BitWriter::new();
209        self.write_rbsp(&mut w);
210        NalUnit::new(3, NalUnitType::Pps, w.into_bytes())
211    }
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use rusty_h264_common::{nal::emulation_unprevent, BitReader};
218
219    /// The shipped default is now HIGH + CABAC + the 8x8 transform (R6, 2026-08-08;
220    /// previously Main + CABAC). Assert all three reach the BITSTREAM, not merely the
221    /// config: `transform_8x8` is inert unless the PPS actually carries
222    /// `transform_8x8_mode_flag`, so checking the struct field would pin nothing.
223    #[test]
224    fn default_config_signals_high_profile_cabac_and_8x8() {
225        let cfg = EncoderConfig::new(320, 240);
226        let sps = Sps::from_config(&cfg);
227        let nal = sps.to_nal();
228        let rbsp = emulation_unprevent(&nal.rbsp);
229        let mut r = BitReader::new(&rbsp);
230        assert_eq!(r.read_bits(8).unwrap(), 100, "profile_idc should be High");
231
232        let pps = Pps::from_config(&cfg);
233        let nal = pps.to_nal();
234        let rbsp = emulation_unprevent(&nal.rbsp);
235        let mut r = BitReader::new(&rbsp);
236        assert_eq!(r.read_ue().unwrap(), 0); // pic_parameter_set_id
237        assert_eq!(r.read_ue().unwrap(), 0); // seq_parameter_set_id
238        assert!(r.read_bit().unwrap(), "entropy_coding_mode should be CABAC");
239        // Walk the rest of the base PPS to reach the extension (spec 7.3.2.2).
240        r.read_bit().unwrap(); // bottom_field_pic_order_in_frame_present_flag
241        assert_eq!(r.read_ue().unwrap(), 0, "num_slice_groups_minus1"); // no slice groups
242        r.read_ue().unwrap(); // num_ref_idx_l0_default_active_minus1
243        r.read_ue().unwrap(); // num_ref_idx_l1_default_active_minus1
244        r.read_bit().unwrap(); // weighted_pred_flag
245        r.read_bits(2).unwrap(); // weighted_bipred_idc
246        r.read_se().unwrap(); // pic_init_qp_minus26
247        r.read_se().unwrap(); // pic_init_qs_minus26
248        r.read_se().unwrap(); // chroma_qp_index_offset
249        r.read_bit().unwrap(); // deblocking_filter_control_present_flag
250        r.read_bit().unwrap(); // constrained_intra_pred_flag
251        r.read_bit().unwrap(); // redundant_pic_cnt_present_flag
252        assert!(
253            r.read_bit().unwrap(),
254            "transform_8x8_mode_flag should be set — without it in the PPS the 8x8              transform cannot be signalled at all and the default is inert"
255        );
256    }
257
258    #[test]
259    fn sps_roundtrips_through_reader() {
260        // Pin the toolset this test is ABOUT (Baseline + CAVLC) rather than inheriting
261        // it from the default, which now ships Main + CABAC.
262        let mut cfg = EncoderConfig::new(1920, 1080); // 1080 not a multiple of 16 -> cropping
263        cfg.profile = rusty_h264_common::Profile::ConstrainedBaseline;
264        cfg.cabac = false;
265        cfg.num_ref_frames = 1; // pinned like profile/cabac: the default is now 3, and at 1080p that (correctly) raises the level floor this test isn't about
266        let sps = Sps::from_config(&cfg);
267        let nal = sps.to_nal();
268
269        let rbsp = emulation_unprevent(&nal.rbsp);
270        let mut r = BitReader::new(&rbsp);
271        assert_eq!(r.read_bits(8).unwrap(), 66); // profile_idc
272        let constraints = r.read_bits(8).unwrap();
273        assert_eq!((constraints >> 6) & 1, 1); // constraint_set1_flag
274        // 40, not the config's 30: 1080p is 8160 MBs and level 3.0's MaxFS is
275        // 1620 — the old fixed level was a latent spec violation on every
276        // 1080p stream, surfaced (and fixed) by the Table A-1 level floor.
277        assert_eq!(r.read_bits(8).unwrap(), 40); // level_idc
278        assert_eq!(r.read_ue().unwrap(), 0); // sps id
279        assert_eq!(r.read_ue().unwrap(), 0); // log2_max_frame_num_minus4
280        assert_eq!(r.read_ue().unwrap(), 0); // poc type
281        assert_eq!(r.read_ue().unwrap(), 4); // log2_max_poc_lsb_minus4 (256-value lsb — the b-pyramid POC fix)
282        assert_eq!(r.read_ue().unwrap(), 1); // max_num_ref_frames
283        assert!(!r.read_bit().unwrap()); // gaps
284        assert_eq!(r.read_ue().unwrap(), 119); // 1920/16 - 1
285        assert_eq!(r.read_ue().unwrap(), 67); // ceil(1080/16)-1 = 68-1
286        assert!(r.read_bit().unwrap()); // frame_mbs_only
287        assert!(r.read_bit().unwrap()); // direct_8x8_inference_flag = 1 (level >= 3.0 requirement)
288        assert!(r.read_bit().unwrap()); // cropping present (1080)
289        assert_eq!(r.read_ue().unwrap(), 0); // crop left
290        assert_eq!(r.read_ue().unwrap(), 0); // crop right
291        assert_eq!(r.read_ue().unwrap(), 0); // crop top
292        assert_eq!(r.read_ue().unwrap(), 4); // crop bottom: (1088-1080)/2
293    }
294
295    /// The DPB-derived level floor (Table A-1 MaxDpbMbs): raises `level_idc`
296    /// exactly when the signalled reference count cannot fit the caller's
297    /// level, and never otherwise.
298    #[test]
299    fn level_floor_tracks_dpb() {
300        let lvl = |w: usize, h: usize, refs: u32| {
301            let mut cfg = EncoderConfig::new(w, h);
302            cfg.num_ref_frames = refs;
303            Sps::from_config(&cfg).level_idc
304        };
305        assert_eq!(lvl(352, 288, 1), 30); // CIF: caller's 3.0 stands
306        assert_eq!(lvl(352, 288, 3), 30); // CIF x3 = 1188 MBs, still fits 3.0
307        assert_eq!(lvl(1280, 720, 1), 31); // 720p = 3600 MBs > 3.0's MaxFS 1620 (latent; floor fixes it)
308        assert_eq!(lvl(1280, 720, 3), 31); // 720p x3 = 10800 fits 3.1's DPB 18000
309        assert_eq!(lvl(1920, 1080, 1), 40); // 1080p = 8160 MBs > 3.2's MaxFS (the latent 1080p violation)
310        assert_eq!(lvl(1920, 1080, 3), 40); // and x3 = 24480 fits 4.0's DPB 32768
311        assert_eq!(lvl(1920, 1080, 16), 51); // stress: 16-ref 1080p
312    }
313
314    #[test]
315    fn pps_roundtrips_through_reader() {
316        let mut cfg = EncoderConfig::new(640, 480);
317        cfg.profile = rusty_h264_common::Profile::ConstrainedBaseline;
318        cfg.cabac = false;
319        cfg.num_ref_frames = 1; // pinned: this test is about PPS syntax, not the refs default (now 3)
320        cfg.weightp = false; // pinned likewise: weightp defaults ON since the x264-parity landing
321        let pps = Pps::from_config(&cfg);
322        let nal = pps.to_nal();
323
324        let rbsp = emulation_unprevent(&nal.rbsp);
325        let mut r = BitReader::new(&rbsp);
326        assert_eq!(r.read_ue().unwrap(), 0); // pps id
327        assert_eq!(r.read_ue().unwrap(), 0); // sps id
328        assert!(!r.read_bit().unwrap()); // entropy_coding_mode (CAVLC)
329        assert!(!r.read_bit().unwrap()); // bottom_field
330        assert_eq!(r.read_ue().unwrap(), 0); // num_slice_groups_minus1
331        assert_eq!(r.read_ue().unwrap(), 0); // num_ref_idx_l0
332        assert_eq!(r.read_ue().unwrap(), 0); // num_ref_idx_l1
333        assert!(!r.read_bit().unwrap()); // weighted_pred
334        assert_eq!(r.read_bits(2).unwrap(), 0); // weighted_bipred_idc
335        assert_eq!(r.read_se().unwrap(), 0); // pic_init_qp_minus26 (qp 26)
336    }
337}