jxl_render/
image.rs

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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
use std::sync::Arc;

use jxl_frame::{data::GlobalModular, FrameHeader};
use jxl_grid::{AlignedGrid, AllocTracker, MutableSubgrid};
use jxl_image::{BitDepth, ImageHeader};
use jxl_modular::{ChannelShift, Sample};
use jxl_threadpool::JxlThreadPool;
use jxl_vardct::LfChannelDequantization;

use crate::{util, FrameRender, FrameRenderHandle, Region, Result};

#[derive(Debug)]
pub enum ImageBuffer {
    F32(AlignedGrid<f32>),
    I32(AlignedGrid<i32>),
    I16(AlignedGrid<i16>),
}

impl ImageBuffer {
    #[inline]
    pub fn from_modular_channel<S: Sample>(g: AlignedGrid<S>) -> Self {
        let g = match S::try_into_grid_i16(g) {
            Ok(g) => return Self::I16(g),
            Err(g) => g,
        };
        match S::try_into_grid_i32(g) {
            Ok(g) => Self::I32(g),
            Err(_) => panic!(),
        }
    }

    #[inline]
    pub fn zeroed_f32(width: usize, height: usize, tracker: Option<&AllocTracker>) -> Result<Self> {
        let grid = AlignedGrid::with_alloc_tracker(width, height, tracker)?;
        Ok(Self::F32(grid))
    }

    #[inline]
    pub fn try_clone(&self) -> Result<Self> {
        match self {
            Self::F32(g) => g.try_clone().map(Self::F32),
            Self::I32(g) => g.try_clone().map(Self::I32),
            Self::I16(g) => g.try_clone().map(Self::I16),
        }
        .map_err(From::from)
    }

    #[inline]
    pub fn width(&self) -> usize {
        match self {
            Self::F32(g) => g.width(),
            Self::I32(g) => g.width(),
            Self::I16(g) => g.width(),
        }
    }

    #[inline]
    pub fn height(&self) -> usize {
        match self {
            Self::F32(g) => g.height(),
            Self::I32(g) => g.height(),
            Self::I16(g) => g.height(),
        }
    }

    #[inline]
    pub fn tracker(&self) -> Option<AllocTracker> {
        match self {
            Self::F32(g) => g.tracker(),
            Self::I32(g) => g.tracker(),
            Self::I16(g) => g.tracker(),
        }
    }

    #[inline]
    pub fn as_float(&self) -> Option<&AlignedGrid<f32>> {
        if let Self::F32(g) = self {
            Some(g)
        } else {
            None
        }
    }

    #[inline]
    pub fn as_float_mut(&mut self) -> Option<&mut AlignedGrid<f32>> {
        if let Self::F32(g) = self {
            Some(g)
        } else {
            None
        }
    }

    pub fn convert_to_float_modular(
        &mut self,
        bit_depth: BitDepth,
    ) -> Result<&mut AlignedGrid<f32>> {
        Ok(match self {
            Self::F32(g) => g,
            Self::I32(g) => {
                let mut out =
                    AlignedGrid::with_alloc_tracker(g.width(), g.height(), g.tracker().as_ref())?;
                for (o, &i) in out.buf_mut().iter_mut().zip(g.buf()) {
                    *o = bit_depth.parse_integer_sample(i);
                }

                *self = Self::F32(out);
                self.as_float_mut().unwrap()
            }
            Self::I16(g) => {
                let mut out =
                    AlignedGrid::with_alloc_tracker(g.width(), g.height(), g.tracker().as_ref())?;
                for (o, &i) in out.buf_mut().iter_mut().zip(g.buf()) {
                    *o = bit_depth.parse_integer_sample(i as i32);
                }

                *self = Self::F32(out);
                self.as_float_mut().unwrap()
            }
        })
    }

    pub fn cast_to_float(&mut self) -> Result<&mut AlignedGrid<f32>> {
        Ok(match self {
            Self::F32(g) => g,
            Self::I32(g) => {
                let mut out =
                    AlignedGrid::with_alloc_tracker(g.width(), g.height(), g.tracker().as_ref())?;
                for (o, &i) in out.buf_mut().iter_mut().zip(g.buf()) {
                    *o = i as f32;
                }

                *self = Self::F32(out);
                self.as_float_mut().unwrap()
            }
            Self::I16(g) => {
                let mut out =
                    AlignedGrid::with_alloc_tracker(g.width(), g.height(), g.tracker().as_ref())?;
                for (o, &i) in out.buf_mut().iter_mut().zip(g.buf()) {
                    *o = i as f32;
                }

                *self = Self::F32(out);
                self.as_float_mut().unwrap()
            }
        })
    }

    pub fn convert_to_float_modular_xyb<'g>(
        yxb: [&'g mut Self; 3],
        lf_dequant: &LfChannelDequantization,
    ) -> Result<[&'g mut AlignedGrid<f32>; 3]> {
        match yxb {
            [Self::F32(_), Self::F32(_), Self::F32(_)] => {
                panic!("channels are already converted");
            }
            [Self::I32(y), Self::I32(_), Self::I32(b)] => {
                for (b, &y) in b.buf_mut().iter_mut().zip(y.buf()) {
                    *b = b.saturating_add(y);
                }
            }
            [Self::I16(y), Self::I16(_), Self::I16(b)] => {
                for (b, &y) in b.buf_mut().iter_mut().zip(y.buf()) {
                    *b = b.saturating_add(y);
                }
            }
            _ => panic!(),
        }

        let [y, x, b] = yxb;
        let y = y.cast_to_float()?;
        let x = x.cast_to_float()?;
        let b = b.cast_to_float()?;
        let buf_y = y.buf_mut();
        let buf_x = x.buf_mut();
        let buf_b = b.buf_mut();
        let m_x_lf = lf_dequant.m_x_lf_unscaled();
        let m_y_lf = lf_dequant.m_y_lf_unscaled();
        let m_b_lf = lf_dequant.m_b_lf_unscaled();

        for ((y, x), b) in buf_y.iter_mut().zip(buf_x).zip(buf_b) {
            let py = *y;
            let px = *x;
            *y = px * m_x_lf;
            *x = py * m_y_lf;
            *b *= m_b_lf;
        }

        Ok([y, x, b])
    }

    pub(crate) fn upsample_nn(&self, factor: u32) -> Result<ImageBuffer> {
        #[inline]
        fn inner<S: Copy>(
            original: &[S],
            target: &mut [S],
            width: usize,
            height: usize,
            factor: u32,
        ) {
            assert_eq!(original.len(), width * height);
            assert_eq!(target.len(), original.len() << (factor * 2));
            let step = 1usize << factor;
            let stride = width << factor;
            for y in 0..height {
                let original = &original[y * width..];
                let target = &mut target[y * step * stride..];
                for (x, &value) in original[..width].iter().enumerate() {
                    target[x * step..][..step].fill(value);
                }
                for row in 1..step {
                    target.copy_within(..stride, stride * row);
                }
            }
        }

        if factor == 0 {
            return self.try_clone();
        }

        let tracker = self.tracker();
        let width = self.width();
        let height = self.height();
        Ok(match self {
            Self::F32(g) => {
                let up_width = width << factor;
                let up_height = height << factor;
                let mut out =
                    AlignedGrid::with_alloc_tracker(up_width, up_height, tracker.as_ref())?;

                let original = g.buf();
                let target = out.buf_mut();
                inner(original, target, width, height, factor);
                Self::F32(out)
            }
            Self::I32(g) => {
                let up_width = width << factor;
                let up_height = height << factor;
                let mut out =
                    AlignedGrid::with_alloc_tracker(up_width, up_height, tracker.as_ref())?;

                let original = g.buf();
                let target = out.buf_mut();
                inner(original, target, width, height, factor);
                Self::I32(out)
            }
            Self::I16(g) => {
                let up_width = width << factor;
                let up_height = height << factor;
                let mut out =
                    AlignedGrid::with_alloc_tracker(up_width, up_height, tracker.as_ref())?;

                let original = g.buf();
                let target = out.buf_mut();
                inner(original, target, width, height, factor);
                Self::I16(out)
            }
        })
    }
}

#[derive(Debug)]
pub struct ImageWithRegion {
    buffer: Vec<ImageBuffer>,
    regions: Vec<(Region, ChannelShift)>,
    color_channels: usize,
    ct_done: bool,
    blend_done: bool,
    tracker: Option<AllocTracker>,
}

impl ImageWithRegion {
    pub(crate) fn new(color_channels: usize, tracker: Option<&AllocTracker>) -> Self {
        Self {
            buffer: Vec::new(),
            regions: Vec::new(),
            color_channels,
            ct_done: false,
            blend_done: false,
            tracker: tracker.cloned(),
        }
    }

    pub(crate) fn try_clone(&self) -> Result<Self> {
        Ok(Self {
            buffer: self
                .buffer
                .iter()
                .map(|x| x.try_clone())
                .collect::<std::result::Result<_, _>>()?,
            regions: self.regions.clone(),
            color_channels: self.color_channels,
            ct_done: self.ct_done,
            blend_done: false,
            tracker: self.tracker.clone(),
        })
    }

    #[inline]
    pub(crate) fn alloc_tracker(&self) -> Option<&AllocTracker> {
        self.tracker.as_ref()
    }

    #[inline]
    pub fn channels(&self) -> usize {
        self.buffer.len()
    }

    #[inline]
    pub fn buffer(&self) -> &[ImageBuffer] {
        &self.buffer
    }

    #[inline]
    pub fn buffer_mut(&mut self) -> &mut [ImageBuffer] {
        &mut self.buffer
    }

    #[inline]
    pub fn take_buffer(&mut self) -> Vec<ImageBuffer> {
        std::mem::take(&mut self.buffer)
    }

    #[inline]
    pub fn regions_and_shifts(&self) -> &[(Region, ChannelShift)] {
        &self.regions
    }

    #[inline]
    pub fn append_channel(&mut self, buffer: ImageBuffer, region: Region) {
        assert_eq!(buffer.width(), region.width as usize);
        assert_eq!(buffer.height(), region.height as usize);
        self.buffer.push(buffer);
        self.regions.push((region, ChannelShift::from_shift(0)));
    }

    #[inline]
    pub fn append_channel_shifted(
        &mut self,
        buffer: ImageBuffer,
        original_region: Region,
        shift: ChannelShift,
    ) {
        let (width, height) = shift.shift_size((original_region.width, original_region.height));
        assert_eq!(buffer.width(), width as usize);
        assert_eq!(buffer.height(), height as usize);
        self.buffer.push(buffer);
        self.regions.push((original_region, shift));
    }

    #[inline]
    pub fn replace_channel(&mut self, index: usize, buffer: ImageBuffer, region: Region) {
        assert_eq!(buffer.width(), region.width as usize);
        assert_eq!(buffer.height(), region.height as usize);
        self.buffer[index] = buffer;
        self.regions[index] = (region, ChannelShift::from_shift(0));
    }

    #[inline]
    pub fn replace_channel_shifted(
        &mut self,
        index: usize,
        buffer: ImageBuffer,
        original_region: Region,
        shift: ChannelShift,
    ) {
        let (width, height) = shift.shift_size((original_region.width, original_region.height));
        assert_eq!(buffer.width(), width as usize);
        assert_eq!(buffer.height(), height as usize);
        self.buffer[index] = buffer;
        self.regions[index] = (original_region, shift);
    }

    #[inline]
    pub(crate) fn swap_channel_f32(
        &mut self,
        index: usize,
        buffer: &mut AlignedGrid<f32>,
        region: Region,
    ) {
        assert_eq!(buffer.width(), region.width as usize);
        assert_eq!(buffer.height(), region.height as usize);
        let ImageBuffer::F32(original_buffer) = &mut self.buffer[index] else {
            panic!("original buffer is not F32");
        };
        std::mem::swap(original_buffer, buffer);
        self.regions[index] = (region, ChannelShift::from_shift(0));
    }

    pub fn extend_from_gmodular<S: Sample>(&mut self, gmodular: GlobalModular<S>) {
        let Some(image) = gmodular.modular.into_image() else {
            return;
        };
        for (g, info) in image.into_image_channels_with_info() {
            let (width, height) = info.original_size();
            let shift = info.shift();

            let original_region = Region::with_size(width, height);
            let buffer = ImageBuffer::from_modular_channel(g);
            self.append_channel_shifted(buffer, original_region, shift);
        }
    }

    pub(crate) fn clone_gray(&mut self) -> Result<()> {
        assert_eq!(self.color_channels, 1);

        let gray = self.buffer[0].try_clone()?;
        let region = self.regions[0];
        self.buffer.insert(1, gray.try_clone()?);
        self.regions.insert(1, region);
        self.buffer.insert(2, gray);
        self.regions.insert(2, region);

        self.color_channels = 3;
        Ok(())
    }

    pub(crate) fn convert_modular_color(&mut self, bit_depth: BitDepth) -> Result<()> {
        assert!(self.buffer.len() >= self.color_channels);
        for g in self.buffer.iter_mut().take(self.color_channels) {
            g.convert_to_float_modular(bit_depth)?;
        }
        Ok(())
    }

    pub(crate) fn convert_modular_xyb(
        &mut self,
        lf_dequant: &LfChannelDequantization,
    ) -> Result<()> {
        assert_eq!(self.color_channels, 3);
        let [y, x, b, ..] = &mut *self.buffer else {
            panic!()
        };
        ImageBuffer::convert_to_float_modular_xyb([y, x, b], lf_dequant)?;
        Ok(())
    }

    pub(crate) fn upsample_lf(&self, lf_level: u32) -> Result<Self> {
        let factor = lf_level * 3;
        let mut out = Self::new(self.color_channels, self.tracker.as_ref());
        for (&(region, shift), buffer) in self.regions.iter().zip(&self.buffer) {
            let up_region = region.upsample(factor);
            let buffer = buffer.upsample_nn(factor)?;
            out.append_channel_shifted(buffer, up_region, shift);
        }
        Ok(out)
    }

    pub(crate) fn upsample_jpeg(
        &mut self,
        valid_region: Region,
        bit_depth: BitDepth,
    ) -> Result<()> {
        assert_eq!(self.color_channels, 3);
        self.convert_modular_color(bit_depth)?;

        for (g, (region, shift)) in self.buffer.iter_mut().zip(&mut self.regions).take(3) {
            let downsampled_image_region = region.downsample_with_shift(*shift);
            let downsampled_valid_region = valid_region.downsample_with_shift(*shift);
            let left = downsampled_valid_region
                .left
                .abs_diff(downsampled_image_region.left);
            let top = downsampled_valid_region
                .top
                .abs_diff(downsampled_image_region.top);
            let width = downsampled_valid_region.width;
            let height = downsampled_valid_region.height;

            let subgrid = g.as_float().unwrap().as_subgrid().subgrid(
                left as usize..(left + width) as usize,
                top as usize..(top + height) as usize,
            );
            let out = crate::filter::apply_jpeg_upsampling_single(
                subgrid,
                *shift,
                valid_region,
                self.tracker.as_ref(),
            )?;

            *g = ImageBuffer::F32(out);
            *region = valid_region;
            *shift = ChannelShift::from_shift(0);
        }

        Ok(())
    }

    pub(crate) fn upsample_nonseparable(
        &mut self,
        image_header: &ImageHeader,
        frame_header: &FrameHeader,
        upsampled_valid_region: Region,
        ec_to_color_only: bool,
    ) -> Result<()> {
        if frame_header.upsampling != 1 && self.buffer[0].as_float().is_none() {
            debug_assert!(!image_header.metadata.xyb_encoded);
        }

        let color_channels = self.color_channels;
        let color_shift = frame_header.upsampling.trailing_zeros();

        for (idx, ((region, shift), g)) in self.regions.iter_mut().zip(&mut self.buffer).enumerate()
        {
            let tracker = g.tracker();
            let ChannelShift::Shifts(upsampling_factor) = *shift else {
                panic!("invalid channel shift for upsampling: {:?}", shift);
            };
            let bit_depth = if let Some(ec_idx) = idx.checked_sub(color_channels) {
                image_header.metadata.ec_info[ec_idx].bit_depth
            } else {
                image_header.metadata.bit_depth
            };

            let target_factor = if ec_to_color_only { color_shift } else { 0 };
            if upsampling_factor == target_factor {
                continue;
            }
            let grid = g.convert_to_float_modular(bit_depth)?;

            let downsampled_image_region = region.downsample(upsampling_factor);
            let downsampled_valid_region = upsampled_valid_region.downsample(upsampling_factor);
            let left = downsampled_valid_region
                .left
                .abs_diff(downsampled_image_region.left);
            let top = downsampled_valid_region
                .top
                .abs_diff(downsampled_image_region.top);
            let width = downsampled_valid_region.width;
            let height = downsampled_valid_region.height;

            let subgrid = grid.as_subgrid().subgrid(
                left as usize..(left + width) as usize,
                top as usize..(top + height) as usize,
            );
            *region = downsampled_valid_region;
            let out = tracing::trace_span!(
                "Non-separable upsampling",
                channel_idx = idx,
                upsampling_factor,
                target_factor
            )
            .in_scope(|| {
                crate::features::upsample(
                    subgrid,
                    region,
                    image_header,
                    upsampling_factor - target_factor,
                    tracker.as_ref(),
                )
            })?;
            if let Some(out) = out {
                *g = ImageBuffer::F32(out);
            }
            *shift = ChannelShift::from_shift(target_factor);
        }

        Ok(())
    }

    pub(crate) fn prepare_color_upsampling(&mut self, frame_header: &FrameHeader) {
        let upsampling_factor = frame_header.upsampling.trailing_zeros();
        for (region, shift) in &mut self.regions {
            match shift {
                ChannelShift::Raw(..=-1, _) | ChannelShift::Raw(_, ..=-1) => continue,
                ChannelShift::Raw(h, v) => {
                    *h = h.wrapping_add_unsigned(upsampling_factor);
                    *v = v.wrapping_add_unsigned(upsampling_factor);
                }
                ChannelShift::Shifts(shift) => {
                    *shift += upsampling_factor;
                }
                ChannelShift::JpegUpsampling {
                    has_h_subsample: false,
                    h_subsample: false,
                    has_v_subsample: false,
                    v_subsample: false,
                } => {
                    *shift = ChannelShift::Shifts(upsampling_factor);
                }
                ChannelShift::JpegUpsampling { .. } => {
                    panic!("unexpected chroma subsampling {:?}", shift);
                }
            }
            *region = region.upsample(upsampling_factor);
        }
    }

    #[inline]
    pub(crate) fn remove_color_channels(&mut self, count: usize) {
        assert!(self.color_channels >= count);
        self.buffer.drain(count..self.color_channels);
        self.regions.drain(count..self.color_channels);
        self.color_channels = count;
    }

    #[inline]
    pub fn color_channels(&self) -> usize {
        self.color_channels
    }

    #[inline]
    pub(crate) fn ct_done(&self) -> bool {
        self.ct_done
    }

    #[inline]
    pub(crate) fn set_ct_done(&mut self, ct_done: bool) {
        self.ct_done = ct_done;
    }

    #[inline]
    pub(crate) fn set_blend_done(&mut self, blend_done: bool) {
        self.blend_done = blend_done;
    }
}

impl ImageWithRegion {
    pub(crate) fn as_color_floats(&self) -> [&AlignedGrid<f32>; 3] {
        assert_eq!(self.color_channels, 3);
        let [a, b, c, ..] = &*self.buffer else {
            panic!()
        };
        let a = a.as_float().unwrap();
        let b = b.as_float().unwrap();
        let c = c.as_float().unwrap();
        [a, b, c]
    }

    pub(crate) fn as_color_floats_mut(&mut self) -> [&mut AlignedGrid<f32>; 3] {
        assert_eq!(self.color_channels, 3);
        let [a, b, c, ..] = &mut *self.buffer else {
            panic!()
        };
        let a = a.as_float_mut().unwrap();
        let b = b.as_float_mut().unwrap();
        let c = c.as_float_mut().unwrap();
        [a, b, c]
    }

    pub(crate) fn color_groups_with_group_id(
        &mut self,
        frame_header: &jxl_frame::FrameHeader,
    ) -> Vec<(u32, [MutableSubgrid<'_, f32>; 3])> {
        assert_eq!(self.color_channels, 3);
        let [fb_x, fb_y, fb_b, ..] = &mut *self.buffer else {
            panic!();
        };

        let group_dim = frame_header.group_dim();
        let base_group_x = self.regions[0].0.left as u32 / group_dim;
        let base_group_y = self.regions[0].0.top as u32 / group_dim;
        let width = self.regions[0].0.width;
        let frame_groups_per_row = frame_header.groups_per_row();
        let groups_per_row = (width + group_dim - 1) / group_dim;

        let [fb_x, fb_y, fb_b] = [(0usize, fb_x), (1, fb_y), (2, fb_b)].map(|(idx, fb)| {
            let fb = fb.as_float_mut().unwrap().as_subgrid_mut();
            let hshift = self.regions[idx].1.hshift();
            let vshift = self.regions[idx].1.vshift();
            let group_dim = group_dim as usize;
            fb.into_groups(group_dim >> hshift, group_dim >> vshift)
        });

        fb_x.into_iter()
            .zip(fb_y)
            .zip(fb_b)
            .enumerate()
            .map(|(idx, ((fb_x, fb_y), fb_b))| {
                let idx = idx as u32;
                let group_x = base_group_x + (idx % groups_per_row);
                let group_y = base_group_y + (idx / groups_per_row);
                let group_idx = group_y * frame_groups_per_row + group_x;
                (group_idx, [fb_x, fb_y, fb_b])
            })
            .collect()
    }
}

pub struct RenderedImage<S: Sample> {
    image: Arc<FrameRenderHandle<S>>,
}

impl<S: Sample> RenderedImage<S> {
    pub(crate) fn new(image: Arc<FrameRenderHandle<S>>) -> Self {
        Self { image }
    }
}

impl<S: Sample> RenderedImage<S> {
    pub(crate) fn blend(
        &self,
        oriented_image_region: Option<Region>,
        pool: &JxlThreadPool,
    ) -> Result<Arc<ImageWithRegion>> {
        let image_header = self.image.frame.image_header();
        let frame_header = self.image.frame.header();
        let image_region = self.image.image_region;
        let oriented_image_region = oriented_image_region
            .unwrap_or_else(|| util::apply_orientation_to_image_region(image_header, image_region));
        let frame_region = oriented_image_region
            .translate(-frame_header.x0, -frame_header.y0)
            .downsample(frame_header.lf_level * 3);
        let frame_region = util::pad_lf_region(frame_header, frame_region);
        let frame_region = util::pad_color_region(image_header, frame_header, frame_region);
        let frame_region = frame_region.upsample(frame_header.upsampling.ilog2());
        let frame_region = if frame_header.frame_type.is_normal_frame() {
            let full_image_region_in_frame =
                Region::with_size(image_header.size.width, image_header.size.height)
                    .translate(-frame_header.x0, -frame_header.y0);
            frame_region.intersection(full_image_region_in_frame)
        } else {
            frame_region
        };

        let mut grid_lock = self.image.render.lock().unwrap();
        if let FrameRender::Blended(image) = &*grid_lock {
            return Ok(Arc::clone(image));
        }

        let render = std::mem::replace(&mut *grid_lock, FrameRender::ErrTaken);
        let FrameRender::Done(mut grid) = render else {
            panic!();
        };

        if frame_header.can_reference() {
            let bit_depth_it = std::iter::repeat(image_header.metadata.bit_depth)
                .take(grid.color_channels)
                .chain(image_header.metadata.ec_info.iter().map(|ec| ec.bit_depth));
            for (buffer, bit_depth) in grid.buffer.iter_mut().zip(bit_depth_it) {
                buffer.convert_to_float_modular(bit_depth)?;
            }
        }

        if !frame_header.frame_type.is_normal_frame() || frame_header.resets_canvas {
            grid.blend_done = true;
            let image = Arc::new(grid);
            *grid_lock = FrameRender::Blended(Arc::clone(&image));
            return Ok(image);
        }

        if !grid.ct_done() {
            util::convert_color_for_record(image_header, frame_header.do_ycbcr, &mut grid, pool)?;
        }

        let image = crate::blend::blend(
            image_header,
            self.image.refs.clone(),
            &self.image.frame,
            &mut grid,
            frame_region,
            pool,
        )?;

        let image = Arc::new(image);
        *grid_lock = FrameRender::Blended(Arc::clone(&image));
        Ok(image)
    }

    pub(crate) fn try_take_blended(&self) -> Option<ImageWithRegion> {
        let mut grid_lock = self.image.render.lock().unwrap();
        match std::mem::take(&mut *grid_lock) {
            FrameRender::Blended(image) => {
                let cloned_image = Arc::clone(&image);
                let image_inner = Arc::into_inner(cloned_image);
                if image_inner.is_none() {
                    *grid_lock = FrameRender::Blended(image);
                }
                image_inner
            }
            render => {
                *grid_lock = render;
                None
            }
        }
    }
}