zencodec 0.1.14

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
//! Object-safe layered encode traits — zero-generics codec-agnostic dispatch.
//!
//! Mirrors the generic encode hierarchy with dyn-safe traits:
//!
//!   DynEncoderConfig → DynEncodeJob → DynEncoder / DynAnimationFrameEncoder
//!
//! Each layer is a separate trait with blanket impls via private shim structs.
//! Every method from the generic traits is exposed.
//!
//! ```rust,ignore
//! fn save(config: &dyn DynEncoderConfig, data: &[u8], w: u32, h: u32) -> Result<Vec<u8>, BoxedError> {
//!     let mut job = config.dyn_job();
//!     job.set_metadata(meta);
//!     job.set_limits(limits);
//!     let encoder = job.into_encoder()?;
//!     let output = encoder.encode_srgba8(data, true, w, h, w)?;
//!     Ok(output.into_vec())
//! }
//! ```

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

use crate::StopToken;
use crate::format::ImageFormat;
use crate::{EncodeCapabilities, EncodeOutput, Metadata, ResourceLimits};
use enough::Stop;
use zenpixels::{PixelDescriptor, PixelSlice, PixelSliceMut};

use super::BoxedError;
use super::encoder::{AnimationFrameEncoder, Encoder};
use super::encoding::{EncodeJob, EncoderConfig};

// ===========================================================================
// DynEncoder
// ===========================================================================

/// Object-safe single-image encoder.
///
/// Wraps [`Encoder`] for dyn dispatch. Produced by
/// [`DynEncodeJob::into_encoder`].
///
/// Encoders may borrow job-scoped data (stop tokens, metadata) so they
/// are not guaranteed `'static`. Attach codec-specific output data via
/// [`EncodeOutput::with_extras`](crate::EncodeOutput::with_extras) instead
/// of downcasting.
pub trait DynEncoder: Send {
    /// Suggested strip height for optimal row-level encoding.
    fn preferred_strip_height(&self) -> u32;

    /// Encode a complete image from type-erased pixels (consumes self).
    fn encode(self: Box<Self>, pixels: PixelSlice<'_>) -> Result<EncodeOutput, BoxedError>;

    /// Encode from sRGB RGBA8 raw bytes (consumes self).
    ///
    /// The buffer is mutable — the encoder may modify it in-place for
    /// format adaptation. See [`Encoder::encode_srgba8`] for details.
    fn encode_srgba8(
        self: Box<Self>,
        data: &mut [u8],
        make_opaque: bool,
        width: u32,
        height: u32,
        stride_pixels: u32,
    ) -> Result<EncodeOutput, BoxedError>;

    /// Push scanline rows incrementally.
    fn push_rows(&mut self, rows: PixelSlice<'_>) -> Result<(), BoxedError>;

    /// Finalize after push_rows. Returns encoded output.
    fn finish(self: Box<Self>) -> Result<EncodeOutput, BoxedError>;

    /// Encode by pulling rows from a source callback.
    fn encode_from(
        self: Box<Self>,
        source: &mut dyn FnMut(u32, PixelSliceMut<'_>) -> usize,
    ) -> Result<EncodeOutput, BoxedError>;
}

impl core::fmt::Debug for dyn DynEncoder + '_ {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("DynEncoder").finish_non_exhaustive()
    }
}

pub(super) struct EncoderShim<E>(pub(super) E);

impl<E: Encoder + Send> DynEncoder for EncoderShim<E> {
    fn preferred_strip_height(&self) -> u32 {
        self.0.preferred_strip_height()
    }

    fn encode(self: Box<Self>, pixels: PixelSlice<'_>) -> Result<EncodeOutput, BoxedError> {
        self.0.encode(pixels).map_err(|e| Box::new(e) as BoxedError)
    }

    fn encode_srgba8(
        self: Box<Self>,
        data: &mut [u8],
        make_opaque: bool,
        width: u32,
        height: u32,
        stride_pixels: u32,
    ) -> Result<EncodeOutput, BoxedError> {
        self.0
            .encode_srgba8(data, make_opaque, width, height, stride_pixels)
            .map_err(|e| Box::new(e) as BoxedError)
    }

    fn push_rows(&mut self, rows: PixelSlice<'_>) -> Result<(), BoxedError> {
        self.0
            .push_rows(rows)
            .map_err(|e| Box::new(e) as BoxedError)
    }

    fn finish(self: Box<Self>) -> Result<EncodeOutput, BoxedError> {
        self.0.finish().map_err(|e| Box::new(e) as BoxedError)
    }

    fn encode_from(
        self: Box<Self>,
        source: &mut dyn FnMut(u32, PixelSliceMut<'_>) -> usize,
    ) -> Result<EncodeOutput, BoxedError> {
        self.0
            .encode_from(source)
            .map_err(|e| Box::new(e) as BoxedError)
    }
}

// ===========================================================================
// DynAnimationFrameEncoder
// ===========================================================================

/// Object-safe full-frame animation encoder.
///
/// Wraps [`AnimationFrameEncoder`] for dyn dispatch. Produced by
/// [`DynEncodeJob::into_animation_frame_encoder`].
///
/// # Downcasting
///
/// Use [`as_any()`](DynAnimationFrameEncoder::as_any) to downcast back to the
/// concrete codec type for format-specific animation controls.
pub trait DynAnimationFrameEncoder: Send {
    /// Downcast to the concrete frame encoder type.
    fn as_any(&self) -> &dyn Any;

    /// Downcast to the concrete frame encoder type (mutable).
    fn as_any_mut(&mut self) -> &mut dyn Any;

    /// Consume and downcast to the concrete frame encoder type.
    fn into_any(self: Box<Self>) -> Box<dyn Any>;

    /// Push a complete full-canvas frame.
    fn push_frame(
        &mut self,
        pixels: PixelSlice<'_>,
        duration_ms: u32,
        stop: Option<&dyn Stop>,
    ) -> Result<(), BoxedError>;

    /// Finalize animation. Returns encoded output.
    fn finish(self: Box<Self>, stop: Option<&dyn Stop>) -> Result<EncodeOutput, BoxedError>;
}

impl core::fmt::Debug for dyn DynAnimationFrameEncoder + '_ {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("DynAnimationFrameEncoder")
            .finish_non_exhaustive()
    }
}

pub(super) struct AnimationFrameEncoderShim<F>(pub(super) F);

impl<F: AnimationFrameEncoder + Send + 'static> DynAnimationFrameEncoder
    for AnimationFrameEncoderShim<F>
{
    fn as_any(&self) -> &dyn Any {
        &self.0
    }

    fn as_any_mut(&mut self) -> &mut dyn Any {
        &mut self.0
    }

    fn into_any(self: Box<Self>) -> Box<dyn Any> {
        Box::new(self.0)
    }

    fn push_frame(
        &mut self,
        pixels: PixelSlice<'_>,
        duration_ms: u32,
        stop: Option<&dyn Stop>,
    ) -> Result<(), BoxedError> {
        self.0
            .push_frame(pixels, duration_ms, stop)
            .map_err(|e| Box::new(e) as BoxedError)
    }

    fn finish(self: Box<Self>, stop: Option<&dyn Stop>) -> Result<EncodeOutput, BoxedError> {
        self.0.finish(stop).map_err(|e| Box::new(e) as BoxedError)
    }
}

// ===========================================================================
// DynEncodeJob
// ===========================================================================

/// Object-safe encode job.
///
/// Wraps [`EncodeJob`] for dyn dispatch. Produced by
/// [`DynEncoderConfig::dyn_job`]. Use the `set_*` methods to configure,
/// then call [`into_encoder`](DynEncodeJob::into_encoder) or
/// [`into_animation_frame_encoder`](DynEncodeJob::into_animation_frame_encoder).
pub trait DynEncodeJob {
    /// Set cooperative cancellation token.
    fn set_stop(&mut self, stop: StopToken);

    /// Override resource limits.
    fn set_limits(&mut self, limits: ResourceLimits);

    /// Set encode security policy.
    fn set_policy(&mut self, policy: crate::EncodePolicy);

    /// Set metadata (ICC, EXIF, XMP) to embed.
    fn set_metadata(&mut self, meta: Metadata);

    /// Set animation canvas dimensions.
    fn set_canvas_size(&mut self, width: u32, height: u32);

    /// Set animation loop count.
    fn set_loop_count(&mut self, count: Option<u32>);

    /// Access codec-specific extensions for this job.
    ///
    /// Returns a reference to a `'static` extension type stored inside the
    /// concrete job. Downcast to the codec's extension type to access
    /// codec-specific configuration or alternate encode paths.
    fn extensions(&self) -> Option<&dyn Any>;

    /// Mutable access to codec-specific extensions.
    fn extensions_mut(&mut self) -> Option<&mut dyn Any>;

    /// Create the single-image encoder (consumes this job).
    fn into_encoder(self: Box<Self>) -> Result<Box<dyn DynEncoder>, BoxedError>;

    /// Create the full-frame animation encoder (consumes this job).
    ///
    /// The returned encoder is `'static` — it owns its configuration.
    fn into_animation_frame_encoder(
        self: Box<Self>,
    ) -> Result<Box<dyn DynAnimationFrameEncoder>, BoxedError>;
}

struct EncodeJobShim<J>(Option<J>);

impl<J> EncodeJobShim<J> {
    fn take(&mut self) -> Result<J, BoxedError> {
        self.0
            .take()
            .ok_or_else(|| "EncodeJobShim: job already consumed (double take)".into())
    }

    fn put(&mut self, job: J) {
        self.0 = Some(job);
    }
}

impl<J> DynEncodeJob for EncodeJobShim<J>
where
    J: EncodeJob,
    J::Enc: Encoder + Send,
    J::AnimationFrameEnc: AnimationFrameEncoder,
{
    fn set_stop(&mut self, stop: StopToken) {
        if let Ok(job) = self.take() {
            self.put(job.with_stop(stop));
        }
    }

    fn set_limits(&mut self, limits: ResourceLimits) {
        if let Ok(job) = self.take() {
            self.put(job.with_limits(limits));
        }
    }

    fn set_policy(&mut self, policy: crate::EncodePolicy) {
        if let Ok(job) = self.take() {
            self.put(job.with_policy(policy));
        }
    }

    fn set_metadata(&mut self, meta: Metadata) {
        if let Ok(job) = self.take() {
            self.put(job.with_metadata(meta));
        }
    }

    fn set_canvas_size(&mut self, width: u32, height: u32) {
        if let Ok(job) = self.take() {
            self.put(job.with_canvas_size(width, height));
        }
    }

    fn set_loop_count(&mut self, count: Option<u32>) {
        if let Ok(job) = self.take() {
            self.put(job.with_loop_count(count));
        }
    }

    fn extensions(&self) -> Option<&dyn Any> {
        self.0.as_ref().and_then(|j| j.extensions())
    }

    fn extensions_mut(&mut self) -> Option<&mut dyn Any> {
        self.0.as_mut().and_then(|j| j.extensions_mut())
    }

    fn into_encoder(mut self: Box<Self>) -> Result<Box<dyn DynEncoder>, BoxedError> {
        let job = self.take()?;
        let enc = job.encoder().map_err(|e| Box::new(e) as BoxedError)?;
        Ok(Box::new(EncoderShim(enc)))
    }

    fn into_animation_frame_encoder(
        mut self: Box<Self>,
    ) -> Result<Box<dyn DynAnimationFrameEncoder>, BoxedError> {
        let job = self.take()?;
        let enc = job
            .animation_frame_encoder()
            .map_err(|e| Box::new(e) as BoxedError)?;
        Ok(Box::new(AnimationFrameEncoderShim(enc)))
    }
}

// ===========================================================================
// DynEncoderConfig
// ===========================================================================

/// Object-safe encoder configuration.
///
/// Blanket-implemented for all [`EncoderConfig`] types whose encoder
/// implements [`Encoder`] and full-frame encoder implements [`AnimationFrameEncoder`].
/// Codecs without animation support should set `type AnimationFrameEnc = ()`.
///
/// ```rust,ignore
/// fn save(config: &dyn DynEncoderConfig, pixels: &[u8], w: u32, h: u32) -> Result<Vec<u8>, BoxedError> {
///     let encoder = config.dyn_job().into_encoder()?;
///     encoder.encode_srgba8(pixels, true, w, h, w)
///         .map(|o| o.into_vec())
/// }
///
/// let jpeg = JpegEncoderConfig::new().with_generic_quality(85.0);
/// let webp = WebpEncoderConfig::lossy();
/// save(&jpeg, &pixels, 100, 100)?;
/// save(&webp, &pixels, 100, 100)?;
/// ```
pub trait DynEncoderConfig: Send + Sync {
    /// Downcast to the concrete config type.
    ///
    /// ```rust,ignore
    /// let config: &dyn DynEncoderConfig = &JpegConfig::new();
    /// let jpeg = config.as_any().downcast_ref::<JpegConfig>().unwrap();
    /// ```
    fn as_any(&self) -> &dyn Any;

    /// The image format this encoder produces.
    fn format(&self) -> ImageFormat;

    /// Pixel formats this encoder accepts natively.
    fn supported_descriptors(&self) -> &'static [PixelDescriptor];

    /// Encoder capabilities (metadata support, cancellation, etc.).
    fn capabilities(&self) -> &'static EncodeCapabilities;

    /// Create a dyn-dispatched encode job.
    ///
    /// The job owns its config (cloned). The `'static` bound means
    /// the job can outlive the config reference — the only remaining
    /// lifetime dependency is the stop token (set via `set_stop`).
    fn dyn_job(&self) -> Box<dyn DynEncodeJob + 'static>;
}

impl<C> DynEncoderConfig for C
where
    C: EncoderConfig + 'static,
    <C::Job as EncodeJob>::Enc: Encoder + Send,
    <C::Job as EncodeJob>::AnimationFrameEnc: AnimationFrameEncoder,
{
    fn as_any(&self) -> &dyn Any {
        self
    }

    fn format(&self) -> ImageFormat {
        C::format()
    }

    fn supported_descriptors(&self) -> &'static [PixelDescriptor] {
        C::supported_descriptors()
    }

    fn capabilities(&self) -> &'static EncodeCapabilities {
        C::capabilities()
    }

    fn dyn_job(&self) -> Box<dyn DynEncodeJob + 'static> {
        Box::new(EncodeJobShim(Some(self.clone().job())))
    }
}