forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-av1-obu': AV1 key-frame header OBU writer

Browse files at this commit

898b3a2970c92e5cadae5fc83790d449fbc5a7c0Ahmet Kaan GümüşParent: 9d66338e203345
Cargo.lockmodified+8 -0
@@ -257,6 +257,14 @@ dependencies = [
257 "ec-subs",257 "ec-subs",
258 ]258 ]
259 259
260+[[package]]
261+name = "ec-av1"
262+version = "0.1.0"
263+dependencies = [
264+ "ec-av1-syntax",
265+ "ec-core",
266+]
267+
260 [[package]]268 [[package]]
261 name = "ec-av1-syntax"269 name = "ec-av1-syntax"
262 version = "0.1.0"270 version = "0.1.0"
Cargo.tomlmodified+1 -0
@@ -12,6 +12,7 @@ authors = ["Ahmet Kaan Gümüş"]
12 ec-aac = { path = "crates/ec-aac", version = "0.1.0" }12 ec-aac = { path = "crates/ec-aac", version = "0.1.0" }
13 ec-ac3 = { path = "crates/ec-ac3", version = "0.1.0" }13 ec-ac3 = { path = "crates/ec-ac3", version = "0.1.0" }
14 ec-alac = { path = "crates/ec-alac", version = "0.1.0" }14 ec-alac = { path = "crates/ec-alac", version = "0.1.0" }
15+ec-av1 = { path = "crates/ec-av1", version = "0.1.0" }
15 ec-av1-syntax = { path = "crates/ec-av1-syntax", version = "0.1.0" }16 ec-av1-syntax = { path = "crates/ec-av1-syntax", version = "0.1.0" }
16 ec-core = { path = "crates/ec-core", version = "0.1.0" }17 ec-core = { path = "crates/ec-core", version = "0.1.0" }
17 ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" }18 ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" }
crates/ec-av1/Cargo.tomladded+11 -0
@@ -0,0 +1,11 @@
1+[package]
2+name = "ec-av1"
3+description = "AV1 OBU writer — bit-exact inverse of the ec-av1-syntax parsers, for the stateless-decoder subset."
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+
9+[dependencies]
10+ec-core.workspace = true
11+ec-av1-syntax.workspace = true
crates/ec-av1/src/bits.rsadded+268 -0
@@ -0,0 +1,268 @@
1+//! AV1 bit-primitive writers — bit-exact inverses of the readers in
2+//! [`ec_av1_syntax::obu`], built on the family [`ec_core::BitWriter`].
3+//!
4+//! Every function here is the inverse of a named AV1 bit-reading descriptor
5+//! (spec section 4.10 / 5.9); the parser function it mirrors is named in its
6+//! docs and roundtripped in the tests below.
7+
8+use ec_av1_syntax::obu::floor_log2;
9+use ec_core::BitWriter;
10+
11+/// `leb128()` writer (spec 4.10.5); inverts [`ec_av1_syntax::obu::read_leb128`].
12+///
13+/// Little-endian base-128: each byte carries 7 payload bits and a high
14+/// continuation bit, set on every byte but the last. A 32-bit value needs at
15+/// most 5 bytes (the parser accepts up to 8 and rejects anything that does not
16+/// fit in 32 bits).
17+pub fn write_leb128(w: &mut BitWriter, value: u32) {
18+ let mut v = value;
19+ loop {
20+ let byte = v & 0x7f;
21+ v >>= 7;
22+ let more = v != 0;
23+ w.write_bits(if more { byte | 0x80 } else { byte }, 8);
24+ if !more {
25+ return;
26+ }
27+ }
28+}
29+
30+/// `uvlc()` writer (spec 4.10.3); inverts [`ec_av1_syntax::obu::read_uvlc`].
31+///
32+/// `0` is a single `1` bit; `u32::MAX` is the 32-leading-zero escape the
33+/// parser returns verbatim; otherwise `lz` zero bits, a `1` bit, then the
34+/// `lz`-bit suffix, where `lz = floor_log2(value + 1)` and the suffix is
35+/// `value - (1 << lz) + 1` (so the decoded value is `suffix + (1 << lz) - 1`).
36+pub fn write_uvlc(w: &mut BitWriter, value: u32) {
37+ if value == u32::MAX {
38+ // The spec escape: 32 leading zeros read back as u32::MAX, with no
39+ // terminating 1 bit.
40+ w.write_bits64(0, 32);
41+ return;
42+ }
43+ let lz = floor_log2(value + 1);
44+ w.write_bits64(0, lz);
45+ w.write_bit(true);
46+ if lz > 0 {
47+ let suffix = value - ((1u32 << lz) - 1);
48+ w.write_bits(suffix, lz);
49+ }
50+}
51+
52+/// `le(n)` writer (spec 4.10.4); inverts [`ec_av1_syntax::obu::read_le`].
53+///
54+/// `n`-byte little-endian, least-significant byte first. AV1 reads `le(n)`
55+/// only at a byte boundary; the writer should be byte aligned when called.
56+pub fn write_le(w: &mut BitWriter, n: u32, value: u32) {
57+ for i in 0..n {
58+ w.write_bits((value >> (i * 8)) & 0xff, 8);
59+ }
60+}
61+
62+/// `su(n)` writer (spec 4.10.6); inverts [`ec_av1_syntax::obu::read_su`].
63+///
64+/// `n`-bit two's complement, delegated to [`BitWriter::write_signed`].
65+pub fn write_su(w: &mut BitWriter, n: u32, value: i32) {
66+ w.write_signed(value, n);
67+}
68+
69+/// `ns(n)` writer (spec 4.10.7); inverts [`ec_av1_syntax::obu::read_ns`].
70+///
71+/// Non-symmetric unsigned below `n`: `w = floor_log2(n) + 1` bits, split into a
72+/// `w - 1`-bit leading part and, for the high range, one extra bit. Values
73+/// `[0, m)` (with `m = (1 << w) - n`) carry themselves in `w - 1` bits; values
74+/// `[m, n)` carry `(value + m) >> 1` in `w - 1` bits plus the low bit of
75+/// `value + m`.
76+pub fn write_ns(w: &mut BitWriter, n: u32, value: u32) {
77+ assert!(value < n, "write_ns: value {value} >= n {n}");
78+ if n <= 1 {
79+ return;
80+ }
81+ let width = floor_log2(n) + 1;
82+ let m = (1u32 << width) - n;
83+ if value < m {
84+ w.write_bits(value, width - 1);
85+ } else {
86+ let combined = value + m;
87+ w.write_bits(combined >> 1, width - 1);
88+ w.write_bit(combined & 1 != 0);
89+ }
90+}
91+
92+/// `delta_q()` writer (spec 5.9.13); inverts
93+/// `ec_av1_syntax::frame::read_delta_q`.
94+///
95+/// One `delta_coded` bit: `0` when the delta is zero, otherwise `1` followed by
96+/// `su(7)` holding the signed delta. (The frame module is private, so the test
97+/// reconstructs the read side from [`ec_av1_syntax::obu::read_su`] plus a bit.)
98+pub fn write_delta_q(w: &mut BitWriter, delta_q: i32) {
99+ if delta_q == 0 {
100+ w.write_bit(false);
101+ } else {
102+ w.write_bit(true);
103+ w.write_signed(delta_q, 7);
104+ }
105+}
106+
107+/// `trailing_bits()` writer (spec 4.8.4).
108+///
109+/// A required `1` bit followed by zero bits up to the next byte boundary. AV1
110+/// ends every OBU that is not a whole number of bytes with this.
111+pub fn write_trailing_bits(w: &mut BitWriter) {
112+ w.write_bit(true);
113+ w.align_to_byte();
114+}
115+
116+/// `byte_alignment()` writer (spec 4.8.5).
117+///
118+/// Zero bits up to the next byte boundary — [`BitWriter::align_to_byte`] is the
119+/// exact inverse of the parser's `while !byte_aligned: read_bit()` loop.
120+pub fn write_byte_alignment(w: &mut BitWriter) {
121+ w.align_to_byte();
122+}
123+
124+#[cfg(test)]
125+mod tests {
126+ use super::*;
127+ use ec_av1_syntax::obu::{read_le, read_leb128, read_ns, read_su, read_uvlc};
128+ use ec_core::{BitReader, BitWriter};
129+
130+ /// Write `f` into a fresh writer, then read it back with `g`.
131+ fn roundtrip<T, F, G>(f: F, g: G) -> T
132+ where
133+ F: FnOnce(&mut BitWriter),
134+ G: FnOnce(&mut BitReader<'_>) -> ec_core::Result<T>,
135+ {
136+ let mut w = BitWriter::new();
137+ f(&mut w);
138+ let bytes = w.into_bytes();
139+ let mut r = BitReader::new(&bytes);
140+ g(&mut r).expect("parser readback failed")
141+ }
142+
143+ #[test]
144+ fn uvlc_roundtrip() {
145+ for v in 0..4096u32 {
146+ assert_eq!(roundtrip(|w| write_uvlc(w, v), read_uvlc), v, "uvlc {v}");
147+ }
148+ assert_eq!(
149+ roundtrip(|w| write_uvlc(w, u32::MAX), read_uvlc),
150+ u32::MAX,
151+ "uvlc escape"
152+ );
153+ }
154+ #[test]
155+ fn leb128_roundtrip() {
156+ // One value at each LEB128 byte-length boundary (1 through 5 bytes),
157+ // plus the all-ones and zero corners.
158+ let spread = [
159+ 0u32,
160+ 1,
161+ 127,
162+ 128,
163+ 255,
164+ 256,
165+ 16_383,
166+ 16_384,
167+ 65_535,
168+ 65_536,
169+ 2_097_151,
170+ 2_097_152,
171+ 134_217_727,
172+ 134_217_728,
173+ 268_435_455,
174+ 268_435_456,
175+ u32::MAX,
176+ ];
177+ for v in spread {
178+ assert_eq!(
179+ roundtrip(|w| write_leb128(w, v), read_leb128),
180+ v,
181+ "leb128 {v}"
182+ );
183+ }
184+ }
185+
186+ #[test]
187+ fn ns_roundtrip() {
188+ for n in 1u32..256 {
189+ if n <= 64 {
190+ for v in 0..n {
191+ assert_eq!(
192+ roundtrip(|w| write_ns(w, n, v), |r| read_ns(r, n)),
193+ v,
194+ "ns n={n} v={v}"
195+ );
196+ }
197+ } else {
198+ for &v in &[0u32, 1, n / 2, n - 2, n - 1] {
199+ assert_eq!(
200+ roundtrip(|w| write_ns(w, n, v), |r| read_ns(r, n)),
201+ v,
202+ "ns n={n} v={v}"
203+ );
204+ }
205+ }
206+ }
207+ }
208+
209+ #[test]
210+ fn su_roundtrip() {
211+ for v in -64..64i32 {
212+ assert_eq!(
213+ roundtrip(|w| write_su(w, 8, v), |r| read_su(r, 8)),
214+ v,
215+ "su {v}"
216+ );
217+ }
218+ }
219+
220+ #[test]
221+ fn le_roundtrip() {
222+ for n in 1u32..=4 {
223+ let max = u32::MAX >> (32 - 8 * n);
224+ for &v in &[0u32, 1, 0xAB, 0x1234, 0x123456, 0xDEADBEEF, max] {
225+ let v = v & max;
226+ assert_eq!(
227+ roundtrip(|w| write_le(w, n, v), |r| read_le(r, n)),
228+ v,
229+ "le n={n} v={v}"
230+ );
231+ }
232+ }
233+ }
234+
235+ #[test]
236+ fn delta_q_roundtrip() {
237+ // Mirrors ec_av1_syntax::frame::read_delta_q exactly: a `delta_coded`
238+ // bit, then su(7) when set. That function is private, so the read side
239+ // is rebuilt from BitReader::read_bit + obu::read_su.
240+ for v in -63..=63i32 {
241+ let got = roundtrip(
242+ |w| write_delta_q(w, v),
243+ |r| -> ec_core::Result<i32> {
244+ if r.read_bit()? {
245+ Ok(read_su(r, 7)?)
246+ } else {
247+ Ok(0)
248+ }
249+ },
250+ );
251+ assert_eq!(got, v, "delta_q {v}");
252+ }
253+ }
254+
255+ #[test]
256+ fn trailing_bits_and_byte_alignment_are_byte_aligned() {
257+ let mut w = BitWriter::new();
258+ w.write_bits(0b101, 3);
259+ assert!(!w.is_byte_aligned());
260+ write_trailing_bits(&mut w);
261+ assert!(w.is_byte_aligned());
262+
263+ let mut w = BitWriter::new();
264+ w.write_bits(0b101, 3);
265+ write_byte_alignment(&mut w);
266+ assert!(w.is_byte_aligned());
267+ }
268+}
crates/ec-av1/src/frame.rsadded+649 -0
@@ -0,0 +1,649 @@
1+//! The frame header OBU (spec 5.9), for shown key frames.
2+//!
3+//! Every writer here is the bit-exact inverse of the matching reader in
4+//! [`ec_av1_syntax::frame`], and the tests prove it by parsing back what they
5+//! wrote. The subset is the one a stateless hardware encoder needs: a key frame
6+//! that is shown, in a sequence with no decoder model, no frame ids and no
7+//! still-picture shortcut. Everything outside it is refused by name rather than
8+//! written wrong — superres with a denominator other than 8, film grain
9+//! synthesis, non-uniform tile spacing, and every non-key or hidden frame.
10+
11+use ec_av1_syntax::obu::{ObuHeader, ObuType, tile_log2};
12+use ec_av1_syntax::sequence::{SELECT_INTEGER_MV, SELECT_SCREEN_CONTENT_TOOLS, SequenceHeader};
13+use ec_av1_syntax::{
14+ FrameHeader, FrameType, MAX_SEGMENTS, MAX_TILE_AREA, MAX_TILE_COLS, MAX_TILE_ROWS,
15+ MAX_TILE_WIDTH, PRIMARY_REF_NONE, RestorationType, SEG_LVL_MAX, TOTAL_REFS_PER_FRAME, TxMode,
16+};
17+use ec_core::{BitWriter, Error, Result};
18+
19+use crate::bits::{write_byte_alignment, write_delta_q, write_su};
20+use crate::obu::wrap_obu;
21+
22+/// `Segmentation_Feature_Bits` (spec 5.9.14).
23+const SEG_FEATURE_BITS: [u32; SEG_LVL_MAX] = [8, 6, 6, 6, 6, 3, 0, 0];
24+/// `Segmentation_Feature_Signed` (spec 5.9.14).
25+const SEG_FEATURE_SIGNED: [bool; SEG_LVL_MAX] = [true, true, true, true, true, false, false, false];
26+/// The loop filter reference deltas a frame with no primary reference starts
27+/// from (spec 6.8.2, `setup_past_independence`); only the ones that differ are
28+/// coded.
29+const DEFAULT_REF_DELTAS: [i8; TOTAL_REFS_PER_FRAME] = [1, 0, 0, 0, -1, 0, -1, -1];
30+
31+/// `REMAP_LR_TYPE` inverted (spec 5.9.20): the coded index is not the enum's
32+/// discriminant, so the mapping is spelled out.
33+fn lr_type_code(t: RestorationType) -> u32 {
34+ match t {
35+ RestorationType::None => 0,
36+ RestorationType::Switchable => 1,
37+ RestorationType::Wiener => 2,
38+ RestorationType::Sgrproj => 3,
39+ }
40+}
41+
42+/// The increasing-flag idiom the tile columns and rows are coded with: a one
43+/// per step from `min` to `target`, and a terminating zero unless `target` is
44+/// already the maximum.
45+fn ramp(w: &mut BitWriter, target: u32, min: u32, max: u32) -> Result<()> {
46+ if target < min || target > max {
47+ return Err(Error::corrupt("AV1 tile_info: tile log2 out of range"));
48+ }
49+ for _ in min..target {
50+ w.write_bit(true);
51+ }
52+ if target < max {
53+ w.write_bit(false);
54+ }
55+ Ok(())
56+}
57+
58+fn sb_cols(seq: &SequenceHeader, mi_cols: u32) -> u32 {
59+ if seq.use_128x128_superblock {
60+ mi_cols.div_ceil(32)
61+ } else {
62+ mi_cols.div_ceil(16)
63+ }
64+}
65+
66+fn sb_rows(seq: &SequenceHeader, mi_rows: u32) -> u32 {
67+ if seq.use_128x128_superblock {
68+ mi_rows.div_ceil(32)
69+ } else {
70+ mi_rows.div_ceil(16)
71+ }
72+}
73+
74+/// `tile_info()` (spec 5.9.15), uniform spacing only.
75+fn write_tile_info(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHeader) -> Result<()> {
76+ if !h.tile_info.uniform_spacing {
77+ return Err(Error::unsupported(
78+ "AV1 tile_info",
79+ "non-uniform tile spacing is not written",
80+ ));
81+ }
82+ let (cols, rows) = (sb_cols(seq, h.mi_cols), sb_rows(seq, h.mi_rows));
83+ let sb_size = if seq.use_128x128_superblock { 7 } else { 6 };
84+ let max_tile_width_sb = MAX_TILE_WIDTH >> sb_size;
85+ let max_tile_area_sb = MAX_TILE_AREA >> (2 * sb_size);
86+ let min_log2_tile_cols = tile_log2(max_tile_width_sb, cols);
87+ let max_log2_tile_cols = tile_log2(1, cols.min(MAX_TILE_COLS));
88+ let max_log2_tile_rows = tile_log2(1, rows.min(MAX_TILE_ROWS));
89+ let min_log2_tiles = min_log2_tile_cols.max(tile_log2(max_tile_area_sb, rows * cols));
90+
91+ w.write_bit(true);
92+ ramp(
93+ w,
94+ h.tile_info.cols_log2,
95+ min_log2_tile_cols,
96+ max_log2_tile_cols,
97+ )?;
98+ let rows_start = min_log2_tiles.saturating_sub(h.tile_info.cols_log2);
99+ ramp(w, h.tile_info.rows_log2, rows_start, max_log2_tile_rows)?;
100+ if h.tile_info.cols_log2 > 0 || h.tile_info.rows_log2 > 0 {
101+ w.write_bits(
102+ h.tile_info.context_update_tile_id,
103+ h.tile_info.rows_log2 + h.tile_info.cols_log2,
104+ );
105+ w.write_bits(h.tile_info.tile_size_bytes - 1, 2);
106+ }
107+ Ok(())
108+}
109+
110+/// `quantization_params()` (spec 5.9.12).
111+fn write_quantization_params(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHeader) {
112+ let color = &seq.color_config;
113+ let q = &h.quantization;
114+ w.write_bits(u32::from(q.base_q_idx), 8);
115+ write_delta_q(w, i32::from(q.delta_q_y_dc));
116+ if color.num_planes > 1 {
117+ let diff_uv_delta = if color.separate_uv_delta_q {
118+ let d = q.delta_q_v_dc != q.delta_q_u_dc || q.delta_q_v_ac != q.delta_q_u_ac;
119+ w.write_bit(d);
120+ d
121+ } else {
122+ false
123+ };
124+ write_delta_q(w, i32::from(q.delta_q_u_dc));
125+ write_delta_q(w, i32::from(q.delta_q_u_ac));
126+ if diff_uv_delta {
127+ write_delta_q(w, i32::from(q.delta_q_v_dc));
128+ write_delta_q(w, i32::from(q.delta_q_v_ac));
129+ }
130+ }
131+ w.write_bit(q.using_qmatrix);
132+ if q.using_qmatrix {
133+ w.write_bits(u32::from(q.qm_y), 4);
134+ w.write_bits(u32::from(q.qm_u), 4);
135+ if color.separate_uv_delta_q {
136+ w.write_bits(u32::from(q.qm_v), 4);
137+ }
138+ }
139+}
140+
141+/// `segmentation_params()` (spec 5.9.14). The frame this writer codes has no
142+/// primary reference, so the update flags are forced and not coded.
143+fn write_segmentation_params(w: &mut BitWriter, h: &FrameHeader) {
144+ let seg = &h.segmentation;
145+ w.write_bit(seg.enabled);
146+ if !seg.enabled {
147+ return;
148+ }
149+ if h.primary_ref_frame != PRIMARY_REF_NONE {
150+ w.write_bit(seg.update_map);
151+ if seg.update_map {
152+ w.write_bit(seg.temporal_update);
153+ }
154+ w.write_bit(seg.update_data);
155+ }
156+ if seg.update_data || h.primary_ref_frame == PRIMARY_REF_NONE {
157+ for segment in 0..MAX_SEGMENTS {
158+ for feature in 0..SEG_LVL_MAX {
159+ let enabled = seg.feature_enabled[segment][feature];
160+ w.write_bit(enabled);
161+ if !enabled {
162+ continue;
163+ }
164+ let bits = SEG_FEATURE_BITS[feature];
165+ let value = i32::from(seg.feature_data[segment][feature]);
166+ if SEG_FEATURE_SIGNED[feature] {
167+ write_su(w, 1 + bits, value);
168+ } else if bits > 0 {
169+ w.write_bits(value as u32, bits);
170+ }
171+ }
172+ }
173+ }
174+}
175+
176+/// `delta_q_params()` (spec 5.9.17).
177+fn write_delta_q_params(w: &mut BitWriter, h: &FrameHeader) {
178+ if h.quantization.base_q_idx > 0 {
179+ w.write_bit(h.delta.q_present);
180+ }
181+ if h.delta.q_present {
182+ w.write_bits(u32::from(h.delta.q_res), 2);
183+ }
184+}
185+
186+/// `delta_lf_params()` (spec 5.9.18).
187+fn write_delta_lf_params(w: &mut BitWriter, h: &FrameHeader) {
188+ if !h.delta.q_present {
189+ return;
190+ }
191+ if !h.allow_intrabc {
192+ w.write_bit(h.delta.lf_present);
193+ }
194+ if h.delta.lf_present {
195+ w.write_bits(u32::from(h.delta.lf_res), 2);
196+ w.write_bit(h.delta.lf_multi);
197+ }
198+}
199+
200+/// `loop_filter_params()` (spec 5.9.11).
201+fn write_loop_filter_params(
202+ w: &mut BitWriter,
203+ seq: &SequenceHeader,
204+ h: &FrameHeader,
205+ coded_lossless: bool,
206+) {
207+ if coded_lossless || h.allow_intrabc {
208+ return;
209+ }
210+ let lf = &h.loop_filter;
211+ w.write_bits(u32::from(lf.level[0]), 6);
212+ w.write_bits(u32::from(lf.level[1]), 6);
213+ if seq.color_config.num_planes > 1 && (lf.level[0] > 0 || lf.level[1] > 0) {
214+ w.write_bits(u32::from(lf.level[2]), 6);
215+ w.write_bits(u32::from(lf.level[3]), 6);
216+ }
217+ w.write_bits(u32::from(lf.sharpness), 3);
218+ w.write_bit(lf.delta_enabled);
219+ if !lf.delta_enabled {
220+ return;
221+ }
222+ w.write_bit(lf.delta_update);
223+ if !lf.delta_update {
224+ return;
225+ }
226+ for (i, &delta) in lf.ref_deltas.iter().enumerate() {
227+ let update = delta != DEFAULT_REF_DELTAS[i];
228+ w.write_bit(update);
229+ if update {
230+ write_su(w, 7, i32::from(delta));
231+ }
232+ }
233+ for &delta in &lf.mode_deltas {
234+ let update = delta != 0;
235+ w.write_bit(update);
236+ if update {
237+ write_su(w, 7, i32::from(delta));
238+ }
239+ }
240+}
241+
242+/// `cdef_params()` (spec 5.9.19).
243+fn write_cdef_params(
244+ w: &mut BitWriter,
245+ seq: &SequenceHeader,
246+ h: &FrameHeader,
247+ coded_lossless: bool,
248+) {
249+ if coded_lossless || h.allow_intrabc || !seq.enable_cdef {
250+ return;
251+ }
252+ let cdef = &h.cdef;
253+ w.write_bits(u32::from(cdef.damping - 3), 2);
254+ w.write_bits(u32::from(cdef.bits), 2);
255+ // A secondary strength of 4 is coded as 3; the reader maps it back.
256+ let coded_sec = |s: u8| u32::from(if s == 4 { 3 } else { s });
257+ for i in 0..(1usize << cdef.bits) {
258+ w.write_bits(u32::from(cdef.y_pri_strength[i]), 4);
259+ w.write_bits(coded_sec(cdef.y_sec_strength[i]), 2);
260+ if seq.color_config.num_planes > 1 {
261+ w.write_bits(u32::from(cdef.uv_pri_strength[i]), 4);
262+ w.write_bits(coded_sec(cdef.uv_sec_strength[i]), 2);
263+ }
264+ }
265+}
266+
267+/// `lr_params()` (spec 5.9.20).
268+fn write_lr_params(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHeader, all_lossless: bool) {
269+ if all_lossless || h.allow_intrabc || !seq.enable_restoration {
270+ return;
271+ }
272+ let lr = &h.loop_restoration;
273+ let (mut uses_lr, mut uses_chroma_lr) = (false, false);
274+ for plane in 0..seq.color_config.num_planes as usize {
275+ w.write_bits(lr_type_code(lr.frame_restoration_type[plane]), 2);
276+ if lr.frame_restoration_type[plane] != RestorationType::None {
277+ uses_lr = true;
278+ uses_chroma_lr |= plane > 0;
279+ }
280+ }
281+ if !uses_lr {
282+ return;
283+ }
284+ if seq.use_128x128_superblock {
285+ w.write_bits(u32::from(lr.lr_unit_shift) - 1, 1);
286+ } else {
287+ w.write_bit(lr.lr_unit_shift > 0);
288+ if lr.lr_unit_shift > 0 {
289+ w.write_bits(u32::from(lr.lr_unit_shift) - 1, 1);
290+ }
291+ }
292+ if seq.color_config.subsampling_x == 1 && seq.color_config.subsampling_y == 1 && uses_chroma_lr
293+ {
294+ w.write_bits(u32::from(lr.lr_uv_shift), 1);
295+ }
296+}
297+
298+/// `uncompressed_header()` (spec 5.9.2) for a shown key frame.
299+pub fn write_frame_header(w: &mut BitWriter, seq: &SequenceHeader, h: &FrameHeader) -> Result<()> {
300+ if h.frame_type != FrameType::Key || !h.show_frame || h.show_existing_frame {
301+ return Err(Error::unsupported(
302+ "AV1 frame header",
303+ "only a shown key frame is written",
304+ ));
305+ }
306+ if seq.reduced_still_picture_header {
307+ return Err(Error::unsupported(
308+ "AV1 frame header",
309+ "reduced_still_picture_header changes the whole header layout",
310+ ));
311+ }
312+ if seq.decoder_model_info.is_some() {
313+ return Err(Error::unsupported(
314+ "AV1 frame header",
315+ "decoder model timing is not written",
316+ ));
317+ }
318+ if seq.frame_id_numbers_present_flag {
319+ return Err(Error::unsupported(
320+ "AV1 frame header",
321+ "frame id numbers are not written",
322+ ));
323+ }
324+
325+ w.write_bit(false); // show_existing_frame
326+ w.write_bits(0, 2); // frame_type: KEY_FRAME
327+ w.write_bit(true); // show_frame
328+ // showable_frame and error_resilient_mode are forced for a shown key frame.
329+
330+ w.write_bit(h.disable_cdf_update);
331+ if seq.seq_force_screen_content_tools == SELECT_SCREEN_CONTENT_TOOLS {
332+ w.write_bit(h.allow_screen_content_tools);
333+ } else if h.allow_screen_content_tools != (seq.seq_force_screen_content_tools != 0) {
334+ return Err(Error::corrupt(
335+ "AV1 frame header: allow_screen_content_tools contradicts the sequence",
336+ ));
337+ }
338+ if h.allow_screen_content_tools && seq.seq_force_integer_mv == SELECT_INTEGER_MV {
339+ // The reader forces this back to true for an intra frame; the bit is
340+ // still coded, and the value it carries is the one the reader discards.
341+ w.write_bit(h.force_integer_mv);
342+ }
343+ w.write_bit(h.frame_size_override_flag);
344+ w.write_bits(h.order_hint, seq.order_hint_bits);
345+ // primary_ref_frame, buffer_removal_time, refresh_frame_flags and the
346+ // ref_order_hint loop are all forced for a shown key frame.
347+
348+ if h.frame_size_override_flag {
349+ w.write_bits(h.frame_width - 1, seq.frame_width_bits);
350+ w.write_bits(h.frame_height - 1, seq.frame_height_bits);
351+ }
352+ if seq.enable_superres {
353+ w.write_bit(h.use_superres);
354+ }
355+ if h.use_superres || h.superres_denom != 8 {
356+ return Err(Error::unsupported(
357+ "AV1 superres",
358+ "only a superres denominator of 8 (no scaling) is written",
359+ ));
360+ }
361+ let render_differs = h.render_width != h.upscaled_width || h.render_height != h.frame_height;
362+ w.write_bit(render_differs);
363+ if render_differs {
364+ w.write_bits(h.render_width - 1, 16);
365+ w.write_bits(h.render_height - 1, 16);
366+ }
367+ if h.allow_screen_content_tools && h.upscaled_width == h.frame_width {
368+ w.write_bit(h.allow_intrabc);
369+ }
370+ if !h.disable_cdf_update {
371+ w.write_bit(h.disable_frame_end_update_cdf);
372+ }
373+
374+ write_tile_info(w, seq, h)?;
375+ write_quantization_params(w, seq, h);
376+ write_segmentation_params(w, h);
377+ write_delta_q_params(w, h);
378+ write_delta_lf_params(w, h);
379+
380+ // `coded_lossless` gates the loop filter, CDEF, restoration and transform
381+ // mode syntax; it is derived, never coded (spec 5.9.2).
382+ let q = &h.quantization;
383+ let coded_lossless = (0..MAX_SEGMENTS).all(|segment| {
384+ h.segment_qindex(segment) == 0
385+ && q.delta_q_y_dc == 0
386+ && q.delta_q_u_ac == 0
387+ && q.delta_q_u_dc == 0
388+ && q.delta_q_v_ac == 0
389+ && q.delta_q_v_dc == 0
390+ });
391+ let all_lossless = coded_lossless && h.frame_width == h.upscaled_width;
392+
393+ write_loop_filter_params(w, seq, h, coded_lossless);
394+ write_cdef_params(w, seq, h, coded_lossless);
395+ write_lr_params(w, seq, h, all_lossless);
396+ if coded_lossless {
397+ if h.tx_mode != TxMode::Only4x4 {
398+ return Err(Error::corrupt(
399+ "AV1 frame header: a lossless frame can only use TX_MODE_ONLY_4X4",
400+ ));
401+ }
402+ } else {
403+ w.write_bit(h.tx_mode == TxMode::Select);
404+ }
405+ // reference_select, skip mode and warped motion are all forced for intra.
406+ w.write_bit(h.reduced_tx_set);
407+ // Global motion is the identity for intra and is not coded.
408+ if seq.film_grain_params_present {
409+ w.write_bit(h.film_grain.apply_grain);
410+ if h.film_grain.apply_grain {
411+ return Err(Error::unsupported(
412+ "AV1 film grain",
413+ "film grain synthesis parameters are not written",
414+ ));
415+ }
416+ }
417+ Ok(())
418+}
419+
420+/// A `OBU_FRAME`: the header above, byte-aligned, followed by the tile group
421+/// payload the caller supplies.
422+pub fn frame_obu(seq: &SequenceHeader, h: &FrameHeader, tile_data: &[u8]) -> Result<Vec<u8>> {
423+ let mut w = BitWriter::new();
424+ write_frame_header(&mut w, seq, h)?;
425+ write_byte_alignment(&mut w);
426+ let mut payload = w.into_bytes();
427+ payload.extend_from_slice(tile_data);
428+ Ok(wrap_obu(
429+ &ObuHeader {
430+ obu_type: ObuType::Frame,
431+ extension_flag: false,
432+ has_size_field: true,
433+ temporal_id: 0,
434+ spatial_id: 0,
435+ },
436+ &payload,
437+ ))
438+}
439+
440+#[cfg(test)]
441+mod tests {
442+ use super::*;
443+ use crate::sequence::sequence_header_obu;
444+ use crate::sequence::tests::sample_1080p;
445+ use ec_av1_syntax::{Av1Parser, ObuKind, QuantizationParams};
446+
447+ /// The key frame the sequence in [`sample_1080p`] would carry: 1920x1080,
448+ /// one tile, quantised (so nothing is lossless), CDEF on.
449+ fn sample_key_frame() -> FrameHeader {
450+ FrameHeader {
451+ frame_type: FrameType::Key,
452+ frame_is_intra: true,
453+ show_frame: true,
454+ showable_frame: false,
455+ error_resilient_mode: true,
456+ force_integer_mv: true,
457+ refresh_frame_flags: 0xFF,
458+ primary_ref_frame: PRIMARY_REF_NONE,
459+ order_hint: 0,
460+ frame_width: 1920,
461+ frame_height: 1080,
462+ upscaled_width: 1920,
463+ render_width: 1920,
464+ render_height: 1080,
465+ mi_cols: 480,
466+ mi_rows: 270,
467+ tile_info: ec_av1_syntax::TileInfo {
468+ uniform_spacing: true,
469+ cols: 1,
470+ rows: 1,
471+ cols_log2: 0,
472+ rows_log2: 0,
473+ mi_col_starts: vec![0, 480],
474+ mi_row_starts: vec![0, 270],
475+ context_update_tile_id: 0,
476+ tile_size_bytes: 1,
477+ },
478+ quantization: QuantizationParams {
479+ base_q_idx: 100,
480+ ..QuantizationParams::default()
481+ },
482+ loop_filter: ec_av1_syntax::LoopFilterParams {
483+ level: [12, 12, 0, 0],
484+ sharpness: 0,
485+ delta_enabled: true,
486+ delta_update: false,
487+ ref_deltas: DEFAULT_REF_DELTAS,
488+ mode_deltas: [0; 2],
489+ },
490+ cdef: ec_av1_syntax::CdefParams {
491+ damping: 4,
492+ bits: 0,
493+ y_pri_strength: [3, 0, 0, 0, 0, 0, 0, 0],
494+ y_sec_strength: [4, 0, 0, 0, 0, 0, 0, 0],
495+ uv_pri_strength: [2, 0, 0, 0, 0, 0, 0, 0],
496+ uv_sec_strength: [0; 8],
497+ },
498+ tx_mode: TxMode::Select,
499+ reduced_tx_set: false,
500+ ..FrameHeader::default()
501+ }
502+ }
503+
504+ /// Parse a sequence header OBU followed by a frame OBU, and hand back what
505+ /// the frame OBU held.
506+ fn roundtrip(
507+ seq: &SequenceHeader,
508+ h: &FrameHeader,
509+ tile_data: &[u8],
510+ ) -> (FrameHeader, Vec<ec_av1_syntax::Tile>) {
511+ let mut stream = sequence_header_obu(seq).unwrap();
512+ let frame_start = stream.len();
513+ stream.extend_from_slice(&frame_obu(seq, h, tile_data).unwrap());
514+
515+ let mut parser = Av1Parser::new();
516+ let obus = parser.parse_temporal_unit(&stream).unwrap();
517+ assert_eq!(obus.len(), 2);
518+ assert_eq!(obus[1].offset, frame_start);
519+ assert_eq!(obus[1].offset + obus[1].total_size, stream.len());
520+ match &obus[1].kind {
521+ ObuKind::Frame(parsed, tiles) => ((**parsed).clone(), tiles.clone()),
522+ other => panic!("expected an OBU_FRAME, got {other:?}"),
523+ }
524+ }
525+
526+ #[test]
527+ fn key_frame_header_roundtrips() {
528+ let seq = sample_1080p();
529+ let mut expected = sample_key_frame();
530+ let (parsed, tiles) = roundtrip(&seq, &expected, &[0x11, 0x22, 0x33]);
531+
532+ // The header's own length is derived, not written; check it against the
533+ // writer rather than copying it out of the parse.
534+ let mut w = BitWriter::new();
535+ write_frame_header(&mut w, &seq, &expected).unwrap();
536+ assert_eq!(parsed.header_bits, w.bit_len());
537+ expected.header_bits = parsed.header_bits;
538+
539+ assert_eq!(parsed, expected);
540+ assert_eq!(tiles.len(), 1);
541+ assert_eq!(tiles[0].size, 3);
542+ }
543+
544+ #[test]
545+ fn four_tile_columns_roundtrip() {
546+ let seq = sample_1080p();
547+ let mut expected = sample_key_frame();
548+ expected.tile_info = ec_av1_syntax::TileInfo {
549+ uniform_spacing: true,
550+ cols: 4,
551+ rows: 1,
552+ cols_log2: 2,
553+ rows_log2: 0,
554+ // 15 superblocks of 128 wide, 4 to a tile: 4, 4, 4, 3.
555+ mi_col_starts: vec![0, 128, 256, 384, 480],
556+ mi_row_starts: vec![0, 270],
557+ context_update_tile_id: 3,
558+ tile_size_bytes: 1,
559+ };
560+ // tile_start_and_end_present_flag = 0, then three sized tiles of one
561+ // byte each (the field codes size - 1) and one unsized last tile.
562+ let tile_data = [0x00, 0x00, 0x11, 0x00, 0x22, 0x00, 0x33, 0x44];
563+ let (parsed, tiles) = roundtrip(&seq, &expected, &tile_data);
564+
565+ let mut w = BitWriter::new();
566+ write_frame_header(&mut w, &seq, &expected).unwrap();
567+ expected.header_bits = w.bit_len();
568+ assert_eq!(parsed, expected);
569+ assert_eq!(tiles.len(), 4);
570+ assert!(tiles.iter().all(|t| t.size == 1));
571+ assert_eq!(tiles[3].column, 3);
572+ }
573+
574+ #[test]
575+ fn segmentation_and_delta_q_roundtrip() {
576+ let seq = sample_1080p();
577+ let mut expected = sample_key_frame();
578+ expected.segmentation.enabled = true;
579+ expected.segmentation.update_map = true;
580+ expected.segmentation.update_data = true;
581+ expected.segmentation.feature_enabled[0][0] = true;
582+ expected.segmentation.feature_data[0][0] = -40;
583+ expected.segmentation.feature_enabled[2][5] = true;
584+ expected.segmentation.feature_data[2][5] = 3;
585+ // Both are derived from the feature table, not coded.
586+ expected.segmentation.seg_id_pre_skip = true;
587+ expected.segmentation.last_active_seg_id = 2;
588+ expected.delta.q_present = true;
589+ expected.delta.q_res = 2;
590+ expected.delta.lf_present = true;
591+ expected.delta.lf_res = 1;
592+ expected.delta.lf_multi = true;
593+
594+ let (parsed, _) = roundtrip(&seq, &expected, &[0x00]);
595+ let mut w = BitWriter::new();
596+ write_frame_header(&mut w, &seq, &expected).unwrap();
597+ expected.header_bits = w.bit_len();
598+ assert_eq!(parsed, expected);
599+ }
600+
601+ #[test]
602+ fn loop_restoration_roundtrips_with_its_own_type_codes() {
603+ let mut seq = sample_1080p();
604+ seq.enable_restoration = true;
605+ let mut expected = sample_key_frame();
606+ expected.loop_restoration.frame_restoration_type = [
607+ RestorationType::Sgrproj,
608+ RestorationType::Wiener,
609+ RestorationType::None,
610+ ];
611+ expected.loop_restoration.lr_unit_shift = 1;
612+ expected.loop_restoration.lr_uv_shift = 1;
613+
614+ let (parsed, _) = roundtrip(&seq, &expected, &[0x00]);
615+ assert_eq!(
616+ parsed.loop_restoration.frame_restoration_type,
617+ expected.loop_restoration.frame_restoration_type
618+ );
619+ assert_eq!(parsed.loop_restoration.lr_unit_shift, 1);
620+ assert_eq!(parsed.loop_restoration.lr_uv_shift, 1);
621+ }
622+
623+ #[test]
624+ fn unsupported_frames_are_refused_by_name() {
625+ let seq = sample_1080p();
626+
627+ let mut inter = sample_key_frame();
628+ inter.frame_type = FrameType::Inter;
629+ assert!(frame_obu(&seq, &inter, &[0x00]).is_err());
630+
631+ let mut hidden = sample_key_frame();
632+ hidden.show_frame = false;
633+ assert!(frame_obu(&seq, &hidden, &[0x00]).is_err());
634+
635+ let mut scaled = sample_key_frame();
636+ scaled.superres_denom = 9;
637+ assert!(frame_obu(&seq, &scaled, &[0x00]).is_err());
638+
639+ let mut ragged = sample_key_frame();
640+ ragged.tile_info.uniform_spacing = false;
641+ assert!(frame_obu(&seq, &ragged, &[0x00]).is_err());
642+
643+ let mut grainy = seq.clone();
644+ grainy.film_grain_params_present = true;
645+ let mut grain_frame = sample_key_frame();
646+ grain_frame.film_grain.apply_grain = true;
647+ assert!(frame_obu(&grainy, &grain_frame, &[0x00]).is_err());
648+ }
649+}
crates/ec-av1/src/lib.rsadded+18 -0
@@ -0,0 +1,18 @@
1+//! AV1 OBU writer — bit-exact inverse of the [`ec_av1_syntax`] parsers, for
2+//! the stateless hardware-decoder subset (sequence header and key-frame header
3+//! OBUs).
4+//!
5+//! [`bits`] holds the bit-primitive writers every higher-level OBU writer is
6+//! built from; each is the direct inverse of the matching reader in
7+//! [`ec_av1_syntax::obu`] and is roundtripped against that reader in its tests.
8+//!
9+//! AV1 is covered by the AOMedia Patent License 1.0; this crate is an
10+//! independent implementation written from the specification alone.
11+
12+#![forbid(unsafe_code)]
13+#![warn(missing_docs)]
14+
15+pub mod bits;
16+pub mod frame;
17+pub mod obu;
18+pub mod sequence;
crates/ec-av1/src/obu.rsadded+139 -0
@@ -0,0 +1,139 @@
1+//! AV1 OBU framing writer — bit-exact inverse of the readers in
2+//! [`ec_av1_syntax::obu`], built on the family [`ec_core::BitWriter`].
3+
4+use ec_av1_syntax::obu::{ObuHeader, ObuType};
5+use ec_core::BitWriter;
6+
7+use crate::bits::write_leb128;
8+
9+/// Map an [`ObuType`] to its 4-bit `obu_type` code (spec 6.2.2); the inverse of
10+/// `ObuType::from_code`.
11+pub fn obu_type_code(t: ObuType) -> u8 {
12+ match t {
13+ ObuType::SequenceHeader => 1,
14+ ObuType::TemporalDelimiter => 2,
15+ ObuType::FrameHeader => 3,
16+ ObuType::TileGroup => 4,
17+ ObuType::Metadata => 5,
18+ ObuType::Frame => 6,
19+ ObuType::RedundantFrameHeader => 7,
20+ ObuType::TileList => 8,
21+ ObuType::Padding => 15,
22+ ObuType::Reserved(code) => code,
23+ }
24+}
25+
26+/// Write an OBU header (spec 5.3.2) — the inverse of [`ObuHeader::parse`].
27+///
28+/// The forbidden bit and every reserved bit are written `0`. The header is
29+/// always a whole number of bytes: one without, two with the extension header.
30+pub fn write_obu_header(w: &mut BitWriter, h: &ObuHeader) {
31+ w.write_bit(false); // obu_forbidden_bit
32+ w.write_bits(obu_type_code(h.obu_type) as u32, 4);
33+ w.write_bit(h.extension_flag);
34+ w.write_bit(h.has_size_field);
35+ w.write_bit(false); // obu_reserved_1bit
36+ if h.extension_flag {
37+ w.write_bits(h.temporal_id as u32, 3);
38+ w.write_bits(h.spatial_id as u32, 2);
39+ w.write_bits(0, 3); // extension reserved bits
40+ }
41+}
42+
43+/// Frame `payload` as a complete low-overhead OBU (spec 5.3): the header
44+/// bytes, then `leb128(obu_size)` when `h.has_size_field`, then the payload.
45+///
46+/// The header is byte-aligned, so the size field and payload follow on byte
47+/// boundaries and the result is a flat byte vector.
48+pub fn wrap_obu(h: &ObuHeader, payload: &[u8]) -> Vec<u8> {
49+ let mut w = BitWriter::new();
50+ write_obu_header(&mut w, h);
51+ if h.has_size_field {
52+ write_leb128(&mut w, payload.len() as u32);
53+ }
54+ let mut out = w.into_bytes();
55+ out.extend_from_slice(payload);
56+ out
57+}
58+
59+/// A temporal-delimiter OBU (spec 6.2.2): type 2, no extension, size field
60+/// present, empty payload — the two bytes `12 00` that mark a new temporal
61+/// unit in the low-overhead format.
62+pub fn temporal_delimiter() -> Vec<u8> {
63+ wrap_obu(
64+ &ObuHeader {
65+ obu_type: ObuType::TemporalDelimiter,
66+ extension_flag: false,
67+ has_size_field: true,
68+ temporal_id: 0,
69+ spatial_id: 0,
70+ },
71+ &[],
72+ )
73+}
74+
75+#[cfg(test)]
76+mod tests {
77+ use super::*;
78+ use ec_av1_syntax::obu::read_leb128;
79+ use ec_core::BitReader;
80+
81+ #[test]
82+ fn obu_header_plain_roundtrip() {
83+ let h = ObuHeader {
84+ obu_type: ObuType::SequenceHeader,
85+ extension_flag: false,
86+ has_size_field: true,
87+ temporal_id: 0,
88+ spatial_id: 0,
89+ };
90+ let mut w = BitWriter::new();
91+ write_obu_header(&mut w, &h);
92+ let bytes = w.into_bytes();
93+ assert_eq!(bytes.len(), 1);
94+ let mut r = BitReader::new(&bytes);
95+ assert_eq!(ObuHeader::parse(&mut r).unwrap(), h);
96+ }
97+
98+ #[test]
99+ fn obu_header_extension_roundtrip() {
100+ let h = ObuHeader {
101+ obu_type: ObuType::Frame,
102+ extension_flag: true,
103+ has_size_field: false,
104+ temporal_id: 3,
105+ spatial_id: 2,
106+ };
107+ let mut w = BitWriter::new();
108+ write_obu_header(&mut w, &h);
109+ let bytes = w.into_bytes();
110+ assert_eq!(bytes.len(), 2);
111+ let mut r = BitReader::new(&bytes);
112+ assert_eq!(ObuHeader::parse(&mut r).unwrap(), h);
113+ }
114+
115+ #[test]
116+ fn wrap_obu_size_field_matches_payload() {
117+ let h = ObuHeader {
118+ obu_type: ObuType::SequenceHeader,
119+ extension_flag: false,
120+ has_size_field: true,
121+ temporal_id: 0,
122+ spatial_id: 0,
123+ };
124+ let payload = [0u8; 19]; // arbitrary
125+ let obu = wrap_obu(&h, &payload);
126+ // Header is one byte; the leb128 size follows; then the payload.
127+ let mut r = BitReader::new(&obu);
128+ let parsed_h = ObuHeader::parse(&mut r).unwrap();
129+ assert_eq!(parsed_h, h);
130+ let size = read_leb128(&mut r).unwrap();
131+ assert_eq!(size as usize, payload.len());
132+ assert_eq!(&obu[obu.len() - payload.len()..], &payload);
133+ }
134+
135+ #[test]
136+ fn temporal_delimiter_is_two_bytes() {
137+ assert_eq!(temporal_delimiter(), [0x12, 0x00]);
138+ }
139+}
crates/ec-av1/src/sequence.rsadded+341 -0
@@ -0,0 +1,341 @@
1+//! Sequence-header OBU writer (spec 5.5) — bit-exact inverse of
2+//! [`ec_av1_syntax::sequence::SequenceHeader::parse`], for the
3+//! stateless-decoder subset.
4+
5+use ec_av1_syntax::obu::{ObuHeader, ObuType};
6+#[cfg(test)]
7+use ec_av1_syntax::sequence::OperatingPoint;
8+use ec_av1_syntax::sequence::{
9+ ChromaSamplePosition, ColorConfig, SELECT_INTEGER_MV, SELECT_SCREEN_CONTENT_TOOLS,
10+ SequenceHeader,
11+};
12+use ec_core::{BitWriter, Error, Result};
13+
14+use crate::bits::write_trailing_bits;
15+use crate::obu::wrap_obu;
16+
17+/// Map a [`ChromaSamplePosition`] to its 2-bit code (spec 6.4.2).
18+fn chroma_sample_position_code(p: ChromaSamplePosition) -> u32 {
19+ match p {
20+ ChromaSamplePosition::Unknown => 0,
21+ ChromaSamplePosition::Vertical => 1,
22+ ChromaSamplePosition::Colocated => 2,
23+ ChromaSamplePosition::Reserved => 3,
24+ }
25+}
26+
27+/// Write `color_config()` (spec 5.5.2) — the inverse of
28+/// `ec_av1_syntax::sequence::read_color_config`.
29+fn write_color_config(w: &mut BitWriter, c: &ColorConfig, seq_profile: u8) -> Result<()> {
30+ let high_bitdepth = c.bit_depth >= 10;
31+ w.write_bit(high_bitdepth);
32+ if seq_profile == 2 && high_bitdepth {
33+ // The extra `twelve_bit` flag: 1 for 12-bit, 0 for 10-bit.
34+ w.write_bit(c.bit_depth == 12);
35+ }
36+
37+ if seq_profile == 1 {
38+ // Profile 1 forces mono_chrome = false; the bit is not coded.
39+ if c.mono_chrome {
40+ return Err(Error::unsupported(
41+ "AV1 color_config mono_chrome",
42+ "profile 1 is 4:4:4 and cannot be monochrome",
43+ ));
44+ }
45+ } else {
46+ w.write_bit(c.mono_chrome);
47+ }
48+
49+ // color_description_present_flag: absent when all three are the
50+ // unspecified default (H.273 code 2), which the parser then assumes.
51+ let present =
52+ c.color_primaries != 2 || c.transfer_characteristics != 2 || c.matrix_coefficients != 2;
53+ w.write_bit(present);
54+ if present {
55+ w.write_bits(c.color_primaries as u32, 8);
56+ w.write_bits(c.transfer_characteristics as u32, 8);
57+ w.write_bits(c.matrix_coefficients as u32, 8);
58+ }
59+
60+ if c.mono_chrome {
61+ w.write_bit(c.color_range);
62+ // subsampling is forced 1,1 and separate_uv_delta_q is not coded.
63+ return Ok(());
64+ }
65+
66+ // sRGB identity (BT.709 primaries, sRGB transfer, identity matrix) forces
67+ // full-range 4:4:4; none of color_range, subsampling or position is coded.
68+ let srgb =
69+ c.color_primaries == 1 && c.transfer_characteristics == 13 && c.matrix_coefficients == 0;
70+ if !srgb {
71+ w.write_bit(c.color_range);
72+ match seq_profile {
73+ 0 => {} // subsampling forced 1,1 (4:2:0), not coded
74+ 1 => {} // subsampling forced 0,0 (4:4:4), not coded
75+ _ => {
76+ if c.bit_depth == 12 {
77+ w.write_bits(c.subsampling_x as u32, 1);
78+ if c.subsampling_x == 1 {
79+ w.write_bits(c.subsampling_y as u32, 1);
80+ }
81+ }
82+ // Profile 2 below 12-bit: subsampling forced 1,0 (4:2:2).
83+ }
84+ }
85+ if c.subsampling_x == 1 && c.subsampling_y == 1 {
86+ w.write_bits(chroma_sample_position_code(c.chroma_sample_position), 2);
87+ }
88+ }
89+ w.write_bit(c.separate_uv_delta_q);
90+ Ok(())
91+}
92+
93+/// Write a sequence-header OBU payload (spec 5.5.1) — the inverse of
94+/// [`SequenceHeader::parse`], ending with `trailing_bits()`.
95+///
96+/// Supported subset (anything else returns [`Error::Unsupported`]):
97+/// `reduced_still_picture_header == false`, no `timing_info`, no
98+/// `decoder_model_info`, and exactly one operating point — the normal
99+/// single-layer video case. Still-image, timed and buffered-decoder-model
100+/// streams are refused rather than mis-written.
101+pub fn write_sequence_header(w: &mut BitWriter, s: &SequenceHeader) -> Result<()> {
102+ if s.reduced_still_picture_header {
103+ return Err(Error::unsupported(
104+ "AV1 reduced_still_picture_header",
105+ "the cut-down still-image header is not implemented",
106+ ));
107+ }
108+ if s.timing_info.is_some() {
109+ return Err(Error::unsupported(
110+ "AV1 timing_info",
111+ "timing info is not implemented",
112+ ));
113+ }
114+ if s.decoder_model_info.is_some() {
115+ return Err(Error::unsupported(
116+ "AV1 decoder_model_info",
117+ "the decoder model is not implemented",
118+ ));
119+ }
120+ if s.operating_points.len() != 1 {
121+ return Err(Error::unsupported(
122+ "AV1 operating_points",
123+ "only one operating point is supported",
124+ ));
125+ }
126+
127+ w.write_bits(s.seq_profile as u32, 3);
128+ w.write_bit(s.still_picture);
129+ w.write_bit(s.reduced_still_picture_header);
130+ // timing_info_present_flag = false (the subset above guarantees it).
131+ w.write_bit(false);
132+ w.write_bit(s.initial_display_delay_present_flag);
133+ // operating_points_cnt_minus_1 = 0.
134+ w.write_bits(0, 5);
135+
136+ let op = &s.operating_points[0];
137+ w.write_bits(op.idc, 12);
138+ w.write_bits(op.seq_level_idx as u32, 5);
139+ if op.seq_level_idx > 7 {
140+ w.write_bit(op.seq_tier != 0);
141+ }
142+ // No decoder model: decoder_model_present_for_this_op is not coded.
143+ if s.initial_display_delay_present_flag {
144+ if op.initial_display_delay > 0 {
145+ w.write_bit(true);
146+ w.write_bits(op.initial_display_delay as u32 - 1, 4);
147+ } else {
148+ w.write_bit(false);
149+ }
150+ }
151+
152+ w.write_bits(s.frame_width_bits - 1, 4);
153+ w.write_bits(s.frame_height_bits - 1, 4);
154+ w.write_bits(s.max_frame_width - 1, s.frame_width_bits);
155+ w.write_bits(s.max_frame_height - 1, s.frame_height_bits);
156+
157+ // reduced_still_picture_header is false, so the flag is always coded.
158+ w.write_bit(s.frame_id_numbers_present_flag);
159+ if s.frame_id_numbers_present_flag {
160+ w.write_bits(s.delta_frame_id_length - 2, 4);
161+ w.write_bits(s.additional_frame_id_length - 1, 3);
162+ }
163+
164+ w.write_bit(s.use_128x128_superblock);
165+ w.write_bit(s.enable_filter_intra);
166+ w.write_bit(s.enable_intra_edge_filter);
167+
168+ // The !reduced_still_picture_header block (spec 5.5.1).
169+ w.write_bit(s.enable_interintra_compound);
170+ w.write_bit(s.enable_masked_compound);
171+ w.write_bit(s.enable_warped_motion);
172+ w.write_bit(s.enable_dual_filter);
173+ w.write_bit(s.enable_order_hint);
174+ if s.enable_order_hint {
175+ w.write_bit(s.enable_jnt_comp);
176+ w.write_bit(s.enable_ref_frame_mvs);
177+ }
178+ // seq_force_screen_content_tools: SELECT (2) is the single-bit form.
179+ if s.seq_force_screen_content_tools == SELECT_SCREEN_CONTENT_TOOLS {
180+ w.write_bit(true);
181+ } else if s.seq_force_screen_content_tools <= 1 {
182+ w.write_bit(false);
183+ w.write_bits(s.seq_force_screen_content_tools as u32, 1);
184+ } else {
185+ return Err(Error::unsupported(
186+ "AV1 seq_force_screen_content_tools",
187+ "value must be 0, 1 or SELECT (2)",
188+ ));
189+ }
190+ // seq_force_integer_mv: only coded when screen content tools are on.
191+ if s.seq_force_screen_content_tools > 0 {
192+ if s.seq_force_integer_mv == SELECT_INTEGER_MV {
193+ w.write_bit(true);
194+ } else if s.seq_force_integer_mv <= 1 {
195+ w.write_bit(false);
196+ w.write_bits(s.seq_force_integer_mv as u32, 1);
197+ } else {
198+ return Err(Error::unsupported(
199+ "AV1 seq_force_integer_mv",
200+ "value must be 0, 1 or SELECT (2)",
201+ ));
202+ }
203+ }
204+ if s.enable_order_hint {
205+ w.write_bits(s.order_hint_bits - 1, 3);
206+ }
207+
208+ w.write_bit(s.enable_superres);
209+ w.write_bit(s.enable_cdef);
210+ w.write_bit(s.enable_restoration);
211+ write_color_config(w, &s.color_config, s.seq_profile)?;
212+ w.write_bit(s.film_grain_params_present);
213+ write_trailing_bits(w);
214+ Ok(())
215+}
216+
217+/// Build a complete sequence-header OBU (spec 5.5.1): the payload from
218+/// [`write_sequence_header`] wrapped by [`wrap_obu`] with
219+/// [`ObuType::SequenceHeader`], `has_size_field` set and no extension header.
220+pub fn sequence_header_obu(s: &SequenceHeader) -> Result<Vec<u8>> {
221+ let mut w = BitWriter::new();
222+ write_sequence_header(&mut w, s)?;
223+ let payload = w.into_bytes();
224+ Ok(wrap_obu(
225+ &ObuHeader {
226+ obu_type: ObuType::SequenceHeader,
227+ extension_flag: false,
228+ has_size_field: true,
229+ temporal_id: 0,
230+ spatial_id: 0,
231+ },
232+ &payload,
233+ ))
234+}
235+
236+#[cfg(test)]
237+pub(crate) mod tests {
238+ use super::*;
239+ use ec_av1_syntax::obu::{ObuHeader, read_leb128};
240+ use ec_av1_syntax::sequence::SequenceHeader;
241+ use ec_core::{BitReader, BitWriter};
242+
243+ /// A realistic 1920x1080 8-bit 4:2:0 main-profile sequence header.
244+ pub(crate) fn sample_1080p() -> SequenceHeader {
245+ SequenceHeader {
246+ seq_profile: 0,
247+ still_picture: false,
248+ reduced_still_picture_header: false,
249+ timing_info: None,
250+ decoder_model_info: None,
251+ initial_display_delay_present_flag: false,
252+ operating_points: vec![OperatingPoint {
253+ idc: 0,
254+ seq_level_idx: 8, // level 4.0; > 7 so seq_tier is coded
255+ seq_tier: 0,
256+ decoder_model_present: false,
257+ decoder_buffer_delay: 0,
258+ encoder_buffer_delay: 0,
259+ low_delay_mode_flag: false,
260+ initial_display_delay: 0,
261+ }],
262+ operating_point: 0,
263+ operating_point_idc: 0,
264+ frame_width_bits: 11,
265+ frame_height_bits: 11,
266+ max_frame_width: 1920,
267+ max_frame_height: 1080,
268+ frame_id_numbers_present_flag: false,
269+ delta_frame_id_length: 0,
270+ additional_frame_id_length: 0,
271+ use_128x128_superblock: true,
272+ enable_filter_intra: true,
273+ enable_intra_edge_filter: true,
274+ enable_interintra_compound: false,
275+ enable_masked_compound: false,
276+ enable_warped_motion: false,
277+ enable_dual_filter: true,
278+ enable_order_hint: true,
279+ enable_jnt_comp: false,
280+ enable_ref_frame_mvs: false,
281+ seq_force_screen_content_tools: SELECT_SCREEN_CONTENT_TOOLS,
282+ seq_force_integer_mv: SELECT_INTEGER_MV,
283+ order_hint_bits: 7,
284+ enable_superres: false,
285+ enable_cdef: true,
286+ enable_restoration: false,
287+ color_config: ColorConfig {
288+ bit_depth: 8,
289+ mono_chrome: false,
290+ num_planes: 3,
291+ color_primaries: 2,
292+ transfer_characteristics: 2,
293+ matrix_coefficients: 2,
294+ color_range: false,
295+ subsampling_x: 1,
296+ subsampling_y: 1,
297+ chroma_sample_position: ChromaSamplePosition::Unknown,
298+ separate_uv_delta_q: false,
299+ },
300+ film_grain_params_present: false,
301+ }
302+ }
303+
304+ #[test]
305+ fn sequence_header_roundtrip() {
306+ let original = sample_1080p();
307+ let mut w = BitWriter::new();
308+ write_sequence_header(&mut w, &original).unwrap();
309+ let payload = w.into_bytes();
310+
311+ let mut r = BitReader::new(&payload);
312+ let parsed = SequenceHeader::parse(&mut r).unwrap();
313+ assert_eq!(parsed, original);
314+ }
315+
316+ #[test]
317+ fn sequence_header_obu_size_matches_payload() {
318+ let s = sample_1080p();
319+
320+ // The payload the OBU must carry.
321+ let mut w = BitWriter::new();
322+ write_sequence_header(&mut w, &s).unwrap();
323+ let payload = w.into_bytes();
324+
325+ let obu = sequence_header_obu(&s).unwrap();
326+
327+ // Header (no extension) → leb128 size → payload.
328+ let mut r = BitReader::new(&obu);
329+ let h = ObuHeader::parse(&mut r).unwrap();
330+ assert_eq!(h.obu_type, ObuType::SequenceHeader);
331+ assert!(h.has_size_field);
332+ let size = read_leb128(&mut r).unwrap();
333+ assert_eq!(size as usize, payload.len());
334+
335+ // The trailing slice re-parses to the same header.
336+ let body = &obu[obu.len() - payload.len()..];
337+ let mut r2 = BitReader::new(body);
338+ let parsed = SequenceHeader::parse(&mut r2).unwrap();
339+ assert_eq!(parsed, s);
340+ }
341+}