diff --git a/Cargo.toml b/Cargo.toml index 47248318..d17fe754 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,6 +14,7 @@ ec-av1-syntax = { path = "crates/ec-av1-syntax", version = "0.1.0" } ec-core = { path = "crates/ec-core", version = "0.1.0" } ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" } ec-h264-syntax = { path = "crates/ec-h264-syntax", version = "0.1.0" } +ec-h265-syntax = { path = "crates/ec-h265-syntax", version = "0.1.0" } ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" } ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" } ec-mp3 = { path = "crates/ec-mp3", version = "0.1.0" } diff --git a/crates/ec-h265-syntax/Cargo.toml b/crates/ec-h265-syntax/Cargo.toml new file mode 100644 index 00000000..af64454d --- /dev/null +++ b/crates/ec-h265-syntax/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "ec-h265-syntax" +description = "HEVC (H.265) NAL framing, parameter sets, slice headers and SEI — written and parsed." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core.workspace = true diff --git a/crates/ec-h265-syntax/src/lib.rs b/crates/ec-h265-syntax/src/lib.rs new file mode 100644 index 00000000..b31b7aa3 --- /dev/null +++ b/crates/ec-h265-syntax/src/lib.rs @@ -0,0 +1,41 @@ +//! HEVC bitstream syntax: NAL framing, parameter sets, slice headers, SEI. +//! +//! This crate is the half of H.265 that both a software encoder and a *stateless +//! hardware* decoder need, and it is deliberately the same code for both +//! directions: every structure here is written and parsed, so a round trip is a +//! test rather than an article of faith. +//! +//! What that buys, concretely: +//! +//! - The conformance window is a field on [`Sps`], not a caller's padding +//! problem. 1920x1080 in 64x64 coding tree blocks is coded 1920x1088 and +//! cropped by the SPS; [`Sps::display_size`] gives back what a player shows. +//! - Every field of `VAPictureParameterBufferHEVC` and +//! `VASliceParameterBufferHEVC` is either a field on [`Sps`], [`Pps`] or +//! [`SliceHeader`], or a named method on one of them — +//! [`Sps::pic_width_in_ctbs`], [`ParsePositions::slice_data_byte_offset`], +//! [`ParsePositions::st_rps_bits`]. A hardware decode path built on this crate +//! should never need to re-parse a header itself. +//! - [`sei::decoded_picture_hash_rbsp`] writes the MD5 of the reconstruction, so +//! any conformant decoder can be asked whether the encoder was right. +//! +//! Malformed input is an [`Error`](ec_core::Error), never a panic: truncation is +//! `NeedMore`, a rule violation is `Corrupt`, and the two constructs the family +//! genuinely does not implement (scaling lists, and short-term reference picture +//! sets predicted from an SPS set that a caller did not keep) are `Unsupported` +//! with the reason stated. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +mod md5; +pub mod nal; +pub mod ps; +pub mod sei; +pub mod slice; +pub mod vui; + +pub use nal::{AnnexBNal, NalHeader, NalUnitType, escape_rbsp, split_annex_b, unescape_rbsp}; +pub use ps::{ConformanceWindow, Pps, ProfileTierLevel, ShortTermRefPicSet, Sps, Vps}; +pub use slice::{ParsePositions, SliceHeader, SliceType}; +pub use vui::{ColourDescription, VideoSignalType, VuiParameters}; diff --git a/crates/ec-h265-syntax/src/md5.rs b/crates/ec-h265-syntax/src/md5.rs new file mode 100644 index 00000000..f4f7d2f1 --- /dev/null +++ b/crates/ec-h265-syntax/src/md5.rs @@ -0,0 +1,181 @@ +//! MD5 (IETF RFC 1321), for the decoded picture hash SEI and nothing else. +//! +//! Not a security primitive and not offered as one: the spec names MD5 as the +//! picture hash, so this exists to reproduce that one number. + +/// `K[i] = floor(2^32 * abs(sin(i + 1)))`, RFC 1321 section 3.4. +const K: [u32; 64] = [ + 0xd76a_a478, 0xe8c7_b756, 0x2420_70db, 0xc1bd_ceee, 0xf57c_0faf, 0x4787_c62a, 0xa830_4613, + 0xfd46_9501, 0x6980_98d8, 0x8b44_f7af, 0xffff_5bb1, 0x895c_d7be, 0x6b90_1122, 0xfd98_7193, + 0xa679_438e, 0x49b4_0821, 0xf61e_2562, 0xc040_b340, 0x265e_5a51, 0xe9b6_c7aa, 0xd62f_105d, + 0x0244_1453, 0xd8a1_e681, 0xe7d3_fbc8, 0x21e1_cde6, 0xc337_07d6, 0xf4d5_0d87, 0x455a_14ed, + 0xa9e3_e905, 0xfcef_a3f8, 0x676f_02d9, 0x8d2a_4c8a, 0xfffa_3942, 0x8771_f681, 0x6d9d_6122, + 0xfde5_380c, 0xa4be_ea44, 0x4bde_cfa9, 0xf6bb_4b60, 0xbebf_bc70, 0x289b_7ec6, 0xeaa1_27fa, + 0xd4ef_3085, 0x0488_1d05, 0xd9d4_d039, 0xe6db_99e5, 0x1fa2_7cf8, 0xc4ac_5665, 0xf429_2244, + 0x432a_ff97, 0xab94_23a7, 0xfc93_a039, 0x655b_59c3, 0x8f0c_cc92, 0xffef_f47d, 0x8584_5dd1, + 0x6fa8_7e4f, 0xfe2c_e6e0, 0xa301_4314, 0x4e08_11a1, 0xf753_7e82, 0xbd3a_f235, 0x2ad7_d2bb, + 0xeb86_d391, +]; + +/// Per-round left rotation amounts. +const S: [u32; 64] = [ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, + 14, 20, 5, 9, 14, 20, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, + 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, +]; + +/// Streaming MD5 state. +pub struct Md5 { + state: [u32; 4], + buffer: [u8; 64], + buffered: usize, + length: u64, +} + +impl Md5 { + /// A fresh context. + pub fn new() -> Md5 { + Md5 { + state: [0x6745_2301, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476], + buffer: [0; 64], + buffered: 0, + length: 0, + } + } + + /// Absorb more bytes. + pub fn update(&mut self, mut data: &[u8]) { + self.length = self.length.wrapping_add(data.len() as u64); + if self.buffered > 0 { + let take = (64 - self.buffered).min(data.len()); + self.buffer[self.buffered..self.buffered + take].copy_from_slice(&data[..take]); + self.buffered += take; + data = &data[take..]; + if self.buffered == 64 { + let block = self.buffer; + self.compress(&block); + self.buffered = 0; + } + // The partial block is still filling; leaving now keeps it, where + // falling through would overwrite `buffered` with an empty tail. + if data.is_empty() { + return; + } + } + let mut chunks = data.chunks_exact(64); + for block in &mut chunks { + let mut b = [0u8; 64]; + b.copy_from_slice(block); + self.compress(&b); + } + let rest = chunks.remainder(); + self.buffer[..rest.len()].copy_from_slice(rest); + self.buffered = rest.len(); + } + + /// The 16-byte digest. + pub fn finish(mut self) -> [u8; 16] { + let bit_len = self.length.wrapping_mul(8); + self.update(&[0x80]); + // update() counted the padding byte; the length is already captured. + while self.buffered != 56 { + self.update(&[0]); + } + let mut block = self.buffer; + block[56..].copy_from_slice(&bit_len.to_le_bytes()); + self.compress(&block); + let mut out = [0u8; 16]; + for (i, word) in self.state.iter().enumerate() { + out[i * 4..i * 4 + 4].copy_from_slice(&word.to_le_bytes()); + } + out + } + + fn compress(&mut self, block: &[u8; 64]) { + let mut m = [0u32; 16]; + for (i, word) in m.iter_mut().enumerate() { + *word = u32::from_le_bytes([ + block[i * 4], + block[i * 4 + 1], + block[i * 4 + 2], + block[i * 4 + 3], + ]); + } + let [mut a, mut b, mut c, mut d] = self.state; + for i in 0..64 { + let (f, g) = match i / 16 { + 0 => ((b & c) | (!b & d), i), + 1 => ((d & b) | (!d & c), (5 * i + 1) % 16), + 2 => (b ^ c ^ d, (3 * i + 5) % 16), + _ => (c ^ (b | !d), (7 * i) % 16), + }; + let tmp = d; + d = c; + c = b; + b = b.wrapping_add( + a.wrapping_add(f) + .wrapping_add(K[i]) + .wrapping_add(m[g]) + .rotate_left(S[i]), + ); + a = tmp; + } + self.state[0] = self.state[0].wrapping_add(a); + self.state[1] = self.state[1].wrapping_add(b); + self.state[2] = self.state[2].wrapping_add(c); + self.state[3] = self.state[3].wrapping_add(d); + } +} + +impl Default for Md5 { + fn default() -> Self { + Md5::new() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hex(digest: [u8; 16]) -> String { + digest.iter().map(|b| format!("{b:02x}")).collect() + } + + fn md5(data: &[u8]) -> String { + let mut m = Md5::new(); + m.update(data); + hex(m.finish()) + } + + #[test] + fn rfc1321_test_suite() { + assert_eq!(md5(b""), "d41d8cd98f00b204e9800998ecf8427e"); + assert_eq!(md5(b"a"), "0cc175b9c0f1b6a831c399e269772661"); + assert_eq!(md5(b"abc"), "900150983cd24fb0d6963f7d28e17f72"); + assert_eq!(md5(b"message digest"), "f96b697d7cb7938d525a2f31aaf161d0"); + assert_eq!( + md5(b"abcdefghijklmnopqrstuvwxyz"), + "c3fcd3d76192e4007dfb496cca67e13b" + ); + assert_eq!( + md5(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"), + "d174ab98d277d9f5a5611c2c9f419d9f" + ); + assert_eq!( + md5(b"12345678901234567890123456789012345678901234567890123456789012345678901234567890"), + "57edf4a22be3c955ac49da2e2107b67a" + ); + } + + #[test] + fn chunked_updates_match_one_shot() { + let data: Vec = (0..1000u32).map(|i| (i * 7) as u8).collect(); + let mut whole = Md5::new(); + whole.update(&data); + let mut split = Md5::new(); + for chunk in data.chunks(7) { + split.update(chunk); + } + assert_eq!(whole.finish(), split.finish()); + } +} diff --git a/crates/ec-h265-syntax/src/nal.rs b/crates/ec-h265-syntax/src/nal.rs new file mode 100644 index 00000000..4276760f --- /dev/null +++ b/crates/ec-h265-syntax/src/nal.rs @@ -0,0 +1,335 @@ +//! NAL units: the two-byte header, RBSP escaping and Annex-B framing. + +use ec_core::error::{Error, Result}; + +/// `nal_unit_type` values this family names (Table 7-1). +/// +/// The numeric value is the wire value; unnamed types travel as +/// [`NalUnitType::Other`] rather than being refused, because a parser that +/// cannot skip a NAL it does not know is a parser that breaks on the next +/// extension. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum NalUnitType { + /// Coded slice of a non-TSA, non-STSA trailing picture (sub-layer non-ref). + TrailN, + /// Coded slice of a non-TSA, non-STSA trailing picture (reference). + TrailR, + /// Coded slice of an IDR picture that may have leading RADL pictures. + IdrWRadl, + /// Coded slice of an IDR picture with no leading pictures. + IdrNLp, + /// Coded slice of a CRA picture. + CraNut, + /// Video parameter set. + Vps, + /// Sequence parameter set. + Sps, + /// Picture parameter set. + Pps, + /// Access unit delimiter. + Aud, + /// End of sequence. + EosNut, + /// End of bitstream. + EobNut, + /// Filler data. + FdNut, + /// SEI that precedes the pictures it describes. + PrefixSei, + /// SEI that follows them — where the decoded picture hash lives. + SuffixSei, + /// Anything else, carried verbatim. + Other(u8), +} + +impl NalUnitType { + /// The wire value. + pub fn code(self) -> u8 { + match self { + NalUnitType::TrailN => 0, + NalUnitType::TrailR => 1, + NalUnitType::IdrWRadl => 19, + NalUnitType::IdrNLp => 20, + NalUnitType::CraNut => 21, + NalUnitType::Vps => 32, + NalUnitType::Sps => 33, + NalUnitType::Pps => 34, + NalUnitType::Aud => 35, + NalUnitType::EosNut => 36, + NalUnitType::EobNut => 37, + NalUnitType::FdNut => 38, + NalUnitType::PrefixSei => 39, + NalUnitType::SuffixSei => 40, + NalUnitType::Other(v) => v, + } + } + + /// The named type for a wire value. + pub fn from_code(code: u8) -> NalUnitType { + match code { + 0 => NalUnitType::TrailN, + 1 => NalUnitType::TrailR, + 19 => NalUnitType::IdrWRadl, + 20 => NalUnitType::IdrNLp, + 21 => NalUnitType::CraNut, + 32 => NalUnitType::Vps, + 33 => NalUnitType::Sps, + 34 => NalUnitType::Pps, + 35 => NalUnitType::Aud, + 36 => NalUnitType::EosNut, + 37 => NalUnitType::EobNut, + 38 => NalUnitType::FdNut, + 39 => NalUnitType::PrefixSei, + 40 => NalUnitType::SuffixSei, + v => NalUnitType::Other(v), + } + } + + /// True for the video coding layer types (0..=31), the ones that carry slices. + pub fn is_vcl(self) -> bool { + self.code() < 32 + } + + /// True for the IRAP range (16..=23): a decoder may be started here. + pub fn is_irap(self) -> bool { + (16..=23).contains(&self.code()) + } + + /// True for the two IDR types, which is what "every AU is a sync point" means. + pub fn is_idr(self) -> bool { + matches!(self, NalUnitType::IdrWRadl | NalUnitType::IdrNLp) + } +} + +/// The two-byte NAL unit header (7.3.1.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct NalHeader { + /// What the payload is. + pub nal_type: NalUnitType, + /// Layer id; 0 for everything this family writes. + pub layer_id: u8, + /// `nuh_temporal_id_plus1 - 1`. + pub temporal_id: u8, +} + +impl NalHeader { + /// A base-layer header at temporal id 0. + pub fn new(nal_type: NalUnitType) -> NalHeader { + NalHeader { + nal_type, + layer_id: 0, + temporal_id: 0, + } + } + + /// The two header bytes. + pub fn to_bytes(self) -> [u8; 2] { + let b0 = (self.nal_type.code() << 1) | (self.layer_id >> 5); + let b1 = ((self.layer_id & 0x1f) << 3) | (self.temporal_id + 1); + [b0, b1] + } + + /// Parse the two header bytes, rejecting a set `forbidden_zero_bit`. + pub fn parse(bytes: &[u8]) -> Result { + let (b0, b1) = match bytes { + [b0, b1, ..] => (*b0, *b1), + _ => return Err(Error::NeedMore), + }; + if b0 & 0x80 != 0 { + return Err(Error::corrupt("HEVC NAL header: forbidden_zero_bit set")); + } + let temporal_id_plus1 = b1 & 0x7; + if temporal_id_plus1 == 0 { + return Err(Error::corrupt("HEVC NAL header: nuh_temporal_id_plus1 = 0")); + } + Ok(NalHeader { + nal_type: NalUnitType::from_code((b0 >> 1) & 0x3f), + layer_id: ((b0 & 1) << 5) | (b1 >> 3), + temporal_id: temporal_id_plus1 - 1, + }) + } +} + +/// Escape an RBSP into a NAL unit payload (7.3.1.1). +/// +/// A `0x03` goes in before any byte that would otherwise complete a +/// `00 00 00`..`00 00 03` sequence, so a start code can never appear inside a +/// NAL unit. Trailing `00 00` at the very end is escaped too: the next thing in +/// the stream is a start code, and `00 00 00 01` read backwards from there would +/// swallow the last payload byte. +pub fn escape_rbsp(rbsp: &[u8], out: &mut Vec) { + let mut zeros = 0usize; + for &b in rbsp { + if zeros >= 2 && b <= 3 { + out.push(3); + zeros = 0; + } + out.push(b); + if b == 0 { + zeros += 1; + } else { + zeros = 0; + } + } + if zeros >= 2 { + out.push(3); + } +} + +/// Strip emulation prevention bytes from a NAL unit payload. +pub fn unescape_rbsp(payload: &[u8]) -> Vec { + let mut out = Vec::with_capacity(payload.len()); + let mut zeros = 0usize; + for &b in payload { + if zeros >= 2 && b == 3 { + zeros = 0; + continue; + } + out.push(b); + if b == 0 { + zeros += 1; + } else { + zeros = 0; + } + } + out +} + +/// Append one Annex-B NAL unit: start code, header, escaped RBSP. +/// +/// The four-byte start code is used for parameter sets and the first slice of a +/// picture, three bytes elsewhere — the same shape ffmpeg writes, and what a +/// caller splitting an access unit back apart expects. +pub fn write_annex_b(out: &mut Vec, header: NalHeader, rbsp: &[u8], long_start_code: bool) { + if long_start_code { + out.extend_from_slice(&[0, 0, 0, 1]); + } else { + out.extend_from_slice(&[0, 0, 1]); + } + out.extend_from_slice(&header.to_bytes()); + escape_rbsp(rbsp, out); +} + +/// One NAL unit found in an Annex-B stream. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AnnexBNal<'a> { + /// Parsed two-byte header. + pub header: NalHeader, + /// Payload after the header, still escaped. + pub payload: &'a [u8], +} + +impl AnnexBNal<'_> { + /// The payload with emulation prevention bytes removed. + pub fn rbsp(&self) -> Vec { + unescape_rbsp(self.payload) + } +} + +/// Split an Annex-B byte stream into NAL units. +/// +/// Bytes before the first start code are ignored rather than refused, which is +/// what makes this usable on a stream joined mid-file. A NAL whose header is +/// malformed is skipped, not fatal. +pub fn split_annex_b(data: &[u8]) -> Vec> { + let mut nals = Vec::new(); + let mut starts = Vec::new(); + let mut i = 0usize; + while i + 3 <= data.len() { + if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 { + starts.push(i + 3); + i += 3; + } else { + i += 1; + } + } + for (n, &start) in starts.iter().enumerate() { + let mut end = starts.get(n + 1).map_or(data.len(), |&next| next - 3); + // A four-byte start code leaves one extra zero at the end of the + // previous unit; trailing zeros are never part of an RBSP. + while end > start && data[end - 1] == 0 { + end -= 1; + } + if end < start + 2 { + continue; + } + if let Ok(header) = NalHeader::parse(&data[start..end]) { + nals.push(AnnexBNal { + header, + payload: &data[start + 2..end], + }); + } + } + nals +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn header_round_trip() { + for code in 0u8..64 { + let h = NalHeader { + nal_type: NalUnitType::from_code(code), + layer_id: 0, + temporal_id: 0, + }; + let bytes = h.to_bytes(); + assert_eq!(NalHeader::parse(&bytes).unwrap(), h); + } + // An IDR slice header is the well-known 0x26 0x01. + assert_eq!(NalHeader::new(NalUnitType::IdrWRadl).to_bytes(), [0x26, 0x01]); + assert_eq!(NalHeader::new(NalUnitType::Vps).to_bytes(), [0x40, 0x01]); + assert!(NalHeader::parse(&[0x80, 0x01]).is_err()); + assert!(NalHeader::parse(&[0x26, 0x00]).is_err()); + assert!(NalHeader::parse(&[0x26]).is_err()); + } + + #[test] + fn escaping_round_trips_and_kills_start_codes() { + let cases: &[&[u8]] = &[ + &[], + &[0, 0, 0], + &[0, 0, 1], + &[0, 0, 2], + &[0, 0, 3], + &[0, 0, 4], + &[1, 0, 0, 0, 0, 1], + &[0, 0], + &[0xff, 0, 0, 3, 0, 0, 0, 1], + ]; + for case in cases { + let mut escaped = Vec::new(); + escape_rbsp(case, &mut escaped); + assert_eq!(&unescape_rbsp(&escaped)[..], *case, "case {case:?}"); + // No start code emulation survives escaping. + assert!( + !escaped.windows(3).any(|w| w == [0, 0, 1]), + "start code in {escaped:?}" + ); + } + } + + #[test] + fn annex_b_split_finds_units() { + let mut stream = Vec::new(); + write_annex_b(&mut stream, NalHeader::new(NalUnitType::Vps), &[1, 2, 3], true); + write_annex_b( + &mut stream, + NalHeader::new(NalUnitType::IdrWRadl), + &[0, 0, 0, 7], + false, + ); + let nals = split_annex_b(&stream); + assert_eq!(nals.len(), 2); + assert_eq!(nals[0].header.nal_type, NalUnitType::Vps); + assert_eq!(nals[0].rbsp(), vec![1, 2, 3]); + assert_eq!(nals[1].header.nal_type, NalUnitType::IdrWRadl); + assert_eq!(nals[1].rbsp(), vec![0, 0, 0, 7]); + assert!(nals[1].header.nal_type.is_idr()); + assert!(nals[1].header.nal_type.is_irap()); + assert!(nals[1].header.nal_type.is_vcl()); + assert!(!nals[0].header.nal_type.is_vcl()); + } +} diff --git a/crates/ec-h265-syntax/src/ps.rs b/crates/ec-h265-syntax/src/ps.rs new file mode 100644 index 00000000..69755e2e --- /dev/null +++ b/crates/ec-h265-syntax/src/ps.rs @@ -0,0 +1,992 @@ +//! Parameter sets: VPS, SPS and PPS, written and parsed. +//! +//! The field sets here are sized by what a *stateless hardware decoder* asks +//! for, not by what this family's own encoder writes: everything in +//! `VAPictureParameterBufferHEVC` is either a field on [`Sps`]/[`Pps`] or +//! derivable from one by a named method. Anything the parser walks past but does +//! not model (scaling lists, HRD, the multilayer and 3D extensions) is a thing +//! no consumer in this family reads, and each such skip says so where it happens. + +use crate::vui::VuiParameters; +use ec_core::bitio::{BitReader, BitWriter}; +use ec_core::error::{Error, Result}; + +/// `profile_tier_level()` for a single-sub-layer stream (7.3.3). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ProfileTierLevel { + /// `general_profile_space`, 0 for everything in the wild. + pub profile_space: u8, + /// False = Main tier, true = High tier. + pub tier_flag: bool, + /// 1 = Main, 2 = Main 10, 3 = Main Still Picture, 4 = range extensions. + pub profile_idc: u8, + /// `general_profile_compatibility_flag[0..32]` as a bit set, bit `j` = flag `j`. + pub profile_compatibility: u32, + /// `general_progressive_source_flag`. + pub progressive_source: bool, + /// `general_interlaced_source_flag`. + pub interlaced_source: bool, + /// `general_non_packed_constraint_flag`. + pub non_packed_constraint: bool, + /// `general_frame_only_constraint_flag`. + pub frame_only_constraint: bool, + /// The 44 bits between the source flags and `general_level_idc`: the + /// profile-dependent constraint flags, their reserved padding and + /// `general_inbld_flag`. Kept verbatim so a re-write is byte-identical, + /// because their *meaning* depends on `profile_idc` while their length + /// never does. + pub constraint_bits: u64, + /// `general_level_idc`: 30 x the level number (level 4 = 120). + pub level_idc: u8, +} + +impl ProfileTierLevel { + /// Main profile at `level_idc`, progressive, frame-only — what an intra + /// 8-bit 4:2:0 encoder emits. + pub fn main(level_idc: u8) -> ProfileTierLevel { + ProfileTierLevel { + profile_space: 0, + tier_flag: false, + profile_idc: 1, + // Main is compatible with itself; bit 1 is what every decoder checks. + profile_compatibility: 1 << 1, + progressive_source: true, + interlaced_source: false, + non_packed_constraint: true, + frame_only_constraint: true, + constraint_bits: 0, + level_idc, + } + } + + /// The smallest level whose limits hold for `width x height` at `fps` + /// (Annex A, Table A.8/A.9 luma sample and sample-rate limits). + /// + /// Levels are a decoder's promise about buffer sizes; naming one too small + /// is what makes a hardware decoder refuse a stream it could otherwise play, + /// so this rounds up and stops at 6.2. + pub fn level_for(width: u32, height: u32, fps: f64) -> u8 { + // (level_idc, MaxLumaPs, MaxLumaSr) + const LIMITS: &[(u8, u64, u64)] = &[ + (30, 36_864, 552_960), + (60, 122_880, 3_686_400), + (63, 245_760, 7_372_800), + (90, 552_960, 16_588_800), + (93, 983_040, 33_177_600), + (120, 2_228_224, 66_846_720), + (123, 2_228_224, 133_693_440), + (126, 2_228_224, 267_386_880), + (150, 8_912_896, 534_773_760), + (153, 8_912_896, 1_069_547_520), + (156, 8_912_896, 1_069_547_520), + (180, 35_651_584, 2_139_095_040), + (183, 35_651_584, 4_278_190_080), + (186, 35_651_584, 4_278_190_080), + ]; + let samples = u64::from(width) * u64::from(height); + let rate = (samples as f64 * fps.max(1.0)) as u64; + for &(idc, max_ps, max_sr) in LIMITS { + if samples <= max_ps && rate <= max_sr { + return idc; + } + } + 186 + } + + /// Write `profile_tier_level(1, 0)` — 96 bits, always. + pub fn write(&self, w: &mut BitWriter) { + w.write_bits(u32::from(self.profile_space), 2); + w.write_bit(self.tier_flag); + w.write_bits(u32::from(self.profile_idc), 5); + for j in 0..32 { + w.write_bit(self.profile_compatibility & (1 << j) != 0); + } + w.write_bit(self.progressive_source); + w.write_bit(self.interlaced_source); + w.write_bit(self.non_packed_constraint); + w.write_bit(self.frame_only_constraint); + w.write_bits64(self.constraint_bits, 44); + w.write_bits(u32::from(self.level_idc), 8); + } + + /// Parse `profile_tier_level(1, max_sub_layers_minus1)`. + pub fn parse(r: &mut BitReader, max_sub_layers_minus1: u32) -> Result { + let profile_space = r.read_bits(2)? as u8; + let tier_flag = r.read_bit()?; + let profile_idc = r.read_bits(5)? as u8; + let mut profile_compatibility = 0u32; + for j in 0..32 { + if r.read_bit()? { + profile_compatibility |= 1 << j; + } + } + let progressive_source = r.read_bit()?; + let interlaced_source = r.read_bit()?; + let non_packed_constraint = r.read_bit()?; + let frame_only_constraint = r.read_bit()?; + let constraint_bits = r.read_bits64(44)?; + let level_idc = r.read_bits(8)? as u8; + let mut sub_layer_profile = Vec::new(); + let mut sub_layer_level = Vec::new(); + for _ in 0..max_sub_layers_minus1 { + sub_layer_profile.push(r.read_bit()?); + sub_layer_level.push(r.read_bit()?); + } + if max_sub_layers_minus1 > 0 { + for _ in max_sub_layers_minus1..8 { + r.read_bits(2)?; + } + } + for i in 0..max_sub_layers_minus1 as usize { + if sub_layer_profile[i] { + r.skip_bits(88)?; + } + if sub_layer_level[i] { + r.read_bits(8)?; + } + } + Ok(ProfileTierLevel { + profile_space, + tier_flag, + profile_idc, + profile_compatibility, + progressive_source, + interlaced_source, + non_packed_constraint, + frame_only_constraint, + constraint_bits, + level_idc, + }) + } +} + +/// The video parameter set (7.3.2.1). +/// +/// A single-layer stream needs one and nothing in it varies, but a decoder that +/// never sees a VPS refuses the stream, so it is written all the same. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Vps { + /// `vps_video_parameter_set_id`. + pub id: u8, + /// Profile, tier and level of the base layer. + pub ptl: ProfileTierLevel, + /// `vps_max_dec_pic_buffering_minus1[0]`. + pub max_dec_pic_buffering_minus1: u32, + /// `vps_max_num_reorder_pics[0]`; 0 for an intra-only stream. + pub max_num_reorder_pics: u32, +} + +impl Vps { + /// The RBSP, trailing bits included. + pub fn to_rbsp(&self) -> Vec { + let mut w = BitWriter::with_capacity(32); + w.write_bits(u32::from(self.id), 4); + w.write_bit(true); // vps_base_layer_internal_flag + w.write_bit(true); // vps_base_layer_available_flag + w.write_bits(0, 6); // vps_max_layers_minus1 + w.write_bits(0, 3); // vps_max_sub_layers_minus1 + w.write_bit(true); // vps_temporal_id_nesting_flag + w.write_bits(0xffff, 16); // vps_reserved_0xffff_16bits + self.ptl.write(&mut w); + w.write_bit(true); // vps_sub_layer_ordering_info_present_flag + w.write_ue(self.max_dec_pic_buffering_minus1); + w.write_ue(self.max_num_reorder_pics); + w.write_ue(0); // vps_max_latency_increase_plus1 + w.write_bits(0, 6); // vps_max_layer_id + w.write_ue(0); // vps_num_layer_sets_minus1 + w.write_bit(false); // vps_timing_info_present_flag + w.write_bit(false); // vps_extension_flag + rbsp_trailing_bits(&mut w); + w.into_bytes() + } + + /// Parse a VPS RBSP. + pub fn parse(rbsp: &[u8]) -> Result { + let mut r = BitReader::new(rbsp); + let id = r.read_bits(4)? as u8; + r.read_bit()?; + r.read_bit()?; + r.read_bits(6)?; // vps_max_layers_minus1 + let max_sub_layers_minus1 = r.read_bits(3)?; + r.read_bit()?; + r.read_bits(16)?; + let ptl = ProfileTierLevel::parse(&mut r, max_sub_layers_minus1)?; + let ordering_info = r.read_bit()?; + let first = if ordering_info { 0 } else { max_sub_layers_minus1 }; + let mut max_dec_pic_buffering_minus1 = 0; + let mut max_num_reorder_pics = 0; + for _ in first..=max_sub_layers_minus1 { + max_dec_pic_buffering_minus1 = r.read_ue()?; + max_num_reorder_pics = r.read_ue()?; + r.read_ue()?; + } + Ok(Vps { + id, + ptl, + max_dec_pic_buffering_minus1, + max_num_reorder_pics, + }) + } +} + +/// The conformance window: how many samples to crop off a coded picture. +/// +/// This is how 1920x1080 is coded with 64x64 coding tree blocks — the picture is +/// coded 1920x1088 and eight rows are cropped — and it is a first-class field +/// here rather than a caller's problem, because a caller that pads its own +/// planes has to guess what the encoder does with the padding. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct ConformanceWindow { + /// `conf_win_left_offset`, in chroma units. + pub left: u32, + /// `conf_win_right_offset`, in chroma units. + pub right: u32, + /// `conf_win_top_offset`, in chroma units. + pub top: u32, + /// `conf_win_bottom_offset`, in chroma units. + pub bottom: u32, +} + +impl ConformanceWindow { + /// True when nothing is cropped. + pub fn is_empty(&self) -> bool { + *self == ConformanceWindow::default() + } +} + +/// The sequence parameter set (7.3.2.2.1). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Sps { + /// `sps_video_parameter_set_id`. + pub vps_id: u8, + /// `sps_seq_parameter_set_id`. + pub id: u32, + /// 0 = monochrome, 1 = 4:2:0, 2 = 4:2:2, 3 = 4:4:4. + pub chroma_format_idc: u32, + /// `separate_colour_plane_flag`. + pub separate_colour_plane: bool, + /// Coded width — a multiple of the minimum coding block size. + pub pic_width_in_luma_samples: u32, + /// Coded height. + pub pic_height_in_luma_samples: u32, + /// What to crop off the coded picture for display. + pub conf_win: ConformanceWindow, + /// `bit_depth_luma_minus8`. + pub bit_depth_luma_minus8: u32, + /// `bit_depth_chroma_minus8`. + pub bit_depth_chroma_minus8: u32, + /// `log2_max_pic_order_cnt_lsb_minus4`. + pub log2_max_poc_lsb_minus4: u32, + /// `sps_max_dec_pic_buffering_minus1[HighestTid]`. + pub max_dec_pic_buffering_minus1: u32, + /// `sps_max_num_reorder_pics[HighestTid]`. + pub max_num_reorder_pics: u32, + /// `log2_min_luma_coding_block_size_minus3`. + pub log2_min_cb_size_minus3: u32, + /// `log2_diff_max_min_luma_coding_block_size`. + pub log2_diff_max_min_cb_size: u32, + /// `log2_min_luma_transform_block_size_minus2`. + pub log2_min_tb_size_minus2: u32, + /// `log2_diff_max_min_luma_transform_block_size`. + pub log2_diff_max_min_tb_size: u32, + /// `max_transform_hierarchy_depth_inter`. + pub max_transform_hierarchy_depth_inter: u32, + /// `max_transform_hierarchy_depth_intra`. + pub max_transform_hierarchy_depth_intra: u32, + /// `scaling_list_enabled_flag`; this family never writes scaling lists. + pub scaling_list_enabled: bool, + /// `amp_enabled_flag`. + pub amp_enabled: bool, + /// `sample_adaptive_offset_enabled_flag`. + pub sao_enabled: bool, + /// `pcm_enabled_flag`. + pub pcm_enabled: bool, + /// `num_short_term_ref_pic_sets`. + pub num_short_term_ref_pic_sets: u32, + /// `long_term_ref_pics_present_flag`. + pub long_term_ref_pics_present: bool, + /// `num_long_term_ref_pics_sps`. + pub num_long_term_ref_pics_sps: u32, + /// `sps_temporal_mvp_enabled_flag`. + pub temporal_mvp_enabled: bool, + /// `strong_intra_smoothing_enabled_flag`. + pub strong_intra_smoothing: bool, + /// Profile, tier, level. + pub ptl: ProfileTierLevel, + /// VUI, when present. + pub vui: Option, +} + +impl Sps { + /// Coding tree block size in luma samples (`CtbSizeY`). + pub fn ctb_size(&self) -> u32 { + 1 << (self.log2_min_cb_size_minus3 + 3 + self.log2_diff_max_min_cb_size) + } + + /// `PicWidthInCtbsY`. + pub fn pic_width_in_ctbs(&self) -> u32 { + self.pic_width_in_luma_samples.div_ceil(self.ctb_size()) + } + + /// `PicHeightInCtbsY`. + pub fn pic_height_in_ctbs(&self) -> u32 { + self.pic_height_in_luma_samples.div_ceil(self.ctb_size()) + } + + /// `SubWidthC`, `SubHeightC` for the chroma format. + pub fn chroma_subsampling(&self) -> (u32, u32) { + match self.chroma_format_idc { + 1 => (2, 2), + 2 => (2, 1), + _ => (1, 1), + } + } + + /// Displayed size after the conformance window is applied. + pub fn display_size(&self) -> (u32, u32) { + let (sub_w, sub_h) = self.chroma_subsampling(); + ( + self.pic_width_in_luma_samples - sub_w * (self.conf_win.left + self.conf_win.right), + self.pic_height_in_luma_samples - sub_h * (self.conf_win.top + self.conf_win.bottom), + ) + } + + /// Number of bits `slice_segment_address` occupies in a slice header: + /// `Ceil( Log2( PicSizeInCtbsY ) )`. + pub fn slice_address_bits(&self) -> u32 { + ceil_log2(self.pic_width_in_ctbs() * self.pic_height_in_ctbs()) + } + + /// The RBSP, trailing bits included. + pub fn to_rbsp(&self) -> Vec { + let mut w = BitWriter::with_capacity(64); + w.write_bits(u32::from(self.vps_id), 4); + w.write_bits(0, 3); // sps_max_sub_layers_minus1 + w.write_bit(true); // sps_temporal_id_nesting_flag + self.ptl.write(&mut w); + w.write_ue(self.id); + w.write_ue(self.chroma_format_idc); + if self.chroma_format_idc == 3 { + w.write_bit(self.separate_colour_plane); + } + w.write_ue(self.pic_width_in_luma_samples); + w.write_ue(self.pic_height_in_luma_samples); + if self.conf_win.is_empty() { + w.write_bit(false); + } else { + w.write_bit(true); + w.write_ue(self.conf_win.left); + w.write_ue(self.conf_win.right); + w.write_ue(self.conf_win.top); + w.write_ue(self.conf_win.bottom); + } + w.write_ue(self.bit_depth_luma_minus8); + w.write_ue(self.bit_depth_chroma_minus8); + w.write_ue(self.log2_max_poc_lsb_minus4); + w.write_bit(true); // sps_sub_layer_ordering_info_present_flag + w.write_ue(self.max_dec_pic_buffering_minus1); + w.write_ue(self.max_num_reorder_pics); + w.write_ue(0); // sps_max_latency_increase_plus1 + w.write_ue(self.log2_min_cb_size_minus3); + w.write_ue(self.log2_diff_max_min_cb_size); + w.write_ue(self.log2_min_tb_size_minus2); + w.write_ue(self.log2_diff_max_min_tb_size); + w.write_ue(self.max_transform_hierarchy_depth_inter); + w.write_ue(self.max_transform_hierarchy_depth_intra); + w.write_bit(self.scaling_list_enabled); + if self.scaling_list_enabled { + w.write_bit(false); // sps_scaling_list_data_present_flag + } + w.write_bit(self.amp_enabled); + w.write_bit(self.sao_enabled); + w.write_bit(self.pcm_enabled); + w.write_ue(self.num_short_term_ref_pic_sets); + w.write_bit(self.long_term_ref_pics_present); + if self.long_term_ref_pics_present { + w.write_ue(self.num_long_term_ref_pics_sps); + } + w.write_bit(self.temporal_mvp_enabled); + w.write_bit(self.strong_intra_smoothing); + match &self.vui { + Some(vui) => { + w.write_bit(true); + vui.write(&mut w); + } + None => w.write_bit(false), + } + w.write_bit(false); // sps_extension_present_flag + rbsp_trailing_bits(&mut w); + w.into_bytes() + } + + /// Parse an SPS RBSP. + /// + /// Short-term reference picture sets are walked but not kept: a decoder + /// resolves them from the slice header, and this family's own streams have + /// none. A stream with scaling lists is refused rather than mis-decoded. + pub fn parse(rbsp: &[u8]) -> Result { + let mut r = BitReader::new(rbsp); + let vps_id = r.read_bits(4)? as u8; + let max_sub_layers_minus1 = r.read_bits(3)?; + r.read_bit()?; // sps_temporal_id_nesting_flag + let ptl = ProfileTierLevel::parse(&mut r, max_sub_layers_minus1)?; + let id = r.read_ue()?; + let chroma_format_idc = r.read_ue()?; + if chroma_format_idc > 3 { + return Err(Error::corrupt(format!( + "HEVC SPS: chroma_format_idc = {chroma_format_idc}" + ))); + } + let separate_colour_plane = if chroma_format_idc == 3 { + r.read_bit()? + } else { + false + }; + let pic_width_in_luma_samples = r.read_ue()?; + let pic_height_in_luma_samples = r.read_ue()?; + if pic_width_in_luma_samples == 0 || pic_height_in_luma_samples == 0 { + return Err(Error::corrupt("HEVC SPS: zero picture dimension")); + } + let mut conf_win = ConformanceWindow::default(); + if r.read_bit()? { + conf_win = ConformanceWindow { + left: r.read_ue()?, + right: r.read_ue()?, + top: r.read_ue()?, + bottom: r.read_ue()?, + }; + } + let bit_depth_luma_minus8 = r.read_ue()?; + let bit_depth_chroma_minus8 = r.read_ue()?; + if bit_depth_luma_minus8 > 8 || bit_depth_chroma_minus8 > 8 { + return Err(Error::corrupt("HEVC SPS: bit depth out of range")); + } + let log2_max_poc_lsb_minus4 = r.read_ue()?; + let ordering_info = r.read_bit()?; + let first = if ordering_info { 0 } else { max_sub_layers_minus1 }; + let mut max_dec_pic_buffering_minus1 = 0; + let mut max_num_reorder_pics = 0; + for _ in first..=max_sub_layers_minus1 { + max_dec_pic_buffering_minus1 = r.read_ue()?; + max_num_reorder_pics = r.read_ue()?; + r.read_ue()?; + } + let log2_min_cb_size_minus3 = r.read_ue()?; + let log2_diff_max_min_cb_size = r.read_ue()?; + let log2_min_tb_size_minus2 = r.read_ue()?; + let log2_diff_max_min_tb_size = r.read_ue()?; + if log2_min_cb_size_minus3 + log2_diff_max_min_cb_size > 3 { + return Err(Error::corrupt("HEVC SPS: CTB larger than 64x64")); + } + let max_transform_hierarchy_depth_inter = r.read_ue()?; + let max_transform_hierarchy_depth_intra = r.read_ue()?; + let scaling_list_enabled = r.read_bit()?; + if scaling_list_enabled && r.read_bit()? { + return Err(Error::unsupported( + "HEVC SPS scaling lists", + "this family codes with the flat 16 matrix only", + )); + } + let amp_enabled = r.read_bit()?; + let sao_enabled = r.read_bit()?; + let pcm_enabled = r.read_bit()?; + if pcm_enabled { + r.read_bits(4)?; // pcm_sample_bit_depth_luma_minus1 + r.read_bits(4)?; // pcm_sample_bit_depth_chroma_minus1 + r.read_ue()?; // log2_min_pcm_luma_coding_block_size_minus3 + r.read_ue()?; // log2_diff_max_min_pcm_luma_coding_block_size + r.read_bit()?; // pcm_loop_filter_disabled_flag + } + let num_short_term_ref_pic_sets = r.read_ue()?; + if num_short_term_ref_pic_sets > 64 { + return Err(Error::corrupt("HEVC SPS: num_short_term_ref_pic_sets > 64")); + } + let mut sets = Vec::new(); + for i in 0..num_short_term_ref_pic_sets { + let set = ShortTermRefPicSet::parse(&mut r, i, &sets)?; + sets.push(set); + } + let long_term_ref_pics_present = r.read_bit()?; + let mut num_long_term_ref_pics_sps = 0; + if long_term_ref_pics_present { + num_long_term_ref_pics_sps = r.read_ue()?; + for _ in 0..num_long_term_ref_pics_sps { + r.read_bits(log2_max_poc_lsb_minus4 + 4)?; + r.read_bit()?; + } + } + let temporal_mvp_enabled = r.read_bit()?; + let strong_intra_smoothing = r.read_bit()?; + let vui = if r.read_bit()? { + Some(VuiParameters::parse(&mut r, max_sub_layers_minus1)?) + } else { + None + }; + Ok(Sps { + vps_id, + id, + chroma_format_idc, + separate_colour_plane, + pic_width_in_luma_samples, + pic_height_in_luma_samples, + conf_win, + bit_depth_luma_minus8, + bit_depth_chroma_minus8, + log2_max_poc_lsb_minus4, + max_dec_pic_buffering_minus1, + max_num_reorder_pics, + log2_min_cb_size_minus3, + log2_diff_max_min_cb_size, + log2_min_tb_size_minus2, + log2_diff_max_min_tb_size, + max_transform_hierarchy_depth_inter, + max_transform_hierarchy_depth_intra, + scaling_list_enabled, + amp_enabled, + sao_enabled, + pcm_enabled, + num_short_term_ref_pic_sets, + long_term_ref_pics_present, + num_long_term_ref_pics_sps, + temporal_mvp_enabled, + strong_intra_smoothing, + ptl, + vui, + }) + } +} + +/// One `st_ref_pic_set()` (7.3.7), kept only as far as re-parsing needs. +/// +/// The delta values themselves are a decoder's reference-list problem; what a +/// *parser* has to get right is the number of pictures in each direction, +/// because the next set's syntax depends on it. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct ShortTermRefPicSet { + /// `NumNegativePics`. + pub num_negative: u32, + /// `NumPositivePics`. + pub num_positive: u32, + /// How many of them have `used_by_curr_pic` set — the count that feeds + /// `NumPicTotalCurr`, which sizes the reference list modification syntax. + pub num_used_by_curr: u32, +} + +impl ShortTermRefPicSet { + /// Parse one set; `prev` holds the sets already parsed for inter-set prediction. + pub fn parse( + r: &mut BitReader, + idx: u32, + prev: &[ShortTermRefPicSet], + ) -> Result { + let inter_ref_pic_set_prediction = if idx != 0 { r.read_bit()? } else { false }; + if inter_ref_pic_set_prediction { + let delta_idx_minus1 = if idx == prev.len() as u32 { + r.read_ue()? + } else { + 0 + }; + let ref_idx = idx + .checked_sub(delta_idx_minus1 + 1) + .ok_or_else(|| Error::corrupt("HEVC st_ref_pic_set: delta_idx out of range"))?; + let reference = *prev + .get(ref_idx as usize) + .ok_or_else(|| Error::corrupt("HEVC st_ref_pic_set: unknown reference set"))?; + r.read_bit()?; // delta_rps_sign + r.read_ue()?; // abs_delta_rps_minus1 + let num_delta_pocs = reference.num_negative + reference.num_positive; + let mut kept = 0; + let mut used_by_curr = 0; + for _ in 0..=num_delta_pocs { + let used = r.read_bit()?; + if used { + kept += 1; + used_by_curr += 1; + } else if r.read_bit()? { + kept += 1; + } + } + // Without reconstructing the POCs the split between negative and + // positive is not knowable; the total is, and that is what the + // syntax of any following set depends on. + Ok(ShortTermRefPicSet { + num_negative: kept, + num_positive: 0, + num_used_by_curr: used_by_curr, + }) + } else { + let num_negative = r.read_ue()?; + let num_positive = r.read_ue()?; + if num_negative > 16 || num_positive > 16 { + return Err(Error::corrupt("HEVC st_ref_pic_set: too many pictures")); + } + let mut num_used_by_curr = 0; + for _ in 0..num_negative + num_positive { + r.read_ue()?; // delta_poc_sX_minus1 + if r.read_bit()? { + num_used_by_curr += 1; // used_by_curr_pic_sX_flag + } + } + Ok(ShortTermRefPicSet { + num_negative, + num_positive, + num_used_by_curr, + }) + } + } +} + +/// The picture parameter set (7.3.2.3.1). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Pps { + /// `pps_pic_parameter_set_id`. + pub id: u32, + /// `pps_seq_parameter_set_id`. + pub sps_id: u32, + /// `dependent_slice_segments_enabled_flag`. + pub dependent_slice_segments_enabled: bool, + /// `output_flag_present_flag`. + pub output_flag_present: bool, + /// `num_extra_slice_header_bits`. + pub num_extra_slice_header_bits: u32, + /// `sign_data_hiding_enabled_flag`. + pub sign_data_hiding_enabled: bool, + /// `cabac_init_present_flag`. + pub cabac_init_present: bool, + /// `num_ref_idx_l0_default_active_minus1`. + pub num_ref_idx_l0_default_active_minus1: u32, + /// `num_ref_idx_l1_default_active_minus1`. + pub num_ref_idx_l1_default_active_minus1: u32, + /// `init_qp_minus26`. + pub init_qp_minus26: i32, + /// `constrained_intra_pred_flag`. + pub constrained_intra_pred: bool, + /// `transform_skip_enabled_flag`. + pub transform_skip_enabled: bool, + /// `cu_qp_delta_enabled_flag`. + pub cu_qp_delta_enabled: bool, + /// `diff_cu_qp_delta_depth`. + pub diff_cu_qp_delta_depth: u32, + /// `pps_cb_qp_offset`. + pub cb_qp_offset: i32, + /// `pps_cr_qp_offset`. + pub cr_qp_offset: i32, + /// `pps_slice_chroma_qp_offsets_present_flag`. + pub slice_chroma_qp_offsets_present: bool, + /// `weighted_pred_flag`. + pub weighted_pred: bool, + /// `weighted_bipred_flag`. + pub weighted_bipred: bool, + /// `transquant_bypass_enabled_flag`. + pub transquant_bypass_enabled: bool, + /// `tiles_enabled_flag`. + pub tiles_enabled: bool, + /// `entropy_coding_sync_enabled_flag` — wavefront parallel processing. + pub entropy_coding_sync_enabled: bool, + /// `num_tile_columns_minus1`. + pub num_tile_columns_minus1: u32, + /// `num_tile_rows_minus1`. + pub num_tile_rows_minus1: u32, + /// `uniform_spacing_flag`. + pub uniform_spacing: bool, + /// `loop_filter_across_tiles_enabled_flag`. + pub loop_filter_across_tiles_enabled: bool, + /// `pps_loop_filter_across_slices_enabled_flag`. + pub loop_filter_across_slices_enabled: bool, + /// `deblocking_filter_control_present_flag`. + pub deblocking_filter_control_present: bool, + /// `deblocking_filter_override_enabled_flag`. + pub deblocking_filter_override_enabled: bool, + /// `pps_deblocking_filter_disabled_flag`. + pub deblocking_filter_disabled: bool, + /// `pps_beta_offset_div2`. + pub beta_offset_div2: i32, + /// `pps_tc_offset_div2`. + pub tc_offset_div2: i32, + /// `lists_modification_present_flag`. + pub lists_modification_present: bool, + /// `log2_parallel_merge_level_minus2`. + pub log2_parallel_merge_level_minus2: u32, + /// `slice_segment_header_extension_present_flag`. + pub slice_segment_header_extension_present: bool, +} + +impl Default for Pps { + fn default() -> Self { + Pps { + id: 0, + sps_id: 0, + dependent_slice_segments_enabled: false, + output_flag_present: false, + num_extra_slice_header_bits: 0, + sign_data_hiding_enabled: false, + cabac_init_present: false, + num_ref_idx_l0_default_active_minus1: 0, + num_ref_idx_l1_default_active_minus1: 0, + init_qp_minus26: 0, + constrained_intra_pred: false, + transform_skip_enabled: false, + cu_qp_delta_enabled: false, + diff_cu_qp_delta_depth: 0, + cb_qp_offset: 0, + cr_qp_offset: 0, + slice_chroma_qp_offsets_present: false, + weighted_pred: false, + weighted_bipred: false, + transquant_bypass_enabled: false, + tiles_enabled: false, + entropy_coding_sync_enabled: false, + num_tile_columns_minus1: 0, + num_tile_rows_minus1: 0, + uniform_spacing: true, + loop_filter_across_tiles_enabled: true, + loop_filter_across_slices_enabled: true, + deblocking_filter_control_present: false, + deblocking_filter_override_enabled: false, + deblocking_filter_disabled: false, + beta_offset_div2: 0, + tc_offset_div2: 0, + lists_modification_present: false, + log2_parallel_merge_level_minus2: 0, + slice_segment_header_extension_present: false, + } + } +} + +impl Pps { + /// The RBSP, trailing bits included. + pub fn to_rbsp(&self) -> Vec { + let mut w = BitWriter::with_capacity(32); + w.write_ue(self.id); + w.write_ue(self.sps_id); + w.write_bit(self.dependent_slice_segments_enabled); + w.write_bit(self.output_flag_present); + w.write_bits(self.num_extra_slice_header_bits, 3); + w.write_bit(self.sign_data_hiding_enabled); + w.write_bit(self.cabac_init_present); + w.write_ue(self.num_ref_idx_l0_default_active_minus1); + w.write_ue(self.num_ref_idx_l1_default_active_minus1); + w.write_se(self.init_qp_minus26); + w.write_bit(self.constrained_intra_pred); + w.write_bit(self.transform_skip_enabled); + w.write_bit(self.cu_qp_delta_enabled); + if self.cu_qp_delta_enabled { + w.write_ue(self.diff_cu_qp_delta_depth); + } + w.write_se(self.cb_qp_offset); + w.write_se(self.cr_qp_offset); + w.write_bit(self.slice_chroma_qp_offsets_present); + w.write_bit(self.weighted_pred); + w.write_bit(self.weighted_bipred); + w.write_bit(self.transquant_bypass_enabled); + w.write_bit(self.tiles_enabled); + w.write_bit(self.entropy_coding_sync_enabled); + if self.tiles_enabled { + w.write_ue(self.num_tile_columns_minus1); + w.write_ue(self.num_tile_rows_minus1); + w.write_bit(self.uniform_spacing); + w.write_bit(self.loop_filter_across_tiles_enabled); + } + w.write_bit(self.loop_filter_across_slices_enabled); + w.write_bit(self.deblocking_filter_control_present); + if self.deblocking_filter_control_present { + w.write_bit(self.deblocking_filter_override_enabled); + w.write_bit(self.deblocking_filter_disabled); + if !self.deblocking_filter_disabled { + w.write_se(self.beta_offset_div2); + w.write_se(self.tc_offset_div2); + } + } + w.write_bit(false); // pps_scaling_list_data_present_flag + w.write_bit(self.lists_modification_present); + w.write_ue(self.log2_parallel_merge_level_minus2); + w.write_bit(self.slice_segment_header_extension_present); + w.write_bit(false); // pps_extension_present_flag + rbsp_trailing_bits(&mut w); + w.into_bytes() + } + + /// Parse a PPS RBSP. + pub fn parse(rbsp: &[u8]) -> Result { + let mut r = BitReader::new(rbsp); + let mut pps = Pps { + id: r.read_ue()?, + sps_id: r.read_ue()?, + ..Pps::default() + }; + pps.dependent_slice_segments_enabled = r.read_bit()?; + pps.output_flag_present = r.read_bit()?; + pps.num_extra_slice_header_bits = r.read_bits(3)?; + pps.sign_data_hiding_enabled = r.read_bit()?; + pps.cabac_init_present = r.read_bit()?; + pps.num_ref_idx_l0_default_active_minus1 = r.read_ue()?; + pps.num_ref_idx_l1_default_active_minus1 = r.read_ue()?; + pps.init_qp_minus26 = r.read_se()?; + pps.constrained_intra_pred = r.read_bit()?; + pps.transform_skip_enabled = r.read_bit()?; + pps.cu_qp_delta_enabled = r.read_bit()?; + if pps.cu_qp_delta_enabled { + pps.diff_cu_qp_delta_depth = r.read_ue()?; + } + pps.cb_qp_offset = r.read_se()?; + pps.cr_qp_offset = r.read_se()?; + pps.slice_chroma_qp_offsets_present = r.read_bit()?; + pps.weighted_pred = r.read_bit()?; + pps.weighted_bipred = r.read_bit()?; + pps.transquant_bypass_enabled = r.read_bit()?; + pps.tiles_enabled = r.read_bit()?; + pps.entropy_coding_sync_enabled = r.read_bit()?; + if pps.tiles_enabled { + pps.num_tile_columns_minus1 = r.read_ue()?; + pps.num_tile_rows_minus1 = r.read_ue()?; + pps.uniform_spacing = r.read_bit()?; + if !pps.uniform_spacing { + for _ in 0..pps.num_tile_columns_minus1 { + r.read_ue()?; + } + for _ in 0..pps.num_tile_rows_minus1 { + r.read_ue()?; + } + } + pps.loop_filter_across_tiles_enabled = r.read_bit()?; + } + pps.loop_filter_across_slices_enabled = r.read_bit()?; + pps.deblocking_filter_control_present = r.read_bit()?; + if pps.deblocking_filter_control_present { + pps.deblocking_filter_override_enabled = r.read_bit()?; + pps.deblocking_filter_disabled = r.read_bit()?; + if !pps.deblocking_filter_disabled { + pps.beta_offset_div2 = r.read_se()?; + pps.tc_offset_div2 = r.read_se()?; + } + } + if r.read_bit()? { + return Err(Error::unsupported( + "HEVC PPS scaling lists", + "this family codes with the flat 16 matrix only", + )); + } + pps.lists_modification_present = r.read_bit()?; + pps.log2_parallel_merge_level_minus2 = r.read_ue()?; + pps.slice_segment_header_extension_present = r.read_bit()?; + Ok(pps) + } +} + +/// `rbsp_trailing_bits()`: a one bit then zeros to the byte boundary. +pub fn rbsp_trailing_bits(w: &mut BitWriter) { + w.write_bit(true); + w.align_to_byte(); +} + +/// `Ceil( Log2( v ) )`, the width of a `u(v)` field counting `v` values. +pub fn ceil_log2(v: u32) -> u32 { + let mut bits = 0; + while (1u64 << bits) < u64::from(v) { + bits += 1; + } + bits +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::vui::{ColourDescription, VideoSignalType}; + + fn sample_sps() -> Sps { + Sps { + vps_id: 0, + id: 0, + chroma_format_idc: 1, + separate_colour_plane: false, + pic_width_in_luma_samples: 1920, + pic_height_in_luma_samples: 1088, + conf_win: ConformanceWindow { + left: 0, + right: 0, + top: 0, + bottom: 4, + }, + bit_depth_luma_minus8: 0, + bit_depth_chroma_minus8: 0, + log2_max_poc_lsb_minus4: 4, + max_dec_pic_buffering_minus1: 0, + max_num_reorder_pics: 0, + log2_min_cb_size_minus3: 0, + log2_diff_max_min_cb_size: 3, + log2_min_tb_size_minus2: 0, + log2_diff_max_min_tb_size: 3, + max_transform_hierarchy_depth_inter: 0, + max_transform_hierarchy_depth_intra: 0, + scaling_list_enabled: false, + amp_enabled: false, + sao_enabled: false, + pcm_enabled: false, + num_short_term_ref_pic_sets: 0, + long_term_ref_pics_present: false, + num_long_term_ref_pics_sps: 0, + temporal_mvp_enabled: false, + strong_intra_smoothing: true, + ptl: ProfileTierLevel::main(120), + vui: Some(VuiParameters { + sample_aspect_ratio: Some((1, 1)), + video_signal_type: Some(VideoSignalType { + video_format: 5, + video_full_range_flag: false, + colour_description: Some(ColourDescription { + colour_primaries: 1, + transfer_characteristics: 1, + matrix_coeffs: 1, + }), + }), + timing: Some((1, 30)), + }), + } + } + + #[test] + fn parameter_sets_round_trip() { + let vps = Vps { + id: 0, + ptl: ProfileTierLevel::main(120), + max_dec_pic_buffering_minus1: 0, + max_num_reorder_pics: 0, + }; + assert_eq!(Vps::parse(&vps.to_rbsp()).unwrap(), vps); + + let sps = sample_sps(); + let parsed = Sps::parse(&sps.to_rbsp()).unwrap(); + assert_eq!(parsed, sps); + // 1080 is cropped back out of the 1088 coded rows. + assert_eq!(parsed.display_size(), (1920, 1080)); + assert_eq!(parsed.ctb_size(), 64); + assert_eq!(parsed.pic_width_in_ctbs(), 30); + assert_eq!(parsed.pic_height_in_ctbs(), 17); + + let pps = Pps { + entropy_coding_sync_enabled: true, + init_qp_minus26: 1, + deblocking_filter_control_present: true, + deblocking_filter_disabled: true, + ..Pps::default() + }; + assert_eq!(Pps::parse(&pps.to_rbsp()).unwrap(), pps); + } + + #[test] + fn levels_round_up_with_size_and_rate() { + assert_eq!(ProfileTierLevel::level_for(1920, 1080, 30.0), 120); // 4 + assert_eq!(ProfileTierLevel::level_for(1920, 1080, 60.0), 123); // 4.1 + assert_eq!(ProfileTierLevel::level_for(3840, 2160, 30.0), 150); // 5 + assert_eq!(ProfileTierLevel::level_for(640, 480, 30.0), 90); // 3 + } + + #[test] + fn ceil_log2_counts_values() { + assert_eq!(ceil_log2(1), 0); + assert_eq!(ceil_log2(2), 1); + assert_eq!(ceil_log2(510), 9); + assert_eq!(ceil_log2(512), 9); + assert_eq!(ceil_log2(513), 10); + } +} diff --git a/crates/ec-h265-syntax/src/sei.rs b/crates/ec-h265-syntax/src/sei.rs new file mode 100644 index 00000000..de635dc0 --- /dev/null +++ b/crates/ec-h265-syntax/src/sei.rs @@ -0,0 +1,151 @@ +//! SEI messages: mastering display, content light level, decoded picture hash. +//! +//! Three messages, and each one is here because something downstream reads it. +//! The two HDR messages are what a tone map finds when the container lost its +//! metadata (see [`ec_core::color::hevc_sei_light`], which reads exactly these +//! payloads back). The decoded picture hash is the encoder's own oracle: an MD5 +//! of the reconstructed picture, which any conformant decoder must reproduce, so +//! a mismatch is a *bit-exactness* failure report rather than a mystery. + +use crate::md5::Md5; +use crate::nal::{NalHeader, NalUnitType}; +use crate::ps::rbsp_trailing_bits; +use ec_core::bitio::BitWriter; +use ec_core::color::ContentLight; + +/// `payloadType` values written here. +const PAYLOAD_MASTERING_DISPLAY: u32 = 137; +const PAYLOAD_CONTENT_LIGHT_LEVEL: u32 = 144; +const PAYLOAD_DECODED_PICTURE_HASH: u32 = 132; + +/// Build one SEI RBSP holding `messages`, each a `(payloadType, payload)` pair. +/// +/// The `ff` byte run for sizes over 254 is written the way the spec spells it, +/// even though nothing here comes close: a hash message is 49 bytes. +fn sei_rbsp(messages: &[(u32, Vec)]) -> Vec { + let mut w = BitWriter::with_capacity(64); + for (payload_type, payload) in messages { + let mut left = *payload_type; + while left >= 255 { + w.write_bits(0xff, 8); + left -= 255; + } + w.write_bits(left, 8); + let mut size = payload.len() as u32; + while size >= 255 { + w.write_bits(0xff, 8); + size -= 255; + } + w.write_bits(size, 8); + w.write_bytes(payload); + } + rbsp_trailing_bits(&mut w); + w.into_bytes() +} + +/// The prefix SEI RBSP describing HDR mastering metadata, or `None` when there +/// is nothing to say. +/// +/// Both messages are written whole or not at all: a `mastering_display_colour_volume` +/// with a zero luminance pair is what ffmpeg writes when it knows nothing, and a +/// tone map that believes it maps the film to black. +pub fn hdr_metadata_rbsp(light: ContentLight) -> Option> { + let mut messages = Vec::new(); + if let (Some(max), Some(min)) = (light.mastering_max, light.mastering_min) { + let mut payload = Vec::with_capacity(24); + // The chromaticities are not modelled by this family (the tone map wants + // the luminance pair), so BT.2020's are written: they are what an HDR + // grade is approved on, and a decoder that reads them gets a true answer + // rather than zeros. + const BT2020_PRIMARIES: [(u16, u16); 3] = + [(8500, 39_850), (6550, 2300), (35_400, 14_600)]; + const D65: (u16, u16) = (15_635, 16_450); + for (x, y) in BT2020_PRIMARIES { + payload.extend_from_slice(&x.to_be_bytes()); + payload.extend_from_slice(&y.to_be_bytes()); + } + payload.extend_from_slice(&D65.0.to_be_bytes()); + payload.extend_from_slice(&D65.1.to_be_bytes()); + payload.extend_from_slice(&((max * 10_000.0) as u32).to_be_bytes()); + payload.extend_from_slice(&((min * 10_000.0) as u32).to_be_bytes()); + messages.push((PAYLOAD_MASTERING_DISPLAY, payload)); + } + if let (Some(cll), Some(fall)) = (light.max_cll, light.max_fall) { + let mut payload = Vec::with_capacity(4); + payload.extend_from_slice(&(cll as u16).to_be_bytes()); + payload.extend_from_slice(&(fall as u16).to_be_bytes()); + messages.push((PAYLOAD_CONTENT_LIGHT_LEVEL, payload)); + } + if messages.is_empty() { + None + } else { + Some(sei_rbsp(&messages)) + } +} + +/// The suffix SEI RBSP carrying one MD5 per colour plane (D.2.20). +/// +/// `planes` are the *reconstructed* planes in coding order, each as +/// `(samples, stride, width, height)` over the whole coded picture — the +/// conformance window is not applied, because the hash is defined over +/// `pic_width_in_luma_samples`. +pub fn decoded_picture_hash_rbsp(planes: &[(&[u8], usize, usize, usize)]) -> Vec { + let mut payload = Vec::with_capacity(1 + 16 * planes.len()); + payload.push(0); // hash_type = MD5 + for &(data, stride, width, height) in planes { + let mut md5 = Md5::new(); + for y in 0..height { + md5.update(&data[y * stride..y * stride + width]); + } + payload.extend_from_slice(&md5.finish()); + } + sei_rbsp(&[(PAYLOAD_DECODED_PICTURE_HASH, payload)]) +} + +/// The NAL header a prefix SEI travels under. +pub fn prefix_sei_header() -> NalHeader { + NalHeader::new(NalUnitType::PrefixSei) +} + +/// The NAL header a suffix SEI (the picture hash) travels under. +pub fn suffix_sei_header() -> NalHeader { + NalHeader::new(NalUnitType::SuffixSei) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn hdr_sei_reads_back_through_ec_core() { + let light = ContentLight { + max_cll: Some(1000.0), + max_fall: Some(400.0), + mastering_max: Some(1000.0), + mastering_min: Some(0.005), + }; + let rbsp = hdr_metadata_rbsp(light).unwrap(); + let mut annex_b = Vec::new(); + crate::nal::write_annex_b(&mut annex_b, prefix_sei_header(), &rbsp, true); + // ec-core's reader is the consumer this exists for. + let read = ec_core::color::hevc_sei_light(&annex_b); + assert_eq!(read.max_cll, Some(1000.0)); + assert_eq!(read.max_fall, Some(400.0)); + assert_eq!(read.mastering_max, Some(1000.0)); + assert_eq!(read.mastering_min, Some(0.005)); + assert!(hdr_metadata_rbsp(ContentLight::default()).is_none()); + } + + #[test] + fn picture_hash_is_md5_of_each_plane() { + let luma = vec![7u8; 16 * 16]; + let rbsp = decoded_picture_hash_rbsp(&[(&luma, 16, 16, 16)]); + // payloadType 132, payloadSize 17, hash_type 0, then the digest. + assert_eq!(rbsp[0], 132); + assert_eq!(rbsp[1], 17); + assert_eq!(rbsp[2], 0); + let mut md5 = Md5::new(); + md5.update(&luma); + assert_eq!(&rbsp[3..19], &md5.finish()[..]); + } +} diff --git a/crates/ec-h265-syntax/src/slice.rs b/crates/ec-h265-syntax/src/slice.rs new file mode 100644 index 00000000..ba6f4044 --- /dev/null +++ b/crates/ec-h265-syntax/src/slice.rs @@ -0,0 +1,553 @@ +//! The slice segment header (7.3.6.1). + +use crate::nal::NalUnitType; +use crate::ps::{Pps, ShortTermRefPicSet, Sps, ceil_log2}; +use ec_core::bitio::{BitReader, BitWriter}; +use ec_core::error::{Error, Result}; + +/// `slice_type`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SliceType { + /// Bi-predictive. + B, + /// Predictive. + P, + /// Intra — the only kind this family's HEVC encoder writes. + I, +} + +impl SliceType { + /// The wire value (`B` = 0, `P` = 1, `I` = 2). + pub fn code(self) -> u32 { + match self { + SliceType::B => 0, + SliceType::P => 1, + SliceType::I => 2, + } + } + + /// The type for a wire value. + pub fn from_code(code: u32) -> Result { + match code { + 0 => Ok(SliceType::B), + 1 => Ok(SliceType::P), + 2 => Ok(SliceType::I), + v => Err(Error::corrupt(format!("HEVC slice: slice_type = {v}"))), + } + } +} + +/// A slice segment header, as far as an intra encoder writes one and a +/// stateless hardware decoder reads one. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SliceHeader { + /// `first_slice_segment_in_pic_flag`. + pub first_slice_segment_in_pic: bool, + /// `no_output_of_prior_pics_flag`, present on IRAP pictures only. + pub no_output_of_prior_pics: bool, + /// `slice_pic_parameter_set_id`. + pub pps_id: u32, + /// `dependent_slice_segment_flag`. + pub dependent_slice_segment: bool, + /// `slice_segment_address` in CTB raster order. + pub segment_address: u32, + /// `slice_type`. + pub slice_type: SliceType, + /// `pic_output_flag`, when the PPS says it is present. + pub pic_output_flag: bool, + /// `slice_pic_order_cnt_lsb`; absent (0) on IDR pictures. + pub poc_lsb: u32, + /// `slice_sao_luma_flag`. + pub sao_luma: bool, + /// `slice_sao_chroma_flag`. + pub sao_chroma: bool, + /// `num_ref_idx_l0_active_minus1` in force for this slice. + pub num_ref_idx_l0_active_minus1: u32, + /// `num_ref_idx_l1_active_minus1` in force for this slice. + pub num_ref_idx_l1_active_minus1: u32, + /// `mvd_l1_zero_flag`. + pub mvd_l1_zero: bool, + /// `cabac_init_flag`. + pub cabac_init: bool, + /// `slice_temporal_mvp_enabled_flag`. + pub temporal_mvp_enabled: bool, + /// `collocated_from_l0_flag`. + pub collocated_from_l0: bool, + /// `collocated_ref_idx`. + pub collocated_ref_idx: u32, + /// `five_minus_max_num_merge_cand`. + pub five_minus_max_num_merge_cand: u32, + /// `slice_qp_delta`: the slice QP is `26 + init_qp_minus26 + this`. + pub qp_delta: i32, + /// `slice_cb_qp_offset`. + pub cb_qp_offset: i32, + /// `slice_cr_qp_offset`. + pub cr_qp_offset: i32, + /// `slice_deblocking_filter_disabled_flag`, after any override. + pub deblocking_filter_disabled: bool, + /// `slice_beta_offset_div2`. + pub beta_offset_div2: i32, + /// `slice_tc_offset_div2`. + pub tc_offset_div2: i32, + /// `slice_loop_filter_across_slices_enabled_flag`. + pub loop_filter_across_slices_enabled: bool, + /// Substream entry points: one per WPP CTB row (or tile) after the first. + pub entry_point_offsets: Vec, +} + +impl SliceHeader { + /// An I slice covering a whole picture at `qp_delta`, filters off. + pub fn intra(pps: &Pps, qp_delta: i32) -> SliceHeader { + SliceHeader { + first_slice_segment_in_pic: true, + no_output_of_prior_pics: false, + pps_id: pps.id, + dependent_slice_segment: false, + segment_address: 0, + slice_type: SliceType::I, + pic_output_flag: true, + poc_lsb: 0, + sao_luma: false, + sao_chroma: false, + num_ref_idx_l0_active_minus1: 0, + num_ref_idx_l1_active_minus1: 0, + mvd_l1_zero: false, + cabac_init: false, + temporal_mvp_enabled: false, + collocated_from_l0: true, + collocated_ref_idx: 0, + five_minus_max_num_merge_cand: 0, + qp_delta, + cb_qp_offset: 0, + cr_qp_offset: 0, + deblocking_filter_disabled: pps.deblocking_filter_disabled, + beta_offset_div2: 0, + tc_offset_div2: 0, + loop_filter_across_slices_enabled: pps.loop_filter_across_slices_enabled, + entry_point_offsets: Vec::new(), + } + } + + /// Write the header, up to and including `byte_alignment()`. + /// + /// Entry point offsets are written from `self.entry_point_offsets`, so a WPP + /// encoder codes its substreams first and builds the header afterwards — + /// the offsets are not knowable any earlier. + pub fn write(&self, w: &mut BitWriter, sps: &Sps, pps: &Pps, nal_type: NalUnitType) { + w.write_bit(self.first_slice_segment_in_pic); + if nal_type.is_irap() { + w.write_bit(self.no_output_of_prior_pics); + } + w.write_ue(self.pps_id); + if !self.first_slice_segment_in_pic { + if pps.dependent_slice_segments_enabled { + w.write_bit(self.dependent_slice_segment); + } + w.write_bits(self.segment_address, sps.slice_address_bits()); + } + if !self.dependent_slice_segment { + for _ in 0..pps.num_extra_slice_header_bits { + w.write_bit(false); + } + w.write_ue(self.slice_type.code()); + if pps.output_flag_present { + w.write_bit(self.pic_output_flag); + } + if !nal_type.is_idr() { + w.write_bits(self.poc_lsb, sps.log2_max_poc_lsb_minus4 + 4); + // An intra encoder writes no reference picture sets at all; a + // non-IDR picture from this family does not exist yet. + w.write_bit(true); // short_term_ref_pic_set_sps_flag + if sps.num_short_term_ref_pic_sets > 1 { + w.write_bits(0, ceil_log2(sps.num_short_term_ref_pic_sets)); + } + if sps.temporal_mvp_enabled { + w.write_bit(self.temporal_mvp_enabled); + } + } + if sps.sao_enabled { + w.write_bit(self.sao_luma); + if sps.chroma_format_idc != 0 { + w.write_bit(self.sao_chroma); + } + } + if self.slice_type != SliceType::I { + w.write_bit(false); // num_ref_idx_active_override_flag + if self.slice_type == SliceType::B { + w.write_bit(self.mvd_l1_zero); + } + if pps.cabac_init_present { + w.write_bit(self.cabac_init); + } + w.write_ue(self.five_minus_max_num_merge_cand); + } + w.write_se(self.qp_delta); + if pps.slice_chroma_qp_offsets_present { + w.write_se(self.cb_qp_offset); + w.write_se(self.cr_qp_offset); + } + if pps.deblocking_filter_override_enabled { + w.write_bit(false); // deblocking_filter_override_flag + } + if pps.loop_filter_across_slices_enabled + && (self.sao_luma || self.sao_chroma || !self.deblocking_filter_disabled) + { + w.write_bit(self.loop_filter_across_slices_enabled); + } + } + if pps.tiles_enabled || pps.entropy_coding_sync_enabled { + w.write_ue(self.entry_point_offsets.len() as u32); + if !self.entry_point_offsets.is_empty() { + let max = self.entry_point_offsets.iter().copied().max().unwrap_or(1); + let offset_len = ceil_log2(max + 1).max(1); + w.write_ue(offset_len - 1); + for &offset in &self.entry_point_offsets { + w.write_bits(offset - 1, offset_len); + } + } + } + // byte_alignment(): a one bit then zeros. + w.write_bit(true); + w.align_to_byte(); + } + + /// Parse a slice segment header out of an unescaped slice NAL payload. + /// + /// Returns the header and the bit position where slice data begins — what + /// `VASliceParameterBufferHEVC::slice_data_byte_offset` is derived from. + pub fn parse( + rbsp: &[u8], + sps: &Sps, + pps: &Pps, + nal_type: NalUnitType, + ) -> Result<(SliceHeader, ParsePositions)> { + let mut r = BitReader::new(rbsp); + let mut h = SliceHeader::intra(pps, 0); + let mut pos = ParsePositions::default(); + h.first_slice_segment_in_pic = r.read_bit()?; + if nal_type.is_irap() { + h.no_output_of_prior_pics = r.read_bit()?; + } + h.pps_id = r.read_ue()?; + if !h.first_slice_segment_in_pic { + if pps.dependent_slice_segments_enabled { + h.dependent_slice_segment = r.read_bit()?; + } + h.segment_address = r.read_bits(sps.slice_address_bits())?; + } + if !h.dependent_slice_segment { + for _ in 0..pps.num_extra_slice_header_bits { + r.read_bit()?; + } + h.slice_type = SliceType::from_code(r.read_ue()?)?; + if pps.output_flag_present { + h.pic_output_flag = r.read_bit()?; + } + if sps.separate_colour_plane { + r.read_bits(2)?; // colour_plane_id + } + let mut st_rps = ShortTermRefPicSet::default(); + let mut num_long_term = 0; + if !nal_type.is_idr() { + h.poc_lsb = r.read_bits(sps.log2_max_poc_lsb_minus4 + 4)?; + let from_sps = r.read_bit()?; + let before = r.bit_position(); + if !from_sps { + // The sets in the SPS are not kept, so an inter-set + // predicted slice set cannot be resolved here. + st_rps = ShortTermRefPicSet::parse(&mut r, 0, &[])?; + } else if sps.num_short_term_ref_pic_sets > 1 { + r.read_bits(ceil_log2(sps.num_short_term_ref_pic_sets))?; + } + pos.st_rps_bits = (r.bit_position() - before) as u32; + if sps.long_term_ref_pics_present { + let num_long_term_sps = if sps.num_long_term_ref_pics_sps > 0 { + r.read_ue()? + } else { + 0 + }; + let num_long_term_pics = r.read_ue()?; + for i in 0..num_long_term_sps + num_long_term_pics { + if i < num_long_term_sps { + if sps.num_long_term_ref_pics_sps > 1 { + r.read_bits(ceil_log2(sps.num_long_term_ref_pics_sps))?; + } + num_long_term += 1; + } else { + r.read_bits(sps.log2_max_poc_lsb_minus4 + 4)?; // poc_lsb_lt + if r.read_bit()? { + num_long_term += 1; // used_by_curr_pic_lt_flag + } + } + if r.read_bit()? { + r.read_ue()?; // delta_poc_msb_cycle_lt + } + } + } + if sps.temporal_mvp_enabled { + h.temporal_mvp_enabled = r.read_bit()?; + } + } + if sps.sao_enabled { + h.sao_luma = r.read_bit()?; + if sps.chroma_format_idc != 0 { + h.sao_chroma = r.read_bit()?; + } + } + if h.slice_type != SliceType::I { + h.num_ref_idx_l0_active_minus1 = pps.num_ref_idx_l0_default_active_minus1; + h.num_ref_idx_l1_active_minus1 = pps.num_ref_idx_l1_default_active_minus1; + if r.read_bit()? { + h.num_ref_idx_l0_active_minus1 = r.read_ue()?; + if h.slice_type == SliceType::B { + h.num_ref_idx_l1_active_minus1 = r.read_ue()?; + } + } + let num_pic_total_curr = st_rps.num_used_by_curr + num_long_term; + if pps.lists_modification_present && num_pic_total_curr > 1 { + let bits = ceil_log2(num_pic_total_curr); + if r.read_bit()? { + for _ in 0..=h.num_ref_idx_l0_active_minus1 { + r.read_bits(bits)?; + } + } + if h.slice_type == SliceType::B && r.read_bit()? { + for _ in 0..=h.num_ref_idx_l1_active_minus1 { + r.read_bits(bits)?; + } + } + } + if h.slice_type == SliceType::B { + h.mvd_l1_zero = r.read_bit()?; + } + if pps.cabac_init_present { + h.cabac_init = r.read_bit()?; + } + if h.temporal_mvp_enabled { + if h.slice_type == SliceType::B { + h.collocated_from_l0 = r.read_bit()?; + } + if (h.collocated_from_l0 && h.num_ref_idx_l0_active_minus1 > 0) + || (!h.collocated_from_l0 && h.num_ref_idx_l1_active_minus1 > 0) + { + h.collocated_ref_idx = r.read_ue()?; + } + } + if (pps.weighted_pred && h.slice_type == SliceType::P) + || (pps.weighted_bipred && h.slice_type == SliceType::B) + { + skip_pred_weight_table(&mut r, &h, sps)?; + } + h.five_minus_max_num_merge_cand = r.read_ue()?; + } + h.qp_delta = r.read_se()?; + if pps.slice_chroma_qp_offsets_present { + h.cb_qp_offset = r.read_se()?; + h.cr_qp_offset = r.read_se()?; + } + h.deblocking_filter_disabled = pps.deblocking_filter_disabled; + h.beta_offset_div2 = pps.beta_offset_div2; + h.tc_offset_div2 = pps.tc_offset_div2; + if pps.deblocking_filter_override_enabled && r.read_bit()? { + h.deblocking_filter_disabled = r.read_bit()?; + if !h.deblocking_filter_disabled { + h.beta_offset_div2 = r.read_se()?; + h.tc_offset_div2 = r.read_se()?; + } + } + h.loop_filter_across_slices_enabled = pps.loop_filter_across_slices_enabled; + if pps.loop_filter_across_slices_enabled + && (h.sao_luma || h.sao_chroma || !h.deblocking_filter_disabled) + { + h.loop_filter_across_slices_enabled = r.read_bit()?; + } + } + if pps.tiles_enabled || pps.entropy_coding_sync_enabled { + let count = r.read_ue()?; + if count > 0 { + if count as u64 > sps.pic_height_in_ctbs() as u64 * sps.pic_width_in_ctbs() as u64 { + return Err(Error::corrupt("HEVC slice: num_entry_point_offsets absurd")); + } + let offset_len = r.read_ue()? + 1; + if offset_len > 32 { + return Err(Error::corrupt("HEVC slice: offset_len_minus1 > 31")); + } + for _ in 0..count { + h.entry_point_offsets.push(r.read_bits(offset_len)? + 1); + } + } + } + if pps.slice_segment_header_extension_present { + let len = r.read_ue()?; + for _ in 0..len { + r.read_bits(8)?; + } + } + // byte_alignment() + if !r.read_bit()? { + return Err(Error::corrupt("HEVC slice: alignment_bit_equal_to_one = 0")); + } + r.align_to_byte(); + pos.header_bits = r.bit_position(); + Ok((h, pos)) + } +} + +/// Where the slice header ended, in the units a hardware decoder wants. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct ParsePositions { + /// Bit position in the *unescaped* RBSP where slice data starts; always a + /// multiple of 8. + pub header_bits: u64, + /// `st_rps_bits`: the size of the `st_ref_pic_set()` in the slice header, + /// which `VAPictureParameterBufferHEVC` carries so the driver can skip it. + pub st_rps_bits: u32, +} + +impl ParsePositions { + /// `slice_data_byte_offset`: the offset from the start of the NAL unit + /// (header bytes included) to the first byte of slice data, counted in the + /// *escaped* bytes a driver is handed. + /// + /// The emulation prevention bytes inside the header count, which is why this + /// takes the escaped payload rather than working from `header_bits` alone. + pub fn slice_data_byte_offset(&self, escaped_payload: &[u8]) -> usize { + let rbsp_bytes = (self.header_bits / 8) as usize; + let mut zeros = 0usize; + let mut rbsp_seen = 0usize; + let mut escaped_seen = 0usize; + for &b in escaped_payload { + escaped_seen += 1; + if zeros >= 2 && b == 3 { + zeros = 0; + continue; + } + rbsp_seen += 1; + if b == 0 { + zeros += 1; + } else { + zeros = 0; + } + if rbsp_seen == rbsp_bytes { + break; + } + } + // 2 = the NAL unit header, which the offset is measured from. + 2 + escaped_seen + } +} + +/// Walk past a `pred_weight_table()` (7.3.6.3). +fn skip_pred_weight_table(r: &mut BitReader, h: &SliceHeader, sps: &Sps) -> Result<()> { + r.read_ue()?; // luma_log2_weight_denom + let chroma = sps.chroma_format_idc != 0; + if chroma { + r.read_se()?; // delta_chroma_log2_weight_denom + } + let lists: &[u32] = if h.slice_type == SliceType::B { + &[h.num_ref_idx_l0_active_minus1, h.num_ref_idx_l1_active_minus1] + } else { + &[h.num_ref_idx_l0_active_minus1] + }; + for &active_minus1 in lists { + let count = active_minus1 + 1; + let mut luma_flags = Vec::with_capacity(count as usize); + for _ in 0..count { + luma_flags.push(r.read_bit()?); + } + let mut chroma_flags = Vec::with_capacity(count as usize); + if chroma { + for _ in 0..count { + chroma_flags.push(r.read_bit()?); + } + } + for i in 0..count as usize { + if luma_flags[i] { + r.read_se()?; // delta_luma_weight + r.read_se()?; // luma_offset + } + if chroma && chroma_flags[i] { + for _ in 0..2 { + r.read_se()?; // delta_chroma_weight + r.read_se()?; // delta_chroma_offset + } + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::ps::{ConformanceWindow, ProfileTierLevel}; + + fn sps() -> Sps { + Sps { + vps_id: 0, + id: 0, + chroma_format_idc: 1, + separate_colour_plane: false, + pic_width_in_luma_samples: 1920, + pic_height_in_luma_samples: 1088, + conf_win: ConformanceWindow::default(), + bit_depth_luma_minus8: 0, + bit_depth_chroma_minus8: 0, + log2_max_poc_lsb_minus4: 4, + max_dec_pic_buffering_minus1: 0, + max_num_reorder_pics: 0, + log2_min_cb_size_minus3: 0, + log2_diff_max_min_cb_size: 3, + log2_min_tb_size_minus2: 0, + log2_diff_max_min_tb_size: 3, + max_transform_hierarchy_depth_inter: 0, + max_transform_hierarchy_depth_intra: 0, + scaling_list_enabled: false, + amp_enabled: false, + sao_enabled: false, + pcm_enabled: false, + num_short_term_ref_pic_sets: 0, + long_term_ref_pics_present: false, + num_long_term_ref_pics_sps: 0, + temporal_mvp_enabled: false, + strong_intra_smoothing: true, + ptl: ProfileTierLevel::main(120), + vui: None, + } + } + + #[test] + fn intra_slice_header_round_trips_with_entry_points() { + let pps = Pps { + entropy_coding_sync_enabled: true, + deblocking_filter_control_present: true, + deblocking_filter_disabled: true, + ..Pps::default() + }; + let sps = sps(); + let mut header = SliceHeader::intra(&pps, -3); + header.entry_point_offsets = vec![1234, 9, 65_540]; + let mut w = BitWriter::new(); + header.write(&mut w, &sps, &pps, NalUnitType::IdrWRadl); + let rbsp = w.into_bytes(); + let (parsed, pos) = SliceHeader::parse(&rbsp, &sps, &pps, NalUnitType::IdrWRadl).unwrap(); + assert_eq!(parsed, header); + assert_eq!(pos.header_bits % 8, 0); + assert_eq!(pos.header_bits as usize / 8, rbsp.len()); + // No emulation prevention in this header, so the byte offset is the + // NAL header plus the RBSP header bytes. + assert_eq!(pos.slice_data_byte_offset(&rbsp), 2 + rbsp.len()); + } + + #[test] + fn byte_offset_counts_escape_bytes() { + // RBSP 00 00 01 ... escapes to 00 00 03 01 ...; a header of four RBSP + // bytes therefore ends five escaped bytes in. + let pos = ParsePositions { + header_bits: 4 * 8, + st_rps_bits: 0, + }; + let escaped = [0u8, 0, 3, 1, 0xff]; + assert_eq!(pos.slice_data_byte_offset(&escaped), 2 + 5); + } +} diff --git a/crates/ec-h265-syntax/src/vui.rs b/crates/ec-h265-syntax/src/vui.rs new file mode 100644 index 00000000..713f2542 --- /dev/null +++ b/crates/ec-h265-syntax/src/vui.rs @@ -0,0 +1,288 @@ +//! VUI parameters — the part of an SPS that says what the samples *mean*. + +use ec_core::bitio::{BitReader, BitWriter}; +use ec_core::color::ColorDescription; +use ec_core::error::Result; + +/// `colour_primaries`, `transfer_characteristics`, `matrix_coeffs` (H.273 code +/// points), carried verbatim. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct ColourDescription { + /// `colour_primaries`: 1 = BT.709, 9 = BT.2020. + pub colour_primaries: u8, + /// `transfer_characteristics`: 1 = BT.709, 16 = PQ, 18 = HLG. + pub transfer_characteristics: u8, + /// `matrix_coeffs`: 1 = BT.709, 9 = BT.2020 non-constant luminance. + pub matrix_coeffs: u8, +} + +impl ColourDescription { + /// The three code points a [`ColorDescription`] resolves to. + /// + /// This is the bridge that keeps the bitstream and the container from + /// drifting apart: both sides come from the same H.273 resolution in + /// [`ec_core::color`]. + pub fn from_color(color: ColorDescription) -> ColourDescription { + let (primaries, transfer, matrix) = color.codes(); + ColourDescription { + colour_primaries: primaries as u8, + transfer_characteristics: transfer as u8, + matrix_coeffs: matrix as u8, + } + } +} + +/// `video_signal_type` and the colour description under it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct VideoSignalType { + /// The analogue system a picture came off; 5 ("unspecified") for anything + /// this family encodes, because none of it did. + pub video_format: u8, + /// False = limited range (16..235), true = full range. + pub video_full_range_flag: bool, + /// The H.273 code points, when stated. + pub colour_description: Option, +} + +impl Default for VideoSignalType { + fn default() -> Self { + VideoSignalType { + video_format: 5, + video_full_range_flag: false, + colour_description: None, + } + } +} + +/// The VUI fields this family writes and reads (E.2.1). +/// +/// Everything absent here is written as "not present"; an HRD block in +/// particular is deliberately never written, since nothing downstream reads one +/// and a wrong one is worse than none. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct VuiParameters { + /// Sample aspect ratio as `aspect_ratio_idc`, or `Some((w, h))` for the + /// extended form. + pub sample_aspect_ratio: Option<(u16, u16)>, + /// What the samples mean. + pub video_signal_type: Option, + /// `(num_units_in_tick, time_scale)`: a rational frame rate, exact. + pub timing: Option<(u32, u32)>, +} + +impl VuiParameters { + /// Write `vui_parameters()`. + pub fn write(&self, w: &mut BitWriter) { + match self.sample_aspect_ratio { + Some((sw, sh)) => { + w.write_bit(true); + w.write_bits(255, 8); // EXTENDED_SAR + w.write_bits(u32::from(sw), 16); + w.write_bits(u32::from(sh), 16); + } + None => w.write_bit(false), + } + w.write_bit(false); // overscan_info_present_flag + match self.video_signal_type { + Some(vst) => { + w.write_bit(true); + w.write_bits(u32::from(vst.video_format), 3); + w.write_bit(vst.video_full_range_flag); + match vst.colour_description { + Some(cd) => { + w.write_bit(true); + w.write_bits(u32::from(cd.colour_primaries), 8); + w.write_bits(u32::from(cd.transfer_characteristics), 8); + w.write_bits(u32::from(cd.matrix_coeffs), 8); + } + None => w.write_bit(false), + } + } + None => w.write_bit(false), + } + w.write_bit(false); // chroma_loc_info_present_flag + w.write_bit(false); // neutral_chroma_indication_flag + w.write_bit(false); // field_seq_flag + w.write_bit(false); // frame_field_info_present_flag + w.write_bit(false); // default_display_window_flag + match self.timing { + Some((units, scale)) => { + w.write_bit(true); + w.write_bits(units, 32); + w.write_bits(scale, 32); + w.write_bit(false); // vui_poc_proportional_to_timing_flag + w.write_bit(false); // vui_hrd_parameters_present_flag + } + None => w.write_bit(false), + } + w.write_bit(false); // bitstream_restriction_flag + } + + /// Parse `vui_parameters()`, skipping past the parts not modelled. + pub fn parse(r: &mut BitReader, max_sub_layers_minus1: u32) -> Result { + let mut vui = VuiParameters::default(); + if r.read_bit()? { + let idc = r.read_bits(8)?; + if idc == 255 { + let sw = r.read_bits(16)? as u16; + let sh = r.read_bits(16)? as u16; + vui.sample_aspect_ratio = Some((sw, sh)); + } + } + if r.read_bit()? { + r.read_bit()?; // overscan_appropriate_flag + } + if r.read_bit()? { + let video_format = r.read_bits(3)? as u8; + let video_full_range_flag = r.read_bit()?; + let colour_description = if r.read_bit()? { + Some(ColourDescription { + colour_primaries: r.read_bits(8)? as u8, + transfer_characteristics: r.read_bits(8)? as u8, + matrix_coeffs: r.read_bits(8)? as u8, + }) + } else { + None + }; + vui.video_signal_type = Some(VideoSignalType { + video_format, + video_full_range_flag, + colour_description, + }); + } + if r.read_bit()? { + r.read_ue()?; + r.read_ue()?; + } + r.read_bit()?; // neutral_chroma_indication_flag + r.read_bit()?; // field_seq_flag + r.read_bit()?; // frame_field_info_present_flag + if r.read_bit()? { + for _ in 0..4 { + r.read_ue()?; + } + } + if r.read_bit()? { + let units = r.read_bits(32)?; + let scale = r.read_bits(32)?; + vui.timing = Some((units, scale)); + if r.read_bit()? { + r.read_ue()?; + } + if r.read_bit()? { + skip_hrd_parameters(r, true, max_sub_layers_minus1)?; + } + } + if r.read_bit()? { + r.read_bit()?; + r.read_bit()?; + r.read_bit()?; + for _ in 0..5 { + r.read_ue()?; + } + } + Ok(vui) + } +} + +/// Walk past an `hrd_parameters()` block (E.2.2) without modelling it. +fn skip_hrd_parameters( + r: &mut BitReader, + common_inf_present: bool, + max_sub_layers_minus1: u32, +) -> Result<()> { + let mut nal_hrd = false; + let mut vcl_hrd = false; + let mut sub_pic_hrd = false; + if common_inf_present { + nal_hrd = r.read_bit()?; + vcl_hrd = r.read_bit()?; + if nal_hrd || vcl_hrd { + sub_pic_hrd = r.read_bit()?; + if sub_pic_hrd { + r.read_bits(8)?; // tick_divisor_minus2 + r.read_bits(5)?; // du_cpb_removal_delay_increment_length_minus1 + r.read_bit()?; // sub_pic_cpb_params_in_pic_timing_sei_flag + r.read_bits(5)?; // dpb_output_delay_du_length_minus1 + } + r.read_bits(4)?; // bit_rate_scale + r.read_bits(4)?; // cpb_size_scale + if sub_pic_hrd { + r.read_bits(4)?; // cpb_size_du_scale + } + r.read_bits(5)?; // initial_cpb_removal_delay_length_minus1 + r.read_bits(5)?; // au_cpb_removal_delay_length_minus1 + r.read_bits(5)?; // dpb_output_delay_length_minus1 + } + } + for _ in 0..=max_sub_layers_minus1 { + let fixed_pic_rate_general = r.read_bit()?; + let mut fixed_pic_rate_within_cvs = fixed_pic_rate_general; + if !fixed_pic_rate_general { + fixed_pic_rate_within_cvs = r.read_bit()?; + } + let mut low_delay = false; + if fixed_pic_rate_within_cvs { + r.read_ue()?; // elemental_duration_in_tc_minus1 + } else { + low_delay = r.read_bit()?; + } + let mut cpb_cnt = 1u32; + if !low_delay { + cpb_cnt = r.read_ue()? + 1; + } + for present in [nal_hrd, vcl_hrd] { + if !present { + continue; + } + for _ in 0..cpb_cnt { + r.read_ue()?; // bit_rate_value_minus1 + r.read_ue()?; // cpb_size_value_minus1 + if sub_pic_hrd { + r.read_ue()?; // cpb_size_du_value_minus1 + r.read_ue()?; // bit_rate_du_value_minus1 + } + r.read_bit()?; // cbr_flag + } + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn vui_round_trips() { + let vui = VuiParameters { + sample_aspect_ratio: Some((1, 1)), + video_signal_type: Some(VideoSignalType { + video_format: 5, + video_full_range_flag: false, + colour_description: Some(ColourDescription { + colour_primaries: 1, + transfer_characteristics: 1, + matrix_coeffs: 1, + }), + }), + timing: Some((1001, 60_000)), + }; + let mut w = BitWriter::new(); + vui.write(&mut w); + w.align_to_byte(); + let bytes = w.into_bytes(); + let mut r = BitReader::new(&bytes); + assert_eq!(VuiParameters::parse(&mut r, 0).unwrap(), vui); + + // Every export this family writes declares itself SDR: 709 above 720 + // lines and 601 below, which is the rule ec-core states, not a guess + // made here. + for height in [1080, 2160] { + let cd = ColourDescription::from_color(ColorDescription::output(height)); + assert_eq!((cd.colour_primaries, cd.transfer_characteristics, cd.matrix_coeffs), (1, 1, 1)); + } + let cd = ColourDescription::from_color(ColorDescription::output(480)); + assert_eq!((cd.colour_primaries, cd.matrix_coeffs), (6, 6)); + } +}