image 0.25.9

Imaging library. Provides basic image processing and encoders/decoders for common image formats.
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
use crate::codecs::avif::yuv::{
    check_rgb_preconditions, check_yuv_plane_preconditions, qrshr, yuv420_to_rgbx_invoker,
    yuv422_to_rgbx_invoker, CbCrInverseTransform, HalvedRowHandler, PlaneDefinition,
    YuvChromaRange, YuvIntensityRange, YuvPlanarImage, YuvStandardMatrix,
};
use crate::ImageError;
use num_traits::AsPrimitive;

/// Computes YCgCo inverse in limited range
/// # Arguments
/// - `dst` - dest buffer
/// - `y_value` - Y value with subtracted bias
/// - `cb` - Cb value with subtracted bias
/// - `cr` - Cr value with subtracted bias
#[inline(always)]
fn ycgco_execute_limited<
    V: Copy + AsPrimitive<i32> + 'static + Sized,
    const PRECISION: i32,
    const CHANNELS: usize,
    const BIT_DEPTH: usize,
>(
    dst: &mut [V; CHANNELS],
    y_value: i32,
    cg: i32,
    co: i32,
    scale: i32,
) where
    i32: AsPrimitive<V>,
{
    let t0 = y_value - cg;

    let r = qrshr::<PRECISION, BIT_DEPTH>((t0 + co) * scale);
    let b = qrshr::<PRECISION, BIT_DEPTH>((t0 - co) * scale);
    let g = qrshr::<PRECISION, BIT_DEPTH>((y_value + cg) * scale);

    if CHANNELS == 4 {
        dst[0] = r.as_();
        dst[1] = g.as_();
        dst[2] = b.as_();
        dst[3] = ((1i32 << BIT_DEPTH) - 1).as_();
    } else if CHANNELS == 3 {
        dst[0] = r.as_();
        dst[1] = g.as_();
        dst[2] = b.as_();
    } else {
        unreachable!();
    }
}

/// Computes YCgCo inverse in full range
/// # Arguments
/// - `dst` - dest buffer
/// - `y_value` - Y value with subtracted bias
/// - `cb` - Cb value with subtracted bias
/// - `cr` - Cr value with subtracted bias
#[inline(always)]
fn ycgco_execute_full<
    V: Copy + AsPrimitive<i32> + 'static + Sized,
    const PRECISION: i32,
    const CHANNELS: usize,
    const BIT_DEPTH: usize,
>(
    dst: &mut [V; CHANNELS],
    y_value: i32,
    cg: i32,
    co: i32,
) where
    i32: AsPrimitive<V>,
{
    let t0 = y_value - cg;

    let max_value = (1i32 << BIT_DEPTH) - 1;

    let r = (t0 + co).clamp(0, max_value);
    let b = (t0 - co).clamp(0, max_value);
    let g = (y_value + cg).clamp(0, max_value);

    if CHANNELS == 4 {
        dst[0] = r.as_();
        dst[1] = g.as_();
        dst[2] = b.as_();
        dst[3] = max_value.as_();
    } else if CHANNELS == 3 {
        dst[0] = r.as_();
        dst[1] = g.as_();
        dst[2] = b.as_();
    } else {
        unreachable!();
    }
}

#[inline(always)]
fn process_halved_chroma_row_cgco<
    V: Copy + AsPrimitive<i32> + 'static + Sized,
    const PRECISION: i32,
    const CHANNELS: usize,
    const BIT_DEPTH: usize,
>(
    image: YuvPlanarImage<V>,
    rgba: &mut [V],
    _: &CbCrInverseTransform<i32>,
    range: &YuvChromaRange,
) where
    i32: AsPrimitive<V>,
{
    let max_value = (1i32 << BIT_DEPTH) - 1;

    // If the stride is larger than the plane size,
    // it might contain junk data beyond the actual valid region.
    // To avoid processing artifacts when working with odd-sized images,
    // the buffer is reshaped to its actual size,
    // preventing accidental use of invalid values from the trailing region.

    let y_plane = &image.y_plane[..image.width];
    let chroma_size = image.width.div_ceil(2);
    let u_plane = &image.u_plane[..chroma_size];
    let v_plane = &image.v_plane[..chroma_size];
    let rgba = &mut rgba[..image.width * CHANNELS];

    let bias_y = range.bias_y as i32;
    let bias_uv = range.bias_uv as i32;
    let y_iter = y_plane.chunks_exact(2);
    let rgb_chunks = rgba.chunks_exact_mut(CHANNELS * 2);

    let scale_coef = ((max_value as f32 / range.range_y as f32) * (1 << PRECISION) as f32) as i32;

    for (((y_src, &u_src), &v_src), rgb_dst) in y_iter.zip(u_plane).zip(v_plane).zip(rgb_chunks) {
        let y_value0: i32 = y_src[0].as_() - bias_y;
        let cg_value: i32 = u_src.as_() - bias_uv;
        let co_value: i32 = v_src.as_() - bias_uv;

        let dst0 = &mut rgb_dst[..CHANNELS];

        ycgco_execute_limited::<V, PRECISION, CHANNELS, BIT_DEPTH>(
            dst0.try_into().unwrap(),
            y_value0,
            cg_value,
            co_value,
            scale_coef,
        );

        let y_value1 = y_src[1].as_() - bias_y;

        let dst1 = &mut rgb_dst[CHANNELS..2 * CHANNELS];

        ycgco_execute_limited::<V, PRECISION, CHANNELS, BIT_DEPTH>(
            dst1.try_into().unwrap(),
            y_value1,
            cg_value,
            co_value,
            scale_coef,
        );
    }

    // Process remainder if width is odd.
    if image.width & 1 != 0 {
        let y_left = y_plane.chunks_exact(2).remainder();
        let rgb_chunks = rgba
            .chunks_exact_mut(CHANNELS * 2)
            .into_remainder()
            .chunks_exact_mut(CHANNELS);
        let u_iter = u_plane.iter().rev();
        let v_iter = v_plane.iter().rev();

        for (((y_src, u_src), v_src), rgb_dst) in
            y_left.iter().zip(u_iter).zip(v_iter).zip(rgb_chunks)
        {
            let y_value = y_src.as_() - bias_y;
            let cg_value = u_src.as_() - bias_uv;
            let co_value = v_src.as_() - bias_uv;

            ycgco_execute_limited::<V, PRECISION, CHANNELS, BIT_DEPTH>(
                rgb_dst.try_into().unwrap(),
                y_value,
                cg_value,
                co_value,
                scale_coef,
            );
        }
    }
}

/// Converts YCgCo 444 planar format to Rgba
///
/// # Arguments
///
/// * `image`: see [YuvPlanarImage]
/// * `rgba`: RGB image layout
/// * `range`: see [YuvIntensityRange]
///
fn ycgco444_to_rgbx_impl<
    V: Copy + AsPrimitive<i32> + 'static + Sized,
    const CHANNELS: usize,
    const BIT_DEPTH: usize,
>(
    image: YuvPlanarImage<V>,
    rgba: &mut [V],
    yuv_range: YuvIntensityRange,
) -> Result<(), ImageError>
where
    i32: AsPrimitive<V>,
{
    assert!(
        CHANNELS == 3 || CHANNELS == 4,
        "YUV 4:4:4 -> RGB is implemented only on 3 and 4 channels"
    );
    assert!(
        (8..=16).contains(&BIT_DEPTH),
        "Invalid bit depth is provided"
    );
    assert!(
        if BIT_DEPTH > 8 {
            size_of::<V>() == 2
        } else {
            size_of::<V>() == 1
        },
        "Unsupported bit depth and data type combination"
    );

    let y_plane = image.y_plane;
    let u_plane = image.u_plane;
    let v_plane = image.v_plane;
    let y_stride = image.y_stride;
    let u_stride = image.u_stride;
    let v_stride = image.v_stride;
    let height = image.height;
    let width = image.width;

    check_yuv_plane_preconditions(y_plane, PlaneDefinition::Y, y_stride, height)?;
    check_yuv_plane_preconditions(u_plane, PlaneDefinition::U, u_stride, height)?;
    check_yuv_plane_preconditions(v_plane, PlaneDefinition::V, v_stride, height)?;

    check_rgb_preconditions(rgba, image.width * CHANNELS, height)?;

    let range = yuv_range.get_yuv_range(BIT_DEPTH as u32);
    const PRECISION: i32 = 13;

    let bias_y = range.bias_y as i32;
    let bias_uv = range.bias_uv as i32;

    let rgb_stride = width * CHANNELS;

    let y_iter = y_plane.chunks_exact(y_stride);
    let rgb_iter = rgba.chunks_exact_mut(rgb_stride);
    let u_iter = u_plane.chunks_exact(u_stride);
    let v_iter = v_plane.chunks_exact(v_stride);

    let max_value: i32 = (1 << BIT_DEPTH) - 1;

    // All branches on generic const will be optimized out.
    for (((y_src, u_src), v_src), rgb) in y_iter.zip(u_iter).zip(v_iter).zip(rgb_iter) {
        let rgb_chunks = rgb.chunks_exact_mut(CHANNELS);
        match yuv_range {
            YuvIntensityRange::Tv => {
                let y_coef =
                    ((max_value as f32 / range.range_y as f32) * (1 << PRECISION) as f32) as i32;
                for (((y_src, u_src), v_src), rgb_dst) in
                    y_src.iter().zip(u_src).zip(v_src).zip(rgb_chunks)
                {
                    let y_value = y_src.as_() - bias_y;
                    let cg_value = u_src.as_() - bias_uv;
                    let co_value = v_src.as_() - bias_uv;

                    ycgco_execute_limited::<V, PRECISION, CHANNELS, BIT_DEPTH>(
                        rgb_dst.try_into().unwrap(),
                        y_value,
                        cg_value,
                        co_value,
                        y_coef,
                    );
                }
            }
            YuvIntensityRange::Pc => {
                for (((y_src, u_src), v_src), rgb_dst) in
                    y_src.iter().zip(u_src).zip(v_src).zip(rgb_chunks)
                {
                    let y_value = y_src.as_() - bias_y;
                    let cg_value = u_src.as_() - bias_uv;
                    let co_value = v_src.as_() - bias_uv;

                    ycgco_execute_full::<V, PRECISION, CHANNELS, BIT_DEPTH>(
                        rgb_dst.try_into().unwrap(),
                        y_value,
                        cg_value,
                        co_value,
                    );
                }
            }
        }
    }

    Ok(())
}

macro_rules! define_ycgco_half_chroma {
    ($name: ident, $invoker: ident, $storage: ident, $cn: expr, $bp: expr, $description: expr) => {
        #[doc = concat!($description, "
        
        # Arguments
        
        * `image`: see [YuvPlanarImage]
        * `rgb`: RGB image layout
        * `range`: see [YuvIntensityRange]
        * `matrix`: see [YuvStandardMatrix]")]
        pub(crate) fn $name(
            image: YuvPlanarImage<$storage>,
            rgb: &mut [$storage],
            range: YuvIntensityRange,
        ) -> Result<(), ImageError> {
            const P: i32 = 13;
            $invoker::<$storage, HalvedRowHandler<$storage>, P, $cn, $bp>(
                image,
                rgb,
                range,
                YuvStandardMatrix::Bt709,
                process_halved_chroma_row_cgco::<$storage, P, $cn, $bp>,
            )
        }
    };
}

const RGBA_CN: usize = 4;

define_ycgco_half_chroma!(
    ycgco420_to_rgba8,
    yuv420_to_rgbx_invoker,
    u8,
    RGBA_CN,
    8,
    "Converts YCgCo 420 8-bit planar format to Rgba 8-bit"
);

define_ycgco_half_chroma!(
    ycgco422_to_rgba8,
    yuv422_to_rgbx_invoker,
    u8,
    RGBA_CN,
    8,
    "Converts YCgCo 420 8-bit planar format to Rgba 8-bit"
);

define_ycgco_half_chroma!(
    ycgco420_to_rgba10,
    yuv420_to_rgbx_invoker,
    u16,
    RGBA_CN,
    10,
    "Converts YCgCo 420 10-bit planar format to Rgba 10-bit"
);

define_ycgco_half_chroma!(
    ycgco422_to_rgba10,
    yuv422_to_rgbx_invoker,
    u16,
    RGBA_CN,
    10,
    "Converts YCgCo 422 10-bit planar format to Rgba 10-bit"
);

define_ycgco_half_chroma!(
    ycgco420_to_rgba12,
    yuv420_to_rgbx_invoker,
    u16,
    RGBA_CN,
    12,
    "Converts YCgCo 420 12-bit planar format to Rgba 12-bit"
);

define_ycgco_half_chroma!(
    ycgco422_to_rgba12,
    yuv422_to_rgbx_invoker,
    u16,
    RGBA_CN,
    12,
    "Converts YCgCo 422 12-bit planar format to Rgba 12-bit"
);

macro_rules! define_ycgcg_full_chroma {
    ($name: ident, $storage: ident, $cn: expr, $bp: expr, $description: expr) => {
        #[doc = concat!($description, "
        
        # Arguments
        
        * `image`: see [YuvPlanarImage]
        * `rgba`: RGB image layout
        * `range`: see [YuvIntensityRange]
        * `matrix`: see [YuvStandardMatrix]
        ")]
        pub(crate) fn $name(
            image: YuvPlanarImage<$storage>,
            rgba: &mut [$storage],
            range: YuvIntensityRange,
        ) -> Result<(), ImageError> {
            ycgco444_to_rgbx_impl::<$storage, $cn, $bp>(image, rgba, range)
        }
    };
}

define_ycgcg_full_chroma!(
    ycgco444_to_rgba8,
    u8,
    RGBA_CN,
    8,
    "Converts YCgCo 444 planar format 8 bit-depth to Rgba 8 bit"
);
define_ycgcg_full_chroma!(
    ycgco444_to_rgba10,
    u16,
    RGBA_CN,
    10,
    "Converts YCgCo 444 planar format 10 bit-depth to Rgba 10 bit"
);
define_ycgcg_full_chroma!(
    ycgco444_to_rgba12,
    u16,
    RGBA_CN,
    12,
    "Converts YCgCo 444 planar format 12 bit-depth to Rgba 12 bit"
);