dds 0.2.0

DDS de/encoder written in 100% safe Rust
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
use crate::{cast, ColorFormat, ImageView, Precision, ResizeFilter, Size};

use resize::{Filter, Resizer};

pub(crate) struct Aligner {
    buffer: Vec<u8>,
}
impl Aligner {
    pub fn new() -> Self {
        Self { buffer: Vec::new() }
    }

    pub fn align<'a>(&'a mut self, image: ImageView<'a>) -> AlignedView<'a> {
        let size = image.size();
        let color = image.color();
        let data = image.data();

        let bytes_per_pixel = color.bytes_per_pixel() as usize;

        let view = if !image.is_contiguous() {
            // Right now, the implementation assumes that the data to be
            // contiguous, so we need to copy it to an aligned buffer line by line.
            let aligned_slice = get_aligned_slice(&mut self.buffer, size, bytes_per_pixel);
            let bytes_per_row = size.width as usize * bytes_per_pixel;
            for (y, data_row) in image.rows().enumerate() {
                debug_assert_eq!(data_row.len(), bytes_per_row);
                let a_start = y * bytes_per_row;
                let a_end = a_start + bytes_per_row;
                aligned_slice[a_start..a_end].copy_from_slice(data_row);
            }
            aligned_slice
        } else if is_aligned(data, color.precision.size() as usize) {
            data
        } else {
            // the image data isn't aligned, so we need to copy it to an aligned buffer
            let aligned_slice = get_aligned_slice(&mut self.buffer, size, bytes_per_pixel);
            aligned_slice.copy_from_slice(data);
            aligned_slice
        };

        AlignedView { view, size, color }
    }
}

pub(crate) struct AlignedView<'a> {
    view: &'a [u8],
    size: Size,
    color: ColorFormat,
}

pub(crate) struct ResizeState {
    dest_buffer: Vec<u8>,
}
impl ResizeState {
    pub fn new() -> Self {
        Self {
            dest_buffer: Vec::new(),
        }
    }

    pub fn resize<'a>(
        &'a mut self,
        src: &AlignedView,
        new_size: Size,
        straight_alpha: bool,
        filter: ResizeFilter,
    ) -> &'a [u8] {
        let bytes_per_pixel = src.color.bytes_per_pixel() as usize;

        // prepare the destination buffer
        let dest_slice = get_aligned_slice(&mut self.dest_buffer, new_size, bytes_per_pixel);

        let filter = to_resize_filter_type(filter);
        let args = Args {
            size: src.size,
            src_bytes: src.view,
            new_size,
            dst_bytes: dest_slice,
            filter,
        };

        use Precision::*;
        match (src.color.precision, src.color.channels.count()) {
            (U8, 1) => resize_typed::<Pixel<[u8; 1]>>(args),
            (U16, 1) => resize_typed::<Pixel<[u16; 1]>>(args),
            (F32, 1) => resize_typed::<Pixel<[f32; 1]>>(args),
            (U8, 3) => resize_typed::<Pixel<[u8; 3]>>(args),
            (U16, 3) => resize_typed::<Pixel<[u16; 3]>>(args),
            (F32, 3) => resize_typed::<Pixel<[f32; 3]>>(args),
            (U8, 4) => {
                if straight_alpha {
                    resize_typed::<StraightAlpha<[u8; 4]>>(args)
                } else {
                    resize_typed::<Pixel<[u8; 4]>>(args)
                }
            }
            (U16, 4) => {
                if straight_alpha {
                    resize_typed::<StraightAlpha<[u16; 4]>>(args)
                } else {
                    resize_typed::<Pixel<[u16; 4]>>(args)
                }
            }
            (F32, 4) => {
                if straight_alpha {
                    resize_typed::<StraightAlpha<[f32; 4]>>(args)
                } else {
                    resize_typed::<Pixel<[f32; 4]>>(args)
                }
            }
            _ => unreachable!(),
        }

        dest_slice
    }
}

struct Args<'a, 'b> {
    size: Size,
    src_bytes: &'a [u8],
    new_size: Size,
    dst_bytes: &'b mut [u8],
    filter: resize::Type,
}
fn resize_typed<P>(
    Args {
        size,
        src_bytes,
        new_size,
        dst_bytes,
        filter,
    }: Args,
) where
    P: resize::PixelFormat + Default,
    P::InputPixel: cast::Castable,
    P::OutputPixel: cast::Castable,
{
    let src_slice: &[P::InputPixel] = cast::from_bytes(src_bytes).expect("invalid source data");
    let dst_slice: &mut [P::OutputPixel] =
        cast::from_bytes_mut(dst_bytes).expect("invalid destination data");

    let mut resizes: Resizer<P> = resize::Resizer::new(
        size.width as usize,
        size.height as usize,
        new_size.width as usize,
        new_size.height as usize,
        P::default(),
        filter,
    )
    .unwrap();

    resizes.resize(src_slice, dst_slice).unwrap();
}

fn get_aligned_slice(buffer: &mut Vec<u8>, size: Size, bytes_per_pixel: usize) -> &mut [u8] {
    let slice_len = size.pixels() as usize * bytes_per_pixel;
    let align_to = 4;

    // we want the buffer to slightly larger than the slice, so we have
    // some space to align the slice
    let buffer_len = size.pixels() as usize * bytes_per_pixel + align_to;
    if buffer.len() < buffer_len {
        buffer.resize(buffer_len, 0);
    }

    // figure out the offset which aligns the slice
    let mut aligned_offset = 0;
    for offset in 0..align_to {
        let slice = &mut buffer[offset..offset + slice_len];
        if is_aligned(slice, align_to) {
            aligned_offset = offset;
            break;
        }
    }

    &mut buffer[aligned_offset..aligned_offset + slice_len]
}

fn is_aligned(slice: &[u8], alignment: usize) -> bool {
    (slice.as_ptr() as usize) % alignment == 0
}

fn to_resize_filter_type(filter: ResizeFilter) -> resize::Type {
    match filter {
        ResizeFilter::Nearest => resize::Type::Point,
        ResizeFilter::Box => resize::Type::Custom(Filter::box_filter(1.0)),
        ResizeFilter::Triangle => resize::Type::Triangle,
        ResizeFilter::Mitchell => resize::Type::Mitchell,
        ResizeFilter::Lanczos3 => resize::Type::Lanczos3,
    }
}

use pixel::{Pixel, StraightAlpha};
mod pixel {
    use glam::Vec4;

    pub(crate) struct Pixel<T> {
        _marker: std::marker::PhantomData<T>,
    }
    impl<T> Default for Pixel<T> {
        fn default() -> Self {
            Self {
                _marker: std::marker::PhantomData,
            }
        }
    }

    pub(crate) trait SelectAccumulator {
        type Accumulator: Accumulator;
    }
    pub(crate) struct Selector<const N: usize>;
    impl SelectAccumulator for Selector<1> {
        type Accumulator = f32;
    }
    impl SelectAccumulator for Selector<3> {
        type Accumulator = Vec4;
    }
    impl SelectAccumulator for Selector<4> {
        type Accumulator = Vec4;
    }

    pub(crate) trait Accumulator: Copy + Send + Sync {
        fn zero() -> Self;
        fn add_scaled(&mut self, input: Self, scale: f32);
    }
    impl Accumulator for f32 {
        fn zero() -> Self {
            0.0
        }
        fn add_scaled(&mut self, input: Self, scale: f32) {
            *self += input * scale;
        }
    }
    impl Accumulator for Vec4 {
        fn zero() -> Self {
            Vec4::ZERO
        }
        fn add_scaled(&mut self, input: Self, scale: f32) {
            *self += input * scale;
        }
    }

    pub(crate) trait IntoAccumulator<T> {
        fn to_accumulator(self) -> T;
        fn to_value(acc: T) -> Self;
    }
    impl IntoAccumulator<f32> for [u8; 1] {
        fn to_accumulator(self) -> f32 {
            self[0] as f32
        }
        fn to_value(acc: f32) -> Self {
            [(acc + 0.5) as u8]
        }
    }
    impl IntoAccumulator<f32> for [u16; 1] {
        fn to_accumulator(self) -> f32 {
            self[0] as f32
        }
        fn to_value(acc: f32) -> Self {
            [(acc + 0.5) as u16]
        }
    }
    impl IntoAccumulator<f32> for [f32; 1] {
        fn to_accumulator(self) -> f32 {
            self[0]
        }
        fn to_value(acc: f32) -> Self {
            [acc]
        }
    }
    impl IntoAccumulator<Vec4> for [u8; 3] {
        fn to_accumulator(self) -> Vec4 {
            Vec4::new(self[0] as f32, self[1] as f32, self[2] as f32, 0.0)
        }
        fn to_value(acc: Vec4) -> Self {
            [
                (acc.x + 0.5) as u8,
                (acc.y + 0.5) as u8,
                (acc.z + 0.5) as u8,
            ]
        }
    }
    impl IntoAccumulator<Vec4> for [u16; 3] {
        fn to_accumulator(self) -> Vec4 {
            Vec4::new(self[0] as f32, self[1] as f32, self[2] as f32, 0.0)
        }
        fn to_value(acc: Vec4) -> Self {
            [
                (acc.x + 0.5) as u16,
                (acc.y + 0.5) as u16,
                (acc.z + 0.5) as u16,
            ]
        }
    }
    impl IntoAccumulator<Vec4> for [f32; 3] {
        fn to_accumulator(self) -> Vec4 {
            Vec4::new(self[0], self[1], self[2], 0.0)
        }
        fn to_value(acc: Vec4) -> Self {
            [acc.x, acc.y, acc.z]
        }
    }
    impl IntoAccumulator<Vec4> for [u8; 4] {
        fn to_accumulator(self) -> Vec4 {
            Vec4::new(
                self[0] as f32,
                self[1] as f32,
                self[2] as f32,
                self[3] as f32,
            )
        }
        fn to_value(acc: Vec4) -> Self {
            [
                (acc.x + 0.5) as u8,
                (acc.y + 0.5) as u8,
                (acc.z + 0.5) as u8,
                (acc.w + 0.5) as u8,
            ]
        }
    }
    impl IntoAccumulator<Vec4> for [u16; 4] {
        fn to_accumulator(self) -> Vec4 {
            Vec4::new(
                self[0] as f32,
                self[1] as f32,
                self[2] as f32,
                self[3] as f32,
            )
        }
        fn to_value(acc: Vec4) -> Self {
            [
                (acc.x + 0.5) as u16,
                (acc.y + 0.5) as u16,
                (acc.z + 0.5) as u16,
                (acc.w + 0.5) as u16,
            ]
        }
    }
    impl IntoAccumulator<Vec4> for [f32; 4] {
        fn to_accumulator(self) -> Vec4 {
            Vec4::new(self[0], self[1], self[2], self[3])
        }
        fn to_value(acc: Vec4) -> Self {
            [acc.x, acc.y, acc.z, acc.w]
        }
    }

    impl<T, const N: usize> resize::PixelFormat for Pixel<[T; N]>
    where
        T: Send + Sync + Copy,
        [T; N]: Default,
        Selector<N>: SelectAccumulator,
        [T; N]: IntoAccumulator<<Selector<N> as SelectAccumulator>::Accumulator>,
    {
        type InputPixel = [T; N];

        type OutputPixel = [T; N];

        type Accumulator = <Selector<N> as SelectAccumulator>::Accumulator;

        fn new() -> Self::Accumulator {
            Self::Accumulator::zero()
        }

        fn add(&self, acc: &mut Self::Accumulator, inp: Self::InputPixel, coeff: f32) {
            acc.add_scaled(inp.to_accumulator(), coeff);
        }

        fn add_acc(acc: &mut Self::Accumulator, inp: Self::Accumulator, coeff: f32) {
            acc.add_scaled(inp, coeff);
        }

        fn into_pixel(&self, acc: Self::Accumulator) -> Self::OutputPixel {
            Self::OutputPixel::to_value(acc)
        }
    }

    pub(crate) struct StraightAlpha<T> {
        _marker: std::marker::PhantomData<T>,
    }
    impl<T> Default for StraightAlpha<T> {
        fn default() -> Self {
            Self {
                _marker: std::marker::PhantomData,
            }
        }
    }
    pub(crate) trait IntoStraightAlphaAccumulator<T> {
        fn to_accumulator(self) -> T;
        fn to_value(acc: T) -> Self;
    }
    impl IntoStraightAlphaAccumulator<Vec4> for [u8; 4] {
        fn to_accumulator(self) -> Vec4 {
            let a = self[3] as f32;
            Vec4::new(
                self[0] as f32 * a,
                self[1] as f32 * a,
                self[2] as f32 * a,
                a,
            )
        }
        fn to_value(acc: Vec4) -> Self {
            let a = acc.w;
            let a_out = (a + 0.5) as u8;
            if a_out == 0 {
                return [0, 0, 0, 0];
            }
            let a_r = a.recip();
            [
                (acc.x * a_r + 0.5) as u8,
                (acc.y * a_r + 0.5) as u8,
                (acc.z * a_r + 0.5) as u8,
                a_out,
            ]
        }
    }
    impl IntoStraightAlphaAccumulator<Vec4> for [u16; 4] {
        fn to_accumulator(self) -> Vec4 {
            let a = self[3] as f32;
            Vec4::new(
                self[0] as f32 * a,
                self[1] as f32 * a,
                self[2] as f32 * a,
                a,
            )
        }
        fn to_value(acc: Vec4) -> Self {
            let a = acc.w;
            let a_out = (a + 0.5) as u16;
            if a_out == 0 {
                return [0, 0, 0, 0];
            }
            let a_r = a.recip();
            [
                (acc.x * a_r + 0.5) as u16,
                (acc.y * a_r + 0.5) as u16,
                (acc.z * a_r + 0.5) as u16,
                a_out,
            ]
        }
    }
    impl IntoStraightAlphaAccumulator<Vec4> for [f32; 4] {
        fn to_accumulator(self) -> Vec4 {
            let a = self[3];
            Vec4::new(self[0] * a, self[1] * a, self[2] * a, a)
        }
        fn to_value(acc: Vec4) -> Self {
            let a = acc.w;
            if a == 0.0 {
                return [0.0, 0.0, 0.0, 0.0];
            }
            let a_r = 1.0 / a.recip();
            [acc.x * a_r, acc.y * a_r, acc.z * a_r, a]
        }
    }

    impl<T> resize::PixelFormat for StraightAlpha<[T; 4]>
    where
        T: Send + Sync + Copy,
        [T; 4]: Default + IntoStraightAlphaAccumulator<Vec4>,
    {
        type InputPixel = [T; 4];

        type OutputPixel = [T; 4];

        type Accumulator = Vec4;

        fn new() -> Self::Accumulator {
            Self::Accumulator::zero()
        }

        fn add(&self, acc: &mut Self::Accumulator, inp: Self::InputPixel, coeff: f32) {
            acc.add_scaled(inp.to_accumulator(), coeff);
        }

        fn add_acc(acc: &mut Self::Accumulator, inp: Self::Accumulator, coeff: f32) {
            acc.add_scaled(inp, coeff);
        }

        fn into_pixel(&self, acc: Self::Accumulator) -> Self::OutputPixel {
            Self::OutputPixel::to_value(acc)
        }
    }
}