Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -1958,6 +1958,23 @@ that havsfunc's QTGMC takes none of them (setting one failed every encode).
720x480), so memory grew with the job's length. Keep the pool until the
bundle has the fixed release (task #63); `removedirt_determinism_test.dart`
checks it.
- **Never build an akarin expression per frame** (issue #253). A FrameEval
that returns a new `_expr(...)` compiles it with LLVM on every frame
wherever akarin is installed (every bundle but macOS x64): ~20 ms each,
serialised under the GIL. Automatic white balance did this and ran at ~60
fps on its own at 706x480 (~8,000 fps now; identical at 8-12 bits, about 2
chroma planes in 1,000 one step apart at 16, as akarin reads a property as
a 32-bit float). It is also the IVTC fade fix's hang
pattern. Read per-frame values as frame properties in **one** akarin
expression (`x x.PropName …`, stamped by PlaneStats, ModifyFrame or
CopyFrameProps), keeping a std.Expr FrameEval only as the no-akarin
fallback, or memoise a bounded set of nodes. **But akarin compiles with
fast-math**: a division can land a .5 tie on the other side of IEEE's, so a
prop-reading expression is not bit-exact against a plugin that divides
(std.Levels: one level off in about 2% of (min, max) pairs). That is why
automatic levels stays a per-frame std.Levels, which is cheap (a lookup
table, ~5,000 fps at 706x480). `test_271` guards both
(docs/reports/issue-253-auto-colour-per-frame-expr).

### VapourSynth Frame Cache (issue #107)

Expand Down
126 changes: 126 additions & 0 deletions app/test/integration_auto_colour_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
// Issue #253: Colour Correction's automatic white balance used to build a new
// expression for every frame, and on akarin (every bundle but macOS x64) each
// one was an LLVM compile, serialised under the GIL. It is now one expression
// that reads the chroma means PlaneStats stamps on each frame. Automatic
// levels is unchanged (a per-frame std.Levels), and runs here alongside it.
// docs/reports/issue-253-auto-colour-per-frame-expr compares the new code
// with the old on synthetic clips (identical at 8-12 bits; at 16 bits a few
// chroma planes in 1,000 one step apart); this checks the user's view through
// the worker on a real one:
//
// * each filter changes the picture (against the same job with it off),
// * the preview of a frame is the lossless encode's frame, sample for
// sample, with both filters on at strengths below 1.
@Tags(['heavy'])
@Timeout(Duration(minutes: 20))
library;

import 'dart:io';
import 'dart:typed_data';

import 'package:flutter_test/flutter_test.dart';
import 'package:path/path.dart' as p;
import 'package:uuid/uuid.dart';

import 'package:vapourbox/models/color_correction_parameters.dart';
import 'package:vapourbox/models/encoding_settings.dart';
import 'package:vapourbox/models/processing_pipeline.dart';
import 'package:vapourbox/models/qtgmc_parameters.dart';
import 'package:vapourbox/models/video_job.dart';

import 'support/worker_harness.dart';

// Camera footage with colour: 320x240, 29.97 fps, 8-bit 4:2:0, progressive.
String get _fixture =>
p.join(WorkerHarness.repoRoot, 'Tests', 'TestResources', 'small_clip.mp4');
String get _dir => p.join(WorkerHarness.outputDir, 'auto_colour');
const _start = 300, _end = 339;

Map<String, dynamic> _job(String name, ColorCorrectionParameters cc,
{bool trimmed = true}) =>
VideoJob(
id: const Uuid().v4(),
inputPath: _fixture,
outputPath: p.join(_dir, '$name.mkv'),
processingPipeline: ProcessingPipeline(
deinterlace: const QTGMCParameters(enabled: false),
colorCorrection: cc,
),
encodingSettings: const EncodingSettings(
codec: VideoCodec.ffv1, container: ContainerFormat.mkv, audioMode: AudioMode.none),
inputWidth: 320,
inputHeight: 240,
inputPixelFormat: 'yuv420p',
inputFrameRate: 29.97,
startFrame: trimmed ? _start : null,
endFrame: trimmed ? _end : null,
).toJson();

int _maxAbsDiff(Uint8List a, Uint8List b) {
expect(a.length, b.length, reason: 'frame sizes differ');
var worst = 0;
for (var i = 0; i < a.length; i++) {
final d = (a[i] - b[i]).abs();
if (d > worst) worst = d;
}
return worst;
}

Future<String> _encode(String name, ColorCorrectionParameters cc) async {
final r = await WorkerHarness.runJob(_job(name, cc), label: '$name encode',
timeout: const Duration(minutes: 5));
expect(r.success, isTrue,
reason: '${r.error}\n${r.logs.reversed.take(30).toList().reversed.join('\n')}');
return r.outputPath ?? p.join(_dir, '$name.mkv');
}

void main() {
setUpAll(() async {
await WorkerHarness.ensureReady();
await Directory(_dir).create(recursive: true);
});

// Enabled with nothing switched on: the pass's own reference.
const off = ColorCorrectionParameters(enabled: true);
const white = ColorCorrectionParameters(
enabled: true, applyAutoWhiteBalance: true, autoWhiteBalanceStrength: 0.8);
const levels = ColorCorrectionParameters(
enabled: true, applyAutoLevels: true, autoLevelsStrength: 0.6);
const both = ColorCorrectionParameters(
enabled: true,
applyAutoLevels: true,
autoLevelsStrength: 0.6,
applyAutoWhiteBalance: true,
autoWhiteBalanceStrength: 0.8);

test('each automatic filter changes the picture (issue #253)', () async {
final reference = await _encode('off', off);
for (final MapEntry(key: name, value: cc) in {'white': white, 'levels': levels}.entries) {
final out = await _encode(name, cc);
for (final frame in [5, 25]) {
final a = await WorkerHarness.previewFrameRgb24(reference, frame, label: 'off_$frame');
final b = await WorkerHarness.previewFrameRgb24(out, frame, label: '${name}_$frame');
final mean = WorkerHarness.meanAbsDiff(a, b);
// ignore: avoid_print
print(' $name frame $frame: mean change ${mean.toStringAsFixed(2)} levels');
expect(mean, greaterThan(0.2), reason: 'automatic $name changed nothing');
}
}
});

test('preview is the encode\'s frame, sample for sample (issue #253)', () async {
final out = await _encode('both', both);
for (final frame in [_start + 10, _start + 30]) {
final encoded =
await WorkerHarness.previewFrameRgb24(out, frame - _start, label: 'both_enc');
final pv = await WorkerHarness.runPreview(_job('both_pv', both, trimmed: false),
frame: frame);
expect(pv.success, isTrue, reason: '${pv.error}\n${pv.logs}');
final preview = await WorkerHarness.imageToRgb24(pv.png!, label: 'both_pv');
final d = _maxAbsDiff(preview, encoded);
// ignore: avoid_print
print(' frame $frame: preview vs encode max $d');
expect(d, 0, reason: 'the preview of frame $frame is not the encode\'s frame');
}
});
}
29 changes: 29 additions & 0 deletions app/test/integration_filter_parameters_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,35 @@ void main() {
print(' PASS');
}, timeout: const Timeout(Duration(minutes: 2)));

// Issue #253: automatic white balance reads the chroma means from frame
// properties in one akarin expression, instead of building an expression
// (an LLVM compile on akarin) per frame. Rust-side twin: test_271.
test('color_correction: automatic colour builds no node per frame',
() async {
loadSchema('color_correction');
final script = await generateScriptViaWorker(buildJob(
testName: 'auto_colour',
colorCorrection: const ColorCorrectionParameters(
enabled: true,
applyAutoLevels: true,
applyAutoWhiteBalance: true,
autoWhiteBalanceStrength: 0.8,
),
));
expect(script, contains('clip = _auto_white(clip, 0.8)'));
expect(script, contains('x._AwbUAverage'));
expect(script, contains('x._AwbVAverage'));
final white = script.substring(script.indexOf('def _auto_white('),
script.indexOf('clip = _auto_white('));
final akarin = white.indexOf('if _akarin_expr is not None:');
final fallback = white.indexOf('su = core.std.PlaneStats(c, plane=1)');
expect(akarin, greaterThan(0));
expect(fallback, greaterThan(akarin));
expect(white.substring(0, fallback), isNot(contains('FrameEval')),
reason: 'the akarin path must evaluate nothing per frame');
print(' PASS');
}, timeout: const Timeout(Duration(minutes: 2)));


// Issue #50: CCD chroma denoise, the pass that pulls in the zsmooth plugin.
test('chroma_denoise: CCD params + derived scale', () async {
Expand Down
34 changes: 34 additions & 0 deletions docs/ENGINEERING_NOTES.md
Original file line number Diff line number Diff line change
Expand Up @@ -7107,3 +7107,37 @@ python-build-standalone (pinned by URL), and akarin's vendored `libz` /
Never a retry.

Report: [docs/reports/task-128-bm3d-heavy-test-time](reports/task-128-bm3d-heavy-test-time/index.html).

### Automatic white balance compiled an expression every frame (issue #253, 2026-11-28)

Reported by a user: Colour Correction with automatic white balance and CLAHE
ran a 706x480 VHS chain at 16.8 fps against 47.6 without it, at ~20% CPU,
and a 48-core EPYC ran it slower than a desktop. `_auto_white` returned a new
`_expr(...)` from a `std.FrameEval` on every frame, with the offsets written
into the expression text. `_expr` sends it to akarin wherever akarin is
installed (every bundle but macOS x64), so each frame was an LLVM compile in
a Python callback holding the GIL: ~17 ms a frame on an M1, serial whatever
the core count.

- **Fix:** with akarin, PlaneStats stamps the chroma means on each frame
(`_AwbU*`, `_AwbV*`, removed afterwards) and one expression reads them.
The FrameEval is only the fallback where akarin is absent, where a
`std.Expr` per frame costs ~0.35 ms. The filter alone at 706x480: ~60 fps
→ ~8,000 fps. The whole chain through the worker did not change measurably
(10.8 → 10.9 fps), but that was on a machine loaded by another task's
tests, where the other passes ran far below the old filter's ~60 fps serial
ceiling; the issue's desktop ran them at 47.6 fps, where it was the limit.
- **Output:** identical at 8-12 bits and on the fallback. At 16 bits 17 of
10,800 chroma planes (0.16%) were one 16-bit step apart, because akarin
reads a frame property as a 32-bit float (~0.004 of a step at a 16-bit
peak) and the old code wrote the offset as a 6-decimal literal.
- **Automatic levels is unchanged.** It builds a `std.Levels` (a lookup
table) per frame, ~0.2 ms; caching the nodes changed nothing measurable.
One akarin expression doing `std.Levels`' arithmetic is not bit-exact:
akarin compiles with fast-math, so its division misses .5 ties in 2.0% of
(min, max) pairs, one level off (55/110 × 219 + 16 = 125.5: std.Levels
126, akarin 125), with `opt=0` or `opt=1`.
- CLAUDE.md ("One script template") now says never to build an akarin
expression per frame, and gives the fast-math caveat.

Report: [docs/reports/issue-253-auto-colour-per-frame-expr](reports/issue-253-auto-colour-per-frame-expr/index.html).
1 change: 1 addition & 0 deletions docs/reports/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ to it.

| Date | Report | Outcome |
|---|---|---|
| 2026-11-28 | [Issue #253: automatic white balance compiled an expression every frame](issue-253-auto-colour-per-frame-expr/index.html) | Fixed in the template: `_auto_white` returned a new expression from a FrameEval each frame, and on akarin (every bundle but macOS x64) that is an LLVM compile under the GIL, ~17 ms a frame on an M1. Now one akarin expression reads PlaneStats' means as frame properties; the FrameEval is only macOS x64's fallback. Filter alone at 706x480: ~60 → ~8,000 fps; the whole chain unchanged (10.8 → 10.9 fps) on a heavily loaded M1, where the other passes ran far below the old filter's serial ceiling. Identical at 8-12 bits; at 16 bits 0.16% of chroma planes one step apart (akarin reads properties as 32-bit floats). Automatic levels left alone: cheap already, and akarin's fast-math division misses .5 ties against std.Levels in 2% of (min, max) pairs |
| 2026-11-28 | [Task #128: the BM3D smoke encode that outgrew the 300 s job limit](task-128-bm3d-heavy-test-time/index.html) | Fixed in the test: across 40 nightlies the 79-frame BM3D encode took 222–300+ s on macos-arm64 and up to 300+ s on the x64 Macs, and hit `runJob`'s default 300 s limit 9 times, all on Mac legs; Linux ≤ 232 s, Windows ≤ 190 s. Runner speed, not the deps. It now encodes 24 frames (radius 1 still has neighbours both sides) under an explicit 5 min job limit and asserts the count |
| 2026-11-27 | [Task #124: the DCTFilter stress test that timed out on Windows](task-124-dctfilter-stress-timeout/index.html) | Fixed in the tests: the test's vspipe was held in its exit by Defender (task #122), and tests ran vspipe with `Process.run`, with no limit, so the worker's 30 s guard never applied. The logs: after the timeout the next test ran at normal speed beside the leftover process (160 s vs 170–177 s), and a console host was left at job end. Every test that runs vspipe now goes through `runVspipe`, the worker's rule as a pinned Dart twin, with stacks before the kill; the stress tests bound (90 s) and time each graph (M1: DCTFilter 0.5–0.8 s, DFTTest 9–11 s). Not yet run on Windows with the change |
| 2026-11-27 | [Task #113: Retinex r4 appends our sigma to its defaults](task-113-retinex-sigma/index.html) | Fixed in the deps scripts (next deps version): Windows shipped the r4 DLL, whose parser runs `sigma=[X]` as `[25, 80, 250, X]`; macOS/Linux built 6bfbdd42 (r4 + the fix). Shadow Detail was 9–11 levels apart at the default sigma (max 34; three frames of small_clip, luma), and the slider moved Windows' picture a seventh as far. The r4 tag built on the same machine matches the emulation exactly. Windows now builds 6bfbdd42 with Zig, marked by a no-code patch; macOS output byte-identical. macOS arm64 measured; the Windows DLL cross-compiled but run only in CI |
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
8-bit 706x480 4:2:0, 600 frames; no filter: 344 fps
_auto_white before (main) 6 fps
_auto_white after, akarin 1415 fps
_auto_white after, no akarin (macOS x64) 530 fps
_auto_levels (unchanged) 1162 fps
10-bit 706x480 4:2:0, 600 frames; no filter: 2614 fps
_auto_white before (main) 20 fps
_auto_white after, akarin 2251 fps
_auto_white after, no akarin (macOS x64) 595 fps
_auto_levels (unchanged) 944 fps
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[in#0 @ 0x14d805460] Referenced QT chapter track not found
SMDegrain + LSFmod 300 frames 20.6 s 14.6 fps
+ Colour Correction (auto WB + CLAHE), before 300 frames 27.8 s 10.8 fps
+ Colour Correction (auto WB + CLAHE), after 300 frames 27.4 s 10.9 fps
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
(lo, hi, output range) cases: 4488
ternary (flat frame kept) opt=0: 91 cases differ (2.0%)
ternary (flat frame kept) opt=1: 91 cases differ (2.0%)
plain opt=0: 91 cases differ (2.0%)
plain opt=1: 91 cases differ (2.0%)
clamp, +0.5, trunc (std.Levels order) opt=0: 91 cases differ (2.0%)
clamp, +0.5, trunc (std.Levels order) opt=1: 91 cases differ (2.0%)
example: min_in=52 max_in=162 min_out=16 max_out=235 input 107: std.Levels 126, akarin 125
Loading
Loading