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
/*
* // 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.
*/
//! SSIMULACRA 2 of XYB images for the closed loop, on the `ssimu2-lite`
//! crate: the source is analysed once, candidates are scored in full or by
//! region-incremental updates in linear RGB.
use crate::image::Image3F;
use ssimu2_lite::{IncrementalState, PreparedReference, RgbImage};
pub(crate) use ssimu2_lite::{Checkpoint as Ssimulacra2Checkpoint, Rect};
/// Linear RGB planes of an XYB image (the encoder's inverse opsin transform).
pub(crate) fn linear_of_xyb(img: &Image3F) -> [Vec<f32>; 3] {
let (w, h) = (img.xsize(), img.ysize());
let mut out = [vec![0f32; w * h], vec![0f32; w * h], vec![0f32; w * h]];
let [r, g, b] = &mut out;
for y in 0..h {
let span = y * w..(y + 1) * w;
crate::xyb::xyb_to_rgb_rows(
&crate::xyb::XybMatrix::SPEC,
[
img.plane_row(0, y),
img.plane_row(1, y),
img.plane_row(2, y),
],
[&mut r[span.clone()], &mut g[span.clone()], &mut b[span]],
);
}
out
}
fn planes(linear: &[Vec<f32>; 3], w: usize, h: usize) -> RgbImage<'_> {
RgbImage::linear_rgb([&linear[0], &linear[1], &linear[2]], w, h, w)
.expect("frame-sized linear planes")
}
/// The source frame, analyzed once.
pub(crate) struct Ssimulacra2Reference {
prepared: PreparedReference,
width: usize,
height: usize,
}
impl Ssimulacra2Reference {
/// `None` below the metric's 8x8 minimum.
pub(crate) fn new(source: &Image3F) -> Option<Self> {
let (width, height) = (source.xsize(), source.ysize());
let linear = linear_of_xyb(source);
let prepared = PreparedReference::new(planes(&linear, width, height)).ok()?;
Some(Self {
prepared,
width,
height,
})
}
/// `100 - SSIMULACRA2` of `recon` and the per-pixel map whose mean is
/// the (linearized) deficit. A non-finite reconstruction scores NaN.
pub(crate) fn deficit_and_map(&self, recon: &Image3F) -> (f32, Vec<f32>) {
let linear = linear_of_xyb(recon);
match self
.prepared
.compare_with_map(planes(&linear, self.width, self.height))
{
Ok((score, map)) => ((100.0 - score) as f32, map),
Err(_) => (f32::NAN, vec![0.0; self.width * self.height]),
}
}
/// The identical pooled score when no per-pixel map is consumed.
pub(crate) fn deficit(&self, recon: &Image3F) -> f32 {
let linear = linear_of_xyb(recon);
self.prepared
.compare(planes(&linear, self.width, self.height))
.map_or(f32::NAN, |score| (100.0 - score) as f32)
}
/// Incremental state following `recon`.
pub(crate) fn state(&self, recon: &Image3F) -> Ssimulacra2State {
let linear = linear_of_xyb(recon);
let state = self
.prepared
.incremental(planes(&linear, self.width, self.height))
.expect("finite reconstruction");
Ssimulacra2State {
state,
linear,
width: self.width,
height: self.height,
}
}
}
/// Incremental SSIMULACRA 2 of a fixed source against a mutable reconstruction.
pub(crate) struct Ssimulacra2State {
state: IncrementalState,
/// Linear RGB staging of the reconstruction; an update converts and reads
/// only its rect, so rolled-back pixels elsewhere are never read.
linear: [Vec<f32>; 3],
width: usize,
height: usize,
}
impl Ssimulacra2State {
/// `100 - score`.
pub(crate) fn deficit(&self) -> f32 {
(100.0 - self.state.score()) as f32
}
/// The reconstruction changed inside `r`: refresh, saving what changes
/// into `cp` for `rollback`.
pub(crate) fn update_checkpointed(
&mut self,
recon: &Image3F,
r: Rect,
cp: &mut Ssimulacra2Checkpoint,
) {
let (w, h) = (self.width, self.height);
let r = Rect::new(r.x0, r.y0, r.x1.min(w), r.y1.min(h));
if r.x1 <= r.x0 || r.y1 <= r.y0 {
return;
}
let [lr, lg, lb] = &mut self.linear;
for y in r.y0..r.y1 {
let span = y * w + r.x0..y * w + r.x1;
crate::xyb::xyb_to_rgb_rows(
&crate::xyb::XybMatrix::SPEC,
[
&recon.plane_row(0, y)[r.x0..r.x1],
&recon.plane_row(1, y)[r.x0..r.x1],
&recon.plane_row(2, y)[r.x0..r.x1],
],
[&mut lr[span.clone()], &mut lg[span.clone()], &mut lb[span]],
);
}
let result = self
.state
.update_checkpointed(planes(&self.linear, w, h), r, cp);
debug_assert!(result.is_ok(), "non-finite reconstruction");
}
/// Undo the `update_checkpointed` that filled `cp`.
pub(crate) fn rollback(&mut self, cp: &Ssimulacra2Checkpoint) {
self.state.rollback(cp);
}
/// Per-pixel linearized map (mean = deficit).
pub(crate) fn map(&self) -> Vec<f32> {
self.state.error_map()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn textured(seed: u32, w: usize, h: usize) -> Image3F {
let mut img = Image3F::new(w, h);
let mut rng = seed;
for c in 0..3 {
for y in 0..h {
for x in 0..w {
rng = rng.wrapping_mul(1664525).wrapping_add(1013904223);
let noise = (rng >> 24) as f32 / 255.0;
let base = if c == 1 { 0.3 } else { 0.0 };
img.plane_row_mut(c, y)[x] = base
+ 0.3 * ((x / 8 + y / 8) % 2) as f32 * (if c == 1 { 1.0 } else { 0.1 })
+ 0.05 * noise;
}
}
}
img
}
#[test]
fn score_only_preserves_the_map_scores_exact_bits() {
for (w, h) in [(8, 8), (9, 17), (161, 97)] {
let source = textured(7, w, h);
let reference = Ssimulacra2Reference::new(&source).unwrap();
for seed in [7, 8, 19] {
let recon = textured(seed, w, h);
assert_eq!(
reference.deficit(&recon).to_bits(),
reference.deficit_and_map(&recon).0.to_bits(),
"{w}x{h}, seed={seed}",
);
}
}
}
#[test]
fn incremental_updates_and_rollback_track_full_scores() {
let (w, h) = (161, 97);
let src = textured(7, w, h);
let mut rec = textured(8, w, h);
let reference = Ssimulacra2Reference::new(&src).unwrap();
let mut state = reference.state(&rec);
let (d0, map0) = reference.deficit_and_map(&rec);
assert!((state.deficit() - d0).abs() < 1e-3);
assert!(
map0.iter()
.zip(state.map())
.all(|(a, b)| (a - b).abs() < 1e-3)
);
let r = Rect::new(40, 30, 90, 70);
for y in r.y0..r.y1 {
for v in &mut rec.plane_row_mut(1, y)[r.x0..r.x1] {
*v += 0.02;
}
}
let mut cp = Ssimulacra2Checkpoint::default();
state.update_checkpointed(&rec, r, &mut cp);
let (d1, _) = reference.deficit_and_map(&rec);
assert!(
(state.deficit() - d1).abs() < 1e-3,
"{} vs {d1}",
state.deficit()
);
assert!(d1 > d0);
state.rollback(&cp);
assert!((state.deficit() - d0).abs() < 1e-6);
}
#[test]
fn identical_frames_have_no_deficit() {
let src = textured(3, 64, 48);
let reference = Ssimulacra2Reference::new(&src).unwrap();
let (d, map) = reference.deficit_and_map(&src);
assert!(d.abs() < 1e-4 && map.iter().all(|v| v.abs() < 1e-6));
assert!(Ssimulacra2Reference::new(&textured(3, 7, 48)).is_none());
}
}