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
/*
 * // 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.
 */

//! ColorVideoVDP arbiter of the closed loop under [`crate::Arbiter::Cvvdp`].
//! The loop's reconstruction carries only the AC quantization error: the
//! lowest frequencies ride on the DC path. Callers supply each 8x8 cell's DC
//! error (decoded minus unrounded DC image value), added before scoring. A
//! block mean is not that value for merged transforms, whose DC image holds
//! their lowest frequencies' transform instead. Whole-frame
//! arms are scored in full; per-candidate moves update an incremental state
//! that follows the accepted frame.

use crate::image::Image3F;
use crate::ssimulacra2::Rect;
use cvvdp_lite::{CvvdpLite, Display, IncrementalState, PreparedReference, RgbImage, Workspace};

/// A 500 nit laptop panel: bright enough that dark-region color errors stay
/// visible, unlike the 200 nit standard displays.
fn display() -> Display {
    Display::macbook_pro_16()
}

/// What a candidate update overwrote.
#[derive(Default)]
pub(crate) struct CvvdpCheckpoint {
    rect: Option<Rect>,
    linear: Vec<f32>,
    state: cvvdp_lite::Checkpoint,
}

pub(crate) struct CvvdpArbiter {
    reference: std::sync::Arc<PreparedReference>,
    workspace: Workspace,
    /// Incremental state of the accepted frame, once `reset`.
    state: Option<IncrementalState>,
    /// Linear RGB of the accepted frame (DC included).
    linear: [Vec<f32>; 3],
    /// DC-adjusted XYB row scratch, reused by full and regional conversions.
    rows: [Vec<f32>; 3],
    width: usize,
    height: usize,
}

impl CvvdpArbiter {
    /// The analysed source, shareable between arbiters of the same frame.
    pub(crate) fn prepare(source: &Image3F) -> Option<std::sync::Arc<PreparedReference>> {
        let (width, height) = (source.xsize(), source.ysize());
        let linear = crate::ssimulacra2::linear_of_xyb(source);
        let planes = [&linear[0][..], &linear[1][..], &linear[2][..]];
        let metric = CvvdpLite::new(display()).ok()?;
        let image = RgbImage::linear_rgb(planes, width, height, width).ok()?;
        // Reference preparation reserves its analysis buffers itself; full-frame
        // comparison masks and blur scratch are unused here.
        Some(std::sync::Arc::new(metric.prepare_reference(image).ok()?))
    }

    pub(crate) fn new(source: &Image3F) -> Option<Self> {
        Self::new_shared(source, Self::prepare(source)?)
    }

    /// Keep the prepared source while releasing the comparison workspace.
    pub(crate) fn into_reference(self) -> std::sync::Arc<PreparedReference> {
        self.reference
    }

    /// An arbiter over an already analysed source.
    pub(crate) fn new_shared(
        source: &Image3F,
        reference: std::sync::Arc<PreparedReference>,
    ) -> Option<Self> {
        let (width, height) = (source.xsize(), source.ysize());
        // Incremental scoring owns its scratch. Full-frame comparisons grow
        // this workspace lazily, so polishing workers retain no unused pyramid.
        let workspace = Workspace::new();
        Some(Self {
            reference,
            workspace,
            state: None,
            linear: Default::default(),
            rows: Default::default(),
            width,
            height,
        })
    }

    /// Linear RGB of `recon` plus every block's DC error `dc_error`, written
    /// into `out` (frame-sized planes) over `r`.
    fn write_linear(
        &mut self,
        recon: &Image3F,
        (ox, oy): (usize, usize),
        dc_error: &Image3F,
        r: Rect,
        out: &mut [Vec<f32>; 3],
    ) {
        let w = self.width;
        let n = r.x1 - r.x0;
        let rows = &mut self.rows;
        for row in rows.iter_mut() {
            row.resize(n, 0.0);
        }
        let [r_out, g_out, b_out] = out;
        let xs = r.x0 - ox..r.x1 - ox;
        for y in r.y0..r.y1 {
            for (c, row) in rows.iter_mut().enumerate() {
                let err = dc_error.plane_row(c, y / 8);
                let src = &recon.plane_row(c, y - oy)[xs.clone()];
                for ((v, &s), x) in row.iter_mut().zip(src).zip(r.x0..) {
                    *v = s + err[x / 8];
                }
            }
            let span = y * w + r.x0..y * w + r.x1;
            crate::xyb::xyb_to_rgb_rows(
                &crate::xyb::XybMatrix::SPEC,
                [&rows[0][..], &rows[1][..], &rows[2][..]],
                [
                    &mut r_out[span.clone()],
                    &mut g_out[span.clone()],
                    &mut b_out[span],
                ],
            );
        }
    }

    fn full(&self) -> Rect {
        Rect {
            x0: 0,
            y0: 0,
            x1: self.width,
            y1: self.height,
        }
    }

    fn image<'a>(&self, linear: &'a [Vec<f32>; 3]) -> RgbImage<'a> {
        let planes = [&linear[0][..], &linear[1][..], &linear[2][..]];
        RgbImage::linear_rgb(planes, self.width, self.height, self.width).expect("decoded planes")
    }

    /// Pooled distortion (smaller is better) of `recon` with `dc_error`,
    /// independent of the accepted frame.
    pub(crate) fn deficit_of(&mut self, recon: &Image3F, dc_error: &Image3F) -> f32 {
        let (w, h) = (self.width, self.height);
        let mut linear = [vec![0f32; w * h], vec![0f32; w * h], vec![0f32; w * h]];
        self.write_linear(recon, (0, 0), dc_error, self.full(), &mut linear);
        let image = self.image(&linear);
        self.workspace
            .compare(&self.reference, image)
            .expect("prepared reference")
            .distortion as f32
    }

    /// Full-frame trials only need the reference and comparison workspace.
    /// Release the accepted frame's incremental pyramid and RGB staging once
    /// the last regional update has finished.
    pub(crate) fn finish_updates(&mut self) {
        self.state = None;
        self.linear = Default::default();
    }

    /// Make `recon` with `dc_error` the accepted frame that updates follow.
    pub(crate) fn reset(&mut self, recon: &Image3F, dc_error: &Image3F) {
        let mut linear = std::mem::take(&mut self.linear);
        for plane in &mut linear {
            plane.resize(self.width * self.height, 0.0);
        }
        self.write_linear(recon, (0, 0), dc_error, self.full(), &mut linear);
        self.linear = linear;
        let image = self.image(&self.linear);
        self.state =
            Some(IncrementalState::new(&self.reference, image).expect("prepared reference"));
    }

    /// Pooled distortion of the accepted frame.
    pub(crate) fn deficit(&self) -> f32 {
        self.state.as_ref().expect("reset").score().distortion as f32
    }

    /// Commit a reconstruction change without saving rollback data.
    /// `origin` locates the supplied reconstruction in frame coordinates.
    /// Linear RGB outside `r` remains available for aligned metric reads.
    pub(crate) fn update_region(
        &mut self,
        recon: &Image3F,
        origin: (usize, usize),
        dc_error: &Image3F,
        r: Rect,
    ) -> f32 {
        let mut linear = std::mem::take(&mut self.linear);
        self.write_linear(recon, origin, dc_error, r, &mut linear);
        self.linear = linear;
        let image = self.image(&self.linear);
        let rect = cvvdp_lite::Rect::new(r.x0, r.y0, r.x1, r.y1);
        self.state
            .as_mut()
            .expect("reset")
            .update(&self.reference, image, rect)
            .expect("prepared reference")
            .distortion as f32
    }

    /// Score the accepted frame with `recon` (and `dc_error`) inside `r`,
    /// keeping it until `rollback(cp)`.
    pub(crate) fn update_checkpointed(
        &mut self,
        recon: &Image3F,
        dc_error: &Image3F,
        r: Rect,
        cp: &mut CvvdpCheckpoint,
    ) -> f32 {
        self.update_region_checkpointed(recon, (0, 0), dc_error, r, cp)
    }

    pub(crate) fn update_region_checkpointed(
        &mut self,
        recon: &Image3F,
        origin: (usize, usize),
        dc_error: &Image3F,
        r: Rect,
        cp: &mut CvvdpCheckpoint,
    ) -> f32 {
        let w = self.width;
        cp.rect = Some(r);
        cp.linear.clear();
        for plane in &self.linear {
            for y in r.y0..r.y1 {
                cp.linear
                    .extend_from_slice(&plane[y * w + r.x0..y * w + r.x1]);
            }
        }
        let mut linear = std::mem::take(&mut self.linear);
        self.write_linear(recon, origin, dc_error, r, &mut linear);
        self.linear = linear;
        let image = self.image(&self.linear);
        let rect = cvvdp_lite::Rect::new(r.x0, r.y0, r.x1, r.y1);
        self.state
            .as_mut()
            .expect("reset")
            .update_checkpointed(&self.reference, image, rect, &mut cp.state)
            .expect("prepared reference")
            .distortion as f32
    }

    /// Undo the `update_checkpointed` that filled `cp`.
    pub(crate) fn rollback(&mut self, cp: &CvvdpCheckpoint) {
        let Some(r) = cp.rect else {
            return;
        };
        let w = self.width;
        let n = r.x1 - r.x0;
        let mut at = 0;
        for plane in &mut self.linear {
            for y in r.y0..r.y1 {
                plane[y * w + r.x0..y * w + r.x1].copy_from_slice(&cp.linear[at..at + n]);
                at += n;
            }
        }
        self.state.as_mut().expect("reset").rollback(&cp.state);
    }
}

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

    #[test]
    fn committed_updates_preserve_scores_rollbacks_and_row_allocations() {
        let (w, h) = (65, 49);
        let mut source = Image3F::new(w, h);
        for c in 0..3 {
            for y in 0..h {
                for x in 0..w {
                    source.plane_row_mut(c, y)[x] = if c == 1 { 0.4 } else { 0.0 }
                        + ((x * 173 + y * 311 + c * 71) % 997) as f32 / 20000.0;
                }
            }
        }
        let reference = CvvdpArbiter::prepare(&source).unwrap();
        let mut committed = CvvdpArbiter::new_shared(&source, reference.clone()).unwrap();
        let mut checkpointed = CvvdpArbiter::new_shared(&source, reference).unwrap();
        let mut dc = Image3F::new(w.div_ceil(8), h.div_ceil(8));
        let mut recon = source.clone();
        committed.reset(&recon, &dc);
        checkpointed.reset(&recon, &dc);
        let allocations: [_; 3] =
            std::array::from_fn(|c| (committed.rows[c].as_ptr(), committed.rows[c].capacity()));
        let mut cp = CvvdpCheckpoint::default();
        let mut trial_cp = CvvdpCheckpoint::default();
        let crop = |image: &Image3F, r: Rect| {
            let mut out = Image3F::new(r.x1 - r.x0, r.y1 - r.y0);
            for c in 0..3 {
                for y in r.y0..r.y1 {
                    out.plane_row_mut(c, y - r.y0)
                        .copy_from_slice(&image.plane_row(c, y)[r.x0..r.x1]);
                }
            }
            out
        };
        for r in [
            Rect::new(7, 9, 24, 31),
            Rect::new(64, 48, 65, 49),
            Rect::new(0, 0, w, h),
            Rect::new(16, 8, 48, 32),
        ] {
            // Exercise DC correction as well as reconstruction changes.
            dc.plane_row_mut(0, r.y0 / 8)[r.x0 / 8] += 0.0003;
            for c in 0..3 {
                for y in r.y0..r.y1 {
                    for v in &mut recon.plane_row_mut(c, y)[r.x0..r.x1] {
                        *v += (c + 1) as f32 * 0.0007;
                    }
                }
            }
            let base = committed.update_region(&recon, (0, 0), &dc, r).to_bits();
            assert_eq!(
                base,
                checkpointed
                    .update_region_checkpointed(&crop(&recon, r), (r.x0, r.y0), &dc, r, &mut cp)
                    .to_bits()
            );
            assert_eq!(committed.linear, checkpointed.linear);
            for (row, &(ptr, capacity)) in committed.rows.iter().zip(&allocations) {
                assert_eq!(row.as_ptr(), ptr);
                assert_eq!(row.capacity(), capacity);
            }

            let mut trial = recon.clone();
            trial.plane_row_mut(1, 17)[23] += 0.003;
            let rect = Rect::new(23, 17, 24, 18);
            let a = committed.update_checkpointed(&trial, &dc, rect, &mut trial_cp);
            let b = checkpointed.update_region_checkpointed(
                &crop(&trial, rect),
                (rect.x0, rect.y0),
                &dc,
                rect,
                &mut cp,
            );
            assert_eq!(a.to_bits(), b.to_bits());
            committed.rollback(&trial_cp);
            checkpointed.rollback(&cp);
            assert_eq!(committed.deficit().to_bits(), base);
            assert_eq!(checkpointed.deficit().to_bits(), base);
            assert_eq!(committed.linear, checkpointed.linear);
        }
    }

    #[test]
    fn full_frame_scores_survive_releasing_incremental_storage() {
        let mut source = Image3F::new(65, 49);
        for c in 0..3 {
            for y in 0..source.ysize() {
                for x in 0..source.xsize() {
                    source.plane_row_mut(c, y)[x] = if c == 1 { 0.4 } else { 0.0 }
                        + ((x * 173 + y * 311 + c * 71) % 997) as f32 / 20000.0;
                }
            }
        }
        let mut judge = CvvdpArbiter::new(&source).unwrap();
        // An incremental-only judge must not reserve full-frame comparison scratch.
        assert_eq!(
            judge.workspace.allocated_bytes(),
            Workspace::new().allocated_bytes()
        );
        assert!(judge.linear.iter().all(|plane| plane.capacity() == 0));
        let dc = Image3F::new(judge.width.div_ceil(8), judge.height.div_ceil(8));
        judge.reset(&source, &dc);
        assert_eq!(
            judge.workspace.allocated_bytes(),
            Workspace::new().allocated_bytes()
        );
        let mut recon = source.clone();
        for v in recon.plane_mut(1).as_mut_slice() {
            *v += 0.01;
        }
        let before = judge.deficit_of(&recon, &dc);
        judge.finish_updates();
        let after = judge.deficit_of(&recon, &dc);
        assert!(before.is_finite());
        assert_eq!(after.to_bits(), before.to_bits());
        assert!(judge.state.is_none());
        assert!(judge.linear.iter().all(|plane| plane.capacity() == 0));
        judge.reset(&recon, &dc);
        assert!((judge.deficit() - after).abs() < 1e-5);
    }
}