still265 0.6.1

Pure-Rust HEVC/H.265 still-image encoder with BPG and HEIC support
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
#![allow(dead_code)]
//! Debug utilities for HEVC decoder
//!
//! This module provides invariant checking, logging, and comparison tools
//! for debugging the decoder.

extern crate alloc;

use alloc::format;
use alloc::vec::Vec;
use core::sync::atomic::{AtomicBool, AtomicU32, Ordering};

/// Per-CU/PU/TU decision capture for encoder-comparison analysis.
///
/// The decoder is bit-exact, so decoding a `.bpg` recovers *every* decision the
/// producing encoder made — intra mode, TU partition, quantised coefficient
/// levels, residual energy. Enabling this log during a decode collects those
/// decisions so two encoders' outputs of the same image can be diffed
/// stage-by-stage (predict → transform-unit → quant) without instrumenting the
/// reference encoder. See `bpg-tools` `decision_diff`.
pub static DECISION_LOG_ACTIVE: AtomicBool = AtomicBool::new(false);

/// A prediction-unit decision (one intra luma mode over a square region).
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub struct PuRecord {
    pub x: u32,
    pub y: u32,
    pub log2_size: u8,
    pub luma_mode: u8,
    pub chroma_mode: u8,
}

/// A transform-unit decision (coded residual block).
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub struct TuRecord {
    pub x: u32,
    pub y: u32,
    pub log2_size: u8,
    pub c_idx: u8,
    /// Number of non-zero quantised levels.
    pub nz: u32,
    /// Sum of absolute quantised levels (coded magnitude).
    pub abs_level_sum: u64,
    /// Energy (Σ r²) of the reconstructed residual after the inverse transform.
    pub residual_energy: u64,
}

/// Collected decisions for one decode.
#[cfg(feature = "std")]
#[derive(Default)]
#[allow(missing_docs)]
pub struct DecisionLog {
    pub pus: Vec<PuRecord>,
    pub tus: Vec<TuRecord>,
}

#[cfg(feature = "std")]
static DECISION_LOG: std::sync::Mutex<Option<DecisionLog>> = std::sync::Mutex::new(None);

/// Fast inactive-path check (one relaxed atomic load); call sites skip the
/// (possibly expensive) record construction when the log is off.
#[inline]
pub fn decision_log_active() -> bool {
    DECISION_LOG_ACTIVE.load(Ordering::Relaxed)
}

/// Start a fresh decision log (clears any previous contents).
#[cfg(feature = "std")]
pub fn enable_decision_log() {
    *DECISION_LOG.lock().unwrap() = Some(DecisionLog::default());
    DECISION_LOG_ACTIVE.store(true, Ordering::Relaxed);
}

/// Stop logging and take the collected decisions.
#[cfg(feature = "std")]
pub fn take_decision_log() -> Option<DecisionLog> {
    DECISION_LOG_ACTIVE.store(false, Ordering::Relaxed);
    DECISION_LOG.lock().unwrap().take()
}

/// Record a PU decision (no-op when logging is inactive).
#[cfg(feature = "std")]
pub fn log_pu(rec: PuRecord) {
    if let Some(log) = DECISION_LOG.lock().unwrap().as_mut() {
        log.pus.push(rec);
    }
}

/// Record a TU decision (no-op when logging is inactive).
#[cfg(feature = "std")]
pub fn log_tu(rec: TuRecord) {
    if let Some(log) = DECISION_LOG.lock().unwrap().as_mut() {
        log.tus.push(rec);
    }
}

/// Parsed `BPG_STILL_DUMP=x,y,log2[,c_idx]` forensic target (shared with the
/// encoder so the same coordinate dumps from both sides). `None` when unset.
#[cfg(feature = "std")]
pub fn dump_target() -> Option<(u32, u32, u8, u8)> {
    use std::sync::OnceLock;
    static VALUE: OnceLock<Option<(u32, u32, u8, u8)>> = OnceLock::new();
    *VALUE.get_or_init(|| {
        let raw = std::env::var("BPG_STILL_DUMP").ok()?;
        let mut it = raw.split(',').map(|s| s.trim());
        let x = it.next()?.parse::<u32>().ok()?;
        let y = it.next()?.parse::<u32>().ok()?;
        let log2 = it.next()?.parse::<u8>().ok()?;
        let c_idx = it.next().and_then(|s| s.parse::<u8>().ok()).unwrap_or(0);
        Some((x, y, log2, c_idx))
    })
}

/// Forensic dump of one decoded TU's residual pipeline (env-gated by
/// `BPG_STILL_DUMP`). Mirrors the encoder's `dump_block_pipeline` field-for-field
/// so a C-produced `.bpg` (decoded bit-exactly) can be diffed against still265's
/// own dump for the same coordinate — no x265 patch needed.
#[cfg(feature = "std")]
#[allow(clippy::too_many_arguments)]
pub fn dump_decode_block(
    x0: u32,
    y0: u32,
    _log2_size: u8,
    c_idx: u8,
    levels: &[i16],
    dequant: &[i16],
    residual: &[i16],
    pred: &[u16],
    recon: &[u16],
    size: usize,
) {
    use std::fmt::Write as _;
    let nnz = levels.iter().filter(|&&l| l != 0).count();
    let mut s = String::with_capacity(4096);
    let _ = writeln!(
        s,
        "=== C-DECODE BLOCK DUMP x={x0} y={y0} size={size} c_idx={c_idx} nnz={nnz} ==="
    );
    let grid = |s: &mut String, label: &str, get: &dyn Fn(usize) -> i64| {
        let _ = writeln!(s, "[{label}]");
        for r in 0..size {
            for c in 0..size {
                let _ = write!(s, "{:6}", get(r * size + c));
            }
            let _ = writeln!(s);
        }
    };
    grid(&mut s, "PRED", &|i| {
        pred.get(i).copied().unwrap_or(0) as i64
    });
    grid(&mut s, "LEVELS", &|i| {
        levels.get(i).copied().unwrap_or(0) as i64
    });
    grid(&mut s, "DEQUANT", &|i| {
        dequant.get(i).copied().unwrap_or(0) as i64
    });
    grid(&mut s, "INV_RESIDUAL", &|i| {
        residual.get(i).copied().unwrap_or(0) as i64
    });
    grid(&mut s, "RECON", &|i| {
        recon.get(i).copied().unwrap_or(0) as i64
    });
    let res_e: i64 = (0..size * size)
        .map(|i| {
            let v = residual.get(i).copied().unwrap_or(0) as i64;
            v * v
        })
        .sum();
    let abs_level: i64 = levels.iter().map(|&l| l.unsigned_abs() as i64).sum();
    let _ = writeln!(
        s,
        "[SUMMARY] residual_energy={res_e} abs_level_sum={abs_level}"
    );
    eprint!("{s}");
}

/// No-op stubs for `no_std` (no global allocator-backed mutex available).
#[cfg(not(feature = "std"))]
pub fn log_pu(_rec: PuRecord) {}
/// No-op stub for `no_std`.
#[cfg(not(feature = "std"))]
pub fn log_tu(_rec: TuRecord) {}

/// Enable verbose coefficient logging
pub static VERBOSE_COEFFS: AtomicBool = AtomicBool::new(false);

/// Enable CABAC state logging
pub static VERBOSE_CABAC: AtomicBool = AtomicBool::new(false);

/// Count of detected invariant violations
pub static INVARIANT_VIOLATIONS: AtomicU32 = AtomicU32::new(0);

/// Log an invariant violation and optionally panic
#[cold]
pub fn invariant_violation(msg: &str, should_panic: bool) {
    let count = INVARIANT_VIOLATIONS.fetch_add(1, Ordering::Relaxed);
    #[cfg(feature = "std")]
    eprintln!("INVARIANT VIOLATION #{}: {}", count + 1, msg);
    let _ = count;
    if should_panic {
        panic!("invariant violation: {}", msg);
    }
}

/// Check CABAC decoder invariants
pub fn check_cabac_invariants(range: u16, offset: u16, context: &str) {
    // After renormalization, range should be >= 256
    if range < 256 {
        invariant_violation(&format!("{}: CABAC range {} < 256", context, range), false);
    }

    // Offset should always be < range
    if offset >= range {
        invariant_violation(
            &format!("{}: CABAC offset {} >= range {}", context, offset, range),
            false,
        );
    }

    // Range should be <= 510 (initial value)
    if range > 510 {
        invariant_violation(&format!("{}: CABAC range {} > 510", context, range), true);
    }
}

/// Check coefficient value invariants
pub fn check_coeff_invariants(value: i16, max_coeff: i16, context: &str) {
    if value.abs() > max_coeff {
        invariant_violation(
            &format!(
                "{}: coefficient {} exceeds max {}",
                context, value, max_coeff
            ),
            false,
        );
    }
}

/// Coefficient decode event for logging
#[derive(Debug, Clone)]
#[allow(missing_docs)]
pub struct CoeffEvent {
    pub tu_x: u32,
    pub tu_y: u32,
    pub c_idx: u8,
    pub sb_idx: u32,
    pub pos: u8,
    pub base_level: i16,
    pub remaining: i16,
    pub sign: i8,
    pub final_value: i16,
    pub cabac_range: u16,
    pub cabac_offset: u16,
}

/// Event log for a single TU decode
#[allow(missing_docs)]
pub struct TuDecodeLog {
    pub events: Vec<CoeffEvent>,
    pub tu_x: u32,
    pub tu_y: u32,
    pub c_idx: u8,
    pub log2_size: u8,
    pub last_x: u32,
    pub last_y: u32,
}

impl TuDecodeLog {
    /// Create a new TU decode log
    pub fn new(tu_x: u32, tu_y: u32, c_idx: u8, log2_size: u8) -> Self {
        Self {
            events: Vec::new(),
            tu_x,
            tu_y,
            c_idx,
            log2_size,
            last_x: 0,
            last_y: 0,
        }
    }

    /// Log a coefficient decode event
    pub fn log_coeff(&mut self, event: CoeffEvent) {
        self.events.push(event);
    }

    /// Print summary of decoded coefficients
    #[cfg(feature = "std")]
    pub fn print_summary(&self) {
        eprintln!(
            "TU ({},{}) c_idx={} size={}x{} last=({},{}) coeffs={}",
            self.tu_x,
            self.tu_y,
            self.c_idx,
            1 << self.log2_size,
            1 << self.log2_size,
            self.last_x,
            self.last_y,
            self.events.len()
        );

        for (i, ev) in self.events.iter().enumerate() {
            eprintln!(
                "  [{}] sb={} pos={}: base={} rem={} sign={} final={} (range={} off={})",
                i,
                ev.sb_idx,
                ev.pos,
                ev.base_level,
                ev.remaining,
                ev.sign,
                ev.final_value,
                ev.cabac_range,
                ev.cabac_offset
            );
        }
    }
}

/// Compare two coefficient buffers and report differences
pub fn compare_coeffs(
    ours: &[i16],
    reference: &[i16],
    size: usize,
    context: &str,
) -> Vec<(usize, usize, i16, i16)> {
    let mut diffs = Vec::new();

    for y in 0..size {
        for x in 0..size {
            let idx = y * size + x;
            if idx < ours.len() && idx < reference.len() && ours[idx] != reference[idx] {
                diffs.push((x, y, ours[idx], reference[idx]));
            }
        }
    }

    #[cfg(feature = "std")]
    if !diffs.is_empty() {
        eprintln!("{}: {} differences found:", context, diffs.len());
        for (x, y, ours_val, ref_val) in &diffs[..diffs.len().min(10)] {
            eprintln!("  ({},{}) ours={} ref={}", x, y, ours_val, ref_val);
        }
        if diffs.len() > 10 {
            eprintln!("  ... and {} more", diffs.len() - 10);
        }
    }

    diffs
}

/// Calculate checksum of coefficient buffer for quick comparison
pub fn coeff_checksum(coeffs: &[i16], size: usize) -> u64 {
    let mut sum = 0u64;
    for y in 0..size {
        for x in 0..size {
            let idx = y * size + x;
            if idx < coeffs.len() {
                // Include position in checksum to catch ordering issues
                sum = sum.wrapping_add((coeffs[idx] as i64).wrapping_mul(idx as i64 + 1) as u64);
            }
        }
    }
    sum
}

/// CABAC state tracker for debugging
/// Tracks byte position progression to detect desync
#[derive(Default)]
pub struct CabacTracker {
    /// Byte positions at each CTU start
    ctu_positions: alloc::vec::Vec<(u32, usize)>,
    /// Number of large coefficients detected (indicates desync)
    large_coeff_count: u32,
    /// First byte position where large coefficients appeared
    first_large_coeff_byte: Option<usize>,
}

impl CabacTracker {
    /// Create a new tracker
    pub fn new() -> Self {
        Self::default()
    }

    /// Record CTU start position
    pub fn record_ctu_start(&mut self, ctu_idx: u32, byte_pos: usize) {
        self.ctu_positions.push((ctu_idx, byte_pos));
    }

    /// Record a large coefficient (indicates potential desync)
    pub fn record_large_coeff(&mut self, byte_pos: usize) {
        self.large_coeff_count += 1;
        if self.first_large_coeff_byte.is_none() {
            self.first_large_coeff_byte = Some(byte_pos);
        }
    }

    /// Print summary of tracking data
    #[cfg(feature = "std")]
    pub fn print_summary(&self) {
        if !self.ctu_positions.is_empty() {
            eprintln!("CABAC Tracker Summary:");
            eprintln!("  CTUs tracked: {}", self.ctu_positions.len());
            if let Some((last_ctu, last_pos)) = self.ctu_positions.last() {
                eprintln!("  Last CTU: {} at byte {}", last_ctu, last_pos);
            }
            eprintln!("  Large coeffs: {}", self.large_coeff_count);
            if let Some(pos) = self.first_large_coeff_byte {
                eprintln!("  First large coeff at byte: {}", pos);
                // Find which CTU this corresponds to
                for (ctu_idx, ctu_pos) in self.ctu_positions.iter().rev() {
                    if *ctu_pos <= pos {
                        eprintln!("  (in or after CTU {})", ctu_idx);
                        break;
                    }
                }
            }
        }
    }

    /// Check if desync is likely occurring
    pub fn is_likely_desynced(&self) -> bool {
        self.large_coeff_count > 5
    }
}

/// Global tracker instance
#[cfg(feature = "std")]
static TRACKER: std::sync::Mutex<Option<CabacTracker>> = std::sync::Mutex::new(None);

/// Initialize global tracker
#[cfg(feature = "std")]
pub fn init_tracker() {
    *TRACKER.lock().unwrap() = Some(CabacTracker::new());
}

/// Record CTU start in global tracker
#[cfg(feature = "std")]
pub fn track_ctu_start(ctu_idx: u32, byte_pos: usize) {
    if let Some(tracker) = TRACKER.lock().unwrap().as_mut() {
        tracker.record_ctu_start(ctu_idx, byte_pos);
    }
}

/// Record large coefficient in global tracker
#[cfg(feature = "std")]
pub fn track_large_coeff(byte_pos: usize) {
    if let Some(tracker) = TRACKER.lock().unwrap().as_mut() {
        tracker.record_large_coeff(byte_pos);
    }
}

/// Print tracker summary
#[cfg(feature = "std")]
pub fn print_tracker_summary() {
    if let Some(tracker) = TRACKER.lock().unwrap().as_ref() {
        tracker.print_summary();
    }
}

/// No-op stubs for no_std
#[cfg(not(feature = "std"))]
pub fn init_tracker() {}
/// No-op stub for no_std
#[cfg(not(feature = "std"))]
pub fn track_ctu_start(_ctu_idx: u32, _byte_pos: usize) {}
/// No-op stub for no_std
#[cfg(not(feature = "std"))]
pub fn track_large_coeff(_byte_pos: usize) {}
/// No-op stub for no_std
#[cfg(not(feature = "std"))]
pub fn print_tracker_summary() {}

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

    #[test]
    fn test_checksum() {
        let coeffs1 = [1i16, 2, 3, 4];
        let coeffs2 = [1i16, 2, 3, 4];
        let coeffs3 = [1i16, 3, 2, 4]; // Swapped order

        assert_eq!(coeff_checksum(&coeffs1, 2), coeff_checksum(&coeffs2, 2));
        assert_ne!(coeff_checksum(&coeffs1, 2), coeff_checksum(&coeffs3, 2));
    }
}