Skip to main content

skia_rs_codec/
generator.rs

1//! Image generator trait for deferred image generation.
2//!
3//! `ImageGenerator` provides a base class for generating image data on-demand.
4//! This is useful for:
5//! - Lazy decoding of encoded image data
6//! - Procedural image generation
7//! - GPU texture generation
8//!
9//! Corresponds to Skia's `SkImageGenerator`.
10
11use crate::ImageInfo;
12use skia_rs_core::{AlphaType, ColorType};
13use std::sync::Arc;
14
15/// Result type for generator operations.
16pub type GeneratorResult<T> = Result<T, GeneratorError>;
17
18/// Error type for generator operations.
19#[derive(Debug, Clone, thiserror::Error)]
20pub enum GeneratorError {
21    /// Failed to generate pixels.
22    #[error("Failed to generate pixels: {0}")]
23    GenerateFailed(String),
24    /// Invalid image info.
25    #[error("Invalid image info: {0}")]
26    InvalidInfo(String),
27    /// Unsupported color type.
28    #[error("Unsupported color type: {0:?}")]
29    UnsupportedColorType(ColorType),
30    /// Unsupported alpha type.
31    #[error("Unsupported alpha type: {0:?}")]
32    UnsupportedAlphaType(AlphaType),
33    /// Decode error.
34    #[error("Decode error: {0}")]
35    DecodeError(String),
36    /// I/O error.
37    #[error("I/O error: {0}")]
38    IoError(String),
39}
40
41/// A generator for image data.
42///
43/// `ImageGenerator` provides a way to generate image pixels on demand.
44/// This enables lazy image loading and procedural image generation.
45///
46/// # Implementing `ImageGenerator`
47///
48/// To implement a custom generator:
49/// 1. Implement `info()` to return the image dimensions and format
50/// 2. Implement `on_get_pixels()` to generate the actual pixel data
51/// 3. Optionally override other methods for optimization
52///
53/// # Example
54///
55/// ```ignore
56/// use skia_rs_codec::{ImageGenerator, ImageInfo, GeneratorResult};
57/// use skia_rs_core::{ColorType, AlphaType};
58///
59/// struct SolidColorGenerator {
60///     info: ImageInfo,
61///     color: [u8; 4],
62/// }
63///
64/// impl ImageGenerator for SolidColorGenerator {
65///     fn info(&self) -> &ImageInfo {
66///         &self.info
67///     }
68///
69///     fn on_get_pixels(&self, pixels: &mut [u8], row_bytes: usize) -> GeneratorResult<()> {
70///         for y in 0..self.info.height as usize {
71///             for x in 0..self.info.width as usize {
72///                 let offset = y * row_bytes + x * 4;
73///                 pixels[offset..offset + 4].copy_from_slice(&self.color);
74///             }
75///         }
76///         Ok(())
77///     }
78/// }
79/// ```
80///
81/// Allocate the next process-wide unique generator ID from a monotonic
82/// atomic counter. Never returns 0, and never reuses a value, so IDs cannot
83/// collide the way recycled pointer addresses can.
84pub fn next_generator_id() -> u32 {
85    static ID_COUNTER: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(1);
86    ID_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
87}
88
89/// Corresponds to Skia's `SkImageGenerator`.
90pub trait ImageGenerator: Send + Sync {
91    /// Get the image info describing the output.
92    fn info(&self) -> &ImageInfo;
93
94    /// Get the width of the generated image.
95    #[inline]
96    fn width(&self) -> i32 {
97        self.info().width
98    }
99
100    /// Get the height of the generated image.
101    #[inline]
102    fn height(&self) -> i32 {
103        self.info().height
104    }
105
106    /// Get the unique ID for this generator.
107    ///
108    /// Two generators with the same ID will produce identical images. IDs
109    /// are drawn from a process-wide monotonic counter (see
110    /// [`next_generator_id`]), never from a pointer address — a freed
111    /// generator's address can be reused, which would alias two logically
112    /// distinct generators. Implementors that must return a *stable* ID
113    /// across calls should store one at construction; this default hands out
114    /// a fresh ID per call, so override it when stability matters.
115    fn unique_id(&self) -> u32 {
116        next_generator_id()
117    }
118
119    /// Get a reference to the original encoded data, if available.
120    ///
121    /// Returns `None` if the generator doesn't have encoded data
122    /// (e.g., procedural generators).
123    fn ref_encoded_data(&self) -> Option<Arc<[u8]>> {
124        None
125    }
126
127    /// Check if generating to the requested info is supported.
128    ///
129    /// Returns `true` if `get_pixels()` can generate pixels
130    /// for the given target info.
131    fn query_supports_info(&self, info: &ImageInfo) -> bool {
132        // Default: only exact match is supported
133        info.width == self.info().width
134            && info.height == self.info().height
135            && info.color_type == self.info().color_type
136            && info.alpha_type == self.info().alpha_type
137    }
138
139    /// Generate pixels into the provided buffer.
140    ///
141    /// # Arguments
142    /// * `info` - The target image info (may differ from generator's native info)
143    /// * `pixels` - Buffer to write pixels into
144    /// * `row_bytes` - Number of bytes per row in the destination buffer
145    ///
146    /// # Returns
147    /// `Ok(())` on success, `Err` on failure.
148    ///
149    /// # Errors
150    /// Returns [`GeneratorError::GenerateFailed`] if `pixels` is too small
151    /// for `info`, or if the requested `info` is not directly generatable
152    /// and not reachable via [`ImageGenerator::query_supports_info`]'s
153    /// conversion path.
154    fn get_pixels(
155        &self,
156        info: &ImageInfo,
157        pixels: &mut [u8],
158        row_bytes: usize,
159    ) -> GeneratorResult<()> {
160        // Validate buffer size
161        let required_size = info.compute_byte_size(row_bytes);
162        if pixels.len() < required_size {
163            return Err(GeneratorError::GenerateFailed(format!(
164                "Buffer too small: {} < {}",
165                pixels.len(),
166                required_size
167            )));
168        }
169
170        // Check if conversion is needed
171        if info.width == self.info().width
172            && info.height == self.info().height
173            && info.color_type == self.info().color_type
174            && info.alpha_type == self.info().alpha_type
175        {
176            // Direct generation
177            self.on_get_pixels(pixels, row_bytes)
178        } else if self.query_supports_info(info) {
179            // Generator supports conversion
180            self.on_get_pixels_with_conversion(info, pixels, row_bytes)
181        } else {
182            Err(GeneratorError::GenerateFailed(
183                "Requested format not supported".into(),
184            ))
185        }
186    }
187
188    /// Generate pixels into the provided buffer (implementation).
189    ///
190    /// This method should be implemented by concrete generators.
191    /// The default implementation fails.
192    ///
193    /// # Errors
194    /// Returns [`GeneratorError`] if pixel generation fails.
195    fn on_get_pixels(&self, pixels: &mut [u8], row_bytes: usize) -> GeneratorResult<()>;
196
197    /// Generate pixels with format conversion.
198    ///
199    /// Default implementation generates native format then converts.
200    ///
201    /// # Errors
202    /// Returns [`GeneratorError`] if native generation or the subsequent
203    /// format conversion fails.
204    fn on_get_pixels_with_conversion(
205        &self,
206        info: &ImageInfo,
207        pixels: &mut [u8],
208        row_bytes: usize,
209    ) -> GeneratorResult<()> {
210        // Generate in native format first
211        let native_info = self.info();
212        let native_row_bytes = native_info.min_row_bytes();
213        let native_size = native_info.compute_byte_size(native_row_bytes);
214        let mut native_pixels = vec![0u8; native_size];
215
216        self.on_get_pixels(&mut native_pixels, native_row_bytes)?;
217
218        // Convert to target format
219        convert_pixels(
220            native_info,
221            &native_pixels,
222            native_row_bytes,
223            info,
224            pixels,
225            row_bytes,
226        )
227    }
228
229    /// Check if the generator is valid and can produce pixels.
230    fn is_valid(&self) -> bool {
231        !self.info().is_empty()
232    }
233}
234
235/// A boxed image generator.
236pub type BoxedImageGenerator = Box<dyn ImageGenerator>;
237
238/// A shared image generator.
239pub type SharedImageGenerator = Arc<dyn ImageGenerator>;
240
241/// Convert pixels between formats.
242///
243/// Delegates to [`skia_rs_core::convert_pixels`], which handles both
244/// color-type translation (RGBA<->BGRA, Gray8<->RGBA, Alpha8<->RGBA,
245/// RGB888<->RGBA, RGB565<->RGBA) and alpha-type translation
246/// (Premul<->Unpremul) in a single row-by-row pass.
247///
248/// # Errors
249/// Returns [`GeneratorError::GenerateFailed`] on a dimension mismatch or
250/// invalid `ImageInfo`, and [`GeneratorError::UnsupportedColorType`] if
251/// the underlying conversion doesn't support the requested color types.
252pub fn convert_pixels(
253    src_info: &ImageInfo,
254    src_pixels: &[u8],
255    src_row_bytes: usize,
256    dst_info: &ImageInfo,
257    dst_pixels: &mut [u8],
258    dst_row_bytes: usize,
259) -> GeneratorResult<()> {
260    // Validate dimensions up front for a clean error message.
261    if src_info.width != dst_info.width || src_info.height != dst_info.height {
262        return Err(GeneratorError::GenerateFailed("Dimension mismatch".into()));
263    }
264
265    let src_core = skia_rs_core::ImageInfo::new(
266        src_info.width,
267        src_info.height,
268        src_info.color_type,
269        src_info.alpha_type,
270    )
271    .map_err(|e| GeneratorError::InvalidInfo(e.to_string()))?;
272    let dst_core = skia_rs_core::ImageInfo::new(
273        dst_info.width,
274        dst_info.height,
275        dst_info.color_type,
276        dst_info.alpha_type,
277    )
278    .map_err(|e| GeneratorError::InvalidInfo(e.to_string()))?;
279
280    skia_rs_core::convert_pixels(
281        src_pixels,
282        &src_core,
283        src_row_bytes,
284        dst_pixels,
285        &dst_core,
286        dst_row_bytes,
287    )
288    .map_err(|e| match e {
289        skia_rs_core::PixelError::UnsupportedColorType => {
290            GeneratorError::UnsupportedColorType(dst_info.color_type)
291        }
292        other => GeneratorError::GenerateFailed(other.to_string()),
293    })
294}
295
296/// A simple solid color generator.
297pub struct SolidColorGenerator {
298    info: ImageInfo,
299    color: [u8; 4],
300    unique_id: u32,
301}
302
303impl SolidColorGenerator {
304    /// Create a new solid color generator.
305    #[must_use]
306    pub fn new(width: i32, height: i32, color: [u8; 4]) -> Self {
307        Self {
308            info: ImageInfo::new(width, height, ColorType::Rgba8888, AlphaType::Premul),
309            color,
310            unique_id: next_generator_id(),
311        }
312    }
313}
314
315impl ImageGenerator for SolidColorGenerator {
316    fn info(&self) -> &ImageInfo {
317        &self.info
318    }
319
320    fn unique_id(&self) -> u32 {
321        self.unique_id
322    }
323
324    fn on_get_pixels(&self, pixels: &mut [u8], row_bytes: usize) -> GeneratorResult<()> {
325        let height = usize::try_from(self.info.height).unwrap_or(0);
326        let width = usize::try_from(self.info.width).unwrap_or(0);
327        for y in 0..height {
328            for x in 0..width {
329                let offset = y * row_bytes + x * 4;
330                pixels[offset..offset + 4].copy_from_slice(&self.color);
331            }
332        }
333        Ok(())
334    }
335}
336
337/// A generator that wraps encoded image data with eager decoding.
338///
339/// The encoded payload is decoded exactly once, at construction time. This
340/// trades a small startup cost for:
341/// - **Correctness**: `info()` returns the decoder's actual color/alpha
342///   type rather than a hard-coded `Rgba8888/Premul` placeholder, so
343///   callers that compare `generator.info()` against a target buffer see
344///   the real format.
345/// - **Performance**: `on_get_pixels` serves from the cached decoded image
346///   instead of re-running the decode on every call.
347///
348/// For deferred decoding at a higher level (the original motivation for
349/// this type), wrap it in a [`LazyImage`](crate::LazyImage) — that API
350/// handles the "don't decode until actually needed" semantics and keeps
351/// the generator's role focused on producing pixels once asked.
352pub struct EncodedImageGenerator {
353    info: ImageInfo,
354    encoded_data: Arc<[u8]>,
355    unique_id: u32,
356    /// Decoded image, computed once in the constructor.
357    decoded: crate::Image,
358}
359
360impl EncodedImageGenerator {
361    /// Create a generator from encoded data.
362    ///
363    /// Returns `None` if the data cannot be decoded.
364    #[must_use]
365    pub fn new(data: Vec<u8>) -> Option<Self> {
366        Self::from_shared(data.into())
367    }
368
369    /// Create a generator from shared encoded data.
370    ///
371    /// Decodes the payload up front to determine its native format.
372    #[must_use]
373    pub fn from_shared(data: Arc<[u8]>) -> Option<Self> {
374        let decoded = crate::decode_image(&data).ok()?;
375
376        Some(Self {
377            info: decoded.info().clone(),
378            encoded_data: data,
379            unique_id: next_generator_id(),
380            decoded,
381        })
382    }
383
384    /// Get a reference to the cached decoded image.
385    #[must_use]
386    pub const fn decoded_image(&self) -> &crate::Image {
387        &self.decoded
388    }
389}
390
391impl ImageGenerator for EncodedImageGenerator {
392    fn info(&self) -> &ImageInfo {
393        &self.info
394    }
395
396    fn unique_id(&self) -> u32 {
397        self.unique_id
398    }
399
400    fn ref_encoded_data(&self) -> Option<Arc<[u8]>> {
401        Some(self.encoded_data.clone())
402    }
403
404    fn on_get_pixels(&self, pixels: &mut [u8], row_bytes: usize) -> GeneratorResult<()> {
405        let info = self.decoded.info();
406        let src_row_bytes = self.decoded.row_bytes();
407        let bytes_per_pixel = info.bytes_per_pixel();
408        let width = usize::try_from(info.width).unwrap_or(0);
409        let height = usize::try_from(info.height).unwrap_or(0);
410
411        let Some(src_pixels) = self.decoded.peek_pixels() else {
412            return Err(GeneratorError::GenerateFailed(
413                "Failed to access decoded pixels".into(),
414            ));
415        };
416        for y in 0..height {
417            let src_offset = y * src_row_bytes;
418            let dst_offset = y * row_bytes;
419            let copy_len = width * bytes_per_pixel;
420            pixels[dst_offset..dst_offset + copy_len]
421                .copy_from_slice(&src_pixels[src_offset..src_offset + copy_len]);
422        }
423        Ok(())
424    }
425
426    fn on_get_pixels_with_conversion(
427        &self,
428        info: &ImageInfo,
429        pixels: &mut [u8],
430        row_bytes: usize,
431    ) -> GeneratorResult<()> {
432        // Convert directly from the cached decoded pixels to the caller's
433        // target. Overrides the default trait impl, which would allocate a
434        // staging buffer and decode into native first.
435        let src_info = self.decoded.info();
436        let src_row_bytes = self.decoded.row_bytes();
437        let src_pixels = self.decoded.peek_pixels().ok_or_else(|| {
438            GeneratorError::GenerateFailed("Failed to access decoded pixels".into())
439        })?;
440
441        convert_pixels(src_info, src_pixels, src_row_bytes, info, pixels, row_bytes)
442    }
443
444    fn query_supports_info(&self, info: &ImageInfo) -> bool {
445        // Native format is always supported.
446        if info.width == self.info.width
447            && info.height == self.info.height
448            && info.color_type == self.info.color_type
449            && info.alpha_type == self.info.alpha_type
450        {
451            return true;
452        }
453        // Otherwise, we support any format convert_pixels can reach. The
454        // function gate-keeps itself by returning UnsupportedColorType, so
455        // probe with a 0x0 info to avoid allocating a buffer here.
456        if info.width != self.info.width || info.height != self.info.height {
457            return false;
458        }
459        // Try the conversion on a tiny probe buffer; the function rejects
460        // on dimension mismatch before touching pixels, so we have to pass
461        // the real dimensions. Check against a whitelist of supported
462        // (src, dst) pairs instead.
463        matches!(
464            (self.info.color_type, info.color_type),
465            (
466                ColorType::Rgba8888 | ColorType::Bgra8888 | ColorType::Gray8 | ColorType::Alpha8,
467                ColorType::Rgba8888
468            ) | (
469                ColorType::Rgba8888 | ColorType::Bgra8888,
470                ColorType::Bgra8888
471            ) | (ColorType::Rgba8888, ColorType::Gray8)
472        )
473    }
474}
475
476#[cfg(test)]
477mod tests {
478    use super::*;
479    #[cfg(feature = "png")]
480    use crate::codec::ImageEncoder;
481
482    #[test]
483    fn test_solid_color_generator() {
484        let generator = SolidColorGenerator::new(10, 10, [255, 0, 0, 255]);
485        assert_eq!(generator.width(), 10);
486        assert_eq!(generator.height(), 10);
487
488        let mut pixels = vec![0u8; 10 * 10 * 4];
489        generator
490            .get_pixels(generator.info(), &mut pixels, 10 * 4)
491            .unwrap();
492
493        // Check first pixel is red
494        assert_eq!(pixels[0], 255); // R
495        assert_eq!(pixels[1], 0); // G
496        assert_eq!(pixels[2], 0); // B
497        assert_eq!(pixels[3], 255); // A
498    }
499
500    #[test]
501    fn test_convert_rgba_to_bgra() {
502        let src_info = ImageInfo::new(2, 2, ColorType::Rgba8888, AlphaType::Premul);
503        let dst_info = ImageInfo::new(2, 2, ColorType::Bgra8888, AlphaType::Premul);
504
505        let src_pixels = [
506            255, 0, 0, 255, // Red
507            0, 255, 0, 255, // Green
508            0, 0, 255, 255, // Blue
509            255, 255, 255, 255, // White
510        ];
511        let mut dst_pixels = vec![0u8; 16];
512
513        convert_pixels(&src_info, &src_pixels, 8, &dst_info, &mut dst_pixels, 8).unwrap();
514
515        // Check that R and B are swapped
516        assert_eq!(dst_pixels[0..4], [0, 0, 255, 255]); // Blue channel first (was Red)
517        assert_eq!(dst_pixels[4..8], [0, 255, 0, 255]); // Green unchanged
518    }
519
520    #[test]
521    fn test_generator_unique_id() {
522        let generator1 = SolidColorGenerator::new(10, 10, [0, 0, 0, 255]);
523        let generator2 = SolidColorGenerator::new(10, 10, [0, 0, 0, 255]);
524
525        // Different generators should have different IDs
526        assert_ne!(generator1.unique_id(), generator2.unique_id());
527    }
528
529    #[test]
530    fn test_convert_pixels_premul_to_unpremul() {
531        // (25, 50, 75, 128) premul -> (50, 100, 150, 128) unpremul
532        let src_info = ImageInfo::new(1, 1, ColorType::Rgba8888, AlphaType::Premul);
533        let dst_info = ImageInfo::new(1, 1, ColorType::Rgba8888, AlphaType::Unpremul);
534        let src = [25, 50, 75, 128];
535        let mut dst = [0u8; 4];
536        convert_pixels(&src_info, &src, 4, &dst_info, &mut dst, 4).unwrap();
537        // Allow off-by-one from integer rounding.
538        assert!((i32::from(dst[0]) - 50).abs() <= 1);
539        assert!((i32::from(dst[1]) - 100).abs() <= 1);
540        assert!((i32::from(dst[2]) - 150).abs() <= 1);
541        assert_eq!(dst[3], 128);
542    }
543
544    #[cfg(feature = "png")]
545    #[test]
546    fn test_encoded_generator_reports_decoded_info() {
547        // Encode a tiny PNG and verify the generator's info reflects the
548        // decoder's actual output (not the hard-coded Rgba8888/Premul
549        // placeholder that caused C-4).
550        let info = ImageInfo::new(2, 2, ColorType::Rgba8888, AlphaType::Unpremul);
551        let src_pixels = vec![
552            255, 0, 0, 255, 0, 255, 0, 255, // row 0
553            0, 0, 255, 255, 255, 255, 0, 255, // row 1
554        ];
555        let src_image =
556            crate::Image::from_raster_data(&info, &src_pixels, 8).expect("raster image");
557        let encoded = crate::PngEncoder::new()
558            .encode_bytes(&src_image)
559            .expect("encode PNG");
560
561        let generator = EncodedImageGenerator::new(encoded).expect("build generator");
562        // After eager decode the advertised info matches decoder output.
563        assert_eq!(generator.info().width, 2);
564        assert_eq!(generator.info().height, 2);
565        assert_eq!(generator.info().color_type, ColorType::Rgba8888);
566
567        // Native format read-out works and matches.
568        let mut dst = vec![0u8; 16];
569        generator
570            .get_pixels(generator.info(), &mut dst, 8)
571            .expect("get_pixels native");
572        // Pixel 0: should be red; alpha interpretation is decoder-dependent
573        // (PNG reports Unpremul for this input) but red still shows red.
574        assert_eq!(dst[0], 255);
575        assert_eq!(dst[1], 0);
576        assert_eq!(dst[2], 0);
577    }
578
579    #[cfg(feature = "png")]
580    #[test]
581    fn test_encoded_generator_caches_decoded_image() {
582        // Decoding is driven by from_shared, so calling get_pixels N times
583        // should not re-decode. We verify by inspecting that repeated
584        // reads from the generator all produce the exact same bytes even
585        // after we drop and recreate the destination buffer.
586        let info = ImageInfo::new(4, 4, ColorType::Rgba8888, AlphaType::Unpremul);
587        let src_pixels: Vec<u8> = (0..(4 * 4 * 4))
588            .map(|i| u8::try_from(i % 256).unwrap())
589            .collect();
590        let src_image =
591            crate::Image::from_raster_data(&info, &src_pixels, 16).expect("raster image");
592        let encoded = crate::PngEncoder::new()
593            .encode_bytes(&src_image)
594            .expect("encode PNG");
595
596        let generator = EncodedImageGenerator::new(encoded).expect("build generator");
597
598        // The decoded image handle should be stable across calls — same
599        // underlying Arc means we are serving from cache, not re-decoding.
600        let img1_ptr = generator.decoded_image().unique_id();
601        let img2_ptr = generator.decoded_image().unique_id();
602        assert_eq!(img1_ptr, img2_ptr);
603
604        // Two calls produce identical bytes.
605        let row_bytes = generator.info().min_row_bytes();
606        let size = generator.info().compute_byte_size(row_bytes);
607        let mut buf1 = vec![0u8; size];
608        let mut buf2 = vec![0u8; size];
609        generator
610            .get_pixels(generator.info(), &mut buf1, row_bytes)
611            .unwrap();
612        generator
613            .get_pixels(generator.info(), &mut buf2, row_bytes)
614            .unwrap();
615        assert_eq!(buf1, buf2);
616    }
617
618    #[cfg(feature = "png")]
619    #[test]
620    fn test_encoded_generator_converts_on_demand() {
621        // Encode a PNG as RGBA, then ask the generator for BGRA: the
622        // conversion path must run over the cached decoded pixels.
623        let info = ImageInfo::new(1, 1, ColorType::Rgba8888, AlphaType::Unpremul);
624        let src_pixels = vec![10, 20, 30, 255];
625        let src_image = crate::Image::from_raster_data(&info, &src_pixels, 4).unwrap();
626        let encoded = crate::PngEncoder::new().encode_bytes(&src_image).unwrap();
627
628        let generator = EncodedImageGenerator::new(encoded).unwrap();
629        // Build a BGRA target info matching the generator's dimensions/alpha.
630        let target = ImageInfo::new(1, 1, ColorType::Bgra8888, generator.info().alpha_type);
631        let mut dst = vec![0u8; 4];
632        generator.get_pixels(&target, &mut dst, 4).unwrap();
633        // BGRA: [B=30, G=20, R=10, A=255]
634        assert_eq!(dst, vec![30, 20, 10, 255]);
635    }
636}