Skip to main content

jxl_encoder/vardct/
debug_log.rs

1// Copyright (c) Imazen LLC and the JPEG XL Project Authors.
2// Algorithms and constants derived from libjxl (BSD-3-Clause).
3// Licensed under AGPL-3.0-or-later. Commercial licenses at https://www.imazen.io/pricing
4
5//! Debug logging to file for the VarDCT encoder.
6//!
7//! When the `debug-tokens` feature is enabled, debug output goes to a file
8//! instead of stderr, making it easy to grep without clobbering context.
9//!
10//! Usage:
11//! ```ignore
12//! debug_log!("DC token: ctx={}, value={}", ctx, value);
13//! ```
14//!
15//! Output goes to `<temp_dir>/jxl_enc_debug.log` (overwritten each run).
16
17#[cfg(feature = "debug-tokens")]
18use std::io::Write;
19#[cfg(feature = "debug-tokens")]
20use std::sync::Mutex;
21
22#[cfg(feature = "debug-tokens")]
23static DEBUG_LOG: Mutex<Option<std::fs::File>> = Mutex::new(None);
24
25/// Initialize the debug log file. Called automatically on first use.
26#[cfg(feature = "debug-tokens")]
27pub fn init_debug_log() {
28    let mut guard = DEBUG_LOG.lock().unwrap();
29    if guard.is_none() {
30        let file = std::fs::File::create(std::env::temp_dir().join("jxl_enc_debug.log"))
31            .expect("Failed to create debug log file");
32        *guard = Some(file);
33    }
34}
35
36/// Write a line to the debug log file.
37#[cfg(feature = "debug-tokens")]
38pub fn write_debug_log(msg: &str) {
39    init_debug_log();
40    let mut guard = DEBUG_LOG.lock().unwrap();
41    if let Some(ref mut file) = *guard {
42        let _ = writeln!(file, "{}", msg);
43    }
44}
45
46/// Flush the debug log file.
47#[cfg(feature = "debug-tokens")]
48#[allow(dead_code)]
49pub fn flush_debug_log() {
50    let mut guard = DEBUG_LOG.lock().unwrap();
51    if let Some(ref mut file) = *guard {
52        let _ = file.flush();
53    }
54}
55
56/// Debug log macro - writes to `<temp_dir>/jxl_enc_debug.log` when debug-tokens feature is enabled.
57///
58/// Usage: `debug_log!("message: {}", value);`
59#[macro_export]
60macro_rules! debug_log {
61    ($($arg:tt)*) => {
62        #[cfg(feature = "debug-tokens")]
63        {
64            $crate::vardct::debug_log::write_debug_log(&format!($($arg)*));
65        }
66    };
67}
68
69/// Debug log macro that also flushes (use sparingly, for important checkpoints).
70#[macro_export]
71macro_rules! debug_log_flush {
72    ($($arg:tt)*) => {
73        #[cfg(feature = "debug-tokens")]
74        {
75            $crate::vardct::debug_log::write_debug_log(&format!($($arg)*));
76            $crate::vardct::debug_log::flush_debug_log();
77        }
78    };
79}