forge
Explore
Log in

Don't you dare go Hollow

NAL framing, parameter sets, slice headers and SEI

Browse files at this commit

0d07f18e8d00c75c474c01e522adfb6865a15358Ahmet Kaan GümüşParent: a132a9d
  • feat
    • NAL framing, parameter sets, slice headers and SEI
Show full message
feat(h265-syntax): NAL framing, parameter sets, slice headers and SEI

Writers and parsers for the same structures, so a round trip is a test
rather than an article of faith. Sized by what a stateless hardware
decoder asks for: every field of VAPictureParameterBufferHEVC and
VASliceParameterBufferHEVC is a field here or a named method on one.

The conformance window is first class - 1920x1080 codes as 1920x1088 and
crops - and the slice header hands back where the data starts, escape
bytes counted, which is what slice_data_byte_offset means.
Cargo.tomlmodified+1 -0
@@ -14,6 +14,7 @@ ec-av1-syntax = { path = "crates/ec-av1-syntax", version = "0.1.0" }
14 ec-core = { path = "crates/ec-core", version = "0.1.0" }14 ec-core = { path = "crates/ec-core", version = "0.1.0" }
15 ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" }15 ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" }
16 ec-h264-syntax = { path = "crates/ec-h264-syntax", version = "0.1.0" }16 ec-h264-syntax = { path = "crates/ec-h264-syntax", version = "0.1.0" }
17+ec-h265-syntax = { path = "crates/ec-h265-syntax", version = "0.1.0" }
17 ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" }18 ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" }
18 ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" }19 ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" }
19 ec-mp3 = { path = "crates/ec-mp3", version = "0.1.0" }20 ec-mp3 = { path = "crates/ec-mp3", version = "0.1.0" }
crates/ec-h265-syntax/Cargo.tomladded+10 -0
@@ -0,0 +1,10 @@
1+[package]
2+name = "ec-h265-syntax"
3+description = "HEVC (H.265) NAL framing, parameter sets, slice headers and SEI — written and parsed."
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+
9+[dependencies]
10+ec-core.workspace = true
crates/ec-h265-syntax/src/lib.rsadded+41 -0
@@ -0,0 +1,41 @@
1+//! HEVC bitstream syntax: NAL framing, parameter sets, slice headers, SEI.
2+//!
3+//! This crate is the half of H.265 that both a software encoder and a *stateless
4+//! hardware* decoder need, and it is deliberately the same code for both
5+//! directions: every structure here is written and parsed, so a round trip is a
6+//! test rather than an article of faith.
7+//!
8+//! What that buys, concretely:
9+//!
10+//! - The conformance window is a field on [`Sps`], not a caller's padding
11+//! problem. 1920x1080 in 64x64 coding tree blocks is coded 1920x1088 and
12+//! cropped by the SPS; [`Sps::display_size`] gives back what a player shows.
13+//! - Every field of `VAPictureParameterBufferHEVC` and
14+//! `VASliceParameterBufferHEVC` is either a field on [`Sps`], [`Pps`] or
15+//! [`SliceHeader`], or a named method on one of them —
16+//! [`Sps::pic_width_in_ctbs`], [`ParsePositions::slice_data_byte_offset`],
17+//! [`ParsePositions::st_rps_bits`]. A hardware decode path built on this crate
18+//! should never need to re-parse a header itself.
19+//! - [`sei::decoded_picture_hash_rbsp`] writes the MD5 of the reconstruction, so
20+//! any conformant decoder can be asked whether the encoder was right.
21+//!
22+//! Malformed input is an [`Error`](ec_core::Error), never a panic: truncation is
23+//! `NeedMore`, a rule violation is `Corrupt`, and the two constructs the family
24+//! genuinely does not implement (scaling lists, and short-term reference picture
25+//! sets predicted from an SPS set that a caller did not keep) are `Unsupported`
26+//! with the reason stated.
27+
28+#![forbid(unsafe_code)]
29+#![warn(missing_docs)]
30+
31+mod md5;
32+pub mod nal;
33+pub mod ps;
34+pub mod sei;
35+pub mod slice;
36+pub mod vui;
37+
38+pub use nal::{AnnexBNal, NalHeader, NalUnitType, escape_rbsp, split_annex_b, unescape_rbsp};
39+pub use ps::{ConformanceWindow, Pps, ProfileTierLevel, ShortTermRefPicSet, Sps, Vps};
40+pub use slice::{ParsePositions, SliceHeader, SliceType};
41+pub use vui::{ColourDescription, VideoSignalType, VuiParameters};
crates/ec-h265-syntax/src/md5.rsadded+181 -0
@@ -0,0 +1,181 @@
1+//! MD5 (IETF RFC 1321), for the decoded picture hash SEI and nothing else.
2+//!
3+//! Not a security primitive and not offered as one: the spec names MD5 as the
4+//! picture hash, so this exists to reproduce that one number.
5+
6+/// `K[i] = floor(2^32 * abs(sin(i + 1)))`, RFC 1321 section 3.4.
7+const K: [u32; 64] = [
8+ 0xd76a_a478, 0xe8c7_b756, 0x2420_70db, 0xc1bd_ceee, 0xf57c_0faf, 0x4787_c62a, 0xa830_4613,
9+ 0xfd46_9501, 0x6980_98d8, 0x8b44_f7af, 0xffff_5bb1, 0x895c_d7be, 0x6b90_1122, 0xfd98_7193,
10+ 0xa679_438e, 0x49b4_0821, 0xf61e_2562, 0xc040_b340, 0x265e_5a51, 0xe9b6_c7aa, 0xd62f_105d,
11+ 0x0244_1453, 0xd8a1_e681, 0xe7d3_fbc8, 0x21e1_cde6, 0xc337_07d6, 0xf4d5_0d87, 0x455a_14ed,
12+ 0xa9e3_e905, 0xfcef_a3f8, 0x676f_02d9, 0x8d2a_4c8a, 0xfffa_3942, 0x8771_f681, 0x6d9d_6122,
13+ 0xfde5_380c, 0xa4be_ea44, 0x4bde_cfa9, 0xf6bb_4b60, 0xbebf_bc70, 0x289b_7ec6, 0xeaa1_27fa,
14+ 0xd4ef_3085, 0x0488_1d05, 0xd9d4_d039, 0xe6db_99e5, 0x1fa2_7cf8, 0xc4ac_5665, 0xf429_2244,
15+ 0x432a_ff97, 0xab94_23a7, 0xfc93_a039, 0x655b_59c3, 0x8f0c_cc92, 0xffef_f47d, 0x8584_5dd1,
16+ 0x6fa8_7e4f, 0xfe2c_e6e0, 0xa301_4314, 0x4e08_11a1, 0xf753_7e82, 0xbd3a_f235, 0x2ad7_d2bb,
17+ 0xeb86_d391,
18+];
19+
20+/// Per-round left rotation amounts.
21+const S: [u32; 64] = [
22+ 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,
23+ 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,
24+ 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21,
25+];
26+
27+/// Streaming MD5 state.
28+pub struct Md5 {
29+ state: [u32; 4],
30+ buffer: [u8; 64],
31+ buffered: usize,
32+ length: u64,
33+}
34+
35+impl Md5 {
36+ /// A fresh context.
37+ pub fn new() -> Md5 {
38+ Md5 {
39+ state: [0x6745_2301, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476],
40+ buffer: [0; 64],
41+ buffered: 0,
42+ length: 0,
43+ }
44+ }
45+
46+ /// Absorb more bytes.
47+ pub fn update(&mut self, mut data: &[u8]) {
48+ self.length = self.length.wrapping_add(data.len() as u64);
49+ if self.buffered > 0 {
50+ let take = (64 - self.buffered).min(data.len());
51+ self.buffer[self.buffered..self.buffered + take].copy_from_slice(&data[..take]);
52+ self.buffered += take;
53+ data = &data[take..];
54+ if self.buffered == 64 {
55+ let block = self.buffer;
56+ self.compress(&block);
57+ self.buffered = 0;
58+ }
59+ // The partial block is still filling; leaving now keeps it, where
60+ // falling through would overwrite `buffered` with an empty tail.
61+ if data.is_empty() {
62+ return;
63+ }
64+ }
65+ let mut chunks = data.chunks_exact(64);
66+ for block in &mut chunks {
67+ let mut b = [0u8; 64];
68+ b.copy_from_slice(block);
69+ self.compress(&b);
70+ }
71+ let rest = chunks.remainder();
72+ self.buffer[..rest.len()].copy_from_slice(rest);
73+ self.buffered = rest.len();
74+ }
75+
76+ /// The 16-byte digest.
77+ pub fn finish(mut self) -> [u8; 16] {
78+ let bit_len = self.length.wrapping_mul(8);
79+ self.update(&[0x80]);
80+ // update() counted the padding byte; the length is already captured.
81+ while self.buffered != 56 {
82+ self.update(&[0]);
83+ }
84+ let mut block = self.buffer;
85+ block[56..].copy_from_slice(&bit_len.to_le_bytes());
86+ self.compress(&block);
87+ let mut out = [0u8; 16];
88+ for (i, word) in self.state.iter().enumerate() {
89+ out[i * 4..i * 4 + 4].copy_from_slice(&word.to_le_bytes());
90+ }
91+ out
92+ }
93+
94+ fn compress(&mut self, block: &[u8; 64]) {
95+ let mut m = [0u32; 16];
96+ for (i, word) in m.iter_mut().enumerate() {
97+ *word = u32::from_le_bytes([
98+ block[i * 4],
99+ block[i * 4 + 1],
100+ block[i * 4 + 2],
101+ block[i * 4 + 3],
102+ ]);
103+ }
104+ let [mut a, mut b, mut c, mut d] = self.state;
105+ for i in 0..64 {
106+ let (f, g) = match i / 16 {
107+ 0 => ((b & c) | (!b & d), i),
108+ 1 => ((d & b) | (!d & c), (5 * i + 1) % 16),
109+ 2 => (b ^ c ^ d, (3 * i + 5) % 16),
110+ _ => (c ^ (b | !d), (7 * i) % 16),
111+ };
112+ let tmp = d;
113+ d = c;
114+ c = b;
115+ b = b.wrapping_add(
116+ a.wrapping_add(f)
117+ .wrapping_add(K[i])
118+ .wrapping_add(m[g])
119+ .rotate_left(S[i]),
120+ );
121+ a = tmp;
122+ }
123+ self.state[0] = self.state[0].wrapping_add(a);
124+ self.state[1] = self.state[1].wrapping_add(b);
125+ self.state[2] = self.state[2].wrapping_add(c);
126+ self.state[3] = self.state[3].wrapping_add(d);
127+ }
128+}
129+
130+impl Default for Md5 {
131+ fn default() -> Self {
132+ Md5::new()
133+ }
134+}
135+
136+#[cfg(test)]
137+mod tests {
138+ use super::*;
139+
140+ fn hex(digest: [u8; 16]) -> String {
141+ digest.iter().map(|b| format!("{b:02x}")).collect()
142+ }
143+
144+ fn md5(data: &[u8]) -> String {
145+ let mut m = Md5::new();
146+ m.update(data);
147+ hex(m.finish())
148+ }
149+
150+ #[test]
151+ fn rfc1321_test_suite() {
152+ assert_eq!(md5(b""), "d41d8cd98f00b204e9800998ecf8427e");
153+ assert_eq!(md5(b"a"), "0cc175b9c0f1b6a831c399e269772661");
154+ assert_eq!(md5(b"abc"), "900150983cd24fb0d6963f7d28e17f72");
155+ assert_eq!(md5(b"message digest"), "f96b697d7cb7938d525a2f31aaf161d0");
156+ assert_eq!(
157+ md5(b"abcdefghijklmnopqrstuvwxyz"),
158+ "c3fcd3d76192e4007dfb496cca67e13b"
159+ );
160+ assert_eq!(
161+ md5(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"),
162+ "d174ab98d277d9f5a5611c2c9f419d9f"
163+ );
164+ assert_eq!(
165+ md5(b"12345678901234567890123456789012345678901234567890123456789012345678901234567890"),
166+ "57edf4a22be3c955ac49da2e2107b67a"
167+ );
168+ }
169+
170+ #[test]
171+ fn chunked_updates_match_one_shot() {
172+ let data: Vec<u8> = (0..1000u32).map(|i| (i * 7) as u8).collect();
173+ let mut whole = Md5::new();
174+ whole.update(&data);
175+ let mut split = Md5::new();
176+ for chunk in data.chunks(7) {
177+ split.update(chunk);
178+ }
179+ assert_eq!(whole.finish(), split.finish());
180+ }
181+}
crates/ec-h265-syntax/src/nal.rsadded+335 -0
@@ -0,0 +1,335 @@
1+//! NAL units: the two-byte header, RBSP escaping and Annex-B framing.
2+
3+use ec_core::error::{Error, Result};
4+
5+/// `nal_unit_type` values this family names (Table 7-1).
6+///
7+/// The numeric value is the wire value; unnamed types travel as
8+/// [`NalUnitType::Other`] rather than being refused, because a parser that
9+/// cannot skip a NAL it does not know is a parser that breaks on the next
10+/// extension.
11+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12+pub enum NalUnitType {
13+ /// Coded slice of a non-TSA, non-STSA trailing picture (sub-layer non-ref).
14+ TrailN,
15+ /// Coded slice of a non-TSA, non-STSA trailing picture (reference).
16+ TrailR,
17+ /// Coded slice of an IDR picture that may have leading RADL pictures.
18+ IdrWRadl,
19+ /// Coded slice of an IDR picture with no leading pictures.
20+ IdrNLp,
21+ /// Coded slice of a CRA picture.
22+ CraNut,
23+ /// Video parameter set.
24+ Vps,
25+ /// Sequence parameter set.
26+ Sps,
27+ /// Picture parameter set.
28+ Pps,
29+ /// Access unit delimiter.
30+ Aud,
31+ /// End of sequence.
32+ EosNut,
33+ /// End of bitstream.
34+ EobNut,
35+ /// Filler data.
36+ FdNut,
37+ /// SEI that precedes the pictures it describes.
38+ PrefixSei,
39+ /// SEI that follows them — where the decoded picture hash lives.
40+ SuffixSei,
41+ /// Anything else, carried verbatim.
42+ Other(u8),
43+}
44+
45+impl NalUnitType {
46+ /// The wire value.
47+ pub fn code(self) -> u8 {
48+ match self {
49+ NalUnitType::TrailN => 0,
50+ NalUnitType::TrailR => 1,
51+ NalUnitType::IdrWRadl => 19,
52+ NalUnitType::IdrNLp => 20,
53+ NalUnitType::CraNut => 21,
54+ NalUnitType::Vps => 32,
55+ NalUnitType::Sps => 33,
56+ NalUnitType::Pps => 34,
57+ NalUnitType::Aud => 35,
58+ NalUnitType::EosNut => 36,
59+ NalUnitType::EobNut => 37,
60+ NalUnitType::FdNut => 38,
61+ NalUnitType::PrefixSei => 39,
62+ NalUnitType::SuffixSei => 40,
63+ NalUnitType::Other(v) => v,
64+ }
65+ }
66+
67+ /// The named type for a wire value.
68+ pub fn from_code(code: u8) -> NalUnitType {
69+ match code {
70+ 0 => NalUnitType::TrailN,
71+ 1 => NalUnitType::TrailR,
72+ 19 => NalUnitType::IdrWRadl,
73+ 20 => NalUnitType::IdrNLp,
74+ 21 => NalUnitType::CraNut,
75+ 32 => NalUnitType::Vps,
76+ 33 => NalUnitType::Sps,
77+ 34 => NalUnitType::Pps,
78+ 35 => NalUnitType::Aud,
79+ 36 => NalUnitType::EosNut,
80+ 37 => NalUnitType::EobNut,
81+ 38 => NalUnitType::FdNut,
82+ 39 => NalUnitType::PrefixSei,
83+ 40 => NalUnitType::SuffixSei,
84+ v => NalUnitType::Other(v),
85+ }
86+ }
87+
88+ /// True for the video coding layer types (0..=31), the ones that carry slices.
89+ pub fn is_vcl(self) -> bool {
90+ self.code() < 32
91+ }
92+
93+ /// True for the IRAP range (16..=23): a decoder may be started here.
94+ pub fn is_irap(self) -> bool {
95+ (16..=23).contains(&self.code())
96+ }
97+
98+ /// True for the two IDR types, which is what "every AU is a sync point" means.
99+ pub fn is_idr(self) -> bool {
100+ matches!(self, NalUnitType::IdrWRadl | NalUnitType::IdrNLp)
101+ }
102+}
103+
104+/// The two-byte NAL unit header (7.3.1.2).
105+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106+pub struct NalHeader {
107+ /// What the payload is.
108+ pub nal_type: NalUnitType,
109+ /// Layer id; 0 for everything this family writes.
110+ pub layer_id: u8,
111+ /// `nuh_temporal_id_plus1 - 1`.
112+ pub temporal_id: u8,
113+}
114+
115+impl NalHeader {
116+ /// A base-layer header at temporal id 0.
117+ pub fn new(nal_type: NalUnitType) -> NalHeader {
118+ NalHeader {
119+ nal_type,
120+ layer_id: 0,
121+ temporal_id: 0,
122+ }
123+ }
124+
125+ /// The two header bytes.
126+ pub fn to_bytes(self) -> [u8; 2] {
127+ let b0 = (self.nal_type.code() << 1) | (self.layer_id >> 5);
128+ let b1 = ((self.layer_id & 0x1f) << 3) | (self.temporal_id + 1);
129+ [b0, b1]
130+ }
131+
132+ /// Parse the two header bytes, rejecting a set `forbidden_zero_bit`.
133+ pub fn parse(bytes: &[u8]) -> Result<NalHeader> {
134+ let (b0, b1) = match bytes {
135+ [b0, b1, ..] => (*b0, *b1),
136+ _ => return Err(Error::NeedMore),
137+ };
138+ if b0 & 0x80 != 0 {
139+ return Err(Error::corrupt("HEVC NAL header: forbidden_zero_bit set"));
140+ }
141+ let temporal_id_plus1 = b1 & 0x7;
142+ if temporal_id_plus1 == 0 {
143+ return Err(Error::corrupt("HEVC NAL header: nuh_temporal_id_plus1 = 0"));
144+ }
145+ Ok(NalHeader {
146+ nal_type: NalUnitType::from_code((b0 >> 1) & 0x3f),
147+ layer_id: ((b0 & 1) << 5) | (b1 >> 3),
148+ temporal_id: temporal_id_plus1 - 1,
149+ })
150+ }
151+}
152+
153+/// Escape an RBSP into a NAL unit payload (7.3.1.1).
154+///
155+/// A `0x03` goes in before any byte that would otherwise complete a
156+/// `00 00 00`..`00 00 03` sequence, so a start code can never appear inside a
157+/// NAL unit. Trailing `00 00` at the very end is escaped too: the next thing in
158+/// the stream is a start code, and `00 00 00 01` read backwards from there would
159+/// swallow the last payload byte.
160+pub fn escape_rbsp(rbsp: &[u8], out: &mut Vec<u8>) {
161+ let mut zeros = 0usize;
162+ for &b in rbsp {
163+ if zeros >= 2 && b <= 3 {
164+ out.push(3);
165+ zeros = 0;
166+ }
167+ out.push(b);
168+ if b == 0 {
169+ zeros += 1;
170+ } else {
171+ zeros = 0;
172+ }
173+ }
174+ if zeros >= 2 {
175+ out.push(3);
176+ }
177+}
178+
179+/// Strip emulation prevention bytes from a NAL unit payload.
180+pub fn unescape_rbsp(payload: &[u8]) -> Vec<u8> {
181+ let mut out = Vec::with_capacity(payload.len());
182+ let mut zeros = 0usize;
183+ for &b in payload {
184+ if zeros >= 2 && b == 3 {
185+ zeros = 0;
186+ continue;
187+ }
188+ out.push(b);
189+ if b == 0 {
190+ zeros += 1;
191+ } else {
192+ zeros = 0;
193+ }
194+ }
195+ out
196+}
197+
198+/// Append one Annex-B NAL unit: start code, header, escaped RBSP.
199+///
200+/// The four-byte start code is used for parameter sets and the first slice of a
201+/// picture, three bytes elsewhere — the same shape ffmpeg writes, and what a
202+/// caller splitting an access unit back apart expects.
203+pub fn write_annex_b(out: &mut Vec<u8>, header: NalHeader, rbsp: &[u8], long_start_code: bool) {
204+ if long_start_code {
205+ out.extend_from_slice(&[0, 0, 0, 1]);
206+ } else {
207+ out.extend_from_slice(&[0, 0, 1]);
208+ }
209+ out.extend_from_slice(&header.to_bytes());
210+ escape_rbsp(rbsp, out);
211+}
212+
213+/// One NAL unit found in an Annex-B stream.
214+#[derive(Debug, Clone, PartialEq, Eq)]
215+pub struct AnnexBNal<'a> {
216+ /// Parsed two-byte header.
217+ pub header: NalHeader,
218+ /// Payload after the header, still escaped.
219+ pub payload: &'a [u8],
220+}
221+
222+impl AnnexBNal<'_> {
223+ /// The payload with emulation prevention bytes removed.
224+ pub fn rbsp(&self) -> Vec<u8> {
225+ unescape_rbsp(self.payload)
226+ }
227+}
228+
229+/// Split an Annex-B byte stream into NAL units.
230+///
231+/// Bytes before the first start code are ignored rather than refused, which is
232+/// what makes this usable on a stream joined mid-file. A NAL whose header is
233+/// malformed is skipped, not fatal.
234+pub fn split_annex_b(data: &[u8]) -> Vec<AnnexBNal<'_>> {
235+ let mut nals = Vec::new();
236+ let mut starts = Vec::new();
237+ let mut i = 0usize;
238+ while i + 3 <= data.len() {
239+ if data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1 {
240+ starts.push(i + 3);
241+ i += 3;
242+ } else {
243+ i += 1;
244+ }
245+ }
246+ for (n, &start) in starts.iter().enumerate() {
247+ let mut end = starts.get(n + 1).map_or(data.len(), |&next| next - 3);
248+ // A four-byte start code leaves one extra zero at the end of the
249+ // previous unit; trailing zeros are never part of an RBSP.
250+ while end > start && data[end - 1] == 0 {
251+ end -= 1;
252+ }
253+ if end < start + 2 {
254+ continue;
255+ }
256+ if let Ok(header) = NalHeader::parse(&data[start..end]) {
257+ nals.push(AnnexBNal {
258+ header,
259+ payload: &data[start + 2..end],
260+ });
261+ }
262+ }
263+ nals
264+}
265+
266+#[cfg(test)]
267+mod tests {
268+ use super::*;
269+
270+ #[test]
271+ fn header_round_trip() {
272+ for code in 0u8..64 {
273+ let h = NalHeader {
274+ nal_type: NalUnitType::from_code(code),
275+ layer_id: 0,
276+ temporal_id: 0,
277+ };
278+ let bytes = h.to_bytes();
279+ assert_eq!(NalHeader::parse(&bytes).unwrap(), h);
280+ }
281+ // An IDR slice header is the well-known 0x26 0x01.
282+ assert_eq!(NalHeader::new(NalUnitType::IdrWRadl).to_bytes(), [0x26, 0x01]);
283+ assert_eq!(NalHeader::new(NalUnitType::Vps).to_bytes(), [0x40, 0x01]);
284+ assert!(NalHeader::parse(&[0x80, 0x01]).is_err());
285+ assert!(NalHeader::parse(&[0x26, 0x00]).is_err());
286+ assert!(NalHeader::parse(&[0x26]).is_err());
287+ }
288+
289+ #[test]
290+ fn escaping_round_trips_and_kills_start_codes() {
291+ let cases: &[&[u8]] = &[
292+ &[],
293+ &[0, 0, 0],
294+ &[0, 0, 1],
295+ &[0, 0, 2],
296+ &[0, 0, 3],
297+ &[0, 0, 4],
298+ &[1, 0, 0, 0, 0, 1],
299+ &[0, 0],
300+ &[0xff, 0, 0, 3, 0, 0, 0, 1],
301+ ];
302+ for case in cases {
303+ let mut escaped = Vec::new();
304+ escape_rbsp(case, &mut escaped);
305+ assert_eq!(&unescape_rbsp(&escaped)[..], *case, "case {case:?}");
306+ // No start code emulation survives escaping.
307+ assert!(
308+ !escaped.windows(3).any(|w| w == [0, 0, 1]),
309+ "start code in {escaped:?}"
310+ );
311+ }
312+ }
313+
314+ #[test]
315+ fn annex_b_split_finds_units() {
316+ let mut stream = Vec::new();
317+ write_annex_b(&mut stream, NalHeader::new(NalUnitType::Vps), &[1, 2, 3], true);
318+ write_annex_b(
319+ &mut stream,
320+ NalHeader::new(NalUnitType::IdrWRadl),
321+ &[0, 0, 0, 7],
322+ false,
323+ );
324+ let nals = split_annex_b(&stream);
325+ assert_eq!(nals.len(), 2);
326+ assert_eq!(nals[0].header.nal_type, NalUnitType::Vps);
327+ assert_eq!(nals[0].rbsp(), vec![1, 2, 3]);
328+ assert_eq!(nals[1].header.nal_type, NalUnitType::IdrWRadl);
329+ assert_eq!(nals[1].rbsp(), vec![0, 0, 0, 7]);
330+ assert!(nals[1].header.nal_type.is_idr());
331+ assert!(nals[1].header.nal_type.is_irap());
332+ assert!(nals[1].header.nal_type.is_vcl());
333+ assert!(!nals[0].header.nal_type.is_vcl());
334+ }
335+}
crates/ec-h265-syntax/src/ps.rsadded+992 -0
@@ -0,0 +1,992 @@
1+//! Parameter sets: VPS, SPS and PPS, written and parsed.
2+//!
3+//! The field sets here are sized by what a *stateless hardware decoder* asks
4+//! for, not by what this family's own encoder writes: everything in
5+//! `VAPictureParameterBufferHEVC` is either a field on [`Sps`]/[`Pps`] or
6+//! derivable from one by a named method. Anything the parser walks past but does
7+//! not model (scaling lists, HRD, the multilayer and 3D extensions) is a thing
8+//! no consumer in this family reads, and each such skip says so where it happens.
9+
10+use crate::vui::VuiParameters;
11+use ec_core::bitio::{BitReader, BitWriter};
12+use ec_core::error::{Error, Result};
13+
14+/// `profile_tier_level()` for a single-sub-layer stream (7.3.3).
15+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16+pub struct ProfileTierLevel {
17+ /// `general_profile_space`, 0 for everything in the wild.
18+ pub profile_space: u8,
19+ /// False = Main tier, true = High tier.
20+ pub tier_flag: bool,
21+ /// 1 = Main, 2 = Main 10, 3 = Main Still Picture, 4 = range extensions.
22+ pub profile_idc: u8,
23+ /// `general_profile_compatibility_flag[0..32]` as a bit set, bit `j` = flag `j`.
24+ pub profile_compatibility: u32,
25+ /// `general_progressive_source_flag`.
26+ pub progressive_source: bool,
27+ /// `general_interlaced_source_flag`.
28+ pub interlaced_source: bool,
29+ /// `general_non_packed_constraint_flag`.
30+ pub non_packed_constraint: bool,
31+ /// `general_frame_only_constraint_flag`.
32+ pub frame_only_constraint: bool,
33+ /// The 44 bits between the source flags and `general_level_idc`: the
34+ /// profile-dependent constraint flags, their reserved padding and
35+ /// `general_inbld_flag`. Kept verbatim so a re-write is byte-identical,
36+ /// because their *meaning* depends on `profile_idc` while their length
37+ /// never does.
38+ pub constraint_bits: u64,
39+ /// `general_level_idc`: 30 x the level number (level 4 = 120).
40+ pub level_idc: u8,
41+}
42+
43+impl ProfileTierLevel {
44+ /// Main profile at `level_idc`, progressive, frame-only — what an intra
45+ /// 8-bit 4:2:0 encoder emits.
46+ pub fn main(level_idc: u8) -> ProfileTierLevel {
47+ ProfileTierLevel {
48+ profile_space: 0,
49+ tier_flag: false,
50+ profile_idc: 1,
51+ // Main is compatible with itself; bit 1 is what every decoder checks.
52+ profile_compatibility: 1 << 1,
53+ progressive_source: true,
54+ interlaced_source: false,
55+ non_packed_constraint: true,
56+ frame_only_constraint: true,
57+ constraint_bits: 0,
58+ level_idc,
59+ }
60+ }
61+
62+ /// The smallest level whose limits hold for `width x height` at `fps`
63+ /// (Annex A, Table A.8/A.9 luma sample and sample-rate limits).
64+ ///
65+ /// Levels are a decoder's promise about buffer sizes; naming one too small
66+ /// is what makes a hardware decoder refuse a stream it could otherwise play,
67+ /// so this rounds up and stops at 6.2.
68+ pub fn level_for(width: u32, height: u32, fps: f64) -> u8 {
69+ // (level_idc, MaxLumaPs, MaxLumaSr)
70+ const LIMITS: &[(u8, u64, u64)] = &[
71+ (30, 36_864, 552_960),
72+ (60, 122_880, 3_686_400),
73+ (63, 245_760, 7_372_800),
74+ (90, 552_960, 16_588_800),
75+ (93, 983_040, 33_177_600),
76+ (120, 2_228_224, 66_846_720),
77+ (123, 2_228_224, 133_693_440),
78+ (126, 2_228_224, 267_386_880),
79+ (150, 8_912_896, 534_773_760),
80+ (153, 8_912_896, 1_069_547_520),
81+ (156, 8_912_896, 1_069_547_520),
82+ (180, 35_651_584, 2_139_095_040),
83+ (183, 35_651_584, 4_278_190_080),
84+ (186, 35_651_584, 4_278_190_080),
85+ ];
86+ let samples = u64::from(width) * u64::from(height);
87+ let rate = (samples as f64 * fps.max(1.0)) as u64;
88+ for &(idc, max_ps, max_sr) in LIMITS {
89+ if samples <= max_ps && rate <= max_sr {
90+ return idc;
91+ }
92+ }
93+ 186
94+ }
95+
96+ /// Write `profile_tier_level(1, 0)` — 96 bits, always.
97+ pub fn write(&self, w: &mut BitWriter) {
98+ w.write_bits(u32::from(self.profile_space), 2);
99+ w.write_bit(self.tier_flag);
100+ w.write_bits(u32::from(self.profile_idc), 5);
101+ for j in 0..32 {
102+ w.write_bit(self.profile_compatibility & (1 << j) != 0);
103+ }
104+ w.write_bit(self.progressive_source);
105+ w.write_bit(self.interlaced_source);
106+ w.write_bit(self.non_packed_constraint);
107+ w.write_bit(self.frame_only_constraint);
108+ w.write_bits64(self.constraint_bits, 44);
109+ w.write_bits(u32::from(self.level_idc), 8);
110+ }
111+
112+ /// Parse `profile_tier_level(1, max_sub_layers_minus1)`.
113+ pub fn parse(r: &mut BitReader, max_sub_layers_minus1: u32) -> Result<ProfileTierLevel> {
114+ let profile_space = r.read_bits(2)? as u8;
115+ let tier_flag = r.read_bit()?;
116+ let profile_idc = r.read_bits(5)? as u8;
117+ let mut profile_compatibility = 0u32;
118+ for j in 0..32 {
119+ if r.read_bit()? {
120+ profile_compatibility |= 1 << j;
121+ }
122+ }
123+ let progressive_source = r.read_bit()?;
124+ let interlaced_source = r.read_bit()?;
125+ let non_packed_constraint = r.read_bit()?;
126+ let frame_only_constraint = r.read_bit()?;
127+ let constraint_bits = r.read_bits64(44)?;
128+ let level_idc = r.read_bits(8)? as u8;
129+ let mut sub_layer_profile = Vec::new();
130+ let mut sub_layer_level = Vec::new();
131+ for _ in 0..max_sub_layers_minus1 {
132+ sub_layer_profile.push(r.read_bit()?);
133+ sub_layer_level.push(r.read_bit()?);
134+ }
135+ if max_sub_layers_minus1 > 0 {
136+ for _ in max_sub_layers_minus1..8 {
137+ r.read_bits(2)?;
138+ }
139+ }
140+ for i in 0..max_sub_layers_minus1 as usize {
141+ if sub_layer_profile[i] {
142+ r.skip_bits(88)?;
143+ }
144+ if sub_layer_level[i] {
145+ r.read_bits(8)?;
146+ }
147+ }
148+ Ok(ProfileTierLevel {
149+ profile_space,
150+ tier_flag,
151+ profile_idc,
152+ profile_compatibility,
153+ progressive_source,
154+ interlaced_source,
155+ non_packed_constraint,
156+ frame_only_constraint,
157+ constraint_bits,
158+ level_idc,
159+ })
160+ }
161+}
162+
163+/// The video parameter set (7.3.2.1).
164+///
165+/// A single-layer stream needs one and nothing in it varies, but a decoder that
166+/// never sees a VPS refuses the stream, so it is written all the same.
167+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
168+pub struct Vps {
169+ /// `vps_video_parameter_set_id`.
170+ pub id: u8,
171+ /// Profile, tier and level of the base layer.
172+ pub ptl: ProfileTierLevel,
173+ /// `vps_max_dec_pic_buffering_minus1[0]`.
174+ pub max_dec_pic_buffering_minus1: u32,
175+ /// `vps_max_num_reorder_pics[0]`; 0 for an intra-only stream.
176+ pub max_num_reorder_pics: u32,
177+}
178+
179+impl Vps {
180+ /// The RBSP, trailing bits included.
181+ pub fn to_rbsp(&self) -> Vec<u8> {
182+ let mut w = BitWriter::with_capacity(32);
183+ w.write_bits(u32::from(self.id), 4);
184+ w.write_bit(true); // vps_base_layer_internal_flag
185+ w.write_bit(true); // vps_base_layer_available_flag
186+ w.write_bits(0, 6); // vps_max_layers_minus1
187+ w.write_bits(0, 3); // vps_max_sub_layers_minus1
188+ w.write_bit(true); // vps_temporal_id_nesting_flag
189+ w.write_bits(0xffff, 16); // vps_reserved_0xffff_16bits
190+ self.ptl.write(&mut w);
191+ w.write_bit(true); // vps_sub_layer_ordering_info_present_flag
192+ w.write_ue(self.max_dec_pic_buffering_minus1);
193+ w.write_ue(self.max_num_reorder_pics);
194+ w.write_ue(0); // vps_max_latency_increase_plus1
195+ w.write_bits(0, 6); // vps_max_layer_id
196+ w.write_ue(0); // vps_num_layer_sets_minus1
197+ w.write_bit(false); // vps_timing_info_present_flag
198+ w.write_bit(false); // vps_extension_flag
199+ rbsp_trailing_bits(&mut w);
200+ w.into_bytes()
201+ }
202+
203+ /// Parse a VPS RBSP.
204+ pub fn parse(rbsp: &[u8]) -> Result<Vps> {
205+ let mut r = BitReader::new(rbsp);
206+ let id = r.read_bits(4)? as u8;
207+ r.read_bit()?;
208+ r.read_bit()?;
209+ r.read_bits(6)?; // vps_max_layers_minus1
210+ let max_sub_layers_minus1 = r.read_bits(3)?;
211+ r.read_bit()?;
212+ r.read_bits(16)?;
213+ let ptl = ProfileTierLevel::parse(&mut r, max_sub_layers_minus1)?;
214+ let ordering_info = r.read_bit()?;
215+ let first = if ordering_info { 0 } else { max_sub_layers_minus1 };
216+ let mut max_dec_pic_buffering_minus1 = 0;
217+ let mut max_num_reorder_pics = 0;
218+ for _ in first..=max_sub_layers_minus1 {
219+ max_dec_pic_buffering_minus1 = r.read_ue()?;
220+ max_num_reorder_pics = r.read_ue()?;
221+ r.read_ue()?;
222+ }
223+ Ok(Vps {
224+ id,
225+ ptl,
226+ max_dec_pic_buffering_minus1,
227+ max_num_reorder_pics,
228+ })
229+ }
230+}
231+
232+/// The conformance window: how many samples to crop off a coded picture.
233+///
234+/// This is how 1920x1080 is coded with 64x64 coding tree blocks — the picture is
235+/// coded 1920x1088 and eight rows are cropped — and it is a first-class field
236+/// here rather than a caller's problem, because a caller that pads its own
237+/// planes has to guess what the encoder does with the padding.
238+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
239+pub struct ConformanceWindow {
240+ /// `conf_win_left_offset`, in chroma units.
241+ pub left: u32,
242+ /// `conf_win_right_offset`, in chroma units.
243+ pub right: u32,
244+ /// `conf_win_top_offset`, in chroma units.
245+ pub top: u32,
246+ /// `conf_win_bottom_offset`, in chroma units.
247+ pub bottom: u32,
248+}
249+
250+impl ConformanceWindow {
251+ /// True when nothing is cropped.
252+ pub fn is_empty(&self) -> bool {
253+ *self == ConformanceWindow::default()
254+ }
255+}
256+
257+/// The sequence parameter set (7.3.2.2.1).
258+#[derive(Debug, Clone, PartialEq, Eq)]
259+pub struct Sps {
260+ /// `sps_video_parameter_set_id`.
261+ pub vps_id: u8,
262+ /// `sps_seq_parameter_set_id`.
263+ pub id: u32,
264+ /// 0 = monochrome, 1 = 4:2:0, 2 = 4:2:2, 3 = 4:4:4.
265+ pub chroma_format_idc: u32,
266+ /// `separate_colour_plane_flag`.
267+ pub separate_colour_plane: bool,
268+ /// Coded width — a multiple of the minimum coding block size.
269+ pub pic_width_in_luma_samples: u32,
270+ /// Coded height.
271+ pub pic_height_in_luma_samples: u32,
272+ /// What to crop off the coded picture for display.
273+ pub conf_win: ConformanceWindow,
274+ /// `bit_depth_luma_minus8`.
275+ pub bit_depth_luma_minus8: u32,
276+ /// `bit_depth_chroma_minus8`.
277+ pub bit_depth_chroma_minus8: u32,
278+ /// `log2_max_pic_order_cnt_lsb_minus4`.
279+ pub log2_max_poc_lsb_minus4: u32,
280+ /// `sps_max_dec_pic_buffering_minus1[HighestTid]`.
281+ pub max_dec_pic_buffering_minus1: u32,
282+ /// `sps_max_num_reorder_pics[HighestTid]`.
283+ pub max_num_reorder_pics: u32,
284+ /// `log2_min_luma_coding_block_size_minus3`.
285+ pub log2_min_cb_size_minus3: u32,
286+ /// `log2_diff_max_min_luma_coding_block_size`.
287+ pub log2_diff_max_min_cb_size: u32,
288+ /// `log2_min_luma_transform_block_size_minus2`.
289+ pub log2_min_tb_size_minus2: u32,
290+ /// `log2_diff_max_min_luma_transform_block_size`.
291+ pub log2_diff_max_min_tb_size: u32,
292+ /// `max_transform_hierarchy_depth_inter`.
293+ pub max_transform_hierarchy_depth_inter: u32,
294+ /// `max_transform_hierarchy_depth_intra`.
295+ pub max_transform_hierarchy_depth_intra: u32,
296+ /// `scaling_list_enabled_flag`; this family never writes scaling lists.
297+ pub scaling_list_enabled: bool,
298+ /// `amp_enabled_flag`.
299+ pub amp_enabled: bool,
300+ /// `sample_adaptive_offset_enabled_flag`.
301+ pub sao_enabled: bool,
302+ /// `pcm_enabled_flag`.
303+ pub pcm_enabled: bool,
304+ /// `num_short_term_ref_pic_sets`.
305+ pub num_short_term_ref_pic_sets: u32,
306+ /// `long_term_ref_pics_present_flag`.
307+ pub long_term_ref_pics_present: bool,
308+ /// `num_long_term_ref_pics_sps`.
309+ pub num_long_term_ref_pics_sps: u32,
310+ /// `sps_temporal_mvp_enabled_flag`.
311+ pub temporal_mvp_enabled: bool,
312+ /// `strong_intra_smoothing_enabled_flag`.
313+ pub strong_intra_smoothing: bool,
314+ /// Profile, tier, level.
315+ pub ptl: ProfileTierLevel,
316+ /// VUI, when present.
317+ pub vui: Option<VuiParameters>,
318+}
319+
320+impl Sps {
321+ /// Coding tree block size in luma samples (`CtbSizeY`).
322+ pub fn ctb_size(&self) -> u32 {
323+ 1 << (self.log2_min_cb_size_minus3 + 3 + self.log2_diff_max_min_cb_size)
324+ }
325+
326+ /// `PicWidthInCtbsY`.
327+ pub fn pic_width_in_ctbs(&self) -> u32 {
328+ self.pic_width_in_luma_samples.div_ceil(self.ctb_size())
329+ }
330+
331+ /// `PicHeightInCtbsY`.
332+ pub fn pic_height_in_ctbs(&self) -> u32 {
333+ self.pic_height_in_luma_samples.div_ceil(self.ctb_size())
334+ }
335+
336+ /// `SubWidthC`, `SubHeightC` for the chroma format.
337+ pub fn chroma_subsampling(&self) -> (u32, u32) {
338+ match self.chroma_format_idc {
339+ 1 => (2, 2),
340+ 2 => (2, 1),
341+ _ => (1, 1),
342+ }
343+ }
344+
345+ /// Displayed size after the conformance window is applied.
346+ pub fn display_size(&self) -> (u32, u32) {
347+ let (sub_w, sub_h) = self.chroma_subsampling();
348+ (
349+ self.pic_width_in_luma_samples - sub_w * (self.conf_win.left + self.conf_win.right),
350+ self.pic_height_in_luma_samples - sub_h * (self.conf_win.top + self.conf_win.bottom),
351+ )
352+ }
353+
354+ /// Number of bits `slice_segment_address` occupies in a slice header:
355+ /// `Ceil( Log2( PicSizeInCtbsY ) )`.
356+ pub fn slice_address_bits(&self) -> u32 {
357+ ceil_log2(self.pic_width_in_ctbs() * self.pic_height_in_ctbs())
358+ }
359+
360+ /// The RBSP, trailing bits included.
361+ pub fn to_rbsp(&self) -> Vec<u8> {
362+ let mut w = BitWriter::with_capacity(64);
363+ w.write_bits(u32::from(self.vps_id), 4);
364+ w.write_bits(0, 3); // sps_max_sub_layers_minus1
365+ w.write_bit(true); // sps_temporal_id_nesting_flag
366+ self.ptl.write(&mut w);
367+ w.write_ue(self.id);
368+ w.write_ue(self.chroma_format_idc);
369+ if self.chroma_format_idc == 3 {
370+ w.write_bit(self.separate_colour_plane);
371+ }
372+ w.write_ue(self.pic_width_in_luma_samples);
373+ w.write_ue(self.pic_height_in_luma_samples);
374+ if self.conf_win.is_empty() {
375+ w.write_bit(false);
376+ } else {
377+ w.write_bit(true);
378+ w.write_ue(self.conf_win.left);
379+ w.write_ue(self.conf_win.right);
380+ w.write_ue(self.conf_win.top);
381+ w.write_ue(self.conf_win.bottom);
382+ }
383+ w.write_ue(self.bit_depth_luma_minus8);
384+ w.write_ue(self.bit_depth_chroma_minus8);
385+ w.write_ue(self.log2_max_poc_lsb_minus4);
386+ w.write_bit(true); // sps_sub_layer_ordering_info_present_flag
387+ w.write_ue(self.max_dec_pic_buffering_minus1);
388+ w.write_ue(self.max_num_reorder_pics);
389+ w.write_ue(0); // sps_max_latency_increase_plus1
390+ w.write_ue(self.log2_min_cb_size_minus3);
391+ w.write_ue(self.log2_diff_max_min_cb_size);
392+ w.write_ue(self.log2_min_tb_size_minus2);
393+ w.write_ue(self.log2_diff_max_min_tb_size);
394+ w.write_ue(self.max_transform_hierarchy_depth_inter);
395+ w.write_ue(self.max_transform_hierarchy_depth_intra);
396+ w.write_bit(self.scaling_list_enabled);
397+ if self.scaling_list_enabled {
398+ w.write_bit(false); // sps_scaling_list_data_present_flag
399+ }
400+ w.write_bit(self.amp_enabled);
401+ w.write_bit(self.sao_enabled);
402+ w.write_bit(self.pcm_enabled);
403+ w.write_ue(self.num_short_term_ref_pic_sets);
404+ w.write_bit(self.long_term_ref_pics_present);
405+ if self.long_term_ref_pics_present {
406+ w.write_ue(self.num_long_term_ref_pics_sps);
407+ }
408+ w.write_bit(self.temporal_mvp_enabled);
409+ w.write_bit(self.strong_intra_smoothing);
410+ match &self.vui {
411+ Some(vui) => {
412+ w.write_bit(true);
413+ vui.write(&mut w);
414+ }
415+ None => w.write_bit(false),
416+ }
417+ w.write_bit(false); // sps_extension_present_flag
418+ rbsp_trailing_bits(&mut w);
419+ w.into_bytes()
420+ }
421+
422+ /// Parse an SPS RBSP.
423+ ///
424+ /// Short-term reference picture sets are walked but not kept: a decoder
425+ /// resolves them from the slice header, and this family's own streams have
426+ /// none. A stream with scaling lists is refused rather than mis-decoded.
427+ pub fn parse(rbsp: &[u8]) -> Result<Sps> {
428+ let mut r = BitReader::new(rbsp);
429+ let vps_id = r.read_bits(4)? as u8;
430+ let max_sub_layers_minus1 = r.read_bits(3)?;
431+ r.read_bit()?; // sps_temporal_id_nesting_flag
432+ let ptl = ProfileTierLevel::parse(&mut r, max_sub_layers_minus1)?;
433+ let id = r.read_ue()?;
434+ let chroma_format_idc = r.read_ue()?;
435+ if chroma_format_idc > 3 {
436+ return Err(Error::corrupt(format!(
437+ "HEVC SPS: chroma_format_idc = {chroma_format_idc}"
438+ )));
439+ }
440+ let separate_colour_plane = if chroma_format_idc == 3 {
441+ r.read_bit()?
442+ } else {
443+ false
444+ };
445+ let pic_width_in_luma_samples = r.read_ue()?;
446+ let pic_height_in_luma_samples = r.read_ue()?;
447+ if pic_width_in_luma_samples == 0 || pic_height_in_luma_samples == 0 {
448+ return Err(Error::corrupt("HEVC SPS: zero picture dimension"));
449+ }
450+ let mut conf_win = ConformanceWindow::default();
451+ if r.read_bit()? {
452+ conf_win = ConformanceWindow {
453+ left: r.read_ue()?,
454+ right: r.read_ue()?,
455+ top: r.read_ue()?,
456+ bottom: r.read_ue()?,
457+ };
458+ }
459+ let bit_depth_luma_minus8 = r.read_ue()?;
460+ let bit_depth_chroma_minus8 = r.read_ue()?;
461+ if bit_depth_luma_minus8 > 8 || bit_depth_chroma_minus8 > 8 {
462+ return Err(Error::corrupt("HEVC SPS: bit depth out of range"));
463+ }
464+ let log2_max_poc_lsb_minus4 = r.read_ue()?;
465+ let ordering_info = r.read_bit()?;
466+ let first = if ordering_info { 0 } else { max_sub_layers_minus1 };
467+ let mut max_dec_pic_buffering_minus1 = 0;
468+ let mut max_num_reorder_pics = 0;
469+ for _ in first..=max_sub_layers_minus1 {
470+ max_dec_pic_buffering_minus1 = r.read_ue()?;
471+ max_num_reorder_pics = r.read_ue()?;
472+ r.read_ue()?;
473+ }
474+ let log2_min_cb_size_minus3 = r.read_ue()?;
475+ let log2_diff_max_min_cb_size = r.read_ue()?;
476+ let log2_min_tb_size_minus2 = r.read_ue()?;
477+ let log2_diff_max_min_tb_size = r.read_ue()?;
478+ if log2_min_cb_size_minus3 + log2_diff_max_min_cb_size > 3 {
479+ return Err(Error::corrupt("HEVC SPS: CTB larger than 64x64"));
480+ }
481+ let max_transform_hierarchy_depth_inter = r.read_ue()?;
482+ let max_transform_hierarchy_depth_intra = r.read_ue()?;
483+ let scaling_list_enabled = r.read_bit()?;
484+ if scaling_list_enabled && r.read_bit()? {
485+ return Err(Error::unsupported(
486+ "HEVC SPS scaling lists",
487+ "this family codes with the flat 16 matrix only",
488+ ));
489+ }
490+ let amp_enabled = r.read_bit()?;
491+ let sao_enabled = r.read_bit()?;
492+ let pcm_enabled = r.read_bit()?;
493+ if pcm_enabled {
494+ r.read_bits(4)?; // pcm_sample_bit_depth_luma_minus1
495+ r.read_bits(4)?; // pcm_sample_bit_depth_chroma_minus1
496+ r.read_ue()?; // log2_min_pcm_luma_coding_block_size_minus3
497+ r.read_ue()?; // log2_diff_max_min_pcm_luma_coding_block_size
498+ r.read_bit()?; // pcm_loop_filter_disabled_flag
499+ }
500+ let num_short_term_ref_pic_sets = r.read_ue()?;
501+ if num_short_term_ref_pic_sets > 64 {
502+ return Err(Error::corrupt("HEVC SPS: num_short_term_ref_pic_sets > 64"));
503+ }
504+ let mut sets = Vec::new();
505+ for i in 0..num_short_term_ref_pic_sets {
506+ let set = ShortTermRefPicSet::parse(&mut r, i, &sets)?;
507+ sets.push(set);
508+ }
509+ let long_term_ref_pics_present = r.read_bit()?;
510+ let mut num_long_term_ref_pics_sps = 0;
511+ if long_term_ref_pics_present {
512+ num_long_term_ref_pics_sps = r.read_ue()?;
513+ for _ in 0..num_long_term_ref_pics_sps {
514+ r.read_bits(log2_max_poc_lsb_minus4 + 4)?;
515+ r.read_bit()?;
516+ }
517+ }
518+ let temporal_mvp_enabled = r.read_bit()?;
519+ let strong_intra_smoothing = r.read_bit()?;
520+ let vui = if r.read_bit()? {
521+ Some(VuiParameters::parse(&mut r, max_sub_layers_minus1)?)
522+ } else {
523+ None
524+ };
525+ Ok(Sps {
526+ vps_id,
527+ id,
528+ chroma_format_idc,
529+ separate_colour_plane,
530+ pic_width_in_luma_samples,
531+ pic_height_in_luma_samples,
532+ conf_win,
533+ bit_depth_luma_minus8,
534+ bit_depth_chroma_minus8,
535+ log2_max_poc_lsb_minus4,
536+ max_dec_pic_buffering_minus1,
537+ max_num_reorder_pics,
538+ log2_min_cb_size_minus3,
539+ log2_diff_max_min_cb_size,
540+ log2_min_tb_size_minus2,
541+ log2_diff_max_min_tb_size,
542+ max_transform_hierarchy_depth_inter,
543+ max_transform_hierarchy_depth_intra,
544+ scaling_list_enabled,
545+ amp_enabled,
546+ sao_enabled,
547+ pcm_enabled,
548+ num_short_term_ref_pic_sets,
549+ long_term_ref_pics_present,
550+ num_long_term_ref_pics_sps,
551+ temporal_mvp_enabled,
552+ strong_intra_smoothing,
553+ ptl,
554+ vui,
555+ })
556+ }
557+}
558+
559+/// One `st_ref_pic_set()` (7.3.7), kept only as far as re-parsing needs.
560+///
561+/// The delta values themselves are a decoder's reference-list problem; what a
562+/// *parser* has to get right is the number of pictures in each direction,
563+/// because the next set's syntax depends on it.
564+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
565+pub struct ShortTermRefPicSet {
566+ /// `NumNegativePics`.
567+ pub num_negative: u32,
568+ /// `NumPositivePics`.
569+ pub num_positive: u32,
570+ /// How many of them have `used_by_curr_pic` set — the count that feeds
571+ /// `NumPicTotalCurr`, which sizes the reference list modification syntax.
572+ pub num_used_by_curr: u32,
573+}
574+
575+impl ShortTermRefPicSet {
576+ /// Parse one set; `prev` holds the sets already parsed for inter-set prediction.
577+ pub fn parse(
578+ r: &mut BitReader,
579+ idx: u32,
580+ prev: &[ShortTermRefPicSet],
581+ ) -> Result<ShortTermRefPicSet> {
582+ let inter_ref_pic_set_prediction = if idx != 0 { r.read_bit()? } else { false };
583+ if inter_ref_pic_set_prediction {
584+ let delta_idx_minus1 = if idx == prev.len() as u32 {
585+ r.read_ue()?
586+ } else {
587+ 0
588+ };
589+ let ref_idx = idx
590+ .checked_sub(delta_idx_minus1 + 1)
591+ .ok_or_else(|| Error::corrupt("HEVC st_ref_pic_set: delta_idx out of range"))?;
592+ let reference = *prev
593+ .get(ref_idx as usize)
594+ .ok_or_else(|| Error::corrupt("HEVC st_ref_pic_set: unknown reference set"))?;
595+ r.read_bit()?; // delta_rps_sign
596+ r.read_ue()?; // abs_delta_rps_minus1
597+ let num_delta_pocs = reference.num_negative + reference.num_positive;
598+ let mut kept = 0;
599+ let mut used_by_curr = 0;
600+ for _ in 0..=num_delta_pocs {
601+ let used = r.read_bit()?;
602+ if used {
603+ kept += 1;
604+ used_by_curr += 1;
605+ } else if r.read_bit()? {
606+ kept += 1;
607+ }
608+ }
609+ // Without reconstructing the POCs the split between negative and
610+ // positive is not knowable; the total is, and that is what the
611+ // syntax of any following set depends on.
612+ Ok(ShortTermRefPicSet {
613+ num_negative: kept,
614+ num_positive: 0,
615+ num_used_by_curr: used_by_curr,
616+ })
617+ } else {
618+ let num_negative = r.read_ue()?;
619+ let num_positive = r.read_ue()?;
620+ if num_negative > 16 || num_positive > 16 {
621+ return Err(Error::corrupt("HEVC st_ref_pic_set: too many pictures"));
622+ }
623+ let mut num_used_by_curr = 0;
624+ for _ in 0..num_negative + num_positive {
625+ r.read_ue()?; // delta_poc_sX_minus1
626+ if r.read_bit()? {
627+ num_used_by_curr += 1; // used_by_curr_pic_sX_flag
628+ }
629+ }
630+ Ok(ShortTermRefPicSet {
631+ num_negative,
632+ num_positive,
633+ num_used_by_curr,
634+ })
635+ }
636+ }
637+}
638+
639+/// The picture parameter set (7.3.2.3.1).
640+#[derive(Debug, Clone, PartialEq, Eq)]
641+pub struct Pps {
642+ /// `pps_pic_parameter_set_id`.
643+ pub id: u32,
644+ /// `pps_seq_parameter_set_id`.
645+ pub sps_id: u32,
646+ /// `dependent_slice_segments_enabled_flag`.
647+ pub dependent_slice_segments_enabled: bool,
648+ /// `output_flag_present_flag`.
649+ pub output_flag_present: bool,
650+ /// `num_extra_slice_header_bits`.
651+ pub num_extra_slice_header_bits: u32,
652+ /// `sign_data_hiding_enabled_flag`.
653+ pub sign_data_hiding_enabled: bool,
654+ /// `cabac_init_present_flag`.
655+ pub cabac_init_present: bool,
656+ /// `num_ref_idx_l0_default_active_minus1`.
657+ pub num_ref_idx_l0_default_active_minus1: u32,
658+ /// `num_ref_idx_l1_default_active_minus1`.
659+ pub num_ref_idx_l1_default_active_minus1: u32,
660+ /// `init_qp_minus26`.
661+ pub init_qp_minus26: i32,
662+ /// `constrained_intra_pred_flag`.
663+ pub constrained_intra_pred: bool,
664+ /// `transform_skip_enabled_flag`.
665+ pub transform_skip_enabled: bool,
666+ /// `cu_qp_delta_enabled_flag`.
667+ pub cu_qp_delta_enabled: bool,
668+ /// `diff_cu_qp_delta_depth`.
669+ pub diff_cu_qp_delta_depth: u32,
670+ /// `pps_cb_qp_offset`.
671+ pub cb_qp_offset: i32,
672+ /// `pps_cr_qp_offset`.
673+ pub cr_qp_offset: i32,
674+ /// `pps_slice_chroma_qp_offsets_present_flag`.
675+ pub slice_chroma_qp_offsets_present: bool,
676+ /// `weighted_pred_flag`.
677+ pub weighted_pred: bool,
678+ /// `weighted_bipred_flag`.
679+ pub weighted_bipred: bool,
680+ /// `transquant_bypass_enabled_flag`.
681+ pub transquant_bypass_enabled: bool,
682+ /// `tiles_enabled_flag`.
683+ pub tiles_enabled: bool,
684+ /// `entropy_coding_sync_enabled_flag` — wavefront parallel processing.
685+ pub entropy_coding_sync_enabled: bool,
686+ /// `num_tile_columns_minus1`.
687+ pub num_tile_columns_minus1: u32,
688+ /// `num_tile_rows_minus1`.
689+ pub num_tile_rows_minus1: u32,
690+ /// `uniform_spacing_flag`.
691+ pub uniform_spacing: bool,
692+ /// `loop_filter_across_tiles_enabled_flag`.
693+ pub loop_filter_across_tiles_enabled: bool,
694+ /// `pps_loop_filter_across_slices_enabled_flag`.
695+ pub loop_filter_across_slices_enabled: bool,
696+ /// `deblocking_filter_control_present_flag`.
697+ pub deblocking_filter_control_present: bool,
698+ /// `deblocking_filter_override_enabled_flag`.
699+ pub deblocking_filter_override_enabled: bool,
700+ /// `pps_deblocking_filter_disabled_flag`.
701+ pub deblocking_filter_disabled: bool,
702+ /// `pps_beta_offset_div2`.
703+ pub beta_offset_div2: i32,
704+ /// `pps_tc_offset_div2`.
705+ pub tc_offset_div2: i32,
706+ /// `lists_modification_present_flag`.
707+ pub lists_modification_present: bool,
708+ /// `log2_parallel_merge_level_minus2`.
709+ pub log2_parallel_merge_level_minus2: u32,
710+ /// `slice_segment_header_extension_present_flag`.
711+ pub slice_segment_header_extension_present: bool,
712+}
713+
714+impl Default for Pps {
715+ fn default() -> Self {
716+ Pps {
717+ id: 0,
718+ sps_id: 0,
719+ dependent_slice_segments_enabled: false,
720+ output_flag_present: false,
721+ num_extra_slice_header_bits: 0,
722+ sign_data_hiding_enabled: false,
723+ cabac_init_present: false,
724+ num_ref_idx_l0_default_active_minus1: 0,
725+ num_ref_idx_l1_default_active_minus1: 0,
726+ init_qp_minus26: 0,
727+ constrained_intra_pred: false,
728+ transform_skip_enabled: false,
729+ cu_qp_delta_enabled: false,
730+ diff_cu_qp_delta_depth: 0,
731+ cb_qp_offset: 0,
732+ cr_qp_offset: 0,
733+ slice_chroma_qp_offsets_present: false,
734+ weighted_pred: false,
735+ weighted_bipred: false,
736+ transquant_bypass_enabled: false,
737+ tiles_enabled: false,
738+ entropy_coding_sync_enabled: false,
739+ num_tile_columns_minus1: 0,
740+ num_tile_rows_minus1: 0,
741+ uniform_spacing: true,
742+ loop_filter_across_tiles_enabled: true,
743+ loop_filter_across_slices_enabled: true,
744+ deblocking_filter_control_present: false,
745+ deblocking_filter_override_enabled: false,
746+ deblocking_filter_disabled: false,
747+ beta_offset_div2: 0,
748+ tc_offset_div2: 0,
749+ lists_modification_present: false,
750+ log2_parallel_merge_level_minus2: 0,
751+ slice_segment_header_extension_present: false,
752+ }
753+ }
754+}
755+
756+impl Pps {
757+ /// The RBSP, trailing bits included.
758+ pub fn to_rbsp(&self) -> Vec<u8> {
759+ let mut w = BitWriter::with_capacity(32);
760+ w.write_ue(self.id);
761+ w.write_ue(self.sps_id);
762+ w.write_bit(self.dependent_slice_segments_enabled);
763+ w.write_bit(self.output_flag_present);
764+ w.write_bits(self.num_extra_slice_header_bits, 3);
765+ w.write_bit(self.sign_data_hiding_enabled);
766+ w.write_bit(self.cabac_init_present);
767+ w.write_ue(self.num_ref_idx_l0_default_active_minus1);
768+ w.write_ue(self.num_ref_idx_l1_default_active_minus1);
769+ w.write_se(self.init_qp_minus26);
770+ w.write_bit(self.constrained_intra_pred);
771+ w.write_bit(self.transform_skip_enabled);
772+ w.write_bit(self.cu_qp_delta_enabled);
773+ if self.cu_qp_delta_enabled {
774+ w.write_ue(self.diff_cu_qp_delta_depth);
775+ }
776+ w.write_se(self.cb_qp_offset);
777+ w.write_se(self.cr_qp_offset);
778+ w.write_bit(self.slice_chroma_qp_offsets_present);
779+ w.write_bit(self.weighted_pred);
780+ w.write_bit(self.weighted_bipred);
781+ w.write_bit(self.transquant_bypass_enabled);
782+ w.write_bit(self.tiles_enabled);
783+ w.write_bit(self.entropy_coding_sync_enabled);
784+ if self.tiles_enabled {
785+ w.write_ue(self.num_tile_columns_minus1);
786+ w.write_ue(self.num_tile_rows_minus1);
787+ w.write_bit(self.uniform_spacing);
788+ w.write_bit(self.loop_filter_across_tiles_enabled);
789+ }
790+ w.write_bit(self.loop_filter_across_slices_enabled);
791+ w.write_bit(self.deblocking_filter_control_present);
792+ if self.deblocking_filter_control_present {
793+ w.write_bit(self.deblocking_filter_override_enabled);
794+ w.write_bit(self.deblocking_filter_disabled);
795+ if !self.deblocking_filter_disabled {
796+ w.write_se(self.beta_offset_div2);
797+ w.write_se(self.tc_offset_div2);
798+ }
799+ }
800+ w.write_bit(false); // pps_scaling_list_data_present_flag
801+ w.write_bit(self.lists_modification_present);
802+ w.write_ue(self.log2_parallel_merge_level_minus2);
803+ w.write_bit(self.slice_segment_header_extension_present);
804+ w.write_bit(false); // pps_extension_present_flag
805+ rbsp_trailing_bits(&mut w);
806+ w.into_bytes()
807+ }
808+
809+ /// Parse a PPS RBSP.
810+ pub fn parse(rbsp: &[u8]) -> Result<Pps> {
811+ let mut r = BitReader::new(rbsp);
812+ let mut pps = Pps {
813+ id: r.read_ue()?,
814+ sps_id: r.read_ue()?,
815+ ..Pps::default()
816+ };
817+ pps.dependent_slice_segments_enabled = r.read_bit()?;
818+ pps.output_flag_present = r.read_bit()?;
819+ pps.num_extra_slice_header_bits = r.read_bits(3)?;
820+ pps.sign_data_hiding_enabled = r.read_bit()?;
821+ pps.cabac_init_present = r.read_bit()?;
822+ pps.num_ref_idx_l0_default_active_minus1 = r.read_ue()?;
823+ pps.num_ref_idx_l1_default_active_minus1 = r.read_ue()?;
824+ pps.init_qp_minus26 = r.read_se()?;
825+ pps.constrained_intra_pred = r.read_bit()?;
826+ pps.transform_skip_enabled = r.read_bit()?;
827+ pps.cu_qp_delta_enabled = r.read_bit()?;
828+ if pps.cu_qp_delta_enabled {
829+ pps.diff_cu_qp_delta_depth = r.read_ue()?;
830+ }
831+ pps.cb_qp_offset = r.read_se()?;
832+ pps.cr_qp_offset = r.read_se()?;
833+ pps.slice_chroma_qp_offsets_present = r.read_bit()?;
834+ pps.weighted_pred = r.read_bit()?;
835+ pps.weighted_bipred = r.read_bit()?;
836+ pps.transquant_bypass_enabled = r.read_bit()?;
837+ pps.tiles_enabled = r.read_bit()?;
838+ pps.entropy_coding_sync_enabled = r.read_bit()?;
839+ if pps.tiles_enabled {
840+ pps.num_tile_columns_minus1 = r.read_ue()?;
841+ pps.num_tile_rows_minus1 = r.read_ue()?;
842+ pps.uniform_spacing = r.read_bit()?;
843+ if !pps.uniform_spacing {
844+ for _ in 0..pps.num_tile_columns_minus1 {
845+ r.read_ue()?;
846+ }
847+ for _ in 0..pps.num_tile_rows_minus1 {
848+ r.read_ue()?;
849+ }
850+ }
851+ pps.loop_filter_across_tiles_enabled = r.read_bit()?;
852+ }
853+ pps.loop_filter_across_slices_enabled = r.read_bit()?;
854+ pps.deblocking_filter_control_present = r.read_bit()?;
855+ if pps.deblocking_filter_control_present {
856+ pps.deblocking_filter_override_enabled = r.read_bit()?;
857+ pps.deblocking_filter_disabled = r.read_bit()?;
858+ if !pps.deblocking_filter_disabled {
859+ pps.beta_offset_div2 = r.read_se()?;
860+ pps.tc_offset_div2 = r.read_se()?;
861+ }
862+ }
863+ if r.read_bit()? {
864+ return Err(Error::unsupported(
865+ "HEVC PPS scaling lists",
866+ "this family codes with the flat 16 matrix only",
867+ ));
868+ }
869+ pps.lists_modification_present = r.read_bit()?;
870+ pps.log2_parallel_merge_level_minus2 = r.read_ue()?;
871+ pps.slice_segment_header_extension_present = r.read_bit()?;
872+ Ok(pps)
873+ }
874+}
875+
876+/// `rbsp_trailing_bits()`: a one bit then zeros to the byte boundary.
877+pub fn rbsp_trailing_bits(w: &mut BitWriter) {
878+ w.write_bit(true);
879+ w.align_to_byte();
880+}
881+
882+/// `Ceil( Log2( v ) )`, the width of a `u(v)` field counting `v` values.
883+pub fn ceil_log2(v: u32) -> u32 {
884+ let mut bits = 0;
885+ while (1u64 << bits) < u64::from(v) {
886+ bits += 1;
887+ }
888+ bits
889+}
890+
891+#[cfg(test)]
892+mod tests {
893+ use super::*;
894+ use crate::vui::{ColourDescription, VideoSignalType};
895+
896+ fn sample_sps() -> Sps {
897+ Sps {
898+ vps_id: 0,
899+ id: 0,
900+ chroma_format_idc: 1,
901+ separate_colour_plane: false,
902+ pic_width_in_luma_samples: 1920,
903+ pic_height_in_luma_samples: 1088,
904+ conf_win: ConformanceWindow {
905+ left: 0,
906+ right: 0,
907+ top: 0,
908+ bottom: 4,
909+ },
910+ bit_depth_luma_minus8: 0,
911+ bit_depth_chroma_minus8: 0,
912+ log2_max_poc_lsb_minus4: 4,
913+ max_dec_pic_buffering_minus1: 0,
914+ max_num_reorder_pics: 0,
915+ log2_min_cb_size_minus3: 0,
916+ log2_diff_max_min_cb_size: 3,
917+ log2_min_tb_size_minus2: 0,
918+ log2_diff_max_min_tb_size: 3,
919+ max_transform_hierarchy_depth_inter: 0,
920+ max_transform_hierarchy_depth_intra: 0,
921+ scaling_list_enabled: false,
922+ amp_enabled: false,
923+ sao_enabled: false,
924+ pcm_enabled: false,
925+ num_short_term_ref_pic_sets: 0,
926+ long_term_ref_pics_present: false,
927+ num_long_term_ref_pics_sps: 0,
928+ temporal_mvp_enabled: false,
929+ strong_intra_smoothing: true,
930+ ptl: ProfileTierLevel::main(120),
931+ vui: Some(VuiParameters {
932+ sample_aspect_ratio: Some((1, 1)),
933+ video_signal_type: Some(VideoSignalType {
934+ video_format: 5,
935+ video_full_range_flag: false,
936+ colour_description: Some(ColourDescription {
937+ colour_primaries: 1,
938+ transfer_characteristics: 1,
939+ matrix_coeffs: 1,
940+ }),
941+ }),
942+ timing: Some((1, 30)),
943+ }),
944+ }
945+ }
946+
947+ #[test]
948+ fn parameter_sets_round_trip() {
949+ let vps = Vps {
950+ id: 0,
951+ ptl: ProfileTierLevel::main(120),
952+ max_dec_pic_buffering_minus1: 0,
953+ max_num_reorder_pics: 0,
954+ };
955+ assert_eq!(Vps::parse(&vps.to_rbsp()).unwrap(), vps);
956+
957+ let sps = sample_sps();
958+ let parsed = Sps::parse(&sps.to_rbsp()).unwrap();
959+ assert_eq!(parsed, sps);
960+ // 1080 is cropped back out of the 1088 coded rows.
961+ assert_eq!(parsed.display_size(), (1920, 1080));
962+ assert_eq!(parsed.ctb_size(), 64);
963+ assert_eq!(parsed.pic_width_in_ctbs(), 30);
964+ assert_eq!(parsed.pic_height_in_ctbs(), 17);
965+
966+ let pps = Pps {
967+ entropy_coding_sync_enabled: true,
968+ init_qp_minus26: 1,
969+ deblocking_filter_control_present: true,
970+ deblocking_filter_disabled: true,
971+ ..Pps::default()
972+ };
973+ assert_eq!(Pps::parse(&pps.to_rbsp()).unwrap(), pps);
974+ }
975+
976+ #[test]
977+ fn levels_round_up_with_size_and_rate() {
978+ assert_eq!(ProfileTierLevel::level_for(1920, 1080, 30.0), 120); // 4
979+ assert_eq!(ProfileTierLevel::level_for(1920, 1080, 60.0), 123); // 4.1
980+ assert_eq!(ProfileTierLevel::level_for(3840, 2160, 30.0), 150); // 5
981+ assert_eq!(ProfileTierLevel::level_for(640, 480, 30.0), 90); // 3
982+ }
983+
984+ #[test]
985+ fn ceil_log2_counts_values() {
986+ assert_eq!(ceil_log2(1), 0);
987+ assert_eq!(ceil_log2(2), 1);
988+ assert_eq!(ceil_log2(510), 9);
989+ assert_eq!(ceil_log2(512), 9);
990+ assert_eq!(ceil_log2(513), 10);
991+ }
992+}
crates/ec-h265-syntax/src/sei.rsadded+151 -0
@@ -0,0 +1,151 @@
1+//! SEI messages: mastering display, content light level, decoded picture hash.
2+//!
3+//! Three messages, and each one is here because something downstream reads it.
4+//! The two HDR messages are what a tone map finds when the container lost its
5+//! metadata (see [`ec_core::color::hevc_sei_light`], which reads exactly these
6+//! payloads back). The decoded picture hash is the encoder's own oracle: an MD5
7+//! of the reconstructed picture, which any conformant decoder must reproduce, so
8+//! a mismatch is a *bit-exactness* failure report rather than a mystery.
9+
10+use crate::md5::Md5;
11+use crate::nal::{NalHeader, NalUnitType};
12+use crate::ps::rbsp_trailing_bits;
13+use ec_core::bitio::BitWriter;
14+use ec_core::color::ContentLight;
15+
16+/// `payloadType` values written here.
17+const PAYLOAD_MASTERING_DISPLAY: u32 = 137;
18+const PAYLOAD_CONTENT_LIGHT_LEVEL: u32 = 144;
19+const PAYLOAD_DECODED_PICTURE_HASH: u32 = 132;
20+
21+/// Build one SEI RBSP holding `messages`, each a `(payloadType, payload)` pair.
22+///
23+/// The `ff` byte run for sizes over 254 is written the way the spec spells it,
24+/// even though nothing here comes close: a hash message is 49 bytes.
25+fn sei_rbsp(messages: &[(u32, Vec<u8>)]) -> Vec<u8> {
26+ let mut w = BitWriter::with_capacity(64);
27+ for (payload_type, payload) in messages {
28+ let mut left = *payload_type;
29+ while left >= 255 {
30+ w.write_bits(0xff, 8);
31+ left -= 255;
32+ }
33+ w.write_bits(left, 8);
34+ let mut size = payload.len() as u32;
35+ while size >= 255 {
36+ w.write_bits(0xff, 8);
37+ size -= 255;
38+ }
39+ w.write_bits(size, 8);
40+ w.write_bytes(payload);
41+ }
42+ rbsp_trailing_bits(&mut w);
43+ w.into_bytes()
44+}
45+
46+/// The prefix SEI RBSP describing HDR mastering metadata, or `None` when there
47+/// is nothing to say.
48+///
49+/// Both messages are written whole or not at all: a `mastering_display_colour_volume`
50+/// with a zero luminance pair is what ffmpeg writes when it knows nothing, and a
51+/// tone map that believes it maps the film to black.
52+pub fn hdr_metadata_rbsp(light: ContentLight) -> Option<Vec<u8>> {
53+ let mut messages = Vec::new();
54+ if let (Some(max), Some(min)) = (light.mastering_max, light.mastering_min) {
55+ let mut payload = Vec::with_capacity(24);
56+ // The chromaticities are not modelled by this family (the tone map wants
57+ // the luminance pair), so BT.2020's are written: they are what an HDR
58+ // grade is approved on, and a decoder that reads them gets a true answer
59+ // rather than zeros.
60+ const BT2020_PRIMARIES: [(u16, u16); 3] =
61+ [(8500, 39_850), (6550, 2300), (35_400, 14_600)];
62+ const D65: (u16, u16) = (15_635, 16_450);
63+ for (x, y) in BT2020_PRIMARIES {
64+ payload.extend_from_slice(&x.to_be_bytes());
65+ payload.extend_from_slice(&y.to_be_bytes());
66+ }
67+ payload.extend_from_slice(&D65.0.to_be_bytes());
68+ payload.extend_from_slice(&D65.1.to_be_bytes());
69+ payload.extend_from_slice(&((max * 10_000.0) as u32).to_be_bytes());
70+ payload.extend_from_slice(&((min * 10_000.0) as u32).to_be_bytes());
71+ messages.push((PAYLOAD_MASTERING_DISPLAY, payload));
72+ }
73+ if let (Some(cll), Some(fall)) = (light.max_cll, light.max_fall) {
74+ let mut payload = Vec::with_capacity(4);
75+ payload.extend_from_slice(&(cll as u16).to_be_bytes());
76+ payload.extend_from_slice(&(fall as u16).to_be_bytes());
77+ messages.push((PAYLOAD_CONTENT_LIGHT_LEVEL, payload));
78+ }
79+ if messages.is_empty() {
80+ None
81+ } else {
82+ Some(sei_rbsp(&messages))
83+ }
84+}
85+
86+/// The suffix SEI RBSP carrying one MD5 per colour plane (D.2.20).
87+///
88+/// `planes` are the *reconstructed* planes in coding order, each as
89+/// `(samples, stride, width, height)` over the whole coded picture — the
90+/// conformance window is not applied, because the hash is defined over
91+/// `pic_width_in_luma_samples`.
92+pub fn decoded_picture_hash_rbsp(planes: &[(&[u8], usize, usize, usize)]) -> Vec<u8> {
93+ let mut payload = Vec::with_capacity(1 + 16 * planes.len());
94+ payload.push(0); // hash_type = MD5
95+ for &(data, stride, width, height) in planes {
96+ let mut md5 = Md5::new();
97+ for y in 0..height {
98+ md5.update(&data[y * stride..y * stride + width]);
99+ }
100+ payload.extend_from_slice(&md5.finish());
101+ }
102+ sei_rbsp(&[(PAYLOAD_DECODED_PICTURE_HASH, payload)])
103+}
104+
105+/// The NAL header a prefix SEI travels under.
106+pub fn prefix_sei_header() -> NalHeader {
107+ NalHeader::new(NalUnitType::PrefixSei)
108+}
109+
110+/// The NAL header a suffix SEI (the picture hash) travels under.
111+pub fn suffix_sei_header() -> NalHeader {
112+ NalHeader::new(NalUnitType::SuffixSei)
113+}
114+
115+#[cfg(test)]
116+mod tests {
117+ use super::*;
118+
119+ #[test]
120+ fn hdr_sei_reads_back_through_ec_core() {
121+ let light = ContentLight {
122+ max_cll: Some(1000.0),
123+ max_fall: Some(400.0),
124+ mastering_max: Some(1000.0),
125+ mastering_min: Some(0.005),
126+ };
127+ let rbsp = hdr_metadata_rbsp(light).unwrap();
128+ let mut annex_b = Vec::new();
129+ crate::nal::write_annex_b(&mut annex_b, prefix_sei_header(), &rbsp, true);
130+ // ec-core's reader is the consumer this exists for.
131+ let read = ec_core::color::hevc_sei_light(&annex_b);
132+ assert_eq!(read.max_cll, Some(1000.0));
133+ assert_eq!(read.max_fall, Some(400.0));
134+ assert_eq!(read.mastering_max, Some(1000.0));
135+ assert_eq!(read.mastering_min, Some(0.005));
136+ assert!(hdr_metadata_rbsp(ContentLight::default()).is_none());
137+ }
138+
139+ #[test]
140+ fn picture_hash_is_md5_of_each_plane() {
141+ let luma = vec![7u8; 16 * 16];
142+ let rbsp = decoded_picture_hash_rbsp(&[(&luma, 16, 16, 16)]);
143+ // payloadType 132, payloadSize 17, hash_type 0, then the digest.
144+ assert_eq!(rbsp[0], 132);
145+ assert_eq!(rbsp[1], 17);
146+ assert_eq!(rbsp[2], 0);
147+ let mut md5 = Md5::new();
148+ md5.update(&luma);
149+ assert_eq!(&rbsp[3..19], &md5.finish()[..]);
150+ }
151+}
crates/ec-h265-syntax/src/slice.rsadded+553 -0
@@ -0,0 +1,553 @@
1+//! The slice segment header (7.3.6.1).
2+
3+use crate::nal::NalUnitType;
4+use crate::ps::{Pps, ShortTermRefPicSet, Sps, ceil_log2};
5+use ec_core::bitio::{BitReader, BitWriter};
6+use ec_core::error::{Error, Result};
7+
8+/// `slice_type`.
9+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10+pub enum SliceType {
11+ /// Bi-predictive.
12+ B,
13+ /// Predictive.
14+ P,
15+ /// Intra — the only kind this family's HEVC encoder writes.
16+ I,
17+}
18+
19+impl SliceType {
20+ /// The wire value (`B` = 0, `P` = 1, `I` = 2).
21+ pub fn code(self) -> u32 {
22+ match self {
23+ SliceType::B => 0,
24+ SliceType::P => 1,
25+ SliceType::I => 2,
26+ }
27+ }
28+
29+ /// The type for a wire value.
30+ pub fn from_code(code: u32) -> Result<SliceType> {
31+ match code {
32+ 0 => Ok(SliceType::B),
33+ 1 => Ok(SliceType::P),
34+ 2 => Ok(SliceType::I),
35+ v => Err(Error::corrupt(format!("HEVC slice: slice_type = {v}"))),
36+ }
37+ }
38+}
39+
40+/// A slice segment header, as far as an intra encoder writes one and a
41+/// stateless hardware decoder reads one.
42+#[derive(Debug, Clone, PartialEq, Eq)]
43+pub struct SliceHeader {
44+ /// `first_slice_segment_in_pic_flag`.
45+ pub first_slice_segment_in_pic: bool,
46+ /// `no_output_of_prior_pics_flag`, present on IRAP pictures only.
47+ pub no_output_of_prior_pics: bool,
48+ /// `slice_pic_parameter_set_id`.
49+ pub pps_id: u32,
50+ /// `dependent_slice_segment_flag`.
51+ pub dependent_slice_segment: bool,
52+ /// `slice_segment_address` in CTB raster order.
53+ pub segment_address: u32,
54+ /// `slice_type`.
55+ pub slice_type: SliceType,
56+ /// `pic_output_flag`, when the PPS says it is present.
57+ pub pic_output_flag: bool,
58+ /// `slice_pic_order_cnt_lsb`; absent (0) on IDR pictures.
59+ pub poc_lsb: u32,
60+ /// `slice_sao_luma_flag`.
61+ pub sao_luma: bool,
62+ /// `slice_sao_chroma_flag`.
63+ pub sao_chroma: bool,
64+ /// `num_ref_idx_l0_active_minus1` in force for this slice.
65+ pub num_ref_idx_l0_active_minus1: u32,
66+ /// `num_ref_idx_l1_active_minus1` in force for this slice.
67+ pub num_ref_idx_l1_active_minus1: u32,
68+ /// `mvd_l1_zero_flag`.
69+ pub mvd_l1_zero: bool,
70+ /// `cabac_init_flag`.
71+ pub cabac_init: bool,
72+ /// `slice_temporal_mvp_enabled_flag`.
73+ pub temporal_mvp_enabled: bool,
74+ /// `collocated_from_l0_flag`.
75+ pub collocated_from_l0: bool,
76+ /// `collocated_ref_idx`.
77+ pub collocated_ref_idx: u32,
78+ /// `five_minus_max_num_merge_cand`.
79+ pub five_minus_max_num_merge_cand: u32,
80+ /// `slice_qp_delta`: the slice QP is `26 + init_qp_minus26 + this`.
81+ pub qp_delta: i32,
82+ /// `slice_cb_qp_offset`.
83+ pub cb_qp_offset: i32,
84+ /// `slice_cr_qp_offset`.
85+ pub cr_qp_offset: i32,
86+ /// `slice_deblocking_filter_disabled_flag`, after any override.
87+ pub deblocking_filter_disabled: bool,
88+ /// `slice_beta_offset_div2`.
89+ pub beta_offset_div2: i32,
90+ /// `slice_tc_offset_div2`.
91+ pub tc_offset_div2: i32,
92+ /// `slice_loop_filter_across_slices_enabled_flag`.
93+ pub loop_filter_across_slices_enabled: bool,
94+ /// Substream entry points: one per WPP CTB row (or tile) after the first.
95+ pub entry_point_offsets: Vec<u32>,
96+}
97+
98+impl SliceHeader {
99+ /// An I slice covering a whole picture at `qp_delta`, filters off.
100+ pub fn intra(pps: &Pps, qp_delta: i32) -> SliceHeader {
101+ SliceHeader {
102+ first_slice_segment_in_pic: true,
103+ no_output_of_prior_pics: false,
104+ pps_id: pps.id,
105+ dependent_slice_segment: false,
106+ segment_address: 0,
107+ slice_type: SliceType::I,
108+ pic_output_flag: true,
109+ poc_lsb: 0,
110+ sao_luma: false,
111+ sao_chroma: false,
112+ num_ref_idx_l0_active_minus1: 0,
113+ num_ref_idx_l1_active_minus1: 0,
114+ mvd_l1_zero: false,
115+ cabac_init: false,
116+ temporal_mvp_enabled: false,
117+ collocated_from_l0: true,
118+ collocated_ref_idx: 0,
119+ five_minus_max_num_merge_cand: 0,
120+ qp_delta,
121+ cb_qp_offset: 0,
122+ cr_qp_offset: 0,
123+ deblocking_filter_disabled: pps.deblocking_filter_disabled,
124+ beta_offset_div2: 0,
125+ tc_offset_div2: 0,
126+ loop_filter_across_slices_enabled: pps.loop_filter_across_slices_enabled,
127+ entry_point_offsets: Vec::new(),
128+ }
129+ }
130+
131+ /// Write the header, up to and including `byte_alignment()`.
132+ ///
133+ /// Entry point offsets are written from `self.entry_point_offsets`, so a WPP
134+ /// encoder codes its substreams first and builds the header afterwards —
135+ /// the offsets are not knowable any earlier.
136+ pub fn write(&self, w: &mut BitWriter, sps: &Sps, pps: &Pps, nal_type: NalUnitType) {
137+ w.write_bit(self.first_slice_segment_in_pic);
138+ if nal_type.is_irap() {
139+ w.write_bit(self.no_output_of_prior_pics);
140+ }
141+ w.write_ue(self.pps_id);
142+ if !self.first_slice_segment_in_pic {
143+ if pps.dependent_slice_segments_enabled {
144+ w.write_bit(self.dependent_slice_segment);
145+ }
146+ w.write_bits(self.segment_address, sps.slice_address_bits());
147+ }
148+ if !self.dependent_slice_segment {
149+ for _ in 0..pps.num_extra_slice_header_bits {
150+ w.write_bit(false);
151+ }
152+ w.write_ue(self.slice_type.code());
153+ if pps.output_flag_present {
154+ w.write_bit(self.pic_output_flag);
155+ }
156+ if !nal_type.is_idr() {
157+ w.write_bits(self.poc_lsb, sps.log2_max_poc_lsb_minus4 + 4);
158+ // An intra encoder writes no reference picture sets at all; a
159+ // non-IDR picture from this family does not exist yet.
160+ w.write_bit(true); // short_term_ref_pic_set_sps_flag
161+ if sps.num_short_term_ref_pic_sets > 1 {
162+ w.write_bits(0, ceil_log2(sps.num_short_term_ref_pic_sets));
163+ }
164+ if sps.temporal_mvp_enabled {
165+ w.write_bit(self.temporal_mvp_enabled);
166+ }
167+ }
168+ if sps.sao_enabled {
169+ w.write_bit(self.sao_luma);
170+ if sps.chroma_format_idc != 0 {
171+ w.write_bit(self.sao_chroma);
172+ }
173+ }
174+ if self.slice_type != SliceType::I {
175+ w.write_bit(false); // num_ref_idx_active_override_flag
176+ if self.slice_type == SliceType::B {
177+ w.write_bit(self.mvd_l1_zero);
178+ }
179+ if pps.cabac_init_present {
180+ w.write_bit(self.cabac_init);
181+ }
182+ w.write_ue(self.five_minus_max_num_merge_cand);
183+ }
184+ w.write_se(self.qp_delta);
185+ if pps.slice_chroma_qp_offsets_present {
186+ w.write_se(self.cb_qp_offset);
187+ w.write_se(self.cr_qp_offset);
188+ }
189+ if pps.deblocking_filter_override_enabled {
190+ w.write_bit(false); // deblocking_filter_override_flag
191+ }
192+ if pps.loop_filter_across_slices_enabled
193+ && (self.sao_luma || self.sao_chroma || !self.deblocking_filter_disabled)
194+ {
195+ w.write_bit(self.loop_filter_across_slices_enabled);
196+ }
197+ }
198+ if pps.tiles_enabled || pps.entropy_coding_sync_enabled {
199+ w.write_ue(self.entry_point_offsets.len() as u32);
200+ if !self.entry_point_offsets.is_empty() {
201+ let max = self.entry_point_offsets.iter().copied().max().unwrap_or(1);
202+ let offset_len = ceil_log2(max + 1).max(1);
203+ w.write_ue(offset_len - 1);
204+ for &offset in &self.entry_point_offsets {
205+ w.write_bits(offset - 1, offset_len);
206+ }
207+ }
208+ }
209+ // byte_alignment(): a one bit then zeros.
210+ w.write_bit(true);
211+ w.align_to_byte();
212+ }
213+
214+ /// Parse a slice segment header out of an unescaped slice NAL payload.
215+ ///
216+ /// Returns the header and the bit position where slice data begins — what
217+ /// `VASliceParameterBufferHEVC::slice_data_byte_offset` is derived from.
218+ pub fn parse(
219+ rbsp: &[u8],
220+ sps: &Sps,
221+ pps: &Pps,
222+ nal_type: NalUnitType,
223+ ) -> Result<(SliceHeader, ParsePositions)> {
224+ let mut r = BitReader::new(rbsp);
225+ let mut h = SliceHeader::intra(pps, 0);
226+ let mut pos = ParsePositions::default();
227+ h.first_slice_segment_in_pic = r.read_bit()?;
228+ if nal_type.is_irap() {
229+ h.no_output_of_prior_pics = r.read_bit()?;
230+ }
231+ h.pps_id = r.read_ue()?;
232+ if !h.first_slice_segment_in_pic {
233+ if pps.dependent_slice_segments_enabled {
234+ h.dependent_slice_segment = r.read_bit()?;
235+ }
236+ h.segment_address = r.read_bits(sps.slice_address_bits())?;
237+ }
238+ if !h.dependent_slice_segment {
239+ for _ in 0..pps.num_extra_slice_header_bits {
240+ r.read_bit()?;
241+ }
242+ h.slice_type = SliceType::from_code(r.read_ue()?)?;
243+ if pps.output_flag_present {
244+ h.pic_output_flag = r.read_bit()?;
245+ }
246+ if sps.separate_colour_plane {
247+ r.read_bits(2)?; // colour_plane_id
248+ }
249+ let mut st_rps = ShortTermRefPicSet::default();
250+ let mut num_long_term = 0;
251+ if !nal_type.is_idr() {
252+ h.poc_lsb = r.read_bits(sps.log2_max_poc_lsb_minus4 + 4)?;
253+ let from_sps = r.read_bit()?;
254+ let before = r.bit_position();
255+ if !from_sps {
256+ // The sets in the SPS are not kept, so an inter-set
257+ // predicted slice set cannot be resolved here.
258+ st_rps = ShortTermRefPicSet::parse(&mut r, 0, &[])?;
259+ } else if sps.num_short_term_ref_pic_sets > 1 {
260+ r.read_bits(ceil_log2(sps.num_short_term_ref_pic_sets))?;
261+ }
262+ pos.st_rps_bits = (r.bit_position() - before) as u32;
263+ if sps.long_term_ref_pics_present {
264+ let num_long_term_sps = if sps.num_long_term_ref_pics_sps > 0 {
265+ r.read_ue()?
266+ } else {
267+ 0
268+ };
269+ let num_long_term_pics = r.read_ue()?;
270+ for i in 0..num_long_term_sps + num_long_term_pics {
271+ if i < num_long_term_sps {
272+ if sps.num_long_term_ref_pics_sps > 1 {
273+ r.read_bits(ceil_log2(sps.num_long_term_ref_pics_sps))?;
274+ }
275+ num_long_term += 1;
276+ } else {
277+ r.read_bits(sps.log2_max_poc_lsb_minus4 + 4)?; // poc_lsb_lt
278+ if r.read_bit()? {
279+ num_long_term += 1; // used_by_curr_pic_lt_flag
280+ }
281+ }
282+ if r.read_bit()? {
283+ r.read_ue()?; // delta_poc_msb_cycle_lt
284+ }
285+ }
286+ }
287+ if sps.temporal_mvp_enabled {
288+ h.temporal_mvp_enabled = r.read_bit()?;
289+ }
290+ }
291+ if sps.sao_enabled {
292+ h.sao_luma = r.read_bit()?;
293+ if sps.chroma_format_idc != 0 {
294+ h.sao_chroma = r.read_bit()?;
295+ }
296+ }
297+ if h.slice_type != SliceType::I {
298+ h.num_ref_idx_l0_active_minus1 = pps.num_ref_idx_l0_default_active_minus1;
299+ h.num_ref_idx_l1_active_minus1 = pps.num_ref_idx_l1_default_active_minus1;
300+ if r.read_bit()? {
301+ h.num_ref_idx_l0_active_minus1 = r.read_ue()?;
302+ if h.slice_type == SliceType::B {
303+ h.num_ref_idx_l1_active_minus1 = r.read_ue()?;
304+ }
305+ }
306+ let num_pic_total_curr = st_rps.num_used_by_curr + num_long_term;
307+ if pps.lists_modification_present && num_pic_total_curr > 1 {
308+ let bits = ceil_log2(num_pic_total_curr);
309+ if r.read_bit()? {
310+ for _ in 0..=h.num_ref_idx_l0_active_minus1 {
311+ r.read_bits(bits)?;
312+ }
313+ }
314+ if h.slice_type == SliceType::B && r.read_bit()? {
315+ for _ in 0..=h.num_ref_idx_l1_active_minus1 {
316+ r.read_bits(bits)?;
317+ }
318+ }
319+ }
320+ if h.slice_type == SliceType::B {
321+ h.mvd_l1_zero = r.read_bit()?;
322+ }
323+ if pps.cabac_init_present {
324+ h.cabac_init = r.read_bit()?;
325+ }
326+ if h.temporal_mvp_enabled {
327+ if h.slice_type == SliceType::B {
328+ h.collocated_from_l0 = r.read_bit()?;
329+ }
330+ if (h.collocated_from_l0 && h.num_ref_idx_l0_active_minus1 > 0)
331+ || (!h.collocated_from_l0 && h.num_ref_idx_l1_active_minus1 > 0)
332+ {
333+ h.collocated_ref_idx = r.read_ue()?;
334+ }
335+ }
336+ if (pps.weighted_pred && h.slice_type == SliceType::P)
337+ || (pps.weighted_bipred && h.slice_type == SliceType::B)
338+ {
339+ skip_pred_weight_table(&mut r, &h, sps)?;
340+ }
341+ h.five_minus_max_num_merge_cand = r.read_ue()?;
342+ }
343+ h.qp_delta = r.read_se()?;
344+ if pps.slice_chroma_qp_offsets_present {
345+ h.cb_qp_offset = r.read_se()?;
346+ h.cr_qp_offset = r.read_se()?;
347+ }
348+ h.deblocking_filter_disabled = pps.deblocking_filter_disabled;
349+ h.beta_offset_div2 = pps.beta_offset_div2;
350+ h.tc_offset_div2 = pps.tc_offset_div2;
351+ if pps.deblocking_filter_override_enabled && r.read_bit()? {
352+ h.deblocking_filter_disabled = r.read_bit()?;
353+ if !h.deblocking_filter_disabled {
354+ h.beta_offset_div2 = r.read_se()?;
355+ h.tc_offset_div2 = r.read_se()?;
356+ }
357+ }
358+ h.loop_filter_across_slices_enabled = pps.loop_filter_across_slices_enabled;
359+ if pps.loop_filter_across_slices_enabled
360+ && (h.sao_luma || h.sao_chroma || !h.deblocking_filter_disabled)
361+ {
362+ h.loop_filter_across_slices_enabled = r.read_bit()?;
363+ }
364+ }
365+ if pps.tiles_enabled || pps.entropy_coding_sync_enabled {
366+ let count = r.read_ue()?;
367+ if count > 0 {
368+ if count as u64 > sps.pic_height_in_ctbs() as u64 * sps.pic_width_in_ctbs() as u64 {
369+ return Err(Error::corrupt("HEVC slice: num_entry_point_offsets absurd"));
370+ }
371+ let offset_len = r.read_ue()? + 1;
372+ if offset_len > 32 {
373+ return Err(Error::corrupt("HEVC slice: offset_len_minus1 > 31"));
374+ }
375+ for _ in 0..count {
376+ h.entry_point_offsets.push(r.read_bits(offset_len)? + 1);
377+ }
378+ }
379+ }
380+ if pps.slice_segment_header_extension_present {
381+ let len = r.read_ue()?;
382+ for _ in 0..len {
383+ r.read_bits(8)?;
384+ }
385+ }
386+ // byte_alignment()
387+ if !r.read_bit()? {
388+ return Err(Error::corrupt("HEVC slice: alignment_bit_equal_to_one = 0"));
389+ }
390+ r.align_to_byte();
391+ pos.header_bits = r.bit_position();
392+ Ok((h, pos))
393+ }
394+}
395+
396+/// Where the slice header ended, in the units a hardware decoder wants.
397+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
398+pub struct ParsePositions {
399+ /// Bit position in the *unescaped* RBSP where slice data starts; always a
400+ /// multiple of 8.
401+ pub header_bits: u64,
402+ /// `st_rps_bits`: the size of the `st_ref_pic_set()` in the slice header,
403+ /// which `VAPictureParameterBufferHEVC` carries so the driver can skip it.
404+ pub st_rps_bits: u32,
405+}
406+
407+impl ParsePositions {
408+ /// `slice_data_byte_offset`: the offset from the start of the NAL unit
409+ /// (header bytes included) to the first byte of slice data, counted in the
410+ /// *escaped* bytes a driver is handed.
411+ ///
412+ /// The emulation prevention bytes inside the header count, which is why this
413+ /// takes the escaped payload rather than working from `header_bits` alone.
414+ pub fn slice_data_byte_offset(&self, escaped_payload: &[u8]) -> usize {
415+ let rbsp_bytes = (self.header_bits / 8) as usize;
416+ let mut zeros = 0usize;
417+ let mut rbsp_seen = 0usize;
418+ let mut escaped_seen = 0usize;
419+ for &b in escaped_payload {
420+ escaped_seen += 1;
421+ if zeros >= 2 && b == 3 {
422+ zeros = 0;
423+ continue;
424+ }
425+ rbsp_seen += 1;
426+ if b == 0 {
427+ zeros += 1;
428+ } else {
429+ zeros = 0;
430+ }
431+ if rbsp_seen == rbsp_bytes {
432+ break;
433+ }
434+ }
435+ // 2 = the NAL unit header, which the offset is measured from.
436+ 2 + escaped_seen
437+ }
438+}
439+
440+/// Walk past a `pred_weight_table()` (7.3.6.3).
441+fn skip_pred_weight_table(r: &mut BitReader, h: &SliceHeader, sps: &Sps) -> Result<()> {
442+ r.read_ue()?; // luma_log2_weight_denom
443+ let chroma = sps.chroma_format_idc != 0;
444+ if chroma {
445+ r.read_se()?; // delta_chroma_log2_weight_denom
446+ }
447+ let lists: &[u32] = if h.slice_type == SliceType::B {
448+ &[h.num_ref_idx_l0_active_minus1, h.num_ref_idx_l1_active_minus1]
449+ } else {
450+ &[h.num_ref_idx_l0_active_minus1]
451+ };
452+ for &active_minus1 in lists {
453+ let count = active_minus1 + 1;
454+ let mut luma_flags = Vec::with_capacity(count as usize);
455+ for _ in 0..count {
456+ luma_flags.push(r.read_bit()?);
457+ }
458+ let mut chroma_flags = Vec::with_capacity(count as usize);
459+ if chroma {
460+ for _ in 0..count {
461+ chroma_flags.push(r.read_bit()?);
462+ }
463+ }
464+ for i in 0..count as usize {
465+ if luma_flags[i] {
466+ r.read_se()?; // delta_luma_weight
467+ r.read_se()?; // luma_offset
468+ }
469+ if chroma && chroma_flags[i] {
470+ for _ in 0..2 {
471+ r.read_se()?; // delta_chroma_weight
472+ r.read_se()?; // delta_chroma_offset
473+ }
474+ }
475+ }
476+ }
477+ Ok(())
478+}
479+
480+#[cfg(test)]
481+mod tests {
482+ use super::*;
483+ use crate::ps::{ConformanceWindow, ProfileTierLevel};
484+
485+ fn sps() -> Sps {
486+ Sps {
487+ vps_id: 0,
488+ id: 0,
489+ chroma_format_idc: 1,
490+ separate_colour_plane: false,
491+ pic_width_in_luma_samples: 1920,
492+ pic_height_in_luma_samples: 1088,
493+ conf_win: ConformanceWindow::default(),
494+ bit_depth_luma_minus8: 0,
495+ bit_depth_chroma_minus8: 0,
496+ log2_max_poc_lsb_minus4: 4,
497+ max_dec_pic_buffering_minus1: 0,
498+ max_num_reorder_pics: 0,
499+ log2_min_cb_size_minus3: 0,
500+ log2_diff_max_min_cb_size: 3,
501+ log2_min_tb_size_minus2: 0,
502+ log2_diff_max_min_tb_size: 3,
503+ max_transform_hierarchy_depth_inter: 0,
504+ max_transform_hierarchy_depth_intra: 0,
505+ scaling_list_enabled: false,
506+ amp_enabled: false,
507+ sao_enabled: false,
508+ pcm_enabled: false,
509+ num_short_term_ref_pic_sets: 0,
510+ long_term_ref_pics_present: false,
511+ num_long_term_ref_pics_sps: 0,
512+ temporal_mvp_enabled: false,
513+ strong_intra_smoothing: true,
514+ ptl: ProfileTierLevel::main(120),
515+ vui: None,
516+ }
517+ }
518+
519+ #[test]
520+ fn intra_slice_header_round_trips_with_entry_points() {
521+ let pps = Pps {
522+ entropy_coding_sync_enabled: true,
523+ deblocking_filter_control_present: true,
524+ deblocking_filter_disabled: true,
525+ ..Pps::default()
526+ };
527+ let sps = sps();
528+ let mut header = SliceHeader::intra(&pps, -3);
529+ header.entry_point_offsets = vec![1234, 9, 65_540];
530+ let mut w = BitWriter::new();
531+ header.write(&mut w, &sps, &pps, NalUnitType::IdrWRadl);
532+ let rbsp = w.into_bytes();
533+ let (parsed, pos) = SliceHeader::parse(&rbsp, &sps, &pps, NalUnitType::IdrWRadl).unwrap();
534+ assert_eq!(parsed, header);
535+ assert_eq!(pos.header_bits % 8, 0);
536+ assert_eq!(pos.header_bits as usize / 8, rbsp.len());
537+ // No emulation prevention in this header, so the byte offset is the
538+ // NAL header plus the RBSP header bytes.
539+ assert_eq!(pos.slice_data_byte_offset(&rbsp), 2 + rbsp.len());
540+ }
541+
542+ #[test]
543+ fn byte_offset_counts_escape_bytes() {
544+ // RBSP 00 00 01 ... escapes to 00 00 03 01 ...; a header of four RBSP
545+ // bytes therefore ends five escaped bytes in.
546+ let pos = ParsePositions {
547+ header_bits: 4 * 8,
548+ st_rps_bits: 0,
549+ };
550+ let escaped = [0u8, 0, 3, 1, 0xff];
551+ assert_eq!(pos.slice_data_byte_offset(&escaped), 2 + 5);
552+ }
553+}
crates/ec-h265-syntax/src/vui.rsadded+288 -0
@@ -0,0 +1,288 @@
1+//! VUI parameters — the part of an SPS that says what the samples *mean*.
2+
3+use ec_core::bitio::{BitReader, BitWriter};
4+use ec_core::color::ColorDescription;
5+use ec_core::error::Result;
6+
7+/// `colour_primaries`, `transfer_characteristics`, `matrix_coeffs` (H.273 code
8+/// points), carried verbatim.
9+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
10+pub struct ColourDescription {
11+ /// `colour_primaries`: 1 = BT.709, 9 = BT.2020.
12+ pub colour_primaries: u8,
13+ /// `transfer_characteristics`: 1 = BT.709, 16 = PQ, 18 = HLG.
14+ pub transfer_characteristics: u8,
15+ /// `matrix_coeffs`: 1 = BT.709, 9 = BT.2020 non-constant luminance.
16+ pub matrix_coeffs: u8,
17+}
18+
19+impl ColourDescription {
20+ /// The three code points a [`ColorDescription`] resolves to.
21+ ///
22+ /// This is the bridge that keeps the bitstream and the container from
23+ /// drifting apart: both sides come from the same H.273 resolution in
24+ /// [`ec_core::color`].
25+ pub fn from_color(color: ColorDescription) -> ColourDescription {
26+ let (primaries, transfer, matrix) = color.codes();
27+ ColourDescription {
28+ colour_primaries: primaries as u8,
29+ transfer_characteristics: transfer as u8,
30+ matrix_coeffs: matrix as u8,
31+ }
32+ }
33+}
34+
35+/// `video_signal_type` and the colour description under it.
36+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37+pub struct VideoSignalType {
38+ /// The analogue system a picture came off; 5 ("unspecified") for anything
39+ /// this family encodes, because none of it did.
40+ pub video_format: u8,
41+ /// False = limited range (16..235), true = full range.
42+ pub video_full_range_flag: bool,
43+ /// The H.273 code points, when stated.
44+ pub colour_description: Option<ColourDescription>,
45+}
46+
47+impl Default for VideoSignalType {
48+ fn default() -> Self {
49+ VideoSignalType {
50+ video_format: 5,
51+ video_full_range_flag: false,
52+ colour_description: None,
53+ }
54+ }
55+}
56+
57+/// The VUI fields this family writes and reads (E.2.1).
58+///
59+/// Everything absent here is written as "not present"; an HRD block in
60+/// particular is deliberately never written, since nothing downstream reads one
61+/// and a wrong one is worse than none.
62+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
63+pub struct VuiParameters {
64+ /// Sample aspect ratio as `aspect_ratio_idc`, or `Some((w, h))` for the
65+ /// extended form.
66+ pub sample_aspect_ratio: Option<(u16, u16)>,
67+ /// What the samples mean.
68+ pub video_signal_type: Option<VideoSignalType>,
69+ /// `(num_units_in_tick, time_scale)`: a rational frame rate, exact.
70+ pub timing: Option<(u32, u32)>,
71+}
72+
73+impl VuiParameters {
74+ /// Write `vui_parameters()`.
75+ pub fn write(&self, w: &mut BitWriter) {
76+ match self.sample_aspect_ratio {
77+ Some((sw, sh)) => {
78+ w.write_bit(true);
79+ w.write_bits(255, 8); // EXTENDED_SAR
80+ w.write_bits(u32::from(sw), 16);
81+ w.write_bits(u32::from(sh), 16);
82+ }
83+ None => w.write_bit(false),
84+ }
85+ w.write_bit(false); // overscan_info_present_flag
86+ match self.video_signal_type {
87+ Some(vst) => {
88+ w.write_bit(true);
89+ w.write_bits(u32::from(vst.video_format), 3);
90+ w.write_bit(vst.video_full_range_flag);
91+ match vst.colour_description {
92+ Some(cd) => {
93+ w.write_bit(true);
94+ w.write_bits(u32::from(cd.colour_primaries), 8);
95+ w.write_bits(u32::from(cd.transfer_characteristics), 8);
96+ w.write_bits(u32::from(cd.matrix_coeffs), 8);
97+ }
98+ None => w.write_bit(false),
99+ }
100+ }
101+ None => w.write_bit(false),
102+ }
103+ w.write_bit(false); // chroma_loc_info_present_flag
104+ w.write_bit(false); // neutral_chroma_indication_flag
105+ w.write_bit(false); // field_seq_flag
106+ w.write_bit(false); // frame_field_info_present_flag
107+ w.write_bit(false); // default_display_window_flag
108+ match self.timing {
109+ Some((units, scale)) => {
110+ w.write_bit(true);
111+ w.write_bits(units, 32);
112+ w.write_bits(scale, 32);
113+ w.write_bit(false); // vui_poc_proportional_to_timing_flag
114+ w.write_bit(false); // vui_hrd_parameters_present_flag
115+ }
116+ None => w.write_bit(false),
117+ }
118+ w.write_bit(false); // bitstream_restriction_flag
119+ }
120+
121+ /// Parse `vui_parameters()`, skipping past the parts not modelled.
122+ pub fn parse(r: &mut BitReader, max_sub_layers_minus1: u32) -> Result<VuiParameters> {
123+ let mut vui = VuiParameters::default();
124+ if r.read_bit()? {
125+ let idc = r.read_bits(8)?;
126+ if idc == 255 {
127+ let sw = r.read_bits(16)? as u16;
128+ let sh = r.read_bits(16)? as u16;
129+ vui.sample_aspect_ratio = Some((sw, sh));
130+ }
131+ }
132+ if r.read_bit()? {
133+ r.read_bit()?; // overscan_appropriate_flag
134+ }
135+ if r.read_bit()? {
136+ let video_format = r.read_bits(3)? as u8;
137+ let video_full_range_flag = r.read_bit()?;
138+ let colour_description = if r.read_bit()? {
139+ Some(ColourDescription {
140+ colour_primaries: r.read_bits(8)? as u8,
141+ transfer_characteristics: r.read_bits(8)? as u8,
142+ matrix_coeffs: r.read_bits(8)? as u8,
143+ })
144+ } else {
145+ None
146+ };
147+ vui.video_signal_type = Some(VideoSignalType {
148+ video_format,
149+ video_full_range_flag,
150+ colour_description,
151+ });
152+ }
153+ if r.read_bit()? {
154+ r.read_ue()?;
155+ r.read_ue()?;
156+ }
157+ r.read_bit()?; // neutral_chroma_indication_flag
158+ r.read_bit()?; // field_seq_flag
159+ r.read_bit()?; // frame_field_info_present_flag
160+ if r.read_bit()? {
161+ for _ in 0..4 {
162+ r.read_ue()?;
163+ }
164+ }
165+ if r.read_bit()? {
166+ let units = r.read_bits(32)?;
167+ let scale = r.read_bits(32)?;
168+ vui.timing = Some((units, scale));
169+ if r.read_bit()? {
170+ r.read_ue()?;
171+ }
172+ if r.read_bit()? {
173+ skip_hrd_parameters(r, true, max_sub_layers_minus1)?;
174+ }
175+ }
176+ if r.read_bit()? {
177+ r.read_bit()?;
178+ r.read_bit()?;
179+ r.read_bit()?;
180+ for _ in 0..5 {
181+ r.read_ue()?;
182+ }
183+ }
184+ Ok(vui)
185+ }
186+}
187+
188+/// Walk past an `hrd_parameters()` block (E.2.2) without modelling it.
189+fn skip_hrd_parameters(
190+ r: &mut BitReader,
191+ common_inf_present: bool,
192+ max_sub_layers_minus1: u32,
193+) -> Result<()> {
194+ let mut nal_hrd = false;
195+ let mut vcl_hrd = false;
196+ let mut sub_pic_hrd = false;
197+ if common_inf_present {
198+ nal_hrd = r.read_bit()?;
199+ vcl_hrd = r.read_bit()?;
200+ if nal_hrd || vcl_hrd {
201+ sub_pic_hrd = r.read_bit()?;
202+ if sub_pic_hrd {
203+ r.read_bits(8)?; // tick_divisor_minus2
204+ r.read_bits(5)?; // du_cpb_removal_delay_increment_length_minus1
205+ r.read_bit()?; // sub_pic_cpb_params_in_pic_timing_sei_flag
206+ r.read_bits(5)?; // dpb_output_delay_du_length_minus1
207+ }
208+ r.read_bits(4)?; // bit_rate_scale
209+ r.read_bits(4)?; // cpb_size_scale
210+ if sub_pic_hrd {
211+ r.read_bits(4)?; // cpb_size_du_scale
212+ }
213+ r.read_bits(5)?; // initial_cpb_removal_delay_length_minus1
214+ r.read_bits(5)?; // au_cpb_removal_delay_length_minus1
215+ r.read_bits(5)?; // dpb_output_delay_length_minus1
216+ }
217+ }
218+ for _ in 0..=max_sub_layers_minus1 {
219+ let fixed_pic_rate_general = r.read_bit()?;
220+ let mut fixed_pic_rate_within_cvs = fixed_pic_rate_general;
221+ if !fixed_pic_rate_general {
222+ fixed_pic_rate_within_cvs = r.read_bit()?;
223+ }
224+ let mut low_delay = false;
225+ if fixed_pic_rate_within_cvs {
226+ r.read_ue()?; // elemental_duration_in_tc_minus1
227+ } else {
228+ low_delay = r.read_bit()?;
229+ }
230+ let mut cpb_cnt = 1u32;
231+ if !low_delay {
232+ cpb_cnt = r.read_ue()? + 1;
233+ }
234+ for present in [nal_hrd, vcl_hrd] {
235+ if !present {
236+ continue;
237+ }
238+ for _ in 0..cpb_cnt {
239+ r.read_ue()?; // bit_rate_value_minus1
240+ r.read_ue()?; // cpb_size_value_minus1
241+ if sub_pic_hrd {
242+ r.read_ue()?; // cpb_size_du_value_minus1
243+ r.read_ue()?; // bit_rate_du_value_minus1
244+ }
245+ r.read_bit()?; // cbr_flag
246+ }
247+ }
248+ }
249+ Ok(())
250+}
251+
252+#[cfg(test)]
253+mod tests {
254+ use super::*;
255+
256+ #[test]
257+ fn vui_round_trips() {
258+ let vui = VuiParameters {
259+ sample_aspect_ratio: Some((1, 1)),
260+ video_signal_type: Some(VideoSignalType {
261+ video_format: 5,
262+ video_full_range_flag: false,
263+ colour_description: Some(ColourDescription {
264+ colour_primaries: 1,
265+ transfer_characteristics: 1,
266+ matrix_coeffs: 1,
267+ }),
268+ }),
269+ timing: Some((1001, 60_000)),
270+ };
271+ let mut w = BitWriter::new();
272+ vui.write(&mut w);
273+ w.align_to_byte();
274+ let bytes = w.into_bytes();
275+ let mut r = BitReader::new(&bytes);
276+ assert_eq!(VuiParameters::parse(&mut r, 0).unwrap(), vui);
277+
278+ // Every export this family writes declares itself SDR: 709 above 720
279+ // lines and 601 below, which is the rule ec-core states, not a guess
280+ // made here.
281+ for height in [1080, 2160] {
282+ let cd = ColourDescription::from_color(ColorDescription::output(height));
283+ assert_eq!((cd.colour_primaries, cd.transfer_characteristics, cd.matrix_coeffs), (1, 1, 1));
284+ }
285+ let cd = ColourDescription::from_color(ColorDescription::output(480));
286+ assert_eq!((cd.colour_primaries, cd.matrix_coeffs), (6, 6));
287+ }
288+}