Skip to content

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

M9.1: filmcraft-hevc — clean-room H.265 decoder (Main / Main 10)

Brandon Thomasd0304c41b8d8
diff --git a/Cargo.lock b/Cargo.lock
index efbea46ba..c1b71c1ec 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1464,6 +1464,15 @@ dependencies = [
"thiserror 2.0.21",
]
+[[package]]
+name = "filmcraft-hevc"
+version = "0.1.0"
+dependencies = [
+ "filmcraft-bitstream",
+ "rayon",
+ "thiserror 2.0.21",
+]
+
[[package]]
name = "filmcraft-isobmff"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 7da9d7b91..507ec6905 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -18,6 +18,7 @@ filmcraft-color = { path = "crates/color" }
filmcraft-bitstream = { path = "crates/bitstream" }
filmcraft-isobmff = { path = "crates/isobmff" }
filmcraft-h264 = { path = "crates/h264" }
+filmcraft-hevc = { path = "crates/hevc" }
filmcraft-prores = { path = "crates/prores" }
filmcraft-aac = { path = "crates/aac" }
filmcraft-frame = { path = "crates/frame" }
diff --git a/crates/hevc/Cargo.toml b/crates/hevc/Cargo.toml
new file mode 100644
index 000000000..7e963a21c
--- /dev/null
+++ b/crates/hevc/Cargo.toml
@@ -0,0 +1,21 @@
+[package]
+name = "filmcraft-hevc"
+description = "Clean-room pure-Rust H.265/HEVC decoder (ITU-T H.265)"
+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/hevc/src/cabac.rs b/crates/hevc/src/cabac.rs
new file mode 100644
index 000000000..e45fcc358
--- /dev/null
+++ b/crates/hevc/src/cabac.rs
@@ -0,0 +1,339 @@
+//! CABAC arithmetic decoding engine (9.3.4.3) and context initialisation (9.3.2.2).
+
+use crate::error::{Result, ensure};
+use crate::spec_tables::{CABAC_INIT, NUM_CTX};
+
+/// Table 9-52 (same values as H.264) rangeTabLPS[pStateIdx][qCodIRangeIdx].
+#[rustfmt::skip]
+pub(crate) static RANGE_TAB_LPS: [[u8; 4]; 64] = [
+ [128, 176, 208, 240], [128, 167, 197, 227], [128, 158, 187, 216], [123, 150, 178, 205],
+ [116, 142, 169, 195], [111, 135, 160, 185], [105, 128, 152, 175], [100, 122, 144, 166],
+ [95, 116, 137, 158], [90, 110, 130, 150], [85, 104, 123, 142], [81, 99, 117, 135],
+ [77, 94, 111, 128], [73, 89, 105, 122], [69, 85, 100, 116], [66, 80, 95, 110],
+ [62, 76, 90, 104], [59, 72, 86, 99], [56, 69, 81, 94], [53, 65, 77, 89],
+ [51, 62, 73, 85], [48, 59, 69, 80], [46, 56, 66, 76], [43, 53, 63, 72],
+ [41, 50, 59, 69], [39, 48, 56, 65], [37, 45, 54, 62], [35, 43, 51, 59],
+ [33, 41, 48, 56], [32, 39, 46, 53], [30, 37, 43, 50], [29, 35, 41, 48],
+ [27, 33, 39, 45], [26, 31, 37, 43], [24, 30, 35, 41], [23, 28, 33, 39],
+ [22, 27, 32, 37], [21, 26, 30, 35], [20, 24, 29, 33], [19, 23, 27, 31],
+ [18, 22, 26, 30], [17, 21, 25, 28], [16, 20, 23, 27], [15, 19, 22, 25],
+ [14, 18, 21, 24], [14, 17, 20, 23], [13, 16, 19, 22], [12, 15, 18, 21],
+ [12, 14, 17, 20], [11, 14, 16, 19], [11, 13, 15, 18], [10, 12, 15, 17],
+ [10, 12, 14, 16], [9, 11, 13, 15], [9, 11, 12, 14], [8, 10, 12, 14],
+ [8, 9, 11, 13], [7, 9, 11, 12], [7, 9, 10, 12], [7, 8, 10, 11],
+ [6, 8, 9, 11], [6, 7, 9, 10], [6, 7, 8, 9], [2, 2, 2, 2],
+];
+
+/// Table 9-53 transIdxLPS.
+#[rustfmt::skip]
+static TRANS_IDX_LPS: [u8; 64] = [
+ 0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12,
+ 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, 21, 22, 22, 23, 24,
+ 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33,
+ 33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63,
+];
+
+/// Table 9-53 transIdxMPS.
+#[rustfmt::skip]
+static TRANS_IDX_MPS: [u8; 64] = [
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
+ 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
+ 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
+ 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63,
+];
+
+/// Combined state transition: index = (pStateIdx << 1 | valMPS) * 2 + bin_is_lps.
+/// Each context is stored as `pStateIdx << 1 | valMPS`.
+pub(crate) static NEXT_STATE: [[u8; 2]; 128] = {
+ let mut t = [[0u8; 2]; 128];
+ let mut s = 0;
+ while s < 128 {
+ let p = s >> 1;
+ let mps = s & 1;
+ // MPS path
+ t[s][0] = (TRANS_IDX_MPS[p] << 1) | mps as u8;
+ // LPS path
+ let new_mps = if p == 0 { 1 - mps } else { mps };
+ t[s][1] = (TRANS_IDX_LPS[p] << 1) | new_mps as u8;
+ s += 1;
+ }
+ t
+};
+
+pub type Contexts = [u8; NUM_CTX];
+
+/// Initialise all context variables for `slice_qp` and `init_type` (9.3.2.2). Each context is stored as
+/// `pStateIdx << 1 | valMps`.
+pub fn init_contexts(ctx: &mut Contexts, slice_qp: i32, init_type: usize) {
+ let qp = slice_qp.clamp(0, 51);
+ for (c, &v) in ctx.iter_mut().zip(CABAC_INIT[init_type].iter()) {
+ let slope = (v >> 4) as i32;
+ let offset = (v & 15) as i32;
+ let m = slope * 5 - 45;
+ let n = (offset << 3) - 16;
+ let pre = (((m * qp) >> 4) + n).clamp(1, 126);
+ *c = if pre <= 63 { ((63 - pre) << 1) as u8 } else { (((pre - 64) << 1) | 1) as u8 };
+ }
+}
+
+pub struct Cabac<'a> {
+ data: &'a [u8],
+ /// Byte position of the next byte to load into `value`.
+ next_byte: usize,
+ range: u32,
+ /// ivlOffset scaled by 2^bits: value = (ivlOffset << bits) | (bits already loaded but not yet
+ /// consumed by the arithmetic decoder).
+ value: u64,
+ bits: u32,
+ pub ctx: Contexts,
+}
+
+impl<'a> Cabac<'a> {
+ /// Create an engine over `data` starting at byte `pos`, with contexts initialised for `slice_qp`
+ /// and `init_type`.
+ pub fn new(data: &'a [u8], pos: usize, slice_qp: i32, init_type: usize) -> Result<Self> {
+ let mut c = Cabac { data, next_byte: pos, range: 0, value: 0, bits: 0, ctx: [0; NUM_CTX] };
+ init_contexts(&mut c.ctx, slice_qp, init_type);
+ c.init_engine()?;
+ Ok(c)
+ }
+
+ /// 9.3.2.6: ivlCurrRange = 510, ivlOffset = read_bits(9) (from the current byte-aligned position).
+ pub fn init_engine(&mut self) -> Result<()> {
+ self.range = 510;
+ self.value = 0;
+ self.bits = 0;
+ self.refill();
+ self.bits -= 9;
+ ensure!((self.value >> self.bits) < 510, "invalid CABAC offset at init");
+ Ok(())
+ }
+
+ /// Load 32 more bits (zeros past the end of the data).
+ #[inline(always)]
+ fn refill(&mut self) {
+ let b = self.next_byte;
+ let mut w = [0u8; 4];
+ if let Some(src) = self.data.get(b..b + 4) {
+ w.copy_from_slice(src);
+ } else if b < self.data.len() {
+ let n = self.data.len() - b;
+ w[..n].copy_from_slice(&self.data[b..]);
+ }
+ self.next_byte += 4;
+ self.value = (self.value << 32) | u32::from_be_bytes(w) as u64;
+ self.bits += 32;
+ }
+
+ /// Bit position of the next bit not consumed by the arithmetic decoder (for PCM samples and
+ /// substream ends after decode_terminate returned 1).
+ pub fn bit_pos(&self) -> usize {
+ self.next_byte * 8 - self.bits as usize
+ }
+ /// Continue reading at byte `pos` (call `init_engine` afterwards).
+ pub fn set_byte_pos(&mut self, pos: usize) {
+ self.next_byte = pos;
+ self.value = 0;
+ self.bits = 0;
+ }
+ pub fn data(&self) -> &'a [u8] {
+ self.data
+ }
+ /// True when the reader has run past the end of the data (corrupt stream).
+ pub fn overrun(&self) -> bool {
+ self.next_byte > self.data.len() + 16
+ }
+
+ #[inline(always)]
+ fn renorm(&mut self) {
+ if self.range < 256 {
+ let shift = self.range.leading_zeros() - 23;
+ self.range <<= shift;
+ if self.bits < shift {
+ self.refill();
+ }
+ self.bits -= shift;
+ }
+ }
+
+ #[inline(always)]
+ pub fn decode_decision(&mut self, ctx_idx: usize) -> u32 {
+ let s = self.ctx[ctx_idx] as usize;
+ let q = ((self.range >> 6) & 3) as usize;
+ let lps = RANGE_TAB_LPS[s >> 1][q] as u32;
+ self.range -= lps;
+ let scaled = (self.range as u64) << self.bits;
+ let bin;
+ if self.value >= scaled {
+ bin = 1 - (s & 1) as u32;
+ self.value -= scaled;
+ self.range = lps;
+ self.ctx[ctx_idx] = NEXT_STATE[s][1];
+ } else {
+ bin = (s & 1) as u32;
+ self.ctx[ctx_idx] = NEXT_STATE[s][0];
+ }
+ self.renorm();
+ bin
+ }
+
+ #[inline(always)]
+ pub fn decode_bypass(&mut self) -> u32 {
+ if self.bits == 0 {
+ self.refill();
+ }
+ self.bits -= 1;
+ let scaled = (self.range as u64) << self.bits;
+ if self.value >= scaled {
+ self.value -= scaled;
+ 1
+ } else {
+ 0
+ }
+ }
+
+ pub fn decode_terminate(&mut self) -> u32 {
+ self.range -= 2;
+ let scaled = (self.range as u64) << self.bits;
+ if self.value >= scaled {
+ 1
+ } else {
+ self.renorm();
+ 0
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Minimal CABAC encoder (9.3.4, informative) used to round-trip test the decoder.
+ struct Enc {
+ low: u32,
+ range: u32,
+ outstanding: u32,
+ first: bool,
+ bits: Vec<bool>,
+ ctx: Vec<u8>,
+ }
+ impl Enc {
+ fn new(ctx: &[u8]) -> Self {
+ Enc { low: 0, range: 510, outstanding: 0, first: true, bits: vec![], ctx: ctx.to_vec() }
+ }
+ fn put(&mut self, b: bool) {
+ if self.first {
+ self.first = false;
+ } else {
+ self.bits.push(b);
+ }
+ while self.outstanding > 0 {
+ self.bits.push(!b);
+ self.outstanding -= 1;
+ }
+ }
+ fn renorm(&mut self) {
+ while self.range < 256 {
+ if self.low < 256 {
+ self.put(false);
+ } else if self.low >= 512 {
+ self.low -= 512;
+ self.put(true);
+ } else {
+ self.low -= 256;
+ self.outstanding += 1;
+ }
+ self.range <<= 1;
+ self.low <<= 1;
+ }
+ }
+ fn encode(&mut self, ctx_idx: usize, bin: u32) {
+ let s = self.ctx[ctx_idx] as usize;
+ let p = s >> 1;
+ let mps = (s & 1) as u32;
+ let q = ((self.range >> 6) & 3) as usize;
+ let lps = RANGE_TAB_LPS[p][q] as u32;
+ self.range -= lps;
+ if bin != mps {
+ self.low += self.range;
+ self.range = lps;
+ self.ctx[ctx_idx] = NEXT_STATE[s][1];
+ } else {
+ self.ctx[ctx_idx] = NEXT_STATE[s][0];
+ }
+ self.renorm();
+ }
+ fn bypass(&mut self, bin: u32) {
+ self.low <<= 1;
+ if bin != 0 {
+ self.low += self.range;
+ }
+ if self.low >= 1024 {
+ self.put(true);
+ self.low -= 1024;
+ } else if self.low < 512 {
+ self.put(false);
+ } else {
+ self.low -= 512;
+ self.outstanding += 1;
+ }
+ }
+ fn terminate_flush(&mut self) -> Vec<u8> {
+ // encode terminate bin = 1 then flush (9.3.4.5)
+ self.range -= 2;
+ self.low += self.range;
+ self.range = 2;
+ self.renorm();
+ self.put((self.low >> 9) & 1 != 0);
+ self.bits.push((self.low >> 8) & 1 != 0);
+ self.bits.push(true); // rbsp_stop_one_bit
+ while !self.bits.len().is_multiple_of(8) {
+ self.bits.push(false);
+ }
+ self.bits.chunks(8).map(|c| c.iter().fold(0u8, |a, &b| (a << 1) | b as u8)).collect()
+ }
+ }
+
+ #[test]
+ fn context_init_formula() {
+ let mut ctx = [0u8; NUM_CTX];
+ // initValue 154 is the "equiprobable" value: m = 0, n = 64 -> pStateIdx 0, valMps 1
+ init_contexts(&mut ctx, 30, 0);
+ assert_eq!(ctx[crate::spec_tables::CU_TRANSQUANT_BYPASS], 1);
+ // split_cu_flag ctx 0 (initValue 139): slope 8, offset 11 -> m = -5, n = 72; QP 30: (-150 >> 4) + 72 = 62
+ assert_eq!(ctx[crate::spec_tables::SPLIT_CU], (63 - 62) << 1);
+ }
+
+ #[test]
+ fn round_trip_random_bins() {
+ let mut seed = 12345u32;
+ let mut rnd = || {
+ seed ^= seed << 13;
+ seed ^= seed >> 17;
+ seed ^= seed << 5;
+ seed
+ };
+ let dummy = Cabac::new(&[0, 0, 0, 0], 0, 30, 1).unwrap();
+ let mut enc = Enc::new(&dummy.ctx);
+ let mut ops = Vec::new();
+ for _ in 0..5000 {
+ let kind = rnd() % 4;
+ let ctx = (rnd() % 16) as usize;
+ // skewed bins so contexts adapt
+ let bin = if rnd() % 10 < 8 { (ctx & 1) as u32 } else { 1 - (ctx & 1) as u32 };
+ if kind == 0 {
+ enc.bypass(bin);
+ } else {
+ enc.encode(ctx, bin);
+ }
+ ops.push((kind, ctx, bin));
+ }
+ let bytes = enc.terminate_flush();
+ let mut dec = Cabac::new(&bytes, 0, 30, 1).unwrap();
+ for (i, &(kind, ctx, bin)) in ops.iter().enumerate() {
+ let got = if kind == 0 { dec.decode_bypass() } else { dec.decode_decision(ctx) };
+ assert_eq!(got, bin, "bin {i}");
+ }
+ assert_eq!(dec.decode_terminate(), 1);
+ }
+}
diff --git a/crates/hevc/src/decoder.rs b/crates/hevc/src/decoder.rs
new file mode 100644
index 000000000..37d71fb3d
--- /dev/null
+++ b/crates/hevc/src/decoder.rs
@@ -0,0 +1,568 @@
+//! Top-level decoder: NAL dispatch, picture boundaries, POC / RPS / DPB management and output.
+//!
+//! The calling thread parses parameter sets and slice headers and does all POC, RPS and DPB
+//! bookkeeping. The CTU layer of each picture runs as a job (on a thread pool with the `threads`
+//! feature) that publishes finished CTB rows into the picture's shared [`Frame`]; jobs of later pictures
+//! block per row on the reference data they read, so several pictures decode concurrently.
+
+use crate::dpb::{Dpb, Output, OutputMeta, PocState, RefPicSet, build_ref_lists};
+use crate::error::{Error, Result, ensure, invalid};
+use crate::params::{Layout, Pps, Sps, Vps};
+use crate::picture::{Frame, FrameRef};
+use crate::slice::{NalHeader, SliceHeader, nal_type};
+use crate::slicedec::{F_INTRA, F_SKIP, PicState, SliceDecoder, SliceJob};
+use crate::{ColorInfo, Picture, Plane};
+use filmcraft_bitstream::{annexb_nals, length_prefixed_nals, unescape_rbsp};
+use std::collections::VecDeque;
+use std::sync::{Arc, Mutex};
+
+/// A picture whose slices are being collected.
+struct PendingPic {
+ frame: FrameRef,
+ sps: Arc<Sps>,
+ pps: Arc<Pps>,
+ layout: Arc<Layout>,
+ /// Header of the latest independent slice segment (for dependent slice segments).
+ last_sh: SliceHeader,
+ first_sh: SliceHeader,
+ rps: RefPicSet,
+ poc: i32,
+ output: bool,
+ meta: Arc<OutputMeta>,
+ slices: Vec<SliceJob>,
+}
+
+/// Counters describing what the decoder has seen (useful to check test coverage).
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct DecodeStats {
+ pub pictures: u64,
+ pub slices_i: u64,
+ pub slices_p: u64,
+ pub slices_b: u64,
+ pub dependent_slices: u64,
+ pub idr: u64,
+ pub cra: u64,
+ pub skipped_rasl: u64,
+ pub intra_4x4_blocks: u64,
+ pub skip_4x4_blocks: u64,
+ pub inter_4x4_blocks: u64,
+ pub weighted_slices: u64,
+ pub tmvp_slices: u64,
+ pub sao_slices: u64,
+ pub deblock_disabled_slices: u64,
+ pub tiles_pictures: u64,
+ pub wpp_pictures: u64,
+ pub scaling_list_pictures: u64,
+ pub transform_skip_pictures: u64,
+ pub long_term_slices: u64,
+ pub missing_refs: u64,
+}
+
+#[derive(Default)]
+struct Shared {
+ error: Mutex<Option<Error>>,
+ stats: Mutex<DecodeStats>,
+}
+
+/// H.265 / HEVC decoder.
+pub struct Decoder {
+ vpss: Vec<Option<Arc<Vps>>>,
+ spss: Vec<Option<Arc<Sps>>>,
+ ppss: Vec<Option<Arc<Pps>>>,
+ nal_length_size: Option<usize>,
+ dpb: Dpb,
+ poc_state: PocState,
+ pending: Option<PendingPic>,
+ next_id: u32,
+ active_sps: Option<Arc<Sps>>,
+ first_picture: bool,
+ after_eos: bool,
+ /// RASL pictures associated with the last IRAP are skipped (it had NoRaslOutputFlag = 1).
+ skip_rasl: bool,
+ layout_cache: Vec<(Arc<Pps>, Arc<Sps>, Arc<Layout>, Option<Arc<Vec<Vec<u8>>>>)>,
+ out_queue: VecDeque<Output>,
+ shared: Arc<Shared>,
+ #[cfg(feature = "threads")]
+ pool: Option<rayon::ThreadPool>,
+ in_flight: VecDeque<FrameRef>,
+ max_in_flight: usize,
+}
+
+impl Default for Decoder {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+fn default_threads() -> usize {
+ #[cfg(all(feature = "threads", not(target_arch = "wasm32")))]
+ {
+ std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1).min(16)
+ }
+ #[cfg(not(all(feature = "threads", not(target_arch = "wasm32"))))]
+ {
+ 1
+ }
+}
+
+impl Decoder {
+ /// A decoder using all available cores (with the `threads` feature).
+ pub fn new() -> Self {
+ Self::with_threads(default_threads())
+ }
+
+ /// A decoder using up to `threads` worker threads (1 = decode on the calling thread).
+ pub fn with_threads(threads: usize) -> Self {
+ #[cfg(feature = "threads")]
+ let pool = if threads > 1 && cfg!(not(target_arch = "wasm32")) {
+ rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|i| format!("hevc-{i}")).build().ok()
+ } else {
+ None
+ };
+ Decoder {
+ vpss: vec![None; 16],
+ spss: vec![None; 16],
+ ppss: vec![None; 64],
+ nal_length_size: None,
+ dpb: Dpb::default(),
+ poc_state: PocState::default(),
+ pending: None,
+ next_id: 1,
+ active_sps: None,
+ first_picture: true,
+ after_eos: false,
+ skip_rasl: false,
+ layout_cache: Vec::new(),
+ out_queue: VecDeque::new(),
+ shared: Arc::new(Shared::default()),
+ #[cfg(feature = "threads")]
+ pool,
+ in_flight: VecDeque::new(),
+ max_in_flight: threads.max(1) + 2,
+ }
+ }
+
+ /// Configure from an `hvcC` (HEVCDecoderConfigurationRecord) box payload.
+ pub fn from_hvcc(hvcc: &[u8]) -> Result<Self> {
+ let mut d = Decoder::new();
+ d.configure_hvcc(hvcc)?;
+ Ok(d)
+ }
+
+ /// Parse an `hvcC` record: parameter-set arrays and the NAL length size used by [`Decoder::decode`].
+ pub fn configure_hvcc(&mut self, hvcc: &[u8]) -> Result<()> {
+ ensure!(hvcc.len() >= 23, "hvcC too short");
+ ensure!(hvcc[0] == 1, "unsupported hvcC version {}", hvcc[0]);
+ self.nal_length_size = Some((hvcc[21] & 3) as usize + 1);
+ let num_arrays = hvcc[22] as usize;
+ let mut pos = 23;
+ for _ in 0..num_arrays {
+ ensure!(pos + 3 <= hvcc.len(), "hvcC truncated");
+ let n = u16::from_be_bytes([hvcc[pos + 1], hvcc[pos + 2]]) as usize;
+ pos += 3;
+ for _ in 0..n {
+ ensure!(pos + 2 <= hvcc.len(), "hvcC truncated");
+ let len = u16::from_be_bytes([hvcc[pos], hvcc[pos + 1]]) as usize;
+ pos += 2;
+ ensure!(pos + len <= hvcc.len(), "hvcC truncated");
+ self.handle_nal(&hvcc[pos..pos + len], 0)?;
+ pos += len;
+ }
+ }
+ Ok(())
+ }
+
+ /// Length of NAL length prefixes (from hvcC), or None for Annex-B input.
+ pub fn nal_length_size(&self) -> Option<usize> {
+ self.nal_length_size
+ }
+
+ /// Decode one access unit (all NAL units of one picture, Annex-B or length-prefixed per
+ /// configuration; a byte stream with several complete access units is accepted too). Returns
+ /// pictures that became ready for output, in output order; `pts` travels with the picture of this
+ /// access unit through reordering.
+ pub fn decode(&mut self, data: &[u8], pts: i64) -> Result<Vec<Picture>> {
+ let nals = match self.nal_length_size {
+ Some(n) => length_prefixed_nals(data, n)?,
+ None => annexb_nals(data),
+ };
+ let mut result = Ok(());
+ for nal in nals {
+ if let Err(e) = self.handle_nal(nal, pts) {
+ result = Err(e);
+ break;
+ }
+ }
+ self.submit_pending();
+ if let Some(e) = self.take_error() {
+ result = result.and(Err(e));
+ }
+ result?;
+ let max_queue = self.max_in_flight * 2;
+ let mut pics = Vec::new();
+ while let Some(o) = self.out_queue.front() {
+ if !o.frame.is_complete() && self.out_queue.len() <= max_queue {
+ break;
+ }
+ let o = self.out_queue.pop_front().expect("front exists");
+ pics.push(make_picture(&o));
+ }
+ Ok(pics)
+ }
+
+ /// Output all remaining pictures (end of stream).
+ pub fn flush(&mut self) -> Vec<Picture> {
+ self.submit_pending();
+ let mut outs = Vec::new();
+ self.dpb.flush(&mut outs);
+ self.out_queue.extend(outs);
+ let pics = self.out_queue.drain(..).map(|o| make_picture(&o)).collect();
+ while let Some(f) = self.in_flight.pop_front() {
+ f.wait_complete();
+ }
+ self.first_picture = true;
+ pics
+ }
+
+ /// Statistics accumulated so far.
+ pub fn stats(&self) -> DecodeStats {
+ self.shared.stats.lock().map(|s| s.clone()).unwrap_or_default()
+ }
+
+ fn stat(&self, f: impl FnOnce(&mut DecodeStats)) {
+ if let Ok(mut s) = self.shared.stats.lock() {
+ f(&mut s);
+ }
+ }
+
+ /// First error reported by a decoding job since the last call (also returned by
+ /// [`Decoder::decode`]); useful after [`Decoder::flush`].
+ pub fn take_error(&mut self) -> Option<Error> {
+ self.shared.error.lock().ok().and_then(|mut e| e.take())
+ }
+
+ fn handle_nal(&mut self, nal: &[u8], pts: i64) -> Result<()> {
+ if nal.len() < 2 {
+ return Ok(());
+ }
+ let hdr = NalHeader::parse(nal)?;
+ if hdr.layer_id != 0 {
+ return Ok(());
+ }
+ match hdr.nal_type {
+ nal_type::VPS => {
+ let v = Vps::parse(&unescape_rbsp(&nal[2..]))?;
+ let id = v.id as usize;
+ self.vpss[id] = Some(Arc::new(v));
+ }
+ nal_type::SPS => {
+ let s = Sps::parse(&unescape_rbsp(&nal[2..]))?;
+ let id = s.id as usize;
+ self.spss[id] = Some(Arc::new(s));
+ }
+ nal_type::PPS => {
+ let p = Pps::parse(&unescape_rbsp(&nal[2..]))?;
+ let id = p.id as usize;
+ self.ppss[id] = Some(Arc::new(p));
+ }
+ nal_type::EOS | nal_type::EOB => {
+ self.submit_pending();
+ self.after_eos = true;
+ }
+ 0..=9 | 16..=21 => self.handle_slice(nal, hdr, pts)?,
+ // AUD, SEI, filler, reserved and unspecified NAL units are skipped
+ _ => {}
+ }
+ Ok(())
+ }
+
+ fn layout_for(&mut self, pps: &Arc<Pps>, sps: &Arc<Sps>) -> Result<(Arc<Layout>, Option<Arc<Vec<Vec<u8>>>>)> {
+ if let Some((_, _, l, s)) = self.layout_cache.iter().find(|(p, s, _, _)| Arc::ptr_eq(p, pps) && Arc::ptr_eq(s, sps)) {
+ return Ok((l.clone(), s.clone()));
+ }
+ let layout = Arc::new(Layout::new(sps, pps)?);
+ let scaling = if sps.scaling_list_enabled {
+ let list = pps.scaling_list.as_ref().or(sps.scaling_list.as_ref()).cloned().unwrap_or_else(crate::params::ScalingList::default_lists);
+ let mut v = Vec::with_capacity(24);
+ for size in 0..4 {
+ for m in 0..6 {
+ v.push(list.factor(size, m));
+ }
+ }
+ Some(Arc::new(v))
+ } else {
+ None
+ };
+ if self.layout_cache.len() > 8 {
+ self.layout_cache.remove(0);
+ }
+ self.layout_cache.push((pps.clone(), sps.clone(), layout.clone(), scaling.clone()));
+ Ok((layout, scaling))
+ }
+
+ fn handle_slice(&mut self, nal: &[u8], hdr: NalHeader, pts: i64) -> Result<()> {
+ let rbsp = unescape_rbsp(&nal[2..]);
+ // a first_slice_segment_in_pic_flag of 1 starts a new picture
+ let first = rbsp.first().is_some_and(|b| b & 0x80 != 0);
+ if first {
+ self.submit_pending();
+ }
+ if hdr.is_rasl() && (self.skip_rasl || self.first_picture) {
+ if first {
+ self.stat(|s| s.skipped_rasl += 1);
+ }
+ return Ok(());
+ }
+ let ppss = &self.ppss;
+ let spss = &self.spss;
+ let prev = self.pending.as_ref().map(|p| &p.last_sh);
+ let (sh, pps, sps) = SliceHeader::parse(
+ &rbsp,
+ hdr,
+ |id| {
+ let pps = ppss[id as usize].as_ref().ok_or_else(|| Error::MissingParameterSet(format!("PPS {id}")))?;
+ let sps = spss[pps.sps_id as usize].as_ref().ok_or_else(|| Error::MissingParameterSet(format!("SPS {}", pps.sps_id)))?;
+ Ok((pps.clone(), sps.clone()))
+ },
+ prev,
+ )?;
+ sps.check_supported()?;
+ pps.check_supported()?;
+ if first {
+ self.start_picture(&sh, &sps, &pps, pts)?;
+ } else {
+ let Some(p) = &self.pending else { return invalid("slice segment without the first slice of its picture") };
+ ensure!(Arc::ptr_eq(&p.pps, &pps), "PPS changed within a picture");
+ }
+ let pending = self.pending.as_mut().expect("picture started");
+ let refs = build_ref_lists(&sh, &pending.rps)?;
+ if !sh.dependent {
+ pending.last_sh = sh.clone();
+ }
+ let (st, dependent, weighted, tmvp, sao, dbk_off, lt) =
+ (sh.slice_type, sh.dependent, sh.pwt.is_some(), sh.temporal_mvp, sh.sao_luma || sh.sao_chroma, sh.deblocking_disabled, !sh.lt.is_empty());
+ pending.slices.push(SliceJob { sh, pps, sps, rbsp, refs });
+ self.stat(|s| {
+ match st {
+ crate::slice::SliceType::I => s.slices_i += 1,
+ crate::slice::SliceType::P => s.slices_p += 1,
+ crate::slice::SliceType::B => s.slices_b += 1,
+ }
+ s.dependent_slices += dependent as u64;
+ s.weighted_slices += weighted as u64;
+ s.tmvp_slices += tmvp as u64;
+ s.sao_slices += sao as u64;
+ s.deblock_disabled_slices += dbk_off as u64;
+ s.long_term_slices += lt as u64;
+ });
+ Ok(())
+ }
+
+ fn start_picture(&mut self, sh: &SliceHeader, sps: &Arc<Sps>, pps: &Arc<Pps>, pts: i64) -> Result<()> {
+ ensure!(sh.first_slice_segment_in_pic && !sh.dependent, "invalid first slice segment");
+ let hdr = sh.nal;
+ let changed = match &self.active_sps {
+ None => true,
+ Some(a) => {
+ a.width != sps.width
+ || a.height != sps.height
+ || a.bit_depth_luma != sps.bit_depth_luma
+ || a.bit_depth_chroma != sps.bit_depth_chroma
+ || a.log2_ctb != sps.log2_ctb
+ }
+ };
+ let mut outs = Vec::new();
+ if changed && self.active_sps.is_some() {
+ self.dpb.flush(&mut outs);
+ }
+ self.active_sps = Some(sps.clone());
+ self.dpb.max_dec_pic_buffering = sps.max_dec_pic_buffering as usize;
+ self.dpb.max_num_reorder = sps.max_num_reorder as usize;
+ self.dpb.max_latency = if sps.max_latency_increase_plus1 != 0 { sps.max_num_reorder + sps.max_latency_increase_plus1 - 1 } else { 0 };
+ let irap_no_rasl = hdr.is_irap() && (hdr.is_idr() || hdr.is_bla() || self.first_picture || self.after_eos);
+ if hdr.is_irap() {
+ self.skip_rasl = irap_no_rasl;
+ self.stat(|s| {
+ if hdr.is_idr() {
+ s.idr += 1;
+ } else {
+ s.cra += 1;
+ }
+ });
+ }
+ let max_lsb = sps.max_poc_lsb();
+ let poc = self.poc_state.compute(sh, max_lsb, irap_no_rasl);
+ let (w, h) = (sps.width as usize, sps.height as usize);
+ let template = Frame::new(0, 0, w, h, sps.log2_ctb, sps.bit_depth_luma, sps.bit_depth_chroma);
+ let next_id = &mut self.next_id;
+ let mut missing = 0u64;
+ let mut make_missing = |p: i32| -> FrameRef {
+ missing += 1;
+ let id = *next_id;
+ *next_id += 1;
+ Arc::new(Frame::gray(id, p, &template))
+ };
+ let rps = self.dpb.apply_rps(sh, poc, max_lsb, irap_no_rasl, &mut make_missing)?;
+ if missing > 0 {
+ self.stat(|s| s.missing_refs += missing);
+ }
+ if irap_no_rasl && !self.first_picture {
+ if sh.no_output_of_prior_pics && hdr.is_idr() {
+ self.dpb.clear();
+ } else {
+ self.dpb.flush(&mut outs);
+ }
+ } else {
+ self.dpb.bump_before_decode(&mut outs);
+ }
+ self.out_queue.extend(outs);
+ let (layout, scaling) = self.layout_for(pps, sps)?;
+ let _ = scaling;
+ let id = self.next_id;
+ self.next_id += 1;
+ let frame = Arc::new(Frame::new(id, poc, w, h, sps.log2_ctb, sps.bit_depth_luma, sps.bit_depth_chroma));
+ let output = sh.pic_output && !(hdr.is_rasl() && self.skip_rasl);
+ let meta = Arc::new(output_meta(sps, pts, hdr.is_irap()));
+ self.pending = Some(PendingPic {
+ frame,
+ sps: sps.clone(),
+ pps: pps.clone(),
+ layout,
+ last_sh: sh.clone(),
+ first_sh: sh.clone(),
+ rps,
+ poc,
+ output,
+ meta,
+ slices: Vec::new(),
+ });
+ self.first_picture = false;
+ self.after_eos = false;
+ self.stat(|s| {
+ s.tiles_pictures += pps.tiles_enabled as u64;
+ s.wpp_pictures += pps.entropy_coding_sync as u64;
+ s.scaling_list_pictures += sps.scaling_list_enabled as u64;
+ s.transform_skip_pictures += pps.transform_skip as u64;
+ });
+ Ok(())
+ }
+
+ /// Start decoding the pending picture and insert it into the DPB.
+ fn submit_pending(&mut self) {
+ let Some(p) = self.pending.take() else { return };
+ let PendingPic { frame, sps, pps, layout, first_sh, poc, output, meta, slices, .. } = p;
+ let scaling = self.layout_cache.iter().find(|(pp, ss, _, _)| Arc::ptr_eq(pp, &pps) && Arc::ptr_eq(ss, &sps)).and_then(|(_, _, _, s)| s.clone());
+ self.dispatch(frame.clone(), sps, pps, layout, scaling, slices);
+ self.poc_state.update(&first_sh, poc);
+ let mut outs = Vec::new();
+ self.dpb.insert(frame, poc, output, meta, &mut outs);
+ self.out_queue.extend(outs);
+ }
+
+ fn dispatch(&mut self, frame: FrameRef, sps: Arc<Sps>, pps: Arc<Pps>, layout: Arc<Layout>, scaling: Option<Arc<Vec<Vec<u8>>>>, slices: Vec<SliceJob>) {
+ let shared = self.shared.clone();
+ #[cfg(feature = "threads")]
+ if let Some(pool) = &self.pool {
+ self.in_flight.retain(|f| !f.is_complete());
+ while self.in_flight.len() >= self.max_in_flight {
+ if let Some(f) = self.in_flight.pop_front() {
+ f.wait_complete();
+ }
+ }
+ self.in_flight.push_back(frame.clone());
+ pool.spawn_fifo(move || run_job(frame, sps, pps, layout, scaling, slices, &shared));
+ return;
+ }
+ run_job(frame, sps, pps, layout, scaling, slices, &shared);
+ }
+}
+
+/// Decode all slices of one picture and publish its rows.
+fn run_job(frame: FrameRef, sps: Arc<Sps>, pps: Arc<Pps>, layout: Arc<Layout>, scaling: Option<Arc<Vec<Vec<u8>>>>, slices: Vec<SliceJob>, shared: &Shared) {
+ let mut pic = PicState::new(frame.clone(), sps, pps, layout, scaling);
+ let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ let mut first_err = None;
+ for s in &slices {
+ if let Err(e) = SliceDecoder::decode(&mut pic, s) {
+ first_err.get_or_insert(e);
+ }
+ }
+ crate::filter::finish(&mut pic);
+ first_err
+ }));
+ let err = match result {
+ Ok(e) => e,
+ Err(_) => {
+ // make sure readers never block on this frame
+ let gray = Frame::gray(0, frame.poc, &frame);
+ for r in 0..frame.num_rows() {
+ if !frame.is_published(r) {
+ let row = gray.row(r);
+ frame.publish(r, crate::picture::FrameRow { y: row.y.clone(), cb: row.cb.clone(), cr: row.cr.clone(), col: row.col.clone() });
+ }
+ }
+ Some(Error::Invalid("internal error while decoding a picture".into()))
+ }
+ };
+ if let Ok(mut s) = shared.stats.lock() {
+ s.pictures += 1;
+ for b in &pic.blk {
+ if b.flags & F_INTRA != 0 {
+ s.intra_4x4_blocks += 1;
+ } else if b.flags & F_SKIP != 0 {
+ s.skip_4x4_blocks += 1;
+ } else if b.flags != 0 {
+ s.inter_4x4_blocks += 1;
+ }
+ }
+ }
+ if let (Some(e), Ok(mut slot)) = (err, shared.error.lock()) {
+ slot.get_or_insert(e);
+ }
+}
+
+fn output_meta(sps: &Sps, pts: i64, key: bool) -> OutputMeta {
+ let vui = sps.vui.clone().unwrap_or_default();
+ OutputMeta {
+ pts,
+ key,
+ crop: sps.crop_rect(),
+ full_range: vui.full_range,
+ colour_primaries: vui.colour_primaries,
+ transfer_characteristics: vui.transfer_characteristics,
+ matrix_coefficients: vui.matrix_coefficients,
+ sar: vui.sar,
+ bit_depth: sps.bit_depth_luma,
+ }
+}
+
+fn make_picture(o: &Output) -> Picture {
+ let (cx, cy, cw, ch) = o.meta.crop;
+ let (cx, cy, cw, ch) = (cx as usize, cy as usize, cw as usize, ch as usize);
+ let (y, u, v) = o.frame.copy_cropped((cx, cy, cw, ch));
+ let (ccw, cch) = (cw.div_ceil(2), ch.div_ceil(2));
+ let bd = o.meta.bit_depth;
+ let conv = |p: Vec<u16>| if bd <= 8 { Plane::U8(p.into_iter().map(|v| v as u8).collect()) } else { Plane::U16(p) };
+ Picture {
+ width: cw as u32,
+ height: ch as u32,
+ chroma_width: ccw as u32,
+ chroma_height: cch as u32,
+ bit_depth: bd,
+ y: conv(y),
+ u: conv(u),
+ v: conv(v),
+ y_stride: cw,
+ uv_stride: ccw,
+ pts: o.meta.pts,
+ poc: o.poc,
+ key: o.meta.key,
+ color: ColorInfo {
+ full_range: o.meta.full_range,
+ primaries: o.meta.colour_primaries,
+ transfer: o.meta.transfer_characteristics,
+ matrix: o.meta.matrix_coefficients,
+ },
+ sar: o.meta.sar,
+ }
+}
diff --git a/crates/hevc/src/dpb.rs b/crates/hevc/src/dpb.rs
new file mode 100644
index 000000000..40448ecf7
--- /dev/null
+++ b/crates/hevc/src/dpb.rs
@@ -0,0 +1,290 @@
+//! Decoded picture buffer: POC derivation (8.3.1), reference picture set (8.3.2), missing
+//! reference generation (8.3.3), reference picture lists (8.3.4) and output / bumping (C.5.2).
+
+use crate::error::{Result, ensure};
+use crate::picture::{FrameRef, RefPic};
+use crate::slice::SliceHeader;
+use std::sync::Arc;
+
+/// Output metadata travelling with a picture.
+#[derive(Clone, Debug)]
+pub struct OutputMeta {
+ pub pts: i64,
+ pub key: bool,
+ pub crop: (u32, u32, u32, u32),
+ pub full_range: bool,
+ pub colour_primaries: u8,
+ pub transfer_characteristics: u8,
+ pub matrix_coefficients: u8,
+ pub sar: (u16, u16),
+ pub bit_depth: u32,
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum Marking {
+ Unused,
+ Short,
+ Long,
+}
+
+pub struct Entry {
+ pub frame: FrameRef,
+ pub poc: i32,
+ pub marking: Marking,
+ pub needed_for_output: bool,
+ pub latency: u32,
+ pub meta: Arc<OutputMeta>,
+}
+
+/// A picture leaving the DPB for output.
+pub struct Output {
+ pub frame: FrameRef,
+ pub poc: i32,
+ pub meta: Arc<OutputMeta>,
+}
+
+/// Reference picture set of the current picture (8.3.2) as DPB indices / generated frames.
+#[derive(Default)]
+pub struct RefPicSet {
+ pub st_curr_before: Vec<RefPic>,
+ pub st_curr_after: Vec<RefPic>,
+ pub lt_curr: Vec<RefPic>,
+}
+
+#[derive(Default)]
+pub struct Dpb {
+ pub entries: Vec<Entry>,
+ pub max_dec_pic_buffering: usize,
+ pub max_num_reorder: usize,
+ /// SpsMaxLatencyPictures (0 = no limit).
+ pub max_latency: u32,
+}
+
+impl Dpb {
+ fn bump(&mut self, outs: &mut Vec<Output>) -> bool {
+ let Some(i) = (0..self.entries.len()).filter(|&i| self.entries[i].needed_for_output).min_by_key(|&i| self.entries[i].poc) else { return false };
+ let e = &mut self.entries[i];
+ e.needed_for_output = false;
+ outs.push(Output { frame: e.frame.clone(), poc: e.poc, meta: e.meta.clone() });
+ self.remove_unused();
+ true
+ }
+
+ fn remove_unused(&mut self) {
+ self.entries.retain(|e| e.needed_for_output || e.marking != Marking::Unused);
+ }
+
+ fn num_output(&self) -> usize {
+ self.entries.iter().filter(|e| e.needed_for_output).count()
+ }
+
+ fn latency_exceeded(&self) -> bool {
+ self.max_latency != 0 && self.entries.iter().any(|e| e.needed_for_output && e.latency >= self.max_latency)
+ }
+
+ /// Output everything (end of stream or IRAP without no_output_of_prior_pics).
+ pub fn flush(&mut self, outs: &mut Vec<Output>) {
+ while self.bump(outs) {}
+ for e in &mut self.entries {
+ e.marking = Marking::Unused;
+ }
+ self.entries.clear();
+ }
+
+ /// Discard everything without output.
+ pub fn clear(&mut self) {
+ self.entries.clear();
+ }
+
+ /// C.5.2.2: removal of pictures before decoding the current (non-IRAP-reset) picture, after the RPS
+ /// has been applied.
+ pub fn bump_before_decode(&mut self, outs: &mut Vec<Output>) {
+ self.remove_unused();
+ loop {
+ let full = self.entries.len() >= self.max_dec_pic_buffering.max(1);
+ if self.num_output() > self.max_num_reorder || self.latency_exceeded() || full {
+ if !self.bump(outs) {
+ // DPB full of reference pictures that are not needed for output: nothing to do
+ break;
+ }
+ } else {
+ break;
+ }
+ }
+ }
+
+ /// C.5.2.3: insert the current picture and apply "additional bumping".
+ pub fn insert(&mut self, frame: FrameRef, poc: i32, output: bool, meta: Arc<OutputMeta>, outs: &mut Vec<Output>) {
+ for e in &mut self.entries {
+ if e.needed_for_output {
+ e.latency += 1;
+ }
+ }
+ self.entries.push(Entry { frame, poc, marking: Marking::Short, needed_for_output: output, latency: 0, meta });
+ while self.num_output() > self.max_num_reorder || self.latency_exceeded() {
+ if !self.bump(outs) {
+ break;
+ }
+ }
+ }
+
+ /// Apply the RPS of the current picture (8.3.2): mark pictures, find (or generate) references.
+ /// `make_missing` creates a replacement frame for a missing reference picture with the given POC.
+ pub fn apply_rps(
+ &mut self,
+ sh: &SliceHeader,
+ poc: i32,
+ max_poc_lsb: i32,
+ irap_no_rasl: bool,
+ make_missing: &mut dyn FnMut(i32) -> FrameRef,
+ ) -> Result<RefPicSet> {
+ let mut set = RefPicSet::default();
+ if sh.nal.is_irap() && irap_no_rasl {
+ for e in &mut self.entries {
+ e.marking = Marking::Unused;
+ }
+ }
+ if sh.nal.is_idr() {
+ for e in &mut self.entries {
+ e.marking = Marking::Unused;
+ }
+ return Ok(set);
+ }
+ // Long-term entries first (they may refer to any reference picture).
+ let mut keep = vec![false; self.entries.len()];
+ let mut lt_idx: Vec<(Option<usize>, i32, bool, bool)> = Vec::new(); // (entry, poc, used, msb_present)
+ for &(lsb, used, msb_present, cycle) in &sh.lt {
+ let mut p = lsb as i32;
+ if msb_present {
+ p += poc - (cycle as i32).wrapping_mul(max_poc_lsb) - (poc & (max_poc_lsb - 1));
+ }
+ let found =
+ self.entries.iter().position(|e| e.marking != Marking::Unused && if msb_present { e.poc == p } else { (e.poc & (max_poc_lsb - 1)) == p });
+ lt_idx.push((found, p, used, msb_present));
+ }
+ // Short-term entries.
+ let mut st: Vec<(Option<usize>, i32, bool, bool)> = Vec::new(); // (entry, poc, used, before)
+ for &(d, used) in &sh.st_rps.s0 {
+ let p = poc + d;
+ let found = self.entries.iter().position(|e| e.marking == Marking::Short && e.poc == p);
+ st.push((found, p, used, true));
+ }
+ for &(d, used) in &sh.st_rps.s1 {
+ let p = poc + d;
+ let found = self.entries.iter().position(|e| e.marking == Marking::Short && e.poc == p);
+ st.push((found, p, used, false));
+ }
+ for &(f, _, _, _) in lt_idx.iter() {
+ if let Some(i) = f {
+ keep[i] = true;
+ }
+ }
+ for &(f, _, _, _) in st.iter() {
+ if let Some(i) = f {
+ keep[i] = true;
+ }
+ }
+ for (i, e) in self.entries.iter_mut().enumerate() {
+ if !keep[i] {
+ e.marking = Marking::Unused;
+ }
+ }
+ for &(f, _, _, _) in &lt_idx {
+ if let Some(i) = f {
+ self.entries[i].marking = Marking::Long;
+ }
+ }
+ let mut make = |found: Option<usize>, p: i32, lt: bool, entries: &mut Vec<Entry>| -> RefPic {
+ match found {
+ Some(i) => RefPic { frame: entries[i].frame.clone(), poc: entries[i].poc, long_term: lt },
+ None => {
+ // 8.3.3: generate an unavailable reference picture
+ let frame = make_missing(p);
+ RefPic { frame, poc: p, long_term: lt }
+ }
+ }
+ };
+ for &(f, p, used, before) in &st {
+ if !used {
+ continue;
+ }
+ let r = make(f, p, false, &mut self.entries);
+ if before {
+ set.st_curr_before.push(r);
+ } else {
+ set.st_curr_after.push(r);
+ }
+ }
+ for &(f, p, used, _) in &lt_idx {
+ if used {
+ let r = make(f, p, true, &mut self.entries);
+ set.lt_curr.push(r);
+ }
+ }
+ Ok(set)
+ }
+}
+
+/// Build RefPicList0/1 (8.3.4).
+pub fn build_ref_lists(sh: &SliceHeader, rps: &RefPicSet) -> Result<[Vec<RefPic>; 2]> {
+ let mut lists: [Vec<RefPic>; 2] = [Vec::new(), Vec::new()];
+ if sh.is_intra() {
+ return Ok(lists);
+ }
+ let total = rps.st_curr_before.len() + rps.st_curr_after.len() + rps.lt_curr.len();
+ ensure!(total > 0, "no reference pictures for an inter slice");
+ for l in 0..if sh.is_b() { 2 } else { 1 } {
+ let n = (sh.num_ref_idx[l] as usize).max(total);
+ let mut temp = Vec::with_capacity(n);
+ let (first, second) = if l == 0 { (&rps.st_curr_before, &rps.st_curr_after) } else { (&rps.st_curr_after, &rps.st_curr_before) };
+ while temp.len() < n {
+ for r in first.iter().chain(second.iter()).chain(rps.lt_curr.iter()) {
+ if temp.len() < n {
+ temp.push(r.clone());
+ }
+ }
+ }
+ for i in 0..sh.num_ref_idx[l] as usize {
+ let idx = match &sh.list_entry[l] {
+ Some(e) => e[i] as usize,
+ None => i,
+ };
+ ensure!(idx < temp.len(), "list_entry out of range");
+ lists[l].push(temp[idx].clone());
+ }
+ }
+ Ok(lists)
+}
+
+/// POC state (8.3.1).
+#[derive(Default, Clone, Copy)]
+pub struct PocState {
+ pub prev_tid0_poc: i32,
+}
+
+impl PocState {
+ pub fn compute(&self, sh: &SliceHeader, max_poc_lsb: i32, irap_no_rasl: bool) -> i32 {
+ let lsb = sh.poc_lsb as i32;
+ let msb = if sh.nal.is_irap() && irap_no_rasl {
+ 0
+ } else {
+ let prev_lsb = self.prev_tid0_poc & (max_poc_lsb - 1);
+ let prev_msb = self.prev_tid0_poc - prev_lsb;
+ if lsb < prev_lsb && prev_lsb - lsb >= max_poc_lsb / 2 {
+ prev_msb + max_poc_lsb
+ } else if lsb > prev_lsb && lsb - prev_lsb > max_poc_lsb / 2 {
+ prev_msb - max_poc_lsb
+ } else {
+ prev_msb
+ }
+ };
+ msb + lsb
+ }
+
+ /// Update after decoding a picture with the given header and POC.
+ pub fn update(&mut self, sh: &SliceHeader, poc: i32) {
+ if sh.nal.temporal_id == 0 && !sh.nal.is_rasl() && !sh.nal.is_radl() && !sh.nal.is_sub_layer_non_ref() {
+ self.prev_tid0_poc = poc;
+ }
+ }
+}
diff --git a/crates/hevc/src/error.rs b/crates/hevc/src/error.rs
new file mode 100644
index 000000000..32f1d89db
--- /dev/null
+++ b/crates/hevc/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/hevc/src/filter.rs b/crates/hevc/src/filter.rs
new file mode 100644
index 000000000..6cc55ed10
--- /dev/null
+++ b/crates/hevc/src/filter.rs
@@ -0,0 +1,505 @@
+//! In-loop filters and row publication: deblocking (8.7.2) and sample adaptive offset (8.7.3), run
+//! row by row behind the CTU decoding so finished CTB rows can be published to later pictures early.
+//!
+//! Row r is deblocked once rows 0..=r+1 are decoded (row r+1 still needs the unfiltered bottom samples
+//! of row r for intra prediction); SAO of row r runs once row r+1 is deblocked; then row r is final.
+
+use crate::picture::{ColMv, FrameRow};
+use crate::slicedec::{E_PU_H, E_PU_V, E_TU_H, E_TU_V, F_CBF, F_CODED, F_INTRA, F_NOFILTER, MvField, PicState};
+use crate::spec_tables::{BETA_TABLE, TC_TABLE};
+use crate::tables::qpc_420;
+
+/// Called after each decoded CTB of CTB row `ry`.
+pub fn ctb_decoded(pic: &mut PicState, ry: usize) {
+ pic.row_done[ry] += 1;
+ while pic.rows_complete < pic.hctb && pic.row_done[pic.rows_complete] as usize == pic.wctb {
+ pic.rows_complete += 1;
+ }
+ advance(pic, false);
+}
+
+/// Run the filters / publication as far as the decoded rows allow (`all`: end of picture).
+pub fn advance(pic: &mut PicState, all: bool) {
+ let h = pic.hctb;
+ loop {
+ let r = pic.rows_deblocked;
+ if r < h && (all || pic.rows_complete >= (r + 2).min(h)) {
+ deblock_row(pic, r);
+ pic.rows_deblocked += 1;
+ continue;
+ }
+ let r = pic.rows_published;
+ if r < h && pic.rows_deblocked >= (r + 2).min(h) {
+ publish_row(pic, r);
+ pic.rows_published += 1;
+ continue;
+ }
+ break;
+ }
+}
+
+/// End of picture: filter and publish everything.
+pub fn finish(pic: &mut PicState) {
+ pic.rows_complete = pic.hctb;
+ advance(pic, true);
+}
+
+#[inline]
+fn tc_beta(q: i32, bs: i32, tc_off: i32, beta_off: i32, bd: u32) -> (i32, i32) {
+ let qb = (q + beta_off).clamp(0, 51);
+ let qt = (q + 2 * (bs - 1) + tc_off).clamp(0, 53);
+ ((TC_TABLE[qt as usize] as i32) << (bd - 8), (BETA_TABLE[qb as usize] as i32) << (bd - 8))
+}
+
+/// Boundary strength (8.7.2.4) between 4x4 blocks p and q.
+fn boundary_strength(pic: &PicState, pi: usize, qi: usize, tu_edge: bool) -> i32 {
+ let (p, q) = (&pic.blk[pi], &pic.blk[qi]);
+ if (p.flags | q.flags) & F_INTRA != 0 {
+ return 2;
+ }
+ if tu_edge && (p.flags | q.flags) & F_CBF != 0 {
+ return 1;
+ }
+ let (mp, mq) = (&pic.mvf[pi], &pic.mvf[qi]);
+ motion_bs(pic, pi, mp, qi, mq)
+}
+
+fn ref_id(pic: &PicState, blk: usize, f: &MvField, l: usize) -> u32 {
+ let (x, y) = ((blk % pic.w4) * 4, (blk / pic.w4) * 4);
+ let ctb = (y >> pic.log2_ctb) * pic.wctb + (x >> pic.log2_ctb);
+ let s = pic.ctb_slice[ctb];
+ if s == u32::MAX {
+ return u32::MAX;
+ }
+ pic.slices[s as usize].ref_ids[l].get(f.ref_idx[l] as usize).copied().unwrap_or(u32::MAX - 1)
+}
+
+fn motion_bs(pic: &PicState, pi: usize, p: &MvField, qi: usize, q: &MvField) -> i32 {
+ let np = p.pred(0) as u32 + p.pred(1) as u32;
+ let nq = q.pred(0) as u32 + q.pred(1) as u32;
+ if np != nq {
+ return 1;
+ }
+ let far = |a: [i16; 2], b: [i16; 2]| (a[0] as i32 - b[0] as i32).abs() >= 4 || (a[1] as i32 - b[1] as i32).abs() >= 4;
+ if np == 1 {
+ let lp = if p.pred(0) { 0 } else { 1 };
+ let lq = if q.pred(0) { 0 } else { 1 };
+ if ref_id(pic, pi, p, lp) != ref_id(pic, qi, q, lq) {
+ return 1;
+ }
+ return far(p.mv[lp], q.mv[lq]) as i32;
+ }
+ let (p0, p1) = (ref_id(pic, pi, p, 0), ref_id(pic, pi, p, 1));
+ let (q0, q1) = (ref_id(pic, qi, q, 0), ref_id(pic, qi, q, 1));
+ if !((p0 == q0 && p1 == q1) || (p0 == q1 && p1 == q0)) {
+ return 1;
+ }
+ if p0 != p1 {
+ if p0 == q0 { (far(p.mv[0], q.mv[0]) || far(p.mv[1], q.mv[1])) as i32 } else { (far(p.mv[0], q.mv[1]) || far(p.mv[1], q.mv[0])) as i32 }
+ } else {
+ ((far(p.mv[0], q.mv[0]) || far(p.mv[1], q.mv[1])) && (far(p.mv[0], q.mv[1]) || far(p.mv[1], q.mv[0]))) as i32
+ }
+}
+
+/// Whether the edge between blocks p and q (q = current block, owning the edge) is filtered, and the
+/// slice-level parameters (tc offset, beta offset) of q's slice.
+fn edge_params(pic: &PicState, px: usize, py: usize, qx: usize, qy: usize) -> Option<(i32, i32)> {
+ let s = pic.log2_ctb;
+ let pc = (py >> s) * pic.wctb + (px >> s);
+ let qc = (qy >> s) * pic.wctb + (qx >> s);
+ let qs = pic.ctb_slice[qc];
+ let ps = pic.ctb_slice[pc];
+ if qs == u32::MAX || ps == u32::MAX {
+ return None;
+ }
+ let sq = &pic.slices[qs as usize];
+ if sq.deblock_disabled {
+ return None;
+ }
+ if pc != qc {
+ if pic.ctb_addr[pc] != pic.ctb_addr[qc] && !sq.lf_across {
+ return None;
+ }
+ if !pic.pps.loop_filter_across_tiles && pic.layout.tile_of_rs(pc as u32) != pic.layout.tile_of_rs(qc as u32) {
+ return None;
+ }
+ }
+ Some((sq.tc_offset, sq.beta_offset))
+}
+
+/// Deblock CTB row `r`: vertical edges of the row, then horizontal edges whose q side is in the row.
+fn deblock_row(pic: &mut PicState, r: usize) {
+ if !pic.deblocking_enabled_anywhere {
+ return;
+ }
+ let ctb = 1usize << pic.log2_ctb;
+ let y0 = r * ctb;
+ let y1 = (y0 + ctb).min(pic.height);
+ let (w, w4) = (pic.width, pic.w4);
+ let (bd, bdc) = (pic.bd_y, pic.bd_c);
+ let (cb_off, cr_off) = (pic.pps.cb_qp_offset, pic.pps.cr_qp_offset);
+ // vertical edges
+ let mut bs_v = vec![0i8; w4 * ((y1 - y0) / 4)];
+ for by in y0 / 4..y1 / 4 {
+ for bx in (2..w4).step_by(2) {
+ let qi = by * w4 + bx;
+ let e = pic.blk[qi].edges;
+ if e & (E_TU_V | E_PU_V) == 0 || pic.blk[qi].flags & F_CODED == 0 {
+ continue;
+ }
+ let (x, y) = (bx * 4, by * 4);
+ let Some((tc_off, beta_off)) = edge_params(pic, x - 1, y, x, y) else { continue };
+ let bs = boundary_strength(pic, qi - 1, qi, e & E_TU_V != 0);
+ bs_v[(by - y0 / 4) * w4 + bx] = bs as i8;
+ if bs == 0 {
+ continue;
+ }
+ let (p, q) = (&pic.blk[qi - 1], &pic.blk[qi]);
+ let qpl = (p.qp as i32 + q.qp as i32 + 1) >> 1;
+ let (tc, beta) = tc_beta(qpl, bs, tc_off, beta_off, bd);
+ let (nfp, nfq) = (p.flags & F_NOFILTER != 0, q.flags & F_NOFILTER != 0);
+ filter_luma(&mut pic.planes[0], y * w + x, 1, w, tc, beta, nfp, nfq, bd);
+ }
+ }
+ // chroma vertical edges (8x8 chroma grid = 16 luma samples), bS == 2 only
+ let cw = pic.cwidth;
+ for by in (y0 / 4..y1 / 4).step_by(2) {
+ for bx in (4..w4).step_by(4) {
+ if bs_v[(by - y0 / 4) * w4 + bx] != 2 {
+ continue;
+ }
+ let (x, y) = (bx * 4, by * 4);
+ let qi = by * w4 + bx;
+ let Some((tc_off, _)) = edge_params(pic, x - 1, y, x, y) else { continue };
+ let (p, q) = (pic.blk[qi - 1], pic.blk[qi]);
+ let (nfp, nfq) = (p.flags & F_NOFILTER != 0, q.flags & F_NOFILTER != 0);
+ for (c, off) in [(1, cb_off), (2, cr_off)] {
+ let qpi = ((p.qp as i32 + q.qp as i32 + 1) >> 1) + off;
+ let qt = (qpc_420(qpi) + 2 + tc_off).clamp(0, 53);
+ let tc = (TC_TABLE[qt as usize] as i32) << (bdc - 8);
+ filter_chroma(&mut pic.planes[c], (y / 2) * cw + x / 2, 1, cw, tc, nfp, nfq, bdc);
+ }
+ }
+ }
+ // horizontal edges with the q side in this row
+ let mut bs_h = vec![0i8; w4 * ((y1 - y0) / 4)];
+ for by in (y0 / 4..y1 / 4).filter(|b| b % 2 == 0 && *b > 0) {
+ for bx in 0..w4 {
+ let qi = by * w4 + bx;
+ let e = pic.blk[qi].edges;
+ if e & (E_TU_H | E_PU_H) == 0 || pic.blk[qi].flags & F_CODED == 0 {
+ continue;
+ }
+ let (x, y) = (bx * 4, by * 4);
+ let Some((tc_off, beta_off)) = edge_params(pic, x, y - 1, x, y) else { continue };
+ let pi = qi - w4;
+ let bs = boundary_strength(pic, pi, qi, e & E_TU_H != 0);
+ bs_h[(by - y0 / 4) * w4 + bx] = bs as i8;
+ if bs == 0 {
+ continue;
+ }
+ let (p, q) = (&pic.blk[pi], &pic.blk[qi]);
+ let qpl = (p.qp as i32 + q.qp as i32 + 1) >> 1;
+ let (tc, beta) = tc_beta(qpl, bs, tc_off, beta_off, bd);
+ let (nfp, nfq) = (p.flags & F_NOFILTER != 0, q.flags & F_NOFILTER != 0);
+ filter_luma(&mut pic.planes[0], y * w + x, w, 1, tc, beta, nfp, nfq, bd);
+ }
+ }
+ for by in (y0 / 4..y1 / 4).filter(|b| b % 4 == 0 && *b > 0) {
+ for bx in (0..w4).step_by(2) {
+ if bs_h[(by - y0 / 4) * w4 + bx] != 2 {
+ continue;
+ }
+ let (x, y) = (bx * 4, by * 4);
+ let qi = by * w4 + bx;
+ let Some((tc_off, _)) = edge_params(pic, x, y - 1, x, y) else { continue };
+ let (p, q) = (pic.blk[qi - w4], pic.blk[qi]);
+ let (nfp, nfq) = (p.flags & F_NOFILTER != 0, q.flags & F_NOFILTER != 0);
+ for (c, off) in [(1, cb_off), (2, cr_off)] {
+ let qpi = ((p.qp as i32 + q.qp as i32 + 1) >> 1) + off;
+ let qt = (qpc_420(qpi) + 2 + tc_off).clamp(0, 53);
+ let tc = (TC_TABLE[qt as usize] as i32) << (bdc - 8);
+ filter_chroma(&mut pic.planes[c], (y / 2) * cw + x / 2, cw, 1, tc, nfp, nfq, bdc);
+ }
+ }
+ }
+}
+
+/// Filter one 4-sample luma edge segment. `o` = offset of q0 of the first line, `step` = distance
+/// between p/q samples across the edge, `along` = distance between lines.
+#[allow(clippy::too_many_arguments)]
+fn filter_luma(s: &mut [u16], o: usize, step: usize, along: usize, tc: i32, beta: i32, nfp: bool, nfq: bool, bd: u32) {
+ let px = |s: &[u16], k: usize, i: usize| s[o + k * along - (i + 1) * step] as i32;
+ let qx = |s: &[u16], k: usize, i: usize| s[o + k * along + i * step] as i32;
+ let dp0 = (px(s, 0, 2) - 2 * px(s, 0, 1) + px(s, 0, 0)).abs();
+ let dp3 = (px(s, 3, 2) - 2 * px(s, 3, 1) + px(s, 3, 0)).abs();
+ let dq0 = (qx(s, 0, 2) - 2 * qx(s, 0, 1) + qx(s, 0, 0)).abs();
+ let dq3 = (qx(s, 3, 2) - 2 * qx(s, 3, 1) + qx(s, 3, 0)).abs();
+ let (dpq0, dpq3) = (dp0 + dq0, dp3 + dq3);
+ let (dp, dq) = (dp0 + dp3, dq0 + dq3);
+ let d = dpq0 + dpq3;
+ if d >= beta {
+ return;
+ }
+ let dsam = |s: &[u16], k: usize, dpq: i32| -> bool {
+ dpq < (beta >> 2)
+ && (px(s, k, 3) - px(s, k, 0)).abs() + (qx(s, k, 0) - qx(s, k, 3)).abs() < (beta >> 3)
+ && (px(s, k, 0) - qx(s, k, 0)).abs() < ((5 * tc + 1) >> 1)
+ };
+ let strong = dsam(s, 0, 2 * dpq0) && dsam(s, 3, 2 * dpq3);
+ let dep = dp < ((beta + (beta >> 1)) >> 3);
+ let deq = dq < ((beta + (beta >> 1)) >> 3);
+ let max = (1i32 << bd) - 1;
+ for k in 0..4 {
+ let base = o + k * along;
+ let p = |i: usize| s[base - (i + 1) * step] as i32;
+ let q = |i: usize| s[base + i * step] as i32;
+ let (p0, p1, p2, p3) = (p(0), p(1), p(2), p(3));
+ let (q0, q1, q2, q3) = (q(0), q(1), q(2), q(3));
+ if strong {
+ let t2 = 2 * tc;
+ if !nfp {
+ s[base - step] = ((p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) >> 3).clamp(p0 - t2, p0 + t2) as u16;
+ s[base - 2 * step] = ((p2 + p1 + p0 + q0 + 2) >> 2).clamp(p1 - t2, p1 + t2) as u16;
+ s[base - 3 * step] = ((2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) >> 3).clamp(p2 - t2, p2 + t2) as u16;
+ }
+ if !nfq {
+ s[base] = ((p1 + 2 * p0 + 2 * q0 + 2 * q1 + q2 + 4) >> 3).clamp(q0 - t2, q0 + t2) as u16;
+ s[base + step] = ((p0 + q0 + q1 + q2 + 2) >> 2).clamp(q1 - t2, q1 + t2) as u16;
+ s[base + 2 * step] = ((p0 + q0 + q1 + 3 * q2 + 2 * q3 + 4) >> 3).clamp(q2 - t2, q2 + t2) as u16;
+ }
+ } else {
+ let mut delta = (9 * (q0 - p0) - 3 * (q1 - p1) + 8) >> 4;
+ if delta.abs() >= tc * 10 {
+ continue;
+ }
+ delta = delta.clamp(-tc, tc);
+ if !nfp {
+ s[base - step] = (p0 + delta).clamp(0, max) as u16;
+ }
+ if !nfq {
+ s[base] = (q0 - delta).clamp(0, max) as u16;
+ }
+ if dep && !nfp {
+ let dp = ((((p2 + p0 + 1) >> 1) - p1 + delta) >> 1).clamp(-(tc >> 1), tc >> 1);
+ s[base - 2 * step] = (p1 + dp).clamp(0, max) as u16;
+ }
+ if deq && !nfq {
+ let dq = ((((q2 + q0 + 1) >> 1) - q1 - delta) >> 1).clamp(-(tc >> 1), tc >> 1);
+ s[base + step] = (q1 + dq).clamp(0, max) as u16;
+ }
+ }
+ }
+}
+
+/// Filter one 4-sample chroma edge segment.
+#[allow(clippy::too_many_arguments)]
+fn filter_chroma(s: &mut [u16], o: usize, step: usize, along: usize, tc: i32, nfp: bool, nfq: bool, bd: u32) {
+ let max = (1i32 << bd) - 1;
+ for k in 0..4 {
+ let base = o + k * along;
+ let (p0, p1) = (s[base - step] as i32, s[base - 2 * step] as i32);
+ let (q0, q1) = (s[base] as i32, s[base + step] as i32);
+ let delta = ((((q0 - p0) << 2) + p1 - q1 + 4) >> 3).clamp(-tc, tc);
+ if !nfp {
+ s[base - step] = (p0 + delta).clamp(0, max) as u16;
+ }
+ if !nfq {
+ s[base] = (q0 - delta).clamp(0, max) as u16;
+ }
+ }
+}
+
+/// SAO of CTB row `r` from the deblocked planes into new row buffers (luma, Cb, Cr).
+fn sao_row(pic: &PicState, r: usize) -> [Vec<u16>; 3] {
+ let ctb = 1usize << pic.log2_ctb;
+ let mut out: [Vec<u16>; 3] = [Vec::new(), Vec::new(), Vec::new()];
+ for c in 0..3 {
+ let (w, h, cs) = if c == 0 { (pic.width, pic.height, ctb) } else { (pic.cwidth, pic.cheight, ctb / 2) };
+ let y0 = r * cs;
+ let y1 = (y0 + cs).min(h);
+ out[c] = pic.planes[c][y0 * w..y1 * w].to_vec();
+ for rx in 0..pic.wctb {
+ let rs = r * pic.wctb + rx;
+ let si = pic.ctb_slice[rs];
+ if si == u32::MAX {
+ continue;
+ }
+ let sl = &pic.slices[si as usize];
+ if !(if c == 0 { sl.sao_luma } else { sl.sao_chroma }) {
+ continue;
+ }
+ let p = pic.sao[rs];
+ if p.type_idx[c] == 0 {
+ continue;
+ }
+ let x0 = rx * cs;
+ let x1 = (x0 + cs).min(w);
+ sao_ctb(pic, c, rs, x0, x1, y0, y1, w, h, &p, &mut out[c]);
+ }
+ }
+ out
+}
+
+#[allow(clippy::too_many_arguments)]
+fn sao_ctb(
+ pic: &PicState,
+ c: usize,
+ rs: usize,
+ x0: usize,
+ x1: usize,
+ y0: usize,
+ y1: usize,
+ w: usize,
+ h: usize,
+ p: &crate::slicedec::SaoParams,
+ dst: &mut [u16],
+) {
+ let bd = if c == 0 { pic.bd_y } else { pic.bd_c };
+ let max = (1i32 << bd) - 1;
+ let sc = if c == 0 { 0 } else { 1 };
+ let offs = p.offsets[c].map(|v| v as i32);
+ // samples of CUs that must not be modified
+ let nofilter = |pic: &PicState, x: usize, y: usize| pic.blk[((y << sc) >> 2) * pic.w4 + ((x << sc) >> 2)].flags & F_NOFILTER != 0;
+ let any_nofilter = {
+ let mut a = false;
+ for by in ((y0 << sc) >> 2)..(((y1 << sc) + 3) >> 2).min(pic.h4) {
+ for bx in ((x0 << sc) >> 2)..(((x1 << sc) + 3) >> 2).min(pic.w4) {
+ a |= pic.blk[by * pic.w4 + bx].flags & F_NOFILTER != 0;
+ }
+ }
+ a
+ };
+ if p.type_idx[c] == 1 {
+ let shift = bd - 5;
+ let mut table = [0i32; 32];
+ for k in 0..4 {
+ table[(k + p.band_pos[c] as usize) & 31] = offs[k];
+ }
+ for y in y0..y1 {
+ for x in x0..x1 {
+ if any_nofilter && nofilter(pic, x, y) {
+ continue;
+ }
+ let v = pic.planes[c][y * w + x] as i32;
+ dst[(y - y0) * w + x] = (v + table[(v >> shift) as usize]).clamp(0, max) as u16;
+ }
+ }
+ return;
+ }
+ let (hp, vp): ([i32; 2], [i32; 2]) = match p.eo_class[c] {
+ 0 => ([-1, 1], [0, 0]),
+ 1 => ([0, 0], [-1, 1]),
+ 2 => ([-1, 1], [-1, 1]),
+ _ => ([1, -1], [-1, 1]),
+ };
+ // Neighbouring CTBs whose samples may not be used (other slice / tile without cross-boundary
+ // filtering), checked per sample only near CTB borders.
+ let s = pic.log2_ctb as usize - sc;
+ let cur_slice = pic.ctb_slice[rs];
+ let lf_cur = pic.slices[cur_slice as usize].lf_across;
+ let cur_ts = pic.layout.rs_to_ts[rs];
+ let cross_ok = |pic: &PicState, xn: usize, yn: usize| -> bool {
+ let nrs = (yn >> s) * pic.wctb + (xn >> s);
+ if nrs == rs {
+ return true;
+ }
+ let ns = pic.ctb_slice[nrs];
+ if ns == u32::MAX {
+ return false;
+ }
+ if pic.ctb_addr[nrs] != pic.ctb_addr[rs] {
+ // different slice: the later one (in decoding order) decides
+ let nts = pic.layout.rs_to_ts[nrs];
+ if nts < cur_ts && !lf_cur {
+ return false;
+ }
+ if cur_ts < nts && !pic.slices[ns as usize].lf_across {
+ return false;
+ }
+ }
+ if !pic.pps.loop_filter_across_tiles && pic.layout.tile_id[pic.layout.rs_to_ts[nrs] as usize] != pic.layout.tile_id[cur_ts as usize] {
+ return false;
+ }
+ true
+ };
+ let edge_map = [1usize, 2, 0, 3, 4];
+ for y in y0..y1 {
+ for x in x0..x1 {
+ if any_nofilter && nofilter(pic, x, y) {
+ continue;
+ }
+ let mut ok = true;
+ let mut sum = 0i32;
+ let v = pic.planes[c][y * w + x] as i32;
+ for k in 0..2 {
+ let xn = x as i32 + hp[k];
+ let yn = y as i32 + vp[k];
+ if xn < 0 || yn < 0 || xn >= w as i32 || yn >= h as i32 {
+ ok = false;
+ break;
+ }
+ let (xn, yn) = (xn as usize, yn as usize);
+ if (xn < x0 || xn >= x1 || yn < y0 || yn >= y1) && !cross_ok(pic, xn, yn) {
+ ok = false;
+ break;
+ }
+ sum += (v - pic.planes[c][yn * w + xn] as i32).signum();
+ }
+ if !ok {
+ continue;
+ }
+ let edge_idx = edge_map[(2 + sum) as usize];
+ if edge_idx == 0 {
+ continue;
+ }
+ dst[(y - y0) * w + x] = (v + offs[edge_idx - 1]).clamp(0, max) as u16;
+ }
+ }
+}
+
+/// Publish CTB row `r` (final samples + compressed motion) into the frame.
+fn publish_row(pic: &mut PicState, r: usize) {
+ let ctb = 1usize << pic.log2_ctb;
+ let (y0, y1) = (r * ctb, ((r + 1) * ctb).min(pic.height));
+ let (c0, c1) = (y0 / 2, y1.div_ceil(2));
+ let (w, cw) = (pic.width, pic.cwidth);
+ let w16 = pic.width.div_ceil(16);
+ let rows16 = (y1 - y0).div_ceil(16);
+ let mut col = vec![ColMv::default(); w16 * rows16];
+ for j in 0..rows16 {
+ for i in 0..w16 {
+ let (x, y) = (i * 16, y0 + j * 16);
+ let bi = (y >> 2) * pic.w4 + (x >> 2);
+ let b = &pic.blk[bi];
+ if b.flags & F_CODED == 0 || b.flags & F_INTRA != 0 {
+ continue;
+ }
+ let f = pic.mvf[bi];
+ let ctbi = (y >> pic.log2_ctb) * pic.wctb + (x >> pic.log2_ctb);
+ let si = pic.ctb_slice[ctbi];
+ if si == u32::MAX {
+ continue;
+ }
+ let sl = &pic.slices[si as usize];
+ let mut cm = ColMv { mv: f.mv, ref_poc: [0; 2], flags: 0 };
+ for l in 0..2 {
+ if f.pred(l) {
+ let ri = f.ref_idx[l] as usize;
+ if ri < sl.ref_pocs[l].len() {
+ cm.flags |= 1 << l;
+ cm.ref_poc[l] = sl.ref_pocs[l][ri];
+ if sl.ref_lt[l][ri] {
+ cm.flags |= 4 << l;
+ }
+ }
+ }
+ }
+ col[j * w16 + i] = cm;
+ }
+ }
+ let [oy, ocb, ocr] = sao_row(pic, r);
+ let _ = (w, cw, c0, c1);
+ let row = FrameRow { y: oy.into(), cb: ocb.into(), cr: ocr.into(), col: col.into() };
+ pic.frame.publish(r, row);
+}
diff --git a/crates/hevc/src/inter.rs b/crates/hevc/src/inter.rs
new file mode 100644
index 000000000..3bcb768e2
--- /dev/null
+++ b/crates/hevc/src/inter.rs
@@ -0,0 +1,166 @@
+//! Fractional sample interpolation (8.5.3.3.3) and weighted sample prediction (8.5.3.3.4).
+
+use crate::picture::Frame;
+use crate::spec_tables::{CHROMA_FILTER, LUMA_FILTER};
+
+/// Max prediction block size + filter margin.
+const WIN: usize = 64 + 7;
+
+/// Luma prediction samples (14-bit intermediate precision) of a w x h block at (x, y) displaced by the
+/// quarter-sample motion vector `mv`, into `out` (stride w).
+pub fn mc_luma(f: &Frame, x: i32, y: i32, mv: [i16; 2], w: usize, h: usize, out: &mut [i16]) {
+ let bd = f.bit_depth;
+ let (fx, fy) = ((mv[0] & 3) as usize, (mv[1] & 3) as usize);
+ let xi = x + (mv[0] as i32 >> 2);
+ let yi = y + (mv[1] as i32 >> 2);
+ let shift1 = bd.min(12) - 8;
+ let shift3 = 14 - bd;
+ let mut win = [0i16; WIN * WIN];
+ if fx == 0 && fy == 0 {
+ f.luma_window(xi, yi, w, h, &mut win, WIN);
+ for r in 0..h {
+ for c in 0..w {
+ out[r * w + c] = win[r * WIN + c] << shift3;
+ }
+ }
+ return;
+ }
+ f.luma_window(xi - 3, yi - 3, w + 7, h + 7, &mut win, WIN);
+ let hf = &LUMA_FILTER[fx];
+ let vf = &LUMA_FILTER[fy];
+ if fy == 0 {
+ for r in 0..h {
+ let row = &win[(r + 3) * WIN..];
+ for c in 0..w {
+ let s: i32 = (0..8).map(|k| hf[k] as i32 * row[c + k] as i32).sum();
+ out[r * w + c] = (s >> shift1) as i16;
+ }
+ }
+ } else if fx == 0 {
+ for r in 0..h {
+ for c in 0..w {
+ let s: i32 = (0..8).map(|k| vf[k] as i32 * win[(r + k) * WIN + c + 3] as i32).sum();
+ out[r * w + c] = (s >> shift1) as i16;
+ }
+ }
+ } else {
+ let mut tmp = [0i16; WIN * WIN];
+ for r in 0..h + 7 {
+ let row = &win[r * WIN..];
+ for c in 0..w {
+ let s: i32 = (0..8).map(|k| hf[k] as i32 * row[c + k] as i32).sum();
+ tmp[r * WIN + c] = (s >> shift1) as i16;
+ }
+ }
+ for r in 0..h {
+ for c in 0..w {
+ let s: i32 = (0..8).map(|k| vf[k] as i32 * tmp[(r + k) * WIN + c] as i32).sum();
+ out[r * w + c] = (s >> 6) as i16;
+ }
+ }
+ }
+}
+
+/// Chroma prediction samples of a w x h chroma block at chroma position (x, y) with a 1/8-sample
+/// vector (4:2:0).
+pub fn mc_chroma(f: &Frame, c: usize, x: i32, y: i32, mv: [i16; 2], w: usize, h: usize, out: &mut [i16]) {
+ let bd = f.bit_depth_c;
+ let (fx, fy) = ((mv[0] & 7) as usize, (mv[1] & 7) as usize);
+ let xi = x + (mv[0] as i32 >> 3);
+ let yi = y + (mv[1] as i32 >> 3);
+ let shift1 = bd.min(12) - 8;
+ let shift3 = 14 - bd;
+ let mut win = [0i16; WIN * WIN];
+ if fx == 0 && fy == 0 {
+ f.chroma_window(c, xi, yi, w, h, &mut win, WIN);
+ for r in 0..h {
+ for cc in 0..w {
+ out[r * w + cc] = win[r * WIN + cc] << shift3;
+ }
+ }
+ return;
+ }
+ f.chroma_window(c, xi - 1, yi - 1, w + 3, h + 3, &mut win, WIN);
+ let hf = &CHROMA_FILTER[fx];
+ let vf = &CHROMA_FILTER[fy];
+ if fy == 0 {
+ for r in 0..h {
+ let row = &win[(r + 1) * WIN..];
+ for cc in 0..w {
+ let s: i32 = (0..4).map(|k| hf[k] as i32 * row[cc + k] as i32).sum();
+ out[r * w + cc] = (s >> shift1) as i16;
+ }
+ }
+ } else if fx == 0 {
+ for r in 0..h {
+ for cc in 0..w {
+ let s: i32 = (0..4).map(|k| vf[k] as i32 * win[(r + k) * WIN + cc + 1] as i32).sum();
+ out[r * w + cc] = (s >> shift1) as i16;
+ }
+ }
+ } else {
+ let mut tmp = [0i16; WIN * WIN];
+ for r in 0..h + 3 {
+ let row = &win[r * WIN..];
+ for cc in 0..w {
+ let s: i32 = (0..4).map(|k| hf[k] as i32 * row[cc + k] as i32).sum();
+ tmp[r * WIN + cc] = (s >> shift1) as i16;
+ }
+ }
+ for r in 0..h {
+ for cc in 0..w {
+ let s: i32 = (0..4).map(|k| vf[k] as i32 * tmp[(r + k) * WIN + cc] as i32).sum();
+ out[r * w + cc] = (s >> 6) as i16;
+ }
+ }
+ }
+}
+
+/// Default weighted prediction, one list (8-262).
+pub fn put_uni(p: &[i16], w: usize, h: usize, bd: u32, dst: &mut [u16], ds: usize) {
+ let shift = 14 - bd;
+ let off = if shift > 0 { 1 << (shift - 1) } else { 0 };
+ let max = (1i32 << bd) - 1;
+ for r in 0..h {
+ for c in 0..w {
+ dst[r * ds + c] = ((p[r * w + c] as i32 + off) >> shift).clamp(0, max) as u16;
+ }
+ }
+}
+
+/// Default weighted prediction, bi-prediction (8-263).
+pub fn put_bi(p0: &[i16], p1: &[i16], w: usize, h: usize, bd: u32, dst: &mut [u16], ds: usize) {
+ let shift = 15 - bd;
+ let off = 1 << (shift - 1);
+ let max = (1i32 << bd) - 1;
+ for r in 0..h {
+ for c in 0..w {
+ let i = r * w + c;
+ dst[r * ds + c] = ((p0[i] as i32 + p1[i] as i32 + off) >> shift).clamp(0, max) as u16;
+ }
+ }
+}
+
+/// Explicit weighted prediction, one list (8-265). `o` is the offset already scaled to the bit depth.
+pub fn put_weighted_uni(p: &[i16], w: usize, h: usize, bd: u32, log2wd: u32, wt: i32, o: i32, dst: &mut [u16], ds: usize) {
+ let max = (1i32 << bd) - 1;
+ for r in 0..h {
+ for c in 0..w {
+ let v = p[r * w + c] as i32 * wt;
+ let v = if log2wd >= 1 { ((v + (1 << (log2wd - 1))) >> log2wd) + o } else { v + o };
+ dst[r * ds + c] = v.clamp(0, max) as u16;
+ }
+ }
+}
+
+/// Explicit weighted bi-prediction (8-266).
+pub fn put_weighted_bi(p0: &[i16], p1: &[i16], w: usize, h: usize, bd: u32, log2wd: u32, w0: i32, w1: i32, o0: i32, o1: i32, dst: &mut [u16], ds: usize) {
+ let max = (1i32 << bd) - 1;
+ for r in 0..h {
+ for c in 0..w {
+ let i = r * w + c;
+ let v = (p0[i] as i32 * w0 + p1[i] as i32 * w1 + ((o0 + o1 + 1) << log2wd)) >> (log2wd + 1);
+ dst[r * ds + c] = v.clamp(0, max) as u16;
+ }
+ }
+}
diff --git a/crates/hevc/src/intra.rs b/crates/hevc/src/intra.rs
new file mode 100644
index 000000000..b1cb62823
--- /dev/null
+++ b/crates/hevc/src/intra.rs
@@ -0,0 +1,253 @@
+//! Intra sample prediction (8.4.4.2): reference substitution, filtering (incl. strong intra
+//! smoothing), planar, DC and the 33 angular modes.
+
+use crate::spec_tables::{INTRA_PRED_ANGLE, INV_ANGLE};
+
+/// Reference samples of an nTbS block: `left[0]` = `top[0]` = p[-1][-1], `left[1 + y]` = p[-1][y],
+/// `top[1 + x]` = p[x][-1] for x, y = 0..2*nTbS-1.
+#[derive(Clone)]
+pub struct Refs {
+ pub left: [u16; 129],
+ pub top: [u16; 129],
+}
+
+impl Default for Refs {
+ fn default() -> Self {
+ Refs { left: [0; 129], top: [0; 129] }
+ }
+}
+
+/// Substitution process (8.4.4.2.2). `avail_left[1 + y]` / `avail_top[1 + x]` (index 0 = corner) tell
+/// which samples are available; unavailable ones are replaced.
+pub fn substitute(r: &mut Refs, avail_left: &[bool; 129], avail_top: &[bool; 129], n: usize, bit_depth: u32) {
+ let n2 = 2 * n;
+ // Sequence order: p[-1][2n-1] .. p[-1][-1], p[0][-1] .. p[2n-1][-1]
+ let any = avail_left[..=n2].iter().any(|&a| a) || avail_top[1..=n2].iter().any(|&a| a);
+ if !any {
+ let v = 1u16 << (bit_depth - 1);
+ r.left[..=n2].fill(v);
+ r.top[..=n2].fill(v);
+ return;
+ }
+ if !avail_left[n2] {
+ // search upwards then along the top
+ let mut found = None;
+ for y in (0..n2).rev() {
+ if avail_left[y] {
+ found = Some(r.left[y]);
+ break;
+ }
+ }
+ if found.is_none() {
+ for x in 1..=n2 {
+ if avail_top[x] {
+ found = Some(r.top[x]);
+ break;
+ }
+ }
+ }
+ r.left[n2] = found.unwrap_or(0);
+ }
+ for y in (0..n2).rev() {
+ if !avail_left[y] {
+ r.left[y] = r.left[y + 1];
+ }
+ }
+ r.top[0] = r.left[0];
+ for x in 1..=n2 {
+ if !avail_top[x] {
+ r.top[x] = r.top[x - 1];
+ }
+ }
+}
+
+/// Filtering process of neighbouring samples (8.4.4.2.3) for luma (and 4:4:4 chroma).
+pub fn filter(r: &mut Refs, mode: u32, n: usize, strong_enabled: bool, is_luma: bool, bit_depth: u32) {
+ if mode == 1 || n == 4 {
+ return;
+ }
+ let min_dist = (mode as i32 - 26).abs().min((mode as i32 - 10).abs());
+ let thres = match n {
+ 8 => 7,
+ 16 => 1,
+ _ => 0,
+ };
+ if min_dist <= thres {
+ return;
+ }
+ let n2 = 2 * n;
+ let c = r.left[0] as i32;
+ if strong_enabled && is_luma && n == 32 {
+ let (bl, tr) = (r.left[n2] as i32, r.top[n2] as i32);
+ let thr = 1 << (bit_depth - 5);
+ if (c + tr - 2 * r.top[n] as i32).abs() < thr && (c + bl - 2 * r.left[n] as i32).abs() < thr {
+ for i in 0..63 {
+ r.left[1 + i] = (((63 - i as i32) * c + (i as i32 + 1) * bl + 32) >> 6) as u16;
+ r.top[1 + i] = (((63 - i as i32) * c + (i as i32 + 1) * tr + 32) >> 6) as u16;
+ }
+ return;
+ }
+ }
+ let (l, t) = (r.left, r.top);
+ let corner = ((l[1] as u32 + 2 * c as u32 + t[1] as u32 + 2) >> 2) as u16;
+ for i in 1..n2 {
+ r.left[i] = ((l[i - 1] as u32 + 2 * l[i] as u32 + l[i + 1] as u32 + 2) >> 2) as u16;
+ r.top[i] = ((t[i - 1] as u32 + 2 * t[i] as u32 + t[i + 1] as u32 + 2) >> 2) as u16;
+ }
+ r.left[0] = corner;
+ r.top[0] = corner;
+}
+
+/// Predict an n x n block with `mode` into `out` (stride `os`). `edge_filters`: DC / horizontal /
+/// vertical boundary smoothing (luma blocks smaller than 32x32).
+pub fn predict(r: &Refs, mode: u32, n: usize, edge_filters: bool, bit_depth: u32, out: &mut [u16], os: usize) {
+ let max = (1i32 << bit_depth) - 1;
+ match mode {
+ 0 => {
+ // planar
+ let log2 = n.trailing_zeros();
+ let tr = r.top[1 + n] as i32;
+ let bl = r.left[1 + n] as i32;
+ for y in 0..n {
+ let l = r.left[1 + y] as i32;
+ for x in 0..n {
+ let t = r.top[1 + x] as i32;
+ let v = ((n - 1 - x) as i32 * l + (x as i32 + 1) * tr + (n - 1 - y) as i32 * t + (y as i32 + 1) * bl + n as i32) >> (log2 + 1);
+ out[y * os + x] = v as u16;
+ }
+ }
+ }
+ 1 => {
+ let log2 = n.trailing_zeros();
+ let sum: u32 = r.top[1..=n].iter().map(|&v| v as u32).sum::<u32>() + r.left[1..=n].iter().map(|&v| v as u32).sum::<u32>();
+ let dc = ((sum + n as u32) >> (log2 + 1)) as u16;
+ for y in 0..n {
+ out[y * os..y * os + n].fill(dc);
+ }
+ if edge_filters && n < 32 {
+ let d = dc as u32;
+ out[0] = ((r.left[1] as u32 + 2 * d + r.top[1] as u32 + 2) >> 2) as u16;
+ for x in 1..n {
+ out[x] = ((r.top[1 + x] as u32 + 3 * d + 2) >> 2) as u16;
+ }
+ for y in 1..n {
+ out[y * os] = ((r.left[1 + y] as u32 + 3 * d + 2) >> 2) as u16;
+ }
+ }
+ }
+ _ => {
+ let angle = INTRA_PRED_ANGLE[mode as usize] as i32;
+ // reference array ref[-n..=2n] stored at offset n
+ let mut refa = [0i32; 3 * 64 + 1];
+ let base = n as i32;
+ let (main, side) = if mode >= 18 { (&r.top, &r.left) } else { (&r.left, &r.top) };
+ for x in 0..=n {
+ refa[(base + x as i32) as usize] = main[x] as i32; // ref[x] = p[-1+x][-1]
+ }
+ if angle < 0 {
+ let lim = (n as i32 * angle) >> 5;
+ if lim < -1 {
+ let inv = INV_ANGLE[(mode - 11) as usize] as i32;
+ for x in lim..=-1 {
+ let idx = -1 + ((x * inv + 128) >> 8);
+ refa[(base + x) as usize] = side[(idx + 1) as usize] as i32;
+ }
+ }
+ } else {
+ for x in n + 1..=2 * n {
+ refa[(base + x as i32) as usize] = main[x] as i32;
+ }
+ }
+ let horizontal = mode < 18;
+ for j in 0..n {
+ let pos = (j as i32 + 1) * angle;
+ let idx = pos >> 5;
+ let fact = pos & 31;
+ for i in 0..n {
+ let k = (base + i as i32 + idx + 1) as usize;
+ let v = if fact != 0 { ((32 - fact) * refa[k] + fact * refa[k + 1] + 16) >> 5 } else { refa[k] };
+ if horizontal {
+ out[i * os + j] = v as u16;
+ } else {
+ out[j * os + i] = v as u16;
+ }
+ }
+ }
+ if edge_filters && n < 32 {
+ if mode == 26 {
+ for y in 0..n {
+ let v = r.top[1] as i32 + ((r.left[1 + y] as i32 - r.left[0] as i32) >> 1);
+ out[y * os] = v.clamp(0, max) as u16;
+ }
+ } else if mode == 10 {
+ for x in 0..n {
+ let v = r.left[1] as i32 + ((r.top[1 + x] as i32 - r.top[0] as i32) >> 1);
+ out[x] = v.clamp(0, max) as u16;
+ }
+ }
+ }
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn refs(f: impl Fn(i32) -> u16) -> Refs {
+ let mut r = Refs::default();
+ r.left[0] = f(0);
+ r.top[0] = f(0);
+ for i in 1..129 {
+ r.left[i] = f(-(i as i32));
+ r.top[i] = f(i as i32);
+ }
+ r
+ }
+
+ #[test]
+ fn dc_and_planar_flat() {
+ let r = refs(|_| 100);
+ let mut out = [0u16; 64];
+ predict(&r, 1, 8, true, 8, &mut out, 8);
+ assert!(out.iter().all(|&v| v == 100));
+ predict(&r, 0, 8, true, 8, &mut out, 8);
+ assert!(out.iter().all(|&v| v == 100));
+ }
+
+ #[test]
+ fn pure_vertical_and_horizontal() {
+ let r = refs(|i| (128 + i) as u16);
+ let mut out = [0u16; 16];
+ predict(&r, 26, 4, false, 8, &mut out, 4);
+ for y in 0..4 {
+ for x in 0..4 {
+ assert_eq!(out[y * 4 + x], r.top[1 + x]);
+ }
+ }
+ predict(&r, 10, 4, false, 8, &mut out, 4);
+ for y in 0..4 {
+ for x in 0..4 {
+ assert_eq!(out[y * 4 + x], r.left[1 + y]);
+ }
+ }
+ // diagonal mode 34 reads top[x + y + 2]
+ predict(&r, 34, 4, false, 8, &mut out, 4);
+ assert_eq!(out[4 + 1], r.top[1 + 1 + 1 + 1]);
+ }
+
+ #[test]
+ fn substitution() {
+ let mut r = Refs::default();
+ let mut al = [false; 129];
+ let at = [false; 129];
+ r.left[3] = 77;
+ al[3] = true;
+ substitute(&mut r, &al, &at, 4, 8);
+ assert!(r.left[..=8].iter().all(|&v| v == 77));
+ assert!(r.top[..=8].iter().all(|&v| v == 77));
+ let mut r = Refs::default();
+ substitute(&mut r, &[false; 129], &[false; 129], 4, 10);
+ assert_eq!(r.top[5], 512);
+ }
+}
diff --git a/crates/hevc/src/lib.rs b/crates/hevc/src/lib.rs
new file mode 100644
index 000000000..b24114508
--- /dev/null
+++ b/crates/hevc/src/lib.rs
@@ -0,0 +1,126 @@
+//! Clean-room pure-Rust H.265 / HEVC decoder, implemented from ITU-T Rec. H.265 (ISO/IEC 23008-2).
+//!
+//! Supported: Main and Main 10 profiles (4:2:0, 8/10-bit; up to 12-bit 4:2:0 without range-extension
+//! tools), all coding tools of those profiles: CABAC, coding / transform quadtrees, AMP, PCM,
+//! transform skip, scaling lists, sign data hiding, 35 intra modes with strong intra smoothing,
+//! merge / AMVP / TMVP, weighted prediction, deblocking, SAO, tiles, wavefront parallel processing
+//! (parsing), dependent slice segments, short- and long-term reference picture sets.
+//!
+//! ```no_run
+//! let mut dec = filmcraft_hevc::Decoder::new();
+//! let stream = std::fs::read("video.h265").unwrap();
+//! for pic in dec.decode(&stream, 0).unwrap() {
+//! println!("{}x{} poc {}", pic.width, pic.height, pic.poc);
+//! }
+//! for pic in dec.flush() {
+//! let _ = pic;
+//! }
+//! ```
+
+// Index loops over fixed-size blocks read more clearly than iterator chains in codec code.
+#![allow(clippy::needless_range_loop, clippy::too_many_arguments)]
+
+mod cabac;
+mod decoder;
+mod dpb;
+mod error;
+mod filter;
+mod inter;
+mod intra;
+mod mvpred;
+pub mod params;
+mod picture;
+pub mod slice;
+mod slicedec;
+#[rustfmt::skip]
+#[allow(dead_code)]
+mod spec_tables;
+mod tables;
+mod transform;
+
+pub use decoder::{DecodeStats, Decoder};
+pub use error::{Error, Result};
+
+/// Colour description from the VUI (ITU-T H.273 code points).
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct ColorInfo {
+ /// `video_full_range_flag`.
+ pub full_range: bool,
+ pub primaries: u8,
+ pub transfer: u8,
+ pub matrix: u8,
+}
+
+/// Samples of one plane: 8-bit streams produce `U8`, higher bit depths `U16` (value range
+/// `0..(1 << bit_depth)`).
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub enum Plane {
+ U8(Vec<u8>),
+ U16(Vec<u16>),
+}
+
+impl Plane {
+ pub fn len(&self) -> usize {
+ match self {
+ Plane::U8(v) => v.len(),
+ Plane::U16(v) => v.len(),
+ }
+ }
+ pub fn is_empty(&self) -> bool {
+ self.len() == 0
+ }
+ pub fn as_u8(&self) -> Option<&[u8]> {
+ match self {
+ Plane::U8(v) => Some(v),
+ Plane::U16(_) => None,
+ }
+ }
+ pub fn as_u16(&self) -> Option<&[u16]> {
+ match self {
+ Plane::U8(_) => None,
+ Plane::U16(v) => Some(v),
+ }
+ }
+ /// Sample `i` widened to u16.
+ pub fn get(&self, i: usize) -> u16 {
+ match self {
+ Plane::U8(v) => v[i] as u16,
+ Plane::U16(v) => v[i],
+ }
+ }
+ /// Raw bytes as written by ffmpeg `rawvideo` (8-bit, or 16-bit little endian).
+ pub fn to_le_bytes(&self) -> Vec<u8> {
+ match self {
+ Plane::U8(v) => v.clone(),
+ Plane::U16(v) => v.iter().flat_map(|s| s.to_le_bytes()).collect(),
+ }
+ }
+}
+
+/// A decoded, cropped picture in planar 4:2:0.
+#[derive(Clone, Debug)]
+pub struct Picture {
+ /// Cropped luma width.
+ pub width: u32,
+ /// Cropped luma height.
+ pub height: u32,
+ pub chroma_width: u32,
+ pub chroma_height: u32,
+ /// Luma bit depth (chroma uses the same storage type).
+ pub bit_depth: u32,
+ pub y: Plane,
+ pub u: Plane,
+ pub v: Plane,
+ /// Strides in samples.
+ pub y_stride: usize,
+ pub uv_stride: usize,
+ /// Presentation timestamp passed to [`Decoder::decode`] with the access unit of this picture.
+ pub pts: i64,
+ /// Picture order count.
+ pub poc: i32,
+ /// IRAP (IDR / CRA / BLA) picture.
+ pub key: bool,
+ pub color: ColorInfo,
+ /// Sample aspect ratio (0, 0 when unspecified).
+ pub sar: (u16, u16),
+}
diff --git a/crates/hevc/src/mvpred.rs b/crates/hevc/src/mvpred.rs
new file mode 100644
index 000000000..bd0f7f85c
--- /dev/null
+++ b/crates/hevc/src/mvpred.rs
@@ -0,0 +1,351 @@
+//! Motion vector prediction: merge candidates (8.5.3.2.2 - 8.5.3.2.5), AMVP (8.5.3.2.6, 8.5.3.2.7)
+//! and temporal motion vector prediction (8.5.3.2.8, 8.5.3.2.9).
+
+use crate::picture::RefPic;
+use crate::slicedec::{F_INTRA, MvField, PartMode, SliceDecoder};
+
+/// l0CandIdx / l1CandIdx of Table 8-7.
+const COMB: [(usize, usize); 12] = [(0, 1), (1, 0), (0, 2), (2, 0), (1, 2), (2, 1), (0, 3), (3, 0), (1, 3), (3, 1), (2, 3), (3, 2)];
+
+/// Motion vector scaling (8-179 .. 8-183).
+pub fn scale_mv(mv: [i16; 2], td: i32, tb: i32) -> [i16; 2] {
+ let td = td.clamp(-128, 127);
+ let tb = tb.clamp(-128, 127);
+ if td == 0 {
+ return mv;
+ }
+ let tx = (16384 + (td.abs() >> 1)) / td;
+ let dsf = ((tb * tx + 32) >> 6).clamp(-4096, 4095);
+ let s = |c: i16| -> i16 {
+ let p = dsf * c as i32;
+ (p.signum() * ((p.abs() + 127) >> 8)).clamp(-32768, 32767) as i16
+ };
+ [s(mv[0]), s(mv[1])]
+}
+
+/// Same motion (used lists only).
+fn same_motion(a: &MvField, b: &MvField) -> bool {
+ for l in 0..2 {
+ if a.pred(l) != b.pred(l) {
+ return false;
+ }
+ if a.pred(l) && (a.ref_idx[l] != b.ref_idx[l] || a.mv[l] != b.mv[l]) {
+ return false;
+ }
+ }
+ true
+}
+
+impl<'a> SliceDecoder<'a> {
+ /// Prediction block availability (6.4.2).
+ fn pb_avail(&self, xc: i32, yc: i32, ncb: i32, xp: i32, yp: i32, w: i32, h: i32, part_idx: usize, xn: i32, yn: i32) -> bool {
+ let same_cb = xc <= xn && yc <= yn && xc + ncb > xn && yc + ncb > yn;
+ let avail = if !same_cb {
+ self.pic.zavail(xp, yp, xn, yn, self.slice_addr)
+ } else {
+ !((w << 1) == ncb && (h << 1) == ncb && part_idx == 1 && yc + h <= yn && xc + w > xn)
+ };
+ avail && self.pic.blk_at(xn, yn).flags & F_INTRA == 0
+ }
+
+ #[inline]
+ fn mv_at(&self, x: i32, y: i32) -> MvField {
+ self.pic.mvf[(y as usize >> 2) * self.pic.w4 + (x as usize >> 2)]
+ }
+
+ #[inline]
+ fn ref_pic(&self, l: usize, idx: i8) -> &RefPic {
+ &self.refs[l][idx as usize]
+ }
+
+ /// Merge mode motion (8.5.3.2.2).
+ pub fn derive_merge(
+ &self,
+ xc: i32,
+ yc: i32,
+ ncb: i32,
+ xp0: i32,
+ yp0: i32,
+ w0: i32,
+ h0: i32,
+ part_idx0: usize,
+ part: PartMode,
+ merge_idx: usize,
+ ) -> MvField {
+ let pml = self.pps.log2_parallel_merge_level;
+ let (xp, yp, w, h, part_idx) = if pml > 2 && ncb == 8 { (xc, yc, ncb, ncb, 0) } else { (xp0, yp0, w0, h0, part_idx0) };
+ let same_mer = |xn: i32, yn: i32| (xp >> pml) == (xn >> pml) && (yp >> pml) == (yn >> pml);
+ let avail = |xn: i32, yn: i32| self.pb_avail(xc, yc, ncb, xp, yp, w, h, part_idx, xn, yn) && !same_mer(xn, yn);
+ let mut list: [MvField; 5] = [MvField::default(); 5];
+ let mut n = 0;
+ let max = self.sh.max_num_merge_cand as usize;
+ // spatial candidates (8.5.3.2.3)
+ let pa1 = (xp - 1, yp + h - 1);
+ let av_a1 = avail(pa1.0, pa1.1) && !(matches!(part, PartMode::PNx2N | PartMode::PnLx2N | PartMode::PnRx2N) && part_idx == 1);
+ let m_a1 = if av_a1 { self.mv_at(pa1.0, pa1.1) } else { MvField::default() };
+ if av_a1 {
+ list[n] = m_a1;
+ n += 1;
+ }
+ let pb1 = (xp + w - 1, yp - 1);
+ let av_b1 = avail(pb1.0, pb1.1) && !(matches!(part, PartMode::P2NxN | PartMode::P2NxnU | PartMode::P2NxnD) && part_idx == 1);
+ let m_b1 = if av_b1 { self.mv_at(pb1.0, pb1.1) } else { MvField::default() };
+ let fl_b1 = av_b1 && !(av_a1 && same_motion(&m_a1, &m_b1));
+ if fl_b1 {
+ list[n] = m_b1;
+ n += 1;
+ }
+ let pb0 = (xp + w, yp - 1);
+ let av_b0 = avail(pb0.0, pb0.1);
+ let fl_b0 = av_b0 && {
+ let m = self.mv_at(pb0.0, pb0.1);
+ !(av_b1 && same_motion(&m_b1, &m))
+ };
+ if fl_b0 {
+ list[n] = self.mv_at(pb0.0, pb0.1);
+ n += 1;
+ }
+ let pa0 = (xp - 1, yp + h);
+ let av_a0 = avail(pa0.0, pa0.1);
+ let fl_a0 = av_a0 && {
+ let m = self.mv_at(pa0.0, pa0.1);
+ !(av_a1 && same_motion(&m_a1, &m))
+ };
+ if fl_a0 {
+ list[n] = self.mv_at(pa0.0, pa0.1);
+ n += 1;
+ }
+ let pb2 = (xp - 1, yp - 1);
+ let av_b2 = avail(pb2.0, pb2.1);
+ let fl_b2 = av_b2 && {
+ let m = self.mv_at(pb2.0, pb2.1);
+ !((av_a1 && same_motion(&m_a1, &m)) || (av_b1 && same_motion(&m_b1, &m))) && (fl_a0 as u32 + av_a1 as u32 + fl_b0 as u32 + fl_b1 as u32) != 4
+ };
+ if fl_b2 {
+ list[n] = self.mv_at(pb2.0, pb2.1);
+ n += 1;
+ }
+ if merge_idx < n {
+ return self.finish_merge(list[merge_idx], w0, h0);
+ }
+ // temporal candidate
+ let mut col = MvField::default();
+ let mut col_avail = false;
+ if let Some(mv) = self.temporal(xp, yp, w, h, 0, 0) {
+ col.mv[0] = mv;
+ col.ref_idx[0] = 0;
+ col_avail = true;
+ }
+ if self.sh.is_b()
+ && let Some(mv) = self.temporal(xp, yp, w, h, 1, 0)
+ {
+ col.mv[1] = mv;
+ col.ref_idx[1] = 0;
+ col_avail = true;
+ }
+ let mut cands: Vec<MvField> = list[..n].to_vec();
+ if col_avail {
+ cands.push(col);
+ }
+ if merge_idx < cands.len() {
+ return self.finish_merge(cands[merge_idx], w0, h0);
+ }
+ // combined bi-predictive candidates (8.5.3.2.4)
+ let num_orig = cands.len();
+ if self.sh.is_b() && num_orig > 1 && num_orig < max {
+ let mut comb = 0;
+ while comb < num_orig * (num_orig - 1) && cands.len() < max {
+ let (i0, i1) = COMB[comb];
+ let (c0, c1) = (cands[i0], cands[i1]);
+ if c0.pred(0) && c1.pred(1) && (self.ref_pic(0, c0.ref_idx[0]).poc != self.ref_pic(1, c1.ref_idx[1]).poc || c0.mv[0] != c1.mv[1]) {
+ cands.push(MvField { mv: [c0.mv[0], c1.mv[1]], ref_idx: [c0.ref_idx[0], c1.ref_idx[1]] });
+ }
+ comb += 1;
+ }
+ }
+ if merge_idx < cands.len() {
+ return self.finish_merge(cands[merge_idx], w0, h0);
+ }
+ // zero candidates (8.5.3.2.5)
+ let num_ref = if self.sh.is_b() { self.sh.num_ref_idx[0].min(self.sh.num_ref_idx[1]) } else { self.sh.num_ref_idx[0] } as usize;
+ let mut zero_idx = 0;
+ while cands.len() <= merge_idx {
+ let r = if zero_idx < num_ref { zero_idx as i8 } else { 0 };
+ cands.push(MvField { mv: [[0; 2]; 2], ref_idx: [r, if self.sh.is_b() { r } else { -1 }] });
+ zero_idx += 1;
+ }
+ self.finish_merge(cands[merge_idx], w0, h0)
+ }
+
+ fn finish_merge(&self, mut f: MvField, w: i32, h: i32) -> MvField {
+ if f.pred(0) && f.pred(1) && w + h == 12 {
+ f.ref_idx[1] = -1;
+ f.mv[1] = [0, 0];
+ }
+ for l in 0..2 {
+ if !f.pred(l) {
+ f.mv[l] = [0, 0];
+ }
+ }
+ f
+ }
+
+ /// Temporal luma motion vector prediction (8.5.3.2.8).
+ pub fn temporal(&self, xp: i32, yp: i32, w: i32, h: i32, l: usize, ref_idx: usize) -> Option<[i16; 2]> {
+ let col = self.col.as_ref()?;
+ let s = self.sps.log2_ctb;
+ let (xbr, ybr) = (xp + w, yp + h);
+ if (yp >> s) == (ybr >> s) && ybr < self.pic.height as i32 && xbr < self.pic.width as i32 {
+ let r = self.col_mv(col, (xbr >> 4) << 4, (ybr >> 4) << 4, l, ref_idx);
+ if r.is_some() {
+ return r;
+ }
+ }
+ let (xc, yc) = (xp + (w >> 1), yp + (h >> 1));
+ self.col_mv(col, (xc >> 4) << 4, (yc >> 4) << 4, l, ref_idx)
+ }
+
+ /// Collocated motion vectors (8.5.3.2.9).
+ fn col_mv(&self, col: &RefPic, x: i32, y: i32, l: usize, ref_idx: usize) -> Option<[i16; 2]> {
+ let f = &col.frame;
+ if f.width != self.pic.width || f.height != self.pic.height {
+ return None;
+ }
+ let cm = f.col_mv(x as usize, y as usize);
+ if cm.flags & 3 == 0 {
+ return None;
+ }
+ let list_col = if cm.flags & 1 == 0 {
+ 1
+ } else if cm.flags & 2 == 0 {
+ 0
+ } else if self.no_backward_pred {
+ l
+ } else {
+ self.sh.collocated_from_l0 as usize
+ };
+ let mv = cm.mv[list_col];
+ let col_lt = (cm.flags >> (2 + list_col)) & 1 == 1;
+ let cur = self.refs[l].get(ref_idx)?;
+ if cur.long_term != col_lt {
+ return None;
+ }
+ let col_diff = col.poc - cm.ref_poc[list_col];
+ let cur_diff = self.pic.poc - cur.poc;
+ if cur.long_term || col_diff == cur_diff { Some(mv) } else { Some(scale_mv(mv, col_diff, cur_diff)) }
+ }
+
+ /// AMVP predictor (8.5.3.2.6, 8.5.3.2.7).
+ pub fn derive_amvp(
+ &self,
+ xc: i32,
+ yc: i32,
+ ncb: i32,
+ xp: i32,
+ yp: i32,
+ w: i32,
+ h: i32,
+ part_idx: usize,
+ l: usize,
+ ref_idx: usize,
+ mvp_flag: usize,
+ ) -> [i16; 2] {
+ let target = &self.refs[l][ref_idx];
+ let (tpoc, tlt) = (target.poc, target.long_term);
+ let cur_poc = self.pic.poc;
+ let y = 1 - l;
+ // exact reference match (no scaling)
+ let unscaled = |f: &MvField| -> Option<[i16; 2]> {
+ if f.pred(l) && self.ref_pic(l, f.ref_idx[l]).poc == tpoc {
+ Some(f.mv[l])
+ } else if f.pred(y) && self.ref_pic(y, f.ref_idx[y]).poc == tpoc {
+ Some(f.mv[y])
+ } else {
+ None
+ }
+ };
+ // long-term-compatible match, scaled when both references are short-term
+ let scaled = |f: &MvField| -> Option<[i16; 2]> {
+ let pick = if f.pred(l) && self.ref_pic(l, f.ref_idx[l]).long_term == tlt {
+ Some((f.mv[l], self.ref_pic(l, f.ref_idx[l])))
+ } else if f.pred(y) && self.ref_pic(y, f.ref_idx[y]).long_term == tlt {
+ Some((f.mv[y], self.ref_pic(y, f.ref_idx[y])))
+ } else {
+ None
+ };
+ pick.map(|(mv, r)| if r.poc != tpoc && !r.long_term && !tlt { scale_mv(mv, cur_poc - r.poc, cur_poc - tpoc) } else { mv })
+ };
+ let pa = [(xp - 1, yp + h), (xp - 1, yp + h - 1)];
+ let av_a = [self.pb_avail(xc, yc, ncb, xp, yp, w, h, part_idx, pa[0].0, pa[0].1), self.pb_avail(xc, yc, ncb, xp, yp, w, h, part_idx, pa[1].0, pa[1].1)];
+ let is_scaled = av_a[0] || av_a[1];
+ let mut a = None;
+ for k in 0..2 {
+ if av_a[k] && a.is_none() {
+ a = unscaled(&self.mv_at(pa[k].0, pa[k].1));
+ }
+ }
+ if a.is_none() {
+ for k in 0..2 {
+ if av_a[k] && a.is_none() {
+ a = scaled(&self.mv_at(pa[k].0, pa[k].1));
+ }
+ }
+ }
+ let pb = [(xp + w, yp - 1), (xp + w - 1, yp - 1), (xp - 1, yp - 1)];
+ let av_b = [0, 1, 2].map(|k| self.pb_avail(xc, yc, ncb, xp, yp, w, h, part_idx, pb[k].0, pb[k].1));
+ let mut b = None;
+ for k in 0..3 {
+ if av_b[k] && b.is_none() {
+ b = unscaled(&self.mv_at(pb[k].0, pb[k].1));
+ }
+ }
+ if !is_scaled && b.is_some() {
+ a = b;
+ }
+ if !is_scaled {
+ b = None;
+ for k in 0..3 {
+ if av_b[k] && b.is_none() {
+ b = scaled(&self.mv_at(pb[k].0, pb[k].1));
+ }
+ }
+ }
+ let mut list: [[i16; 2]; 3] = [[0; 2]; 3];
+ let mut n = 0;
+ if let Some(a) = a {
+ list[n] = a;
+ n += 1;
+ if let Some(b) = b
+ && b != a
+ {
+ list[n] = b;
+ n += 1;
+ }
+ } else if let Some(b) = b {
+ list[n] = b;
+ n += 1;
+ }
+ if n < 2
+ && mvp_flag >= n
+ && let Some(c) = self.temporal(xp, yp, w, h, l, ref_idx)
+ {
+ list[n] = c;
+ n += 1;
+ }
+ let _ = n;
+ list[mvp_flag.min(1)]
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn mv_scaling() {
+ // same distance: unchanged; double distance: doubled
+ assert_eq!(scale_mv([8, -4], 2, 2), [8, -4]);
+ assert_eq!(scale_mv([8, -4], 1, 2), [16, -8]);
+ assert_eq!(scale_mv([8, -4], 2, -2), [-8, 4]);
+ }
+}
diff --git a/crates/hevc/src/params.rs b/crates/hevc/src/params.rs
new file mode 100644
index 000000000..d866f9214
--- /dev/null
+++ b/crates/hevc/src/params.rs
@@ -0,0 +1,919 @@
+//! Parameter sets: VPS (7.3.2.1), SPS (7.3.2.2), PPS (7.3.2.3), profile/tier/level, scaling lists
+//! (7.3.4), short-term reference picture sets (7.3.7) and VUI (E.2.1).
+
+use crate::error::{Result, ensure, unsupported};
+use crate::spec_tables::{DEFAULT_SCALING_INTER, DEFAULT_SCALING_INTRA};
+use crate::tables::scan_diag;
+use filmcraft_bitstream::BitReader;
+
+/// General profile / tier / level information.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct ProfileTierLevel {
+ pub profile_space: u8,
+ pub tier: bool,
+ pub profile_idc: u8,
+ pub compatibility: u32,
+ pub progressive_source: bool,
+ pub interlaced_source: bool,
+ pub level_idc: u8,
+}
+
+pub fn parse_ptl(r: &mut BitReader, profile_present: bool, max_sub_layers_minus1: u32) -> Result<ProfileTierLevel> {
+ let mut p = ProfileTierLevel::default();
+ if profile_present {
+ p.profile_space = r.read_bits(2)? as u8;
+ p.tier = r.read_flag()?;
+ p.profile_idc = r.read_bits(5)? as u8;
+ p.compatibility = r.read_bits(32)?;
+ p.progressive_source = r.read_flag()?;
+ p.interlaced_source = r.read_flag()?;
+ r.skip(2)?; // non_packed, frame_only
+ r.skip(43)?; // constraint flags / reserved bits (always 43 bits)
+ r.skip(1)?; // inbld / reserved
+ }
+ p.level_idc = r.read_bits(8)? as u8;
+ let n = max_sub_layers_minus1 as usize;
+ let mut sub_profile = [false; 8];
+ let mut sub_level = [false; 8];
+ for i in 0..n {
+ sub_profile[i] = r.read_flag()?;
+ sub_level[i] = r.read_flag()?;
+ }
+ if n > 0 {
+ for _ in n..8 {
+ r.skip(2)?;
+ }
+ }
+ for i in 0..n {
+ if sub_profile[i] {
+ r.skip(2 + 1 + 5 + 32 + 4 + 43 + 1)?;
+ }
+ if sub_level[i] {
+ r.skip(8)?;
+ }
+ }
+ Ok(p)
+}
+
+fn skip_sub_layer_hrd(r: &mut BitReader, cpb_cnt: u32, sub_pic: bool) -> Result<()> {
+ for _ in 0..cpb_cnt {
+ r.read_ue()?;
+ r.read_ue()?;
+ if sub_pic {
+ r.read_ue()?;
+ r.read_ue()?;
+ }
+ r.skip(1)?;
+ }
+ Ok(())
+}
+
+/// hrd_parameters() (E.2.2), skipped.
+pub fn skip_hrd(r: &mut BitReader, common: bool, max_sub_layers_minus1: u32) -> Result<()> {
+ let (mut nal, mut vcl, mut sub_pic) = (false, false, false);
+ if common {
+ nal = r.read_flag()?;
+ vcl = r.read_flag()?;
+ if nal || vcl {
+ sub_pic = r.read_flag()?;
+ if sub_pic {
+ r.skip(8 + 5 + 1 + 5)?;
+ }
+ r.skip(8)?;
+ if sub_pic {
+ r.skip(4)?;
+ }
+ r.skip(15)?;
+ }
+ }
+ for _ in 0..=max_sub_layers_minus1 {
+ let fixed_general = r.read_flag()?;
+ let fixed_cvs = if !fixed_general { r.read_flag()? } else { true };
+ let mut low_delay = false;
+ if fixed_cvs {
+ r.read_ue()?;
+ } else {
+ low_delay = r.read_flag()?;
+ }
+ let mut cpb_cnt = 1;
+ if !low_delay {
+ cpb_cnt = r.read_ue()? + 1;
+ ensure!(cpb_cnt <= 32, "cpb_cnt_minus1 out of range");
+ }
+ if nal {
+ skip_sub_layer_hrd(r, cpb_cnt, sub_pic)?;
+ }
+ if vcl {
+ skip_sub_layer_hrd(r, cpb_cnt, sub_pic)?;
+ }
+ }
+ Ok(())
+}
+
+/// Video parameter set (only the fields a single-layer decoder needs).
+#[derive(Clone, Debug)]
+pub struct Vps {
+ pub id: u8,
+ pub max_sub_layers_minus1: u32,
+ pub ptl: ProfileTierLevel,
+}
+
+impl Vps {
+ pub fn parse(rbsp: &[u8]) -> Result<Vps> {
+ let mut r = BitReader::new(rbsp);
+ let id = r.read_bits(4)? as u8;
+ r.skip(2 + 6)?;
+ let max_sub_layers_minus1 = r.read_bits(3)?;
+ r.skip(1 + 16)?;
+ let ptl = parse_ptl(&mut r, true, max_sub_layers_minus1)?;
+ Ok(Vps { id, max_sub_layers_minus1, ptl })
+ }
+}
+
+/// VUI fields relevant for output.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct Vui {
+ pub sar: (u16, u16),
+ pub full_range: bool,
+ pub colour_primaries: u8,
+ pub transfer_characteristics: u8,
+ pub matrix_coefficients: u8,
+ pub field_seq: bool,
+ pub timing: Option<(u32, u32)>,
+}
+
+impl Default for Vui {
+ fn default() -> Self {
+ Vui { sar: (0, 0), full_range: false, colour_primaries: 2, transfer_characteristics: 2, matrix_coefficients: 2, field_seq: false, timing: None }
+ }
+}
+
+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, max_sub_layers_minus1: u32) -> Result<Vui> {
+ let mut v = Vui::default();
+ if r.read_flag()? {
+ let idc = r.read_bits(8)?;
+ if idc == 255 {
+ v.sar = (r.read_bits(16)? as u16, r.read_bits(16)? as u16);
+ } else if (idc as usize) < SAR_TABLE.len() {
+ v.sar = SAR_TABLE[idc as usize];
+ }
+ }
+ if r.read_flag()? {
+ r.skip(1)?;
+ }
+ if r.read_flag()? {
+ r.skip(3)?;
+ 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()? {
+ r.read_ue()?;
+ r.read_ue()?;
+ }
+ r.skip(1)?; // neutral_chroma_indication_flag
+ v.field_seq = r.read_flag()?;
+ r.skip(1)?; // frame_field_info_present_flag
+ if r.read_flag()? {
+ for _ in 0..4 {
+ r.read_ue()?;
+ }
+ }
+ if r.read_flag()? {
+ let units = r.read_bits(32)?;
+ let scale = r.read_bits(32)?;
+ v.timing = Some((units, scale));
+ if r.read_flag()? {
+ r.read_ue()?;
+ }
+ if r.read_flag()? {
+ skip_hrd(r, true, max_sub_layers_minus1)?;
+ }
+ }
+ if r.read_flag()? {
+ r.skip(3)?;
+ for _ in 0..5 {
+ r.read_ue()?;
+ }
+ }
+ Ok(v)
+}
+
+/// Scaling list data (7.3.4) with prediction resolved: lists in up-right diagonal coefficient order.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct ScalingList {
+ /// [sizeId][matrixId][i]; sizeId 0 uses 16 entries.
+ pub lists: [[[u8; 64]; 6]; 4],
+ /// scaling_list_dc_coef for sizeId 2, 3.
+ pub dc: [[u8; 6]; 2],
+}
+
+impl ScalingList {
+ /// Default lists (Tables 7-5, 7-6).
+ pub fn default_lists() -> Self {
+ let mut lists = [[[16u8; 64]; 6]; 4];
+ for size in 1..4 {
+ for m in 0..6 {
+ lists[size][m] = if m < 3 { DEFAULT_SCALING_INTRA } else { DEFAULT_SCALING_INTER };
+ }
+ }
+ ScalingList { lists, dc: [[16; 6]; 2] }
+ }
+
+ pub fn parse(r: &mut BitReader) -> Result<Self> {
+ let mut sl = Self::default_lists();
+ for size in 0..4 {
+ let step = if size == 3 { 3 } else { 1 };
+ let mut m = 0;
+ while m < 6 {
+ let coef_num = if size == 0 { 16 } else { 64 };
+ if !r.read_flag()? {
+ let delta = r.read_ue()? as usize * step;
+ ensure!(delta <= m, "scaling_list_pred_matrix_id_delta out of range");
+ if delta == 0 {
+ // default list
+ let d = Self::default_lists();
+ sl.lists[size][m] = d.lists[size][m];
+ if size > 1 {
+ sl.dc[size - 2][m] = 16;
+ }
+ } else {
+ let rm = m - delta;
+ sl.lists[size][m] = sl.lists[size][rm];
+ if size > 1 {
+ sl.dc[size - 2][m] = sl.dc[size - 2][rm];
+ }
+ }
+ } else {
+ let mut next: i32 = 8;
+ if size > 1 {
+ let dc = r.read_se()?;
+ ensure!((-7..=247).contains(&dc), "scaling_list_dc_coef_minus8 out of range");
+ next = dc + 8;
+ sl.dc[size - 2][m] = next as u8;
+ }
+ for i in 0..coef_num {
+ let d = r.read_se()?;
+ ensure!((-128..=127).contains(&d), "scaling_list_delta_coef out of range");
+ next = (next + d + 256).rem_euclid(256);
+ sl.lists[size][m][i] = next as u8;
+ }
+ }
+ m += step;
+ }
+ }
+ // 32x32 chroma lists (only used for ChromaArrayType 3) are copied from the 16x16 ones.
+ for m in [1, 2, 4, 5] {
+ sl.lists[3][m] = sl.lists[2][m];
+ sl.dc[1][m] = sl.dc[0][m];
+ }
+ Ok(sl)
+ }
+
+ /// ScalingFactor for sizeId (log2 size = sizeId + 2) and matrixId as a row-major [y][x] matrix
+ /// (7-44..7-48).
+ pub fn factor(&self, size_id: usize, matrix_id: usize) -> Vec<u8> {
+ let n = 4usize << size_id;
+ let mut out = vec![0u8; n * n];
+ if size_id == 0 {
+ let scan = scan_diag(2);
+ for (i, &(x, y)) in scan.iter().enumerate() {
+ out[y as usize * 4 + x as usize] = self.lists[0][matrix_id][i];
+ }
+ return out;
+ }
+ let rep = n / 8;
+ let scan = scan_diag(3);
+ for (i, &(x, y)) in scan.iter().enumerate() {
+ let v = self.lists[size_id][matrix_id][i];
+ for j in 0..rep {
+ for k in 0..rep {
+ out[(y as usize * rep + j) * n + x as usize * rep + k] = v;
+ }
+ }
+ }
+ if size_id >= 2 {
+ out[0] = self.dc[size_id - 2][matrix_id];
+ }
+ out
+ }
+}
+
+/// A short-term reference picture set (7.4.8), resolved.
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct StRps {
+ /// DeltaPocS0 (negative, decreasing) with UsedByCurrPicS0.
+ pub s0: Vec<(i32, bool)>,
+ /// DeltaPocS1 (positive, increasing) with UsedByCurrPicS1.
+ pub s1: Vec<(i32, bool)>,
+}
+
+impl StRps {
+ pub fn num_delta_pocs(&self) -> usize {
+ self.s0.len() + self.s1.len()
+ }
+
+ /// st_ref_pic_set(idx) with the previously parsed candidate sets `sets` (idx == sets.len() for a
+ /// slice-header RPS).
+ pub fn parse(r: &mut BitReader, idx: usize, sets: &[StRps], num_sets: usize) -> Result<StRps> {
+ let inter = if idx != 0 { r.read_flag()? } else { false };
+ if inter {
+ let delta_idx = if idx == num_sets { r.read_ue()? as usize + 1 } else { 1 };
+ ensure!(delta_idx <= idx, "delta_idx_minus1 out of range");
+ let rf = &sets[idx - delta_idx];
+ let sign = r.read_flag()?;
+ let abs = r.read_ue()? as i32 + 1;
+ ensure!(abs <= 1 << 15, "abs_delta_rps_minus1 out of range");
+ let delta_rps = if sign { -abs } else { abs };
+ let n = rf.num_delta_pocs();
+ let mut used = vec![false; n + 1];
+ let mut use_delta = vec![true; n + 1];
+ for j in 0..=n {
+ used[j] = r.read_flag()?;
+ if !used[j] {
+ use_delta[j] = r.read_flag()?;
+ }
+ }
+ let nneg = rf.s0.len();
+ let mut out = StRps::default();
+ for j in (0..rf.s1.len()).rev() {
+ let d = rf.s1[j].0 + delta_rps;
+ if d < 0 && use_delta[nneg + j] {
+ out.s0.push((d, used[nneg + j]));
+ }
+ }
+ if delta_rps < 0 && use_delta[n] {
+ out.s0.push((delta_rps, used[n]));
+ }
+ for j in 0..nneg {
+ let d = rf.s0[j].0 + delta_rps;
+ if d < 0 && use_delta[j] {
+ out.s0.push((d, used[j]));
+ }
+ }
+ for j in (0..nneg).rev() {
+ let d = rf.s0[j].0 + delta_rps;
+ if d > 0 && use_delta[j] {
+ out.s1.push((d, used[j]));
+ }
+ }
+ if delta_rps > 0 && use_delta[n] {
+ out.s1.push((delta_rps, used[n]));
+ }
+ for j in 0..rf.s1.len() {
+ let d = rf.s1[j].0 + delta_rps;
+ if d > 0 && use_delta[nneg + j] {
+ out.s1.push((d, used[nneg + j]));
+ }
+ }
+ ensure!(out.num_delta_pocs() <= 16, "too many pictures in RPS");
+ Ok(out)
+ } else {
+ let nneg = r.read_ue()? as usize;
+ let npos = r.read_ue()? as usize;
+ ensure!(nneg <= 16 && npos <= 16 && nneg + npos <= 16, "too many pictures in RPS");
+ let mut out = StRps::default();
+ let mut poc = 0i32;
+ for _ in 0..nneg {
+ let d = r.read_ue()? as i32 + 1;
+ ensure!(d <= 1 << 15, "delta_poc_s0_minus1 out of range");
+ poc -= d;
+ out.s0.push((poc, r.read_flag()?));
+ }
+ poc = 0;
+ for _ in 0..npos {
+ let d = r.read_ue()? as i32 + 1;
+ ensure!(d <= 1 << 15, "delta_poc_s1_minus1 out of range");
+ poc += d;
+ out.s1.push((poc, r.read_flag()?));
+ }
+ Ok(out)
+ }
+ }
+}
+
+/// Sequence parameter set.
+#[derive(Clone, Debug)]
+pub struct Sps {
+ pub vps_id: u8,
+ pub max_sub_layers_minus1: u32,
+ pub ptl: ProfileTierLevel,
+ pub id: u32,
+ pub chroma_format_idc: u32,
+ pub separate_colour_plane: bool,
+ pub width: u32,
+ pub height: u32,
+ /// Conformance window in luma samples (left, right, top, bottom).
+ pub conf_win: (u32, u32, u32, u32),
+ pub bit_depth_luma: u32,
+ pub bit_depth_chroma: u32,
+ pub log2_max_poc_lsb: u32,
+ pub max_dec_pic_buffering: u32,
+ pub max_num_reorder: u32,
+ pub max_latency_increase_plus1: u32,
+ pub log2_min_cb: u32,
+ pub log2_ctb: u32,
+ pub log2_min_tb: u32,
+ pub log2_max_tb: u32,
+ pub max_th_depth_inter: u32,
+ pub max_th_depth_intra: u32,
+ pub scaling_list_enabled: bool,
+ /// SPS-level scaling list (defaults when enabled without data).
+ pub scaling_list: Option<ScalingList>,
+ pub amp: bool,
+ pub sao: bool,
+ pub pcm: bool,
+ pub pcm_bit_depth_luma: u32,
+ pub pcm_bit_depth_chroma: u32,
+ pub log2_min_pcm: u32,
+ pub log2_max_pcm: u32,
+ pub pcm_loop_filter_disabled: bool,
+ pub st_rps: Vec<StRps>,
+ pub long_term_refs_present: bool,
+ /// lt_ref_pic_poc_lsb_sps, used_by_curr_pic_lt_sps_flag.
+ pub lt_ref_pics: Vec<(u32, bool)>,
+ pub temporal_mvp: bool,
+ pub strong_intra_smoothing: bool,
+ pub vui: Option<Vui>,
+ /// Range extension flags that change decoding (any set -> unsupported for now).
+ pub range_extension: bool,
+ pub extension_flags: u8,
+}
+
+impl Sps {
+ pub fn parse(rbsp: &[u8]) -> Result<Sps> {
+ let mut r = BitReader::new(rbsp);
+ let vps_id = r.read_bits(4)? as u8;
+ let max_sub_layers_minus1 = r.read_bits(3)?;
+ ensure!(max_sub_layers_minus1 <= 6, "sps_max_sub_layers_minus1 out of range");
+ r.skip(1)?;
+ let ptl = parse_ptl(&mut r, true, max_sub_layers_minus1)?;
+ let id = r.read_ue()?;
+ ensure!(id < 16, "sps_seq_parameter_set_id out of range");
+ let chroma_format_idc = r.read_ue()?;
+ ensure!(chroma_format_idc <= 3, "chroma_format_idc out of range");
+ let separate_colour_plane = if chroma_format_idc == 3 { r.read_flag()? } else { false };
+ let width = r.read_ue()?;
+ let height = r.read_ue()?;
+ ensure!(width > 0 && height > 0 && width <= 16888 && height <= 16888, "picture size {width}x{height} out of range");
+ let mut conf_win = (0, 0, 0, 0);
+ if r.read_flag()? {
+ conf_win = (r.read_ue()?, r.read_ue()?, r.read_ue()?, r.read_ue()?);
+ }
+ let bit_depth_luma = r.read_ue()? + 8;
+ let bit_depth_chroma = r.read_ue()? + 8;
+ ensure!(bit_depth_luma <= 16 && bit_depth_chroma <= 16, "bit depth out of range");
+ let log2_max_poc_lsb = r.read_ue()? + 4;
+ ensure!(log2_max_poc_lsb <= 16, "log2_max_pic_order_cnt_lsb_minus4 out of range");
+ let ordering_all = r.read_flag()?;
+ let (mut dpb, mut reorder, mut latency) = (1, 0, 0);
+ let start = if ordering_all { 0 } else { max_sub_layers_minus1 };
+ for _ in start..=max_sub_layers_minus1 {
+ // the values of the highest sub-layer are used
+ dpb = r.read_ue()? + 1;
+ reorder = r.read_ue()?;
+ latency = r.read_ue()?;
+ }
+ ensure!(dpb <= 16 && reorder <= 16, "sps_max_dec_pic_buffering out of range");
+ let log2_min_cb = r.read_ue()? + 3;
+ let log2_ctb = log2_min_cb + r.read_ue()?;
+ let log2_min_tb = r.read_ue()? + 2;
+ let log2_max_tb = log2_min_tb + r.read_ue()?;
+ ensure!((4..=6).contains(&log2_ctb) && log2_min_cb <= log2_ctb, "CTB size out of range");
+ ensure!(log2_min_tb < log2_min_cb && log2_max_tb <= log2_ctb.min(5), "transform block sizes out of range");
+ ensure!(width % (1 << log2_min_cb) == 0 && height % (1 << log2_min_cb) == 0, "picture size not a multiple of MinCbSizeY");
+ let max_th_depth_inter = r.read_ue()?;
+ let max_th_depth_intra = r.read_ue()?;
+ ensure!(max_th_depth_inter <= log2_ctb - log2_min_tb && max_th_depth_intra <= log2_ctb - log2_min_tb, "transform hierarchy depth out of range");
+ let scaling_list_enabled = r.read_flag()?;
+ let mut scaling_list = None;
+ if scaling_list_enabled {
+ scaling_list = Some(if r.read_flag()? { ScalingList::parse(&mut r)? } else { ScalingList::default_lists() });
+ }
+ let amp = r.read_flag()?;
+ let sao = r.read_flag()?;
+ let pcm = r.read_flag()?;
+ let (mut pcm_bit_depth_luma, mut pcm_bit_depth_chroma, mut log2_min_pcm, mut log2_max_pcm, mut pcm_loop_filter_disabled) = (8, 8, 0, 0, false);
+ if pcm {
+ pcm_bit_depth_luma = r.read_bits(4)? + 1;
+ pcm_bit_depth_chroma = r.read_bits(4)? + 1;
+ log2_min_pcm = r.read_ue()? + 3;
+ log2_max_pcm = log2_min_pcm + r.read_ue()?;
+ pcm_loop_filter_disabled = r.read_flag()?;
+ ensure!(pcm_bit_depth_luma <= bit_depth_luma && pcm_bit_depth_chroma <= bit_depth_chroma, "PCM bit depth out of range");
+ ensure!(log2_max_pcm <= log2_ctb.min(5), "PCM size out of range");
+ }
+ let num_st = r.read_ue()? as usize;
+ ensure!(num_st <= 64, "num_short_term_ref_pic_sets out of range");
+ let mut st_rps = Vec::with_capacity(num_st);
+ for i in 0..num_st {
+ let s = StRps::parse(&mut r, i, &st_rps, num_st)?;
+ st_rps.push(s);
+ }
+ let long_term_refs_present = r.read_flag()?;
+ let mut lt_ref_pics = Vec::new();
+ if long_term_refs_present {
+ let n = r.read_ue()?;
+ ensure!(n <= 32, "num_long_term_ref_pics_sps out of range");
+ for _ in 0..n {
+ lt_ref_pics.push((r.read_bits(log2_max_poc_lsb)?, r.read_flag()?));
+ }
+ }
+ let temporal_mvp = r.read_flag()?;
+ let strong_intra_smoothing = r.read_flag()?;
+ let vui = if r.read_flag()? { Some(parse_vui(&mut r, max_sub_layers_minus1)?) } else { None };
+ let mut range_extension = false;
+ let mut extension_flags = 0;
+ if r.read_flag()? {
+ extension_flags = r.read_bits(8)? as u8;
+ if extension_flags & 0x80 != 0 {
+ // sps_range_extension(): any enabled tool is outside Main / Main 10
+ let bits = r.read_bits(9)?;
+ range_extension = bits != 0;
+ }
+ }
+ Ok(Sps {
+ vps_id,
+ max_sub_layers_minus1,
+ ptl,
+ id,
+ chroma_format_idc,
+ separate_colour_plane,
+ width,
+ height,
+ conf_win,
+ bit_depth_luma,
+ bit_depth_chroma,
+ log2_max_poc_lsb,
+ max_dec_pic_buffering: dpb,
+ max_num_reorder: reorder,
+ max_latency_increase_plus1: latency,
+ log2_min_cb,
+ log2_ctb,
+ log2_min_tb,
+ log2_max_tb,
+ max_th_depth_inter,
+ max_th_depth_intra,
+ scaling_list_enabled,
+ scaling_list,
+ amp,
+ sao,
+ pcm,
+ pcm_bit_depth_luma,
+ pcm_bit_depth_chroma,
+ log2_min_pcm,
+ log2_max_pcm,
+ pcm_loop_filter_disabled,
+ st_rps,
+ long_term_refs_present,
+ lt_ref_pics,
+ temporal_mvp,
+ strong_intra_smoothing,
+ vui,
+ range_extension,
+ extension_flags,
+ })
+ }
+
+ /// ChromaArrayType.
+ pub fn chroma_array_type(&self) -> u32 {
+ if self.separate_colour_plane { 0 } else { self.chroma_format_idc }
+ }
+ pub fn sub_width_c(&self) -> u32 {
+ if self.chroma_format_idc == 1 || self.chroma_format_idc == 2 { 2 } else { 1 }
+ }
+ pub fn sub_height_c(&self) -> u32 {
+ if self.chroma_format_idc == 1 { 2 } else { 1 }
+ }
+ pub fn ctb_size(&self) -> u32 {
+ 1 << self.log2_ctb
+ }
+ pub fn pic_width_in_ctbs(&self) -> u32 {
+ self.width.div_ceil(self.ctb_size())
+ }
+ pub fn pic_height_in_ctbs(&self) -> u32 {
+ self.height.div_ceil(self.ctb_size())
+ }
+ pub fn max_poc_lsb(&self) -> i32 {
+ 1 << self.log2_max_poc_lsb
+ }
+
+ /// Cropped output rectangle (x, y, width, height) in luma samples.
+ pub fn crop_rect(&self) -> (u32, u32, u32, u32) {
+ let (l, r, t, b) = self.conf_win;
+ let (sw, sh) = (self.sub_width_c(), self.sub_height_c());
+ let x = (l * sw).min(self.width - 1);
+ let y = (t * sh).min(self.height - 1);
+ let w = self.width.saturating_sub(x + r * sw).max(1);
+ let h = self.height.saturating_sub(y + b * sh).max(1);
+ (x, y, w, h)
+ }
+
+ /// Features this decoder does not handle yet.
+ pub fn check_supported(&self) -> Result<()> {
+ if self.chroma_format_idc != 1 {
+ return unsupported(format!("chroma_format_idc {} (only 4:2:0)", self.chroma_format_idc));
+ }
+ if self.bit_depth_luma > 12 || self.bit_depth_chroma > 12 {
+ return unsupported(format!("bit depth {}/{}", self.bit_depth_luma, self.bit_depth_chroma));
+ }
+ if self.range_extension {
+ return unsupported("SPS range extension tools");
+ }
+ if self.extension_flags & 0x7f != 0 {
+ return unsupported("SPS multilayer / 3D / SCC extensions");
+ }
+ Ok(())
+ }
+}
+
+/// Picture parameter set.
+#[derive(Clone, Debug)]
+pub struct Pps {
+ pub id: u32,
+ pub sps_id: u32,
+ pub dependent_slice_segments_enabled: bool,
+ pub output_flag_present: bool,
+ pub num_extra_slice_header_bits: u32,
+ pub sign_data_hiding: bool,
+ pub cabac_init_present: bool,
+ pub num_ref_idx_l0_default: u32,
+ pub num_ref_idx_l1_default: u32,
+ pub init_qp: i32,
+ pub constrained_intra_pred: bool,
+ pub transform_skip: bool,
+ pub cu_qp_delta_enabled: bool,
+ pub diff_cu_qp_delta_depth: u32,
+ pub cb_qp_offset: i32,
+ pub cr_qp_offset: i32,
+ pub slice_chroma_qp_offsets_present: bool,
+ pub weighted_pred: bool,
+ pub weighted_bipred: bool,
+ pub transquant_bypass: bool,
+ pub tiles_enabled: bool,
+ pub entropy_coding_sync: bool,
+ pub num_tile_columns: u32,
+ pub num_tile_rows: u32,
+ pub uniform_spacing: bool,
+ /// column_width_minus1 + 1 (explicit spacing only).
+ pub column_widths: Vec<u32>,
+ pub row_heights: Vec<u32>,
+ pub loop_filter_across_tiles: bool,
+ pub loop_filter_across_slices: bool,
+ pub deblocking_control_present: bool,
+ pub deblocking_override_enabled: bool,
+ pub deblocking_disabled: bool,
+ pub beta_offset_div2: i32,
+ pub tc_offset_div2: i32,
+ pub scaling_list: Option<ScalingList>,
+ pub lists_modification_present: bool,
+ pub log2_parallel_merge_level: u32,
+ pub slice_header_extension_present: bool,
+ pub range_extension: bool,
+ pub extension_flags: u8,
+}
+
+impl Pps {
+ pub fn parse(rbsp: &[u8]) -> Result<Pps> {
+ let mut r = BitReader::new(rbsp);
+ let id = r.read_ue()?;
+ ensure!(id < 64, "pps_pic_parameter_set_id out of range");
+ let sps_id = r.read_ue()?;
+ ensure!(sps_id < 16, "pps_seq_parameter_set_id out of range");
+ let dependent_slice_segments_enabled = r.read_flag()?;
+ let output_flag_present = r.read_flag()?;
+ let num_extra_slice_header_bits = r.read_bits(3)?;
+ let sign_data_hiding = r.read_flag()?;
+ let cabac_init_present = r.read_flag()?;
+ let num_ref_idx_l0_default = r.read_ue()? + 1;
+ let num_ref_idx_l1_default = r.read_ue()? + 1;
+ ensure!(num_ref_idx_l0_default <= 15 && num_ref_idx_l1_default <= 15, "num_ref_idx_default_active out of range");
+ let init_qp = 26 + r.read_se()?;
+ let constrained_intra_pred = r.read_flag()?;
+ let transform_skip = r.read_flag()?;
+ let cu_qp_delta_enabled = r.read_flag()?;
+ let diff_cu_qp_delta_depth = if cu_qp_delta_enabled { r.read_ue()? } else { 0 };
+ ensure!(diff_cu_qp_delta_depth <= 3, "diff_cu_qp_delta_depth out of range");
+ let cb_qp_offset = r.read_se()?;
+ let cr_qp_offset = r.read_se()?;
+ ensure!((-12..=12).contains(&cb_qp_offset) && (-12..=12).contains(&cr_qp_offset), "chroma QP offset out of range");
+ let slice_chroma_qp_offsets_present = r.read_flag()?;
+ let weighted_pred = r.read_flag()?;
+ let weighted_bipred = r.read_flag()?;
+ let transquant_bypass = r.read_flag()?;
+ let tiles_enabled = r.read_flag()?;
+ let entropy_coding_sync = r.read_flag()?;
+ let (mut num_tile_columns, mut num_tile_rows, mut uniform_spacing) = (1, 1, true);
+ let (mut column_widths, mut row_heights) = (Vec::new(), Vec::new());
+ let mut loop_filter_across_tiles = true;
+ if tiles_enabled {
+ num_tile_columns = r.read_ue()? + 1;
+ num_tile_rows = r.read_ue()? + 1;
+ ensure!(num_tile_columns <= 64 && num_tile_rows <= 64, "too many tiles");
+ uniform_spacing = r.read_flag()?;
+ if !uniform_spacing {
+ for _ in 0..num_tile_columns - 1 {
+ column_widths.push(r.read_ue()?.saturating_add(1));
+ }
+ for _ in 0..num_tile_rows - 1 {
+ row_heights.push(r.read_ue()?.saturating_add(1));
+ }
+ }
+ loop_filter_across_tiles = r.read_flag()?;
+ }
+ let loop_filter_across_slices = r.read_flag()?;
+ let deblocking_control_present = r.read_flag()?;
+ let (mut deblocking_override_enabled, mut deblocking_disabled, mut beta_offset_div2, mut tc_offset_div2) = (false, false, 0, 0);
+ if deblocking_control_present {
+ deblocking_override_enabled = r.read_flag()?;
+ deblocking_disabled = r.read_flag()?;
+ if !deblocking_disabled {
+ beta_offset_div2 = r.read_se()?;
+ tc_offset_div2 = r.read_se()?;
+ ensure!((-6..=6).contains(&beta_offset_div2) && (-6..=6).contains(&tc_offset_div2), "deblocking offsets out of range");
+ }
+ }
+ let scaling_list = if r.read_flag()? { Some(ScalingList::parse(&mut r)?) } else { None };
+ let lists_modification_present = r.read_flag()?;
+ let log2_parallel_merge_level = r.read_ue()? + 2;
+ ensure!(log2_parallel_merge_level <= 6, "log2_parallel_merge_level out of range");
+ let slice_header_extension_present = r.read_flag()?;
+ let mut range_extension = false;
+ let mut extension_flags = 0;
+ if r.read_flag()? {
+ extension_flags = r.read_bits(8)? as u8;
+ if extension_flags & 0x80 != 0 {
+ // pps_range_extension(): treated as unsupported when it enables anything
+ let mut any = false;
+ if transform_skip {
+ any |= r.read_ue()? != 0;
+ }
+ any |= r.read_flag()?; // cross_component_prediction
+ any |= r.read_flag()?; // chroma_qp_offset_list
+ range_extension = any;
+ }
+ }
+ Ok(Pps {
+ id,
+ sps_id,
+ dependent_slice_segments_enabled,
+ output_flag_present,
+ num_extra_slice_header_bits,
+ sign_data_hiding,
+ cabac_init_present,
+ num_ref_idx_l0_default,
+ num_ref_idx_l1_default,
+ init_qp,
+ constrained_intra_pred,
+ transform_skip,
+ cu_qp_delta_enabled,
+ diff_cu_qp_delta_depth,
+ cb_qp_offset,
+ cr_qp_offset,
+ slice_chroma_qp_offsets_present,
+ weighted_pred,
+ weighted_bipred,
+ transquant_bypass,
+ tiles_enabled,
+ entropy_coding_sync,
+ num_tile_columns,
+ num_tile_rows,
+ uniform_spacing,
+ column_widths,
+ row_heights,
+ loop_filter_across_tiles,
+ loop_filter_across_slices,
+ deblocking_control_present,
+ deblocking_override_enabled,
+ deblocking_disabled,
+ beta_offset_div2,
+ tc_offset_div2,
+ scaling_list,
+ lists_modification_present,
+ log2_parallel_merge_level,
+ slice_header_extension_present,
+ range_extension,
+ extension_flags,
+ })
+ }
+
+ pub fn check_supported(&self) -> Result<()> {
+ if self.range_extension {
+ return unsupported("PPS range extension tools");
+ }
+ if self.extension_flags & 0x7f != 0 {
+ return unsupported("PPS multilayer / 3D / SCC extensions");
+ }
+ Ok(())
+ }
+}
+
+/// CTB addressing for a PPS/SPS pair: tile boundaries and the raster <-> tile scan conversion
+/// (6.5.1).
+#[derive(Clone, Debug)]
+pub struct Layout {
+ pub width_ctbs: u32,
+ pub height_ctbs: u32,
+ /// Tile column boundaries in CTBs (num_tile_columns + 1 entries).
+ pub col_bd: Vec<u32>,
+ pub row_bd: Vec<u32>,
+ pub rs_to_ts: Vec<u32>,
+ pub ts_to_rs: Vec<u32>,
+ pub tile_id: Vec<u32>,
+}
+
+impl Layout {
+ pub fn new(sps: &Sps, pps: &Pps) -> Result<Layout> {
+ let (w, h) = (sps.pic_width_in_ctbs(), sps.pic_height_in_ctbs());
+ let (nc, nr) = (pps.num_tile_columns, pps.num_tile_rows);
+ ensure!(nc <= w && nr <= h, "more tiles than CTBs");
+ let mut colw = Vec::new();
+ let mut rowh = Vec::new();
+ if pps.uniform_spacing {
+ for i in 0..nc {
+ colw.push((i + 1) * w / nc - i * w / nc);
+ }
+ for j in 0..nr {
+ rowh.push((j + 1) * h / nr - j * h / nr);
+ }
+ } else {
+ let sw: u64 = pps.column_widths.iter().map(|&v| v as u64).sum();
+ let sh: u64 = pps.row_heights.iter().map(|&v| v as u64).sum();
+ ensure!(sw < w as u64 && sh < h as u64, "tile sizes exceed the picture");
+ colw.extend_from_slice(&pps.column_widths);
+ colw.push(w - sw as u32);
+ rowh.extend_from_slice(&pps.row_heights);
+ rowh.push(h - sh as u32);
+ }
+ let mut col_bd = vec![0];
+ for c in &colw {
+ col_bd.push(col_bd.last().unwrap() + c);
+ }
+ let mut row_bd = vec![0];
+ for r in &rowh {
+ row_bd.push(row_bd.last().unwrap() + r);
+ }
+ let n = (w * h) as usize;
+ let mut rs_to_ts = vec![0u32; n];
+ for rs in 0..w * h {
+ let (tbx, tby) = (rs % w, rs / w);
+ let tile_x = (0..nc as usize).rev().find(|&i| tbx >= col_bd[i]).unwrap_or(0);
+ let tile_y = (0..nr as usize).rev().find(|&j| tby >= row_bd[j]).unwrap_or(0);
+ let mut v = 0;
+ for i in 0..tile_x {
+ v += rowh[tile_y] * colw[i];
+ }
+ for j in 0..tile_y {
+ v += w * rowh[j];
+ }
+ v += (tby - row_bd[tile_y]) * colw[tile_x] + tbx - col_bd[tile_x];
+ rs_to_ts[rs as usize] = v;
+ }
+ let mut ts_to_rs = vec![0u32; n];
+ for rs in 0..n {
+ ts_to_rs[rs_to_ts[rs] as usize] = rs as u32;
+ }
+ let mut tile_id = vec![0u32; n];
+ let mut tid = 0;
+ for j in 0..nr as usize {
+ for i in 0..nc as usize {
+ for y in row_bd[j]..row_bd[j + 1] {
+ for x in col_bd[i]..col_bd[i + 1] {
+ tile_id[rs_to_ts[(y * w + x) as usize] as usize] = tid;
+ }
+ }
+ tid += 1;
+ }
+ }
+ Ok(Layout { width_ctbs: w, height_ctbs: h, col_bd, row_bd, rs_to_ts, ts_to_rs, tile_id })
+ }
+
+ /// Tile id of the CTB at raster address `rs`.
+ #[inline]
+ pub fn tile_of_rs(&self, rs: u32) -> u32 {
+ self.tile_id[self.rs_to_ts[rs as usize] as usize]
+ }
+}
diff --git a/crates/hevc/src/picture.rs b/crates/hevc/src/picture.rs
new file mode 100644
index 000000000..5aadbf6e2
--- /dev/null
+++ b/crates/hevc/src/picture.rs
@@ -0,0 +1,215 @@
+//! Decoded picture storage shared between decoding jobs: CTB rows are published once final (after
+//! deblocking and SAO) together with the compressed motion field used for temporal motion vector
+//! prediction.
+
+use std::sync::{Arc, OnceLock};
+
+/// Motion data of one 16x16 block of a decoded picture (8.5.3.2.9 uses the motion of the top-left
+/// 4x4 block of each 16x16 block).
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct ColMv {
+ pub mv: [[i16; 2]; 2],
+ /// POC of the referenced picture per list.
+ pub ref_poc: [i32; 2],
+ /// bit0/1: predFlagL0/L1, bit2/3: reference is long-term (L0/L1). 0 = intra / unavailable.
+ pub flags: u8,
+}
+
+/// One published CTB row.
+pub struct FrameRow {
+ /// Luma lines of the row (stride = picture width).
+ pub y: Box<[u16]>,
+ pub cb: Box<[u16]>,
+ pub cr: Box<[u16]>,
+ /// Motion per 16x16 block: (width16 * rows16) entries, raster within the row.
+ pub col: Box<[ColMv]>,
+}
+
+/// A decoded (or in-progress) picture as stored in the DPB and referenced by later pictures.
+pub struct Frame {
+ pub id: u32,
+ pub poc: i32,
+ pub width: usize,
+ pub height: usize,
+ pub cwidth: usize,
+ pub cheight: usize,
+ pub log2_ctb: u32,
+ pub bit_depth: u32,
+ pub bit_depth_c: u32,
+ rows: Box<[OnceLock<FrameRow>]>,
+}
+
+impl Frame {
+ pub fn new(id: u32, poc: i32, width: usize, height: usize, log2_ctb: u32, bit_depth: u32, bit_depth_c: u32) -> Self {
+ let n = height.div_ceil(1 << log2_ctb);
+ Frame {
+ id,
+ poc,
+ width,
+ height,
+ cwidth: width / 2,
+ cheight: height / 2,
+ log2_ctb,
+ bit_depth,
+ bit_depth_c,
+ rows: (0..n).map(|_| OnceLock::new()).collect(),
+ }
+ }
+
+ pub fn num_rows(&self) -> usize {
+ self.rows.len()
+ }
+
+ /// Number of luma lines in CTB row `r`.
+ pub fn row_lines(&self, r: usize) -> usize {
+ let ctb = 1usize << self.log2_ctb;
+ ctb.min(self.height - r * ctb)
+ }
+
+ pub fn width16(&self) -> usize {
+ self.width.div_ceil(16)
+ }
+
+ /// Publish CTB row `r` (ignored if already published).
+ pub fn publish(&self, r: usize, row: FrameRow) {
+ let _ = self.rows[r].set(row);
+ }
+
+ pub fn is_published(&self, r: usize) -> bool {
+ self.rows[r].get().is_some()
+ }
+
+ pub fn is_complete(&self) -> bool {
+ self.rows.last().is_none_or(|r| r.get().is_some())
+ }
+
+ /// CTB row `r`, waiting until it has been published.
+ #[inline]
+ pub fn row(&self, r: usize) -> &FrameRow {
+ #[cfg(feature = "threads")]
+ {
+ self.rows[r].wait()
+ }
+ #[cfg(not(feature = "threads"))]
+ {
+ self.rows[r].get().expect("reference row decoded before use")
+ }
+ }
+
+ pub fn wait_complete(&self) {
+ for r in 0..self.rows.len() {
+ self.row(r);
+ }
+ }
+
+ /// Motion of the 16x16 block containing luma sample (x, y) (inside the picture).
+ #[inline]
+ pub fn col_mv(&self, x: usize, y: usize) -> ColMv {
+ let r = y >> self.log2_ctb;
+ let row = self.row(r);
+ let y16 = (y & ((1 << self.log2_ctb) - 1)) >> 4;
+ row.col[y16 * self.width16() + (x >> 4)]
+ }
+
+ /// Copy a w x h luma window at (x0, y0) with edge replication into `out` (stride `os`).
+ pub fn luma_window(&self, x0: i32, y0: i32, w: usize, h: usize, out: &mut [i16], os: usize) {
+ let (width, height) = (self.width as i32, self.height as i32);
+ let sh = self.log2_ctb;
+ let mask = (1i32 << sh) - 1;
+ for r in 0..h {
+ let yy = (y0 + r as i32).clamp(0, height - 1);
+ let row = self.row((yy >> sh) as usize);
+ let off = ((yy & mask) * width) as usize;
+ copy_line(&row.y[off..off + width as usize], x0, &mut out[r * os..r * os + w]);
+ }
+ }
+
+ /// Copy a w x h window of chroma component `c` (0 = Cb, 1 = Cr) with edge replication.
+ pub fn chroma_window(&self, c: usize, x0: i32, y0: i32, w: usize, h: usize, out: &mut [i16], os: usize) {
+ let (cw, ch) = (self.cwidth as i32, self.cheight as i32);
+ let sh = self.log2_ctb - 1;
+ let mask = (1i32 << sh) - 1;
+ for r in 0..h {
+ let yy = (y0 + r as i32).clamp(0, ch - 1);
+ let row = self.row((yy >> sh) as usize);
+ let plane = if c == 0 { &row.cb } else { &row.cr };
+ let off = ((yy & mask) * cw) as usize;
+ copy_line(&plane[off..off + cw as usize], x0, &mut out[r * os..r * os + w]);
+ }
+ }
+
+ /// Crop and copy the frame into planar buffers (waits for completion).
+ pub fn copy_cropped(&self, crop: (usize, usize, usize, usize)) -> (Vec<u16>, Vec<u16>, Vec<u16>) {
+ let (cx, cy, cw, ch) = crop;
+ let ctb = 1usize << self.log2_ctb;
+ let mut y = Vec::with_capacity(cw * ch);
+ for r in cy..cy + ch {
+ let row = self.row(r / ctb);
+ let o = (r % ctb) * self.width + cx;
+ y.extend_from_slice(&row.y[o..o + cw]);
+ }
+ let (ccx, ccy, ccw, cch) = (cx / 2, cy / 2, cw.div_ceil(2), ch.div_ceil(2));
+ let cctb = ctb / 2;
+ let mut u = Vec::with_capacity(ccw * cch);
+ let mut v = Vec::with_capacity(ccw * cch);
+ for r in ccy..ccy + cch {
+ let row = self.row(r / cctb);
+ let o = (r % cctb) * self.cwidth + ccx;
+ u.extend_from_slice(&row.cb[o..o + ccw]);
+ v.extend_from_slice(&row.cr[o..o + ccw]);
+ }
+ (y, u, v)
+ }
+
+ /// A frame with every row published from full-picture planes and no motion (used to replace missing
+ /// reference pictures).
+ pub fn from_planes(id: u32, poc: i32, like: &Frame, y: &[u16], cb: &[u16], cr: &[u16]) -> Frame {
+ let f = Frame::new(id, poc, like.width, like.height, like.log2_ctb, like.bit_depth, like.bit_depth_c);
+ let ctb = 1usize << f.log2_ctb;
+ let w16 = f.width16();
+ for r in 0..f.num_rows() {
+ let lines = f.row_lines(r);
+ let (y0, y1) = (r * ctb * f.width, (r * ctb + lines) * f.width);
+ let clines = lines.div_ceil(2);
+ let (c0, c1) = (r * ctb / 2 * f.cwidth, (r * ctb / 2 + clines) * f.cwidth);
+ f.publish(
+ r,
+ FrameRow { y: y[y0..y1].into(), cb: cb[c0..c1].into(), cr: cr[c0..c1].into(), col: vec![ColMv::default(); w16 * lines.div_ceil(16)].into() },
+ );
+ }
+ f
+ }
+
+ /// A mid-grey frame with the geometry of `like`.
+ pub fn gray(id: u32, poc: i32, like: &Frame) -> Frame {
+ let y = vec![1u16 << (like.bit_depth - 1); like.width * like.height];
+ let c = vec![1u16 << (like.bit_depth_c - 1); like.cwidth * like.cheight];
+ Frame::from_planes(id, poc, like, &y, &c, &c)
+ }
+}
+
+/// Copy `out.len()` samples of `line` starting at x0, replicating edge samples outside the line.
+#[inline(always)]
+fn copy_line(line: &[u16], x0: i32, out: &mut [i16]) {
+ let w = out.len();
+ if x0 >= 0 && x0 as usize + w <= line.len() {
+ for (o, &s) in out.iter_mut().zip(&line[x0 as usize..x0 as usize + w]) {
+ *o = s as i16;
+ }
+ } else {
+ let max = line.len() as i32 - 1;
+ for (c, o) in out.iter_mut().enumerate() {
+ *o = line[(x0 + c as i32).clamp(0, max) as usize] as i16;
+ }
+ }
+}
+
+pub type FrameRef = Arc<Frame>;
+
+/// An entry of RefPicList0/1 of the current slice.
+#[derive(Clone)]
+pub struct RefPic {
+ pub frame: FrameRef,
+ pub poc: i32,
+ pub long_term: bool,
+}
diff --git a/crates/hevc/src/slice.rs b/crates/hevc/src/slice.rs
new file mode 100644
index 000000000..084eec8f3
--- /dev/null
+++ b/crates/hevc/src/slice.rs
@@ -0,0 +1,434 @@
+//! NAL unit header (7.3.1.2) and slice segment header (7.3.6).
+
+use crate::error::{Result, ensure, invalid};
+use crate::params::{Pps, Sps, StRps};
+use filmcraft_bitstream::BitReader;
+
+pub mod nal_type {
+ pub const TRAIL_N: u8 = 0;
+ pub const RADL_N: u8 = 6;
+ pub const RADL_R: u8 = 7;
+ pub const RASL_N: u8 = 8;
+ pub const RASL_R: u8 = 9;
+ pub const RSV_VCL_N14: u8 = 14;
+ pub const BLA_W_LP: u8 = 16;
+ pub const BLA_W_RADL: u8 = 17;
+ pub const BLA_N_LP: u8 = 18;
+ pub const IDR_W_RADL: u8 = 19;
+ pub const IDR_N_LP: u8 = 20;
+ pub const CRA: u8 = 21;
+ pub const RSV_IRAP_23: u8 = 23;
+ pub const VPS: u8 = 32;
+ pub const SPS: u8 = 33;
+ pub const PPS: u8 = 34;
+ pub const AUD: u8 = 35;
+ pub const EOS: u8 = 36;
+ pub const EOB: u8 = 37;
+ pub const FD: u8 = 38;
+ pub const PREFIX_SEI: u8 = 39;
+ pub const SUFFIX_SEI: u8 = 40;
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct NalHeader {
+ pub nal_type: u8,
+ pub layer_id: u8,
+ pub temporal_id: u8,
+}
+
+impl NalHeader {
+ pub fn parse(b: &[u8]) -> Result<NalHeader> {
+ ensure!(b.len() >= 2, "NAL unit too short");
+ ensure!(b[0] & 0x80 == 0, "forbidden_zero_bit set");
+ let tid = b[1] & 7;
+ ensure!(tid != 0, "nuh_temporal_id_plus1 is 0");
+ Ok(NalHeader { nal_type: (b[0] >> 1) & 0x3f, layer_id: ((b[0] & 1) << 5) | (b[1] >> 3), temporal_id: tid - 1 })
+ }
+ pub fn is_vcl(&self) -> bool {
+ self.nal_type < 32
+ }
+ pub fn is_irap(&self) -> bool {
+ (nal_type::BLA_W_LP..=nal_type::RSV_IRAP_23).contains(&self.nal_type)
+ }
+ pub fn is_idr(&self) -> bool {
+ self.nal_type == nal_type::IDR_W_RADL || self.nal_type == nal_type::IDR_N_LP
+ }
+ pub fn is_bla(&self) -> bool {
+ (nal_type::BLA_W_LP..=nal_type::BLA_N_LP).contains(&self.nal_type)
+ }
+ pub fn is_cra(&self) -> bool {
+ self.nal_type == nal_type::CRA
+ }
+ pub fn is_rasl(&self) -> bool {
+ self.nal_type == nal_type::RASL_N || self.nal_type == nal_type::RASL_R
+ }
+ pub fn is_radl(&self) -> bool {
+ self.nal_type == nal_type::RADL_N || self.nal_type == nal_type::RADL_R
+ }
+ /// Sub-layer non-reference picture (TRAIL_N, TSA_N, ..., RSV_VCL_N14).
+ pub fn is_sub_layer_non_ref(&self) -> bool {
+ self.nal_type <= nal_type::RSV_VCL_N14 && self.nal_type.is_multiple_of(2)
+ }
+}
+
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum SliceType {
+ B = 0,
+ P = 1,
+ I = 2,
+}
+
+/// Explicit weighted prediction parameters for one reference (7.4.7.3), already derived.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct WpEntry {
+ /// LumaWeightLX, luma_offset_lX (8-bit units).
+ pub luma: (i32, i32),
+ pub luma_flag: bool,
+ /// ChromaWeightLX, ChromaOffsetLX (8-bit units) for Cb and Cr.
+ pub chroma: [(i32, i32); 2],
+ pub chroma_flag: bool,
+}
+
+#[derive(Clone, Debug, Default, PartialEq, Eq)]
+pub struct PredWeightTable {
+ pub luma_log2_denom: u32,
+ pub chroma_log2_denom: u32,
+ pub l: [Vec<WpEntry>; 2],
+}
+
+#[derive(Clone, Debug)]
+pub struct SliceHeader {
+ pub nal: NalHeader,
+ pub first_slice_segment_in_pic: bool,
+ pub no_output_of_prior_pics: bool,
+ pub pps_id: u32,
+ pub dependent: bool,
+ pub segment_address: u32,
+ pub slice_type: SliceType,
+ pub pic_output: bool,
+ pub poc_lsb: u32,
+ /// The short-term RPS used by this picture (from the SPS or the header).
+ pub st_rps: StRps,
+ pub st_rps_bits: usize,
+ /// Long-term entries: (PocLsbLt, UsedByCurrPicLt, delta_poc_msb_present, DeltaPocMsbCycleLt).
+ pub lt: Vec<(u32, bool, bool, u32)>,
+ pub temporal_mvp: bool,
+ pub sao_luma: bool,
+ pub sao_chroma: bool,
+ pub num_ref_idx: [u32; 2],
+ pub list_entry: [Option<Vec<u32>>; 2],
+ pub mvd_l1_zero: bool,
+ pub cabac_init_flag: bool,
+ pub collocated_from_l0: bool,
+ pub collocated_ref_idx: u32,
+ pub pwt: Option<PredWeightTable>,
+ pub max_num_merge_cand: u32,
+ pub qp_delta: i32,
+ pub cb_qp_offset: i32,
+ pub cr_qp_offset: i32,
+ pub deblocking_disabled: bool,
+ pub beta_offset_div2: i32,
+ pub tc_offset_div2: i32,
+ pub loop_filter_across_slices: bool,
+ pub entry_points: Vec<u32>,
+ /// Byte offset of slice_segment_data() in the RBSP.
+ pub data_offset: usize,
+}
+
+fn ceil_log2(n: u32) -> u32 {
+ if n <= 1 { 0 } else { 32 - (n - 1).leading_zeros() }
+}
+
+impl SliceHeader {
+ pub fn is_intra(&self) -> bool {
+ self.slice_type == SliceType::I
+ }
+ pub fn is_b(&self) -> bool {
+ self.slice_type == SliceType::B
+ }
+
+ /// NumPicTotalCurr (7-55), without pps_curr_pic_ref.
+ pub fn num_pic_total_curr(&self) -> u32 {
+ let st = self.st_rps.s0.iter().chain(self.st_rps.s1.iter()).filter(|e| e.1).count();
+ let lt = self.lt.iter().filter(|e| e.1).count();
+ (st + lt) as u32
+ }
+
+ /// Parse a slice segment header. `prev` is the header of the preceding independent slice segment
+ /// of the same picture (needed for dependent slice segments).
+ pub fn parse(
+ rbsp: &[u8],
+ nal: NalHeader,
+ lookup: impl FnOnce(u32) -> Result<(std::sync::Arc<Pps>, std::sync::Arc<Sps>)>,
+ prev: Option<&SliceHeader>,
+ ) -> Result<(SliceHeader, std::sync::Arc<Pps>, std::sync::Arc<Sps>)> {
+ let mut r = BitReader::new(rbsp);
+ let first = r.read_flag()?;
+ let no_output_of_prior_pics = if nal.is_irap() { r.read_flag()? } else { false };
+ let pps_id = r.read_ue()?;
+ ensure!(pps_id < 64, "slice_pic_parameter_set_id out of range");
+ let (pps, sps) = lookup(pps_id)?;
+ let mut dependent = false;
+ let mut segment_address = 0;
+ if !first {
+ if pps.dependent_slice_segments_enabled {
+ dependent = r.read_flag()?;
+ }
+ let pic_size = sps.pic_width_in_ctbs() * sps.pic_height_in_ctbs();
+ segment_address = r.read_bits(ceil_log2(pic_size))?;
+ ensure!(segment_address < pic_size, "slice_segment_address out of range");
+ }
+ let mut sh = if dependent {
+ let Some(p) = prev else { return invalid("dependent slice segment without a preceding slice") };
+ let mut s = p.clone();
+ s.nal = nal;
+ s
+ } else {
+ SliceHeader {
+ nal,
+ first_slice_segment_in_pic: first,
+ no_output_of_prior_pics,
+ pps_id,
+ dependent: false,
+ segment_address,
+ slice_type: SliceType::I,
+ pic_output: true,
+ poc_lsb: 0,
+ st_rps: StRps::default(),
+ st_rps_bits: 0,
+ lt: Vec::new(),
+ temporal_mvp: false,
+ sao_luma: false,
+ sao_chroma: false,
+ num_ref_idx: [0, 0],
+ list_entry: [None, None],
+ mvd_l1_zero: false,
+ cabac_init_flag: false,
+ collocated_from_l0: true,
+ collocated_ref_idx: 0,
+ pwt: None,
+ max_num_merge_cand: 5,
+ qp_delta: 0,
+ cb_qp_offset: 0,
+ cr_qp_offset: 0,
+ deblocking_disabled: pps.deblocking_disabled,
+ beta_offset_div2: pps.beta_offset_div2,
+ tc_offset_div2: pps.tc_offset_div2,
+ loop_filter_across_slices: pps.loop_filter_across_slices,
+ entry_points: Vec::new(),
+ data_offset: 0,
+ }
+ };
+ sh.first_slice_segment_in_pic = first;
+ sh.no_output_of_prior_pics = no_output_of_prior_pics;
+ sh.pps_id = pps_id;
+ sh.dependent = dependent;
+ sh.segment_address = segment_address;
+ if !dependent {
+ r.skip(pps.num_extra_slice_header_bits as usize)?;
+ let st = r.read_ue()?;
+ sh.slice_type = match st {
+ 0 => SliceType::B,
+ 1 => SliceType::P,
+ 2 => SliceType::I,
+ _ => return invalid(format!("slice_type {st}")),
+ };
+ if nal.is_irap() {
+ ensure!(sh.slice_type == SliceType::I, "IRAP picture with inter slice");
+ }
+ if pps.output_flag_present {
+ sh.pic_output = r.read_flag()?;
+ }
+ if sps.separate_colour_plane {
+ r.skip(2)?;
+ }
+ if !nal.is_idr() {
+ sh.poc_lsb = r.read_bits(sps.log2_max_poc_lsb)?;
+ let from_sps = r.read_flag()?;
+ if !from_sps {
+ let start = r.position();
+ sh.st_rps = StRps::parse(&mut r, sps.st_rps.len(), &sps.st_rps, sps.st_rps.len())?;
+ sh.st_rps_bits = r.position() - start;
+ } else {
+ ensure!(!sps.st_rps.is_empty(), "no short-term RPS in the SPS");
+ let idx = if sps.st_rps.len() > 1 { r.read_bits(ceil_log2(sps.st_rps.len() as u32))? as usize } else { 0 };
+ ensure!(idx < sps.st_rps.len(), "short_term_ref_pic_set_idx out of range");
+ sh.st_rps = sps.st_rps[idx].clone();
+ }
+ if sps.long_term_refs_present {
+ let num_lt_sps = if !sps.lt_ref_pics.is_empty() { r.read_ue()? } else { 0 };
+ ensure!(num_lt_sps as usize <= sps.lt_ref_pics.len(), "num_long_term_sps out of range");
+ let num_lt_pics = r.read_ue()?;
+ ensure!(num_lt_sps + num_lt_pics <= 32, "too many long-term pictures");
+ let mut msb_acc = 0u32;
+ for i in 0..num_lt_sps + num_lt_pics {
+ let (lsb, used) = if i < num_lt_sps {
+ let idx = if sps.lt_ref_pics.len() > 1 { r.read_bits(ceil_log2(sps.lt_ref_pics.len() as u32))? } else { 0 };
+ ensure!((idx as usize) < sps.lt_ref_pics.len(), "lt_idx_sps out of range");
+ sps.lt_ref_pics[idx as usize]
+ } else {
+ (r.read_bits(sps.log2_max_poc_lsb)?, r.read_flag()?)
+ };
+ let msb_present = r.read_flag()?;
+ let cycle = if msb_present { r.read_ue()? } else { 0 };
+ // DeltaPocMsbCycleLt accumulates within each of the two groups (7-52)
+ if i == 0 || i == num_lt_sps {
+ msb_acc = cycle;
+ } else {
+ msb_acc = msb_acc.wrapping_add(cycle);
+ }
+ sh.lt.push((lsb, used, msb_present, msb_acc));
+ }
+ }
+ if sps.temporal_mvp {
+ sh.temporal_mvp = r.read_flag()?;
+ }
+ }
+ if sps.sao {
+ sh.sao_luma = r.read_flag()?;
+ if sps.chroma_array_type() != 0 {
+ sh.sao_chroma = r.read_flag()?;
+ }
+ }
+ if sh.slice_type != SliceType::I {
+ sh.num_ref_idx = [pps.num_ref_idx_l0_default, if sh.is_b() { pps.num_ref_idx_l1_default } else { 0 }];
+ if r.read_flag()? {
+ sh.num_ref_idx[0] = r.read_ue()? + 1;
+ if sh.is_b() {
+ sh.num_ref_idx[1] = r.read_ue()? + 1;
+ }
+ }
+ ensure!(sh.num_ref_idx[0] <= 15 && sh.num_ref_idx[1] <= 15, "num_ref_idx_active out of range");
+ let total = sh.num_pic_total_curr();
+ ensure!(total > 0, "inter slice without reference pictures in the RPS");
+ if pps.lists_modification_present && total > 1 {
+ let bits = ceil_log2(total);
+ for l in 0..if sh.is_b() { 2 } else { 1 } {
+ if r.read_flag()? {
+ let mut e = Vec::new();
+ for _ in 0..sh.num_ref_idx[l] {
+ let v = r.read_bits(bits)?;
+ ensure!(v < total, "list_entry out of range");
+ e.push(v);
+ }
+ sh.list_entry[l] = Some(e);
+ }
+ }
+ }
+ if sh.is_b() {
+ sh.mvd_l1_zero = r.read_flag()?;
+ }
+ if pps.cabac_init_present {
+ sh.cabac_init_flag = r.read_flag()?;
+ }
+ if sh.temporal_mvp {
+ if sh.is_b() {
+ sh.collocated_from_l0 = r.read_flag()?;
+ }
+ let l = if sh.collocated_from_l0 { 0 } else { 1 };
+ if sh.num_ref_idx[l] > 1 {
+ sh.collocated_ref_idx = r.read_ue()?;
+ ensure!(sh.collocated_ref_idx < sh.num_ref_idx[l], "collocated_ref_idx out of range");
+ }
+ }
+ if (pps.weighted_pred && sh.slice_type == SliceType::P) || (pps.weighted_bipred && sh.is_b()) {
+ sh.pwt = Some(parse_pwt(&mut r, &sh, &sps)?);
+ }
+ let five_minus = r.read_ue()?;
+ ensure!(five_minus <= 4, "five_minus_max_num_merge_cand out of range");
+ sh.max_num_merge_cand = 5 - five_minus;
+ }
+ sh.qp_delta = r.read_se()?;
+ let qp = pps.init_qp + sh.qp_delta;
+ let qp_bd = 6 * (sps.bit_depth_luma as i32 - 8);
+ ensure!((-qp_bd..=51).contains(&qp), "SliceQpY {qp} out of range");
+ if pps.slice_chroma_qp_offsets_present {
+ sh.cb_qp_offset = r.read_se()?;
+ sh.cr_qp_offset = r.read_se()?;
+ ensure!((-12..=12).contains(&sh.cb_qp_offset) && (-12..=12).contains(&sh.cr_qp_offset), "slice chroma QP offset out of range");
+ }
+ let override_flag = if pps.deblocking_override_enabled { r.read_flag()? } else { false };
+ if override_flag {
+ sh.deblocking_disabled = r.read_flag()?;
+ if !sh.deblocking_disabled {
+ sh.beta_offset_div2 = r.read_se()?;
+ sh.tc_offset_div2 = r.read_se()?;
+ ensure!((-6..=6).contains(&sh.beta_offset_div2) && (-6..=6).contains(&sh.tc_offset_div2), "deblocking offsets out of range");
+ }
+ }
+ if pps.loop_filter_across_slices && (sh.sao_luma || sh.sao_chroma || !sh.deblocking_disabled) {
+ sh.loop_filter_across_slices = r.read_flag()?;
+ }
+ }
+ sh.entry_points.clear();
+ if pps.tiles_enabled || pps.entropy_coding_sync {
+ let n = r.read_ue()?;
+ ensure!(n <= sps.pic_width_in_ctbs() * sps.pic_height_in_ctbs(), "num_entry_point_offsets out of range");
+ if n > 0 {
+ let len = r.read_ue()? + 1;
+ ensure!(len <= 32, "offset_len_minus1 out of range");
+ for _ in 0..n {
+ sh.entry_points.push(r.read_bits(len)? + 1);
+ }
+ }
+ }
+ if pps.slice_header_extension_present {
+ let len = r.read_ue()?;
+ ensure!(len <= 256, "slice_segment_header_extension_length out of range");
+ r.skip(8 * len as usize)?;
+ }
+ // byte_alignment(): alignment_bit_equal_to_one then zeros
+ ensure!(r.read_flag()?, "missing alignment_bit_equal_to_one");
+ r.byte_align();
+ sh.data_offset = r.position() / 8;
+ ensure!(sh.data_offset <= rbsp.len(), "slice header runs past the NAL unit");
+ Ok((sh, pps, sps))
+ }
+}
+
+fn parse_pwt(r: &mut BitReader, sh: &SliceHeader, sps: &Sps) -> Result<PredWeightTable> {
+ let mut t = PredWeightTable { luma_log2_denom: r.read_ue()?, ..Default::default() };
+ ensure!(t.luma_log2_denom <= 7, "luma_log2_weight_denom out of range");
+ let chroma = sps.chroma_array_type() != 0;
+ if chroma {
+ let d = t.luma_log2_denom as i32 + r.read_se()?;
+ ensure!((0..=7).contains(&d), "ChromaLog2WeightDenom out of range");
+ t.chroma_log2_denom = d as u32;
+ }
+ let lists = if sh.is_b() { 2 } else { 1 };
+ for l in 0..lists {
+ let n = sh.num_ref_idx[l] as usize;
+ let mut e = vec![WpEntry::default(); n];
+ for x in e.iter_mut() {
+ x.luma_flag = r.read_flag()?;
+ }
+ if chroma {
+ for x in e.iter_mut() {
+ x.chroma_flag = r.read_flag()?;
+ }
+ }
+ for x in e.iter_mut() {
+ x.luma = (1 << t.luma_log2_denom, 0);
+ if x.luma_flag {
+ let dw = r.read_se()?;
+ let off = r.read_se()?;
+ ensure!((-128..=127).contains(&dw) && (-128..=127).contains(&off), "luma weight out of range");
+ x.luma = ((1 << t.luma_log2_denom) + dw, off);
+ }
+ x.chroma = [(1 << t.chroma_log2_denom, 0); 2];
+ if x.chroma_flag {
+ let half = 128; // wpOffsetHalfRangeC (no high_precision_offsets)
+ for c in 0..2 {
+ let dw = r.read_se()?;
+ let doff = r.read_se()?;
+ ensure!((-128..=127).contains(&dw) && (-4 * half..4 * half).contains(&doff), "chroma weight out of range");
+ let w = (1 << t.chroma_log2_denom) + dw;
+ let off = (half - ((half * w) >> t.chroma_log2_denom) + doff).clamp(-half, half - 1);
+ x.chroma[c] = (w, off);
+ }
+ }
+ }
+ t.l[l] = e;
+ }
+ Ok(t)
+}
diff --git a/crates/hevc/src/slicedec.rs b/crates/hevc/src/slicedec.rs
new file mode 100644
index 000000000..354cf9d8e
--- /dev/null
+++ b/crates/hevc/src/slicedec.rs
@@ -0,0 +1,1486 @@
+//! Slice segment data decoding (7.3.8) with reconstruction: CTU / coding quadtree / coding unit /
+//! prediction unit / transform tree parsing (CABAC, 9.3) interleaved with intra prediction, motion
+//! compensation, scaling and inverse transforms. In-loop filters and row publication live in
+//! `filter.rs`.
+
+use crate::cabac::{Cabac, Contexts, init_contexts};
+use crate::error::{Result, ensure, invalid};
+use crate::inter;
+use crate::intra::{self, Refs};
+use crate::params::{Layout, Pps, Sps};
+use crate::picture::{FrameRef, RefPic};
+use crate::slice::{SliceHeader, SliceType};
+use crate::spec_tables::*;
+use crate::tables::{CTX_IDX_MAP, LEVEL_SCALE, SCAN_4, qpc_420, scan_order};
+use crate::transform;
+use std::sync::Arc;
+
+pub const F_INTRA: u8 = 1;
+pub const F_SKIP: u8 = 2;
+/// PCM with pcm_loop_filter_disabled_flag, or cu_transquant_bypass: in-loop filters leave the samples alone.
+pub const F_NOFILTER: u8 = 4;
+/// The luma transform block covering this 4x4 block has non-zero coefficients.
+pub const F_CBF: u8 = 8;
+/// Block has been decoded.
+pub const F_CODED: u8 = 16;
+
+pub const E_TU_V: u8 = 1;
+pub const E_PU_V: u8 = 2;
+pub const E_TU_H: u8 = 4;
+pub const E_PU_H: u8 = 8;
+
+/// Per 4x4 luma block state.
+#[derive(Clone, Copy, Default)]
+pub struct Blk {
+ pub flags: u8,
+ pub depth: u8,
+ pub qp: i8,
+ /// IntraPredModeY (DC for non-intra / PCM blocks, as used by the MPM derivation).
+ pub ipm: u8,
+ pub edges: u8,
+}
+
+/// Motion of a 4x4 block.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub struct MvField {
+ pub mv: [[i16; 2]; 2],
+ pub ref_idx: [i8; 2],
+}
+
+impl Default for MvField {
+ fn default() -> Self {
+ MvField { mv: [[0; 2]; 2], ref_idx: [-1, -1] }
+ }
+}
+
+impl MvField {
+ #[inline]
+ pub fn pred(&self, l: usize) -> bool {
+ self.ref_idx[l] >= 0
+ }
+}
+
+/// SAO parameters of one CTB.
+#[derive(Clone, Copy, Default, Debug)]
+pub struct SaoParams {
+ pub type_idx: [u8; 3],
+ pub band_pos: [u8; 3],
+ pub eo_class: [u8; 3],
+ /// SaoOffsetVal[1..4].
+ pub offsets: [[i16; 4]; 3],
+}
+
+/// Slice-level data needed after parsing (in-loop filters, collocated motion).
+pub struct SliceInfo {
+ pub addr_rs: u32,
+ pub deblock_disabled: bool,
+ pub beta_offset: i32,
+ pub tc_offset: i32,
+ pub lf_across: bool,
+ pub sao_luma: bool,
+ pub sao_chroma: bool,
+ /// Frame ids, POCs and long-term flags of RefPicList0/1.
+ pub ref_ids: [Vec<u32>; 2],
+ pub ref_pocs: [Vec<i32>; 2],
+ pub ref_lt: [Vec<bool>; 2],
+}
+
+/// One slice segment of a picture job.
+pub struct SliceJob {
+ pub sh: SliceHeader,
+ pub pps: Arc<Pps>,
+ pub sps: Arc<Sps>,
+ pub rbsp: Vec<u8>,
+ pub refs: [Vec<RefPic>; 2],
+}
+
+/// Per-picture decoding state.
+pub struct PicState {
+ pub frame: FrameRef,
+ #[allow(dead_code)]
+ pub sps: Arc<Sps>,
+ pub pps: Arc<Pps>,
+ pub layout: Arc<Layout>,
+ pub poc: i32,
+ pub width: usize,
+ pub height: usize,
+ pub cwidth: usize,
+ pub cheight: usize,
+ pub w4: usize,
+ pub h4: usize,
+ pub log2_ctb: u32,
+ pub wctb: usize,
+ pub hctb: usize,
+ pub bd_y: u32,
+ pub bd_c: u32,
+ /// Reconstructed (pre-SAO) planes.
+ pub planes: [Vec<u16>; 3],
+ pub blk: Vec<Blk>,
+ pub mvf: Vec<MvField>,
+ /// Index into `slices` per CTB (u32::MAX = not decoded).
+ pub ctb_slice: Vec<u32>,
+ /// SliceAddrRs per CTB (u32::MAX = not decoded).
+ pub ctb_addr: Vec<u32>,
+ pub sao: Vec<SaoParams>,
+ pub slices: Vec<SliceInfo>,
+ pub row_done: Vec<u32>,
+ pub rows_complete: usize,
+ pub rows_deblocked: usize,
+ pub rows_published: usize,
+ pub wpp_ctx: Option<Box<Contexts>>,
+ pub ds_ctx: Option<(Box<Contexts>, i32)>,
+ /// Scaling factors [sizeId][matrixId] when scaling lists are enabled.
+ pub scaling: Option<Arc<Vec<Vec<u8>>>>,
+ pub deblocking_enabled_anywhere: bool,
+}
+
+impl PicState {
+ pub fn new(frame: FrameRef, sps: Arc<Sps>, pps: Arc<Pps>, layout: Arc<Layout>, scaling: Option<Arc<Vec<Vec<u8>>>>) -> Self {
+ let (width, height) = (sps.width as usize, sps.height as usize);
+ let (cwidth, cheight) = (width / 2, height / 2);
+ let (w4, h4) = (width.div_ceil(4), height.div_ceil(4));
+ let log2_ctb = sps.log2_ctb;
+ let (wctb, hctb) = (sps.pic_width_in_ctbs() as usize, sps.pic_height_in_ctbs() as usize);
+ let (bd_y, bd_c) = (sps.bit_depth_luma, sps.bit_depth_chroma);
+ let gy = 1u16 << (bd_y - 1);
+ let gc = 1u16 << (bd_c - 1);
+ PicState {
+ poc: frame.poc,
+ frame,
+ sps,
+ pps,
+ layout,
+ width,
+ height,
+ cwidth,
+ cheight,
+ w4,
+ h4,
+ log2_ctb,
+ wctb,
+ hctb,
+ bd_y,
+ bd_c,
+ planes: [vec![gy; width * height], vec![gc; cwidth * cheight], vec![gc; cwidth * cheight]],
+ blk: vec![Blk::default(); w4 * h4],
+ mvf: vec![MvField::default(); w4 * h4],
+ ctb_slice: vec![u32::MAX; wctb * hctb],
+ ctb_addr: vec![u32::MAX; wctb * hctb],
+ sao: vec![SaoParams::default(); wctb * hctb],
+ slices: Vec::new(),
+ row_done: vec![0; hctb],
+ rows_complete: 0,
+ rows_deblocked: 0,
+ rows_published: 0,
+ wpp_ctx: None,
+ ds_ctx: None,
+ scaling,
+ deblocking_enabled_anywhere: false,
+ }
+ }
+
+ /// z-scan order availability (6.4.1) of luma location (xn, yn) for the block at (xc, yc) in the slice
+ /// with SliceAddrRs `addr`.
+ #[inline]
+ pub fn zavail(&self, xc: i32, yc: i32, xn: i32, yn: i32, addr: u32) -> bool {
+ if xn < 0 || yn < 0 || xn >= self.width as i32 || yn >= self.height as i32 {
+ return false;
+ }
+ let s = self.log2_ctb;
+ let ctb_n = (yn >> s) as usize * self.wctb + (xn >> s) as usize;
+ let ctb_c = (yc >> s) as usize * self.wctb + (xc >> s) as usize;
+ if ctb_n != ctb_c {
+ let tsn = self.layout.rs_to_ts[ctb_n];
+ let tsc = self.layout.rs_to_ts[ctb_c];
+ tsn < tsc && self.ctb_addr[ctb_n] == addr && self.layout.tile_id[tsn as usize] == self.layout.tile_id[tsc as usize]
+ } else {
+ let m = (1 << s) - 1;
+ morton(((xn & m) >> 2) as u32, ((yn & m) >> 2) as u32) <= morton(((xc & m) >> 2) as u32, ((yc & m) >> 2) as u32)
+ }
+ }
+
+ #[inline]
+ pub fn blk_at(&self, x: i32, y: i32) -> &Blk {
+ &self.blk[(y as usize >> 2) * self.w4 + (x as usize >> 2)]
+ }
+}
+
+#[inline]
+fn morton(x: u32, y: u32) -> u32 {
+ let mut r = 0;
+ for i in 0..5 {
+ r |= ((x >> i) & 1) << (2 * i);
+ r |= ((y >> i) & 1) << (2 * i + 1);
+ }
+ r
+}
+
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+pub enum PartMode {
+ P2Nx2N,
+ P2NxN,
+ PNx2N,
+ PNxN,
+ P2NxnU,
+ P2NxnD,
+ PnLx2N,
+ PnRx2N,
+}
+
+/// Decoder of one slice segment.
+pub struct SliceDecoder<'a> {
+ pub pic: &'a mut PicState,
+ pub sh: &'a SliceHeader,
+ pub sps: &'a Sps,
+ pub pps: &'a Pps,
+ pub refs: &'a [Vec<RefPic>; 2],
+ pub c: Cabac<'a>,
+ pub slice_idx: u32,
+ pub slice_addr: u32,
+ pub slice_qp: i32,
+ pub init_type: usize,
+ // quantization state
+ pub qp_y: i32,
+ pub qp_y_pred: i32,
+ pub last_qp: i32,
+ pub is_cu_qp_delta_coded: bool,
+ pub cu_qp_delta: i32,
+ pub log2_min_cu_qp_delta: u32,
+ pub qp_cb: i32,
+ pub qp_cr: i32,
+ // current CU
+ pub cu_transquant_bypass: bool,
+ pub cu_intra: bool,
+ pub intra_chroma_mode: u32,
+ pub max_trafo_depth: u32,
+ pub intra_split: bool,
+ pub cu_part: PartMode,
+ // scratch
+ pub coeffs: Vec<i32>,
+ pub pred0: Vec<i16>,
+ pub pred1: Vec<i16>,
+ pub refs_buf: Refs,
+ /// Collocated picture for TMVP.
+ pub col: Option<RefPic>,
+ /// NoBackwardPredFlag.
+ pub no_backward_pred: bool,
+ pub ctb_x: i32,
+ pub ctb_y: i32,
+}
+
+impl<'a> SliceDecoder<'a> {
+ #[inline(always)]
+ fn dd(&mut self, ctx: usize) -> u32 {
+ self.c.decode_decision(ctx)
+ }
+ #[inline(always)]
+ fn bypass(&mut self) -> u32 {
+ self.c.decode_bypass()
+ }
+ #[inline]
+ fn bypass_bits(&mut self, n: u32) -> u32 {
+ let mut v = 0;
+ for _ in 0..n {
+ v = (v << 1) | self.c.decode_bypass();
+ }
+ v
+ }
+
+ /// Decode the slice segment `job` into `pic`.
+ pub fn decode(pic: &'a mut PicState, job: &'a SliceJob) -> Result<()> {
+ let sh = &job.sh;
+ let (sps, pps) = (&*job.sps, &*job.pps);
+ ensure!(sh.data_offset < job.rbsp.len(), "empty slice segment data");
+ let slice_qp = pps.init_qp + sh.qp_delta;
+ let init_type = match sh.slice_type {
+ SliceType::I => 0,
+ SliceType::P => {
+ if sh.cabac_init_flag {
+ 2
+ } else {
+ 1
+ }
+ }
+ SliceType::B => {
+ if sh.cabac_init_flag {
+ 1
+ } else {
+ 2
+ }
+ }
+ };
+ // SliceAddrRs: address of the first CTB of the (independent) slice
+ let slice_addr = if sh.dependent {
+ match pic.slices.last() {
+ Some(s) => s.addr_rs,
+ None => return invalid("dependent slice segment without a preceding slice"),
+ }
+ } else {
+ sh.segment_address
+ };
+ if !sh.dependent {
+ let ids = |l: usize| job.refs[l].iter().map(|r| r.frame.id).collect::<Vec<_>>();
+ let pocs = |l: usize| job.refs[l].iter().map(|r| r.poc).collect::<Vec<_>>();
+ let lts = |l: usize| job.refs[l].iter().map(|r| r.long_term).collect::<Vec<_>>();
+ pic.slices.push(SliceInfo {
+ addr_rs: slice_addr,
+ deblock_disabled: sh.deblocking_disabled,
+ beta_offset: sh.beta_offset_div2 * 2,
+ tc_offset: sh.tc_offset_div2 * 2,
+ lf_across: sh.loop_filter_across_slices,
+ sao_luma: sh.sao_luma,
+ sao_chroma: sh.sao_chroma,
+ ref_ids: [ids(0), ids(1)],
+ ref_pocs: [pocs(0), pocs(1)],
+ ref_lt: [lts(0), lts(1)],
+ });
+ if !sh.deblocking_disabled {
+ pic.deblocking_enabled_anywhere = true;
+ }
+ }
+ let slice_idx = (pic.slices.len() - 1) as u32;
+ let col = if sh.temporal_mvp && !sh.is_intra() {
+ let l = if sh.is_b() && !sh.collocated_from_l0 { 1 } else { 0 };
+ job.refs[l].get(sh.collocated_ref_idx as usize).cloned()
+ } else {
+ None
+ };
+ let no_backward_pred = job.refs.iter().flatten().all(|r| r.poc <= pic.poc);
+ let log2_min_cu_qp_delta = sps.log2_ctb - pps.diff_cu_qp_delta_depth;
+ let c = Cabac::new(&job.rbsp, sh.data_offset, slice_qp, init_type)?;
+ let mut d = SliceDecoder {
+ pic,
+ sh,
+ sps,
+ pps,
+ refs: &job.refs,
+ c,
+ slice_idx,
+ slice_addr,
+ slice_qp,
+ init_type,
+ qp_y: slice_qp,
+ qp_y_pred: slice_qp,
+ last_qp: slice_qp,
+ is_cu_qp_delta_coded: false,
+ cu_qp_delta: 0,
+ log2_min_cu_qp_delta,
+ qp_cb: 0,
+ qp_cr: 0,
+ cu_transquant_bypass: false,
+ cu_intra: false,
+ intra_chroma_mode: 0,
+ max_trafo_depth: 0,
+ intra_split: false,
+ cu_part: PartMode::P2Nx2N,
+ coeffs: vec![0; 32 * 32],
+ pred0: vec![0; 64 * 64],
+ pred1: vec![0; 64 * 64],
+ refs_buf: Refs::default(),
+ col,
+ no_backward_pred,
+ ctb_x: 0,
+ ctb_y: 0,
+ };
+ d.decode_data()
+ }
+
+ fn decode_data(&mut self) -> Result<()> {
+ let layout = self.pic.layout.clone();
+ let wctb = self.pic.wctb as u32;
+ let npic = (self.pic.wctb * self.pic.hctb) as u32;
+ let mut ts = layout.rs_to_ts[self.sh.segment_address as usize];
+ let mut first = true;
+ loop {
+ let rs = layout.ts_to_rs[ts as usize];
+ ensure!(self.pic.ctb_slice[rs as usize] == u32::MAX, "CTB {rs} decoded twice");
+ let (rx, ry) = ((rs % wctb) as i32, (rs / wctb) as i32);
+ let ctb = 1i32 << self.sps.log2_ctb;
+ self.ctb_x = rx * ctb;
+ self.ctb_y = ry * ctb;
+ self.pic.ctb_slice[rs as usize] = self.slice_idx;
+ self.pic.ctb_addr[rs as usize] = self.slice_addr;
+ // context initialisation / synchronisation (9.3.1, 9.3.2.1)
+ let first_in_tile = ts == 0 || layout.tile_id[ts as usize] != layout.tile_id[ts as usize - 1];
+ let wpp_row_start = self.pps.entropy_coding_sync
+ && (rs.is_multiple_of(wctb) || layout.tile_id[ts as usize] != layout.tile_id[layout.rs_to_ts[rs as usize - 1] as usize]);
+ if first_in_tile {
+ if !first {
+ init_contexts(&mut self.c.ctx, self.slice_qp, self.init_type);
+ }
+ self.last_qp = self.slice_qp;
+ } else if wpp_row_start {
+ let (x0, y0) = (self.ctb_x, self.ctb_y);
+ let avail = self.pic.zavail(x0, y0, x0 + ctb, y0 - ctb, self.slice_addr);
+ match (&self.pic.wpp_ctx, avail) {
+ (Some(saved), true) => self.c.ctx = **saved,
+ _ => init_contexts(&mut self.c.ctx, self.slice_qp, self.init_type),
+ }
+ self.last_qp = self.slice_qp;
+ } else if first && self.sh.dependent {
+ match &self.pic.ds_ctx {
+ Some((saved, qp)) => {
+ self.c.ctx = **saved;
+ self.last_qp = *qp;
+ }
+ None => return invalid("dependent slice segment without stored contexts"),
+ }
+ }
+ first = false;
+ if self.sh.sao_luma || self.sh.sao_chroma {
+ self.parse_sao(rx, ry, rs)?;
+ }
+ self.coding_quadtree(self.ctb_x, self.ctb_y, self.sps.log2_ctb, 0)?;
+ let end = self.c.decode_terminate() == 1;
+ ensure!(!self.c.overrun(), "slice data overrun");
+ // WPP storage after the second CTB of a row in a tile (9.3.1)
+ if self.pps.entropy_coding_sync
+ && (rs % wctb == 1 || (rs > 1 && layout.tile_id[ts as usize] != layout.tile_id[layout.rs_to_ts[rs as usize - 2] as usize]))
+ {
+ self.pic.wpp_ctx = Some(Box::new(self.c.ctx));
+ }
+ crate::filter::ctb_decoded(self.pic, ry as usize);
+ ts += 1;
+ if end {
+ if self.pps.dependent_slice_segments_enabled {
+ self.pic.ds_ctx = Some((Box::new(self.c.ctx), self.last_qp));
+ }
+ break;
+ }
+ ensure!(ts < npic, "slice data continues past the last CTB");
+ let nrs = layout.ts_to_rs[ts as usize];
+ let new_tile = self.pps.tiles_enabled && layout.tile_id[ts as usize] != layout.tile_id[ts as usize - 1];
+ let new_row = self.pps.entropy_coding_sync
+ && (nrs.is_multiple_of(wctb) || layout.tile_id[ts as usize] != layout.tile_id[layout.rs_to_ts[nrs as usize - 1] as usize]);
+ if new_tile || new_row {
+ ensure!(self.c.decode_terminate() == 1, "end_of_subset_one_bit is 0");
+ let pos = self.c.bit_pos().div_ceil(8);
+ self.c.set_byte_pos(pos);
+ self.c.init_engine()?;
+ }
+ }
+ Ok(())
+ }
+
+ fn parse_sao(&mut self, rx: i32, ry: i32, rs: u32) -> Result<()> {
+ let layout = self.pic.layout.clone();
+ let wctb = self.pic.wctb as u32;
+ let ts = layout.rs_to_ts[rs as usize];
+ let mut merge_left = false;
+ let mut merge_up = false;
+ if rx > 0 {
+ let left_in_slice = self.pic.ctb_addr[rs as usize - 1] == self.slice_addr;
+ let left_in_tile = layout.tile_id[ts as usize] == layout.tile_id[layout.rs_to_ts[rs as usize - 1] as usize];
+ if left_in_slice && left_in_tile {
+ merge_left = self.dd(SAO_MERGE) == 1;
+ }
+ }
+ if ry > 0 && !merge_left {
+ let up = rs - wctb;
+ let up_in_slice = self.pic.ctb_addr[up as usize] == self.slice_addr;
+ let up_in_tile = layout.tile_id[ts as usize] == layout.tile_id[layout.rs_to_ts[up as usize] as usize];
+ if up_in_slice && up_in_tile {
+ merge_up = self.dd(SAO_MERGE) == 1;
+ }
+ }
+ if merge_left {
+ self.pic.sao[rs as usize] = self.pic.sao[rs as usize - 1];
+ return Ok(());
+ }
+ if merge_up {
+ self.pic.sao[rs as usize] = self.pic.sao[(rs - wctb) as usize];
+ return Ok(());
+ }
+ let mut p = SaoParams::default();
+ for c in 0..3 {
+ let enabled = if c == 0 { self.sh.sao_luma } else { self.sh.sao_chroma };
+ if !enabled {
+ continue;
+ }
+ if c == 2 {
+ p.type_idx[2] = p.type_idx[1];
+ p.eo_class[2] = p.eo_class[1];
+ } else {
+ p.type_idx[c] = if self.dd(SAO_TYPE) == 0 {
+ 0
+ } else if self.bypass() == 0 {
+ 1
+ } else {
+ 2
+ };
+ }
+ if p.type_idx[c] == 0 {
+ continue;
+ }
+ let bd = if c == 0 { self.pic.bd_y } else { self.pic.bd_c };
+ let cmax = (1u32 << (bd.min(10) - 5)) - 1;
+ let mut abs = [0i16; 4];
+ for a in abs.iter_mut() {
+ let mut v = 0;
+ while v < cmax && self.bypass() == 1 {
+ v += 1;
+ }
+ *a = v as i16;
+ }
+ if p.type_idx[c] == 1 {
+ for a in abs.iter_mut() {
+ if *a != 0 && self.bypass() == 1 {
+ *a = -*a;
+ }
+ }
+ p.band_pos[c] = self.bypass_bits(5) as u8;
+ p.offsets[c] = abs;
+ } else {
+ p.offsets[c] = [abs[0], abs[1], -abs[2], -abs[3]];
+ if c == 0 {
+ p.eo_class[0] = self.bypass_bits(2) as u8;
+ }
+ if c == 1 {
+ p.eo_class[1] = self.bypass_bits(2) as u8;
+ }
+ }
+ }
+ self.pic.sao[rs as usize] = p;
+ Ok(())
+ }
+
+ fn coding_quadtree(&mut self, x0: i32, y0: i32, log2: u32, depth: u32) -> Result<()> {
+ let size = 1i32 << log2;
+ let (w, h) = (self.pic.width as i32, self.pic.height as i32);
+ let split = if x0 + size <= w && y0 + size <= h && log2 > self.sps.log2_min_cb {
+ // ctxInc from neighbouring depths (9.3.4.2.2)
+ let mut inc = 0;
+ if self.pic.zavail(x0, y0, x0 - 1, y0, self.slice_addr) && self.pic.blk_at(x0 - 1, y0).depth as u32 > depth {
+ inc += 1;
+ }
+ if self.pic.zavail(x0, y0, x0, y0 - 1, self.slice_addr) && self.pic.blk_at(x0, y0 - 1).depth as u32 > depth {
+ inc += 1;
+ }
+ self.dd(SPLIT_CU + inc) == 1
+ } else {
+ log2 > self.sps.log2_min_cb
+ };
+ if self.pps.cu_qp_delta_enabled && log2 >= self.log2_min_cu_qp_delta {
+ self.is_cu_qp_delta_coded = false;
+ self.cu_qp_delta = 0;
+ }
+ if split {
+ let half = size >> 1;
+ let (x1, y1) = (x0 + half, y0 + half);
+ self.coding_quadtree(x0, y0, log2 - 1, depth + 1)?;
+ if x1 < w {
+ self.coding_quadtree(x1, y0, log2 - 1, depth + 1)?;
+ }
+ if y1 < h {
+ self.coding_quadtree(x0, y1, log2 - 1, depth + 1)?;
+ }
+ if x1 < w && y1 < h {
+ self.coding_quadtree(x1, y1, log2 - 1, depth + 1)?;
+ }
+ Ok(())
+ } else {
+ self.coding_unit(x0, y0, log2, depth)
+ }
+ }
+
+ /// Set per-4x4 state of a rectangle (luma coordinates).
+ fn fill_blk(&mut self, x0: i32, y0: i32, w: i32, h: i32, f: impl Fn(&mut Blk)) {
+ let (bx0, by0) = ((x0 >> 2) as usize, (y0 >> 2) as usize);
+ let bx1 = (((x0 + w) as usize).min(self.pic.width).div_ceil(4)).max(bx0);
+ let by1 = (((y0 + h) as usize).min(self.pic.height).div_ceil(4)).max(by0);
+ for by in by0..by1 {
+ for b in &mut self.pic.blk[by * self.pic.w4 + bx0..by * self.pic.w4 + bx1] {
+ f(b);
+ }
+ }
+ }
+
+ /// qPY_PRED derivation (8.6.1) at the start of a quantization group.
+ fn derive_qp_pred(&mut self, xq: i32, yq: i32) {
+ let prev = self.last_qp;
+ let s = self.sps.log2_ctb;
+ let cur_ctb = ((yq >> s), (xq >> s));
+ let qa = if self.pic.zavail(xq, yq, xq - 1, yq, self.slice_addr) && ((yq >> s), ((xq - 1) >> s)) == cur_ctb {
+ self.pic.blk_at(xq - 1, yq).qp as i32
+ } else {
+ prev
+ };
+ let qb = if self.pic.zavail(xq, yq, xq, yq - 1, self.slice_addr) && (((yq - 1) >> s), (xq >> s)) == cur_ctb {
+ self.pic.blk_at(xq, yq - 1).qp as i32
+ } else {
+ prev
+ };
+ self.qp_y_pred = (qa + qb + 1) >> 1;
+ }
+
+ fn update_qp(&mut self) {
+ let off = 6 * (self.pic.bd_y as i32 - 8);
+ self.qp_y = ((self.qp_y_pred + self.cu_qp_delta + 52 + 2 * off) % (52 + off)) - off;
+ let offc = 6 * (self.pic.bd_c as i32 - 8);
+ let qpi_cb = (self.qp_y + self.pps.cb_qp_offset + self.sh.cb_qp_offset).clamp(-offc, 57);
+ let qpi_cr = (self.qp_y + self.pps.cr_qp_offset + self.sh.cr_qp_offset).clamp(-offc, 57);
+ self.qp_cb = qpc_420(qpi_cb) + offc;
+ self.qp_cr = qpc_420(qpi_cr) + offc;
+ }
+
+ fn coding_unit(&mut self, x0: i32, y0: i32, log2: u32, depth: u32) -> Result<()> {
+ let n = 1i32 << log2;
+ // quantization group start
+ let qg_mask = (1 << self.log2_min_cu_qp_delta) - 1;
+ if (x0 & qg_mask) == 0 && (y0 & qg_mask) == 0 {
+ self.derive_qp_pred(x0, y0);
+ }
+ self.update_qp();
+ self.cu_transquant_bypass = if self.pps.transquant_bypass { self.dd(CU_TRANSQUANT_BYPASS) == 1 } else { false };
+ let mut skip = false;
+ if !self.sh.is_intra() {
+ let mut inc = 0;
+ if self.pic.zavail(x0, y0, x0 - 1, y0, self.slice_addr) && self.pic.blk_at(x0 - 1, y0).flags & F_SKIP != 0 {
+ inc += 1;
+ }
+ if self.pic.zavail(x0, y0, x0, y0 - 1, self.slice_addr) && self.pic.blk_at(x0, y0 - 1).flags & F_SKIP != 0 {
+ inc += 1;
+ }
+ skip = self.dd(CU_SKIP + inc) == 1;
+ }
+ // CU-level block state: depth, skip, coded; CU edges are transform and prediction edges
+ let bypass = self.cu_transquant_bypass;
+ let qp = self.qp_y as i8;
+ self.fill_blk(x0, y0, n, n, |b| {
+ b.depth = depth as u8;
+ b.flags = F_CODED | if skip { F_SKIP } else { 0 } | if bypass { F_NOFILTER } else { 0 };
+ b.qp = qp;
+ b.ipm = 1;
+ b.edges = 0;
+ });
+ self.mark_edges(x0, y0, n, n, E_TU_V | E_PU_V, E_TU_H | E_PU_H);
+ if skip {
+ self.cu_intra = false;
+ self.prediction_unit(x0, y0, n, x0, y0, n, n, 0, PartMode::P2Nx2N, true)?;
+ self.finish_cu(x0, y0, n);
+ return Ok(());
+ }
+ let intra = if !self.sh.is_intra() { self.dd(PRED_MODE) == 1 } else { true };
+ self.cu_intra = intra;
+ let mut part = PartMode::P2Nx2N;
+ if !intra || log2 == self.sps.log2_min_cb {
+ part = self.parse_part_mode(intra, log2)?;
+ }
+ self.cu_part = part;
+ if intra {
+ self.fill_blk(x0, y0, n, n, |b| b.flags |= F_INTRA);
+ self.intra_split = part == PartMode::PNxN;
+ let pcm =
+ part == PartMode::P2Nx2N && self.sps.pcm && log2 >= self.sps.log2_min_pcm && log2 <= self.sps.log2_max_pcm && self.c.decode_terminate() == 1;
+ if pcm {
+ self.pcm_sample(x0, y0, log2)?;
+ if self.sps.pcm_loop_filter_disabled {
+ self.fill_blk(x0, y0, n, n, |b| b.flags |= F_NOFILTER);
+ }
+ self.finish_cu(x0, y0, n);
+ return Ok(());
+ }
+ self.parse_intra_modes(x0, y0, n, part)?;
+ self.max_trafo_depth = self.sps.max_th_depth_intra + self.intra_split as u32;
+ self.transform_tree(x0, y0, x0, y0, log2, 0, 0, [true, true])?;
+ } else {
+ self.intra_split = false;
+ let mut merge2nx2n = false;
+ let h = n / 2;
+ let q = n / 4;
+ let parts: &[(i32, i32, i32, i32)] = match part {
+ PartMode::P2Nx2N => &[(0, 0, n, n)],
+ PartMode::P2NxN => &[(0, 0, n, h), (0, h, n, h)],
+ PartMode::PNx2N => &[(0, 0, h, n), (h, 0, h, n)],
+ PartMode::P2NxnU => &[(0, 0, n, q), (0, q, n, n - q)],
+ PartMode::P2NxnD => &[(0, 0, n, n - q), (0, n - q, n, q)],
+ PartMode::PnLx2N => &[(0, 0, q, n), (q, 0, n - q, n)],
+ PartMode::PnRx2N => &[(0, 0, n - q, n), (n - q, 0, q, n)],
+ PartMode::PNxN => &[(0, 0, h, h), (h, 0, h, h), (0, h, h, h), (h, h, h, h)],
+ };
+ for (i, &(px, py, pw, ph)) in parts.iter().enumerate() {
+ let merge = self.prediction_unit(x0, y0, n, x0 + px, y0 + py, pw, ph, i, part, false)?;
+ if part == PartMode::P2Nx2N {
+ merge2nx2n = merge;
+ }
+ if px != 0 {
+ self.mark_edges(x0 + px, y0 + py, pw, ph, E_PU_V, 0);
+ }
+ if py != 0 {
+ self.mark_edges(x0 + px, y0 + py, pw, ph, 0, E_PU_H);
+ }
+ }
+ let root_cbf = if !merge2nx2n { self.dd(RQT_ROOT_CBF) == 1 } else { true };
+ if root_cbf {
+ self.max_trafo_depth = self.sps.max_th_depth_inter;
+ self.transform_tree(x0, y0, x0, y0, log2, 0, 0, [true, true])?;
+ }
+ }
+ self.finish_cu(x0, y0, n);
+ Ok(())
+ }
+
+ /// Store the final QpY of the CU (may have changed with cu_qp_delta).
+ fn finish_cu(&mut self, x0: i32, y0: i32, n: i32) {
+ let qp = self.qp_y as i8;
+ self.fill_blk(x0, y0, n, n, |b| b.qp = qp);
+ self.last_qp = self.qp_y;
+ }
+
+ /// Mark the left (vertical) and top (horizontal) edges of a rectangle.
+ fn mark_edges(&mut self, x0: i32, y0: i32, w: i32, h: i32, v: u8, hz: u8) {
+ let w4 = self.pic.w4;
+ let (bx0, by0) = ((x0 >> 2) as usize, (y0 >> 2) as usize);
+ if v != 0 {
+ let by1 = ((y0 + h) as usize).min(self.pic.height).div_ceil(4);
+ for by in by0..by1 {
+ self.pic.blk[by * w4 + bx0].edges |= v;
+ }
+ }
+ if hz != 0 {
+ let bx1 = ((x0 + w) as usize).min(self.pic.width).div_ceil(4);
+ for b in &mut self.pic.blk[by0 * w4 + bx0..by0 * w4 + bx1] {
+ b.edges |= hz;
+ }
+ }
+ }
+
+ fn parse_part_mode(&mut self, intra: bool, log2: u32) -> Result<PartMode> {
+ if intra {
+ return Ok(if self.dd(PART_MODE) == 1 { PartMode::P2Nx2N } else { PartMode::PNxN });
+ }
+ if self.dd(PART_MODE) == 1 {
+ return Ok(PartMode::P2Nx2N);
+ }
+ let min = log2 == self.sps.log2_min_cb;
+ if min {
+ if self.dd(PART_MODE + 1) == 1 {
+ return Ok(PartMode::P2NxN);
+ }
+ if log2 == 3 {
+ return Ok(PartMode::PNx2N);
+ }
+ return Ok(if self.dd(PART_MODE + 2) == 1 { PartMode::PNx2N } else { PartMode::PNxN });
+ }
+ let amp = self.sps.amp;
+ let hor = self.dd(PART_MODE + 1) == 1;
+ if !amp {
+ return Ok(if hor { PartMode::P2NxN } else { PartMode::PNx2N });
+ }
+ let no_amp = self.dd(PART_MODE + 3) == 1;
+ if no_amp {
+ return Ok(if hor { PartMode::P2NxN } else { PartMode::PNx2N });
+ }
+ let b = self.bypass();
+ Ok(match (hor, b) {
+ (true, 0) => PartMode::P2NxnU,
+ (true, _) => PartMode::P2NxnD,
+ (false, 0) => PartMode::PnLx2N,
+ (false, _) => PartMode::PnRx2N,
+ })
+ }
+
+ fn pcm_sample(&mut self, x0: i32, y0: i32, log2: u32) -> Result<()> {
+ // the PCM samples start at the next byte boundary after the terminate bin
+ let start = self.c.bit_pos().div_ceil(8);
+ let data = self.c.data();
+ let n = 1usize << log2;
+ let (bl, bc) = (self.sps.pcm_bit_depth_luma, self.sps.pcm_bit_depth_chroma);
+ let total_bits = n * n * bl as usize + 2 * (n / 2) * (n / 2) * bc as usize;
+ ensure!(start + total_bits.div_ceil(8) <= data.len(), "PCM samples truncated");
+ let mut r = filmcraft_bitstream::BitReader::new(&data[start..]);
+ let (sy, sc) = (self.pic.bd_y - bl, self.pic.bd_c - bc);
+ let w = self.pic.width;
+ for y in 0..n {
+ for x in 0..n {
+ let v = r.read_bits(bl)? as u16;
+ self.pic.planes[0][(y0 as usize + y) * w + x0 as usize + x] = v << sy;
+ }
+ }
+ let cw = self.pic.cwidth;
+ for c in 1..3 {
+ for y in 0..n / 2 {
+ for x in 0..n / 2 {
+ let v = r.read_bits(bc)? as u16;
+ self.pic.planes[c][(y0 as usize / 2 + y) * cw + x0 as usize / 2 + x] = v << sc;
+ }
+ }
+ }
+ let end = start + r.position().div_ceil(8);
+ self.c.set_byte_pos(end);
+ self.c.init_engine()
+ }
+
+ fn parse_intra_modes(&mut self, x0: i32, y0: i32, n: i32, part: PartMode) -> Result<()> {
+ let nb = if part == PartMode::PNxN { 2 } else { 1 };
+ let pb = n / nb;
+ let mut prev = [false; 4];
+ for (i, p) in prev.iter_mut().enumerate().take((nb * nb) as usize) {
+ let _ = i;
+ *p = self.dd(PREV_INTRA_LUMA) == 1;
+ }
+ for j in 0..nb {
+ for i in 0..nb {
+ let k = (j * nb + i) as usize;
+ let (xp, yp) = (x0 + i * pb, y0 + j * pb);
+ // candidate modes (8.4.2)
+ let cand_a = if self.pic.zavail(xp, yp, xp - 1, yp, self.slice_addr) {
+ let b = self.pic.blk_at(xp - 1, yp);
+ if b.flags & F_INTRA != 0 { b.ipm as u32 } else { 1 }
+ } else {
+ 1
+ };
+ let cand_b = if self.pic.zavail(xp, yp, xp, yp - 1, self.slice_addr) && yp > ((yp >> self.sps.log2_ctb) << self.sps.log2_ctb) {
+ let b = self.pic.blk_at(xp, yp - 1);
+ if b.flags & F_INTRA != 0 { b.ipm as u32 } else { 1 }
+ } else {
+ 1
+ };
+ let mut list = if cand_a == cand_b {
+ if cand_a < 2 { [0, 1, 26] } else { [cand_a, 2 + ((cand_a + 29) % 32), 2 + ((cand_a - 2 + 1) % 32)] }
+ } else {
+ let c = if cand_a != 0 && cand_b != 0 {
+ 0
+ } else if cand_a != 1 && cand_b != 1 {
+ 1
+ } else {
+ 26
+ };
+ [cand_a, cand_b, c]
+ };
+ let mode = if prev[k] {
+ let idx = if self.bypass() == 0 {
+ 0
+ } else if self.bypass() == 0 {
+ 1
+ } else {
+ 2
+ };
+ list[idx]
+ } else {
+ let mut m = self.bypass_bits(5);
+ list.sort_unstable();
+ for &c in &list {
+ if m >= c {
+ m += 1;
+ }
+ }
+ m
+ };
+ self.fill_blk(xp, yp, pb, pb, |b| b.ipm = mode as u8);
+ }
+ }
+ // chroma mode (4:2:0: one per CU, derived from the first PU's luma mode)
+ let icpm = if self.dd(INTRA_CHROMA) == 0 { 4 } else { self.bypass_bits(2) };
+ let luma = self.pic.blk_at(x0, y0).ipm as u32;
+ self.intra_chroma_mode = match icpm {
+ 4 => luma,
+ _ => {
+ let m = [0, 26, 10, 1][icpm as usize];
+ if m == luma { 34 } else { m }
+ }
+ };
+ Ok(())
+ }
+
+ fn transform_tree(&mut self, x0: i32, y0: i32, xb: i32, yb: i32, log2: u32, depth: u32, blk_idx: u32, parent_cbf_c: [bool; 2]) -> Result<()> {
+ let split = if log2 <= self.sps.log2_max_tb && log2 > self.sps.log2_min_tb && depth < self.max_trafo_depth && !(self.intra_split && depth == 0) {
+ self.dd(SPLIT_TRANSFORM + (5 - log2 as usize)) == 1
+ } else {
+ // interSplitFlag (7.4.9.8)
+ let inter_split = self.sps.max_th_depth_inter == 0 && !self.cu_intra && self.cu_part != PartMode::P2Nx2N && depth == 0;
+ log2 > self.sps.log2_max_tb || (self.intra_split && depth == 0) || inter_split
+ };
+ let mut cbf_c = [false, false];
+ if log2 > 2 {
+ for (c, cbf) in cbf_c.iter_mut().enumerate() {
+ if depth == 0 || parent_cbf_c[c] {
+ *cbf = self.dd(CBF_CHROMA + depth as usize) == 1;
+ }
+ }
+ } else {
+ // 4x4 luma blocks: chroma cbfs are those of the parent (coded at blkIdx 3)
+ cbf_c = parent_cbf_c;
+ if depth == 0 {
+ cbf_c = [false, false];
+ }
+ }
+ if split {
+ let h = 1 << (log2 - 1);
+ self.transform_tree(x0, y0, x0, y0, log2 - 1, depth + 1, 0, cbf_c)?;
+ self.transform_tree(x0 + h, y0, x0, y0, log2 - 1, depth + 1, 1, cbf_c)?;
+ self.transform_tree(x0, y0 + h, x0, y0, log2 - 1, depth + 1, 2, cbf_c)?;
+ self.transform_tree(x0 + h, y0 + h, x0, y0, log2 - 1, depth + 1, 3, cbf_c)?;
+ return Ok(());
+ }
+ let cbf_luma = if self.cu_intra || depth != 0 || cbf_c[0] || cbf_c[1] { self.dd(CBF_LUMA + if depth == 0 { 1 } else { 0 }) == 1 } else { true };
+ let n = 1 << log2;
+ if depth > 0 {
+ self.mark_edges(x0, y0, n, n, E_TU_V, E_TU_H);
+ }
+ self.transform_unit(x0, y0, xb, yb, log2, blk_idx, cbf_luma, cbf_c)
+ }
+
+ fn transform_unit(&mut self, x0: i32, y0: i32, xb: i32, yb: i32, log2: u32, blk_idx: u32, cbf_luma: bool, cbf_c: [bool; 2]) -> Result<()> {
+ let n = 1i32 << log2;
+ let chroma_here = log2 > 2 || blk_idx == 3;
+ let cbf_chroma = cbf_c[0] || cbf_c[1];
+ if (cbf_luma || cbf_chroma) && self.pps.cu_qp_delta_enabled && !self.is_cu_qp_delta_coded {
+ // cu_qp_delta_abs: prefix TU(5) with ctx 0,1,1,1,1, suffix EG0
+ let mut v = 0;
+ while v < 5 && self.dd(CU_QP_DELTA_ABS + if v == 0 { 0 } else { 1 }) == 1 {
+ v += 1;
+ }
+ if v == 5 {
+ let mut k = 0;
+ while self.bypass() == 1 {
+ v += 1 << k;
+ k += 1;
+ ensure!(k < 32, "invalid cu_qp_delta_abs");
+ }
+ v += self.bypass_bits(k) as i32;
+ }
+ if v != 0 && self.bypass() == 1 {
+ v = -v;
+ }
+ let off = 6 * (self.pic.bd_y as i32 - 8);
+ ensure!(v >= -(26 + off / 2) && v <= 25 + off / 2, "CuQpDeltaVal out of range");
+ self.is_cu_qp_delta_coded = true;
+ self.cu_qp_delta = v;
+ self.update_qp();
+ }
+ // luma
+ if self.cu_intra {
+ let mode = self.pic.blk_at(x0, y0).ipm as u32;
+ self.intra_predict(x0, y0, log2, 0, mode);
+ }
+ if cbf_luma {
+ let qp_bd = 6 * (self.pic.bd_y as i32 - 8);
+ let qp = self.qp_y + qp_bd;
+ self.residual(x0, y0, log2, 0, qp)?;
+ self.fill_blk(x0, y0, n, n, |b| b.flags |= F_CBF);
+ }
+ if !chroma_here {
+ return Ok(());
+ }
+ let (xc, yc, log2c) = if log2 > 2 { (x0 / 2, y0 / 2, log2 - 1) } else { (xb / 2, yb / 2, 2) };
+ for c in 1..3 {
+ if self.cu_intra {
+ let mode = self.intra_chroma_mode;
+ self.intra_predict(xc, yc, log2c, c, mode);
+ }
+ if cbf_c[c - 1] {
+ let qp = if c == 1 { self.qp_cb } else { self.qp_cr };
+ self.residual(xc, yc, log2c, c, qp)?;
+ }
+ }
+ Ok(())
+ }
+
+ /// Intra prediction of an n x n block of component `c` at component position (x0, y0).
+ fn intra_predict(&mut self, x0: i32, y0: i32, log2: u32, c: usize, mode: u32) {
+ let n = 1usize << log2;
+ let sc = if c == 0 { 1 } else { 2 };
+ let (xl, yl) = (x0 * sc, y0 * sc);
+ let unit = 4 / sc as usize; // component samples per 4x4 luma block
+ let stride = if c == 0 { self.pic.width } else { self.pic.cwidth };
+ let constrained = self.pps.constrained_intra_pred;
+ let mut al = [false; 129];
+ let mut at = [false; 129];
+ let addr = self.slice_addr;
+ let avail =
+ |pic: &PicState, xn: i32, yn: i32| -> bool { pic.zavail(xl, yl, xn, yn, addr) && (!constrained || pic.blk_at(xn, yn).flags & F_INTRA != 0) };
+ let plane = &self.pic.planes[c];
+ let r = &mut self.refs_buf;
+ // corner
+ if avail(self.pic, xl - 1, yl - 1) {
+ al[0] = true;
+ at[0] = true;
+ let v = plane[(y0 - 1) as usize * stride + (x0 - 1) as usize];
+ r.left[0] = v;
+ r.top[0] = v;
+ }
+ let mut k = 0;
+ while k < 2 * n {
+ let yn = y0 + k as i32;
+ if avail(self.pic, xl - 1, yn * sc) {
+ for i in 0..unit {
+ al[1 + k + i] = true;
+ r.left[1 + k + i] = plane[(yn as usize + i) * stride + (x0 - 1) as usize];
+ }
+ }
+ let xn = x0 + k as i32;
+ if avail(self.pic, xn * sc, yl - 1) {
+ let o = (y0 - 1) as usize * stride + xn as usize;
+ for i in 0..unit {
+ at[1 + k + i] = true;
+ r.top[1 + k + i] = plane[o + i];
+ }
+ }
+ k += unit;
+ }
+ let bd = if c == 0 { self.pic.bd_y } else { self.pic.bd_c };
+ intra::substitute(r, &al, &at, n, bd);
+ if c == 0 {
+ intra::filter(r, mode, n, self.sps.strong_intra_smoothing, true, bd);
+ }
+ let off = y0 as usize * stride + x0 as usize;
+ intra::predict(r, mode, n, c == 0, bd, &mut self.pic.planes[c][off..], stride);
+ }
+
+ /// residual_coding() + scaling + transform + reconstruction for one transform block.
+ fn residual(&mut self, x0: i32, y0: i32, log2: u32, c: usize, qp: i32) -> Result<()> {
+ let n = 1usize << log2;
+ let bypass = self.cu_transquant_bypass;
+ let ts = if self.pps.transform_skip && !bypass && log2 == 2 { self.dd(TRANSFORM_SKIP + (c > 0) as usize) == 1 } else { false };
+ // last significant coefficient
+ let cmax = (log2 << 1) - 1;
+ let (off, shift) = if c == 0 { (3 * (log2 - 2) + ((log2 - 1) >> 2), (log2 + 1) >> 2) } else { (15, log2 - 2) };
+ let mut px = 0;
+ while px < cmax && self.dd(LAST_X_PREFIX + (off + (px >> shift)) as usize) == 1 {
+ px += 1;
+ }
+ let mut py = 0;
+ while py < cmax && self.dd(LAST_Y_PREFIX + (off + (py >> shift)) as usize) == 1 {
+ py += 1;
+ }
+ let mut lx = px;
+ if px > 3 {
+ let nb = (px >> 1) - 1;
+ lx = (1 << nb) * (2 + (px & 1)) + self.bypass_bits(nb);
+ }
+ let mut ly = py;
+ if py > 3 {
+ let nb = (py >> 1) - 1;
+ ly = (1 << nb) * (2 + (py & 1)) + self.bypass_bits(nb);
+ }
+ // scanIdx (7.4.9.11)
+ let scan_idx = if self.cu_intra && (log2 == 2 || (log2 == 3 && c == 0)) {
+ let m = if c == 0 { self.pic.blk_at(x0, y0).ipm as u32 } else { self.intra_chroma_mode };
+ if (6..=14).contains(&m) {
+ 2
+ } else if (22..=30).contains(&m) {
+ 1
+ } else {
+ 0
+ }
+ } else {
+ 0
+ };
+ if scan_idx == 2 {
+ std::mem::swap(&mut lx, &mut ly);
+ }
+ ensure!((lx as usize) < n && (ly as usize) < n, "last significant coefficient outside the block");
+ let log2sb = log2 - 2;
+ let sb_scan = scan_order(log2sb, scan_idx);
+ let pos_scan = &SCAN_4[scan_idx];
+ let sb_w = 1usize << log2sb;
+ let last_sb = sb_scan.iter().position(|&(x, y)| x as u32 == lx >> 2 && y as u32 == ly >> 2).unwrap_or(0);
+ let last_pos = pos_scan.iter().position(|&(x, y)| x as u32 == lx & 3 && y as u32 == ly & 3).unwrap_or(0);
+ self.coeffs[..n * n].fill(0);
+ let mut csbf = [0u8; 64];
+ let mut prev_g1: Option<u32> = None;
+ let sdh = self.pps.sign_data_hiding && !bypass;
+ let (mut max_x, mut max_y) = (0usize, 0usize);
+ let c_off_sig = if c == 0 { 0 } else { 27 };
+ for i in (0..=last_sb).rev() {
+ let (xs, ys) = (sb_scan[i].0 as usize, sb_scan[i].1 as usize);
+ let mut infer_dc = false;
+ let right = if xs + 1 < sb_w { csbf[ys * 8 + xs + 1] } else { 0 };
+ let below = if ys + 1 < sb_w { csbf[(ys + 1) * 8 + xs] } else { 0 };
+ if i < last_sb && i > 0 {
+ let inc = (right | below).min(1) as usize + if c > 0 { 2 } else { 0 };
+ csbf[ys * 8 + xs] = self.c.decode_decision(CODED_SUB_BLOCK + inc) as u8;
+ infer_dc = true;
+ } else {
+ csbf[ys * 8 + xs] = 1;
+ }
+ // significance map
+ let mut sig = [0u8; 16]; // scan positions n of significant coefficients, descending
+ let mut nsig = 0;
+ let start: i32 = if i == last_sb {
+ sig[0] = last_pos as u8;
+ nsig = 1;
+ last_pos as i32 - 1
+ } else {
+ 15
+ };
+ if csbf[ys * 8 + xs] != 0 {
+ let prev_csbf = right + (below << 1);
+ let mut np = start;
+ while np >= 0 {
+ let (xp, yp) = (pos_scan[np as usize].0 as usize, pos_scan[np as usize].1 as usize);
+ let (xc, yc) = (xs * 4 + xp, ys * 4 + yp);
+ if np > 0 || !infer_dc {
+ let sig_ctx = if log2 == 2 {
+ CTX_IDX_MAP[(yc << 2) + xc] as usize
+ } else if xc + yc == 0 {
+ 0
+ } else {
+ let mut s = match prev_csbf {
+ 0 => {
+ if xp + yp == 0 {
+ 2
+ } else if xp + yp < 3 {
+ 1
+ } else {
+ 0
+ }
+ }
+ 1 => {
+ if yp == 0 {
+ 2
+ } else if yp == 1 {
+ 1
+ } else {
+ 0
+ }
+ }
+ 2 => {
+ if xp == 0 {
+ 2
+ } else if xp == 1 {
+ 1
+ } else {
+ 0
+ }
+ }
+ _ => 2,
+ };
+ if c == 0 {
+ if xs + ys > 0 {
+ s += 3;
+ }
+ s += if log2 == 3 { if scan_idx == 0 { 9 } else { 15 } } else { 21 };
+ } else {
+ s += if log2 == 3 { 9 } else { 12 };
+ }
+ s
+ };
+ if self.c.decode_decision(SIG_COEFF + c_off_sig + sig_ctx) == 1 {
+ sig[nsig] = np as u8;
+ nsig += 1;
+ infer_dc = false;
+ }
+ } else {
+ // np == 0 with inferSbDcSigCoeffFlag
+ sig[nsig] = 0;
+ nsig += 1;
+ }
+ np -= 1;
+ }
+ }
+ if nsig == 0 {
+ continue;
+ }
+ // greater1 / greater2 flags
+ let mut ctx_set = if i == 0 || c > 0 { 0 } else { 2 };
+ if let Some(g) = prev_g1
+ && g == 0
+ {
+ ctx_set += 1;
+ }
+ let mut g1ctx = 1u32;
+ let mut gt1 = [0u8; 16];
+ let mut first_g1: Option<usize> = None;
+ let c_off_g1 = if c > 0 { 16 } else { 0 };
+ for k in 0..nsig.min(8) {
+ let inc = ctx_set * 4 + g1ctx.min(3) as usize + c_off_g1;
+ let f = self.c.decode_decision(GT1 + inc);
+ gt1[k] = f as u8;
+ if f == 1 {
+ g1ctx = 0;
+ if first_g1.is_none() {
+ first_g1 = Some(k);
+ }
+ } else if g1ctx > 0 {
+ g1ctx += 1;
+ }
+ }
+ prev_g1 = Some(g1ctx);
+ let mut gt2 = 0u8;
+ if let Some(k) = first_g1 {
+ gt2 = self.c.decode_decision(GT2 + ctx_set + if c > 0 { 4 } else { 0 }) as u8;
+ let _ = k;
+ }
+ // signs
+ let last_sig_pos = sig[0] as i32;
+ let first_sig_pos = sig[nsig - 1] as i32;
+ let sign_hidden = sdh && last_sig_pos - first_sig_pos > 3;
+ let nsigns = if sign_hidden { nsig - 1 } else { nsig };
+ let mut signs = if nsigns > 0 { self.bypass_bits(nsigns as u32) << (32 - nsigns) } else { 0 };
+ // remaining levels
+ let mut rice = 0u32;
+ let mut sum_abs = 0i32;
+ for k in 0..nsig {
+ let mut base = 1 + gt1[k] as i32;
+ if Some(k) == first_g1 {
+ base += gt2 as i32;
+ }
+ let thresh = if k < 8 { if Some(k) == first_g1 { 3 } else { 2 } } else { 1 };
+ let mut level = base;
+ if base == thresh {
+ let rem = self.coeff_abs_level_remaining(rice)?;
+ level = base + rem;
+ if level > 3 * (1 << rice) {
+ rice = (rice + 1).min(4);
+ }
+ }
+ let np = sig[k] as usize;
+ let (xc, yc) = (xs * 4 + pos_scan[np].0 as usize, ys * 4 + pos_scan[np].1 as usize);
+ let mut v = level;
+ if !(sign_hidden && k == nsig - 1) {
+ if signs & 0x8000_0000 != 0 {
+ v = -v;
+ }
+ signs <<= 1;
+ }
+ if sign_hidden {
+ sum_abs += level;
+ if k == nsig - 1 && sum_abs & 1 == 1 {
+ v = -v;
+ }
+ }
+ self.coeffs[yc * n + xc] = v;
+ max_x = max_x.max(xc);
+ max_y = max_y.max(yc);
+ }
+ }
+ self.reconstruct(x0, y0, log2, c, qp, ts, max_x, max_y)
+ }
+
+ fn coeff_abs_level_remaining(&mut self, rice: u32) -> Result<i32> {
+ let mut prefix = 0u32;
+ while prefix < 32 && self.bypass() == 1 {
+ prefix += 1;
+ }
+ ensure!(prefix < 32, "invalid coeff_abs_level_remaining");
+ if prefix <= 3 {
+ Ok(((prefix << rice) + self.bypass_bits(rice)) as i32)
+ } else {
+ let nb = prefix - 3 + rice;
+ ensure!(nb <= 24, "coeff_abs_level_remaining too large");
+ Ok(((((1u32 << (prefix - 3)) + 2) << rice) + self.bypass_bits(nb)) as i32)
+ }
+ }
+
+ /// Scaling, transform and addition to the prediction.
+ fn reconstruct(&mut self, x0: i32, y0: i32, log2: u32, c: usize, qp: i32, ts: bool, max_x: usize, max_y: usize) -> Result<()> {
+ let n = 1usize << log2;
+ let bd = if c == 0 { self.pic.bd_y } else { self.pic.bd_c };
+ let coeffs = &mut self.coeffs[..n * n];
+ let mut dc_only = false;
+ if !self.cu_transquant_bypass {
+ // scaling (8.6.3)
+ let bd_shift = bd + log2 - 5;
+ let round = 1i64 << (bd_shift - 1);
+ let scale = (LEVEL_SCALE[(qp % 6) as usize] as i64) << (qp / 6);
+ let m: Option<&[u8]> = match &self.pic.scaling {
+ Some(s) if !(ts && n > 4) => {
+ let size_id = (log2 - 2) as usize;
+ let matrix_id = if self.cu_intra { c } else { 3 + c };
+ Some(&s[size_id * 6 + matrix_id])
+ }
+ _ => None,
+ };
+ for y in 0..=max_y {
+ for x in 0..=max_x {
+ let v = coeffs[y * n + x];
+ if v != 0 {
+ let f = m.map_or(16, |m| m[y * n + x] as i64);
+ coeffs[y * n + x] = ((v as i64 * f * scale + round) >> bd_shift).clamp(-32768, 32767) as i32;
+ }
+ }
+ }
+ let bd_shift = 20 - bd;
+ if ts {
+ transform::transform_skip(coeffs, n, bd_shift);
+ } else if max_x == 0 && max_y == 0 && !(self.cu_intra && c == 0 && n == 4) {
+ let v = transform::inverse_dc(coeffs[0], bd_shift);
+ coeffs.fill(v);
+ dc_only = true;
+ } else {
+ let dst = self.cu_intra && c == 0 && n == 4;
+ transform::inverse_transform(coeffs, n, dst, max_x, max_y, bd_shift);
+ }
+ }
+ let _ = dc_only;
+ let (stride, max) = (if c == 0 { self.pic.width } else { self.pic.cwidth }, (1i32 << bd) - 1);
+ let plane = &mut self.pic.planes[c];
+ for y in 0..n {
+ let row = &mut plane[(y0 as usize + y) * stride + x0 as usize..][..n];
+ for (x, s) in row.iter_mut().enumerate() {
+ *s = (*s as i32 + coeffs[y * n + x]).clamp(0, max) as u16;
+ }
+ }
+ Ok(())
+ }
+
+ /// prediction_unit(): parse, derive motion, store it and predict. Returns merge_flag.
+ fn prediction_unit(&mut self, xc: i32, yc: i32, ncb: i32, xp: i32, yp: i32, w: i32, h: i32, part_idx: usize, part: PartMode, skip: bool) -> Result<bool> {
+ let merge = if skip { true } else { self.dd(MERGE_FLAG) == 1 };
+ let mvf = if merge {
+ let idx = if self.sh.max_num_merge_cand > 1 {
+ let mut i = 0;
+ if self.dd(MERGE_IDX) == 1 {
+ i = 1;
+ while i < self.sh.max_num_merge_cand - 1 && self.bypass() == 1 {
+ i += 1;
+ }
+ }
+ i
+ } else {
+ 0
+ };
+ self.derive_merge(xc, yc, ncb, xp, yp, w, h, part_idx, part, idx as usize)
+ } else {
+ let pred_idc = if self.sh.is_b() {
+ if w + h != 12 {
+ let depth = self.pic.blk_at(xc, yc).depth as usize;
+ if self.dd(INTER_PRED_IDC + depth) == 1 { 2 } else { self.dd(INTER_PRED_IDC + 4) }
+ } else {
+ self.dd(INTER_PRED_IDC + 4)
+ }
+ } else {
+ 0
+ };
+ let mut ref_idx = [-1i8; 2];
+ let mut mvd = [[0i32; 2]; 2];
+ let mut mvp_flag = [0u32; 2];
+ for l in 0..2 {
+ let used = if l == 0 { pred_idc != 1 } else { pred_idc != 0 };
+ if !used {
+ continue;
+ }
+ let nref = self.sh.num_ref_idx[l];
+ let mut ri = 0;
+ if nref > 1 {
+ while ri < nref - 1 {
+ let bin = if ri < 2 { self.dd(REF_IDX + ri as usize) } else { self.bypass() };
+ if bin == 0 {
+ break;
+ }
+ ri += 1;
+ }
+ }
+ ref_idx[l] = ri as i8;
+ if l == 1 && self.sh.mvd_l1_zero && pred_idc == 2 {
+ mvd[1] = [0, 0];
+ } else {
+ mvd[l] = self.mvd_coding()?;
+ }
+ mvp_flag[l] = self.dd(MVP_FLAG);
+ }
+ let mut f = MvField { mv: [[0; 2]; 2], ref_idx };
+ for l in 0..2 {
+ if ref_idx[l] < 0 {
+ continue;
+ }
+ let mvp = self.derive_amvp(xc, yc, ncb, xp, yp, w, h, part_idx, l, ref_idx[l] as usize, mvp_flag[l] as usize);
+ // mvLX = (mvp + mvd) wrapped to 16 bits (8-94)
+ f.mv[l] = [(mvp[0] as i32 + mvd[l][0]) as i16, (mvp[1] as i32 + mvd[l][1]) as i16];
+ }
+ f
+ };
+ for l in 0..2 {
+ if mvf.ref_idx[l] >= 0 {
+ ensure!((mvf.ref_idx[l] as usize) < self.refs[l].len(), "reference index out of range");
+ }
+ }
+ // store motion
+ let w4 = self.pic.w4;
+ for by in (yp >> 2)..((yp + h) >> 2) {
+ let o = by as usize * w4;
+ self.pic.mvf[o + (xp >> 2) as usize..o + ((xp + w) >> 2) as usize].fill(mvf);
+ }
+ self.motion_compensate(xp, yp, w as usize, h as usize, &mvf);
+ Ok(merge)
+ }
+
+ fn mvd_coding(&mut self) -> Result<[i32; 2]> {
+ let g0 = [self.dd(ABS_MVD_GT0), self.dd(ABS_MVD_GT0)];
+ let mut g1 = [0, 0];
+ for k in 0..2 {
+ if g0[k] == 1 {
+ g1[k] = self.dd(ABS_MVD_GT1);
+ }
+ }
+ let mut out = [0i32; 2];
+ for k in 0..2 {
+ if g0[k] == 1 {
+ let mut v = 1i32;
+ if g1[k] == 1 {
+ // EG1
+ let mut kk = 1;
+ let mut val = 0i32;
+ while self.bypass() == 1 {
+ val += 1 << kk;
+ kk += 1;
+ ensure!(kk < 31, "invalid abs_mvd_minus2");
+ }
+ val += self.bypass_bits(kk) as i32;
+ v = val + 2;
+ }
+ if self.bypass() == 1 {
+ v = -v;
+ }
+ out[k] = v;
+ }
+ }
+ Ok(out)
+ }
+
+ /// Motion compensation + weighted prediction of one PU into the picture.
+ fn motion_compensate(&mut self, xp: i32, yp: i32, w: usize, h: usize, f: &MvField) {
+ let weighted = match self.sh.slice_type {
+ SliceType::P => self.pps.weighted_pred,
+ SliceType::B => self.pps.weighted_bipred,
+ SliceType::I => false,
+ };
+ let bi = f.pred(0) && f.pred(1);
+ for c in 0..3 {
+ let (x, y, bw, bh, bd) = if c == 0 { (xp, yp, w, h, self.pic.bd_y) } else { (xp / 2, yp / 2, w / 2, h / 2, self.pic.bd_c) };
+ let mut lists = [false; 2];
+ for l in 0..2 {
+ if !f.pred(l) {
+ continue;
+ }
+ lists[l] = true;
+ let frame = &self.refs[l][f.ref_idx[l] as usize].frame;
+ let buf = if l == 0 || !bi { &mut self.pred0 } else { &mut self.pred1 };
+ if c == 0 {
+ inter::mc_luma(frame, x, y, f.mv[l], bw, bh, buf);
+ } else {
+ inter::mc_chroma(frame, c - 1, x, y, f.mv[l], bw, bh, buf);
+ }
+ }
+ let stride = if c == 0 { self.pic.width } else { self.pic.cwidth };
+ let dst = &mut self.pic.planes[c][y as usize * stride + x as usize..];
+ if !weighted {
+ if bi {
+ inter::put_bi(&self.pred0, &self.pred1, bw, bh, bd, dst, stride);
+ } else {
+ inter::put_uni(&self.pred0, bw, bh, bd, dst, stride);
+ }
+ continue;
+ }
+ let pwt = self.sh.pwt.as_ref().expect("weighted prediction table");
+ let shift1 = 14 - bd;
+ let log2wd = if c == 0 { pwt.luma_log2_denom } else { pwt.chroma_log2_denom } + shift1;
+ let get = |l: usize| -> (i32, i32) {
+ let e = &pwt.l[l][f.ref_idx[l] as usize];
+ let (wt, o) = if c == 0 { e.luma } else { e.chroma[c - 1] };
+ (wt, o << (bd - 8))
+ };
+ if bi {
+ let (w0, o0) = get(0);
+ let (w1, o1) = get(1);
+ inter::put_weighted_bi(&self.pred0, &self.pred1, bw, bh, bd, log2wd, w0, w1, o0, o1, dst, stride);
+ } else {
+ let l = if lists[0] { 0 } else { 1 };
+ let (wt, o) = get(l);
+ inter::put_weighted_uni(&self.pred0, bw, bh, bd, log2wd, wt, o, dst, stride);
+ }
+ }
+ }
+}
diff --git a/crates/hevc/src/spec_tables.rs b/crates/hevc/src/spec_tables.rs
new file mode 100644
index 000000000..a68cd518f
--- /dev/null
+++ b/crates/hevc/src/spec_tables.rs
@@ -0,0 +1,101 @@
+// Generated by crates/hevc/tools/extract_tables.py from the text of Rec. ITU-T H.265. Do not edit.
+
+// CABAC context layout: offset of each syntax element in the context array (Table 9-4).
+pub const SAO_MERGE: usize = 0;
+pub const SAO_TYPE: usize = 1;
+pub const SPLIT_CU: usize = 2;
+pub const CU_TRANSQUANT_BYPASS: usize = 5;
+pub const CU_SKIP: usize = 6;
+pub const PRED_MODE: usize = 9;
+pub const PART_MODE: usize = 10;
+pub const PREV_INTRA_LUMA: usize = 14;
+pub const INTRA_CHROMA: usize = 15;
+pub const RQT_ROOT_CBF: usize = 16;
+pub const MERGE_FLAG: usize = 17;
+pub const MERGE_IDX: usize = 18;
+pub const INTER_PRED_IDC: usize = 19;
+pub const REF_IDX: usize = 24;
+pub const MVP_FLAG: usize = 26;
+pub const SPLIT_TRANSFORM: usize = 27;
+pub const CBF_LUMA: usize = 30;
+pub const CBF_CHROMA: usize = 32;
+pub const ABS_MVD_GT0: usize = 37;
+pub const ABS_MVD_GT1: usize = 38;
+pub const CU_QP_DELTA_ABS: usize = 39;
+pub const TRANSFORM_SKIP: usize = 41;
+pub const LAST_X_PREFIX: usize = 43;
+pub const LAST_Y_PREFIX: usize = 61;
+pub const CODED_SUB_BLOCK: usize = 79;
+pub const SIG_COEFF: usize = 83;
+pub const GT1: usize = 127;
+pub const GT2: usize = 151;
+pub const EXPLICIT_RDPCM: usize = 157;
+pub const EXPLICIT_RDPCM_DIR: usize = 159;
+pub const CU_CHROMA_QP_OFFSET_FLAG: usize = 161;
+pub const CU_CHROMA_QP_OFFSET_IDX: usize = 162;
+pub const NUM_CTX: usize = 163;
+
+/// initValue per initType (9.3.2.2).
+pub static CABAC_INIT: [[u8; NUM_CTX]; 3] = [
+ [153, 200, 139, 141, 157, 154, 154, 154, 154, 154, 184, 154, 154, 154, 184, 63, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 154, 153, 138, 138, 111, 141, 94, 138, 182, 154, 154, 154, 154, 154, 154, 139, 139, 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63, 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63, 91, 171, 134, 141, 111, 111, 125, 110, 110, 94, 124, 108, 124, 107, 125, 141, 179, 153, 125, 107, 125, 141, 179, 153, 125, 107, 125, 141, 179, 153, 125, 140, 139, 182, 182, 152, 136, 152, 136, 153, 136, 139, 111, 136, 139, 111, 141, 111, 140, 92, 137, 138, 140, 152, 138, 139, 153, 74, 149, 92, 139, 107, 122, 152, 140, 179, 166, 182, 140, 227, 122, 197, 138, 153, 136, 167, 152, 152, 154, 154, 154, 154, 154, 154],
+ [153, 185, 107, 139, 126, 154, 197, 185, 201, 149, 154, 139, 154, 154, 154, 152, 79, 110, 122, 95, 79, 63, 31, 31, 153, 153, 168, 124, 138, 94, 153, 111, 149, 107, 167, 154, 154, 140, 198, 154, 154, 139, 139, 125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 108, 123, 108, 125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 108, 123, 108, 121, 140, 61, 154, 155, 154, 139, 153, 139, 123, 123, 63, 153, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 170, 153, 123, 123, 107, 121, 107, 121, 167, 151, 183, 140, 151, 183, 140, 140, 140, 154, 196, 196, 167, 154, 152, 167, 182, 182, 134, 149, 136, 153, 121, 136, 137, 169, 194, 166, 167, 154, 167, 137, 182, 107, 167, 91, 122, 107, 167, 139, 139, 139, 139, 154, 154],
+ [153, 160, 107, 139, 126, 154, 197, 185, 201, 134, 154, 139, 154, 154, 183, 152, 79, 154, 137, 95, 79, 63, 31, 31, 153, 153, 168, 224, 167, 122, 153, 111, 149, 92, 167, 154, 154, 169, 198, 154, 154, 139, 139, 125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 108, 123, 93, 125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 108, 123, 93, 121, 140, 61, 154, 170, 154, 139, 153, 139, 123, 123, 63, 124, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 170, 153, 138, 138, 122, 121, 122, 121, 167, 151, 183, 140, 151, 183, 140, 140, 140, 154, 196, 167, 167, 154, 152, 167, 182, 182, 134, 149, 136, 153, 121, 136, 122, 169, 208, 166, 167, 154, 152, 167, 182, 107, 167, 91, 107, 107, 167, 139, 139, 139, 139, 154, 154],
+];
+
+/// Table 7-6: default ScalingList[1..3][0..2] (intra) and [3..5] (inter), in up-right diagonal order.
+pub static DEFAULT_SCALING_INTRA: [u8; 64] = [16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 16, 17, 16, 17, 18, 17, 18, 18, 17, 18, 21, 19, 20, 21, 20, 19, 21, 24, 22, 22, 24, 24, 22, 22, 24, 25, 25, 27, 30, 27, 25, 25, 29, 31, 35, 35, 31, 29, 36, 41, 44, 41, 36, 47, 54, 54, 47, 65, 70, 65, 88, 88, 115];
+pub static DEFAULT_SCALING_INTER: [u8; 64] = [16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 20, 20, 20, 20, 20, 20, 20, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 28, 28, 28, 28, 28, 28, 33, 33, 33, 33, 33, 41, 41, 41, 41, 54, 54, 54, 71, 71, 91];
+
+/// Table 8-5: intraPredAngle for predModeIntra 0..34 (0 for planar / DC).
+pub static INTRA_PRED_ANGLE: [i8; 35] = [0, 0, 32, 26, 21, 17, 13, 9, 5, 2, 0, -2, -5, -9, -13, -17, -21, -26, -32, -26, -21, -17, -13, -9, -5, -2, 0, 2, 5, 9, 13, 17, 21, 26, 32];
+/// Table 8-6: invAngle for predModeIntra 11..25 (index = mode - 11).
+pub static INV_ANGLE: [i16; 15] = [-4096, -1638, -910, -630, -482, -390, -315, -256, -315, -390, -482, -630, -910, -1638, -4096];
+
+/// Table 8-10: QpC for qPi = 30..43 (qPi < 30: QpC = qPi; qPi > 43: QpC = qPi - 6).
+pub static QPC_30_43: [u8; 14] = [29, 30, 31, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37];
+
+/// Table 8-12: beta' for Q = 0..51.
+pub static BETA_TABLE: [u8; 52] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64];
+/// Table 8-12: tC' for Q = 0..53.
+pub static TC_TABLE: [u8; 54] = [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, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5, 6, 6, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22, 24];
+
+/// Luma 8-tap interpolation filter fL[xFrac][k] (8-236..8-238), taps at offsets -3..4.
+pub static LUMA_FILTER: [[i8; 8]; 4] = [[0, 0, 0, 64, 0, 0, 0, 0], [-1, 4, -10, 58, 17, -5, 1, 0], [-1, 4, -11, 40, 40, -11, 4, -1], [0, 1, -5, 17, 58, -10, 4, -1]];
+/// Chroma 4-tap interpolation filter fC[xFrac][k] (8-255..8-261), taps at offsets -1..2.
+pub static CHROMA_FILTER: [[i8; 4]; 8] = [[0, 64, 0, 0], [-2, 58, 10, -2], [-4, 54, 16, -2], [-6, 46, 28, -4], [-4, 36, 36, -4], [-4, 28, 46, -6], [-2, 16, 54, -4], [-2, 10, 58, -2]];
+
+/// DCT matrix (8-319, 8-321): TRANS_MATRIX[n][m] = transMatrix[m][n] (row n = basis function).
+pub static TRANS_MATRIX: [[i8; 32]; 32] = [
+ [64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64],
+ [90, 90, 88, 85, 82, 78, 73, 67, 61, 54, 46, 38, 31, 22, 13, 4, -4, -13, -22, -31, -38, -46, -54, -61, -67, -73, -78, -82, -85, -88, -90, -90],
+ [90, 87, 80, 70, 57, 43, 25, 9, -9, -25, -43, -57, -70, -80, -87, -90, -90, -87, -80, -70, -57, -43, -25, -9, 9, 25, 43, 57, 70, 80, 87, 90],
+ [90, 82, 67, 46, 22, -4, -31, -54, -73, -85, -90, -88, -78, -61, -38, -13, 13, 38, 61, 78, 88, 90, 85, 73, 54, 31, 4, -22, -46, -67, -82, -90],
+ [89, 75, 50, 18, -18, -50, -75, -89, -89, -75, -50, -18, 18, 50, 75, 89, 89, 75, 50, 18, -18, -50, -75, -89, -89, -75, -50, -18, 18, 50, 75, 89],
+ [88, 67, 31, -13, -54, -82, -90, -78, -46, -4, 38, 73, 90, 85, 61, 22, -22, -61, -85, -90, -73, -38, 4, 46, 78, 90, 82, 54, 13, -31, -67, -88],
+ [87, 57, 9, -43, -80, -90, -70, -25, 25, 70, 90, 80, 43, -9, -57, -87, -87, -57, -9, 43, 80, 90, 70, 25, -25, -70, -90, -80, -43, 9, 57, 87],
+ [85, 46, -13, -67, -90, -73, -22, 38, 82, 88, 54, -4, -61, -90, -78, -31, 31, 78, 90, 61, 4, -54, -88, -82, -38, 22, 73, 90, 67, 13, -46, -85],
+ [83, 36, -36, -83, -83, -36, 36, 83, 83, 36, -36, -83, -83, -36, 36, 83, 83, 36, -36, -83, -83, -36, 36, 83, 83, 36, -36, -83, -83, -36, 36, 83],
+ [82, 22, -54, -90, -61, 13, 78, 85, 31, -46, -90, -67, 4, 73, 88, 38, -38, -88, -73, -4, 67, 90, 46, -31, -85, -78, -13, 61, 90, 54, -22, -82],
+ [80, 9, -70, -87, -25, 57, 90, 43, -43, -90, -57, 25, 87, 70, -9, -80, -80, -9, 70, 87, 25, -57, -90, -43, 43, 90, 57, -25, -87, -70, 9, 80],
+ [78, -4, -82, -73, 13, 85, 67, -22, -88, -61, 31, 90, 54, -38, -90, -46, 46, 90, 38, -54, -90, -31, 61, 88, 22, -67, -85, -13, 73, 82, 4, -78],
+ [75, -18, -89, -50, 50, 89, 18, -75, -75, 18, 89, 50, -50, -89, -18, 75, 75, -18, -89, -50, 50, 89, 18, -75, -75, 18, 89, 50, -50, -89, -18, 75],
+ [73, -31, -90, -22, 78, 67, -38, -90, -13, 82, 61, -46, -88, -4, 85, 54, -54, -85, 4, 88, 46, -61, -82, 13, 90, 38, -67, -78, 22, 90, 31, -73],
+ [70, -43, -87, 9, 90, 25, -80, -57, 57, 80, -25, -90, -9, 87, 43, -70, -70, 43, 87, -9, -90, -25, 80, 57, -57, -80, 25, 90, 9, -87, -43, 70],
+ [67, -54, -78, 38, 85, -22, -90, 4, 90, 13, -88, -31, 82, 46, -73, -61, 61, 73, -46, -82, 31, 88, -13, -90, -4, 90, 22, -85, -38, 78, 54, -67],
+ [64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64],
+ [61, -73, -46, 82, 31, -88, -13, 90, -4, -90, 22, 85, -38, -78, 54, 67, -67, -54, 78, 38, -85, -22, 90, 4, -90, 13, 88, -31, -82, 46, 73, -61],
+ [57, -80, -25, 90, -9, -87, 43, 70, -70, -43, 87, 9, -90, 25, 80, -57, -57, 80, 25, -90, 9, 87, -43, -70, 70, 43, -87, -9, 90, -25, -80, 57],
+ [54, -85, -4, 88, -46, -61, 82, 13, -90, 38, 67, -78, -22, 90, -31, -73, 73, 31, -90, 22, 78, -67, -38, 90, -13, -82, 61, 46, -88, 4, 85, -54],
+ [50, -89, 18, 75, -75, -18, 89, -50, -50, 89, -18, -75, 75, 18, -89, 50, 50, -89, 18, 75, -75, -18, 89, -50, -50, 89, -18, -75, 75, 18, -89, 50],
+ [46, -90, 38, 54, -90, 31, 61, -88, 22, 67, -85, 13, 73, -82, 4, 78, -78, -4, 82, -73, -13, 85, -67, -22, 88, -61, -31, 90, -54, -38, 90, -46],
+ [43, -90, 57, 25, -87, 70, 9, -80, 80, -9, -70, 87, -25, -57, 90, -43, -43, 90, -57, -25, 87, -70, -9, 80, -80, 9, 70, -87, 25, 57, -90, 43],
+ [38, -88, 73, -4, -67, 90, -46, -31, 85, -78, 13, 61, -90, 54, 22, -82, 82, -22, -54, 90, -61, -13, 78, -85, 31, 46, -90, 67, 4, -73, 88, -38],
+ [36, -83, 83, -36, -36, 83, -83, 36, 36, -83, 83, -36, -36, 83, -83, 36, 36, -83, 83, -36, -36, 83, -83, 36, 36, -83, 83, -36, -36, 83, -83, 36],
+ [31, -78, 90, -61, 4, 54, -88, 82, -38, -22, 73, -90, 67, -13, -46, 85, -85, 46, 13, -67, 90, -73, 22, 38, -82, 88, -54, -4, 61, -90, 78, -31],
+ [25, -70, 90, -80, 43, 9, -57, 87, -87, 57, -9, -43, 80, -90, 70, -25, -25, 70, -90, 80, -43, -9, 57, -87, 87, -57, 9, 43, -80, 90, -70, 25],
+ [22, -61, 85, -90, 73, -38, -4, 46, -78, 90, -82, 54, -13, -31, 67, -88, 88, -67, 31, 13, -54, 82, -90, 78, -46, 4, 38, -73, 90, -85, 61, -22],
+ [18, -50, 75, -89, 89, -75, 50, -18, -18, 50, -75, 89, -89, 75, -50, 18, 18, -50, 75, -89, 89, -75, 50, -18, -18, 50, -75, 89, -89, 75, -50, 18],
+ [13, -38, 61, -78, 88, -90, 85, -73, 54, -31, 4, 22, -46, 67, -82, 90, -90, 82, -67, 46, -22, -4, 31, -54, 73, -85, 90, -88, 78, -61, 38, -13],
+ [9, -25, 43, -57, 70, -80, 87, -90, 90, -87, 80, -70, 57, -43, 25, -9, -9, 25, -43, 57, -70, 80, -87, 90, -90, 87, -80, 70, -57, 43, -25, 9],
+ [4, -13, 22, -31, 38, -46, 54, -61, 67, -73, 78, -82, 85, -88, 90, -90, 90, -90, 88, -85, 82, -78, 73, -67, 61, -54, 46, -38, 31, -22, 13, -4],
+];
diff --git a/crates/hevc/src/tables.rs b/crates/hevc/src/tables.rs
new file mode 100644
index 000000000..bce0b7a9d
--- /dev/null
+++ b/crates/hevc/src/tables.rs
@@ -0,0 +1,123 @@
+//! Derived tables: scan orders (6.5.3 - 6.5.5), chroma QP mapping and small helper tables.
+
+pub use crate::spec_tables::*;
+
+/// Up-right diagonal scan (6.5.3) of a `N x N` block as (x, y) pairs.
+const fn diag<const L: usize>(n: usize) -> [(u8, u8); L] {
+ let mut out = [(0u8, 0u8); L];
+ let mut i = 0;
+ let mut x: i32 = 0;
+ let mut y: i32 = 0;
+ while i < L {
+ while y >= 0 {
+ if (x as usize) < n && (y as usize) < n {
+ out[i] = (x as u8, y as u8);
+ i += 1;
+ }
+ y -= 1;
+ x += 1;
+ }
+ y = x;
+ x = 0;
+ }
+ out
+}
+
+/// Horizontal (6.5.4, `vertical == false`) or vertical (6.5.5) scan.
+const fn hv<const L: usize>(n: usize, vertical: bool) -> [(u8, u8); L] {
+ let mut out = [(0u8, 0u8); L];
+ let mut i = 0;
+ while i < L {
+ let (a, b) = ((i % n) as u8, (i / n) as u8);
+ out[i] = if vertical { (b, a) } else { (a, b) };
+ i += 1;
+ }
+ out
+}
+
+pub static SCAN_1: [[(u8, u8); 1]; 3] = [[(0, 0)], [(0, 0)], [(0, 0)]];
+pub static SCAN_2: [[(u8, u8); 4]; 3] = [diag::<4>(2), hv::<4>(2, false), hv::<4>(2, true)];
+pub static SCAN_4: [[(u8, u8); 16]; 3] = [diag::<16>(4), hv::<16>(4, false), hv::<16>(4, true)];
+pub static SCAN_8: [[(u8, u8); 64]; 3] = [diag::<64>(8), hv::<64>(8, false), hv::<64>(8, true)];
+
+/// ScanOrder[log2BlockSize][scanIdx] (log2BlockSize 0..=3).
+#[inline]
+pub fn scan_order(log2: u32, scan_idx: usize) -> &'static [(u8, u8)] {
+ match log2 {
+ 0 => &SCAN_1[scan_idx],
+ 1 => &SCAN_2[scan_idx],
+ 2 => &SCAN_4[scan_idx],
+ _ => &SCAN_8[scan_idx],
+ }
+}
+
+/// Up-right diagonal scan for log2 size 2 or 3.
+pub fn scan_diag(log2: u32) -> &'static [(u8, u8)] {
+ scan_order(log2, 0)
+}
+
+/// Table 8-10: QpC as a function of qPi (ChromaArrayType 1).
+#[inline]
+pub fn qpc_420(qpi: i32) -> i32 {
+ if qpi < 30 {
+ qpi
+ } else if qpi > 43 {
+ qpi - 6
+ } else {
+ QPC_30_43[(qpi - 30) as usize] as i32
+ }
+}
+
+/// Table 9-50 ctxIdxMap for 4x4 sig_coeff_flag contexts.
+pub static CTX_IDX_MAP: [u8; 16] = [0, 1, 4, 5, 2, 3, 4, 5, 6, 6, 8, 8, 7, 7, 8, 8];
+
+/// levelScale (8-309).
+pub static LEVEL_SCALE: [i32; 6] = [40, 45, 51, 57, 64, 72];
+
+/// DST-VII 4x4 matrix (8.6.4.2, trType 1).
+pub static DST_MATRIX: [[i8; 4]; 4] = [[29, 55, 74, 84], [74, 74, 0, -74], [84, -29, -74, 55], [55, -84, 74, -29]];
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn diagonal_scan_4x4() {
+ let s = &SCAN_4[0];
+ assert_eq!(&s[..6], &[(0, 0), (0, 1), (1, 0), (0, 2), (1, 1), (2, 0)]);
+ assert_eq!(s[15], (3, 3));
+ assert_eq!(SCAN_2[0], [(0, 0), (0, 1), (1, 0), (1, 1)]);
+ assert_eq!(SCAN_4[2][1], (0, 1));
+ assert_eq!(SCAN_4[1][1], (1, 0));
+ }
+
+ #[test]
+ fn dct_matrix_properties() {
+ // rows are nearly orthogonal with norm ~ 64^2 * 32
+ for a in 0..32 {
+ for b in 0..32 {
+ let d: i64 = (0..32).map(|k| TRANS_MATRIX[a][k] as i64 * TRANS_MATRIX[b][k] as i64).sum();
+ if a == b {
+ assert!((d - 131072).abs() < 1000, "row {a} norm {d}");
+ } else {
+ assert!(d.abs() < 1000, "rows {a},{b}: {d}");
+ }
+ }
+ }
+ // even basis functions are symmetric, odd ones antisymmetric
+ for n in 0..32 {
+ for m in 0..16 {
+ let (a, b) = (TRANS_MATRIX[n][m] as i32, TRANS_MATRIX[n][31 - m] as i32);
+ assert_eq!(a, if n % 2 == 0 { b } else { -b }, "{n} {m}");
+ }
+ }
+ }
+
+ #[test]
+ fn qpc_table() {
+ assert_eq!(qpc_420(29), 29);
+ assert_eq!(qpc_420(30), 29);
+ assert_eq!(qpc_420(43), 37);
+ assert_eq!(qpc_420(51), 45);
+ }
+}
diff --git a/crates/hevc/src/transform.rs b/crates/hevc/src/transform.rs
new file mode 100644
index 000000000..b22b4e535
--- /dev/null
+++ b/crates/hevc/src/transform.rs
@@ -0,0 +1,82 @@
+//! Scaling (8.6.3), transform skip and inverse transforms (8.6.4): DCT 4..32 and DST 4x4.
+
+use crate::tables::{DST_MATRIX, TRANS_MATRIX};
+
+/// Inverse transform of an n x n block of scaled coefficients `c` (row-major, `c[y * n + x]`) in place,
+/// producing residuals after the final `bd_shift` rounding (8-299). `max_x` / `max_y` bound the
+/// non-zero coefficients (inclusive). `dst`: DST-VII (intra 4x4 luma).
+pub fn inverse_transform(c: &mut [i32], n: usize, dst: bool, max_x: usize, max_y: usize, bd_shift: u32) {
+ let mut tmp = [0i32; 32 * 32];
+ let step = 32 / n;
+ // 1. columns: e[x][y] = sum_j M[j][y] * d[x][j]
+ for x in 0..=max_x {
+ for y in 0..n {
+ let mut s = 0i32;
+ for j in 0..=max_y {
+ let m = if dst { DST_MATRIX[j][y] as i32 } else { TRANS_MATRIX[j * step][y] as i32 };
+ s += m * c[j * n + x];
+ }
+ tmp[y * n + x] = ((s + 64) >> 7).clamp(-32768, 32767);
+ }
+ }
+ // 2. rows: r[x][y] = sum_j M[j][x] * g[j][y]
+ let round = 1 << (bd_shift - 1);
+ for y in 0..n {
+ let row = &tmp[y * n..y * n + n];
+ for x in 0..n {
+ let mut s = 0i32;
+ for j in 0..=max_x {
+ let m = if dst { DST_MATRIX[j][x] as i32 } else { TRANS_MATRIX[j * step][x] as i32 };
+ s += m * row[j];
+ }
+ c[y * n + x] = (s + round) >> bd_shift;
+ }
+ }
+}
+
+/// DC-only inverse DCT: every residual sample gets the same value.
+pub fn inverse_dc(dc: i32, bd_shift: u32) -> i32 {
+ let e = ((64 * dc + 64) >> 7).clamp(-32768, 32767);
+ (64 * e + (1 << (bd_shift - 1))) >> bd_shift
+}
+
+/// Transform skip residual (8-298, 8-299): r = (d << tsShift + round) >> bdShift.
+pub fn transform_skip(c: &mut [i32], n: usize, bd_shift: u32) {
+ let ts_shift = 5 + n.trailing_zeros();
+ let round = 1 << (bd_shift - 1);
+ for v in c[..n * n].iter_mut() {
+ *v = ((*v << ts_shift) + round) >> bd_shift;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn dc_only_matches_full_transform() {
+ for &n in &[4usize, 8, 16, 32] {
+ for dc in [-300, -1, 1, 7, 64, 1000] {
+ let mut c = vec![0i32; n * n];
+ c[0] = dc;
+ inverse_transform(&mut c, n, false, 0, 0, 12);
+ let v = inverse_dc(dc, 12);
+ assert!(c.iter().all(|&x| x == v), "n {n} dc {dc}");
+ }
+ }
+ }
+
+ #[test]
+ fn bounded_region_matches_full() {
+ let n = 16;
+ let mut c = vec![0i32; n * n];
+ c[0] = 50;
+ c[1] = -20;
+ c[2 * n + 3] = 9;
+ let mut a = c.clone();
+ inverse_transform(&mut a, n, false, 3, 2, 12);
+ let mut b = c.clone();
+ inverse_transform(&mut b, n, false, n - 1, n - 1, 12);
+ assert_eq!(a, b);
+ }
+}
diff --git a/crates/hevc/tests/common/mod.rs b/crates/hevc/tests/common/mod.rs
new file mode 100644
index 000000000..2957b98e5
--- /dev/null
+++ b/crates/hevc/tests/common/mod.rs
@@ -0,0 +1,318 @@
+//! Test fixture generation (ffmpeg + libx265 / VideoToolbox as external oracle and encoder) and
+//! comparison helpers.
+#![allow(dead_code)]
+
+use filmcraft_hevc::{Decoder, Picture};
+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,
+ /// 10 (yuv420p10le) or 8.
+ pub bit_depth: u32,
+ /// Encoder arguments (libx265 unless `-c:v` is given).
+ pub args: &'static [&'static str],
+}
+
+const NOISE: &str = "noise=alls=12:allf=t+u";
+
+macro_rules! fx {
+ ($name:expr, $src:expr, $w:expr, $h:expr, $n:expr, $filter:expr, $bd:expr, [$($a:expr),* $(,)?]) => {
+ Fixture { name: $name, source: $src, width: $w, height: $h, frames: $n, filter: $filter, bit_depth: $bd, args: &[$($a),*] }
+ };
+}
+
+pub const FIXTURES: &[Fixture] = &[
+ // intra only
+ fx!("intra_main", "testsrc2", 352, 288, 3, NOISE, 8, ["-x265-params", "keyint=1:log-level=error"]),
+ fx!("intra_main10", "testsrc2", 352, 288, 3, NOISE, 10, ["-x265-params", "keyint=1:log-level=error"]),
+ fx!("intra_nosao_nodbk", "testsrc2", 352, 288, 2, NOISE, 8, ["-x265-params", "keyint=1:no-sao=1:no-deblock=1:log-level=error"]),
+ // presets (WPP is on by default in x265)
+ fx!("ultrafast", "testsrc2", 352, 288, 20, NOISE, 8, ["-preset", "ultrafast", "-x265-params", "log-level=error"]),
+ fx!("veryfast", "testsrc2", 352, 288, 20, NOISE, 8, ["-preset", "veryfast", "-x265-params", "log-level=error"]),
+ fx!("medium", "testsrc2", 352, 288, 20, NOISE, 8, ["-preset", "medium", "-x265-params", "log-level=error"]),
+ fx!("slow", "mandelbrot", 352, 288, 16, NOISE, 8, ["-preset", "slow", "-x265-params", "log-level=error"]),
+ fx!("medium_main10", "testsrc2", 352, 288, 20, NOISE, 10, ["-preset", "medium", "-x265-params", "log-level=error"]),
+ fx!("slow_main10", "mandelbrot", 352, 288, 12, NOISE, 10, ["-preset", "slow", "-x265-params", "log-level=error"]),
+ // coding tools
+ fx!("p_only", "testsrc2", 352, 288, 20, NOISE, 8, ["-x265-params", "bframes=0:log-level=error"]),
+ fx!("bframes", "testsrc2", 352, 288, 30, NOISE, 8, ["-x265-params", "bframes=8:b-pyramid=1:ref=4:log-level=error"]),
+ fx!("no_sao", "testsrc2", 352, 288, 16, NOISE, 8, ["-x265-params", "no-sao=1:log-level=error"]),
+ fx!("no_deblock", "testsrc2", 352, 288, 16, NOISE, 8, ["-x265-params", "no-deblock=1:log-level=error"]),
+ fx!("deblock_m3_3", "testsrc2", 352, 288, 12, NOISE, 8, ["-x265-params", "deblock=-3,3:log-level=error"]),
+ fx!("no_wpp", "testsrc2", 352, 288, 12, NOISE, 8, ["-x265-params", "no-wpp=1:log-level=error"]),
+ fx!("rect_amp", "mandelbrot", 352, 288, 16, NOISE, 8, ["-x265-params", "rect=1:amp=1:log-level=error"]),
+ fx!("tskip", "testsrc2", 352, 288, 12, NOISE, 8, ["-x265-params", "tskip=1:log-level=error"]),
+ fx!("weightp", "testsrc2", 352, 288, 30, "fade=in:0:25", 8, ["-x265-params", "weightp=1:weightb=1:bframes=3:log-level=error"]),
+ fx!("weightp_main10", "testsrc2", 352, 288, 20, "fade=in:0:18", 10, ["-x265-params", "weightp=1:weightb=1:log-level=error"]),
+ fx!("crf0", "mandelbrot", 176, 144, 6, NOISE, 8, ["-crf", "0", "-x265-params", "log-level=error"]),
+ fx!("crf51", "testsrc2", 352, 288, 12, NOISE, 8, ["-crf", "51", "-x265-params", "log-level=error"]),
+ fx!("qp1_main10", "mandelbrot", 176, 144, 4, NOISE, 10, ["-x265-params", "qp=1:log-level=error"]),
+ fx!("lossless", "testsrc2", 176, 144, 6, NOISE, 8, ["-x265-params", "lossless=1:log-level=error"]),
+ fx!("cu_lossless", "testsrc2", 176, 144, 6, NOISE, 8, ["-x265-params", "cu-lossless=1:log-level=error"]),
+ fx!("slices4", "testsrc2", 352, 288, 12, NOISE, 8, ["-x265-params", "slices=4:log-level=error"]),
+ fx!("scaling_list", "testsrc2", 352, 288, 12, NOISE, 8, ["-x265-params", "scaling-list=default:log-level=error"]),
+ fx!("ctu16", "testsrc2", 352, 288, 12, NOISE, 8, ["-x265-params", "ctu=16:log-level=error"]),
+ fx!("ctu32_tu4", "testsrc2", 352, 288, 12, NOISE, 8, ["-x265-params", "ctu=32:tu-intra-depth=4:tu-inter-depth=4:max-tu-size=16:log-level=error"]),
+ fx!("min_cu16", "testsrc2", 352, 288, 12, NOISE, 8, ["-x265-params", "min-cu-size=16:rect=1:amp=1:log-level=error"]),
+ fx!("no_signhide", "testsrc2", 352, 288, 12, NOISE, 8, ["-x265-params", "no-signhide=1:log-level=error"]),
+ fx!("constrained_intra", "testsrc2", 352, 288, 12, NOISE, 8, ["-x265-params", "constrained-intra=1:log-level=error"]),
+ fx!("no_tmvp", "testsrc2", 352, 288, 12, NOISE, 8, ["-x265-params", "no-temporal-mvp=1:log-level=error"]),
+ fx!("no_strong_intra", "testsrc2", 352, 288, 6, NOISE, 8, ["-x265-params", "no-strong-intra-smoothing=1:keyint=1:log-level=error"]),
+ fx!("max_merge1", "testsrc2", 352, 288, 12, NOISE, 8, ["-x265-params", "max-merge=1:log-level=error"]),
+ fx!("open_gop", "testsrc2", 352, 288, 40, NOISE, 8, ["-x265-params", "keyint=12:min-keyint=12:open-gop=1:bframes=3:log-level=error"]),
+ fx!("keyint5_idr", "testsrc2", 352, 288, 20, NOISE, 8, ["-x265-params", "keyint=5:no-open-gop=1:log-level=error"]),
+ fx!("odd_1918x1078", "testsrc2", 1918, 1078, 3, NOISE, 8, ["-preset", "veryfast", "-x265-params", "log-level=error"]),
+ fx!("hd_1080p", "testsrc2", 1920, 1080, 3, "", 8, ["-preset", "fast", "-x265-params", "log-level=error"]),
+ fx!("uhd_4k_main10", "testsrc2", 3840, 2160, 2, "", 10, ["-preset", "ultrafast", "-x265-params", "log-level=error"]),
+ // performance reference streams (tests/perf.rs)
+ fx!("bench_1080p", "testsrc2", 1920, 1080, 60, "noise=alls=3:allf=t", 8, ["-preset", "medium", "-crf", "24", "-x265-params", "log-level=error"]),
+ fx!("bench_4k", "testsrc2", 3840, 2160, 20, "noise=alls=3:allf=t", 10, ["-preset", "fast", "-crf", "26", "-x265-params", "log-level=error"]),
+ // Apple VideoToolbox (hardware encoder, macOS only)
+ fx!("vt_main", "testsrc2", 640, 360, 20, NOISE, 8, ["-c:v", "hevc_videotoolbox", "-b:v", "2M"]),
+ fx!("vt_main10", "mandelbrot", 640, 360, 20, NOISE, 10, ["-c:v", "hevc_videotoolbox", "-profile:v", "main10", "-b:v", "2M"]),
+];
+
+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/hevc");
+ 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
+ }
+ }
+}
+
+pub fn pix_fmt(bd: u32) -> &'static str {
+ if bd > 8 { "yuv420p10le" } else { "yuv420p" }
+}
+
+/// Generate (if needed) the fixture stream and its ffmpeg reference decode.
+/// Returns None (with a message) when ffmpeg or the encoder 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 hevc = dir.join(format!("{}.hevc", f.name));
+ let yuv = dir.join(format!("{}.yuv", f.name));
+ if !hevc.exists() {
+ let tmp = dir.join(format!("{}.tmp.{}.hevc", f.name, std::process::id()));
+ let mut vf = format!("{}=size={}x{}:rate=25,format={}", f.source, f.width, f.height, pix_fmt(f.bit_depth));
+ 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()]);
+ if !f.args.contains(&"-c:v") {
+ c.args(["-c:v", "libx265"]);
+ }
+ c.args(["-pix_fmt", pix_fmt(f.bit_depth)]);
+ c.args(f.args);
+ c.args(["-f", "hevc"]).arg(&tmp);
+ if !run(&mut c) {
+ // Platform encoders (VideoToolbox) are optional; libx265 fixtures must generate.
+ assert!(f.args.contains(&"-c:v"), "fixture generation failed for {}", f.name);
+ let _ = std::fs::remove_file(&tmp);
+ eprintln!("SKIP {}: encoder unavailable", f.name);
+ return None;
+ }
+ std::fs::rename(&tmp, &hevc).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(&hevc);
+ c.args(["-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", pix_fmt(f.bit_depth)]).arg(&tmp);
+ assert!(run(&mut c), "reference decode failed for {}", f.name);
+ std::fs::rename(&tmp, &yuv).unwrap();
+ }
+ Some((hevc, yuv))
+}
+
+fn is_vcl(t: u8) -> bool {
+ t < 32
+}
+
+/// Split an Annex-B stream into access units: a new AU starts at an AUD / VPS / SPS / PPS / prefix SEI
+/// NAL after a VCL NAL, or at a VCL NAL with first_slice_segment_in_pic_flag = 1.
+pub fn split_access_units(data: &[u8]) -> Vec<&[u8]> {
+ 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_vcl = false;
+ for &(sc, payload) in &starts {
+ if payload + 2 >= data.len() {
+ continue;
+ }
+ let t = (data[payload] >> 1) & 0x3f;
+ let first_slice = is_vcl(t) && data[payload + 2] & 0x80 != 0;
+ let boundary = seen_vcl && (matches!(t, 32..=35 | 39) || first_slice);
+ if boundary {
+ aus.push(&data[au_start..sc]);
+ au_start = sc;
+ seen_vcl = false;
+ }
+ if is_vcl(t) {
+ seen_vcl = true;
+ }
+ }
+ if au_start < data.len() {
+ aus.push(&data[au_start..]);
+ }
+ aus
+}
+
+/// Failed decode: (access unit index, error, pictures output before the error).
+pub type DecodeFailure = (usize, filmcraft_hevc::Error, Vec<Picture>);
+
+/// Decode with `threads` worker threads (0 = decoder default), pts = access unit index.
+pub fn decode_file_threads(path: &Path, threads: usize) -> Result<Vec<Picture>, DecodeFailure> {
+ let data = std::fs::read(path).unwrap();
+ let mut dec = if threads == 0 { Decoder::new() } else { Decoder::with_threads(threads) };
+ let mut out = Vec::new();
+ for (i, au) in split_access_units(&data).into_iter().enumerate() {
+ match dec.decode(au, i as i64) {
+ Ok(p) => out.extend(p),
+ Err(e) => return Err((i, e, out)),
+ }
+ }
+ out.extend(dec.flush());
+ if let Some(e) = dec.take_error() {
+ return Err((usize::MAX, e, out));
+ }
+ Ok(out)
+}
+
+/// Compare decoded pictures with a raw yuv420p / yuv420p10le reference; returns a diagnostic on the
+/// first mismatch (frame, plane, sample position, CTB (64x64) and 8x8 block).
+pub fn compare(pics: &[Picture], reference: &[u8], w: usize, h: usize, bd: u32) -> Result<(), String> {
+ let bps = if bd > 8 { 2 } else { 1 };
+ let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
+ let fsize = (w * h + 2 * cw * ch) * bps;
+ let nref = reference.len() / fsize;
+ for (i, p) in pics.iter().enumerate() {
+ if i >= nref {
+ return Err(format!("decoder produced {} frames, reference has {}", pics.len(), nref));
+ }
+ if p.width as usize != w || p.height as usize != h {
+ return Err(format!("frame {i}: size {}x{} != {}x{}", p.width, p.height, w, h));
+ }
+ let f = &reference[i * fsize..(i + 1) * fsize];
+ let sample = |buf: &[u8], k: usize| if bps == 2 { u16::from_le_bytes([buf[2 * k], buf[2 * k + 1]]) } else { buf[k] as u16 };
+ let (ys, cs) = (w * h * bps, cw * ch * bps);
+ let planes = [("Y", &p.y, &f[..ys], w, h, 1), ("U", &p.u, &f[ys..ys + cs], cw, ch, 2), ("V", &p.v, &f[ys + cs..], cw, ch, 2)];
+ for (name, got, exp, pw, ph, sub) in planes {
+ let mut first = None;
+ let mut count = 0usize;
+ let mut maxd = 0i32;
+ for y in 0..ph {
+ for x in 0..pw {
+ let (a, b) = (got.get(y * pw + x), sample(exp, y * pw + x));
+ if a != b {
+ count += 1;
+ maxd = maxd.max((a as i32 - b as i32).abs());
+ if first.is_none() {
+ first = Some((x, y, a, b));
+ }
+ }
+ }
+ }
+ if let Some((x, y, a, b)) = first {
+ let (lx, ly) = (x * sub, y * sub);
+ return Err(format!(
+ "frame {i} (poc {}, pts {}) plane {name}: first mismatch at ({x},{y}) [luma ({lx},{ly}), CTB64 ({},{}), 8x8 ({},{})]: got {a} want {b}; {count} samples differ, max diff {maxd}",
+ p.poc,
+ p.pts,
+ lx / 64,
+ ly / 64,
+ lx / 8,
+ ly / 8
+ ));
+ }
+ }
+ }
+ if pics.len() != nref {
+ return Err(format!("decoder produced {} frames, reference has {}", pics.len(), nref));
+ }
+ Ok(())
+}
+
+/// Full check of one fixture: generate, decode (single- and multi-threaded), compare. Ok(false) when skipped.
+pub fn check_fixture(name: &str) -> Result<bool, String> {
+ let f = fixture(name);
+ let Some((hevc, yuv)) = ensure(f) else { return Ok(false) };
+ let reference = std::fs::read(&yuv).unwrap();
+ for threads in [1, 0] {
+ let pics = match decode_file_threads(&hevc, threads) {
+ Ok(p) => p,
+ Err((au, e, partial)) => {
+ let cmp = compare(&partial, &reference, f.width as usize, f.height as usize, f.bit_depth).err().unwrap_or_default();
+ return Err(format!("{name} (threads {threads}): decode error at access unit {au}: {e} (after {} pictures) {cmp}", partial.len()));
+ }
+ };
+ compare(&pics, &reference, f.width as usize, f.height as usize, f.bit_depth).map_err(|e| format!("{name} (threads {threads}): {e}"))?;
+ check_pts(&pics).map_err(|e| format!("{name} (threads {threads}): {e}"))?;
+ }
+ Ok(true)
+}
+
+/// Output pts values must be distinct and follow POC order between IRAP pictures.
+pub fn check_pts(pics: &[Picture]) -> Result<(), String> {
+ let mut seen = std::collections::HashSet::new();
+ for p in pics {
+ if !seen.insert(p.pts) {
+ return Err(format!("duplicate pts {} in output", p.pts));
+ }
+ }
+ for w in pics.windows(2) {
+ if !w[1].key && w[1].poc <= w[0].poc {
+ return Err(format!("output POC order violated: {} then {}", w[0].poc, w[1].poc));
+ }
+ }
+ Ok(())
+}
diff --git a/crates/hevc/tests/conformance.rs b/crates/hevc/tests/conformance.rs
new file mode 100644
index 000000000..0dfd0d8cd
--- /dev/null
+++ b/crates/hevc/tests/conformance.rs
@@ -0,0 +1,93 @@
+//! Bit-exactness against ffmpeg's decoder on libx265 / VideoToolbox fixtures (skipped when ffmpeg is
+//! absent).
+
+mod common;
+
+macro_rules! fixture_tests {
+ ($($name:ident),* $(,)?) => {
+ $(
+ #[test]
+ fn $name() {
+ match common::check_fixture(stringify!($name)) {
+ Ok(true) => {}
+ Ok(false) => eprintln!("skipped {}", stringify!($name)),
+ Err(e) => panic!("{e}"),
+ }
+ }
+ )*
+ };
+}
+
+fixture_tests!(
+ intra_main,
+ intra_main10,
+ intra_nosao_nodbk,
+ ultrafast,
+ veryfast,
+ medium,
+ slow,
+ medium_main10,
+ slow_main10,
+ p_only,
+ bframes,
+ no_sao,
+ no_deblock,
+ deblock_m3_3,
+ no_wpp,
+ rect_amp,
+ tskip,
+ weightp,
+ weightp_main10,
+ crf0,
+ crf51,
+ qp1_main10,
+ lossless,
+ cu_lossless,
+ slices4,
+ scaling_list,
+ ctu16,
+ ctu32_tu4,
+ min_cu16,
+ no_signhide,
+ constrained_intra,
+ no_tmvp,
+ no_strong_intra,
+ max_merge1,
+ open_gop,
+ keyint5_idr,
+ odd_1918x1078,
+ hd_1080p,
+ uhd_4k_main10,
+ vt_main,
+ vt_main10,
+);
+
+/// Print which coding tools each fixture exercises (run with `-- --ignored --nocapture`).
+#[test]
+#[ignore]
+fn coverage_report() {
+ for f in common::FIXTURES {
+ let Some((hevc, _)) = common::ensure(f) else { continue };
+ let data = std::fs::read(hevc).unwrap();
+ let mut dec = filmcraft_hevc::Decoder::new();
+ for au in common::split_access_units(&data) {
+ let _ = dec.decode(au, 0);
+ }
+ dec.flush();
+ println!("{:<20} {:?}", f.name, dec.stats());
+ }
+}
+
+/// The comparison must report a single flipped sample (guards against a vacuous harness).
+#[test]
+fn compare_detects_mismatch() {
+ let f = common::fixture("intra_main10");
+ let Some((hevc, yuv)) = common::ensure(f) else { return };
+ let pics = common::decode_file_threads(&hevc, 1).map_err(|e| e.1).unwrap();
+ let mut reference = std::fs::read(yuv).unwrap();
+ common::compare(&pics, &reference, f.width as usize, f.height as usize, f.bit_depth).unwrap();
+ let pos = reference.len() - 7;
+ reference[pos] ^= 1;
+ let err = common::compare(&pics, &reference, f.width as usize, f.height as usize, f.bit_depth).unwrap_err();
+ assert!(err.contains("plane V"), "{err}");
+}
diff --git a/crates/hevc/tests/perf.rs b/crates/hevc/tests/perf.rs
new file mode 100644
index 000000000..4091166b6
--- /dev/null
+++ b/crates/hevc/tests/perf.rs
@@ -0,0 +1,43 @@
+//! Decode speed (ignored by default; run with
+//! `cargo test --release -p filmcraft-hevc --test perf -- --ignored --nocapture`).
+
+mod common;
+
+use filmcraft_hevc::Decoder;
+use std::time::Instant;
+
+fn bench(data: &[u8], threads: usize, iters: usize) -> (usize, f64) {
+ let mut best = f64::MAX;
+ let mut frames = 0;
+ for _ in 0..iters {
+ let mut dec = Decoder::with_threads(threads);
+ let t0 = Instant::now();
+ frames = dec.decode(data, 0).expect("decode").len() + dec.flush().len();
+ best = best.min(t0.elapsed().as_secs_f64());
+ }
+ (frames, best)
+}
+
+fn run(name: &str, label: &str) {
+ let f = common::fixture(name);
+ let Some((hevc, _)) = common::ensure(f) else { return };
+ common::check_fixture(name).unwrap();
+ let data = std::fs::read(hevc).unwrap();
+ let cores = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(1);
+ for threads in [1, cores.min(16)] {
+ let (frames, secs) = bench(&data, threads, 3);
+ println!("{label} ({} KB): {threads} thread(s): {frames} frames in {secs:.3}s = {:.1} fps", data.len() / 1024, frames as f64 / secs);
+ }
+}
+
+#[test]
+#[ignore]
+fn perf_1080p() {
+ run("bench_1080p", "1080p Main CRF24 medium");
+}
+
+#[test]
+#[ignore]
+fn perf_4k() {
+ run("bench_4k", "2160p Main10 CRF26 fast");
+}
diff --git a/crates/hevc/tests/robustness.rs b/crates/hevc/tests/robustness.rs
new file mode 100644
index 000000000..075d5fde2
--- /dev/null
+++ b/crates/hevc/tests/robustness.rs
@@ -0,0 +1,122 @@
+//! hvcC / length-prefixed input and resilience against damaged streams.
+
+mod common;
+
+use filmcraft_bitstream::annexb_nals;
+use filmcraft_hevc::Decoder;
+
+/// Build an hvcC record and length-prefixed samples from an Annex-B stream.
+fn to_hvcc(data: &[u8]) -> (Vec<u8>, Vec<Vec<u8>>) {
+ let mut sets: [Vec<Vec<u8>>; 3] = [Vec::new(), Vec::new(), Vec::new()];
+ let mut samples = Vec::new();
+ for au in common::split_access_units(data) {
+ let mut sample = Vec::new();
+ for nal in annexb_nals(au) {
+ let t = (nal[0] >> 1) & 0x3f;
+ match t {
+ 32..=34 => sets[(t - 32) as usize].push(nal.to_vec()),
+ _ => {
+ sample.extend((nal.len() as u32).to_be_bytes());
+ sample.extend_from_slice(nal);
+ }
+ }
+ }
+ if !sample.is_empty() {
+ samples.push(sample);
+ }
+ }
+ for s in sets.iter_mut() {
+ s.dedup();
+ }
+ let mut hvcc = vec![1u8];
+ hvcc.extend([0u8; 20]); // profile / level / misc fields (not used by the decoder)
+ hvcc.push(0xfc | 3); // lengthSizeMinusOne = 3
+ hvcc.push(3);
+ for (k, s) in sets.iter().enumerate() {
+ hvcc.push(0x80 | (32 + k as u8));
+ hvcc.extend((s.len() as u16).to_be_bytes());
+ for n in s {
+ hvcc.extend((n.len() as u16).to_be_bytes());
+ hvcc.extend_from_slice(n);
+ }
+ }
+ (hvcc, samples)
+}
+
+#[test]
+fn hvcc_input_matches_reference() {
+ for name in ["medium", "intra_main10"] {
+ let f = common::fixture(name);
+ let Some((hevc, yuv)) = common::ensure(f) else { return };
+ let (hvcc, samples) = to_hvcc(&std::fs::read(hevc).unwrap());
+ let mut dec = Decoder::from_hvcc(&hvcc).unwrap();
+ assert_eq!(dec.nal_length_size(), Some(4));
+ let mut pics = Vec::new();
+ for (i, s) in samples.iter().enumerate() {
+ pics.extend(dec.decode(s, i as i64 * 1000).unwrap());
+ }
+ pics.extend(dec.flush());
+ let reference = std::fs::read(yuv).unwrap();
+ common::compare(&pics, &reference, f.width as usize, f.height as usize, f.bit_depth).unwrap();
+ let mut pts: Vec<i64> = pics.iter().map(|p| p.pts).collect();
+ pts.sort();
+ assert_eq!(pts, (0..samples.len() as i64).map(|i| i * 1000).collect::<Vec<_>>());
+ let p0 = &pics[0];
+ assert!(p0.key);
+ assert_eq!(p0.bit_depth, f.bit_depth);
+ assert_eq!((p0.y_stride, p0.uv_stride), (f.width as usize, f.width as usize / 2));
+ }
+}
+
+fn xorshift(seed: &mut u64) -> u64 {
+ *seed ^= *seed << 13;
+ *seed ^= *seed >> 7;
+ *seed ^= *seed << 17;
+ *seed
+}
+
+/// Damaged streams must never panic or hang; errors are fine.
+#[test]
+fn corrupted_streams_do_not_panic() {
+ for name in ["medium", "bframes", "intra_main10", "rect_amp", "weightp"] {
+ let f = common::fixture(name);
+ let Some((hevc, _)) = common::ensure(f) else { return };
+ let data = std::fs::read(hevc).unwrap();
+ let mut seed = 0x1234_5678_9abc_def0u64 ^ name.len() as u64;
+ for round in 0..12 {
+ let mut d = data.clone();
+ for _ in 0..(1 + round * 3) {
+ let pos = 100 + (xorshift(&mut seed) as usize) % (d.len() - 100);
+ d[pos] ^= 1 << (xorshift(&mut seed) % 8);
+ }
+ if round % 4 == 3 {
+ d.truncate(d.len() * 2 / 3);
+ }
+ for threads in [1, 4] {
+ let mut dec = Decoder::with_threads(threads);
+ for au in common::split_access_units(&d) {
+ let _ = dec.decode(au, 0);
+ }
+ let _ = dec.flush();
+ let _ = dec.take_error();
+ }
+ }
+ }
+}
+
+#[test]
+fn garbage_input_is_rejected_gracefully() {
+ let mut seed = 42u64;
+ for len in [0usize, 1, 5, 100, 5000] {
+ for _ in 0..20 {
+ let mut g: Vec<u8> = (0..len).map(|_| xorshift(&mut seed) as u8).collect();
+ if len > 10 {
+ g[..4].copy_from_slice(&[0, 0, 0, 1]);
+ }
+ let mut dec = Decoder::new();
+ let _ = dec.decode(&g, 0);
+ let _ = dec.flush();
+ }
+ }
+ assert!(Decoder::from_hvcc(&[1, 2, 3]).is_err());
+}
diff --git a/crates/hevc/tools/extract_tables.py b/crates/hevc/tools/extract_tables.py
new file mode 100644
index 000000000..8b9fa3979
--- /dev/null
+++ b/crates/hevc/tools/extract_tables.py
@@ -0,0 +1,223 @@
+#!/usr/bin/env python3
+"""Extract HEVC syntax / decoding tables from the text of the public ITU-T H.265 specification.
+
+Usage:
+ curl -L -o h265.pdf 'https://www.itu.int/rec/dologin_pub.asp?lang=e&id=T-REC-H.265-202108-S!!PDF-E&type=items'
+ pdftotext -layout h265.pdf h265.txt
+ python3 extract_tables.py h265.txt > ../src/spec_tables.rs
+
+Only the specification text is read. Extracted: CABAC initValue tables (Tables 9-5..9-35) arranged per
+initType following Table 9-4, default scaling lists (Table 7-6), intraPredAngle / invAngle (Tables 8-5,
+8-6), QpC (Table 8-10), beta'/tC' (Table 8-12), luma / chroma interpolation filter taps
+(equations 8-236..8-238 and 8-249..8-261) and the 32x32 DCT matrix (equations 8-319, 8-321).
+"""
+import re
+import sys
+
+text = open(sys.argv[1], encoding="utf-8").read().replace("−", "-").replace("–", "-")
+lines = text.split("\n")
+
+
+def body_after(title_regex, stop_regex=r"^\s*(Table \d+-\d+ - |\d+\s+Rec\. ITU|Rec\. ITU)", skip_first=True):
+ """Lines following the (last) occurrence of a table title, until the next title."""
+ idx = [i for i, l in enumerate(lines) if re.search(title_regex, l)]
+ assert idx, title_regex
+ start = idx[-1] + 1 # last occurrence = the table itself (first is the table of contents)
+ out = []
+ for l in lines[start:]:
+ if re.search(r"^\s*Table \d+-\d+ - ", l):
+ break
+ out.append(l)
+ return out
+
+
+def init_values(table):
+ vals = []
+ for l in body_after(r"Table %s - Values of initValue" % re.escape(table)):
+ m = re.match(r"^\s*initValue\s+(.*)$", l)
+ if m:
+ vals += [int(v) for v in m.group(1).split()]
+ return vals
+
+
+# (name, table, ranges per initType 0,1,2 as lists of ctxIdx; None = element not used for that initType)
+R = lambda a, b: list(range(a, b + 1))
+CABAC = [
+ ("SAO_MERGE", "9-5", [[0], [1], [2]]),
+ ("SAO_TYPE", "9-6", [[0], [1], [2]]),
+ ("SPLIT_CU", "9-7", [R(0, 2), R(3, 5), R(6, 8)]),
+ ("CU_TRANSQUANT_BYPASS", "9-8", [[0], [1], [2]]),
+ ("CU_SKIP", "9-9", [None, R(0, 2), R(3, 5)]),
+ ("PRED_MODE", "9-10", [None, [0], [1]]),
+ ("PART_MODE", "9-11", [[0], R(1, 4), R(5, 8)]),
+ ("PREV_INTRA_LUMA", "9-12", [[0], [1], [2]]),
+ ("INTRA_CHROMA", "9-13", [[0], [1], [2]]),
+ ("RQT_ROOT_CBF", "9-14", [None, [0], [1]]),
+ ("MERGE_FLAG", "9-15", [None, [0], [1]]),
+ ("MERGE_IDX", "9-16", [None, [0], [1]]),
+ ("INTER_PRED_IDC", "9-17", [None, R(0, 4), R(5, 9)]),
+ ("REF_IDX", "9-18", [None, R(0, 1), R(2, 3)]),
+ ("MVP_FLAG", "9-19", [None, [0], [1]]),
+ ("SPLIT_TRANSFORM", "9-20", [R(0, 2), R(3, 5), R(6, 8)]),
+ ("CBF_LUMA", "9-21", [R(0, 1), R(2, 3), R(4, 5)]),
+ ("CBF_CHROMA", "9-22", [R(0, 3) + [12], R(4, 7) + [13], R(8, 11) + [14]]),
+ ("ABS_MVD_GT0", "9-23", [None, [0], [2]]),
+ ("ABS_MVD_GT1", "9-23", [None, [1], [3]]),
+ ("CU_QP_DELTA_ABS", "9-24", [R(0, 1), R(2, 3), R(4, 5)]),
+ ("TRANSFORM_SKIP", "9-25", [[0, 3], [1, 4], [2, 5]]),
+ ("LAST_X_PREFIX", "9-26", [R(0, 17), R(18, 35), R(36, 53)]),
+ ("LAST_Y_PREFIX", "9-27", [R(0, 17), R(18, 35), R(36, 53)]),
+ ("CODED_SUB_BLOCK", "9-28", [R(0, 3), R(4, 7), R(8, 11)]),
+ ("SIG_COEFF", "9-29", [R(0, 41) + R(126, 127), R(42, 83) + R(128, 129), R(84, 125) + R(130, 131)]),
+ ("GT1", "9-30", [R(0, 23), R(24, 47), R(48, 71)]),
+ ("GT2", "9-31", [R(0, 5), R(6, 11), R(12, 17)]),
+ ("EXPLICIT_RDPCM", "9-32", [None, [0, 2], [1, 3]]),
+ ("EXPLICIT_RDPCM_DIR", "9-33", [None, [0, 2], [1, 3]]),
+ ("CU_CHROMA_QP_OFFSET_FLAG", "9-34", [[0], [1], [2]]),
+ ("CU_CHROMA_QP_OFFSET_IDX", "9-35", [[0], [1], [2]]),
+]
+
+out = []
+w = out.append
+w("// Generated by crates/hevc/tools/extract_tables.py from the text of Rec. ITU-T H.265. Do not edit.")
+w("")
+w("// CABAC context layout: offset of each syntax element in the context array (Table 9-4).")
+offset = 0
+init = [[], [], []]
+for name, table, ranges in CABAC:
+ vals = init_values(table)
+ n = max(len(r) for r in ranges if r is not None)
+ for t in range(3):
+ r = ranges[t]
+ if r is None:
+ init[t] += [154] * n # element not present in this initType (value unused)
+ else:
+ # shorter ranges (part_mode in I slices) are padded with an unused value
+ init[t] += [vals[i] for i in r] + [154] * (n - len(r))
+ w("pub const %s: usize = %d;" % (name, offset))
+ offset += n
+w("pub const NUM_CTX: usize = %d;" % offset)
+w("")
+w("/// initValue per initType (9.3.2.2).")
+w("pub static CABAC_INIT: [[u8; NUM_CTX]; 3] = [")
+for t in range(3):
+ w(" [%s]," % ", ".join(str(v) for v in init[t]))
+w("];")
+w("")
+
+# Table 7-6: default 8x8 scaling lists (intra matrixId 0..2, inter 3..5)
+intra, inter = [], []
+for l in body_after(r"Table 7-6 - Specification of default values of ScalingList"):
+ m = re.match(r"^\s*ScalingList\[ 1\.\.3 \]\[ (0\.\.2|3\.\.5) \]\[ i \]\s+(.*)$", l)
+ if m:
+ (intra if m.group(1) == "0..2" else inter).extend(int(v) for v in m.group(2).split())
+assert len(intra) == 64 and len(inter) == 64
+w("/// Table 7-6: default ScalingList[1..3][0..2] (intra) and [3..5] (inter), in up-right diagonal order.")
+w("pub static DEFAULT_SCALING_INTRA: [u8; 64] = [%s];" % ", ".join(map(str, intra)))
+w("pub static DEFAULT_SCALING_INTER: [u8; 64] = [%s];" % ", ".join(map(str, inter)))
+w("")
+
+# Table 8-5 / 8-6
+angle = {}
+for l in body_after(r"Table 8-5 - Specification of intraPredAngle"):
+ if l.strip().startswith("predModeIntra"):
+ modes = [int(v) for v in l.split()[1:]]
+ elif l.strip().startswith("intraPredAngle"):
+ vs = l.split()[1:]
+ for mo, v in zip(modes, vs):
+ if v != "-":
+ angle[mo] = int(v)
+assert sorted(angle) == list(range(2, 35))
+w("/// Table 8-5: intraPredAngle for predModeIntra 0..34 (0 for planar / DC).")
+w("pub static INTRA_PRED_ANGLE: [i8; 35] = [%s];" % ", ".join(str(angle.get(i, 0)) for i in range(35)))
+inv = {}
+for l in body_after(r"Table 8-6 - Specification of invAngle"):
+ s = l.strip()
+ if s.startswith("predModeIntra"):
+ modes = [int(v) for v in s.split()[1:]]
+ elif s.startswith("invAngle"):
+ vs = [int(v.replace(" ", "")) for v in re.findall(r"-\d+(?: \d{3})?", s)]
+ for mo, v in zip(modes, vs):
+ inv[mo] = v
+assert sorted(inv) == list(range(11, 26)), inv
+w("/// Table 8-6: invAngle for predModeIntra 11..25 (index = mode - 11).")
+w("pub static INV_ANGLE: [i16; 15] = [%s];" % ", ".join(str(inv[i]) for i in range(11, 26)))
+w("")
+
+# Table 8-10: QpC for qPi 30..43
+for l in body_after(r"Table 8-10 - Specification of QpC as a function of qPi"):
+ s = l.strip()
+ if s.startswith("qPi"):
+ qpi = s.split()
+ elif s.startswith("QpC"):
+ qpc = s.split()
+qpi_n = [int(v) for v in qpi[3:-2]]
+qpc_n = [int(v) for v in qpc[3:-4]]
+assert qpi_n == list(range(30, 44)) and len(qpc_n) == 14, (qpi_n, qpc_n)
+w("/// Table 8-10: QpC for qPi = 30..43 (qPi < 30: QpC = qPi; qPi > 43: QpC = qPi - 6).")
+w("pub static QPC_30_43: [u8; 14] = [%s];" % ", ".join(map(str, qpc_n)))
+w("")
+
+# Table 8-12
+beta, tc = [], []
+for l in body_after(r"Table 8-12 - Derivation of threshold variables"):
+ s = l.strip()
+ if s.startswith("β"):
+ beta += [int(v) for v in s.split()[1:] if v != "-"]
+ elif s.startswith("t C"):
+ tc += [int(v) for v in s.split()[2:]]
+assert len(beta) == 52 and len(tc) == 54, (len(beta), len(tc))
+w("/// Table 8-12: beta' for Q = 0..51.")
+w("pub static BETA_TABLE: [u8; 52] = [%s];" % ", ".join(map(str, beta)))
+w("/// Table 8-12: tC' for Q = 0..53.")
+w("pub static TC_TABLE: [u8; 54] = [%s];" % ", ".join(map(str, tc)))
+w("")
+
+
+def taps(eq_no, var, n):
+ for l in lines:
+ if "(%s)" % eq_no in l:
+ expr = l.split("=", 1)[1].split(">>")[0]
+ coef = {}
+ for sign, c, k in re.findall(r"([+-]?)\s*(?:(\d+)\s*\*\s*)?%s0,\s*(-?\d)" % var, expr):
+ coef[int(k)] = (-1 if sign == "-" else 1) * (int(c) if c else 1)
+ return coef
+ raise SystemExit("equation %s not found" % eq_no)
+
+
+luma = []
+for eq in ["8-236", "8-237", "8-238"]:
+ c = taps(eq, "c", 8)
+ luma.append([c.get(k, 0) for k in range(-3, 5)])
+w("/// Luma 8-tap interpolation filter fL[xFrac][k] (8-236..8-238), taps at offsets -3..4.")
+w("pub static LUMA_FILTER: [[i8; 8]; 4] = [[0, 0, 0, 64, 0, 0, 0, 0], %s];" % ", ".join("[%s]" % ", ".join(map(str, t)) for t in luma))
+chroma = []
+for eq in ["8-255", "8-256", "8-257", "8-258", "8-259", "8-260", "8-261"]:
+ c = taps(eq, "aX", 4)
+ chroma.append([c.get(k, 0) for k in range(-1, 3)])
+w("/// Chroma 4-tap interpolation filter fC[xFrac][k] (8-255..8-261), taps at offsets -1..2.")
+w("pub static CHROMA_FILTER: [[i8; 4]; 8] = [[0, 64, 0, 0], %s];" % ", ".join("[%s]" % ", ".join(map(str, t)) for t in chroma))
+w("")
+
+# DCT matrix: transMatrix[m][n] (m = sample column 0..31, n = row 0..31); printed as 32 rows of 16 columns twice.
+def matrix_rows(eq):
+ i = [k for k, l in enumerate(lines) if "(%s)" % eq in l][-1]
+ rows = []
+ for l in lines[i + 1:]:
+ m = re.match(r"^\s*\{([-\d\s]+)\}\s*$", l)
+ if m:
+ rows.append([int(v) for v in m.group(1).split()])
+ elif rows and l.strip() == "}":
+ break
+ rows = rows[:32]
+ assert len(rows) == 32 and all(len(r) == 16 for r in rows), (eq, len(rows))
+ return rows
+
+
+a, b = matrix_rows("8-319"), matrix_rows("8-321")
+w("/// DCT matrix (8-319, 8-321): TRANS_MATRIX[n][m] = transMatrix[m][n] (row n = basis function).")
+w("pub static TRANS_MATRIX: [[i8; 32]; 32] = [")
+for n in range(32):
+ w(" [%s]," % ", ".join(str(v) for v in a[n] + b[n]))
+w("];")
+print("\n".join(out))