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
/*
 * // Copyright (c) Radzivon Bartoshyk 7/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::afv;
use crate::quant_weights::DequantMatrices;
use crate::thread_pool::ThreadPool;
use crate::{
    Speed, ac_strategy, adaptive_quant, color_correlation, dct, frame, group, inflated_cost, xyb,
};

#[inline]
fn channel_weights_for_bias(bias: f32, distance: f32) -> [f32; 3] {
    let matrix_mix = ((bias - xyb::B_BIAS) / (0.85 - xyb::B_BIAS)).clamp(0.0, 1.0);
    // The coarse yellow transform protects chroma by itself. Carrying the
    // fine-quality B error boost along with it mostly buys extra coefficients.
    // Mild yellow matrices (bias <= 0.70) retain their existing weights.
    let coarse = crate::yellow_opsin::coarse_weight_strength(distance)
        * ((bias - 0.70) / 0.15).clamp(0.0, 1.0);
    [
        0.30 + (0.10 - 0.30) * matrix_mix,
        1.0,
        0.28 + (0.83 - 0.28) * matrix_mix * (1.0 - coarse),
    ]
}

/// Per-encode dispatch table. The individual modules still own their `OnceLock`
/// selectors, but hot inner loops receive these already-resolved function
/// references instead of touching a static guard for every block / band / token.
pub(crate) struct EncodingContext {
    pub(crate) thread_pool: ThreadPool,
    pub(crate) speed: Speed,
    /// Lossy arm selection from the public config
    pub(crate) lossy_modular: crate::LossyModular,
    /// Experimental spline coding (see `EncodeConfig::splines`).
    #[cfg(feature = "splines")]
    pub(crate) splines: bool,
    #[cfg(feature = "splines")]
    pub(crate) spline_continuous_idct: crate::splines::ContinuousIdctFn,
    #[cfg(feature = "splines")]
    pub(crate) spline_render_row: crate::splines::RenderRowFn,
    #[cfg(feature = "splines")]
    pub(crate) spline_distance: crate::splines::SegmentDistanceFn,
    #[cfg(feature = "splines")]
    pub(crate) spline_ridge_row: crate::splines::RidgeRowFn,
    pub(crate) xyb: xyb::XybMatrix,
    /// Cached with the matrix, including a later adaptive yellow selection.
    channel_weights: [f32; 3],
    /// Transform-merge knobs resolved at this encodes distance.
    pub(crate) merge: ac_strategy::MergeTuning,
    /// Which AC-strategy selector runs (study switch, see [`ac_strategy::SelectorPolicy`]).
    pub(crate) selector: ac_strategy::SelectorPolicy,
    base_matrices: &'static DequantMatrices,
    sat_matrices: &'static DequantMatrices,
    pair_b_matrices: &'static DequantMatrices,
    sat_pair_b_matrices: &'static DequantMatrices,
    x_heavy_matrices: &'static DequantMatrices,
    /// Set once per frame (post-XYB, before any table use) by the
    /// chroma-saturation gate in `frame::encode_frame`.
    chroma_heavy: std::sync::atomic::AtomicBool,
    x_heavy: std::sync::atomic::AtomicBool,
    pair_b_fine: std::sync::atomic::AtomicBool,
    /// Blue-axis twin of `x_heavy`: structure lives in B−Y where luma-driven
    /// masking cannot see it (saturated blue detail on low-luma ground).
    b_heavy: std::sync::atomic::AtomicBool,
    b_qm_scale: std::sync::atomic::AtomicU32,
    /// Content floor for the signaled X quant scale (2 = none).
    x_qm_scale_floor: std::sync::atomic::AtomicU32,
    pub(crate) to_xyb_band: xyb::ToXybBandFn,
    pub(crate) fill_quant_field: adaptive_quant::FillQuantFieldFn,
    pub(crate) sse_and_rate: inflated_cost::SseAndRateFn,
    pub(crate) recon_dist_and_rate: inflated_cost::ReconDistAndRateFn,
    pub(crate) recon_error_kernels: inflated_cost::ReconErrorKernels,
    pub(crate) rate_log2_lut: &'static inflated_cost::RateLog2Lut,
    pub(crate) quantize_block_ac: group::QuantizeBlockAcFn,
    pub(crate) quantize_dc: group::QuantizeDcFn,
    pub(crate) quantize_dc_cfl: group::QuantizeDcCflFn,
    pub(crate) apply_cfl: ac_strategy::ApplyCflFn,
    pub(crate) mosaic_seam_stats: crate::mosaic_seam::MosaicSeamStatsFn,
    pub(crate) gradient_region_stats: ac_strategy::GradientRegionStatsFn,
    pub(crate) gradient_region_stats_with_chroma: ac_strategy::GradientRegionStatsFn,
    pub(crate) cfl_regression: color_correlation::CflRegressionFn,
    pub(crate) cfl_rdo_block: color_correlation::CflRdoBlockFn,
    pub(crate) cfl_rdo_stats: color_correlation::CflRdoStatsFn,
    pub(crate) cfl_closed_loop_cost: color_correlation::CflClosedLoopCostFn,
    pub(crate) chroma_gradient_sums: frame::ChromaGradientSumsFn,
    pub(crate) fill_ytob_row: color_correlation::FillYtobRowFn,
    pub(crate) accumulate_ytob_weights: color_correlation::AccumulateYtobWeightsFn,
    pub(crate) fill_ytob_residuals: color_correlation::FillYtobResidualsFn,

    pub(crate) idct: &'static dct::IdctMethods,
    pub(crate) identity8x8: &'static dct::DctFn<8, 8, 64>,
    pub(crate) dct2x2_8x8: &'static dct::DctFn<8, 8, 64>,
    pub(crate) dct8x8: &'static dct::DctFn<8, 8, 64>,
    pub(crate) dct8x16: &'static dct::DctFn<16, 8, 128>,
    pub(crate) dct16x8: &'static dct::DctFn<8, 16, 128>,
    pub(crate) dct16x16: &'static dct::DctFn<16, 16, 256>,
    pub(crate) dct4x4: &'static dct::DctFn<8, 8, 64>,
    pub(crate) dct4x8: &'static dct::DctFn<8, 8, 64>,
    pub(crate) dct8x4: &'static dct::DctFn<8, 8, 64>,
    pub(crate) dct32x32: &'static dct::DctFn<32, 32, 1024>,
    pub(crate) dct64x64: &'static dct::DctFn<64, 64, 4096>,
    pub(crate) dct64x32: &'static dct::DctFn<32, 64, 2048>,
    pub(crate) dct32x64: &'static dct::DctFn<64, 32, 2048>,
    pub(crate) dct32x16: &'static dct::DctFn<16, 32, 512>,
    pub(crate) dct16x32: &'static dct::DctFn<32, 16, 512>,
    pub(crate) dc_from_dct32x32: dct::DcFromDct32x32Fn,
    pub(crate) dc_from_dct32x16: dct::DcFromDct32x16Fn,
    pub(crate) dc_from_dct16x32: dct::DcFromDct16x32Fn,
    pub(crate) dc_from_dct64x64: dct::DcFromDct64x64Fn,
    pub(crate) dc_from_dct64x32: dct::DcFromDct64x32Fn,
    pub(crate) dc_from_dct32x64: dct::DcFromDct32x64Fn,
    pub(crate) afv0: afv::AfvFn,
    pub(crate) afv1: afv::AfvFn,
    pub(crate) afv2: afv::AfvFn,
    pub(crate) afv3: afv::AfvFn,
}

impl EncodingContext {
    /// The dequant tables for the current frame: the distance-tier default,
    /// the saturated-content variant when the chroma gate fired, or the
    /// X-gradient variant (it outranks the chroma gate: both fire on saturated
    /// red content, where flattened B bands are a strict RD loss).
    #[inline]
    pub(crate) fn matrices(&self) -> &'static DequantMatrices {
        use std::sync::atomic::Ordering::Relaxed;
        if self.x_heavy.load(Relaxed) {
            self.x_heavy_matrices
        } else {
            match (
                self.chroma_heavy.load(Relaxed),
                self.pair_b_fine.load(Relaxed),
            ) {
                (true, true) => self.sat_pair_b_matrices,
                (true, false) => self.sat_matrices,
                (false, true) => self.pair_b_matrices,
                (false, false) => self.base_matrices,
            }
        }
    }

    pub(crate) fn set_pair_b_fine(&self, fine: bool) {
        self.pair_b_fine
            .store(fine, std::sync::atomic::Ordering::Relaxed);
    }

    pub(crate) fn set_chroma_heavy(&self, heavy: bool) {
        self.chroma_heavy
            .store(heavy, std::sync::atomic::Ordering::Relaxed);
    }

    pub(crate) fn x_heavy(&self) -> bool {
        self.x_heavy.load(std::sync::atomic::Ordering::Relaxed)
    }

    pub(crate) fn set_x_heavy(&self, heavy: bool) {
        self.x_heavy
            .store(heavy, std::sync::atomic::Ordering::Relaxed);
    }

    pub(crate) fn b_heavy(&self) -> bool {
        self.b_heavy.load(std::sync::atomic::Ordering::Relaxed)
    }

    pub(crate) fn set_b_heavy(&self, heavy: bool) {
        self.b_heavy
            .store(heavy, std::sync::atomic::Ordering::Relaxed);
    }

    pub(crate) fn raise_x_qm_scale_floor(&self, scale: u32) {
        self.x_qm_scale_floor
            .fetch_max(scale.clamp(2, 7), std::sync::atomic::Ordering::Relaxed);
    }

    pub(crate) fn x_qm_scale_floor(&self) -> u32 {
        self.x_qm_scale_floor
            .load(std::sync::atomic::Ordering::Relaxed)
    }

    pub(crate) fn raise_b_qm_scale(&self, scale: u32) {
        self.b_qm_scale
            .fetch_max(scale.clamp(2, 7), std::sync::atomic::Ordering::Relaxed);
    }

    pub(crate) fn b_qm_scale(&self) -> u32 {
        self.b_qm_scale.load(std::sync::atomic::Ordering::Relaxed)
    }

    #[inline]
    pub(crate) fn b_qm_mul(&self) -> f32 {
        // The signaled scale is an integer in 2..=7. All powers below are
        // exact binary fractions, so a lookup avoids a libm `powf` in the
        // block-level RDO paths without changing the quantizer value.
        static MULTIPLIERS: [f32; 6] = [1.0, 1.25, 1.5625, 1.953125, 2.441_406_2, 3.051_757_8];
        MULTIPLIERS[(self.b_qm_scale().clamp(2, 7) - 2) as usize]
    }

    /// Update the adaptive matrix and its cached reconstruction weights together.
    #[inline]
    pub(crate) fn set_xyb_matrix(
        &mut self,
        matrix: xyb::XybMatrix,
        distance: f32,
        default_weights: bool,
    ) {
        self.xyb = matrix;
        let weight_bias = if default_weights {
            xyb::B_BIAS
        } else {
            matrix.fwd[8]
        };
        self.channel_weights = channel_weights_for_bias(weight_bias, distance);
    }

    #[inline]
    pub(crate) fn channel_weights(&self) -> [f32; 3] {
        self.channel_weights
    }

    #[inline]
    pub(crate) fn channel_weight(&self, channel: usize) -> f32 {
        self.channel_weights()[channel]
    }

    pub(crate) fn new(
        speed: Speed,
        xyb: xyb::XybMatrix,
        distance: f32,
        num_threads: usize,
    ) -> Self {
        let quantize_dc = group::selected_quantize_dc_methods();
        let dc_from_dct = dct::selected_dc_from_dct_methods();
        let afv = afv::selected_afv_methods();
        let base_matrices = if speed == Speed::Slow {
            DequantMatrices::new(distance)
        } else {
            DequantMatrices::new_fast(distance)
        };
        Self {
            thread_pool: ThreadPool::new(num_threads),
            speed,
            lossy_modular: crate::LossyModular::Off,
            #[cfg(feature = "splines")]
            splines: false,
            xyb,
            channel_weights: channel_weights_for_bias(xyb.fwd[8], distance),
            merge: ac_strategy::MergeTuning::new(distance),
            selector: ac_strategy::SelectorPolicy::default(),
            base_matrices,
            sat_matrices: DequantMatrices::new_saturated(distance),
            pair_b_matrices: if speed == Speed::Slow {
                DequantMatrices::new_pair_b(distance)
            } else {
                base_matrices
            },
            sat_pair_b_matrices: DequantMatrices::new_saturated_pair_b(distance),
            x_heavy_matrices: if speed == Speed::Slow {
                DequantMatrices::new_x_heavy(distance)
            } else {
                DequantMatrices::new(0.0)
            },
            chroma_heavy: std::sync::atomic::AtomicBool::new(false),
            x_heavy: std::sync::atomic::AtomicBool::new(false),
            pair_b_fine: std::sync::atomic::AtomicBool::new(false),
            b_heavy: std::sync::atomic::AtomicBool::new(false),
            b_qm_scale: std::sync::atomic::AtomicU32::new(2),
            x_qm_scale_floor: std::sync::atomic::AtomicU32::new(2),
            #[cfg(feature = "splines")]
            spline_continuous_idct: crate::splines::select_continuous_idct_fn(),
            #[cfg(feature = "splines")]
            spline_render_row: crate::splines::select_render_row_fn(),
            #[cfg(feature = "splines")]
            spline_distance: crate::splines::select_segment_distance_fn(),
            #[cfg(feature = "splines")]
            spline_ridge_row: crate::splines::select_ridge_row_fn(),
            to_xyb_band: xyb::selected_to_xyb_band_fn(),
            fill_quant_field: adaptive_quant::selected_fill_quant_field_fn(),
            sse_and_rate: inflated_cost::selected_sse_and_rate_fn(),
            recon_dist_and_rate: inflated_cost::select_recon_dist_and_rate_fn(),
            recon_error_kernels: inflated_cost::ReconErrorKernels {
                gradient_energy: inflated_cost::select_error_gradient_energy_fn(),
                gradient_peak_energy: inflated_cost::select_error_gradient_peak_energy_fn(),
                combine: inflated_cost::select_combine_error_fn(),
                rgb_hue_chroma_edge_loss: inflated_cost::select_rgb_hue_chroma_edge_loss_fn(),
            },
            rate_log2_lut: inflated_cost::rate_log2_lut(),
            quantize_block_ac: group::selected_quantize_block_ac_fn(),
            quantize_dc: quantize_dc.quantize,
            quantize_dc_cfl: quantize_dc.quantize_cfl,
            apply_cfl: ac_strategy::selected_apply_cfl_fn(),
            mosaic_seam_stats: crate::mosaic_seam::select_mosaic_seam_stats_fn(),
            gradient_region_stats: ac_strategy::select_gradient_region_stats_fn(),
            gradient_region_stats_with_chroma:
                ac_strategy::select_gradient_region_stats_with_chroma_fn(),
            cfl_regression: color_correlation::selected_cfl_regression_fn(),
            cfl_rdo_block: color_correlation::selected_cfl_rdo_block_fn(),
            cfl_rdo_stats: color_correlation::selected_cfl_rdo_stats_fn(),
            cfl_closed_loop_cost: color_correlation::selected_cfl_closed_loop_cost_fn(),
            chroma_gradient_sums: frame::selected_chroma_gradient_sums_fn(),
            fill_ytob_row: color_correlation::selected_fill_ytob_row_fn(),
            accumulate_ytob_weights: color_correlation::selected_accumulate_ytob_weights_fn(),
            fill_ytob_residuals: color_correlation::selected_fill_ytob_residuals_fn(),

            idct: dct::selected_idct_methods(),
            identity8x8: dct::selected_identity8x8(),
            dct2x2_8x8: dct::selected_dct2x2_8x8(),
            dct8x8: dct::selected_dct8x8(),
            dct8x16: dct::selected_dct8x16(),
            dct16x8: dct::selected_dct16x8(),
            dct16x16: dct::selected_dct16x16(),
            dct4x4: dct::selected_dct4x4(),
            dct4x8: dct::selected_dct4x8(),
            dct8x4: dct::selected_dct8x4(),
            dct32x32: dct::selected_dct32x32(),
            dct64x64: dct::selected_dct64x64(),
            dct64x32: dct::selected_dct64x32(),
            dct32x64: dct::selected_dct32x64(),
            dct32x16: dct::selected_dct32x16(),
            dct16x32: dct::selected_dct16x32(),
            dc_from_dct32x32: dc_from_dct.dct32x32,
            dc_from_dct32x16: dc_from_dct.dct32x16,
            dc_from_dct16x32: dc_from_dct.dct16x32,
            dc_from_dct64x64: dc_from_dct.dct64x64,
            dc_from_dct64x32: dc_from_dct.dct64x32,
            dc_from_dct32x64: dc_from_dct.dct32x64,
            afv0: afv.afv0,
            afv1: afv.afv1,
            afv2: afv.afv2,
            afv3: afv.afv3,
        }
    }
}

impl Default for EncodingContext {
    #[inline]
    fn default() -> Self {
        Self::new(Speed::Fast, xyb::XybMatrix::SPEC, 1.0, 1)
    }
}

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

    #[test]
    fn hue_tables_require_the_frame_content_gate() {
        use super::{DequantMatrices, EncodingContext, Speed, xyb};
        let ctx = EncodingContext::new(Speed::Slow, xyb::XybMatrix::SPEC, 1.0, 1);
        assert!(std::ptr::eq(ctx.matrices(), DequantMatrices::new(1.0)));
        ctx.set_chroma_heavy(true);
        assert!(std::ptr::eq(
            ctx.matrices(),
            DequantMatrices::new_saturated(1.0)
        ));
        ctx.set_x_heavy(true);
        assert!(std::ptr::eq(
            ctx.matrices(),
            DequantMatrices::new_x_heavy(1.0)
        ));
        ctx.set_x_heavy(false);
        assert!(std::ptr::eq(
            ctx.matrices(),
            DequantMatrices::new_saturated(1.0)
        ));
    }

    #[test]
    fn channel_weights_follow_the_opsin_b_row() {
        assert_eq!(
            channel_weights_for_bias(crate::xyb::B_BIAS, 1.0),
            [0.30, 1.0, 0.28]
        );
        let strong = channel_weights_for_bias(0.85, 1.0);
        assert!((strong[0] - 0.10).abs() < 1e-6);
        assert_eq!(strong[1], 1.0);
        assert!((strong[2] - 0.83).abs() < 1e-6);

        let mid = channel_weights_for_bias((crate::xyb::B_BIAS + 0.85) * 0.5, 1.0);
        assert!((mid[0] - 0.20).abs() < 1e-6);
        assert!((mid[2] - 0.555).abs() < 1e-6);
    }

    #[test]
    fn adaptive_matrix_updates_cached_coarse_weights() {
        use super::{EncodingContext, Speed, xyb};
        let mut ctx = EncodingContext::new(Speed::Slow, xyb::XybMatrix::SPEC, 2.0, 1);
        assert_eq!(ctx.channel_weights(), [0.30, 1.0, 0.28]);
        let matrix = crate::yellow_opsin::matrix_for_bias(0.90);
        ctx.set_xyb_matrix(matrix, 2.0, false);
        assert_eq!(ctx.xyb, matrix);
        let coarse = ctx.channel_weights();
        assert!((coarse[0] - 0.10).abs() < 1e-6);
        assert_eq!(coarse[1], 1.0);
        assert_eq!(coarse[2], 0.28);
        // The smooth-yellow tier and the successful d1 path keep their boost.
        assert_eq!(
            channel_weights_for_bias(0.70, 2.0),
            channel_weights_for_bias(0.70, 1.0)
        );
        ctx.set_xyb_matrix(crate::yellow_opsin::matrix_for_bias(0.85), 1.0, false);
        assert_eq!(ctx.channel_weights(), channel_weights_for_bias(0.85, 1.0));
        // The sparse-yellow fallback signals its matrix but uses the default
        // error budget, even after a previous matrix had stronger weights.
        let mild = crate::yellow_opsin::matrix_for_bias(0.65);
        ctx.set_xyb_matrix(mild, 2.0, true);
        assert_eq!(ctx.xyb, mild);
        assert_eq!(ctx.channel_weights(), [0.30, 1.0, 0.28]);
    }
}