leptonica 0.4.0

Rust port of Leptonica image processing library
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
//! GIF image format support
//!
//! Supports reading and writing single-frame GIF images.
//! Animated GIFs (multiple frames) are not supported.

use crate::color::{OctreeOptions, octree_quant};
use crate::core::{ImageFormat, Pix, PixColormap, PixelDepth};
use crate::io::{IoError, IoResult, header::ImageHeader};
use gif::{ColorOutput, DecodeOptions, Encoder, Frame, Repeat};
use std::io::{Read, Write};

/// Read GIF header metadata without decoding pixel data
pub fn read_header_gif(data: &[u8]) -> IoResult<ImageHeader> {
    let mut options = DecodeOptions::new();
    options.set_color_output(ColorOutput::Indexed);

    let decoder = options
        .read_info(data)
        .map_err(|e| IoError::DecodeError(format!("GIF decode error: {}", e)))?;

    let width = decoder.width() as u32;
    let height = decoder.height() as u32;
    let num_colors = decoder.global_palette().map_or(0, |p| (p.len() / 3) as u32);

    Ok(ImageHeader {
        width,
        height,
        depth: 8,
        bps: 8,
        spp: 1,
        has_colormap: true,
        num_colors,
        format: ImageFormat::Gif,
        x_resolution: None,
        y_resolution: None,
    })
}

/// Read a GIF image
///
/// Reads the first frame of a GIF image. Animated GIFs (multiple frames)
/// will return an error.
pub fn read_gif<R: Read>(reader: R) -> IoResult<Pix> {
    let mut options = DecodeOptions::new();
    options.set_color_output(ColorOutput::Indexed);

    let mut decoder = options
        .read_info(reader)
        .map_err(|e| IoError::DecodeError(format!("GIF decode error: {}", e)))?;

    // Read the first frame
    let frame = decoder
        .read_next_frame()
        .map_err(|e| IoError::DecodeError(format!("GIF frame error: {}", e)))?
        .ok_or_else(|| IoError::InvalidData("no frames in GIF".to_string()))?
        .clone();

    // Check for additional frames (animated GIF)
    if decoder
        .read_next_frame()
        .map_err(|e| IoError::DecodeError(format!("GIF frame error: {}", e)))?
        .is_some()
    {
        return Err(IoError::UnsupportedFormat(
            "animated GIF not supported".to_string(),
        ));
    }

    // Get palette - prefer local, fall back to global
    let palette: &[u8] = if let Some(ref local_palette) = frame.palette {
        local_palette
    } else if let Some(global_palette) = decoder.global_palette() {
        global_palette
    } else {
        return Err(IoError::InvalidData("GIF has no color map".to_string()));
    };

    // Validate palette size
    let ncolors = palette.len() / 3;
    if ncolors == 0 || ncolors > 256 {
        return Err(IoError::InvalidData(format!(
            "invalid palette size: {}",
            ncolors
        )));
    }

    // Determine depth based on color count (same as C version)
    let depth = if ncolors <= 2 {
        PixelDepth::Bit1
    } else if ncolors <= 4 {
        PixelDepth::Bit2
    } else if ncolors <= 16 {
        PixelDepth::Bit4
    } else {
        PixelDepth::Bit8
    };

    let width = frame.width as u32;
    let height = frame.height as u32;

    // Create pix with colormap
    let pix = Pix::new(width, height, depth)?;
    let mut pix_mut = pix.try_into_mut().unwrap();

    // Build colormap
    let mut cmap = PixColormap::new(depth.bits()).map_err(IoError::Core)?;
    for chunk in palette.chunks(3) {
        if chunk.len() == 3 {
            cmap.add_rgb(chunk[0], chunk[1], chunk[2])
                .map_err(IoError::Core)?;
        }
    }
    pix_mut.set_colormap(Some(cmap)).map_err(IoError::Core)?;

    // Copy pixel data
    let buffer = &frame.buffer;
    for y in 0..height {
        for x in 0..width {
            let idx = (y * width + x) as usize;
            if idx < buffer.len() {
                let val = buffer[idx] as u32;
                pix_mut.set_pixel_unchecked(x, y, val);
            }
        }
    }

    Ok(pix_mut.into())
}

/// Write a GIF image
///
/// Writes a pix as a single-frame GIF.
///
/// # Supported depths
/// - 1/2/4/8 bpp: Written with existing or generated colormap
/// - 16 bpp: Converted to 8bpp grayscale
/// - 32 bpp: Quantized to 8bpp using octree algorithm
pub fn write_gif<W: Write>(pix: &Pix, mut writer: W) -> IoResult<()> {
    // Convert to 8bpp with colormap if needed
    let (write_pix, cmap) = prepare_pix_for_gif(pix)?;

    let width = write_pix.width() as u16;
    let height = write_pix.height() as u16;

    // Build GIF palette (must be power of 2 size)
    let cmap_len = cmap.len();
    let gif_palette_size = cmap_len.next_power_of_two().max(2);

    let mut palette = Vec::with_capacity(gif_palette_size * 3);
    for i in 0..gif_palette_size {
        if i < cmap_len {
            if let Some((r, g, b)) = cmap.get_rgb(i) {
                palette.push(r);
                palette.push(g);
                palette.push(b);
            } else {
                palette.extend_from_slice(&[0, 0, 0]);
            }
        } else {
            palette.extend_from_slice(&[0, 0, 0]);
        }
    }

    // Create encoder
    let mut encoder = Encoder::new(&mut writer, width, height, &palette)
        .map_err(|e| IoError::EncodeError(format!("GIF encoder error: {}", e)))?;

    encoder
        .set_repeat(Repeat::Finite(0))
        .map_err(|e| IoError::EncodeError(format!("GIF repeat error: {}", e)))?;

    // Build frame buffer (always 8-bit indices)
    let mut buffer = Vec::with_capacity((width as usize) * (height as usize));

    for y in 0..(height as u32) {
        for x in 0..(width as u32) {
            let val = write_pix.get_pixel(x, y).unwrap_or(0);
            buffer.push(val as u8);
        }
    }

    // Create and write frame
    let mut frame = Frame::from_indexed_pixels(width, height, buffer, None);
    frame.palette = None; // Use global palette

    encoder
        .write_frame(&frame)
        .map_err(|e| IoError::EncodeError(format!("GIF frame write error: {}", e)))?;

    Ok(())
}

/// Prepare pix for GIF output
///
/// Converts the input pix to a format suitable for GIF encoding.
/// Returns the converted pix and its colormap.
fn prepare_pix_for_gif(pix: &Pix) -> IoResult<(Pix, PixColormap)> {
    match pix.depth() {
        PixelDepth::Bit1 | PixelDepth::Bit2 | PixelDepth::Bit4 | PixelDepth::Bit8 => {
            if let Some(cmap) = pix.colormap() {
                // Already has colormap, clone the pix
                let new_pix = clone_pix(pix)?;
                Ok((new_pix, cmap.clone()))
            } else {
                // Create grayscale colormap
                let (new_pix, cmap) = create_grayscale_colormapped_pix(pix)?;
                Ok((new_pix, cmap))
            }
        }
        PixelDepth::Bit16 => {
            // Convert 16bpp to 8bpp grayscale
            let (new_pix, cmap) = convert_16bpp_to_8bpp_grayscale(pix)?;
            Ok((new_pix, cmap))
        }
        PixelDepth::Bit32 => {
            // Quantize 32bpp to 8bpp with colormap using octree
            let quantized = octree_quant(pix, &OctreeOptions { max_colors: 256 })
                .map_err(|e| IoError::EncodeError(format!("quantization error: {}", e)))?;
            let cmap = quantized
                .colormap()
                .ok_or_else(|| IoError::EncodeError("quantized image has no colormap".to_string()))?
                .clone();
            Ok((quantized, cmap))
        }
    }
}

/// Clone a pix
fn clone_pix(pix: &Pix) -> IoResult<Pix> {
    let new_pix = Pix::new(pix.width(), pix.height(), pix.depth())?;
    let mut new_mut = new_pix.try_into_mut().unwrap();

    for y in 0..pix.height() {
        for x in 0..pix.width() {
            if let Some(val) = pix.get_pixel(x, y) {
                new_mut.set_pixel_unchecked(x, y, val);
            }
        }
    }

    if let Some(cmap) = pix.colormap() {
        new_mut
            .set_colormap(Some(cmap.clone()))
            .map_err(IoError::Core)?;
    }

    Ok(new_mut.into())
}

/// Create a grayscale-colormapped version of a pix without colormap
fn create_grayscale_colormapped_pix(pix: &Pix) -> IoResult<(Pix, PixColormap)> {
    let depth = pix.depth();
    let max_val = match depth {
        PixelDepth::Bit1 => 1,
        PixelDepth::Bit2 => 3,
        PixelDepth::Bit4 => 15,
        PixelDepth::Bit8 => 255,
        _ => return Err(IoError::UnsupportedFormat("unsupported depth".to_string())),
    };

    // Create grayscale colormap
    let mut cmap = PixColormap::new(depth.bits()).map_err(IoError::Core)?;

    // Add grayscale entries
    let num_entries = max_val + 1;
    for i in 0..num_entries {
        let gray = ((i * 255) / max_val) as u8;
        cmap.add_rgb(gray, gray, gray).map_err(IoError::Core)?;
    }

    // Clone pix with colormap
    let new_pix = Pix::new(pix.width(), pix.height(), depth)?;
    let mut new_mut = new_pix.try_into_mut().unwrap();

    for y in 0..pix.height() {
        for x in 0..pix.width() {
            if let Some(val) = pix.get_pixel(x, y) {
                new_mut.set_pixel_unchecked(x, y, val);
            }
        }
    }

    new_mut
        .set_colormap(Some(cmap.clone()))
        .map_err(IoError::Core)?;

    Ok((new_mut.into(), cmap))
}

/// Convert 16bpp grayscale to 8bpp with grayscale colormap
fn convert_16bpp_to_8bpp_grayscale(pix: &Pix) -> IoResult<(Pix, PixColormap)> {
    // Create 8bpp grayscale colormap
    let mut cmap = PixColormap::new(8).map_err(IoError::Core)?;
    for i in 0..=255u8 {
        cmap.add_rgb(i, i, i).map_err(IoError::Core)?;
    }

    // Create new 8bpp pix
    let new_pix = Pix::new(pix.width(), pix.height(), PixelDepth::Bit8)?;
    let mut new_mut = new_pix.try_into_mut().unwrap();

    for y in 0..pix.height() {
        for x in 0..pix.width() {
            if let Some(val16) = pix.get_pixel(x, y) {
                // Scale 16-bit to 8-bit
                let val8 = val16 >> 8;
                new_mut.set_pixel_unchecked(x, y, val8);
            }
        }
    }

    new_mut
        .set_colormap(Some(cmap.clone()))
        .map_err(IoError::Core)?;

    Ok((new_mut.into(), cmap))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::pixel;
    use std::io::Cursor;

    fn create_paletted_pix() -> Pix {
        let pix = Pix::new(10, 10, PixelDepth::Bit8).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        // Create a colormap with a few colors
        let mut cmap = PixColormap::new(8).unwrap();
        cmap.add_rgb(255, 0, 0).unwrap(); // 0: Red
        cmap.add_rgb(0, 255, 0).unwrap(); // 1: Green
        cmap.add_rgb(0, 0, 255).unwrap(); // 2: Blue
        cmap.add_rgb(255, 255, 0).unwrap(); // 3: Yellow
        pix_mut.set_colormap(Some(cmap)).unwrap();

        // Fill with pattern
        for y in 0..10 {
            for x in 0..10 {
                let val = (x + y) % 4;
                pix_mut.set_pixel(x, y, val).unwrap();
            }
        }

        pix_mut.into()
    }

    #[test]
    fn test_gif_roundtrip_paletted() {
        let pix = create_paletted_pix();

        let mut buffer = Vec::new();
        write_gif(&pix, &mut buffer).unwrap();

        let cursor = Cursor::new(buffer);
        let pix2 = read_gif(cursor).unwrap();

        assert_eq!(pix2.width(), 10);
        assert_eq!(pix2.height(), 10);
        assert!(pix2.has_colormap());

        // Check pixel values match
        for y in 0..10 {
            for x in 0..10 {
                assert_eq!(
                    pix2.get_pixel(x, y),
                    pix.get_pixel(x, y),
                    "mismatch at ({}, {})",
                    x,
                    y
                );
            }
        }
    }

    #[test]
    fn test_gif_roundtrip_1bpp() {
        let pix = Pix::new(16, 16, PixelDepth::Bit1).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        // Create 1bpp colormap
        let mut cmap = PixColormap::new(1).unwrap();
        cmap.add_rgb(255, 255, 255).unwrap(); // 0: White
        cmap.add_rgb(0, 0, 0).unwrap(); // 1: Black
        pix_mut.set_colormap(Some(cmap)).unwrap();

        // Checkerboard pattern
        for y in 0..16 {
            for x in 0..16 {
                let val = (x + y) % 2;
                pix_mut.set_pixel(x, y, val).unwrap();
            }
        }

        let pix: Pix = pix_mut.into();

        let mut buffer = Vec::new();
        write_gif(&pix, &mut buffer).unwrap();

        let cursor = Cursor::new(buffer);
        let pix2 = read_gif(cursor).unwrap();

        // Should be read as 1bpp (2 colors)
        assert_eq!(pix2.depth(), PixelDepth::Bit1);

        for y in 0..16 {
            for x in 0..16 {
                assert_eq!(pix2.get_pixel(x, y), pix.get_pixel(x, y));
            }
        }
    }

    #[test]
    fn test_gif_roundtrip_2bpp() {
        let pix = Pix::new(8, 8, PixelDepth::Bit2).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        let mut cmap = PixColormap::new(2).unwrap();
        cmap.add_rgb(0, 0, 0).unwrap();
        cmap.add_rgb(85, 85, 85).unwrap();
        cmap.add_rgb(170, 170, 170).unwrap();
        cmap.add_rgb(255, 255, 255).unwrap();
        pix_mut.set_colormap(Some(cmap)).unwrap();

        for y in 0..8 {
            for x in 0..8 {
                let val = (x + y) % 4;
                pix_mut.set_pixel(x, y, val).unwrap();
            }
        }

        let pix: Pix = pix_mut.into();

        let mut buffer = Vec::new();
        write_gif(&pix, &mut buffer).unwrap();

        let cursor = Cursor::new(buffer);
        let pix2 = read_gif(cursor).unwrap();

        assert_eq!(pix2.depth(), PixelDepth::Bit2);

        for y in 0..8 {
            for x in 0..8 {
                assert_eq!(pix2.get_pixel(x, y), pix.get_pixel(x, y));
            }
        }
    }

    #[test]
    fn test_gif_roundtrip_4bpp() {
        let pix = Pix::new(8, 8, PixelDepth::Bit4).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        let mut cmap = PixColormap::new(4).unwrap();
        for i in 0..16 {
            let gray = (i * 17) as u8;
            cmap.add_rgb(gray, gray, gray).unwrap();
        }
        pix_mut.set_colormap(Some(cmap)).unwrap();

        for y in 0..8 {
            for x in 0..8 {
                let val = (x + y) % 16;
                pix_mut.set_pixel(x, y, val).unwrap();
            }
        }

        let pix: Pix = pix_mut.into();

        let mut buffer = Vec::new();
        write_gif(&pix, &mut buffer).unwrap();

        let cursor = Cursor::new(buffer);
        let pix2 = read_gif(cursor).unwrap();

        assert_eq!(pix2.depth(), PixelDepth::Bit4);

        for y in 0..8 {
            for x in 0..8 {
                assert_eq!(pix2.get_pixel(x, y), pix.get_pixel(x, y));
            }
        }
    }

    #[test]
    fn test_gif_grayscale_without_colormap() {
        // Test 8bpp without colormap - should add grayscale colormap
        let pix = Pix::new(8, 8, PixelDepth::Bit8).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        for y in 0..8 {
            for x in 0..8 {
                let val = (x + y) * 16;
                pix_mut.set_pixel(x, y, val).unwrap();
            }
        }

        let pix: Pix = pix_mut.into();

        let mut buffer = Vec::new();
        write_gif(&pix, &mut buffer).unwrap();

        let cursor = Cursor::new(buffer);
        let pix2 = read_gif(cursor).unwrap();

        assert!(pix2.has_colormap());
    }

    #[test]
    fn test_gif_16bpp_conversion() {
        let pix = Pix::new(4, 4, PixelDepth::Bit16).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        for y in 0..4 {
            for x in 0..4 {
                let val = (x + y) * 16384; // 16-bit values
                pix_mut.set_pixel(x, y, val).unwrap();
            }
        }

        let pix: Pix = pix_mut.into();

        let mut buffer = Vec::new();
        write_gif(&pix, &mut buffer).unwrap();

        let cursor = Cursor::new(buffer);
        let pix2 = read_gif(cursor).unwrap();

        // Should be 8bpp after conversion
        assert_eq!(pix2.depth(), PixelDepth::Bit8);
        assert!(pix2.has_colormap());
    }

    #[test]
    fn test_gif_32bpp_quantization() {
        let pix = Pix::new(16, 16, PixelDepth::Bit32).unwrap();
        let mut pix_mut = pix.try_into_mut().unwrap();

        // Create a gradient image
        for y in 0..16 {
            for x in 0..16 {
                let r = (x * 16) as u8;
                let g = (y * 16) as u8;
                let b = 128u8;
                let pixel = pixel::compose_rgb(r, g, b);
                pix_mut.set_pixel_unchecked(x, y, pixel);
            }
        }

        let pix: Pix = pix_mut.into();

        let mut buffer = Vec::new();
        write_gif(&pix, &mut buffer).unwrap();

        let cursor = Cursor::new(buffer);
        let pix2 = read_gif(cursor).unwrap();

        // Should be 8bpp after quantization
        assert_eq!(pix2.depth(), PixelDepth::Bit8);
        assert!(pix2.has_colormap());
    }

    #[test]
    fn test_gif_colormap_preservation() {
        let pix = create_paletted_pix();
        let original_cmap = pix.colormap().unwrap();

        let mut buffer = Vec::new();
        write_gif(&pix, &mut buffer).unwrap();

        let cursor = Cursor::new(buffer);
        let pix2 = read_gif(cursor).unwrap();

        let read_cmap = pix2.colormap().unwrap();

        // Check first 4 colors match
        for i in 0..4 {
            let orig = original_cmap.get_rgb(i);
            let read = read_cmap.get_rgb(i);
            assert_eq!(orig, read, "colormap mismatch at index {}", i);
        }
    }
}