jixel 0.5.13

JPEG XL encoder
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
/*
 * // Copyright (c) Radzivon Bartoshyk 5/2026. All rights reserved.
 * //
 * // Redistribution and use in source and binary forms, with or without modification,
 * // are permitted provided that the following conditions are met:
 * //
 * // 1.  Redistributions of source code must retain the above copyright notice, this
 * // list of conditions and the following disclaimer.
 * //
 * // 2.  Redistributions in binary form must reproduce the above copyright notice,
 * // this list of conditions and the following disclaimer in the documentation
 * // and/or other materials provided with the distribution.
 * //
 * // 3.  Neither the name of the copyright holder nor the names of its
 * // contributors may be used to endorse or promote products derived from
 * // this software without specific prior written permission.
 * //
 * // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
use crate::image::{Image3S, ImageB, ImageSB};
use crate::util::{EncodeError, try_vec};

pub(crate) const STRATEGY_DCT: u8 = 0;
pub(crate) const STRATEGY_DCT16X8: u8 = 1;
pub(crate) const STRATEGY_DCT8X16: u8 = 2;
pub(crate) const STRATEGY_DCT16X16: u8 = 3;
pub(crate) const STRATEGY_DCT32X32: u8 = 4;
pub(crate) const STRATEGY_DCT4X4: u8 = 5;
pub(crate) const STRATEGY_DCT4X8: u8 = 6;
pub(crate) const STRATEGY_DCT8X4: u8 = 7;
pub(crate) const STRATEGY_DCT32X16: u8 = 8;
pub(crate) const STRATEGY_DCT16X32: u8 = 9;
pub(crate) const STRATEGY_AFV0: u8 = 10;
pub(crate) const STRATEGY_AFV1: u8 = 11;
pub(crate) const STRATEGY_AFV2: u8 = 12;
pub(crate) const STRATEGY_AFV3: u8 = 13;
pub(crate) const STRATEGY_DCT64X64: u8 = 14;
pub(crate) const STRATEGY_DCT64X32: u8 = 15;
pub(crate) const STRATEGY_DCT32X64: u8 = 16;
pub(crate) const STRATEGY_IDENTITY: u8 = 17;
pub(crate) const STRATEGY_DCT2X2: u8 = 18;
pub(crate) const STRATEGY_DCT128X128: u8 = 19;
/// 128 rows x 64 columns.
pub(crate) const STRATEGY_DCT128X64: u8 = 20;
/// 64 rows x 128 columns.
pub(crate) const STRATEGY_DCT64X128: u8 = 21;
/// 32 rows x 8 columns.
pub(crate) const STRATEGY_DCT32X8: u8 = 22;
/// 8 rows x 32 columns.
pub(crate) const STRATEGY_DCT8X32: u8 = 23;
pub(crate) const NUM_STRATEGIES: usize = 24;

#[inline]
pub(crate) fn is_128_strategy(strategy: u8) -> bool {
    matches!(
        strategy,
        STRATEGY_DCT128X128 | STRATEGY_DCT128X64 | STRATEGY_DCT64X128
    )
}

#[inline]
pub(crate) fn is_gated_sub8_strategy(strategy: u8) -> bool {
    matches!(strategy, STRATEGY_IDENTITY | STRATEGY_DCT2X2)
}

#[cfg(test)]
pub(crate) fn is_sub8_strategy(strategy: u8) -> bool {
    matches!(
        strategy,
        STRATEGY_IDENTITY
            | STRATEGY_DCT2X2
            | STRATEGY_DCT4X4
            | STRATEGY_DCT4X8
            | STRATEGY_DCT8X4
            | STRATEGY_AFV0
            | STRATEGY_AFV1
            | STRATEGY_AFV2
            | STRATEGY_AFV3
    )
}

/// Map raw strategy -> JXL HfTransformType code (= what the bitstream stores).
/// DCT8=0, DCT16X16=4, DCT32X32=5, DCT16X8=6, DCT8X16=7, DCT4X4=3, DCT4X8=12, DCT8X4=13,
/// DCT32X16=10, DCT16X32=11, AFV0..3=14..17, DCT64 family=18..20,
/// IDENTITY=1, DCT2X2=2, DCT32X8=8, DCT8X32=9.
pub(crate) static STRATEGY_CODE_LUT: [u8; NUM_STRATEGIES] = [
    0, 6, 7, 4, 5, 3, 12, 13, 10, 11, 14, 15, 16, 17, 18, 19, 20, 1, 2, 21, 22, 23, 8, 9,
];

const FIRST_BLOCK_BIT: u8 = 1;

pub(crate) struct AcStrategyImage {
    xsize: usize,
    ysize: usize,
    /// Row-major xsize × ysize. Each entry: (raw_strategy << 1) | is_first_bit.
    cells: Vec<u8>,
}

impl AcStrategyImage {
    pub(crate) fn new(xsize: usize, ysize: usize) -> Self {
        // Default: every block is its own DCT8 first block: (0 << 1) | 1 = 1.
        Self {
            xsize,
            ysize,
            cells: vec![(STRATEGY_DCT << 1) | FIRST_BLOCK_BIT; xsize * ysize],
        }
    }

    pub(crate) fn try_new(xsize: usize, ysize: usize) -> Result<Self, EncodeError> {
        let len = xsize
            .checked_mul(ysize)
            .ok_or(EncodeError::AllocationFailed { size: usize::MAX })?;
        Ok(Self {
            xsize,
            ysize,
            cells: try_vec![(STRATEGY_DCT << 1) | FIRST_BLOCK_BIT; len]?,
        })
    }

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

    /// Restore the default all-DCT8 layout while retaining the cell allocation.
    pub(crate) fn reset(&mut self) {
        self.cells.fill((STRATEGY_DCT << 1) | FIRST_BLOCK_BIT);
    }

    /// Copy block rows `y0..y1` from `src` into `self` (both must share
    /// dimensions). Used to merge per-band selection results computed on
    /// independent worker threads back into the group's strategy image.
    pub(crate) fn copy_rows_from(&mut self, src: &AcStrategyImage, y0: usize, y1: usize) {
        debug_assert_eq!(self.xsize, src.xsize);
        let a = y0 * self.xsize;
        let b = y1 * self.xsize;
        self.cells[a..b].copy_from_slice(&src.cells[a..b]);
    }

    #[inline]
    pub(crate) fn is_first_block(&self, x: usize, y: usize) -> bool {
        self.cells[y * self.xsize + x] & FIRST_BLOCK_BIT != 0
    }
    #[inline]
    pub(crate) fn raw_strategy(&self, x: usize, y: usize) -> u8 {
        self.cells[y * self.xsize + x] >> 1
    }
    /// JXL HfTransformType code used in the bitstream.
    #[inline]
    pub(crate) fn strategy_code(&self, x: usize, y: usize) -> u8 {
        STRATEGY_CODE_LUT[self.raw_strategy(x, y) as usize]
    }

    #[inline]
    pub(crate) fn covered_blocks_x_of(strategy: u8) -> usize {
        // {DCT: 1, DCT16X8: 1, DCT8X16: 2, DCT16X16: 2, DCT32X32: 4, DCT4X4: 1,
        //  DCT4X8: 1, DCT8X4: 1, DCT32X16: 2, DCT16X32: 4, AFV0..3: 1}
        static LUT: [u8; NUM_STRATEGIES] = [
            1, 1, 2, 2, 4, 1, 1, 1, 2, 4, 1, 1, 1, 1, 8, 4, 8, 1, 1, 16, 8, 16, 1, 4,
        ];
        LUT[strategy as usize] as usize
    }

    #[inline]
    pub(crate) fn covered_blocks_y_of(strategy: u8) -> usize {
        // {DCT: 1, DCT16X8: 2, DCT8X16: 1, DCT16X16: 2, DCT32X32: 4, DCT4X4: 1,
        //  DCT4X8: 1, DCT8X4: 1, DCT32X16: 4, DCT16X32: 2, AFV0..3: 1}
        static LUT: [u8; NUM_STRATEGIES] = [
            1, 2, 1, 2, 4, 1, 1, 1, 4, 2, 1, 1, 1, 1, 8, 8, 4, 1, 1, 16, 16, 8, 4, 1,
        ];
        LUT[strategy as usize] as usize
    }

    pub(crate) fn can_place_strategy(&self, x: usize, y: usize, strategy: u8) -> bool {
        let cx = Self::covered_blocks_x_of(strategy);
        let cy = Self::covered_blocks_y_of(strategy);
        if x + cx > self.xsize || y + cy > self.ysize {
            return false;
        }
        const GROUP: usize = 32;
        if (x / GROUP) != ((x + cx - 1) / GROUP) {
            return false;
        }
        if (y / GROUP) != ((y + cy - 1) / GROUP) {
            return false;
        }
        // A multi-block transform must also stay within a single 8-block
        // (64 px) tile, since `write_ac_group` processes one tile-tall stripe
        // at a time. The layout DP may place even pair transforms at an
        // 8-pixel origin, so this bound applies to every multi-block shape.
        const TILE: usize = 8;
        if is_128_strategy(strategy) {
            // 128px transforms span several 64px tiles; the AC group writer
            // processes whole groups, so only the group bound applies. Keep
            // them on their own size grid like every other merge.
            return x.is_multiple_of(cx) && y.is_multiple_of(cy);
        }
        if (x / TILE) != ((x + cx - 1) / TILE) {
            return false;
        }
        if (y / TILE) != ((y + cy - 1) / TILE) {
            return false;
        }
        true
    }

    /// The format's own rule only: inside the image and one 256px AC group.
    /// Unlike `can_place_strategy`, a block may cross 64px CfL tiles (the
    /// decoder takes the tile of its first block).
    pub(crate) fn can_place_strategy_crossing(&self, x: usize, y: usize, strategy: u8) -> bool {
        let cx = Self::covered_blocks_x_of(strategy);
        let cy = Self::covered_blocks_y_of(strategy);
        const GROUP: usize = 32;
        x + cx <= self.xsize
            && y + cy <= self.ysize
            && x / GROUP == (x + cx - 1) / GROUP
            && y / GROUP == (y + cy - 1) / GROUP
            && !is_128_strategy(strategy)
    }

    /// Mark (x, y) as the first block of a multi-block transform with the
    /// given `strategy`. Fills covered cells with non-first markers.
    pub(crate) fn set_first(&mut self, x: usize, y: usize, strategy: u8) {
        let cx = Self::covered_blocks_x_of(strategy);
        let cy = Self::covered_blocks_y_of(strategy);
        assert!(
            x + cx <= self.xsize && y + cy <= self.ysize,
            "transform out of bounds: ({x},{y}) +{cx}x{cy} on {}x{}",
            self.xsize,
            self.ysize
        );
        self.cells[y * self.xsize + x] = (strategy << 1) | FIRST_BLOCK_BIT;
        let v = strategy << 1;

        let mut rows = self.cells.chunks_exact_mut(self.xsize).skip(y).take(cy);

        if let Some(row) = rows.next() {
            row[x + 1..x + cx].fill(v);
        }

        for row in rows {
            row[x..x + cx].fill(v);
        }
    }

    #[cfg(feature = "extraslow")]
    /// Raw cells of a `w`x`h` region, for an exact restore.
    pub(crate) fn save_region(&self, x: usize, y: usize, w: usize, h: usize) -> Vec<u8> {
        (y..y + h)
            .flat_map(|r| {
                self.cells[r * self.xsize + x..r * self.xsize + x + w]
                    .iter()
                    .copied()
            })
            .collect()
    }

    /// True if no transform crosses the boundary of the block region, so a
    /// new layout can replace exactly the transforms inside it. Transforms may
    /// cross 64px tiles, so tile alignment alone does not imply this.
    #[cfg(feature = "extraslow")]
    pub(crate) fn region_closed(&self, x: usize, y: usize, w: usize, h: usize) -> bool {
        let mut covered = 0;
        for yy in y..y + h {
            for xx in x..x + w {
                if self.is_first_block(xx, yy) {
                    let raw = self.raw_strategy(xx, yy);
                    let (cx, cy) = (
                        Self::covered_blocks_x_of(raw),
                        Self::covered_blocks_y_of(raw),
                    );
                    if xx + cx > x + w || yy + cy > y + h {
                        return false;
                    }
                    covered += cx * cy;
                }
            }
        }
        covered == w * h
    }

    #[cfg(feature = "extraslow")]
    pub(crate) fn restore_region(&mut self, x: usize, y: usize, w: usize, saved: &[u8]) {
        for (i, row) in saved.chunks_exact(w).enumerate() {
            let start = (y + i) * self.xsize + x;
            self.cells[start..start + w].copy_from_slice(row);
        }
    }

    /// True if a multi-block transform of `strategy` can be placed at (x, y).
    /// Iterate first blocks in raster order, yielding (x, y, raw_strategy).
    pub(crate) fn iter_first_blocks(&self) -> impl Iterator<Item = (usize, usize, u8)> + '_ {
        let xs = self.xsize;
        let cells = &self.cells;
        (0..self.ysize).flat_map(move |y| {
            (0..xs).filter_map(move |x| {
                let cell = cells[y * xs + x];
                if cell & FIRST_BLOCK_BIT != 0 {
                    Some((x, y, cell >> 1))
                } else {
                    None
                }
            })
        })
    }

    /// Count first blocks (== modular channel[2] width).
    pub(crate) fn count_first_blocks(&self) -> usize {
        self.cells
            .iter()
            .filter(|&&c| c & FIRST_BLOCK_BIT != 0)
            .count()
    }
}

#[cfg_attr(not(feature = "extraslow"), allow(dead_code))]
/// A re-tiling proposal: the pieces (strategy, dx, dy) tiling one closed
/// rectangle of blocks that the proposal lays out differently.
#[derive(Clone, Debug)]
pub(crate) struct DpRegion {
    pub(crate) bx: usize,
    pub(crate) by: usize,
    pub(crate) w: usize,
    pub(crate) h: usize,
    pub(crate) pieces: Vec<(u8, usize, usize)>,
}

pub(crate) struct DcGroupData {
    pub(crate) quant_dc: Image3S,
    /// Unrounded B DC from the first coefficient pass, retained only until
    /// the frame's DC predictor has been checked with the final quantizer.
    pub(crate) source_dc_b: Option<crate::image::Plane<f32>>,
    /// Unrounded Y DC from the first coefficient pass, retained until the
    /// frame's DC steps are chosen.
    pub(crate) source_dc_y: Option<crate::image::Plane<f32>>,
    /// Unrounded X DC, kept with `source_dc_b` for the chroma DC coding choice.
    pub(crate) source_dc_x: Option<crate::image::Plane<f32>>,
    pub(crate) raw_quant_field: ImageB,
    /// Per-block field from before selection merged it over each transform,
    /// retained until the frame-level matrix gate has re-tiled any region.
    pub(crate) block_quant_field: Option<ImageB>,
    pub(crate) ac_strategy: AcStrategyImage,
    pub(crate) ytox_map: ImageSB,
    pub(crate) ytob_map: ImageSB,
    /// Accumulated RD benefit of all sub-8x8 strategies from
    /// `fill_ac_strategy`, used by the frame-level activation gate. 0 until
    /// selection runs.
    pub(crate) sub8_benefit: f32,
    /// Closed regions whose layout the exact re-tiling would change, for
    /// the ExtraSlow layout loop to arbitrate (DC-group block coordinates).
    pub(crate) dp_regions: Vec<DpRegion>,
}

const TILE_DIM_IN_BLOCKS: usize = 8;

impl DcGroupData {
    pub(crate) fn new(xsize_blocks: usize, ysize_blocks: usize) -> Result<Self, EncodeError> {
        let xtiles = xsize_blocks.div_ceil(TILE_DIM_IN_BLOCKS);
        let ytiles = ysize_blocks.div_ceil(TILE_DIM_IN_BLOCKS);
        Ok(Self {
            quant_dc: Image3S::try_new(xsize_blocks, ysize_blocks)?,
            source_dc_b: None,
            source_dc_y: None,
            source_dc_x: None,
            raw_quant_field: ImageB::try_new_fill(xsize_blocks, ysize_blocks, 1)?,
            block_quant_field: None,
            ac_strategy: AcStrategyImage::try_new(xsize_blocks, ysize_blocks)?,
            ytox_map: ImageSB::try_new_fill(xtiles, ytiles, 0)?,
            ytob_map: ImageSB::try_new_fill(xtiles, ytiles, 0)?,
            sub8_benefit: 0.0,
            dp_regions: Vec::new(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn dc_group_allocation_failure_is_reported() {
        assert!(matches!(
            DcGroupData::new(usize::MAX, 1),
            Err(EncodeError::AllocationFailed { size: usize::MAX })
        ));
    }

    #[test]
    fn sub8_strategy_set_is_complete() {
        for strategy in 0..NUM_STRATEGIES as u8 {
            assert_eq!(
                is_sub8_strategy(strategy),
                matches!(
                    strategy,
                    STRATEGY_IDENTITY
                        | STRATEGY_DCT2X2
                        | STRATEGY_DCT4X4
                        | STRATEGY_DCT4X8
                        | STRATEGY_DCT8X4
                        | STRATEGY_AFV0
                        | STRATEGY_AFV1
                        | STRATEGY_AFV2
                        | STRATEGY_AFV3
                )
            );
        }
    }

    #[test]
    fn fine_strategies_use_the_spec_wire_codes() {
        assert_eq!(STRATEGY_CODE_LUT[STRATEGY_IDENTITY as usize], 1);
        assert_eq!(STRATEGY_CODE_LUT[STRATEGY_DCT2X2 as usize], 2);
        assert_eq!(AcStrategyImage::covered_blocks_x_of(STRATEGY_IDENTITY), 1);
        assert_eq!(AcStrategyImage::covered_blocks_y_of(STRATEGY_IDENTITY), 1);
        assert_eq!(AcStrategyImage::covered_blocks_x_of(STRATEGY_DCT2X2), 1);
        assert_eq!(AcStrategyImage::covered_blocks_y_of(STRATEGY_DCT2X2), 1);
    }

    #[test]
    fn default_is_dct8_first_blocks() {
        let a = AcStrategyImage::new(4, 4);
        for y in 0..4 {
            for x in 0..4 {
                assert!(a.is_first_block(x, y));
                assert_eq!(a.raw_strategy(x, y), STRATEGY_DCT);
                assert_eq!(a.strategy_code(x, y), 0); // JXL HfTransformType for DCT
            }
        }
        assert_eq!(a.count_first_blocks(), 16);
    }

    #[test]
    fn dct16x8_covers_1x2_blocks() {
        // DCT16X8: 1 col × 2 rows of 8x8 blocks.
        let mut a = AcStrategyImage::new(4, 4);
        a.set_first(0, 0, STRATEGY_DCT16X8);
        assert!(a.is_first_block(0, 0));
        assert_eq!(a.raw_strategy(0, 0), STRATEGY_DCT16X8);
        assert_eq!(a.strategy_code(0, 0), 6); // JXL DCT16X8
        // Covered block at (0, 1) — same column, next row down.
        assert!(!a.is_first_block(0, 1));
        assert_eq!(a.raw_strategy(0, 1), STRATEGY_DCT16X8);
        // Other blocks still DCT8 first.
        assert!(a.is_first_block(1, 0));
        assert!(a.is_first_block(0, 2));
        // 16 default - 1 covered = 15 first blocks.
        assert_eq!(a.count_first_blocks(), 15);
    }

    #[test]
    fn dct8x16_covers_2x1_blocks() {
        // DCT8X16: 2 cols × 1 row of 8x8 blocks.
        let mut a = AcStrategyImage::new(4, 4);
        a.set_first(0, 0, STRATEGY_DCT8X16);
        assert!(a.is_first_block(0, 0));
        assert_eq!(a.strategy_code(0, 0), 7); // JXL DCT8X16
        assert!(!a.is_first_block(1, 0));
        assert_eq!(a.raw_strategy(1, 0), STRATEGY_DCT8X16);
        assert!(a.is_first_block(0, 1));
        assert_eq!(a.count_first_blocks(), 15);
    }

    #[test]
    fn crossing_placement_keeps_only_the_format_rules() {
        let a = AcStrategyImage::new(40, 40);
        // Crosses the 64px tile at x=8 while staying inside group 0.
        assert!(!a.can_place_strategy(7, 0, STRATEGY_DCT8X16));
        assert!(a.can_place_strategy_crossing(7, 0, STRATEGY_DCT8X16));
        assert!(a.can_place_strategy_crossing(6, 6, STRATEGY_DCT32X32));
        // The 256px group, the image bounds and the 128 family stay fenced.
        assert!(!a.can_place_strategy_crossing(31, 0, STRATEGY_DCT8X16));
        assert!(!a.can_place_strategy_crossing(39, 0, STRATEGY_DCT8X16));
        assert!(!a.can_place_strategy_crossing(0, 0, STRATEGY_DCT128X128));
    }

    #[test]
    fn can_place_respects_bounds_and_groups() {
        let a = AcStrategyImage::new(4, 4);
        assert!(a.can_place_strategy(0, 0, STRATEGY_DCT16X8)); // 1×2 fits
        assert!(a.can_place_strategy(3, 0, STRATEGY_DCT16X8)); // 1×2 fits at right edge (col 3)
        assert!(!a.can_place_strategy(0, 3, STRATEGY_DCT16X8)); // 1×2 doesn't fit at row 3
        assert!(a.can_place_strategy(0, 3, STRATEGY_DCT8X16)); // 2×1 fits at bottom edge
        assert!(!a.can_place_strategy(3, 0, STRATEGY_DCT8X16)); // 2×1 doesn't fit at col 3

        // Group boundary check (32-block AC groups):
        let big = AcStrategyImage::new(35, 35);
        assert!(!big.can_place_strategy(0, 31, STRATEGY_DCT16X8)); // 1×2 would straddle y=32
        assert!(big.can_place_strategy(0, 30, STRATEGY_DCT16X8)); // 1×2 stays within group 0
        assert!(!big.can_place_strategy(31, 0, STRATEGY_DCT8X16)); // 2×1 would straddle x=32
        assert!(big.can_place_strategy(30, 0, STRATEGY_DCT8X16)); // 2×1 stays within group 0
    }
}