rawshift-image 0.1.1

Still-image decoding, RAW processing, and encoding for rawshift
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
//! Integration tests for standard format decoding from on-disk fixture files.
//!
//! These tests load real image files from `test_data/standard/<format>/` and verify
//! decoding produces correct dimensions and pixel data. Tests skip gracefully when
//! fixture files are not present.
//!
//! Generate fixtures with:
//!   cargo run --example generate_test_fixtures

use rawshift_image::formats::{
    StandardFormat, decode_standard_image, detect_standard_format, read_standard_image_metadata,
};
use serde::Deserialize;
use std::path::PathBuf;

/// Ground truth for a standard format fixture.
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct StandardGroundTruth {
    format: String,
    file_name: String,
    width: u32,
    height: u32,
    channels: u32,
    bit_depth_output: u32,
    #[serde(default)]
    metadata: Option<MetadataGroundTruth>,
}

/// Expected metadata values for formats that embed EXIF/ICC/XMP.
#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct MetadataGroundTruth {
    make: Option<String>,
    model: Option<String>,
    iso: Option<u32>,
    focal_length_num: Option<u32>,
    datetime_original: Option<String>,
    has_icc: Option<bool>,
    has_xmp: Option<bool>,
}

fn test_data_path(rel: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../..")
        .join("test_data")
        .join("standard")
        .join(rel)
}

fn test_fixture_path(rel: &str) -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("../..")
        .join("test_fixtures")
        .join("standard")
        .join(rel)
}

fn load_standard_ground_truth(format_dir: &str) -> Option<StandardGroundTruth> {
    let path = test_fixture_path(&format!("{}/expected.json", format_dir));
    let contents = std::fs::read_to_string(&path).ok()?;
    serde_json::from_str(&contents).ok()
}

/// Skip test if fixture file doesn't exist.
macro_rules! skip_if_missing {
    ($path:expr) => {
        if !$path.exists() {
            eprintln!(
                "Skipping test: fixture not found: {:?}\n  Run: cargo run --example generate_test_fixtures",
                $path
            );
            return;
        }
    };
}

// ============================================================================
// Format Detection from File
// ============================================================================

#[test]
fn detect_jpeg_from_file() {
    let gt = match load_standard_ground_truth("jpeg") {
        Some(gt) => gt,
        None => return,
    };
    let path = test_data_path(&format!("jpeg/{}", gt.file_name));
    skip_if_missing!(path);

    let data = std::fs::read(&path).unwrap();
    let fmt = detect_standard_format(&data);
    assert_eq!(fmt, Some(StandardFormat::Jpeg), "JPEG detection from file");
}

#[test]
fn detect_png_from_file() {
    let gt = match load_standard_ground_truth("png") {
        Some(gt) => gt,
        None => return,
    };
    let path = test_data_path(&format!("png/{}", gt.file_name));
    skip_if_missing!(path);

    let data = std::fs::read(&path).unwrap();
    let fmt = detect_standard_format(&data);
    assert_eq!(fmt, Some(StandardFormat::Png), "PNG detection from file");
}

#[test]
fn detect_gif_from_file() {
    let gt = match load_standard_ground_truth("gif") {
        Some(gt) => gt,
        None => return,
    };
    let path = test_data_path(&format!("gif/{}", gt.file_name));
    skip_if_missing!(path);

    let data = std::fs::read(&path).unwrap();
    let fmt = detect_standard_format(&data);
    assert_eq!(fmt, Some(StandardFormat::Gif), "GIF detection from file");
}

#[test]
fn detect_tiff_from_file() {
    let gt = match load_standard_ground_truth("tiff") {
        Some(gt) => gt,
        None => return,
    };
    let path = test_data_path(&format!("tiff/{}", gt.file_name));
    skip_if_missing!(path);

    let data = std::fs::read(&path).unwrap();
    let fmt = detect_standard_format(&data);
    assert_eq!(fmt, Some(StandardFormat::Tiff), "TIFF detection from file");
}

#[test]
fn detect_webp_from_file() {
    let gt = match load_standard_ground_truth("webp") {
        Some(gt) => gt,
        None => return,
    };
    let path = test_data_path(&format!("webp/{}", gt.file_name));
    skip_if_missing!(path);

    let data = std::fs::read(&path).unwrap();
    let fmt = detect_standard_format(&data);
    assert_eq!(fmt, Some(StandardFormat::WebP), "WebP detection from file");
}

#[test]
fn detect_svg_from_file() {
    let gt = match load_standard_ground_truth("svg") {
        Some(gt) => gt,
        None => return,
    };
    let path = test_data_path(&format!("svg/{}", gt.file_name));
    skip_if_missing!(path);

    let data = std::fs::read(&path).unwrap();
    let fmt = detect_standard_format(&data);
    assert_eq!(fmt, Some(StandardFormat::Svg), "SVG detection from file");
}

#[cfg(feature = "heic")]
#[test]
fn detect_heic_from_file() {
    let gt = match load_standard_ground_truth("heic") {
        Some(gt) => gt,
        None => return,
    };
    let path = test_data_path(&format!("heic/{}", gt.file_name));
    skip_if_missing!(path);

    let data = std::fs::read(&path).unwrap();
    let fmt = detect_standard_format(&data);
    assert_eq!(fmt, Some(StandardFormat::Heic), "HEIC detection from file");
}

// ============================================================================
// Decode Dimensions from File
// ============================================================================

fn assert_decode_dimensions(format_dir: &str, expected_format: StandardFormat) {
    let gt = match load_standard_ground_truth(format_dir) {
        Some(gt) => gt,
        None => return,
    };
    let path = test_data_path(&format!("{}/{}", format_dir, gt.file_name));
    skip_if_missing!(path);

    let data = std::fs::read(&path).unwrap();
    let img = decode_standard_image(&data, expected_format)
        .unwrap_or_else(|e| panic!("{} decode failed: {}", gt.format, e));

    assert_eq!(
        img.width(),
        gt.width,
        "{} width mismatch: expected {}, got {}",
        gt.format,
        gt.width,
        img.width()
    );
    assert_eq!(
        img.height(),
        gt.height,
        "{} height mismatch: expected {}, got {}",
        gt.format,
        gt.height,
        img.height()
    );
    assert_eq!(
        img.data.len(),
        (gt.width * gt.height * gt.channels) as usize,
        "{} pixel data length mismatch",
        gt.format
    );
}

#[test]
fn decode_jpeg_dimensions_from_file() {
    assert_decode_dimensions("jpeg", StandardFormat::Jpeg);
}

#[test]
fn decode_png_dimensions_from_file() {
    assert_decode_dimensions("png", StandardFormat::Png);
}

#[test]
fn decode_gif_dimensions_from_file() {
    assert_decode_dimensions("gif", StandardFormat::Gif);
}

#[test]
fn decode_tiff_dimensions_from_file() {
    assert_decode_dimensions("tiff", StandardFormat::Tiff);
}

#[test]
fn decode_webp_dimensions_from_file() {
    assert_decode_dimensions("webp", StandardFormat::WebP);
}

#[cfg(feature = "svg")]
#[test]
fn decode_svg_dimensions_from_file() {
    assert_decode_dimensions("svg", StandardFormat::Svg);
}

#[cfg(feature = "avif")]
#[test]
fn decode_avif_dimensions_from_file() {
    assert_decode_dimensions("avif", StandardFormat::Avif);
}

#[cfg(feature = "heic")]
#[test]
fn decode_heic_dimensions_from_file() {
    assert_decode_dimensions("heic", StandardFormat::Heic);
}

// ============================================================================
// Full Detect + Decode Pipeline from File
// ============================================================================

fn assert_detect_then_decode(format_dir: &str, expected_format: StandardFormat) {
    let gt = match load_standard_ground_truth(format_dir) {
        Some(gt) => gt,
        None => return,
    };
    let path = test_data_path(&format!("{}/{}", format_dir, gt.file_name));
    skip_if_missing!(path);

    let data = std::fs::read(&path).unwrap();

    let detected = detect_standard_format(&data);
    assert_eq!(
        detected,
        Some(expected_format),
        "{}: detection should match expected format",
        gt.format
    );

    let img = decode_standard_image(&data, detected.unwrap())
        .unwrap_or_else(|e| panic!("{} decode after detection failed: {}", gt.format, e));

    assert_eq!(img.width(), gt.width);
    assert_eq!(img.height(), gt.height);
}

#[test]
fn detect_then_decode_jpeg_from_file() {
    assert_detect_then_decode("jpeg", StandardFormat::Jpeg);
}

#[test]
fn detect_then_decode_png_from_file() {
    assert_detect_then_decode("png", StandardFormat::Png);
}

#[test]
fn detect_then_decode_gif_from_file() {
    assert_detect_then_decode("gif", StandardFormat::Gif);
}

#[test]
fn detect_then_decode_tiff_from_file() {
    assert_detect_then_decode("tiff", StandardFormat::Tiff);
}

#[test]
fn detect_then_decode_webp_from_file() {
    assert_detect_then_decode("webp", StandardFormat::WebP);
}

#[cfg(feature = "svg")]
#[test]
fn detect_then_decode_svg_from_file() {
    assert_detect_then_decode("svg", StandardFormat::Svg);
}

#[cfg(feature = "avif")]
#[test]
fn detect_then_decode_avif_from_file() {
    assert_detect_then_decode("avif", StandardFormat::Avif);
}

#[cfg(feature = "heic")]
#[test]
fn detect_then_decode_heic_from_file() {
    assert_detect_then_decode("heic", StandardFormat::Heic);
}

// ============================================================================
// Pixel Value Verification
// ============================================================================

#[test]
fn decode_png_pixel_values_from_file() {
    let gt = match load_standard_ground_truth("png") {
        Some(gt) => gt,
        None => return,
    };
    let path = test_data_path(&format!("png/{}", gt.file_name));
    skip_if_missing!(path);

    let data = std::fs::read(&path).unwrap();
    let img = decode_standard_image(&data, StandardFormat::Png).unwrap();

    // PNG is lossless, so first pixel (red: 255,0,0) should be exact after u8->u16 scaling.
    // u8 255 -> u16 65535 (255 * 257)
    assert_eq!(img.data[0], 65535, "PNG first pixel R should be 65535");
    assert_eq!(img.data[1], 0, "PNG first pixel G should be 0");
    assert_eq!(img.data[2], 0, "PNG first pixel B should be 0");
}

#[test]
fn decode_tiff_pixel_values_from_file() {
    let gt = match load_standard_ground_truth("tiff") {
        Some(gt) => gt,
        None => return,
    };
    let path = test_data_path(&format!("tiff/{}", gt.file_name));
    skip_if_missing!(path);

    let data = std::fs::read(&path).unwrap();
    let img = decode_standard_image(&data, StandardFormat::Tiff).unwrap();

    // TIFF is lossless, first pixel (red: 255,0,0) should be exact.
    assert_eq!(img.data[0], 65535, "TIFF first pixel R should be 65535");
    assert_eq!(img.data[1], 0, "TIFF first pixel G should be 0");
    assert_eq!(img.data[2], 0, "TIFF first pixel B should be 0");
}

#[test]
fn decode_gif_first_pixel_from_file() {
    let gt = match load_standard_ground_truth("gif") {
        Some(gt) => gt,
        None => return,
    };
    let path = test_data_path(&format!("gif/{}", gt.file_name));
    skip_if_missing!(path);

    let data = std::fs::read(&path).unwrap();
    let img = decode_standard_image(&data, StandardFormat::Gif).unwrap();

    // GIF palette index 0 = red (255, 0, 0) -> u16: (65535, 0, 0)
    assert_eq!(img.data[0], 65535, "GIF first pixel R should be 65535");
    assert_eq!(img.data[1], 0, "GIF first pixel G should be 0");
    assert_eq!(img.data[2], 0, "GIF first pixel B should be 0");
}

// ============================================================================
// Metadata Round-Trip Verification
// ============================================================================

fn assert_metadata_extraction(format_dir: &str, expected_format: StandardFormat) {
    let gt = match load_standard_ground_truth(format_dir) {
        Some(gt) => gt,
        None => return,
    };
    let meta_gt = match gt.metadata {
        Some(ref m) => m,
        None => {
            eprintln!(
                "Skipping metadata test for {}: no metadata in expected.json",
                gt.format
            );
            return;
        }
    };
    let path = test_data_path(&format!("{}/{}", format_dir, gt.file_name));
    skip_if_missing!(path);

    let data = std::fs::read(&path).unwrap();
    let md = read_standard_image_metadata(&data, expected_format);

    if let Some(ref make) = meta_gt.make {
        assert_eq!(
            &md.camera.make, make,
            "{} metadata: make mismatch",
            gt.format
        );
    }
    if let Some(ref model) = meta_gt.model {
        assert_eq!(
            &md.camera.model, model,
            "{} metadata: model mismatch",
            gt.format
        );
    }
    if let Some(expected_iso) = meta_gt.iso {
        assert_eq!(
            md.exif.iso,
            Some(expected_iso),
            "{} metadata: ISO mismatch",
            gt.format
        );
    }
    if let Some(expected_fl) = meta_gt.focal_length_num {
        let actual_fl = md.exif.focal_length.map(|r| r.numerator);
        assert_eq!(
            actual_fl,
            Some(expected_fl),
            "{} metadata: focal length mismatch",
            gt.format
        );
    }
    if let Some(ref expected_dt) = meta_gt.datetime_original {
        assert_eq!(
            md.datetime.datetime_original.as_deref(),
            Some(expected_dt.as_str()),
            "{} metadata: datetime_original mismatch",
            gt.format
        );
    }
}

#[test]
fn read_metadata_jpeg_from_file() {
    assert_metadata_extraction("jpeg", StandardFormat::Jpeg);
}

#[test]
fn read_metadata_png_from_file() {
    assert_metadata_extraction("png", StandardFormat::Png);
}

#[test]
fn read_metadata_webp_from_file() {
    assert_metadata_extraction("webp", StandardFormat::WebP);
}

#[cfg(feature = "avif")]
#[test]
fn read_metadata_avif_from_file() {
    assert_metadata_extraction("avif", StandardFormat::Avif);
}

#[cfg(feature = "heic")]
#[test]
fn read_metadata_heic_from_file() {
    assert_metadata_extraction("heic", StandardFormat::Heic);
}