From f07dac79e9d2db2d0b11399236155920c154526c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Fri, 14 Aug 2026 09:07:55 +0300 Subject: [PATCH] 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.toml | 10 + crates/ec-h264-syntax/src/lib.rs | 41 ++ crates/ec-h264-syntax/src/nal.rs | 257 ++++++++++++ crates/ec-h264-syntax/src/pps.rs | 266 ++++++++++++ crates/ec-h264-syntax/src/slice.rs | 608 +++++++++++++++++++++++++++ crates/ec-h264-syntax/src/sps.rs | 648 +++++++++++++++++++++++++++++ 6 files changed, 1830 insertions(+) create mode 100644 crates/ec-h264-syntax/Cargo.toml create mode 100644 crates/ec-h264-syntax/src/lib.rs create mode 100644 crates/ec-h264-syntax/src/nal.rs create mode 100644 crates/ec-h264-syntax/src/pps.rs create mode 100644 crates/ec-h264-syntax/src/slice.rs create mode 100644 crates/ec-h264-syntax/src/sps.rs diff --git a/crates/ec-h264-syntax/Cargo.toml b/crates/ec-h264-syntax/Cargo.toml new file mode 100644 index 00000000..ec5e1886 --- /dev/null +++ b/crates/ec-h264-syntax/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "ec-h264-syntax" +description = "H.264 (ITU-T Rec. H.264) bitstream syntax: NAL, SPS/PPS, slice headers" +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core = { workspace = true } diff --git a/crates/ec-h264-syntax/src/lib.rs b/crates/ec-h264-syntax/src/lib.rs new file mode 100644 index 00000000..a645369c --- /dev/null +++ b/crates/ec-h264-syntax/src/lib.rs @@ -0,0 +1,41 @@ +//! H.264 (ITU-T Rec. H.264 / ISO 14496-10) bitstream syntax. +//! +//! Parsing only — no reconstruction. Shared by the software decoder +//! (`ec-h264`) and the stateless hardware path, so every struct is a plain +//! value type whose derived geometry (macroblock counts, crop rectangle, +//! bit depths) is computed once at parse time; a decoder feeds these fields +//! straight into flat per-picture arrays without re-deriving anything per +//! macroblock. +//! +//! Layout of the crate follows the spec's own structure: +//! - [`nal`]: Annex B framing + emulation-prevention removal (7.3.1, 7.4.1) +//! - [`sps`]: sequence parameter set incl. VUI and HRD (7.3.2.1, E.1) +//! - [`pps`]: picture parameter set incl. the High-profile tail (7.3.2.2) +//! - [`slice`]: slice header for I/SI/P/SP/B (7.3.3) + +#![forbid(unsafe_code)] + +pub mod nal; +pub mod pps; +pub mod slice; +pub mod sps; + +pub use nal::{AnnexBIter, NalHeader, NalUnitType, unescape_rbsp}; +pub use pps::Pps; +pub use slice::{DeblockControl, SliceHeader, SliceType}; +pub use sps::{Hrd, ScalingLists, Sps, Vui}; + +/// True when there is at least one more RBSP syntax element before the +/// `rbsp_stop_one_bit` (spec 7.2 `more_rbsp_data()`). +/// +/// `data` is the full unescaped RBSP the reader walks; the stop bit is the +/// last set bit of the last non-zero byte. +pub fn more_rbsp_data(reader: &ec_core::BitReader<'_>, data: &[u8]) -> bool { + // Find the rbsp_stop_one_bit from the tail. + let Some(last_nonzero) = data.iter().rposition(|&b| b != 0) else { + return false; // all zero: corrupt, but by definition nothing left + }; + let byte = data[last_nonzero]; + let stop_bit_index = last_nonzero as u64 * 8 + (7 - byte.trailing_zeros() as u64); + reader.bit_position() < stop_bit_index +} diff --git a/crates/ec-h264-syntax/src/nal.rs b/crates/ec-h264-syntax/src/nal.rs new file mode 100644 index 00000000..7ff5d126 --- /dev/null +++ b/crates/ec-h264-syntax/src/nal.rs @@ -0,0 +1,257 @@ +//! NAL unit framing: Annex B start-code scan and emulation-prevention +//! removal (spec 7.3.1, 7.4.1, B.1). + +use ec_core::error::{Error, Result}; + +/// `nal_unit_type` code points (spec Table 7-1). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum NalUnitType { + /// 1 — coded slice of a non-IDR picture. + Slice, + /// 2 — coded slice data partition A. + SliceDataA, + /// 3 — coded slice data partition B. + SliceDataB, + /// 4 — coded slice data partition C. + SliceDataC, + /// 5 — coded slice of an IDR picture. + SliceIdr, + /// 6 — supplemental enhancement information. + Sei, + /// 7 — sequence parameter set. + Sps, + /// 8 — picture parameter set. + Pps, + /// 9 — access unit delimiter. + AccessUnitDelimiter, + /// 10 — end of sequence. + EndOfSequence, + /// 11 — end of stream. + EndOfStream, + /// 12 — filler data. + Filler, + /// 13 — SPS extension. + SpsExtension, + /// 14 — prefix NAL unit (SVC/MVC). + Prefix, + /// 15 — subset SPS (SVC/MVC). + SubsetSps, + /// 19 — auxiliary coded picture slice. + SliceAux, + /// 20 — slice extension (SVC/MVC). + SliceExtension, + /// 21 — slice extension for depth/3D. + SliceDepth, + /// Any reserved or unspecified code point, carried verbatim. + Other(u8), +} + +impl NalUnitType { + /// Map the 5-bit code point. + pub fn from_code(code: u8) -> NalUnitType { + use NalUnitType::*; + match code { + 1 => Slice, + 2 => SliceDataA, + 3 => SliceDataB, + 4 => SliceDataC, + 5 => SliceIdr, + 6 => Sei, + 7 => Sps, + 8 => Pps, + 9 => AccessUnitDelimiter, + 10 => EndOfSequence, + 11 => EndOfStream, + 12 => Filler, + 13 => SpsExtension, + 14 => Prefix, + 15 => SubsetSps, + 19 => SliceAux, + 20 => SliceExtension, + 21 => SliceDepth, + n => Other(n), + } + } + + /// True for the VCL slice types the decoder reconstructs pictures from. + pub fn is_slice(&self) -> bool { + matches!(self, NalUnitType::Slice | NalUnitType::SliceIdr) + } +} + +/// First byte of a NAL unit (spec 7.3.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct NalHeader { + /// `nal_ref_idc`: 0 = disposable, >0 = used for reference. + pub ref_idc: u8, + /// `nal_unit_type`. + pub unit_type: NalUnitType, +} + +impl NalHeader { + /// Parse the header byte; `forbidden_zero_bit` set is a corrupt stream. + pub fn parse(byte: u8) -> Result { + if byte & 0x80 != 0 { + return Err(Error::corrupt("NAL forbidden_zero_bit set")); + } + Ok(NalHeader { + ref_idc: (byte >> 5) & 0x3, + unit_type: NalUnitType::from_code(byte & 0x1F), + }) + } + + /// True for an IDR slice. + pub fn is_idr(&self) -> bool { + self.unit_type == NalUnitType::SliceIdr + } +} + +/// Iterator over NAL unit payloads in an Annex B byte stream (spec B.1). +/// +/// Yields each NAL unit as a sub-slice of the input **including** its header +/// byte, with start codes (`00 00 01` / `00 00 00 01`) stripped and trailing +/// zero padding removed. Borrowing, zero-copy: emulation prevention is left +/// in place for [`unescape_rbsp`] to strip into a reusable buffer. +#[derive(Debug, Clone)] +pub struct AnnexBIter<'a> { + data: &'a [u8], + pos: usize, +} + +impl<'a> AnnexBIter<'a> { + /// Iterate over `data`, skipping anything before the first start code. + pub fn new(data: &'a [u8]) -> AnnexBIter<'a> { + AnnexBIter { data, pos: 0 } + } + + /// Position of the next `00 00 01` at or after `from`, or `len`. + fn next_start_code(&self, from: usize) -> Option { + let d = self.data; + let mut i = from; + // memchr-style scan on the middle zero of `00 00 01`. + while i + 2 < d.len() { + if d[i + 1] != 0 { + i += 2; + } else if d[i] != 0 { + i += 1; + } else if d[i + 2] == 1 { + return Some(i); + } else { + i += 1; + } + } + None + } +} + +impl<'a> Iterator for AnnexBIter<'a> { + type Item = &'a [u8]; + + fn next(&mut self) -> Option<&'a [u8]> { + let start = self.next_start_code(self.pos)? + 3; + if start >= self.data.len() { + self.pos = self.data.len(); + return None; + } + let (end, next_pos) = match self.next_start_code(start) { + Some(sc) => (sc, sc), + None => (self.data.len(), self.data.len()), + }; + self.pos = next_pos; + // Trailing zero bytes before the next start code belong to the start + // code prefix / trailing_zero_8bits, not to this NAL unit. + let mut end = end; + while end > start && self.data[end - 1] == 0 { + end -= 1; + } + if end == start { + // Empty NAL unit (all-zero span): skip to the next one. + return self.next(); + } + Some(&self.data[start..end]) + } +} + +/// Strip emulation-prevention bytes (spec 7.4.1.1): every `00 00 03` becomes +/// `00 00`. `nal` is the NAL payload **after** the header byte; the result is +/// appended into `out`, which is cleared first and whose capacity is reused +/// across calls — the steady-state decode loop performs no allocation once +/// `out` has grown to the largest NAL size. +pub fn unescape_rbsp(nal: &[u8], out: &mut Vec) { + out.clear(); + out.reserve(nal.len()); + let mut zeros = 0u32; + let mut i = 0; + while i < nal.len() { + let b = nal[i]; + if zeros >= 2 && b == 3 { + // Emulation prevention byte: drop it, next byte restarts the count. + zeros = 0; + i += 1; + continue; + } + zeros = if b == 0 { zeros + 1 } else { 0 }; + out.push(b); + i += 1; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn annexb_split_three_and_four_byte_codes() { + let data = [ + 0x00, 0x00, 0x00, 0x01, 0x67, 0xAA, // SPS + 0x00, 0x00, 0x01, 0x68, 0xBB, // PPS + 0x00, 0x00, 0x00, 0x01, 0x65, 0xCC, 0xDD, // IDR + ]; + let nals: Vec<&[u8]> = AnnexBIter::new(&data).collect(); + assert_eq!(nals.len(), 3); + assert_eq!(nals[0], &[0x67, 0xAA]); + assert_eq!(nals[1], &[0x68, 0xBB]); + assert_eq!(nals[2], &[0x65, 0xCC, 0xDD]); + } + + #[test] + fn annexb_trailing_zeros_trimmed_and_garbage_prefix_skipped() { + let data = [ + 0xDE, 0xAD, // garbage before the first start code + 0x00, 0x00, 0x01, 0x41, 0x01, 0x00, 0x00, // trailing zeros + 0x00, 0x00, 0x01, 0x41, 0x02, + ]; + let nals: Vec<&[u8]> = AnnexBIter::new(&data).collect(); + assert_eq!(nals.len(), 2); + assert_eq!(nals[0], &[0x41, 0x01]); + assert_eq!(nals[1], &[0x41, 0x02]); + } + + #[test] + fn unescape_removes_only_emulation_bytes() { + let mut out = Vec::new(); + unescape_rbsp(&[0x00, 0x00, 0x03, 0x00, 0x01], &mut out); + assert_eq!(out, &[0x00, 0x00, 0x00, 0x01]); + // 00 00 03 03 -> 00 00 03: only the first 03 is the escape. + unescape_rbsp(&[0x00, 0x00, 0x03, 0x03, 0x01], &mut out); + assert_eq!(out, &[0x00, 0x00, 0x03, 0x01]); + // A 03 not preceded by two zeros stays. + unescape_rbsp(&[0x01, 0x03, 0x00, 0x03], &mut out); + assert_eq!(out, &[0x01, 0x03, 0x00, 0x03]); + // Reuse does not leak previous contents. + unescape_rbsp(&[0x7F], &mut out); + assert_eq!(out, &[0x7F]); + } + + #[test] + fn header_parse_and_forbidden_bit() { + let h = NalHeader::parse(0x67).unwrap(); + assert_eq!(h.ref_idc, 3); + assert_eq!(h.unit_type, NalUnitType::Sps); + assert!(!h.is_idr()); + let h = NalHeader::parse(0x65).unwrap(); + assert!(h.is_idr()); + assert!(h.unit_type.is_slice()); + assert!(NalHeader::parse(0x80).is_err()); + } +} diff --git a/crates/ec-h264-syntax/src/pps.rs b/crates/ec-h264-syntax/src/pps.rs new file mode 100644 index 00000000..dbbb6a71 --- /dev/null +++ b/crates/ec-h264-syntax/src/pps.rs @@ -0,0 +1,266 @@ +//! Picture parameter set (spec 7.3.2.2, 7.4.2.2). + +use ec_core::BitReader; +use ec_core::error::{Error, Result}; + +use crate::more_rbsp_data; +use crate::sps::{ScalingLists, Sps, parse_scaling_matrix}; + +/// Slice-group (FMO) map data, parsed but not interpreted here. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SliceGroupMap { + /// Type 0: `run_length_minus1` per group. + Interleaved(Vec), + /// Type 1: dispersed, no extra data. + Dispersed, + /// Type 2: `(top_left, bottom_right)` per group but the last. + Foreground(Vec<(u32, u32)>), + /// Types 3..=5: `(change_direction_flag, change_rate_minus1)`. + Changing { + /// `slice_group_map_type` (3, 4 or 5). + map_type: u8, + /// `slice_group_change_direction_flag`. + change_direction: bool, + /// `slice_group_change_rate_minus1`. + change_rate_minus1: u32, + }, + /// Type 6: explicit per-map-unit assignment. + Explicit(Vec), +} + +/// Picture parameter set with decode-ready fields. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Pps { + /// `pic_parameter_set_id` (0..=255). + pub id: u32, + /// `seq_parameter_set_id` of the SPS this PPS refers to. + pub sps_id: u8, + /// `entropy_coding_mode_flag`: false = CAVLC, true = CABAC. + pub entropy_coding_mode: bool, + /// `bottom_field_pic_order_in_frame_present_flag`. + pub bottom_field_pic_order_in_frame_present: bool, + /// `num_slice_groups_minus1` + 1. + pub num_slice_groups: u32, + /// FMO map when `num_slice_groups > 1`. + pub slice_group_map: Option, + /// `num_ref_idx_l0_default_active_minus1` + 1. + pub num_ref_idx_l0_default_active: u32, + /// `num_ref_idx_l1_default_active_minus1` + 1. + pub num_ref_idx_l1_default_active: u32, + /// `weighted_pred_flag`. + pub weighted_pred: bool, + /// `weighted_bipred_idc` (0..=2). + pub weighted_bipred_idc: u8, + /// `pic_init_qp_minus26` + 26. + pub pic_init_qp: i32, + /// `pic_init_qs_minus26` + 26. + pub pic_init_qs: i32, + /// `chroma_qp_index_offset` (-12..=12), for Cb. + pub chroma_qp_index_offset: i32, + /// `deblocking_filter_control_present_flag`. + pub deblocking_filter_control_present: bool, + /// `constrained_intra_pred_flag`. + pub constrained_intra_pred: bool, + /// `redundant_pic_cnt_present_flag`. + pub redundant_pic_cnt_present: bool, + /// `transform_8x8_mode_flag` (High-profile tail; false when absent). + pub transform_8x8_mode: bool, + /// PPS scaling lists when `pic_scaling_matrix_present_flag`, resolved + /// against the SPS lists per fall-back rule B. + pub scaling_lists: Option, + /// `second_chroma_qp_index_offset` for Cr (defaults to the Cb offset). + pub second_chroma_qp_index_offset: i32, +} + +impl Pps { + /// Parse a PPS RBSP (header byte consumed, emulation stripped). + /// + /// `sps_lookup` resolves the referenced SPS — needed for the High-profile + /// tail (scaling-list fall-back and 4:4:4 list count). + pub fn parse<'s>(rbsp: &[u8], sps_lookup: impl Fn(u8) -> Option<&'s Sps>) -> Result { + let mut reader = BitReader::new(rbsp); + let r = &mut reader; + let id = r.read_ue()?; + if id > 255 { + return Err(Error::corrupt("pic_parameter_set_id > 255")); + } + let sps_id = r.read_ue()?; + if sps_id > 31 { + return Err(Error::corrupt("seq_parameter_set_id > 31")); + } + let sps_id = sps_id as u8; + let entropy_coding_mode = r.read_bit()?; + let bottom_field_pic_order_in_frame_present = r.read_bit()?; + let num_slice_groups = r.read_ue()?.checked_add(1).ok_or(Error::NeedMore)?; + if num_slice_groups > 8 { + return Err(Error::corrupt("num_slice_groups > 8")); + } + let slice_group_map = if num_slice_groups > 1 { + Some(Self::parse_slice_groups(r, num_slice_groups)?) + } else { + None + }; + let num_ref_idx_l0_default_active = r.read_ue()? + 1; + let num_ref_idx_l1_default_active = r.read_ue()? + 1; + if num_ref_idx_l0_default_active > 32 || num_ref_idx_l1_default_active > 32 { + return Err(Error::corrupt("num_ref_idx_default_active > 32")); + } + let weighted_pred = r.read_bit()?; + let weighted_bipred_idc = r.read_bits(2)? as u8; + let pic_init_qp = 26 + r.read_se()?; + let pic_init_qs = 26 + r.read_se()?; + let chroma_qp_index_offset = r.read_se()?; + if !(-12..=12).contains(&chroma_qp_index_offset) { + return Err(Error::corrupt("chroma_qp_index_offset outside [-12, 12]")); + } + let deblocking_filter_control_present = r.read_bit()?; + let constrained_intra_pred = r.read_bit()?; + let redundant_pic_cnt_present = r.read_bit()?; + + let mut transform_8x8_mode = false; + let mut scaling_lists = None; + let mut second_chroma_qp_index_offset = chroma_qp_index_offset; + if more_rbsp_data(r, rbsp) { + transform_8x8_mode = r.read_bit()?; + if r.read_bit()? { + // pic_scaling_matrix_present_flag + let sps = sps_lookup(sps_id); + let chroma_444 = sps.map(|s| s.chroma_format_idc == 3).unwrap_or(false); + let count = 6 + if chroma_444 { 6 } else { 2 } * usize::from(transform_8x8_mode); + scaling_lists = Some(parse_scaling_matrix( + r, + count, + sps.and_then(|s| s.scaling_lists.as_ref()), + )?); + } + second_chroma_qp_index_offset = r.read_se()?; + if !(-12..=12).contains(&second_chroma_qp_index_offset) { + return Err(Error::corrupt( + "second_chroma_qp_index_offset outside [-12, 12]", + )); + } + } + + Ok(Pps { + id, + sps_id, + entropy_coding_mode, + bottom_field_pic_order_in_frame_present, + num_slice_groups, + slice_group_map, + num_ref_idx_l0_default_active, + num_ref_idx_l1_default_active, + weighted_pred, + weighted_bipred_idc, + pic_init_qp, + pic_init_qs, + chroma_qp_index_offset, + deblocking_filter_control_present, + constrained_intra_pred, + redundant_pic_cnt_present, + transform_8x8_mode, + scaling_lists, + second_chroma_qp_index_offset, + }) + } + + fn parse_slice_groups(r: &mut BitReader<'_>, groups: u32) -> Result { + let map_type = r.read_ue()?; + Ok(match map_type { + 0 => { + let mut runs = Vec::with_capacity(groups as usize); + for _ in 0..groups { + runs.push(r.read_ue()?); + } + SliceGroupMap::Interleaved(runs) + } + 1 => SliceGroupMap::Dispersed, + 2 => { + let mut rects = Vec::with_capacity(groups as usize - 1); + for _ in 0..groups - 1 { + rects.push((r.read_ue()?, r.read_ue()?)); + } + SliceGroupMap::Foreground(rects) + } + 3..=5 => SliceGroupMap::Changing { + map_type: map_type as u8, + change_direction: r.read_bit()?, + change_rate_minus1: r.read_ue()?, + }, + 6 => { + let count = r.read_ue()?.checked_add(1).ok_or(Error::NeedMore)?; + if count > 1 << 20 { + return Err(Error::corrupt("slice group map unit count implausible")); + } + let bits = 32 - (groups - 1).leading_zeros().min(31); + let bits = if groups > 1 { bits.max(1) } else { 1 }; + let mut ids = Vec::with_capacity(count as usize); + for _ in 0..count { + ids.push(r.read_bits(bits)?); + } + SliceGroupMap::Explicit(ids) + } + _ => return Err(Error::corrupt("slice_group_map_type > 6")), + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ec_core::BitWriter; + + fn write_baseline_pps(w: &mut BitWriter) { + w.write_ue(0); // pps id + w.write_ue(0); // sps id + w.write_bit(false); // CAVLC + w.write_bit(false); // bottom_field_pic_order + w.write_ue(0); // one slice group + w.write_ue(0); // l0 default + w.write_ue(0); // l1 default + w.write_bit(false); // weighted_pred + w.write_bits(0, 2); // weighted_bipred_idc + w.write_se(0); // pic_init_qp = 26 + w.write_se(0); // pic_init_qs + w.write_se(2); // chroma_qp_index_offset + w.write_bit(true); // deblocking control present + w.write_bit(false); // constrained intra + w.write_bit(false); // redundant pic cnt + } + + #[test] + fn baseline_pps_without_tail() { + let mut w = BitWriter::new(); + write_baseline_pps(&mut w); + w.write_bit(true); // rbsp_stop_one_bit + w.align_to_byte(); + let pps = Pps::parse(w.as_bytes(), |_| None).unwrap(); + assert_eq!(pps.id, 0); + assert!(!pps.entropy_coding_mode); + assert_eq!(pps.pic_init_qp, 26); + assert_eq!(pps.chroma_qp_index_offset, 2); + assert_eq!(pps.second_chroma_qp_index_offset, 2); // inherits + assert!(!pps.transform_8x8_mode); + assert!(pps.deblocking_filter_control_present); + } + + #[test] + fn high_profile_tail_parsed() { + let mut w = BitWriter::new(); + write_baseline_pps(&mut w); + w.write_bit(true); // transform_8x8_mode + w.write_bit(false); // no pic scaling matrix + w.write_se(-3); // second_chroma_qp_index_offset + w.write_bit(true); // stop bit + w.align_to_byte(); + let pps = Pps::parse(w.as_bytes(), |_| None).unwrap(); + assert!(pps.transform_8x8_mode); + assert_eq!(pps.second_chroma_qp_index_offset, -3); + assert_eq!(pps.chroma_qp_index_offset, 2); + } + + #[test] + fn truncated_pps_is_need_more() { + assert!(Pps::parse(&[], |_| None).unwrap_err().is_need_more()); + } +} diff --git a/crates/ec-h264-syntax/src/slice.rs b/crates/ec-h264-syntax/src/slice.rs new file mode 100644 index 00000000..b3ca69ca --- /dev/null +++ b/crates/ec-h264-syntax/src/slice.rs @@ -0,0 +1,608 @@ +//! Slice header (spec 7.3.3, 7.4.3) for all five slice types. + +use ec_core::BitReader; +use ec_core::error::{Error, Result}; + +use crate::nal::NalHeader; +use crate::pps::Pps; +use crate::sps::Sps; + +/// `slice_type` % 5 (spec Table 7-6). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum SliceType { + /// Predicted slice. + P, + /// Bi-predicted slice. + B, + /// Intra slice. + I, + /// Switching-predicted slice. + Sp, + /// Switching-intra slice. + Si, +} + +impl SliceType { + /// Map `slice_type` (0..=9); values 5..=9 assert the type for the whole + /// picture but decode identically. + pub fn from_code(code: u32) -> Result { + Ok(match code % 5 { + 0 => SliceType::P, + 1 => SliceType::B, + 2 => SliceType::I, + 3 => SliceType::Sp, + 4 => SliceType::Si, + _ => unreachable!(), + }) + } + + /// True for I and SI. + pub fn is_intra(&self) -> bool { + matches!(self, SliceType::I | SliceType::Si) + } +} + +/// One `ref_pic_list_modification` operation (spec 7.3.3.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RefPicListMod { + /// `modification_of_pic_nums_idc` 0/1: `abs_diff_pic_num_minus1`, + /// subtract (idc 0) or add (idc 1). + ShortTerm { + /// `abs_diff_pic_num_minus1`. + abs_diff_pic_num_minus1: u32, + /// idc 1 = add, idc 0 = subtract. + add: bool, + }, + /// idc 2: `long_term_pic_num`. + LongTerm(u32), +} + +/// One explicit weight entry of the `pred_weight_table` (spec 7.3.3.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct WeightEntry { + /// `(luma_weight, luma_offset)` when `luma_weight_flag`. + pub luma: Option<(i32, i32)>, + /// `[(cb_weight, cb_offset), (cr_weight, cr_offset)]` when signalled. + pub chroma: Option<[(i32, i32); 2]>, +} + +/// `pred_weight_table` (spec 7.3.3.2). +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct PredWeightTable { + /// `luma_log2_weight_denom`. + pub luma_log2_weight_denom: u32, + /// `chroma_log2_weight_denom` (chroma formats only). + pub chroma_log2_weight_denom: u32, + /// Per-reference weights, list 0. + pub l0: Vec, + /// Per-reference weights, list 1 (B slices). + pub l1: Vec, +} + +/// One memory-management control operation (spec 7.3.3.3, Table 7-9). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Mmco { + /// `memory_management_control_operation` (1..=6). + pub op: u32, + /// First operand (difference_of_pic_nums_minus1 / long_term_pic_num / + /// long_term_frame_idx / max_long_term_frame_idx_plus1), op-dependent. + pub arg1: u32, + /// Second operand (op 3: `long_term_frame_idx`). + pub arg2: u32, +} + +/// `dec_ref_pic_marking` (spec 7.3.3.3). +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct DecRefPicMarking { + /// IDR: `no_output_of_prior_pics_flag`. + pub no_output_of_prior_pics: bool, + /// IDR: `long_term_reference_flag`. + pub long_term_reference: bool, + /// Non-IDR: `adaptive_ref_pic_marking_mode_flag`. + pub adaptive: bool, + /// Adaptive-mode operations, in order. + pub mmcos: Vec, +} + +/// Deblocking-filter control from the slice header (spec 7.4.3). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct DeblockControl { + /// `disable_deblocking_filter_idc`: 0 = on, 1 = off, 2 = on but not + /// across slice boundaries. + pub disable_idc: u8, + /// `slice_alpha_c0_offset_div2` * 2. + pub alpha_c0_offset: i32, + /// `slice_beta_offset_div2` * 2. + pub beta_offset: i32, +} + +/// Parsed slice header. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SliceHeader { + /// `first_mb_in_slice` (macroblock address; frame coding). + pub first_mb_in_slice: u32, + /// Slice type (already reduced mod 5). + pub slice_type: SliceType, + /// True when `slice_type` was 5..=9: every slice of the picture has + /// this type. + pub all_slices_same_type: bool, + /// `pic_parameter_set_id`. + pub pps_id: u32, + /// `colour_plane_id` (separate colour planes only). + pub colour_plane_id: u8, + /// `frame_num`. + pub frame_num: u32, + /// `field_pic_flag`. + pub field_pic: bool, + /// `bottom_field_flag`. + pub bottom_field: bool, + /// `idr_pic_id` for IDR slices. + pub idr_pic_id: Option, + /// `pic_order_cnt_lsb` (POC type 0). + pub pic_order_cnt_lsb: u32, + /// `delta_pic_order_cnt_bottom` (POC type 0 + PPS flag). + pub delta_pic_order_cnt_bottom: i32, + /// `delta_pic_order_cnt[0..2]` (POC type 1). + pub delta_pic_order_cnt: [i32; 2], + /// `redundant_pic_cnt` when present. + pub redundant_pic_cnt: u32, + /// B: `direct_spatial_mv_pred_flag`. + pub direct_spatial_mv_pred: bool, + /// Active reference count, list 0 (P/SP/B; PPS default applied). + pub num_ref_idx_l0_active: u32, + /// Active reference count, list 1 (B; PPS default applied). + pub num_ref_idx_l1_active: u32, + /// Reference list modifications, list 0. + pub ref_pic_list_mod_l0: Vec, + /// Reference list modifications, list 1. + pub ref_pic_list_mod_l1: Vec, + /// Prediction weight table when signalled. + pub pred_weight_table: Option, + /// Reference-picture marking when `nal_ref_idc != 0`. + pub dec_ref_pic_marking: Option, + /// `cabac_init_idc` (CABAC, non-intra slices). + pub cabac_init_idc: u32, + /// `SliceQPY` = 26 + pic_init_qp_minus26 + slice_qp_delta. + pub slice_qp: i32, + /// SP: `sp_for_switch_flag`. + pub sp_for_switch: bool, + /// SP/SI: `SliceQSY`. + pub slice_qs: i32, + /// Deblocking control (defaults when the PPS does not signal it). + pub deblock: DeblockControl, + /// `slice_group_change_cycle` (FMO map types 3..=5). + pub slice_group_change_cycle: u32, + /// Bits consumed by the header — slice data starts here. + pub header_bits: u64, +} + +impl SliceHeader { + /// Parse a slice header from the RBSP after the NAL header byte. + pub fn parse(rbsp: &[u8], nal: NalHeader, sps: &Sps, pps: &Pps) -> Result { + let mut reader = BitReader::new(rbsp); + let r = &mut reader; + let first_mb_in_slice = r.read_ue()?; + let slice_type_code = r.read_ue()?; + if slice_type_code > 9 { + return Err(Error::corrupt("slice_type > 9")); + } + let slice_type = SliceType::from_code(slice_type_code)?; + let all_slices_same_type = slice_type_code > 4; + let pps_id = r.read_ue()?; + if pps_id != pps.id { + return Err(Error::corrupt("slice parsed against the wrong PPS")); + } + let colour_plane_id = if sps.separate_colour_plane { + r.read_bits(2)? as u8 + } else { + 0 + }; + let frame_num = r.read_bits(sps.log2_max_frame_num as u32)?; + let mut field_pic = false; + let mut bottom_field = false; + if !sps.frame_mbs_only { + field_pic = r.read_bit()?; + if field_pic { + bottom_field = r.read_bit()?; + } + } + let idr_pic_id = if nal.is_idr() { + let v = r.read_ue()?; + if v > 65535 { + return Err(Error::corrupt("idr_pic_id > 65535")); + } + Some(v) + } else { + None + }; + let mut pic_order_cnt_lsb = 0; + let mut delta_pic_order_cnt_bottom = 0; + let mut delta_pic_order_cnt = [0i32; 2]; + match sps.pic_order_cnt_type { + 0 => { + pic_order_cnt_lsb = r.read_bits(sps.log2_max_pic_order_cnt_lsb as u32)?; + if pps.bottom_field_pic_order_in_frame_present && !field_pic { + delta_pic_order_cnt_bottom = r.read_se()?; + } + } + 1 if !sps.delta_pic_order_always_zero => { + delta_pic_order_cnt[0] = r.read_se()?; + if pps.bottom_field_pic_order_in_frame_present && !field_pic { + delta_pic_order_cnt[1] = r.read_se()?; + } + } + _ => {} + } + let redundant_pic_cnt = if pps.redundant_pic_cnt_present { + r.read_ue()? + } else { + 0 + }; + let direct_spatial_mv_pred = if slice_type == SliceType::B { + r.read_bit()? + } else { + false + }; + + let mut num_ref_idx_l0_active = pps.num_ref_idx_l0_default_active; + let mut num_ref_idx_l1_active = pps.num_ref_idx_l1_default_active; + if matches!(slice_type, SliceType::P | SliceType::Sp | SliceType::B) { + if r.read_bit()? { + // num_ref_idx_active_override_flag + num_ref_idx_l0_active = r.read_ue()? + 1; + if slice_type == SliceType::B { + num_ref_idx_l1_active = r.read_ue()? + 1; + } + } + if num_ref_idx_l0_active > 32 || num_ref_idx_l1_active > 32 { + return Err(Error::corrupt("num_ref_idx_active > 32")); + } + } + + // ref_pic_list_modification (7.3.3.1) — not for I/SI. + let mut ref_pic_list_mod_l0 = Vec::new(); + let mut ref_pic_list_mod_l1 = Vec::new(); + if !slice_type.is_intra() { + Self::parse_ref_list_mod(r, &mut ref_pic_list_mod_l0)?; + } + if slice_type == SliceType::B { + Self::parse_ref_list_mod(r, &mut ref_pic_list_mod_l1)?; + } + + // pred_weight_table (7.3.3.2). + let pred_weight_table = if (pps.weighted_pred + && matches!(slice_type, SliceType::P | SliceType::Sp)) + || (pps.weighted_bipred_idc == 1 && slice_type == SliceType::B) + { + Some(Self::parse_pred_weight_table( + r, + sps, + slice_type, + num_ref_idx_l0_active, + num_ref_idx_l1_active, + )?) + } else { + None + }; + + // dec_ref_pic_marking (7.3.3.3). + let dec_ref_pic_marking = if nal.ref_idc != 0 { + let mut m = DecRefPicMarking::default(); + if nal.is_idr() { + m.no_output_of_prior_pics = r.read_bit()?; + m.long_term_reference = r.read_bit()?; + } else { + m.adaptive = r.read_bit()?; + if m.adaptive { + loop { + let op = r.read_ue()?; + if op == 0 { + break; + } + if op > 6 { + return Err(Error::corrupt("memory_management_control_operation > 6")); + } + if m.mmcos.len() >= 64 { + return Err(Error::corrupt("more than 64 MMCO operations")); + } + let arg1 = match op { + 1..=4 => r.read_ue()?, + 6 => r.read_ue()?, + _ => 0, + }; + let arg2 = if op == 3 { r.read_ue()? } else { 0 }; + m.mmcos.push(Mmco { op, arg1, arg2 }); + } + } + } + Some(m) + } else { + None + }; + + let cabac_init_idc = if pps.entropy_coding_mode && !slice_type.is_intra() { + let v = r.read_ue()?; + if v > 2 { + return Err(Error::corrupt("cabac_init_idc > 2")); + } + v + } else { + 0 + }; + + let slice_qp_delta = r.read_se()?; + let slice_qp = pps.pic_init_qp + slice_qp_delta; + if !(-(sps.bit_depth_luma as i32 - 8) * 6..=51).contains(&slice_qp) { + return Err(Error::corrupt("SliceQPY out of range")); + } + + let mut sp_for_switch = false; + let mut slice_qs = pps.pic_init_qs; + if matches!(slice_type, SliceType::Sp | SliceType::Si) { + if slice_type == SliceType::Sp { + sp_for_switch = r.read_bit()?; + } + slice_qs = pps.pic_init_qs + r.read_se()?; + if !(0..=51).contains(&slice_qs) { + return Err(Error::corrupt("SliceQSY out of range")); + } + } + + let mut deblock = DeblockControl::default(); + if pps.deblocking_filter_control_present { + let idc = r.read_ue()?; + if idc > 2 { + return Err(Error::corrupt("disable_deblocking_filter_idc > 2")); + } + deblock.disable_idc = idc as u8; + if idc != 1 { + let a = r.read_se()?; + let b = r.read_se()?; + if !(-6..=6).contains(&a) || !(-6..=6).contains(&b) { + return Err(Error::corrupt("deblocking offset div2 outside [-6, 6]")); + } + deblock.alpha_c0_offset = a * 2; + deblock.beta_offset = b * 2; + } + } + + let mut slice_group_change_cycle = 0; + if pps.num_slice_groups > 1 + && let Some(crate::pps::SliceGroupMap::Changing { + change_rate_minus1, .. + }) = &pps.slice_group_map + { + // u(v) with v = Ceil(Log2(PicSizeInMapUnits / SliceGroupChangeRate + 1)). + let pic_size_in_map_units = + sps.mb_width * (sps.mb_height / if sps.frame_mbs_only { 1 } else { 2 }); + let rate = change_rate_minus1 + 1; + let max = pic_size_in_map_units.div_ceil(rate) + 1; + let bits = 32 - (max - 1).leading_zeros(); + slice_group_change_cycle = r.read_bits(bits.max(1))?; + } + + Ok(SliceHeader { + first_mb_in_slice, + slice_type, + all_slices_same_type, + pps_id, + colour_plane_id, + frame_num, + field_pic, + bottom_field, + idr_pic_id, + pic_order_cnt_lsb, + delta_pic_order_cnt_bottom, + delta_pic_order_cnt, + redundant_pic_cnt, + direct_spatial_mv_pred, + num_ref_idx_l0_active, + num_ref_idx_l1_active, + ref_pic_list_mod_l0, + ref_pic_list_mod_l1, + pred_weight_table, + dec_ref_pic_marking, + cabac_init_idc, + slice_qp, + sp_for_switch, + slice_qs, + deblock, + slice_group_change_cycle, + header_bits: reader.bit_position(), + }) + } + + fn parse_ref_list_mod(r: &mut BitReader<'_>, out: &mut Vec) -> Result<()> { + if !r.read_bit()? { + return Ok(()); // ref_pic_list_modification_flag == 0 + } + loop { + let idc = r.read_ue()?; + match idc { + 0 | 1 => out.push(RefPicListMod::ShortTerm { + abs_diff_pic_num_minus1: r.read_ue()?, + add: idc == 1, + }), + 2 => out.push(RefPicListMod::LongTerm(r.read_ue()?)), + 3 => return Ok(()), + _ => return Err(Error::corrupt("modification_of_pic_nums_idc > 3")), + } + if out.len() > 64 { + return Err(Error::corrupt("more than 64 ref list modifications")); + } + } + } + + fn parse_pred_weight_table( + r: &mut BitReader<'_>, + sps: &Sps, + slice_type: SliceType, + l0_count: u32, + l1_count: u32, + ) -> Result { + let mut t = PredWeightTable { + luma_log2_weight_denom: r.read_ue()?, + ..Default::default() + }; + if t.luma_log2_weight_denom > 7 { + return Err(Error::corrupt("luma_log2_weight_denom > 7")); + } + let has_chroma = sps.chroma_format_idc != 0 && !sps.separate_colour_plane; + if has_chroma { + t.chroma_log2_weight_denom = r.read_ue()?; + if t.chroma_log2_weight_denom > 7 { + return Err(Error::corrupt("chroma_log2_weight_denom > 7")); + } + } + let parse_list = |r: &mut BitReader<'_>, count: u32| -> Result> { + let mut list = Vec::with_capacity(count as usize); + for _ in 0..count { + let luma = if r.read_bit()? { + Some((r.read_se()?, r.read_se()?)) + } else { + None + }; + let chroma = if has_chroma && r.read_bit()? { + Some([(r.read_se()?, r.read_se()?), (r.read_se()?, r.read_se()?)]) + } else { + None + }; + list.push(WeightEntry { luma, chroma }); + } + Ok(list) + }; + t.l0 = parse_list(r, l0_count)?; + if slice_type == SliceType::B { + t.l1 = parse_list(r, l1_count)?; + } + Ok(t) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::nal::NalHeader; + use crate::pps::Pps; + use crate::sps::Sps; + use ec_core::BitWriter; + + fn qcif_sps() -> Sps { + let mut w = BitWriter::new(); + w.write_bits(66, 8); + w.write_bits(0xC0, 8); + w.write_bits(10, 8); + w.write_ue(0); + w.write_ue(0); // log2_max_frame_num = 4 + w.write_ue(0); // poc type 0, log2 lsb next + w.write_ue(0); + w.write_ue(1); + w.write_bit(false); + w.write_ue(10); + w.write_ue(8); + w.write_bit(true); + w.write_bit(true); + w.write_bit(false); + w.write_bit(false); + w.write_bit(true); + w.align_to_byte(); + Sps::parse(w.as_bytes()).unwrap() + } + + fn simple_pps() -> Pps { + let mut w = BitWriter::new(); + w.write_ue(0); + w.write_ue(0); + w.write_bit(false); + w.write_bit(false); + w.write_ue(0); + w.write_ue(0); + w.write_ue(0); + w.write_bit(false); + w.write_bits(0, 2); + w.write_se(0); + w.write_se(0); + w.write_se(0); + w.write_bit(false); // no deblocking control in header + w.write_bit(false); + w.write_bit(false); + w.write_bit(true); + w.align_to_byte(); + Pps::parse(w.as_bytes(), |_| None).unwrap() + } + + #[test] + fn idr_i_slice_header() { + let sps = qcif_sps(); + let pps = simple_pps(); + let mut w = BitWriter::new(); + w.write_ue(0); // first_mb_in_slice + w.write_ue(7); // slice_type: I, all slices + w.write_ue(0); // pps id + w.write_bits(0, 4); // frame_num + w.write_ue(3); // idr_pic_id + w.write_bits(0, 4); // pic_order_cnt_lsb + w.write_bit(false); // no_output_of_prior_pics (nal_ref_idc != 0) + w.write_bit(false); // long_term_reference + w.write_se(4); // slice_qp_delta -> QP 30 + w.write_bit(true); // first slice-data bit, not part of header + w.align_to_byte(); + let nal = NalHeader::parse(0x65).unwrap(); + let h = SliceHeader::parse(w.as_bytes(), nal, &sps, &pps).unwrap(); + assert_eq!(h.slice_type, SliceType::I); + assert!(h.all_slices_same_type); + assert_eq!(h.idr_pic_id, Some(3)); + assert_eq!(h.slice_qp, 30); + assert_eq!(h.deblock.disable_idc, 0); + // Header ends right before the trailing data bit we appended. + assert_eq!(h.header_bits, w.bit_len() - 8 + 7); // wrote 1 bit + 7 pad + } + + #[test] + fn p_slice_fields_parse() { + let sps = qcif_sps(); + let pps = simple_pps(); + let mut w = BitWriter::new(); + w.write_ue(2); // first_mb_in_slice + w.write_ue(0); // slice_type: P + w.write_ue(0); // pps id + w.write_bits(1, 4); // frame_num + w.write_bits(2, 4); // pic_order_cnt_lsb + w.write_bit(true); // num_ref_idx_active_override + w.write_ue(1); // l0 active = 2 + w.write_bit(true); // ref_pic_list_modification_flag_l0 + w.write_ue(0); // idc 0: short term subtract + w.write_ue(4); // abs_diff_pic_num_minus1 + w.write_ue(3); // idc 3: end + w.write_bit(false); // adaptive_ref_pic_marking (nal_ref_idc != 0) + w.write_se(-2); // slice_qp_delta -> 24 + w.write_bit(true); + w.align_to_byte(); + let nal = NalHeader::parse(0x41).unwrap(); // non-IDR slice, ref + let h = SliceHeader::parse(w.as_bytes(), nal, &sps, &pps).unwrap(); + assert_eq!(h.slice_type, SliceType::P); + assert_eq!(h.first_mb_in_slice, 2); + assert_eq!(h.num_ref_idx_l0_active, 2); + assert_eq!( + h.ref_pic_list_mod_l0, + vec![RefPicListMod::ShortTerm { + abs_diff_pic_num_minus1: 4, + add: false + }] + ); + assert_eq!(h.slice_qp, 24); + assert!(h.dec_ref_pic_marking.is_some()); + } + + #[test] + fn truncated_header_is_need_more() { + let sps = qcif_sps(); + let pps = simple_pps(); + let nal = NalHeader::parse(0x65).unwrap(); + assert!( + SliceHeader::parse(&[0x88], nal, &sps, &pps) + .unwrap_err() + .is_need_more() + ); + } +} diff --git a/crates/ec-h264-syntax/src/sps.rs b/crates/ec-h264-syntax/src/sps.rs new file mode 100644 index 00000000..17a6a54d --- /dev/null +++ b/crates/ec-h264-syntax/src/sps.rs @@ -0,0 +1,648 @@ +//! Sequence parameter set (spec 7.3.2.1, 7.4.2.1) incl. VUI (Annex E). + +use ec_core::BitReader; +use ec_core::error::{Error, Result}; + +/// The 4x4 and 8x8 quantisation scaling lists (spec 7.3.2.1.1.1). +/// +/// Stored fully resolved: fall-back rules (flat default / previous list) are +/// applied at parse time so a decoder indexes these directly. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ScalingLists { + /// Six 4x4 lists in raster order: Intra Y/Cb/Cr, Inter Y/Cb/Cr. + pub list_4x4: [[u8; 16]; 6], + /// 8x8 lists: Intra Y, Inter Y (plus 4 chroma lists for 4:4:4). + pub list_8x8: [[u8; 64]; 6], +} + +/// Default (flat) scaling: weightScale 16 everywhere = no weighting. +pub const FLAT_4X4: [u8; 16] = [16; 16]; +/// Flat 8x8 list. +pub const FLAT_8X8: [u8; 64] = [16; 64]; + +/// Default Intra 4x4 scaling list (spec Table 7-3), in zig-zag scan order. +pub const DEFAULT_4X4_INTRA: [u8; 16] = [ + 6, 13, 13, 20, 20, 20, 28, 28, 28, 28, 32, 32, 32, 37, 37, 42, +]; +/// Default Inter 4x4 scaling list (spec Table 7-3), in zig-zag scan order. +pub const DEFAULT_4X4_INTER: [u8; 16] = [ + 10, 14, 14, 20, 20, 20, 24, 24, 24, 24, 27, 27, 27, 30, 30, 34, +]; +/// Default Intra 8x8 scaling list (spec Table 7-4), in zig-zag scan order. +pub const DEFAULT_8X8_INTRA: [u8; 64] = [ + 6, 10, 10, 13, 11, 13, 16, 16, 16, 16, 18, 18, 18, 18, 18, 23, 23, 23, 23, 23, 23, 25, 25, 25, + 25, 25, 25, 25, 27, 27, 27, 27, 27, 27, 27, 27, 29, 29, 29, 29, 29, 29, 29, 31, 31, 31, 31, 31, + 31, 33, 33, 33, 33, 33, 36, 36, 36, 36, 38, 38, 38, 40, 40, 42, +]; +/// Default Inter 8x8 scaling list (spec Table 7-4), in zig-zag scan order. +pub const DEFAULT_8X8_INTER: [u8; 64] = [ + 9, 13, 13, 15, 13, 15, 17, 17, 17, 17, 19, 19, 19, 19, 19, 21, 21, 21, 21, 21, 21, 22, 22, 22, + 22, 22, 22, 22, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 27, 27, 27, 27, 27, + 27, 28, 28, 28, 28, 28, 30, 30, 30, 30, 32, 32, 32, 33, 33, 35, +]; + +/// Place a zig-zag-scan-order list into raster order. +fn scan_to_raster(scan_order: &[u8; N], scan: &[u8; N]) -> [u8; N] { + let mut out = [0u8; N]; + for (j, &v) in scan_order.iter().enumerate() { + out[scan[j] as usize] = v; + } + out +} + +impl Default for ScalingLists { + /// Flat lists — the state when no scaling matrix is signalled. + fn default() -> ScalingLists { + ScalingLists { + list_4x4: [FLAT_4X4; 6], + list_8x8: [FLAT_8X8; 6], + } + } +} + +/// Zig-zag scan for 4x4 blocks (spec Table 8-13, frame scan), used to place +/// scaling-list entries and residual levels into raster order. +pub const ZIGZAG_4X4: [u8; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15]; + +/// Zig-zag (frame) scan for 8x8 blocks (spec Table 8-14). +pub const ZIGZAG_8X8: [u8; 64] = [ + 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, + 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, + 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, +]; + +/// Parse one `scaling_list` (spec 7.3.2.1.1.1) of `N` entries into raster +/// order. Returns `None` when `use_default_scaling_matrix_flag` fired. +fn parse_scaling_list( + r: &mut BitReader<'_>, + scan: &[u8; N], +) -> Result> { + let mut list = [0u8; N]; + let mut last_scale = 8i32; + let mut next_scale = 8i32; + for j in 0..N { + if next_scale != 0 { + let delta = r.read_se()?; + next_scale = (last_scale + delta + 256) % 256; + if j == 0 && next_scale == 0 { + return Ok(None); // use_default_scaling_matrix_flag + } + } + let v = if next_scale == 0 { + last_scale + } else { + next_scale + }; + list[scan[j] as usize] = v as u8; + last_scale = v; + } + Ok(Some(list)) +} + +/// Parse the `seq_scaling_list` / `pic_scaling_list` block shared by SPS and +/// PPS (spec 7.3.2.1, fall-back rules of Table 7-2). `count` is 8 +/// (4:2:0/4:2:2) or 12 (4:4:4). `sps_lists` is `None` in an SPS (fall-back +/// rule A: absent list 0/3/6/7 takes the *default* list) and `Some` in a PPS +/// whose SPS carried a matrix (rule B: those indices take the SPS list). +/// Lists are returned in raster order, fully resolved. +pub(crate) fn parse_scaling_matrix( + r: &mut BitReader<'_>, + count: usize, + sps_lists: Option<&ScalingLists>, +) -> Result { + let mut out = ScalingLists::default(); + let d4_intra = scan_to_raster(&DEFAULT_4X4_INTRA, &ZIGZAG_4X4); + let d4_inter = scan_to_raster(&DEFAULT_4X4_INTER, &ZIGZAG_4X4); + let d8_intra = scan_to_raster(&DEFAULT_8X8_INTRA, &ZIGZAG_8X8); + let d8_inter = scan_to_raster(&DEFAULT_8X8_INTER, &ZIGZAG_8X8); + for idx in 0..count { + let present = r.read_bit()?; + if idx < 6 { + let default = if idx < 3 { d4_intra } else { d4_inter }; + let fallback = match idx { + 0 | 3 => match sps_lists { + Some(s) => s.list_4x4[idx], + None => default, + }, + _ => out.list_4x4[idx - 1], + }; + out.list_4x4[idx] = if present { + parse_scaling_list::<16>(r, &ZIGZAG_4X4)?.unwrap_or(default) + } else { + fallback + }; + } else { + let i = idx - 6; + let default = if i % 2 == 0 { d8_intra } else { d8_inter }; + let fallback = if i < 2 { + match sps_lists { + Some(s) => s.list_8x8[i], + None => default, + } + } else { + out.list_8x8[i - 2] + }; + out.list_8x8[i] = if present { + parse_scaling_list::<64>(r, &ZIGZAG_8X8)?.unwrap_or(default) + } else { + fallback + }; + } + } + Ok(out) +} + +/// HRD parameters (spec E.1.2), carried for completeness. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Hrd { + /// Per-CPB `(bit_rate_value_minus1, cpb_size_value_minus1, cbr_flag)`. + pub cpb: Vec<(u32, u32, bool)>, + /// `bit_rate_scale`. + pub bit_rate_scale: u8, + /// `cpb_size_scale`. + pub cpb_size_scale: u8, + /// `initial_cpb_removal_delay_length_minus1`. + pub initial_cpb_removal_delay_length_minus1: u8, + /// `cpb_removal_delay_length_minus1`. + pub cpb_removal_delay_length_minus1: u8, + /// `dpb_output_delay_length_minus1`. + pub dpb_output_delay_length_minus1: u8, + /// `time_offset_length`. + pub time_offset_length: u8, +} + +impl Hrd { + fn parse(r: &mut BitReader<'_>) -> Result { + let cpb_cnt_minus1 = r.read_ue()?; + if cpb_cnt_minus1 > 31 { + return Err(Error::corrupt("cpb_cnt_minus1 > 31")); + } + let bit_rate_scale = r.read_bits(4)? as u8; + let cpb_size_scale = r.read_bits(4)? as u8; + let mut cpb = Vec::with_capacity(cpb_cnt_minus1 as usize + 1); + for _ in 0..=cpb_cnt_minus1 { + let bit_rate = r.read_ue()?; + let cpb_size = r.read_ue()?; + let cbr = r.read_bit()?; + cpb.push((bit_rate, cpb_size, cbr)); + } + Ok(Hrd { + cpb, + bit_rate_scale, + cpb_size_scale, + initial_cpb_removal_delay_length_minus1: r.read_bits(5)? as u8, + cpb_removal_delay_length_minus1: r.read_bits(5)? as u8, + dpb_output_delay_length_minus1: r.read_bits(5)? as u8, + time_offset_length: r.read_bits(5)? as u8, + }) + } +} + +/// VUI parameters (spec E.1.1). +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Vui { + /// Sample aspect ratio `(width, height)` when signalled; `aspect_ratio_idc` + /// table values are resolved here, Extended_SAR reads the pair verbatim. + pub sample_aspect_ratio: Option<(u16, u16)>, + /// `overscan_appropriate_flag` when `overscan_info_present_flag`. + pub overscan_appropriate: Option, + /// `video_format` (E-2) when signalled. + pub video_format: Option, + /// `video_full_range_flag`. + pub video_full_range: bool, + /// H.273 `(colour_primaries, transfer_characteristics, matrix_coefficients)`. + pub colour_description: Option<(u8, u8, u8)>, + /// `(chroma_sample_loc_type_top_field, chroma_sample_loc_type_bottom_field)`. + pub chroma_sample_loc: Option<(u32, u32)>, + /// `(num_units_in_tick, time_scale, fixed_frame_rate_flag)`. + pub timing_info: Option<(u32, u32, bool)>, + /// NAL HRD parameters. + pub nal_hrd: Option, + /// VCL HRD parameters. + pub vcl_hrd: Option, + /// `low_delay_hrd_flag` (present when either HRD is). + pub low_delay_hrd: bool, + /// `pic_struct_present_flag`. + pub pic_struct_present: bool, + /// Bitstream restriction fields, in spec order. + pub bitstream_restriction: Option, +} + +/// `bitstream_restriction` fields (spec E.1.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct BitstreamRestriction { + /// `motion_vectors_over_pic_boundaries_flag`. + pub motion_vectors_over_pic_boundaries: bool, + /// `max_bytes_per_pic_denom`. + pub max_bytes_per_pic_denom: u32, + /// `max_bits_per_mb_denom`. + pub max_bits_per_mb_denom: u32, + /// `log2_max_mv_length_horizontal`. + pub log2_max_mv_length_horizontal: u32, + /// `log2_max_mv_length_vertical`. + pub log2_max_mv_length_vertical: u32, + /// `max_num_reorder_frames`. + pub max_num_reorder_frames: u32, + /// `max_dec_frame_buffering`. + pub max_dec_frame_buffering: u32, +} + +/// Table E-1 aspect ratios for `aspect_ratio_idc` 1..=16. +const SAR_TABLE: [(u16, u16); 17] = [ + (0, 0), // 0 = unspecified + (1, 1), + (12, 11), + (10, 11), + (16, 11), + (40, 33), + (24, 11), + (20, 11), + (32, 11), + (80, 33), + (18, 11), + (15, 11), + (64, 33), + (160, 99), + (4, 3), + (3, 2), + (2, 1), +]; + +impl Vui { + fn parse(r: &mut BitReader<'_>) -> Result { + let mut vui = Vui::default(); + if r.read_bit()? { + // aspect_ratio_info_present_flag + let idc = r.read_bits(8)? as u8; + vui.sample_aspect_ratio = match idc { + 0 => None, + 255 => Some((r.read_bits(16)? as u16, r.read_bits(16)? as u16)), + 1..=16 => Some(SAR_TABLE[idc as usize]), + _ => None, // reserved: ignore per spec + }; + } + if r.read_bit()? { + vui.overscan_appropriate = Some(r.read_bit()?); + } + if r.read_bit()? { + // video_signal_type_present_flag + vui.video_format = Some(r.read_bits(3)? as u8); + vui.video_full_range = r.read_bit()?; + if r.read_bit()? { + vui.colour_description = Some(( + r.read_bits(8)? as u8, + r.read_bits(8)? as u8, + r.read_bits(8)? as u8, + )); + } + } + if r.read_bit()? { + vui.chroma_sample_loc = Some((r.read_ue()?, r.read_ue()?)); + } + if r.read_bit()? { + vui.timing_info = Some((r.read_bits(32)?, r.read_bits(32)?, r.read_bit()?)); + } + let nal_hrd_present = r.read_bit()?; + if nal_hrd_present { + vui.nal_hrd = Some(Hrd::parse(r)?); + } + let vcl_hrd_present = r.read_bit()?; + if vcl_hrd_present { + vui.vcl_hrd = Some(Hrd::parse(r)?); + } + if nal_hrd_present || vcl_hrd_present { + vui.low_delay_hrd = r.read_bit()?; + } + vui.pic_struct_present = r.read_bit()?; + if r.read_bit()? { + vui.bitstream_restriction = Some(BitstreamRestriction { + motion_vectors_over_pic_boundaries: r.read_bit()?, + max_bytes_per_pic_denom: r.read_ue()?, + max_bits_per_mb_denom: r.read_ue()?, + log2_max_mv_length_horizontal: r.read_ue()?, + log2_max_mv_length_vertical: r.read_ue()?, + max_num_reorder_frames: r.read_ue()?, + max_dec_frame_buffering: r.read_ue()?, + }); + } + Ok(vui) + } +} + +/// Sequence parameter set (spec 7.4.2.1) with decode-ready derived geometry. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Sps { + /// `profile_idc`. + pub profile_idc: u8, + /// `constraint_setX_flag` bits (bit 7 = set0) + reserved bits, verbatim. + pub constraint_flags: u8, + /// `level_idc`. + pub level_idc: u8, + /// `seq_parameter_set_id` (0..=31). + pub id: u8, + /// `chroma_format_idc`: 0 mono, 1 = 4:2:0, 2 = 4:2:2, 3 = 4:4:4. + pub chroma_format_idc: u8, + /// `separate_colour_plane_flag` (4:4:4 only). + pub separate_colour_plane: bool, + /// Luma bit depth (8..=14). + pub bit_depth_luma: u8, + /// Chroma bit depth (8..=14). + pub bit_depth_chroma: u8, + /// `qpprime_y_zero_transform_bypass_flag`. + pub transform_bypass: bool, + /// Scaling lists when `seq_scaling_matrix_present_flag`, resolved. + pub scaling_lists: Option, + /// `log2_max_frame_num` (4..=16, offset applied). + pub log2_max_frame_num: u8, + /// `pic_order_cnt_type` (0..=2). + pub pic_order_cnt_type: u8, + /// `log2_max_pic_order_cnt_lsb` (POC type 0, offset applied). + pub log2_max_pic_order_cnt_lsb: u8, + /// `delta_pic_order_always_zero_flag` (POC type 1). + pub delta_pic_order_always_zero: bool, + /// `offset_for_non_ref_pic` (POC type 1). + pub offset_for_non_ref_pic: i32, + /// `offset_for_top_to_bottom_field` (POC type 1). + pub offset_for_top_to_bottom_field: i32, + /// `offset_for_ref_frame` list (POC type 1). + pub offsets_for_ref_frame: Vec, + /// `max_num_ref_frames`. + pub max_num_ref_frames: u32, + /// `gaps_in_frame_num_value_allowed_flag`. + pub gaps_in_frame_num_allowed: bool, + /// `frame_mbs_only_flag`. + pub frame_mbs_only: bool, + /// `mb_adaptive_frame_field_flag` (when `!frame_mbs_only`). + pub mb_adaptive_frame_field: bool, + /// `direct_8x8_inference_flag`. + pub direct_8x8_inference: bool, + /// Crop offsets in luma samples `(left, right, top, bottom)`, already + /// scaled by the chroma-format crop units (spec 7.4.2.1.1). + pub crop: (u32, u32, u32, u32), + /// VUI parameters when present. + pub vui: Option, + + // ---- derived, computed once at parse time ---- + /// `PicWidthInMbs`. + pub mb_width: u32, + /// `FrameHeightInMbs` (frame coding). + pub mb_height: u32, + /// Coded luma width in samples (mb_width * 16). + pub coded_width: u32, + /// Coded luma height in samples. + pub coded_height: u32, + /// Visible width after cropping. + pub width: u32, + /// Visible height after cropping. + pub height: u32, +} + +impl Sps { + /// Parse an SPS RBSP (header byte already consumed, emulation stripped). + pub fn parse(rbsp: &[u8]) -> Result { + let mut r = BitReader::new(rbsp); + let r = &mut r; + let profile_idc = r.read_bits(8)? as u8; + let constraint_flags = r.read_bits(8)? as u8; + let level_idc = r.read_bits(8)? as u8; + let id = r.read_ue()?; + if id > 31 { + return Err(Error::corrupt("seq_parameter_set_id > 31")); + } + + let mut chroma_format_idc = 1u8; + let mut separate_colour_plane = false; + let mut bit_depth_luma = 8u8; + let mut bit_depth_chroma = 8u8; + let mut transform_bypass = false; + let mut scaling_lists = None; + if matches!( + profile_idc, + 100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135 + ) { + let cf = r.read_ue()?; + if cf > 3 { + return Err(Error::corrupt("chroma_format_idc > 3")); + } + chroma_format_idc = cf as u8; + if chroma_format_idc == 3 { + separate_colour_plane = r.read_bit()?; + } + let bdl = r.read_ue()?; + let bdc = r.read_ue()?; + if bdl > 6 || bdc > 6 { + return Err(Error::corrupt("bit_depth_minus8 > 6")); + } + bit_depth_luma = 8 + bdl as u8; + bit_depth_chroma = 8 + bdc as u8; + transform_bypass = r.read_bit()?; + if r.read_bit()? { + let count = if chroma_format_idc == 3 { 12 } else { 8 }; + scaling_lists = Some(parse_scaling_matrix(r, count, None)?); + } + } + + let log2_mfn = r.read_ue()?; + if log2_mfn > 12 { + return Err(Error::corrupt("log2_max_frame_num_minus4 > 12")); + } + let log2_max_frame_num = 4 + log2_mfn as u8; + let pic_order_cnt_type = r.read_ue()?; + if pic_order_cnt_type > 2 { + return Err(Error::corrupt("pic_order_cnt_type > 2")); + } + let pic_order_cnt_type = pic_order_cnt_type as u8; + let mut log2_max_pic_order_cnt_lsb = 0u8; + let mut delta_pic_order_always_zero = false; + let mut offset_for_non_ref_pic = 0i32; + let mut offset_for_top_to_bottom_field = 0i32; + let mut offsets_for_ref_frame = Vec::new(); + match pic_order_cnt_type { + 0 => { + let v = r.read_ue()?; + if v > 12 { + return Err(Error::corrupt("log2_max_pic_order_cnt_lsb_minus4 > 12")); + } + log2_max_pic_order_cnt_lsb = 4 + v as u8; + } + 1 => { + delta_pic_order_always_zero = r.read_bit()?; + offset_for_non_ref_pic = r.read_se()?; + offset_for_top_to_bottom_field = r.read_se()?; + let n = r.read_ue()?; + if n > 255 { + return Err(Error::corrupt( + "num_ref_frames_in_pic_order_cnt_cycle > 255", + )); + } + offsets_for_ref_frame.reserve(n as usize); + for _ in 0..n { + offsets_for_ref_frame.push(r.read_se()?); + } + } + _ => {} + } + let max_num_ref_frames = r.read_ue()?; + let gaps_in_frame_num_allowed = r.read_bit()?; + let pic_width_in_mbs_minus1 = r.read_ue()?; + let pic_height_in_map_units_minus1 = r.read_ue()?; + let frame_mbs_only = r.read_bit()?; + let mb_adaptive_frame_field = if !frame_mbs_only { + r.read_bit()? + } else { + false + }; + let direct_8x8_inference = r.read_bit()?; + + let mb_width = pic_width_in_mbs_minus1 + 1; + let map_height = pic_height_in_map_units_minus1 + 1; + let mb_height = map_height * if frame_mbs_only { 1 } else { 2 }; + if mb_width > 1024 || mb_height > 1024 { + return Err(Error::corrupt("picture larger than 16384x16384")); + } + let coded_width = mb_width * 16; + let coded_height = mb_height * 16; + + // Crop units (spec 7.4.2.1.1): chroma-format dependent. + let (crop_x, crop_y_frame) = match chroma_format_idc { + 0 => (1, 1), + 1 => (2, 2), + 2 => (2, 1), + _ => (1, 1), + }; + let crop_y = crop_y_frame * if frame_mbs_only { 1 } else { 2 }; + let crop = if r.read_bit()? { + let l = r.read_ue()?; + let rr = r.read_ue()?; + let t = r.read_ue()?; + let b = r.read_ue()?; + (crop_x * l, crop_x * rr, crop_y * t, crop_y * b) + } else { + (0, 0, 0, 0) + }; + let width = coded_width + .checked_sub(crop.0 + crop.1) + .filter(|&w| w > 0) + .ok_or_else(|| Error::corrupt("frame cropping wider than the picture"))?; + let height = coded_height + .checked_sub(crop.2 + crop.3) + .filter(|&h| h > 0) + .ok_or_else(|| Error::corrupt("frame cropping taller than the picture"))?; + + let vui = if r.read_bit()? { + Some(Vui::parse(r)?) + } else { + None + }; + + Ok(Sps { + profile_idc, + constraint_flags, + level_idc, + id: id as u8, + chroma_format_idc, + separate_colour_plane, + bit_depth_luma, + bit_depth_chroma, + transform_bypass, + scaling_lists, + log2_max_frame_num, + pic_order_cnt_type, + log2_max_pic_order_cnt_lsb, + delta_pic_order_always_zero, + offset_for_non_ref_pic, + offset_for_top_to_bottom_field, + offsets_for_ref_frame, + max_num_ref_frames, + gaps_in_frame_num_allowed, + frame_mbs_only, + mb_adaptive_frame_field, + direct_8x8_inference, + crop, + vui, + mb_width, + mb_height, + coded_width, + coded_height, + width, + height, + }) + } + + /// Total macroblocks per picture. + pub fn mbs_per_picture(&self) -> u32 { + self.mb_width * self.mb_height + } +} + +#[cfg(test)] +mod tests { + use super::*; + use ec_core::BitWriter; + + /// Build a minimal Baseline QCIF SPS and check the derived geometry. + #[test] + fn baseline_qcif_geometry() { + let mut w = BitWriter::new(); + w.write_bits(66, 8); // profile_idc Baseline + w.write_bits(0xC0, 8); // constraint flags + w.write_bits(10, 8); // level_idc + w.write_ue(0); // sps id + w.write_ue(0); // log2_max_frame_num_minus4 + w.write_ue(0); // pic_order_cnt_type + w.write_ue(0); // log2_max_pic_order_cnt_lsb_minus4 + w.write_ue(1); // max_num_ref_frames + w.write_bit(false); // gaps allowed + w.write_ue(10); // width 11 MBs = 176 + w.write_ue(8); // height 9 MBs = 144 + w.write_bit(true); // frame_mbs_only + w.write_bit(true); // direct_8x8_inference + w.write_bit(false); // no cropping + w.write_bit(false); // no VUI + w.write_bit(true); // rbsp_stop_one_bit + w.align_to_byte(); + let sps = Sps::parse(w.as_bytes()).unwrap(); + assert_eq!(sps.profile_idc, 66); + assert_eq!((sps.mb_width, sps.mb_height), (11, 9)); + assert_eq!((sps.width, sps.height), (176, 144)); + assert_eq!(sps.chroma_format_idc, 1); + assert_eq!(sps.bit_depth_luma, 8); + assert!(sps.frame_mbs_only); + } + + /// Cropping in 4:2:0 is in 2-sample units both directions. + #[test] + fn crop_units_420() { + let mut w = BitWriter::new(); + w.write_bits(66, 8); + w.write_bits(0, 8); + w.write_bits(40, 8); + w.write_ue(0); + w.write_ue(0); + w.write_ue(2); // poc type 2 + w.write_ue(1); + w.write_bit(false); + w.write_ue(119); // 1920 + w.write_ue(67); // 68 MBs = 1088 + w.write_bit(true); + w.write_bit(true); + w.write_bit(true); // cropping + w.write_ue(0); + w.write_ue(0); + w.write_ue(0); + w.write_ue(4); // bottom crop 4 units = 8 luma rows + w.write_bit(false); // no VUI + w.write_bit(true); + w.align_to_byte(); + let sps = Sps::parse(w.as_bytes()).unwrap(); + assert_eq!((sps.width, sps.height), (1920, 1080)); + assert_eq!(sps.crop, (0, 0, 0, 8)); + } + + /// Truncated SPS is NeedMore, never a panic. + #[test] + fn truncated_is_need_more() { + assert!(Sps::parse(&[0x42]).unwrap_err().is_need_more()); + assert!(Sps::parse(&[]).unwrap_err().is_need_more()); + } +}