av-denoise 0.3.1

Fast and efficient video denoising using accelerated nlmeans.
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
use super::helpers::*;
use crate::nlmeans::*;

/// Shared baseline for the fast path. Each test overrides just the
/// field it's exercising via struct-update syntax.
fn base_params() -> NlmParams {
    NlmParams {
        temporal_radius: 0,
        search_radius: 2,
        patch_radius: 2,
        strength: 1.2,
        self_weight: 1.0,
        channels: ChannelMode::Luma,
        prefilter: PrefilterMode::None,
        motion_compensation: MotionCompensationMode::None,
        hq: None,
    }
}

/// With both HQ features off, `effective_strength` and `noise_offset`
/// degenerate to exactly what the fast path already computes, so the
/// two denoisers must agree bit-for-bit.
#[test]
fn hq_disabled_features_match_fast_mode() {
    let client = make_client();
    let w = 16;
    let h = 16;
    let frame = make_frame_with_noisy_region(w, h, 1, 0.5, 8, 8, 3, 0.9);

    let mut fast = NlmDenoiser::<R>::new(&client, base_params(), w, h);
    fast.push_frame(&frame);
    let fast_out = fast.denoise().unwrap().unwrap().to_vec();

    let hq_params = NlmParams {
        hq: Some(HqParams {
            auto_strength: false,
            noise_floor: false,
            sigma_override: Some(8.0 / 255.0),
            temporal_confidence: true,
            thsad_scale: 1.0,
            sigma_scale: 1.0,
        }),
        ..base_params()
    };
    let mut hq = NlmDenoiser::<R>::new(&client, hq_params, w, h);
    hq.push_frame(&frame);
    let hq_out = hq.denoise().unwrap().unwrap().to_vec();

    assert_eq!(
        fast_out, hq_out,
        "disabled HQ features should reproduce the fast path exactly"
    );
}

/// Turning on the noise floor shifts every patch distance by a
/// nonzero offset. Neighbours whose distance falls below that offset
/// get clamped to full weight instead of the fast path's decayed
/// weight. That changes their contribution to the weighted average
/// relative to neighbours that stay above the offset, so the two
/// outputs must differ somewhere while staying finite and in range.
///
/// `sigma` here is set well above the CLI's "heavy noise" guidance.
/// The synthetic frame is a solid block edge rather than real
/// per-pixel noise, so patch distances only take a few discrete
/// values, either zero or a multiple of one mismatched tap's
/// contribution, instead of the small continuum real sensor noise
/// would produce. A small, realistic sigma would sit below every
/// nonzero distance and never clamp anything. The larger sigma exists
/// purely to land the offset between two of those discrete steps.
#[test]
fn hq_noise_floor_changes_output() {
    let client = make_client();
    let w = 16;
    let h = 16;
    let frame = make_frame_with_noisy_region(w, h, 1, 0.5, 8, 8, 3, 0.9);

    let mut fast = NlmDenoiser::<R>::new(&client, base_params(), w, h);
    fast.push_frame(&frame);
    let fast_out = fast.denoise().unwrap().unwrap().to_vec();

    let hq_params = NlmParams {
        hq: Some(HqParams {
            auto_strength: false,
            noise_floor: true,
            sigma_override: Some(40.0 / 255.0),
            temporal_confidence: true,
            thsad_scale: 1.0,
            sigma_scale: 1.0,
        }),
        ..base_params()
    };
    let mut hq = NlmDenoiser::<R>::new(&client, hq_params, w, h);
    hq.push_frame(&frame);
    let hq_out = hq.denoise().unwrap().unwrap().to_vec();

    let mut max_diff = 0.0f32;
    for (i, (&f, &q)) in fast_out.iter().zip(hq_out.iter()).enumerate() {
        assert!(q.is_finite(), "pixel {i}: non-finite HQ output {q}");
        assert!((0.0..=1.0).contains(&q), "pixel {i}: out-of-range HQ output {q}");
        max_diff = max_diff.max((f - q).abs());
    }

    assert!(
        max_diff > 1e-3,
        "expected the noise floor to change the output somewhere, max diff was {max_diff}"
    );
}

/// Mirrors `spatial::uniform_image_passthrough`: every patch distance
/// is zero on a flat frame, so both HQ features are no-ops and the
/// output must stay unchanged.
#[test]
fn hq_uniform_input_passthrough() {
    let client = make_client();
    let w = 16;
    let h = 16;
    let frame = make_uniform_frame(w, h, 1, 0.5);

    let params = NlmParams {
        hq: Some(HqParams::with_sigma(8.0 / 255.0)),
        ..base_params()
    };

    let mut denoiser = NlmDenoiser::<R>::new(&client, params, w, h);
    denoiser.push_frame(&frame);
    let result = denoiser.denoise().unwrap().unwrap().to_vec();

    for (i, &v) in result.iter().enumerate() {
        assert!((v - 0.5).abs() < 1e-5, "pixel {i}: expected 0.5, got {v}");
    }
}

#[test]
fn hq_temporal_smoke() {
    let client = make_client();
    let w = 16;
    let h = 16;

    let params = NlmParams {
        temporal_radius: 1,
        hq: Some(HqParams::with_sigma(6.0 / 255.0)),
        ..base_params()
    };

    let mut denoiser = NlmDenoiser::<R>::new(&client, params, w, h);

    let frames: Vec<Vec<f32>> = (0..5)
        .map(|i| make_frame_with_noisy_region(w, h, 1, 0.5, 6 + i, 8, 2, 0.8))
        .collect();

    let mut emitted = 0usize;
    let check = |frame: &[f32]| {
        for (i, &v) in frame.iter().enumerate() {
            assert!(v.is_finite(), "pixel {i}: non-finite output {v}");
            assert!((0.0..=1.0).contains(&v), "pixel {i}: out-of-range output {v}");
        }
    };

    for frame in &frames {
        denoiser.push_frame(frame);
        if let Some(result) = denoiser.denoise().unwrap() {
            check(result);
            emitted += 1;
        }
    }

    denoiser
        .flush(|frame| {
            check(frame);
            emitted += 1;
        })
        .unwrap();

    assert_eq!(emitted, frames.len(), "expected one output per pushed frame");
}

/// `sigma_override: None` measures the noise level from the pushed
/// frame instead of requiring a caller-supplied value, and the
/// measured sigma must still drive real denoising.
///
/// Uses per-pixel Gaussian noise rather than a solid noisy block. The
/// Immerkær estimator responds to genuine high-frequency variation. A
/// single flat block only disturbs its boundary ring, so it reads back
/// close to the noise floor and barely denoises anything.
#[test]
fn hq_auto_sigma_denoises() {
    let client = make_client();
    let w = 32;
    let h = 32;
    let frame = make_noisy_gaussian_frame(w, h, 1, 0.5, &[8.0 / 255.0]);

    let params = NlmParams {
        hq: Some(HqParams {
            auto_strength: true,
            noise_floor: true,
            sigma_override: None,
            temporal_confidence: true,
            thsad_scale: 1.0,
            sigma_scale: 1.0,
        }),
        ..base_params()
    };

    let mut denoiser = NlmDenoiser::<R>::new(&client, params, w, h);
    denoiser.push_frame(&frame);
    let result = denoiser.denoise().unwrap().unwrap().to_vec();

    let mut max_diff = 0.0f32;
    for (i, (&input, &output)) in frame.iter().zip(result.iter()).enumerate() {
        assert!(output.is_finite(), "pixel {i}: non-finite output {output}");
        assert!(
            (0.0..=1.0).contains(&output),
            "pixel {i}: out-of-range output {output}"
        );
        max_diff = max_diff.max((input - output).abs());
    }

    assert!(
        max_diff > 1e-3,
        "expected the auto-estimated sigma to actually denoise the input, max diff was {max_diff}"
    );
}

/// Mirrors `hq_temporal_smoke` but with the noise level measured
/// automatically instead of supplied up front.
#[test]
fn hq_auto_sigma_temporal_smoke() {
    let client = make_client();
    let w = 16;
    let h = 16;

    let params = NlmParams {
        temporal_radius: 1,
        hq: Some(HqParams {
            auto_strength: true,
            noise_floor: true,
            sigma_override: None,
            temporal_confidence: true,
            thsad_scale: 1.0,
            sigma_scale: 1.0,
        }),
        ..base_params()
    };

    let mut denoiser = NlmDenoiser::<R>::new(&client, params, w, h);

    let frames: Vec<Vec<f32>> = (0..5)
        .map(|i| make_frame_with_noisy_region(w, h, 1, 0.5, 6 + i, 8, 2, 0.8))
        .collect();

    let mut emitted = 0usize;
    let check = |frame: &[f32]| {
        for (i, &v) in frame.iter().enumerate() {
            assert!(v.is_finite(), "pixel {i}: non-finite output {v}");
            assert!((0.0..=1.0).contains(&v), "pixel {i}: out-of-range output {v}");
        }
    };

    for frame in &frames {
        denoiser.push_frame(frame);
        if let Some(result) = denoiser.denoise().unwrap() {
            check(result);
            emitted += 1;
        }
    }

    denoiser
        .flush(|frame| {
            check(frame);
            emitted += 1;
        })
        .unwrap();

    assert_eq!(emitted, frames.len(), "expected one output per pushed frame");
}

#[test]
fn hq_override_skips_estimation() {
    let client = make_client();
    let w = 16;
    let h = 16;

    let params = NlmParams {
        hq: Some(HqParams::with_sigma(8.0 / 255.0)),
        ..base_params()
    };

    let denoiser = NlmDenoiser::<R>::new(&client, params, w, h);

    assert!(
        denoiser.noise_partials.is_none(),
        "sigma_override must skip allocating the partials scratch buffer"
    );
    assert!(
        denoiser.noise_results.is_none(),
        "sigma_override must skip allocating the results buffer"
    );
}

/// `reset_stream_state` (called by `flush`) must clear the noise
/// estimator's EMA so a new stream doesn't inherit the previous
/// stream's noise level. Verified by observable behaviour. Pushing a
/// low-noise frame right after a reset must derive exactly the same
/// `h2_inv_norm` / `noise_offset` as a brand-new denoiser that only
/// ever saw that frame, instead of a value blended with the earlier
/// high-noise estimate.
#[test]
fn hq_reset_clears_noise_state() {
    let client = make_client();
    let w = 16;
    let h = 16;
    let noisy = make_frame_with_noisy_region(w, h, 1, 0.5, 8, 8, 3, 0.9);
    let low = make_uniform_frame(w, h, 1, 0.5);

    let params = NlmParams {
        hq: Some(HqParams {
            auto_strength: true,
            noise_floor: true,
            sigma_override: None,
            temporal_confidence: true,
            thsad_scale: 1.0,
            sigma_scale: 1.0,
        }),
        ..base_params()
    };

    let mut denoiser = NlmDenoiser::<R>::new(&client, params.clone(), w, h);
    denoiser.push_frame(&noisy);
    denoiser.denoise().unwrap();

    denoiser.reset_stream_state();
    denoiser.push_frame(&low);
    denoiser.denoise().unwrap();

    let mut fresh = NlmDenoiser::<R>::new(&client, params, w, h);
    fresh.push_frame(&low);
    fresh.denoise().unwrap();

    assert_eq!(
        denoiser.h2_inv_norm, fresh.h2_inv_norm,
        "reset should clear the EMA so the next estimate starts fresh, not blended with stale state"
    );
    assert_eq!(
        denoiser.noise_offset, fresh.noise_offset,
        "reset should clear the EMA so the next estimate starts fresh, not blended with stale state"
    );
}

/// HQ auto-σ combined with the nlm-spatial pilot over a short temporal
/// sequence. Mirrors `hq_auto_sigma_temporal_smoke` but with the pilot
/// enabled. Every produced frame must stay finite and in range, and the
/// pipeline must still emit exactly one output per pushed frame.
#[test]
fn hq_pilot_temporal_end_to_end() {
    let client = make_client();
    let w = 16;
    let h = 16;

    let params = NlmParams {
        temporal_radius: 1,
        prefilter: PrefilterMode::NlmSpatial { strength_scale: 1.0 },
        hq: Some(HqParams {
            auto_strength: true,
            noise_floor: true,
            sigma_override: None,
            temporal_confidence: true,
            thsad_scale: 1.0,
            sigma_scale: 1.0,
        }),
        ..base_params()
    };

    let mut denoiser = NlmDenoiser::<R>::new(&client, params, w, h);

    let frames: Vec<Vec<f32>> = (0..5)
        .map(|i| make_frame_with_noisy_region(w, h, 1, 0.5, 6 + i, 8, 2, 0.8))
        .collect();

    let mut emitted = 0usize;
    let check = |frame: &[f32]| {
        for (i, &v) in frame.iter().enumerate() {
            assert!(v.is_finite(), "pixel {i}: non-finite output {v}");
            assert!((0.0..=1.0).contains(&v), "pixel {i}: out-of-range output {v}");
        }
    };

    for frame in &frames {
        denoiser.push_frame(frame);
        if let Some(result) = denoiser.denoise().unwrap() {
            check(result);
            emitted += 1;
        }
    }

    denoiser
        .flush(|frame| {
            check(frame);
            emitted += 1;
        })
        .unwrap();

    assert_eq!(emitted, frames.len(), "expected one output per pushed frame");
}

/// The nlm-spatial pilot changes what the main pass reads as its
/// distance signal, so HQ with the pilot enabled must diverge from
/// plain HQ (`prefilter: None`) on the same input.
///
/// Uses per-pixel Gaussian noise rather than a solid noisy block (as
/// `hq_noise_floor_changes_output` explains, a flat block only
/// disturbs its boundary ring, leaving patch distances elsewhere
/// identical whether or not the pilot ran).
#[test]
fn hq_pilot_differs_from_unguided() {
    let client = make_client();
    let w = 32;
    let h = 32;
    let frame = make_noisy_gaussian_frame(w, h, 1, 0.5, &[10.0 / 255.0]);

    let hq_params = |prefilter: PrefilterMode| NlmParams {
        prefilter,
        hq: Some(HqParams {
            auto_strength: true,
            noise_floor: true,
            sigma_override: None,
            temporal_confidence: true,
            thsad_scale: 1.0,
            sigma_scale: 1.0,
        }),
        ..base_params()
    };

    let mut unguided = NlmDenoiser::<R>::new(&client, hq_params(PrefilterMode::None), w, h);
    unguided.push_frame(&frame);
    let unguided_out = unguided.denoise().unwrap().unwrap().to_vec();

    let mut piloted = NlmDenoiser::<R>::new(
        &client,
        hq_params(PrefilterMode::NlmSpatial { strength_scale: 1.0 }),
        w,
        h,
    );
    piloted.push_frame(&frame);
    let piloted_out = piloted.denoise().unwrap().unwrap().to_vec();

    let mut max_diff = 0.0f32;
    for (i, (&a, &b)) in unguided_out.iter().zip(piloted_out.iter()).enumerate() {
        assert!(b.is_finite(), "pixel {i}: non-finite piloted output {b}");
        assert!(
            (0.0..=1.0).contains(&b),
            "pixel {i}: out-of-range piloted output {b}"
        );
        max_diff = max_diff.max((a - b).abs());
    }

    assert!(
        max_diff > 1e-4,
        "expected the pilot to change HQ output somewhere, max diff was {max_diff}"
    );
}

/// HQ temporal params tuned so a uniformly mismatched neighbour sits
/// well past `thsad` (confidence collapses to ~0) while the plain NLM
/// patch weight for that same neighbour stays significant on its own.
/// `strength`/`patch_radius` are chosen so the two thresholds don't
/// coincide, otherwise confidence toggling wouldn't be separable from
/// the intrinsic Welsch suppression.
fn temporal_conf_params(temporal_confidence: bool) -> NlmParams {
    NlmParams {
        temporal_radius: 1,
        search_radius: 1,
        patch_radius: 1,
        strength: 20.0,
        self_weight: 0.0,
        channels: ChannelMode::Luma,
        prefilter: PrefilterMode::None,
        motion_compensation: MotionCompensationMode::None,
        hq: Some(HqParams {
            auto_strength: false,
            noise_floor: false,
            sigma_override: Some(2.0 / 255.0),
            temporal_confidence,
            thsad_scale: 1.0,
            sigma_scale: 1.0,
        }),
    }
}

/// A mismatched neighbour's contribution must be suppressed by
/// confidence weighting while a matching neighbour's is not. The
/// centre frame and the "next" neighbour are flat at 0.5. The "prev"
/// neighbour is flat at 0.55 (uniformly mismatched by 0.05, well past
/// the default `thsad` at the library's block size). Without
/// confidence, plain NLM weighting still gives `prev` a non-negligible
/// weight (patch distances are small at this `strength`), pulling the
/// output away from 0.5. With confidence, `prev`'s block-level
/// mismatch collapses its weight to ~0, so the output stays at 0.5 —
/// the style of comparison `temporal_asymmetric_frames_correct_weights`
/// uses for the fast path, applied here against confidence-off instead
/// of a hand-computed target.
#[test]
fn hq_temporal_confidence_suppresses_mismatched_neighbour() {
    let client = make_client();
    let w = 16;
    let h = 16;

    let prev = make_uniform_frame(w, h, 1, 0.55);
    let center = make_uniform_frame(w, h, 1, 0.5);
    let next = make_uniform_frame(w, h, 1, 0.5);

    let run = |temporal_confidence: bool| {
        let mut d = NlmDenoiser::<R>::new(&client, temporal_conf_params(temporal_confidence), w, h);
        d.push_frame(&prev);
        d.push_frame(&center);
        d.push_frame(&next);
        d.denoise().unwrap().unwrap().to_vec()
    };

    let off = run(false);
    let on = run(true);

    let off_dev = (off[(8 * w + 8) as usize] - 0.5).abs();
    let on_dev = (on[(8 * w + 8) as usize] - 0.5).abs();

    assert!(
        off_dev > 5e-3,
        "without confidence weighting the mismatched neighbour should pull the \
         output measurably away from 0.5, got deviation {off_dev}"
    );
    assert!(
        on_dev < off_dev * 0.5,
        "confidence weighting should suppress the mismatched neighbour's \
         contribution: off deviation {off_dev}, on deviation {on_dev}"
    );
}

/// HQ with `temporal_confidence` set to `false` must ignore the
/// confidence machinery entirely, not just apply a weak version of it.
/// `thsad_scale` only ever feeds the confidence threshold (see
/// `HqParams::thsad_scale`), so if the disabled kernel path genuinely
/// never reads the confidence buffer, sweeping it must leave the
/// output bitwise unchanged. This is the observable form of "compiles
/// to the same code as before confidence consumption existed" for a
/// config the plan requires to match prior HQ output exactly.
#[test]
fn hq_temporal_confidence_disabled_ignores_thsad_scale() {
    let client = make_client();
    let w = 16;
    let h = 16;
    let frames: Vec<Vec<f32>> = (0..3)
        .map(|i| make_frame_with_noisy_region(w, h, 1, 0.5, 6 + i, 8, 2, 0.8))
        .collect();

    let run = |thsad_scale: f32| {
        let params = NlmParams {
            temporal_radius: 1,
            search_radius: 2,
            patch_radius: 2,
            strength: 1.2,
            self_weight: 1.0,
            channels: ChannelMode::Luma,
            prefilter: PrefilterMode::None,
            motion_compensation: MotionCompensationMode::None,
            hq: Some(HqParams {
                auto_strength: true,
                noise_floor: true,
                sigma_override: Some(6.0 / 255.0),
                temporal_confidence: false,
                thsad_scale,
                sigma_scale: 1.0,
            }),
        };
        let mut d = NlmDenoiser::<R>::new(&client, params, w, h);
        for frame in &frames {
            d.push_frame(frame);
        }
        d.denoise().unwrap().unwrap().to_vec()
    };

    let base = run(1.0);
    let scaled = run(4.0);

    assert_eq!(
        base, scaled,
        "temporal_confidence: false must make thsad_scale inert (confidence buffer unused)"
    );
}

/// End-to-end smoke test covering HQ temporal denoising with motion
/// compensation and (default-on) confidence weighting together, over a
/// short synthetic sequence. Every produced frame must stay finite and
/// in range, mirroring `hq_auto_sigma_temporal_smoke` with MC layered
/// on top.
#[test]
fn hq_temporal_mc_confidence_smoke() {
    let client = make_client();
    let w = 32;
    let h = 32;

    let params = NlmParams {
        temporal_radius: 1,
        motion_compensation: MotionCompensationMode::Mvtools {
            blksize: 8,
            overlap: 4,
            search_radius: 2,
            pyramid_levels: 2,
            estimation: MotionEstimation::Direct,
        },
        hq: Some(HqParams::with_sigma(6.0 / 255.0)),
        ..base_params()
    };

    let mut denoiser = NlmDenoiser::<R>::new(&client, params, w, h);

    let frames: Vec<Vec<f32>> = (0..5)
        .map(|i| make_frame_with_noisy_region(w, h, 1, 0.5, 6 + i, 8, 2, 0.8))
        .collect();

    let mut emitted = 0usize;
    let check = |frame: &[f32]| {
        for (i, &v) in frame.iter().enumerate() {
            assert!(v.is_finite(), "pixel {i}: non-finite output {v}");
            assert!((0.0..=1.0).contains(&v), "pixel {i}: out-of-range output {v}");
        }
    };

    for frame in &frames {
        denoiser.push_frame(frame);
        if let Some(result) = denoiser.denoise().unwrap() {
            check(result);
            emitted += 1;
        }
    }

    denoiser
        .flush(|frame| {
            check(frame);
            emitted += 1;
        })
        .unwrap();

    assert_eq!(emitted, frames.len(), "expected one output per pushed frame");
}

/// `sigma_scale` multiplies each channel's raw sigma before it folds
/// into the running EMA, so doubling it must exactly double the folded
/// estimator state (the EMA's first sample sets its state directly,
/// with no nonlinearity to round off) and quadruple `noise_offset`
/// (quadratic in sigma). Checking both consumers from a single fold
/// proves the multiply sits before the blend feeds either of them,
/// rather than one of them picking it up incidentally.
#[test]
fn hq_sigma_scale_multiplies_the_folded_estimate() {
    let client = make_client();
    let w = 32;
    let h = 32;
    let frame = make_noisy_gaussian_frame(w, h, 1, 0.5, &[8.0 / 255.0]);

    let run = |sigma_scale: f32| {
        let params = NlmParams {
            hq: Some(HqParams {
                auto_strength: true,
                noise_floor: true,
                sigma_override: None,
                temporal_confidence: true,
                thsad_scale: 1.0,
                sigma_scale,
            }),
            ..base_params()
        };
        let mut d = NlmDenoiser::<R>::new(&client, params, w, h);
        d.push_frame(&frame);
        d.denoise().unwrap();
        let folded = d
            .noise_estimator
            .current()
            .expect("estimator should hold a value after one push")[0];
        (folded, d.noise_offset)
    };

    let (folded_1x, offset_1x) = run(1.0);
    let (folded_2x, offset_2x) = run(2.0);

    assert!(
        (folded_2x - folded_1x * 2.0).abs() < folded_1x * 1e-4,
        "expected the folded estimate to scale exactly 2x: 1x={folded_1x}, 2x={folded_2x}"
    );
    assert!(
        (offset_2x - offset_1x * 4.0).abs() < offset_1x * 1e-4,
        "expected noise_offset to scale 4x (quadratic in sigma): 1x={offset_1x}, 2x={offset_2x}"
    );
}