diff --git a/CLAUDE.md b/CLAUDE.md index fd6c61f5..f898b42a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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) diff --git a/app/test/integration_auto_colour_test.dart b/app/test/integration_auto_colour_test.dart new file mode 100644 index 00000000..185b575e --- /dev/null +++ b/app/test/integration_auto_colour_test.dart @@ -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 _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 _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'); + } + }); +} diff --git a/app/test/integration_filter_parameters_test.dart b/app/test/integration_filter_parameters_test.dart index 7337e3af..19314f60 100644 --- a/app/test/integration_filter_parameters_test.dart +++ b/app/test/integration_filter_parameters_test.dart @@ -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 { diff --git a/docs/ENGINEERING_NOTES.md b/docs/ENGINEERING_NOTES.md index de509141..d4925e6d 100644 --- a/docs/ENGINEERING_NOTES.md +++ b/docs/ENGINEERING_NOTES.md @@ -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). diff --git a/docs/reports/README.md b/docs/reports/README.md index a49e0b62..af08ac67 100644 --- a/docs/reports/README.md +++ b/docs/reports/README.md @@ -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 | diff --git a/docs/reports/issue-253-auto-colour-per-frame-expr/data/bench_isolated_macos-arm64.txt b/docs/reports/issue-253-auto-colour-per-frame-expr/data/bench_isolated_macos-arm64.txt new file mode 100644 index 00000000..1e3cad4f --- /dev/null +++ b/docs/reports/issue-253-auto-colour-per-frame-expr/data/bench_isolated_macos-arm64.txt @@ -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 diff --git a/docs/reports/issue-253-auto-colour-per-frame-expr/data/chain_timing_macos-arm64.txt b/docs/reports/issue-253-auto-colour-per-frame-expr/data/chain_timing_macos-arm64.txt new file mode 100644 index 00000000..4f3bbf36 --- /dev/null +++ b/docs/reports/issue-253-auto-colour-per-frame-expr/data/chain_timing_macos-arm64.txt @@ -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 diff --git a/docs/reports/issue-253-auto-colour-per-frame-expr/data/probe_akarin_levels.txt b/docs/reports/issue-253-auto-colour-per-frame-expr/data/probe_akarin_levels.txt new file mode 100644 index 00000000..ff58c630 --- /dev/null +++ b/docs/reports/issue-253-auto-colour-per-frame-expr/data/probe_akarin_levels.txt @@ -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 diff --git a/docs/reports/issue-253-auto-colour-per-frame-expr/data/probe_exact.txt b/docs/reports/issue-253-auto-colour-per-frame-expr/data/probe_exact.txt new file mode 100644 index 00000000..07c31369 --- /dev/null +++ b/docs/reports/issue-253-auto-colour-per-frame-expr/data/probe_exact.txt @@ -0,0 +1,97 @@ +auto_white bits=8 4:2:0 strength=0.0 path=akarin maxdiff=0 +auto_white bits=8 4:2:0 strength=0.0 path=fallback maxdiff=0 +auto_white bits=8 4:2:0 strength=0.37 path=akarin maxdiff=0 +auto_white bits=8 4:2:0 strength=0.37 path=fallback maxdiff=0 +auto_white bits=8 4:2:0 strength=0.8 path=akarin maxdiff=0 +auto_white bits=8 4:2:0 strength=0.8 path=fallback maxdiff=0 +auto_white bits=8 4:2:0 strength=1.0 path=akarin maxdiff=0 +auto_white bits=8 4:2:0 strength=1.0 path=fallback maxdiff=0 +auto_white bits=8 4:2:2 strength=0.0 path=akarin maxdiff=0 +auto_white bits=8 4:2:2 strength=0.0 path=fallback maxdiff=0 +auto_white bits=8 4:2:2 strength=0.37 path=akarin maxdiff=0 +auto_white bits=8 4:2:2 strength=0.37 path=fallback maxdiff=0 +auto_white bits=8 4:2:2 strength=0.8 path=akarin maxdiff=0 +auto_white bits=8 4:2:2 strength=0.8 path=fallback maxdiff=0 +auto_white bits=8 4:2:2 strength=1.0 path=akarin maxdiff=0 +auto_white bits=8 4:2:2 strength=1.0 path=fallback maxdiff=0 +auto_white bits=8 4:4:4 strength=0.0 path=akarin maxdiff=0 +auto_white bits=8 4:4:4 strength=0.0 path=fallback maxdiff=0 +auto_white bits=8 4:4:4 strength=0.37 path=akarin maxdiff=0 +auto_white bits=8 4:4:4 strength=0.37 path=fallback maxdiff=0 +auto_white bits=8 4:4:4 strength=0.8 path=akarin maxdiff=0 +auto_white bits=8 4:4:4 strength=0.8 path=fallback maxdiff=0 +auto_white bits=8 4:4:4 strength=1.0 path=akarin maxdiff=0 +auto_white bits=8 4:4:4 strength=1.0 path=fallback maxdiff=0 +auto_white bits=10 4:2:0 strength=0.0 path=akarin maxdiff=0 +auto_white bits=10 4:2:0 strength=0.0 path=fallback maxdiff=0 +auto_white bits=10 4:2:0 strength=0.37 path=akarin maxdiff=0 +auto_white bits=10 4:2:0 strength=0.37 path=fallback maxdiff=0 +auto_white bits=10 4:2:0 strength=0.8 path=akarin maxdiff=0 +auto_white bits=10 4:2:0 strength=0.8 path=fallback maxdiff=0 +auto_white bits=10 4:2:0 strength=1.0 path=akarin maxdiff=0 +auto_white bits=10 4:2:0 strength=1.0 path=fallback maxdiff=0 +auto_white bits=10 4:2:2 strength=0.0 path=akarin maxdiff=0 +auto_white bits=10 4:2:2 strength=0.0 path=fallback maxdiff=0 +auto_white bits=10 4:2:2 strength=0.37 path=akarin maxdiff=0 +auto_white bits=10 4:2:2 strength=0.37 path=fallback maxdiff=0 +auto_white bits=10 4:2:2 strength=0.8 path=akarin maxdiff=0 +auto_white bits=10 4:2:2 strength=0.8 path=fallback maxdiff=0 +auto_white bits=10 4:2:2 strength=1.0 path=akarin maxdiff=0 +auto_white bits=10 4:2:2 strength=1.0 path=fallback maxdiff=0 +auto_white bits=10 4:4:4 strength=0.0 path=akarin maxdiff=0 +auto_white bits=10 4:4:4 strength=0.0 path=fallback maxdiff=0 +auto_white bits=10 4:4:4 strength=0.37 path=akarin maxdiff=0 +auto_white bits=10 4:4:4 strength=0.37 path=fallback maxdiff=0 +auto_white bits=10 4:4:4 strength=0.8 path=akarin maxdiff=0 +auto_white bits=10 4:4:4 strength=0.8 path=fallback maxdiff=0 +auto_white bits=10 4:4:4 strength=1.0 path=akarin maxdiff=0 +auto_white bits=10 4:4:4 strength=1.0 path=fallback maxdiff=0 +auto_white bits=12 4:2:0 strength=0.0 path=akarin maxdiff=0 +auto_white bits=12 4:2:0 strength=0.0 path=fallback maxdiff=0 +auto_white bits=12 4:2:0 strength=0.37 path=akarin maxdiff=0 +auto_white bits=12 4:2:0 strength=0.37 path=fallback maxdiff=0 +auto_white bits=12 4:2:0 strength=0.8 path=akarin maxdiff=0 +auto_white bits=12 4:2:0 strength=0.8 path=fallback maxdiff=0 +auto_white bits=12 4:2:0 strength=1.0 path=akarin maxdiff=0 +auto_white bits=12 4:2:0 strength=1.0 path=fallback maxdiff=0 +auto_white bits=12 4:2:2 strength=0.0 path=akarin maxdiff=0 +auto_white bits=12 4:2:2 strength=0.0 path=fallback maxdiff=0 +auto_white bits=12 4:2:2 strength=0.37 path=akarin maxdiff=0 +auto_white bits=12 4:2:2 strength=0.37 path=fallback maxdiff=0 +auto_white bits=12 4:2:2 strength=0.8 path=akarin maxdiff=0 +auto_white bits=12 4:2:2 strength=0.8 path=fallback maxdiff=0 +auto_white bits=12 4:2:2 strength=1.0 path=akarin maxdiff=0 +auto_white bits=12 4:2:2 strength=1.0 path=fallback maxdiff=0 +auto_white bits=12 4:4:4 strength=0.0 path=akarin maxdiff=0 +auto_white bits=12 4:4:4 strength=0.0 path=fallback maxdiff=0 +auto_white bits=12 4:4:4 strength=0.37 path=akarin maxdiff=0 +auto_white bits=12 4:4:4 strength=0.37 path=fallback maxdiff=0 +auto_white bits=12 4:4:4 strength=0.8 path=akarin maxdiff=0 +auto_white bits=12 4:4:4 strength=0.8 path=fallback maxdiff=0 +auto_white bits=12 4:4:4 strength=1.0 path=akarin maxdiff=0 +auto_white bits=12 4:4:4 strength=1.0 path=fallback maxdiff=0 +auto_white bits=16 4:2:0 strength=0.0 path=akarin maxdiff=0 +auto_white bits=16 4:2:0 strength=0.0 path=fallback maxdiff=0 +auto_white bits=16 4:2:0 strength=0.37 path=akarin maxdiff=0 +auto_white bits=16 4:2:0 strength=0.37 path=fallback maxdiff=0 +auto_white bits=16 4:2:0 strength=0.8 path=akarin maxdiff=0 +auto_white bits=16 4:2:0 strength=0.8 path=fallback maxdiff=0 +auto_white bits=16 4:2:0 strength=1.0 path=akarin maxdiff=0 +auto_white bits=16 4:2:0 strength=1.0 path=fallback maxdiff=0 +auto_white bits=16 4:2:2 strength=0.0 path=akarin maxdiff=0 +auto_white bits=16 4:2:2 strength=0.0 path=fallback maxdiff=0 +auto_white bits=16 4:2:2 strength=0.37 path=akarin maxdiff=0 +auto_white bits=16 4:2:2 strength=0.37 path=fallback maxdiff=0 +auto_white bits=16 4:2:2 strength=0.8 path=akarin maxdiff=1 <-- DIFFERS +auto_white bits=16 4:2:2 strength=0.8 path=fallback maxdiff=0 +auto_white bits=16 4:2:2 strength=1.0 path=akarin maxdiff=0 +auto_white bits=16 4:2:2 strength=1.0 path=fallback maxdiff=0 +auto_white bits=16 4:4:4 strength=0.0 path=akarin maxdiff=0 +auto_white bits=16 4:4:4 strength=0.0 path=fallback maxdiff=0 +auto_white bits=16 4:4:4 strength=0.37 path=akarin maxdiff=0 +auto_white bits=16 4:4:4 strength=0.37 path=fallback maxdiff=0 +auto_white bits=16 4:4:4 strength=0.8 path=akarin maxdiff=1 <-- DIFFERS +auto_white bits=16 4:4:4 strength=0.8 path=fallback maxdiff=0 +auto_white bits=16 4:4:4 strength=1.0 path=akarin maxdiff=0 +auto_white bits=16 4:4:4 strength=1.0 path=fallback maxdiff=0 +FAILURES 2 diff --git a/docs/reports/issue-253-auto-colour-per-frame-expr/data/probe_white_rate.txt b/docs/reports/issue-253-auto-colour-per-frame-expr/data/probe_white_rate.txt new file mode 100644 index 00000000..9c83c49b --- /dev/null +++ b/docs/reports/issue-253-auto-colour-per-frame-expr/data/probe_white_rate.txt @@ -0,0 +1,36 @@ + 8-bit 4:2:0 strength=0.37: 0 of 1200 chroma planes differ, max 0 + 8-bit 4:2:0 strength=0.8: 0 of 1200 chroma planes differ, max 0 + 8-bit 4:2:0 strength=1.0: 0 of 1200 chroma planes differ, max 0 + 8-bit 4:2:2 strength=0.37: 0 of 1200 chroma planes differ, max 0 + 8-bit 4:2:2 strength=0.8: 0 of 1200 chroma planes differ, max 0 + 8-bit 4:2:2 strength=1.0: 0 of 1200 chroma planes differ, max 0 + 8-bit 4:4:4 strength=0.37: 0 of 1200 chroma planes differ, max 0 + 8-bit 4:4:4 strength=0.8: 0 of 1200 chroma planes differ, max 0 + 8-bit 4:4:4 strength=1.0: 0 of 1200 chroma planes differ, max 0 +10-bit 4:2:0 strength=0.37: 0 of 1200 chroma planes differ, max 0 +10-bit 4:2:0 strength=0.8: 0 of 1200 chroma planes differ, max 0 +10-bit 4:2:0 strength=1.0: 0 of 1200 chroma planes differ, max 0 +10-bit 4:2:2 strength=0.37: 0 of 1200 chroma planes differ, max 0 +10-bit 4:2:2 strength=0.8: 0 of 1200 chroma planes differ, max 0 +10-bit 4:2:2 strength=1.0: 0 of 1200 chroma planes differ, max 0 +10-bit 4:4:4 strength=0.37: 0 of 1200 chroma planes differ, max 0 +10-bit 4:4:4 strength=0.8: 0 of 1200 chroma planes differ, max 0 +10-bit 4:4:4 strength=1.0: 0 of 1200 chroma planes differ, max 0 +12-bit 4:2:0 strength=0.37: 0 of 1200 chroma planes differ, max 0 +12-bit 4:2:0 strength=0.8: 0 of 1200 chroma planes differ, max 0 +12-bit 4:2:0 strength=1.0: 0 of 1200 chroma planes differ, max 0 +12-bit 4:2:2 strength=0.37: 0 of 1200 chroma planes differ, max 0 +12-bit 4:2:2 strength=0.8: 0 of 1200 chroma planes differ, max 0 +12-bit 4:2:2 strength=1.0: 0 of 1200 chroma planes differ, max 0 +12-bit 4:4:4 strength=0.37: 0 of 1200 chroma planes differ, max 0 +12-bit 4:4:4 strength=0.8: 0 of 1200 chroma planes differ, max 0 +12-bit 4:4:4 strength=1.0: 0 of 1200 chroma planes differ, max 0 +16-bit 4:2:0 strength=0.37: 2 of 1200 chroma planes differ, max 1 +16-bit 4:2:0 strength=0.8: 0 of 1200 chroma planes differ, max 0 +16-bit 4:2:0 strength=1.0: 1 of 1200 chroma planes differ, max 1 +16-bit 4:2:2 strength=0.37: 2 of 1200 chroma planes differ, max 1 +16-bit 4:2:2 strength=0.8: 0 of 1200 chroma planes differ, max 0 +16-bit 4:2:2 strength=1.0: 5 of 1200 chroma planes differ, max 1 +16-bit 4:4:4 strength=0.37: 0 of 1200 chroma planes differ, max 0 +16-bit 4:4:4 strength=0.8: 4 of 1200 chroma planes differ, max 1 +16-bit 4:4:4 strength=1.0: 3 of 1200 chroma planes differ, max 1 diff --git a/docs/reports/issue-253-auto-colour-per-frame-expr/data/timing_conditions.txt b/docs/reports/issue-253-auto-colour-per-frame-expr/data/timing_conditions.txt new file mode 100644 index 00000000..2ae21f4a --- /dev/null +++ b/docs/reports/issue-253-auto-colour-per-frame-expr/data/timing_conditions.txt @@ -0,0 +1,3 @@ +load before (1/5/15 min): { 164.86 176.20 158.37 }; another task's heavy tests were running on this 8-core M1 +load after isolated bench: { 164.68 180.35 163.82 } +load after chain timing: { 219.02 193.04 171.52 } diff --git a/docs/reports/issue-253-auto-colour-per-frame-expr/index.html b/docs/reports/issue-253-auto-colour-per-frame-expr/index.html new file mode 100644 index 00000000..d4ca854c --- /dev/null +++ b/docs/reports/issue-253-auto-colour-per-frame-expr/index.html @@ -0,0 +1,126 @@ + + + + + +Auto white balance cost + + + +

Automatic white balance compiled an expression for every frame

+

GitHub issue #253 (task #136), 2026-11-28. Measured on an Apple M1 (8 cores), deps 1.18.0-rc5 (macOS arm64) unless stated. The issue's own numbers are from a Windows desktop and a 48-core EPYC.

+ +

Outcome

+ + +

The code

+

Before (worker/templates/pipeline_template.vpy, {{#CC_AUTO_WHITE}}):

+
su = core.std.PlaneStats(c, plane=1)
+sv = core.std.PlaneStats(c, plane=2)
+
+def _apply(n, f, clip_in):
+    du = (neutral - f[0].props['PlaneStatsAverage'] * peak) * strength
+    dv = (neutral - f[1].props['PlaneStatsAverage'] * peak) * strength
+    return _expr(clip_in, ['', 'x {:.6f} +'.format(du), 'x {:.6f} +'.format(dv)])
+
+return core.std.FrameEval(c, functools.partial(_apply, clip_in=c), prop_src=[su, sv])
+

After, where akarin is present:

+
st = core.std.PlaneStats(c, plane=1, prop='_AwbU')
+st = core.std.PlaneStats(st, plane=2, prop='_AwbV')
+out = _expr(st, ['',
+    f'x {neutral} x._AwbUAverage {peak} * - {strength} * +',
+    f'x {neutral} x._AwbVAverage {peak} * - {strength} * +'])
+return core.std.RemoveFrameProps(out, props=[...the six _Awb* properties...])
+

The same arithmetic, per frame. The prefixed property names keep the stats from colliding with a later pass's PlaneStats, and they are removed afterwards. Everything before the akarin branch, and the fallback after it, is unchanged.

+ +

Speed of the filter alone

+

scripts/bench_isolated.py takes _auto_white verbatim from the template before (main) and after, and pulls it through frames() on a synthetic 706x480 4:2:0 clip: AddGrain noise, a chroma cast that changes every frame, and a luma contrast that drifts. No decoder or encoder. _auto_levels, unchanged, is timed alongside for scale.

+

The machine was never idle while this was measured: another task's heavy tests were running. Two runs are shown. Run A, 1,200 frames, came right after this task's own test suite finished, and the load was not recorded. Run B, 600 frames, was taken with a load average of 165–180 on 8 cores (data/timing_conditions.txt; output in data/bench_isolated_macos-arm64.txt). Absolute numbers swing with the load (B's "no filter" row: 344 fps at 8 bits, 2,614 at 10). The ratio is the result: the old filter's cost is one serial compile per frame, and it does not shrink with spare cores.

+ + + + + + + +
_auto_whiteRun A (load not recorded)Run B (load ~170)
8-bit10-bit8-bit10-bit
before (main)59 fps61 fps6 fps20 fps
after, akarin8,399 fps7,949 fps1,415 fps2,251 fps
after, no akarin (macOS x64's fallback, unchanged)2,862 fps2,967 fps530 fps595 fps
_auto_levels (unchanged), for scale~5,000 fps~4,500 fps1,162 fps944 fps
+

Run A was made with an earlier version of the script, while automatic levels was being tried with a node cache (since dropped); its _auto_white rows are the same code as now, and its levels figure is the before/after range given further down. Run A's output file was overwritten by run B; its numbers, and the first-look numbers below, are copied from the session's terminal output.

+

The first measurement, made while planning (scripts/bench_first_look.py, the two versions written out inline, deps 1.16.0, machine load not recorded), agreed: old 47.4 fps, new 8,088 fps at 8 bits, old 38.3, new 1,873 at 10 bits, with a std.Expr per frame (the macOS x64 path) at 2,856 fps.

+ +

Speed of the issue's chain

+

scripts/chain_timing.py runs the issue's chain through the worker binary (--config): SMDegrain, LSFmod, then Colour Correction with automatic white balance and local contrast (CLAHE), x264 CRF 10. The source is Tests/TestResources/pal-sd-25.mov, looped to 300 frames, scaled to 706x480 and stored as 8-bit 4:2:0 FFV1. "Before" puts main's templates beside the worker, which reads them first. The generated scripts were checked: "before" has no _AwbU, "after" has it. Wall time per job, the faster of two runs, with the load average at 165–220 (data/chain_timing_macos-arm64.txt, data/timing_conditions.txt).

+ + + + + +
JobSeconds (300 frames)fps
SMDegrain + LSFmod20.614.6
+ Colour Correction (auto WB + CLAHE), before27.810.8
+ Colour Correction (auto WB + CLAHE), after27.410.9
+

No measurable change here, and why. The old filter's cost is serial: ~17 ms a frame on this M1, a ceiling of ~60 fps for the job. Here the rest of the chain, sharing 8 cores with another task's tests, ran at ~11 fps, far below that ceiling, so the old filter's work overlapped the other passes and cost almost nothing extra. It becomes the limit when the rest of the chain runs faster than its ceiling, as on the issue's desktop (47.6 fps for SMDegrain + LSFmod, 16.8 with Colour Correction: ~38 ms a frame for the colour correction, at 20% CPU). That case, a free machine fast enough to hit the ceiling, was not measured here. The isolated numbers above are what this change is shown to remove; how much of a whole job that is depends on the machine and the rest of the chain.

+ +

Is the picture the same?

+

scripts/probe_exact.py runs both versions of _auto_white on the same clips: 60 frames at 706x480, every depth (8/10/12/16), every subsampling, strengths 0, 0.37, 0.8 and 1. The new function runs once with akarin and once bound to std.Expr (the fallback). data/probe_exact.txt:

+ + + + +
PathCasesIdentical
akarin4846; 16-bit 4:2:2 and 4:4:4 at strength 0.8: max 1
fallback (std.Expr)4848
+

scripts/probe_white_rate.py counts how often, over 600 frames per case (data/probe_white_rate.txt):

+ + + + +
DepthChroma planes that differ (of 1,200 per case, 9 cases)Largest difference
8, 10, 12-bit0 of 10,800 at each depth0
16-bit17 of 10,800 (0.16%): 0–5 per case1 sample step
+

Why: the integer sample x plus the offset rounds to x + round(offset), so only the offset's rounding matters. The old code computed the offset in double precision and wrote it with 6 decimals; akarin reads the PlaneStats mean (a double in [0, 1]) as a 32-bit float, which times a 16-bit peak leaves about 0.004 of a step of error. Where the offset's fraction is that close to .5, the plane rounds the other way. At 12 bits the error is under 0.0003 of a step, and nothing differed. A Python callback stamping a double-precision offset (as the fade fix does) would remove the difference at the cost of Python on every frame again; for 1/65,535 of full range on 0.16% of planes, it is not worth it.

+

The heavy test app/test/integration_auto_colour_test.dart also checks, through the worker on a real clip (small_clip.mp4), that each automatic filter changes the picture and that the preview of a frame is the lossless encode's frame, sample for sample (max 0).

+ +

Why automatic levels stays a std.Levels

+

Automatic levels has the same shape, a std.Levels (and std.Merge below strength 1) per frame, but a std.Levels is a lookup table built in microseconds, not a compile: ~5,000 fps on its own at 706x480 before and after. Caching each (min, max) pair's node was tried and made no measurable difference on the drifting clip (5,052 → 5,432 fps at 8 bits, 4,843 → 4,118 at 10; machine load not recorded), so it was not kept.

+

One akarin expression reading the measured points from frame properties was tried too, written as std.Levels' own arithmetic (R78 genericfilters.cpp: clamp, (v − min_in) / (max_in − min_in), × range, + min_out, clamp, + 0.5, truncate). It is not bit-exact. akarin compiles with fast-math, so the division becomes a multiplication by a reciprocal, and where the exact result is a .5 tie the reciprocal's rounding drops it: min_in=52 max_in=162 min_out=16 max_out=235, input 107 is 55/110 × 219 + 16 = 125.5, std.Levels 126, akarin 125. scripts/probe_akarin_levels.py, data/probe_akarin_levels.txt:

+ + + + + +
Spelling of the expressionopt=0opt=1
with the flat-frame test (max ≤ min keeps the frame)91 of 4,488 (2.0%)91 (2.0%)
plain91 (2.0%)91 (2.0%)
clamp, + 0.5, truncate (std.Levels' order)91 (2.0%)91 (2.0%)
+

Cases are seeded random (min, max) pairs at 8 bits, with three output ranges (16–235, 0–255, 40–200); a case differs if any of the 256 inputs does. With constants in place of properties, opt=1 happened to match and opt=0 did not; with properties neither does. The white balance has no division, which is why it can be one expression.

+ +

What changed

+ + +

Corrections made during the work

+ + +

Limits

+
+

The machine was shared with another task's heavy tests for every timing: the load average was not recorded for run A and was 165–220 for run B and the chain. Whole-job speed on a free machine was not measured. All speeds are one M1 on macOS. The issue's machine is Windows x86, where akarin's compile cost per frame will differ, but the cost was per frame and serial on every platform, and it is gone on every platform. The isolated numbers are synthetic clips through frames(), the filter's own cost; the chain's speed depends on the other passes and the encoder. The chain's source is a camera clip, not a VHS capture. macOS x64 (no akarin) keeps the fallback: it ran a std.Expr per frame before and still does, so nothing changes there; its speed was not measured on Intel hardware. The exactness probes use synthetic clips (grain plus a moving chroma cast); the 16-bit rate depends on how often a frame's offset lands within ~0.004 of a half step, which is a property of the arithmetic, not the picture.

+
+ + diff --git a/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/bench_first_look.py b/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/bench_first_look.py new file mode 100644 index 00000000..a142101f --- /dev/null +++ b/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/bench_first_look.py @@ -0,0 +1,56 @@ +"""Issue #253, the first measurement (planning stage, before any change): +the old and the proposed automatic white balance written out inline (not +read from the template), on a synthetic 706x480 clip. Modes: none, old +(akarin node per frame, as the template did), oldstd (std.Expr node per +frame: what macOS x64 runs), new (one akarin expression reading the +PlaneStats means). A sixth argument compares old with new. + +Usage: -I bench_first_look.py [cmp] +Run on deps 1.16.0 (macOS arm64), Apple M1; the machine's load was not recorded. +""" +import sys, time, functools +sys.path.insert(0, sys.argv[1]) +import vapoursynth as vs +core = vs.core +mode = sys.argv[2]; bits=int(sys.argv[3]); N=int(sys.argv[4]) +fmt = {8: vs.YUV420P8, 10: vs.YUV420P10}[bits] +c = core.std.BlankClip(width=706, height=480, format=fmt, length=N) +c = core.grain.Add(c, var=40, uvar=20, seed=1) if hasattr(core,'grain') else core.noise.Add(c) if hasattr(core,'noise') else c +# vary chroma per frame +c = core.std.Expr([c], ['', 'x N 7 % +', 'x N 5 % -']) if False else c +c = core.akarin.Expr([c], ['', 'x N 13 % 1.37 * + X 0.01 * +', 'x N 11 % 0.91 * - Y 0.02 * +']) +peak=(1<5: + # compare old vs new + def _apply(n,f,ci): + du=(neutral-f[0].props['PlaneStatsAverage']*peak)*s + dv=(neutral-f[1].props['PlaneStatsAverage']*peak)*s + return core.akarin.Expr(ci, ['', 'x {:.6f} +'.format(du), 'x {:.6f} +'.format(dv)]) + old = core.std.FrameEval(c, functools.partial(_apply, ci=c), prop_src=[su,sv]) + d = core.std.Expr([old,out],'x y - abs') + mx=0 + for p in range(3): + dd=core.std.PlaneStats(d,plane=p) + for f in dd.frames(): mx=max(mx,f.props['PlaneStatsMax']) + print('maxdiff',mx); sys.exit() +t=time.time() +for f in out.frames(): pass +print(mode,bits,'fps %.1f'%(N/(time.time()-t))) diff --git a/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/bench_isolated.py b/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/bench_isolated.py new file mode 100644 index 00000000..ae5c2313 --- /dev/null +++ b/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/bench_isolated.py @@ -0,0 +1,53 @@ +"""Issue #253: frames per second of automatic white balance on its own, +before and after, with the function taken verbatim from the two copies of +pipeline_template.vpy (probe_exact.load). Automatic levels, which this change +leaves as it was, is timed alongside for scale. + +Source: a synthetic 706x480 clip (the issue's capture size) with AddGrain +noise, a chroma cast that changes every frame and a luma contrast that drifts, +at 8 and 10 bits 4:2:0. Each variant is pulled through `frames()` +(VapourSynth's own threads, no decoder or encoder) after a 50-frame warm-up. +The numbers are each filter's own cost on this machine, not a job's speed: +chain_timing.py measures that. + +Usage: as probe_exact.py: [frames] +""" +import os +import sys +import time + +deps, old_path, new_path = sys.argv[1:4] +N = int(sys.argv[4]) if len(sys.argv) > 4 else 1200 +sys.path.insert(0, deps) +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import probe_exact as pe # noqa: E402 + +core, vs = pe.core, pe.vs + + +def source(bits): + peak = (1 << bits) - 1 + c = pe.white_source(bits, 2, N) + return core.akarin.Expr([c], [f'x {peak // 2} - N 400 % 0.002 * 0.6 + * {peak // 2} + X 0.05 * {peak / 255.0} * +', + '', '']) + + +def fps(clip): + for _ in clip[:50].frames(): + pass + t = time.perf_counter() + for _ in clip.frames(): + pass + return clip.num_frames / (time.perf_counter() - t) + + +for bits in (8, 10): + c = source(bits) + print(f'{bits}-bit 706x480 4:2:0, {N} frames; no filter: {fps(c):.0f} fps', flush=True) + for label, path, akarin in (('before (main)', old_path, True), + ('after, akarin', new_path, True), + ('after, no akarin (macOS x64)', new_path, False)): + fn = pe.load(path, '_auto_white', akarin)[0] + print(f' _auto_white {label:30s} {fps(fn(c, 1.0)):8.0f} fps', flush=True) + fn = pe.load(new_path, '_auto_levels', True)[0] + print(f' _auto_levels {"(unchanged)":30s} {fps(fn(c, 16, 235, 1.0)):8.0f} fps', flush=True) diff --git a/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/chain_timing.py b/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/chain_timing.py new file mode 100644 index 00000000..b6e16bf2 --- /dev/null +++ b/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/chain_timing.py @@ -0,0 +1,97 @@ +"""Issue #253: whole-job speed of the issue's chain, before and after. + +The chain is the one the issue measured: SMDegrain, then LSFmod, then Colour +Correction with automatic white balance and local contrast (CLAHE), encoded +with x264 at CRF 10. Each job is run through the real worker binary +(`--config`), and the wall time from start to exit is divided into the frame +count. "Before" puts a copy of the old templates beside the worker +(`/templates`, the first place the worker looks), "after" runs the +repository's own; the copy is removed afterwards. + +Source: `Tests/TestResources/pal-sd-25.mov` (720x576 ProRes, 125 frames), +looped, scaled to the issue's 706x480 and stored as 8-bit 4:2:0 FFV1, so +decoding costs little. It is a camera clip, not a VHS capture: the colour +correction does the same work on any picture, the denoiser and sharpener not +quite. + +Usage (plain Python 3, no VapourSynth needed): + python3 chain_timing.py [frames] +Prints one line per job: frames, seconds, fps. Runs each job twice and keeps +the faster run. +""" +import copy +import json +import os +import shutil +import subprocess +import sys +import time +import uuid + +repo, deps, worker, old_templates, scratch = sys.argv[1:6] +frames = int(sys.argv[6]) if len(sys.argv) > 6 else 750 +os.makedirs(scratch, exist_ok=True) +ffmpeg = os.path.join(deps, 'ffmpeg', 'ffmpeg') +fixture = os.path.join(scratch, f'chain_706x480_{frames}.mkv') +if not os.path.exists(fixture): + subprocess.run([ffmpeg, '-v', 'error', '-y', '-stream_loop', '-1', + '-i', os.path.join(repo, 'Tests', 'TestResources', 'pal-sd-25.mov'), + '-vf', 'scale=706:480,format=yuv420p,setsar=1', '-frames:v', str(frames), + '-an', '-c:v', 'ffv1', fixture], check=True) + +base = json.load(open(os.path.join( + repo, 'docs', 'reports', 'task-122-vspipe-exit-hang', 'data', 'pitch-job.json'))) +for key in ('inputWidth', 'inputHeight', 'inputPixelFormat', 'totalFrames', + 'inputFrameRate', 'source'): + base[key] = None +base['detectedFieldOrder'] = 'progressive' +base['encodingSettings'].update({'codec': 'libx264', 'quality': 10, 'container': 'mkv', + 'encoderPreset': 'medium', 'maxCacheSizeMb': None}) +pp = base['processingPipeline'] +pp['stabilize']['enabled'] = False + + +def job(colour): + j = copy.deepcopy(base) + j['id'] = str(uuid.uuid4()) + j['inputPath'] = fixture + j['outputPath'] = os.path.join(scratch, f'out_{j["id"]}.mkv') + p = j['processingPipeline'] + p['noiseReduction'].update({'enabled': True, 'method': 'smDegrain'}) + p['sharpen'].update({'enabled': True, 'method': 'LSFmod'}) + if colour: + p['colorCorrection'].update({'enabled': True, 'applyAutoWhiteBalance': True, + 'applyLocalContrast': True}) + return j + + +def run(j, templates=None): + target = os.path.join(os.path.dirname(worker), 'templates') + if templates: + if os.path.exists(target): + raise SystemExit(f'{target} exists; remove it first') + shutil.copytree(templates, target) + try: + cfg = os.path.join(scratch, f'job_{j["id"]}.json') + json.dump(j, open(cfg, 'w')) + t = time.perf_counter() + r = subprocess.run([worker, '--config', cfg], capture_output=True, text=True) + dt = time.perf_counter() - t + if r.returncode != 0: + print(r.stdout[-3000:], r.stderr[-3000:]) + raise SystemExit(f'job failed ({r.returncode})') + os.remove(j['outputPath']) + return dt + finally: + if templates: + shutil.rmtree(target) + + +rows = [ + ('SMDegrain + LSFmod', False, None), + ('+ Colour Correction (auto WB + CLAHE), before', True, old_templates), + ('+ Colour Correction (auto WB + CLAHE), after', True, None), +] +for label, colour, templates in rows: + dt = min(run(job(colour), templates) for _ in range(2)) + print(f'{label:48s} {frames} frames {dt:7.1f} s {frames / dt:6.1f} fps', flush=True) diff --git a/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/probe_akarin_levels.py b/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/probe_akarin_levels.py new file mode 100644 index 00000000..daf91c12 --- /dev/null +++ b/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/probe_akarin_levels.py @@ -0,0 +1,62 @@ +"""Issue #253: can auto levels be one akarin expression that reads the measured +black and white points from frame properties, bit-identical to std.Levels? + +No. std.Levels builds a lookup table from IEEE float arithmetic +(R78 genericfilters.cpp: clamp, (v - min_in) / (max_in - min_in), * range, ++ min_out, clamp, + 0.5, truncate). The same arithmetic in akarin.Expr is +compiled with fast-math, which turns the division into a multiplication by a +reciprocal; where the exact result is a .5 tie (e.g. 55 / 110 * 219 + 16 = +125.5) the reciprocal's rounding drops it to 125.4999 and the output one level. + +For seeded random (lo, hi) pairs at 8 bits and three output ranges, this +counts the pairs where any input sample differs from std.Levels, for three +spellings of the expression and both settings of akarin's `opt`. + +Usage: as probe_exact.py, with just . +""" +import random +import sys + +sys.path.insert(0, sys.argv[1]) +import vapoursynth as vs # noqa: E402 + +core = vs.core +base = core.std.BlankClip(width=256, height=2, format=vs.YUV420P8, length=1) +ramp = core.akarin.Expr(base, ['X', '', '']) +L, H = 'x._L', 'x._H' +variants = { + 'ternary (flat frame kept)': + lambda lt, ht: f'{H} {L} <= x x {L} max {H} min {L} - {H} {L} - / {ht - lt} * {lt} + 0.5 + floor 0 max 255 min ?', + 'plain': + lambda lt, ht: f'x {L} max {H} min {L} - {H} {L} - / {ht - lt} * {lt} + 0.5 + floor 0 max 255 min', + 'clamp, +0.5, trunc (std.Levels order)': + lambda lt, ht: f'x {L} max {H} min {L} - {H} {L} - / {ht - lt} * {lt} + 0 max 255 min 0.5 + trunc', +} +rng = random.Random(1) +bad = {(k, o): 0 for k in variants for o in (0, 1)} +cases = 0 +example = None +for _ in range(1500): + lo, hi = sorted(rng.randrange(256) for _ in range(2)) + if lo == hi: + continue + for lt, ht in ((16, 235), (0, 255), (40, 200)): + ref = core.std.Levels(ramp, min_in=lo, max_in=hi, min_out=lt, max_out=ht, planes=[0]).get_frame(0)[0] + st = core.std.SetFrameProps(ramp, _L=lo, _H=hi) + cases += 1 + for k, f in variants.items(): + for o in (0, 1): + out = core.akarin.Expr(st, [f(lt, ht), '', ''], opt=o).get_frame(0)[0] + diff = [v for v in range(256) if out[0, v] != ref[0, v]] + if diff: + bad[(k, o)] += 1 + if example is None: + v = diff[0] + example = (lo, hi, lt, ht, v, ref[0, v], out[0, v]) +print(f'(lo, hi, output range) cases: {cases}') +for (k, o), n in bad.items(): + print(f'{k:40s} opt={o}: {n} cases differ ({100.0 * n / cases:.1f}%)') +if example: + lo, hi, lt, ht, v, r, a = example + print(f'example: min_in={lo} max_in={hi} min_out={lt} max_out={ht} input {v}: ' + f'std.Levels {r}, akarin {a}') diff --git a/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/probe_exact.py b/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/probe_exact.py new file mode 100644 index 00000000..d8268566 --- /dev/null +++ b/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/probe_exact.py @@ -0,0 +1,90 @@ +"""Issue #253: does the rewritten automatic white balance give the same +picture as the one it replaced? + +Takes `_auto_white` verbatim from two copies of pipeline_template.vpy (the one +before the change, and the one after) and runs both on the same clips through +the deps bundle's VapourSynth. The new function runs twice: with akarin (the +path every bundle but macOS x64 takes) and with `_akarin_expr = None` (macOS +x64's fallback, a std.Expr per frame). + +Clips: 706x480 (the issue's size), 60 frames of AddGrain noise plus a chroma +cast that changes every frame, at 8/10/12/16 bits, 4:2:0/4:2:2/4:4:4, four +strengths. The fixtures use akarin.Expr (X, Y, N), so run it on a bundle that +has akarin. probe_white_rate.py runs the akarin path over more frames. + +Usage (macOS/Linux; the bundle's own Python): + PYTHONHOME=/python PYTHONPATH= XDG_CONFIG_HOME=/config \ + /python/bin/python3 -I probe_exact.py [--quick] +Prints one line per case and exits non-zero on any difference. +""" +import functools +import re +import sys + +deps, old_path, new_path = sys.argv[1:4] +quick = '--quick' in sys.argv +sys.path.insert(0, deps) +import vapoursynth as vs # noqa: E402 + +core = vs.core + + +def extract(path, name): + text = open(path, encoding='utf-8').read().replace('\r\n', '\n') + m = re.search(rf'^def {name}\(.*?(?=^\S)', text, re.S | re.M) + if not m: + raise SystemExit(f'{name} not found in {path}') + return m.group(0) + + +def load(path, name, akarin): + """The template's function, bound to akarin or (akarin=False) to std.Expr.""" + akarin_expr = getattr(getattr(core, 'akarin', None), 'Expr', None) if akarin else None + + def _expr(clips, expr, **kw): + if akarin_expr is not None: + return akarin_expr(clips, expr, **kw) + return core.std.Expr(clips, expr, **kw) + + ns = {'core': core, 'vs': vs, 'functools': functools, + '_akarin_expr': akarin_expr, '_expr': _expr} + exec(extract(path, name), ns) + return ns[name], ns + + +def maxdiff(a, b): + worst = 0 + d = core.std.Expr([a, b], 'x y - abs') + for p in range(a.format.num_planes): + for f in core.std.PlaneStats(d, plane=p).frames(): + worst = max(worst, f.props['PlaneStatsMax']) + return worst + + +def white_source(bits, sub, n): + fmt = core.query_video_format(vs.YUV, vs.INTEGER, bits, min(sub, 1), 1 if sub == 2 else 0).id + peak = (1 << bits) - 1 + c = core.std.BlankClip(width=706, height=480, format=fmt, length=n, + color=[peak // 2, 1 << (bits - 1), 1 << (bits - 1)]) + c = core.grain.Add(c, var=40, uvar=20, seed=1) + s = peak / 255.0 + return core.akarin.Expr([c], ['', + f'x N 13 % 1.37 * X 0.01 * + {s} * +', + f'x N 11 % 0.91 * Y 0.02 * - {s} * +']) + + +if __name__ == '__main__': + failures = 0 + for bits in (8, 10, 12, 16): + for sub, name in ((2, '4:2:0'), (1, '4:2:2'), (0, '4:4:4')): + c = white_source(bits, sub, 20 if quick else 60) + for strength in (0.0, 0.37, 0.8, 1.0): + ref = load(old_path, '_auto_white', akarin=True)[0](c, strength) + for akarin in (True, False): + d = maxdiff(ref, load(new_path, '_auto_white', akarin=akarin)[0](c, strength)) + failures += d != 0 + print(f'auto_white bits={bits} {name} strength={strength} ' + f'path={"akarin" if akarin else "fallback"} maxdiff={d}' + f'{"" if d == 0 else " <-- DIFFERS"}', flush=True) + print('FAILURES', failures) + sys.exit(1 if failures else 0) diff --git a/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/probe_white_rate.py b/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/probe_white_rate.py new file mode 100644 index 00000000..9b8b8597 --- /dev/null +++ b/docs/reports/issue-253-auto-colour-per-frame-expr/scripts/probe_white_rate.py @@ -0,0 +1,42 @@ +"""Issue #253: how often does the new automatic white balance (one akarin +expression reading the PlaneStats means as frame properties) differ from the +old one (a std.Expr / akarin expression per frame with the offset written in +as a 6-decimal literal), and by how much? + +akarin reads a frame property as a 32-bit float, so the mean (a double in +[0, 1]) loses precision: times a 16-bit peak, about 0.004 of a sample step. +Where the offset's fraction is that close to .5, the sum rounds the other way +and the whole plane of that frame is one sample step off. At 8-12 bits the +lost precision is under 0.0003 of a step. + +Per depth, subsampling and strength: frames whose output differs anywhere, +and the largest difference. Same clips as probe_exact.py, longer. + +Usage: as probe_exact.py: [frames] +""" +import sys + +deps, old_path, new_path = sys.argv[1:4] +N = int(sys.argv[4]) if len(sys.argv) > 4 else 600 +sys.path.insert(0, deps) +sys.argv = sys.argv[:4] +import os # noqa: E402 + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import probe_exact as pe # noqa: E402 + +for bits in (8, 10, 12, 16): + for sub, name in ((2, '4:2:0'), (1, '4:2:2'), (0, '4:4:4')): + c = pe.white_source(bits, sub, N) + for strength in (0.37, 0.8, 1.0): + old = pe.load(old_path, '_auto_white', akarin=True)[0] + new = pe.load(new_path, '_auto_white', akarin=True)[0] + d = pe.core.std.Expr([old(c, strength), new(c, strength)], 'x y - abs') + frames, worst = 0, 0 + for p in (1, 2): + for f in pe.core.std.PlaneStats(d, plane=p).frames(): + m = f.props['PlaneStatsMax'] + worst = max(worst, m) + frames += m > 0 + print(f'{bits:2d}-bit {name} strength={strength}: {frames} of {2 * N} ' + f'chroma planes differ, max {worst}', flush=True) diff --git a/worker/templates/pipeline_template.vpy b/worker/templates/pipeline_template.vpy index 11e3d67e..e2395f03 100644 --- a/worker/templates/pipeline_template.vpy +++ b/worker/templates/pipeline_template.vpy @@ -2152,6 +2152,13 @@ clip = _colorize.colorize( # # PlaneStatsMin/Max come back in the CLIP's own depth, so they are used raw; # only the user's targets, which are in 8-bit UI units, get scaled to the format. +# +# This builds a std.Levels per frame, which is cheap (a lookup table; ~5,000 +# fps for the filter alone at 706x480) and needs no change for speed. Don't +# turn it into one akarin expression reading the points from frame properties +# as the white balance below does: akarin compiles with fast-math, and its +# division puts a .5 tie on the other side of std.Levels' in ~2% of (min, max) +# pairs, one level off (issue #253, docs/reports/issue-253-auto-colour-per-frame-expr). def _auto_levels(c, black_8bit, white_8bit, strength): peak = (1 << c.format.bits_per_sample) - 1 to_fmt = lambda v: int(round(v * peak / 255.0)) @@ -2184,12 +2191,34 @@ clip = _auto_levels(clip, {{CC_AUTO_LEVELS_BLACK}}, {{CC_AUTO_LEVELS_WHITE}}, {{ # # Chroma means are averages already, so they are far steadier frame to frame # than the luma min/max above and need no outlier handling. +# +# With akarin the means are stamped on each frame by PlaneStats and ONE +# expression, compiled once, reads them (issue #253). This used to return a +# new expression per frame from a FrameEval, which on akarin is an LLVM compile +# per frame (~20 ms, serialised under the GIL): ~60 fps for this filter alone +# at 706x480, ~8,000 now. The output is identical at 8-12 bits; at 16 bits +# akarin reads the mean as a 32-bit float, and about 2 chroma planes in 1,000 +# come out one 16-bit step apart from the old per-frame literal. The fallback +# below is for macOS x64, which has no akarin; there each frame's std.Expr is +# cheap (docs/reports/issue-253-auto-colour-per-frame-expr). def _auto_white(c, strength): if c.format.num_planes < 3: return c # GRAY: PlaneStats(plane=1) would error bits = c.format.bits_per_sample peak = (1 << bits) - 1 neutral = 1 << (bits - 1) + + if _akarin_expr is not None: + st = core.std.PlaneStats(c, plane=1, prop='_AwbU') + st = core.std.PlaneStats(st, plane=2, prop='_AwbV') + out = _expr(st, [ + '', + f'x {neutral} x._AwbUAverage {peak} * - {strength} * +', + f'x {neutral} x._AwbVAverage {peak} * - {strength} * +', + ]) + return core.std.RemoveFrameProps( + out, props=[f'_Awb{p}{s}' for p in 'UV' for s in ('Min', 'Max', 'Average')]) + su = core.std.PlaneStats(c, plane=1) sv = core.std.PlaneStats(c, plane=2) diff --git a/worker/tests/filter_integration_test.rs b/worker/tests/filter_integration_test.rs index 8cfc3807..4fa3e1a9 100644 --- a/worker/tests/filter_integration_test.rs +++ b/worker/tests/filter_integration_test.rs @@ -10702,3 +10702,53 @@ fn test_270_both_scripts_end_with_the_pipe_output_tracker() { } } } + +/// Issue #253: automatic white balance must not build an expression per frame. +/// It returned a new `_expr` from a FrameEval on every frame, and on akarin +/// (every bundle but macOS x64) each one is an LLVM compile, serialised under +/// the GIL: ~60 fps for the filter alone at 706x480. With akarin it is now one +/// expression reading PlaneStats' frame properties, and the FrameEval is only +/// macOS x64's fallback, after that branch returns. Automatic levels stays a +/// per-frame std.Levels (cheap, and akarin's fast-math division would put +/// .5 ties a level off). +#[test] +fn test_271_auto_colour_builds_no_node_per_frame() { + create_output_dir(); + let mut job = create_base_job("test_271_auto_colour"); + job.qtgmc_parameters.enabled = false; + job.processing_pipeline = Some(ProcessingPipeline { + deinterlace: QTGMCParameters { enabled: false, ..QTGMCParameters::default() }, + color_correction: ColorCorrectionParameters { + enabled: true, + apply_auto_levels: true, + apply_auto_white_balance: true, + auto_white_balance_strength: 0.8, + ..ColorCorrectionParameters::default() + }, + ..ProcessingPipeline::default() + }); + let (encode, preview) = generate_both_scripts(&job); + for (side, script) in [("encode", &encode), ("preview", &preview)] { + let white = &script[script.find("def _auto_white(").expect("auto white block")..]; + let white = &white[..white.find("clip = _auto_white(").expect("auto white call")]; + let akarin = white.find("if _akarin_expr is not None:").expect("akarin branch"); + let branch = &white[akarin..]; + let branch_end = branch.find("\n return ").expect("akarin branch returns"); + let branch_end = branch_end + branch[branch_end..].find(")\n").expect("return ends"); + let (branch, fallback) = branch.split_at(branch_end); + assert!(branch.contains("x._AwbUAverage") && branch.contains("x._AwbVAverage"), + "{side}: the akarin branch must read the chroma means from frame properties"); + assert!(!branch.contains("FrameEval") && !branch.contains("def _apply"), + "{side}: the akarin branch must not evaluate anything per frame"); + assert!(!white[..akarin].contains("FrameEval"), + "{side}: nothing per frame may run before the akarin branch"); + assert!(fallback.contains("FrameEval"), "{side}: macOS x64 keeps the FrameEval fallback"); + assert!(script.contains("clip = _auto_white(clip, 0.8)"), "{side}"); + + let levels = &script[script.find("def _auto_levels(").expect("auto levels block")..]; + let levels = &levels[..levels.find("clip = _auto_levels(").expect("auto levels call")]; + assert!(levels.contains("core.std.Levels("), "{side}: auto levels stays std.Levels"); + assert!(!levels.contains("_expr("), + "{side}: auto levels stays std.Levels (bit-exact), never an expression"); + } +}