zencodec 0.1.17

Shared traits and types for zen* image codecs
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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
//! Encode and decode output types.

use alloc::boxed::Box;
use alloc::vec::Vec;
use core::any::Any;

use crate::detect::SourceEncodingDetails;
use crate::extensions::Extensions;
use crate::{ImageFormat, ImageInfo, Metadata};
use zenpixels::{PixelBuffer, PixelDescriptor, PixelSlice};

/// Output from an encode operation.
///
/// Carries the encoded bytes, the format enum, and the actual MIME type and
/// file extension of the output. The MIME type and extension default to
/// [`ImageFormat::mime_type()`] / [`ImageFormat::extension()`] but can be
/// overridden with [`with_mime_type()`](EncodeOutput::with_mime_type) /
/// [`with_extension()`](EncodeOutput::with_extension) for cases where the
/// output differs from the base format (e.g. `image/apng` vs `image/png`).
#[non_exhaustive]
pub struct EncodeOutput {
    data: Vec<u8>,
    format: ImageFormat,
    mime_type: &'static str,
    extension: &'static str,
    extensions: Extensions,
}

#[cfg(target_pointer_width = "64")]
const _: () = assert!(core::mem::size_of::<EncodeOutput>() == 96);

impl EncodeOutput {
    /// Create a new encode output.
    ///
    /// MIME type and extension default to the format's primary values.
    /// Use [`with_mime_type()`](EncodeOutput::with_mime_type) /
    /// [`with_extension()`](EncodeOutput::with_extension) to override
    /// (e.g. for animated PNG → `"image/apng"` / `"apng"`).
    pub fn new(data: Vec<u8>, format: ImageFormat) -> Self {
        Self {
            data,
            mime_type: format.mime_type(),
            extension: format.extension(),
            format,
            extensions: Extensions::new(),
        }
    }

    /// Override the MIME type for the encoded output.
    ///
    /// Use when the actual output differs from the base format's default,
    /// e.g. `"image/apng"` for animated PNG.
    pub fn with_mime_type(mut self, mime_type: &'static str) -> Self {
        self.mime_type = mime_type;
        self
    }

    /// Override the file extension for the encoded output.
    ///
    /// Use when the actual output differs from the base format's default,
    /// e.g. `"apng"` for animated PNG.
    pub fn with_extension(mut self, extension: &'static str) -> Self {
        self.extension = extension;
        self
    }

    /// Consume and return the encoded bytes.
    pub fn into_vec(self) -> Vec<u8> {
        self.data
    }

    /// Borrow the encoded bytes.
    pub fn data(&self) -> &[u8] {
        &self.data
    }

    /// Encoded byte count.
    pub fn len(&self) -> usize {
        self.data.len()
    }

    /// Whether the output is empty.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }

    /// The format that was used for encoding.
    pub fn format(&self) -> ImageFormat {
        self.format
    }

    /// MIME type of the encoded output (e.g. `"image/png"` or `"image/apng"`).
    ///
    /// Defaults to [`ImageFormat::mime_type()`] unless overridden by the
    /// encoder via [`with_mime_type()`](EncodeOutput::with_mime_type).
    pub fn mime_type(&self) -> &'static str {
        self.mime_type
    }

    /// Suggested file extension for the encoded output (e.g. `"png"` or `"apng"`).
    ///
    /// Defaults to [`ImageFormat::extension()`] unless overridden by the
    /// encoder via [`with_extension()`](EncodeOutput::with_extension).
    pub fn extension(&self) -> &'static str {
        self.extension
    }

    /// Attach a typed extension value (e.g., encoding statistics, codec-specific metadata).
    ///
    /// Multiple independently-typed values can be stored. Inserting a value of a type
    /// that already exists replaces the previous value.
    pub fn with_extras<T: Any + Send + Sync + 'static>(mut self, extras: T) -> Self {
        self.extensions.insert(extras);
        self
    }

    /// Borrow a typed extension value if present.
    pub fn extras<T: Any + Send + Sync + 'static>(&self) -> Option<&T> {
        self.extensions.get()
    }

    /// Remove and return a typed extension value.
    ///
    /// Returns `Some(T)` only when this is the sole `Arc` reference to the value.
    /// Returns `None` if the type is not present or other references exist (e.g. after clone).
    pub fn take_extras<T: Any + Send + Sync + 'static>(&mut self) -> Option<T> {
        self.extensions.remove()
    }

    /// Access the full extension map.
    pub fn extensions(&self) -> &Extensions {
        &self.extensions
    }

    /// Mutable access to the full extension map.
    pub fn extensions_mut(&mut self) -> &mut Extensions {
        &mut self.extensions
    }
}

impl Clone for EncodeOutput {
    fn clone(&self) -> Self {
        Self {
            data: self.data.clone(),
            format: self.format,
            mime_type: self.mime_type,
            extension: self.extension,
            extensions: self.extensions.clone(),
        }
    }
}

impl core::fmt::Debug for EncodeOutput {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("EncodeOutput")
            .field("data_len", &self.data.len())
            .field("format", &self.format)
            .field("mime_type", &self.mime_type)
            .field("extension", &self.extension)
            .field("extensions", &self.extensions)
            .finish()
    }
}

impl PartialEq for EncodeOutput {
    fn eq(&self, other: &Self) -> bool {
        self.data == other.data
            && self.format == other.format
            && self.mime_type == other.mime_type
            && self.extension == other.extension
    }
}

impl Eq for EncodeOutput {}

impl AsRef<[u8]> for EncodeOutput {
    fn as_ref(&self) -> &[u8] {
        &self.data
    }
}

/// Output from a decode operation.
///
/// Stores pixel data as a [`PixelBuffer`] with embedded format descriptor.
/// The descriptor carries the correct transfer function, color primaries,
/// and signal range — no need to resolve from CICP separately.
#[non_exhaustive]
pub struct DecodeOutput {
    pixels: PixelBuffer,
    info: ImageInfo,
    source_encoding: Option<Box<dyn SourceEncodingDetails>>,
    extensions: Extensions,
}

#[cfg(target_pointer_width = "64")]
const _: () = assert!(core::mem::size_of::<DecodeOutput>() == 352);

impl DecodeOutput {
    /// Create a new decode output from a [`PixelBuffer`].
    ///
    /// The PixelBuffer's descriptor should already have the correct transfer
    /// function and color primaries set by the decoder.
    pub fn new(pixels: PixelBuffer, info: ImageInfo) -> Self {
        Self {
            pixels,
            info,
            source_encoding: None,
            extensions: Extensions::new(),
        }
    }

    /// Attach source encoding details (quality estimate, codec-specific probe data).
    ///
    /// The concrete type must implement [`SourceEncodingDetails`] — typically
    /// a codec's probe type (e.g. `WebPProbe`, `JpegProbe`).
    ///
    /// Callers access the generic quality via
    /// [`source_encoding_details()`](DecodeOutput::source_encoding_details)
    /// and downcast for codec-specific fields.
    pub fn with_source_encoding_details<T: SourceEncodingDetails + 'static>(
        mut self,
        details: T,
    ) -> Self {
        self.source_encoding = Some(Box::new(details));
        self
    }

    /// Source encoding details, if available.
    ///
    /// Returns the codec's probe result with both generic quality
    /// (via [`SourceEncodingDetails::source_generic_quality()`]) and
    /// codec-specific fields (via `codec_details::<T>()`).
    pub fn source_encoding_details(&self) -> Option<&dyn SourceEncodingDetails> {
        self.source_encoding.as_deref()
    }

    /// Take source encoding details, consuming them from this output.
    pub fn take_source_encoding_details(&mut self) -> Option<Box<dyn SourceEncodingDetails>> {
        self.source_encoding.take()
    }

    /// Attach a typed extension value (e.g., JPEG gain maps, MPF data).
    ///
    /// Multiple independently-typed values can be stored. Inserting a value of a type
    /// that already exists replaces the previous value.
    pub fn with_extras<T: Any + Send + Sync + 'static>(mut self, extras: T) -> Self {
        self.extensions.insert(extras);
        self
    }

    /// Borrow a typed extension value if present.
    pub fn extras<T: Any + Send + Sync + 'static>(&self) -> Option<&T> {
        self.extensions.get()
    }

    /// Remove and return a typed extension value.
    ///
    /// Returns `Some(T)` only when this is the sole `Arc` reference to the value.
    /// Returns `None` if the type is not present or other references exist.
    pub fn take_extras<T: Any + Send + Sync + 'static>(&mut self) -> Option<T> {
        self.extensions.remove()
    }

    /// Access the full extension map.
    pub fn extensions(&self) -> &Extensions {
        &self.extensions
    }

    /// Mutable access to the full extension map.
    pub fn extensions_mut(&mut self) -> &mut Extensions {
        &mut self.extensions
    }

    /// Borrow the pixel data as a [`PixelSlice`].
    pub fn pixels(&self) -> PixelSlice<'_> {
        self.pixels.as_slice()
    }

    /// Take the pixel buffer, consuming this output.
    pub fn into_buffer(self) -> PixelBuffer {
        self.pixels
    }

    /// Image info.
    pub fn info(&self) -> &ImageInfo {
        &self.info
    }

    /// Image width.
    pub fn width(&self) -> u32 {
        self.pixels.width()
    }

    /// Image height.
    pub fn height(&self) -> u32 {
        self.pixels.height()
    }

    /// Whether the image has an alpha channel.
    pub fn has_alpha(&self) -> bool {
        self.pixels.has_alpha()
    }

    /// Pixel format descriptor.
    pub fn descriptor(&self) -> PixelDescriptor {
        self.pixels.descriptor()
    }

    /// Detected format.
    pub fn format(&self) -> ImageFormat {
        self.info.format
    }

    /// Get embedded metadata for roundtrip encode.
    pub fn metadata(&self) -> Metadata {
        self.info.metadata()
    }
}

impl core::fmt::Debug for DecodeOutput {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("DecodeOutput")
            .field("pixels", &self.pixels)
            .field("format", &self.info.format)
            .field("has_source_encoding", &self.source_encoding.is_some())
            .finish()
    }
}

/// A composited full-canvas animation frame, borrowing the decoder's canvas.
///
/// Returned by [`AnimationFrameDecoder::render_next_frame()`](crate::decode::AnimationFrameDecoder::render_next_frame).
/// The pixel data borrows the decoder's internal canvas buffer — calling
/// `render_next_frame()` again invalidates this borrow.
///
/// Use [`to_owned_frame()`](AnimationFrame::to_owned_frame) to copy the pixel data
/// if you need to retain the frame across calls.
#[non_exhaustive]
pub struct AnimationFrame<'a> {
    pixels: PixelSlice<'a>,
    duration_ms: u32,
    frame_index: u32,
}

impl<'a> AnimationFrame<'a> {
    /// Create a full frame borrowing pixel data.
    pub fn new(pixels: PixelSlice<'a>, duration_ms: u32, frame_index: u32) -> Self {
        Self {
            pixels,
            duration_ms,
            frame_index,
        }
    }

    /// Borrow the composited pixel data.
    pub fn pixels(&self) -> &PixelSlice<'a> {
        &self.pixels
    }

    /// Frame duration in milliseconds.
    ///
    /// Zero means platform-dependent minimum display time for most formats.
    /// For JXL, zero-duration frames are compositing helpers and are never
    /// yielded by [`AnimationFrameDecoder`](crate::decode::AnimationFrameDecoder).
    pub fn duration_ms(&self) -> u32 {
        self.duration_ms
    }

    /// Displayed frame index (0-based).
    ///
    /// Counts only frames yielded by the decoder — internal compositing
    /// frames (e.g. JXL zero-duration) are not counted.
    pub fn frame_index(&self) -> u32 {
        self.frame_index
    }

    /// Copy pixel data to produce an owned frame.
    pub fn to_owned_frame(&self) -> OwnedAnimationFrame {
        let ps = &self.pixels;
        let w = ps.width();
        let h = ps.rows();
        let desc = ps.descriptor();
        let bpp = desc.bytes_per_pixel();
        let row_bytes = w as usize * bpp;

        // Copy rows into a tightly-packed buffer
        let mut data = alloc::vec::Vec::with_capacity(h as usize * row_bytes);
        for y in 0..h {
            data.extend_from_slice(ps.row(y));
        }

        let pixels = PixelBuffer::from_vec(data, w, h, desc)
            .expect("to_owned_frame: buffer sized correctly");

        OwnedAnimationFrame {
            pixels,
            duration_ms: self.duration_ms,
            frame_index: self.frame_index,
            extensions: Extensions::new(),
        }
    }
}

impl core::fmt::Debug for AnimationFrame<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("AnimationFrame")
            .field("pixels", &self.pixels)
            .field("duration_ms", &self.duration_ms)
            .field("frame_index", &self.frame_index)
            .finish()
    }
}

/// A composited full-canvas animation frame with owned pixel data.
///
/// Produced by [`AnimationFrame::to_owned_frame()`] or
/// [`AnimationFrameDecoder::render_next_frame_owned()`](crate::decode::AnimationFrameDecoder::render_next_frame_owned).
#[non_exhaustive]
pub struct OwnedAnimationFrame {
    pixels: PixelBuffer,
    duration_ms: u32,
    frame_index: u32,
    extensions: Extensions,
}

impl OwnedAnimationFrame {
    /// Create an owned frame from a [`PixelBuffer`].
    pub fn new(pixels: PixelBuffer, duration_ms: u32, frame_index: u32) -> Self {
        Self {
            pixels,
            duration_ms,
            frame_index,
            extensions: Extensions::new(),
        }
    }

    /// Borrow the pixel data as a [`PixelSlice`].
    pub fn pixels(&self) -> PixelSlice<'_> {
        self.pixels.as_slice()
    }

    /// Take the pixel buffer, consuming this frame.
    pub fn into_buffer(self) -> PixelBuffer {
        self.pixels
    }

    /// Frame duration in milliseconds.
    pub fn duration_ms(&self) -> u32 {
        self.duration_ms
    }

    /// Displayed frame index (0-based).
    pub fn frame_index(&self) -> u32 {
        self.frame_index
    }

    /// Borrow as a [`AnimationFrame`].
    pub fn as_animation_frame(&self) -> AnimationFrame<'_> {
        AnimationFrame::new(self.pixels.as_slice(), self.duration_ms, self.frame_index)
    }

    /// Attach a typed extension value (e.g., per-frame codec metadata).
    ///
    /// Multiple independently-typed values can be stored.
    pub fn with_extras<T: Any + Send + Sync + 'static>(mut self, extras: T) -> Self {
        self.extensions.insert(extras);
        self
    }

    /// Borrow a typed extension value if present.
    pub fn extras<T: Any + Send + Sync + 'static>(&self) -> Option<&T> {
        self.extensions.get()
    }

    /// Remove and return a typed extension value.
    ///
    /// Returns `Some(T)` only when this is the sole `Arc` reference to the value.
    /// Returns `None` if the type is not present or other references exist.
    pub fn take_extras<T: Any + Send + Sync + 'static>(&mut self) -> Option<T> {
        self.extensions.remove()
    }

    /// Access the full extension map.
    pub fn extensions(&self) -> &Extensions {
        &self.extensions
    }

    /// Mutable access to the full extension map.
    pub fn extensions_mut(&mut self) -> &mut Extensions {
        &mut self.extensions
    }
}

impl core::fmt::Debug for OwnedAnimationFrame {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("OwnedAnimationFrame")
            .field("pixels", &self.pixels)
            .field("duration_ms", &self.duration_ms)
            .field("frame_index", &self.frame_index)
            .field("extensions", &self.extensions)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;
    use zenpixels::PixelDescriptor;

    fn make_rgb8_buffer(w: u32, h: u32) -> PixelBuffer {
        PixelBuffer::new(w, h, PixelDescriptor::RGB8_SRGB)
    }

    fn make_rgba8_buffer(w: u32, h: u32) -> PixelBuffer {
        PixelBuffer::new(w, h, PixelDescriptor::RGBA8_SRGB)
    }

    fn make_gray8_buffer(w: u32, h: u32) -> PixelBuffer {
        PixelBuffer::new(w, h, PixelDescriptor::GRAY8_SRGB)
    }

    #[test]
    fn encode_output() {
        let output = EncodeOutput::new(vec![1, 2, 3], ImageFormat::Jpeg);
        assert_eq!(output.format(), ImageFormat::Jpeg);
        assert_eq!(output.mime_type(), "image/jpeg");
        assert_eq!(output.extension(), "jpg");
        assert_eq!(output.len(), 3);
        assert_eq!(output.data(), &[1, 2, 3]);
        assert!(!output.is_empty());
        assert_eq!(output.into_vec(), vec![1, 2, 3]);
    }

    #[test]
    fn encode_output_mime_extension_override() {
        let output = EncodeOutput::new(vec![], ImageFormat::Png)
            .with_mime_type("image/apng")
            .with_extension("apng");
        assert_eq!(output.format(), ImageFormat::Png);
        assert_eq!(output.mime_type(), "image/apng");
        assert_eq!(output.extension(), "apng");
    }

    #[test]
    fn encode_output_eq() {
        let a = EncodeOutput::new(vec![1, 2, 3], ImageFormat::Jpeg);
        let b = EncodeOutput::new(vec![1, 2, 3], ImageFormat::Jpeg);
        assert_eq!(a, b);

        let c = EncodeOutput::new(vec![1, 2, 3], ImageFormat::Png);
        assert_ne!(a, c);
    }

    #[test]
    fn decode_output() {
        let buf = make_rgb8_buffer(2, 2);
        let info = ImageInfo::new(2, 2, ImageFormat::Png);
        let output = DecodeOutput::new(buf, info);
        assert_eq!(output.width(), 2);
        assert_eq!(output.height(), 2);
        assert!(!output.has_alpha());
        assert_eq!(output.format(), ImageFormat::Png);
    }

    #[test]
    fn decode_output_extras() {
        let buf = make_rgb8_buffer(2, 2);
        let info = ImageInfo::new(2, 2, ImageFormat::Jpeg);
        let mut output = DecodeOutput::new(buf, info).with_extras(42u32);
        assert_eq!(output.extras::<u32>(), Some(&42u32));
        assert_eq!(output.extras::<u64>(), None);
        let taken = output.take_extras::<u32>();
        assert_eq!(taken, Some(42u32));
        assert!(output.extras::<u32>().is_none());
    }

    #[test]
    fn animation_frame_borrowed() {
        let buf = make_rgba8_buffer(4, 4);
        let ps = buf.as_slice();
        let frame = AnimationFrame::new(ps, 100, 0);
        assert_eq!(frame.duration_ms(), 100);
        assert_eq!(frame.frame_index(), 0);
        assert_eq!(frame.pixels().width(), 4);
        assert_eq!(frame.pixels().rows(), 4);
    }

    #[test]
    fn animation_frame_to_owned() {
        let buf = make_rgb8_buffer(2, 2);
        let ps = buf.as_slice();
        let frame = AnimationFrame::new(ps, 50, 3);
        let owned = frame.to_owned_frame();
        assert_eq!(owned.duration_ms(), 50);
        assert_eq!(owned.frame_index(), 3);
        assert_eq!(owned.pixels().width(), 2);
        assert_eq!(owned.pixels().rows(), 2);
    }

    #[test]
    fn owned_animation_frame_as_animation_frame() {
        let buf = make_rgb8_buffer(2, 2);
        let owned = OwnedAnimationFrame::new(buf, 100, 5);
        let borrowed = owned.as_animation_frame();
        assert_eq!(borrowed.duration_ms(), 100);
        assert_eq!(borrowed.frame_index(), 5);
    }

    #[test]
    fn owned_animation_frame_into_buffer() {
        let buf = make_rgb8_buffer(3, 3);
        let owned = OwnedAnimationFrame::new(buf, 200, 0);
        let recovered = owned.into_buffer();
        assert_eq!(recovered.width(), 3);
        assert_eq!(recovered.height(), 3);
    }

    #[test]
    fn animation_frame_debug() {
        let buf = make_gray8_buffer(2, 2);
        let ps = buf.as_slice();
        let frame = AnimationFrame::new(ps, 100, 3);
        let s = alloc::format!("{:?}", frame);
        assert!(s.contains("AnimationFrame"));
        assert!(s.contains("duration_ms: 100"));
        assert!(s.contains("frame_index: 3"));
    }

    #[test]
    fn owned_animation_frame_debug() {
        let buf = make_rgb8_buffer(2, 2);
        let owned = OwnedAnimationFrame::new(buf, 50, 1);
        let s = alloc::format!("{:?}", owned);
        assert!(s.contains("OwnedAnimationFrame"));
        assert!(s.contains("duration_ms: 50"));
        assert!(s.contains("frame_index: 1"));
    }
}