jpegli-rs 0.12.0

Pure Rust JPEG encoder/decoder - port of Google's jpegli with perceptual optimizations
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
//! Comprehensive encoder configuration matrix test.
//!
//! Tests ALL combinations of jpegli encoder settings and verifies:
//! 1. Valid combinations produce decodable JPEGs with all major decoders
//! 2. Invalid combinations (e.g., progressive + fixed Huffman) error appropriately
//!
//! This is the "loop test" to run while developing to ensure nothing breaks.
//!
//! Run with:
//! ```
//! cargo test --test encoder_matrix -- --nocapture
//! ```

use jpegli::{
    decoder::Decoder,
    encoder::{ChromaSubsampling, EncoderConfig, PixelLayout, XybSubsampling},
};

/// Result of testing one encoder configuration
#[derive(Debug)]
struct MatrixResult {
    config: String,
    encode_result: EncodeOutcome,
    jpegli_decode: bool,
    zune_jpeg: bool,
    file_size: usize,
}

#[derive(Debug, Clone, PartialEq)]
enum EncodeOutcome {
    Success,
    ExpectedError(String),
    UnexpectedError(String),
}

/// Generate a test image
fn generate_test_image(width: usize, height: usize, channels: usize) -> Vec<u8> {
    let mut data = Vec::with_capacity(width * height * channels);
    for y in 0..height {
        for x in 0..width {
            data.push((x * 255 / width) as u8);
            if channels >= 3 {
                data.push((y * 255 / height) as u8);
                data.push(((x + y) * 127 / (width + height)) as u8);
            }
            if channels == 4 {
                data.push(255); // Alpha
            }
        }
    }
    data
}

fn encode_rgb(
    width: u32,
    height: u32,
    data: &[u8],
    config: &EncoderConfig,
) -> jpegli::encoder::Result<Vec<u8>> {
    let mut enc = config.encode_from_bytes(width, height, PixelLayout::Rgb8Srgb)?;
    enc.push_packed(data, enough::Unstoppable)?;
    enc.finish()
}

fn encode_gray(
    width: u32,
    height: u32,
    data: &[u8],
    config: &EncoderConfig,
) -> jpegli::encoder::Result<Vec<u8>> {
    let mut enc = config.encode_from_bytes(width, height, PixelLayout::Gray8Srgb)?;
    enc.push_packed(data, enough::Unstoppable)?;
    enc.finish()
}

/// Decode with jpegli-rs
fn decode_jpegli(data: &[u8]) -> bool {
    Decoder::new().decode(data).is_ok()
}

/// Decode with zune-jpeg
fn decode_zune_jpeg(data: &[u8]) -> bool {
    use zune_jpeg::zune_core::bytestream::ZCursor;
    use zune_jpeg::JpegDecoder;
    let cursor = ZCursor::new(data);
    let mut decoder = JpegDecoder::new(cursor);
    decoder.decode().is_ok()
}

/// Test a single encoder configuration
fn test_config(
    width: u32,
    height: u32,
    is_grayscale: bool,
    progressive: bool,
    subsampling: ChromaSubsampling,
    optimize_huffman: bool,
    use_xyb: bool,
    quality: f32,
) -> MatrixResult {
    let channels = if is_grayscale { 1 } else { 3 };
    let data = generate_test_image(width as usize, height as usize, channels);

    let pixel_format_name = if is_grayscale { "Gray" } else { "Rgb" };
    let mode_name = if progressive {
        "Progressive"
    } else {
        "Baseline"
    };
    let sub_name = match subsampling {
        ChromaSubsampling::None => "444",
        ChromaSubsampling::HalfHorizontal => "422",
        ChromaSubsampling::Quarter => "420",
        ChromaSubsampling::HalfVertical => "440",
        _ => "unknown",
    };

    let config_name = format!(
        "{}/{}/{}/huff={}/xyb={}/Q{}",
        pixel_format_name,
        mode_name,
        sub_name,
        if optimize_huffman { "opt" } else { "fix" },
        use_xyb,
        quality as u32
    );

    let config = if is_grayscale {
        EncoderConfig::grayscale(quality)
    } else if use_xyb {
        EncoderConfig::xyb(quality, XybSubsampling::BQuarter)
    } else {
        EncoderConfig::ycbcr(quality, subsampling)
    }
    .progressive(progressive)
    .optimize_huffman(optimize_huffman);

    let encode_result = if is_grayscale {
        encode_gray(width, height, &data, &config)
    } else {
        encode_rgb(width, height, &data, &config)
    };

    match encode_result {
        Ok(jpeg_data) => {
            let jpegli = decode_jpegli(&jpeg_data);
            let zune = decode_zune_jpeg(&jpeg_data);

            MatrixResult {
                config: config_name,
                encode_result: EncodeOutcome::Success,
                jpegli_decode: jpegli,
                zune_jpeg: zune,
                file_size: jpeg_data.len(),
            }
        }
        Err(e) => {
            let err_str = format!("{}", e);
            // Check if this is an expected error
            let is_expected = err_str.contains("Progressive mode with fixed Huffman");

            MatrixResult {
                config: config_name,
                encode_result: if is_expected {
                    EncodeOutcome::ExpectedError(err_str)
                } else {
                    EncodeOutcome::UnexpectedError(err_str)
                },
                jpegli_decode: false,
                zune_jpeg: false,
                file_size: 0,
            }
        }
    }
}

/// Main matrix test
#[test]
fn test_encoder_matrix() {
    let width = 128;
    let height = 128;
    let quality = 85.0;

    println!("\n{}", "=".repeat(90));
    println!("ENCODER CONFIGURATION MATRIX TEST");
    println!("{}\n", "=".repeat(90));

    let mut results: Vec<MatrixResult> = Vec::new();
    let mut pass_count = 0;
    let mut fail_count = 0;

    // Define test matrix
    let progressives = [false, true];
    let subsamplings = [
        ChromaSubsampling::None,
        ChromaSubsampling::HalfHorizontal,
        ChromaSubsampling::Quarter,
        ChromaSubsampling::HalfVertical,
    ];
    let huffman_opts = [false, true]; // false = fixed, true = optimized
    let xyb_opts = [false, true];

    // Test RGB combinations
    for &progressive in &progressives {
        for &subsampling in &subsamplings {
            for &optimize_huffman in &huffman_opts {
                // Skip progressive + fixed Huffman (invalid combination, not supported)
                if progressive && !optimize_huffman {
                    continue;
                }

                for &use_xyb in &xyb_opts {
                    // Skip XYB with subsampling (XYB should use 4:4:4)
                    if use_xyb && subsampling != ChromaSubsampling::None {
                        continue;
                    }

                    let result = test_config(
                        width,
                        height,
                        false, // not grayscale
                        progressive,
                        subsampling,
                        optimize_huffman,
                        use_xyb,
                        quality,
                    );
                    results.push(result);
                }
            }
        }
    }

    // Test Grayscale combinations (no subsampling, no XYB)
    for &progressive in &progressives {
        for &optimize_huffman in &huffman_opts {
            // Skip progressive + fixed Huffman (invalid combination, not supported)
            if progressive && !optimize_huffman {
                continue;
            }

            let result = test_config(
                width,
                height,
                true, // grayscale
                progressive,
                ChromaSubsampling::None, // Grayscale ignores subsampling
                optimize_huffman,
                false, // No XYB for grayscale
                quality,
            );
            results.push(result);
        }
    }

    // Print results table
    println!(
        "{:<55} {:>6} {:>8} {:>8} {:>8}",
        "Configuration", "Status", "jpegli", "zune", "Size"
    );
    println!("{}", "-".repeat(90));

    for result in &results {
        let status = match &result.encode_result {
            EncodeOutcome::Success => {
                if result.jpegli_decode && result.zune_jpeg {
                    pass_count += 1;
                    "OK"
                } else {
                    fail_count += 1;
                    "DECODE?"
                }
            }
            EncodeOutcome::ExpectedError(_) | EncodeOutcome::UnexpectedError(_) => {
                fail_count += 1;
                "ERR!"
            }
        };

        let decode_str = |ok: bool| if ok { "" } else { "" };
        let size_str = if result.file_size > 0 {
            format!("{}", result.file_size)
        } else {
            "-".to_string()
        };

        println!(
            "{:<55} {:>6} {:>8} {:>8} {:>8}",
            result.config,
            status,
            decode_str(result.jpegli_decode),
            decode_str(result.zune_jpeg),
            size_str
        );

        // Print error details for unexpected failures
        if let EncodeOutcome::UnexpectedError(ref e) = result.encode_result {
            println!("  └─ ERROR: {}", e);
        }
    }

    println!("{}", "-".repeat(90));
    println!("\nSummary: {} passed, {} failures", pass_count, fail_count);

    assert_eq!(fail_count, 0, "There were {} failures!", fail_count);
}

/// Quick smoke test for the most common configurations
#[test]
fn test_common_configurations() {
    let width = 64;
    let height = 64;
    let data = generate_test_image(width, height, 3);

    let configs: Vec<(&str, bool, ChromaSubsampling, bool, bool)> = vec![
        // (name, progressive, subsampling, optimize_huffman, use_xyb)
        (
            "baseline_444_fixed",
            false,
            ChromaSubsampling::None,
            false,
            false,
        ),
        (
            "baseline_444_opt",
            false,
            ChromaSubsampling::None,
            true,
            false,
        ),
        (
            "baseline_420_opt",
            false,
            ChromaSubsampling::Quarter,
            true,
            false,
        ),
        (
            "progressive_444_opt",
            true,
            ChromaSubsampling::None,
            true,
            false,
        ),
        (
            "progressive_420_opt",
            true,
            ChromaSubsampling::Quarter,
            true,
            false,
        ),
        (
            "xyb_baseline_opt",
            false,
            ChromaSubsampling::None,
            true,
            true,
        ),
        (
            "xyb_progressive_opt",
            true,
            ChromaSubsampling::None,
            true,
            true,
        ),
    ];

    println!("\n=== Common Configuration Smoke Test ===\n");

    for (name, progressive, subsampling, optimize_huffman, use_xyb) in configs {
        let config = if use_xyb {
            EncoderConfig::xyb(85.0, XybSubsampling::BQuarter)
        } else {
            EncoderConfig::ycbcr(85.0, subsampling)
        }
        .progressive(progressive)
        .optimize_huffman(optimize_huffman);

        let result = encode_rgb(width as u32, height as u32, &data, &config);

        match result {
            Ok(jpeg) => {
                let jpegli_ok = decode_jpegli(&jpeg);
                let zune_ok = decode_zune_jpeg(&jpeg);

                let all_ok = jpegli_ok && zune_ok;
                println!(
                    "{:<25}: {} bytes, decoders: {}",
                    name,
                    jpeg.len(),
                    if all_ok { "ALL OK" } else { "SOME FAILED" }
                );

                assert!(all_ok, "{} failed decoder compatibility", name);
            }
            Err(e) => {
                panic!("{} encoding failed: {}", name, e);
            }
        }
    }
}

/// Test that progressive + fixed Huffman produces expected error
#[test]
fn test_progressive_fixed_huffman_errors() {
    let data = vec![128u8; 64 * 64 * 3];

    let config = EncoderConfig::ycbcr(85.0, ChromaSubsampling::Quarter)
        .progressive(true)
        .optimize_huffman(false); // Fixed Huffman

    let result = encode_rgb(64, 64, &data, &config);

    match result {
        Err(e) => {
            let err_str = format!("{}", e);
            assert!(
                err_str.contains("progressive mode requires optimized Huffman"),
                "Expected error about Progressive + fixed Huffman, got: {}",
                err_str
            );
            println!(
                "✓ Progressive + Fixed Huffman correctly errors: {}",
                err_str
            );
        }
        Ok(_) => {
            panic!("Expected error for Progressive + Fixed Huffman, but encoding succeeded!");
        }
    }
}