threers-codec 0.0.12

Pure-Rust media codecs: H.264/HEVC/VP9 encoders, H.264/HEVC/VP9/AV1 decoders, AAC/MP3/Opus/Vorbis/FLAC/WAV decoders, AAC-LC and MP3 encoders, MP4/WebM/Matroska/Ogg, GIF/APNG, captions, and VideoToolbox acceleration on macOS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
//! HEVC residual (transform-coefficient) CABAC coding — `residual_coding`
//! (H.265 §7.3.8.11, context derivation §9.3.4.2). The most intricate syntax in
//! HEVC: last-significant position, per-sub-block significance, greater-1/2
//! flags, signs, and Golomb-Rice remainders, each with position/neighbor-derived
//! contexts.
//!
//! Verified two ways, and only the second is load-bearing. The `tests` module
//! round-trips random coefficient blocks through the encoder and a matching
//! decoder, which checks the *syntax logic* — but both sides share this crate's
//! constants, so it cannot see a wrong one (below). Conformance comes from
//! `tests/hevc_residual_conformance.rs`, which decodes with ffmpeg.
//!
//! # Resolved: the conformance gap was two bytes in the CABAC tables
//!
//! This coder used to produce streams ffmpeg parsed without complaint but
//! reconstructed differently, on anything but smooth content. The cause was not
//! in this file at all: `tables.rs` had `transIdxLps[28] = 23` (spec: 22) and
//! `rangeTabLps[31][0] = 28` (spec: 29).
//!
//! Both are worth remembering as a *testing* lesson rather than a transcription
//! one. The round-trip test in the `tests` module encodes and decodes with the
//! **same tables**, so a wrong table is invisible to it — the two sides agree
//! with each other while both disagree with the standard. And a context only
//! reaches state 28 or 31 after a long run of bins in one direction, so smooth
//! content (few coefficients, few bins) never got there. That combination is
//! why the failure looked content-dependent and mysterious: it needed both a
//! detailed block *and* an external decoder to show up at all.
//!
//! The wrong `transIdxLps` entry was findable without any reference: the spec
//! table is monotonically non-decreasing, and `..., 21, 21, 23, 22, 23, ...`
//! is not. `tests/hevc_residual_conformance.rs` now pins the behaviour against
//! ffmpeg on detailed content.

use crate::hevc::cabac::{CabacEncoder, CtxModel};

// ---- context init values (I-slice / initType 0, §9.3.2.2) ----
const INIT_LAST_X: [u8; 18] = [
    110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63,
];
const INIT_LAST_Y: [u8; 18] = INIT_LAST_X;
const INIT_CSBF: [u8; 4] = [91, 171, 134, 141];
// sig_coeff_flag init (§9.3.2.2, I-slice): 27 luma contexts (0..=26) then 15
// chroma contexts (27..=41). The chroma DC context is index 27.
const INIT_SIG: [u8; 42] = [
    // luma (ctxInc 0..=26)
    111, 111, 125, 110, 110, 94, 124, 108, 124, 107, 125, 141, 179, 153, 125, 107, 125, 141, 179,
    153, 125, 107, 125, 141, 179, 153, 125, //
    // chroma (ctxInc 27..=41)
    140, 139, 182, 182, 152, 136, 152, 136, 153, 136, 139, 111, 136, 139, 111,
];
const INIT_GT1: [u8; 24] = [
    140, 92, 137, 138, 140, 152, 138, 139, 153, 74, 149, 92, 139, 107, 122, 152, 140, 179, 166,
    182, 140, 227, 122, 197,
];
const INIT_GT2: [u8; 6] = [138, 153, 136, 167, 152, 152];

/// The coefficient-coding CABAC contexts for one slice.
///
/// Fixed-size arrays, not `Vec`s: rate-distortion decisions clone the whole
/// context set once per candidate per level, and six heap allocations per clone
/// dominated the encoder's time once the coding quadtree started making
/// thousands of them per picture.
#[derive(Clone, Copy)]
pub struct ResidualCtx {
    last_x: [CtxModel; 18],
    last_y: [CtxModel; 18],
    csbf: [CtxModel; 4],
    sig: [CtxModel; 42],
    gt1: [CtxModel; 24],
    gt2: [CtxModel; 6],
}

impl ResidualCtx {
    pub fn new(qp: i32) -> Self {
        Self {
            last_x: std::array::from_fn(|i| CtxModel::init(INIT_LAST_X[i], qp)),
            last_y: std::array::from_fn(|i| CtxModel::init(INIT_LAST_Y[i], qp)),
            csbf: std::array::from_fn(|i| CtxModel::init(INIT_CSBF[i], qp)),
            sig: std::array::from_fn(|i| CtxModel::init(INIT_SIG[i], qp)),
            gt1: std::array::from_fn(|i| CtxModel::init(INIT_GT1[i], qp)),
            gt2: std::array::from_fn(|i| CtxModel::init(INIT_GT2[i], qp)),
        }
    }
}

// ---- scan orders ----

/// Scan order (`0` diagonal up-right, `1` horizontal, `2` vertical) over a
/// `k × k` grid, as a list of `(x, y)`.
pub fn scan_kxk(k: usize, scan_idx: u8) -> Vec<(usize, usize)> {
    let mut v = Vec::with_capacity(k * k);
    match scan_idx {
        1 => {
            for y in 0..k {
                for x in 0..k {
                    v.push((x, y));
                }
            }
        }
        2 => {
            for x in 0..k {
                for y in 0..k {
                    v.push((x, y));
                }
            }
        }
        _ => {
            for d in 0..(2 * k - 1) {
                for x in 0..k {
                    let y = d as isize - x as isize;
                    if y >= 0 && (y as usize) < k {
                        v.push((x, y as usize));
                    }
                }
            }
        }
    }
    v
}

/// Full coefficient scan of an `n × n` transform block: sub-blocks (4×4) scanned
/// in `scan_idx`, and the 16 positions within each in the same order.
pub fn full_scan(n: usize, scan_idx: u8) -> Vec<(usize, usize)> {
    if n == 4 {
        return scan_kxk(4, scan_idx);
    }
    let sb = scan_kxk(n / 4, scan_idx);
    let inner = scan_kxk(4, scan_idx);
    let mut out = Vec::with_capacity(n * n);
    for &(sx, sy) in &sb {
        for &(px, py) in &inner {
            out.push((sx * 4 + px, sy * 4 + py));
        }
    }
    out
}

#[inline]
fn log2(n: usize) -> usize {
    n.trailing_zeros() as usize
}

/// `last_sig_coeff` group index and group base (§9.3.4.2.3 tables).
const GROUP_IDX: [usize; 32] = [
    0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, //
    8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
];
const MIN_IN_GROUP: [usize; 10] = [0, 1, 2, 3, 4, 6, 8, 12, 16, 24];

fn last_ctx(bin_idx: usize, log2n: usize, chroma: bool) -> usize {
    if chroma {
        15 + (bin_idx >> (log2n - 2))
    } else {
        let offset = 3 * (log2n - 2) + ((log2n - 1) >> 2);
        let shift = (log2n + 1) >> 2;
        (bin_idx >> shift) + offset
    }
}

/// sig_coeff_flag context index (§9.3.4.2.5). `csbf_rb` = right + 2·below CSBF.
fn sig_ctx(
    xc: usize,
    yc: usize,
    log2n: usize,
    chroma: bool,
    sub_nonzero: bool,
    csbf_rb: u8,
    scan_idx: u8,
) -> usize {
    if log2n == 2 {
        const MAP: [usize; 16] = [0, 1, 4, 5, 2, 3, 4, 5, 6, 6, 8, 8, 7, 7, 8, 8];
        let base = MAP[(yc << 2) + xc];
        return if chroma { 27 + base } else { base };
    }
    if xc + yc == 0 {
        return if chroma { 27 } else { 0 };
    }
    let (xp, yp) = (xc & 3, yc & 3);
    let mut s = match csbf_rb {
        0 => {
            if xp + yp == 0 {
                2
            } else if xp + yp < 3 {
                1
            } else {
                0
            }
        }
        1 => {
            if yp == 0 {
                2
            } else if yp == 1 {
                1
            } else {
                0
            }
        }
        2 => {
            if xp == 0 {
                2
            } else if xp == 1 {
                1
            } else {
                0
            }
        }
        _ => 2,
    };
    // Size offset (§9.3.4.2.5). At 8x8 *luma* it keys off the scan —
    // `sigCtx += (scanIdx == 0) ? 9 : 15` — which is the one place scanIdx
    // reaches this derivation. Chroma has no such split and always adds 9 at
    // 8x8; giving chroma the 15 would run its index past the 15 chroma
    // contexts the table holds.
    if !chroma {
        if sub_nonzero {
            s += 3;
        }
        s + if log2n == 3 {
            if scan_idx == 0 {
                9
            } else {
                15
            }
        } else {
            21
        }
    } else {
        27 + s + if log2n == 3 { 9 } else { 12 }
    }
}

/// Encode `coeff` (`n × n` quantized levels, row-major) for `residual_coding`.
/// `chroma` selects luma/chroma contexts; `scan_idx` the scan order. The block
/// must contain at least one nonzero level (caller codes `cbf`).
pub fn encode(
    cabac: &mut CabacEncoder,
    ctx: &mut ResidualCtx,
    coeff: &[i32],
    n: usize,
    chroma: bool,
    scan_idx: u8,
) {
    let log2n = log2(n);
    let scan = full_scan(n, scan_idx);
    let inner = scan_kxk(4, scan_idx);
    let sb_per_side = n / 4;

    // Last significant position (in scan order).
    let last_scan = (0..scan.len())
        .rev()
        .find(|&i| coeff[scan[i].1 * n + scan[i].0] != 0)
        .unwrap();
    // A vertical scan signals the last position transposed (§7.4.9.11): the
    // decoder swaps the decoded pair back, so the encoder must swap going in.
    let (last_x, last_y) = if scan_idx == 2 {
        (scan[last_scan].1, scan[last_scan].0)
    } else {
        scan[last_scan]
    };

    // --- last_sig_coeff: x_prefix, y_prefix, then x_suffix, y_suffix (§7.3.8.11) ---
    let gx = code_last_prefix(cabac, &mut ctx.last_x, last_x, log2n, chroma);
    let gy = code_last_prefix(cabac, &mut ctx.last_y, last_y, log2n, chroma);
    code_last_suffix(cabac, last_x, gx);
    code_last_suffix(cabac, last_y, gy);

    let last_sb = last_scan / 16;
    let last_pos_in_sb = last_scan % 16;

    // coded_sub_block_flag grid.
    let mut csbf = vec![vec![false; sb_per_side]; sb_per_side];
    let sb_scan = scan_kxk(sb_per_side, scan_idx);

    let mut c1_carry = 1u32; // greater1 state carried across sub-blocks

    for si in (0..=last_sb).rev() {
        let (sxs, sys) = sb_scan[si];
        let mut infer_dc = false;
        let is_first = si == 0;
        let is_last = si == last_sb;
        if !is_first && !is_last {
            let rb = csbf_right_below(&csbf, sxs, sys, sb_per_side);
            let ctx_i = (rb.min(1) as usize) + if chroma { 2 } else { 0 };
            let bit = block_has_sig(coeff, n, sxs, sys, &inner);
            cabac.encode_bin(&mut ctx.csbf[ctx_i], bit as u32);
            csbf[sys][sxs] = bit;
            if !bit {
                continue;
            }
            infer_dc = true;
        } else {
            csbf[sys][sxs] = true;
        }
        let csbf_rb = csbf_right_below(&csbf, sxs, sys, sb_per_side);

        // --- sig_coeff_flag for positions in this sub-block ---
        let start = if is_last {
            last_pos_in_sb as i32 - 1
        } else {
            15
        };
        let mut sig = [false; 16];
        if is_last {
            sig[last_pos_in_sb] = true;
        }
        let sub_nonzero = sxs + sys != 0;
        let mut num_sig = if is_last { 1 } else { 0 };
        for p in (0..=start).rev() {
            let (px, py) = inner[p as usize];
            let (xc, yc) = (sxs * 4 + px, sys * 4 + py);
            if p == 0 && infer_dc && num_sig == 0 {
                // inferred significant (sub-block coded but nothing yet).
                sig[0] = true;
                num_sig += 1;
                break;
            }
            let ci = sig_ctx(xc, yc, log2n, chroma, sub_nonzero, csbf_rb, scan_idx);
            let bit = coeff[yc * n + xc] != 0;
            cabac.encode_bin(&mut ctx.sig[ci], bit as u32);
            if bit {
                sig[p as usize] = true;
                num_sig += 1;
            }
        }
        if num_sig == 0 {
            continue;
        }

        // Significant coeffs in reverse scan order (high → low position).
        let mut abs_levels = Vec::with_capacity(num_sig);
        let mut positions = Vec::with_capacity(num_sig);
        for p in (0..16).rev() {
            if sig[p] {
                let (px, py) = inner[p];
                let (xc, yc) = (sxs * 4 + px, sys * 4 + py);
                abs_levels.push(coeff[yc * n + xc].unsigned_abs());
                positions.push((xc, yc));
            }
        }

        // --- coeff_abs_level_greater1_flag (first 8) ---
        let ctx_set_base = if si > 0 && !chroma { 2 } else { 0 };
        let ctx_set = ctx_set_base + if c1_carry == 0 { 1 } else { 0 };
        let mut c1 = 1u32;
        let mut first_gt1: i32 = -1;
        let n_gt1 = abs_levels.len().min(8);
        for idx in 0..n_gt1 {
            let bin = (abs_levels[idx] > 1) as u32;
            let base = if chroma { 16 } else { 0 };
            let ci = base + (ctx_set << 2) + c1 as usize;
            cabac.encode_bin(&mut ctx.gt1[ci], bin);
            if bin == 1 {
                c1 = 0;
                if first_gt1 < 0 {
                    first_gt1 = idx as i32;
                }
            } else if c1 > 0 && c1 < 3 {
                c1 += 1;
            }
        }
        c1_carry = c1;

        // --- coeff_abs_level_greater2_flag (first greater1 coeff only) ---
        if first_gt1 >= 0 {
            let bin = (abs_levels[first_gt1 as usize] > 2) as u32;
            let base = if chroma { 4 } else { 0 };
            cabac.encode_bin(&mut ctx.gt2[base + ctx_set], bin);
        }

        // --- coeff_sign_flag (bypass) ---
        for &(xc, yc) in &positions {
            let sign = (coeff[yc * n + xc] < 0) as u32;
            cabac.encode_bypass(sign);
        }

        // --- coeff_abs_level_remaining (bypass, Golomb-Rice) ---
        let mut first_coeff2 = 1u32;
        let mut rice = 0u32;
        for (idx, &abs) in abs_levels.iter().enumerate() {
            let base_level = if idx < 8 { 2 + first_coeff2 } else { 1 };
            if abs >= base_level {
                write_remaining(cabac, abs - base_level, rice);
                if abs > 3 * (1 << rice) {
                    rice = (rice + 1).min(4);
                }
            }
            if abs >= 2 {
                first_coeff2 = 0;
            }
        }
    }
}

/// Code the truncated-unary `last_sig_coeff_*_prefix` (each bin context-coded);
/// returns the group index for the suffix step.
fn code_last_prefix(
    cabac: &mut CabacEncoder,
    ctxs: &mut [CtxModel],
    pos: usize,
    log2n: usize,
    chroma: bool,
) -> usize {
    let group = GROUP_IDX[pos];
    let c_max = (log2n << 1) - 1;
    for b in 0..group {
        cabac.encode_bin(&mut ctxs[last_ctx(b, log2n, chroma)], 1);
    }
    if group < c_max {
        cabac.encode_bin(&mut ctxs[last_ctx(group, log2n, chroma)], 0);
    }
    group
}

/// Fixed-length `last_sig_coeff_*_suffix` (bypass) when the group spans a range.
fn code_last_suffix(cabac: &mut CabacEncoder, pos: usize, group: usize) {
    if group > 3 {
        let nbits = (group >> 1) - 1;
        let suffix = (pos - MIN_IN_GROUP[group]) as u32;
        cabac.encode_bypass_bits(suffix, nbits as u32);
    }
}

/// Golomb-Rice / exp-Golomb `coeff_abs_level_remaining` (§9.3.3.9), all bypass.
fn write_remaining(cabac: &mut CabacEncoder, value: u32, rice: u32) {
    let threshold = 3u32 << rice;
    if value < threshold {
        let prefix = value >> rice;
        // `prefix` ones then a 0.
        for _ in 0..prefix {
            cabac.encode_bypass(1);
        }
        cabac.encode_bypass(0);
        if rice > 0 {
            cabac.encode_bypass_bits(value & ((1 << rice) - 1), rice);
        }
    } else {
        let mut v = value - threshold;
        let mut len = rice;
        while v >= (1 << len) {
            v -= 1 << len;
            len += 1;
        }
        // Escape prefix: (3 + len − rice) ones then a 0, then `len` suffix bits.
        let prefix_ones = 3 + len - rice;
        for _ in 0..prefix_ones {
            cabac.encode_bypass(1);
        }
        cabac.encode_bypass(0);
        cabac.encode_bypass_bits(v, len);
    }
}

fn csbf_right_below(csbf: &[Vec<bool>], sx: usize, sy: usize, side: usize) -> u8 {
    let right = if sx + 1 < side {
        csbf[sy][sx + 1] as u8
    } else {
        0
    };
    let below = if sy + 1 < side {
        csbf[sy + 1][sx] as u8
    } else {
        0
    };
    right + 2 * below
}

fn block_has_sig(
    coeff: &[i32],
    n: usize,
    sxs: usize,
    sys: usize,
    inner: &[(usize, usize)],
) -> bool {
    inner
        .iter()
        .any(|&(px, py)| coeff[(sys * 4 + py) * n + (sxs * 4 + px)] != 0)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The two `last_sig_coeff` tables have to agree, and the suffix width has
    /// to span each group exactly.
    ///
    /// `MIN_IN_GROUP[g]` is where group `g` starts and the suffix carries
    /// `(g >> 1) - 1` bits, so every group above 3 must hold precisely that many
    /// positions. A transcription slip in either table breaks the identity, and
    /// nothing else would notice until a decoder read the wrong position.
    #[test]
    fn last_significant_coefficient_groups_tile_the_positions() {
        for (pos, &g) in GROUP_IDX.iter().enumerate() {
            let first = GROUP_IDX.iter().position(|&x| x == g).unwrap();
            assert_eq!(MIN_IN_GROUP[g], first, "group {g} starts at {first}");
            assert!(pos >= MIN_IN_GROUP[g], "position {pos} precedes its group");
        }
        for g in 4..MIN_IN_GROUP.len() {
            let end = MIN_IN_GROUP.get(g + 1).copied().unwrap_or(GROUP_IDX.len());
            let span = end - MIN_IN_GROUP[g];
            assert_eq!(span, 1 << ((g >> 1) - 1), "group {g} spans {span}");
        }
        // `last_sig_coeff_prefix` is truncated unary with cMax = 2·log2 − 1, so
        // the largest group a 32-point transform can name is 9.
        assert_eq!(GROUP_IDX[31], (5 << 1) - 1);
    }
    use crate::hevc::cabac::CtxModel;

    // A CABAC decoder + residual decoder mirror, to round-trip the coefficient
    // coding logic independent of whether the init values match the spec.
    include!("residual_decode_test.rs");
}