Skip to content

FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust

M2.1: H.264 NAL/SPS/PPS/slice header parsing

Brandon Thomasa2ac32916b24
diff --git a/Cargo.lock b/Cargo.lock
index 4f3edd481..95c5b5d00 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -35,6 +35,37 @@ version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+[[package]]
+name = "crossbeam-deque"
+version = "0.8.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a"
+dependencies = [
+ "crossbeam-epoch",
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-epoch"
+version = "0.9.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
+
+[[package]]
+name = "either"
+version = "1.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34"
+
[[package]]
name = "errno"
version = "0.3.14"
@@ -74,6 +105,15 @@ dependencies = [
"serde",
]
+[[package]]
+name = "filmcraft-h264"
+version = "0.1.0"
+dependencies = [
+ "filmcraft-bitstream",
+ "rayon",
+ "thiserror",
+]
+
[[package]]
name = "filmcraft-time"
version = "0.1.0"
@@ -252,6 +292,26 @@ dependencies = [
"rand_core",
]
+[[package]]
+name = "rayon"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d"
+dependencies = [
+ "either",
+ "rayon-core",
+]
+
+[[package]]
+name = "rayon-core"
+version = "1.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91"
+dependencies = [
+ "crossbeam-deque",
+ "crossbeam-utils",
+]
+
[[package]]
name = "regex-syntax"
version = "0.8.11"
@@ -361,6 +421,26 @@ dependencies = [
"windows-sys",
]
+[[package]]
+name = "thiserror"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
[[package]]
name = "unarray"
version = "0.1.4"
diff --git a/Cargo.toml b/Cargo.toml
index 2c249a925..56be8255b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -16,6 +16,7 @@ filmcraft-time = { path = "crates/time" }
filmcraft-geom = { path = "crates/geom" }
filmcraft-color = { path = "crates/color" }
filmcraft-bitstream = { path = "crates/bitstream" }
+filmcraft-h264 = { path = "crates/h264" }
filmcraft-frame = { path = "crates/frame" }
filmcraft-media = { path = "crates/media" }
filmcraft-project = { path = "crates/project" }
diff --git a/crates/h264/Cargo.toml b/crates/h264/Cargo.toml
new file mode 100644
index 000000000..c33f682c2
--- /dev/null
+++ b/crates/h264/Cargo.toml
@@ -0,0 +1,21 @@
+[package]
+name = "filmcraft-h264"
+description = "Clean-room pure-Rust H.264/AVC decoder (ITU-T H.264)"
+version.workspace = true
+edition.workspace = true
+license.workspace = true
+rust-version.workspace = true
+
+[lints]
+workspace = true
+
+[features]
+default = ["threads"]
+threads = ["dep:rayon"]
+
+[dependencies]
+filmcraft-bitstream = { workspace = true }
+thiserror = { workspace = true }
+rayon = { workspace = true, optional = true }
+
+[dev-dependencies]
diff --git a/crates/h264/src/error.rs b/crates/h264/src/error.rs
new file mode 100644
index 000000000..32f1d89db
--- /dev/null
+++ b/crates/h264/src/error.rs
@@ -0,0 +1,38 @@
+use filmcraft_bitstream::BitError;
+
+/// Errors produced by the decoder.
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+pub enum Error {
+ /// The bitstream ended early or contained an invalid Exp-Golomb code.
+ #[error("bitstream error: {0}")]
+ Bitstream(#[from] BitError),
+ /// A syntax element had a value outside its legal range.
+ #[error("invalid bitstream: {0}")]
+ Invalid(String),
+ /// A valid feature this decoder does not implement (yet).
+ #[error("unsupported: {0}")]
+ Unsupported(String),
+ /// A slice referenced a parameter set that has not been received.
+ #[error("missing parameter set: {0}")]
+ MissingParameterSet(String),
+}
+
+pub type Result<T> = std::result::Result<T, Error>;
+
+pub(crate) fn invalid<T>(msg: impl Into<String>) -> Result<T> {
+ Err(Error::Invalid(msg.into()))
+}
+
+pub(crate) fn unsupported<T>(msg: impl Into<String>) -> Result<T> {
+ Err(Error::Unsupported(msg.into()))
+}
+
+/// `ensure!(cond, "message")` returns `Error::Invalid` when `cond` is false.
+macro_rules! ensure {
+ ($cond:expr, $($arg:tt)+) => {
+ if !$cond {
+ return Err($crate::error::Error::Invalid(format!($($arg)+)));
+ }
+ };
+}
+pub(crate) use ensure;
diff --git a/crates/h264/src/lib.rs b/crates/h264/src/lib.rs
new file mode 100644
index 000000000..a316c54ed
--- /dev/null
+++ b/crates/h264/src/lib.rs
@@ -0,0 +1,13 @@
+//! Clean-room pure-Rust H.264 / AVC decoder, implemented from ITU-T Rec. H.264 (ISO/IEC 14496-10).
+//!
+//! M2.1: NAL unit, parameter set, slice header and picture order count parsing.
+
+// Constant tables are shared with the macroblock decoding stages that follow.
+#![allow(dead_code)]
+
+mod error;
+pub mod params;
+pub mod slice;
+mod tables;
+
+pub use error::{Error, Result};
diff --git a/crates/h264/src/params.rs b/crates/h264/src/params.rs
new file mode 100644
index 000000000..51ca1fd2b
--- /dev/null
+++ b/crates/h264/src/params.rs
@@ -0,0 +1,716 @@
+//! Sequence and picture parameter sets (7.3.2.1, 7.3.2.2) including VUI and scaling lists.
+
+use crate::error::{Result, ensure, unsupported};
+use crate::tables::*;
+use filmcraft_bitstream::BitReader;
+
+/// Scaling matrices after applying fall-back rules, stored in raster order (weightScale).
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ScalingMatrices {
+ /// [Intra Y, Intra Cb, Intra Cr, Inter Y, Inter Cb, Inter Cr], raster order.
+ pub m4: [[u8; 16]; 6],
+ /// [Intra Y, Inter Y, Intra Cb, Inter Cb, Intra Cr, Inter Cr], raster order.
+ pub m8: [[u8; 64]; 6],
+}
+
+impl ScalingMatrices {
+ pub fn flat() -> Self {
+ Self { m4: [[16; 16]; 6], m8: [[16; 64]; 6] }
+ }
+ pub fn is_flat(&self) -> bool {
+ self.m4.iter().all(|m| m.iter().all(|&v| v == 16)) && self.m8.iter().all(|m| m.iter().all(|&v| v == 16))
+ }
+}
+
+/// Lists as parsed, in zig-zag order, before inverse scanning.
+#[derive(Clone, Debug)]
+struct ZzLists {
+ l4: [[u8; 16]; 6],
+ l8: [[u8; 64]; 6],
+}
+
+fn zz4_to_raster(l: &[u8; 16]) -> [u8; 16] {
+ let mut out = [0; 16];
+ for (k, &v) in l.iter().enumerate() {
+ out[ZIGZAG4[k] as usize] = v;
+ }
+ out
+}
+fn zz8_to_raster(l: &[u8; 64]) -> [u8; 64] {
+ let mut out = [0; 64];
+ for (k, &v) in l.iter().enumerate() {
+ out[ZIGZAG8[k] as usize] = v;
+ }
+ out
+}
+
+impl ZzLists {
+ fn to_matrices(&self) -> ScalingMatrices {
+ let mut m = ScalingMatrices::flat();
+ for i in 0..6 {
+ m.m4[i] = zz4_to_raster(&self.l4[i]);
+ m.m8[i] = zz8_to_raster(&self.l8[i]);
+ }
+ m
+ }
+ fn flat() -> Self {
+ Self { l4: [[16; 16]; 6], l8: [[16; 64]; 6] }
+ }
+}
+
+/// Result of parsing one scaling_list(): Some(list) or None meaning "use default".
+fn parse_scaling_list<const N: usize>(r: &mut BitReader) -> Result<Option<[u8; N]>> {
+ let mut list = [0u8; N];
+ let mut last = 8i32;
+ let mut next = 8i32;
+ for (j, item) in list.iter_mut().enumerate() {
+ if next != 0 {
+ let delta = r.read_se()?;
+ ensure!((-128..=127).contains(&delta), "delta_scale out of range");
+ next = (last + delta + 256) % 256;
+ if j == 0 && next == 0 {
+ return Ok(None);
+ }
+ }
+ *item = if next == 0 { last as u8 } else { next as u8 };
+ last = *item as i32;
+ }
+ Ok(Some(list))
+}
+
+/// Parse scaling lists with a fall-back rule. `fallback` gives the lists used for rule B
+/// (sequence-level) or None for rule A.
+fn parse_scaling_lists(r: &mut BitReader, count: usize, fallback: Option<&ZzLists>) -> Result<ZzLists> {
+ let mut out = ZzLists::flat();
+ for i in 0..count.max(8) {
+ let present = if i < count { r.read_flag()? } else { false };
+ if i < 6 {
+ let parsed = if present { Some(parse_scaling_list::<16>(r)?) } else { None };
+ out.l4[i] = match parsed {
+ Some(Some(l)) => l,
+ Some(None) => {
+ if i < 3 {
+ DEFAULT_4X4_INTRA
+ } else {
+ DEFAULT_4X4_INTER
+ }
+ }
+ None => match (i, fallback) {
+ (0, None) => DEFAULT_4X4_INTRA,
+ (3, None) => DEFAULT_4X4_INTER,
+ (0 | 3, Some(f)) => f.l4[i],
+ _ => out.l4[i - 1],
+ },
+ };
+ } else {
+ let k = i - 6;
+ if k >= 6 {
+ break;
+ }
+ let parsed = if present { Some(parse_scaling_list::<64>(r)?) } else { None };
+ out.l8[k] = match parsed {
+ Some(Some(l)) => l,
+ Some(None) => {
+ if k % 2 == 0 {
+ DEFAULT_8X8_INTRA
+ } else {
+ DEFAULT_8X8_INTER
+ }
+ }
+ None => match (k, fallback) {
+ (0, None) => DEFAULT_8X8_INTRA,
+ (1, None) => DEFAULT_8X8_INTER,
+ (0 | 1, Some(f)) => f.l8[k],
+ _ => out.l8[k - 2],
+ },
+ };
+ }
+ }
+ // 8x8 chroma lists that were never signalled (count == 8) follow rule A/B chains as well.
+ if count <= 8 {
+ for k in 2..6 {
+ out.l8[k] = out.l8[k - 2];
+ }
+ }
+ Ok(out)
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct HrdParameters {
+ pub cpb_cnt: u32,
+ pub bit_rate_scale: u8,
+ pub cpb_size_scale: u8,
+ pub bit_rate_value_minus1: Vec<u32>,
+ pub cpb_size_value_minus1: Vec<u32>,
+ pub cbr_flag: Vec<bool>,
+ pub initial_cpb_removal_delay_length: u8,
+ pub cpb_removal_delay_length: u8,
+ pub dpb_output_delay_length: u8,
+ pub time_offset_length: u8,
+}
+
+fn parse_hrd(r: &mut BitReader) -> Result<HrdParameters> {
+ let cpb_cnt = r.read_ue()? + 1;
+ ensure!(cpb_cnt <= 32, "cpb_cnt_minus1 out of range");
+ let mut h = HrdParameters { cpb_cnt, bit_rate_scale: r.read_bits(4)? as u8, cpb_size_scale: r.read_bits(4)? as u8, ..Default::default() };
+ for _ in 0..cpb_cnt {
+ h.bit_rate_value_minus1.push(r.read_ue()?);
+ h.cpb_size_value_minus1.push(r.read_ue()?);
+ h.cbr_flag.push(r.read_flag()?);
+ }
+ h.initial_cpb_removal_delay_length = r.read_bits(5)? as u8 + 1;
+ h.cpb_removal_delay_length = r.read_bits(5)? as u8 + 1;
+ h.dpb_output_delay_length = r.read_bits(5)? as u8 + 1;
+ h.time_offset_length = r.read_bits(5)? as u8;
+ Ok(h)
+}
+
+/// Video usability information (Annex E).
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Vui {
+ pub aspect_ratio_idc: u8,
+ pub sar: (u16, u16),
+ pub overscan_appropriate: Option<bool>,
+ pub video_format: u8,
+ pub full_range: bool,
+ pub colour_primaries: u8,
+ pub transfer_characteristics: u8,
+ pub matrix_coefficients: u8,
+ pub chroma_loc: Option<(u32, u32)>,
+ pub timing: Option<(u32, u32, bool)>,
+ pub nal_hrd: Option<HrdParameters>,
+ pub vcl_hrd: Option<HrdParameters>,
+ pub low_delay_hrd: bool,
+ pub pic_struct_present: bool,
+ pub bitstream_restriction: Option<BitstreamRestriction>,
+}
+
+impl Default for Vui {
+ fn default() -> Self {
+ Self {
+ aspect_ratio_idc: 0,
+ sar: (0, 0),
+ overscan_appropriate: None,
+ video_format: 5,
+ full_range: false,
+ colour_primaries: 2,
+ transfer_characteristics: 2,
+ matrix_coefficients: 2,
+ chroma_loc: None,
+ timing: None,
+ nal_hrd: None,
+ vcl_hrd: None,
+ low_delay_hrd: false,
+ pic_struct_present: false,
+ bitstream_restriction: None,
+ }
+ }
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct BitstreamRestriction {
+ pub motion_vectors_over_pic_boundaries: bool,
+ pub max_bytes_per_pic_denom: u32,
+ pub max_bits_per_mb_denom: u32,
+ pub log2_max_mv_length_horizontal: u32,
+ pub log2_max_mv_length_vertical: u32,
+ pub max_num_reorder_frames: u32,
+ pub max_dec_frame_buffering: u32,
+}
+
+/// Table E-1 sample aspect ratios.
+const SAR_TABLE: [(u16, u16); 17] = [
+ (0, 0),
+ (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),
+];
+
+fn parse_vui(r: &mut BitReader) -> Result<Vui> {
+ let mut v = Vui::default();
+ if r.read_flag()? {
+ v.aspect_ratio_idc = r.read_bits(8)? as u8;
+ if v.aspect_ratio_idc == 255 {
+ v.sar = (r.read_bits(16)? as u16, r.read_bits(16)? as u16);
+ } else if (v.aspect_ratio_idc as usize) < SAR_TABLE.len() {
+ v.sar = SAR_TABLE[v.aspect_ratio_idc as usize];
+ }
+ }
+ if r.read_flag()? {
+ v.overscan_appropriate = Some(r.read_flag()?);
+ }
+ if r.read_flag()? {
+ v.video_format = r.read_bits(3)? as u8;
+ v.full_range = r.read_flag()?;
+ if r.read_flag()? {
+ v.colour_primaries = r.read_bits(8)? as u8;
+ v.transfer_characteristics = r.read_bits(8)? as u8;
+ v.matrix_coefficients = r.read_bits(8)? as u8;
+ }
+ }
+ if r.read_flag()? {
+ v.chroma_loc = Some((r.read_ue()?, r.read_ue()?));
+ }
+ if r.read_flag()? {
+ let n = r.read_bits(32)?;
+ let t = r.read_bits(32)?;
+ let fixed = r.read_flag()?;
+ v.timing = Some((n, t, fixed));
+ }
+ if r.read_flag()? {
+ v.nal_hrd = Some(parse_hrd(r)?);
+ }
+ if r.read_flag()? {
+ v.vcl_hrd = Some(parse_hrd(r)?);
+ }
+ if v.nal_hrd.is_some() || v.vcl_hrd.is_some() {
+ v.low_delay_hrd = r.read_flag()?;
+ }
+ v.pic_struct_present = r.read_flag()?;
+ // Some streams truncate the VUI after this point; treat EOF as "absent".
+ if r.bits_left() > 0 && r.read_flag()? {
+ let br = (|| -> Result<BitstreamRestriction> {
+ Ok(BitstreamRestriction {
+ motion_vectors_over_pic_boundaries: r.read_flag()?,
+ 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()?,
+ })
+ })();
+ v.bitstream_restriction = br.ok();
+ }
+ Ok(v)
+}
+
+/// Sequence parameter set.
+#[derive(Clone, Debug)]
+pub struct Sps {
+ pub profile_idc: u8,
+ pub constraint_flags: u8,
+ pub level_idc: u8,
+ pub id: u32,
+ pub chroma_format_idc: u32,
+ pub separate_colour_plane: bool,
+ pub bit_depth_luma: u32,
+ pub bit_depth_chroma: u32,
+ pub qpprime_y_zero_transform_bypass: bool,
+ pub seq_scaling_matrix_present: bool,
+ scaling_lists: ZzLists,
+ pub scaling: ScalingMatrices,
+ pub log2_max_frame_num: u32,
+ pub pic_order_cnt_type: u32,
+ pub log2_max_poc_lsb: u32,
+ pub delta_pic_order_always_zero: bool,
+ pub offset_for_non_ref_pic: i32,
+ pub offset_for_top_to_bottom_field: i32,
+ pub offset_for_ref_frame: Vec<i32>,
+ pub max_num_ref_frames: u32,
+ pub gaps_in_frame_num_allowed: bool,
+ pub pic_width_in_mbs: u32,
+ pub pic_height_in_map_units: u32,
+ pub frame_mbs_only: bool,
+ pub mb_adaptive_frame_field: bool,
+ pub direct_8x8_inference: bool,
+ /// (left, right, top, bottom) in crop units as coded.
+ pub frame_crop: Option<(u32, u32, u32, u32)>,
+ pub vui: Option<Vui>,
+}
+
+impl Sps {
+ pub fn parse(rbsp: &[u8]) -> Result<Sps> {
+ let mut r = BitReader::new(rbsp);
+ 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()?;
+ ensure!(id < 32, "seq_parameter_set_id {id} out of range");
+ let mut chroma_format_idc = 1;
+ let mut separate_colour_plane = false;
+ let mut bit_depth_luma = 8;
+ let mut bit_depth_chroma = 8;
+ let mut bypass = false;
+ let mut seq_scaling_matrix_present = false;
+ let mut scaling_lists = ZzLists::flat();
+ if matches!(profile_idc, 100 | 110 | 122 | 244 | 44 | 83 | 86 | 118 | 128 | 138 | 139 | 134 | 135) {
+ chroma_format_idc = r.read_ue()?;
+ ensure!(chroma_format_idc <= 3, "chroma_format_idc out of range");
+ if chroma_format_idc == 3 {
+ separate_colour_plane = r.read_flag()?;
+ }
+ bit_depth_luma = r.read_ue()? + 8;
+ bit_depth_chroma = r.read_ue()? + 8;
+ ensure!(bit_depth_luma <= 14 && bit_depth_chroma <= 14, "bit depth out of range");
+ bypass = r.read_flag()?;
+ seq_scaling_matrix_present = r.read_flag()?;
+ if seq_scaling_matrix_present {
+ let count = if chroma_format_idc != 3 { 8 } else { 12 };
+ scaling_lists = parse_scaling_lists(&mut r, count, None)?;
+ }
+ }
+ let log2_max_frame_num = r.read_ue()? + 4;
+ ensure!(log2_max_frame_num <= 16, "log2_max_frame_num out of range");
+ let pic_order_cnt_type = r.read_ue()?;
+ ensure!(pic_order_cnt_type <= 2, "pic_order_cnt_type out of range");
+ let mut log2_max_poc_lsb = 0;
+ let mut delta_pic_order_always_zero = false;
+ let mut offset_for_non_ref_pic = 0;
+ let mut offset_for_top_to_bottom_field = 0;
+ let mut offset_for_ref_frame = Vec::new();
+ if pic_order_cnt_type == 0 {
+ log2_max_poc_lsb = r.read_ue()? + 4;
+ ensure!(log2_max_poc_lsb <= 16, "log2_max_pic_order_cnt_lsb out of range");
+ } else if pic_order_cnt_type == 1 {
+ delta_pic_order_always_zero = r.read_flag()?;
+ offset_for_non_ref_pic = r.read_se()?;
+ offset_for_top_to_bottom_field = r.read_se()?;
+ let n = r.read_ue()?;
+ ensure!(n <= 255, "num_ref_frames_in_pic_order_cnt_cycle out of range");
+ for _ in 0..n {
+ offset_for_ref_frame.push(r.read_se()?);
+ }
+ }
+ let max_num_ref_frames = r.read_ue()?;
+ ensure!(max_num_ref_frames <= 16, "max_num_ref_frames out of range");
+ let gaps_in_frame_num_allowed = r.read_flag()?;
+ let pic_width_in_mbs = r.read_ue()? + 1;
+ let pic_height_in_map_units = r.read_ue()? + 1;
+ ensure!(pic_width_in_mbs <= 1024 && pic_height_in_map_units <= 1024, "picture too large");
+ let frame_mbs_only = r.read_flag()?;
+ let mb_adaptive_frame_field = if !frame_mbs_only { r.read_flag()? } else { false };
+ let direct_8x8_inference = r.read_flag()?;
+ let frame_crop = if r.read_flag()? { Some((r.read_ue()?, r.read_ue()?, r.read_ue()?, r.read_ue()?)) } else { None };
+ let vui = if r.read_flag()? { Some(parse_vui(&mut r)?) } else { None };
+ let scaling = if seq_scaling_matrix_present { scaling_lists.to_matrices() } else { ScalingMatrices::flat() };
+ let sps = Sps {
+ profile_idc,
+ constraint_flags,
+ level_idc,
+ id,
+ chroma_format_idc,
+ separate_colour_plane,
+ bit_depth_luma,
+ bit_depth_chroma,
+ qpprime_y_zero_transform_bypass: bypass,
+ seq_scaling_matrix_present,
+ scaling_lists,
+ scaling,
+ log2_max_frame_num,
+ pic_order_cnt_type,
+ log2_max_poc_lsb,
+ delta_pic_order_always_zero,
+ offset_for_non_ref_pic,
+ offset_for_top_to_bottom_field,
+ offset_for_ref_frame,
+ max_num_ref_frames,
+ gaps_in_frame_num_allowed,
+ pic_width_in_mbs,
+ pic_height_in_map_units,
+ frame_mbs_only,
+ mb_adaptive_frame_field,
+ direct_8x8_inference,
+ frame_crop,
+ vui,
+ };
+ if let Some((l, rr, t, b)) = sps.frame_crop {
+ let (cx, cy) = sps.crop_unit();
+ ensure!((l + rr) * cx < sps.width() && (t + b) * cy < sps.height(), "frame cropping exceeds picture size");
+ }
+ Ok(sps)
+ }
+
+ /// ChromaArrayType.
+ pub fn chroma_array_type(&self) -> u32 {
+ if self.separate_colour_plane { 0 } else { self.chroma_format_idc }
+ }
+ pub fn frame_height_in_mbs(&self) -> u32 {
+ (2 - self.frame_mbs_only as u32) * self.pic_height_in_map_units
+ }
+ /// Decoded (uncropped) luma width.
+ pub fn width(&self) -> u32 {
+ self.pic_width_in_mbs * 16
+ }
+ pub fn height(&self) -> u32 {
+ self.frame_height_in_mbs() * 16
+ }
+ pub fn max_frame_num(&self) -> u32 {
+ 1 << self.log2_max_frame_num
+ }
+ /// (CropUnitX, CropUnitY).
+ pub fn crop_unit(&self) -> (u32, u32) {
+ let (sub_w, sub_h) = match self.chroma_array_type() {
+ 1 => (2, 2),
+ 2 => (2, 1),
+ _ => (1, 1),
+ };
+ if self.chroma_array_type() == 0 { (1, 2 - self.frame_mbs_only as u32) } else { (sub_w, sub_h * (2 - self.frame_mbs_only as u32)) }
+ }
+ /// Cropping rectangle in luma samples: (x, y, width, height).
+ pub fn crop_rect(&self) -> (u32, u32, u32, u32) {
+ match self.frame_crop {
+ None => (0, 0, self.width(), self.height()),
+ Some((l, r, t, b)) => {
+ let (cx, cy) = self.crop_unit();
+ (l * cx, t * cy, self.width() - (l + r) * cx, self.height() - (t + b) * cy)
+ }
+ }
+ }
+
+ /// MaxDpbFrames from Table A-1 (and the VUI max_dec_frame_buffering when present).
+ pub fn max_dpb_frames(&self) -> usize {
+ let max_dpb_mbs: u32 = match self.level_idc {
+ 9 => 396,
+ 10 => 396,
+ 11 => {
+ if self.constraint_flags & 0x10 != 0 && !matches!(self.profile_idc, 100 | 110 | 122 | 244 | 44) {
+ 396
+ } else {
+ 900
+ }
+ }
+ 12 | 13 | 20 => 2376,
+ 21 => 4752,
+ 22 | 30 => 8100,
+ 31 => 18000,
+ 32 => 20480,
+ 40 | 41 => 32768,
+ 42 => 34816,
+ 50 => 110400,
+ 51 | 52 => 184320,
+ 60..=62 => 696320,
+ _ => 184320,
+ };
+ let frame_mbs = self.pic_width_in_mbs * self.frame_height_in_mbs();
+ let mut n = (max_dpb_mbs / frame_mbs.max(1)).clamp(1, 16) as usize;
+ if let Some(br) = self.vui.as_ref().and_then(|v| v.bitstream_restriction.as_ref()) {
+ n = (br.max_dec_frame_buffering as usize).min(16);
+ }
+ n.max(self.max_num_ref_frames as usize).max(1)
+ }
+
+ /// Number of frames that may precede a frame in decoding order and follow it in output order.
+ pub fn max_num_reorder_frames(&self) -> usize {
+ if let Some(br) = self.vui.as_ref().and_then(|v| v.bitstream_restriction.as_ref()) {
+ return br.max_num_reorder_frames as usize;
+ }
+ // Profiles that cannot reorder (no B slices) with constraint_set3 (intra) etc.
+ if matches!(self.profile_idc, 44 | 86 | 100 | 110 | 122 | 244) && self.constraint_flags & 0x10 != 0 {
+ return 0;
+ }
+ self.max_dpb_frames()
+ }
+
+ pub fn check_supported(&self) -> Result<()> {
+ if !self.frame_mbs_only {
+ return unsupported("interlaced (field / MBAFF) coding");
+ }
+ if self.chroma_array_type() != 1 {
+ return unsupported(format!("chroma_format_idc {} (only 4:2:0 is implemented)", self.chroma_format_idc));
+ }
+ if self.bit_depth_luma != 8 || self.bit_depth_chroma != 8 {
+ return unsupported(format!("bit depth luma {} chroma {} (only 8-bit is implemented)", self.bit_depth_luma, self.bit_depth_chroma));
+ }
+ if self.qpprime_y_zero_transform_bypass {
+ return unsupported("qpprime_y_zero_transform_bypass (lossless)");
+ }
+ Ok(())
+ }
+}
+
+/// Picture parameter set.
+#[derive(Clone, Debug)]
+pub struct Pps {
+ pub id: u32,
+ pub sps_id: u32,
+ pub entropy_coding_mode: bool,
+ pub bottom_field_pic_order_in_frame_present: bool,
+ pub num_slice_groups: u32,
+ pub slice_group_map_type: u32,
+ pub num_ref_idx_l0_default_active: u32,
+ pub num_ref_idx_l1_default_active: u32,
+ pub weighted_pred: bool,
+ pub weighted_bipred_idc: u32,
+ pub pic_init_qp: i32,
+ pub pic_init_qs: i32,
+ pub chroma_qp_index_offset: i32,
+ pub deblocking_filter_control_present: bool,
+ pub constrained_intra_pred: bool,
+ pub redundant_pic_cnt_present: bool,
+ pub transform_8x8_mode: bool,
+ pub pic_scaling_matrix_present: bool,
+ pub second_chroma_qp_index_offset: i32,
+ /// Effective scaling matrices (after PPS/SPS fall-back), raster order.
+ pub scaling: ScalingMatrices,
+}
+
+impl Pps {
+ /// Parse a PPS. Needs the SPS table because the tail depends on chroma_format_idc.
+ pub fn parse(rbsp: &[u8], spss: &[Option<Sps>]) -> Result<Pps> {
+ let mut r = BitReader::new(rbsp);
+ let id = r.read_ue()?;
+ ensure!(id < 256, "pic_parameter_set_id out of range");
+ let sps_id = r.read_ue()?;
+ ensure!(sps_id < 32, "seq_parameter_set_id out of range");
+ let sps = spss.get(sps_id as usize).and_then(|s| s.as_ref()).ok_or_else(|| crate::Error::MissingParameterSet(format!("SPS {sps_id} for PPS {id}")))?;
+ let entropy_coding_mode = r.read_flag()?;
+ let bottom_field_pic_order_in_frame_present = r.read_flag()?;
+ let num_slice_groups = r.read_ue()? + 1;
+ ensure!(num_slice_groups <= 8, "num_slice_groups out of range");
+ let mut slice_group_map_type = 0;
+ if num_slice_groups > 1 {
+ // Parsed for completeness; FMO decoding is unsupported.
+ slice_group_map_type = r.read_ue()?;
+ match slice_group_map_type {
+ 0 => {
+ for _ in 0..num_slice_groups {
+ r.read_ue()?;
+ }
+ }
+ 2 => {
+ for _ in 0..num_slice_groups - 1 {
+ r.read_ue()?;
+ r.read_ue()?;
+ }
+ }
+ 3..=5 => {
+ r.read_flag()?;
+ r.read_ue()?;
+ }
+ 6 => {
+ let n = r.read_ue()? + 1;
+ let bits = 32 - (num_slice_groups - 1).leading_zeros();
+ for _ in 0..n {
+ r.read_bits(bits)?;
+ }
+ }
+ _ => {}
+ }
+ }
+ let num_ref_idx_l0_default_active = r.read_ue()? + 1;
+ let num_ref_idx_l1_default_active = r.read_ue()? + 1;
+ ensure!(num_ref_idx_l0_default_active <= 32 && num_ref_idx_l1_default_active <= 32, "num_ref_idx_default_active out of range");
+ let weighted_pred = r.read_flag()?;
+ let weighted_bipred_idc = r.read_bits(2)?;
+ let pic_init_qp = 26 + r.read_se()?;
+ let pic_init_qs = 26 + r.read_se()?;
+ let chroma_qp_index_offset = r.read_se()?;
+ ensure!((-12..=12).contains(&chroma_qp_index_offset), "chroma_qp_index_offset out of range");
+ let deblocking_filter_control_present = r.read_flag()?;
+ let constrained_intra_pred = r.read_flag()?;
+ let redundant_pic_cnt_present = r.read_flag()?;
+ let mut transform_8x8_mode = false;
+ let mut pic_scaling_matrix_present = false;
+ let mut second_chroma_qp_index_offset = chroma_qp_index_offset;
+ let mut scaling = sps.scaling.clone();
+ if r.more_rbsp_data() {
+ transform_8x8_mode = r.read_flag()?;
+ pic_scaling_matrix_present = r.read_flag()?;
+ if pic_scaling_matrix_present {
+ let count = 6 + if sps.chroma_format_idc != 3 { 2 } else { 6 } * transform_8x8_mode as usize;
+ // Fall-back rule B uses the sequence-level lists (or Flat when the SPS has none, but then
+ // rule A applies per 7.4.2.2).
+ let lists = if sps.seq_scaling_matrix_present {
+ parse_scaling_lists(&mut r, count, Some(&sps.scaling_lists))?
+ } else {
+ parse_scaling_lists(&mut r, count, None)?
+ };
+ scaling = lists.to_matrices();
+ }
+ second_chroma_qp_index_offset = r.read_se()?;
+ ensure!((-12..=12).contains(&second_chroma_qp_index_offset), "second_chroma_qp_index_offset out of range");
+ }
+ Ok(Pps {
+ id,
+ sps_id,
+ entropy_coding_mode,
+ bottom_field_pic_order_in_frame_present,
+ num_slice_groups,
+ slice_group_map_type,
+ 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,
+ pic_scaling_matrix_present,
+ second_chroma_qp_index_offset,
+ scaling,
+ })
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use filmcraft_bitstream::BitWriter;
+
+ #[test]
+ fn scaling_list_default_signal() {
+ // delta_scale = -8 on the first entry => nextScale 0 => use default.
+ let mut w = BitWriter::new();
+ w.write_se(-8);
+ w.rbsp_trailing();
+ let b = w.finish();
+ let mut r = BitReader::new(&b);
+ assert_eq!(parse_scaling_list::<16>(&mut r).unwrap(), None);
+ }
+
+ #[test]
+ fn scaling_list_repeat_last() {
+ // 8 -> +2 = 10, then +0 = 10, then -10 => 0 => repeat 10 for the rest.
+ let mut w = BitWriter::new();
+ w.write_se(2);
+ w.write_se(0);
+ w.write_se(-10);
+ w.rbsp_trailing();
+ let b = w.finish();
+ let mut r = BitReader::new(&b);
+ let l = parse_scaling_list::<16>(&mut r).unwrap().unwrap();
+ assert_eq!(l, [10; 16]);
+ }
+
+ #[test]
+ fn parse_minimal_baseline_sps() {
+ // profile 66, level 30, sps_id 0, log2_max_frame_num_minus4 0, poc type 2, 1 ref, 11x9 MBs.
+ let mut w = BitWriter::new();
+ w.write_bits(66, 8);
+ w.write_bits(0xC0, 8);
+ w.write_bits(30, 8);
+ w.write_ue(0);
+ w.write_ue(0);
+ w.write_ue(2);
+ w.write_ue(1);
+ w.write_bit(false);
+ w.write_ue(10);
+ w.write_ue(8);
+ w.write_bit(true); // frame_mbs_only
+ w.write_bit(true); // direct_8x8
+ w.write_bit(false); // cropping
+ w.write_bit(false); // vui
+ w.rbsp_trailing();
+ let sps = Sps::parse(&w.finish()).unwrap();
+ assert_eq!((sps.width(), sps.height()), (176, 144));
+ assert_eq!(sps.pic_order_cnt_type, 2);
+ assert_eq!(sps.crop_rect(), (0, 0, 176, 144));
+ }
+}
diff --git a/crates/h264/src/slice.rs b/crates/h264/src/slice.rs
new file mode 100644
index 000000000..b92bdf69a
--- /dev/null
+++ b/crates/h264/src/slice.rs
@@ -0,0 +1,500 @@
+//! NAL unit header and slice header parsing (7.3.1, 7.3.3).
+
+use crate::error::{Result, ensure};
+use crate::params::{Pps, Sps};
+use filmcraft_bitstream::BitReader;
+
+/// NAL unit types used by the decoder.
+pub mod nal_type {
+ pub const SLICE: u8 = 1;
+ pub const SLICE_DPA: u8 = 2;
+ pub const SLICE_DPB: u8 = 3;
+ pub const SLICE_DPC: u8 = 4;
+ pub const IDR: u8 = 5;
+ pub const SEI: u8 = 6;
+ pub const SPS: u8 = 7;
+ pub const PPS: u8 = 8;
+ pub const AUD: u8 = 9;
+ pub const END_SEQ: u8 = 10;
+ pub const END_STREAM: u8 = 11;
+ pub const FILLER: u8 = 12;
+ pub const SPS_EXT: u8 = 13;
+ pub const PREFIX: u8 = 14;
+ pub const SUBSET_SPS: u8 = 15;
+ pub const AUX_SLICE: u8 = 19;
+ pub const SLICE_EXT: u8 = 20;
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct NalHeader {
+ pub nal_ref_idc: u8,
+ pub nal_unit_type: u8,
+}
+
+impl NalHeader {
+ pub fn parse(b: u8) -> Result<Self> {
+ ensure!(b & 0x80 == 0, "forbidden_zero_bit set");
+ Ok(Self { nal_ref_idc: (b >> 5) & 3, nal_unit_type: b & 0x1f })
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum SliceType {
+ P,
+ B,
+ I,
+ Sp,
+ Si,
+}
+
+impl SliceType {
+ fn from_raw(v: u32) -> Result<Self> {
+ Ok(match v % 5 {
+ 0 => SliceType::P,
+ 1 => SliceType::B,
+ 2 => SliceType::I,
+ 3 => SliceType::Sp,
+ _ => SliceType::Si,
+ })
+ }
+ pub fn is_intra(self) -> bool {
+ matches!(self, SliceType::I | SliceType::Si)
+ }
+ pub fn is_b(self) -> bool {
+ self == SliceType::B
+ }
+ pub fn is_p(self) -> bool {
+ matches!(self, SliceType::P | SliceType::Sp)
+ }
+}
+
+/// One entry of ref_pic_list_modification().
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct RefPicListMod {
+ pub idc: u32,
+ /// abs_diff_pic_num_minus1 or long_term_pic_num.
+ pub value: u32,
+}
+
+/// memory_management_control_operation entry.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Mmco {
+ pub op: u32,
+ pub difference_of_pic_nums_minus1: u32,
+ pub long_term_pic_num: u32,
+ pub long_term_frame_idx: u32,
+ pub max_long_term_frame_idx_plus1: u32,
+}
+
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct WeightEntry {
+ pub luma_weight: i32,
+ pub luma_offset: i32,
+ pub luma_flag: bool,
+ pub chroma_weight: [i32; 2],
+ pub chroma_offset: [i32; 2],
+ pub chroma_flag: bool,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct PredWeightTable {
+ pub luma_log2_denom: u32,
+ pub chroma_log2_denom: u32,
+ pub l0: Vec<WeightEntry>,
+ pub l1: Vec<WeightEntry>,
+}
+
+#[derive(Clone, Debug)]
+pub struct SliceHeader {
+ pub nal_ref_idc: u8,
+ pub nal_unit_type: u8,
+ pub idr: bool,
+ pub first_mb_in_slice: u32,
+ pub slice_type_raw: u32,
+ pub slice_type: SliceType,
+ pub pps_id: u32,
+ pub colour_plane_id: u32,
+ pub frame_num: u32,
+ pub field_pic: bool,
+ pub bottom_field: bool,
+ pub idr_pic_id: u32,
+ pub pic_order_cnt_lsb: u32,
+ pub delta_pic_order_cnt_bottom: i32,
+ pub delta_pic_order_cnt: [i32; 2],
+ pub redundant_pic_cnt: u32,
+ pub direct_spatial_mv_pred: bool,
+ pub num_ref_idx_active: [u32; 2],
+ pub ref_pic_list_mod: [Vec<RefPicListMod>; 2],
+ pub pred_weight_table: Option<PredWeightTable>,
+ pub no_output_of_prior_pics: bool,
+ pub long_term_reference: bool,
+ pub adaptive_ref_pic_marking: bool,
+ pub mmcos: Vec<Mmco>,
+ pub cabac_init_idc: u32,
+ pub slice_qp_delta: i32,
+ pub sp_for_switch: bool,
+ pub slice_qs_delta: i32,
+ pub disable_deblocking_filter_idc: u32,
+ pub slice_alpha_c0_offset_div2: i32,
+ pub slice_beta_offset_div2: i32,
+ pub slice_group_change_cycle: u32,
+ /// Bit offset of slice_data() within the RBSP.
+ pub header_bits: usize,
+}
+
+impl SliceHeader {
+ pub fn qp(&self, pps: &Pps) -> i32 {
+ pps.pic_init_qp + self.slice_qp_delta
+ }
+ pub fn has_mmco5(&self) -> bool {
+ self.mmcos.iter().any(|m| m.op == 5)
+ }
+
+ /// Parse the slice header. `pps_lookup` resolves pic_parameter_set_id to (PPS, SPS).
+ pub fn parse<'a>(rbsp: &[u8], nal: NalHeader, pps_lookup: impl FnOnce(u32) -> Result<(&'a Pps, &'a Sps)>) -> Result<(SliceHeader, &'a Pps, &'a Sps)> {
+ let mut r = BitReader::new(rbsp);
+ let idr = nal.nal_unit_type == nal_type::IDR;
+ let first_mb_in_slice = r.read_ue()?;
+ let slice_type_raw = r.read_ue()?;
+ ensure!(slice_type_raw <= 9, "slice_type out of range");
+ let slice_type = SliceType::from_raw(slice_type_raw)?;
+ let pps_id = r.read_ue()?;
+ ensure!(pps_id < 256, "pic_parameter_set_id out of range");
+ let (pps, sps) = pps_lookup(pps_id)?;
+ let mut colour_plane_id = 0;
+ if sps.separate_colour_plane {
+ colour_plane_id = r.read_bits(2)?;
+ }
+ let frame_num = r.read_bits(sps.log2_max_frame_num)?;
+ let mut field_pic = false;
+ let mut bottom_field = false;
+ if !sps.frame_mbs_only {
+ field_pic = r.read_flag()?;
+ if field_pic {
+ bottom_field = r.read_flag()?;
+ }
+ }
+ let idr_pic_id = if idr { r.read_ue()? } else { 0 };
+ let mut pic_order_cnt_lsb = 0;
+ let mut delta_pic_order_cnt_bottom = 0;
+ let mut delta_pic_order_cnt = [0; 2];
+ if sps.pic_order_cnt_type == 0 {
+ pic_order_cnt_lsb = r.read_bits(sps.log2_max_poc_lsb)?;
+ if pps.bottom_field_pic_order_in_frame_present && !field_pic {
+ delta_pic_order_cnt_bottom = r.read_se()?;
+ }
+ }
+ if sps.pic_order_cnt_type == 1 && !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.is_b() { r.read_flag()? } else { false };
+ let mut num_ref_idx_active = [pps.num_ref_idx_l0_default_active, pps.num_ref_idx_l1_default_active];
+ if !slice_type.is_intra() {
+ if r.read_flag()? {
+ num_ref_idx_active[0] = r.read_ue()? + 1;
+ if slice_type.is_b() {
+ num_ref_idx_active[1] = r.read_ue()? + 1;
+ }
+ }
+ let max = if field_pic { 32 } else { 16 };
+ ensure!(num_ref_idx_active[0] <= max && num_ref_idx_active[1] <= max, "num_ref_idx_active out of range");
+ }
+ if !slice_type.is_b() {
+ num_ref_idx_active[1] = 0;
+ }
+ if slice_type.is_intra() {
+ num_ref_idx_active[0] = 0;
+ }
+ ensure!(nal.nal_unit_type != 20 && nal.nal_unit_type != 21, "MVC slices are not supported");
+ let mut ref_pic_list_mod = [Vec::new(), Vec::new()];
+ for (list, mods) in ref_pic_list_mod.iter_mut().enumerate() {
+ let present = if list == 0 { !slice_type.is_intra() } else { slice_type.is_b() };
+ if present && r.read_flag()? {
+ loop {
+ let idc = r.read_ue()?;
+ ensure!(idc <= 5, "modification_of_pic_nums_idc out of range");
+ if idc == 3 {
+ break;
+ }
+ let value = r.read_ue()?;
+ mods.push(RefPicListMod { idc, value });
+ ensure!(mods.len() <= 66, "too many ref_pic_list_modification entries");
+ }
+ }
+ }
+ let mut pred_weight_table = None;
+ if (pps.weighted_pred && slice_type.is_p()) || (pps.weighted_bipred_idc == 1 && slice_type.is_b()) {
+ let luma_log2_denom = r.read_ue()?;
+ ensure!(luma_log2_denom <= 7, "luma_log2_weight_denom out of range");
+ let mut chroma_log2_denom = 0;
+ if sps.chroma_array_type() != 0 {
+ chroma_log2_denom = r.read_ue()?;
+ ensure!(chroma_log2_denom <= 7, "chroma_log2_weight_denom out of range");
+ }
+ let mut lists = [Vec::new(), Vec::new()];
+ let nlists = if slice_type.is_b() { 2 } else { 1 };
+ for (l, entries) in lists.iter_mut().enumerate().take(nlists) {
+ for _ in 0..num_ref_idx_active[l] {
+ let mut e = WeightEntry { luma_weight: 1 << luma_log2_denom, chroma_weight: [1 << chroma_log2_denom; 2], ..Default::default() };
+ if r.read_flag()? {
+ e.luma_flag = true;
+ e.luma_weight = r.read_se()?;
+ e.luma_offset = r.read_se()?;
+ ensure!((-128..=127).contains(&e.luma_weight) && (-128..=127).contains(&e.luma_offset), "luma weight out of range");
+ }
+ if sps.chroma_array_type() != 0 && r.read_flag()? {
+ e.chroma_flag = true;
+ for j in 0..2 {
+ e.chroma_weight[j] = r.read_se()?;
+ e.chroma_offset[j] = r.read_se()?;
+ ensure!((-128..=127).contains(&e.chroma_weight[j]) && (-128..=127).contains(&e.chroma_offset[j]), "chroma weight out of range");
+ }
+ }
+ entries.push(e);
+ }
+ }
+ let [l0, l1] = lists;
+ pred_weight_table = Some(PredWeightTable { luma_log2_denom, chroma_log2_denom, l0, l1 });
+ }
+ let mut no_output_of_prior_pics = false;
+ let mut long_term_reference = false;
+ let mut adaptive_ref_pic_marking = false;
+ let mut mmcos = Vec::new();
+ if nal.nal_ref_idc != 0 {
+ if idr {
+ no_output_of_prior_pics = r.read_flag()?;
+ long_term_reference = r.read_flag()?;
+ } else {
+ adaptive_ref_pic_marking = r.read_flag()?;
+ if adaptive_ref_pic_marking {
+ loop {
+ let op = r.read_ue()?;
+ ensure!(op <= 6, "memory_management_control_operation out of range");
+ if op == 0 {
+ break;
+ }
+ let mut m =
+ Mmco { op, difference_of_pic_nums_minus1: 0, long_term_pic_num: 0, long_term_frame_idx: 0, max_long_term_frame_idx_plus1: 0 };
+ if op == 1 || op == 3 {
+ m.difference_of_pic_nums_minus1 = r.read_ue()?;
+ }
+ if op == 2 {
+ m.long_term_pic_num = r.read_ue()?;
+ }
+ if op == 3 || op == 6 {
+ m.long_term_frame_idx = r.read_ue()?;
+ }
+ if op == 4 {
+ m.max_long_term_frame_idx_plus1 = r.read_ue()?;
+ }
+ mmcos.push(m);
+ ensure!(mmcos.len() <= 66, "too many MMCOs");
+ }
+ }
+ }
+ }
+ let mut cabac_init_idc = 0;
+ if pps.entropy_coding_mode && !slice_type.is_intra() {
+ cabac_init_idc = r.read_ue()?;
+ ensure!(cabac_init_idc <= 2, "cabac_init_idc out of range");
+ }
+ let slice_qp_delta = r.read_se()?;
+ let qp = pps.pic_init_qp + slice_qp_delta;
+ ensure!((0..=51).contains(&qp), "slice QP {qp} out of range");
+ let mut sp_for_switch = false;
+ let mut slice_qs_delta = 0;
+ if matches!(slice_type, SliceType::Sp | SliceType::Si) {
+ if slice_type == SliceType::Sp {
+ sp_for_switch = r.read_flag()?;
+ }
+ slice_qs_delta = r.read_se()?;
+ }
+ let mut disable_deblocking_filter_idc = 0;
+ let mut slice_alpha_c0_offset_div2 = 0;
+ let mut slice_beta_offset_div2 = 0;
+ if pps.deblocking_filter_control_present {
+ disable_deblocking_filter_idc = r.read_ue()?;
+ ensure!(disable_deblocking_filter_idc <= 2, "disable_deblocking_filter_idc out of range");
+ if disable_deblocking_filter_idc != 1 {
+ slice_alpha_c0_offset_div2 = r.read_se()?;
+ slice_beta_offset_div2 = r.read_se()?;
+ ensure!((-6..=6).contains(&slice_alpha_c0_offset_div2) && (-6..=6).contains(&slice_beta_offset_div2), "deblocking offsets out of range");
+ }
+ }
+ let mut slice_group_change_cycle = 0;
+ if pps.num_slice_groups > 1 && (3..=5).contains(&pps.slice_group_map_type) {
+ // Ceil(Log2(PicSizeInMapUnits / SliceGroupChangeRate + 1)); rate is not retained, so read
+ // conservatively using the picture size (FMO is unsupported for decoding anyway).
+ let pic_size = sps.pic_width_in_mbs * sps.pic_height_in_map_units;
+ let bits = 32 - pic_size.leading_zeros();
+ slice_group_change_cycle = r.read_bits(bits)?;
+ }
+ let header_bits = r.position();
+ Ok((
+ SliceHeader {
+ nal_ref_idc: nal.nal_ref_idc,
+ nal_unit_type: nal.nal_unit_type,
+ idr,
+ first_mb_in_slice,
+ slice_type_raw,
+ slice_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_active,
+ ref_pic_list_mod,
+ pred_weight_table,
+ no_output_of_prior_pics,
+ long_term_reference,
+ adaptive_ref_pic_marking,
+ mmcos,
+ cabac_init_idc,
+ slice_qp_delta,
+ sp_for_switch,
+ slice_qs_delta,
+ disable_deblocking_filter_idc,
+ slice_alpha_c0_offset_div2,
+ slice_beta_offset_div2,
+ slice_group_change_cycle,
+ header_bits,
+ },
+ pps,
+ sps,
+ ))
+ }
+}
+
+/// POC decoding state carried between pictures (8.2.1).
+#[derive(Clone, Debug, Default)]
+pub struct PocState {
+ /// PicOrderCntMsb / pic_order_cnt_lsb of the previous reference picture (type 0).
+ prev_ref_msb: i32,
+ prev_ref_lsb: i32,
+ /// FrameNumOffset / frame_num of the previous picture (types 1 and 2).
+ prev_frame_num_offset: i32,
+ prev_frame_num: u32,
+}
+
+/// Output of POC computation.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct Poc {
+ pub top: i32,
+ pub bottom: i32,
+ msb: i32,
+ frame_num_offset: i32,
+}
+
+impl Poc {
+ pub fn frame(&self) -> i32 {
+ self.top.min(self.bottom)
+ }
+}
+
+impl PocState {
+ /// Compute TopFieldOrderCnt/BottomFieldOrderCnt of a frame (8.2.1.1-8.2.1.3).
+ pub fn compute(&self, sh: &SliceHeader, sps: &Sps) -> Poc {
+ match sps.pic_order_cnt_type {
+ 0 => {
+ let (prev_msb, prev_lsb) = if sh.idr { (0, 0) } else { (self.prev_ref_msb, self.prev_ref_lsb) };
+ let max_lsb = 1i32 << sps.log2_max_poc_lsb;
+ let lsb = sh.pic_order_cnt_lsb as i32;
+ let msb = if lsb < prev_lsb && prev_lsb - lsb >= max_lsb / 2 {
+ prev_msb + max_lsb
+ } else if lsb > prev_lsb && lsb - prev_lsb > max_lsb / 2 {
+ prev_msb - max_lsb
+ } else {
+ prev_msb
+ };
+ let top = msb + lsb;
+ let bottom = top + sh.delta_pic_order_cnt_bottom;
+ Poc { top, bottom, msb, frame_num_offset: 0 }
+ }
+ 1 => {
+ let frame_num_offset = self.frame_num_offset(sh.idr, sh.frame_num, sps);
+ let n = sps.offset_for_ref_frame.len() as i32;
+ let mut abs_frame_num = if n != 0 { frame_num_offset + sh.frame_num as i32 } else { 0 };
+ if sh.nal_ref_idc == 0 && abs_frame_num > 0 {
+ abs_frame_num -= 1;
+ }
+ let mut expected = 0i32;
+ if abs_frame_num > 0 {
+ let cycle_cnt = (abs_frame_num - 1) / n;
+ let in_cycle = (abs_frame_num - 1) % n;
+ let delta_cycle: i32 = sps.offset_for_ref_frame.iter().sum();
+ expected = cycle_cnt.wrapping_mul(delta_cycle);
+ for &o in &sps.offset_for_ref_frame[..=in_cycle as usize] {
+ expected += o;
+ }
+ }
+ if sh.nal_ref_idc == 0 {
+ expected += sps.offset_for_non_ref_pic;
+ }
+ let top = expected + sh.delta_pic_order_cnt[0];
+ let bottom = top + sps.offset_for_top_to_bottom_field + sh.delta_pic_order_cnt[1];
+ Poc { top, bottom, msb: 0, frame_num_offset }
+ }
+ _ => {
+ let frame_num_offset = self.frame_num_offset(sh.idr, sh.frame_num, sps);
+ let temp = if sh.idr {
+ 0
+ } else if sh.nal_ref_idc == 0 {
+ 2 * (frame_num_offset + sh.frame_num as i32) - 1
+ } else {
+ 2 * (frame_num_offset + sh.frame_num as i32)
+ };
+ Poc { top: temp, bottom: temp, msb: 0, frame_num_offset }
+ }
+ }
+ }
+
+ fn frame_num_offset(&self, idr: bool, frame_num: u32, sps: &Sps) -> i32 {
+ if idr {
+ 0
+ } else if self.prev_frame_num > frame_num {
+ self.prev_frame_num_offset + sps.max_frame_num() as i32
+ } else {
+ self.prev_frame_num_offset
+ }
+ }
+
+ /// Update after a picture has been decoded. `poc` is the value returned by [`PocState::compute`]
+ /// (before any MMCO5 adjustment).
+ pub fn update(&mut self, sh: &SliceHeader, poc: &Poc) {
+ let mmco5 = sh.has_mmco5();
+ if sh.nal_ref_idc != 0 {
+ if mmco5 {
+ self.prev_ref_msb = 0;
+ self.prev_ref_lsb = poc.top - poc.frame();
+ } else {
+ self.prev_ref_msb = poc.msb;
+ self.prev_ref_lsb = sh.pic_order_cnt_lsb as i32;
+ }
+ }
+ if mmco5 {
+ self.prev_frame_num_offset = 0;
+ self.prev_frame_num = 0;
+ } else {
+ self.prev_frame_num_offset = poc.frame_num_offset;
+ self.prev_frame_num = sh.frame_num;
+ }
+ }
+
+ /// Account for a "non-existing" frame inferred by the frame_num gap process (8.2.5.2).
+ pub fn update_gap_frame(&mut self, frame_num: u32, sps: &Sps) {
+ let off = self.frame_num_offset(false, frame_num, sps);
+ self.prev_frame_num_offset = off;
+ self.prev_frame_num = frame_num;
+ }
+}
diff --git a/crates/h264/src/tables.rs b/crates/h264/src/tables.rs
new file mode 100644
index 000000000..d6e0d5888
--- /dev/null
+++ b/crates/h264/src/tables.rs
@@ -0,0 +1,175 @@
+//! Small constant tables from the H.264 specification.
+
+/// 4x4 frame zig-zag scan: scan position -> raster index (row * 4 + col).
+pub const ZIGZAG4: [u8; 16] = [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15];
+
+/// 8x8 frame zig-zag scan: scan position -> raster index (row * 8 + col).
+pub const ZIGZAG8: [u8; 64] = zigzag8();
+
+const fn zigzag8() -> [u8; 64] {
+ let mut out = [0u8; 64];
+ let mut k = 0;
+ let mut d: i32 = 0; // anti-diagonal index = row + col
+ while d < 15 {
+ // even diagonals go up-right (row decreasing), odd go down-left
+ let mut i: i32 = 0;
+ while i < 8 {
+ let (row, col) = if d % 2 == 0 { (d - i, i) } else { (i, d - i) };
+ if row >= 0 && row < 8 && col >= 0 && col < 8 {
+ out[k] = (row * 8 + col) as u8;
+ k += 1;
+ }
+ i += 1;
+ }
+ d += 1;
+ }
+ out
+}
+
+/// Table 7-3.
+pub const DEFAULT_4X4_INTRA: [u8; 16] = [6, 13, 13, 20, 20, 20, 28, 28, 28, 28, 32, 32, 32, 37, 37, 42];
+pub const DEFAULT_4X4_INTER: [u8; 16] = [10, 14, 14, 20, 20, 20, 24, 24, 24, 24, 27, 27, 27, 30, 30, 34];
+/// Table 7-4.
+#[rustfmt::skip]
+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,
+];
+#[rustfmt::skip]
+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,
+];
+
+/// Table 8-15: QPc as a function of qPI (0..=51).
+pub const QPC_TABLE: [u8; 52] = {
+ let mut t = [0u8; 52];
+ let tail = [29u8, 30, 31, 32, 32, 33, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 39];
+ let mut i = 0;
+ while i < 52 {
+ t[i] = if i < 30 { i as u8 } else { tail[i - 30] };
+ i += 1;
+ }
+ t
+};
+
+/// (8-315) v matrix for normAdjust4x4.
+pub const NORM_ADJUST4: [[u16; 3]; 6] = [[10, 16, 13], [11, 18, 14], [13, 20, 16], [14, 23, 18], [16, 25, 20], [18, 29, 23]];
+/// (8-318) v matrix for normAdjust8x8.
+pub const NORM_ADJUST8: [[u16; 6]; 6] = [
+ [20, 18, 32, 19, 25, 24],
+ [22, 19, 35, 21, 28, 26],
+ [26, 23, 42, 24, 33, 31],
+ [28, 25, 45, 26, 35, 33],
+ [32, 28, 51, 30, 40, 38],
+ [36, 32, 58, 34, 46, 43],
+];
+
+/// normAdjust4x4(m, i, j) for raster position `pos` (i = row, j = col).
+pub const fn norm_adjust4(m: usize, pos: usize) -> u16 {
+ let (i, j) = (pos / 4, pos % 4);
+ if i % 2 == 0 && j % 2 == 0 {
+ NORM_ADJUST4[m][0]
+ } else if i % 2 == 1 && j % 2 == 1 {
+ NORM_ADJUST4[m][1]
+ } else {
+ NORM_ADJUST4[m][2]
+ }
+}
+
+/// normAdjust8x8(m, i, j) for raster position `pos` (i = row, j = col).
+pub const fn norm_adjust8(m: usize, pos: usize) -> u16 {
+ let (i, j) = (pos / 8, pos % 8);
+ let k = if i % 4 == 0 && j % 4 == 0 {
+ 0
+ } else if i % 2 == 1 && j % 2 == 1 {
+ 1
+ } else if i % 4 == 2 && j % 4 == 2 {
+ 2
+ } else if (i % 4 == 0 && j % 2 == 1) || (i % 2 == 1 && j % 4 == 0) {
+ 3
+ } else if (i % 4 == 0 && j % 4 == 2) || (i % 4 == 2 && j % 4 == 0) {
+ 4
+ } else {
+ 5
+ };
+ NORM_ADJUST8[m][k]
+}
+
+/// Table 8-16 alpha' (indexA 0..=51).
+#[rustfmt::skip]
+pub const ALPHA: [u8; 52] = [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 5, 6, 7, 8, 9, 10, 12, 13,
+ 15, 17, 20, 22, 25, 28, 32, 36, 40, 45, 50, 56, 63, 71, 80, 90, 101, 113, 127, 144, 162, 182, 203, 226, 255, 255,
+];
+/// Table 8-16 beta' (indexB 0..=51).
+#[rustfmt::skip]
+pub const BETA: [u8; 52] = [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4,
+ 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
+];
+/// Table 8-17 tC0' for bS = 1, 2, 3 (indexA 0..=51).
+#[rustfmt::skip]
+pub const TC0: [[u8; 3]; 52] = {
+ let b1: [u8; 52] = [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1,
+ 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 6, 6, 7, 8, 9, 10, 11, 13,
+ ];
+ let b2: [u8; 52] = [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 7, 8, 8, 10, 11, 12, 13, 15, 17,
+ ];
+ let b3: [u8; 52] = [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 6, 6, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 23, 25,
+ ];
+ let mut t = [[0u8; 3]; 52];
+ let mut i = 0;
+ while i < 52 {
+ t[i] = [b1[i], b2[i], b3[i]];
+ i += 1;
+ }
+ t
+};
+
+/// Luma 4x4 block index (decoding order, 6.4.3) -> (x, y) in 4-sample units.
+pub const BLK4_XY: [(u8, u8); 16] =
+ [(0, 0), (1, 0), (0, 1), (1, 1), (2, 0), (3, 0), (2, 1), (3, 1), (0, 2), (1, 2), (0, 3), (1, 3), (2, 2), (3, 2), (2, 3), (3, 3)];
+
+/// Raster 4x4 position (y * 4 + x) -> luma4x4BlkIdx.
+pub const RASTER_TO_BLK4: [u8; 16] = [0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15];
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn zigzag8_known_prefix() {
+ assert_eq!(&ZIGZAG8[..16], &[0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5]);
+ assert_eq!(&ZIGZAG8[48..], &[58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63]);
+ let mut seen = [false; 64];
+ for &z in &ZIGZAG8 {
+ seen[z as usize] = true;
+ }
+ assert!(seen.iter().all(|&s| s));
+ }
+
+ #[test]
+ fn blk4_maps_consistent() {
+ for (b, &(x, y)) in BLK4_XY.iter().enumerate() {
+ let r = (y * 4 + x) as usize;
+ assert_eq!(RASTER_TO_BLK4[r] as usize, b);
+ }
+ }
+
+ #[test]
+ fn qpc() {
+ assert_eq!(QPC_TABLE[29], 29);
+ assert_eq!(QPC_TABLE[30], 29);
+ assert_eq!(QPC_TABLE[51], 39);
+ }
+}
diff --git a/crates/h264/tests/common/mod.rs b/crates/h264/tests/common/mod.rs
new file mode 100644
index 000000000..63206541e
--- /dev/null
+++ b/crates/h264/tests/common/mod.rs
@@ -0,0 +1,366 @@
+//! Test fixture generation (ffmpeg/libx264 as an external oracle) and comparison helpers.
+#![allow(dead_code)]
+
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+/// One encoder configuration of the fixture matrix.
+pub struct Fixture {
+ pub name: &'static str,
+ /// lavfi source (without size / rate).
+ pub source: &'static str,
+ pub width: u32,
+ pub height: u32,
+ pub frames: u32,
+ /// Extra video filter appended after the source (e.g. noise, fade).
+ pub filter: &'static str,
+ /// Encoder arguments.
+ pub args: &'static [&'static str],
+}
+
+const NOISE: &str = "noise=alls=12:allf=t+u";
+
+pub const FIXTURES: &[Fixture] = &[
+ Fixture {
+ name: "intra_cavlc",
+ source: "testsrc2",
+ width: 176,
+ height: 144,
+ frames: 3,
+ filter: "",
+ args: &["-profile:v", "baseline", "-x264-params", "keyint=1:no-deblock=1"],
+ },
+ Fixture {
+ name: "intra_cavlc_noise",
+ source: "mandelbrot",
+ width: 352,
+ height: 288,
+ frames: 3,
+ filter: NOISE,
+ args: &["-profile:v", "baseline", "-x264-params", "keyint=1:no-deblock=1"],
+ },
+ Fixture {
+ name: "intra_cavlc_8x8",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 3,
+ filter: NOISE,
+ args: &["-profile:v", "high", "-x264-params", "keyint=1:no-deblock=1:cabac=0"],
+ },
+ Fixture {
+ name: "intra_cavlc_cqm",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 3,
+ filter: NOISE,
+ args: &["-profile:v", "high", "-x264-params", "keyint=1:no-deblock=1:cabac=0:cqm=jvt"],
+ },
+ Fixture {
+ name: "p_cavlc_nodeblock",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 20,
+ filter: NOISE,
+ args: &["-profile:v", "baseline", "-x264-params", "no-deblock=1:ref=3"],
+ },
+ Fixture {
+ name: "baseline_qcif",
+ source: "testsrc2",
+ width: 176,
+ height: 144,
+ frames: 30,
+ filter: "",
+ args: &["-profile:v", "baseline", "-x264-params", "keyint=15"],
+ },
+ Fixture { name: "baseline_cif_noise", source: "mandelbrot", width: 352, height: 288, frames: 25, filter: NOISE, args: &["-profile:v", "baseline"] },
+ Fixture {
+ name: "cavlc_b",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 30,
+ filter: NOISE,
+ args: &["-profile:v", "high", "-x264-params", "cabac=0:bframes=3"],
+ },
+ Fixture {
+ name: "cavlc_b_temporal",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 30,
+ filter: NOISE,
+ args: &["-profile:v", "main", "-x264-params", "cabac=0:bframes=3:direct=temporal:weightb=1"],
+ },
+ Fixture {
+ name: "cavlc_weightp",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 30,
+ filter: "fade=in:0:25",
+ args: &["-profile:v", "main", "-x264-params", "cabac=0:weightp=2:bframes=2:weightb=1"],
+ },
+ Fixture { name: "main_cabac_b", source: "testsrc2", width: 352, height: 288, frames: 30, filter: NOISE, args: &["-profile:v", "main"] },
+ Fixture { name: "high_720p", source: "smptehdbars", width: 1280, height: 720, frames: 10, filter: NOISE, args: &["-profile:v", "high"] },
+ Fixture { name: "high_1080p", source: "testsrc2", width: 1920, height: 1080, frames: 6, filter: "", args: &["-profile:v", "high"] },
+ Fixture { name: "crop_1918x1078", source: "testsrc2", width: 1918, height: 1078, frames: 5, filter: NOISE, args: &["-profile:v", "high"] },
+ Fixture {
+ name: "bpyramid",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 30,
+ filter: NOISE,
+ args: &["-profile:v", "high", "-x264-params", "bframes=3:b-pyramid=normal"],
+ },
+ Fixture {
+ name: "weightp2",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 30,
+ filter: "fade=in:0:25",
+ args: &["-profile:v", "high", "-x264-params", "weightp=2"],
+ },
+ Fixture {
+ name: "weightb",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 30,
+ filter: "fade=in:0:25",
+ args: &["-profile:v", "high", "-x264-params", "weightb=1:bframes=3"],
+ },
+ Fixture {
+ name: "direct_temporal",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 30,
+ filter: NOISE,
+ args: &["-profile:v", "high", "-x264-params", "direct=temporal:bframes=3"],
+ },
+ Fixture {
+ name: "direct_spatial",
+ source: "mandelbrot",
+ width: 352,
+ height: 288,
+ frames: 30,
+ filter: NOISE,
+ args: &["-profile:v", "high", "-x264-params", "direct=spatial:bframes=3"],
+ },
+ Fixture {
+ name: "ref4",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 30,
+ filter: NOISE,
+ args: &["-profile:v", "high", "-x264-params", "ref=4:bframes=2"],
+ },
+ Fixture {
+ name: "no_deblock",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 20,
+ filter: NOISE,
+ args: &["-profile:v", "high", "-x264-params", "no-deblock=1"],
+ },
+ Fixture {
+ name: "deblock_m2_2",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 20,
+ filter: NOISE,
+ args: &["-profile:v", "high", "-x264-params", "deblock=-2,2"],
+ },
+ Fixture {
+ name: "cqm_jvt",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 20,
+ filter: NOISE,
+ args: &["-profile:v", "high", "-x264-params", "cqm=jvt"],
+ },
+ Fixture {
+ name: "slices4",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 20,
+ filter: NOISE,
+ args: &["-profile:v", "high", "-x264-params", "slices=4"],
+ },
+ Fixture {
+ name: "slices4_cavlc",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 20,
+ filter: NOISE,
+ args: &["-profile:v", "baseline", "-x264-params", "slices=4"],
+ },
+ Fixture {
+ name: "keyint10",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 30,
+ filter: NOISE,
+ args: &["-profile:v", "high", "-x264-params", "keyint=10"],
+ },
+ Fixture {
+ name: "open_gop",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 40,
+ filter: NOISE,
+ args: &["-profile:v", "high", "-x264-params", "open-gop=1:keyint=12:bframes=3"],
+ },
+ Fixture {
+ name: "constrained_intra",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 20,
+ filter: NOISE,
+ args: &["-profile:v", "high", "-x264-params", "constrained-intra=1"],
+ },
+ Fixture {
+ name: "no8x8dct",
+ source: "testsrc2",
+ width: 352,
+ height: 288,
+ frames: 20,
+ filter: NOISE,
+ args: &["-profile:v", "high", "-x264-params", "8x8dct=0"],
+ },
+ Fixture { name: "qp50", source: "testsrc2", width: 352, height: 288, frames: 20, filter: NOISE, args: &["-profile:v", "high", "-qp", "50"] },
+ Fixture { name: "qp1", source: "mandelbrot", width: 352, height: 288, frames: 10, filter: NOISE, args: &["-profile:v", "high", "-qp", "1"] },
+ Fixture {
+ name: "qp1_cavlc",
+ source: "mandelbrot",
+ width: 176,
+ height: 144,
+ frames: 10,
+ filter: NOISE,
+ args: &["-profile:v", "main", "-qp", "1", "-x264-params", "cabac=0"],
+ },
+];
+
+pub fn fixture(name: &str) -> &'static Fixture {
+ FIXTURES.iter().find(|f| f.name == name).unwrap_or_else(|| panic!("unknown fixture {name}"))
+}
+
+pub fn ffmpeg() -> Option<PathBuf> {
+ for p in ["/opt/homebrew/bin/ffmpeg", "/usr/local/bin/ffmpeg", "/usr/bin/ffmpeg"] {
+ if Path::new(p).exists() {
+ return Some(PathBuf::from(p));
+ }
+ }
+ None
+}
+
+pub fn fixtures_dir() -> PathBuf {
+ let d = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../target/fixtures/h264");
+ std::fs::create_dir_all(&d).expect("create fixtures dir");
+ d
+}
+
+fn run(cmd: &mut Command) -> bool {
+ match cmd.output() {
+ Ok(o) if o.status.success() => true,
+ Ok(o) => {
+ eprintln!("command failed: {:?}\n{}", cmd, String::from_utf8_lossy(&o.stderr));
+ false
+ }
+ Err(e) => {
+ eprintln!("failed to run {:?}: {e}", cmd);
+ false
+ }
+ }
+}
+
+/// Generate (if needed) the fixture stream and its ffmpeg reference decode.
+/// Returns None (with a message) when ffmpeg is unavailable.
+pub fn ensure(f: &Fixture) -> Option<(PathBuf, PathBuf)> {
+ let Some(ff) = ffmpeg() else {
+ eprintln!("SKIP {}: ffmpeg not found", f.name);
+ return None;
+ };
+ let dir = fixtures_dir();
+ let h264 = dir.join(format!("{}.h264", f.name));
+ let yuv = dir.join(format!("{}.yuv", f.name));
+ if !h264.exists() {
+ let tmp = dir.join(format!("{}.tmp.{}.h264", f.name, std::process::id()));
+ let mut vf = format!("{}=size={}x{}:rate=25,format=yuv420p", f.source, f.width, f.height);
+ if !f.filter.is_empty() {
+ vf.push(',');
+ vf.push_str(f.filter);
+ }
+ let mut c = Command::new(&ff);
+ c.args(["-hide_banner", "-loglevel", "error", "-y", "-f", "lavfi", "-i", &vf]);
+ c.args(["-frames:v", &f.frames.to_string(), "-c:v", "libx264"]);
+ c.args(f.args);
+ c.args(["-f", "h264"]).arg(&tmp);
+ assert!(run(&mut c), "fixture generation failed for {}", f.name);
+ std::fs::rename(&tmp, &h264).unwrap();
+ }
+ if !yuv.exists() {
+ let tmp = dir.join(format!("{}.tmp.{}.yuv", f.name, std::process::id()));
+ let mut c = Command::new(&ff);
+ c.args(["-hide_banner", "-loglevel", "error", "-y", "-i"]).arg(&h264);
+ c.args(["-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "yuv420p"]).arg(&tmp);
+ assert!(run(&mut c), "reference decode failed for {}", f.name);
+ std::fs::rename(&tmp, &yuv).unwrap();
+ }
+ Some((h264, yuv))
+}
+
+/// Split an Annex-B stream into access units (new AU at AUD/SPS/PPS/SEI after a slice, or at a slice with
+/// first_mb_in_slice == 0).
+pub fn split_access_units(data: &[u8]) -> Vec<&[u8]> {
+ // find start code positions
+ let mut starts = Vec::new();
+ let mut i = 0;
+ while i + 3 <= data.len() {
+ if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 {
+ let s = if i > 0 && data[i - 1] == 0 { i - 1 } else { i };
+ starts.push((s, i + 3));
+ i += 3;
+ } else {
+ i += 1;
+ }
+ }
+ let mut aus = Vec::new();
+ let mut au_start = 0usize;
+ let mut seen_slice = false;
+ for &(sc, payload) in &starts {
+ if payload >= data.len() {
+ continue;
+ }
+ let t = data[payload] & 0x1f;
+ let is_slice = t == 1 || t == 5;
+ let first_mb_zero = is_slice && payload + 1 < data.len() && data[payload + 1] & 0x80 != 0;
+ let boundary = seen_slice && (matches!(t, 6..=9) || first_mb_zero);
+ if boundary {
+ aus.push(&data[au_start..sc]);
+ au_start = sc;
+ seen_slice = false;
+ }
+ if is_slice {
+ seen_slice = true;
+ }
+ }
+ if au_start < data.len() {
+ aus.push(&data[au_start..]);
+ }
+ aus
+}
diff --git a/crates/h264/tests/headers.rs b/crates/h264/tests/headers.rs
new file mode 100644
index 000000000..f0f7a59e3
--- /dev/null
+++ b/crates/h264/tests/headers.rs
@@ -0,0 +1,120 @@
+//! Parameter set / slice header / POC parsing over the fixture streams.
+
+mod common;
+
+use filmcraft_bitstream::{annexb_nals, unescape_rbsp};
+use filmcraft_h264::params::{Pps, Sps};
+use filmcraft_h264::slice::{NalHeader, PocState, SliceHeader, nal_type};
+
+/// Parse every NAL of a fixture; returns (sps, number of pictures, pocs in decoding order).
+fn parse_stream(name: &str) -> Option<(Sps, usize, Vec<i32>)> {
+ let f = common::fixture(name);
+ let (h264, _) = common::ensure(f)?;
+ let data = std::fs::read(h264).unwrap();
+ let mut spss: Vec<Option<Sps>> = vec![None; 32];
+ let mut ppss: Vec<Option<Pps>> = vec![None; 256];
+ let mut poc_state = PocState::default();
+ let mut pocs = Vec::new();
+ let mut last: Option<SliceHeader> = None;
+ let mut pictures = 0;
+ for nal in annexb_nals(&data) {
+ let hdr = NalHeader::parse(nal[0]).unwrap();
+ let rbsp = unescape_rbsp(&nal[1..]);
+ match hdr.nal_unit_type {
+ nal_type::SPS => {
+ let s = Sps::parse(&rbsp).unwrap();
+ let id = s.id as usize;
+ spss[id] = Some(s);
+ }
+ nal_type::PPS => {
+ let p = Pps::parse(&rbsp, &spss).unwrap();
+ let id = p.id as usize;
+ ppss[id] = Some(p);
+ }
+ nal_type::SLICE | nal_type::IDR => {
+ let (sh, _, sps) = SliceHeader::parse(&rbsp, hdr, |id| {
+ let p = ppss[id as usize].as_ref().unwrap();
+ Ok((p, spss[p.sps_id as usize].as_ref().unwrap()))
+ })
+ .unwrap();
+ assert!(sh.header_bits <= rbsp.len() * 8);
+ if sh.first_mb_in_slice == 0 {
+ if let Some(prev) = &last {
+ let poc = poc_state.compute(prev, sps);
+ poc_state.update(prev, &poc);
+ pocs.push(poc.frame());
+ }
+ pictures += 1;
+ last = Some(sh);
+ }
+ }
+ _ => {}
+ }
+ }
+ let sps = spss.into_iter().flatten().next().unwrap();
+ if let Some(prev) = &last {
+ let poc = poc_state.compute(prev, &sps);
+ pocs.push(poc.frame());
+ }
+ Some((sps, pictures, pocs))
+}
+
+#[test]
+fn baseline_headers() {
+ let Some((sps, pictures, pocs)) = parse_stream("baseline_qcif") else { return };
+ assert_eq!(sps.profile_idc, 66);
+ assert_eq!((sps.width(), sps.height()), (176, 144));
+ assert_eq!(pictures, 30);
+ // no B-frames: POC strictly increases between IDRs (keyint 15)
+ for w in pocs.windows(2) {
+ assert!(w[1] > w[0] || w[1] == 0, "{pocs:?}");
+ }
+}
+
+#[test]
+fn cropped_high_profile_headers() {
+ let Some((sps, pictures, _)) = parse_stream("crop_1918x1078") else { return };
+ assert_eq!(sps.profile_idc, 100);
+ assert_eq!(sps.chroma_format_idc, 1);
+ assert_eq!(sps.crop_rect(), (0, 0, 1918, 1078));
+ assert_eq!(pictures, 5);
+ let vui = sps.vui.as_ref().expect("x264 writes a VUI");
+ assert!(vui.bitstream_restriction.is_some());
+}
+
+#[test]
+fn b_frame_pocs_are_a_permutation() {
+ let Some((_, pictures, pocs)) = parse_stream("bpyramid") else { return };
+ assert_eq!(pictures, 30);
+ let mut sorted = pocs.clone();
+ sorted.sort();
+ sorted.dedup();
+ assert_eq!(sorted.len(), pocs.len(), "duplicate POCs: {pocs:?}");
+ // decoding order differs from output order
+ assert_ne!(sorted, pocs);
+}
+
+#[test]
+fn custom_scaling_matrices_parsed() {
+ let Some(f) = common::ensure(common::fixture("cqm_jvt")) else { return };
+ let data = std::fs::read(f.0).unwrap();
+ let mut spss: Vec<Option<Sps>> = vec![None; 32];
+ let mut found = false;
+ for nal in annexb_nals(&data) {
+ let hdr = NalHeader::parse(nal[0]).unwrap();
+ let rbsp = unescape_rbsp(&nal[1..]);
+ if hdr.nal_unit_type == nal_type::SPS {
+ let s = Sps::parse(&rbsp).unwrap();
+ let id = s.id as usize;
+ spss[id] = Some(s);
+ } else if hdr.nal_unit_type == nal_type::PPS {
+ let p = Pps::parse(&rbsp, &spss).unwrap();
+ // JVT matrices are the spec defaults: intra 4x4 luma (0,0) = 6
+ assert_eq!(p.scaling.m4[0][0], 6);
+ assert_eq!(p.scaling.m8[0][0], 6);
+ assert!(p.transform_8x8_mode);
+ found = true;
+ }
+ }
+ assert!(found);
+}