forge
Explore
Log in

Don't you dare go Hollow

The Golomb tail carries levels the base range cannot reach

Browse files at this commit

0eba7705ffda46bd2a87bcbde8f116f9fd8faf4cAhmet Kaan GümüşParent: 7f9b390
  • feat
    • the Golomb tail carries levels the base range cannot reach
Show full message
feat(av1): the Golomb tail carries levels the base range cannot reach

The base and base-range syntax reach level fourteen between them, and
until now the writer refused anything above it. The spec carries the
rest as a Golomb tail — the remainder plus one, as its bit length in
unary followed by its own bits — written after the coefficient's sign
rather than beside its level, which is where `write_golomb` now puts it.
The refusal moves up to the largest level the spec's twenty-bit reader
can read back.

Two gates. The spec's own `read_golomb`, written from the pseudocode,
must hand back the level that was asked for over the whole range, which
fails the moment the tail is a bit long, a bit short, or written against
the wrong base. And ffmpeg must decode a run of DC levels either side of
the threshold into a run of steadily brighter blocks, with the negatives
of the same levels steadily darker, which fails if the tail lands in the
wrong place in the syntax.
crates/ec-av1/src/msac.rsmodified+4 -4
@@ -204,13 +204,13 @@ fn update_cdf(cdf: &mut [u16], symbol: usize) {
204204 }
205205
206206 #[cfg(test)]
207-mod tests {
207+pub(crate) mod tests {
208208 use super::*;
209209
210210 /// The decoding process of spec 8.2, written from the specification's
211211 /// pseudocode so that the roundtrip tests measure the encoder against the
212212 /// decoder AV1 defines rather than against the encoder's own arithmetic.
213- struct SymbolDecoder<'a> {
213+ pub(crate) struct SymbolDecoder<'a> {
214214 data: &'a [u8],
215215 /// Next bit to read, as a bit offset into `data`.
216216 bit: usize,
@@ -223,7 +223,7 @@ mod tests {
223223
224224 impl<'a> SymbolDecoder<'a> {
225225 /// `init_symbol` (spec 8.2.2).
226- fn new(data: &'a [u8]) -> SymbolDecoder<'a> {
226+ pub(crate) fn new(data: &'a [u8]) -> SymbolDecoder<'a> {
227227 let mut d = SymbolDecoder {
228228 data,
229229 bit: 0,
@@ -285,7 +285,7 @@ mod tests {
285285 symbol
286286 }
287287
288- fn literal(&mut self, bits: u32) -> u32 {
288+ pub(crate) fn literal(&mut self, bits: u32) -> u32 {
289289 let mut v = 0;
290290 for _ in 0..bits {
291291 v = (v << 1) | self.symbol_fixed(&EQUIPROBABLE) as u32;
crates/ec-av1/src/tile.rsmodified+140 -6
@@ -68,7 +68,12 @@ const COEFF_BASE_RANGE: i32 = 12;
6868 /// carries.
6969 const BR_STEP: i32 = 3;
7070 /// The largest level the base and base-range syntax carry between them.
71-const MAX_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
71+/// Anything above it is written as a Golomb tail on top of this.
72+const MAX_BR_LEVEL: i32 = NUM_BASE_LEVELS + COEFF_BASE_RANGE;
73+/// The largest level this writer codes. The Golomb tail is a length in unary
74+/// followed by that many bits, and the spec's decoder reads at most twenty of
75+/// each, so a level a decoder cannot read back is refused rather than written.
76+const MAX_LEVEL: i32 = MAX_BR_LEVEL + (1 << 19);
7277 /// The q-context band whose default CDFs [`crate::cdf`] carries.
7378 const Q_CTX_2: std::ops::RangeInclusive<u8> = 61..=120;
7479
@@ -610,8 +615,9 @@ fn level_grid(coeffs: &[Coeff], side: usize) -> Result<Vec<i32>> {
610615 if coeff.level == 0 || coeff.level.abs() > MAX_LEVEL {
611616 return Err(Error::unsupported(
612617 "AV1 tile",
613- "coefficients are written for levels -14..=14 without zero; \
614- wider levels need the Golomb tail",
618+ format!(
619+ "coefficients are written for levels -{MAX_LEVEL}..={MAX_LEVEL} without zero"
620+ ),
615621 ));
616622 }
617623 let pos = usize::from(coeff.row) * side + usize::from(coeff.col);
@@ -717,6 +723,11 @@ fn write_coeffs(
717723 } else {
718724 enc.literal(u32::from(level < 0), 1);
719725 }
726+ // A level the base and base-range syntax cannot reach carries the rest
727+ // of itself here, after its own sign (spec 5.11.39).
728+ if level.abs() > MAX_BR_LEVEL {
729+ write_golomb(enc, (level.abs() - MAX_BR_LEVEL - 1) as u32);
730+ }
720731 }
721732 }
722733
@@ -749,6 +760,20 @@ fn write_eob(enc: &mut SymbolEncoder, coding: &TxbCoding, eob: usize) {
749760 }
750761 }
751762
763+/// Writes the remainder of a level the base and base-range syntax could not
764+/// reach (spec 5.11.40): the value plus one, as its bit length in unary
765+/// followed by the value's own bits, most significant first.
766+pub(crate) fn write_golomb(enc: &mut SymbolEncoder, value: u32) {
767+ let x = value + 1;
768+ let length = 32 - x.leading_zeros();
769+ for _ in 0..length - 1 {
770+ enc.literal(0, 1);
771+ }
772+ for i in (0..length).rev() {
773+ enc.literal((x >> i) & 1, 1);
774+ }
775+}
776+
752777 /// The context of the level of the last coded coefficient (spec 8.3.2): how
753778 /// far into the scan it sits, in quarters and eighths of the transform.
754779 fn eob_coeff_ctx(scan_idx: usize, area: usize) -> usize {
@@ -813,7 +838,7 @@ fn check_levels(levels: &[i32], blocks: usize, base_q_idx: u8) -> Result<()> {
813838 "a DC-only key frame needs one level per coded block",
814839 ));
815840 }
816- if levels.iter().any(|&l| l == 0 || l.abs() > MAX_LEVEL) {
841+ if levels.iter().any(|&l| l == 0 || l.abs() > MAX_BR_LEVEL) {
817842 return Err(Error::unsupported(
818843 "AV1 tile",
819844 "a DC-only key frame is written for levels -14..=14 without zero; \
@@ -1852,6 +1877,115 @@ mod tests {
18521877 );
18531878 }
18541879
1880+ /// The mean sample of a decoded block.
1881+ fn mean_of(block: &[Vec<u8>]) -> f64 {
1882+ let sum: i32 = block.iter().flatten().map(|&s| i32::from(s)).sum();
1883+ f64::from(sum) / (block.len() * block[0].len()) as f64
1884+ }
1885+
1886+ /// The top-left block of a frame whose only coefficient is a luma DC of
1887+ /// `level`.
1888+ fn decode_dc_level_block(level: i32) -> Vec<Vec<u8>> {
1889+ let blocks = vec![
1890+ vec![Coeff {
1891+ row: 0,
1892+ col: 0,
1893+ level,
1894+ }],
1895+ Vec::new(),
1896+ Vec::new(),
1897+ Vec::new(),
1898+ ];
1899+ top_left_block(&decode_coeff_quadrants(&blocks))
1900+ }
1901+
1902+ /// `read_golomb` (spec 5.11.40), written from the specification's
1903+ /// pseudocode, and the level its caller builds from it: a level above the
1904+ /// base-range tail is fifteen plus what the tail carries.
1905+ fn read_golomb_level(dec: &mut crate::msac::tests::SymbolDecoder) -> u32 {
1906+ let mut length = 0;
1907+ while dec.literal(1) == 0 {
1908+ length += 1;
1909+ assert!(
1910+ length < 20,
1911+ "the tail's length prefix runs past twenty bits"
1912+ );
1913+ }
1914+ let mut x = 1;
1915+ for _ in 0..length {
1916+ x = (x << 1) | dec.literal(1);
1917+ }
1918+ (MAX_BR_LEVEL + 1) as u32 + (x - 1)
1919+ }
1920+
1921+ /// The tail says how much of the level the base and base-range syntax could
1922+ /// not carry, and the spec's own reader must hand back the level that was
1923+ /// asked for — not one either side of it. A tail written a bit long, a bit
1924+ /// short, or against the wrong base fails this at the first level it
1925+ /// reaches.
1926+ #[test]
1927+ fn the_golomb_tail_reads_back_as_the_level_it_was_written_for() {
1928+ for level in (MAX_BR_LEVEL + 1..=MAX_BR_LEVEL + 300)
1929+ .chain([MAX_LEVEL - 1, MAX_LEVEL])
1930+ .map(|l| l as u32)
1931+ {
1932+ let mut enc = SymbolEncoder::new();
1933+ write_golomb(&mut enc, level - (MAX_BR_LEVEL + 1) as u32);
1934+ // The tail is raw bits, so it needs no padding beyond what the
1935+ // encoder's own flush writes.
1936+ let data = enc.finish();
1937+ let mut dec = crate::msac::tests::SymbolDecoder::new(&data);
1938+ assert_eq!(
1939+ read_golomb_level(&mut dec),
1940+ level,
1941+ "the tail of level {level}"
1942+ );
1943+ }
1944+ }
1945+
1946+ /// The base and base-range syntax reach level fourteen between them;
1947+ /// anything above that carries the rest of itself as a Golomb tail, written
1948+ /// after its own sign. A DC level moves the whole block off its mid-grey
1949+ /// prediction by an amount that grows with the level, so a run of levels
1950+ /// either side of the tail's threshold — spaced wide enough that the
1951+ /// quantiser separates them — must decode to a run of steadily
1952+ /// brighter blocks — and the negatives of the same levels to steadily
1953+ /// darker ones. A tail written with the wrong length, in the wrong place in
1954+ /// the syntax, or off by one desyncs the decoder outright.
1955+ #[test]
1956+ fn levels_above_the_base_range_tail_carry_a_golomb_tail() {
1957+ if !have_ffmpeg() {
1958+ eprintln!("SKIP levels_above_the_base_range_tail_carry_a_golomb_tail: no ffmpeg");
1959+ return;
1960+ }
1961+ let mut brighter = Vec::new();
1962+ let mut darker = Vec::new();
1963+ for level in [10, 14, 18, 31, 60, 400] {
1964+ brighter.push((level, mean_of(&decode_dc_level_block(level))));
1965+ darker.push((level, mean_of(&decode_dc_level_block(-level))));
1966+ }
1967+ for pair in brighter.windows(2) {
1968+ let [(low, dim), (high, bright)] = [pair[0], pair[1]];
1969+ assert!(
1970+ bright > dim,
1971+ "level {high} decodes brighter than level {low}, got {bright} against {dim}"
1972+ );
1973+ }
1974+ for pair in darker.windows(2) {
1975+ let [(low, bright), (high, dim)] = [pair[0], pair[1]];
1976+ assert!(
1977+ dim < bright,
1978+ "level -{high} decodes darker than level -{low}, got {dim} against {bright}"
1979+ );
1980+ }
1981+ let (_, mid) = brighter[0];
1982+ assert!(
1983+ mid > 128.0 && darker[0].1 < 128.0,
1984+ "a positive level brightens its block and a negative one darkens it, got {mid} and {}",
1985+ darker[0].1
1986+ );
1987+ }
1988+
18551989 /// A frame need not be a whole number of superblocks. A 96x64 frame is a
18561990 /// superblock and a half across: the second superblock has no right-hand
18571991 /// half, so its partition is a gathered flag rather than the full symbol,
@@ -2016,12 +2150,12 @@ mod tests {
20162150 }];
20172151 b
20182152 }),
2019- ("a level past the base-range tail", {
2153+ ("a level past the Golomb tail's reach", {
20202154 let mut b = empty();
20212155 b[2].luma = vec![Coeff {
20222156 row: 0,
20232157 col: 0,
2024- level: 15,
2158+ level: MAX_LEVEL + 1,
20252159 }];
20262160 b
20272161 }),