forge
Explore
Log in

Don't you dare go Hollow

NAL, SPS/PPS incl VUI+HRD, slice headers

Browse files at this commit

f07dac79e9d2db2d0b11399236155920c154526cAhmet Kaan GümüşParent: 1bc9080
  • feat
    • NAL, SPS/PPS incl VUI+HRD, slice headers
Show full message
feat(h264-syntax): NAL, SPS/PPS incl VUI+HRD, slice headers

Clean-room from Rec. ITU-T H.264 (V15, 08/2024) alone. Annex B scan and
emulation-prevention removal reuse a caller buffer (no per-NAL alloc);
SPS/PPS carry decode-ready derived geometry (MB counts, crop, bit depth)
so a decoder feeds flat per-picture arrays without re-deriving anything.
Slice headers parse all five slice types including P/B reference-list
modification, prediction weights and dec_ref_pic_marking, ready for the
inter slices that arrive with S18c. Scaling lists resolve fall-back
rules A/B at parse time.
crates/ec-h264-syntax/Cargo.tomladded+10 -0
@@ -0,0 +1,10 @@
1+[package]
2+name = "ec-h264-syntax"
3+description = "H.264 (ITU-T Rec. H.264) bitstream syntax: NAL, SPS/PPS, slice headers"
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+
9+[dependencies]
10+ec-core = { workspace = true }
crates/ec-h264-syntax/src/lib.rsadded+41 -0
@@ -0,0 +1,41 @@
1+//! H.264 (ITU-T Rec. H.264 / ISO 14496-10) bitstream syntax.
2+//!
3+//! Parsing only — no reconstruction. Shared by the software decoder
4+//! (`ec-h264`) and the stateless hardware path, so every struct is a plain
5+//! value type whose derived geometry (macroblock counts, crop rectangle,
6+//! bit depths) is computed once at parse time; a decoder feeds these fields
7+//! straight into flat per-picture arrays without re-deriving anything per
8+//! macroblock.
9+//!
10+//! Layout of the crate follows the spec's own structure:
11+//! - [`nal`]: Annex B framing + emulation-prevention removal (7.3.1, 7.4.1)
12+//! - [`sps`]: sequence parameter set incl. VUI and HRD (7.3.2.1, E.1)
13+//! - [`pps`]: picture parameter set incl. the High-profile tail (7.3.2.2)
14+//! - [`slice`]: slice header for I/SI/P/SP/B (7.3.3)
15+
16+#![forbid(unsafe_code)]
17+
18+pub mod nal;
19+pub mod pps;
20+pub mod slice;
21+pub mod sps;
22+
23+pub use nal::{AnnexBIter, NalHeader, NalUnitType, unescape_rbsp};
24+pub use pps::Pps;
25+pub use slice::{DeblockControl, SliceHeader, SliceType};
26+pub use sps::{Hrd, ScalingLists, Sps, Vui};
27+
28+/// True when there is at least one more RBSP syntax element before the
29+/// `rbsp_stop_one_bit` (spec 7.2 `more_rbsp_data()`).
30+///
31+/// `data` is the full unescaped RBSP the reader walks; the stop bit is the
32+/// last set bit of the last non-zero byte.
33+pub fn more_rbsp_data(reader: &ec_core::BitReader<'_>, data: &[u8]) -> bool {
34+ // Find the rbsp_stop_one_bit from the tail.
35+ let Some(last_nonzero) = data.iter().rposition(|&b| b != 0) else {
36+ return false; // all zero: corrupt, but by definition nothing left
37+ };
38+ let byte = data[last_nonzero];
39+ let stop_bit_index = last_nonzero as u64 * 8 + (7 - byte.trailing_zeros() as u64);
40+ reader.bit_position() < stop_bit_index
41+}
crates/ec-h264-syntax/src/nal.rsadded+257 -0
@@ -0,0 +1,257 @@
1+//! NAL unit framing: Annex B start-code scan and emulation-prevention
2+//! removal (spec 7.3.1, 7.4.1, B.1).
3+
4+use ec_core::error::{Error, Result};
5+
6+/// `nal_unit_type` code points (spec Table 7-1).
7+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8+pub enum NalUnitType {
9+ /// 1 — coded slice of a non-IDR picture.
10+ Slice,
11+ /// 2 — coded slice data partition A.
12+ SliceDataA,
13+ /// 3 — coded slice data partition B.
14+ SliceDataB,
15+ /// 4 — coded slice data partition C.
16+ SliceDataC,
17+ /// 5 — coded slice of an IDR picture.
18+ SliceIdr,
19+ /// 6 — supplemental enhancement information.
20+ Sei,
21+ /// 7 — sequence parameter set.
22+ Sps,
23+ /// 8 — picture parameter set.
24+ Pps,
25+ /// 9 — access unit delimiter.
26+ AccessUnitDelimiter,
27+ /// 10 — end of sequence.
28+ EndOfSequence,
29+ /// 11 — end of stream.
30+ EndOfStream,
31+ /// 12 — filler data.
32+ Filler,
33+ /// 13 — SPS extension.
34+ SpsExtension,
35+ /// 14 — prefix NAL unit (SVC/MVC).
36+ Prefix,
37+ /// 15 — subset SPS (SVC/MVC).
38+ SubsetSps,
39+ /// 19 — auxiliary coded picture slice.
40+ SliceAux,
41+ /// 20 — slice extension (SVC/MVC).
42+ SliceExtension,
43+ /// 21 — slice extension for depth/3D.
44+ SliceDepth,
45+ /// Any reserved or unspecified code point, carried verbatim.
46+ Other(u8),
47+}
48+
49+impl NalUnitType {
50+ /// Map the 5-bit code point.
51+ pub fn from_code(code: u8) -> NalUnitType {
52+ use NalUnitType::*;
53+ match code {
54+ 1 => Slice,
55+ 2 => SliceDataA,
56+ 3 => SliceDataB,
57+ 4 => SliceDataC,
58+ 5 => SliceIdr,
59+ 6 => Sei,
60+ 7 => Sps,
61+ 8 => Pps,
62+ 9 => AccessUnitDelimiter,
63+ 10 => EndOfSequence,
64+ 11 => EndOfStream,
65+ 12 => Filler,
66+ 13 => SpsExtension,
67+ 14 => Prefix,
68+ 15 => SubsetSps,
69+ 19 => SliceAux,
70+ 20 => SliceExtension,
71+ 21 => SliceDepth,
72+ n => Other(n),
73+ }
74+ }
75+
76+ /// True for the VCL slice types the decoder reconstructs pictures from.
77+ pub fn is_slice(&self) -> bool {
78+ matches!(self, NalUnitType::Slice | NalUnitType::SliceIdr)
79+ }
80+}
81+
82+/// First byte of a NAL unit (spec 7.3.1).
83+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84+pub struct NalHeader {
85+ /// `nal_ref_idc`: 0 = disposable, >0 = used for reference.
86+ pub ref_idc: u8,
87+ /// `nal_unit_type`.
88+ pub unit_type: NalUnitType,
89+}
90+
91+impl NalHeader {
92+ /// Parse the header byte; `forbidden_zero_bit` set is a corrupt stream.
93+ pub fn parse(byte: u8) -> Result<NalHeader> {
94+ if byte & 0x80 != 0 {
95+ return Err(Error::corrupt("NAL forbidden_zero_bit set"));
96+ }
97+ Ok(NalHeader {
98+ ref_idc: (byte >> 5) & 0x3,
99+ unit_type: NalUnitType::from_code(byte & 0x1F),
100+ })
101+ }
102+
103+ /// True for an IDR slice.
104+ pub fn is_idr(&self) -> bool {
105+ self.unit_type == NalUnitType::SliceIdr
106+ }
107+}
108+
109+/// Iterator over NAL unit payloads in an Annex B byte stream (spec B.1).
110+///
111+/// Yields each NAL unit as a sub-slice of the input **including** its header
112+/// byte, with start codes (`00 00 01` / `00 00 00 01`) stripped and trailing
113+/// zero padding removed. Borrowing, zero-copy: emulation prevention is left
114+/// in place for [`unescape_rbsp`] to strip into a reusable buffer.
115+#[derive(Debug, Clone)]
116+pub struct AnnexBIter<'a> {
117+ data: &'a [u8],
118+ pos: usize,
119+}
120+
121+impl<'a> AnnexBIter<'a> {
122+ /// Iterate over `data`, skipping anything before the first start code.
123+ pub fn new(data: &'a [u8]) -> AnnexBIter<'a> {
124+ AnnexBIter { data, pos: 0 }
125+ }
126+
127+ /// Position of the next `00 00 01` at or after `from`, or `len`.
128+ fn next_start_code(&self, from: usize) -> Option<usize> {
129+ let d = self.data;
130+ let mut i = from;
131+ // memchr-style scan on the middle zero of `00 00 01`.
132+ while i + 2 < d.len() {
133+ if d[i + 1] != 0 {
134+ i += 2;
135+ } else if d[i] != 0 {
136+ i += 1;
137+ } else if d[i + 2] == 1 {
138+ return Some(i);
139+ } else {
140+ i += 1;
141+ }
142+ }
143+ None
144+ }
145+}
146+
147+impl<'a> Iterator for AnnexBIter<'a> {
148+ type Item = &'a [u8];
149+
150+ fn next(&mut self) -> Option<&'a [u8]> {
151+ let start = self.next_start_code(self.pos)? + 3;
152+ if start >= self.data.len() {
153+ self.pos = self.data.len();
154+ return None;
155+ }
156+ let (end, next_pos) = match self.next_start_code(start) {
157+ Some(sc) => (sc, sc),
158+ None => (self.data.len(), self.data.len()),
159+ };
160+ self.pos = next_pos;
161+ // Trailing zero bytes before the next start code belong to the start
162+ // code prefix / trailing_zero_8bits, not to this NAL unit.
163+ let mut end = end;
164+ while end > start && self.data[end - 1] == 0 {
165+ end -= 1;
166+ }
167+ if end == start {
168+ // Empty NAL unit (all-zero span): skip to the next one.
169+ return self.next();
170+ }
171+ Some(&self.data[start..end])
172+ }
173+}
174+
175+/// Strip emulation-prevention bytes (spec 7.4.1.1): every `00 00 03` becomes
176+/// `00 00`. `nal` is the NAL payload **after** the header byte; the result is
177+/// appended into `out`, which is cleared first and whose capacity is reused
178+/// across calls — the steady-state decode loop performs no allocation once
179+/// `out` has grown to the largest NAL size.
180+pub fn unescape_rbsp(nal: &[u8], out: &mut Vec<u8>) {
181+ out.clear();
182+ out.reserve(nal.len());
183+ let mut zeros = 0u32;
184+ let mut i = 0;
185+ while i < nal.len() {
186+ let b = nal[i];
187+ if zeros >= 2 && b == 3 {
188+ // Emulation prevention byte: drop it, next byte restarts the count.
189+ zeros = 0;
190+ i += 1;
191+ continue;
192+ }
193+ zeros = if b == 0 { zeros + 1 } else { 0 };
194+ out.push(b);
195+ i += 1;
196+ }
197+}
198+
199+#[cfg(test)]
200+mod tests {
201+ use super::*;
202+
203+ #[test]
204+ fn annexb_split_three_and_four_byte_codes() {
205+ let data = [
206+ 0x00, 0x00, 0x00, 0x01, 0x67, 0xAA, // SPS
207+ 0x00, 0x00, 0x01, 0x68, 0xBB, // PPS
208+ 0x00, 0x00, 0x00, 0x01, 0x65, 0xCC, 0xDD, // IDR
209+ ];
210+ let nals: Vec<&[u8]> = AnnexBIter::new(&data).collect();
211+ assert_eq!(nals.len(), 3);
212+ assert_eq!(nals[0], &[0x67, 0xAA]);
213+ assert_eq!(nals[1], &[0x68, 0xBB]);
214+ assert_eq!(nals[2], &[0x65, 0xCC, 0xDD]);
215+ }
216+
217+ #[test]
218+ fn annexb_trailing_zeros_trimmed_and_garbage_prefix_skipped() {
219+ let data = [
220+ 0xDE, 0xAD, // garbage before the first start code
221+ 0x00, 0x00, 0x01, 0x41, 0x01, 0x00, 0x00, // trailing zeros
222+ 0x00, 0x00, 0x01, 0x41, 0x02,
223+ ];
224+ let nals: Vec<&[u8]> = AnnexBIter::new(&data).collect();
225+ assert_eq!(nals.len(), 2);
226+ assert_eq!(nals[0], &[0x41, 0x01]);
227+ assert_eq!(nals[1], &[0x41, 0x02]);
228+ }
229+
230+ #[test]
231+ fn unescape_removes_only_emulation_bytes() {
232+ let mut out = Vec::new();
233+ unescape_rbsp(&[0x00, 0x00, 0x03, 0x00, 0x01], &mut out);
234+ assert_eq!(out, &[0x00, 0x00, 0x00, 0x01]);
235+ // 00 00 03 03 -> 00 00 03: only the first 03 is the escape.
236+ unescape_rbsp(&[0x00, 0x00, 0x03, 0x03, 0x01], &mut out);
237+ assert_eq!(out, &[0x00, 0x00, 0x03, 0x01]);
238+ // A 03 not preceded by two zeros stays.
239+ unescape_rbsp(&[0x01, 0x03, 0x00, 0x03], &mut out);
240+ assert_eq!(out, &[0x01, 0x03, 0x00, 0x03]);
241+ // Reuse does not leak previous contents.
242+ unescape_rbsp(&[0x7F], &mut out);
243+ assert_eq!(out, &[0x7F]);
244+ }
245+
246+ #[test]
247+ fn header_parse_and_forbidden_bit() {
248+ let h = NalHeader::parse(0x67).unwrap();
249+ assert_eq!(h.ref_idc, 3);
250+ assert_eq!(h.unit_type, NalUnitType::Sps);
251+ assert!(!h.is_idr());
252+ let h = NalHeader::parse(0x65).unwrap();
253+ assert!(h.is_idr());
254+ assert!(h.unit_type.is_slice());
255+ assert!(NalHeader::parse(0x80).is_err());
256+ }
257+}
crates/ec-h264-syntax/src/pps.rsadded+266 -0
@@ -0,0 +1,266 @@
1+//! Picture parameter set (spec 7.3.2.2, 7.4.2.2).
2+
3+use ec_core::BitReader;
4+use ec_core::error::{Error, Result};
5+
6+use crate::more_rbsp_data;
7+use crate::sps::{ScalingLists, Sps, parse_scaling_matrix};
8+
9+/// Slice-group (FMO) map data, parsed but not interpreted here.
10+#[derive(Debug, Clone, PartialEq, Eq)]
11+pub enum SliceGroupMap {
12+ /// Type 0: `run_length_minus1` per group.
13+ Interleaved(Vec<u32>),
14+ /// Type 1: dispersed, no extra data.
15+ Dispersed,
16+ /// Type 2: `(top_left, bottom_right)` per group but the last.
17+ Foreground(Vec<(u32, u32)>),
18+ /// Types 3..=5: `(change_direction_flag, change_rate_minus1)`.
19+ Changing {
20+ /// `slice_group_map_type` (3, 4 or 5).
21+ map_type: u8,
22+ /// `slice_group_change_direction_flag`.
23+ change_direction: bool,
24+ /// `slice_group_change_rate_minus1`.
25+ change_rate_minus1: u32,
26+ },
27+ /// Type 6: explicit per-map-unit assignment.
28+ Explicit(Vec<u32>),
29+}
30+
31+/// Picture parameter set with decode-ready fields.
32+#[derive(Debug, Clone, PartialEq, Eq)]
33+pub struct Pps {
34+ /// `pic_parameter_set_id` (0..=255).
35+ pub id: u32,
36+ /// `seq_parameter_set_id` of the SPS this PPS refers to.
37+ pub sps_id: u8,
38+ /// `entropy_coding_mode_flag`: false = CAVLC, true = CABAC.
39+ pub entropy_coding_mode: bool,
40+ /// `bottom_field_pic_order_in_frame_present_flag`.
41+ pub bottom_field_pic_order_in_frame_present: bool,
42+ /// `num_slice_groups_minus1` + 1.
43+ pub num_slice_groups: u32,
44+ /// FMO map when `num_slice_groups > 1`.
45+ pub slice_group_map: Option<SliceGroupMap>,
46+ /// `num_ref_idx_l0_default_active_minus1` + 1.
47+ pub num_ref_idx_l0_default_active: u32,
48+ /// `num_ref_idx_l1_default_active_minus1` + 1.
49+ pub num_ref_idx_l1_default_active: u32,
50+ /// `weighted_pred_flag`.
51+ pub weighted_pred: bool,
52+ /// `weighted_bipred_idc` (0..=2).
53+ pub weighted_bipred_idc: u8,
54+ /// `pic_init_qp_minus26` + 26.
55+ pub pic_init_qp: i32,
56+ /// `pic_init_qs_minus26` + 26.
57+ pub pic_init_qs: i32,
58+ /// `chroma_qp_index_offset` (-12..=12), for Cb.
59+ pub chroma_qp_index_offset: i32,
60+ /// `deblocking_filter_control_present_flag`.
61+ pub deblocking_filter_control_present: bool,
62+ /// `constrained_intra_pred_flag`.
63+ pub constrained_intra_pred: bool,
64+ /// `redundant_pic_cnt_present_flag`.
65+ pub redundant_pic_cnt_present: bool,
66+ /// `transform_8x8_mode_flag` (High-profile tail; false when absent).
67+ pub transform_8x8_mode: bool,
68+ /// PPS scaling lists when `pic_scaling_matrix_present_flag`, resolved
69+ /// against the SPS lists per fall-back rule B.
70+ pub scaling_lists: Option<ScalingLists>,
71+ /// `second_chroma_qp_index_offset` for Cr (defaults to the Cb offset).
72+ pub second_chroma_qp_index_offset: i32,
73+}
74+
75+impl Pps {
76+ /// Parse a PPS RBSP (header byte consumed, emulation stripped).
77+ ///
78+ /// `sps_lookup` resolves the referenced SPS — needed for the High-profile
79+ /// tail (scaling-list fall-back and 4:4:4 list count).
80+ pub fn parse<'s>(rbsp: &[u8], sps_lookup: impl Fn(u8) -> Option<&'s Sps>) -> Result<Pps> {
81+ let mut reader = BitReader::new(rbsp);
82+ let r = &mut reader;
83+ let id = r.read_ue()?;
84+ if id > 255 {
85+ return Err(Error::corrupt("pic_parameter_set_id > 255"));
86+ }
87+ let sps_id = r.read_ue()?;
88+ if sps_id > 31 {
89+ return Err(Error::corrupt("seq_parameter_set_id > 31"));
90+ }
91+ let sps_id = sps_id as u8;
92+ let entropy_coding_mode = r.read_bit()?;
93+ let bottom_field_pic_order_in_frame_present = r.read_bit()?;
94+ let num_slice_groups = r.read_ue()?.checked_add(1).ok_or(Error::NeedMore)?;
95+ if num_slice_groups > 8 {
96+ return Err(Error::corrupt("num_slice_groups > 8"));
97+ }
98+ let slice_group_map = if num_slice_groups > 1 {
99+ Some(Self::parse_slice_groups(r, num_slice_groups)?)
100+ } else {
101+ None
102+ };
103+ let num_ref_idx_l0_default_active = r.read_ue()? + 1;
104+ let num_ref_idx_l1_default_active = r.read_ue()? + 1;
105+ if num_ref_idx_l0_default_active > 32 || num_ref_idx_l1_default_active > 32 {
106+ return Err(Error::corrupt("num_ref_idx_default_active > 32"));
107+ }
108+ let weighted_pred = r.read_bit()?;
109+ let weighted_bipred_idc = r.read_bits(2)? as u8;
110+ let pic_init_qp = 26 + r.read_se()?;
111+ let pic_init_qs = 26 + r.read_se()?;
112+ let chroma_qp_index_offset = r.read_se()?;
113+ if !(-12..=12).contains(&chroma_qp_index_offset) {
114+ return Err(Error::corrupt("chroma_qp_index_offset outside [-12, 12]"));
115+ }
116+ let deblocking_filter_control_present = r.read_bit()?;
117+ let constrained_intra_pred = r.read_bit()?;
118+ let redundant_pic_cnt_present = r.read_bit()?;
119+
120+ let mut transform_8x8_mode = false;
121+ let mut scaling_lists = None;
122+ let mut second_chroma_qp_index_offset = chroma_qp_index_offset;
123+ if more_rbsp_data(r, rbsp) {
124+ transform_8x8_mode = r.read_bit()?;
125+ if r.read_bit()? {
126+ // pic_scaling_matrix_present_flag
127+ let sps = sps_lookup(sps_id);
128+ let chroma_444 = sps.map(|s| s.chroma_format_idc == 3).unwrap_or(false);
129+ let count = 6 + if chroma_444 { 6 } else { 2 } * usize::from(transform_8x8_mode);
130+ scaling_lists = Some(parse_scaling_matrix(
131+ r,
132+ count,
133+ sps.and_then(|s| s.scaling_lists.as_ref()),
134+ )?);
135+ }
136+ second_chroma_qp_index_offset = r.read_se()?;
137+ if !(-12..=12).contains(&second_chroma_qp_index_offset) {
138+ return Err(Error::corrupt(
139+ "second_chroma_qp_index_offset outside [-12, 12]",
140+ ));
141+ }
142+ }
143+
144+ Ok(Pps {
145+ id,
146+ sps_id,
147+ entropy_coding_mode,
148+ bottom_field_pic_order_in_frame_present,
149+ num_slice_groups,
150+ slice_group_map,
151+ num_ref_idx_l0_default_active,
152+ num_ref_idx_l1_default_active,
153+ weighted_pred,
154+ weighted_bipred_idc,
155+ pic_init_qp,
156+ pic_init_qs,
157+ chroma_qp_index_offset,
158+ deblocking_filter_control_present,
159+ constrained_intra_pred,
160+ redundant_pic_cnt_present,
161+ transform_8x8_mode,
162+ scaling_lists,
163+ second_chroma_qp_index_offset,
164+ })
165+ }
166+
167+ fn parse_slice_groups(r: &mut BitReader<'_>, groups: u32) -> Result<SliceGroupMap> {
168+ let map_type = r.read_ue()?;
169+ Ok(match map_type {
170+ 0 => {
171+ let mut runs = Vec::with_capacity(groups as usize);
172+ for _ in 0..groups {
173+ runs.push(r.read_ue()?);
174+ }
175+ SliceGroupMap::Interleaved(runs)
176+ }
177+ 1 => SliceGroupMap::Dispersed,
178+ 2 => {
179+ let mut rects = Vec::with_capacity(groups as usize - 1);
180+ for _ in 0..groups - 1 {
181+ rects.push((r.read_ue()?, r.read_ue()?));
182+ }
183+ SliceGroupMap::Foreground(rects)
184+ }
185+ 3..=5 => SliceGroupMap::Changing {
186+ map_type: map_type as u8,
187+ change_direction: r.read_bit()?,
188+ change_rate_minus1: r.read_ue()?,
189+ },
190+ 6 => {
191+ let count = r.read_ue()?.checked_add(1).ok_or(Error::NeedMore)?;
192+ if count > 1 << 20 {
193+ return Err(Error::corrupt("slice group map unit count implausible"));
194+ }
195+ let bits = 32 - (groups - 1).leading_zeros().min(31);
196+ let bits = if groups > 1 { bits.max(1) } else { 1 };
197+ let mut ids = Vec::with_capacity(count as usize);
198+ for _ in 0..count {
199+ ids.push(r.read_bits(bits)?);
200+ }
201+ SliceGroupMap::Explicit(ids)
202+ }
203+ _ => return Err(Error::corrupt("slice_group_map_type > 6")),
204+ })
205+ }
206+}
207+
208+#[cfg(test)]
209+mod tests {
210+ use super::*;
211+ use ec_core::BitWriter;
212+
213+ fn write_baseline_pps(w: &mut BitWriter) {
214+ w.write_ue(0); // pps id
215+ w.write_ue(0); // sps id
216+ w.write_bit(false); // CAVLC
217+ w.write_bit(false); // bottom_field_pic_order
218+ w.write_ue(0); // one slice group
219+ w.write_ue(0); // l0 default
220+ w.write_ue(0); // l1 default
221+ w.write_bit(false); // weighted_pred
222+ w.write_bits(0, 2); // weighted_bipred_idc
223+ w.write_se(0); // pic_init_qp = 26
224+ w.write_se(0); // pic_init_qs
225+ w.write_se(2); // chroma_qp_index_offset
226+ w.write_bit(true); // deblocking control present
227+ w.write_bit(false); // constrained intra
228+ w.write_bit(false); // redundant pic cnt
229+ }
230+
231+ #[test]
232+ fn baseline_pps_without_tail() {
233+ let mut w = BitWriter::new();
234+ write_baseline_pps(&mut w);
235+ w.write_bit(true); // rbsp_stop_one_bit
236+ w.align_to_byte();
237+ let pps = Pps::parse(w.as_bytes(), |_| None).unwrap();
238+ assert_eq!(pps.id, 0);
239+ assert!(!pps.entropy_coding_mode);
240+ assert_eq!(pps.pic_init_qp, 26);
241+ assert_eq!(pps.chroma_qp_index_offset, 2);
242+ assert_eq!(pps.second_chroma_qp_index_offset, 2); // inherits
243+ assert!(!pps.transform_8x8_mode);
244+ assert!(pps.deblocking_filter_control_present);
245+ }
246+
247+ #[test]
248+ fn high_profile_tail_parsed() {
249+ let mut w = BitWriter::new();
250+ write_baseline_pps(&mut w);
251+ w.write_bit(true); // transform_8x8_mode
252+ w.write_bit(false); // no pic scaling matrix
253+ w.write_se(-3); // second_chroma_qp_index_offset
254+ w.write_bit(true); // stop bit
255+ w.align_to_byte();
256+ let pps = Pps::parse(w.as_bytes(), |_| None).unwrap();
257+ assert!(pps.transform_8x8_mode);
258+ assert_eq!(pps.second_chroma_qp_index_offset, -3);
259+ assert_eq!(pps.chroma_qp_index_offset, 2);
260+ }
261+
262+ #[test]
263+ fn truncated_pps_is_need_more() {
264+ assert!(Pps::parse(&[], |_| None).unwrap_err().is_need_more());
265+ }
266+}
crates/ec-h264-syntax/src/slice.rsadded+608 -0
@@ -0,0 +1,608 @@
1+//! Slice header (spec 7.3.3, 7.4.3) for all five slice types.
2+
3+use ec_core::BitReader;
4+use ec_core::error::{Error, Result};
5+
6+use crate::nal::NalHeader;
7+use crate::pps::Pps;
8+use crate::sps::Sps;
9+
10+/// `slice_type` % 5 (spec Table 7-6).
11+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12+pub enum SliceType {
13+ /// Predicted slice.
14+ P,
15+ /// Bi-predicted slice.
16+ B,
17+ /// Intra slice.
18+ I,
19+ /// Switching-predicted slice.
20+ Sp,
21+ /// Switching-intra slice.
22+ Si,
23+}
24+
25+impl SliceType {
26+ /// Map `slice_type` (0..=9); values 5..=9 assert the type for the whole
27+ /// picture but decode identically.
28+ pub fn from_code(code: u32) -> Result<SliceType> {
29+ Ok(match code % 5 {
30+ 0 => SliceType::P,
31+ 1 => SliceType::B,
32+ 2 => SliceType::I,
33+ 3 => SliceType::Sp,
34+ 4 => SliceType::Si,
35+ _ => unreachable!(),
36+ })
37+ }
38+
39+ /// True for I and SI.
40+ pub fn is_intra(&self) -> bool {
41+ matches!(self, SliceType::I | SliceType::Si)
42+ }
43+}
44+
45+/// One `ref_pic_list_modification` operation (spec 7.3.3.1).
46+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47+pub enum RefPicListMod {
48+ /// `modification_of_pic_nums_idc` 0/1: `abs_diff_pic_num_minus1`,
49+ /// subtract (idc 0) or add (idc 1).
50+ ShortTerm {
51+ /// `abs_diff_pic_num_minus1`.
52+ abs_diff_pic_num_minus1: u32,
53+ /// idc 1 = add, idc 0 = subtract.
54+ add: bool,
55+ },
56+ /// idc 2: `long_term_pic_num`.
57+ LongTerm(u32),
58+}
59+
60+/// One explicit weight entry of the `pred_weight_table` (spec 7.3.3.2).
61+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
62+pub struct WeightEntry {
63+ /// `(luma_weight, luma_offset)` when `luma_weight_flag`.
64+ pub luma: Option<(i32, i32)>,
65+ /// `[(cb_weight, cb_offset), (cr_weight, cr_offset)]` when signalled.
66+ pub chroma: Option<[(i32, i32); 2]>,
67+}
68+
69+/// `pred_weight_table` (spec 7.3.3.2).
70+#[derive(Debug, Clone, PartialEq, Eq, Default)]
71+pub struct PredWeightTable {
72+ /// `luma_log2_weight_denom`.
73+ pub luma_log2_weight_denom: u32,
74+ /// `chroma_log2_weight_denom` (chroma formats only).
75+ pub chroma_log2_weight_denom: u32,
76+ /// Per-reference weights, list 0.
77+ pub l0: Vec<WeightEntry>,
78+ /// Per-reference weights, list 1 (B slices).
79+ pub l1: Vec<WeightEntry>,
80+}
81+
82+/// One memory-management control operation (spec 7.3.3.3, Table 7-9).
83+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84+pub struct Mmco {
85+ /// `memory_management_control_operation` (1..=6).
86+ pub op: u32,
87+ /// First operand (difference_of_pic_nums_minus1 / long_term_pic_num /
88+ /// long_term_frame_idx / max_long_term_frame_idx_plus1), op-dependent.
89+ pub arg1: u32,
90+ /// Second operand (op 3: `long_term_frame_idx`).
91+ pub arg2: u32,
92+}
93+
94+/// `dec_ref_pic_marking` (spec 7.3.3.3).
95+#[derive(Debug, Clone, PartialEq, Eq, Default)]
96+pub struct DecRefPicMarking {
97+ /// IDR: `no_output_of_prior_pics_flag`.
98+ pub no_output_of_prior_pics: bool,
99+ /// IDR: `long_term_reference_flag`.
100+ pub long_term_reference: bool,
101+ /// Non-IDR: `adaptive_ref_pic_marking_mode_flag`.
102+ pub adaptive: bool,
103+ /// Adaptive-mode operations, in order.
104+ pub mmcos: Vec<Mmco>,
105+}
106+
107+/// Deblocking-filter control from the slice header (spec 7.4.3).
108+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
109+pub struct DeblockControl {
110+ /// `disable_deblocking_filter_idc`: 0 = on, 1 = off, 2 = on but not
111+ /// across slice boundaries.
112+ pub disable_idc: u8,
113+ /// `slice_alpha_c0_offset_div2` * 2.
114+ pub alpha_c0_offset: i32,
115+ /// `slice_beta_offset_div2` * 2.
116+ pub beta_offset: i32,
117+}
118+
119+/// Parsed slice header.
120+#[derive(Debug, Clone, PartialEq, Eq)]
121+pub struct SliceHeader {
122+ /// `first_mb_in_slice` (macroblock address; frame coding).
123+ pub first_mb_in_slice: u32,
124+ /// Slice type (already reduced mod 5).
125+ pub slice_type: SliceType,
126+ /// True when `slice_type` was 5..=9: every slice of the picture has
127+ /// this type.
128+ pub all_slices_same_type: bool,
129+ /// `pic_parameter_set_id`.
130+ pub pps_id: u32,
131+ /// `colour_plane_id` (separate colour planes only).
132+ pub colour_plane_id: u8,
133+ /// `frame_num`.
134+ pub frame_num: u32,
135+ /// `field_pic_flag`.
136+ pub field_pic: bool,
137+ /// `bottom_field_flag`.
138+ pub bottom_field: bool,
139+ /// `idr_pic_id` for IDR slices.
140+ pub idr_pic_id: Option<u32>,
141+ /// `pic_order_cnt_lsb` (POC type 0).
142+ pub pic_order_cnt_lsb: u32,
143+ /// `delta_pic_order_cnt_bottom` (POC type 0 + PPS flag).
144+ pub delta_pic_order_cnt_bottom: i32,
145+ /// `delta_pic_order_cnt[0..2]` (POC type 1).
146+ pub delta_pic_order_cnt: [i32; 2],
147+ /// `redundant_pic_cnt` when present.
148+ pub redundant_pic_cnt: u32,
149+ /// B: `direct_spatial_mv_pred_flag`.
150+ pub direct_spatial_mv_pred: bool,
151+ /// Active reference count, list 0 (P/SP/B; PPS default applied).
152+ pub num_ref_idx_l0_active: u32,
153+ /// Active reference count, list 1 (B; PPS default applied).
154+ pub num_ref_idx_l1_active: u32,
155+ /// Reference list modifications, list 0.
156+ pub ref_pic_list_mod_l0: Vec<RefPicListMod>,
157+ /// Reference list modifications, list 1.
158+ pub ref_pic_list_mod_l1: Vec<RefPicListMod>,
159+ /// Prediction weight table when signalled.
160+ pub pred_weight_table: Option<PredWeightTable>,
161+ /// Reference-picture marking when `nal_ref_idc != 0`.
162+ pub dec_ref_pic_marking: Option<DecRefPicMarking>,
163+ /// `cabac_init_idc` (CABAC, non-intra slices).
164+ pub cabac_init_idc: u32,
165+ /// `SliceQPY` = 26 + pic_init_qp_minus26 + slice_qp_delta.
166+ pub slice_qp: i32,
167+ /// SP: `sp_for_switch_flag`.
168+ pub sp_for_switch: bool,
169+ /// SP/SI: `SliceQSY`.
170+ pub slice_qs: i32,
171+ /// Deblocking control (defaults when the PPS does not signal it).
172+ pub deblock: DeblockControl,
173+ /// `slice_group_change_cycle` (FMO map types 3..=5).
174+ pub slice_group_change_cycle: u32,
175+ /// Bits consumed by the header — slice data starts here.
176+ pub header_bits: u64,
177+}
178+
179+impl SliceHeader {
180+ /// Parse a slice header from the RBSP after the NAL header byte.
181+ pub fn parse(rbsp: &[u8], nal: NalHeader, sps: &Sps, pps: &Pps) -> Result<SliceHeader> {
182+ let mut reader = BitReader::new(rbsp);
183+ let r = &mut reader;
184+ let first_mb_in_slice = r.read_ue()?;
185+ let slice_type_code = r.read_ue()?;
186+ if slice_type_code > 9 {
187+ return Err(Error::corrupt("slice_type > 9"));
188+ }
189+ let slice_type = SliceType::from_code(slice_type_code)?;
190+ let all_slices_same_type = slice_type_code > 4;
191+ let pps_id = r.read_ue()?;
192+ if pps_id != pps.id {
193+ return Err(Error::corrupt("slice parsed against the wrong PPS"));
194+ }
195+ let colour_plane_id = if sps.separate_colour_plane {
196+ r.read_bits(2)? as u8
197+ } else {
198+ 0
199+ };
200+ let frame_num = r.read_bits(sps.log2_max_frame_num as u32)?;
201+ let mut field_pic = false;
202+ let mut bottom_field = false;
203+ if !sps.frame_mbs_only {
204+ field_pic = r.read_bit()?;
205+ if field_pic {
206+ bottom_field = r.read_bit()?;
207+ }
208+ }
209+ let idr_pic_id = if nal.is_idr() {
210+ let v = r.read_ue()?;
211+ if v > 65535 {
212+ return Err(Error::corrupt("idr_pic_id > 65535"));
213+ }
214+ Some(v)
215+ } else {
216+ None
217+ };
218+ let mut pic_order_cnt_lsb = 0;
219+ let mut delta_pic_order_cnt_bottom = 0;
220+ let mut delta_pic_order_cnt = [0i32; 2];
221+ match sps.pic_order_cnt_type {
222+ 0 => {
223+ pic_order_cnt_lsb = r.read_bits(sps.log2_max_pic_order_cnt_lsb as u32)?;
224+ if pps.bottom_field_pic_order_in_frame_present && !field_pic {
225+ delta_pic_order_cnt_bottom = r.read_se()?;
226+ }
227+ }
228+ 1 if !sps.delta_pic_order_always_zero => {
229+ delta_pic_order_cnt[0] = r.read_se()?;
230+ if pps.bottom_field_pic_order_in_frame_present && !field_pic {
231+ delta_pic_order_cnt[1] = r.read_se()?;
232+ }
233+ }
234+ _ => {}
235+ }
236+ let redundant_pic_cnt = if pps.redundant_pic_cnt_present {
237+ r.read_ue()?
238+ } else {
239+ 0
240+ };
241+ let direct_spatial_mv_pred = if slice_type == SliceType::B {
242+ r.read_bit()?
243+ } else {
244+ false
245+ };
246+
247+ let mut num_ref_idx_l0_active = pps.num_ref_idx_l0_default_active;
248+ let mut num_ref_idx_l1_active = pps.num_ref_idx_l1_default_active;
249+ if matches!(slice_type, SliceType::P | SliceType::Sp | SliceType::B) {
250+ if r.read_bit()? {
251+ // num_ref_idx_active_override_flag
252+ num_ref_idx_l0_active = r.read_ue()? + 1;
253+ if slice_type == SliceType::B {
254+ num_ref_idx_l1_active = r.read_ue()? + 1;
255+ }
256+ }
257+ if num_ref_idx_l0_active > 32 || num_ref_idx_l1_active > 32 {
258+ return Err(Error::corrupt("num_ref_idx_active > 32"));
259+ }
260+ }
261+
262+ // ref_pic_list_modification (7.3.3.1) — not for I/SI.
263+ let mut ref_pic_list_mod_l0 = Vec::new();
264+ let mut ref_pic_list_mod_l1 = Vec::new();
265+ if !slice_type.is_intra() {
266+ Self::parse_ref_list_mod(r, &mut ref_pic_list_mod_l0)?;
267+ }
268+ if slice_type == SliceType::B {
269+ Self::parse_ref_list_mod(r, &mut ref_pic_list_mod_l1)?;
270+ }
271+
272+ // pred_weight_table (7.3.3.2).
273+ let pred_weight_table = if (pps.weighted_pred
274+ && matches!(slice_type, SliceType::P | SliceType::Sp))
275+ || (pps.weighted_bipred_idc == 1 && slice_type == SliceType::B)
276+ {
277+ Some(Self::parse_pred_weight_table(
278+ r,
279+ sps,
280+ slice_type,
281+ num_ref_idx_l0_active,
282+ num_ref_idx_l1_active,
283+ )?)
284+ } else {
285+ None
286+ };
287+
288+ // dec_ref_pic_marking (7.3.3.3).
289+ let dec_ref_pic_marking = if nal.ref_idc != 0 {
290+ let mut m = DecRefPicMarking::default();
291+ if nal.is_idr() {
292+ m.no_output_of_prior_pics = r.read_bit()?;
293+ m.long_term_reference = r.read_bit()?;
294+ } else {
295+ m.adaptive = r.read_bit()?;
296+ if m.adaptive {
297+ loop {
298+ let op = r.read_ue()?;
299+ if op == 0 {
300+ break;
301+ }
302+ if op > 6 {
303+ return Err(Error::corrupt("memory_management_control_operation > 6"));
304+ }
305+ if m.mmcos.len() >= 64 {
306+ return Err(Error::corrupt("more than 64 MMCO operations"));
307+ }
308+ let arg1 = match op {
309+ 1..=4 => r.read_ue()?,
310+ 6 => r.read_ue()?,
311+ _ => 0,
312+ };
313+ let arg2 = if op == 3 { r.read_ue()? } else { 0 };
314+ m.mmcos.push(Mmco { op, arg1, arg2 });
315+ }
316+ }
317+ }
318+ Some(m)
319+ } else {
320+ None
321+ };
322+
323+ let cabac_init_idc = if pps.entropy_coding_mode && !slice_type.is_intra() {
324+ let v = r.read_ue()?;
325+ if v > 2 {
326+ return Err(Error::corrupt("cabac_init_idc > 2"));
327+ }
328+ v
329+ } else {
330+ 0
331+ };
332+
333+ let slice_qp_delta = r.read_se()?;
334+ let slice_qp = pps.pic_init_qp + slice_qp_delta;
335+ if !(-(sps.bit_depth_luma as i32 - 8) * 6..=51).contains(&slice_qp) {
336+ return Err(Error::corrupt("SliceQPY out of range"));
337+ }
338+
339+ let mut sp_for_switch = false;
340+ let mut slice_qs = pps.pic_init_qs;
341+ if matches!(slice_type, SliceType::Sp | SliceType::Si) {
342+ if slice_type == SliceType::Sp {
343+ sp_for_switch = r.read_bit()?;
344+ }
345+ slice_qs = pps.pic_init_qs + r.read_se()?;
346+ if !(0..=51).contains(&slice_qs) {
347+ return Err(Error::corrupt("SliceQSY out of range"));
348+ }
349+ }
350+
351+ let mut deblock = DeblockControl::default();
352+ if pps.deblocking_filter_control_present {
353+ let idc = r.read_ue()?;
354+ if idc > 2 {
355+ return Err(Error::corrupt("disable_deblocking_filter_idc > 2"));
356+ }
357+ deblock.disable_idc = idc as u8;
358+ if idc != 1 {
359+ let a = r.read_se()?;
360+ let b = r.read_se()?;
361+ if !(-6..=6).contains(&a) || !(-6..=6).contains(&b) {
362+ return Err(Error::corrupt("deblocking offset div2 outside [-6, 6]"));
363+ }
364+ deblock.alpha_c0_offset = a * 2;
365+ deblock.beta_offset = b * 2;
366+ }
367+ }
368+
369+ let mut slice_group_change_cycle = 0;
370+ if pps.num_slice_groups > 1
371+ && let Some(crate::pps::SliceGroupMap::Changing {
372+ change_rate_minus1, ..
373+ }) = &pps.slice_group_map
374+ {
375+ // u(v) with v = Ceil(Log2(PicSizeInMapUnits / SliceGroupChangeRate + 1)).
376+ let pic_size_in_map_units =
377+ sps.mb_width * (sps.mb_height / if sps.frame_mbs_only { 1 } else { 2 });
378+ let rate = change_rate_minus1 + 1;
379+ let max = pic_size_in_map_units.div_ceil(rate) + 1;
380+ let bits = 32 - (max - 1).leading_zeros();
381+ slice_group_change_cycle = r.read_bits(bits.max(1))?;
382+ }
383+
384+ Ok(SliceHeader {
385+ first_mb_in_slice,
386+ slice_type,
387+ all_slices_same_type,
388+ pps_id,
389+ colour_plane_id,
390+ frame_num,
391+ field_pic,
392+ bottom_field,
393+ idr_pic_id,
394+ pic_order_cnt_lsb,
395+ delta_pic_order_cnt_bottom,
396+ delta_pic_order_cnt,
397+ redundant_pic_cnt,
398+ direct_spatial_mv_pred,
399+ num_ref_idx_l0_active,
400+ num_ref_idx_l1_active,
401+ ref_pic_list_mod_l0,
402+ ref_pic_list_mod_l1,
403+ pred_weight_table,
404+ dec_ref_pic_marking,
405+ cabac_init_idc,
406+ slice_qp,
407+ sp_for_switch,
408+ slice_qs,
409+ deblock,
410+ slice_group_change_cycle,
411+ header_bits: reader.bit_position(),
412+ })
413+ }
414+
415+ fn parse_ref_list_mod(r: &mut BitReader<'_>, out: &mut Vec<RefPicListMod>) -> Result<()> {
416+ if !r.read_bit()? {
417+ return Ok(()); // ref_pic_list_modification_flag == 0
418+ }
419+ loop {
420+ let idc = r.read_ue()?;
421+ match idc {
422+ 0 | 1 => out.push(RefPicListMod::ShortTerm {
423+ abs_diff_pic_num_minus1: r.read_ue()?,
424+ add: idc == 1,
425+ }),
426+ 2 => out.push(RefPicListMod::LongTerm(r.read_ue()?)),
427+ 3 => return Ok(()),
428+ _ => return Err(Error::corrupt("modification_of_pic_nums_idc > 3")),
429+ }
430+ if out.len() > 64 {
431+ return Err(Error::corrupt("more than 64 ref list modifications"));
432+ }
433+ }
434+ }
435+
436+ fn parse_pred_weight_table(
437+ r: &mut BitReader<'_>,
438+ sps: &Sps,
439+ slice_type: SliceType,
440+ l0_count: u32,
441+ l1_count: u32,
442+ ) -> Result<PredWeightTable> {
443+ let mut t = PredWeightTable {
444+ luma_log2_weight_denom: r.read_ue()?,
445+ ..Default::default()
446+ };
447+ if t.luma_log2_weight_denom > 7 {
448+ return Err(Error::corrupt("luma_log2_weight_denom > 7"));
449+ }
450+ let has_chroma = sps.chroma_format_idc != 0 && !sps.separate_colour_plane;
451+ if has_chroma {
452+ t.chroma_log2_weight_denom = r.read_ue()?;
453+ if t.chroma_log2_weight_denom > 7 {
454+ return Err(Error::corrupt("chroma_log2_weight_denom > 7"));
455+ }
456+ }
457+ let parse_list = |r: &mut BitReader<'_>, count: u32| -> Result<Vec<WeightEntry>> {
458+ let mut list = Vec::with_capacity(count as usize);
459+ for _ in 0..count {
460+ let luma = if r.read_bit()? {
461+ Some((r.read_se()?, r.read_se()?))
462+ } else {
463+ None
464+ };
465+ let chroma = if has_chroma && r.read_bit()? {
466+ Some([(r.read_se()?, r.read_se()?), (r.read_se()?, r.read_se()?)])
467+ } else {
468+ None
469+ };
470+ list.push(WeightEntry { luma, chroma });
471+ }
472+ Ok(list)
473+ };
474+ t.l0 = parse_list(r, l0_count)?;
475+ if slice_type == SliceType::B {
476+ t.l1 = parse_list(r, l1_count)?;
477+ }
478+ Ok(t)
479+ }
480+}
481+
482+#[cfg(test)]
483+mod tests {
484+ use super::*;
485+ use crate::nal::NalHeader;
486+ use crate::pps::Pps;
487+ use crate::sps::Sps;
488+ use ec_core::BitWriter;
489+
490+ fn qcif_sps() -> Sps {
491+ let mut w = BitWriter::new();
492+ w.write_bits(66, 8);
493+ w.write_bits(0xC0, 8);
494+ w.write_bits(10, 8);
495+ w.write_ue(0);
496+ w.write_ue(0); // log2_max_frame_num = 4
497+ w.write_ue(0); // poc type 0, log2 lsb next
498+ w.write_ue(0);
499+ w.write_ue(1);
500+ w.write_bit(false);
501+ w.write_ue(10);
502+ w.write_ue(8);
503+ w.write_bit(true);
504+ w.write_bit(true);
505+ w.write_bit(false);
506+ w.write_bit(false);
507+ w.write_bit(true);
508+ w.align_to_byte();
509+ Sps::parse(w.as_bytes()).unwrap()
510+ }
511+
512+ fn simple_pps() -> Pps {
513+ let mut w = BitWriter::new();
514+ w.write_ue(0);
515+ w.write_ue(0);
516+ w.write_bit(false);
517+ w.write_bit(false);
518+ w.write_ue(0);
519+ w.write_ue(0);
520+ w.write_ue(0);
521+ w.write_bit(false);
522+ w.write_bits(0, 2);
523+ w.write_se(0);
524+ w.write_se(0);
525+ w.write_se(0);
526+ w.write_bit(false); // no deblocking control in header
527+ w.write_bit(false);
528+ w.write_bit(false);
529+ w.write_bit(true);
530+ w.align_to_byte();
531+ Pps::parse(w.as_bytes(), |_| None).unwrap()
532+ }
533+
534+ #[test]
535+ fn idr_i_slice_header() {
536+ let sps = qcif_sps();
537+ let pps = simple_pps();
538+ let mut w = BitWriter::new();
539+ w.write_ue(0); // first_mb_in_slice
540+ w.write_ue(7); // slice_type: I, all slices
541+ w.write_ue(0); // pps id
542+ w.write_bits(0, 4); // frame_num
543+ w.write_ue(3); // idr_pic_id
544+ w.write_bits(0, 4); // pic_order_cnt_lsb
545+ w.write_bit(false); // no_output_of_prior_pics (nal_ref_idc != 0)
546+ w.write_bit(false); // long_term_reference
547+ w.write_se(4); // slice_qp_delta -> QP 30
548+ w.write_bit(true); // first slice-data bit, not part of header
549+ w.align_to_byte();
550+ let nal = NalHeader::parse(0x65).unwrap();
551+ let h = SliceHeader::parse(w.as_bytes(), nal, &sps, &pps).unwrap();
552+ assert_eq!(h.slice_type, SliceType::I);
553+ assert!(h.all_slices_same_type);
554+ assert_eq!(h.idr_pic_id, Some(3));
555+ assert_eq!(h.slice_qp, 30);
556+ assert_eq!(h.deblock.disable_idc, 0);
557+ // Header ends right before the trailing data bit we appended.
558+ assert_eq!(h.header_bits, w.bit_len() - 8 + 7); // wrote 1 bit + 7 pad
559+ }
560+
561+ #[test]
562+ fn p_slice_fields_parse() {
563+ let sps = qcif_sps();
564+ let pps = simple_pps();
565+ let mut w = BitWriter::new();
566+ w.write_ue(2); // first_mb_in_slice
567+ w.write_ue(0); // slice_type: P
568+ w.write_ue(0); // pps id
569+ w.write_bits(1, 4); // frame_num
570+ w.write_bits(2, 4); // pic_order_cnt_lsb
571+ w.write_bit(true); // num_ref_idx_active_override
572+ w.write_ue(1); // l0 active = 2
573+ w.write_bit(true); // ref_pic_list_modification_flag_l0
574+ w.write_ue(0); // idc 0: short term subtract
575+ w.write_ue(4); // abs_diff_pic_num_minus1
576+ w.write_ue(3); // idc 3: end
577+ w.write_bit(false); // adaptive_ref_pic_marking (nal_ref_idc != 0)
578+ w.write_se(-2); // slice_qp_delta -> 24
579+ w.write_bit(true);
580+ w.align_to_byte();
581+ let nal = NalHeader::parse(0x41).unwrap(); // non-IDR slice, ref
582+ let h = SliceHeader::parse(w.as_bytes(), nal, &sps, &pps).unwrap();
583+ assert_eq!(h.slice_type, SliceType::P);
584+ assert_eq!(h.first_mb_in_slice, 2);
585+ assert_eq!(h.num_ref_idx_l0_active, 2);
586+ assert_eq!(
587+ h.ref_pic_list_mod_l0,
588+ vec![RefPicListMod::ShortTerm {
589+ abs_diff_pic_num_minus1: 4,
590+ add: false
591+ }]
592+ );
593+ assert_eq!(h.slice_qp, 24);
594+ assert!(h.dec_ref_pic_marking.is_some());
595+ }
596+
597+ #[test]
598+ fn truncated_header_is_need_more() {
599+ let sps = qcif_sps();
600+ let pps = simple_pps();
601+ let nal = NalHeader::parse(0x65).unwrap();
602+ assert!(
603+ SliceHeader::parse(&[0x88], nal, &sps, &pps)
604+ .unwrap_err()
605+ .is_need_more()
606+ );
607+ }
608+}
crates/ec-h264-syntax/src/sps.rsadded+648 -0
@@ -0,0 +1,648 @@
1+//! Sequence parameter set (spec 7.3.2.1, 7.4.2.1) incl. VUI (Annex E).
2+
3+use ec_core::BitReader;
4+use ec_core::error::{Error, Result};
5+
6+/// The 4x4 and 8x8 quantisation scaling lists (spec 7.3.2.1.1.1).
7+///
8+/// Stored fully resolved: fall-back rules (flat default / previous list) are
9+/// applied at parse time so a decoder indexes these directly.
10+#[derive(Debug, Clone, PartialEq, Eq)]
11+pub struct ScalingLists {
12+ /// Six 4x4 lists in raster order: Intra Y/Cb/Cr, Inter Y/Cb/Cr.
13+ pub list_4x4: [[u8; 16]; 6],
14+ /// 8x8 lists: Intra Y, Inter Y (plus 4 chroma lists for 4:4:4).
15+ pub list_8x8: [[u8; 64]; 6],
16+}
17+
18+/// Default (flat) scaling: weightScale 16 everywhere = no weighting.
19+pub const FLAT_4X4: [u8; 16] = [16; 16];
20+/// Flat 8x8 list.
21+pub const FLAT_8X8: [u8; 64] = [16; 64];
22+
23+/// Default Intra 4x4 scaling list (spec Table 7-3), in zig-zag scan order.
24+pub const DEFAULT_4X4_INTRA: [u8; 16] = [
25+ 6, 13, 13, 20, 20, 20, 28, 28, 28, 28, 32, 32, 32, 37, 37, 42,
26+];
27+/// Default Inter 4x4 scaling list (spec Table 7-3), in zig-zag scan order.
28+pub const DEFAULT_4X4_INTER: [u8; 16] = [
29+ 10, 14, 14, 20, 20, 20, 24, 24, 24, 24, 27, 27, 27, 30, 30, 34,
30+];
31+/// Default Intra 8x8 scaling list (spec Table 7-4), in zig-zag scan order.
32+pub const DEFAULT_8X8_INTRA: [u8; 64] = [
33+ 6, 10, 10, 13, 11, 13, 16, 16, 16, 16, 18, 18, 18, 18, 18, 23, 23, 23, 23, 23, 23, 25, 25, 25,
34+ 25, 25, 25, 25, 27, 27, 27, 27, 27, 27, 27, 27, 29, 29, 29, 29, 29, 29, 29, 31, 31, 31, 31, 31,
35+ 31, 33, 33, 33, 33, 33, 36, 36, 36, 36, 38, 38, 38, 40, 40, 42,
36+];
37+/// Default Inter 8x8 scaling list (spec Table 7-4), in zig-zag scan order.
38+pub const DEFAULT_8X8_INTER: [u8; 64] = [
39+ 9, 13, 13, 15, 13, 15, 17, 17, 17, 17, 19, 19, 19, 19, 19, 21, 21, 21, 21, 21, 21, 22, 22, 22,
40+ 22, 22, 22, 22, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 27, 27, 27, 27, 27,
41+ 27, 28, 28, 28, 28, 28, 30, 30, 30, 30, 32, 32, 32, 33, 33, 35,
42+];
43+
44+/// Place a zig-zag-scan-order list into raster order.
45+fn scan_to_raster<const N: usize>(scan_order: &[u8; N], scan: &[u8; N]) -> [u8; N] {
46+ let mut out = [0u8; N];
47+ for (j, &v) in scan_order.iter().enumerate() {
48+ out[scan[j] as usize] = v;
49+ }
50+ out
51+}
52+
53+impl Default for ScalingLists {
54+ /// Flat lists — the state when no scaling matrix is signalled.
55+ fn default() -> ScalingLists {
56+ ScalingLists {
57+ list_4x4: [FLAT_4X4; 6],
58+ list_8x8: [FLAT_8X8; 6],
59+ }
60+ }
61+}
62+
63+/// Zig-zag scan for 4x4 blocks (spec Table 8-13, frame scan), used to place
64+/// scaling-list entries and residual levels into raster order.
65+pub const ZIGZAG_4X4: [u8; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
66+
67+/// Zig-zag (frame) scan for 8x8 blocks (spec Table 8-14).
68+pub const ZIGZAG_8X8: [u8; 64] = [
69+ 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20,
70+ 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59,
71+ 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
72+];
73+
74+/// Parse one `scaling_list` (spec 7.3.2.1.1.1) of `N` entries into raster
75+/// order. Returns `None` when `use_default_scaling_matrix_flag` fired.
76+fn parse_scaling_list<const N: usize>(
77+ r: &mut BitReader<'_>,
78+ scan: &[u8; N],
79+) -> Result<Option<[u8; N]>> {
80+ let mut list = [0u8; N];
81+ let mut last_scale = 8i32;
82+ let mut next_scale = 8i32;
83+ for j in 0..N {
84+ if next_scale != 0 {
85+ let delta = r.read_se()?;
86+ next_scale = (last_scale + delta + 256) % 256;
87+ if j == 0 && next_scale == 0 {
88+ return Ok(None); // use_default_scaling_matrix_flag
89+ }
90+ }
91+ let v = if next_scale == 0 {
92+ last_scale
93+ } else {
94+ next_scale
95+ };
96+ list[scan[j] as usize] = v as u8;
97+ last_scale = v;
98+ }
99+ Ok(Some(list))
100+}
101+
102+/// Parse the `seq_scaling_list` / `pic_scaling_list` block shared by SPS and
103+/// PPS (spec 7.3.2.1, fall-back rules of Table 7-2). `count` is 8
104+/// (4:2:0/4:2:2) or 12 (4:4:4). `sps_lists` is `None` in an SPS (fall-back
105+/// rule A: absent list 0/3/6/7 takes the *default* list) and `Some` in a PPS
106+/// whose SPS carried a matrix (rule B: those indices take the SPS list).
107+/// Lists are returned in raster order, fully resolved.
108+pub(crate) fn parse_scaling_matrix(
109+ r: &mut BitReader<'_>,
110+ count: usize,
111+ sps_lists: Option<&ScalingLists>,
112+) -> Result<ScalingLists> {
113+ let mut out = ScalingLists::default();
114+ let d4_intra = scan_to_raster(&DEFAULT_4X4_INTRA, &ZIGZAG_4X4);
115+ let d4_inter = scan_to_raster(&DEFAULT_4X4_INTER, &ZIGZAG_4X4);
116+ let d8_intra = scan_to_raster(&DEFAULT_8X8_INTRA, &ZIGZAG_8X8);
117+ let d8_inter = scan_to_raster(&DEFAULT_8X8_INTER, &ZIGZAG_8X8);
118+ for idx in 0..count {
119+ let present = r.read_bit()?;
120+ if idx < 6 {
121+ let default = if idx < 3 { d4_intra } else { d4_inter };
122+ let fallback = match idx {
123+ 0 | 3 => match sps_lists {
124+ Some(s) => s.list_4x4[idx],
125+ None => default,
126+ },
127+ _ => out.list_4x4[idx - 1],
128+ };
129+ out.list_4x4[idx] = if present {
130+ parse_scaling_list::<16>(r, &ZIGZAG_4X4)?.unwrap_or(default)
131+ } else {
132+ fallback
133+ };
134+ } else {
135+ let i = idx - 6;
136+ let default = if i % 2 == 0 { d8_intra } else { d8_inter };
137+ let fallback = if i < 2 {
138+ match sps_lists {
139+ Some(s) => s.list_8x8[i],
140+ None => default,
141+ }
142+ } else {
143+ out.list_8x8[i - 2]
144+ };
145+ out.list_8x8[i] = if present {
146+ parse_scaling_list::<64>(r, &ZIGZAG_8X8)?.unwrap_or(default)
147+ } else {
148+ fallback
149+ };
150+ }
151+ }
152+ Ok(out)
153+}
154+
155+/// HRD parameters (spec E.1.2), carried for completeness.
156+#[derive(Debug, Clone, PartialEq, Eq, Default)]
157+pub struct Hrd {
158+ /// Per-CPB `(bit_rate_value_minus1, cpb_size_value_minus1, cbr_flag)`.
159+ pub cpb: Vec<(u32, u32, bool)>,
160+ /// `bit_rate_scale`.
161+ pub bit_rate_scale: u8,
162+ /// `cpb_size_scale`.
163+ pub cpb_size_scale: u8,
164+ /// `initial_cpb_removal_delay_length_minus1`.
165+ pub initial_cpb_removal_delay_length_minus1: u8,
166+ /// `cpb_removal_delay_length_minus1`.
167+ pub cpb_removal_delay_length_minus1: u8,
168+ /// `dpb_output_delay_length_minus1`.
169+ pub dpb_output_delay_length_minus1: u8,
170+ /// `time_offset_length`.
171+ pub time_offset_length: u8,
172+}
173+
174+impl Hrd {
175+ fn parse(r: &mut BitReader<'_>) -> Result<Hrd> {
176+ let cpb_cnt_minus1 = r.read_ue()?;
177+ if cpb_cnt_minus1 > 31 {
178+ return Err(Error::corrupt("cpb_cnt_minus1 > 31"));
179+ }
180+ let bit_rate_scale = r.read_bits(4)? as u8;
181+ let cpb_size_scale = r.read_bits(4)? as u8;
182+ let mut cpb = Vec::with_capacity(cpb_cnt_minus1 as usize + 1);
183+ for _ in 0..=cpb_cnt_minus1 {
184+ let bit_rate = r.read_ue()?;
185+ let cpb_size = r.read_ue()?;
186+ let cbr = r.read_bit()?;
187+ cpb.push((bit_rate, cpb_size, cbr));
188+ }
189+ Ok(Hrd {
190+ cpb,
191+ bit_rate_scale,
192+ cpb_size_scale,
193+ initial_cpb_removal_delay_length_minus1: r.read_bits(5)? as u8,
194+ cpb_removal_delay_length_minus1: r.read_bits(5)? as u8,
195+ dpb_output_delay_length_minus1: r.read_bits(5)? as u8,
196+ time_offset_length: r.read_bits(5)? as u8,
197+ })
198+ }
199+}
200+
201+/// VUI parameters (spec E.1.1).
202+#[derive(Debug, Clone, PartialEq, Eq, Default)]
203+pub struct Vui {
204+ /// Sample aspect ratio `(width, height)` when signalled; `aspect_ratio_idc`
205+ /// table values are resolved here, Extended_SAR reads the pair verbatim.
206+ pub sample_aspect_ratio: Option<(u16, u16)>,
207+ /// `overscan_appropriate_flag` when `overscan_info_present_flag`.
208+ pub overscan_appropriate: Option<bool>,
209+ /// `video_format` (E-2) when signalled.
210+ pub video_format: Option<u8>,
211+ /// `video_full_range_flag`.
212+ pub video_full_range: bool,
213+ /// H.273 `(colour_primaries, transfer_characteristics, matrix_coefficients)`.
214+ pub colour_description: Option<(u8, u8, u8)>,
215+ /// `(chroma_sample_loc_type_top_field, chroma_sample_loc_type_bottom_field)`.
216+ pub chroma_sample_loc: Option<(u32, u32)>,
217+ /// `(num_units_in_tick, time_scale, fixed_frame_rate_flag)`.
218+ pub timing_info: Option<(u32, u32, bool)>,
219+ /// NAL HRD parameters.
220+ pub nal_hrd: Option<Hrd>,
221+ /// VCL HRD parameters.
222+ pub vcl_hrd: Option<Hrd>,
223+ /// `low_delay_hrd_flag` (present when either HRD is).
224+ pub low_delay_hrd: bool,
225+ /// `pic_struct_present_flag`.
226+ pub pic_struct_present: bool,
227+ /// Bitstream restriction fields, in spec order.
228+ pub bitstream_restriction: Option<BitstreamRestriction>,
229+}
230+
231+/// `bitstream_restriction` fields (spec E.1.1).
232+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
233+pub struct BitstreamRestriction {
234+ /// `motion_vectors_over_pic_boundaries_flag`.
235+ pub motion_vectors_over_pic_boundaries: bool,
236+ /// `max_bytes_per_pic_denom`.
237+ pub max_bytes_per_pic_denom: u32,
238+ /// `max_bits_per_mb_denom`.
239+ pub max_bits_per_mb_denom: u32,
240+ /// `log2_max_mv_length_horizontal`.
241+ pub log2_max_mv_length_horizontal: u32,
242+ /// `log2_max_mv_length_vertical`.
243+ pub log2_max_mv_length_vertical: u32,
244+ /// `max_num_reorder_frames`.
245+ pub max_num_reorder_frames: u32,
246+ /// `max_dec_frame_buffering`.
247+ pub max_dec_frame_buffering: u32,
248+}
249+
250+/// Table E-1 aspect ratios for `aspect_ratio_idc` 1..=16.
251+const SAR_TABLE: [(u16, u16); 17] = [
252+ (0, 0), // 0 = unspecified
253+ (1, 1),
254+ (12, 11),
255+ (10, 11),
256+ (16, 11),
257+ (40, 33),
258+ (24, 11),
259+ (20, 11),
260+ (32, 11),
261+ (80, 33),
262+ (18, 11),
263+ (15, 11),
264+ (64, 33),
265+ (160, 99),
266+ (4, 3),
267+ (3, 2),
268+ (2, 1),
269+];
270+
271+impl Vui {
272+ fn parse(r: &mut BitReader<'_>) -> Result<Vui> {
273+ let mut vui = Vui::default();
274+ if r.read_bit()? {
275+ // aspect_ratio_info_present_flag
276+ let idc = r.read_bits(8)? as u8;
277+ vui.sample_aspect_ratio = match idc {
278+ 0 => None,
279+ 255 => Some((r.read_bits(16)? as u16, r.read_bits(16)? as u16)),
280+ 1..=16 => Some(SAR_TABLE[idc as usize]),
281+ _ => None, // reserved: ignore per spec
282+ };
283+ }
284+ if r.read_bit()? {
285+ vui.overscan_appropriate = Some(r.read_bit()?);
286+ }
287+ if r.read_bit()? {
288+ // video_signal_type_present_flag
289+ vui.video_format = Some(r.read_bits(3)? as u8);
290+ vui.video_full_range = r.read_bit()?;
291+ if r.read_bit()? {
292+ vui.colour_description = Some((
293+ r.read_bits(8)? as u8,
294+ r.read_bits(8)? as u8,
295+ r.read_bits(8)? as u8,
296+ ));
297+ }
298+ }
299+ if r.read_bit()? {
300+ vui.chroma_sample_loc = Some((r.read_ue()?, r.read_ue()?));
301+ }
302+ if r.read_bit()? {
303+ vui.timing_info = Some((r.read_bits(32)?, r.read_bits(32)?, r.read_bit()?));
304+ }
305+ let nal_hrd_present = r.read_bit()?;
306+ if nal_hrd_present {
307+ vui.nal_hrd = Some(Hrd::parse(r)?);
308+ }
309+ let vcl_hrd_present = r.read_bit()?;
310+ if vcl_hrd_present {
311+ vui.vcl_hrd = Some(Hrd::parse(r)?);
312+ }
313+ if nal_hrd_present || vcl_hrd_present {
314+ vui.low_delay_hrd = r.read_bit()?;
315+ }
316+ vui.pic_struct_present = r.read_bit()?;
317+ if r.read_bit()? {
318+ vui.bitstream_restriction = Some(BitstreamRestriction {
319+ motion_vectors_over_pic_boundaries: r.read_bit()?,
320+ max_bytes_per_pic_denom: r.read_ue()?,
321+ max_bits_per_mb_denom: r.read_ue()?,
322+ log2_max_mv_length_horizontal: r.read_ue()?,
323+ log2_max_mv_length_vertical: r.read_ue()?,
324+ max_num_reorder_frames: r.read_ue()?,
325+ max_dec_frame_buffering: r.read_ue()?,
326+ });
327+ }
328+ Ok(vui)
329+ }
330+}
331+
332+/// Sequence parameter set (spec 7.4.2.1) with decode-ready derived geometry.
333+#[derive(Debug, Clone, PartialEq, Eq)]
334+pub struct Sps {
335+ /// `profile_idc`.
336+ pub profile_idc: u8,
337+ /// `constraint_setX_flag` bits (bit 7 = set0) + reserved bits, verbatim.
338+ pub constraint_flags: u8,
339+ /// `level_idc`.
340+ pub level_idc: u8,
341+ /// `seq_parameter_set_id` (0..=31).
342+ pub id: u8,
343+ /// `chroma_format_idc`: 0 mono, 1 = 4:2:0, 2 = 4:2:2, 3 = 4:4:4.
344+ pub chroma_format_idc: u8,
345+ /// `separate_colour_plane_flag` (4:4:4 only).
346+ pub separate_colour_plane: bool,
347+ /// Luma bit depth (8..=14).
348+ pub bit_depth_luma: u8,
349+ /// Chroma bit depth (8..=14).
350+ pub bit_depth_chroma: u8,
351+ /// `qpprime_y_zero_transform_bypass_flag`.
352+ pub transform_bypass: bool,
353+ /// Scaling lists when `seq_scaling_matrix_present_flag`, resolved.
354+ pub scaling_lists: Option<ScalingLists>,
355+ /// `log2_max_frame_num` (4..=16, offset applied).
356+ pub log2_max_frame_num: u8,
357+ /// `pic_order_cnt_type` (0..=2).
358+ pub pic_order_cnt_type: u8,
359+ /// `log2_max_pic_order_cnt_lsb` (POC type 0, offset applied).
360+ pub log2_max_pic_order_cnt_lsb: u8,
361+ /// `delta_pic_order_always_zero_flag` (POC type 1).
362+ pub delta_pic_order_always_zero: bool,
363+ /// `offset_for_non_ref_pic` (POC type 1).
364+ pub offset_for_non_ref_pic: i32,
365+ /// `offset_for_top_to_bottom_field` (POC type 1).
366+ pub offset_for_top_to_bottom_field: i32,
367+ /// `offset_for_ref_frame` list (POC type 1).
368+ pub offsets_for_ref_frame: Vec<i32>,
369+ /// `max_num_ref_frames`.
370+ pub max_num_ref_frames: u32,
371+ /// `gaps_in_frame_num_value_allowed_flag`.
372+ pub gaps_in_frame_num_allowed: bool,
373+ /// `frame_mbs_only_flag`.
374+ pub frame_mbs_only: bool,
375+ /// `mb_adaptive_frame_field_flag` (when `!frame_mbs_only`).
376+ pub mb_adaptive_frame_field: bool,
377+ /// `direct_8x8_inference_flag`.
378+ pub direct_8x8_inference: bool,
379+ /// Crop offsets in luma samples `(left, right, top, bottom)`, already
380+ /// scaled by the chroma-format crop units (spec 7.4.2.1.1).
381+ pub crop: (u32, u32, u32, u32),
382+ /// VUI parameters when present.
383+ pub vui: Option<Vui>,
384+
385+ // ---- derived, computed once at parse time ----
386+ /// `PicWidthInMbs`.
387+ pub mb_width: u32,
388+ /// `FrameHeightInMbs` (frame coding).
389+ pub mb_height: u32,
390+ /// Coded luma width in samples (mb_width * 16).
391+ pub coded_width: u32,
392+ /// Coded luma height in samples.
393+ pub coded_height: u32,
394+ /// Visible width after cropping.
395+ pub width: u32,
396+ /// Visible height after cropping.
397+ pub height: u32,
398+}
399+
400+impl Sps {
401+ /// Parse an SPS RBSP (header byte already consumed, emulation stripped).
402+ pub fn parse(rbsp: &[u8]) -> Result<Sps> {
403+ let mut r = BitReader::new(rbsp);
404+ let r = &mut r;
405+ let profile_idc = r.read_bits(8)? as u8;
406+ let constraint_flags = r.read_bits(8)? as u8;
407+ let level_idc = r.read_bits(8)? as u8;
408+ let id = r.read_ue()?;
409+ if id > 31 {
410+ return Err(Error::corrupt("seq_parameter_set_id > 31"));
411+ }
412+
413+ let mut chroma_format_idc = 1u8;
414+ let mut separate_colour_plane = false;
415+ let mut bit_depth_luma = 8u8;
416+ let mut bit_depth_chroma = 8u8;
417+ let mut transform_bypass = false;
418+ let mut scaling_lists = None;
419+ if matches!(
420+ profile_idc,
421+ 100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135
422+ ) {
423+ let cf = r.read_ue()?;
424+ if cf > 3 {
425+ return Err(Error::corrupt("chroma_format_idc > 3"));
426+ }
427+ chroma_format_idc = cf as u8;
428+ if chroma_format_idc == 3 {
429+ separate_colour_plane = r.read_bit()?;
430+ }
431+ let bdl = r.read_ue()?;
432+ let bdc = r.read_ue()?;
433+ if bdl > 6 || bdc > 6 {
434+ return Err(Error::corrupt("bit_depth_minus8 > 6"));
435+ }
436+ bit_depth_luma = 8 + bdl as u8;
437+ bit_depth_chroma = 8 + bdc as u8;
438+ transform_bypass = r.read_bit()?;
439+ if r.read_bit()? {
440+ let count = if chroma_format_idc == 3 { 12 } else { 8 };
441+ scaling_lists = Some(parse_scaling_matrix(r, count, None)?);
442+ }
443+ }
444+
445+ let log2_mfn = r.read_ue()?;
446+ if log2_mfn > 12 {
447+ return Err(Error::corrupt("log2_max_frame_num_minus4 > 12"));
448+ }
449+ let log2_max_frame_num = 4 + log2_mfn as u8;
450+ let pic_order_cnt_type = r.read_ue()?;
451+ if pic_order_cnt_type > 2 {
452+ return Err(Error::corrupt("pic_order_cnt_type > 2"));
453+ }
454+ let pic_order_cnt_type = pic_order_cnt_type as u8;
455+ let mut log2_max_pic_order_cnt_lsb = 0u8;
456+ let mut delta_pic_order_always_zero = false;
457+ let mut offset_for_non_ref_pic = 0i32;
458+ let mut offset_for_top_to_bottom_field = 0i32;
459+ let mut offsets_for_ref_frame = Vec::new();
460+ match pic_order_cnt_type {
461+ 0 => {
462+ let v = r.read_ue()?;
463+ if v > 12 {
464+ return Err(Error::corrupt("log2_max_pic_order_cnt_lsb_minus4 > 12"));
465+ }
466+ log2_max_pic_order_cnt_lsb = 4 + v as u8;
467+ }
468+ 1 => {
469+ delta_pic_order_always_zero = r.read_bit()?;
470+ offset_for_non_ref_pic = r.read_se()?;
471+ offset_for_top_to_bottom_field = r.read_se()?;
472+ let n = r.read_ue()?;
473+ if n > 255 {
474+ return Err(Error::corrupt(
475+ "num_ref_frames_in_pic_order_cnt_cycle > 255",
476+ ));
477+ }
478+ offsets_for_ref_frame.reserve(n as usize);
479+ for _ in 0..n {
480+ offsets_for_ref_frame.push(r.read_se()?);
481+ }
482+ }
483+ _ => {}
484+ }
485+ let max_num_ref_frames = r.read_ue()?;
486+ let gaps_in_frame_num_allowed = r.read_bit()?;
487+ let pic_width_in_mbs_minus1 = r.read_ue()?;
488+ let pic_height_in_map_units_minus1 = r.read_ue()?;
489+ let frame_mbs_only = r.read_bit()?;
490+ let mb_adaptive_frame_field = if !frame_mbs_only {
491+ r.read_bit()?
492+ } else {
493+ false
494+ };
495+ let direct_8x8_inference = r.read_bit()?;
496+
497+ let mb_width = pic_width_in_mbs_minus1 + 1;
498+ let map_height = pic_height_in_map_units_minus1 + 1;
499+ let mb_height = map_height * if frame_mbs_only { 1 } else { 2 };
500+ if mb_width > 1024 || mb_height > 1024 {
501+ return Err(Error::corrupt("picture larger than 16384x16384"));
502+ }
503+ let coded_width = mb_width * 16;
504+ let coded_height = mb_height * 16;
505+
506+ // Crop units (spec 7.4.2.1.1): chroma-format dependent.
507+ let (crop_x, crop_y_frame) = match chroma_format_idc {
508+ 0 => (1, 1),
509+ 1 => (2, 2),
510+ 2 => (2, 1),
511+ _ => (1, 1),
512+ };
513+ let crop_y = crop_y_frame * if frame_mbs_only { 1 } else { 2 };
514+ let crop = if r.read_bit()? {
515+ let l = r.read_ue()?;
516+ let rr = r.read_ue()?;
517+ let t = r.read_ue()?;
518+ let b = r.read_ue()?;
519+ (crop_x * l, crop_x * rr, crop_y * t, crop_y * b)
520+ } else {
521+ (0, 0, 0, 0)
522+ };
523+ let width = coded_width
524+ .checked_sub(crop.0 + crop.1)
525+ .filter(|&w| w > 0)
526+ .ok_or_else(|| Error::corrupt("frame cropping wider than the picture"))?;
527+ let height = coded_height
528+ .checked_sub(crop.2 + crop.3)
529+ .filter(|&h| h > 0)
530+ .ok_or_else(|| Error::corrupt("frame cropping taller than the picture"))?;
531+
532+ let vui = if r.read_bit()? {
533+ Some(Vui::parse(r)?)
534+ } else {
535+ None
536+ };
537+
538+ Ok(Sps {
539+ profile_idc,
540+ constraint_flags,
541+ level_idc,
542+ id: id as u8,
543+ chroma_format_idc,
544+ separate_colour_plane,
545+ bit_depth_luma,
546+ bit_depth_chroma,
547+ transform_bypass,
548+ scaling_lists,
549+ log2_max_frame_num,
550+ pic_order_cnt_type,
551+ log2_max_pic_order_cnt_lsb,
552+ delta_pic_order_always_zero,
553+ offset_for_non_ref_pic,
554+ offset_for_top_to_bottom_field,
555+ offsets_for_ref_frame,
556+ max_num_ref_frames,
557+ gaps_in_frame_num_allowed,
558+ frame_mbs_only,
559+ mb_adaptive_frame_field,
560+ direct_8x8_inference,
561+ crop,
562+ vui,
563+ mb_width,
564+ mb_height,
565+ coded_width,
566+ coded_height,
567+ width,
568+ height,
569+ })
570+ }
571+
572+ /// Total macroblocks per picture.
573+ pub fn mbs_per_picture(&self) -> u32 {
574+ self.mb_width * self.mb_height
575+ }
576+}
577+
578+#[cfg(test)]
579+mod tests {
580+ use super::*;
581+ use ec_core::BitWriter;
582+
583+ /// Build a minimal Baseline QCIF SPS and check the derived geometry.
584+ #[test]
585+ fn baseline_qcif_geometry() {
586+ let mut w = BitWriter::new();
587+ w.write_bits(66, 8); // profile_idc Baseline
588+ w.write_bits(0xC0, 8); // constraint flags
589+ w.write_bits(10, 8); // level_idc
590+ w.write_ue(0); // sps id
591+ w.write_ue(0); // log2_max_frame_num_minus4
592+ w.write_ue(0); // pic_order_cnt_type
593+ w.write_ue(0); // log2_max_pic_order_cnt_lsb_minus4
594+ w.write_ue(1); // max_num_ref_frames
595+ w.write_bit(false); // gaps allowed
596+ w.write_ue(10); // width 11 MBs = 176
597+ w.write_ue(8); // height 9 MBs = 144
598+ w.write_bit(true); // frame_mbs_only
599+ w.write_bit(true); // direct_8x8_inference
600+ w.write_bit(false); // no cropping
601+ w.write_bit(false); // no VUI
602+ w.write_bit(true); // rbsp_stop_one_bit
603+ w.align_to_byte();
604+ let sps = Sps::parse(w.as_bytes()).unwrap();
605+ assert_eq!(sps.profile_idc, 66);
606+ assert_eq!((sps.mb_width, sps.mb_height), (11, 9));
607+ assert_eq!((sps.width, sps.height), (176, 144));
608+ assert_eq!(sps.chroma_format_idc, 1);
609+ assert_eq!(sps.bit_depth_luma, 8);
610+ assert!(sps.frame_mbs_only);
611+ }
612+
613+ /// Cropping in 4:2:0 is in 2-sample units both directions.
614+ #[test]
615+ fn crop_units_420() {
616+ let mut w = BitWriter::new();
617+ w.write_bits(66, 8);
618+ w.write_bits(0, 8);
619+ w.write_bits(40, 8);
620+ w.write_ue(0);
621+ w.write_ue(0);
622+ w.write_ue(2); // poc type 2
623+ w.write_ue(1);
624+ w.write_bit(false);
625+ w.write_ue(119); // 1920
626+ w.write_ue(67); // 68 MBs = 1088
627+ w.write_bit(true);
628+ w.write_bit(true);
629+ w.write_bit(true); // cropping
630+ w.write_ue(0);
631+ w.write_ue(0);
632+ w.write_ue(0);
633+ w.write_ue(4); // bottom crop 4 units = 8 luma rows
634+ w.write_bit(false); // no VUI
635+ w.write_bit(true);
636+ w.align_to_byte();
637+ let sps = Sps::parse(w.as_bytes()).unwrap();
638+ assert_eq!((sps.width, sps.height), (1920, 1080));
639+ assert_eq!(sps.crop, (0, 0, 0, 8));
640+ }
641+
642+ /// Truncated SPS is NeedMore, never a panic.
643+ #[test]
644+ fn truncated_is_need_more() {
645+ assert!(Sps::parse(&[0x42]).unwrap_err().is_need_more());
646+ assert!(Sps::parse(&[]).unwrap_err().is_need_more());
647+ }
648+}