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
/*
 * // Copyright (c) Radzivon Bartoshyk 10/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.
 */

//! Per-tier encoder tool switches. Every effort-dependent decision reads one
//! named gate here instead of comparing against a [`Speed`] variant, so a
//! tier is just a row of this table.

use crate::Speed;

macro_rules! effort_gates {
    (
        $($(#[$doc:meta])* $name:ident,)* ;
        $($(#[$xdoc:meta])* $xname:ident,)*
    ) => {
        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
        pub(crate) struct Effort {
            $($(#[$doc])* pub(crate) $name: bool,)*
            $($xname: bool,)*
        }

        impl Effort {
            const NONE: Self = Self { $($name: false,)* $($xname: false,)* };
            const ALL: Self = Self { $($name: true,)* $($xname: true,)* };

            $(
                $(#[$xdoc])*
                #[cfg_attr(not(feature = "extraslow"), allow(dead_code))]
                #[inline(always)]
                pub(crate) const fn $xname(&self) -> bool {
                    cfg!(feature = "extraslow") && self.$xname
                }
            )*

            #[cfg(test)]
            fn gates(&self) -> Vec<(&'static str, bool)> {
                vec![$((stringify!($name), self.$name),)* $((stringify!($xname), self.$xname),)*]
            }
        }
    };
}

effort_gates! {
    // --- lossy VarDCT ---
    /// Full thread budget on small images (otherwise one lane per 64K pixels).
    full_threads,
    /// Square merge search (16x16/32x32) over the plain 8x8 DCT grid, with
    /// the per-strategy block contexts and custom-matrix accounting it needs.
    square_merges,
    /// 32x32 merges in the square search (otherwise 16x16 only).
    merge_32,
    /// Evaluate merges on quads whose DCT8 incumbent already exceeds
    /// `MERGE_PRESCREEN_BITS`.
    merge_busy_quads,
    /// Per-block quantizer refinement after the transform search.
    quant_refine,
    /// Pixel-chromacity X steps outside the chroma policy.
    pixel_chromacity_x,
    /// CfL slope search for YCbCr frames.
    cfl_ycbcr_rdo,
    /// Weighted DC predictor with per-context gradient fallback.
    dc_predictor_search,
    /// Chroma DC rounding with frozen residual prices and a pooled rate check.
    dc_rdoq,
    /// ... refined once more under the written DC tree's contexts, leaf
    /// predictors and clustered histograms, then re-tokenized under it.
    dc_rdoq_refit,
    /// Per-image learned DC context tree raced against the static tree.
    dc_learned_tree,
    /// The DC streams race the second libjxl weighted-predictor preset
    /// exactly against the default (Fast and up).
    dc_wp_race,
    /// The MA-learned DC tree arm under its xlite budget (32 leaves, 64K
    /// samples, one side predictor, static metadata side).
    ma_dc_tree_xlite,
    /// ... under its lite budget (`ma_dc_tree` runs the full budget).
    ma_dc_tree_lite,
    /// ... with 400 leaves learned from every DC sample (Medium; large
    /// screenshots carry it, small DC planes never fill the lite cap).
    ma_dc_tree_deep,
    /// ... and fit the parameters by coordinate descent when it wins
    /// (`dc_wp_fit` races every preset and always fits).
    dc_wp_fit_on_win,
    /// Per-cluster hybrid-uint config selection.
    huc_select,
    /// Prefix-model AC context clustering (otherwise a coarse context merge).
    ac_prefix_clustering,
    /// Greedy context clustering may open every cluster the format allows
    /// (otherwise `FAST_CLUSTERS_LIMIT`).
    wide_clustering,
    /// Fast ANS cluster refinement of the DC and AC codes.
    ans_fast_refine,
    /// The refined ANS codes race their prefix-coded twins.
    ans_prefix_race,
    /// Below `ans_recluster`: recluster at distance >= 3 during the fast refinement.
    ans_recluster_coarse,
    /// Rectangular, sub-8x8 (DCT4/AFV/IDENTITY) and leaf-first transform search.
    rectangles,
    /// SSIM reconstruction rerank at every distance (otherwise high quality only).
    full_rerank,
    dct64,
    fine_mosaic,
    learned_rate,
    /// Chroma content analysis and every policy it drives: saturated/pair-B/x-heavy
    /// tables, point chroma, chroma HF protection, pixel-chromacity B steps.
    chroma_policy,
    /// Exact DP re-tiling of closed 64x64 tiles over 8/16/32-family pieces at
    /// any 8-pixel origin; skipped where `layout_loop` re-chooses layouts exactly.
    /// Where it installs its layout, the rerank's downgrade and upgrade passes
    /// are skipped: the DP covers both.
    layout_retile,
    /// 32-family pieces (strips, 32x16/16x32, 32x32) in the `layout_retile` DP;
    /// otherwise it re-tiles over DCT8, pairs and 16x16 only.
    layout_retile_32,
    /// After the aligned `layout_retile` pass, passes on half-tile-shifted
    /// grids whose pieces may cross the 64px CfL tiles (the format only
    /// fences the 256px group). libjxl and jxl-rs decode them exactly;
    /// jxl-oxide 0.12 applies CfL per tile and deviates on crossing pieces.
    /// Also drives the shifted passes of the coefficient-model DP.
    layout_crossing,
    /// The two axis-shifted grids after the diagonal one of `layout_crossing`.
    layout_crossing_axes,
    /// Coefficient-model DP re-tiling of the merge search's tiles over DCT8,
    /// pairs and 16x16 at any 8-pixel origin; superseded by `layout_retile`.
    layout_dp_coefficient,
    /// The coefficient-model DP also places pairs and 16x16 squares off the
    /// 16-pixel grid (otherwise only inside aligned 2x2 quads).
    layout_dp_unaligned,
    cfl_rdo,
    /// Frame-constant EPF strength and pass count fitted on the final
    /// reconstruction by the luma proxy.
    epf_fit,
    yellow_opsin,
    /// A refine pass re-quantizes every group on custom coefficient orders
    /// with RDOQ under the first pass's token prices.
    coeff_orders,
    /// RDOQ by a beam of backward paths (otherwise one greedy pass).
    rdoq_beam,
    /// RDOQ by the count-banded trellis (over `rdoq_beam`).
    rdoq_trellis,
    ac_ctx_plan,
    ma_dc_tree,
    /// Luma-error-compensated B DC targets and, per chroma channel, a 2x finer
    /// DC step holding a squeeze-smoothed plane when cheaper and closer.
    chroma_dc_squeeze,
    /// Frame-level X DC chroma-from-luma search on the unrounded source,
    /// under the final luma levels and DC quantization steps.
    dc_x_cfl,
    ans_refine,
    /// Below `ans_refine`: recluster at every distance (otherwise from d=3).
    ans_recluster,
    lossy_modular_auto,
    splines,
    patches_default,
    /// `EncodeConfig::ink_layer` is on by default at this speed.
    ink_layer_default,
    /// `EncodeConfig::vector_layers` is on by default at this speed.
    vector_layers_default,
    /// Saturated pixels take a free target beyond the clip limit before the
    /// forward transform.
    clip_continuation,
    /// Lossy tile patches also match near-duplicate tiles, not only exact ones.
    near_patch_tiles,
    /// Any config strictly cheaper than the default hybrid-uint wins (else a 0.5% bar).
    huc_strict,
    // --- modular (lossless, lossy squeeze, patch atlases) ---
    /// Ring-hash LZ77 matcher next to run-only LZ77.
    lz_deep,
    /// ANS, per-cluster hybrid-uint selection and refined clustering for LZ streams.
    lz_refined_entropy,
    predictor_search,
    rct_search,
    /// RCT ranking covers all 42 rct_types (otherwise cjxl -e7's seven).
    rct_all_types,
    /// RCT ranking scores every row (otherwise one row in `RCT_DENSE_ROW_STEP`).
    rct_every_row,
    /// RCT ranking scores one row in `RCT_DENSE_ROW_STEP` (otherwise one in
    /// `RCT_SPARSE_ROW_STEP`).
    rct_dense_rows,
    wp_search,
    /// Parallel per-group palettes behind a global coverage gate.
    local_palette_select,
    /// Searched predictors for the local-palette frame (otherwise fixed).
    local_palette_predictors,
    /// Flat-path channels split their context on the WP error property at
    /// fixed cut-offs (`WP_CONTEXT_CUTOFFS`).
    flat_wp_contexts,
    /// Encode the normal frame too when a palette frame succeeded; keep the smaller.
    palette_dual,
    /// Meta-adaptive learned trees and the candidate-frame race.
    learned_tree,
    /// Coarse-learn comparison of the palette and RGB sources and the RCT runner-up.
    tree_rank,
    /// 8M/16M-sample final tree learn.
    tree_dense_sampling,
    /// 2M-sample tree learn (otherwise 512K).
    tree_full_sampling,
    /// Learn under both the 1024 px and the 256 px group layouts.
    tree_dual_layout,
    /// Final learns of sub-sampled sources keep the full leaf budget and split
    /// candidates (otherwise `MA_LITE_MAX_LEAVES` and `MA_LITE_CANDIDATES`).
    tree_deep_final,
    /// Final learns sample their source afresh (otherwise they deepen the
    /// ranking stage's sample set when it matches their own).
    tree_fresh_final_samples,
    tree_global_palette,
    /// The global palette's index order by the cheap estimate races the
    /// coarse learn's best other order: complete estimates under the first
    /// layout, then complete frames when those are close.
    palette_order_race,
    tree_group_palette,
    tree_ctx_v1,
    /// Gradient and photo-like rectangles of a screenshot as cropped frames
    /// of their own (`region_frames`).
    region_frames,
    /// A squeezed extra channel codes its AC groups through the frame's global
    /// tree beside the DC tree, raced against their local trees.
    extra_global_tree,
    ;
    // --- ExtraSlow only: always off without the `extraslow` feature ---
    /// Closed-loop quant-field refinement on the reconstructed luma (MS-SSIM).
    aq_closed_loop,
    /// Per-coefficient polish of the settled frame against the exact
    /// SSIMULACRA2 and ColorVideoVDP states (`coef_polish`).
    coef_polish,
    /// Lossy-modular luma residuals polished against the exact SSIMULACRA2
    /// and ColorVideoVDP states (`lossy_modular::polish`).
    lm_residual_polish,
    /// 128-family transforms placed by the closed loop's exact SSIMULACRA2 arbiter.
    dct128_loop,
    /// 16x16 transform layouts (DCT8 quad, DCT16, rectangle pairs) re-chosen by
    /// the closed loop's exact SSIMULACRA2 arbiter.
    layout_loop,
    /// Race frequency-derived coefficient orders against natural scans using
    /// serialized permutation headers and final entropy-coded AC streams.
    coeff_order_entropy_race,
    /// Rank B DC CfL slopes with weighted prediction in pooled WP-error contexts.
    dc_cfl_weighted,
    /// Re-tokenize on the custom orders before pricing RDOQ however little
    /// the scans moved (otherwise only past `RDOQ_FRESH_PRICES_MIN_SCAN_MOVE`).
    rdoq_fresh_prices,
    /// Broader final hybrid-uint and ANS-table search.
    ans_exhaustive,
    /// Price every hybrid-uint candidate under its fully searched ANS table.
    lz_exhaustive_entropy,
    /// Broader cost-aware LZ77 parses alongside the normal stream candidates.
    lz_priced_search,
    /// The priced LZ77 parse is a shortest path over token positions
    /// (otherwise greedy: the best match at each position).
    lz_optimal_parse,
    /// Ranking learns of every WP preset.
    tree_rank_deep,
    /// The VarDCT DC streams race libjxl's four weighted-predictor presets
    /// exactly, then fit the parameters from the winner by coordinate
    /// descent on a proxy and price the fit exactly.
    dc_wp_fit,
    /// Final RCT tree learns score more predictors on each side of a split.
    tree_wide_side_preds,
    /// One EM step on the MA-learned DC tree: leaves re-pick their predictor
    /// under the clustered histograms and the winning arm is priced again
    /// (−0.012 % at Slow for +5..13 % time, so ExtraSlow only).
    ma_dc_repick,
}

static ULTRAFAST: Effort = Effort {
    dc_learned_tree: true,
    ans_fast_refine: true,
    ..Effort::NONE
};

static FASTEST: Effort = Effort {
    square_merges: true,
    merge_32: true,
    merge_busy_quads: true,
    layout_dp_coefficient: true,
    dc_predictor_search: true,
    ma_dc_tree_xlite: true,
    ac_prefix_clustering: true,
    ..ULTRAFAST
};

static FAST: Effort = Effort {
    full_threads: true,
    square_merges: true,
    merge_32: true,
    merge_busy_quads: true,
    quant_refine: true,
    layout_dp_coefficient: true,
    layout_dp_unaligned: true,
    layout_crossing: true,
    pixel_chromacity_x: true,
    cfl_ycbcr_rdo: true,
    dc_predictor_search: true,
    dc_learned_tree: true,
    dc_wp_race: true,
    ma_dc_tree_xlite: true,
    ma_dc_tree_lite: true,
    huc_select: true,
    ac_prefix_clustering: true,
    wide_clustering: true,
    ans_fast_refine: true,
    ans_prefix_race: true,
    ans_recluster_coarse: true,
    rct_search: true,
    local_palette_predictors: true,
    flat_wp_contexts: true,
    coeff_orders: true,
    ..Effort::NONE
};

static MEDIUM: Effort = Effort {
    layout_crossing: true,
    layout_crossing_axes: true,
    cfl_rdo: true,
    yellow_opsin: true,
    rdoq_beam: true,
    chroma_policy: true,
    fine_mosaic: true,
    dc_rdoq: true,
    dc_rdoq_refit: true,
    dc_wp_race: true,
    ma_dc_tree_deep: true,
    chroma_dc_squeeze: true,
    dc_x_cfl: true,
    ink_layer_default: true,
    clip_continuation: true,
    lz_deep: true,
    lz_refined_entropy: true,
    predictor_search: true,
    rct_dense_rows: true,
    wp_search: true,
    local_palette_select: true,
    palette_dual: true,
    learned_tree: true,
    tree_rank: true,
    tree_global_palette: true,
    tree_group_palette: true,
    ..FAST
};

static MEDIUM_SLOW: Effort = Effort {
    layout_retile_32: false,
    vector_layers_default: false,
    ac_ctx_plan: false,
    lossy_modular_auto: false,
    splines: false,
    rct_every_row: false,
    tree_dense_sampling: false,
    tree_dual_layout: false,
    tree_ctx_v1: false,
    tree_deep_final: false,
    tree_fresh_final_samples: false,
    palette_order_race: false,
    patches_default: false,
    region_frames: false,
    ..SLOW
};

static SLOW: Effort = Effort {
    aq_closed_loop: false,
    coef_polish: false,
    lm_residual_polish: false,
    dct128_loop: false,
    layout_loop: false,
    coeff_order_entropy_race: false,
    dc_cfl_weighted: false,
    rdoq_fresh_prices: false,
    ans_exhaustive: false,
    lz_exhaustive_entropy: false,
    lz_priced_search: false,
    lz_optimal_parse: false,
    tree_rank_deep: false,
    dc_wp_fit: false,
    tree_wide_side_preds: false,
    ma_dc_repick: false,
    ..Effort::ALL
};

#[cfg(feature = "extraslow")]
static EXTRASLOW: Effort = Effort::ALL;

impl Speed {
    pub(crate) const fn effort(self) -> &'static Effort {
        match self {
            Speed::UltraFast => &ULTRAFAST,
            Speed::Fastest => &FASTEST,
            Speed::Fast => &FAST,
            Speed::Medium => &MEDIUM,
            Speed::MediumSlow => &MEDIUM_SLOW,
            Speed::Slow => &SLOW,
            #[cfg(feature = "extraslow")]
            Speed::ExtraSlow => &EXTRASLOW,
            #[cfg(not(feature = "extraslow"))]
            Speed::ExtraSlow => &SLOW,
        }
    }
}

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

    #[test]
    fn slower_tiers_keep_every_faster_tool() {
        let tiers = [
            Speed::UltraFast,
            Speed::Fastest,
            Speed::Fast,
            Speed::Medium,
            Speed::MediumSlow,
            Speed::Slow,
            Speed::ExtraSlow,
        ];
        for pair in tiers.array_windows::<2>() {
            let (faster, slower) = (pair[0].effort().gates(), pair[1].effort().gates());
            for ((name, on), (_, slower_on)) in faster.into_iter().zip(slower) {
                assert!(
                    !on || slower_on,
                    "{name} on at {:?} but off at {:?}",
                    pair[0],
                    pair[1]
                );
            }
        }
    }
}