Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

feat: publish the capcodec encoder source

Richie McIlroyd36bfa5c2bf4
diff --git a/apps/media-server/capcodec-benchmarks.md b/apps/media-server/capcodec-benchmarks.md
index 5d3ec74bc..f412d8255 100644
--- a/apps/media-server/capcodec-benchmarks.md
+++ b/apps/media-server/capcodec-benchmarks.md
@@ -19,7 +19,7 @@ The 12-clip speed table is main `00fecf7` (read-ahead, CABAC, intra minIndex), r
Quality measured 2026-10-09 on main `fff504d`. Speed remeasured the same day on main `00fecf7` (read-ahead, pin7 intra minIndex, CABAC table). Those commits match the `fff504d` bitstreams, so the quality tables still describe this encoder. Pending quality branch `rd-next` `d0cce5e`. All 12 corpus clips.
-How to reproduce (in the capcodec tree; these scripts are not in this repository):
+How to reproduce (from the `capcodec/` directory in this repository):
- Quality: `CAPCODEC_BIN_UNCHECKED=<binary> python3 bench/bench.py standard --quality-only --encoders capcodec-medium,capcodec-live,capcodec-live-zerolatency,x264-veryfast,x264-veryfast-zerolatency --out <dir>` (1080p, 10 s per clip; code_4k is scaled to 1080p here). capcodec's CRF ladder runs 20-44 so its VMAF range covers x264's CRF 18-33; the overlap column shows how much of the two curves BD-rate compares (it was 15-24% on screen clips with the old 20-36 ladder).
- Speed: `bench/lane.sh start`, then `bench/lane.sh run "python3 bench/speedcmp.py --binary <binary> --clips all --modes medium,live,zerolatency --retime bench/out/speedcmp-fff504d-v2 --out <dir>"`. The rerun reuses the CRF that matched x264 CRF 23 (bitstreams are unchanged, so the match stands). 5 shuffled, interleaved rounds at 1 and 4 threads; every other process is stopped for each timed run (about 690 processes stopped, frozen median). code_4k runs at native 4K for 5 s. Output: `bench/out/speedcmp-00fecf7`.
diff --git a/apps/media-server/capcodec.md b/apps/media-server/capcodec.md
index ae9651c2d..ec5a4b361 100644
--- a/apps/media-server/capcodec.md
+++ b/apps/media-server/capcodec.md
@@ -11,4 +11,4 @@ To encode with capcodec:
Optional overrides: `CAPCODEC_CRF` (0–51), `CAPCODEC_PRESET` (`live`, `fast`, `medium`, `slow`), `CAPCODEC_KEYINT`, and `CAPCODEC_NOISE`. Without those, the job's CRF and preset are used. `ultrafast` maps to `fast`.
-Benchmark tables against x264 veryfast are in `capcodec-benchmarks.md`.
+Benchmark tables against x264 veryfast are in `capcodec-benchmarks.md`. The encoder source is `capcodec/` at the repository root.
diff --git a/biome.json b/biome.json
index e37af6e12..997ea30a3 100644
--- a/biome.json
+++ b/biome.json
@@ -13,7 +13,8 @@
"!apps/desktop/src/utils/tauri.ts",
"!apps/desktop/src/global.d.ts",
"!apps/web/public/gif.worker.js",
- "!packages/ui-solid/src/auto-imports.d.ts"
+ "!packages/ui-solid/src/auto-imports.d.ts",
+ "!capcodec"
],
"ignoreUnknown": false
},
diff --git a/capcodec/.gitignore b/capcodec/.gitignore
new file mode 100644
index 000000000..5cdca7f85
--- /dev/null
+++ b/capcodec/.gitignore
@@ -0,0 +1,9 @@
+/build/
+/bench/out/
+__pycache__/
+*.pyc
+*.yuv
+*.264
+*.h264
+*.mkv
+/tmp/
diff --git a/capcodec/CAP_BASELINES.md b/capcodec/CAP_BASELINES.md
new file mode 100644
index 000000000..95398295d
--- /dev/null
+++ b/capcodec/CAP_BASELINES.md
@@ -0,0 +1,1759 @@
+# Cap H.264 production encoding baselines
+
+This file lists the exact H.264 encoder settings used by each Cap surface, so a benchmark harness can reproduce them on Linux.
+
+## Sources and environment
+
+| Item | Value |
+|---|---|
+| Cap repo | `/workspace` on branch `main`, commit `d327051c1` (read only) |
+| PR 2312 | `FETCH_HEAD` = `549c5afa9` (`origin/feature/web-editor-desktop-parity`), read with `git show FETCH_HEAD:<path>` |
+| Rust ffmpeg bindings | `ffmpeg-next`, CapSoftware fork rev `49db1fede112` |
+| Verification ffmpeg | 6.1.1-3ubuntu5 |
+| Verification libx264 | core 164 r3108 |
+| Verification Chrome | Google Chrome 148.0.7778.96 at `/usr/local/bin/google-chrome`, headless |
+| Verification CPU | `nproc` = 4 |
+
+Line numbers refer to `main` unless marked "PR".
+
+A value marked "verified" was observed in an encode on this VM, either in ffprobe output or in the x264 SEI options string. A value marked "source" was read from code but not run. Hardware encoders (VideoToolbox, NVENC, QSV, AMF, Media Foundation, AVFoundation) cannot run on this VM.
+
+## Contents
+
+0. Conventions and shared facts
+1. Media server
+2. Web app server-side ffmpeg
+3. Render farm
+4. Desktop recording
+5. Desktop export
+6. Web recorders on `main` (MediaRecorder)
+7. Browser WebCodecs encoders on `main`
+8. PR 2312 differences
+9. Running browser surfaces in headless Chrome with Playwright
+10. Ambiguities and assumptions
+11. Summary table
+
+---
+
+## 0. Conventions and shared facts
+
+### 0.1 Placeholders
+
+| Placeholder | Meaning |
+|---|---|
+| `W`, `H` | Output width and height |
+| `FPS` | Frame rate |
+| `B` | Target bitrate in bit/s |
+| `M` | maxrate, always `B * 3 / 2` with integer division where Cap sets it |
+| `K` | Keyframe interval in frames |
+| `N` | `nproc` |
+
+All ffmpeg reproductions read raw input with:
+
+```
+-f rawvideo -pix_fmt yuv420p -s WxH -r FPS -i in.yuv
+```
+
+### 0.2 Shared bits-per-pixel (bpp) bitrate model
+
+Desktop export, desktop recording through `enc-ffmpeg`, the render farm, and the PR browser export all use this model.
+
+| Implementation | Location |
+|---|---|
+| `get_bitrate` | `crates/enc-ffmpeg/src/video/h264.rs` lines 1651-1658 |
+| `bitrate` | `crates/render-farm/src/video.rs` lines 184-187 |
+| `exportBitrate` (PR) | `packages/editor-solid-web/src/browser-export-estimate.ts` |
+
+The formula is:
+
+```
+B = W * H * ((max(FPS - 30, 0) * 0.6) + 30) * bpp
+M = B * 3 / 2 (Rust only: encoder.set_max_bit_rate(bitrate * 3 / 2))
+```
+
+How each implementation computes it:
+
+- **Rust:** bpp is an `f32`, widened to `f64`, and the result is truncated to `usize`. That gives slightly odd values, for example 29,859,841.
+- **PR browser export:** uses JavaScript `f64` with `Math.round`.
+
+Worked values for the Rust model, shown as `B (M)`:
+
+| bpp | 1280x720@30 | 1920x1080@30 | 1920x1080@60 | 3840x2160@30 |
+|---|---|---|---|---|
+| 1.0 | 27,648,000 (41,472,000) | 62,208,000 (93,312,000) | 99,532,800 (149,299,200) | 248,832,000 (373,248,000) |
+| 0.3 | 8,294,400 (12,441,600) | 18,662,400 (27,993,600) | 29,859,841 (44,789,761) | 74,649,602 (111,974,403) |
+| 0.18 | 4,976,640 (7,464,960) | 11,197,440 (16,796,160) | 17,915,904 (26,873,856) | 44,789,761 (67,184,641) |
+| 0.15 | 4,147,200 (6,220,800) | 9,331,200 (13,996,800) | 14,929,920 (22,394,880) | 37,324,801 (55,987,201) |
+| 0.08 | 2,211,839 (3,317,758) | 4,976,639 (7,464,958) | 7,962,623 (11,943,934) | 19,906,559 (29,859,838) |
+| 0.04 | 1,105,919 (1,658,878) | 2,488,319 (3,732,478) | 3,981,311 (5,971,966) | 9,953,279 (14,929,918) |
+
+Browser model (`Math.round`, `f64`), B only:
+
+| bpp | 1280x720@30 | 1920x1080@30 | 1920x1080@60 | 3840x2160@30 |
+|---|---|---|---|---|
+| 0.3 | 8,294,400 | 18,662,400 | 29,859,840 | 74,649,600 |
+| 0.15 | 4,147,200 | 9,331,200 | 14,929,920 | 37,324,800 |
+| 0.08 | 2,211,840 | 4,976,640 | 7,962,624 | 19,906,560 |
+| 0.04 | 1,105,920 | 2,488,320 | 3,981,312 | 9,953,280 |
+
+### 0.3 Shared keyframe interval
+
+`crates/enc-ffmpeg/src/video/h264.rs` lines 1223-1239:
+
+```
+DEFAULT_KEYFRAME_INTERVAL_SECS = 2
+K = round(2 * FPS).max(1)
+```
+
+| FPS | K |
+|---|---|
+| 30 | 60 |
+| 60 | 120 |
+
+The render farm uses `fps * 2` with integer fps (`crates/render-farm/src/video.rs` line 473; keyframe secs = 2 at line 629). That gives the same values.
+
+### 0.4 How Cap's x264 options reach libx264 (applies to every `enc-ffmpeg` and render-farm libx264 path)
+
+Options are passed as an AVDictionary to `open_as_with`, which calls `avcodec_open2`. Keys that libx264/AVCodecContext does not recognise are silently left unconsumed and ignored.
+
+| Key | Status |
+|---|---|
+| `preset`, `tune`, `crf`, `threads`, `bf`, `rc-lookahead`, `aq-mode`, `trellis`, `g`, `keyint_min` | Consumed |
+| `b-adapt` | Ignored. The real option name is `b_strategy`. |
+| `ref` | Ignored. The real option name is `refs`. |
+| `subme` | Ignored. The real option name is `subq`. |
+| `pix_fmt` | Ignored. It is not a codec option. |
+
+Effect, verified from the x264 SEI string:
+
+- The export/render-farm "fast" set produces `ref=1 subme=2`, which are the veryfast preset defaults. The intended `ref 2` never applies.
+- `subme 2` and `trellis 0` happen to equal the veryfast defaults.
+- `b-adapt` is irrelevant because `bf 0`.
+
+Two more x264 behaviours, both verified:
+
+- **`maxrate` is ignored.** Cap sets `rc_max_rate` (`M`) but never sets `rc_buffer_size`. x264 logs `VBV maxrate specified, but no bufsize, ignored`, so every Cap libx264 bitrate encode is plain ABR (`rc=abr`, no VBV).
+- **`keyint_min` is clamped.** Cap sets `keyint_min = K`. x264 clamps it to `K/2 + 1`, so 60 becomes 31 and 120 becomes 61.
+
+### 0.5 Shared `enc-ffmpeg` encoder context
+
+Source: `crates/enc-ffmpeg/src/video/h264.rs` lines 775-816.
+
+**Threading:** `threads = available_parallelism()` via `set_threading(Config::count(...))`.
+
+**Colour tags:**
+- colorspace BT709
+- color_range MPEG (limited)
+- color_primaries BT709
+- color_trc BT709
+
+**Rate control:**
+- CRF mode: `bit_rate = 0`.
+- Otherwise: `bit_rate = get_bitrate(out_w, out_h, fps, bpp)` and `max_bit_rate = bit_rate * 3 / 2`.
+
+**Timing:**
+- Encoder time base is the input `VideoInfo.time_base`.
+- Muxer stream time base is `1/90000` (lines 286 and 413).
+
+**Pixel format (lines 671-688):**
+- Uses the input format if the encoder supports it.
+- Otherwise YUV420P for libx264 and NV12 for the others.
+
+**Scaler (lines 627-657):**
+- BICUBIC when resizing, FAST_BILINEAR otherwise.
+- RGB input uses BT.709 coefficients, full-range in, limited-range out.
+
+**Encoder priority:**
+
+| Platform | Order |
+|---|---|
+| macOS | `h264_videotoolbox`, `libx264` |
+| Windows, NVIDIA GPU | `h264_nvenc`, `h264_mf`, `h264_qsv`, `h264_amf`, `libx264` |
+| Windows, AMD GPU | `h264_amf`, `h264_mf`, `h264_nvenc`, `h264_qsv`, `libx264` |
+| Windows, Intel GPU | `h264_qsv`, `h264_mf`, `h264_nvenc`, `h264_amf`, `libx264` |
+| Windows, other or unknown GPU | `h264_nvenc`, `h264_qsv`, `h264_amf`, `h264_mf`, `libx264` |
+| Windows, GPU without hardware encoding | `libx264` |
+| Linux with `/dev/nvidiactl` present | `h264_nvenc`, `libx264` |
+| Linux otherwise | `libx264` |
+
+Sources: `get_default_encoder_priority` at lines 1133-1173 and `linux_encoder_priority` at lines 1124-1131.
+
+**Priority overrides:**
+- `CAP_EXPORT_FORCE_SOFTWARE_ENCODER` set to `1`, `true`, `yes` or `on` forces `libx264` (line 1192).
+- `requires_software_encoder` (line 1062) never applies to exports. For recordings it forces `libx264` when:
+ - the preset is `HighThroughput`, or
+ - on macOS/Windows, FPS is above 0.9 times the estimated hardware maximum.
+- A CRF request always forces `libx264` (line 1241).
+- Windows export with an AMD GPU uses `h264_amf`, `h264_mf`, `h264_nvenc`, `h264_qsv`, `libx264` (lines 1201-1221).
+
+**Fallback:** encoders are tried in priority order, and the first that opens is used.
+
+### 0.6 Option sets per encoder
+
+Source: `crates/enc-ffmpeg/src/video/h264.rs` lines 1258-1357, quoted literally.
+
+**`h264_videotoolbox`**
+
+| Mode | Options |
+|---|---|
+| Export | `realtime=false`, `profile=main`, `allow_sw=0` |
+| Recording | `realtime=true`, `prio_speed=true`, `profile=main` |
+
+No `g` is set in either mode.
+
+**`h264_nvenc`**
+
+| Mode | Options |
+|---|---|
+| Export | `preset=p5`, `tune=hq`, `rc=vbr`, `spatial-aq=1`, `temporal-aq=1`, `b_ref_mode=middle`, `g=K` |
+| Recording | `preset=p4`, `tune=ll`, `rc=vbr`, `spatial-aq=1`, `temporal-aq=1`, `g=K` |
+
+**`h264_qsv`**
+
+| Mode | Options |
+|---|---|
+| Export | `preset=medium`, `look_ahead=1`, `look_ahead_depth=20`, `g=K` |
+| Recording | `preset=faster`, `look_ahead=1`, `g=K` |
+
+**`h264_amf`**
+
+| Mode | Options |
+|---|---|
+| Export | `quality=quality`, `rc=vbr_peak`, `g=K` |
+| Recording | `quality=balanced`, `rc=vbr_latency`, `g=K` |
+
+**`h264_mf`**
+
+| Mode | Options |
+|---|---|
+| Export | `hw_encoding=true`, `scenario=0`, `quality=0`, `g=K` |
+| Recording | `hw_encoding=true`, `scenario=4`, `quality=1`, `g=K` |
+
+**`libx264`**, which branch applies:
+
+| Condition | Options |
+|---|---|
+| CRF requested | `preset=slow`, `crf=<crf>`, `pix_fmt=yuv420p` (ignored) |
+| Export, preset Slow | `preset=slow` |
+| Export, preset Medium | `preset=medium` |
+| Export, any other preset | `preset=veryfast`, `threads=N`, `bf=0`, `rc-lookahead=10`, `b-adapt=0` (ignored), `aq-mode=1`, `ref=2` (ignored), `subme=2` (ignored), `trellis=0` |
+| Recording, Slow or Medium | `preset=veryfast`, `tune=zerolatency` |
+| Recording, Ultrafast or HighThroughput | `preset=ultrafast`, `tune=zerolatency` |
+
+All `libx264` branches also set `g=K` and `keyint_min=K`.
+
+### 0.7 VideoToolbox and NVENC defaults that Cap inherits (source: FFmpeg 7.1)
+
+**VideoToolbox (`libavcodec/videotoolboxenc.c`):**
+- `vt_defaults` only sets `b`, `qmin` and `qmax`, so `gop_size` keeps the AVCodecContext default of 12.
+- Because Cap never sets `g` for VideoToolbox, `MaxKeyFrameInterval = 12` frames. This is not 2 s.
+- `max_b_frames` defaults to 0, so `AllowFrameReordering = false` (no B-frames).
+- `profile=main` maps to `kVTProfileLevel_H264_Main_AutoLevel`.
+- `rc_max_rate` maps to `kVTCompressionPropertyKey_DataRateLimits` as `[M/8 bytes, 1 s]`.
+
+**NVENC:**
+- `g` is set by Cap.
+- `bf` stays at -1, meaning the preset decides.
+- `refs` stays at 0 (default).
+- `rc-lookahead` and `bufsize` are not set by Cap.
+
+### 0.8 Audio summary
+
+| Surface | Audio |
+|---|---|
+| Media server processVideo | AAC 128k |
+| Media server edit | AAC 160k |
+| Render farm | AAC 320 kbps, 48 kHz |
+| Desktop `enc-ffmpeg` | AAC 320 kbps |
+
+The desktop value comes from `crates/enc-ffmpeg/src/audio/aac.rs` line 33: `OUTPUT_BITRATE: usize = 320 * 1000; // 128k`. The trailing comment is stale.
+
+---
+
+## 1. Media server (`apps/media-server`)
+
+Image: `apps/media-server/Dockerfile` uses `FROM oven/bun:1.4.0` plus apt `ffmpeg`, with no version pinned.
+
+### 1.1 MS-TRANSCODE: `processVideo` video transcode
+
+**Location:** `apps/media-server/src/lib/media-video.ts`.
+
+| Lines | What |
+|---|---|
+| 162-172 | `DEFAULT_OPTIONS` |
+| 47-50 | Level size constants |
+| 1288-1302 | `needsVideoTranscode` |
+| 1304-1306 | `needsAudioTranscode` |
+| 1405-1420 | `pickMobileSafeH264Level` |
+| 1483-1581 | `processVideo` |
+
+**Constants resolved from `DEFAULT_OPTIONS`:**
+
+| Option | Value |
+|---|---|
+| maxWidth | 1920 |
+| maxHeight | 1080 |
+| crf | 23 |
+| preset | `"medium"` |
+| audioBitrate | `"128k"` |
+| videoBitrate | `"5M"` (defined, never used in any argument) |
+| remuxOnly | false |
+| normalizeH264Level | false |
+
+**Literal argument vector when `videoTranscode` is true:**
+
+```
+ffmpeg -threads 2 [extraInputArgs] -i <in>
+ -c:v libx264 -preset medium -crf 23
+ -vf "scale='min(1920,iw)':'min(1080,ih)':force_original_aspect_ratio=decrease,scale=trunc(iw/2)*2:trunc(ih/2)*2"
+ -pix_fmt yuv420p -level:v <4.2|5.1|5.2>
+ [-bf 0] # only when source codec is vp8 or vp9
+ <-c:a aac -b:a 128k | -c:a copy | -an>
+ -movflags +faststart [extraOutputArgs] -progress pipe:2 -y <out>.mp4
+```
+
+**When it runs.** `needsVideoTranscode` is true when any of these hold:
+
+- source width > maxWidth, or height > maxHeight
+- the codec is not `h264`
+- the probed source H.264 level is above the target level
+
+**Level choice** (`pickMobileSafeH264Level`) uses the target size `(min(srcW, maxW), min(srcH, maxH))`:
+
+| Target size | Level |
+|---|---|
+| ≤2048x1088 | `4.2` |
+| ≤4096x2304 | `5.1` |
+| Larger | `5.2` |
+
+With the defaults every transcode is level 4.2.
+
+**Callers:**
+
+| Caller | Options passed | Effect |
+|---|---|---|
+| Web workflows (`process-video.ts`, admin reprocess) | No size or quality options | Defaults apply: a 1080p cap, level 4.2 |
+| `/video/convert` (`routes/video.ts` line 594) | Source dimensions as max | No downscale; 4K gets level 5.1 |
+| Multipart (`multipart.ts` line 977) | `remuxOnly: true` for web MP4 | Video and audio copied |
+
+**Audio:**
+- Source audio is AAC: `-c:a copy`.
+- Other source audio: `-c:a aac -b:a 128k`.
+- No audio: `-an`.
+
+**Resilient mode.** The retry path adds these flags, built at `routes/video.ts` lines 842-847:
+
+| Position | Flags |
+|---|---|
+| Input | `-err_detect ignore_err -fflags +genpts+discardcorrupt` |
+| Output | `-max_muxing_queue_size 1024` |
+
+**Encoder settings:**
+
+| Setting | Value |
+|---|---|
+| Encoder | libx264 |
+| Rate control | CRF 23. No bitrate cap or VBV. |
+| GOP | x264 defaults: keyint 250, keyint_min 25, scenecut 40 (verified) |
+| B-frames, VP8/VP9 source | `-bf 0` (verified bframes=0) |
+| B-frames, other sources | x264 medium default bframes=3 |
+| Preset / tune | `medium`, no tune |
+| x264 internals at medium | ref=3, subme=7, trellis=1, rc_lookahead=40 (verified) |
+| Profile | High (x264 automatic, verified) |
+| Level | Forced by `-level:v` (verified 42) |
+| Pixel format | yuv420p |
+
+**Threads.** `-threads 2` is placed before `-i`, so it applies to the decoder only. The encoder uses ffmpeg's automatic count: verified threads=6 on 4 cores.
+
+**Colour.** No colour options are set, so tags are passed through from the decoder. Untagged sources stay untagged.
+
+**Scaling:**
+- First: fit inside 1920x1080, preserving aspect ratio, never upscaling.
+- Then: round both dimensions down to even.
+- Scaler flags: swscale default (bicubic).
+
+**Frame rate:**
+- No `-r`, no fps filter, no `-fps_mode`/`-vsync`.
+- The ffmpeg CLI `fps_mode auto` picks CFR for the MP4 muxer, so VFR browser captures are duplicated/dropped to the rate ffmpeg guesses for the input.
+- Verified: a VFR WebM tagged 30/1 came out as 90 frames at 30/1.
+
+**Container:** MP4 with `+faststart`. Audio, when transcoded, is AAC 128k.
+
+**Reproduction on Linux (verified):**
+
+```
+ffmpeg -y -threads 2 -f rawvideo -pix_fmt yuv420p -s WxH -r FPS -i in.yuv \
+ -c:v libx264 -preset medium -crf 23 \
+ -vf "scale='min(1920,iw)':'min(1080,ih)':force_original_aspect_ratio=decrease,scale=trunc(iw/2)*2:trunc(ih/2)*2" \
+ -pix_fmt yuv420p -level:v 4.2 -an -movflags +faststart ms_transcode.mp4
+```
+
+- **MS-TRANSCODE-VPX:** add `-bf 0` before `-an`. This is the variant that applies to Chrome WebM recordings on `main`.
+- **3840x2160 input:** with default options, the output is 1920x1080 at level 4.2.
+
+### 1.2 MS-LEVELFIX: level rewrite without re-encode (dormant)
+
+**Location:** `media-video.ts` lines 1533-1539.
+
+```
+ffmpeg -threads 2 -i <in> -c:v copy -bsf:v h264_metadata=level=<4.2|5.1|5.2> ... -movflags +faststart -progress pipe:2 -y <out>
+```
+
+It runs only when `opts.normalizeH264Level` is true and the source fits inside the size limits with a level above the target. No caller sets `normalizeH264Level`, so this is not reached in production. A too-high level instead causes a full MS-TRANSCODE.
+
+### 1.3 Other media-server ffmpeg invocations (no H.264 encode)
+
+**Copy path:** `-c:v copy` in `processVideo`, used for H.264 sources within the size and level limits.
+
+**Container repair** (`media-video.ts` lines 1325-1361):
+
+```
+ffmpeg -threads 2 -err_detect ignore_err -fflags +genpts+igndts -i <in> -c copy -y <out>.mkv
+```
+
+**Edit concat** (`media-edit.ts` `buildConcatArgs`, line 207):
+
+```
+ffmpeg -hide_banner -y -f concat -safe 0 -i <list> -map 0 -c copy -movflags +faststart <out>
+```
+
+**Unused:** `buildTranscodeSegmentArgs` and `buildStreamCopySegmentArgs` in `media-edit.ts` have no callers.
+
+### 1.4 MS-EDIT: edited-video render (`renderEditedVideo`)
+
+**Location:** `apps/media-server/src/lib/media-edit.ts`.
+
+| Lines | What |
+|---|---|
+| 83-87 | `getOutputFps` |
+| 151-205 | `buildTranscodeEditArgs` |
+| 446-469 | `renderEditedVideo` |
+
+It is called from `routes/video.ts` line 1168.
+
+**Inputs and constants:**
+- `fps` is the probed `metadata.fps`.
+- `getOutputFps(fps) = min(120, max(1, round(fps*100)/100))`, or `DEFAULT_OUTPUT_FPS` = 30 when fps is missing or invalid.
+- Up to `MAX_TRANSCODE_RANGES_PER_BATCH` = 4 ranges per ffmpeg run. Multiple batches are joined by the concat copy in section 1.3.
+
+**Literal arguments:**
+
+```
+ffmpeg -hide_banner -y
+ (-ss <start> -t <dur> -i <in>) x ranges
+ -filter_complex "[i:v:0]fps=F,setpts=PTS-STARTPTS[vi];[i:a:0]asetpts=PTS-STARTPTS[ai];...;[v0][a0]...concat=n=R:v=1:a=1[v][a]"
+ -map [v] -c:v libx264 -preset fast -crf 18 -pix_fmt yuv420p -enc_time_base:v 1/F
+ (-map [a] -c:a aac -b:a 160k | -an)
+ -movflags +faststart <out>
+```
+
+Without audio, each video filter is `[i:v:0]fps=F,setpts=PTS-STARTPTS[vi]` and the concat is `concat=n=R:v=1:a=0[v]`.
+
+**Encoder settings:**
+
+| Setting | Value |
+|---|---|
+| Encoder | libx264 |
+| Rate control | CRF 18 |
+| GOP | x264 default keyint 250, min 25 |
+| B-frames | x264 fast default bframes=3, b_adapt=1 (verified has_b_frames=2) |
+| Preset / tune | `fast`, no tune |
+| x264 internals at fast | ref=2, subme=6, rc_lookahead=30 (verified) |
+| Profile | High (verified) |
+| Level | x264 automatic (verified 3.1 at 720p30) |
+| Pixel format | yuv420p |
+| Colour | Passed through from input |
+
+**Frame rate:** CFR at `F`, enforced by the `fps` filter, with `-enc_time_base:v 1/F`.
+
+**Container and audio:** MP4 with `+faststart`; AAC 160k.
+
+**Reproduction on Linux** (single range, no audio, exactly the filter string the code builds; verified):
+
+```
+ffmpeg -hide_banner -y -f rawvideo -pix_fmt yuv420p -s WxH -r FPS -i in.yuv \
+ -filter_complex "[0:v:0]fps=FPS,setpts=PTS-STARTPTS[v0];[v0]concat=n=1:v=1:a=0[v]" \
+ -map "[v]" -c:v libx264 -preset fast -crf 18 -pix_fmt yuv420p -enc_time_base:v 1/FPS \
+ -an -movflags +faststart ms_edit.mp4
+```
+
+---
+
+## 2. Web app server-side ffmpeg
+
+### 2.1 WEB-LOOM-FFMPEG: Loom download conversion
+
+**Location:** `apps/web/lib/video-convert.ts`, used by `app/api/tools/loom-download/route.ts`.
+
+It first tries a remux (line 212):
+
+```
+ffmpeg -y -i <url> -c copy -movflags +faststart <out>
+```
+
+If the remux fails, it re-encodes (line 223):
+
+```
+ffmpeg -y -i <url> -c:v libx264 -preset veryfast -pix_fmt yuv420p -c:a aac -b:a 128k -movflags +faststart <out>
+```
+
+**Encoder settings:**
+
+| Setting | Value |
+|---|---|
+| Rate control | CRF 23 (libx264 default, no `-crf` given) |
+| GOP | 250/25 |
+| B-frames | veryfast default bframes=3 (verified has_b_frames=2) |
+| Profile / level | High, automatic level (verified 3.1 at 720p30) |
+| Frame rate | CLI auto, so CFR for MP4 |
+| Colour | Passed through |
+| Container | MP4 `+faststart` |
+| Audio | AAC 128k |
+
+**Reproduction on Linux (verified):**
+
+```
+ffmpeg -y -f rawvideo -pix_fmt yuv420p -s WxH -r FPS -i in.yuv \
+ -c:v libx264 -preset veryfast -pix_fmt yuv420p -an -movflags +faststart web_loom_ffmpeg.mp4
+```
+
+---
+
+## 3. Render farm
+
+### 3.1 Runtime configuration
+
+**Location:** `apps/render-farm/Dockerfile`.
+
+- Base image: Debian trixie, using Debian's ffmpeg.
+- Lines 47-49:
+ ```
+ ENV RF_ENCODER=h264_nvenc
+ ENV RF_NVENC_PRESET=p1
+ ENV RF_REQUIRE_GPU=1
+ ```
+
+**Encoder selection and fallback:**
+- In code, `RF_ENCODER` defaults to `"libx264"` (`crates/render-farm/src/video.rs` line 425). Production sets NVENC through the Dockerfile.
+- There is no automatic NVENC to libx264 fallback.
+- If NVENC is unavailable, `find_by_name` fails (`"{encoder_name} unavailable"`).
+- `RF_REQUIRE_GPU` checks at `video.rs` lines 257 and 364 fail fast without a GPU.
+- libx264 is used only when `RF_ENCODER` is overridden.
+
+**Job defaults** (`apps/render-farm/src/coordinator.ts` lines 374-384):
+
+| Field | Value |
+|---|---|
+| compression | `Maximum` |
+| fps | 30 |
+| resolution | `[1920, 1080]` |
+| Worker threads per task | 8 (line 1067) |
+
+**Compression map** (`apps/render-farm/src/protocol.ts` `COMPRESSION_BPP`):
+
+| Compression | bpp |
+|---|---|
+| Maximum | 0.3 |
+| Social | 0.15 |
+| Web | 0.08 |
+| Potato | 0.04 |
+
+### 3.2 RF-RENDER-NVENC and RF-RENDER-X264: chunked render encode
+
+**Location:** `crates/render-farm/src/video.rs` `encode`, lines 415-512.
+
+**Common settings, both encoders:**
+
+| Setting | Value |
+|---|---|
+| Input pixel format | NV12, or CUDA surfaces when NVENC and the renderer produced GPU frames (Linux) |
+| Time base | `1/fps` |
+| Frame rate | `fps/1` (CFR; frame-numbered) |
+| Colour | BT709 colorspace, MPEG (limited) range, BT709 primaries, BT709 trc |
+| Bitrate | `bit_rate = bitrate(W, H, fps, bpp)`, `max_bit_rate = B * 3 / 2` |
+| Flags | `GLOBAL_HEADER` |
+| K | `fps * 2` |
+
+**NVENC dictionary (production):**
+
+| Option | Value |
+|---|---|
+| preset | `RF_NVENC_PRESET` or `"p1"` |
+| tune | `RF_NVENC_TUNE` or `"hq"` |
+| rc | `constqp` with `qp=0` if tune is `"lossless"`, otherwise `vbr` |
+| spatial-aq | `RF_NVENC_SAQ` or `"1"` |
+| temporal-aq | `RF_NVENC_TAQ` or `"1"` |
+| bf | `0` |
+| g | K |
+| forced-idr | `1` |
+
+NVENC does not get the thread setting.
+
+**libx264 dictionary (override only):**
+
+| Option | Value |
+|---|---|
+| preset | `veryfast` |
+| threads | `8` |
+| bf | `0` |
+| rc-lookahead | `10` |
+| b-adapt | `0` (ignored) |
+| aq-mode | `1` |
+| ref | `2` (ignored) |
+| subme | `2` (ignored) |
+| trellis | `0` |
+| g | K |
+| keyint_min | K |
+
+The context threading count is also 8.
+
+**Rate control:**
+- NVENC: VBR with average B and max M. bufsize is not set, so NVENC's default VBV applies.
+- libx264: ABR at B, maxrate ignored (verified `rc=abr bitrate=8294` at 720p30, Maximum).
+
+**GOP:**
+- NVENC: K with forced IDR. Each HLS segment of `round(fps*2)` frames is one GOP.
+- libx264: keyint K, keyint_min clamped to K/2+1 (verified 60/31), scenecut 40, no B-frames.
+
+**Profile and level:**
+- NVENC: not set, so the encoder picks it. The preset decides profile; High is expected.
+- libx264: High, automatic level (verified High).
+
+**Container.** The farm writes its own boxes rather than using ffmpeg's muxer:
+
+- **MP4** (`apps/render-farm/src/mp4.ts`):
+ - `buildHeader` (line 654) writes `ftyp` (major `isom`, minor `0x200`, brands `isom iso2 avc1 mp41`), then `moov`, `free`, `mdat`. The moov is up front.
+ - Video timescale is `fps*1000` and sample delta is 1000 (CFR).
+ - The `avc1` entry (line 584) carries `colr nclx 1/1/1/0` and `pasp`.
+- **HLS** (`RF_HLS` is on unless it is `"0"`; `RF_HLS_SEGMENT_SECONDS` defaults to 2; `coordinator.ts` lines 94-95):
+ - Segments are fMP4 with `init.mp4` (line 1981) plus `styp+moof+mdat` `.m4s` files.
+ - Segment keys are `${prefix}/c${chunk}-p${firstPart}-${index}.m4s` (`hls.ts` line 40).
+ - `segmentFrames = round(fps*2)` (line 1087).
+ - The playlist (`fmp4.ts` lines 267-285) has `#EXT-X-VERSION:7`, `#EXT-X-TARGETDURATION:<HLS_SEGMENT_SECONDS+2>` = 4, `#EXT-X-MEDIA-SEQUENCE:0`, `#EXT-X-PLAYLIST-TYPE:EVENT`, `#EXT-X-INDEPENDENT-SEGMENTS`, `#EXT-X-MAP`, `#EXTINF:<toFixed(3)>` and `#EXT-X-ENDLIST`.
+
+**Audio:** AAC at 320,000 bit/s and 48,000 Hz (`crates/render-farm/src/audio.rs`).
+
+**Worked bitrates at Maximum (bpp 0.3):**
+
+| Resolution | B | M |
+|---|---|---|
+| 1920x1080@30 (job default) | 18,662,400 | 27,993,600 |
+| 1920x1080@60 | 29,859,841 | 44,789,761 |
+| 1280x720@30 | 8,294,400 | |
+| 3840x2160@30 | 74,649,602 | |
+
+Other compressions follow the table in section 0.2.
+
+**Reproduction on Linux.**
+
+RF-RENDER-X264 (verified; the x264 SEI matches `ref=1 subme=2 trellis=0 threads=8 keyint=60 keyint_min=31 rc_lookahead=10 rc=abr bitrate=8294`):
+
+```
+ffmpeg -y -f rawvideo -pix_fmt yuv420p -s WxH -r FPS -i in.yuv \
+ -pix_fmt nv12 -c:v libx264 -preset veryfast -threads 8 -b:v B -maxrate M \
+ -bf 0 -rc-lookahead 10 -aq-mode 1 -trellis 0 -g K -keyint_min K \
+ -colorspace bt709 -color_primaries bt709 -color_trc bt709 -color_range tv \
+ -an -movflags +faststart rf_render_x264.mp4
+```
+
+- `-maxrate` is included because the production code sets it. It has no effect without `-bufsize`.
+- The farm's own MP4 writer is approximated with `-movflags +faststart` (moov first).
+
+HLS approximation (verified to produce `#EXT-X-VERSION:7`, `PLAYLIST-TYPE:EVENT`, `INDEPENDENT-SEGMENTS`, `EXT-X-MAP init.mp4`). Replace the last line of the previous command with:
+
+```
+ -f hls -hls_time 2 -hls_segment_type fmp4 -hls_playlist_type event \
+ -hls_fmp4_init_filename init.mp4 -hls_flags independent_segments out/rf.m3u8
+```
+
+This approximation differs from production in two ways:
+- ffmpeg writes TARGETDURATION 2, while the farm writes 4.
+- Segment names differ.
+
+RF-RENDER-X264-INTENDED is not production. It shows what the dictionary was meant to do: add `-refs 2 -subq 2 -b_strategy 0`.
+
+RF-RENDER-NVENC cannot run on this VM. On an NVIDIA host:
+
+```
+ffmpeg -y -f rawvideo -pix_fmt yuv420p -s WxH -r FPS -i in.yuv \
+ -pix_fmt nv12 -c:v h264_nvenc -preset p1 -tune hq -rc vbr -b:v B -maxrate M \
+ -spatial-aq 1 -temporal-aq 1 -bf 0 -g K -forced-idr 1 \
+ -colorspace bt709 -color_primaries bt709 -color_trc bt709 -color_range tv \
+ -an -movflags +faststart rf_render_nvenc.mp4
+```
+
+### 3.3 RF-TRANSCODE: source preparation before rendering
+
+**Location:** `apps/render-farm/src/transcode.ts`.
+
+| Lines | What |
+|---|---|
+| 7-49 | `transcodeArgs` |
+| 56 | `MAX_REMUX_KEYFRAME_GAP_SECONDS = 4` |
+| 77-111 | `canRemux` |
+| 113 | `remuxArgs` |
+
+`worker.ts` line 705 sets `TRANSCODE_ENCODER = process.env.RF_TRANSCODE_ENCODER ?? "h264_nvenc"`. `keyframeSeconds` is `TRANSCODE_KEYFRAME_SECONDS = 1` (`coordinator.ts` line 1551).
+
+**Remux path.** It is used when `canRemux` is true:
+- codec h264
+- `yuv420p`
+- `has_b_frames=0`
+- every packet has pts == dts
+- keyframe gaps ≤ 4 s, including the tail
+
+```
+ffmpeg -hide_banner -nostdin -y -loglevel error -progress pipe:1 -nostats -i <in> -map 0:v:0 -an -c:v copy -movflags +faststart <out>
+```
+
+**Transcode path, literal** (with `keyframeSeconds = 1`):
+
+```
+ffmpeg -hide_banner -nostdin -y -loglevel error -progress pipe:1 -nostats
+ [-hwaccel cuda] # NVENC only
+ -i <in> -map 0:v:0 -an -fps_mode passthrough -pix_fmt yuv420p -c:v <encoder>
+ NVENC: -preset p1 -rc vbr -cq 19 -b:v 0
+ libx264: -preset veryfast -crf 18
+ -bf 0 -force_key_frames "expr:gte(t,n_forced*1)"
+ [-forced-idr 1] # NVENC only
+ -movflags +faststart <out>
+```
+
+**Encoder settings:**
+
+| Setting | NVENC (production default) | libx264 |
+|---|---|---|
+| Rate control | Constant-quality VBR, `-cq 19`, `-b:v 0` | CRF 18 |
+| Preset | p1 | veryfast |
+| Keyframes | Forced every 1 s, as IDR | Forced every 1 s, on top of x264 keyint 250 / min 25 / scenecut 40 |
+| B-frames | None | None |
+
+- **Profile and level:** encoder automatic. libx264 verified High.
+- **Frame rate:** `-fps_mode passthrough` keeps the source VFR timestamps.
+- **Colour:** passed through.
+- **Container:** MP4 `+faststart`, video only.
+- **Hardware decode:** `-hwaccel cuda` decodes on the GPU but frames are downloaded (no `-hwaccel_output_format`), so `-pix_fmt yuv420p` applies.
+
+**Reproduction on Linux.**
+
+RF-TRANSCODE-X264 (verified keyframes at 0, 1, 2 s, bframes=0, High):
+
+```
+ffmpeg -hide_banner -nostdin -y -f rawvideo -pix_fmt yuv420p -s WxH -r FPS -i in.yuv \
+ -map 0:v:0 -an -fps_mode passthrough -pix_fmt yuv420p -c:v libx264 -preset veryfast -crf 18 \
+ -bf 0 -force_key_frames "expr:gte(t,n_forced*1)" -movflags +faststart rf_transcode_x264.mp4
+```
+
+RF-TRANSCODE-NVENC cannot run on this VM:
+
+```
+ffmpeg -hide_banner -nostdin -y -hwaccel cuda -i in.mp4 -map 0:v:0 -an -fps_mode passthrough \
+ -pix_fmt yuv420p -c:v h264_nvenc -preset p1 -rc vbr -cq 19 -b:v 0 -bf 0 \
+ -force_key_frames "expr:gte(t,n_forced*1)" -forced-idr 1 -movflags +faststart rf_transcode_nvenc.mp4
+```
+
+---
+
+## 4. Desktop recording
+
+### 4.1 Common facts
+
+**Defaults** (`crates/recording/src/defaults.rs`):
+
+| Constant | Value |
+|---|---|
+| `DEFAULT_STUDIO_MAX_FPS` | 60 |
+| `CAMERA_ACTIVE_STUDIO_MAX_FPS` | 30 |
+| `DEFAULT_INSTANT_MODE_FPS` | 30 |
+| `FREE_INSTANT_MODE_MAX_RESOLUTION` | 1280 |
+| `PRO_INSTANT_MODE_MAX_RESOLUTION` | 1920 |
+| `DEFAULT_CRASH_RECOVERY_RECORDING` | true, so fragmented recording is the default |
+| `DEFAULT_OUT_OF_PROCESS_MUXER` | false |
+
+- Default studio quality is `Compatibility` if total RAM is under 16 GiB, else `Balanced`. `Ultra` is opt-in.
+- Instant mode clamps the output to fit `(max, max*9/16)`: 1280x720 for free users, 1920x1080 for Pro (`instant_recording.rs` lines 719-734).
+
+**Timestamps (all `enc-ffmpeg` recording paths):**
+- `VideoInfo.time_base = 1/1_000_000` (`crates/media-info/src/lib.rs` lines 47, 58, 89).
+- `update_pts` (`crates/enc-ffmpeg/src/base.rs` lines 76-104) sets `pts = round(capture_ts_secs * 1e6) - first_pts`.
+- So output is VFR, following capture timestamps.
+- `frame_rate` is the capture rate. It is used only for bitrate and K.
+
+**Fragmented container.** `SegmentedVideoEncoder` (`crates/enc-ffmpeg/src/mux/segmented_stream.rs` lines 195-240) uses the ffmpeg `dash` muxer writing `dash_manifest.mpd`:
+
+| Muxer option | Value |
+|---|---|
+| `init_seg_name` | `init.mp4` |
+| `media_seg_name` | `segment_$Number%03d$.m4s` |
+| `seg_duration` | `<secs>` |
+| `use_timeline` | `1` |
+| `use_template` | `1` |
+| `single_file` | `0` |
+| `hls_playlist` | `1` |
+
+Output files, verified: `init.mp4`, `segment_001.m4s`, ..., `master.m3u8`, and `media_0.m3u8` (`#EXT-X-VERSION:6` with `PROGRAM-DATE-TIME`).
+
+### 4.2 Linux (X11 capture)
+
+**Location:** `crates/recording/src/capture_pipeline.rs` lines 374-430, and `crates/recording/src/output_pipeline/ffmpeg.rs`.
+
+**Studio:** `SegmentedVideoMuxer`, 2 s segments, preset `Medium` when quality is Ultra, otherwise `Ultrafast`.
+
+**Instant:** `SegmentedVideoMuxer`, 2 s segments, preset `Ultrafast`, output size clamped as in section 4.1.
+
+**bpp is always 0.3.** `start_encoder` (`ffmpeg.rs` lines 648-672) hardcodes `bpp: H264EncoderBuilder::QUALITY_BPP` (0.3) for every quality and for instant mode. Instant mode does not use 0.15 here, unlike macOS and Windows. `prefer_videotoolbox_hw_input` is false.
+
+**Camera:** `SegmentedVideoMuxer` with a 3 s segment (line 825). The muxer default is 3 s (line 471).
+
+**Encoder:** `/dev/nvidiactl` present gives `h264_nvenc` (recording set: p4, ll, vbr, AQ, `g=K`), otherwise `libx264`.
+
+**libx264 settings:**
+
+| Quality | Preset / tune |
+|---|---|
+| Balanced or Compatibility | `ultrafast` + `zerolatency` |
+| Ultra (preset Medium) | `veryfast` + `zerolatency` |
+
+| Setting | Value |
+|---|---|
+| Rate control | ABR at B (bpp 0.3), maxrate ignored |
+| GOP | keyint K, keyint_min clamped to K/2+1 |
+| Scenecut | 0 (zerolatency) |
+| B-frames | None |
+| Pixel format | yuv420p, converted from capture format by swscale (BT.709, full-range in, limited out) |
+| Colour | BT.709 tags |
+
+**Verified ultrafast/zerolatency output at 720p30:**
+- Constrained Baseline, level 3.2
+- `cabac=0 ref=1 subme=0 trellis=0 8x8dct=0 sliced_threads=1 bframes=0 keyint=60 keyint_min=31 scenecut=0 rc=abr mbtree=0 aq=0`
+
+**Worked B at bpp 0.3:**
+
+| Resolution | B |
+|---|---|
+| 1280x720@30 | 8,294,400 |
+| 1920x1080@30 | 18,662,400 |
+| 1920x1080@60 | 29,859,841 |
+| 3840x2160@30 | 74,649,602 |
+
+K is 60 at 30 fps and 120 at 60 fps.
+
+**Audio:** AAC 320 kbps via `enc-ffmpeg`.
+
+**Reproduction on Linux.**
+
+DESK-REC-X264 (verified):
+
+```
+mkdir -p out && ffmpeg -y -f rawvideo -pix_fmt yuv420p -s WxH -r FPS -i in.yuv \
+ -c:v libx264 -preset ultrafast -tune zerolatency -threads N -b:v B -maxrate M -g K -keyint_min K \
+ -pix_fmt yuv420p -colorspace bt709 -color_primaries bt709 -color_trc bt709 -color_range tv -an \
+ -f dash -seg_duration 2 -use_timeline 1 -use_template 1 -single_file 0 -hls_playlist 1 \
+ -init_seg_name init.mp4 -media_seg_name 'segment_$Number%03d$.m4s' out/dash_manifest.mpd
+```
+
+DESK-REC-X264-ULTRA: the same command with `-preset veryfast`. B stays at bpp 0.3 on Linux.
+
+Difference from production: the raw input is CFR. Production uses VFR capture timestamps in a 1/1e6 time base.
+
+### 4.3 macOS (cannot run on this VM)
+
+**Fragmented studio (default)** (`capture_pipeline.rs` lines 113-226):
+
+- Muxer: `MacOSFragmentedM4SMuxer`, or the out-of-process muxer when enabled. Both use `SegmentedVideoEncoder`.
+- `prefer_videotoolbox_hw_input` is true for screen (`macos_fragmented_m4s.rs` line 295) and false for camera (line 682).
+- Defaults (lines 185-187): 2 s segments, `Ultrafast`, bpp 0.3.
+
+| Quality | bpp | Preset |
+|---|---|---|
+| Ultra | 1.0 | Medium |
+| Compatibility | 0.15 | Ultrafast |
+| Balanced | 0.3 | Ultrafast |
+
+**DESK-REC-VT** (`h264_videotoolbox`, recording set):
+
+| Setting | Value |
+|---|---|
+| Options | `realtime=true`, `prio_speed=true`, `profile=main` |
+| Bitrate | B; `DataRateLimits` = M/8 bytes per 1 s |
+| GOP | 12 frames (FFmpeg default; Cap sets no `g`) |
+| B-frames | None (frame reordering off) |
+| Level | Main AutoLevel |
+| Input | NV12 hardware surfaces, no scaling |
+| Colour | BT.709 tags |
+| Fallback | libx264 (section 0.6 recording set) when VideoToolbox fails to open or fps exceeds 0.9 times the estimated VideoToolbox maximum |
+
+Platform command (not runnable here):
+
+```
+ffmpeg -f rawvideo -pix_fmt nv12 -s WxH -r FPS -i in.nv12 -c:v h264_videotoolbox -realtime true -prio_speed true -profile:v main -b:v B -maxrate M -colorspace bt709 -color_primaries bt709 -color_trc bt709 -color_range tv out.mp4
+```
+
+Production passes no `-g`, so the ffmpeg CLI default `gop_size` (12) also applies here.
+
+**Non-fragmented studio:** `AVFoundationMp4Muxer` (`crates/recording/src/output_pipeline/macos.rs` lines 326-352) builds `cap_enc_avfoundation::MP4Encoder` (`crates/enc-avfoundation/src/mp4.rs`).
+
+| Setting | Value |
+|---|---|
+| Settings base | `OutputSettingsAssistant::with_preset(h264_3840x2160)` (line 251) |
+| Output height | `ensure_even(output_height or source height)` |
+| Output width | Proportional, even (lines 260-268) |
+| Bitrate | `AVVideoAverageBitRateKey` from the formulas below |
+| `AVVideoAllowFrameReorderingKey` | `ultra && !instant` |
+| `AVVideoExpectedSourceFrameRateKey` | fps |
+| `AVVideoMaxKeyFrameIntervalKey` | `floor(0.75 * fps).max(1)` |
+| Colour | `ITU_R_709_2` for transfer, primaries and matrix (lines 325-339) |
+| Writer | `expects_media_data_in_real_time` true |
+| Profile, level, entropy coding | AVFoundation defaults |
+
+Bitrate formulas (lines 1070-1109), with `pixels = W*H` and `f = min(fps, 60)/30`:
+
+| Profile | Formula |
+|---|---|
+| Balanced | `max(pixels*f*5, 8,000,000)` |
+| Ultra | `clamp(pixels*f*10, 8,000,000, 120,000,000)` |
+| Compatibility | `clamp(pixels*f*2.5, 2,500,000, 10,000,000)` |
+| Instant | `1,500,000 + pixels/(1920*1080)*1,500,000 + f*500,000` |
+
+Worked values:
+
+| Profile | 1280x720@30 | 1920x1080@30 | 1920x1080@60 | 3840x2160@30 |
+|---|---|---|---|---|
+| Balanced | 8,000,000 | 10,368,000 | 20,736,000 | 41,472,000 |
+| Ultra | 9,216,000 | 20,736,000 | 41,472,000 | 82,944,000 |
+| Compatibility | 2,500,000 | 5,184,000 | 10,000,000 | 10,000,000 |
+| Instant | 2,666,666 | 3,500,000 | 4,000,000 | 8,000,000 |
+
+Keyframe interval: 22 at 30 fps, 45 at 60 fps.
+
+**Instant mode:**
+- Screen: `MacOSFragmentedM4SMuxer` with bpp 0.15 through VideoToolbox, 2 s segments.
+- Camera-only instant: AVFoundation `init_instant_mode` (instant formula, no reordering).
+
+**Studio camera:** `AVFoundationCameraMuxer` (`macos.rs` lines 973-995), using the Compatibility profile when the compatibility flag is set, otherwise Balanced. Reordering is off.
+
+AVFoundation reproduction is a platform API (`AVAssetWriter` with the keys above). There is no ffmpeg equivalent.
+
+### 4.4 Windows (cannot run on this VM)
+
+**Fragmented studio (default)** (`capture_pipeline.rs` lines 247-369, `win_fragmented_m4s.rs`):
+
+- `SegmentedVideoEncoder` with 2 s segments (line 232). The camera uses 3 s (line 659).
+- Hardware input is false.
+
+| Quality | bpp | Preset |
+|---|---|---|
+| Ultra | 1.0 | Medium |
+| Other | 0.3 | Ultrafast |
+
+The encoder follows the Windows priority in section 0.5, with the recording option sets from section 0.6.
+
+NVENC example (platform command):
+
+```
+ffmpeg ... -c:v h264_nvenc -preset p4 -tune ll -rc vbr -spatial-aq 1 -temporal-aq 1 -g K -b:v B -maxrate M -colorspace bt709 -color_primaries bt709 -color_trc bt709 -color_range tv -f dash ...
+```
+
+**Instant:** 2 s segments, `Ultrafast`, bpp 0.15.
+
+**Non-fragmented studio:** `WindowsMuxer` (`output_pipeline/win.rs`).
+
+| Setting | Value |
+|---|---|
+| `frame_rate` | 30 |
+| `bitrate_multiplier` | 0.3 for Ultra, else 0.15 |
+| `fragmented` | false |
+| `frag_duration_us` | 2,000,000 |
+
+- Encoder: `cap_enc_mediafoundation::H264Encoder` (`crates/enc-mediafoundation/src/video/h264.rs`).
+ - `MF_MT_AVG_BITRATE` (line 359) = `calculate_bitrate` (lines 693-696): `W*H*((max(fps-30,0)/2)+30)*multiplier`, with fps 30.
+ - `MF_MT_FRAME_RATE` = `frame_rate/1` (line 366).
+ - No GOP, profile or rate-control mode is set, so these are Media Foundation transform defaults.
+- Frame pacing at `1/frame_rate` (`win.rs` line 340) gives CFR at 30 fps.
+
+Worked MF bitrates (fps fixed at 30):
+
+| Multiplier | 1280x720 | 1920x1080 | 1920x1080 (60 fps capture) | 3840x2160 |
+|---|---|---|---|---|
+| 0.3 | 8,294,400 | 18,662,400 | 18,662,400 | 74,649,600 |
+| 0.15 | 4,147,200 | 9,331,200 | 9,331,200 | 37,324,800 |
+
+**Software fallback** (`win.rs` lines 229-243): `H264Encoder::builder(video_config)` with builder defaults (bpp 0.3, `Ultrafast`, recording mode, default priority). It is used when:
+- software is forced
+- the primary GPU is AMD (so AMD goes through `h264_amf` with `quality=balanced`, `rc=vbr_latency` first)
+- Media Foundation init or validation fails
+
+**Camera:** Media Foundation multiplier 0.2 at the camera fps (`win.rs` line 763).
+
+---
+
+## 5. Desktop export
+
+**Location:** `crates/export/src/mp4.rs`.
+
+**Compression map:**
+
+| Compression | bpp (lines 147-152) | CRF (lines 156-161) |
+|---|---|---|
+| Maximum | 0.3 | 24 |
+| Social | 0.15 | 28 |
+| Web | 0.08 | 32 |
+| Potato | 0.04 | 36 |
+
+**`Mp4ExportSettings`** (lines 180-190):
+
+| Field | Notes |
+|---|---|
+| `fps` | |
+| `resolution_base` | |
+| `compression` | |
+| `custom_bpp` | |
+| `force_ffmpeg_decoder` | |
+| `optimize_filesize` | serde default false |
+
+- `effective_bpp` (line 193) is `custom_bpp` if set, else the map.
+- `VideoInfo` is NV12 with `time_base = 1/fps` (lines 365-367). Frames are numbered, so output is CFR.
+- Builder chain: `with_bpp`, `with_export_priority` (`is_export = true`), `with_export_settings`, `with_external_conversion`, plus `with_crf(crf)` if `optimize_filesize`.
+- The builder preset stays at its default `Ultrafast`, which selects the libx264 "fast" set.
+- Container: `MP4File::init("output", path, self.optimize_filesize, ...)`. `+faststart` is written only when `optimize_filesize` is true (`crates/enc-ffmpeg/src/mux/mp4.rs` lines 44-90). Default exports have the moov at the end.
+- Audio: AAC 320 kbps.
+- macOS: `want_hw_input = !optimize_filesize && frame is a Surface`.
+
+**UI defaults** (`apps/desktop/src/routes/editor/ExportPage.tsx`):
+
+| Setting | Value |
+|---|---|
+| Format | Mp4 |
+| fps | 30 (options 15/30/60, lines 79-83) |
+| Resolution | 720p 1280x720 |
+| Compression | Maximum |
+| `optimizeFilesize` | false |
+| Custom bpp slider | 0.02 to 0.5, step 0.01 (lines 1408-1410) |
+
+- Resolution options (`Header.tsx` lines 33-37): 720p 1280x720, 1080p 1920x1080, 4K 3840x2160.
+- Output size is rounded: width up to a multiple of 4, height up to even (`crates/rendering/src/lib.rs` `get_output_size`, lines 3228-3242).
+
+### 5.1 DESK-EXPORT-X264-{Maximum,Social,Web,Potato}: default export on Linux, or any platform's software fallback
+
+Encoder settings: libx264 export "fast" set plus `g=K`, `keyint_min=K`, `threads=N`.
+
+| Setting | Value |
+|---|---|
+| Rate control | ABR at B, maxrate ignored |
+| GOP | K, min K/2+1 |
+| B-frames | None |
+| Preset / tune | veryfast, no tune |
+| Effective internals | ref=1, subme=2, trellis=0, rc_lookahead=10 |
+| Profile / level | High, automatic level |
+| Colour | BT.709 limited |
+| Container | MP4 without faststart; track time base 1/90000 |
+
+Verified at 720p30 Maximum: SEI identical to the render farm except `threads=4`.
+
+Worked B per quality (Rust model, section 0.2):
+
+| Compression | 1280x720@30 | 1920x1080@30 | 1920x1080@60 | 3840x2160@30 |
+|---|---|---|---|---|
+| Maximum | 8,294,400 | 18,662,400 | 29,859,841 | 74,649,602 |
+| Social | 4,147,200 | 9,331,200 | 14,929,920 | 37,324,801 |
+| Web | 2,211,839 | 4,976,639 | 7,962,623 | 19,906,559 |
+| Potato | 1,105,919 | 2,488,319 | 3,981,311 | 9,953,279 |
+
+K is 60 at 30 fps and 120 at 60 fps. The desktop UI also offers 15 fps, where K = 30.
+
+**Reproduction on Linux (verified):**
+
+```
+ffmpeg -y -f rawvideo -pix_fmt yuv420p -s WxH -r FPS -i in.yuv \
+ -pix_fmt nv12 -c:v libx264 -preset veryfast -threads N -b:v B -maxrate M \
+ -bf 0 -rc-lookahead 10 -aq-mode 1 -trellis 0 -g K -keyint_min K \
+ -colorspace bt709 -color_primaries bt709 -color_trc bt709 -color_range tv \
+ -an -video_track_timescale 90000 desk_export_x264.mp4
+```
+
+### 5.2 DESK-EXPORT-CRF-{24,28,32,36}: "Optimize file size"
+
+CRF forces libx264. Dictionary: `preset=slow`, `crf=<24|28|32|36>`, `pix_fmt=yuv420p` (ignored), `g=K`, `keyint_min=K`. Threading is N through the context. No bitrate is set (`bit_rate = 0`).
+
+| Setting | Value |
+|---|---|
+| Rate control | CRF |
+| GOP | K, min K/2+1 |
+| B-frames | x264 slow default: bframes=3, b_adapt=1 |
+| Preset | slow |
+| Effective internals | ref=5, subme=8, trellis=2, rc_lookahead=50 |
+| Profile | High |
+| Colour | BT.709 limited |
+| Container | MP4 with `+faststart` |
+
+Verified at 720p30, CRF 24: `ref=5 subme=8 trellis=2 threads=4 bframes=3 keyint=60 keyint_min=31 rc_lookahead=50 rc=crf crf=24.0`.
+
+Compression maps to CRF as Maximum 24, Social 28, Web 32, Potato 36.
+
+**Reproduction on Linux (verified):**
+
+```
+ffmpeg -y -f rawvideo -pix_fmt yuv420p -s WxH -r FPS -i in.yuv \
+ -pix_fmt nv12 -c:v libx264 -preset slow -crf 24 -threads N -g K -keyint_min K \
+ -colorspace bt709 -color_primaries bt709 -color_trc bt709 -color_range tv \
+ -an -movflags +faststart -video_track_timescale 90000 desk_export_crf24.mp4
+```
+
+### 5.3 Hardware export variants (cannot run on this VM)
+
+All variants use the same B and M as section 5.1.
+
+**DESK-EXPORT-VT (macOS default):**
+- Options: `realtime=false`, `profile=main`, `allow_sw=0`; b B, maxrate M.
+- GOP is 12 frames because no `g` is set. There are no B-frames.
+- Input is NV12 surfaces.
+
+```
+ffmpeg ... -c:v h264_videotoolbox -realtime false -profile:v main -allow_sw 0 -b:v B -maxrate M ...
+```
+
+**DESK-EXPORT-NVENC** (Windows NVIDIA, or Linux with `/dev/nvidiactl`):
+
+```
+-c:v h264_nvenc -preset p5 -tune hq -rc vbr -spatial-aq 1 -temporal-aq 1 -b_ref_mode middle -g K -b:v B -maxrate M
+```
+
+**DESK-EXPORT-QSV:**
+
+```
+-c:v h264_qsv -preset medium -look_ahead 1 -look_ahead_depth 20 -g K -b:v B -maxrate M
+```
+
+**DESK-EXPORT-AMF:**
+
+```
+-c:v h264_amf -quality quality -rc vbr_peak -g K -b:v B -maxrate M
+```
+
+**DESK-EXPORT-MF:**
+
+```
+-c:v h264_mf -hw_encoding true -scenario 0 -quality 0 -g K -b:v B -maxrate M
+```
+
+---
+
+## 6. Web recorders on `main` (MediaRecorder)
+
+### 6.1 BR-MR-MAIN: dashboard web recorder
+
+**Locations:**
+- `packages/recorder-core/src/recorder-constants.ts`
+- `packages/recorder-core/src/recorder-utils.ts`
+- `apps/web/app/(org)/dashboard/caps/components/web-recorder-dialog/useWebRecorder.ts`
+
+**Capture constraints** (`recorder-constants.ts` lines 9-19): `{frameRate:{ideal:30}, width:{ideal:1920}, height:{ideal:1080}}`. These are ideal values, not exact.
+
+**MIME candidates:**
+
+| List | Candidates |
+|---|---|
+| `WEBM_MIME_TYPES` (lines 94-97), withAudio | `video/webm;codecs=vp9,opus`, `video/webm;codecs=vp8,opus` |
+| `WEBM_MIME_TYPES`, videoOnly | `video/webm;codecs=vp9`, `video/webm;codecs=vp8`, `video/webm` |
+| `MP4_MIME_TYPES` (lines 82-92), withAudio | `video/mp4;codecs="avc1.42E01E,mp4a.40.2"`, `video/mp4;codecs="avc1.4d401e,mp4a.40.2"` |
+| `MP4_MIME_TYPES`, videoOnly | `video/mp4;codecs="avc1.42E01E"`, `video/mp4;codecs="avc1.4d401e"`, `video/mp4` |
+
+**Pipeline selection** (`selectRecordingPipelineFromSupport`, lines 140-190):
+
+1. WebM is supported and `preferStreamingUpload !== false`: mode `streaming-webm`.
+2. Otherwise the first supported MP4 candidate: mode `buffered-raw`.
+3. Otherwise WebM in mode `buffered-raw`.
+
+`shouldPreferStreamingUpload` (lines 105-130) returns false for iOS, Firefox and Safari, and true for Chromium brands.
+
+**Recorder options** (`getMediaRecorderOptions`, lines 36-41):
+
+```
+{ mimeType, videoKeyFrameIntervalDuration: 2_000 }
+```
+
+No `videoBitsPerSecond` is set, so the browser default applies (Chrome: 2.5 Mbps video, 128 kbps audio). It is constructed at `useWebRecorder.ts` line 1101.
+
+**Timeslice:**
+- `streaming-webm`: `start(1000)` (`INSTANT_UPLOAD_REQUEST_INTERVAL_MS`, line 75).
+- If that throws: `start()` with manual flushing.
+- `buffered-raw`: `start(200)` (line 1141).
+
+**What each browser records:**
+
+| Browser | Output |
+|---|---|
+| Chrome / Edge | VP9 + Opus WebM. This is not H.264. |
+| Safari | H.264 MP4, `avc1.42E01E,mp4a.40.2` (Constrained Baseline 3.0 requested; Safari's own encoder) |
+| Firefox | First supported MP4 candidate, else WebM |
+
+`videoInstantCreate` is called with `videoCodec: "h264"` (line 1056).
+
+**Server step:**
+- Chrome VP9 is transcoded by MS-TRANSCODE-VPX: libx264 medium, CRF 23, `-bf 0`, capped at 1080p, level 4.2, CFR, AAC 128k.
+- Safari H.264 at or below 1080p and level 4.2 is copied.
+- `recording-conversion.ts` `convertToMp4` (line 127) is unused.
+
+**Reproduction on Linux.** Chrome via Playwright:
+
+```js
+new MediaRecorder(stream, { mimeType: "video/webm;codecs=vp9,opus", videoKeyFrameIntervalDuration: 2000 })
+recorder.start(1000)
+```
+
+Then apply MS-TRANSCODE-VPX to the WebM (use `-i rec.webm` in place of the rawvideo input).
+
+**BR-MR-MAIN-MP4 (Safari-path equivalent in Chrome):** `{ mimeType: 'video/mp4;codecs="avc1.42E01E"', videoKeyFrameIntervalDuration: 2000 }` with `start(200)`. Linux Chrome has no AAC MediaRecorder encoder, so the `mp4a.40.2` variants are unsupported there.
+
+### 6.2 BR-MR-EXT-MAIN: Chrome extension
+
+**Location:** `apps/chrome-extension/src/offscreen/recorder.ts`.
+
+- `new MediaRecorder(recordingStream, { mimeType: pipeline.mimeType })` at lines 944-946.
+- No keyframe or bitrate options.
+- `start(RECORDING_TIMESLICE_MS)` with `RECORDING_TIMESLICE_MS` = 1000 (lines 70, 1086).
+- In Chrome this gives VP9/Opus WebM at the Chrome default bitrate, then MS-TRANSCODE-VPX.
+
+Reproduction: `new MediaRecorder(stream, { mimeType: "video/webm;codecs=vp9,opus" }); recorder.start(1000)`.
+
+### 6.3 BR-MR-TOOLS: SpeedController and TrimmingTool
+
+**Location:** `apps/web/components/tools/SpeedController.tsx` and `TrimmingTool.tsx`.
+
+- Source: `canvas.captureStream(60)` (SpeedController line 243, TrimmingTool line 408).
+- Options: `{ mimeType: selectedMimeType, videoBitsPerSecond: 5000000 }` (SpeedController line 263, TrimmingTool line 446).
+- Timeslice: `start(1000)` in SpeedController (line 296), `start(100)` in TrimmingTool (line 485).
+
+MIME list for MP4 input (non-MP4 input uses the same WebM entries first, then `video/mp4`):
+
+```
+"video/mp4", "video/webm;codecs=vp9,opus", "video/webm;codecs=vp8,opus", "video/webm;codecs=vp9", "video/webm;codecs=vp8", "video/webm"
+```
+
+Reproduction: `new MediaRecorder(canvas.captureStream(60), { mimeType: "video/mp4", videoBitsPerSecond: 5000000 })`. The codec Chrome picks for bare `video/mp4` is browser-dependent.
+
+---
+
+## 7. Browser WebCodecs encoders on `main`
+
+### 7.1 BR-WC-REMOTION: Remotion `convertMedia`
+
+**Packages:** `@remotion/webcodecs` 4.0.484 and mediabunny 1.49.0, unpacked to `/tmp` for reading.
+
+**Callers:**
+- `apps/web/app/s/[videoId]/_components/timeline/recording/convert-comment-media.ts` lines 25-32: `convertMedia({ container: "mp4", videoCodec: "h264", audioCodec: "aac" })` with `installAvcLevelClamp()` active. It skips conversion when the input is already MP4 or `canConvertToMp4InBrowser` (probe `avc1.42E01F` 1280x720 plus AAC) fails.
+- `apps/web/components/tools/MediaFormatConverter.tsx` lines 650-657: `convertMedia({ container: "mp4", videoCodec: "h264" })` with no clamp.
+
+**VideoEncoderConfig built by Remotion:**
+
+| Field | Value |
+|---|---|
+| bitrate | Not set in Chrome. Safari: 3,000,000. |
+| framerate | Source fps |
+| hardwareAcceleration | Tries `prefer-hardware`, then `prefer-software` |
+| Keyframes | Every 40 frames |
+| Codec | `avc1.64` + `00` + level from Remotion's width/height/fps table (profile byte always 0x64) |
+
+**Level clamp.** `installAvcLevelClamp` (`avc-level-clamp.ts`) patches `VideoEncoder.prototype.configure` to replace the codec with `pickMobileSafeAvcCodec(width, height)`:
+
+| Size | Codec |
+|---|---|
+| ≤2048x1088 | `avc1.64002A` |
+| ≤4096x2304 | `avc1.640033` |
+| Larger | `avc1.640034` |
+
+**Chromium default bitrate** when none is given (`media/base/video_encoder.cc` `GetDefaultVideoEncodeBitrate`, source only):
+
+```
+2,000,000 * clamp(fps,1,300) * clamp(W*H,1,64M) / (1280*720*30)
+```
+
+The result is clamped to at least 10,000.
+
+**Worked values:**
+
+| | 1280x720@30 | 1920x1080@30 | 1920x1080@60 | 3840x2160@30 |
+|---|---|---|---|---|
+| Chromium default bitrate | 2,000,000 | 4,500,000 | 9,000,000 | 18,000,000 |
+| Codec without clamp | `avc1.64001F` | `avc1.64002A` | `avc1.64002A` | `avc1.640034` |
+| Codec with clamp | `avc1.64002A` | `avc1.64002A` | `avc1.64002A` | `avc1.640033` |
+
+**Container:** MP4 written by Remotion. Audio is AAC; Linux Chrome has no AAC AudioEncoder, so comment media with audio is left as WebM there.
+
+**Reproduction on Linux** (Playwright, Google Chrome):
+
+```js
+new VideoEncoder(...).configure({
+ codec: "avc1.64002A", // with clamp; "avc1.64001F" etc. without
+ width: W,
+ height: H,
+ framerate: FPS,
+ hardwareAcceleration: "prefer-software",
+})
+```
+
+Set `keyFrame: true` every 40th frame and leave `bitrate` unset. Headless Linux Chrome rejects `prefer-hardware` (verified), so Remotion's software retry is the path that runs.
+
+### 7.2 BR-WC-MEDIABUNNY-LOOM: Loom browser conversion
+
+**Location:** `apps/web/lib/loom-browser-conversion.ts` (same on `main` and the PR).
+
+DASH WebM path (lines 644-662):
+
+```js
+new Mp4OutputFormat({ fastStart: false })
+new VideoSampleSource({ codec: "avc", bitrate: QUALITY_HIGH, hardwareAcceleration: "prefer-hardware", alpha: "discard" })
+new AudioSampleSource({ codec: "aac", bitrate: QUALITY_MEDIUM })
+```
+
+Conversion path (lines 857-873):
+
+```js
+Mp4OutputFormat({ fastStart: false })
+Conversion.init({
+ video: { codec: "avc", bitrate: QUALITY_HIGH, hardwareAcceleration: "prefer-hardware" },
+ audio: { codec: "aac", bitrate: QUALITY_MEDIUM },
+})
+```
+
+**mediabunny 1.49.0 behaviour (source):**
+- Quality factors: VERY_LOW 0.3, LOW 0.6, MEDIUM 1, HIGH 2, VERY_HIGH 4.
+- Video bitrate: `ceil(3e6 * (W*H/2073600)^0.95 * 1.0(avc) * 2 / 1000) * 1000`. It does not depend on fps.
+- `keyFrameInterval` defaults to 2 s, by timestamp.
+- `latencyMode` defaults to quality.
+- Codec is `avc1.6400LL` from mediabunny's AVC level table, chosen by macroblocks and bitrate.
+- The config adds `avc: { format: "avc" }`.
+- Timestamps are passed through from the source (VFR).
+- AAC QUALITY_MEDIUM is 128,000 bit/s.
+
+**Worked values:**
+
+| | 1280x720 | 1920x1080 (any fps) | 3840x2160 |
+|---|---|---|---|
+| Video bitrate | 2,778,000 | 6,000,000 | 22,393,000 |
+| Codec | `avc1.64001F` | `avc1.640028` | `avc1.640033` |
+
+**Container:** MP4 with the moov at the end (`fastStart: false`).
+
+**Reproduction on Linux:**
+
+```js
+VideoEncoder.configure({
+ codec: "avc1.640028",
+ width: 1920,
+ height: 1080,
+ bitrate: 6000000,
+ framerate: FPS,
+ hardwareAcceleration: "no-preference",
+ alpha: "discard",
+ avc: { format: "avc" },
+})
+```
+
+`prefer-hardware` is unsupported in headless Linux Chrome (verified). Force a keyframe every 2 s of timestamp.
+
+---
+
+## 8. PR 2312 differences (`FETCH_HEAD` 549c5afa9)
+
+The PR does not change:
+- `crates/enc-ffmpeg`
+- `crates/export/src/mp4.rs`
+- `crates/render-farm/src/video.rs`
+- the desktop capture pipelines
+
+### 8.1 BR-MR-PR-SCREEN, BR-MR-PR-CAMERA, BR-MR-PR-OVERLAY: web recorder
+
+**Location (PR):** `packages/recorder-core/src/recorder-encoding.ts`.
+
+**MIME candidates:** `recorder-constants.ts` lines 96-102 add:
+
+| List | Candidates |
+|---|---|
+| `STREAMING_MP4_MIME_TYPES`, withAudio | `video/mp4;codecs="avc1.64002A,mp4a.40.2"`, `video/mp4;codecs="avc1.64002A,opus"` |
+| `STREAMING_MP4_MIME_TYPES`, videoOnly | `video/mp4;codecs="avc1.64002A"` |
+
+**Pipeline selection** (`recorder-utils.ts` lines 139-211):
+- If `preferStreamingUpload !== false`: streaming MP4, else streaming WebM. Both use mode `"streaming"`.
+- Otherwise buffered MP4 (`avc1.42E01E` list), else buffered WebM.
+- `getMediaRecorderOptions` is removed.
+
+**Bitrate tiers** (`BITRATES`, lines 45-49), in bit/s for captures with ≤1280x720, ≤1920x1088, ≤2560x1600 and larger pixel counts:
+
+| Content | ≤720p | ≤1080p | ≤1600p | Larger |
+|---|---|---|---|---|
+| screen | 2,500,000 | 4,000,000 | 6,000,000 | 10,000,000 |
+| camera | 2,600,000 | 4,500,000 | 6,500,000 | 10,000,000 |
+| cameraOverlay | 2,000,000 | 3,500,000 | 5,000,000 | 8,000,000 |
+
+- `recordingBitrate` (lines 57-74): above 40 fps, `Math.round(base * 1.5)`.
+- Missing width/height default to 1920x1080. Missing fps defaults to 30.
+
+**Recorder options** (`recorderOptions`, lines 87-117):
+
+```
+{ mimeType, videoBitsPerSecond: round(tier * bitrateScale * (vp8 ? 1.3 : 1)), videoKeyFrameIntervalDuration: 2000 }
+```
+
+- For a `video/mp4` MIME containing `avc1.xxxxxx`, the codec is rewritten to `pickMobileSafeAvcCodec(track W, H)`: `64002A`, `640033` or `640034`. The rewrite is kept only if `isTypeSupported`.
+- The `avc1.42E01E` Safari candidate is also rewritten.
+- W, H and fps come from `track.getSettings()`.
+
+**Quality settings** (`web-recorder-dialog/recording-quality.ts`, PR):
+
+| Setting | Value |
+|---|---|
+| Default | `screenHeight` 1080, `frameRate` 30, `cameraHeight` 1080, `level` standard |
+| Screen height options | 1080 / 1440 / 2160 |
+| fps options | 30 / 60 |
+| Camera height options | 720 / 1080 |
+| `qualityBitrateScale` | high = 1.6, standard = 1 |
+| Storage | `localStorage` `"cap-web-recorder-quality"` |
+
+**Capture constraints** (`capture-streams.ts`): `{ frameRate: { ideal: q.frameRate ?? 30 }, width: { ideal: round(h*16/9) }, height: { ideal: h } }`. `DEFAULT_CAMERA_QUALITY` is 1080@30.
+
+**useWebRecorder (PR):**
+- The display recorder uses `recorderOptions(pipeline.mimeType, mixedStream.getVideoTracks()[0], isSupported, qualityBitrateScale(quality), recordingMode === "camera" ? "camera" : "screen")` (lines 1753-1762 of the PR file).
+- The separate camera recorder records a video-only stream with `"cameraOverlay"` (lines 1764-1775).
+- `selectPairedCameraPipeline` (lines 77-93): if the display pipeline is buffered-raw MP4 (Safari), the camera uses `video/webm;codecs=vp8` in streaming mode, so the 1.3 VP8 scale applies.
+- Timeslice: `start(1000)` for streaming, else `start(200)`. The camera recorder uses `start(1000)`.
+
+**Worked videoBitsPerSecond:**
+
+| Content | Scale | 1280x720@30 | 1920x1080@30 | 1920x1080@60 | 3840x2160@30 |
+|---|---|---|---|---|---|
+| screen | standard | 2,500,000 | 4,000,000 | 6,000,000 | 10,000,000 |
+| screen | high (1.6) | 4,000,000 | 6,400,000 | 9,600,000 | 16,000,000 |
+| camera | standard | 2,600,000 | 4,500,000 | 6,750,000 | 10,000,000 |
+| camera | high (1.6) | 4,160,000 | 7,200,000 | 10,800,000 | 16,000,000 |
+| cameraOverlay | standard | 2,000,000 | 3,500,000 | 5,250,000 | 8,000,000 |
+| cameraOverlay | high (1.6) | 3,200,000 | 5,600,000 | 8,400,000 | 12,800,000 |
+| cameraOverlay, VP8 (Safari camera) | standard | 2,600,000 | 4,550,000 | 6,825,000 | 10,400,000 |
+
+At 2560x1440@30 (the PR's 1440 option), screen standard is 6,000,000.
+
+**Observed Chrome 148 behaviour on Linux (verified, canvas source, 1280x720, 2,500,000 bit/s, `avc1.64002A`, 2 s keyframes):**
+
+| Property | Observed |
+|---|---|
+| Reported `recorder.mimeType` | `video/mp4;codecs=avc1.640020`. Chrome picked level 3.2 itself. |
+| Profile | High |
+| B-frames | `has_b_frames=0` |
+| Colour tags | smpte170m, tv range |
+| Container | Fragmented MP4: `ftyp`, `moov`, then `moof`/`mdat` per 1 s timeslice |
+| Timestamps | VFR (avg 29.8 fps) |
+| Keyframes | At 0, 2.03 and 4.06 s, plus extra encoder-chosen IDRs on scene changes |
+| Achieved rate | 1.94 Mbit/s on synthetic content |
+| Supported withAudio MIME | `avc1.64002A,opus` (no AAC) |
+
+**Server step:**
+- PR media server: H.264 at or below 1080p and level 4.2 has its video copied; Opus audio is transcoded to AAC 128k.
+- 1440p and 2160p captures are transcoded down to 1080p with MS-TRANSCODE. The PR `process-video` still passes no size options.
+- Render-farm sources from these recordings usually take the remux path, because they have 2 s keyframes and no B-frames.
+
+**Reproduction on Linux** (Playwright, Google Chrome, fake-camera track from `in.y4m`; see section 9):
+
+```js
+// BR-MR-PR-SCREEN at 1920x1080@30, standard
+new MediaRecorder(stream, { mimeType: 'video/mp4;codecs="avc1.64002A,opus"', videoBitsPerSecond: 4000000, videoKeyFrameIntervalDuration: 2000 }); rec.start(1000);
+// BR-MR-PR-CAMERA at 1920x1080@30: videoBitsPerSecond 4500000
+// BR-MR-PR-OVERLAY at 1920x1080@30: videoBitsPerSecond 3500000
+// 3840x2160: mimeType 'video/mp4;codecs="avc1.640033,opus"' (only if isTypeSupported), bitrate per table
+```
+
+### 8.2 Chrome extension (PR)
+
+`recorder.ts` lines 1318-1340 (PR):
+- `recorderOptions(pipeline.mimeType, recordingStream.getVideoTracks()[0], isSupported, 1, request.mode === "camera" ? "camera" : "screen")` for the main track.
+- `"cameraOverlay"` for the camera track.
+- Timeslice 1000.
+
+The bitrates match the standard rows of the table in section 8.1.
+
+### 8.3 BR-MR-CLIP-PR: editor clip recorder
+
+**Location:** `apps/web/lib/editor-clip-recorder.ts`.
+
+- `new MediaRecorder(stream, { mimeType })`, with the MIME from `selectRecordingPipelineFromSupport`.
+- No bitrate or keyframe option.
+- `start(1000)`.
+- In Chrome this records `avc1.64002A` streaming MP4 at the Chrome default (2.5 Mbps).
+
+Reproduction: `new MediaRecorder(stream, { mimeType: 'video/mp4;codecs="avc1.64002A,opus"' }); rec.start(1000)`.
+
+### 8.4 BR-WC-EXPORT-PR: browser local export (WebCodecs)
+
+**Locations (PR):**
+- `packages/editor-solid-web/src/browser-export-worker.ts` lines 779-806
+- `browser-export-encoder.ts`
+- `browser-export-estimate.ts`
+- `browser-export-audio.ts`
+- `browser-local-export.ts`
+
+**Job inputs:**
+- fps is clamped to 1-120.
+- `bitsPerPixel` is `custom_bpp` or `COMPRESSION_BPP`: Maximum 0.3, Social 0.15, Web 0.08, Potato 0.04.
+- `optimize_filesize`, GIF and cursor-only exports are not handled locally and go to the server.
+
+**Constants:**
+
+| Constant | Safari | Other browsers |
+|---|---|---|
+| `HOLDS_QUALITY_FRAMES` | true | false |
+| `KEYFRAME_SECONDS` | 5 | 2 |
+| `BITRATE_SCALE` | 1.35 | 1 |
+
+**Config, literal:**
+
+```ts
+const bitrate = Math.round(exportBitrate(width, height, job.fps, job.bitsPerPixel) * BITRATE_SCALE);
+// guarded by mediabunny canEncodeVideo("avc", { width, height, bitrate })
+const encoderConfig: VideoEncoderConfig = {
+ codec: avcCodecString(width, height, bitrate),
+ width, height, bitrate,
+ framerate: job.fps,
+ latencyMode: HOLDS_QUALITY_FRAMES ? "realtime" : "quality",
+ hardwareAcceleration: "prefer-hardware",
+ alpha: "discard",
+ avc: { format: "avc" },
+};
+```
+
+**Codec string** (`avcCodecString`): `avc1.6400LL`, where LL is the first entry of `AVC_LEVELS` with `ceil(W/16)*ceil(H/16) <= maxMacroblocks` and `bitrate <= maxBitrate`. The table mirrors mediabunny.
+
+**Frames and keyframes:**
+- `VideoFrame` timestamp is `trunc(frame/fps*1e6)`, and duration is `trunc(1e6/fps)`. This is CFR.
+- A keyframe is requested when `floor(frame/fps/KEYFRAME_SECONDS)` changes: every 2 s, or every 5 s on Safari.
+- Up to 4 frames are queued in the encoder.
+
+**Container and audio:**
+- `Mp4OutputFormat({ fastStart: file ? "reserve" : "in-memory" })`. Either way the moov is at the front.
+- Packets are re-stamped `frame/fps`.
+- Audio: 48 kHz stereo, AAC at `EXPORT_AUDIO_BITRATE` = 320,000 if `canEncodeAudio`, else Opus.
+
+**Fallback:**
+- An error before the first progress message becomes `BrowserLocalExportUnavailable`.
+- `tauri-bridge.ts` lines 248-271 then switches to the server export (section 8.6).
+- In headless Linux Chrome, `isConfigSupported` with `prefer-hardware` returns unsupported (verified), so the PR as written falls back to the server there.
+
+**Worked values (non-Safari, Maximum 0.3):**
+
+| | 1280x720@30 | 1920x1080@30 | 1920x1080@60 | 3840x2160@30 |
+|---|---|---|---|---|
+| Bitrate | 8,294,400 | 18,662,400 | 29,859,840 | 74,649,600 |
+| Codec | `avc1.64001F` | `avc1.640028` | `avc1.640029` | `avc1.640033` |
+
+Codecs at Social, Web and Potato: `64001F`, `640028`, `640028`, `640033`.
+
+Safari at Maximum (×1.35): 11,197,440 / 25,194,240 / 40,310,784 / 100,776,960.
+
+K is 60 at 30 fps and 120 at 60 fps (Safari: 150 at 30 fps).
+
+**Reproduction on Linux** (Playwright, Google Chrome; substitute `hardwareAcceleration`):
+
+```js
+VideoEncoder.configure({
+ codec: "avc1.640028",
+ width: 1920,
+ height: 1080,
+ bitrate: 18662400,
+ framerate: 30,
+ latencyMode: "quality",
+ hardwareAcceleration: "no-preference", // production: "prefer-hardware"
+ alpha: "discard",
+ avc: { format: "avc" },
+})
+// encode(frame, { keyFrame: Math.floor(i/30/2) !== Math.floor((i-1)/30/2) || i === 0 })
+```
+
+**Observed Chrome 148 software path on Linux (verified, 1280x720, `avc1.640028` requested, 4,976,640 bit/s):**
+- avcC `profile_idc` 100 with constraint byte `0x0C` (Constrained High).
+- `level_idc` 31, not the requested 0x28.
+- No B-frames.
+- Requested keyframes were honoured, with extra encoder-inserted IDRs on scene changes.
+
+### 8.5 BR-WC-AUDIO2VIDEO-PR: audio-only to video
+
+**Location:** `apps/web/lib/audio-to-video.ts`.
+
+```js
+// 1280x720 canvas
+new Mp4OutputFormat({ fastStart: "in-memory" })
+new CanvasSource(canvas, { codec: "avc", bitrate: 150_000, keyFrameInterval: 60, latencyMode: "realtime" })
+// frameRate 1
+// audio: AAC (Opus if unsupported) at 160_000
+```
+
+- Codec: `avc1.64001F` (mediabunny).
+- Keyframe interval: 60 s, which is 60 frames at 1 fps.
+
+Reproduction:
+
+```js
+VideoEncoder.configure({
+ codec: "avc1.64001F",
+ width: 1280,
+ height: 720,
+ bitrate: 150000,
+ framerate: 1,
+ latencyMode: "realtime",
+ hardwareAcceleration: "no-preference",
+ avc: { format: "avc" },
+})
+```
+
+Set `keyFrame` every 60th frame.
+
+### 8.6 Server export and web Save (PR)
+
+**Server export:**
+- `apps/media-server/src/lib/editor-exports.ts` validates settings with zod (fps 1-60, x ≤ 3840, y ≤ 2160, `custom_bpp` ≤ 1, `optimize_filesize` optional).
+- It spawns the native `export` binary (`crates/export/src/bin/web-editor.rs` `export()`, lines 512-566).
+- That binary clamps fps to `1..=60`, caps size at 3840x2160, sets `force_ffmpeg_decoder = true`, and calls `Mp4ExportSettings.export`.
+- So it is identical to section 5: on a Linux server, DESK-EXPORT-X264-* by default, DESK-EXPORT-CRF-* with optimize file size, and NVENC p5 if `/dev/nvidiactl` exists.
+
+**Web Save** (`apps/web/lib/render-farm-start.ts`):
+
+| Setting | Value |
+|---|---|
+| Resolution | `SAVE_RESOLUTION = [1920, 1080]` |
+| fps | `clamp(round(fps ?? 30), 24, 60)` |
+| Format | Mp4 |
+| Compression | Maximum |
+| `custom_bpp` | null |
+
+- Rendered by RF-RENDER-NVENC in production.
+- At 30 fps: B = 18,662,400, M = 27,993,600, K = 60. At 60 fps: B = 29,859,841, K = 120.
+- The fallback worker save uses the same `workerSaveSettings` without `optimize_filesize`, so it has no faststart.
+
+### 8.7 PR-PREVIEW-X264: live editor preview stream
+
+**Locations:**
+- `crates/editor/src/bin/web-editor-service/preview_h264.rs`
+- `web-editor-service.rs` (default preview_fps 60 at line 1255; bpp 18/100 at line 990; `{"bitrate":"low"}` gives 4/100 and `{"bitrate":"high"}` gives 18/100, lines 1053-1056)
+
+**Configuration:**
+- `VideoInfo`: RGBA, `time_base 1/1_000_000`, `frame_rate fps/1`.
+- Validation: fps `1..=60`, bpp `0.04..=0.18`.
+- Builder: `.with_bpp(bpp).with_encoder_priority_override(&["libx264"]).build_standalone()`.
+- Preset is the builder default `Ultrafast` in non-export mode, giving `preset=ultrafast`, `tune=zerolatency`, `g=K`, `keyint_min=K`.
+
+**Encoder settings:**
+
+| Setting | Value |
+|---|---|
+| Rate control | ABR at B, maxrate ignored |
+| GOP | 2*fps, so 120 at the default 60 fps |
+| Profile | Constrained Baseline (verified) |
+| Colour | BT.709 limited, from RGBA via swscale |
+| Output | Raw AVC packets with avcC description, sent to the browser decoder. There is no container. |
+
+**Worked B:**
+
+| Resolution | bpp 0.18 | bpp 0.04 |
+|---|---|---|
+| 1280x720@60 | 7,962,624 | 1,769,471 |
+| 1920x1080@60 | 17,915,904 | 3,981,311 |
+
+**Reproduction on Linux** (verified at 720p30):
+
+```
+ffmpeg -y -f rawvideo -pix_fmt yuv420p -s WxH -r FPS -i in.yuv \
+ -c:v libx264 -preset ultrafast -tune zerolatency -threads N -b:v B -maxrate M -g K -keyint_min K \
+ -pix_fmt yuv420p -colorspace bt709 -color_primaries bt709 -color_trc bt709 -color_range tv \
+ -an -f h264 preview.h264
+```
+
+The production defaults are FPS=60, K=120 and bpp 0.18.
+
+### 8.8 PR media server and render farm changes
+
+**`media-video.ts` (PR):**
+- `getOrientedLimits` swaps the max width and height for portrait sources, so the limit becomes 1080x1920.
+- Level selection uses the long and short edge.
+- `AUDIO_RUN_ARGS = ["-chunk_duration", "1000000"]` is appended after `+faststart` when audio is present, and in `muxMediaTracksToMp4`.
+- Video encoder arguments are unchanged.
+
+**Render farm (PR):**
+- `transcode.ts` only adds `downloadSource`.
+- `worker.ts` line 721 keeps `RF_TRANSCODE_ENCODER ?? "h264_nvenc"`.
+- `protocol.ts` adds a `CursorTask` that runs the external `cap-cursor-service` binary. Its encoding settings are not in this repo.
+
+---
+
+## 9. Running browser surfaces in headless Chrome with Playwright
+
+1. Use Google Chrome, not Playwright's bundled Chromium, which lacks proprietary H.264/MP4 support:
+ ```js
+ chromium.launch({ executablePath: "/usr/local/bin/google-chrome", args: [...] })
+ ```
+ `channel: "chrome"` also works.
+2. Feed the source frames:
+ - **MediaRecorder:** convert the raw input to y4m and use it as the fake camera:
+ ```
+ ffmpeg -f rawvideo -pix_fmt yuv420p -s WxH -r FPS -i in.yuv -f yuv4mpegpipe in.y4m
+ ```
+ Launch with `--use-fake-device-for-media-stream --use-fake-ui-for-media-stream --use-file-for-fake-video-capture=/abs/in.y4m`. Then call `getUserMedia({ video: { width: { exact: W }, height: { exact: H }, frameRate: { exact: FPS } } })`. The fake device loops the file. Content type changes only the bitrate tier, so the same track works for the screen, camera and overlay variants.
+ - **WebCodecs:** serve `in.yuv` over HTTP. Slice `W*H*3/2` bytes per frame and build:
+ ```js
+ new VideoFrame(buf, { format: "I420", codedWidth: W, codedHeight: H, timestamp: Math.trunc(i/FPS*1e6), duration: Math.trunc(1e6/FPS) })
+ ```
+3. Replace `hardwareAcceleration: "prefer-hardware"` with `"no-preference"` or `"prefer-software"`. Headless Linux Chrome 148 reports `prefer-hardware` unsupported, while `no-preference` and `prefer-software` (OpenH264) work. This changes the encoder compared with production on Windows/macOS.
+4. Linux Chrome supports neither AAC in MediaRecorder nor AAC in `AudioEncoder`. Use the `,opus` MIME variants, or video-only.
+5. Avoid `--dump-dom --virtual-time-budget` for encoder probes. Virtual time stalls the encoders. Post results from the page to a local HTTP endpoint instead (used here: about 8 s per probe).
+
+---
+
+## 10. Ambiguities and assumptions
+
+- **Media-server ffmpeg version:** `oven/bun:1.4.0` plus apt `ffmpeg` is unpinned. It is probably Debian's 5.1.x but not verified. Verification here used 6.1.1. The x264 presets and the `fps_mode auto` choice of CFR for MP4 are expected to match.
+- **Media-server output frame rate:** for VFR WebM input, the output rate is whatever ffmpeg guesses (`r_frame_rate`, often the stream's nominal 30/1 or a 1000/1 time base fallback). The repro uses the raw input rate.
+- **VideoToolbox GOP of 12** comes from the FFmpeg 7.1 source (AVCodecContext `gop_size` default, `vt_defaults`). It is not observed on a Mac. The FFmpeg version linked into the desktop app was not checked.
+- **NVENC, QSV, AMF, Media Foundation and AVFoundation:** B-frames, profile, level, VBV and lookahead not set by Cap come from encoder or preset defaults. These were not observed.
+- **Rust f32 model:** f32-to-f64 rounding makes some values 1-3 bit/s off the browser model. Benchmarks should use the Rust values for Rust surfaces.
+- **getDisplayMedia and getUserMedia** use `ideal` constraints, so actual capture size and fps may differ. The PR bitrate uses `track.getSettings()`, so it follows the actual size.
+- **Chrome MediaRecorder** chooses its own H.264 level (it reported `avc1.640020` for 720p) and inserts scene-change IDRs. On Windows/macOS Chrome uses platform hardware encoders, whose output will differ from Linux OpenH264.
+- **Chromium default WebCodecs bitrate** comes from the Chromium source. The probe's achieved rate on synthetic content was dominated by scene-change IDRs, so it is not evidence either way.
+- **The `video/mp4` MIME without codecs** (web tools) leaves the codec choice to the browser.
+- **Instant-mode output size** on desktop is clamped to fit within (max, max*9/16). The free/Pro limit comes from the account, which is outside the encoder code.
+- **`cap-cursor-service`** (PR cursor-only render) is an external binary whose encoding is unknown.
+- **libx264 dictionary keys:** the "ignored" list is based on FFmpeg option names and on observed `ref=1` in the output. A different FFmpeg build linked into the desktop app could accept other aliases. This was not checked.
+
+---
+
+## 11. Summary table
+
+| surface | encoder | rate control | GOP | preset/tune | profile/level | container | repro command id |
+|---|---|---|---|---|---|---|---|
+| Media server processVideo (non-H.264, >1080p or level too high) | libx264 | CRF 23, no cap | x264 default 250/25, scenecut; `-bf 0` for VP8/VP9 source, else 3 B-frames | medium / none | High / forced 4.2 (5.1, 5.2 above 2048x1088) | MP4 `+faststart`, CFR (auto), AAC 128k | MS-TRANSCODE, MS-TRANSCODE-VPX |
+| Media server level fix (dormant) | copy + `h264_metadata` | n/a | source | n/a | level rewritten | MP4 `+faststart` | MS-LEVELFIX |
+| Media server edit render | libx264 | CRF 18 | 250/25, 3 B-frames | fast / none | High / auto | MP4 `+faststart`, CFR via fps filter, AAC 160k | MS-EDIT |
+| Web Loom download fallback | libx264 | CRF 23 (default) | 250/25, 3 B-frames | veryfast / none | High / auto | MP4 `+faststart`, AAC 128k | WEB-LOOM-FFMPEG |
+| Render farm render (production) | h264_nvenc | VBR B, max 1.5B (bpp model, default Maximum 0.3) | 2*fps, forced IDR, bf 0 | p1 / hq, spatial+temporal AQ | encoder default | Custom MP4 (moov first) or fMP4 HLS 2 s, AAC 320k | RF-RENDER-NVENC |
+| Render farm render (override) | libx264 | ABR B, maxrate ignored | 2*fps, min fps+1, bf 0 | veryfast (ref 1, rc-lookahead 10) | High / auto | as above | RF-RENDER-X264 |
+| Render farm source transcode (production) | h264_nvenc | VBR CQ 19, b:v 0 | forced IDR every 1 s, bf 0 | p1 / none | encoder default | MP4 `+faststart`, VFR passthrough, no audio | RF-TRANSCODE-NVENC |
+| Render farm source transcode (override) | libx264 | CRF 18 | forced every 1 s plus 250/25, bf 0 | veryfast / none | High / auto | MP4 `+faststart`, VFR passthrough | RF-TRANSCODE-X264 |
+| Desktop recording Linux (Balanced/Compat/Instant) | libx264 (h264_nvenc p4/ll if `/dev/nvidiactl`) | ABR B at bpp 0.3, maxrate ignored | 2*fps, min fps+1, scenecut 0, bf 0 | ultrafast / zerolatency | Constrained Baseline / auto (3.2 at 720p30) | DASH fMP4 2 s + HLS playlists, VFR, AAC 320k | DESK-REC-X264 |
+| Desktop recording Linux Ultra | libx264 | ABR B at bpp 0.3 | 2*fps, min fps+1, bf 0 | veryfast / zerolatency | auto | DASH fMP4 2 s | DESK-REC-X264-ULTRA |
+| Desktop recording macOS fragmented (default) | h264_videotoolbox (libx264 fallback) | ABR B (bpp 0.3 / 1.0 Ultra / 0.15 Compat or Instant), DataRateLimits 1.5B per s | 12 frames (not set), no B-frames | realtime, prio_speed | Main / AutoLevel | DASH fMP4 2 s, VFR | DESK-REC-VT (not runnable) |
+| Desktop recording macOS non-fragmented and camera | AVFoundation | AverageBitRate (Balanced/Ultra/Compat/Instant formulas) | floor(0.75*fps); reordering only Ultra | n/a | AVFoundation default | MP4 (AVAssetWriter) | DESK-REC-AVF (not runnable) |
+| Desktop recording Windows fragmented (default) | nvenc/mf/qsv/amf, then libx264 | VBR B (bpp 0.3 / 1.0 Ultra / 0.15 Instant), max 1.5B | 2*fps | NVENC p4/ll; QSV faster; AMF balanced vbr_latency; MF scenario 4 | encoder default | DASH fMP4 2 s | DESK-REC-WIN-HW (not runnable) |
+| Desktop recording Windows non-fragmented | Media Foundation | AVG_BITRATE, fps fixed 30, multiplier 0.15 (0.3 Ultra) | MFT default | MFT default | MFT default | MP4, CFR 30 | DESK-REC-WINMF (not runnable) |
+| Desktop export (default, Linux or software) | libx264 | ABR B: 0.3 / 0.15 / 0.08 / 0.04 | 2*fps, min fps+1, bf 0 | veryfast (ref 1, rc-lookahead 10, trellis 0) | High / auto | MP4, moov at end, CFR, AAC 320k | DESK-EXPORT-X264-{Maximum,Social,Web,Potato} |
+| Desktop export, Optimize file size | libx264 | CRF 24 / 28 / 32 / 36 | 2*fps, min fps+1, 3 B-frames | slow / none | High / auto | MP4 `+faststart` | DESK-EXPORT-CRF-{24,28,32,36} |
+| Desktop export macOS | h264_videotoolbox | ABR B, DataRateLimits 1.5B | 12 frames (not set) | realtime false, allow_sw 0 | Main / AutoLevel | MP4, moov at end | DESK-EXPORT-VT (not runnable) |
+| Desktop export Windows/Linux NVIDIA | h264_nvenc | VBR B, max 1.5B | 2*fps | p5 / hq, b_ref_mode middle, AQ | encoder default | MP4, moov at end | DESK-EXPORT-NVENC (not runnable) |
+| Desktop export QSV / AMF / MF | h264_qsv / h264_amf / h264_mf | VBR(-peak) B, max 1.5B | 2*fps | medium la 20 / quality vbr_peak / scenario 0 quality 0 | encoder default | MP4, moov at end | DESK-EXPORT-QSV, -AMF, -MF (not runnable) |
+| Web recorder main, Chrome | MediaRecorder VP9 (H.264 made by MS-TRANSCODE-VPX) | browser default 2.5 Mbps | 2 s requested | n/a | VP9 | WebM streaming, 1 s slices | BR-MR-MAIN |
+| Web recorder main, Safari/Firefox | MediaRecorder H.264 | browser default | 2 s requested | n/a | `avc1.42E01E` / `4d401e` requested | MP4 buffered, 200 ms slices | BR-MR-MAIN-MP4 |
+| Chrome extension main | MediaRecorder VP9 | browser default | browser default | n/a | VP9 | WebM, 1 s slices | BR-MR-EXT-MAIN |
+| Web tools (speed, trim) | MediaRecorder | 5,000,000 | browser default | n/a | browser choice for `video/mp4` | MP4 or WebM | BR-MR-TOOLS |
+| Comment media / format converter | WebCodecs via Remotion | none (Chromium default formula; Safari 3M) | 40 frames | prefer-hardware, then software | 0x64, level table; clamp to `64002A/640033/640034` for comments | MP4 (AAC) | BR-WC-REMOTION |
+| Loom browser conversion | WebCodecs via mediabunny | QUALITY_HIGH (2.778M / 6M / 22.393M) | 2 s | prefer-hardware, latency quality | `6400LL` from mediabunny table | MP4 moov at end, AAC 128k | BR-WC-MEDIABUNNY-LOOM |
+| PR web recorder screen/camera/overlay | MediaRecorder H.264 | tier bit/s × 1.5 above 40 fps × 1.6 high × 1.3 VP8 | 2 s requested | n/a | `avc1.64002A` / `640033` / `640034` (Chrome picks actual level) | fragmented MP4 streaming, 1 s slices | BR-MR-PR-SCREEN, -CAMERA, -OVERLAY |
+| PR editor clip recorder | MediaRecorder H.264 | browser default | browser default | n/a | `avc1.64002A` | fragmented MP4, 1 s slices | BR-MR-CLIP-PR |
+| PR browser export | WebCodecs | bpp model × (Safari 1.35) | 2 s (Safari 5 s) | prefer-hardware, latency quality (Safari realtime) | `avc1.6400LL` from table | MP4 moov first, AAC 320k or Opus | BR-WC-EXPORT-PR |
+| PR audio-to-video | WebCodecs via mediabunny | 150,000 | 60 frames at 1 fps | latency realtime | `avc1.64001F` | MP4 moov first, audio 160k | BR-WC-AUDIO2VIDEO-PR |
+| PR editor preview stream | libx264 | ABR bpp 0.18 (low 0.04) | 2*fps (120 at 60 fps), min fps+1 | ultrafast / zerolatency | Constrained Baseline / auto | raw AVC packets | PR-PREVIEW-X264 |
+| PR server export | as desktop export | as desktop export | as desktop export | as desktop export | as desktop export | MP4 | DESK-EXPORT-X264-*, DESK-EXPORT-CRF-* |
+| PR web Save | as render farm render, 1920x1080 Maximum, fps 24-60 | VBR B, max 1.5B | 2*fps | p1 / hq | encoder default | Custom MP4 or fMP4 HLS | RF-RENDER-NVENC |
diff --git a/capcodec/DECISIONS.md b/capcodec/DECISIONS.md
new file mode 100644
index 000000000..be394d9eb
--- /dev/null
+++ b/capcodec/DECISIONS.md
@@ -0,0 +1,77 @@
+# Decisions
+
+Choices made where the brief was ambiguous, newest last. Each entry: the decision, then why.
+
+## Project
+
+- **Repository name `capcodec`.** Nothing more specific was obvious. The encoder library, CLI and muxers are Tov; the benchmark harness and corpus tooling are Python 3 (they are tooling, not the product, and the brief's "no JavaScript/npm workarounds" rule is about gaps in Tov).
+- **The Tov feature branch is delivered as a git bundle and patch series.** The token on this machine has no push access to `richiemcilroy/tov`, so `encoder-features` lives in the local clone and is exported to the artifacts directory.
+- **Speed is the primary goal** (follow-up brief): the pitch is the fastest H.264 encoder for screen recordings at quality equal to x264 veryfast. Every design choice below that trades a little compression for a lot of speed is taken in that direction, and the headline metric is encode fps vs x264 veryfast at matched VMAF.
+- **The OpenAI `math` repository was reviewed and is not used.** Its relevant results (an O(n (log n)^(1-1e-13)) exact DFT, `o(n log n)` Fourier circuits for unbounded lengths, matrix-multiplication exponent bounds) are asymptotic. H.264 fixes the transforms at 4x4 and 8x8 integer butterflies and SATD uses a 4x4/8x8 Hadamard, which already cost only additions and shifts; none of the results lowers the operation count at those sizes. Re-reviewed on 2026-10-07 (all 722 preprint titles, abstracts of the Fourier, tensor and matrix-multiplication papers): same conclusion. Speed comes from vector throughput, memory traffic, fewer evaluated candidates and threads, and from video-coding practice (global motion for screen content, weighted prediction, byte-oriented CABAC, decimation and fast skip), which is what the encoder applies.
+
+## Benchmark harness
+
+- **Colour conversion.** Lossless RGB captures are converted once to 8-bit 4:2:0 with BT.709 matrix, limited range, Lanczos scaling, and the VUI of every encoder is tagged BT.709/limited. This is what HD screen recordings and Cap's pipelines use.
+- **GOP for reference encoders is 2 seconds** (`-g 2*fps`, `keyint_min 1 s`) so that keyframe cost matches Cap's 2 second chunking and HLS segments. Production Cap baselines keep their own production GOP.
+- **Rate ladders.** x264: CRF 18/23/28/33. capcodec: QP 20/25/30/35 until rate control exists. Bitrate-driven encoders (OpenH264, browser encoders, hardware) use a ladder relative to an anchor, x264 veryfast's bitrate at CRF 23 on the same source, times 0.35/0.6/1/1.7/3. This keeps every curve overlapping the reference on clips whose bitrates differ by 100x (idle vs full motion).
+- **BD-rate** uses piecewise cubic (PCHIP) interpolation of log-rate against quality over the overlapping quality range (the method of current codec evaluations), averaged over clips. PSNR is weighted YUV (6Y+U+V)/8, each component computed from the mean MSE over all frames, capped at 100 dB.
+- **Matched-quality speed.** The target quality per clip is x264 veryfast at CRF 23. Each capcodec preset is re-encoded at the QP interpolated to the same VMAF, rounded towards higher quality, and both encoders are timed in serial runs using all cores. Single-thread CPU speedups are reported beside it.
+- **Quality runs are single-threaded and parallel across cores; speed runs are serial and use each encoder's own threading.** CPU time and peak RSS come from `wait4` rusage. Production Cap reproductions keep their production threading.
+- **VFR outputs are compared at the source frame rate**: decoded frames are mapped to source frames by presentation time (or by the encoder's frame map for elementary streams), repeating the last decoded frame, which is how a player shows a variable-frame-rate stream.
+- **Regression gate**: smoke fails if capcodec-medium's BD-rate (PSNR-YUV vs x264 veryfast) is more than 1.0 percentage point worse than the committed `bench/best.json`, if its median single-thread fps drops more than 10%, or if any decode check fails.
+- **Stage timing is batched.** Stages run as separate passes over each macroblock row (analysis, motion search, mode decision, transform/quant/reconstruction, entropy coding, deblocking), so the encoder reads the clock a few times per row instead of per macroblock. This costs well under 0.1% and makes the per-stage breakdown exact rather than sampled.
+- **Change-proportional cost** is measured in single-threaded speed runs: static frame time (frames where nothing changed) against an explicit full-analysis run of the same clip (every macroblock forced through analysis, no frame dropping), plus the pixel-difference fallback without side info.
+- **Colour tags go on the raw input, not the output.** Tagging only the output (`-colorspace bt709` after `-i`) makes ffmpeg insert a BT.601-to-BT.709 conversion in front of the encoder, so every ffmpeg-based encoder compressed a colour-shifted picture and was scored against the original (x264 lost about 5 dB PSNR-Y). Found by checking harness PSNR against a direct numpy computation; all ffmpeg adapters now tag the rawvideo input, and their cache identity carries a version marker so old encodes are discarded.
+- **Production capcodec presets are the `--unchecked` build**, as Rust release builds are; `capcodec-medium-checked` (bounds and overflow checks on) runs beside them in every tier so that any memory-safety bug traps in the harness instead of corrupting output.
+- **The OpenAI `math` repository** — see above; nothing applicable.
+
+- **Texture AQ off by default (2026-10-07).** The text-aware AQ lowered QP by 3 on text macroblocks and raised it by 2 on textured ones. A harness sweep (standard tier, five clips, `/tmp/std8`) showed the texture raise costs VMAF on video (full_motion BD +39.0% with it, +35.3% without) and slides (−6.9% vs −8.3%) and changes nothing on the screen clips, while the OCR tier showed the text reduction lowers character error on scrolling text by about a third at equal bitrate. Default: text −3 kept, texture raise 0 (`--aq-texture N` restores it). Refresh and lifetime AQ stay on: dropping refresh costs slides +9 points, dropping lifetime AQ costs busy_ui/code_editor +2.5 points.
+
+- **Benchmark builds target x86-64-v3 (AVX2).** `bench/build_encoder.sh` builds `build/capcodec` and `build/capcodec-unchecked` with `--target-cpu x86-64-v3` and keeps `build/capcodec-unchecked-baseline` for SSE2-only CPUs. x264 dispatches to AVX2/AVX-512 at run time on this machine, so comparing against a baseline build would understate capcodec; the AVX2 build is 10-18% faster (full_motion 23.6 -> 27.8 fps, text_scroll 154.7 -> 170.5 fps, identical output). On Arm (Apple silicon) the vectors compile to NEON either way. A shipping CLI would pick between the two builds at start-up.
+- **Benchmark builds carry no unwind tables or symbols (Linux, without `-g`).** `bench/build_encoder.sh` adds `-fno-asynchronous-unwind-tables -fno-unwind-tables -Wl,-s` through `TOV_CFLAGS`, and `-fuse-ld=lld` when lld is installed: nothing unwinds a Tov program's stack and the instructions are unchanged, while the files shrink by 37.8 KB unchecked and 45.4 KB checked (460,240 and 608,256 bytes). A `-g` build keeps both for debuggers and profilers.
+
+- **Lookahead QP from macroblock lifetime, buffered in the CLI (2026-10-07).** `--lookahead N` (default 10 on fast, medium and slow; 0 on live, which must not add delay) reads N frames ahead and sets each macroblock's QP from how long its content stays, x264's macroblock tree adapted to screen content. The ring buffer and analysis live in the CLI (`src/lookahead.tov`, `enc.setLookahead()` before each `encodeFrame`) so the encoder's frame flow stays as it is for B-frame scheduling; with more than one thread the analysis runs on the read-ahead thread. Only changed macroblocks are analysed (side-info dirty rects and scroll rects, otherwise the pixel-difference test). Intra cost is the SAD against the block mean; inter cost is the best full-pel SAD over zero, the scroll hint, neighbour and previous-frame motion and a two-step diamond, on even rows. The kept fraction 1 - inter/intra carries each macroblock's cost back along its motion over the window (x264's propagate step), and content still unchanged at the window end is assumed to last to the horizon, weighted by kept^12 where it changed. QP offset -3 + 1.75 log2(span / lifetime), at most +8, span = min(keyint, 2 s). IDR frames skip lifetime AQ (it counts the same persistence twice); P frames keep it (full_motion 1.9 points better) and text AQ stays. Measured alternatives (standard tier, VMAF BD-rate, five clips): N=30 gains 0.1-0.25 points over N=10 and N=60 no more, for 3-6x the delay and memory; strength 1.5 or 2, base -2.5 and a +10 cap are worse; applying it to IDR frames only loses 2-8% on full_motion; ending unchanged content at the window edge halves the gain; text AQ off under the lookahead leaves -1.9% instead of about -4%, and a floor on text macroblocks' offsets is also worse; a wider search (steps 8 to 1) and a half-resolution model with DC/H/V intra costs leave full_motion at -0.7% and +0.6%. Without the 2 s span cap a 250-frame GOP lost 8% on full_motion; with it the loss is about 2%.
+- **Benchmark builds target x86-64-v3 (AVX2).** `bench/build_encoder.sh` builds `build/capcodec` and `build/capcodec-unchecked` with `--target-cpu x86-64-v3` and keeps `build/capcodec-unchecked-baseline` for SSE2-only CPUs. x264 dispatches to AVX2/AVX-512 at run time on this machine, so comparing against a baseline build would understate capcodec; the AVX2 build is 10-18% faster (full_motion 23.6 -> 27.8 fps, text_scroll 154.7 -> 170.5 fps, identical output). On Arm (Apple silicon) the vectors compile to NEON either way. A shipping CLI would pick between the two builds at start-up. On x86-64 it also builds `build/capcodec-unchecked-v4` (`--target-cpu x86-64-v4`, AVX-512, identical output). The kernels stay 256-bit in both: Tov has no compile-time query of the target's vector width, and a 32-lane 16x16 SATD that is 10-20% faster under AVX-512 costs 3.4% more instructions and runs slower under AVX2 (register spills), while 64-byte SAD is no faster than the two-row 32-byte form on AVX-512.
+
+## B-frames
+
+- **One reference per list; adaptive `--bframes 3` by default (fast, medium and slow since `9bce84f`, live since `c6225e5`; 0 with `--zerolatency`).** Each B-frame is coded after its future anchor with L0 = previous anchor and L1 = next anchor (with the pyramid, the middle B-frame replaces one of them for the outer B-frames, see below). Macroblock types are B_Skip, B_Direct_16x16 (spatial direct with `direct_8x8_inference`, colZero from the anchor's vectors), and 16x16 L0, L1 and Bi; no B sub-partitions. POC type 0 is only used when B-frames are on, so `--bframes 0` streams stay byte-identical to the P-only encoder. Live first stayed at 0 because B-frames add up to `bframes` frames of latency and reordering; it uses them since `c6225e5` (see "Adaptive B-frames on every preset" below). The screen clips gain nothing from them (adaptive B usage keeps them within ±0.5% of P-only). See PROGRESS.md for the recommended settings.
+- **B-pyramid (`--b-pyramid`, default on fast, medium and slow, off on live).** In runs of 2 or 3 the middle B-frame (index (n-1)/2) is coded first as a reference (`nal_ref_idc` 2) at the anchor's macroblock QP + 5 (`--b-ref-qp-offset`; 4 and 6 were 0.1-0.3 points worse), and the outer B-frames predict from it: the earlier ones with L1 = middle, the later ones with L0 = middle. The next anchor reorders L0 back to the previous anchor and frees the middle B-frame with MMCO 1, so the P chain and its references are unchanged; the decoded picture buffer grows by one frame, `max_num_reorder_frames` is 2 and fragmented MP4/HLS delay composition by two frame durations. full_motion VMAF/PSNR BD-rate against no pyramid (120 frames, CRF 22-34, with the B search gates below): medium −2.26/−0.66%, fast −2.31/−0.59%, slow −1.15/−0.18%, live b3 −2.69/−1.02%, for about 1.5% more instructions. The outer B-frames wait for the middle one's padded picture and half-pel tiles, so on 4 threads part of the run is serial (CPU +11%, wall −5% at load ~20 before the gates). Live keeps it off because it doubles the decoder's reorder depth. The lookahead does not credit the middle B-frame; it inherits the anchor's lookahead offset through the anchor's macroblock QP.
+- **B-frames are not deblocked.** B slices signal `disable_deblocking_filter_idc` 1, including the pyramid's reference B-frame and with `--recon`. At the B QP the filter cost more bits than it gave back in VMAF: full_motion BD-rate −0.26/−0.16% (medium), −0.27/−0.13% (fast), −0.37/−0.26% (slow), −0.25/−0.07% (live b3) without it, and ffmpeg decodes full_motion 12% faster.
+- **The B-frames of a run are coded concurrently and alongside the next anchor.** They read only the anchors (and the middle B-frame), so each gets its own reconstruction and per-macroblock state (the source is the padded pending buffer); workers claim rows from any frame of the run (a wavefront per frame) and whoever finishes a frame entropy-codes it, so the output does not depend on scheduling. With more than one thread and outside VBR the run is coded asynchronously while the next anchor is coded, and joined after that anchor's frame or at flush, which is how x264 scales B-frames: full_motion 4 threads wall medium b3 7.34 → 5.59 s at load ~12 (CPU unchanged). VBR joins the run before the next anchor because its rate control spends each B-frame's bits before choosing the anchor's QP. The price is memory: at 1080p each concurrent frame holds about 8.7 MB of macroblock state (6.8 MB of it coefficients) and a 3.5 MB reconstruction, and an asynchronous run keeps its three sources while the next three arrive, so 4 threads peak at 151.8 MiB on medium and 114.5 MiB on live b3 where main's sequential B-frames peaked at 95.5 and 65.3 MiB. With one worker the frames are coded one after another, share one slot and reconstruct into the idle frame (112.6 and 72.0 MiB against 91.1 and 60.7; the rest is the pyramid's reference frame). Entropy-coding B rows as they finish would let the coefficients live in a few rows instead of a frame.
+- **Concurrent B runs on thread-efficiency's wavefront (merge of main `7189fa4`, 2026-10-08).** B rows run through the same wavefront row function as P rows but skip its row prep and per-row QP assignment: a run's macroblock QPs are set from the anchor's when it starts, and its sources were padded when they were queued. Each B-frame is entropy-coded whole by the worker that finishes its last row, so a run never takes the main thread, and the anchor coded while a run is in flight keeps the pipelined entropy coding. B workers do not claim half-pel tiles: the run computes both anchors' tiles in one parallel pass before its workers start, so the next anchor's on-demand claims on the same reference find every tile done; the pyramid's outer B-frames wait for the middle one with the adaptive spin-wait. The anchor scan peek runs when the B queue fills, which with asynchronous runs is while the previous run is in flight (13 of 14 peeks on full_motion without side info, 2 and 4 threads); it reads only the previous anchor's source and reconstruction, which the run also only reads, and writes its own buffers. Output is byte-identical to the branch before the merge with 1-4 threads, and ThreadSanitizer finds nothing in 43 scenarios. A run with one worker (one thread, or frames under 8 macroblock rows) is coded on the calling thread: spawning its only worker and joining it at once cost two thread handoffs per run, which at load 20-30 left the 1-thread full_motion encodes waiting on the scheduler (medium wall 29.7 → 11.1 s best of 5, 488 → 53 voluntary context switches; main 33.0 s and 18). Memory is unchanged by the merge; at 1080p (90 frames, CRF 24) live peaks at 80, 117 and 126 MiB on 1, 2 and 4 threads (main 67, 72, 73) and medium at 115, 150 and 159 MiB (main 92, 96, 97), `--zerolatency` at 42 and 47 MiB either way. Of live's +53 MiB on four threads, three B slots of macroblock state are about 26 MB (20 MB of it coefficients), three reconstructions about 10 MB and the asynchronous run's three sources, held while the next three arrive, about 9 MB; two threads already code the run's frames concurrently and pay almost as much.
+- **Concurrent B runs with lookahead round 4 and the all-intra pool (merge of main `08b3b02`, 2026-10-09).** B candidates are buffered before analysis and never pass through the anchor encoder's `analyse`, so the encoder's source copy is current for the lookahead's change map only on an anchor coded right after an anchor (`heldAt === frameIndex - 1`); anchors after a B run compute their own codes, and the anchor scan peek's codes enter through `takeCodes`. Main's sequential B loop rebinds the encoder's planes to each B-frame with `bindSource`; a concurrent run instead slices each B-frame's source from the padded pending buffer, with the same layout, into its own `SharedState`, because the next anchor is coded on the encoder's planes while the run is in flight. B workers keep deblocking off and take the anchor's `filterRecon`, which is true whenever a B-frame can occur (keyint above 1). With `--keyint 1` and more than one thread main's frame-parallel intra pool codes every frame and no B path is reached; `flush()` drains the pool before the B queue. The 4x4 dead-zone tests (`lumaZero`, `chromaZero`) combine the branch's SAD gate (`6e2ef20`) with main's paired transform `fwd4x2`: a pair is transformed only when either block's SAD could reach outside the dead zone, and chroma tests both blocks of a pair in 8-lane vectors. All three variants are exact tests with the same output; callgrind (x86-64-v3, full_motion 31 frames CRF 24, one thread), against the SAD gate with single transforms and against main's ungated pairs: medium 4.090G / 4.137G -> 4.055G, live 3.652G / 3.701G -> 3.617G, `--bframes 0` 5.550G / 5.526G -> 5.513G instructions. In the benchmark lane full_motion's 4-thread wall clock against x264 veryfast at matched VMAF is 1.15x on medium and 1.32x on live (main 0.92x and 0.96x; PROGRESS.md).
+- **Concurrent B runs on footprint's coefficient chunks and padding (merge of main `1859bac`, 2026-10-09).** Each B slot packs its macroblocks' coded 32-coefficient chunks into its own store, sized like the anchor's (the frame's worst case plus one partial block per thread and two spare), and a run resets the slot's top when it starts. B workers are fresh encoders per run, thread and frame, so their block cursors start empty; with one worker the run's frames share slot 0 and reset it after each frame's entropy coding. B macroblocks are nearly all cbp 0, so a slot touches little of its store, which is where most of the B-frames' memory went (6.8 MB of coefficients per concurrent 1080p frame). B targets and the pyramid's reference frame take the 32-pixel padding with tile guard rows, and the middle B-frame's half-pel tiles cover every tile row from the guard origin as `precomputeTiles` does. A run is joined after the next anchor's frame and before that anchor writes its co-located vectors, which are now written only while B-frames wait; an anchor coded while a run is in flight trims references only into the spare list and swaps half-plane buffers by reference, so nothing reconstructs into a frame the run reads before the join. Peak RSS (90 frames, CRF 26; main `1859bac` / `812670f` / merge, MiB): full_motion 1080p live 58 / 73 / 59, 63 / 108 / 85 and 64 / 112 / 89 on 1, 2 and 4 threads, medium 83 / 109 / 94, 87 / 141 / 116 and 89 / 144 / 120, zerolatency on 4 threads 39 / 47 / 39; busy_ui live 30 / 47 / 30 and 34 / 51 / 34 on 1 and 4 threads, medium 64 / 75 / 64 on 4; full_motion 1440p live 99 / 126 / 101 and 106 / 187 / 146, 4K live 214 / 274 / 218 and 229 / 416 / 315, 4K medium on 4 threads 327 / 543 / 439. The B-frames' extra over main at 1080p on 2 and 4 threads fell from 45-56 to 23-31 MiB. What remains of live's +25 MiB on four threads is mostly the run's three reconstructions (about 10 MB) and its three sources, held while the next three arrive (about 9 MB); medium's +11 MiB on one thread is the pyramid's reference frame with its half-pel planes.
+- **No B-frame declarations for GOPs shorter than three frames.** A B run needs a P anchor after it inside its GOP, so `--keyint 1` and `2` never code one; `configureB` leaves B-frames off there, and the CLI configures them before the muxer, the lookahead and the pipelined path read the result. Before, the SPS of medium at keyint 1 declared POC type 0 with a 16-bit LSB, three reference and DPB frames, two reorder frames and `weighted_bipred_idc` 2 (8 bytes more per SPS, which an all-intra stream repeats on every frame; the slices were identical), and MP4, fMP4 and HLS carried a reorder delay. keyint 1 and 2 are now byte-identical to `--bframes 0`. keyint 3 and 4 still declare three B-frames and, on the pyramid presets, its reorder depth, though their runs are at most one and two frames long.
+- **Concurrent B runs with main's read-ahead (merge of main `e20b7fe`, 2026-10-09).** Once the CLI waits for frame n, the read-ahead thread may reuse the ring slot of every earlier frame while an asynchronous run of B-frames before n is still being coded. The run reads only encoder-owned memory: its sources were copied out of the ring by `padInput` when they were submitted, and otherwise it reads the anchors' reconstructions and its own slots. The anchor-scan peek reads frame n+1's slot synchronously while frame n is submitted, when that slot cannot be reused. B workers receive the anchor's lifetime map, a CLI array that the reader rewrites when it takes frame n+2+extra, but never read it: only row prep (`assignMbQp`) and the all-intra pool do, and B rows skip row prep. ThreadSanitizer finds nothing in the 43 scenarios and in 14 more with the read-ahead running (0, 3 and 5 frames, 2-4 threads, 23-60 frames, side info, VBR, keyint 7, stdin, MP4 with `--recon`). The extra ring slots follow `enc.bframes`, so keyint 1 and 2 run as main's `--bframes 0`. Main's CABAC skip-run writer already takes B_Skip with its own contexts, and the merged `endSlice` keeps `nal_ref_idc` 2 for the pyramid's middle B-frame, which the auto-merged line would have marked non-reference. B configurations are byte-identical to `70ebc48` and to themselves with `--read-ahead 0`, 3 and 5 on 2 and 4 threads; P-only configurations are identical to main `e20b7fe`. In the benchmark lane, full_motion's 4-thread wall clock against x264 veryfast at matched VMAF rose from 1.16-1.25x to 1.35-1.40x on medium and from 1.38-1.39x to 1.44-1.50x on live (main 1.09-1.10x and 1.19-1.21x in the same sessions). The read-ahead's three extra raw frames add 9-10 MiB at 1080p and 38 MiB at 4K on 2 and 4 threads, as on main (90 frames, CRF 26; main `e20b7fe` / merge, MiB): full_motion 1080p live 58 / 59, 72 / 95 and 73 / 98 on 1, 2 and 4 threads, medium 82 / 94, 96 / 126 and 98 / 130; busy_ui on 4 threads live 43 / 43 and medium 73 / 73; full_motion 4K live on 4 threads 268 / 353.
+- **Adaptive B usage (default; `--no-b-adapt` turns it off).** An input frame joins a B run only while at least half of its macroblocks change (side-info dirty rects, scroll hints excluded; without side info, the last anchor's changed macroblocks) and the last anchor itself moved without weighted prediction, scroll or global shift. Every other frame is coded at once as a P frame with its side info, and is dropped if unchanged, and a static frame ends a pending run. Screen recordings therefore keep P-mode behaviour: B-frames cannot use weighted prediction, scroll vectors or global shift, so the first rule tried ("B whenever the frame moves") lost +13.7% on slides and +8.3% on text_scroll. Anchors after a B run are coded without side info, because side info describes the change from the previous input frame and the anchor's reference is several frames back.
+- **B QP is the anchor's macroblock QP + 6 (`--b-qp-offset`).** Offsets 2/4/6/8 were swept on full_motion (BD-rate keeps improving up to 12). At 6 the B-frames sit 0.8 dB PSNR below their anchors with a mean frame-to-frame PSNR step of 0.57 dB, which is less than x264 veryfast's own B/P swing (1.0 dB, 0.90 dB per step); 8 adds under one point.
+- **Implicit weighted bi-prediction** (`weighted_bipred_idc` 2) whenever weighted prediction is enabled: B-frames at 1/3 and 2/3 of the anchor distance blend the anchors by POC distance (43/21), as x264's default `weightb` does. About 1% fewer bits at equal VMAF and 2% at equal PSNR on full_motion; no extra syntax.
+- **Early B_Direct and gated B searches.** The presets with early exits (live, fast, medium) take B_Direct_16x16 without the L0/L1/Bi searches and intra when the direct prediction's SATD is under 96 lambda, or under 112 lambda (128 with the pyramid) when the left and top macroblocks are B_Skip or B_Direct, whose choice says the direct vectors fit the area. The 96 lambda gate alone was quality-neutral on full_motion (0.0% VMAF, −0.3% PSNR) for 13-14% less CPU; raising it for every macroblock lost 2.8% (128) and 18.5% (192). On the same presets quarter-pel refinement runs only on the list that is cheaper after half-pel (both when equal), and intra is skipped when the best inter cost is below 1.5 times the intra estimate (was 0.75). Together, against the 96 lambda gate with both lists refined: 6.6% fewer instructions on medium (10.0% with the pyramid), 7.3% (10.6%) on fast and 5.6% on live b3, with VMAF BD-rate −0.35/−0.46% (medium without/with pyramid), −0.42/−0.65% (fast) and −0.09% (live b3). With the pyramid a neighbour threshold of 144 ended 0.25 points worse than no gates (128: 0.46 points better); without it 128 ended +0.16% (medium), −0.01% (fast) and +0.32% (live b3) against no gates. Rejected: refining sub-pel only on lists whose integer cost is within 1-1.5 times the better one (−6.5% to −1.3% instructions for +1.3% to +0.2% BD-rate), bi-prediction only when the list costs are within 1.5-2 times (no change), half-pel only (1.8-8.5% BD-rate for 2-10% CPU), and capping diamond iterations (B searches converge earlier). Below macroblock QP 30 the neighbour threshold, the one-list quarter-pel and the Bi gate (that one on every preset) are off. They were tuned at CRF 22-34, where over 99% of B macroblocks end with cbp 0; at CRF 12-21 (Cap's 0.15 and 0.3 bpp bitrate targets on full_motion) residuals are coded, and medium was +1.9% VMAF / +3.4% PSNR BD-rate behind main. Removing each gate there: quarter-pel on both lists −1.0/−2.0 points, Bi always −1.0/−0.5, the neighbour threshold −0.5/−0.1, the intra skip 0.0, and deblocking B-frames +0.3/−0.1. With the QP 30 limit, CRF 12-21 against before: medium −1.95/−2.33% (now −0.16/+0.87% against main), fast −1.85/−2.24%, slow −0.85/−0.52%, live b3 −2.99/−2.95%, live b3 with the pyramid −3.23/−2.95%; CRF 22-34 within 0.1%. Instructions (31 frames) +1.7% at CRF 22 on medium and fast, 0.0% at CRF 24 on live b3, +7.9% (medium) and +4.2% (live b3) at CRF 16. A limit of 27 costs nothing at CRF 22 but keeps half the high-rate loss (+0.66/+1.50% against main).
+- **B searches share the P search's cost shortcuts.** After merging intra-speed and me-speed, `searchB` uses the same visited-position map and, like `motionSearch`, compares half-pel candidates by SAD and (medium, macroblocks whose QP AQ did not lower) quarter-pel candidates by SAD, converting only the winner to SATD; on near text-free frames it uses the P search's video sub-pel settings (8 half-pel directions, SAD quarter-pel with 4 directions on live and 8 on fast). Unlike `motionSearch` it refines to quarter-pel even on presets whose P search stops at half-pel (on the cheaper list, see the previous item). Effect on full_motion: VMAF BD-rate within 0.2 points (medium b2 -26.6 -> -26.8% vs P-only), 5.1% fewer instructions for a medium b2 encode, 1.5% for live b2.
+- **B macroblocks reuse the mode-decision prediction.** Direct, L0 and L1 winners are coded from the prediction built during the decision (the Bi trial is built into its own buffer) and test the 4x4 dead zone before transforming: over 99% of B macroblocks end with cbp 0. The closed-loop intra decision codes I4/I8 blocks through the same prediction buffer, so the direct prediction is saved around it when direct is the best inter mode.
+- **Lifetime AQ counts streaks between analysed frames.** With B-frames only anchors are analysed, so change streaks and recency are measured against the previously analysed frame instead of `frameIndex - 1`; otherwise every continuously moving macroblock looked new at each anchor and lost lifetime AQ's +2 QP.
+- **Containers.** Decode times are the sorted presentation times. Progressive MP4 stores non-negative ctts offsets and an edit list that removes the reorder delay; fragmented MP4 and HLS do the same with a constant delay of one frame duration (two with the pyramid, rounded up) and the edit list in the init segment, because the delay has to be known before the first fragment. Signed trun offsets (CMAF style) were tried first: ffmpeg's mov demuxer turns the first negative offset it meets into a stream-wide pts shift, so in HLS, where segments are read in order and adaptive B usage leaves early segments without B-frames, presentation times jumped by one frame at the first segment with B-frames. ffmpeg and Chrome (file playback and MSE) apply the edit list and present the first frame at 0.
+- **Lookahead with B-frames (2026-10-08).** Since `9bce84f` fast, medium and slow use adaptive `--bframes 3` and the 10-frame lookahead together. The CLI keeps the lookahead ring and takes one map per input frame before `enc.submit()`; each buffered B candidate keeps its map in its `Pending` frame, so whichever picture becomes the anchor (at once, when a run fills, or on flush) is coded with the map of its own display index (`enc.takeLookahead()`; the ring logic stays in `src/lookahead.tov` and the CLI loop). B-frames inherit the anchor's macroblock QP + 6. Outside the pyramid they are non-reference, so propagation gives them nothing of their own, but setting their QP from the B offset alone (removing the anchor's lookahead offset) put full_motion at +9.3% vs main instead of -0.7%. Anchors are credited with the B-frames that predict from them through list 1, as x264's macroblock tree propagates B costs into both lists (list 0 is already the P-chain model): each B-frame of the run adds its bi-prediction weight (distance from the previous anchor over the anchor distance) times the co-located kept fraction from the anchor back to it, times 4, to the anchor's lifetime. Weights 0/0.5/1/2/3/4/6/8 on full_motion: -0.7/-1.2/-1.4/-2.1/-2.3/-2.5/-2.9/-2.9% VMAF BD-rate vs main (slides -12.4 to -12.7%, -12.5% at 8); webcam_overlay is flat (-8.7 to -9.0%), and the screen clips have no B runs. 4 keeps most of the gain short of the plateau. Offsets stay absolute, so CRF means less quality on video than before (full_motion at equal CRF: 23-29% fewer bits, 2-9 VMAF points below main; at the VMAF of x264 veryfast CRF 23 it needs CRF 22.4 where main needs 24.5) and more on screen content (busy_ui, code_editor, text_scroll: 4-14% more bits at 0.1-2.2 points more VMAF, CRF 31.9-32.9 where main needs 29.3-30.2). Holding the running mean of the offsets over every coded anchor macroblock since the start at or below zero (a positive mean is subtracted from each offset) keeps every clip at or above main's VMAF at every CRF (+2 to +25% bits). It leaves the screen clips byte-identical (their mean stays negative), moves full_motion from -2.5 to -2.8% (fast -2.8 to -3.2%, slow -1.8 to -2.5%) and slides from -12.7 to -11.7% (fast -12.6 to -11.9%, slow -15.0 to -14.1%), and its webcam_overlay gain (-8.9 to -12.1%) comes from main's CRF 20 point alone: without that point both are about +2%. It is not used: at equal CRF it costs 11% more single-thread CPU (full_motion +15%) because it codes video at higher quality, which fails the 5% CPU limit, although at matched VMAF it is no dearer than absolute offsets. A per-picture mean (+1.3% vs main over the five clips) and a two-sided running mean (-2.5%) give back most of the gain, and with `--bframes 0` the clamp loses on webcam_overlay (+4.1%), which keeps absolute offsets as on the P-only lookahead. Letting the lookahead's changed-macroblock count drive the adaptive B decision when there is no side info (otherwise the dirty rects already are its change map) lost 5% on a 3:2-pulldown copy of full_motion, where repeated frames left B runs, and is not used.
+- **Measuring periodic GOPs.** VMAF with `n_subsample` 2 scores only even frames, which samples a periodic GOP unevenly (with one B-frame only anchors or only B-frames, with three the anchors and middle B-frames but never the outer ones), so it biased the b1/b3 offset sweeps by about 2 points. B-frame tuning used `n_subsample=1`; the harness's `n_subsample=5` is coprime with the 2-4 frame GOP periods.
+
+- **Adaptive B-frames on every preset, `--zerolatency` for strict real time (2026-10-08).** Live now defaults to `--bframes 3` like the other presets. Adaptive B only buffers frames while most of the frame moves, so screen recordings stay P-only and unchanged in quality, while full-motion video on live goes from +39.3% to -6.9% VMAF BD-rate vs x264 veryfast (PSNR +64.5% -> -3.7%, SSIM +80.6% -> +7.8%; `/tmp/std16`) for at most 3 frames (100 ms at 30 fps) of delay on moving content; x264 veryfast's default delay is about 13 frames. `--zerolatency` restores zero output delay (no B-frames, no lookahead) and is byte-identical to the previous live preset. A 4-frame lookahead on live gave a further -4.5 points mean (busy_ui +1.8%, code_editor +0.3%, slides -20.8%) for 4 more frames; it is left for the lookahead round that measures 1-4 frame windows.
+- **Lookahead propagation on the read-ahead thread (2026-10-08).** With more than one thread, the thread that reads and analyses frame n+depth+1 also runs `take()` and the keep map for frame n+1 into double-buffered maps while frame n is coded (`22748f4`). The horizon it uses is the GOP position, periodic by display index; the main thread checks it against the encoder's and recomputes on a mismatch, so the propagation's visit tags come from an epoch counter shared by both. The propagation is a serial backward pass over the window and the read-ahead thread is idle once its read is done, so a pooled worker or `parallelFor` would only add a handoff. Main-thread instructions at 4 threads (medium, 60 frames): full_motion -9.1%, slides -29.7%; total instructions within 0.5%; output byte-identical to the main-thread version for any thread count.
+- **Vector change map without side info (2026-10-08).** The lookahead's pixel-difference change map (the media server's `--noise 3 --no-sideinfo` path) compares 16- and 8-wide blocks with vectors: a pixel difference above the noise (lane maximum) or a block sum above the budget gives the same answer as the scalar `diffMb` (`17ebf21`). busy_ui at the media-server settings: 5.86G -> 3.52G instructions (the lookahead's cost over `--lookahead 0` from +83% to +9.6%); full_motion -1.9%. The encoder's own `mbDiffers` (`src/encoder.tov`) still calls the scalar `diffMb` on this path and is now 2.7G of busy_ui's 3.5G instructions.
+- **Geometric tail on video frames without B-frames; no video cost model (2026-10-08).** On current main the media-server settings (medium with B-frames, `--keyint 250 --noise 3 --no-sideinfo`) no longer lose on full_motion: -1.6% VMAF BD-rate against `--lookahead 0` (busy_ui -8.3, code_editor -9.0, slides -9.9, text_scroll -1.4, webcam_overlay -14.6%). The loss is P-only: with `--bframes 0` full_motion is +2.9%. A video cost model on frames where most macroblocks change (SATD at the full-pel vector, 4 or 8 bilinear half-pel SATD positions, the best of i16 DC/V/H/plane SATD from source neighbours as intra cost, a step-8 diamond, an intra bias of 64) moved full_motion by -0.33 to +0.56% and webcam_overlay by -0.33 to +1.13% with B-frames, and gained 0.87% on P-only full_motion, for +2.7% (SATD and i16 intra costs) to +14% (with half-pel) instructions; strength 1.25 and 2.25, an offset cap of 4 and a 20-frame window gained at most 0.11% on either clip. The P-only loss is in the tail instead: content that changes in a video frame and is not seen again inside the window was credited n * q^12 frames up to the horizon (n frames left, q the kept fraction). Without B-frames a frame where at least half the macroblocks changed now uses q(1 - q^n)/(1 - q), the expected survival if every later frame keeps the same fraction (34 instead of 46 frames at q 0.98 with 58 left, 9 instead of 16 at 0.9, 1 instead of 0.01 at 0.5). VMAF BD-rate against the same lookahead without it: live `--lookahead 1/2/4` -0.46/-0.67/-0.81% (full_motion -3.2/-2.2/-1.0%, worst clip slides +0.46% at depth 1), medium `--bframes 0` -0.06% (worst +0.15%), P-only media-server settings -0.07% (full_motion -0.50%, worst slides +0.24%); full_motion is still +2.4% there against `--lookahead 0`. Ending that content at the window edge instead gains more on the long-GOP P-only setting (-0.82%) but loses on live depth 1 (+0.84%), on webcam_overlay at depth 2 (+0.71%) and with medium `--bframes 0` (+0.87%). With B-frames the geometric tail costs 0.5% on long-GOP slides (mean +0.05%), so fast, medium and slow keep the power law and stay byte-identical.
+- **Live lookahead depth: default 0, `--lookahead 2` for desktop recording (2026-10-08).** Each frame of lookahead delays output by one frame (33 ms at 30 fps) and adds about 3 MB at 1080p (the raw frame in the ring). VMAF BD-rate against live (six clips, mean): depth 1 -5.9% but full_motion +1.9%; depth 2 -6.3% with every clip better (full_motion -1.0%); depth 4 -6.6% (webcam_overlay -12.6 instead of -10.9%); before the geometric tail depth 10 gave -6.3%. Callgrind instructions at CRF 26 over the six clips: -5.3/-4.9/-4.5% at depth 1/2/4 (text_scroll +3.5 to +3.8%, the rest -1.0 to -17.4%), because video and short-lived content get higher QPs; the analysis itself is 2.8% of text_scroll's and 8.7% of full_motion's instructions at depth 4. Live stays at 0 because it must not add delay; 2 is the point to offer when about 67 ms is acceptable, and 4 adds 0.24 points for another 67 ms and 6 MB. OCR character error at depth 2 and 4: text_scroll 1.81 -> 1.41/1.39%, slides 0.48 -> 0.45%, code_editor 4.70 -> 4.80/4.74%, busy_ui 3.68 -> 4.33/4.34%; busy_ui's text-region luma PSNR on the four OCR frames is -0.29 to +0.25 dB against live at matched bitrate (code_editor -0.26 to +1.06 dB), so the busy_ui difference is at least partly sampling noise but is not explained.
+- **Lookahead memory stays a raw-frame ring (2026-10-08).** The +31 MB at 1080p is the ring of depth + 1 raw frames (one more with the read-ahead thread); the analysis keeps about 1.5 MB of per-macroblock state and no pixels. The ring is also the encoder's input delay: frame n is coded from its slot after n + depth has been read, so luma-only or half-resolution copies would add memory rather than replace any. Pointing the B-frame `Pending` copies at ring slots would need the ring to hold those frames for up to 3 more frames, the same memory. A ring of changed macroblocks only would shrink with static content, but peak RSS is set by full-change frames unless its allocation is shared with the encoder's buffers, and storing exact deltas needs a pixel compare (side-info dirty rects are conservative) of about 4.6M instructions per 1080p frame, +45% on live busy_ui; it is free only fused into the no-side-info change map. Tov's large typed arrays are resident only once touched, so the ring costs memory as it fills. A shorter window on medium saves 12 MB at depth 6 and 19 MB at depth 4 for +0.06% mean BD-rate, but full_motion loses 0.54 and 0.78%, so 10 stays.
+- **Live reads 2 frames ahead by default (2026-10-08).** With adaptive B-frames already on, `--lookahead 2` on live takes VMAF BD-rate vs x264 veryfast from -4.3% to -8.7% mean (busy_ui +5.1 -> +1.7, code_editor +4.1 -> +0.7, slides -9.8 -> -22.1, text_scroll -14.0 -> -16.2, full_motion -6.9 -> -7.8; PSNR mean +1.0 -> -0.4, SSIM +4.2 -> +1.0; `/tmp/std17`) at matched-VMAF CPU within noise, for 67 ms of extra delay at 30 fps. full_motion PSNR/SSIM get slightly worse (-3.7 -> -1.9, +7.8 -> +12.0) and the lookahead agent measured a small busy_ui OCR change that it is investigating. `--zerolatency` keeps zero delay.
+- **Change detection without side info: one vector pass, shared with the lookahead (2026-10-08).** At the media server's settings (medium, `--keyint 250 --noise 3`, no side info) the encoder compared every macroblock with the scalar `diffMb` (`mbDiffers`), 2.7G of busy_ui's 3.4G instructions over 60 frames on main `52510d7`. Four byte-identical steps replace it. (1) One vector change-map pass per frame (`49b82ed`), (2) two macroblocks per 32-byte luma row, the per-macroblock maxima from the halves of the mask and the SADs from the halves of `sadParts`, chroma one 16-byte U and V row each (`0ba6f14`). (3) The encoder takes the lookahead's map of the frame it codes (`572b08a`). The two compare different things: the lookahead frame n with frame n-1, the encoder frame n with its source copy, which only takes the macroblocks marked changed, so a macroblock that moves within the noise leaves the copy behind the input. The lookahead's map therefore has three codes (identical, changed, different within the noise) and lives in a ring of depth + 2 slots, because the read-ahead thread writes frame n + depth + 1 while n is coded; the encoder keeps a flag per macroblock for "the copy equals input frame `heldAt`", takes the map's code where the flag is set (16 flags at a time), compares the other macroblocks itself and keeps the flag where the code is identical or the macroblock is copied. Side-info frames, anchors after a B run and flushed anchors use the full pass. (4) Each pair of macroblocks is first tested for exact equality, four rows at a time with an early return (XOR and OR, then one mask), which skips the maxima and SADs on static content. Callgrind, 60 frames, one thread, millions of instructions:
+
+| clip | main `52510d7` | (1) | (2) | (3) | (4) | vs main |
+|---|---|---|---|---|---|---|
+| busy_ui | 3398.0 | 835.4 | 681.1 | 589.6 | 558.0 | -83.6% |
+| code_editor | 3357.6 | 793.0 | 638.4 | 545.4 | 513.6 | -84.7% |
+| slides | 3201.9 | 636.0 | 481.4 | 388.4 | 356.7 | -88.9% |
+| full_motion | 12052.3 | 11941.1 | 11905.2 | 11925.7 | 11932.9 | -1.0% |
+| webcam_overlay | 3722.6 | 1267.1 | 1117.3 | 1027.3 | 997.3 | -73.2% |
+
+The map is now the lookahead's only pass (70M of busy_ui's 558M; CABAC is 163M); with B-frames only 3 of full_motion's 17 anchors can take it, so there step (3) costs +0.17% and step (4) +0.06%. Without side info at noise 0 busy_ui goes from 956.8M on main to 563.9M and full_motion stays at 11725M. Rejected: loading all 16 rows before one exact test (0.3-0.9 points better on the screen clips, full_motion +0.23%; clang keeps the 16 row offsets in stack slots in both forms), a separate exact kernel for noise 0 (busy_ui +0.4%, full_motion -0.5%), and storing every code into an unzeroed map (+15% for the pass). Since main `7189fa4` the rows copy their changed macroblocks in the wavefront workers and the next-frame peeks (`diffFrame`) run the same vector pass, so the flags are set on the main encoder: from the codes in `analyse`, and for every macroblock the rows will copy once the frame is known to be coded. Against main `7189fa4` the merge executes -83.1/-84.3/-88.4/-1.0/-73.0% instructions at the media-server settings; wavefront frames take the peek's map, busy_ui's small changes stay off the wavefront and keep the lookahead's map at 2 threads.
+- **Window tail for P-only GOPs longer than the lifetime span (2026-10-08).** Without B-frames and with `--keyint` above the 2 s span, content that a video frame replaces and that is not seen again inside the window now ends at the window edge instead of decaying geometrically (`7f60c22`). The gate keeps every case where the window edge lost (live and medium at their 2 s GOPs, above) on the geometric tail, so all preset defaults stay byte-identical. VMAF BD-rate at `--preset medium --bframes 0 --keyint 250 --noise 3 --no-sideinfo` against the geometric tail: busy_ui 0.00, code_editor 0.00, full_motion -0.50, slides -2.78, text_scroll -0.02, webcam_overlay -1.24% (mean -0.76%); against `--lookahead 0` full_motion goes from +2.37 to +1.67% and the mean from -8.66 to -9.31%; against x264 veryfast from -32.79 to -33.40%. OCR character error unchanged (text_scroll 1.33 -> 1.32%). Instructions at that setting: full_motion -0.63%, the screen clips +0.05 to +0.13%. What is left on full_motion is the same shape: content credited past the edge of a 10-frame window in a 250-frame GOP.
+- **No text-aware lifetime rule for the live lookahead's busy_ui OCR result (2026-10-08).** With `--preset live --lookahead 2` busy_ui's character error is 4.33% against 3.68%. It is not text: the tokens that differ are icon glyphs that OCR reads as characters (tag icons fused with labels, "@upload" -> "e@upload", "e@camera" -> "ecamera"; calendar icons fused with dates, "OHOcti3", "Foct21"; priority bars read as "ail"; sidebar chevrons and badge counts), in all three text regions; the words next to them are read in both, the text-region luma PSNR is 0.4 to 1.9 dB higher with the lookahead at every CRF (-0.29 to +0.25 dB at matched bitrate), and the difference changes sign between CRFs (CER over 30 frames 2.49/2.55/3.02/4.32/6.92% without and 2.58/3.14/4.13/5.32/5.53% with it at CRF 20-36) and between regions at the same CRF. Most of that text does not change (the sidebar never does, the two board columns go through 8 and 3 states over the 30 frames), and most differences are one token read differently in all 30 frames, so each CRF point holds about a dozen independent renderings rather than 90. Capping the lookahead's QP raise at 0 or +2 on macroblocks the AQ classifier marks as text leaves busy_ui at 4.35/4.36% and gives up a third (-4.23% instead of -6.68% against live) or a fifth (-5.46%) of the BD-rate gain, so neither is used.
diff --git a/capcodec/FINDINGS.md b/capcodec/FINDINGS.md
new file mode 100644
index 000000000..1f701fbab
--- /dev/null
+++ b/capcodec/FINDINGS.md
@@ -0,0 +1,97 @@
+# Findings: capcodec against each Cap surface's encoder
+
+Status: 2026-10-07, interim (threads, the C ABI build and the WASM build are not in yet). Every number comes from the harness's standard tier: 1080p, 10 s of each clip, VMAF (every 5th frame), BD-rate over the overlapping quality range, `/tmp/std9` and `/tmp/std10` (results.csv, summary.json, report.html). Clips: busy_ui, code_editor, text_scroll, slides (screen recordings) and full_motion (a film playing full screen, the worst case). Negative BD-rate means capcodec needs fewer bits than the surface's encoder for the same VMAF.
+
+Speeds are single-core CPU frames per second for the harness's quality encodes (capcodec has no threads yet; the x264 surfaces run with `-threads 1` for these runs). Every capcodec stream decoded without error in JM and ffmpeg and matched the encoder's reconstruction bit for bit.
+
+The surfaces' settings come from CAP_BASELINES.md; hardware encoders (VideoToolbox, NVENC, Quick Sync, AMF, Media Foundation) cannot run on this Linux VM and are not compared.
+
+## Summary
+
+| Surface (today's encoder) | capcodec VMAF BD-rate | Bitrate capcodec needs at Cap's production point | Single-core speed, capcodec vs today | Verdict |
+|---|---|---|---|---|
+| Web recorder, PR 2312 (Chrome MediaRecorder H.264) | −51% (medium), −49% (live) | 0.15-0.66x | not comparable (browser) | capcodec wins on bits; needs the WASM build to replace it |
+| Browser export, PR 2312 (WebCodecs) | −63% (medium), −59% (live) | 0.20-0.94x | not comparable (browser) | capcodec wins on bits; needs the WASM build |
+| Desktop recording, Linux (x264 ultrafast zerolatency, ABR bpp 0.3) | −67% (medium), −63% (live) | 0.22-0.54x | ultrafast is faster on video (108 vs 23 fps), capcodec faster on screen content | capcodec wins on bits; speed depends on content |
+| Desktop export and render-farm libx264 override (x264 veryfast ABR, no B-frames, 2 s GOP) | −34% (medium), −29% (live) | 0.29-0.73x on screen clips, 1.0x on video | 2.2-2.4x faster on screen clips, 0.4-0.5x on video | capcodec wins on screen content, ties on video bits but is slower there |
+| Render-farm source transcode (x264 veryfast CRF 18, no B-frames, 1 s IDR) | −38% (medium), −32% (live) | 0.49-0.76x | 2.3x faster on screen clips, 0.5x on video | capcodec wins on screen content |
+| Desktop export "Optimize file size" (x264 slow CRF 24-36, B-frames) | +27% (medium), +37% (live) | 1.2-1.3x on screen clips, 2x on video | 5x faster on screen clips | x264 slow wins on bits; capcodec is far cheaper |
+| Media server transcode (x264 medium CRF 23, 250-frame GOP, B-frames) | +27% (medium, same GOP), +41% (live) | 1.28-1.38x on screen clips, 0.63x on scrolling text, 1.9x on video | 4-5x faster on screen clips, 1.1x on video | x264 medium wins on bits except scrolling text; capcodec costs a quarter of the CPU |
+| Media server edit render (x264 fast CRF 18, 250-frame GOP) | +26% (medium, same GOP) | 1.25-1.44x, 0.61x on scrolling text | 4x faster on screen clips | as above |
+
+Matched-VMAF speed against x264 veryfast (wall clock, capcodec on one core, x264 on four), from `/tmp/std9`: capcodec-live busy_ui 1.62x, code_editor 1.58x, slides 0.86x, text_scroll 0.68x, full_motion 0.23x; geometric mean 0.81x (CPU time: 1.48x).
+
+## Per surface
+
+### Web recorder (PR 2312: Chrome MediaRecorder, `video/mp4;codecs="avc1.64002A"`, 4 Mbit/s at 1080p30)
+
+- **Does capcodec beat it?** Yes, by about half the bits at equal VMAF on every clip: busy_ui −47%, code_editor −48%, slides −75%, full_motion −34% (medium). Chrome's software H.264 encoder (OpenH264) has no screen-content tools, no CABAC and a fixed bitrate tier.
+- **Speed and CPU.** Not comparable here: the browser encodes in real time at its own pace. The replacement path is the WASM build of capcodec running in the page, which waits on Tov's WASM target.
+- **Where it loses.** Nowhere on quality; the integration is the open item.
+
+### Browser export (PR 2312: WebCodecs `avc1.6400LL`, bpp model)
+
+- **Does capcodec beat it?** Yes: −63% (medium) / −59% (live) BD-rate, text_scroll −80%. At Cap's production points capcodec needs 0.2x-0.94x of the bitrate for the same quality.
+- **Speed.** Not comparable (headless Chrome software path); same WASM dependency as the recorder.
+
+### Desktop recording on Linux (x264 ultrafast, tune zerolatency, Constrained Baseline, ABR at bpp 0.3, 2 s DASH segments)
+
+- **Does capcodec beat it?** Yes: −67% (medium) / −63% (live) on the clips where the curves overlap (text_scroll −67%, full_motion −68%). Ultrafast disables CABAC, B-frames and most analysis.
+- **Speed.** Ultrafast is the faster encoder on full-motion video (108 vs 23 fps on one core); on screen content capcodec's change-proportional coding is faster (280-330 fps on busy_ui/code_editor, ultrafast 220-240).
+- **macOS and Windows** use VideoToolbox and GPU encoders, which cannot be measured here.
+
+### Desktop export (Linux default) and render-farm libx264 override (x264 veryfast ABR, bf 0, rc-lookahead 10, 2 s GOP)
+
+- **Does capcodec beat it?** Yes on screen content: busy_ui −32%, code_editor −31%, slides −48%, text_scroll −44% (medium). On full_motion medium is −16% and live +6%.
+- **Production points.** At the export presets capcodec needs 0.29x (slides, Social) to 0.73x (code_editor, Potato) of the bitrate for the same quality; on full_motion about the same bitrate.
+- **Speed.** 2.2-2.4x faster on screen clips on one core; about half the speed on full-motion video.
+- **Integration.** Cap calls libx264 from Rust (crates/export); the drop-in needs the C ABI build (Tov `--lib`, in progress).
+
+### Render-farm source transcode (x264 veryfast CRF 18, bf 0, IDR every 1 s)
+
+- −38% (medium) BD-rate; 2.3x faster on screen clips, half the speed on video. Production renders use NVENC p1 on GPUs, which isn't measurable here.
+
+### Desktop export "Optimize file size" (x264 slow CRF 24/28/32/36, 3 B-frames)
+
+- **Does capcodec beat it?** No: +27% (medium) on average, +25% to +31% on screen clips and +78% on full_motion; it wins on text_scroll (−24%).
+- **Cost.** capcodec is about 5x faster on one core on screen clips (280 vs 55 fps).
+- **Where it loses.** x264 slow's RDO, trellis quantisation, B-frames and macroblock-tree rate control.
+
+### Media server transcode (x264 medium CRF 23, High 4.2, default 250-frame GOP, 3 B-frames)
+
+- **Like for like** (capcodec with `--keyint 250`): capcodec-medium needs 27% more bits on average: busy_ui +20%, code_editor +35%, slides +29%, full_motion +87%, and 36% fewer on text_scroll. With capcodec's default 2 s keyframes the gap is +95%, which is a GOP difference, not a coding one: on static screens keyframes dominate the bitrate.
+- **Cost.** capcodec uses about a quarter of the CPU on screen clips (280-330 vs 65-72 fps on one core) and about the same on video.
+- **End to end** (prototype in Cap branch `cursor/capcodec-integration-aa45`, draft PR #2429, 10 s 1080p typing clip from a VP9 upload): libx264 2.10 s, 309 KB, VMAF 92.9; capcodec 2.56 s, 531 KB, VMAF 93.7 (before this session's speed work and with 2 s keyframes).
+- **Where it loses.** B-frames and macroblock-tree rate control (x264 veryfast without B-frames is +47.5% on full_motion; capcodec medium is +35%), and the noise of lossy uploads.
+
+## What is missing before capcodec can replace these encoders
+
+1. **Threads.** Wavefront coding is implemented and bit-identical for any thread count (`typed-planes` branch, commit `482440a`), but it is slower than one thread until Tov stops doing atomic reference counting on every typed-array field access (TOV_GAPS.md, in progress in Tov). Expected 2.5-3.5x wall clock on four cores for heavy frames.
+2. **B-frames** for camera and video content (the media server, the render farm with webcam overlays) were x264's whole advantage on full_motion. They are now in, opt-in (`--bframes 1-3`, adaptive): on full_motion `--preset medium --bframes 3` needs 4.6% fewer bits than x264 veryfast for the same VMAF (P-only medium: +32.6%) and the screen clips are unchanged (standard tier, `/tmp/bf-post`, see PROGRESS.md). The surface comparisons above predate them. Still missing against x264 medium and slow: B sub-partitions, B-frames as references (pyramid), several references per list, and lookahead / macroblock-tree rate control.
+3. **The C ABI build** for crates/export and the desktop app, and **the WASM build** for the browser recorder and export (both in progress in Tov).
+4. **Hardware encoder comparisons** on macOS and Windows (VideoToolbox, NVENC, Media Foundation): run the harness's hardware adapters on those machines (see CAP_BASELINES.md section 9 and bench/harness/adapters/hardware.py).
+
+## Footprint and raw speed against x264 (2026-10-07)
+
+x264 built here from source (commit 0480cb0, `--enable-static`, nasm 2.16); capcodec main `ec8d3ac`. 4-core Sapphire Rapids VM, best of 3 interleaved runs on an idle machine.
+
+| | capcodec | x264 |
+|---|---|---|
+| Binary | 506 KB (498 KB stripped) | 2.50 MB (2.32 MB stripped) |
+| Runtime dependencies | libc, libm | libc, libm |
+| Clean build | 8.9 s (one C translation unit; 0.06 s when cached) | 17.1 s with `make -j4`, 59.7 s with `-j1`; needs nasm |
+| Source | 8.8K non-blank lines of Tov, tests included | 79.7K lines of C, 60.1K lines of assembly |
+| Startup, one 64x64 frame | 1.1 ms | 1.4 ms (veryfast) |
+| Peak memory, 1080p | 46-53 MB | 152-249 MB (veryfast, 1-4 threads) |
+| Output delay | 0 frames (N with `--bframes N`) | 3 B-frames + 10-frame lookahead (veryfast) |
+
+Since these measurements the fast, medium and slow presets use adaptive B-frames (`--bframes 3`) and read 10 frames ahead (`--lookahead`): up to 13 frames of output delay, about 31 MB more at 1080p, and a mean VMAF BD-rate against x264 veryfast of −3.4% (fast), −5.6% (medium) and −5.4% (slow) over busy_ui, code_editor, full_motion, slides and text_scroll; live is unchanged. At the media server's settings (medium, 250-frame GOP, `--noise 3` without side info) the lookahead gains on every clip, full_motion included (−1.6%), and since round 4 the change detection there is one vector pass per frame shared with the lookahead: single-thread instructions against main `52510d7` busy_ui −84%, code_editor −85%, slides −89%, webcam_overlay −73%, full_motion −1% (CPU at 300 frames on one thread −63%, −66%, −40%, −32% and −1%), with identical output. For desktop recording, `--preset live --lookahead 2` adds 2 frames of delay (67 ms at 30 fps) and 6 MB at 1080p for −6.3% VMAF BD-rate against live (every clip better) at 4.9% fewer instructions, and moves live from −0.4% to −4.5% against x264 veryfast over the six clips including webcam_overlay (PROGRESS.md).
+
+| Raw speed, 1080p | capcodec | x264 veryfast |
+|---|---|---|
+| busy_ui, 4 threads, no side info | 433 fps, 0.9 s CPU | 343 fps, 2.2 s CPU |
+| full_motion, 1 thread (live CRF 30, 3.4 Mbit/s vs CRF 23, 3.7 Mbit/s) | 34.6 fps | 46.3 fps |
+| full_motion, 4 threads | 65 fps, 11.4 s CPU | 115.5 fps, 6.6 s CPU |
+| 30 keyframes (keyint 1), 1 / 4 threads | 20 / 32 fps | 65 / 210 fps |
+
+At similar bitrates x264's full-motion quality is much higher (VMAF BD-rate: capcodec-medium +35.5%, live +63.5%). Keyframe coding is the slowest path (scalar intra transforms, poor 4-thread scaling) but keyframe reuse hides it on typical screen recordings.
diff --git a/capcodec/PROGRESS.md b/capcodec/PROGRESS.md
new file mode 100644
index 000000000..7ebe01a6f
--- /dev/null
+++ b/capcodec/PROGRESS.md
@@ -0,0 +1,203 @@
+# Progress
+
+**Headline (main `1a1794a`; the 12-clip speed table in `SCOREBOARD.md` is still `00fecf7`, before concurrent B-frames, and `--bframes 0` matches that encoder): at matched VMAF that table is faster than x264 veryfast on every clip in every mode, on CPU and on wall clock, at 1 and at 4 threads (36/36). Geometric mean CPU 4.9-5.9x, wall 3.2-5.2x. Concurrent B-frames are now the default. On full_motion in the benchmark lane, 4-thread wall is 1.35-1.40x medium and 1.44-1.50x live (the same sessions measured the previous main at 1.09-1.10x and 1.19-1.21x). The other 11 clips were not retimed. Peak memory on the 12-clip run is 3-8x under x264. Quality on this encoder is the `fff504d` result (bitstreams match): level, 17-20 wins of 36 clip-metrics per mode. The pending quality branch `rd-next` wins VMAF on 12/12 clips and PSNR on 11/12, and still loses SSIM on 6-8 clips. SSIM round 3 (`ssim` `b72e995`, not on main; base is `rd-next` plus main `08b3b02`, 84 commits behind) lowers light flat and smooth IDR macroblocks above QP 34 and moves the 12-clip SSIM mean from about 0 to −1.4% on medium and live. It still loses SSIM on dashboard (+10.0% medium), busy UI, code, webcam, and full motion. Intra rounding and IDR rate-distortion (`intra-rd` `99822eb`, not on main) pass the 0.5% gate against main on all 12 clips in medium, live, and zerolatency. All-intra wins against x264 veryfast keyint 1 go from 7 to 12 of 36. The screen-clip SSIM and PSNR losses shrink and do not flip. All-intra CPU stays ahead of x264; full_motion is 1.01× and a round reaches 1.00×. Line and edge AQ (`dashboard` `4ca9f20`, on `rd-next`, not on main) cuts dashboard's loss to x264 veryfast from SSIM +12.8% to +6.2% and PSNR-YUV +3.2% to +1.7% in medium, and from +14.0% to +7.3% and +3.8% to +2.4% in live. Zerolatency dashboard wins all three metrics. No other clip gets worse by more than 0.5 against x264.**
+
+Threads: deterministic wavefront (rows claimed in order, each macroblock waits for the row above to pass its top-right neighbour), output byte-identical for any thread count.
+
+## Intra RD (not on main)
+
+`intra-rd` `99822eb` (rounding `719dab7` plus CABAC SSD choice among close I4/I8/I16 SATD candidates; `--no-intra-rd` matches the rounding commit). All-intra uses round-to-nearest above the first luma level, and textured or natural macroblocks use a 0.4 offset (chroma 0.36). In a normal GOP, IDRs keep main's rounding except lasting textured or natural macroblocks, which take the 0.4 offset. Against main, every clip in medium, live, and zerolatency is inside the 0.5% gate; the worst cells are live slides VMAF +0.28% and zerolatency webcam_overlay PSNR-Y +0.27%. Against x264, wins go from 19 to 20 (medium), 17 to 20 (live), and 19 to 22 (zerolatency). All-intra mean versus main is VMAF −13.2%, PSNR-YUV −1.0%, SSIM −1.7%. `tov test` 85/85, thread identity, TSan 0, `verify.py` 23/23. Not merged: it changes bitstreams, and full_motion all-intra speed is only 1.01× x264.
+
+## Dashboard lines (not on main)
+
+`dashboard` `4ca9f20` (docs `b74f140`) sits on `rd-next` `d0cce5e`. Macroblocks whose 16 rows or 16 columns are constant split into lines and edges. Edges take −4 QP in every frame. Lines on IDRs take −8, or −12 when the range is under 16; lines in P and B frames take −4. Flags: `--aq-stroke`, `--aq-line`, `--aq-faint-line`. full_motion stays byte-identical. The worst change outside dashboard against x264 is slow_typing medium VMAF +0.38. `tov test` 65/65, `verify.py` bit-exact on busy_ui and full_motion, 1 and 4 threads identical in 18 configurations. Instructions rise at most 0.38%. Not merged: medium and live dashboard still lose SSIM (+6.2%, +7.3%) and PSNR-YUV (+1.7%, +2.4%) to x264, and the base is `rd-next`.
+
+## Scoreboard vs x264 veryfast (goal: win every row)
+
+Quality: harness standard tier on 12 clips (1080p, 10 s) with capcodec's CRF ladder reaching 44 so both curves overlap (42-88%; the old ladder compared only 15-24% of screen-clip curves and flattered capcodec). Speed: `bench/speedcmp.py` in the benchmark lane (CRF matched to x264 CRF 23's VMAF, interleaved rounds, rest of the machine paused). Clip counts are wins out of 12.
+
+| Metric | main `fff504d` | quality branch `rd-next` | status |
+|---|---|---|---|
+| VMAF BD, medium / live / zerolatency | 8 / 6 / 7 | 12 / 12 / 12 (-12% to -81%) | win after rd-next |
+| PSNR BD, medium / live / zerolatency | 5 / 6 / 6 | 11 / 11 / 12 | lose dashboard (+3.2% / +3.8%) |
+| SSIM BD, medium / live / zerolatency | 5 / 5 / 6 | 4 / 4 / 6 | lose on rd-next: dashboard +12.8%, busy_ui +6.5%, busy_ui_60fps +6.4%, code_4k +5.0%, webcam_overlay +3.4%, code_editor +2.5%, slow_typing +2.2%, full_motion +1.5% (live +6.8%). `ssim` `9b329be` (not merged): medium 27/36 wins, SSIM mean −1.36% (dashboard +10.0, busy_ui +3.5, busy_ui_60fps +0.9, code_4k +3.8, code_editor +1.7, webcam +3.4, full_motion +1.5); zerolatency 31/36, slow_typing SSIM becomes a win |
+| CPU at matched VMAF, 1 thread | 36/36 faster; geomean medium 5.53x, live 5.83x, zerolatency 5.39x; min 1.39x (full_motion medium) | | win |
+| CPU at matched VMAF, 4 threads | 36/36; geomean 5.51x / 5.87x / 4.90x; min 1.21x (full_motion zerolatency) | | win |
+| Wall at matched VMAF, 1 thread | 36/36; geomean 4.94x / 5.23x / 4.80x | | win |
+| Wall at matched VMAF, 4 threads | 36/36; geomean 3.15x / 3.46x / 3.26x; min 1.06x (full_motion medium), live 1.21x, zerolatency 1.49x | | win (`bench/out/speedcmp-00fecf7`; other processes stopped, frozen median about 690); with the concurrent B-frames after merging `e20b7fe`, full_motion medium 1.35-1.40x and live 1.44-1.50x in the benchmark lane (main 1.09-1.10x and 1.19-1.21x in the same sessions) |
+| Keyframe-only CPU at matched VMAF (`speedcmp.py --keyint1`, main `558481e`) | 1.07-1.75x at 1 thread, 1.06-1.76x at 4 (full_motion 1.07x / 1.06x, busy_ui 1.21x / 1.28x); 4-thread wall fps full_motion 149 vs 136 | | win on every clip; busy_ui needs 12% more bits than x264 at matched VMAF in all-intra |
+| Peak memory, 4 threads | 34-308 MiB vs 141-1304 MiB on the `00fecf7` rerun | | win |
+| Delay before output | live 2 frames (5 with B-frames), medium 10 (steady 13), zerolatency 0 | | win vs x264 at 4 threads (17) and auto (19); medium steady lag 13 vs 10 at 1 thread |
+| Startup | 0.9-1.2 ms vs 1.3-1.5 ms (64x64 frame); first 1080p frame 30.5 vs 54.9 ms at default threads | | win; 1-thread medium first 1080p frame 48.9 vs 40.3 ms (keyframe speed) |
+| Decode CPU of the output at matched VMAF | 0.58-1.54 s vs 1.59-2.40 s (dashboard, dark_mode, webcam_overlay, slow_typing, idle) | | win |
+| Binary | 550 KB vs 1.29 MB (minimal x264 build) / 2.5 MB (CLI) | | win |
+| Build CPU time | about 12 s vs 36.5 s (minimal x264) / 71 s (full) | | win |
+| Bitrate accuracy at Cap targets (10 s, reachable) | two-pass 4.9% vs 5.5%; one-pass 7.7% vs 5.5% | | two-pass win, one-pass lose (rate-control round in progress) |
+
+## State
+
+| Milestone | State |
+|---|---|
+| 0 Benchmark harness | Done. Corpus: 12 clips including full-motion video (Big Buck Bunny, CC BY 3.0) and 4K; scripts and manifest in `bench/corpus/`, sources outside git. |
+| 1 Minimal stream | Done |
+| 2 Full intra | Done |
+| 3 CABAC | Done; byte-oriented arithmetic coder, bit-exact with the spec engine (`src/cabac_ref.tov`, randomised equivalence tests) |
+| 4 P frames | Done; global shift candidates (column/row profile matching) find slide push/cover transitions |
+| 5 Screen-aware side info | Done; IDR frames reuse unchanged macroblocks of the previous IDR (decisions, coefficients and reconstruction) |
+| 6 Text-aware AQ | Done (defaults under review) |
+| 7 Rate control | Done; weighted prediction for fades added; lookahead QP from macroblock lifetime (`--lookahead`, 10 frames on fast/medium/slow) |
+| 8 Speed | SIMD kernels (SAD, SATD, SA8D, half-pel, transforms, quantisation, deblocking, classification, hashing, chroma MC) and wavefront threads; IDR entropy and deblocking still serial |
+| 9 Integration | Media server prototype on Cap branch `cursor/capcodec-integration-aa45` (draft PR #2429); C ABI and WASM wait on Tov |
+| Muxers | Done: MP4 faststart, fragmented MP4, HLS |
+| B-frames | Done: `--bframes 0-3` (default 3, 0 with `--zerolatency`), adaptive by default (`--no-b-adapt`), B-pyramid (default with the B-frames except on live, `--no-b-pyramid`; the middle B-frame of a run is a reference at the anchor's QP + 5), `--b-qp-offset` (6); one reference per list, B_Skip / B_Direct_16x16 / 16x16 L0, L1, Bi; the B-frames of a run are coded concurrently and alongside the next anchor; MP4, fMP4 and HLS (edit lists remove the reorder delay) |
+| Read-ahead | On main. More than one thread already overlapped the next frame's read and lookahead (one extra ring slot) at `fff504d`. `f4781c5` (`cli/main.tov` only) reads further frames while a B run is coded (`--read-ahead`, default 3; off when B-frames are off). `a9b86d5` matched `/tmp/capcodec-main-latest18` in 459/459 configurations (verify.py 10/10, tov test 81/81, TSan 0 reports). A pin7 rebuild of `f4781c5` matched that baseline on busy_ui and full_motion for default, live, zerolatency, fast, `--bframes 0`, `--lookahead 0`, bitrate and `--keyint 1` at 1 and 4 threads (32/32; full_motion default and live also matched at 90 frames). `--read-ahead 0` and `5` are new flags; on these clips they hash the same as the default encode. Retimed on `00fecf7` with other processes stopped: full_motion 4-thread wall is 1.06x medium and 1.21x live (was 0.89x and 0.97x) |
+
+Every capcodec bitstream decodes without errors in JM 19 and ffmpeg and is bit-exact with the encoder's reconstruction (every harness tier, and `tools/verify.py` after each change). B-frames, after merging intra-speed and me-speed: 51 verify cases (bframes 1-3 x live/medium/slow x CABAC/CAVLC, keyint 7, stream ends 1-15 frames, ABR, constant QP, fixed pattern, no side info, adaptive runs on five screen clips, 300-frame encodes of four clips) are JM and ffmpeg bit-exact and identical for 1 and 4 threads; `--bframes 0` is byte-identical to main `dc8d9fb` (full_motion, busy_ui, slides x live/medium x 1/4 threads x CABAC/CAVLC, and MP4/fMP4/HLS); ffmpeg presentation and decode checks pass in all three containers (bframes 1-3, VFR drops), and Chrome 148 plays MP4, fMP4 and HLS (MSE) with B-frames in order. B-frames round 2 (speed, concurrent runs, pyramid; `6765509`): the 53-case verify matrix (the same kinds of cases as above, now 53) is JM and ffmpeg bit-exact and identical for 1 and 4 threads with and without the pyramid, every speed step that claims it is byte-identical (P-only, slow and screen clips where the decisions do not change), the reconstruction written with `--recon` matches ffmpeg's decode, and the container checks pass with reorder depth 2. After merging main `08b3b02` (`149f001`): B-frame configurations are byte-identical to the branch at `c12ee19` (36 configurations with 1-4 threads, and `--keyint 1` with the default B-frames), P-only configurations to main `08b3b02` (16 configurations with 1-4 threads, including the window tail at `--bframes 0 --keyint 250` and `300`, and all-intra), the 53-case matrix is JM and ffmpeg bit-exact and identical for 1 and 4 threads, ThreadSanitizer finds nothing in 43 scenarios, and the container checks and `tov test` pass. After merging main `1859bac` (`f1c6e24`): B-frame configurations are byte-identical to `812670f` (36 configurations with 1-4 threads, and footprint's odd sizes, synthetic pans, mixed content and live / zerolatency at 1080p, 1440p and 4K), P-only configurations to main `1859bac` (15 configurations with 1-4 threads), the 51-case matrix is JM and ffmpeg bit-exact and identical for 1 and 4 threads, ThreadSanitizer finds nothing in 43 scenarios, and the container checks and `tov test` pass. After merging main `e20b7fe` (`0c662ea`): B-frame configurations are byte-identical to `70ebc48` (the same 36 configurations and footprint sweeps) and to themselves with `--read-ahead 0`, 3 and 5 on 2 and 4 threads (10 configurations), P-only configurations to main `e20b7fe` (15 configurations with 1-4 threads), `--keyint 1` and `2` with the default B-frames to its `--bframes 0` (3 clips x 3 presets x 1-4 threads), the 51-case matrix is JM and ffmpeg bit-exact and identical for 1 and 4 threads, ThreadSanitizer finds nothing in 57 scenarios (14 of them with the read-ahead running), and the container checks and `tov test` (86) pass.
+
+## Numbers
+
+Standard tier, 1080p 10 s, VMAF BD-rate vs x264 veryfast (negative = fewer bits than x264 for the same VMAF), 2026-10-07 07:21, before weighted prediction:
+
+| clip | capcodec-live | capcodec-medium |
+|---|---|---|
+| busy_ui | +9.9% | +9.3% |
+| code_editor | +10.5% | +7.5% |
+| slides | +7.0% (was +65%) | +5.5% (was +57%) |
+| text_scroll | −7.5% | −7.8% |
+| full_motion | +67.7% | +39.0% |
+
+Since then: weighted prediction (slides −6.6% live / −6.9% medium, now fewer bits than x264 veryfast) and texture AQ off by default (capcodec-medium: busy_ui +9.4%, code_editor +7.5%, slides −8.3%, text_scroll −7.8%, full_motion +35.3%; mean +7.2%).
+
+Where full_motion loses: x264 veryfast's B-frames. Without them x264 is +47.5% on full_motion (and +0.0%/+2.2% on busy_ui/code_editor), so capcodec-medium's P-only +35.3% beats x264 veryfast without B-frames by about 12 points (`/tmp/std7`, `/tmp/std8`). capcodec's own B-frames close the gap (next section).
+
+### B-frames
+
+Standard tier, B-frames round 2 (2026-10-08, `/tmp/bf-r2`, branch `bframes` at `ca086f8`, which `6765509` reproduces byte for byte; variants via `CAPCODEC_VARIANTS`, side info on, lookahead on except on live). fast and medium are the defaults (three adaptive B-frames with the pyramid). VMAF BD-rate vs x264 veryfast, PSNR (YUV) in brackets:
+
+| clip | live | live b3 | live b3 pyramid | fast | medium | medium no pyramid | medium P-only |
+|---|---|---|---|---|---|---|---|
+| full_motion | +39.3% (+64.5%) | −8.5% (−4.4%) | −11.0% (−5.2%) | −14.3% (−7.9%) | −15.0% (−11.1%) | −12.7% (−10.3%) | +25.5% (+41.5%) |
+| busy_ui | +5.1% | +5.2% | +5.2% | +1.7% | +1.3% | +1.3% | +1.3% |
+| code_editor | +4.1% | +4.1% | +4.1% | −0.0% | −2.8% | −2.8% | −2.9% |
+| slides | −9.8% | −9.8% | −9.8% | −21.1% | −20.9% | −20.9% | −20.7% |
+| text_scroll | −14.0% | −14.0% | −14.0% | −16.3% | −16.1% | −16.1% | −16.2% |
+| mean | +4.9% (+14.8%) | −4.6% (+0.9%) | −5.1% (+0.7%) | −10.0% (−1.3%) | −10.7% (−2.7%) | −10.3% (−2.5%) | −2.6% (+7.9%) |
+
+Against P-only of the same preset (VMAF/PSNR): full_motion medium −34.1/−37.8%, medium without the pyramid −32.4/−37.1%, live b3 −34.5/−41.7%, live b3 with the pyramid −36.2/−42.2%; the screen clips stay within ±0.1% because adaptive B usage codes them almost entirely as P frames. Main before round 2 (`0c7af6c`, same harness, full_motion, `/tmp/bf-r2-main`): medium −12.2% (−10.0%), live b3 −6.9% (−3.7%). Against main on `tune.py` (full_motion, 120 frames, CRF 22-34, VMAF/PSNR BD-rate): medium −2.94/−1.48%, medium without the pyramid −0.45/−0.34%, fast −4.08/−2.29%, slow −2.22/−1.21%, live b3 −1.50/−0.65%, live b3 with the pyramid −4.27/−1.68%.
+
+Matched-VMAF speed vs x264 veryfast CRF 23 (capcodec CRF from the harness: full_motion live 25, live b3 24, fast and medium 22, and main's medium 22 and live b3 24; busy_ui live 29, fast and medium 32; code_editor 31 and 32; slides 30; text_scroll 30 and 33), 300 frames, interleaved best of 3 per variant, 1 and 4 threads for both encoders, load average 21-27 on the 4-core VM (`/tmp/bfdbg/abtime_r2final.log`, `/tmp/bfdbg/abtime_r2screen.log`):
+
+| | live | live b3 | live b3 pyramid | fast | medium | medium no pyramid | main medium | main live b3 |
+|---|---|---|---|---|---|---|---|---|
+| full_motion, 1 thread, CPU | 1.04x | 1.37x | 1.32x | 1.18x | 1.11x | 1.07x | 0.91x | 1.01x |
+| full_motion, 4 threads, CPU | 0.82x | 1.14x | 1.10x | 1.03x | 0.99x | 1.02x | 0.78x | 0.89x |
+| full_motion, 4 threads, wall | 0.45x | 1.03x | 1.21x | 1.04x | 1.03x | 0.98x | 0.48x | 0.55x |
+| 5 clips geometric mean, 1 thread, CPU | 3.77x | 3.84x | 3.84x | 3.56x | 3.47x | 3.49x | | |
+| 5 clips geometric mean, 4 threads, CPU | 3.39x | 3.55x | 3.58x | 3.32x | 3.23x | 3.27x | | |
+| 5 clips geometric mean, 4 threads, wall | 1.87x | 2.07x | 2.35x | 1.98x | 1.94x | 1.83x | | |
+
+Main was timed on full_motion only. x264's best 4-thread wall time on full_motion was 1.6x its CPU time (it got 0.63 cores at this load), so the 4-thread wall ratios mostly measure the load; the full_motion CPU ratios repeat within about ±3%. On the screen clips live and live b3 make the same decisions on nearly every frame (BD-rate within 0.1%), so their CPU differences of up to 9% (text_scroll, about 1 s encodes) are load noise. Callgrind (x86-64-v2, full_motion 31 frames CRF 24) against main: medium 7.516G → 5.664G instructions (−24.6%), live b3 7.116G → 5.126G (−28.0%); the steps are in DECISIONS.md under B-frames. Peak RSS at 1080p: medium 112.6 MiB on one thread and 151.8 MiB on four (main 91.1 and 95.5), live b3 72.0 and 114.5 MiB (main 60.7 and 65.3); the extra on four threads is the state of concurrently coded B-frames.
+
+Merging thread-efficiency (main `7189fa4`) took 5-8% off the 4-thread CPU time of the B-frame encodes (pipelined entropy, row prep inside the wavefront, adaptive spin-waits) and left 1-thread CPU unchanged (`/tmp/bfdbg/timing_m7.log`, `timing_m8.log`, timed at load 29-57).
+
+After merging main `08b3b02` (`149f001`), in the benchmark lane (`bench/lane.sh run "python3 bench/speedcmp.py ..."`: capcodec's CRF matched in quarter steps to the VMAF of x264 veryfast CRF 23, 300 frames with side info, five interleaved rounds, the rest of the machine paused for each timed run), two sessions for each binary (`/tmp/bfdbg/m9/lane-merged`, `lane-merged-r2`, `lane-main`, `lane-main-r2`). x264's median time over capcodec's (above 1 is faster), first / second session:
+
+| clip, mode | CPU, 1 thread | main | wall, 1 thread | main | CPU, 4 threads | main | wall, 4 threads | main |
+|---|---|---|---|---|---|---|---|---|
+| full_motion medium | 1.46 / 1.49x | 1.32 / 1.27x | 1.39 / 1.42x | 1.27 / 1.21x | 1.31 / 1.33x | 1.17 / 1.16x | 1.15 / 1.16x | 0.92 / 0.92x |
+| full_motion live | 1.69 / 1.63x | 1.41 / 1.40x | 1.62 / 1.56x | 1.35 / 1.34x | 1.47 / 1.50x | 1.19 / 1.21x | 1.32 / 1.33x | 0.96 / 0.97x |
+| full_motion zerolatency | 1.41 / 1.41x | 1.42 / 1.43x | 1.32 / 1.34x | 1.26 / 1.36x | 1.00 / 1.00x | 1.01 / 0.99x | 1.19 / 1.22x | 1.07 / 1.16x |
+| webcam_overlay medium | 3.79 / 3.76x | 3.78 / 3.83x | 3.42 / 3.40x | 3.40 / 3.46x | 3.85 / 3.68x | 3.69 / 3.66x | 2.63 / 2.55x | 2.52 / 2.45x |
+| webcam_overlay live | 4.09 / 4.08x | 4.16 / 4.00x | 3.09 / 3.68x | 3.76 / 3.62x | 3.84 / 3.93x | 4.09 / 3.90x | 2.32 / 2.75x | 2.90 / 2.76x |
+| webcam_overlay zerolatency | 4.38 / 4.46x | 4.41 / 4.42x | 4.00 / 4.09x | 4.05 / 4.03x | 3.94 / 3.90x | 3.87 / 3.87x | 3.65 / 3.60x | 3.57 / 3.65x |
+| busy_ui medium | 6.53 / 6.61x | 6.52 / 6.28x | 5.75 / 5.77x | 5.76 / 5.53x | 6.99 / 7.16x | 7.07 / 7.34x | 3.13 / 3.38x | 3.27 / 3.35x |
+| busy_ui live | 6.70 / 6.73x | 6.81 / 6.70x | 5.78 / 5.91x | 6.01 / 5.88x | 7.91 / 7.71x | 7.52 / 7.45x | 3.79 / 3.56x | 3.57 / 3.51x |
+| busy_ui zerolatency | 6.17 / 6.16x | 6.06 / 6.20x | 5.36 / 5.39x | 5.27 / 5.41x | 6.13 / 6.09x | 6.16 / 6.04x | 3.61 / 3.67x | 3.68 / 3.57x |
+
+full_motion's 4-thread wall clock, main's last speed loss on the scoreboard, is a win: medium 1.94 / 1.86 s against x264's 2.23 / 2.15 s (main 2.48 / 2.34 s), live 1.65 / 1.59 s against 2.18 / 2.11 s (main 2.29 / 2.14 s), from the concurrent and asynchronous B runs; with B-frames full_motion also takes 12-19% less CPU time than on main (round 2's B search and pyramid steps). The matched CRFs are the same for both binaries (full_motion 22.5 / 22.25 / 25.75 for medium / live / zerolatency, webcam_overlay 28.5 / 28.25 / 26.25, busy_ui 32.25 / 32.25 / 25). zerolatency output is byte-identical to main's, and on the screen clips adaptive B usage codes nearly every frame as P, so those rows differ only by the sessions' spread; webcam_overlay live's first session (wall 3.09x and 2.32x) had slow runs, and a 7-round lane recheck put the branch, `c12ee19` and main at 0.75, 0.76 and 0.78 s on one thread and 0.43 s each on four. Peak RSS at 1080p on 1 / 4 threads: full_motion medium 115 / 155 MiB (main 97 / 102, x264 253-260 / 373-385), live 82 / 125 (main 72-73 / 78), zerolatency 52 / 54 as on main; webcam_overlay medium 104 / 119-120 (main 91 / 96), live 70 / 88 (main 67 / 71-72). The extra is the concurrently coded B-frames' state (DECISIONS.md).
+
+After merging main `1859bac` (`f1c6e24`: footprint rounds 3-4, intra-speed round 2; B-frame output byte-identical to `812670f`), each concurrently coded B-frame packs its coefficients into its own chunk store, which halves the B-frames' extra memory. Peak RSS at 1080p on 1 / 2 / 4 threads (90 frames, CRF 26): full_motion live 59 / 85 / 89 MiB (main `1859bac` 58 / 63 / 64, `812670f` 73 / 108 / 112), medium 94 / 116 / 120 (main 83 / 87 / 89, `812670f` 109 / 141 / 144); zerolatency 39 on 4 threads and busy_ui 30-64 as on main; full_motion 4K live 218 / 315 on 1 / 4 threads (main 214 / 229, `812670f` 274 / 416). `--keyint 1` and `2` no longer declare B-frames in the SPS and are byte-identical to `--bframes 0`. In the benchmark lane (two sessions per binary, matched VMAF against x264 veryfast, ratios on 1 / 4 threads), full_motion medium takes 1.58-1.63x / 1.41-1.47x less CPU time and 1.45-1.55x / 1.16-1.25x less wall clock than x264 (main 1.31-1.32x / 1.19-1.22x and 1.26x / 0.94-0.97x), live 1.69-1.72x / 1.56-1.57x and 1.61-1.64x / 1.38-1.39x (main 1.45-1.49x / 1.24-1.30x and 1.39-1.43x / 1.01-1.02x); the 4-thread wall clock is 1.72-1.88 s on medium against x264's 2.15-2.17 s (main 2.16-2.31 s) and 1.48-1.49 s on live against 2.06 s (main 2.01-2.62 s).
+
+After merging main `e20b7fe` (`0c662ea`: read-ahead during B runs, pin7 CABAC round), in the benchmark lane (two sessions per binary), full_motion medium takes 1.69-1.71x / 1.48-1.49x less CPU time and 1.62-1.64x / 1.35-1.40x less wall clock than x264 veryfast on 1 / 4 threads (main `e20b7fe` 1.43-1.45x / 1.25-1.26x and 1.37-1.39x / 1.09-1.10x), live 1.88-1.93x / 1.60-1.66x and 1.80-1.85x / 1.44-1.50x (main 1.58-1.61x / 1.34-1.36x and 1.52-1.54x / 1.19-1.21x); the 4-thread wall clock is 1.51-1.53 s on medium against x264's 2.04-2.15 s (main 1.91-2.01 s) and 1.42-1.53 s on live against 2.13-2.20 s (main 1.71-1.81 s). Peak RSS at 1080p on 1 / 2 / 4 threads (90 frames, CRF 26): full_motion live 59 / 95 / 98 MiB (main 58 / 72 / 73), medium 94 / 126 / 130 (main 82 / 96 / 98); the read-ahead's three extra raw frames add 9-10 MiB on 2 and 4 threads to both, and 38 MiB at 4K (live on 4 threads 353, main 268).
+
+Recommended settings: the defaults (three adaptive B-frames with the pyramid on fast, medium and slow) wherever the reorder delay is acceptable (exports, uploads, the media server and render farm); live also defaults to three adaptive B-frames (no pyramid, 2 frames of lookahead), with `--zerolatency` for no reorder delay and the least memory.
+
+OCR (text-region character error, 3 frames per clip, `bench.py ocr`): the text AQ lowers character errors on scrolling text by about a third at equal bitrate; other clips are within noise.
+
+Lookahead (10 frames, on by default except live), VMAF BD-rate against the encoder without it (busy_ui, code_editor, full_motion, slides, text_scroll; mean): fast −1.6/−5.0/−1.3/−12.6/−4.5 (−5.0%), medium −1.7/−5.0/−0.7/−12.5/−4.5 (−4.9%), slow −1.4/−5.1/−1.7/−14.9/−4.9 (−5.6%). Against x264 veryfast, medium goes from +4.8% to +2.3% and slow from +6.8% to +2.0%. Single-thread instructions −3% to +4% per clip, 10 frames of delay, +31 MB at 1080p; OCR character error is unchanged on text_scroll and lower on code_editor. At equal CRF video gets fewer bits and long-lived screen content more (full_motion CRF 20 13.3 → 7.4 Mbit/s, text_scroll CRF 26 +13%). With 250-frame GOPs full_motion is still about 2% worse than without lookahead while the screen clips gain 3-18%.
+
+Lookahead with adaptive B-frames (the fast, medium and slow defaults since `9bce84f`; DECISIONS.md): every picture is coded with the lookahead map of its own display index, B-frames take the anchor's macroblock QP + 6, and an anchor gains lifetime from the B-frames that predict from it through list 1. VMAF BD-rate against main `9bce84f` (B-frames, no lookahead) of the same preset (busy_ui, code_editor, full_motion, slides, text_scroll; mean): fast −1.6/−5.0/−2.8/−12.6/−4.5 (−5.3%), medium −1.7/−5.0/−2.5/−12.7/−4.5 (−5.3%), slow −1.4/−5.1/−1.8/−15.0/−4.9 (−5.6%); without the list-1 credit medium full_motion is −0.7%. Against x264 veryfast the mean goes from +1.5% to −3.4% (fast), from −0.9% to −5.6% (medium) and from −0.4% to −5.4% (slow). webcam_overlay gains 8.9-11.6%, all of it from main's CRF 20 point (about +2% without it). Single-thread CPU at CRF 26 (best of 5, interleaved, loaded machine) over the six clips: fast +2.8%, medium +1.4%, slow +2.9%; callgrind instructions for medium −2.4/−2.0/+1.4/−0.6/+4.1% (+1.3%). The 5-10% on the shortest screen clips (0.4-1.2 s encodes) is about 8,000 more page faults from first touching the lookahead buffers plus noise; their user time is −3% to +3.5%. Up to 13 frames of output delay (10 lookahead + 3 B-frames), +31 MB at 1080p. OCR character error: busy_ui 3.96 → 4.00, code_editor 4.77 → 4.54, text_scroll 2.02 → 2.03; on slides 0.54 → 0.79 comes from icon and bullet glyphs and source misreads (the P-only lookahead gives 0.80) with equal or higher PSNR in the text regions. At equal CRF full_motion gets 23-29% fewer bits (2-9 VMAF points below main) and the screen clips 4-14% more; holding the mean offset at or below zero keeps main's quality at every CRF but costs 11% CPU at equal CRF (DECISIONS.md).
+
+Lookahead round 3 (2026-10-08, standard tier, six clips; DECISIONS.md): with more than one thread the read-ahead thread runs the propagation for the next frame (main-thread instructions -9.1% full_motion, -29.7% slides at 4 threads); the change map without side info is vectorised (media-server busy_ui -40% instructions); without B-frames, content that a video frame (at least half the macroblocks changed) replaces is assumed to decay geometrically to the horizon. fast, medium, slow, live and `--lookahead 0` are byte-identical to main. The media-server settings (medium, `--keyint 250 --noise 3 --no-sideinfo`) now gain on every clip against `--lookahead 0` (full_motion -1.6%, mean -7.5%); with `--bframes 0` full_motion is still +2.4% (+2.9% before the geometric tail). SATD, half-pel and i16 intra costs in the lookahead gained at most 0.9% (P-only full_motion) for +2.7 to +14% instructions. Live with a short lookahead (VMAF BD-rate against live; instructions at CRF 26 against live; peak memory at 1080p, one thread):
+
+| `--preset live` | busy_ui | code_editor | full_motion | slides | text_scroll | webcam_overlay | mean | vs x264 veryfast | instructions | delay at 30 fps | memory |
+|---|---|---|---|---|---|---|---|---|---|---|---|
+| `--lookahead 0` (default) | | | | | | | | -0.4% | | 0 | 41-52 MB |
+| `--lookahead 1` | -3.4 | -3.3 | +1.9 | -16.5 | -4.0 | -9.8 | -5.9% | -3.8% | -5.3% | 33 ms | +3 MB |
+| `--lookahead 2` | -3.3 | -3.5 | -1.0 | -15.2 | -4.1 | -10.9 | -6.3% | -4.5% | -4.9% | 67 ms | +6 MB |
+| `--lookahead 4` | -3.3 | -3.9 | -1.2 | -14.4 | -4.1 | -12.6 | -6.6% | -4.6% | -4.5% | 133 ms | +12 MB |
+
+Live reads 2 frames ahead by default since `b0d85fb` (67 ms at 30 fps); `--zerolatency` keeps 0. OCR character error at depth 2: text_scroll 1.81 -> 1.41%, slides 0.48 -> 0.45%, code_editor 4.70 -> 4.80%, busy_ui 3.68 -> 4.33% with equal text-region PSNR (-0.29 to +0.25 dB at matched bitrate); the busy_ui rise is icon glyphs Tesseract fuses onto words, and the word-level `ocr_word_cer` stays at or below 0.7% for every clip from ~400 kbps. Medium at depth 6 or 4 saves 12 or 19 MB for +0.06% mean but loses 0.54 or 0.78% on full_motion; the ring of raw frames is the encoder's input delay, so the memory stays.
+
+Lookahead round 4 (2026-10-08, DECISIONS.md): the media server's settings (medium, `--keyint 250 --noise 3`, no side info) spent most of their time in the encoder's scalar per-macroblock change test. Change detection is now one vector pass per frame, two macroblocks per vector row with an exact-equality test first, and the encoder reuses the lookahead's map wherever its source copy is current. Every preset default and `--lookahead 0` is byte-identical to main `52510d7`, and after merging main `7189fa4` to it (270/270 gate runs identical to the pre-merge branch; instructions against `7189fa4` -83.1/-84.3/-88.4/-1.0/-73.0%). At the media-server settings against main `52510d7` (CPU is user + system time, best of 5 interleaved runs on a loaded 4-core VM; full_motion at one thread is the median of 10 paired runs, whose best-of-5 moved between -3 and +4%):
+
+| | busy_ui | code_editor | slides | full_motion | webcam_overlay |
+|---|---|---|---|---|---|
+| instructions, 60 frames, 1 thread | -83.6% | -84.7% | -88.9% | -1.0% | -73.2% |
+| CPU, 300 frames, 1 thread | -62.6% | -66.1% | -40.1% | -0.6% | -32.1% |
+| CPU, 300 frames, default threads | -61.1% | -58.8% | -36.2% | | -31.7% |
+
+P-only GOPs longer than 2 s (`--bframes 0 --keyint 250`) end content that a video frame replaces at the window edge: -0.76% mean VMAF BD-rate (slides -2.78, webcam_overlay -1.24, full_motion -0.50%, no clip worse), full_motion +1.67% against `--lookahead 0` (was +2.37%). The busy_ui OCR difference under the live lookahead is icon glyphs that OCR reads as characters, in mostly unchanging text, with higher text PSNR and a sign that flips between CRFs and regions; capping the lookahead's QP raise on text macroblocks does not change it and gives up a fifth to a third of the BD-rate gain, so live keeps reading 2 frames ahead as measured (its default since `b0d85fb`).
+
+Single-thread speed at 1080p (live preset, warm page cache): busy_ui ~590 fps (a third of it is the kernel copying the raw input file; a library integration would not pay that), code_editor ~450, text_scroll ~140, slides ~160, full_motion ~21.5. x264 veryfast on this VM: ~110-145 fps on one core, ~150-370 on four.
+
+Intra coding at equal QP (all-intra, AQ off): capcodec frames are 2.5% larger than x264 veryfast's with luma PSNR within 0.1 dB; chroma is ~1 dB lower because x264 uses chroma_qp_index_offset −2 (VMAF ignores chroma).
+
+Change-proportional cost (slow_typing, earlier measurement): static frame 0.18% of a full frame with side info; 1.7% with the pixel-difference fallback.
+
+## Speed rounds (profile-driven; each round worked on the top stage)
+
+| Round | Top stage | Change | Effect |
+|---|---|---|---|
+| 1-4 | ME, intra | sub-pel prediction, cached half-pel tiles, intra early exits, table-driven directional intra | full-change frame 265 → 125 ms |
+| 5 | entropy (IDR) | byte-oriented CABAC | IDR entropy 31 → 14 ms |
+| 6 | mode + tq (IDR) | IDR macroblock reuse | IDR ~95 → ~45 ms on typing/editor/UI clips (79-99% of macroblocks reused) |
+| 7 | bookkeeping | one MV per macroblock, untouched skip state | 10-20% on motion-heavy clips |
+| 8 | deblock | batched edges, flat-line skip | busy_ui deblock 38 → 27 ms total |
+| 9 | ME/mode (video) | SIMD SAD/SATD/SA8D/half-pel/qpel | full_motion 10.3 → 16.1 fps |
+| 10 | tq (video) | SIMD 4x4 transforms and quantisation | 16.1 → 18.6 fps |
+| 11 | analysis | SIMD classification, row hashing, copies | 19.8 → 21.5 fps |
+
+Current full-motion profile (live, per frame): tq 16, motion 14, analysis 9.5, mode 6.7, deblock 3.9, entropy 2.8 ms.
+
+## Research applied
+
+- OpenAI math preprints (`~/work/openai-math`, 722 papers): the algorithmic results (DFT in O(n (log n)^(1−10⁻¹³)), complex matrix multiplication below 2.258, integer multiplication below n log n, finite tensor savings for Fourier circuits) are asymptotic and do not reduce work at H.264's 4x4/8x8 integer butterflies, which are already at minimal add counts; the bottleneck is vector throughput and memory traffic. Recorded in DECISIONS.md.
+- Applied from video-coding practice: hash/profile-based global motion (screen content coding), byte-oriented CABAC (x264/FFmpeg style), weighted prediction for fades, x264-style decimation and fast skip, SIMD kernels. Tried and reverted: EPZS-style cursor and dominant-motion predictors for every macroblock (no gain on the corpus, slides +0.7%).
+
+## Tov
+
+`encoder-features` branch (all committed): binary fs I/O, `--unchecked`, typed arrays, SIMD vectors, threads and Atomics, borrowed typed-array field arguments (`976bb78`), loop hoisting of array fields (`dee1ec3`), module init order (`d8a0f81`), `Math.clz32`/`imul` (`eced999`), C library output `tov build --lib` (`5cb7538`: `libname.a/.so` + `name.h`, typed arrays borrowed zero-copy, opaque class handles, `name_last_error`), function-value adapters (`7b58f21`), `--target wasm32-wasi` for programs and libraries (`3bee8b1`; a thread-free capcodec build is byte-identical to native at 1.86x the CPU per frame). The installed compiler is `encoder-features` 20ea68f (from `~/work/tov-pin7`, installed 2026-10-09 07:50; capcodec builds byte-identically to 538446e; adds horizontal `min`/`max`/`minIndex`/`maxIndex` (`phminposuw`), vector records returned in registers, `mulHigh`/`mulWideLow`/`mulWideHigh`, `@inline`/`@noinline`, Buffer-style `readUInt32LE`/`writeUInt32BE`/... on `Uint8Array`; 538446e stays at `/usr/local/cargo/bin/tov.pin6-538446e`). Previously 538446e (from `~/work/tov-pin6`, installed 2026-10-08 23:50; against 64982fa: capcodec unchecked 620,816 -> 550,024 bytes, 0.8-1.8% fewer instructions, clean builds compiled as 16 parallel C units, `Math.select`, run-time `T.shuffle`, `pushFrom`, `Math.idiv`, `Target.vectorBits`, narrowing stores, `discard`; byte-identical encodes; 64982fa stays at `/usr/local/cargo/bin/tov.pin5-64982fa`). Previously 64982fa (from `~/work/tov-pin5`; 2.9-5.2% fewer capcodec instructions than 548ff6b, byte-identical output, multi-target `--target-cpu x86-64-v3,x86-64-v4` binaries, `--profile-generate`, module constants as C constants, smaller binaries): element borrows folded in (72b793b), serial threads on wasm (3b00bba), 512-bit vectors and concat/low/high, register-resident sums, mask/ctz/popcount, branch-free `?:`, borrowed typed-array locals, integer-quotient rounding, Atomics memory orders, Int64Array and 64-bit lanes, Channel, parallelFor options; capcodec builds byte-identically with it. See TOV_GAPS.md.
+
+## How to resume
+
+```sh
+export PATH=$HOME/tools/bin:$PATH # static ffmpeg 8.1 (libx264, libopenh264, libvmaf), JM ldecod
+cd ~/work/tov-pin2 && git log --oneline -1 && cargo +1.88.0 install --path crates/tov # elem-borrow 02a302a on top of encoder-features
+cd ~/work/capcodec && bench/build_encoder.sh
+python3 bench/bench.py smoke # < 60 s, regression gate
+python3 bench/bench.py standard --encoders "capcodec-live,capcodec-medium,x264-veryfast"
+python3 tools/profile.py full_motion busy_ui --presets live,medium # per-stage times
+python3 tools/verify.py slides --binary build/capcodec-unchecked --preset medium # JM + ffmpeg bit-exact check
+```
+
+Backups (git bundles of capcodec and the Tov branch, PROGRESS.md) are written to `/cursor/stores/self/backups` by `tools/backup.sh`.
+
+## Next steps
+
+1. Parallel entropy coding for IDR frames (a few row-band slices, about +0.5% bits) and row-parallel deblocking: IDR frames are now the serial bottleneck on typing/editor/UI clips.
+2. Full-motion efficiency: live preset is +68% BD vs medium's +39% without B-frames; stronger motion search where the frame is video-like, SIMD 8x8 transforms, intra in P frames. B-frames next steps: B sub-partitions (16x8, 8x16, 8x8 and direct 8x8), lookahead to choose the B run length per scene (and to credit the middle B-frame of a pyramid run), a second reference per list, and entropy coding of B rows as they finish so concurrent B-frames need a few rows of coefficients instead of a frame.
+3. Screen-content BD-rate: tune I/P offset, refresh, lifetime AQ and AQ strength with harness variants; transient-content QP for animations.
+4. C ABI build for crates/export, WASM build for the browser export, FINDINGS.md.
+5. Lookahead: choose the B run length and reference structure from its lifetimes (the changed-macroblock count alone lost 5% on pulldown, DECISIONS.md); an opt-in quality-anchored CRF (the one-sided offset clamp) where CRF has to mean the same quality on video; P-only long GOPs, where full_motion still loses 1.7% (a per-macroblock tail from how long each block's motion has lasted, or intra refresh of the decayed content); a changed-macroblock ring sharing the encoder's buffers.
+6. Media-server CPU after the change-detection round: CABAC (163M of busy_ui's 558M instructions over 60 frames, about 70M of it the first IDR frame), the change map (70M, nearly all of it the lookahead's pass, which already runs on the read-ahead thread with more than one thread), intra decisions (41M, mostly the IDR frame), and letting B-run anchors take the lookahead's map (full_motion: 3 of 17 anchors can today).
diff --git a/capcodec/README.md b/capcodec/README.md
new file mode 100644
index 000000000..eab724a46
--- /dev/null
+++ b/capcodec/README.md
@@ -0,0 +1,7 @@
+# capcodec
+
+Tov source for the H.264 screen encoder used when `CAP_MEDIA_VIDEO_ENCODER=capcodec`. This directory is the `main` snapshot (`517b7e6`). Cap CI leaves it unbuilt. Mount a binary as described in `apps/media-server/capcodec.md`.
+
+`capcodec.bundle` stores every branch. Restore it with `git clone capcodec.bundle`. The media-server flag runs `main`. `rd-next`, `ssim`, `intra-rd`, and `dashboard` stay on their own branches.
+
+Benchmark notes keep the commit ids of the builds that were measured. In this bundle those commits are `76be2a6` (measured as `00fecf7`), `82b7840` (measured as `fff504d`), `42e1d3b` (measured as `d0cce5e`, branch `rd-next`), and `6610051` (measured as `b72e995`, branch `ssim`).
diff --git a/capcodec/SCOREBOARD.md b/capcodec/SCOREBOARD.md
new file mode 100644
index 000000000..68e14f770
--- /dev/null
+++ b/capcodec/SCOREBOARD.md
@@ -0,0 +1,177 @@
+# Scoreboard against x264 veryfast
+
+Quality measured 2026-10-09 on main `fff504d`. Speed remeasured the same day on main `00fecf7` (read-ahead, pin7 intra minIndex, CABAC table). Those commits match the `fff504d` bitstreams, so the quality tables still describe this encoder. Pending quality branch `rd-next` `d0cce5e`. All 12 corpus clips.
+
+How to reproduce:
+
+- Quality: `CAPCODEC_BIN_UNCHECKED=<binary> python3 bench/bench.py standard --quality-only --encoders capcodec-medium,capcodec-live,capcodec-live-zerolatency,x264-veryfast,x264-veryfast-zerolatency --out <dir>` (1080p, 10 s per clip; code_4k is scaled to 1080p here). capcodec's CRF ladder runs 20-44 so its VMAF range covers x264's CRF 18-33; the overlap column shows how much of the two curves BD-rate compares (it was 15-24% on screen clips with the old 20-36 ladder).
+- Speed: `bench/lane.sh start`, then `bench/lane.sh run "python3 bench/speedcmp.py --binary <binary> --clips all --modes medium,live,zerolatency --retime bench/out/speedcmp-fff504d-v2 --out <dir>"`. The rerun reuses the CRF that matched x264 CRF 23 (bitstreams are unchanged, so the match stands). 5 shuffled, interleaved rounds at 1 and 4 threads; every other process is stopped for each timed run (about 690 processes stopped, frozen median). code_4k runs at native 4K for 5 s. Output: `bench/out/speedcmp-00fecf7`.
+- Tables: `python3 bench/scoreboard.py --quality LABEL=<dir> --speed LABEL=<dir> --out SCOREBOARD.md`.
+
+### main fff504d: capcodec-medium vs x264-veryfast (BD-rate, negative = capcodec needs fewer bits)
+
+| clip | VMAF | PSNR-YUV | SSIM | VMAF range overlap |
+|---|---|---|---|---|
+| busy_ui | +5.4% lose | +5.1% lose | +14.8% lose | 52% |
+| busy_ui_60fps | +2.6% lose | +2.0% lose | +16.8% lose | 74% |
+| code_4k | -3.3% win | +1.0% lose | +9.2% lose | 72% |
+| code_editor | -0.5% win | +4.9% lose | +7.3% lose | 76% |
+| dark_mode | -17.2% win | -16.9% win | -11.9% win | 75% |
+| dashboard | +7.9% lose | +12.3% lose | +25.9% lose | 59% |
+| full_motion | -12.2% win | -10.0% win | +4.8% lose | 44% |
+| idle | -8.8% win | -6.3% win | -3.4% win | 73% |
+| slides | -18.0% win | +0.5% lose | -3.6% win | 66% |
+| slow_typing | -0.8% win | +4.5% lose | +8.6% lose | 80% |
+| text_scroll | -15.5% win | -14.8% win | -14.9% win | 88% |
+| webcam_overlay | -20.0% win | -4.3% win | -4.0% win | 69% |
+
+19 wins, 17 losses across 12 clips x 3 metrics.
+
+### main fff504d: capcodec-live vs x264-veryfast (BD-rate, negative = capcodec needs fewer bits)
+
+| clip | VMAF | PSNR-YUV | SSIM | VMAF range overlap |
+|---|---|---|---|---|
+| busy_ui | +5.7% lose | +5.7% lose | +15.6% lose | 51% |
+| busy_ui_60fps | +3.5% lose | +2.9% lose | +18.1% lose | 73% |
+| code_4k | +0.2% lose | +5.3% lose | +13.4% lose | 72% |
+| code_editor | +2.8% lose | +8.6% lose | +11.2% lose | 76% |
+| dark_mode | -16.6% win | -16.2% win | -10.9% win | 75% |
+| dashboard | +10.8% lose | +15.7% lose | +29.3% lose | 61% |
+| full_motion | -7.8% win | -1.9% win | +12.0% lose | 43% |
+| idle | -8.4% win | -6.2% win | -3.0% win | 72% |
+| slides | -20.0% win | -1.5% win | -6.4% win | 65% |
+| slow_typing | +1.1% lose | +4.8% lose | +9.1% lose | 78% |
+| text_scroll | -15.1% win | -14.7% win | -14.8% win | 88% |
+| webcam_overlay | -18.7% win | -3.8% win | -1.7% win | 67% |
+
+17 wins, 19 losses across 12 clips x 3 metrics.
+
+### main fff504d: capcodec-live-zerolatency vs x264-veryfast-zerolatency (BD-rate, negative = capcodec needs fewer bits)
+
+| clip | VMAF | PSNR-YUV | SSIM | VMAF range overlap |
+|---|---|---|---|---|
+| busy_ui | +1.6% lose | +2.3% lose | +6.7% lose | 23% |
+| busy_ui_60fps | +2.0% lose | +1.9% lose | +9.2% lose | 30% |
+| code_4k | -1.2% win | +2.4% lose | +7.9% lose | 36% |
+| code_editor | -0.5% win | +8.0% lose | +5.8% lose | 36% |
+| dark_mode | -22.3% win | -21.6% win | -21.3% win | 35% |
+| dashboard | +0.2% lose | +2.3% lose | +7.4% lose | 27% |
+| full_motion | -3.1% win | -1.0% win | +15.1% lose | 98% |
+| idle | -17.2% win | -17.8% win | -15.6% win | 28% |
+| slides | -30.8% win | -22.7% win | -20.8% win | 40% |
+| slow_typing | -0.8% win | +3.8% lose | +4.8% lose | 37% |
+| text_scroll | -16.3% win | -17.6% win | -20.7% win | 33% |
+| webcam_overlay | -74.8% win | -64.5% win | -54.8% win | 42% |
+
+20 wins, 16 losses across 12 clips x 3 metrics.
+
+### rd-next d0cce5e: capcodec-medium vs x264-veryfast (BD-rate, negative = capcodec needs fewer bits)
+
+| clip | VMAF | PSNR-YUV | SSIM | VMAF range overlap |
+|---|---|---|---|---|
+| busy_ui | -17.0% win | -2.4% win | +6.5% lose | 65% |
+| busy_ui_60fps | -18.8% win | -3.8% win | +6.4% lose | 42% |
+| code_4k | -23.0% win | -1.4% win | +5.0% lose | 57% |
+| code_editor | -22.7% win | -3.7% win | +2.5% lose | 57% |
+| dark_mode | -35.0% win | -19.9% win | -13.5% win | 58% |
+| dashboard | -12.3% win | +3.2% lose | +12.8% lose | 77% |
+| full_motion | -21.6% win | -8.9% win | +1.5% lose | 52% |
+| idle | -24.0% win | -11.8% win | -2.9% win | 66% |
+| slides | -33.6% win | -13.3% win | -10.2% win | 81% |
+| slow_typing | -22.4% win | -4.1% win | +2.2% lose | 43% |
+| text_scroll | -31.1% win | -19.6% win | -14.3% win | 54% |
+| webcam_overlay | -34.1% win | -14.0% win | +3.4% lose | 87% |
+
+27 wins, 9 losses across 12 clips x 3 metrics.
+
+### rd-next d0cce5e: capcodec-live vs x264-veryfast (BD-rate, negative = capcodec needs fewer bits)
+
+| clip | VMAF | PSNR-YUV | SSIM | VMAF range overlap |
+|---|---|---|---|---|
+| busy_ui | -17.3% win | -2.3% win | +6.5% lose | 64% |
+| busy_ui_60fps | -18.9% win | -3.7% win | +6.5% lose | 42% |
+| code_4k | -22.7% win | -1.3% win | +5.2% lose | 58% |
+| code_editor | -22.1% win | -3.7% win | +2.7% lose | 57% |
+| dark_mode | -34.4% win | -19.6% win | -13.0% win | 59% |
+| dashboard | -12.4% win | +3.8% lose | +14.0% lose | 73% |
+| full_motion | -18.0% win | -2.6% win | +6.8% lose | 51% |
+| idle | -23.8% win | -11.7% win | -2.7% win | 67% |
+| slides | -35.3% win | -15.6% win | -12.6% win | 83% |
+| slow_typing | -21.3% win | -4.1% win | +2.2% lose | 43% |
+| text_scroll | -31.0% win | -19.6% win | -14.3% win | 54% |
+| webcam_overlay | -34.1% win | -14.9% win | +1.2% lose | 88% |
+
+27 wins, 9 losses across 12 clips x 3 metrics.
+
+### rd-next d0cce5e: capcodec-live-zerolatency vs x264-veryfast-zerolatency (BD-rate, negative = capcodec needs fewer bits)
+
+| clip | VMAF | PSNR-YUV | SSIM | VMAF range overlap |
+|---|---|---|---|---|
+| busy_ui | -21.3% win | -6.6% win | +1.0% lose | 48% |
+| busy_ui_60fps | -18.9% win | -6.2% win | +3.0% lose | 64% |
+| code_4k | -20.7% win | -0.8% win | +5.4% lose | 62% |
+| code_editor | -22.6% win | -3.7% win | +2.8% lose | 62% |
+| dark_mode | -37.4% win | -26.1% win | -22.1% win | 58% |
+| dashboard | -21.6% win | -7.8% win | -0.1% win | 45% |
+| full_motion | -15.6% win | -0.3% win | +7.4% lose | 62% |
+| idle | -33.5% win | -25.2% win | -13.5% win | 46% |
+| slides | -46.6% win | -35.0% win | -23.4% win | 58% |
+| slow_typing | -21.3% win | -6.2% win | +0.5% lose | 70% |
+| text_scroll | -32.6% win | -24.5% win | -20.8% win | 53% |
+| webcam_overlay | -80.6% win | -64.2% win | -43.9% win | 58% |
+
+30 wins, 6 losses across 12 clips x 3 metrics.
+
+### main 00fecf7: speed at matched VMAF (x264 / capcodec, interleaved medians, other work paused)
+
+| clip | mode | VMAF | CPU 1t | wall 1t | CPU 4t | wall 4t | peak RSS 4t capcodec / x264 MiB |
+|---|---|---|---|---|---|---|---|
+| busy_ui | live | 94.5 | 7.42x win | 6.55x win | 8.25x win | 4.40x win | 46 / 377 |
+| busy_ui_60fps | live | 93.2 | 8.20x win | 7.23x win | 9.21x win | 4.17x win | 46 / 374 |
+| code_4k | live | 95.2 | 8.92x win | 7.96x win | 9.73x win | 4.58x win | 176 / 1304 |
+| code_editor | live | 94.4 | 7.36x win | 6.52x win | 7.97x win | 4.49x win | 49 / 382 |
+| dark_mode | live | 93.4 | 7.33x win | 6.54x win | 6.80x win | 4.59x win | 48 / 393 |
+| dashboard | live | 94.4 | 3.86x win | 3.51x win | 4.25x win | 2.10x win | 51 / 384 |
+| full_motion | live | 88.2 | 1.61x win | 1.54x win | 1.37x win | 1.21x win | 80 / 379 |
+| idle | live | 95.3 | 9.18x win | 8.11x win | 10.19x win | 4.55x win | 44 / 379 |
+| slides | live | 95.0 | 5.15x win | 4.64x win | 4.61x win | 3.24x win | 74 / 391 |
+| slow_typing | live | 95.2 | 7.87x win | 6.88x win | 8.82x win | 4.15x win | 45 / 387 |
+| text_scroll | live | 95.0 | 4.88x win | 4.40x win | 3.84x win | 3.10x win | 53 / 384 |
+| webcam_overlay | live | 95.4 | 4.64x win | 4.21x win | 4.55x win | 3.46x win | 74 / 391 |
+| busy_ui | medium | 94.5 | 7.30x win | 6.31x win | 7.77x win | 4.11x win | 77 / 371 |
+| busy_ui_60fps | medium | 93.2 | 8.08x win | 7.13x win | 8.77x win | 4.09x win | 77 / 372 |
+| code_4k | medium | 95.2 | 7.96x win | 7.13x win | 8.78x win | 3.89x win | 308 / 1279 |
+| code_editor | medium | 94.4 | 7.01x win | 6.17x win | 7.88x win | 4.13x win | 83 / 379 |
+| dark_mode | medium | 93.4 | 7.25x win | 6.48x win | 6.37x win | 4.24x win | 79 / 386 |
+| dashboard | medium | 94.4 | 3.59x win | 3.21x win | 3.82x win | 1.75x win | 85 / 382 |
+| full_motion | medium | 88.2 | 1.39x win | 1.33x win | 1.22x win | 1.06x win | 103 / 375 |
+| idle | medium | 95.3 | 9.37x win | 8.30x win | 10.28x win | 4.54x win | 73 / 385 |
+| slides | medium | 95.0 | 4.86x win | 4.40x win | 4.34x win | 2.90x win | 98 / 384 |
+| slow_typing | medium | 95.2 | 7.94x win | 6.94x win | 8.26x win | 3.97x win | 76 / 384 |
+| text_scroll | medium | 95.0 | 4.39x win | 3.88x win | 3.64x win | 2.89x win | 88 / 385 |
+| webcam_overlay | medium | 95.4 | 4.32x win | 3.92x win | 4.20x win | 3.01x win | 99 / 386 |
+| busy_ui | zerolatency | 96.0 | 6.79x win | 5.96x win | 6.92x win | 3.85x win | 34 / 144 |
+| busy_ui_60fps | zerolatency | 95.5 | 7.75x win | 6.82x win | 7.96x win | 3.95x win | 34 / 150 |
+| code_4k | zerolatency | 96.0 | 7.51x win | 6.58x win | 7.06x win | 3.92x win | 113 / 458 |
+| code_editor | zerolatency | 95.8 | 6.32x win | 5.51x win | 6.38x win | 3.61x win | 34 / 146 |
+| dark_mode | zerolatency | 95.5 | 6.51x win | 5.67x win | 5.00x win | 3.76x win | 34 / 151 |
+| dashboard | zerolatency | 96.1 | 3.44x win | 3.08x win | 3.64x win | 2.17x win | 37 / 150 |
+| full_motion | zerolatency | 88.1 | 1.65x win | 1.58x win | 1.21x win | 1.49x win | 46 / 142 |
+| idle | zerolatency | 96.4 | 9.40x win | 8.32x win | 8.89x win | 4.40x win | 34 / 141 |
+| slides | zerolatency | 96.2 | 4.84x win | 4.34x win | 3.86x win | 2.95x win | 39 / 149 |
+| slow_typing | zerolatency | 96.4 | 7.15x win | 6.15x win | 7.16x win | 3.53x win | 34 / 148 |
+| text_scroll | zerolatency | 96.3 | 3.90x win | 3.45x win | 3.12x win | 2.78x win | 38 / 149 |
+| webcam_overlay | zerolatency | 96.2 | 5.17x win | 4.73x win | 4.60x win | 4.27x win | 39 / 142 |
+- live 1 thread cpu: geometric mean 5.83x, min 1.61x (12/12 clips faster)
+- live 1 thread wall: geometric mean 5.23x, min 1.54x (12/12 clips faster)
+- live 4 threads cpu: geometric mean 5.87x, min 1.37x (12/12 clips faster)
+- live 4 threads wall: geometric mean 3.46x, min 1.21x (12/12 clips faster)
+- medium 1 thread cpu: geometric mean 5.53x, min 1.39x (12/12 clips faster)
+- medium 1 thread wall: geometric mean 4.94x, min 1.33x (12/12 clips faster)
+- medium 4 threads cpu: geometric mean 5.51x, min 1.22x (12/12 clips faster)
+- medium 4 threads wall: geometric mean 3.15x, min 1.06x (12/12 clips faster)
+- zerolatency 1 thread cpu: geometric mean 5.39x, min 1.65x (12/12 clips faster)
+- zerolatency 1 thread wall: geometric mean 4.80x, min 1.58x (12/12 clips faster)
+- zerolatency 4 threads cpu: geometric mean 4.90x, min 1.21x (12/12 clips faster)
+- zerolatency 4 threads wall: geometric mean 3.26x, min 1.49x (12/12 clips faster)
+
diff --git a/capcodec/TOV_GAPS.md b/capcodec/TOV_GAPS.md
new file mode 100644
index 000000000..e7b853246
--- /dev/null
+++ b/capcodec/TOV_GAPS.md
@@ -0,0 +1,155 @@
+# Tov gaps
+
+Features an encoder needs that Tov lacked, what was added on the `encoder-features` branch of Tov, and why. Each feature is general purpose, follows Tov's conventions, and ships with tests and spec updates.
+
+| # | Gap | Status | Commit |
+|---|---|---|---|
+| 1 | Binary file I/O (`readFileSync` only returned strings) | done | `9cfd397` feat(fs) |
+| 2 | `--unchecked` kept bounds checks | done | `bce77c2` feat(unchecked) |
+| 3 | Typed arrays (reference semantics, no copy-on-write, shareable) | done | `d4f036f` feat(typed-arrays) |
+| 4 | SIMD vector types | done | `d65eb21` feat(simd) |
+| 5 | Threads and Atomics | done | `386512e` feat(threads) |
+| 6 | C ABI library output (`tov build --lib`) | planned | |
+| 7 | WASM target | planned | |
+| 8 | Field array stores re-check uniqueness on every store | open | |
+| 9 | Module constants initialised by calls see imported constants empty | open | |
+| 10 | Typed arrays passed from class fields retain/release atomically per call | done (arguments `976bb78`; element access `02a302a` on branch elem-borrow) | |
+
+## 1. Binary file I/O
+
+**Gap.** `node:fs` had only `readFileSync`/`writeFileSync` on strings. An encoder reads raw YUV frames (3 MB each at 1080p) from files and pipes and writes bitstreams.
+
+**Added.** Node's descriptor API: `openSync`, `closeSync`, `readSync(fd, &buffer, offset?, length?, position?)`, `writeSync(fd, buffer, offset?, length?, position?)`, `fstatSync`. Because Tov arrays are values, `readSync` takes its `u8[]` buffer `inout` (`&buffer`); to support that, standard-library natives can now declare an `inout` array parameter (`native_inout_param`), which code generation passes by pointer after making the buffer unique. Writes to stdout flush `console.log`'s buffer first so output never interleaves. Errors use Node's messages (`EBADF: bad file descriptor, read`), ranges are checked with Node's `RangeError` text.
+
+**Tests.** `tests/run/native_fs_bytes.tov`. **Spec.** §7a.
+
+## 2. `--unchecked` drops bounds checks
+
+**Gap.** `--unchecked` only made integer overflow wrap; every `xs[i]!` and `xs[i] = v` still compared against the length, which blocks vectorisation of pixel loops.
+
+**Added** (commit `bce77c2`): under `--unchecked`, `xs[i]!`, index assignment and compound assignment compile to bare loads/stores (out of bounds is undefined behaviour, as in C); `xs[i]` keeps its defined `T | undefined` result; sized-integer conversions keep the low bits and unary minus and `**` wrap. A 16x16 SAD over a 1080p frame: 0.92 ms instead of 1.5 ms.
+
+**Encoder measurement.** The production presets build with `--unchecked` (see DECISIONS.md); the checked build is kept for the harness's `capcodec-medium-checked` adapter and every unit test.
+
+## 3. Typed arrays
+
+**Gap.** Tov arrays are copy-on-write values, so a buffer held in a class field is made unique on every write, and nothing can be shared between threads or wrapped around memory owned by a C caller.
+
+**Added** (commit `d4f036f`): `Uint8Array`, `Int8Array`, `Uint16Array`, `Int16Array`, `Uint32Array`, `Int32Array`, `Float32Array`, `Float64Array`, `Uint8ClampedArray` with JavaScript semantics (shared references, fixed length, `subarray` views, `set`, `fill`, ...), one compare per element access (none unchecked), atomic reference counts, `readSync`/`writeSync` on `Uint8Array`.
+
+**Follow-up gap (10).** Passing a typed array held in a class field as an argument retains and releases it around every call, atomically. Porting the encoder to typed arrays (branch `typed-arrays-port` in capcodec, bit-identical output) made it 2x slower for this reason alone (transform/quant 1.9 ms → 8.6 ms per 1080p frame), so the encoder stays on `u8[]`/sized-number arrays. Fix to make in Tov: biased reference counting (plain increments until a typed array is shared with another thread) and/or not retaining field reads passed to callees that cannot reassign the field.
+
+## 4. SIMD vector types
+
+**Gap.** Every pixel kernel (SAD, SATD, interpolation, transforms, deblocking) was scalar; clang's auto-vectoriser does not vectorise loops over Tov arrays with 64-bit `int` arithmetic.
+
+**Added** (commit `d65eb21`): `i8x16 u8x16 i16x8 u16x8 i32x4 u32x4 f32x4` and their 256-bit twins as values compiled to the C compiler's vector extensions; `T.load`/`v.store` on typed arrays and sized-number arrays (one bounds check per access, none unchecked), widening loads, lane-wise arithmetic, masks and `select`, `absDiff`, `avg`, `u8x16.sad` (psadbw), `i16x8.madd` (pmaddwd), literal shuffles/swizzles, `widenLow/High`, `packSat`, `bitcast`, `convert`, and `tov build --target-cpu`.
+
+**Encoder use.** SAD, 4x4/8x8 SATD and SA8D, the 6-tap half-pel tiles, quarter-pel averaging, the 4x4 forward and inverse transforms with quantisation, macroblock classification, scroll row hashing, unchanged-macroblock tests, copies and weighted prediction run on vectors; each kernel has a unit test against its scalar definition and the encoder's output stayed byte-identical. Full-motion 1080p (live preset, one core): 10.3 → 21.5 fps across these rounds.
+
+## 8. Field array stores re-check uniqueness on every store
+
+**Gap.** `this.xs[i] = v` on an array held in a class field compiles to `tvg_at_mut(&self->f_xs, ...)`: a copy-on-write uniqueness check (load the buffer pointer, load its refcount) on every store, which the C compiler cannot hoist because the store may alias the refcount. A loop over 8160 macroblocks copying one field array into another (`prevMvx[mb] = mvx[mb]`) took 8% of a whole encode.
+
+**Workaround in the encoder.** Hot loops move into free functions taking the arrays `inout` (one uniqueness check per call), and per-macroblock state was shrunk (one motion vector per macroblock instead of sixteen).
+
+**Fix to make in Tov.** Hoist the uniqueness check and data pointer of a field array out of a loop when the loop body cannot make the array shared (no assignment of the field to another binding, no calls that receive it by value).
+
+## 9. Module constants initialised by calls see imported constants empty
+
+**Gap.** `const T: int[] = build()` at module level, where `build` reads a constant array exported by another module, ran before that module's constants were initialised, and trapped (`index 0 out of bounds for length 0`).
+
+**Workaround in the encoder.** Derived tables (CABAC state transitions, significance context maps, renormalisation shifts, 32-bit quantisation tables) are generated by `tools/gen_tables.py` as literals.
+
+**Fix to make in Tov.** Initialise modules in dependency order (imports first), as JavaScript does.
+
+## 10. Typed-array reference counting on shared data (threads)
+
+**Gap.** With threads, every atomic retain/release of a shared typed array bounces its header's cache line between cores. The encoder's wavefront was slower on 4 threads than on 1 (full_motion 11 vs 15 fps) because field reads passed as arguments (`sad(this.srcY, ...)`), element stores whose value read another field (`this.qpY[mb] = this.mbQp[mb]!`) and element reads whose index read a field (`this.changed[mby * this.mbw + mbx]!`) each took a count.
+
+**Added.** `976bb78` (Tov task): field reads passed to calls are lent without a count when no code the call can run replaces that field. `02a302a` (branch `elem-borrow`, by the encoder author, to be folded in with a test): an element access keeps the array alive only when its index or stored value may replace the field it was read from (Tov's `ta_element` used a syntactic "runs code" test that treated every field read and conversion call as running code). Remaining encoder-side rule: scratch buffers are typed arrays, because a call with an `inout` argument still retains its other typed-array arguments.
+
+**Effect.** 4-thread wavefront: full_motion 1080p 50.8 fps (one thread 25.0), text_scroll 295 (122); byte-identical output.
+
+## 11. Comparing a typed-array element with a sized-integer literal crashes code generation
+
+`ta[i]! === u8(0)` (or `i32(0)`) type-checks but fails in C generation with "internal compiler error: no conversion from `u8` to `int`" (C0003), reported at 1:1 of the entry file. Workaround: compare with an untyped literal (`=== 0`). Fix in Tov: either reject the comparison in the checker with a fix suggestion or convert.
+
+## 12-18. Found while vectorising intra coding (intra-speed branch, all worked around)
+
+12. **`.sum()` widens to 256-bit.** `d.abs().sum()` on an `i16x8` lowers to `__builtin_reduce_add` over eight 32-bit lanes (`vpmovsxwd %xmm,%ymm; vpaddd; vextracti128; ...`, 24 sites). Wanted: lane-width-preserving reductions, pmaddwd-style pair sums for 8/16-bit lanes, horizontal add and movemask primitives. Workaround: accumulate in 16-bit lanes, reduce once per block.
+13. **A typed-array local copied from a field takes an atomic count** (`const t = this.c` emits `tv_ta_retain`/`tv_ta_release`), while indexing `this.c[i]!` reloads `self_->f_c->data` and `len` on every access because C is built with `-fno-strict-aliasing`. Wanted: borrow such locals when the field cannot be replaced in their scope (same analysis as gap 10), and keep the data pointer in a register. Workaround: pass arrays as parameters.
+14. **`Atomics.wait`/`notify` share one process-global mutex and a linear waiter list**; `notify` locks it even with no waiters. Wanted: per-address (hashed) wait queues and a lock-free no-waiter fast path. Workaround: per-entry waiter counts in capcodec.
+15. **The conditional operator lowers to `if`/`else`**, which clang kept as an unpredictable branch in the CABAC LPS select. Wanted: emit `c ? a : b` as a C conditional expression when both arms are pure. Workaround: mask arithmetic.
+16. **No combine of two 128-bit vectors into a 256-bit one** (or split): the 16-lane deblock had to store two `i16x8` and reload an `i16x16`, defeating store-to-load forwarding. (Requested with the AVX-512 work: `concat`/`low`/`high`.)
+17. **No 64-bit typed arrays or 64-bit vector lanes** (`BigInt64Array`-like `Int64Array`/`Uint64Array`, `i64x2`/`i64x4`): CABAC output uses 32-bit words with backward carry propagation instead.
+18. **`parallelFor` hands out chunks of one index** and closures deep-copy captured objects; results come back through `join` or shared typed arrays.
+
+## 19-21. Found while pipelining P frames (thread-efficiency branch, worked around)
+
+19. **`Math.trunc(a / b)` on ints compiles to a float division plus a checked conversion call.** Wanted: an integer division operator or lowering `Math.trunc(int / int)` to C integer division (with the divide-by-zero check). Workaround: multiply-shift helpers for constant divisors.
+20. **Every `Atomics` operation is sequentially consistent.** A wavefront progress publish needs only a release store and the wait an acquire load; each macroblock pays a full barrier. Wanted: `Atomics.storeRelease`/`loadAcquire` (or an ordering argument).
+21. **Threads can't capture functions or class instances, and a running thread can't receive new typed arrays.** That forces per-frame spawning with a fresh worker `Encoder`, and rules out persistent workers unless reference frames live in a fixed pool of typed arrays. Wanted: a way to pass typed arrays to a running thread (e.g. a channel or a shared slot table) so a pool can live across frames.
+
+## 22-26. Found while reducing peak memory and binary size (footprint branch)
+
+Sizes are x86-64-v3 builds of the footprint branch (unchecked 460,240 bytes, checked 608,256) with Tov 548ff6b; effects of Tov changes were measured by patching the generated C through `CC`, with identical output.
+
+22. **Module integer constants are mutable globals set at start-up.** `const COEF_PER_MB = 416` becomes `static tv_int g7_COEF_PER_MB;`, assigned in `tvg_program`, so every use is a load, products and shifts by it aren't folded and `switch`es on `MB_*` or `CAT_*` can't become jump tables. Emitting the 77 literal-initialised ones as `static const tv_int g7_COEF_PER_MB = INT64_C(416);` (and folding constant expressions such as `BIN_TERM`, `BIG`, `COST_NA`): unchecked -9,568 bytes, checked -6,800, callgrind -1.5% (live busy_ui) to -7.1% (keyint 1 full_motion), -2.7% on medium full_motion. Not worked around: literals in the hot code would replace the names.
+23. **Every `try` exit repeats the release of every live local.** `encodeCommand` has 23 error exits, each releasing up to ten strings, arrays and objects (139 release calls, 68 inlined `rl_K*`), an estimated 4-5 KB of its 20.7 KB of own code. Wanted: one cleanup chain per function (labels in reverse declaration order, each exit jumping to the label for its live set) or an outlined cold cleanup.
+24. **The global symbol table stays without `-g`.** `-Wl,-x` drops local symbols, but the runtime's `tv_*` globals and their names cost 7,760 bytes; `-Wl,-s` drops them. Worked around in `bench/build_encoder.sh`.
+25. **GNU ld pads the segments** (`-z separate-code`): linking with lld saves 10,376 bytes and `-Wl,-z,noseparate-code` with ld.bfd 4,096, code unchanged. Worked around in `bench/build_encoder.sh` (lld when installed). Unwind tables (20.5 KB unchecked, 28.7 KB checked) are already gone without `-g` in Tov 3369524; the script passes the flags until that Tov is installed.
+26. **`fill` on a typed array of 16-, 32- or 64-bit elements calls `tv_ta_put_int` per element** (a switch on the element kind each time), where byte arrays get a `memset`. Wanted: a loop per element kind, `memset` for 0.
+
+## 27-32. Found while applying the 548ff6b features (tov-features branch, worked around)
+
+27. **No compile-time query of the target's vector width.** One source serves the x86-64-v3 and v4 builds, so the v4 build cannot select 512-bit kernels (a 32-lane SATD is 10-20% faster on v4 but slower on v3). Wanted: a constant such as `Target.vectorBits` (or `Target.hasAvx512`) usable in `if` so dead branches are removed per build, or per-function multiversioning.
+28. **No narrow vector stores.** `v.store` writes every lane; nothing writes 8 bytes (the counterpart of `i16x8.loadU8`), so 8-pixel chroma rows, copies and pads stay scalar. Wanted: `v.storeLow(ta, i)` / `storeN(ta, i, lanes)` and narrowing stores (`i16x8.storeU8`).
+29. **Lane lists can't be function parameters** (T0523), so helpers are duplicated per shuffle pattern. Wanted: `const` lane-list parameters (compile-time generic) or inlining-time constant propagation.
+30. **Conditional or reassigned typed-array locals still take atomic counts** (`const p = c ? this.a : this.b`), so the 16-way branch in `predictQpel` stays. Wanted: borrow when every arm is a borrowable field path.
+31. **Scalar fields are reloaded every iteration in loops that store to typed arrays** because the C is built with `-fno-strict-aliasing`; capcodec hoists `const mbw = this.mbw` by hand. Wanted: hoist loop-invariant scalar field reads when the loop only stores to typed-array elements (which can't alias object fields), or emit `restrict`.
+32. **Integer division costs:** `Math.trunc(a / b)` with a constant divisor still adds a ±2^53 range check (about 10 instructions vs 2 for multiply-shift); a variable divisor is a double division; `%` is a checked `idiv`. Wanted: plain C integer division/modulo with only the zero check when both operands are ints.
+
+## 33-40. Found while speeding up keyframes (intra-speed2 branch, worked around)
+
+Measured with callgrind on all-intra encodes (3 frames, 1080p, one thread, matched CRF), as the machine has no hardware counters; every workaround kept the output byte-identical. Tov 538446e (installed during the round) closed two earlier gaps: `Target.vectorBits` / `Target.has` answer 27, and `storeLow` / `storeU8` answer 28 (8- and 4-pixel rows stored with them instead of lane-by-lane stores: 0.04 to 0.23% fewer instructions, commit `5e6ea66`).
+
+33. **No horizontal minimum or argmin.** The I4 mode decision needs the cheapest of nine costs and the first mode reaching it; the scalar loop over the costs took 11.4M instructions on full_motion. Worked around with a swizzle/min ladder, an `eq` against the minimum, `mask()` and `Math.ctz32` (part of `7566916`, -2.1% on full_motion). Wanted: `v.minLanes()` / `maxLanes()` and an index form (`phminposuw` does both for `u16x8` in one instruction).
+34. **No shuffle by a runtime index vector** (answered by Tov 538446e's `T.shuffle(table, indices)`, with the branchless `Math.select` requested alongside; not used here yet). The I4 kernel stores every candidate prediction (five 16- or 32-byte stores per 4x4 block, 1.9M instructions on full_motion, 0.27% of the all-intra encode) so the caller can load the chosen mode's by offset; with `pshufb`/`vpermd` by a per-mode index row it would build only the chosen one from the edge vector, so 0.27% is the most it can save.
+35. **No multiple return values (tuples are "later").** Kernels with several results write them into a typed-array scratch the caller reloads: the I4 kernel's nine costs plus best mode and cost in an `Int32Array(16)`, the I8 V/H/DC costs, the chroma plane parameters in an `Int16Array(32)` and its edges and DC quads in a 176-byte block. Wanted: returning a record or tuple of ints and vectors, kept in registers when the callee is inlined.
+36. **No multiply-high for 16-bit lanes** (`pmulhw` / `pmulhuw` / `pmulhrsw`). capcodec's quantiser adds its rounding offset to the full 32-bit product (`(|c| * q + f) >> qbits`), so the 16-bit path uses `madd` against tables with the odd or even factors zeroed (two `pmaddwd` per 16 coefficients and a recombination) and the rest stays in 32-bit lanes (`vpmulld`). A multiply-high would serve x264's form (`((|c| + bias) * mf) >> 16`), which rounds differently, so it was not measured here.
+37. **`mask()` of 16-bit lanes needs a pack first.** `i16x16.eq(...).mask()` lowers to a pack and lane fix-up before `vpmovmskb`; code4's zero test and coefficient count use the byte mask of the same comparison (`u8x32.bitcast`) and halve the popcount (with the `qp % 6` change below, `77e1dc1`: -0.3 to -0.6%). Wanted: `mask()` on 16-bit lanes as `vpmovmskb` plus `pext`, or a `maskBytes()`.
+38. **`qp % 6` is a checked signed division** (gap 32's `%`), on every quantiser call: `qp - 6 * qpDiv6(qp)` with the existing multiply-shift `qpDiv6` instead (in `77e1dc1`).
+39. **Module-level vector constants are mutable globals.** `const EVEN16 = i16x16(...)` becomes `static tvv_i16x16 g18_EVEN16;` assigned by an initialiser at start-up (as gap 22 for integers), so a `select` against one is an and/andn/or with a memory operand instead of a blend with a constant, and shuffles can't fold it. Wanted: `static const` vector initialisers for literal lanes.
+40. **Profiling a split build.** Since programs over 384 KiB of C compile as parallel units, the debug information names temporary C files that are deleted after the build, so `callgrind_annotate` (and `perf annotate`) can't show source lines. `TOV_UNITS=1 tov build -g` restores it (the whole-program build runs 0.4% more instructions than the split one on full_motion). Wanted: keep the unit C files in the cache under stable names in `-g` builds.
+
+## 41-46. Found while profiling main with B-frames and the lookahead (tov-features branch, numbered 33-38 there)
+
+41. **The v4 build can't keep 512-bit types at 256 bits.** Refines 27: lane-wise `i32x16`/`u8x64` code lowers to two ymm operations on x86-64-v3 at the instruction count of two `i32x8`s (16-lane `quant4v`/`dequant4v`/`quant8v`/`dequant8v` and a 32-lane `nonzeroMask`: -0.01% to -0.12% instructions, CPU within noise), so one source can carry wide kernels for v3. On v4 the same code becomes sparse zmm instructions inside ymm code and was slower on this AVX512-FP16 Xeon (interleaved best of 7 and 9: all-intra +2.9% and +5.0%, full_motion medium +1.3% and +2.4%), so it was dropped. Four-row `u8x64` SADs (`sad16` and `sadAvg16`, one `vpsadbw` per four rows) are not neutral on v3 (full_motion medium +0.42%, live +0.12% instructions, from building the two ymm halves out of four 16-byte loads and reducing the wider accumulator) and on v4 CPU, best of 9, cost full_motion medium +4.6% (+11.6% with only `sad16` widened) for full_motion live -0.4% (-2.5%) and text_scroll live within noise, so no v4-only SAD module was kept either. Tov 9d70528 (`Target.vectorBits`) and ce80f99 (`--target-cpu x86-64-v3,x86-64-v4` in one binary) in ~/work/tov answer 27's query but are not in the installed 548ff6b compiler (`Target` is N0001 there). Wanted, next to 27's query: a build option (or per-function attribute) that lowers vectors wider than 256 bits as ymm halves while still using AVX-512VL/BW instructions on ymm (mask compares, `vpternlog`, `vpermt2*`), since clang's `-mprefer-vector-width=256` does not split explicit vector types.
+42. **No permute with run-time lane indices.** `shuffle`/`swizzle` take literal lists only, so `pshufb`/`vpermd`/`vpermb` with an index vector (and v4's `vpcompressd`) are unreachable. The CABAC significance-map writer `residualBins` (3.7% of instructions on average, 5.5% on all-intra) could compact four positions' significance and last bins through a 16-entry index table, but stays scalar at about 8 instructions per coefficient position. Wanted: `T.permute(v, idx)` (`pshufb`/`vpermd`), `u8x16.lookup(table, idx)` and `v.compress(mask)`.
+43. **No bulk append to a `u8[]` from a typed array.** Copying n bytes is n `push`es, each a `TVG_PUSH_C` with its capacity check: `escapeBytes` pushes the 16 bytes of an escape-free chunk one by one, and `endSlice` used to push every CABAC byte onto the slice header's array before escaping the whole array (removing that copy and escaping the coder's buffer in place: -0.9% to -1.3% instructions on screen content and all-intra). Wanted: `arr.pushFrom(ta, start, n)` (one reserve and a `memcpy`).
+44. **Pushes skip their capacity check only for local arrays in loops bounded by a local or a literal.** `reserve_for_pushes` does not apply to `inout` array parameters (the `out` of `escapeBytes`, whose inner loop is `j < 16`) or to loops bounded by a field or `.length`, so those pushes stay `TVG_PUSH_C`/`TVG_PUSH_U`. Wanted: reserve before such loops too, for `inout` targets and loop-invariant field or length bounds.
+45. **`subarray` allocates.** `ta.subarray(a, b)` creates a typed-array object (`tv_ta_subarray`), so `dst.set(src.subarray(s, s + 8), d)` is no option for short rows; `copyRect`'s 8- and 4-byte rows are written as all loads then all stores, which clang merges into one 8- or 4-byte load and store (the workaround for 28). Wanted: `dst.setFrom(d, src, s, n)` lowering to `memmove`, or `set(src.subarray(...))` without the allocation.
+46. **No way to ask for a branchless select.** `c ? a : b` on ints becomes a C conditional, and whether clang emits `cmov` or a branch depends on the surrounding code: five variants of the CABAC bin loop with the same selects (`range = isLps ? rl : rm`, the renormalisation shift) compiled to between 0 and 2 `cmov`s and 22 to 24 conditional jumps. Wanted: `Math.select(c, a, b)` emitted with `__builtin_unpredictable` (or as mask arithmetic).
+
+## 47-50. Found with Tov 786b6c7 and in the CABAC bin loop (tov-features and tov-features-next branches, numbered 39-42 there)
+
+Instruction counts are callgrind totals of one-thread encodes (full_motion medium 30 frames and live 30, busy_ui and code_editor medium 90, text_scroll live 90, all-intra medium 10); `-g` and stripped builds of one source differ by under 110 instructions.
+
+47. **Field reads outside loops still compile differently from a hand-hoisted local, and nothing pins inlining.** 786b6c7 reads a number field once before a loop when nothing the loop runs can assign it, and removing the encoder's hand hoists, mostly before such loops (`const mbw = this.mbw`), was neutral (-0.05% to +0.12%). The lookahead reads `this.w` and `this.h` in straight-line code instead (`intraOf`, `keepOf`, and `candCost`, which `keepOf` calls up to 11 times per macroblock), where the rule does not apply; removing those hoists too cost full_motion +2.68% (medium) and +3.03% (live) instructions, other content +0.02% to +0.16%, all of it in `Lookahead_push` (+112.6M). `Lookahead_push` inlines `keepOf`, its `candCost` calls and `rowsSad`'s 8-row SAD loop; with the field reads clang made 17 copies of that loop instead of 13, and in four of them loop strength reduction kept sixteen row pointers and spilled them (73-75 instructions with 17-25 stack accesses per 8 rows, instead of 42 with none and the stride in a register). Workaround: the hoists stay in the lookahead. Wanted: the same single read for a field in straight-line code (until something that can assign it runs), so a hand-written local and the field read give the same C, and `@noinline`/`@inline` on functions and methods, so a small kernel such as `rowsSad` is compiled once instead of once per inlined call site.
+48. **`Math.idiv` by a variable divisor perturbs the same function.** At the constant divisors (`qp / 6`, the quantiser rounding offsets) `Math.idiv` saves the range check (text_scroll live -0.12%). At the 15 variable-divisor sites (and one by 48) it cost full_motion +2.03% (medium) and +2.23% (live) instructions, other content +0.01% to +0.12%. The lookahead's divisions per macroblock (`mb / this.mbw`, the mean of a short bottom row, `keepOf`'s keep factor) take fewer instructions themselves (the keep factor 3.0M instead of 4.8M), but `Lookahead_push` grew by 85.6M through 39's mechanism (17 SAD loops instead of 13, four of them spilling). Workaround: variable divisors stay `Math.trunc(a / b)`, which 786b6c7 already lowers to the `f64` division because a 64-bit `idiv` has under half `divsd`'s throughput. Wanted: `Math.idiv` by a non-constant divisor lowered the same way when both operands are within ±2^53, so choosing the exact operator costs nothing.
+49. **No branch-likelihood hint, so block layout follows how a test is phrased.** In the CABAC bin loop, `if (b >= 0) { decision } else if ...` made clang end the decision block with a `jmp` back to the shared word-flush test; matching plain decisions by `b >= 0 && b < SKIP_TERM`, which clang compiles to one unsigned compare, made the decision the loop's fall-through path, one instruction fewer per decision (all-intra -0.77%, where the new skip-run code never runs). Wanted: `if (Math.likely(c))` (or an `expect` form) emitted as `__builtin_expect`, so the hot path's layout does not depend on the form of its condition. Related to 46.
+50. **Scalar shift semantics are undocumented and differ from JavaScript.** `<<`, `>>` and `>>>` on `int` shift 64 bits with the count taken modulo 64 (`1 << 32` is 4294967296, `1 << 64` is 1, and `1 << 41` is 2^41 where JavaScript gives 512); the spec states the modulo rule only for vector lanes. The CABAC table lookup relies on it (`e >> (b & 63)` picks a bin's next state out of one 64-bit table entry; the generated C masks the count again and clang folds both into one `sarx`). Wanted: the rule in the spec's operator section, next to the vector one.
+
+## 51-52. Found in the CABAC range update (tov-features branch, numbered 43-44 there)
+
+Same measurement setup as 47-50; the compiler is the installed Tov with clang 18.1.3.
+
+51. **A change inside one class moves inlining in unrelated encoder functions.** Two versions of the CABAC range update differ only inside `Cabac`: one keeps the LPS renormalisation shifts in spare bits of the existing table, the other in a second `Int64Array` field passed to `encodeBins` as one more parameter. Once closure and temporary names are renumbered, their generated C differs in 48 lines, all of them `Cabac` code: its struct, constructor, drop and print functions, `run`, `encodeBins`, and the field initialisation where the `Encoder` constructor allocates its `Cabac`. Clang nevertheless inlined differently: `diffFrame` (468 instructions) was inlined and `mbDiffers` (733) emitted out of line instead, `ensureTiles` went from 150 to 174 instructions and `computeMvpL` from 211 to 157. Relative to the parent commit, the first version changed full_motion medium by +0.84% instructions, all of it `Cabac_run` (+35.2M), and the second by -0.98% (live +0.99% and -0.98%). Between the two, `Cabac_run` differed by the expected -15.4M, while `ensureTiles` (-23.3M), `computeMvpL` (-4.3M), `codeMbAt` (-3.9M) and `entropyRow` (-3.0M) account for most of the remaining -61M. How the change reaches those functions (presumably through the inliner's cost budgets) was not traced. Consequence: a single change's instruction delta on full_motion carries perturbations of about ±1% that it did not cause, so steps are attributed per function from `-g` profiles. Wanted: as 47, `@noinline`/`@inline`, so the encoder's inlining does not move with unrelated edits.
+52. **No branchless select, so an unpredictable select can become a branch.** `range = isLps ? lps << ls : mps << ms` compiles to two `cmov`s. The equivalent `range = (isLps ? lps : mps) << rs`, with `rs = isLps ? ls : ms` and `ls` read from a table, compiles to `test r8d, 0x100; je`, which branches on whether the bin is the LPS (close to random in CABAC) and executes the `ls` load only on that path. This is presumably LLVM's x86 cmov-conversion pass, which turns a `cmov` fed by a load into a branch. Workaround: the first form. Wanted: `Math.select(c, a, b)` that stays branchless, or an unpredictable hint lowered to `__builtin_unpredictable`, so latency-bound loops do not depend on how a select is written. Related to 49.
+
+## 53. Found while shortening the CABAC MPS renormalisation test (tov-features branch, numbered 45 there)
+
+Same setup as 51-52.
+
+53. **No way to keep an expression's association, so a constant can be moved onto the critical path.** In `encodeBins`, `ms = (range - 256 - lps) >>> 63`, next to `mps = range - lps`, is meant to subtract `lps` from `range - 256`, which is ready before the table lookup gives `lps`. Clang instead computes `mps` and derives `ms` from it (`sub r8, rbx; lea rdx, [r8-0x100]; shr rdx, 0x3f`), presumably to share the subtraction. That makes the MPS test three operations after `lps` instead of two, and puts one more cycle on the range chain that limits the bin loop. Reading the `-256` from memory once before the loop keeps the intended order (`add rcx, r12; sub rcx, r9; shr rcx, 0x3f`) at one more instruction per decision (all-intra 2,487,389,509 instead of 2,466,833,084 instructions). Yet that version is faster: interleaved 1-thread medians over 9 reps are busy_ui all-intra 2.224 s against 2.257 s, code_editor all-intra 2.088 s against 2.170 s and all-intra at QP 26 0.714 s against 0.728 s (A/A 1.006, 1.006, 0.991). Neither beat the committed `lps > range - 256 ? 1 : 0` (`cmp` and `setg`), so neither was kept. Wanted: an opaque-value hint (as Rust's `core::hint::black_box`, an empty `asm("" : "+r"(x))` in C) so a latency-bound loop can fix where a constant is applied without loading it from memory.
diff --git a/capcodec/bench/bench.py b/capcodec/bench/bench.py
new file mode 100644
index 000000000..7c828b169
--- /dev/null
+++ b/capcodec/bench/bench.py
@@ -0,0 +1,121 @@
+#!/usr/bin/env python3
+import argparse
+import dataclasses
+import json
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from harness import report # noqa: E402
+from harness.common import BENCH, MANIFEST, OUT_DIR, ROOT, Cache, ffmpeg_version, git_commit, log, ncores # noqa: E402
+from harness.runner import GATE_ENCODER, REFERENCE, TIERS, Bench, gate, machine_id, summarize # noqa: E402
+
+BEST = BENCH / "best.json"
+HISTORY = BENCH / "history.jsonl"
+
+
+def committed_best() -> dict | None:
+ r = subprocess.run(["git", "-C", str(ROOT), "show", "HEAD:bench/best.json"], capture_output=True, text=True)
+ if r.returncode == 0 and r.stdout.strip():
+ return json.loads(r.stdout)
+ if BEST.exists():
+ return json.loads(BEST.read_text())
+ return None
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description="capcodec benchmark harness")
+ ap.add_argument("tier", choices=sorted(TIERS))
+ ap.add_argument("--encoders", help="comma-separated adapter names (prefix* allowed)")
+ ap.add_argument("--clips", help="comma-separated clip names")
+ ap.add_argument("--jobs", type=int, default=ncores())
+ ap.add_argument("--no-cache", action="store_true")
+ ap.add_argument("--manifest", type=Path, default=MANIFEST)
+ ap.add_argument("--out", type=Path)
+ ap.add_argument("--update-best", action="store_true", help="write bench/best.json when the gate encoder improved")
+ ap.add_argument("--accept", action="store_true", help="write bench/best.json from this run unconditionally")
+ ap.add_argument("--no-history", action="store_true")
+ ap.add_argument("--list", action="store_true", help="list adapters and availability")
+ ap.add_argument("--quality-only", action="store_true",
+ help="skip speed, matched-speed and proportionality runs (speedcmp.py measures speed)")
+ args = ap.parse_args()
+
+ tier = TIERS[args.tier]
+ if args.quality_only:
+ tier = dataclasses.replace(tier, speed=False, matched_key=None, proportionality=False)
+ out_dir = args.out or (OUT_DIR / tier.name)
+ out_dir.mkdir(parents=True, exist_ok=True)
+ encoders = args.encoders.split(",") if args.encoders else None
+ clips = args.clips.split(",") if args.clips else None
+ bench = Bench(tier, Cache(enabled=not args.no_cache), out_dir, encoders, clips, args.jobs, args.manifest)
+ if args.list:
+ for a in bench.adapters:
+ print(f"available {a.name:34s} {a.description}")
+ for n, why in sorted(bench.unavailable.items()):
+ print(f"unavailable {n:34s} {why}")
+ return 0
+ if not bench.clips:
+ log(f"no clips available (manifest {args.manifest}); generate the corpus first")
+ return 2
+ t0 = time.time()
+ rows = bench.run()
+ refs = [REFERENCE] + sorted({a.name for a in bench.adapters if getattr(a, "production", False)})
+ refs = [r for r in refs if any(x["encoder"] == r for x in rows)]
+ summ = summarize(rows, tier, refs)
+ report.write_csv(rows, out_dir / "results.csv")
+ (out_dir / "summary.json").write_text(json.dumps(summ, indent=1, sort_keys=True, default=str))
+ notes = []
+ if any(a.family == "browser" for a in bench.adapters):
+ notes.append("Browser encoders run in headless Google Chrome on Linux, so MediaRecorder and WebCodecs use "
+ "Chrome's software H.264 path (OpenH264), not a hardware encoder.")
+ if bench.unavailable:
+ notes.append("Not available on this machine: " + ", ".join(f"{k} ({v})" for k, v in sorted(bench.unavailable.items())))
+ meta = {"tier": tier.name, "commit": git_commit(), "machine": machine_id(), "ffmpeg": ffmpeg_version(),
+ "clips": len(bench.clips), "elapsed_s": f"{time.time() - t0:.0f}"}
+ ok, msgs = (True, [])
+ best = committed_best()
+ if tier.gate:
+ ok, msgs = gate(summ["summary"], best)
+ report.write_html(out_dir / "report.html", tier.name, rows, summ, refs, meta, out_dir / "crops", notes + msgs)
+ entry = {"time": time.strftime("%Y-%m-%dT%H:%M:%S"), "tier": tier.name, "commit": git_commit(),
+ "machine": machine_id(), "elapsed_s": round(time.time() - t0, 1), "clips": [c.name for c in bench.clips],
+ "summary": summ["summary"], "gate": {"ok": ok, "messages": msgs} if tier.gate else None}
+ if not args.no_history:
+ report.append_history(HISTORY, entry)
+ s = summ["summary"].get(GATE_ENCODER, {})
+ cand = {"bd_psnr_yuv": s.get(f"bd_psnr_yuv_vs_{REFERENCE}"), "cpu_fps": s.get("cpu_fps_median"),
+ "commit": git_commit(), "tier": tier.name, "clips": [c.name for c in bench.clips]}
+ if tier.gate and cand["bd_psnr_yuv"] is not None:
+ better = best is None or (
+ (best.get("bd_psnr_yuv") is None or cand["bd_psnr_yuv"] <= best["bd_psnr_yuv"])
+ and (not best.get("cpu_fps") or (cand["cpu_fps"] or 0) >= best["cpu_fps"] * 0.97))
+ if args.accept or (args.update_best and ok and better):
+ BEST.write_text(json.dumps(cand, indent=1, sort_keys=True) + "\n")
+ msgs.append(f"wrote {BEST}")
+ for e, s in sorted(summ["summary"].items()):
+ bits = [f"{k}={v:+.2f}%" if k.startswith("bd_") and not k.endswith("_n") else None
+ for k, v in s.items() if v is not None]
+ bits = [b for b in bits if b]
+ fps = s.get("cpu_fps_median")
+ sp = s.get("speed_wall_fps_median")
+ print(f"{e:34s} {' '.join(bits)} cpu-fps={'' if fps is None else f'{fps:.1f}'}"
+ f"{'' if sp is None else f' wall-fps={sp:.1f}'} decode_fail={s.get('decode_failures')} "
+ f"errors={s.get('errors')}")
+ for surf, t in sorted((s.get("vs_cap_targets") or {}).items()):
+ deltas = [f"{label}={t[k]:+.2f}" for label, k in (("dVMAF", "d_vmaf_mean"), ("dPSNR", "d_psnr_yuv_mean"))
+ if t.get(k) is not None]
+ if t.get("cpu_speedup_geomean"):
+ deltas.append(f"cpu x{t['cpu_speedup_geomean']:.2f}")
+ print(f"{'':34s} vs {surf} at Cap bpp targets ({t['n']}): |err| {t['our_abs_err_mean'] * 100:.1f}% "
+ f"(theirs {t['their_abs_err_mean'] * 100:.1f}%) {' '.join(deltas)}")
+ for m in msgs:
+ print(m)
+ print(f"report: {out_dir / 'report.html'}")
+ return 0 if ok else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/capcodec/bench/best.json b/capcodec/bench/best.json
new file mode 100644
index 000000000..1e9504012
--- /dev/null
+++ b/capcodec/bench/best.json
@@ -0,0 +1,11 @@
+{
+ "bd_psnr_yuv": 1.5927990279928197,
+ "clips": [
+ "code_editor",
+ "text_scroll",
+ "slides"
+ ],
+ "commit": "1c82bfaeb12e-dirty",
+ "cpu_fps": 291.64864116037273,
+ "tier": "smoke"
+}
diff --git a/capcodec/bench/build_encoder.sh b/capcodec/bench/build_encoder.sh
new file mode 100755
index 000000000..8315ca929
--- /dev/null
+++ b/capcodec/bench/build_encoder.sh
@@ -0,0 +1,19 @@
+#!/usr/bin/env bash
+set -euo pipefail
+cd "$(dirname "$0")/.."
+mkdir -p build
+TOV="${TOV:-tov}"
+CPU="${CAPCODEC_TARGET_CPU:-x86-64-v3}"
+if [ "$(uname -s)" = Linux ] && [[ " $* " != *" -g "* ]]; then
+ FLAGS="-fno-asynchronous-unwind-tables -fno-unwind-tables -Wl,-s"
+ if command -v ld.lld >/dev/null; then
+ FLAGS="$FLAGS -fuse-ld=lld"
+ fi
+ export TOV_CFLAGS="$FLAGS ${TOV_CFLAGS:-}"
+fi
+"$TOV" build cli/main.tov -o build/capcodec --target-cpu "$CPU" "$@"
+"$TOV" build cli/main.tov -o build/capcodec-unchecked --unchecked --target-cpu "$CPU" "$@"
+"$TOV" build cli/main.tov -o build/capcodec-unchecked-baseline --unchecked "$@"
+if [ "$(uname -m)" = x86_64 ]; then
+ "$TOV" build cli/main.tov -o build/capcodec-unchecked-v4 --unchecked --target-cpu x86-64-v4 "$@"
+fi
diff --git a/capcodec/bench/corpus/README.md b/capcodec/bench/corpus/README.md
new file mode 100644
index 000000000..bac8e8530
--- /dev/null
+++ b/capcodec/bench/corpus/README.md
@@ -0,0 +1,352 @@
+# Lossless screen-recording corpus
+
+Synthetic but app-like screen recordings for benchmarking the capcodec
+screen-content H.264 encoder. Every clip is a real-time `x11grab` capture of
+Chrome on a private Xvfb display, driven by scripted human-like input. The
+captures are stored losslessly next to per-frame side info: dirty rects,
+cursor position and scroll vectors. One clip, `full_motion`, is the worst
+case for a screen encoder: a natural video (Big Buck Bunny) playing full
+screen.
+
+Scripts, pages and the manifest live here (`bench/corpus/`). Captures and side
+info go to `$CAPCODEC_CORPUS`, which defaults to `/home/ubuntu/work/corpus` and is
+never committed.
+
+## Regenerating
+
+```sh
+cd bench/corpus
+python3 generate.py --list # clip table
+python3 generate.py --clip slides # one clip (repeatable)
+python3 generate.py --all # everything (~20 min)
+python3 generate.py --all --missing # only clips without outputs
+python3 generate.py --clip idle --sideinfo-only # recompute side info, previews, manifest entry
+python3 generate.py --verify-lossless # codec round-trip check
+```
+
+Run long jobs inside tmux (`tmux new-session -d -s corpus-gen ...`). Each run
+is idempotent: the clip's work dir (`$CAPCODEC_CORPUS/.work/<name>`, which
+holds the raw capture and the Chrome profile) is wiped, every output is
+overwritten, and the clip's manifest entry is replaced. The work dir is
+deleted again once the outputs are written. Clips are written to
+`manifest.json` in `CLIPS` order.
+
+Environment:
+
+| variable | default |
+|---|---|
+| `CAPCODEC_CORPUS` | `/home/ubuntu/work/corpus` |
+| `CAPCODEC_CACHE` | `/home/ubuntu/work/cache/capcodec-corpus` (downloaded source video, segment, match features; outside git) |
+| `CAPCODEC_FFMPEG` | `/home/ubuntu/tools/bin/ffmpeg` (8.1) |
+| `CAPCODEC_FFPROBE` | `ffprobe` next to `CAPCODEC_FFMPEG` |
+
+Requirements: Xvfb, xdotool, python3 with `python3-xlib`, `numpy` and
+Playwright, and Google Chrome (`channel="chrome"`, tested with 148). The pages
+use locally installed fonts (Noto Sans, Liberation, Inter, JetBrains Mono,
+Bitstream Charter). `sudo -n renice` is used when available. Displays: `:99` at
+1920x1080x24 is reused if it is already running (otherwise it is started), and
+`:98` at 3840x2160x24 is started and stopped for `code_4k`. `:1` is refused.
+Pages are `file://` URLs and all data (code, article text, board data) is
+embedded in `pages/data/*.js`. The only network access is the one-time
+download of the `full_motion` source video into `$CAPCODEC_CACHE`, which is
+verified by sha256. Captures never touch the network.
+
+## Clips
+
+| name | size @ fps | s | page | content |
+|---|---|---|---|---|
+| slow_typing | 1920x1080@30 | 40 | `docs.html` | Docs-like editor, 15px text, human typing with pauses and BackSpace fixes |
+| code_editor | 1920x1080@30 | 40 | `code.html` | VS Code Light+, 13px JetBrains Mono, typing with auto-indent, wheel/PageDown/caret |
+| text_scroll | 1920x1080@30 | 40 | `article.html` | Wikipedia-like article: notches, flicks, eased smooth scroll, selection, hovers |
+| slides | 1920x1080@30 | 40 | `slides.html` | deck advancing every ~3 s: cuts, fades, push/cover slide-ins, builds |
+| busy_ui | 1920x1080@30 | 40 | `board.html` | dense issue board, constant curved pointer motion, menus, drags, scroll |
+| dashboard | 1920x1080@30 | 40 | `dashboard.html` | 11-12px tables, KPI tiles, 1 s updates, animated charts and sparklines |
+| dark_mode | 1920x1080@30 | 40 | `dark.html` | VS Code Dark+ and a terminal streaming logs, occasional typing |
+| idle | 1920x1080@30 | 60 | `idle.html` | static desktop/PDF viewer, ticking clock, 3 toasts, 4 pointer moves |
+| webcam_overlay | 1920x1080@30 | 40 | `slides.html?webcam=1` | slides with a 320px circular canvas webcam (gradient, figure, noise), dragged 4 times |
+| busy_ui_60fps | 1920x1080@60 | 20 | `board.html` | short busy_ui variant at 60 fps |
+| code_4k | 3840x2160@30 | 20 | `code.html` | DSF 2 on a 4K Xvfb, code typing and scrolling |
+| full_motion | 1920x1080@30 | 30 | `video.html` | Big Buck Bunny 27.47-57.43 s full screen in a `<video>`: camera push-in over grass and foliage, dark burrow close-up, bunny in the meadow; no input, cursor hidden |
+
+Scenario timelines are in `scenarios.py` (`SCENARIOS`), and clip parameters
+(page, seed, start pointer, settle time, encoder threads) are in `generate.py`
+(`CLIPS`). Page animations use seeded PRNGs (mulberry32) and virtual clocks.
+Scenarios use seeded `random.Random`. Re-captures therefore follow the same
+script, but they are not bit-identical because real-time scheduling varies by a
+few ms.
+
+## Outputs per clip (`$CAPCODEC_CORPUS`)
+
+| file | content |
+|---|---|
+| `<name>.mkv` | lossless H.264 (libx264rgb `-qp 0`, High 4:4:4 Predictive, GBR planes), CFR pts `n/fps` |
+| `<name>.sideinfo.jsonl` | one line per frame (format below) |
+| `<name>.events.jsonl` | merged timeline sorted by wallclock: `scroll` (page scroll reports), `page` (app events such as slide, toast, menu_open, drop), `input` (DOM key/mouse/wheel events), `action` (injected input), `pointer` (deduplicated pointer samples), `capture` (first/last frame) |
+| `<name>.pointer.jsonl` | raw 240 Hz pointer samples `{t, x, y, rtt}` |
+| `<name>.capture.json` | per-frame wallclock, interval stats, ffmpeg command, grab latency, scenario start/end offsets, page info |
+| `<name>.capture.log` | full ffmpeg log |
+| `previews/<name>_fNNNNN.png`, `previews/<name>_sheet.png` | frames 0, n/3, 2n/3, n-1 and the frame with the largest dirty area, plus a 2x2 sheet |
+| `full_motion.playback.json` | playback check: source frame shown by every captured frame, match distances, Chrome presentation stats, dirty fractions vs the source |
+
+`manifest.json` (here) has one entry per clip with `name, file, width, height,
+fps, frames, duration_s, sha256, tags, description, text_regions, sideinfo,
+capture{codec, dropped_frames, duplicated_frames, method, ...},
+scroll_validation, generator{script, args}`. It also includes
+`avg_dirty_fraction`, `cursor_check` and file pointers, plus a top-level
+`lossless_check`. `text_regions` holds 2-4 screen-pixel rects with dense text,
+taken from each page's `capTextRegions()` at capture start. It is empty for
+`full_motion`, which has no text. `full_motion` also has `source_video`
+(title, URL, sha256 hashes, segment, source range, licence and attribution)
+and `playback_check` (the summary of `full_motion.playback.json`). Its
+`capture` block adds `phase_lock` and `trim`.
+
+Side info line:
+
+```json
+{"frame": 12, "t_ms": 400.1, "dirty": [[x,y,w,h], ...], "cursor": [x,y] | null,
+ "scroll": [{"rect": [x,y,w,h], "dx": 0, "dy": -57, "id": "editor", "valid": true,
+ "align": "latency", "match": 0.9993}]}
+```
+
+- `t_ms` is the capture wallclock relative to frame 0.
+- `dirty` is the exact diff against the previous decoded frame. Frame 0 is the
+ whole frame. Changed pixels mark 16x16 tiles. Each tile row is merged into
+ horizontal runs, then runs are merged vertically when consecutive rows have
+ the same x-extent. Rects are 16-aligned and clipped to the frame (the last
+ 1080p tile row is 8 px tall).
+- `scroll` has one entry per tracked scroll container whose offset changed.
+ `(dx, dy)` is the screen-pixel motion of the content inside `rect`, and `dy`
+ is negative when content moves up. `valid` records whether the pixels confirm
+ the vector, and is null when the jump exceeds the container (for example
+ Ctrl+Home), so nothing overlaps.
+
+`sideinfo.py` is reusable. Use `compute()` as a module, or the CLI:
+`python3 sideinfo.py --video X.mkv --capture X.capture.json --events
+X.events.jsonl --pointer X.pointer.jsonl --out X.sideinfo.jsonl`. It streams
+`bgr0` frames from an ffmpeg pipe into numpy and makes two decode passes.
+
+## How a capture works
+
+1. Calibrate. Run a 120-frame `x11grab -framerate 1000` against the null muxer.
+ The median frame gap gives the per-grab latency (0.5-1 ms at 1080p, ~2 ms at
+ 4K), and the first frame's wallclock gives ffmpeg's startup delay.
+2. Launch Chrome with `launch_persistent_context(channel="chrome",
+ headless=False, no_viewport=True, ignore_default_args=["--enable-automation"])`
+ and `--kiosk --force-device-scale-factor=N --force-color-profile=srgb`, with
+ background networking off and no infobars. There is no window manager, so
+ `xdotool windowmove/windowsize` pins the window to exactly WxH, and the
+ generator checks `[innerWidth, innerHeight, devicePixelRatio]`.
+3. Get keyboard focus. Without a WM, Chrome reports `document.hasFocus()` but
+ drops X key events until the first click. The generator calls
+ `page.bring_to_front()`, then presses Shift through xdotool and waits for the
+ page to see the keydown. If the page never sees it, the capture aborts.
+4. Wait for `capReady` (fonts loaded, two rAFs). Then warp the pointer, run
+ the clip's `prepare_js` and settle for 1.2-2.5 s.
+5. Start `pointer_sampler.py` (240 Hz), then ffmpeg:
+
+ ```
+ ffmpeg -f x11grab -framerate FPS -video_size WxH -draw_mouse 1 -use_wallclock_as_timestamps 1 -i :99
+ -copyts -fps_mode passthrough -enc_time_base:v demux -frames:v N
+ -c:v libx264rgb -preset ultrafast -qp 0 -g 5*FPS -threads T
+ -stats_enc_pre frames.txt -stats_enc_pre_fmt "{n} {tb} {pts}" -progress progress.txt raw.mkv
+ ```
+
+ ffmpeg and Xvfb are reniced to -10. The scenario thread starts at the
+ expected first-frame instant. Pointer motion goes through XTest
+ (`fake_input`): cubic Bezier paths with minimum-jerk timing at 120 Hz,
+ Fitts-like durations and random curvature. The wheel uses buttons 4-7 (one
+ notch is deltaY 120, smooth-scrolled by Chrome). Typing uses `xdotool type
+ --delay N` with N drawn per word, plus punctuation and hesitation pauses.
+ Keys use `xdotool key`. The main thread only pumps Playwright and answers
+ the scenario's `page.evaluate` requests.
+6. End cleanly. Scenarios stop 1.4 s before the clip ends: a step that would
+ overrun raises `ScenarioOutOfTime`, logged as `scenario.truncated`, and all
+ buttons and keys are released. ffmpeg stops by itself after exactly N frames.
+7. Finalize. Check that the encoder saw N frames with strictly increasing
+ wallclock. Then remux with `-c copy -bsf:v setts=ts=N/(FPS*TB)` to clean CFR
+ pts, verify the packet count and size with ffprobe, and write the logs,
+ events, side info, previews and manifest entry.
+
+## Natural video (`full_motion`)
+
+1. Source. `prepare_video()` downloads
+ `bbb_sunflower_1080p_30fps_normal.mp4.zip` from download.blender.org into
+ `$CAPCODEC_CACHE` once and checks the sha256 of the zip and the mp4. It then
+ stream-copies 1325 frames from the keyframe at 16.3 s (`-c copy -an`, no
+ re-encode) and checks every decoded segment frame against the matching
+ source frame with framemd5. The clip starts at the shot cut at 27.467 s
+ (segment frame 335). The 11 s before it leave room for phase locking.
+2. Playback. `pages/video.html` holds `<video autoplay muted loop playsinline>`
+ with no controls, sized 100vw x 100vh with `object-fit: cover`, so the
+ 1920x1080 source maps 1:1 onto the screen. The page sets `cursor: none`,
+ the pointer is parked at (1919, 1079) and ffmpeg runs with `-draw_mouse 0`,
+ so `cursor` is null in the side info. Chrome decodes in software. A
+ `requestVideoFrameCallback` loop logs every presented frame as a
+ `video_frame` page event (`media_time`, `presented_frames`,
+ `expected_display`, `presentation`). `capReady` is set after 45 presented
+ frames.
+3. Phase lock. x11grab grabs on a fixed grid: its start time plus k/30 s. The
+ start time is random to tens of ms, and pausing ffmpeg does not move the
+ grid. A grid that sits next to Chrome's frame swaps catches single frames
+ early or late, which shows up as a repeat followed by a skip.
+ - Measurements (1000 fps probes): Chrome's presentation phase (expected
+ display time E) drifts only ~1.6 ms over 40 s, and the framebuffer
+ switches to the next frame 3.5-14 ms after E. Content matching shows
+ that frame k is already on screen ~26 ms before E(k).
+ - Locking: the generator launches the real capture command and reads the
+ first 16 frames' wallclock pts from `-stats_enc_pre`. It accepts when
+ the grid phase is E + 25 ± 4.5 ms, the middle of the safe window.
+ Otherwise it kills ffmpeg by PID and relaunches.
+ - If the cut gets closer than 2.5 s, playback restarts from 0. The
+ attempts are recorded in `capture.json` under `phase_lock`.
+ - Every thread of the Chrome instance is reniced to -10 as well, like
+ ffmpeg and Xvfb. `renice -p` only affects one thread on Linux, so the
+ generator walks `/proc/<pid>/task` for each Chrome process.
+4. Trim. ffmpeg records the lead plus 900 + 45 frames. `trim_to_cut()` maps
+ the raw frames around the predicted cut onto source frames (step 5) and
+ keeps the first raw frame that shows the cut frame. Raw frames
+ [first, first + 900) are decoded and re-encoded with libx264rgb `-qp 0`, and
+ verified against the raw capture with framemd5 (bgr0). The steps from step 7
+ of the capture flow follow.
+5. Playback check (`playback.py`).
+ - Matching: captured and source frames are area-downscaled to 480x270
+ luma, high-passed (minus a 9x9 box blur), 2x2-averaged and normalised.
+ Each captured frame is matched to a source frame by
+ 1 - normalised cross-correlation along a monotonic Viterbi path (offset
+ band ±6, penalty 0.004 per offset change). This makes it insensitive to
+ Chrome's YUV->RGB conversion. On a synthetic test with a deliberately
+ wrong BT.601 conversion and 6 injected repeats and 6 skips per run,
+ 2699/2700 frames were mapped correctly.
+ - `playback_check` reports the source frame steps, repeats and skips,
+ match distances and Chrome's presentation stats: media-time steps,
+ presented-frame steps and display intervals in vsyncs. It also reports
+ `getVideoPlaybackQuality()` dropped frames (sampled every 5 s) and the
+ per-frame dirty distribution.
+ - It compares the captured dirty fraction with the source's own fraction
+ of 16x16 tiles whose Y, U or V samples changed (`dirty_vs_source`).
+6. Recapture. A run is clean when the check shows source frames 335..1234
+ in steps of exactly 1, with no repeats, skips or dropped grabs. Otherwise
+ the generator captures again, up to 3 runs in total
+ (`SOURCE_CAPTURE_RUNS`). The rejected runs are summarised in
+ `capture.json` under `capture_runs` and in the manifest's `capture.runs`.
+ If the last run is still not clean, the clip is reported as failed.
+
+## Timing method
+
+All clocks are CLOCK_REALTIME: Python's `time.time()`, Chrome's `Date.now()`
+and `performance.timeOrigin + performance.now()` (records carry both `t` in ms
+and `tp` in sub-ms), and ffmpeg's `av_gettime()` behind
+`-use_wallclock_as_timestamps`.
+
+- Frame time comes from `-stats_enc_pre`, which gives each frame's wallclock
+ pts in µs. `-enc_time_base:v demux` matters here: with the default 1/fps
+ encoder time base, wallclock pts are rounded onto the frame grid, and the mkv
+ itself only stores ms.
+- Frame accounting:
+ - `dropped_frames` counts missed capture slots: intervals over 1.5x nominal,
+ each counted as `round(interval/nominal) - 1`.
+ - `duplicated_frames` counts catch-up grabs: intervals under 0.5x nominal.
+ - ffmpeg's own `dup_frames`/`drop_frames` from `-progress` are recorded too.
+ They are 0 by construction with `-fps_mode passthrough`, which is why the
+ interval-based numbers are the meaningful ones.
+- Cursor: x11grab paints the pointer after grabbing the image, right before
+ the wallclock pts is taken. `cursor` is the latest 240 Hz sample at or before
+ `T_frame + C`. C is fitted per clip in [-12, +12] ms to maximise the fraction
+ of moved frames whose hotspot tile is dirty at both the old and new position
+ (it lands at 0 to +4 ms). The manifest `cursor_check` reports the
+ chosen offset, the fraction at that offset and at 0, and how many frames
+ moved.
+- Scroll: pages report `scrollLeft/scrollTop` and the container rect on every
+ scroll event and every rAF through an `expose_binding`. Offsets are converted
+ to screen px (x DSF).
+ - Pass 1 fits one global report-to-screen latency L in -70..70 ms. For each
+ L, every resulting per-frame vector is checked against the pixels, and the
+ plateau centre of (valid - invalid) wins.
+ - Pass 2 walks the frames in order. For each container it uses the offset
+ reported at `T - L` if the pixels confirm it (`align: "latency"`). If the
+ container did not change on screen, it holds the previous offset.
+ Otherwise it picks whichever other offset reported within ±1 frame the
+ pixels confirm (`"realigned"`). If nothing fits, the latency value is kept
+ with `valid: false`.
+ - A vector is confirmed when the shifted previous frame matches at least 90%
+ of the overlap and removes at least 75% of the mismatches of the unshifted
+ comparison, or matches at least 99.95% of it. Cursor boxes (±34 px, ±60 at
+ DSF 2) are masked out. The residual criterion exists because ±1 px
+ shifts of mostly white pages still match about 95%.
+ - `scroll_validation` reports the fraction over verifiable frames, the
+ latency-only fraction, the align counts and L.
+
+## Lossless check
+
+`--verify-lossless` feeds one x11grab input, captured while the dashboard
+animates at 1080p and while the 4K editor scrolls, into two outputs in the same
+ffmpeg process: rawvideo NUT and libx264rgb `-qp 0`. It then compares the
+`framemd5` of both decoded to bgr0, frame by frame. Results go to
+`lossless_check.json` and to the manifest's `lossless_check`.
+
+## Decisions
+
+- libx264rgb `-preset ultrafast -qp 0` instead of FFV1. It is lossless for
+ bgr0 sources (verified above) and keeps up in real time at 4K@30 and
+ 1080p@60 with 2-3 threads. It is also H.264, the format being benchmarked.
+- No window manager: there are no decorations or focus quirks beyond the one
+ handled by the keyboard-focus probe. The pointer is the default X/Chrome
+ cursor as drawn by `-draw_mouse 1`.
+- Text uses the VM's fontconfig defaults: RGB subpixel antialiasing with slight
+ hinting, i.e. ClearType-like colour fringes, as on Windows or Linux
+ desktops. macOS-style grayscale AA is not represented.
+- The 4K clip uses device scale factor 2, so it has a HiDPI layout with 26px
+ code rather than four times the content.
+- `full_motion` plays the original stream without a pre-transcode. Chrome
+ software-decodes 1080p30 H.264 High (~3 Mbit/s) under Xvfb with 0 dropped
+ frames, and every media-time step is exactly one frame, both in a 40 s test
+ and during the capture.
+- The `full_motion` window was chosen by computing the per-frame changed-tile
+ fraction for the whole film up to the credits (~512 s). 27.47-57.43 s is the
+ best 30 s window by mean (0.949) and by 1st percentile (0.66). Every other
+ window has near-static frames, because Big Buck Bunny has many locked-off
+ shots whose static backgrounds H.264 reproduces bit-identically.
+ - The first 12 s (a camera push-in over grass and foliage) average 0.996,
+ and every frame there is >= 0.969 except frame 1. Source frame 336
+ nearly repeats 335 right after the cut: only 8.6% of tiles change.
+ - The dark burrow close-up and the meadow shot keep static regions
+ (0.92 average, minimum 0.40), so the clip averages 0.949 rather than
+ 1.0. Per frame, the capture matches the source's own changed-tile
+ fraction within 0.0011.
+- Content sources: `difflib.py` comes from CPython (PSF License), `inflate.c`
+ from zlib (zlib License), and the article text is adapted from the English
+ Wikipedia "Typewriter" article (CC BY-SA 4.0). The docs, slides, board,
+ dashboard and PDF content are original.
+- `full_motion` contains a 30 s excerpt (27.47-57.43 s) of Big Buck Bunny, (c)
+ copyright 2008, Blender Foundation / www.bigbuckbunny.org, licensed under
+ [CC BY 3.0](https://creativecommons.org/licenses/by/3.0/). It uses the 2013
+ "sunflower" 1080p 30 fps edition, unmodified apart from being played back
+ and screen-captured.
+
+## Limitations
+
+- These are Chrome renderings of mock apps, not native apps. Compositor
+ effects such as window shadows and blur are absent. Only `full_motion`
+ covers video playback, and only full screen (no UI around it, no
+ picture-in-picture or windowed video).
+- Capture timing is real time on a shared 4-core VM. Each run reports missed
+ slots and interval stdev; re-run a clip if `dropped_frames` > 0.
+- `full_motion`: even when phase-locked, about one run in two shows a single
+ repeat followed by a skip (roughly one event per 900 frames). Chrome's own
+ counters stay clean (0 dropped, every presented-frame step 1). The cause is
+ a late paint or an early buffer switch under CPU load, which the grab grid
+ cannot avoid. The recapture step handles it.
+- The cursor position comes from 240 Hz polling, so it is about ±4 ms
+ uncertain. Fast moves can therefore be off by a few px on single frames.
+ `cursor_check` quantifies this.
+- Scroll vectors describe container offsets. Content that moves without a
+ scroll offset is not reported as scroll: CSS push/cover slide transitions,
+ the dashboard's chart shift, the events feed inserting rows, drag ghosts. A
+ scroll entry can still have extra dirty content inside its rect (sticky
+ headers, caret, hover, new terminal lines). Smooth-scroll frames rendered between two rAF
+ reports are matched by realignment and are flagged when no reported offset
+ fits.
+- The docs page in `slow_typing` scrolls only ~31 px, so that clip has just a
+ few scroll frames.
+- `busy_ui_60fps` and `code_4k` are 20 s by spec, and their scenarios end about
+ 1-2 s early to guarantee a clean ending.
diff --git a/capcodec/bench/corpus/generate.py b/capcodec/bench/corpus/generate.py
new file mode 100644
index 000000000..1c72697d1
--- /dev/null
+++ b/capcodec/bench/corpus/generate.py
@@ -0,0 +1,1515 @@
+#!/usr/bin/env python3
+"""Generate the lossless screen-recording benchmark corpus.
+
+ python3 generate.py --list
+ python3 generate.py --clip slow_typing [--clip dashboard ...]
+ python3 generate.py --all
+ python3 generate.py --all --missing # only clips without outputs
+ python3 generate.py --clip idle --sideinfo-only
+ python3 generate.py --verify-lossless
+
+Outputs go to $CAPCODEC_CORPUS (default /home/ubuntu/work/corpus); the manifest
+is written next to this script. See README.md for the method.
+"""
+
+import argparse
+import cmath
+import hashlib
+import json
+import math
+import os
+import queue
+import random
+import shutil
+import signal
+import statistics
+import subprocess
+import sys
+import threading
+import time
+import traceback
+import urllib.request
+import zipfile
+from dataclasses import dataclass, field
+from pathlib import Path
+from urllib.parse import quote
+
+import numpy as np
+from Xlib import X
+from Xlib import display as xdisplay
+
+import playback
+import scenarios
+import sideinfo
+
+HERE = Path(__file__).resolve().parent
+PAGES = HERE / "pages"
+MANIFEST = HERE / "manifest.json"
+CORPUS = Path(os.environ.get("CAPCODEC_CORPUS", "/home/ubuntu/work/corpus"))
+CACHE = Path(os.environ.get("CAPCODEC_CACHE", "/home/ubuntu/work/cache/capcodec-corpus"))
+FFMPEG = os.environ.get("CAPCODEC_FFMPEG", "/home/ubuntu/tools/bin/ffmpeg")
+FFPROBE = os.environ.get("CAPCODEC_FFPROBE", str(Path(FFMPEG).with_name("ffprobe")))
+CHROME_CHANNEL = "chrome"
+
+LOCK_TARGET_MS = 25.0
+LOCK_TOLERANCE_MS = 4.5
+LOCK_MAX_ATTEMPTS = 40
+LOCK_MIN_LEAD_S = 1.5
+LOCK_TAIL_FRAMES = 45
+SOURCE_CAPTURE_RUNS = 3
+
+
+@dataclass(frozen=True)
+class VideoSource:
+ key: str
+ title: str
+ url: str
+ zip_sha256: str
+ member: str
+ sha256: str
+ fps: int
+ segment_start_s: float
+ segment_frames: int
+ cut_s: float
+ licence: str
+ licence_url: str
+ attribution: str
+ homepage: str
+
+ @property
+ def segment_name(self):
+ return f"{Path(self.member).stem}_from{self.segment_start_s:.3f}s_{self.segment_frames}f.mp4"
+
+ @property
+ def cut_frame(self):
+ return round((self.cut_s - self.segment_start_s) * self.fps)
+
+
+BIG_BUCK_BUNNY = VideoSource(
+ key="big_buck_bunny_sunflower",
+ title="Big Buck Bunny (2013 'sunflower' edition, 1920x1080, 30 fps, H.264 High, ~3 Mbit/s)",
+ url="https://download.blender.org/demo/movies/BBB/bbb_sunflower_1080p_30fps_normal.mp4.zip",
+ zip_sha256="e320fef389ec749117d0c1583945039266a40f25483881c2ff0d33207e62b362",
+ member="bbb_sunflower_1080p_30fps_normal.mp4",
+ sha256="ae51005850b0ff757fe60c3dd7a12d754d3cd2397d87d939b55235e457f97658",
+ fps=30,
+ segment_start_s=16.3,
+ segment_frames=1325,
+ cut_s=27.466667,
+ licence="CC BY 3.0",
+ licence_url="https://creativecommons.org/licenses/by/3.0/",
+ attribution="Big Buck Bunny, (c) copyright 2008, Blender Foundation / www.bigbuckbunny.org",
+ homepage="https://peach.blender.org/",
+)
+
+
+@dataclass
+class Clip:
+ name: str
+ page: str
+ description: str
+ tags: list
+ duration: int = 40
+ fps: int = 30
+ width: int = 1920
+ height: int = 1080
+ dsf: int = 1
+ display: str = ":99"
+ start_pointer: tuple = (1500, 800)
+ prepare_js: str = ""
+ settle_s: float = 1.2
+ seed: int = 1
+ threads: int = 2
+ draw_mouse: bool = True
+ source: VideoSource | None = None
+ extra: dict = field(default_factory=dict)
+
+ @property
+ def frames(self):
+ return self.duration * self.fps
+
+
+CLIPS = [
+ Clip(
+ "slow_typing",
+ "docs.html",
+ "Google-Docs-like editor, 15px Liberation Sans body text. Human typing via xdotool (120-250 ms per keystroke, "
+ "word-level pauses, two typo corrections with BackSpace), one wheel notch down/up, a few mouse moves and clicks.",
+ ["typing", "text", "light", "docs", "low-motion"],
+ start_pointer=(1380, 640),
+ seed=11,
+ ),
+ Clip(
+ "code_editor",
+ "code.html",
+ "VS Code Light+ workbench on CPython difflib.py, 13px JetBrains Mono. Types a new Python function with "
+ "auto-indent and IntelliSense popups, saves, then wheel-scrolls (single notches and bursts), PageDown x3, "
+ "arrow-key caret moves, a click and Ctrl+Home.",
+ ["code", "typing", "scroll", "text", "light", "monospace"],
+ start_pointer=(1250, 700),
+ seed=12,
+ ),
+ Clip(
+ "text_scroll",
+ "article.html",
+ "Wikipedia (Vector 2022)-like article with images, tables and references. Wheel scrolling at varying speeds "
+ "(single smooth notches, fast flicks up and down), link-preview hovers, a drag text selection, a 4.2 s eased "
+ "smooth scroll and keyboard PageDown.",
+ ["scroll", "text", "light", "web", "images"],
+ start_pointer=(1300, 600),
+ seed=13,
+ ),
+ Clip(
+ "slides",
+ "slides.html",
+ "16:9 presentation deck (charts, photo with grain, tables, timeline). Advances every ~3 s with cuts, 600 ms "
+ "fades and 650 ms push/cover slide-ins, incl. bullet builds, one step back, and a couple of pointer moves.",
+ ["slides", "transitions", "fades", "light"],
+ start_pointer=(1600, 880),
+ seed=14,
+ ),
+ Clip(
+ "busy_ui",
+ "board.html",
+ "Dense Linear/Notion-like issue board. The pointer moves almost constantly along curved paths: hover states, "
+ "tooltips, filter/card/display menus, a details side panel, three card drags with toasts, vertical column "
+ "scroll and horizontal board scroll.",
+ ["ui", "pointer", "menus", "drag", "scroll", "light"],
+ start_pointer=(900, 300),
+ seed=15,
+ ),
+ Clip(
+ "dashboard",
+ "dashboard.html",
+ "Analytics dashboard: 11-12px tables, KPI tiles with sparklines, numbers updating every second with flash "
+ "highlights, two canvas line charts shifting every second (420 ms animation), live event feed; pointer sweeps "
+ "chart crosshairs/tooltips and hovers table rows.",
+ ["dashboard", "small-text", "charts", "animation", "light"],
+ start_pointer=(1500, 560),
+ prepare_js="capStart()",
+ settle_s=2.5,
+ seed=16,
+ ),
+ Clip(
+ "dark_mode",
+ "dark.html",
+ "VS Code Dark+ on zlib inflate.c with an integrated terminal streaming libFuzzer logs (auto-scrolling). "
+ "Ctrl+C, typed git status / make test (build log), a one-line C edit + save, editor wheel scroll, then restarts "
+ "the fuzzer.",
+ ["code", "dark", "terminal", "scroll", "typing", "monospace"],
+ start_pointer=(1500, 420),
+ prepare_js="capStart()",
+ settle_s=2.0,
+ seed=17,
+ ),
+ Clip(
+ "idle",
+ "idle.html",
+ "Desktop-like static scene (PDF viewer window, dock, menu bar). Only the menu-bar clock ticks each second, "
+ "three notification toasts slide in/out, and the pointer moves four times.",
+ ["idle", "static", "text", "toasts"],
+ duration=60,
+ start_pointer=(1240, 760),
+ seed=18,
+ ),
+ Clip(
+ "webcam_overlay",
+ "slides.html?webcam=1",
+ "Slide deck with a 320px circular webcam bubble rendered on a canvas at 30 fps (moving gradient, "
+ "head-and-shoulders, blink/talk, per-frame sensor noise). The bubble is dragged to four positions; slides "
+ "advance every ~4 s.",
+ ["webcam", "noise", "slides", "drag", "overlay"],
+ start_pointer=(1400, 500),
+ seed=19,
+ ),
+ Clip(
+ "busy_ui_60fps",
+ "board.html",
+ "busy_ui scenario variant at 60 fps: continuous curved pointer motion and hovers, filter and card menus, a "
+ "card drag with toast, column wheel scroll.",
+ ["ui", "pointer", "60fps", "menus", "drag", "light"],
+ duration=20,
+ fps=60,
+ start_pointer=(900, 300),
+ seed=20,
+ threads=3,
+ ),
+ Clip(
+ "code_4k",
+ "code.html",
+ "3840x2160 (device scale factor 2) VS Code Light+ on difflib.py: types a short function, saves, wheel scroll, "
+ "PageDown, caret moves.",
+ ["code", "4k", "hidpi", "typing", "scroll", "monospace"],
+ duration=20,
+ width=3840,
+ height=2160,
+ dsf=2,
+ display=":98",
+ start_pointer=(2500, 1400),
+ seed=21,
+ threads=3,
+ ),
+ Clip(
+ "full_motion",
+ "video.html",
+ "Natural video full screen (worst case for a screen encoder): Big Buck Bunny 1080p30 (Blender Foundation, "
+ "CC BY 3.0) played by Chrome in a <video> filling the viewport (object-fit: cover, autoplay muted loop, no "
+ "controls), source 27.47-57.43 s from a shot cut: slow camera push-in on the burrow under the tree with "
+ "wind-blown grass and foliage, the dark burrow close-up as the bunny emerges, the bunny stretching in the "
+ "sunlit meadow. No input; pointer parked bottom-right, hidden (cursor: none, -draw_mouse 0).",
+ ["video", "natural", "full-motion", "camera-motion", "fine-detail", "worst-case"],
+ duration=30,
+ start_pointer=(1919, 1079),
+ settle_s=0.5,
+ seed=22,
+ threads=3,
+ draw_mouse=False,
+ source=BIG_BUCK_BUNNY,
+ ),
+]
+CLIP_BY_NAME = {c.name: c for c in CLIPS}
+
+
+def log(msg):
+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)
+
+
+def write_json(path, obj):
+ tmp = Path(str(path) + ".tmp")
+ with open(tmp, "w") as f:
+ json.dump(obj, f, indent=2)
+ f.write("\n")
+ tmp.replace(path)
+
+
+def sha256(path):
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ for chunk in iter(lambda: f.read(1 << 20), b""):
+ h.update(chunk)
+ return h.hexdigest()
+
+
+def framemd5(path, count=None, pix_fmt=None):
+ cmd = [FFMPEG, "-hide_banner", "-nostdin", "-loglevel", "error", "-i", str(path), "-map", "0:v:0"]
+ if count is not None:
+ cmd += ["-frames:v", str(count)]
+ if pix_fmt:
+ cmd += ["-pix_fmt", pix_fmt]
+ out = subprocess.run(cmd + ["-f", "framemd5", "-"], capture_output=True, text=True, check=True).stdout
+ return [ln.split(",")[-1].strip() for ln in out.splitlines() if ln and not ln.startswith("#")]
+
+
+def download(url, dest):
+ part = Path(str(dest) + ".part")
+ for attempt in range(4):
+ try:
+ log(f"downloading {url}")
+ urllib.request.urlretrieve(url, part)
+ part.replace(dest)
+ return
+ except OSError as e:
+ log(f"download failed ({e}); retrying")
+ time.sleep(4 * 2**attempt)
+ raise RuntimeError(f"could not download {url}")
+
+
+def prepare_video(src):
+ """Fetch the source into CACHE once and stream-copy the segment the page plays."""
+ CACHE.mkdir(parents=True, exist_ok=True)
+ mp4 = CACHE / src.member
+ if not mp4.exists() or sha256(mp4) != src.sha256:
+ z = CACHE / (src.member + ".zip")
+ if not z.exists() or sha256(z) != src.zip_sha256:
+ download(src.url, z)
+ if sha256(z) != src.zip_sha256:
+ raise RuntimeError(f"{z}: sha256 mismatch")
+ with zipfile.ZipFile(z) as zf, zf.open(src.member) as fin, open(str(mp4) + ".part", "wb") as fout:
+ shutil.copyfileobj(fin, fout, 1 << 20)
+ Path(str(mp4) + ".part").replace(mp4)
+ if sha256(mp4) != src.sha256:
+ raise RuntimeError(f"{mp4}: sha256 mismatch")
+ seg = CACHE / src.segment_name
+ meta_path = seg.with_suffix(".json")
+ meta = json.load(open(meta_path)) if meta_path.exists() else {}
+ if seg.exists() and meta.get("sha256") == sha256(seg) and meta.get("source_sha256") == src.sha256:
+ return meta
+ log(f"cutting {seg.name} (stream copy) and verifying it against the source")
+ probe = json.loads(
+ subprocess.run(
+ [FFPROBE, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=start_time", "-of", "json", str(mp4)],
+ capture_output=True, text=True, check=True,
+ ).stdout
+ )["streams"][0] # fmt: skip
+ first = round(src.segment_start_s * src.fps) - round(float(probe["start_time"]) * src.fps)
+ tmp = seg.with_suffix(".part.mp4")
+ subprocess.run(
+ [FFMPEG, "-hide_banner", "-nostdin", "-loglevel", "error", "-y", "-ss", str(src.segment_start_s), "-i", str(mp4),
+ "-map", "0:v:0", "-c", "copy", "-an", "-frames:v", str(src.segment_frames), "-movflags", "+faststart", str(tmp)],
+ check=True,
+ ) # fmt: skip
+ got = framemd5(tmp)
+ want = subprocess.run(
+ [FFMPEG, "-hide_banner", "-nostdin", "-loglevel", "error", "-i", str(mp4), "-map", "0:v:0",
+ "-vf", f"select=between(n\\,{first}\\,{first + src.segment_frames - 1})", "-fps_mode", "passthrough",
+ "-f", "framemd5", "-"],
+ capture_output=True, text=True, check=True,
+ ).stdout # fmt: skip
+ want = [ln.split(",")[-1].strip() for ln in want.splitlines() if ln and not ln.startswith("#")]
+ if len(got) != src.segment_frames or got != want:
+ raise RuntimeError(f"{tmp}: decoded segment differs from source frames {first}..")
+ tmp.replace(seg)
+ meta = {
+ "file": str(seg),
+ "sha256": sha256(seg),
+ "source_sha256": src.sha256,
+ "frames": src.segment_frames,
+ "source_first_frame_index": first,
+ "source_first_pts_s": src.segment_start_s,
+ "method": "ffmpeg -ss START -i SOURCE -map 0:v:0 -c copy -an (starts on a keyframe; no re-encode); every "
+ "decoded frame verified identical (framemd5) to the matching source frame",
+ }
+ write_json(meta_path, meta)
+ return meta
+
+
+def source_features(src):
+ meta = prepare_video(src)
+ cache = CACHE / f"{Path(src.segment_name).stem}.features.{meta['sha256'][:12]}.npy"
+ if cache.exists():
+ return np.load(cache)
+ feat = playback.features(playback.luma_frames(FFMPEG, CACHE / src.segment_name, yuv_bt709=True))
+ if len(feat) != src.segment_frames:
+ raise RuntimeError(f"decoded {len(feat)} segment frames, expected {src.segment_frames}")
+ np.save(cache, feat)
+ return feat
+
+
+def source_dirty(src):
+ meta = prepare_video(src)
+ cache = CACHE / f"{Path(src.segment_name).stem}.tiledirty.{meta['sha256'][:12]}.npy"
+ if cache.exists():
+ return np.load(cache)
+ dirty = playback.source_tile_dirty(FFMPEG, CACHE / src.segment_name, 1920, 1080)
+ if len(dirty) != src.segment_frames:
+ raise RuntimeError(f"decoded {len(dirty)} segment frames, expected {src.segment_frames}")
+ np.save(cache, dirty)
+ return dirty
+
+
+def circular_phase(values_ms, period_ms):
+ z = sum(cmath.exp(2j * math.pi * (v % period_ms) / period_ms) for v in values_ms) / len(values_ms)
+ return (cmath.phase(z) / (2 * math.pi) * period_ms) % period_ms, abs(z)
+
+
+def wrap(x, period):
+ return (x + period / 2) % period - period / 2
+
+
+def display_number(disp):
+ return int(disp.lstrip(":").split(".")[0])
+
+
+def screen_size(disp):
+ try:
+ d = xdisplay.Display(disp)
+ except Exception:
+ return None
+ s = d.screen()
+ size = (s.width_in_pixels, s.height_in_pixels)
+ d.close()
+ return size
+
+
+def xvfb_pid(disp):
+ lock = Path(f"/tmp/.X{display_number(disp)}-lock")
+ try:
+ return int(lock.read_text().strip())
+ except (OSError, ValueError):
+ return None
+
+
+class XvfbManager:
+ def __init__(self):
+ self.started = {}
+
+ def ensure(self, disp, width, height):
+ if disp == ":1":
+ raise RuntimeError("display :1 is reserved for VNC")
+ size = screen_size(disp)
+ if size is not None:
+ if size != (width, height):
+ raise RuntimeError(f"{disp} is running at {size}, need {width}x{height}")
+ return
+ log(f"starting Xvfb {disp} {width}x{height}")
+ proc = subprocess.Popen(
+ ["Xvfb", disp, "-screen", "0", f"{width}x{height}x24", "-nolisten", "tcp", "-dpi", "96", "-noreset"],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ start_new_session=True,
+ )
+ self.started[disp] = proc
+ for _ in range(100):
+ if screen_size(disp) == (width, height):
+ return
+ time.sleep(0.1)
+ raise RuntimeError(f"Xvfb {disp} did not come up")
+
+ def stop_all(self):
+ for disp, proc in self.started.items():
+ log(f"stopping Xvfb {disp} (pid {proc.pid})")
+ os.kill(proc.pid, signal.SIGTERM)
+ try:
+ proc.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ os.kill(proc.pid, signal.SIGKILL)
+ self.started.clear()
+
+
+def renice(pids):
+ pids = [str(p) for p in pids if p]
+ if pids:
+ subprocess.run(["sudo", "-n", "renice", "-n", "-10", "-p", *pids], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+
+
+def chrome_thread_ids(profile):
+ """Every thread of the Chrome instance using this profile (renice -p is per thread on Linux)."""
+ flag = f"--user-data-dir={profile}".encode()
+ children = {}
+ roots = []
+ for d in Path("/proc").iterdir():
+ if not d.name.isdigit():
+ continue
+ try:
+ ppid = int((d / "stat").read_text().rsplit(")", 1)[1].split()[1])
+ cmdline = (d / "cmdline").read_bytes().split(b"\0")
+ except (OSError, IndexError, ValueError):
+ continue
+ children.setdefault(ppid, []).append(int(d.name))
+ if flag in cmdline:
+ roots.append(int(d.name))
+ pids, todo = set(), list(roots)
+ while todo:
+ p = todo.pop()
+ if p not in pids:
+ pids.add(p)
+ todo.extend(children.get(p, []))
+ tids = []
+ for p in sorted(pids):
+ try:
+ tids += [int(t.name) for t in Path(f"/proc/{p}/task").iterdir()]
+ except OSError:
+ pass
+ return sorted(pids), tids
+
+
+def calibrate(clip, workdir):
+ """Measure x11grab per-grab latency and ffmpeg's start-to-first-frame delay."""
+ out = workdir / "calib.txt"
+ cmd = [
+ FFMPEG, "-hide_banner", "-nostdin", "-loglevel", "error", "-y",
+ "-f", "x11grab", "-framerate", "1000", "-video_size", f"{clip.width}x{clip.height}", "-draw_mouse", "1",
+ "-use_wallclock_as_timestamps", "1", "-i", clip.display, "-copyts", "-fps_mode", "passthrough",
+ "-enc_time_base:v", "demux", "-frames:v", "120", "-stats_enc_pre", str(out), "-stats_enc_pre_fmt", "{n} {pts}",
+ "-f", "null", "-",
+ ] # fmt: skip
+ t_start = time.time()
+ subprocess.run(cmd, check=True)
+ ts = [int(line.split()[1]) for line in out.read_text().split("\n") if line.strip()]
+ gaps = [(b - a) / 1000.0 for a, b in zip(ts[10:], ts[11:])]
+ return {"grab_latency_ms": round(statistics.median(gaps), 3), "startup_ms": round(ts[0] / 1000.0 - t_start * 1000.0, 1)}
+
+
+class PageBridge:
+ def __init__(self, page):
+ self.page = page
+ self.q = queue.Queue()
+
+ def call(self, expr, arg=None, timeout=15):
+ ev = threading.Event()
+ box = {}
+ self.q.put((expr, arg, ev, box))
+ if not ev.wait(timeout):
+ raise TimeoutError(f"page call timed out: {expr[:80]}")
+ if "err" in box:
+ raise box["err"]
+ return box["val"]
+
+ def pump(self, ms=10):
+ while True:
+ try:
+ expr, arg, ev, box = self.q.get_nowait()
+ except queue.Empty:
+ break
+ try:
+ box["val"] = self.page.evaluate(expr, arg)
+ except Exception as e:
+ box["err"] = e
+ ev.set()
+ self.page.wait_for_timeout(ms)
+
+
+def chrome_windows(disp):
+ r = subprocess.run(
+ ["xdotool", "search", "--onlyvisible", "--class", "Google-chrome"],
+ capture_output=True,
+ text=True,
+ env={"DISPLAY": disp, "PATH": "/usr/bin:/bin"},
+ )
+ return [w for w in r.stdout.split() if w.strip()]
+
+
+def fit_window(clip, page):
+ env = {"DISPLAY": clip.display, "PATH": "/usr/bin:/bin"}
+ want = [clip.width // clip.dsf, clip.height // clip.dsf, clip.dsf]
+ got = None
+ for _ in range(40):
+ for w in chrome_windows(clip.display):
+ subprocess.run(["xdotool", "windowmove", w, "0", "0", "windowsize", w, str(clip.width), str(clip.height)], env=env)
+ page.wait_for_timeout(150)
+ got = page.evaluate("[innerWidth, innerHeight, devicePixelRatio]")
+ if got == want:
+ wins = chrome_windows(clip.display)
+ if wins:
+ try:
+ subprocess.run(["xdotool", "windowfocus", "--sync", wins[-1]], env=env, timeout=5)
+ except subprocess.TimeoutExpired:
+ log("xdotool windowfocus timed out")
+ return got
+ page.wait_for_timeout(100)
+ raise RuntimeError(f"window did not reach {want}, got {got}")
+
+
+def focus_largest_chrome_window(disp):
+ d = xdisplay.Display(disp)
+ try:
+ best = None
+ for wid in chrome_windows(disp):
+ w = d.create_resource_object("window", int(wid))
+ g = w.get_geometry()
+ if best is None or g.width * g.height > best[0]:
+ best = (g.width * g.height, w)
+ if best is None:
+ return False
+ d.set_input_focus(best[1], X.RevertToParent, X.CurrentTime)
+ d.sync()
+ return True
+ finally:
+ d.close()
+
+
+def ensure_keyboard_focus(clip, page):
+ """Without a window manager Chrome reports document.hasFocus() but drops X key
+ events until the first click; Page.bringToFront activates the web contents.
+ A real Shift press verifies it before recording."""
+ env = {"DISPLAY": clip.display, "PATH": "/usr/bin:/bin"}
+ page.evaluate(
+ "() => { window.__capShiftSeen = 0; addEventListener('keydown', (e) => { if (e.key === 'Shift') window.__capShiftSeen++; }, true); }"
+ )
+
+ def probe():
+ before = page.evaluate("window.__capShiftSeen")
+ subprocess.run(["xdotool", "key", "shift"], env=env, timeout=5)
+ for _ in range(20):
+ page.wait_for_timeout(25)
+ if page.evaluate("window.__capShiftSeen") > before:
+ return True
+ return False
+
+ page.bring_to_front()
+ if probe():
+ return "bring_to_front"
+ if focus_largest_chrome_window(clip.display) and probe():
+ return "bring_to_front+XSetInputFocus"
+ raise RuntimeError("page does not receive X keyboard events")
+
+
+def parse_progress(path):
+ last = {}
+ try:
+ text = Path(path).read_text()
+ except OSError:
+ return last
+ for line in text.splitlines():
+ if "=" in line:
+ k, v = line.split("=", 1)
+ last[k.strip()] = v.strip()
+ return last
+
+
+def frame_timing(ts_us, fps):
+ nominal = 1000.0 / fps
+ ms = [t / 1000.0 for t in ts_us]
+ iv = [b - a for a, b in zip(ms, ms[1:])]
+ late = [x for x in iv if x > 1.5 * nominal]
+ catchup = [x for x in iv if x < 0.5 * nominal]
+ missed = sum(max(0, round(x / nominal) - 1) for x in late)
+ return {
+ "nominal_interval_ms": round(nominal, 3),
+ "mean_interval_ms": round(statistics.mean(iv), 3),
+ "stdev_interval_ms": round(statistics.pstdev(iv), 3),
+ "min_interval_ms": round(min(iv), 3),
+ "max_interval_ms": round(max(iv), 3),
+ "late_grabs": len(late),
+ "catchup_grabs": len(catchup),
+ "missed_slots": missed,
+ "wall_duration_ms": round(ms[-1] - ms[0] + nominal, 3),
+ }
+
+
+def chrome_args(clip):
+ return [
+ "--kiosk",
+ "--no-first-run",
+ "--no-default-browser-check",
+ "--disable-infobars",
+ "--disable-session-crashed-bubble",
+ "--disable-features=Translate,TranslateUI,MediaRouter,OptimizationHints,AutofillServerCommunication,DialMediaRouteProvider",
+ "--disable-background-networking",
+ "--disable-component-update",
+ "--disable-sync",
+ "--no-pings",
+ "--password-store=basic",
+ "--force-color-profile=srgb",
+ "--allow-file-access-from-files",
+ "--window-position=0,0",
+ f"--window-size={clip.width},{clip.height}",
+ f"--force-device-scale-factor={clip.dsf}",
+ ]
+
+
+def ffmpeg_cmd(clip, frames, work):
+ return [
+ FFMPEG, "-hide_banner", "-nostdin", "-y", "-loglevel", "info",
+ "-thread_queue_size", "64",
+ "-f", "x11grab", "-framerate", str(clip.fps), "-video_size", f"{clip.width}x{clip.height}",
+ "-draw_mouse", "1" if clip.draw_mouse else "0", "-use_wallclock_as_timestamps", "1", "-i", clip.display,
+ "-copyts", "-fps_mode", "passthrough", "-enc_time_base:v", "demux",
+ "-frames:v", str(frames),
+ "-c:v", "libx264rgb", "-preset", "ultrafast", "-qp", "0", "-g", str(clip.fps * 5), "-threads", str(clip.threads),
+ "-stats_enc_pre", str(work / "frames.txt"), "-stats_enc_pre_fmt", "{n} {tb} {pts}",
+ "-progress", str(work / "progress.txt"),
+ str(work / "raw.mkv"),
+ ] # fmt: skip
+
+
+def read_frame_pts_ms(path):
+ try:
+ lines = [ln.split() for ln in Path(path).read_text().splitlines() if ln.strip()]
+ except OSError:
+ return []
+ out = []
+ for ln in lines:
+ if len(ln) == 3:
+ num, den = (int(x) for x in ln[1].split("/"))
+ out.append(int(ln[2]) * 1000.0 * num / den)
+ return out
+
+
+def phase_lock(clip, page, work, launch):
+ """Relaunch ffmpeg until its x11grab grid sits LOCK_TARGET_MS after Chrome's video frame presentation phase.
+
+ x11grab grabs on a fixed grid (its start time + k/fps); the start time is random and pausing ffmpeg does not
+ move it. Chrome's 30 fps presentations keep a stable phase (requestVideoFrameCallback expectedDisplayTime E,
+ drift ~1.6 ms per 40 s) and the framebuffer switches to frame k+1 3.5-14 ms after E(k) (1000 fps probes;
+ content matching shows frame k is already on screen ~10 ms before E(k)), so a grid at E + 25 ms sits mid-way
+ between two switches. Each attempt is measured from ffmpeg's per-frame wallclock stats.
+ """
+ src = clip.source
+ period = 1000.0 / clip.fps
+ cut_media = src.cut_frame / src.fps
+ attempts = []
+ restarts = 0
+ while len(attempts) < LOCK_MAX_ATTEMPTS:
+ st = page.evaluate("capStats()")
+ if st["current_time"] > cut_media - LOCK_MIN_LEAD_S - 1.0 or st["paused"]:
+ restarts += 1
+ log(f"{clip.name}: media time {st['current_time']:.2f}s too close to the cut, restarting playback")
+ page.evaluate("capRestart()")
+ page.wait_for_function("window.capReady === true", timeout=30000)
+ continue
+ frames = math.ceil((cut_media - st["current_time"]) * clip.fps) + clip.frames + LOCK_TAIL_FRAMES
+ ff = launch(frames)
+ pts = []
+ deadline = time.time() + 5
+ while time.time() < deadline and ff.poll() is None:
+ pts = read_frame_pts_ms(work / "frames.txt")
+ if len(pts) >= 16:
+ break
+ page.wait_for_timeout(20)
+ if ff.poll() is not None:
+ raise RuntimeError(f"ffmpeg exited with {ff.returncode} during phase lock; see {work / 'ffmpeg.log'}")
+ if len(pts) < 16:
+ raise RuntimeError("ffmpeg produced no frame stats during phase lock")
+ grid, grid_r = circular_phase(pts[-8:], period)
+ recent = page.evaluate("capRecentFrames(30)")
+ vid, vid_r = circular_phase([r["expected_display"] for r in recent], period)
+ delta = wrap(grid - vid - LOCK_TARGET_MS, period)
+ media_now = page.evaluate("capStats().current_time")
+ ok = abs(delta) <= LOCK_TOLERANCE_MS and grid_r > 0.99 and vid_r > 0.98 and media_now < cut_media - LOCK_MIN_LEAD_S
+ attempts.append(
+ {
+ "frames_requested": frames,
+ "grid_phase_ms": round(grid, 3),
+ "grid_R": round(grid_r, 5),
+ "video_phase_ms": round(vid, 3),
+ "video_R": round(vid_r, 5),
+ "delta_ms": round(delta, 3),
+ "media_time_s": round(media_now, 3),
+ "accepted": ok,
+ }
+ )
+ if ok:
+ ref = recent[-1]
+ e_cut = ref["expected_display"] + (src.cut_frame - round(ref["media_time"] * src.fps)) * period
+ first_grab = e_cut - period + LOCK_TARGET_MS + wrap(pts[-1] - e_cut - LOCK_TARGET_MS, period)
+ log(f"{clip.name}: phase locked after {len(attempts)} attempt(s), delta {delta:+.1f} ms, lead {e_cut / 1000 - time.time():.1f}s")
+ lock = {
+ "target_ms": LOCK_TARGET_MS,
+ "tolerance_ms": LOCK_TOLERANCE_MS,
+ "playback_restarts": restarts,
+ "attempts": attempts,
+ "predicted_cut_display_ms": round(e_cut, 3),
+ "predicted_first_frame_ms": round(first_grab, 3),
+ "frames_total": frames,
+ }
+ return ff, lock
+ os.kill(ff.pid, signal.SIGKILL)
+ ff.wait(timeout=10)
+ raise RuntimeError(f"no phase lock after {len(attempts)} attempts: {attempts[-5:]}")
+
+
+def capture(clip, xvfb):
+ from playwright.sync_api import sync_playwright
+
+ work = CORPUS / ".work" / clip.name
+ if work.exists():
+ shutil.rmtree(work)
+ work.mkdir(parents=True)
+ video_meta = prepare_video(clip.source) if clip.source else None
+ xvfb.ensure(clip.display, clip.width, clip.height)
+ calib = calibrate(clip, work)
+ log(f"{clip.name}: grab latency {calib['grab_latency_ms']} ms, ffmpeg startup {calib['startup_ms']} ms")
+
+ page_records = []
+ actions = []
+ actions_lock = threading.Lock()
+
+ def action_log(kind, **kw):
+ rec = {"k": "action", "t": round(time.time() * 1000.0, 3), "type": kind, **kw}
+ with actions_lock:
+ actions.append(rec)
+
+ ff_log = work / "ffmpeg.log"
+ pointer_file = work / "pointer.jsonl"
+ ff_cmd = ffmpeg_cmd(clip, clip.frames, work)
+ url = (PAGES / clip.page.split("?")[0]).as_uri() + (("?" + clip.page.split("?", 1)[1]) if "?" in clip.page else "")
+ if video_meta:
+ url += ("&" if "?" in url else "?") + "src=" + quote(Path(video_meta["file"]).as_uri(), safe="")
+ info = {"url": url, "calibration": calib}
+ if video_meta:
+ info["source_segment"] = video_meta
+
+ def launch(frames):
+ for name in ("raw.mkv", "frames.txt", "progress.txt"):
+ (work / name).unlink(missing_ok=True)
+ cmd = ffmpeg_cmd(clip, frames, work)
+ with open(ff_log, "w") as flog:
+ proc = subprocess.Popen(cmd, stdout=flog, stderr=subprocess.STDOUT, start_new_session=True)
+ renice([proc.pid, xvfb_pid(clip.display)])
+ return proc
+ scenario_state = {"error": None, "truncated": None, "start_wall": None, "end_wall": None}
+ profile = work / "profile"
+ sampler = None
+ ff = None
+
+ with sync_playwright() as pw:
+ ctx = pw.chromium.launch_persistent_context(
+ str(profile),
+ channel=CHROME_CHANNEL,
+ headless=False,
+ no_viewport=True,
+ args=chrome_args(clip),
+ ignore_default_args=["--enable-automation"],
+ env={**os.environ, "DISPLAY": clip.display},
+ )
+ try:
+ info["chrome_version"] = ctx.browser.version if ctx.browser else None
+ ctx.expose_binding("__capReport", lambda source, batch: page_records.extend(batch))
+ page = ctx.pages[0] if ctx.pages else ctx.new_page()
+ console = []
+ page.on("console", lambda m: console.append(f"{m.type}: {m.text}") if m.type in ("error", "warning") else None)
+ page.on("pageerror", lambda e: console.append(f"pageerror: {e}"))
+ page.goto(url)
+ info["viewport"] = fit_window(clip, page)
+ page.wait_for_function("window.capReady === true", timeout=15000)
+ inp_rng = random.Random(clip.seed)
+ inp = scenarios.Input(clip.display, action_log, inp_rng)
+ inp.warp(*clip.start_pointer)
+ if clip.prepare_js:
+ page.evaluate(clip.prepare_js)
+ page.wait_for_timeout(int(clip.settle_s * 1000))
+ info["text_regions_css"] = page.evaluate("window.capTextRegions ? capTextRegions() : []")
+ info["has_focus"] = page.evaluate("document.hasFocus()")
+ info["keyboard_focus"] = ensure_keyboard_focus(clip, page)
+ bridge = PageBridge(page)
+
+ sampler = subprocess.Popen(
+ [sys.executable, str(HERE / "pointer_sampler.py"), "--display", clip.display, "--hz", "240", "--out", str(pointer_file)],
+ start_new_session=True,
+ )
+ for _ in range(100):
+ if pointer_file.exists() and pointer_file.stat().st_size > 0:
+ break
+ page.wait_for_timeout(20)
+
+ if clip.source:
+ pids, tids = chrome_thread_ids(profile)
+ renice(tids)
+ info["reniced_chrome"] = {"processes": len(pids), "threads": len(tids)}
+ info["video_stats_before"] = page.evaluate("capStats()")
+ ff, info["phase_lock"] = phase_lock(clip, page, work, launch)
+ ff_cmd = ffmpeg_cmd(clip, info["phase_lock"]["frames_total"], work)
+ t0 = info["phase_lock"]["predicted_first_frame_ms"] / 1000.0
+ else:
+ t_launch = time.time()
+ ff = launch(clip.frames)
+ t0 = t_launch + calib["startup_ms"] / 1000.0
+ sctx = scenarios.Ctx(clip, inp, random.Random(clip.seed * 7919), bridge.call, t0, action_log)
+
+ def run_scenario():
+ scenario_state["start_wall"] = time.time()
+ try:
+ scenarios.SCENARIOS[clip.name](sctx)
+ except scenarios.ScenarioOutOfTime as e:
+ scenario_state["truncated"] = str(e)
+ action_log("scenario_truncated", reason=str(e))
+ except Exception as e:
+ scenario_state["error"] = f"{type(e).__name__}: {e}\n{traceback.format_exc()}"
+ action_log("scenario_error", error=str(e))
+ finally:
+ inp.release_all()
+ scenario_state["end_wall"] = time.time()
+ action_log("scenario_end")
+
+ th = threading.Thread(target=run_scenario, name="scenario", daemon=True)
+ action_log("scenario_start")
+ th.start()
+ deadline = time.time() + clip.duration + 60
+ while (th.is_alive() or ff.poll() is None) and time.time() < deadline:
+ bridge.pump(10)
+ if ff.poll() is None:
+ ff.send_signal(signal.SIGINT)
+ ff.wait(timeout=20)
+ raise RuntimeError("ffmpeg did not finish in time")
+ th.join(timeout=10)
+ if clip.source:
+ info["video_stats_after"] = page.evaluate("capStats()")
+ page.evaluate("cap.flush()")
+ for _ in range(30):
+ bridge.pump(10)
+ info["console"] = console[:50]
+ finally:
+ if sampler is not None and sampler.poll() is None:
+ os.kill(sampler.pid, signal.SIGTERM)
+ sampler.wait(timeout=10)
+ if ff is not None and ff.poll() is None:
+ os.kill(ff.pid, signal.SIGINT)
+ ff.wait(timeout=20)
+ ctx.close()
+
+ if ff.returncode != 0:
+ raise RuntimeError(f"ffmpeg exited with {ff.returncode}; see {ff_log}")
+ if scenario_state["error"]:
+ log(f"{clip.name}: SCENARIO ERROR\n{scenario_state['error']}")
+ return finalize(clip, work, info, scenario_state, page_records, actions, ff_cmd)
+
+
+def trim_to_cut(clip, work, ts_us, page_records, lock):
+ """Find the raw frame that first shows the source cut frame and re-encode the clip from it (bit-exact)."""
+ src = clip.source
+ period = 1000.0 / clip.fps
+ ms = [t / 1000.0 for t in ts_us]
+
+ def nearest(t):
+ return min(range(len(ms)), key=lambda i: abs(ms[i] - t))
+
+ lock_index = nearest(lock["predicted_first_frame_ms"])
+ at_cut = [
+ r for r in page_records
+ if r.get("type") == "video_frame" and r["expected_display"] >= ms[0] - period
+ and round(r["media_time"] * src.fps) == src.cut_frame
+ ] # fmt: skip
+ rvfc_index = nearest(at_cut[0]["expected_display"] - period + LOCK_TARGET_MS) if at_cut else None
+ center = rvfc_index if rvfc_index is not None else lock_index
+ seg = source_features(src)
+ cap = playback.features(playback.luma_frames(FFMPEG, work / "raw.mkv", count=min(center + 45, len(ms))))
+ lo = max(0, center - 60)
+ window = cap[lo:]
+ offset = playback.find_offset(window, seg, probe=range(center - lo - 6, center - lo + 6))
+ js, chosen, other = playback.match(window, seg, offset)
+ hits = [k for k, j in enumerate(js) if j == src.cut_frame]
+ if not hits:
+ raise RuntimeError(f"{clip.name}: no raw frame near {center} shows source frame {src.cut_frame}: {js[-50:]}")
+ k = hits[0]
+ first = lo + k
+ if first + clip.frames > len(ms):
+ raise RuntimeError(f"{clip.name}: cut at raw frame {first} leaves fewer than {clip.frames} frames")
+ trim = work / "trim.mkv"
+ subprocess.run(
+ [FFMPEG, "-hide_banner", "-nostdin", "-loglevel", "error", "-y", "-i", str(work / "raw.mkv"), "-map", "0:v:0",
+ "-vf", f"select=between(n\\,{first}\\,{first + clip.frames - 1})", "-fps_mode", "passthrough",
+ "-frames:v", str(clip.frames), "-c:v", "libx264rgb", "-preset", "ultrafast", "-qp", "0",
+ "-g", str(clip.fps * 5), "-threads", "0", str(trim)],
+ check=True,
+ ) # fmt: skip
+ want = framemd5(work / "raw.mkv", count=first + clip.frames, pix_fmt="bgr0")[first:]
+ got = framemd5(trim, pix_fmt="bgr0")
+ if got != want:
+ raise RuntimeError(f"{clip.name}: trimmed clip is not bit-exact to raw frames {first}..")
+ log(f"{clip.name}: cut at raw frame {first} (rVFC {rvfc_index}, lock {lock_index}), trim verified bit-exact")
+ return {
+ "cut_source_s": src.cut_s,
+ "cut_segment_frame": src.cut_frame,
+ "raw_frames": len(ms),
+ "first_raw_frame": first,
+ "rvfc_predicted_raw_frame": rvfc_index,
+ "lock_predicted_raw_frame": lock_index,
+ "segment_frames_around_cut": js[max(0, k - 4) : k + 5],
+ "match_distance_at_cut": round(chosen[k], 4),
+ "next_best_distance_at_cut": round(other[k], 4),
+ "method": "raw frames mapped to segment frames by downscaled-luma matching (playback.py); first raw frame "
+ "showing the cut frame kept; frames [first, first+N) decoded and re-encoded with libx264rgb -qp 0 and "
+ "verified identical to the raw capture with framemd5 (bgr0)",
+ "verified_bit_exact": True,
+ }
+
+
+def finalize(clip, work, info, scenario_state, page_records, actions, ff_cmd):
+ raw = work / "raw.mkv"
+ lines = [ln.split() for ln in (work / "frames.txt").read_text().splitlines() if ln.strip()]
+ tb_num, tb_den = (int(x) for x in lines[0][1].split("/"))
+ ts_us = [int(ln[2]) * 1_000_000 * tb_num // tb_den for ln in lines]
+ expected_raw = info["phase_lock"]["frames_total"] if clip.source else clip.frames
+ if len(ts_us) != expected_raw:
+ raise RuntimeError(f"{clip.name}: encoder saw {len(ts_us)} frames, expected {expected_raw}")
+ if any(b <= a for a, b in zip(ts_us, ts_us[1:])):
+ raise RuntimeError(f"{clip.name}: non-increasing capture timestamps")
+
+ if clip.source:
+ info["trim"] = trim_to_cut(clip, work, ts_us, page_records, info["phase_lock"])
+ start = info["trim"]["first_raw_frame"]
+ ts_us = ts_us[start : start + clip.frames]
+ raw = work / "trim.mkv"
+
+ final = CORPUS / f"{clip.name}.mkv"
+ tmp_final = work / "final.mkv"
+ subprocess.run(
+ [
+ FFMPEG, "-hide_banner", "-nostdin", "-loglevel", "error", "-y", "-i", str(raw),
+ "-map", "0:v:0", "-c", "copy", "-bsf:v", f"setts=ts=N/({clip.fps}*TB)",
+ "-metadata", f"title={clip.name}", "-metadata", "comment=capcodec lossless screen corpus (libx264rgb qp0, GBR)",
+ str(tmp_final),
+ ],
+ check=True,
+ ) # fmt: skip
+ probe = json.loads(
+ subprocess.run(
+ [FFPROBE, "-v", "error", "-count_packets", "-select_streams", "v:0", "-show_entries",
+ "stream=codec_name,profile,pix_fmt,width,height,nb_read_packets,r_frame_rate", "-of", "json", str(tmp_final)],
+ capture_output=True, text=True, check=True,
+ ).stdout
+ )["streams"][0] # fmt: skip
+ if int(probe["nb_read_packets"]) != clip.frames or (probe["width"], probe["height"]) != (clip.width, clip.height):
+ raise RuntimeError(f"{clip.name}: remuxed file mismatch {probe}")
+ shutil.move(str(tmp_final), final)
+
+ timing = frame_timing(ts_us, clip.fps)
+ progress = parse_progress(work / "progress.txt")
+ ff_text = (work / "ffmpeg.log").read_text(errors="replace")
+ frame_ms = [round(t / 1000.0, 3) for t in ts_us]
+ video = {k: info.pop(k) for k in ("source_segment", "phase_lock", "trim", "video_stats_before", "video_stats_after") if k in info}
+ cap_log = {
+ "name": clip.name,
+ "width": clip.width,
+ "height": clip.height,
+ "fps": clip.fps,
+ "dsf": clip.dsf,
+ "display": clip.display,
+ "frames": clip.frames,
+ "codec": "libx264rgb -preset ultrafast -qp 0 (H.264 High 4:4:4 Predictive, lossless, GBR planes)",
+ "ffmpeg_command": ff_cmd,
+ "ffmpeg_dup_frames": int(progress.get("dup_frames", 0)),
+ "ffmpeg_drop_frames": int(progress.get("drop_frames", 0)),
+ "ffmpeg_speed": progress.get("speed"),
+ "ffmpeg_log_tail": ff_text.splitlines()[-12:],
+ "timing": timing,
+ "grab_latency_ms": info["calibration"]["grab_latency_ms"],
+ "ffmpeg_startup_ms": info["calibration"]["startup_ms"],
+ "first_frame_wallclock_ms": frame_ms[0],
+ "scenario": {
+ "start_offset_ms": round(scenario_state["start_wall"] * 1000.0 - frame_ms[0], 1) if scenario_state["start_wall"] else None,
+ "end_offset_ms": round(scenario_state["end_wall"] * 1000.0 - frame_ms[0], 1) if scenario_state["end_wall"] else None,
+ "truncated": scenario_state["truncated"],
+ "error": scenario_state["error"],
+ },
+ "page": info,
+ **video,
+ "frame_wallclock_ms": frame_ms,
+ }
+ write_json(CORPUS / f"{clip.name}.capture.json", cap_log)
+ (CORPUS / f"{clip.name}.capture.log").write_text(ff_text)
+ shutil.copy(work / "pointer.jsonl", CORPUS / f"{clip.name}.pointer.jsonl")
+
+ pointer = sideinfo.read_jsonl(CORPUS / f"{clip.name}.pointer.jsonl")
+ events = list(page_records) + list(actions)
+ last = None
+ for p in pointer:
+ pos = (p["x"], p["y"])
+ if pos != last:
+ events.append({"k": "pointer", "t": p["t"], "x": p["x"], "y": p["y"]})
+ last = pos
+ events.append({"k": "capture", "type": "first_frame", "t": frame_ms[0]})
+ events.append({"k": "capture", "type": "last_frame", "t": frame_ms[-1]})
+ events.sort(key=lambda e: e.get("tp", e["t"]))
+ with open(CORPUS / f"{clip.name}.events.jsonl", "w") as f:
+ for e in events:
+ f.write(json.dumps(e, separators=(",", ":")) + "\n")
+ shutil.rmtree(work, ignore_errors=True)
+ return postprocess(clip)
+
+
+def text_regions_px(clip, css_rects):
+ out = []
+ for r in css_rects or []:
+ x, y, w, h = (round(v * clip.dsf) for v in r)
+ c = sideinfo.clip_rect([x, y, w, h], clip.width, clip.height)
+ if c:
+ out.append(c)
+ return out
+
+
+def previews(clip, stats_dirty):
+ pdir = CORPUS / "previews"
+ pdir.mkdir(exist_ok=True)
+ for old in pdir.glob(f"{clip.name}_*.png"):
+ old.unlink()
+ n = clip.frames
+ sheet_frames = [0, n // 3, (2 * n) // 3, n - 1]
+ picks = sorted(set(sheet_frames) | {stats_dirty})
+ sel = "+".join(f"eq(n\\,{i})" for i in picks)
+ tmpl = pdir / f"{clip.name}_%02d.png"
+ subprocess.run(
+ [FFMPEG, "-hide_banner", "-nostdin", "-loglevel", "error", "-y", "-i", str(CORPUS / f"{clip.name}.mkv"),
+ "-vf", f"select='{sel}'", "-fps_mode", "passthrough", "-frames:v", str(len(picks)), str(tmpl)],
+ check=True,
+ ) # fmt: skip
+ files = {}
+ for k, i in enumerate(picks, start=1):
+ src = pdir / f"{clip.name}_{k:02d}.png"
+ dst = pdir / f"{clip.name}_f{i:05d}.png"
+ src.replace(dst)
+ files[i] = dst.name
+ sheet = pdir / f"{clip.name}_sheet.png"
+ inputs = []
+ for i in sheet_frames:
+ inputs += ["-i", str(pdir / files[i])]
+ filt = (
+ ";".join(f"[{k}:v]scale=960:-1[s{k}]" for k in range(4))
+ + ";[s0][s1][s2][s3]xstack=inputs=4:layout=0_0|w0_0|0_h0|w0_h0[out]"
+ )
+ subprocess.run([FFMPEG, "-hide_banner", "-nostdin", "-loglevel", "error", "-y", *inputs, "-filter_complex", filt, "-map", "[out]", str(sheet)], check=True)
+ return [f"previews/{files[i]}" for i in picks] + [f"previews/{sheet.name}"]
+
+
+def postprocess(clip):
+ cap_log = json.load(open(CORPUS / f"{clip.name}.capture.json"))
+ events = sideinfo.read_jsonl(CORPUS / f"{clip.name}.events.jsonl")
+ pointer = sideinfo.read_jsonl(CORPUS / f"{clip.name}.pointer.jsonl")
+ scroll = [e for e in events if e.get("k") == "scroll"]
+ log(f"{clip.name}: computing side info")
+ t = time.time()
+ stats = sideinfo.compute(
+ str(CORPUS / f"{clip.name}.mkv"),
+ cap_log["frame_wallclock_ms"],
+ clip.width,
+ clip.height,
+ clip.dsf,
+ pointer if clip.draw_mouse else [],
+ scroll,
+ str(CORPUS / f"{clip.name}.sideinfo.jsonl"),
+ ffmpeg=FFMPEG,
+ grab_latency_ms=cap_log["grab_latency_ms"],
+ )
+ log(f"{clip.name}: side info done in {time.time() - t:.1f}s")
+ max_dirty_frame = 0
+ best = -1.0
+ with open(CORPUS / f"{clip.name}.sideinfo.jsonl") as f:
+ for line in f:
+ rec = json.loads(line)
+ if rec["frame"] == 0:
+ continue
+ area = sum(r[2] * r[3] for r in rec["dirty"])
+ if area > best:
+ best, max_dirty_frame = area, rec["frame"]
+ prev_files = previews(clip, max_dirty_frame)
+ timing = cap_log["timing"]
+ entry = {
+ "name": clip.name,
+ "file": f"{clip.name}.mkv",
+ "width": clip.width,
+ "height": clip.height,
+ "fps": clip.fps,
+ "frames": clip.frames,
+ "duration_s": round(clip.frames / clip.fps, 3),
+ "sha256": sha256(CORPUS / f"{clip.name}.mkv"),
+ "tags": clip.tags,
+ "description": clip.description,
+ "device_scale_factor": clip.dsf,
+ "page": f"pages/{clip.page}",
+ "text_regions": text_regions_px(clip, cap_log["page"].get("text_regions_css")),
+ "sideinfo": f"{clip.name}.sideinfo.jsonl",
+ "events": f"{clip.name}.events.jsonl",
+ "pointer_samples": f"{clip.name}.pointer.jsonl",
+ "capture_log": f"{clip.name}.capture.json",
+ "previews": prev_files,
+ "avg_dirty_fraction": stats["avg_dirty_fraction"],
+ "identical_frames": stats["identical_frames"],
+ "cursor_check": stats["cursor"],
+ "capture": {
+ "codec": "libx264rgb qp0 (lossless H.264 High 4:4:4 Predictive, GBR), ultrafast, keyint " + str(clip.fps * 5),
+ "dropped_frames": timing["missed_slots"],
+ "duplicated_frames": timing["catchup_grabs"],
+ "ffmpeg_drop_frames": cap_log["ffmpeg_drop_frames"],
+ "ffmpeg_dup_frames": cap_log["ffmpeg_dup_frames"],
+ "late_grabs": timing["late_grabs"],
+ "max_interval_ms": timing["max_interval_ms"],
+ "interval_stdev_ms": timing["stdev_interval_ms"],
+ "method": (
+ f"ffmpeg x11grab -framerate {clip.fps} -draw_mouse {int(clip.draw_mouse)} -use_wallclock_as_timestamps 1 "
+ f"on Xvfb {clip.display} ({clip.width}x{clip.height}x24), -fps_mode passthrough, encoder time base = "
+ "demuxer (us); per-frame wallclock from -stats_enc_pre; remuxed with setts to CFR pts n/fps; Chrome kiosk, "
+ f"--force-device-scale-factor={clip.dsf}"
+ ),
+ },
+ "scroll_validation": stats["scroll"],
+ "generator": {"script": "bench/corpus/generate.py", "args": ["--clip", clip.name]},
+ }
+ if clip.source:
+ lock, trim = cap_log["phase_lock"], cap_log["trim"]
+ entry["capture"]["method"] += (
+ f"; ffmpeg relaunched until its grab grid sat {LOCK_TARGET_MS} +- {LOCK_TOLERANCE_MS} ms after Chrome's "
+ "video presentation phase (requestVideoFrameCallback expectedDisplayTime), started before the cut and "
+ "trimmed bit-exactly to the first frame showing it"
+ )
+ entry["capture"]["phase_lock"] = {
+ "attempts": len(lock["attempts"]),
+ "accepted_delta_ms": lock["attempts"][-1]["delta_ms"],
+ "playback_restarts": lock["playback_restarts"],
+ }
+ entry["capture"]["trim"] = {k: trim[k] for k in ("raw_frames", "first_raw_frame", "rvfc_predicted_raw_frame", "verified_bit_exact")}
+ if cap_log.get("capture_runs"):
+ entry["capture"]["runs"] = cap_log["capture_runs"]
+ entry["source_video"] = source_entry(clip, cap_log)
+ entry["playback_check"] = playback_check(clip, cap_log, events)
+ entry["playback"] = f"{clip.name}.playback.json"
+ update_manifest(entry)
+ return entry
+
+
+def playback_clean(entry):
+ pb, cap = entry["playback_check"], entry["capture"]
+ return (
+ pb["repeated_frames"] == 0
+ and pb["skipped_source_frames"] == 0
+ and pb["backward_steps"] == 0
+ and pb["source_first"] == pb["source_first_expected"]
+ and pb["source_last"] == pb["source_last_expected"]
+ and cap["dropped_frames"] == 0
+ and cap["duplicated_frames"] == 0
+ )
+
+
+def run_summary(entry):
+ pb = entry["playback_check"]
+ return {
+ "repeated_frames": pb["repeated_frames"],
+ "skipped_source_frames": pb["skipped_source_frames"],
+ "irregular_steps": pb["irregular_steps"][:6],
+ "identical_frames": entry["identical_frames"],
+ "dropped_frames": entry["capture"]["dropped_frames"],
+ "phase_lock_delta_ms": entry["capture"]["phase_lock"]["accepted_delta_ms"],
+ "chrome_dropped": pb["chrome_video_quality"]["dropped_during_clip"],
+ }
+
+
+def record_runs(clip, entry, rejected):
+ path = CORPUS / f"{clip.name}.capture.json"
+ cap_log = json.load(open(path))
+ cap_log["capture_runs"] = {
+ "runs": len(rejected) + 1,
+ "max_runs": SOURCE_CAPTURE_RUNS,
+ "policy": "recapture while the playback check shows repeated/skipped source frames or dropped grabs",
+ "rejected": rejected,
+ }
+ write_json(path, cap_log)
+ entry["capture"]["runs"] = cap_log["capture_runs"]
+ update_manifest(entry)
+ return entry
+
+
+def source_entry(clip, cap_log):
+ src = clip.source
+ seg = cap_log.get("source_segment", {})
+ last = src.cut_frame + clip.frames - 1
+ return {
+ "title": src.title,
+ "url": src.url,
+ "homepage": src.homepage,
+ "licence": src.licence,
+ "licence_url": src.licence_url,
+ "attribution": src.attribution,
+ "zip_sha256": src.zip_sha256,
+ "sha256": src.sha256,
+ "cache_dir": str(CACHE),
+ "segment": {
+ "file": src.segment_name,
+ "sha256": seg.get("sha256"),
+ "start_s": src.segment_start_s,
+ "frames": src.segment_frames,
+ "source_first_frame_index": seg.get("source_first_frame_index"),
+ "method": seg.get("method"),
+ },
+ "clip_source_range_s": [src.cut_s, round(src.segment_start_s + last / src.fps, 6)],
+ "clip_segment_frames": [src.cut_frame, last],
+ "transcoded": False,
+ "playback": "Chrome <video> (software H.264 decode of the original stream), muted, loop, object-fit: cover, "
+ "1:1 pixels at 1920x1080",
+ }
+
+
+def playback_check(clip, cap_log, events):
+ src = clip.source
+ log(f"{clip.name}: matching captured frames to source frames")
+ seg = source_features(src)
+ cap = playback.features(playback.luma_frames(FFMPEG, CORPUS / f"{clip.name}.mkv"))
+ if len(cap) != clip.frames:
+ raise RuntimeError(f"{clip.name}: decoded {len(cap)} frames for the playback check")
+ js, chosen, other = playback.match(cap, seg, src.cut_frame)
+ summary = playback.summarize(js, chosen, other, first_expected=src.cut_frame)
+ fm = cap_log["frame_wallclock_ms"]
+ summary["chrome_presentation"] = playback.video_frame_stats(events, fm[0], fm[-1], clip.fps)
+ stats = [e for e in events if e.get("k") == "action" and e.get("type") == "video_stats"]
+ after = cap_log.get("video_stats_after") or {}
+ summary["chrome_video_quality"] = {
+ "samples_during_clip": len(stats),
+ "dropped_during_clip": stats[-1]["dropped_video_frames"] - stats[0]["dropped_video_frames"] if len(stats) > 1 else None,
+ "decoded_during_clip": stats[-1]["total_video_frames"] - stats[0]["total_video_frames"] if len(stats) > 1 else None,
+ "dropped_total_at_end": after.get("dropped_video_frames"),
+ "decoded_total_at_end": after.get("total_video_frames"),
+ }
+ captured = playback.dirty_fractions(CORPUS / f"{clip.name}.sideinfo.jsonl", clip.width, clip.height)
+ summary["dirty_fraction_per_frame"] = playback.dirty_distribution(captured)
+ summary["dirty_vs_source"] = playback.dirty_vs_source(captured, source_dirty(src), js)
+ summary["method"] = (
+ "captured and source frames area-downscaled to 480x270 luma, high-passed and normalised (playback.py); each "
+ "captured frame matched to a source frame by 1 - normalised cross-correlation along a monotonic Viterbi path "
+ f"(offset band +-{playback.BAND}, {playback.OFFSET_PENALTY} per offset change); repeated_frames and "
+ "skipped_source_frames count source steps of 0 and >1 between consecutive captured frames"
+ )
+ write_json(
+ CORPUS / f"{clip.name}.playback.json",
+ {**summary, "source_frame_per_frame": js, "match_distance_per_frame": [round(x, 4) for x in chosen]},
+ )
+ return summary
+
+
+def load_manifest():
+ if MANIFEST.exists():
+ return json.load(open(MANIFEST))
+ return {"version": 1, "clips": []}
+
+
+def update_manifest(entry=None, **top):
+ m = load_manifest()
+ m["version"] = 1
+ m["corpus_dir"] = str(CORPUS)
+ m.update(top)
+ clips = {c["name"]: c for c in m.get("clips", [])}
+ if entry is not None:
+ clips[entry["name"]] = entry
+ order = [c.name for c in CLIPS]
+ m["clips"] = [clips[n] for n in order if n in clips] + [c for n, c in clips.items() if n not in order]
+ write_json(MANIFEST, m)
+
+
+def verify_lossless(xvfb):
+ """Feed one x11grab input to rawvideo and to libx264rgb qp0 and compare decoded frame hashes."""
+ results = []
+ for clip in (CLIP_BY_NAME["dashboard"], CLIP_BY_NAME["code_4k"]):
+ from playwright.sync_api import sync_playwright
+
+ work = CORPUS / ".work" / f"lossless_{clip.name}"
+ if work.exists():
+ shutil.rmtree(work)
+ work.mkdir(parents=True)
+ xvfb.ensure(clip.display, clip.width, clip.height)
+ with sync_playwright() as pw:
+ ctx = pw.chromium.launch_persistent_context(
+ str(work / "profile"),
+ channel=CHROME_CHANNEL,
+ headless=False,
+ no_viewport=True,
+ args=chrome_args(clip),
+ ignore_default_args=["--enable-automation"],
+ env={**os.environ, "DISPLAY": clip.display},
+ )
+ try:
+ page = ctx.pages[0] if ctx.pages else ctx.new_page()
+ page.goto((PAGES / clip.page.split("?")[0]).as_uri())
+ fit_window(clip, page)
+ page.wait_for_function("window.capReady === true", timeout=15000)
+ if "capStart" in clip.prepare_js:
+ page.evaluate(clip.prepare_js)
+ else:
+ page.evaluate("capEditor.scroller.scrollTop = 0; setInterval(() => { capEditor.scroller.scrollTop += 19; }, 120)")
+ page.wait_for_timeout(1000)
+ n = 3 * clip.fps
+ cmd = [
+ FFMPEG, "-hide_banner", "-nostdin", "-loglevel", "error", "-y",
+ "-f", "x11grab", "-framerate", str(clip.fps), "-video_size", f"{clip.width}x{clip.height}",
+ "-draw_mouse", "1", "-i", clip.display, "-frames:v", str(n),
+ "-map", "0:v", "-c:v", "rawvideo", "-f", "nut", str(work / "ref.nut"),
+ "-map", "0:v", "-frames:v", str(n), "-c:v", "libx264rgb", "-preset", "ultrafast", "-qp", "0",
+ "-threads", str(clip.threads), str(work / "x264.mkv"),
+ ] # fmt: skip
+ proc = subprocess.Popen(cmd)
+ inp = scenarios.Input(clip.display, lambda *a, **k: None, random.Random(1))
+ inp.warp(200, 200)
+ end = time.time() + 3.5
+ while proc.poll() is None and time.time() < end:
+ inp.move(random.uniform(100, clip.width - 100), random.uniform(100, clip.height - 100), dur=0.4)
+ proc.wait(timeout=60)
+ finally:
+ ctx.close()
+ hashes = {}
+ for name in ("ref.nut", "x264.mkv"):
+ out = subprocess.run(
+ [FFMPEG, "-hide_banner", "-nostdin", "-loglevel", "error", "-i", str(work / name), "-map", "0:v",
+ "-pix_fmt", "bgr0", "-f", "framemd5", "-"],
+ capture_output=True, text=True, check=True,
+ ).stdout # fmt: skip
+ hashes[name] = [ln.split(",")[-1].strip() for ln in out.splitlines() if ln and not ln.startswith("#")]
+ a, b = hashes["ref.nut"], hashes["x264.mkv"]
+ same = sum(x == y for x, y in zip(a, b))
+ distinct = len(set(a))
+ res = {
+ "resolution": f"{clip.width}x{clip.height}",
+ "fps": clip.fps,
+ "frames_compared": min(len(a), len(b)),
+ "frames_identical": same,
+ "distinct_frames": distinct,
+ "lossless": len(a) == len(b) and same == len(a) and len(a) > 0,
+ }
+ log(f"lossless check {res}")
+ results.append(res)
+ shutil.rmtree(work)
+ summary = {
+ "method": "single x11grab input -> (a) rawvideo NUT and (b) libx264rgb -preset ultrafast -qp 0 in one ffmpeg run; "
+ "framemd5 of both decoded to bgr0 compared frame by frame",
+ "results": results,
+ "lossless": all(r["lossless"] for r in results),
+ "checked_at": time.strftime("%Y-%m-%dT%H:%M:%S%z"),
+ }
+ write_json(CORPUS / "lossless_check.json", summary)
+ update_manifest(lossless_check=summary)
+ return summary
+
+
+def outputs_exist(clip):
+ return all((CORPUS / f"{clip.name}{ext}").exists() for ext in (".mkv", ".sideinfo.jsonl", ".events.jsonl", ".capture.json"))
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--clip", action="append", default=[], help="clip name (repeatable)")
+ ap.add_argument("--all", action="store_true", help="generate every clip")
+ ap.add_argument("--missing", action="store_true", help="with --all: skip clips whose outputs already exist")
+ ap.add_argument("--sideinfo-only", action="store_true", help="recompute side info/previews/manifest from existing captures")
+ ap.add_argument("--verify-lossless", action="store_true")
+ ap.add_argument("--list", action="store_true")
+ args = ap.parse_args()
+
+ if args.list:
+ for c in CLIPS:
+ print(f"{c.name:16s} {c.width}x{c.height}@{c.fps} {c.duration}s dsf={c.dsf} {c.page}")
+ return 0
+ names = [c.name for c in CLIPS] if args.all else args.clip
+ unknown = [n for n in names if n not in CLIP_BY_NAME]
+ if unknown:
+ ap.error(f"unknown clip(s): {', '.join(unknown)}")
+ if not names and not args.verify_lossless:
+ ap.error("nothing to do (use --clip NAME, --all, --verify-lossless or --list)")
+
+ CORPUS.mkdir(parents=True, exist_ok=True)
+ xvfb = XvfbManager()
+ failures = []
+ try:
+ if args.verify_lossless:
+ s = verify_lossless(xvfb)
+ if not s["lossless"]:
+ failures.append("lossless_check")
+ for n in names:
+ clip = CLIP_BY_NAME[n]
+ if args.missing and outputs_exist(clip):
+ log(f"{n}: outputs exist, skipping")
+ continue
+ log(f"{n}: start ({clip.width}x{clip.height}@{clip.fps}, {clip.duration}s, {clip.display})")
+ try:
+ if args.sideinfo_only:
+ entry = postprocess(clip)
+ else:
+ entry = capture(clip, xvfb)
+ rejected = []
+ while clip.source and not playback_clean(entry) and len(rejected) + 1 < SOURCE_CAPTURE_RUNS:
+ rejected.append(run_summary(entry))
+ log(f"{n}: playback check not clean {rejected[-1]}, recapturing")
+ entry = capture(clip, xvfb)
+ if clip.source:
+ entry = record_runs(clip, entry, rejected)
+ cap_log = json.load(open(CORPUS / f"{n}.capture.json"))
+ if cap_log["scenario"]["error"]:
+ failures.append(n)
+ elif clip.source and not playback_clean(entry):
+ log(f"{n}: playback check still not clean after {SOURCE_CAPTURE_RUNS} runs")
+ failures.append(n)
+ sv = entry["scroll_validation"]
+ log(
+ f"{n}: done frames={entry['frames']} dirty={entry['avg_dirty_fraction']:.4f} "
+ f"dropped={entry['capture']['dropped_frames']} late={entry['capture']['late_grabs']} "
+ f"scroll={sv['validated_frames']}/{sv['frames_with_scroll'] - sv.get('unverifiable_frames', 0)}"
+ f"(+{sv.get('unverifiable_frames', 0)} unverifiable) lat={sv['latency_ms']}ms "
+ f"cursor={entry['cursor_check']['fraction']} truncated={cap_log['scenario']['truncated']}"
+ )
+ if "playback_check" in entry:
+ pb = entry["playback_check"]
+ log(
+ f"{n}: source frames {pb['source_first']}..{pb['source_last']} repeated={pb['repeated_frames']} "
+ f"skipped={pb['skipped_source_frames']} identical={entry['identical_frames']} "
+ f"dirty min={pb['dirty_fraction_per_frame']['min']} >=0.99: "
+ f"{pb['dirty_fraction_per_frame']['frames_ge_0_99']}/{pb['dirty_fraction_per_frame']['frames_considered']} "
+ f"chrome dropped={pb['chrome_video_quality']['dropped_during_clip']}"
+ )
+ except Exception:
+ log(f"{n}: FAILED\n{traceback.format_exc()}")
+ failures.append(n)
+ finally:
+ xvfb.stop_all()
+ if failures:
+ log(f"failures: {failures}")
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/capcodec/bench/corpus/manifest.json b/capcodec/bench/corpus/manifest.json
new file mode 100644
index 000000000..4d70898d4
--- /dev/null
+++ b/capcodec/bench/corpus/manifest.json
@@ -0,0 +1,1464 @@
+{
+ "version": 1,
+ "clips": [
+ {
+ "name": "slow_typing",
+ "file": "slow_typing.mkv",
+ "width": 1920,
+ "height": 1080,
+ "fps": 30,
+ "frames": 1200,
+ "duration_s": 40.0,
+ "sha256": "405b196876613bf31c5f74f1fd9046d808745ddcf01928c3248beea542d58fc3",
+ "tags": [
+ "typing",
+ "text",
+ "light",
+ "docs",
+ "low-motion"
+ ],
+ "description": "Google-Docs-like editor, 15px Liberation Sans body text. Human typing via xdotool (120-250 ms per keystroke, word-level pauses, two typo corrections with BackSpace), one wheel notch down/up, a few mouse moves and clicks.",
+ "device_scale_factor": 1,
+ "page": "pages/docs.html",
+ "text_regions": [
+ [
+ 648,
+ 153,
+ 624,
+ 455
+ ],
+ [
+ 648,
+ 608,
+ 624,
+ 455
+ ]
+ ],
+ "sideinfo": "slow_typing.sideinfo.jsonl",
+ "events": "slow_typing.events.jsonl",
+ "pointer_samples": "slow_typing.pointer.jsonl",
+ "capture_log": "slow_typing.capture.json",
+ "previews": [
+ "previews/slow_typing_f00000.png",
+ "previews/slow_typing_f00400.png",
+ "previews/slow_typing_f00659.png",
+ "previews/slow_typing_f00800.png",
+ "previews/slow_typing_f01199.png",
+ "previews/slow_typing_sheet.png"
+ ],
+ "avg_dirty_fraction": 0.002112,
+ "identical_frames": 908,
+ "cursor_check": {
+ "frames_with_cursor": 1200,
+ "moved_frames": 97,
+ "moved_frames_with_dirty_hotspot_tile_at_old_and_new_pos": 92,
+ "fraction": 0.9485,
+ "sample_offset_ms": 4,
+ "fraction_at_zero_offset": 0.899,
+ "grab_latency_ms": 0.907,
+ "method": "latest 240 Hz query_pointer sample at or before frame wallclock + sample_offset_ms; offset fitted in [-12, 12] ms (1 ms steps) to maximise frames whose hotspot tile is dirty at both the previous and the new position"
+ },
+ "capture": {
+ "codec": "libx264rgb qp0 (lossless H.264 High 4:4:4 Predictive, GBR), ultrafast, keyint 150",
+ "dropped_frames": 0,
+ "duplicated_frames": 0,
+ "ffmpeg_drop_frames": 0,
+ "ffmpeg_dup_frames": 0,
+ "late_grabs": 0,
+ "max_interval_ms": 35.428,
+ "interval_stdev_ms": 0.493,
+ "method": "ffmpeg x11grab -framerate 30 -draw_mouse 1 -use_wallclock_as_timestamps 1 on Xvfb :99 (1920x1080x24), -fps_mode passthrough, encoder time base = demuxer (us); per-frame wallclock from -stats_enc_pre; remuxed with setts to CFR pts n/fps; Chrome kiosk, --force-device-scale-factor=1"
+ },
+ "scroll_validation": {
+ "frames_with_scroll": 12,
+ "unverifiable_frames": 0,
+ "validated_frames": 12,
+ "fraction": 1.0,
+ "entries": 12,
+ "valid_entries": 12,
+ "unverifiable_entries": 0,
+ "align_counts": {
+ "latency": 12,
+ "realigned": 0,
+ "held": 0,
+ "invalid": 0,
+ "unverifiable": 0
+ },
+ "latency_ms": 24,
+ "latency_frames": 0.72,
+ "latency_only": {
+ "frames_with_scroll": 12,
+ "validated_frames": 12,
+ "fraction": 1.0,
+ "score_at_chosen_latency": [
+ 12,
+ 12,
+ 0
+ ],
+ "score_at_zero_latency": [
+ -11,
+ 0,
+ 11
+ ]
+ },
+ "match_threshold": 0.9,
+ "residual_max": 0.25
+ },
+ "generator": {
+ "script": "bench/corpus/generate.py",
+ "args": [
+ "--clip",
+ "slow_typing"
+ ]
+ }
+ },
+ {
+ "name": "code_editor",
+ "file": "code_editor.mkv",
+ "width": 1920,
+ "height": 1080,
+ "fps": 30,
+ "frames": 1200,
+ "duration_s": 40.0,
+ "sha256": "d7cd86a27f5d55cf5ccb23d80ceb43f20f8f15535040c034259dc7b1e10fa1f8",
+ "tags": [
+ "code",
+ "typing",
+ "scroll",
+ "text",
+ "light",
+ "monospace"
+ ],
+ "description": "VS Code Light+ workbench on CPython difflib.py, 13px JetBrains Mono. Types a new Python function with auto-indent and IntelliSense popups, saves, then wheel-scrolls (single notches and bursts), PageDown x3, arrow-key caret moves, a click and Ctrl+Home.",
+ "device_scale_factor": 1,
+ "page": "pages/code.html",
+ "text_regions": [
+ [
+ 310,
+ 91,
+ 720,
+ 481
+ ],
+ [
+ 310,
+ 572,
+ 720,
+ 481
+ ]
+ ],
+ "sideinfo": "code_editor.sideinfo.jsonl",
+ "events": "code_editor.events.jsonl",
+ "pointer_samples": "code_editor.pointer.jsonl",
+ "capture_log": "code_editor.capture.json",
+ "previews": [
+ "previews/code_editor_f00000.png",
+ "previews/code_editor_f00400.png",
+ "previews/code_editor_f00772.png",
+ "previews/code_editor_f00800.png",
+ "previews/code_editor_f01199.png",
+ "previews/code_editor_sheet.png"
+ ],
+ "avg_dirty_fraction": 0.006199,
+ "identical_frames": 864,
+ "cursor_check": {
+ "frames_with_cursor": 1200,
+ "moved_frames": 108,
+ "moved_frames_with_dirty_hotspot_tile_at_old_and_new_pos": 108,
+ "fraction": 1.0,
+ "sample_offset_ms": 4,
+ "fraction_at_zero_offset": 0.963,
+ "grab_latency_ms": 0.994,
+ "method": "latest 240 Hz query_pointer sample at or before frame wallclock + sample_offset_ms; offset fitted in [-12, 12] ms (1 ms steps) to maximise frames whose hotspot tile is dirty at both the previous and the new position"
+ },
+ "capture": {
+ "codec": "libx264rgb qp0 (lossless H.264 High 4:4:4 Predictive, GBR), ultrafast, keyint 150",
+ "dropped_frames": 0,
+ "duplicated_frames": 0,
+ "ffmpeg_drop_frames": 0,
+ "ffmpeg_dup_frames": 0,
+ "late_grabs": 0,
+ "max_interval_ms": 34.564,
+ "interval_stdev_ms": 0.469,
+ "method": "ffmpeg x11grab -framerate 30 -draw_mouse 1 -use_wallclock_as_timestamps 1 on Xvfb :99 (1920x1080x24), -fps_mode passthrough, encoder time base = demuxer (us); per-frame wallclock from -stats_enc_pre; remuxed with setts to CFR pts n/fps; Chrome kiosk, --force-device-scale-factor=1"
+ },
+ "scroll_validation": {
+ "frames_with_scroll": 19,
+ "unverifiable_frames": 1,
+ "validated_frames": 18,
+ "fraction": 1.0,
+ "entries": 19,
+ "valid_entries": 18,
+ "unverifiable_entries": 1,
+ "align_counts": {
+ "latency": 18,
+ "realigned": 0,
+ "held": 0,
+ "invalid": 0,
+ "unverifiable": 1
+ },
+ "latency_ms": 4,
+ "latency_frames": 0.12,
+ "latency_only": {
+ "frames_with_scroll": 18,
+ "validated_frames": 18,
+ "fraction": 1.0,
+ "score_at_chosen_latency": [
+ 17,
+ 18,
+ 1
+ ],
+ "score_at_zero_latency": [
+ 17,
+ 18,
+ 1
+ ]
+ },
+ "match_threshold": 0.9,
+ "residual_max": 0.25
+ },
+ "generator": {
+ "script": "bench/corpus/generate.py",
+ "args": [
+ "--clip",
+ "code_editor"
+ ]
+ }
+ },
+ {
+ "name": "text_scroll",
+ "file": "text_scroll.mkv",
+ "width": 1920,
+ "height": 1080,
+ "fps": 30,
+ "frames": 1200,
+ "duration_s": 40.0,
+ "sha256": "ee286ac6cffa25d01fd244097f4cf8694c525e0bad66ee0fcf31cd8963ad8f1b",
+ "tags": [
+ "scroll",
+ "text",
+ "light",
+ "web",
+ "images"
+ ],
+ "description": "Wikipedia (Vector 2022)-like article with images, tables and references. Wheel scrolling at varying speeds (single smooth notches, fast flicks up and down), link-preview hovers, a drag text selection, a 4.2 s eased smooth scroll and keyboard PageDown.",
+ "device_scale_factor": 1,
+ "page": "pages/article.html",
+ "text_regions": [
+ [
+ 458,
+ 120,
+ 600,
+ 440
+ ],
+ [
+ 458,
+ 580,
+ 600,
+ 440
+ ]
+ ],
+ "sideinfo": "text_scroll.sideinfo.jsonl",
+ "events": "text_scroll.events.jsonl",
+ "pointer_samples": "text_scroll.pointer.jsonl",
+ "capture_log": "text_scroll.capture.json",
+ "previews": [
+ "previews/text_scroll_f00000.png",
+ "previews/text_scroll_f00069.png",
+ "previews/text_scroll_f00400.png",
+ "previews/text_scroll_f00800.png",
+ "previews/text_scroll_f01199.png",
+ "previews/text_scroll_sheet.png"
+ ],
+ "avg_dirty_fraction": 0.083433,
+ "identical_frames": 892,
+ "cursor_check": {
+ "frames_with_cursor": 1200,
+ "moved_frames": 81,
+ "moved_frames_with_dirty_hotspot_tile_at_old_and_new_pos": 81,
+ "fraction": 1.0,
+ "sample_offset_ms": 0,
+ "fraction_at_zero_offset": 1.0,
+ "grab_latency_ms": 0.991,
+ "method": "latest 240 Hz query_pointer sample at or before frame wallclock + sample_offset_ms; offset fitted in [-12, 12] ms (1 ms steps) to maximise frames whose hotspot tile is dirty at both the previous and the new position"
+ },
+ "capture": {
+ "codec": "libx264rgb qp0 (lossless H.264 High 4:4:4 Predictive, GBR), ultrafast, keyint 150",
+ "dropped_frames": 0,
+ "duplicated_frames": 0,
+ "ffmpeg_drop_frames": 0,
+ "ffmpeg_dup_frames": 0,
+ "late_grabs": 0,
+ "max_interval_ms": 34.423,
+ "interval_stdev_ms": 0.385,
+ "method": "ffmpeg x11grab -framerate 30 -draw_mouse 1 -use_wallclock_as_timestamps 1 on Xvfb :99 (1920x1080x24), -fps_mode passthrough, encoder time base = demuxer (us); per-frame wallclock from -stats_enc_pre; remuxed with setts to CFR pts n/fps; Chrome kiosk, --force-device-scale-factor=1"
+ },
+ "scroll_validation": {
+ "frames_with_scroll": 220,
+ "unverifiable_frames": 0,
+ "validated_frames": 220,
+ "fraction": 1.0,
+ "entries": 220,
+ "valid_entries": 220,
+ "unverifiable_entries": 0,
+ "align_counts": {
+ "latency": 112,
+ "realigned": 108,
+ "held": 0,
+ "invalid": 0,
+ "unverifiable": 0
+ },
+ "latency_ms": 2,
+ "latency_frames": 0.06,
+ "latency_only": {
+ "frames_with_scroll": 221,
+ "validated_frames": 178,
+ "fraction": 0.8054,
+ "score_at_chosen_latency": [
+ 135,
+ 178,
+ 43
+ ],
+ "score_at_zero_latency": [
+ 135,
+ 178,
+ 43
+ ]
+ },
+ "match_threshold": 0.9,
+ "residual_max": 0.25
+ },
+ "generator": {
+ "script": "bench/corpus/generate.py",
+ "args": [
+ "--clip",
+ "text_scroll"
+ ]
+ }
+ },
+ {
+ "name": "slides",
+ "file": "slides.mkv",
+ "width": 1920,
+ "height": 1080,
+ "fps": 30,
+ "frames": 1200,
+ "duration_s": 40.0,
+ "sha256": "0f20ec4335c7be5e2312fbce05086542110577ac376d69a25ec4be2070e0d756",
+ "tags": [
+ "slides",
+ "transitions",
+ "fades",
+ "light"
+ ],
+ "description": "16:9 presentation deck (charts, photo with grain, tables, timeline). Advances every ~3 s with cuts, 600 ms fades and 650 ms push/cover slide-ins, incl. bullet builds, one step back, and a couple of pointer moves.",
+ "device_scale_factor": 1,
+ "page": "pages/slides.html",
+ "text_regions": [
+ [
+ 120,
+ 80,
+ 1400,
+ 150
+ ],
+ [
+ 120,
+ 240,
+ 1500,
+ 560
+ ]
+ ],
+ "sideinfo": "slides.sideinfo.jsonl",
+ "events": "slides.events.jsonl",
+ "pointer_samples": "slides.pointer.jsonl",
+ "capture_log": "slides.capture.json",
+ "previews": [
+ "previews/slides_f00000.png",
+ "previews/slides_f00080.png",
+ "previews/slides_f00400.png",
+ "previews/slides_f00800.png",
+ "previews/slides_f01199.png",
+ "previews/slides_sheet.png"
+ ],
+ "avg_dirty_fraction": 0.052426,
+ "identical_frames": 913,
+ "cursor_check": {
+ "frames_with_cursor": 1200,
+ "moved_frames": 89,
+ "moved_frames_with_dirty_hotspot_tile_at_old_and_new_pos": 89,
+ "fraction": 1.0,
+ "sample_offset_ms": 2,
+ "fraction_at_zero_offset": 0.9775,
+ "grab_latency_ms": 0.95,
+ "method": "latest 240 Hz query_pointer sample at or before frame wallclock + sample_offset_ms; offset fitted in [-12, 12] ms (1 ms steps) to maximise frames whose hotspot tile is dirty at both the previous and the new position"
+ },
+ "capture": {
+ "codec": "libx264rgb qp0 (lossless H.264 High 4:4:4 Predictive, GBR), ultrafast, keyint 150",
+ "dropped_frames": 0,
+ "duplicated_frames": 0,
+ "ffmpeg_drop_frames": 0,
+ "ffmpeg_dup_frames": 0,
+ "late_grabs": 0,
+ "max_interval_ms": 37.952,
+ "interval_stdev_ms": 0.473,
+ "method": "ffmpeg x11grab -framerate 30 -draw_mouse 1 -use_wallclock_as_timestamps 1 on Xvfb :99 (1920x1080x24), -fps_mode passthrough, encoder time base = demuxer (us); per-frame wallclock from -stats_enc_pre; remuxed with setts to CFR pts n/fps; Chrome kiosk, --force-device-scale-factor=1"
+ },
+ "scroll_validation": {
+ "frames_with_scroll": 0,
+ "unverifiable_frames": 0,
+ "validated_frames": 0,
+ "fraction": null,
+ "entries": 0,
+ "valid_entries": 0,
+ "unverifiable_entries": 0,
+ "align_counts": {
+ "latency": 0,
+ "realigned": 0,
+ "held": 0,
+ "invalid": 0,
+ "unverifiable": 0
+ },
+ "latency_ms": null,
+ "latency_frames": null,
+ "latency_only": {
+ "frames_with_scroll": 0,
+ "validated_frames": 0,
+ "fraction": null,
+ "score_at_chosen_latency": null,
+ "score_at_zero_latency": null
+ },
+ "match_threshold": 0.9,
+ "residual_max": 0.25
+ },
+ "generator": {
+ "script": "bench/corpus/generate.py",
+ "args": [
+ "--clip",
+ "slides"
+ ]
+ }
+ },
+ {
+ "name": "busy_ui",
+ "file": "busy_ui.mkv",
+ "width": 1920,
+ "height": 1080,
+ "fps": 30,
+ "frames": 1200,
+ "duration_s": 40.0,
+ "sha256": "9a2b47e62a82c3eed3a6d2bdcb01001d820053a7065f023f31e0c23adc244605",
+ "tags": [
+ "ui",
+ "pointer",
+ "menus",
+ "drag",
+ "scroll",
+ "light"
+ ],
+ "description": "Dense Linear/Notion-like issue board. The pointer moves almost constantly along curved paths: hover states, tooltips, filter/card/display menus, a details side panel, three card drags with toasts, vertical column scroll and horizontal board scroll.",
+ "device_scale_factor": 1,
+ "page": "pages/board.html",
+ "text_regions": [
+ [
+ 4,
+ 60,
+ 236,
+ 560
+ ],
+ [
+ 268,
+ 152,
+ 304,
+ 600
+ ],
+ [
+ 900,
+ 152,
+ 304,
+ 600
+ ]
+ ],
+ "sideinfo": "busy_ui.sideinfo.jsonl",
+ "events": "busy_ui.events.jsonl",
+ "pointer_samples": "busy_ui.pointer.jsonl",
+ "capture_log": "busy_ui.capture.json",
+ "previews": [
+ "previews/busy_ui_f00000.png",
+ "previews/busy_ui_f00400.png",
+ "previews/busy_ui_f00800.png",
+ "previews/busy_ui_f01073.png",
+ "previews/busy_ui_f01199.png",
+ "previews/busy_ui_sheet.png"
+ ],
+ "avg_dirty_fraction": 0.014476,
+ "identical_frames": 467,
+ "cursor_check": {
+ "frames_with_cursor": 1200,
+ "moved_frames": 642,
+ "moved_frames_with_dirty_hotspot_tile_at_old_and_new_pos": 614,
+ "fraction": 0.9564,
+ "sample_offset_ms": 2,
+ "fraction_at_zero_offset": 0.9314,
+ "grab_latency_ms": 0.951,
+ "method": "latest 240 Hz query_pointer sample at or before frame wallclock + sample_offset_ms; offset fitted in [-12, 12] ms (1 ms steps) to maximise frames whose hotspot tile is dirty at both the previous and the new position"
+ },
+ "capture": {
+ "codec": "libx264rgb qp0 (lossless H.264 High 4:4:4 Predictive, GBR), ultrafast, keyint 150",
+ "dropped_frames": 0,
+ "duplicated_frames": 0,
+ "ffmpeg_drop_frames": 0,
+ "ffmpeg_dup_frames": 0,
+ "late_grabs": 0,
+ "max_interval_ms": 35.189,
+ "interval_stdev_ms": 0.384,
+ "method": "ffmpeg x11grab -framerate 30 -draw_mouse 1 -use_wallclock_as_timestamps 1 on Xvfb :99 (1920x1080x24), -fps_mode passthrough, encoder time base = demuxer (us); per-frame wallclock from -stats_enc_pre; remuxed with setts to CFR pts n/fps; Chrome kiosk, --force-device-scale-factor=1"
+ },
+ "scroll_validation": {
+ "frames_with_scroll": 38,
+ "unverifiable_frames": 0,
+ "validated_frames": 38,
+ "fraction": 1.0,
+ "entries": 38,
+ "valid_entries": 38,
+ "unverifiable_entries": 0,
+ "align_counts": {
+ "latency": 22,
+ "realigned": 16,
+ "held": 1,
+ "invalid": 0,
+ "unverifiable": 0
+ },
+ "latency_ms": 4,
+ "latency_frames": 0.12,
+ "latency_only": {
+ "frames_with_scroll": 39,
+ "validated_frames": 21,
+ "fraction": 0.5385,
+ "score_at_chosen_latency": [
+ 3,
+ 21,
+ 18
+ ],
+ "score_at_zero_latency": [
+ 3,
+ 21,
+ 18
+ ]
+ },
+ "match_threshold": 0.9,
+ "residual_max": 0.25
+ },
+ "generator": {
+ "script": "bench/corpus/generate.py",
+ "args": [
+ "--clip",
+ "busy_ui"
+ ]
+ }
+ },
+ {
+ "name": "dashboard",
+ "file": "dashboard.mkv",
+ "width": 1920,
+ "height": 1080,
+ "fps": 30,
+ "frames": 1200,
+ "duration_s": 40.0,
+ "sha256": "025783d2e2ee7682e284e6d1003c359734feba7f2aa58916d2d24876aea5292a",
+ "tags": [
+ "dashboard",
+ "small-text",
+ "charts",
+ "animation",
+ "light"
+ ],
+ "description": "Analytics dashboard: 11-12px tables, KPI tiles with sparklines, numbers updating every second with flash highlights, two canvas line charts shifting every second (420 ms animation), live event feed; pointer sweeps chart crosshairs/tooltips and hovers table rows.",
+ "device_scale_factor": 1,
+ "page": "pages/dashboard.html",
+ "text_regions": [
+ [
+ 35,
+ 576,
+ 820,
+ 400
+ ],
+ [
+ 20,
+ 66,
+ 934,
+ 104
+ ],
+ [
+ 1296,
+ 745,
+ 589,
+ 320
+ ]
+ ],
+ "sideinfo": "dashboard.sideinfo.jsonl",
+ "events": "dashboard.events.jsonl",
+ "pointer_samples": "dashboard.pointer.jsonl",
+ "capture_log": "dashboard.capture.json",
+ "previews": [
+ "previews/dashboard_f00000.png",
+ "previews/dashboard_f00400.png",
+ "previews/dashboard_f00548.png",
+ "previews/dashboard_f00800.png",
+ "previews/dashboard_f01199.png",
+ "previews/dashboard_sheet.png"
+ ],
+ "avg_dirty_fraction": 0.062966,
+ "identical_frames": 0,
+ "cursor_check": {
+ "frames_with_cursor": 1200,
+ "moved_frames": 582,
+ "moved_frames_with_dirty_hotspot_tile_at_old_and_new_pos": 573,
+ "fraction": 0.9845,
+ "sample_offset_ms": 4,
+ "fraction_at_zero_offset": 0.9416,
+ "grab_latency_ms": 0.993,
+ "method": "latest 240 Hz query_pointer sample at or before frame wallclock + sample_offset_ms; offset fitted in [-12, 12] ms (1 ms steps) to maximise frames whose hotspot tile is dirty at both the previous and the new position"
+ },
+ "capture": {
+ "codec": "libx264rgb qp0 (lossless H.264 High 4:4:4 Predictive, GBR), ultrafast, keyint 150",
+ "dropped_frames": 0,
+ "duplicated_frames": 0,
+ "ffmpeg_drop_frames": 0,
+ "ffmpeg_dup_frames": 0,
+ "late_grabs": 0,
+ "max_interval_ms": 35.541,
+ "interval_stdev_ms": 0.354,
+ "method": "ffmpeg x11grab -framerate 30 -draw_mouse 1 -use_wallclock_as_timestamps 1 on Xvfb :99 (1920x1080x24), -fps_mode passthrough, encoder time base = demuxer (us); per-frame wallclock from -stats_enc_pre; remuxed with setts to CFR pts n/fps; Chrome kiosk, --force-device-scale-factor=1"
+ },
+ "scroll_validation": {
+ "frames_with_scroll": 0,
+ "unverifiable_frames": 0,
+ "validated_frames": 0,
+ "fraction": null,
+ "entries": 0,
+ "valid_entries": 0,
+ "unverifiable_entries": 0,
+ "align_counts": {
+ "latency": 0,
+ "realigned": 0,
+ "held": 0,
+ "invalid": 0,
+ "unverifiable": 0
+ },
+ "latency_ms": null,
+ "latency_frames": null,
+ "latency_only": {
+ "frames_with_scroll": 0,
+ "validated_frames": 0,
+ "fraction": null,
+ "score_at_chosen_latency": null,
+ "score_at_zero_latency": null
+ },
+ "match_threshold": 0.9,
+ "residual_max": 0.25
+ },
+ "generator": {
+ "script": "bench/corpus/generate.py",
+ "args": [
+ "--clip",
+ "dashboard"
+ ]
+ }
+ },
+ {
+ "name": "dark_mode",
+ "file": "dark_mode.mkv",
+ "width": 1920,
+ "height": 1080,
+ "fps": 30,
+ "frames": 1200,
+ "duration_s": 40.0,
+ "sha256": "92840637b541123dae559debe387bc40776e964f2f40a948801ea13e7688676d",
+ "tags": [
+ "code",
+ "dark",
+ "terminal",
+ "scroll",
+ "typing",
+ "monospace"
+ ],
+ "description": "VS Code Dark+ on zlib inflate.c with an integrated terminal streaming libFuzzer logs (auto-scrolling). Ctrl+C, typed git status / make test (build log), a one-line C edit + save, editor wheel scroll, then restarts the fuzzer.",
+ "device_scale_factor": 1,
+ "page": "pages/dark.html",
+ "text_regions": [
+ [
+ 310,
+ 91,
+ 720,
+ 559
+ ],
+ [
+ 330,
+ 692,
+ 1100,
+ 364
+ ]
+ ],
+ "sideinfo": "dark_mode.sideinfo.jsonl",
+ "events": "dark_mode.events.jsonl",
+ "pointer_samples": "dark_mode.pointer.jsonl",
+ "capture_log": "dark_mode.capture.json",
+ "previews": [
+ "previews/dark_mode_f00000.png",
+ "previews/dark_mode_f00400.png",
+ "previews/dark_mode_f00672.png",
+ "previews/dark_mode_f00800.png",
+ "previews/dark_mode_f01199.png",
+ "previews/dark_mode_sheet.png"
+ ],
+ "avg_dirty_fraction": 0.007266,
+ "identical_frames": 876,
+ "cursor_check": {
+ "frames_with_cursor": 1200,
+ "moved_frames": 131,
+ "moved_frames_with_dirty_hotspot_tile_at_old_and_new_pos": 124,
+ "fraction": 0.9466,
+ "sample_offset_ms": 1,
+ "fraction_at_zero_offset": 0.8931,
+ "grab_latency_ms": 0.975,
+ "method": "latest 240 Hz query_pointer sample at or before frame wallclock + sample_offset_ms; offset fitted in [-12, 12] ms (1 ms steps) to maximise frames whose hotspot tile is dirty at both the previous and the new position"
+ },
+ "capture": {
+ "codec": "libx264rgb qp0 (lossless H.264 High 4:4:4 Predictive, GBR), ultrafast, keyint 150",
+ "dropped_frames": 0,
+ "duplicated_frames": 0,
+ "ffmpeg_drop_frames": 0,
+ "ffmpeg_dup_frames": 0,
+ "late_grabs": 0,
+ "max_interval_ms": 34.45,
+ "interval_stdev_ms": 0.479,
+ "method": "ffmpeg x11grab -framerate 30 -draw_mouse 1 -use_wallclock_as_timestamps 1 on Xvfb :99 (1920x1080x24), -fps_mode passthrough, encoder time base = demuxer (us); per-frame wallclock from -stats_enc_pre; remuxed with setts to CFR pts n/fps; Chrome kiosk, --force-device-scale-factor=1"
+ },
+ "scroll_validation": {
+ "frames_with_scroll": 88,
+ "unverifiable_frames": 0,
+ "validated_frames": 88,
+ "fraction": 1.0,
+ "entries": 88,
+ "valid_entries": 88,
+ "unverifiable_entries": 0,
+ "align_counts": {
+ "latency": 88,
+ "realigned": 0,
+ "held": 0,
+ "invalid": 0,
+ "unverifiable": 0
+ },
+ "latency_ms": 10,
+ "latency_frames": 0.3,
+ "latency_only": {
+ "frames_with_scroll": 88,
+ "validated_frames": 88,
+ "fraction": 1.0,
+ "score_at_chosen_latency": [
+ 88,
+ 88,
+ 0
+ ],
+ "score_at_zero_latency": [
+ 6,
+ 47,
+ 41
+ ]
+ },
+ "match_threshold": 0.9,
+ "residual_max": 0.25
+ },
+ "generator": {
+ "script": "bench/corpus/generate.py",
+ "args": [
+ "--clip",
+ "dark_mode"
+ ]
+ }
+ },
+ {
+ "name": "idle",
+ "file": "idle.mkv",
+ "width": 1920,
+ "height": 1080,
+ "fps": 30,
+ "frames": 1800,
+ "duration_s": 60.0,
+ "sha256": "cf3e3c23d8d1f51b3d654c6cc6480defc79cda9a9e9e979f4faa74af41f3a1d9",
+ "tags": [
+ "idle",
+ "static",
+ "text",
+ "toasts"
+ ],
+ "description": "Desktop-like static scene (PDF viewer window, dock, menu bar). Only the menu-bar clock ticks each second, three notification toasts slide in/out, and the pointer moves four times.",
+ "device_scale_factor": 1,
+ "page": "pages/idle.html",
+ "text_regions": [
+ [
+ 712,
+ 291,
+ 692,
+ 214
+ ],
+ [
+ 712,
+ 804,
+ 692,
+ 90
+ ]
+ ],
+ "sideinfo": "idle.sideinfo.jsonl",
+ "events": "idle.events.jsonl",
+ "pointer_samples": "idle.pointer.jsonl",
+ "capture_log": "idle.capture.json",
+ "previews": [
+ "previews/idle_f00000.png",
+ "previews/idle_f00600.png",
+ "previews/idle_f01200.png",
+ "previews/idle_f01543.png",
+ "previews/idle_f01799.png",
+ "previews/idle_sheet.png"
+ ],
+ "avg_dirty_fraction": 0.000678,
+ "identical_frames": 1576,
+ "cursor_check": {
+ "frames_with_cursor": 1800,
+ "moved_frames": 104,
+ "moved_frames_with_dirty_hotspot_tile_at_old_and_new_pos": 104,
+ "fraction": 1.0,
+ "sample_offset_ms": 2,
+ "fraction_at_zero_offset": 0.9709,
+ "grab_latency_ms": 0.975,
+ "method": "latest 240 Hz query_pointer sample at or before frame wallclock + sample_offset_ms; offset fitted in [-12, 12] ms (1 ms steps) to maximise frames whose hotspot tile is dirty at both the previous and the new position"
+ },
+ "capture": {
+ "codec": "libx264rgb qp0 (lossless H.264 High 4:4:4 Predictive, GBR), ultrafast, keyint 150",
+ "dropped_frames": 0,
+ "duplicated_frames": 0,
+ "ffmpeg_drop_frames": 0,
+ "ffmpeg_dup_frames": 0,
+ "late_grabs": 0,
+ "max_interval_ms": 34.789,
+ "interval_stdev_ms": 0.419,
+ "method": "ffmpeg x11grab -framerate 30 -draw_mouse 1 -use_wallclock_as_timestamps 1 on Xvfb :99 (1920x1080x24), -fps_mode passthrough, encoder time base = demuxer (us); per-frame wallclock from -stats_enc_pre; remuxed with setts to CFR pts n/fps; Chrome kiosk, --force-device-scale-factor=1"
+ },
+ "scroll_validation": {
+ "frames_with_scroll": 0,
+ "unverifiable_frames": 0,
+ "validated_frames": 0,
+ "fraction": null,
+ "entries": 0,
+ "valid_entries": 0,
+ "unverifiable_entries": 0,
+ "align_counts": {
+ "latency": 0,
+ "realigned": 0,
+ "held": 0,
+ "invalid": 0,
+ "unverifiable": 0
+ },
+ "latency_ms": null,
+ "latency_frames": null,
+ "latency_only": {
+ "frames_with_scroll": 0,
+ "validated_frames": 0,
+ "fraction": null,
+ "score_at_chosen_latency": null,
+ "score_at_zero_latency": null
+ },
+ "match_threshold": 0.9,
+ "residual_max": 0.25
+ },
+ "generator": {
+ "script": "bench/corpus/generate.py",
+ "args": [
+ "--clip",
+ "idle"
+ ]
+ }
+ },
+ {
+ "name": "webcam_overlay",
+ "file": "webcam_overlay.mkv",
+ "width": 1920,
+ "height": 1080,
+ "fps": 30,
+ "frames": 1200,
+ "duration_s": 40.0,
+ "sha256": "e6ebac847d0ea7a28108e37fe408211838099cea7704184c6b35a887c8ee2c3c",
+ "tags": [
+ "webcam",
+ "noise",
+ "slides",
+ "drag",
+ "overlay"
+ ],
+ "description": "Slide deck with a 320px circular webcam bubble rendered on a canvas at 30 fps (moving gradient, head-and-shoulders, blink/talk, per-frame sensor noise). The bubble is dragged to four positions; slides advance every ~4 s.",
+ "device_scale_factor": 1,
+ "page": "pages/slides.html?webcam=1",
+ "text_regions": [
+ [
+ 120,
+ 80,
+ 1400,
+ 150
+ ],
+ [
+ 120,
+ 240,
+ 1500,
+ 560
+ ]
+ ],
+ "sideinfo": "webcam_overlay.sideinfo.jsonl",
+ "events": "webcam_overlay.events.jsonl",
+ "pointer_samples": "webcam_overlay.pointer.jsonl",
+ "capture_log": "webcam_overlay.capture.json",
+ "previews": [
+ "previews/webcam_overlay_f00000.png",
+ "previews/webcam_overlay_f00181.png",
+ "previews/webcam_overlay_f00400.png",
+ "previews/webcam_overlay_f00800.png",
+ "previews/webcam_overlay_f01199.png",
+ "previews/webcam_overlay_sheet.png"
+ ],
+ "avg_dirty_fraction": 0.087328,
+ "identical_frames": 0,
+ "cursor_check": {
+ "frames_with_cursor": 1200,
+ "moved_frames": 364,
+ "moved_frames_with_dirty_hotspot_tile_at_old_and_new_pos": 359,
+ "fraction": 0.9863,
+ "sample_offset_ms": 2,
+ "fraction_at_zero_offset": 0.9752,
+ "grab_latency_ms": 0.986,
+ "method": "latest 240 Hz query_pointer sample at or before frame wallclock + sample_offset_ms; offset fitted in [-12, 12] ms (1 ms steps) to maximise frames whose hotspot tile is dirty at both the previous and the new position"
+ },
+ "capture": {
+ "codec": "libx264rgb qp0 (lossless H.264 High 4:4:4 Predictive, GBR), ultrafast, keyint 150",
+ "dropped_frames": 0,
+ "duplicated_frames": 0,
+ "ffmpeg_drop_frames": 0,
+ "ffmpeg_dup_frames": 0,
+ "late_grabs": 0,
+ "max_interval_ms": 34.6,
+ "interval_stdev_ms": 0.439,
+ "method": "ffmpeg x11grab -framerate 30 -draw_mouse 1 -use_wallclock_as_timestamps 1 on Xvfb :99 (1920x1080x24), -fps_mode passthrough, encoder time base = demuxer (us); per-frame wallclock from -stats_enc_pre; remuxed with setts to CFR pts n/fps; Chrome kiosk, --force-device-scale-factor=1"
+ },
+ "scroll_validation": {
+ "frames_with_scroll": 0,
+ "unverifiable_frames": 0,
+ "validated_frames": 0,
+ "fraction": null,
+ "entries": 0,
+ "valid_entries": 0,
+ "unverifiable_entries": 0,
+ "align_counts": {
+ "latency": 0,
+ "realigned": 0,
+ "held": 0,
+ "invalid": 0,
+ "unverifiable": 0
+ },
+ "latency_ms": null,
+ "latency_frames": null,
+ "latency_only": {
+ "frames_with_scroll": 0,
+ "validated_frames": 0,
+ "fraction": null,
+ "score_at_chosen_latency": null,
+ "score_at_zero_latency": null
+ },
+ "match_threshold": 0.9,
+ "residual_max": 0.25
+ },
+ "generator": {
+ "script": "bench/corpus/generate.py",
+ "args": [
+ "--clip",
+ "webcam_overlay"
+ ]
+ }
+ },
+ {
+ "name": "busy_ui_60fps",
+ "file": "busy_ui_60fps.mkv",
+ "width": 1920,
+ "height": 1080,
+ "fps": 60,
+ "frames": 1200,
+ "duration_s": 20.0,
+ "sha256": "1c4715bf397d2b9bb41346b636016dfa626155c5216307f2115cf4a403907a8f",
+ "tags": [
+ "ui",
+ "pointer",
+ "60fps",
+ "menus",
+ "drag",
+ "light"
+ ],
+ "description": "busy_ui scenario variant at 60 fps: continuous curved pointer motion and hovers, filter and card menus, a card drag with toast, column wheel scroll.",
+ "device_scale_factor": 1,
+ "page": "pages/board.html",
+ "text_regions": [
+ [
+ 4,
+ 60,
+ 236,
+ 560
+ ],
+ [
+ 268,
+ 152,
+ 304,
+ 600
+ ],
+ [
+ 900,
+ 152,
+ 304,
+ 600
+ ]
+ ],
+ "sideinfo": "busy_ui_60fps.sideinfo.jsonl",
+ "events": "busy_ui_60fps.events.jsonl",
+ "pointer_samples": "busy_ui_60fps.pointer.jsonl",
+ "capture_log": "busy_ui_60fps.capture.json",
+ "previews": [
+ "previews/busy_ui_60fps_f00000.png",
+ "previews/busy_ui_60fps_f00400.png",
+ "previews/busy_ui_60fps_f00730.png",
+ "previews/busy_ui_60fps_f00800.png",
+ "previews/busy_ui_60fps_f01199.png",
+ "previews/busy_ui_60fps_sheet.png"
+ ],
+ "avg_dirty_fraction": 0.006611,
+ "identical_frames": 534,
+ "cursor_check": {
+ "frames_with_cursor": 1200,
+ "moved_frames": 596,
+ "moved_frames_with_dirty_hotspot_tile_at_old_and_new_pos": 567,
+ "fraction": 0.9513,
+ "sample_offset_ms": 2,
+ "fraction_at_zero_offset": 0.9433,
+ "grab_latency_ms": 0.988,
+ "method": "latest 240 Hz query_pointer sample at or before frame wallclock + sample_offset_ms; offset fitted in [-12, 12] ms (1 ms steps) to maximise frames whose hotspot tile is dirty at both the previous and the new position"
+ },
+ "capture": {
+ "codec": "libx264rgb qp0 (lossless H.264 High 4:4:4 Predictive, GBR), ultrafast, keyint 300",
+ "dropped_frames": 0,
+ "duplicated_frames": 0,
+ "ffmpeg_drop_frames": 0,
+ "ffmpeg_dup_frames": 0,
+ "late_grabs": 0,
+ "max_interval_ms": 17.682,
+ "interval_stdev_ms": 0.348,
+ "method": "ffmpeg x11grab -framerate 60 -draw_mouse 1 -use_wallclock_as_timestamps 1 on Xvfb :99 (1920x1080x24), -fps_mode passthrough, encoder time base = demuxer (us); per-frame wallclock from -stats_enc_pre; remuxed with setts to CFR pts n/fps; Chrome kiosk, --force-device-scale-factor=1"
+ },
+ "scroll_validation": {
+ "frames_with_scroll": 31,
+ "unverifiable_frames": 0,
+ "validated_frames": 31,
+ "fraction": 1.0,
+ "entries": 31,
+ "valid_entries": 31,
+ "unverifiable_entries": 0,
+ "align_counts": {
+ "latency": 27,
+ "realigned": 4,
+ "held": 0,
+ "invalid": 0,
+ "unverifiable": 0
+ },
+ "latency_ms": 24,
+ "latency_frames": 1.44,
+ "latency_only": {
+ "frames_with_scroll": 34,
+ "validated_frames": 27,
+ "fraction": 0.7941,
+ "score_at_chosen_latency": [
+ 20,
+ 27,
+ 7
+ ],
+ "score_at_zero_latency": [
+ -29,
+ 1,
+ 30
+ ]
+ },
+ "match_threshold": 0.9,
+ "residual_max": 0.25
+ },
+ "generator": {
+ "script": "bench/corpus/generate.py",
+ "args": [
+ "--clip",
+ "busy_ui_60fps"
+ ]
+ }
+ },
+ {
+ "name": "code_4k",
+ "file": "code_4k.mkv",
+ "width": 3840,
+ "height": 2160,
+ "fps": 30,
+ "frames": 600,
+ "duration_s": 20.0,
+ "sha256": "99410a781263162a5a8755668b6d159bc1b54500fd341c05f9c30e25d3af00ce",
+ "tags": [
+ "code",
+ "4k",
+ "hidpi",
+ "typing",
+ "scroll",
+ "monospace"
+ ],
+ "description": "3840x2160 (device scale factor 2) VS Code Light+ on difflib.py: types a short function, saves, wheel scroll, PageDown, caret moves.",
+ "device_scale_factor": 2,
+ "page": "pages/code.html",
+ "text_regions": [
+ [
+ 620,
+ 182,
+ 1440,
+ 962
+ ],
+ [
+ 620,
+ 1144,
+ 1440,
+ 962
+ ]
+ ],
+ "sideinfo": "code_4k.sideinfo.jsonl",
+ "events": "code_4k.events.jsonl",
+ "pointer_samples": "code_4k.pointer.jsonl",
+ "capture_log": "code_4k.capture.json",
+ "previews": [
+ "previews/code_4k_f00000.png",
+ "previews/code_4k_f00200.png",
+ "previews/code_4k_f00400.png",
+ "previews/code_4k_f00433.png",
+ "previews/code_4k_f00599.png",
+ "previews/code_4k_sheet.png"
+ ],
+ "avg_dirty_fraction": 0.005939,
+ "identical_frames": 393,
+ "cursor_check": {
+ "frames_with_cursor": 600,
+ "moved_frames": 67,
+ "moved_frames_with_dirty_hotspot_tile_at_old_and_new_pos": 67,
+ "fraction": 1.0,
+ "sample_offset_ms": 0,
+ "fraction_at_zero_offset": 1.0,
+ "grab_latency_ms": 2.24,
+ "method": "latest 240 Hz query_pointer sample at or before frame wallclock + sample_offset_ms; offset fitted in [-12, 12] ms (1 ms steps) to maximise frames whose hotspot tile is dirty at both the previous and the new position"
+ },
+ "capture": {
+ "codec": "libx264rgb qp0 (lossless H.264 High 4:4:4 Predictive, GBR), ultrafast, keyint 150",
+ "dropped_frames": 0,
+ "duplicated_frames": 0,
+ "ffmpeg_drop_frames": 0,
+ "ffmpeg_dup_frames": 0,
+ "late_grabs": 0,
+ "max_interval_ms": 40.322,
+ "interval_stdev_ms": 1.435,
+ "method": "ffmpeg x11grab -framerate 30 -draw_mouse 1 -use_wallclock_as_timestamps 1 on Xvfb :98 (3840x2160x24), -fps_mode passthrough, encoder time base = demuxer (us); per-frame wallclock from -stats_enc_pre; remuxed with setts to CFR pts n/fps; Chrome kiosk, --force-device-scale-factor=2"
+ },
+ "scroll_validation": {
+ "frames_with_scroll": 11,
+ "unverifiable_frames": 0,
+ "validated_frames": 11,
+ "fraction": 1.0,
+ "entries": 11,
+ "valid_entries": 11,
+ "unverifiable_entries": 0,
+ "align_counts": {
+ "latency": 11,
+ "realigned": 0,
+ "held": 1,
+ "invalid": 0,
+ "unverifiable": 0
+ },
+ "latency_ms": 14,
+ "latency_frames": 0.42,
+ "latency_only": {
+ "frames_with_scroll": 11,
+ "validated_frames": 10,
+ "fraction": 0.9091,
+ "score_at_chosen_latency": [
+ 9,
+ 10,
+ 1
+ ],
+ "score_at_zero_latency": [
+ 2,
+ 6,
+ 4
+ ]
+ },
+ "match_threshold": 0.9,
+ "residual_max": 0.25
+ },
+ "generator": {
+ "script": "bench/corpus/generate.py",
+ "args": [
+ "--clip",
+ "code_4k"
+ ]
+ }
+ },
+ {
+ "name": "full_motion",
+ "file": "full_motion.mkv",
+ "width": 1920,
+ "height": 1080,
+ "fps": 30,
+ "frames": 900,
+ "duration_s": 30.0,
+ "sha256": "de20d89fd2e78ec9a176e84b06263130342ad7a87074ced030252f4e28daa848",
+ "tags": [
+ "video",
+ "natural",
+ "full-motion",
+ "camera-motion",
+ "fine-detail",
+ "worst-case"
+ ],
+ "description": "Natural video full screen (worst case for a screen encoder): Big Buck Bunny 1080p30 (Blender Foundation, CC BY 3.0) played by Chrome in a <video> filling the viewport (object-fit: cover, autoplay muted loop, no controls), source 27.47-57.43 s from a shot cut: slow camera push-in on the burrow under the tree with wind-blown grass and foliage, the dark burrow close-up as the bunny emerges, the bunny stretching in the sunlit meadow. No input; pointer parked bottom-right, hidden (cursor: none, -draw_mouse 0).",
+ "device_scale_factor": 1,
+ "page": "pages/video.html",
+ "text_regions": [],
+ "sideinfo": "full_motion.sideinfo.jsonl",
+ "events": "full_motion.events.jsonl",
+ "pointer_samples": "full_motion.pointer.jsonl",
+ "capture_log": "full_motion.capture.json",
+ "previews": [
+ "previews/full_motion_f00000.png",
+ "previews/full_motion_f00250.png",
+ "previews/full_motion_f00300.png",
+ "previews/full_motion_f00600.png",
+ "previews/full_motion_f00899.png",
+ "previews/full_motion_sheet.png"
+ ],
+ "avg_dirty_fraction": 0.949286,
+ "identical_frames": 0,
+ "cursor_check": {
+ "frames_with_cursor": 0,
+ "moved_frames": 0,
+ "moved_frames_with_dirty_hotspot_tile_at_old_and_new_pos": 0,
+ "fraction": null,
+ "sample_offset_ms": 0,
+ "fraction_at_zero_offset": null,
+ "grab_latency_ms": 0.969,
+ "method": "latest 240 Hz query_pointer sample at or before frame wallclock + sample_offset_ms; offset fitted in [-12, 12] ms (1 ms steps) to maximise frames whose hotspot tile is dirty at both the previous and the new position"
+ },
+ "capture": {
+ "codec": "libx264rgb qp0 (lossless H.264 High 4:4:4 Predictive, GBR), ultrafast, keyint 150",
+ "dropped_frames": 0,
+ "duplicated_frames": 0,
+ "ffmpeg_drop_frames": 0,
+ "ffmpeg_dup_frames": 0,
+ "late_grabs": 0,
+ "max_interval_ms": 35.314,
+ "interval_stdev_ms": 0.241,
+ "method": "ffmpeg x11grab -framerate 30 -draw_mouse 0 -use_wallclock_as_timestamps 1 on Xvfb :99 (1920x1080x24), -fps_mode passthrough, encoder time base = demuxer (us); per-frame wallclock from -stats_enc_pre; remuxed with setts to CFR pts n/fps; Chrome kiosk, --force-device-scale-factor=1; ffmpeg relaunched until its grab grid sat 25.0 +- 4.5 ms after Chrome's video presentation phase (requestVideoFrameCallback expectedDisplayTime), started before the cut and trimmed bit-exactly to the first frame showing it",
+ "phase_lock": {
+ "attempts": 5,
+ "accepted_delta_ms": -0.919,
+ "playback_restarts": 0
+ },
+ "trim": {
+ "raw_frames": 1149,
+ "first_raw_frame": 202,
+ "rvfc_predicted_raw_frame": 202,
+ "verified_bit_exact": true
+ },
+ "runs": {
+ "runs": 2,
+ "max_runs": 3,
+ "policy": "recapture while the playback check shows repeated/skipped source frames or dropped grabs",
+ "rejected": [
+ {
+ "repeated_frames": 1,
+ "skipped_source_frames": 1,
+ "irregular_steps": [
+ {
+ "frame": 491,
+ "source_step": 2
+ },
+ {
+ "frame": 492,
+ "source_step": 0
+ }
+ ],
+ "identical_frames": 1,
+ "dropped_frames": 0,
+ "phase_lock_delta_ms": 4.211,
+ "chrome_dropped": 0
+ }
+ ]
+ }
+ },
+ "scroll_validation": {
+ "frames_with_scroll": 0,
+ "unverifiable_frames": 0,
+ "validated_frames": 0,
+ "fraction": null,
+ "entries": 0,
+ "valid_entries": 0,
+ "unverifiable_entries": 0,
+ "align_counts": {
+ "latency": 0,
+ "realigned": 0,
+ "held": 0,
+ "invalid": 0,
+ "unverifiable": 0
+ },
+ "latency_ms": null,
+ "latency_frames": null,
+ "latency_only": {
+ "frames_with_scroll": 0,
+ "validated_frames": 0,
+ "fraction": null,
+ "score_at_chosen_latency": null,
+ "score_at_zero_latency": null
+ },
+ "match_threshold": 0.9,
+ "residual_max": 0.25
+ },
+ "generator": {
+ "script": "bench/corpus/generate.py",
+ "args": [
+ "--clip",
+ "full_motion"
+ ]
+ },
+ "source_video": {
+ "title": "Big Buck Bunny (2013 'sunflower' edition, 1920x1080, 30 fps, H.264 High, ~3 Mbit/s)",
+ "url": "https://download.blender.org/demo/movies/BBB/bbb_sunflower_1080p_30fps_normal.mp4.zip",
+ "homepage": "https://peach.blender.org/",
+ "licence": "CC BY 3.0",
+ "licence_url": "https://creativecommons.org/licenses/by/3.0/",
+ "attribution": "Big Buck Bunny, (c) copyright 2008, Blender Foundation / www.bigbuckbunny.org",
+ "zip_sha256": "e320fef389ec749117d0c1583945039266a40f25483881c2ff0d33207e62b362",
+ "sha256": "ae51005850b0ff757fe60c3dd7a12d754d3cd2397d87d939b55235e457f97658",
+ "cache_dir": "/home/ubuntu/work/cache/capcodec-corpus",
+ "segment": {
+ "file": "bbb_sunflower_1080p_30fps_normal_from16.300s_1325f.mp4",
+ "sha256": "2f8170a7d990bb5f28c712091764bded2dec247f21b12e5c8dd7424848c5be2a",
+ "start_s": 16.3,
+ "frames": 1325,
+ "source_first_frame_index": 487,
+ "method": "ffmpeg -ss START -i SOURCE -map 0:v:0 -c copy -an (starts on a keyframe; no re-encode); every decoded frame verified identical (framemd5) to the matching source frame"
+ },
+ "clip_source_range_s": [
+ 27.466667,
+ 57.433333
+ ],
+ "clip_segment_frames": [
+ 335,
+ 1234
+ ],
+ "transcoded": false,
+ "playback": "Chrome <video> (software H.264 decode of the original stream), muted, loop, object-fit: cover, 1:1 pixels at 1920x1080"
+ },
+ "playback_check": {
+ "frames": 900,
+ "source_first": 335,
+ "source_last": 1234,
+ "source_steps": {
+ "1": 899
+ },
+ "repeated_frames": 0,
+ "skipped_source_frames": 0,
+ "backward_steps": 0,
+ "irregular_steps": [],
+ "match_distance": {
+ "median": 0.0006,
+ "p99": 0.0009,
+ "max": 0.0009
+ },
+ "next_best_distance_ratio": {
+ "min": 1.114,
+ "p01": 2.918,
+ "median": 20.976
+ },
+ "frames_with_next_best_ratio_below_2": 2,
+ "source_first_expected": 335,
+ "source_last_expected": 1234,
+ "chrome_presentation": {
+ "callbacks": 900,
+ "media_time_steps_frames": {
+ "1": 899
+ },
+ "presented_frames_steps": {
+ "1": 899
+ },
+ "expected_display_interval_vsyncs": {
+ "2": 899
+ },
+ "expected_display_interval_ms": {
+ "mean": 33.3319,
+ "stdev": 0.058
+ }
+ },
+ "chrome_video_quality": {
+ "samples_during_clip": 7,
+ "dropped_during_clip": 0,
+ "decoded_during_clip": 858,
+ "dropped_total_at_end": 0,
+ "decoded_total_at_end": 1289
+ },
+ "dirty_fraction_per_frame": {
+ "min": 0.085556,
+ "p01": 0.663677,
+ "p05": 0.825179,
+ "median": 0.972346,
+ "frames_ge_0_99": 360,
+ "frames_ge_0_95": 580,
+ "frames_ge_0_90": 763,
+ "frames_lt_0_50": 4,
+ "frames_considered": 899
+ },
+ "dirty_vs_source": {
+ "frames_compared": 899,
+ "source_mean": 0.94935,
+ "captured_mean": 0.949286,
+ "mean_abs_diff": 6.4e-05,
+ "max_abs_diff": 0.001111,
+ "correlation": 0.999998
+ },
+ "method": "captured and source frames area-downscaled to 480x270 luma, high-passed and normalised (playback.py); each captured frame matched to a source frame by 1 - normalised cross-correlation along a monotonic Viterbi path (offset band +-6, 0.004 per offset change); repeated_frames and skipped_source_frames count source steps of 0 and >1 between consecutive captured frames"
+ },
+ "playback": "full_motion.playback.json"
+ }
+ ],
+ "corpus_dir": "/home/ubuntu/work/corpus",
+ "lossless_check": {
+ "method": "single x11grab input -> (a) rawvideo NUT and (b) libx264rgb -preset ultrafast -qp 0 in one ffmpeg run; framemd5 of both decoded to bgr0 compared frame by frame",
+ "results": [
+ {
+ "resolution": "1920x1080",
+ "fps": 30,
+ "frames_compared": 90,
+ "frames_identical": 90,
+ "distinct_frames": 90,
+ "lossless": true
+ },
+ {
+ "resolution": "3840x2160",
+ "fps": 30,
+ "frames_compared": 90,
+ "frames_identical": 90,
+ "distinct_frames": 89,
+ "lossless": true
+ }
+ ],
+ "lossless": true,
+ "checked_at": "2026-10-07T05:27:27+0000"
+ }
+}
diff --git a/capcodec/bench/corpus/pages/article.html b/capcodec/bench/corpus/pages/article.html
new file mode 100644
index 000000000..7ebe0bec7
--- /dev/null
+++ b/capcodec/bench/corpus/pages/article.html
@@ -0,0 +1,96 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Typewriter - Wikipedia</title>
+<link rel="stylesheet" href="common/wiki.css">
+<script src="common/cap.js"></script>
+</head>
+<body>
+<svg width="0" height="0" style="position:absolute">
+ <defs>
+ <filter id="grain" x="0" y="0" width="100%" height="100%">
+ <feTurbulence type="fractalNoise" baseFrequency="0.9" numOctaves="2" seed="4" result="n"/>
+ <feColorMatrix in="n" type="matrix" values="0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 0.55 0" result="g"/>
+ <feComposite in="g" in2="SourceGraphic" operator="in" result="gi"/>
+ <feBlend in="SourceGraphic" in2="gi" mode="overlay"/>
+ </filter>
+ <filter id="soft"><feGaussianBlur stdDeviation="1.2"/></filter>
+ <linearGradient id="metal" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#4a4a4a"/><stop offset="0.45" stop-color="#1d1d1d"/><stop offset="1" stop-color="#0c0c0c"/></linearGradient>
+ <linearGradient id="platen" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#555"/><stop offset="0.5" stop-color="#111"/><stop offset="1" stop-color="#333"/></linearGradient>
+ <radialGradient id="key" cx="0.4" cy="0.35" r="0.7"><stop offset="0" stop-color="#f4f1e8"/><stop offset="0.7" stop-color="#cfc9b8"/><stop offset="1" stop-color="#6d6758"/></radialGradient>
+ <radialGradient id="vign" cx="0.5" cy="0.45" r="0.75"><stop offset="0.55" stop-color="#000" stop-opacity="0"/><stop offset="1" stop-color="#000" stop-opacity="0.55"/></radialGradient>
+ <linearGradient id="desk" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#7a4b2a"/><stop offset="0.5" stop-color="#5b3519"/><stop offset="1" stop-color="#3b220f"/></linearGradient>
+ <linearGradient id="wall" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#d9cbb0"/><stop offset="1" stop-color="#b9a685"/></linearGradient>
+ <linearGradient id="sepia" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#e7d8b8"/><stop offset="1" stop-color="#a88d63"/></linearGradient>
+ </defs>
+</svg>
+<header id="hdr">
+ <div class="hl">
+ <span class="burger">☰</span>
+ <span class="logo"><svg viewBox="0 0 50 50" width="50" height="50"><circle cx="25" cy="25" r="22" fill="url(#key)" stroke="#888" stroke-width="1"/><path d="M8 18q17-8 34 0M5 27q20-6 40 0M9 36q16 6 32 0M25 3v44M15 6q-6 19 0 38M35 6q6 19 0 38" stroke="#555" stroke-width="1.1" fill="none"/><text x="25" y="31" text-anchor="middle" font-family="Liberation Serif" font-size="15" fill="#222">W</text></svg>
+ <span class="wm"><span class="wm1">Wikipedia</span><span class="wm2">The Free Encyclopedia</span></span></span>
+ </div>
+ <div class="search"><span class="sbox"><svg viewBox="0 0 20 20" width="18" height="18"><circle cx="8" cy="8" r="5.5" stroke="#202122" stroke-width="2" fill="none"/><path d="M12 12l5 5" stroke="#202122" stroke-width="2"/></svg><span class="ph">Search Wikipedia</span></span><span class="sbtn">Search</span></div>
+ <div class="hr"><span>Donate</span><span>Create account</span><span>Log in</span><span class="dots">⋯</span></div>
+</header>
+<div id="container">
+ <nav id="toc">
+ <div class="toch">Contents <span class="hide">hide</span></div>
+ <ol id="toclist"></ol>
+ </nav>
+ <main id="main">
+ <div class="titlebar">
+ <h1 id="firstHeading">Typewriter</h1>
+ <span class="lang">文A 96 languages ⌄</span>
+ </div>
+ <div class="tabs">
+ <span class="tab sel">Article</span><span class="tab">Talk</span>
+ <span class="sp"></span>
+ <span class="tab sel">Read</span><span class="tab">Edit</span><span class="tab">View history</span><span class="tab">Tools ⌄</span>
+ </div>
+ <div id="content">
+ <div class="from">From Wikipedia, the free encyclopedia</div>
+ <div class="hatnote">This article is about the mechanical or electromechanical writing machine. For other uses, see <a>Typewriter (disambiguation)</a>.</div>
+ <table class="infobox">
+ <tr><th colspan="2" class="ibt">Typewriter</th></tr>
+ <tr><td colspan="2" class="ibimg"><svg viewBox="0 0 280 200" width="280" height="200" filter="url(#grain)">
+ <rect width="280" height="200" fill="url(#wall)"/>
+ <rect y="150" width="280" height="50" fill="url(#desk)"/>
+ <rect x="88" y="18" width="104" height="70" fill="#f6f3ea" transform="skewX(-4)"/>
+ <path d="M100 30h70M100 38h66M100 46h72M100 54h40" stroke="#555" stroke-width="1.5" opacity=".6"/>
+ <rect x="52" y="74" width="176" height="22" rx="11" fill="url(#platen)"/>
+ <circle cx="46" cy="85" r="9" fill="#222"/><circle cx="234" cy="85" r="9" fill="#222"/>
+ <path d="M44 96h192l26 64H18z" fill="url(#metal)"/>
+ <path d="M90 98q50-20 100 0" fill="none" stroke="#bfae7a" stroke-width="2"/>
+ <g id="keys"></g>
+ <rect x="18" y="160" width="244" height="8" fill="#0a0a0a"/>
+ <rect width="280" height="200" fill="url(#vign)"/>
+ </svg></td></tr>
+ <tr><td colspan="2" class="ibcap">An Underwood No. 5 typewriter from the 1920s, one of the best-selling models of its era</td></tr>
+ <tr><th>Classification</th><td>Writing machine</td></tr>
+ <tr><th>Industry</th><td>Office equipment</td></tr>
+ <tr><th>Inventor</th><td><a>Christopher Latham Sholes</a>, <a>Carlos Glidden</a>, <a>Samuel W. Soule</a></td></tr>
+ <tr><th>Invented</th><td>1868 (patented)</td></tr>
+ <tr><th>Manufacturer</th><td><a>E. Remington and Sons</a> (first commercial model)</td></tr>
+ <tr><th>Peak production</th><td>c. 1920–1975</td></tr>
+ <tr><th>Successor</th><td><a>Word processor</a>, <a>personal computer</a></td></tr>
+ </table>
+ <div id="article"></div>
+ </div>
+ </main>
+ <aside id="tools">
+ <div class="th">Appearance <span class="hide">hide</span></div>
+ <div class="tg"><div class="tl">Text</div><label><span class="rb"></span>Small</label><label><span class="rb on"></span>Standard</label><label><span class="rb"></span>Large</label></div>
+ <div class="tg"><div class="tl">Width</div><label><span class="rb on"></span>Standard</label><label><span class="rb"></span>Wide</label></div>
+ <div class="tg"><div class="tl">Color <span class="beta">(beta)</span></div><label><span class="rb on"></span>Automatic</label><label><span class="rb"></span>Light</label><label><span class="rb"></span>Dark</label></div>
+ </aside>
+</div>
+<div id="preview"></div>
+<script src="data/article_text.js"></script>
+<script src="common/wiki.js"></script>
+<script>
+capSetReady();
+</script>
+</body>
+</html>
diff --git a/capcodec/bench/corpus/pages/board.html b/capcodec/bench/corpus/pages/board.html
new file mode 100644
index 000000000..ae36dc00c
--- /dev/null
+++ b/capcodec/bench/corpus/pages/board.html
@@ -0,0 +1,28 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Sprint 42 · Capture – Board</title>
+<link rel="stylesheet" href="common/board.css">
+<script src="common/cap.js"></script>
+</head>
+<body>
+<div id="app">
+ <aside id="side"></aside>
+ <section id="mainpane">
+ <header id="topbar"></header>
+ <div id="filters"></div>
+ <div id="board" data-scroll-id="board"></div>
+ </section>
+ <aside id="details"></aside>
+</div>
+<div id="tooltip"></div>
+<div id="menu"></div>
+<div id="toast"></div>
+<script src="data/board_data.js"></script>
+<script src="common/board.js"></script>
+<script>
+capSetReady();
+</script>
+</body>
+</html>
diff --git a/capcodec/bench/corpus/pages/code.html b/capcodec/bench/corpus/pages/code.html
new file mode 100644
index 000000000..c706082e1
--- /dev/null
+++ b/capcodec/bench/corpus/pages/code.html
@@ -0,0 +1,75 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>difflib.py - textkit - Visual Studio Code</title>
+<link rel="stylesheet" href="common/workbench.css">
+<script src="common/cap.js"></script>
+<script src="common/editor.js"></script>
+<script src="common/workbench.js"></script>
+<script src="data/difflib_py.js"></script>
+</head>
+<body>
+<script>
+const editor = buildWorkbench({
+ theme: "light",
+ project: "textkit",
+ branch: "feat/ratio-normalize*",
+ scmCount: 3,
+ warnings: 2,
+ lang: "py",
+ langLabel: "Python",
+ interp: "3.12.3 ('.venv': venv)",
+ source: window.SOURCE_DIFFLIB_PY,
+ minimapColors: MINIMAP_LIGHT,
+ crumbs: ["src", "textkit", "difflib.py", "_calculate_ratio"],
+ tabs: [
+ { name: "difflib.py", active: true },
+ { name: "test_difflib.py" },
+ { name: "README.md", preview: true },
+ { name: "pyproject.toml" },
+ ],
+ tree: [
+ { depth: 0, dir: true, name: ".github" },
+ { depth: 0, dir: true, name: ".venv" },
+ { depth: 0, dir: true, name: "docs" },
+ { depth: 0, dir: true, open: true, name: "src", gs: "M" },
+ { depth: 1, dir: true, open: true, name: "textkit", gs: "M" },
+ { depth: 2, name: "__init__.py" },
+ { depth: 2, name: "_compat.py" },
+ { depth: 2, name: "cli.py" },
+ { depth: 2, name: "difflib.py", active: true, gs: "M" },
+ { depth: 2, name: "fuzzy.py", gs: "M" },
+ { depth: 2, name: "html.py" },
+ { depth: 2, name: "normalize.py", gs: "U" },
+ { depth: 2, name: "py.typed" },
+ { depth: 2, name: "tokens.py" },
+ { depth: 0, dir: true, open: true, name: "tests" },
+ { depth: 1, name: "conftest.py" },
+ { depth: 1, name: "test_cli.py" },
+ { depth: 1, name: "test_difflib.py" },
+ { depth: 1, name: "test_fuzzy.py" },
+ { depth: 1, name: "test_html.py" },
+ { depth: 0, name: ".gitignore" },
+ { depth: 0, name: "CHANGELOG.md" },
+ { depth: 0, name: "LICENSE.txt" },
+ { depth: 0, name: "pyproject.toml" },
+ { depth: 0, name: "README.md" },
+ { depth: 0, name: "setup.cfg" },
+ { depth: 0, name: "tox.ini" },
+ { depth: 0, name: "uv.lock" },
+ ],
+});
+window.capEditor = editor;
+window.capTextRegions = () => {
+ const r = editor.scroller.getBoundingClientRect();
+ const h = Math.floor((r.height - 8) / 2);
+ return [
+ [r.left, r.top + 4, 720, h],
+ [r.left, r.top + 4 + h, 720, h],
+ ];
+};
+capSetReady();
+</script>
+</body>
+</html>
diff --git a/capcodec/bench/corpus/pages/common/board.css b/capcodec/bench/corpus/pages/common/board.css
new file mode 100644
index 000000000..c1e1d3419
--- /dev/null
+++ b/capcodec/bench/corpus/pages/common/board.css
@@ -0,0 +1,679 @@
+* {
+ box-sizing: border-box;
+}
+html,
+body {
+ margin: 0;
+ height: 100%;
+ overflow: hidden;
+ font-family: "Noto Sans", "Liberation Sans", sans-serif;
+ font-size: 13px;
+ color: #1f2328;
+ background: #fff;
+ user-select: none;
+ cursor: default;
+}
+svg.i {
+ width: 16px;
+ height: 16px;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.6;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+ flex: none;
+}
+#app {
+ display: flex;
+ height: 100vh;
+ position: relative;
+}
+#side {
+ width: 248px;
+ flex: none;
+ background: #f7f7f8;
+ border-right: 1px solid #e6e6e9;
+ display: flex;
+ flex-direction: column;
+ padding: 10px 8px;
+ color: #3c4049;
+}
+.ws {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 8px;
+ border-radius: 6px;
+ font-weight: 600;
+ font-size: 13.5px;
+}
+.ws .sq {
+ width: 22px;
+ height: 22px;
+ border-radius: 6px;
+ background: linear-gradient(135deg, #6366f1, #a855f7);
+ color: #fff;
+ font-size: 12px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+.ws .acts {
+ margin-left: auto;
+ display: flex;
+ gap: 4px;
+}
+.ibtn {
+ width: 28px;
+ height: 28px;
+ border-radius: 6px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: #5d6170;
+}
+.ibtn:hover {
+ background: #e9e9ec;
+ color: #1f2328;
+}
+.nav {
+ margin-top: 6px;
+}
+.ni {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ height: 30px;
+ padding: 0 8px;
+ border-radius: 6px;
+ font-size: 13px;
+ white-space: nowrap;
+}
+.ni:hover {
+ background: #ececef;
+}
+.ni.active {
+ background: #e6e6ea;
+ font-weight: 600;
+ color: #1f2328;
+}
+.ni .badge {
+ margin-left: auto;
+ font-size: 11px;
+ color: #5d6170;
+ background: #e3e3e8;
+ border-radius: 9px;
+ padding: 0 7px;
+ line-height: 18px;
+}
+.ni.sub {
+ padding-left: 34px;
+}
+.sec {
+ font-size: 11.5px;
+ color: #7c8090;
+ font-weight: 600;
+ padding: 16px 8px 6px;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+}
+.team {
+ width: 18px;
+ height: 18px;
+ border-radius: 5px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 11px;
+ color: #fff;
+}
+.side-bottom {
+ margin-top: auto;
+}
+#mainpane {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+}
+#topbar {
+ height: 52px;
+ flex: none;
+ display: flex;
+ align-items: center;
+ padding: 0 16px 0 20px;
+ gap: 10px;
+ border-bottom: 1px solid #ececef;
+}
+.crumb {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 14px;
+ font-weight: 600;
+}
+.crumb .dim {
+ color: #7c8090;
+ font-weight: 400;
+}
+.seg {
+ display: flex;
+ margin-left: 22px;
+ background: #f3f3f5;
+ border-radius: 8px;
+ padding: 3px;
+ gap: 2px;
+}
+.seg span {
+ padding: 4px 12px;
+ border-radius: 6px;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ color: #5d6170;
+ font-size: 13px;
+}
+.seg span:hover {
+ color: #1f2328;
+}
+.seg span.on {
+ background: #fff;
+ color: #1f2328;
+ box-shadow: 0 1px 2px #0000001f;
+ font-weight: 600;
+}
+.tr {
+ margin-left: auto;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+.avs {
+ display: flex;
+ margin-right: 6px;
+}
+.av {
+ width: 24px;
+ height: 24px;
+ border-radius: 50%;
+ color: #fff;
+ font-size: 10px;
+ font-weight: 700;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex: none;
+}
+.avs .av {
+ border: 2px solid #fff;
+ margin-left: -6px;
+ width: 28px;
+ height: 28px;
+}
+.btn {
+ height: 30px;
+ border-radius: 7px;
+ border: 1px solid #dfe0e4;
+ padding: 0 11px;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 13px;
+ background: #fff;
+ color: #30343c;
+ box-shadow: 0 1px 1px #0000000a;
+}
+.btn:hover {
+ background: #f5f5f7;
+ border-color: #cfd1d6;
+}
+.btn.on {
+ background: #eef0ff;
+ border-color: #c7caff;
+ color: #4338ca;
+}
+.btn.primary {
+ background: #5e5ce6;
+ border-color: #5452d6;
+ color: #fff;
+ font-weight: 600;
+}
+.btn.primary:hover {
+ background: #4f4dd8;
+}
+#filters {
+ height: 44px;
+ flex: none;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 0 20px;
+ border-bottom: 1px solid #ececef;
+}
+.fchip {
+ height: 26px;
+ border-radius: 6px;
+ border: 1px solid #e3e4e8;
+ display: flex;
+ align-items: center;
+ font-size: 12px;
+ overflow: hidden;
+}
+.fchip span {
+ padding: 0 8px;
+ height: 100%;
+ display: flex;
+ align-items: center;
+ gap: 5px;
+ border-right: 1px solid #e3e4e8;
+}
+.fchip span:last-child {
+ border-right: 0;
+}
+.fchip span:hover {
+ background: #f5f5f7;
+}
+.fchip .k {
+ color: #5d6170;
+}
+.addf {
+ color: #7c8090;
+ font-size: 12px;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 4px 8px;
+ border-radius: 6px;
+}
+.addf:hover {
+ background: #f3f3f5;
+ color: #30343c;
+}
+#filters .right {
+ margin-left: auto;
+ color: #7c8090;
+ font-size: 12px;
+ display: flex;
+ gap: 14px;
+ align-items: center;
+}
+#board {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ gap: 12px;
+ padding: 14px 20px 0;
+ overflow-x: auto;
+ overflow-y: hidden;
+ background: #fbfbfc;
+}
+#board::-webkit-scrollbar {
+ height: 10px;
+}
+#board::-webkit-scrollbar-thumb {
+ background: #d4d5da;
+ border-radius: 5px;
+ border: 2px solid #fbfbfc;
+}
+.col {
+ width: 304px;
+ flex: none;
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ background: #f4f4f6;
+ border-radius: 10px;
+}
+.colh {
+ height: 42px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 0 8px 0 12px;
+ font-weight: 600;
+ font-size: 13px;
+ flex: none;
+}
+.colh .cnt {
+ color: #7c8090;
+ font-weight: 400;
+}
+.colh .acts {
+ margin-left: auto;
+ display: flex;
+}
+.colh .ibtn {
+ width: 26px;
+ height: 26px;
+}
+.list {
+ flex: 1;
+ overflow-y: auto;
+ padding: 0 8px 12px;
+ min-height: 60px;
+}
+.list::-webkit-scrollbar {
+ width: 8px;
+}
+.list::-webkit-scrollbar-thumb {
+ background: #d4d5da;
+ border-radius: 4px;
+}
+.card {
+ background: #fff;
+ border: 1px solid #e4e5e9;
+ border-radius: 8px;
+ padding: 10px 11px 9px;
+ margin-bottom: 8px;
+ box-shadow: 0 1px 1px #0000000a;
+ position: relative;
+ transition: box-shadow 0.12s ease, border-color 0.12s ease;
+}
+.card:hover {
+ border-color: #cbcdd3;
+ box-shadow: 0 3px 10px #00000014;
+}
+.card .r1 {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 12px;
+ color: #7c8090;
+ height: 18px;
+}
+.card .r1 .av {
+ margin-left: auto;
+ width: 20px;
+ height: 20px;
+ font-size: 9px;
+}
+.card .more {
+ position: absolute;
+ right: 36px;
+ top: 7px;
+ width: 22px;
+ height: 22px;
+ border-radius: 5px;
+ display: none;
+ align-items: center;
+ justify-content: center;
+ color: #5d6170;
+ background: #fff;
+}
+.card:hover .more {
+ display: flex;
+}
+.card .more:hover {
+ background: #ececef;
+}
+.card .tt {
+ font-size: 13.5px;
+ line-height: 1.38;
+ margin: 5px 0 8px;
+ color: #1f2328;
+ font-weight: 500;
+}
+.card .r3 {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex-wrap: wrap;
+ font-size: 11.5px;
+ color: #5d6170;
+}
+.lab {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ border-radius: 9px;
+ padding: 0 7px;
+ line-height: 18px;
+ font-size: 11px;
+ font-weight: 600;
+}
+.lab::before {
+ content: "";
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: currentColor;
+}
+.meta {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ border: 1px solid #e4e5e9;
+ border-radius: 9px;
+ padding: 0 6px;
+ line-height: 17px;
+}
+.prio {
+ display: inline-flex;
+ gap: 1.5px;
+ align-items: flex-end;
+ height: 12px;
+ width: 14px;
+}
+.prio i {
+ width: 3px;
+ background: #c9cbd1;
+ border-radius: 1px;
+}
+.prio i.on {
+ background: #5d6170;
+}
+.prio.urgent {
+ background: #f97316;
+ border-radius: 3px;
+ color: #fff;
+ font-size: 10px;
+ font-weight: 800;
+ align-items: center;
+ justify-content: center;
+ width: 14px;
+ height: 14px;
+}
+.placeholder {
+ border: 2px dashed #b9bbff;
+ background: #eef0ff;
+ border-radius: 8px;
+ margin-bottom: 8px;
+}
+.ghost {
+ position: fixed;
+ pointer-events: none;
+ z-index: 100;
+ transform: rotate(2.5deg);
+ box-shadow: 0 16px 40px #0000002e, 0 2px 6px #0000001f !important;
+ border-color: #b9bbff !important;
+ margin: 0;
+}
+.list.over {
+ background: #ececf7;
+ border-radius: 0 0 10px 10px;
+}
+#details {
+ position: absolute;
+ right: 0;
+ top: 0;
+ bottom: 0;
+ width: 420px;
+ background: #fff;
+ border-left: 1px solid #e3e4e8;
+ box-shadow: -12px 0 32px #00000014;
+ transform: translateX(100%);
+ transition: transform 0.22s cubic-bezier(0.2, 0.7, 0.2, 1);
+ z-index: 20;
+ display: flex;
+ flex-direction: column;
+}
+#details.open {
+ transform: none;
+}
+#details .dh {
+ height: 52px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 0 12px 0 20px;
+ border-bottom: 1px solid #ececef;
+ color: #5d6170;
+ font-size: 13px;
+}
+#details .dh .acts {
+ margin-left: auto;
+ display: flex;
+ gap: 2px;
+}
+#details .db {
+ padding: 18px 20px;
+ overflow: hidden;
+}
+#details h3 {
+ font-size: 19px;
+ line-height: 1.35;
+ margin: 0 0 16px;
+}
+#details .prop {
+ display: flex;
+ align-items: center;
+ height: 34px;
+ font-size: 13px;
+ border-radius: 6px;
+ padding: 0 6px;
+ margin: 0 -6px;
+}
+#details .prop:hover {
+ background: #f5f5f7;
+}
+#details .prop .k {
+ width: 110px;
+ color: #7c8090;
+}
+#details .prop .v {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+}
+#details .desc {
+ font-size: 13.5px;
+ line-height: 1.6;
+ color: #30343c;
+ margin: 16px 0;
+ border-top: 1px solid #ececef;
+ padding-top: 14px;
+}
+#details .act {
+ display: flex;
+ gap: 10px;
+ font-size: 12.5px;
+ color: #5d6170;
+ margin-bottom: 12px;
+ line-height: 1.45;
+}
+#details .act b {
+ color: #1f2328;
+ font-weight: 600;
+}
+#tooltip {
+ position: fixed;
+ display: none;
+ background: #1f2023;
+ color: #f3f3f5;
+ font-size: 12px;
+ padding: 5px 9px;
+ border-radius: 6px;
+ z-index: 200;
+ white-space: nowrap;
+ box-shadow: 0 4px 14px #0000002e;
+ align-items: center;
+ gap: 8px;
+}
+#tooltip kbd {
+ font-family: "Noto Sans", sans-serif;
+ background: #3a3b40;
+ border-radius: 4px;
+ padding: 0 5px;
+ font-size: 11px;
+ line-height: 16px;
+}
+#menu {
+ position: fixed;
+ display: none;
+ min-width: 220px;
+ background: #fff;
+ border: 1px solid #e3e4e8;
+ border-radius: 10px;
+ box-shadow: 0 12px 32px #0000001f, 0 2px 6px #00000012;
+ padding: 5px;
+ z-index: 150;
+}
+#menu .mi {
+ height: 32px;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 0 10px;
+ border-radius: 6px;
+ font-size: 13px;
+ color: #30343c;
+}
+#menu .mi:hover {
+ background: #f1f1f4;
+ color: #1f2328;
+}
+#menu .mi .sc {
+ margin-left: auto;
+ color: #9a9eab;
+ font-size: 12px;
+}
+#menu .mi.danger {
+ color: #dc2626;
+}
+#menu .sep {
+ height: 1px;
+ background: #ececef;
+ margin: 5px 2px;
+}
+#menu .mh {
+ font-size: 11.5px;
+ color: #9a9eab;
+ padding: 6px 10px 4px;
+ font-weight: 600;
+}
+#menu .search {
+ height: 34px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 0 10px;
+ color: #9a9eab;
+ border-bottom: 1px solid #ececef;
+ margin: -5px -5px 5px;
+}
+#toast {
+ position: fixed;
+ left: 264px;
+ bottom: 20px;
+ background: #1f2023;
+ color: #fff;
+ border-radius: 10px;
+ padding: 11px 16px;
+ font-size: 13px;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ box-shadow: 0 10px 30px #00000033;
+ transform: translateY(140%);
+ transition: transform 0.25s cubic-bezier(0.2, 0.7, 0.2, 1);
+ z-index: 160;
+}
+#toast.show {
+ transform: none;
+}
+#toast .undo {
+ color: #a5b4fc;
+ font-weight: 600;
+ margin-left: 12px;
+}
diff --git a/capcodec/bench/corpus/pages/common/board.js b/capcodec/bench/corpus/pages/common/board.js
new file mode 100644
index 000000000..297bbf4b6
--- /dev/null
+++ b/capcodec/bench/corpus/pages/common/board.js
@@ -0,0 +1,354 @@
+(() => {
+ const D = window.BOARD;
+ const P = {
+ inbox: '<path d="M3 13l3-8h12l3 8v6H3z"/><path d="M3 13h5l1 3h6l1-3h5"/>',
+ user: '<circle cx="12" cy="8" r="4"/><path d="M4 21c1-4 4-6 8-6s7 2 8 6"/>',
+ review: '<circle cx="12" cy="12" r="3"/><path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12z"/>',
+ pulse: '<path d="M3 12h4l3-7 4 14 3-7h4"/>',
+ box: '<path d="M4 7l8-4 8 4v10l-8 4-8-4z"/><path d="M4 7l8 4 8-4M12 11v10"/>',
+ layers: '<path d="M12 3l9 5-9 5-9-5z"/><path d="M3 13l9 5 9-5"/>',
+ target: '<circle cx="12" cy="12" r="8"/><circle cx="12" cy="12" r="4"/>',
+ users: '<circle cx="9" cy="8" r="3.5"/><path d="M2.5 20c.8-3.5 3.3-5.5 6.5-5.5s5.7 2 6.5 5.5"/><path d="M16 4.5a3.5 3.5 0 0 1 0 7M18.5 14.5c1.6.8 2.6 2.7 3 5.5"/>',
+ issue: '<rect x="4" y="4" width="16" height="16" rx="4"/><path d="M9 12l2 2 4-4"/>',
+ cycle: '<path d="M20 12a8 8 0 1 1-3-6.2"/><path d="M20 4v5h-5"/>',
+ search: '<circle cx="11" cy="11" r="6.5"/><path d="M16 16l4.5 4.5"/>',
+ edit: '<path d="M4 20h4L19 9l-4-4L4 16z"/>',
+ star: '<path d="M12 4l2.5 5.2 5.7.8-4.1 4 1 5.6-5.1-2.7-5.1 2.7 1-5.6-4.1-4 5.7-.8z"/>',
+ chev: '<path d="M9 6l6 6-6 6"/>',
+ down: '<path d="M6 9l6 6 6-6"/>',
+ board: '<rect x="4" y="4" width="5" height="16" rx="1.5"/><rect x="10.5" y="4" width="5" height="11" rx="1.5"/><rect x="17" y="4" width="3" height="7" rx="1"/>',
+ list: '<path d="M8 6h12M8 12h12M8 18h12M4 6h.5M4 12h.5M4 18h.5"/>',
+ timeline: '<path d="M4 6h9M8 12h12M6 18h8"/>',
+ cal: '<rect x="4" y="5" width="16" height="15" rx="2"/><path d="M4 10h16M9 3v4M15 3v4"/>',
+ filter: '<path d="M4 6h16M7 12h10M10 18h4"/>',
+ display: '<path d="M4 7h10M18 7h2M4 17h4M12 17h8"/><circle cx="16" cy="7" r="2"/><circle cx="10" cy="17" r="2"/>',
+ plus: '<path d="M12 5v14M5 12h14"/>',
+ more: '<circle cx="6" cy="12" r="1.2"/><circle cx="12" cy="12" r="1.2"/><circle cx="18" cy="12" r="1.2"/>',
+ comment: '<path d="M5 5h14v10H9l-4 4z"/>',
+ subtask: '<path d="M6 4v10a3 3 0 0 0 3 3h9"/><path d="M15 14l3 3-3 3"/>',
+ date: '<rect x="4" y="5" width="16" height="15" rx="2"/><path d="M4 10h16"/>',
+ link: '<path d="M10 14a4 4 0 0 0 6 0l3-3a4 4 0 0 0-6-6l-1 1M14 10a4 4 0 0 0-6 0l-3 3a4 4 0 0 0 6 6l1-1"/>',
+ close: '<path d="M6 6l12 12M18 6L6 18"/>',
+ share: '<path d="M12 4v11M8 8l4-4 4 4M5 14v5h14v-5"/>',
+ help: '<circle cx="12" cy="12" r="8"/><path d="M9.5 9.5a2.5 2.5 0 1 1 3.5 2.3c-.7.3-1 .9-1 1.7M12 16.5v.5"/>',
+ bell: '<path d="M6 16V11a6 6 0 0 1 12 0v5l2 2H4z"/><path d="M10 20a2 2 0 0 0 4 0"/>',
+ trash: '<path d="M5 7h14M10 7V4h4v3M7 7l1 13h8l1-13"/>',
+ copy: '<rect x="8" y="8" width="12" height="12" rx="2"/><path d="M16 8V5a1 1 0 0 0-1-1H5a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h3"/>',
+ archive: '<rect x="3" y="4" width="18" height="5" rx="1"/><path d="M5 9v10h14V9M10 13h4"/>',
+ };
+ const ic = (n) => `<svg class="i" viewBox="0 0 24 24">${P[n] || ""}</svg>`;
+ const STATUS = {
+ backlog: '<svg class="i" viewBox="0 0 24 24" style="color:#9a9eab"><circle cx="12" cy="12" r="7.5" stroke-dasharray="3 2.6"/></svg>',
+ todo: '<svg class="i" viewBox="0 0 24 24" style="color:#9a9eab"><circle cx="12" cy="12" r="7.5"/></svg>',
+ progress: '<svg class="i" viewBox="0 0 24 24" style="color:#eab308"><circle cx="12" cy="12" r="7.5"/><path d="M12 7.5a4.5 4.5 0 0 1 0 9z" fill="#eab308" stroke="none"/></svg>',
+ review: '<svg class="i" viewBox="0 0 24 24" style="color:#22c55e"><circle cx="12" cy="12" r="7.5"/><path d="M12 7.5a4.5 4.5 0 1 1-4.5 4.5H12z" fill="#22c55e" stroke="none"/></svg>',
+ done: '<svg class="i" viewBox="0 0 24 24" style="color:#6366f1"><circle cx="12" cy="12" r="8" fill="#6366f1" stroke="none"/><path d="M8.5 12.2l2.4 2.4 4.6-4.8" stroke="#fff"/></svg>',
+ canceled: '<svg class="i" viewBox="0 0 24 24" style="color:#9a9eab"><circle cx="12" cy="12" r="8" fill="#b4b7c0" stroke="none"/><path d="M9.5 9.5l5 5M14.5 9.5l-5 5" stroke="#fff"/></svg>',
+ };
+ const av = (k, size) => {
+ if (!k) return `<span class="av" style="background:#fff;border:1.5px dashed #b4b7c0;color:#9a9eab${size ? `;width:${size}px;height:${size}px` : ""}"></span>`;
+ const [, c] = D.people[k];
+ return `<span class="av" style="background:${c}${size ? `;width:${size}px;height:${size}px` : ""}">${k}</span>`;
+ };
+ const prio = (p) => {
+ if (p === 4) return '<span class="prio urgent">!</span>';
+ if (p === 0) return '<span class="prio"><i style="height:2px"></i><i style="height:2px"></i><i style="height:2px"></i></span>';
+ return `<span class="prio"><i class="on" style="height:5px"></i><i class="${p >= 2 ? "on" : ""}" style="height:8px"></i><i class="${p >= 3 ? "on" : ""}" style="height:11px"></i></span>`;
+ };
+ const PRIO_NAMES = ["No priority", "Low", "Medium", "High", "Urgent"];
+
+ document.getElementById("side").innerHTML = `
+<div class="ws"><span class="sq">N</span>Northwind<span style="color:#9a9eab">${ic("down")}</span><span class="acts"><span class="ibtn" data-tip="Search" data-key="/">${ic("search")}</span><span class="ibtn" data-tip="New issue" data-key="C">${ic("edit")}</span></span></div>
+<div class="nav">
+<div class="ni" data-k="nav-inbox">${ic("inbox")}Inbox<span class="badge">4</span></div>
+<div class="ni" data-k="nav-my">${ic("user")}My issues</div>
+<div class="ni" data-k="nav-reviews">${ic("review")}Reviews<span class="badge">2</span></div>
+<div class="ni" data-k="nav-pulse">${ic("pulse")}Pulse</div>
+</div>
+<div class="sec">Workspace ${ic("down")}</div>
+<div class="ni" data-k="nav-projects">${ic("box")}Projects</div>
+<div class="ni" data-k="nav-views">${ic("layers")}Views</div>
+<div class="ni" data-k="nav-init">${ic("target")}Initiatives</div>
+<div class="ni" data-k="nav-teams">${ic("users")}Teams</div>
+<div class="sec">Your teams ${ic("down")}</div>
+<div class="ni" data-k="team-capture"><span class="team" style="background:#7c3aed">C</span>Capture<span style="margin-left:auto;color:#9a9eab">${ic("down")}</span></div>
+<div class="ni sub active" data-k="team-issues">${ic("issue")}Issues</div>
+<div class="ni sub" data-k="team-cycles">${ic("cycle")}Cycles</div>
+<div class="ni sub" data-k="team-projects">${ic("box")}Projects</div>
+<div class="ni sub" data-k="team-views">${ic("layers")}Views</div>
+<div class="ni" data-k="team-web"><span class="team" style="background:#0891b2">W</span>Web<span style="margin-left:auto;color:#9a9eab">${ic("chev")}</span></div>
+<div class="ni" data-k="team-infra"><span class="team" style="background:#db2777">I</span>Infra<span style="margin-left:auto;color:#9a9eab">${ic("chev")}</span></div>
+<div class="sec">Favorites ${ic("down")}</div>
+<div class="ni" data-k="fav-1">${ic("board")}Sprint 42 board</div>
+<div class="ni" data-k="fav-2">${ic("pulse")}Encoder performance</div>
+<div class="ni" data-k="fav-3">${ic("filter")}Bug triage</div>
+<div class="ni" data-k="fav-4">${ic("timeline")}Q4 roadmap</div>
+<div class="side-bottom"><div class="ni" data-k="nav-invite">${ic("plus")}Invite people</div><div class="ni" data-k="nav-help">${ic("help")}Help &amp; support</div></div>`;
+
+ document.getElementById("topbar").innerHTML = `
+<div class="crumb"><span class="team" style="background:#7c3aed">C</span><span class="dim">Capture</span><span class="dim">${ic("chev")}</span>Sprint 42<span class="ibtn" data-tip="Add to favorites" data-k="star">${ic("star")}</span></div>
+<div class="seg"><span class="on" data-k="view-board">${ic("board")}Board</span><span data-k="view-list">${ic("list")}List</span><span data-k="view-timeline">${ic("timeline")}Timeline</span><span data-k="view-cal">${ic("cal")}Calendar</span></div>
+<div class="tr">
+<div class="avs">${["ML", "MF", "PR", "DO"].map((k) => av(k)).join("")}<span class="av" style="background:#e5e6ea;color:#5d6170;border:2px solid #fff;margin-left:-6px;width:28px;height:28px">+4</span></div>
+<span class="btn" data-k="btn-filter" data-tip="Filter issues" data-key="F">${ic("filter")}Filter</span>
+<span class="btn" data-k="btn-display" data-tip="Display options" data-key="⇧ V">${ic("display")}Display</span>
+<span class="ibtn" data-k="btn-bell" data-tip="Notifications">${ic("bell")}</span>
+<span class="btn" data-k="btn-share">${ic("share")}Share</span>
+<span class="btn primary" data-k="btn-new" data-tip="Create new issue" data-key="C">${ic("plus")}New issue</span>
+</div>`;
+
+ document.getElementById("filters").innerHTML = `
+<span class="fchip"><span class="k">${ic("user")}Assignee</span><span>is any of</span><span>${av("MF", 16)}${av("PR", 16)} 3 people</span><span>${ic("close")}</span></span>
+<span class="fchip"><span class="k">${ic("layers")}Label</span><span>includes</span><span><span class="lab" style="color:#7c3aed;background:#f3e8ff">encoder</span></span><span>${ic("close")}</span></span>
+<span class="fchip"><span class="k">${ic("pulse")}Priority</span><span>is at least</span><span>Medium</span><span>${ic("close")}</span></span>
+<span class="addf" data-k="add-filter">${ic("plus")}Add filter</span>
+<span class="right"><span>Cycle 42 · Oct 6 – Oct 19</span><span>31 issues</span><span style="display:flex;align-items:center;gap:6px"><span style="width:90px;height:6px;border-radius:3px;background:#e5e6ea;overflow:hidden;display:inline-block"><span style="display:block;width:38%;height:100%;background:#6366f1"></span></span>38%</span></span>`;
+
+ const board = document.getElementById("board");
+ const cardEls = new Map();
+ function cardHTML(c) {
+ const [id, title, labels, who, p, due, sub, comments] = c;
+ const labs = labels
+ .map((l) => {
+ const [fg, bg] = D.labels[l];
+ return `<span class="lab" style="color:${fg};background:${bg}">${l}</span>`;
+ })
+ .join("");
+ return `<div class="r1">${prio(p)}<span>${id}</span>${av(who)}</div><span class="more" data-tip="More actions">${ic("more")}</span>
+<div class="tt">${title}</div>
+<div class="r3">${labs}${due ? `<span class="meta">${ic("date")}${due}</span>` : ""}${sub ? `<span class="meta">${ic("subtask")}${sub}</span>` : ""}${comments ? `<span class="meta">${ic("comment")}${comments}</span>` : ""}</div>`;
+ }
+ for (const col of D.columns) {
+ const el = document.createElement("div");
+ el.className = "col";
+ el.dataset.col = col.id;
+ el.innerHTML = `<div class="colh">${STATUS[col.icon]}<span>${col.name}</span><span class="cnt">${col.cards.length}</span><span class="acts"><span class="ibtn" data-tip="Add issue">${ic("plus")}</span><span class="ibtn" data-tip="Column options">${ic("more")}</span></span></div><div class="list" data-scroll-id="col-${col.id}"></div>`;
+ const list = el.querySelector(".list");
+ for (const c of col.cards) {
+ const ce = document.createElement("div");
+ ce.className = "card";
+ ce.dataset.id = c[0];
+ ce.innerHTML = cardHTML(c);
+ list.append(ce);
+ cardEls.set(c[0], { el: ce, data: c, col: col.id });
+ }
+ board.append(el);
+ }
+
+ function updateCounts() {
+ for (const col of board.querySelectorAll(".col")) col.querySelector(".cnt").textContent = col.querySelectorAll(".list .card").length;
+ }
+
+ const tooltip = document.getElementById("tooltip");
+ let tipTimer = null;
+ let tipFor = null;
+ document.addEventListener("mouseover", (e) => {
+ const t = e.target.closest("[data-tip]");
+ if (t === tipFor) return;
+ clearTimeout(tipTimer);
+ tooltip.style.display = "none";
+ tipFor = t;
+ if (!t || dragging) return;
+ tipTimer = setTimeout(() => {
+ const r = t.getBoundingClientRect();
+ tooltip.innerHTML = `${t.dataset.tip}${t.dataset.key ? `<kbd>${t.dataset.key}</kbd>` : ""}`;
+ tooltip.style.display = "flex";
+ const w = tooltip.offsetWidth;
+ tooltip.style.left = `${Math.round(Math.min(innerWidth - w - 8, Math.max(8, r.left + r.width / 2 - w / 2)))}px`;
+ tooltip.style.top = `${Math.round(r.bottom + 8)}px`;
+ cap.event("tooltip", { tip: t.dataset.tip });
+ }, 480);
+ });
+
+ const menu = document.getElementById("menu");
+ let menuOpen = false;
+ const MENUS = {
+ filter: `<div class="search">${ic("search")}Filter…</div><div class="mi">${STATUS.todo}Status<span class="sc">S</span></div><div class="mi">${ic("user")}Assignee<span class="sc">A</span></div><div class="mi">${ic("user")}Creator</div><div class="mi">${ic("pulse")}Priority<span class="sc">P</span></div><div class="mi">${ic("layers")}Labels<span class="sc">L</span></div><div class="mi">${ic("box")}Project</div><div class="mi">${ic("cycle")}Cycle</div><div class="mi">${ic("date")}Due date</div><div class="sep"></div><div class="mi">${ic("target")}Estimate</div><div class="mi">${ic("link")}Links</div>`,
+ display: `<div class="mh">Grouping</div><div class="mi">${ic("board")}Status<span class="sc">✓</span></div><div class="mi">${ic("user")}Assignee</div><div class="mi">${ic("pulse")}Priority</div><div class="sep"></div><div class="mh">Ordering</div><div class="mi">${ic("filter")}Manual<span class="sc">✓</span></div><div class="mi">${ic("date")}Due date</div><div class="mi">${ic("cycle")}Last updated</div><div class="sep"></div><div class="mi">Show sub-issues<span class="sc">On</span></div><div class="mi">Show empty columns<span class="sc">Off</span></div>`,
+ card: `<div class="mi">${ic("review")}Open<span class="sc">↵</span></div><div class="mi">${ic("link")}Copy link<span class="sc">⌘ L</span></div><div class="mi">${ic("copy")}Copy ID<span class="sc">⌘ .</span></div><div class="sep"></div><div class="mi">${STATUS.progress}Status<span class="sc">›</span></div><div class="mi">${ic("user")}Assignee<span class="sc">›</span></div><div class="mi">${ic("pulse")}Priority<span class="sc">›</span></div><div class="mi">${ic("layers")}Labels<span class="sc">›</span></div><div class="sep"></div><div class="mi">${ic("archive")}Archive</div><div class="mi danger">${ic("trash")}Delete<span class="sc">⌘ ⌫</span></div>`,
+ };
+ function openMenu(kind, anchor) {
+ const r = anchor.getBoundingClientRect();
+ menu.innerHTML = MENUS[kind];
+ menu.style.display = "block";
+ const w = menu.offsetWidth;
+ menu.style.left = `${Math.round(Math.min(innerWidth - w - 8, r.left))}px`;
+ menu.style.top = `${Math.round(r.bottom + 6)}px`;
+ menuOpen = true;
+ cap.event("menu_open", { kind });
+ }
+ function closeMenu() {
+ if (!menuOpen) return;
+ menu.style.display = "none";
+ menuOpen = false;
+ cap.event("menu_close");
+ }
+
+ const details = document.getElementById("details");
+ function openDetails(id) {
+ const { data, col } = cardEls.get(id);
+ const [cid, title, labels, who, p, due, sub, comments] = data;
+ const colDef = D.columns.find((c) => c.id === col);
+ details.innerHTML = `<div class="dh">${STATUS[colDef.icon]}<span>${cid}</span><span class="acts"><span class="ibtn" data-tip="Copy link">${ic("link")}</span><span class="ibtn" data-tip="More">${ic("more")}</span><span class="ibtn" data-k="details-close" data-tip="Close" data-key="Esc">${ic("close")}</span></span></div>
+<div class="db"><h3>${title}</h3>
+<div class="prop"><span class="k">Status</span><span class="v">${STATUS[colDef.icon]}${colDef.name}</span></div>
+<div class="prop"><span class="k">Priority</span><span class="v">${prio(p)}${PRIO_NAMES[p]}</span></div>
+<div class="prop"><span class="k">Assignee</span><span class="v">${av(who, 20)}${who ? D.people[who][0] : "Unassigned"}</span></div>
+<div class="prop"><span class="k">Labels</span><span class="v">${labels.map((l) => `<span class="lab" style="color:${D.labels[l][0]};background:${D.labels[l][1]}">${l}</span>`).join("")}</span></div>
+<div class="prop"><span class="k">Cycle</span><span class="v">${ic("cycle")}Cycle 42</span></div>
+<div class="prop"><span class="k">Due date</span><span class="v">${ic("date")}${due || "No due date"}</span></div>
+<div class="prop"><span class="k">Sub-issues</span><span class="v">${ic("subtask")}${sub || "None"}</span></div>
+<div class="desc">We see this on roughly 3% of sessions according to the telemetry dashboard. The first step is to reproduce it reliably on the test machines, then capture a trace with the frame pool counters enabled so we can tell whether the problem is in capture, conversion or upload.</div>
+<div class="act">${av("MF", 22)}<div><b>Marcus Feld</b> moved this from Todo to In Progress · 2 days ago</div></div>
+<div class="act">${av("PR", 22)}<div><b>Priya Raman</b> commented: Could we gate this behind the new encoder flag first? · yesterday</div></div>
+<div class="act">${av("DO", 22)}<div><b>Daniel Okafor</b> added the label ${labels[0]} · 5 hours ago</div></div>
+<div class="act" style="color:#9a9eab">${ic("comment")}<div>${comments} comments · Leave a comment…</div></div></div>`;
+ details.classList.add("open");
+ cap.event("details_open", { id });
+ }
+ function closeDetails() {
+ if (!details.classList.contains("open")) return;
+ details.classList.remove("open");
+ cap.event("details_close");
+ }
+
+ const toast = document.getElementById("toast");
+ let toastTimer = null;
+ function showToast(html) {
+ toast.innerHTML = html;
+ toast.classList.add("show");
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => toast.classList.remove("show"), 2600);
+ }
+
+ let press = null;
+ let dragging = null;
+ document.addEventListener("mousedown", (e) => {
+ if (e.button !== 0) return;
+ if (menuOpen && !e.target.closest("#menu")) {
+ closeMenu();
+ if (!e.target.closest("[data-k=btn-filter],[data-k=btn-display],.more")) return;
+ }
+ const k = e.target.closest("[data-k]");
+ if (k && k.dataset.k === "btn-filter") return openMenu("filter", k);
+ if (k && k.dataset.k === "btn-display") return openMenu("display", k);
+ if (k && k.dataset.k === "details-close") return closeDetails();
+ if (e.target.closest(".more")) return openMenu("card", e.target.closest(".more"));
+ if (e.target.closest("#menu .mi")) return closeMenu();
+ if (k && k.classList.contains("ni")) {
+ for (const n of document.querySelectorAll(".ni.active")) n.classList.remove("active");
+ k.classList.add("active");
+ setTimeout(() => {
+ k.classList.remove("active");
+ document.querySelector("[data-k=team-issues]").classList.add("active");
+ }, 900);
+ return;
+ }
+ const card = e.target.closest(".card");
+ if (card) {
+ const r = card.getBoundingClientRect();
+ press = { card, x: e.clientX, y: e.clientY, ox: e.clientX - r.left, oy: e.clientY - r.top, w: r.width, h: r.height };
+ e.preventDefault();
+ return;
+ }
+ if (!e.target.closest("#details")) closeDetails();
+ });
+ document.addEventListener("mousemove", (e) => {
+ if (press && !dragging && Math.hypot(e.clientX - press.x, e.clientY - press.y) > 5) {
+ const { card } = press;
+ const ghost = card.cloneNode(true);
+ ghost.classList.add("ghost");
+ ghost.style.width = `${press.w}px`;
+ document.body.append(ghost);
+ const ph = document.createElement("div");
+ ph.className = "placeholder";
+ ph.style.height = `${press.h}px`;
+ card.replaceWith(ph);
+ dragging = { card, ghost, ph };
+ tooltip.style.display = "none";
+ cap.event("drag_start", { id: card.dataset.id });
+ }
+ if (!dragging) return;
+ dragging.ghost.style.left = `${e.clientX - press.ox}px`;
+ dragging.ghost.style.top = `${e.clientY - press.oy}px`;
+ const under = document.elementFromPoint(e.clientX, e.clientY);
+ const list = under && under.closest(".list");
+ for (const l of document.querySelectorAll(".list.over")) if (l !== list) l.classList.remove("over");
+ if (!list) return;
+ list.classList.add("over");
+ const cards = [...list.querySelectorAll(".card")];
+ let before = null;
+ for (const c of cards) {
+ const r = c.getBoundingClientRect();
+ if (e.clientY < r.top + r.height / 2) {
+ before = c;
+ break;
+ }
+ }
+ if (before) {
+ if (dragging.ph.nextSibling !== before) list.insertBefore(dragging.ph, before);
+ } else if (list.lastElementChild !== dragging.ph) {
+ list.append(dragging.ph);
+ }
+ });
+ document.addEventListener("mouseup", () => {
+ if (dragging) {
+ const { card, ghost, ph } = dragging;
+ ph.replaceWith(card);
+ ghost.remove();
+ for (const l of document.querySelectorAll(".list.over")) l.classList.remove("over");
+ const col = card.closest(".col").dataset.col;
+ const info = cardEls.get(card.dataset.id);
+ const moved = info.col !== col;
+ info.col = col;
+ updateCounts();
+ const name = D.columns.find((c) => c.id === col).name;
+ if (moved) showToast(`${STATUS[D.columns.find((c) => c.id === col).icon]}<span>Moved <b>${card.dataset.id}</b> to ${name}</span><span class="undo">Undo</span>`);
+ cap.event("drop", { id: card.dataset.id, col });
+ dragging = null;
+ press = null;
+ return;
+ }
+ if (press) {
+ openDetails(press.card.dataset.id);
+ press = null;
+ }
+ });
+ window.addEventListener("keydown", (e) => {
+ if (e.key === "Escape") {
+ closeMenu();
+ closeDetails();
+ }
+ });
+
+ function center(el) {
+ const r = el.getBoundingClientRect();
+ return [Math.round(r.left + r.width / 2), Math.round(r.top + r.height / 2), Math.round(r.width), Math.round(r.height)];
+ }
+ window.capFind = (what) => {
+ let el = null;
+ if (what.startsWith("card:")) el = cardEls.get(what.slice(5)).el;
+ else if (what.startsWith("more:")) {
+ const c = cardEls.get(what.slice(5)).el;
+ const r = c.getBoundingClientRect();
+ return [Math.round(r.right - 47), Math.round(r.top + 18), 22, 22];
+ } else if (what.startsWith("col:")) el = board.querySelector(`[data-col=${what.slice(4)}] .list`);
+ else if (what.startsWith("colhead:")) el = board.querySelector(`[data-col=${what.slice(8)}] .colh`);
+ else if (what.startsWith("menuitem:")) el = menu.querySelectorAll(".mi")[Number(what.slice(9))];
+ else if (what.startsWith("prop:")) el = details.querySelectorAll(".prop")[Number(what.slice(5))];
+ else el = document.querySelector(`[data-k="${what}"]`);
+ return el ? center(el) : null;
+ };
+ window.capCardsIn = (col) => [...board.querySelectorAll(`[data-col=${col}] .card`)].map((c) => c.dataset.id);
+ window.capTextRegions = () => {
+ const s = document.getElementById("side").getBoundingClientRect();
+ const cols = [...board.querySelectorAll(".col")];
+ const a = cols[0].getBoundingClientRect();
+ const b = cols[2].getBoundingClientRect();
+ return [
+ [s.left + 4, 60, 236, 560],
+ [a.left, a.top + 42, a.width, 600],
+ [b.left, b.top + 42, b.width, 600],
+ ];
+ };
+})();
diff --git a/capcodec/bench/corpus/pages/common/cap.js b/capcodec/bench/corpus/pages/common/cap.js
new file mode 100644
index 000000000..abd36e9fa
--- /dev/null
+++ b/capcodec/bench/corpus/pages/common/cap.js
@@ -0,0 +1,94 @@
+(() => {
+ const buffer = [];
+ const tracked = new Map();
+ let nextId = 1;
+
+ function now() {
+ return Date.now();
+ }
+
+ function preciseNow() {
+ return performance.timeOrigin + performance.now();
+ }
+
+ function push(record) {
+ record.t = now();
+ record.tp = Math.round(preciseNow() * 1000) / 1000;
+ buffer.push(record);
+ }
+
+ function clientRect(el) {
+ if (el === document.scrollingElement || el === document.documentElement) {
+ const de = document.documentElement;
+ return [0, 0, de.clientWidth, de.clientHeight];
+ }
+ const r = el.getBoundingClientRect();
+ return [r.left + el.clientLeft, r.top + el.clientTop, el.clientWidth, el.clientHeight];
+ }
+
+ function track(el, name) {
+ if (!el || tracked.has(el)) return;
+ tracked.set(el, { id: name || el.dataset.scrollId || `s${nextId++}`, last: null });
+ }
+
+ function sample(src) {
+ for (const [el, info] of tracked) {
+ if (!el.isConnected) continue;
+ const rect = clientRect(el);
+ const sx = el.scrollLeft;
+ const sy = el.scrollTop;
+ const key = `${sx},${sy},${rect.join(",")}`;
+ if (src !== "scroll" && info.last === key) continue;
+ info.last = key;
+ push({ k: "scroll", id: info.id, src, sx, sy, rect });
+ }
+ }
+
+ function onFrame() {
+ sample("raf");
+ requestAnimationFrame(onFrame);
+ }
+
+ function flush() {
+ if (!buffer.length || typeof window.__capReport !== "function") return;
+ const batch = buffer.splice(0, buffer.length);
+ window.__capReport(batch);
+ }
+
+ function event(type, data) {
+ push({ k: "page", type, ...(data || {}) });
+ }
+
+ function trackAll() {
+ track(document.scrollingElement, "document");
+ for (const el of document.querySelectorAll("[data-scroll-id]")) track(el);
+ }
+
+ document.addEventListener("scroll", () => sample("scroll"), { capture: true, passive: true });
+ for (const type of ["keydown", "keyup"]) {
+ window.addEventListener(type, (e) => push({ k: "input", type, key: e.key, code: e.code }), { capture: true });
+ }
+ for (const type of ["mousedown", "mouseup", "click", "dblclick"]) {
+ window.addEventListener(type, (e) => push({ k: "input", type, x: e.clientX, y: e.clientY, button: e.button }), { capture: true });
+ }
+ window.addEventListener(
+ "wheel",
+ (e) => push({ k: "input", type: "wheel", x: e.clientX, y: e.clientY, dx: e.deltaX, dy: e.deltaY, mode: e.deltaMode }),
+ { capture: true, passive: true },
+ );
+
+ window.cap = { track, trackAll, event, flush, sample };
+ window.capReady = false;
+ window.capSetReady = () => {
+ trackAll();
+ sample("ready");
+ event("ready", { w: innerWidth, h: innerHeight, dpr: devicePixelRatio });
+ document.fonts.ready.then(() => {
+ requestAnimationFrame(() => requestAnimationFrame(() => {
+ window.capReady = true;
+ }));
+ });
+ };
+ requestAnimationFrame(onFrame);
+ setInterval(flush, 250);
+})();
diff --git a/capcodec/bench/corpus/pages/common/dashboard.js b/capcodec/bench/corpus/pages/common/dashboard.js
new file mode 100644
index 000000000..e4e6b7294
--- /dev/null
+++ b/capcodec/bench/corpus/pages/common/dashboard.js
@@ -0,0 +1,573 @@
+(() => {
+ const rng = window.mulberry32(20261007);
+ const rand = (a, b) => a + (b - a) * rng();
+ const pick = (arr) => arr[Math.floor(rng() * arr.length)];
+ const gauss = () => {
+ let s = 0;
+ for (let i = 0; i < 4; i++) s += rng();
+ return (s - 2) / 0.58;
+ };
+ const dpr = () => window.devicePixelRatio || 1;
+ const fmtInt = (v) => Math.round(v).toLocaleString("en-US");
+ const fmt1 = (v) => v.toLocaleString("en-US", { minimumFractionDigits: 1, maximumFractionDigits: 1 });
+ const fmt2 = (v) => v.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
+ const el = (tag, cls, html) => {
+ const e = document.createElement(tag);
+ if (cls) e.className = cls;
+ if (html !== undefined) e.innerHTML = html;
+ return e;
+ };
+
+ const startPerf = performance.now();
+ const baseClock = new Date(2026, 9, 7, 14, 32, 5).getTime();
+ const vnow = () => baseClock + (performance.now() - startPerf);
+ const pad = (n) => String(n).padStart(2, "0");
+ const hms = (ms) => {
+ const d = new Date(ms);
+ return `${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
+ };
+
+ function sizeCanvas(c) {
+ const r = c.getBoundingClientRect();
+ const k = dpr();
+ c.width = Math.round(r.width * k);
+ c.height = Math.round(r.height * k);
+ const ctx = c.getContext("2d");
+ ctx.setTransform(k, 0, 0, k, 0, 0);
+ return { ctx, w: r.width, h: r.height };
+ }
+
+ function drawSpark(c, data, color, fill) {
+ if (!c._ctx) Object.assign(c, (({ ctx, w, h }) => ({ _ctx: ctx, _w: w, _h: h }))(sizeCanvas(c)));
+ const ctx = c._ctx;
+ const w = c._w;
+ const h = c._h;
+ ctx.clearRect(0, 0, w, h);
+ let lo = Math.min(...data);
+ let hi = Math.max(...data);
+ if (hi - lo < 1e-9) hi = lo + 1;
+ const padY = 2;
+ const xs = (i) => (i / (data.length - 1)) * (w - 2) + 1;
+ const ys = (v) => h - padY - ((v - lo) / (hi - lo)) * (h - 2 * padY);
+ ctx.beginPath();
+ data.forEach((v, i) => (i ? ctx.lineTo(xs(i), ys(v)) : ctx.moveTo(xs(i), ys(v))));
+ if (fill) {
+ ctx.save();
+ ctx.lineTo(xs(data.length - 1), h);
+ ctx.lineTo(xs(0), h);
+ ctx.closePath();
+ const g = ctx.createLinearGradient(0, 0, 0, h);
+ g.addColorStop(0, `${color}38`);
+ g.addColorStop(1, `${color}00`);
+ ctx.fillStyle = g;
+ ctx.fill();
+ ctx.restore();
+ ctx.beginPath();
+ data.forEach((v, i) => (i ? ctx.lineTo(xs(i), ys(v)) : ctx.moveTo(xs(i), ys(v))));
+ }
+ ctx.strokeStyle = color;
+ ctx.lineWidth = 1.5;
+ ctx.lineJoin = "round";
+ ctx.stroke();
+ const lx = xs(data.length - 1);
+ const ly = ys(data[data.length - 1]);
+ if (fill) {
+ ctx.fillStyle = color;
+ ctx.beginPath();
+ ctx.arc(lx, ly, 2.2, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ }
+
+ const grid = document.getElementById("grid");
+ const tip = document.getElementById("tip");
+
+ const kpiDefs = [
+ { lab: "Active users", v: 18432, dv: 0.004, f: fmtInt, unit: "", vs: "+6.2%", color: "#4f46e5", up: true },
+ { lab: "Requests / s", v: 2864, dv: 0.03, f: fmtInt, unit: "", vs: "+3.9%", color: "#0891b2", up: true },
+ { lab: "p95 latency", v: 184, dv: 0.04, f: fmtInt, unit: "ms", vs: "−11 ms", color: "#d97706", up: true },
+ { lab: "Error rate", v: 0.42, dv: 0.06, f: fmt2, unit: "%", vs: "+0.05 pp", color: "#dc2626", up: false },
+ { lab: "Revenue today", v: 48213.5, dv: 0, f: (v) => `$${fmtInt(v)}`, unit: "", vs: "+12.4%", color: "#16a34a", up: true },
+ { lab: "Conversion", v: 3.18, dv: 0.01, f: fmt2, unit: "%", vs: "+0.21 pp", color: "#9333ea", up: true },
+ ];
+ const kpis = kpiDefs.map((d, i) => {
+ const p = el("div", "panel kpi");
+ p.innerHTML = `<div class="lab">${d.lab}</div><div class="val num"></div><div class="dl"><span class="${d.up ? "up" : "dn"}">${d.up ? "▲" : "▼"} ${d.vs}</span><span class="vs">vs. last hour</span></div><canvas></canvas>`;
+ grid.append(p);
+ const hist = [];
+ let v = d.v;
+ for (let k = 0; k < 32; k++) {
+ v = i === 4 ? v - rand(30, 160) : v * (1 + gauss() * d.dv * 0.6);
+ hist.unshift(v);
+ }
+ hist[hist.length - 1] = d.v;
+ return { d, p, val: p.querySelector(".val"), canvas: p.querySelector("canvas"), hist, v: d.v };
+ });
+
+ function renderKpi(k) {
+ k.val.innerHTML = `${k.d.f(k.v)}${k.d.unit ? `<small>${k.d.unit}</small>` : ""}`;
+ drawSpark(k.canvas, k.hist, k.d.color, true);
+ }
+
+ class LineChart {
+ constructor(panel, opts) {
+ this.panel = panel;
+ this.opts = opts;
+ this.canvas = panel.querySelector("canvas");
+ this.series = opts.series.map((s) => ({ ...s, data: [] }));
+ this.n = 90;
+ this.times = [];
+ const t0 = vnow() - this.n * 1000;
+ for (let i = 0; i <= this.n; i++) {
+ this.times.push(t0 + i * 1000);
+ const vals = opts.gen(i - this.n);
+ this.series.forEach((s, j) => s.data.push(vals[j]));
+ }
+ this.anim = null;
+ this.yMax = this.targetMax();
+ this.hover = null;
+ this.dirty = true;
+ const sized = sizeCanvas(this.canvas);
+ this.ctx = sized.ctx;
+ this.w = sized.w;
+ this.h = sized.h;
+ this.left = 46;
+ this.right = 10;
+ this.top = 10;
+ this.bottom = 22;
+ this.canvas.addEventListener("mousemove", (e) => {
+ const r = this.canvas.getBoundingClientRect();
+ this.hover = { x: e.clientX - r.left, y: e.clientY - r.top, cx: e.clientX, cy: e.clientY };
+ this.dirty = true;
+ });
+ this.canvas.addEventListener("mouseleave", () => {
+ this.hover = null;
+ tip.style.display = "none";
+ this.dirty = true;
+ });
+ }
+
+ targetMax() {
+ let m = 0;
+ for (const s of this.series) for (const v of s.data.slice(-this.n - 1)) m = Math.max(m, v);
+ const step = this.opts.step;
+ return Math.ceil((m * 1.12) / step) * step;
+ }
+
+ push(vals, t) {
+ this.series.forEach((s, j) => {
+ s.data.push(vals[j]);
+ if (s.data.length > this.n + 3) s.data.shift();
+ });
+ this.times.push(t);
+ if (this.times.length > this.n + 3) this.times.shift();
+ this.anim = { t0: performance.now(), dur: 420, from: this.yMax, to: this.targetMax() };
+ this.dirty = true;
+ }
+
+ draw(now) {
+ let frac = 1;
+ if (this.anim) {
+ const p = Math.min(1, (now - this.anim.t0) / this.anim.dur);
+ frac = 1 - (1 - p) ** 3;
+ this.yMax = this.anim.from + (this.anim.to - this.anim.from) * frac;
+ if (p >= 1) this.anim = null;
+ this.dirty = true;
+ }
+ if (!this.dirty) return;
+ this.dirty = !!this.anim;
+ const { ctx, w, h, left, right, top, bottom } = this;
+ const pw = w - left - right;
+ const ph = h - top - bottom;
+ ctx.clearRect(0, 0, w, h);
+ ctx.font = '11px "Noto Sans", "Liberation Sans", sans-serif';
+ ctx.textBaseline = "middle";
+ const yTicks = 5;
+ for (let i = 0; i <= yTicks; i++) {
+ const y = Math.round(top + ph - (i / yTicks) * ph) + 0.5;
+ ctx.strokeStyle = i === 0 ? "#d5d9df" : "#eef0f3";
+ ctx.lineWidth = 1;
+ ctx.beginPath();
+ ctx.moveTo(left, y);
+ ctx.lineTo(left + pw, y);
+ ctx.stroke();
+ ctx.fillStyle = "#8a94a3";
+ ctx.textAlign = "right";
+ ctx.fillText(this.opts.axis((i / yTicks) * this.yMax), left - 8, y);
+ }
+ const step = pw / (this.n - 1);
+ const len = this.times.length;
+ const shift = this.anim ? 1 - frac : 0;
+ const xOf = (idx) => left + pw - (len - 1 - idx - shift) * step;
+ const yOf = (v) => top + ph - (v / this.yMax) * ph;
+ ctx.save();
+ ctx.beginPath();
+ ctx.rect(left, top - 2, pw, ph + 4);
+ ctx.clip();
+ this.series.forEach((s, j) => {
+ ctx.beginPath();
+ s.data.forEach((v, i) => (i ? ctx.lineTo(xOf(i), yOf(v)) : ctx.moveTo(xOf(i), yOf(v))));
+ if (j === 0) {
+ ctx.save();
+ ctx.lineTo(xOf(len - 1), top + ph);
+ ctx.lineTo(xOf(0), top + ph);
+ ctx.closePath();
+ const g = ctx.createLinearGradient(0, top, 0, top + ph);
+ g.addColorStop(0, `${s.color}30`);
+ g.addColorStop(1, `${s.color}02`);
+ ctx.fillStyle = g;
+ ctx.fill();
+ ctx.restore();
+ ctx.beginPath();
+ s.data.forEach((v, i) => (i ? ctx.lineTo(xOf(i), yOf(v)) : ctx.moveTo(xOf(i), yOf(v))));
+ }
+ ctx.strokeStyle = s.color;
+ ctx.lineWidth = s.width || 1.6;
+ ctx.lineJoin = "round";
+ ctx.setLineDash(s.dash || []);
+ ctx.stroke();
+ ctx.setLineDash([]);
+ });
+ ctx.restore();
+ ctx.textAlign = "center";
+ ctx.fillStyle = "#8a94a3";
+ for (let i = 0; i < len; i++) {
+ const t = this.times[i];
+ if (Math.round(t / 1000) % 15 !== 0) continue;
+ const x = xOf(i);
+ if (x < left + 18 || x > left + pw - 18) continue;
+ ctx.fillText(hms(t), x, top + ph + 12);
+ ctx.strokeStyle = "#d5d9df";
+ ctx.beginPath();
+ ctx.moveTo(Math.round(x) + 0.5, top + ph);
+ ctx.lineTo(Math.round(x) + 0.5, top + ph + 4);
+ ctx.stroke();
+ }
+ if (this.hover && this.hover.x >= left && this.hover.x <= left + pw && this.hover.y >= top && this.hover.y <= top + ph) {
+ let best = len - 1;
+ let bd = Number.POSITIVE_INFINITY;
+ for (let i = 0; i < len; i++) {
+ const d = Math.abs(xOf(i) - this.hover.x);
+ if (d < bd) {
+ bd = d;
+ best = i;
+ }
+ }
+ const x = Math.round(xOf(best)) + 0.5;
+ ctx.strokeStyle = "#9aa3af";
+ ctx.setLineDash([3, 3]);
+ ctx.beginPath();
+ ctx.moveTo(x, top);
+ ctx.lineTo(x, top + ph);
+ ctx.stroke();
+ ctx.setLineDash([]);
+ let html = `<b>${hms(this.times[best])}</b><br>`;
+ for (const s of this.series) {
+ const v = s.data[best];
+ ctx.fillStyle = "#fff";
+ ctx.strokeStyle = s.color;
+ ctx.lineWidth = 2;
+ ctx.beginPath();
+ ctx.arc(x, yOf(v), 3.5, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.stroke();
+ html += `<i style="background:${s.color}"></i>${s.name} <b class="num">${this.opts.tip(v)}</b><br>`;
+ }
+ tip.innerHTML = html;
+ tip.style.display = "block";
+ const tw = tip.offsetWidth;
+ const tx = this.hover.cx + 16 + tw > innerWidth ? this.hover.cx - 16 - tw : this.hover.cx + 16;
+ tip.style.left = `${tx}px`;
+ tip.style.top = `${this.hover.cy - 30}px`;
+ }
+ }
+ }
+
+ function chartPanel(cls, title, sub, series) {
+ const p = el("div", `panel chart${cls}`);
+ p.innerHTML = `<h4>${title}<span class="sub">${sub}</span></h4><div class="legend">${series
+ .map((s) => `<span><i style="background:${s.color}"></i>${s.name}</span>`)
+ .join("")}</div><canvas></canvas>`;
+ grid.append(p);
+ return p;
+ }
+
+ let rpsBase = 2800;
+ const rpsSeries = [
+ { name: "2xx", color: "#0891b2", width: 1.8 },
+ { name: "4xx", color: "#d97706" },
+ { name: "5xx", color: "#dc2626" },
+ ];
+ const latSeries = [
+ { name: "p50", color: "#4f46e5", width: 1.8 },
+ { name: "p95", color: "#d97706" },
+ { name: "p99", color: "#dc2626", dash: [4, 3] },
+ ];
+ const rpsGen = (i) => {
+ rpsBase += gauss() * 40 + (2850 - rpsBase) * 0.05 + Math.sin(i / 9) * 12;
+ const spike = rng() < 0.04 ? rand(1.1, 1.3) : 1;
+ const ok = rpsBase * spike;
+ return [ok, ok * rand(0.035, 0.06), ok * rand(0.002, 0.009) * (rng() < 0.05 ? 4 : 1)];
+ };
+ let latBase = 62;
+ const latGen = () => {
+ latBase += gauss() * 3 + (62 - latBase) * 0.08;
+ const p95 = latBase * rand(2.7, 3.2) * (rng() < 0.05 ? 1.5 : 1);
+ return [latBase, p95, p95 * rand(1.5, 2.1)];
+ };
+ const rpsChart = new LineChart(chartPanel("", "Requests per second", "by status class · 1 s resolution", rpsSeries), {
+ series: rpsSeries,
+ gen: rpsGen,
+ step: 500,
+ axis: (v) => (v >= 1000 ? `${fmt1(v / 1000)}k` : fmtInt(v)),
+ tip: (v) => `${fmtInt(v)} req/s`,
+ });
+ const latChart = new LineChart(chartPanel(" r", "Latency", "all endpoints · ms", latSeries), {
+ series: latSeries,
+ gen: latGen,
+ step: 100,
+ axis: (v) => `${fmtInt(v)}`,
+ tip: (v) => `${fmtInt(v)} ms`,
+ });
+ const charts = [rpsChart, latChart];
+
+ const endpoints = [
+ ["GET", "/api/v2/orders"],
+ ["POST", "/api/v2/orders"],
+ ["GET", "/api/v2/orders/:id"],
+ ["GET", "/api/v2/products"],
+ ["GET", "/api/v2/products/:sku"],
+ ["GET", "/api/v2/cart"],
+ ["POST", "/api/v2/cart/items"],
+ ["DELETE", "/api/v2/cart/items/:id"],
+ ["POST", "/api/v2/checkout"],
+ ["POST", "/api/v2/payments/intent"],
+ ["GET", "/api/v2/users/me"],
+ ["PATCH", "/api/v2/users/me"],
+ ["POST", "/api/v2/auth/token"],
+ ["POST", "/api/v2/auth/refresh"],
+ ["GET", "/api/v2/search"],
+ ["GET", "/api/v2/recommendations"],
+ ["POST", "/api/v2/events/batch"],
+ ["GET", "/healthz"],
+ ];
+ const tblPanel = el("div", "panel tbl");
+ tblPanel.innerHTML = `<h4>Top endpoints<span class="sub">sorted by traffic · last 5 min</span><span class="acts"><span>Export CSV</span><span>Columns ▾</span></span></h4>`;
+ const table = el("table", "num");
+ table.innerHTML =
+ "<thead><tr><th>Endpoint</th><th>Req/min</th><th>p50</th><th>p95</th><th>p99</th><th>Errors</th><th>Error %</th><th>Apdex</th><th>Throughput (15 min)</th></tr></thead>";
+ const tbody = el("tbody");
+ table.append(tbody);
+ tblPanel.append(table);
+ grid.append(tblPanel);
+ const rows = endpoints.map(([m, path], i) => {
+ const rpm = Math.round(42000 / (1 + i * 0.55) ** 1.25 + rand(-400, 400));
+ const p50 = Math.round(rand(14, 90) * (m === "POST" ? 1.6 : 1));
+ const r = {
+ m,
+ path,
+ rpm,
+ p50,
+ p95: Math.round(p50 * rand(2.4, 3.6)),
+ p99: 0,
+ err: 0,
+ hist: [],
+ };
+ r.p99 = Math.round(r.p95 * rand(1.4, 2.2));
+ r.errPct = path === "/healthz" ? 0 : rand(0.02, 1.1);
+ r.err = Math.round((r.rpm * 5 * r.errPct) / 100);
+ r.apdex = Math.min(0.99, 1.02 - r.p95 / 900 - r.errPct / 30);
+ for (let k = 0; k < 30; k++) r.hist.push(r.rpm * (1 + gauss() * 0.06 + Math.sin(k / 4 + i) * 0.05));
+ const tr = el("tr");
+ tr.innerHTML = `<td class="ep"><span class="m">${m}</span>${path}</td><td data-c="rpm"></td><td data-c="p50"></td><td data-c="p95"></td><td data-c="p99"></td><td data-c="err"></td><td data-c="errPct"></td><td><span data-c="apdex"></span><span class="bar"><i></i></span></td><td><canvas></canvas></td>`;
+ tbody.append(tr);
+ r.tr = tr;
+ r.cells = Object.fromEntries([...tr.querySelectorAll("[data-c]")].map((c) => [c.dataset.c, c]));
+ r.barI = tr.querySelector(".bar i");
+ r.canvas = tr.querySelector("canvas");
+ return r;
+ });
+
+ function renderRow(r, flash) {
+ const vals = {
+ rpm: fmtInt(r.rpm),
+ p50: `${r.p50} ms`,
+ p95: `${r.p95} ms`,
+ p99: `${r.p99} ms`,
+ err: fmtInt(r.err),
+ errPct: `${fmt2(r.errPct)}%`,
+ apdex: r.apdex.toFixed(2),
+ };
+ for (const [k, v] of Object.entries(vals)) {
+ const c = r.cells[k];
+ if (c.textContent === v) continue;
+ c.textContent = v;
+ if (flash && k !== "apdex") {
+ c.classList.remove("flash");
+ void c.offsetWidth;
+ c.classList.add("flash");
+ }
+ }
+ r.cells.errPct.className = r.errPct > 0.8 ? "dn" : "";
+ r.barI.style.width = `${Math.round(r.apdex * 100)}%`;
+ r.barI.style.background = r.apdex > 0.85 ? "#22c55e" : r.apdex > 0.7 ? "#f59e0b" : "#ef4444";
+ drawSpark(r.canvas, r.hist, "#6366f1", false);
+ }
+
+ const side = el("div", "side");
+ const errPanel = el("div", "panel errs");
+ errPanel.innerHTML = `<h4>Errors by type<span class="sub">last 15 min</span><span class="acts"><span>View all</span></span></h4>`;
+ const errTypes = [
+ ["UpstreamTimeout (payments)", 412],
+ ["HTTP 502 Bad Gateway", 268],
+ ["ValidationError: sku", 191],
+ ["RateLimitExceeded", 143],
+ ["ConnectionResetError", 87],
+ ["KeyError: 'currency'", 41],
+ ].map(([n, c]) => {
+ const row = el("div", "er", `<span class="n">${n}</span><span class="b"><i></i></span><span class="c num"></span>`);
+ errPanel.append(row);
+ return { n, c, i: row.querySelector("i"), cEl: row.querySelector(".c") };
+ });
+ const feedPanel = el("div", "panel feed");
+ feedPanel.innerHTML = `<h4>Live events<span class="sub">all services</span><span class="acts"><span>Pause</span><span>Filter ▾</span></span></h4>`;
+ const feedList = el("div");
+ feedPanel.append(feedList);
+ side.append(errPanel, feedPanel);
+ grid.append(side);
+
+ function renderErrs() {
+ const max = Math.max(...errTypes.map((e) => e.c));
+ for (const e of errTypes) {
+ e.i.style.width = `${((e.c / max) * 100).toFixed(1)}%`;
+ e.cEl.textContent = fmtInt(e.c);
+ }
+ }
+
+ const services = ["api-gateway", "checkout-svc", "payments-svc", "cart-svc", "search-svc", "catalog-svc", "auth-svc", "worker-events"];
+ const pods = () => `${pick(services)}-${Math.floor(rand(4096, 65535)).toString(16)}-${pick(["x7k2p", "m4q9z", "t2v8c", "b6n1r", "h3d5w"])}`;
+ const eventTemplates = [
+ ["info", () => `deploy <b>${pick(services)}</b> v2.${Math.floor(rand(30, 48))}.${Math.floor(rand(0, 9))} rolled out to ${Math.floor(rand(6, 13))}/12 pods`],
+ ["info", () => `autoscaler: <b>${pick(services)}</b> scaled ${Math.floor(rand(4, 7))} → ${Math.floor(rand(7, 11))} replicas`],
+ ["warn", () => `p95 latency on <b>/api/v2/${pick(["search", "checkout", "orders", "recommendations"])}</b> above ${pick([300, 400, 500])} ms`],
+ ["err", () => `<b>payments-svc</b> 502 from upstream stripe-proxy (${Math.floor(rand(2, 30))} in 60 s)`],
+ ["info", () => `cache hit ratio ${fmt1(rand(91, 97))}% on redis-${pick(["main", "sessions", "catalog"])}`],
+ ["info", () => `job <b>${pick(["nightly-reindex", "export-orders", "sync-inventory", "gc-sessions"])}</b> completed in ${Math.floor(rand(1, 9))}m${pad(Math.floor(rand(0, 59)))}s`],
+ ["warn", () => `pod <b>${pods()}</b> restarted (OOMKilled)`],
+ ["info", () => `alert resolved: ${pick(["High error rate", "Disk usage > 80%", "Queue backlog"])} on ${pick(services)}`],
+ ["err", () => `<b>${pick(services)}</b> ${pick(["ConnectionResetError", "UpstreamTimeout", "KeyError: 'currency'"])} in ${pick(["handler.py:212", "client.go:88", "routes.ts:47"])}`],
+ ["info", () => `${pick(["sw", "mk", "jl", "ar"])}@acme.io acknowledged INC-${Math.floor(rand(2200, 2400))}`],
+ ["warn", () => `queue <b>${pick(["events.batch", "emails", "webhooks"])}</b> depth ${fmtInt(rand(1200, 9000))} (consumer lag ${fmt1(rand(1, 9))} s)`],
+ ];
+ function addEvent(animate, tms) {
+ const [lv, f] = pick(eventTemplates);
+ const ev = el("div", `ev${animate ? " new" : ""}`, `<span class="t">${hms(tms)}</span><span class="lv ${lv}">${lv.toUpperCase()}</span><span>${f()}</span>`);
+ feedList.prepend(ev);
+ while (feedList.children.length > 16) feedList.lastChild.remove();
+ if (animate) cap.event("dash_event", { level: lv });
+ }
+ for (let i = 14; i >= 0; i--) addEvent(false, vnow() - i * rand(2000, 6000));
+
+ for (const k of kpis) renderKpi(k);
+ for (const r of rows) renderRow(r, false);
+ renderErrs();
+
+ const upd = document.getElementById("upd");
+ const lag = document.getElementById("lag");
+ const pts = document.getElementById("pts");
+ const cd = document.getElementById("cd");
+ let points = 1284331;
+ let tickNo = 0;
+ let countdown = 10;
+ const timers = [];
+ const later = (ms, fn) => timers.push(setTimeout(fn, ms));
+
+ function tick() {
+ tickNo++;
+ const t = vnow();
+ upd.textContent = hms(t);
+ lag.textContent = `${fmt1(rand(0.4, 1.4))} s`;
+ points += Math.floor(rand(2400, 3400));
+ pts.textContent = fmtInt(points);
+ countdown = countdown <= 1 ? 10 : countdown - 1;
+ cd.textContent = `${countdown}s`;
+ later(30, () => rpsChart.push(rpsGen(tickNo), t));
+ later(90, () => latChart.push(latGen(), t));
+ kpis.forEach((k, i) => {
+ later(140 + i * 110, () => {
+ if (i === 4) k.v += rand(8, 140) * (rng() < 0.25 ? 3 : 1);
+ else k.v *= 1 + gauss() * k.d.dv * 0.5;
+ if (i === 1) k.v = rpsChart.series[0].data.at(-1) + rpsChart.series[1].data.at(-1) + rpsChart.series[2].data.at(-1);
+ if (i === 2) k.v = latChart.series[1].data.at(-1);
+ k.hist.push(k.v);
+ k.hist.shift();
+ renderKpi(k);
+ });
+ });
+ const nUpd = countdown === 10 ? rows.length : Math.floor(rand(3, 7));
+ const chosen = new Set();
+ while (chosen.size < nUpd) chosen.add(Math.floor(rng() * rows.length));
+ [...chosen].forEach((idx, j) => {
+ later(220 + j * 45, () => {
+ const r = rows[idx];
+ r.rpm = Math.max(10, Math.round(r.rpm * (1 + gauss() * 0.025)));
+ r.p50 = Math.max(3, Math.round(r.p50 * (1 + gauss() * 0.04)));
+ r.p95 = Math.max(r.p50 + 4, Math.round(r.p95 * (1 + gauss() * 0.05)));
+ r.p99 = Math.max(r.p95 + 6, Math.round(r.p99 * (1 + gauss() * 0.06)));
+ if (r.path !== "/healthz") r.errPct = Math.max(0, r.errPct * (1 + gauss() * 0.08));
+ r.err = Math.round((r.rpm * 5 * r.errPct) / 100);
+ r.apdex = Math.max(0.4, Math.min(0.99, 1.02 - r.p95 / 900 - r.errPct / 30));
+ r.hist.push(r.rpm);
+ r.hist.shift();
+ renderRow(r, true);
+ });
+ });
+ if (tickNo % 2 === 0) {
+ later(500, () => {
+ for (const e of errTypes) e.c += Math.floor(rand(0, 6) * (rng() < 0.15 ? 4 : 1));
+ renderErrs();
+ });
+ }
+ }
+
+ function eventLoop() {
+ addEvent(true, vnow());
+ later(rand(900, 2300), eventLoop);
+ }
+
+ function frame(now) {
+ for (const c of charts) c.draw(now);
+ requestAnimationFrame(frame);
+ }
+ requestAnimationFrame(frame);
+ upd.textContent = hms(vnow());
+
+ let started = false;
+ window.capStart = () => {
+ if (started) return;
+ started = true;
+ const msToNext = 1000 - (Math.round(vnow()) % 1000);
+ later(msToNext, () => {
+ tick();
+ timers.push(setInterval(tick, 1000));
+ });
+ later(700, eventLoop);
+ };
+ window.capStop = () => {
+ for (const t of timers) {
+ clearTimeout(t);
+ clearInterval(t);
+ }
+ };
+ window.capTextRegions = () => {
+ const tb = tbody.getBoundingClientRect();
+ const kr = kpis[0].p.getBoundingClientRect();
+ const kl = kpis[2].p.getBoundingClientRect();
+ const fr = feedList.getBoundingClientRect();
+ return [
+ [tb.left, tb.top, Math.min(820, tb.width), Math.min(400, tb.height)],
+ [kr.left, kr.top, kl.right - kr.left, kr.height],
+ [fr.left, fr.top, fr.width, Math.min(320, fr.height)],
+ ];
+ };
+})();
diff --git a/capcodec/bench/corpus/pages/common/editor.js b/capcodec/bench/corpus/pages/common/editor.js
new file mode 100644
index 000000000..a46ccbb95
--- /dev/null
+++ b/capcodec/bench/corpus/pages/common/editor.js
@@ -0,0 +1,722 @@
+(() => {
+ const PY_CONTROL = new Set(
+ "if elif else for while return yield break continue pass raise try except finally with as import from in not and or is lambda assert del global nonlocal await async".split(" "),
+ );
+ const PY_STORAGE = new Set("def class True False None".split(" "));
+ const PY_SELF = new Set(["self", "cls"]);
+ const PY_TYPES = new Set(
+ "int str list dict set tuple float bool bytes object type frozenset ValueError TypeError KeyError IndexError StopIteration Exception NotImplementedError AttributeError".split(" "),
+ );
+ const PY_BUILTINS = new Set(
+ "len range isinstance min max sum enumerate zip sorted reversed print super any all map filter iter next abs hash id repr getattr setattr hasattr divmod round".split(" "),
+ );
+ const C_CONTROL = new Set("if else for while do switch case default break continue return goto".split(" "));
+ const C_STORAGE = new Set(
+ "int unsigned signed char void struct union enum const static extern register typedef sizeof long short local volatile inline".split(" "),
+ );
+ const C_TYPES = new Set(
+ "z_streamp z_stream Bytef uInt uLong code ZLIB_INTERNAL voidpf gz_headerp inflate_mode size_t uint32_t uint8_t ptrdiff_t".split(" "),
+ );
+
+ function classifyIdent(lang, word, prevWord, nextChar) {
+ if (lang === "py") {
+ if (PY_CONTROL.has(word)) return "kw";
+ if (PY_STORAGE.has(word)) return "st";
+ if (PY_SELF.has(word)) return "self";
+ if (prevWord === "def") return "fn";
+ if (prevWord === "class") return "ty";
+ if (PY_TYPES.has(word)) return "ty";
+ if (nextChar === "(") return "fn";
+ if (/^[A-Z][a-z]/.test(word)) return "ty";
+ if (/^[A-Z_][A-Z0-9_]+$/.test(word)) return "num";
+ return "var";
+ }
+ if (C_CONTROL.has(word)) return "kw";
+ if (C_STORAGE.has(word)) return "st";
+ if (C_TYPES.has(word)) return "ty";
+ if (/^[A-Z_][A-Z0-9_]+$/.test(word) && word.length > 1) return "mac";
+ if (nextChar === "(") return "fn";
+ if (prevWord === "struct") return "ty";
+ return "var";
+ }
+
+ function tokenize(lang, line, state) {
+ const out = [];
+ let i = 0;
+ let prevWord = "";
+ const n = line.length;
+ const pushTok = (cls, text) => {
+ if (!text) return;
+ const last = out[out.length - 1];
+ if (last && last[0] === cls) last[1] += text;
+ else out.push([cls, text]);
+ };
+ if (lang === "c" && state.comment) {
+ const end = line.indexOf("*/");
+ if (end < 0) {
+ pushTok("com", line);
+ return { tokens: out, state: { comment: true } };
+ }
+ pushTok("com", line.slice(0, end + 2));
+ i = end + 2;
+ }
+ if (lang === "py" && state.str) {
+ const end = line.indexOf(state.str);
+ if (end < 0) {
+ pushTok("str", line);
+ return { tokens: out, state: { str: state.str } };
+ }
+ pushTok("str", line.slice(0, end + 3));
+ i = end + 3;
+ }
+ if (lang === "c") {
+ const m = /^(\s*)(#\s*\w+)(.*)$/.exec(line);
+ if (m && i === 0) {
+ pushTok("plain", m[1]);
+ pushTok("pp", m[2]);
+ const rest = m[3];
+ const inc = /^(\s*)(<[^>]*>|"[^"]*")(.*)$/.exec(rest);
+ if (inc) {
+ pushTok("plain", inc[1]);
+ pushTok("str", inc[2]);
+ pushTok("com", inc[3]);
+ return { tokens: out, state: {} };
+ }
+ const def = /^(\s+)([A-Za-z_]\w*)(.*)$/.exec(rest);
+ if (def) {
+ pushTok("plain", def[1]);
+ pushTok("mac", def[2]);
+ line = def[3];
+ i = 0;
+ const sub = tokenize("c", line, {});
+ for (const t of sub.tokens) pushTok(t[0], t[1]);
+ return { tokens: out, state: sub.state };
+ }
+ line = rest;
+ i = 0;
+ }
+ }
+ const len = line.length;
+ while (i < len) {
+ const ch = line[i];
+ const rest = line.slice(i);
+ if (ch === " " || ch === "\t") {
+ let j = i;
+ while (j < len && (line[j] === " " || line[j] === "\t")) j++;
+ pushTok("plain", line.slice(i, j));
+ i = j;
+ continue;
+ }
+ if (lang === "py" && ch === "#") {
+ pushTok("com", rest);
+ break;
+ }
+ if (lang === "c" && rest.startsWith("//")) {
+ pushTok("com", rest);
+ break;
+ }
+ if (lang === "c" && rest.startsWith("/*")) {
+ const end = line.indexOf("*/", i + 2);
+ if (end < 0) {
+ pushTok("com", rest);
+ return { tokens: out, state: { comment: true } };
+ }
+ pushTok("com", line.slice(i, end + 2));
+ i = end + 2;
+ continue;
+ }
+ if (lang === "py") {
+ const tm = /^([rRbBuUfF]{0,2})("""|''')/.exec(rest);
+ if (tm) {
+ const delim = tm[2];
+ const start = i + tm[0].length;
+ const end = line.indexOf(delim, start);
+ if (end < 0) {
+ pushTok("str", rest);
+ return { tokens: out, state: { str: delim } };
+ }
+ pushTok("str", line.slice(i, end + 3));
+ i = end + 3;
+ continue;
+ }
+ }
+ const sm = (lang === "py" ? /^[rRbBuUfF]{0,2}("|')/ : /^("|')/).exec(rest);
+ if (sm) {
+ const q = sm[1];
+ let j = i + sm[0].length;
+ while (j < len && line[j] !== q) {
+ if (line[j] === "\\") j++;
+ j++;
+ }
+ pushTok("str", line.slice(i, Math.min(len, j + 1)));
+ i = Math.min(len, j + 1);
+ continue;
+ }
+ const nm = /^(0[xX][0-9a-fA-F]+[uUlL]*|\d+(\.\d+)?([eE][+-]?\d+)?[uUlLj]*)/.exec(rest);
+ if (nm && !/[A-Za-z_]/.test(line[i - 1] || "")) {
+ pushTok("num", nm[0]);
+ i += nm[0].length;
+ continue;
+ }
+ if (lang === "py" && ch === "@") {
+ const dm = /^@[A-Za-z_][\w.]*/.exec(rest);
+ if (dm) {
+ pushTok("fn", dm[0]);
+ i += dm[0].length;
+ continue;
+ }
+ }
+ const im = /^[A-Za-z_]\w*/.exec(rest);
+ if (im) {
+ const word = im[0];
+ let k = i + word.length;
+ while (k < len && line[k] === " ") k++;
+ pushTok(classifyIdent(lang, word, prevWord, line[k]), word);
+ prevWord = word;
+ i += word.length;
+ continue;
+ }
+ pushTok("plain", ch);
+ if (ch !== "." && ch !== "*") prevWord = "";
+ i++;
+ }
+ return { tokens: out, state: {} };
+ }
+
+ const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+
+ class CodeEditor {
+ constructor(host, opts) {
+ this.host = host;
+ this.lang = opts.lang;
+ this.lines = opts.text.replace(/\r/g, "").split("\n");
+ if (this.lines[this.lines.length - 1] === "") this.lines.pop();
+ this.fontSize = opts.fontSize || 13;
+ this.lineHeight = opts.lineHeight || 19;
+ this.onStatus = opts.onStatus || (() => {});
+ this.onDirty = opts.onDirty || (() => {});
+ this.minimapColors = opts.minimapColors;
+ this.added = new Set();
+ this.modified = new Set();
+ this.caret = { line: opts.caretLine || 0, col: 0 };
+ this.focused = false;
+ this.states = [];
+ this.build();
+ this.retokenizeFrom(0, true);
+ this.renderAll();
+ this.updateCaret(false);
+ this.bind();
+ }
+
+ build() {
+ const h = this.host;
+ h.classList.add("ce");
+ h.innerHTML = "";
+ this.scroller = document.createElement("div");
+ this.scroller.className = "ce-scroller";
+ this.scroller.dataset.scrollId = this.host.id || "editor";
+ this.content = document.createElement("div");
+ this.content.className = "ce-content";
+ this.lineHL = document.createElement("div");
+ this.lineHL.className = "ce-linehl";
+ this.selEl = document.createElement("div");
+ this.selEl.className = "ce-sel";
+ this.rowsEl = document.createElement("div");
+ this.rowsEl.className = "ce-rows";
+ this.caretEl = document.createElement("div");
+ this.caretEl.className = "ce-caret blink";
+ this.suggest = document.createElement("div");
+ this.suggest.className = "ce-suggest";
+ this.content.append(this.lineHL, this.selEl, this.rowsEl, this.caretEl, this.suggest);
+ this.scroller.append(this.content);
+ this.minimap = document.createElement("canvas");
+ this.minimap.className = "ce-minimap";
+ this.vbar = document.createElement("div");
+ this.vbar.className = "ce-vbar";
+ this.vthumb = document.createElement("div");
+ this.vthumb.className = "ce-vthumb";
+ this.vbar.append(this.vthumb);
+ for (const [pos, cls] of [
+ [0.12, "warn"],
+ [0.31, "mod"],
+ [0.47, "warn"],
+ [0.66, "add"],
+ [0.83, "mod"],
+ ]) {
+ const m = document.createElement("div");
+ m.className = `ce-mark ${cls}`;
+ m.style.top = `${pos * 100}%`;
+ this.vbar.append(m);
+ }
+ h.append(this.scroller, this.minimap, this.vbar);
+ const probe = document.createElement("span");
+ probe.className = "ce-probe";
+ probe.textContent = "M".repeat(100);
+ this.rowsEl.append(probe);
+ this.cw = probe.getBoundingClientRect().width / 100;
+ probe.remove();
+ this.gutter = 66;
+ }
+
+ retokenizeFrom(start, all) {
+ let state = start > 0 ? this.states[start - 1].end : {};
+ this.tokens = this.tokens || [];
+ for (let i = start; i < this.lines.length; i++) {
+ const prev = this.states[i];
+ const r = tokenize(this.lang, this.lines[i], state);
+ const changedEnd = !prev || JSON.stringify(prev.end) !== JSON.stringify(r.state);
+ const changedStart = !prev || JSON.stringify(prev.start) !== JSON.stringify(state);
+ this.states[i] = { start: state, end: r.state };
+ this.tokens[i] = r.tokens;
+ if (!all && i > start && !changedEnd && !changedStart) {
+ this.dirtyRows.add(i);
+ break;
+ }
+ if (this.dirtyRows) this.dirtyRows.add(i);
+ state = r.state;
+ }
+ }
+
+ rowHTML(i) {
+ const line = this.lines[i];
+ const toks = this.tokens[i] || [];
+ let html = "";
+ const lead = /^ */.exec(line)[0].length;
+ let col = 0;
+ for (const [cls, text] of toks) {
+ let t = text;
+ if (col < lead && cls === "plain") {
+ const take = Math.min(t.length, lead - col);
+ let guides = "";
+ let k = 0;
+ while (k + 4 <= take) {
+ guides += '<span class="ig"> </span>';
+ k += 4;
+ }
+ if (k < take) guides += " ".repeat(take - k);
+ html += guides;
+ t = t.slice(take);
+ col += take;
+ if (!t) continue;
+ }
+ html += cls === "plain" ? esc(t) : `<span class="tk-${cls}">${esc(t)}</span>`;
+ col += t.length;
+ }
+ const mark = this.added.has(i) ? " add" : this.modified.has(i) ? " mod" : "";
+ return `<span class="ln${mark}">${i + 1}</span><span class="code">${html || " "}</span>`;
+ }
+
+ renderAll() {
+ const frag = document.createDocumentFragment();
+ this.rowsEl.innerHTML = "";
+ this.rowEls = [];
+ for (let i = 0; i < this.lines.length; i++) {
+ const d = document.createElement("div");
+ d.className = "ce-row";
+ d.innerHTML = this.rowHTML(i);
+ this.rowEls.push(d);
+ frag.append(d);
+ }
+ this.rowsEl.append(frag);
+ this.content.style.height = `${(this.lines.length + Math.floor(this.visibleLines() - 2)) * this.lineHeight}px`;
+ this.renderMinimapFull();
+ this.updateScrollUI();
+ }
+
+ renderRows(rows) {
+ for (const i of rows) {
+ if (!this.rowEls[i]) continue;
+ this.rowEls[i].innerHTML = this.rowHTML(i);
+ }
+ }
+
+ insertRow(at) {
+ const d = document.createElement("div");
+ d.className = "ce-row";
+ d.innerHTML = '<span class="ln"></span><span class="code"> </span>';
+ const ref = this.rowEls[at] || null;
+ this.rowsEl.insertBefore(d, ref);
+ this.rowEls.splice(at, 0, d);
+ this.states.splice(at, 0, null);
+ this.tokens.splice(at, 0, []);
+ this.shiftSets(at, 1);
+ this.content.style.height = `${(this.lines.length + Math.floor(this.visibleLines() - 2)) * this.lineHeight}px`;
+ this.renumber(at);
+ }
+
+ removeRow(at) {
+ this.rowEls[at].remove();
+ this.rowEls.splice(at, 1);
+ this.states.splice(at, 1);
+ this.tokens.splice(at, 1);
+ this.shiftSets(at, -1);
+ this.renumber(at);
+ }
+
+ renumber(from) {
+ for (let i = from; i < this.rowEls.length; i++) this.rowEls[i].firstChild.textContent = i + 1;
+ }
+
+ shiftSets(at, delta) {
+ for (const name of ["added", "modified"]) {
+ const next = new Set();
+ for (const v of this[name]) next.add(v >= at ? v + delta : v);
+ this[name] = next;
+ }
+ }
+
+ visibleLines() {
+ return this.scroller.clientHeight / this.lineHeight;
+ }
+
+ bind() {
+ this.scroller.addEventListener(
+ "wheel",
+ (e) => {
+ e.preventDefault();
+ const lines = Math.round((e.deltaY / 120) * 3) || Math.sign(e.deltaY);
+ this.scrollTo(this.scroller.scrollTop + lines * this.lineHeight);
+ },
+ { passive: false },
+ );
+ this.scroller.addEventListener("scroll", () => this.updateScrollUI());
+ this.scroller.addEventListener("mousedown", (e) => {
+ e.preventDefault();
+ this.focus();
+ const r = this.content.getBoundingClientRect();
+ const line = Math.max(0, Math.min(this.lines.length - 1, Math.floor((e.clientY - r.top) / this.lineHeight)));
+ const col = Math.max(0, Math.min(this.lines[line].length, Math.round((e.clientX - r.left - this.gutter) / this.cw)));
+ this.caret = { line, col };
+ this.hideSuggest();
+ this.clearSel();
+ this.updateCaret(false);
+ if (e.detail === 2) this.selectWord();
+ });
+ window.addEventListener("keydown", (e) => {
+ if (!this.focused) return;
+ if (this.handleKey(e)) e.preventDefault();
+ });
+ }
+
+ focus() {
+ this.focused = true;
+ this.host.classList.add("focused");
+ if (this.onFocus) this.onFocus();
+ }
+
+ blur() {
+ this.focused = false;
+ this.host.classList.remove("focused");
+ this.hideSuggest();
+ }
+
+ pointFor(line, col) {
+ const l = Math.max(0, Math.min(this.lines.length - 1, line));
+ const c = Math.max(0, Math.min(this.lines[l].length, col));
+ const r = this.content.getBoundingClientRect();
+ return [Math.round(r.left + this.gutter + c * this.cw), Math.round(r.top + l * this.lineHeight + this.lineHeight / 2)];
+ }
+
+ scrollTo(y) {
+ const max = this.scroller.scrollHeight - this.scroller.clientHeight;
+ this.scroller.scrollTop = Math.max(0, Math.min(max, Math.round(y)));
+ }
+
+ edited(line) {
+ if (!this.added.has(line)) this.modified.add(line);
+ this.onDirty();
+ }
+
+ handleKey(e) {
+ const { line, col } = this.caret;
+ const text = this.lines[line];
+ if (e.ctrlKey && e.key === "s") {
+ if (this.onSave) this.onSave();
+ return true;
+ }
+ if (e.ctrlKey && e.key === "Home") {
+ this.caret = { line: 0, col: 0 };
+ this.updateCaret(true);
+ return true;
+ }
+ if (e.ctrlKey && e.key === "End") {
+ const l = this.lines.length - 1;
+ this.caret = { line: l, col: this.lines[l].length };
+ this.updateCaret(true);
+ return true;
+ }
+ if (e.ctrlKey || e.metaKey || e.altKey) return false;
+ this.dirtyRows = new Set();
+ let handled = true;
+ this.clearSel();
+ if (e.key.length === 1) {
+ this.typeChar(e.key);
+ } else if (e.key === "Enter") {
+ this.hideSuggest();
+ const before = text.slice(0, col);
+ const after = text.slice(col);
+ let indent = /^ */.exec(text)[0].length;
+ const trimmed = before.trimEnd();
+ if ((this.lang === "py" && trimmed.endsWith(":")) || (this.lang === "c" && trimmed.endsWith("{"))) indent += 4;
+ this.lines[line] = before.replace(/ +$/, "") || (before.trim() ? before : "");
+ this.lines.splice(line + 1, 0, " ".repeat(indent) + after.replace(/^ +/, ""));
+ this.insertRow(line + 1);
+ this.added.add(line + 1);
+ this.edited(line);
+ this.caret = { line: line + 1, col: indent };
+ this.retokenizeFrom(line);
+ this.dirtyRows.add(line);
+ this.dirtyRows.add(line + 1);
+ } else if (e.key === "Backspace") {
+ if (col > 0) {
+ const lead = /^ */.exec(text)[0].length;
+ let n = 1;
+ if (col <= lead && col % 4 === 0) n = 4;
+ else if (col <= lead) n = col % 4;
+ const pair = text[col - 1] + (text[col] || "");
+ if (["()", "[]", '""', "''"].includes(pair)) {
+ this.lines[line] = text.slice(0, col - 1) + text.slice(col + 1);
+ } else {
+ this.lines[line] = text.slice(0, col - n) + text.slice(col);
+ }
+ this.caret.col = col - n;
+ this.edited(line);
+ this.retokenizeFrom(line);
+ this.dirtyRows.add(line);
+ this.updateSuggest();
+ } else if (line > 0) {
+ const prev = this.lines[line - 1];
+ this.lines[line - 1] = prev + text;
+ this.lines.splice(line, 1);
+ this.removeRow(line);
+ this.caret = { line: line - 1, col: prev.length };
+ this.edited(line - 1);
+ this.retokenizeFrom(line - 1);
+ this.dirtyRows.add(line - 1);
+ }
+ } else if (e.key === "Delete") {
+ this.lines[line] = text.slice(0, col) + text.slice(col + 1);
+ this.edited(line);
+ this.retokenizeFrom(line);
+ } else if (e.key === "Tab") {
+ const n = 4 - (col % 4);
+ this.lines[line] = text.slice(0, col) + " ".repeat(n) + text.slice(col);
+ this.caret.col += n;
+ this.edited(line);
+ this.retokenizeFrom(line);
+ } else if (e.key === "ArrowLeft") {
+ if (col > 0) this.caret.col--;
+ else if (line > 0) this.caret = { line: line - 1, col: this.lines[line - 1].length };
+ this.hideSuggest();
+ } else if (e.key === "ArrowRight") {
+ if (col < text.length) this.caret.col++;
+ else if (line < this.lines.length - 1) this.caret = { line: line + 1, col: 0 };
+ this.hideSuggest();
+ } else if (e.key === "ArrowUp" || e.key === "ArrowDown") {
+ const d = e.key === "ArrowUp" ? -1 : 1;
+ const l = Math.max(0, Math.min(this.lines.length - 1, line + d));
+ this.goalCol = this.goalCol ?? col;
+ this.caret = { line: l, col: Math.min(this.lines[l].length, this.goalCol) };
+ this.hideSuggest();
+ this.updateCaret(true, true);
+ this.renderRows(this.dirtyRows);
+ return true;
+ } else if (e.key === "Home") {
+ const lead = /^ */.exec(text)[0].length;
+ this.caret.col = col === lead ? 0 : lead;
+ } else if (e.key === "End") {
+ this.caret.col = text.length;
+ } else if (e.key === "PageDown" || e.key === "PageUp") {
+ const page = Math.max(1, Math.floor(this.visibleLines()) - 1);
+ const d = e.key === "PageDown" ? page : -page;
+ const l = Math.max(0, Math.min(this.lines.length - 1, line + d));
+ this.caret = { line: l, col: Math.min(this.lines[l].length, col) };
+ this.scrollTo(this.scroller.scrollTop + d * this.lineHeight);
+ } else if (e.key === "Escape") {
+ this.hideSuggest();
+ } else {
+ handled = false;
+ }
+ if (!["ArrowUp", "ArrowDown"].includes(e.key)) this.goalCol = null;
+ this.renderRows(this.dirtyRows);
+ this.renderMinimapRows(this.dirtyRows);
+ this.updateCaret(true);
+ return handled;
+ }
+
+ typeChar(ch) {
+ const { line, col } = this.caret;
+ const text = this.lines[line];
+ const next = text[col] || "";
+ const closers = { "(": ")", "[": "]" };
+ if ((ch === ")" || ch === "]" || ch === '"' || ch === "'") && next === ch) {
+ this.caret.col++;
+ this.updateSuggest();
+ return;
+ }
+ let ins = ch;
+ if (closers[ch] && (!next || /[\s)\],:]/.test(next))) ins = ch + closers[ch];
+ else if ((ch === '"' || ch === "'") && !/\w/.test(text[col - 1] || "") && text[col - 1] !== ch && (!next || /[\s)\],:]/.test(next))) ins = ch + ch;
+ let newText = text.slice(0, col) + ins + text.slice(col);
+ let newCol = col + 1;
+ if (this.lang === "c" && ch === "}" && /^ +$/.test(text.slice(0, col)) && col >= 4) {
+ newText = text.slice(0, col - 4) + "}" + text.slice(col);
+ newCol = col - 3;
+ }
+ this.lines[line] = newText;
+ this.caret.col = newCol;
+ this.edited(line);
+ this.retokenizeFrom(line);
+ this.dirtyRows.add(line);
+ this.updateSuggest();
+ }
+
+ wordBeforeCaret() {
+ const { line, col } = this.caret;
+ const m = /[A-Za-z_]\w*$/.exec(this.lines[line].slice(0, col));
+ return m ? m[0] : "";
+ }
+
+ updateSuggest() {
+ const w = this.wordBeforeCaret();
+ if (w.length < 2) return this.hideSuggest();
+ if (!this.vocab) {
+ const counts = new Map();
+ for (const l of this.lines) for (const m of l.matchAll(/[A-Za-z_]\w{2,}/g)) counts.set(m[0], (counts.get(m[0]) || 0) + 1);
+ this.vocab = [...counts.entries()].sort((a, b) => b[1] - a[1]).map((x) => x[0]);
+ }
+ const lw = w.toLowerCase();
+ const items = this.vocab.filter((v) => v.toLowerCase().startsWith(lw) && v !== w).slice(0, 8);
+ if (!items.length) return this.hideSuggest();
+ const kinds = ["method", "variable", "field", "keyword", "class"];
+ this.suggest.innerHTML = items
+ .map((it, k) => {
+ const kind = /^[A-Z]/.test(it) ? "class" : kinds[(it.length * 7 + k) % 3];
+ return `<div class="sg-item${k === 0 ? " active" : ""}"><span class="sg-icon ${kind}"></span><b>${esc(it.slice(0, w.length))}</b>${esc(it.slice(w.length))}${k === 0 ? `<span class="sg-detail">${kind}</span>` : ""}</div>`;
+ })
+ .join("");
+ const { line, col } = this.caret;
+ this.suggest.style.left = `${this.gutter + (col - w.length) * this.cw - 4}px`;
+ this.suggest.style.top = `${(line + 1) * this.lineHeight + 2}px`;
+ this.suggest.style.display = "block";
+ }
+
+ hideSuggest() {
+ this.suggest.style.display = "none";
+ }
+
+ selectWord() {
+ const { line, col } = this.caret;
+ const t = this.lines[line];
+ let a = col;
+ let b = col;
+ while (a > 0 && /\w/.test(t[a - 1])) a--;
+ while (b < t.length && /\w/.test(t[b])) b++;
+ if (b <= a) return;
+ this.selEl.style.display = "block";
+ this.selEl.style.left = `${this.gutter + a * this.cw}px`;
+ this.selEl.style.top = `${line * this.lineHeight}px`;
+ this.selEl.style.width = `${(b - a) * this.cw}px`;
+ this.selEl.style.height = `${this.lineHeight}px`;
+ this.caret.col = b;
+ this.updateCaret(false);
+ }
+
+ clearSel() {
+ this.selEl.style.display = "none";
+ }
+
+ updateCaret(reveal, keepGoal) {
+ const { line, col } = this.caret;
+ const lh = this.lineHeight;
+ this.caretEl.style.transform = `translate(${this.gutter + col * this.cw}px, ${line * lh}px)`;
+ this.lineHL.style.transform = `translateY(${line * lh}px)`;
+ this.caretEl.classList.remove("blink");
+ void this.caretEl.offsetWidth;
+ clearTimeout(this.blinkTimer);
+ this.blinkTimer = setTimeout(() => this.caretEl.classList.add("blink"), 550);
+ const ln = this.rowEls[line] && this.rowEls[line].firstChild;
+ if (this.curLnEl && this.curLnEl !== ln) this.curLnEl.classList.remove("cur");
+ if (ln) ln.classList.add("cur");
+ this.curLnEl = ln;
+ if (reveal) {
+ const top = this.scroller.scrollTop;
+ const h = this.scroller.clientHeight;
+ const y = line * lh;
+ if (y < top) this.scrollTo(y - 2 * lh);
+ else if (y + lh > top + h) this.scrollTo(y + lh - h + 2 * lh);
+ }
+ this.onStatus({ line: line + 1, col: col + 1 });
+ }
+
+ renderMinimapFull() {
+ const dpr = window.devicePixelRatio || 1;
+ const w = this.minimap.clientWidth;
+ this.miniLineH = 2;
+ const total = this.lines.length * this.miniLineH;
+ this.mini = document.createElement("canvas");
+ this.mini.width = Math.round(w * dpr);
+ this.mini.height = Math.round((total + 200) * dpr);
+ this.miniCtx = this.mini.getContext("2d");
+ this.miniCtx.scale(dpr, dpr);
+ for (let i = 0; i < this.lines.length; i++) this.drawMiniLine(i);
+ this.minimap.width = Math.round(w * dpr);
+ this.minimap.height = Math.round(this.minimap.clientHeight * dpr);
+ }
+
+ drawMiniLine(i) {
+ const ctx = this.miniCtx;
+ const y = i * this.miniLineH;
+ ctx.clearRect(0, y, this.minimap.clientWidth, this.miniLineH);
+ let x = 4;
+ for (const [cls, text] of this.tokens[i] || []) {
+ const colr = this.minimapColors[cls] || this.minimapColors.plain;
+ let start = 0;
+ for (const seg of text.split(/(\s+)/)) {
+ if (seg && !/^\s+$/.test(seg)) {
+ ctx.fillStyle = colr;
+ ctx.fillRect(x + start * 1, y, seg.length * 1, this.miniLineH - 0.5);
+ }
+ start += seg.length;
+ }
+ x += text.length;
+ }
+ }
+
+ renderMinimapRows(rows) {
+ if (!rows || !rows.size || !this.miniCtx) return;
+ if (this.lines.length * this.miniLineH + 200 > this.mini.height / (window.devicePixelRatio || 1)) {
+ this.renderMinimapFull();
+ } else {
+ const first = Math.min(...rows);
+ for (let i = first; i < this.lines.length; i++) this.drawMiniLine(i);
+ }
+ this.updateScrollUI();
+ }
+
+ updateScrollUI() {
+ const sc = this.scroller;
+ const max = Math.max(1, sc.scrollHeight - sc.clientHeight);
+ const frac = sc.scrollTop / max;
+ const barH = this.vbar.clientHeight;
+ const thumbH = Math.max(20, (sc.clientHeight / sc.scrollHeight) * barH);
+ this.vthumb.style.height = `${thumbH}px`;
+ this.vthumb.style.transform = `translateY(${frac * (barH - thumbH)}px)`;
+ if (!this.mini) return;
+ const dpr = window.devicePixelRatio || 1;
+ const ctx = this.minimap.getContext("2d");
+ const mh = this.minimap.clientHeight;
+ const total = this.lines.length * this.miniLineH;
+ const firstLine = sc.scrollTop / this.lineHeight;
+ const visLines = sc.clientHeight / this.lineHeight;
+ const miniTop = total > mh ? frac * (total + visLines * this.miniLineH - mh) : 0;
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
+ ctx.clearRect(0, 0, this.minimap.width, this.minimap.height);
+ ctx.drawImage(this.mini, 0, Math.round(miniTop * dpr), this.minimap.width, this.minimap.height, 0, 0, this.minimap.width, this.minimap.height);
+ ctx.fillStyle = this.minimapColors.slider;
+ ctx.fillRect(0, Math.round((firstLine * this.miniLineH - miniTop) * dpr), this.minimap.width, Math.round(visLines * this.miniLineH * dpr));
+ }
+ }
+
+ window.CodeEditor = CodeEditor;
+})();
diff --git a/capcodec/bench/corpus/pages/common/slides.css b/capcodec/bench/corpus/pages/common/slides.css
new file mode 100644
index 000000000..bbdf6df2d
--- /dev/null
+++ b/capcodec/bench/corpus/pages/common/slides.css
@@ -0,0 +1,409 @@
+* {
+ box-sizing: border-box;
+}
+html,
+body {
+ margin: 0;
+ height: 100%;
+ overflow: hidden;
+ background: #000;
+ font-family: "Noto Sans", "Liberation Sans", sans-serif;
+}
+#deck {
+ position: absolute;
+ inset: 0;
+ overflow: hidden;
+}
+.slide {
+ position: absolute;
+ inset: 0;
+ background: #fff;
+ color: #1d2433;
+ display: none;
+ overflow: hidden;
+ padding: 92px 120px 80px;
+}
+.slide.show {
+ display: block;
+}
+.slide h1 {
+ font-size: 64px;
+ font-weight: 700;
+ letter-spacing: -0.01em;
+ margin: 0 0 18px;
+ line-height: 1.12;
+}
+.slide h2 {
+ font-size: 54px;
+ font-weight: 700;
+ margin: 0 0 40px;
+ letter-spacing: -0.01em;
+ line-height: 1.15;
+}
+.slide .kicker {
+ font-size: 22px;
+ font-weight: 700;
+ letter-spacing: 0.12em;
+ text-transform: uppercase;
+ color: #4f46e5;
+ margin-bottom: 14px;
+}
+.slide ul.b {
+ margin: 0;
+ padding-left: 0;
+ list-style: none;
+ font-size: 34px;
+ line-height: 1.45;
+}
+.slide ul.b li {
+ position: relative;
+ padding-left: 48px;
+ margin-bottom: 22px;
+}
+.slide ul.b li::before {
+ content: "";
+ position: absolute;
+ left: 4px;
+ top: 18px;
+ width: 16px;
+ height: 16px;
+ border-radius: 4px;
+ background: #4f46e5;
+}
+.slide ul.b li .sub {
+ display: block;
+ font-size: 25px;
+ color: #5b6475;
+ line-height: 1.4;
+ margin-top: 4px;
+}
+.slide .foot {
+ position: absolute;
+ left: 120px;
+ right: 120px;
+ bottom: 34px;
+ display: flex;
+ align-items: center;
+ font-size: 18px;
+ color: #8a93a6;
+ gap: 14px;
+}
+.slide .foot .logo {
+ width: 26px;
+ height: 26px;
+ border-radius: 7px;
+ background: linear-gradient(135deg, #6366f1, #06b6d4);
+}
+.slide .foot .num {
+ margin-left: auto;
+ font-variant-numeric: tabular-nums;
+}
+.slide.dark {
+ color: #fff;
+}
+.slide.dark .foot {
+ color: #ffffffa0;
+}
+.slide.title-slide {
+ background: radial-gradient(1200px 700px at 78% 18%, #7c3aed 0%, transparent 60%), radial-gradient(900px 600px at 12% 90%, #0891b2 0%, transparent 60%), linear-gradient(135deg, #111827, #1e1b4b);
+ display: none;
+ padding: 0 140px;
+}
+.slide.title-slide.show,
+.slide.end-slide.show {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+}
+.slide.title-slide h1 {
+ font-size: 104px;
+ margin-bottom: 26px;
+ line-height: 1.04;
+}
+.slide.title-slide .subt {
+ font-size: 38px;
+ color: #c7d2fe;
+ margin-bottom: 70px;
+}
+.slide.title-slide .by {
+ display: flex;
+ align-items: center;
+ gap: 22px;
+ font-size: 26px;
+ color: #e0e7ff;
+}
+.avatar {
+ border-radius: 50%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: #fff;
+ font-weight: 700;
+}
+.agenda {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 28px 60px;
+ margin-top: 20px;
+}
+.agenda .ai {
+ display: flex;
+ gap: 28px;
+ align-items: flex-start;
+ border-top: 3px solid #e5e7eb;
+ padding-top: 22px;
+}
+.agenda .ai .n {
+ font-size: 54px;
+ font-weight: 700;
+ color: #4f46e5;
+ line-height: 1;
+ width: 76px;
+}
+.agenda .ai .t {
+ font-size: 34px;
+ font-weight: 700;
+}
+.agenda .ai .d {
+ font-size: 24px;
+ color: #5b6475;
+ margin-top: 6px;
+}
+.chips {
+ display: flex;
+ gap: 22px;
+ margin-top: 40px;
+}
+.chip {
+ background: #eef2ff;
+ color: #3730a3;
+ border-radius: 999px;
+ padding: 12px 26px;
+ font-size: 24px;
+ font-weight: 600;
+}
+.cols2 {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 56px;
+}
+.card {
+ border-radius: 24px;
+ padding: 40px 44px;
+ background: #f6f7fb;
+ border: 2px solid #e6e8f0;
+}
+.card h3 {
+ font-size: 36px;
+ margin: 0 0 22px;
+ display: flex;
+ align-items: center;
+ gap: 16px;
+}
+.card.after {
+ background: #ecfdf5;
+ border-color: #a7f3d0;
+}
+.card .row {
+ font-size: 27px;
+ padding: 14px 0;
+ border-bottom: 1px solid #00000014;
+ display: flex;
+ justify-content: space-between;
+}
+.card .row b {
+ font-variant-numeric: tabular-nums;
+}
+.kpis {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 40px;
+ margin-top: 60px;
+}
+.kpi .v {
+ font-size: 128px;
+ font-weight: 800;
+ letter-spacing: -0.03em;
+ line-height: 1;
+ background: linear-gradient(135deg, #4f46e5, #0891b2);
+ -webkit-background-clip: text;
+ background-clip: text;
+ color: transparent;
+}
+.kpi .l {
+ font-size: 30px;
+ font-weight: 700;
+ margin-top: 20px;
+}
+.kpi .s {
+ font-size: 24px;
+ color: #5b6475;
+ margin-top: 8px;
+ line-height: 1.4;
+}
+.quote {
+ font-family: "Liberation Serif", "DejaVu Serif", serif;
+ font-size: 62px;
+ line-height: 1.3;
+ margin: 40px 0 60px;
+ max-width: 1500px;
+}
+.quote::before {
+ content: "“";
+ color: #4f46e5;
+ font-size: 160px;
+ line-height: 0;
+ position: relative;
+ top: 54px;
+ margin-right: 12px;
+}
+.qby {
+ display: flex;
+ align-items: center;
+ gap: 26px;
+ font-size: 28px;
+}
+.qby .r {
+ color: #5b6475;
+ font-size: 24px;
+}
+table.rm {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 27px;
+}
+table.rm th {
+ text-align: left;
+ color: #5b6475;
+ font-size: 22px;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ padding: 0 0 16px;
+ border-bottom: 3px solid #e5e7eb;
+}
+table.rm td {
+ padding: 22px 0;
+ border-bottom: 1px solid #e5e7eb;
+}
+.pill {
+ display: inline-block;
+ border-radius: 999px;
+ padding: 6px 20px;
+ font-size: 21px;
+ font-weight: 700;
+}
+.pill.done {
+ background: #dcfce7;
+ color: #166534;
+}
+.pill.prog {
+ background: #dbeafe;
+ color: #1e40af;
+}
+.pill.risk {
+ background: #fef3c7;
+ color: #92400e;
+}
+.pill.plan {
+ background: #f3f4f6;
+ color: #374151;
+}
+.timeline {
+ position: relative;
+ margin-top: 120px;
+ height: 420px;
+}
+.timeline .line {
+ position: absolute;
+ left: 0;
+ right: 0;
+ top: 120px;
+ height: 6px;
+ background: linear-gradient(90deg, #4f46e5, #06b6d4);
+ border-radius: 3px;
+}
+.timeline .ms {
+ position: absolute;
+ top: 0;
+ width: 300px;
+ transform: translateX(-50%);
+ text-align: center;
+}
+.timeline .ms .d {
+ font-size: 24px;
+ color: #4f46e5;
+ font-weight: 700;
+ height: 90px;
+}
+.timeline .ms .dot {
+ width: 34px;
+ height: 34px;
+ border-radius: 50%;
+ background: #fff;
+ border: 7px solid #4f46e5;
+ margin: 0 auto 30px;
+}
+.timeline .ms .t {
+ font-size: 29px;
+ font-weight: 700;
+}
+.timeline .ms .x {
+ font-size: 22px;
+ color: #5b6475;
+ margin-top: 8px;
+ line-height: 1.4;
+}
+.build {
+ opacity: 0;
+}
+.build.on {
+ opacity: 1;
+ transition: opacity 0.35s ease, transform 0.35s ease;
+ transform: none;
+}
+.photo-cap {
+ position: absolute;
+ left: 120px;
+ bottom: 120px;
+ color: #fff;
+ text-shadow: 0 2px 24px #0006;
+}
+.photo-cap .k {
+ font-size: 24px;
+ font-weight: 700;
+ letter-spacing: 0.14em;
+ text-transform: uppercase;
+ opacity: 0.9;
+}
+.photo-cap .t {
+ font-size: 84px;
+ font-weight: 800;
+ line-height: 1.05;
+ margin-top: 12px;
+ max-width: 1100px;
+}
+#webcam {
+ position: absolute;
+ display: none;
+ width: 320px;
+ height: 320px;
+ border-radius: 50%;
+ overflow: hidden;
+ box-shadow: 0 10px 40px #0000004d, 0 0 0 4px #ffffff;
+ z-index: 50;
+ cursor: grab;
+ left: 72px;
+ top: 688px;
+}
+#webcam.on {
+ display: block;
+}
+#webcam.drag {
+ cursor: grabbing;
+ box-shadow: 0 18px 60px #00000066, 0 0 0 4px #ffffff;
+}
+#cam {
+ width: 320px;
+ height: 320px;
+ display: block;
+}
diff --git a/capcodec/bench/corpus/pages/common/slides.js b/capcodec/bench/corpus/pages/common/slides.js
new file mode 100644
index 000000000..4e1d80af4
--- /dev/null
+++ b/capcodec/bench/corpus/pages/common/slides.js
@@ -0,0 +1,319 @@
+(() => {
+ const deck = document.getElementById("deck");
+ const TOTAL = 14;
+ const foot = (n, dark) => `<div class="foot"><span class="logo"></span><span>Capture Pipeline 2.0 · Q3 Review</span><span class="num">${n} / ${TOTAL}</span></div>`;
+
+ function barChart() {
+ const groups = [
+ ["macOS (Apple Silicon)", 640, 210],
+ ["macOS (Intel)", 1480, 690],
+ ["Windows 11", 1910, 760],
+ ["Windows 10", 2350, 980],
+ ["Linux (X11)", 1720, 820],
+ ];
+ const W = 1560;
+ const H = 640;
+ const x0 = 150;
+ const y0 = 560;
+ const max = 2500;
+ let s = `<svg width="${W}" height="${H}" font-family="Noto Sans">`;
+ for (let v = 0; v <= max; v += 500) {
+ const y = y0 - (v / max) * 480;
+ s += `<line x1="${x0}" x2="${W - 20}" y1="${y}" y2="${y}" stroke="#e5e7eb" stroke-width="2"/><text x="${x0 - 18}" y="${y + 8}" text-anchor="end" font-size="22" fill="#6b7280">${v.toLocaleString("en-US")}</text>`;
+ }
+ const gw = (W - x0 - 40) / groups.length;
+ groups.forEach(([name, a, b], i) => {
+ const gx = x0 + 30 + i * gw;
+ const ha = (a / max) * 480;
+ const hb = (b / max) * 480;
+ s += `<rect x="${gx + 20}" y="${y0 - ha}" width="96" height="${ha}" rx="8" fill="#c7d2fe"/>`;
+ s += `<rect x="${gx + 126}" y="${y0 - hb}" width="96" height="${hb}" rx="8" fill="#4f46e5"/>`;
+ s += `<text x="${gx + 68}" y="${y0 - ha - 14}" text-anchor="middle" font-size="22" fill="#4b5563">${a}</text>`;
+ s += `<text x="${gx + 174}" y="${y0 - hb - 14}" text-anchor="middle" font-size="22" font-weight="700" fill="#312e81">${b}</text>`;
+ s += `<text x="${gx + 121}" y="${y0 + 42}" text-anchor="middle" font-size="24" fill="#374151">${name}</text>`;
+ });
+ s += `<line x1="${x0}" x2="${W - 20}" y1="${y0}" y2="${y0}" stroke="#9ca3af" stroke-width="2"/>`;
+ s += `<rect x="${W - 360}" y="10" width="26" height="26" rx="5" fill="#c7d2fe"/><text x="${W - 322}" y="31" font-size="24" fill="#374151">Q2</text>`;
+ s += `<rect x="${W - 250}" y="10" width="26" height="26" rx="5" fill="#4f46e5"/><text x="${W - 212}" y="31" font-size="24" fill="#374151">Q3</text>`;
+ s += `<text x="20" y="300" font-size="22" fill="#6b7280" transform="rotate(-90 40 300)">milliseconds</text></svg>`;
+ return s;
+ }
+
+ function lineChart() {
+ const W = 1640;
+ const H = 620;
+ const x0 = 110;
+ const y0 = 540;
+ const pts = [];
+ let v = 9.8;
+ for (let i = 0; i < 26; i++) {
+ v += Math.sin(i * 1.7) * 0.6 - (i > 8 ? 0.28 : 0.02);
+ if (i === 15) v += 1.4;
+ pts.push(Math.max(3.2, v));
+ }
+ let s = `<svg width="${W}" height="${H}" font-family="Noto Sans">`;
+ for (let k = 0; k <= 12; k += 2) {
+ const y = y0 - (k / 12) * 460;
+ s += `<line x1="${x0}" x2="${W - 10}" y1="${y}" y2="${y}" stroke="#eef0f4" stroke-width="2"/><text x="${x0 - 16}" y="${y + 8}" text-anchor="end" font-size="22" fill="#6b7280">${k}</text>`;
+ }
+ const px = (i) => x0 + 20 + i * ((W - x0 - 60) / 25);
+ const py = (val) => y0 - (val / 12) * 460;
+ const line = pts.map((p, i) => `${px(i).toFixed(1)},${py(p).toFixed(1)}`).join(" ");
+ s += `<polygon points="${px(0)},${y0} ${line} ${px(25)},${y0}" fill="#4f46e5" opacity=".08"/>`;
+ s += `<polyline points="${line}" fill="none" stroke="#4f46e5" stroke-width="5" stroke-linejoin="round"/>`;
+ pts.forEach((p, i) => {
+ if (i % 5 === 0 || i === 25) s += `<circle cx="${px(i)}" cy="${py(p)}" r="8" fill="#fff" stroke="#4f46e5" stroke-width="4"/>`;
+ if (i % 4 === 0) s += `<text x="${px(i)}" y="${y0 + 40}" text-anchor="middle" font-size="22" fill="#6b7280">W${27 + i}</text>`;
+ });
+ s += `<line x1="${px(15)}" x2="${px(15)}" y1="${py(pts[15]) - 30}" y2="${py(pts[15]) - 100}" stroke="#f59e0b" stroke-width="3"/>`;
+ s += `<text x="${px(15) + 14}" y="${py(pts[15]) - 104}" font-size="24" fill="#b45309" font-weight="700">CDN incident (Aug 14)</text>`;
+ s += `<line x1="${px(9)}" x2="${px(9)}" y1="${y0}" y2="40" stroke="#10b981" stroke-width="3" stroke-dasharray="10 8"/>`;
+ s += `<text x="${px(9) + 14}" y="62" font-size="24" fill="#047857" font-weight="700">Resumable uploads ship</text>`;
+ s += `<line x1="${x0}" x2="${W - 10}" y1="${y0}" y2="${y0}" stroke="#9ca3af" stroke-width="2"/></svg>`;
+ return s;
+ }
+
+ function donut() {
+ const parts = [
+ ["1080p", 52, "#4f46e5"],
+ ["1440p", 17, "#06b6d4"],
+ ["4K", 21, "#a855f7"],
+ ["720p and below", 10, "#f59e0b"],
+ ];
+ let a0 = -Math.PI / 2;
+ let s = '<svg width="620" height="620" viewBox="-310 -310 620 620">';
+ for (const [, pct, c] of parts) {
+ const a1 = a0 + (pct / 100) * Math.PI * 2;
+ const large = a1 - a0 > Math.PI ? 1 : 0;
+ const r = 280;
+ const ri = 170;
+ s += `<path d="M${Math.cos(a0) * r} ${Math.sin(a0) * r} A${r} ${r} 0 ${large} 1 ${Math.cos(a1) * r} ${Math.sin(a1) * r} L${Math.cos(a1) * ri} ${Math.sin(a1) * ri} A${ri} ${ri} 0 ${large} 0 ${Math.cos(a0) * ri} ${Math.sin(a0) * ri}Z" fill="${c}"/>`;
+ a0 = a1;
+ }
+ s += '<text x="0" y="-6" text-anchor="middle" font-family="Noto Sans" font-size="76" font-weight="800" fill="#1d2433">1.9M</text><text x="0" y="46" text-anchor="middle" font-family="Noto Sans" font-size="28" fill="#6b7280">recordings in Q3</text></svg>';
+ const legend = parts
+ .map(([n, p, c]) => `<div style="display:flex;align-items:center;gap:22px;font-size:34px;margin-bottom:30px"><span style="width:30px;height:30px;border-radius:8px;background:${c}"></span><span style="flex:1">${n}</span><b>${p}%</b></div>`)
+ .join("");
+ return `<div style="display:flex;gap:120px;align-items:center;margin-top:10px">${s}<div style="width:640px">${legend}<div style="font-size:24px;color:#5b6475;line-height:1.45;margin-top:40px">4K share doubled since Q1, driven by new external displays and the 5K iMac refresh.</div></div></div>`;
+ }
+
+ function landscape() {
+ let ridges = "";
+ const layers = [
+ ["#3b4a7a", 0.62, 90, 1],
+ ["#2a3560", 0.7, 70, 2],
+ ["#1b2343", 0.78, 50, 3],
+ ];
+ for (const [c, base, amp, seed] of layers) {
+ let d = `M0 1080 L0 ${base * 1080}`;
+ for (let x = 0; x <= 1920; x += 40) {
+ const y = base * 1080 - Math.abs(Math.sin(x / (180 + seed * 40) + seed) * amp) - Math.sin(x / 63 + seed * 2) * amp * 0.25;
+ d += ` L${x} ${y.toFixed(1)}`;
+ }
+ d += " L1920 1080Z";
+ ridges += `<path d="${d}" fill="${c}"/>`;
+ }
+ return `<svg width="1920" height="1080" viewBox="0 0 1920 1080" style="position:absolute;inset:0" filter="url(#grain)">
+<defs><linearGradient id="sky" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#1e3a8a"/><stop offset=".45" stop-color="#c2649a"/><stop offset=".62" stop-color="#f6a05c"/><stop offset=".7" stop-color="#ffd59e"/></linearGradient>
+<radialGradient id="sun" cx="0.5" cy="0.5" r="0.5"><stop offset="0" stop-color="#fff7d6"/><stop offset=".25" stop-color="#ffe29a" stop-opacity=".95"/><stop offset="1" stop-color="#ffb46b" stop-opacity="0"/></radialGradient>
+<linearGradient id="lake" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#f3a667"/><stop offset=".3" stop-color="#7a5a8c"/><stop offset="1" stop-color="#101a36"/></linearGradient></defs>
+<rect width="1920" height="1080" fill="url(#sky)"/>
+<circle cx="1260" cy="700" r="380" fill="url(#sun)"/>
+<g filter="url(#blur8)" opacity=".55"><ellipse cx="520" cy="300" rx="420" ry="46" fill="#f8c3d0"/><ellipse cx="1500" cy="220" rx="360" ry="34" fill="#f2b5c8"/><ellipse cx="980" cy="420" rx="520" ry="30" fill="#ffd1a6"/></g>
+${ridges}
+<rect y="842" width="1920" height="238" fill="url(#lake)"/>
+<g opacity=".35" filter="url(#blur3)">${Array.from({ length: 18 }, (_, i) => `<rect x="${1110 + Math.sin(i * 2.1) * 120}" y="${860 + i * 11}" width="${300 - i * 12}" height="3" fill="#ffe8c2"/>`).join("")}</g>
+<path d="M0 842 L1920 842" stroke="#ffd8a8" stroke-width="2" opacity=".5"/>
+</svg>`;
+ }
+
+ const slides = [
+ {
+ cls: "title-slide dark",
+ tr: "cut",
+ html: `<div class="kicker" style="color:#a5b4fc">Desktop &amp; Media · Q3 2026</div><h1>Capture Pipeline 2.0</h1><div class="subt">What we shipped, what we learned, and what comes next</div>
+<div class="by"><div class="avatar" style="width:72px;height:72px;background:#7c3aed;font-size:30px">ML</div><div>Maya Lindqvist<br><span style="color:#a5b4fc;font-size:22px">Engineering Manager · October 7, 2026</span></div></div>`,
+ },
+ {
+ tr: "fade",
+ html: `<div class="kicker">Agenda</div><h2>Today we will cover</h2><div class="agenda">
+${[
+ ["01", "Where we started", "Baseline from the Q2 review"],
+ ["02", "Results", "Startup time, uploads, file size"],
+ ["03", "Customer voice", "What users told us"],
+ ["04", "Roadmap", "Q4 milestones and owners"],
+ ["05", "Risks", "Memory growth on long recordings"],
+ ["06", "Q&amp;A", "Open discussion"],
+]
+ .map(([n, t, d]) => `<div class="ai"><div class="n">${n}</div><div><div class="t">${t}</div><div class="d">${d}</div></div></div>`)
+ .join("")}</div>`,
+ },
+ {
+ tr: "push",
+ html: `<div class="kicker">01 · Baseline</div><h2>Where we started in July</h2><ul class="b">
+<li>Recording took almost two seconds to start on Windows<span class="sub">Most of the time was spent creating the encoder and probing the camera</span></li>
+<li>One in a hundred uploads failed on the first attempt<span class="sub">Hotel and conference Wi-Fi were the worst offenders</span></li>
+<li>Text in screen recordings looked soft at 1080p<span class="sub">The encoder was tuned for camera footage, not for user interfaces</span></li></ul>
+<div class="chips"><span class="chip">1.8 s to first frame</span><span class="chip">9.4 failures / 1,000</span><span class="chip">38 MB per minute</span></div>`,
+ },
+ {
+ tr: "fade",
+ html: `<div class="kicker">02 · Results</div><h2>Time to first frame, by platform</h2>${barChart()}`,
+ },
+ {
+ cls: "dark",
+ tr: "cover",
+ html: `${landscape()}<div class="photo-cap"><div class="k">Design principle</div><div class="t">Fast should feel calm, not hurried.</div></div>`,
+ },
+ {
+ tr: "cut",
+ html: `<div class="kicker">02 · Results</div><h2>Before and after the new pipeline</h2><div class="cols2">
+<div class="card"><h3>⏱ Q2 pipeline</h3><div class="row"><span>Encoder startup</span><b>1,240 ms</b></div><div class="row"><span>Camera probe</span><b>410 ms</b></div><div class="row"><span>First segment upload</span><b>6.2 s</b></div><div class="row"><span>Peak memory (30 min)</span><b>1.9 GB</b></div><div class="row"><span>CPU while idle</span><b>7.5%</b></div></div>
+<div class="card after"><h3>⚡ Q3 pipeline</h3><div class="row"><span>Encoder startup</span><b>380 ms</b></div><div class="row"><span>Camera probe</span><b>95 ms</b></div><div class="row"><span>First segment upload</span><b>1.4 s</b></div><div class="row"><span>Peak memory (30 min)</span><b>1.1 GB</b></div><div class="row"><span>CPU while idle</span><b>2.1%</b></div></div></div>`,
+ },
+ {
+ tr: "push",
+ html: `<div class="kicker">02 · Results</div><h2>Failed uploads per 1,000 recordings</h2>${lineChart()}`,
+ },
+ {
+ tr: "fade",
+ html: `<div class="kicker">02 · Results</div><h2>The quarter in three numbers</h2><div class="kpis">
+<div class="kpi"><div class="v">−61%</div><div class="l">Time to first frame</div><div class="s">Median across all desktop platforms, measured on 1.2M sessions</div></div>
+<div class="kpi"><div class="v">4,118</div><div class="l">Recordings recovered</div><div class="s">Uploads that resumed after a dropped connection instead of failing</div></div>
+<div class="kpi"><div class="v">99.72%</div><div class="l">Crash-free sessions</div><div class="s">Up from 99.31% in Q2, the best result since launch</div></div></div>`,
+ },
+ {
+ tr: "cover",
+ html: `<div class="kicker">03 · Customer voice</div><div class="quote">I hit record, explain the bug, and the link is already in my clipboard before I have finished talking. It feels like the app is waiting for me, not the other way round.</div>
+<div class="qby"><div class="avatar" style="width:84px;height:84px;background:#0891b2;font-size:32px">PR</div><div><b>Priya Raman</b><div class="r">Staff Engineer, Northwind Logistics</div></div></div>`,
+ },
+ {
+ tr: "fade",
+ html: `<div class="kicker">04 · Roadmap</div><h2>Q4 milestones</h2><table class="rm"><tr><th>Milestone</th><th>Owner</th><th>Target</th><th>Status</th></tr>
+<tr><td>Frame pool rewrite for long recordings</td><td>Marcus Feld</td><td>Oct 21</td><td><span class="pill prog">In progress</span></td></tr>
+<tr><td>Screen content encoder, beta</td><td>Priya Raman</td><td>Nov 4</td><td><span class="pill prog">In progress</span></td></tr>
+<tr><td>Windows on ARM native build</td><td>Daniel Okafor</td><td>Nov 18</td><td><span class="pill risk">At risk</span></td></tr>
+<tr><td>Camera overlay GPU compositing</td><td>Lena Hoffmann</td><td>Dec 2</td><td><span class="pill plan">Planned</span></td></tr>
+<tr><td>Upload resume on mobile networks</td><td>Sam Whitaker</td><td>Sep 30</td><td><span class="pill done">Done</span></td></tr></table>`,
+ },
+ {
+ tr: "push",
+ html: `<div class="kicker">04 · Roadmap</div><h2>How the next quarter fits together</h2><div class="timeline"><div class="line"></div>
+${[
+ ["Oct 7", "Q3 review", "Today", 6],
+ ["Oct 21", "Frame pool", "Fix memory growth", 26],
+ ["Nov 4", "Encoder beta", "Opt-in for teams", 48],
+ ["Nov 18", "ARM build", "Native Windows on ARM", 70],
+ ["Dec 2", "GPU overlay", "Camera bubble on GPU", 92],
+]
+ .map(([d, t, x, p]) => `<div class="ms" style="left:${p}%"><div class="d">${d}</div><div class="dot"></div><div class="t">${t}</div><div class="x">${x}</div></div>`)
+ .join("")}</div>`,
+ },
+ {
+ tr: "cut",
+ build: 3,
+ html: `<div class="kicker">05 · Risks</div><h2>What could still go wrong</h2><ul class="b">
+<li>Memory growth on long recordings with the camera enabled<span class="sub">Seen mostly on 8 GB machines after about 30 minutes</span></li>
+<li class="build">Driver bugs in hardware encoders on older Intel GPUs<span class="sub">We fall back to software encoding, which costs battery life</span></li>
+<li class="build">Windows on ARM toolchain is still changing<span class="sub">Two of our dependencies do not publish ARM64 builds yet</span></li>
+<li class="build">Beta feedback may arrive late in the quarter<span class="sub">We are recruiting 40 design partners to test early</span></li></ul>`,
+ },
+ {
+ tr: "fade",
+ html: `<div class="kicker">Appendix</div><h2>Recording mix by resolution</h2>${donut()}`,
+ },
+ {
+ cls: "title-slide dark end-slide",
+ tr: "fade",
+ html: `<h1 style="font-size:120px">Thank you</h1><div class="subt">Questions, ideas and complaints are all welcome in #capture-pipeline</div>`,
+ },
+ ];
+
+ const els = slides.map((s, i) => {
+ const d = document.createElement("div");
+ d.className = `slide ${s.cls || ""}`;
+ d.innerHTML = s.html + (i > 0 && i < slides.length - 1 ? foot(i + 1) : "");
+ deck.append(d);
+ return d;
+ });
+ let cur = 0;
+ let buildStep = 0;
+ let anims = [];
+ els[0].classList.add("show");
+
+ function finishAnims() {
+ for (const a of anims) a.finish();
+ anims = [];
+ }
+
+ function go(next) {
+ if (next < 0 || next >= els.length || next === cur) return;
+ finishAnims();
+ const from = els[cur];
+ const to = els[next];
+ const tr = next > cur ? slides[next].tr : "cut";
+ to.classList.add("show");
+ for (const b of to.querySelectorAll(".build")) b.classList.remove("on");
+ buildStep = 0;
+ const opts = { duration: tr === "fade" ? 600 : 650, easing: "cubic-bezier(.2,.7,.2,1)", fill: "both" };
+ const done = () => {
+ from.classList.remove("show");
+ from.style.zIndex = "";
+ to.style.zIndex = "";
+ };
+ cap.event("slide", { index: next, transition: tr });
+ cur = next;
+ if (tr === "cut") {
+ done();
+ return;
+ }
+ to.style.zIndex = 2;
+ from.style.zIndex = 1;
+ let a;
+ if (tr === "fade") {
+ a = to.animate([{ opacity: 0 }, { opacity: 1 }], opts);
+ } else if (tr === "push") {
+ a = to.animate([{ transform: "translateX(100%)" }, { transform: "translateX(0)" }], opts);
+ anims.push(from.animate([{ transform: "translateX(0)" }, { transform: "translateX(-100%)" }], opts));
+ } else {
+ a = to.animate([{ transform: "translateX(100%)" }, { transform: "translateX(0)" }], opts);
+ }
+ anims.push(a);
+ a.finished.then(() => {
+ for (const x of [from, to]) for (const an of x.getAnimations()) an.cancel();
+ done();
+ });
+ }
+
+ function advance() {
+ const s = slides[cur];
+ const builds = els[cur].querySelectorAll(".build");
+ if (s.build && buildStep < builds.length) {
+ builds[buildStep].classList.add("on");
+ buildStep++;
+ cap.event("build", { index: cur, step: buildStep });
+ return;
+ }
+ go(cur + 1);
+ }
+
+ window.addEventListener("keydown", (e) => {
+ if (["ArrowRight", "PageDown", " ", "Enter"].includes(e.key)) {
+ e.preventDefault();
+ advance();
+ } else if (["ArrowLeft", "PageUp", "Backspace"].includes(e.key)) {
+ e.preventDefault();
+ go(cur - 1);
+ }
+ });
+ window.addEventListener("mousedown", (e) => {
+ if (e.target.closest("#webcam")) return;
+ if (e.button === 0) advance();
+ });
+
+ window.capSlides = { go, advance, count: els.length, current: () => cur };
+ window.capTextRegions = () => [
+ [120, 80, 1400, 150],
+ [120, 240, 1500, 560],
+ ];
+})();
diff --git a/capcodec/bench/corpus/pages/common/terminal.js b/capcodec/bench/corpus/pages/common/terminal.js
new file mode 100644
index 000000000..e2f60c2e4
--- /dev/null
+++ b/capcodec/bench/corpus/pages/common/terminal.js
@@ -0,0 +1,150 @@
+(() => {
+ function mulberry32(seed) {
+ let a = seed >>> 0;
+ return () => {
+ a = (a + 0x6d2b79f5) >>> 0;
+ let t = a;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+ }
+ window.mulberry32 = mulberry32;
+
+ const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+
+ class Terminal {
+ constructor(host, opts) {
+ this.host = host;
+ this.rng = mulberry32(opts.seed || 7);
+ this.prompt = opts.prompt;
+ this.scroller = document.createElement("div");
+ this.scroller.className = "term-scroller";
+ this.scroller.dataset.scrollId = "terminal";
+ this.body = document.createElement("div");
+ this.body.className = "term-body";
+ this.scroller.append(this.body);
+ host.append(this.scroller);
+ this.input = "";
+ this.proc = null;
+ this.queue = [];
+ this.commands = opts.commands || {};
+ this.focused = false;
+ this.inputLine = null;
+ window.addEventListener("keydown", (e) => {
+ if (!this.focused) return;
+ if (this.key(e)) e.preventDefault();
+ });
+ host.addEventListener("mousedown", () => this.focus());
+ }
+
+ focus() {
+ this.focused = true;
+ this.host.classList.add("focused");
+ if (this.onFocus) this.onFocus();
+ }
+
+ blur() {
+ this.focused = false;
+ this.host.classList.remove("focused");
+ }
+
+ line(html, cls) {
+ const d = document.createElement("div");
+ d.className = `tl${cls ? ` ${cls}` : ""}`;
+ d.innerHTML = html || " ";
+ if (this.inputLine && this.inputLine.isConnected) this.body.insertBefore(d, this.inputLine);
+ else this.body.append(d);
+ while (this.body.childElementCount > 2000) this.body.firstChild.remove();
+ this.scrollBottom();
+ return d;
+ }
+
+ scrollBottom() {
+ this.scroller.scrollTop = this.scroller.scrollHeight;
+ }
+
+ showPrompt() {
+ this.inputLine = document.createElement("div");
+ this.inputLine.className = "tl";
+ this.body.append(this.inputLine);
+ this.input = "";
+ this.renderInput();
+ this.scrollBottom();
+ }
+
+ renderInput() {
+ if (!this.inputLine) return;
+ this.inputLine.innerHTML = `${this.prompt}${esc(this.input)}<span class="tcur"> </span>`;
+ }
+
+ key(e) {
+ if (e.ctrlKey && (e.key === "c" || e.key === "C")) {
+ if (this.proc) {
+ this.proc.stop = true;
+ const p = this.proc;
+ this.proc = null;
+ if (p.onInterrupt) for (const l of p.onInterrupt()) this.line(l);
+ this.showPrompt();
+ } else {
+ this.input += "^C";
+ this.renderInput();
+ this.inputLine = null;
+ this.showPrompt();
+ }
+ return true;
+ }
+ if (e.ctrlKey || e.altKey || e.metaKey) return false;
+ if (this.proc || !this.inputLine) return true;
+ if (e.key.length === 1) {
+ this.input += e.key;
+ this.renderInput();
+ } else if (e.key === "Backspace") {
+ this.input = this.input.slice(0, -1);
+ this.renderInput();
+ } else if (e.key === "Enter") {
+ const cmd = this.input.trim();
+ this.inputLine.innerHTML = `${this.prompt}${esc(this.input)}`;
+ this.inputLine = null;
+ this.run(cmd);
+ } else {
+ return e.key === "Tab";
+ }
+ return true;
+ }
+
+ run(cmd) {
+ cap.event("term_run", { cmd });
+ const name = Object.keys(this.commands).find((k) => cmd.startsWith(k));
+ if (!cmd) return this.showPrompt();
+ if (!name) {
+ this.line(esc(`${cmd.split(" ")[0]}: command not found`));
+ return this.showPrompt();
+ }
+ this.start(this.commands[name](cmd, this.rng, this));
+ }
+
+ start(proc) {
+ this.proc = proc;
+ const step = () => {
+ if (proc.stop) return;
+ const next = proc.next();
+ if (next.done) {
+ if (this.proc === proc) {
+ this.proc = null;
+ this.showPrompt();
+ }
+ return;
+ }
+ const [delay, lines] = next.value;
+ setTimeout(() => {
+ if (proc.stop) return;
+ for (const l of lines) this.line(l);
+ step();
+ }, delay);
+ };
+ step();
+ }
+ }
+ window.Terminal = Terminal;
+})();
diff --git a/capcodec/bench/corpus/pages/common/video.js b/capcodec/bench/corpus/pages/common/video.js
new file mode 100644
index 000000000..21f15ac7c
--- /dev/null
+++ b/capcodec/bench/corpus/pages/common/video.js
@@ -0,0 +1,64 @@
+(() => {
+ const video = document.getElementById("video");
+ const params = new URLSearchParams(location.search);
+ const steadyFrames = Number(params.get("steady") || 45);
+ const recent = [];
+ let callbacks = 0;
+ let readySet = false;
+
+ function wallclock(ms) {
+ return Math.round((performance.timeOrigin + ms) * 1000) / 1000;
+ }
+
+ function onFrame(_now, meta) {
+ callbacks += 1;
+ const rec = {
+ media_time: Math.round(meta.mediaTime * 1e6) / 1e6,
+ presented_frames: meta.presentedFrames,
+ expected_display: wallclock(meta.expectedDisplayTime),
+ presentation: wallclock(meta.presentationTime),
+ };
+ recent.push(rec);
+ if (recent.length > 120) recent.shift();
+ cap.event("video_frame", rec);
+ if (!readySet && callbacks >= steadyFrames) {
+ readySet = true;
+ capSetReady();
+ }
+ video.requestVideoFrameCallback(onFrame);
+ }
+
+ video.addEventListener("error", () => {
+ cap.event("video_error", { code: video.error?.code, message: video.error?.message });
+ });
+ for (const type of ["playing", "waiting", "stalled", "seeked"]) {
+ video.addEventListener(type, () => cap.event(`video_${type}`, { current_time: video.currentTime }));
+ }
+
+ window.capStats = () => {
+ const q = video.getVideoPlaybackQuality();
+ return {
+ current_time: video.currentTime,
+ paused: video.paused,
+ total_video_frames: q.totalVideoFrames,
+ dropped_video_frames: q.droppedVideoFrames,
+ frame_callbacks: callbacks,
+ video_width: video.videoWidth,
+ video_height: video.videoHeight,
+ };
+ };
+ window.capRecentFrames = (n) => recent.slice(-n);
+ window.capRestart = () => {
+ readySet = false;
+ callbacks = 0;
+ recent.length = 0;
+ window.capReady = false;
+ video.currentTime = 0;
+ video.play().catch((e) => cap.event("video_play_error", { message: String(e) }));
+ };
+ window.capTextRegions = () => [];
+
+ video.requestVideoFrameCallback(onFrame);
+ video.src = params.get("src");
+ video.play().catch((e) => cap.event("video_play_error", { message: String(e) }));
+})();
diff --git a/capcodec/bench/corpus/pages/common/webcam.js b/capcodec/bench/corpus/pages/common/webcam.js
new file mode 100644
index 000000000..b5b96775e
--- /dev/null
+++ b/capcodec/bench/corpus/pages/common/webcam.js
@@ -0,0 +1,211 @@
+(() => {
+ const params = new URLSearchParams(location.search);
+ const bubble = document.getElementById("webcam");
+ if (!bubble || params.get("webcam") !== "1") return;
+ bubble.classList.add("on");
+ const canvas = document.getElementById("cam");
+ const dpr = window.devicePixelRatio || 1;
+ const S = 320;
+ const N = Math.round(S * dpr);
+ canvas.width = N;
+ canvas.height = N;
+ const ctx = canvas.getContext("2d", { willReadFrequently: true });
+
+ let seed = 12345;
+ const rand = () => {
+ seed = (seed * 1664525 + 1013904223) >>> 0;
+ return seed / 4294967296;
+ };
+
+ const shelf = [];
+ for (let i = 0; i < 26; i++) {
+ shelf.push({
+ x: 8 + i * 12 + rand() * 4,
+ w: 7 + rand() * 6,
+ h: 34 + rand() * 30,
+ row: i % 2,
+ c: `hsl(${Math.floor(rand() * 360)}, ${35 + Math.floor(rand() * 30)}%, ${30 + Math.floor(rand() * 30)}%)`,
+ });
+ }
+
+ let noise = null;
+ let frame = 0;
+ let lastDraw = 0;
+
+ function draw(tms) {
+ const t = tms / 1000;
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ const exposure = 0.94 + 0.05 * Math.sin(t * 0.21) + 0.02 * Math.sin(t * 1.3);
+ const wall = ctx.createLinearGradient(0, 0, S, S);
+ wall.addColorStop(0, `hsl(${32 + 6 * Math.sin(t * 0.13)}, 32%, ${Math.round(70 * exposure)}%)`);
+ wall.addColorStop(1, `hsl(${24 + 4 * Math.sin(t * 0.17)}, 28%, ${Math.round(46 * exposure)}%)`);
+ ctx.fillStyle = wall;
+ ctx.fillRect(0, 0, S, S);
+ const win = ctx.createRadialGradient(260 + 6 * Math.sin(t * 0.3), 70, 10, 260, 70, 150);
+ win.addColorStop(0, `rgba(255,248,225,${0.55 + 0.1 * Math.sin(t * 0.4)})`);
+ win.addColorStop(1, "rgba(255,248,225,0)");
+ ctx.fillStyle = win;
+ ctx.fillRect(0, 0, S, S);
+ const sway = 3 * Math.sin(t * 0.37);
+ ctx.save();
+ ctx.globalAlpha = 0.55;
+ for (const b of shelf) {
+ ctx.fillStyle = b.c;
+ const y = b.row ? 112 : 46;
+ ctx.fillRect(b.x - 20 + sway * 0.4, y + (64 - b.h), b.w, b.h);
+ }
+ ctx.fillStyle = "rgba(70,45,25,0.6)";
+ ctx.fillRect(-10 + sway * 0.4, 110, 200, 6);
+ ctx.fillRect(-10 + sway * 0.4, 176, 200, 6);
+ ctx.restore();
+ const plant = ctx.createRadialGradient(286 + sway * 0.4, 220, 4, 286, 220, 60);
+ plant.addColorStop(0, "rgba(60,110,50,0.85)");
+ plant.addColorStop(1, "rgba(60,110,50,0)");
+ ctx.fillStyle = plant;
+ ctx.fillRect(200, 150, 140, 140);
+
+ const breathe = 1 + 0.012 * Math.sin(t * 1.55);
+ const hx = 162 + 9 * Math.sin(t * 0.61) + 3 * Math.sin(t * 1.9);
+ const hy = 128 + 4 * Math.sin(t * 0.83) + 2 * Math.sin(t * 2.3);
+ const tilt = 0.06 * Math.sin(t * 0.47);
+
+ ctx.save();
+ ctx.translate(160 + 4 * Math.sin(t * 0.61), 330);
+ ctx.scale(breathe, breathe);
+ const shirt = ctx.createLinearGradient(-150, -120, 150, 0);
+ shirt.addColorStop(0, "#2f4f7a");
+ shirt.addColorStop(0.5, "#3b6296");
+ shirt.addColorStop(1, "#22395c");
+ ctx.fillStyle = shirt;
+ ctx.beginPath();
+ ctx.moveTo(-170, 10);
+ ctx.bezierCurveTo(-160, -90, -110, -118, -40, -128);
+ ctx.lineTo(40, -128);
+ ctx.bezierCurveTo(110, -118, 160, -90, 170, 10);
+ ctx.closePath();
+ ctx.fill();
+ ctx.fillStyle = "rgba(0,0,0,0.18)";
+ ctx.beginPath();
+ ctx.moveTo(-36, -128);
+ ctx.lineTo(0, -84);
+ ctx.lineTo(36, -128);
+ ctx.closePath();
+ ctx.fill();
+ ctx.restore();
+
+ const neck = ctx.createLinearGradient(hx - 30, 0, hx + 30, 0);
+ neck.addColorStop(0, "#b9805c");
+ neck.addColorStop(1, "#d39b74");
+ ctx.fillStyle = neck;
+ ctx.fillRect(hx - 26, hy + 50, 52, 70);
+
+ ctx.save();
+ ctx.translate(hx, hy);
+ ctx.rotate(tilt);
+ const skin = ctx.createRadialGradient(-18, -22, 8, 0, 0, 82);
+ skin.addColorStop(0, "#f1c7a3");
+ skin.addColorStop(0.6, "#d9a07a");
+ skin.addColorStop(1, "#a9704f");
+ ctx.fillStyle = skin;
+ ctx.beginPath();
+ ctx.ellipse(0, 0, 54, 70, 0, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.fillStyle = "#c48862";
+ ctx.beginPath();
+ ctx.ellipse(-54, 6, 9, 15, 0, 0, Math.PI * 2);
+ ctx.ellipse(54, 6, 9, 15, 0, 0, Math.PI * 2);
+ ctx.fill();
+ const hair = ctx.createLinearGradient(0, -80, 0, -20);
+ hair.addColorStop(0, "#2b1d14");
+ hair.addColorStop(1, "#4a3122");
+ ctx.fillStyle = hair;
+ ctx.beginPath();
+ ctx.moveTo(-58, -6);
+ ctx.bezierCurveTo(-66, -70, -30, -84, 6, -82);
+ ctx.bezierCurveTo(44, -82, 66, -60, 58, -6);
+ ctx.bezierCurveTo(46, -40, 20, -48, -4, -46);
+ ctx.bezierCurveTo(-30, -46, -46, -36, -58, -6);
+ ctx.fill();
+ const blink = (t % 4.3) < 0.13;
+ ctx.fillStyle = "#2a1a12";
+ for (const ex of [-21, 21]) {
+ ctx.beginPath();
+ ctx.ellipse(ex + 2 * Math.sin(t * 0.9), -6, 7, blink ? 1 : 4.5, 0, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ ctx.strokeStyle = "rgba(60,35,25,0.6)";
+ ctx.lineWidth = 3;
+ for (const ex of [-21, 21]) {
+ ctx.beginPath();
+ ctx.moveTo(ex - 11, -20);
+ ctx.quadraticCurveTo(ex, -25 - Math.sin(t * 0.7), ex + 11, -20);
+ ctx.stroke();
+ }
+ ctx.strokeStyle = "rgba(120,70,50,0.45)";
+ ctx.lineWidth = 2.5;
+ ctx.beginPath();
+ ctx.moveTo(-2, -2);
+ ctx.quadraticCurveTo(-7, 18, 2, 22);
+ ctx.stroke();
+ const talk = Math.max(0, Math.sin(t * 9.1) * Math.sin(t * 2.3) + 0.25 * Math.sin(t * 13.7));
+ ctx.fillStyle = "#7a3b32";
+ ctx.beginPath();
+ ctx.ellipse(0, 40, 16, 3 + 6 * talk, 0, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.restore();
+
+ const vig = ctx.createRadialGradient(160, 160, 90, 160, 160, 230);
+ vig.addColorStop(0, "rgba(0,0,0,0)");
+ vig.addColorStop(1, "rgba(0,0,0,0.35)");
+ ctx.fillStyle = vig;
+ ctx.fillRect(0, 0, S, S);
+
+ const img = ctx.getImageData(0, 0, N, N);
+ const d = img.data;
+ if (!noise) noise = new Int8Array(d.length);
+ for (let i = 0; i < d.length; i += 4) {
+ const g = ((rand() + rand() + rand() - 1.5) * 9) | 0;
+ d[i] += g + ((rand() * 5) | 0) - 2;
+ d[i + 1] += g + ((rand() * 3) | 0) - 1;
+ d[i + 2] += g + ((rand() * 7) | 0) - 3;
+ }
+ ctx.putImageData(img, 0, 0);
+ frame++;
+ }
+
+ function loop(ts) {
+ if (ts - lastDraw >= 1000 / 30 - 2) {
+ lastDraw = ts;
+ draw(ts);
+ }
+ requestAnimationFrame(loop);
+ }
+ requestAnimationFrame(loop);
+
+ let drag = null;
+ bubble.addEventListener("mousedown", (e) => {
+ e.preventDefault();
+ const r = bubble.getBoundingClientRect();
+ drag = { dx: e.clientX - r.left, dy: e.clientY - r.top };
+ bubble.classList.add("drag");
+ cap.event("webcam_drag_start", { x: r.left, y: r.top });
+ });
+ window.addEventListener("mousemove", (e) => {
+ if (!drag) return;
+ const x = Math.max(8, Math.min(innerWidth - S - 8, e.clientX - drag.dx));
+ const y = Math.max(8, Math.min(innerHeight - S - 8, e.clientY - drag.dy));
+ bubble.style.left = `${x}px`;
+ bubble.style.top = `${y}px`;
+ });
+ window.addEventListener("mouseup", () => {
+ if (!drag) return;
+ drag = null;
+ bubble.classList.remove("drag");
+ const r = bubble.getBoundingClientRect();
+ cap.event("webcam_drag_end", { x: r.left, y: r.top });
+ });
+ window.capWebcamRect = () => {
+ const r = bubble.getBoundingClientRect();
+ return [r.left, r.top, r.width, r.height];
+ };
+})();
diff --git a/capcodec/bench/corpus/pages/common/wiki.css b/capcodec/bench/corpus/pages/common/wiki.css
new file mode 100644
index 000000000..c3e0d1c95
--- /dev/null
+++ b/capcodec/bench/corpus/pages/common/wiki.css
@@ -0,0 +1,478 @@
+html {
+ font-size: 16px;
+}
+body {
+ margin: 0;
+ background: #fff;
+ color: #202122;
+ font-family: "Noto Sans", "Liberation Sans", "DejaVu Sans", sans-serif;
+}
+a {
+ color: #3366cc;
+ text-decoration: none;
+ cursor: pointer;
+}
+a:hover {
+ text-decoration: underline;
+}
+#hdr {
+ height: 56px;
+ max-width: 1596px;
+ margin: 0 auto;
+ display: flex;
+ align-items: center;
+ padding: 0 24px;
+ box-sizing: border-box;
+ gap: 22px;
+}
+#hdr .hl {
+ display: flex;
+ align-items: center;
+ gap: 16px;
+ width: 248px;
+}
+#hdr .burger {
+ font-size: 20px;
+ color: #202122;
+ width: 32px;
+ text-align: center;
+}
+#hdr .logo {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+#hdr .wm {
+ display: flex;
+ flex-direction: column;
+ line-height: 1.1;
+}
+#hdr .wm1 {
+ font-family: "Liberation Serif", "DejaVu Serif", serif;
+ font-size: 21px;
+ letter-spacing: 0.08em;
+ font-variant: small-caps;
+}
+#hdr .wm2 {
+ font-family: "Liberation Serif", serif;
+ font-size: 11.5px;
+ letter-spacing: 0.02em;
+}
+#hdr .search {
+ display: flex;
+ align-items: center;
+ margin-left: 26px;
+}
+#hdr .sbox {
+ width: 480px;
+ height: 32px;
+ border: 1px solid #a2a9b1;
+ border-radius: 2px 0 0 2px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 0 8px;
+ box-sizing: border-box;
+ font-size: 14px;
+ color: #72777d;
+}
+#hdr .sbtn {
+ height: 32px;
+ border: 1px solid #a2a9b1;
+ border-left: 0;
+ background: #f8f9fa;
+ display: flex;
+ align-items: center;
+ padding: 0 12px;
+ font-size: 14px;
+ font-weight: 700;
+ color: #202122;
+ box-sizing: border-box;
+ border-radius: 0 2px 2px 0;
+}
+#hdr .hr {
+ margin-left: auto;
+ display: flex;
+ gap: 20px;
+ font-size: 14px;
+ color: #3366cc;
+ align-items: center;
+}
+#hdr .hr .dots {
+ color: #202122;
+ font-size: 18px;
+}
+#container {
+ max-width: 1596px;
+ margin: 0 auto;
+ display: grid;
+ grid-template-columns: 248px minmax(0, 1fr) 176px;
+ column-gap: 32px;
+ padding: 0 24px;
+ box-sizing: border-box;
+}
+#toc {
+ padding-top: 22px;
+ font-size: 14px;
+}
+#toc .toch,
+#tools .th {
+ font-size: 14px;
+ font-weight: 700;
+ padding-bottom: 6px;
+ border-bottom: 1px solid #c8ccd1;
+ margin-bottom: 8px;
+ display: flex;
+ align-items: baseline;
+}
+#toc .hide,
+#tools .hide {
+ margin-left: auto;
+ font-weight: 400;
+ font-size: 12px;
+ color: #3366cc;
+ border: 1px solid #a2a9b1;
+ border-radius: 2px;
+ padding: 1px 6px;
+}
+#toc ol {
+ list-style: none;
+ padding: 0;
+ margin: 0;
+}
+#toc li {
+ padding: 4px 0;
+ color: #3366cc;
+ line-height: 1.35;
+}
+#toc li.l3 {
+ padding-left: 14px;
+}
+#toc li.top {
+ color: #202122;
+ font-weight: 700;
+}
+#toc li .tn {
+ color: #54595d;
+ margin-right: 4px;
+}
+#main {
+ min-width: 0;
+}
+.titlebar {
+ display: flex;
+ align-items: flex-end;
+ border-bottom: 1px solid #a2a9b1;
+ padding-top: 14px;
+}
+#firstHeading {
+ font-family: "Liberation Serif", "DejaVu Serif", Georgia, serif;
+ font-weight: 400;
+ font-size: 28.8px;
+ line-height: 1.375;
+ margin: 0 0 4px;
+}
+.titlebar .lang {
+ margin-left: auto;
+ font-size: 14px;
+ font-weight: 700;
+ color: #3366cc;
+ padding: 6px 10px;
+ margin-bottom: 6px;
+}
+.tabs {
+ display: flex;
+ font-size: 14px;
+ gap: 18px;
+ height: 38px;
+ align-items: center;
+ border-bottom: 1px solid #a2a9b1;
+ margin-bottom: 8px;
+}
+.tabs .tab {
+ color: #3366cc;
+ height: 38px;
+ display: flex;
+ align-items: center;
+ box-sizing: border-box;
+}
+.tabs .tab.sel {
+ color: #202122;
+ border-bottom: 2px solid #202122;
+}
+.tabs .sp {
+ flex: 1;
+}
+#content {
+ font-size: 14px;
+ line-height: 1.6;
+}
+#content .from {
+ font-size: 12.6px;
+ color: #54595d;
+ margin: 4px 0 8px;
+}
+#content .hatnote {
+ font-style: italic;
+ padding-left: 1.6em;
+ margin-bottom: 8px;
+}
+#content p {
+ margin: 7px 0 10px;
+}
+#content sup {
+ font-size: 11px;
+ line-height: 1;
+ color: #3366cc;
+}
+#content h2 {
+ font-family: "Liberation Serif", "DejaVu Serif", Georgia, serif;
+ font-weight: 400;
+ font-size: 24px;
+ line-height: 1.375;
+ border-bottom: 1px solid #a2a9b1;
+ margin: 18px 0 4px;
+ padding-bottom: 2px;
+ overflow: hidden;
+}
+#content h3 {
+ font-size: 16.8px;
+ font-weight: 700;
+ line-height: 1.6;
+ margin: 14px 0 2px;
+ overflow: hidden;
+}
+#content h2 .edit,
+#content h3 .edit {
+ font-family: "Noto Sans", sans-serif;
+ font-size: 12.6px;
+ font-weight: 400;
+ color: #54595d;
+ margin-left: 10px;
+}
+.infobox {
+ float: right;
+ clear: right;
+ width: 302px;
+ margin: 6px 0 16px 22px;
+ border: 1px solid #a2a9b1;
+ background: #f8f9fa;
+ font-size: 12.6px;
+ line-height: 1.5;
+ border-spacing: 3px;
+ padding: 2px;
+}
+.infobox th,
+.infobox td {
+ text-align: left;
+ vertical-align: top;
+ padding: 2px 4px;
+}
+.infobox .ibt {
+ text-align: center;
+ font-size: 15.6px;
+ font-weight: 700;
+ padding: 4px;
+}
+.infobox .ibimg {
+ text-align: center;
+ padding: 4px 0;
+}
+.infobox .ibcap {
+ text-align: center;
+ font-size: 12px;
+ padding-bottom: 8px;
+}
+.thumb {
+ float: right;
+ clear: right;
+ margin: 6px 0 12px 22px;
+ border: 1px solid #c8ccd1;
+ background: #f8f9fa;
+ padding: 3px;
+ font-size: 12.6px;
+ line-height: 1.45;
+}
+.thumb svg {
+ display: block;
+ border: 1px solid #c8ccd1;
+ background: #fff;
+}
+.thumb .cap {
+ padding: 4px 3px 2px;
+}
+.thumb.left {
+ float: left;
+ clear: left;
+ margin: 6px 22px 12px 0;
+}
+table.wikitable {
+ border-collapse: collapse;
+ background: #f8f9fa;
+ color: #202122;
+ margin: 12px 0 14px;
+ border: 1px solid #a2a9b1;
+ font-size: 14px;
+ line-height: 1.5;
+}
+table.wikitable caption {
+ font-weight: 700;
+ padding: 4px;
+}
+table.wikitable th,
+table.wikitable td {
+ border: 1px solid #a2a9b1;
+ padding: 3px 7px;
+ text-align: left;
+ vertical-align: top;
+}
+table.wikitable th {
+ background: #eaecf0;
+ text-align: center;
+}
+table.wikitable td.n {
+ text-align: right;
+ font-variant-numeric: tabular-nums;
+}
+.cols {
+ column-width: 22em;
+ column-gap: 2em;
+ font-size: 12.6px;
+ line-height: 1.6;
+}
+.cols ul {
+ margin: 0;
+ padding-left: 1.4em;
+}
+ol.refs {
+ column-width: 30em;
+ column-gap: 2em;
+ font-size: 12.6px;
+ line-height: 1.6;
+ margin: 6px 0 12px;
+ padding-left: 2.6em;
+}
+ol.refs li {
+ break-inside: avoid;
+ margin-bottom: 2px;
+}
+ol.refs .up {
+ color: #3366cc;
+ font-weight: 700;
+ margin-right: 4px;
+}
+ul.fr {
+ padding-left: 1.6em;
+ margin: 6px 0 12px;
+}
+.navbox {
+ clear: both;
+ border: 1px solid #a2a9b1;
+ width: 100%;
+ margin: 18px 0 8px;
+ font-size: 12.6px;
+ border-collapse: collapse;
+ line-height: 1.6;
+}
+.navbox th.nt {
+ background: #ccccff;
+ text-align: center;
+ padding: 3px 8px;
+ font-size: 14px;
+}
+.navbox th.ng {
+ background: #ddddff;
+ text-align: right;
+ padding: 3px 8px;
+ white-space: nowrap;
+ width: 1%;
+ border-top: 2px solid #fdfdfd;
+}
+.navbox td {
+ padding: 3px 8px;
+ border-top: 2px solid #fdfdfd;
+}
+.navbox tr:nth-child(odd) td {
+ background: #f7f7f7;
+}
+.navbox td a + a::before {
+ content: " · ";
+ color: #202122;
+ font-weight: 700;
+}
+#footer {
+ clear: both;
+ border-top: 1px solid #a2a9b1;
+ margin-top: 22px;
+ padding: 16px 0 40px;
+ font-size: 12.6px;
+ color: #202122;
+}
+#footer .fl {
+ display: flex;
+ gap: 16px;
+ flex-wrap: wrap;
+ color: #3366cc;
+ margin-top: 10px;
+}
+#tools {
+ padding-top: 22px;
+ font-size: 14px;
+}
+#tools .tg {
+ margin-bottom: 14px;
+}
+#tools .tl {
+ font-weight: 700;
+ margin-bottom: 4px;
+}
+#tools .beta {
+ font-weight: 400;
+ color: #54595d;
+}
+#tools label {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 3px 0;
+}
+#tools .rb {
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ border: 1px solid #72777d;
+ box-sizing: border-box;
+ background: #fff;
+}
+#tools .rb.on {
+ border: 5px solid #3366cc;
+}
+#preview {
+ position: absolute;
+ display: none;
+ width: 450px;
+ background: #fff;
+ box-shadow: 0 30px 90px -20px #00000052, 0 0 1px #a2a9b1;
+ border-radius: 2px;
+ z-index: 10;
+ font-size: 14px;
+ line-height: 1.5;
+}
+#preview .pb {
+ padding: 16px 18px 12px;
+}
+#preview .pt {
+ font-weight: 700;
+ margin-bottom: 4px;
+}
+#preview .pf {
+ border-top: 1px solid #eaecf0;
+ padding: 8px 18px;
+ font-size: 12px;
+ color: #72777d;
+ display: flex;
+ justify-content: space-between;
+}
+::selection {
+ background: #b4d5fe;
+}
diff --git a/capcodec/bench/corpus/pages/common/wiki.js b/capcodec/bench/corpus/pages/common/wiki.js
new file mode 100644
index 000000000..f759b2004
--- /dev/null
+++ b/capcodec/bench/corpus/pages/common/wiki.js
@@ -0,0 +1,341 @@
+(() => {
+ const FIGS = {
+ pellegrino: {
+ w: 260,
+ h: 210,
+ cap: "Rasmus Malling-Hansen's writing ball (1870), the first typewriter sold commercially",
+ svg: `<rect width="260" height="210" fill="url(#sepia)"/>
+<ellipse cx="130" cy="186" rx="110" ry="16" fill="#3b2a18" opacity=".55"/>
+<rect x="40" y="150" width="180" height="36" rx="4" fill="#4a3420"/>
+<ellipse cx="130" cy="120" rx="82" ry="62" fill="#b08d3c"/>
+<ellipse cx="118" cy="98" rx="54" ry="34" fill="#e6cf86" opacity=".55"/>
+${Array.from({ length: 52 }, (_, i) => {
+ const row = Math.floor(i / 13);
+ const col = i % 13;
+ const a = (col / 12 - 0.5) * 2.4;
+ const x = 130 + Math.sin(a) * (70 - row * 11);
+ const y = 82 + row * 17 + Math.cos(a) * 6;
+ return `<circle cx="${x.toFixed(1)}" cy="${y.toFixed(1)}" r="${(5.6 - row * 0.5).toFixed(1)}" fill="#f2ead3" stroke="#3a2a12" stroke-width="1.2"/>`;
+}).join("")}
+<rect x="200" y="40" width="34" height="110" rx="3" fill="#2b1d10" opacity=".8"/>
+<rect width="260" height="210" fill="url(#vign)"/>`,
+ },
+ sholes: {
+ w: 300,
+ h: 220,
+ cap: "The Sholes and Glidden typewriter, produced by E. Remington and Sons from 1873",
+ svg: `<rect width="300" height="220" fill="url(#sepia)"/>
+<rect x="0" y="150" width="300" height="70" fill="#6d5233" opacity=".8"/>
+<path d="M60 60h180l20 90H40z" fill="#2c2117"/>
+<path d="M70 70h160l10 40H60z" fill="#7a5c34" opacity=".75"/>
+<path d="M80 76q70 18 140 0" stroke="#e8d7a8" stroke-width="2" fill="none" opacity=".7"/>
+<rect x="56" y="40" width="188" height="20" rx="10" fill="#1a130c"/>
+<rect x="90" y="18" width="120" height="26" fill="#efe6cf" opacity=".9"/>
+${Array.from({ length: 44 }, (_, i) => {
+ const row = Math.floor(i / 11);
+ const col = i % 11;
+ const x = 64 + col * 16 + row * 5;
+ const y = 118 + row * 10;
+ return `<ellipse cx="${x}" cy="${y}" rx="5.5" ry="4" fill="#f4ecd6" stroke="#20160c" stroke-width="1"/>`;
+}).join("")}
+<rect x="30" y="160" width="240" height="10" fill="#1e150c"/>
+<rect width="300" height="220" fill="url(#vign)"/>`,
+ },
+ selectric: {
+ w: 300,
+ h: 200,
+ cap: "An IBM Selectric typewriter, with its spherical type element visible",
+ svg: `<defs><linearGradient id="sb" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#4b79b8"/><stop offset="1" stop-color="#1d3d6b"/></linearGradient>
+<radialGradient id="ball" cx=".35" cy=".35" r=".7"><stop offset="0" stop-color="#f5f5f5"/><stop offset=".6" stop-color="#9aa0a6"/><stop offset="1" stop-color="#3c4043"/></radialGradient>
+<linearGradient id="room" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#e9e4da"/><stop offset="1" stop-color="#b8b1a4"/></linearGradient></defs>
+<rect width="300" height="200" fill="url(#room)"/>
+<rect y="150" width="300" height="50" fill="#8b7355"/>
+<path d="M30 80h240l18 78H12z" fill="url(#sb)"/>
+<rect x="44" y="56" width="212" height="28" rx="12" fill="#1f2a36"/>
+<rect x="96" y="20" width="108" height="40" fill="#fbfaf6"/>
+<path d="M104 30h86M104 38h80M104 46h90" stroke="#777" stroke-width="1.2"/>
+<circle cx="150" cy="84" r="12" fill="url(#ball)"/>
+${Array.from({ length: 48 }, (_, i) => {
+ const row = Math.floor(i / 12);
+ const col = i % 12;
+ const x = 46 + col * 18 + row * 3;
+ const y = 112 + row * 11;
+ return `<rect x="${x}" y="${y}" width="14" height="8" rx="2" fill="#e8eaed" stroke="#1d2b3a" stroke-width=".8"/>`;
+}).join("")}
+<rect x="96" y="158" width="110" height="8" rx="3" fill="#e8eaed"/>
+<rect width="300" height="200" fill="url(#vign)" opacity=".7"/>`,
+ },
+ office: {
+ w: 320,
+ h: 210,
+ cap: "A typing pool at an insurance company in the 1940s",
+ svg: `<rect width="320" height="210" fill="url(#sepia)"/>
+<path d="M0 0h320v70L160 40 0 70z" fill="#cdbb95"/>
+${Array.from({ length: 5 }, (_, r) => {
+ const y = 70 + r * 26;
+ const s = 0.5 + r * 0.14;
+ return Array.from({ length: 6 }, (_, c) => {
+ const x = 160 + (c - 2.5) * 52 * s;
+ return `<g transform="translate(${x.toFixed(1)} ${y}) scale(${s.toFixed(2)})"><rect x="-22" y="10" width="44" height="12" fill="#4b3621"/><rect x="-10" y="0" width="20" height="10" fill="#2b2016"/><circle cx="0" cy="-14" r="7" fill="#6b5236"/><path d="M-10 -6h20l3 16h-26z" fill="#3e3022"/></g>`;
+ }).join("");
+}).join("")}
+<rect width="320" height="210" fill="url(#vign)"/>`,
+ },
+ production: {
+ w: 330,
+ h: 236,
+ cap: "Estimated typewriter production in the United States, 1900–1990 (millions of units per year)",
+ svg: (() => {
+ const data = [0.12, 0.31, 0.55, 0.9, 1.15, 0.72, 1.05, 1.42, 1.9, 2.35, 2.62, 2.1, 1.35, 0.6, 0.22, 0.08, 0.04, 0.02, 0.01];
+ const years = [1900, 1905, 1910, 1915, 1920, 1925, 1930, 1935, 1940, 1945, 1950, 1955, 1960, 1965, 1970, 1975, 1980, 1985, 1990];
+ const series = [0.12, 0.3, 0.52, 0.85, 1.1, 0.95, 0.8, 0.98, 1.3, 1.6, 2.1, 2.55, 2.75, 2.6, 2.2, 1.6, 0.9, 0.35, 0.12];
+ let s = '<rect width="330" height="236" fill="#fff"/>';
+ for (let i = 0; i <= 6; i++) {
+ const y = 196 - i * 28;
+ s += `<line x1="40" x2="320" y1="${y}" y2="${y}" stroke="#e5e5e5"/><text x="34" y="${y + 4}" font-size="10" text-anchor="end" fill="#444" font-family="Noto Sans">${(i * 0.5).toFixed(1)}</text>`;
+ }
+ series.forEach((v, i) => {
+ const x = 46 + i * 14.4;
+ const h = v * 56;
+ s += `<rect x="${x}" y="${196 - h}" width="10" height="${h}" fill="#5b8ccf"/>`;
+ if (i % 3 === 0) s += `<text x="${x + 5}" y="210" font-size="9.5" text-anchor="middle" fill="#444" font-family="Noto Sans">${years[i]}</text>`;
+ });
+ s += `<polyline fill="none" stroke="#d9534f" stroke-width="2" points="${data.map((v, i) => `${51 + i * 14.4},${196 - v * 56}`).join(" ")}"/>`;
+ s += '<line x1="40" x2="320" y1="196" y2="196" stroke="#333"/><line x1="40" x2="40" y1="20" y2="196" stroke="#333"/>';
+ s += '<rect x="196" y="16" width="10" height="10" fill="#5b8ccf"/><text x="210" y="25" font-size="10" fill="#222" font-family="Noto Sans">All typewriters</text>';
+ s += '<line x1="196" x2="206" y1="38" y2="38" stroke="#d9534f" stroke-width="2"/><text x="210" y="41" font-size="10" fill="#222" font-family="Noto Sans">Portable models</text>';
+ s += '<text x="180" y="230" font-size="10" text-anchor="middle" fill="#222" font-family="Noto Sans">Year</text>';
+ return s;
+ })(),
+ },
+ typebar: {
+ w: 300,
+ h: 210,
+ cap: "Simplified diagram of a front-strike typebar mechanism: key lever (A), sublever (B), typebar (C), platen (D) and ribbon (E)",
+ svg: `<rect width="300" height="210" fill="#fff"/>
+<circle cx="236" cy="56" r="26" fill="#ddd" stroke="#333" stroke-width="2"/>
+<circle cx="236" cy="56" r="4" fill="#333"/>
+<path d="M196 70h30" stroke="#c0392b" stroke-width="4"/>
+<path d="M30 180l90-10" stroke="#333" stroke-width="4"/>
+<rect x="18" y="172" width="26" height="12" rx="3" fill="#f2f2f2" stroke="#333" stroke-width="2"/>
+<path d="M120 170l30-40" stroke="#555" stroke-width="3"/>
+<path d="M150 130l60-56" stroke="#2c3e50" stroke-width="4"/>
+<rect x="204" y="64" width="12" height="16" fill="#2c3e50" transform="rotate(-42 210 72)"/>
+<circle cx="150" cy="130" r="4" fill="#fff" stroke="#333" stroke-width="2"/>
+<circle cx="120" cy="170" r="4" fill="#fff" stroke="#333" stroke-width="2"/>
+<path d="M140 150a40 40 0 0 1 40-40" fill="none" stroke="#888" stroke-dasharray="4 3"/>
+${[
+ ["A", 70, 196],
+ ["B", 128, 150],
+ ["C", 176, 96],
+ ["D", 270, 40],
+ ["E", 206, 92],
+]
+ .map(([t, x, y]) => `<text x="${x}" y="${y}" font-family="Noto Sans" font-weight="700" font-size="14" fill="#222">${t}</text>`)
+ .join("")}`,
+ },
+ keyboard: {
+ w: 330,
+ h: 128,
+ cap: "The QWERTY layout as used on most English-language typewriters",
+ svg: (() => {
+ const rows = ["1234567890-", "QWERTYUIOP", "ASDFGHJKL;", "ZXCVBNM,./"];
+ let s = '<rect width="330" height="128" fill="#f4f4f4"/>';
+ rows.forEach((r, ri) => {
+ [...r].forEach((ch, ci) => {
+ const x = 10 + ri * 9 + ci * 27;
+ const y = 8 + ri * 27;
+ s += `<rect x="${x}" y="${y}" width="24" height="24" rx="4" fill="#fff" stroke="#888"/><text x="${x + 12}" y="${y + 16.5}" text-anchor="middle" font-family="DejaVu Sans Mono" font-size="12" fill="#222">${ch}</text>`;
+ });
+ });
+ s += '<rect x="80" y="116" width="170" height="10" rx="3" fill="#fff" stroke="#888"/>';
+ return s;
+ })(),
+ },
+ };
+
+ const TABLES = {
+ models: `<table class="wikitable"><caption>Selected typewriter models</caption>
+<tr><th>Year</th><th>Manufacturer</th><th>Model</th><th>Type</th><th>Notable features</th></tr>
+${[
+ ["1865", "Malling-Hansen", "Writing ball", "Index/keyboard", "First commercially sold typewriter"],
+ ["1873", "E. Remington and Sons", "Sholes and Glidden", "Upstrike", "QWERTY layout, capitals only"],
+ ["1878", "Remington", "No. 2", "Upstrike", "Shift key for upper and lower case"],
+ ["1893", "Blickensderfer", "No. 5", "Typewheel", "Portable, interchangeable typewheel"],
+ ["1895", "Underwood", "No. 1", "Front-strike", "Visible writing"],
+ ["1900", "Underwood", "No. 5", "Front-strike", "Best-selling desktop model for decades"],
+ ["1909", "Corona", "No. 3", "Front-strike", "Folding carriage portable"],
+ ["1935", "IBM", "Electromatic Model 01", "Electric", "First mass-produced IBM electric"],
+ ["1950", "Olivetti", "Lettera 22", "Portable", "Industrial design award winner"],
+ ["1961", "IBM", "Selectric", "Typeball", "Moving element, stationary paper"],
+ ["1973", "IBM", "Correcting Selectric II", "Typeball", "Built-in lift-off correction"],
+ ["1984", "Brother", "AX-10", "Daisy wheel", "Electronic, line memory"],
+]
+ .map((r) => `<tr>${r.map((c) => `<td>${c}</td>`).join("")}</tr>`)
+ .join("")}
+</table>`,
+ layouts: `<table class="wikitable"><caption>Common keyboard layouts</caption>
+<tr><th>Layout</th><th>Main region</th><th>Top letter row</th><th>Introduced</th></tr>
+${[
+ ["QWERTY", "English-speaking countries, many others", "Q W E R T Y U I O P", "1873"],
+ ["QWERTZ", "Germany, Austria, Central Europe", "Q W E R T Z U I O P Ü", "c. 1890"],
+ ["AZERTY", "France, Belgium", "A Z E R T Y U I O P", "c. 1900"],
+ ["QZERTY", "Italy (historical)", "Q Z E R T Y U I O P", "c. 1910"],
+ ["Dvorak", "Alternative for English", "' , . P Y F G C R L", "1936"],
+ ["JCUKEN", "Russia and other Cyrillic users", "Й Ц У К Е Н Г Ш Щ З", "c. 1900"],
+]
+ .map((r) => `<tr>${r.map((c) => `<td>${c}</td>`).join("")}</tr>`)
+ .join("")}
+</table>`,
+ };
+
+ function refs() {
+ const authors = [
+ "Beeching, Wilfred A.", "Current, Richard N.", "Polt, Richard", "Adler, Michael H.", "Rehr, Darryl", "Romano, Frank J.", "Yamada, Hisao", "David, Paul A.", "Liebowitz, S. J.; Margolis, Stephen E.", "Utterback, James M.", "Hoke, Donald", "Davies, Margery W.", "Kittler, Friedrich", "Wershler-Henry, Darren", "Masi, Frank T.", "Bliven, Bruce Jr.", "Lundmark, Torbjörn", "Herkimer County Historical Society", "Stamp, Jimmy", "Nesmith Graham, Bette",
+ ];
+ const titles = [
+ ["<i>Century of the Typewriter</i>", "London: Heinemann"],
+ ["<i>The Typewriter and the Men Who Made It</i>", "Urbana: University of Illinois Press"],
+ ["<i>The Typewriter Revolution</i>", "Woodstock, VT: Countryman Press"],
+ ["<i>The Writing Machine</i>", "London: George Allen &amp; Unwin"],
+ ["<i>Antique Typewriters and Office Collectibles</i>", "Paducah: Collector Books"],
+ ["<i>Machine Writing and Typesetting</i>", "Salem, NH: GAMA"],
+ ['"A historical study of typewriters and typing methods"', "<i>Journal of Information Processing</i>"],
+ ['"Clio and the Economics of QWERTY"', "<i>American Economic Review</i>"],
+ ['"The Fable of the Keys"', "<i>Journal of Law and Economics</i>"],
+ ["<i>Mastering the Dynamics of Innovation</i>", "Boston: Harvard Business School Press"],
+ ["<i>Ingenious Yankees</i>", "New York: Columbia University Press"],
+ ["<i>Woman's Place Is at the Typewriter</i>", "Philadelphia: Temple University Press"],
+ ["<i>Gramophone, Film, Typewriter</i>", "Stanford: Stanford University Press"],
+ ["<i>The Iron Whim: A Fragmented History of Typewriting</i>", "Ithaca: Cornell University Press"],
+ ["<i>The Typewriter Legend</i>", "Secaucus, NJ: Matsushita Electric"],
+ ["<i>The Wonderful Writing Machine</i>", "New York: Random House"],
+ ['"The keyboard that would not die"', "<i>Smithsonian Magazine</i>"],
+ ["<i>The Story of the Typewriter, 1873–1923</i>", "Herkimer, NY"],
+ ['"How the typewriter changed office work"', "<i>The Atlantic</i>"],
+ ['"Mistake Out: the invention of correction fluid"', "<i>Texas Monthly</i>"],
+ ];
+ const out = [];
+ for (let i = 0; i < 38; i++) {
+ const a = authors[(i * 7) % authors.length];
+ const [t, p] = titles[(i * 11 + 3) % titles.length];
+ const y = 1923 + ((i * 37) % 98);
+ const pg = 12 + ((i * 53) % 290);
+ const back = i % 4 === 1 ? '<span class="up">^ <sup>a</sup> <sup>b</sup></span>' : '<span class="up">^</span>';
+ const isbn = i % 3 === 0 ? ` ISBN 978-0-${String(100000 + i * 7919).slice(0, 3)}-${String(10000 + i * 3571).slice(0, 5)}-${i % 10}.` : "";
+ out.push(`<li>${back}${a} (${y}). ${t}. ${p}. p. ${pg}.${isbn}${i % 5 === 2 ? " Retrieved 14 March 2024." : ""}</li>`);
+ }
+ return `<ol class="refs">${out.join("")}</ol>`;
+ }
+
+ const SEEALSO = `<div class="cols"><ul>${["Daisy wheel printing", "Index typewriter", "Keyboard layout", "List of typewriter brands", "Mimeograph", "Stenotype", "Teleprinter", "Typewriter ribbon", "Typing", "Word processor"].map((s) => `<li><a data-p="${s}">${s}</a></li>`).join("")}</ul></div>`;
+
+ const NAVBOX = `<table class="navbox">
+<tr><th class="nt" colspan="2">Writing and office technology</th></tr>
+${[
+ ["Handwriting", ["Pen", "Pencil", "Fountain pen", "Ballpoint pen", "Quill", "Stylus"]],
+ ["Mechanical", ["Typewriter", "Index typewriter", "Stenotype", "Mimeograph", "Hectograph", "Adding machine"]],
+ ["Electromechanical", ["Electric typewriter", "Teleprinter", "Flexowriter", "Dictaphone", "Telex"]],
+ ["Electronic", ["Electronic typewriter", "Word processor", "Daisy wheel printer", "Dot matrix printer", "Personal computer"]],
+ ["Copying", ["Carbon paper", "Photocopier", "Spirit duplicator", "Fax"]],
+]
+ .map(([g, items]) => `<tr><th class="ng">${g}</th><td>${items.map((x) => `<a>${x}</a>`).join("")}</td></tr>`)
+ .join("")}
+</table>`;
+
+ function figure(key) {
+ const f = FIGS[key];
+ return `<div class="thumb" style="width:${f.w + 2}px"><svg viewBox="0 0 ${f.w} ${f.h}" width="${f.w}" height="${f.h}" ${key === "production" || key === "typebar" || key === "keyboard" ? "" : 'filter="url(#grain)"'}>${f.svg}</svg><div class="cap">${f.cap}</div></div>`;
+ }
+
+ const article = document.getElementById("article");
+ const toc = document.getElementById("toclist");
+ let h2n = 0;
+ let h3n = 0;
+ let html = "";
+ const tocItems = ['<li class="top">(Top)</li>'];
+ for (const sec of window.ARTICLE) {
+ let body = sec.html
+ .replace(/\{fig:(\w+)\}/g, (_, k) => figure(k))
+ .replace(/\{table:(\w+)\}/g, (_, k) => TABLES[k])
+ .replace("{refs}", refs())
+ .replace("{seealso}", SEEALSO)
+ .replace("{navbox}", NAVBOX);
+ if (sec.lead) {
+ html += body;
+ continue;
+ }
+ if (sec.h === 2) {
+ h2n++;
+ h3n = 0;
+ tocItems.push(`<li><span class="tn">${h2n}</span>${sec.title}</li>`);
+ html += `<h2>${sec.title}<span class="edit">[edit]</span></h2>${body}`;
+ } else {
+ h3n++;
+ tocItems.push(`<li class="l3"><span class="tn">${h2n}.${h3n}</span>${sec.title}</li>`);
+ html += `<h3>${sec.title}<span class="edit">[edit]</span></h3>${body}`;
+ }
+ }
+ html += `<div id="footer">This page was last edited on 2 October 2026, at 14:12<span> (UTC)</span>.<br>Text is available under the Creative Commons Attribution-ShareAlike 4.0 License; additional terms may apply. By using this site, you agree to the Terms of Use and Privacy Policy. Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization.
+<div class="fl"><span>Privacy policy</span><span>About Wikipedia</span><span>Disclaimers</span><span>Contact Wikipedia</span><span>Code of Conduct</span><span>Developers</span><span>Statistics</span><span>Cookie statement</span><span>Mobile view</span></div></div>`;
+ article.innerHTML = html;
+ toc.innerHTML = tocItems.join("");
+
+ const keys = document.getElementById("keys");
+ let k = "";
+ for (let r = 0; r < 4; r++) {
+ for (let c = 0; c < 11; c++) {
+ const x = 58 + c * 15.5 + r * 6;
+ const y = 108 + r * 12;
+ k += `<circle cx="${x}" cy="${y}" r="5" fill="url(#key)" stroke="#111" stroke-width="1"/>`;
+ }
+ }
+ keys.innerHTML = k;
+
+ const preview = document.getElementById("preview");
+ let hoverTimer = null;
+ let hideTimer = null;
+ const SUMMARIES = {
+ "Personal computer": "A personal computer is a computer designed for individual use. It is intended to be operated directly by an end user, rather than by a computer expert or technician.",
+ "Word processor": "A word processor is a device or computer program that provides for input, editing, formatting, and output of text, often with some additional features.",
+ QWERTY: "QWERTY is a keyboard layout for Latin-script alphabets. The name comes from the order of the first six keys on the top letter row of the keyboard.",
+ };
+ document.addEventListener("mouseover", (e) => {
+ const a = e.target.closest("a");
+ if (!a) return;
+ clearTimeout(hideTimer);
+ clearTimeout(hoverTimer);
+ hoverTimer = setTimeout(() => {
+ const name = a.dataset.p || a.textContent;
+ const r = a.getBoundingClientRect();
+ preview.innerHTML = `<div class="pb"><div class="pt">${name}</div>${SUMMARIES[name] || `${name} is a topic related to the history of writing machines and office technology. It is covered in more detail in its own article.`}</div><div class="pf"><span>⚙ Preferences</span><span>Read more ›</span></div>`;
+ preview.style.left = `${Math.round(r.left + scrollX)}px`;
+ preview.style.top = `${Math.round(r.bottom + scrollY + 6)}px`;
+ preview.style.display = "block";
+ cap.event("preview_show", { name });
+ }, 700);
+ });
+ document.addEventListener("mouseout", (e) => {
+ if (!e.target.closest("a")) return;
+ clearTimeout(hoverTimer);
+ hideTimer = setTimeout(() => {
+ if (preview.style.display !== "none") cap.event("preview_hide");
+ preview.style.display = "none";
+ }, 300);
+ });
+ window.addEventListener("scroll", () => {
+ clearTimeout(hoverTimer);
+ if (preview.style.display !== "none") {
+ preview.style.display = "none";
+ cap.event("preview_hide");
+ }
+ });
+
+ window.capTextRegions = () => {
+ const c = document.getElementById("content").getBoundingClientRect();
+ return [
+ [c.left, 120, 600, 440],
+ [c.left, 580, 600, 440],
+ ];
+ };
+})();
diff --git a/capcodec/bench/corpus/pages/common/workbench.css b/capcodec/bench/corpus/pages/common/workbench.css
new file mode 100644
index 000000000..585e91551
--- /dev/null
+++ b/capcodec/bench/corpus/pages/common/workbench.css
@@ -0,0 +1,668 @@
+* {
+ box-sizing: border-box;
+}
+html,
+body {
+ margin: 0;
+ height: 100%;
+ overflow: hidden;
+}
+body {
+ font-family: "Noto Sans", "DejaVu Sans", sans-serif;
+ font-size: 13px;
+ cursor: default;
+ user-select: none;
+}
+.theme-light {
+ --titlebar-bg: #dddddd;
+ --titlebar-fg: #333333;
+ --activity-bg: #2c2c2c;
+ --activity-fg: #ffffff;
+ --activity-inactive: #ffffff66;
+ --sidebar-bg: #f3f3f3;
+ --sidebar-fg: #616161;
+ --sidebar-head: #6f6f6f;
+ --list-hover: #e8e8e8;
+ --list-active: #e4e6f1;
+ --list-active-border: #0090f1;
+ --tabs-bg: #f3f3f3;
+ --tab-inactive: #ececec;
+ --tab-inactive-fg: #8e8e8e;
+ --tab-active: #ffffff;
+ --tab-active-fg: #333333;
+ --tab-border: #f3f3f3;
+ --editor-bg: #ffffff;
+ --editor-fg: #000000;
+ --gutter-fg: #237893;
+ --gutter-cur: #0b216f;
+ --line-hl: #eeeeee;
+ --caret: #000000;
+ --sel: #add6ff;
+ --guide: #d3d3d3;
+ --status-bg: #007acc;
+ --status-fg: #ffffff;
+ --breadcrumb-fg: #616161;
+ --suggest-bg: #f3f3f3;
+ --suggest-border: #c8c8c8;
+ --suggest-active: #0060c0;
+ --panel-bg: #ffffff;
+ --panel-border: #80808059;
+ --scroll-thumb: #64646466;
+ --tk-kw: #af00db;
+ --tk-st: #0000ff;
+ --tk-self: #0000ff;
+ --tk-str: #a31515;
+ --tk-com: #008000;
+ --tk-num: #098658;
+ --tk-fn: #795e26;
+ --tk-ty: #267f99;
+ --tk-var: #001080;
+ --tk-mac: #0000ff;
+ --tk-pp: #0000ff;
+}
+.theme-dark {
+ --titlebar-bg: #3c3c3c;
+ --titlebar-fg: #cccccc;
+ --activity-bg: #333333;
+ --activity-fg: #ffffff;
+ --activity-inactive: #ffffff66;
+ --sidebar-bg: #252526;
+ --sidebar-fg: #cccccc;
+ --sidebar-head: #bbbbbb;
+ --list-hover: #2a2d2e;
+ --list-active: #37373d;
+ --list-active-border: #007fd4;
+ --tabs-bg: #252526;
+ --tab-inactive: #2d2d2d;
+ --tab-inactive-fg: #969696;
+ --tab-active: #1e1e1e;
+ --tab-active-fg: #ffffff;
+ --tab-border: #252526;
+ --editor-bg: #1e1e1e;
+ --editor-fg: #d4d4d4;
+ --gutter-fg: #858585;
+ --gutter-cur: #c6c6c6;
+ --line-hl: #282828;
+ --caret: #aeafad;
+ --sel: #264f78;
+ --guide: #404040;
+ --status-bg: #007acc;
+ --status-fg: #ffffff;
+ --breadcrumb-fg: #a9a9a9;
+ --suggest-bg: #252526;
+ --suggest-border: #454545;
+ --suggest-active: #04395e;
+ --panel-bg: #1e1e1e;
+ --panel-border: #80808059;
+ --scroll-thumb: #79797966;
+ --tk-kw: #c586c0;
+ --tk-st: #569cd6;
+ --tk-self: #569cd6;
+ --tk-str: #ce9178;
+ --tk-com: #6a9955;
+ --tk-num: #b5cea8;
+ --tk-fn: #dcdcaa;
+ --tk-ty: #4ec9b0;
+ --tk-var: #9cdcfe;
+ --tk-mac: #569cd6;
+ --tk-pp: #c586c0;
+}
+#wb {
+ display: grid;
+ grid-template-rows: 30px 1fr 22px;
+ height: 100vh;
+ background: var(--editor-bg);
+}
+#titlebar {
+ background: var(--titlebar-bg);
+ color: var(--titlebar-fg);
+ display: flex;
+ align-items: center;
+ font-size: 13px;
+ padding-left: 8px;
+ position: relative;
+}
+#titlebar .appicon {
+ width: 16px;
+ height: 16px;
+ margin-right: 8px;
+}
+#titlebar .menu span {
+ padding: 4px 8px;
+ border-radius: 4px;
+}
+#titlebar .cc {
+ position: absolute;
+ left: 50%;
+ transform: translateX(-50%);
+ width: 520px;
+ height: 22px;
+ border: 1px solid #80808040;
+ border-radius: 6px;
+ background: #ffffff1a;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ font-size: 12px;
+ opacity: 0.85;
+}
+.theme-light #titlebar .cc {
+ background: #ececec;
+ border-color: #cecece;
+}
+#titlebar .wctl {
+ margin-left: auto;
+ display: flex;
+ height: 100%;
+}
+#titlebar .wctl span {
+ width: 46px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+#titlebar .layout {
+ display: flex;
+ gap: 10px;
+ margin-right: 14px;
+ margin-left: auto;
+ opacity: 0.8;
+}
+#titlebar .layout + .wctl {
+ margin-left: 0;
+}
+#main {
+ display: flex;
+ min-height: 0;
+}
+#activity {
+ width: 48px;
+ background: var(--activity-bg);
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ padding-top: 4px;
+}
+#activity .ai {
+ width: 48px;
+ height: 48px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: var(--activity-inactive);
+ position: relative;
+}
+#activity .ai.active {
+ color: var(--activity-fg);
+ box-shadow: inset 2px 0 0 var(--activity-fg);
+}
+#activity .ai .badge {
+ position: absolute;
+ right: 8px;
+ bottom: 8px;
+ background: #007acc;
+ color: #fff;
+ font-size: 9px;
+ border-radius: 8px;
+ padding: 1px 4px;
+ line-height: 12px;
+}
+#activity .spacer {
+ flex: 1;
+}
+#sidebar {
+ width: 262px;
+ background: var(--sidebar-bg);
+ color: var(--sidebar-fg);
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+}
+#sidebar .sb-head {
+ height: 35px;
+ display: flex;
+ align-items: center;
+ padding: 0 8px 0 20px;
+ font-size: 11px;
+ letter-spacing: 0.04em;
+ color: var(--sidebar-head);
+}
+#sidebar .sb-head .acts {
+ margin-left: auto;
+ display: flex;
+ gap: 8px;
+ opacity: 0.8;
+}
+#sidebar .sec {
+ font-size: 11px;
+ font-weight: 700;
+ height: 22px;
+ display: flex;
+ align-items: center;
+ padding-left: 4px;
+ gap: 2px;
+}
+.tree {
+ font-size: 13px;
+ overflow: hidden;
+ flex: 1;
+}
+.tree .ti {
+ height: 22px;
+ display: flex;
+ align-items: center;
+ white-space: nowrap;
+ gap: 5px;
+ border: 1px solid transparent;
+}
+.tree .ti:hover {
+ background: var(--list-hover);
+}
+.tree .ti.active {
+ background: var(--list-active);
+ border-color: var(--list-active-border);
+}
+.tree .ti .chev {
+ width: 16px;
+ text-align: center;
+ font-size: 10px;
+ opacity: 0.8;
+}
+.tree .fi {
+ width: 16px;
+ text-align: center;
+ font-size: 10px;
+ font-weight: 700;
+ font-family: "DejaVu Sans Mono", monospace;
+}
+.tree .ti .gs {
+ margin-left: auto;
+ margin-right: 12px;
+ font-size: 11px;
+ font-weight: 600;
+}
+.gs.m {
+ color: #e2c08d;
+}
+.theme-light .gs.m {
+ color: #895503;
+}
+.gs.u {
+ color: #73c991;
+}
+.theme-light .gs.u {
+ color: #007100;
+}
+.ti.mod .nm {
+ color: #e2c08d;
+}
+.theme-light .ti.mod .nm {
+ color: #895503;
+}
+.ti.unt .nm {
+ color: #73c991;
+}
+.theme-light .ti.unt .nm {
+ color: #007100;
+}
+#sidebar .outline {
+ border-top: 1px solid #80808033;
+}
+#edarea {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ min-width: 0;
+ min-height: 0;
+}
+#tabs {
+ height: 35px;
+ background: var(--tabs-bg);
+ display: flex;
+ flex: none;
+}
+.tab {
+ height: 35px;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 0 10px 0 12px;
+ background: var(--tab-inactive);
+ color: var(--tab-inactive-fg);
+ border-right: 1px solid var(--tab-border);
+ font-size: 13px;
+ min-width: 120px;
+}
+.tab.active {
+ background: var(--tab-active);
+ color: var(--tab-active-fg);
+}
+.tab .x {
+ margin-left: auto;
+ width: 20px;
+ text-align: center;
+ opacity: 0;
+ font-size: 14px;
+}
+.tab.active .x,
+.tab.dirty .x {
+ opacity: 0.9;
+}
+.tab .it {
+ font-style: italic;
+}
+#tabs .tacts {
+ margin-left: auto;
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding-right: 12px;
+ color: var(--sidebar-fg);
+ opacity: 0.8;
+}
+#crumbs {
+ height: 22px;
+ display: flex;
+ align-items: center;
+ padding-left: 16px;
+ gap: 4px;
+ color: var(--breadcrumb-fg);
+ font-size: 13px;
+ background: var(--editor-bg);
+ flex: none;
+}
+#crumbs .sep {
+ opacity: 0.7;
+ font-size: 10px;
+ margin: 0 2px;
+}
+.ce {
+ display: flex;
+ flex: 1;
+ min-height: 0;
+ position: relative;
+ background: var(--editor-bg);
+ color: var(--editor-fg);
+}
+.ce-scroller {
+ flex: 1;
+ overflow-y: scroll;
+ overflow-x: hidden;
+ position: relative;
+}
+.ce-scroller::-webkit-scrollbar {
+ width: 0;
+ height: 0;
+}
+.ce-content {
+ position: relative;
+ font-family: "JetBrains Mono", "DejaVu Sans Mono", monospace;
+ font-size: 13px;
+ line-height: 19px;
+ font-variant-ligatures: none;
+ white-space: pre;
+ cursor: text;
+}
+.ce-probe {
+ font-family: "JetBrains Mono", "DejaVu Sans Mono", monospace;
+ font-size: 13px;
+}
+.ce-row {
+ height: 19px;
+ display: flex;
+}
+.ce-row .ln {
+ width: 66px;
+ flex: none;
+ text-align: right;
+ padding-right: 26px;
+ color: var(--gutter-fg);
+ position: relative;
+ cursor: default;
+}
+.ce-row .ln.cur {
+ color: var(--gutter-cur);
+}
+.ce-row .ln.add::after,
+.ce-row .ln.mod::after {
+ content: "";
+ position: absolute;
+ right: 10px;
+ top: 0;
+ width: 3px;
+ height: 19px;
+ background: #487e02;
+}
+.theme-dark .ce-row .ln.add::after {
+ background: #587c0c;
+}
+.ce-row .ln.mod::after {
+ background: #1b81a8;
+}
+.theme-dark .ce-row .ln.mod::after {
+ background: #0c7d9d;
+}
+.ce-row .code {
+ flex: 1;
+}
+.ig {
+ box-shadow: inset 1px 0 0 var(--guide);
+}
+.ce-linehl {
+ position: absolute;
+ left: 66px;
+ right: 0;
+ top: 0;
+ height: 19px;
+ border: 2px solid var(--line-hl);
+ pointer-events: none;
+ display: none;
+}
+.ce.focused .ce-linehl {
+ display: block;
+}
+.ce-sel {
+ position: absolute;
+ background: var(--sel);
+ display: none;
+ pointer-events: none;
+}
+.ce-caret {
+ position: absolute;
+ left: 0;
+ top: 0;
+ width: 2px;
+ height: 19px;
+ background: var(--caret);
+ display: none;
+ pointer-events: none;
+}
+.ce.focused .ce-caret {
+ display: block;
+}
+.ce-caret.blink {
+ animation: ce-blink 1.1s steps(1) infinite;
+}
+@keyframes ce-blink {
+ 0% {
+ opacity: 1;
+ }
+ 50% {
+ opacity: 0;
+ }
+}
+.ce-minimap {
+ width: 92px;
+ flex: none;
+ height: 100%;
+ box-shadow: -6px 0 6px -6px #00000040;
+}
+.theme-dark .ce-minimap {
+ box-shadow: -6px 0 6px -6px #000000a0;
+}
+.ce-vbar {
+ width: 14px;
+ flex: none;
+ position: relative;
+ border-left: 1px solid #7f7f7f22;
+}
+.ce-vthumb {
+ position: absolute;
+ left: 0;
+ right: 0;
+ top: 0;
+ background: var(--scroll-thumb);
+}
+.ce-mark {
+ position: absolute;
+ right: 0;
+ width: 6px;
+ height: 3px;
+}
+.ce-mark.warn {
+ background: #bf8803;
+}
+.ce-mark.mod {
+ background: #1b81a8;
+ left: 0;
+ width: 4px;
+}
+.ce-mark.add {
+ background: #487e02;
+ left: 0;
+ width: 4px;
+}
+.ce-suggest {
+ position: absolute;
+ display: none;
+ width: 430px;
+ background: var(--suggest-bg);
+ border: 1px solid var(--suggest-border);
+ box-shadow: 0 0 8px 2px #00000029;
+ font-family: "Noto Sans", sans-serif;
+ font-size: 13px;
+ line-height: 22px;
+ white-space: nowrap;
+ z-index: 5;
+ color: var(--editor-fg);
+ padding: 1px 0;
+}
+.sg-item {
+ height: 22px;
+ display: flex;
+ align-items: center;
+ padding: 0 6px;
+ font-family: "JetBrains Mono", monospace;
+ font-size: 13px;
+}
+.sg-item b {
+ color: #0066bf;
+ font-weight: 700;
+}
+.theme-dark .sg-item b {
+ color: #18a3ff;
+}
+.sg-item.active {
+ background: var(--suggest-active);
+ color: #fff;
+}
+.sg-item.active b {
+ color: #9dddff;
+}
+.sg-icon {
+ width: 14px;
+ height: 14px;
+ margin-right: 6px;
+ border-radius: 2px;
+ flex: none;
+}
+.sg-icon.method {
+ background: #652d90;
+}
+.sg-icon.variable {
+ background: #007acc;
+}
+.sg-icon.field {
+ background: #1a85ff;
+ border-radius: 7px;
+}
+.sg-icon.class {
+ background: #d67e00;
+}
+.sg-detail {
+ margin-left: auto;
+ opacity: 0.75;
+ font-family: "Noto Sans", sans-serif;
+ font-size: 12px;
+}
+.tk-kw {
+ color: var(--tk-kw);
+}
+.tk-st {
+ color: var(--tk-st);
+}
+.tk-self {
+ color: var(--tk-self);
+}
+.tk-str {
+ color: var(--tk-str);
+}
+.tk-com {
+ color: var(--tk-com);
+}
+.tk-num {
+ color: var(--tk-num);
+}
+.tk-fn {
+ color: var(--tk-fn);
+}
+.tk-ty {
+ color: var(--tk-ty);
+}
+.tk-var {
+ color: var(--tk-var);
+}
+.tk-mac {
+ color: var(--tk-mac);
+}
+.tk-pp {
+ color: var(--tk-pp);
+}
+#statusbar {
+ background: var(--status-bg);
+ color: var(--status-fg);
+ display: flex;
+ align-items: center;
+ font-size: 12px;
+ gap: 2px;
+}
+#statusbar .si {
+ padding: 0 7px;
+ height: 22px;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ white-space: nowrap;
+}
+#statusbar .remote {
+ background: #16825d;
+ padding: 0 10px;
+}
+#statusbar .right {
+ margin-left: auto;
+ display: flex;
+}
+svg.ic {
+ width: 16px;
+ height: 16px;
+ fill: none;
+ stroke: currentColor;
+ stroke-width: 1.3;
+ flex: none;
+}
+#activity svg.ic {
+ width: 24px;
+ height: 24px;
+ stroke-width: 1.4;
+}
diff --git a/capcodec/bench/corpus/pages/common/workbench.js b/capcodec/bench/corpus/pages/common/workbench.js
new file mode 100644
index 000000000..8dc32bd35
--- /dev/null
+++ b/capcodec/bench/corpus/pages/common/workbench.js
@@ -0,0 +1,183 @@
+(() => {
+ const ICONS = {
+ files: '<path d="M14 3H8a1 1 0 0 0-1 1v13a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V8z"/><path d="M14 3v5h5"/><path d="M4 7v13a1 1 0 0 0 1 1h10"/>',
+ search: '<circle cx="10.5" cy="10.5" r="6.5"/><path d="M15.5 15.5 21 21"/>',
+ scm: '<circle cx="6.5" cy="5" r="2"/><circle cx="6.5" cy="19" r="2"/><circle cx="17.5" cy="8" r="2"/><path d="M6.5 7v10"/><path d="M17.5 10c0 4.5-5 3.5-10 7.5"/>',
+ run: '<path d="M7 4.5v15l12-7.5z"/><circle cx="18" cy="18" r="3"/>',
+ ext: '<rect x="3.5" y="10.5" width="5" height="5"/><rect x="8.5" y="10.5" width="5" height="5"/><rect x="3.5" y="15.5" width="5" height="5"/><rect x="8.5" y="15.5" width="5" height="5"/><rect x="14.5" y="3.5" width="5" height="5" transform="rotate(12 17 6)"/>',
+ test: '<path d="M9 3v6l-5 9a2 2 0 0 0 2 3h12a2 2 0 0 0 2-3l-5-9V3"/><path d="M8 3h8"/>',
+ account: '<circle cx="12" cy="8.5" r="4"/><path d="M4 21c1-4.5 4.5-6.5 8-6.5s7 2 8 6.5"/>',
+ gear: '<circle cx="12" cy="12" r="3"/><path d="M12 2.5v3M12 18.5v3M2.5 12h3M18.5 12h3M5.3 5.3l2.1 2.1M16.6 16.6l2.1 2.1M5.3 18.7l2.1-2.1M16.6 7.4l2.1-2.1"/>',
+ split: '<rect x="3.5" y="4.5" width="17" height="15" rx="1"/><path d="M12 4.5v15"/>',
+ more: '<circle cx="6" cy="12" r="1"/><circle cx="12" cy="12" r="1"/><circle cx="18" cy="12" r="1"/>',
+ branch: '<circle cx="6" cy="5" r="2"/><circle cx="6" cy="19" r="2"/><circle cx="18" cy="7" r="2"/><path d="M6 7v10M18 9c0 4-5 4-11 8"/>',
+ sync: '<path d="M4 12a8 8 0 0 1 14-5.3M20 12a8 8 0 0 1-14 5.3"/><path d="M18 3v4h-4M6 21v-4h4"/>',
+ err: '<circle cx="12" cy="12" r="8"/><path d="M9 9l6 6M15 9l-6 6"/>',
+ warn: '<path d="M12 4 21 20H3z"/><path d="M12 10v5M12 17.5v.5"/>',
+ bell: '<path d="M6 16V11a6 6 0 0 1 12 0v5l2 2H4z"/><path d="M10 20a2 2 0 0 0 4 0"/>',
+ layout1: '<rect x="3.5" y="4.5" width="17" height="15" rx="1"/><path d="M9 4.5v15"/>',
+ layout2: '<rect x="3.5" y="4.5" width="17" height="15" rx="1"/><path d="M3.5 14h17"/>',
+ layout3: '<rect x="3.5" y="4.5" width="17" height="15" rx="1"/><path d="M15 4.5v15"/>',
+ newfile: '<path d="M13 3H7a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V8z"/><path d="M12 11v6M9 14h6"/>',
+ refresh: '<path d="M19 12a7 7 0 1 1-2-5"/><path d="M19 4v4h-4"/>',
+ collapse: '<rect x="4" y="4" width="16" height="16" rx="1"/><path d="M8 12h8"/>',
+ close: '<path d="M6 6l12 12M18 6 6 18"/>',
+ min: '<path d="M5 12h14"/>',
+ max: '<rect x="6" y="6" width="12" height="12"/>',
+ trash: '<path d="M5 7h14M10 7V4h4v3M7 7l1 13h8l1-13"/>',
+ plus: '<path d="M12 5v14M5 12h14"/>',
+ chevup: '<path d="M6 15l6-6 6 6"/>',
+ term: '<rect x="3.5" y="4.5" width="17" height="15" rx="1"/><path d="M7 9l3 3-3 3M12 15h5"/>',
+ };
+ const icon = (name, extra) => `<svg class="ic ${extra || ""}" viewBox="0 0 24 24">${ICONS[name] || ""}</svg>`;
+ window.wbIcon = icon;
+
+ const FILE_BADGES = {
+ py: ["#3572a5", "py"],
+ c: ["#555599", "C"],
+ h: ["#a074c4", "h"],
+ md: ["#519aba", "M"],
+ json: ["#cbcb41", "{}"],
+ toml: ["#9c4221", "≡"],
+ yml: ["#a074c4", "!"],
+ txt: ["#888888", "≡"],
+ rs: ["#dea584", "R"],
+ lock: ["#888888", "🔒"],
+ cfg: ["#6d8086", "⚙"],
+ ini: ["#6d8086", "⚙"],
+ sh: ["#89e051", "$"],
+ gitignore: ["#41535b", "◆"],
+ };
+
+ function treeHTML(items) {
+ return items
+ .map((it) => {
+ const pad = 8 + it.depth * 8;
+ if (it.dir) {
+ return `<div class="ti" style="padding-left:${pad}px"><span class="chev">${it.open ? "⌄" : "›"}</span><span class="nm">${it.name}</span>${it.gs ? `<span class="gs ${it.gs === "M" ? "m" : "u"}" style="opacity:.6">●</span>` : ""}</div>`;
+ }
+ const ext = it.name.includes(".") ? it.name.split(".").pop() : "txt";
+ const [color, glyph] = FILE_BADGES[ext] || FILE_BADGES.txt;
+ const cls = [it.active ? "active" : "", it.gs === "M" ? "mod" : it.gs === "U" ? "unt" : ""].join(" ");
+ return `<div class="ti ${cls}" style="padding-left:${pad + 16}px"><span class="fi" style="color:${color}">${glyph}</span><span class="nm">${it.name}</span>${it.gs ? `<span class="gs ${it.gs === "M" ? "m" : "u"}">${it.gs}</span>` : ""}</div>`;
+ })
+ .join("");
+ }
+
+ function buildWorkbench(cfg) {
+ document.body.classList.add(cfg.theme === "dark" ? "theme-dark" : "theme-light");
+ const tabs = cfg.tabs
+ .map((t) => {
+ const ext = t.name.split(".").pop();
+ const [color, glyph] = FILE_BADGES[ext] || FILE_BADGES.txt;
+ return `<div class="tab${t.active ? " active" : ""}${t.preview ? " preview" : ""}" data-name="${t.name}"><span class="fi" style="color:${color};font:700 10px 'DejaVu Sans Mono'">${glyph}</span><span class="${t.preview ? "it" : ""}">${t.name}</span><span class="x">${t.active ? "×" : ""}</span></div>`;
+ })
+ .join("");
+ const crumbs = cfg.crumbs.map((c, i) => `<span>${c}</span>${i < cfg.crumbs.length - 1 ? '<span class="sep">❯</span>' : ""}`).join("");
+ document.body.innerHTML = `
+<div id="wb">
+ <div id="titlebar">
+ <svg class="appicon" viewBox="0 0 24 24"><path d="M17 2 8 11 4 8 2 9v6l2 1 4-3 9 9 5-2V4z" fill="#0078d4"/><path d="M17 7v10l-6-5z" fill="#fff"/></svg>
+ <div class="menu">${["File", "Edit", "Selection", "View", "Go", "Run", "Terminal", "Help"].map((m) => `<span>${m}</span>`).join("")}</div>
+ <div class="cc">${icon("search")}<span>${cfg.project}</span></div>
+ <div class="layout">${icon("layout1")}${icon("layout2")}${icon("layout3")}</div>
+ <div class="wctl"><span>${icon("min")}</span><span>${icon("max")}</span><span>${icon("close")}</span></div>
+ </div>
+ <div id="main">
+ <div id="activity">
+ <div class="ai active">${icon("files")}</div>
+ <div class="ai">${icon("search")}</div>
+ <div class="ai">${icon("scm")}<span class="badge">${cfg.scmCount}</span></div>
+ <div class="ai">${icon("run")}</div>
+ <div class="ai">${icon("ext")}</div>
+ <div class="ai">${icon("test")}</div>
+ <div class="spacer"></div>
+ <div class="ai">${icon("account")}</div>
+ <div class="ai">${icon("gear")}</div>
+ </div>
+ <div id="sidebar">
+ <div class="sb-head">EXPLORER<span class="acts">${icon("more")}</span></div>
+ <div class="sec">⌄ ${cfg.project.toUpperCase()}<span style="margin-left:auto;display:flex;gap:6px;padding-right:8px;opacity:.8;font-weight:400">${icon("newfile")}${icon("refresh")}${icon("collapse")}</span></div>
+ <div class="tree">${treeHTML(cfg.tree)}</div>
+ <div class="outline"><div class="sec">› OUTLINE</div><div class="sec">› TIMELINE</div></div>
+ </div>
+ <div id="edarea">
+ <div id="tabs">${tabs}<div class="tacts">${icon("run")}${icon("split")}${icon("more")}</div></div>
+ <div id="crumbs">${crumbs}</div>
+ <div id="editor"></div>
+ ${cfg.panel ? '<div id="panel"></div>' : ""}
+ </div>
+ </div>
+ <div id="statusbar">
+ <div class="si remote">&gt;&lt;</div>
+ <div class="si">${icon("branch")}<span>${cfg.branch}</span></div>
+ <div class="si">${icon("sync")}</div>
+ <div class="si">${icon("err")}<span>0</span>${icon("warn")}<span>${cfg.warnings}</span></div>
+ <div class="right">
+ <div class="si" id="st-pos">Ln 1, Col 1</div>
+ <div class="si">Spaces: 4</div>
+ <div class="si">UTF-8</div>
+ <div class="si">LF</div>
+ <div class="si">${cfg.langLabel}</div>
+ ${cfg.interp ? `<div class="si">${cfg.interp}</div>` : ""}
+ <div class="si">${icon("bell")}</div>
+ </div>
+ </div>
+</div>`;
+ const pos = document.getElementById("st-pos");
+ const activeTab = document.querySelector(".tab.active");
+ const editor = new CodeEditor(document.getElementById("editor"), {
+ text: cfg.source,
+ lang: cfg.lang,
+ minimapColors: cfg.minimapColors,
+ onStatus: ({ line, col }) => {
+ pos.textContent = `Ln ${line}, Col ${col}`;
+ },
+ onDirty: () => {
+ if (!activeTab.classList.contains("dirty")) {
+ activeTab.classList.add("dirty");
+ activeTab.querySelector(".x").textContent = "●";
+ cap.event("dirty");
+ }
+ },
+ });
+ editor.onSave = () => {
+ activeTab.classList.remove("dirty");
+ activeTab.querySelector(".x").textContent = "×";
+ cap.event("save");
+ };
+ return editor;
+ }
+
+ window.buildWorkbench = buildWorkbench;
+ window.MINIMAP_LIGHT = {
+ plain: "#00000055",
+ kw: "#af00db99",
+ st: "#0000ff99",
+ self: "#0000ff99",
+ str: "#a3151599",
+ com: "#00800099",
+ num: "#09865899",
+ fn: "#795e2699",
+ ty: "#267f9999",
+ var: "#00108099",
+ mac: "#0000ff99",
+ pp: "#0000ff99",
+ slider: "#64646420",
+ };
+ window.MINIMAP_DARK = {
+ plain: "#d4d4d455",
+ kw: "#c586c099",
+ st: "#569cd699",
+ self: "#569cd699",
+ str: "#ce917899",
+ com: "#6a995599",
+ num: "#b5cea899",
+ fn: "#dcdcaa99",
+ ty: "#4ec9b099",
+ var: "#9cdcfe99",
+ mac: "#569cd699",
+ pp: "#c586c099",
+ slider: "#79797933",
+ };
+})();
diff --git a/capcodec/bench/corpus/pages/dark.html b/capcodec/bench/corpus/pages/dark.html
new file mode 100644
index 000000000..faf35a60b
--- /dev/null
+++ b/capcodec/bench/corpus/pages/dark.html
@@ -0,0 +1,362 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>inflate.c - zlib - Visual Studio Code</title>
+<link rel="stylesheet" href="common/workbench.css">
+<style>
+#editor {
+ flex: 1;
+ min-height: 0;
+}
+#panel {
+ height: 404px;
+ flex: none;
+ border-top: 1px solid var(--panel-border);
+ background: var(--panel-bg);
+ display: flex;
+ flex-direction: column;
+}
+#panel .ph {
+ height: 35px;
+ display: flex;
+ align-items: center;
+ padding: 0 8px 0 12px;
+ gap: 22px;
+ font-size: 11px;
+ letter-spacing: 0.03em;
+ color: #969696;
+ flex: none;
+}
+#panel .ph .pt.active {
+ color: #e7e7e7;
+ box-shadow: inset 0 -1px 0 #e7e7e7;
+ padding: 8px 0;
+}
+#panel .ph .pt .cnt {
+ background: #616161;
+ color: #fff;
+ border-radius: 9px;
+ padding: 0 5px;
+ margin-left: 4px;
+ font-size: 10px;
+}
+#panel .ph .pacts {
+ margin-left: auto;
+ display: flex;
+ gap: 10px;
+ align-items: center;
+ color: #c5c5c5;
+}
+#panel .ph .shell {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ font-size: 12px;
+ letter-spacing: 0;
+}
+#term {
+ flex: 1;
+ min-height: 0;
+ display: flex;
+ padding-left: 20px;
+}
+.term-scroller {
+ flex: 1;
+ overflow-y: scroll;
+ overflow-x: hidden;
+}
+.term-scroller::-webkit-scrollbar {
+ width: 10px;
+}
+.term-scroller::-webkit-scrollbar-thumb {
+ background: #79797966;
+}
+.term-body {
+ font-family: "JetBrains Mono", "DejaVu Sans Mono", monospace;
+ font-size: 13px;
+ line-height: 17px;
+ color: #cccccc;
+ white-space: pre;
+ padding-bottom: 2px;
+ font-variant-ligatures: none;
+}
+.tl {
+ height: 17px;
+ overflow: hidden;
+}
+.tcur {
+ background: #cccccc80;
+ outline: 1px solid #cccccc;
+}
+#term.focused .tcur {
+ background: #cccccc;
+}
+.c-g {
+ color: #0dbc79;
+}
+.c-b {
+ color: #3b8eea;
+}
+.c-y {
+ color: #e5e510;
+}
+.c-r {
+ color: #f14c4c;
+}
+.c-c {
+ color: #11a8cd;
+}
+.c-m {
+ color: #d670d6;
+}
+.c-k {
+ color: #8a8a8a;
+}
+.b {
+ font-weight: 700;
+}
+#term-tabs {
+ width: 168px;
+ flex: none;
+ border-left: 1px solid #80808059;
+ font-size: 13px;
+ color: #cccccc;
+ padding-top: 2px;
+}
+#term-tabs .tt {
+ height: 22px;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding-left: 10px;
+}
+#term-tabs .tt.active {
+ background: #37373d;
+ box-shadow: inset 1px 0 0 #007fd4;
+}
+</style>
+<script src="common/cap.js"></script>
+<script src="common/editor.js"></script>
+<script src="common/workbench.js"></script>
+<script src="common/terminal.js"></script>
+<script src="data/inflate_c.js"></script>
+</head>
+<body>
+<script>
+const editor = buildWorkbench({
+ theme: "dark",
+ project: "zlib",
+ branch: "fix/window-reset*",
+ scmCount: 2,
+ warnings: 4,
+ lang: "c",
+ langLabel: "C",
+ interp: "Linux",
+ panel: true,
+ source: window.SOURCE_INFLATE_C,
+ minimapColors: MINIMAP_DARK,
+ crumbs: ["zlib", "inflate.c", "inflateResetKeep(z_streamp)"],
+ tabs: [
+ { name: "inflate.c", active: true },
+ { name: "inflate.h" },
+ { name: "inftrees.c" },
+ { name: "fuzz_inflate.c", preview: true },
+ { name: "Makefile.in" },
+ ],
+ tree: [
+ { depth: 0, dir: true, name: ".github" },
+ { depth: 0, dir: true, name: "amiga" },
+ { depth: 0, dir: true, name: "contrib" },
+ { depth: 0, dir: true, name: "doc" },
+ { depth: 0, dir: true, name: "examples" },
+ { depth: 0, dir: true, open: true, name: "fuzz", gs: "U" },
+ { depth: 1, dir: true, name: "corpus" },
+ { depth: 1, name: "fuzz_inflate.c", gs: "U" },
+ { depth: 0, dir: true, name: "test" },
+ { depth: 0, name: "adler32.c" },
+ { depth: 0, name: "compress.c" },
+ { depth: 0, name: "crc32.c" },
+ { depth: 0, name: "crc32.h" },
+ { depth: 0, name: "deflate.c" },
+ { depth: 0, name: "deflate.h" },
+ { depth: 0, name: "gzguts.h" },
+ { depth: 0, name: "infback.c" },
+ { depth: 0, name: "inffast.c" },
+ { depth: 0, name: "inffixed.h" },
+ { depth: 0, name: "inflate.c", active: true, gs: "M" },
+ { depth: 0, name: "inflate.h", gs: "M" },
+ { depth: 0, name: "inftrees.c" },
+ { depth: 0, name: "inftrees.h" },
+ { depth: 0, name: "Makefile.in" },
+ { depth: 0, name: "README" },
+ { depth: 0, name: "trees.c" },
+ { depth: 0, name: "zconf.h" },
+ { depth: 0, name: "zlib.h" },
+ { depth: 0, name: "zutil.c" },
+ { depth: 0, name: "zutil.h" },
+ ],
+});
+window.capEditor = editor;
+
+const panel = document.getElementById("panel");
+panel.innerHTML = `<div class="ph">
+ <span class="pt">PROBLEMS<span class="cnt">4</span></span><span class="pt">OUTPUT</span><span class="pt">DEBUG CONSOLE</span><span class="pt active">TERMINAL</span><span class="pt">PORTS</span>
+ <span class="pacts"><span class="shell">${wbIcon("term")} bash</span>${wbIcon("plus")}${wbIcon("split")}${wbIcon("trash")}${wbIcon("more")}${wbIcon("chevup")}${wbIcon("close")}</span></div>
+ <div id="term"></div>`;
+const termHost = document.getElementById("term");
+const PROMPT = '<span class="c-g b">dev@buildbox</span>:<span class="c-b b">~/src/zlib</span>$ ';
+
+const SOURCES = "adler32 crc32 deflate infback inffast inflate inftrees trees zutil compress uncompr gzclose gzlib gzread gzwrite".split(" ");
+const MUTATIONS = "ChangeBit EraseBytes InsertByte CopyPart ChangeByte ShuffleBytes CrossOver InsertRepeatedBytes ChangeBinInt PersAutoDict ChangeASCIIInt CMP ManualDict".split(" ");
+
+function fuzzState(rng) {
+ return { execs: 2097152 + Math.floor(rng() * 100000), cov: 1184, ft: 5873, corp: 642, kb: 318, rss: 412 };
+}
+
+function fuzzLine(s, rng) {
+ const r = rng();
+ s.execs += 300 + Math.floor(rng() * 5000);
+ let kind = "REDUCE";
+ if (r < 0.22) {
+ kind = "NEW ";
+ s.cov += rng() < 0.4 ? 1 : 0;
+ s.ft += 1 + Math.floor(rng() * 6);
+ s.corp += 1;
+ s.kb += Math.floor(rng() * 3);
+ } else if (r < 0.3) {
+ kind = "pulse ";
+ }
+ if (rng() < 0.05) s.rss += 1;
+ const n = 1 + Math.floor(rng() * 4);
+ const ms = [];
+ for (let i = 0; i < n; i++) ms.push(MUTATIONS[Math.floor(rng() * MUTATIONS.length)]);
+ const L = 1 + Math.floor(rng() * 3800);
+ const eps = 41000 + Math.floor(rng() * 9000);
+ const tail = kind === "pulse " ? "" : ` L: ${L}/4096 MS: ${n} ${ms.join("-")}-`;
+ return `#${s.execs}\t${kind} cov: ${s.cov} ft: ${s.ft} corp: ${s.corp}/${s.kb}Kb lim: 4096 exec/s: ${eps} rss: ${s.rss}Mb${tail}`;
+}
+
+function* fuzzer(rng, s, header) {
+ if (header) {
+ yield [60, ["INFO: Running with entropic power schedule (0xFF, 100).", "INFO: Seed: 1803446715"]];
+ yield [40, ["INFO: Loaded 1 modules (2316 inline 8-bit counters): 2316 [0x5603a2f0, 0x5603ac1c),"]];
+ yield [30, ["INFO: Loaded 1 PC tables (2316 PCs): 2316 [0x5603ac20,0x56044ee0),"]];
+ yield [180, ["INFO: 642 files found in corpus/", "INFO: -max_len is not provided; libFuzzer will not generate inputs larger than 4096 bytes"]];
+ yield [420, ["INFO: seed corpus: files: 642 min: 1b max: 4096b total: 325873b rss: 38Mb", `#643\tINITED cov: ${s.cov} ft: ${s.ft} corp: ${s.corp}/${s.kb}Kb exec/s: 0 rss: 61Mb`]];
+ }
+ for (;;) {
+ const r = rng();
+ if (r < 0.12) {
+ const lines = [];
+ const n = 4 + Math.floor(rng() * 10);
+ for (let i = 0; i < n; i++) lines.push(fuzzLine(s, rng));
+ yield [30, lines];
+ } else {
+ yield [90 + Math.floor(rng() * 520), [fuzzLine(s, rng)]];
+ }
+ }
+}
+
+const fstate = { s: null };
+function fuzzCommand(cmd, rng, t, header = true) {
+ fstate.s = fstate.s || fuzzState(rng);
+ const g = fuzzer(rng, fstate.s, header);
+ g.onInterrupt = () => [
+ "==31337== libFuzzer: run interrupted; exiting",
+ `stat::number_of_executed_units: ${fstate.s.execs}`,
+ "stat::average_exec_per_sec: 45871",
+ "stat::new_units_added: 1288",
+ "stat::slowest_unit_time_sec: 0",
+ `stat::peak_rss_mb: ${fstate.s.rss}`,
+ ];
+ return g;
+}
+
+function* makeTest(rng) {
+ const flags = "-O3 -Wall -D_LARGEFILE64_SOURCE=1 -DHAVE_HIDDEN -I.";
+ for (const s of SOURCES) yield [90 + Math.floor(rng() * 260), [`gcc ${flags} -c -o ${s}.o ${s}.c`]];
+ yield [120, [`ar rc libz.a ${SOURCES.map((s) => `${s}.o`).join(" ")}`]];
+ yield [60, [`gcc ${flags} -c -o example.o test/example.c`, `gcc ${flags} -c -o minigzip.o test/minigzip.c`]];
+ yield [240, [`gcc ${flags} -o example example.o -L. libz.a`, `gcc ${flags} -o minigzip minigzip.o -L. libz.a`]];
+ yield [300, ["hello world", "zlib version 1.3.1.1-motley = 0x1311, compile flags = 0xa9", "uncompress(): hello, hello!"]];
+ yield [80, ["gzread(): hello, hello!", "gzgets() after gzseek: hello!", "inflate(): hello, hello!"]];
+ yield [400, ["large_inflate(): OK", "after inflateSync(): hello, hello!", "inflate with dictionary: hello, hello!"]];
+ yield [60, ['\t\t<span class="c-g">*** zlib test OK ***</span>']];
+ yield [200, ["hello world", "zlib version 1.3.1.1-motley = 0x1311, compile flags = 0xa9", "uncompress(): hello, hello!", "gzread(): hello, hello!"]];
+ yield [120, ["inflate(): hello, hello!", "large_inflate(): OK", '\t\t<span class="c-g">*** zlib shared test OK ***</span>']];
+}
+
+function* gitStatus() {
+ yield [40, [
+ "On branch fix/window-reset",
+ "Your branch is ahead of 'origin/fix/window-reset' by 1 commit.",
+ ' (use "git push" to publish your local commits)',
+ "",
+ "Changes not staged for commit:",
+ ' (use "git add &lt;file&gt;..." to update what will be committed)',
+ ' (use "git restore &lt;file&gt;..." to discard changes in working directory)',
+ '\t<span class="c-r">modified: inflate.c</span>',
+ '\t<span class="c-r">modified: inflate.h</span>',
+ "",
+ "Untracked files:",
+ ' (use "git add &lt;file&gt;..." to include in what will be committed)',
+ '\t<span class="c-r">fuzz/</span>',
+ "",
+ ]];
+}
+
+const term = new Terminal(termHost, {
+ seed: 1234,
+ prompt: PROMPT,
+ commands: {
+ "./fuzz": fuzzCommand,
+ make: (cmd, rng) => makeTest(rng),
+ "git status": () => gitStatus(),
+ clear: (cmd, rng, t) => {
+ t.body.innerHTML = "";
+ return (function* () {})();
+ },
+ },
+});
+const tabsEl = document.createElement("div");
+tabsEl.id = "term-tabs";
+tabsEl.innerHTML = `<div class="tt">${wbIcon("term")} bash</div><div class="tt active">${wbIcon("term")} fuzz_inflate</div>`;
+termHost.append(tabsEl);
+term.onFocus = () => editor.blur();
+editor.onFocus = () => term.blur();
+
+const history = [
+ `${PROMPT}make -j4 fuzz_inflate`,
+ "clang -g -O1 -fsanitize=fuzzer,address -I. -o fuzz_inflate fuzz/fuzz_inflate.c libz.a",
+ `${PROMPT}./fuzz_inflate -jobs=1 -max_len=4096 corpus/`,
+];
+for (const h of history) term.line(h);
+const prng = mulberry32(99);
+fstate.s = fuzzState(prng);
+const pre = fuzzer(prng, fstate.s, true);
+for (let i = 0; i < 30; i++) for (const l of pre.next().value[1]) term.line(l);
+const live = fuzzCommand("./fuzz", term.rng, term, false);
+
+editor.scrollTo(118 * 19);
+editor.caret = { line: 141, col: 0 };
+editor.updateCaret(false);
+editor.focus();
+term.blur();
+editor.focused = false;
+editor.host.classList.remove("focused");
+
+window.capStart = () => term.start(live);
+window.capTerm = term;
+window.capTextRegions = () => {
+ const t = term.scroller.getBoundingClientRect();
+ const e = editor.scroller.getBoundingClientRect();
+ return [
+ [e.left, e.top + 4, 720, Math.floor(e.height - 8)],
+ [t.left, t.top + 2, 1100, Math.floor(t.height - 4)],
+ ];
+};
+capSetReady();
+</script>
+</body>
+</html>
diff --git a/capcodec/bench/corpus/pages/dashboard.html b/capcodec/bench/corpus/pages/dashboard.html
new file mode 100644
index 000000000..994cebc4f
--- /dev/null
+++ b/capcodec/bench/corpus/pages/dashboard.html
@@ -0,0 +1,479 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Overview · Production · Pulseboard</title>
+<style>
+* {
+ box-sizing: border-box;
+}
+html,
+body {
+ margin: 0;
+ height: 100%;
+ overflow: hidden;
+ background: #f5f6f8;
+ font-family: "Noto Sans", "Liberation Sans", sans-serif;
+ color: #1b1f24;
+ font-size: 12px;
+ cursor: default;
+ user-select: none;
+}
+.num {
+ font-variant-numeric: tabular-nums;
+}
+header {
+ height: 52px;
+ background: #fff;
+ border-bottom: 1px solid #e3e6ea;
+ display: flex;
+ align-items: center;
+ padding: 0 20px;
+ gap: 24px;
+}
+.brand {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ font-weight: 700;
+ font-size: 15px;
+}
+.brand .lg {
+ width: 24px;
+ height: 24px;
+ border-radius: 7px;
+ background: conic-gradient(from 200deg, #22c55e, #06b6d4, #6366f1, #22c55e);
+}
+nav {
+ display: flex;
+ gap: 4px;
+ height: 100%;
+}
+nav span {
+ display: flex;
+ align-items: center;
+ padding: 0 12px;
+ font-size: 13px;
+ color: #5b6573;
+ border-bottom: 2px solid transparent;
+}
+nav span:hover {
+ color: #1b1f24;
+}
+nav span.on {
+ color: #1b1f24;
+ font-weight: 600;
+ border-bottom-color: #4f46e5;
+}
+.hr {
+ margin-left: auto;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+}
+.sel {
+ height: 30px;
+ border: 1px solid #dde1e6;
+ border-radius: 7px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 0 10px;
+ font-size: 12.5px;
+ background: #fff;
+}
+.sel:hover {
+ border-color: #c4c9d0;
+ background: #fafbfc;
+}
+.sel .car {
+ font-size: 9px;
+ color: #8a94a3;
+}
+.live {
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ font-size: 12px;
+ font-weight: 600;
+ color: #15803d;
+ background: #dcfce7;
+ border-radius: 999px;
+ padding: 4px 11px;
+}
+.live i {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: #22c55e;
+ box-shadow: 0 0 0 0 #22c55e80;
+ animation: pulse 1.6s infinite;
+}
+@keyframes pulse {
+ 0% {
+ box-shadow: 0 0 0 0 #22c55e80;
+ }
+ 70% {
+ box-shadow: 0 0 0 7px #22c55e00;
+ }
+ 100% {
+ box-shadow: 0 0 0 0 #22c55e00;
+ }
+}
+.avatar {
+ width: 30px;
+ height: 30px;
+ border-radius: 50%;
+ background: #0891b2;
+ color: #fff;
+ font-weight: 700;
+ font-size: 12px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+main {
+ padding: 14px 20px;
+ display: grid;
+ grid-template-columns: repeat(12, 1fr);
+ grid-auto-rows: min-content;
+ gap: 12px;
+}
+.panel {
+ background: #fff;
+ border: 1px solid #e3e6ea;
+ border-radius: 10px;
+ padding: 12px 14px;
+ position: relative;
+}
+.panel h4 {
+ margin: 0 0 8px;
+ font-size: 12.5px;
+ font-weight: 600;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+.panel h4 .sub {
+ color: #8a94a3;
+ font-weight: 400;
+ font-size: 11.5px;
+}
+.panel h4 .acts {
+ margin-left: auto;
+ color: #8a94a3;
+ font-weight: 400;
+ display: flex;
+ gap: 10px;
+ font-size: 11px;
+}
+.kpi {
+ grid-column: span 2;
+ height: 104px;
+ display: flex;
+ flex-direction: column;
+}
+.kpi .lab {
+ font-size: 11px;
+ color: #6b7583;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+ font-weight: 600;
+}
+.kpi .val {
+ font-size: 26px;
+ font-weight: 700;
+ margin-top: 4px;
+ letter-spacing: -0.01em;
+}
+.kpi .val small {
+ font-size: 14px;
+ color: #6b7583;
+ font-weight: 600;
+ margin-left: 2px;
+}
+.kpi .dl {
+ font-size: 11.5px;
+ margin-top: auto;
+ display: flex;
+ gap: 6px;
+ align-items: center;
+}
+.up {
+ color: #15803d;
+}
+.dn {
+ color: #b91c1c;
+}
+.kpi .dl .vs {
+ color: #8a94a3;
+}
+.kpi canvas {
+ position: absolute;
+ right: 12px;
+ top: 34px;
+ width: 112px;
+ height: 40px;
+}
+.chart {
+ grid-column: span 7;
+ height: 318px;
+}
+.chart.r {
+ grid-column: span 5;
+}
+.chart canvas {
+ width: 100%;
+ height: 262px;
+ display: block;
+}
+.legend {
+ display: flex;
+ gap: 14px;
+ font-size: 11.5px;
+ color: #4b5563;
+ position: absolute;
+ right: 14px;
+ top: 12px;
+}
+.legend span {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+}
+.legend i {
+ width: 10px;
+ height: 3px;
+ border-radius: 2px;
+}
+.tbl {
+ grid-column: span 8;
+}
+table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: 11.5px;
+}
+th {
+ text-align: right;
+ font-weight: 600;
+ color: #6b7583;
+ font-size: 11px;
+ padding: 5px 8px;
+ border-bottom: 1px solid #e3e6ea;
+ white-space: nowrap;
+}
+th:first-child,
+td:first-child {
+ text-align: left;
+}
+td {
+ text-align: right;
+ padding: 3px 8px;
+ border-bottom: 1px solid #f0f2f4;
+ height: 24px;
+ white-space: nowrap;
+}
+tr:hover td {
+ background: #f7f8fb;
+}
+td.ep {
+ font-family: "JetBrains Mono", "DejaVu Sans Mono", monospace;
+ font-size: 11px;
+ color: #1f2937;
+}
+td .m {
+ display: inline-block;
+ width: 42px;
+ font-family: "Noto Sans", sans-serif;
+ font-weight: 700;
+ font-size: 10px;
+ color: #6b7583;
+}
+td canvas {
+ width: 90px;
+ height: 18px;
+ vertical-align: middle;
+}
+.bar {
+ display: inline-block;
+ width: 54px;
+ height: 6px;
+ border-radius: 3px;
+ background: #eef0f3;
+ vertical-align: middle;
+ overflow: hidden;
+ margin-left: 6px;
+}
+.bar i {
+ display: block;
+ height: 100%;
+ background: #22c55e;
+}
+.flash {
+ animation: flash 0.9s ease-out;
+}
+@keyframes flash {
+ 0% {
+ background: #fff4c2;
+ }
+ 100% {
+ background: transparent;
+ }
+}
+.side {
+ grid-column: span 4;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+.errs .er {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 11.5px;
+ margin-bottom: 7px;
+}
+.errs .er .n {
+ width: 150px;
+ color: #374151;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.errs .er .b {
+ flex: 1;
+ height: 8px;
+ background: #f1f3f5;
+ border-radius: 4px;
+ overflow: hidden;
+}
+.errs .er .b i {
+ display: block;
+ height: 100%;
+ background: #f87171;
+ border-radius: 4px;
+ transition: width 0.5s ease;
+}
+.errs .er .c {
+ width: 44px;
+ text-align: right;
+ color: #4b5563;
+}
+.feed {
+ flex: 1;
+ overflow: hidden;
+ height: 236px;
+}
+.ev {
+ display: flex;
+ gap: 8px;
+ font-size: 11.5px;
+ padding: 5px 0;
+ border-bottom: 1px solid #f0f2f4;
+ align-items: center;
+ white-space: nowrap;
+ overflow: hidden;
+}
+.ev .t {
+ color: #8a94a3;
+ font-family: "JetBrains Mono", monospace;
+ font-size: 10.5px;
+}
+.ev .lv {
+ font-size: 10px;
+ font-weight: 700;
+ border-radius: 4px;
+ padding: 0 5px;
+ line-height: 16px;
+}
+.lv.info {
+ background: #e0f2fe;
+ color: #0369a1;
+}
+.lv.warn {
+ background: #fef3c7;
+ color: #92400e;
+}
+.lv.err {
+ background: #fee2e2;
+ color: #b91c1c;
+}
+.ev.new {
+ animation: slidein 0.35s ease-out;
+}
+@keyframes slidein {
+ from {
+ transform: translateY(-14px);
+ opacity: 0;
+ }
+ to {
+ transform: none;
+ opacity: 1;
+ }
+}
+#tip {
+ position: absolute;
+ display: none;
+ pointer-events: none;
+ background: #111827;
+ color: #f9fafb;
+ font-size: 11.5px;
+ border-radius: 7px;
+ padding: 7px 10px;
+ line-height: 1.55;
+ z-index: 10;
+ box-shadow: 0 6px 18px #0003;
+ white-space: nowrap;
+}
+#tip i {
+ display: inline-block;
+ width: 8px;
+ height: 8px;
+ border-radius: 2px;
+ margin-right: 6px;
+}
+.statusline {
+ position: fixed;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ height: 26px;
+ background: #fff;
+ border-top: 1px solid #e3e6ea;
+ display: flex;
+ align-items: center;
+ gap: 18px;
+ padding: 0 20px;
+ font-size: 11.5px;
+ color: #6b7583;
+}
+.statusline .ok {
+ color: #15803d;
+ font-weight: 600;
+}
+</style>
+<script src="common/cap.js"></script>
+<script src="common/terminal.js"></script>
+</head>
+<body>
+<header>
+ <div class="brand"><span class="lg"></span>Pulseboard</div>
+ <nav><span class="on">Overview</span><span>Traffic</span><span>Performance</span><span>Errors</span><span>Revenue</span><span>Alerts</span></nav>
+ <div class="hr">
+ <span class="sel" id="env">● <b style="font-weight:600">Production</b> · eu-west-1<span class="car">▼</span></span>
+ <span class="sel" id="range">Last 1 hour<span class="car">▼</span></span>
+ <span class="live"><i></i>Live</span>
+ <span class="sel" id="refresh">↻ <span id="cd" class="num">1s</span></span>
+ <span class="avatar">SW</span>
+ </div>
+</header>
+<main id="grid"></main>
+<div id="tip"></div>
+<div class="statusline"><span class="ok">● All systems operational</span><span>Last updated <b id="upd" class="num"></b></span><span>Ingest lag <b id="lag" class="num">0.8 s</b></span><span>Data points <b id="pts" class="num">1,284,331</b></span><span style="margin-left:auto">Region eu-west-1 · 12 hosts · 48 pods</span></div>
+<script src="common/dashboard.js"></script>
+<script>
+capSetReady();
+</script>
+</body>
+</html>
diff --git a/capcodec/bench/corpus/pages/data/article_text.js b/capcodec/bench/corpus/pages/data/article_text.js
new file mode 100644
index 000000000..2dfb91960
--- /dev/null
+++ b/capcodec/bench/corpus/pages/data/article_text.js
@@ -0,0 +1,120 @@
+window.ARTICLE = [
+ {
+ lead: true,
+ html: `
+<p>A <b>typewriter</b> is a mechanical or electromechanical machine for typing characters. Typically, a typewriter has an array of keys, and each one causes a different single character to be produced on paper by striking an inked ribbon selectively against the paper with a type element. Thereby, the machine produces a legible written document composed of ink and paper. By the end of the 19th century, the term "typewriter" was also applied to a person who used such a device.<sup>[1]</sup></p>
+<p>The first commercial typewriters were introduced in 1874, but did not become common in offices in the United States until after the mid-1880s.<sup>[2]</sup> The typewriter quickly became an indispensable tool for practically all writing other than personal handwritten correspondence. It was widely used by professional writers, in offices, in business correspondence in private homes, and by students preparing written assignments.</p>
+<p>Typewriters were a standard fixture in most offices up to the 1980s. After that, they began to be largely supplanted by <a data-p="Personal computer">personal computers</a> running <a data-p="Word processor">word processing</a> software. Nevertheless, typewriters remain common in some parts of the world. For example, typewriters are still used in many Indian cities and towns, especially in roadside and legal offices, due to a lack of continuous, reliable electricity.<sup>[3]</sup></p>
+<p>The <a data-p="QWERTY">QWERTY</a> keyboard layout, developed for typewriters in the 1870s, remains the de facto standard for English-language computer keyboards. The origins of this layout still need to be clarified.<sup>[4]</sup> Similar typewriter keyboards, with layouts optimised for other languages and orthographies, emerged soon afterward, and their layouts have also become standard for computer keyboards in their respective markets.</p>`,
+ },
+ {
+ h: 2,
+ title: "History",
+ html: `
+<p>Although many modern typewriters have one of several similar designs, their invention was incremental, developed by numerous inventors working independently or in competition with each other over a series of decades. As with the <a data-p="Automobile">automobile</a>, <a data-p="Telephone">telephone</a>, and <a data-p="Telegraphy">telegraph</a>, several people contributed insights and inventions that eventually resulted in ever more commercially successful instruments. Historians have estimated that some form of typewriter was invented 52 times as thinkers tried to come up with a workable design.<sup>[5]</sup></p>`,
+ },
+ {
+ h: 3,
+ title: "Early innovations",
+ html: `
+{fig:pellegrino}
+<p>Some of the early typing instruments include: In 1575, an Italian printmaker, Francesco Rampazetto, invented the <i>scrittura tattile</i>, a machine to impress letters in papers.<sup>[6]</sup> In 1714, Henry Mill obtained a patent in Britain for a machine that, from the patent, appears to have been similar to a typewriter. The patent shows that this machine was actually created: "[he] hath by his great study and paines &amp; expence invented and brought to perfection an artificial machine or method for impressing or transcribing of letters, one after another, as in writing, whereby all writing whatsoever may be engrossed in paper or parchment so neat and exact as not to be distinguished from print."<sup>[7]</sup></p>
+<p>In 1802, Italian Agostino Fantoni developed a particular typewriter to enable his blind sister to write.<sup>[8]</sup> Between 1801 and 1808, Italian Pellegrino Turri invented a typewriter for his blind friend Countess Carolina Fantoni da Fivizzano.<sup>[9]</sup> In 1823, Italian Pietro Conti di Cilavegna invented a new model of typewriter, the <i>tachigrafo</i>, also known as <i>tachitipo</i>.<sup>[10]</sup> In 1829, American William Austin Burt patented a machine called the "Typographer" which, in common with many other early machines, is listed as the "first typewriter". The London Science Museum describes it merely as "the first writing mechanism whose invention was documented", but even that claim may be excessive, since Turri's invention pre-dates it.<sup>[11]</sup></p>
+<p>By the mid-19th century, the increasing pace of business communication had created a need for mechanisation of the writing process. Stenographers and telegraphers could take down information at rates up to 130 words per minute, whereas a writer with a pen was limited to a maximum of 30 words per minute. From 1829 to 1870, many printing or typing machines were patented by inventors in Europe and America, but none went into commercial production.<sup>[12]</sup></p>
+<p>The Danish pastor Rasmus Malling-Hansen invented the "writing ball" in 1865, which became the first commercially sold typewriter. Its keys were arranged on a brass hemisphere, so that the letters struck the paper at a single central point, and the most frequently used letters were placed under the fastest fingers. The writing ball was used in offices in Copenhagen and London for several decades, and the philosopher Friedrich Nietzsche famously owned one, although he complained that it was difficult to keep in adjustment.<sup>[13]</sup></p>`,
+ },
+ {
+ h: 3,
+ title: "Sholes and Glidden",
+ html: `
+{fig:sholes}
+<p>The first typewriter to be commercially successful was patented in 1868 by Americans Christopher Latham Sholes, Frank Glidden and Samuel W. Soule in Milwaukee, Wisconsin, although Sholes soon disowned the machine and refused to use or even recommend it.<sup>[14]</sup> The working prototype was made by clock-maker and machinist Matthias Schwalbach.<sup>[15]</sup> The patent (US 79,265) was sold for $12,000 to Densmore and Yost, who made an agreement with E. Remington and Sons, then famous as a manufacturer of sewing machines, to commercialise the machine as the Sholes and Glidden Type-Writer.</p>
+<p>Remington began production of its first typewriter on 1 March 1873, in Ilion, New York. It had a QWERTY keyboard layout, which, because of the machine's success, was slowly adopted by other typewriter manufacturers. As with most other early typewriters, because the typebars strike upwards, the typist could not see the characters as they were typed. The machine printed only capital letters, and a carriage return lever on the right had to be operated after every line, which gave rise to the phrase that is still used for the key that ends a line on a computer keyboard.<sup>[16]</sup></p>
+<p>Sales were slow at first. The machine was expensive, at $125, and it was marketed as a novelty for writers and clergymen rather than as an office tool. Mark Twain bought one in 1874 and claimed in his autobiography to have been the first author to submit a typewritten manuscript to a publisher, although historians disagree about which of his books it was.<sup>[17]</sup> The improved Remington No. 2 of 1878 added a shift key, which allowed both upper and lower case letters to be typed with the same set of typebars, and from that point demand grew steadily.</p>`,
+ },
+ {
+ h: 3,
+ title: "Standardization",
+ html: `
+<p>By about 1910, the "manual" or "mechanical" typewriter had reached a somewhat standardized design. There were minor variations from one manufacturer to another, but most typewriters followed the concept that each key was attached to a typebar that had the corresponding letter molded, in reverse, into its striking head. When a key was struck briskly and firmly, the typebar hit a ribbon, usually made of inked fabric, making a printed mark on the paper wrapped around a cylindrical platen.<sup>[18]</sup></p>
+<p>The platen was mounted on a carriage that moved horizontally to the left, automatically advancing the typing position, after each character was typed. The carriage-return lever at the far left was then pressed to the right to return the carriage to its starting position and rotating the platen to advance the paper vertically. A small bell was struck a few characters before the right hand margin was reached to warn the operator to complete the word and then use the carriage-return lever.<sup>[19]</sup></p>
+{table:models}
+<p>The front-strike "visible" typewriter, on which the typist could see the text as it was being written, was popularised by the Underwood No. 1 of 1895, designed by Franz Xaver Wagner. Within two decades almost every manufacturer had moved to the same arrangement, and the Underwood No. 5 became so common that its silhouette is still used as a generic picture of a typewriter. The machines were heavy, durable and easy to repair, and many offices kept the same machines in service for thirty years or more.<sup>[20]</sup></p>
+{fig:production}
+<p>Typing schools and secretarial colleges spread rapidly in the same period. Touch typing, in which the typist uses all ten fingers and does not look at the keyboard, was promoted from the 1880s and had become the standard method of instruction by the 1920s. Competitions between expert typists drew large audiences, and the fastest of them could sustain well over 140 words per minute for an hour on a manual machine.<sup>[21]</sup></p>`,
+ },
+ {
+ h: 3,
+ title: "Electric designs",
+ html: `
+<p>Although electric typewriters would not achieve widespread popularity until nearly a century later, the basic groundwork for the electric typewriter was laid by the Universal Stock Ticker, invented by Thomas Edison in 1870. This device remotely printed letters and numbers on a stream of paper tape from input generated by a specially designed typewriter at the other end of a telegraph line.<sup>[22]</sup></p>
+{fig:selectric}
+<p>The first electric typewriters to sell in quantity were produced in the 1920s and 1930s, but they were expensive and were mostly used for specialised work such as billing. IBM entered the market in 1933 by acquiring the Electromatic Typewriter Company, and its Model A and later models established a reputation for an even, consistent impression that made documents look almost as if they had been printed. Because the motor supplied the force for each stroke, the typist only needed to touch the keys lightly, which reduced fatigue and allowed several carbon copies to be made at once.<sup>[23]</sup></p>
+<p>In 1961, IBM introduced the Selectric, which replaced the typebars and moving carriage with a small spherical type element, often called a "golf ball", that moved across the page while the paper stayed still. The element could be swapped in seconds to change the font, and the machine could not jam when two keys were pressed close together. The Selectric and its successors eventually captured a large share of the office market, and later versions added a correction tape that could lift a mistyped character from the page.<sup>[24]</sup></p>`,
+ },
+ {
+ h: 3,
+ title: "Electronic typewriters and decline",
+ html: `
+<p>Electronic typewriters, which replaced most of the mechanical linkages with circuit boards and a daisy wheel or thimble print element, appeared in the late 1970s. Many of them included a small display and a memory of a few lines or pages, which allowed text to be corrected before it was printed. In this sense they became a stepping stone between the typewriter and the dedicated word processor, and some models could even be connected to a personal computer and used as a letter-quality printer.<sup>[25]</sup></p>
+<p>As personal computers and inexpensive printers became common in the late 1980s, sales of typewriters fell sharply. Smith-Corona, one of the last large American manufacturers, filed for bankruptcy protection in 1995, and by the early 2000s most of the remaining production had moved to Asia. In 2011 a widely reported news story claimed that the last typewriter factory in the world had closed; the claim was inaccurate, because several companies continued to make both manual and electronic machines.<sup>[26]</sup></p>`,
+ },
+ {
+ h: 2,
+ title: "Design",
+ html: ``,
+ },
+ {
+ h: 3,
+ title: "Typebar mechanism",
+ html: `
+{fig:typebar}
+<p>In a typical manual machine, each key lever is connected through a short linkage to a typebar arranged in a semicircular "basket". When the key is pressed, the typebar swings up and forward, and its slug strikes the ribbon against the paper at the printing point. At the same time a mechanism called the escapement releases the carriage, which is pulled one step to the left by a spring, so that the next character appears in the right place. Most designs move the carriage by a fixed distance for every character, which is why typewritten text uses monospaced fonts.<sup>[27]</sup></p>
+<p>The ribbon is advanced by a small amount after each keystroke and is guided by a vibrator that lifts it into position only while a character is being typed, so that the typist can see the most recent text. Many ribbons were printed with two colours, typically black and red, and a lever on the machine selected which half of the ribbon would be used. A stencil setting moved the ribbon out of the way altogether, so that the type slug cut directly into a wax stencil for use on a mimeograph machine.<sup>[28]</sup></p>`,
+ },
+ {
+ h: 3,
+ title: "Keyboard layouts",
+ html: `
+{fig:keyboard}
+<p>The QWERTY layout was designed by Sholes and his collaborators over a period of several years, and the version used on the 1873 Remington was already close to the modern layout. A widely repeated explanation is that the letters were arranged to slow down typists in order to prevent jams, but historians have argued that the layout was more probably shaped by the needs of telegraph operators who transcribed Morse code, and by the mechanical arrangement of the typebars in the basket.<sup>[29]</sup></p>
+{table:layouts}
+<p>Several alternative layouts have been proposed since then. The best known is the Dvorak Simplified Keyboard, patented in 1936 by August Dvorak and William Dealey, which places the most common letters of English on the home row. Studies of its benefits have produced conflicting results, and despite periodic interest it has never displaced QWERTY. In other countries, local variants such as QWERTZ in Germany and Central Europe and AZERTY in France and Belgium became standard, and most of them survive on computer keyboards today.<sup>[30]</sup></p>`,
+ },
+ {
+ h: 3,
+ title: "Correction methods",
+ html: `
+<p>Mistakes on a typewriter were difficult to correct, and many offices expected letters to be typed again from the beginning if an error was found. Typists used special erasers, made of a hard abrasive rubber, to remove single characters, often with a thin metal shield to protect neighbouring letters. Correction fluid, invented in the 1950s by Bette Nesmith Graham while she was working as a secretary in Dallas, made it possible to paint over a mistake and type again once the fluid had dried, and it became one of the best-selling office supplies of the twentieth century.<sup>[31]</sup></p>
+<p>Later, correction paper and lift-off tapes allowed the typist to backspace and strike the incorrect character again through a coated strip, which either covered the character with white powder or physically lifted the ink from the page. Electronic typewriters automated the process by keeping a record of the last characters typed and striking them again through the correction tape when the typist pressed a dedicated key.<sup>[32]</sup></p>`,
+ },
+ {
+ h: 2,
+ title: "Social impact",
+ html: `
+{fig:office}
+<p>When Remington started marketing typewriters, the company assumed the machine would not be used for composing but for transcribing dictation, and that the person typing would be a woman. The 1800s Sholes and Glidden typewriter had floral ornamentation on its case, and early advertising showed women at the keyboard. During World War I, increasing numbers of women entered the workforce, and the typewriter became one of the most important tools by which they did so.<sup>[33]</sup></p>
+<p>By the 1920s the great majority of typists and stenographers in the United States were women, and the job of secretary had become one of the most common occupations open to them. Historians have described the typewriter as one of the technologies that changed the relationship between women and paid office work, although the jobs it created were often poorly paid and offered little chance of promotion. The image of the typing pool, a large room of desks where typists worked under a supervisor, became a familiar part of office life in the middle of the century.<sup>[34]</sup></p>
+<p>Writers also adopted the machine. Some, such as Henry James in his later years, dictated their work to a typist, while others learned to compose directly at the keyboard. Ernest Hemingway was known to write standing up at a portable typewriter placed on a bookshelf, and Jack Kerouac typed the first draft of <i>On the Road</i> on a single continuous roll of paper about 37 metres long so that he would not have to stop to change sheets.<sup>[35]</sup></p>`,
+ },
+ {
+ h: 2,
+ title: "Collecting and revival",
+ html: `
+<p>Interest in old typewriters has grown since the early 2000s. Collectors look for early machines with unusual mechanisms, such as index typewriters that select letters with a pointer instead of keys, and for portable models from the 1930s to the 1960s, which are small enough to use every day. Online forums, repair guides and regional "type-in" meetings, where people gather in cafés to write letters on their machines, have helped to keep the necessary skills alive.<sup>[36]</sup></p>
+<p>Some writers and artists use typewriters precisely because they lack the distractions of a computer. Machines without a network connection also appeal to people who are concerned about surveillance, and several government offices have been reported to keep typewriters for producing especially sensitive documents.<sup>[37]</sup> The distinctive sound of typing, with its bell at the end of each line, has been used as a musical instrument, most famously in the orchestral piece <i>The Typewriter</i> by Leroy Anderson.<sup>[38]</sup></p>`,
+ },
+ { h: 2, title: "See also", html: `{seealso}` },
+ { h: 2, title: "References", html: `{refs}` },
+ {
+ h: 2,
+ title: "Further reading",
+ html: `<ul class="fr">
+<li>Beeching, Wilfred A. (1974). <i>Century of the Typewriter</i>. London: Heinemann. ISBN 978-0-434-90120-1.</li>
+<li>Current, Richard N. (1954). <i>The Typewriter and the Men Who Made It</i>. Urbana: University of Illinois Press.</li>
+<li>Polt, Richard (2015). <i>The Typewriter Revolution: A Typist's Companion for the 21st Century</i>. Woodstock, VT: Countryman Press. ISBN 978-1-58157-311-6.</li>
+<li>Yamada, Hisao (1980). "A historical study of typewriters and typing methods: from the position of planning Japanese parallels". <i>Journal of Information Processing</i>. <b>2</b> (4): 175–202.</li>
+</ul>`,
+ },
+ { h: 2, title: "External links", html: `<ul class="fr"><li>Typewriter Database – a collaborative record of serial numbers and production dates</li><li>Media related to Typewriters at Wikimedia Commons</li><li>"How typewriters work" – an illustrated introduction from a museum collection</li></ul>{navbox}` },
+];
diff --git a/capcodec/bench/corpus/pages/data/board_data.js b/capcodec/bench/corpus/pages/data/board_data.js
new file mode 100644
index 000000000..f7f54bd35
--- /dev/null
+++ b/capcodec/bench/corpus/pages/data/board_data.js
@@ -0,0 +1,98 @@
+window.BOARD = {
+ people: {
+ ML: ["Maya Lindqvist", "#7c3aed"],
+ MF: ["Marcus Feld", "#0891b2"],
+ PR: ["Priya Raman", "#db2777"],
+ DO: ["Daniel Okafor", "#16a34a"],
+ LH: ["Lena Hoffmann", "#ea580c"],
+ SW: ["Sam Whitaker", "#2563eb"],
+ AK: ["Aiko Kimura", "#9333ea"],
+ JT: ["Jonas Tran", "#0d9488"],
+ },
+ labels: {
+ encoder: ["#7c3aed", "#f3e8ff"],
+ bug: ["#dc2626", "#fee2e2"],
+ perf: ["#c2410c", "#ffedd5"],
+ ui: ["#2563eb", "#dbeafe"],
+ upload: ["#0f766e", "#ccfbf1"],
+ camera: ["#a16207", "#fef9c3"],
+ windows: ["#0369a1", "#e0f2fe"],
+ macos: ["#4b5563", "#f3f4f6"],
+ infra: ["#be185d", "#fce7f3"],
+ },
+ columns: [
+ {
+ id: "backlog",
+ name: "Backlog",
+ icon: "backlog",
+ cards: [
+ ["CAP-1288", "Investigate green frames after resuming from sleep on Intel Macs", ["bug", "macos"], "MF", 2, "Oct 24", "0/2", 4],
+ ["CAP-1291", "Add per-segment checksums to the upload manifest", ["upload"], "SW", 1, "", "", 1],
+ ["CAP-1297", "Expose encoder statistics in the debug overlay", ["encoder", "ui"], "PR", 1, "Nov 2", "", 0],
+ ["CAP-1302", "Support 10-bit HEVC export for HDR displays", ["encoder"], "", 0, "", "0/4", 2],
+ ["CAP-1305", "Warn when free disk space drops below 2 GB during recording", ["ui"], "LH", 2, "", "", 3],
+ ["CAP-1311", "Audit log for workspace recording retention changes", ["infra"], "JT", 1, "", "", 0],
+ ["CAP-1314", "Keyboard shortcut to pause and resume recording", ["ui"], "AK", 1, "", "", 6],
+ ["CAP-1318", "Measure memory use of the frame pool across 2 hour sessions", ["perf"], "MF", 3, "Oct 30", "1/3", 2],
+ ["CAP-1320", "Camera picker shows virtual devices twice on Windows", ["bug", "camera", "windows"], "DO", 2, "", "", 1],
+ ["CAP-1323", "Document the screen content tuning presets", ["encoder"], "PR", 1, "", "", 0],
+ ],
+ },
+ {
+ id: "todo",
+ name: "Todo",
+ icon: "todo",
+ cards: [
+ ["CAP-1254", "Fall back to software encoding when the GPU driver resets", ["encoder", "windows"], "DO", 3, "Oct 14", "0/3", 5],
+ ["CAP-1259", "Show upload progress in the menu bar icon", ["ui", "upload"], "LH", 2, "Oct 16", "", 2],
+ ["CAP-1262", "Reduce camera probe time on cold start", ["camera", "perf"], "AK", 2, "Oct 15", "", 1],
+ ["CAP-1266", "Retry policy for 429 responses from the storage API", ["upload", "infra"], "SW", 2, "Oct 18", "1/2", 3],
+ ["CAP-1270", "Crop recordings to a window without re-encoding", ["encoder"], "PR", 1, "", "", 0],
+ ["CAP-1273", "Move crash reporter uploads off the main thread", ["perf"], "JT", 2, "Oct 20", "", 2],
+ ],
+ },
+ {
+ id: "progress",
+ name: "In Progress",
+ icon: "progress",
+ cards: [
+ ["CAP-1231", "Frame pool rewrite for long recordings", ["perf", "encoder"], "MF", 4, "Oct 21", "3/5", 12],
+ ["CAP-1236", "Screen content encoder: adaptive quantisation for text", ["encoder"], "PR", 3, "Nov 4", "2/6", 8],
+ ["CAP-1240", "Resumable uploads on mobile hotspots", ["upload"], "SW", 3, "Oct 12", "4/4", 6],
+ ["CAP-1244", "Camera bubble flickers when dragged across displays", ["bug", "camera"], "LH", 3, "Oct 13", "", 4],
+ ["CAP-1247", "Windows on ARM build pipeline", ["windows", "infra"], "DO", 2, "Nov 18", "1/4", 3],
+ ],
+ },
+ {
+ id: "review",
+ name: "In Review",
+ icon: "review",
+ cards: [
+ ["CAP-1219", "Hardware encoder selection on hybrid GPU laptops", ["encoder", "windows"], "DO", 3, "Oct 9", "", 7],
+ ["CAP-1223", "Make the trim handles snap to keyframes", ["ui"], "AK", 2, "Oct 10", "", 3],
+ ["CAP-1227", "Cache thumbnails for the recordings list", ["perf", "ui"], "JT", 1, "", "", 2],
+ ],
+ },
+ {
+ id: "done",
+ name: "Done",
+ icon: "done",
+ cards: [
+ ["CAP-1198", "Start recording in under a second on Apple Silicon", ["perf", "macos"], "MF", 4, "", "5/5", 15],
+ ["CAP-1203", "Upload segments while recording", ["upload"], "SW", 3, "", "3/3", 9],
+ ["CAP-1207", "Scene-change keyframes for faster seeking", ["encoder"], "PR", 2, "", "", 4],
+ ["CAP-1210", "Fix audio drift on recordings longer than an hour", ["bug"], "LH", 3, "", "", 11],
+ ["CAP-1214", "New onboarding checklist", ["ui"], "AK", 1, "", "4/4", 2],
+ ],
+ },
+ {
+ id: "canceled",
+ name: "Canceled",
+ icon: "canceled",
+ cards: [
+ ["CAP-1189", "Record directly to GIF", ["encoder"], "", 0, "", "", 5],
+ ["CAP-1193", "Custom watermark fonts", ["ui"], "LH", 0, "", "", 1],
+ ],
+ },
+ ],
+};
diff --git a/capcodec/bench/corpus/pages/data/difflib_py.js b/capcodec/bench/corpus/pages/data/difflib_py.js
new file mode 100644
index 000000000..4bfbd4c18
--- /dev/null
+++ b/capcodec/bench/corpus/pages/data/difflib_py.js
@@ -0,0 +1 @@
+window.SOURCE_DIFFLIB_PY = "\"\"\"\nModule difflib -- helpers for computing deltas between objects.\n\nFunction get_close_matches(word, possibilities, n=3, cutoff=0.6):\n Use SequenceMatcher to return list of the best \"good enough\" matches.\n\nFunction context_diff(a, b):\n For two lists of strings, return a delta in context diff format.\n\nFunction ndiff(a, b):\n Return a delta: the difference between `a` and `b` (lists of strings).\n\nFunction restore(delta, which):\n Return one of the two sequences that generated an ndiff delta.\n\nFunction unified_diff(a, b):\n For two lists of strings, return a delta in unified diff format.\n\nClass SequenceMatcher:\n A flexible class for comparing pairs of sequences of any type.\n\nClass Differ:\n For producing human-readable deltas from sequences of lines of text.\n\nClass HtmlDiff:\n For producing HTML side by side comparison with change highlights.\n\"\"\"\n\n__all__ = ['get_close_matches', 'ndiff', 'restore', 'SequenceMatcher',\n 'Differ','IS_CHARACTER_JUNK', 'IS_LINE_JUNK', 'context_diff',\n 'unified_diff', 'diff_bytes', 'HtmlDiff', 'Match']\n\nfrom heapq import nlargest as _nlargest\nfrom collections import namedtuple as _namedtuple\nfrom types import GenericAlias\n\nMatch = _namedtuple('Match', 'a b size')\n\ndef _calculate_ratio(matches, length):\n if length:\n return 2.0 * matches / length\n return 1.0\n\nclass SequenceMatcher:\n\n \"\"\"\n SequenceMatcher is a flexible class for comparing pairs of sequences of\n any type, so long as the sequence elements are hashable. The basic\n algorithm predates, and is a little fancier than, an algorithm\n published in the late 1980's by Ratcliff and Obershelp under the\n hyperbolic name \"gestalt pattern matching\". The basic idea is to find\n the longest contiguous matching subsequence that contains no \"junk\"\n elements (R-O doesn't address junk). The same idea is then applied\n recursively to the pieces of the sequences to the left and to the right\n of the matching subsequence. This does not yield minimal edit\n sequences, but does tend to yield matches that \"look right\" to people.\n\n SequenceMatcher tries to compute a \"human-friendly diff\" between two\n sequences. Unlike e.g. UNIX(tm) diff, the fundamental notion is the\n longest *contiguous* & junk-free matching subsequence. That's what\n catches peoples' eyes. The Windows(tm) windiff has another interesting\n notion, pairing up elements that appear uniquely in each sequence.\n That, and the method here, appear to yield more intuitive difference\n reports than does diff. This method appears to be the least vulnerable\n to syncing up on blocks of \"junk lines\", though (like blank lines in\n ordinary text files, or maybe \"<P>\" lines in HTML files). That may be\n because this is the only method of the 3 that has a *concept* of\n \"junk\" <wink>.\n\n Example, comparing two strings, and considering blanks to be \"junk\":\n\n >>> s = SequenceMatcher(lambda x: x == \" \",\n ... \"private Thread currentThread;\",\n ... \"private volatile Thread currentThread;\")\n >>>\n\n .ratio() returns a float in [0, 1], measuring the \"similarity\" of the\n sequences. As a rule of thumb, a .ratio() value over 0.6 means the\n sequences are close matches:\n\n >>> print(round(s.ratio(), 3))\n 0.866\n >>>\n\n If you're only interested in where the sequences match,\n .get_matching_blocks() is handy:\n\n >>> for block in s.get_matching_blocks():\n ... print(\"a[%d] and b[%d] match for %d elements\" % block)\n a[0] and b[0] match for 8 elements\n a[8] and b[17] match for 21 elements\n a[29] and b[38] match for 0 elements\n\n Note that the last tuple returned by .get_matching_blocks() is always a\n dummy, (len(a), len(b), 0), and this is the only case in which the last\n tuple element (number of elements matched) is 0.\n\n If you want to know how to change the first sequence into the second,\n use .get_opcodes():\n\n >>> for opcode in s.get_opcodes():\n ... print(\"%6s a[%d:%d] b[%d:%d]\" % opcode)\n equal a[0:8] b[0:8]\n insert a[8:8] b[8:17]\n equal a[8:29] b[17:38]\n\n See the Differ class for a fancy human-friendly file differencer, which\n uses SequenceMatcher both to compare sequences of lines, and to compare\n sequences of characters within similar (near-matching) lines.\n\n See also function get_close_matches() in this module, which shows how\n simple code building on SequenceMatcher can be used to do useful work.\n\n Timing: Basic R-O is cubic time worst case and quadratic time expected\n case. SequenceMatcher is quadratic time for the worst case and has\n expected-case behavior dependent in a complicated way on how many\n elements the sequences have in common; best case time is linear.\n \"\"\"\n\n def __init__(self, isjunk=None, a='', b='', autojunk=True):\n \"\"\"Construct a SequenceMatcher.\n\n Optional arg isjunk is None (the default), or a one-argument\n function that takes a sequence element and returns true iff the\n element is junk. None is equivalent to passing \"lambda x: 0\", i.e.\n no elements are considered to be junk. For example, pass\n lambda x: x in \" \\\\t\"\n if you're comparing lines as sequences of characters, and don't\n want to synch up on blanks or hard tabs.\n\n Optional arg a is the first of two sequences to be compared. By\n default, an empty string. The elements of a must be hashable. See\n also .set_seqs() and .set_seq1().\n\n Optional arg b is the second of two sequences to be compared. By\n default, an empty string. The elements of b must be hashable. See\n also .set_seqs() and .set_seq2().\n\n Optional arg autojunk should be set to False to disable the\n \"automatic junk heuristic\" that treats popular elements as junk\n (see module documentation for more information).\n \"\"\"\n\n # Members:\n # a\n # first sequence\n # b\n # second sequence; differences are computed as \"what do\n # we need to do to 'a' to change it into 'b'?\"\n # b2j\n # for x in b, b2j[x] is a list of the indices (into b)\n # at which x appears; junk and popular elements do not appear\n # fullbcount\n # for x in b, fullbcount[x] == the number of times x\n # appears in b; only materialized if really needed (used\n # only for computing quick_ratio())\n # matching_blocks\n # a list of (i, j, k) triples, where a[i:i+k] == b[j:j+k];\n # ascending & non-overlapping in i and in j; terminated by\n # a dummy (len(a), len(b), 0) sentinel\n # opcodes\n # a list of (tag, i1, i2, j1, j2) tuples, where tag is\n # one of\n # 'replace' a[i1:i2] should be replaced by b[j1:j2]\n # 'delete' a[i1:i2] should be deleted\n # 'insert' b[j1:j2] should be inserted\n # 'equal' a[i1:i2] == b[j1:j2]\n # isjunk\n # a user-supplied function taking a sequence element and\n # returning true iff the element is \"junk\" -- this has\n # subtle but helpful effects on the algorithm, which I'll\n # get around to writing up someday <0.9 wink>.\n # DON'T USE! Only __chain_b uses this. Use \"in self.bjunk\".\n # bjunk\n # the items in b for which isjunk is True.\n # bpopular\n # nonjunk items in b treated as junk by the heuristic (if used).\n\n self.isjunk = isjunk\n self.a = self.b = None\n self.autojunk = autojunk\n self.set_seqs(a, b)\n\n def set_seqs(self, a, b):\n \"\"\"Set the two sequences to be compared.\n\n >>> s = SequenceMatcher()\n >>> s.set_seqs(\"abcd\", \"bcde\")\n >>> s.ratio()\n 0.75\n \"\"\"\n\n self.set_seq1(a)\n self.set_seq2(b)\n\n def set_seq1(self, a):\n \"\"\"Set the first sequence to be compared.\n\n The second sequence to be compared is not changed.\n\n >>> s = SequenceMatcher(None, \"abcd\", \"bcde\")\n >>> s.ratio()\n 0.75\n >>> s.set_seq1(\"bcde\")\n >>> s.ratio()\n 1.0\n >>>\n\n SequenceMatcher computes and caches detailed information about the\n second sequence, so if you want to compare one sequence S against\n many sequences, use .set_seq2(S) once and call .set_seq1(x)\n repeatedly for each of the other sequences.\n\n See also set_seqs() and set_seq2().\n \"\"\"\n\n if a is self.a:\n return\n self.a = a\n self.matching_blocks = self.opcodes = None\n\n def set_seq2(self, b):\n \"\"\"Set the second sequence to be compared.\n\n The first sequence to be compared is not changed.\n\n >>> s = SequenceMatcher(None, \"abcd\", \"bcde\")\n >>> s.ratio()\n 0.75\n >>> s.set_seq2(\"abcd\")\n >>> s.ratio()\n 1.0\n >>>\n\n SequenceMatcher computes and caches detailed information about the\n second sequence, so if you want to compare one sequence S against\n many sequences, use .set_seq2(S) once and call .set_seq1(x)\n repeatedly for each of the other sequences.\n\n See also set_seqs() and set_seq1().\n \"\"\"\n\n if b is self.b:\n return\n self.b = b\n self.matching_blocks = self.opcodes = None\n self.fullbcount = None\n self.__chain_b()\n\n # For each element x in b, set b2j[x] to a list of the indices in\n # b where x appears; the indices are in increasing order; note that\n # the number of times x appears in b is len(b2j[x]) ...\n # when self.isjunk is defined, junk elements don't show up in this\n # map at all, which stops the central find_longest_match method\n # from starting any matching block at a junk element ...\n # b2j also does not contain entries for \"popular\" elements, meaning\n # elements that account for more than 1 + 1% of the total elements, and\n # when the sequence is reasonably large (>= 200 elements); this can\n # be viewed as an adaptive notion of semi-junk, and yields an enormous\n # speedup when, e.g., comparing program files with hundreds of\n # instances of \"return NULL;\" ...\n # note that this is only called when b changes; so for cross-product\n # kinds of matches, it's best to call set_seq2 once, then set_seq1\n # repeatedly\n\n def __chain_b(self):\n # Because isjunk is a user-defined (not C) function, and we test\n # for junk a LOT, it's important to minimize the number of calls.\n # Before the tricks described here, __chain_b was by far the most\n # time-consuming routine in the whole module! If anyone sees\n # Jim Roskind, thank him again for profile.py -- I never would\n # have guessed that.\n # The first trick is to build b2j ignoring the possibility\n # of junk. I.e., we don't call isjunk at all yet. Throwing\n # out the junk later is much cheaper than building b2j \"right\"\n # from the start.\n b = self.b\n self.b2j = b2j = {}\n\n for i, elt in enumerate(b):\n indices = b2j.setdefault(elt, [])\n indices.append(i)\n\n # Purge junk elements\n self.bjunk = junk = set()\n isjunk = self.isjunk\n if isjunk:\n for elt in b2j.keys():\n if isjunk(elt):\n junk.add(elt)\n for elt in junk: # separate loop avoids separate list of keys\n del b2j[elt]\n\n # Purge popular elements that are not junk\n self.bpopular = popular = set()\n n = len(b)\n if self.autojunk and n >= 200:\n ntest = n // 100 + 1\n for elt, idxs in b2j.items():\n if len(idxs) > ntest:\n popular.add(elt)\n for elt in popular: # ditto; as fast for 1% deletion\n del b2j[elt]\n\n def find_longest_match(self, alo=0, ahi=None, blo=0, bhi=None):\n \"\"\"Find longest matching block in a[alo:ahi] and b[blo:bhi].\n\n By default it will find the longest match in the entirety of a and b.\n\n If isjunk is not defined:\n\n Return (i,j,k) such that a[i:i+k] is equal to b[j:j+k], where\n alo <= i <= i+k <= ahi\n blo <= j <= j+k <= bhi\n and for all (i',j',k') meeting those conditions,\n k >= k'\n i <= i'\n and if i == i', j <= j'\n\n In other words, of all maximal matching blocks, return one that\n starts earliest in a, and of all those maximal matching blocks that\n start earliest in a, return the one that starts earliest in b.\n\n >>> s = SequenceMatcher(None, \" abcd\", \"abcd abcd\")\n >>> s.find_longest_match(0, 5, 0, 9)\n Match(a=0, b=4, size=5)\n\n If isjunk is defined, first the longest matching block is\n determined as above, but with the additional restriction that no\n junk element appears in the block. Then that block is extended as\n far as possible by matching (only) junk elements on both sides. So\n the resulting block never matches on junk except as identical junk\n happens to be adjacent to an \"interesting\" match.\n\n Here's the same example as before, but considering blanks to be\n junk. That prevents \" abcd\" from matching the \" abcd\" at the tail\n end of the second sequence directly. Instead only the \"abcd\" can\n match, and matches the leftmost \"abcd\" in the second sequence:\n\n >>> s = SequenceMatcher(lambda x: x==\" \", \" abcd\", \"abcd abcd\")\n >>> s.find_longest_match(0, 5, 0, 9)\n Match(a=1, b=0, size=4)\n\n If no blocks match, return (alo, blo, 0).\n\n >>> s = SequenceMatcher(None, \"ab\", \"c\")\n >>> s.find_longest_match(0, 2, 0, 1)\n Match(a=0, b=0, size=0)\n \"\"\"\n\n # CAUTION: stripping common prefix or suffix would be incorrect.\n # E.g.,\n # ab\n # acab\n # Longest matching block is \"ab\", but if common prefix is\n # stripped, it's \"a\" (tied with \"b\"). UNIX(tm) diff does so\n # strip, so ends up claiming that ab is changed to acab by\n # inserting \"ca\" in the middle. That's minimal but unintuitive:\n # \"it's obvious\" that someone inserted \"ac\" at the front.\n # Windiff ends up at the same place as diff, but by pairing up\n # the unique 'b's and then matching the first two 'a's.\n\n a, b, b2j, isbjunk = self.a, self.b, self.b2j, self.bjunk.__contains__\n if ahi is None:\n ahi = len(a)\n if bhi is None:\n bhi = len(b)\n besti, bestj, bestsize = alo, blo, 0\n # find longest junk-free match\n # during an iteration of the loop, j2len[j] = length of longest\n # junk-free match ending with a[i-1] and b[j]\n j2len = {}\n nothing = []\n for i in range(alo, ahi):\n # look at all instances of a[i] in b; note that because\n # b2j has no junk keys, the loop is skipped if a[i] is junk\n j2lenget = j2len.get\n newj2len = {}\n for j in b2j.get(a[i], nothing):\n # a[i] matches b[j]\n if j < blo:\n continue\n if j >= bhi:\n break\n k = newj2len[j] = j2lenget(j-1, 0) + 1\n if k > bestsize:\n besti, bestj, bestsize = i-k+1, j-k+1, k\n j2len = newj2len\n\n # Extend the best by non-junk elements on each end. In particular,\n # \"popular\" non-junk elements aren't in b2j, which greatly speeds\n # the inner loop above, but also means \"the best\" match so far\n # doesn't contain any junk *or* popular non-junk elements.\n while besti > alo and bestj > blo and \\\n not isbjunk(b[bestj-1]) and \\\n a[besti-1] == b[bestj-1]:\n besti, bestj, bestsize = besti-1, bestj-1, bestsize+1\n while besti+bestsize < ahi and bestj+bestsize < bhi and \\\n not isbjunk(b[bestj+bestsize]) and \\\n a[besti+bestsize] == b[bestj+bestsize]:\n bestsize += 1\n\n # Now that we have a wholly interesting match (albeit possibly\n # empty!), we may as well suck up the matching junk on each\n # side of it too. Can't think of a good reason not to, and it\n # saves post-processing the (possibly considerable) expense of\n # figuring out what to do with it. In the case of an empty\n # interesting match, this is clearly the right thing to do,\n # because no other kind of match is possible in the regions.\n while besti > alo and bestj > blo and \\\n isbjunk(b[bestj-1]) and \\\n a[besti-1] == b[bestj-1]:\n besti, bestj, bestsize = besti-1, bestj-1, bestsize+1\n while besti+bestsize < ahi and bestj+bestsize < bhi and \\\n isbjunk(b[bestj+bestsize]) and \\\n a[besti+bestsize] == b[bestj+bestsize]:\n bestsize = bestsize + 1\n\n return Match(besti, bestj, bestsize)\n\n def get_matching_blocks(self):\n \"\"\"Return list of triples describing matching subsequences.\n\n Each triple is of the form (i, j, n), and means that\n a[i:i+n] == b[j:j+n]. The triples are monotonically increasing in\n i and in j. New in Python 2.5, it's also guaranteed that if\n (i, j, n) and (i', j', n') are adjacent triples in the list, and\n the second is not the last triple in the list, then i+n != i' or\n j+n != j'. IOW, adjacent triples never describe adjacent equal\n blocks.\n\n The last triple is a dummy, (len(a), len(b), 0), and is the only\n triple with n==0.\n\n >>> s = SequenceMatcher(None, \"abxcd\", \"abcd\")\n >>> list(s.get_matching_blocks())\n [Match(a=0, b=0, size=2), Match(a=3, b=2, size=2), Match(a=5, b=4, size=0)]\n \"\"\"\n\n if self.matching_blocks is not None:\n return self.matching_blocks\n la, lb = len(self.a), len(self.b)\n\n # This is most naturally expressed as a recursive algorithm, but\n # at least one user bumped into extreme use cases that exceeded\n # the recursion limit on their box. So, now we maintain a list\n # ('queue`) of blocks we still need to look at, and append partial\n # results to `matching_blocks` in a loop; the matches are sorted\n # at the end.\n queue = [(0, la, 0, lb)]\n matching_blocks = []\n while queue:\n alo, ahi, blo, bhi = queue.pop()\n i, j, k = x = self.find_longest_match(alo, ahi, blo, bhi)\n # a[alo:i] vs b[blo:j] unknown\n # a[i:i+k] same as b[j:j+k]\n # a[i+k:ahi] vs b[j+k:bhi] unknown\n if k: # if k is 0, there was no matching block\n matching_blocks.append(x)\n if alo < i and blo < j:\n queue.append((alo, i, blo, j))\n if i+k < ahi and j+k < bhi:\n queue.append((i+k, ahi, j+k, bhi))\n matching_blocks.sort()\n\n # It's possible that we have adjacent equal blocks in the\n # matching_blocks list now. Starting with 2.5, this code was added\n # to collapse them.\n i1 = j1 = k1 = 0\n non_adjacent = []\n for i2, j2, k2 in matching_blocks:\n # Is this block adjacent to i1, j1, k1?\n if i1 + k1 == i2 and j1 + k1 == j2:\n # Yes, so collapse them -- this just increases the length of\n # the first block by the length of the second, and the first\n # block so lengthened remains the block to compare against.\n k1 += k2\n else:\n # Not adjacent. Remember the first block (k1==0 means it's\n # the dummy we started with), and make the second block the\n # new block to compare against.\n if k1:\n non_adjacent.append((i1, j1, k1))\n i1, j1, k1 = i2, j2, k2\n if k1:\n non_adjacent.append((i1, j1, k1))\n\n non_adjacent.append( (la, lb, 0) )\n self.matching_blocks = list(map(Match._make, non_adjacent))\n return self.matching_blocks\n\n def get_opcodes(self):\n \"\"\"Return list of 5-tuples describing how to turn a into b.\n\n Each tuple is of the form (tag, i1, i2, j1, j2). The first tuple\n has i1 == j1 == 0, and remaining tuples have i1 == the i2 from the\n tuple preceding it, and likewise for j1 == the previous j2.\n\n The tags are strings, with these meanings:\n\n 'replace': a[i1:i2] should be replaced by b[j1:j2]\n 'delete': a[i1:i2] should be deleted.\n Note that j1==j2 in this case.\n 'insert': b[j1:j2] should be inserted at a[i1:i1].\n Note that i1==i2 in this case.\n 'equal': a[i1:i2] == b[j1:j2]\n\n >>> a = \"qabxcd\"\n >>> b = \"abycdf\"\n >>> s = SequenceMatcher(None, a, b)\n >>> for tag, i1, i2, j1, j2 in s.get_opcodes():\n ... print((\"%7s a[%d:%d] (%s) b[%d:%d] (%s)\" %\n ... (tag, i1, i2, a[i1:i2], j1, j2, b[j1:j2])))\n delete a[0:1] (q) b[0:0] ()\n equal a[1:3] (ab) b[0:2] (ab)\n replace a[3:4] (x) b[2:3] (y)\n equal a[4:6] (cd) b[3:5] (cd)\n insert a[6:6] () b[5:6] (f)\n \"\"\"\n\n if self.opcodes is not None:\n return self.opcodes\n i = j = 0\n self.opcodes = answer = []\n for ai, bj, size in self.get_matching_blocks():\n # invariant: we've pumped out correct diffs to change\n # a[:i] into b[:j], and the next matching block is\n # a[ai:ai+size] == b[bj:bj+size]. So we need to pump\n # out a diff to change a[i:ai] into b[j:bj], pump out\n # the matching block, and move (i,j) beyond the match\n tag = ''\n if i < ai and j < bj:\n tag = 'replace'\n elif i < ai:\n tag = 'delete'\n elif j < bj:\n tag = 'insert'\n if tag:\n answer.append( (tag, i, ai, j, bj) )\n i, j = ai+size, bj+size\n # the list of matching blocks is terminated by a\n # sentinel with size 0\n if size:\n answer.append( ('equal', ai, i, bj, j) )\n return answer\n\n def get_grouped_opcodes(self, n=3):\n \"\"\" Isolate change clusters by eliminating ranges with no changes.\n\n Return a generator of groups with up to n lines of context.\n Each group is in the same format as returned by get_opcodes().\n\n >>> from pprint import pprint\n >>> a = list(map(str, range(1,40)))\n >>> b = a[:]\n >>> b[8:8] = ['i'] # Make an insertion\n >>> b[20] += 'x' # Make a replacement\n >>> b[23:28] = [] # Make a deletion\n >>> b[30] += 'y' # Make another replacement\n >>> pprint(list(SequenceMatcher(None,a,b).get_grouped_opcodes()))\n [[('equal', 5, 8, 5, 8), ('insert', 8, 8, 8, 9), ('equal', 8, 11, 9, 12)],\n [('equal', 16, 19, 17, 20),\n ('replace', 19, 20, 20, 21),\n ('equal', 20, 22, 21, 23),\n ('delete', 22, 27, 23, 23),\n ('equal', 27, 30, 23, 26)],\n [('equal', 31, 34, 27, 30),\n ('replace', 34, 35, 30, 31),\n ('equal', 35, 38, 31, 34)]]\n \"\"\"\n\n codes = self.get_opcodes()\n if not codes:\n codes = [(\"equal\", 0, 1, 0, 1)]\n # Fixup leading and trailing groups if they show no changes.\n if codes[0][0] == 'equal':\n tag, i1, i2, j1, j2 = codes[0]\n codes[0] = tag, max(i1, i2-n), i2, max(j1, j2-n), j2\n if codes[-1][0] == 'equal':\n tag, i1, i2, j1, j2 = codes[-1]\n codes[-1] = tag, i1, min(i2, i1+n), j1, min(j2, j1+n)\n\n nn = n + n\n group = []\n for tag, i1, i2, j1, j2 in codes:\n # End the current group and start a new one whenever\n # there is a large range with no changes.\n if tag == 'equal' and i2-i1 > nn:\n group.append((tag, i1, min(i2, i1+n), j1, min(j2, j1+n)))\n yield group\n group = []\n i1, j1 = max(i1, i2-n), max(j1, j2-n)\n group.append((tag, i1, i2, j1 ,j2))\n if group and not (len(group)==1 and group[0][0] == 'equal'):\n yield group\n\n def ratio(self):\n \"\"\"Return a measure of the sequences' similarity (float in [0,1]).\n\n Where T is the total number of elements in both sequences, and\n M is the number of matches, this is 2.0*M / T.\n Note that this is 1 if the sequences are identical, and 0 if\n they have nothing in common.\n\n .ratio() is expensive to compute if you haven't already computed\n .get_matching_blocks() or .get_opcodes(), in which case you may\n want to try .quick_ratio() or .real_quick_ratio() first to get an\n upper bound.\n\n >>> s = SequenceMatcher(None, \"abcd\", \"bcde\")\n >>> s.ratio()\n 0.75\n >>> s.quick_ratio()\n 0.75\n >>> s.real_quick_ratio()\n 1.0\n \"\"\"\n\n matches = sum(triple[-1] for triple in self.get_matching_blocks())\n return _calculate_ratio(matches, len(self.a) + len(self.b))\n\n def quick_ratio(self):\n \"\"\"Return an upper bound on ratio() relatively quickly.\n\n This isn't defined beyond that it is an upper bound on .ratio(), and\n is faster to compute.\n \"\"\"\n\n # viewing a and b as multisets, set matches to the cardinality\n # of their intersection; this counts the number of matches\n # without regard to order, so is clearly an upper bound\n if self.fullbcount is None:\n self.fullbcount = fullbcount = {}\n for elt in self.b:\n fullbcount[elt] = fullbcount.get(elt, 0) + 1\n fullbcount = self.fullbcount\n # avail[x] is the number of times x appears in 'b' less the\n # number of times we've seen it in 'a' so far ... kinda\n avail = {}\n availhas, matches = avail.__contains__, 0\n for elt in self.a:\n if availhas(elt):\n numb = avail[elt]\n else:\n numb = fullbcount.get(elt, 0)\n avail[elt] = numb - 1\n if numb > 0:\n matches = matches + 1\n return _calculate_ratio(matches, len(self.a) + len(self.b))\n\n def real_quick_ratio(self):\n \"\"\"Return an upper bound on ratio() very quickly.\n\n This isn't defined beyond that it is an upper bound on .ratio(), and\n is faster to compute than either .ratio() or .quick_ratio().\n \"\"\"\n\n la, lb = len(self.a), len(self.b)\n # can't have more matches than the number of elements in the\n # shorter sequence\n return _calculate_ratio(min(la, lb), la + lb)\n\n __class_getitem__ = classmethod(GenericAlias)\n\n\ndef get_close_matches(word, possibilities, n=3, cutoff=0.6):\n \"\"\"Use SequenceMatcher to return list of the best \"good enough\" matches.\n\n word is a sequence for which close matches are desired (typically a\n string).\n\n possibilities is a list of sequences against which to match word\n (typically a list of strings).\n\n Optional arg n (default 3) is the maximum number of close matches to\n return. n must be > 0.\n\n Optional arg cutoff (default 0.6) is a float in [0, 1]. Possibilities\n that don't score at least that similar to word are ignored.\n\n The best (no more than n) matches among the possibilities are returned\n in a list, sorted by similarity score, most similar first.\n\n >>> get_close_matches(\"appel\", [\"ape\", \"apple\", \"peach\", \"puppy\"])\n ['apple', 'ape']\n >>> import keyword as _keyword\n >>> get_close_matches(\"wheel\", _keyword.kwlist)\n ['while']\n >>> get_close_matches(\"Apple\", _keyword.kwlist)\n []\n >>> get_close_matches(\"accept\", _keyword.kwlist)\n ['except']\n \"\"\"\n\n if not n > 0:\n raise ValueError(\"n must be > 0: %r\" % (n,))\n if not 0.0 <= cutoff <= 1.0:\n raise ValueError(\"cutoff must be in [0.0, 1.0]: %r\" % (cutoff,))\n result = []\n s = SequenceMatcher()\n s.set_seq2(word)\n for x in possibilities:\n s.set_seq1(x)\n if s.real_quick_ratio() >= cutoff and \\\n s.quick_ratio() >= cutoff and \\\n s.ratio() >= cutoff:\n result.append((s.ratio(), x))\n\n # Move the best scorers to head of list\n result = _nlargest(n, result)\n # Strip scores for the best n matches\n return [x for score, x in result]\n\n\ndef _keep_original_ws(s, tag_s):\n \"\"\"Replace whitespace with the original whitespace characters in `s`\"\"\"\n return ''.join(\n c if tag_c == \" \" and c.isspace() else tag_c\n for c, tag_c in zip(s, tag_s)\n )\n\n\n\nclass Differ:\n r\"\"\"\n Differ is a class for comparing sequences of lines of text, and\n producing human-readable differences or deltas. Differ uses\n SequenceMatcher both to compare sequences of lines, and to compare\n sequences of characters within similar (near-matching) lines.\n\n Each line of a Differ delta begins with a two-letter code:\n\n '- ' line unique to sequence 1\n '+ ' line unique to sequence 2\n ' ' line common to both sequences\n '? ' line not present in either input sequence\n\n Lines beginning with '? ' attempt to guide the eye to intraline\n differences, and were not present in either input sequence. These lines\n can be confusing if the sequences contain tab characters.\n\n Note that Differ makes no claim to produce a *minimal* diff. To the\n contrary, minimal diffs are often counter-intuitive, because they synch\n up anywhere possible, sometimes accidental matches 100 pages apart.\n Restricting synch points to contiguous matches preserves some notion of\n locality, at the occasional cost of producing a longer diff.\n\n Example: Comparing two texts.\n\n First we set up the texts, sequences of individual single-line strings\n ending with newlines (such sequences can also be obtained from the\n `readlines()` method of file-like objects):\n\n >>> text1 = ''' 1. Beautiful is better than ugly.\n ... 2. Explicit is better than implicit.\n ... 3. Simple is better than complex.\n ... 4. Complex is better than complicated.\n ... '''.splitlines(keepends=True)\n >>> len(text1)\n 4\n >>> text1[0][-1]\n '\\n'\n >>> text2 = ''' 1. Beautiful is better than ugly.\n ... 3. Simple is better than complex.\n ... 4. Complicated is better than complex.\n ... 5. Flat is better than nested.\n ... '''.splitlines(keepends=True)\n\n Next we instantiate a Differ object:\n\n >>> d = Differ()\n\n Note that when instantiating a Differ object we may pass functions to\n filter out line and character 'junk'. See Differ.__init__ for details.\n\n Finally, we compare the two:\n\n >>> result = list(d.compare(text1, text2))\n\n 'result' is a list of strings, so let's pretty-print it:\n\n >>> from pprint import pprint as _pprint\n >>> _pprint(result)\n [' 1. Beautiful is better than ugly.\\n',\n '- 2. Explicit is better than implicit.\\n',\n '- 3. Simple is better than complex.\\n',\n '+ 3. Simple is better than complex.\\n',\n '? ++\\n',\n '- 4. Complex is better than complicated.\\n',\n '? ^ ---- ^\\n',\n '+ 4. Complicated is better than complex.\\n',\n '? ++++ ^ ^\\n',\n '+ 5. Flat is better than nested.\\n']\n\n As a single multi-line string it looks like this:\n\n >>> print(''.join(result), end=\"\")\n 1. Beautiful is better than ugly.\n - 2. Explicit is better than implicit.\n - 3. Simple is better than complex.\n + 3. Simple is better than complex.\n ? ++\n - 4. Complex is better than complicated.\n ? ^ ---- ^\n + 4. Complicated is better than complex.\n ? ++++ ^ ^\n + 5. Flat is better than nested.\n \"\"\"\n\n def __init__(self, linejunk=None, charjunk=None):\n \"\"\"\n Construct a text differencer, with optional filters.\n\n The two optional keyword parameters are for filter functions:\n\n - `linejunk`: A function that should accept a single string argument,\n and return true iff the string is junk. The module-level function\n `IS_LINE_JUNK` may be used to filter out lines without visible\n characters, except for at most one splat ('#'). It is recommended\n to leave linejunk None; the underlying SequenceMatcher class has\n an adaptive notion of \"noise\" lines that's better than any static\n definition the author has ever been able to craft.\n\n - `charjunk`: A function that should accept a string of length 1. The\n module-level function `IS_CHARACTER_JUNK` may be used to filter out\n whitespace characters (a blank or tab; **note**: bad idea to include\n newline in this!). Use of IS_CHARACTER_JUNK is recommended.\n \"\"\"\n\n self.linejunk = linejunk\n self.charjunk = charjunk\n\n def compare(self, a, b):\n r\"\"\"\n Compare two sequences of lines; generate the resulting delta.\n\n Each sequence must contain individual single-line strings ending with\n newlines. Such sequences can be obtained from the `readlines()` method\n of file-like objects. The delta generated also consists of newline-\n terminated strings, ready to be printed as-is via the writelines()\n method of a file-like object.\n\n Example:\n\n >>> print(''.join(Differ().compare('one\\ntwo\\nthree\\n'.splitlines(True),\n ... 'ore\\ntree\\nemu\\n'.splitlines(True))),\n ... end=\"\")\n - one\n ? ^\n + ore\n ? ^\n - two\n - three\n ? -\n + tree\n + emu\n \"\"\"\n\n cruncher = SequenceMatcher(self.linejunk, a, b)\n for tag, alo, ahi, blo, bhi in cruncher.get_opcodes():\n if tag == 'replace':\n g = self._fancy_replace(a, alo, ahi, b, blo, bhi)\n elif tag == 'delete':\n g = self._dump('-', a, alo, ahi)\n elif tag == 'insert':\n g = self._dump('+', b, blo, bhi)\n elif tag == 'equal':\n g = self._dump(' ', a, alo, ahi)\n else:\n raise ValueError('unknown tag %r' % (tag,))\n\n yield from g\n\n def _dump(self, tag, x, lo, hi):\n \"\"\"Generate comparison results for a same-tagged range.\"\"\"\n for i in range(lo, hi):\n yield '%s %s' % (tag, x[i])\n\n def _plain_replace(self, a, alo, ahi, b, blo, bhi):\n assert alo < ahi and blo < bhi\n # dump the shorter block first -- reduces the burden on short-term\n # memory if the blocks are of very different sizes\n if bhi - blo < ahi - alo:\n first = self._dump('+', b, blo, bhi)\n second = self._dump('-', a, alo, ahi)\n else:\n first = self._dump('-', a, alo, ahi)\n second = self._dump('+', b, blo, bhi)\n\n for g in first, second:\n yield from g\n\n def _fancy_replace(self, a, alo, ahi, b, blo, bhi):\n r\"\"\"\n When replacing one block of lines with another, search the blocks\n for *similar* lines; the best-matching pair (if any) is used as a\n synch point, and intraline difference marking is done on the\n similar pair. Lots of work, but often worth it.\n\n Example:\n\n >>> d = Differ()\n >>> results = d._fancy_replace(['abcDefghiJkl\\n'], 0, 1,\n ... ['abcdefGhijkl\\n'], 0, 1)\n >>> print(''.join(results), end=\"\")\n - abcDefghiJkl\n ? ^ ^ ^\n + abcdefGhijkl\n ? ^ ^ ^\n \"\"\"\n\n # don't synch up unless the lines have a similarity score of at\n # least cutoff; best_ratio tracks the best score seen so far\n best_ratio, cutoff = 0.74, 0.75\n cruncher = SequenceMatcher(self.charjunk)\n eqi, eqj = None, None # 1st indices of equal lines (if any)\n\n # search for the pair that matches best without being identical\n # (identical lines must be junk lines, & we don't want to synch up\n # on junk -- unless we have to)\n for j in range(blo, bhi):\n bj = b[j]\n cruncher.set_seq2(bj)\n for i in range(alo, ahi):\n ai = a[i]\n if ai == bj:\n if eqi is None:\n eqi, eqj = i, j\n continue\n cruncher.set_seq1(ai)\n # computing similarity is expensive, so use the quick\n # upper bounds first -- have seen this speed up messy\n # compares by a factor of 3.\n # note that ratio() is only expensive to compute the first\n # time it's called on a sequence pair; the expensive part\n # of the computation is cached by cruncher\n if cruncher.real_quick_ratio() > best_ratio and \\\n cruncher.quick_ratio() > best_ratio and \\\n cruncher.ratio() > best_ratio:\n best_ratio, best_i, best_j = cruncher.ratio(), i, j\n if best_ratio < cutoff:\n # no non-identical \"pretty close\" pair\n if eqi is None:\n # no identical pair either -- treat it as a straight replace\n yield from self._plain_replace(a, alo, ahi, b, blo, bhi)\n return\n # no close pair, but an identical pair -- synch up on that\n best_i, best_j, best_ratio = eqi, eqj, 1.0\n else:\n # there's a close pair, so forget the identical pair (if any)\n eqi = None\n\n # a[best_i] very similar to b[best_j]; eqi is None iff they're not\n # identical\n\n # pump out diffs from before the synch point\n yield from self._fancy_helper(a, alo, best_i, b, blo, best_j)\n\n # do intraline marking on the synch pair\n aelt, belt = a[best_i], b[best_j]\n if eqi is None:\n # pump out a '-', '?', '+', '?' quad for the synched lines\n atags = btags = \"\"\n cruncher.set_seqs(aelt, belt)\n for tag, ai1, ai2, bj1, bj2 in cruncher.get_opcodes():\n la, lb = ai2 - ai1, bj2 - bj1\n if tag == 'replace':\n atags += '^' * la\n btags += '^' * lb\n elif tag == 'delete':\n atags += '-' * la\n elif tag == 'insert':\n btags += '+' * lb\n elif tag == 'equal':\n atags += ' ' * la\n btags += ' ' * lb\n else:\n raise ValueError('unknown tag %r' % (tag,))\n yield from self._qformat(aelt, belt, atags, btags)\n else:\n # the synch pair is identical\n yield ' ' + aelt\n\n # pump out diffs from after the synch point\n yield from self._fancy_helper(a, best_i+1, ahi, b, best_j+1, bhi)\n\n def _fancy_helper(self, a, alo, ahi, b, blo, bhi):\n g = []\n if alo < ahi:\n if blo < bhi:\n g = self._fancy_replace(a, alo, ahi, b, blo, bhi)\n else:\n g = self._dump('-', a, alo, ahi)\n elif blo < bhi:\n g = self._dump('+', b, blo, bhi)\n\n yield from g\n\n def _qformat(self, aline, bline, atags, btags):\n r\"\"\"\n Format \"?\" output and deal with tabs.\n\n Example:\n\n >>> d = Differ()\n >>> results = d._qformat('\\tabcDefghiJkl\\n', '\\tabcdefGhijkl\\n',\n ... ' ^ ^ ^ ', ' ^ ^ ^ ')\n >>> for line in results: print(repr(line))\n ...\n '- \\tabcDefghiJkl\\n'\n '? \\t ^ ^ ^\\n'\n '+ \\tabcdefGhijkl\\n'\n '? \\t ^ ^ ^\\n'\n \"\"\"\n atags = _keep_original_ws(aline, atags).rstrip()\n btags = _keep_original_ws(bline, btags).rstrip()\n\n yield \"- \" + aline\n if atags:\n yield f\"? {atags}\\n\"\n\n yield \"+ \" + bline\n if btags:\n yield f\"? {btags}\\n\"\n\n# With respect to junk, an earlier version of ndiff simply refused to\n# *start* a match with a junk element. The result was cases like this:\n# before: private Thread currentThread;\n# after: private volatile Thread currentThread;\n# If you consider whitespace to be junk, the longest contiguous match\n# not starting with junk is \"e Thread currentThread\". So ndiff reported\n# that \"e volatil\" was inserted between the 't' and the 'e' in \"private\".\n# While an accurate view, to people that's absurd. The current version\n# looks for matching blocks that are entirely junk-free, then extends the\n# longest one of those as far as possible but only with matching junk.\n# So now \"currentThread\" is matched, then extended to suck up the\n# preceding blank; then \"private\" is matched, and extended to suck up the\n# following blank; then \"Thread\" is matched; and finally ndiff reports\n# that \"volatile \" was inserted before \"Thread\". The only quibble\n# remaining is that perhaps it was really the case that \" volatile\"\n# was inserted after \"private\". I can live with that <wink>.\n\nimport re\n\ndef IS_LINE_JUNK(line, pat=re.compile(r\"\\s*(?:#\\s*)?$\").match):\n r\"\"\"\n Return True for ignorable line: iff `line` is blank or contains a single '#'.\n\n Examples:\n\n >>> IS_LINE_JUNK('\\n')\n True\n >>> IS_LINE_JUNK(' # \\n')\n True\n >>> IS_LINE_JUNK('hello\\n')\n False\n \"\"\"\n\n return pat(line) is not None\n\ndef IS_CHARACTER_JUNK(ch, ws=\" \\t\"):\n r\"\"\"\n Return True for ignorable character: iff `ch` is a space or tab.\n\n Examples:\n\n >>> IS_CHARACTER_JUNK(' ')\n True\n >>> IS_CHARACTER_JUNK('\\t')\n True\n >>> IS_CHARACTER_JUNK('\\n')\n False\n >>> IS_CHARACTER_JUNK('x')\n False\n \"\"\"\n\n return ch in ws\n\n\n########################################################################\n### Unified Diff\n########################################################################\n\ndef _format_range_unified(start, stop):\n 'Convert range to the \"ed\" format'\n # Per the diff spec at http://www.unix.org/single_unix_specification/\n beginning = start + 1 # lines start numbering with one\n length = stop - start\n if length == 1:\n return '{}'.format(beginning)\n if not length:\n beginning -= 1 # empty ranges begin at line just before the range\n return '{},{}'.format(beginning, length)\n\ndef unified_diff(a, b, fromfile='', tofile='', fromfiledate='',\n tofiledate='', n=3, lineterm='\\n'):\n r\"\"\"\n Compare two sequences of lines; generate the delta as a unified diff.\n\n Unified diffs are a compact way of showing line changes and a few\n lines of context. The number of context lines is set by 'n' which\n defaults to three.\n\n By default, the diff control lines (those with ---, +++, or @@) are\n created with a trailing newline. This is helpful so that inputs\n created from file.readlines() result in diffs that are suitable for\n file.writelines() since both the inputs and outputs have trailing\n newlines.\n\n For inputs that do not have trailing newlines, set the lineterm\n argument to \"\" so that the output will be uniformly newline free.\n\n The unidiff format normally has a header for filenames and modification\n times. Any or all of these may be specified using strings for\n 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.\n The modification times are normally expressed in the ISO 8601 format.\n\n Example:\n\n >>> for line in unified_diff('one two three four'.split(),\n ... 'zero one tree four'.split(), 'Original', 'Current',\n ... '2005-01-26 23:30:50', '2010-04-02 10:20:52',\n ... lineterm=''):\n ... print(line) # doctest: +NORMALIZE_WHITESPACE\n --- Original 2005-01-26 23:30:50\n +++ Current 2010-04-02 10:20:52\n @@ -1,4 +1,4 @@\n +zero\n one\n -two\n -three\n +tree\n four\n \"\"\"\n\n _check_types(a, b, fromfile, tofile, fromfiledate, tofiledate, lineterm)\n started = False\n for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):\n if not started:\n started = True\n fromdate = '\\t{}'.format(fromfiledate) if fromfiledate else ''\n todate = '\\t{}'.format(tofiledate) if tofiledate else ''\n yield '--- {}{}{}'.format(fromfile, fromdate, lineterm)\n yield '+++ {}{}{}'.format(tofile, todate, lineterm)\n\n first, last = group[0], group[-1]\n file1_range = _format_range_unified(first[1], last[2])\n file2_range = _format_range_unified(first[3], last[4])\n yield '@@ -{} +{} @@{}'.format(file1_range, file2_range, lineterm)\n\n for tag, i1, i2, j1, j2 in group:\n if tag == 'equal':\n for line in a[i1:i2]:\n yield ' ' + line\n continue\n if tag in {'replace', 'delete'}:\n for line in a[i1:i2]:\n yield '-' + line\n if tag in {'replace', 'insert'}:\n for line in b[j1:j2]:\n yield '+' + line\n\n\n########################################################################\n### Context Diff\n########################################################################\n\ndef _format_range_context(start, stop):\n 'Convert range to the \"ed\" format'\n # Per the diff spec at http://www.unix.org/single_unix_specification/\n beginning = start + 1 # lines start numbering with one\n length = stop - start\n if not length:\n beginning -= 1 # empty ranges begin at line just before the range\n if length <= 1:\n return '{}'.format(beginning)\n return '{},{}'.format(beginning, beginning + length - 1)\n\n# See http://www.unix.org/single_unix_specification/\ndef context_diff(a, b, fromfile='', tofile='',\n fromfiledate='', tofiledate='', n=3, lineterm='\\n'):\n r\"\"\"\n Compare two sequences of lines; generate the delta as a context diff.\n\n Context diffs are a compact way of showing line changes and a few\n lines of context. The number of context lines is set by 'n' which\n defaults to three.\n\n By default, the diff control lines (those with *** or ---) are\n created with a trailing newline. This is helpful so that inputs\n created from file.readlines() result in diffs that are suitable for\n file.writelines() since both the inputs and outputs have trailing\n newlines.\n\n For inputs that do not have trailing newlines, set the lineterm\n argument to \"\" so that the output will be uniformly newline free.\n\n The context diff format normally has a header for filenames and\n modification times. Any or all of these may be specified using\n strings for 'fromfile', 'tofile', 'fromfiledate', and 'tofiledate'.\n The modification times are normally expressed in the ISO 8601 format.\n If not specified, the strings default to blanks.\n\n Example:\n\n >>> print(''.join(context_diff('one\\ntwo\\nthree\\nfour\\n'.splitlines(True),\n ... 'zero\\none\\ntree\\nfour\\n'.splitlines(True), 'Original', 'Current')),\n ... end=\"\")\n *** Original\n --- Current\n ***************\n *** 1,4 ****\n one\n ! two\n ! three\n four\n --- 1,4 ----\n + zero\n one\n ! tree\n four\n \"\"\"\n\n _check_types(a, b, fromfile, tofile, fromfiledate, tofiledate, lineterm)\n prefix = dict(insert='+ ', delete='- ', replace='! ', equal=' ')\n started = False\n for group in SequenceMatcher(None,a,b).get_grouped_opcodes(n):\n if not started:\n started = True\n fromdate = '\\t{}'.format(fromfiledate) if fromfiledate else ''\n todate = '\\t{}'.format(tofiledate) if tofiledate else ''\n yield '*** {}{}{}'.format(fromfile, fromdate, lineterm)\n yield '--- {}{}{}'.format(tofile, todate, lineterm)\n\n first, last = group[0], group[-1]\n yield '***************' + lineterm\n\n file1_range = _format_range_context(first[1], last[2])\n yield '*** {} ****{}'.format(file1_range, lineterm)\n\n if any(tag in {'replace', 'delete'} for tag, _, _, _, _ in group):\n for tag, i1, i2, _, _ in group:\n if tag != 'insert':\n for line in a[i1:i2]:\n yield prefix[tag] + line\n\n file2_range = _format_range_context(first[3], last[4])\n yield '--- {} ----{}'.format(file2_range, lineterm)\n\n if any(tag in {'replace', 'insert'} for tag, _, _, _, _ in group):\n for tag, _, _, j1, j2 in group:\n if tag != 'delete':\n for line in b[j1:j2]:\n yield prefix[tag] + line\n\ndef _check_types(a, b, *args):\n # Checking types is weird, but the alternative is garbled output when\n # someone passes mixed bytes and str to {unified,context}_diff(). E.g.\n # without this check, passing filenames as bytes results in output like\n # --- b'oldfile.txt'\n # +++ b'newfile.txt'\n # because of how str.format() incorporates bytes objects.\n if a and not isinstance(a[0], str):\n raise TypeError('lines to compare must be str, not %s (%r)' %\n (type(a[0]).__name__, a[0]))\n if b and not isinstance(b[0], str):\n raise TypeError('lines to compare must be str, not %s (%r)' %\n (type(b[0]).__name__, b[0]))\n for arg in args:\n if not isinstance(arg, str):\n raise TypeError('all arguments must be str, not: %r' % (arg,))\n\ndef diff_bytes(dfunc, a, b, fromfile=b'', tofile=b'',\n fromfiledate=b'', tofiledate=b'', n=3, lineterm=b'\\n'):\n r\"\"\"\n Compare `a` and `b`, two sequences of lines represented as bytes rather\n than str. This is a wrapper for `dfunc`, which is typically either\n unified_diff() or context_diff(). Inputs are losslessly converted to\n strings so that `dfunc` only has to worry about strings, and encoded\n back to bytes on return. This is necessary to compare files with\n unknown or inconsistent encoding. All other inputs (except `n`) must be\n bytes rather than str.\n \"\"\"\n def decode(s):\n try:\n return s.decode('ascii', 'surrogateescape')\n except AttributeError as err:\n msg = ('all arguments must be bytes, not %s (%r)' %\n (type(s).__name__, s))\n raise TypeError(msg) from err\n a = list(map(decode, a))\n b = list(map(decode, b))\n fromfile = decode(fromfile)\n tofile = decode(tofile)\n fromfiledate = decode(fromfiledate)\n tofiledate = decode(tofiledate)\n lineterm = decode(lineterm)\n\n lines = dfunc(a, b, fromfile, tofile, fromfiledate, tofiledate, n, lineterm)\n for line in lines:\n yield line.encode('ascii', 'surrogateescape')\n\ndef ndiff(a, b, linejunk=None, charjunk=IS_CHARACTER_JUNK):\n r\"\"\"\n Compare `a` and `b` (lists of strings); return a `Differ`-style delta.\n\n Optional keyword parameters `linejunk` and `charjunk` are for filter\n functions, or can be None:\n\n - linejunk: A function that should accept a single string argument and\n return true iff the string is junk. The default is None, and is\n recommended; the underlying SequenceMatcher class has an adaptive\n notion of \"noise\" lines.\n\n - charjunk: A function that accepts a character (string of length\n 1), and returns true iff the character is junk. The default is\n the module-level function IS_CHARACTER_JUNK, which filters out\n whitespace characters (a blank or tab; note: it's a bad idea to\n include newline in this!).\n\n Tools/scripts/ndiff.py is a command-line front-end to this function.\n\n Example:\n\n >>> diff = ndiff('one\\ntwo\\nthree\\n'.splitlines(keepends=True),\n ... 'ore\\ntree\\nemu\\n'.splitlines(keepends=True))\n >>> print(''.join(diff), end=\"\")\n - one\n ? ^\n + ore\n ? ^\n - two\n - three\n ? -\n + tree\n + emu\n \"\"\"\n return Differ(linejunk, charjunk).compare(a, b)\n\ndef _mdiff(fromlines, tolines, context=None, linejunk=None,\n charjunk=IS_CHARACTER_JUNK):\n r\"\"\"Returns generator yielding marked up from/to side by side differences.\n\n Arguments:\n fromlines -- list of text lines to compared to tolines\n tolines -- list of text lines to be compared to fromlines\n context -- number of context lines to display on each side of difference,\n if None, all from/to text lines will be generated.\n linejunk -- passed on to ndiff (see ndiff documentation)\n charjunk -- passed on to ndiff (see ndiff documentation)\n\n This function returns an iterator which returns a tuple:\n (from line tuple, to line tuple, boolean flag)\n\n from/to line tuple -- (line num, line text)\n line num -- integer or None (to indicate a context separation)\n line text -- original line text with following markers inserted:\n '\\0+' -- marks start of added text\n '\\0-' -- marks start of deleted text\n '\\0^' -- marks start of changed text\n '\\1' -- marks end of added/deleted/changed text\n\n boolean flag -- None indicates context separation, True indicates\n either \"from\" or \"to\" line contains a change, otherwise False.\n\n This function/iterator was originally developed to generate side by side\n file difference for making HTML pages (see HtmlDiff class for example\n usage).\n\n Note, this function utilizes the ndiff function to generate the side by\n side difference markup. Optional ndiff arguments may be passed to this\n function and they in turn will be passed to ndiff.\n \"\"\"\n import re\n\n # regular expression for finding intraline change indices\n change_re = re.compile(r'(\\++|\\-+|\\^+)')\n\n # create the difference iterator to generate the differences\n diff_lines_iterator = ndiff(fromlines,tolines,linejunk,charjunk)\n\n def _make_line(lines, format_key, side, num_lines=[0,0]):\n \"\"\"Returns line of text with user's change markup and line formatting.\n\n lines -- list of lines from the ndiff generator to produce a line of\n text from. When producing the line of text to return, the\n lines used are removed from this list.\n format_key -- '+' return first line in list with \"add\" markup around\n the entire line.\n '-' return first line in list with \"delete\" markup around\n the entire line.\n '?' return first line in list with add/delete/change\n intraline markup (indices obtained from second line)\n None return first line in list with no markup\n side -- indice into the num_lines list (0=from,1=to)\n num_lines -- from/to current line number. This is NOT intended to be a\n passed parameter. It is present as a keyword argument to\n maintain memory of the current line numbers between calls\n of this function.\n\n Note, this function is purposefully not defined at the module scope so\n that data it needs from its parent function (within whose context it\n is defined) does not need to be of module scope.\n \"\"\"\n num_lines[side] += 1\n # Handle case where no user markup is to be added, just return line of\n # text with user's line format to allow for usage of the line number.\n if format_key is None:\n return (num_lines[side],lines.pop(0)[2:])\n # Handle case of intraline changes\n if format_key == '?':\n text, markers = lines.pop(0), lines.pop(0)\n # find intraline changes (store change type and indices in tuples)\n sub_info = []\n def record_sub_info(match_object,sub_info=sub_info):\n sub_info.append([match_object.group(1)[0],match_object.span()])\n return match_object.group(1)\n change_re.sub(record_sub_info,markers)\n # process each tuple inserting our special marks that won't be\n # noticed by an xml/html escaper.\n for key,(begin,end) in reversed(sub_info):\n text = text[0:begin]+'\\0'+key+text[begin:end]+'\\1'+text[end:]\n text = text[2:]\n # Handle case of add/delete entire line\n else:\n text = lines.pop(0)[2:]\n # if line of text is just a newline, insert a space so there is\n # something for the user to highlight and see.\n if not text:\n text = ' '\n # insert marks that won't be noticed by an xml/html escaper.\n text = '\\0' + format_key + text + '\\1'\n # Return line of text, first allow user's line formatter to do its\n # thing (such as adding the line number) then replace the special\n # marks with what the user's change markup.\n return (num_lines[side],text)\n\n def _line_iterator():\n \"\"\"Yields from/to lines of text with a change indication.\n\n This function is an iterator. It itself pulls lines from a\n differencing iterator, processes them and yields them. When it can\n it yields both a \"from\" and a \"to\" line, otherwise it will yield one\n or the other. In addition to yielding the lines of from/to text, a\n boolean flag is yielded to indicate if the text line(s) have\n differences in them.\n\n Note, this function is purposefully not defined at the module scope so\n that data it needs from its parent function (within whose context it\n is defined) does not need to be of module scope.\n \"\"\"\n lines = []\n num_blanks_pending, num_blanks_to_yield = 0, 0\n while True:\n # Load up next 4 lines so we can look ahead, create strings which\n # are a concatenation of the first character of each of the 4 lines\n # so we can do some very readable comparisons.\n while len(lines) < 4:\n lines.append(next(diff_lines_iterator, 'X'))\n s = ''.join([line[0] for line in lines])\n if s.startswith('X'):\n # When no more lines, pump out any remaining blank lines so the\n # corresponding add/delete lines get a matching blank line so\n # all line pairs get yielded at the next level.\n num_blanks_to_yield = num_blanks_pending\n elif s.startswith('-?+?'):\n # simple intraline change\n yield _make_line(lines,'?',0), _make_line(lines,'?',1), True\n continue\n elif s.startswith('--++'):\n # in delete block, add block coming: we do NOT want to get\n # caught up on blank lines yet, just process the delete line\n num_blanks_pending -= 1\n yield _make_line(lines,'-',0), None, True\n continue\n elif s.startswith(('--?+', '--+', '- ')):\n # in delete block and see an intraline change or unchanged line\n # coming: yield the delete line and then blanks\n from_line,to_line = _make_line(lines,'-',0), None\n num_blanks_to_yield,num_blanks_pending = num_blanks_pending-1,0\n elif s.startswith('-+?'):\n # intraline change\n yield _make_line(lines,None,0), _make_line(lines,'?',1), True\n continue\n elif s.startswith('-?+'):\n # intraline change\n yield _make_line(lines,'?',0), _make_line(lines,None,1), True\n continue\n elif s.startswith('-'):\n # delete FROM line\n num_blanks_pending -= 1\n yield _make_line(lines,'-',0), None, True\n continue\n elif s.startswith('+--'):\n # in add block, delete block coming: we do NOT want to get\n # caught up on blank lines yet, just process the add line\n num_blanks_pending += 1\n yield None, _make_line(lines,'+',1), True\n continue\n elif s.startswith(('+ ', '+-')):\n # will be leaving an add block: yield blanks then add line\n from_line, to_line = None, _make_line(lines,'+',1)\n num_blanks_to_yield,num_blanks_pending = num_blanks_pending+1,0\n elif s.startswith('+'):\n # inside an add block, yield the add line\n num_blanks_pending += 1\n yield None, _make_line(lines,'+',1), True\n continue\n elif s.startswith(' '):\n # unchanged text, yield it to both sides\n yield _make_line(lines[:],None,0),_make_line(lines,None,1),False\n continue\n # Catch up on the blank lines so when we yield the next from/to\n # pair, they are lined up.\n while(num_blanks_to_yield < 0):\n num_blanks_to_yield += 1\n yield None,('','\\n'),True\n while(num_blanks_to_yield > 0):\n num_blanks_to_yield -= 1\n yield ('','\\n'),None,True\n if s.startswith('X'):\n return\n else:\n yield from_line,to_line,True\n\n def _line_pair_iterator():\n \"\"\"Yields from/to lines of text with a change indication.\n\n This function is an iterator. It itself pulls lines from the line\n iterator. Its difference from that iterator is that this function\n always yields a pair of from/to text lines (with the change\n indication). If necessary it will collect single from/to lines\n until it has a matching pair from/to pair to yield.\n\n Note, this function is purposefully not defined at the module scope so\n that data it needs from its parent function (within whose context it\n is defined) does not need to be of module scope.\n \"\"\"\n line_iterator = _line_iterator()\n fromlines,tolines=[],[]\n while True:\n # Collecting lines of text until we have a from/to pair\n while (len(fromlines)==0 or len(tolines)==0):\n try:\n from_line, to_line, found_diff = next(line_iterator)\n except StopIteration:\n return\n if from_line is not None:\n fromlines.append((from_line,found_diff))\n if to_line is not None:\n tolines.append((to_line,found_diff))\n # Once we have a pair, remove them from the collection and yield it\n from_line, fromDiff = fromlines.pop(0)\n to_line, to_diff = tolines.pop(0)\n yield (from_line,to_line,fromDiff or to_diff)\n\n # Handle case where user does not want context differencing, just yield\n # them up without doing anything else with them.\n line_pair_iterator = _line_pair_iterator()\n if context is None:\n yield from line_pair_iterator\n # Handle case where user wants context differencing. We must do some\n # storage of lines until we know for sure that they are to be yielded.\n else:\n context += 1\n lines_to_write = 0\n while True:\n # Store lines up until we find a difference, note use of a\n # circular queue because we only need to keep around what\n # we need for context.\n index, contextLines = 0, [None]*(context)\n found_diff = False\n while(found_diff is False):\n try:\n from_line, to_line, found_diff = next(line_pair_iterator)\n except StopIteration:\n return\n i = index % context\n contextLines[i] = (from_line, to_line, found_diff)\n index += 1\n # Yield lines that we have collected so far, but first yield\n # the user's separator.\n if index > context:\n yield None, None, None\n lines_to_write = context\n else:\n lines_to_write = index\n index = 0\n while(lines_to_write):\n i = index % context\n index += 1\n yield contextLines[i]\n lines_to_write -= 1\n # Now yield the context lines after the change\n lines_to_write = context-1\n try:\n while(lines_to_write):\n from_line, to_line, found_diff = next(line_pair_iterator)\n # If another change within the context, extend the context\n if found_diff:\n lines_to_write = context-1\n else:\n lines_to_write -= 1\n yield from_line, to_line, found_diff\n except StopIteration:\n # Catch exception from next() and return normally\n return\n\n\n_file_template = \"\"\"\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html>\n\n<head>\n <meta http-equiv=\"Content-Type\"\n content=\"text/html; charset=%(charset)s\" />\n <title></title>\n <style type=\"text/css\">%(styles)s\n </style>\n</head>\n\n<body>\n %(table)s%(legend)s\n</body>\n\n</html>\"\"\"\n\n_styles = \"\"\"\n table.diff {font-family:Courier; border:medium;}\n .diff_header {background-color:#e0e0e0}\n td.diff_header {text-align:right}\n .diff_next {background-color:#c0c0c0}\n .diff_add {background-color:#aaffaa}\n .diff_chg {background-color:#ffff77}\n .diff_sub {background-color:#ffaaaa}\"\"\"\n\n_table_template = \"\"\"\n <table class=\"diff\" id=\"difflib_chg_%(prefix)s_top\"\n cellspacing=\"0\" cellpadding=\"0\" rules=\"groups\" >\n <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>\n <colgroup></colgroup> <colgroup></colgroup> <colgroup></colgroup>\n %(header_row)s\n <tbody>\n%(data_rows)s </tbody>\n </table>\"\"\"\n\n_legend = \"\"\"\n <table class=\"diff\" summary=\"Legends\">\n <tr> <th colspan=\"2\"> Legends </th> </tr>\n <tr> <td> <table border=\"\" summary=\"Colors\">\n <tr><th> Colors </th> </tr>\n <tr><td class=\"diff_add\">&nbsp;Added&nbsp;</td></tr>\n <tr><td class=\"diff_chg\">Changed</td> </tr>\n <tr><td class=\"diff_sub\">Deleted</td> </tr>\n </table></td>\n <td> <table border=\"\" summary=\"Links\">\n <tr><th colspan=\"2\"> Links </th> </tr>\n <tr><td>(f)irst change</td> </tr>\n <tr><td>(n)ext change</td> </tr>\n <tr><td>(t)op</td> </tr>\n </table></td> </tr>\n </table>\"\"\"\n\nclass HtmlDiff(object):\n \"\"\"For producing HTML side by side comparison with change highlights.\n\n This class can be used to create an HTML table (or a complete HTML file\n containing the table) showing a side by side, line by line comparison\n of text with inter-line and intra-line change highlights. The table can\n be generated in either full or contextual difference mode.\n\n The following methods are provided for HTML generation:\n\n make_table -- generates HTML for a single side by side table\n make_file -- generates complete HTML file with a single side by side table\n\n See tools/scripts/diff.py for an example usage of this class.\n \"\"\"\n\n _file_template = _file_template\n _styles = _styles\n _table_template = _table_template\n _legend = _legend\n _default_prefix = 0\n\n def __init__(self,tabsize=8,wrapcolumn=None,linejunk=None,\n charjunk=IS_CHARACTER_JUNK):\n \"\"\"HtmlDiff instance initializer\n\n Arguments:\n tabsize -- tab stop spacing, defaults to 8.\n wrapcolumn -- column number where lines are broken and wrapped,\n defaults to None where lines are not wrapped.\n linejunk,charjunk -- keyword arguments passed into ndiff() (used by\n HtmlDiff() to generate the side by side HTML differences). See\n ndiff() documentation for argument default values and descriptions.\n \"\"\"\n self._tabsize = tabsize\n self._wrapcolumn = wrapcolumn\n self._linejunk = linejunk\n self._charjunk = charjunk\n\n def make_file(self, fromlines, tolines, fromdesc='', todesc='',\n context=False, numlines=5, *, charset='utf-8'):\n \"\"\"Returns HTML file of side by side comparison with change highlights\n\n Arguments:\n fromlines -- list of \"from\" lines\n tolines -- list of \"to\" lines\n fromdesc -- \"from\" file column header string\n todesc -- \"to\" file column header string\n context -- set to True for contextual differences (defaults to False\n which shows full differences).\n numlines -- number of context lines. When context is set True,\n controls number of lines displayed before and after the change.\n When context is False, controls the number of lines to place\n the \"next\" link anchors before the next change (so click of\n \"next\" link jumps to just before the change).\n charset -- charset of the HTML document\n \"\"\"\n\n return (self._file_template % dict(\n styles=self._styles,\n legend=self._legend,\n table=self.make_table(fromlines, tolines, fromdesc, todesc,\n context=context, numlines=numlines),\n charset=charset\n )).encode(charset, 'xmlcharrefreplace').decode(charset)\n\n def _tab_newline_replace(self,fromlines,tolines):\n \"\"\"Returns from/to line lists with tabs expanded and newlines removed.\n\n Instead of tab characters being replaced by the number of spaces\n needed to fill in to the next tab stop, this function will fill\n the space with tab characters. This is done so that the difference\n algorithms can identify changes in a file when tabs are replaced by\n spaces and vice versa. At the end of the HTML generation, the tab\n characters will be replaced with a nonbreakable space.\n \"\"\"\n def expand_tabs(line):\n # hide real spaces\n line = line.replace(' ','\\0')\n # expand tabs into spaces\n line = line.expandtabs(self._tabsize)\n # replace spaces from expanded tabs back into tab characters\n # (we'll replace them with markup after we do differencing)\n line = line.replace(' ','\\t')\n return line.replace('\\0',' ').rstrip('\\n')\n fromlines = [expand_tabs(line) for line in fromlines]\n tolines = [expand_tabs(line) for line in tolines]\n return fromlines,tolines\n\n def _split_line(self,data_list,line_num,text):\n \"\"\"Builds list of text lines by splitting text lines at wrap point\n\n This function will determine if the input text line needs to be\n wrapped (split) into separate lines. If so, the first wrap point\n will be determined and the first line appended to the output\n text line list. This function is used recursively to handle\n the second part of the split line to further split it.\n \"\"\"\n # if blank line or context separator, just add it to the output list\n if not line_num:\n data_list.append((line_num,text))\n return\n\n # if line text doesn't need wrapping, just add it to the output list\n size = len(text)\n max = self._wrapcolumn\n if (size <= max) or ((size -(text.count('\\0')*3)) <= max):\n data_list.append((line_num,text))\n return\n\n # scan text looking for the wrap point, keeping track if the wrap\n # point is inside markers\n i = 0\n n = 0\n mark = ''\n while n < max and i < size:\n if text[i] == '\\0':\n i += 1\n mark = text[i]\n i += 1\n elif text[i] == '\\1':\n i += 1\n mark = ''\n else:\n i += 1\n n += 1\n\n # wrap point is inside text, break it up into separate lines\n line1 = text[:i]\n line2 = text[i:]\n\n # if wrap point is inside markers, place end marker at end of first\n # line and start marker at beginning of second line because each\n # line will have its own table tag markup around it.\n if mark:\n line1 = line1 + '\\1'\n line2 = '\\0' + mark + line2\n\n # tack on first line onto the output list\n data_list.append((line_num,line1))\n\n # use this routine again to wrap the remaining text\n self._split_line(data_list,'>',line2)\n\n def _line_wrapper(self,diffs):\n \"\"\"Returns iterator that splits (wraps) mdiff text lines\"\"\"\n\n # pull from/to data and flags from mdiff iterator\n for fromdata,todata,flag in diffs:\n # check for context separators and pass them through\n if flag is None:\n yield fromdata,todata,flag\n continue\n (fromline,fromtext),(toline,totext) = fromdata,todata\n # for each from/to line split it at the wrap column to form\n # list of text lines.\n fromlist,tolist = [],[]\n self._split_line(fromlist,fromline,fromtext)\n self._split_line(tolist,toline,totext)\n # yield from/to line in pairs inserting blank lines as\n # necessary when one side has more wrapped lines\n while fromlist or tolist:\n if fromlist:\n fromdata = fromlist.pop(0)\n else:\n fromdata = ('',' ')\n if tolist:\n todata = tolist.pop(0)\n else:\n todata = ('',' ')\n yield fromdata,todata,flag\n\n def _collect_lines(self,diffs):\n \"\"\"Collects mdiff output into separate lists\n\n Before storing the mdiff from/to data into a list, it is converted\n into a single line of text with HTML markup.\n \"\"\"\n\n fromlist,tolist,flaglist = [],[],[]\n # pull from/to data and flags from mdiff style iterator\n for fromdata,todata,flag in diffs:\n try:\n # store HTML markup of the lines into the lists\n fromlist.append(self._format_line(0,flag,*fromdata))\n tolist.append(self._format_line(1,flag,*todata))\n except TypeError:\n # exceptions occur for lines where context separators go\n fromlist.append(None)\n tolist.append(None)\n flaglist.append(flag)\n return fromlist,tolist,flaglist\n\n def _format_line(self,side,flag,linenum,text):\n \"\"\"Returns HTML markup of \"from\" / \"to\" text lines\n\n side -- 0 or 1 indicating \"from\" or \"to\" text\n flag -- indicates if difference on line\n linenum -- line number (used for line number column)\n text -- line text to be marked up\n \"\"\"\n try:\n linenum = '%d' % linenum\n id = ' id=\"%s%s\"' % (self._prefix[side],linenum)\n except TypeError:\n # handle blank lines where linenum is '>' or ''\n id = ''\n # replace those things that would get confused with HTML symbols\n text=text.replace(\"&\",\"&amp;\").replace(\">\",\"&gt;\").replace(\"<\",\"&lt;\")\n\n # make space non-breakable so they don't get compressed or line wrapped\n text = text.replace(' ','&nbsp;').rstrip()\n\n return '<td class=\"diff_header\"%s>%s</td><td nowrap=\"nowrap\">%s</td>' \\\n % (id,linenum,text)\n\n def _make_prefix(self):\n \"\"\"Create unique anchor prefixes\"\"\"\n\n # Generate a unique anchor prefix so multiple tables\n # can exist on the same HTML page without conflicts.\n fromprefix = \"from%d_\" % HtmlDiff._default_prefix\n toprefix = \"to%d_\" % HtmlDiff._default_prefix\n HtmlDiff._default_prefix += 1\n # store prefixes so line format method has access\n self._prefix = [fromprefix,toprefix]\n\n def _convert_flags(self,fromlist,tolist,flaglist,context,numlines):\n \"\"\"Makes list of \"next\" links\"\"\"\n\n # all anchor names will be generated using the unique \"to\" prefix\n toprefix = self._prefix[1]\n\n # process change flags, generating middle column of next anchors/links\n next_id = ['']*len(flaglist)\n next_href = ['']*len(flaglist)\n num_chg, in_change = 0, False\n last = 0\n for i,flag in enumerate(flaglist):\n if flag:\n if not in_change:\n in_change = True\n last = i\n # at the beginning of a change, drop an anchor a few lines\n # (the context lines) before the change for the previous\n # link\n i = max([0,i-numlines])\n next_id[i] = ' id=\"difflib_chg_%s_%d\"' % (toprefix,num_chg)\n # at the beginning of a change, drop a link to the next\n # change\n num_chg += 1\n next_href[last] = '<a href=\"#difflib_chg_%s_%d\">n</a>' % (\n toprefix,num_chg)\n else:\n in_change = False\n # check for cases where there is no content to avoid exceptions\n if not flaglist:\n flaglist = [False]\n next_id = ['']\n next_href = ['']\n last = 0\n if context:\n fromlist = ['<td></td><td>&nbsp;No Differences Found&nbsp;</td>']\n tolist = fromlist\n else:\n fromlist = tolist = ['<td></td><td>&nbsp;Empty File&nbsp;</td>']\n # if not a change on first line, drop a link\n if not flaglist[0]:\n next_href[0] = '<a href=\"#difflib_chg_%s_0\">f</a>' % toprefix\n # redo the last link to link to the top\n next_href[last] = '<a href=\"#difflib_chg_%s_top\">t</a>' % (toprefix)\n\n return fromlist,tolist,flaglist,next_href,next_id\n\n def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False,\n numlines=5):\n \"\"\"Returns HTML table of side by side comparison with change highlights\n\n Arguments:\n fromlines -- list of \"from\" lines\n tolines -- list of \"to\" lines\n fromdesc -- \"from\" file column header string\n todesc -- \"to\" file column header string\n context -- set to True for contextual differences (defaults to False\n which shows full differences).\n numlines -- number of context lines. When context is set True,\n controls number of lines displayed before and after the change.\n When context is False, controls the number of lines to place\n the \"next\" link anchors before the next change (so click of\n \"next\" link jumps to just before the change).\n \"\"\"\n\n # make unique anchor prefixes so that multiple tables may exist\n # on the same page without conflict.\n self._make_prefix()\n\n # change tabs to spaces before it gets more difficult after we insert\n # markup\n fromlines,tolines = self._tab_newline_replace(fromlines,tolines)\n\n # create diffs iterator which generates side by side from/to data\n if context:\n context_lines = numlines\n else:\n context_lines = None\n diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk,\n charjunk=self._charjunk)\n\n # set up iterator to wrap lines that exceed desired width\n if self._wrapcolumn:\n diffs = self._line_wrapper(diffs)\n\n # collect up from/to lines and flags into lists (also format the lines)\n fromlist,tolist,flaglist = self._collect_lines(diffs)\n\n # process change flags, generating middle column of next anchors/links\n fromlist,tolist,flaglist,next_href,next_id = self._convert_flags(\n fromlist,tolist,flaglist,context,numlines)\n\n s = []\n fmt = ' <tr><td class=\"diff_next\"%s>%s</td>%s' + \\\n '<td class=\"diff_next\">%s</td>%s</tr>\\n'\n for i in range(len(flaglist)):\n if flaglist[i] is None:\n # mdiff yields None on separator lines skip the bogus ones\n # generated for the first line\n if i > 0:\n s.append(' </tbody> \\n <tbody>\\n')\n else:\n s.append( fmt % (next_id[i],next_href[i],fromlist[i],\n next_href[i],tolist[i]))\n if fromdesc or todesc:\n header_row = '<thead><tr>%s%s%s%s</tr></thead>' % (\n '<th class=\"diff_next\"><br /></th>',\n '<th colspan=\"2\" class=\"diff_header\">%s</th>' % fromdesc,\n '<th class=\"diff_next\"><br /></th>',\n '<th colspan=\"2\" class=\"diff_header\">%s</th>' % todesc)\n else:\n header_row = ''\n\n table = self._table_template % dict(\n data_rows=''.join(s),\n header_row=header_row,\n prefix=self._prefix[1])\n\n return table.replace('\\0+','<span class=\"diff_add\">'). \\\n replace('\\0-','<span class=\"diff_sub\">'). \\\n replace('\\0^','<span class=\"diff_chg\">'). \\\n replace('\\1','</span>'). \\\n replace('\\t','&nbsp;')\n\ndel re\n\ndef restore(delta, which):\n r\"\"\"\n Generate one of the two sequences that generated a delta.\n\n Given a `delta` produced by `Differ.compare()` or `ndiff()`, extract\n lines originating from file 1 or 2 (parameter `which`), stripping off line\n prefixes.\n\n Examples:\n\n >>> diff = ndiff('one\\ntwo\\nthree\\n'.splitlines(keepends=True),\n ... 'ore\\ntree\\nemu\\n'.splitlines(keepends=True))\n >>> diff = list(diff)\n >>> print(''.join(restore(diff, 1)), end=\"\")\n one\n two\n three\n >>> print(''.join(restore(diff, 2)), end=\"\")\n ore\n tree\n emu\n \"\"\"\n try:\n tag = {1: \"- \", 2: \"+ \"}[int(which)]\n except KeyError:\n raise ValueError('unknown delta choice (must be 1 or 2): %r'\n % which) from None\n prefixes = (\" \", tag)\n for line in delta:\n if line[:2] in prefixes:\n yield line[2:]\n\ndef _test():\n import doctest, difflib\n return doctest.testmod(difflib)\n\nif __name__ == \"__main__\":\n _test()\n";
diff --git a/capcodec/bench/corpus/pages/data/inflate_c.js b/capcodec/bench/corpus/pages/data/inflate_c.js
new file mode 100644
index 000000000..3fa9cd72e
--- /dev/null
+++ b/capcodec/bench/corpus/pages/data/inflate_c.js
@@ -0,0 +1 @@
+window.SOURCE_INFLATE_C = "/* inflate.c -- zlib decompression\n * Copyright (C) 1995-2022 Mark Adler\n * For conditions of distribution and use, see copyright notice in zlib.h\n */\n\n/*\n * Change history:\n *\n * 1.2.beta0 24 Nov 2002\n * - First version -- complete rewrite of inflate to simplify code, avoid\n * creation of window when not needed, minimize use of window when it is\n * needed, make inffast.c even faster, implement gzip decoding, and to\n * improve code readability and style over the previous zlib inflate code\n *\n * 1.2.beta1 25 Nov 2002\n * - Use pointers for available input and output checking in inffast.c\n * - Remove input and output counters in inffast.c\n * - Change inffast.c entry and loop from avail_in >= 7 to >= 6\n * - Remove unnecessary second byte pull from length extra in inffast.c\n * - Unroll direct copy to three copies per loop in inffast.c\n *\n * 1.2.beta2 4 Dec 2002\n * - Change external routine names to reduce potential conflicts\n * - Correct filename to inffixed.h for fixed tables in inflate.c\n * - Make hbuf[] unsigned char to match parameter type in inflate.c\n * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)\n * to avoid negation problem on Alphas (64 bit) in inflate.c\n *\n * 1.2.beta3 22 Dec 2002\n * - Add comments on state->bits assertion in inffast.c\n * - Add comments on op field in inftrees.h\n * - Fix bug in reuse of allocated window after inflateReset()\n * - Remove bit fields--back to byte structure for speed\n * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths\n * - Change post-increments to pre-increments in inflate_fast(), PPC biased?\n * - Add compile time option, POSTINC, to use post-increments instead (Intel?)\n * - Make MATCH copy in inflate() much faster for when inflate_fast() not used\n * - Use local copies of stream next and avail values, as well as local bit\n * buffer and bit count in inflate()--for speed when inflate_fast() not used\n *\n * 1.2.beta4 1 Jan 2003\n * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings\n * - Move a comment on output buffer sizes from inffast.c to inflate.c\n * - Add comments in inffast.c to introduce the inflate_fast() routine\n * - Rearrange window copies in inflate_fast() for speed and simplification\n * - Unroll last copy for window match in inflate_fast()\n * - Use local copies of window variables in inflate_fast() for speed\n * - Pull out common wnext == 0 case for speed in inflate_fast()\n * - Make op and len in inflate_fast() unsigned for consistency\n * - Add FAR to lcode and dcode declarations in inflate_fast()\n * - Simplified bad distance check in inflate_fast()\n * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new\n * source file infback.c to provide a call-back interface to inflate for\n * programs like gzip and unzip -- uses window as output buffer to avoid\n * window copying\n *\n * 1.2.beta5 1 Jan 2003\n * - Improved inflateBack() interface to allow the caller to provide initial\n * input in strm.\n * - Fixed stored blocks bug in inflateBack()\n *\n * 1.2.beta6 4 Jan 2003\n * - Added comments in inffast.c on effectiveness of POSTINC\n * - Typecasting all around to reduce compiler warnings\n * - Changed loops from while (1) or do {} while (1) to for (;;), again to\n * make compilers happy\n * - Changed type of window in inflateBackInit() to unsigned char *\n *\n * 1.2.beta7 27 Jan 2003\n * - Changed many types to unsigned or unsigned short to avoid warnings\n * - Added inflateCopy() function\n *\n * 1.2.0 9 Mar 2003\n * - Changed inflateBack() interface to provide separate opaque descriptors\n * for the in() and out() functions\n * - Changed inflateBack() argument and in_func typedef to swap the length\n * and buffer address return values for the input function\n * - Check next_in and next_out for Z_NULL on entry to inflate()\n *\n * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.\n */\n\n#include \"zutil.h\"\n#include \"inftrees.h\"\n#include \"inflate.h\"\n#include \"inffast.h\"\n\n#ifdef MAKEFIXED\n# ifndef BUILDFIXED\n# define BUILDFIXED\n# endif\n#endif\n\nlocal int inflateStateCheck(z_streamp strm) {\n struct inflate_state FAR *state;\n if (strm == Z_NULL ||\n strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)\n return 1;\n state = (struct inflate_state FAR *)strm->state;\n if (state == Z_NULL || state->strm != strm ||\n state->mode < HEAD || state->mode > SYNC)\n return 1;\n return 0;\n}\n\nint ZEXPORT inflateResetKeep(z_streamp strm) {\n struct inflate_state FAR *state;\n\n if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n state = (struct inflate_state FAR *)strm->state;\n strm->total_in = strm->total_out = state->total = 0;\n strm->msg = Z_NULL;\n if (state->wrap) /* to support ill-conceived Java test suite */\n strm->adler = state->wrap & 1;\n state->mode = HEAD;\n state->last = 0;\n state->havedict = 0;\n state->flags = -1;\n state->dmax = 32768U;\n state->head = Z_NULL;\n state->hold = 0;\n state->bits = 0;\n state->lencode = state->distcode = state->next = state->codes;\n state->sane = 1;\n state->back = -1;\n Tracev((stderr, \"inflate: reset\\n\"));\n return Z_OK;\n}\n\nint ZEXPORT inflateReset(z_streamp strm) {\n struct inflate_state FAR *state;\n\n if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n state = (struct inflate_state FAR *)strm->state;\n state->wsize = 0;\n state->whave = 0;\n state->wnext = 0;\n return inflateResetKeep(strm);\n}\n\nint ZEXPORT inflateReset2(z_streamp strm, int windowBits) {\n int wrap;\n struct inflate_state FAR *state;\n\n /* get the state */\n if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n state = (struct inflate_state FAR *)strm->state;\n\n /* extract wrap request from windowBits parameter */\n if (windowBits < 0) {\n if (windowBits < -15)\n return Z_STREAM_ERROR;\n wrap = 0;\n windowBits = -windowBits;\n }\n else {\n wrap = (windowBits >> 4) + 5;\n#ifdef GUNZIP\n if (windowBits < 48)\n windowBits &= 15;\n#endif\n }\n\n /* set number of window bits, free window if different */\n if (windowBits && (windowBits < 8 || windowBits > 15))\n return Z_STREAM_ERROR;\n if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {\n ZFREE(strm, state->window);\n state->window = Z_NULL;\n }\n\n /* update state and reset the rest of it */\n state->wrap = wrap;\n state->wbits = (unsigned)windowBits;\n return inflateReset(strm);\n}\n\nint ZEXPORT inflateInit2_(z_streamp strm, int windowBits,\n const char *version, int stream_size) {\n int ret;\n struct inflate_state FAR *state;\n\n if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||\n stream_size != (int)(sizeof(z_stream)))\n return Z_VERSION_ERROR;\n if (strm == Z_NULL) return Z_STREAM_ERROR;\n strm->msg = Z_NULL; /* in case we return an error */\n if (strm->zalloc == (alloc_func)0) {\n#ifdef Z_SOLO\n return Z_STREAM_ERROR;\n#else\n strm->zalloc = zcalloc;\n strm->opaque = (voidpf)0;\n#endif\n }\n if (strm->zfree == (free_func)0)\n#ifdef Z_SOLO\n return Z_STREAM_ERROR;\n#else\n strm->zfree = zcfree;\n#endif\n state = (struct inflate_state FAR *)\n ZALLOC(strm, 1, sizeof(struct inflate_state));\n if (state == Z_NULL) return Z_MEM_ERROR;\n Tracev((stderr, \"inflate: allocated\\n\"));\n strm->state = (struct internal_state FAR *)state;\n state->strm = strm;\n state->window = Z_NULL;\n state->mode = HEAD; /* to pass state test in inflateReset2() */\n ret = inflateReset2(strm, windowBits);\n if (ret != Z_OK) {\n ZFREE(strm, state);\n strm->state = Z_NULL;\n }\n return ret;\n}\n\nint ZEXPORT inflateInit_(z_streamp strm, const char *version,\n int stream_size) {\n return inflateInit2_(strm, DEF_WBITS, version, stream_size);\n}\n\nint ZEXPORT inflatePrime(z_streamp strm, int bits, int value) {\n struct inflate_state FAR *state;\n\n if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n if (bits == 0)\n return Z_OK;\n state = (struct inflate_state FAR *)strm->state;\n if (bits < 0) {\n state->hold = 0;\n state->bits = 0;\n return Z_OK;\n }\n if (bits > 16 || state->bits + (uInt)bits > 32) return Z_STREAM_ERROR;\n value &= (1L << bits) - 1;\n state->hold += (unsigned)value << state->bits;\n state->bits += (uInt)bits;\n return Z_OK;\n}\n\n/*\n Return state with length and distance decoding tables and index sizes set to\n fixed code decoding. Normally this returns fixed tables from inffixed.h.\n If BUILDFIXED is defined, then instead this routine builds the tables the\n first time it's called, and returns those tables the first time and\n thereafter. This reduces the size of the code by about 2K bytes, in\n exchange for a little execution time. However, BUILDFIXED should not be\n used for threaded applications, since the rewriting of the tables and virgin\n may not be thread-safe.\n */\nlocal void fixedtables(struct inflate_state FAR *state) {\n#ifdef BUILDFIXED\n static int virgin = 1;\n static code *lenfix, *distfix;\n static code fixed[544];\n\n /* build fixed huffman tables if first call (may not be thread safe) */\n if (virgin) {\n unsigned sym, bits;\n static code *next;\n\n /* literal/length table */\n sym = 0;\n while (sym < 144) state->lens[sym++] = 8;\n while (sym < 256) state->lens[sym++] = 9;\n while (sym < 280) state->lens[sym++] = 7;\n while (sym < 288) state->lens[sym++] = 8;\n next = fixed;\n lenfix = next;\n bits = 9;\n inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);\n\n /* distance table */\n sym = 0;\n while (sym < 32) state->lens[sym++] = 5;\n distfix = next;\n bits = 5;\n inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);\n\n /* do this just once */\n virgin = 0;\n }\n#else /* !BUILDFIXED */\n# include \"inffixed.h\"\n#endif /* BUILDFIXED */\n state->lencode = lenfix;\n state->lenbits = 9;\n state->distcode = distfix;\n state->distbits = 5;\n}\n\n#ifdef MAKEFIXED\n#include <stdio.h>\n\n/*\n Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also\n defines BUILDFIXED, so the tables are built on the fly. makefixed() writes\n those tables to stdout, which would be piped to inffixed.h. A small program\n can simply call makefixed to do this:\n\n void makefixed(void);\n\n int main(void)\n {\n makefixed();\n return 0;\n }\n\n Then that can be linked with zlib built with MAKEFIXED defined and run:\n\n a.out > inffixed.h\n */\nvoid makefixed(void)\n{\n unsigned low, size;\n struct inflate_state state;\n\n fixedtables(&state);\n puts(\" /* inffixed.h -- table for decoding fixed codes\");\n puts(\" * Generated automatically by makefixed().\");\n puts(\" */\");\n puts(\"\");\n puts(\" /* WARNING: this file should *not* be used by applications.\");\n puts(\" It is part of the implementation of this library and is\");\n puts(\" subject to change. Applications should only use zlib.h.\");\n puts(\" */\");\n puts(\"\");\n size = 1U << 9;\n printf(\" static const code lenfix[%u] = {\", size);\n low = 0;\n for (;;) {\n if ((low % 7) == 0) printf(\"\\n \");\n printf(\"{%u,%u,%d}\", (low & 127) == 99 ? 64 : state.lencode[low].op,\n state.lencode[low].bits, state.lencode[low].val);\n if (++low == size) break;\n putchar(',');\n }\n puts(\"\\n };\");\n size = 1U << 5;\n printf(\"\\n static const code distfix[%u] = {\", size);\n low = 0;\n for (;;) {\n if ((low % 6) == 0) printf(\"\\n \");\n printf(\"{%u,%u,%d}\", state.distcode[low].op, state.distcode[low].bits,\n state.distcode[low].val);\n if (++low == size) break;\n putchar(',');\n }\n puts(\"\\n };\");\n}\n#endif /* MAKEFIXED */\n\n/*\n Update the window with the last wsize (normally 32K) bytes written before\n returning. If window does not exist yet, create it. This is only called\n when a window is already in use, or when output has been written during this\n inflate call, but the end of the deflate stream has not been reached yet.\n It is also called to create a window for dictionary data when a dictionary\n is loaded.\n\n Providing output buffers larger than 32K to inflate() should provide a speed\n advantage, since only the last 32K of output is copied to the sliding window\n upon return from inflate(), and since all distances after the first 32K of\n output will fall in the output data, making match copies simpler and faster.\n The advantage may be dependent on the size of the processor's data caches.\n */\nlocal int updatewindow(z_streamp strm, const Bytef *end, unsigned copy) {\n struct inflate_state FAR *state;\n unsigned dist;\n\n state = (struct inflate_state FAR *)strm->state;\n\n /* if it hasn't been done already, allocate space for the window */\n if (state->window == Z_NULL) {\n state->window = (unsigned char FAR *)\n ZALLOC(strm, 1U << state->wbits,\n sizeof(unsigned char));\n if (state->window == Z_NULL) return 1;\n }\n\n /* if window not in use yet, initialize */\n if (state->wsize == 0) {\n state->wsize = 1U << state->wbits;\n state->wnext = 0;\n state->whave = 0;\n }\n\n /* copy state->wsize or less output bytes into the circular window */\n if (copy >= state->wsize) {\n zmemcpy(state->window, end - state->wsize, state->wsize);\n state->wnext = 0;\n state->whave = state->wsize;\n }\n else {\n dist = state->wsize - state->wnext;\n if (dist > copy) dist = copy;\n zmemcpy(state->window + state->wnext, end - copy, dist);\n copy -= dist;\n if (copy) {\n zmemcpy(state->window, end - copy, copy);\n state->wnext = copy;\n state->whave = state->wsize;\n }\n else {\n state->wnext += dist;\n if (state->wnext == state->wsize) state->wnext = 0;\n if (state->whave < state->wsize) state->whave += dist;\n }\n }\n return 0;\n}\n\n/* Macros for inflate(): */\n\n/* check function to use adler32() for zlib or crc32() for gzip */\n#ifdef GUNZIP\n# define UPDATE_CHECK(check, buf, len) \\\n (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))\n#else\n# define UPDATE_CHECK(check, buf, len) adler32(check, buf, len)\n#endif\n\n/* check macros for header crc */\n#ifdef GUNZIP\n# define CRC2(check, word) \\\n do { \\\n hbuf[0] = (unsigned char)(word); \\\n hbuf[1] = (unsigned char)((word) >> 8); \\\n check = crc32(check, hbuf, 2); \\\n } while (0)\n\n# define CRC4(check, word) \\\n do { \\\n hbuf[0] = (unsigned char)(word); \\\n hbuf[1] = (unsigned char)((word) >> 8); \\\n hbuf[2] = (unsigned char)((word) >> 16); \\\n hbuf[3] = (unsigned char)((word) >> 24); \\\n check = crc32(check, hbuf, 4); \\\n } while (0)\n#endif\n\n/* Load registers with state in inflate() for speed */\n#define LOAD() \\\n do { \\\n put = strm->next_out; \\\n left = strm->avail_out; \\\n next = strm->next_in; \\\n have = strm->avail_in; \\\n hold = state->hold; \\\n bits = state->bits; \\\n } while (0)\n\n/* Restore state from registers in inflate() */\n#define RESTORE() \\\n do { \\\n strm->next_out = put; \\\n strm->avail_out = left; \\\n strm->next_in = next; \\\n strm->avail_in = have; \\\n state->hold = hold; \\\n state->bits = bits; \\\n } while (0)\n\n/* Clear the input bit accumulator */\n#define INITBITS() \\\n do { \\\n hold = 0; \\\n bits = 0; \\\n } while (0)\n\n/* Get a byte of input into the bit accumulator, or return from inflate()\n if there is no input available. */\n#define PULLBYTE() \\\n do { \\\n if (have == 0) goto inf_leave; \\\n have--; \\\n hold += (unsigned long)(*next++) << bits; \\\n bits += 8; \\\n } while (0)\n\n/* Assure that there are at least n bits in the bit accumulator. If there is\n not enough available input to do that, then return from inflate(). */\n#define NEEDBITS(n) \\\n do { \\\n while (bits < (unsigned)(n)) \\\n PULLBYTE(); \\\n } while (0)\n\n/* Return the low n bits of the bit accumulator (n < 16) */\n#define BITS(n) \\\n ((unsigned)hold & ((1U << (n)) - 1))\n\n/* Remove n bits from the bit accumulator */\n#define DROPBITS(n) \\\n do { \\\n hold >>= (n); \\\n bits -= (unsigned)(n); \\\n } while (0)\n\n/* Remove zero to seven bits as needed to go to a byte boundary */\n#define BYTEBITS() \\\n do { \\\n hold >>= bits & 7; \\\n bits -= bits & 7; \\\n } while (0)\n\n/*\n inflate() uses a state machine to process as much input data and generate as\n much output data as possible before returning. The state machine is\n structured roughly as follows:\n\n for (;;) switch (state) {\n ...\n case STATEn:\n if (not enough input data or output space to make progress)\n return;\n ... make progress ...\n state = STATEm;\n break;\n ...\n }\n\n so when inflate() is called again, the same case is attempted again, and\n if the appropriate resources are provided, the machine proceeds to the\n next state. The NEEDBITS() macro is usually the way the state evaluates\n whether it can proceed or should return. NEEDBITS() does the return if\n the requested bits are not available. The typical use of the BITS macros\n is:\n\n NEEDBITS(n);\n ... do something with BITS(n) ...\n DROPBITS(n);\n\n where NEEDBITS(n) either returns from inflate() if there isn't enough\n input left to load n bits into the accumulator, or it continues. BITS(n)\n gives the low n bits in the accumulator. When done, DROPBITS(n) drops\n the low n bits off the accumulator. INITBITS() clears the accumulator\n and sets the number of available bits to zero. BYTEBITS() discards just\n enough bits to put the accumulator on a byte boundary. After BYTEBITS()\n and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.\n\n NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return\n if there is no input available. The decoding of variable length codes uses\n PULLBYTE() directly in order to pull just enough bytes to decode the next\n code, and no more.\n\n Some states loop until they get enough input, making sure that enough\n state information is maintained to continue the loop where it left off\n if NEEDBITS() returns in the loop. For example, want, need, and keep\n would all have to actually be part of the saved state in case NEEDBITS()\n returns:\n\n case STATEw:\n while (want < need) {\n NEEDBITS(n);\n keep[want++] = BITS(n);\n DROPBITS(n);\n }\n state = STATEx;\n case STATEx:\n\n As shown above, if the next state is also the next case, then the break\n is omitted.\n\n A state may also return if there is not enough output space available to\n complete that state. Those states are copying stored data, writing a\n literal byte, and copying a matching string.\n\n When returning, a \"goto inf_leave\" is used to update the total counters,\n update the check value, and determine whether any progress has been made\n during that inflate() call in order to return the proper return code.\n Progress is defined as a change in either strm->avail_in or strm->avail_out.\n When there is a window, goto inf_leave will update the window with the last\n output written. If a goto inf_leave occurs in the middle of decompression\n and there is no window currently, goto inf_leave will create one and copy\n output to the window for the next call of inflate().\n\n In this implementation, the flush parameter of inflate() only affects the\n return code (per zlib.h). inflate() always writes as much as possible to\n strm->next_out, given the space available and the provided input--the effect\n documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers\n the allocation of and copying into a sliding window until necessary, which\n provides the effect documented in zlib.h for Z_FINISH when the entire input\n stream available. So the only thing the flush parameter actually does is:\n when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it\n will return Z_BUF_ERROR if it has not reached the end of the stream.\n */\n\nint ZEXPORT inflate(z_streamp strm, int flush) {\n struct inflate_state FAR *state;\n z_const unsigned char FAR *next; /* next input */\n unsigned char FAR *put; /* next output */\n unsigned have, left; /* available input and output */\n unsigned long hold; /* bit buffer */\n unsigned bits; /* bits in bit buffer */\n unsigned in, out; /* save starting available input and output */\n unsigned copy; /* number of stored or match bytes to copy */\n unsigned char FAR *from; /* where to copy match bytes from */\n code here; /* current decoding table entry */\n code last; /* parent table entry */\n unsigned len; /* length to copy for repeats, bits to drop */\n int ret; /* return code */\n#ifdef GUNZIP\n unsigned char hbuf[4]; /* buffer for gzip header crc calculation */\n#endif\n static const unsigned short order[19] = /* permutation of code lengths */\n {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};\n\n if (inflateStateCheck(strm) || strm->next_out == Z_NULL ||\n (strm->next_in == Z_NULL && strm->avail_in != 0))\n return Z_STREAM_ERROR;\n\n state = (struct inflate_state FAR *)strm->state;\n if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */\n LOAD();\n in = have;\n out = left;\n ret = Z_OK;\n for (;;)\n switch (state->mode) {\n case HEAD:\n if (state->wrap == 0) {\n state->mode = TYPEDO;\n break;\n }\n NEEDBITS(16);\n#ifdef GUNZIP\n if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */\n if (state->wbits == 0)\n state->wbits = 15;\n state->check = crc32(0L, Z_NULL, 0);\n CRC2(state->check, hold);\n INITBITS();\n state->mode = FLAGS;\n break;\n }\n if (state->head != Z_NULL)\n state->head->done = -1;\n if (!(state->wrap & 1) || /* check if zlib header allowed */\n#else\n if (\n#endif\n ((BITS(8) << 8) + (hold >> 8)) % 31) {\n strm->msg = (char *)\"incorrect header check\";\n state->mode = BAD;\n break;\n }\n if (BITS(4) != Z_DEFLATED) {\n strm->msg = (char *)\"unknown compression method\";\n state->mode = BAD;\n break;\n }\n DROPBITS(4);\n len = BITS(4) + 8;\n if (state->wbits == 0)\n state->wbits = len;\n if (len > 15 || len > state->wbits) {\n strm->msg = (char *)\"invalid window size\";\n state->mode = BAD;\n break;\n }\n state->dmax = 1U << len;\n state->flags = 0; /* indicate zlib header */\n Tracev((stderr, \"inflate: zlib header ok\\n\"));\n strm->adler = state->check = adler32(0L, Z_NULL, 0);\n state->mode = hold & 0x200 ? DICTID : TYPE;\n INITBITS();\n break;\n#ifdef GUNZIP\n case FLAGS:\n NEEDBITS(16);\n state->flags = (int)(hold);\n if ((state->flags & 0xff) != Z_DEFLATED) {\n strm->msg = (char *)\"unknown compression method\";\n state->mode = BAD;\n break;\n }\n if (state->flags & 0xe000) {\n strm->msg = (char *)\"unknown header flags set\";\n state->mode = BAD;\n break;\n }\n if (state->head != Z_NULL)\n state->head->text = (int)((hold >> 8) & 1);\n if ((state->flags & 0x0200) && (state->wrap & 4))\n CRC2(state->check, hold);\n INITBITS();\n state->mode = TIME;\n /* fallthrough */\n case TIME:\n NEEDBITS(32);\n if (state->head != Z_NULL)\n state->head->time = hold;\n if ((state->flags & 0x0200) && (state->wrap & 4))\n CRC4(state->check, hold);\n INITBITS();\n state->mode = OS;\n /* fallthrough */\n case OS:\n NEEDBITS(16);\n if (state->head != Z_NULL) {\n state->head->xflags = (int)(hold & 0xff);\n state->head->os = (int)(hold >> 8);\n }\n if ((state->flags & 0x0200) && (state->wrap & 4))\n CRC2(state->check, hold);\n INITBITS();\n state->mode = EXLEN;\n /* fallthrough */\n case EXLEN:\n if (state->flags & 0x0400) {\n NEEDBITS(16);\n state->length = (unsigned)(hold);\n if (state->head != Z_NULL)\n state->head->extra_len = (unsigned)hold;\n if ((state->flags & 0x0200) && (state->wrap & 4))\n CRC2(state->check, hold);\n INITBITS();\n }\n else if (state->head != Z_NULL)\n state->head->extra = Z_NULL;\n state->mode = EXTRA;\n /* fallthrough */\n case EXTRA:\n if (state->flags & 0x0400) {\n copy = state->length;\n if (copy > have) copy = have;\n if (copy) {\n if (state->head != Z_NULL &&\n state->head->extra != Z_NULL &&\n (len = state->head->extra_len - state->length) <\n state->head->extra_max) {\n zmemcpy(state->head->extra + len, next,\n len + copy > state->head->extra_max ?\n state->head->extra_max - len : copy);\n }\n if ((state->flags & 0x0200) && (state->wrap & 4))\n state->check = crc32(state->check, next, copy);\n have -= copy;\n next += copy;\n state->length -= copy;\n }\n if (state->length) goto inf_leave;\n }\n state->length = 0;\n state->mode = NAME;\n /* fallthrough */\n case NAME:\n if (state->flags & 0x0800) {\n if (have == 0) goto inf_leave;\n copy = 0;\n do {\n len = (unsigned)(next[copy++]);\n if (state->head != Z_NULL &&\n state->head->name != Z_NULL &&\n state->length < state->head->name_max)\n state->head->name[state->length++] = (Bytef)len;\n } while (len && copy < have);\n if ((state->flags & 0x0200) && (state->wrap & 4))\n state->check = crc32(state->check, next, copy);\n have -= copy;\n next += copy;\n if (len) goto inf_leave;\n }\n else if (state->head != Z_NULL)\n state->head->name = Z_NULL;\n state->length = 0;\n state->mode = COMMENT;\n /* fallthrough */\n case COMMENT:\n if (state->flags & 0x1000) {\n if (have == 0) goto inf_leave;\n copy = 0;\n do {\n len = (unsigned)(next[copy++]);\n if (state->head != Z_NULL &&\n state->head->comment != Z_NULL &&\n state->length < state->head->comm_max)\n state->head->comment[state->length++] = (Bytef)len;\n } while (len && copy < have);\n if ((state->flags & 0x0200) && (state->wrap & 4))\n state->check = crc32(state->check, next, copy);\n have -= copy;\n next += copy;\n if (len) goto inf_leave;\n }\n else if (state->head != Z_NULL)\n state->head->comment = Z_NULL;\n state->mode = HCRC;\n /* fallthrough */\n case HCRC:\n if (state->flags & 0x0200) {\n NEEDBITS(16);\n if ((state->wrap & 4) && hold != (state->check & 0xffff)) {\n strm->msg = (char *)\"header crc mismatch\";\n state->mode = BAD;\n break;\n }\n INITBITS();\n }\n if (state->head != Z_NULL) {\n state->head->hcrc = (int)((state->flags >> 9) & 1);\n state->head->done = 1;\n }\n strm->adler = state->check = crc32(0L, Z_NULL, 0);\n state->mode = TYPE;\n break;\n#endif\n case DICTID:\n NEEDBITS(32);\n strm->adler = state->check = ZSWAP32(hold);\n INITBITS();\n state->mode = DICT;\n /* fallthrough */\n case DICT:\n if (state->havedict == 0) {\n RESTORE();\n return Z_NEED_DICT;\n }\n strm->adler = state->check = adler32(0L, Z_NULL, 0);\n state->mode = TYPE;\n /* fallthrough */\n case TYPE:\n if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;\n /* fallthrough */\n case TYPEDO:\n if (state->last) {\n BYTEBITS();\n state->mode = CHECK;\n break;\n }\n NEEDBITS(3);\n state->last = BITS(1);\n DROPBITS(1);\n switch (BITS(2)) {\n case 0: /* stored block */\n Tracev((stderr, \"inflate: stored block%s\\n\",\n state->last ? \" (last)\" : \"\"));\n state->mode = STORED;\n break;\n case 1: /* fixed block */\n fixedtables(state);\n Tracev((stderr, \"inflate: fixed codes block%s\\n\",\n state->last ? \" (last)\" : \"\"));\n state->mode = LEN_; /* decode codes */\n if (flush == Z_TREES) {\n DROPBITS(2);\n goto inf_leave;\n }\n break;\n case 2: /* dynamic block */\n Tracev((stderr, \"inflate: dynamic codes block%s\\n\",\n state->last ? \" (last)\" : \"\"));\n state->mode = TABLE;\n break;\n case 3:\n strm->msg = (char *)\"invalid block type\";\n state->mode = BAD;\n }\n DROPBITS(2);\n break;\n case STORED:\n BYTEBITS(); /* go to byte boundary */\n NEEDBITS(32);\n if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {\n strm->msg = (char *)\"invalid stored block lengths\";\n state->mode = BAD;\n break;\n }\n state->length = (unsigned)hold & 0xffff;\n Tracev((stderr, \"inflate: stored length %u\\n\",\n state->length));\n INITBITS();\n state->mode = COPY_;\n if (flush == Z_TREES) goto inf_leave;\n /* fallthrough */\n case COPY_:\n state->mode = COPY;\n /* fallthrough */\n case COPY:\n copy = state->length;\n if (copy) {\n if (copy > have) copy = have;\n if (copy > left) copy = left;\n if (copy == 0) goto inf_leave;\n zmemcpy(put, next, copy);\n have -= copy;\n next += copy;\n left -= copy;\n put += copy;\n state->length -= copy;\n break;\n }\n Tracev((stderr, \"inflate: stored end\\n\"));\n state->mode = TYPE;\n break;\n case TABLE:\n NEEDBITS(14);\n state->nlen = BITS(5) + 257;\n DROPBITS(5);\n state->ndist = BITS(5) + 1;\n DROPBITS(5);\n state->ncode = BITS(4) + 4;\n DROPBITS(4);\n#ifndef PKZIP_BUG_WORKAROUND\n if (state->nlen > 286 || state->ndist > 30) {\n strm->msg = (char *)\"too many length or distance symbols\";\n state->mode = BAD;\n break;\n }\n#endif\n Tracev((stderr, \"inflate: table sizes ok\\n\"));\n state->have = 0;\n state->mode = LENLENS;\n /* fallthrough */\n case LENLENS:\n while (state->have < state->ncode) {\n NEEDBITS(3);\n state->lens[order[state->have++]] = (unsigned short)BITS(3);\n DROPBITS(3);\n }\n while (state->have < 19)\n state->lens[order[state->have++]] = 0;\n state->next = state->codes;\n state->lencode = (const code FAR *)(state->next);\n state->lenbits = 7;\n ret = inflate_table(CODES, state->lens, 19, &(state->next),\n &(state->lenbits), state->work);\n if (ret) {\n strm->msg = (char *)\"invalid code lengths set\";\n state->mode = BAD;\n break;\n }\n Tracev((stderr, \"inflate: code lengths ok\\n\"));\n state->have = 0;\n state->mode = CODELENS;\n /* fallthrough */\n case CODELENS:\n while (state->have < state->nlen + state->ndist) {\n for (;;) {\n here = state->lencode[BITS(state->lenbits)];\n if ((unsigned)(here.bits) <= bits) break;\n PULLBYTE();\n }\n if (here.val < 16) {\n DROPBITS(here.bits);\n state->lens[state->have++] = here.val;\n }\n else {\n if (here.val == 16) {\n NEEDBITS(here.bits + 2);\n DROPBITS(here.bits);\n if (state->have == 0) {\n strm->msg = (char *)\"invalid bit length repeat\";\n state->mode = BAD;\n break;\n }\n len = state->lens[state->have - 1];\n copy = 3 + BITS(2);\n DROPBITS(2);\n }\n else if (here.val == 17) {\n NEEDBITS(here.bits + 3);\n DROPBITS(here.bits);\n len = 0;\n copy = 3 + BITS(3);\n DROPBITS(3);\n }\n else {\n NEEDBITS(here.bits + 7);\n DROPBITS(here.bits);\n len = 0;\n copy = 11 + BITS(7);\n DROPBITS(7);\n }\n if (state->have + copy > state->nlen + state->ndist) {\n strm->msg = (char *)\"invalid bit length repeat\";\n state->mode = BAD;\n break;\n }\n while (copy--)\n state->lens[state->have++] = (unsigned short)len;\n }\n }\n\n /* handle error breaks in while */\n if (state->mode == BAD) break;\n\n /* check for end-of-block code (better have one) */\n if (state->lens[256] == 0) {\n strm->msg = (char *)\"invalid code -- missing end-of-block\";\n state->mode = BAD;\n break;\n }\n\n /* build code tables -- note: do not change the lenbits or distbits\n values here (9 and 6) without reading the comments in inftrees.h\n concerning the ENOUGH constants, which depend on those values */\n state->next = state->codes;\n state->lencode = (const code FAR *)(state->next);\n state->lenbits = 9;\n ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),\n &(state->lenbits), state->work);\n if (ret) {\n strm->msg = (char *)\"invalid literal/lengths set\";\n state->mode = BAD;\n break;\n }\n state->distcode = (const code FAR *)(state->next);\n state->distbits = 6;\n ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,\n &(state->next), &(state->distbits), state->work);\n if (ret) {\n strm->msg = (char *)\"invalid distances set\";\n state->mode = BAD;\n break;\n }\n Tracev((stderr, \"inflate: codes ok\\n\"));\n state->mode = LEN_;\n if (flush == Z_TREES) goto inf_leave;\n /* fallthrough */\n case LEN_:\n state->mode = LEN;\n /* fallthrough */\n case LEN:\n if (have >= 6 && left >= 258) {\n RESTORE();\n inflate_fast(strm, out);\n LOAD();\n if (state->mode == TYPE)\n state->back = -1;\n break;\n }\n state->back = 0;\n for (;;) {\n here = state->lencode[BITS(state->lenbits)];\n if ((unsigned)(here.bits) <= bits) break;\n PULLBYTE();\n }\n if (here.op && (here.op & 0xf0) == 0) {\n last = here;\n for (;;) {\n here = state->lencode[last.val +\n (BITS(last.bits + last.op) >> last.bits)];\n if ((unsigned)(last.bits + here.bits) <= bits) break;\n PULLBYTE();\n }\n DROPBITS(last.bits);\n state->back += last.bits;\n }\n DROPBITS(here.bits);\n state->back += here.bits;\n state->length = (unsigned)here.val;\n if ((int)(here.op) == 0) {\n Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?\n \"inflate: literal '%c'\\n\" :\n \"inflate: literal 0x%02x\\n\", here.val));\n state->mode = LIT;\n break;\n }\n if (here.op & 32) {\n Tracevv((stderr, \"inflate: end of block\\n\"));\n state->back = -1;\n state->mode = TYPE;\n break;\n }\n if (here.op & 64) {\n strm->msg = (char *)\"invalid literal/length code\";\n state->mode = BAD;\n break;\n }\n state->extra = (unsigned)(here.op) & 15;\n state->mode = LENEXT;\n /* fallthrough */\n case LENEXT:\n if (state->extra) {\n NEEDBITS(state->extra);\n state->length += BITS(state->extra);\n DROPBITS(state->extra);\n state->back += state->extra;\n }\n Tracevv((stderr, \"inflate: length %u\\n\", state->length));\n state->was = state->length;\n state->mode = DIST;\n /* fallthrough */\n case DIST:\n for (;;) {\n here = state->distcode[BITS(state->distbits)];\n if ((unsigned)(here.bits) <= bits) break;\n PULLBYTE();\n }\n if ((here.op & 0xf0) == 0) {\n last = here;\n for (;;) {\n here = state->distcode[last.val +\n (BITS(last.bits + last.op) >> last.bits)];\n if ((unsigned)(last.bits + here.bits) <= bits) break;\n PULLBYTE();\n }\n DROPBITS(last.bits);\n state->back += last.bits;\n }\n DROPBITS(here.bits);\n state->back += here.bits;\n if (here.op & 64) {\n strm->msg = (char *)\"invalid distance code\";\n state->mode = BAD;\n break;\n }\n state->offset = (unsigned)here.val;\n state->extra = (unsigned)(here.op) & 15;\n state->mode = DISTEXT;\n /* fallthrough */\n case DISTEXT:\n if (state->extra) {\n NEEDBITS(state->extra);\n state->offset += BITS(state->extra);\n DROPBITS(state->extra);\n state->back += state->extra;\n }\n#ifdef INFLATE_STRICT\n if (state->offset > state->dmax) {\n strm->msg = (char *)\"invalid distance too far back\";\n state->mode = BAD;\n break;\n }\n#endif\n Tracevv((stderr, \"inflate: distance %u\\n\", state->offset));\n state->mode = MATCH;\n /* fallthrough */\n case MATCH:\n if (left == 0) goto inf_leave;\n copy = out - left;\n if (state->offset > copy) { /* copy from window */\n copy = state->offset - copy;\n if (copy > state->whave) {\n if (state->sane) {\n strm->msg = (char *)\"invalid distance too far back\";\n state->mode = BAD;\n break;\n }\n#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n Trace((stderr, \"inflate.c too far\\n\"));\n copy -= state->whave;\n if (copy > state->length) copy = state->length;\n if (copy > left) copy = left;\n left -= copy;\n state->length -= copy;\n do {\n *put++ = 0;\n } while (--copy);\n if (state->length == 0) state->mode = LEN;\n break;\n#endif\n }\n if (copy > state->wnext) {\n copy -= state->wnext;\n from = state->window + (state->wsize - copy);\n }\n else\n from = state->window + (state->wnext - copy);\n if (copy > state->length) copy = state->length;\n }\n else { /* copy from output */\n from = put - state->offset;\n copy = state->length;\n }\n if (copy > left) copy = left;\n left -= copy;\n state->length -= copy;\n do {\n *put++ = *from++;\n } while (--copy);\n if (state->length == 0) state->mode = LEN;\n break;\n case LIT:\n if (left == 0) goto inf_leave;\n *put++ = (unsigned char)(state->length);\n left--;\n state->mode = LEN;\n break;\n case CHECK:\n if (state->wrap) {\n NEEDBITS(32);\n out -= left;\n strm->total_out += out;\n state->total += out;\n if ((state->wrap & 4) && out)\n strm->adler = state->check =\n UPDATE_CHECK(state->check, put - out, out);\n out = left;\n if ((state->wrap & 4) && (\n#ifdef GUNZIP\n state->flags ? hold :\n#endif\n ZSWAP32(hold)) != state->check) {\n strm->msg = (char *)\"incorrect data check\";\n state->mode = BAD;\n break;\n }\n INITBITS();\n Tracev((stderr, \"inflate: check matches trailer\\n\"));\n }\n#ifdef GUNZIP\n state->mode = LENGTH;\n /* fallthrough */\n case LENGTH:\n if (state->wrap && state->flags) {\n NEEDBITS(32);\n if ((state->wrap & 4) && hold != (state->total & 0xffffffff)) {\n strm->msg = (char *)\"incorrect length check\";\n state->mode = BAD;\n break;\n }\n INITBITS();\n Tracev((stderr, \"inflate: length matches trailer\\n\"));\n }\n#endif\n state->mode = DONE;\n /* fallthrough */\n case DONE:\n ret = Z_STREAM_END;\n goto inf_leave;\n case BAD:\n ret = Z_DATA_ERROR;\n goto inf_leave;\n case MEM:\n return Z_MEM_ERROR;\n case SYNC:\n /* fallthrough */\n default:\n return Z_STREAM_ERROR;\n }\n\n /*\n Return from inflate(), updating the total counts and the check value.\n If there was no progress during the inflate() call, return a buffer\n error. Call updatewindow() to create and/or update the window state.\n Note: a memory error from inflate() is non-recoverable.\n */\n inf_leave:\n RESTORE();\n if (state->wsize || (out != strm->avail_out && state->mode < BAD &&\n (state->mode < CHECK || flush != Z_FINISH)))\n if (updatewindow(strm, strm->next_out, out - strm->avail_out)) {\n state->mode = MEM;\n return Z_MEM_ERROR;\n }\n in -= strm->avail_in;\n out -= strm->avail_out;\n strm->total_in += in;\n strm->total_out += out;\n state->total += out;\n if ((state->wrap & 4) && out)\n strm->adler = state->check =\n UPDATE_CHECK(state->check, strm->next_out - out, out);\n strm->data_type = (int)state->bits + (state->last ? 64 : 0) +\n (state->mode == TYPE ? 128 : 0) +\n (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);\n if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)\n ret = Z_BUF_ERROR;\n return ret;\n}\n\nint ZEXPORT inflateEnd(z_streamp strm) {\n struct inflate_state FAR *state;\n if (inflateStateCheck(strm))\n return Z_STREAM_ERROR;\n state = (struct inflate_state FAR *)strm->state;\n if (state->window != Z_NULL) ZFREE(strm, state->window);\n ZFREE(strm, strm->state);\n strm->state = Z_NULL;\n Tracev((stderr, \"inflate: end\\n\"));\n return Z_OK;\n}\n\nint ZEXPORT inflateGetDictionary(z_streamp strm, Bytef *dictionary,\n uInt *dictLength) {\n struct inflate_state FAR *state;\n\n /* check state */\n if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n state = (struct inflate_state FAR *)strm->state;\n\n /* copy dictionary */\n if (state->whave && dictionary != Z_NULL) {\n zmemcpy(dictionary, state->window + state->wnext,\n state->whave - state->wnext);\n zmemcpy(dictionary + state->whave - state->wnext,\n state->window, state->wnext);\n }\n if (dictLength != Z_NULL)\n *dictLength = state->whave;\n return Z_OK;\n}\n\nint ZEXPORT inflateSetDictionary(z_streamp strm, const Bytef *dictionary,\n uInt dictLength) {\n struct inflate_state FAR *state;\n unsigned long dictid;\n int ret;\n\n /* check state */\n if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n state = (struct inflate_state FAR *)strm->state;\n if (state->wrap != 0 && state->mode != DICT)\n return Z_STREAM_ERROR;\n\n /* check for correct dictionary identifier */\n if (state->mode == DICT) {\n dictid = adler32(0L, Z_NULL, 0);\n dictid = adler32(dictid, dictionary, dictLength);\n if (dictid != state->check)\n return Z_DATA_ERROR;\n }\n\n /* copy dictionary to window using updatewindow(), which will amend the\n existing dictionary if appropriate */\n ret = updatewindow(strm, dictionary + dictLength, dictLength);\n if (ret) {\n state->mode = MEM;\n return Z_MEM_ERROR;\n }\n state->havedict = 1;\n Tracev((stderr, \"inflate: dictionary set\\n\"));\n return Z_OK;\n}\n\nint ZEXPORT inflateGetHeader(z_streamp strm, gz_headerp head) {\n struct inflate_state FAR *state;\n\n /* check state */\n if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n state = (struct inflate_state FAR *)strm->state;\n if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;\n\n /* save header structure */\n state->head = head;\n head->done = 0;\n return Z_OK;\n}\n\n/*\n Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found\n or when out of input. When called, *have is the number of pattern bytes\n found in order so far, in 0..3. On return *have is updated to the new\n state. If on return *have equals four, then the pattern was found and the\n return value is how many bytes were read including the last byte of the\n pattern. If *have is less than four, then the pattern has not been found\n yet and the return value is len. In the latter case, syncsearch() can be\n called again with more data and the *have state. *have is initialized to\n zero for the first call.\n */\nlocal unsigned syncsearch(unsigned FAR *have, const unsigned char FAR *buf,\n unsigned len) {\n unsigned got;\n unsigned next;\n\n got = *have;\n next = 0;\n while (next < len && got < 4) {\n if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))\n got++;\n else if (buf[next])\n got = 0;\n else\n got = 4 - got;\n next++;\n }\n *have = got;\n return next;\n}\n\nint ZEXPORT inflateSync(z_streamp strm) {\n unsigned len; /* number of bytes to look at or looked at */\n int flags; /* temporary to save header status */\n unsigned long in, out; /* temporary to save total_in and total_out */\n unsigned char buf[4]; /* to restore bit buffer to byte string */\n struct inflate_state FAR *state;\n\n /* check parameters */\n if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n state = (struct inflate_state FAR *)strm->state;\n if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;\n\n /* if first time, start search in bit buffer */\n if (state->mode != SYNC) {\n state->mode = SYNC;\n state->hold >>= state->bits & 7;\n state->bits -= state->bits & 7;\n len = 0;\n while (state->bits >= 8) {\n buf[len++] = (unsigned char)(state->hold);\n state->hold >>= 8;\n state->bits -= 8;\n }\n state->have = 0;\n syncsearch(&(state->have), buf, len);\n }\n\n /* search available input */\n len = syncsearch(&(state->have), strm->next_in, strm->avail_in);\n strm->avail_in -= len;\n strm->next_in += len;\n strm->total_in += len;\n\n /* return no joy or set up to restart inflate() on a new block */\n if (state->have != 4) return Z_DATA_ERROR;\n if (state->flags == -1)\n state->wrap = 0; /* if no header yet, treat as raw */\n else\n state->wrap &= ~4; /* no point in computing a check value now */\n flags = state->flags;\n in = strm->total_in; out = strm->total_out;\n inflateReset(strm);\n strm->total_in = in; strm->total_out = out;\n state->flags = flags;\n state->mode = TYPE;\n return Z_OK;\n}\n\n/*\n Returns true if inflate is currently at the end of a block generated by\n Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP\n implementation to provide an additional safety check. PPP uses\n Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored\n block. When decompressing, PPP checks that at the end of input packet,\n inflate is waiting for these length bytes.\n */\nint ZEXPORT inflateSyncPoint(z_streamp strm) {\n struct inflate_state FAR *state;\n\n if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n state = (struct inflate_state FAR *)strm->state;\n return state->mode == STORED && state->bits == 0;\n}\n\nint ZEXPORT inflateCopy(z_streamp dest, z_streamp source) {\n struct inflate_state FAR *state;\n struct inflate_state FAR *copy;\n unsigned char FAR *window;\n unsigned wsize;\n\n /* check input */\n if (inflateStateCheck(source) || dest == Z_NULL)\n return Z_STREAM_ERROR;\n state = (struct inflate_state FAR *)source->state;\n\n /* allocate space */\n copy = (struct inflate_state FAR *)\n ZALLOC(source, 1, sizeof(struct inflate_state));\n if (copy == Z_NULL) return Z_MEM_ERROR;\n window = Z_NULL;\n if (state->window != Z_NULL) {\n window = (unsigned char FAR *)\n ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));\n if (window == Z_NULL) {\n ZFREE(source, copy);\n return Z_MEM_ERROR;\n }\n }\n\n /* copy state */\n zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));\n zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state));\n copy->strm = dest;\n if (state->lencode >= state->codes &&\n state->lencode <= state->codes + ENOUGH - 1) {\n copy->lencode = copy->codes + (state->lencode - state->codes);\n copy->distcode = copy->codes + (state->distcode - state->codes);\n }\n copy->next = copy->codes + (state->next - state->codes);\n if (window != Z_NULL) {\n wsize = 1U << state->wbits;\n zmemcpy(window, state->window, wsize);\n }\n copy->window = window;\n dest->state = (struct internal_state FAR *)copy;\n return Z_OK;\n}\n\nint ZEXPORT inflateUndermine(z_streamp strm, int subvert) {\n struct inflate_state FAR *state;\n\n if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n state = (struct inflate_state FAR *)strm->state;\n#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR\n state->sane = !subvert;\n return Z_OK;\n#else\n (void)subvert;\n state->sane = 1;\n return Z_DATA_ERROR;\n#endif\n}\n\nint ZEXPORT inflateValidate(z_streamp strm, int check) {\n struct inflate_state FAR *state;\n\n if (inflateStateCheck(strm)) return Z_STREAM_ERROR;\n state = (struct inflate_state FAR *)strm->state;\n if (check && state->wrap)\n state->wrap |= 4;\n else\n state->wrap &= ~4;\n return Z_OK;\n}\n\nlong ZEXPORT inflateMark(z_streamp strm) {\n struct inflate_state FAR *state;\n\n if (inflateStateCheck(strm))\n return -(1L << 16);\n state = (struct inflate_state FAR *)strm->state;\n return (long)(((unsigned long)((long)state->back)) << 16) +\n (state->mode == COPY ? state->length :\n (state->mode == MATCH ? state->was - state->length : 0));\n}\n\nunsigned long ZEXPORT inflateCodesUsed(z_streamp strm) {\n struct inflate_state FAR *state;\n if (inflateStateCheck(strm)) return (unsigned long)-1;\n state = (struct inflate_state FAR *)strm->state;\n return (unsigned long)(state->next - state->codes);\n}\n";
diff --git a/capcodec/bench/corpus/pages/docs.html b/capcodec/bench/corpus/pages/docs.html
new file mode 100644
index 000000000..3e16877d4
--- /dev/null
+++ b/capcodec/bench/corpus/pages/docs.html
@@ -0,0 +1,599 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Q3 Capture Pipeline Review - Google Docs</title>
+<style>
+* {
+ box-sizing: border-box;
+}
+html,
+body {
+ margin: 0;
+ height: 100%;
+ overflow: hidden;
+ background: #f9fbfd;
+ font-family: "Noto Sans", "Liberation Sans", sans-serif;
+ color: #1f1f1f;
+}
+svg.i {
+ width: 20px;
+ height: 20px;
+ fill: none;
+ stroke: #444746;
+ stroke-width: 1.7;
+ stroke-linecap: round;
+ stroke-linejoin: round;
+ flex: none;
+}
+#top {
+ height: 64px;
+ display: flex;
+ align-items: center;
+ padding: 0 16px 0 12px;
+ background: #f9fbfd;
+}
+#logo {
+ width: 40px;
+ height: 40px;
+ margin-right: 8px;
+}
+#titles {
+ display: flex;
+ flex-direction: column;
+ justify-content: center;
+}
+#titlerow {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ font-size: 18px;
+ height: 26px;
+}
+#titlerow .ttl {
+ padding: 0 4px;
+}
+#saving {
+ font-size: 13px;
+ color: #444746;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ margin-left: 4px;
+}
+#menus {
+ display: flex;
+ font-size: 14px;
+ gap: 2px;
+ margin-left: -4px;
+}
+#menus span {
+ padding: 2px 7px;
+ border-radius: 4px;
+}
+#topright {
+ margin-left: auto;
+ display: flex;
+ align-items: center;
+ gap: 18px;
+}
+#share {
+ background: #c2e7ff;
+ border-radius: 20px;
+ height: 40px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 0 18px 0 14px;
+ font-size: 14px;
+ font-weight: 600;
+ color: #001d35;
+}
+.avatar {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: #fff;
+ font-size: 14px;
+ font-weight: 600;
+}
+#toolbar {
+ height: 40px;
+ margin: 0 16px 0 16px;
+ background: #edf2fa;
+ border-radius: 24px;
+ display: flex;
+ align-items: center;
+ padding: 0 12px;
+ gap: 4px;
+ font-size: 14px;
+ color: #444746;
+}
+#toolbar .tb {
+ height: 28px;
+ min-width: 28px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ border-radius: 4px;
+ padding: 0 3px;
+ gap: 4px;
+}
+#toolbar .sep {
+ width: 1px;
+ height: 20px;
+ background: #c7c7c7;
+ margin: 0 5px;
+}
+#toolbar .dd {
+ padding: 0 6px;
+ gap: 10px;
+}
+#toolbar .fs {
+ border: 1px solid #747775;
+ border-radius: 4px;
+ width: 36px;
+ height: 24px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+#toolbar b,
+#toolbar i,
+#toolbar u {
+ font-family: "Liberation Serif", serif;
+ font-size: 17px;
+ color: #444746;
+}
+#toolbar .right {
+ margin-left: auto;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+#ruler {
+ height: 24px;
+ position: relative;
+ margin-top: 8px;
+ border-bottom: 1px solid #e3e3e3;
+ background: #f9fbfd;
+}
+#ruler .bar {
+ position: absolute;
+ left: 552px;
+ width: 816px;
+ top: 3px;
+ height: 18px;
+ background: #fff;
+ border: 1px solid #dadce0;
+}
+#ruler .margin {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ width: 96px;
+ background: #e8eaed;
+}
+#ruler .tick {
+ position: absolute;
+ top: 11px;
+ width: 1px;
+ height: 4px;
+ background: #80868b;
+}
+#ruler .tick.big {
+ top: 8px;
+ height: 7px;
+}
+#ruler .num {
+ position: absolute;
+ top: 1px;
+ font-size: 10px;
+ color: #5f6368;
+ transform: translateX(-50%);
+}
+#ruler .ind {
+ position: absolute;
+ top: 0;
+ width: 0;
+ height: 0;
+ border-left: 6px solid transparent;
+ border-right: 6px solid transparent;
+ border-top: 8px solid #1a73e8;
+ transform: translateX(-6px);
+}
+#body {
+ position: absolute;
+ top: 145px;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ display: flex;
+}
+#outline {
+ width: 264px;
+ padding: 18px 0 0 22px;
+ font-size: 14px;
+ color: #444746;
+ flex: none;
+}
+#outline .oh {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ margin-bottom: 18px;
+ font-size: 14px;
+ color: #1f1f1f;
+}
+#outline .tabitem {
+ background: #d3e3fd;
+ border-radius: 18px;
+ padding: 8px 14px;
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ margin-right: 18px;
+ color: #0b57d0;
+ font-weight: 600;
+ margin-bottom: 8px;
+}
+#outline .oi {
+ padding: 6px 0 6px 40px;
+ font-size: 13px;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ margin-right: 18px;
+}
+#outline .oi.h2 {
+ padding-left: 54px;
+}
+#canvas {
+ flex: 1;
+ overflow-y: scroll;
+ position: relative;
+}
+#canvas::-webkit-scrollbar {
+ width: 14px;
+}
+#canvas::-webkit-scrollbar-thumb {
+ background: #dadce0;
+ border-radius: 8px;
+ border: 3px solid #f9fbfd;
+}
+#canvas::-webkit-scrollbar-track {
+ background: #f9fbfd;
+}
+#pagewrap {
+ position: relative;
+ margin: 12px 0 40px 288px;
+ width: 816px;
+}
+.page {
+ width: 816px;
+ min-height: 1056px;
+ background: #fff;
+ box-shadow: 0 1px 3px 1px #3c40431a, 0 1px 2px 0 #3c404326;
+ padding: 96px 96px 96px 96px;
+}
+#doc {
+ outline: none;
+ font-family: "Liberation Sans", Arial, sans-serif;
+ font-size: 15px;
+ line-height: 1.38;
+ color: #000;
+ caret-color: #000;
+}
+#doc p {
+ margin: 0 0 10px;
+}
+#doc h1 {
+ font-size: 26px;
+ font-weight: 400;
+ margin: 0 0 4px;
+}
+#doc .subtitle {
+ font-size: 15px;
+ color: #666;
+ margin-bottom: 18px;
+}
+#doc h2 {
+ font-size: 20px;
+ font-weight: 400;
+ margin: 22px 0 8px;
+}
+#doc h3 {
+ font-size: 16px;
+ font-weight: 400;
+ color: #434343;
+ margin: 18px 0 6px;
+}
+#doc ul {
+ margin: 0 0 10px;
+ padding-left: 26px;
+}
+#doc li {
+ margin-bottom: 3px;
+}
+#doc table {
+ border-collapse: collapse;
+ width: 100%;
+ margin: 6px 0 14px;
+ font-size: 14px;
+}
+#doc td,
+#doc th {
+ border: 1px solid #000;
+ padding: 5px 7px;
+ text-align: left;
+ vertical-align: top;
+}
+#doc th {
+ background: #f3f3f3;
+ font-weight: 700;
+}
+#doc .chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ background: #e1e3e1;
+ border-radius: 10px;
+ padding: 0 7px;
+ font-size: 13px;
+ line-height: 19px;
+}
+#doc .hl {
+ background: #fef7cd;
+}
+#doc a {
+ color: #1155cc;
+}
+.comment {
+ position: absolute;
+ left: 836px;
+ width: 300px;
+ background: #fff;
+ border-radius: 8px;
+ box-shadow: 0 1px 2px 0 #3c40434d, 0 1px 3px 1px #3c404326;
+ padding: 12px 14px;
+ font-size: 13px;
+ color: #1f1f1f;
+}
+.comment .who {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ margin-bottom: 8px;
+}
+.comment .who .avatar {
+ width: 28px;
+ height: 28px;
+ font-size: 12px;
+}
+.comment .nm {
+ font-weight: 600;
+ font-size: 13px;
+}
+.comment .tm {
+ font-size: 11px;
+ color: #444746;
+}
+.comment .reply {
+ margin-top: 10px;
+ border: 1px solid #c4c7c5;
+ border-radius: 16px;
+ height: 30px;
+ padding: 0 12px;
+ display: flex;
+ align-items: center;
+ color: #747775;
+}
+#explore {
+ position: absolute;
+ right: 24px;
+ bottom: 20px;
+ width: 48px;
+ height: 48px;
+ border-radius: 16px;
+ background: #fff;
+ box-shadow: 0 1px 3px 1px #3c404326, 0 1px 2px #3c40434d;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+</style>
+<script src="common/cap.js"></script>
+</head>
+<body>
+<div id="top">
+ <svg id="logo" viewBox="0 0 40 40"><path d="M10 3h14l9 9v23a2 2 0 0 1-2 2H10a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z" fill="#4285f4"/><path d="M24 3v7a2 2 0 0 0 2 2h7z" fill="#a1c2fa"/><path d="M13 19h14M13 23h14M13 27h14M13 31h9" stroke="#fff" stroke-width="2"/></svg>
+ <div id="titles">
+ <div id="titlerow"><span class="ttl">Q3 Capture Pipeline Review</span>
+ <svg class="i" viewBox="0 0 24 24"><path d="M12 3.5l2.6 5.3 5.9.9-4.3 4.1 1 5.8L12 16.9l-5.2 2.7 1-5.8L3.5 9.7l5.9-.9z"/></svg>
+ <svg class="i" viewBox="0 0 24 24"><path d="M3.5 6.5h6l2 2h9v10h-17z"/><path d="M12 11.5l2.5 2.5-2.5 2.5M9 14h5"/></svg>
+ <span id="saving"><svg class="i" viewBox="0 0 24 24"><path d="M7 18a4.5 4.5 0 0 1-.6-9A6 6 0 0 1 18 9.5a4 4 0 0 1-.5 8.5z"/><path d="M9.5 13.5l2 2 3.5-3.5"/></svg><span id="savetext">Saved to Drive</span></span>
+ </div>
+ <div id="menus"><span>File</span><span>Edit</span><span>View</span><span>Insert</span><span>Format</span><span>Tools</span><span>Extensions</span><span>Help</span></div>
+ </div>
+ <div id="topright">
+ <svg class="i" viewBox="0 0 24 24"><path d="M4 12a8 8 0 1 0 2.5-5.8"/><path d="M4 4v4h4M12 8v4.5l3 2"/></svg>
+ <svg class="i" viewBox="0 0 24 24"><path d="M4 5h16v11H8l-4 4z"/></svg>
+ <span style="display:flex;align-items:center;gap:4px"><svg class="i" viewBox="0 0 24 24"><rect x="3" y="7" width="12" height="10" rx="2"/><path d="M15 11l5-3v8l-5-3"/></svg><span style="font-size:10px">▼</span></span>
+ <div id="share"><svg class="i" viewBox="0 0 24 24" style="stroke:#001d35"><rect x="6" y="10.5" width="12" height="9" rx="1.5"/><path d="M8.5 10.5V8a3.5 3.5 0 0 1 7 0v2.5"/></svg>Share</div>
+ <div class="avatar" style="background:#7b1fa2">M</div>
+ </div>
+</div>
+<div id="toolbar">
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><circle cx="10.5" cy="10.5" r="5.5"/><path d="M15 15l5 5"/></svg></div>
+ <div class="tb" style="font-size:13px;padding:0 8px;border-radius:14px;background:#dde3ea">Menus</div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><path d="M9 7 5 11l4 4"/><path d="M5 11h9a5 5 0 0 1 0 10h-2"/></svg></div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><path d="M15 7l4 4-4 4"/><path d="M19 11h-9a5 5 0 0 0 0 10h2"/></svg></div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><path d="M7 9V4h10v5M7 17H4v-7h16v7h-3M7 14h10v6H7z"/></svg></div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><path d="M4 18 8.5 6 13 18M5.7 14h5.6M14 15l2.5 2.5L21 12"/></svg></div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><path d="M5 4h11v4H5zM16 6h3v5h-8v3M10 14h2v6h-2z"/></svg></div>
+ <div class="tb dd">100% <span style="font-size:9px">▼</span></div>
+ <div class="sep"></div>
+ <div class="tb dd" style="width:116px;justify-content:space-between">Normal text <span style="font-size:9px">▼</span></div>
+ <div class="sep"></div>
+ <div class="tb dd" style="width:92px;justify-content:space-between">Arial <span style="font-size:9px">▼</span></div>
+ <div class="sep"></div>
+ <div class="tb">−</div><div class="fs">11</div><div class="tb">+</div>
+ <div class="sep"></div>
+ <div class="tb"><b>B</b></div><div class="tb"><i>I</i></div><div class="tb"><u>U</u></div>
+ <div class="tb" style="flex-direction:column;gap:0;font-family:'Liberation Serif';font-size:16px;line-height:16px">A<span style="display:block;width:16px;height:3px;background:#000"></span></div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><path d="M6 14l7-9 5 4-7 9H6z"/><path d="M4 21h16" stroke="#ffeb3b" stroke-width="3"/></svg></div>
+ <div class="sep"></div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><path d="M10 14a4 4 0 0 0 6 0l3-3a4 4 0 0 0-6-6l-1 1M14 10a4 4 0 0 0-6 0l-3 3a4 4 0 0 0 6 6l1-1"/></svg></div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><path d="M4 5h16v11H8l-4 4z"/><path d="M12 8v5M9.5 10.5h5"/></svg></div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><rect x="4" y="4" width="16" height="16" rx="2"/><path d="M4 16l5-5 4 4 2-2 5 5"/><circle cx="15.5" cy="8.5" r="1.5"/></svg></div>
+ <div class="sep"></div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><path d="M4 6h16M4 10h10M4 14h16M4 18h10"/></svg><span style="font-size:9px">▼</span></div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><path d="M11 6h9M11 12h9M11 18h9M4 4v4M2.5 10l1.5 2 1.5-2M4 20v-4"/></svg></div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><path d="M4 6l1.5 1.5L8 5M4 12l1.5 1.5L8 11M4 18l1.5 1.5L8 17M11 6h9M11 12h9M11 18h9"/></svg><span style="font-size:9px">▼</span></div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><circle cx="5" cy="6" r="1"/><circle cx="5" cy="12" r="1"/><circle cx="5" cy="18" r="1"/><path d="M9 6h11M9 12h11M9 18h11"/></svg><span style="font-size:9px">▼</span></div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><path d="M5 6h1M5 12h1M5 18h1M9 6h11M9 12h11M9 18h11"/></svg><span style="font-size:9px">▼</span></div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><path d="M4 5h16M10 10h10M10 14h10M4 19h16M7 10l-3 2 3 2"/></svg></div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><path d="M4 5h16M10 10h10M10 14h10M4 19h16M4 10l3 2-3 2"/></svg></div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><path d="M6 5h12M12 5l-3 14M4 20l16-16"/></svg></div>
+ <div class="right">
+ <div class="tb dd"><svg class="i" viewBox="0 0 24 24"><path d="M4 20h4L19 9l-4-4L4 16z"/></svg><span style="font-size:9px">▼</span></div>
+ <div class="tb"><svg class="i" viewBox="0 0 24 24"><path d="M6 15l6-6 6 6"/></svg></div>
+ </div>
+</div>
+<div id="ruler"><div class="bar" id="rulerbar"></div></div>
+<div id="body">
+ <div id="outline">
+ <div class="oh"><svg class="i" viewBox="0 0 24 24"><path d="M15 6l-6 6 6 6"/></svg>Document tabs<svg class="i" viewBox="0 0 24 24" style="margin-left:auto;margin-right:18px"><path d="M12 5v14M5 12h14"/></svg></div>
+ <div class="tabitem"><svg class="i" viewBox="0 0 24 24" style="stroke:#0b57d0"><path d="M6 3h8l4 4v14H6z"/><path d="M9 11h6M9 15h6"/></svg>Tab 1</div>
+ <div class="oi">Q3 Capture Pipeline Review</div>
+ <div class="oi">Summary</div>
+ <div class="oi">Highlights</div>
+ <div class="oi h2">Encoder</div>
+ <div class="oi h2">Capture and upload</div>
+ <div class="oi">Metrics</div>
+ <div class="oi">Risks</div>
+ <div class="oi">Next steps</div>
+ </div>
+ <div id="canvas" data-scroll-id="canvas">
+ <div id="pagewrap">
+ <div class="page">
+ <div id="doc" contenteditable="true" spellcheck="false">
+<h1>Q3 Capture Pipeline Review</h1>
+<div class="subtitle">Prepared by Maya Lindqvist · Desktop &amp; Media team · <span class="chip">📅 Oct 6, 2026</span></div>
+<h2>Summary</h2>
+<p>This quarter we shipped the new capture pipeline to every desktop user. Recordings now start in under a second on most machines, the editor opens files twice as fast, and the number of failed uploads dropped by more than half. The remaining work is mostly about long recordings on older laptops, where memory use still grows too quickly after the first twenty minutes.</p>
+<h2>Highlights</h2>
+<h3>Encoder</h3>
+<ul>
+<li>Hardware encoding is now the default on Apple Silicon and on recent Intel and AMD GPUs.</li>
+<li>Screen content mode cuts the size of text-heavy recordings by about 30% at the same quality.</li>
+<li>Keyframes are placed on scene changes, so seeking in the web player feels instant.</li>
+</ul>
+<h3>Capture and upload</h3>
+<p>Segments are uploaded while the recording is still running, which means a ten minute video is usually ready to share a few seconds after the user clicks stop. We also added a <span class="hl">resumable upload path</span> for flaky connections; it has already recovered more than 4,000 recordings that would have failed before.</p>
+<h2>Metrics</h2>
+<table>
+<tr><th>Metric</th><th>Q2</th><th>Q3</th><th>Change</th></tr>
+<tr><td>Median time to first frame</td><td>1.8 s</td><td>0.7 s</td><td>−61%</td></tr>
+<tr><td>Failed uploads per 1,000 recordings</td><td>9.4</td><td>4.1</td><td>−56%</td></tr>
+<tr><td>Average file size per minute (1080p)</td><td>38 MB</td><td>26 MB</td><td>−32%</td></tr>
+<tr><td>Crash-free sessions</td><td>99.31%</td><td>99.72%</td><td>+0.41 pt</td></tr>
+</table>
+<h2>Risks</h2>
+<p>Memory growth on long recordings is the biggest open issue. We see it mostly on machines with 8 GB of RAM when the camera overlay is enabled, and it can lead to dropped frames after about half an hour. A fix for the frame pool is in review and should land in the next release.</p>
+<h2>Next steps</h2>
+<p id="last">For Q4 we want to finish the work on long recordings and start testing the new encoder with real customer content.</p>
+ </div>
+ </div>
+ <div class="comment" style="top:820px">
+ <div class="who"><div class="avatar" style="background:#00897b">D</div><div><div class="nm">Daniel Okafor</div><div class="tm">10:42 AM Today</div></div></div>
+ Can we add the numbers for Windows on ARM here as well? Even rough ones would help.
+ <div class="reply">Reply or add others with @</div>
+ </div>
+ </div>
+ </div>
+</div>
+<div id="explore"><svg class="i" viewBox="0 0 24 24" style="width:24px;height:24px"><path d="M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8z"/><path d="M18 15l.8 2.2L21 18l-2.2.8L18 21l-.8-2.2L15 18l2.2-.8z"/></svg></div>
+<script>
+const ruler = document.getElementById("rulerbar");
+ruler.innerHTML = '<div class="margin" style="left:0"></div><div class="margin" style="right:0"></div>';
+for (let i = 0; i <= 8.5 * 8; i++) {
+ const x = i * 12;
+ const t = document.createElement("div");
+ t.className = `tick${i % 8 === 0 ? " big" : ""}`;
+ t.style.left = `${x}px`;
+ if (i % 8 !== 0 && i % 4 !== 0 && i % 2 !== 0) t.style.height = "3px";
+ ruler.append(t);
+ if (i % 8 === 0 && i > 0 && i < 68) {
+ const n = document.createElement("div");
+ n.className = "num";
+ n.style.left = `${x}px`;
+ n.textContent = String(i / 8 - 1);
+ ruler.append(n);
+ }
+}
+for (const x of [96, 720]) {
+ const d = document.createElement("div");
+ d.className = "ind";
+ d.style.left = `${x}px`;
+ ruler.append(d);
+}
+const canvas = document.getElementById("canvas");
+const pagewrap = document.getElementById("pagewrap");
+const doc = document.getElementById("doc");
+const page = document.querySelector(".page");
+function syncRuler() {
+ ruler.style.left = `${page.getBoundingClientRect().left}px`;
+}
+syncRuler();
+const savetext = document.getElementById("savetext");
+let saveTimer = null;
+doc.addEventListener("input", () => {
+ savetext.textContent = "Saving…";
+ clearTimeout(saveTimer);
+ saveTimer = setTimeout(() => {
+ savetext.textContent = "Saved to Drive";
+ cap.event("saved");
+ }, 1600);
+});
+function placeCaretAtEnd(el) {
+ const r = document.createRange();
+ r.selectNodeContents(el);
+ r.collapse(false);
+ const s = getSelection();
+ s.removeAllRanges();
+ s.addRange(r);
+}
+const last = document.getElementById("last");
+doc.focus({ preventScroll: true });
+placeCaretAtEnd(last);
+function positionView() {
+ const lastBottom = last.getBoundingClientRect().bottom - canvas.getBoundingClientRect().top + canvas.scrollTop;
+ canvas.scrollTop = Math.max(0, Math.round(lastBottom - canvas.clientHeight * 0.6));
+}
+positionView();
+document.fonts.ready.then(positionView);
+window.capEndOfText = () => {
+ const r = document.createRange();
+ r.selectNodeContents(doc);
+ const rects = r.getClientRects();
+ const lr = rects[rects.length - 1];
+ return [Math.round(lr.right), Math.round(lr.top + lr.height / 2)];
+};
+window.capTextRegions = () => {
+ const p = page.getBoundingClientRect();
+ const c = canvas.getBoundingClientRect();
+ const top = Math.max(c.top, p.top) + 8;
+ const h = Math.floor((c.bottom - top - 16) / 2);
+ return [
+ [p.left + 96, top, 624, h],
+ [p.left + 96, top + h, 624, h],
+ ];
+};
+capSetReady();
+</script>
+</body>
+</html>
diff --git a/capcodec/bench/corpus/pages/idle.html b/capcodec/bench/corpus/pages/idle.html
new file mode 100644
index 000000000..da4c5c4a6
--- /dev/null
+++ b/capcodec/bench/corpus/pages/idle.html
@@ -0,0 +1,558 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Q3 Infrastructure Review.pdf</title>
+<style>
+* {
+ box-sizing: border-box;
+}
+html,
+body {
+ margin: 0;
+ height: 100%;
+ overflow: hidden;
+ font-family: Inter, "Noto Sans", sans-serif;
+ font-size: 13px;
+ color: #1d1d1f;
+ cursor: default;
+ user-select: none;
+}
+body {
+ background:
+ radial-gradient(1200px 800px at 18% 85%, #f6a37a 0%, #f6a37a00 60%),
+ radial-gradient(1100px 900px at 85% 20%, #6d5bd0 0%, #6d5bd000 65%),
+ linear-gradient(160deg, #1f3c88 0%, #5a3e9b 45%, #d9708a 100%);
+}
+#menubar {
+ position: fixed;
+ top: 0;
+ left: 0;
+ right: 0;
+ height: 30px;
+ background: #e9e6efd9;
+ display: flex;
+ align-items: center;
+ padding: 0 14px;
+ gap: 20px;
+ font-size: 13.5px;
+ z-index: 5;
+}
+#menubar .app {
+ font-weight: 700;
+}
+#menubar .logo {
+ width: 15px;
+ height: 15px;
+ border-radius: 50%;
+ background: conic-gradient(#1d1d1f 0 25%, #555 0 50%, #1d1d1f 0 75%, #555 0);
+}
+#menubar .rt {
+ margin-left: auto;
+ display: flex;
+ align-items: center;
+ gap: 17px;
+}
+#menubar svg {
+ display: block;
+}
+#clock {
+ font-variant-numeric: tabular-nums;
+ min-width: 150px;
+ text-align: right;
+}
+.win {
+ position: absolute;
+ left: 230px;
+ top: 58px;
+ width: 1460px;
+ height: 906px;
+ background: #ececee;
+ border-radius: 12px;
+ box-shadow:
+ 0 0 0 1px #0000002e,
+ 0 28px 70px #00000059;
+ overflow: hidden;
+ display: flex;
+ flex-direction: column;
+}
+.titlebar {
+ height: 52px;
+ background: #f6f5f8;
+ border-bottom: 1px solid #d9d8dd;
+ display: flex;
+ align-items: center;
+ padding: 0 16px;
+ gap: 16px;
+ flex: none;
+}
+.lights {
+ display: flex;
+ gap: 8px;
+}
+.lights i {
+ width: 12px;
+ height: 12px;
+ border-radius: 50%;
+ box-shadow: inset 0 0 0 0.5px #0003;
+}
+.ttl {
+ display: flex;
+ flex-direction: column;
+ line-height: 1.25;
+ margin-left: 8px;
+}
+.ttl b {
+ font-size: 13px;
+ font-weight: 600;
+}
+.ttl span {
+ font-size: 11px;
+ color: #86868b;
+}
+.tools {
+ margin-left: auto;
+ display: flex;
+ gap: 6px;
+ align-items: center;
+}
+.tools .tb {
+ width: 34px;
+ height: 26px;
+ border-radius: 6px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: #555;
+}
+.tools .tb:hover {
+ background: #e3e2e7;
+}
+.tools .search {
+ width: 190px;
+ height: 26px;
+ border-radius: 7px;
+ background: #e4e3e8;
+ color: #86868b;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 0 9px;
+ font-size: 12.5px;
+ margin-left: 8px;
+}
+.body {
+ flex: 1;
+ display: flex;
+ min-height: 0;
+}
+.thumbs {
+ width: 196px;
+ background: #f2f1f4;
+ border-right: 1px solid #d9d8dd;
+ padding: 16px 0;
+ overflow: hidden;
+ flex: none;
+}
+.th {
+ margin: 0 auto 16px;
+ width: 106px;
+ text-align: center;
+ font-size: 11px;
+ color: #6e6e73;
+}
+.th .pg {
+ width: 106px;
+ height: 137px;
+ background: #fff;
+ box-shadow: 0 0 0 1px #0000001f;
+ margin-bottom: 5px;
+ padding: 11px 9px;
+}
+.th.on .pg {
+ box-shadow:
+ 0 0 0 1px #0000001f,
+ 0 0 0 4px #b8cff8;
+}
+.th .pg i {
+ display: block;
+ height: 2px;
+ background: #c8c8cc;
+ margin-bottom: 3.5px;
+}
+.th .pg i.h {
+ height: 4px;
+ width: 60%;
+ background: #555;
+ margin-bottom: 6px;
+}
+.th .pg i.f {
+ height: 26px;
+ background: #dfe6f2;
+ margin: 5px 0;
+}
+.viewer {
+ flex: 1;
+ overflow: hidden;
+ background: #dcdbe0;
+ position: relative;
+}
+.page {
+ position: absolute;
+ left: 50%;
+ transform: translateX(-50%);
+ top: 24px;
+ width: 860px;
+ min-height: 1113px;
+ background: #fff;
+ box-shadow:
+ 0 0 0 1px #0000001a,
+ 0 4px 14px #0000001f;
+ padding: 64px 84px;
+ font-family: Charter, "Bitstream Charter", "Liberation Serif", serif;
+ font-size: 14.5px;
+ line-height: 1.55;
+ color: #222;
+}
+.page .hdr {
+ display: flex;
+ justify-content: space-between;
+ font-family: Inter, sans-serif;
+ font-size: 10.5px;
+ color: #888;
+ border-bottom: 1px solid #e3e3e3;
+ padding-bottom: 8px;
+ margin-bottom: 26px;
+}
+.page h2 {
+ font-family: Inter, sans-serif;
+ font-size: 19px;
+ margin: 0 0 12px;
+ font-weight: 700;
+ color: #111;
+}
+.page h3 {
+ font-family: Inter, sans-serif;
+ font-size: 14.5px;
+ margin: 22px 0 6px;
+ font-weight: 600;
+ color: #111;
+}
+.page p {
+ margin: 0 0 11px;
+ text-align: justify;
+ hyphens: auto;
+}
+.page table {
+ width: 100%;
+ border-collapse: collapse;
+ font-family: Inter, sans-serif;
+ font-size: 12px;
+ margin: 12px 0 14px;
+ font-variant-numeric: tabular-nums;
+}
+.page th,
+.page td {
+ padding: 5px 8px;
+ border-bottom: 1px solid #e5e5e5;
+ text-align: right;
+}
+.page th:first-child,
+.page td:first-child {
+ text-align: left;
+}
+.page th {
+ border-bottom: 1.5px solid #333;
+ font-weight: 600;
+}
+.page .cap {
+ font-family: Inter, sans-serif;
+ font-size: 11px;
+ color: #666;
+ margin-top: -6px;
+}
+#dock {
+ position: fixed;
+ bottom: 8px;
+ left: 50%;
+ transform: translateX(-50%);
+ height: 72px;
+ padding: 8px 10px;
+ display: flex;
+ gap: 8px;
+ align-items: flex-end;
+ background: #f4f2f8a6;
+ border: 1px solid #ffffff59;
+ border-radius: 22px;
+ box-shadow: 0 10px 30px #0000003d;
+ z-index: 4;
+}
+#dock .ic {
+ width: 54px;
+ height: 54px;
+ border-radius: 13px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: #fff;
+ font-weight: 700;
+ font-size: 22px;
+ position: relative;
+ box-shadow:
+ inset 0 0 0 0.5px #0003,
+ 0 1px 2px #0003;
+}
+#dock .ic.run::after {
+ content: "";
+ position: absolute;
+ bottom: -6px;
+ left: 50%;
+ width: 4px;
+ height: 4px;
+ margin-left: -2px;
+ border-radius: 50%;
+ background: #333;
+}
+#dock .sep {
+ width: 1px;
+ height: 50px;
+ background: #00000026;
+ margin: 0 3px 2px;
+}
+#toasts {
+ position: fixed;
+ top: 40px;
+ right: 14px;
+ width: 364px;
+ z-index: 6;
+}
+.toast {
+ background: #f5f4f8f2;
+ border-radius: 16px;
+ box-shadow:
+ 0 0 0 0.5px #0000002e,
+ 0 10px 28px #0000003d;
+ padding: 12px 14px;
+ display: flex;
+ gap: 11px;
+ margin-bottom: 10px;
+ transform: translateX(420px);
+ transition: transform 0.45s cubic-bezier(0.2, 0.85, 0.25, 1);
+}
+.toast.in {
+ transform: none;
+}
+.toast.out {
+ transform: translateX(420px);
+ transition-duration: 0.35s;
+ transition-timing-function: cubic-bezier(0.55, 0, 0.8, 0.3);
+}
+.toast .ti {
+ width: 38px;
+ height: 38px;
+ border-radius: 9px;
+ flex: none;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ color: #fff;
+ font-weight: 700;
+ font-size: 17px;
+}
+.toast .tx {
+ flex: 1;
+ min-width: 0;
+ line-height: 1.35;
+}
+.toast .tx .row {
+ display: flex;
+ justify-content: space-between;
+}
+.toast .tx b {
+ font-size: 13px;
+ font-weight: 600;
+}
+.toast .tx .when {
+ font-size: 11.5px;
+ color: #86868b;
+}
+.toast .tx .msg {
+ font-size: 12.5px;
+ color: #3a3a3c;
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+</style>
+<script src="common/cap.js"></script>
+</head>
+<body>
+<div id="menubar">
+ <span class="logo"></span><span class="app">Preview</span><span>File</span><span>Edit</span><span>View</span><span>Go</span><span>Tools</span><span>Window</span><span>Help</span>
+ <span class="rt">
+ <svg width="22" height="12" viewBox="0 0 22 12"><rect x="0.5" y="0.5" width="18" height="11" rx="3" fill="none" stroke="#1d1d1f" stroke-opacity=".5"/><rect x="2" y="2" width="12" height="8" rx="1.6" fill="#1d1d1f"/><rect x="19.5" y="4" width="1.6" height="4" rx=".8" fill="#1d1d1f" fill-opacity=".5"/></svg>
+ <svg width="17" height="13" viewBox="0 0 17 13"><path d="M8.5 12.2 6.2 9.5a3.4 3.4 0 0 1 4.6 0zM3.9 7.2a6.6 6.6 0 0 1 9.2 0l-1.2 1.4a4.8 4.8 0 0 0-6.8 0zM1.5 4.6a10 10 0 0 1 14 0l-1.2 1.4a8.2 8.2 0 0 0-11.6 0z" fill="#1d1d1f"/></svg>
+ <svg width="15" height="15" viewBox="0 0 15 15"><circle cx="6.3" cy="6.3" r="4.6" fill="none" stroke="#1d1d1f" stroke-width="1.6"/><path d="m9.7 9.7 4 4" stroke="#1d1d1f" stroke-width="1.8" stroke-linecap="round"/></svg>
+ <svg width="16" height="14" viewBox="0 0 16 14"><rect x="1" y="1" width="14" height="5" rx="2.5" fill="none" stroke="#1d1d1f" stroke-width="1.3"/><circle cx="12.5" cy="3.5" r="1.5" fill="#1d1d1f"/><rect x="1" y="8" width="14" height="5" rx="2.5" fill="none" stroke="#1d1d1f" stroke-width="1.3"/><circle cx="3.5" cy="10.5" r="1.5" fill="#1d1d1f"/></svg>
+ <span id="clock"></span>
+ </span>
+</div>
+
+<div class="win">
+ <div class="titlebar">
+ <span class="lights"><i style="background:#ff5f57"></i><i style="background:#febc2e"></i><i style="background:#28c840"></i></span>
+ <span class="tb" style="color:#555"><svg width="18" height="14" viewBox="0 0 18 14"><rect x=".75" y=".75" width="16.5" height="12.5" rx="2.5" fill="none" stroke="currentColor" stroke-width="1.4"/><path d="M6 1v12" stroke="currentColor" stroke-width="1.4"/></svg></span>
+ <span class="ttl"><b>Q3 Infrastructure Review.pdf</b><span>Page 2 of 14</span></span>
+ <span class="tools">
+ <span class="tb"><svg width="16" height="16" viewBox="0 0 16 16"><circle cx="7" cy="7" r="5.3" fill="none" stroke="currentColor" stroke-width="1.4"/><path d="M4.6 7h4.8" stroke="currentColor" stroke-width="1.4"/><path d="m11 11 3.6 3.6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg></span>
+ <span class="tb"><svg width="16" height="16" viewBox="0 0 16 16"><circle cx="7" cy="7" r="5.3" fill="none" stroke="currentColor" stroke-width="1.4"/><path d="M4.6 7h4.8M7 4.6v4.8" stroke="currentColor" stroke-width="1.4"/><path d="m11 11 3.6 3.6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg></span>
+ <span class="tb"><svg width="16" height="16" viewBox="0 0 16 16"><path d="M8 1.5v9M4.5 5 8 1.5 11.5 5" fill="none" stroke="currentColor" stroke-width="1.4"/><path d="M3 8.5v5h10v-5" fill="none" stroke="currentColor" stroke-width="1.4"/></svg></span>
+ <span class="tb"><svg width="16" height="16" viewBox="0 0 16 16"><path d="M2.5 13.5 3.3 10 11 2.3a1.6 1.6 0 0 1 2.3 2.3L5.6 12.3z" fill="none" stroke="currentColor" stroke-width="1.4"/></svg></span>
+ <span class="search"><svg width="13" height="13" viewBox="0 0 15 15"><circle cx="6.3" cy="6.3" r="4.6" fill="none" stroke="currentColor" stroke-width="1.6"/><path d="m9.7 9.7 4 4" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>Search</span>
+ </span>
+ </div>
+ <div class="body">
+ <div class="thumbs" id="thumbs"></div>
+ <div class="viewer" id="viewer" data-scroll-id="viewer">
+ <div class="page" id="page">
+ <div class="hdr"><span>Platform Engineering · Q3 Infrastructure Review</span><span>Confidential — internal distribution</span></div>
+ <h2>2. Reliability and capacity</h2>
+ <p>Across the quarter the production fleet served 7.4 billion API requests, up 18 percent from Q2, while the monthly availability of the public API stayed at or above the 99.95 percent objective in all three months. The single largest contributor to the error budget was the payments upstream incident on 14 August, which consumed 41 percent of the quarterly budget in under two hours. Excluding that event, the remaining burn was spread across routine deploys and two short regional network events.</p>
+ <p>Capacity planning moved from quarterly spreadsheets to the forecasting job introduced in July. The job projects request volume per service from the previous twelve weeks and flags any service whose projected p95 utilisation exceeds 70 percent within the next 30 days. In its first ten weeks it raised eleven warnings, nine of which led to scaling changes before the threshold was reached; the other two were seasonal spikes that the model now accounts for.</p>
+ <h3>2.1 Availability by service</h3>
+ <table>
+ <thead><tr><th>Service</th><th>Requests (M)</th><th>Availability</th><th>p95 (ms)</th><th>Incidents</th><th>Budget used</th></tr></thead>
+ <tbody>
+ <tr><td>api-gateway</td><td>7,412</td><td>99.982%</td><td>142</td><td>1</td><td>36%</td></tr>
+ <tr><td>checkout-svc</td><td>612</td><td>99.961%</td><td>318</td><td>2</td><td>78%</td></tr>
+ <tr><td>payments-svc</td><td>201</td><td>99.912%</td><td>466</td><td>3</td><td>176%</td></tr>
+ <tr><td>search-svc</td><td>2,904</td><td>99.990%</td><td>211</td><td>0</td><td>20%</td></tr>
+ <tr><td>catalog-svc</td><td>3,377</td><td>99.994%</td><td>88</td><td>0</td><td>12%</td></tr>
+ <tr><td>auth-svc</td><td>1,145</td><td>99.987%</td><td>64</td><td>1</td><td>26%</td></tr>
+ </tbody>
+ </table>
+ <p class="cap">Table 2. Quarterly availability and latency per tier-one service. Budget used is relative to each service's own objective.</p>
+ <p>Payments remains the only tier-one service that exceeded its error budget. The follow-up work agreed in the August review — request hedging towards the secondary provider, a shorter client timeout, and an explicit circuit breaker in the checkout path — shipped in September. Since then the service has had no incident longer than four minutes, and its p95 latency has dropped from 466 to 301 milliseconds over the last three weeks of the quarter.</p>
+ <h3>2.2 Cost</h3>
+ <p>Compute spend grew by 6 percent against an 18 percent increase in traffic, which brings the cost per million requests down to $3.12 from $3.47 in Q2. Most of the saving came from moving the search and catalog tiers onto the newer instance family and from right-sizing forty-two over-provisioned deployments identified by the utilisation report. Storage costs were flat; the log retention change planned for Q4 is expected to reduce them by roughly a fifth.</p>
+ <p>For the next quarter we propose to keep the availability objectives unchanged, to add latency objectives for the three checkout endpoints, and to extend the forecasting job to databases and queues, which are currently planned by hand.</p>
+ </div>
+ </div>
+ </div>
+</div>
+
+<div id="dock"></div>
+<div id="toasts"></div>
+
+<script>
+(() => {
+ const thumbs = document.getElementById("thumbs");
+ const pat = ["h", "", "", "", "", "f", "", "", "", "", "", "", "", "", "", "", "", "", "", "", ""];
+ for (let i = 1; i <= 6; i++) {
+ const t = document.createElement("div");
+ t.className = `th${i === 2 ? " on" : ""}`;
+ const lines = pat.map((c, k) => `<i class="${c}" style="width:${c ? "" : `${[100, 96, 100, 92, 100, 70][(k + i) % 6]}%`}"></i>`).join("");
+ t.innerHTML = `<div class="pg">${lines}</div>${i}`;
+ thumbs.append(t);
+ }
+
+ const dockApps = [
+ ["#3b82f6", "#1d4ed8", "F"],
+ ["#f97316", "#c2410c", "◉"],
+ ["#22c55e", "#15803d", "✉"],
+ ["#e5e7eb", "#9ca3af", "▦", "#ef4444"],
+ ["#a855f7", "#7e22ce", "♪"],
+ ["#0ea5e9", "#0369a1", "◎"],
+ ["#fde68a", "#f59e0b", "✎", "#7c2d12"],
+ ["#111827", "#374151", ">_"],
+ ["#f43f5e", "#be123c", "▶"],
+ ["#64748b", "#334155", "⚙"],
+ ];
+ const dock = document.getElementById("dock");
+ const running = new Set([0, 2, 6, 7]);
+ dockApps.forEach(([a, b, g, fg], i) => {
+ const d = document.createElement("div");
+ d.className = `ic${running.has(i) ? " run" : ""}`;
+ d.style.background = `linear-gradient(180deg, ${a}, ${b})`;
+ if (fg) d.style.color = fg;
+ d.textContent = g;
+ dock.append(d);
+ });
+ const sep = document.createElement("div");
+ sep.className = "sep";
+ dock.append(sep);
+ for (const [a, b, g] of [
+ ["#dbeafe", "#93c5fd", "▤"],
+ ["#e5e7eb", "#cbd5e1", "🗑"],
+ ]) {
+ const d = document.createElement("div");
+ d.className = "ic";
+ d.style.background = `linear-gradient(180deg, ${a}, ${b})`;
+ d.style.color = "#334155";
+ d.textContent = g;
+ dock.append(d);
+ }
+
+ const clock = document.getElementById("clock");
+ const startPerf = performance.now();
+ const base = new Date(2026, 9, 7, 9, 41, 12).getTime();
+ const days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
+ const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+ const pad = (n) => String(n).padStart(2, "0");
+ let lastText = "";
+ function renderClock() {
+ const d = new Date(base + Math.floor((performance.now() - startPerf) / 1000) * 1000);
+ const text = `${days[d.getDay()]} ${d.getDate()} ${months[d.getMonth()]} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
+ if (text !== lastText) {
+ clock.textContent = text;
+ lastText = text;
+ }
+ const msToNext = 1000 - ((performance.now() - startPerf) % 1000);
+ setTimeout(renderClock, msToNext + 2);
+ }
+ renderClock();
+
+ const toastHost = document.getElementById("toasts");
+ const toastDefs = [
+ { app: "Calendar", color: "linear-gradient(180deg,#fb7185,#e11d48)", glyph: "7", title: "Design review — in 10 minutes", msg: "Room 4.12 · Platform Engineering · with Maya, Jonas and 4 others" },
+ { app: "Messages", color: "linear-gradient(180deg,#4ade80,#16a34a)", glyph: "✉", title: "Jonas Becker", msg: "Saw your note on the payments budget — can we add the hedging numbers to section 2.1 before Friday?" },
+ { app: "Mail", color: "linear-gradient(180deg,#60a5fa,#2563eb)", glyph: "@", title: "Finance Ops", msg: "Re: Q3 cloud invoice reconciliation — attached the corrected cost allocation by team" },
+ ];
+ function showToast(i) {
+ const def = toastDefs[i % toastDefs.length];
+ const t = document.createElement("div");
+ t.className = "toast";
+ t.innerHTML = `<div class="ti" style="background:${def.color}">${def.glyph}</div><div class="tx"><div class="row"><b>${def.app}</b><span class="when">now</span></div><div style="font-weight:600;font-size:12.5px">${def.title}</div><div class="msg">${def.msg}</div></div>`;
+ toastHost.append(t);
+ requestAnimationFrame(() => requestAnimationFrame(() => t.classList.add("in")));
+ cap.event("toast_show", { index: i });
+ setTimeout(() => {
+ t.classList.add("out");
+ cap.event("toast_hide", { index: i });
+ setTimeout(() => t.remove(), 500);
+ }, 5600);
+ }
+ window.capToast = showToast;
+ let started = false;
+ window.capStart = (offsets) => {
+ if (started) return;
+ started = true;
+ (offsets || [11000, 29500, 46000]).forEach((ms, i) => setTimeout(() => showToast(i), ms));
+ };
+
+ window.capTextRegions = () => {
+ const r = document.getElementById("page").getBoundingClientRect();
+ const ps = document.querySelectorAll(".page p");
+ const a = ps[0].getBoundingClientRect();
+ const b = ps[ps.length - 3].getBoundingClientRect();
+ return [
+ [r.left + 84, a.top, 692, Math.min(300, a.height + ps[1].getBoundingClientRect().height + 12)],
+ [r.left + 84, b.top, 692, Math.min(300, b.bottom - b.top)],
+ ];
+ };
+ capSetReady();
+})();
+</script>
+</body>
+</html>
diff --git a/capcodec/bench/corpus/pages/slides.html b/capcodec/bench/corpus/pages/slides.html
new file mode 100644
index 000000000..b07e2f0b8
--- /dev/null
+++ b/capcodec/bench/corpus/pages/slides.html
@@ -0,0 +1,30 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Capture Pipeline 2.0 – Q3 Review - Presentation</title>
+<link rel="stylesheet" href="common/slides.css">
+<script src="common/cap.js"></script>
+</head>
+<body>
+<svg width="0" height="0" style="position:absolute">
+ <defs>
+ <filter id="grain" x="0" y="0" width="100%" height="100%">
+ <feTurbulence type="fractalNoise" baseFrequency="0.85" numOctaves="2" seed="11" result="n"/>
+ <feColorMatrix in="n" type="matrix" values="0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 0 0.5 0 0 0 0.5 0" result="g"/>
+ <feComposite in="g" in2="SourceGraphic" operator="in" result="gi"/>
+ <feBlend in="SourceGraphic" in2="gi" mode="overlay"/>
+ </filter>
+ <filter id="blur8"><feGaussianBlur stdDeviation="8"/></filter>
+ <filter id="blur3"><feGaussianBlur stdDeviation="3"/></filter>
+ </defs>
+</svg>
+<div id="deck"></div>
+<div id="webcam"><canvas id="cam"></canvas></div>
+<script src="common/slides.js"></script>
+<script src="common/webcam.js"></script>
+<script>
+capSetReady();
+</script>
+</body>
+</html>
diff --git a/capcodec/bench/corpus/pages/video.html b/capcodec/bench/corpus/pages/video.html
new file mode 100644
index 000000000..9cfdd6698
--- /dev/null
+++ b/capcodec/bench/corpus/pages/video.html
@@ -0,0 +1,32 @@
+<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<title>Big Buck Bunny</title>
+<style>
+html,
+body {
+ margin: 0;
+ width: 100%;
+ height: 100%;
+ overflow: hidden;
+ background: #000;
+ cursor: none;
+}
+video {
+ position: fixed;
+ inset: 0;
+ width: 100vw;
+ height: 100vh;
+ object-fit: cover;
+ background: #000;
+ cursor: none;
+}
+</style>
+<script src="common/cap.js"></script>
+</head>
+<body>
+<video id="video" autoplay muted loop playsinline disablepictureinpicture disableremoteplayback></video>
+<script src="common/video.js"></script>
+</body>
+</html>
diff --git a/capcodec/bench/corpus/playback.py b/capcodec/bench/corpus/playback.py
new file mode 100644
index 000000000..57fdb265c
--- /dev/null
+++ b/capcodec/bench/corpus/playback.py
@@ -0,0 +1,244 @@
+"""Map the frames of a captured video-playback clip back to source video frames.
+
+Capture (GBR) and source (H.264 4:2:0) are both decoded by ffmpeg, area-downscaled
+to 480x270 RGB and reduced to 8-bit luma. Chrome's YUV->RGB conversion is not
+swscale's (matrix, range, chroma upsampling), which leaves a smooth, colour-
+dependent bias of a few levels that is as large as the difference between
+neighbouring frames, so frames are compared on high-passed luma (minus a 9x9 box
+blur, 2x2-averaged to 240x135, normalised to zero mean and unit variance) with
+distance 1 - normalised cross-correlation. Each captured frame i is compared with
+source frames j = i + o for offsets o in a band, and a Viterbi pass picks the
+mapping that minimises total distance plus OFFSET_PENALTY per unit change of o.
+A repeated source frame shows up as j(i) == j(i-1), a skipped one as
+j(i) > j(i-1) + 1.
+"""
+
+import collections
+import json
+import subprocess
+
+import numpy as np
+
+W, H = 480, 270
+BLUR_RADIUS = 4
+BAND = 6
+OFFSET_PENALTY = 0.004
+
+
+def luma_frames(ffmpeg, path, yuv_bt709=False, count=None):
+ scale = f"scale={W}:{H}:flags=area" + (":in_color_matrix=bt709:in_range=tv" if yuv_bt709 else "")
+ cmd = [ffmpeg, "-v", "error", "-nostdin", "-i", str(path), "-map", "0:v:0", "-fps_mode", "passthrough"]
+ if count is not None:
+ cmd += ["-frames:v", str(count)]
+ cmd += ["-vf", f"{scale},format=rgb24", "-f", "rawvideo", "-"]
+ size = W * H * 3
+ out = []
+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
+ try:
+ while True:
+ buf = proc.stdout.read(size)
+ if len(buf) < size:
+ break
+ rgb = np.frombuffer(buf, dtype=np.uint8).reshape(H, W, 3).astype(np.uint16)
+ out.append(((54 * rgb[..., 0] + 183 * rgb[..., 1] + 19 * rgb[..., 2] + 128) >> 8).astype(np.uint8))
+ finally:
+ proc.stdout.close()
+ rc = proc.wait()
+ if rc != 0:
+ raise RuntimeError(f"ffmpeg decode of {path} failed with exit code {rc}")
+ return np.stack(out) if out else np.zeros((0, H, W), dtype=np.uint8)
+
+
+def _box(f, r):
+ k = 2 * r + 1
+ p = np.pad(f, r, mode="edge")
+ c = np.concatenate([np.zeros((1, p.shape[1])), p.cumsum(axis=0)], axis=0)
+ v = c[k:] - c[:-k]
+ c = np.concatenate([np.zeros((v.shape[0], 1)), v.cumsum(axis=1)], axis=1)
+ return (c[:, k:] - c[:, :-k]) / (k * k)
+
+
+def features(luma):
+ out = np.empty((len(luma), H // 2, W // 2), dtype=np.float32)
+ for i, frame in enumerate(luma):
+ f = frame.astype(np.float64)
+ hp = (f - _box(f, BLUR_RADIUS)).reshape(H // 2, 2, W // 2, 2).mean(axis=(1, 3))
+ hp -= hp.mean()
+ out[i] = hp / max(float(hp.std()), 1e-6)
+ return out
+
+
+def _dist(a, b):
+ return 1.0 - (a * b).mean(axis=(-2, -1))
+
+
+def find_offset(cap, src, probe=range(8, 16)):
+ idx = [i for i in probe if 0 <= i < len(cap)]
+ span = max(idx) - min(idx)
+ cost = np.zeros(len(src) - span)
+ for i in idx:
+ j = i - idx[0]
+ cost += _dist(src[j : j + len(cost)], cap[i])
+ return int(np.argmin(cost)) - idx[0]
+
+
+def match(cap, src, offset):
+ """Return (source index per captured frame, distance of the chosen match, distance of the best other offset)."""
+ n = len(cap)
+ offs = np.arange(offset - BAND, offset + BAND + 1)
+ d = np.full((n, len(offs)), np.inf, dtype=np.float64)
+ for i in range(n):
+ lo, hi = i + offs[0], i + offs[-1] + 1
+ a, b = max(lo, 0), min(hi, len(src))
+ if b > a:
+ d[i, a - lo : b - lo] = _dist(src[a:b], cap[i])
+ k = len(offs)
+ trans = OFFSET_PENALTY * np.abs(np.arange(k)[:, None] - np.arange(k)[None, :])
+ cost = d[0].copy()
+ back = np.zeros((n, k), dtype=np.int32)
+ for i in range(1, n):
+ tot = cost[:, None] + trans
+ back[i] = np.argmin(tot, axis=0)
+ cost = tot[back[i], np.arange(k)] + d[i]
+ path = [int(np.argmin(cost))]
+ for i in range(n - 1, 0, -1):
+ path.append(int(back[i, path[-1]]))
+ path.reverse()
+ js = [int(i + offs[p]) for i, p in enumerate(path)]
+ chosen = [float(d[i, p]) for i, p in enumerate(path)]
+ other = [float(np.min(np.delete(d[i], p))) for i, p in enumerate(path)]
+ return js, chosen, other
+
+
+def summarize(js, chosen, other, first_expected=None):
+ steps = [b - a for a, b in zip(js, js[1:])]
+ events = [{"frame": i + 1, "source_step": s} for i, s in enumerate(steps) if s != 1]
+ ratio = [o / max(c, 1e-6) for c, o in zip(chosen, other)]
+ out = {
+ "frames": len(js),
+ "source_first": js[0],
+ "source_last": js[-1],
+ "source_steps": dict(sorted(collections.Counter(steps).items())),
+ "repeated_frames": sum(s == 0 for s in steps),
+ "skipped_source_frames": sum(s - 1 for s in steps if s > 1),
+ "backward_steps": sum(s < 0 for s in steps),
+ "irregular_steps": events[:40],
+ "match_distance": {
+ "median": round(float(np.median(chosen)), 4),
+ "p99": round(float(np.percentile(chosen, 99)), 4),
+ "max": round(float(np.max(chosen)), 4),
+ },
+ "next_best_distance_ratio": {
+ "min": round(float(np.min(ratio)), 3),
+ "p01": round(float(np.percentile(ratio, 1)), 3),
+ "median": round(float(np.median(ratio)), 3),
+ },
+ "frames_with_next_best_ratio_below_2": int(sum(r < 2 for r in ratio)),
+ }
+ if first_expected is not None:
+ out["source_first_expected"] = first_expected
+ out["source_last_expected"] = first_expected + len(js) - 1
+ return out
+
+
+def video_frame_stats(events, t_first_ms, t_last_ms, fps):
+ """Chrome-side presentation stats from requestVideoFrameCallback records between two wallclock instants."""
+ vf = [e for e in events if e.get("k") == "page" and e.get("type") == "video_frame"]
+ vf = [e for e in vf if t_first_ms - 1000.0 / fps <= e["expected_display"] <= t_last_ms]
+ if len(vf) < 2:
+ return {"callbacks": len(vf)}
+ vsync = 1000.0 / 60
+ media_steps = collections.Counter(round((b["media_time"] - a["media_time"]) * fps) for a, b in zip(vf, vf[1:]))
+ presented = collections.Counter(b["presented_frames"] - a["presented_frames"] for a, b in zip(vf, vf[1:]))
+ disp = [b["expected_display"] - a["expected_display"] for a, b in zip(vf, vf[1:])]
+ disp_vsyncs = collections.Counter(round(x / vsync) for x in disp)
+ return {
+ "callbacks": len(vf),
+ "media_time_steps_frames": {str(k): v for k, v in sorted(media_steps.items())},
+ "presented_frames_steps": {str(k): v for k, v in sorted(presented.items())},
+ "expected_display_interval_vsyncs": {str(k): v for k, v in sorted(disp_vsyncs.items())},
+ "expected_display_interval_ms": {
+ "mean": round((vf[-1]["expected_display"] - vf[0]["expected_display"]) / (len(vf) - 1), 4),
+ "stdev": round(float(np.std(disp)), 3),
+ },
+ }
+
+
+def source_tile_dirty(ffmpeg, path, width, height, tile=16):
+ """Per-frame fraction of 16x16 tiles whose Y or co-sited U/V samples differ from the previous decoded frame."""
+ ysz, csz = width * height, (width // 2) * (height // 2)
+ th, tw = -(-height // tile), -(-width // tile)
+ ypad = np.zeros((th * tile, tw * tile), dtype=bool)
+ cpad = np.zeros((th * tile // 2, tw * tile // 2), dtype=bool)
+ area = np.full((th, tw), float(tile * tile))
+ if height % tile:
+ area[-1] = (height % tile) * tile
+ cmd = [ffmpeg, "-v", "error", "-nostdin", "-i", str(path), "-map", "0:v:0", "-fps_mode", "passthrough",
+ "-f", "rawvideo", "-pix_fmt", "yuv420p", "-"] # fmt: skip
+ out = []
+ prev = None
+ proc = subprocess.Popen(cmd, stdout=subprocess.PIPE)
+ try:
+ while True:
+ buf = proc.stdout.read(ysz + 2 * csz)
+ if len(buf) < ysz + 2 * csz:
+ break
+ cur = np.frombuffer(buf, dtype=np.uint8)
+ if prev is None:
+ out.append(1.0)
+ else:
+ d = cur != prev
+ ypad[:height, :width] = d[:ysz].reshape(height, width)
+ tiles = ypad.reshape(th, tile, tw, tile).any(axis=(1, 3))
+ for k in range(2):
+ cpad[: height // 2, : width // 2] = d[ysz + k * csz : ysz + (k + 1) * csz].reshape(height // 2, width // 2)
+ tiles |= cpad.reshape(th, tile // 2, tw, tile // 2).any(axis=(1, 3))
+ out.append(float((area * tiles).sum() / (width * height)))
+ prev = cur
+ finally:
+ proc.stdout.close()
+ rc = proc.wait()
+ if rc != 0:
+ raise RuntimeError(f"ffmpeg decode of {path} failed with exit code {rc}")
+ return np.array(out)
+
+
+def dirty_fractions(sideinfo_path, width, height):
+ fr = []
+ with open(sideinfo_path) as f:
+ for line in f:
+ rec = json.loads(line)
+ fr.append(sum(r[2] * r[3] for r in rec["dirty"]) / (width * height))
+ return np.array(fr)
+
+
+def dirty_distribution(captured):
+ a = captured[1:]
+ return {
+ "min": round(float(a.min()), 6),
+ "p01": round(float(np.percentile(a, 1)), 6),
+ "p05": round(float(np.percentile(a, 5)), 6),
+ "median": round(float(np.median(a)), 6),
+ "frames_ge_0_99": int((a >= 0.99).sum()),
+ "frames_ge_0_95": int((a >= 0.95).sum()),
+ "frames_ge_0_90": int((a >= 0.90).sum()),
+ "frames_lt_0_50": int((a < 0.5).sum()),
+ "frames_considered": len(a),
+ }
+
+
+def dirty_vs_source(captured, source_dirty, source_index):
+ """Compare captured per-frame dirty fractions with the source's own changed-tile fractions (frames 1..n-1)."""
+ js = np.asarray(source_index[1:])
+ ok = np.asarray(source_index[:-1]) + 1 == js
+ cap = captured[1:][ok]
+ src = source_dirty[js[ok]]
+ d = cap - src
+ return {
+ "frames_compared": int(ok.sum()),
+ "source_mean": round(float(src.mean()), 6),
+ "captured_mean": round(float(cap.mean()), 6),
+ "mean_abs_diff": round(float(np.abs(d).mean()), 6),
+ "max_abs_diff": round(float(np.abs(d).max()), 6),
+ "correlation": round(float(np.corrcoef(cap, src)[0, 1]), 6),
+ }
diff --git a/capcodec/bench/corpus/pointer_sampler.py b/capcodec/bench/corpus/pointer_sampler.py
new file mode 100644
index 000000000..b27e0c611
--- /dev/null
+++ b/capcodec/bench/corpus/pointer_sampler.py
@@ -0,0 +1,56 @@
+#!/usr/bin/env python3
+"""Sample the X pointer position at a fixed rate and write JSON lines.
+
+Each line is {"t": epoch_ms, "x": int, "y": int, "rtt": ms}. "t" is the
+midpoint of the query_pointer round trip measured with time.time(), the same
+clock that Chrome's Date.now() and ffmpeg's wallclock timestamps use.
+Runs until SIGTERM/SIGINT.
+"""
+
+import argparse
+import signal
+import time
+
+from Xlib import display
+
+
+def main():
+ ap = argparse.ArgumentParser()
+ ap.add_argument("--display", required=True)
+ ap.add_argument("--hz", type=float, default=240.0)
+ ap.add_argument("--out", required=True)
+ args = ap.parse_args()
+
+ dpy = display.Display(args.display)
+ root = dpy.screen().root
+ stop = False
+
+ def on_signal(signum, frame):
+ nonlocal stop
+ stop = True
+
+ signal.signal(signal.SIGTERM, on_signal)
+ signal.signal(signal.SIGINT, on_signal)
+
+ period = 1.0 / args.hz
+ with open(args.out, "w", buffering=1 << 16) as f:
+ next_t = time.time()
+ first = True
+ while not stop:
+ t0 = time.time()
+ p = root.query_pointer()
+ t1 = time.time()
+ f.write(f'{{"t":{(t0 + t1) * 500.0:.3f},"x":{p.root_x},"y":{p.root_y},"rtt":{(t1 - t0) * 1000.0:.3f}}}\n')
+ if first:
+ f.flush()
+ first = False
+ next_t += period
+ delay = next_t - time.time()
+ if delay > 0:
+ time.sleep(delay)
+ else:
+ next_t = time.time()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/capcodec/bench/corpus/scenarios.py b/capcodec/bench/corpus/scenarios.py
new file mode 100644
index 000000000..4537b2e1d
--- /dev/null
+++ b/capcodec/bench/corpus/scenarios.py
@@ -0,0 +1,802 @@
+"""Input helpers and per-clip scenario timelines.
+
+Scenarios run in a worker thread. They only inject X input (XTest for pointer
+and buttons, xdotool for keyboard) and talk to the page through ctx.js(),
+which is executed by the Playwright thread.
+"""
+
+import math
+import re
+import subprocess
+import time
+
+from Xlib import X, display
+from Xlib.ext import xtest
+
+
+class ScenarioOutOfTime(Exception):
+ pass
+
+
+class Input:
+ def __init__(self, disp, log, rng):
+ self.disp = disp
+ self.d = display.Display(disp)
+ self.root = self.d.screen().root
+ self.log = log
+ self.rng = rng
+ self.buttons_down = set()
+
+ def pos(self):
+ p = self.root.query_pointer()
+ return p.root_x, p.root_y
+
+ def _motion(self, x, y):
+ xtest.fake_input(self.d, X.MotionNotify, x=int(x), y=int(y))
+ self.d.sync()
+
+ def warp(self, x, y):
+ self._motion(round(x), round(y))
+ self.log("warp", to=[round(x), round(y)])
+
+ def move(self, x, y, dur=None, curve=None, hz=120.0, log=True):
+ x0, y0 = self.pos()
+ x, y = round(x), round(y)
+ dist = math.hypot(x - x0, y - y0)
+ if dist < 1:
+ return
+ if dur is None:
+ dur = (0.16 + 0.12 * math.log2(1 + dist / 14.0)) * self.rng.uniform(0.85, 1.2)
+ if curve is None:
+ curve = self.rng.uniform(-0.22, 0.22)
+ ux, uy = (x - x0) / dist, (y - y0) / dist
+ nx, ny = -uy, ux
+ b1 = curve * dist * self.rng.uniform(0.7, 1.3)
+ b2 = curve * dist * self.rng.uniform(0.4, 1.0)
+ p1 = (x0 + (x - x0) * 0.3 + nx * b1, y0 + (y - y0) * 0.3 + ny * b1)
+ p2 = (x0 + (x - x0) * 0.72 + nx * b2, y0 + (y - y0) * 0.72 + ny * b2)
+ steps = max(2, int(dur * hz))
+ start = time.time()
+ last = (x0, y0)
+ for i in range(1, steps + 1):
+ u = i / steps
+ s = 10 * u**3 - 15 * u**4 + 6 * u**5
+ m = 1 - s
+ bx = m**3 * x0 + 3 * m * m * s * p1[0] + 3 * m * s * s * p2[0] + s**3 * x
+ by = m**3 * y0 + 3 * m * m * s * p1[1] + 3 * m * s * s * p2[1] + s**3 * y
+ pt = (round(bx), round(by))
+ delay = start + u * dur - time.time()
+ if delay > 0:
+ time.sleep(delay)
+ if pt != last:
+ self._motion(*pt)
+ last = pt
+ if last != (x, y):
+ self._motion(x, y)
+ if log:
+ self.log("move", frm=[x0, y0], to=[x, y], dur=round(dur, 3))
+
+ def jiggle(self, radius=6, dur=0.6):
+ x0, y0 = self.pos()
+ tx = x0 + self.rng.uniform(-radius, radius)
+ ty = y0 + self.rng.uniform(-radius, radius)
+ self.move(tx, ty, dur=dur)
+
+ def press(self, button=1):
+ xtest.fake_input(self.d, X.ButtonPress, button)
+ self.d.sync()
+ self.buttons_down.add(button)
+ self.log("button_down", button=button, at=list(self.pos()))
+
+ def release(self, button=1):
+ xtest.fake_input(self.d, X.ButtonRelease, button)
+ self.d.sync()
+ self.buttons_down.discard(button)
+ self.log("button_up", button=button, at=list(self.pos()))
+
+ def click(self, button=1, hold=None):
+ self.press(button)
+ time.sleep(hold if hold is not None else self.rng.uniform(0.06, 0.11))
+ self.release(button)
+
+ def double_click(self):
+ self.click(hold=0.05)
+ time.sleep(0.09)
+ self.click(hold=0.05)
+
+ def wheel(self, notches, delay=0.08, horizontal=False):
+ if notches == 0:
+ return
+ if horizontal:
+ button = 7 if notches > 0 else 6
+ else:
+ button = 5 if notches > 0 else 4
+ for i in range(abs(notches)):
+ xtest.fake_input(self.d, X.ButtonPress, button)
+ xtest.fake_input(self.d, X.ButtonRelease, button)
+ self.d.sync()
+ if i + 1 < abs(notches):
+ time.sleep(delay)
+ self.log("wheel", notches=notches, delay=delay, horizontal=horizontal, at=list(self.pos()))
+
+ def drag(self, x, y, dur=None, hold_before=0.18, hold_after=0.15):
+ x0, y0 = self.pos()
+ self.press(1)
+ time.sleep(hold_before)
+ sx = x0 + (6 if x > x0 else -6)
+ self.move(sx, y0 + (3 if y > y0 else -3), dur=0.12, curve=0)
+ self.move(x, y, dur=dur, curve=self.rng.uniform(-0.12, 0.12))
+ time.sleep(hold_after)
+ self.release(1)
+
+ def xdo(self, *args):
+ subprocess.run(["xdotool", *args], check=True, env={"DISPLAY": self.disp, "PATH": "/usr/bin:/bin"})
+
+ def key(self, *keys, delay=40):
+ self.xdo("key", "--delay", str(delay), *keys)
+ self.log("key", keys=list(keys))
+
+ def type(self, text, delay):
+ if not text:
+ return
+ self.xdo("type", "--delay", str(int(delay)), "--", text)
+ self.log("type", text=text, delay=int(delay))
+
+ def release_all(self):
+ for b in list(self.buttons_down):
+ self.release(b)
+
+
+TYPO_RE = re.compile(r"\[\[([^|\]]*)\|([^\]]*)\]\]")
+PAUSE_RE = re.compile(r"<p:([0-9.]+)>")
+
+
+class Ctx:
+ def __init__(self, clip, inp, rng, js, t0, log):
+ self.clip = clip
+ self.inp = inp
+ self.rng = rng
+ self._js = js
+ self.t0 = t0
+ self.duration = clip.duration
+ self.dsf = clip.dsf
+ self.log = log
+ self.end_margin = 1.4
+
+ def t(self):
+ return time.time() - self.t0
+
+ def left(self):
+ return self.t0 + self.duration - self.end_margin - time.time()
+
+ def at(self, sec):
+ delay = self.t0 + sec - time.time()
+ if delay > 0:
+ time.sleep(delay)
+
+ def sleep(self, sec):
+ if sec > 0:
+ time.sleep(sec)
+
+ def need(self, sec):
+ if self.left() < sec:
+ raise ScenarioOutOfTime(f"needed {sec:.2f}s at t={self.t():.2f}")
+
+ def js(self, expr, arg=None):
+ return self._js(expr, arg)
+
+ def pt(self, expr, arg=None, dx=0, dy=0):
+ r = self.js(expr, arg)
+ if r is None:
+ raise RuntimeError(f"page returned no point for {expr} {arg}")
+ return (r[0] + dx) * self.dsf, (r[1] + dy) * self.dsf
+
+ def move(self, x, y, **kw):
+ self.need(0.3)
+ self.inp.move(x, y, **kw)
+
+ def move_css(self, x, y, **kw):
+ self.move(x * self.dsf, y * self.dsf, **kw)
+
+ def type_human(self, text, delay=(120, 250), punct_pause=(0.25, 0.7), hesitate=0.08, hesitate_pause=(0.4, 1.2)):
+ """Type text word by word with `xdotool type --delay N`, N drawn per word.
+
+ Markup: [[typed|correct]] types `typed`, pauses, backspaces the differing
+ suffix and types the rest of `correct`; <p:SECONDS> pauses; "\\n" presses Return.
+ """
+ pos = 0
+ parts = []
+ for m in re.finditer(r"\[\[[^\]]*\]\]|<p:[0-9.]+>|\n", text):
+ if m.start() > pos:
+ parts.append(("text", text[pos : m.start()]))
+ tok = m.group(0)
+ if tok == "\n":
+ parts.append(("enter", None))
+ elif tok.startswith("<p:"):
+ parts.append(("pause", float(PAUSE_RE.match(tok).group(1))))
+ else:
+ tm = TYPO_RE.match(tok)
+ parts.append(("typo", (tm.group(1), tm.group(2))))
+ pos = m.end()
+ if pos < len(text):
+ parts.append(("text", text[pos:]))
+ for kind, val in parts:
+ if kind == "pause":
+ self.need(val)
+ self.sleep(val)
+ elif kind == "enter":
+ self.need(0.5)
+ self.inp.key("Return")
+ self.sleep(self.rng.uniform(0.3, 0.8))
+ elif kind == "typo":
+ wrong, right = val
+ k = 0
+ while k < min(len(wrong), len(right)) and wrong[k] == right[k]:
+ k += 1
+ d = self.rng.randint(*delay)
+ self.need(len(wrong) * d / 1000 + 1.5 + len(right) * d / 1000)
+ self.inp.type(wrong, d)
+ self.sleep(self.rng.uniform(0.35, 0.8))
+ self.inp.key(*(["BackSpace"] * (len(wrong) - k)), delay=self.rng.randint(90, 140))
+ self.sleep(self.rng.uniform(0.15, 0.35))
+ self.inp.type(right[k:], self.rng.randint(*delay))
+ else:
+ for chunk in re.findall(r"\S+\s*|\s+", val):
+ d = self.rng.randint(*delay)
+ self.need(len(chunk) * d / 1000 + 0.2)
+ self.inp.type(chunk, d)
+ if chunk.rstrip()[-1:] in ".,;:!?" and chunk.rstrip():
+ self.sleep(self.rng.uniform(*punct_pause))
+ elif self.rng.random() < hesitate:
+ self.sleep(self.rng.uniform(*hesitate_pause))
+
+ def type_code(self, lines, lang, start_indent, delay=(55, 135), line_pause=(0.25, 0.9)):
+ """Type source lines into the CodeEditor, compensating for its auto-indent."""
+ cur = start_indent
+ prev_text = None
+ for idx, line in enumerate(lines):
+ if idx > 0:
+ self.need(0.6)
+ self.inp.key("Return")
+ indent = len(prev_text) - len(prev_text.lstrip(" ")) if prev_text.strip() else cur
+ stripped = prev_text.rstrip()
+ if (lang == "py" and stripped.endswith(":")) or (lang == "c" and stripped.endswith("{")):
+ indent += 4
+ cur = indent
+ self.sleep(self.rng.uniform(*line_pause))
+ content = line.strip(" ")
+ target = len(line) - len(line.lstrip(" ")) if content else cur
+ if lang == "c" and content.startswith("}"):
+ target += 4
+ if target < cur:
+ self.inp.key(*(["BackSpace"] * ((cur - target) // 4)), delay=70)
+ elif target > cur:
+ self.inp.key(*(["Tab"] * ((target - cur) // 4)), delay=70)
+ cur = target
+ if content:
+ self.type_human(content, delay=delay, punct_pause=(0.05, 0.25), hesitate=0.05, hesitate_pause=(0.3, 0.9))
+ prev_text = " " * cur + content if content else " " * cur
+ if lang == "c" and content.startswith("}"):
+ prev_text = " " * (cur - 4) + content
+ cur -= 4
+
+ def wander(self, until, region, dwell=(0.05, 0.35), seg=(120, 520)):
+ x0, y0, x1, y1 = region
+ while self.t() < until and self.left() > 0.8:
+ cx, cy = self.inp.pos()
+ ang = self.rng.uniform(0, 2 * math.pi)
+ dist = self.rng.uniform(*seg)
+ tx = min(max(cx + math.cos(ang) * dist, x0), x1)
+ ty = min(max(cy + math.sin(ang) * dist, y0), y1)
+ self.inp.move(tx, ty, curve=self.rng.uniform(-0.35, 0.35))
+ self.sleep(self.rng.uniform(*dwell))
+
+
+def css_rect(ctx, selector):
+ return ctx.js(
+ "(sel) => { const r = document.querySelector(sel).getBoundingClientRect(); return [r.left, r.top, r.width, r.height]; }",
+ selector,
+ )
+
+
+def editor_point(ctx, line_index, col=999):
+ return ctx.pt("([l, c]) => capEditor.pointFor(l, c)", [line_index, col])
+
+
+def code_editor_common(ctx, lines, line_no, typing_delay):
+ x, y = editor_point(ctx, line_no - 1)
+ ctx.move(x + 40, y)
+ ctx.sleep(0.25)
+ ctx.inp.click()
+ ctx.sleep(0.4)
+ ctx.inp.key("End")
+ ctx.sleep(0.3)
+ ctx.inp.key("Return")
+ ctx.sleep(0.25)
+ ctx.inp.key("Return")
+ ctx.sleep(0.35)
+ ctx.inp.key("BackSpace")
+ ctx.sleep(0.5)
+ ctx.move(x + 260, y + 160 * ctx.dsf, dur=0.5)
+ ctx.type_code(lines, "py", 0, delay=typing_delay)
+
+
+def sc_slow_typing(ctx):
+ ctx.at(1.0)
+ x, y = ctx.pt("capEndOfText()")
+ ctx.move(x + 3 * ctx.dsf, y)
+ ctx.sleep(0.3)
+ ctx.inp.click()
+ ctx.sleep(0.6)
+ ctx.inp.key("ctrl+End")
+ ctx.sleep(0.5)
+ ctx.move(x + 180, y + 110, dur=0.6)
+ ctx.inp.key("Return")
+ ctx.sleep(0.9)
+ ctx.type_human("Next steps: run the pilot with three teams in November and collect [[feedbak|feedback]] weekly.<p:1.6>")
+ ctx.need(6)
+ cx, cy = ctx.pt("(() => { const r = document.querySelector('.comment').getBoundingClientRect(); return [r.left + 120, r.top + 40]; })()")
+ ctx.move(cx, cy)
+ ctx.sleep(1.1)
+ ctx.inp.wheel(1)
+ ctx.sleep(1.4)
+ ctx.inp.wheel(-1)
+ ctx.sleep(0.9)
+ x, y = ctx.pt("capEndOfText()")
+ ctx.move(x + 2 * ctx.dsf, y)
+ ctx.sleep(0.25)
+ ctx.inp.click()
+ ctx.sleep(0.5)
+ ctx.move(x + 150, y + 90, dur=0.5)
+ ctx.type_human(" If it [[hods|holds]] up, we roll out in January.<p:1.2>")
+ ctx.need(3)
+ ctx.type_human(" Owner: Priya.")
+
+
+def sc_code_editor(ctx):
+ ctx.at(1.0)
+ lines = [
+ "def _normalize_ratio(ratio, lo=0.0, hi=1.0):",
+ " if hi <= lo:",
+ ' raise ValueError("hi must be greater than lo")',
+ " return min(max((ratio - lo) / (hi - lo), 0.0), 1.0)",
+ ]
+ code_editor_common(ctx, lines, 42, (55, 135))
+ ctx.sleep(0.6)
+ ctx.inp.key("ctrl+s")
+ ctx.at(max(ctx.t() + 0.8, 22.0))
+ sx, sy = ctx.pt("(() => { const r = capEditor.scroller.getBoundingClientRect(); return [r.left + r.width * 0.45, r.top + r.height * 0.5]; })()")
+ ctx.move(sx, sy)
+ ctx.sleep(0.4)
+ for n, d, pause in [(1, 0, 0.7), (1, 0, 0.6), (3, 0.045, 1.0), (5, 0.025, 1.2), (2, 0.11, 0.8)]:
+ ctx.need(pause + 0.3)
+ ctx.inp.wheel(n, delay=d)
+ ctx.sleep(pause)
+ for _ in range(3):
+ ctx.need(1.0)
+ ctx.inp.key("Next")
+ ctx.sleep(0.85)
+ ctx.need(2.0)
+ ctx.inp.key(*(["Down"] * 6), delay=95)
+ ctx.sleep(0.3)
+ ctx.inp.key(*(["Right"] * 12), delay=45)
+ ctx.sleep(0.5)
+ ctx.need(1.5)
+ ctx.inp.wheel(-4, delay=0.06)
+ ctx.sleep(0.8)
+ ctx.need(1.5)
+ tx, ty = ctx.pt("(() => { const r = capEditor.scroller.getBoundingClientRect(); return [r.left + 330, r.top + 300]; })()")
+ ctx.move(tx, ty)
+ ctx.inp.click()
+ ctx.sleep(0.7)
+ ctx.need(1.2)
+ ctx.inp.key("ctrl+Home")
+ ctx.sleep(0.6)
+ ctx.move(sx + 200, sy - 120)
+
+
+def sc_text_scroll(ctx):
+ ctx.at(1.0)
+ ctx.move(940, 520)
+ ctx.sleep(0.5)
+ for gap in (0.9, 0.7, 1.1, 1.3):
+ ctx.need(gap)
+ ctx.inp.wheel(1)
+ ctx.sleep(gap)
+ ctx.sleep(0.8)
+ ctx.inp.wheel(6, delay=0.018)
+ ctx.sleep(1.6)
+ ctx.inp.wheel(2, delay=0.07)
+ ctx.sleep(1.0)
+ link = ctx.js(
+ "(() => { for (const a of document.querySelectorAll('#content p a')) { const r = a.getBoundingClientRect(); if (r.top > 260 && r.bottom < innerHeight - 280 && r.width > 40) return [r.left + r.width / 2, r.top + r.height / 2]; } return null; })()"
+ )
+ if link:
+ ctx.move(link[0] * ctx.dsf, link[1] * ctx.dsf)
+ ctx.sleep(1.6)
+ ctx.move(link[0] * ctx.dsf + 260, link[1] * ctx.dsf - 160)
+ ctx.sleep(0.6)
+ sel = ctx.js(
+ "(() => { for (const p of document.querySelectorAll('#content p')) { const r = p.getBoundingClientRect(); if (r.top > 200 && r.top < innerHeight - 300 && r.height > 60) { const rg = document.createRange(); rg.setStart(p.firstChild, 0); rg.setEnd(p.firstChild, 1); const a = rg.getBoundingClientRect(); return [a.left + 1, a.top + a.height / 2, r.left + r.width * 0.55, a.top + a.height * 1.5 + 4]; } } return null; })()"
+ )
+ if sel:
+ ctx.need(3.5)
+ ctx.move(sel[0] * ctx.dsf, sel[1] * ctx.dsf)
+ ctx.sleep(0.3)
+ ctx.inp.press(1)
+ ctx.sleep(0.1)
+ ctx.inp.move(sel[2] * ctx.dsf, sel[1] * ctx.dsf + 2, dur=0.7, curve=0.02)
+ ctx.inp.move(sel[2] * ctx.dsf - 120, sel[3] * ctx.dsf, dur=0.35, curve=0.05)
+ ctx.inp.release(1)
+ ctx.sleep(1.3)
+ ctx.move(sel[2] * ctx.dsf + 60, sel[3] * ctx.dsf + 60, dur=0.4)
+ ctx.inp.click()
+ ctx.sleep(0.6)
+ ctx.need(6.0)
+ ctx.js(
+ "(() => { const start = scrollY, dist = 1400, dur = 4200, t0 = performance.now(); cap.event('smooth_scroll', {dist, dur}); function step(now) { const u = Math.min(1, (now - t0) / dur); const s = u < 0.5 ? 4 * u * u * u : 1 - Math.pow(-2 * u + 2, 3) / 2; scrollTo(0, Math.round(start + dist * s)); if (u < 1) requestAnimationFrame(step); } requestAnimationFrame(step); })()"
+ )
+ ctx.sleep(4.6)
+ for _ in range(2):
+ ctx.need(1.4)
+ ctx.inp.key("Next")
+ ctx.sleep(1.3)
+ ctx.need(2.0)
+ ctx.inp.wheel(-8, delay=0.015)
+ ctx.sleep(1.4)
+ for n, d, pause in [(-3, 0.12, 0.9), (2, 0.3, 1.0), (1, 0, 0.6)]:
+ ctx.need(pause + abs(n) * d + 0.2)
+ ctx.inp.wheel(n, delay=d)
+ ctx.sleep(pause)
+ ctx.need(2.0)
+ ctx.inp.wheel(10, delay=0.012)
+ ctx.sleep(1.8)
+ link = ctx.js(
+ "(() => { for (const a of document.querySelectorAll('#content a')) { const r = a.getBoundingClientRect(); if (r.top > 300 && r.bottom < innerHeight - 300 && r.width > 40 && r.left > 470) return [r.left + r.width / 2, r.top + r.height / 2]; } return null; })()"
+ )
+ if link and ctx.left() > 3:
+ ctx.move(link[0] * ctx.dsf, link[1] * ctx.dsf)
+ ctx.sleep(1.5)
+ ctx.move(link[0] * ctx.dsf - 200, link[1] * ctx.dsf + 220)
+ ctx.sleep(0.5)
+ ctx.need(1.0)
+ ctx.inp.wheel(1)
+
+
+def sc_slides(ctx):
+ ctx.at(1.0)
+ ctx.move(1700, 900, dur=0.8)
+ ctx.at(2.6)
+ k = 0
+ plan = ["Right", "Right", "space", "Right", "click", "Right", "Left", "Right", "Right", "Right", "Right", "Right", "Right", "Right", "Right", "Right"]
+ next_t = 2.6
+ for action in plan:
+ ctx.at(next_t)
+ if ctx.left() < 0.9:
+ break
+ if action == "click":
+ ctx.inp.click()
+ else:
+ ctx.inp.key(action)
+ k += 1
+ if k == 3:
+ ctx.sleep(0.6)
+ ctx.move(820, 560, dur=0.9)
+ ctx.sleep(0.5)
+ ctx.move(1180, 470, dur=0.7)
+ if k == 9:
+ ctx.sleep(0.8)
+ ctx.move(1500, 860, dur=0.8)
+ next_t += ctx.rng.uniform(2.6, 3.3) if action != "Left" else 1.1
+
+
+def sc_busy_ui(ctx, long=True):
+ def find(what):
+ return ctx.js("(w) => capFind(w)", what)
+
+ def go(what, dx=0, dy=0, dur=None):
+ r = find(what)
+ if r is None:
+ raise RuntimeError(f"capFind({what}) returned null")
+ ctx.move((r[0] + dx) * ctx.dsf, (r[1] + dy) * ctx.dsf, dur=dur, curve=ctx.rng.uniform(-0.3, 0.3))
+ return r
+
+ backlog = ctx.js("capCardsIn('backlog')")
+ todo = ctx.js("capCardsIn('todo')")
+ review = ctx.js("capCardsIn('review')")
+ ctx.at(0.8)
+ for cid in backlog[: 3 if long else 1]:
+ go(f"card:{cid}", ctx.rng.uniform(-60, 60), ctx.rng.uniform(-15, 15))
+ ctx.sleep(ctx.rng.uniform(0.1, 0.3))
+ go("btn-filter")
+ ctx.sleep(0.7 if long else 0.4)
+ ctx.inp.click()
+ ctx.sleep(0.35)
+ for i in (0, 1, 2, 3, 2) if long else (0, 1, 2):
+ go(f"menuitem:{i}", ctx.rng.uniform(-30, 30))
+ ctx.sleep(ctx.rng.uniform(0.1, 0.25))
+ ctx.inp.click()
+ ctx.sleep(0.3)
+ go(f"card:{todo[1]}", 40, -10)
+ ctx.sleep(0.25)
+ go(f"more:{todo[1]}")
+ ctx.sleep(0.3)
+ ctx.inp.click()
+ ctx.sleep(0.3)
+ for i in (0, 1, 2, 4, 3) if long else (0, 2, 1):
+ go(f"menuitem:{i}", ctx.rng.uniform(-30, 30))
+ ctx.sleep(ctx.rng.uniform(0.08, 0.22))
+ ctx.inp.key("Escape")
+ ctx.sleep(0.15)
+ go(f"card:{backlog[1]}", -40, 0)
+ ctx.sleep(0.2)
+ target = find("col:progress")
+ ctx.inp.drag(target[0] * ctx.dsf, (target[1] - target[3] / 2 + 150) * ctx.dsf, dur=1.1)
+ ctx.sleep(0.4)
+ if not long:
+ go(f"card:{backlog[4]}", 30, 10)
+ ctx.inp.wheel(3, delay=0.09)
+ ctx.sleep(0.5)
+ ctx.wander(ctx.t() + 0.8, (290, 200, 560, 1000), seg=(60, 200))
+ ctx.inp.wheel(-2, delay=0.12)
+ ctx.sleep(0.3)
+ prog = ctx.js("capCardsIn('progress')")
+ for cid in prog[1:4]:
+ go(f"card:{cid}", ctx.rng.uniform(-70, 70), ctx.rng.uniform(-12, 12))
+ ctx.sleep(ctx.rng.uniform(0.08, 0.25))
+ go(f"card:{prog[2]}", -30, 4)
+ ctx.sleep(0.2)
+ ctx.inp.click()
+ ctx.sleep(0.5)
+ for i in (0, 1, 2, 3, 4, 2) if long else (0, 1, 2):
+ go(f"prop:{i}", ctx.rng.uniform(-40, 60))
+ ctx.sleep(ctx.rng.uniform(0.1, 0.3))
+ ctx.inp.key("Escape")
+ ctx.sleep(0.2)
+ if not long:
+ ctx.wander(ctx.duration, (300, 150, 1800, 1000))
+ return
+ go(f"card:{backlog[5]}", 30, 10)
+ ctx.sleep(0.2)
+ ctx.inp.wheel(3, delay=0.09)
+ ctx.sleep(0.5)
+ ctx.wander(ctx.t() + 1.2, (290, 200, 560, 1000), seg=(60, 200))
+ ctx.inp.wheel(-2, delay=0.14)
+ ctx.sleep(0.4)
+ todo = ctx.js("capCardsIn('todo')")
+ go(f"card:{todo[2]}", -20, 0)
+ ctx.sleep(0.2)
+ target = find("col:review")
+ ctx.inp.drag(target[0] * ctx.dsf, (target[1] - target[3] / 2 + 230) * ctx.dsf, dur=1.2)
+ ctx.sleep(0.4)
+ go("colhead:review", 40, 0)
+ ctx.sleep(0.2)
+ ctx.inp.wheel(3, delay=0.1, horizontal=True)
+ ctx.sleep(0.8)
+ ctx.wander(ctx.t() + 1.0, (700, 200, 1800, 900))
+ ctx.inp.wheel(-3, delay=0.12, horizontal=True)
+ ctx.sleep(0.4)
+ for k in ("team-issues", "team-cycles", "team-projects", "team-views", "nav-my", "nav-inbox"):
+ if find(k):
+ go(k, ctx.rng.uniform(-30, 40))
+ ctx.sleep(ctx.rng.uniform(0.08, 0.2))
+ if find("team-views"):
+ go("team-views")
+ ctx.inp.click()
+ ctx.sleep(0.4)
+ go("btn-display")
+ ctx.sleep(0.6)
+ ctx.inp.click()
+ ctx.sleep(0.3)
+ for i in (0, 1, 2, 1):
+ go(f"menuitem:{i}", ctx.rng.uniform(-30, 30))
+ ctx.sleep(ctx.rng.uniform(0.1, 0.25))
+ ctx.inp.key("Escape")
+ review = ctx.js("capCardsIn('review')")
+ go(f"card:{review[0]}", -10, 0)
+ ctx.sleep(0.15)
+ target = find("col:done")
+ ctx.inp.drag(target[0] * ctx.dsf, (target[1] - target[3] / 2 + 90) * ctx.dsf, dur=1.0)
+ ctx.sleep(0.3)
+ for k in ("btn-share", "btn-bell", "btn-new", "view-list", "view-board"):
+ if ctx.left() < 1.2:
+ break
+ if find(k):
+ go(k)
+ ctx.sleep(0.6)
+ ctx.wander(ctx.duration, (300, 150, 1800, 1000))
+
+
+def sc_busy_ui_60(ctx):
+ sc_busy_ui(ctx, long=False)
+
+
+def sc_dashboard(ctx):
+ ctx.at(1.2)
+
+ def rect(sel):
+ return css_rect(ctx, sel)
+
+ c = rect(".chart canvas")
+ ctx.move(c[0] + 90, c[1] + c[3] * 0.45)
+ ctx.sleep(0.3)
+ steps = 28
+ for i in range(steps):
+ ctx.inp.move(c[0] + 90 + (c[2] - 140) * (i + 1) / steps, c[1] + c[3] * (0.45 + 0.08 * math.sin(i / 4)), dur=0.17, curve=0, log=False)
+ ctx.inp.log("sweep", what="rps chart")
+ ctx.sleep(0.6)
+ t = rect(".tbl tbody")
+ ctx.move(t[0] + 260, t[1] + 12)
+ for i in range(1, 9):
+ ctx.inp.move(t[0] + 260 + ctx.rng.uniform(-20, 40), t[1] + 12 + i * 24, dur=0.35, curve=0.05, log=False)
+ ctx.sleep(ctx.rng.uniform(0.15, 0.45))
+ ctx.inp.log("sweep", what="table rows")
+ ctx.move(t[0] + 900, t[1] + 300)
+ ctx.at(max(ctx.t(), 17.5))
+ lc = rect(".chart.r canvas")
+ ctx.move(lc[0] + lc[2] - 30, lc[1] + lc[3] * 0.5)
+ for i in range(22):
+ ctx.inp.move(lc[0] + lc[2] - 30 - (lc[2] - 100) * (i + 1) / 22, lc[1] + lc[3] * (0.5 - 0.1 * math.sin(i / 3)), dur=0.18, curve=0, log=False)
+ ctx.inp.log("sweep", what="latency chart")
+ ctx.sleep(0.4)
+ k = rect(".kpi")
+ ctx.move(k[0] + 80, k[1] + 50)
+ ctx.sleep(0.8)
+ ctx.move(k[0] + k[2] * 2.2, k[1] + 45)
+ ctx.sleep(0.8)
+ ctx.move(1000, 640)
+ ctx.at(max(ctx.t(), 31.0))
+ f = rect(".feed")
+ ctx.move(f[0] + 200, f[1] + 80)
+ ctx.sleep(1.0)
+ ctx.move(f[0] + 230, f[1] + 160, dur=0.9)
+ ctx.sleep(0.8)
+ r = rect("#range")
+ ctx.move(r[0] + r[2] / 2, r[1] + r[3] / 2)
+ ctx.sleep(1.0)
+ ctx.move(r[0] - 260, r[1] + 300)
+
+
+def sc_dark_mode(ctx):
+ ctx.at(1.2)
+ tr = ctx.js("(() => { const r = capTerm.scroller.getBoundingClientRect(); return [r.left, r.top, r.width, r.height]; })()")
+ ctx.move(tr[0] + 520, tr[1] + tr[3] - 60)
+ ctx.sleep(0.6)
+ ctx.inp.click()
+ ctx.at(4.5)
+ ctx.inp.key("ctrl+c")
+ ctx.sleep(1.0)
+ ctx.type_human("git status", delay=(70, 140), hesitate=0)
+ ctx.sleep(0.3)
+ ctx.inp.key("Return")
+ ctx.sleep(2.0)
+ ctx.type_human("make test", delay=(70, 140), hesitate=0)
+ ctx.sleep(0.25)
+ ctx.inp.key("Return")
+ ctx.sleep(1.5)
+ ex = editor_point(ctx, 124)
+ ctx.move(ex[0] + 60, ex[1])
+ ctx.sleep(4.0)
+ ctx.inp.click()
+ ctx.sleep(0.4)
+ ctx.inp.key("End")
+ ctx.sleep(0.3)
+ ctx.inp.key("Return")
+ ctx.sleep(0.4)
+ ctx.type_human("state->wsize = 0; /* force window reallocation */", delay=(60, 130), hesitate=0.04)
+ ctx.sleep(0.6)
+ ctx.inp.key("ctrl+s")
+ ctx.sleep(0.6)
+ er = ctx.js("(() => { const r = capEditor.scroller.getBoundingClientRect(); return [r.left, r.top, r.width, r.height]; })()")
+ ctx.move(er[0] + er[2] * 0.5, er[1] + er[3] * 0.4)
+ ctx.inp.wheel(3, delay=0.09)
+ ctx.sleep(0.9)
+ ctx.inp.wheel(-2, delay=0.12)
+ ctx.sleep(0.7)
+ ctx.need(6)
+ ctx.move(tr[0] + 600, tr[1] + tr[3] - 50)
+ ctx.inp.click()
+ ctx.sleep(0.5)
+ ctx.type_human("./fuzz_inflate -max_len=4096 corpus/", delay=(55, 120), hesitate=0)
+ ctx.sleep(0.4)
+ ctx.inp.key("Return")
+ ctx.sleep(1.0)
+ ctx.move(tr[0] + 1100, tr[1] - 140, dur=0.9)
+
+
+def sc_idle(ctx):
+ ctx.at(0.8)
+ ctx.js("capStart([10000, 28500, 45000])")
+ for when, (x, y) in [(6.0, (1010, 560)), (19.5, (1180, 640)), (34.0, (930, 470)), (51.0, (1250, 820))]:
+ ctx.at(when)
+ ctx.move(x, y, dur=ctx.rng.uniform(0.7, 1.1))
+
+
+def sc_webcam(ctx):
+ def bubble():
+ r = ctx.js("capWebcamRect()")
+ return r[0] + r[2] / 2, r[1] + r[3] / 2
+
+ ctx.at(1.2)
+ bx, by = bubble()
+ ctx.move(bx + 20, by - 10)
+ ctx.sleep(0.4)
+ ctx.inp.drag(1920 - 72 - 160 + 20, by - 10, dur=1.3)
+ ctx.sleep(0.5)
+ ctx.move(1000, 600)
+ plan = [
+ (6.0, "key"),
+ (10.0, "key"),
+ (13.0, ("drag", (1920 - 72 - 160, 72 + 160))),
+ (17.5, "key"),
+ (21.0, "key"),
+ (24.0, ("drag", (72 + 160, 1080 - 72 - 160))),
+ (28.5, "key"),
+ (32.0, "key"),
+ (35.0, ("drag", (72 + 160 + 40, 1080 - 72 - 160 - 300))),
+ ]
+ for when, action in plan:
+ ctx.at(when)
+ if ctx.left() < 1.0:
+ break
+ if action == "key":
+ ctx.inp.key("Right")
+ continue
+ bx, by = bubble()
+ ctx.move(bx + ctx.rng.uniform(-30, 30), by + ctx.rng.uniform(-30, 30))
+ ctx.sleep(0.3)
+ tx, ty = action[1]
+ ctx.inp.drag(tx, ty, dur=ctx.rng.uniform(1.0, 1.4))
+ ctx.sleep(0.4)
+ ctx.move(ctx.rng.uniform(700, 1300), ctx.rng.uniform(400, 700))
+
+
+def sc_code_4k(ctx):
+ ctx.at(1.0)
+ lines = [
+ "def _normalize_ratio(ratio, lo=0.0, hi=1.0):",
+ " span = hi - lo",
+ " return min(max((ratio - lo) / span, 0.0), 1.0)",
+ ]
+ code_editor_common(ctx, lines, 42, (45, 110))
+ ctx.sleep(0.5)
+ ctx.inp.key("ctrl+s")
+ ctx.sleep(0.5)
+ sx, sy = ctx.pt("(() => { const r = capEditor.scroller.getBoundingClientRect(); return [r.left + r.width * 0.45, r.top + r.height * 0.5]; })()")
+ ctx.move(sx, sy)
+ for n, d, pause in [(1, 0, 0.6), (3, 0.05, 0.8), (5, 0.025, 0.9)]:
+ ctx.need(pause + 0.3)
+ ctx.inp.wheel(n, delay=d)
+ ctx.sleep(pause)
+ for _ in range(2):
+ ctx.need(0.9)
+ ctx.inp.key("Next")
+ ctx.sleep(0.7)
+ ctx.need(1.4)
+ ctx.inp.key(*(["Down"] * 5), delay=90)
+ ctx.inp.key(*(["Right"] * 8), delay=45)
+ ctx.sleep(0.4)
+ ctx.need(1.0)
+ ctx.inp.wheel(-4, delay=0.06)
+
+
+def sc_full_motion(ctx):
+ for sec in [*range(0, ctx.duration, 5), ctx.duration - ctx.end_margin]:
+ ctx.at(sec)
+ ctx.log("video_stats", **ctx.js("capStats()"))
+
+
+SCENARIOS = {
+ "slow_typing": sc_slow_typing,
+ "code_editor": sc_code_editor,
+ "text_scroll": sc_text_scroll,
+ "slides": sc_slides,
+ "busy_ui": sc_busy_ui,
+ "dashboard": sc_dashboard,
+ "dark_mode": sc_dark_mode,
+ "idle": sc_idle,
+ "webcam_overlay": sc_webcam,
+ "busy_ui_60fps": sc_busy_ui_60,
+ "code_4k": sc_code_4k,
+ "full_motion": sc_full_motion,
+}
diff --git a/capcodec/bench/corpus/sideinfo.py b/capcodec/bench/corpus/sideinfo.py
new file mode 100644
index 000000000..1056ee6c0
--- /dev/null
+++ b/capcodec/bench/corpus/sideinfo.py
@@ -0,0 +1,539 @@
+#!/usr/bin/env python3
+"""Compute per-frame side info for a lossless capture.
+
+Output: one JSON object per frame
+ {"frame": i, "t_ms": float, "dirty": [[x,y,w,h],...], "cursor": [x,y] | null,
+ "scroll": [{"rect": [x,y,w,h], "dx": int, "dy": int, "id": str, "valid": bool | null,
+ "align": "latency" | "realigned", "match": float | null}, ...]}
+
+dirty exact pixel diff vs. the previous decoded frame (frame 0: whole frame),
+ marked on a 16x16 tile grid, merged into horizontal runs per tile row and
+ then vertically when consecutive rows have a run with the same x-extent.
+ Rects are 16-aligned and clipped to the frame.
+cursor pointer position (hotspot, screen px) of the latest 240 Hz sample taken
+ at or before T_frame + C. x11grab paints the cursor after grabbing the
+ image, just before the wallclock pts is taken, so C is fitted per clip in
+ [-12, +12] ms by requiring the hotspot tile to be dirty at both the old and
+ the new position on every frame where the pointer moved.
+scroll per tracked scroll container whose offset changed since the previous
+ frame: content moved by (dx, dy) screen px inside rect (dy < 0 when the
+ content moves up). Offsets are page-reported scrollLeft/scrollTop
+ (scroll events + every rAF) x device scale factor. valid is null when the
+ jump is larger than the container (no overlapping pixels to compare).
+
+Scroll alignment: pass 1 fits one global report-to-screen latency L by
+validating every candidate L against the pixels. Pass 2 walks the frames in
+order and, per container, takes the offset reported at T_frame - L when the
+pixels confirm it ("latency"); otherwise it may pick another reported offset
+within +-1 frame of that instant if the pixels confirm that one ("realigned"),
+or keep the previous offset if the container did not change on screen yet.
+Entries that no candidate explains keep the latency-based value, valid=false.
+
+Usable as a module (compute()) or from the command line.
+"""
+
+import argparse
+import bisect
+import json
+import subprocess
+import sys
+
+import numpy as np
+
+TILE = 16
+MATCH_THRESHOLD = 0.9
+RESIDUAL_MAX = 0.25
+HELD_THRESHOLD = 0.998
+CURSOR_FIT_MS = (-12, 12)
+
+
+def read_jsonl(path):
+ out = []
+ with open(path) as f:
+ for line in f:
+ line = line.strip()
+ if line:
+ out.append(json.loads(line))
+ return out
+
+
+def iter_frames(ffmpeg, video, width, height):
+ size = width * height * 4
+ proc = subprocess.Popen(
+ [ffmpeg, "-v", "error", "-nostdin", "-i", video, "-map", "0:v:0", "-f", "rawvideo", "-pix_fmt", "bgr0", "-"],
+ stdout=subprocess.PIPE,
+ bufsize=0,
+ )
+ bufs = [bytearray(size), bytearray(size)]
+ k = 0
+ complete = False
+ try:
+ while True:
+ buf = bufs[k]
+ view = memoryview(buf)
+ got = 0
+ while got < size:
+ n = proc.stdout.readinto(view[got:])
+ if not n:
+ break
+ got += n
+ if got < size:
+ complete = True
+ break
+ yield np.frombuffer(buf, dtype=np.uint32).reshape(height, width)
+ k ^= 1
+ finally:
+ proc.stdout.close()
+ rc = proc.wait()
+ if complete and rc != 0:
+ raise RuntimeError(f"ffmpeg decode of {video} failed with exit code {rc}")
+
+
+def tile_mask(diff, th, tw):
+ h, w = diff.shape
+ if h != th * TILE or w != tw * TILE:
+ padded = np.zeros((th * TILE, tw * TILE), dtype=bool)
+ padded[:h, :w] = diff
+ diff = padded
+ return diff.reshape(th, TILE, tw, TILE).any(axis=(1, 3))
+
+
+def rects_from_tiles(mask, width, height):
+ th, tw = mask.shape
+ active = {}
+ out = []
+
+ def emit(key, y0, y1):
+ x0, x1 = key
+ x = x0 * TILE
+ y = y0 * TILE
+ out.append([x, y, min(x1 * TILE, width) - x, min(y1 * TILE, height) - y])
+
+ for r in range(th + 1):
+ runs = set()
+ if r < th and mask[r].any():
+ d = np.diff(np.concatenate(([0], mask[r].astype(np.int8), [0])))
+ runs = set(zip(np.flatnonzero(d == 1).tolist(), np.flatnonzero(d == -1).tolist()))
+ for key in [k for k in active if k not in runs]:
+ emit(key, active.pop(key), r)
+ for key in runs:
+ if key not in active:
+ active[key] = r
+ out.sort(key=lambda q: (q[1], q[0]))
+ return out
+
+
+def clip_rect(rect, width, height):
+ x, y, w, h = rect
+ x0, y0 = max(0, x), max(0, y)
+ x1, y1 = min(width, x + w), min(height, y + h)
+ if x1 <= x0 or y1 <= y0:
+ return None
+ return [x0, y0, x1 - x0, y1 - y0]
+
+
+class ScrollTrack:
+ def __init__(self, records, dsf):
+ self.dsf = dsf
+ self.ts = [r["_t"] for r in records]
+ self.recs = records
+
+ def index_at(self, t):
+ return bisect.bisect_right(self.ts, t) - 1
+
+ def state_at(self, t):
+ i = self.index_at(t)
+ return self.recs[i] if i >= 0 else None
+
+ def offset(self, rec):
+ return round(rec["sx"] * self.dsf), round(rec["sy"] * self.dsf)
+
+ def rect(self, rec, width, height):
+ x, y, w, h = rec["rect"]
+ d = self.dsf
+ return clip_rect([round(x * d), round(y * d), round(w * d), round(h * d)], width, height)
+
+
+def shift_match(prev, cur, rect, dx, dy, mask_boxes):
+ x, y, w, h = rect
+ cx0, cx1 = max(x, x + dx), min(x + w, x + w + dx)
+ cy0, cy1 = max(y, y + dy), min(y + h, y + h + dy)
+ if cx1 - cx0 < 8 or cy1 - cy0 < 4:
+ return None
+ a = cur[cy0:cy1, cx0:cx1]
+ b = prev[cy0 - dy : cy1 - dy, cx0 - dx : cx1 - dx]
+ z = prev[cy0:cy1, cx0:cx1]
+ keep = np.ones(a.shape, dtype=bool)
+ for bx0, by0, bx1, by1 in mask_boxes:
+ ix0, iy0 = max(bx0, cx0) - cx0, max(by0, cy0) - cy0
+ ix1, iy1 = min(bx1, cx1) - cx0, min(by1, cy1) - cy0
+ if ix1 > ix0 and iy1 > iy0:
+ keep[iy0:iy1, ix0:ix1] = False
+ n = int(keep.sum())
+ if n == 0:
+ return None
+ m_shift = float(np.count_nonzero((a == b) & keep)) / n
+ m_zero = float(np.count_nonzero((a == z) & keep)) / n
+ return [round(m_shift, 6), round(m_zero, 6), (cx1 - cx0) * (cy1 - cy0)]
+
+
+def is_valid(res):
+ """Shifted previous frame matches the overlap and explains most of the change.
+
+ res = [match_with_shift, match_without_shift, overlap_px]. On mostly-uniform
+ content a shift that is off by 1px still matches ~95% of pixels, so besides
+ the absolute threshold the shift must remove >= 75% of the mismatches of the
+ unshifted comparison.
+ """
+ if res is None:
+ return False
+ m_shift, m_zero = res[0], res[1]
+ if m_shift < MATCH_THRESHOLD:
+ return False
+ return (1.0 - m_shift) <= RESIDUAL_MAX * (1.0 - m_zero) or m_shift >= 0.9995
+
+
+def compute(
+ video,
+ frame_times_ms,
+ width,
+ height,
+ dsf,
+ pointer_samples,
+ scroll_records,
+ out_path,
+ ffmpeg="ffmpeg",
+ grab_latency_ms=0.0,
+ latency_range_ms=(-70, 70),
+ latency_step_ms=2,
+ cursor_box=None,
+):
+ n_frames = len(frame_times_ms)
+ th = (height + TILE - 1) // TILE
+ tw = (width + TILE - 1) // TILE
+ box = cursor_box or (34 if dsf <= 1 else 60)
+ frame_dur = (frame_times_ms[-1] - frame_times_ms[0]) / max(1, n_frames - 1)
+
+ ptr = sorted(((p["t"], p["x"], p["y"]) for p in pointer_samples), key=lambda q: q[0])
+ ptr_t = [p[0] for p in ptr]
+
+ def cursor_at(t):
+ i = bisect.bisect_right(ptr_t, t) - 1
+ if i < 0:
+ return None
+ _, x, y = ptr[i]
+ if 0 <= x < width and 0 <= y < height:
+ return [x, y]
+ return None
+
+ cursors = [cursor_at(t) for t in frame_times_ms]
+
+ by_id = {}
+ for r in scroll_records:
+ r = dict(r)
+ r["_t"] = r.get("tp", r["t"])
+ by_id.setdefault(r["id"], []).append(r)
+ tracks = {}
+ for sid, recs in sorted(by_id.items()):
+ recs.sort(key=lambda q: q["_t"])
+ tracks[sid] = ScrollTrack(recs, dsf)
+
+ def boxes_for(i, dx, dy):
+ out = []
+ for c, off in ((cursors[i], (0, 0)), (cursors[i - 1], (0, 0)), (cursors[i - 1], (dx, dy))):
+ if c is not None:
+ cx, cy = c[0] + off[0], c[1] + off[1]
+ out.append((cx - box, cy - box, cx + box, cy + box))
+ return out
+
+ latencies = list(range(latency_range_ms[0], latency_range_ms[1] + 1, latency_step_ms))
+
+ def deltas_for(lat):
+ per_frame = [[] for _ in range(n_frames)]
+ for sid, tr in tracks.items():
+ prev_rec = tr.state_at(frame_times_ms[0] - lat)
+ for i in range(1, n_frames):
+ rec = tr.state_at(frame_times_ms[i] - lat)
+ if rec is not None and prev_rec is not None:
+ ox0, oy0 = tr.offset(prev_rec)
+ ox1, oy1 = tr.offset(rec)
+ if (ox0, oy0) != (ox1, oy1):
+ rect = tr.rect(rec, width, height)
+ if rect is not None:
+ per_frame[i].append((sid, tuple(rect), -(ox1 - ox0), -(oy1 - oy0)))
+ prev_rec = rec
+ return per_frame
+
+ by_latency = {lat: deltas_for(lat) for lat in latencies}
+ candidates = [set() for _ in range(n_frames)]
+ for per_frame in by_latency.values():
+ for i, items in enumerate(per_frame):
+ candidates[i].update(items)
+
+ results = {}
+ tiles = np.zeros((n_frames, th, tw), dtype=bool)
+ dirty = []
+ identical = 0
+ prev = None
+ decoded = 0
+ for i, cur in enumerate(iter_frames(ffmpeg, video, width, height)):
+ decoded += 1
+ if i >= n_frames:
+ continue
+ if prev is None:
+ tiles[i] = True
+ dirty.append([[0, 0, width, height]])
+ else:
+ mask = tile_mask(cur != prev, th, tw)
+ tiles[i] = mask
+ if not mask.any():
+ identical += 1
+ dirty.append([])
+ else:
+ dirty.append(rects_from_tiles(mask, width, height))
+ for cand in candidates[i]:
+ sid, rect, dx, dy = cand
+ results[(i, cand)] = shift_match(prev, cur, rect, dx, dy, boxes_for(i, dx, dy))
+ prev = cur
+ if decoded != n_frames:
+ raise RuntimeError(f"decoded {decoded} frames but capture log lists {n_frames}")
+
+ def cursor_consistency(offset_ms):
+ cur = [cursor_at(t + offset_ms) for t in frame_times_ms]
+ moved = consistent = 0
+ for i in range(1, n_frames):
+ a, b = cur[i - 1], cur[i]
+ if a is None or b is None or a == b:
+ continue
+ moved += 1
+ consistent += bool(tiles[i, a[1] // TILE, a[0] // TILE] and tiles[i, b[1] // TILE, b[0] // TILE])
+ return consistent, moved, cur
+
+ cursor_fit = {}
+ for off in range(CURSOR_FIT_MS[0], CURSOR_FIT_MS[1] + 1):
+ c, m, _ = cursor_consistency(off)
+ cursor_fit[off] = (c, m)
+ cursor_frac = {off: round(c / m, 6) if m else 0.0 for off, (c, m) in cursor_fit.items()}
+ best_frac = max(cursor_frac.values())
+ cursor_plateau = [off for off, f in cursor_frac.items() if f == best_frac]
+ cursor_offset = cursor_plateau[len(cursor_plateau) // 2] if best_frac else 0
+ _, _, cursors = cursor_consistency(cursor_offset)
+
+ def score(lat):
+ good = bad = 0
+ for i, items in enumerate(by_latency[lat]):
+ for cand in items:
+ if is_valid(results.get((i, cand))):
+ good += 1
+ else:
+ bad += 1
+ return good - bad, good, bad
+
+ scores = {lat: score(lat) for lat in latencies}
+ has_scroll = any(s[1] + s[2] for s in scores.values())
+ chosen_lat = 0
+ if has_scroll:
+ best = max(s[0] for s in scores.values())
+ plateau = [lat for lat in latencies if scores[lat][0] == best]
+ chosen_lat = plateau[len(plateau) // 2]
+
+ entries = [[] for _ in range(n_frames)]
+ align_counts = {"latency": 0, "realigned": 0, "held": 0, "invalid": 0, "unverifiable": 0}
+ if has_scroll:
+ window = frame_dur
+ plans = {}
+ for sid, tr in tracks.items():
+ plan = []
+ for t in frame_times_ms:
+ tt = t - chosen_lat
+ plan.append((tr.index_at(tt), bisect.bisect_left(tr.ts, tt - window), bisect.bisect_right(tr.ts, tt + window)))
+ plans[sid] = plan
+ chosen = {sid: plans[sid][0][0] for sid in tracks}
+ prev = None
+ for i, cur in enumerate(iter_frames(ffmpeg, video, width, height)):
+ if i >= n_frames:
+ continue
+ if prev is None:
+ prev = cur
+ continue
+ for sid, tr in tracks.items():
+ c = chosen[sid]
+ g, lo, hi = plans[sid][i]
+ if c < 0:
+ chosen[sid] = g
+ continue
+ off_c = tr.offset(tr.recs[c])
+ pool = set(range(max(lo, c), hi))
+ if g >= c:
+ pool.add(g)
+ cands = {}
+ for idx in pool:
+ off = tr.offset(tr.recs[idx])
+ if off != off_c and (off not in cands or abs(idx - g) < abs(cands[off] - g)):
+ cands[off] = idx
+ if not cands:
+ if g > c:
+ chosen[sid] = g
+ continue
+ g_off = tr.offset(tr.recs[g]) if g >= c else off_c
+ rect = tr.rect(tr.recs[max(g, c)], width, height)
+ if rect is None:
+ chosen[sid] = max(g, c)
+ continue
+ res = {}
+ for off, idx in cands.items():
+ dx, dy = -(off[0] - off_c[0]), -(off[1] - off_c[1])
+ res[off] = (idx, dx, dy, shift_match(prev, cur, rect, dx, dy, boxes_for(i, dx, dy)))
+ ref = res.get(g_off) or next(iter(res.values()))
+ m_zero = ref[3][1] if ref[3] is not None else None
+ if g_off != off_c and is_valid(res[g_off][3]):
+ pick, status = res[g_off], "latency"
+ elif m_zero is not None and m_zero >= HELD_THRESHOLD:
+ pick, status = None, ("held" if g_off != off_c else None)
+ else:
+ ok = [r for r in res.values() if is_valid(r[3])]
+ if ok:
+ pick, status = max(ok, key=lambda r: r[3][0]), "realigned"
+ elif g_off != off_c and res[g_off][3] is None:
+ pick, status = res[g_off], "unverifiable"
+ elif g_off != off_c:
+ pick, status = res[g_off], "invalid"
+ else:
+ pick, status = None, None
+ if status:
+ align_counts[status] += 1
+ if pick is None:
+ continue
+ idx, dx, dy, r = pick
+ chosen[sid] = idx
+ entries[i].append(
+ {
+ "rect": list(rect),
+ "dx": dx,
+ "dy": dy,
+ "id": sid,
+ "valid": None if status == "unverifiable" else status != "invalid",
+ "align": "realigned" if status == "realigned" else "latency",
+ "match": r[0] if r else None,
+ }
+ )
+ prev = cur
+
+ tile_area = np.full((th, tw), TILE * TILE, dtype=np.int64)
+ if height % TILE:
+ tile_area[-1, :] = (height % TILE) * TILE
+ if width % TILE:
+ tile_area[:, -1] = tile_area[:, -1] // TILE * (width % TILE)
+ dirty_frac = [(tile_area * tiles[i]).sum() / (width * height) for i in range(n_frames)]
+
+ consistent, moved = cursor_fit[cursor_offset]
+ consistent_at_zero, moved_at_zero = cursor_fit.get(0, (0, 0))
+
+ scroll_frames = valid_frames = unverifiable_frames = 0
+ n_entries = n_valid = n_unverifiable = 0
+ with open(out_path, "w") as f:
+ for i in range(n_frames):
+ scroll = entries[i]
+ if scroll:
+ scroll_frames += 1
+ verdicts = [e["valid"] for e in scroll if e["valid"] is not None]
+ if not verdicts:
+ unverifiable_frames += 1
+ elif all(verdicts):
+ valid_frames += 1
+ n_entries += len(scroll)
+ n_valid += sum(e["valid"] is True for e in scroll)
+ n_unverifiable += sum(e["valid"] is None for e in scroll)
+ rec = {
+ "frame": i,
+ "t_ms": round(frame_times_ms[i] - frame_times_ms[0], 3),
+ "dirty": dirty[i],
+ "cursor": cursors[i],
+ "scroll": scroll,
+ }
+ f.write(json.dumps(rec, separators=(",", ":")) + "\n")
+
+ lat_frames = by_latency[chosen_lat] if has_scroll else [[] for _ in range(n_frames)]
+ lat_verifiable = [
+ (i, [c for c in items if results.get((i, c)) is not None]) for i, items in enumerate(lat_frames) if items
+ ]
+ lat_scroll_frames = sum(1 for _, items in lat_verifiable if items)
+ lat_valid_frames = sum(1 for i, items in lat_verifiable if items and all(is_valid(results[(i, c)]) for c in items))
+ later = dirty_frac[1:] if n_frames > 1 else dirty_frac
+ return {
+ "frames": n_frames,
+ "avg_dirty_fraction": round(float(np.mean(later)), 6),
+ "median_dirty_fraction": round(float(np.median(later)), 6),
+ "max_dirty_fraction": round(float(np.max(later)), 6),
+ "identical_frames": identical,
+ "cursor": {
+ "frames_with_cursor": sum(c is not None for c in cursors),
+ "moved_frames": moved,
+ "moved_frames_with_dirty_hotspot_tile_at_old_and_new_pos": consistent,
+ "fraction": round(consistent / moved, 4) if moved else None,
+ "sample_offset_ms": cursor_offset,
+ "fraction_at_zero_offset": round(consistent_at_zero / moved_at_zero, 4) if moved_at_zero else None,
+ "grab_latency_ms": grab_latency_ms,
+ "method": "latest 240 Hz query_pointer sample at or before frame wallclock + sample_offset_ms; offset "
+ f"fitted in [{CURSOR_FIT_MS[0]}, {CURSOR_FIT_MS[1]}] ms (1 ms steps) to maximise frames whose hotspot "
+ "tile is dirty at both the previous and the new position",
+ },
+ "scroll": {
+ "frames_with_scroll": scroll_frames,
+ "unverifiable_frames": unverifiable_frames,
+ "validated_frames": valid_frames,
+ "fraction": round(valid_frames / (scroll_frames - unverifiable_frames), 4)
+ if scroll_frames > unverifiable_frames
+ else None,
+ "entries": n_entries,
+ "valid_entries": n_valid,
+ "unverifiable_entries": n_unverifiable,
+ "align_counts": align_counts,
+ "latency_ms": chosen_lat if has_scroll else None,
+ "latency_frames": round(chosen_lat / frame_dur, 2) if has_scroll else None,
+ "latency_only": {
+ "frames_with_scroll": lat_scroll_frames,
+ "validated_frames": lat_valid_frames,
+ "fraction": round(lat_valid_frames / lat_scroll_frames, 4) if lat_scroll_frames else None,
+ "score_at_chosen_latency": list(scores[chosen_lat]) if has_scroll else None,
+ "score_at_zero_latency": list(scores[0]) if has_scroll and 0 in scores else None,
+ },
+ "match_threshold": MATCH_THRESHOLD,
+ "residual_max": RESIDUAL_MAX,
+ },
+ }
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--video", required=True)
+ ap.add_argument("--capture", required=True, help="<name>.capture.json written by generate.py")
+ ap.add_argument("--events", required=True, help="<name>.events.jsonl (scroll records)")
+ ap.add_argument("--pointer", required=True, help="<name>.pointer.jsonl (240 Hz samples)")
+ ap.add_argument("--out", required=True)
+ ap.add_argument("--ffmpeg", default="ffmpeg")
+ ap.add_argument("--stats", help="write summary stats JSON here")
+ args = ap.parse_args()
+ cap = json.load(open(args.capture))
+ scroll = [e for e in read_jsonl(args.events) if e.get("k") == "scroll"]
+ stats = compute(
+ args.video,
+ cap["frame_wallclock_ms"],
+ cap["width"],
+ cap["height"],
+ cap["dsf"],
+ read_jsonl(args.pointer),
+ scroll,
+ args.out,
+ ffmpeg=args.ffmpeg,
+ grab_latency_ms=cap.get("grab_latency_ms", 0.0),
+ )
+ text = json.dumps(stats, indent=2)
+ if args.stats:
+ with open(args.stats, "w") as f:
+ f.write(text + "\n")
+ print(text)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/capcodec/bench/harness/adapters/__init__.py b/capcodec/bench/harness/adapters/__init__.py
new file mode 100644
index 000000000..2d83ff02b
--- /dev/null
+++ b/capcodec/bench/harness/adapters/__init__.py
@@ -0,0 +1,51 @@
+import os
+import shlex
+
+from .base import Adapter
+from .capcodec import Capcodec
+from .hardware import hardware_adapters
+from .x264 import OpenH264, X264
+
+
+def registry() -> list[Adapter]:
+ adapters: list[Adapter] = [
+ X264("ultrafast"),
+ X264("veryfast"),
+ X264("medium"),
+ X264("slow"),
+ X264("medium", tune="stillimage"),
+ X264("veryfast", tune="zerolatency"),
+ OpenH264(),
+ ]
+ try:
+ from .cap_baselines import cap_adapters
+ adapters += cap_adapters()
+ except ImportError:
+ pass
+ try:
+ from .browser import browser_adapters
+ adapters += browser_adapters()
+ except ImportError:
+ pass
+ adapters += hardware_adapters()
+ for preset in ("live", "fast", "medium", "slow"):
+ adapters.append(Capcodec(preset, unchecked=True, label=f"capcodec-{preset}"))
+ adapters.append(Capcodec("live", unchecked=True, extra=["--zerolatency"], label="capcodec-live-zerolatency"))
+ for preset in ("live", "medium"):
+ adapters.append(Capcodec(preset, unchecked=True, rate="bitrate", label=f"capcodec-{preset}-abr"))
+ adapters.append(Capcodec("medium", unchecked=False, label="capcodec-medium-checked"))
+ adapters.append(Capcodec("medium", unchecked=True, sideinfo=False, label="capcodec-medium-nosideinfo"))
+ for spec in filter(None, os.environ.get("CAPCODEC_VARIANTS", "").split(";")):
+ name, _, args = spec.partition(":")
+ argv = shlex.split(args)
+ preset = "medium"
+ if "--preset" in argv:
+ i = argv.index("--preset")
+ preset = argv[i + 1]
+ del argv[i:i + 2]
+ adapters.append(Capcodec(preset, unchecked=True, extra=argv, label=f"capcodec-x-{name}"))
+ for spec in filter(None, os.environ.get("X264_VARIANTS", "").split(";")):
+ name, _, rest = spec.partition(":")
+ preset, _, params = rest.partition(":")
+ adapters.append(X264(preset or "veryfast", params=params, label=f"x264-x-{name}"))
+ return adapters
diff --git a/capcodec/bench/harness/adapters/base.py b/capcodec/bench/harness/adapters/base.py
new file mode 100644
index 000000000..ce2a34333
--- /dev/null
+++ b/capcodec/bench/harness/adapters/base.py
@@ -0,0 +1,115 @@
+from dataclasses import dataclass, field
+from pathlib import Path
+
+from ..common import FFMPEG, RunResult, ffmpeg_version, run, run_measured, sha256_file
+from ..corpus import Source
+
+
+@dataclass
+class Point:
+ label: str
+ params: dict
+ production: bool = False
+
+
+@dataclass
+class EncodeOutput:
+ file: Path
+ container: str
+ run: RunResult
+ recon: Path | None = None
+ extra: dict = field(default_factory=dict)
+ error: str | None = None
+
+
+class Adapter:
+ name = "base"
+ family = "base"
+ description = ""
+ container = "mp4"
+ weight = 1
+ speed_weight = 0
+ reference = False
+ production = False
+ notes = ""
+
+ def available(self) -> tuple[bool, str]:
+ return True, ""
+
+ def identity(self) -> dict:
+ raise NotImplementedError
+
+ def points(self, tier: str, src: Source) -> list[Point]:
+ raise NotImplementedError
+
+ def encode(self, src: Source, point: Point, workdir: Path, speed: bool = False) -> EncodeOutput:
+ raise NotImplementedError
+
+
+_ffmpeg_identity: dict | None = None
+
+
+def ffmpeg_identity() -> dict:
+ global _ffmpeg_identity
+ if _ffmpeg_identity is None:
+ try:
+ digest = sha256_file(Path(FFMPEG).resolve())
+ except OSError:
+ digest = "missing"
+ _ffmpeg_identity = {"ffmpeg": ffmpeg_version(), "sha256": digest}
+ return _ffmpeg_identity
+
+
+_encoder_list: str | None = None
+
+
+def ffmpeg_has_encoder(name: str) -> bool:
+ global _encoder_list
+ if _encoder_list is None:
+ r = run([FFMPEG, "-hide_banner", "-encoders"])
+ _encoder_list = r.stdout.decode(errors="replace")
+ return f" {name} " in _encoder_list
+
+
+COLOR_TAGS = ["-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709", "-color_range", "tv"]
+
+
+def raw_input_args(src: Source) -> list[str]:
+ return ["-f", "rawvideo", "-pix_fmt", "yuv420p", "-s", f"{src.width}x{src.height}", "-r", src.fps_arg,
+ *COLOR_TAGS, "-i", str(src.path), "-frames:v", str(src.frames)]
+
+
+class FFmpegAdapter(Adapter):
+ """An encoder driven through ffmpeg: codec_args(src, params, speed) returns the codec options."""
+
+ codec = "libx264"
+ ladder: list[Point] = []
+ out_ext = "mp4"
+ mux_args: list[str] = ["-movflags", "+faststart"]
+
+ def available(self) -> tuple[bool, str]:
+ if not ffmpeg_has_encoder(self.codec):
+ return False, f"ffmpeg has no {self.codec} encoder"
+ return True, ""
+
+ def identity(self) -> dict:
+ return {"adapter": self.name, "codec": self.codec, "args": self.codec_args_template(), "input": "bt709-tagged-v2",
+ **ffmpeg_identity()}
+
+ def codec_args_template(self) -> list[str]:
+ return []
+
+ def codec_args(self, src: Source, params: dict, speed: bool) -> list[str]:
+ raise NotImplementedError
+
+ def points(self, tier: str, src: Source) -> list[Point]:
+ return list(self.ladder)
+
+ def encode(self, src: Source, point: Point, workdir: Path, speed: bool = False) -> EncodeOutput:
+ out = workdir / f"out.{self.out_ext}"
+ cmd = [FFMPEG, "-hide_banner", "-loglevel", "error", "-nostdin", "-y", *raw_input_args(src),
+ *self.codec_args(src, point.params, speed), "-an", *self.mux_args, str(out)]
+ r = run_measured(cmd, cwd=workdir)
+ err = None if r.returncode == 0 and out.exists() else (
+ r.stderr.decode(errors="replace")[-2000:] or f"exit status {r.returncode}, no output")
+ return EncodeOutput(file=out, container=self.out_ext, run=r, error=err, extra={"cmd": [str(c) for c in cmd]})
diff --git a/capcodec/bench/harness/adapters/browser.py b/capcodec/bench/harness/adapters/browser.py
new file mode 100644
index 000000000..d582ca89f
--- /dev/null
+++ b/capcodec/bench/harness/adapters/browser.py
@@ -0,0 +1,143 @@
+import hashlib
+import os
+import time
+from pathlib import Path
+
+from ..common import RunResult
+from ..corpus import Source
+from .base import Adapter, EncodeOutput, Point
+
+PAGE_DIR = Path(__file__).resolve().parents[1] / "browser"
+CHROME_ARGS = ["--autoplay-policy=no-user-gesture-required", "--disable-gpu", "--no-first-run",
+ "--disable-background-timer-throttling", "--disable-renderer-backgrounding",
+ "--disable-backgrounding-occluded-windows"]
+
+_chrome_version: str | None = None
+
+
+def chrome_version() -> str:
+ global _chrome_version
+ if _chrome_version is None:
+ try:
+ import subprocess
+ exe = os.environ.get("CAPCODEC_CHROME", "google-chrome")
+ _chrome_version = subprocess.run([exe, "--version"], capture_output=True, text=True).stdout.strip()
+ except OSError:
+ _chrome_version = "missing"
+ return _chrome_version
+
+
+def page_hash() -> str:
+ h = hashlib.sha256()
+ for f in sorted(PAGE_DIR.glob("*")):
+ if f.suffix in (".html", ".js"):
+ h.update(f.read_bytes())
+ return h.hexdigest()[:16]
+
+
+def descendants_cpu() -> float:
+ import psutil
+ total = 0.0
+ try:
+ for p in psutil.Process().children(recursive=True):
+ try:
+ ct = p.cpu_times()
+ total += ct.user + ct.system
+ except psutil.Error:
+ pass
+ except psutil.Error:
+ pass
+ return total
+
+
+def run_in_chrome(job: dict, src: Source, workdir: Path, timeout_s: float) -> tuple[dict, float, float]:
+ from playwright.sync_api import sync_playwright
+
+ from ..browser.server import JobState, server
+ srv = server()
+ state = JobState(src.path, src.frame_bytes, src.frames, workdir)
+ jid = srv.add(state)
+ job = {**job, "id": jid}
+ try:
+ with sync_playwright() as p:
+ browser = p.chromium.launch(channel="chrome", headless=True, args=CHROME_ARGS)
+ try:
+ page = browser.new_page()
+ page.goto(f"{srv.origin}/encode.html")
+ cpu0 = descendants_cpu()
+ t0 = time.perf_counter()
+ page.evaluate("job => { window.runJob(job); }", job)
+ page.wait_for_function("window.__status.state === 'done' || window.__status.state === 'error'",
+ timeout=timeout_s * 1000, polling=200)
+ wall = time.perf_counter() - t0
+ cpu = descendants_cpu() - cpu0
+ status = page.evaluate("window.__status")
+ finally:
+ browser.close()
+ finally:
+ srv.remove(jid)
+ return status, wall, cpu
+
+
+class BrowserAdapter(Adapter):
+ family = "browser"
+ weight = 2
+ speed_weight = 0
+ production = True
+
+ def __init__(self, name: str, mode: str, description: str, config_fn, ladder_fn, ext: str = "mp4",
+ key_interval_s: float | None = 2.0, timeslice_ms: int | None = None):
+ self.name = name
+ self.mode = mode
+ self.description = description
+ self.config_fn = config_fn
+ self.ladder_fn = ladder_fn
+ self.ext = ext
+ self.key_interval_s = key_interval_s
+ self.timeslice_ms = timeslice_ms
+ self.container = "annexb" if mode == "webcodecs" else ext
+
+ def available(self) -> tuple[bool, str]:
+ try:
+ import playwright # noqa: F401
+ except ImportError:
+ return False, "playwright not installed"
+ if chrome_version() == "missing":
+ return False, "Google Chrome not found"
+ return True, ""
+
+ def identity(self) -> dict:
+ return {"adapter": self.name, "mode": self.mode, "chrome": chrome_version(), "page": page_hash(),
+ "key_interval_s": self.key_interval_s, "ext": self.ext, "timeslice": self.timeslice_ms,
+ "config": self.config_fn.__name__}
+
+ def points(self, tier: str, src: Source, anchor_kbps: float | None = None) -> list[Point]:
+ return self.ladder_fn(src, anchor_kbps)
+
+ def encode(self, src: Source, point: Point, workdir: Path, speed: bool = False) -> EncodeOutput:
+ config = self.config_fn(src, point.params)
+ fps = src.fps
+ job = {"mode": self.mode, "config": config, "width": src.width, "height": src.height,
+ "frames": src.frames, "fpsNum": fps.numerator, "fpsDen": fps.denominator, "ext": self.ext,
+ "keyInterval": int(round(self.key_interval_s * src.fps_float)) if self.key_interval_s else 0,
+ "timeslice": self.timeslice_ms}
+ timeout = 120 + 3 * src.duration_s + src.frames * 0.2
+ status, wall, cpu = run_in_chrome(job, src, workdir, timeout)
+ name = "out.264" if self.mode == "webcodecs" else f"out.{self.ext}"
+ out = workdir / name
+ err = None
+ if status.get("state") != "done" or not out.exists():
+ err = status.get("error") or f"browser state {status.get('state')}"
+ result = status.get("result") or {}
+ rr = RunResult(0 if err is None else 1, wall, cpu, 0.0)
+ return EncodeOutput(file=out, container=self.container, run=rr, error=err,
+ extra={"browser": result, "config": config, "chrome": chrome_version(),
+ "note": "headless Google Chrome on Linux: software H.264 (OpenH264)"})
+
+
+def browser_adapters() -> list[Adapter]:
+ try:
+ from .cap_baselines import cap_browser_adapters
+ return cap_browser_adapters()
+ except ImportError:
+ return []
diff --git a/capcodec/bench/harness/adapters/cap_baselines.py b/capcodec/bench/harness/adapters/cap_baselines.py
new file mode 100644
index 000000000..5f7823228
--- /dev/null
+++ b/capcodec/bench/harness/adapters/cap_baselines.py
@@ -0,0 +1,151 @@
+from ..corpus import Source
+from .base import FFmpegAdapter, Point
+
+
+def cap_bitrate(src: Source, bpp: float) -> int:
+ fps = src.fps_float
+ return int(src.width * src.height * (max(fps - 30.0, 0.0) * 0.6 + 30.0) * bpp)
+
+
+def keyint(src: Source) -> int:
+ return max(1, int(round(2.0 * src.fps_float)))
+
+
+class CapX264(FFmpegAdapter):
+ codec = "libx264"
+ family = "cap"
+ production = True
+ speed_weight = 1
+ weight = 4
+
+ def __init__(self, name: str, description: str, ladder: list[Point], args_fn, max_height: int | None = None):
+ self.name = name
+ self.description = description
+ self.ladder = ladder
+ self.args_fn = args_fn
+ self.max_height = max_height
+
+ def codec_args_template(self) -> list[str]:
+ return [self.description]
+
+ def points(self, tier: str, src: Source) -> list[Point]:
+ if self.max_height and src.height > self.max_height:
+ return []
+ return list(self.ladder)
+
+ def codec_args(self, src: Source, params: dict, speed: bool) -> list[str]:
+ return self.args_fn(src, params)
+
+
+def ms_transcode(src: Source, p: dict) -> list[str]:
+ return ["-c:v", "libx264", "-preset", "medium", "-crf", str(p["crf"]), "-pix_fmt", "yuv420p", "-level:v", "4.2"]
+
+
+def ms_edit(src: Source, p: dict) -> list[str]:
+ return ["-c:v", "libx264", "-preset", "fast", "-crf", str(p["crf"]), "-pix_fmt", "yuv420p"]
+
+
+def export_x264(src: Source, p: dict) -> list[str]:
+ b = cap_bitrate(src, p["bpp"])
+ k = keyint(src)
+ return ["-pix_fmt", "nv12", "-c:v", "libx264", "-preset", "veryfast", "-b:v", str(b), "-maxrate", str(b * 3 // 2),
+ "-bf", "0", "-rc-lookahead", "10", "-aq-mode", "1", "-trellis", "0", "-g", str(k), "-keyint_min", str(k)]
+
+
+def export_crf(src: Source, p: dict) -> list[str]:
+ k = keyint(src)
+ return ["-pix_fmt", "nv12", "-c:v", "libx264", "-preset", "slow", "-crf", str(p["crf"]), "-g", str(k),
+ "-keyint_min", str(k)]
+
+
+def rec_linux(src: Source, p: dict) -> list[str]:
+ b = cap_bitrate(src, p["bpp"])
+ k = keyint(src)
+ return ["-c:v", "libx264", "-preset", "ultrafast", "-tune", "zerolatency", "-b:v", str(b), "-maxrate",
+ str(b * 3 // 2), "-g", str(k), "-keyint_min", str(k), "-pix_fmt", "yuv420p"]
+
+
+def rf_transcode(src: Source, p: dict) -> list[str]:
+ return ["-fps_mode", "passthrough", "-pix_fmt", "yuv420p", "-c:v", "libx264", "-preset", "veryfast", "-crf",
+ str(p["crf"]), "-bf", "0", "-force_key_frames", "expr:gte(t,n_forced*1)"]
+
+
+def cap_adapters() -> list[FFmpegAdapter]:
+ return [
+ CapX264("cap-ms-transcode", "Media server processVideo: libx264 medium CRF 23, [email protected], x264 default GOP and 3 B-frames",
+ [Point(f"crf{c}", {"crf": c}, c == 23) for c in (18, 23, 28, 33)], ms_transcode, max_height=1088),
+ CapX264("cap-ms-edit", "Media server edited render: libx264 fast CRF 18",
+ [Point(f"crf{c}", {"crf": c}, c == 18) for c in (14, 18, 23, 28)], ms_edit),
+ CapX264("cap-export-x264", "Desktop export default and render-farm libx264 override: veryfast ABR at Cap's bpp "
+ "presets (Potato 0.04, Web 0.08, Social 0.15, Maximum 0.3), bf 0, rc-lookahead 10, trellis 0, 2 s GOP",
+ [Point(f"bpp{b:g}", {"bpp": b}, b == 0.3) for b in (0.04, 0.08, 0.15, 0.3)], export_x264),
+ CapX264("cap-export-crf", "Desktop export 'Optimize file size': libx264 slow CRF 24/28/32/36, 3 B-frames, 2 s GOP",
+ [Point(f"crf{c}", {"crf": c}, c == 28) for c in (24, 28, 32, 36)], export_crf),
+ CapX264("cap-rec-linux", "Desktop recording on Linux: libx264 ultrafast zerolatency ABR at bpp 0.3 (Balanced), "
+ "2 s GOP; ladder adds Compat 0.15, 0.08 and Ultra-level 1.0",
+ [Point(f"bpp{b:g}", {"bpp": b}, b == 0.3) for b in (0.08, 0.15, 0.3, 1.0)], rec_linux),
+ CapX264("cap-rf-transcode", "Render-farm source transcode (libx264 override): veryfast CRF 18, bf 0, IDR every 1 s",
+ [Point(f"crf{c}", {"crf": c}, c == 18) for c in (14, 18, 23, 28)], rf_transcode),
+ ]
+
+
+def recorder_bitrate(src: Source) -> int:
+ px = src.width * src.height
+ if px <= 1280 * 720:
+ base = 2_500_000
+ elif px <= 1920 * 1088:
+ base = 4_000_000
+ elif px <= 2560 * 1600:
+ base = 6_000_000
+ else:
+ base = 10_000_000
+ if src.fps_float > 40:
+ base = int(round(base * 1.5))
+ return base
+
+
+def avc_level_codec(src: Source, bitrate: int) -> str:
+ mbs = ((src.width + 15) // 16) * ((src.height + 15) // 16)
+ levels = [(0x1F, 3600, 14_000_000), (0x20, 5120, 20_000_000), (0x28, 8192, 25_000_000),
+ (0x29, 8192, 62_500_000), (0x2A, 8704, 62_500_000), (0x32, 22080, 168_750_000),
+ (0x33, 36864, 300_000_000), (0x34, 36864, 300_000_000)]
+ for lv, maxmb, maxbr in levels:
+ if mbs <= maxmb and bitrate <= maxbr:
+ return f"avc1.6400{lv:02X}"
+ return "avc1.640034"
+
+
+def mr_config(src: Source, p: dict) -> dict:
+ return {"mimeType": 'video/mp4;codecs="avc1.64002A"',
+ "videoBitsPerSecond": int(round(recorder_bitrate(src) * p["scale"])),
+ "videoKeyFrameIntervalDuration": 2000}
+
+
+def wc_config(src: Source, p: dict) -> dict:
+ fps = src.fps_float
+ bitrate = int(round(src.width * src.height * (max(fps - 30.0, 0.0) * 0.6 + 30.0) * p["bpp"]))
+ return {"codec": avc_level_codec(src, bitrate), "width": src.width, "height": src.height, "bitrate": bitrate,
+ "framerate": fps, "latencyMode": "quality", "hardwareAcceleration": "no-preference", "alpha": "discard",
+ "avc": {"format": "annexb"}}
+
+
+def mr_ladder(src: Source, anchor):
+ return [Point(f"x{s:g}", {"scale": s}, s == 1.0) for s in (0.25, 0.5, 1.0, 1.6)]
+
+
+def wc_ladder(src: Source, anchor):
+ return [Point(f"bpp{b:g}", {"bpp": b}, b == 0.3) for b in (0.04, 0.08, 0.15, 0.3)]
+
+
+def cap_browser_adapters():
+ from .browser import BrowserAdapter
+ return [
+ BrowserAdapter("cap-web-recorder", "mediarecorder",
+ "PR 2312 web recorder (BR-MR-PR-SCREEN): MediaRecorder video/mp4 avc1.64002A, screen bitrate "
+ "tier (4 Mbit/s at 1080p30, x1.5 above 40 fps; high quality x1.6), 2 s keyframes, 1 s slices",
+ mr_config, mr_ladder, ext="mp4", key_interval_s=None, timeslice_ms=1000),
+ BrowserAdapter("cap-browser-export", "webcodecs",
+ "PR 2312 browser export (BR-WC-EXPORT-PR): WebCodecs avc1.6400LL, bpp model (Maximum 0.3 ... "
+ "Potato 0.04), latencyMode quality, keyframe every 2 s",
+ wc_config, wc_ladder, key_interval_s=2.0),
+ ]
diff --git a/capcodec/bench/harness/adapters/capcodec.py b/capcodec/bench/harness/adapters/capcodec.py
new file mode 100644
index 000000000..efb4641b6
--- /dev/null
+++ b/capcodec/bench/harness/adapters/capcodec.py
@@ -0,0 +1,88 @@
+import json
+import os
+from pathlib import Path
+
+from ..common import ROOT, run_measured, sha256_file
+from ..corpus import Source
+from .base import Adapter, EncodeOutput, Point
+from .cap_baselines import cap_bitrate
+
+QP_LADDER = [20, 25, 30, 35]
+CRF_LADDER = [20, 24, 28, 32, 36, 40, 44]
+CAP_BPP = [0.04, 0.08, 0.15, 0.3]
+
+
+def default_binary(unchecked: bool = False) -> Path:
+ env = os.environ.get("CAPCODEC_BIN_UNCHECKED" if unchecked else "CAPCODEC_BIN")
+ if env:
+ return Path(env)
+ return ROOT / "build" / ("capcodec-unchecked" if unchecked else "capcodec")
+
+
+class Capcodec(Adapter):
+ family = "capcodec"
+ speed_weight = 1
+
+ def __init__(self, preset: str = "medium", unchecked: bool = False, output: str = "mp4", sideinfo: bool = True,
+ extra: list[str] | None = None, label: str | None = None, rate: str = "crf"):
+ self.preset = preset
+ self.unchecked = unchecked
+ self.output = output
+ self.use_sideinfo = sideinfo
+ self.extra = extra or []
+ self.rate = rate
+ self.binary = default_binary(unchecked)
+ suffix = "-unchecked" if unchecked else ""
+ self.name = label or f"capcodec-{preset}{suffix}"
+ self.description = f"capcodec preset {preset}" + (" (built with --unchecked)" if unchecked else "")
+ if rate == "bitrate":
+ self.description += ", bitrate mode at Cap's bpp targets (Potato 0.04 ... Maximum 0.3, maxrate 1.5x)"
+ self.container = "annexb" if output == "264" else output
+
+ def available(self) -> tuple[bool, str]:
+ if not self.binary.exists():
+ return False, f"{self.binary} not built (run bench/build_encoder.sh)"
+ return True, ""
+
+ def identity(self) -> dict:
+ return {"adapter": "capcodec", "preset": self.preset, "binary": sha256_file(self.binary),
+ "output": self.output, "sideinfo": self.use_sideinfo, "extra": self.extra, "rate": self.rate}
+
+ def points(self, tier: str, src: Source) -> list[Point]:
+ if self.rate == "crf":
+ return [Point(f"crf{q}", {"crf": q}) for q in CRF_LADDER]
+ if self.rate == "bitrate":
+ return [Point(f"bpp{b:g}", {"bitrate": cap_bitrate(src, b) // 1000,
+ "maxrate": cap_bitrate(src, b) * 3 // 2 // 1000}) for b in CAP_BPP]
+ return [Point(f"qp{q}", {"qp": q}) for q in QP_LADDER]
+
+ def encode(self, src: Source, point: Point, workdir: Path, speed: bool = False) -> EncodeOutput:
+ out = workdir / f"out.{self.output}"
+ recon = workdir / "recon.yuv"
+ stats = workdir / "stats.json"
+ cmd = [str(self.binary), "encode", "--input", str(src.path), "--width", str(src.width),
+ "--height", str(src.height), "--fps", src.fps_arg, "--frames", str(src.frames),
+ "--preset", self.preset, "--output", str(out), "--stats", str(stats)]
+ for k, v in point.params.items():
+ if v is True:
+ cmd.append(f"--{k}")
+ elif v is not False and v is not None:
+ cmd += [f"--{k}", str(v)]
+ if not speed:
+ cmd += ["--recon", str(recon)]
+ if "threads" not in point.params:
+ cmd += ["--threads", "1"]
+ if self.use_sideinfo and src.sideinfo:
+ cmd += ["--sideinfo", str(src.sideinfo)]
+ cmd += self.extra
+ r = run_measured(cmd, cwd=workdir)
+ err = None if r.returncode == 0 and out.exists() else (
+ (r.stderr + r.stdout).decode(errors="replace")[-3000:] or f"exit status {r.returncode}, no output")
+ extra = {"cmd": cmd}
+ if stats.exists():
+ try:
+ extra["stats"] = json.loads(stats.read_text())
+ except json.JSONDecodeError:
+ pass
+ return EncodeOutput(file=out, container=self.container, run=r, recon=recon if recon.exists() else None,
+ extra=extra, error=err)
diff --git a/capcodec/bench/harness/adapters/hardware.py b/capcodec/bench/harness/adapters/hardware.py
new file mode 100644
index 000000000..c1701c396
--- /dev/null
+++ b/capcodec/bench/harness/adapters/hardware.py
@@ -0,0 +1,73 @@
+import tempfile
+from pathlib import Path
+
+from ..common import FFMPEG, run
+from ..corpus import Source
+from .base import FFmpegAdapter, Point, ffmpeg_has_encoder
+
+_probe_cache: dict[str, tuple[bool, str]] = {}
+
+
+def probe_encoder(codec: str, extra: list[str]) -> tuple[bool, str]:
+ if codec in _probe_cache:
+ return _probe_cache[codec]
+ if not ffmpeg_has_encoder(codec):
+ _probe_cache[codec] = (False, f"ffmpeg has no {codec} encoder")
+ return _probe_cache[codec]
+ with tempfile.TemporaryDirectory() as d:
+ out = Path(d) / "probe.mp4"
+ r = run([FFMPEG, "-hide_banner", "-loglevel", "error", "-nostdin", "-f", "lavfi", "-i",
+ "testsrc2=size=1280x720:rate=30", "-frames:v", "10", "-pix_fmt", "yuv420p", *extra, "-c:v", codec,
+ "-b:v", "2M", str(out)], timeout=60)
+ ok = r.returncode == 0 and out.exists() and out.stat().st_size > 0
+ reason = "" if ok else (r.stderr.decode(errors="replace").strip().splitlines() or ["probe failed"])[-1]
+ _probe_cache[codec] = (ok, reason)
+ return _probe_cache[codec]
+
+
+class HardwareEncoder(FFmpegAdapter):
+ family = "hardware"
+ weight = 2
+ anchor_scale = [0.35, 0.6, 1.0, 1.7, 3.0]
+ init_args: list[str] = []
+ rc_args: list[str] = []
+
+ def __init__(self, codec: str, name: str, description: str, rc_args: list[str], init_args: list[str] | None = None,
+ pix_fmt: str = "yuv420p"):
+ self.codec = codec
+ self.name = name
+ self.description = description
+ self.rc_args = rc_args
+ self.init_args = init_args or []
+ self.pix_fmt = pix_fmt
+
+ def available(self) -> tuple[bool, str]:
+ return probe_encoder(self.codec, self.init_args)
+
+ def codec_args_template(self) -> list[str]:
+ return [*self.init_args, *self.rc_args, "-b:v", "{kbps}", "-g", "2s", "-pix_fmt", self.pix_fmt]
+
+ def points(self, tier: str, src: Source, anchor_kbps: float | None = None) -> list[Point]:
+ base = anchor_kbps or 0.03 * src.width * src.height * src.fps_float / 1000.0
+ return [Point(f"x{s:g}", {"kbps": max(50, int(round(base * s)))}) for s in self.anchor_scale]
+
+ def codec_args(self, src: Source, params: dict, speed: bool) -> list[str]:
+ g = max(1, int(round(2.0 * src.fps_float)))
+ kbps = params["kbps"]
+ return [*self.init_args, "-pix_fmt", self.pix_fmt, "-c:v", self.codec, *self.rc_args, "-b:v", f"{kbps}k",
+ "-maxrate", f"{int(kbps * 1.5)}k", "-bufsize", f"{int(kbps * 2)}k", "-g", str(g)]
+
+
+def hardware_adapters() -> list[HardwareEncoder]:
+ return [
+ HardwareEncoder("h264_nvenc", "nvenc", "NVIDIA NVENC H.264, VBR, preset p4, high profile",
+ ["-preset", "p4", "-rc", "vbr", "-profile:v", "high", "-bf", "0"]),
+ HardwareEncoder("h264_videotoolbox", "videotoolbox", "Apple VideoToolbox H.264, ABR, high profile",
+ ["-profile:v", "high", "-allow_sw", "0", "-realtime", "1"]),
+ HardwareEncoder("h264_qsv", "qsv", "Intel Quick Sync H.264, VBR, preset medium",
+ ["-preset", "medium", "-profile:v", "high"], pix_fmt="nv12"),
+ HardwareEncoder("h264_amf", "amf", "AMD AMF H.264, VBR peak, quality",
+ ["-quality", "quality", "-rc", "vbr_peak", "-profile:v", "high"]),
+ HardwareEncoder("h264_mf", "mediafoundation", "Windows Media Foundation H.264, hardware, quality rate control",
+ ["-hw_encoding", "1", "-rate_control", "quality"], pix_fmt="nv12"),
+ ]
diff --git a/capcodec/bench/harness/adapters/x264.py b/capcodec/bench/harness/adapters/x264.py
new file mode 100644
index 000000000..b62f4c1ec
--- /dev/null
+++ b/capcodec/bench/harness/adapters/x264.py
@@ -0,0 +1,61 @@
+from ..corpus import Source
+from .base import FFmpegAdapter, Point
+
+CRF_LADDER = [18, 23, 28, 33]
+
+
+def gop_args(src: Source, seconds: float = 2.0) -> list[str]:
+ g = max(1, int(round(seconds * src.fps_float)))
+ return ["-g", str(g), "-keyint_min", str(min(g, max(1, int(round(src.fps_float)))))]
+
+
+class X264(FFmpegAdapter):
+ codec = "libx264"
+ family = "x264"
+ reference = True
+ speed_weight = 1
+
+ def __init__(self, preset: str, tune: str | None = None, label: str | None = None, params: str = ""):
+ self.preset = preset
+ self.tune = tune
+ self.params = params
+ self.name = label or f"x264-{preset}" + (f"-{tune}" if tune else "")
+ self.description = (f"libx264 preset {preset}" + (f", tune {tune}" if tune else "") +
+ (f", x264-params {params}" if params else "") + ", CRF ladder, 2 s GOP")
+ self.ladder = [Point(f"crf{c}", {"crf": c}) for c in CRF_LADDER]
+
+ def codec_args_template(self) -> list[str]:
+ extra = ["-x264-params", self.params] if self.params else []
+ return ["-preset", self.preset, "-tune", self.tune or "", *extra, "-crf", "{crf}", "-g", "2s", "-threads", "1|auto"]
+
+ def codec_args(self, src: Source, params: dict, speed: bool) -> list[str]:
+ args = ["-c:v", "libx264", "-preset", self.preset]
+ if self.tune:
+ args += ["-tune", self.tune]
+ if self.params:
+ args += ["-x264-params", self.params]
+ args += ["-crf", str(params["crf"]), *gop_args(src), "-pix_fmt", "yuv420p",
+ "-threads", "0" if speed else "1"]
+ return args
+
+
+class OpenH264(FFmpegAdapter):
+ codec = "libopenh264"
+ family = "openh264"
+ name = "openh264"
+ description = "OpenH264 (the library Chrome uses for software H.264), bitrate mode, anchor-relative ladder, 2 s GOP"
+ reference = True
+ speed_weight = 1
+ anchor_scale = [0.35, 0.6, 1.0, 1.7, 3.0]
+
+ def codec_args_template(self) -> list[str]:
+ return ["-rc_mode", "bitrate", "-b:v", "{kbps}", "-coder", "cavlc", "-g", "2s", "-threads", "1|auto"]
+
+ def points(self, tier: str, src: Source, anchor_kbps: float | None = None) -> list[Point]:
+ base = anchor_kbps or 0.03 * src.width * src.height * src.fps_float / 1000.0
+ return [Point(f"x{s:g}", {"kbps": max(20, int(round(base * s)))}) for s in self.anchor_scale]
+
+ def codec_args(self, src: Source, params: dict, speed: bool) -> list[str]:
+ g = max(1, int(round(2.0 * src.fps_float)))
+ return ["-c:v", "libopenh264", "-rc_mode", "bitrate", "-b:v", f"{params['kbps']}k", "-coder", "cavlc",
+ "-g", str(g), "-allow_skip_frames", "0", "-threads", "0" if speed else "1"]
diff --git a/capcodec/bench/harness/bdrate.py b/capcodec/bench/harness/bdrate.py
new file mode 100644
index 000000000..95beaec46
--- /dev/null
+++ b/capcodec/bench/harness/bdrate.py
@@ -0,0 +1,65 @@
+import math
+
+import numpy as np
+from scipy.interpolate import PchipInterpolator
+
+
+def _clean(rates, quals):
+ pts = sorted((q, r) for r, q in zip(rates, quals) if r and r > 0 and q is not None and not math.isnan(q))
+ out = []
+ for q, r in pts:
+ if out and (q <= out[-1][0] + 1e-9 or r <= out[-1][1]):
+ continue
+ out.append((q, r))
+ return out
+
+
+def bd_rate(ref_rates, ref_quals, test_rates, test_quals, min_points: int = 3) -> float | None:
+ ref = _clean(ref_rates, ref_quals)
+ test = _clean(test_rates, test_quals)
+ if len(ref) < min_points or len(test) < min_points:
+ return None
+ rq = np.array([p[0] for p in ref])
+ rr = np.log10(np.array([p[1] for p in ref]))
+ tq = np.array([p[0] for p in test])
+ tr = np.log10(np.array([p[1] for p in test]))
+ lo = max(rq.min(), tq.min())
+ hi = min(rq.max(), tq.max())
+ if hi - lo < 1e-6 * max(1.0, abs(hi)):
+ return None
+ f_ref = PchipInterpolator(rq, rr)
+ f_test = PchipInterpolator(tq, tr)
+ xs = np.linspace(lo, hi, 256)
+ avg_diff = np.trapezoid(f_test(xs) - f_ref(xs), xs) / (hi - lo)
+ return float((10.0 ** avg_diff - 1.0) * 100.0)
+
+
+def overlap_fraction(ref_quals, test_quals) -> float:
+ a = [q for q in ref_quals if q is not None]
+ b = [q for q in test_quals if q is not None]
+ if not a or not b:
+ return 0.0
+ lo, hi = max(min(a), min(b)), min(max(a), max(b))
+ span = max(max(a), max(b)) - min(min(a), min(b))
+ return max(0.0, hi - lo) / span if span > 0 else 0.0
+
+
+def bd_quality(ref_rates, ref_quals, test_rates, test_quals) -> float | None:
+ ref = _clean(ref_rates, ref_quals)
+ test = _clean(test_rates, test_quals)
+ if len(ref) < 3 or len(test) < 3:
+ return None
+ rr = np.log10([p[1] for p in ref])
+ rq = np.array([p[0] for p in ref])
+ tr = np.log10([p[1] for p in test])
+ tq = np.array([p[0] for p in test])
+ o_r = np.argsort(rr)
+ o_t = np.argsort(tr)
+ lo = max(rr.min(), tr.min())
+ hi = min(rr.max(), tr.max())
+ if hi <= lo:
+ return None
+ f_ref = PchipInterpolator(rr[o_r], rq[o_r])
+ f_test = PchipInterpolator(tr[o_t], tq[o_t])
+ xs = np.linspace(lo, hi, 256)
+ return float(np.trapezoid(f_test(xs) - f_ref(xs), xs) / (hi - lo))
diff --git a/capcodec/bench/harness/browser/encode.html b/capcodec/bench/harness/browser/encode.html
new file mode 100644
index 000000000..d60099dd7
--- /dev/null
+++ b/capcodec/bench/harness/browser/encode.html
@@ -0,0 +1,127 @@
+<!doctype html>
+<html>
+<head><meta charset="utf-8"><title>capcodec browser encode</title></head>
+<body>
+<script>
+"use strict";
+window.__status = { state: "idle" };
+
+async function fetchFrame(job, index) {
+ const res = await fetch(`/frame/${job.id}/${index}`);
+ if (!res.ok) throw new Error(`frame ${index}: HTTP ${res.status}`);
+ return new Uint8Array(await res.arrayBuffer());
+}
+
+function makeFrame(job, data, index) {
+ return new VideoFrame(data, {
+ format: "I420",
+ codedWidth: job.width,
+ codedHeight: job.height,
+ timestamp: Math.round((index * 1e6 * job.fpsDen) / job.fpsNum),
+ duration: Math.round((1e6 * job.fpsDen) / job.fpsNum),
+ colorSpace: { primaries: "bt709", transfer: "bt709", matrix: "bt709", fullRange: false },
+ });
+}
+
+async function upload(job, parts, name) {
+ const blob = new Blob(parts);
+ const res = await fetch(`/upload/${job.id}/${name}`, { method: "POST", body: blob });
+ if (!res.ok) throw new Error(`upload failed: HTTP ${res.status}`);
+ return blob.size;
+}
+
+async function prefetch(job, count) {
+ const frames = new Array(job.frames);
+ let next = 0;
+ const workers = [];
+ for (let w = 0; w < 4; w++) {
+ workers.push((async () => {
+ while (next < count) {
+ const i = next++;
+ frames[i] = await fetchFrame(job, i);
+ }
+ })());
+ }
+ await Promise.all(workers);
+ return frames;
+}
+
+async function runWebCodecs(job) {
+ const support = await VideoEncoder.isConfigSupported(job.config);
+ if (!support.supported) throw new Error("config not supported: " + JSON.stringify(job.config));
+ const chunks = [];
+ let error = null;
+ let keyframes = 0;
+ const encoder = new VideoEncoder({
+ output: (chunk) => {
+ const buf = new Uint8Array(chunk.byteLength);
+ chunk.copyTo(buf);
+ chunks.push(buf);
+ if (chunk.type === "key") keyframes++;
+ },
+ error: (e) => { error = e; },
+ });
+ encoder.configure(job.config);
+ const t0 = performance.now();
+ for (let i = 0; i < job.frames; i++) {
+ if (error) throw error;
+ const data = await fetchFrame(job, i);
+ const frame = makeFrame(job, data, i);
+ const keyFrame = job.keyInterval > 0 && i % job.keyInterval === 0;
+ encoder.encode(frame, { keyFrame });
+ frame.close();
+ while (encoder.encodeQueueSize > 8) await new Promise((r) => setTimeout(r, 1));
+ }
+ await encoder.flush();
+ const encodeMs = performance.now() - t0;
+ encoder.close();
+ if (error) throw error;
+ const bytes = await upload(job, chunks, "out.264");
+ return { bytes, chunks: chunks.length, keyframes, encodeMs, support: support.config };
+}
+
+async function runMediaRecorder(job) {
+ if (!MediaRecorder.isTypeSupported(job.config.mimeType)) throw new Error("mime not supported: " + job.config.mimeType);
+ const generator = new MediaStreamTrackGenerator({ kind: "video" });
+ const writer = generator.writable.getWriter();
+ const stream = new MediaStream([generator]);
+ const opts = { ...job.config };
+ const recorder = new MediaRecorder(stream, opts);
+ const parts = [];
+ recorder.ondataavailable = (e) => { if (e.data && e.data.size) parts.push(e.data); };
+ const stopped = new Promise((resolve) => { recorder.onstop = resolve; });
+ const frames = await prefetch(job, job.frames);
+ recorder.start(job.timeslice || 1000);
+ const interval = (1000 * job.fpsDen) / job.fpsNum;
+ const t0 = performance.now();
+ let late = 0;
+ for (let i = 0; i < job.frames; i++) {
+ const due = t0 + i * interval;
+ const wait = due - performance.now();
+ if (wait > 1) await new Promise((r) => setTimeout(r, wait - 0.5));
+ while (performance.now() < due) {}
+ if (performance.now() - due > interval) late++;
+ await writer.write(makeFrame(job, frames[i], i));
+ frames[i] = null;
+ }
+ await new Promise((r) => setTimeout(r, interval));
+ recorder.stop();
+ await stopped;
+ await writer.close();
+ const encodeMs = performance.now() - t0;
+ const bytes = await upload(job, parts, "out." + job.ext);
+ return { bytes, encodeMs, late, mimeType: recorder.mimeType };
+}
+
+window.runJob = async function (job) {
+ window.__status = { state: "running" };
+ try {
+ const result = job.mode === "webcodecs" ? await runWebCodecs(job) : await runMediaRecorder(job);
+ window.__status = { state: "done", result };
+ } catch (e) {
+ window.__status = { state: "error", error: String(e && e.stack ? e.stack : e) };
+ }
+};
+</script>
+</body>
+</html>
diff --git a/capcodec/bench/harness/browser/server.py b/capcodec/bench/harness/browser/server.py
new file mode 100644
index 000000000..b401961b1
--- /dev/null
+++ b/capcodec/bench/harness/browser/server.py
@@ -0,0 +1,106 @@
+import threading
+import uuid
+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
+from pathlib import Path
+
+PAGE = Path(__file__).resolve().parent / "encode.html"
+
+
+class JobState:
+ def __init__(self, yuv: Path, frame_bytes: int, frames: int, out_dir: Path):
+ self.yuv = yuv
+ self.frame_bytes = frame_bytes
+ self.frames = frames
+ self.out_dir = out_dir
+ self.uploads: dict[str, Path] = {}
+
+
+class _Handler(BaseHTTPRequestHandler):
+ server_version = "capcodec-bench"
+
+ def log_message(self, fmt, *args):
+ pass
+
+ def _send(self, code: int, body: bytes, ctype: str = "application/octet-stream"):
+ self.send_response(code)
+ self.send_header("Content-Type", ctype)
+ self.send_header("Content-Length", str(len(body)))
+ self.send_header("Cache-Control", "no-store")
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ parts = self.path.strip("/").split("/")
+ if parts == ["encode.html"] or parts == [""]:
+ self._send(200, PAGE.read_bytes(), "text/html; charset=utf-8")
+ return
+ if len(parts) == 3 and parts[0] == "frame":
+ job = self.server.jobs.get(parts[1])
+ if job is None:
+ self._send(404, b"no job")
+ return
+ i = int(parts[2])
+ if i < 0 or i >= job.frames:
+ self._send(404, b"no frame")
+ return
+ with open(job.yuv, "rb") as f:
+ f.seek(i * job.frame_bytes)
+ data = f.read(job.frame_bytes)
+ self._send(200, data)
+ return
+ self._send(404, b"not found")
+
+ def do_POST(self):
+ parts = self.path.strip("/").split("/")
+ if len(parts) == 3 and parts[0] == "upload":
+ job = self.server.jobs.get(parts[1])
+ if job is None:
+ self._send(404, b"no job")
+ return
+ n = int(self.headers.get("Content-Length", "0"))
+ name = Path(parts[2]).name
+ out = job.out_dir / name
+ remaining = n
+ with open(out, "wb") as f:
+ while remaining > 0:
+ chunk = self.rfile.read(min(remaining, 1 << 20))
+ if not chunk:
+ break
+ f.write(chunk)
+ remaining -= len(chunk)
+ job.uploads[name] = out
+ self._send(200, b"ok", "text/plain")
+ return
+ self._send(404, b"not found")
+
+
+class FrameServer:
+ def __init__(self):
+ self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)
+ self.httpd.jobs = {}
+ self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True)
+ self.thread.start()
+
+ @property
+ def origin(self) -> str:
+ return f"http://127.0.0.1:{self.httpd.server_address[1]}"
+
+ def add(self, state: JobState) -> str:
+ jid = uuid.uuid4().hex
+ self.httpd.jobs[jid] = state
+ return jid
+
+ def remove(self, jid: str):
+ self.httpd.jobs.pop(jid, None)
+
+
+_server: FrameServer | None = None
+_lock = threading.Lock()
+
+
+def server() -> FrameServer:
+ global _server
+ with _lock:
+ if _server is None:
+ _server = FrameServer()
+ return _server
diff --git a/capcodec/bench/harness/common.py b/capcodec/bench/harness/common.py
new file mode 100644
index 000000000..e462adeed
--- /dev/null
+++ b/capcodec/bench/harness/common.py
@@ -0,0 +1,228 @@
+import hashlib
+import json
+import os
+import platform
+import shutil
+import subprocess
+import sys
+import time
+from dataclasses import dataclass
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[2]
+BENCH = ROOT / "bench"
+CORPUS_DIR = Path(os.environ.get("CAPCODEC_CORPUS", str(Path.home() / "work" / "corpus")))
+CACHE_DIR = Path(os.environ.get("CAPCODEC_BENCH_CACHE", str(Path.home() / ".cache" / "capcodec-bench")))
+OUT_DIR = Path(os.environ.get("CAPCODEC_BENCH_OUT", str(BENCH / "out")))
+MANIFEST = Path(os.environ.get("CAPCODEC_MANIFEST", str(BENCH / "corpus" / "manifest.json")))
+IS_WINDOWS = platform.system() == "Windows"
+IS_MAC = platform.system() == "Darwin"
+EXE = ".exe" if IS_WINDOWS else ""
+
+
+def tool(name: str) -> str:
+ env = os.environ.get("CAPCODEC_" + name.upper())
+ if env:
+ return env
+ local = Path.home() / "tools" / "bin" / (name + EXE)
+ if local.exists():
+ return str(local)
+ found = shutil.which(name)
+ return found or name
+
+
+FFMPEG = tool("ffmpeg")
+FFPROBE = tool("ffprobe")
+LDECOD = tool("ldecod")
+TESSERACT = tool("tesseract")
+
+
+def ncores() -> int:
+ env = os.environ.get("CAPCODEC_BENCH_JOBS")
+ if env:
+ return max(1, int(env))
+ return os.cpu_count() or 1
+
+
+def sha256_bytes(data: bytes) -> str:
+ return hashlib.sha256(data).hexdigest()
+
+
+_file_hash_cache: dict[tuple[str, int, int], str] = {}
+
+
+def sha256_file(path: Path) -> str:
+ st = path.stat()
+ key = (str(path), st.st_size, int(st.st_mtime_ns))
+ hit = _file_hash_cache.get(key)
+ if hit:
+ return hit
+ h = hashlib.sha256()
+ with open(path, "rb") as f:
+ while True:
+ chunk = f.read(1 << 22)
+ if not chunk:
+ break
+ h.update(chunk)
+ digest = h.hexdigest()
+ _file_hash_cache[key] = digest
+ return digest
+
+
+def stable_json(obj) -> str:
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"))
+
+
+def key_of(*parts) -> str:
+ return sha256_bytes(stable_json(parts).encode())[:32]
+
+
+@dataclass
+class RunResult:
+ returncode: int
+ wall_s: float
+ cpu_s: float
+ maxrss_mb: float
+ stdout: bytes = b""
+ stderr: bytes = b""
+
+
+def run(cmd: list[str], cwd: Path | None = None, stdin_path: Path | None = None, stdout_path: Path | None = None,
+ env: dict | None = None, timeout: float | None = None) -> RunResult:
+ stdin = open(stdin_path, "rb") if stdin_path else subprocess.DEVNULL
+ stdout = open(stdout_path, "wb") if stdout_path else subprocess.PIPE
+ t0 = time.perf_counter()
+ try:
+ proc = subprocess.run([str(c) for c in cmd], cwd=cwd, stdin=stdin, stdout=stdout, stderr=subprocess.PIPE,
+ env={**os.environ, **(env or {})}, timeout=timeout)
+ return RunResult(proc.returncode, time.perf_counter() - t0, 0.0, 0.0, proc.stdout or b"", proc.stderr or b"")
+ finally:
+ if stdin_path:
+ stdin.close()
+ if stdout_path:
+ stdout.close()
+
+
+def run_measured(cmd: list[str], cwd: Path | None = None, stdin_path: Path | None = None, stdout_path: Path | None = None,
+ env: dict | None = None, timeout: float | None = None) -> RunResult:
+ """Runs a command and reports its wall time, CPU time (user+sys, including reaped children) and peak RSS."""
+ if not hasattr(os, "wait4"):
+ return _run_measured_psutil(cmd, cwd, stdin_path, stdout_path, env, timeout)
+ import tempfile
+ stdin = open(stdin_path, "rb") if stdin_path else subprocess.DEVNULL
+ stdout = open(stdout_path, "wb") if stdout_path else subprocess.PIPE
+ errtmp = tempfile.TemporaryFile()
+ outtmp = None if stdout_path else tempfile.TemporaryFile()
+ t0 = time.perf_counter()
+ try:
+ proc = subprocess.Popen([str(c) for c in cmd], cwd=cwd, stdin=stdin, stdout=outtmp if outtmp else stdout,
+ stderr=errtmp, env={**os.environ, **(env or {})})
+ deadline = None if timeout is None else t0 + timeout
+ while True:
+ pid, status, ru = os.wait4(proc.pid, os.WNOHANG)
+ if pid != 0:
+ break
+ if deadline and time.perf_counter() > deadline:
+ proc.kill()
+ pid, status, ru = os.wait4(proc.pid, 0)
+ break
+ time.sleep(0.005)
+ wall = time.perf_counter() - t0
+ proc.returncode = os.waitstatus_to_exitcode(status)
+ errtmp.seek(0)
+ err = errtmp.read()
+ out = b""
+ if outtmp:
+ outtmp.seek(0)
+ out = outtmp.read()
+ rss = ru.ru_maxrss / (1024.0 * 1024.0) if IS_MAC else ru.ru_maxrss / 1024.0
+ return RunResult(proc.returncode, wall, ru.ru_utime + ru.ru_stime, rss, out, err)
+ finally:
+ errtmp.close()
+ if outtmp:
+ outtmp.close()
+ if stdin_path:
+ stdin.close()
+ if stdout_path:
+ stdout.close()
+
+
+def _run_measured_psutil(cmd, cwd, stdin_path, stdout_path, env, timeout) -> RunResult:
+ import psutil
+ stdin = open(stdin_path, "rb") if stdin_path else subprocess.DEVNULL
+ stdout = open(stdout_path, "wb") if stdout_path else subprocess.PIPE
+ t0 = time.perf_counter()
+ try:
+ proc = psutil.Popen([str(c) for c in cmd], cwd=cwd, stdin=stdin, stdout=stdout, stderr=subprocess.PIPE,
+ env={**os.environ, **(env or {})})
+ peak, cpu = 0.0, 0.0
+ while proc.poll() is None:
+ try:
+ mi = proc.memory_info()
+ peak = max(peak, mi.rss / (1024.0 * 1024.0))
+ ct = proc.cpu_times()
+ cpu = ct.user + ct.system
+ except psutil.Error:
+ pass
+ if timeout and time.perf_counter() - t0 > timeout:
+ proc.kill()
+ break
+ time.sleep(0.02)
+ out, err = proc.communicate()
+ return RunResult(proc.returncode, time.perf_counter() - t0, cpu, peak, out or b"", err or b"")
+ finally:
+ if stdin_path:
+ stdin.close()
+ if stdout_path:
+ stdout.close()
+
+
+def git_commit(path: Path = ROOT) -> str:
+ try:
+ out = subprocess.run(["git", "-C", str(path), "rev-parse", "--short=12", "HEAD"], capture_output=True, text=True)
+ rev = out.stdout.strip() or "unknown"
+ dirty = subprocess.run(["git", "-C", str(path), "status", "--porcelain", "--untracked-files=no"], capture_output=True, text=True)
+ return rev + ("-dirty" if dirty.stdout.strip() else "")
+ except OSError:
+ return "unknown"
+
+
+def ffmpeg_version() -> str:
+ try:
+ out = subprocess.run([FFMPEG, "-hide_banner", "-version"], capture_output=True, text=True)
+ return out.stdout.splitlines()[0]
+ except OSError:
+ return "missing"
+
+
+def log(msg: str) -> None:
+ sys.stderr.write(time.strftime("%H:%M:%S ") + msg + "\n")
+ sys.stderr.flush()
+
+
+@dataclass
+class Cache:
+ root: Path = CACHE_DIR
+ enabled: bool = True
+
+ def dir(self, kind: str, key: str) -> Path:
+ d = self.root / kind / key[:2] / key
+ return d
+
+ def get_json(self, kind: str, key: str) -> dict | None:
+ if not self.enabled:
+ return None
+ p = self.dir(kind, key) / "result.json"
+ if p.exists():
+ try:
+ return json.loads(p.read_text())
+ except json.JSONDecodeError:
+ return None
+ return None
+
+ def put_json(self, kind: str, key: str, obj: dict) -> None:
+ d = self.dir(kind, key)
+ d.mkdir(parents=True, exist_ok=True)
+ tmp = d / "result.json.tmp"
+ tmp.write_text(json.dumps(obj, indent=1, sort_keys=True))
+ tmp.replace(d / "result.json")
diff --git a/capcodec/bench/harness/corpus.py b/capcodec/bench/harness/corpus.py
new file mode 100644
index 000000000..e49453775
--- /dev/null
+++ b/capcodec/bench/harness/corpus.py
@@ -0,0 +1,175 @@
+import json
+import math
+from dataclasses import dataclass, field
+from fractions import Fraction
+from pathlib import Path
+
+from .common import CACHE_DIR, CORPUS_DIR, FFMPEG, MANIFEST, key_of, log, run
+
+CONVERSION_VERSION = "bt709-limited-lanczos-v1"
+
+
+@dataclass
+class Clip:
+ name: str
+ file: Path
+ width: int
+ height: int
+ fps: Fraction
+ frames: int
+ sha256: str
+ tags: list[str]
+ text_regions: list[list[int]]
+ sideinfo: Path | None
+ description: str = ""
+
+ @property
+ def available(self) -> bool:
+ return self.file.exists()
+
+
+@dataclass
+class Source:
+ clip: Clip
+ path: Path
+ width: int
+ height: int
+ fps: Fraction
+ frames: int
+ id: str
+ sideinfo: Path | None
+ text_regions: list[list[int]] = field(default_factory=list)
+
+ @property
+ def name(self) -> str:
+ return self.clip.name
+
+ @property
+ def frame_bytes(self) -> int:
+ return self.width * self.height * 3 // 2
+
+ @property
+ def fps_float(self) -> float:
+ return float(self.fps)
+
+ @property
+ def fps_arg(self) -> str:
+ return f"{self.fps.numerator}/{self.fps.denominator}"
+
+ @property
+ def duration_s(self) -> float:
+ return self.frames / float(self.fps)
+
+ def describe(self) -> dict:
+ return {"clip": self.name, "width": self.width, "height": self.height, "fps": self.fps_arg,
+ "frames": self.frames, "id": self.id}
+
+
+def load_manifest(path: Path = MANIFEST) -> list[Clip]:
+ if not path.exists():
+ return []
+ data = json.loads(path.read_text())
+ clips = []
+ for c in data.get("clips", []):
+ fps = Fraction(str(c.get("fps", 30))).limit_denominator(1001)
+ side = c.get("sideinfo")
+ clips.append(Clip(
+ name=c["name"],
+ file=CORPUS_DIR / c["file"],
+ width=int(c["width"]),
+ height=int(c["height"]),
+ fps=fps,
+ frames=int(c["frames"]),
+ sha256=c.get("sha256", ""),
+ tags=list(c.get("tags", [])),
+ text_regions=[list(map(int, r)) for r in c.get("text_regions", [])],
+ sideinfo=(CORPUS_DIR / side) if side else None,
+ description=c.get("description", ""),
+ ))
+ return clips
+
+
+def even(v: float) -> int:
+ return max(2, int(round(v / 2.0)) * 2)
+
+
+def target_size(clip: Clip, max_height: int | None) -> tuple[int, int]:
+ if max_height is None or clip.height <= max_height:
+ return clip.width, clip.height
+ scale = max_height / clip.height
+ return even(clip.width * scale), even(max_height)
+
+
+def prepare_source(clip: Clip, max_height: int | None, max_seconds: float | None) -> Source:
+ width, height = target_size(clip, max_height)
+ frames = clip.frames
+ if max_seconds is not None:
+ frames = min(frames, int(math.floor(max_seconds * float(clip.fps) + 1e-6)))
+ sid = key_of("source", clip.name, clip.sha256, width, height, clip.fps.numerator, clip.fps.denominator, frames,
+ CONVERSION_VERSION)
+ out_dir = CACHE_DIR / "sources"
+ out_dir.mkdir(parents=True, exist_ok=True)
+ yuv = out_dir / f"{clip.name}_{width}x{height}_{frames}f_{sid[:10]}.yuv"
+ expected = width * height * 3 // 2 * frames
+ if not yuv.exists() or yuv.stat().st_size != expected:
+ log(f"prepare source {clip.name} {width}x{height} {frames} frames")
+ tmp = yuv.with_suffix(".tmp")
+ vf = (f"scale={width}:{height}:flags=lanczos+accurate_rnd+full_chroma_int:in_range=pc:out_range=tv:"
+ f"out_color_matrix=bt709,format=yuv420p")
+ cmd = [FFMPEG, "-hide_banner", "-loglevel", "error", "-y", "-i", str(clip.file), "-frames:v", str(frames),
+ "-vf", vf, "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "yuv420p", str(tmp)]
+ r = run(cmd)
+ if r.returncode != 0:
+ raise RuntimeError(f"source conversion failed for {clip.name}: {r.stderr.decode(errors='replace')}")
+ got = tmp.stat().st_size
+ if got != expected:
+ frames = got // (width * height * 3 // 2)
+ log(f" {clip.name}: decoded {frames} frames, fewer than requested")
+ sid = key_of("source", clip.name, clip.sha256, width, height, clip.fps.numerator, clip.fps.denominator,
+ frames, CONVERSION_VERSION)
+ yuv = out_dir / f"{clip.name}_{width}x{height}_{frames}f_{sid[:10]}.yuv"
+ tmp.replace(yuv)
+ side = None
+ if clip.sideinfo and clip.sideinfo.exists():
+ side = scaled_sideinfo(clip, width, height, frames, sid)
+ sx = width / clip.width
+ sy = height / clip.height
+ regions = [[int(r[0] * sx), int(r[1] * sy), int(r[2] * sx), int(r[3] * sy)] for r in clip.text_regions]
+ return Source(clip=clip, path=yuv, width=width, height=height, fps=clip.fps, frames=frames, id=sid,
+ sideinfo=side, text_regions=regions)
+
+
+def scaled_sideinfo(clip: Clip, width: int, height: int, frames: int, sid: str) -> Path:
+ out = CACHE_DIR / "sources" / f"{clip.name}_{width}x{height}_{frames}f_{sid[:10]}.sideinfo.jsonl"
+ if out.exists():
+ return out
+ sx = width / clip.width
+ sy = height / clip.height
+ lines = []
+ with open(clip.sideinfo) as f:
+ for i, line in enumerate(f):
+ if i >= frames:
+ break
+ rec = json.loads(line)
+ if sx != 1.0 or sy != 1.0:
+ rec["dirty"] = [scale_rect(r, sx, sy, width, height) for r in rec.get("dirty", [])]
+ if rec.get("cursor"):
+ rec["cursor"] = [int(round(rec["cursor"][0] * sx)), int(round(rec["cursor"][1] * sy))]
+ scrolls = []
+ for s in rec.get("scroll", []):
+ scrolls.append({"rect": scale_rect(s["rect"], sx, sy, width, height),
+ "dx": int(round(s.get("dx", 0) * sx)), "dy": int(round(s.get("dy", 0) * sy))})
+ rec["scroll"] = scrolls
+ lines.append(json.dumps(rec, separators=(",", ":")))
+ tmp = out.with_suffix(".tmp")
+ tmp.write_text("\n".join(lines) + "\n")
+ tmp.replace(out)
+ return out
+
+
+def scale_rect(r, sx, sy, width, height):
+ x0 = int(math.floor(r[0] * sx))
+ y0 = int(math.floor(r[1] * sy))
+ x1 = min(width, int(math.ceil((r[0] + r[2]) * sx)))
+ y1 = min(height, int(math.ceil((r[1] + r[3]) * sy)))
+ return [x0, y0, max(0, x1 - x0), max(0, y1 - y0)]
diff --git a/capcodec/bench/harness/metrics.py b/capcodec/bench/harness/metrics.py
new file mode 100644
index 000000000..8c7a33043
--- /dev/null
+++ b/capcodec/bench/harness/metrics.py
@@ -0,0 +1,480 @@
+import hashlib
+import json
+import math
+import re
+import shutil
+import subprocess
+import tempfile
+from dataclasses import dataclass, field
+from pathlib import Path
+
+import numpy as np
+
+from .common import FFMPEG, FFPROBE, LDECOD, TESSERACT, log, run
+from .corpus import Source
+
+METRICS_VERSION = "m5"
+OCR_WORDS_VERSION = 1
+OCR_WORD_MIN_CONF = 80.0
+OCR_WORD_MIN_COVER = 0.5
+OCR_STRIP = ".,;:!?()[]{}<>\"'`|"
+
+
+@dataclass
+class MetricConfig:
+ psnr: bool = True
+ ssim: bool = True
+ vmaf: bool = False
+ vmaf_subsample: int = 1
+ ocr: bool = False
+ ocr_frames: int = 4
+ crops: bool = True
+ vmaf_threads: int = 1
+
+ def key(self) -> dict:
+ k = {"v": METRICS_VERSION, "psnr": self.psnr, "ssim": self.ssim, "vmaf": self.vmaf,
+ "vmaf_sub": self.vmaf_subsample if self.vmaf else 0, "ocr": self.ocr,
+ "ocr_frames": self.ocr_frames if self.ocr else 0, "crops": self.crops}
+ if self.ocr:
+ k["ocr_words"] = OCR_WORDS_VERSION
+ return k
+
+
+def input_args(path: Path, container: str) -> list[str]:
+ if container == "annexb":
+ return ["-f", "h264", "-i", str(path)]
+ return ["-i", str(path)]
+
+
+def frame_times(path: Path, container: str) -> list[float] | None:
+ if container == "annexb":
+ return None
+ r = run([FFPROBE, "-v", "error", "-select_streams", "v:0", "-show_entries", "packet=pts_time", "-of", "csv=p=0",
+ str(path)])
+ times = []
+ for line in r.stdout.decode().splitlines():
+ line = line.strip().strip(",")
+ if not line or line == "N/A":
+ continue
+ try:
+ times.append(float(line))
+ except ValueError:
+ continue
+ times.sort()
+ return times or None
+
+
+def cfr_map(n_source: int, fps: float, times: list[float] | None, n_decoded: int,
+ frame_map: list[int] | None = None) -> list[int]:
+ if frame_map:
+ out, j = [], 0
+ for k in range(n_source):
+ while j + 1 < len(frame_map) and frame_map[j + 1] <= k:
+ j += 1
+ out.append(min(j, n_decoded - 1))
+ return out
+ if n_decoded == n_source or not times:
+ return [min(k, n_decoded - 1) for k in range(n_source)]
+ t0 = times[0]
+ rel = [t - t0 for t in times[:n_decoded]]
+ out, j = [], 0
+ for k in range(n_source):
+ t = k / fps + 0.5 / fps
+ while j + 1 < len(rel) and rel[j + 1] <= t:
+ j += 1
+ out.append(j)
+ return out
+
+
+def parse_psnr(path: Path) -> list[dict]:
+ rows = []
+ for line in path.read_text().splitlines():
+ d = dict(re.findall(r"(\w+):(\S+)", line))
+ if "mse_y" in d:
+ rows.append({k: float(d[k]) for k in ("mse_y", "mse_u", "mse_v") if k in d})
+ return rows
+
+
+def parse_ssim(path: Path) -> list[dict]:
+ rows = []
+ for line in path.read_text().splitlines():
+ d = dict(re.findall(r"(\w+):(\S+)", line))
+ if "All" in d:
+ rows.append({"ssim_y": float(d.get("Y", "nan")), "ssim": float(d["All"])})
+ return rows
+
+
+def mse_to_psnr(mse: float) -> float:
+ if mse <= 1e-10:
+ return 100.0
+ return min(100.0, 10.0 * math.log10(255.0 * 255.0 / mse))
+
+
+def ocr_read(img: np.ndarray, workdir: Path, tag: str) -> tuple[str, list[list]]:
+ from PIL import Image
+ im = Image.fromarray(img).resize((img.shape[1] * 2, img.shape[0] * 2), Image.Resampling.BICUBIC)
+ p = workdir / f"ocr_{tag}.png"
+ base = workdir / f"ocr_{tag}"
+ im.save(p)
+ run([TESSERACT, str(p), str(base), "--psm", "6", "-l", "eng", "txt", "tsv"], env={"OMP_THREAD_LIMIT": "1"},
+ timeout=300)
+ txt_path, tsv_path = Path(f"{base}.txt"), Path(f"{base}.tsv")
+ text = " ".join(txt_path.read_text(errors="replace").split()) if txt_path.exists() else ""
+ words = parse_tsv_words(tsv_path.read_text(errors="replace")) if tsv_path.exists() else []
+ for f in (p, txt_path, tsv_path):
+ f.unlink(missing_ok=True)
+ return text, words
+
+
+def ocr_text(img: np.ndarray, workdir: Path, tag: str) -> str:
+ return ocr_read(img, workdir, tag)[0]
+
+
+def parse_tsv_words(tsv: str) -> list[list]:
+ words = []
+ for line in tsv.splitlines()[1:]:
+ cols = line.split("\t")
+ if len(cols) < 12 or cols[0] != "5" or not cols[11].strip():
+ continue
+ words.append([cols[11].strip(), float(cols[10]), int(cols[6]), int(cols[7]), int(cols[8]), int(cols[9])])
+ return words
+
+
+def ocr_reference_words(words: list[list]) -> list[list]:
+ out = []
+ for text, conf, x, y, w, h in words:
+ t = text.strip(OCR_STRIP)
+ alnum = sum(c.isalnum() for c in t)
+ if conf >= OCR_WORD_MIN_CONF and alnum >= 2 and alnum * 5 >= len(t) * 3:
+ out.append([t, x, y, w, h])
+ return out
+
+
+def ocr_word_errors(ref_words: list[list], got_words: list[list]) -> tuple[int, int]:
+ errs, total = 0, 0
+ for t, x, y, w, h in ref_words:
+ parts = []
+ for gt, _conf, gx, gy, gw, gh in got_words:
+ ix = min(x + w, gx + gw) - max(x, gx)
+ iy = min(y + h, gy + gh) - max(y, gy)
+ if ix > 0 and iy > 0 and ix * iy >= OCR_WORD_MIN_COVER * min(w * h, gw * gh):
+ parts.append((gx, gt.strip(OCR_STRIP)))
+ got = "".join(p for _, p in sorted(parts))
+ errs += min(substring_distance(t, got), len(t))
+ total += len(t)
+ return errs, total
+
+
+def substring_distance(word: str, text: str) -> int:
+ prev = [0] * (len(text) + 1)
+ for i, cw in enumerate(word, 1):
+ cur = [i] + [0] * len(text)
+ for j, ct in enumerate(text, 1):
+ cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (cw != ct))
+ prev = cur
+ return min(prev)
+
+
+def levenshtein(a: str, b: str) -> int:
+ if a == b:
+ return 0
+ if not a:
+ return len(b)
+ if not b:
+ return len(a)
+ prev = list(range(len(b) + 1))
+ for i, ca in enumerate(a, 1):
+ cur = [i] + [0] * len(b)
+ for j, cb in enumerate(b, 1):
+ cur[j] = min(prev[j] + 1, cur[j - 1] + 1, prev[j - 1] + (ca != cb))
+ prev = cur
+ return prev[-1]
+
+
+def read_frame(f, nbytes: int) -> bytes | None:
+ buf = bytearray()
+ while len(buf) < nbytes:
+ chunk = f.read(nbytes - len(buf))
+ if not chunk:
+ return None if not buf else bytes(buf)
+ buf += chunk
+ return bytes(buf)
+
+
+def y_plane(frame: bytes, w: int, h: int) -> np.ndarray:
+ return np.frombuffer(frame, dtype=np.uint8, count=w * h).reshape(h, w)
+
+
+def to_rgb(frame: bytes, w: int, h: int) -> np.ndarray:
+ y = np.frombuffer(frame, dtype=np.uint8, count=w * h).reshape(h, w).astype(np.float32)
+ u = np.frombuffer(frame, dtype=np.uint8, count=w * h // 4, offset=w * h).reshape(h // 2, w // 2).astype(np.float32)
+ v = np.frombuffer(frame, dtype=np.uint8, count=w * h // 4, offset=w * h * 5 // 4).reshape(h // 2, w // 2).astype(np.float32)
+ u = u.repeat(2, 0).repeat(2, 1) - 128.0
+ v = v.repeat(2, 0).repeat(2, 1) - 128.0
+ yy = (y - 16.0) * (255.0 / 219.0)
+ r = yy + 1.5748 * (255.0 / 224.0) * v
+ g = yy - 0.1873 * (255.0 / 224.0) * u - 0.4681 * (255.0 / 224.0) * v
+ b = yy + 1.8556 * (255.0 / 224.0) * u
+ return np.clip(np.stack([r, g, b], -1), 0, 255).astype(np.uint8)
+
+
+def crop_frames(src: Source) -> list[int]:
+ return [src.frames // 2]
+
+
+def ocr_frame_indices(src: Source, n: int) -> list[int]:
+ if src.frames <= n:
+ return list(range(src.frames))
+ return [int((i + 0.5) * src.frames / n) for i in range(n)]
+
+
+def source_ocr(src: Source, cfg: MetricConfig, cache_dir: Path) -> dict:
+ p = cache_dir / f"ocr_{src.id}_{cfg.ocr_frames}.json"
+ if p.exists():
+ return json.loads(p.read_text())
+ out = {}
+ fb = src.frame_bytes
+ with open(src.path, "rb") as f, tempfile.TemporaryDirectory() as td:
+ for k in ocr_frame_indices(src, cfg.ocr_frames):
+ f.seek(k * fb)
+ frame = f.read(fb)
+ y = y_plane(frame, src.width, src.height)
+ for ri, (x, yy, w, h) in enumerate(src.text_regions):
+ out[f"{k}:{ri}"] = ocr_text(np.ascontiguousarray(y[yy:yy + h, x:x + w]), Path(td), f"s{k}_{ri}")
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(json.dumps(out))
+ return out
+
+
+def source_ocr_words(src: Source, cfg: MetricConfig, cache_dir: Path) -> dict:
+ p = cache_dir / f"ocr_words{OCR_WORDS_VERSION}_{src.id}_{cfg.ocr_frames}.json"
+ if p.exists():
+ return json.loads(p.read_text())
+ out = {}
+ fb = src.frame_bytes
+ with open(src.path, "rb") as f, tempfile.TemporaryDirectory() as td:
+ for k in ocr_frame_indices(src, cfg.ocr_frames):
+ f.seek(k * fb)
+ frame = f.read(fb)
+ y = y_plane(frame, src.width, src.height)
+ for ri, (x, yy, w, h) in enumerate(src.text_regions):
+ _, words = ocr_read(np.ascontiguousarray(y[yy:yy + h, x:x + w]), Path(td), f"w{k}_{ri}")
+ out[f"{k}:{ri}"] = ocr_reference_words(words)
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(json.dumps(out))
+ return out
+
+
+def measure(src: Source, enc_file: Path, container: str, cfg: MetricConfig, workdir: Path, cache_dir: Path,
+ crops_dir: Path | None = None, frame_map: list[int] | None = None) -> dict:
+ workdir.mkdir(parents=True, exist_ok=True)
+ w, h, fb = src.width, src.height, src.frame_bytes
+ times = frame_times(enc_file, container)
+ dec_cmd = [FFMPEG, "-hide_banner", "-v", "error", "-nostdin", "-xerror", "-err_detect",
+ "crccheck+bitstream+buffer+explode", "-threads", "1", *input_args(enc_file, container),
+ "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]
+ dec_err = workdir / "decode_stderr.txt"
+ psnr_log, ssim_log, vmaf_log = workdir / "psnr.log", workdir / "ssim.log", workdir / "vmaf.json"
+ n_out = int(cfg.psnr) + int(cfg.ssim) + int(cfg.vmaf)
+ graph = None
+ if n_out:
+ da = "".join(f"[d{i}]" for i in range(n_out))
+ ra = "".join(f"[r{i}]" for i in range(n_out))
+ parts = [f"[0:v]split={n_out}{da}" if n_out > 1 else "[0:v]null[d0]",
+ f"[1:v]split={n_out}{ra}" if n_out > 1 else "[1:v]null[r0]"]
+ i = 0
+ if cfg.psnr:
+ parts.append(f"[d{i}][r{i}]psnr=stats_file={psnr_log}")
+ i += 1
+ if cfg.ssim:
+ parts.append(f"[d{i}][r{i}]ssim=stats_file={ssim_log}")
+ i += 1
+ if cfg.vmaf:
+ parts.append(f"[d{i}][r{i}]libvmaf=log_fmt=json:log_path={vmaf_log}:n_subsample={cfg.vmaf_subsample}"
+ f":n_threads={cfg.vmaf_threads}")
+ graph = ";".join(parts)
+ met_cmd = [FFMPEG, "-hide_banner", "-v", "error", "-nostdin", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-s",
+ f"{w}x{h}", "-r", src.fps_arg, "-i", "pipe:0", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-s",
+ f"{w}x{h}", "-r", src.fps_arg, "-i", str(src.path), "-lavfi", graph or "[0:v][1:v]psnr", "-f", "null",
+ "-"]
+ met_err = workdir / "metrics_stderr.txt"
+ want_ocr = set(ocr_frame_indices(src, cfg.ocr_frames)) if cfg.ocr and src.text_regions else set()
+ want_crop = set(crop_frames(src)) if cfg.crops and crops_dir else set()
+ decoded_md5: list[str] = []
+ ocr_crops: dict[str, np.ndarray] = {}
+ if frame_map:
+ n_expected = len(frame_map)
+ elif times:
+ n_expected = len(times)
+ else:
+ n_expected = src.frames
+ mapping = cfr_map(src.frames, src.fps_float, times, n_expected, frame_map)
+ with open(dec_err, "wb") as de, open(met_err, "wb") as me:
+ dec = subprocess.Popen(dec_cmd, stdout=subprocess.PIPE, stderr=de, stdin=subprocess.DEVNULL)
+ met = subprocess.Popen(met_cmd, stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=me)
+ cur: bytes | None = None
+ cur_j = -1
+ dec_done = False
+ try:
+ for k, j in enumerate(mapping):
+ while cur_j < j and not dec_done:
+ fr = read_frame(dec.stdout, fb)
+ if fr is None or len(fr) != fb:
+ dec_done = True
+ break
+ decoded_md5.append(hashlib.md5(fr).hexdigest())
+ cur, cur_j = fr, cur_j + 1
+ if cur is None:
+ break
+ met.stdin.write(cur)
+ if k in want_ocr:
+ y = y_plane(cur, w, h)
+ for ri, (x, yy, rw, rh) in enumerate(src.text_regions):
+ ocr_crops[f"{k}:{ri}"] = np.ascontiguousarray(y[yy:yy + rh, x:x + rw])
+ if k in want_crop and crops_dir is not None and src.text_regions:
+ save_crop(cur, src, crops_dir / f"k{k}.png")
+ met.stdin.close()
+ except BrokenPipeError:
+ pass
+ while not dec_done:
+ fr = read_frame(dec.stdout, fb)
+ if fr is None or len(fr) != fb:
+ break
+ decoded_md5.append(hashlib.md5(fr).hexdigest())
+ dec.wait()
+ met.wait()
+ n_dec = len(decoded_md5)
+ result = {"frames_decoded": n_dec, "frames_source": src.frames, "frames_expected": n_expected,
+ "decoded_md5": decoded_md5, "cfr_duplicated": src.frames - len(set(mapping))}
+ dec_stderr = dec_err.read_text(errors="replace").strip()
+ result["decode_ffmpeg_ok"] = dec.returncode == 0 and not dec_stderr and n_dec > 0 and n_dec == n_expected
+ if dec_stderr:
+ result["decode_ffmpeg_error"] = dec_stderr[-2000:]
+ elif n_dec != n_expected:
+ result["decode_ffmpeg_error"] = f"decoded {n_dec} frames, container has {n_expected}"
+ else:
+ result["decode_ffmpeg_error"] = ""
+ if n_dec == 0:
+ result["metrics_error"] = f"no frames decoded: {result['decode_ffmpeg_error'][-300:]}"
+ return result
+ if met.returncode != 0:
+ result["metrics_error"] = (met_err.read_text(errors="replace")[-2000:]
+ or f"metrics ffmpeg exit status {met.returncode}, no output")
+ return result
+ if cfg.psnr and psnr_log.exists():
+ rows = parse_psnr(psnr_log)
+ if rows:
+ my = float(np.mean([r["mse_y"] for r in rows]))
+ mu = float(np.mean([r["mse_u"] for r in rows]))
+ mv = float(np.mean([r["mse_v"] for r in rows]))
+ py, pu, pv = mse_to_psnr(my), mse_to_psnr(mu), mse_to_psnr(mv)
+ result.update({"psnr_y": py, "psnr_u": pu, "psnr_v": pv, "psnr_yuv": (6 * py + pu + pv) / 8.0,
+ "psnr_y_framemean": float(np.mean([mse_to_psnr(r["mse_y"]) for r in rows])),
+ "psnr_y_min": float(min(mse_to_psnr(r["mse_y"]) for r in rows))})
+ if cfg.ssim and ssim_log.exists():
+ rows = parse_ssim(ssim_log)
+ if rows:
+ result["ssim"] = float(np.mean([r["ssim"] for r in rows]))
+ result["ssim_y"] = float(np.mean([r["ssim_y"] for r in rows]))
+ result["ssim_min"] = float(min(r["ssim"] for r in rows))
+ if cfg.vmaf and vmaf_log.exists():
+ v = json.loads(vmaf_log.read_text())
+ scores = [fr["metrics"]["vmaf"] for fr in v.get("frames", []) if "vmaf" in fr.get("metrics", {})]
+ if scores:
+ result["vmaf"] = float(np.mean(scores))
+ result["vmaf_min"] = float(min(scores))
+ result["vmaf_p5"] = float(np.percentile(scores, 5))
+ result["vmaf_frames"] = len(scores)
+ if want_ocr:
+ ref = source_ocr(src, cfg, cache_dir)
+ ref_words = source_ocr_words(src, cfg, cache_dir)
+ errs, total, werrs, wtotal = 0, 0, 0, 0
+ with tempfile.TemporaryDirectory() as td:
+ for key, img in ocr_crops.items():
+ truth = ref.get(key, "")
+ rw = ref_words.get(key, [])
+ if not truth and not rw:
+ continue
+ got, got_words = ocr_read(img, Path(td), key.replace(":", "_"))
+ if truth:
+ errs += levenshtein(got, truth)
+ total += len(truth)
+ e, n = ocr_word_errors(rw, got_words)
+ werrs += e
+ wtotal += n
+ result["ocr_cer"] = errs / total if total else None
+ result["ocr_chars"] = total
+ result["ocr_word_cer"] = werrs / wtotal if wtotal else None
+ result["ocr_word_chars"] = wtotal
+ for p in (psnr_log, ssim_log, vmaf_log):
+ p.unlink(missing_ok=True)
+ return result
+
+
+def save_crop(frame: bytes, src: Source, path: Path) -> None:
+ from PIL import Image
+ x, y, w, h = src.text_regions[0]
+ w = min(w, 640)
+ h = min(h, 360)
+ rgb = to_rgb(frame, src.width, src.height)[y:y + h, x:x + w]
+ path.parent.mkdir(parents=True, exist_ok=True)
+ Image.fromarray(rgb).save(path)
+
+
+def save_source_crops(src: Source, crops_dir: Path) -> None:
+ fb = src.frame_bytes
+ with open(src.path, "rb") as f:
+ for k in crop_frames(src):
+ out = crops_dir / f"k{k}.png"
+ if out.exists() or not src.text_regions:
+ continue
+ f.seek(k * fb)
+ save_crop(f.read(fb), src, out)
+
+
+def annexb_for(enc_file: Path, container: str, workdir: Path) -> Path | None:
+ if container == "annexb":
+ return enc_file
+ out = workdir / "stream.264"
+ r = run([FFMPEG, "-hide_banner", "-v", "error", "-nostdin", "-y", "-i", str(enc_file), "-map", "0:v:0", "-c", "copy",
+ "-bsf:v", "h264_mp4toannexb", "-f", "h264", str(out)])
+ if r.returncode != 0:
+ return None
+ return out
+
+
+def md5_frames(path: Path, fb: int) -> list[str]:
+ out = []
+ with open(path, "rb") as f:
+ while True:
+ fr = read_frame(f, fb)
+ if fr is None or len(fr) != fb:
+ break
+ out.append(hashlib.md5(fr).hexdigest())
+ return out
+
+
+def jm_check(src: Source, enc_file: Path, container: str, workdir: Path) -> dict:
+ if not shutil.which(LDECOD) and not Path(LDECOD).exists():
+ return {"decode_jm_ok": None, "decode_jm_error": "JM ldecod not installed"}
+ td = Path(tempfile.mkdtemp(dir=workdir.parent if workdir.parent.exists() else None))
+ try:
+ stream = annexb_for(enc_file, container, td)
+ if stream is None:
+ return {"decode_jm_ok": False, "decode_jm_error": "could not extract an Annex B stream"}
+ out = td / "jm.yuv"
+ r = run([LDECOD, "-p", f"InputFile={stream}", "-p", f"OutputFile={out}", "-p", "WriteUV=1"], cwd=td,
+ timeout=3600)
+ text = (r.stdout + r.stderr).decode(errors="replace")
+ bad = [ln for ln in text.splitlines() if re.search(r"error|warning|unsupported|concealment", ln, re.I)]
+ if r.returncode != 0 or not out.exists():
+ return {"decode_jm_ok": False, "decode_jm_error": (bad or text.splitlines()[-5:])[-5:]}
+ md5s = md5_frames(out, src.frame_bytes)
+ return {"decode_jm_ok": not bad and len(md5s) > 0, "decode_jm_error": bad[-5:] if bad else "",
+ "jm_md5": md5s}
+ finally:
+ shutil.rmtree(td, ignore_errors=True)
+
+
+def recon_md5(src: Source, recon: Path) -> list[str]:
+ return md5_frames(recon, src.frame_bytes)
diff --git a/capcodec/bench/harness/report.py b/capcodec/bench/harness/report.py
new file mode 100644
index 000000000..3dec5c740
--- /dev/null
+++ b/capcodec/bench/harness/report.py
@@ -0,0 +1,418 @@
+import csv
+import html
+import json
+import math
+import os
+import time
+from pathlib import Path
+
+CSV_FIELDS = ["tier", "kind", "clip", "encoder", "family", "point", "production", "width", "height", "fps", "frames",
+ "bytes", "kbps", "wall_s", "cpu_s", "cpu_fps", "wall_fps", "maxrss_mb", "speed_wall_fps",
+ "speed_cpu_fps", "speed_threads_cpu", "psnr_y", "psnr_u", "psnr_v", "psnr_yuv", "psnr_y_min", "ssim",
+ "ssim_min", "vmaf", "vmaf_min", "vmaf_p5", "ocr_cer", "ocr_word_cer", "frames_decoded", "cfr_duplicated",
+ "decode_ffmpeg_ok", "decode_jm_ok", "jm_match", "recon_match", "ms_total", "ms_analysis", "ms_motion",
+ "ms_mode", "ms_tq", "ms_entropy", "ms_deblock", "frames_coded", "frames_dropped", "match_key", "target",
+ "achieved", "ref_kbps", "ref_wall_fps", "ref_cpu_fps", "speedup_wall", "speedup_cpu", "bitrate_ratio",
+ "prop_static_frames", "prop_static_frame_ms_mean", "prop_p_frame_ms_median", "prop_full_p_frame_ms",
+ "prop_static_vs_full", "prop_fallback_static_frame_ms", "prop_fallback_static_vs_full",
+ "prop_fit_fixed_ms", "prop_fit_full_frame_ms", "error"]
+
+STAGES = ["analysis", "motion", "mode", "tq", "entropy", "deblock"]
+STAGE_COLORS = {"analysis": "#8c564b", "motion": "#1f77b4", "mode": "#ff7f0e", "tq": "#2ca02c",
+ "entropy": "#d62728", "deblock": "#9467bd", "other": "#bbbbbb"}
+
+PALETTE = ["#d62728", "#1f77b4", "#2ca02c", "#ff7f0e", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22",
+ "#17becf", "#393b79", "#637939", "#8c6d31", "#843c39", "#7b4173", "#3182bd", "#e6550d", "#31a354",
+ "#756bb1", "#636363"]
+
+
+def write_csv(rows: list[dict], path: Path) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with open(path, "w", newline="") as f:
+ w = csv.DictWriter(f, fieldnames=CSV_FIELDS, extrasaction="ignore")
+ w.writeheader()
+ for r in sorted(rows, key=lambda r: (r.get("kind", ""), r["clip"], r["encoder"], str(r.get("point")))):
+ rr = dict(r)
+ if rr.get("error"):
+ rr["error"] = str(rr["error"]).replace("\n", " ")[:300]
+ for k, v in rr.items():
+ if isinstance(v, float):
+ rr[k] = f"{v:.4f}"
+ w.writerow(rr)
+
+
+def append_history(path: Path, entry: dict) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with open(path, "a") as f:
+ f.write(json.dumps(entry, sort_keys=True) + "\n")
+
+
+def esc(s) -> str:
+ return html.escape(str(s))
+
+
+def fmt(v, nd=2, pct=False):
+ if v is None or (isinstance(v, float) and math.isnan(v)):
+ return "–"
+ if pct:
+ return f"{v:+.{nd}f}%"
+ if isinstance(v, float):
+ return f"{v:.{nd}f}"
+ return str(v)
+
+
+def svg_rd(rows: list[dict], clip: str, qkey: str, colors: dict, w=520, h=320) -> str:
+ pts = [r for r in rows if r["clip"] == clip and r.get(qkey) is not None and r.get("kbps")]
+ if not pts:
+ return ""
+ xs = [math.log10(r["kbps"]) for r in pts]
+ ys = [r[qkey] for r in pts]
+ x0, x1 = min(xs), max(xs)
+ y0, y1 = min(ys), max(ys)
+ if x1 - x0 < 1e-6:
+ x1 = x0 + 1
+ if y1 - y0 < 1e-6:
+ y1 = y0 + 1
+ pad = 46
+ sx = lambda x: pad + (x - x0) / (x1 - x0) * (w - pad - 12)
+ sy = lambda y: h - pad + 10 - (y - y0) / (y1 - y0) * (h - pad - 10)
+ out = [f'<svg width="{w}" height="{h}" xmlns="http://www.w3.org/2000/svg" class="chart">',
+ f'<rect x="0" y="0" width="{w}" height="{h}" fill="#fff"/>']
+ for i in range(5):
+ yv = y0 + (y1 - y0) * i / 4
+ out.append(f'<line x1="{pad}" x2="{w - 12}" y1="{sy(yv):.1f}" y2="{sy(yv):.1f}" stroke="#eee"/>')
+ out.append(f'<text x="{pad - 4}" y="{sy(yv) + 4:.1f}" font-size="10" text-anchor="end">{yv:.1f}</text>')
+ lo, hi = math.floor(x0 * 4) / 4, math.ceil(x1 * 4) / 4
+ t = lo
+ while t <= hi + 1e-9:
+ if x0 - 1e-9 <= t <= x1 + 1e-9:
+ out.append(f'<line y1="{h - pad + 10}" y2="16" x1="{sx(t):.1f}" x2="{sx(t):.1f}" stroke="#f3f3f3"/>')
+ out.append(f'<text x="{sx(t):.1f}" y="{h - pad + 24}" font-size="10" text-anchor="middle">'
+ f'{10 ** t:.0f}</text>')
+ t += 0.25
+ out.append(f'<text x="{w / 2}" y="{h - 6}" font-size="11" text-anchor="middle">kbps (log)</text>')
+ out.append(f'<text x="12" y="{h / 2}" font-size="11" transform="rotate(-90 12 {h / 2})" text-anchor="middle">'
+ f'{esc(qkey)}</text>')
+ by = {}
+ for r in pts:
+ by.setdefault(r["encoder"], []).append(r)
+ for e, rs in sorted(by.items()):
+ rs.sort(key=lambda r: r["kbps"])
+ c = colors.get(e, "#000")
+ path = " ".join(f"{sx(math.log10(r['kbps'])):.1f},{sy(r[qkey]):.1f}" for r in rs)
+ dash = ' stroke-dasharray="4 3"' if not e.startswith("capcodec") else ' stroke-width="2.5"'
+ out.append(f'<polyline points="{path}" fill="none" stroke="{c}"{dash}><title>{esc(e)}</title></polyline>')
+ for r in rs:
+ mark = "rect" if r.get("production") else "circle"
+ cx, cy = sx(math.log10(r["kbps"])), sy(r[qkey])
+ tip = f"{e} {r['point']}: {r['kbps']:.0f} kbps, {qkey} {r[qkey]:.2f}"
+ if mark == "rect":
+ out.append(f'<rect x="{cx - 4:.1f}" y="{cy - 4:.1f}" width="8" height="8" fill="{c}"><title>'
+ f'{esc(tip)} (production)</title></rect>')
+ else:
+ out.append(f'<circle cx="{cx:.1f}" cy="{cy:.1f}" r="3" fill="{c}"><title>{esc(tip)}</title></circle>')
+ out.append("</svg>")
+ return "".join(out)
+
+
+def svg_scatter(summary: dict, ref: str, w=560, h=340) -> str:
+ pts = []
+ for e, s in summary.items():
+ bd = s.get(f"bd_psnr_yuv_vs_{ref}")
+ fps = s.get("speed_wall_fps_median") or s.get("cpu_fps_median")
+ if bd is not None and fps:
+ pts.append((e, math.log10(fps), bd))
+ if len(pts) < 2:
+ return ""
+ xs = [p[1] for p in pts]
+ ys = [p[2] for p in pts]
+ x0, x1 = min(xs) - 0.1, max(xs) + 0.1
+ y0, y1 = min(ys) - 2, max(ys) + 2
+ pad = 50
+ sx = lambda x: pad + (x - x0) / (x1 - x0) * (w - pad - 20)
+ sy = lambda y: 20 + (y - y0) / (y1 - y0) * (h - pad - 20)
+ out = [f'<svg width="{w}" height="{h}" xmlns="http://www.w3.org/2000/svg" class="chart">',
+ f'<rect width="{w}" height="{h}" fill="#fff"/>']
+ if y0 < 0 < y1:
+ out.append(f'<line x1="{pad}" x2="{w - 20}" y1="{sy(0):.1f}" y2="{sy(0):.1f}" stroke="#999"/>')
+ for e, x, y in pts:
+ c = "#d62728" if e.startswith("capcodec") else "#1f77b4"
+ out.append(f'<circle cx="{sx(x):.1f}" cy="{sy(y):.1f}" r="4" fill="{c}"/>')
+ out.append(f'<text x="{sx(x) + 6:.1f}" y="{sy(y) + 3:.1f}" font-size="10">{esc(e)}</text>')
+ out.append(f'<text x="{w / 2}" y="{h - 8}" font-size="11" text-anchor="middle">encode fps (log; speed run '
+ f'wall fps where measured, else single-thread CPU fps)</text>')
+ out.append(f'<text x="14" y="{h / 2}" font-size="11" transform="rotate(-90 14 {h / 2})" text-anchor="middle">'
+ f'BD-rate vs {esc(ref)} (lower is better)</text>')
+ out.append("</svg>")
+ return "".join(out)
+
+
+def svg_stages(bars: list[tuple[str, dict]], w=760) -> str:
+ if not bars:
+ return ""
+ row_h = 18
+ h = 30 + row_h * len(bars) + 30
+ label_w = 300
+ vmax = max(sum(v for v in d.values()) for _, d in bars) or 1.0
+ sx = (w - label_w - 70) / vmax
+ out = [f'<svg width="{w}" height="{h}" xmlns="http://www.w3.org/2000/svg" class="chart">',
+ f'<rect width="{w}" height="{h}" fill="#fff"/>']
+ x = label_w
+ for i, s in enumerate(STAGES + ["other"]):
+ out.append(f'<rect x="{label_w + i * 70}" y="6" width="10" height="10" fill="{STAGE_COLORS[s]}"/>'
+ f'<text x="{label_w + i * 70 + 13}" y="15" font-size="10">{s}</text>')
+ for i, (label, d) in enumerate(bars):
+ y = 26 + i * row_h
+ out.append(f'<text x="{label_w - 6}" y="{y + 12}" font-size="10" text-anchor="end">{esc(label)}</text>')
+ x = label_w
+ for s in STAGES + ["other"]:
+ v = d.get(s, 0.0)
+ if v <= 0:
+ continue
+ out.append(f'<rect x="{x:.1f}" y="{y}" width="{v * sx:.1f}" height="{row_h - 4}" fill="{STAGE_COLORS[s]}">'
+ f'<title>{esc(label)} {s}: {v:.3f} ms/frame</title></rect>')
+ x += v * sx
+ out.append(f'<text x="{x + 4:.1f}" y="{y + 12}" font-size="10">{sum(d.values()):.2f} ms</text>')
+ out.append("</svg>")
+ return "".join(out)
+
+
+def write_html(path: Path, tier: str, rows: list[dict], summ: dict, refs: list[str], meta: dict,
+ crops_root: Path, notes: list[str]) -> None:
+ summary = summ["summary"]
+ q = [r for r in rows if not r.get("kind") and not r.get("error")]
+ encoders = sorted({r["encoder"] for r in rows})
+ colors = {e: PALETTE[i % len(PALETTE)] for i, e in enumerate(encoders)}
+ clips = sorted({r["clip"] for r in q})
+ qkeys = [k for k in ("psnr_yuv", "vmaf", "ssim") if any(r.get(k) is not None for r in q)]
+ parts = ["<!doctype html><html><head><meta charset='utf-8'><title>capcodec bench: ", esc(tier),
+ "</title><style>body{font-family:system-ui,sans-serif;margin:24px;color:#222}"
+ "table{border-collapse:collapse;font-size:12px;margin:8px 0 20px}td,th{border:1px solid #ddd;"
+ "padding:3px 7px;text-align:right}th{background:#f6f6f6}td:first-child,th:first-child{text-align:left}"
+ ".good{color:#0a7d22;font-weight:600}.bad{color:#b3261e}.chart{border:1px solid #eee;margin:4px}"
+ ".crops{display:flex;flex-wrap:wrap;gap:8px}.crops figure{margin:0}.crops img{image-rendering:pixelated;"
+ "max-width:640px;border:1px solid #ccc}.crops figcaption{font-size:11px}.legend span{display:inline-block;"
+ "margin-right:12px;font-size:12px}h2{margin-top:36px}</style></head><body>"]
+ parts.append(f"<h1>capcodec benchmark — {esc(tier)} tier</h1>")
+ parts.append("<p>" + " · ".join(f"<b>{esc(k)}</b>: {esc(v)}" for k, v in meta.items()) + "</p>")
+ for n in notes:
+ parts.append(f"<p>{esc(n)}</p>")
+ matched = [r for r in rows if r.get("kind") == "matched"]
+ if matched:
+ parts.append("<h2>Encode speed vs x264 veryfast at matched quality</h2><p>For each clip, the target is "
+ "x264 veryfast's quality at CRF 23; each capcodec preset is encoded at the QP that reaches the "
+ "same quality (interpolated, rounded towards higher quality), and both are timed in serial speed "
+ "runs using all cores. Speedup above 1 means capcodec is faster.</p>")
+ encs = sorted({r["encoder"] for r in matched})
+ mclips = sorted({r["clip"] for r in matched})
+ parts.append("<table><tr><th>clip</th>")
+ for e in encs:
+ parts.append(f"<th>{esc(e)}<br>speedup (wall)</th><th>CPU speedup<br>(1 thread)</th>"
+ f"<th>{esc(matched[0]['match_key'])}<br>target → got</th><th>bitrate<br>ratio</th>")
+ parts.append("<th>x264 veryfast<br>wall fps</th></tr>")
+ for c in mclips:
+ parts.append(f"<tr><td>{esc(c)}</td>")
+ ref_fps = None
+ for e in encs:
+ r = next((x for x in matched if x["clip"] == c and x["encoder"] == e), None)
+ if r is None:
+ parts.append("<td>–</td><td>–</td><td>–</td><td>–</td>")
+ continue
+ ref_fps = r["ref_wall_fps"]
+ cls = "good" if r["speedup_wall"] >= 1 else "bad"
+ parts.append(f"<td class='{cls}'>{r['speedup_wall']:.2f}×</td><td>{fmt(r.get('speedup_cpu'))}×</td>"
+ f"<td>{r['target']:.2f} → {r['achieved']:.2f}</td><td>{fmt(r.get('bitrate_ratio'))}</td>")
+ parts.append(f"<td>{fmt(ref_fps, 1)}</td></tr>")
+ parts.append("<tr><th>geometric mean</th>")
+ for e in encs:
+ s = summary.get(e, {})
+ parts.append(f"<th>{fmt(s.get('matched_speedup_wall_geomean'))}×</th>"
+ f"<th>{fmt(s.get('matched_speedup_cpu_geomean'))}×</th><th></th><th></th>")
+ parts.append("<th></th></tr></table>")
+ prodm = summ.get("production") or {}
+ if prodm:
+ pkey = summ.get("production_key", "vmaf")
+ parts.append(f"<h2>Against each Cap production setting</h2><p>For every production point of a Cap surface "
+ f"(squares in the RD plots), the bitrate capcodec needs to reach the same {esc(pkey)}, "
+ f"interpolated on its RD curve (log-rate). Ratio below 1 means capcodec needs fewer bits. "
+ f"Values marked * are extrapolated beyond capcodec's ladder.</p>")
+ for e in sorted(prodm):
+ parts.append(f"<h3>{esc(e)}</h3><table><tr><th>surface</th><th>clip</th><th>production point</th>"
+ f"<th>{esc(pkey)}</th><th>their kbps</th><th>capcodec kbps</th><th>ratio</th></tr>")
+ for surf in sorted(prodm[e]):
+ for clip, c in sorted(prodm[e][surf].items()):
+ cls = "good" if c["ratio"] < 1 else "bad"
+ star = "" if c["interpolated"] else "*"
+ parts.append(f"<tr><td>{esc(surf)}</td><td>{esc(clip)}</td><td>{esc(c['point'])}</td>"
+ f"<td>{c['quality']:.2f}</td><td>{c['their_kbps']:.0f}</td><td>{c['our_kbps']:.0f}{star}</td>"
+ f"<td class='{cls}'>{c['ratio']:.2f}</td></tr>")
+ parts.append("</table>")
+ targets = summ.get("cap_targets") or {}
+ if targets:
+ parts.append("<h2>At Cap's bitrate targets</h2><p>capcodec in bitrate mode (--bitrate B --maxrate 1.5B) "
+ "against each Cap ABR surface at the same bpp point: B = W*H*fps*bpp. Error is the achieved "
+ "average bitrate against B; screen clips undershoot when the encoder reaches its quality floor "
+ "before spending the budget. Deltas are capcodec minus the Cap surface; CPU speedup is "
+ "single-threaded CPU fps.</p>")
+ for e in sorted(targets):
+ for surf in sorted(targets[e]):
+ agg = summary.get(e, {}).get("vs_cap_targets", {}).get(surf, {})
+ parts.append(f"<h3>{esc(e)} vs {esc(surf)}</h3><table><tr><th>clip</th><th>point</th>"
+ "<th>target kbps</th><th>capcodec kbps</th><th>error</th><th>their kbps</th>"
+ "<th>their error</th><th>VMAF</th><th>their VMAF</th><th>ΔVMAF</th><th>ΔPSNR-YUV</th>"
+ "<th>CPU speedup</th></tr>")
+ for clip, pts in sorted(targets[e][surf].items()):
+ for point, c in sorted(pts.items(), key=lambda kv: kv[1]["target_kbps"]):
+ dv = c.get("d_vmaf")
+ cls = "" if dv is None else ("good" if dv >= 0 else "bad")
+ parts.append(f"<tr><td>{esc(clip)}</td><td>{esc(point)}</td><td>{c['target_kbps']:.0f}</td>"
+ f"<td>{c['our_kbps']:.0f}</td><td>{fmt(c['our_err'] * 100, 1, True)}</td>"
+ f"<td>{c['their_kbps']:.0f}</td><td>{fmt(c['their_err'] * 100, 1, True)}</td>"
+ f"<td>{fmt(c.get('vmaf'))}</td><td>{fmt(c.get('their_vmaf'))}</td>"
+ f"<td class='{cls}'>{fmt(dv)}</td><td>{fmt(c.get('d_psnr_yuv'))}</td>"
+ f"<td>{fmt(c.get('cpu_speedup'))}×</td></tr>")
+ if agg:
+ parts.append(f"<tr><th>mean</th><th>{agg['n']}</th><th></th><th></th>"
+ f"<th>|{agg['our_abs_err_mean'] * 100:.1f}%|</th><th></th>"
+ f"<th>|{agg['their_abs_err_mean'] * 100:.1f}%|</th><th></th><th></th>"
+ f"<th>{fmt(agg.get('d_vmaf_mean'))}</th><th>{fmt(agg.get('d_psnr_yuv_mean'))}</th>"
+ f"<th>{fmt(agg.get('cpu_speedup_geomean'))}×</th></tr>")
+ parts.append("</table>")
+ stage_rows = [r for r in rows if (not r.get("kind") or r.get("kind") == "speed") and r.get("ms_total")]
+ if stage_rows:
+ parts.append("<h2>Encode time per frame by stage</h2><p>Milliseconds per input frame, from the encoder's "
+ "own stage timers. Quality runs are single-threaded (CPU time per frame); speed runs use all "
+ "cores (summed across threads). 'other' is input, setup and muxing.</p>")
+ bars = []
+ for r in sorted(stage_rows, key=lambda r: (r.get("kind") or "", r["clip"], r["encoder"], str(r["point"]))):
+ d = {s: r.get(f"ms_{s}") or 0.0 for s in STAGES}
+ d["other"] = max(0.0, r["ms_total"] - sum(d.values()))
+ tag = "speed" if r.get("kind") == "speed" else "1 thread"
+ bars.append((f"{r['clip']} · {r['encoder']} · {r['point']} · {tag}", d))
+ parts.append(svg_stages(bars))
+ prop = [r for r in rows if r.get("kind") == "proportionality"]
+ if prop:
+ parts.append("<h2>Cost proportional to changed area</h2><p>Single-threaded speed runs. Static frame cost is "
+ "the mean time of input frames in which no macroblock changed (dropped or skipped). Full P-frame "
+ "cost is measured explicitly on the same clip with every macroblock forced through full "
+ "analysis. Target: static frames under 1% of a full frame. The fit columns regress frame time "
+ "on the changed fraction.</p><table><tr><th>clip</th><th>static frames</th>"
+ "<th>static frame ms</th><th>full P frame ms</th><th>static / full</th>"
+ "<th>pixel-fallback static ms</th><th>fallback / full</th><th>fit fixed ms</th>"
+ "<th>fit full-frame ms</th><th>median P frame ms</th></tr>")
+ for r in sorted(prop, key=lambda r: r["clip"]):
+ ratio = r.get("prop_static_vs_full")
+ fb = r.get("prop_fallback_static_vs_full")
+ cls = "" if ratio is None else ("good" if ratio < 0.01 else "bad")
+ ratio_s = "–" if ratio is None else f"{ratio * 100:.3f}%"
+ fb_s = "–" if fb is None else f"{fb * 100:.2f}%"
+ parts.append(f"<tr><td>{esc(r['clip'])}</td><td>{fmt(r.get('prop_static_frames'))}</td>"
+ f"<td>{fmt(r.get('prop_static_frame_ms_mean'), 4)}</td>"
+ f"<td>{fmt(r.get('prop_full_p_frame_ms'), 3)}</td>"
+ f"<td class='{cls}'>{ratio_s}</td>"
+ f"<td>{fmt(r.get('prop_fallback_static_frame_ms'), 4)}</td><td>{fb_s}</td>"
+ f"<td>{fmt(r.get('prop_fit_fixed_ms'), 3)}</td><td>{fmt(r.get('prop_fit_full_frame_ms'), 3)}</td>"
+ f"<td>{fmt(r.get('prop_p_frame_ms_median'), 3)}</td></tr>")
+ parts.append("</table>")
+ parts.append("<h2>Summary</h2><table><tr><th>encoder</th><th>encodes</th>")
+ for k in qkeys:
+ for ref in refs:
+ parts.append(f"<th>BD-rate {esc(k)}<br>vs {esc(ref)}</th>")
+ parts.append("<th>CPU fps (1 thread, median)</th><th>speed run wall fps</th><th>decode failures</th>"
+ "<th>errors</th></tr>")
+ for e in encoders:
+ s = summary.get(e, {})
+ parts.append(f"<tr><td><span style='color:{colors[e]}'>■</span> {esc(e)}</td><td>{s.get('encodes', 0)}</td>")
+ for k in qkeys:
+ for ref in refs:
+ v = s.get(f"bd_{k}_vs_{ref}")
+ n = s.get(f"bd_{k}_vs_{ref}_n")
+ cls = "" if v is None else ("good" if v < 0 else "bad")
+ parts.append(f"<td class='{cls}'>{fmt(v, 1, True)}{'' if v is None else f' <small>({n})</small>'}</td>")
+ parts.append(f"<td>{fmt(s.get('cpu_fps_median'), 1)}</td><td>{fmt(s.get('speed_wall_fps_median'), 1)}</td>"
+ f"<td class='{'bad' if s.get('decode_failures') else ''}'>{s.get('decode_failures', 0)}</td>"
+ f"<td>{s.get('errors', 0)}</td></tr>")
+ parts.append("</table><p>BD-rate: average bitrate difference at equal quality, piecewise-cubic interpolation over "
+ "the overlapping quality range, averaged over clips (number of clips in brackets). Negative means "
+ "fewer bits than the reference.</p>")
+ for ref in refs[:1]:
+ sc = svg_scatter(summary, ref)
+ if sc:
+ parts.append(f"<h2>Speed vs compression</h2>{sc}")
+ for k in qkeys:
+ for ref in refs:
+ t = summ["tables"].get(k, {})
+ ent = {key.split("|")[0]: v for key, v in t.items() if key.split("|")[1] == ref}
+ if not ent:
+ continue
+ parts.append(f"<h3>Per-clip BD-rate ({esc(k)}) vs {esc(ref)}</h3><table><tr><th>encoder</th>")
+ parts += [f"<th>{esc(c)}</th>" for c in clips]
+ parts.append("<th>mean</th></tr>")
+ for e in encoders:
+ if e not in ent:
+ continue
+ parts.append(f"<tr><td>{esc(e)}</td>")
+ for c in clips:
+ v = ent[e]["clips"].get(c)
+ cls = "" if v is None else ("good" if v < 0 else "bad")
+ parts.append(f"<td class='{cls}'>{fmt(v, 1, True)}</td>")
+ parts.append(f"<td>{fmt(ent[e]['mean'], 1, True)}</td></tr>")
+ parts.append("</table>")
+ parts.append("<h2>Rate-distortion curves</h2><div class='legend'>")
+ parts += [f"<span><span style='color:{colors[e]}'>■</span> {esc(e)}</span>" for e in encoders]
+ parts.append("</div><p>Squares mark production settings.</p>")
+ for c in clips:
+ parts.append(f"<h3>{esc(c)}</h3><div>")
+ for k in qkeys:
+ parts.append(svg_rd(q, c, k, colors))
+ parts.append("</div>")
+ speed = [r for r in rows if r.get("kind") == "speed"]
+ if speed:
+ parts.append("<h2>Speed runs</h2><p>Serial runs, one at a time, encoder's own threading, wall-clock "
+ "fps.</p><table><tr><th>encoder</th><th>clip</th><th>point</th><th>size</th><th>wall fps</th>"
+ "<th>CPU fps</th><th>cores used</th><th>peak MB</th></tr>")
+ for r in sorted(speed, key=lambda r: (r["encoder"], r["clip"])):
+ parts.append(f"<tr><td>{esc(r['encoder'])}</td><td>{esc(r['clip'])}</td><td>{esc(r['point'])}</td>"
+ f"<td>{r['width']}x{r['height']}@{r['fps']:g}</td><td>{fmt(r.get('speed_wall_fps'), 1)}</td>"
+ f"<td>{fmt(r.get('speed_cpu_fps'), 1)}</td><td>{fmt(r.get('speed_threads_cpu'), 2)}</td>"
+ f"<td>{fmt(r.get('maxrss_mb'), 0)}</td></tr>")
+ parts.append("</table>")
+ if crops_root.exists():
+ parts.append("<h2>Side-by-side crops</h2><p>Middle frame, first text region, decoded output at each "
+ "encoder's production point or its second-highest-quality ladder point.</p>")
+ for c in clips:
+ d = crops_root / c
+ if not d.exists():
+ continue
+ figs = []
+ src_imgs = sorted((d / "source").glob("*.png")) if (d / "source").exists() else []
+ if src_imgs:
+ figs.append(("source (lossless)", src_imgs[0]))
+ for e in encoders:
+ er = sorted([r for r in q if r["clip"] == c and r["encoder"] == e], key=lambda r: r.get("kbps") or 0)
+ if not er:
+ continue
+ prod = [r for r in er if r.get("production")]
+ pick = prod[0] if prod else er[-2] if len(er) >= 2 else er[-1]
+ imgs = sorted((d / f"{e}_{pick['point']}").glob("*.png"))
+ if imgs:
+ figs.append((f"{e} {pick['point']} · {pick['kbps']:.0f} kbps · PSNR-Y {fmt(pick.get('psnr_y'))}",
+ imgs[0]))
+ if figs:
+ parts.append(f"<h3>{esc(c)}</h3><div class='crops'>")
+ for cap, img in figs:
+ rel = os.path.relpath(img, path.parent)
+ parts.append(f"<figure><img src='{esc(rel)}' loading='lazy'><figcaption>{esc(cap)}</figcaption>"
+ f"</figure>")
+ parts.append("</div>")
+ parts.append("<h2>All encodes</h2><table><tr>")
+ cols = ["clip", "encoder", "point", "kbps", "psnr_yuv", "psnr_y", "ssim", "vmaf", "ocr_cer", "ocr_word_cer", "cpu_fps",
+ "maxrss_mb", "decode_ffmpeg_ok", "decode_jm_ok", "jm_match", "recon_match"]
+ parts += [f"<th>{esc(c)}</th>" for c in cols]
+ parts.append("</tr>")
+ for r in sorted(rows, key=lambda r: (r["clip"], r["encoder"], r.get("kbps") or 0)):
+ if r.get("kind"):
+ continue
+ parts.append("<tr>" + "".join(f"<td>{esc(fmt(r.get(c)))}</td>" for c in cols) + "</tr>")
+ parts.append(f"</table><p>Generated {esc(time.strftime('%Y-%m-%d %H:%M:%S'))}.</p></body></html>")
+ path.write_text("".join(parts))
diff --git a/capcodec/bench/harness/runner.py b/capcodec/bench/harness/runner.py
new file mode 100644
index 000000000..f88538c4c
--- /dev/null
+++ b/capcodec/bench/harness/runner.py
@@ -0,0 +1,654 @@
+import os
+import math
+import platform
+import shutil
+import statistics
+import threading
+import time
+import traceback
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from dataclasses import dataclass, field
+from pathlib import Path
+
+from . import bdrate
+from .adapters import registry
+from .adapters.base import Adapter, Point
+from .common import CACHE_DIR, Cache, key_of, log, ncores
+from .corpus import Source, load_manifest, prepare_source
+from .metrics import MetricConfig, jm_check, measure, recon_md5, save_source_crops
+
+SPEED_REPS = int(os.environ.get("CAPCODEC_SPEED_REPS", "3"))
+
+REFERENCE = "x264-veryfast"
+REFERENCE_POINT = "crf23"
+GATE_ENCODER = "capcodec-medium"
+JM_VERSION = "jm19.1-v3"
+STAGES = ["analysis", "motion", "mode", "tq", "entropy", "deblock"]
+PROPORTIONALITY_CLIPS = ["idle", "slow_typing"]
+
+
+@dataclass
+class Tier:
+ name: str
+ clips: list[str] | None
+ max_height: int | None
+ max_seconds: float | None
+ metrics: MetricConfig
+ encoders: list[str] | None
+ jm_families: list[str]
+ speed: bool
+ speed_clips: list[str]
+ playback: bool
+ gate: bool
+ quality_keys: list[str] = field(default_factory=lambda: ["psnr_yuv"])
+ matched_key: str | None = None
+ proportionality: bool = False
+
+
+TIERS = {
+ "smoke": Tier("smoke", ["code_editor", "text_scroll", "slides"], 720, 4.0,
+ MetricConfig(psnr=True, ssim=True, vmaf=False, crops=False),
+ ["capcodec-medium", "x264-veryfast"], ["capcodec"], False, [], False, True, ["psnr_yuv"]),
+ "standard": Tier("standard", None, 1080, 10.0,
+ MetricConfig(psnr=True, ssim=True, vmaf=True, vmaf_subsample=5, crops=True),
+ None, ["capcodec"], True, ["code_editor", "busy_ui", "webcam_overlay"], False, False,
+ ["psnr_yuv", "vmaf", "ssim"], "vmaf", True),
+ "ocr": Tier("ocr", ["code_editor", "slow_typing", "text_scroll", "busy_ui"], 1080, 10.0,
+ MetricConfig(psnr=True, ssim=False, vmaf=True, vmaf_subsample=5, ocr=True, ocr_frames=3, crops=False),
+ None, ["capcodec"], False, [], False, False, ["psnr_yuv", "vmaf"], None, False),
+ "full": Tier("full", None, None, None,
+ MetricConfig(psnr=True, ssim=True, vmaf=True, vmaf_subsample=1, ocr=True, ocr_frames=6, crops=True),
+ None, ["*"], True, ["code_editor", "busy_ui", "webcam_overlay", "busy_ui_60fps", "code_4k"], True,
+ False, ["psnr_yuv", "vmaf", "ssim"], "vmaf", True),
+}
+
+
+class WeightedSlots:
+ def __init__(self, total: int):
+ self.total = total
+ self.used = 0
+ self.cv = threading.Condition()
+
+ def acquire(self, w: int):
+ w = max(1, min(w, self.total))
+ with self.cv:
+ while self.used + w > self.total:
+ self.cv.wait()
+ self.used += w
+ return w
+
+ def release(self, w: int):
+ with self.cv:
+ self.used -= w
+ self.cv.notify_all()
+
+
+def machine_id() -> str:
+ cpu = platform.processor() or ""
+ try:
+ for line in open("/proc/cpuinfo"):
+ if line.startswith("model name"):
+ cpu = line.split(":", 1)[1].strip()
+ break
+ except OSError:
+ pass
+ return f"{platform.node()}|{platform.system()}|{cpu}|{ncores()}"
+
+
+@dataclass
+class Job:
+ adapter: Adapter
+ src: Source
+ point: Point
+ key: str
+
+
+class Bench:
+ def __init__(self, tier: Tier, cache: Cache, out_dir: Path, encoders: list[str] | None, clips: list[str] | None,
+ jobs: int, manifest: Path | None = None):
+ self.tier = tier
+ self.cache = cache
+ self.out_dir = out_dir
+ self.jobs = jobs
+ self.slots = WeightedSlots(jobs)
+ all_adapters = registry()
+ wanted = encoders or tier.encoders
+ self.unavailable: dict[str, str] = {}
+ self.adapters: list[Adapter] = []
+ for a in all_adapters:
+ if wanted and a.name not in wanted and not any(w.endswith("*") and a.name.startswith(w[:-1]) for w in wanted):
+ continue
+ ok, why = a.available()
+ if ok:
+ self.adapters.append(a)
+ else:
+ self.unavailable[a.name] = why
+ clips_all = load_manifest(manifest) if manifest else load_manifest()
+ want_clips = clips or tier.clips
+ self.clips = [c for c in clips_all if c.available and (not want_clips or c.name in want_clips)]
+ if not self.clips and want_clips:
+ self.clips = [c for c in clips_all if c.available][: len(want_clips)]
+ self.rows: list[dict] = []
+ self.lock = threading.Lock()
+ self.anchor: dict[str, float] = {}
+
+ def sources(self) -> list[Source]:
+ out = []
+ for c in self.clips:
+ out.append(prepare_source(c, self.tier.max_height, self.tier.max_seconds))
+ return out
+
+ def points_for(self, a: Adapter, src: Source) -> list[Point]:
+ try:
+ return a.points(self.tier.name, src, anchor_kbps=self.anchor.get(src.id))
+ except TypeError:
+ return a.points(self.tier.name, src)
+
+ def run(self) -> list[dict]:
+ t0 = time.time()
+ srcs = self.sources()
+ crops_root = self.out_dir / "crops"
+ if self.tier.metrics.crops:
+ for s in srcs:
+ save_source_crops(s, crops_root / s.name / "source")
+ ref = [a for a in self.adapters if a.name == REFERENCE]
+ rest = [a for a in self.adapters if a.name != REFERENCE]
+ if ref:
+ self._run_jobs([self._job(ref[0], s, p) for s in srcs for p in self.points_for(ref[0], s)])
+ for s in srcs:
+ for r in self.rows:
+ if r["encoder"] == REFERENCE and r["source_id"] == s.id and r["point"] == "crf23" and r.get("kbps"):
+ self.anchor[s.id] = r["kbps"]
+ self._run_jobs([self._job(a, s, p) for a in rest for s in srcs for p in self.points_for(a, s)])
+ if self.tier.speed:
+ self._speed_runs(srcs)
+ if self.tier.matched_key:
+ self._matched_speed(srcs, self.tier.matched_key)
+ if self.tier.proportionality:
+ self._proportionality(srcs)
+ log(f"{self.tier.name}: {len(self.rows)} encodes in {time.time() - t0:.1f}s")
+ return self.rows
+
+ def _speed(self, a: Adapter, s: Source, p: Point, tag: str = "") -> dict | None:
+ key = key_of("speed", a.identity(), p.params, s.id, machine_id(), tag, SPEED_REPS)
+ res = self.cache.get_json("speed", key)
+ if res is None:
+ d = self.cache.dir("speed", key)
+ if d.exists():
+ shutil.rmtree(d)
+ d.mkdir(parents=True)
+ w = self.slots.acquire(self.jobs)
+ try:
+ log(f"speed {a.name} {s.name} {p.label} {tag}")
+ out = None
+ for _ in range(SPEED_REPS):
+ o = a.encode(s, p, d, speed=True)
+ if o.error is not None:
+ out = o
+ break
+ if out is None or o.run.wall_s < out.run.wall_s:
+ out = o
+ finally:
+ self.slots.release(w)
+ res = {"wall_s": out.run.wall_s, "cpu_s": out.run.cpu_s, "maxrss_mb": out.run.maxrss_mb,
+ "error": out.error, "frames": s.frames, "stats": (out.extra or {}).get("stats"), "reps": SPEED_REPS}
+ for f in d.iterdir():
+ if f.name != "result.json":
+ f.unlink(missing_ok=True) if f.is_file() else shutil.rmtree(f, ignore_errors=True)
+ if out.error is None:
+ self.cache.put_json("speed", key, res)
+ if res.get("error"):
+ log(f"speed run failed: {a.name} {s.name} {p.label}: {str(res['error'])[-300:]}")
+ return None
+ return res
+
+ def _quality_row(self, enc: str, clip: str, point: str) -> dict | None:
+ for r in self.rows:
+ if r["encoder"] == enc and r["clip"] == clip and r["point"] == point and r.get("kind") != "speed" \
+ and not r.get("error"):
+ return r
+ return None
+
+ def _matched_speed(self, srcs: list[Source], qkey: str):
+ ref_adapter = next((a for a in self.adapters if a.name == REFERENCE), None)
+ if ref_adapter is None:
+ return
+ for s in srcs:
+ ref_row = self._quality_row(REFERENCE, s.name, REFERENCE_POINT)
+ if not ref_row or ref_row.get(qkey) is None:
+ continue
+ target = ref_row[qkey]
+ ref_point = next(p for p in self.points_for(ref_adapter, s) if p.label == REFERENCE_POINT)
+ ref_speed = self._speed(ref_adapter, s, ref_point, "matched")
+ if not ref_speed:
+ continue
+ for a in self.adapters:
+ if a.family != "capcodec":
+ continue
+ curve = []
+ pkey = "qp"
+ for r in self.rows:
+ params = r.get("params") or {}
+ if r["encoder"] == a.name and r["clip"] == s.name and not r.get("kind") \
+ and r.get(qkey) is not None and ("qp" in params or "crf" in params):
+ pkey = "crf" if "crf" in params else "qp"
+ curve.append((params[pkey], r[qkey]))
+ if len(curve) < 2:
+ continue
+ curve.sort()
+ qp = matched_qp(curve, target)
+ if qp is None:
+ continue
+ point = Point(f"{pkey}{qp}", {pkey: qp})
+ job = self._job(a, s, point)
+ row = self._quality_row(a.name, s.name, point.label)
+ if row is None:
+ row = self._do_job(job)
+ with self.lock:
+ self.rows.append(row)
+ if row.get(qkey) is None:
+ continue
+ sp = self._speed(a, s, point, "matched")
+ if not sp:
+ continue
+ self.rows.append({
+ "tier": self.tier.name, "kind": "matched", "clip": s.name, "source_id": s.id, "encoder": a.name,
+ "family": a.family, "point": point.label, "width": s.width, "height": s.height,
+ "fps": s.fps_float, "frames": s.frames, "match_key": qkey, "target": target,
+ "achieved": row[qkey], "ref_kbps": ref_row["kbps"], "kbps": row["kbps"],
+ "ref_wall_fps": s.frames / ref_speed["wall_s"], "wall_fps": s.frames / sp["wall_s"],
+ "ref_cpu_fps": ref_row.get("cpu_fps"), "cpu_fps": row.get("cpu_fps"),
+ "speedup_wall": ref_speed["wall_s"] / sp["wall_s"],
+ "speedup_cpu": (row["cpu_fps"] / ref_row["cpu_fps"]) if row.get("cpu_fps") and ref_row.get("cpu_fps") else None,
+ "bitrate_ratio": row["kbps"] / ref_row["kbps"] if ref_row.get("kbps") else None})
+
+ def _proportionality(self, srcs: list[Source]):
+ for s in srcs:
+ for a in self.adapters:
+ if a.family != "capcodec" or a.name != GATE_ENCODER:
+ continue
+ variants = [("normal", {"crf": 28, "threads": 1})]
+ if s.name in PROPORTIONALITY_CLIPS or "idle" in s.name or "typing" in s.name:
+ variants += [("full_analysis", {"crf": 28, "threads": 1, "full-analysis": True}),
+ ("pixel_fallback", {"crf": 28, "threads": 1, "no-sideinfo": True})]
+ out = {}
+ for tag, params in variants:
+ sp = self._speed(a, s, Point(f"crf28-{tag}", params), "prop")
+ if sp and sp.get("stats"):
+ out[tag] = proportionality_stats(sp["stats"])
+ if not out.get("normal"):
+ continue
+ row = {"tier": self.tier.name, "kind": "proportionality", "clip": s.name, "source_id": s.id,
+ "encoder": a.name, "family": a.family, "point": "crf28", "width": s.width,
+ "height": s.height, "fps": s.fps_float, "frames": s.frames, **{f"prop_{k}": v for k, v in
+ out["normal"].items()}}
+ if out.get("full_analysis"):
+ full = out["full_analysis"].get("p_frame_ms_median")
+ row["prop_full_p_frame_ms"] = full
+ static = out["normal"].get("static_frame_ms_mean")
+ if full and static is not None:
+ row["prop_static_vs_full"] = static / full
+ if out.get("pixel_fallback"):
+ fb = out["pixel_fallback"]
+ row["prop_fallback_static_frame_ms"] = fb.get("static_frame_ms_mean")
+ if row.get("prop_full_p_frame_ms") and fb.get("static_frame_ms_mean") is not None:
+ row["prop_fallback_static_vs_full"] = fb["static_frame_ms_mean"] / row["prop_full_p_frame_ms"]
+ self.rows.append(row)
+
+ def _job(self, a: Adapter, src: Source, p: Point) -> Job:
+ return Job(a, src, p, key_of("encode", a.identity(), p.params, src.id))
+
+ def _run_jobs(self, jobs: list[Job]):
+ if not jobs:
+ return
+ with ThreadPoolExecutor(max_workers=self.jobs) as ex:
+ futs = {ex.submit(self._do_job, j): j for j in jobs}
+ for f in as_completed(futs):
+ j = futs[f]
+ try:
+ row = f.result()
+ except Exception:
+ row = self._base_row(j)
+ row["error"] = traceback.format_exc()[-2000:]
+ with self.lock:
+ self.rows.append(row)
+
+ def _base_row(self, j: Job) -> dict:
+ return {"tier": self.tier.name, "clip": j.src.name, "source_id": j.src.id, "encoder": j.adapter.name,
+ "family": j.adapter.family, "point": j.point.label, "params": j.point.params,
+ "production": j.point.production or getattr(j.adapter, "production", False),
+ "width": j.src.width, "height": j.src.height, "fps": j.src.fps_float, "frames": j.src.frames,
+ "key": j.key}
+
+ def _do_job(self, j: Job) -> dict:
+ row = self._base_row(j)
+ enc = self.cache.get_json("encode", j.key)
+ enc_dir = self.cache.dir("encode", j.key)
+ if enc and not (enc_dir / enc.get("file", "")).exists():
+ enc = None
+ if enc is None:
+ w = self.slots.acquire(j.adapter.weight)
+ try:
+ if enc_dir.exists():
+ shutil.rmtree(enc_dir)
+ enc_dir.mkdir(parents=True)
+ log(f"encode {j.adapter.name} {j.src.name} {j.point.label}")
+ out = j.adapter.encode(j.src, j.point, enc_dir)
+ finally:
+ self.slots.release(w)
+ enc = {"file": out.file.name, "container": out.container, "returncode": out.run.returncode,
+ "wall_s": out.run.wall_s, "cpu_s": out.run.cpu_s, "maxrss_mb": out.run.maxrss_mb,
+ "error": out.error, "extra": out.extra, "time": time.time()}
+ if out.file.exists():
+ enc["bytes"] = out.file.stat().st_size
+ if out.recon is not None and out.recon.exists():
+ enc["recon_md5"] = recon_md5(j.src, out.recon)
+ out.recon.unlink()
+ frame_map = out.extra.get("stats", {}).get("frame_map") if out.extra else None
+ if frame_map:
+ enc["frame_map"] = frame_map
+ if out.error is None:
+ self.cache.put_json("encode", j.key, enc)
+ row.update({k: enc.get(k) for k in ("container", "wall_s", "cpu_s", "maxrss_mb", "bytes", "error")})
+ stats = (enc.get("extra") or {}).get("stats") or {}
+ if stats:
+ row.update(stage_columns(stats, j.src.frames))
+ if enc.get("error"):
+ return row
+ nbytes = enc.get("bytes", 0)
+ row["kbps"] = nbytes * 8.0 / 1000.0 / j.src.duration_s
+ row["cpu_fps"] = j.src.frames / enc["cpu_s"] if enc.get("cpu_s") else None
+ row["wall_fps"] = j.src.frames / enc["wall_s"] if enc.get("wall_s") else None
+ mkey = key_of("metrics", j.key, self.tier.metrics.key())
+ met = self.cache.get_json("metrics", mkey)
+ if met is None:
+ w = self.slots.acquire(1)
+ try:
+ crops_dir = self.out_dir / "crops" / j.src.name / f"{j.adapter.name}_{j.point.label}"
+ met = measure(j.src, enc_dir / enc["file"], enc["container"], self.tier.metrics,
+ self.cache.dir("metrics", mkey), CACHE_DIR / "ocr", crops_dir,
+ enc.get("frame_map"))
+ finally:
+ self.slots.release(w)
+ if "metrics_error" not in met:
+ self.cache.put_json("metrics", mkey, met)
+ row.update({k: v for k, v in met.items() if k not in ("decoded_md5",)})
+ dec_md5 = met.get("decoded_md5") or []
+ if enc.get("recon_md5") is not None:
+ row["recon_match"] = enc["recon_md5"] == dec_md5
+ if not row["recon_match"]:
+ row["recon_mismatch_first"] = next(
+ (i for i, (a, b) in enumerate(zip(enc["recon_md5"], dec_md5)) if a != b),
+ min(len(enc["recon_md5"]), len(dec_md5)))
+ fams = self.tier.jm_families
+ if "*" in fams or j.adapter.family in fams:
+ jkey = key_of("jm", j.key, JM_VERSION)
+ jm = self.cache.get_json("jm", jkey)
+ if jm is None:
+ w = self.slots.acquire(1)
+ try:
+ jm = jm_check(j.src, enc_dir / enc["file"], enc["container"], self.cache.dir("jm", jkey))
+ finally:
+ self.slots.release(w)
+ if jm.get("decode_jm_ok") is not None:
+ self.cache.put_json("jm", jkey, jm)
+ row["decode_jm_ok"] = jm.get("decode_jm_ok")
+ row["decode_jm_error"] = jm.get("decode_jm_error")
+ if jm.get("jm_md5") is not None:
+ row["jm_match"] = jm["jm_md5"] == dec_md5
+ return row
+
+ def _speed_runs(self, srcs: list[Source]):
+ chosen = [s for s in srcs if s.name in self.tier.speed_clips] or srcs[:2]
+ for a in self.adapters:
+ if not a.speed_weight:
+ continue
+ for s in chosen:
+ pts = self.points_for(a, s)
+ prod = [p for p in pts if p.production]
+ p = prod[0] if prod else pts[len(pts) // 2 - 1 if len(pts) % 2 == 0 else len(pts) // 2]
+ res = self._speed(a, s, p)
+ if not res:
+ continue
+ row = {"tier": self.tier.name, "kind": "speed", "clip": s.name, "source_id": s.id,
+ "encoder": a.name, "family": a.family, "point": p.label,
+ "width": s.width, "height": s.height, "fps": s.fps_float, "frames": s.frames,
+ "speed_wall_fps": s.frames / res["wall_s"] if res["wall_s"] else None,
+ "speed_cpu_fps": s.frames / res["cpu_s"] if res["cpu_s"] else None,
+ "speed_threads_cpu": res["cpu_s"] / res["wall_s"] if res["wall_s"] else None,
+ "maxrss_mb": res["maxrss_mb"]}
+ row.update(stage_columns(res.get("stats"), s.frames))
+ self.rows.append(row)
+
+
+def matched_qp(curve: list[tuple[int, float]], target: float) -> int | None:
+ best = None
+ for (q0, v0), (q1, v1) in zip(curve, curve[1:]):
+ lo, hi = min(v0, v1), max(v0, v1)
+ if lo <= target <= hi and v0 != v1:
+ best = q0 + (target - v0) * (q1 - q0) / (v1 - v0)
+ break
+ if best is None:
+ if target > max(v for _, v in curve):
+ best = curve[0][0] - 2
+ else:
+ best = curve[-1][0] + 2
+ q = int(best)
+ return max(10, min(51, q))
+
+
+def stage_columns(stats: dict | None, frames: int) -> dict:
+ if not stats or not frames:
+ return {}
+ t = stats.get("time_ms") or {}
+ out = {f"ms_{k}": t[k] / frames for k in STAGES if t.get(k) is not None}
+ if t.get("total") is not None:
+ out["ms_total"] = t["total"] / frames
+ for k in ("frames_coded", "frames_dropped", "changed_mb_fraction"):
+ if stats.get(k) is not None:
+ out[k] = stats[k]
+ return out
+
+
+def proportionality_stats(stats: dict) -> dict:
+ frames = stats.get("frames") or []
+ mbs = stats.get("mbs") or 1
+ pf = [f for f in frames if f.get("type") in ("P", "D")]
+ xs = [f.get("changed_mbs", 0) / mbs for f in pf]
+ ys = [f.get("ms", {}).get("total", 0.0) for f in pf]
+ static = [y for x, y in zip(xs, ys) if x == 0]
+ out = {"frames": len(frames), "static_frames": len(static),
+ "static_frame_ms_mean": statistics.mean(static) if static else None,
+ "p_frame_ms_median": statistics.median(ys) if ys else None,
+ "changed_fraction_mean": statistics.mean(xs) if xs else None}
+ if len(set(xs)) >= 2:
+ mx, my = statistics.mean(xs), statistics.mean(ys)
+ sxx = sum((x - mx) ** 2 for x in xs)
+ slope = sum((x - mx) * (y - my) for x, y in zip(xs, ys)) / sxx if sxx else 0.0
+ out["fit_fixed_ms"] = my - slope * mx
+ out["fit_full_frame_ms"] = my - slope * mx + slope
+ return out
+
+
+def quality_rows(rows: list[dict]) -> list[dict]:
+ return [r for r in rows if not r.get("kind") and not r.get("error")]
+
+
+def bd_table(rows: list[dict], refs: list[str], qkey: str) -> dict:
+ rows = quality_rows(rows)
+ by = {}
+ for r in rows:
+ by.setdefault((r["encoder"], r["clip"]), []).append(r)
+ encoders = sorted({r["encoder"] for r in rows})
+ clips = sorted({r["clip"] for r in rows})
+ out = {}
+ for ref in refs:
+ for e in encoders:
+ vals = {}
+ for c in clips:
+ R = by.get((ref, c), [])
+ T = by.get((e, c), [])
+ if not R or not T:
+ continue
+ v = bdrate.bd_rate([r["kbps"] for r in R], [r.get(qkey) for r in R], [t["kbps"] for t in T],
+ [t.get(qkey) for t in T])
+ if v is not None:
+ vals[c] = v
+ if vals:
+ out[(e, ref)] = {"mean": statistics.mean(vals.values()), "clips": vals, "n": len(vals)}
+ return out
+
+
+def rate_at_quality(curve: list[tuple[float, float]], q: float) -> tuple[float | None, bool]:
+ pts = sorted((qq, r) for r, qq in curve if r and qq is not None)
+ clean = []
+ for qq, r in pts:
+ if clean and (qq <= clean[-1][0] or r <= clean[-1][1]):
+ continue
+ clean.append((qq, r))
+ if len(clean) < 2:
+ return None, False
+ for (q0, r0), (q1, r1) in zip(clean, clean[1:]):
+ if q0 <= q <= q1:
+ t = (q - q0) / (q1 - q0)
+ return math.exp(math.log(r0) + t * (math.log(r1) - math.log(r0))), True
+ (q0, r0), (q1, r1) = (clean[0], clean[1]) if q < clean[0][0] else (clean[-2], clean[-1])
+ t = (q - q0) / (q1 - q0)
+ return math.exp(math.log(r0) + t * (math.log(r1) - math.log(r0))), False
+
+
+def production_matches(rows: list[dict], qkey: str) -> dict:
+ q = quality_rows(rows)
+ prod = [r for r in q if r.get("production") and r.get(qkey) is not None]
+ ours = sorted({r["encoder"] for r in q if r["family"] == "capcodec"})
+ out = {}
+ for e in ours:
+ for pr in prod:
+ curve = [(r["kbps"], r.get(qkey)) for r in q if r["encoder"] == e and r["clip"] == pr["clip"]]
+ rate, inside = rate_at_quality(curve, pr[qkey])
+ if rate is None:
+ continue
+ ent = out.setdefault(e, {}).setdefault(pr["encoder"], {})
+ ent[pr["clip"]] = {"point": pr["point"], "quality": pr[qkey], "their_kbps": pr["kbps"], "our_kbps": rate,
+ "ratio": rate / pr["kbps"], "interpolated": inside,
+ "their_cpu_fps": pr.get("cpu_fps")}
+ return out
+
+
+def cap_target_matches(rows: list[dict]) -> dict:
+ q = quality_rows(rows)
+ theirs = [r for r in q if r["family"] == "cap" and "bpp" in (r.get("params") or {})]
+ out = {}
+ for o in q:
+ target = (o.get("params") or {}).get("bitrate")
+ if o["family"] != "capcodec" or not target or not o.get("kbps"):
+ continue
+ for t in theirs:
+ if t["clip"] != o["clip"] or t["point"] != o["point"] or not t.get("kbps"):
+ continue
+ ent = {"target_kbps": target, "our_kbps": o["kbps"], "their_kbps": t["kbps"],
+ "our_err": o["kbps"] / target - 1.0, "their_err": t["kbps"] / target - 1.0}
+ for k in ("vmaf", "psnr_yuv"):
+ if o.get(k) is not None and t.get(k) is not None:
+ ent[k] = o[k]
+ ent[f"their_{k}"] = t[k]
+ ent[f"d_{k}"] = o[k] - t[k]
+ if o.get("cpu_fps") and t.get("cpu_fps"):
+ ent["cpu_speedup"] = o["cpu_fps"] / t["cpu_fps"]
+ out.setdefault(o["encoder"], {}).setdefault(t["encoder"], {}).setdefault(o["clip"], {})[o["point"]] = ent
+ return out
+
+
+def cap_target_summary(per_clip: dict) -> dict:
+ ents = [e for pts in per_clip.values() for e in pts.values()]
+ s = {"n": len(ents), "our_abs_err_mean": statistics.mean(abs(e["our_err"]) for e in ents),
+ "their_abs_err_mean": statistics.mean(abs(e["their_err"]) for e in ents),
+ "our_over_max": max(e["our_err"] for e in ents), "their_over_max": max(e["their_err"] for e in ents)}
+ for k in ("vmaf", "psnr_yuv"):
+ d = [e[f"d_{k}"] for e in ents if e.get(f"d_{k}") is not None]
+ if d:
+ s[f"d_{k}_mean"] = statistics.mean(d)
+ sp = [e["cpu_speedup"] for e in ents if e.get("cpu_speedup")]
+ if sp:
+ s["cpu_speedup_geomean"] = math.exp(statistics.mean(math.log(v) for v in sp))
+ return s
+
+
+def summarize(rows: list[dict], tier: Tier, refs: list[str]) -> dict:
+ q = quality_rows(rows)
+ encoders = sorted({r["encoder"] for r in rows})
+ summary = {}
+ tables = {k: bd_table(rows, refs, k) for k in tier.quality_keys}
+ for e in encoders:
+ er = [r for r in q if r["encoder"] == e]
+ sr = [r for r in rows if r.get("kind") == "speed" and r["encoder"] == e]
+ s = {
+ "encodes": len(er),
+ "cpu_fps_median": statistics.median([r["cpu_fps"] for r in er if r.get("cpu_fps")]) if any(r.get("cpu_fps") for r in er) else None,
+ "speed_wall_fps_median": statistics.median([r["speed_wall_fps"] for r in sr if r.get("speed_wall_fps")]) if sr else None,
+ "decode_failures": sum(1 for r in er if r.get("decode_ffmpeg_ok") is False or r.get("decode_jm_ok") is False
+ or r.get("recon_match") is False or r.get("jm_match") is False),
+ "errors": sum(1 for r in rows if r["encoder"] == e and r.get("error")),
+ }
+ for k, t in tables.items():
+ for ref in refs:
+ v = t.get((e, ref))
+ if v:
+ s[f"bd_{k}_vs_{ref}"] = v["mean"]
+ s[f"bd_{k}_vs_{ref}_n"] = v["n"]
+ mr = [r for r in rows if r.get("kind") == "matched" and r["encoder"] == e and r.get("speedup_wall")]
+ if mr:
+ s["matched_speedup_wall_geomean"] = math.exp(statistics.mean(math.log(r["speedup_wall"]) for r in mr))
+ s["matched_speedup_wall_min"] = min(r["speedup_wall"] for r in mr)
+ s["matched_speedup_clips"] = {r["clip"]: r["speedup_wall"] for r in mr}
+ cpu = [r["speedup_cpu"] for r in mr if r.get("speedup_cpu")]
+ if cpu:
+ s["matched_speedup_cpu_geomean"] = math.exp(statistics.mean(math.log(v) for v in cpu))
+ pr = [r for r in rows if r.get("kind") == "proportionality" and r["encoder"] == e]
+ if pr:
+ s["static_vs_full"] = {r["clip"]: r.get("prop_static_vs_full") for r in pr if r.get("prop_static_vs_full") is not None}
+ summary[e] = s
+ mkey = tier.matched_key or "psnr_yuv"
+ prodm = production_matches(rows, mkey)
+ for e, per in prodm.items():
+ s = summary.setdefault(e, {})
+ vs = {}
+ for p, clips in per.items():
+ ratios = [c["ratio"] for c in clips.values()]
+ vs[p] = {"bitrate_ratio_geomean": math.exp(statistics.mean(math.log(x) for x in ratios)),
+ "clips": len(ratios), "interpolated": sum(1 for c in clips.values() if c["interpolated"])}
+ s["vs_production"] = vs
+ targets = cap_target_matches(rows)
+ for e, per in targets.items():
+ summary.setdefault(e, {})["vs_cap_targets"] = {surf: cap_target_summary(clips) for surf, clips in per.items()}
+ return {"summary": summary, "tables": {k: {f"{e}|{r}": v for (e, r), v in t.items()} for k, t in tables.items()},
+ "production": prodm, "production_key": mkey, "cap_targets": targets}
+
+
+def gate(summary: dict, best: dict | None) -> tuple[bool, list[str]]:
+ msgs = []
+ ok = True
+ s = summary.get(GATE_ENCODER)
+ for e, v in summary.items():
+ if v.get("decode_failures"):
+ ok = False
+ msgs.append(f"FAIL decode check: {e} has {v['decode_failures']} failing encodes")
+ if v.get("errors"):
+ ok = False
+ msgs.append(f"FAIL {e}: {v['errors']} encodes errored")
+ if s is None:
+ msgs.append(f"{GATE_ENCODER} not run; gate checks decode only")
+ return ok, msgs
+ bd = s.get(f"bd_psnr_yuv_vs_{REFERENCE}")
+ fps = s.get("cpu_fps_median")
+ if best:
+ b_bd, b_fps = best.get("bd_psnr_yuv"), best.get("cpu_fps")
+ if bd is not None and b_bd is not None and bd > b_bd + 1.0:
+ ok = False
+ msgs.append(f"FAIL BD-rate regressed: {bd:+.2f}% vs best {b_bd:+.2f}% (limit +1.0)")
+ if fps is not None and b_fps and fps < 0.9 * b_fps:
+ ok = False
+ msgs.append(f"FAIL speed regressed: {fps:.1f} cpu-fps vs best {b_fps:.1f} (limit -10%)")
+ msgs.append(f"{GATE_ENCODER}: BD-rate(PSNR-YUV) vs {REFERENCE} = "
+ f"{'n/a' if bd is None else f'{bd:+.2f}%'}, cpu-fps median = {'n/a' if fps is None else f'{fps:.1f}'}")
+ return ok, msgs
diff --git a/capcodec/bench/history.jsonl b/capcodec/bench/history.jsonl
new file mode 100644
index 000000000..8ebd93a0d
--- /dev/null
+++ b/capcodec/bench/history.jsonl
@@ -0,0 +1,9 @@
+{"clips": ["code_editor", "text_scroll", "slides"], "commit": "c998c8842198-dirty", "elapsed_s": 0.3, "gate": {"messages": ["capcodec-medium: BD-rate(PSNR-YUV) vs x264-veryfast = +15.00%, cpu-fps median = 39.3"], "ok": true}, "machine": "cursor|Linux|Intel(R) Xeon(R) Processor|4", "summary": {"capcodec-medium": {"bd_psnr_yuv_vs_x264-veryfast": 14.996833559563981, "bd_psnr_yuv_vs_x264-veryfast_n": 3, "cpu_fps_median": 39.326301135251995, "decode_failures": 0, "encodes": 15, "errors": 0, "speed_wall_fps_median": null}, "x264-veryfast": {"bd_psnr_yuv_vs_x264-veryfast": 0.0, "bd_psnr_yuv_vs_x264-veryfast_n": 3, "cpu_fps_median": 207.56890546232756, "decode_failures": 0, "encodes": 12, "errors": 0, "speed_wall_fps_median": null}}, "tier": "smoke", "time": "2026-10-07T05:27:32"}
+{"clips": ["code_editor", "text_scroll", "slides"], "commit": "ad7b7ccb74a0-dirty", "elapsed_s": 9.1, "gate": {"messages": ["capcodec-medium: BD-rate(PSNR-YUV) vs x264-veryfast = +13.99%, cpu-fps median = 105.2"], "ok": true}, "machine": "cursor|Linux|Intel(R) Xeon(R) Processor|4", "summary": {"capcodec-medium": {"bd_psnr_yuv_vs_x264-veryfast": 13.991711763793969, "bd_psnr_yuv_vs_x264-veryfast_n": 3, "cpu_fps_median": 105.17145576576213, "decode_failures": 0, "encodes": 15, "errors": 0, "speed_wall_fps_median": null}, "x264-veryfast": {"bd_psnr_yuv_vs_x264-veryfast": 0.0, "bd_psnr_yuv_vs_x264-veryfast_n": 3, "cpu_fps_median": 207.56890546232756, "decode_failures": 0, "encodes": 12, "errors": 0, "speed_wall_fps_median": null}}, "tier": "smoke", "time": "2026-10-07T05:44:10"}
+{"clips": ["code_editor", "text_scroll", "slides", "busy_ui", "full_motion"], "commit": "6917bc5f13fb-dirty", "elapsed_s": 356.8, "gate": null, "machine": "cursor|Linux|Intel(R) Xeon(R) Processor|4", "summary": {"capcodec-live": {"bd_psnr_yuv_vs_x264-veryfast": 26.590809732383793, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_x264-veryfast": 31.55772782531878, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_x264-veryfast": 17.517178944159866, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 159.25876031515838, "decode_failures": 0, "encodes": 28, "errors": 0, "matched_speedup_clips": {"busy_ui": 1.6027942515506715, "code_editor": 1.570706681376886, "full_motion": 0.17260613643507072, "slides": 0.6952361824351686, "text_scroll": 0.5667142825294141}, "matched_speedup_cpu_geomean": 1.3940068454860552, "matched_speedup_wall_geomean": 0.7025951128929889, "matched_speedup_wall_min": 0.17260613643507072, "speed_wall_fps_median": 507.2924461828651}, "capcodec-medium": {"bd_psnr_yuv_vs_x264-veryfast": 16.67637911786774, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_x264-veryfast": 23.170475085408, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_x264-veryfast": 10.70515346152424, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 140.83975232261855, "decode_failures": 0, "encodes": 28, "errors": 0, "matched_speedup_clips": {"busy_ui": 1.4886503902992048, "code_editor": 1.531641285282068, "full_motion": 0.10830402036065169, "slides": 0.6157483298659282, "text_scroll": 0.44656198826799764}, "matched_speedup_cpu_geomean": 1.1819777951184138, "matched_speedup_wall_geomean": 0.5839502795968571, "matched_speedup_wall_min": 0.10830402036065169, "speed_wall_fps_median": 517.1314491410367, "static_vs_full": {}}, "x264-veryfast": {"bd_psnr_yuv_vs_x264-veryfast": 0.0, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_x264-veryfast": 0.0, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_x264-veryfast": 0.0, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 107.32664081999883, "decode_failures": 0, "encodes": 20, "errors": 0, "speed_wall_fps_median": 318.683973315324}}, "tier": "standard", "time": "2026-10-07T07:21:24"}
+{"clips": ["slides", "full_motion"], "commit": "6917bc5f13fb-dirty", "elapsed_s": 257.8, "gate": null, "machine": "cursor|Linux|Intel(R) Xeon(R) Processor|4", "summary": {"capcodec-live": {"bd_psnr_yuv_vs_x264-veryfast": 50.017245539568364, "bd_psnr_yuv_vs_x264-veryfast_n": 2, "bd_ssim_vs_x264-veryfast": 56.50831158069045, "bd_ssim_vs_x264-veryfast_n": 2, "bd_vmaf_vs_x264-veryfast": 30.51561858805754, "bd_vmaf_vs_x264-veryfast_n": 2, "cpu_fps_median": 148.58598150698876, "decode_failures": 0, "encodes": 11, "errors": 0, "matched_speedup_clips": {"full_motion": 0.17404396456749066, "slides": 0.7340279408556696}, "matched_speedup_cpu_geomean": 0.8490621395463752, "matched_speedup_wall_geomean": 0.3574257026709639, "matched_speedup_wall_min": 0.17404396456749066, "speed_wall_fps_median": 110.92917277646109}, "capcodec-medium": {"bd_psnr_yuv_vs_x264-veryfast": 27.463893290129203, "bd_psnr_yuv_vs_x264-veryfast_n": 2, "bd_ssim_vs_x264-veryfast": 36.975934651185625, "bd_ssim_vs_x264-veryfast_n": 2, "bd_vmaf_vs_x264-veryfast": 16.07353404320849, "bd_vmaf_vs_x264-veryfast_n": 2, "cpu_fps_median": 136.00575576358392, "decode_failures": 0, "encodes": 11, "errors": 0, "matched_speedup_clips": {"full_motion": 0.11041925565857949, "slides": 0.6335158768124995}, "matched_speedup_cpu_geomean": 0.6444965970440536, "matched_speedup_wall_geomean": 0.26448506870053845, "matched_speedup_wall_min": 0.11041925565857949, "speed_wall_fps_median": 91.10998488797684, "static_vs_full": {}}, "x264-veryfast": {"bd_psnr_yuv_vs_x264-veryfast": 0.0, "bd_psnr_yuv_vs_x264-veryfast_n": 2, "bd_ssim_vs_x264-veryfast": 0.0, "bd_ssim_vs_x264-veryfast_n": 2, "bd_vmaf_vs_x264-veryfast": 0.0, "bd_vmaf_vs_x264-veryfast_n": 2, "cpu_fps_median": 80.61629996687034, "decode_failures": 0, "encodes": 8, "errors": 0, "speed_wall_fps_median": 214.49318029549414}}, "tier": "standard", "time": "2026-10-07T07:27:02"}
+{"clips": ["code_editor", "text_scroll", "slides", "busy_ui", "full_motion"], "commit": "34d45a01f708", "elapsed_s": 1105.2, "gate": null, "machine": "cursor|Linux|Intel(R) Xeon(R) Processor|4", "summary": {"cap-browser-export": {"bd_psnr_yuv_vs_cap-browser-export": 0.0, "bd_psnr_yuv_vs_cap-browser-export_n": 3, "bd_psnr_yuv_vs_cap-export-crf": 242.81507921252393, "bd_psnr_yuv_vs_cap-export-crf_n": 3, "bd_psnr_yuv_vs_cap-export-x264": 46.003854357088734, "bd_psnr_yuv_vs_cap-export-x264_n": 1, "bd_psnr_yuv_vs_cap-ms-edit": 312.73077780226515, "bd_psnr_yuv_vs_cap-ms-edit_n": 3, "bd_psnr_yuv_vs_cap-ms-transcode": 336.487307761783, "bd_psnr_yuv_vs_cap-ms-transcode_n": 3, "bd_psnr_yuv_vs_cap-rec-linux": -60.531421023621924, "bd_psnr_yuv_vs_cap-rec-linux_n": 1, "bd_psnr_yuv_vs_cap-rf-transcode": 93.84135636345346, "bd_psnr_yuv_vs_cap-rf-transcode_n": 3, "bd_psnr_yuv_vs_cap-web-recorder": -0.2472056790166081, "bd_psnr_yuv_vs_cap-web-recorder_n": 3, "bd_psnr_yuv_vs_x264-veryfast": 242.41216140671514, "bd_psnr_yuv_vs_x264-veryfast_n": 3, "bd_ssim_vs_cap-browser-export": 0.0, "bd_ssim_vs_cap-browser-export_n": 3, "bd_ssim_vs_cap-export-crf": 248.57593892627872, "bd_ssim_vs_cap-export-crf_n": 3, "bd_ssim_vs_cap-export-x264": 78.85313538539623, "bd_ssim_vs_cap-export-x264_n": 1, "bd_ssim_vs_cap-ms-edit": 351.40544780911245, "bd_ssim_vs_cap-ms-edit_n": 3, "bd_ssim_vs_cap-ms-transcode": 347.2836399430552, "bd_ssim_vs_cap-ms-transcode_n": 3, "bd_ssim_vs_cap-rec-linux": -58.31023613841045, "bd_ssim_vs_cap-rec-linux_n": 1, "bd_ssim_vs_cap-rf-transcode": 104.65575689396834, "bd_ssim_vs_cap-rf-transcode_n": 3, "bd_ssim_vs_cap-web-recorder": -0.07051303877137667, "bd_ssim_vs_cap-web-recorder_n": 3, "bd_ssim_vs_x264-veryfast": 249.43412749955914, "bd_ssim_vs_x264-veryfast_n": 3, "bd_vmaf_vs_cap-browser-export": 0.0, "bd_vmaf_vs_cap-browser-export_n": 3, "bd_vmaf_vs_cap-export-crf": 285.6871626609122, "bd_vmaf_vs_cap-export-crf_n": 3, "bd_vmaf_vs_cap-export-x264": 54.309119252263336, "bd_vmaf_vs_cap-export-x264_n": 1, "bd_vmaf_vs_cap-ms-edit": 341.5120434632103, "bd_vmaf_vs_cap-ms-edit_n": 3, "bd_vmaf_vs_cap-ms-transcode": 379.2105726325619, "bd_vmaf_vs_cap-ms-transcode_n": 3, "bd_vmaf_vs_cap-rec-linux": -40.4420079660789, "bd_vmaf_vs_cap-rec-linux_n": 1, "bd_vmaf_vs_cap-rf-transcode": 94.56195617361679, "bd_vmaf_vs_cap-rf-transcode_n": 3, "bd_vmaf_vs_cap-web-recorder": -0.27815372146747414, "bd_vmaf_vs_cap-web-recorder_n": 3, "bd_vmaf_vs_x264-veryfast": 250.27754554393346, "bd_vmaf_vs_x264-veryfast_n": 3, "cpu_fps_median": 43.67561794324077, "decode_failures": 0, "encodes": 20, "errors": 0, "speed_wall_fps_median": null}, "cap-export-crf": {"bd_psnr_yuv_vs_cap-browser-export": -70.53424509818984, "bd_psnr_yuv_vs_cap-browser-export_n": 3, "bd_psnr_yuv_vs_cap-export-crf": 0.0, "bd_psnr_yuv_vs_cap-export-crf_n": 5, "bd_psnr_yuv_vs_cap-export-x264": -32.62841667324613, "bd_psnr_yuv_vs_cap-export-x264_n": 2, "bd_psnr_yuv_vs_cap-ms-edit": 60.93003500712981, "bd_psnr_yuv_vs_cap-ms-edit_n": 5, "bd_psnr_yuv_vs_cap-ms-transcode": 60.31170558305415, "bd_psnr_yuv_vs_cap-ms-transcode_n": 5, "bd_psnr_yuv_vs_cap-rec-linux": -72.11566222846947, "bd_psnr_yuv_vs_cap-rec-linux_n": 2, "bd_psnr_yuv_vs_cap-rf-transcode": -43.457522551644004, "bd_psnr_yuv_vs_cap-rf-transcode_n": 5, "bd_psnr_yuv_vs_cap-web-recorder": -63.75508798933567, "bd_psnr_yuv_vs_cap-web-recorder_n": 4, "bd_psnr_yuv_vs_x264-veryfast": -0.36916075337361853, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_cap-browser-export": -71.25055365878917, "bd_ssim_vs_cap-browser-export_n": 3, "bd_ssim_vs_cap-export-crf": 0.0, "bd_ssim_vs_cap-export-crf_n": 5, "bd_ssim_vs_cap-export-x264": -31.78768664433165, "bd_ssim_vs_cap-export-x264_n": 2, "bd_ssim_vs_cap-ms-edit": 62.48945064178668, "bd_ssim_vs_cap-ms-edit_n": 5, "bd_ssim_vs_cap-ms-transcode": 58.37858786729512, "bd_ssim_vs_cap-ms-transcode_n": 5, "bd_ssim_vs_cap-rec-linux": -73.10773609762708, "bd_ssim_vs_cap-rec-linux_n": 2, "bd_ssim_vs_cap-rf-transcode": -43.50841362315374, "bd_ssim_vs_cap-rf-transcode_n": 5, "bd_ssim_vs_cap-web-recorder": -65.92089736158741, "bd_ssim_vs_cap-web-recorder_n": 3, "bd_ssim_vs_x264-veryfast": 0.9508923197905702, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_cap-browser-export": -73.66512092414047, "bd_vmaf_vs_cap-browser-export_n": 3, "bd_vmaf_vs_cap-export-crf": 0.0, "bd_vmaf_vs_cap-export-crf_n": 5, "bd_vmaf_vs_cap-export-x264": -42.744045869985115, "bd_vmaf_vs_cap-export-x264_n": 3, "bd_vmaf_vs_cap-ms-edit": 56.68366702248953, "bd_vmaf_vs_cap-ms-edit_n": 5, "bd_vmaf_vs_cap-ms-transcode": 56.605209193739846, "bd_vmaf_vs_cap-ms-transcode_n": 5, "bd_vmaf_vs_cap-rec-linux": -69.8702365522359, "bd_vmaf_vs_cap-rec-linux_n": 2, "bd_vmaf_vs_cap-rf-transcode": -49.46596296716999, "bd_vmaf_vs_cap-rf-transcode_n": 5, "bd_vmaf_vs_cap-web-recorder": -66.28901955295642, "bd_vmaf_vs_cap-web-recorder_n": 3, "bd_vmaf_vs_x264-veryfast": -11.819334402277917, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 42.3540468973779, "decode_failures": 0, "encodes": 20, "errors": 0, "speed_wall_fps_median": 125.32318659572208}, "cap-export-x264": {"bd_psnr_yuv_vs_cap-browser-export": -31.508657466380896, "bd_psnr_yuv_vs_cap-browser-export_n": 1, "bd_psnr_yuv_vs_cap-export-crf": 61.24668721000983, "bd_psnr_yuv_vs_cap-export-crf_n": 2, "bd_psnr_yuv_vs_cap-export-x264": 0.0, "bd_psnr_yuv_vs_cap-export-x264_n": 5, "bd_psnr_yuv_vs_cap-ms-edit": 190.2306538240627, "bd_psnr_yuv_vs_cap-ms-edit_n": 5, "bd_psnr_yuv_vs_cap-ms-transcode": 199.8921517940393, "bd_psnr_yuv_vs_cap-ms-transcode_n": 4, "bd_psnr_yuv_vs_cap-rec-linux": -35.18082526348379, "bd_psnr_yuv_vs_cap-rec-linux_n": 5, "bd_psnr_yuv_vs_cap-rf-transcode": -1.2394924814120323, "bd_psnr_yuv_vs_cap-rf-transcode_n": 5, "bd_psnr_yuv_vs_x264-veryfast": 64.00235197977989, "bd_psnr_yuv_vs_x264-veryfast_n": 2, "bd_ssim_vs_cap-browser-export": -44.08820410974733, "bd_ssim_vs_cap-browser-export_n": 1, "bd_ssim_vs_cap-export-crf": 57.792017919774665, "bd_ssim_vs_cap-export-crf_n": 2, "bd_ssim_vs_cap-export-x264": 0.0, "bd_ssim_vs_cap-export-x264_n": 5, "bd_ssim_vs_cap-ms-edit": 202.7475147690856, "bd_ssim_vs_cap-ms-edit_n": 5, "bd_ssim_vs_cap-ms-transcode": 197.36203890042444, "bd_ssim_vs_cap-ms-transcode_n": 5, "bd_ssim_vs_cap-rec-linux": -39.52589808567981, "bd_ssim_vs_cap-rec-linux_n": 5, "bd_ssim_vs_cap-rf-transcode": -1.453718507281809, "bd_ssim_vs_cap-rf-transcode_n": 5, "bd_ssim_vs_x264-veryfast": 61.1391470360278, "bd_ssim_vs_x264-veryfast_n": 2, "bd_vmaf_vs_cap-browser-export": -35.19501602719877, "bd_vmaf_vs_cap-browser-export_n": 1, "bd_vmaf_vs_cap-export-crf": 81.97208108094577, "bd_vmaf_vs_cap-export-crf_n": 3, "bd_vmaf_vs_cap-export-x264": 0.0, "bd_vmaf_vs_cap-export-x264_n": 5, "bd_vmaf_vs_cap-ms-edit": 200.3181593378819, "bd_vmaf_vs_cap-ms-edit_n": 5, "bd_vmaf_vs_cap-ms-transcode": 218.75234429970283, "bd_vmaf_vs_cap-ms-transcode_n": 4, "bd_vmaf_vs_cap-rec-linux": -27.01710721981013, "bd_vmaf_vs_cap-rec-linux_n": 5, "bd_vmaf_vs_cap-rf-transcode": -6.982133082296091, "bd_vmaf_vs_cap-rf-transcode_n": 5, "bd_vmaf_vs_x264-veryfast": 53.52049088342207, "bd_vmaf_vs_x264-veryfast_n": 2, "cpu_fps_median": 94.47010855595914, "decode_failures": 0, "encodes": 20, "errors": 0, "speed_wall_fps_median": 288.5232245181399}, "cap-ms-edit": {"bd_psnr_yuv_vs_cap-browser-export": -74.99471887456467, "bd_psnr_yuv_vs_cap-browser-export_n": 3, "bd_psnr_yuv_vs_cap-export-crf": -32.913814507037195, "bd_psnr_yuv_vs_cap-export-crf_n": 5, "bd_psnr_yuv_vs_cap-export-x264": -62.24154576049307, "bd_psnr_yuv_vs_cap-export-x264_n": 5, "bd_psnr_yuv_vs_cap-ms-edit": 0.0, "bd_psnr_yuv_vs_cap-ms-edit_n": 5, "bd_psnr_yuv_vs_cap-ms-transcode": 2.1535814208436777, "bd_psnr_yuv_vs_cap-ms-transcode_n": 5, "bd_psnr_yuv_vs_cap-rec-linux": -79.96278669367088, "bd_psnr_yuv_vs_cap-rec-linux_n": 4, "bd_psnr_yuv_vs_cap-rf-transcode": -62.23335572760981, "bd_psnr_yuv_vs_cap-rf-transcode_n": 5, "bd_psnr_yuv_vs_cap-web-recorder": -76.90464020420067, "bd_psnr_yuv_vs_cap-web-recorder_n": 2, "bd_psnr_yuv_vs_x264-veryfast": -36.46302363692466, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_cap-browser-export": -77.52433848824636, "bd_ssim_vs_cap-browser-export_n": 3, "bd_ssim_vs_cap-export-crf": -33.79944771187631, "bd_ssim_vs_cap-export-crf_n": 5, "bd_ssim_vs_cap-export-x264": -63.61033214945496, "bd_ssim_vs_cap-export-x264_n": 5, "bd_ssim_vs_cap-ms-edit": 0.0, "bd_ssim_vs_cap-ms-edit_n": 5, "bd_ssim_vs_cap-ms-transcode": -0.44990909259608136, "bd_ssim_vs_cap-ms-transcode_n": 5, "bd_ssim_vs_cap-rec-linux": -79.54739440172527, "bd_ssim_vs_cap-rec-linux_n": 5, "bd_ssim_vs_cap-rf-transcode": -63.519995474928436, "bd_ssim_vs_cap-rf-transcode_n": 5, "bd_ssim_vs_x264-veryfast": -38.34674412226972, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_cap-browser-export": -75.82888755337402, "bd_vmaf_vs_cap-browser-export_n": 3, "bd_vmaf_vs_cap-export-crf": -29.827581189356344, "bd_vmaf_vs_cap-export-crf_n": 5, "bd_vmaf_vs_cap-export-x264": -63.57306929854565, "bd_vmaf_vs_cap-export-x264_n": 5, "bd_vmaf_vs_cap-ms-edit": 0.0, "bd_vmaf_vs_cap-ms-edit_n": 5, "bd_vmaf_vs_cap-ms-transcode": 1.7134578276049783, "bd_vmaf_vs_cap-ms-transcode_n": 5, "bd_vmaf_vs_cap-rec-linux": -79.26639946887121, "bd_vmaf_vs_cap-rec-linux_n": 4, "bd_vmaf_vs_cap-rf-transcode": -64.57012084028332, "bd_vmaf_vs_cap-rf-transcode_n": 5, "bd_vmaf_vs_x264-veryfast": -42.84478305645313, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 52.25710202453119, "decode_failures": 0, "encodes": 20, "errors": 0, "speed_wall_fps_median": 203.29020834280843}, "cap-ms-transcode": {"bd_psnr_yuv_vs_cap-browser-export": -76.33305008622071, "bd_psnr_yuv_vs_cap-browser-export_n": 3, "bd_psnr_yuv_vs_cap-export-crf": -33.70176143231447, "bd_psnr_yuv_vs_cap-export-crf_n": 5, "bd_psnr_yuv_vs_cap-export-x264": -63.10224450085725, "bd_psnr_yuv_vs_cap-export-x264_n": 4, "bd_psnr_yuv_vs_cap-ms-edit": -1.9923933333375254, "bd_psnr_yuv_vs_cap-ms-edit_n": 5, "bd_psnr_yuv_vs_cap-ms-transcode": 0.0, "bd_psnr_yuv_vs_cap-ms-transcode_n": 5, "bd_psnr_yuv_vs_cap-rec-linux": -80.56589680985047, "bd_psnr_yuv_vs_cap-rec-linux_n": 2, "bd_psnr_yuv_vs_cap-rf-transcode": -63.231693137222564, "bd_psnr_yuv_vs_cap-rf-transcode_n": 5, "bd_psnr_yuv_vs_cap-web-recorder": -79.82841994885742, "bd_psnr_yuv_vs_cap-web-recorder_n": 3, "bd_psnr_yuv_vs_x264-veryfast": -36.22679486854682, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_cap-browser-export": -77.41977158497627, "bd_ssim_vs_cap-browser-export_n": 3, "bd_ssim_vs_cap-export-crf": -32.594631615821875, "bd_ssim_vs_cap-export-crf_n": 5, "bd_ssim_vs_cap-export-x264": -62.899176483123036, "bd_ssim_vs_cap-export-x264_n": 5, "bd_ssim_vs_cap-ms-edit": 0.5000320817533122, "bd_ssim_vs_cap-ms-edit_n": 5, "bd_ssim_vs_cap-ms-transcode": 0.0, "bd_ssim_vs_cap-ms-transcode_n": 5, "bd_ssim_vs_cap-rec-linux": -80.65396332961971, "bd_ssim_vs_cap-rec-linux_n": 2, "bd_ssim_vs_cap-rf-transcode": -62.86915613181257, "bd_ssim_vs_cap-rf-transcode_n": 5, "bd_ssim_vs_cap-web-recorder": -80.24548839428387, "bd_ssim_vs_cap-web-recorder_n": 3, "bd_ssim_vs_x264-veryfast": -34.49489245627783, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_cap-browser-export": -78.36309691555553, "bd_vmaf_vs_cap-browser-export_n": 3, "bd_vmaf_vs_cap-export-crf": -31.730602054832136, "bd_vmaf_vs_cap-export-crf_n": 5, "bd_vmaf_vs_cap-export-x264": -65.73762428284437, "bd_vmaf_vs_cap-export-x264_n": 4, "bd_vmaf_vs_cap-ms-edit": -1.4585876039851486, "bd_vmaf_vs_cap-ms-edit_n": 5, "bd_vmaf_vs_cap-ms-transcode": 0.0, "bd_vmaf_vs_cap-ms-transcode_n": 5, "bd_vmaf_vs_cap-rec-linux": -78.66334469949935, "bd_vmaf_vs_cap-rec-linux_n": 2, "bd_vmaf_vs_cap-rf-transcode": -65.07729921261304, "bd_vmaf_vs_cap-rf-transcode_n": 5, "bd_vmaf_vs_cap-web-recorder": -80.36578399039786, "bd_vmaf_vs_cap-web-recorder_n": 3, "bd_vmaf_vs_x264-veryfast": -41.55561463799112, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 54.204577353139186, "decode_failures": 0, "encodes": 20, "errors": 0, "speed_wall_fps_median": 208.99745700092126}, "cap-rec-linux": {"bd_psnr_yuv_vs_cap-browser-export": 153.36610182963503, "bd_psnr_yuv_vs_cap-browser-export_n": 1, "bd_psnr_yuv_vs_cap-export-crf": 401.74329925534005, "bd_psnr_yuv_vs_cap-export-crf_n": 2, "bd_psnr_yuv_vs_cap-export-x264": 84.91584372227082, "bd_psnr_yuv_vs_cap-export-x264_n": 5, "bd_psnr_yuv_vs_cap-ms-edit": 455.923847217226, "bd_psnr_yuv_vs_cap-ms-edit_n": 4, "bd_psnr_yuv_vs_cap-ms-transcode": 532.7803929684119, "bd_psnr_yuv_vs_cap-ms-transcode_n": 2, "bd_psnr_yuv_vs_cap-rec-linux": 0.0, "bd_psnr_yuv_vs_cap-rec-linux_n": 5, "bd_psnr_yuv_vs_cap-rf-transcode": 166.57039494634643, "bd_psnr_yuv_vs_cap-rf-transcode_n": 2, "bd_psnr_yuv_vs_cap-web-recorder": 115.63463948622253, "bd_psnr_yuv_vs_cap-web-recorder_n": 1, "bd_psnr_yuv_vs_x264-veryfast": 367.3889085096039, "bd_psnr_yuv_vs_x264-veryfast_n": 2, "bd_ssim_vs_cap-browser-export": 139.8670338647181, "bd_ssim_vs_cap-browser-export_n": 1, "bd_ssim_vs_cap-export-crf": 459.34310662327556, "bd_ssim_vs_cap-export-crf_n": 2, "bd_ssim_vs_cap-export-x264": 109.25897498844603, "bd_ssim_vs_cap-export-x264_n": 5, "bd_ssim_vs_cap-ms-edit": 489.20601422830515, "bd_ssim_vs_cap-ms-edit_n": 5, "bd_ssim_vs_cap-ms-transcode": 602.8572950319916, "bd_ssim_vs_cap-ms-transcode_n": 2, "bd_ssim_vs_cap-rec-linux": 0.0, "bd_ssim_vs_cap-rec-linux_n": 5, "bd_ssim_vs_cap-rf-transcode": 205.98013971301336, "bd_ssim_vs_cap-rf-transcode_n": 2, "bd_ssim_vs_cap-web-recorder": 93.98436689491415, "bd_ssim_vs_cap-web-recorder_n": 1, "bd_ssim_vs_x264-veryfast": 412.1955699235736, "bd_ssim_vs_x264-veryfast_n": 2, "bd_vmaf_vs_cap-browser-export": 67.90357865497758, "bd_vmaf_vs_cap-browser-export_n": 1, "bd_vmaf_vs_cap-export-crf": 292.36123739121365, "bd_vmaf_vs_cap-export-crf_n": 2, "bd_vmaf_vs_cap-export-x264": 54.87250979197879, "bd_vmaf_vs_cap-export-x264_n": 5, "bd_vmaf_vs_cap-ms-edit": 401.5224101205231, "bd_vmaf_vs_cap-ms-edit_n": 4, "bd_vmaf_vs_cap-ms-transcode": 410.1014985868926, "bd_vmaf_vs_cap-ms-transcode_n": 2, "bd_vmaf_vs_cap-rec-linux": 0.0, "bd_vmaf_vs_cap-rec-linux_n": 5, "bd_vmaf_vs_cap-rf-transcode": 104.17919498432417, "bd_vmaf_vs_cap-rf-transcode_n": 2, "bd_vmaf_vs_x264-veryfast": 289.54296068995944, "bd_vmaf_vs_x264-veryfast_n": 1, "cpu_fps_median": 199.8281006070226, "decode_failures": 0, "encodes": 20, "errors": 0, "speed_wall_fps_median": 240.4688194577069}, "cap-rf-transcode": {"bd_psnr_yuv_vs_cap-browser-export": -44.62889742097198, "bd_psnr_yuv_vs_cap-browser-export_n": 3, "bd_psnr_yuv_vs_cap-export-crf": 82.59410723005192, "bd_psnr_yuv_vs_cap-export-crf_n": 5, "bd_psnr_yuv_vs_cap-export-x264": 2.670909213128694, "bd_psnr_yuv_vs_cap-export-x264_n": 5, "bd_psnr_yuv_vs_cap-ms-edit": 195.5518196790618, "bd_psnr_yuv_vs_cap-ms-edit_n": 5, "bd_psnr_yuv_vs_cap-ms-transcode": 198.04351104834976, "bd_psnr_yuv_vs_cap-ms-transcode_n": 5, "bd_psnr_yuv_vs_cap-rec-linux": -57.67224352088294, "bd_psnr_yuv_vs_cap-rec-linux_n": 2, "bd_psnr_yuv_vs_cap-rf-transcode": 0.0, "bd_psnr_yuv_vs_cap-rf-transcode_n": 5, "bd_psnr_yuv_vs_cap-web-recorder": -10.412964712006012, "bd_psnr_yuv_vs_cap-web-recorder_n": 2, "bd_psnr_yuv_vs_x264-veryfast": 73.44454336609449, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_cap-browser-export": -49.76269206991424, "bd_ssim_vs_cap-browser-export_n": 3, "bd_ssim_vs_cap-export-crf": 82.30077880923017, "bd_ssim_vs_cap-export-crf_n": 5, "bd_ssim_vs_cap-export-x264": 3.632412845058601, "bd_ssim_vs_cap-export-x264_n": 5, "bd_ssim_vs_cap-ms-edit": 205.53827665173645, "bd_ssim_vs_cap-ms-edit_n": 5, "bd_ssim_vs_cap-ms-transcode": 196.17849901786417, "bd_ssim_vs_cap-ms-transcode_n": 5, "bd_ssim_vs_cap-rec-linux": -58.58802087206365, "bd_ssim_vs_cap-rec-linux_n": 2, "bd_ssim_vs_cap-rf-transcode": 0.0, "bd_ssim_vs_cap-rf-transcode_n": 5, "bd_ssim_vs_cap-web-recorder": -15.31762325753272, "bd_ssim_vs_cap-web-recorder_n": 1, "bd_ssim_vs_x264-veryfast": 72.38027426384407, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_cap-browser-export": -45.58268136456107, "bd_vmaf_vs_cap-browser-export_n": 3, "bd_vmaf_vs_cap-export-crf": 103.28494146081306, "bd_vmaf_vs_cap-export-crf_n": 5, "bd_vmaf_vs_cap-export-x264": 10.116833653771314, "bd_vmaf_vs_cap-export-x264_n": 5, "bd_vmaf_vs_cap-ms-edit": 229.26183127042017, "bd_vmaf_vs_cap-ms-edit_n": 5, "bd_vmaf_vs_cap-ms-transcode": 221.84807300239018, "bd_vmaf_vs_cap-ms-transcode_n": 5, "bd_vmaf_vs_cap-rec-linux": -47.12302160306196, "bd_vmaf_vs_cap-rec-linux_n": 2, "bd_vmaf_vs_cap-rf-transcode": 0.0, "bd_vmaf_vs_cap-rf-transcode_n": 5, "bd_vmaf_vs_cap-web-recorder": -5.55492283945016, "bd_vmaf_vs_cap-web-recorder_n": 2, "bd_vmaf_vs_x264-veryfast": 69.72581055347601, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 110.05430315328988, "decode_failures": 0, "encodes": 20, "errors": 0, "speed_wall_fps_median": 181.3972046525023}, "cap-web-recorder": {"bd_psnr_yuv_vs_cap-browser-export": 0.4390892697554327, "bd_psnr_yuv_vs_cap-browser-export_n": 3, "bd_psnr_yuv_vs_cap-export-crf": 206.38495485550263, "bd_psnr_yuv_vs_cap-export-crf_n": 4, "bd_psnr_yuv_vs_cap-ms-edit": 333.0132856165943, "bd_psnr_yuv_vs_cap-ms-edit_n": 2, "bd_psnr_yuv_vs_cap-ms-transcode": 400.90155635428636, "bd_psnr_yuv_vs_cap-ms-transcode_n": 3, "bd_psnr_yuv_vs_cap-rec-linux": -53.62526158215444, "bd_psnr_yuv_vs_cap-rec-linux_n": 1, "bd_psnr_yuv_vs_cap-rf-transcode": 11.681723818012557, "bd_psnr_yuv_vs_cap-rf-transcode_n": 2, "bd_psnr_yuv_vs_cap-web-recorder": 0.0, "bd_psnr_yuv_vs_cap-web-recorder_n": 5, "bd_psnr_yuv_vs_x264-veryfast": 191.00063337293864, "bd_psnr_yuv_vs_x264-veryfast_n": 4, "bd_ssim_vs_cap-browser-export": 0.13251034330237962, "bd_ssim_vs_cap-browser-export_n": 3, "bd_ssim_vs_cap-export-crf": 224.0592335820823, "bd_ssim_vs_cap-export-crf_n": 3, "bd_ssim_vs_cap-ms-transcode": 407.8364308582017, "bd_ssim_vs_cap-ms-transcode_n": 3, "bd_ssim_vs_cap-rec-linux": -48.449454148966375, "bd_ssim_vs_cap-rec-linux_n": 1, "bd_ssim_vs_cap-rf-transcode": 18.088324686629996, "bd_ssim_vs_cap-rf-transcode_n": 1, "bd_ssim_vs_cap-web-recorder": 0.0, "bd_ssim_vs_cap-web-recorder_n": 5, "bd_ssim_vs_x264-veryfast": 204.5773581838583, "bd_ssim_vs_x264-veryfast_n": 4, "bd_vmaf_vs_cap-browser-export": 0.4303645239213412, "bd_vmaf_vs_cap-browser-export_n": 3, "bd_vmaf_vs_cap-export-crf": 238.01716958433394, "bd_vmaf_vs_cap-export-crf_n": 3, "bd_vmaf_vs_cap-ms-transcode": 414.35928167738615, "bd_vmaf_vs_cap-ms-transcode_n": 3, "bd_vmaf_vs_cap-rf-transcode": 5.964594272510415, "bd_vmaf_vs_cap-rf-transcode_n": 2, "bd_vmaf_vs_cap-web-recorder": 0.0, "bd_vmaf_vs_cap-web-recorder_n": 5, "bd_vmaf_vs_x264-veryfast": 192.4537368073319, "bd_vmaf_vs_x264-veryfast_n": 4, "cpu_fps_median": 50.63727473178625, "decode_failures": 1, "encodes": 20, "errors": 0, "speed_wall_fps_median": null}, "capcodec-live": {"bd_psnr_yuv_vs_cap-browser-export": -55.410747366506406, "bd_psnr_yuv_vs_cap-browser-export_n": 3, "bd_psnr_yuv_vs_cap-export-crf": 31.532845754588042, "bd_psnr_yuv_vs_cap-export-crf_n": 5, "bd_psnr_yuv_vs_cap-export-x264": -25.208354477003546, "bd_psnr_yuv_vs_cap-export-x264_n": 4, "bd_psnr_yuv_vs_cap-ms-edit": 108.60305550922139, "bd_psnr_yuv_vs_cap-ms-edit_n": 5, "bd_psnr_yuv_vs_cap-ms-transcode": 105.89462281017157, "bd_psnr_yuv_vs_cap-ms-transcode_n": 5, "bd_psnr_yuv_vs_cap-rec-linux": -70.71715684034808, "bd_psnr_yuv_vs_cap-rec-linux_n": 2, "bd_psnr_yuv_vs_cap-rf-transcode": -28.62819662772658, "bd_psnr_yuv_vs_cap-rf-transcode_n": 5, "bd_psnr_yuv_vs_cap-web-recorder": -47.66270685313697, "bd_psnr_yuv_vs_cap-web-recorder_n": 4, "bd_psnr_yuv_vs_x264-veryfast": 21.73488194858836, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_cap-browser-export": -58.76275012578096, "bd_ssim_vs_cap-browser-export_n": 3, "bd_ssim_vs_cap-export-crf": 35.77042769017862, "bd_ssim_vs_cap-export-crf_n": 5, "bd_ssim_vs_cap-export-x264": -22.94646936860606, "bd_ssim_vs_cap-export-x264_n": 4, "bd_ssim_vs_cap-ms-edit": 124.6596683219922, "bd_ssim_vs_cap-ms-edit_n": 5, "bd_ssim_vs_cap-ms-transcode": 108.169913623121, "bd_ssim_vs_cap-ms-transcode_n": 5, "bd_ssim_vs_cap-rec-linux": -71.84273713734285, "bd_ssim_vs_cap-rec-linux_n": 2, "bd_ssim_vs_cap-rf-transcode": -24.749004062976052, "bd_ssim_vs_cap-rf-transcode_n": 5, "bd_ssim_vs_cap-web-recorder": -51.39909972415601, "bd_ssim_vs_cap-web-recorder_n": 4, "bd_ssim_vs_x264-veryfast": 27.16700079223234, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_cap-browser-export": -58.79996832366071, "bd_vmaf_vs_cap-browser-export_n": 3, "bd_vmaf_vs_cap-export-crf": 37.2021968153662, "bd_vmaf_vs_cap-export-crf_n": 5, "bd_vmaf_vs_cap-export-x264": -29.03157872202819, "bd_vmaf_vs_cap-export-x264_n": 5, "bd_vmaf_vs_cap-ms-edit": 114.90032956866438, "bd_vmaf_vs_cap-ms-edit_n": 5, "bd_vmaf_vs_cap-ms-transcode": 109.0897563877457, "bd_vmaf_vs_cap-ms-transcode_n": 5, "bd_vmaf_vs_cap-rec-linux": -62.93387328478616, "bd_vmaf_vs_cap-rec-linux_n": 2, "bd_vmaf_vs_cap-rf-transcode": -32.52974510101308, "bd_vmaf_vs_cap-rf-transcode_n": 5, "bd_vmaf_vs_cap-web-recorder": -48.71195832678624, "bd_vmaf_vs_cap-web-recorder_n": 4, "bd_vmaf_vs_x264-veryfast": 13.820741042017056, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 157.0916677008535, "decode_failures": 0, "encodes": 29, "errors": 0, "matched_speedup_clips": {"busy_ui": 1.6187981617179326, "code_editor": 1.5821552584379, "full_motion": 0.2296963902722925, "slides": 0.8636906517097483, "text_scroll": 0.6826421768967295}, "matched_speedup_cpu_geomean": 1.4787007862889077, "matched_speedup_wall_geomean": 0.8091507884647902, "matched_speedup_wall_min": 0.2296963902722925, "speed_wall_fps_median": 479.86286460985133, "vs_production": {"cap-browser-export": {"bitrate_ratio_geomean": 0.5514156183017997, "clips": 5, "interpolated": 5}, "cap-export-crf": {"bitrate_ratio_geomean": 1.249657138546431, "clips": 5, "interpolated": 2}, "cap-export-x264": {"bitrate_ratio_geomean": 0.5612766958712461, "clips": 5, "interpolated": 1}, "cap-ms-edit": {"bitrate_ratio_geomean": 1.8266090030850775, "clips": 5, "interpolated": 3}, "cap-ms-transcode": {"bitrate_ratio_geomean": 1.829880169811149, "clips": 5, "interpolated": 3}, "cap-rec-linux": {"bitrate_ratio_geomean": 0.3552563433066385, "clips": 5, "interpolated": 0}, "cap-rf-transcode": {"bitrate_ratio_geomean": 0.6668028935973517, "clips": 5, "interpolated": 5}, "cap-web-recorder": {"bitrate_ratio_geomean": 0.406220956358247, "clips": 5, "interpolated": 4}}}, "capcodec-medium": {"bd_psnr_yuv_vs_cap-browser-export": -61.20589142836103, "bd_psnr_yuv_vs_cap-browser-export_n": 3, "bd_psnr_yuv_vs_cap-export-crf": 19.742726768700553, "bd_psnr_yuv_vs_cap-export-crf_n": 5, "bd_psnr_yuv_vs_cap-export-x264": -32.72774099163607, "bd_psnr_yuv_vs_cap-export-x264_n": 4, "bd_psnr_yuv_vs_cap-ms-edit": 91.53817448326875, "bd_psnr_yuv_vs_cap-ms-edit_n": 5, "bd_psnr_yuv_vs_cap-ms-transcode": 90.16139835245514, "bd_psnr_yuv_vs_cap-ms-transcode_n": 5, "bd_psnr_yuv_vs_cap-rec-linux": -74.25695302596611, "bd_psnr_yuv_vs_cap-rec-linux_n": 2, "bd_psnr_yuv_vs_cap-rf-transcode": -34.78390017481545, "bd_psnr_yuv_vs_cap-rf-transcode_n": 5, "bd_psnr_yuv_vs_cap-web-recorder": -50.840310993299866, "bd_psnr_yuv_vs_cap-web-recorder_n": 4, "bd_psnr_yuv_vs_x264-veryfast": 12.148392827204004, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_cap-browser-export": -62.626988706986175, "bd_ssim_vs_cap-browser-export_n": 3, "bd_ssim_vs_cap-export-crf": 24.759389895806713, "bd_ssim_vs_cap-export-crf_n": 5, "bd_ssim_vs_cap-export-x264": -30.285283198938565, "bd_ssim_vs_cap-export-x264_n": 4, "bd_ssim_vs_cap-ms-edit": 104.2319919320917, "bd_ssim_vs_cap-ms-edit_n": 5, "bd_ssim_vs_cap-ms-transcode": 93.45146335732964, "bd_ssim_vs_cap-ms-transcode_n": 5, "bd_ssim_vs_cap-rec-linux": -74.27587165407886, "bd_ssim_vs_cap-rec-linux_n": 2, "bd_ssim_vs_cap-rf-transcode": -31.36679605671647, "bd_ssim_vs_cap-rf-transcode_n": 5, "bd_ssim_vs_cap-web-recorder": -52.88790528076442, "bd_ssim_vs_cap-web-recorder_n": 4, "bd_ssim_vs_x264-veryfast": 18.60095878345423, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_cap-browser-export": -62.87407771811222, "bd_vmaf_vs_cap-browser-export_n": 3, "bd_vmaf_vs_cap-export-crf": 27.0573047005621, "bd_vmaf_vs_cap-export-crf_n": 5, "bd_vmaf_vs_cap-export-x264": -34.253510832348695, "bd_vmaf_vs_cap-export-x264_n": 5, "bd_vmaf_vs_cap-ms-edit": 99.19366879924125, "bd_vmaf_vs_cap-ms-edit_n": 5, "bd_vmaf_vs_cap-ms-transcode": 95.2883096107535, "bd_vmaf_vs_cap-ms-transcode_n": 5, "bd_vmaf_vs_cap-rec-linux": -67.25434250450067, "bd_vmaf_vs_cap-rec-linux_n": 2, "bd_vmaf_vs_cap-rf-transcode": -37.82458396240339, "bd_vmaf_vs_cap-rf-transcode_n": 5, "bd_vmaf_vs_cap-web-recorder": -50.94553207862251, "bd_vmaf_vs_cap-web-recorder_n": 4, "bd_vmaf_vs_x264-veryfast": 7.212437675070971, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 153.57373766226985, "decode_failures": 0, "encodes": 29, "errors": 0, "matched_speedup_clips": {"busy_ui": 1.5709578038517753, "code_editor": 1.517821029077065, "full_motion": 0.1522033781240062, "slides": 0.7728859479494019, "text_scroll": 0.5417238516128725}, "matched_speedup_cpu_geomean": 1.4175201352320832, "matched_speedup_wall_geomean": 0.6860259584437817, "matched_speedup_wall_min": 0.1522033781240062, "speed_wall_fps_median": 415.82211024799705, "static_vs_full": {}, "vs_production": {"cap-browser-export": {"bitrate_ratio_geomean": 0.5132608293835318, "clips": 5, "interpolated": 5}, "cap-export-crf": {"bitrate_ratio_geomean": 1.208574202135157, "clips": 5, "interpolated": 2}, "cap-export-x264": {"bitrate_ratio_geomean": 0.5229690620695444, "clips": 5, "interpolated": 1}, "cap-ms-edit": {"bitrate_ratio_geomean": 1.702426102984849, "clips": 5, "interpolated": 3}, "cap-ms-transcode": {"bitrate_ratio_geomean": 1.7092022610858828, "clips": 5, "interpolated": 3}, "cap-rec-linux": {"bitrate_ratio_geomean": 0.3311830231398074, "clips": 5, "interpolated": 0}, "cap-rf-transcode": {"bitrate_ratio_geomean": 0.6205549904833497, "clips": 5, "interpolated": 5}, "cap-web-recorder": {"bitrate_ratio_geomean": 0.3932868372420528, "clips": 5, "interpolated": 4}}}, "x264-veryfast": {"bd_psnr_yuv_vs_cap-browser-export": -67.8952211145364, "bd_psnr_yuv_vs_cap-browser-export_n": 3, "bd_psnr_yuv_vs_cap-export-crf": 4.628934095255968, "bd_psnr_yuv_vs_cap-export-crf_n": 5, "bd_psnr_yuv_vs_cap-export-x264": -39.02396372928775, "bd_psnr_yuv_vs_cap-export-x264_n": 2, "bd_psnr_yuv_vs_cap-ms-edit": 69.7062042316482, "bd_psnr_yuv_vs_cap-ms-edit_n": 5, "bd_psnr_yuv_vs_cap-ms-transcode": 67.00180282939445, "bd_psnr_yuv_vs_cap-ms-transcode_n": 5, "bd_psnr_yuv_vs_cap-rec-linux": -76.5903570915919, "bd_psnr_yuv_vs_cap-rec-linux_n": 2, "bd_psnr_yuv_vs_cap-rf-transcode": -41.29102197104441, "bd_psnr_yuv_vs_cap-rf-transcode_n": 5, "bd_psnr_yuv_vs_cap-web-recorder": -62.947802748803326, "bd_psnr_yuv_vs_cap-web-recorder_n": 4, "bd_psnr_yuv_vs_x264-veryfast": 0.0, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_cap-browser-export": -69.83412994875547, "bd_ssim_vs_cap-browser-export_n": 3, "bd_ssim_vs_cap-export-crf": 2.827413688904081, "bd_ssim_vs_cap-export-crf_n": 5, "bd_ssim_vs_cap-export-x264": -37.76155357842598, "bd_ssim_vs_cap-export-x264_n": 2, "bd_ssim_vs_cap-ms-edit": 74.31444970435683, "bd_ssim_vs_cap-ms-edit_n": 5, "bd_ssim_vs_cap-ms-transcode": 62.99915144734856, "bd_ssim_vs_cap-ms-transcode_n": 5, "bd_ssim_vs_cap-rec-linux": -76.76236463931943, "bd_ssim_vs_cap-rec-linux_n": 2, "bd_ssim_vs_cap-rf-transcode": -40.390341578961326, "bd_ssim_vs_cap-rf-transcode_n": 5, "bd_ssim_vs_cap-web-recorder": -65.68932541231825, "bd_ssim_vs_cap-web-recorder_n": 4, "bd_ssim_vs_x264-veryfast": 0.0, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_cap-browser-export": -68.91204880040621, "bd_vmaf_vs_cap-browser-export_n": 3, "bd_vmaf_vs_cap-export-crf": 17.286060763101997, "bd_vmaf_vs_cap-export-crf_n": 5, "bd_vmaf_vs_cap-export-x264": -34.82187089898283, "bd_vmaf_vs_cap-export-x264_n": 2, "bd_vmaf_vs_cap-ms-edit": 90.36610518280024, "bd_vmaf_vs_cap-ms-edit_n": 5, "bd_vmaf_vs_cap-ms-transcode": 82.402076023638, "bd_vmaf_vs_cap-ms-transcode_n": 5, "bd_vmaf_vs_cap-rec-linux": -74.32889049698659, "bd_vmaf_vs_cap-rec-linux_n": 1, "bd_vmaf_vs_cap-rf-transcode": -39.90006813905599, "bd_vmaf_vs_cap-rf-transcode_n": 5, "bd_vmaf_vs_cap-web-recorder": -62.81952960916177, "bd_vmaf_vs_cap-web-recorder_n": 4, "bd_vmaf_vs_x264-veryfast": 0.0, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 107.32664081999883, "decode_failures": 0, "encodes": 20, "errors": 0, "speed_wall_fps_median": 318.683973315324}}, "tier": "standard", "time": "2026-10-07T09:30:27"}
+{"clips": ["code_editor", "text_scroll", "slides"], "commit": "1c82bfaeb12e", "elapsed_s": 6.4, "gate": {"messages": ["capcodec-medium: BD-rate(PSNR-YUV) vs x264-veryfast = +1.59%, cpu-fps median = 291.6"], "ok": true}, "machine": "cursor|Linux|Intel(R) Xeon(R) Processor|4", "summary": {"capcodec-medium": {"bd_psnr_yuv_vs_x264-veryfast": 1.5927990279928197, "bd_psnr_yuv_vs_x264-veryfast_n": 3, "cpu_fps_median": 291.64864116037273, "decode_failures": 0, "encodes": 15, "errors": 0, "speed_wall_fps_median": null}, "x264-veryfast": {"bd_psnr_yuv_vs_x264-veryfast": 0.0, "bd_psnr_yuv_vs_x264-veryfast_n": 3, "cpu_fps_median": 207.56890546232756, "decode_failures": 0, "encodes": 12, "errors": 0, "speed_wall_fps_median": null}}, "tier": "smoke", "time": "2026-10-07T09:46:28"}
+{"clips": ["code_editor", "text_scroll", "slides", "busy_ui", "full_motion"], "commit": "8b8f3cf037be", "elapsed_s": 312.3, "gate": null, "machine": "cursor|Linux|Intel(R) Xeon(R) Processor|4", "summary": {"capcodec-live": {"bd_psnr_yuv_vs_x264-veryfast": 21.73488194858836, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_x264-veryfast": 27.16700079223234, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_x264-veryfast": 13.820741042017056, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 234.014106370332, "decode_failures": 0, "encodes": 29, "errors": 0, "matched_speedup_clips": {"busy_ui": 1.6940124690949978, "code_editor": 1.7940734253075497, "full_motion": 0.44821037777839934, "slides": 1.2842644542264094, "text_scroll": 1.1560886554907053}, "matched_speedup_cpu_geomean": 2.0484323600875847, "matched_speedup_wall_geomean": 1.1512691444661218, "matched_speedup_wall_min": 0.44821037777839934, "speed_wall_fps_median": 599.1251304740448}, "capcodec-medium": {"bd_psnr_yuv_vs_x264-veryfast": 12.148392827204004, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_x264-veryfast": 18.60095878345423, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_x264-veryfast": 7.212437675070971, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 200.502191154779, "decode_failures": 0, "encodes": 29, "errors": 0, "matched_speedup_clips": {"busy_ui": 1.690646212350034, "code_editor": 1.7068939602718416, "full_motion": 0.4090565114884956, "slides": 1.1612068544431104, "text_scroll": 1.1537511706933872}, "matched_speedup_cpu_geomean": 1.81093374146593, "matched_speedup_wall_geomean": 1.0960058359382954, "matched_speedup_wall_min": 0.4090565114884956, "speed_wall_fps_median": 582.0421943031246, "static_vs_full": {}}, "x264-veryfast": {"bd_psnr_yuv_vs_x264-veryfast": 0.0, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_x264-veryfast": 0.0, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_x264-veryfast": 0.0, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 107.32664081999883, "decode_failures": 0, "encodes": 20, "errors": 0, "speed_wall_fps_median": 318.683973315324}}, "tier": "standard", "time": "2026-10-07T10:14:40"}
+{"clips": ["code_editor", "text_scroll", "slides", "busy_ui", "full_motion"], "commit": "a6eece366390", "elapsed_s": 339.4, "gate": null, "machine": "cursor|Linux|Intel(R) Xeon(R) Processor|4", "summary": {"capcodec-live": {"bd_psnr_yuv_vs_x264-veryfast": 21.621020673835712, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_x264-veryfast": 27.408956047770474, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_x264-veryfast": 13.95411263558328, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 238.59200238593948, "decode_failures": 0, "encodes": 30, "errors": 0, "matched_speedup_clips": {"busy_ui": 1.8595281128284133, "code_editor": 1.7378428353191013, "full_motion": 0.35817200810036987, "slides": 0.8136929096385535, "text_scroll": 0.9384178538947964}, "matched_speedup_cpu_geomean": 1.9360579150524597, "matched_speedup_wall_geomean": 0.9756012235682405, "matched_speedup_wall_min": 0.35817200810036987, "speed_wall_fps_median": 173.12314777906784}, "capcodec-medium": {"bd_psnr_yuv_vs_x264-veryfast": 12.442683916847697, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_x264-veryfast": 19.008214137569702, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_x264-veryfast": 7.383011073238442, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 212.96961620355592, "decode_failures": 0, "encodes": 30, "errors": 0, "matched_speedup_clips": {"busy_ui": 1.299729161044796, "code_editor": 1.7034905393397781, "full_motion": 0.30890312815927845, "slides": 0.9258838664218133, "text_scroll": 1.1494052551884273}, "matched_speedup_cpu_geomean": 1.776781361096459, "matched_speedup_wall_geomean": 0.9384452015994434, "matched_speedup_wall_min": 0.30890312815927845, "speed_wall_fps_median": 632.9335804898697, "static_vs_full": {}}, "x264-veryfast": {"bd_psnr_yuv_vs_x264-veryfast": 0.0, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_x264-veryfast": 0.0, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_x264-veryfast": 0.0, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 107.32664081999883, "decode_failures": 0, "encodes": 20, "errors": 0, "speed_wall_fps_median": 318.683973315324}}, "tier": "standard", "time": "2026-10-07T10:32:18"}
+{"clips": ["code_editor", "text_scroll", "slides", "busy_ui", "full_motion"], "commit": "a6eece366390-dirty", "elapsed_s": 128.1, "gate": null, "machine": "cursor|Linux|Intel(R) Xeon(R) Processor|4", "summary": {"capcodec-live": {"bd_psnr_yuv_vs_x264-veryfast": 21.621020673835712, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_x264-veryfast": 27.408956047770474, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_x264-veryfast": 13.95411263558328, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 238.59200238593948, "decode_failures": 0, "encodes": 30, "errors": 0, "matched_speedup_clips": {"busy_ui": 1.8208188225886257, "code_editor": 1.702931772741124, "full_motion": 0.39594285805554746, "slides": 1.194163077554535, "text_scroll": 1.2085601126674634}, "matched_speedup_cpu_geomean": 1.9360579150524597, "matched_speedup_wall_geomean": 1.1212066847929683, "matched_speedup_wall_min": 0.39594285805554746, "speed_wall_fps_median": 656.4577604852676}, "capcodec-medium": {"bd_psnr_yuv_vs_x264-veryfast": 12.442683916847697, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_x264-veryfast": 19.008214137569702, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_x264-veryfast": 7.383011073238442, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 212.96961620355592, "decode_failures": 0, "encodes": 30, "errors": 0, "matched_speedup_clips": {"busy_ui": 1.8012725536929792, "code_editor": 1.6859287590825796, "full_motion": 0.3405555301606423, "slides": 1.0914914244956073, "text_scroll": 1.0843600300064486}, "matched_speedup_cpu_geomean": 1.776781361096459, "matched_speedup_wall_geomean": 1.0412621531021968, "matched_speedup_wall_min": 0.3405555301606423, "speed_wall_fps_median": 630.2168239059058, "static_vs_full": {}}, "x264-veryfast": {"bd_psnr_yuv_vs_x264-veryfast": 0.0, "bd_psnr_yuv_vs_x264-veryfast_n": 5, "bd_ssim_vs_x264-veryfast": 0.0, "bd_ssim_vs_x264-veryfast_n": 5, "bd_vmaf_vs_x264-veryfast": 0.0, "bd_vmaf_vs_x264-veryfast_n": 5, "cpu_fps_median": 107.32664081999883, "decode_failures": 0, "encodes": 20, "errors": 0, "speed_wall_fps_median": 351.1627493993604}}, "tier": "standard", "time": "2026-10-07T10:38:15"}
diff --git a/capcodec/bench/integration/media-server-driver.ts b/capcodec/bench/integration/media-server-driver.ts
new file mode 100644
index 000000000..f38bc1946
--- /dev/null
+++ b/capcodec/bench/integration/media-server-driver.ts
@@ -0,0 +1,15 @@
+import { processVideo } from "/workspace/apps/media-server/src/lib/media-video";
+import { probeVideoFile } from "/workspace/apps/media-server/src/lib/media-probe";
+
+const [input, output] = process.argv.slice(2);
+if (!input || !output) {
+ console.error("usage: bun media-server-driver.ts <input> <output.mp4>");
+ process.exit(2);
+}
+const metadata = await probeVideoFile(input);
+const started = performance.now();
+const result = await processVideo(input, metadata, {});
+const elapsed = performance.now() - started;
+await Bun.write(output, Bun.file(result.path));
+await result.cleanup();
+console.log(JSON.stringify({ encoder: process.env.CAP_MEDIA_VIDEO_ENCODER ?? "libx264", elapsedMs: elapsed, metadata }));
diff --git a/capcodec/bench/lane.sh b/capcodec/bench/lane.sh
new file mode 100755
index 000000000..89f420be7
--- /dev/null
+++ b/capcodec/bench/lane.sh
@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+set -euo pipefail
+SOCKET="${BENCH_LANE_SOCKET:-bench}"
+ROOT="$(cd "$(dirname "$0")/.." && pwd)"
+cmd="${1:-status}"
+server_pid() { tmux -L "$SOCKET" display-message -p '#{pid}' 2>/dev/null || true; }
+outside_threads() {
+ ps -e -L -o pid=,ppid=,lwp=,ni=,uid= | awk -v root="$1" -v uid="$(id -u)" '
+ { pid[NR] = $1; ppid[$1] = $2; lwp[NR] = $3; ni[NR] = $4; u[NR] = $5 }
+ END {
+ for (i = 1; i <= NR; i++) {
+ if (u[i] != uid || ni[i] >= 19) continue
+ p = pid[i]; inlane = 0
+ for (d = 0; d < 64 && p > 1; d++) { if (p == root) { inlane = 1; break } p = ppid[p] }
+ if (!inlane) print lwp[i]
+ }
+ }'
+}
+case "$cmd" in
+start)
+ tmux -L "$SOCKET" has-session -t bench 2>/dev/null || tmux -L "$SOCKET" new-session -d -s bench -c "$ROOT" -- bash -l
+ "$0" demote
+ ;;
+demote)
+ sp="$(server_pid)"
+ [ -n "$sp" ] || { echo "no bench lane"; exit 1; }
+ tids="$(outside_threads "$sp" | tr '\n' ' ')"
+ n=0
+ if [ -n "${tids// /}" ]; then
+ renice -n 19 -p $tids >/dev/null 2>&1 || true
+ n=$(echo "$tids" | wc -w)
+ fi
+ echo "lane server $sp at nice $(ps -o ni= -p "$sp" | tr -d ' '); demoted $n threads to nice 19"
+ ;;
+watch)
+ while sleep "${2:-30}"; do "$0" demote >/dev/null; done
+ ;;
+run)
+ shift
+ [ -n "$(server_pid)" ] || { echo "no bench lane; run $0 start"; exit 1; }
+ tmux -L "$SOCKET" new-window -d -t bench -c "$ROOT" -- bash -lc "$*"
+ ;;
+status)
+ sp="$(server_pid)"
+ if [ -n "$sp" ]; then
+ echo "lane server $sp nice $(ps -o ni= -p "$sp" | tr -d ' '); threads below nice 19 outside the lane: $(outside_threads "$sp" | wc -l)"
+ else
+ echo "no bench lane"
+ fi
+ ;;
+esac
diff --git a/capcodec/bench/scoreboard.py b/capcodec/bench/scoreboard.py
new file mode 100644
index 000000000..e321c85f2
--- /dev/null
+++ b/capcodec/bench/scoreboard.py
@@ -0,0 +1,120 @@
+#!/usr/bin/env python3
+import argparse
+import csv
+import json
+import math
+import sys
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from harness.bdrate import bd_rate, overlap_fraction # noqa: E402
+
+PAIRS = [("capcodec-medium", "x264-veryfast", "medium"), ("capcodec-live", "x264-veryfast", "live"),
+ ("capcodec-live-zerolatency", "x264-veryfast-zerolatency", "zerolatency")]
+METRICS = [("vmaf", "VMAF"), ("psnr_yuv", "PSNR"), ("ssim", "SSIM")]
+
+
+def num(v: str | None) -> float | None:
+ try:
+ f = float(v)
+ except (TypeError, ValueError):
+ return None
+ return None if math.isnan(f) else f
+
+
+def load_rows(path: Path) -> list[dict]:
+ with open(path / "results.csv") as f:
+ return [r for r in csv.DictReader(f) if not r.get("kind") and not r.get("error")]
+
+
+def curve(rows: list[dict], enc: str, clip: str, key: str) -> tuple[list[float], list[float]]:
+ pts = [(num(r["kbps"]), num(r.get(key))) for r in rows if r["encoder"] == enc and r["clip"] == clip]
+ pts = [(k, q) for k, q in pts if k and q is not None]
+ return [k for k, _ in pts], [q for _, q in pts]
+
+
+def mark(v: float | None, lower_is_better: bool = True, tie: float = 0.0) -> str:
+ if v is None:
+ return "n/a"
+ good = v < -tie if lower_is_better else v > tie
+ bad = v > tie if lower_is_better else v < -tie
+ return f"{v:+.1f}% {'win' if good else 'lose' if bad else 'tie'}"
+
+
+def quality_tables(rows: list[dict], label: str) -> tuple[list[str], dict]:
+ clips = sorted({r["clip"] for r in rows})
+ out = []
+ tally = {}
+ for cap, ref, mode in PAIRS:
+ if not any(r["encoder"] == cap for r in rows) or not any(r["encoder"] == ref for r in rows):
+ continue
+ out += [f"### {label}: {cap} vs {ref} (BD-rate, negative = capcodec needs fewer bits)", "",
+ "| clip | VMAF | PSNR-YUV | SSIM | VMAF range overlap |", "|---|---|---|---|---|"]
+ wins = losses = 0
+ for clip in clips:
+ cells = []
+ for key, _ in METRICS:
+ rr, rq = curve(rows, ref, clip, key)
+ tr, tq = curve(rows, cap, clip, key)
+ v = bd_rate(rr, rq, tr, tq)
+ cells.append(mark(v))
+ if v is not None:
+ wins += v < 0
+ losses += v > 0
+ _, rq = curve(rows, ref, clip, "vmaf")
+ _, tq = curve(rows, cap, clip, "vmaf")
+ out.append(f"| {clip} | {' | '.join(cells)} | {overlap_fraction(rq, tq):.0%} |")
+ tally[mode] = (wins, losses)
+ out += ["", f"{wins} wins, {losses} losses across {len(clips)} clips x 3 metrics.", ""]
+ return out, tally
+
+
+def speed_tables(speed: dict, label: str) -> list[str]:
+ out = [f"### {label}: speed at matched VMAF (x264 / capcodec, interleaved medians, other work paused)", "",
+ "| clip | mode | VMAF | CPU 1t | wall 1t | CPU 4t | wall 4t | peak RSS 4t capcodec / x264 MiB |",
+ "|---|---|---|---|---|---|---|---|"]
+ for e in sorted(speed.values(), key=lambda e: (e["mode"], e["clip"])):
+ t1, t4 = e["threads"].get("1"), e["threads"].get("4")
+
+ def r(d, k):
+ return f"{d[k]:.2f}x {'win' if d[k] > 1 else 'lose'}" if d else "n/a"
+ rss = f"{t4['capcodec']['rss_mb']:.0f} / {t4['x264']['rss_mb']:.0f}" if t4 else "n/a"
+ out.append(f"| {e['clip']} | {e['mode']} | {e['target_vmaf']:.1f} | {r(t1, 'cpu_ratio')} | "
+ f"{r(t1, 'wall_ratio')} | {r(t4, 'cpu_ratio')} | {r(t4, 'wall_ratio')} | {rss} |")
+ for mode in sorted({e["mode"] for e in speed.values()}):
+ es = [e for e in speed.values() if e["mode"] == mode]
+ for t in ("1", "4"):
+ for k in ("cpu_ratio", "wall_ratio"):
+ vs = [e["threads"][t][k] for e in es if t in e["threads"]]
+ if vs:
+ g = math.exp(sum(math.log(v) for v in vs) / len(vs))
+ out.append(f"- {mode} {t} thread{'s' if t != '1' else ''} {k.split('_')[0]}: geometric mean "
+ f"{g:.2f}x, min {min(vs):.2f}x ({sum(v > 1 for v in vs)}/{len(vs)} clips faster)")
+ out.append("")
+ return out
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description="scoreboard against x264 from harness quality and speedcmp results")
+ ap.add_argument("--quality", type=Path, action="append", default=[], help="LABEL=DIR with results.csv")
+ ap.add_argument("--speed", type=Path, action="append", default=[], help="LABEL=DIR with results.json")
+ ap.add_argument("--out", type=Path, required=True)
+ a = ap.parse_args()
+ lines = ["# Scoreboard against x264", ""]
+ for spec in a.quality:
+ label, _, d = str(spec).partition("=")
+ if (Path(d) / "results.csv").exists():
+ t, _ = quality_tables(load_rows(Path(d)), label)
+ lines += t
+ for spec in a.speed:
+ label, _, d = str(spec).partition("=")
+ p = Path(d) / "results.json"
+ if p.exists():
+ lines += speed_tables(json.loads(p.read_text()), label)
+ a.out.write_text("\n".join(lines) + "\n")
+ print(a.out)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/capcodec/bench/speedcmp.py b/capcodec/bench/speedcmp.py
new file mode 100644
index 000000000..ddcf077e9
--- /dev/null
+++ b/capcodec/bench/speedcmp.py
@@ -0,0 +1,390 @@
+#!/usr/bin/env python3
+import argparse
+import fcntl
+import json
+import os
+import random
+import signal
+import statistics
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+
+from harness.adapters.base import raw_input_args # noqa: E402
+from harness.adapters.x264 import gop_args # noqa: E402
+from harness.common import CACHE_DIR, FFMPEG, OUT_DIR, ROOT, log # noqa: E402
+from harness.corpus import load_manifest, prepare_source # noqa: E402
+from harness.metrics import MetricConfig, measure # noqa: E402
+
+FROZEN_FILE = Path(tempfile.gettempdir()) / "speedcmp-frozen.json"
+LOCK_FILE = Path(tempfile.gettempdir()) / "speedcmp.lock"
+PROTECTED = {"node", "tini", "pod-daemon", "sshd", "systemd", "dbus-daemon", "cursor-agent-st"}
+SHELLS = {"bash", "sh", "dash", "zsh"}
+TMUX = {"tmux: server", "tmux"}
+VMAF_CFG = MetricConfig(psnr=False, ssim=False, vmaf=True, vmaf_subsample=5, ocr=False, crops=False, vmaf_threads=4)
+LONG_CLIP_SECONDS = {"code_4k": 5.0}
+DEFAULT_CLIPS = ["busy_ui", "code_editor", "slides", "text_scroll", "full_motion", "webcam_overlay"]
+MODES = {
+ "medium": {"capcodec": ["--preset", "medium"], "x264": ("veryfast", None)},
+ "live": {"capcodec": ["--preset", "live"], "x264": ("veryfast", None)},
+ "zerolatency": {"capcodec": ["--preset", "live", "--zerolatency"], "x264": ("veryfast", "zerolatency")},
+}
+
+
+def ancestors(pid: int) -> set[int]:
+ out = set()
+ while pid > 1:
+ out.add(pid)
+ try:
+ pid = int(Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()[1])
+ except (OSError, ValueError, IndexError):
+ break
+ return out
+
+
+def comm_of(pid: int) -> str:
+ try:
+ return Path(f"/proc/{pid}/comm").read_text().strip()
+ except OSError:
+ return ""
+
+
+def rank(pid: int) -> int:
+ c = comm_of(pid)
+ return 0 if c in TMUX else 1 if c in SHELLS else 2
+
+
+def kept() -> set[int]:
+ return {p for p in ancestors(os.getpid()) if comm_of(p) not in TMUX}
+
+
+def freezable() -> list[int]:
+ me = os.getuid()
+ keep = kept()
+ pids = []
+ for d in Path("/proc").iterdir():
+ if not d.name.isdigit():
+ continue
+ pid = int(d.name)
+ if pid in keep:
+ continue
+ try:
+ if d.stat().st_uid != me:
+ continue
+ comm = (d / "comm").read_text().strip()
+ state = (d / "stat").read_text().rsplit(")", 1)[1].split()[0]
+ except OSError:
+ continue
+ if comm in PROTECTED or state in ("T", "Z"):
+ continue
+ pids.append(pid)
+ return sorted(pids, key=rank)
+
+
+def thaw(pids: list[int]) -> None:
+ order = list(reversed(pids))
+ ranks = {p: rank(p) for p in order}
+ for r in (2, 1, 0):
+ for p in order:
+ if ranks[p] == r:
+ try:
+ os.kill(p, signal.SIGCONT)
+ except OSError:
+ pass
+ time.sleep(0.02)
+ FROZEN_FILE.unlink(missing_ok=True)
+
+
+def thaw_leftovers() -> None:
+ if not FROZEN_FILE.exists():
+ return
+ with open(LOCK_FILE, "w") as lock:
+ try:
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
+ except OSError:
+ return
+ try:
+ thaw(json.loads(FROZEN_FILE.read_text()))
+ except (OSError, ValueError):
+ FROZEN_FILE.unlink(missing_ok=True)
+
+
+def children(pid: int) -> list[int]:
+ out = []
+ try:
+ for t in Path(f"/proc/{pid}/task").iterdir():
+ out += [int(c) for c in (t / "children").read_text().split()]
+ except OSError:
+ pass
+ return out
+
+
+def spawners() -> list[int]:
+ me = os.getuid()
+ out = []
+ for d in Path("/proc").iterdir():
+ if d.name.isdigit():
+ try:
+ if d.stat().st_uid == me and (d / "comm").read_text().strip() in PROTECTED:
+ out.append(int(d.name))
+ except OSError:
+ pass
+ return out
+
+
+class Quiet:
+ def __init__(self, enabled: bool):
+ self.enabled = enabled
+ self.pids: list[int] = []
+ self.stopped: set[int] = set()
+ self.done = threading.Event()
+ self.lock = threading.Lock()
+ self.watcher: threading.Thread | None = None
+
+ def stop(self, pids: list[int]) -> None:
+ with self.lock:
+ new = [p for p in pids if p not in self.stopped]
+ self.pids += new
+ self.stopped.update(new)
+ FROZEN_FILE.write_text(json.dumps(self.pids))
+ for p in new:
+ try:
+ os.kill(p, signal.SIGSTOP)
+ except OSError:
+ pass
+
+ def watch(self, roots: list[int], keep: set[int]) -> None:
+ while not self.done.wait(0.01):
+ fresh = []
+ todo = [c for r in roots for c in children(r)]
+ while todo:
+ c = todo.pop()
+ if c in keep or c in self.stopped:
+ continue
+ fresh.append(c)
+ todo += children(c)
+ if fresh:
+ self.stop(fresh)
+
+ def __enter__(self):
+ if self.enabled:
+ for _ in range(20):
+ new = [p for p in freezable() if p not in self.stopped]
+ if not new:
+ break
+ self.stop(new)
+ time.sleep(0.05)
+ self.watcher = threading.Thread(target=self.watch, args=(spawners(), ancestors(os.getpid())), daemon=True)
+ self.watcher.start()
+ time.sleep(0.3)
+ return self
+
+ def __exit__(self, *exc):
+ if self.enabled:
+ self.done.set()
+ if self.watcher:
+ self.watcher.join()
+ thaw(self.pids)
+ return False
+
+
+def timed(cmd: list[str], quiet: bool) -> dict:
+ with open(LOCK_FILE, "w") as lock:
+ fcntl.flock(lock, fcntl.LOCK_EX)
+ return timed_locked(cmd, quiet)
+
+
+def timed_locked(cmd: list[str], quiet: bool) -> dict:
+ with Quiet(quiet) as q:
+ load = os.getloadavg()[0]
+ t0 = time.perf_counter()
+ proc = subprocess.Popen(cmd, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
+ _, status, ru = os.wait4(proc.pid, 0)
+ wall = time.perf_counter() - t0
+ err = proc.stderr.read().decode(errors="replace") if proc.stderr else ""
+ if os.waitstatus_to_exitcode(status) != 0:
+ raise RuntimeError(f"{cmd[0]} failed: {err[-1000:]}")
+ return {"wall": wall, "cpu": ru.ru_utime + ru.ru_stime, "rss_mb": ru.ru_maxrss / 1024, "frozen": len(q.pids),
+ "load": load}
+
+
+def capcodec_cmd(binary: str, src, crf: float, mode: str, threads: int | None, out: Path,
+ keyint1: bool = False) -> list[str]:
+ cmd = [binary, "encode", "--input", str(src.path), "--width", str(src.width), "--height", str(src.height),
+ "--fps", src.fps_arg, "--frames", str(src.frames), *MODES[mode]["capcodec"], "--crf", f"{crf:g}",
+ "--output", str(out)]
+ if keyint1:
+ # With IDR reuse every keyframe copies the macroblocks whose source equals the previous frame's (busy_ui
+ # 28% less CPU), which is not keyframe coding, and frame-parallel intra coding only runs without it.
+ cmd += ["--keyint", "1", "--no-idr-reuse"]
+ if src.sideinfo:
+ cmd += ["--sideinfo", str(src.sideinfo)]
+ if threads is not None:
+ cmd += ["--threads", str(threads)]
+ return cmd
+
+
+def x264_cmd(src, crf: float, mode: str, threads: int, out: Path, keyint1: bool = False) -> list[str]:
+ preset, tune = MODES[mode]["x264"]
+ args = ["-c:v", "libx264", "-preset", preset]
+ if tune:
+ args += ["-tune", tune]
+ gop = ["-g", "1", "-keyint_min", "1"] if keyint1 else gop_args(src)
+ args += ["-crf", f"{crf:g}", *gop, "-pix_fmt", "yuv420p", "-threads", str(threads)]
+ return [FFMPEG, "-hide_banner", "-loglevel", "error", "-nostdin", "-y", *raw_input_args(src), *args, "-an",
+ "-movflags", "+faststart", str(out)]
+
+
+def vmaf_of(src, path: Path, work: Path) -> tuple[float, float]:
+ r = measure(src, path, "mp4", VMAF_CFG, work, CACHE_DIR / "ocr")
+ if r.get("vmaf") is None:
+ raise RuntimeError(f"no VMAF for {path}: {r.get('decode_ffmpeg_error') or r.get('metrics_error')}")
+ return r["vmaf"], path.stat().st_size * 8 / (src.frames / src.fps_float) / 1000
+
+
+def match_crf(binary: str, src, mode: str, target: float, work: Path, start: float, keyint1: bool) -> dict:
+ tried: dict[float, tuple[float, float]] = {}
+
+ def at(c: float) -> float:
+ c = max(10.0, min(51.0, round(c * 4) / 4))
+ if c not in tried:
+ out = work / f"cap_{mode}_{c:g}.mp4"
+ subprocess.run(capcodec_cmd(binary, src, c, mode, None, out, keyint1), check=True,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ tried[c] = vmaf_of(src, out, work / "m")
+ out.unlink(missing_ok=True)
+ return c
+
+ c = at(start)
+ slope = -0.6
+ for _ in range(6):
+ v = tried[c][0]
+ if abs(v - target) <= 0.1:
+ break
+ nxt = at(c + (target - v) / slope)
+ if nxt == c:
+ break
+ if tried[nxt][0] != v:
+ slope = (tried[nxt][0] - v) / (nxt - c)
+ slope = min(-0.05, slope)
+ c = nxt
+ pts = sorted(tried.items())
+ best = min(pts, key=lambda kv: abs(kv[1][0] - target))
+ for (c0, (v0, _)), (c1, (v1, _)) in zip(pts, pts[1:]):
+ if min(v0, v1) <= target <= max(v0, v1) and v0 != v1:
+ ci = at(c0 + (target - v0) * (c1 - c0) / (v1 - v0))
+ if abs(tried[ci][0] - target) <= abs(best[1][0] - target):
+ best = (ci, tried[ci])
+ break
+ return {"crf": best[0], "vmaf": best[1][0], "kbps": best[1][1], "tried": {f"{k:g}": v for k, v in tried.items()}}
+
+
+def summarize(runs: list[dict]) -> dict:
+ return {"wall": statistics.median(r["wall"] for r in runs), "cpu": statistics.median(r["cpu"] for r in runs),
+ "wall_min": min(r["wall"] for r in runs), "cpu_min": min(r["cpu"] for r in runs),
+ "rss_mb": max(r["rss_mb"] for r in runs), "n": len(runs)}
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser(description="interleaved speed comparison against x264 at matched VMAF")
+ ap.add_argument("--binary", default=str(ROOT / "build" / "capcodec-unchecked"))
+ ap.add_argument("--clips", default=",".join(DEFAULT_CLIPS))
+ ap.add_argument("--modes", default="medium,live")
+ ap.add_argument("--threads", default="1,4")
+ ap.add_argument("--rounds", type=int, default=5)
+ ap.add_argument("--height", type=int, default=1080)
+ ap.add_argument("--seconds", type=float, default=10.0)
+ ap.add_argument("--x264-crf", type=float, default=23.0)
+ ap.add_argument("--keyint1", action="store_true",
+ help="all-intra: every frame a keyframe (capcodec --keyint 1, x264 -g 1), reported as MODE-keyint1")
+ ap.add_argument("--no-freeze", action="store_true")
+ ap.add_argument("--retime", type=Path, help="reuse the matched CRFs of an earlier results.json and only time")
+ ap.add_argument("--out", default=str(OUT_DIR / "speedcmp"))
+ a = ap.parse_args()
+ thaw_leftovers()
+ for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
+ signal.signal(sig, lambda *_: (thaw_leftovers(), sys.exit(1)))
+ outdir = Path(a.out)
+ outdir.mkdir(parents=True, exist_ok=True)
+ clips = {c.name: c for c in load_manifest()}
+ names = list(clips) if a.clips == "all" else a.clips.split(",")
+ threads = [int(t) for t in a.threads.split(",")]
+ results = json.loads((outdir / "results.json").read_text()) if (outdir / "results.json").exists() else {}
+ matched = json.loads((a.retime / "results.json").read_text()) if a.retime else {}
+ shm = Path("/dev/shm") if Path("/dev/shm").is_dir() else Path(tempfile.gettempdir())
+ with tempfile.TemporaryDirectory(dir=shm, prefix="speedcmp-") as td:
+ work = Path(td)
+ for name in names:
+ clip = clips[name]
+ height = None if name in LONG_CLIP_SECONDS else a.height
+ src = prepare_source(clip, height, LONG_CLIP_SECONDS.get(name, a.seconds))
+ for mode in a.modes.split(","):
+ mode_label = f"{mode}-keyint1" if a.keyint1 else mode
+ key = f"{name}:{mode_label}"
+ if key in results:
+ continue
+ if key in matched:
+ target, xkbps, m = matched[key]["target_vmaf"], matched[key]["x264_kbps"], matched[key]["capcodec"]
+ else:
+ log(f"{key}: matching VMAF")
+ xq = work / "x264_q.mp4"
+ subprocess.run(x264_cmd(src, a.x264_crf, mode, 1, xq, a.keyint1), check=True)
+ target, xkbps = vmaf_of(src, xq, work / "m")
+ m = match_crf(a.binary, src, mode, target, work, 26.0, a.keyint1)
+ log(f"{key}: x264 crf {a.x264_crf:g} vmaf {target:.2f} {xkbps:.0f} kbps; capcodec crf {m['crf']:g} "
+ f"vmaf {m['vmaf']:.2f} {m['kbps']:.0f} kbps")
+ runs: dict[str, list[dict]] = {}
+ jobs = []
+ for t in threads:
+ jobs.append((f"x264_t{t}", x264_cmd(src, a.x264_crf, mode, 0 if t > 1 else 1, work / "x.mp4",
+ a.keyint1)))
+ jobs.append((f"cap_t{t}", capcodec_cmd(a.binary, src, m["crf"], mode, t, work / "c.mp4",
+ a.keyint1)))
+ for r in range(a.rounds):
+ random.shuffle(jobs)
+ for label, cmd in jobs:
+ runs.setdefault(label, []).append(timed(cmd, not a.no_freeze))
+ log(f"{key}: round {r + 1}/{a.rounds}")
+ entry = {"clip": name, "mode": mode_label, "width": src.width, "height": src.height,
+ "frames": src.frames, "fps": src.fps_float, "target_vmaf": target, "x264_kbps": xkbps,
+ "capcodec": m, "threads": {}}
+ for t in threads:
+ xs, cs = summarize(runs[f"x264_t{t}"]), summarize(runs[f"cap_t{t}"])
+ ratios = [x["cpu"] / c["cpu"] for x, c in zip(runs[f"x264_t{t}"], runs[f"cap_t{t}"])]
+ entry["threads"][str(t)] = {
+ "x264": xs, "capcodec": cs, "cpu_ratio": xs["cpu"] / cs["cpu"], "wall_ratio": xs["wall"] / cs["wall"],
+ "cpu_ratio_range": [min(ratios), max(ratios)],
+ "frozen_median": statistics.median(r["frozen"] for r in runs[f"cap_t{t}"])}
+ results[key] = entry
+ (outdir / "results.json").write_text(json.dumps(results, indent=1))
+ write_report(results, outdir / "report.md", threads)
+ write_report(results, outdir / "report.md", threads)
+ log(f"wrote {outdir / 'report.md'}")
+
+
+def write_report(results: dict, path: Path, threads: list[int]) -> None:
+ lines = ["# Speed at matched VMAF vs x264 (interleaved, other work paused during each timed run)", "",
+ "Ratio = x264 / capcodec (above 1 means capcodec is faster). Medians over rounds.", ""]
+ head = "| clip | mode | VMAF | capcodec crf | kbps vs x264 |"
+ sep = "|---|---|---|---|---|"
+ for t in threads:
+ head += f" CPU {t}t | wall {t}t |"
+ sep += "---|---|"
+ lines += [head, sep]
+ for e in results.values():
+ row = (f"| {e['clip']} | {e['mode']} | {e['target_vmaf']:.2f} | {e['capcodec']['crf']:g} "
+ f"({e['capcodec']['vmaf']:.2f}) | {e['capcodec']['kbps'] / e['x264_kbps']:.2f} |")
+ for t in threads:
+ d = e["threads"].get(str(t))
+ row += f" {d['cpu_ratio']:.2f}x | {d['wall_ratio']:.2f}x |" if d else " | |"
+ lines.append(row)
+ path.write_text("\n".join(lines) + "\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/capcodec/capcodec.bundle b/capcodec/capcodec.bundle
new file mode 100644
index 000000000..8c2acc914
Binary files /dev/null and b/capcodec/capcodec.bundle differ
diff --git a/capcodec/cli/main.tov b/capcodec/cli/main.tov
new file mode 100644
index 000000000..06834a24f
--- /dev/null
+++ b/capcodec/cli/main.tov
@@ -0,0 +1,828 @@
+import { closeSync, openSync, readFileSync, readSync, writeFileSync, writeSync } from "node:fs"
+import { availableParallelism } from "node:os"
+import * as path from "node:path"
+import { SideInfo, parseSideInfo } from "../src/analysis"
+import { Lookahead, LookaheadState } from "../src/lookahead"
+import { masterPlaylist, mediaPlaylist, segmentName } from "../src/mux/hls"
+import { Mp4Muxer, TIMESCALE } from "../src/mux/mp4"
+import { Encoder, FrameStats } from "../src/encoder"
+
+type Args = {
+ input: string,
+ output: string,
+ recon: string,
+ stats: string,
+ sideinfo: string,
+ width: int,
+ height: int,
+ fpsNum: int,
+ fpsDen: int,
+ frames: int,
+ qp: int,
+ preset: string,
+ profile: int,
+ keyintSec: f64,
+ threads: int,
+ noSideinfo: bool,
+ fullAnalysis: bool,
+ cavlc: bool,
+ refs: int,
+ noVfr: bool,
+ zeroLatency: bool,
+ crf: f64,
+ bitrate: int,
+ maxrate: int,
+ bufsize: int,
+ ipOffset: int,
+ rcMode: int,
+ aq: int,
+ refresh: int,
+ lifetime: bool,
+ inter8x8: bool,
+ decimate: bool,
+ idrReuse: bool,
+ globalShift: bool,
+ weightp: bool,
+ aqTexture: int,
+ sliceRows: int,
+ idrSliceRows: int,
+ idrSlices: int,
+ bframes: int,
+ bQpOffset: int,
+ bAdapt: bool,
+ bPyramid: int,
+ bRefQpOffset: int,
+ format: string,
+ subme: int,
+ subpelDirs: int,
+ keyint: int,
+ noise: int,
+ lookahead: int,
+ laStrength: f64,
+ readAheadFrames: int,
+}
+
+class UsageError extends Error {
+ constructor(message: string) {
+ super(message)
+ this.name = "UsageError"
+ }
+}
+
+function usage(): string {
+ return [
+ "usage: capcodec encode --input <file|-> --width W --height H --fps N[/D] --output <file.264|-> [options]",
+ " --frames K stop after K frames",
+ " --preset P live | fast | medium | slow (default medium)",
+ " --crf Q constant quality (default 26)",
+ " --qp Q constant QP",
+ " --bitrate K capped VBR target in kbit/s (--maxrate K, --bufsize K)",
+ " --aq-strength N text-aware adaptive quantisation strength (default 1, 0 disables)",
+ " --aq-texture N QP raise for textured (non-text) macroblocks (default 0)",
+ " --profile P high | main (default high)",
+ " --keyint-sec S seconds between IDR frames (default 2); --keyint N in frames",
+ " --noise N treat per-pixel changes up to N as unchanged when no side info is given",
+ " --slice-rows N macroblock rows per slice (default 0: one slice per frame); --idr-slice-rows N for IDR frames",
+ " --idr-slices N IDR frames as N row bands coded on separate threads (default 4, 1 for one slice)",
+ " --lookahead N read N frames ahead and set macroblock QPs from how long their content stays (default 10, 2 on live; 0 disables)",
+ " --bframes N 0..3 B-frames between anchors while most of the frame moves (default 3)",
+ " --read-ahead N with B-frames and threads, read and analyse up to N more frames while a run is coded (default 3)",
+ " --zerolatency no B-frames and no lookahead: every frame is output as soon as it is read",
+ " --no-b-adapt use B-frames on static content too; ignores side info and never drops frames",
+ " --b-qp-offset N B-frame QP relative to the macroblock QP of the following anchor (default 6)",
+ " --b-pyramid code the middle B-frame of runs of 2 or more as a reference for the others (default on, off",
+ " with --preset live); --no-b-pyramid",
+ " --b-ref-qp-offset N QP offset of the reference B-frame in a pyramid (default 5)",
+ " --no-idr-reuse code every IDR macroblock afresh instead of reusing unchanged ones from the last IDR",
+ " --recon FILE write the reconstruction (yuv420p)",
+ " --stats FILE write per-frame statistics as JSON",
+ " --sideinfo FILE per-frame dirty rects, cursor and scroll hints (JSONL)",
+ " --threads N worker threads (default: all cores)",
+ ].join("\n")
+}
+
+function parseIntArg(name: string, v: string | undefined): int throws UsageError {
+ if (v === undefined) throw new UsageError(`missing value for ${name}`)
+ const n = parseInt(v)
+ if (n === undefined) throw new UsageError(`${name} expects an integer, got ${v}`)
+ return n
+}
+
+function parseArgs(argv: string[]): Args throws UsageError {
+ const a: Args = {
+ input: "", output: "", recon: "", stats: "", sideinfo: "", width: 0, height: 0, fpsNum: 30, fpsDen: 1,
+ frames: -1, qp: 26, preset: "medium", profile: 100, keyintSec: 2.0, threads: 0, noSideinfo: false,
+ fullAnalysis: false, cavlc: false, refs: 0, noVfr: false, zeroLatency: false, crf: 26.0, bitrate: 0, maxrate: 0,
+ bufsize: 0, ipOffset: 3, rcMode: 1, aq: 1, refresh: 3, lifetime: true, inter8x8: true, decimate: true, idrReuse: true, globalShift: true, weightp: true, aqTexture: 0, sliceRows: 0, idrSliceRows: -1, idrSlices: 4, bframes: -1, bQpOffset: 6, bAdapt: true, bPyramid: -1, bRefQpOffset: 5, format: "", subme: -1, subpelDirs: 0, keyint: 0, noise: 0,
+ lookahead: -1, laStrength: -1.0, readAheadFrames: -1,
+ }
+ let i = 0
+ while (i < argv.length) {
+ const k = argv[i]!
+ const v = argv[i + 1]
+ if (k === "--input") {
+ a.input = v ?? ""
+ } else if (k === "--output") {
+ a.output = v ?? ""
+ } else if (k === "--recon") {
+ a.recon = v ?? ""
+ } else if (k === "--stats") {
+ a.stats = v ?? ""
+ } else if (k === "--sideinfo") {
+ a.sideinfo = v ?? ""
+ } else if (k === "--width") {
+ a.width = try parseIntArg(k, v)
+ } else if (k === "--height") {
+ a.height = try parseIntArg(k, v)
+ } else if (k === "--frames") {
+ a.frames = try parseIntArg(k, v)
+ } else if (k === "--qp") {
+ a.qp = try parseIntArg(k, v)
+ a.rcMode = 0
+ } else if (k === "--crf") {
+ a.crf = parseFloat(v ?? "") ?? 26.0
+ a.rcMode = 1
+ } else if (k === "--bitrate") {
+ a.bitrate = try parseIntArg(k, v)
+ a.rcMode = 2
+ } else if (k === "--maxrate") {
+ a.maxrate = try parseIntArg(k, v)
+ } else if (k === "--bufsize") {
+ a.bufsize = try parseIntArg(k, v)
+ } else if (k === "--ipoffset") {
+ a.ipOffset = try parseIntArg(k, v)
+ } else if (k === "--aq-strength") {
+ a.aq = try parseIntArg(k, v)
+ } else if (k === "--refresh") {
+ a.refresh = try parseIntArg(k, v)
+ } else if (k === "--refs") {
+ a.refs = try parseIntArg(k, v)
+ } else if (k === "--threads") {
+ a.threads = try parseIntArg(k, v)
+ } else if (k === "--keyint") {
+ a.keyint = try parseIntArg(k, v)
+ } else if (k === "--noise") {
+ a.noise = try parseIntArg(k, v)
+ } else if (k === "--lookahead") {
+ a.lookahead = try parseIntArg(k, v)
+ } else if (k === "--read-ahead") {
+ a.readAheadFrames = try parseIntArg(k, v)
+ } else if (k === "--la-strength") {
+ a.laStrength = parseFloat(v ?? "") ?? -1.0
+ } else if (k === "--subme") {
+ a.subme = try parseIntArg(k, v)
+ } else if (k === "--subpel-dirs") {
+ a.subpelDirs = try parseIntArg(k, v)
+ } else if (k === "--format") {
+ a.format = v ?? ""
+ } else if (k === "--aq-texture") {
+ a.aqTexture = try parseIntArg(k, v)
+ } else if (k === "--slice-rows") {
+ a.sliceRows = try parseIntArg(k, v)
+ } else if (k === "--idr-slice-rows") {
+ a.idrSliceRows = try parseIntArg(k, v)
+ } else if (k === "--idr-slices") {
+ a.idrSlices = try parseIntArg(k, v)
+ } else if (k === "--bframes") {
+ a.bframes = try parseIntArg(k, v)
+ } else if (k === "--b-qp-offset") {
+ a.bQpOffset = try parseIntArg(k, v)
+ } else if (k === "--b-ref-qp-offset") {
+ a.bRefQpOffset = try parseIntArg(k, v)
+ } else if (k === "--preset") {
+ a.preset = v ?? "medium"
+ } else if (k === "--profile") {
+ a.profile = v === "main" ? 77 : 100
+ } else if (k === "--keyint-sec") {
+ a.keyintSec = parseFloat(v ?? "") ?? 2.0
+ } else if (k === "--fps") {
+ const s = v ?? ""
+ const parts = s.split("/")
+ a.fpsNum = try parseIntArg(k, parts[0])
+ a.fpsDen = parts.length > 1 ? try parseIntArg(k, parts[1]) : 1
+ } else if (k === "--no-sideinfo") {
+ a.noSideinfo = true
+ i++
+ continue
+ } else if (k === "--no-inter8x8") {
+ a.inter8x8 = false
+ i++
+ continue
+ } else if (k === "--no-decimate") {
+ a.decimate = false
+ i++
+ continue
+ } else if (k === "--no-weightp") {
+ a.weightp = false
+ i++
+ continue
+ } else if (k === "--no-global-shift") {
+ a.globalShift = false
+ i++
+ continue
+ } else if (k === "--no-idr-reuse") {
+ a.idrReuse = false
+ i++
+ continue
+ } else if (k === "--no-lifetime-aq") {
+ a.lifetime = false
+ i++
+ continue
+ } else if (k === "--no-vfr") {
+ a.noVfr = true
+ i++
+ continue
+ } else if (k === "--zerolatency") {
+ a.zeroLatency = true
+ i++
+ continue
+ } else if (k === "--no-b-adapt") {
+ a.bAdapt = false
+ i++
+ continue
+ } else if (k === "--b-pyramid" || k === "--no-b-pyramid") {
+ a.bPyramid = k === "--b-pyramid" ? 1 : 0
+ i++
+ continue
+ } else if (k === "--cavlc") {
+ a.cavlc = true
+ i++
+ continue
+ } else if (k === "--full-analysis") {
+ a.fullAnalysis = true
+ i++
+ continue
+ } else {
+ throw new UsageError(`unknown option ${k}`)
+ }
+ i += 2
+ }
+ if (a.input === "" || a.output === "" || a.width <= 0 || a.height <= 0) throw new UsageError("missing required options")
+ if ((a.width & 1) !== 0 || (a.height & 1) !== 0) throw new UsageError("width and height must be even")
+ if (a.qp < 0 || a.qp > 51) throw new UsageError("qp must be in 0..51")
+ if (a.bframes === -1) a.bframes = a.zeroLatency ? 0 : 3
+ if (a.bframes < 0 || a.bframes > 3) throw new UsageError("--bframes must be in 0..3")
+ if (a.bPyramid === -1) a.bPyramid = a.preset === "live" ? 0 : 1
+ if (a.refs === 0) a.refs = a.preset === "slow" ? 3 : a.preset === "medium" ? 2 : 1
+ if (a.lookahead < 0) a.lookahead = a.zeroLatency ? 0 : a.preset === "live" ? 2 : 10
+ if (a.readAheadFrames < 0) a.readAheadFrames = 3
+ return a
+}
+
+function readFull(fd: int, buf: Uint8Array, off: int, n: int): int throws Error {
+ let got = 0
+ while (got < n) {
+ const k = try readSync(fd, buf, off + got, n - got)
+ if (k === 0) break
+ got += k
+ }
+ return got
+}
+
+const RA_READ = 0
+const RA_TAKEN = 1
+const RA_TOTAL = 2
+const RA_FAIL = 3
+const RA_DONE = 4
+const RA_BASE = 5
+const RA_SEQ = 6
+const RA_WAITERS = 7
+const RA_LINES = 64
+
+type AheadJob = {
+ fd: int, ring: Uint8Array, fb: int, slotOf: Int32Array, prog: Int32Array, hz: Int32Array, horizons: Int32Array,
+ life: Int32Array[], keep: Uint8Array[], state: LookaheadState, w: int, h: int, depth: int, extra: int, noise: int,
+ geometricTail: bool, windowTail: bool, frameStop: int,
+}
+
+function raPublish(prog: Int32Array, at: int, v: int) {
+ Atomics.store(prog, at, v)
+ Atomics.add(prog, RA_SEQ, 1)
+ if (Atomics.load(prog, RA_WAITERS) > 0) Atomics.notify(prog, RA_SEQ)
+}
+
+// Reads, pushes and takes in the serial order while the main thread leaves room (RA_BASE is the oldest frame it may
+// still use), and returns rather than wait for room, so threads that run one after another (wasm) never block on it.
+function readBatch(job: AheadJob, lines: string[], from: int, taken: int, total: int, nLines: int, id: int) {
+ const prog = job.prog
+ const slots = job.slotOf.length
+ const look = new Lookahead(job.w, job.h, job.depth + job.extra + 1, true)
+ look.attach(job.state, from, job.noise, job.geometricTail, job.windowTail)
+ look.total = total
+ let k = from
+ let t = taken
+ try {
+ while (true) {
+ const base = Atomics.load(prog, RA_BASE)
+ const end = base + 1 + job.extra
+ if (t <= end && (look.total >= 0 ? t < look.total : t + job.depth < k)) {
+ const i = t % job.life.length
+ const horizon = job.horizons[t % job.horizons.length]!
+ job.hz[i] = horizon
+ look.takeAhead(t, horizon, job.life[i]!, job.keep.length > 0 ? job.keep[i]! : new Uint8Array(0))
+ t++
+ raPublish(prog, RA_TAKEN, t)
+ } else if (look.total < 0 && k <= end + job.depth && (k - from < lines.length || k >= nLines)) {
+ let slot = 0
+ let j = base
+ while (j < k) {
+ if (job.slotOf[j % slots]! === slot) {
+ slot++
+ j = base
+ } else {
+ j++
+ }
+ }
+ const got = job.frameStop >= 0 && k >= job.frameStop ? 0 : try readFull(job.fd, job.ring, slot * job.fb, job.fb)
+ if (got < job.fb) {
+ look.total = k
+ raPublish(prog, RA_TOTAL, k)
+ } else {
+ const line = k - from < lines.length ? lines[k - from]! : ""
+ const side = line !== "" ? try parseSideInfo(line) : undefined
+ job.slotOf[k % slots] = slot
+ look.push(job.ring, slot * job.fb, job.slotOf[(k - 1) % slots]! * job.fb, side)
+ k++
+ raPublish(prog, RA_READ, k)
+ }
+ } else {
+ break
+ }
+ }
+ } catch (e) {
+ raPublish(prog, RA_FAIL, k)
+ }
+ raPublish(prog, RA_DONE, id)
+}
+
+class ReadAhead {
+ job: AheadJob
+ sideLines: string[]
+ batch: Thread<void> | undefined = undefined
+ spawned = 0
+
+ constructor(job: AheadJob, sideLines: string[], read: int) {
+ this.job = job
+ this.sideLines = sideLines
+ Atomics.store(job.prog, RA_READ, read)
+ Atomics.store(job.prog, RA_TAKEN, 1)
+ Atomics.store(job.prog, RA_TOTAL, -1)
+ Atomics.store(job.prog, RA_FAIL, -1)
+ }
+
+ join() {
+ const b = this.batch
+ if (b === undefined) return
+ b.join()
+ this.batch = undefined
+ }
+
+ advance(base: int) {
+ const prog = this.job.prog
+ if (base > Atomics.load(prog, RA_BASE)) Atomics.store(prog, RA_BASE, base)
+ if (this.batch !== undefined && Atomics.load(prog, RA_DONE) === this.spawned) this.join()
+ const taken = Atomics.load(prog, RA_TAKEN)
+ const total = Atomics.load(prog, RA_TOTAL)
+ if (this.batch !== undefined || Atomics.load(prog, RA_FAIL) >= 0 || taken > base + 1 + this.job.extra ||
+ (total >= 0 && taken >= total)) {
+ return
+ }
+ const from = Atomics.load(prog, RA_READ)
+ const lines = this.sideLines.slice(from, from + RA_LINES)
+ const nLines = this.sideLines.length
+ const job = this.job
+ this.spawned++
+ const id = this.spawned
+ this.batch = Thread.spawn(() => readBatch(job, lines, from, taken, total, nLines, id))
+ }
+
+ wait(n: int): void throws Error {
+ const prog = this.job.prog
+ // Frame n-1 is done with before this wait; freeing its slot now keeps a reader that is keeping up with real-time
+ // input inside the per-frame path's depth + 2 slots, so the extra slots are only touched when the encoder falls behind.
+ if (n > Atomics.load(prog, RA_BASE)) Atomics.store(prog, RA_BASE, n)
+ while (true) {
+ const seq = Atomics.load(prog, RA_SEQ)
+ const total = Atomics.load(prog, RA_TOTAL)
+ if (Atomics.load(prog, RA_TAKEN) > n || (total >= 0 && n >= total)) return
+ const fail = Atomics.load(prog, RA_FAIL)
+ if (fail >= 0) {
+ if (fail < this.sideLines.length && this.sideLines[fail]! !== "") try parseSideInfo(this.sideLines[fail]!)
+ throw new Error("can't read the input")
+ }
+ if (this.batch === undefined || Atomics.load(prog, RA_DONE) === this.spawned) {
+ this.advance(n - 1)
+ } else {
+ Atomics.add(prog, RA_WAITERS, 1)
+ Atomics.wait(prog, RA_SEQ, seq)
+ Atomics.sub(prog, RA_WAITERS, 1)
+ }
+ }
+ }
+
+ // What the serial loop would have read when taking frame n: a fallback take must not see further.
+ readFor(n: int): int {
+ const got = Atomics.load(this.job.prog, RA_READ)
+ return got < n + this.job.depth + 1 ? got : n + this.job.depth + 1
+ }
+
+ endedFor(n: int): bool {
+ const total = Atomics.load(this.job.prog, RA_TOTAL)
+ return total >= 0 && total <= n + this.job.depth
+ }
+}
+
+function writeFragment(format: string, fd: int, dir: string, frag: u8[], index: int): int throws Error {
+ if (format === "hls") {
+ const sfd = try openSync(path.join(dir, segmentName(index)), "w")
+ try writeSync(sfd, frag)
+ try closeSync(sfd)
+ } else {
+ try writeSync(fd, frag)
+ }
+ return frag.length
+}
+
+class Sink {
+ format: string
+ fd: int
+ dir: string
+ mux: Mp4Muxer
+ initWritten = false
+ segDurations: f64[] = []
+ bytes = 0
+
+ constructor(format: string, fd: int, dir: string, mux: Mp4Muxer) {
+ this.format = format
+ this.fd = fd
+ this.dir = dir
+ this.mux = mux
+ }
+
+ fragmented(): bool {
+ return this.format === "fmp4" || this.format === "hls"
+ }
+}
+
+function flushFragment(sink: Sink, nextFrame: int): void throws Error {
+ const frag = sink.mux.fragment(sink.mux.sizes.length, nextFrame)
+ sink.bytes += try writeFragment(sink.format, sink.fd, sink.dir, frag, sink.segDurations.length + 1)
+ sink.segDurations.push(f64(sink.mux.lastFragmentTicks) / f64(TIMESCALE))
+}
+
+function emitUnit(sink: Sink, bits: u8[], index: int, idr: bool): void throws Error {
+ if (sink.format === "annexb") {
+ try writeSync(sink.fd, bits)
+ sink.bytes += bits.length
+ return
+ }
+ if (sink.fragmented() && idr && sink.mux.pendingSamples() > 0) try flushFragment(sink, index)
+ sink.mux.addSample(bits, index, idr)
+ if (sink.fragmented() && !sink.initWritten) {
+ const init = sink.mux.initSegment()
+ try writeSync(sink.fd, init)
+ sink.bytes += init.length
+ sink.initWritten = true
+ }
+}
+
+function emitCoded(sink: Sink, enc: Encoder, bits: u8[], firstStat: int): void throws Error {
+ let off = 0
+ for (let k = firstStat; k < enc.frames.length; k++) {
+ const f = enc.frames[k]!
+ if (f.bytes === 0) continue
+ try emitUnit(sink, bits.slice(off, off + f.bytes), f.index, f.type === "I")
+ off += f.bytes
+ }
+}
+
+function statsJson(enc: Encoder, args: Args, wallMs: f64, bytes: int, frameMap: int[]): string {
+ const frames: string[] = []
+ for (const f of enc.frames) {
+ frames.push(frameJson(f))
+ }
+ const mbs = enc.mbw * enc.mbh
+ const total = enc.tAnalysis + enc.tMotion + enc.tMode + enc.tTq + enc.tEntropy + enc.tDeblock
+ return "{" + [
+ `"encoder":"capcodec"`,
+ `"preset":${JSON.stringify(args.preset)}`,
+ `"width":${args.width}`,
+ `"height":${args.height}`,
+ `"mbs":${mbs}`,
+ `"frames_in":${enc.frameIndex}`,
+ `"frames_coded":${enc.codedFrames}`,
+ `"frames_dropped":${enc.frameIndex - enc.codedFrames}`,
+ `"bytes":${bytes}`,
+ `"time_ms":{"total":${wallMs},"stages":${total},"analysis":${enc.tAnalysis},"motion":${enc.tMotion},"mode":${enc.tMode},"tq":${enc.tTq},"entropy":${enc.tEntropy},"deblock":${enc.tDeblock}}`,
+ `"frame_map":[${frameMap.join(",")}]`,
+ `"frames":[${frames.join(",")}]`,
+ ].join(",") + "}"
+}
+
+function frameJson(f: FrameStats): string {
+ return `{"i":${f.index},"type":"${f.type}","bytes":${f.bytes},"qp":${f.qp},"changed_mbs":${f.changedMbs},` +
+ `"ms":{"analysis":${f.analysis},"motion":${f.motion},"mode":${f.mode},"tq":${f.tq},"entropy":${f.entropy},` +
+ `"deblock":${f.deblock},"total":${f.total}},"reused":${f.reused}}`
+}
+
+function encodeCommand(args: Args): void throws Error {
+ const t0 = performance.now()
+ const w = args.width
+ const h = args.height
+ const frameBytes = w * h * 3 / 2
+ const fb = Math.trunc(frameBytes)
+ const enc = new Encoder({
+ width: w, height: h, fpsNum: args.fpsNum, fpsDen: args.fpsDen, qp: args.qp,
+ keyint: args.keyint > 0 ? args.keyint : Math.max(1, Math.round(args.keyintSec * f64(args.fpsNum) / f64(args.fpsDen))),
+ profile: args.profile,
+ preset: args.preset, cabac: !args.cavlc, refs: args.refs, rcMode: args.rcMode, crf: args.crf,
+ bitrate: args.bitrate, maxrate: args.maxrate > 0 ? args.maxrate : Math.round(f64(args.bitrate) * 1.5),
+ bufsize: args.bufsize, ipOffset: args.ipOffset, weightedPred: args.weightp, worker: false,
+ })
+ enc.threads = args.threads > 0 ? args.threads : availableParallelism()
+ enc.vfr = !args.noVfr && !args.fullAnalysis
+ enc.aqStrength = args.aq
+ enc.aqTexture = args.aqTexture
+ enc.noise = args.noise
+ enc.refreshDelta = args.refresh
+ enc.lifetimeAq = args.lifetime
+ enc.inter8x8 = args.inter8x8
+ enc.decimate = args.decimate
+ enc.idrReuse = args.idrReuse
+ enc.globalShift = args.globalShift
+ enc.sliceRowsP = args.sliceRows
+ enc.sliceRowsI = args.idrSliceRows >= 0 ? args.idrSliceRows : args.sliceRows
+ enc.idrSlices = args.idrSlices < 1 ? 1 : args.idrSlices
+ if (args.subme >= 0) enc.subpel = args.subme
+ if (args.subpelDirs > 0) {
+ enc.subpelDirs = args.subpelDirs
+ enc.videoHpelDirs = args.subpelDirs
+ enc.videoQpelDirs = args.subpelDirs
+ }
+ enc.fullAnalysis = args.fullAnalysis
+ enc.bQpOffset = args.bQpOffset
+ enc.bAdapt = args.bAdapt
+ enc.pyramid = args.bPyramid === 1
+ enc.bRefQpOffset = args.bRefQpOffset
+ if (args.bframes > 0) enc.configureB(args.bframes)
+ if (args.laStrength >= 0) enc.laStrength = args.laStrength
+ let sideLines: string[] = []
+ if (args.sideinfo !== "" && !args.noSideinfo) {
+ const text = try readFileSync(args.sideinfo)
+ sideLines = text.split("\n")
+ }
+ const inFd = args.input === "-" ? 0 : try openSync(args.input, "r")
+ let format = args.format
+ if (format === "") {
+ const ext = path.extname(args.output).toLowerCase()
+ format = ext === ".mp4" ? "mp4" : ext === ".fmp4" ? "fmp4" : ext === ".m3u8" ? "hls" : "annexb"
+ }
+ const outDir = path.dirname(args.output)
+ const outFd = format === "hls" ? try openSync(path.join(outDir, "init.mp4"), "w") : args.output === "-" ? 1 : try openSync(args.output, "w")
+ const mux = new Mp4Muxer(w, h, args.fpsNum, args.fpsDen)
+ mux.reorder = enc.bframes > 0
+ mux.reorderFrames = enc.pyramid && enc.bframes >= 2 ? 2 : 1
+ const sink = new Sink(format, outFd, outDir, mux)
+ const reconFd = args.recon === "" ? -1 : try openSync(args.recon, "w")
+ const depth = args.lookahead
+ const pushLook = depth > 0 && !enc.flatLookahead()
+ const readAhead = enc.threads > 1
+ const extra = readAhead && enc.bframes > 0 && pushLook ? args.readAheadFrames : 0
+ const slots = depth + (readAhead ? 2 : 1) + extra
+ const ring = new Uint8Array(fb * slots)
+ const slotOf = new Int32Array(slots)
+ for (let k = 0; k < slots; k++) slotOf[k] = k
+ let sides: (SideInfo | undefined)[] = []
+ for (let k = 0; k < slots; k++) sides.push(undefined)
+ // While this thread waits for or codes frame n the reader may push up to frame n + depth + extra + 1; a take that
+ // falls back to this thread still needs frames n..n+depth in the lookahead's ring, and the encoder frame n's change map.
+ const look = new Lookahead(w, h, extra > 0 ? depth + extra + 1 : depth, false)
+ const geometricTail = enc.bframes === 0
+ const windowTail = geometricTail && enc.keyint > enc.laSpan
+ look.noise = args.noise
+ look.geometricTail = geometricTail
+ look.windowTail = windowTail
+ const noise = args.noise
+ const laMbs = depth > 0 ? ((w + 15) >> 4) * ((h + 15) >> 4) : 0
+ const laLife = [new Int32Array(laMbs), new Int32Array(laMbs)]
+ const laKeep = [new Uint8Array(laMbs), new Uint8Array(laMbs)]
+ for (let k = 0; k < extra; k++) {
+ laLife.push(new Int32Array(laMbs))
+ laKeep.push(new Uint8Array(laMbs))
+ }
+ let ra: ReadAhead | undefined = undefined
+ let read = 0
+ let eof = false
+ let pending: Thread<int> | undefined = undefined
+ const aheadRead = new Int32Array(1)
+ const inRing = new Int32Array(1)
+ Atomics.store(inRing, 0, 1)
+ const none = new Uint8Array(0)
+ let pendingHorizon = -1
+ let aheadHorizon = -1
+ let n = 0
+ let frameMap: int[] = []
+ enc.wantRecon = reconFd >= 0
+ enc.frameThreads = !args.zeroLatency
+ const pipelined = enc.bframes > 0 || enc.intraParallel()
+ while (args.frames < 0 || n < args.frames) {
+ if (ra !== undefined) {
+ try ra.wait(n)
+ read = ra.readFor(n)
+ eof = ra.endedFor(n)
+ look.pushed = read
+ aheadHorizon = ra.job.hz[n % laLife.length]!
+ }
+ while (!eof && read <= n + depth) {
+ const slot = read % slots
+ let got = 0
+ if (pending !== undefined) {
+ got = pending.join()
+ pending = undefined
+ if (got < 0) throw new Error("can't read the input")
+ if (got === fb && pushLook) look.pushed++
+ aheadHorizon = pendingHorizon
+ } else if (args.frames < 0 || read < args.frames) {
+ got = try readFull(inFd, ring, slot * fb, fb)
+ if (got === fb) {
+ sides[slot] = read < sideLines.length && sideLines[read]! !== "" ? try parseSideInfo(sideLines[read]!) : undefined
+ if (pushLook) look.push(ring, slot * fb, ((read + slots - 1) % slots) * fb, sides[slot])
+ }
+ }
+ if (got < fb) {
+ eof = true
+ break
+ }
+ read++
+ }
+ if (n >= read) break
+ if (depth > 0) {
+ if (eof && look.total < 0) look.finish()
+ const life = laLife[n % laLife.length]!
+ const keep = laKeep[n % laKeep.length]!
+ if (aheadHorizon >= 0 && aheadHorizon === enc.laHorizon()) {
+ look.taken++
+ enc.useLookahead(life, keep)
+ } else {
+ if (ra !== undefined) ra.join()
+ enc.takeLookahead(look, life, keep)
+ }
+ aheadHorizon = -1
+ enc.useChanges(look.changesOf(n), n, look.noise)
+ }
+ if (extra > 0 && n === 0 && !eof) {
+ const horizons = new Int32Array(enc.keyint)
+ for (let k = 0; k < enc.keyint; k++) horizons[k] = enc.laHorizonAt(k)
+ ra = new ReadAhead({
+ fd: inFd, ring, fb, slotOf, prog: new Int32Array(8), hz: new Int32Array(laLife.length), horizons, life: laLife,
+ keep: enc.wantsKeepMap() ? laKeep : [], state: look.share(), w, h, depth, extra, noise, geometricTail, windowTail,
+ frameStop: args.frames,
+ }, sideLines, read)
+ }
+ if (ra !== undefined) {
+ ra.advance(n)
+ } else if (readAhead && !eof && (args.frames < 0 || read < args.frames)) {
+ const buf = ring
+ const slot = read % slots
+ const off = slot * fb
+ const prevOff = ((read + slots - 1) % slots) * fb
+ const side = read < sideLines.length && sideLines[read]! !== "" ? try parseSideInfo(sideLines[read]!) : undefined
+ sides[slot] = side
+ const hasSide = side !== undefined
+ const dirty = side !== undefined ? side.dirty : []
+ const scroll = side !== undefined ? side.scroll : []
+ const st = look.share()
+ const at = look.pushed
+ const target = n + 1
+ const horizon = pushLook && (args.frames < 0 || target < args.frames) ? enc.laHorizonAt(target) : -1
+ const life = laLife[target % 2]!
+ const keep = enc.wantsKeepMap() ? laKeep[target % 2]! : new Uint8Array(0)
+ pendingHorizon = horizon
+ Atomics.store(aheadRead, 0, 0)
+ pending = Thread.spawn(() => {
+ try {
+ const got = try readFull(inFd, buf, off, fb)
+ Atomics.store(aheadRead, 0, got >= fb ? 1 : -1)
+ if (pushLook) {
+ const worker = new Lookahead(w, h, depth, true)
+ worker.attach(st, at, noise, geometricTail, windowTail)
+ if (got === fb) {
+ let s: SideInfo | undefined = undefined
+ if (hasSide) {
+ const t = new SideInfo()
+ t.dirty = dirty
+ t.scroll = scroll
+ s = t
+ }
+ worker.push(buf, off, prevOff, s)
+ } else {
+ worker.total = at
+ }
+ if (horizon >= 0) worker.takeAhead(target, horizon, life, keep)
+ }
+ return got
+ } catch (e) {
+ Atomics.store(aheadRead, 0, -1)
+ return -1
+ }
+ })
+ }
+ const off = slotOf[n % slots]! * fb
+ const side = ra === undefined || n <= depth ? sides[n % slots] :
+ n < sideLines.length && sideLines[n]! !== "" ? try parseSideInfo(sideLines[n]!) : undefined
+ const next = n + 1
+ let nextFrame = none
+ let nextReady = inRing
+ if (readAhead && (next >= sideLines.length || sideLines[next]! === "")) {
+ if (next < read) {
+ nextFrame = ring
+ } else if (pending !== undefined) {
+ nextFrame = ring
+ nextReady = aheadRead
+ }
+ }
+ enc.expectNext(nextFrame, slotOf[next % slots]! * fb, nextReady)
+ if (pipelined) {
+ const first = enc.frames.length
+ const bits = enc.submit(ring, off, side)
+ try emitCoded(sink, enc, bits, first)
+ for (const r of enc.takeRecon()) try writeSync(reconFd, r)
+ } else {
+ const bits = enc.encodeFrame(ring, off, side)
+ if (bits.length > 0) {
+ try emitUnit(sink, bits, n, enc.frames[enc.frames.length - 1]!.type === "I")
+ frameMap.push(n)
+ if (reconFd >= 0) try writeSync(reconFd, enc.reconFrame())
+ }
+ }
+ n++
+ }
+ if (ra !== undefined) ra.join()
+ if (pipelined) {
+ enc.expectNext(none, 0, aheadRead)
+ const first = enc.frames.length
+ const tail = enc.flush()
+ try emitCoded(sink, enc, tail, first)
+ for (const r of enc.takeRecon()) try writeSync(reconFd, r)
+ for (const f of enc.frames) {
+ if (f.bytes === 0) continue
+ let j = frameMap.length
+ frameMap.push(f.index)
+ while (j > 0 && frameMap[j - 1]! > f.index) {
+ frameMap[j] = frameMap[j - 1]!
+ j--
+ }
+ frameMap[j] = f.index
+ }
+ }
+ try finishOutput(args, enc, sink, n, frameMap, inFd, reconFd, t0)
+}
+
+function finishOutput(args: Args, enc: Encoder, sink: Sink, n: int, frameMap: int[], inFd: int, reconFd: int, t0: f64): void throws Error {
+ if (sink.format === "mp4") {
+ const file = sink.mux.progressive(n)
+ try writeSync(sink.fd, file)
+ sink.bytes += file.length
+ } else if (sink.fragmented() && sink.mux.pendingSamples() > 0) {
+ try flushFragment(sink, n)
+ }
+ const bytes = sink.bytes
+ if (sink.format === "hls") {
+ const segDurations = sink.segDurations
+ try writeFileSync(args.output, mediaPlaylist(segDurations, "init.mp4"))
+ const sps = sink.mux.sps
+ const hex = (b: u8): string => {
+ const v = int(b)
+ const d = "0123456789abcdef"
+ return d.slice(v >> 4, (v >> 4) + 1) + d.slice(v & 15, (v & 15) + 1)
+ }
+ const codecs = sps.length >= 4 ? `avc1.${hex(sps[1]!)}${hex(sps[2]!)}${hex(sps[3]!)}` : "avc1.640028"
+ let total = 0.0
+ for (const d of segDurations) total += d
+ const bw = total > 0.0 ? Math.round(f64(bytes) * 8.0 / total * 1.2) : 1000000
+ try writeFileSync(path.join(sink.dir, "master.m3u8"), masterPlaylist(path.basename(args.output), bw, codecs, args.width, args.height, f64(args.fpsNum) / f64(args.fpsDen)))
+ }
+ if (inFd !== 0) try closeSync(inFd)
+ if (sink.fd !== 1) try closeSync(sink.fd)
+ if (reconFd >= 0) try closeSync(reconFd)
+ const wall = performance.now() - t0
+ if (args.stats !== "") try writeFileSync(args.stats, statsJson(enc, args, wall, bytes, frameMap))
+ console.error(`capcodec: ${n} frames, ${bytes} bytes, ${(f64(n) * 1000.0 / wall).toFixed(1)} fps`)
+}
+
+function main(): int {
+ const argv = process.argv.slice(2)
+ if (argv.length === 0 || argv[0]! !== "encode") {
+ console.error(usage())
+ return 2
+ }
+ try {
+ const args = try parseArgs(argv.slice(1))
+ try encodeCommand(args)
+ } catch (e) {
+ console.error(`capcodec: ${e.message}`)
+ if (e instanceof UsageError) console.error(usage())
+ return 1
+ }
+ return 0
+}
diff --git a/capcodec/src/analysis.tov b/capcodec/src/analysis.tov
new file mode 100644
index 000000000..506e6489d
--- /dev/null
+++ b/capcodec/src/analysis.tov
@@ -0,0 +1,1282 @@
+export type ScrollHint = { x: int, y: int, w: int, h: int, dx: int, dy: int }
+
+export class SideInfo {
+ dirty: int[] = []
+ cursorX = -1
+ cursorY = -1
+ scroll: ScrollHint[] = []
+}
+
+type RawScroll = { rect: int[], dx: int, dy: int }
+type RawSide = { frame?: int, dirty?: int[][], cursor?: int[], scroll?: RawScroll[] }
+
+export function parseSideInfo(line: string): SideInfo throws SyntaxError {
+ const raw: RawSide = try JSON.parse(line)
+ const s = new SideInfo()
+ const dirty = raw.dirty ?? []
+ for (const r of dirty) {
+ if (r.length < 4) continue
+ s.dirty.push(r[0]!)
+ s.dirty.push(r[1]!)
+ s.dirty.push(r[2]!)
+ s.dirty.push(r[3]!)
+ }
+ const c = raw.cursor
+ if (c !== undefined && c.length >= 2) {
+ s.cursorX = c[0]!
+ s.cursorY = c[1]!
+ }
+ const sc = raw.scroll ?? []
+ for (const h of sc) {
+ if (h.rect.length < 4) continue
+ s.scroll.push({ x: h.rect[0]!, y: h.rect[1]!, w: h.rect[2]!, h: h.rect[3]!, dx: h.dx, dy: h.dy })
+ }
+ return s
+}
+
+export function markRects(changed: Uint8Array, mbw: int, mbh: int, rects: int[]): int {
+ let n = 0
+ for (let i = 0; i + 3 < rects.length; i += 4) {
+ const x0 = rects[i]!
+ const y0 = rects[i + 1]!
+ const w = rects[i + 2]!
+ const h = rects[i + 3]!
+ if (w <= 0 || h <= 0) continue
+ let mx0 = x0 >> 4
+ let my0 = y0 >> 4
+ let mx1 = (x0 + w - 1) >> 4
+ let my1 = (y0 + h - 1) >> 4
+ if (mx0 < 0) mx0 = 0
+ if (my0 < 0) my0 = 0
+ if (mx1 >= mbw) mx1 = mbw - 1
+ if (my1 >= mbh) my1 = mbh - 1
+ for (let my = my0; my <= my1; my++) {
+ for (let mx = mx0; mx <= mx1; mx++) {
+ const k = my * mbw + mx
+ if (changed[k]! === 0) {
+ changed[k] = 1
+ n++
+ }
+ }
+ }
+ }
+ return n
+}
+
+export function diffMb(src: Uint8Array, so: int, ss: int, frame: Uint8Array, fo: int, fs: int, w: int, h: int, noise: int): bool {
+ if (noise === 0 && w === 16) {
+ for (let y = 0; y < h; y++) {
+ if (u8x16.load(src, so + y * ss).ne(u8x16.load(frame, fo + y * fs)).mask() !== 0) return true
+ }
+ return false
+ }
+ if (noise === 0 && w === 8) {
+ let acc = i16x8.splat(0)
+ for (let y = 0; y < h; y++) acc |= i16x8.loadU8(src, so + y * ss) ^ i16x8.loadU8(frame, fo + y * fs)
+ return acc.ne(i16x8.splat(0)).mask() !== 0
+ }
+ if (noise === 0) {
+ for (let y = 0; y < h; y++) {
+ const a = so + y * ss
+ const b = fo + y * fs
+ for (let x = 0; x < w; x++) {
+ if (src[a + x]! !== frame[b + x]!) return true
+ }
+ }
+ return false
+ }
+ if (noise > 255 || h > 16 || (w !== 16 && w !== 8)) return diffNoisy(src, so, ss, frame, fo, fs, w, h, noise)
+ if (w === 16 && h === 16) return noisy16(src, so, ss, frame, fo, fs, noise)
+ const budget = (noise * w * h) >> 1
+ if (w === 16) {
+ let top = u8x32.splat(0)
+ let sum = u32x8.splat(0)
+ let y = 0
+ while (y + 2 <= h) {
+ const p = u8x32.concat(u8x16.load(src, so + y * ss), u8x16.load(src, so + (y + 1) * ss))
+ const q = u8x32.concat(u8x16.load(frame, fo + y * fs), u8x16.load(frame, fo + (y + 1) * fs))
+ top = top.max(p.absDiff(q))
+ sum = sum + u8x32.sadParts(p, q)
+ y += 2
+ }
+ if (y < h) {
+ const p = u8x32.concat(u8x16.load(src, so + y * ss), u8x16.splat(0))
+ const q = u8x32.concat(u8x16.load(frame, fo + y * fs), u8x16.splat(0))
+ top = top.max(p.absDiff(q))
+ sum = sum + u8x32.sadParts(p, q)
+ }
+ return top.gt(u8x32.splat(noise)).mask() !== 0 || sum.sum() > budget
+ }
+ let top = i16x8.splat(0)
+ let sum = i16x8.splat(0)
+ for (let y = 0; y < h; y++) {
+ const d = (i16x8.loadU8(src, so + y * ss) - i16x8.loadU8(frame, fo + y * fs)).abs()
+ top = top.max(d)
+ sum = sum + d
+ }
+ return top.gt(i16x8.splat(noise)).mask() !== 0 || sum.sum() > budget
+}
+
+function noisy16(src: Uint8Array, so: int, ss: int, frame: Uint8Array, fo: int, fs: int, noise: int): bool {
+ let top = u8x32.splat(0)
+ let sum = u32x8.splat(0)
+ for (let y = 0; y < 16; y += 2) {
+ const p = u8x32.concat(u8x16.load(src, so + y * ss), u8x16.load(src, so + (y + 1) * ss))
+ const q = u8x32.concat(u8x16.load(frame, fo + y * fs), u8x16.load(frame, fo + (y + 1) * fs))
+ top = top.max(p.absDiff(q))
+ sum = sum + u8x32.sadParts(p, q)
+ }
+ return top.gt(u8x32.splat(noise)).mask() !== 0 || sum.sum() > noise * 128
+}
+
+function noisyChroma(u: Uint8Array, uo: int, v: Uint8Array, vo: int, ss: int, frame: Uint8Array, fu: int, fv: int, fs: int,
+ noise: int): bool {
+ let top = i16x16.splat(0)
+ let sum = i16x16.splat(0)
+ for (let y = 0; y < 8; y++) {
+ const p = i16x16.concat(i16x8.loadU8(u, uo + y * ss), i16x8.loadU8(v, vo + y * ss))
+ const q = i16x16.concat(i16x8.loadU8(frame, fu + y * fs), i16x8.loadU8(frame, fv + y * fs))
+ const d = (p - q).abs()
+ top = top.max(d)
+ sum = sum + d
+ }
+ const budget = noise * 32
+ return top.gt(i16x16.splat(noise)).mask() !== 0 || sum.low().sum() > budget || sum.high().sum() > budget
+}
+
+function noisyPair(src: Uint8Array, so: int, ss: int, frame: Uint8Array, fo: int, fs: int, noise: int): int {
+ let top = u8x32.splat(0)
+ let sum = u32x8.splat(0)
+ for (let y = 0; y < 16; y++) {
+ const p = u8x32.load(src, so + y * ss)
+ const q = u8x32.load(frame, fo + y * fs)
+ top = top.max(p.absDiff(q))
+ sum = sum + u8x32.sadParts(p, q)
+ }
+ const m = top.gt(u8x32.splat(noise)).mask()
+ const z = top.ne(u8x32.splat(0)).mask()
+ const budget = noise * 128
+ const a = (m & 0xffff) !== 0 || sum.low().sum() > budget ? 1 : 0
+ const b = (m >> 16) !== 0 || sum.high().sum() > budget ? 2 : 0
+ const c = (z & 0xffff) !== 0 ? 4 : 0
+ const e = (z >> 16) !== 0 ? 8 : 0
+ return a | b | c | e
+}
+
+function noisyChromaPair(u: Uint8Array, uo: int, v: Uint8Array, vo: int, ss: int, frame: Uint8Array, fu: int, fv: int,
+ fs: int, noise: int): int {
+ let top = u8x32.splat(0)
+ let sum = u32x8.splat(0)
+ for (let y = 0; y < 8; y++) {
+ const p = u8x32.concat(u8x16.load(u, uo + y * ss), u8x16.load(v, vo + y * ss))
+ const q = u8x32.concat(u8x16.load(frame, fu + y * fs), u8x16.load(frame, fv + y * fs))
+ top = top.max(p.absDiff(q))
+ sum = sum + u8x32.sadParts(p, q)
+ }
+ const m = top.gt(u8x32.splat(noise)).mask()
+ const z = top.ne(u8x32.splat(0)).mask()
+ const budget = noise * 32
+ const a = (m & 0xff00ff) !== 0 || int(sum.lane(0)) > budget || int(sum.lane(4)) > budget ? 1 : 0
+ const b = (m & 0xff00ff00) !== 0 || int(sum.lane(2)) > budget || int(sum.lane(6)) > budget ? 2 : 0
+ const c = (z & 0xff00ff) !== 0 ? 4 : 0
+ const e = (z & 0xff00ff00) !== 0 ? 8 : 0
+ return a | b | c | e
+}
+
+function samePair(src: Uint8Array, so: int, ss: int, frame: Uint8Array, fo: int, fs: int): bool {
+ const zero = u8x32.splat(0)
+ for (let y = 0; y < 16; y += 4) {
+ const s = so + y * ss
+ const f = fo + y * fs
+ const acc = (u8x32.load(src, s) ^ u8x32.load(frame, f)) | (u8x32.load(src, s + ss) ^ u8x32.load(frame, f + fs)) |
+ (u8x32.load(src, s + 2 * ss) ^ u8x32.load(frame, f + 2 * fs)) |
+ (u8x32.load(src, s + 3 * ss) ^ u8x32.load(frame, f + 3 * fs))
+ if (acc.eq(zero).mask() !== 0xffffffff) return false
+ }
+ return true
+}
+
+function sameChromaPair(u: Uint8Array, uo: int, v: Uint8Array, vo: int, ss: int, frame: Uint8Array, fu: int, fv: int,
+ fs: int): bool {
+ const zero = u8x16.splat(0)
+ for (let y = 0; y < 8; y += 4) {
+ let acc = zero
+ for (let r = y; r < y + 4; r++) {
+ acc = acc | (u8x16.load(u, uo + r * ss) ^ u8x16.load(frame, fu + r * fs)) |
+ (u8x16.load(v, vo + r * ss) ^ u8x16.load(frame, fv + r * fs))
+ }
+ if (acc.eq(zero).mask() !== 0xffff) return false
+ }
+ return true
+}
+
+export function changeMap(sy: Uint8Array, syo: int, sys: int, su: Uint8Array, suo: int, sv: Uint8Array, svo: int, scs: int,
+ f: Uint8Array, fyo: int, fys: int, fuo: int, fvo: int, fcs: int, w: int, h: int, noise: int, out: Uint8Array): int {
+ const mbw = (w + 15) >> 4
+ const mbh = (h + 15) >> 4
+ let n = 0
+ for (let mby = 0; mby < mbh; mby++) {
+ const py = mby * 16
+ const cy = mby * 8
+ const row = mby * mbw
+ let mbx = 0
+ if (noise <= 255 && py + 16 <= h) {
+ while ((mbx + 2) * 16 <= w) {
+ const so = syo + py * sys + mbx * 16
+ const fo = fyo + py * fys + mbx * 16
+ const sc = cy * scs + mbx * 8
+ const fc = cy * fcs + mbx * 8
+ let d = samePair(sy, so, sys, f, fo, fys) ? 0 : noisyPair(sy, so, sys, f, fo, fys, noise)
+ if (d === 0 ? !sameChromaPair(su, suo + sc, sv, svo + sc, scs, f, fuo + fc, fvo + fc, fcs) : (d & 3) !== 3) {
+ d |= noisyChromaPair(su, suo + sc, sv, svo + sc, scs, f, fuo + fc, fvo + fc, fcs, noise)
+ }
+ if (d !== 0) {
+ if ((d & 4) !== 0) out[row + mbx] = (d & 1) !== 0 ? 1 : 2
+ if ((d & 8) !== 0) out[row + mbx + 1] = (d & 2) !== 0 ? 1 : 2
+ n += (d & 1) + ((d >> 1) & 1)
+ }
+ mbx += 2
+ }
+ }
+ for (; mbx < mbw; mbx++) {
+ const c = mbChange(sy, syo, sys, su, suo, sv, svo, scs, f, fyo, fys, fuo, fvo, fcs, w, h, noise, mbx, mby)
+ if (c !== 0) {
+ out[row + mbx] = c
+ if (c === 1) n++
+ }
+ }
+ }
+ return n
+}
+
+export function mbChange(sy: Uint8Array, syo: int, sys: int, su: Uint8Array, suo: int, sv: Uint8Array, svo: int, scs: int,
+ f: Uint8Array, fyo: int, fys: int, fuo: int, fvo: int, fcs: int, w: int, h: int, noise: int, mbx: int, mby: int): int {
+ const vector = noise <= 255
+ const px = mbx * 16
+ const py = mby * 16
+ const bw = px + 16 <= w ? 16 : w - px
+ const bh = py + 16 <= h ? 16 : h - py
+ const so = syo + py * sys + px
+ const fo = fyo + py * fys + px
+ const lumaSame = !diffMb(sy, so, sys, f, fo, fys, bw, bh, 0)
+ if (!lumaSame && (noise === 0 || (vector && bw === 16 && bh === 16 ? noisy16(sy, so, sys, f, fo, fys, noise) :
+ diffMb(sy, so, sys, f, fo, fys, bw, bh, noise)))) return 1
+ const cw = w >> 1
+ const ch = h >> 1
+ const cx = mbx * 8
+ const cy = mby * 8
+ const cbw = cx + 8 <= cw ? 8 : cw - cx
+ const cbh = cy + 8 <= ch ? 8 : ch - cy
+ const sc = cy * scs + cx
+ const fc = cy * fcs + cx
+ const chromaSame = !diffMb(su, suo + sc, scs, f, fuo + fc, fcs, cbw, cbh, 0) &&
+ !diffMb(sv, svo + sc, scs, f, fvo + fc, fcs, cbw, cbh, 0)
+ if (!chromaSame && (noise === 0 || (vector && cbw === 8 && cbh === 8 ?
+ noisyChroma(su, suo + sc, sv, svo + sc, scs, f, fuo + fc, fvo + fc, fcs, noise) :
+ diffMb(su, suo + sc, scs, f, fuo + fc, fcs, cbw, cbh, noise) || diffMb(sv, svo + sc, scs, f, fvo + fc, fcs, cbw, cbh, noise)))) {
+ return 1
+ }
+ return lumaSame && chromaSame ? 0 : 2
+}
+
+function diffNoisy(src: Uint8Array, so: int, ss: int, frame: Uint8Array, fo: int, fs: int, w: int, h: int, noise: int): bool {
+ const budget = (noise * w * h) >> 1
+ let sum = 0
+ for (let y = 0; y < h; y++) {
+ const a = so + y * ss
+ const b = fo + y * fs
+ for (let x = 0; x < w; x++) {
+ const d = int(src[a + x]!) - int(frame[b + x]!)
+ const ad = d < 0 ? -d : d
+ if (ad > noise) return true
+ sum += ad
+ }
+ if (sum > budget) return true
+ }
+ return false
+}
+
+export function copyRect(dst: Uint8Array, dO: int, ds: int, src: Uint8Array, so: int, ss: int, w: int, h: int) {
+ if (w === 16) {
+ for (let y = 0; y < h; y++) u8x16.load(src, so + y * ss).store(dst, dO + y * ds)
+ return
+ }
+ if (w === 8) {
+ for (let y = 0; y < h; y++) copyRow8(dst, dO + y * ds, src, so + y * ss)
+ return
+ }
+ if (w === 4) {
+ for (let y = 0; y < h; y++) copyRow4(dst, dO + y * ds, src, so + y * ss)
+ return
+ }
+ for (let y = 0; y < h; y++) {
+ const a = dO + y * ds
+ const b = so + y * ss
+ for (let x = 0; x < w; x++) dst[a + x] = src[b + x]!
+ }
+}
+
+function copyRow8(dst: Uint8Array, a: int, src: Uint8Array, b: int) {
+ u8x16.loadLow(src, b).storeLow(dst, a)
+}
+
+function copyRow4(dst: Uint8Array, a: int, src: Uint8Array, b: int) {
+ const p0 = src[b]!
+ const p1 = src[b + 1]!
+ const p2 = src[b + 2]!
+ const p3 = src[b + 3]!
+ dst[a] = p0
+ dst[a + 1] = p1
+ dst[a + 2] = p2
+ dst[a + 3] = p3
+}
+
+export function copyBytes(dst: Uint8Array, d: int, src: Uint8Array, s: int, n: int) {
+ let x = 0
+ while (x + 16 <= n) {
+ u8x16.load(src, s + x).store(dst, d + x)
+ x += 16
+ }
+ if (x + 8 <= n) {
+ copyRow8(dst, d + x, src, s + x)
+ x += 8
+ }
+ while (x < n) {
+ dst[d + x] = src[s + x]!
+ x++
+ }
+}
+
+export function fillBytes(dst: Uint8Array, d: int, n: int, v: int) {
+ const s = u8x16.splat(v)
+ let x = 0
+ while (x + 16 <= n) {
+ s.store(dst, d + x)
+ x += 16
+ }
+ while (x < n) {
+ dst[d + x] = v
+ x++
+ }
+}
+
+export const AQ_FLAT = 0
+export const AQ_TEXT = 1
+export const AQ_TEXTURE = 2
+export const AQ_NORMAL = 3
+
+function laneMin(v: u8x16): int {
+ const a = v.min(v.swizzle([8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7]))
+ const b = a.min(a.swizzle([4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11]))
+ const c = b.min(b.swizzle([2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13]))
+ return c.min(c.swizzle([1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14])).lane(0)
+}
+
+function laneMax(v: u8x16): int {
+ const a = v.max(v.swizzle([8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7]))
+ const b = a.max(a.swizzle([4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11]))
+ const c = b.max(b.swizzle([2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13]))
+ return c.max(c.swizzle([1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14])).lane(0)
+}
+
+const NEXT_COLUMN = [
+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 31,
+]
+
+// Two rows per register: rows y and y + 1 against their right neighbours and against rows y + 1 and y + 2. The last
+// pair compares row 15 with itself, which counts nothing; a lane counts at most 16 hits, so byte lanes hold them.
+export function classifyMb(p: Uint8Array, o: int, stride: int): int {
+ const t48 = u8x32.splat(48)
+ const t6 = u8x32.splat(6)
+ const keep15 = u8x32(
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0,
+ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0,
+ )
+ let lo = u8x32.splat(255)
+ let hi = u8x32.splat(0)
+ let strong = u8x32.splat(0)
+ let edges = u8x32.splat(0)
+ let r = u8x16.load(p, o)
+ for (let y = 0; y < 16; y += 2) {
+ const a = o + y * stride
+ const r1 = u8x16.load(p, a + stride)
+ const r2 = y < 14 ? u8x16.load(p, a + 2 * stride) : r1
+ const pair = u8x32.concat(r, r1)
+ lo = lo.min(pair)
+ hi = hi.max(pair)
+ const dh = pair.absDiff(pair.swizzle(NEXT_COLUMN)) & keep15
+ const dv = pair.absDiff(u8x32.concat(r1, r2))
+ strong = strong - dh.ge(t48) - dv.ge(t48)
+ edges = edges - dh.ge(t6) - dv.ge(t6)
+ r = r2
+ }
+ const ns = strong.sum()
+ const nm = edges.sum() - ns
+ const range = laneMax(hi.low().max(hi.high())) - laneMin(lo.low().min(lo.high()))
+ if (range < 12 && ns === 0) return AQ_FLAT
+ if (ns >= 10 && range >= 80 && ns * 2 >= nm) return AQ_TEXT
+ if (nm >= 160 && ns < 10) return AQ_TEXTURE
+ return AQ_NORMAL
+}
+
+export function mbActivity(p: Uint8Array, o: int, stride: int): int {
+ const t32 = u8x16.splat(32)
+ const zero = u8x16.splat(0)
+ const keep15 = u8x16(255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0)
+ let a = 0
+ let r = u8x16.load(p, o)
+ for (let y = 0; y < 16; y++) {
+ a += u8x16.sad(r.absDiff(u8x16.load(p, o + y * stride + 1)).min(t32) & keep15, zero)
+ if (y < 15) {
+ const nx = u8x16.load(p, o + (y + 1) * stride)
+ a += u8x16.sad(r.absDiff(nx).min(t32), zero)
+ r = nx
+ }
+ }
+ return a
+}
+
+function classifyMbRef(p: Uint8Array, o: int, stride: int): int {
+ let strong = 0
+ let medium = 0
+ let lo = 255
+ let hi = 0
+ for (let y = 0; y < 16; y++) {
+ const r = o + y * stride
+ for (let x = 0; x < 16; x++) {
+ const v = int(p[r + x]!)
+ if (v < lo) lo = v
+ if (v > hi) hi = v
+ if (x < 15) {
+ const d = v - int(p[r + x + 1]!)
+ const a = d < 0 ? -d : d
+ if (a >= 48) {
+ strong++
+ } else if (a >= 6) {
+ medium++
+ }
+ }
+ if (y < 15) {
+ const d = v - int(p[r + x + stride]!)
+ const a = d < 0 ? -d : d
+ if (a >= 48) {
+ strong++
+ } else if (a >= 6) {
+ medium++
+ }
+ }
+ }
+ }
+ if (hi - lo < 12 && strong === 0) return AQ_FLAT
+ if (strong >= 10 && hi - lo >= 80 && strong * 2 >= medium) return AQ_TEXT
+ if (medium >= 160 && strong < 10) return AQ_TEXTURE
+ return AQ_NORMAL
+}
+
+function hashLanes(p: Uint8Array, o: int): i32x4 {
+ const v = u8x16.load(p, o)
+ return i16x8.madd(v.widenLow(), i16x8(3, 5, 7, 11, 13, 17, 19, 23)) +
+ i16x8.madd(v.widenHigh(), i16x8(29, 31, 37, 41, 43, 47, 53, 59))
+}
+
+function hashStep(p: Uint8Array, o: int): int {
+ return hashLanes(p, o).sum()
+}
+
+function hashSteps4(p: Uint8Array, o0: int, o1: int, o2: int, o3: int): u32x4 {
+ const s0 = hashLanes(p, o0)
+ const s1 = hashLanes(p, o1)
+ const s2 = hashLanes(p, o2)
+ const s3 = hashLanes(p, o3)
+ const a = i32x4.shuffle(s0, s1, [0, 1, 4, 5]) + i32x4.shuffle(s0, s1, [2, 3, 6, 7])
+ const b = i32x4.shuffle(s2, s3, [0, 1, 4, 5]) + i32x4.shuffle(s2, s3, [2, 3, 6, 7])
+ return u32x4.bitcast(i32x4.shuffle(a, b, [0, 2, 4, 6]) + i32x4.shuffle(a, b, [1, 3, 5, 7]))
+}
+
+function hashTail(p: Uint8Array, o: int, x0: int, w: int, h0: int): int {
+ let h = h0
+ for (let x = x0; x < w; x++) h = ((h ^ int(p[o + x]!)) * 16777619) & 0xffffffff
+ return h
+}
+
+function rowHash(p: Uint8Array, o: int, w: int): int {
+ let h = 1469598103
+ let x = 0
+ while (x + 16 <= w) {
+ h = (h * 16777619 + hashStep(p, o + x)) & 0xffffffff
+ x += 16
+ }
+ return hashTail(p, o, x, w, h)
+}
+
+export function rowHashes(out: Uint32Array, at: int, p: Uint8Array, o: int, stride: int, w: int, n: int) {
+ const wv = w - w % 16
+ let i = 0
+ while (i + 4 <= n) {
+ const o0 = o + i * stride
+ const o1 = o0 + stride
+ const o2 = o1 + stride
+ const o3 = o2 + stride
+ const m = u32x4.splat(16777619)
+ let h = u32x4.splat(1469598103)
+ for (let x = 0; x < wv; x += 16) h = h * m + hashSteps4(p, o0 + x, o1 + x, o2 + x, o3 + x)
+ out[at + i] = hashTail(p, o0, wv, w, h.lane(0))
+ out[at + i + 1] = hashTail(p, o1, wv, w, h.lane(1))
+ out[at + i + 2] = hashTail(p, o2, wv, w, h.lane(2))
+ out[at + i + 3] = hashTail(p, o3, wv, w, h.lane(3))
+ i += 4
+ }
+ for (; i < n; i++) out[at + i] = rowHash(p, o + i * stride, w)
+}
+
+export function scrollSpan(w: int, h: int, y0: int, frameH: int, maxShift: int): int[] {
+ if (w < 32 || h < 48) return []
+ const ylo = y0 - maxShift < 0 ? 0 : y0 - maxShift
+ const yhi = y0 + h + maxShift > frameH ? frameH : y0 + h + maxShift
+ return [ylo, yhi]
+}
+
+export function estimateScroll(cur: Uint8Array, cs: int, cOff: int, prev: Uint8Array, ps: int, pOff: int,
+ x0: int, y0: int, w: int, h: int, frameH: int, maxShift: int): int {
+ const span = scrollSpan(w, h, y0, frameH, maxShift)
+ if (span.length === 0) return 0
+ const ylo = span[0]!
+ const prevHashes = new Uint32Array(span[1]! - ylo)
+ rowHashes(prevHashes, 0, prev, pOff + ylo * ps + x0, ps, w, prevHashes.length)
+ const curHashes = new Uint32Array(h)
+ rowHashes(curHashes, 0, cur, cOff + y0 * cs + x0, cs, w, h)
+ return matchScroll(prevHashes, ylo, curHashes, y0)
+}
+
+export function matchScroll(prevHashes: Uint32Array, ylo: int, curHashes: Uint32Array, y0: int): int {
+ const h = curHashes.length
+ const yhi = ylo + prevHashes.length
+ let prevRows: Map<int, int> = new Map()
+ for (let y = ylo; y < yhi; y++) {
+ const k = prevHashes[y - ylo]!
+ if (!prevRows.has(k)) prevRows.set(k, y)
+ }
+ let votes: Map<int, int> = new Map()
+ let flat = 0
+ for (let y = y0; y < y0 + h; y++) {
+ const k = curHashes[y - y0]!
+ const py = prevRows.get(k)
+ if (py === undefined) continue
+ const d = py - y
+ if (d === 0) {
+ flat++
+ continue
+ }
+ votes.set(d, (votes.get(d) ?? 0) + 1)
+ }
+ let best = 0
+ let bestN = 0
+ for (const d of votes.keys()) {
+ const n = votes.get(d) ?? 0
+ if (n > bestN) {
+ bestN = n
+ best = d
+ }
+ }
+ if (bestN * 3 < h) return 0
+ return best
+}
+
+function profileRef(p: Uint8Array, off: int, stride: int, x0: int, y0: int, w: int, h: int, horizontal: bool): int[] {
+ let out: int[] = []
+ if (horizontal) {
+ const acc = new Int32Array(w)
+ const w8 = w & ~7
+ for (let y = y0; y < y0 + h; y += 2) {
+ const r = off + y * stride + x0
+ for (let x = 0; x < w8; x += 8) (i32x8.load(acc, x) + i32x8.loadU8(p, r + x)).store(acc, x)
+ for (let x = w8; x < w; x++) acc[x] = acc[x]! + int(p[r + x]!)
+ }
+ for (let x = 0; x < w; x++) out.push(acc[x]!)
+ } else {
+ const even = u8x16(255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0, 255, 0)
+ const zero = u8x16.splat(0)
+ const w16 = w & ~15
+ for (let y = y0; y < y0 + h; y++) {
+ const r = off + y * stride + x0
+ let s = 0
+ for (let x = 0; x < w16; x += 16) s += u8x16.sad(u8x16.load(p, r + x) & even, zero)
+ for (let x = w16; x < w; x += 2) s += int(p[r + x]!)
+ out.push(s)
+ }
+ }
+ return out
+}
+
+function flushColumns(sums: Int32Array, part: Int16Array, n: int) {
+ for (let x = 0; x < n; x += 4) {
+ const s = i32x4.load(sums, x) + i32x4.loadI16(part, x)
+ s.store(sums, x)
+ }
+ part.fill(0)
+}
+
+function profile(p: Uint8Array, off: int, stride: int, x0: int, y0: int, w: int, h: int, horizontal: bool): int[] {
+ let out: int[] = []
+ const wv = w - w % 16
+ if (horizontal) {
+ const sums = new Int32Array(w)
+ const part = new Int16Array(wv)
+ let rows = 0
+ for (let y = y0; y < y0 + h; y += 2) {
+ const r = off + y * stride + x0
+ for (let x = 0; x < wv; x += 16) {
+ const v = u8x16.load(p, r + x)
+ const lo = i16x8.load(part, x) + v.widenLow()
+ const hi = i16x8.load(part, x + 8) + v.widenHigh()
+ lo.store(part, x)
+ hi.store(part, x + 8)
+ }
+ for (let x = wv; x < w; x++) sums[x] = sums[x]! + int(p[r + x]!)
+ rows++
+ if (rows === 128) {
+ flushColumns(sums, part, wv)
+ rows = 0
+ }
+ }
+ flushColumns(sums, part, wv)
+ for (let x = 0; x < w; x++) out.push(sums[x]!)
+ return out
+ }
+ const even = i16x8.splat(255)
+ for (let y = y0; y < y0 + h; y++) {
+ const r = off + y * stride + x0
+ let acc = i32x4.splat(0)
+ let x = 0
+ while (x < wv) {
+ const end = x + 2048 < wv ? x + 2048 : wv
+ let part = i16x8.splat(0)
+ for (; x < end; x += 16) part = part + (i16x8.bitcast(u8x16.load(p, r + x)) & even)
+ acc = acc + part.widenLow() + part.widenHigh()
+ }
+ let s = acc.sum()
+ for (let xx = wv; xx < w; xx += 2) s += int(p[r + xx]!)
+ out.push(s)
+ }
+ return out
+}
+
+function profileCost(cur: int[], prev: int[], off: int): int {
+ let lo = 0
+ let hi = cur.length
+ if (off < 0) lo = -off
+ if (off + hi > prev.length) hi = prev.length - off
+ const len = hi - lo
+ if (len <= 0 || len * 3 < cur.length) return -1
+ let s = 0
+ for (let i = lo; i < hi; i++) {
+ const a = cur[i]!
+ const b = prev[i + off]!
+ s += a > b ? a - b : b - a
+ }
+ return Math.trunc(s * 64 / len)
+}
+
+function decimate4(v: int[]): int[] {
+ let out: int[] = []
+ for (let i = 0; i + 3 < v.length; i += 4) out.push(v[i]! + v[i + 1]! + v[i + 2]! + v[i + 3]!)
+ return out
+}
+
+export function estimateShift(cur: Uint8Array, cs: int, cOff: int, prev: Uint8Array, ps: int, pOff: int,
+ x0: int, y0: int, w: int, h: int, frameW: int, frameH: int, horizontal: bool, maxShift: int): int {
+ if (w < 64 || h < 64) return 0
+ const pc = profile(cur, cOff, cs, x0, y0, w, h, horizontal)
+ const pp = horizontal ? profile(prev, pOff, ps, 0, y0, frameW, h, true) : profile(prev, pOff, ps, x0, 0, w, frameH, false)
+ const c0 = horizontal ? x0 : y0
+ const zero = profileCost(pc, pp, c0)
+ if (zero <= 0) return 0
+ const pc4 = decimate4(pc)
+ const pp4 = decimate4(pp)
+ const range = maxShift >> 2
+ let best = 0
+ let bestCost = profileCost(pc4, pp4, c0 >> 2)
+ for (let d = -range; d <= range; d++) {
+ if (d === 0) continue
+ const c = profileCost(pc4, pp4, (c0 >> 2) + d)
+ if (c >= 0 && (bestCost < 0 || c < bestCost)) {
+ bestCost = c
+ best = d * 4
+ }
+ }
+ if (best === 0) return 0
+ let fine = best
+ let fineCost = profileCost(pc, pp, c0 + best)
+ for (let d = best - 4; d <= best + 4; d++) {
+ if (d === best || d === 0) continue
+ const c = profileCost(pc, pp, c0 + d)
+ if (c >= 0 && (fineCost < 0 || c < fineCost)) {
+ fineCost = c
+ fine = d
+ }
+ }
+ if (fineCost < 0 || fineCost * 2 > zero) return 0
+ return fine
+}
+
+function fitWeight(sc: int, sc2: int, sr: int, sr2: int, n: int): int[] {
+ const mc = f64(sc) / f64(n)
+ const mr = f64(sr) / f64(n)
+ const vc = f64(sc2) / f64(n) - mc * mc
+ const vr = f64(sr2) / f64(n) - mr * mr
+ let w = 64
+ if (vr > 4.0 && vc > 0.0) w = Math.round(64.0 * Math.sqrt(vc / vr))
+ if (w > 127) w = 127
+ if (w < 0) w = 0
+ let o = Math.round(mc - f64(w) * mr / 64.0)
+ if (o > 127) o = 127
+ if (o < -128) o = -128
+ return [w, o]
+}
+
+function lumaFitRef(frame: Uint8Array, frameOff: int, w: int, h: int, refY: Uint8Array, yorg: int, ys: int): int[] {
+ let sc = 0
+ let sc2 = 0
+ let sr = 0
+ let sr2 = 0
+ let n = 0
+ for (let y = 2; y < h; y += 4) {
+ const fo = frameOff + y * w
+ const ro = yorg + y * ys
+ for (let x = 1; x < w; x += 4) {
+ const c = int(frame[fo + x]!)
+ const r = int(refY[ro + x]!)
+ sc += c
+ sc2 += c * c
+ sr += r
+ sr2 += r * r
+ n++
+ }
+ }
+ if (n === 0) return []
+ const lw = fitWeight(sc, sc2, sr, sr2, n)
+ let plain = 0
+ let weighted = 0
+ for (let y = 2; y < h; y += 4) {
+ const fo = frameOff + y * w
+ const ro = yorg + y * ys
+ for (let x = 1; x < w; x += 4) {
+ const c = int(frame[fo + x]!)
+ const r = int(refY[ro + x]!)
+ const pv = ((r * lw[0]! + 32) >> 6) + lw[1]!
+ const p = pv < 0 ? 0 : pv > 255 ? 255 : pv
+ plain += c > r ? c - r : r - c
+ weighted += c > p ? c - p : p - c
+ }
+ }
+ if (weighted * 5 >= plain * 4 || (lw[0]! === 64 && lw[1]! === 0)) return []
+ return lw
+}
+
+function samples4(p: Uint8Array, o: int): i32x4 {
+ return (i32x4.bitcast(u8x16.load(p, o)) >> 8) & i32x4.splat(255)
+}
+
+function lumaFit(frame: Uint8Array, frameOff: int, w: int, h: int, refY: Uint8Array, yorg: int, ys: int): int[] {
+ const wv = w - w % 16
+ let sc = 0
+ let sc2 = 0
+ let sr = 0
+ let sr2 = 0
+ let n = 0
+ for (let y = 2; y < h; y += 4) {
+ const fo = frameOff + y * w
+ const ro = yorg + y * ys
+ let vc = i32x4.splat(0)
+ let vc2 = i32x4.splat(0)
+ let vr = i32x4.splat(0)
+ let vr2 = i32x4.splat(0)
+ for (let x = 0; x < wv; x += 16) {
+ const c = samples4(frame, fo + x)
+ const r = samples4(refY, ro + x)
+ vc = vc + c
+ vc2 = vc2 + c * c
+ vr = vr + r
+ vr2 = vr2 + r * r
+ }
+ sc += vc.sum()
+ sc2 += vc2.sum()
+ sr += vr.sum()
+ sr2 += vr2.sum()
+ n += wv >> 2
+ for (let x = wv + 1; x < w; x += 4) {
+ const c = int(frame[fo + x]!)
+ const r = int(refY[ro + x]!)
+ sc += c
+ sc2 += c * c
+ sr += r
+ sr2 += r * r
+ n++
+ }
+ }
+ if (n === 0) return []
+ const lw = fitWeight(sc, sc2, sr, sr2, n)
+ const wt = i32x4.splat(lw[0]!)
+ const off = i32x4.splat(lw[1]!)
+ const rnd = i32x4.splat(32)
+ const zero = i32x4.splat(0)
+ const top = i32x4.splat(255)
+ let plain = 0
+ let weighted = 0
+ for (let y = 2; y < h; y += 4) {
+ const fo = frameOff + y * w
+ const ro = yorg + y * ys
+ let vp = i32x4.splat(0)
+ let vw = i32x4.splat(0)
+ for (let x = 0; x < wv; x += 16) {
+ const c = samples4(frame, fo + x)
+ const r = samples4(refY, ro + x)
+ const p = (((r * wt + rnd) >> 6) + off).max(zero).min(top)
+ vp = vp + (c - r).abs()
+ vw = vw + (c - p).abs()
+ }
+ plain += vp.sum()
+ weighted += vw.sum()
+ for (let x = wv + 1; x < w; x += 4) {
+ const c = int(frame[fo + x]!)
+ const r = int(refY[ro + x]!)
+ const pv = ((r * lw[0]! + 32) >> 6) + lw[1]!
+ const p = pv < 0 ? 0 : pv > 255 ? 255 : pv
+ plain += c > r ? c - r : r - c
+ weighted += c > p ? c - p : p - c
+ }
+ }
+ if (weighted * 5 >= plain * 4 || (lw[0]! === 64 && lw[1]! === 0)) return []
+ return lw
+}
+
+export function weightFit(frame: Uint8Array, frameOff: int, w: int, h: int, refY: Uint8Array, refU: Uint8Array,
+ refV: Uint8Array, yorg: int, ys: int, corg: int, cs: int, out: Int32Array) {
+ out[0] = 0
+ const lw = lumaFit(frame, frameOff, w, h, refY, yorg, ys)
+ if (lw.length === 0) return
+ out[0] = 1
+ out[1] = lw[0]!
+ out[2] = lw[1]!
+ const cwIn = w >> 1
+ const chIn = h >> 1
+ let gainC = false
+ for (let pl = 0; pl < 2; pl++) {
+ const base = frameOff + w * h + pl * cwIn * chIn
+ const rp = pl === 0 ? refU : refV
+ let a = 0
+ let a2 = 0
+ let b = 0
+ let b2 = 0
+ let m = 0
+ for (let y = 1; y < chIn; y += 2) {
+ const ro = corg + y * cs
+ for (let x = 1; x < cwIn; x += 2) {
+ const c = int(frame[base + y * cwIn + x]!)
+ const r = int(rp[ro + x]!)
+ a += c
+ a2 += c * c
+ b += r
+ b2 += r * r
+ m++
+ }
+ }
+ const cwt = m > 0 ? fitWeight(a, a2, b, b2, m) : [64, 0]
+ let e0 = 0
+ let e1 = 0
+ for (let y = 1; y < chIn; y += 2) {
+ const ro = corg + y * cs
+ for (let x = 1; x < cwIn; x += 2) {
+ const c = int(frame[base + y * cwIn + x]!)
+ const r = int(rp[ro + x]!)
+ const pv = ((r * cwt[0]! + 32) >> 6) + cwt[1]!
+ const p = pv < 0 ? 0 : pv > 255 ? 255 : pv
+ e0 += c > r ? c - r : r - c
+ e1 += c > p ? c - p : p - c
+ }
+ }
+ const gain = e1 * 5 < e0 * 4
+ if (gain) gainC = true
+ out[3 + pl * 2] = gain ? cwt[0]! : 64
+ out[4 + pl * 2] = gain ? cwt[1]! : 0
+ }
+ out[7] = gainC ? 1 : 0
+}
+
+test("a horizontal push is found from column profiles", () => {
+ const w = 256
+ const h = 96
+ let prev: u8[] = []
+ let cur: u8[] = []
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const v = ((x * x * 31 + x * 7) % 211) + ((y * 17 + x * y) % 13)
+ const vv = v > 255 ? 255 : v
+ prev.push(u8(vv))
+ }
+ }
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const sx = x + 37 < w ? x + 37 : w - 1
+ cur.push(prev[y * w + sx]!)
+ }
+ }
+ const tc = new Uint8Array(cur)
+ const tp = new Uint8Array(prev)
+ expect(estimateShift(tc, w, 0, tp, w, 0, 0, 0, w, h, w, h, true, 128)).toBe(37)
+ expect(estimateShift(tp, w, 0, tp, w, 0, 0, 0, w, h, w, h, true, 128)).toBe(0)
+})
+
+test("vector profiles and interleaved row hashes match the scalar ones", () => {
+ const w = 2103
+ const h = 300
+ const p = new Uint8Array(w * h)
+ let x = 11
+ for (let i = 0; i < w * h; i++) {
+ x = (x * 1103515245 + 12345) & 0x7fffffff
+ p[i] = i % 7 === 0 ? 255 : (x >> 9) & 255
+ }
+ let bad = 0
+ for (const cw of [16, 37, 160, 187, 2090]) {
+ for (const horizontal of [true, false]) {
+ const a = profile(p, 3, w, 5, 2, cw, 290, horizontal)
+ const b = profileRef(p, 3, w, 5, 2, cw, 290, horizontal)
+ if (a.length !== b.length) bad++
+ for (let i = 0; i < a.length; i++) {
+ if (a[i]! !== b[i]!) bad++
+ }
+ }
+ for (let n = 0; n < 7; n++) {
+ const hs = new Uint32Array(n + 2)
+ rowHashes(hs, 2, p, 4 + w, w, cw, n)
+ for (let i = 0; i < n; i++) {
+ if (hs[i + 2]! !== rowHash(p, 4 + w + i * w, cw)) bad++
+ }
+ }
+ }
+ expect(bad).toBe(0)
+})
+
+test("a vertical scroll is found from row hashes computed in chunks", () => {
+ const w = 96
+ const h = 200
+ const prev = new Uint8Array(w * h)
+ const cur = new Uint8Array(w * h)
+ let x = 5
+ for (let i = 0; i < w * h; i++) {
+ x = (x * 1103515245 + 12345) & 0x7fffffff
+ prev[i] = (x >> 9) & 255
+ }
+ for (let y = 0; y < h; y++) {
+ for (let xx = 0; xx < w; xx++) cur[y * w + xx] = prev[(y + 23 < h ? y + 23 : y) * w + xx]!
+ }
+ expect(estimateScroll(cur, w, 0, prev, w, 0, 0, 0, w, h, h, 64)).toBe(23)
+ const span = scrollSpan(w, h, 0, h, 64)
+ const ph = new Uint32Array(span[1]! - span[0]!)
+ const ch = new Uint32Array(h)
+ for (let r = 0; r < h; r += 37) {
+ const n = r + 37 < h ? 37 : h - r
+ rowHashes(ph, r, prev, r * w, w, w, n)
+ rowHashes(ch, r, cur, r * w, w, w, n)
+ }
+ expect(matchScroll(ph, span[0]!, ch, 0)).toBe(23)
+ expect(scrollSpan(31, h, 0, h, 64).length).toBe(0)
+})
+
+test("vector weighted-prediction sampling matches the scalar one", () => {
+ let bad = 0
+ let fitted = 0
+ let x = 3
+ for (const w of [1, 15, 16, 37, 160, 203, 1920]) {
+ for (const gain of [0, 40, 64, 90]) {
+ const h = 45
+ const ys = w + 37
+ const yorg = 2 * ys + 19
+ const frame = new Uint8Array(5 + w * h)
+ const ref = new Uint8Array(yorg + h * ys + 16)
+ for (let y = 0; y < h; y++) {
+ for (let xx = 0; xx < ys; xx++) {
+ x = (x * 1103515245 + 12345) & 0x7fffffff
+ const r = (x >> 9) & 255
+ ref[yorg + y * ys + xx] = r
+ if (xx < w) {
+ const v = gain === 0 ? (x >> 17) & 255 : ((r * gain) >> 6) + ((x >> 20) & 3) + 7
+ frame[5 + y * w + xx] = v > 255 ? 255 : v
+ }
+ }
+ }
+ const a = lumaFit(frame, 5, w, h, ref, yorg, ys)
+ const b = lumaFitRef(frame, 5, w, h, ref, yorg, ys)
+ if (a.length !== b.length) bad++
+ for (let i = 0; i < a.length && i < b.length; i++) {
+ if (a[i]! !== b[i]!) bad++
+ }
+ if (b.length > 0) fitted++
+ }
+ }
+ expect(bad).toBe(0)
+ expect(fitted >= 6).toBe(true)
+})
+
+test("vector macroblock classification matches the scalar one", () => {
+ let p: u8[] = []
+ let x = 7
+ for (let i = 0; i < 48 * 48; i++) {
+ x = (x * 1103515245 + 12345) & 0x7fffffff
+ const k = Math.trunc(i / 48)
+ const v = k % 4 === 0 ? 255 : k % 4 === 1 ? 200 + ((x >> 9) & 7) : k % 4 === 2 ? (x >> 9) & 255 : 30 + (x >> 12) % 70
+ p.push(u8(v))
+ }
+ let bad = 0
+ let classes = 0
+ const tp = new Uint8Array(p)
+ for (let y = 0; y < 32; y += 3) {
+ for (let xx = 0; xx < 32; xx += 5) {
+ const o = y * 48 + xx
+ const c = classifyMb(tp, o, 48)
+ if (c !== classifyMbRef(tp, o, 48)) bad++
+ classes |= 1 << c
+ }
+ }
+ const flat = new Uint8Array(48 * 48)
+ for (let i = 0; i < 48 * 48; i++) flat[i] = i % 48 < 24 ? 40 : 220
+ if (classifyMb(flat, 0, 48) !== classifyMbRef(flat, 0, 48)) bad++
+ if (classifyMb(flat, 16, 48) !== classifyMbRef(flat, 16, 48)) bad++
+ const steps: int[] = [0, 5, 6, 7, 47, 48, 49, 11, 80]
+ const q = new Uint8Array(16 * 16)
+ for (let seed = 0; seed < 4000; seed++) {
+ x = (seed * 2654435761 + 17) & 0x7fffffff
+ for (let i = 0; i < 256; i++) {
+ x = (x * 1103515245 + 12345) & 0x7fffffff
+ const base = i === 0 ? 100 : int(q[i % 16 === 0 ? i - 16 : i - 1]!)
+ const d = steps[(x >> 8) % (seed % 9 + 1)]!
+ const v = ((x >> 4) & 1) === 0 ? base + d : base - d
+ q[i] = v < 0 ? 0 : v > 255 ? 255 : v
+ }
+ const c = classifyMb(q, 0, 16)
+ if (c !== classifyMbRef(q, 0, 16)) bad++
+ classes |= 1 << c
+ }
+ expect(bad).toBe(0)
+ expect(classes).toBe(15)
+})
+
+test("vector macroblock difference tests find every changed pixel", () => {
+ const a = new Uint8Array(40 * 20)
+ const b = new Uint8Array(40 * 20)
+ let x = 3
+ for (let i = 0; i < 40 * 20; i++) {
+ x = (x * 1103515245 + 12345) & 0x7fffffff
+ a[i] = (x >> 9) & 255
+ b[i] = a[i]!
+ }
+ let bad = 0
+ for (const w of [16, 8]) {
+ for (const h of [w, 4]) {
+ if (diffMb(a, 41, 40, b, 41, 40, w, h, 0)) bad++
+ for (let y = 0; y < h; y++) {
+ for (let xx = 0; xx < w; xx++) {
+ const i = 41 + y * 40 + xx
+ b[i] = a[i]! ^ ((y & 1) === 1 ? 128 : 1)
+ if (!diffMb(a, 41, 40, b, 41, 40, w, h, 0)) bad++
+ b[i] = a[i]!
+ }
+ }
+ b[41 + h * 40] = a[41 + h * 40]! ^ 1
+ b[41 + w] = a[41 + w]! ^ 1
+ if (diffMb(a, 41, 40, b, 41, 40, w, h, 0)) bad++
+ b[41 + h * 40] = a[41 + h * 40]!
+ b[41 + w] = a[41 + w]!
+ }
+ }
+ expect(bad).toBe(0)
+})
+
+test("vector noise comparisons agree with the scalar one", () => {
+ const a = new Uint8Array(40 * 20)
+ const b = new Uint8Array(40 * 20)
+ let seed = 12345
+ let bad = 0
+ let same = 0
+ let differ = 0
+ for (let t = 0; t < 300; t++) {
+ const amp = t % 5
+ for (let i = 0; i < a.length; i++) {
+ seed = (seed * 1103515245 + 12345) & 0x7fffffff
+ const v = (seed >> 8) & 255
+ const r = (seed >> 3) & 31
+ const d = r === 0 && t % 7 === 0 ? 40 : (r % (2 * amp + 1)) - amp
+ a[i] = v
+ b[i] = v + d < 0 ? 0 : v + d > 255 ? 255 : v + d
+ }
+ for (let noise = 1; noise <= 4; noise++) {
+ for (let s = 0; s < 6; s++) {
+ const w = s < 3 ? 16 : 8
+ const h = s % 3 === 0 ? w : s % 3 === 1 ? w >> 1 : 7
+ const want = diffNoisy(a, 41, 40, b, 41, 40, w, h, noise)
+ if (diffMb(a, 41, 40, b, 41, 40, w, h, noise) !== want) bad++
+ if (want) {
+ differ++
+ } else {
+ same++
+ }
+ }
+ }
+ }
+ expect(`${bad} ${same > 100} ${differ > 100}`).toBe("0 true true")
+})
+
+function perturb(src: Uint8Array, ss: int, dst: Uint8Array, dOff: int, ds: int, w: int, h: int, amp: int, spike: bool,
+ seed: int): int {
+ let s = seed
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ s = (s * 1103515245 + 12345) & 0x7fffffff
+ const v = (s >> 8) & 255
+ const r = (s >> 3) & 31
+ const d = ((s >> 11) & 255) === 0 && spike ? 40 : (r % (2 * amp + 1)) - amp
+ src[y * ss + x] = v
+ dst[dOff + y * ds + x] = v + d < 0 ? 0 : v + d > 255 ? 255 : v + d
+ }
+ }
+ return s
+}
+
+function restore(src: Uint8Array, ss: int, dst: Uint8Array, dOff: int, ds: int, x0: int, y0: int, w: int, h: int) {
+ for (let y = y0; y < y0 + h; y++) {
+ for (let x = x0; x < x0 + w; x++) dst[dOff + y * ds + x] = src[y * ss + x]!
+ }
+}
+
+test("the change map agrees with comparing each macroblock", () => {
+ const w = 56
+ const h = 40
+ const mbw = 4
+ const mbh = 3
+ const cw = w >> 1
+ const ch = h >> 1
+ const sy = new Uint8Array(64 * h)
+ const su = new Uint8Array(32 * ch)
+ const sv = new Uint8Array(32 * ch)
+ const fuo = 5 + w * h
+ const fvo = fuo + cw * ch
+ const f = new Uint8Array(fvo + cw * ch)
+ const out = new Uint8Array(mbw * mbh)
+ let seed = 777
+ let bad = 0
+ let same = 0
+ let differ = 0
+ let split = 0
+ let similar = 0
+ for (let t = 0; t < 480; t++) {
+ const amp = t % 4
+ const spike = t % 5 === 0
+ seed = perturb(sy, 64, f, 5, w, w, h, amp, spike && t % 3 !== 0, seed)
+ seed = perturb(su, 32, f, fuo, cw, cw, ch, t % 3 === 0 ? 0 : amp, spike && t % 2 === 0, seed)
+ seed = perturb(sv, 32, f, fvo, cw, cw, ch, t % 3 === 1 ? 0 : amp, spike && t % 2 === 1, seed)
+ const keepY = seed >> 4
+ const keepC = seed >> 16
+ for (let mb = 0; mb < mbw * mbh; mb++) {
+ const x = (mb % mbw) * 16
+ const y = Math.trunc(mb / mbw) * 16
+ const bw = x + 16 <= w ? 16 : w - x
+ const bh = y + 16 <= h ? 16 : h - y
+ if (((keepY >> mb) & 1) !== 0) restore(sy, 64, f, 5, w, x, y, bw, bh)
+ if (((keepC >> mb) & 1) !== 0) {
+ restore(su, 32, f, fuo, cw, x >> 1, y >> 1, bw >> 1, bh >> 1)
+ restore(sv, 32, f, fvo, cw, x >> 1, y >> 1, bw >> 1, bh >> 1)
+ }
+ }
+ for (const noise of [0, 1, 2, 3, 4, 300]) {
+ out.fill(0)
+ const n = changeMap(sy, 0, 64, su, 0, sv, 0, 32, f, 5, w, fuo, fvo, cw, w, h, noise, out)
+ let count = 0
+ for (let mby = 0; mby < mbh; mby++) {
+ let prev = false
+ for (let mbx = 0; mbx < mbw; mbx++) {
+ const bw = mbx * 16 + 16 <= w ? 16 : w - mbx * 16
+ const bh = mby * 16 + 16 <= h ? 16 : h - mby * 16
+ const so = mby * 16 * 64 + mbx * 16
+ const fo = 5 + mby * 16 * w + mbx * 16
+ const sc = mby * 8 * 32 + mbx * 8
+ const fc = mby * 8 * cw + mbx * 8
+ const want = diffMb(sy, so, 64, f, fo, w, bw, bh, noise) ||
+ diffMb(su, sc, 32, f, fuo + fc, cw, bw >> 1, bh >> 1, noise) ||
+ diffMb(sv, sc, 32, f, fvo + fc, cw, bw >> 1, bh >> 1, noise)
+ const exact = !diffMb(sy, so, 64, f, fo, w, bw, bh, 0) &&
+ !diffMb(su, sc, 32, f, fuo + fc, cw, bw >> 1, bh >> 1, 0) &&
+ !diffMb(sv, sc, 32, f, fvo + fc, cw, bw >> 1, bh >> 1, 0)
+ const got = int(out[mby * mbw + mbx]!)
+ if (got !== (want ? 1 : exact ? 0 : 2)) bad++
+ if (got !== mbChange(sy, 0, 64, su, 0, sv, 0, 32, f, 5, w, fuo, fvo, cw, w, h, noise, mbx, mby)) bad++
+ if (!want && !exact) similar++
+ if (want) count++
+ if (bw === 16 && bh === 16) {
+ if (want) {
+ differ++
+ } else {
+ same++
+ }
+ if (mbx % 2 === 1 && want !== prev) split++
+ }
+ prev = want
+ }
+ }
+ if (count !== n) bad++
+ }
+ }
+ expect(`${bad} ${same > 50} ${differ > 50} ${split > 50} ${similar > 50}`).toBe("0 true true true true")
+})
+
+test("dirty rects mark overlapping macroblocks", () => {
+ const ch = new Uint8Array(12)
+ const n = markRects(ch, 4, 3, [8, 8, 20, 4, 60, 40, 100, 100])
+ expect(n).toBe(3)
+ expect(ch[0]!).toBe(1)
+ expect(ch[1]!).toBe(1)
+ expect(ch[11]!).toBe(1)
+})
+
+test("vector row and column profiles match the scalar sums at every width and offset", () => {
+ const stride = 83
+ let seed = 7
+ let px: u8[] = []
+ for (let i = 0; i < stride * 61; i++) {
+ seed = (seed * 1103515245 + 12345) & 0x7fffffff
+ const v = i % 5 === 0 ? 255 : (seed >> 9) & 255
+ px.push(u8(v))
+ }
+ const p = new Uint8Array(px)
+ let bad = 0
+ for (let w = 1; w <= 70; w += 3) {
+ for (let x0 = 0; x0 < 5; x0++) {
+ for (let y0 = 0; y0 < 3; y0++) {
+ const h = 50 - y0
+ const ph = profile(p, 1, stride, x0, y0, w, h, true)
+ const pv = profile(p, 1, stride, x0, y0, w, h, false)
+ for (let x = 0; x < w; x++) {
+ let s = 0
+ for (let y = y0; y < y0 + h; y += 2) s += int(p[1 + y * stride + x0 + x]!)
+ if (ph[x]! !== s) bad++
+ }
+ for (let y = y0; y < y0 + h; y++) {
+ let s = 0
+ for (let x = 0; x < w; x += 2) s += int(p[1 + y * stride + x0 + x]!)
+ if (pv[y - y0]! !== s) bad++
+ }
+ }
+ }
+ }
+ expect(bad).toBe(0)
+})
+
+test("side info lines parse with null cursors", () => {
+ try {
+ const s = try parseSideInfo("{\"frame\":3,\"t_ms\":100.0,\"dirty\":[[0,0,16,16]],\"cursor\":null,\"scroll\":[{\"rect\":[0,0,64,64],\"dx\":0,\"dy\":-40}]}")
+ expect(s.dirty.length).toBe(4)
+ expect(s.cursorX).toBe(-1)
+ expect(s.scroll[0]!.dy).toBe(-40)
+ } catch (e) {
+ expect(e.message).toBe("")
+ }
+})
diff --git a/capcodec/src/bitwriter.tov b/capcodec/src/bitwriter.tov
new file mode 100644
index 000000000..165431682
--- /dev/null
+++ b/capcodec/src/bitwriter.tov
@@ -0,0 +1,219 @@
+export class BitWriter {
+ buf: u8[] = []
+ acc = 0
+ n = 0
+
+ reset() {
+ this.buf = []
+ this.acc = 0
+ this.n = 0
+ }
+
+ putBits(v: int, bits: int) {
+ if (bits === 0) return
+ this.acc = (this.acc << bits) | (v & ((1 << bits) - 1))
+ this.n += bits
+ while (this.n >= 8) {
+ this.n -= 8
+ this.buf.push(u8((this.acc >> this.n) & 255))
+ }
+ this.acc = this.acc & ((1 << this.n) - 1)
+ }
+
+ putBit(b: int) {
+ this.putBits(b, 1)
+ }
+
+ ue(v: int) {
+ const x = v + 1
+ let len = 0
+ let t = x
+ while (t > 1) {
+ t = t >> 1
+ len++
+ }
+ if (len < 16) {
+ this.putBits(x, 2 * len + 1)
+ } else {
+ this.putBits(0, len)
+ this.putBits(x, len + 1)
+ }
+ }
+
+ se(v: int) {
+ this.ue(v > 0 ? 2 * v - 1 : -2 * v)
+ }
+
+ bitPos(): int {
+ return this.buf.length * 8 + this.n
+ }
+
+ aligned(): bool {
+ return this.n === 0
+ }
+
+ trailing() {
+ this.putBits(1, 1)
+ if (this.n > 0) this.putBits(0, 8 - this.n)
+ }
+
+ alignZero() {
+ if (this.n > 0) this.putBits(0, 8 - this.n)
+ }
+}
+
+function ueBitsSlow(v: int): int {
+ let x = v + 1
+ let len = 0
+ while (x > 1) {
+ x = x >> 1
+ len++
+ }
+ return 2 * len + 1
+}
+
+export function ueBits(v: int): int {
+ return 127 - 2 * Math.clz64(v + 1)
+}
+
+export function seBits(v: int): int {
+ return 127 - 2 * Math.clz64(((v < 0 ? -v : v) << 1) | 1)
+}
+
+function nalHeader(inout out: u8[], nalRefIdc: int, nalType: int, longStart: bool) {
+ if (longStart) out.push(u8(0))
+ out.push(u8(0))
+ out.push(u8(0))
+ out.push(u8(1))
+ out.push(u8((nalRefIdc << 5) | nalType))
+}
+
+function escapeArray(inout out: u8[], rbsp: u8[]): int {
+ let zeros = 0
+ const n = rbsp.length
+ for (let i = 0; i < n; i++) {
+ const b = rbsp[i]!
+ if (zeros >= 2 && b <= u8(3)) {
+ out.push(u8(3))
+ zeros = 0
+ }
+ out.push(b)
+ zeros = b === u8(0) ? zeros + 1 : 0
+ }
+ return zeros
+}
+
+function escapeBytes(inout out: u8[], src: Uint8Array, n: int, zeros0: int) {
+ let zeros = zeros0
+ const three = u8x16.splat(3)
+ let i = 0
+ while (i < n) {
+ const run = i
+ while (i + 16 <= n && u8x16.load(src, i).max(three).eq(three).mask() === 0) i += 16
+ if (i > run) {
+ out.pushFrom(src, run, i)
+ zeros = 0
+ }
+ const end = i + 16 <= n ? i + 16 : n
+ while (i < end) {
+ const b = src[i]!
+ if (zeros >= 2 && b <= 3) {
+ out.push(u8(3))
+ zeros = 0
+ }
+ out.push(u8(b))
+ zeros = b === 0 ? zeros + 1 : 0
+ i++
+ }
+ }
+}
+
+export function appendNal(inout out: u8[], nalRefIdc: int, nalType: int, rbsp: u8[], longStart: bool) {
+ nalHeader(&out, nalRefIdc, nalType, longStart)
+ escapeArray(&out, rbsp)
+}
+
+export function appendNalBytes(inout out: u8[], nalRefIdc: int, nalType: int, head: u8[], body: Uint8Array, n: int) {
+ nalHeader(&out, nalRefIdc, nalType, true)
+ escapeBytes(&out, body, n, escapeArray(&out, head))
+}
+
+test("putBits packs MSB first", () => {
+ const w = new BitWriter()
+ w.putBits(5, 3)
+ w.putBits(1, 1)
+ w.putBits(0xabc, 12)
+ expect(w.buf.length).toBe(2)
+ expect(int(w.buf[0]!)).toBe(0xba)
+ expect(int(w.buf[1]!)).toBe(0xbc)
+})
+
+test("exp-golomb ue matches the spec table", () => {
+ const w = new BitWriter()
+ for (let v = 0; v < 9; v++) w.ue(v)
+ w.alignZero()
+ const expected = "1" + "010" + "011" + "00100" + "00101" + "00110" + "00111" + "0001000" + "0001001"
+ let bits = ""
+ for (let i = 0; i < w.buf.length; i++) {
+ let b = int(w.buf[i]!)
+ for (let k = 7; k >= 0; k--) bits += ((b >> k) & 1) === 1 ? "1" : "0"
+ }
+ expect(bits.slice(0, expected.byteLength)).toBe(expected)
+ expect(ueBits(0)).toBe(1)
+ expect(ueBits(7)).toBe(7)
+ expect(ueBits(65535)).toBe(33)
+ for (let v = 0; v < 5000; v++) expect(ueBits(v)).toBe(ueBitsSlow(v))
+})
+
+test("exp-golomb se maps signs", () => {
+ expect(seBits(0)).toBe(1)
+ expect(seBits(1)).toBe(3)
+ expect(seBits(-1)).toBe(3)
+ expect(seBits(2)).toBe(5)
+ for (let v = -5000; v <= 5000; v++) expect(seBits(v)).toBe(ueBitsSlow(v > 0 ? 2 * v - 1 : -2 * v))
+ const w = new BitWriter()
+ w.se(-2)
+ w.alignZero()
+ expect(int(w.buf[0]!)).toBe(0x28)
+})
+
+test("large ue values", () => {
+ const w = new BitWriter()
+ w.ue(100000)
+ w.alignZero()
+ expect(w.bitPos()).toBe(40)
+})
+
+test("emulation prevention", () => {
+ let out: u8[] = []
+ appendNal(&out, 3, 7, [u8(0), u8(0), u8(1), u8(0), u8(0), u8(0), u8(5)], false)
+ const got = out.slice(3).map((b) => int(b))
+ expect(got).toEqual([0x67, 0, 0, 3, 1, 0, 0, 3, 0, 5])
+})
+
+test("escaping a byte buffer after a header equals escaping both as one array", () => {
+ let seed = 5
+ for (let t = 0; t < 200; t++) {
+ const hn = t % 7
+ const n = (t * 37) % 151
+ const head: u8[] = []
+ const body = new Uint8Array(n + 3)
+ const all: u8[] = []
+ for (let i = 0; i < hn + n; i++) {
+ seed = (seed * 1103515245 + 12345) & 0x7fffffff
+ const r = (seed >> 9) & 255
+ const b = t % 3 === 0 ? r : r < 96 ? 0 : r < 128 ? r & 3 : r
+ if (i < hn) {
+ head.push(u8(b))
+ } else {
+ body[i - hn] = b
+ }
+ all.push(u8(b))
+ }
+ let a: u8[] = []
+ let b: u8[] = []
+ appendNal(&a, 2, 1, all, true)
+ appendNalBytes(&b, 2, 1, head, body, n)
+ expect(b).toEqual(a)
+ }
+})
diff --git a/capcodec/src/cabac.tov b/capcodec/src/cabac.tov
new file mode 100644
index 000000000..18c99513c
--- /dev/null
+++ b/capcodec/src/cabac.tov
@@ -0,0 +1,616 @@
+import { BitWriter } from "./bitwriter"
+import { CabacRef } from "./cabac_ref"
+import {
+ CABAC_INIT_I, CABAC_INIT_P, CABAC_LAST_CTX, CABAC_RANGE_LPS, CABAC_SIG_CTX, CABAC_TRANSITION,
+} from "./tables"
+import { nonzeroMask } from "./tq"
+
+export const CAT_LUMA_DC = 0
+export const CAT_LUMA_AC = 1
+export const CAT_LUMA_4x4 = 2
+export const CAT_CHROMA_DC = 3
+export const CAT_CHROMA_AC = 4
+export const CAT_LUMA_8x8 = 5
+
+const CBF_BASE: int[] = [85, 89, 93, 97, 101, 0]
+const ABS_BASE: int[] = [227, 237, 247, 257, 266, 426]
+
+const BIN_CAP = 16384
+const BIN_FLUSH = 8192
+const BIN_TERM = -3
+const BYPASS_RUN = -4
+const BIN_END = -(1 << 30)
+// A decision bin is ctxIdx << 8 | DEC_BASE + DEC_ONE * bin: its low six bits are where tab[state] keeps the bin's
+// next state, with whether the bin is the LPS one bit above it. SIGN_FLAG and SIGN_NEG append a coefficient's sign;
+// SKIP_TERM appends an end_of_slice_flag of 0 to a skip flag. lsh[state] keeps, in the byte of each range quarter, the
+// renormalisation shift of that quarter's LPS range, so the range update needs no leading-zero count; the MPS one tests
+// lps > range - 256 rather than mps < 256 so that it does not wait for the subtraction.
+const DEC_BASE = 32
+const DEC_ONE = 9
+const SIGN_FLAG = 64
+const SIGN_NEG = 128
+const SKIP_TERM = 1 << 20
+
+const C1_INC = 0x4321
+const GT1_INC = 0x98765555
+const GT1_INC_DC = 0x88765555
+const NEXT_EQ1 = 0x76543321
+const NEXT_GT1_DIFF = 0x1111123
+
+function residualBins(bins: Int32Array, k0: int, cat: int, c: Int16Array, o: int, n: int, sl: Int32Array, pk: Int32Array, lv: Int32Array): int {
+ let k = k0
+ const nz = nonzeroMask(c, o, n)
+ const last = 63 - Math.clz64(nz)
+ const so = cat * 128
+ const tail = last >= 0 && last < n - 1
+ const stop = tail ? last : n - 1
+ const head = nz & ~(-1 << stop)
+ // Four positions a step, each one's significance bin followed by its last bin if it is significant. The final step
+ // can run past stop and write bins for positions that have none; k is recounted after it and later bins overwrite them.
+ for (let i = 0; i < stop; i += 4) {
+ const m = (head >> i) & 15
+ const v = i32x8.load(sl, so + 2 * i) + i32x8.load(pk, m * 16)
+ i32x8.shuffle(v, i32x8.load(pk, m * 16 + 8)).store(bins, k)
+ k += 4 + Math.popcount32(m)
+ }
+ k = k0 + stop + Math.popcount64(head)
+ if (tail) {
+ bins[k] = sl[so + 2 * last]! + DEC_ONE
+ bins[k + 1] = sl[so + 2 * last + 1]! + DEC_ONE
+ k += 2
+ }
+ let node = cat * 64
+ let m = nz
+ while (m !== 0) {
+ const i = 63 - Math.clz64(m)
+ m ^= 1 << i
+ const v = c[o + i]!
+ const a = v < 0 ? -v : v
+ const t = node + (a > 1 ? 4 : 0)
+ const c1 = lv[t]!
+ const ones = i32x8.splat(lv[t + 1]!)
+ node = lv[t + 2]!
+ ones.store(bins, k + 1)
+ ones.store(bins, k + 9)
+ const am1 = a - 1
+ if (am1 < 14) {
+ bins[k] = c1
+ bins[k + am1] = lv[t + 3]! + ((v >> 63) & SIGN_NEG)
+ k += am1 + 1
+ } else {
+ bins[k] = c1
+ const x = am1 - 13
+ const e = 63 - Math.clz64(x)
+ const w = (((1 << e) - 1) << (e + 2)) | ((x - (1 << e)) << 1) | ((v >> 63) & 1)
+ if (e < 8) {
+ bins[k + 14] = BYPASS_RUN - (w | ((2 * e + 1) << 16))
+ k += 15
+ } else {
+ bins[k + 14] = BYPASS_RUN - ((w >> 16) | ((2 * e - 15) << 16))
+ bins[k + 15] = BYPASS_RUN - ((w & 0xffff) | (15 << 16))
+ k += 16
+ }
+ }
+ }
+ return k
+}
+
+function carryInto(out: Uint8Array, len: int) {
+ let j = len - 1
+ while (j >= 0) {
+ const t = out[j]! + 1
+ out[j] = t & 255
+ if (t < 256) return
+ j--
+ }
+}
+
+function encodeBins(st: Int32Array, bins: Int32Array, ctx: Uint8Array, tab: Int64Array, lsh: Int64Array, out: Uint8Array) {
+ let low = st[0]!
+ let range = st[1]!
+ let queue = st[2]!
+ let len = st[3]!
+ let i = 0
+ while (true) {
+ const b = bins[i]!
+ i++
+ if (b >= 0 && b < SKIP_TERM) {
+ const ci = b >> 8
+ const s = ctx[ci]!
+ const e = tab[s]!
+ const t = e >> (b & 63)
+ ctx[ci] = t & 255
+ const q8 = (range >> 3) & 24
+ const lps = (e >> q8) & 255
+ const ls = (lsh[s]! >> q8) & 7
+ const mps = range - lps
+ const isLps = (t & 256) !== 0
+ const ms = lps > range - 256 ? 1 : 0
+ const rs = isLps ? ls : ms
+ range = isLps ? lps << ls : mps << ms
+ const sh = rs + ((b >> 6) & 1)
+ low = ((low + (isLps ? mps : 0)) << sh) + (range & -((b >> 7) & 1))
+ queue += sh
+ } else if (b >= 0) {
+ const ci = (b >> 8) & 1023
+ const s = ctx[ci]!
+ const e = tab[s]!
+ const t = e >> (b & 63)
+ ctx[ci] = t & 255
+ const q8 = (range >> 3) & 24
+ const lps = (e >> q8) & 255
+ const ls = (lsh[s]! >> q8) & 7
+ const mps = range - lps
+ const isLps = (t & 256) !== 0
+ const rs = isLps ? ls : mps < 256 ? 1 : 0
+ const term = (isLps ? lps << ls : mps < 256 ? mps + mps : mps) - 2
+ const ts = term >= 256 ? 0 : 1
+ range = term << ts
+ low = (low + (isLps ? mps : 0)) << (rs + ts)
+ queue += rs + ts
+ } else if (b > BIN_TERM) {
+ low = (low << 1) + (range & -(b & 1))
+ queue++
+ } else if (b === BIN_TERM) {
+ range -= 2
+ const sh = range >= 256 ? 0 : 1
+ low = low << sh
+ range = range << sh
+ queue += sh
+ } else if (b !== BIN_END) {
+ const x = BYPASS_RUN - b
+ const nb = (x >> 16) + 1
+ low = (low << nb) + range * (x & 0xffff)
+ queue += nb
+ } else {
+ break
+ }
+ if (queue >= 24) {
+ const sft = queue - 14
+ const v = low >> sft
+ low = low & ((1 << sft) - 1)
+ queue -= 32
+ if (v > 0xffffffff) carryInto(out, len)
+ out[len] = (v >> 24) & 255
+ out[len + 1] = (v >> 16) & 255
+ out[len + 2] = (v >> 8) & 255
+ out[len + 3] = v & 255
+ len += 4
+ }
+ }
+ while (queue >= 0) {
+ const v = low >> (queue + 10)
+ low = low & ((0x400 << queue) - 1)
+ queue -= 8
+ if (v > 0xff) carryInto(out, len)
+ out[len] = v & 255
+ len++
+ }
+ st[0] = low
+ st[1] = range
+ st[2] = queue
+ st[3] = len
+}
+
+export class Cabac {
+ ctx: Uint8Array = new Uint8Array(1024)
+ low = 0
+ range = 510
+ queue = -9
+ out: Uint8Array = new Uint8Array(65536)
+ len = 0
+ bins: Int32Array = new Int32Array(BIN_CAP + 1)
+ nb = 0
+ st: Int32Array = new Int32Array(4)
+ tab: Int64Array = new Int64Array(128)
+ lsh: Int64Array = new Int64Array(128)
+ sl: Int32Array = new Int32Array(768)
+ pk: Int32Array = new Int32Array(256)
+ lv: Int32Array = new Int32Array(384)
+
+ constructor() {
+ for (let s = 0; s < 128; s++) {
+ const mps = s & 1
+ let e = (int(CABAC_TRANSITION[s * 2]!) << 32) + (mps << 40)
+ e += (int(CABAC_TRANSITION[s * 2 + 1]!) << 41) + ((1 - mps) << 49)
+ let l = 0
+ for (let q = 0; q < 4; q++) {
+ const lps = int(CABAC_RANGE_LPS[(s >> 1) * 4 + q]!)
+ e += lps << (8 * q)
+ l += (Math.clz64(lps) - 55) << (8 * q)
+ }
+ this.tab[s] = e
+ this.lsh[s] = l
+ }
+ for (let i = 0; i < 384; i++) {
+ this.sl[2 * i] = (int(CABAC_SIG_CTX[i]!) << 8) + DEC_BASE
+ this.sl[2 * i + 1] = (int(CABAC_LAST_CTX[i]!) << 8) + DEC_BASE
+ }
+ for (let m = 0; m < 16; m++) {
+ let k = m * 16 + 8
+ for (let j = 0; j < 4; j++) {
+ const b = (m >> j) & 1
+ this.pk[m * 16 + 2 * j] = DEC_ONE * b
+ this.pk[k] = 2 * j
+ k++
+ if (b === 1) {
+ this.pk[k] = 2 * j + 1
+ k++
+ }
+ }
+ }
+ for (let cat = 0; cat < 6; cat++) {
+ const ab = (ABS_BASE[cat]! << 8) + DEC_BASE
+ const gtInc = cat === CAT_CHROMA_DC ? GT1_INC_DC : GT1_INC
+ for (let node = 0; node < 8; node++) {
+ const sh = node * 4
+ const g = ab + (((gtInc >> sh) & 15) << 8)
+ for (let gt = 0; gt < 2; gt++) {
+ const c1 = ab + (((C1_INC >> sh) & 15) << 8) + DEC_ONE * gt
+ const next = ((NEXT_EQ1 + (NEXT_GT1_DIFF & -gt)) >> sh) & 15
+ const t = cat * 64 + node * 8 + gt * 4
+ this.lv[t] = c1
+ this.lv[t + 1] = g + DEC_ONE
+ this.lv[t + 2] = cat * 64 + next * 8
+ this.lv[t + 3] = (gt === 0 ? c1 : g) + SIGN_FLAG
+ }
+ }
+ }
+ }
+
+ init(sliceQp: int, intraSlice: bool, initIdc: int) {
+ const qp = sliceQp < 0 ? 0 : sliceQp > 51 ? 51 : sliceQp
+ for (let i = 0; i < 1024; i++) {
+ let m = 0
+ let n = 0
+ if (intraSlice) {
+ m = int(CABAC_INIT_I[2 * i]!)
+ n = int(CABAC_INIT_I[2 * i + 1]!)
+ } else {
+ m = int(CABAC_INIT_P[initIdc * 2048 + 2 * i]!)
+ n = int(CABAC_INIT_P[initIdc * 2048 + 2 * i + 1]!)
+ }
+ let pre = ((m * qp) >> 4) + n
+ pre = pre < 1 ? 1 : pre > 126 ? 126 : pre
+ if (pre <= 63) {
+ this.ctx[i] = (63 - pre) * 2
+ } else {
+ this.ctx[i] = (pre - 64) * 2 + 1
+ }
+ }
+ this.low = 0
+ this.range = 510
+ this.queue = -9
+ this.len = 0
+ this.nb = 0
+ }
+
+ reserve(extra: int) {
+ const need = this.len + extra
+ if (need <= this.out.length) return
+ let cap = this.out.length * 2
+ while (cap < need) cap *= 2
+ const grown = new Uint8Array(cap)
+ grown.set(this.out.subarray(0, this.len), 0)
+ this.out = grown
+ }
+
+ putByte() {
+ const v = this.low >> (this.queue + 10)
+ this.low = this.low & ((0x400 << this.queue) - 1)
+ this.queue -= 8
+ this.reserve(1)
+ if (v > 0xff) carryInto(this.out, this.len)
+ this.out[this.len] = v & 255
+ this.len++
+ }
+
+ run() {
+ const n = this.nb
+ if (n === 0) return
+ this.reserve(n + 8)
+ this.st[0] = this.low
+ this.st[1] = this.range
+ this.st[2] = this.queue
+ this.st[3] = this.len
+ this.bins[n] = BIN_END
+ encodeBins(this.st, this.bins, this.ctx, this.tab, this.lsh, this.out)
+ this.low = this.st[0]!
+ this.range = this.st[1]!
+ this.queue = this.st[2]!
+ this.len = this.st[3]!
+ this.nb = 0
+ }
+
+ // Once per macroblock suffices: its header adds at most ~2,600 bins and residual() reserves per block (at most ~3,100).
+ room() {
+ if (this.nb > BIN_FLUSH) this.run()
+ }
+
+ add(b: int) {
+ this.bins[this.nb] = b
+ this.nb++
+ }
+
+ decision(ctxIdx: int, bin: int) {
+ this.add((ctxIdx << 8) + DEC_BASE + DEC_ONE * bin)
+ }
+
+ bypass(bin: int) {
+ this.add(bin - 2)
+ }
+
+ bypassBits(v: int, n: int) {
+ let m = n
+ while (m > 16) {
+ m -= 16
+ this.add(BYPASS_RUN - (((v >> m) & 0xffff) | (15 << 16)))
+ }
+ if (m > 0) this.add(BYPASS_RUN - ((v & ((1 << m) - 1)) | ((m - 1) << 16)))
+ }
+
+ terminate(bin: int) {
+ if (bin === 0) {
+ this.add(BIN_TERM)
+ return
+ }
+ this.run()
+ this.range -= 2
+ this.low += this.range
+ this.flush()
+ }
+
+ flush() {
+ this.low = this.low << 7
+ this.queue += 7
+ if (this.queue >= 0) this.putByte()
+ this.low = (this.low | 0x80) << 3
+ this.queue += 3
+ while (this.queue >= 0) this.putByte()
+ this.low = (this.low >> 10) << 10
+ if (this.queue > -8) {
+ this.low = this.low << (-this.queue)
+ this.queue = 0
+ this.putByte()
+ } else if (((this.low >> 10) & 1) !== 0) {
+ carryInto(this.out, this.len)
+ }
+ this.range = 2
+ }
+
+ residual(cat: int, c: Int16Array, o: int, n: int) {
+ if (this.nb > BIN_FLUSH) this.run()
+ this.nb = residualBins(this.bins, this.nb, cat, c, o, n, this.sl, this.pk, this.lv)
+ }
+
+ cbf(cat: int, inc: int, coded: bool) {
+ this.decision(CBF_BASE[cat]! + inc, coded ? 1 : 0)
+ }
+
+ skipRun(types: Int32Array, top: int, n: int, left: int, skip: int, ctxIdx: int) {
+ if (this.nb > BIN_FLUSH) this.run()
+ const bins = this.bins
+ const one = (ctxIdx << 8) + DEC_BASE + DEC_ONE + SKIP_TERM
+ const k = this.nb
+ bins[k] = one + (left << 8) + (top >= 0 && types[top]! !== skip ? 256 : 0)
+ for (let i = 1; i < n; i++) bins[k + i] = one + (top >= 0 && types[top + i]! !== skip ? 256 : 0)
+ this.nb = k + n
+ }
+
+ bytes(): u8[] {
+ let r: u8[] = []
+ for (let i = 0; i < this.len; i++) r.push(u8(this.out[i]!))
+ return r
+ }
+}
+
+class Lcg {
+ x: int
+ constructor(seed: int) {
+ this.x = seed
+ }
+ next(n: int): int {
+ this.x = (this.x * 1103515245 + 12345) & 0x7fffffff
+ return (this.x >> 8) % n
+ }
+}
+
+function sameBytes(a: u8[], b: u8[]): bool {
+ if (a.length !== b.length) return false
+ for (let i = 0; i < a.length; i++) {
+ if (a[i]! !== b[i]!) return false
+ }
+ return true
+}
+
+function compareRandom(seed: int, ops: int, bias: int, terminates: bool): bool {
+ const bw = new BitWriter()
+ const ref = new CabacRef(bw)
+ const fast = new Cabac()
+ ref.init(26, seed % 2 === 0, 0)
+ fast.init(26, seed % 2 === 0, 0)
+ const rng = new Lcg(seed)
+ for (let i = 0; i < ops; i++) {
+ fast.room()
+ const kind = rng.next(terminates ? 10 : 9)
+ if (kind < 7) {
+ const ctx = rng.next(460)
+ const bin = rng.next(100) < bias ? 1 : 0
+ ref.decision(ctx, bin)
+ fast.decision(ctx, bin)
+ } else if (kind < 9) {
+ const bin = rng.next(2)
+ ref.bypass(bin)
+ fast.bypass(bin)
+ } else {
+ ref.terminate(0)
+ fast.terminate(0)
+ }
+ }
+ ref.terminate(1)
+ bw.alignZero()
+ fast.terminate(1)
+ return sameBytes(bw.buf, fast.bytes())
+}
+
+function coeffBlock(rng: Lcg, n: int, density: int, big: bool): int[] {
+ let c: int[] = []
+ for (let i = 0; i < n; i++) {
+ if (rng.next(100) < density) {
+ let a = 1 + rng.next(big ? 300 : 4)
+ if (rng.next(2) === 0) a = -a
+ c.push(a)
+ } else {
+ c.push(0)
+ }
+ }
+ return c
+}
+
+test("context initialisation follows 9.3.1.1", () => {
+ const c = new Cabac()
+ c.init(26, true, 0)
+ const m = int(CABAC_INIT_I[2 * 60]!)
+ const n = int(CABAC_INIT_I[2 * 60 + 1]!)
+ let pre = ((m * 26) >> 4) + n
+ pre = pre < 1 ? 1 : pre > 126 ? 126 : pre
+ const expected = pre <= 63 ? (63 - pre) * 2 : (pre - 64) * 2 + 1
+ expect(c.ctx[60]!).toBe(expected)
+})
+
+test("a terminated empty stream flushes to whole bytes matching the spec engine", () => {
+ const bw = new BitWriter()
+ const ref = new CabacRef(bw)
+ ref.init(26, true, 0)
+ ref.terminate(1)
+ bw.alignZero()
+ const c = new Cabac()
+ c.init(26, true, 0)
+ c.terminate(1)
+ expect(c.len > 0).toBe(true)
+ expect(sameBytes(bw.buf, c.bytes())).toBe(true)
+})
+
+test("byte-oriented engine is bit-exact with the spec engine on random symbol streams", () => {
+ let ok = 0
+ const total = 400
+ for (let seed = 1; seed <= total; seed++) {
+ const ops = seed < 100 ? seed : seed * 37
+ const bias = seed % 5 === 0 ? 50 : seed % 5 === 1 ? 3 : seed % 5 === 2 ? 97 : seed % 5 === 3 ? 20 : 80
+ if (compareRandom(seed, ops, bias, true)) ok++
+ }
+ expect(ok).toBe(total)
+})
+
+test("streams longer than the pending-bin buffer stay bit-exact without terminations", () => {
+ let ok = 0
+ for (let seed = 1; seed <= 6; seed++) {
+ if (compareRandom(seed, 50000 + seed * 3001, seed % 2 === 0 ? 10 : 60, false)) ok++
+ }
+ expect(ok).toBe(6)
+})
+
+test("multi-bit bypass runs are bit-exact with single bypass bins of the spec engine", () => {
+ let ok = 0
+ for (let seed = 1; seed <= 200; seed++) {
+ const bw = new BitWriter()
+ const ref = new CabacRef(bw)
+ const fast = new Cabac()
+ ref.init(26, seed % 2 === 0, 0)
+ fast.init(26, seed % 2 === 0, 0)
+ const rng = new Lcg(seed * 104729)
+ for (let i = 0; i < 400; i++) {
+ fast.room()
+ if (rng.next(2) === 0) {
+ const ctx = rng.next(460)
+ const bin = rng.next(100) < 30 ? 1 : 0
+ ref.decision(ctx, bin)
+ fast.decision(ctx, bin)
+ } else {
+ const n = 1 + rng.next(32)
+ const v = (rng.next(65536) << 16) | rng.next(65536)
+ for (let k = n - 1; k >= 0; k--) ref.bypass((v >> k) & 1)
+ fast.bypassBits(v, n)
+ }
+ }
+ ref.terminate(1)
+ bw.alignZero()
+ fast.terminate(1)
+ if (sameBytes(bw.buf, fast.bytes())) ok++
+ }
+ expect(ok).toBe(200)
+})
+
+test("skip runs are bit-exact with per-macroblock skip flags and terminations of the spec engine", () => {
+ let ok = 0
+ for (let seed = 1; seed <= 200; seed++) {
+ const bw = new BitWriter()
+ const ref = new CabacRef(bw)
+ const fast = new Cabac()
+ ref.init(26, false, 0)
+ fast.init(26, false, 0)
+ const rng = new Lcg(seed * 7561)
+ const types = new Int32Array(64)
+ for (let i = 0; i < 64; i++) types[i] = rng.next(3) === 0 ? 4 : 5
+ for (let i = 0; i < 300; i++) {
+ fast.room()
+ if (rng.next(3) === 0) {
+ const ctx = rng.next(460)
+ const bin = rng.next(2)
+ ref.decision(ctx, bin)
+ fast.decision(ctx, bin)
+ } else {
+ const n = 1 + rng.next(32)
+ const top = rng.next(4) === 0 ? -1 : rng.next(64 - n)
+ const left = rng.next(2)
+ const ctxIdx = rng.next(2) === 0 ? 11 : 24
+ for (let k = 0; k < n; k++) {
+ const b = top >= 0 && types[top + k]! !== 5 ? 1 : 0
+ ref.decision(ctxIdx + (k === 0 ? left : 0) + b, 1)
+ ref.terminate(0)
+ }
+ fast.skipRun(types, top, n, left, 5, ctxIdx)
+ }
+ }
+ ref.terminate(1)
+ bw.alignZero()
+ fast.terminate(1)
+ if (sameBytes(bw.buf, fast.bytes())) ok++
+ }
+ expect(ok).toBe(200)
+})
+
+test("residual coding is bit-exact with the spec engine for every block category", () => {
+ let ok = 0
+ let total = 0
+ for (let seed = 1; seed <= 120; seed++) {
+ const rng = new Lcg(seed * 7919)
+ const bw = new BitWriter()
+ const ref = new CabacRef(bw)
+ const fast = new Cabac()
+ ref.init(20 + seed % 20, seed % 3 === 0, 0)
+ fast.init(20 + seed % 20, seed % 3 === 0, 0)
+ for (let b = 0; b < 40; b++) {
+ const cat = rng.next(6)
+ const n = cat === CAT_LUMA_8x8 ? 64 : cat === CAT_CHROMA_DC ? 4 : cat === CAT_LUMA_AC || cat === CAT_CHROMA_AC ? 15 : 16
+ const c0 = coeffBlock(rng, n, 5 + rng.next(80), rng.next(4) === 0)
+ let any = false
+ for (const v of c0) if (v !== 0) any = true
+ if (!any) c0[0] = 1
+ const c = new Int16Array(n + 16)
+ for (let i = 0; i < n + 16; i++) c[i] = i < n ? c0[i]! : i - n + 1
+ ref.residual(cat, c, 0, n)
+ fast.residual(cat, c, 0, n)
+ const inc = rng.next(4)
+ const coded = rng.next(2) === 0
+ ref.cbf(cat, inc, coded)
+ fast.cbf(cat, inc, coded)
+ }
+ ref.terminate(1)
+ bw.alignZero()
+ fast.terminate(1)
+ total++
+ if (sameBytes(bw.buf, fast.bytes())) ok++
+ }
+ expect(ok).toBe(total)
+})
diff --git a/capcodec/src/cabac_ref.tov b/capcodec/src/cabac_ref.tov
new file mode 100644
index 000000000..e2a8704aa
--- /dev/null
+++ b/capcodec/src/cabac_ref.tov
@@ -0,0 +1,193 @@
+import { BitWriter } from "./bitwriter"
+import { CABAC_INIT_I, CABAC_INIT_P, CABAC_NEXT_LPS, CABAC_NEXT_MPS, CABAC_RANGE_LPS, LAST8, SIG8_FRAME } from "./tables"
+
+const CAT_CHROMA_DC = 3
+const CAT_LUMA_8x8 = 5
+
+const CBF_BASE: int[] = [85, 89, 93, 97, 101, 0]
+const SIG_BASE: int[] = [105, 120, 134, 149, 152, 402]
+const LAST_BASE: int[] = [166, 181, 195, 210, 213, 417]
+const ABS_BASE: int[] = [227, 237, 247, 257, 266, 426]
+
+export class CabacRef {
+ ctx: int[] = []
+ low = 0
+ range = 510
+ outstanding = 0
+ firstBit = true
+ bw: BitWriter
+ bins = 0
+
+ constructor(bw: BitWriter) {
+ this.bw = bw
+ for (let i = 0; i < 1024; i++) this.ctx.push(0)
+ }
+
+ init(sliceQp: int, intraSlice: bool, initIdc: int) {
+ const qp = sliceQp < 0 ? 0 : sliceQp > 51 ? 51 : sliceQp
+ for (let i = 0; i < 1024; i++) {
+ let m = 0
+ let n = 0
+ if (intraSlice) {
+ m = int(CABAC_INIT_I[2 * i]!)
+ n = int(CABAC_INIT_I[2 * i + 1]!)
+ } else {
+ m = int(CABAC_INIT_P[initIdc * 2048 + 2 * i]!)
+ n = int(CABAC_INIT_P[initIdc * 2048 + 2 * i + 1]!)
+ }
+ let pre = ((m * qp) >> 4) + n
+ pre = pre < 1 ? 1 : pre > 126 ? 126 : pre
+ if (pre <= 63) {
+ this.ctx[i] = (63 - pre) * 2
+ } else {
+ this.ctx[i] = (pre - 64) * 2 + 1
+ }
+ }
+ this.low = 0
+ this.range = 510
+ this.outstanding = 0
+ this.firstBit = true
+ this.bins = 0
+ }
+
+ putBit(b: int) {
+ if (this.firstBit) {
+ this.firstBit = false
+ } else {
+ this.bw.putBits(b, 1)
+ }
+ let left = this.outstanding
+ while (left > 0) {
+ const k = left > 24 ? 24 : left
+ this.bw.putBits(b === 1 ? 0 : (1 << k) - 1, k)
+ left -= k
+ }
+ this.outstanding = 0
+ }
+
+ renorm() {
+ while (this.range < 256) {
+ if (this.low < 256) {
+ this.putBit(0)
+ } else if (this.low >= 512) {
+ this.low -= 512
+ this.putBit(1)
+ } else {
+ this.low -= 256
+ this.outstanding++
+ }
+ this.range = this.range << 1
+ this.low = this.low << 1
+ }
+ }
+
+ decision(ctxIdx: int, bin: int) {
+ const s = this.ctx[ctxIdx]!
+ const state = s >> 1
+ const mps = s & 1
+ const lps = int(CABAC_RANGE_LPS[state * 4 + ((this.range >> 6) & 3)]!)
+ this.range -= lps
+ if (bin !== mps) {
+ this.low += this.range
+ this.range = lps
+ this.ctx[ctxIdx] = state === 0 ? int(CABAC_NEXT_LPS[state]!) * 2 + (1 - mps) : int(CABAC_NEXT_LPS[state]!) * 2 + mps
+ } else {
+ this.ctx[ctxIdx] = int(CABAC_NEXT_MPS[state]!) * 2 + mps
+ }
+ this.bins++
+ if (this.range < 256) this.renorm()
+ }
+
+ bypass(bin: int) {
+ this.low = this.low << 1
+ if (bin !== 0) this.low += this.range
+ if (this.low >= 1024) {
+ this.putBit(1)
+ this.low -= 1024
+ } else if (this.low < 512) {
+ this.putBit(0)
+ } else {
+ this.low -= 512
+ this.outstanding++
+ }
+ this.bins++
+ }
+
+ terminate(bin: int) {
+ this.range -= 2
+ if (bin !== 0) {
+ this.low += this.range
+ this.range = 2
+ this.renorm()
+ this.putBit((this.low >> 9) & 1)
+ this.bw.putBits(((this.low >> 7) & 3) | 1, 2)
+ } else if (this.range < 256) {
+ this.renorm()
+ }
+ this.bins++
+ }
+
+ residual(cat: int, c: Int16Array, o: int, n: int) {
+ let last = -1
+ for (let i = n - 1; i >= 0; i--) {
+ if (c[o + i]! !== 0) {
+ last = i
+ break
+ }
+ }
+ const sb = SIG_BASE[cat]!
+ const lb = LAST_BASE[cat]!
+ for (let i = 0; i < n - 1; i++) {
+ const sig = c[o + i]! !== 0 ? 1 : 0
+ const si = cat === CAT_CHROMA_DC ? (i < 2 ? i : 2) : cat === CAT_LUMA_8x8 ? int(SIG8_FRAME[i]!) : i
+ this.decision(sb + si, sig)
+ if (sig === 1) {
+ const li = cat === CAT_CHROMA_DC ? (i < 2 ? i : 2) : cat === CAT_LUMA_8x8 ? int(LAST8[i]!) : i
+ this.decision(lb + li, i === last ? 1 : 0)
+ if (i === last) break
+ }
+ }
+ const ab = ABS_BASE[cat]!
+ const gtMax = cat === CAT_CHROMA_DC ? 3 : 4
+ let numGt1 = 0
+ let numEq1 = 0
+ for (let i = last; i >= 0; i--) {
+ const v = c[o + i]!
+ if (v === 0) continue
+ const a = v < 0 ? -v : v
+ const am1 = a - 1
+ const inc0 = numGt1 !== 0 ? 0 : (1 + numEq1 < 4 ? 1 + numEq1 : 4)
+ if (am1 === 0) {
+ this.decision(ab + inc0, 0)
+ numEq1++
+ } else {
+ this.decision(ab + inc0, 1)
+ const incG = 5 + (numGt1 < gtMax ? numGt1 : gtMax)
+ const pre = am1 < 14 ? am1 : 14
+ for (let k = 1; k < pre; k++) this.decision(ab + incG, 1)
+ if (am1 < 14) {
+ this.decision(ab + incG, 0)
+ } else {
+ let suf = am1 - 14
+ let k = 0
+ while (suf >= (1 << k)) {
+ this.bypass(1)
+ suf -= 1 << k
+ k++
+ }
+ this.bypass(0)
+ while (k > 0) {
+ k--
+ this.bypass((suf >> k) & 1)
+ }
+ }
+ numGt1++
+ }
+ this.bypass(v < 0 ? 1 : 0)
+ }
+ }
+
+ cbf(cat: int, inc: int, coded: bool) {
+ this.decision(CBF_BASE[cat]! + inc, coded ? 1 : 0)
+ }
+}
diff --git a/capcodec/src/cavlc.tov b/capcodec/src/cavlc.tov
new file mode 100644
index 000000000..21e68b8ea
--- /dev/null
+++ b/capcodec/src/cavlc.tov
@@ -0,0 +1,158 @@
+import { BitWriter } from "./bitwriter"
+import {
+ COEFF_TOKEN_LEN, COEFF_TOKEN_CODE, COEFF_TOKEN_DC_LEN, COEFF_TOKEN_DC_CODE, TOTAL_ZEROS_LEN, TOTAL_ZEROS_CODE,
+ TOTAL_ZEROS_DC_LEN, TOTAL_ZEROS_DC_CODE, RUN_BEFORE_LEN, RUN_BEFORE_CODE,
+} from "./tables"
+
+export function writeCoeffToken(bw: BitWriter, nC: int, totalCoeff: int, trailingOnes: int) {
+ if (nC < 0) {
+ const i = trailingOnes * 17 + totalCoeff
+ bw.putBits(int(COEFF_TOKEN_DC_CODE[i]!), int(COEFF_TOKEN_DC_LEN[i]!))
+ return
+ }
+ if (nC >= 8) {
+ bw.putBits(totalCoeff > 0 ? ((totalCoeff - 1) << 2) | trailingOnes : 3, 6)
+ return
+ }
+ const vlc = nC < 2 ? 0 : nC < 4 ? 1 : 2
+ const i = vlc * 68 + trailingOnes * 17 + totalCoeff
+ bw.putBits(int(COEFF_TOKEN_CODE[i]!), int(COEFF_TOKEN_LEN[i]!))
+}
+
+export function writeLevel(bw: BitWriter, levelCode: int, suffixLength: int) {
+ if (suffixLength === 0) {
+ if (levelCode < 14) {
+ bw.putBits(1, levelCode + 1)
+ return
+ }
+ if (levelCode < 30) {
+ bw.putBits(1, 15)
+ bw.putBits(levelCode - 14, 4)
+ return
+ }
+ writeEscape(bw, levelCode - 30)
+ return
+ }
+ if (levelCode < (15 << suffixLength)) {
+ bw.putBits(1, (levelCode >> suffixLength) + 1)
+ bw.putBits(levelCode & ((1 << suffixLength) - 1), suffixLength)
+ return
+ }
+ writeEscape(bw, levelCode - (15 << suffixLength))
+}
+
+function writeEscape(bw: BitWriter, rest: int) {
+ if (rest < 4096) {
+ bw.putBits(1, 16)
+ bw.putBits(rest, 12)
+ return
+ }
+ let prefix = 16
+ while (rest >= (1 << (prefix - 2)) - 4096) prefix++
+ bw.putBits(1, prefix + 1)
+ bw.putBits(rest - ((1 << (prefix - 3)) - 4096), prefix - 3)
+}
+
+export function writeResidual(bw: BitWriter, c: Int16Array, o: int, maxNum: int, nC: int): int {
+ const lim = (1 << maxNum) - 1
+ const v16 = i16x16.load(c, o)
+ const nz = v16.ne(i16x16.splat(0)).mask() & lim
+ const big = (v16.gt(i16x16.splat(1)) | v16.lt(i16x16.splat(-1))).mask() & lim
+ const total = Math.popcount64(nz)
+ const last = 63 - Math.clz64(nz)
+ const ones = Math.popcount64(nz >> (64 - Math.clz64(big)))
+ const t1 = ones < 3 ? ones : 3
+ writeCoeffToken(bw, nC, total, t1)
+ if (total === 0) return 0
+ let seen = 0
+ let suffixLength = total > 10 && t1 < 3 ? 1 : 0
+ let m = nz
+ while (m !== 0) {
+ const i = 63 - Math.clz64(m)
+ m ^= 1 << i
+ const v = c[o + i]!
+ if (seen < t1) {
+ bw.putBit(v < 0 ? 1 : 0)
+ } else {
+ let levelCode = v > 0 ? 2 * v - 2 : -2 * v - 1
+ if (seen === t1 && t1 < 3) levelCode -= 2
+ writeLevel(bw, levelCode, suffixLength)
+ if (suffixLength === 0) suffixLength = 1
+ const a = v < 0 ? -v : v
+ if (a > (3 << (suffixLength - 1)) && suffixLength < 6) suffixLength++
+ }
+ seen++
+ }
+ const totalZeros = last + 1 - total
+ if (total < maxNum) {
+ const i = (total - 1) * 16 + totalZeros
+ if (maxNum === 4) {
+ bw.putBits(int(TOTAL_ZEROS_DC_CODE[i]!), int(TOTAL_ZEROS_DC_LEN[i]!))
+ } else {
+ bw.putBits(int(TOTAL_ZEROS_CODE[i]!), int(TOTAL_ZEROS_LEN[i]!))
+ }
+ }
+ let zerosLeft = totalZeros
+ let rest = nz ^ (1 << last)
+ let i = last
+ while (rest !== 0 && zerosLeft > 0) {
+ const j = 63 - Math.clz64(rest)
+ rest ^= 1 << j
+ const run = i - 1 - j
+ const t = (zerosLeft > 7 ? 6 : zerosLeft - 1) * 16 + run
+ bw.putBits(int(RUN_BEFORE_CODE[t]!), int(RUN_BEFORE_LEN[t]!))
+ zerosLeft -= run
+ i = j
+ }
+ return total
+}
+
+test("coeff token for an empty block at nC 0 is a single 1", () => {
+ const bw = new BitWriter()
+ writeResidual(bw, new Int16Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]), 0, 16, 0)
+ expect(bw.bitPos()).toBe(1)
+})
+
+test("the spec's worked example encodes to the published bits", () => {
+ const bw = new BitWriter()
+ writeResidual(bw, new Int16Array([0, 3, 0, 1, -1, -1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]), 0, 16, 0)
+ let bits = ""
+ const n = bw.bitPos()
+ bw.alignZero()
+ for (let i = 0; i < bw.buf.length; i++) {
+ const b = int(bw.buf[i]!)
+ for (let k = 7; k >= 0; k--) bits += ((b >> k) & 1) === 1 ? "1" : "0"
+ }
+ expect(bits.slice(0, n)).toBe("000010001110010111101101")
+})
+
+test("large levels use the escape", () => {
+ const bw = new BitWriter()
+ let c: int[] = [3000, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
+ const t = writeResidual(bw, new Int16Array(c), 0, 16, 0)
+ expect(t).toBe(1)
+ expect(bw.bitPos() > 16).toBe(true)
+})
+
+test("coefficients past maxNum do not change the coded bits", () => {
+ const sizes: int[] = [4, 15, 16]
+ let same = 0
+ for (const n of sizes) {
+ const clean = new Int16Array([1, 0, -1, 2, 0, 0, 1, 0, 0, -1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0])
+ const junk = new Int16Array(20)
+ for (let i = 0; i < 20; i++) {
+ if (i >= n) clean[i] = 0
+ junk[i] = i < n ? clean[i]! : 7 - i
+ }
+ const a = new BitWriter()
+ const b = new BitWriter()
+ const ta = writeResidual(a, clean, 0, n, n === 4 ? -1 : 0)
+ const tb = writeResidual(b, junk, 0, n, n === 4 ? -1 : 0)
+ a.alignZero()
+ b.alignZero()
+ let eq = ta === tb && a.buf.length === b.buf.length
+ for (let i = 0; eq && i < a.buf.length; i++) eq = a.buf[i]! === b.buf[i]!
+ if (eq) same++
+ }
+ expect(same).toBe(3)
+})
diff --git a/capcodec/src/deblock.tov b/capcodec/src/deblock.tov
new file mode 100644
index 000000000..7ea9c58f7
--- /dev/null
+++ b/capcodec/src/deblock.tov
@@ -0,0 +1,466 @@
+import { DEBLOCK_ALPHA, DEBLOCK_BETA, DEBLOCK_TC0 } from "./tables"
+
+const ZIP8 = [0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39, 16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55]
+const ZIP16_LO = [0, 16, 1, 17, 2, 18, 3, 19, 8, 24, 9, 25, 10, 26, 11, 27]
+const ZIP16_HI = [4, 20, 5, 21, 6, 22, 7, 23, 12, 28, 13, 29, 14, 30, 15, 31]
+const ZIP32_LO = [0, 8, 1, 9, 4, 12, 5, 13]
+const ZIP32_HI = [2, 10, 3, 11, 6, 14, 7, 15]
+const HALVES = [0, 2, 1, 3]
+const HIGH8 = [8, 9, 10, 11, 12, 13, 14, 15, 8, 9, 10, 11, 12, 13, 14, 15]
+const ROW4_0 = [0, 1, 2, 3, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
+const ROW4_1 = [4, 5, 6, 7, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
+const ROW4_2 = [8, 9, 10, 11, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
+const ROW4_3 = [12, 13, 14, 15, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
+
+function iabs(v: int): int {
+ return v < 0 ? -v : v
+}
+
+function clip3(lo: int, hi: int, v: int): int {
+ return v < lo ? lo : v > hi ? hi : v
+}
+
+function clip1(v: int): int {
+ return v < 0 ? 0 : v > 255 ? 255 : v
+}
+
+export function edgeAlpha(indexA: int): int {
+ return DEBLOCK_ALPHA[indexA]!
+}
+
+export function edgeBeta(indexB: int): int {
+ return DEBLOCK_BETA[indexB]!
+}
+
+export function filterLuma(px: Uint8Array, o: int, across: int, along: int, lines: int, bs: int, indexA: int, indexB: int) {
+ const alpha = DEBLOCK_ALPHA[indexA]!
+ const beta = DEBLOCK_BETA[indexB]!
+ if (alpha === 0 || beta === 0) return
+ const tc0 = DEBLOCK_TC0[indexA * 5 + bs]!
+ for (let l = 0; l < lines; l++) {
+ const q = o + l * along
+ const p0 = int(px[q - across]!)
+ const q0 = int(px[q]!)
+ if (iabs(p0 - q0) >= alpha) continue
+ const p1 = int(px[q - 2 * across]!)
+ if (iabs(p1 - p0) >= beta) continue
+ const q1 = int(px[q + across]!)
+ if (iabs(q1 - q0) >= beta) continue
+ const p2 = int(px[q - 3 * across]!)
+ const q2 = int(px[q + 2 * across]!)
+ if (p0 === q0 && p1 === p0 && q1 === q0 && p2 === p0 && q2 === q0) {
+ if (bs < 4) continue
+ if (int(px[q - 4 * across]!) === p0 && int(px[q + 3 * across]!) === q0) continue
+ }
+ const ap = iabs(p2 - p0)
+ const aq = iabs(q2 - q0)
+ if (bs < 4) {
+ const tc = tc0 + (ap < beta ? 1 : 0) + (aq < beta ? 1 : 0)
+ const delta = clip3(-tc, tc, (((q0 - p0) << 2) + (p1 - q1) + 4) >> 3)
+ px[q - across] = clip1(p0 + delta)
+ px[q] = clip1(q0 - delta)
+ if (ap < beta) px[q - 2 * across] = p1 + clip3(-tc0, tc0, (p2 + ((p0 + q0 + 1) >> 1) - (p1 << 1)) >> 1)
+ if (aq < beta) px[q + across] = q1 + clip3(-tc0, tc0, (q2 + ((p0 + q0 + 1) >> 1) - (q1 << 1)) >> 1)
+ } else {
+ const strong = iabs(p0 - q0) < ((alpha >> 2) + 2)
+ if (ap < beta && strong) {
+ const p3 = int(px[q - 4 * across]!)
+ px[q - across] = (p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) >> 3
+ px[q - 2 * across] = (p2 + p1 + p0 + q0 + 2) >> 2
+ px[q - 3 * across] = (2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) >> 3
+ } else {
+ px[q - across] = (2 * p1 + p0 + q1 + 2) >> 2
+ }
+ if (aq < beta && strong) {
+ const q3 = int(px[q + 3 * across]!)
+ px[q] = (p1 + 2 * p0 + 2 * q0 + 2 * q1 + q2 + 4) >> 3
+ px[q + across] = (p0 + q0 + q1 + q2 + 2) >> 2
+ px[q + 2 * across] = (2 * q3 + 3 * q2 + q1 + q0 + p0 + 4) >> 3
+ } else {
+ px[q] = (2 * q1 + q0 + p1 + 2) >> 2
+ }
+ }
+ }
+}
+
+export function filterChroma(px: Uint8Array, o: int, across: int, along: int, lines: int, bs: int, indexA: int, indexB: int) {
+ const alpha = DEBLOCK_ALPHA[indexA]!
+ const beta = DEBLOCK_BETA[indexB]!
+ if (alpha === 0 || beta === 0) return
+ const tc = DEBLOCK_TC0[indexA * 5 + bs]! + 1
+ for (let l = 0; l < lines; l++) {
+ const q = o + l * along
+ const p0 = int(px[q - across]!)
+ const q0 = int(px[q]!)
+ if (iabs(p0 - q0) >= alpha) continue
+ const p1 = int(px[q - 2 * across]!)
+ if (iabs(p1 - p0) >= beta) continue
+ const q1 = int(px[q + across]!)
+ if (iabs(q1 - q0) >= beta) continue
+ if (bs < 4) {
+ const delta = clip3(-tc, tc, (((q0 - p0) << 2) + (p1 - q1) + 4) >> 3)
+ px[q - across] = clip1(p0 + delta)
+ px[q] = clip1(q0 - delta)
+ } else {
+ px[q - across] = (2 * p1 + p0 + q1 + 2) >> 2
+ px[q] = (2 * q1 + q0 + p1 + 2) >> 2
+ }
+ }
+}
+
+function edgeMask(p1: i16x16, p0: i16x16, q0: i16x16, q1: i16x16, alpha: int, beta: int): i16x16 {
+ const vb = i16x16.splat(beta)
+ return (p0 - q0).abs().lt(i16x16.splat(alpha)) & (p1 - p0).abs().lt(vb) & (q1 - q0).abs().lt(vb)
+}
+
+function weakDelta(p1: i16x16, p0: i16x16, q0: i16x16, q1: i16x16, tc: i16x16): i16x16 {
+ return ((((q0 - p0) << 2) + (p1 - q1) + i16x16.splat(4)) >> 3).max(-tc).min(tc)
+}
+
+function weakOuter(x2: i16x16, x1: i16x16, avg: i16x16, tc0: i16x16): i16x16 {
+ return x1 + ((x2 + avg - (x1 << 1)) >> 1).max(-tc0).min(tc0)
+}
+
+function weakInner(x1: i16x16, x0: i16x16, y1: i16x16): i16x16 {
+ return ((x1 << 1) + x0 + y1 + i16x16.splat(2)) >> 2
+}
+
+function strongInner(x2: i16x16, x1: i16x16, x0: i16x16, y0: i16x16, y1: i16x16): i16x16 {
+ return (x2 + ((x1 + x0 + y0) << 1) + y1 + i16x16.splat(4)) >> 3
+}
+
+function strongMid(x2: i16x16, x1: i16x16, x0: i16x16, y0: i16x16): i16x16 {
+ return (x2 + x1 + x0 + y0 + i16x16.splat(2)) >> 2
+}
+
+function strongOuter(x3: i16x16, x2: i16x16, x1: i16x16, x0: i16x16, y0: i16x16): i16x16 {
+ return ((x3 << 1) + x2 + (x2 << 1) + x1 + x0 + y0 + i16x16.splat(4)) >> 3
+}
+
+function clampPixel(v: i16x16): i16x16 {
+ return v.max(i16x16.splat(0)).min(i16x16.splat(255))
+}
+
+function bytePairs(lo: i16x16, hi: i16x16): i16x16 {
+ return lo | (hi << 8)
+}
+
+function columnPairs(v: i32x8): u8x32 {
+ return u8x32.bitcast(i64x4.bitcast(v).swizzle(HALVES))
+}
+
+function zipRows(px: Uint8Array, a: int, along: int): i16x16 {
+ const r0 = u8x32.concat(u8x16.load(px, a), u8x16.load(px, a + 8 * along))
+ const r1 = u8x32.concat(u8x16.load(px, a + along), u8x16.load(px, a + 9 * along))
+ return i16x16.bitcast(u8x32.shuffle(r0, r1, ZIP8))
+}
+
+function zipPlanes(u: Uint8Array, v: Uint8Array, a: int, along: int): i16x16 {
+ const r0 = u8x32.concat(u8x16.load(u, a), u8x16.load(v, a))
+ const r1 = u8x32.concat(u8x16.load(u, a + along), u8x16.load(v, a + along))
+ return i16x16.bitcast(u8x32.shuffle(r0, r1, ZIP8))
+}
+
+function storeRow(px: Uint8Array, a: int, v: i16x16) {
+ u8x16.packSat(v.low(), v.high()).store(px, a)
+}
+
+function putRows8(px: Uint8Array, a: int, along: int, rows: u8x32) {
+ const lo = rows.low()
+ const hi = rows.high()
+ lo.storeLow(px, a)
+ lo.swizzle(HIGH8).storeLow(px, a + along)
+ hi.storeLow(px, a + 8 * along)
+ hi.swizzle(HIGH8).storeLow(px, a + 9 * along)
+}
+
+function putRows4(px: Uint8Array, a: int, along: int, rows: u8x16) {
+ u8x16.shuffle(rows, u8x16.load(px, a), ROW4_0).store(px, a)
+ u8x16.shuffle(rows, u8x16.load(px, a + along), ROW4_1).store(px, a + along)
+ u8x16.shuffle(rows, u8x16.load(px, a + 2 * along), ROW4_2).store(px, a + 2 * along)
+ u8x16.shuffle(rows, u8x16.load(px, a + 3 * along), ROW4_3).store(px, a + 3 * along)
+}
+
+function putPlanes(u: Uint8Array, v: Uint8Array, a: int, x: i16x16) {
+ x.low().storeU8(u, a)
+ x.high().storeU8(v, a)
+}
+
+export function filterLuma16(px: Uint8Array, o: int, across: int, along: int, bs: int, indexA: int, indexB: int) {
+ const alpha = DEBLOCK_ALPHA[indexA]!
+ const beta = DEBLOCK_BETA[indexB]!
+ if (alpha === 0 || beta === 0) return
+ lumaEdge(px, o, across, along, alpha, beta, bs === 4, i16x16.splat(DEBLOCK_TC0[indexA * 5 + bs]!))
+}
+
+export function filterLumaSegments(px: Uint8Array, o: int, across: int, along: int, coded: int, motion: int, indexA: int, indexB: int) {
+ const alpha = DEBLOCK_ALPHA[indexA]!
+ const beta = DEBLOCK_BETA[indexB]!
+ if (alpha === 0 || beta === 0) return
+ const sel = (i16x16.splat(coded) & i16x16(1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8)).ne(i16x16.splat(0))
+ const other = motion === 0 ? -1 : DEBLOCK_TC0[indexA * 5 + motion]!
+ lumaEdge(px, o, across, along, alpha, beta, false, i16x16.select(sel, i16x16.splat(DEBLOCK_TC0[indexA * 5 + 2]!), i16x16.splat(other)))
+}
+
+function lumaEdge(px: Uint8Array, o: int, across: int, along: int, alpha: int, beta: int, bs4: bool, tc0: i16x16) {
+ let p3: i16x16
+ let p2: i16x16
+ let p1: i16x16
+ let p0: i16x16
+ let q0: i16x16
+ let q1: i16x16
+ let q2: i16x16
+ let q3: i16x16
+ if (along === 1) {
+ p3 = i16x16.loadU8(px, o - 4 * across)
+ p2 = i16x16.loadU8(px, o - 3 * across)
+ p1 = i16x16.loadU8(px, o - 2 * across)
+ p0 = i16x16.loadU8(px, o - across)
+ q0 = i16x16.loadU8(px, o)
+ q1 = i16x16.loadU8(px, o + across)
+ q2 = i16x16.loadU8(px, o + 2 * across)
+ q3 = i16x16.loadU8(px, o + 3 * across)
+ } else {
+ const b = o - 4
+ const a0 = zipRows(px, b, along)
+ const a1 = zipRows(px, b + 2 * along, along)
+ const a2 = zipRows(px, b + 4 * along, along)
+ const a3 = zipRows(px, b + 6 * along, along)
+ const lo0 = i32x8.bitcast(i16x16.shuffle(a0, a1, ZIP16_LO))
+ const hi0 = i32x8.bitcast(i16x16.shuffle(a0, a1, ZIP16_HI))
+ const lo1 = i32x8.bitcast(i16x16.shuffle(a2, a3, ZIP16_LO))
+ const hi1 = i32x8.bitcast(i16x16.shuffle(a2, a3, ZIP16_HI))
+ const c01 = columnPairs(i32x8.shuffle(lo0, lo1, ZIP32_LO))
+ const c23 = columnPairs(i32x8.shuffle(lo0, lo1, ZIP32_HI))
+ const c45 = columnPairs(i32x8.shuffle(hi0, hi1, ZIP32_LO))
+ const c67 = columnPairs(i32x8.shuffle(hi0, hi1, ZIP32_HI))
+ p3 = i16x16.convert(c01.low())
+ p2 = i16x16.convert(c01.high())
+ p1 = i16x16.convert(c23.low())
+ p0 = i16x16.convert(c23.high())
+ q0 = i16x16.convert(c45.low())
+ q1 = i16x16.convert(c45.high())
+ q2 = i16x16.convert(c67.low())
+ q3 = i16x16.convert(c67.high())
+ }
+ const m = edgeMask(p1, p0, q0, q1, alpha, beta) & tc0.ge(i16x16.splat(0))
+ if (m.mask() === 0) return
+ const vb = i16x16.splat(beta)
+ const ap = (p2 - p0).abs().lt(vb)
+ const aq = (q2 - q0).abs().lt(vb)
+ let p2n = p2
+ let p1n: i16x16
+ let p0n: i16x16
+ let q0n: i16x16
+ let q1n: i16x16
+ let q2n = q2
+ if (!bs4) {
+ const delta = weakDelta(p1, p0, q0, q1, tc0 - ap - aq)
+ const avg = (p0 + q0 + i16x16.splat(1)) >> 1
+ p1n = i16x16.select(m & ap, weakOuter(p2, p1, avg, tc0), p1)
+ p0n = i16x16.select(m, clampPixel(p0 + delta), p0)
+ q0n = i16x16.select(m, clampPixel(q0 - delta), q0)
+ q1n = i16x16.select(m & aq, weakOuter(q2, q1, avg, tc0), q1)
+ } else {
+ const strong = (p0 - q0).abs().lt(i16x16.splat((alpha >> 2) + 2))
+ const sp = m & ap & strong
+ const sq = m & aq & strong
+ p2n = i16x16.select(sp, strongOuter(p3, p2, p1, p0, q0), p2)
+ p1n = i16x16.select(sp, strongMid(p2, p1, p0, q0), p1)
+ p0n = i16x16.select(m, i16x16.select(sp, strongInner(p2, p1, p0, q0, q1), weakInner(p1, p0, q1)), p0)
+ q0n = i16x16.select(m, i16x16.select(sq, strongInner(q2, q1, q0, p0, p1), weakInner(q1, q0, p1)), q0)
+ q1n = i16x16.select(sq, strongMid(q2, q1, q0, p0), q1)
+ q2n = i16x16.select(sq, strongOuter(q3, q2, q1, q0, p0), q2)
+ }
+ if (along === 1) {
+ if (bs4) storeRow(px, o - 3 * across, p2n)
+ storeRow(px, o - 2 * across, p1n)
+ storeRow(px, o - across, p0n)
+ storeRow(px, o, q0n)
+ storeRow(px, o + across, q1n)
+ if (bs4) storeRow(px, o + 2 * across, q2n)
+ return
+ }
+ const w0 = bytePairs(p3, p2n)
+ const w1 = bytePairs(p1n, p0n)
+ const w2 = bytePairs(q0n, q1n)
+ const w3 = bytePairs(q2n, q3)
+ const l0 = i32x8.bitcast(i16x16.shuffle(w0, w1, ZIP16_LO))
+ const l1 = i32x8.bitcast(i16x16.shuffle(w0, w1, ZIP16_HI))
+ const l2 = i32x8.bitcast(i16x16.shuffle(w2, w3, ZIP16_LO))
+ const l3 = i32x8.bitcast(i16x16.shuffle(w2, w3, ZIP16_HI))
+ const b = o - 4
+ putRows8(px, b, along, u8x32.bitcast(i32x8.shuffle(l0, l2, ZIP32_LO)))
+ putRows8(px, b + 2 * along, along, u8x32.bitcast(i32x8.shuffle(l0, l2, ZIP32_HI)))
+ putRows8(px, b + 4 * along, along, u8x32.bitcast(i32x8.shuffle(l1, l3, ZIP32_LO)))
+ putRows8(px, b + 6 * along, along, u8x32.bitcast(i32x8.shuffle(l1, l3, ZIP32_HI)))
+}
+
+export function filterChromaUV(u: Uint8Array, v: Uint8Array, o: int, across: int, along: int, bs: int, indexA: int, indexB: int) {
+ const alpha = DEBLOCK_ALPHA[indexA]!
+ const beta = DEBLOCK_BETA[indexB]!
+ if (alpha === 0 || beta === 0) return
+ chromaEdge(u, v, o, across, along, alpha, beta, bs === 4, i16x16.splat(DEBLOCK_TC0[indexA * 5 + bs]! + 1))
+}
+
+export function filterChromaSegments(u: Uint8Array, v: Uint8Array, o: int, across: int, along: int, coded: int, motion: int, indexA: int, indexB: int) {
+ const alpha = DEBLOCK_ALPHA[indexA]!
+ const beta = DEBLOCK_BETA[indexB]!
+ if (alpha === 0 || beta === 0) return
+ const sel = (i16x16.splat(coded) & i16x16(1, 1, 2, 2, 4, 4, 8, 8, 1, 1, 2, 2, 4, 4, 8, 8)).ne(i16x16.splat(0))
+ const other = motion === 0 ? 0 : DEBLOCK_TC0[indexA * 5 + motion]! + 1
+ chromaEdge(u, v, o, across, along, alpha, beta, false, i16x16.select(sel, i16x16.splat(DEBLOCK_TC0[indexA * 5 + 2]! + 1), i16x16.splat(other)))
+}
+
+function chromaEdge(u: Uint8Array, v: Uint8Array, o: int, across: int, along: int, alpha: int, beta: int, bs4: bool, tc: i16x16) {
+ let p1: i16x16
+ let p0: i16x16
+ let q0: i16x16
+ let q1: i16x16
+ if (along === 1) {
+ p1 = i16x16.concat(i16x8.loadU8(u, o - 2 * across), i16x8.loadU8(v, o - 2 * across))
+ p0 = i16x16.concat(i16x8.loadU8(u, o - across), i16x8.loadU8(v, o - across))
+ q0 = i16x16.concat(i16x8.loadU8(u, o), i16x8.loadU8(v, o))
+ q1 = i16x16.concat(i16x8.loadU8(u, o + across), i16x8.loadU8(v, o + across))
+ } else {
+ const b = o - 2
+ const a0 = zipPlanes(u, v, b, along)
+ const a1 = zipPlanes(u, v, b + 2 * along, along)
+ const a2 = zipPlanes(u, v, b + 4 * along, along)
+ const a3 = zipPlanes(u, v, b + 6 * along, along)
+ const lo0 = i32x8.bitcast(i16x16.shuffle(a0, a1, ZIP16_LO))
+ const lo1 = i32x8.bitcast(i16x16.shuffle(a2, a3, ZIP16_LO))
+ const c01 = columnPairs(i32x8.shuffle(lo0, lo1, ZIP32_LO))
+ const c23 = columnPairs(i32x8.shuffle(lo0, lo1, ZIP32_HI))
+ p1 = i16x16.convert(c01.low())
+ p0 = i16x16.convert(c01.high())
+ q0 = i16x16.convert(c23.low())
+ q1 = i16x16.convert(c23.high())
+ }
+ const m = edgeMask(p1, p0, q0, q1, alpha, beta)
+ if (m.mask() === 0) return
+ let p0n: i16x16
+ let q0n: i16x16
+ if (!bs4) {
+ const delta = weakDelta(p1, p0, q0, q1, tc)
+ p0n = i16x16.select(m, clampPixel(p0 + delta), p0)
+ q0n = i16x16.select(m, clampPixel(q0 - delta), q0)
+ } else {
+ p0n = i16x16.select(m, weakInner(p1, p0, q1), p0)
+ q0n = i16x16.select(m, weakInner(q1, q0, p1), q0)
+ }
+ if (along === 1) {
+ putPlanes(u, v, o - across, p0n)
+ putPlanes(u, v, o, q0n)
+ return
+ }
+ const w0 = bytePairs(p1, p0n)
+ const w1 = bytePairs(q0n, q1)
+ const top = u8x32.bitcast(i16x16.shuffle(w0, w1, ZIP16_LO))
+ const bottom = u8x32.bitcast(i16x16.shuffle(w0, w1, ZIP16_HI))
+ const b = o - 2
+ putRows4(u, b, along, top.low())
+ putRows4(u, b + 4 * along, along, bottom.low())
+ putRows4(v, b, along, top.high())
+ putRows4(v, b + 4 * along, along, bottom.high())
+}
+
+function noisePlane(seed: int, n: int, smooth: bool): u8[] {
+ let out: u8[] = []
+ let x = seed
+ let prev = 128
+ for (let i = 0; i < n; i++) {
+ x = (x * 1103515245 + 12345) & 0x7fffffff
+ let v = (x >> 9) & 255
+ if (smooth) {
+ v = prev + ((x >> 9) % 7) - 3
+ v = v < 0 ? 0 : v > 255 ? 255 : v
+ prev = v
+ }
+ out.push(u8(v))
+ }
+ return out
+}
+
+test("vector luma and chroma deblocking equal the scalar filters", () => {
+ let bad = 0
+ const stride = 48
+ for (let seed = 1; seed <= 160; seed++) {
+ const base = noisePlane(seed, stride * 48, seed % 3 !== 0)
+ const other = noisePlane(seed + 1000, stride * 48, seed % 5 !== 0)
+ const bs = 1 + seed % 4
+ const ia = 10 + (seed * 7) % 42
+ const ib = 10 + (seed * 11) % 42
+ for (let dir = 0; dir < 2; dir++) {
+ const a = new Uint8Array(base)
+ const b = new Uint8Array(base)
+ const o = 16 * stride + 16
+ const across = dir === 0 ? 1 : stride
+ const along = dir === 0 ? stride : 1
+ filterLuma(a, o, across, along, 16, bs, ia, ib)
+ filterLuma16(b, o, across, along, bs, ia, ib)
+ for (let i = 0; i < a.length; i++) {
+ if (a[i]! !== b[i]!) bad++
+ }
+ const cu = new Uint8Array(base)
+ const cv = new Uint8Array(other)
+ const du = new Uint8Array(base)
+ const dv = new Uint8Array(other)
+ filterChroma(cu, o, across, along, 8, bs, ia, ib)
+ filterChroma(cv, o, across, along, 8, bs, ia, ib)
+ filterChromaUV(du, dv, o, across, along, bs, ia, ib)
+ for (let i = 0; i < cu.length; i++) {
+ if (cu[i]! !== du[i]!) bad++
+ if (cv[i]! !== dv[i]!) bad++
+ }
+ }
+ }
+ expect(bad).toBe(0)
+})
+
+test("per-segment vector deblocking equals the scalar filters segment by segment", () => {
+ let bad = 0
+ const stride = 48
+ for (let seed = 1; seed <= 160; seed++) {
+ const base = noisePlane(seed, stride * 48, seed % 3 !== 0)
+ const other = noisePlane(seed + 2000, stride * 48, seed % 4 !== 0)
+ const coded = 1 + seed % 14
+ const motion = (seed >> 2) & 1
+ const ia = 10 + (seed * 13) % 42
+ const ib = 10 + (seed * 5) % 42
+ for (let dir = 0; dir < 2; dir++) {
+ const o = 16 * stride + 16
+ const across = dir === 0 ? 1 : stride
+ const along = dir === 0 ? stride : 1
+ const a = new Uint8Array(base)
+ const b = new Uint8Array(base)
+ const cu = new Uint8Array(base)
+ const cv = new Uint8Array(other)
+ for (let k = 0; k < 4; k++) {
+ const bs = ((coded >> k) & 1) !== 0 ? 2 : motion
+ if (bs === 0) continue
+ filterLuma(a, o + k * 4 * along, across, along, 4, bs, ia, ib)
+ filterChroma(cu, o + k * 2 * along, across, along, 2, bs, ia, ib)
+ filterChroma(cv, o + k * 2 * along, across, along, 2, bs, ia, ib)
+ }
+ filterLumaSegments(b, o, across, along, coded, motion, ia, ib)
+ const du = new Uint8Array(base)
+ const dv = new Uint8Array(other)
+ filterChromaSegments(du, dv, o, across, along, coded, motion, ia, ib)
+ for (let i = 0; i < a.length; i++) {
+ if (a[i]! !== b[i]!) bad++
+ if (cu[i]! !== du[i]!) bad++
+ if (cv[i]! !== dv[i]!) bad++
+ }
+ }
+ }
+ expect(bad).toBe(0)
+})
+
+test("a strong edge across a flat area is smoothed at bS 4", () => {
+ const px = new Uint8Array(8)
+ for (let i = 0; i < 8; i++) px[i] = i < 4 ? 100 : 104
+ filterLuma(px, 4, 1, 0, 1, 4, 40, 40)
+ expect(px[3]! > 100).toBe(true)
+ expect(px[4]! < 104).toBe(true)
+})
diff --git a/capcodec/src/encoder.tov b/capcodec/src/encoder.tov
new file mode 100644
index 000000000..771f3c99d
--- /dev/null
+++ b/capcodec/src/encoder.tov
@@ -0,0 +1,6620 @@
+import { availableParallelism } from "node:os"
+import { RC_CQP, RC_VBR, RateControl } from "./ratecontrol"
+import {
+ AQ_TEXT, AQ_TEXTURE, SideInfo, changeMap, classifyMb, copyBytes, copyRect, diffMb, estimateScroll, estimateShift, fillBytes,
+ markRects, matchScroll, mbActivity, mbChange, rowHashes, scrollSpan, weightFit,
+} from "./analysis"
+import { BitWriter, appendNal, appendNalBytes, seBits, ueBits } from "./bitwriter"
+import { CAT_CHROMA_AC, CAT_CHROMA_DC, CAT_LUMA_4x4, CAT_LUMA_8x8, CAT_LUMA_AC, CAT_LUMA_DC, Cabac } from "./cabac"
+import { writeResidual } from "./cavlc"
+import { filterChromaSegments, filterChromaUV, filterLuma16, filterLumaSegments } from "./deblock"
+import { SLICE_B, SLICE_I, SLICE_P, SliceParams, StreamParams, chooseLevel, writePps, writeSliceHeader, writeSps } from "./headers"
+import { avgPlanes, computeHalfTile, median3, predictChroma, qpelPlanes, weightedAvgPlanes } from "./inter"
+import {
+ AV_LEFT, AV_TL, AV_TOP, AV_TR, C_PLANE, I16_DC, I16_PLANE, I4_DC, I4_DDL, I4_H, I4_V, chromaModeAvailable, mode16Available,
+ modeMask,
+} from "./intra"
+import {
+ I4_BEST_COST, I4_BEST_MODE, T8_SIZE, UV_SIZE, blocks4, chromaPlaneSatd, chromaSatd, edge4m, edge8m,
+ i16PlaneSatd, i16Satd, i4Costs, i8Cost, i8Cost2, i8SrcCosts, pred16v, pred4v, pred8v, predChromaUv, predChromaV,
+ unblocks4, unblocks8,
+} from "./ipred"
+import { KEEP_ONE, LIFE_ONE, Lookahead } from "./lookahead"
+import { copyPadded } from "./pixel"
+import {
+ chromaAcZero, code4, copy16, copy8, dequant4v, dequant8v, dequantChromaDcv, dequantLumaDcv, fwd4, fwd4x2, fwd8, hadamard2v,
+ hadamard4v, idct4v, idct8v, idctC8, nonzeroMask, quant4v, quant8v, quantDcv, recon16, recon4, recon8, recon8b, reconDc16,
+ reconDcC8, zigzag4, zigzag8, zigzagAc4,
+} from "./tq"
+import { sa8dPair, sad16, sadAvg16, satd16, satdAvg16 } from "./satd"
+import { CBP_CODE_INTER, CBP_CODE_INTRA, CHROMA_QP, QUANT4, ZIGZAG4, ZIGZAG8 } from "./tables"
+
+export type EncoderOptions = {
+ width: int,
+ height: int,
+ fpsNum: int,
+ fpsDen: int,
+ qp: int,
+ keyint: int,
+ profile: int,
+ preset: string,
+ cabac: bool,
+ refs: int,
+ rcMode: int,
+ crf: f64,
+ bitrate: int,
+ maxrate: int,
+ bufsize: int,
+ ipOffset: int,
+ weightedPred: bool,
+ worker: bool,
+}
+
+export type SharedState = {
+ srcY: Uint8Array, srcU: Uint8Array, srcV: Uint8Array,
+ curY: Uint8Array, curU: Uint8Array, curV: Uint8Array,
+ refY: Uint8Array[], refU: Uint8Array[], refV: Uint8Array[],
+ refHb: Uint8Array[], refHh: Uint8Array[], refHj: Uint8Array[], refTiles: Int32Array[],
+ wref: Uint8Array, curVer: Int32Array, refVer: Int32Array[], lastChange: Int32Array, streak: Int32Array,
+ changed: Uint8Array, refresh: Uint8Array, mbClass: Uint8Array, mbQp: Int32Array, codedQp: Int32Array,
+ mbType: Int32Array, i16Mode: Int32Array, cMode: Int32Array, imode: Uint8Array, t8: Int32Array, cbp: Int32Array,
+ dcCbf: Int32Array, nnz: Uint8Array, mvx: Int32Array, mvy: Int32Array, refIdx: Int32Array, mvdx: Int32Array,
+ mvdy: Int32Array, prevMvx: Int32Array, prevMvy: Int32Array, pkCoef: Int16Array,
+ pkMask: Uint16Array, pkOff: Int32Array, pkTop: Int32Array, qpY: Int32Array, qpDelta: Int32Array,
+ srcSame: Uint8Array, recSame: Uint8Array, cType: Uint8Array, cI16: Uint8Array, cCMode: Uint8Array, cCbp: Uint8Array,
+ cDcCbf: Uint8Array, cQp: Uint8Array, cImode: Uint8Array, cNnz: Uint8Array, cCoef: Int8Array, cMask: Int64Array,
+ cOff: Int32Array,
+ idrSaved: Int32Array, idrSlotMb: Int32Array, idrPool: Uint8Array, idrTop: Int32Array, idrRecY: Uint8Array, idrRecU: Uint8Array, idrRecV: Uint8Array,
+ mvx1: Int32Array, mvy1: Int32Array, refIdx1: Int32Array, mvdx1: Int32Array, mvdy1: Int32Array, colMvx: Int32Array,
+ colMvy: Int32Array, colRef: Int32Array,
+}
+
+type BSlot = {
+ mbType: Int32Array, i16Mode: Int32Array, cMode: Int32Array, imode: Uint8Array, t8: Int32Array, cbp: Int32Array,
+ dcCbf: Int32Array, nnz: Uint8Array, mvx: Int32Array, mvy: Int32Array, refIdx: Int32Array, mvdx: Int32Array,
+ mvdy: Int32Array, pkCoef: Int16Array, pkMask: Uint16Array, pkOff: Int32Array, pkTop: Int32Array, qpY: Int32Array,
+ qpDelta: Int32Array, mvx1: Int32Array, mvy1: Int32Array, refIdx1: Int32Array, mvdx1: Int32Array, mvdy1: Int32Array,
+}
+
+type BMid = {
+ mid: int, gate: Int32Array, tileCnt: Int32Array, lazy: bool, oneSlot: bool, colMvx: Int32Array, colMvy: Int32Array,
+ colRef: Int32Array, y: Uint8Array, hb: Uint8Array, hh: Uint8Array, hj: Uint8Array, tileGen: Int32Array, gen: int,
+}
+
+export type FrameParams = {
+ sliceType: int, refsActive: int, refGen: int[], wpOn: bool, wpChromaOn: bool, wpY: int[], wpU: int[], wpV: int[],
+ shiftHx: int, shiftVy: int, scrollMvx: int, scrollMvy: int, scrollMb0: int, scrollMb1: int, cursorMvx: int,
+ cursorMvy: int, cursorMb: int, idrCache: bool, idrReuse: bool, frameNum: int, idrPicId: int, frameQp: int,
+ deblock: bool, filterRecon: bool, counter: int, bTb: int, bTd: int, bTdCol: int, pocBase: int, frameIndex: int,
+ params: StreamParams, refreshDelta: int, lifetimeAq: bool, lastAnalysed: int, textMbs: int, laLife: Int32Array,
+ laOn: bool, laHz: int, laStrength: f64, nalRef: bool, l0Reorder: int[], mmco: int[],
+}
+
+export type IntraJob = {
+ seq: int, slot: int, buf: Uint8Array, qp: Int32Array, frameQp: int, idrPicId: int, frameIndex: int, pocBase: int,
+ recon: bool, analysis: f64,
+}
+
+export type IntraCoded = {
+ seq: int, slot: int, frameIndex: int, frameQp: int, bits: u8[], recon: Uint8Array, analysis: f64, mode: f64,
+ tq: f64, entropy: f64, deblock: f64, total: f64,
+}
+
+export type FrameStats = {
+ index: int,
+ type: string,
+ bytes: int,
+ qp: int,
+ changedMbs: int,
+ analysis: f64,
+ motion: f64,
+ mode: f64,
+ tq: f64,
+ entropy: f64,
+ deblock: f64,
+ total: f64,
+ reused: int,
+}
+
+export class RefFrame {
+ y: Uint8Array = new Uint8Array(0)
+ u: Uint8Array = new Uint8Array(0)
+ v: Uint8Array = new Uint8Array(0)
+ ver: Int32Array = new Int32Array(0)
+ hb: Uint8Array = new Uint8Array(0)
+ hh: Uint8Array = new Uint8Array(0)
+ hj: Uint8Array = new Uint8Array(0)
+ tileGen: Int32Array = new Int32Array(0)
+ gen = 0
+ frameNum = 0
+ id = 0
+}
+
+export const MB_I16 = 1
+export const MB_I4 = 2
+export const MB_I8 = 3
+export const MB_P16 = 4
+export const MB_PSKIP = 5
+export const MB_BSKIP = 6
+export const MB_BDIRECT = 7
+export const MB_BL0 = 8
+export const MB_BL1 = 9
+export const MB_BBI = 10
+
+export class Pending {
+ data: Uint8Array
+ index: int
+ off = 0
+ life: Int32Array = new Int32Array(0)
+ keep: Uint8Array = new Uint8Array(0)
+ constructor(data: Uint8Array, index: int) {
+ this.data = data
+ this.index = index
+ }
+}
+
+// clampMvx/clampMvy keep luma reads within 29 pixels of the picture, so 32 pixels of padding suffice; the half-pel
+// tiles of the outermost ring read 2 rows above and 3 rows plus 3 bytes below the padded plane (TILE_GUARD rows).
+const PADY = 32
+const TILE_GUARD = 4
+const MVPAD = 32
+const PADC = 16
+const ROW_SLOT = 16
+// Spin budgets are times, not pause counts: a pause takes tens of nanoseconds on x86 and next to nothing on
+// Apple silicon (`yield`). Each thread adapts its own budget between the two bounds (waitRow).
+const SPIN_MIN_MS = 0.003
+const SPIN_MAX_MS = 0.05
+const SLEEP_MAX_MS = 8
+const TILE_BUSY = -2
+const WP_FIT = 8
+const SCAN_WEIGHTS = 0
+const SCAN_SHIFT_H = 1
+const SCAN_SHIFT_V = 2
+const SCAN_HASH = 3
+const HASH_ROWS = 128
+const PLAN_N = 0
+const PLAN_MINX = 1
+const PLAN_MAXX = 2
+const PLAN_MINY = 3
+const PLAN_MAXY = 4
+const PLAN_X0 = 5
+const PLAN_Y0 = 6
+const PLAN_WW = 7
+const PLAN_HH = 8
+const PLAN_YLO = 9
+const PLAN_PREV = 10
+const PLAN_CUR = 11
+const PLAN_SPAN = 12
+const PLAN_SHIFT = 13
+const PLAN_DY = 14
+const PLAN_JOBS = 15
+const PLAN_JOB0 = 16
+const PEEK_PREPPED = 0
+const PEEK_PHASE = 1
+const PEEK_NEXT = 2
+const ENTROPY_THREAD_MIN = 4
+const ENTROPY_BATCH = 8
+const BLK_RASTER: int[] = [0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15]
+const DIR_DX: int[] = [-1, 1, 0, 0, -1, 1, -1, 1]
+const DIR_DY: int[] = [0, 0, -1, 1, -1, -1, 1, 1]
+const COEF_PER_MB = 416
+const PK_BLOCK = 8192
+const DC_OFF = 256
+const CHROMA_DC_OFF = 272
+const CHROMA_AC_OFF = 280
+const LAMBDA: int[] = [
+ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 6, 6, 7, 8, 9, 10, 11, 13, 14,
+ 16, 18, 20, 23, 25, 29, 32, 36, 40, 45, 51, 57, 64, 72, 81, 91,
+]
+const BIG = 1 << 40
+const B_DIRECT_EARLY = 96
+const I8_DIR_MODES = 0x1f8
+const B_DIRECT_NB = 112
+const B_DIRECT_NB_PYRAMID = 128
+const B_SKIP_SAD = 16
+const B_GATE_QP = 30
+
+function zeroSadMax(qm: int, thr: int, k0: int): int {
+ let w = 0
+ for (let k = k0; k < 16; k++) {
+ const v = ((k & 4) !== 0 ? 2 : 1) * ((k & 1) !== 0 ? 2 : 1) * int(QUANT4[qm + k]!)
+ if (v > w) w = v
+ }
+ return Math.trunc((thr - 1) / w)
+}
+
+function sadBlocks16(a: Uint8Array, ao: int, as: int, b: Uint8Array, bo: int, bs: int, out: Int32Array) {
+ let lo = i16x8.splat(0)
+ let hi = i16x8.splat(0)
+ for (let y = 0; y < 4; y++) {
+ const d = u8x16.load(a, ao + y * as).absDiff(u8x16.load(b, bo + y * bs))
+ lo = lo + d.widenLow()
+ hi = hi + d.widenHigh()
+ }
+ const one = i16x8.splat(1)
+ const l = i16x8.madd(lo, one)
+ const h = i16x8.madd(hi, one)
+ out[0] = l.lane(0) + l.lane(1)
+ out[1] = l.lane(2) + l.lane(3)
+ out[2] = h.lane(0) + h.lane(1)
+ out[3] = h.lane(2) + h.lane(3)
+}
+
+function sadBlocks8(a: Uint8Array, ao: int, as: int, b: Uint8Array, bo: int, out: Int32Array) {
+ const one = i16x8.splat(1)
+ for (let h = 0; h < 2; h++) {
+ let acc = i16x8.splat(0)
+ for (let y = 0; y < 4; y++) {
+ const r = h * 4 + y
+ acc = acc + (i16x8.loadU8(a, ao + r * as) - i16x8.loadU8(b, bo + r * 8)).abs()
+ }
+ const s = i16x8.madd(acc, one)
+ out[h * 2] = s.lane(0) + s.lane(1)
+ out[h * 2 + 1] = s.lane(2) + s.lane(3)
+ }
+}
+const I8_DIR_LANES = i32x8(3, 4, 5, 6, 7, 8, 9, 10)
+const I8_DIR_BITS = i32x8(8, 16, 32, 64, 128, 256, 0, 0)
+
+function blockAvail(bx: int, by: int, mbAv: int, n: int): int {
+ let av = 0
+ const top = by > 0 || (mbAv & AV_TOP) !== 0
+ const left = bx > 0 || (mbAv & AV_LEFT) !== 0
+ if (top) av |= AV_TOP
+ if (left) av |= AV_LEFT
+ if (bx > 0 && by > 0) {
+ av |= AV_TL
+ } else if (bx > 0) {
+ if ((mbAv & AV_TOP) !== 0) av |= AV_TL
+ } else if (by > 0) {
+ if ((mbAv & AV_LEFT) !== 0) av |= AV_TL
+ } else if ((mbAv & AV_TL) !== 0) {
+ av |= AV_TL
+ }
+ const last = n === 4 ? 3 : 1
+ if (by === 0) {
+ if (bx < last) {
+ if ((mbAv & AV_TOP) !== 0) av |= AV_TR
+ } else if ((mbAv & AV_TR) !== 0) {
+ av |= AV_TR
+ }
+ } else if (bx < last) {
+ if (n === 4) {
+ if (zIndex4(bx + 1, by - 1) < zIndex4(bx, by)) av |= AV_TR
+ } else if (bx === 0 && by === 1) {
+ av |= AV_TR
+ }
+ }
+ return av
+}
+
+function blockAvailTable(): Uint8Array {
+ const t = new Uint8Array(320)
+ for (let av = 0; av < 16; av++) {
+ for (let r = 0; r < 16; r++) t[av * 16 + r] = blockAvail(r & 3, r >> 2, av, 4)
+ for (let b = 0; b < 4; b++) t[256 + av * 4 + b] = blockAvail(b & 1, b >> 1, av, 8)
+ }
+ return t
+}
+
+function zIndex4(bx: int, by: int): int {
+ return ((by >> 1) * 2 + (bx >> 1)) * 4 + (by & 1) * 2 + (bx & 1)
+}
+
+const DECIMATE4: int[] = [3, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
+const DECIMATE8: int[] = [
+ 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+]
+
+const CBP_BLOCKS: int[] = [
+ 0x0000, 0x0033, 0x00cc, 0x00ff, 0x3300, 0x3333, 0x33cc, 0x33ff, 0xcc00, 0xcc33, 0xcccc, 0xccff, 0xff00, 0xff33, 0xffcc, 0xffff,
+]
+
+function transposeBlocks(m: int): int {
+ const a = (m ^ (m >> 3)) & 0x0a0a
+ const b = m ^ a ^ (a << 3)
+ const c = (b ^ (b >> 6)) & 0x00cc
+ return b ^ c ^ (c << 6)
+}
+
+function decimateScore(c: Int16Array, o: int, n: int, is8: bool): int {
+ let m = nonzeroMask(c, o, n)
+ let score = 0
+ while (m !== 0) {
+ const i = 63 - Math.clz64(m)
+ const v = c[o + i]!
+ if (v > 1 || v < -1) return 9
+ m ^= 1 << i
+ const run = i - 64 + Math.clz64(m)
+ score += is8 ? DECIMATE8[run]! : DECIMATE4[run]!
+ }
+ return score
+}
+
+function coefChunks(t: int, cbp: int, t8: int): int {
+ const cbpL = cbp & 15
+ const cbpC = cbp >> 4
+ let m = 0
+ if (t === MB_I16) {
+ m = cbpL !== 0 ? 0x1ff : 0x100
+ } else if (t8 === 1) {
+ const s = (cbpL & 1) | (cbpL & 2) << 1 | (cbpL & 4) << 2 | (cbpL & 8) << 3
+ m = s | s << 1
+ } else {
+ const q = (cbpL & 3) | (cbpL & 12) << 2
+ m = q | q << 2
+ }
+ if (cbpC !== 0) m |= cbpC === 2 ? 0x1f00 : 0x100
+ return m
+}
+
+function chunkTable(): Uint16Array {
+ const tab = new Uint16Array(192)
+ for (let cbp = 0; cbp < 64; cbp++) {
+ tab[cbp] = coefChunks(MB_P16, cbp, 0)
+ tab[64 + cbp] = coefChunks(MB_P16, cbp, 1)
+ tab[128 + cbp] = coefChunks(MB_I16, cbp, 0)
+ }
+ return tab
+}
+
+const CHUNKS = chunkTable()
+
+function iabs(v: int): int {
+ return v < 0 ? -v : v
+}
+
+function progressArray(n: int): Int32Array {
+ return new Int32Array(n * ROW_SLOT)
+}
+
+function publish(a: Int32Array, i: int, v: int) {
+ const at = i * ROW_SLOT
+ Atomics.store(a, at, v)
+ if (Atomics.load(a, at + 1) > 0) Atomics.notify(a, at)
+}
+
+function publishRows(a: Int32Array, v: int) {
+ Atomics.store(a, 0, v)
+ if (Atomics.load(a, 1) > 0 && v >= Atomics.load(a, 2)) Atomics.notify(a, 0)
+}
+
+function bump(a: Int32Array, i: int) {
+ const at = i * ROW_SLOT
+ Atomics.add(a, at, 1)
+ if (Atomics.load(a, at + 1) > 0) Atomics.notify(a, at)
+}
+
+function copyRow16(dst: Uint8Array, d: int, ds: int, src: Uint8Array, so: int, ss: int) {
+ for (let y = 0; y < 16; y++) u8x16.load(src, so + y * ss).store(dst, d + y * ds)
+}
+
+function weightBlock(p: Uint8Array, o: int, stride: int, w: int, h: int, wt: int, off: int) {
+ if (w === 16) {
+ const wv = i16x8.splat(wt)
+ const ov = i16x8.splat(off)
+ const r = i16x8.splat(32)
+ for (let y = 0; y < h; y++) {
+ const v = u8x16.load(p, o + y * stride)
+ const lo = ((v.widenLow() * wv + r) >> 6) + ov
+ const hi = ((v.widenHigh() * wv + r) >> 6) + ov
+ u8x16.packSat(lo, hi).store(p, o + y * stride)
+ }
+ return
+ }
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) {
+ const v = ((int(p[o + y * stride + x]!) * wt + 32) >> 6) + off
+ const c = v < 0 ? 0 : v > 255 ? 255 : v
+ p[o + y * stride + x] = c
+ }
+ }
+}
+
+type FrameScan = {
+ frame: Uint8Array, frameOff: int, w: int, h: int, src: Uint8Array, aw: int, x0: int, y0: int, ww: int, hh: int,
+ ylo: int, prevHashes: Uint32Array, curHashes: Uint32Array, shifts: Int32Array, refY: Uint8Array, refU: Uint8Array,
+ refV: Uint8Array, yorg: int, ys: int, corg: int, cs: int, wpFit: Int32Array,
+}
+
+function runScanJob(s: FrameScan, job: int) {
+ if (job === SCAN_WEIGHTS) {
+ weightFit(s.frame, s.frameOff, s.w, s.h, s.refY, s.refU, s.refV, s.yorg, s.ys, s.corg, s.cs, s.wpFit)
+ } else if (job === SCAN_SHIFT_H || job === SCAN_SHIFT_V) {
+ const horizontal = job === SCAN_SHIFT_H
+ s.shifts[job - SCAN_SHIFT_H] = estimateShift(s.frame, s.w, s.frameOff, s.src, s.aw, 0, s.x0, s.y0, s.ww, s.hh, s.w,
+ s.h, horizontal, horizontal ? 512 : 256)
+ } else {
+ const k = job - SCAN_HASH
+ const r = k >> 1
+ if ((k & 1) === 0) {
+ const n = s.prevHashes.length - r < HASH_ROWS ? s.prevHashes.length - r : HASH_ROWS
+ rowHashes(s.prevHashes, r, s.src, (s.ylo + r) * s.aw + s.x0, s.aw, s.ww, n)
+ } else {
+ const n = s.hh - r < HASH_ROWS ? s.hh - r : HASH_ROWS
+ rowHashes(s.curHashes, r, s.frame, s.frameOff + (s.y0 + r) * s.w + s.x0, s.w, s.ww, n)
+ }
+ }
+}
+
+function scanJobs(s: FrameScan, plan: Int32Array, next: Int32Array, jobs: int) {
+ while (true) {
+ const j = Atomics.add(next, 0, 1)
+ if (j >= jobs) return
+ runScanJob(s, plan[PLAN_JOB0 + j]!)
+ if (Atomics.add(next, 1, 1) === jobs - 1) Atomics.notify(next, 1)
+ }
+}
+
+function scanDone(s: FrameScan, plan: Int32Array) {
+ plan[PLAN_DY] = plan[PLAN_SPAN]! === 1 ? matchScroll(s.prevHashes, s.ylo, s.curHashes, s.y0) : 0
+}
+
+type Peek = {
+ frame: Uint8Array, frameOff: int, ready: Int32Array, sync: Int32Array, changed: Uint8Array, plan: Int32Array,
+ prev: Uint32Array, cur: Uint32Array, shifts: Int32Array,
+}
+
+function minPositive(a: int, b: int): int {
+ return a >= 0 && b >= 0 ? (a < b ? a : b) : (a > b ? a : b)
+}
+
+function newPlane(n: int): Uint8Array {
+ return new Uint8Array(n)
+}
+
+function bWorker(opts: EncoderOptions, sh: SharedState, fp: FrameParams, tuning: int[], tilesReady: bool): Encoder {
+ const w = new Encoder(opts)
+ w.attach(sh, fp)
+ w.tune(tuning)
+ w.tilesReady = tilesReady
+ w.sharedTiles = false
+ return w
+}
+
+function pickBFrame(next: Int32Array, n: int, mbh: int, only: int): int {
+ let k = -1
+ let most = 0
+ for (let i = 0; i < n; i++) {
+ if (only >= 0 && i !== only) continue
+ const left = mbh - Atomics.load(next, i)
+ if (left > most) {
+ most = left
+ k = i
+ }
+ }
+ return k
+}
+
+function padRef(w: Encoder, bm: BMid) {
+ for (let y = 0; y < w.mbh; y++) {
+ for (let x = 0; x < w.mbw; x++) w.padMb(x, y)
+ }
+ publish(bm.gate, 0, bm.lazy ? 2 : 1)
+}
+
+function helpTiles(w: Encoder, bm: BMid) {
+ const rows = w.tilesY
+ while (true) {
+ const r = Atomics.add(bm.tileCnt, 0, 1)
+ if (r >= rows) return
+ w.halfTileRow(bm.y, bm.hb, bm.hh, bm.hj, bm.tileGen, bm.gen, r)
+ if (Atomics.add(bm.tileCnt, 1, 1) + 1 === rows) publish(bm.gate, 0, 2)
+ }
+}
+
+function codeBRun(ws: Encoder[], next: Int32Array, done: Int32Array, progress: Int32Array[], stats: Float64Array,
+ slot: int, bm: BMid): u8[][] {
+ const n = ws.length
+ const mbh = ws[0]!.mbh
+ let parts: u8[][] = []
+ for (let i = 0; i < n; i++) parts.push([])
+ let k = bm.mid >= 0 ? bm.mid : slot % n
+ while (true) {
+ if (k < 0 || Atomics.load(next, k) >= mbh) {
+ const st = bm.mid < 0 ? 2 : Atomics.load(bm.gate, 0)
+ k = pickBFrame(next, n, mbh, st >= 2 ? -1 : bm.mid)
+ if (k < 0) {
+ if (st >= 2) break
+ if (st === 1) {
+ const h0 = performance.now()
+ helpTiles(ws[bm.mid]!, bm)
+ const om = (slot * n + bm.mid) * 5
+ stats[om + 4] = stats[om + 4]! + performance.now() - h0
+ }
+ ws[0]!.waitRow(bm.gate, 0, st + 1)
+ continue
+ }
+ }
+ const r = Atomics.add(next, k, 1)
+ if (r >= mbh) continue
+ const w = ws[k]!
+ w.codeRowWave(r, false, mbh, progress[k]!)
+ if (Atomics.add(done, k, 1) + 1 < mbh) continue
+ const e0 = performance.now()
+ w.finishQpRows(mbh, 0, mbh)
+ if (k === bm.mid) {
+ w.storeCol(bm.colMvx, bm.colMvy, bm.colRef)
+ padRef(w, bm)
+ }
+ let out: u8[] = []
+ w.entropyRows(false, mbh, 0, mbh, &out)
+ if (bm.oneSlot) w.pkTop[0] = 0
+ parts[k] = out
+ stats[(slot * n + k) * 5 + 3] = performance.now() - e0
+ }
+ for (let i = 0; i < n; i++) {
+ const o = (slot * n + i) * 5
+ stats[o] = ws[i]!.rMo
+ stats[o + 1] = ws[i]!.rMd
+ stats[o + 2] = ws[i]!.rTq
+ }
+ return parts
+}
+
+export class Encoder {
+ readonly w: int
+ readonly h: int
+ readonly mbw: int
+ readonly mbh: int
+ readonly aw: int
+ readonly ah: int
+ readonly cw: int
+ readonly chh: int
+ readonly ys: int
+ readonly yorg: int
+ readonly ytile: int
+ readonly ysize: int
+ readonly cs: int
+ readonly corg: int
+ params: StreamParams
+ qp: int
+ keyint: int
+ maxRefs: int
+ srcY: Uint8Array = new Uint8Array(0)
+ srcU: Uint8Array = new Uint8Array(0)
+ srcV: Uint8Array = new Uint8Array(0)
+ cur: RefFrame = new RefFrame()
+ refs: RefFrame[] = []
+ spare: RefFrame[] = []
+ genSeq = 0
+ mbType: Int32Array = new Int32Array(0)
+ i16Mode: Int32Array = new Int32Array(0)
+ cMode: Int32Array = new Int32Array(0)
+ imode: Uint8Array = new Uint8Array(0)
+ t8: Int32Array = new Int32Array(0)
+ cbp: Int32Array = new Int32Array(0)
+ dcCbf: Int32Array = new Int32Array(0)
+ nnz: Uint8Array = new Uint8Array(0)
+ mvx: Int32Array = new Int32Array(0)
+ mvy: Int32Array = new Int32Array(0)
+ refIdx: Int32Array = new Int32Array(0)
+ mvdx: Int32Array = new Int32Array(0)
+ mvdy: Int32Array = new Int32Array(0)
+ prevMvx: Int32Array = new Int32Array(0)
+ prevMvy: Int32Array = new Int32Array(0)
+ coef: Int16Array = new Int16Array(COEF_PER_MB)
+ pkCoef: Int16Array = new Int16Array(0)
+ pkMask: Uint16Array = new Uint16Array(0)
+ pkOff: Int32Array = new Int32Array(0)
+ pkTop: Int32Array = new Int32Array(1)
+ pkW = 0
+ pkEnd = 0
+ blk16: Int16Array = new Int16Array(16)
+ pred: Uint8Array = new Uint8Array(0)
+ trial: Uint8Array = new Uint8Array(0)
+ xb: Uint8Array = new Uint8Array(16)
+ p4: Uint8Array = new Uint8Array(144)
+ ip8: Uint8Array = new Uint8Array(T8_SIZE)
+ srcBlk: Uint8Array = new Uint8Array(256)
+ edgeBlk: Uint8Array = new Uint8Array(256)
+ uvBlk: Uint8Array = new Uint8Array(UV_SIZE)
+ uvPlane: Int16Array = new Int16Array(32)
+ uvMb = -1
+ cost9: Int32Array = new Int32Array(16)
+ g4: Int32Array = new Int32Array(25)
+ blkAv: Uint8Array = blockAvailTable()
+ modes4: int[] = []
+ modes8: int[] = []
+ coded4 = -1
+ coded8 = -1
+ cbp4 = 0
+ cbp8 = 0
+ rec4: Uint8Array = new Uint8Array(256)
+ rec8: Uint8Array = new Uint8Array(256)
+ lv8: Int32Array = new Int32Array(256)
+ nz8: Int32Array = new Int32Array(4)
+ tilesX = 0
+ tilesY = 0
+ bw: BitWriter = new BitWriter()
+ cabac: Cabac
+ out: u8[] = []
+ frameNum = 0
+ idrPicId = 0
+ frameIndex = 0
+ codedFrames = 0
+ sinceIdr = 0
+ skipRun = 0
+ sliceType = SLICE_I
+ refsActive = 1
+ meCost = 0
+ intraEst = 0
+ earlyExit = true
+ predReady = false
+ mvpX = 0
+ mvpY = 0
+ skipX = 0
+ skipY = 0
+ best16 = I16_DC
+ bestC = 0
+ intraType = MB_I16
+ tAnalysis = 0.0
+ tMotion = 0.0
+ tMode = 0.0
+ tTq = 0.0
+ tEntropy = 0.0
+ tDeblock = 0.0
+ frames: FrameStats[] = []
+ changed: Uint8Array = new Uint8Array(0)
+ held: Uint8Array = new Uint8Array(0)
+ heldAt = -1
+ changeCodes: Uint8Array = new Uint8Array(0)
+ laChanges: Uint8Array = new Uint8Array(0)
+ laChangesAt = -1
+ laChangesNoise = -1
+ prevChanged: Uint8Array = new Uint8Array(0)
+ refresh: Uint8Array = new Uint8Array(0)
+ mbClass: Uint8Array = new Uint8Array(0)
+ mbQp: Int32Array = new Int32Array(0)
+ codedQp: Int32Array = new Int32Array(0)
+ qpY: Int32Array = new Int32Array(0)
+ qpDelta: Int32Array = new Int32Array(0)
+ mbq = 26
+ qpPred = 26
+ lastDeltaNz = false
+ aqStrength = 1
+ aqTexture = 0
+ noise = 0
+ refreshDelta = 3
+ lifetimeAq = true
+ frameQp = 26
+ lastChange: Int32Array = new Int32Array(0)
+ streak: Int32Array = new Int32Array(0)
+ lastAnalysed = -1
+ lastCodedIndex = -1
+ lastActive = -1
+ refineGain = 6
+ rate: RateControl
+ rcAct = false
+ fpsF: f64
+ counter = 0
+ vfr = true
+ fullAnalysis = false
+ deblock = true
+ scrollMvx = 0
+ scrollMvy = 0
+ scrollMb0 = -1
+ scrollMb1 = -1
+ cursorMvx = 0
+ cursorMvy = 0
+ cursorMb = -1
+ shiftHx = 0
+ shiftVy = 0
+ globalShift = true
+ prevCursorX = -1
+ prevCursorY = -1
+ useI8: bool
+ useI4: bool
+ inter8x8 = true
+ decimate = true
+ subpel: int
+ subpelDirs: int
+ videoHpelDirs = 8
+ videoQpelDirs = 8
+ meIters: int
+ earlySkip = false
+ i8PredOnly = false
+ hpelSad = false
+ qpelSad = false
+ textMbs = 0
+ classReady = false
+ skipProbed = false
+ seen: Int32Array = new Int32Array(64 * 64)
+ seenGen = 0
+ seenX = 0
+ seenY = 0
+ idrReuse = true
+ idrCache = false
+ idrSaved: Int32Array = new Int32Array(0)
+ idrSlotMb: Int32Array = new Int32Array(0)
+ idrPool: Uint8Array = new Uint8Array(0)
+ idrTop: Int32Array = new Int32Array(1)
+ idrRecY: Uint8Array = new Uint8Array(0)
+ idrRecU: Uint8Array = new Uint8Array(0)
+ idrRecV: Uint8Array = new Uint8Array(0)
+ cType: Uint8Array = new Uint8Array(0)
+ cI16: Uint8Array = new Uint8Array(0)
+ cCMode: Uint8Array = new Uint8Array(0)
+ cCbp: Uint8Array = new Uint8Array(0)
+ cDcCbf: Uint8Array = new Uint8Array(0)
+ cQp: Uint8Array = new Uint8Array(0)
+ cImode: Uint8Array = new Uint8Array(0)
+ cNnz: Uint8Array = new Uint8Array(0)
+ cCoef: Int8Array = new Int8Array(0)
+ cMask: Int64Array = new Int64Array(0)
+ cOff: Int32Array = new Int32Array(0)
+ cRow = 0
+ rowOld: Int8Array = new Int8Array(0)
+ rowAt = 0
+ srcSame: Uint8Array = new Uint8Array(0)
+ recSame: Uint8Array = new Uint8Array(0)
+ reusedMbs = 0
+ threads = 1
+ opts: EncoderOptions
+ sharedTiles = false
+ tilesReady = false
+ bframes = 0
+ dpbRefs = 1
+ pending: Pending[] = []
+ mvx1: Int32Array = new Int32Array(0)
+ mvy1: Int32Array = new Int32Array(0)
+ refIdx1: Int32Array = new Int32Array(0)
+ mvdx1: Int32Array = new Int32Array(0)
+ mvdy1: Int32Array = new Int32Array(0)
+ colMvx: Int32Array = new Int32Array(0)
+ colMvy: Int32Array = new Int32Array(0)
+ colRef: Int32Array = new Int32Array(0)
+ bSlots: BSlot[] = []
+ bTargets: RefFrame[] = []
+ bThreads: Thread<u8[][]>[] = []
+ bInline: u8[][][] = []
+ bRunIdx: int[] = []
+ bRunData: Uint8Array[] = []
+ bRunRecon: RefFrame[] = []
+ bRunStats: Float64Array = new Float64Array(0)
+ bRunQps: int[] = []
+ bRunAnchorQp = 26
+ bRunAnalysis = 0.0
+ bRunT1 = 0.0
+ inputPool: Uint8Array[] = []
+ bMbQp: Int32Array = new Int32Array(0)
+ bChanged: Uint8Array = new Uint8Array(0)
+ bRefresh: Uint8Array = new Uint8Array(0)
+ predB: Uint8Array = new Uint8Array(384)
+ predBi: Uint8Array = new Uint8Array(384)
+ zsad: Int32Array = new Int32Array(4)
+ wantRecon = false
+ filterRecon = true
+ frameThreads = true
+ srcRing: Uint8Array[] = []
+ ringBusy: Uint8Array = new Uint8Array(0)
+ srcSlot = -1
+ intraWork: Channel<IntraJob> | undefined = undefined
+ intraDone: Channel<IntraCoded> | undefined = undefined
+ intraPool: Thread<void>[] = []
+ intraHeld: IntraCoded[] = []
+ intraSent = 0
+ intraEmitted = 0
+ reconHeld: Pending[] = []
+ reconReady: Uint8Array[] = []
+ nextRecon = 0
+ pocBase = 0
+ inputIndex = 0
+ anchorQp = 26
+ bQpOffset = 6
+ bRefQpOffset = 5
+ bDirectNb = B_DIRECT_NB
+ bAdapt = true
+ pyramid = false
+ nalRef = false
+ l0Reorder: int[] = []
+ mmco: int[] = []
+ bRefNum = -1
+ bRefFrame: RefFrame = new RefFrame()
+ bColMvx: Int32Array = new Int32Array(0)
+ bColMvy: Int32Array = new Int32Array(0)
+ bColRef: Int32Array = new Int32Array(0)
+ bMbQpRef: Int32Array = new Int32Array(0)
+ bRunOrder: int[] = []
+ bRunMid = -1
+ bReady = false
+ dirtyScratch: Uint8Array = new Uint8Array(0)
+ dRef0 = 0
+ dRef1 = 0
+ dMx0 = 0
+ dMy0 = 0
+ dMx1 = 0
+ dMy1 = 0
+ sMx = 0
+ sMy = 0
+ sCost = 0
+ sSad = false
+ bTb = 1
+ bTd = 2
+ bTdCol = 2
+ lastAnchorIndex = 0
+ prevAnchorIndex = 0
+ rMo = 0.0
+ rMd = 0.0
+ rTq = 0.0
+ rEnt = 0.0
+ rDb = 0.0
+ rPrep = 0.0
+ rUn = 0.0
+ tN = 0
+ tNs = 0
+ uN = 0
+ uNs = 0
+ pipeMain = false
+ pipeProgress: Int32Array = new Int32Array(0)
+ pipeEnt = 0
+ pipeIdr = false
+ pipeSliceRows = 0
+ qpRows: Int32Array = new Int32Array(0)
+ spinMs = SPIN_MAX_MS
+ spinBudget: Float64Array = new Float64Array(0)
+ weighted = true
+ wpOn = false
+ wpChromaOn = false
+ wpY: int[] = [64, 0]
+ wpU: int[] = [64, 0]
+ wpV: int[] = [64, 0]
+ wref: Uint8Array = new Uint8Array(0)
+ wpFrames = 0
+ wpFit: Int32Array = new Int32Array(WP_FIT)
+ wpScanned = false
+ sliceRow0 = 0
+ lv32: Int32Array = new Int32Array(256)
+ c32: Int32Array = new Int32Array(128)
+ dc32: Int32Array = new Int32Array(16)
+ nz4: int[] = []
+ sliceRowsI = 0
+ idrSlices = 4
+ sliceRowsP = 0
+ nextFrame: Uint8Array = new Uint8Array(0)
+ nextOff = 0
+ nextRead: Int32Array = new Int32Array(0)
+ pkSync: Int32Array = new Int32Array(0)
+ pkChanged: Uint8Array = new Uint8Array(0)
+ pkPlan: Int32Array = new Int32Array(0)
+ pkPrev: Uint32Array = new Uint32Array(0)
+ pkCur: Uint32Array = new Uint32Array(0)
+ pkShifts: Int32Array = new Int32Array(0)
+ pkFit: Int32Array = new Int32Array(WP_FIT)
+ pkWeighed = false
+ peeked = false
+ peekedFrame: Uint8Array = new Uint8Array(0)
+ peekedOff = 0
+ peekedIndex = -1
+ laLife: Int32Array = new Int32Array(0)
+ laNext = false
+ laOn = false
+ laHz = 0
+ laStrength = 1.75
+ laBase = -3.0
+ laMax = 8.0
+ laSpan = 1
+ laL1 = 4.0
+ laKeep: Uint8Array = new Uint8Array(0)
+ flatLife: Int32Array = new Int32Array(0)
+
+ constructor(opts: EncoderOptions) {
+ this.opts = opts
+ this.w = opts.width
+ this.h = opts.height
+ this.mbw = (opts.width + 15) >> 4
+ this.mbh = (opts.height + 15) >> 4
+ this.cRow = this.mbw * COEF_PER_MB * 2 + 16
+ this.aw = this.mbw * 16
+ this.ah = this.mbh * 16
+ this.cw = this.aw >> 1
+ this.chh = this.ah >> 1
+ this.ys = this.aw + 2 * PADY
+ this.ytile = TILE_GUARD * this.ys
+ this.yorg = this.ytile + PADY * this.ys + PADY
+ this.ysize = this.ys * (this.ah + 2 * PADY + 2 * TILE_GUARD)
+ this.cs = this.cw + 2 * PADC
+ this.corg = PADC * this.cs + PADC
+ this.qp = opts.qp
+ this.keyint = opts.keyint
+ this.fpsF = f64(opts.fpsNum) / f64(opts.fpsDen)
+ const twoSeconds = Math.round(2.0 * this.fpsF)
+ this.laSpan = twoSeconds < 1 ? 1 : twoSeconds < this.keyint ? twoSeconds : this.keyint
+ const rcBase = opts.rcMode === RC_CQP ? f64(opts.qp) : opts.crf
+ this.rate = new RateControl(opts.rcMode, rcBase, opts.rcMode === RC_CQP ? 0 : opts.ipOffset, opts.bitrate,
+ opts.maxrate, opts.bufsize, this.fpsF, opts.keyint)
+ this.rcAct = opts.rcMode === RC_VBR && !opts.worker
+ this.useI8 = opts.profile === 100
+ this.useI4 = true
+ this.subpel = 2
+ this.subpelDirs = opts.preset === "live" || opts.preset === "fast" ? 4 : 8
+ this.videoQpelDirs = opts.preset === "live" ? 4 : 8
+ this.earlyExit = opts.preset !== "slow"
+ this.earlySkip = opts.preset !== "slow"
+ this.i8PredOnly = opts.preset === "live"
+ this.hpelSad = opts.preset !== "slow"
+ this.qpelSad = opts.preset === "medium"
+ this.meIters = opts.preset === "live" ? 4 : opts.preset === "fast" ? 8 : 16
+ const fps = f64(opts.fpsNum) / f64(opts.fpsDen)
+ const refs = opts.refs < 1 ? 1 : opts.refs > 4 ? 4 : opts.refs
+ const level = chooseLevel(this.mbw, this.mbh, fps, refs, 0)
+ this.maxRefs = refs
+ this.dpbRefs = refs
+ this.cabac = new Cabac()
+ this.params = {
+ width: opts.width, height: opts.height, mbw: this.mbw, mbh: this.mbh, profile: opts.profile, level,
+ refs, fpsNum: opts.fpsNum, fpsDen: opts.fpsDen, log2MaxFrameNum: 8, cabac: opts.cabac,
+ transform8x8: this.useI8, weightedPred: opts.weightedPred, dpbRefs: refs, bframes: 0, pyramid: false,
+ }
+ this.tilesX = this.ys >> 4
+ this.tilesY = (this.ah + 2 * PADY) >> 4
+ for (let i = 0; i < 16; i++) this.nz4.push(0)
+ this.pred = newPlane(384)
+ this.trial = newPlane(384)
+ for (let i = 0; i < 16; i++) this.modes4.push(2)
+ for (let i = 0; i < 4; i++) this.modes8.push(2)
+ this.threads = 1
+ if (opts.worker) return
+ this.srcY = newPlane(this.aw * this.ah + 64)
+ this.srcU = newPlane(this.cw * this.chh + 64)
+ this.srcV = newPlane(this.cw * this.chh + 64)
+ this.cur = this.newFrame()
+ const mbs = this.mbw * this.mbh
+ this.changed = new Uint8Array(mbs)
+ this.changed.fill(1)
+ this.held = new Uint8Array(mbs)
+ this.changeCodes = new Uint8Array(mbs)
+ this.prevChanged = new Uint8Array(mbs)
+ this.refresh = new Uint8Array(mbs)
+ this.mbClass = new Uint8Array(mbs)
+ this.mbType = new Int32Array(mbs)
+ this.i16Mode = new Int32Array(mbs)
+ this.cMode = new Int32Array(mbs)
+ this.t8 = new Int32Array(mbs)
+ this.cbp = new Int32Array(mbs)
+ this.dcCbf = new Int32Array(mbs)
+ this.refIdx = new Int32Array(mbs)
+ this.prevMvx = new Int32Array(mbs)
+ this.prevMvy = new Int32Array(mbs)
+ this.mbQp = new Int32Array(mbs)
+ this.mbQp.fill(opts.qp)
+ this.codedQp = new Int32Array(mbs)
+ this.qpY = new Int32Array(mbs)
+ this.qpY.fill(opts.qp)
+ this.qpDelta = new Int32Array(mbs)
+ this.lastChange = new Int32Array(mbs)
+ this.lastChange.fill(-1000000)
+ this.streak = new Int32Array(mbs)
+ this.imode = new Uint8Array(mbs * 16)
+ this.imode.fill(2)
+ this.mvx = new Int32Array(mbs)
+ this.mvy = new Int32Array(mbs)
+ this.mvdx = new Int32Array(mbs)
+ this.mvdy = new Int32Array(mbs)
+ this.nnz = new Uint8Array(mbs * 24)
+ this.pkMask = new Uint16Array(mbs)
+ this.pkOff = new Int32Array(mbs)
+ }
+
+ newFrame(): RefFrame {
+ const f = new RefFrame()
+ f.y = newPlane(this.ysize)
+ f.u = newPlane(this.cs * (this.chh + 2 * PADC))
+ f.v = newPlane(this.cs * (this.chh + 2 * PADC))
+ f.ver = new Int32Array(this.mbw * this.mbh)
+ f.ver.fill(-1)
+ return f
+ }
+
+ giveHalfPlanes(rf: RefFrame) {
+ if (rf.tileGen.length > 0) return
+ for (const s of this.spare) {
+ if (s.tileGen.length === 0) continue
+ const hb = rf.hb
+ const hh = rf.hh
+ const hj = rf.hj
+ const tiles = rf.tileGen
+ rf.hb = s.hb
+ rf.hh = s.hh
+ rf.hj = s.hj
+ rf.tileGen = s.tileGen
+ s.hb = hb
+ s.hh = hh
+ s.hj = hj
+ s.tileGen = tiles
+ return
+ }
+ rf.hb = newPlane(this.ysize)
+ rf.hh = newPlane(this.ysize)
+ rf.hj = newPlane(this.ysize)
+ rf.tileGen = new Int32Array(this.tilesX * this.tilesY)
+ }
+
+ ensureTiles(rf: RefFrame, x0: int, y0: int, w: int, h: int) {
+ if (this.tilesReady) return
+ const tiles = rf.tileGen
+ const gen = rf.gen
+ const tw = this.tilesX
+ const ys = this.ys
+ const org = this.ytile
+ const tx0 = (x0 + PADY) >> 4
+ const ty0 = (y0 + PADY) >> 4
+ const tx1 = (x0 + w - 1 + PADY) >> 4
+ const ty1 = (y0 + h - 1 + PADY) >> 4
+ for (let ty = ty0; ty <= ty1; ty++) {
+ const row = ty * tw
+ for (let tx = tx0; tx <= tx1; tx++) {
+ const t = row + tx
+ if (this.sharedTiles) {
+ if (Atomics.load(tiles, t) !== gen) this.claimTile(rf, t, tx, ty)
+ } else if (tiles[t]! !== gen) {
+ computeHalfTile(rf.hb, rf.hh, rf.hj, rf.y, ys, org + ty * 16 * ys + tx * 16)
+ tiles[t] = gen
+ }
+ }
+ }
+ }
+
+ precomputeTiles(rf: RefFrame) {
+ const tx = this.tilesX
+ const rows = this.tilesY
+ const n = this.threads
+ const gen = rf.gen
+ const y = rf.y
+ const hb = rf.hb
+ const hh = rf.hh
+ const hj = rf.hj
+ const tiles = rf.tileGen
+ const ys = this.ys
+ const org = this.ytile
+ Thread.parallelFor(n, (k) => {
+ for (let r = k; r < rows; r += n) {
+ for (let c = 0; c < tx; c++) {
+ const t = r * tx + c
+ if (tiles[t]! === gen) continue
+ computeHalfTile(hb, hh, hj, y, ys, org + r * 16 * ys + c * 16)
+ tiles[t] = gen
+ }
+ }
+ })
+ }
+
+ claimTile(rf: RefFrame, t: int, tx: int, ty: int) {
+ const gen = rf.gen
+ while (true) {
+ const seen = Atomics.load(rf.tileGen, t)
+ if (seen === gen) return
+ if (seen !== TILE_BUSY && Atomics.compareExchange(rf.tileGen, t, seen, TILE_BUSY) === seen) {
+ computeHalfTile(rf.hb, rf.hh, rf.hj, rf.y, this.ys, this.ytile + ty * 16 * this.ys + tx * 16)
+ Atomics.store(rf.tileGen, t, gen)
+ return
+ }
+ Atomics.pause()
+ }
+ }
+
+ plane(rf: RefFrame, id: int): Uint8Array {
+ if (id === 1) return rf.hb
+ if (id === 2) return rf.hh
+ if (id === 3) return rf.hj
+ return rf.y
+ }
+
+ predictQpel(dst: Uint8Array, dO: int, ds: int, rf: RefFrame, x: int, y: int, mx: int, my: int, w: int, h: int) {
+ const code = qpelPlanes(mx & 3, my & 3)
+ const base = this.ry(x + (mx >> 2), y + (my >> 2))
+ const ao = (code >> 4) & 3
+ const bo = code & 3
+ const offA = ao === 1 ? 1 : ao === 2 ? this.ys : 0
+ const offB = bo === 1 ? 1 : bo === 2 ? this.ys : 0
+ const pa = code >> 6
+ const pb = (code >> 2) & 3
+ if (pa === 0 && pb === 0) {
+ avgPlanes(dst, dO, ds, rf.y, base + offA, rf.y, base + offB, this.ys, w, h)
+ } else if (pa === 0 && pb === 1) {
+ avgPlanes(dst, dO, ds, rf.y, base + offA, rf.hb, base + offB, this.ys, w, h)
+ } else if (pa === 0 && pb === 2) {
+ avgPlanes(dst, dO, ds, rf.y, base + offA, rf.hh, base + offB, this.ys, w, h)
+ } else if (pa === 0 && pb === 3) {
+ avgPlanes(dst, dO, ds, rf.y, base + offA, rf.hj, base + offB, this.ys, w, h)
+ } else if (pa === 1 && pb === 0) {
+ avgPlanes(dst, dO, ds, rf.hb, base + offA, rf.y, base + offB, this.ys, w, h)
+ } else if (pa === 1 && pb === 1) {
+ avgPlanes(dst, dO, ds, rf.hb, base + offA, rf.hb, base + offB, this.ys, w, h)
+ } else if (pa === 1 && pb === 2) {
+ avgPlanes(dst, dO, ds, rf.hb, base + offA, rf.hh, base + offB, this.ys, w, h)
+ } else if (pa === 1 && pb === 3) {
+ avgPlanes(dst, dO, ds, rf.hb, base + offA, rf.hj, base + offB, this.ys, w, h)
+ } else if (pa === 2 && pb === 0) {
+ avgPlanes(dst, dO, ds, rf.hh, base + offA, rf.y, base + offB, this.ys, w, h)
+ } else if (pa === 2 && pb === 1) {
+ avgPlanes(dst, dO, ds, rf.hh, base + offA, rf.hb, base + offB, this.ys, w, h)
+ } else if (pa === 2 && pb === 2) {
+ avgPlanes(dst, dO, ds, rf.hh, base + offA, rf.hh, base + offB, this.ys, w, h)
+ } else if (pa === 2 && pb === 3) {
+ avgPlanes(dst, dO, ds, rf.hh, base + offA, rf.hj, base + offB, this.ys, w, h)
+ } else if (pa === 3 && pb === 0) {
+ avgPlanes(dst, dO, ds, rf.hj, base + offA, rf.y, base + offB, this.ys, w, h)
+ } else if (pa === 3 && pb === 1) {
+ avgPlanes(dst, dO, ds, rf.hj, base + offA, rf.hb, base + offB, this.ys, w, h)
+ } else if (pa === 3 && pb === 2) {
+ avgPlanes(dst, dO, ds, rf.hj, base + offA, rf.hh, base + offB, this.ys, w, h)
+ } else if (pa === 3 && pb === 3) {
+ avgPlanes(dst, dO, ds, rf.hj, base + offA, rf.hj, base + offB, this.ys, w, h)
+ }
+ if (this.wpOn && rf === this.refs[0]!) weightBlock(dst, dO, ds, w, h, this.wpY[0]!, this.wpY[1]!)
+ }
+
+ weightChroma(rf: RefFrame, o: int) {
+ if (!this.wpChromaOn || rf !== this.refs[0]!) return
+ weightBlock(this.pred, o, 8, 8, 8, this.wpU[0]!, this.wpU[1]!)
+ weightBlock(this.pred, o + 64, 8, 8, 8, this.wpV[0]!, this.wpV[1]!)
+ }
+
+ mbAvail(mbx: int, mby: int): int {
+ let av = 0
+ const top = mby > this.sliceRow0
+ if (top) av |= AV_TOP
+ if (mbx > 0) av |= AV_LEFT
+ if (mbx > 0 && top) av |= AV_TL
+ if (top && mbx + 1 < this.mbw) av |= AV_TR
+ return av
+ }
+
+ ry(x: int, y: int): int {
+ return this.yorg + y * this.ys + x
+ }
+
+ rc(x: int, y: int): int {
+ return this.corg + y * this.cs + x
+ }
+
+ copyMbFromFrame(frame: Uint8Array, frameOff: int, mbx: int, mby: int) {
+ const w = this.w
+ const h = this.h
+ const px = mbx * 16
+ const py = mby * 16
+ if (px + 16 <= w && py + 16 <= h) {
+ copyRow16(this.srcY, py * this.aw + px, this.aw, frame, frameOff + py * w + px, w)
+ } else {
+ for (let y = 0; y < 16; y++) {
+ const sy = py + y < h ? py + y : h - 1
+ const so = frameOff + sy * w
+ const d = (py + y) * this.aw
+ for (let x = 0; x < 16; x++) {
+ const sx = px + x < w ? px + x : w - 1
+ this.srcY[d + px + x] = frame[so + sx]!
+ }
+ }
+ }
+ const cwIn = w >> 1
+ const chIn = h >> 1
+ const uo = frameOff + w * h
+ const vo = uo + cwIn * chIn
+ const cx = mbx * 8
+ const cy = mby * 8
+ if (cx + 8 <= cwIn && cy + 8 <= chIn) {
+ copyRect(this.srcU, cy * this.cw + cx, this.cw, frame, uo + cy * cwIn + cx, cwIn, 8, 8)
+ copyRect(this.srcV, cy * this.cw + cx, this.cw, frame, vo + cy * cwIn + cx, cwIn, 8, 8)
+ return
+ }
+ for (let y = 0; y < 8; y++) {
+ const sy = cy + y < chIn ? cy + y : chIn - 1
+ const d = (cy + y) * this.cw
+ for (let x = 0; x < 8; x++) {
+ const sx = cx + x < cwIn ? cx + x : cwIn - 1
+ this.srcU[d + cx + x] = frame[uo + sy * cwIn + sx]!
+ this.srcV[d + cx + x] = frame[vo + sy * cwIn + sx]!
+ }
+ }
+ }
+
+ keepIdrSource(mbx: int, mby: int) {
+ const mb = mby * this.mbw + mbx
+ const slot = Atomics.add(this.idrTop, 0, 1)
+ const po = slot * 384
+ this.idrSlotMb[slot] = mb
+ this.idrSaved[mb] = slot + 1
+ copyRect(this.idrPool, po, 16, this.srcY, mby * 16 * this.aw + mbx * 16, this.aw, 16, 16)
+ const co = mby * 8 * this.cw + mbx * 8
+ copyRect(this.idrPool, po + 256, 8, this.srcU, co, this.cw, 8, 8)
+ copyRect(this.idrPool, po + 320, 8, this.srcV, co, this.cw, 8, 8)
+ }
+
+ saveIdrSource(frame: Uint8Array, frameOff: int, mbx: int, mby: int) {
+ if (this.idrSaved[mby * this.mbw + mbx]! !== 0) return
+ const w = this.w
+ const h = this.h
+ const cwIn = w >> 1
+ const uo = frameOff + w * h
+ if (mbChange(this.srcY, 0, this.aw, this.srcU, 0, this.srcV, 0, this.cw, frame, frameOff, w, uo, uo + cwIn * (h >> 1),
+ cwIn, w, h, 0, mbx, mby) !== 0) this.keepIdrSource(mbx, mby)
+ }
+
+ compactIdrPool() {
+ let top = 0
+ const n = this.idrTop[0]!
+ for (let s = 0; s < n; s++) {
+ const mb = this.idrSlotMb[s]!
+ if (this.idrSaved[mb]! !== s + 1) continue
+ if (top !== s) this.idrPool.copyWithin(top * 384, s * 384, s * 384 + 384)
+ this.idrSlotMb[top] = mb
+ this.idrSaved[mb] = top + 1
+ top++
+ }
+ this.idrTop[0] = top
+ }
+
+ useChanges(map: Uint8Array, index: int, noise: int) {
+ this.laChanges = map
+ this.laChangesAt = index
+ this.laChangesNoise = noise
+ }
+
+ markChanged(frame: Uint8Array, frameOff: int): int {
+ const w = this.w
+ const h = this.h
+ const cwIn = w >> 1
+ const uo = frameOff + w * h
+ const vo = uo + cwIn * (h >> 1)
+ const mbw = this.mbw
+ const mbs = mbw * this.mbh
+ const held = this.held
+ const changed = this.changed
+ const one = u8x16.splat(1)
+ const zero = u8x16.splat(0)
+ let n = 0
+ if (this.laChangesAt === this.frameIndex && this.heldAt === this.frameIndex - 1 && this.laChangesNoise === this.noise &&
+ this.laChanges.length === mbs) {
+ const shared = this.laChanges
+ let mb = 0
+ while (mb < mbs) {
+ if (mb + 16 <= mbs && u8x16.load(held, mb).eq(one).mask() === 0xffff) {
+ const c = u8x16.load(shared, mb)
+ const ch = c.eq(one) & one
+ const same = c.eq(zero) & one
+ ch.store(changed, mb)
+ same.store(held, mb)
+ n += ch.sum()
+ mb += 16
+ continue
+ }
+ const end = mb + 16 < mbs ? mb + 16 : mbs
+ for (; mb < end; mb++) {
+ const c = held[mb]! !== 0 ? int(shared[mb]!) : mbChange(this.srcY, 0, this.aw, this.srcU, 0, this.srcV, 0, this.cw,
+ frame, frameOff, w, uo, vo, cwIn, w, h, this.noise, mb % mbw, Math.trunc(mb / mbw))
+ if (c === 1) {
+ changed[mb] = 1
+ n++
+ }
+ held[mb] = c === 0 ? 1 : 0
+ }
+ }
+ return n
+ }
+ n = this.codesOf(frame, frameOff, this.changeCodes)
+ this.takeCodes(this.changeCodes)
+ return n
+ }
+
+ codesOf(frame: Uint8Array, frameOff: int, codes: Uint8Array): int {
+ const w = this.w
+ const h = this.h
+ const cwIn = w >> 1
+ const uo = frameOff + w * h
+ codes.fill(0)
+ return changeMap(this.srcY, 0, this.aw, this.srcU, 0, this.srcV, 0, this.cw, frame, frameOff, w, uo,
+ uo + cwIn * (h >> 1), cwIn, w, h, this.noise, codes)
+ }
+
+ takeCodes(codes: Uint8Array) {
+ const mbs = this.mbw * this.mbh
+ const changed = this.changed
+ const held = this.held
+ const one = u8x16.splat(1)
+ const zero = u8x16.splat(0)
+ let mb = 0
+ for (; mb + 16 <= mbs; mb += 16) {
+ const c = u8x16.load(codes, mb)
+ (c.eq(one) & one).store(changed, mb)
+ (c.eq(zero) & one).store(held, mb)
+ }
+ for (; mb < mbs; mb++) {
+ const c = codes[mb]!
+ changed[mb] = c === 1 ? 1 : 0
+ held[mb] = c === 0 ? 1 : 0
+ }
+ }
+
+ holdChanged() {
+ const mbs = this.mbw * this.mbh
+ const changed = this.changed
+ const held = this.held
+ const one = u8x16.splat(1)
+ const zero = u8x16.splat(0)
+ let mb = 0
+ for (; mb + 16 <= mbs; mb += 16) {
+ (u8x16.load(held, mb) | (one - (u8x16.load(changed, mb).eq(zero) & one))).store(held, mb)
+ }
+ for (; mb < mbs; mb++) {
+ if (changed[mb]! !== 0) held[mb] = 1
+ }
+ }
+
+ planBox(changed: Uint8Array, n: int, plan: Int32Array) {
+ let minY = this.mbh
+ let maxY = -1
+ let minX = this.mbw
+ let maxX = -1
+ if (n > 0) {
+ for (let mby = 0; mby < this.mbh; mby++) {
+ for (let mbx = 0; mbx < this.mbw; mbx++) {
+ if (changed[mby * this.mbw + mbx]! === 1) {
+ if (mby < minY) minY = mby
+ if (mby > maxY) maxY = mby
+ if (mbx < minX) minX = mbx
+ if (mbx > maxX) maxX = mbx
+ }
+ }
+ }
+ }
+ plan[PLAN_N] = n
+ plan[PLAN_MINX] = minX
+ plan[PLAN_MAXX] = maxX
+ plan[PLAN_MINY] = minY
+ plan[PLAN_MAXY] = maxY
+ }
+
+ analyse(frame: Uint8Array, frameOff: int, side: SideInfo | undefined, full: bool): int {
+ const mbs = this.mbw * this.mbh
+ const peeked = this.peeked && frame === this.peekedFrame && frameOff === this.peekedOff &&
+ this.frameIndex === this.peekedIndex && side === undefined && !full
+ const weighed = peeked && this.pkWeighed
+ this.peeked = false
+ this.pkWeighed = false
+ for (let i = 0; i < mbs; i++) this.changed[i] = 0
+ this.scrollMvx = 0
+ this.scrollMvy = 0
+ this.scrollMb0 = -1
+ this.scrollMb1 = -1
+ this.cursorMvx = 0
+ this.cursorMvy = 0
+ this.cursorMb = -1
+ this.shiftHx = 0
+ this.shiftVy = 0
+ this.wpScanned = false
+ for (let i = 0; i < mbs; i++) this.refresh[i] = 0
+ if (full) {
+ if (side !== undefined) {
+ markRects(this.changed, this.mbw, this.mbh, side.dirty)
+ } else if (this.frameIndex > 0) {
+ this.markChanged(frame, frameOff)
+ }
+ for (let i = 0; i < mbs; i++) {
+ if (this.changed[i]! === 0) this.changed[i] = 3
+ }
+ if (this.idrCache) {
+ const exact = side === undefined && this.frameIndex > 0
+ for (let mby = 0; mby < this.mbh; mby++) {
+ for (let mbx = 0; mbx < this.mbw; mbx++) {
+ const mb = mby * this.mbw + mbx
+ if (!exact) this.saveIdrSource(frame, frameOff, mbx, mby)
+ else if (this.held[mb]! === 0 && this.idrSaved[mb]! === 0) this.keepIdrSource(mbx, mby)
+ }
+ }
+ }
+ if (this.srcSlot >= 0) this.bindSource(this.srcRing[this.srcSlot]!)
+ copyPadded(this.srcY, this.aw, this.ah, frame, frameOff, this.w, this.w, this.h)
+ const cwIn = this.w >> 1
+ const chIn = this.h >> 1
+ copyPadded(this.srcU, this.cw, this.chh, frame, frameOff + this.w * this.h, cwIn, cwIn, chIn)
+ copyPadded(this.srcV, this.cw, this.chh, frame, frameOff + this.w * this.h + cwIn * chIn, cwIn, cwIn, chIn)
+ this.held.fill(1)
+ this.heldAt = this.frameIndex
+ if (side !== undefined) this.noteHints(side)
+ return mbs
+ }
+ let n = 0
+ if (side !== undefined) {
+ this.held.fill(0)
+ this.heldAt = this.frameIndex
+ n = markRects(this.changed, this.mbw, this.mbh, side.dirty)
+ for (const sc of side.scroll) n += markRects(this.changed, this.mbw, this.mbh, [sc.x, sc.y, sc.w, sc.h])
+ this.noteHints(side)
+ this.estimateGlobalShift(frame, frameOff, n)
+ return n
+ }
+ let plan = this.pkPlan
+ if (peeked) {
+ this.takeCodes(this.pkChanged)
+ n = plan[PLAN_N]!
+ } else {
+ plan = new Int32Array(this.planSize())
+ n = this.markChanged(frame, frameOff)
+ this.planBox(this.changed, n, plan)
+ }
+ this.heldAt = this.frameIndex
+ const minX = plan[PLAN_MINX]!
+ const maxX = plan[PLAN_MAXX]!
+ const minY = plan[PLAN_MINY]!
+ const maxY = plan[PLAN_MAXY]!
+ if (this.threads > 1 && n * 4 >= mbs && this.refs.length > 0) {
+ if (peeked) {
+ this.applyScan(plan, this.pkShifts)
+ if (weighed) {
+ this.wpFit.set(this.pkFit)
+ this.wpScanned = true
+ }
+ } else {
+ this.scanConcurrent(frame, frameOff, plan)
+ }
+ return n
+ }
+ if (n >= 6 && maxY - minY >= 2 && this.refs.length > 0) {
+ const x0 = minX * 16
+ const y0 = minY * 16
+ const ww = (maxX - minX + 1) * 16 < this.w - x0 ? (maxX - minX + 1) * 16 : this.w - x0
+ const hh = (maxY - minY + 1) * 16 < this.h - y0 ? (maxY - minY + 1) * 16 : this.h - y0
+ const dy = estimateScroll(frame, this.w, frameOff, this.srcY, this.aw, 0, x0, y0, ww, hh, this.h, 256)
+ if (dy !== 0) {
+ this.scrollMvx = 0
+ this.scrollMvy = dy * 4
+ this.scrollMb0 = minY * this.mbw + minX
+ this.scrollMb1 = maxY * this.mbw + maxX
+ }
+ }
+ this.estimateGlobalShift(frame, frameOff, n)
+ return n
+ }
+
+ estimateGlobalShift(frame: Uint8Array, frameOff: int, n: int) {
+ const mbs = this.mbw * this.mbh
+ if (!this.globalShift || this.refs.length === 0 || n < 48 || n * 50 < mbs) return
+ let minY = this.mbh
+ let maxY = -1
+ let minX = this.mbw
+ let maxX = -1
+ for (let mby = 0; mby < this.mbh; mby++) {
+ for (let mbx = 0; mbx < this.mbw; mbx++) {
+ if (this.changed[mby * this.mbw + mbx]! === 0) continue
+ if (mby < minY) minY = mby
+ if (mby > maxY) maxY = mby
+ if (mbx < minX) minX = mbx
+ if (mbx > maxX) maxX = mbx
+ }
+ }
+ if (maxY < 0) return
+ const x0 = minX * 16
+ const y0 = minY * 16
+ const ww = (maxX - minX + 1) * 16 < this.w - x0 ? (maxX - minX + 1) * 16 : this.w - x0
+ const hh = (maxY - minY + 1) * 16 < this.h - y0 ? (maxY - minY + 1) * 16 : this.h - y0
+ const dx = estimateShift(frame, this.w, frameOff, this.srcY, this.aw, 0, x0, y0, ww, hh, this.w, this.h, true, 512)
+ this.shiftHx = dx * 4
+ if (this.scrollMvy === 0) {
+ const dy = estimateShift(frame, this.w, frameOff, this.srcY, this.aw, 0, x0, y0, ww, hh, this.w, this.h, false, 256)
+ this.shiftVy = dy * 4
+ }
+ }
+
+ diffFrame(frame: Uint8Array, frameOff: int, codes: Uint8Array, plan: Int32Array): int {
+ const n = this.codesOf(frame, frameOff, codes)
+ this.planBox(codes, n, plan)
+ return n
+ }
+
+ planSize(): int {
+ return PLAN_JOB0 + 3 + 2 * Math.trunc((this.h + HASH_ROWS - 1) / HASH_ROWS)
+ }
+
+ scanPlan(plan: Int32Array, weigh: bool) {
+ const mbs = this.mbw * this.mbh
+ const n = plan[PLAN_N]!
+ const minX = plan[PLAN_MINX]!
+ const maxX = plan[PLAN_MAXX]!
+ const minY = plan[PLAN_MINY]!
+ const maxY = plan[PLAN_MAXY]!
+ const x0 = minX * 16
+ const y0 = minY * 16
+ const ww = (maxX - minX + 1) * 16 < this.w - x0 ? (maxX - minX + 1) * 16 : this.w - x0
+ const hh = (maxY - minY + 1) * 16 < this.h - y0 ? (maxY - minY + 1) * 16 : this.h - y0
+ const span = n >= 6 && maxY - minY >= 2 ? scrollSpan(ww, hh, y0, this.h, 256) : []
+ const shift = this.globalShift && n >= 48 && n * 50 >= mbs
+ const ylo = span.length > 0 ? span[0]! : 0
+ const prevRows = span.length > 0 ? span[1]! - ylo : 0
+ const curRows = span.length > 0 ? hh : 0
+ plan[PLAN_X0] = x0
+ plan[PLAN_Y0] = y0
+ plan[PLAN_WW] = ww
+ plan[PLAN_HH] = hh
+ plan[PLAN_YLO] = ylo
+ plan[PLAN_PREV] = prevRows
+ plan[PLAN_CUR] = curRows
+ plan[PLAN_SPAN] = span.length > 0 ? 1 : 0
+ plan[PLAN_SHIFT] = shift ? 1 : 0
+ plan[PLAN_DY] = 0
+ let k = PLAN_JOB0
+ if (weigh) {
+ plan[k] = SCAN_WEIGHTS
+ k++
+ }
+ if (shift) {
+ plan[k] = SCAN_SHIFT_H
+ plan[k + 1] = SCAN_SHIFT_V
+ k += 2
+ }
+ for (let r = 0; r < prevRows; r += HASH_ROWS) {
+ plan[k] = SCAN_HASH + r * 2
+ k++
+ }
+ for (let r = 0; r < curRows; r += HASH_ROWS) {
+ plan[k] = SCAN_HASH + r * 2 + 1
+ k++
+ }
+ plan[PLAN_JOBS] = k - PLAN_JOB0
+ }
+
+ scanOf(plan: Int32Array, frame: Uint8Array, frameOff: int, prevHashes: Uint32Array, curHashes: Uint32Array,
+ shifts: Int32Array, rf: RefFrame, wpFit: Int32Array): FrameScan {
+ return {
+ frame, frameOff, w: this.w, h: this.h, src: this.srcY, aw: this.aw, x0: plan[PLAN_X0]!, y0: plan[PLAN_Y0]!,
+ ww: plan[PLAN_WW]!, hh: plan[PLAN_HH]!, ylo: plan[PLAN_YLO]!, prevHashes, curHashes, shifts, refY: rf.y,
+ refU: rf.u, refV: rf.v, yorg: this.yorg, ys: this.ys, corg: this.corg, cs: this.cs, wpFit,
+ }
+ }
+
+ applyScan(plan: Int32Array, shifts: Int32Array) {
+ const dy = plan[PLAN_DY]!
+ if (dy !== 0) {
+ this.scrollMvx = 0
+ this.scrollMvy = dy * 4
+ this.scrollMb0 = plan[PLAN_MINY]! * this.mbw + plan[PLAN_MINX]!
+ this.scrollMb1 = plan[PLAN_MAXY]! * this.mbw + plan[PLAN_MAXX]!
+ }
+ if (plan[PLAN_SHIFT]! === 1) {
+ this.shiftHx = shifts[0]! * 4
+ if (this.scrollMvy === 0) this.shiftVy = shifts[1]! * 4
+ }
+ }
+
+ scanConcurrent(frame: Uint8Array, frameOff: int, plan: Int32Array) {
+ const mbs = this.mbw * this.mbh
+ const weigh = this.params.weightedPred && plan[PLAN_N]! * 20 >= mbs * 19
+ this.scanPlan(plan, weigh)
+ const s = this.scanOf(plan, frame, frameOff, new Uint32Array(plan[PLAN_PREV]!), new Uint32Array(plan[PLAN_CUR]!),
+ new Int32Array(2), this.refs[0]!, this.wpFit)
+ this.runScan(s, plan)
+ this.applyScan(plan, s.shifts)
+ this.wpScanned = weigh
+ }
+
+ runScan(s: FrameScan, plan: Int32Array) {
+ const jobs = plan[PLAN_JOBS]!
+ const next = new Int32Array(2)
+ const helpers = this.threads - 1 < jobs - 1 ? this.threads - 1 : jobs - 1
+ // Helpers are never joined: one the scheduler starts late finds no job left and touches nothing, so waiting
+ // for it would only add its wake-up latency; the completed-job count orders the results instead. The job
+ // count goes by value because peekAnchor's plan is rewritten by later peeks.
+ for (let k = 0; k < helpers; k++) Thread.spawn(() => scanJobs(s, plan, next, jobs))
+ scanJobs(s, plan, next, jobs)
+ let done = Atomics.load(next, 1)
+ while (done < jobs) {
+ Atomics.wait(next, 1, done, 1)
+ done = Atomics.load(next, 1)
+ }
+ scanDone(s, plan)
+ }
+
+ peekAnchor(idx: int) {
+ const next = idx + 1
+ if (this.threads < 2 || this.nextFrame.length === 0 || this.fullAnalysis || this.refs.length === 0 ||
+ next - this.pocBase >= this.keyint || Atomics.load(this.nextRead, 0) !== 1) {
+ return
+ }
+ const mbs = this.mbw * this.mbh
+ const plan = this.pkPlan
+ const n = this.diffFrame(this.nextFrame, this.nextOff, this.pkChanged, plan)
+ this.pkWeighed = false
+ if (n * 4 >= mbs) {
+ const weigh = this.params.weightedPred && n * 20 >= mbs * 19
+ this.scanPlan(plan, weigh)
+ const s = this.scanOf(plan, this.nextFrame, this.nextOff, this.pkPrev.subarray(0, plan[PLAN_PREV]!),
+ this.pkCur.subarray(0, plan[PLAN_CUR]!), this.pkShifts, this.refs[0]!, this.pkFit)
+ this.runScan(s, plan)
+ this.pkWeighed = weigh
+ }
+ this.peeked = true
+ this.peekedFrame = this.nextFrame
+ this.peekedOff = this.nextOff
+ this.peekedIndex = next
+ }
+
+ expectNext(frame: Uint8Array, frameOff: int, ready: Int32Array) {
+ this.nextFrame = frame
+ this.nextOff = frameOff
+ this.nextRead = ready
+ if (frame.length === 0 || this.pkChanged.length > 0) return
+ this.pkSync = progressArray(3)
+ this.pkChanged = new Uint8Array(this.mbw * this.mbh)
+ this.pkPlan = new Int32Array(this.planSize())
+ this.pkPrev = new Uint32Array(this.h)
+ this.pkCur = new Uint32Array(this.h)
+ this.pkShifts = new Int32Array(2)
+ }
+
+ peekLead(pk: Peek) {
+ // The next frame is compared with srcY, which holds the current frame's source only after every row is prepped;
+ // the weighted-prediction fit is left to analyse because it needs the current frame's reconstruction.
+ this.waitRow(pk.sync, PEEK_PREPPED, this.mbh)
+ if (Atomics.load(pk.ready, 0) !== 1) {
+ publish(pk.sync, PEEK_PHASE, 3)
+ return
+ }
+ const n = this.diffFrame(pk.frame, pk.frameOff, pk.changed, pk.plan)
+ if (n * 4 >= this.mbw * this.mbh) {
+ this.scanPlan(pk.plan, false)
+ } else {
+ pk.plan[PLAN_JOBS] = 0
+ }
+ publish(pk.sync, PEEK_PHASE, 2)
+ }
+
+ peekWork(pk: Peek) {
+ const sync = pk.sync
+ if (Atomics.compareExchange(sync, PEEK_PHASE * ROW_SLOT, 0, 1) === 0) this.peekLead(pk)
+ this.waitRow(sync, PEEK_PHASE, 2)
+ if (Atomics.load(sync, PEEK_PHASE * ROW_SLOT) !== 2) return
+ const plan = pk.plan
+ const jobs = plan[PLAN_JOBS]!
+ if (jobs === 0) return
+ const s = this.scanOf(plan, pk.frame, pk.frameOff, pk.prev.subarray(0, plan[PLAN_PREV]!),
+ pk.cur.subarray(0, plan[PLAN_CUR]!), pk.shifts, this.cur, this.wpFit)
+ while (true) {
+ const j = Atomics.add(sync, PEEK_NEXT * ROW_SLOT, 1)
+ if (j >= jobs) return
+ runScanJob(s, plan[PLAN_JOB0 + j]!)
+ if (Atomics.add(sync, PEEK_NEXT * ROW_SLOT + 1, 1) === jobs - 1) scanDone(s, plan)
+ }
+ }
+
+ estimateWeights(frame: Uint8Array, frameOff: int, nChanged: int): int {
+ const rf = this.refs[0]!
+ const fit = this.wpFit
+ if (!this.wpScanned) {
+ weightFit(frame, frameOff, this.w, this.h, rf.y, rf.u, rf.v, this.yorg, this.ys, this.corg, this.cs, fit)
+ }
+ this.wpScanned = false
+ if (fit[0]! === 0) return nChanged
+ this.wpOn = true
+ this.wpY = [fit[1]!, fit[2]!]
+ this.wpU = [fit[3]!, fit[4]!]
+ this.wpV = [fit[5]!, fit[6]!]
+ this.wpChromaOn = fit[7]! === 1
+ this.wpFrames++
+ const plane = rf.y.length
+ if (this.wref.length !== plane) this.wref = newPlane(plane)
+ const wv = i16x8.splat(fit[1]!)
+ const ov = i16x8.splat(fit[2]!)
+ const rr = i16x8.splat(32)
+ for (let i = 0; i + 16 <= plane; i += 16) {
+ const v = u8x16.load(rf.y, i)
+ u8x16.packSat(((v.widenLow() * wv + rr) >> 6) + ov, ((v.widenHigh() * wv + rr) >> 6) + ov).store(this.wref, i)
+ }
+ let n2 = nChanged
+ const mbs = this.mbw * this.mbh
+ for (let i = 0; i < mbs; i++) {
+ if (this.changed[i]! !== 0) continue
+ this.changed[i] = 1
+ n2++
+ }
+ return n2
+ }
+
+ markRefresh(): int {
+ if (this.refreshDelta <= 0) return 0
+ const mbs = this.mbw * this.mbh
+ let n = 0
+ for (let mb = 0; mb < mbs; mb++) {
+ if (this.prevChanged[mb]! !== 0 && this.changed[mb]! === 0) {
+ this.refresh[mb] = 1
+ n++
+ }
+ }
+ return n
+ }
+
+ markIdleRefine(): int {
+ if (!this.rcAct || this.refreshDelta <= 0 || this.lastCodedIndex < 0) return 0
+ if (this.frameIndex - this.lastActive < Math.round(this.fpsF * 0.5)) return 0
+ const mbs = this.mbw * this.mbh
+ const lowest = this.rate.vbrMinQp - this.refreshDelta + this.refineGain
+ let n = 0
+ for (let mb = 0; mb < mbs; mb++) {
+ if (this.codedQp[mb]! >= lowest) n++
+ }
+ if (n === 0) return 0
+ const limit = this.rate.peekQp(n, this.frameIndex - this.lastCodedIndex) - this.refreshDelta + this.refineGain
+ n = 0
+ for (let mb = 0; mb < mbs; mb++) {
+ if (this.codedQp[mb]! >= limit) {
+ this.refresh[mb] = 1
+ n++
+ }
+ }
+ return n
+ }
+
+ classifyCount(mbx: int, mby: int): int {
+ const cls = classifyMb(this.srcY, mby * 16 * this.aw + mbx * 16, this.aw)
+ if (cls === AQ_TEXT) this.textMbs++
+ return cls
+ }
+
+ aqOffset(mb: int, mbx: int, mby: int): int {
+ if (this.aqStrength <= 0) return 0
+ const cls = this.classReady ? this.mbClass[mb]! : this.classifyCount(mbx, mby)
+ if (cls === AQ_TEXT) return -3 * this.aqStrength
+ return cls === AQ_TEXTURE ? this.aqTexture * this.aqStrength : 0
+ }
+
+ // textMbs only reaches motion search through the sub-pel settings tested here; when the text and video
+ // settings agree, the wavefront skips the frame-wide text count (and the barrier it needs).
+ textGated(): bool {
+ if (this.aqStrength <= 0 || this.subpel <= 0) return false
+ if (this.subpelDirs !== this.videoHpelDirs) return true
+ return this.subpel >= 2 && (this.subpelDirs !== this.videoQpelDirs || (this.hpelSad && !this.qpelSad))
+ }
+
+ classifyInput(frame: Uint8Array, frameOff: int, mbx: int, mby: int): int {
+ const w = this.w
+ const h = this.h
+ const px = mbx * 16
+ const py = mby * 16
+ if (px + 16 <= w && py + 16 <= h) return classifyMb(frame, frameOff + py * w + px, w)
+ const b = this.edgeBlk
+ for (let y = 0; y < 16; y++) {
+ const so = frameOff + (py + y < h ? py + y : h - 1) * w
+ for (let x = 0; x < 16; x++) b[y * 16 + x] = frame[so + (px + x < w ? px + x : w - 1)]!
+ }
+ return classifyMb(b, 0, 16)
+ }
+
+ classifyRow(frame: Uint8Array, frameOff: int, full: bool, mby: int): int {
+ const mbw = this.mbw
+ let n = 0
+ for (let mbx = 0; mbx < mbw; mbx++) {
+ const mb = mby * mbw + mbx
+ const ch = this.changed[mb]! !== 0
+ if (!full && !ch && this.refresh[mb]! === 0) continue
+ const cls = full || !ch ? classifyMb(this.srcY, mby * 16 * this.aw + mbx * 16, this.aw) :
+ this.classifyInput(frame, frameOff, mbx, mby)
+ this.mbClass[mb] = cls
+ if (cls === AQ_TEXT) n++
+ }
+ return n
+ }
+
+ classifyFrame(frame: Uint8Array, frameOff: int, full: bool, next: Int32Array, done: Int32Array, text: Int32Array) {
+ const t = performance.now()
+ const mbh = this.mbh
+ while (true) {
+ const r = Atomics.add(next, 0, 1)
+ if (r >= mbh) break
+ text[r] = this.classifyRow(frame, frameOff, full, r)
+ bump(done, 0)
+ }
+ this.waitRow(done, 0, mbh)
+ let n = 0
+ for (let r = 0; r < mbh; r++) n += text[r]!
+ this.textMbs = n
+ this.classReady = true
+ this.rPrep += performance.now() - t
+ }
+
+ laHorizon(): int {
+ const since = this.bframes > 0 ? this.inputIndex - this.pocBase : this.sinceIdr
+ const left = this.refs.length === 0 || since >= this.keyint ? this.keyint : this.keyint - since
+ return left < this.laSpan ? left : this.laSpan
+ }
+
+ setLookahead(life: Int32Array) {
+ this.laLife = life
+ this.laNext = life.length > 0
+ }
+
+ laHorizonAt(idx: int): int {
+ const k = idx % this.keyint
+ const left = k === 0 ? this.keyint : this.keyint - k
+ return left < this.laSpan ? left : this.laSpan
+ }
+
+ wantsKeepMap(): bool {
+ return this.bframes > 0 && this.laL1 > 0.0
+ }
+
+ flatLookahead(): bool {
+ return this.keyint === 1
+ }
+
+ takeLookahead(look: Lookahead, life: Int32Array, keep: Uint8Array) {
+ if (this.flatLookahead()) {
+ if (this.flatLife.length === 0) this.flatLife = new Int32Array(this.mbw * this.mbh)
+ this.setLookahead(this.flatLife)
+ return
+ }
+ look.takeInto(this.laHorizon(), life)
+ if (this.wantsKeepMap()) look.keepMap(keep)
+ this.useLookahead(life, keep)
+ }
+
+ useLookahead(life: Int32Array, keep: Uint8Array) {
+ this.setLookahead(life)
+ if (this.wantsKeepMap()) this.laKeep = keep
+ }
+
+ anchorLookahead(life: Int32Array, keep: Uint8Array, idx: int) {
+ this.setLookahead(life)
+ if (!this.laNext || this.laL1 <= 0.0 || this.pending.length === 0 || keep.length === 0) return
+ const mbs = this.mbw * this.mbh
+ const p0 = this.lastAnchorIndex
+ const span = f64(idx - p0)
+ const scale = this.laL1 * f64(LIFE_ONE)
+ const one = f64(KEEP_ONE)
+ const last = this.pending.length - 1
+ for (let mb = 0; mb < mbs; mb++) {
+ let chain = f64(keep[mb]!) / one
+ let credit = 0.0
+ for (let k = last; k >= 0; k--) {
+ const p = this.pending[k]!
+ credit += chain * f64(p.index - p0) / span
+ chain *= f64(p.keep[mb]!) / one
+ }
+ life[mb] = life[mb]! + Math.trunc(scale * credit + 0.5)
+ }
+ }
+
+ lifeOffset(life: int, horizon: int): int {
+ const l = life < LIFE_ONE ? LIFE_ONE : life < horizon ? life : horizon
+ const o = this.laBase + this.laStrength * Math.log2(f64(this.laSpan * LIFE_ONE) / f64(l))
+ return Math.round(o < this.laMax ? o : this.laMax)
+ }
+
+ assignMbQp(mb: int, mbx: int, mby: int, full: bool, idr: bool, longStatic: int) {
+ if (!full && this.changed[mb]! === 0 && this.refresh[mb]! === 0) return
+ const q = this.baseMbQp(mb, idr, longStatic) + this.aqOffset(mb, mbx, mby)
+ this.mbQp[mb] = q < 0 ? 0 : q > 51 ? 51 : q
+ }
+
+ baseMbQp(mb: int, idr: bool, longStatic: int): int {
+ let q = this.frameQp
+ if (this.laOn) q += this.lifeOffset(this.laLife[mb]!, this.laHz)
+ if (this.lifetimeAq && this.frameIndex > 0 && !(this.laOn && idr)) {
+ const age = this.frameIndex - this.lastChange[mb]!
+ const st = this.streak[mb]!
+ const gap = this.frameIndex - this.lastAnalysed
+ if (idr) {
+ if (age >= longStatic) {
+ q -= 2
+ } else if (st >= 3 && age <= gap) {
+ q += 1
+ }
+ } else if (this.changed[mb]! !== 0) {
+ if (st >= 3 && age <= gap) {
+ q += 2
+ } else if (age >= longStatic) {
+ q -= 2
+ }
+ }
+ }
+ if (this.refresh[mb]! !== 0) q -= this.refreshDelta
+ this.codedQp[mb] = q
+ return q
+ }
+
+ aqRow(mby: int) {
+ for (let mbx = 0; mbx < this.mbw; mbx++) {
+ const mb = mby * this.mbw + mbx
+ const q = this.mbQp[mb]! + this.aqOffset(mb, mbx, mby)
+ this.mbQp[mb] = q < 0 ? 0 : q > 51 ? 51 : q
+ }
+ }
+
+ updateMbHistory(mb: int) {
+ if (this.changed[mb]! !== 1) return
+ this.streak[mb] = this.lastChange[mb]! === this.lastAnalysed ? this.streak[mb]! + 1 : 1
+ this.lastChange[mb] = this.frameIndex
+ }
+
+ updateHistory() {
+ const mbs = this.mbw * this.mbh
+ for (let mb = 0; mb < mbs; mb++) this.updateMbHistory(mb)
+ this.lastAnalysed = this.frameIndex
+ }
+
+ prepRowTimed(frame: Uint8Array, frameOff: int, mby: int, full: bool, idr: bool) {
+ const t = performance.now()
+ this.prepRow(frame, frameOff, mby, full, idr)
+ this.rPrep += performance.now() - t
+ }
+
+ prepRow(frame: Uint8Array, frameOff: int, mby: int, full: bool, idr: bool) {
+ const mbw = this.mbw
+ const longStatic = Math.round(this.fpsF)
+ for (let mbx = 0; mbx < mbw; mbx++) {
+ const mb = mby * mbw + mbx
+ const ch = this.changed[mb]! !== 0
+ if (!full && ch) {
+ if (this.idrCache) this.saveIdrSource(frame, frameOff, mbx, mby)
+ this.copyMbFromFrame(frame, frameOff, mbx, mby)
+ }
+ this.assignMbQp(mb, mbx, mby, full, idr, longStatic)
+ this.updateMbHistory(mb)
+ if (!idr && !ch && this.refresh[mb]! === 0) this.syncMb(mb, mbx, mby)
+ }
+ }
+
+ finishQp(mb: int) {
+ const t = this.mbType[mb]!
+ const has = t === MB_I16 || (t !== MB_PSKIP && this.cbp[mb]! !== 0)
+ if (has) {
+ let d = this.mbQp[mb]! - this.qpPred
+ if (d > 25) d -= 52
+ if (d < -26) d += 52
+ this.qpDelta[mb] = d
+ this.qpY[mb] = this.mbQp[mb]!
+ } else {
+ this.qpDelta[mb] = 0
+ this.qpY[mb] = this.qpPred
+ }
+ this.qpPred = this.qpY[mb]!
+ }
+
+ noteHints(side: SideInfo) {
+ if (side.scroll.length > 0) {
+ const sc = side.scroll[0]!
+ this.scrollMvx = -sc.dx * 4
+ this.scrollMvy = -sc.dy * 4
+ const x1 = sc.x + sc.w - 1
+ const y1 = sc.y + sc.h - 1
+ this.scrollMb0 = (sc.y >> 4) * this.mbw + (sc.x >> 4)
+ this.scrollMb1 = ((y1 >> 4) < this.mbh ? y1 >> 4 : this.mbh - 1) * this.mbw + ((x1 >> 4) < this.mbw ? x1 >> 4 : this.mbw - 1)
+ }
+ if (side.cursorX >= 0 && this.prevCursorX >= 0) {
+ this.cursorMvx = -(side.cursorX - this.prevCursorX) * 4
+ this.cursorMvy = -(side.cursorY - this.prevCursorY) * 4
+ this.cursorMb = (side.cursorY >> 4) * this.mbw + (side.cursorX >> 4)
+ }
+ this.prevCursorX = side.cursorX
+ this.prevCursorY = side.cursorY
+ }
+
+ inScroll(mbx: int, mby: int): bool {
+ if (this.scrollMb0 < 0) return false
+ const y0 = Math.trunc(this.scrollMb0 / this.mbw)
+ const x0 = this.scrollMb0 - y0 * this.mbw
+ const y1 = Math.trunc(this.scrollMb1 / this.mbw)
+ const x1 = this.scrollMb1 - y1 * this.mbw
+ return mbx >= x0 && mbx <= x1 && mby >= y0 && mby <= y1
+ }
+
+ refMarking(idr: bool) {
+ let reorder: int[] = []
+ let mmco: int[] = []
+ if (this.bRefNum >= 0 && !idr) {
+ const max = 1 << this.params.log2MaxFrameNum
+ const cur = this.frameNum
+ let pred = cur
+ for (let i = 0; i < this.refsActive; i++) {
+ const f = this.refs[i]!.frameNum
+ const pn = f > cur ? f - max : f
+ reorder.push(pn < pred ? 0 : 1)
+ reorder.push(iabs(pred - pn) - 1)
+ pred = pn
+ }
+ const b = this.bRefNum > cur ? this.bRefNum - max : this.bRefNum
+ mmco.push(cur - b - 1)
+ }
+ this.l0Reorder = reorder
+ this.mmco = mmco
+ this.bRefNum = -1
+ }
+
+ syncMb(mb: int, mbx: int, mby: int) {
+ const ref0 = this.refs[0]!
+ if (this.cur.ver[mb]! === ref0.ver[mb]!) return
+ copyRect(this.cur.y, this.ry(mbx * 16, mby * 16), this.ys, ref0.y, this.ry(mbx * 16, mby * 16), this.ys, 16, 16)
+ copyRect(this.cur.u, this.rc(mbx * 8, mby * 8), this.cs, ref0.u, this.rc(mbx * 8, mby * 8), this.cs, 8, 8)
+ copyRect(this.cur.v, this.rc(mbx * 8, mby * 8), this.cs, ref0.v, this.rc(mbx * 8, mby * 8), this.cs, 8, 8)
+ this.cur.ver[mb] = ref0.ver[mb]!
+ this.padMb(mbx, mby)
+ }
+
+ padMb(mbx: int, mby: int) {
+ const last = mbx === this.mbw - 1
+ const bottom = mby === this.mbh - 1
+ if (mbx !== 0 && !last && mby !== 0 && !bottom) return
+ this.padPlaneMb(this.cur.y, this.ys, this.yorg, mbx, mby, 16, PADY, this.aw, this.ah)
+ this.padPlaneMb(this.cur.u, this.cs, this.corg, mbx, mby, 8, PADC, this.cw, this.chh)
+ this.padPlaneMb(this.cur.v, this.cs, this.corg, mbx, mby, 8, PADC, this.cw, this.chh)
+ }
+
+ padPlaneMb(p: Uint8Array, stride: int, org: int, mbx: int, mby: int, n: int, pad: int, pw: int, ph: int) {
+ const x0 = mbx * n
+ const y0 = mby * n
+ const left = mbx === 0
+ const right = mbx === this.mbw - 1
+ if (left || right) {
+ for (let y = y0; y < y0 + n; y++) {
+ const row = org + y * stride
+ if (left) fillBytes(p, row - pad, pad, p[row]!)
+ if (right) fillBytes(p, row + pw, pad, p[row + pw - 1]!)
+ }
+ }
+ const xa = left ? x0 - pad : x0
+ const xb = right ? x0 + n + pad : x0 + n
+ if (mby === 0) {
+ for (let y = 1; y <= pad; y++) copyBytes(p, org - y * stride + xa, p, org + xa, xb - xa)
+ }
+ if (mby === this.mbh - 1) {
+ const lastRow = org + (ph - 1) * stride
+ for (let y = 1; y <= pad; y++) copyBytes(p, lastRow + y * stride + xa, p, lastRow + xa, xb - xa)
+ }
+ }
+
+ unchangedMb(mbx: int, mby: int) {
+ const mb = mby * this.mbw + mbx
+ this.computeSkipMv(mbx, mby)
+ if (this.skipX === 0 && this.skipY === 0 && this.mbType[mb]! === MB_PSKIP && this.mvx[mb]! === 0 && this.mvy[mb]! === 0) {
+ return
+ }
+ this.cbp[mb] = 0
+ this.t8[mb] = 0
+ this.dcCbf[mb] = 0
+ for (let k = 0; k < 24; k++) this.nnz[mb * 24 + k] = 0
+ if (this.skipX === 0 && this.skipY === 0) {
+ this.setSkip(mb)
+ return
+ }
+ this.mbType[mb] = MB_P16
+ this.refIdx[mb] = 0
+ this.computeMvp(mbx, mby, 0)
+ this.mvx[mb] = 0
+ this.mvy[mb] = 0
+ this.mvdx[mb] = -this.mvpX
+ this.mvdy[mb] = -this.mvpY
+ }
+
+ probeIntra(frame: Uint8Array, frameOff: int, side: SideInfo | undefined) {
+ const o = this.opts
+ const qp = this.rate.probeQpValue()
+ const p = new Encoder({
+ width: o.width, height: o.height, fpsNum: o.fpsNum, fpsDen: o.fpsDen, qp, keyint: o.keyint, profile: o.profile,
+ preset: o.preset, cabac: o.cabac, refs: o.refs, rcMode: RC_CQP, crf: o.crf, bitrate: 0, maxrate: 0, bufsize: 0,
+ ipOffset: 0, weightedPred: o.weightedPred, worker: false,
+ })
+ p.rate.minQp = 0
+ p.threads = this.threads
+ p.vfr = false
+ p.aqStrength = this.aqStrength
+ p.aqTexture = this.aqTexture
+ p.noise = this.noise
+ p.idrSlices = this.idrSlices
+ p.sliceRowsI = this.sliceRowsI
+ this.rate.seedIntra(qp, p.encodeFrame(frame, frameOff, side).length * 8)
+ }
+
+ frameActivity(): int {
+ let a = 0
+ for (let mby = 0; mby < this.mbh; mby++) {
+ for (let mbx = 0; mbx < this.mbw; mbx++) a += mbActivity(this.srcY, mby * 16 * this.aw + mbx * 16, this.aw)
+ }
+ return a
+ }
+
+ encodeFrame(frame: Uint8Array, frameOff: int, side: SideInfo | undefined): u8[] {
+ const t0 = performance.now()
+ this.out = []
+ const idr = this.refs.length === 0 || this.sinceIdr >= this.keyint
+ const full = idr || this.fullAnalysis
+ this.filterRecon = !idr || this.keyint > 1 || this.idrReuse || this.wantRecon
+ let nChanged = this.analyse(frame, frameOff, side, full)
+ this.wpOn = false
+ this.wpChromaOn = false
+ if (!idr && this.params.weightedPred && this.refs.length > 0 && nChanged * 20 >= this.mbw * this.mbh * 19) {
+ nChanged = this.estimateWeights(frame, frameOff, nChanged)
+ }
+ let nRefresh = full ? 0 : this.markRefresh()
+ if (!full && nChanged === 0 && nRefresh === 0) nRefresh = this.markIdleRefine()
+ if (full || nChanged > 0 || nRefresh > 0) this.lastActive = this.frameIndex
+ const willDrop = !full && nChanged === 0 && nRefresh === 0 && this.vfr
+ if (!willDrop) {
+ const dt = this.lastCodedIndex < 0 ? 1 : this.frameIndex - this.lastCodedIndex
+ const act = idr && this.rcAct ? f64(this.frameActivity()) : 0.0
+ if (idr && this.rate.wantsProbe(act)) this.probeIntra(frame, frameOff, side)
+ this.frameQp = this.rate.frameQp(idr, act, idr ? this.mbw * this.mbh : nChanged + nRefresh, dt)
+ }
+ const left = idr ? this.keyint : this.keyint - this.sinceIdr
+ this.laOn = this.laNext
+ this.laHz = (left < this.laSpan ? left : this.laSpan) * LIFE_ONE
+ this.laNext = false
+ if (willDrop) {
+ this.updateHistory()
+ const td = performance.now()
+ this.tAnalysis += td - t0
+ this.frames.push({
+ index: this.frameIndex, type: "D", bytes: 0, qp: this.qp, changedMbs: 0, analysis: td - t0, motion: 0.0,
+ mode: 0.0, tq: 0.0, entropy: 0.0, deblock: 0.0, total: td - t0, reused: 0,
+ })
+ this.frameIndex++
+ this.sinceIdr++
+ return this.out
+ }
+ if (!full) this.holdChanged()
+ const parallel = this.threads > 1 && this.parallelWorth(idr)
+ this.textMbs = 0
+ if (!parallel) {
+ for (let mby = 0; mby < this.mbh; mby++) this.prepRow(frame, frameOff, mby, full, idr)
+ }
+ this.resetPacking()
+ this.reusedMbs = 0
+ if (idr && this.idrReuse) this.prepareIdrCache()
+ const t1 = performance.now()
+ if (idr) {
+ appendNal(&this.out, 3, 7, writeSps(this.params), true)
+ appendNal(&this.out, 3, 8, writePps(this.params), true)
+ this.frameNum = 0
+ while (this.refs.length > 0) this.spare.push(this.refs.pop()!)
+ this.sinceIdr = 0
+ }
+ this.sliceType = idr ? SLICE_I : SLICE_P
+ this.refsActive = this.refs.length < this.maxRefs ? (this.refs.length > 0 ? this.refs.length : 1) : this.maxRefs
+ this.refMarking(idr)
+ this.anchorQp = this.frameQp
+ const cabac = this.params.cabac
+ const rowsI = this.sliceRowsI > 0 ? this.sliceRowsI : this.idrSlices > 1 ? Math.trunc((this.mbh + this.idrSlices - 1) / this.idrSlices) : this.mbh
+ const rowsP = this.sliceRowsP > 0 ? this.sliceRowsP : this.mbh
+ const sliceRows = idr ? rowsI : rowsP
+ const mbs0 = this.mbw * this.mbh
+ let tmo = 0.0
+ let tmd = 0.0
+ let ttq = 0.0
+ let tent = 0.0
+ let tdb = 0.0
+ let tprep = 0.0
+ this.rMo = 0.0
+ this.rMd = 0.0
+ this.rTq = 0.0
+ this.rEnt = 0.0
+ this.rDb = 0.0
+ this.rPrep = 0.0
+ this.rUn = 0.0
+ this.tN = 0
+ this.tNs = 0
+ this.uN = 0
+ this.uNs = 0
+ const nSlices = Math.trunc((this.mbh + sliceRows - 1) / sliceRows)
+ if (parallel && idr && nSlices > 1) {
+ const tp = performance.now()
+ const sums = this.codeSlicesParallel(frame, frameOff, sliceRows, nSlices)
+ const span = performance.now() - tp
+ const sum = sums[0]! + sums[1]! + sums[2]! + sums[3]! + sums[4]! + sums[5]!
+ if (sum > 0.0) {
+ tmo = span * sums[0]! / sum
+ tmd = span * sums[1]! / sum
+ ttq = span * sums[2]! / sum
+ tent = span * sums[3]! / sum
+ tdb = span * sums[4]! / sum
+ tprep = span * sums[5]! / sum
+ }
+ } else if (parallel) {
+ const pipe = nSlices === 1
+ const peek = this.nextFrame.length > 0 && !this.fullAnalysis && this.sinceIdr + 1 < this.keyint &&
+ this.nextInputAnalysed()
+ const tp = performance.now()
+ const tPeek = this.codeFrameParallel(frame, frameOff, idr, full, sliceRows, pipe, peek)
+ const span = performance.now() - tp - tPeek
+ const sum = this.rMo + this.rMd + this.rTq + this.rEnt + this.rDb + this.rPrep
+ if (sum > 0.0) {
+ tmo = span * this.rMo / sum
+ tmd = span * this.rMd / sum
+ ttq = span * this.rTq / sum
+ tent = span * this.rEnt / sum
+ tdb = span * this.rDb / sum
+ tprep = span * this.rPrep / sum
+ }
+ tprep += tPeek
+ if (!pipe) {
+ const e0 = performance.now()
+ this.entropyParallel(idr, sliceRows)
+ tent += performance.now() - e0
+ }
+ } else {
+ const c0 = performance.now()
+ for (let mby = 0; mby < this.mbh; mby++) this.codeRow(mby, idr, sliceRows)
+ this.scaleTiming()
+ const span = performance.now() - c0
+ const sum = this.rMo + this.rMd + this.rTq
+ if (sum > 0.0) {
+ tmo = span * this.rMo / sum
+ tmd = span * this.rMd / sum
+ ttq = span * this.rTq / sum
+ } else {
+ tmd = span
+ }
+ const e0 = performance.now()
+ if (this.threads > 1 && sliceRows < this.mbh) {
+ this.entropyParallel(idr, sliceRows)
+ } else {
+ this.finishQpRows(sliceRows, 0, this.mbh)
+ this.entropyRows(idr, sliceRows, 0, this.mbh, &this.out)
+ }
+ tent = performance.now() - e0
+ }
+ this.sliceRow0 = 0
+ this.lastAnalysed = this.frameIndex
+ const t2 = performance.now()
+ this.counter++
+ for (let mb = 0; mb < mbs0; mb++) {
+ if (this.refresh[mb]! !== 0) this.changed[mb] = 2
+ }
+ if (idr && this.idrReuse) {
+ this.idrCache = true
+ this.compactIdrPool()
+ }
+ if (!parallel && this.filterRecon) this.deblockFrame(idr)
+ const t3 = performance.now()
+ tdb += t3 - t2
+ if (idr) this.idrPicId = (this.idrPicId + 1) & 1
+ this.cur.frameNum = this.frameNum
+ this.cur.id = this.codedFrames
+ this.genSeq++
+ this.cur.gen = this.genSeq
+ this.refs.unshift(this.cur)
+ const keep = this.pending.length > 0 ? this.dpbRefs : this.maxRefs
+ while (this.refs.length > keep) this.spare.push(this.refs.pop()!)
+ this.giveHalfPlanes(this.cur)
+ this.cur = this.spare.length > 0 ? this.spare.pop()! : this.newFrame()
+ const mbs = this.mbw * this.mbh
+ for (let mb = 0; mb < mbs; mb++) {
+ this.prevMvx[mb] = this.mvx[mb]!
+ this.prevMvy[mb] = this.mvy[mb]!
+ }
+ this.frameNum = (this.frameNum + 1) & ((1 << this.params.log2MaxFrameNum) - 1)
+ for (let mb = 0; mb < mbs; mb++) this.prevChanged[mb] = idr || this.changed[mb]! !== 1 ? 0 : 1
+ const t4 = performance.now()
+ this.tAnalysis += t1 - t0 + (t4 - t3) + tprep
+ this.tMotion += tmo
+ this.tMode += tmd
+ this.tTq += ttq
+ this.tEntropy += tent
+ this.tDeblock += tdb
+ this.frames.push({
+ index: this.frameIndex, type: idr ? "I" : "P", bytes: this.out.length, qp: this.frameQp,
+ changedMbs: idr ? mbs : nChanged, analysis: t1 - t0 + (t4 - t3) + tprep, motion: tmo, mode: tmd, tq: ttq,
+ entropy: tent, deblock: tdb, total: t4 - t0, reused: this.reusedMbs,
+ })
+ this.rate.update(idr, this.frameQp, this.out.length * 8, idr ? mbs : nChanged + nRefresh)
+ this.lastCodedIndex = this.frameIndex
+ this.frameIndex++
+ this.codedFrames++
+ this.sinceIdr++
+ return this.out
+ }
+
+ prepareIdrCache() {
+ const mbs = this.mbw * this.mbh
+ if (this.cType.length === 0) {
+ this.srcSame = new Uint8Array(mbs)
+ this.recSame = new Uint8Array(mbs)
+ this.idrSaved = new Int32Array(mbs)
+ this.idrSlotMb = new Int32Array(mbs)
+ this.idrPool = newPlane(mbs * 384)
+ this.idrRecY = newPlane(this.ysize)
+ this.idrRecU = newPlane(this.cs * (this.chh + 2 * PADC))
+ this.idrRecV = newPlane(this.cs * (this.chh + 2 * PADC))
+ this.cType = new Uint8Array(mbs)
+ this.cI16 = new Uint8Array(mbs)
+ this.cCMode = new Uint8Array(mbs)
+ this.cCbp = new Uint8Array(mbs)
+ this.cDcCbf = new Uint8Array(mbs)
+ this.cQp = new Uint8Array(mbs)
+ this.cImode = new Uint8Array(mbs * 16)
+ this.cNnz = new Uint8Array(mbs * 24)
+ this.cCoef = new Int8Array(this.mbh * this.cRow)
+ this.cMask = new Int64Array(mbs)
+ this.cOff = new Int32Array(mbs)
+ }
+ for (let i = 0; i < mbs; i++) this.recSame[i] = 0
+ if (!this.idrCache) {
+ for (let i = 0; i < mbs; i++) this.srcSame[i] = 0
+ return
+ }
+ for (let mby = 0; mby < this.mbh; mby++) {
+ for (let mbx = 0; mbx < this.mbw; mbx++) {
+ const mb = mby * this.mbw + mbx
+ const slot = this.idrSaved[mb]!
+ let same = true
+ if (slot !== 0) {
+ const yo = mby * 16 * this.aw + mbx * 16
+ const co = mby * 8 * this.cw + mbx * 8
+ const po = (slot - 1) * 384
+ same = !diffMb(this.srcY, yo, this.aw, this.idrPool, po, 16, 16, 16, this.noise)
+ if (same) same = !diffMb(this.srcU, co, this.cw, this.idrPool, po + 256, 8, 8, 8, this.noise)
+ if (same) same = !diffMb(this.srcV, co, this.cw, this.idrPool, po + 320, 8, 8, 8, this.noise)
+ }
+ this.srcSame[mb] = same ? 1 : 0
+ }
+ }
+ }
+
+ idrReuseLevel(mb: int, mbx: int, mby: int): int {
+ if (!this.idrCache || this.srcSame[mb]! === 0 || this.cQp[mb]! > this.mbq) return 0
+ let rec = true
+ if (mbx > 0) {
+ if (this.srcSame[mb - 1]! === 0) return 0
+ if (this.recSame[mb - 1]! === 0) rec = false
+ }
+ if (mby > this.sliceRow0) {
+ const t = mb - this.mbw
+ if (this.srcSame[t]! === 0) return 0
+ if (this.recSame[t]! === 0) rec = false
+ if (mbx > 0) {
+ if (this.srcSame[t - 1]! === 0) return 0
+ if (this.recSame[t - 1]! === 0) rec = false
+ }
+ if (mbx + 1 < this.mbw) {
+ if (this.srcSame[t + 1]! === 0) return 0
+ if (this.recSame[t + 1]! === 0) rec = false
+ }
+ }
+ return rec ? 2 : 1
+ }
+
+ restoreIdrDecisions(mb: int) {
+ const t = this.cType[mb]!
+ this.mbType[mb] = t
+ this.refIdx[mb] = -1
+ this.i16Mode[mb] = this.cI16[mb]!
+ this.cMode[mb] = this.cCMode[mb]!
+ this.mvx[mb] = 0
+ this.mvy[mb] = 0
+ this.mvdx[mb] = 0
+ this.mvdy[mb] = 0
+ u8x16.load(this.cImode, mb * 16).store(this.imode, mb * 16)
+ this.mbq = this.cQp[mb]!
+ this.mbQp[mb] = this.mbq
+ }
+
+ beginIdrRow(mby: int) {
+ this.rowAt = 0
+ if (!this.idrCache) return
+ const mb0 = mby * this.mbw
+ const row = mby * this.cRow
+ for (let mbx = 0; mbx < this.mbw; mbx++) {
+ const mb = mb0 + mbx
+ if (!this.mayRestoreCoding(mb, mbx, mby)) continue
+ if (this.rowOld.length === 0) this.rowOld = new Int8Array(this.cRow)
+ const o = this.cOff[mb]!
+ const n = this.cBytes(mb)
+ for (let k = 0; k < n; k += 16) u8x16.load(this.cCoef, row + o + k).store(this.rowOld, o + k)
+ }
+ }
+
+ cBytes(mb: int): int {
+ const g = this.cMask[mb]!
+ return g < 0 ? (Math.popcount64(g) - 1) * 16 : Math.popcount64(g) * 8
+ }
+
+ mayRestoreCoding(mb: int, mbx: int, mby: int): bool {
+ if (this.srcSame[mb]! === 0) return false
+ if (mbx > 0 && this.srcSame[mb - 1]! === 0) return false
+ if (mby > this.sliceRow0) {
+ const t = mb - this.mbw
+ if (this.srcSame[t]! === 0) return false
+ if (mbx > 0 && this.srcSame[t - 1]! === 0) return false
+ if (mbx + 1 < this.mbw && this.srcSame[t + 1]! === 0) return false
+ }
+ return true
+ }
+
+ restoreIdrCoding(mb: int, mbx: int, mby: int) {
+ this.reusedMbs++
+ this.cbp[mb] = this.cCbp[mb]!
+ this.dcCbf[mb] = this.cDcCbf[mb]!
+ this.t8[mb] = this.cType[mb]! === MB_I8 ? 1 : 0
+ u8x16.load(this.cNnz, mb * 24).store(this.nnz, mb * 24)
+ u8x16.load(this.cNnz, mb * 24 + 8).store(this.nnz, mb * 24 + 8)
+ const yo = this.ry(mbx * 16, mby * 16)
+ const uo = this.rc(mbx * 8, mby * 8)
+ copyRect(this.cur.y, yo, this.ys, this.idrRecY, yo, this.ys, 16, 16)
+ copyRect(this.cur.u, uo, this.cs, this.idrRecU, uo, this.cs, 8, 8)
+ copyRect(this.cur.v, uo, this.cs, this.idrRecV, uo, this.cs, 8, 8)
+ }
+
+ packSize(): int {
+ return (Math.trunc((this.mbw * this.mbh * COEF_PER_MB - 1) / (PK_BLOCK - COEF_PER_MB)) + this.threads + 2) * PK_BLOCK
+ }
+
+ resetPacking() {
+ const size = this.packSize()
+ if (this.pkCoef.length < size) this.pkCoef = new Int16Array(size)
+ this.pkTop[0] = 0
+ this.pkW = 0
+ this.pkEnd = 0
+ }
+
+ packCoef(mb: int) {
+ let m = CHUNKS[(this.mbType[mb]! === MB_I16 ? 128 : this.t8[mb]! * 64) + this.cbp[mb]!]!
+ if (m === 0) return
+ this.pkMask[mb] = m
+ const n = Math.popcount32(m) * 32
+ if (this.pkW + n > this.pkEnd) {
+ this.pkW = Atomics.add(this.pkTop, 0, PK_BLOCK)
+ this.pkEnd = this.pkW + PK_BLOCK
+ }
+ let w = this.pkW
+ this.pkW = w + n
+ this.pkOff[mb] = w
+ while (m !== 0) {
+ i16x32.load(this.coef, Math.ctz32(m) * 32).store(this.pkCoef, w)
+ w += 32
+ m &= m - 1
+ }
+ }
+
+ loadCoef(mb: int, mby: int, t: int, cbp: int) {
+ if (this.sliceType === SLICE_I && this.idrReuse) {
+ let m = CHUNKS[(t === MB_I16 ? 128 : this.t8[mb]! * 64) + cbp]!
+ const zero = i16x32.splat(0)
+ while (m !== 0) {
+ zero.store(this.coef, Math.ctz32(m) * 32)
+ m &= m - 1
+ }
+ let g = this.cMask[mb]!
+ let r = mby * this.cRow + this.cOff[mb]!
+ if (g >= 0) {
+ while (g !== 0) {
+ i16x8.loadI8(this.cCoef, r).store(this.coef, Math.ctz64(g) * 8)
+ r += 8
+ g &= g - 1
+ }
+ return
+ }
+ g &= 0xfffffffffffff
+ while (g !== 0) {
+ ((i16x8.loadI8(this.cCoef, r + 8) << 8) | i16x8.loadU8(this.cCoef, r)).store(this.coef, Math.ctz64(g) * 8)
+ r += 16
+ g &= g - 1
+ }
+ return
+ }
+ let m = this.pkMask[mb]!
+ let r = this.pkOff[mb]!
+ while (m !== 0) {
+ i16x32.load(this.pkCoef, r).store(this.coef, Math.ctz32(m) * 32)
+ r += 32
+ m &= m - 1
+ }
+ }
+
+ sameRecon(mbx: int, mby: int): bool {
+ const yo = this.ry(mbx * 16, mby * 16)
+ const uo = this.rc(mbx * 8, mby * 8)
+ if (diffMb(this.cur.y, yo, this.ys, this.idrRecY, yo, this.ys, 16, 16, 0)) return false
+ if (diffMb(this.cur.u, uo, this.cs, this.idrRecU, uo, this.cs, 8, 8, 0)) return false
+ return !diffMb(this.cur.v, uo, this.cs, this.idrRecV, uo, this.cs, 8, 8, 0)
+ }
+
+ storeIdrMb(mb: int, mbx: int, mby: int, level: int) {
+ const row = mby * this.cRow
+ if (level === 2) {
+ this.recSame[mb] = 1
+ const n = this.cBytes(mb)
+ const o = this.cOff[mb]!
+ const at = row + this.rowAt
+ for (let k = 0; k < n; k += 16) u8x16.load(this.rowOld, o + k).store(this.cCoef, at + k)
+ this.cOff[mb] = this.rowAt
+ this.rowAt += n
+ return
+ }
+ this.recSame[mb] = this.idrCache && this.sameRecon(mbx, mby) ? 1 : 0
+ this.cType[mb] = this.mbType[mb]!
+ this.cI16[mb] = this.i16Mode[mb]!
+ this.cCMode[mb] = this.cMode[mb]!
+ this.cCbp[mb] = this.cbp[mb]!
+ this.cDcCbf[mb] = this.dcCbf[mb]!
+ this.cQp[mb] = this.mbq
+ u8x16.load(this.imode, mb * 16).store(this.cImode, mb * 16)
+ u8x16.load(this.nnz, mb * 24).store(this.cNnz, mb * 24)
+ u8x16.load(this.nnz, mb * 24 + 8).store(this.cNnz, mb * 24 + 8)
+ this.cOff[mb] = this.rowAt
+ this.rowAt += this.storeIdrCoef(mb, row + this.rowAt)
+ const yo = this.ry(mbx * 16, mby * 16)
+ const uo = this.rc(mbx * 8, mby * 8)
+ copyRect(this.idrRecY, yo, this.ys, this.cur.y, yo, this.ys, 16, 16)
+ copyRect(this.idrRecU, uo, this.cs, this.cur.u, uo, this.cs, 8, 8)
+ copyRect(this.idrRecV, uo, this.cs, this.cur.v, uo, this.cs, 8, 8)
+ if (level === 0) this.idrSaved[mb] = 0
+ }
+
+ storeIdrCoef(mb: int, at: int): int {
+ const zero = i16x32.splat(0)
+ let mask = 0
+ for (let q = 0; q < COEF_PER_MB >> 5; q++) {
+ const nz = ~i16x32.load(this.coef, q * 32).eq(zero).mask() & 0xffffffff
+ let t = nz | (nz >> 4)
+ t |= t >> 2
+ t |= t >> 1
+ mask |= ((((t & 0x01010101) * 0x204081) >> 21) & 15) << (q * 4)
+ }
+ this.cMask[mb] = mask
+ let w = at
+ let m = mask
+ let hi = i8x16.splat(0)
+ let lo = hi
+ while (m !== 0) {
+ const v = i16x8.load(this.coef, Math.ctz64(m) * 8)
+ m &= m - 1
+ const p = i8x16.packSat(v, i16x8.load(this.coef, Math.ctz64(m | 0x8000000000000) * 8))
+ p.store(this.cCoef, w)
+ hi = hi.max(p)
+ lo = lo.min(p)
+ w += 16
+ m &= m - 1
+ }
+ if (hi.eq(i8x16.splat(127)).mask() === 0 && lo.eq(i8x16.splat(-128)).mask() === 0) return Math.popcount64(mask) * 8
+ this.cMask[mb] = mask | (1 << 63)
+ w = at
+ m = mask
+ const bytes = i16x8.splat(255)
+ while (m !== 0) {
+ const v = i16x8.load(this.coef, Math.ctz64(m) * 8)
+ u8x16.packSat(v & bytes, v).store(this.cCoef, w)
+ i8x16.packSat(v >> 8, v).store(this.cCoef, w + 8)
+ w += 16
+ m &= m - 1
+ }
+ return w - at
+ }
+
+ beginSlice(idr: bool, row0: int) {
+ this.sliceRow0 = row0
+ const bw = this.bw
+ bw.reset()
+ const sp: SliceParams = {
+ idr, sliceType: this.sliceType, frameNum: this.frameNum, idrPicId: this.idrPicId, qpDelta: this.frameQp - 26,
+ refsActive: this.refsActive, deblock: this.deblock ? 0 : 1, alphaOffset: 0, betaOffset: 0, cabacInitIdc: 0,
+ firstMb: row0 * this.mbw, wpLuma: this.wpOn && this.wpY.length > 0 && !idr, wpChroma: this.wpChromaOn && !idr,
+ wp: [this.wpY[0]!, this.wpY[1]!, this.wpU[0]!, this.wpU[1]!, this.wpV[0]!, this.wpV[1]!],
+ poc: 2 * (this.frameIndex - this.pocBase), nalRef: this.nalRef, reorder: this.l0Reorder, mmco: this.mmco,
+ }
+ writeSliceHeader(bw, this.params, sp)
+ if (this.params.cabac) {
+ while (!bw.aligned()) bw.putBit(1)
+ this.cabac.init(this.frameQp, idr, 0)
+ }
+ this.skipRun = 0
+ this.qpPred = this.frameQp
+ this.lastDeltaNz = false
+ }
+
+ endSlice(idr: bool, inout out: u8[]) {
+ const bw = this.bw
+ const refIdc = idr ? 3 : this.sliceType === SLICE_B && !this.nalRef ? 0 : 2
+ if (this.params.cabac) {
+ appendNalBytes(&out, refIdc, idr ? 5 : 1, bw.buf, this.cabac.out, this.cabac.len)
+ return
+ }
+ if (this.skipRun > 0) bw.ue(this.skipRun)
+ bw.trailing()
+ appendNal(&out, refIdc, idr ? 5 : 1, bw.buf, true)
+ }
+
+ finishQpRows(sliceRows: int, r0: int, r1: int) {
+ for (let mby = r0; mby < r1; mby++) {
+ if (mby % sliceRows === 0) this.qpPred = this.frameQp
+ for (let mbx = 0; mbx < this.mbw; mbx++) this.finishQp(mby * this.mbw + mbx)
+ }
+ }
+
+ entropyRows(idr: bool, sliceRows: int, r0: int, r1: int, inout out: u8[]) {
+ for (let mby = r0; mby < r1; mby++) this.entropyRow(idr, sliceRows, mby, &out)
+ this.sliceRow0 = 0
+ }
+
+ entropyRow(idr: bool, sliceRows: int, mby: int, inout out: u8[]) {
+ const cabac = this.params.cabac
+ if (mby % sliceRows === 0) this.beginSlice(idr, mby)
+ this.sliceRow0 = mby - mby % sliceRows
+ const lastRow = (mby + 1) % sliceRows === 0 || mby === this.mbh - 1
+ if (cabac) {
+ this.writeRowCabac(mby, lastRow)
+ } else {
+ for (let mbx = 0; mbx < this.mbw; mbx++) this.writeMbCavlc(mbx, mby)
+ }
+ if (lastRow) this.endSlice(idr, &out)
+ }
+
+ entropyReady(): bool {
+ const keep = this.sliceRow0
+ let did = false
+ while (this.pipeEnt < this.mbh) {
+ const at = this.pipeEnt * ROW_SLOT
+ if (Atomics.load(this.pipeProgress, at) <= this.mbw) break
+ const t = performance.now()
+ this.entropyRow(this.pipeIdr, this.pipeSliceRows, this.pipeEnt, &this.out)
+ this.rEnt += performance.now() - t
+ this.pipeEnt++
+ did = true
+ }
+ this.sliceRow0 = keep
+ return did
+ }
+
+ workerOpts(): EncoderOptions {
+ return {
+ width: this.opts.width, height: this.opts.height, fpsNum: this.opts.fpsNum, fpsDen: this.opts.fpsDen,
+ qp: this.opts.qp, keyint: this.opts.keyint, profile: this.opts.profile, preset: this.opts.preset,
+ cabac: this.opts.cabac, refs: this.opts.refs, rcMode: this.opts.rcMode, crf: this.opts.crf,
+ bitrate: this.opts.bitrate, maxrate: this.opts.maxrate, bufsize: this.opts.bufsize, ipOffset: this.opts.ipOffset,
+ weightedPred: this.opts.weightedPred, worker: true,
+ }
+ }
+
+ entropyParallel(idr: bool, sliceRows: int) {
+ const sh = this.shareState()
+ const fp = this.frameParams()
+ const opts = this.workerOpts()
+ const mbh = this.mbh
+ let threads: Thread<u8[]>[] = []
+ for (let r0 = 0; r0 < mbh; r0 += sliceRows) {
+ const r1 = r0 + sliceRows < mbh ? r0 + sliceRows : mbh
+ threads.push(Thread.spawn(() => {
+ const w = new Encoder(opts)
+ w.attach(sh, fp)
+ let out: u8[] = []
+ w.finishQpRows(sliceRows, r0, r1)
+ w.entropyRows(idr, sliceRows, r0, r1, &out)
+ return out
+ }))
+ }
+ for (const t of threads) {
+ const part = t.join()
+ for (const b of part) this.out.push(b)
+ }
+ }
+
+ qpRow(mby: int, sliceRows: int, progress: Int32Array) {
+ const mbw = this.mbw
+ if (mby % sliceRows === 0) {
+ this.qpPred = this.frameQp
+ } else {
+ this.waitRow(progress, mby - 1, mbw + 1)
+ this.qpPred = this.qpY[mby * mbw - 1]!
+ }
+ for (let mbx = 0; mbx < mbw; mbx++) this.finishQp(mby * mbw + mbx)
+ if (this.qpRows.length > 0) publishRows(this.qpRows, mby + 1)
+ publish(progress, mby, mbw + 1)
+ }
+
+ awaitRows(rows: Int32Array, need: int) {
+ // publishRows only wakes the entropy thread once `wake` rows are ready: it then sleeps about once per
+ // ENTROPY_BATCH rows instead of once per row, and per row near the end so the frame's tail is not delayed.
+ const wake = need + ENTROPY_BATCH < this.mbh ? need + ENTROPY_BATCH - 1 : need
+ const start = performance.now()
+ while (Atomics.load(rows, 0) < need) {
+ if (performance.now() - start < SPIN_MIN_MS) {
+ Atomics.pause()
+ continue
+ }
+ Atomics.store(rows, 2, wake)
+ Atomics.add(rows, 1, 1)
+ const seen = Atomics.load(rows, 0)
+ if (seen < need) Atomics.wait(rows, 0, seen, 1)
+ Atomics.sub(rows, 1, 1)
+ }
+ }
+
+ deblockRowWave(mby: int, full: bool, dbp: Int32Array) {
+ const mbw = this.mbw
+ for (let mbx = 0; mbx < mbw; mbx++) {
+ if (this.dbNeed(mbx, mby, full)) {
+ if (mby > 0) this.waitRow(dbp, mby - 1, mbx + 2 < mbw ? mbx + 2 : mbw)
+ this.deblockMb(mbx, mby)
+ }
+ publish(dbp, mby, mbx + 1)
+ }
+ }
+
+ closeRow(mby: int, full: bool, ver: int, dbp: Int32Array) {
+ if (!this.filterRecon) return
+ if (this.deblock) this.deblockRowWave(mby, full, dbp)
+ if (mby > 0) {
+ if (this.deblock) this.waitRow(dbp, mby - 1, this.mbw)
+ this.finalizeRow(mby - 1, full, ver)
+ }
+ if (mby === this.mbh - 1) this.finalizeRow(mby, full, ver)
+ }
+
+ finishRow(mby: int, sliceRows: int, full: bool, ver: int, progress: Int32Array, dbp: Int32Array) {
+ this.qpRow(mby, sliceRows, progress)
+ const t = performance.now()
+ if (mby > 0) {
+ if (mby % sliceRows === 0) this.waitRow(progress, mby - 1, this.mbw + 1)
+ this.closeRow(mby - 1, full, ver, dbp)
+ }
+ if (mby === this.mbh - 1) this.closeRow(mby, full, ver, dbp)
+ this.rDb += performance.now() - t
+ }
+
+ timedMb(coded: bool): bool {
+ if (coded) {
+ const s = (this.tN & 7) === 0
+ this.tN++
+ if (s) this.tNs++
+ return s
+ }
+ const s = (this.uN & 7) === 0
+ this.uN++
+ if (s) this.uNs++
+ return s
+ }
+
+ scaleTiming() {
+ const k = this.tNs > 0 ? f64(this.tN) / f64(this.tNs) : 0.0
+ const ku = this.uNs > 0 ? f64(this.uN) / f64(this.uNs) : 0.0
+ this.rMo *= k
+ this.rMd = this.rMd * k + this.rUn * ku
+ this.rTq *= k
+ }
+
+ codeMbAt(mbx: int, mby: int, idr: bool) {
+ const mb = mby * this.mbw + mbx
+ if (this.sliceType === SLICE_B) {
+ this.codeMbB(mbx, mby)
+ this.packCoef(mb)
+ return
+ }
+ if (!idr && this.changed[mb]! === 0 && this.refresh[mb]! === 0) {
+ if (!this.timedMb(false)) {
+ this.unchangedMb(mbx, mby)
+ return
+ }
+ const t0 = performance.now()
+ this.unchangedMb(mbx, mby)
+ this.rUn += performance.now() - t0
+ return
+ }
+ this.mbq = this.mbQp[mb]!
+ const timed = this.timedMb(true)
+ const a = timed ? performance.now() : 0.0
+ let b = a
+ let skipped = false
+ this.skipProbed = false
+ if (!idr) {
+ if (this.refresh[mb]! !== 0) {
+ this.zeroMotion(mbx, mby)
+ } else if (this.earlySkip && this.earlySkipMb(mbx, mby)) {
+ skipped = true
+ } else {
+ this.motionSearch(mbx, mby)
+ }
+ if (timed) b = performance.now()
+ }
+ let level = 0
+ if (idr) {
+ if (mbx === 0 && this.idrReuse) this.beginIdrRow(mby)
+ level = this.idrReuseLevel(mb, mbx, mby)
+ if (level === 0) {
+ this.decideIntra(mbx, mby, BIG)
+ this.commitIntra(mb, mbx, mby)
+ } else {
+ this.restoreIdrDecisions(mb)
+ }
+ } else if (!skipped) {
+ this.decideInter(mbx, mby)
+ }
+ const c = timed ? performance.now() : 0.0
+ if (level === 2) {
+ this.restoreIdrCoding(mb, mbx, mby)
+ } else {
+ this.codeMb(mbx, mby)
+ }
+ if (idr && this.idrReuse) {
+ this.storeIdrMb(mb, mbx, mby, level)
+ } else {
+ this.packCoef(mb)
+ }
+ if (timed) {
+ const d = performance.now()
+ this.rMo += b - a
+ this.rMd += c - b
+ this.rTq += d - c
+ }
+ }
+
+ codeRow(mby: int, idr: bool, sliceRows: int) {
+ this.sliceRow0 = mby - mby % sliceRows
+ for (let mbx = 0; mbx < this.mbw; mbx++) this.codeMbAt(mbx, mby, idr)
+ this.sliceRow0 = 0
+ }
+
+ // The spin budget restarts whenever the row moves. A step of the row that outlasts the budget doubles it if it
+ // still arrived within SPIN_MAX_MS (spinning longer would have caught it without a sleep and a wake-up) and
+ // halves it otherwise (a producer that stalls that long was descheduled or is waiting itself): on a busy host
+ // the budget falls to SPIN_MIN_MS and the CPU goes to other work.
+ waitRow(progress: Int32Array, row: int, need: int) {
+ const at = row * ROW_SLOT
+ let last = Atomics.load(progress, at)
+ if (last >= need) return
+ let since = performance.now()
+ let overran = false
+ let timeout = 1
+ while (true) {
+ if (this.pipeMain && this.entropyReady()) {
+ since = performance.now()
+ overran = false
+ } else if (performance.now() - since < this.spinMs) {
+ Atomics.pause()
+ } else {
+ overran = true
+ Atomics.add(progress, at + 1, 1)
+ const seen = Atomics.load(progress, at)
+ if (seen < need && Atomics.wait(progress, at, seen, timeout) === "timed-out" && timeout < SLEEP_MAX_MS) timeout *= 2
+ Atomics.sub(progress, at + 1, 1)
+ }
+ const v = Atomics.load(progress, at)
+ if (v === last) continue
+ const now = performance.now()
+ if (overran) {
+ this.spinMs = now - since < SPIN_MAX_MS ? Math.min(this.spinMs * 2, SPIN_MAX_MS) :
+ Math.max(this.spinMs / 2, SPIN_MIN_MS)
+ }
+ if (v >= need) return
+ last = v
+ since = now
+ overran = false
+ }
+ }
+
+ spinBudgets(): Float64Array {
+ if (this.spinBudget.length !== this.threads) {
+ this.spinBudget = new Float64Array(this.threads)
+ this.spinBudget.fill(SPIN_MAX_MS)
+ }
+ return this.spinBudget
+ }
+
+ codeRowWave(mby: int, idr: bool, sliceRows: int, progress: Int32Array) {
+ this.sliceRow0 = mby - mby % sliceRows
+ const mbw = this.mbw
+ for (let mbx = 0; mbx < mbw; mbx++) {
+ if (mby > this.sliceRow0) this.waitRow(progress, mby - 1, mbx + 2 < mbw ? mbx + 2 : mbw)
+ this.codeMbAt(mbx, mby, idr)
+ publish(progress, mby, mbx + 1)
+ }
+ this.sliceRow0 = 0
+ }
+
+ parallelWorth(idr: bool): bool {
+ const mbs = this.mbw * this.mbh
+ if (this.mbh < 8) return false
+ if (idr) return true
+ let n = 0
+ for (let i = 0; i < mbs; i++) {
+ if (this.changed[i]! !== 0 || this.refresh[i]! !== 0) n++
+ }
+ return n * 4 >= mbs
+ }
+
+ shareState(): SharedState {
+ let refY: Uint8Array[] = []
+ let refU: Uint8Array[] = []
+ let refV: Uint8Array[] = []
+ let refHb: Uint8Array[] = []
+ let refHh: Uint8Array[] = []
+ let refHj: Uint8Array[] = []
+ let refTiles: Int32Array[] = []
+ let refVer: Int32Array[] = []
+ for (const rf of this.refs) {
+ refVer.push(rf.ver)
+ refY.push(rf.y)
+ refU.push(rf.u)
+ refV.push(rf.v)
+ refHb.push(rf.hb)
+ refHh.push(rf.hh)
+ refHj.push(rf.hj)
+ refTiles.push(rf.tileGen)
+ }
+ return {
+ srcY: this.srcY, srcU: this.srcU, srcV: this.srcV, curY: this.cur.y, curU: this.cur.u, curV: this.cur.v,
+ refY, refU, refV, refHb, refHh, refHj, refTiles, wref: this.wref, curVer: this.cur.ver, refVer,
+ lastChange: this.lastChange, streak: this.streak, mbClass: this.mbClass,
+ changed: this.changed, refresh: this.refresh, mbQp: this.mbQp, codedQp: this.codedQp, mbType: this.mbType,
+ i16Mode: this.i16Mode, cMode: this.cMode, imode: this.imode, t8: this.t8, cbp: this.cbp, dcCbf: this.dcCbf, nnz: this.nnz,
+ mvx: this.mvx, mvy: this.mvy, refIdx: this.refIdx, mvdx: this.mvdx, mvdy: this.mvdy, prevMvx: this.prevMvx,
+ prevMvy: this.prevMvy, pkCoef: this.pkCoef, pkMask: this.pkMask, pkOff: this.pkOff, pkTop: this.pkTop, qpY: this.qpY, qpDelta: this.qpDelta, srcSame: this.srcSame, recSame: this.recSame, cType: this.cType,
+ cI16: this.cI16, cCMode: this.cCMode, cCbp: this.cCbp, cDcCbf: this.cDcCbf, cQp: this.cQp, cImode: this.cImode,
+ cNnz: this.cNnz, cCoef: this.cCoef, cMask: this.cMask, cOff: this.cOff, idrSaved: this.idrSaved, idrSlotMb: this.idrSlotMb, idrPool: this.idrPool, idrTop: this.idrTop,
+ idrRecY: this.idrRecY, idrRecU: this.idrRecU, idrRecV: this.idrRecV, mvx1: this.mvx1, mvy1: this.mvy1,
+ refIdx1: this.refIdx1, mvdx1: this.mvdx1, mvdy1: this.mvdy1, colMvx: this.colMvx, colMvy: this.colMvy,
+ colRef: this.colRef,
+ }
+ }
+
+ frameParams(): FrameParams {
+ let refGen: int[] = []
+ for (const rf of this.refs) refGen.push(rf.gen)
+ return {
+ sliceType: this.sliceType, refsActive: this.refsActive, refGen, wpOn: this.wpOn, wpChromaOn: this.wpChromaOn,
+ wpY: this.wpY, wpU: this.wpU, wpV: this.wpV, shiftHx: this.shiftHx, shiftVy: this.shiftVy,
+ scrollMvx: this.scrollMvx, scrollMvy: this.scrollMvy, scrollMb0: this.scrollMb0, scrollMb1: this.scrollMb1,
+ cursorMvx: this.cursorMvx, cursorMvy: this.cursorMvy, cursorMb: this.cursorMb, idrCache: this.idrCache,
+ idrReuse: this.idrReuse, frameNum: this.frameNum, idrPicId: this.idrPicId, frameQp: this.frameQp,
+ deblock: this.deblock, filterRecon: this.filterRecon, counter: this.counter, bTb: this.bTb, bTd: this.bTd,
+ bTdCol: this.bTdCol, pocBase: this.pocBase, frameIndex: this.frameIndex, params: this.params,
+ refreshDelta: this.refreshDelta, lifetimeAq: this.lifetimeAq, lastAnalysed: this.lastAnalysed,
+ textMbs: this.textMbs, laLife: this.laLife, laOn: this.laOn, laHz: this.laHz, laStrength: this.laStrength,
+ nalRef: this.nalRef, l0Reorder: this.l0Reorder, mmco: this.mmco,
+ }
+ }
+
+ attach(sh: SharedState, fp: FrameParams) {
+ this.srcY = sh.srcY
+ this.srcU = sh.srcU
+ this.srcV = sh.srcV
+ const cur = new RefFrame()
+ cur.y = sh.curY
+ cur.u = sh.curU
+ cur.v = sh.curV
+ cur.ver = sh.curVer
+ this.cur = cur
+ this.refs = []
+ for (let k = 0; k < sh.refY.length; k++) {
+ const rf = new RefFrame()
+ rf.y = sh.refY[k]!
+ rf.u = sh.refU[k]!
+ rf.v = sh.refV[k]!
+ rf.hb = sh.refHb[k]!
+ rf.hh = sh.refHh[k]!
+ rf.hj = sh.refHj[k]!
+ rf.tileGen = sh.refTiles[k]!
+ rf.ver = sh.refVer[k]!
+ rf.gen = fp.refGen[k]!
+ this.refs.push(rf)
+ }
+ this.wref = sh.wref
+ this.lastChange = sh.lastChange
+ this.streak = sh.streak
+ this.changed = sh.changed
+ this.refresh = sh.refresh
+ this.mbClass = sh.mbClass
+ this.mbQp = sh.mbQp
+ this.codedQp = sh.codedQp
+ this.mbType = sh.mbType
+ this.i16Mode = sh.i16Mode
+ this.cMode = sh.cMode
+ this.imode = sh.imode
+ this.t8 = sh.t8
+ this.cbp = sh.cbp
+ this.dcCbf = sh.dcCbf
+ this.nnz = sh.nnz
+ this.mvx = sh.mvx
+ this.mvy = sh.mvy
+ this.refIdx = sh.refIdx
+ this.mvdx = sh.mvdx
+ this.mvdy = sh.mvdy
+ this.prevMvx = sh.prevMvx
+ this.prevMvy = sh.prevMvy
+ this.pkCoef = sh.pkCoef
+ this.pkOff = sh.pkOff
+ this.pkMask = sh.pkMask
+ this.pkTop = sh.pkTop
+ this.qpY = sh.qpY
+ this.qpDelta = sh.qpDelta
+ this.srcSame = sh.srcSame
+ this.recSame = sh.recSame
+ this.cType = sh.cType
+ this.cI16 = sh.cI16
+ this.cCMode = sh.cCMode
+ this.cCbp = sh.cCbp
+ this.cDcCbf = sh.cDcCbf
+ this.cQp = sh.cQp
+ this.cImode = sh.cImode
+ this.cNnz = sh.cNnz
+ this.cCoef = sh.cCoef
+ this.cMask = sh.cMask
+ this.cOff = sh.cOff
+ this.idrSaved = sh.idrSaved
+ this.idrSlotMb = sh.idrSlotMb
+ this.idrPool = sh.idrPool
+ this.idrTop = sh.idrTop
+ this.idrRecY = sh.idrRecY
+ this.idrRecU = sh.idrRecU
+ this.idrRecV = sh.idrRecV
+ this.mvx1 = sh.mvx1
+ this.mvy1 = sh.mvy1
+ this.refIdx1 = sh.refIdx1
+ this.mvdx1 = sh.mvdx1
+ this.mvdy1 = sh.mvdy1
+ this.colMvx = sh.colMvx
+ this.colMvy = sh.colMvy
+ this.colRef = sh.colRef
+ this.sliceType = fp.sliceType
+ this.refsActive = fp.refsActive
+ this.wpOn = fp.wpOn
+ this.wpChromaOn = fp.wpChromaOn
+ this.wpY = fp.wpY
+ this.wpU = fp.wpU
+ this.wpV = fp.wpV
+ this.shiftHx = fp.shiftHx
+ this.shiftVy = fp.shiftVy
+ this.scrollMvx = fp.scrollMvx
+ this.scrollMvy = fp.scrollMvy
+ this.scrollMb0 = fp.scrollMb0
+ this.scrollMb1 = fp.scrollMb1
+ this.cursorMvx = fp.cursorMvx
+ this.cursorMvy = fp.cursorMvy
+ this.cursorMb = fp.cursorMb
+ this.idrCache = fp.idrCache
+ this.idrReuse = fp.idrReuse
+ this.frameNum = fp.frameNum
+ this.idrPicId = fp.idrPicId
+ this.frameQp = fp.frameQp
+ this.deblock = fp.deblock
+ this.filterRecon = fp.filterRecon
+ this.counter = fp.counter
+ this.bTb = fp.bTb
+ this.bTd = fp.bTd
+ this.bTdCol = fp.bTdCol
+ this.pocBase = fp.pocBase
+ this.frameIndex = fp.frameIndex
+ this.params = fp.params
+ this.refreshDelta = fp.refreshDelta
+ this.lifetimeAq = fp.lifetimeAq
+ this.lastAnalysed = fp.lastAnalysed
+ this.textMbs = fp.textMbs
+ this.laLife = fp.laLife
+ this.laOn = fp.laOn
+ this.laHz = fp.laHz
+ this.laStrength = fp.laStrength
+ this.nalRef = fp.nalRef
+ this.l0Reorder = fp.l0Reorder
+ this.mmco = fp.mmco
+ this.sharedTiles = true
+ }
+
+ halfTileRow(y: Uint8Array, hb: Uint8Array, hh: Uint8Array, hj: Uint8Array, tileGen: Int32Array, gen: int, row: int) {
+ const tx = this.tilesX
+ for (let c = 0; c < tx; c++) {
+ computeHalfTile(hb, hh, hj, y, this.ys, this.ytile + row * 16 * this.ys + c * 16)
+ tileGen[row * tx + c] = gen
+ }
+ }
+
+ storeCol(cmx: Int32Array, cmy: Int32Array, cref: Int32Array) {
+ const mbs = this.mbw * this.mbh
+ for (let mb = 0; mb < mbs; mb++) {
+ const l0 = this.refIdx[mb]! >= 0
+ const intra = this.isIntra(mb)
+ cref[mb] = intra ? -1 : l0 ? this.refIdx[mb]! : this.refIdx1[mb]!
+ cmx[mb] = intra ? 0 : l0 ? this.mvx[mb]! : this.mvx1[mb]!
+ cmy[mb] = intra ? 0 : l0 ? this.mvy[mb]! : this.mvy1[mb]!
+ }
+ }
+
+ tuning(): int[] {
+ return [this.inter8x8 ? 1 : 0, this.decimate ? 1 : 0, this.subpel, this.subpelDirs, this.meIters,
+ this.earlyExit ? 1 : 0, this.globalShift ? 1 : 0, this.useI4 ? 1 : 0, this.aqStrength, this.aqTexture,
+ this.earlySkip ? 1 : 0, this.hpelSad ? 1 : 0, this.qpelSad ? 1 : 0, this.videoHpelDirs, this.videoQpelDirs,
+ this.i8PredOnly ? 1 : 0, this.noise, this.bDirectNb]
+ }
+
+ tune(t: int[]) {
+ this.inter8x8 = t[0]! === 1
+ this.decimate = t[1]! === 1
+ this.subpel = t[2]!
+ this.subpelDirs = t[3]!
+ this.meIters = t[4]!
+ this.earlyExit = t[5]! === 1
+ this.globalShift = t[6]! === 1
+ this.useI4 = t[7]! === 1
+ this.aqStrength = t[8]!
+ this.aqTexture = t[9]!
+ this.earlySkip = t[10]! === 1
+ this.hpelSad = t[11]! === 1
+ this.qpelSad = t[12]! === 1
+ this.videoHpelDirs = t[13]!
+ this.videoQpelDirs = t[14]!
+ this.i8PredOnly = t[15]! === 1
+ this.noise = t[16]!
+ this.bDirectNb = t[17]!
+ }
+
+ sliceLen(s: int, sliceRows: int): int {
+ const r0 = s * sliceRows
+ return r0 + sliceRows < this.mbh ? sliceRows : this.mbh - r0
+ }
+
+ sliceWork(frame: Uint8Array, frameOff: int, sliceRows: int, next: Int32Array, done: Int32Array, ready: Int32Array,
+ sync: Int32Array, coded: Int32Array, filtered: Int32Array, stats: Float64Array, slot: int): u8[][] {
+ const mbh = this.mbh
+ const nSlices = next.length
+ let parts: u8[][] = []
+ for (let s = 0; s < nSlices; s++) parts.push([])
+ let tEnt = 0.0
+ while (true) {
+ let s = slot % nSlices
+ if (Atomics.load(next, s) >= this.sliceLen(s, sliceRows)) {
+ s = -1
+ let most = 0
+ for (let i = 0; i < nSlices; i++) {
+ const left = this.sliceLen(i, sliceRows) - Atomics.load(next, i)
+ if (left > most) {
+ most = left
+ s = i
+ }
+ }
+ if (s < 0) break
+ }
+ const len = this.sliceLen(s, sliceRows)
+ const k = Atomics.add(next, s, 1)
+ if (k >= len) continue
+ const r0 = s * sliceRows
+ this.prepRowTimed(frame, frameOff, r0 + k, true, true)
+ this.codeRowWave(r0 + k, true, sliceRows, coded)
+ if (Atomics.add(done, s, 1) + 1 < len) continue
+ const e0 = performance.now()
+ this.finishQpRows(sliceRows, r0, r0 + len)
+ publish(ready, s, 1)
+ let out: u8[] = []
+ this.entropyRows(true, sliceRows, r0, r0 + len, &out)
+ parts[s] = out
+ tEnt += performance.now() - e0
+ }
+ const d0 = performance.now()
+ if (this.filterRecon) {
+ const ver = this.counter + 1
+ while (true) {
+ const r = Atomics.add(sync, 0, 1)
+ if (r >= mbh) break
+ const s = Math.trunc(r / sliceRows)
+ if (s > 0 && r === s * sliceRows) this.waitRow(ready, s - 1, 1)
+ this.waitRow(ready, s, 1)
+ this.closeRow(r, true, ver, filtered)
+ }
+ }
+ this.scaleTiming()
+ const k = slot * 6
+ stats[k] = this.rMo
+ stats[k + 1] = this.rMd
+ stats[k + 2] = this.rTq
+ stats[k + 3] = tEnt
+ stats[k + 4] = performance.now() - d0
+ stats[k + 5] = this.rPrep
+ return parts
+ }
+
+ codeSlicesParallel(frame: Uint8Array, frameOff: int, sliceRows: int, nSlices: int): f64[] {
+ const sh = this.shareState()
+ const fp = this.frameParams()
+ const opts = this.workerOpts()
+ const tuning = this.tuning()
+ const helpers = this.threads - 1
+ const next = new Int32Array(nSlices)
+ const done = new Int32Array(nSlices)
+ const ready = progressArray(nSlices)
+ const sync = new Int32Array(2)
+ const coded = progressArray(this.mbh)
+ const filtered = progressArray(this.mbh)
+ const stats = new Float64Array((helpers + 1) * 6)
+ let threads: Thread<u8[][]>[] = []
+ for (let t = 1; t <= helpers; t++) {
+ const slot = t
+ threads.push(Thread.spawn(() => {
+ const w = new Encoder(opts)
+ w.attach(sh, fp)
+ w.tune(tuning)
+ const parts = w.sliceWork(frame, frameOff, sliceRows, next, done, ready, sync, coded, filtered, stats, slot)
+ Atomics.add(sync, 1, w.reusedMbs)
+ return parts
+ }))
+ }
+ let results: u8[][][] = [this.sliceWork(frame, frameOff, sliceRows, next, done, ready, sync, coded, filtered, stats, 0)]
+ for (const th of threads) results.push(th.join())
+ for (let s = 0; s < nSlices; s++) {
+ for (const parts of results) {
+ for (const b of parts[s]!) this.out.push(b)
+ }
+ }
+ this.reusedMbs += Atomics.load(sync, 1)
+ let sums: f64[] = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
+ for (let t = 0; t <= helpers; t++) {
+ for (let j = 0; j < 6; j++) sums[j] = sums[j]! + stats[t * 6 + j]!
+ }
+ return sums
+ }
+
+ codeFrameParallel(frame: Uint8Array, frameOff: int, idr: bool, full: bool, sliceRows: int, pipe: bool,
+ peek: bool): f64 {
+ const sh = this.shareState()
+ const fp = this.frameParams()
+ const opts = this.workerOpts()
+ const tuning = this.tuning()
+ const mbh = this.mbh
+ const ver = this.counter + 1
+ const progress = progressArray(mbh)
+ const dbp = progressArray(mbh)
+ const next = new Int32Array(1)
+ const stats = new Float64Array(5 * this.threads + 1)
+ const dedicated = pipe && this.threads >= ENTROPY_THREAD_MIN && this.threads < availableParallelism()
+ const qpRows = progressArray(dedicated ? 1 : 0)
+ const classify = !idr && this.textGated()
+ const clsNext = new Int32Array(1)
+ const clsDone = progressArray(1)
+ const textRows = new Int32Array(classify ? mbh : 0)
+ const pk: Peek = {
+ frame: this.nextFrame, frameOff: this.nextOff, ready: this.nextRead, sync: this.pkSync, changed: this.pkChanged,
+ plan: this.pkPlan, prev: this.pkPrev, cur: this.pkCur, shifts: this.pkShifts,
+ }
+ if (peek) pk.sync.fill(0)
+ const spin = this.spinBudgets()
+ let workers: Thread<int>[] = []
+ for (let k = 1; k < this.threads; k++) {
+ const slot = k * 5
+ workers.push(Thread.spawn(() => {
+ const w = new Encoder(opts)
+ w.attach(sh, fp)
+ w.tune(tuning)
+ w.spinMs = spin[k]!
+ w.qpRows = qpRows
+ if (classify) w.classifyFrame(frame, frameOff, full, clsNext, clsDone, textRows)
+ while (true) {
+ const r = Atomics.add(next, 0, 1)
+ if (r >= mbh) break
+ w.prepRowTimed(frame, frameOff, r, full, idr)
+ if (peek) bump(pk.sync, PEEK_PREPPED)
+ w.codeRowWave(r, idr, sliceRows, progress)
+ w.finishRow(r, sliceRows, idr, ver, progress, dbp)
+ }
+ w.scaleTiming()
+ stats[slot] = w.rMo
+ stats[slot + 1] = w.rMd
+ stats[slot + 2] = w.rTq
+ stats[slot + 3] = w.rDb
+ stats[slot + 4] = w.rPrep
+ if (peek) w.peekWork(pk)
+ spin[k] = w.spinMs
+ return w.reusedMbs
+ }))
+ }
+ let entropy: Thread<u8[]> | undefined = undefined
+ if (dedicated) {
+ const slot = 5 * this.threads
+ entropy = Thread.spawn(() => {
+ const w = new Encoder(opts)
+ w.attach(sh, fp)
+ let out: u8[] = []
+ for (let r = 0; r < mbh; r++) {
+ w.awaitRows(qpRows, r + 1)
+ const t = performance.now()
+ w.entropyRow(idr, sliceRows, r, &out)
+ w.rEnt += performance.now() - t
+ }
+ stats[slot] = w.rEnt
+ return out
+ })
+ }
+ if (classify) this.classifyFrame(frame, frameOff, full, clsNext, clsDone, textRows)
+ const inline = pipe && !dedicated
+ this.qpRows = qpRows
+ this.pipeMain = inline
+ this.pipeProgress = progress
+ this.pipeEnt = 0
+ this.pipeIdr = idr
+ this.pipeSliceRows = sliceRows
+ this.sharedTiles = true
+ while (true) {
+ if (inline) this.entropyReady()
+ const r = Atomics.add(next, 0, 1)
+ if (r >= mbh) break
+ this.prepRowTimed(frame, frameOff, r, full, idr)
+ if (peek) bump(pk.sync, PEEK_PREPPED)
+ this.codeRowWave(r, idr, sliceRows, progress)
+ this.finishRow(r, sliceRows, idr, ver, progress, dbp)
+ }
+ if (inline) {
+ while (this.pipeEnt < mbh) {
+ this.waitRow(progress, this.pipeEnt, this.mbw + 1)
+ this.entropyReady()
+ }
+ }
+ this.scaleTiming()
+ this.pipeMain = false
+ this.pipeProgress = new Int32Array(0)
+ let tPeek = 0.0
+ if (peek) {
+ const t = performance.now()
+ this.peekWork(pk)
+ tPeek = performance.now() - t
+ }
+ this.sharedTiles = false
+ this.classReady = false
+ this.qpRows = new Int32Array(0)
+ for (const t of workers) this.reusedMbs += t.join()
+ if (entropy !== undefined) {
+ for (const b of entropy.join()) this.out.push(b)
+ this.rEnt += stats[5 * this.threads]!
+ }
+ this.peeked = peek && Atomics.load(pk.sync, PEEK_PHASE * ROW_SLOT) === 2
+ this.peekedFrame = pk.frame
+ this.peekedOff = pk.frameOff
+ this.peekedIndex = this.frameIndex + 1
+ for (let k = 1; k < this.threads; k++) {
+ this.rMo += stats[k * 5]!
+ this.rMd += stats[k * 5 + 1]!
+ this.rTq += stats[k * 5 + 2]!
+ this.rDb += stats[k * 5 + 3]!
+ this.rPrep += stats[k * 5 + 4]!
+ }
+ return tPeek
+ }
+
+ configureB(n: int) {
+ // A B run needs a P anchor after it inside its GOP, so GOPs of one or two frames never code one.
+ this.bframes = this.keyint <= 2 || n < 0 ? 0 : n > 3 ? 3 : n
+ this.pyramid = this.pyramid && this.bframes >= 2
+ if (this.bframes === 0) return
+ this.bDirectNb = this.pyramid ? B_DIRECT_NB_PYRAMID : B_DIRECT_NB
+ this.dpbRefs = this.maxRefs < 2 ? 2 : this.maxRefs
+ const dpb = this.dpbRefs + (this.pyramid ? 1 : 0)
+ const p = this.params
+ this.params = {
+ width: p.width, height: p.height, mbw: p.mbw, mbh: p.mbh, profile: p.profile,
+ level: chooseLevel(this.mbw, this.mbh, this.fpsF, dpb, 0), refs: p.refs, fpsNum: p.fpsNum,
+ fpsDen: p.fpsDen, log2MaxFrameNum: p.log2MaxFrameNum, cabac: p.cabac, transform8x8: p.transform8x8,
+ weightedPred: p.weightedPred, dpbRefs: dpb, bframes: this.bframes, pyramid: this.pyramid,
+ }
+ const mbs = this.mbw * this.mbh
+ if (this.pyramid) {
+ this.bRefFrame = this.newFrame()
+ this.giveHalfPlanes(this.bRefFrame)
+ this.bColMvx = new Int32Array(mbs)
+ this.bColMvy = new Int32Array(mbs)
+ this.bColRef = new Int32Array(mbs)
+ this.bMbQpRef = new Int32Array(mbs)
+ }
+ this.mvx1 = new Int32Array(mbs)
+ this.mvy1 = new Int32Array(mbs)
+ this.refIdx1 = new Int32Array(mbs)
+ this.mvdx1 = new Int32Array(mbs)
+ this.mvdy1 = new Int32Array(mbs)
+ this.colMvx = new Int32Array(mbs)
+ this.colMvy = new Int32Array(mbs)
+ this.colRef = new Int32Array(mbs)
+ this.bSlots = []
+ this.bTargets = []
+ this.bMbQp = new Int32Array(mbs)
+ this.bChanged = new Uint8Array(mbs)
+ this.bChanged.fill(1)
+ this.bRefresh = new Uint8Array(mbs)
+ this.dirtyScratch = new Uint8Array(mbs)
+ }
+
+ bSlot(k: int): BSlot {
+ while (this.bSlots.length <= k) this.bSlots.push(this.newBSlot())
+ return this.bSlots[k]!
+ }
+
+ bTarget(j: int): RefFrame {
+ while (this.bTargets.length <= j) {
+ const f = new RefFrame()
+ f.y = newPlane(this.ysize)
+ f.u = newPlane(this.cs * (this.chh + 2 * PADC))
+ f.v = newPlane(this.cs * (this.chh + 2 * PADC))
+ this.bTargets.push(f)
+ }
+ return this.bTargets[j]!
+ }
+
+ newBSlot(): BSlot {
+ const mbs = this.mbw * this.mbh
+ const imode = new Uint8Array(mbs * 16)
+ imode.fill(2)
+ const qpY = new Int32Array(mbs)
+ qpY.fill(this.opts.qp)
+ return {
+ mbType: new Int32Array(mbs), i16Mode: new Int32Array(mbs), cMode: new Int32Array(mbs), imode,
+ t8: new Int32Array(mbs), cbp: new Int32Array(mbs), dcCbf: new Int32Array(mbs), nnz: new Uint8Array(mbs * 24),
+ mvx: new Int32Array(mbs), mvy: new Int32Array(mbs), refIdx: new Int32Array(mbs), mvdx: new Int32Array(mbs),
+ mvdy: new Int32Array(mbs), pkCoef: new Int16Array(this.packSize()), pkMask: new Uint16Array(mbs),
+ pkOff: new Int32Array(mbs), pkTop: new Int32Array(1), qpY, qpDelta: new Int32Array(mbs),
+ mvx1: new Int32Array(mbs), mvy1: new Int32Array(mbs), refIdx1: new Int32Array(mbs),
+ mvdx1: new Int32Array(mbs), mvdy1: new Int32Array(mbs),
+ }
+ }
+
+ bSlotState(s: BSlot, data: Uint8Array, target: RefFrame): SharedState {
+ const sh = this.shareState()
+ const ySize = this.aw * this.ah + 64
+ const cSize = this.cw * this.chh + 64
+ sh.srcY = data.subarray(0, ySize)
+ sh.srcU = data.subarray(ySize, ySize + cSize)
+ sh.srcV = data.subarray(ySize + cSize, ySize + 2 * cSize)
+ sh.curY = target.y
+ sh.curU = target.u
+ sh.curV = target.v
+ sh.changed = this.bChanged
+ sh.refresh = this.bRefresh
+ sh.mbQp = this.bMbQp
+ sh.mbType = s.mbType
+ sh.i16Mode = s.i16Mode
+ sh.cMode = s.cMode
+ sh.imode = s.imode
+ sh.t8 = s.t8
+ sh.cbp = s.cbp
+ sh.dcCbf = s.dcCbf
+ sh.nnz = s.nnz
+ sh.mvx = s.mvx
+ sh.mvy = s.mvy
+ sh.refIdx = s.refIdx
+ sh.mvdx = s.mvdx
+ sh.mvdy = s.mvdy
+ s.pkTop[0] = 0
+ sh.pkCoef = s.pkCoef
+ sh.pkMask = s.pkMask
+ sh.pkOff = s.pkOff
+ sh.pkTop = s.pkTop
+ sh.qpY = s.qpY
+ sh.qpDelta = s.qpDelta
+ sh.mvx1 = s.mvx1
+ sh.mvy1 = s.mvy1
+ sh.refIdx1 = s.refIdx1
+ sh.mvdx1 = s.mvdx1
+ sh.mvdy1 = s.mvdy1
+ return sh
+ }
+
+ useB(side: SideInfo | undefined): bool {
+ if (!this.bReady) return false
+ if (side === undefined) return true
+ if (side.scroll.length > 0) return false
+ this.dirtyScratch.fill(0)
+ return markRects(this.dirtyScratch, this.mbw, this.mbh, side.dirty) * 2 >= this.mbw * this.mbh
+ }
+
+ submit(frame: Uint8Array, frameOff: int, side: SideInfo | undefined): u8[] {
+ if (this.intraParallel()) return this.submitIntra(frame, frameOff, side)
+ const idx = this.inputIndex
+ this.inputIndex++
+ const life = this.laNext ? this.laLife : new Int32Array(0)
+ this.laNext = false
+ let out: u8[] = []
+ const idrNext = this.refs.length === 0 || idx - this.pocBase >= this.keyint
+ if (idrNext) {
+ this.flushPending(&out)
+ this.setLookahead(life)
+ this.codeAnchor(frame, frameOff, idx, this.bAdapt ? side : undefined, &out)
+ return out
+ }
+ if (this.bAdapt && !this.useB(side)) {
+ this.flushPending(&out)
+ this.setLookahead(life)
+ this.codeAnchor(frame, frameOff, idx, side, &out)
+ return out
+ }
+ if (this.pending.length < this.bframes) {
+ const p = new Pending(this.padInput(frame, frameOff), idx)
+ if (life.length > 0) {
+ p.life = life.slice()
+ if (this.laL1 > 0.0) p.keep = this.laKeep.slice()
+ }
+ this.pending.push(p)
+ if (this.pending.length === this.bframes) this.peekAnchor(idx)
+ return out
+ }
+ this.anchorLookahead(life, this.laKeep, idx)
+ this.codeAnchor(frame, frameOff, idx, undefined, &out)
+ this.codeBFrames(&out)
+ return out
+ }
+
+ flush(): u8[] {
+ let out: u8[] = []
+ if (this.intraPool.length > 0) {
+ this.drainIntra(&out)
+ return out
+ }
+ this.flushPending(&out)
+ this.finishBRun(&out)
+ return out
+ }
+
+ intraParallel(): bool {
+ return this.frameThreads && this.threads > 1 && this.keyint === 1 && !this.idrReuse && this.opts.rcMode !== RC_VBR
+ }
+
+ bindSource(buf: Uint8Array) {
+ const ySize = this.aw * this.ah + 64
+ const cSize = this.cw * this.chh + 64
+ this.srcY = buf.subarray(0, ySize)
+ this.srcU = buf.subarray(ySize, ySize + cSize)
+ this.srcV = buf.subarray(ySize + cSize, ySize + 2 * cSize)
+ }
+
+ startIntraPool() {
+ const n = this.threads
+ if (this.srcRing.length !== n + 2) {
+ const size = this.aw * this.ah + 2 * (this.cw * this.chh) + 192
+ this.srcRing = []
+ for (let k = 0; k < n + 2; k++) this.srcRing.push(newPlane(size))
+ this.ringBusy = new Uint8Array(n + 2)
+ }
+ const work = new Channel<IntraJob>()
+ const done = new Channel<IntraCoded>()
+ this.intraWork = work
+ this.intraDone = done
+ const opts = this.opts
+ const params = this.params
+ const tuning = this.tuning()
+ const cfg = [this.deblock ? 1 : 0, this.idrSlices, this.sliceRowsI]
+ for (let t = 0; t < n; t++) {
+ this.intraPool.push(Thread.spawn(() => {
+ const w = new Encoder(opts)
+ w.params = params
+ w.tune(tuning)
+ w.deblock = cfg[0]! === 1
+ w.idrSlices = cfg[1]!
+ w.sliceRowsI = cfg[2]!
+ w.idrReuse = false
+ while (true) {
+ const job = work.receive()
+ if (job === undefined) return
+ done.send(w.codeIntraJob(job))
+ }
+ }))
+ }
+ }
+
+ submitIntra(frame: Uint8Array, frameOff: int, side: SideInfo | undefined): u8[] {
+ const t0 = performance.now()
+ if (this.intraPool.length === 0) this.startIntraPool()
+ let out: u8[] = []
+ const seq = this.intraSent
+ const slot = seq % this.srcRing.length
+ while (this.ringBusy[slot]! !== 0) this.takeIntra(this.intraDone!.receive()!, &out)
+ if (this.bframes > 0) {
+ this.pocBase = this.inputIndex
+ this.frameIndex = this.inputIndex
+ this.inputIndex++
+ }
+ this.filterRecon = this.wantRecon
+ this.srcSlot = slot
+ this.analyse(frame, frameOff, side, true)
+ this.srcSlot = -1
+ this.wpOn = false
+ this.wpChromaOn = false
+ this.lastActive = this.frameIndex
+ const mbs = this.mbw * this.mbh
+ const dt = this.lastCodedIndex < 0 ? 1 : this.frameIndex - this.lastCodedIndex
+ this.frameQp = this.rate.frameQp(true, 0.0, mbs, dt)
+ this.laOn = this.laNext
+ this.laHz = (this.keyint < this.laSpan ? this.keyint : this.laSpan) * LIFE_ONE
+ this.laNext = false
+ const longStatic = Math.round(this.fpsF)
+ for (let mb = 0; mb < mbs; mb++) this.mbQp[mb] = this.baseMbQp(mb, true, longStatic)
+ this.updateHistory()
+ this.ringBusy[slot] = 1
+ this.intraWork!.send({
+ seq, slot, buf: this.srcRing[slot]!, qp: this.mbQp.slice(), frameQp: this.frameQp, idrPicId: this.idrPicId,
+ frameIndex: this.frameIndex, pocBase: this.pocBase, recon: this.wantRecon, analysis: performance.now() - t0,
+ })
+ this.intraSent++
+ this.counter++
+ this.idrPicId = (this.idrPicId + 1) & 1
+ this.frameNum = 1 & ((1 << this.params.log2MaxFrameNum) - 1)
+ this.prevChanged.fill(0)
+ this.sliceType = SLICE_I
+ this.anchorQp = this.frameQp
+ this.sinceIdr = 1
+ this.lastCodedIndex = this.frameIndex
+ this.frameIndex++
+ this.codedFrames++
+ while (true) {
+ const r = this.intraDone!.tryReceive()
+ if (r === undefined) break
+ this.takeIntra(r, &out)
+ }
+ return out
+ }
+
+ codeIntraJob(job: IntraJob): IntraCoded {
+ const t0 = performance.now()
+ this.bindSource(job.buf)
+ this.mbQp.set(job.qp)
+ this.frameQp = job.frameQp
+ this.idrPicId = job.idrPicId
+ this.frameIndex = job.frameIndex
+ this.pocBase = job.pocBase
+ this.filterRecon = job.recon
+ this.textMbs = 0
+ for (let mby = 0; mby < this.mbh; mby++) this.aqRow(mby)
+ let out: u8[] = []
+ appendNal(&out, 3, 7, writeSps(this.params), true)
+ appendNal(&out, 3, 8, writePps(this.params), true)
+ this.frameNum = 0
+ this.sliceType = SLICE_I
+ this.refsActive = 1
+ this.anchorQp = this.frameQp
+ const rowsI = this.sliceRowsI > 0 ? this.sliceRowsI : this.idrSlices > 1 ? Math.trunc((this.mbh + this.idrSlices - 1) / this.idrSlices) : this.mbh
+ this.rMo = 0.0
+ this.rMd = 0.0
+ this.rTq = 0.0
+ this.rUn = 0.0
+ this.tN = 0
+ this.tNs = 0
+ this.uN = 0
+ this.uNs = 0
+ this.resetPacking()
+ for (let mby = 0; mby < this.mbh; mby++) this.codeRow(mby, true, rowsI)
+ this.scaleTiming()
+ const e0 = performance.now()
+ this.finishQpRows(rowsI, 0, this.mbh)
+ this.entropyRows(true, rowsI, 0, this.mbh, &out)
+ const e1 = performance.now()
+ let recon = new Uint8Array(0)
+ if (job.recon) {
+ this.counter++
+ this.deblockFrame(true)
+ recon = this.reconOf(this.cur)
+ }
+ const t1 = performance.now()
+ return {
+ seq: job.seq, slot: job.slot, frameIndex: job.frameIndex, frameQp: job.frameQp, bits: out, recon,
+ analysis: job.analysis, mode: this.rMd, tq: this.rTq, entropy: e1 - e0, deblock: t1 - e1, total: t1 - t0,
+ }
+ }
+
+ takeIntra(r: IntraCoded, inout out: u8[]) {
+ this.ringBusy[r.slot] = 0
+ this.intraHeld.push(r)
+ let moved = true
+ while (moved) {
+ moved = false
+ let keep: IntraCoded[] = []
+ for (const h of this.intraHeld) {
+ if (!moved && h.seq === this.intraEmitted) {
+ this.emitIntra(h, &out)
+ moved = true
+ } else {
+ keep.push(h)
+ }
+ }
+ this.intraHeld = keep
+ }
+ }
+
+ emitIntra(h: IntraCoded, inout out: u8[]) {
+ for (const b of h.bits) out.push(b)
+ const mbs = this.mbw * this.mbh
+ this.tAnalysis += h.analysis
+ this.tMode += h.mode
+ this.tTq += h.tq
+ this.tEntropy += h.entropy
+ this.tDeblock += h.deblock
+ this.frames.push({
+ index: h.frameIndex, type: "I", bytes: h.bits.length, qp: h.frameQp, changedMbs: mbs, analysis: h.analysis,
+ motion: 0.0, mode: h.mode, tq: h.tq, entropy: h.entropy, deblock: h.deblock, total: h.analysis + h.total,
+ reused: 0,
+ })
+ this.rate.update(true, h.frameQp, h.bits.length * 8, mbs)
+ if (h.recon.length > 0) this.queueRecon(h.recon, h.frameIndex)
+ this.intraEmitted++
+ }
+
+ drainIntra(inout out: u8[]) {
+ while (this.intraEmitted < this.intraSent) this.takeIntra(this.intraDone!.receive()!, &out)
+ this.intraWork!.close()
+ for (const t of this.intraPool) t.join()
+ this.intraPool = []
+ }
+
+ padInput(frame: Uint8Array, frameOff: int): Uint8Array {
+ const ySize = this.aw * this.ah + 64
+ const cSize = this.cw * this.chh + 64
+ const buf = this.inputPool.length > 0 ? this.inputPool.pop()! : newPlane(ySize + 2 * cSize)
+ const cwIn = this.w >> 1
+ const chIn = this.h >> 1
+ const uIn = frameOff + this.w * this.h
+ copyPadded(buf, this.aw, this.ah, frame, frameOff, this.w, this.w, this.h)
+ copyPadded(buf.subarray(ySize), this.cw, this.chh, frame, uIn, cwIn, cwIn, chIn)
+ copyPadded(buf.subarray(ySize + cSize), this.cw, this.chh, frame, uIn + cwIn * chIn, cwIn, cwIn, chIn)
+ buf.fill(0, ySize - 64, ySize)
+ buf.fill(0, ySize + cSize - 64, ySize + cSize)
+ buf.fill(0, ySize + 2 * cSize - 64, ySize + 2 * cSize)
+ return buf
+ }
+
+ unpadInput(buf: Uint8Array) {
+ const ySize = this.aw * this.ah + 64
+ const cSize = this.cw * this.chh + 64
+ const cwIn = this.w >> 1
+ const chIn = this.h >> 1
+ for (let y = 0; y < this.h; y++) buf.copyWithin(y * this.w, y * this.aw, y * this.aw + this.w)
+ const uIn = this.w * this.h
+ for (let y = 0; y < chIn; y++) {
+ buf.copyWithin(uIn + y * cwIn, ySize + y * this.cw, ySize + y * this.cw + cwIn)
+ }
+ const vIn = uIn + cwIn * chIn
+ for (let y = 0; y < chIn; y++) {
+ buf.copyWithin(vIn + y * cwIn, ySize + cSize + y * this.cw, ySize + cSize + y * this.cw + cwIn)
+ }
+ }
+
+ flushPending(inout out: u8[]) {
+ if (this.pending.length === 0) return
+ const last = this.pending.pop()!
+ this.anchorLookahead(last.life, last.keep, last.index)
+ this.unpadInput(last.data)
+ this.codeAnchor(last.data, 0, last.index, undefined, &out)
+ this.inputPool.push(last.data)
+ this.codeBFrames(&out)
+ }
+
+ codeAnchor(frame: Uint8Array, frameOff: int, idx: int, side: SideInfo | undefined, inout out: u8[]) {
+ const idr = this.refs.length === 0 || idx - this.pocBase >= this.keyint
+ if (idr) this.pocBase = idx
+ this.frameIndex = idx
+ this.sinceIdr = idr ? this.keyint : idx - this.pocBase
+ const vfr = this.vfr
+ this.vfr = vfr && this.bAdapt && this.pending.length === 0
+ const at = this.frames.length
+ const bits = this.encodeFrame(frame, frameOff, side)
+ this.vfr = vfr
+ if (this.bThreads.length > 0) {
+ this.finishBRun(&out)
+ const last = this.frames.length - 1
+ const e = this.frames[at]!
+ for (let i = at; i < last; i++) this.frames[i] = this.frames[i + 1]!
+ this.frames[last] = e
+ }
+ for (const b of bits) out.push(b)
+ const mbs = this.mbw * this.mbh
+ this.bReady = this.mostlyMoving()
+ if (bits.length === 0) {
+ if (this.wantRecon) this.nextRecon = idx + 1
+ return
+ }
+ this.prevAnchorIndex = this.lastAnchorIndex
+ this.lastAnchorIndex = idx
+ if (this.pending.length > 0) {
+ for (let mb = 0; mb < mbs; mb++) {
+ const intra = idr || this.isIntra(mb)
+ this.colRef[mb] = intra ? -1 : this.refIdx[mb]!
+ this.colMvx[mb] = intra ? 0 : this.mvx[mb]!
+ this.colMvy[mb] = intra ? 0 : this.mvy[mb]!
+ }
+ }
+ this.holdRecon(this.refs[0]!, idx)
+ }
+
+ mostlyMoving(): bool {
+ const mbs = this.mbw * this.mbh
+ let moved = 0
+ for (let mb = 0; mb < mbs; mb++) {
+ if (this.changed[mb]! === 1) moved++
+ }
+ return moved * 2 >= mbs && !this.wpOn && this.scrollMvy === 0 && this.shiftHx === 0 && this.shiftVy === 0
+ }
+
+ nextInputAnalysed(): bool {
+ if (this.bframes === 0) return true
+ // Under B-frames the next input is analysed next only if submit() coded this anchor directly and the anchor
+ // leaves bReady false; otherwise it is queued as a B candidate. changed is final once analysis ends.
+ return this.bAdapt && this.frameIndex + 1 === this.inputIndex && !this.mostlyMoving()
+ }
+
+ codeBFrames(inout out: u8[]) {
+ if (this.pending.length > 0) this.startBRun()
+ this.pending = []
+ if (!this.bAsync()) this.finishBRun(&out)
+ }
+
+ bAsync(): bool {
+ return this.threads > 1 && this.mbh >= 8 && this.opts.rcMode !== RC_VBR
+ }
+
+ holdRecon(rf: RefFrame, idx: int) {
+ if (!this.wantRecon) return
+ this.queueRecon(this.reconOf(rf), idx)
+ }
+
+ queueRecon(data: Uint8Array, idx: int) {
+ this.reconHeld.push(new Pending(data, idx))
+ let moved = true
+ while (moved) {
+ moved = false
+ let keep: Pending[] = []
+ for (const h of this.reconHeld) {
+ if (!moved && h.index === this.nextRecon) {
+ this.reconReady.push(h.data)
+ this.nextRecon++
+ moved = true
+ } else {
+ keep.push(h)
+ }
+ }
+ this.reconHeld = keep
+ }
+ }
+
+ takeRecon(): Uint8Array[] {
+ const r = this.reconReady
+ this.reconReady = []
+ return r
+ }
+
+ startBRun() {
+ const t0 = performance.now()
+ const n = this.pending.length
+ const mbs = this.mbw * this.mbh
+ const mid = this.pyramid && n >= 2 ? (n - 1) >> 1 : -1
+ for (let i = 0; i < mbs; i++) {
+ const q = this.mbQp[i]! + this.bQpOffset
+ this.bMbQp[i] = q < 0 ? 0 : q > 51 ? 51 : q
+ }
+ if (mid >= 0) {
+ for (let i = 0; i < mbs; i++) {
+ const q = this.mbQp[i]! + this.bRefQpOffset
+ this.bMbQpRef[i] = q < 0 ? 0 : q > 51 ? 51 : q
+ }
+ }
+ const aFrameIndex = this.frameIndex
+ const aFrameNum = this.frameNum
+ this.sliceType = SLICE_B
+ const fq = this.anchorQp + this.bQpOffset
+ const bq = fq < 0 ? 0 : fq > 51 ? 51 : fq
+ const rq0 = this.anchorQp + this.bRefQpOffset
+ const rq = rq0 < 0 ? 0 : rq0 > 51 ? 51 : rq0
+ this.refsActive = 1
+ this.wpOn = false
+ this.wpChromaOn = false
+ this.shiftHx = 0
+ this.shiftVy = 0
+ this.scrollMb0 = -1
+ this.scrollMb1 = -1
+ this.cursorMb = -1
+ this.l0Reorder = []
+ this.mmco = []
+ const parallel = this.threads > 1 && this.mbh >= 8
+ if (parallel) {
+ for (let k = 0; k < 2; k++) {
+ const r = this.refs[k]!
+ if (r.tileGen.length > 0) this.precomputeTiles(r)
+ }
+ }
+ const rf = this.bRefFrame
+ if (mid >= 0) {
+ this.genSeq++
+ rf.gen = this.genSeq
+ }
+ const midIndex = mid >= 0 ? this.pending[mid]!.index : -1
+ const intoCur = !parallel && !this.wantRecon
+ if (intoCur) this.cur.ver.fill(-1)
+ let shs: SharedState[] = []
+ let fps: FrameParams[] = []
+ this.bRunIdx = []
+ this.bRunQps = []
+ this.bRunAnchorQp = this.anchorQp
+ this.bRunData = []
+ this.bRunRecon = []
+ let targets = 0
+ for (let k = 0; k < n; k++) {
+ const p = this.pending[k]!
+ const isMid = k === mid
+ const before = mid >= 0 && k < mid
+ const after = mid >= 0 && k > mid
+ const l0 = after ? midIndex : this.prevAnchorIndex
+ const l1 = before ? midIndex : this.lastAnchorIndex
+ this.frameIndex = p.index
+ this.bTb = p.index - l0
+ this.bTd = l1 - l0
+ this.bTdCol = before ? this.bTd : this.lastAnchorIndex - this.prevAnchorIndex
+ this.frameQp = isMid ? rq : bq
+ this.nalRef = isMid
+ this.frameNum = before || after ? (aFrameNum + 1) & ((1 << this.params.log2MaxFrameNum) - 1) : aFrameNum
+ let target = rf
+ if (!isMid) {
+ target = intoCur ? this.cur : this.bTarget(targets)
+ targets++
+ }
+ const sh = this.bSlotState(this.bSlot(parallel ? k : 0), p.data, target)
+ const fp = this.frameParams()
+ fp.deblock = false
+ if (isMid) sh.mbQp = this.bMbQpRef
+ if (before || after) {
+ const j = before ? 0 : 1
+ sh.refY[j] = rf.y
+ sh.refU[j] = rf.u
+ sh.refV[j] = rf.v
+ sh.refHb[j] = rf.hb
+ sh.refHh[j] = rf.hh
+ sh.refHj[j] = rf.hj
+ sh.refTiles[j] = rf.tileGen
+ fp.refGen[j] = rf.gen
+ }
+ if (before) {
+ sh.colMvx = this.bColMvx
+ sh.colMvy = this.bColMvy
+ sh.colRef = this.bColRef
+ }
+ shs.push(sh)
+ fps.push(fp)
+ this.bRunData.push(p.data)
+ this.bRunRecon.push(target)
+ this.bRunIdx.push(p.index)
+ this.bRunQps.push(this.frameQp)
+ }
+ this.bRunMid = mid
+ this.bRunOrder = []
+ if (mid >= 0) this.bRunOrder.push(mid)
+ for (let k = 0; k < n; k++) {
+ if (k !== mid) this.bRunOrder.push(k)
+ }
+ this.frameIndex = aFrameIndex
+ this.frameQp = bq
+ this.nalRef = false
+ this.frameNum = mid >= 0 ? (aFrameNum + 1) & ((1 << this.params.log2MaxFrameNum) - 1) : aFrameNum
+ if (mid >= 0) this.bRefNum = aFrameNum
+ this.sliceType = SLICE_P
+ this.codedFrames += n
+ const opts = this.workerOpts()
+ const tuning = this.tuning()
+ const workers = parallel ? this.threads : 1
+ let progress: Int32Array[] = []
+ for (let k = 0; k < n; k++) progress.push(progressArray(this.mbh))
+ const next = new Int32Array(n)
+ const done = new Int32Array(n)
+ const stats = new Float64Array(workers * n * 5)
+ const bm: BMid = {
+ mid, gate: new Int32Array(2), tileCnt: new Int32Array(2), lazy: !parallel, oneSlot: !parallel, colMvx: this.bColMvx,
+ colMvy: this.bColMvy, colRef: this.bColRef, y: rf.y, hb: rf.hb, hh: rf.hh, hj: rf.hj, tileGen: rf.tileGen,
+ gen: rf.gen,
+ }
+ this.bRunStats = stats
+ this.bRunAnalysis = (performance.now() - t0) / f64(n)
+ this.bRunT1 = performance.now()
+ if (!parallel) {
+ let ws: Encoder[] = []
+ for (let k = 0; k < n; k++) ws.push(bWorker(opts, shs[k]!, fps[k]!, tuning, false))
+ this.bInline.push(codeBRun(ws, next, done, progress, stats, 0, bm))
+ return
+ }
+ for (let t = 0; t < workers; t++) {
+ const slot = t
+ this.bThreads.push(Thread.spawn(() => {
+ let ws: Encoder[] = []
+ for (let k = 0; k < n; k++) ws.push(bWorker(opts, shs[k]!, fps[k]!, tuning, parallel))
+ return codeBRun(ws, next, done, progress, stats, slot, bm)
+ }))
+ }
+ }
+
+ finishBRun(inout out: u8[]) {
+ if (this.bThreads.length === 0 && this.bInline.length === 0) return
+ let results: u8[][][] = this.bInline
+ this.bInline = []
+ for (const th of this.bThreads) results.push(th.join())
+ this.bThreads = []
+ const span = performance.now() - this.bRunT1
+ const stats = this.bRunStats
+ const n = this.bRunIdx.length
+ const workers = results.length
+ const mbs = this.mbw * this.mbh
+ let work = 0.0
+ for (const v of stats) work += v
+ const scale = work > 0.0 ? span / work : 0.0
+ const analysis = this.bRunAnalysis
+ for (const k of this.bRunOrder) {
+ const index = this.bRunIdx[k]!
+ const before = out.length
+ for (const parts of results) {
+ for (const b of parts[k]!) out.push(b)
+ }
+ let ms: f64[] = [0.0, 0.0, 0.0, 0.0, 0.0]
+ for (let t = 0; t < workers; t++) {
+ for (let j = 0; j < 5; j++) ms[j] = ms[j]! + stats[(t * n + k) * 5 + j]! * scale
+ }
+ const total = analysis + ms[0]! + ms[1]! + ms[2]! + ms[3]! + ms[4]!
+ this.tAnalysis += analysis
+ this.tMotion += ms[0]!
+ this.tMode += ms[1]!
+ this.tTq += ms[2]!
+ this.tEntropy += ms[3]!
+ this.tDeblock += ms[4]!
+ this.rate.updateB(this.bRunAnchorQp, (out.length - before) * 8)
+ this.frames.push({
+ index, type: "B", bytes: out.length - before, qp: this.bRunQps[k]!, changedMbs: mbs, analysis,
+ motion: ms[0]!, mode: ms[1]!, tq: ms[2]!, entropy: ms[3]!, deblock: ms[4]!, total, reused: 0,
+ })
+ this.holdRecon(this.bRunRecon[k]!, index)
+ }
+ for (const d of this.bRunData) this.inputPool.push(d)
+ this.bRunData = []
+ this.bRunRecon = []
+ }
+
+ setBDirect(mb: int, t: int) {
+ this.mbType[mb] = t
+ this.refIdx[mb] = this.dRef0
+ this.refIdx1[mb] = this.dRef1
+ this.mvx[mb] = this.dRef0 >= 0 ? this.dMx0 : 0
+ this.mvy[mb] = this.dRef0 >= 0 ? this.dMy0 : 0
+ this.mvx1[mb] = this.dRef1 >= 0 ? this.dMx1 : 0
+ this.mvy1[mb] = this.dRef1 >= 0 ? this.dMy1 : 0
+ this.mvdx[mb] = 0
+ this.mvdy[mb] = 0
+ this.mvdx1[mb] = 0
+ this.mvdy1[mb] = 0
+ }
+
+ deriveDirect(mbx: int, mby: int) {
+ const mb = mby * this.mbw + mbx
+ const aAv = mbx > 0
+ const bAv = mby > this.sliceRow0
+ let cAv = bAv && mbx + 1 < this.mbw
+ let mbC = mb - this.mbw + 1
+ if (!cAv) {
+ cAv = mbx > 0 && bAv
+ mbC = mb - this.mbw - 1
+ }
+ let r0 = this.directRef(this.refIdx, mb, aAv, bAv, cAv, mbC)
+ let r1 = this.directRef(this.refIdx1, mb, aAv, bAv, cAv, mbC)
+ let zero = false
+ if (r0 < 0 && r1 < 0) {
+ r0 = 0
+ r1 = 0
+ zero = true
+ }
+ const colZero = this.colRef[mb]! === 0 && iabs(this.colMvx[mb]!) <= 1 && iabs(this.colMvy[mb]!) <= 1
+ this.dRef0 = r0
+ this.dRef1 = r1
+ this.dMx0 = 0
+ this.dMy0 = 0
+ this.dMx1 = 0
+ this.dMy1 = 0
+ if (!zero && r0 >= 0 && !(r0 === 0 && colZero)) {
+ this.computeMvpL(mbx, mby, r0, 0)
+ this.dMx0 = this.mvpX
+ this.dMy0 = this.mvpY
+ }
+ if (!zero && r1 >= 0 && !(r1 === 0 && colZero)) {
+ this.computeMvpL(mbx, mby, r1, 1)
+ this.dMx1 = this.mvpX
+ this.dMy1 = this.mvpY
+ }
+ }
+
+ directRef(refs: Int32Array, mb: int, aAv: bool, bAv: bool, cAv: bool, mbC: int): int {
+ const ra = aAv && !this.isIntra(mb - 1) ? refs[mb - 1]! : -1
+ const rb = bAv && !this.isIntra(mb - this.mbw) ? refs[mb - this.mbw]! : -1
+ const rc = cAv && !this.isIntra(mbC) ? refs[mbC]! : -1
+ return minPositive(ra, minPositive(rb, rc))
+ }
+
+ directInRange(px: int, py: int): bool {
+ if (this.dRef0 >= 0) {
+ const ix = this.dMx0 >> 2
+ const iy = this.dMy0 >> 2
+ if (ix !== this.clampMvx(px, ix) || iy !== this.clampMvy(py, iy)) return false
+ }
+ if (this.dRef1 >= 0) {
+ const ix = this.dMx1 >> 2
+ const iy = this.dMy1 >> 2
+ if (ix !== this.clampMvx(px, ix) || iy !== this.clampMvy(py, iy)) return false
+ }
+ return true
+ }
+
+ buildPredB(mbx: int, mby: int, use0: bool, use1: bool, m0x: int, m0y: int, m1x: int, m1y: int, luma: bool,
+ chroma: bool) {
+ this.buildPredInto(this.pred, mbx, mby, use0, use1, m0x, m0y, m1x, m1y, luma, chroma)
+ }
+
+ directChroma(mbx: int, mby: int) {
+ this.buildPredB(mbx, mby, this.dRef0 >= 0, this.dRef1 >= 0, this.dMx0, this.dMy0, this.dMx1, this.dMy1, false,
+ true)
+ }
+
+ buildPredInto(dst: Uint8Array, mbx: int, mby: int, use0: bool, use1: bool, m0x: int, m0y: int, m1x: int, m1y: int,
+ luma: bool, chroma: bool) {
+ if (use0) this.predictList(dst, this.refs[1]!, mbx, mby, m0x, m0y, luma, chroma)
+ if (use1) {
+ if (use0) {
+ this.predictList(this.predB, this.refs[0]!, mbx, mby, m1x, m1y, luma, chroma)
+ } else {
+ this.predictList(dst, this.refs[0]!, mbx, mby, m1x, m1y, luma, chroma)
+ }
+ }
+ if (use0 && use1) {
+ const w1 = this.implicitW1()
+ if (w1 === 32) {
+ if (luma) avgPlanes(dst, 0, 16, dst, 0, this.predB, 0, 16, 16, 16)
+ if (chroma) {
+ avgPlanes(dst, 256, 16, dst, 256, this.predB, 256, 16, 16, 8)
+ }
+ return
+ }
+ if (luma) weightedAvgPlanes(dst, 0, 16, dst, 0, this.predB, 0, 16, 16, 16, 64 - w1, w1)
+ if (chroma) {
+ weightedAvgPlanes(dst, 256, 16, dst, 256, this.predB, 256, 16, 16, 8, 64 - w1, w1)
+ }
+ }
+ }
+
+ predictList(dst: Uint8Array, rf: RefFrame, mbx: int, mby: int, mx: int, my: int, luma: bool, chroma: bool) {
+ const px = mbx * 16
+ const py = mby * 16
+ if (luma) {
+ this.ensureTiles(rf, px + (mx >> 2) - 1, py + (my >> 2) - 1, 19, 19)
+ this.predictQpel(dst, 0, 16, rf, px, py, mx, my, 16, 16)
+ }
+ if (chroma) {
+ const base = this.rc(mbx * 8, mby * 8)
+ predictChroma(dst, 256, 8, rf.u, this.cs, base, mx, my, 8, 8)
+ predictChroma(dst, 320, 8, rf.v, this.cs, base, mx, my, 8, 8)
+ }
+ }
+
+ implicitW1(): int {
+ if (!this.params.weightedPred || this.bTd <= 0) return 32
+ const td = 2 * this.bTd
+ const tx = Math.trunc((16384 + (td >> 1)) / td)
+ const dsf = (2 * this.bTb * tx + 32) >> 6
+ const w1 = (dsf < -1024 ? -1024 : dsf > 1023 ? 1023 : dsf) >> 2
+ return w1 < -64 || w1 > 128 ? 32 : w1
+ }
+
+ interPred(mb: int, mbx: int, mby: int) {
+ if (this.sliceType !== SLICE_B) {
+ this.predictInter(mb, mbx, mby, this.mvx[mb]!, this.mvy[mb]!, this.refIdx[mb]!)
+ return
+ }
+ this.buildPredB(mbx, mby, this.refIdx[mb]! >= 0, this.refIdx1[mb]! >= 0, this.mvx[mb]!, this.mvy[mb]!,
+ this.mvx1[mb]!, this.mvy1[mb]!, true, true)
+ }
+
+ residualZero(mbx: int, mby: int): bool {
+ if (!this.lumaZero(mbx * 16, mby * 16)) return false
+ return this.chromaZero(mbx, mby)
+ }
+
+ storePredZero(mb: int, mbx: int, mby: int) {
+ this.storePred(mbx, mby)
+ this.cbp[mb] = 0
+ for (let k = 0; k < 24; k++) this.nnz[mb * 24 + k] = 0
+ }
+
+ finishB(mb: int, mbx: int, mby: int, tested: bool) {
+ if (!tested && this.residualZero(mbx, mby)) {
+ if (this.mbType[mb]! === MB_BDIRECT) this.mbType[mb] = MB_BSKIP
+ this.storePredZero(mb, mbx, mby)
+ return
+ }
+ this.predReady = true
+ this.codeMb(mbx, mby)
+ }
+
+ searchB(rf: RefFrame, mvxs: Int32Array, mvys: Int32Array, mbx: int, mby: int, lambda: int, list: int) {
+ const mb = mby * this.mbw + mbx
+ const px = mbx * 16
+ const py = mby * 16
+ let bix = this.clampMvx(px, (this.mvpX + 2) >> 2)
+ let biy = this.clampMvy(py, (this.mvpY + 2) >> 2)
+ this.seenGen++
+ if (this.seenGen >= 1 << 30) {
+ this.seen.fill(0)
+ this.seenGen = 1
+ }
+ this.seenX = bix - 32
+ this.seenY = biy - 32
+ this.visited(bix, biy)
+ let bsad = this.sadAt(rf, px, py, bix, biy)
+ let bc = bsad + this.mvCost(bix * 4, biy * 4, lambda)
+ const td = this.bTd > 0 ? this.bTd : 1
+ const tdc = this.bTdCol > 0 ? this.bTdCol : td
+ const scale = list === 0 ? this.bTb : this.bTb - td
+ for (let k = 0; k < 6 && bsad > 0; k++) {
+ let cx = 0
+ let cy = 0
+ if (k === 1) {
+ const dr = list === 0 ? this.dRef0 : this.dRef1
+ if (dr < 0) continue
+ cx = list === 0 ? this.dMx0 : this.dMx1
+ cy = list === 0 ? this.dMy0 : this.dMy1
+ } else if (k === 2) {
+ if (mbx === 0) continue
+ cx = mvxs[mb - 1]!
+ cy = mvys[mb - 1]!
+ } else if (k === 3) {
+ if (mby <= this.sliceRow0) continue
+ cx = mvxs[mb - this.mbw]!
+ cy = mvys[mb - this.mbw]!
+ } else if (k === 4) {
+ if (mby <= this.sliceRow0 || mbx + 1 >= this.mbw) continue
+ cx = mvxs[mb - this.mbw + 1]!
+ cy = mvys[mb - this.mbw + 1]!
+ } else if (k === 5) {
+ if (this.colRef[mb]! < 0) continue
+ cx = Math.trunc(this.colMvx[mb]! * scale / tdc)
+ cy = Math.trunc(this.colMvy[mb]! * scale / tdc)
+ }
+ const ix = this.clampMvx(px, (cx + 2) >> 2)
+ const iy = this.clampMvy(py, (cy + 2) >> 2)
+ if (ix === bix && iy === biy) continue
+ if (this.visited(ix, iy)) continue
+ const sd = this.sadAt(rf, px, py, ix, iy)
+ const c = sd + this.mvCost(ix * 4, iy * 4, lambda)
+ if (c < bc) {
+ bc = c
+ bix = ix
+ biy = iy
+ bsad = sd
+ }
+ }
+ for (let it = 0; it < this.meIters && bsad > 0; it++) {
+ let moved = false
+ for (let d = 0; d < 4; d++) {
+ const ix = this.clampMvx(px, bix + DIR_DX[d]!)
+ const iy = this.clampMvy(py, biy + DIR_DY[d]!)
+ if (ix === bix && iy === biy) continue
+ if (this.visited(ix, iy)) continue
+ const c = this.sadAt(rf, px, py, ix, iy) + this.mvCost(ix * 4, iy * 4, lambda)
+ if (c < bc) {
+ bc = c
+ bix = ix
+ biy = iy
+ moved = true
+ }
+ }
+ if (!moved) break
+ }
+ this.sMx = bix * 4
+ this.sMy = biy * 4
+ this.sCost = bc
+ this.sSad = true
+ }
+
+ refineB(rf: RefFrame, mbx: int, mby: int, lambda: int, first: int, last: int) {
+ const px = mbx * 16
+ const py = mby * 16
+ let bmx = this.sMx
+ let bmy = this.sMy
+ const halfSad = this.hpelSad && this.subpel > 0
+ const video = this.textMbs * 256 < this.mbw * this.mbh
+ const quarterSad = halfSad && (this.qpelSad || video) && this.mbq >= this.frameQp
+ let bq = this.sCost
+ let sadCost = this.sSad
+ if (first === 2) {
+ this.ensureTiles(rf, px + (bmx >> 2) - 1, py + (bmy >> 2) - 1, 19, 19)
+ if (!halfSad) bq = this.satdQpel(rf, px, py, bmx, bmy) + this.mvCost(bmx, bmy, lambda)
+ sadCost = halfSad
+ }
+ for (let step = first; step >= last && this.subpel > 0; step = step >> 1) {
+ const cx = bmx
+ const cy = bmy
+ const useSad = step === 2 ? halfSad : quarterSad
+ if (sadCost && !useSad) {
+ bq = this.satdQpel(rf, px, py, bmx, bmy) + this.mvCost(bmx, bmy, lambda)
+ sadCost = false
+ }
+ const dirs = !video ? this.subpelDirs : step === 2 ? this.videoHpelDirs : this.videoQpelDirs
+ for (let d = 0; d < dirs; d++) {
+ const mx = cx + DIR_DX[d]! * step
+ const my = cy + DIR_DY[d]! * step
+ const dist = !useSad ? this.satdQpel(rf, px, py, mx, my) : step === 2 ? this.sadHalf(rf, px, py, mx, my) :
+ this.sadQuarter(rf, px, py, mx, my)
+ const c = dist + this.mvCost(mx, my, lambda)
+ if (c < bq) {
+ bq = c
+ bmx = mx
+ bmy = my
+ }
+ }
+ }
+ if (last === 1 && sadCost) {
+ bq = this.satdQpel(rf, px, py, bmx, bmy) + this.mvCost(bmx, bmy, lambda)
+ sadCost = false
+ }
+ this.sMx = bmx
+ this.sMy = bmy
+ this.sCost = bq
+ this.sSad = sadCost
+ }
+
+ setSearchB(mx: int, my: int, cost: int, sadCost: bool, pX: int, pY: int) {
+ this.sMx = mx
+ this.sMy = my
+ this.sCost = cost
+ this.sSad = sadCost
+ this.mvpX = pX
+ this.mvpY = pY
+ }
+
+ codeMbB(mbx: int, mby: int) {
+ const mb = mby * this.mbw + mbx
+ this.mbq = this.mbQp[mb]!
+ const lambda = LAMBDA[this.mbq]!
+ const timed = ((mbx + mby) & 7) === 0
+ const a = timed ? performance.now() : 0.0
+ const px = mbx * 16
+ const py = mby * 16
+ const aw = this.aw
+ const so = py * aw + px
+ this.dcCbf[mb] = 0
+ this.t8[mb] = 0
+ this.deriveDirect(mbx, mby)
+ const gated = this.mbq >= B_GATE_QP
+ let dCost = BIG
+ let dTested = false
+ let dChroma = false
+ if (this.directInRange(px, py)) {
+ this.buildPredB(mbx, mby, this.dRef0 >= 0, this.dRef1 >= 0, this.dMx0, this.dMy0, this.dMx1, this.dMy1, true,
+ false)
+ if (sad16(this.srcY, so, aw, this.pred, 0, 16) <= B_SKIP_SAD * lambda) {
+ if (this.lumaZero(px, py)) {
+ this.directChroma(mbx, mby)
+ dChroma = true
+ if (this.chromaZero(mbx, mby)) {
+ this.setBDirect(mb, MB_BSKIP)
+ this.storePredZero(mb, mbx, mby)
+ if (timed) this.rMd += (performance.now() - a) * 8.0
+ return
+ }
+ }
+ dTested = true
+ }
+ const dSatd = satd16(this.srcY, so, aw, this.pred, 0, 16)
+ dCost = dSatd + lambda
+ const nb = mbx > 0 && mby > this.sliceRow0 && this.mbType[mb - 1]! >= MB_BSKIP &&
+ this.mbType[mb - 1]! <= MB_BDIRECT && this.mbType[mb - this.mbw]! >= MB_BSKIP &&
+ this.mbType[mb - this.mbw]! <= MB_BDIRECT
+ if (this.earlyExit && dSatd < (nb && gated ? this.bDirectNb : B_DIRECT_EARLY) * lambda) {
+ if (!dChroma) this.directChroma(mbx, mby)
+ this.setBDirect(mb, MB_BDIRECT)
+ const c = timed ? performance.now() : 0.0
+ this.finishB(mb, mbx, mby, dTested)
+ if (timed) {
+ const d = performance.now()
+ this.rMo += (c - a) * 8.0
+ this.rTq += (d - c) * 8.0
+ }
+ return
+ }
+ }
+ this.computeMvpL(mbx, mby, 0, 0)
+ const p0x = this.mvpX
+ const p0y = this.mvpY
+ const qpelBest = this.earlyExit && gated
+ const halfLast = qpelBest ? 2 : 1
+ this.searchB(this.refs[1]!, this.mvx, this.mvy, mbx, mby, lambda, 0)
+ this.refineB(this.refs[1]!, mbx, mby, lambda, 2, halfLast)
+ const h0x = this.sMx
+ const h0y = this.sMy
+ const h0c = this.sCost
+ const h0s = this.sSad
+ this.computeMvpL(mbx, mby, 0, 1)
+ const p1x = this.mvpX
+ const p1y = this.mvpY
+ this.searchB(this.refs[0]!, this.mvx1, this.mvy1, mbx, mby, lambda, 1)
+ this.refineB(this.refs[0]!, mbx, mby, lambda, 2, halfLast)
+ const h1c = this.sCost
+ this.refineB(this.refs[0]!, mbx, mby, lambda, qpelBest && h1c <= h0c ? 1 : 0, 1)
+ const m1x = this.sMx
+ const m1y = this.sMy
+ const c1 = this.sCost + 3 * lambda
+ this.setSearchB(h0x, h0y, h0c, h0s, p0x, p0y)
+ this.refineB(this.refs[1]!, mbx, mby, lambda, qpelBest && h0c <= h1c ? 1 : 0, 1)
+ const m0x = this.sMx
+ const m0y = this.sMy
+ const c0 = this.sCost + 3 * lambda
+ const asDirect = dCost < BIG && this.dRef0 >= 0 && this.dRef1 >= 0 && m0x === this.dMx0 && m0y === this.dMy0 &&
+ m1x === this.dMx1 && m1y === this.dMy1
+ let cBi = BIG
+ if (!asDirect && (!gated || c0 <= dCost || c1 <= dCost)) {
+ this.buildPredInto(this.predBi, mbx, mby, true, true, m0x, m0y, m1x, m1y, true, false)
+ cBi = satd16(this.srcY, so, aw, this.predBi, 0, 16) + lambda * (seBits(m0x - p0x) + seBits(m0y - p0y) +
+ seBits(m1x - p1x) + seBits(m1y - p1y) + 5)
+ }
+ let best = MB_BDIRECT
+ let bestCost = dCost
+ if (c0 < bestCost) {
+ best = MB_BL0
+ bestCost = c0
+ }
+ if (c1 < bestCost) {
+ best = MB_BL1
+ bestCost = c1
+ }
+ if (cBi < bestCost) {
+ best = MB_BBI
+ bestCost = cBi
+ }
+ const b = timed ? performance.now() : 0.0
+ this.intraEst = this.intraEstimate(mbx, mby)
+ const skipIntra = this.earlyExit && bestCost * 2 < this.intraEst * 3
+ // decideIntra codes its I4/I8 blocks through this.pred, which holds the direct prediction finishB reuses.
+ const keepDirect = !skipIntra && best === MB_BDIRECT
+ if (keepDirect) copyRect(this.predBi, 0, 16, this.pred, 0, 16, 16, 16)
+ const intraCost = skipIntra ? BIG : this.decideIntra(mbx, mby, bestCost)
+ if (keepDirect && intraCost >= bestCost) copyRect(this.pred, 0, 16, this.predBi, 0, 16, 16, 16)
+ const c = timed ? performance.now() : 0.0
+ if (intraCost < bestCost) {
+ this.commitIntra(mb, mbx, mby)
+ this.refIdx[mb] = -1
+ this.refIdx1[mb] = -1
+ this.mvx[mb] = 0
+ this.mvy[mb] = 0
+ this.mvx1[mb] = 0
+ this.mvy1[mb] = 0
+ this.mvdx[mb] = 0
+ this.mvdy[mb] = 0
+ this.mvdx1[mb] = 0
+ this.mvdy1[mb] = 0
+ this.codeMb(mbx, mby)
+ } else if (best === MB_BDIRECT) {
+ if (!dChroma) this.directChroma(mbx, mby)
+ this.setBDirect(mb, MB_BDIRECT)
+ this.finishB(mb, mbx, mby, dTested)
+ } else {
+ const u0 = best !== MB_BL1
+ const u1 = best !== MB_BL0
+ this.mbType[mb] = best
+ this.refIdx[mb] = u0 ? 0 : -1
+ this.refIdx1[mb] = u1 ? 0 : -1
+ this.mvx[mb] = u0 ? m0x : 0
+ this.mvy[mb] = u0 ? m0y : 0
+ this.mvx1[mb] = u1 ? m1x : 0
+ this.mvy1[mb] = u1 ? m1y : 0
+ this.mvdx[mb] = u0 ? m0x - p0x : 0
+ this.mvdy[mb] = u0 ? m0y - p0y : 0
+ this.mvdx1[mb] = u1 ? m1x - p1x : 0
+ this.mvdy1[mb] = u1 ? m1y - p1y : 0
+ if (best === MB_BBI) {
+ copyRect(this.pred, 0, 16, this.predBi, 0, 16, 16, 16)
+ this.buildPredB(mbx, mby, true, true, m0x, m0y, m1x, m1y, false, true)
+ } else {
+ this.buildPredB(mbx, mby, u0, u1, m0x, m0y, m1x, m1y, true, true)
+ }
+ this.finishB(mb, mbx, mby, false)
+ }
+ if (timed) {
+ const d = performance.now()
+ this.rMo += (b - a) * 8.0
+ this.rMd += (c - b) * 8.0
+ this.rTq += (d - c) * 8.0
+ }
+ }
+
+ edgeBsB(p: int, q: int): int {
+ const p0 = this.refIdx[p]! >= 0
+ const p1 = this.refIdx1[p]! >= 0
+ const q0 = this.refIdx[q]! >= 0
+ const q1 = this.refIdx1[q]! >= 0
+ if (p0 !== q0 || p1 !== q1) return 1
+ if (p0 && (iabs(this.mvx[p]! - this.mvx[q]!) >= 4 || iabs(this.mvy[p]! - this.mvy[q]!) >= 4)) return 1
+ if (p1 && (iabs(this.mvx1[p]! - this.mvx1[q]!) >= 4 || iabs(this.mvy1[p]! - this.mvy1[q]!) >= 4)) return 1
+ return 0
+ }
+
+ isIntra(mb: int): bool {
+ return this.mbType[mb]! <= MB_I8
+ }
+
+ computeMvp(mbx: int, mby: int, ref: int) {
+ this.computeMvpL(mbx, mby, ref, 0)
+ }
+
+ computeMvpL(mbx: int, mby: int, ref: int, list: int) {
+ if (list === 0) {
+ this.mvpFrom(this.mvx, this.mvy, this.refIdx, mbx, mby, ref)
+ } else {
+ this.mvpFrom(this.mvx1, this.mvy1, this.refIdx1, mbx, mby, ref)
+ }
+ }
+
+ mvpFrom(mvxs: Int32Array, mvys: Int32Array, refs: Int32Array, mbx: int, mby: int, ref: int) {
+ const mb = mby * this.mbw + mbx
+ const aAv = mbx > 0
+ const bAv = mby > this.sliceRow0
+ let cAv = bAv && mbx + 1 < this.mbw
+ let mbC = mb - this.mbw + 1
+ let rC = 12
+ if (!cAv) {
+ cAv = mbx > 0 && bAv
+ mbC = mb - this.mbw - 1
+ rC = 15
+ }
+ let refA = -1
+ let refB = -1
+ let refC = -1
+ let ax = 0
+ let ay = 0
+ let bx = 0
+ let by = 0
+ let cx = 0
+ let cy = 0
+ if (aAv && !this.isIntra(mb - 1)) {
+ refA = refs[mb - 1]!
+ ax = mvxs[mb - 1]!
+ ay = mvys[mb - 1]!
+ }
+ if (bAv && !this.isIntra(mb - this.mbw)) {
+ refB = refs[mb - this.mbw]!
+ bx = mvxs[mb - this.mbw]!
+ by = mvys[mb - this.mbw]!
+ }
+ if (cAv && !this.isIntra(mbC)) {
+ refC = refs[mbC]!
+ cx = mvxs[mbC]!
+ cy = mvys[mbC]!
+ }
+ if (!bAv && !cAv && aAv) {
+ refB = refA
+ refC = refA
+ bx = ax
+ by = ay
+ cx = ax
+ cy = ay
+ }
+ const ma = refA === ref ? 1 : 0
+ const mbb = refB === ref ? 1 : 0
+ const mc = refC === ref ? 1 : 0
+ if (ma + mbb + mc === 1) {
+ if (ma === 1) {
+ this.mvpX = ax
+ this.mvpY = ay
+ } else if (mbb === 1) {
+ this.mvpX = bx
+ this.mvpY = by
+ } else {
+ this.mvpX = cx
+ this.mvpY = cy
+ }
+ return
+ }
+ this.mvpX = median3(ax, bx, cx)
+ this.mvpY = median3(ay, by, cy)
+ }
+
+ computeSkipMv(mbx: int, mby: int) {
+ const mb = mby * this.mbw + mbx
+ if (mbx === 0 || mby === this.sliceRow0) {
+ this.skipX = 0
+ this.skipY = 0
+ return
+ }
+ const a = mb - 1
+ const b = mb - this.mbw
+ if (!this.isIntra(a) && this.refIdx[a]! === 0 && this.mvx[a]! === 0 && this.mvy[a]! === 0) {
+ this.skipX = 0
+ this.skipY = 0
+ return
+ }
+ if (!this.isIntra(b) && this.refIdx[b]! === 0 && this.mvx[b]! === 0 && this.mvy[b]! === 0) {
+ this.skipX = 0
+ this.skipY = 0
+ return
+ }
+ this.computeMvp(mbx, mby, 0)
+ this.skipX = this.mvpX
+ this.skipY = this.mvpY
+ }
+
+ clampMvx(px: int, ix: int): int {
+ const lo = -MVPAD - px + 6
+ const hi = this.aw + MVPAD - px - 24
+ return ix < lo ? lo : ix > hi ? hi : ix
+ }
+
+ clampMvy(py: int, iy: int): int {
+ let lo = -MVPAD - py + 6
+ let hi = this.ah + MVPAD - py - 24
+ if (lo < -500) lo = -500
+ if (hi > 500) hi = 500
+ return iy < lo ? lo : iy > hi ? hi : iy
+ }
+
+ sadAt(ref: RefFrame, px: int, py: int, ix: int, iy: int): int {
+ if (this.wpOn && ref === this.refs[0]!) return sad16(this.srcY, py * this.aw + px, this.aw, this.wref, this.ry(px + ix, py + iy), this.ys)
+ return sad16(this.srcY, py * this.aw + px, this.aw, ref.y, this.ry(px + ix, py + iy), this.ys)
+ }
+
+ satdQpel(rf: RefFrame, px: int, py: int, mx: int, my: int): int {
+ const so = py * this.aw + px
+ if (this.wpOn && rf === this.refs[0]!) {
+ this.predictQpel(this.trial, 0, 16, rf, px, py, mx, my, 16, 16)
+ return satd16(this.srcY, so, this.aw, this.trial, 0, 16)
+ }
+ const fx = mx & 3
+ const fy = my & 3
+ const base = this.ry(px + (mx >> 2), py + (my >> 2))
+ const ys = this.ys
+ if (fx === 0 && fy === 0) return satd16(this.srcY, so, this.aw, rf.y, base, ys)
+ if (fx === 2 && fy === 0) return satd16(this.srcY, so, this.aw, rf.hb, base, ys)
+ if (fx === 0 && fy === 2) return satd16(this.srcY, so, this.aw, rf.hh, base, ys)
+ if (fx === 2 && fy === 2) return satd16(this.srcY, so, this.aw, rf.hj, base, ys)
+ if (fy === 0) return satdAvg16(this.srcY, so, this.aw, rf.y, base + (fx >> 1), rf.hb, base, ys)
+ if (fx === 0) return satdAvg16(this.srcY, so, this.aw, rf.y, base + (fy >> 1) * ys, rf.hh, base, ys)
+ if (fx === 2) return satdAvg16(this.srcY, so, this.aw, rf.hj, base, rf.hb, base + (fy >> 1) * ys, ys)
+ if (fy === 2) return satdAvg16(this.srcY, so, this.aw, rf.hj, base, rf.hh, base + (fx >> 1), ys)
+ return satdAvg16(this.srcY, so, this.aw, rf.hb, base + (fy >> 1) * ys, rf.hh, base + (fx >> 1), ys)
+ }
+
+ visited(ix: int, iy: int): bool {
+ const sx = ix - this.seenX
+ const sy = iy - this.seenY
+ if ((sx | sy) < 0 || sx >= 64 || sy >= 64) return false
+ const k = sy * 64 + sx
+ if (this.seen[k]! === this.seenGen) return true
+ this.seen[k] = this.seenGen
+ return false
+ }
+
+ sadHalf(rf: RefFrame, px: int, py: int, mx: int, my: int): int {
+ const so = py * this.aw + px
+ if (this.wpOn && rf === this.refs[0]!) {
+ this.predictQpel(this.trial, 0, 16, rf, px, py, mx, my, 16, 16)
+ return sad16(this.srcY, so, this.aw, this.trial, 0, 16)
+ }
+ const base = this.ry(px + (mx >> 2), py + (my >> 2))
+ if ((mx & 3) === 0 && (my & 3) === 0) return sad16(this.srcY, so, this.aw, rf.y, base, this.ys)
+ if ((my & 3) === 0) return sad16(this.srcY, so, this.aw, rf.hb, base, this.ys)
+ if ((mx & 3) === 0) return sad16(this.srcY, so, this.aw, rf.hh, base, this.ys)
+ return sad16(this.srcY, so, this.aw, rf.hj, base, this.ys)
+ }
+
+ sadQuarter(rf: RefFrame, px: int, py: int, mx: int, my: int): int {
+ const so = py * this.aw + px
+ if (this.wpOn && rf === this.refs[0]!) {
+ this.predictQpel(this.trial, 0, 16, rf, px, py, mx, my, 16, 16)
+ return sad16(this.srcY, so, this.aw, this.trial, 0, 16)
+ }
+ const base = this.ry(px + (mx >> 2), py + (my >> 2))
+ const fx = mx & 3
+ const fy = my & 3
+ const ys = this.ys
+ if (fy === 0) return sadAvg16(this.srcY, so, this.aw, rf.y, base + (fx >> 1), rf.hb, base, ys)
+ if (fx === 0) return sadAvg16(this.srcY, so, this.aw, rf.y, base + (fy >> 1) * ys, rf.hh, base, ys)
+ if (fx === 2) return sadAvg16(this.srcY, so, this.aw, rf.hj, base, rf.hb, base + (fy >> 1) * ys, ys)
+ if (fy === 2) return sadAvg16(this.srcY, so, this.aw, rf.hj, base, rf.hh, base + (fx >> 1), ys)
+ return sadAvg16(this.srcY, so, this.aw, rf.hb, base + (fy >> 1) * ys, rf.hh, base + (fx >> 1), ys)
+ }
+
+ mvCost(mx: int, my: int, lambda: int): int {
+ return lambda * (seBits(mx - this.mvpX) + seBits(my - this.mvpY))
+ }
+
+ intraEstimate(mbx: int, mby: int): int {
+ const px = mbx * 16
+ const py = mby * 16
+ const av = this.mbAvail(mbx, mby)
+ pred16v(this.trial, 0, 16, this.srcY, this.aw, px, py, I16_DC, av)
+ return satd16(this.srcY, py * this.aw + px, this.aw, this.trial, 0, 16)
+ }
+
+ motionSearch(mbx: int, mby: int) {
+ const mb = mby * this.mbw + mbx
+ const px = mbx * 16
+ const py = mby * 16
+ const lambda = LAMBDA[this.mbq]!
+ this.intraEst = this.intraEstimate(mbx, mby)
+ const giveUp = this.intraEst + (this.intraEst >> 2) + 16 * lambda
+ let bestCost = BIG
+ let bestRef = 0
+ let bestMx = 0
+ let bestMy = 0
+ for (let ref = 0; ref < this.refsActive; ref++) {
+ const rf = this.refs[ref]!
+ this.computeMvp(mbx, mby, ref)
+ let bix = this.clampMvx(px, (this.mvpX + 2) >> 2)
+ let biy = this.clampMvy(py, (this.mvpY + 2) >> 2)
+ this.seenGen++
+ if (this.seenGen >= 1 << 30) {
+ this.seen.fill(0)
+ this.seenGen = 1
+ }
+ this.seenX = bix - 32
+ this.seenY = biy - 32
+ this.visited(bix, biy)
+ let bsad = this.sadAt(rf, px, py, bix, biy)
+ let bc = bsad + this.mvCost(bix * 4, biy * 4, lambda)
+ const cands = ref === 0 ? 9 : 5
+ for (let k = 0; k < cands && bsad > 0; k++) {
+ let cx = 0
+ let cy = 0
+ if (k === 1) {
+ if (mbx === 0) continue
+ cx = this.mvx[(mb - 1)]!
+ cy = this.mvy[(mb - 1)]!
+ } else if (k === 2) {
+ if (mby <= this.sliceRow0) continue
+ cx = this.mvx[(mb - this.mbw)]!
+ cy = this.mvy[(mb - this.mbw)]!
+ } else if (k === 3) {
+ if (mby <= this.sliceRow0 || mbx + 1 >= this.mbw) continue
+ cx = this.mvx[(mb - this.mbw + 1)]!
+ cy = this.mvy[(mb - this.mbw + 1)]!
+ } else if (k === 4) {
+ cx = this.prevMvx[mb]!
+ cy = this.prevMvy[mb]!
+ } else if (k === 5) {
+ if (!this.inScroll(mbx, mby)) continue
+ cx = this.scrollMvx
+ cy = this.scrollMvy
+ } else if (k === 6) {
+ if (this.cursorMb < 0) continue
+ const cmy = Math.trunc(this.cursorMb / this.mbw)
+ const cmx = this.cursorMb - cmy * this.mbw
+ if (iabs(cmx - mbx) > 2 || iabs(cmy - mby) > 2) continue
+ cx = this.cursorMvx
+ cy = this.cursorMvy
+ } else if (k === 7) {
+ if (this.shiftHx === 0) continue
+ cx = this.shiftHx
+ } else if (k === 8) {
+ if (this.shiftVy === 0) continue
+ cy = this.shiftVy
+ }
+ const ix = this.clampMvx(px, (cx + 2) >> 2)
+ const iy = this.clampMvy(py, (cy + 2) >> 2)
+ if (ix === bix && iy === biy) continue
+ if (this.visited(ix, iy)) continue
+ const sd = this.sadAt(rf, px, py, ix, iy)
+ const c = sd + this.mvCost(ix * 4, iy * 4, lambda)
+ if (c < bc || sd === 0) {
+ bc = c
+ bix = ix
+ biy = iy
+ bsad = sd
+ }
+ }
+ if (bsad === 0 || (this.earlyExit && bsad > giveUp)) {
+ const c0 = bc + lambda * (this.refsActive > 1 ? (this.refsActive === 2 ? 1 : ueBits(ref)) : 0)
+ if (c0 < bestCost) {
+ bestCost = c0
+ bestRef = ref
+ bestMx = bix * 4
+ bestMy = biy * 4
+ }
+ continue
+ }
+ for (let it = 0; it < this.meIters; it++) {
+ let moved = false
+ for (let d = 0; d < 4; d++) {
+ const ix = this.clampMvx(px, bix + DIR_DX[d]!)
+ const iy = this.clampMvy(py, biy + DIR_DY[d]!)
+ if (ix === bix && iy === biy) continue
+ if (this.visited(ix, iy)) continue
+ const c = this.sadAt(rf, px, py, ix, iy) + this.mvCost(ix * 4, iy * 4, lambda)
+ if (c < bc) {
+ bc = c
+ bix = ix
+ biy = iy
+ moved = true
+ }
+ }
+ if (!moved) break
+ }
+ this.ensureTiles(rf, px + bix - 1, py + biy - 1, 19, 19)
+ let bmx = bix * 4
+ let bmy = biy * 4
+ const halfSad = this.hpelSad && this.subpel > 0
+ const video = this.textMbs * 256 < this.mbw * this.mbh
+ const quarterSad = halfSad && (this.qpelSad || video) && this.mbq >= this.frameQp
+ let bq = halfSad ? bc : this.satdQpel(rf, px, py, bmx, bmy) + this.mvCost(bmx, bmy, lambda)
+ let sadCost = halfSad
+ for (let step = 2; step >= (this.subpel >= 2 ? 1 : 2) && this.subpel > 0; step = step >> 1) {
+ const cx = bmx
+ const cy = bmy
+ const useSad = step === 2 ? halfSad : quarterSad
+ if (sadCost && !useSad) {
+ bq = this.satdQpel(rf, px, py, bmx, bmy) + this.mvCost(bmx, bmy, lambda)
+ sadCost = false
+ }
+ const dirs = !video ? this.subpelDirs : step === 2 ? this.videoHpelDirs : this.videoQpelDirs
+ for (let d = 0; d < dirs; d++) {
+ const mx = cx + DIR_DX[d]! * step
+ const my = cy + DIR_DY[d]! * step
+ const dist = !useSad ? this.satdQpel(rf, px, py, mx, my) : step === 2 ? this.sadHalf(rf, px, py, mx, my) :
+ this.sadQuarter(rf, px, py, mx, my)
+ const c = dist + this.mvCost(mx, my, lambda)
+ if (c < bq) {
+ bq = c
+ bmx = mx
+ bmy = my
+ }
+ }
+ }
+ if (sadCost) bq = this.satdQpel(rf, px, py, bmx, bmy) + this.mvCost(bmx, bmy, lambda)
+ bq += lambda * (this.refsActive > 1 ? (this.refsActive === 2 ? 1 : ueBits(ref)) : 0)
+ if (bq < bestCost) {
+ bestCost = bq
+ bestRef = ref
+ bestMx = bmx
+ bestMy = bmy
+ }
+ }
+ this.refIdx[mb] = bestRef
+ this.mvx[mb] = bestMx
+ this.mvy[mb] = bestMy
+ this.mbType[mb] = MB_P16
+ this.meCost = bestCost
+ }
+
+ zeroMotion(mbx: int, mby: int) {
+ const mb = mby * this.mbw + mbx
+ this.refIdx[mb] = 0
+ this.mvx[mb] = 0
+ this.mvy[mb] = 0
+ this.mbType[mb] = MB_P16
+ this.computeMvp(mbx, mby, 0)
+ this.meCost = this.mvCost(0, 0, LAMBDA[this.mbq]!)
+ }
+
+ earlySkipMb(mbx: int, mby: int): bool {
+ const mb = mby * this.mbw + mbx
+ const top = mby > this.sliceRow0
+ const nb = (mbx > 0 && this.mbType[mb - 1]! === MB_PSKIP) || (top && this.mbType[mb - this.mbw]! === MB_PSKIP) ||
+ (top && mbx > 0 && this.mbType[mb - this.mbw - 1]! === MB_PSKIP) ||
+ (top && mbx + 1 < this.mbw && this.mbType[mb - this.mbw + 1]! === MB_PSKIP)
+ if (!nb) return false
+ this.computeSkipMv(mbx, mby)
+ this.skipProbed = true
+ if (!this.probeSkip(mbx, mby)) return false
+ this.setSkip(mb)
+ return true
+ }
+
+ probeSkip(mbx: int, mby: int): bool {
+ const px = mbx * 16
+ const py = mby * 16
+ const rf = this.refs[0]!
+ const ix = this.skipX >> 2
+ const iy = this.skipY >> 2
+ if (ix !== this.clampMvx(px, ix) || iy !== this.clampMvy(py, iy)) return false
+ this.ensureTiles(rf, px + ix - 1, py + iy - 1, 19, 19)
+ this.predictQpel(this.pred, 0, 16, rf, px, py, this.skipX, this.skipY, 16, 16)
+ const s = sad16(this.srcY, py * this.aw + px, this.aw, this.pred, 0, 16)
+ if (s === 0) return this.chromaSkipZero(mbx, mby)
+ if (s > 32 * LAMBDA[this.mbq]! * 4) return false
+ if (!this.lumaZero(px, py)) return false
+ return this.chromaSkipZero(mbx, mby)
+ }
+
+ lumaZero(px: int, py: int): bool {
+ const qbits = 15 + Math.idiv(this.mbq, 6)
+ const thr = (1 << qbits) - Math.idiv(1 << qbits, 6)
+ const t = i32x8.splat(thr)
+ const qm = (this.mbq % 6) * 16
+ const q0 = i32x8.load(QUANT4, qm)
+ const q1 = i32x8.load(QUANT4, qm + 8)
+ const sadMax = zeroSadMax(qm, thr, 0)
+ for (let by = 0; by < 16; by += 4) {
+ const so = (py + by) * this.aw + px
+ sadBlocks16(this.srcY, so, this.aw, this.pred, by * 16, 16, this.zsad)
+ for (let bx = 0; bx < 4; bx += 2) {
+ if (int(this.zsad[bx]!) <= sadMax && int(this.zsad[bx + 1]!) <= sadMax) continue
+ fwd4x2(this.srcY, so + bx * 4, this.aw, this.pred, by * 16 + bx * 4, 16, this.c32, 0)
+ const m = (i32x8.load(this.c32, 0).abs() * q0).max(i32x8.load(this.c32, 8).abs() * q1)
+ .max((i32x8.load(this.c32, 16).abs() * q0).max(i32x8.load(this.c32, 24).abs() * q1))
+ if (m.ge(t).mask() !== 0) return false
+ }
+ }
+ return true
+ }
+
+ chromaSkipZero(mbx: int, mby: int): bool {
+ const cx = mbx * 8
+ const cy = mby * 8
+ for (let pl = 0; pl < 2; pl++) {
+ const po = 256 + pl * 64
+ if (pl === 0) {
+ predictChroma(this.pred, po, 8, this.refs[0]!.u, this.cs, this.rc(cx, cy), this.skipX, this.skipY, 8, 8)
+ } else {
+ predictChroma(this.pred, po, 8, this.refs[0]!.v, this.cs, this.rc(cx, cy), this.skipX, this.skipY, 8, 8)
+ }
+ if (this.wpChromaOn) weightBlock(this.pred, po, 8, 8, 8, pl === 0 ? this.wpU[0]! : this.wpV[0]!, pl === 0 ? this.wpU[1]! : this.wpV[1]!)
+ }
+ return this.chromaZero(mbx, mby)
+ }
+
+ chromaZero(mbx: int, mby: int): bool {
+ const cx = mbx * 8
+ const cy = mby * 8
+ const qpc = int(CHROMA_QP[this.mbq]!)
+ const qbits = 15 + Math.trunc(qpc / 6)
+ const t = i32x8.splat((1 << qbits) - Math.trunc((1 << qbits) / 6))
+ const dcT = (2 << qbits) - Math.trunc((2 << qbits) / 6)
+ const qm = (qpc % 6) * 16
+ const mf = int(QUANT4[qm]!)
+ const q01 = i32x8.load(QUANT4, qm).withLane(0, 0)
+ const q23 = i32x8.load(QUANT4, qm + 8)
+ const acMax = zeroSadMax(qm, (1 << qbits) - Math.trunc((1 << qbits) / 6), 1)
+ const dcMax = Math.trunc((dcT - 1) / mf)
+ for (let pl = 0; pl < 2; pl++) {
+ const po = 256 + pl * 64
+ if (pl === 0) {
+ sadBlocks8(this.srcU, cy * this.cw + cx, this.cw, this.pred, po, this.zsad)
+ } else {
+ sadBlocks8(this.srcV, cy * this.cw + cx, this.cw, this.pred, po, this.zsad)
+ }
+ const dcFree = int(this.zsad[0]!) + int(this.zsad[1]!) + int(this.zsad[2]!) + int(this.zsad[3]!) <= dcMax
+ for (let b = 0; b < 4; b += 2) {
+ if (dcFree && int(this.zsad[b]!) <= acMax && int(this.zsad[b + 1]!) <= acMax) continue
+ const by = (b >> 1) * 4
+ const so = (cy + by) * this.cw + cx
+ if (pl === 0) {
+ fwd4x2(this.srcU, so, this.cw, this.pred, po + by * 8, 8, this.c32, 0)
+ } else {
+ fwd4x2(this.srcV, so, this.cw, this.pred, po + by * 8, 8, this.c32, 0)
+ }
+ const m = (i32x8.load(this.c32, 0).abs() * q01).max(i32x8.load(this.c32, 8).abs() * q23)
+ .max((i32x8.load(this.c32, 16).abs() * q01).max(i32x8.load(this.c32, 24).abs() * q23))
+ if (m.ge(t).mask() !== 0) return false
+ this.dc32[b] = this.c32[0]!
+ this.dc32[b + 1] = this.c32[16]!
+ }
+ if (dcFree) continue
+ hadamard2v(this.dc32, 0)
+ for (let k = 0; k < 4; k++) {
+ if (iabs(int(this.dc32[k]!)) * mf >= dcT) return false
+ }
+ }
+ return true
+ }
+
+ setSkip(mb: int) {
+ this.mbType[mb] = MB_PSKIP
+ this.refIdx[mb] = 0
+ this.mvx[mb] = this.skipX
+ this.mvy[mb] = this.skipY
+ this.mvdx[mb] = 0
+ this.mvdy[mb] = 0
+ }
+
+ decideInter(mbx: int, mby: int) {
+ const mb = mby * this.mbw + mbx
+ const meCost = this.meCost
+ const lambda = LAMBDA[this.mbq]!
+ this.computeSkipMv(mbx, mby)
+ const mvx = this.mvx[mb]!
+ const mvy = this.mvy[mb]!
+ if (this.refIdx[mb]! === 0 && mvx === this.skipX && mvy === this.skipY && !this.skipProbed && this.probeSkip(mbx, mby)) {
+ this.setSkip(mb)
+ return
+ }
+ const costInter = meCost + lambda
+ const keepRef = this.refIdx[mb]!
+ const skipIntra = this.refresh[mb]! !== 0 || (this.earlyExit && costInter * 4 < this.intraEst * 3)
+ const intraCost = skipIntra ? BIG : this.decideIntra(mbx, mby, costInter)
+ if (intraCost < costInter) {
+ this.commitIntra(mb, mbx, mby)
+ return
+ }
+ this.mbType[mb] = MB_P16
+ this.refIdx[mb] = keepRef
+ this.mvx[mb] = mvx
+ this.mvy[mb] = mvy
+ }
+
+ nbMode(n: int, r: int): int {
+ const t = this.mbType[n]!
+ return t === MB_I4 || t === MB_I8 ? this.imode[n * 16 + r]! : 2
+ }
+
+ predMode4(mb: int, mbx: int, mby: int, bx: int, by: int): int {
+ let a = -1
+ let b = -1
+ if (bx > 0) {
+ a = this.imode[mb * 16 + by * 4 + bx - 1]!
+ } else if (mbx > 0) {
+ a = this.nbMode(mb - 1, by * 4 + 3)
+ }
+ if (by > 0) {
+ b = this.imode[mb * 16 + (by - 1) * 4 + bx]!
+ } else if (mby > this.sliceRow0) {
+ b = this.nbMode(mb - this.mbw, 12 + bx)
+ }
+ if (a < 0 || b < 0) return 2
+ return a < b ? a : b
+ }
+
+ loadNbModes(mb: int, mbx: int, mby: int) {
+ const top = mby > this.sliceRow0
+ for (let k = 0; k < 4; k++) {
+ this.g4[(k + 1) * 5] = mbx > 0 ? this.nbMode(mb - 1, k * 4 + 3) : -1
+ this.g4[k + 1] = top ? this.nbMode(mb - this.mbw, 12 + k) : -1
+ }
+ }
+
+ predModeG(g: int): int {
+ const a = this.g4[g - 1]!
+ const b = this.g4[g - 5]!
+ return (a | b) < 0 ? I4_DC : a < b ? a : b
+ }
+
+ trial4(mb: int, mbx: int, mby: int, av: int, lambda: int, limit: int): int {
+ const px = mbx * 16
+ const py = mby * 16
+ const aw = this.aw
+ const ys = this.ys
+ const rec = this.cur.y
+ const rx = this.yorg + px
+ const b3 = lambda * 3
+ const b4 = lambda * 4
+ let cost4 = lambda * 2
+ let cbp = 0
+ blocks4(this.srcBlk, this.srcY, py * aw + px, aw)
+ for (let i = 0; i < 16 && cost4 < limit; i++) {
+ const r = BLK_RASTER[i]!
+ const bx = r & 3
+ const by = r >> 2
+ const bav = this.blkAv[av * 16 + r]!
+ edge4m(this.xb, rec, ys, rx + bx * 4, py + by * 4, bav, this.rec4, r)
+ const g = r + by + 6
+ i4Costs(this.cost9, this.srcBlk, r * 16, this.xb, bav, this.p4, this.predModeG(g), b3)
+ const bm = this.cost9[I4_BEST_MODE]!
+ this.g4[g] = bm
+ this.modes4[r] = bm
+ cost4 += this.cost9[I4_BEST_COST]! + b4
+ if (cost4 >= limit) break
+ cbp |= this.codeBlock4(r * 16, mb * 24 + r, r, u8x16.load(this.p4, bm * 16)) << (i >> 2)
+ }
+ if (cost4 < limit) this.cbp4 = cbp
+ return cost4
+ }
+
+ trial8(mb: int, mbx: int, mby: int, av: int, lambda: int, limit: int): int {
+ const px = mbx * 16
+ const py = mby * 16
+ const aw = this.aw
+ const ys = this.ys
+ const rec = this.cur.y
+ const rx = this.yorg + px
+ const b3 = lambda * 3
+ const b4 = lambda * 4
+ let cost8 = lambda * 2
+ let cbp = 0
+ for (let b8 = 0; b8 < 4 && cost8 < limit; b8++) {
+ const bx = b8 & 1
+ const by = b8 >> 1
+ const bav = this.blkAv[256 + av * 4 + b8]!
+ const x = px + bx * 8
+ const y = py + by * 8
+ edge8m(this.ip8, rec, ys, rx + bx * 8, y, bav, this.rec8, b8)
+ i8SrcCosts(this.cost9, this.srcY, y * aw + x, aw, this.ip8, bav)
+ const g = by * 10 + bx * 2 + 6
+ const pm = this.predModeG(g)
+ const avm = modeMask(bav)
+ let bm = I4_DC
+ let bc = BIG
+ if ((avm & 1) !== 0) {
+ bc = this.cost9[I4_V]! - (pm === I4_V ? b3 : 0)
+ bm = I4_V
+ }
+ if ((avm & 2) !== 0) {
+ const c = this.cost9[I4_H]! - (pm === I4_H ? b3 : 0)
+ if (c < bc) {
+ bc = c
+ bm = I4_H
+ }
+ }
+ const cd = this.cost9[I4_DC]! - (pm === I4_DC ? b3 : 0)
+ if (cd < bc) {
+ bc = cd
+ bm = I4_DC
+ }
+ const pmBit = pm > I4_DC ? 1 << pm : 0
+ let need = avm & (bc <= 0 || this.i8PredOnly ? pmBit : I8_DIR_MODES)
+ if (bc <= -b3) need &= ~pmBit
+ const so = y * aw + x
+ let left = need
+ while (left !== 0) {
+ const ma = Math.ctz32(left)
+ left &= left - 1
+ if (left === 0) {
+ this.cost9[ma] = i8Cost(this.srcY, so, aw, this.ip8, ma)
+ } else {
+ i8Cost2(this.cost9, this.srcY, so, aw, this.ip8, ma, Math.ctz32(left))
+ left &= left - 1
+ }
+ }
+ if (need !== 0) {
+ const c = i32x8.load(this.cost9, I4_DDL) - (i32x8.splat(pm).eq(I8_DIR_LANES) & i32x8.splat(b3))
+ const dir = i32x8.select((i32x8.splat(need) & I8_DIR_BITS).eq(i32x8.splat(0)), i32x8.splat(2147483647), c).minIndex()
+ if (dir.value < bc) {
+ bc = dir.value
+ bm = I4_DDL + dir.index
+ }
+ }
+ bc += b4
+ this.modes8[b8] = bm
+ this.g4[g] = bm
+ this.g4[g + 1] = bm
+ this.g4[g + 5] = bm
+ this.g4[g + 6] = bm
+ cost8 += bc
+ if (cost8 >= limit) break
+ cbp |= this.codeBlock8(b8, x, y, bm) << b8
+ }
+ if (cost8 < limit) this.cbp8 = cbp
+ return cost8
+ }
+
+ nearI8(mb: int, av: int): bool {
+ if ((av & AV_LEFT) !== 0 && this.mbType[mb - 1]! === MB_I8) return true
+ return (av & AV_TOP) !== 0 && this.mbType[mb - this.mbw]! === MB_I8
+ }
+
+ decideIntra(mbx: int, mby: int, bound: int): int {
+ const mb = mby * this.mbw + mbx
+ const px = mbx * 16
+ const py = mby * 16
+ const aw = this.aw
+ const ys = this.ys
+ const rec = this.cur.y
+ const rx = this.yorg + px
+ const av = this.mbAvail(mbx, mby)
+ const lambda = LAMBDA[this.mbq]!
+ let best16 = I16_DC
+ let cost16 = BIG
+ i16Satd(this.cost9, this.srcY, py * aw + px, aw, rec, ys, rx, py, av)
+ for (let m = 0; m < I16_PLANE; m++) {
+ if (!mode16Available(m, av)) continue
+ const c = lambda * (m === I16_DC ? 1 : 3) + this.cost9[m]!
+ if (c < cost16) {
+ cost16 = c
+ best16 = m
+ }
+ }
+ if (cost16 > lambda * 3 && mode16Available(I16_PLANE, av)) {
+ const c = lambda * 3 + i16PlaneSatd(this.srcY, py * aw + px, aw, rec, ys, rx, py)
+ if (c < cost16) {
+ cost16 = c
+ best16 = I16_PLANE
+ }
+ }
+ cost16 += lambda * 4
+ this.best16 = best16
+ let limit = cost16 < bound ? cost16 : bound
+ const flat16 = this.earlyExit && cost16 < 256 + lambda * 8
+ let cost4 = BIG
+ let cost8 = BIG
+ let done4 = false
+ let done8 = false
+ if (!flat16) {
+ this.loadNbModes(mb, mbx, mby)
+ if (this.useI4 && this.useI8 && bound === BIG && this.nearI8(mb, av)) {
+ cost8 = this.trial8(mb, mbx, mby, av, lambda, limit)
+ done8 = cost8 < limit
+ const limit4 = done8 ? cost8 + 1 : limit
+ cost4 = this.trial4(mb, mbx, mby, av, lambda, limit4)
+ done4 = cost4 < limit4
+ } else {
+ if (this.useI4) {
+ cost4 = this.trial4(mb, mbx, mby, av, lambda, limit)
+ if (cost4 < limit) {
+ limit = cost4
+ done4 = true
+ }
+ }
+ if (this.useI8) {
+ cost8 = this.trial8(mb, mbx, mby, av, lambda, limit)
+ done8 = cost8 < limit
+ }
+ }
+ }
+ this.coded4 = done4 ? mb : -1
+ this.coded8 = done8 ? mb : -1
+ for (let r = 0; r < 16; r++) this.imode[mb * 16 + r] = 2
+ let best = cost16
+ this.intraType = MB_I16
+ if (cost8 < cost16 && cost8 < cost4) {
+ this.intraType = MB_I8
+ best = cost8
+ } else if (cost4 < cost16) {
+ this.intraType = MB_I4
+ best = cost4
+ }
+ return best
+ }
+
+ commitIntra(mb: int, mbx: int, mby: int) {
+ const t = this.intraType
+ this.mbType[mb] = t
+ this.refIdx[mb] = -1
+ this.mvx[mb] = 0
+ this.mvy[mb] = 0
+ this.mvdx[mb] = 0
+ this.mvdy[mb] = 0
+ if (t === MB_I4) {
+ for (let r = 0; r < 16; r++) this.imode[mb * 16 + r] = this.modes4[r]!
+ } else if (t === MB_I8) {
+ for (let b8 = 0; b8 < 4; b8++) {
+ const r0 = (b8 >> 1) * 8 + (b8 & 1) * 2
+ const m = this.modes8[b8]!
+ this.imode[mb * 16 + r0] = m
+ this.imode[mb * 16 + r0 + 1] = m
+ this.imode[mb * 16 + r0 + 4] = m
+ this.imode[mb * 16 + r0 + 5] = m
+ }
+ } else {
+ this.i16Mode[mb] = this.best16
+ for (let r = 0; r < 16; r++) this.imode[mb * 16 + r] = 2
+ }
+ const av = this.mbAvail(mbx, mby)
+ const cx = mbx * 8
+ const cy = mby * 8
+ const cw = this.cw
+ const lambda = LAMBDA[this.mbq]!
+ let bestC = 0
+ let costC = BIG
+ const rcx = this.corg + cx
+ chromaSatd(this.cost9, this.srcU, this.srcV, cy * cw + cx, cw, this.cur.u, this.cur.v, this.cs, rcx, cy, av, this.uvBlk)
+ this.uvMb = mb
+ for (let m = 0; m < C_PLANE; m++) {
+ if (!chromaModeAvailable(m, av)) continue
+ const c = lambda * (m === 0 ? 1 : 3) + this.cost9[m]!
+ if (c < costC) {
+ costC = c
+ bestC = m
+ }
+ }
+ if (costC > lambda * 3 && chromaModeAvailable(C_PLANE, av)) {
+ const c = lambda * 3 + chromaPlaneSatd(this.uvBlk, this.cur.u, this.cur.v, this.cs, rcx, cy, this.uvPlane)
+ if (c < costC) bestC = C_PLANE
+ }
+ this.cMode[mb] = bestC
+ }
+
+ codeMb(mbx: int, mby: int) {
+ const mb = mby * this.mbw + mbx
+ const t = this.mbType[mb]!
+ const done4 = this.coded4 === mb
+ const done8 = this.coded8 === mb
+ const uvOk = this.uvMb === mb
+ this.coded4 = -1
+ this.coded8 = -1
+ this.uvMb = -1
+ this.dcCbf[mb] = 0
+ this.t8[mb] = 0
+ if (t === MB_PSKIP || t === MB_BSKIP) {
+ if (t === MB_PSKIP) {
+ this.copySkip(mbx, mby)
+ } else {
+ this.interPred(mb, mbx, mby)
+ this.storePred(mbx, mby)
+ }
+ this.cbp[mb] = 0
+ for (let k = 0; k < 24; k++) this.nnz[mb * 24 + k] = 0
+ return
+ }
+ if (t === MB_P16 || t >= MB_BDIRECT) {
+ this.codeInter(mb, mbx, mby)
+ return
+ }
+ let cbpL = 0
+ if (t === MB_I16) {
+ cbpL = this.codeLuma16(mb, mbx, mby)
+ } else if (t === MB_I4) {
+ if (done4) {
+ unblocks4(this.cur.y, this.ry(mbx * 16, mby * 16), this.ys, this.rec4)
+ cbpL = this.cbp4
+ } else {
+ cbpL = this.codeLuma4(mb, mbx, mby)
+ }
+ } else {
+ if (done8) {
+ unblocks8(this.cur.y, this.ry(mbx * 16, mby * 16), this.ys, this.rec8)
+ this.finishLuma8(mb)
+ cbpL = this.cbp8
+ } else {
+ cbpL = this.codeLuma8(mb, mbx, mby)
+ }
+ this.t8[mb] = 1
+ }
+ const cbpC = this.codeChromaIntra(mb, mbx, mby, uvOk)
+ this.cbp[mb] = cbpL | (cbpC << 4)
+ }
+
+ predictInter(mb: int, mbx: int, mby: int, mx: int, my: int, ref: int) {
+ const px = mbx * 16
+ const py = mby * 16
+ const rf = this.refs[ref]!
+ const ix = mx >> 2
+ const iy = my >> 2
+ this.ensureTiles(rf, px + ix - 1, py + iy - 1, 19, 19)
+ this.predictQpel(this.pred, 0, 16, rf, px, py, mx, my, 16, 16)
+ const base = this.rc(mbx * 8, mby * 8)
+ predictChroma(this.pred, 256, 8, rf.u, this.cs, base, mx, my, 8, 8)
+ predictChroma(this.pred, 320, 8, rf.v, this.cs, base, mx, my, 8, 8)
+ this.weightChroma(rf, 256)
+ }
+
+ copySkip(mbx: int, mby: int) {
+ const mb = mby * this.mbw + mbx
+ this.predictInter(mb, mbx, mby, this.skipX, this.skipY, 0)
+ this.storePred(mbx, mby)
+ }
+
+ storePred(mbx: int, mby: int) {
+ const cur = this.cur
+ copyRect(cur.y, this.ry(mbx * 16, mby * 16), this.ys, this.pred, 0, 16, 16, 16)
+ copy8(cur.u, this.rc(mbx * 8, mby * 8), this.cs, this.pred, 256, 8)
+ copy8(cur.v, this.rc(mbx * 8, mby * 8), this.cs, this.pred, 320, 8)
+ }
+
+ codeInter(mb: int, mbx: int, mby: int) {
+ const px = mbx * 16
+ const py = mby * 16
+ const aw = this.aw
+ const qp = this.mbq
+ const mx = this.mvx[mb]!
+ const my = this.mvy[mb]!
+ if (this.predReady) {
+ this.predReady = false
+ } else {
+ this.interPred(mb, mbx, mby)
+ }
+ let use8 = false
+ if (this.useI8 && this.inter8x8) {
+ const s4 = satd16(this.srcY, py * aw + px, aw, this.pred, 0, 16)
+ const s8 = sa8dPair(this.srcY, py * aw + px, aw, this.pred, 0, 16) +
+ sa8dPair(this.srcY, (py + 8) * aw + px, aw, this.pred, 128, 16)
+ use8 = s8 * 2 < s4 * 2 - (s4 >> 4)
+ }
+ let cbpL = 0
+ let mbScore = 0
+ const cabac = this.params.cabac
+ if (use8) {
+ for (let b8 = 0; b8 < 4; b8++) {
+ const bx = (b8 & 1) * 8
+ const by = (b8 >> 1) * 8
+ fwd8(this.srcY, (py + by) * aw + px + bx, aw, this.pred, by * 16 + bx, 16, this.lv32, b8 * 64)
+ const nz = quant8v(this.lv32, b8 * 64, qp, false)
+ const zo = b8 * 64
+ zigzag8(this.lv32, b8 * 64, this.coef, zo)
+ let sc = 0
+ if (nz > 0) sc = this.decimate ? decimateScore(this.coef, zo, 64, true) : 9
+ if (sc < 4) {
+ for (let k = 0; k < 64; k += 16) i16x16.splat(0).store(this.coef, zo + k)
+ } else {
+ cbpL |= 1 << b8
+ }
+ mbScore += sc
+ }
+ } else {
+ for (let b8 = 0; b8 < 4; b8++) {
+ let sc8 = 0
+ for (let s = 0; s < 4; s++) {
+ const r = BLK_RASTER[b8 * 4 + s]!
+ if ((s & 1) === 0) {
+ const bx = (r & 3) * 4
+ const by = (r >> 2) * 4
+ fwd4x2(this.srcY, (py + by) * aw + px + bx, aw, this.pred, by * 16 + bx, 16, this.lv32, r * 16)
+ }
+ const nz = quant4v(this.lv32, r * 16, qp, false, 0)
+ this.nz4[r] = nz
+ if (nz > 0) {
+ zigzag4(this.lv32, r * 16, this.coef, r * 16)
+ sc8 += this.decimate ? decimateScore(this.coef, r * 16, 16, false) : 9
+ } else if (!cabac) {
+ i16x16.splat(0).store(this.coef, r * 16)
+ }
+ }
+ if (sc8 < 4) {
+ for (let s = 0; s < 4; s++) {
+ const r = BLK_RASTER[b8 * 4 + s]!
+ this.nz4[r] = 0
+ if (!cabac) {
+ i16x16.splat(0).store(this.coef, r * 16)
+ }
+ }
+ } else {
+ cbpL |= 1 << b8
+ }
+ mbScore += sc8
+ }
+ }
+ if (this.decimate && mbScore < 6 && cbpL !== 0) {
+ cbpL = 0
+ for (let r = 0; r < 16; r++) this.nz4[r] = 0
+ if (!cabac || use8) {
+ for (let k = 0; k < 256; k += 16) i16x16.splat(0).store(this.coef, k)
+ }
+ }
+ this.t8[mb] = use8 && cbpL !== 0 ? 1 : 0
+ copyRect(this.cur.y, this.ry(px, py), this.ys, this.pred, 0, 16, 16, 16)
+ if (use8) {
+ for (let b8 = 0; b8 < 4; b8++) {
+ const bx = (b8 & 1) * 8
+ const by = (b8 >> 1) * 8
+ let nz = 0
+ for (let k = 0; k < 64; k++) {
+ if (this.coef[b8 * 64 + k]! !== 0) nz++
+ }
+ for (let s = 0; s < 4; s++) {
+ let c = 0
+ if (this.params.cabac) {
+ c = nz
+ } else {
+ for (let k = s; k < 64; k += 4) {
+ if (this.coef[b8 * 64 + k]! !== 0) c++
+ }
+ }
+ this.nnz[mb * 24 + BLK_RASTER[b8 * 4 + s]!] = c
+ }
+ if ((cbpL >> b8 & 1) !== 0) {
+ dequant8v(this.lv32, b8 * 64, this.lv32, b8 * 64, qp)
+ idct8v(this.lv32, b8 * 64)
+ recon8(this.cur.y, this.ry(px + bx, py + by), this.ys, this.lv32, b8 * 64, this.pred, by * 16 + bx, 16)
+ }
+ }
+ } else {
+ for (let r = 0; r < 16; r++) {
+ const bx = (r & 3) * 4
+ const by = (r >> 2) * 4
+ const nz = this.nz4[r]!
+ this.nnz[mb * 24 + r] = nz
+ if (nz > 0) {
+ dequant4v(this.lv32, r * 16, qp)
+ idct4v(this.lv32, r * 16)
+ recon4(this.cur.y, this.ry(px + bx, py + by), this.ys, this.lv32, r * 16, this.pred, by * 16 + bx, 16)
+ }
+ }
+ }
+ const cbpC = this.codeChromaResidual(mb, mbx, mby, false)
+ this.cbp[mb] = cbpL | (cbpC << 4)
+ if (this.sliceType === SLICE_B) {
+ if (this.mbType[mb]! === MB_BDIRECT && this.cbp[mb]! === 0) {
+ this.mbType[mb] = MB_BSKIP
+ this.t8[mb] = 0
+ for (let k = 0; k < 24; k++) this.nnz[mb * 24 + k] = 0
+ }
+ return
+ }
+ this.computeMvp(mbx, mby, this.refIdx[mb]!)
+ this.mvdx[mb] = mx - this.mvpX
+ this.mvdy[mb] = my - this.mvpY
+ if (this.cbp[mb]! === 0 && this.refIdx[mb]! === 0 && mx === this.skipX && my === this.skipY) {
+ this.setSkip(mb)
+ this.t8[mb] = 0
+ for (let k = 0; k < 24; k++) this.nnz[mb * 24 + k] = 0
+ }
+ }
+
+ codeLuma16(mb: int, mbx: int, mby: int): int {
+ const px = mbx * 16
+ const py = mby * 16
+ const aw = this.aw
+ const qp = this.mbq
+ const av = this.mbAvail(mbx, mby)
+ pred16v(this.pred, 0, 16, this.cur.y, this.ys, this.yorg + px, py, this.i16Mode[mb]!, av)
+ for (let b = 0; b < 16; b += 2) {
+ const bx = (b & 3) * 4
+ const by = (b >> 2) * 4
+ fwd4x2(this.srcY, (py + by) * aw + px + bx, aw, this.pred, by * 16 + bx, 16, this.lv32, b * 16)
+ this.dc32[b] = this.lv32[b * 16]!
+ this.dc32[b + 1] = this.lv32[b * 16 + 16]!
+ }
+ hadamard4v(this.dc32, 0, true)
+ const dcNz = quantDcv(this.dc32, 0, 16, qp, true)
+ this.dcCbf[mb] = dcNz > 0 ? 1 : 0
+ zigzag4(this.dc32, 0, this.coef, DC_OFF)
+ let acNz = 0
+ for (let b = 0; b < 16; b++) {
+ const nz = quant4v(this.lv32, b * 16, qp, true, 1)
+ this.nnz[mb * 24 + b] = nz
+ acNz += nz
+ zigzagAc4(this.lv32, b * 16, this.coef, b * 16)
+ }
+ const ro = this.ry(px, py)
+ if (acNz === 0 && dcNz === 0) {
+ copy16(this.cur.y, ro, this.ys, this.pred, 0)
+ return 0
+ }
+ hadamard4v(this.dc32, 0, false)
+ dequantLumaDcv(this.dc32, 0, qp)
+ if (acNz === 0) {
+ reconDc16(this.cur.y, ro, this.ys, this.dc32, this.pred, 0)
+ return 0
+ }
+ for (let b = 0; b < 16; b++) {
+ if (this.nnz[mb * 24 + b]! === 0) {
+ const k = i32x4.splat((this.dc32[b]! + 32) >> 6)
+ k.store(this.lv32, b * 16)
+ k.store(this.lv32, b * 16 + 4)
+ k.store(this.lv32, b * 16 + 8)
+ k.store(this.lv32, b * 16 + 12)
+ } else {
+ dequant4v(this.lv32, b * 16, qp)
+ this.lv32[b * 16] = this.dc32[b]!
+ idct4v(this.lv32, b * 16)
+ }
+ }
+ recon16(this.cur.y, ro, this.ys, this.lv32, this.pred, 0)
+ return 15
+ }
+
+ codeLuma4(mb: int, mbx: int, mby: int): int {
+ const px = mbx * 16
+ const py = mby * 16
+ const av = this.mbAvail(mbx, mby)
+ let cbpL = 0
+ blocks4(this.srcBlk, this.srcY, py * this.aw + px, this.aw)
+ for (let i = 0; i < 16; i++) {
+ const r = BLK_RASTER[i]!
+ const bav = this.blkAv[av * 16 + r]!
+ edge4m(this.xb, this.cur.y, this.ys, this.yorg + px + (r & 3) * 4, py + (r >> 2) * 4, bav, this.rec4, r)
+ cbpL |= this.codeBlock4(r * 16, mb * 24 + r, r, pred4v(this.xb, this.imode[mb * 16 + r]!, bav)) << (i >> 2)
+ }
+ unblocks4(this.cur.y, this.ry(px, py), this.ys, this.rec4)
+ return cbpL
+ }
+
+ codeBlock4(zo: int, no: int, r: int, pred: u8x16): int {
+ const nz = code4(u8x16.load(this.srcBlk, r * 16), pred, this.mbq, true, this.coef, zo, this.rec4, r * 16)
+ this.nnz[no] = nz
+ return nz > 0 ? 1 : 0
+ }
+
+ codeLuma8(mb: int, mbx: int, mby: int): int {
+ const px = mbx * 16
+ const py = mby * 16
+ const av = this.mbAvail(mbx, mby)
+ let cbpL = 0
+ for (let b8 = 0; b8 < 4; b8++) {
+ const bx = b8 & 1
+ const by = b8 >> 1
+ const bav = this.blkAv[256 + av * 4 + b8]!
+ const x = px + bx * 8
+ const y = py + by * 8
+ edge8m(this.ip8, this.cur.y, this.ys, this.yorg + x, y, bav, this.rec8, b8)
+ const mode = this.imode[mb * 16 + by * 8 + bx * 2]!
+ cbpL |= this.codeBlock8(b8, x, y, mode) << b8
+ }
+ unblocks8(this.cur.y, this.ry(px, py), this.ys, this.rec8)
+ this.finishLuma8(mb)
+ return cbpL
+ }
+
+ codeBlock8(b8: int, x: int, y: int, mode: int): int {
+ const qp = this.mbq
+ const lo = b8 * 64
+ pred8v(this.pred, 0, this.ip8, mode)
+ fwd8(this.srcY, y * this.aw + x, this.aw, this.pred, 0, 8, this.lv8, lo)
+ const nz = quant8v(this.lv8, lo, qp, true)
+ this.nz8[b8] = nz
+ if (nz > 0) {
+ dequant8v(this.lv8, lo, this.lv32, 0, qp)
+ idct8v(this.lv32, 0)
+ recon8b(this.rec8, lo, this.lv32, 0, this.pred, 0)
+ return 1
+ }
+ for (let k = 0; k < 64; k += 16) u8x16.load(this.pred, k).store(this.rec8, lo + k)
+ return 0
+ }
+
+ finishLuma8(mb: int) {
+ for (let b8 = 0; b8 < 4; b8++) {
+ const zo = b8 * 64
+ const nz = this.nz8[b8]!
+ if (nz === 0) {
+ const z = i16x16.splat(0)
+ for (let k = 0; k < 64; k += 16) z.store(this.coef, zo + k)
+ } else {
+ zigzag8(this.lv8, b8 * 64, this.coef, zo)
+ }
+ for (let s = 0; s < 4; s++) {
+ let n = 0
+ if (this.params.cabac) {
+ n = nz
+ } else if (nz > 0) {
+ for (let k = s; k < 64; k += 4) {
+ if (this.coef[zo + k]! !== 0) n++
+ }
+ }
+ this.nnz[mb * 24 + BLK_RASTER[b8 * 4 + s]!] = n
+ }
+ }
+ }
+
+ codeChromaIntra(mb: int, mbx: int, mby: int, uvOk: bool): int {
+ const mode = this.cMode[mb]!
+ if (uvOk) {
+ predChromaUv(this.pred, 256, this.uvBlk, this.uvPlane, mode)
+ } else {
+ const cx = mbx * 8
+ const cy = mby * 8
+ const av = this.mbAvail(mbx, mby)
+ predChromaV(this.pred, 256, 8, this.cur.u, this.cs, this.corg + cx, cy, mode, av)
+ predChromaV(this.pred, 320, 8, this.cur.v, this.cs, this.corg + cx, cy, mode, av)
+ }
+ return this.codeChromaResidual(mb, mbx, mby, true)
+ }
+
+ codeChromaResidual(mb: int, mbx: int, mby: int, intra: bool): int {
+ const qpc = int(CHROMA_QP[this.mbq]!)
+ const cx = mbx * 8
+ const cy = mby * 8
+ const cw = this.cw
+ let chromaAc = 0
+ let chromaDc = 0
+ let acU = 0
+ for (let pl = 0; pl < 2; pl++) {
+ if (pl === 1) acU = chromaAc
+ const po = 256 + pl * 64
+ const cb = pl * 64
+ for (let b = 0; b < 4; b += 2) {
+ const by = (b >> 1) * 4
+ const so = (cy + by) * cw + cx
+ if (pl === 0) {
+ fwd4x2(this.srcU, so, cw, this.pred, po + by * 8, 8, this.c32, cb + b * 16)
+ } else {
+ fwd4x2(this.srcV, so, cw, this.pred, po + by * 8, 8, this.c32, cb + b * 16)
+ }
+ this.dc32[pl * 4 + b] = this.c32[cb + b * 16]!
+ this.dc32[pl * 4 + b + 1] = this.c32[cb + b * 16 + 16]!
+ }
+ hadamard2v(this.dc32, pl * 4)
+ const dn = quantDcv(this.dc32, pl * 4, 4, qpc, intra)
+ chromaDc += dn
+ if (dn > 0) this.dcCbf[mb] = this.dcCbf[mb]! | (2 << pl)
+ for (let k = 0; k < 4; k++) this.coef[CHROMA_DC_OFF + pl * 4 + k] = this.dc32[pl * 4 + k]!
+ const acZero = chromaAcZero(this.c32, cb, qpc, intra)
+ for (let b = 0; b < 4; b++) {
+ const zo = CHROMA_AC_OFF + (pl * 4 + b) * 16
+ const nz = acZero ? 0 : quant4v(this.c32, cb + b * 16, qpc, intra, 1)
+ this.nnz[mb * 24 + 16 + pl * 4 + b] = nz
+ chromaAc += nz
+ if (nz === 0) {
+ i16x16.splat(0).store(this.coef, zo)
+ } else {
+ zigzagAc4(this.c32, cb + b * 16, this.coef, zo)
+ }
+ }
+ }
+ if (!intra && this.decimate && chromaAc > 0) {
+ let sc = 0
+ for (let pl = 0; pl < 2 && sc < 7; pl++) {
+ for (let b = 0; b < 4 && sc < 7; b++) {
+ sc += decimateScore(this.coef, CHROMA_AC_OFF + (pl * 4 + b) * 16, 15, false)
+ }
+ }
+ if (sc < 7) {
+ chromaAc = 0
+ for (let b = 0; b < 8; b++) this.nnz[mb * 24 + 16 + b] = 0
+ for (let k = 0; k < 128; k += 16) i16x16.splat(0).store(this.coef, CHROMA_AC_OFF + k)
+ }
+ }
+ const cbpC = chromaAc > 0 ? 2 : chromaDc > 0 ? 1 : 0
+ const ro = this.rc(cx, cy)
+ for (let pl = 0; pl < 2; pl++) {
+ const po = 256 + pl * 64
+ const cb = pl * 64
+ if (cbpC === 0) {
+ if (pl === 0) {
+ copy8(this.cur.u, ro, this.cs, this.pred, po, 8)
+ } else {
+ copy8(this.cur.v, ro, this.cs, this.pred, po, 8)
+ }
+ continue
+ }
+ hadamard2v(this.dc32, pl * 4)
+ dequantChromaDcv(this.dc32, pl * 4, qpc)
+ if (cbpC === 1 || (pl === 0 ? acU : chromaAc - acU) === 0) {
+ if (pl === 0) {
+ reconDcC8(this.cur.u, ro, this.cs, this.dc32, 0, this.pred, po)
+ } else {
+ reconDcC8(this.cur.v, ro, this.cs, this.dc32, 4, this.pred, po)
+ }
+ continue
+ }
+ for (let b = 0; b < 4; b++) {
+ const o = cb + b * 16
+ if (cbpC === 2) {
+ dequant4v(this.c32, o, qpc)
+ } else {
+ for (let k = 0; k < 16; k += 4) i32x4.splat(0).store(this.c32, o + k)
+ }
+ this.c32[o] = this.dc32[pl * 4 + b]!
+ }
+ idctC8(this.c32, cb, pl === 0 ? this.cur.u : this.cur.v, ro, this.cs, this.pred, po)
+ }
+ if (cbpC !== 2) {
+ for (let k = 16; k < 24; k++) this.nnz[mb * 24 + k] = 0
+ }
+ return cbpC
+ }
+
+ lumaNc(mb: int, mbx: int, mby: int, b: int): int {
+ const bx = b & 3
+ const by = b >> 2
+ let na = -1
+ let nb = -1
+ if (bx > 0) {
+ na = this.nnz[mb * 24 + b - 1]!
+ } else if (mbx > 0) {
+ na = this.nnz[(mb - 1) * 24 + b + 3]!
+ }
+ if (by > 0) {
+ nb = this.nnz[mb * 24 + b - 4]!
+ } else if (mby > this.sliceRow0) {
+ nb = this.nnz[(mb - this.mbw) * 24 + b + 12]!
+ }
+ if (na >= 0 && nb >= 0) return (na + nb + 1) >> 1
+ if (na >= 0) return na
+ if (nb >= 0) return nb
+ return 0
+ }
+
+ chromaNc(mb: int, mbx: int, mby: int, pl: int, b: int): int {
+ const bx = b & 1
+ const by = b >> 1
+ const base = 16 + pl * 4
+ let na = -1
+ let nb = -1
+ if (bx > 0) {
+ na = this.nnz[mb * 24 + base + b - 1]!
+ } else if (mbx > 0) {
+ na = this.nnz[(mb - 1) * 24 + base + b + 1]!
+ }
+ if (by > 0) {
+ nb = this.nnz[mb * 24 + base + b - 2]!
+ } else if (mby > this.sliceRow0) {
+ nb = this.nnz[(mb - this.mbw) * 24 + base + b + 2]!
+ }
+ if (na >= 0 && nb >= 0) return (na + nb + 1) >> 1
+ if (na >= 0) return na
+ if (nb >= 0) return nb
+ return 0
+ }
+
+ writeMbCavlc(mbx: int, mby: int) {
+ const bw = this.bw
+ const mb = mby * this.mbw + mbx
+ const t = this.mbType[mb]!
+ if (t === MB_PSKIP || t === MB_BSKIP) {
+ this.skipRun++
+ return
+ }
+ if (this.sliceType !== SLICE_I) {
+ bw.ue(this.skipRun)
+ this.skipRun = 0
+ }
+ const cbp = this.cbp[mb]!
+ if (t === MB_I16 || cbp !== 0) this.loadCoef(mb, mby, t, cbp)
+ const cbpL = cbp & 15
+ const cbpC = cbp >> 4
+ const off = this.sliceType === SLICE_P ? 5 : this.sliceType === SLICE_B ? 23 : 0
+ if (t >= MB_BDIRECT) {
+ bw.ue(t === MB_BDIRECT ? 0 : t === MB_BL0 ? 1 : t === MB_BL1 ? 2 : 3)
+ if (t === MB_BL0 || t === MB_BBI) {
+ bw.se(this.mvdx[mb]!)
+ bw.se(this.mvdy[mb]!)
+ }
+ if (t === MB_BL1 || t === MB_BBI) {
+ bw.se(this.mvdx1[mb]!)
+ bw.se(this.mvdy1[mb]!)
+ }
+ bw.ue(int(CBP_CODE_INTER[cbp]!))
+ if (cbpL !== 0 && this.params.transform8x8) bw.putBit(this.t8[mb]!)
+ if (cbp !== 0) bw.se(this.qpDelta[mb]!)
+ this.writeLumaResidualCavlc(mb, mbx, mby, cbpL, this.t8[mb]! === 1)
+ } else if (t === MB_P16) {
+ bw.ue(0)
+ if (this.refsActive === 2) {
+ bw.putBit(this.refIdx[mb]! === 0 ? 1 : 0)
+ } else if (this.refsActive > 2) {
+ bw.ue(this.refIdx[mb]!)
+ }
+ bw.se(this.mvdx[mb]!)
+ bw.se(this.mvdy[mb]!)
+ bw.ue(int(CBP_CODE_INTER[cbp]!))
+ if (cbpL !== 0 && this.params.transform8x8) bw.putBit(this.t8[mb]!)
+ if (cbp !== 0) bw.se(this.qpDelta[mb]!)
+ this.writeLumaResidualCavlc(mb, mbx, mby, cbpL, this.t8[mb]! === 1)
+ } else if (t === MB_I16) {
+ bw.ue(off + 1 + this.i16Mode[mb]! + 4 * cbpC + (cbpL !== 0 ? 12 : 0))
+ bw.ue(this.cMode[mb]!)
+ bw.se(this.qpDelta[mb]!)
+ writeResidual(bw, this.coef, DC_OFF, 16, this.lumaNc(mb, mbx, mby, 0))
+ if (cbpL !== 0) {
+ for (let i = 0; i < 16; i++) {
+ const b = BLK_RASTER[i]!
+ writeResidual(bw, this.coef, b * 16, 15, this.lumaNc(mb, mbx, mby, b))
+ }
+ } else {
+ for (let b = 0; b < 16; b++) this.nnz[mb * 24 + b] = 0
+ }
+ } else {
+ bw.ue(off)
+ if (this.params.transform8x8) bw.putBit(t === MB_I8 ? 1 : 0)
+ if (t === MB_I4) {
+ for (let i = 0; i < 16; i++) {
+ const r = BLK_RASTER[i]!
+ this.writeModeFlag(this.imode[mb * 16 + r]!, this.predMode4(mb, mbx, mby, r & 3, r >> 2))
+ }
+ } else {
+ for (let b8 = 0; b8 < 4; b8++) {
+ const bx = (b8 & 1) * 2
+ const by = (b8 >> 1) * 2
+ this.writeModeFlag(this.imode[mb * 16 + by * 4 + bx]!, this.predMode4(mb, mbx, mby, bx, by))
+ }
+ }
+ bw.ue(this.cMode[mb]!)
+ bw.ue(int(CBP_CODE_INTRA[cbp]!))
+ if (cbp !== 0) bw.se(this.qpDelta[mb]!)
+ this.writeLumaResidualCavlc(mb, mbx, mby, cbpL, t === MB_I8)
+ }
+ if (cbpC !== 0) {
+ writeResidual(bw, this.coef, CHROMA_DC_OFF, 4, -1)
+ writeResidual(bw, this.coef, CHROMA_DC_OFF + 4, 4, -1)
+ }
+ if (cbpC === 2) {
+ for (let pl = 0; pl < 2; pl++) {
+ for (let b = 0; b < 4; b++) {
+ writeResidual(bw, this.coef, CHROMA_AC_OFF + (pl * 4 + b) * 16, 15, this.chromaNc(mb, mbx, mby, pl, b))
+ }
+ }
+ }
+ }
+
+ writeLumaResidualCavlc(mb: int, mbx: int, mby: int, cbpL: int, is8: bool) {
+ const bw = this.bw
+ for (let b8 = 0; b8 < 4; b8++) {
+ if ((cbpL & (1 << b8)) === 0) {
+ // Entropy rows run while the deblocking wavefront reads nnz; coding already zeroed these, so don't store.
+ for (let s = 0; s < 4; s++) {
+ const k = mb * 24 + BLK_RASTER[b8 * 4 + s]!
+ if (this.nnz[k]! !== 0) this.nnz[k] = 0
+ }
+ continue
+ }
+ for (let s = 0; s < 4; s++) {
+ const r = BLK_RASTER[b8 * 4 + s]!
+ if (is8) {
+ for (let k = 0; k < 16; k++) this.blk16[k] = this.coef[b8 * 64 + 4 * k + s]!
+ writeResidual(bw, this.blk16, 0, 16, this.lumaNc(mb, mbx, mby, r))
+ } else {
+ writeResidual(bw, this.coef, r * 16, 16, this.lumaNc(mb, mbx, mby, r))
+ }
+ }
+ }
+ }
+
+ leftMb(mb: int, mbx: int): int {
+ return mbx > 0 ? mb - 1 : -1
+ }
+
+ topMb(mb: int, mby: int): int {
+ return mby > this.sliceRow0 ? mb - this.mbw : -1
+ }
+
+ cbfLuma4(mb: int, mbx: int, mby: int, r: int, intraCur: bool): int {
+ const bx = r & 3
+ const by = r >> 2
+ let a = 0
+ let b = 0
+ if (bx > 0) {
+ a = this.lumaBlkCoded(mb, r - 1)
+ } else if (mbx > 0) {
+ a = this.lumaBlkCoded(mb - 1, r + 3)
+ } else {
+ a = intraCur ? 1 : 0
+ }
+ if (by > 0) {
+ b = this.lumaBlkCoded(mb, r - 4)
+ } else if (mby > this.sliceRow0) {
+ b = this.lumaBlkCoded(mb - this.mbw, r + 12)
+ } else {
+ b = intraCur ? 1 : 0
+ }
+ return a + 2 * b
+ }
+
+ lumaBlkCoded(mb: int, r: int): int {
+ if (this.mbType[mb]! === MB_PSKIP || this.mbType[mb]! === MB_BSKIP) return 0
+ const b8 = ((r >> 3) << 1) | ((r & 3) >> 1)
+ if (((this.cbp[mb]! & 15) >> b8 & 1) === 0) return 0
+ if (this.t8[mb]! === 1) return 1
+ return this.nnz[mb * 24 + r]! > 0 ? 1 : 0
+ }
+
+ cbfChroma4(mb: int, mbx: int, mby: int, pl: int, b: int, intraCur: bool): int {
+ const bx = b & 1
+ const by = b >> 1
+ const base = 16 + pl * 4
+ let a = 0
+ let c = 0
+ if (bx > 0) {
+ a = this.nnz[mb * 24 + base + b - 1]! > 0 ? 1 : 0
+ } else if (mbx > 0) {
+ a = (this.cbp[mb - 1]! >> 4) === 2 && this.nnz[(mb - 1) * 24 + base + b + 1]! > 0 ? 1 : 0
+ } else {
+ a = intraCur ? 1 : 0
+ }
+ if (by > 0) {
+ c = this.nnz[mb * 24 + base + b - 2]! > 0 ? 1 : 0
+ } else if (mby > this.sliceRow0) {
+ c = (this.cbp[mb - this.mbw]! >> 4) === 2 && this.nnz[(mb - this.mbw) * 24 + base + b + 2]! > 0 ? 1 : 0
+ } else {
+ c = intraCur ? 1 : 0
+ }
+ return a + 2 * c
+ }
+
+ cbfDc(mb: int, mbx: int, mby: int, bit: int, intraCur: bool): int {
+ const l = this.leftMb(mb, mbx)
+ const t = this.topMb(mb, mby)
+ let a = intraCur ? 1 : 0
+ let b = intraCur ? 1 : 0
+ if (l >= 0) a = this.dcCoded(l, bit)
+ if (t >= 0) b = this.dcCoded(t, bit)
+ return a + 2 * b
+ }
+
+ dcCoded(mb: int, bit: int): int {
+ if (this.mbType[mb]! === MB_PSKIP || this.mbType[mb]! === MB_BSKIP) return 0
+ if (bit === 0 && this.mbType[mb]! !== MB_I16) return 0
+ if (bit > 0 && (this.cbp[mb]! >> 4) === 0) return 0
+ return ((this.dcCbf[mb]! >> bit) & 1)
+ }
+
+ writeMvdCabac(base: int, v: int, sumAbs: int) {
+ const c = this.cabac
+ const inc0 = sumAbs < 3 ? 0 : sumAbs > 32 ? 2 : 1
+ const a = v < 0 ? -v : v
+ const pre = a < 9 ? a : 9
+ for (let k = 0; k < pre; k++) {
+ const inc = k === 0 ? inc0 : k === 1 ? 3 : k === 2 ? 4 : k === 3 ? 5 : 6
+ c.decision(base + inc, 1)
+ }
+ if (a < 9) {
+ const inc = pre === 0 ? inc0 : pre === 1 ? 3 : pre === 2 ? 4 : pre === 3 ? 5 : 6
+ c.decision(base + inc, 0)
+ } else {
+ const k = 63 - Math.clz64(a - 1)
+ c.bypassBits((((1 << (k - 3)) - 1) << (k + 2)) | ((a - 1 - (1 << k)) << 1) | (v < 0 ? 1 : 0), 2 * k - 1)
+ return
+ }
+ if (a !== 0) c.bypass(v < 0 ? 1 : 0)
+ }
+
+ writeRowCabac(mby: int, lastRow: bool) {
+ const c = this.cabac
+ const mbw = this.mbw
+ const types = this.mbType
+ const skip = this.sliceType === SLICE_P ? MB_PSKIP : this.sliceType === SLICE_B ? MB_BSKIP : 0
+ const ctxIdx = this.sliceType === SLICE_P ? 11 : 24
+ const row = mby * mbw
+ const end = skip === 0 ? 0 : lastRow ? mbw - 1 : mbw
+ let mbx = 0
+ while (mbx < mbw) {
+ if (mbx < end && types[row + mbx]! === skip) {
+ const x0 = mbx
+ mbx++
+ while (mbx < end && types[row + mbx]! === skip) mbx++
+ const left = x0 > 0 && types[row + x0 - 1]! !== skip ? 1 : 0
+ c.skipRun(types, mby > this.sliceRow0 ? row - mbw + x0 : -1, mbx - x0, left, skip, ctxIdx)
+ this.lastDeltaNz = false
+ } else {
+ this.writeMbCabac(mbx, mby)
+ c.terminate(lastRow && mbx === mbw - 1 ? 1 : 0)
+ mbx++
+ }
+ }
+ }
+
+ writeMbCabac(mbx: int, mby: int) {
+ const c = this.cabac
+ c.room()
+ const mb = mby * this.mbw + mbx
+ const t = this.mbType[mb]!
+ const l = this.leftMb(mb, mbx)
+ const tp = this.topMb(mb, mby)
+ const pslice = this.sliceType === SLICE_P
+ const bslice = this.sliceType === SLICE_B
+ if (pslice) {
+ const sa = l >= 0 && this.mbType[l]! !== MB_PSKIP ? 1 : 0
+ const sb = tp >= 0 && this.mbType[tp]! !== MB_PSKIP ? 1 : 0
+ c.decision(11 + sa + sb, t === MB_PSKIP ? 1 : 0)
+ if (t === MB_PSKIP) {
+ this.lastDeltaNz = false
+ return
+ }
+ } else if (bslice) {
+ const sa = l >= 0 && this.mbType[l]! !== MB_BSKIP ? 1 : 0
+ const sb = tp >= 0 && this.mbType[tp]! !== MB_BSKIP ? 1 : 0
+ c.decision(24 + sa + sb, t === MB_BSKIP ? 1 : 0)
+ if (t === MB_BSKIP) {
+ this.lastDeltaNz = false
+ return
+ }
+ }
+ const cbp = this.cbp[mb]!
+ if (t === MB_I16 || cbp !== 0) this.loadCoef(mb, mby, t, cbp)
+ const cbpL = cbp & 15
+ const cbpC = cbp >> 4
+ const intra = t <= MB_I8
+ if (bslice) {
+ const ca = l >= 0 && this.mbType[l]! !== MB_BSKIP && this.mbType[l]! !== MB_BDIRECT ? 1 : 0
+ const cb = tp >= 0 && this.mbType[tp]! !== MB_BSKIP && this.mbType[tp]! !== MB_BDIRECT ? 1 : 0
+ if (t === MB_BDIRECT) {
+ c.decision(27 + ca + cb, 0)
+ } else {
+ c.decision(27 + ca + cb, 1)
+ if (t === MB_BL0 || t === MB_BL1) {
+ c.decision(30, 0)
+ c.decision(32, t === MB_BL1 ? 1 : 0)
+ } else if (t === MB_BBI) {
+ c.decision(30, 1)
+ c.decision(31, 0)
+ c.decision(32, 0)
+ c.decision(32, 0)
+ c.decision(32, 0)
+ } else {
+ c.decision(30, 1)
+ c.decision(31, 1)
+ c.decision(32, 1)
+ c.decision(32, 0)
+ c.decision(32, 1)
+ }
+ }
+ if (t === MB_BL0 || t === MB_BBI) {
+ const ax = l >= 0 ? iabs(this.mvdx[l]!) : 0
+ const bx = tp >= 0 ? iabs(this.mvdx[tp]!) : 0
+ this.writeMvdCabac(40, this.mvdx[mb]!, ax + bx)
+ const ay = l >= 0 ? iabs(this.mvdy[l]!) : 0
+ const by = tp >= 0 ? iabs(this.mvdy[tp]!) : 0
+ this.writeMvdCabac(47, this.mvdy[mb]!, ay + by)
+ }
+ if (t === MB_BL1 || t === MB_BBI) {
+ const ax = l >= 0 ? iabs(this.mvdx1[l]!) : 0
+ const bx = tp >= 0 ? iabs(this.mvdx1[tp]!) : 0
+ this.writeMvdCabac(40, this.mvdx1[mb]!, ax + bx)
+ const ay = l >= 0 ? iabs(this.mvdy1[l]!) : 0
+ const by = tp >= 0 ? iabs(this.mvdy1[tp]!) : 0
+ this.writeMvdCabac(47, this.mvdy1[mb]!, ay + by)
+ }
+ }
+ if (t === MB_P16) {
+ c.decision(14, 0)
+ c.decision(15, 0)
+ c.decision(16, 0)
+ if (this.refsActive > 1) {
+ const ra = l >= 0 && !this.isIntra(l) && this.mbType[l]! !== MB_PSKIP && this.refIdx[l]! > 0 ? 1 : 0
+ const rb = tp >= 0 && !this.isIntra(tp) && this.mbType[tp]! !== MB_PSKIP && this.refIdx[tp]! > 0 ? 1 : 0
+ const ref = this.refIdx[mb]!
+ for (let k = 0; k < ref; k++) c.decision(54 + (k === 0 ? ra + 2 * rb : k === 1 ? 4 : 5), 1)
+ c.decision(54 + (ref === 0 ? ra + 2 * rb : ref === 1 ? 4 : 5), 0)
+ }
+ const ax = l >= 0 ? iabs(this.mvdx[l]!) : 0
+ const bx = tp >= 0 ? iabs(this.mvdx[tp]!) : 0
+ this.writeMvdCabac(40, this.mvdx[mb]!, ax + bx)
+ const ay = l >= 0 ? iabs(this.mvdy[l]!) : 0
+ const by = tp >= 0 ? iabs(this.mvdy[tp]!) : 0
+ this.writeMvdCabac(47, this.mvdy[mb]!, ay + by)
+ } else if (intra) {
+ const incA = l >= 0 && this.mbType[l]! !== MB_I4 && this.mbType[l]! !== MB_I8 ? 1 : 0
+ const incB = tp >= 0 && this.mbType[tp]! !== MB_I4 && this.mbType[tp]! !== MB_I8 ? 1 : 0
+ if (pslice) c.decision(14, 1)
+ const sufOff = pslice ? 17 : 32
+ const b0 = pslice || bslice ? sufOff : 3 + incA + incB
+ if (t === MB_I16) {
+ c.decision(b0, 1)
+ c.terminate(0)
+ const m = this.i16Mode[mb]!
+ if (pslice || bslice) {
+ c.decision(sufOff + 1, cbpL !== 0 ? 1 : 0)
+ c.decision(sufOff + 2, cbpC !== 0 ? 1 : 0)
+ if (cbpC !== 0) c.decision(sufOff + 2, cbpC === 2 ? 1 : 0)
+ c.decision(sufOff + 3, m >> 1)
+ c.decision(sufOff + 3, m & 1)
+ } else {
+ c.decision(6, cbpL !== 0 ? 1 : 0)
+ c.decision(7, cbpC !== 0 ? 1 : 0)
+ if (cbpC !== 0) c.decision(8, cbpC === 2 ? 1 : 0)
+ c.decision(9, m >> 1)
+ c.decision(10, m & 1)
+ }
+ } else {
+ c.decision(b0, 0)
+ if (this.params.transform8x8) {
+ const ta = l >= 0 && this.t8[l]! === 1 ? 1 : 0
+ const tb = tp >= 0 && this.t8[tp]! === 1 ? 1 : 0
+ c.decision(399 + ta + tb, t === MB_I8 ? 1 : 0)
+ }
+ if (t === MB_I4) {
+ for (let i = 0; i < 16; i++) {
+ const r = BLK_RASTER[i]!
+ this.cabacModeFlag(this.imode[mb * 16 + r]!, this.predMode4(mb, mbx, mby, r & 3, r >> 2))
+ }
+ } else {
+ for (let b8 = 0; b8 < 4; b8++) {
+ const bx = (b8 & 1) * 2
+ const by = (b8 >> 1) * 2
+ this.cabacModeFlag(this.imode[mb * 16 + by * 4 + bx]!, this.predMode4(mb, mbx, mby, bx, by))
+ }
+ }
+ }
+ const cm = this.cMode[mb]!
+ const ca = l >= 0 && this.isIntra(l) && this.cMode[l]! !== 0 ? 1 : 0
+ const cb = tp >= 0 && this.isIntra(tp) && this.cMode[tp]! !== 0 ? 1 : 0
+ c.decision(64 + ca + cb, cm > 0 ? 1 : 0)
+ if (cm > 0) {
+ c.decision(67, cm > 1 ? 1 : 0)
+ if (cm > 1) c.decision(67, cm > 2 ? 1 : 0)
+ }
+ }
+ if (t !== MB_I16) {
+ for (let b8 = 0; b8 < 4; b8++) {
+ let ca8 = 0
+ let cb8 = 0
+ if ((b8 & 1) === 1) {
+ ca8 = (cbpL >> (b8 - 1) & 1) === 0 ? 1 : 0
+ } else if (l >= 0) {
+ ca8 = ((this.cbp[l]! & 15) >> (b8 + 1) & 1) === 0 ? 1 : 0
+ }
+ if (b8 >= 2) {
+ cb8 = (cbpL >> (b8 - 2) & 1) === 0 ? 1 : 0
+ } else if (tp >= 0) {
+ cb8 = ((this.cbp[tp]! & 15) >> (b8 + 2) & 1) === 0 ? 1 : 0
+ }
+ c.decision(73 + ca8 + 2 * cb8, (cbpL >> b8) & 1)
+ }
+ const la = l >= 0 && (this.cbp[l]! >> 4) !== 0 ? 1 : 0
+ const lb = tp >= 0 && (this.cbp[tp]! >> 4) !== 0 ? 1 : 0
+ c.decision(77 + la + 2 * lb, cbpC !== 0 ? 1 : 0)
+ if (cbpC !== 0) {
+ const ma = l >= 0 && (this.cbp[l]! >> 4) === 2 ? 1 : 0
+ const mb2 = tp >= 0 && (this.cbp[tp]! >> 4) === 2 ? 1 : 0
+ c.decision(81 + ma + 2 * mb2, cbpC === 2 ? 1 : 0)
+ }
+ if (!intra && cbpL !== 0 && this.params.transform8x8) {
+ const ta = l >= 0 && this.t8[l]! === 1 ? 1 : 0
+ const tb = tp >= 0 && this.t8[tp]! === 1 ? 1 : 0
+ c.decision(399 + ta + tb, this.t8[mb]!)
+ }
+ }
+ if (t === MB_I16 || cbp !== 0) {
+ const d = this.qpDelta[mb]!
+ const k = d > 0 ? 2 * d - 1 : -2 * d
+ c.decision(60 + (this.lastDeltaNz ? 1 : 0), k > 0 ? 1 : 0)
+ for (let i = 1; i <= k; i++) c.decision(i === 1 ? 62 : 63, i < k ? 1 : 0)
+ this.lastDeltaNz = d !== 0
+ } else {
+ this.lastDeltaNz = false
+ }
+ if (t === MB_I16) {
+ const dcCoded = (this.dcCbf[mb]! & 1) !== 0
+ c.cbf(CAT_LUMA_DC, this.cbfDc(mb, mbx, mby, 0, true), dcCoded)
+ if (dcCoded) c.residual(CAT_LUMA_DC, this.coef, DC_OFF, 16)
+ if (cbpL !== 0) {
+ for (let i = 0; i < 16; i++) {
+ const r = BLK_RASTER[i]!
+ const coded = this.nnz[mb * 24 + r]! > 0
+ c.cbf(CAT_LUMA_AC, this.cbfLuma4(mb, mbx, mby, r, true), coded)
+ if (coded) c.residual(CAT_LUMA_AC, this.coef, r * 16, 15)
+ }
+ }
+ } else {
+ for (let b8 = 0; b8 < 4; b8++) {
+ if (((cbpL >> b8) & 1) === 0) continue
+ if (this.t8[mb]! === 1) {
+ c.residual(CAT_LUMA_8x8, this.coef, b8 * 64, 64)
+ continue
+ }
+ for (let s = 0; s < 4; s++) {
+ const r = BLK_RASTER[b8 * 4 + s]!
+ const coded = this.nnz[mb * 24 + r]! > 0
+ c.cbf(CAT_LUMA_4x4, this.cbfLuma4(mb, mbx, mby, r, intra), coded)
+ if (coded) c.residual(CAT_LUMA_4x4, this.coef, r * 16, 16)
+ }
+ }
+ }
+ if (cbpC !== 0) {
+ for (let pl = 0; pl < 2; pl++) {
+ const coded = ((this.dcCbf[mb]! >> (pl + 1)) & 1) !== 0
+ c.cbf(CAT_CHROMA_DC, this.cbfDc(mb, mbx, mby, pl + 1, intra), coded)
+ if (coded) c.residual(CAT_CHROMA_DC, this.coef, CHROMA_DC_OFF + pl * 4, 4)
+ }
+ }
+ if (cbpC === 2) {
+ for (let pl = 0; pl < 2; pl++) {
+ for (let b = 0; b < 4; b++) {
+ const coded = this.nnz[mb * 24 + 16 + pl * 4 + b]! > 0
+ c.cbf(CAT_CHROMA_AC, this.cbfChroma4(mb, mbx, mby, pl, b, intra), coded)
+ if (coded) c.residual(CAT_CHROMA_AC, this.coef, CHROMA_AC_OFF + (pl * 4 + b) * 16, 15)
+ }
+ }
+ }
+ }
+
+ cabacModeFlag(mode: int, pred: int) {
+ const c = this.cabac
+ if (mode === pred) {
+ c.decision(68, 1)
+ } else {
+ c.decision(68, 0)
+ const rem = mode < pred ? mode : mode - 1
+ c.decision(69, rem & 1)
+ c.decision(69, (rem >> 1) & 1)
+ c.decision(69, (rem >> 2) & 1)
+ }
+ }
+
+ writeModeFlag(mode: int, pred: int) {
+ if (mode === pred) {
+ this.bw.putBit(1)
+ } else {
+ this.bw.putBit(0)
+ this.bw.putBits(mode < pred ? mode : mode - 1, 3)
+ }
+ }
+
+ codedBlocks(mb: int): int {
+ if (this.t8[mb]! === 1) return CBP_BLOCKS[this.cbp[mb]! & 15]!
+ return i8x16.load(this.nnz, mb * 24).gt(i8x16.splat(0)).mask()
+ }
+
+ motionBs(mbP: int, mbQ: int): int {
+ if (this.sliceType === SLICE_B) return this.edgeBsB(mbP, mbQ)
+ if (this.refs[this.refIdx[mbP]!]! !== this.refs[this.refIdx[mbQ]!]!) return 1
+ if (iabs(this.mvx[mbP]! - this.mvx[mbQ]!) >= 4) return 1
+ if (iabs(this.mvy[mbP]! - this.mvy[mbQ]!) >= 4) return 1
+ return 0
+ }
+
+ dirty(mb: int): bool {
+ return this.changed[mb]! !== 0 || this.refresh[mb]! !== 0
+ }
+
+ dbNeed(mbx: int, mby: int, full: bool): bool {
+ if (full) return true
+ const mb = mby * this.mbw + mbx
+ return this.dirty(mb) || (mbx > 0 && this.dirty(mb - 1)) || (mby > 0 && this.dirty(mb - this.mbw))
+ }
+
+ finalizeRow(mby: int, full: bool, ver: int) {
+ const mbw = this.mbw
+ const below = mby + 1 < this.mbh
+ for (let mbx = 0; mbx < mbw; mbx++) {
+ const hit = this.dbNeed(mbx, mby, full) || (mbx + 1 < mbw && this.dbNeed(mbx + 1, mby, full)) ||
+ (below && this.dbNeed(mbx, mby + 1, full))
+ if (!hit) continue
+ this.cur.ver[mby * mbw + mbx] = ver
+ this.padMb(mbx, mby)
+ }
+ }
+
+ deblockFrame(full: bool) {
+ for (let mby = 0; mby < this.mbh; mby++) {
+ if (this.deblock) {
+ for (let mbx = 0; mbx < this.mbw; mbx++) {
+ if (this.dbNeed(mbx, mby, full)) this.deblockMb(mbx, mby)
+ }
+ }
+ if (mby > 0) this.finalizeRow(mby - 1, full, this.counter)
+ }
+ this.finalizeRow(this.mbh - 1, full, this.counter)
+ }
+
+ deblockMb(mbx: int, mby: int) {
+ const mb = mby * this.mbw + mbx
+ const t8 = this.t8[mb]! === 1
+ const qpQ = this.qpY[mb]!
+ if (this.isIntra(mb)) {
+ for (let dir = 0; dir < 2; dir++) {
+ for (let e = 0; e < 4; e++) {
+ if (e === 0 && (dir === 0 ? mbx === 0 : mby === 0)) continue
+ if (t8 && (e & 1) === 1) continue
+ const qpP = e === 0 ? this.qpY[dir === 0 ? mb - 1 : mb - this.mbw]! : qpQ
+ const qpc = (int(CHROMA_QP[qpP]!) + int(CHROMA_QP[qpQ]!) + 1) >> 1
+ this.filterEdge(mbx, mby, dir, e, 0, e === 0 ? 4 : 3, (qpP + qpQ + 1) >> 1, qpc)
+ }
+ }
+ return
+ }
+ const codedQ = this.codedBlocks(mb)
+ for (let dir = 0; dir < 2; dir++) {
+ const sideQ = dir === 0 ? transposeBlocks(codedQ) : codedQ
+ for (let e = 0; e < 4; e++) {
+ if (e === 0 && (dir === 0 ? mbx === 0 : mby === 0)) continue
+ if (t8 && (e & 1) === 1) continue
+ const mbP = e === 0 ? (dir === 0 ? mb - 1 : mb - this.mbw) : mb
+ const qpP = this.qpY[mbP]!
+ const ia = (qpP + qpQ + 1) >> 1
+ const qpc = (int(CHROMA_QP[qpP]!) + int(CHROMA_QP[qpQ]!) + 1) >> 1
+ if (e === 0 && this.isIntra(mbP)) {
+ this.filterEdge(mbx, mby, dir, e, 0, 4, ia, qpc)
+ continue
+ }
+ let coded = (sideQ >> (4 * e)) & 15
+ let motion = 0
+ if (e === 0) {
+ const codedP = this.codedBlocks(mbP)
+ coded |= ((dir === 0 ? transposeBlocks(codedP) : codedP) >> 12) & 15
+ motion = this.motionBs(mbP, mb)
+ } else {
+ coded |= (sideQ >> (4 * e - 4)) & 15
+ }
+ if (coded === 15) {
+ this.filterEdge(mbx, mby, dir, e, 0, 2, ia, qpc)
+ } else if (coded !== 0 || motion !== 0) {
+ this.filterEdge(mbx, mby, dir, e, coded, motion, ia, qpc)
+ }
+ }
+ }
+ }
+
+ filterEdge(mbx: int, mby: int, dir: int, e: int, coded: int, bs: int, ia: int, qpc: int) {
+ const o = dir === 0 ? this.ry(mbx * 16 + e * 4, mby * 16) : this.ry(mbx * 16, mby * 16 + e * 4)
+ const across = dir === 0 ? 1 : this.ys
+ const along = dir === 0 ? this.ys : 1
+ if (coded === 0) {
+ filterLuma16(this.cur.y, o, across, along, bs, ia, ia)
+ } else {
+ filterLumaSegments(this.cur.y, o, across, along, coded, bs, ia, ia)
+ }
+ if ((e & 1) !== 0) return
+ const oc = dir === 0 ? this.rc(mbx * 8 + e * 2, mby * 8) : this.rc(mbx * 8, mby * 8 + e * 2)
+ const acrossC = dir === 0 ? 1 : this.cs
+ const alongC = dir === 0 ? this.cs : 1
+ if (coded === 0) {
+ filterChromaUV(this.cur.u, this.cur.v, oc, acrossC, alongC, bs, qpc, qpc)
+ } else {
+ filterChromaSegments(this.cur.u, this.cur.v, oc, acrossC, alongC, coded, bs, qpc, qpc)
+ }
+ }
+
+ reconFrame(): Uint8Array {
+ return this.reconOf(this.refs[0]!)
+ }
+
+ reconOf(f: RefFrame): Uint8Array {
+ const cwOut = this.w >> 1
+ const out = new Uint8Array(this.w * this.h + 2 * cwOut * (this.h >> 1))
+ let k = 0
+ for (let y = 0; y < this.h; y++) {
+ out.set(f.y.subarray(this.ry(0, y), this.ry(0, y) + this.w), k)
+ k += this.w
+ }
+ for (let pl = 0; pl < 2; pl++) {
+ const src = pl === 0 ? f.u : f.v
+ for (let y = 0; y < this.h >> 1; y++) {
+ out.set(src.subarray(this.rc(0, y), this.rc(0, y) + cwOut), k)
+ k += cwOut
+ }
+ }
+ return out
+ }
+}
+
+function testFrame(w: int, h: int, shift: int): Uint8Array {
+ const f = new Uint8Array(w * h + (w * h >> 1))
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) f[y * w + x] = ((x + shift) * 37 + y * 11 + ((x + shift) >> 2) * y) & 255
+ }
+ for (let i = w * h; i < f.length; i++) f[i] = 128 + (i & 7)
+ return f
+}
+
+function adaptiveRun(adapt: bool): string {
+ const enc = new Encoder({
+ width: 64, height: 64, fpsNum: 30, fpsDen: 1, qp: 26, keyint: 100, profile: 100, preset: "medium", cabac: true,
+ refs: 1, rcMode: RC_CQP, crf: 26.0, bitrate: 0, maxrate: 0, bufsize: 0, ipOffset: 3, weightedPred: false, worker: false,
+ })
+ enc.bAdapt = adapt
+ enc.wantRecon = true
+ enc.configureB(2)
+ let recon = 0
+ for (let i = 0; i < 12; i++) {
+ const moving = i >= 4 && i <= 8
+ const side = new SideInfo()
+ if (moving) side.dirty = [0, 0, 64, 64]
+ enc.submit(testFrame(64, 64, i < 4 ? 3 : i > 8 ? 8 : i), 0, side)
+ recon += enc.takeRecon().length
+ }
+ enc.flush()
+ recon += enc.takeRecon().length
+ let types = ""
+ let coded = 0
+ for (const f of enc.frames) {
+ types += f.type
+ if (f.bytes > 0) coded++
+ }
+ return `${types} ${coded} ${recon}`
+}
+
+function idleRefineRun(rcMode: int, bitrate: int): string {
+ const enc = new Encoder({
+ width: 64, height: 64, fpsNum: 30, fpsDen: 1, qp: 26, keyint: 1000, profile: 100, preset: "live", cabac: true,
+ refs: 1, rcMode, crf: 26.0, bitrate, maxrate: (bitrate * 3) >> 1, bufsize: 0, ipOffset: 3, weightedPred: false,
+ worker: false,
+ })
+ for (let i = 0; i < 48; i++) {
+ const side = new SideInfo()
+ if (i < 8) side.dirty = [0, 0, 64, 64]
+ enc.encodeFrame(testFrame(64, 64, i < 8 ? i : 7), 0, side)
+ }
+ let s = ""
+ for (const f of enc.frames) s += f.bytes === 0 ? "D" : f.type === "I" || f.changedMbs > 0 ? f.type : `R${f.qp}`
+ return s
+}
+
+test("bitrate mode re-codes macroblocks left at a high qp once the screen has idled and the budget allows it", () => {
+ expect(idleRefineRun(RC_VBR, 60)).toBe("IPPPPPPPR14DDDDDDDDDDDDDDR8DDDDDDDDDDDDDDDDDDDDDDDD")
+ expect(idleRefineRun(RC_CQP, 0)).toBe("IPPPPPPPR26DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD")
+})
+
+test("adaptive B-frames drop or P-code static frames and use B-frames only while the frame moves", () => {
+ expect(adaptiveRun(true)).toBe("IDDDPPBBPPDD 7 7")
+ expect(adaptiveRun(false)).toBe("IPBBPBBPBBPB 12 12")
+})
+
+test("with B-frames every anchor takes the lookahead map of its own display index", () => {
+ const enc = new Encoder({
+ width: 64, height: 64, fpsNum: 30, fpsDen: 1, qp: 26, keyint: 100, profile: 100, preset: "medium", cabac: true,
+ refs: 1, rcMode: RC_CQP, crf: 26.0, bitrate: 0, maxrate: 0, bufsize: 0, ipOffset: 3, weightedPred: false, worker: false,
+ })
+ enc.aqStrength = 0
+ enc.lifetimeAq = false
+ enc.refreshDelta = 0
+ enc.configureB(2)
+ const lives = [60, 20, 1, 1, 4, 30, 1, 1]
+ let seen: string[] = []
+ for (let i = 0; i < lives.length; i++) {
+ const life = new Int32Array(16)
+ life.fill(lives[i]! * LIFE_ONE)
+ enc.setLookahead(life)
+ const moving = i > 0 && i < 6
+ const side = new SideInfo()
+ if (moving) side.dirty = [0, 0, 64, 64]
+ enc.submit(testFrame(64, 64, moving ? i : i === 0 ? 0 : 5), 0, side)
+ seen.push(`${enc.lastAnchorIndex}:${enc.mbQp[0]! - enc.anchorQp}`)
+ }
+ expect(seen.join(" ")).toBe("0:-3 1:0 1:0 1:0 4:4 4:4 5:-1 5:-1")
+})
+
+function driftFrames(w: int, h: int, n: int): Uint8Array {
+ const fb = w * h + ((w * h) >> 1)
+ const all = new Uint8Array(fb * n)
+ all.set(testFrame(w, h, 0), 0)
+ let s = 4242
+ for (let i = 1; i < n; i++) {
+ const o = i * fb
+ all.copyWithin(o, i % 6 === 0 ? 0 : o - fb, i % 6 === 0 ? fb : o)
+ for (let k = 0; k < 12; k++) {
+ s = (s * 1103515245 + 12345) & 0x7fffffff
+ const x = (s >> 4) % w
+ const y = (s >> 12) % h
+ const kind = (s >> 20) & 3
+ const p = kind === 3 ? o + w * h + (y >> 1) * (w >> 1) + (x >> 1) : o + y * w + x
+ const v = int(all[p]!) + (kind === 0 ? 40 : kind === 1 ? 1 : kind === 2 ? -1 : 2)
+ all[p] = v < 0 ? 0 : v > 255 ? 255 : v
+ }
+ }
+ return all
+}
+
+test("macroblock changes taken from the lookahead's map are the ones the encoder finds itself", () => {
+ const w = 80
+ const h = 40
+ const n = 18
+ const fb = w * h + ((w * h) >> 1)
+ const all = driftFrames(w, h, n)
+ const runs: string[] = []
+ for (let v = 0; v < 3; v++) {
+ const enc = new Encoder({
+ width: w, height: h, fpsNum: 30, fpsDen: 1, qp: 26, keyint: 100, profile: 100, preset: "medium", cabac: true,
+ refs: 1, rcMode: RC_CQP, crf: 26.0, bitrate: 0, maxrate: 0, bufsize: 0, ipOffset: 3, weightedPred: false, worker: false,
+ })
+ enc.noise = 2
+ const la = new Lookahead(w, h, 2, false)
+ la.noise = 2
+ let s = ""
+ for (let i = 0; i < n; i++) {
+ la.push(all, i * fb, i > 0 ? (i - 1) * fb : 0, undefined)
+ const map = la.changesOf(i)
+ if (v === 1) enc.useChanges(map, i, 2)
+ if (v === 2) {
+ const wrong = new Uint8Array(map.length)
+ wrong.fill(1)
+ enc.useChanges(wrong, i, 2)
+ }
+ const bits = enc.encodeFrame(all, i * fb, undefined)
+ s += `${bits.length}:${enc.frames[enc.frames.length - 1]!.changedMbs} `
+ }
+ runs.push(s)
+ }
+ expect(`${runs[0]! === runs[1]!} ${runs[0]! !== runs[2]!}`).toBe("true true")
+})
+
+test("the lookahead horizon of a frame is known before the frames ahead of it are coded", () => {
+ let seen = ""
+ for (const b of [0, 2]) {
+ const enc = new Encoder({
+ width: 64, height: 64, fpsNum: 30, fpsDen: 1, qp: 26, keyint: 5, profile: 100, preset: "medium", cabac: true,
+ refs: 1, rcMode: RC_CQP, crf: 26.0, bitrate: 0, maxrate: 0, bufsize: 0, ipOffset: 3, weightedPred: false, worker: false,
+ })
+ if (b > 0) enc.configureB(b)
+ for (let i = 0; i < 13; i++) {
+ seen += enc.laHorizonAt(i) === enc.laHorizon() ? `${enc.laHorizon()}` : "x"
+ const moving = i % 4 !== 3
+ const side = new SideInfo()
+ if (moving) side.dirty = [0, 0, 64, 64]
+ const frame = testFrame(64, 64, moving ? i : i - 1)
+ if (b > 0) {
+ enc.submit(frame, 0, side)
+ } else {
+ enc.encodeFrame(frame, 0, side)
+ }
+ }
+ seen += " "
+ }
+ expect(seen).toBe("5432154321543 5432154321543 ")
+})
+
+test("an anchor gains lifetime from the B-frames that predict from it through list 1", () => {
+ const enc = new Encoder({
+ width: 64, height: 64, fpsNum: 30, fpsDen: 1, qp: 26, keyint: 100, profile: 100, preset: "medium", cabac: true,
+ refs: 1, rcMode: RC_CQP, crf: 26.0, bitrate: 0, maxrate: 0, bufsize: 0, ipOffset: 3, weightedPred: false, worker: false,
+ })
+ enc.configureB(2)
+ enc.lastAnchorIndex = 4
+ const b5 = new Pending(new Uint8Array(0), 5)
+ b5.keep = new Uint8Array(16)
+ b5.keep.fill(KEEP_ONE)
+ const b6 = new Pending(new Uint8Array(0), 6)
+ b6.keep = new Uint8Array(16)
+ b6.keep.fill(KEEP_ONE)
+ b6.keep[0] = KEEP_ONE >> 1
+ enc.pending = [b5, b6]
+ const keep = new Uint8Array(16)
+ keep.fill(KEEP_ONE)
+ keep[1] = 0
+ const life = new Int32Array(16)
+ life.fill(10 * LIFE_ONE)
+ enc.anchorLookahead(life, keep, 7)
+ const whole = Math.trunc(enc.laL1 * f64(LIFE_ONE) + 0.5)
+ const partial = Math.trunc(enc.laL1 * f64(LIFE_ONE) * (2.0 / 3.0 + 0.5 / 3.0) + 0.5)
+ expect(`${life[0]! - 10 * LIFE_ONE} ${life[1]! - 10 * LIFE_ONE} ${life[2]! - 10 * LIFE_ONE}`).toBe(`${partial} 0 ${whole}`)
+})
+
+test("GOPs too short for a B run declare no B-frames", () => {
+ let seen = ""
+ for (const k of [1, 2, 3]) {
+ const enc = new Encoder({
+ width: 64, height: 64, fpsNum: 30, fpsDen: 1, qp: 26, keyint: k, profile: 100, preset: "medium", cabac: true,
+ refs: 1, rcMode: RC_CQP, crf: 26.0, bitrate: 0, maxrate: 0, bufsize: 0, ipOffset: 3, weightedPred: false, worker: false,
+ })
+ enc.pyramid = true
+ enc.configureB(3)
+ seen += `${enc.bframes}/${enc.params.bframes}/${enc.params.dpbRefs}/${enc.pyramid} `
+ }
+ expect(seen).toBe("0/0/1/false 0/0/1/false 3/3/3/true ")
+})
+
+test("transposeBlocks swaps the row and column of every 4x4 block bit", () => {
+ let bad = 0
+ for (let m = 0; m < 65536; m++) {
+ let want = 0
+ for (let r = 0; r < 16; r++) {
+ if (((m >> r) & 1) !== 0) want |= 1 << ((r & 3) * 4 + (r >> 2))
+ }
+ if (transposeBlocks(m) !== want) bad++
+ }
+ expect(bad).toBe(0)
+})
diff --git a/capcodec/src/headers.tov b/capcodec/src/headers.tov
new file mode 100644
index 000000000..847c3dcd1
--- /dev/null
+++ b/capcodec/src/headers.tov
@@ -0,0 +1,262 @@
+import { BitWriter } from "./bitwriter"
+
+export type StreamParams = {
+ width: int,
+ height: int,
+ mbw: int,
+ mbh: int,
+ profile: int,
+ level: int,
+ refs: int,
+ fpsNum: int,
+ fpsDen: int,
+ log2MaxFrameNum: int,
+ cabac: bool,
+ transform8x8: bool,
+ weightedPred: bool,
+ dpbRefs: int,
+ bframes: int,
+ pyramid: bool,
+}
+
+export type SliceParams = {
+ idr: bool,
+ sliceType: int,
+ frameNum: int,
+ idrPicId: int,
+ qpDelta: int,
+ refsActive: int,
+ deblock: int,
+ alphaOffset: int,
+ betaOffset: int,
+ cabacInitIdc: int,
+ firstMb: int,
+ wpLuma: bool,
+ wpChroma: bool,
+ wp: int[],
+ poc: int,
+ nalRef: bool,
+ reorder: int[],
+ mmco: int[],
+}
+
+export const SLICE_P = 0
+export const SLICE_B = 1
+export const SLICE_I = 2
+export const LOG2_MAX_POC_LSB = 16
+
+const LEVELS: int[] = [
+ 30, 40500, 1620, 8100, 10000,
+ 31, 108000, 3600, 18000, 14000,
+ 32, 216000, 5120, 20480, 20000,
+ 40, 245760, 8192, 32768, 20000,
+ 41, 245760, 8192, 32768, 50000,
+ 42, 522240, 8704, 34816, 50000,
+ 50, 589824, 22080, 110400, 135000,
+ 51, 983040, 36864, 184320, 240000,
+ 52, 2073600, 36864, 184320, 240000,
+]
+
+export function chooseLevel(mbw: int, mbh: int, fps: f64, refs: int, kbps: int): int {
+ const fs = mbw * mbh
+ const mbps = f64(fs) * fps
+ for (let i = 0; i < LEVELS.length; i += 5) {
+ const maxFs = LEVELS[i + 2]!
+ const side = Math.trunc(Math.sqrt(f64(maxFs * 8)))
+ if (fs > maxFs || mbw > side || mbh > side) continue
+ if (mbps > f64(LEVELS[i + 1]!)) continue
+ if (refs * fs > LEVELS[i + 3]!) continue
+ if (kbps > LEVELS[i + 4]!) continue
+ return LEVELS[i]!
+ }
+ return 52
+}
+
+export function maxDpbFrames(level: int, mbw: int, mbh: int): int {
+ for (let i = 0; i < LEVELS.length; i += 5) {
+ if (LEVELS[i]! === level) return Math.min(16, Math.trunc(LEVELS[i + 3]! / (mbw * mbh)))
+ }
+ return 1
+}
+
+export function writeSps(p: StreamParams): u8[] {
+ const bw = new BitWriter()
+ bw.putBits(p.profile, 8)
+ bw.putBits(p.profile === 77 ? 0x40 : 0, 8)
+ bw.putBits(p.level, 8)
+ bw.ue(0)
+ if (p.profile === 100) {
+ bw.ue(1)
+ bw.ue(0)
+ bw.ue(0)
+ bw.putBit(0)
+ bw.putBit(0)
+ }
+ bw.ue(p.log2MaxFrameNum - 4)
+ if (p.bframes > 0) {
+ bw.ue(0)
+ bw.ue(LOG2_MAX_POC_LSB - 4)
+ } else {
+ bw.ue(2)
+ }
+ bw.ue(p.dpbRefs)
+ bw.putBit(0)
+ bw.ue(p.mbw - 1)
+ bw.ue(p.mbh - 1)
+ bw.putBit(1)
+ bw.putBit(1)
+ const cropRight = (p.mbw * 16 - p.width) >> 1
+ const cropBottom = (p.mbh * 16 - p.height) >> 1
+ if (cropRight > 0 || cropBottom > 0) {
+ bw.putBit(1)
+ bw.ue(0)
+ bw.ue(cropRight)
+ bw.ue(0)
+ bw.ue(cropBottom)
+ } else {
+ bw.putBit(0)
+ }
+ bw.putBit(1)
+ bw.putBit(0)
+ bw.putBit(0)
+ bw.putBit(1)
+ bw.putBits(5, 3)
+ bw.putBit(0)
+ bw.putBit(1)
+ bw.putBits(1, 8)
+ bw.putBits(1, 8)
+ bw.putBits(1, 8)
+ bw.putBit(0)
+ bw.putBit(1)
+ bw.putBits(p.fpsDen, 32)
+ bw.putBits(2 * p.fpsNum, 32)
+ bw.putBit(0)
+ bw.putBit(0)
+ bw.putBit(0)
+ bw.putBit(0)
+ bw.putBit(1)
+ bw.putBit(1)
+ bw.ue(0)
+ bw.ue(0)
+ bw.ue(15)
+ bw.ue(15)
+ bw.ue(p.pyramid ? 2 : p.bframes > 0 ? 1 : 0)
+ bw.ue(p.dpbRefs)
+ bw.trailing()
+ return bw.buf
+}
+
+export function writePps(p: StreamParams): u8[] {
+ const bw = new BitWriter()
+ bw.ue(0)
+ bw.ue(0)
+ bw.putBit(p.cabac ? 1 : 0)
+ bw.putBit(0)
+ bw.ue(0)
+ bw.ue(p.refs - 1)
+ bw.ue(0)
+ bw.putBit(p.weightedPred ? 1 : 0)
+ bw.putBits(p.bframes > 0 && p.weightedPred ? 2 : 0, 2)
+ bw.se(0)
+ bw.se(0)
+ bw.se(0)
+ bw.putBit(1)
+ bw.putBit(0)
+ bw.putBit(0)
+ if (p.profile === 100) {
+ bw.putBit(p.transform8x8 ? 1 : 0)
+ bw.putBit(0)
+ bw.se(0)
+ }
+ bw.trailing()
+ return bw.buf
+}
+
+export function writeSliceHeader(bw: BitWriter, p: StreamParams, s: SliceParams) {
+ bw.ue(s.firstMb)
+ bw.ue(s.sliceType + 5)
+ bw.ue(0)
+ bw.putBits(s.frameNum, p.log2MaxFrameNum)
+ if (s.idr) bw.ue(s.idrPicId)
+ if (p.bframes > 0) bw.putBits(s.poc & ((1 << LOG2_MAX_POC_LSB) - 1), LOG2_MAX_POC_LSB)
+ if (s.sliceType === SLICE_B) {
+ bw.putBit(1)
+ if (p.refs !== 1) {
+ bw.putBit(1)
+ bw.ue(0)
+ bw.ue(0)
+ } else {
+ bw.putBit(0)
+ }
+ bw.putBit(0)
+ bw.putBit(0)
+ }
+ if (s.sliceType === SLICE_P) {
+ if (s.refsActive !== p.refs) {
+ bw.putBit(1)
+ bw.ue(s.refsActive - 1)
+ } else {
+ bw.putBit(0)
+ }
+ if (s.reorder.length > 0) {
+ bw.putBit(1)
+ for (let i = 0; i < s.reorder.length; i += 2) {
+ bw.ue(s.reorder[i]!)
+ bw.ue(s.reorder[i + 1]!)
+ }
+ bw.ue(3)
+ } else {
+ bw.putBit(0)
+ }
+ if (p.weightedPred) {
+ bw.ue(6)
+ bw.ue(6)
+ for (let i = 0; i < s.refsActive; i++) {
+ const lw = i === 0 && s.wpLuma
+ bw.putBit(lw ? 1 : 0)
+ if (lw) {
+ bw.se(s.wp[0]!)
+ bw.se(s.wp[1]!)
+ }
+ const cw = i === 0 && s.wpChroma
+ bw.putBit(cw ? 1 : 0)
+ if (cw) {
+ bw.se(s.wp[2]!)
+ bw.se(s.wp[3]!)
+ bw.se(s.wp[4]!)
+ bw.se(s.wp[5]!)
+ }
+ }
+ }
+ }
+ if (s.idr) {
+ bw.putBit(0)
+ bw.putBit(0)
+ } else if (s.sliceType !== SLICE_B || s.nalRef) {
+ if (s.mmco.length > 0) {
+ bw.putBit(1)
+ for (const d of s.mmco) {
+ bw.ue(1)
+ bw.ue(d)
+ }
+ bw.ue(0)
+ } else {
+ bw.putBit(0)
+ }
+ }
+ if (p.cabac && s.sliceType !== SLICE_I) bw.ue(s.cabacInitIdc)
+ bw.se(s.qpDelta)
+ bw.ue(s.deblock)
+ if (s.deblock !== 1) {
+ bw.se(s.alphaOffset >> 1)
+ bw.se(s.betaOffset >> 1)
+ }
+}
+
+test("level selection follows the brief", () => {
+ expect(chooseLevel(120, 68, 60.0, 1, 0)).toBe(42)
+ expect(chooseLevel(240, 135, 30.0, 1, 0)).toBe(51)
+ expect(chooseLevel(120, 68, 30.0, 4, 0)).toBe(40)
+ expect(chooseLevel(80, 45, 30.0, 1, 0)).toBe(31)
+ expect(maxDpbFrames(40, 120, 68)).toBe(4)
+})
diff --git a/capcodec/src/inter.tov b/capcodec/src/inter.tov
new file mode 100644
index 000000000..a97e4ab2d
--- /dev/null
+++ b/capcodec/src/inter.tov
@@ -0,0 +1,322 @@
+function clip(v: int): int {
+ return v < 0 ? 0 : v > 255 ? 255 : v
+}
+
+function tap6(a: int, b: int, c: int, d: int, e: int, f: int): int {
+ return a - 5 * b + 20 * c + 20 * d - 5 * e + f
+}
+
+const PEL_PAIRS = [0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8]
+const INTERLEAVE_LO = [0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23]
+const INTERLEAVE_HI = [8, 24, 9, 25, 10, 26, 11, 27, 12, 28, 13, 29, 14, 30, 15, 31]
+
+export function predictChroma(dst: Uint8Array, dO: int, ds: int, ref: Uint8Array, stride: int, base: int, mvx: int, mvy: int, w: int, h: int) {
+ const fx = mvx & 7
+ const fy = mvy & 7
+ const p0 = base + (mvy >> 3) * stride + (mvx >> 3)
+ if (w === 8 && ds === 8 && (h & 3) === 0) {
+ const wab = i8x32.bitcast(i16x16.splat((fx * (8 - fy)) * 256 + (8 - fx) * (8 - fy)))
+ const wcd = i8x32.bitcast(i16x16.splat((fx * fy) * 256 + (8 - fx) * fy))
+ const r32 = i16x16.splat(32)
+ let top = u8x16.load(ref, p0).swizzle(PEL_PAIRS)
+ for (let y = 0; y < h; y += 4) {
+ const r1 = p0 + (y + 1) * stride
+ const s1 = u8x16.load(ref, r1).swizzle(PEL_PAIRS)
+ const s2 = u8x16.load(ref, r1 + stride).swizzle(PEL_PAIRS)
+ const s3 = u8x16.load(ref, r1 + 2 * stride).swizzle(PEL_PAIRS)
+ const s4 = u8x16.load(ref, r1 + 3 * stride).swizzle(PEL_PAIRS)
+ const v01 = (u8x32.madd(u8x32.concat(top, s1), wab) + u8x32.madd(u8x32.concat(s1, s2), wcd) + r32) >> 6
+ const v23 = (u8x32.madd(u8x32.concat(s2, s3), wab) + u8x32.madd(u8x32.concat(s3, s4), wcd) + r32) >> 6
+ u8x32.packSat(v01, v23).store(dst, dO + y * 8)
+ top = s4
+ }
+ return
+ }
+ if (fx === 0 && fy === 0) {
+ for (let y = 0; y < h; y++) {
+ const r = p0 + y * stride
+ for (let x = 0; x < w; x++) dst[dO + y * ds + x] = ref[r + x]!
+ }
+ return
+ }
+ const wa = (8 - fx) * (8 - fy)
+ const wb = fx * (8 - fy)
+ const wc = (8 - fx) * fy
+ const wd = fx * fy
+ for (let y = 0; y < h; y++) {
+ const r = p0 + y * stride
+ for (let x = 0; x < w; x++) {
+ const p = r + x
+ const v = (wa * int(ref[p]!) + wb * int(ref[p + 1]!) + wc * int(ref[p + stride]!) + wd * int(ref[p + stride + 1]!) + 32) >> 6
+ dst[dO + y * ds + x] = v
+ }
+ }
+}
+
+export function median3(a: int, b: int, c: int): int {
+ if (a > b) {
+ if (b > c) return b
+ return a > c ? c : a
+ }
+ if (a > c) return a
+ return b > c ? c : b
+}
+
+function tap6v(a: i16x16, b: i16x16, c: i16x16, d: i16x16, e: i16x16, f: i16x16): i16x16 {
+ return a + f + (c + d) * i16x16.splat(20) - (b + e) * i16x16.splat(5)
+}
+
+function pixels(v: i16x16): u8x16 {
+ return u8x16.convert(v.max(i16x16.splat(0)).min(i16x16.splat(255)))
+}
+
+const ZIP_LO = [0, 16, 1, 17, 2, 18, 3, 19, 8, 24, 9, 25, 10, 26, 11, 27]
+const ZIP_HI = [4, 20, 5, 21, 6, 22, 7, 23, 12, 28, 13, 29, 14, 30, 15, 31]
+const QUARTERS = [0, 1, 2, 3, 8, 9, 10, 11, 4, 5, 6, 7, 12, 13, 14, 15]
+
+function hTap(y: Uint8Array, q: int): i16x16 {
+ return tap6v(i16x16.loadU8(y, q - 2), i16x16.loadU8(y, q - 1), i16x16.loadU8(y, q), i16x16.loadU8(y, q + 1),
+ i16x16.loadU8(y, q + 2), i16x16.loadU8(y, q + 3))
+}
+
+function tapJ(outerInner: i16x16, midMid: i16x16): i32x8 {
+ const ab = i16x16.madd(outerInner, i16x16(1, -5, 1, -5, 1, -5, 1, -5, 1, -5, 1, -5, 1, -5, 1, -5))
+ return (ab + i16x16.madd(midMid, i16x16.splat(10)) + i32x8.splat(512)) >> 10
+}
+
+export function computeHalfTile(hb: Uint8Array, hh: Uint8Array, hj: Uint8Array, y: Uint8Array, stride: int, base: int) {
+ const r16 = i16x16.splat(16)
+ let t0 = hTap(y, base - 2 * stride)
+ let t1 = hTap(y, base - stride)
+ let t2 = hTap(y, base)
+ let t3 = hTap(y, base + stride)
+ let t4 = hTap(y, base + 2 * stride)
+ for (let r = 0; r < 16; r++) {
+ const row = base + r * stride
+ const t5 = hTap(y, row + 3 * stride)
+ pixels((t2 + r16) >> 5).store(hb, row)
+ const v = tap6v(i16x16.loadU8(y, row - 2 * stride), i16x16.loadU8(y, row - stride), i16x16.loadU8(y, row),
+ i16x16.loadU8(y, row + stride), i16x16.loadU8(y, row + 2 * stride), i16x16.loadU8(y, row + 3 * stride))
+ pixels((v + r16) >> 5).store(hh, row)
+ const outer = t0 + t5
+ const inner = t1 + t4
+ const mid = t2 + t3
+ const lo = tapJ(i16x16.shuffle(outer, inner, ZIP_LO), i16x16.shuffle(mid, mid, ZIP_LO))
+ const hi = tapJ(i16x16.shuffle(outer, inner, ZIP_HI), i16x16.shuffle(mid, mid, ZIP_HI))
+ const j = i16x16.packSat(lo, hi)
+ pixels(j.swizzle(QUARTERS)).store(hj, row)
+ t0 = t1
+ t1 = t2
+ t2 = t3
+ t3 = t4
+ t4 = t5
+ }
+}
+
+function computeHalfTileRef(hb: Uint8Array, hh: Uint8Array, hj: Uint8Array, inout tmp: int[], y: Uint8Array, stride: int, base: int) {
+ for (let r = -2; r < 19; r++) {
+ const row = base + r * stride
+ const to = (r + 2) * 16
+ for (let i = 0; i < 16; i++) {
+ const q = row + i
+ tmp[to + i] = tap6(int(y[q - 2]!), int(y[q - 1]!), int(y[q]!), int(y[q + 1]!), int(y[q + 2]!), int(y[q + 3]!))
+ }
+ }
+ for (let r = 0; r < 16; r++) {
+ const row = base + r * stride
+ const to = (r + 2) * 16
+ for (let i = 0; i < 16; i++) {
+ const q = row + i
+ hb[q] = clip((tmp[to + i]! + 16) >> 5)
+ const v = tap6(int(y[q - 2 * stride]!), int(y[q - stride]!), int(y[q]!), int(y[q + stride]!),
+ int(y[q + 2 * stride]!), int(y[q + 3 * stride]!))
+ hh[q] = clip((v + 16) >> 5)
+ const k = to + i
+ const j1 = tap6(tmp[k - 32]!, tmp[k - 16]!, tmp[k]!, tmp[k + 16]!, tmp[k + 32]!, tmp[k + 48]!)
+ hj[q] = clip((j1 + 512) >> 10)
+ }
+ }
+}
+
+export function qpelPlanes(fx: int, fy: int): int {
+ let a = 0
+ let ao = 0
+ let b = 0
+ let bo = 0
+ if (fy === 0) {
+ if (fx === 1) {
+ b = 1
+ } else if (fx === 2) {
+ a = 1
+ b = 1
+ } else if (fx === 3) {
+ ao = 1
+ b = 1
+ }
+ } else if (fx === 0) {
+ if (fy === 1) {
+ b = 2
+ } else if (fy === 2) {
+ a = 2
+ b = 2
+ } else {
+ ao = 2
+ b = 2
+ }
+ } else if (fx === 2 && fy === 2) {
+ a = 3
+ b = 3
+ } else if (fx === 2) {
+ a = 3
+ b = 1
+ bo = fy === 1 ? 0 : 2
+ } else if (fy === 2) {
+ a = 3
+ b = 2
+ bo = fx === 1 ? 0 : 1
+ } else {
+ a = 1
+ ao = fy === 1 ? 0 : 2
+ b = 2
+ bo = fx === 1 ? 0 : 1
+ }
+ return a * 64 + ao * 16 + b * 4 + bo
+}
+
+export function avgPlanes(dst: Uint8Array, dO: int, ds: int, a: Uint8Array, ao: int, b: Uint8Array, bo: int, stride: int, w: int, h: int) {
+ if (w === 16) {
+ for (let y = 0; y < h; y++) u8x16.load(a, ao + y * stride).avg(u8x16.load(b, bo + y * stride)).store(dst, dO + y * ds)
+ return
+ }
+ for (let y = 0; y < h; y++) {
+ const pa = ao + y * stride
+ const pb = bo + y * stride
+ const d = dO + y * ds
+ for (let x = 0; x < w; x++) dst[d + x] = (int(a[pa + x]!) + int(b[pb + x]!) + 1) >> 1
+ }
+}
+
+export function weightedAvgPlanes(dst: Uint8Array, dO: int, ds: int, a: Uint8Array, ao: int, b: Uint8Array, bo: int, stride: int, w: int, h: int, w0: int, w1: int) {
+ if (w === 16 && w0 >= 0 && w1 >= 0 && w0 < 128 && w1 < 128 && w0 + w1 <= 128) {
+ const wv = i8x16.bitcast(i16x8.splat(w1 * 256 + w0))
+ const r = i16x8.splat(32)
+ for (let y = 0; y < h; y++) {
+ const va = u8x16.load(a, ao + y * stride)
+ const vb = u8x16.load(b, bo + y * stride)
+ const lo = (u8x16.madd(u8x16.shuffle(va, vb, INTERLEAVE_LO), wv) + r) >> 6
+ const hi = (u8x16.madd(u8x16.shuffle(va, vb, INTERLEAVE_HI), wv) + r) >> 6
+ u8x16.packSat(lo, hi).store(dst, dO + y * ds)
+ }
+ return
+ }
+ if (w === 16) {
+ const v0 = i16x8.splat(w0)
+ const v1 = i16x8.splat(w1)
+ const r = i16x8.splat(32)
+ for (let y = 0; y < h; y++) {
+ const va = u8x16.load(a, ao + y * stride)
+ const vb = u8x16.load(b, bo + y * stride)
+ const lo = (va.widenLow() * v0 + vb.widenLow() * v1 + r) >> 6
+ const hi = (va.widenHigh() * v0 + vb.widenHigh() * v1 + r) >> 6
+ u8x16.packSat(lo, hi).store(dst, dO + y * ds)
+ }
+ return
+ }
+ for (let y = 0; y < h; y++) {
+ const pa = ao + y * stride
+ const pb = bo + y * stride
+ const d = dO + y * ds
+ for (let x = 0; x < w; x++) dst[d + x] = (int(a[pa + x]!) * w0 + int(b[pb + x]!) * w1 + 32) >> 6
+ }
+}
+
+test("vector weighted bi-prediction average equals the scalar formula for every implicit weight", () => {
+ const a = new Uint8Array(16 * 4)
+ const b = new Uint8Array(16 * 4)
+ let x = 7
+ for (let i = 0; i < 64; i++) {
+ x = (x * 1103515245 + 12345) & 0x7fffffff
+ a[i] = i % 7 === 0 ? 255 : (x >> 9) & 255
+ b[i] = i % 5 === 0 ? 255 : (x >> 17) & 255
+ }
+ const v = new Uint8Array(64)
+ const s = new Uint8Array(64)
+ let bad = 0
+ for (let w1 = 0; w1 <= 64; w1++) {
+ weightedAvgPlanes(v, 0, 16, a, 0, b, 0, 16, 16, 4, 64 - w1, w1)
+ weightedAvgPlanes(s, 0, 8, a, 0, b, 0, 8, 8, 8, 64 - w1, w1)
+ for (let i = 0; i < 64; i++) {
+ if (v[i]! !== s[i]!) bad++
+ }
+ }
+ weightedAvgPlanes(v, 0, 16, a, 0, b, 0, 16, 16, 4, 32, 32)
+ avgPlanes(s, 0, 16, a, 0, b, 0, 16, 16, 4)
+ for (let i = 0; i < 64; i++) {
+ if (v[i]! !== s[i]!) bad++
+ }
+ expect(bad).toBe(0)
+})
+
+test("vector half-pel tiles equal the scalar 6-tap filter", () => {
+ const stride = 64
+ const y = new Uint8Array(stride * 64)
+ const hb = new Uint8Array(stride * 64)
+ const hh = new Uint8Array(stride * 64)
+ const hj = new Uint8Array(stride * 64)
+ const rb = new Uint8Array(stride * 64)
+ const rh = new Uint8Array(stride * 64)
+ const rj = new Uint8Array(stride * 64)
+ let t64: int[] = []
+ for (let i = 0; i < 21 * 16; i++) t64.push(0)
+ let bad = 0
+ for (let pat = 0; pat < 4; pat++) {
+ let x = 99 + pat
+ for (let i = 0; i < stride * 64; i++) {
+ x = (x * 1103515245 + 12345) & 0x7fffffff
+ const c = i % stride
+ const r = Math.trunc(i / stride)
+ const ext = pat === 1 ? (c + r) % 3 === 1 : pat === 2 ? c % 6 === 2 || c % 6 === 3 || r % 6 === 2 || r % 6 === 3 : false
+ const v = pat === 0 ? (i % 5 === 0 ? 255 : i % 11 === 0 ? 0 : (x >> 9) & 255) : pat === 3 ? ((x >> 9) & 1) * 255 : ext ? 255 : 0
+ y[i] = v
+ }
+ for (let ty = 1; ty < 3; ty++) {
+ for (let tx = 1; tx < 3; tx++) {
+ const base = ty * 16 * stride + tx * 16
+ computeHalfTile(hb, hh, hj, y, stride, base)
+ computeHalfTileRef(rb, rh, rj, &t64, y, stride, base)
+ }
+ }
+ for (let i = 0; i < stride * 64; i++) {
+ if (hb[i]! !== rb[i]! || hh[i]! !== rh[i]! || hj[i]! !== rj[i]!) bad++
+ }
+ }
+ expect(bad).toBe(0)
+})
+
+test("vector chroma interpolation equals the scalar bilinear filter", () => {
+ const ref = new Uint8Array(40 * 40)
+ let x = 5
+ for (let i = 0; i < 40 * 40; i++) {
+ x = (x * 1103515245 + 12345) & 0x7fffffff
+ ref[i] = (x >> 9) & 255
+ }
+ let bad = 0
+ for (let mv = 0; mv < 64; mv++) {
+ const mvx = (mv & 7) + 8 * (mv % 3) - 8
+ const mvy = (mv >> 3) + 8 * (mv % 2)
+ const a = new Uint8Array(64)
+ predictChroma(a, 0, 8, ref, 40, 10 * 40 + 10, mvx, mvy, 8, 8)
+ const fx = mvx & 7
+ const fy = mvy & 7
+ const p0 = 10 * 40 + 10 + (mvy >> 3) * 40 + (mvx >> 3)
+ for (let yy = 0; yy < 8; yy++) {
+ for (let xx = 0; xx < 8; xx++) {
+ const p = p0 + yy * 40 + xx
+ const v = ((8 - fx) * (8 - fy) * int(ref[p]!) + fx * (8 - fy) * int(ref[p + 1]!) + (8 - fx) * fy * int(ref[p + 40]!) +
+ fx * fy * int(ref[p + 41]!) + 32) >> 6
+ if (int(a[yy * 8 + xx]!) !== v) bad++
+ }
+ }
+ }
+ expect(bad).toBe(0)
+})
diff --git a/capcodec/src/intra.tov b/capcodec/src/intra.tov
new file mode 100644
index 000000000..75dc65cde
--- /dev/null
+++ b/capcodec/src/intra.tov
@@ -0,0 +1,408 @@
+export const AV_TOP = 1
+export const AV_LEFT = 2
+export const AV_TL = 4
+export const AV_TR = 8
+
+export const I4_V = 0
+export const I4_H = 1
+export const I4_DC = 2
+export const I4_DDL = 3
+export const I4_DDR = 4
+export const I4_VR = 5
+export const I4_HD = 6
+export const I4_VL = 7
+export const I4_HU = 8
+
+export const I16_V = 0
+export const I16_H = 1
+export const I16_DC = 2
+export const I16_PLANE = 3
+
+export const C_DC = 0
+export const C_H = 1
+export const C_V = 2
+export const C_PLANE = 3
+
+export function modeAvailable(mode: int, av: int): bool {
+ const top = (av & AV_TOP) !== 0
+ const left = (av & AV_LEFT) !== 0
+ const tl = (av & AV_TL) !== 0
+ if (mode === I4_V || mode === I4_DDL || mode === I4_VL) return top
+ if (mode === I4_H || mode === I4_HU) return left
+ if (mode === I4_DC) return true
+ return top && left && tl
+}
+
+export function modeMask(av: int): int {
+ const top = (av & AV_TOP) !== 0
+ const left = (av & AV_LEFT) !== 0
+ return 4 | (top ? 0x89 : 0) | (left ? 0x102 : 0) | (top && left && (av & AV_TL) !== 0 ? 0x70 : 0)
+}
+
+export function mode16Available(mode: int, av: int): bool {
+ const top = (av & AV_TOP) !== 0
+ const left = (av & AV_LEFT) !== 0
+ if (mode === I16_V) return top
+ if (mode === I16_H) return left
+ if (mode === I16_DC) return true
+ return top && left && (av & AV_TL) !== 0
+}
+
+export function chromaModeAvailable(mode: int, av: int): bool {
+ const top = (av & AV_TOP) !== 0
+ const left = (av & AV_LEFT) !== 0
+ if (mode === C_V) return top
+ if (mode === C_H) return left
+ if (mode === C_DC) return true
+ return top && left && (av & AV_TL) !== 0
+}
+
+export function gather4(e: Int32Array, p: Uint8Array, stride: int, x: int, y: int, av: int) {
+ if ((av & AV_TOP) !== 0) {
+ const o = (y - 1) * stride + x
+ for (let i = 0; i < 4; i++) e[5 + i] = int(p[o + i]!)
+ if ((av & AV_TR) !== 0) {
+ for (let i = 4; i < 8; i++) e[5 + i] = int(p[o + i]!)
+ } else {
+ const t = e[8]!
+ for (let i = 4; i < 8; i++) e[5 + i] = t
+ }
+ }
+ if ((av & AV_LEFT) !== 0) {
+ for (let i = 0; i < 4; i++) e[3 - i] = int(p[(y + i) * stride + x - 1]!)
+ }
+ if ((av & AV_TL) !== 0) e[4] = int(p[(y - 1) * stride + x - 1]!)
+}
+
+export function pred4(dst: Uint8Array, dO: int, ds: int, e: Int32Array, mode: int, av: int) {
+ if (mode === I4_V) {
+ for (let y = 0; y < 4; y++) {
+ for (let x = 0; x < 4; x++) dst[dO + y * ds + x] = e[5 + x]!
+ }
+ return
+ }
+ if (mode === I4_H) {
+ for (let y = 0; y < 4; y++) {
+ const v = e[3 - y]!
+ for (let x = 0; x < 4; x++) dst[dO + y * ds + x] = v
+ }
+ return
+ }
+ if (mode === I4_DC) {
+ const top = (av & AV_TOP) !== 0
+ const left = (av & AV_LEFT) !== 0
+ let dc = 128
+ if (top && left) {
+ dc = (e[5]! + e[6]! + e[7]! + e[8]! + e[0]! + e[1]! + e[2]! + e[3]! + 4) >> 3
+ } else if (top) {
+ dc = (e[5]! + e[6]! + e[7]! + e[8]! + 2) >> 2
+ } else if (left) {
+ dc = (e[0]! + e[1]! + e[2]! + e[3]! + 2) >> 2
+ }
+ const v = dc
+ for (let y = 0; y < 4; y++) {
+ for (let x = 0; x < 4; x++) dst[dO + y * ds + x] = v
+ }
+ return
+ }
+ directional(dst, dO, ds, e, mode, 4)
+}
+
+function fAt(e: Int32Array, i: int): int {
+ return (e[i - 1]! + 2 * e[i]! + e[i + 1]! + 2) >> 2
+}
+
+function aAt(e: Int32Array, i: int): int {
+ return (e[i]! + e[i + 1]! + 1) >> 1
+}
+
+function directional(dst: Uint8Array, dO: int, ds: int, e: Int32Array, mode: int, n: int) {
+ const tl = n
+ const t0 = n + 1
+ const last = 3 * n
+ for (let y = 0; y < n; y++) {
+ const row = dO + y * ds
+ for (let x = 0; x < n; x++) {
+ let v = 0
+ if (mode === I4_DDL) {
+ v = x === n - 1 && y === n - 1 ? (e[last - 1]! + 3 * e[last]! + 2) >> 2 : fAt(e, t0 + 1 + x + y)
+ } else if (mode === I4_DDR) {
+ v = fAt(e, tl + x - y)
+ } else if (mode === I4_VR) {
+ const z = 2 * x - y
+ if (z >= 0) {
+ v = (z & 1) === 0 ? aAt(e, tl + x - (y >> 1)) : fAt(e, tl + x - (y >> 1))
+ } else if (z === -1) {
+ v = fAt(e, tl)
+ } else {
+ v = fAt(e, tl + 1 - y + 2 * x)
+ }
+ } else if (mode === I4_HD) {
+ const z = 2 * y - x
+ if (z >= 0) {
+ v = (z & 1) === 0 ? aAt(e, tl - 1 - y + (x >> 1)) : fAt(e, tl - y + (x >> 1))
+ } else if (z === -1) {
+ v = fAt(e, tl)
+ } else {
+ v = fAt(e, tl - 1 + x - 2 * y)
+ }
+ } else if (mode === I4_VL) {
+ v = (y & 1) === 0 ? aAt(e, t0 + x + (y >> 1)) : fAt(e, t0 + 1 + x + (y >> 1))
+ } else {
+ const z = x + 2 * y
+ const k = y + (x >> 1)
+ const lim = 2 * n - 3
+ if (z < lim) {
+ v = (z & 1) === 0 ? aAt(e, n - 2 - k) : fAt(e, n - 2 - k)
+ } else if (z === lim) {
+ v = (e[1]! + 3 * e[0]! + 2) >> 2
+ } else {
+ v = e[0]!
+ }
+ }
+ dst[row + x] = v
+ }
+ }
+}
+
+export function gather8(e: Int32Array, f: Int32Array, p: Uint8Array, stride: int, x: int, y: int, av: int) {
+ const top = (av & AV_TOP) !== 0
+ const left = (av & AV_LEFT) !== 0
+ const tl = (av & AV_TL) !== 0
+ if (top) {
+ const o = (y - 1) * stride + x
+ for (let i = 0; i < 8; i++) e[9 + i] = int(p[o + i]!)
+ if ((av & AV_TR) !== 0) {
+ for (let i = 8; i < 16; i++) e[9 + i] = int(p[o + i]!)
+ } else {
+ const t = e[16]!
+ for (let i = 8; i < 16; i++) e[9 + i] = t
+ }
+ }
+ if (left) {
+ for (let i = 0; i < 8; i++) e[7 - i] = int(p[(y + i) * stride + x - 1]!)
+ }
+ if (tl) e[8] = int(p[(y - 1) * stride + x - 1]!)
+ if (tl) {
+ if (top && left) {
+ f[8] = (e[9]! + 2 * e[8]! + e[7]! + 2) >> 2
+ } else if (top) {
+ f[8] = (3 * e[8]! + e[9]! + 2) >> 2
+ } else if (left) {
+ f[8] = (3 * e[8]! + e[7]! + 2) >> 2
+ } else {
+ f[8] = e[8]!
+ }
+ }
+ if (top) {
+ f[9] = tl ? (e[8]! + 2 * e[9]! + e[10]! + 2) >> 2 : (3 * e[9]! + e[10]! + 2) >> 2
+ for (let i = 1; i < 15; i++) f[9 + i] = (e[8 + i]! + 2 * e[9 + i]! + e[10 + i]! + 2) >> 2
+ f[24] = (e[23]! + 3 * e[24]! + 2) >> 2
+ }
+ if (left) {
+ f[7] = tl ? (e[8]! + 2 * e[7]! + e[6]! + 2) >> 2 : (3 * e[7]! + e[6]! + 2) >> 2
+ for (let i = 1; i < 7; i++) f[7 - i] = (e[8 - i]! + 2 * e[7 - i]! + e[6 - i]! + 2) >> 2
+ f[0] = (e[1]! + 3 * e[0]! + 2) >> 2
+ }
+}
+
+export function pred8(dst: Uint8Array, dO: int, ds: int, f: Int32Array, mode: int, av: int) {
+ if (mode === I4_V) {
+ for (let y = 0; y < 8; y++) {
+ for (let x = 0; x < 8; x++) dst[dO + y * ds + x] = f[9 + x]!
+ }
+ return
+ }
+ if (mode === I4_H) {
+ for (let y = 0; y < 8; y++) {
+ const v = f[7 - y]!
+ for (let x = 0; x < 8; x++) dst[dO + y * ds + x] = v
+ }
+ return
+ }
+ if (mode === I4_DC) {
+ const top = (av & AV_TOP) !== 0
+ const left = (av & AV_LEFT) !== 0
+ let st = 0
+ let sl = 0
+ for (let i = 0; i < 8; i++) {
+ st += f[9 + i]!
+ sl += f[7 - i]!
+ }
+ let dc = 128
+ if (top && left) {
+ dc = (st + sl + 8) >> 4
+ } else if (top) {
+ dc = (st + 4) >> 3
+ } else if (left) {
+ dc = (sl + 4) >> 3
+ }
+ const v = dc
+ for (let y = 0; y < 8; y++) {
+ for (let x = 0; x < 8; x++) dst[dO + y * ds + x] = v
+ }
+ return
+ }
+ directional(dst, dO, ds, f, mode, 8)
+}
+
+export function pred16(dst: Uint8Array, dO: int, ds: int, p: Uint8Array, stride: int, x: int, y: int, mode: int, av: int) {
+ if (mode === I16_V) {
+ const o = (y - 1) * stride + x
+ for (let j = 0; j < 16; j++) {
+ for (let i = 0; i < 16; i++) dst[dO + j * ds + i] = p[o + i]!
+ }
+ return
+ }
+ if (mode === I16_H) {
+ for (let j = 0; j < 16; j++) {
+ const v = p[(y + j) * stride + x - 1]!
+ for (let i = 0; i < 16; i++) dst[dO + j * ds + i] = v
+ }
+ return
+ }
+ if (mode === I16_DC) {
+ const top = (av & AV_TOP) !== 0
+ const left = (av & AV_LEFT) !== 0
+ let sum = 0
+ if (top) {
+ const o = (y - 1) * stride + x
+ for (let i = 0; i < 16; i++) sum += int(p[o + i]!)
+ }
+ if (left) {
+ for (let j = 0; j < 16; j++) sum += int(p[(y + j) * stride + x - 1]!)
+ }
+ let dc = 128
+ if (top && left) {
+ dc = (sum + 16) >> 5
+ } else if (top || left) {
+ dc = (sum + 8) >> 4
+ }
+ const v = dc
+ for (let j = 0; j < 16; j++) {
+ for (let i = 0; i < 16; i++) dst[dO + j * ds + i] = v
+ }
+ return
+ }
+ const to = (y - 1) * stride + x
+ let hh = 0
+ let vv = 0
+ for (let k = 0; k < 8; k++) {
+ hh += (k + 1) * (int(p[to + 8 + k]!) - int(p[to + 6 - k]!))
+ vv += (k + 1) * (int(p[(y + 8 + k) * stride + x - 1]!) - int(p[(y + 6 - k) * stride + x - 1]!))
+ }
+ const a = 16 * (int(p[(y + 15) * stride + x - 1]!) + int(p[to + 15]!))
+ const b = (5 * hh + 32) >> 6
+ const c = (5 * vv + 32) >> 6
+ for (let j = 0; j < 16; j++) {
+ for (let i = 0; i < 16; i++) {
+ const v = (a + b * (i - 7) + c * (j - 7) + 16) >> 5
+ const c255 = v < 0 ? 0 : v > 255 ? 255 : v
+ dst[dO + j * ds + i] = c255
+ }
+ }
+}
+
+export function predChroma(dst: Uint8Array, dO: int, ds: int, p: Uint8Array, stride: int, x: int, y: int, mode: int, av: int) {
+ const top = (av & AV_TOP) !== 0
+ const left = (av & AV_LEFT) !== 0
+ if (mode === C_V) {
+ const o = (y - 1) * stride + x
+ for (let j = 0; j < 8; j++) {
+ for (let i = 0; i < 8; i++) dst[dO + j * ds + i] = p[o + i]!
+ }
+ return
+ }
+ if (mode === C_H) {
+ for (let j = 0; j < 8; j++) {
+ const v = p[(y + j) * stride + x - 1]!
+ for (let i = 0; i < 8; i++) dst[dO + j * ds + i] = v
+ }
+ return
+ }
+ if (mode === C_DC) {
+ for (let by = 0; by < 2; by++) {
+ for (let bx = 0; bx < 2; bx++) {
+ let st = 0
+ let sl = 0
+ if (top) {
+ const o = (y - 1) * stride + x + bx * 4
+ for (let i = 0; i < 4; i++) st += int(p[o + i]!)
+ }
+ if (left) {
+ for (let j = 0; j < 4; j++) sl += int(p[(y + by * 4 + j) * stride + x - 1]!)
+ }
+ let dc = 128
+ if (bx === by) {
+ if (top && left) {
+ dc = (st + sl + 4) >> 3
+ } else if (left) {
+ dc = (sl + 2) >> 2
+ } else if (top) {
+ dc = (st + 2) >> 2
+ }
+ } else if (bx === 1) {
+ if (top) {
+ dc = (st + 2) >> 2
+ } else if (left) {
+ dc = (sl + 2) >> 2
+ }
+ } else {
+ if (left) {
+ dc = (sl + 2) >> 2
+ } else if (top) {
+ dc = (st + 2) >> 2
+ }
+ }
+ const v = dc
+ for (let j = 0; j < 4; j++) {
+ for (let i = 0; i < 4; i++) dst[dO + (by * 4 + j) * ds + bx * 4 + i] = v
+ }
+ }
+ }
+ return
+ }
+ const to = (y - 1) * stride + x
+ let hh = 0
+ let vv = 0
+ for (let k = 0; k < 4; k++) {
+ hh += (k + 1) * (int(p[to + 4 + k]!) - int(p[to + 2 - k]!))
+ vv += (k + 1) * (int(p[(y + 4 + k) * stride + x - 1]!) - int(p[(y + 2 - k) * stride + x - 1]!))
+ }
+ const a = 16 * (int(p[(y + 7) * stride + x - 1]!) + int(p[to + 7]!))
+ const b = (34 * hh + 32) >> 6
+ const c = (34 * vv + 32) >> 6
+ for (let j = 0; j < 8; j++) {
+ for (let i = 0; i < 8; i++) {
+ const v = (a + b * (i - 3) + c * (j - 3) + 16) >> 5
+ const c255 = v < 0 ? 0 : v > 255 ? 255 : v
+ dst[dO + j * ds + i] = c255
+ }
+ }
+}
+
+test("4x4 directional modes on a known edge", () => {
+ const e = new Int32Array(13)
+ for (let i = 0; i < 4; i++) e[3 - i] = 10 * (i + 1)
+ e[4] = 5
+ for (let i = 0; i < 8; i++) e[5 + i] = 100 + i * 4
+ const d = new Uint8Array(16)
+ const all = AV_TOP | AV_LEFT | AV_TL | AV_TR
+ pred4(d, 0, 4, e, I4_DDL, all)
+ expect((d[0]!)).toBe((100 + 2 * 104 + 108 + 2) >> 2)
+ expect((d[15]!)).toBe((124 + 3 * 128 + 2) >> 2)
+ pred4(d, 0, 4, e, I4_DDR, all)
+ expect((d[0]!)).toBe((100 + 2 * 5 + 10 + 2) >> 2)
+ expect((d[12]!)).toBe((40 + 2 * 30 + 20 + 2) >> 2)
+ pred4(d, 0, 4, e, I4_HU, all)
+ expect((d[15]!)).toBe(40)
+ expect((d[9]!)).toBe((30 + 3 * 40 + 2) >> 2)
+ expect((d[10]!)).toBe(40)
+ pred4(d, 0, 4, e, I4_VR, all)
+ expect((d[4]!)).toBe((10 + 2 * 5 + 100 + 2) >> 2)
+ expect((d[8]!)).toBe((20 + 2 * 10 + 5 + 2) >> 2)
+ pred4(d, 0, 4, e, I4_HD, all)
+ expect((d[1]!)).toBe((10 + 2 * 5 + 100 + 2) >> 2)
+ expect((d[3]!)).toBe((108 + 2 * 104 + 100 + 2) >> 2)
+ expect((d[2]!)).toBe((104 + 2 * 100 + 5 + 2) >> 2)
+})
diff --git a/capcodec/src/ipred.tov b/capcodec/src/ipred.tov
new file mode 100644
index 000000000..80ac9ff9e
--- /dev/null
+++ b/capcodec/src/ipred.tov
@@ -0,0 +1,1262 @@
+import {
+ AV_LEFT, AV_TL, AV_TOP, AV_TR, C_DC, C_H, C_PLANE, C_V, I16_DC, I16_H, I16_PLANE, I16_V, I4_DC, I4_DDL, I4_DDR, I4_H,
+ I4_HD, I4_HU, I4_V, I4_VL, I4_VR, chromaModeAvailable, gather4, gather8, mode16Available, modeAvailable, modeMask, pred16,
+ pred4, pred8, predChroma,
+} from "./intra"
+import {
+ T16_HI, T16_LO, T32_HI, T32_LO, T64_HI, T64_LO, h4x4, sa8d, sa8dMax, sa8dMax2, satd16, satd4, satd8,
+} from "./satd"
+
+export const COST_NA = 1 << 30
+
+const VH = 0
+const DT = 16
+const HT = 32
+const DL = 96
+const DR = 112
+const VE = 128
+const VO = 144
+const HQ = 160
+const HQ8 = 176
+const VA = 192
+const HU = 208
+const HU8 = 224
+export const T8_SIZE = 240
+
+const ROW8: int[] = [
+ VH, VH, VH, VH, VH, VH, VH, VH,
+ HT, HT + 8, HT + 16, HT + 24, HT + 32, HT + 40, HT + 48, HT + 56,
+ DT, DT, DT, DT, DT, DT, DT, DT,
+ DL, DL + 1, DL + 2, DL + 3, DL + 4, DL + 5, DL + 6, DL + 7,
+ DR + 7, DR + 6, DR + 5, DR + 4, DR + 3, DR + 2, DR + 1, DR,
+ VE + 4, VO + 3, VE + 3, VO + 2, VE + 2, VO + 1, VE + 1, VO,
+ HQ8 + 6, HQ8 + 4, HQ8 + 2, HQ + 8, HQ + 6, HQ + 4, HQ + 2, HQ,
+ VA, DL, VA + 1, DL + 1, VA + 2, DL + 2, VA + 3, DL + 3,
+ HU, HU + 2, HU + 4, HU + 6, HU + 8, HU8 + 2, HU8 + 4, HU8 + 6,
+]
+
+function lowpass(x: u8x16, xm: u8x16, xp: u8x16): u8x16 {
+ return x.avg(xm.avg(xp) - ((xm ^ xp) & u8x16.splat(1)))
+}
+
+export function blocks4(dst: Uint8Array, src: Uint8Array, so: int, ss: int) {
+ for (let by = 0; by < 4; by++) {
+ const o = so + by * 4 * ss
+ const r0 = i32x4.bitcast(u8x16.load(src, o))
+ const r1 = i32x4.bitcast(u8x16.load(src, o + ss))
+ const r2 = i32x4.bitcast(u8x16.load(src, o + 2 * ss))
+ const r3 = i32x4.bitcast(u8x16.load(src, o + 3 * ss))
+ const t0 = i32x4.shuffle(r0, r1, [0, 4, 1, 5])
+ const t1 = i32x4.shuffle(r2, r3, [0, 4, 1, 5])
+ const t2 = i32x4.shuffle(r0, r1, [2, 6, 3, 7])
+ const t3 = i32x4.shuffle(r2, r3, [2, 6, 3, 7])
+ u8x16.bitcast(i32x4.shuffle(t0, t1, [0, 1, 4, 5])).store(dst, by * 64)
+ u8x16.bitcast(i32x4.shuffle(t0, t1, [2, 3, 6, 7])).store(dst, by * 64 + 16)
+ u8x16.bitcast(i32x4.shuffle(t2, t3, [0, 1, 4, 5])).store(dst, by * 64 + 32)
+ u8x16.bitcast(i32x4.shuffle(t2, t3, [2, 3, 6, 7])).store(dst, by * 64 + 48)
+ }
+}
+
+export function unblocks4(dst: Uint8Array, d: int, ds: int, blk: Uint8Array) {
+ for (let by = 0; by < 4; by++) {
+ const b0 = i32x4.bitcast(u8x16.load(blk, by * 64))
+ const b1 = i32x4.bitcast(u8x16.load(blk, by * 64 + 16))
+ const b2 = i32x4.bitcast(u8x16.load(blk, by * 64 + 32))
+ const b3 = i32x4.bitcast(u8x16.load(blk, by * 64 + 48))
+ const t0 = i32x4.shuffle(b0, b1, [0, 4, 1, 5])
+ const t1 = i32x4.shuffle(b2, b3, [0, 4, 1, 5])
+ const t2 = i32x4.shuffle(b0, b1, [2, 6, 3, 7])
+ const t3 = i32x4.shuffle(b2, b3, [2, 6, 3, 7])
+ const o = d + by * 4 * ds
+ u8x16.bitcast(i32x4.shuffle(t0, t1, [0, 1, 4, 5])).store(dst, o)
+ u8x16.bitcast(i32x4.shuffle(t0, t1, [2, 3, 6, 7])).store(dst, o + ds)
+ u8x16.bitcast(i32x4.shuffle(t2, t3, [0, 1, 4, 5])).store(dst, o + 2 * ds)
+ u8x16.bitcast(i32x4.shuffle(t2, t3, [2, 3, 6, 7])).store(dst, o + 3 * ds)
+ }
+}
+
+export function edge4m(xb: Uint8Array, p: Uint8Array, stride: int, x: int, y: int, av: int, rb: Uint8Array, r: int) {
+ const bx = r & 3
+ const by = r >> 2
+ let v = u8x16.splat(0)
+ if (by > 0) {
+ const up = u8x16.load(rb, (r - 4) * 16)
+ v = (av & AV_TR) !== 0 ?
+ u8x16.shuffle(up, u8x16.load(rb, (r - 3) * 16), [0, 0, 0, 0, 0, 0, 12, 13, 14, 15, 28, 29, 30, 31, 31, 31]) :
+ up.swizzle([0, 0, 0, 0, 0, 0, 12, 13, 14, 15, 15, 15, 15, 15, 15, 15])
+ v = v.withLane(5, bx > 0 ? rb[(r - 5) * 16 + 15]! : p[(y - 1) * stride + x - 1]!)
+ } else if ((av & AV_TOP) !== 0) {
+ const t = u8x16.load(p, (y - 1) * stride + x - 6)
+ v = (av & AV_TR) !== 0 ? t.swizzle([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 13, 13]) :
+ t.swizzle([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 9, 9])
+ }
+ if (bx > 0) {
+ v = u8x16.shuffle(v, u8x16.load(rb, (r - 1) * 16), [31, 31, 27, 23, 19, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
+ } else if ((av & AV_LEFT) !== 0) {
+ const o = y * stride + x - 1
+ const l3 = p[o + 3 * stride]!
+ v = v.withLane(4, p[o]!).withLane(3, p[o + stride]!).withLane(2, p[o + 2 * stride]!).withLane(1, l3).withLane(0, l3)
+ }
+ v.store(xb, 0)
+}
+
+export function edge4(xb: Uint8Array, p: Uint8Array, stride: int, x: int, y: int, av: int) {
+ let v = u8x16.splat(0)
+ if ((av & AV_TOP) !== 0) {
+ const t = u8x16.load(p, (y - 1) * stride + x - 6)
+ v = (av & AV_TR) !== 0 ? t.swizzle([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 13, 13]) :
+ t.swizzle([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9, 9, 9, 9, 9, 9])
+ }
+ if ((av & AV_LEFT) !== 0) {
+ const o = y * stride + x - 1
+ const l3 = p[o + 3 * stride]!
+ v = v.withLane(4, p[o]!).withLane(3, p[o + stride]!).withLane(2, p[o + 2 * stride]!).withLane(1, l3).withLane(0, l3)
+ }
+ v.store(xb, 0)
+}
+
+function dc4(xb: Uint8Array, av: int): int {
+ const top = (av & AV_TOP) !== 0
+ const left = (av & AV_LEFT) !== 0
+ const st = int(xb[6]!) + int(xb[7]!) + int(xb[8]!) + int(xb[9]!)
+ const sl = int(xb[1]!) + int(xb[2]!) + int(xb[3]!) + int(xb[4]!)
+ if (top && left) return (st + sl + 4) >> 3
+ if (top) return (st + 2) >> 2
+ if (left) return (sl + 2) >> 2
+ return 128
+}
+
+export function pred4v(xb: Uint8Array, mode: int, av: int): u8x16 {
+ const x = u8x16.load(xb, 0)
+ if (mode === I4_V) return x.swizzle([6, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9])
+ if (mode === I4_H) return x.swizzle([4, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 2, 1, 1, 1, 1])
+ if (mode === I4_DC) return u8x16.splat(dc4(xb, av))
+ const xp = x.swizzle([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15])
+ const f = lowpass(x, x.swizzle([0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]), xp)
+ const a = x.avg(xp)
+ if (mode === I4_DDL) return u8x16.shuffle(f, a, [7, 8, 9, 10, 8, 9, 10, 11, 9, 10, 11, 12, 10, 11, 12, 13])
+ if (mode === I4_DDR) return u8x16.shuffle(f, a, [5, 6, 7, 8, 4, 5, 6, 7, 3, 4, 5, 6, 2, 3, 4, 5])
+ if (mode === I4_VR) return u8x16.shuffle(f, a, [21, 22, 23, 24, 5, 6, 7, 8, 4, 21, 22, 23, 3, 5, 6, 7])
+ if (mode === I4_HD) return u8x16.shuffle(f, a, [20, 5, 6, 7, 19, 4, 20, 5, 18, 3, 19, 4, 17, 2, 18, 3])
+ if (mode === I4_VL) return u8x16.shuffle(f, a, [22, 23, 24, 25, 7, 8, 9, 10, 23, 24, 25, 26, 8, 9, 10, 11])
+ return u8x16.shuffle(f, a, [19, 3, 18, 2, 18, 2, 17, 1, 17, 1, 16, 16, 16, 16, 16, 16])
+}
+
+const DUP4_01 = [0, 1, 0, 1, 2, 3, 2, 3, 4, 5, 4, 5, 6, 7, 6, 7, 16, 17, 16, 17, 18, 19, 18, 19, 20, 21, 20, 21, 22, 23, 22, 23]
+const DUP4_23 = [
+ 8, 9, 8, 9, 10, 11, 10, 11, 12, 13, 12, 13, 14, 15, 14, 15, 24, 25, 24, 25, 26, 27, 26, 27, 28, 29, 28, 29, 30, 31, 30, 31,
+]
+const HMUL4 = i8x32(
+ 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1, 1, 1, 1, -1,
+)
+const SWAP_DW = [2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13]
+const SWAP_QW = [4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11]
+const EVEN16 = i16x16(-1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0)
+const PRED_VH = [6, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9, 6, 7, 8, 9, 20, 20, 20, 20, 19, 19, 19, 19, 18, 18, 18, 18, 17, 17, 17, 17]
+const PRED_DDL_DDR = [
+ 7, 8, 9, 10, 8, 9, 10, 11, 9, 10, 11, 12, 10, 11, 12, 13, 21, 22, 23, 24, 20, 21, 22, 23, 19, 20, 21, 22, 18, 19, 20, 21,
+]
+const PRED_VR_HD = [
+ 37, 38, 39, 40, 5, 6, 7, 8, 4, 37, 38, 39, 3, 5, 6, 7, 52, 21, 22, 23, 51, 20, 52, 21, 50, 19, 51, 20, 49, 18, 50, 19,
+]
+const PRED_VL_HU = [
+ 38, 39, 40, 41, 7, 8, 9, 10, 39, 40, 41, 42, 8, 9, 10, 11, 51, 19, 50, 18, 50, 18, 49, 17, 49, 17, 48, 48, 48, 48, 48, 48,
+]
+const NEXT32 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 31]
+const PREV32 = [0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30]
+
+function i4NaCosts(): Int32Array {
+ const t = new Int32Array(256)
+ for (let av = 0; av < 16; av++) {
+ for (let m = 0; m < 16; m++) t[av * 16 + m] = m < 9 && modeAvailable(m, av) ? 0 : COST_NA
+ }
+ return t
+}
+
+const I4_NA = i4NaCosts()
+const HEAD_MODES = i32x4(0, 1, 2, -1)
+const DIR_MODES = i32x8(3, 4, 5, 6, 7, 8, -1, -1)
+export const I4_BEST_MODE = 12
+export const I4_BEST_COST = 13
+
+function absMax4(v: i16x16): i16x16 {
+ const s = v.swizzle(SWAP_DW)
+ const h = i16x16.select(i16x16(-1, -1, 0, 0, -1, -1, 0, 0, -1, -1, 0, 0, -1, -1, 0, 0), v + s, s - v).abs()
+ return h.max(h.swizzle(SWAP_QW))
+}
+
+function satd4Pair(s01: i16x16, s23: i16x16, p: u8x32): i16x16 {
+ const r01 = s01 - u8x32.madd(p.swizzle(DUP4_01), HMUL4)
+ const r23 = s23 - u8x32.madd(p.swizzle(DUP4_23), HMUL4)
+ return absMax4(r01 + r23) + absMax4(r01 - r23)
+}
+
+export function i4Costs(
+ costs: Int32Array, src: Uint8Array, so: int, xb: Uint8Array, av: int, pb: Uint8Array, pm: int, bias: int,
+) {
+ // pmaddubsw takes the first horizontal butterfly of the source and of each prediction from duplicated pixel pairs,
+ // and the residual's is their difference. The last vertical stage folds into |a + b| + |a - b| = 2 * max(|a|, |b|);
+ // each half of a pair's sum holds one mode and adds the 16 coefficients' magnitudes, at most 16 * 4 * 255 < 32768
+ // (Cauchy-Schwarz with Parseval). The DC prediction's first butterfly is 2 * dc in the even lanes of every row, so its
+ // residual rows 0 - 2 and 1 - 3 are the source's. The choice is the first cheapest of V, H and DC with the most
+ // probable mode's bias; a directional mode replaces it only when strictly cheaper, all of them where that choice costs
+ // more than 0, else the most probable mode alone if directional, and none (nor their costs) where its bias can't win.
+ // Lanes 9 and 10 of the directional costs repeat VL and HU and are masked like unavailable modes.
+ const s = u8x16.load(src, so)
+ const sd = u8x32.concat(s, s)
+ const s01 = u8x32.madd(sd.swizzle(DUP4_01), HMUL4)
+ const s23 = u8x32.madd(sd.swizzle(DUP4_23), HMUL4)
+ const x = u8x16.load(xb, 0)
+ const x2 = u8x32.concat(x, x)
+ const top = (av & AV_TOP) !== 0
+ const left = (av & AV_LEFT) !== 0
+ const e = u8x16.sadParts(x.swizzle([6, 7, 8, 9, 6, 7, 8, 9, 1, 2, 3, 4, 1, 2, 3, 4]), u8x16.splat(0))
+ const st2 = int(e.lane(0))
+ const sl2 = int(e.lane(2))
+ const dc = top && left ? (st2 + sl2 + 8) >> 4 : top ? (st2 + 4) >> 3 : left ? (sl2 + 4) >> 3 : 128
+ const pvh = x2.swizzle(PRED_VH)
+ pvh.store(pb, I4_V * 16)
+ u8x16.splat(dc).store(pb, I4_DC * 16)
+ const m1 = satd4Pair(s01, s23, pvh)
+ const m2 = absMax4(s01 + s23 - (i16x16.splat(4 * dc) & EVEN16)) + absMax4(s01 - s23)
+ const t = i16x16.madd(i16x16.hadd(m1, m2), i16x16.splat(1))
+ const r = (i32x8.hadd(t, t).low() >> 1).max(i32x4.load(I4_NA, av * 16)) -
+ (i32x4.splat(pm).eq(HEAD_MODES) & i32x4.splat(bias))
+ r.store(costs, 0)
+ const r1 = r.min(r.swizzle([2, 3, 0, 1]))
+ const rm = r1.min(r1.swizzle([1, 0, 3, 2]))
+ let bc = int(rm.lane(0))
+ let bm = Math.ctz32(r.eq(rm).mask())
+ if (bc > 0 || (pm > I4_DC && bc > -bias)) {
+ const xp = x2.swizzle(NEXT32)
+ const xm = x2.swizzle(PREV32)
+ const f = x2.avg(xm.avg(xp) - ((xm ^ xp) & u8x32.splat(1)))
+ const a = x2.avg(xp)
+ const p34 = u8x32.shuffle(f, a, PRED_DDL_DDR)
+ const p56 = u8x32.shuffle(f, a, PRED_VR_HD)
+ const p78 = u8x32.shuffle(f, a, PRED_VL_HU)
+ p34.store(pb, I4_DDL * 16)
+ p56.store(pb, I4_VR * 16)
+ p78.store(pb, I4_VL * 16)
+ const m3 = satd4Pair(s01, s23, p34)
+ const m4 = satd4Pair(s01, s23, p56)
+ const m5 = satd4Pair(s01, s23, p78)
+ const k = i16x16.hadd(i16x16.hadd(m3, m4), i16x16.hadd(m5, m5))
+ const rd = (i16x16.madd(k, i16x16.splat(1)) >> 1).max(i32x8.load(I4_NA, av * 16 + I4_DDL)) -
+ (i32x8.splat(pm).eq(DIR_MODES) & i32x8.splat(bias))
+ rd.store(costs, I4_DDL)
+ if (bc > 0) {
+ const d1 = rd.min(rd.swizzle([4, 5, 6, 7, 0, 1, 2, 3]))
+ const d2 = d1.min(d1.swizzle([2, 3, 0, 1, 6, 7, 4, 5]))
+ const dm = d2.min(d2.swizzle([1, 0, 3, 2, 5, 4, 7, 6]))
+ const md = int(dm.lane(0))
+ if (md < bc) {
+ bc = md
+ bm = I4_DDL + Math.ctz32(rd.eq(dm).mask())
+ }
+ } else {
+ const c = costs[pm]!
+ if (c < bc) {
+ bc = c
+ bm = pm
+ }
+ }
+ }
+ costs[I4_BEST_MODE] = bm
+ costs[I4_BEST_COST] = bc
+}
+
+const SHIFT1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
+const SHIFT2 = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]
+
+export function unblocks8(dst: Uint8Array, d: int, ds: int, blk: Uint8Array) {
+ for (let k = 0; k < 8; k++) {
+ const b = (k >> 2) * 128 + (k & 3) * 16
+ const l = i64x2.bitcast(u8x16.load(blk, b))
+ const r = i64x2.bitcast(u8x16.load(blk, b + 64))
+ const o = d + ((k >> 2) * 8 + (k & 3) * 2) * ds
+ u8x16.bitcast(i64x2.shuffle(l, r, [0, 2])).store(dst, o)
+ u8x16.bitcast(i64x2.shuffle(l, r, [1, 3])).store(dst, o + ds)
+ }
+}
+
+export function edge8m(t: Uint8Array, p: Uint8Array, stride: int, x: int, y: int, av: int, rb: Uint8Array, b8: int) {
+ const top = (av & AV_TOP) !== 0
+ const left = (av & AV_LEFT) !== 0
+ const tl = (av & AV_TL) !== 0
+ const zero = u8x16.splat(0)
+ let c: int = 0
+ if (tl) c = b8 === 3 ? int(rb[63]!) : int(p[(y - 1) * stride + x - 1]!)
+ let tv = u8x16.splat(c)
+ if (top) {
+ const tr = (av & AV_TR) !== 0
+ if (b8 < 2) {
+ const v = u8x16.load(p, (y - 1) * stride + x)
+ tv = tr ? v : v.swizzle([0, 1, 2, 3, 4, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7])
+ } else {
+ const v = u8x16.load(rb, (b8 - 2) * 64 + 48)
+ tv = tr ? u8x16.shuffle(v, u8x16.load(rb, 112), [8, 9, 10, 11, 12, 13, 14, 15, 24, 25, 26, 27, 28, 29, 30, 31]) :
+ v.swizzle([8, 9, 10, 11, 12, 13, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15])
+ }
+ }
+ let lv = u8x16.splat(c)
+ if (left) {
+ if ((b8 & 1) === 0) {
+ const o = y * stride + x - 1
+ lv = lv.withLane(0, p[o]!).withLane(1, p[o + stride]!).withLane(2, p[o + 2 * stride]!).withLane(3, p[o + 3 * stride]!)
+ .withLane(4, p[o + 4 * stride]!).withLane(5, p[o + 5 * stride]!).withLane(6, p[o + 6 * stride]!).withLane(7, p[o + 7 * stride]!)
+ } else {
+ const b = (b8 - 1) * 64
+ const s01 = u8x16.shuffle(u8x16.load(rb, b), u8x16.load(rb, b + 16), [7, 15, 23, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
+ const s23 = u8x16.shuffle(u8x16.load(rb, b + 32), u8x16.load(rb, b + 48), [7, 15, 23, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
+ lv = u8x16.shuffle(s01, s23, [0, 1, 2, 3, 16, 17, 18, 19, 0, 0, 0, 0, 0, 0, 0, 0]).withLane(8, c)
+ }
+ }
+ const r0 = u8x16.shuffle(lv, tv, [7, 7, 6, 5, 4, 3, 2, 1, 0, 8, 16, 17, 18, 19, 20, 21])
+ const r1 = u8x16.shuffle(tv, zero, [6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15, 16, 16, 16, 16, 16])
+ let f0 = lowpass(u8x16.shuffle(r0, r1, SHIFT1), r0, u8x16.shuffle(r0, r1, SHIFT2))
+ const f1 = lowpass(u8x16.shuffle(r1, zero, SHIFT1), r1, u8x16.shuffle(r1, zero, SHIFT2))
+ if (!tl) {
+ if (top) f0 = f0.withLane(9, u8((3 * int(tv.lane(0)) + int(tv.lane(1)) + 2) >> 2))
+ if (left) f0 = f0.withLane(7, u8((3 * int(lv.lane(0)) + int(lv.lane(1)) + 2) >> 2))
+ }
+ const xa = u8x16.shuffle(f0, zero, [16, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
+ const xb = u8x16.shuffle(f0, f1, [14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 24, 26, 27, 28, 29])
+ const xc = u8x16.shuffle(f1, zero, [14, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16])
+ const x1a = u8x16.shuffle(xa, xb, SHIFT1)
+ const x2a = u8x16.shuffle(xa, xb, SHIFT2)
+ const x1b = u8x16.shuffle(xb, xc, SHIFT1)
+ const x2b = u8x16.shuffle(xb, xc, SHIFT2)
+ const ft0 = lowpass(x1a, xa, x2a)
+ const ft1 = lowpass(x1b, xb, x2b)
+ const at0 = x1a.avg(x2a)
+ const at1 = x1b.avg(x2b)
+ const vh = u8x16.shuffle(f0, f1, [9, 10, 11, 12, 13, 14, 15, 16, 7, 6, 5, 4, 3, 2, 1, 0])
+ vh.store(t, VH)
+ const sp = u8x16.sadParts(vh, zero)
+ let dc = 128
+ if (top && left) {
+ dc = (int(sp.lane(0)) + int(sp.lane(2)) + 8) >> 4
+ } else if (top) {
+ dc = (int(sp.lane(0)) + 4) >> 3
+ } else if (left) {
+ dc = (int(sp.lane(2)) + 4) >> 3
+ }
+ u8x16.splat(dc).store(t, DT)
+ f0.swizzle([7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6]).store(t, HT)
+ f0.swizzle([5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4]).store(t, HT + 16)
+ f0.swizzle([3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2]).store(t, HT + 32)
+ f0.swizzle([1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0]).store(t, HT + 48)
+ u8x16.shuffle(ft0, ft1, [11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]).store(t, DL)
+ u8x16.shuffle(ft0, ft1, SHIFT2).store(t, DR)
+ const a2 = u8x16.shuffle(at0, at1, SHIFT2)
+ u8x16.shuffle(ft0, a2, [2, 4, 6, 8, 23, 24, 25, 26, 27, 28, 29, 30, 30, 30, 30, 30]).store(t, VE)
+ u8x16.shuffle(ft0, ft1, [3, 5, 7, 9, 10, 11, 12, 13, 14, 15, 16, 17, 17, 17, 17, 17]).store(t, VO)
+ const hq = u8x16.shuffle(ft0, at0, [17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23, 8, 24, 9])
+ hq.store(t, HQ)
+ const hq1 = u8x16.shuffle(ft0, ft1, [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25])
+ u8x16.shuffle(hq, hq1, [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]).store(t, HQ8)
+ u8x16.shuffle(at0, at1, [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]).store(t, VA)
+ const hu = u8x16.shuffle(ft0, at0, [23, 7, 22, 6, 21, 5, 20, 4, 19, 3, 18, 2, 17, 1, 16, 16])
+ hu.store(t, HU)
+ u8x16.shuffle(hu, at0, [8, 9, 10, 11, 12, 13, 14, 15, 16, 16, 16, 16, 16, 16, 16, 16]).store(t, HU8)
+}
+
+function sa8dT(a: Uint8Array, ao: int, as: int, t: Uint8Array, m: int): int {
+ const k = m * 8
+ const r0 = i16x8.loadU8(a, ao) - i16x8.loadU8(t, ROW8[k]!)
+ const r1 = i16x8.loadU8(a, ao + as) - i16x8.loadU8(t, ROW8[k + 1]!)
+ const r2 = i16x8.loadU8(a, ao + 2 * as) - i16x8.loadU8(t, ROW8[k + 2]!)
+ const r3 = i16x8.loadU8(a, ao + 3 * as) - i16x8.loadU8(t, ROW8[k + 3]!)
+ const r4 = i16x8.loadU8(a, ao + 4 * as) - i16x8.loadU8(t, ROW8[k + 4]!)
+ const r5 = i16x8.loadU8(a, ao + 5 * as) - i16x8.loadU8(t, ROW8[k + 5]!)
+ const r6 = i16x8.loadU8(a, ao + 6 * as) - i16x8.loadU8(t, ROW8[k + 6]!)
+ const r7 = i16x8.loadU8(a, ao + 7 * as) - i16x8.loadU8(t, ROW8[k + 7]!)
+ return (sa8dMax(r0, r1, r2, r3, r4, r5, r6, r7).sum() + 1) >> 1
+}
+
+export function i8SrcCosts(costs: Int32Array, a: Uint8Array, ao: int, as: int, t: Uint8Array, av: int) {
+ const r0 = i16x8.loadU8(a, ao)
+ const r1 = i16x8.loadU8(a, ao + as)
+ const r2 = i16x8.loadU8(a, ao + 2 * as)
+ const r3 = i16x8.loadU8(a, ao + 3 * as)
+ const r4 = i16x8.loadU8(a, ao + 4 * as)
+ const r5 = i16x8.loadU8(a, ao + 5 * as)
+ const r6 = i16x8.loadU8(a, ao + 6 * as)
+ const r7 = i16x8.loadU8(a, ao + 7 * as)
+ const a0 = r0 + r1
+ const a1 = r0 - r1
+ const a2 = r2 + r3
+ const a3 = r2 - r3
+ const a4 = r4 + r5
+ const a5 = r4 - r5
+ const a6 = r6 + r7
+ const a7 = r6 - r7
+ const b0 = a0 + a2
+ const b1 = a1 + a3
+ const b2 = a0 - a2
+ const b3 = a1 - a3
+ const b4 = a4 + a6
+ const b5 = a5 + a7
+ const b6 = a4 - a6
+ const b7 = a5 - a7
+ const c0 = b0 + b4
+ const c1 = b1 + b5
+ const c2 = b2 + b6
+ const c3 = b3 + b7
+ const c4 = b0 - b4
+ const c5 = b1 - b5
+ const c6 = b2 - b6
+ const c7 = b3 - b7
+ const t0 = i16x8.shuffle(c0, c1, T16_LO)
+ const t1 = i16x8.shuffle(c0, c1, T16_HI)
+ const t2 = i16x8.shuffle(c2, c3, T16_LO)
+ const t3 = i16x8.shuffle(c2, c3, T16_HI)
+ const t4 = i16x8.shuffle(c4, c5, T16_LO)
+ const t5 = i16x8.shuffle(c4, c5, T16_HI)
+ const t6 = i16x8.shuffle(c6, c7, T16_LO)
+ const t7 = i16x8.shuffle(c6, c7, T16_HI)
+ const u0 = i16x8.shuffle(t0, t2, T32_LO)
+ const u1 = i16x8.shuffle(t0, t2, T32_HI)
+ const u2 = i16x8.shuffle(t1, t3, T32_LO)
+ const u3 = i16x8.shuffle(t1, t3, T32_HI)
+ const u4 = i16x8.shuffle(t4, t6, T32_LO)
+ const u5 = i16x8.shuffle(t4, t6, T32_HI)
+ const u6 = i16x8.shuffle(t5, t7, T32_LO)
+ const u7 = i16x8.shuffle(t5, t7, T32_HI)
+ const v0 = i16x8.shuffle(u0, u4, T64_LO)
+ const v1 = i16x8.shuffle(u0, u4, T64_HI)
+ const v2 = i16x8.shuffle(u1, u5, T64_LO)
+ const v3 = i16x8.shuffle(u1, u5, T64_HI)
+ const v4 = i16x8.shuffle(u2, u6, T64_LO)
+ const v5 = i16x8.shuffle(u2, u6, T64_HI)
+ const v6 = i16x8.shuffle(u3, u7, T64_LO)
+ const v7 = i16x8.shuffle(u3, u7, T64_HI)
+ const e0 = v0 + v1
+ const e1 = v0 - v1
+ const e2 = v2 + v3
+ const e3 = v2 - v3
+ const e4 = v4 + v5
+ const e5 = v4 - v5
+ const e6 = v6 + v7
+ const e7 = v6 - v7
+ const f0 = e0 + e2
+ const f1 = e1 + e3
+ const f2 = e0 - e2
+ const f3 = e1 - e3
+ const f4 = e4 + e6
+ const f5 = e5 + e7
+ const f6 = e4 - e6
+ const f7 = e5 - e7
+ // Lane i of g0 is the first coefficient of row i, and twice lane i of half is the sum of row i's |coefficients|
+ // (|a + b| + |a - b| = 2 * max(|a|, |b|)); V and DC change only row 0, and H only the first coefficient of each row.
+ const half = u16x8.bitcast(f0.abs().max(f4.abs()) + f1.abs().max(f5.abs()) + f2.abs().max(f6.abs()) + f3.abs().max(f7.abs()))
+ const g0 = f0 + f4
+ const e = h8x2(i16x16.concat(c0 - (i16x8.loadU8(t, VH) << 3), i16x8.loadU8(t, VH + 8)))
+ const r = u32x4.hadd(
+ u32x4.hadd(u16x8.bitcast(e.low().abs()).addPairs(), u16x8.bitcast((g0 - (e.high() << 3)).abs()).addPairs()),
+ u32x4.hadd(u16x8.bitcast(g0.abs()).addPairs(), half.addPairs()),
+ )
+ const all = 2 * int(r.lane(3))
+ const row0 = 2 * int(half.lane(0))
+ const dc0 = int(g0.lane(0))
+ const dcp = dc0 - 64 * int(t[DT]!)
+ if ((av & AV_TOP) !== 0) costs[I4_V] = (int(r.lane(0)) - row0 + all + 2) >> 2
+ if ((av & AV_LEFT) !== 0) costs[I4_H] = (int(r.lane(1)) - int(r.lane(2)) + all + 2) >> 2
+ costs[I4_DC] = ((dcp < 0 ? -dcp : dcp) - (dc0 < 0 ? -dc0 : dc0) + all + 2) >> 2
+}
+
+export function i8Cost(src: Uint8Array, so: int, ss: int, t: Uint8Array, mode: int): int {
+ return sa8dT(src, so, ss, t, mode)
+}
+
+function h8x2(v: i16x16): i16x16 {
+ const u = h4x4(v)
+ const r = u.swizzle([4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11])
+ return i16x16.select(i16x16(-1, -1, -1, -1, 0, 0, 0, 0, -1, -1, -1, -1, 0, 0, 0, 0), u + r, r - u)
+}
+
+function diff2(a: Uint8Array, ao: int, t: Uint8Array, pa: int, pb: int): i16x16 {
+ const s = i16x8.loadU8(a, ao)
+ return i16x16.concat(s, s) - i16x16.concat(i16x8.loadU8(t, pa), i16x8.loadU8(t, pb))
+}
+
+export function i8Cost2(costs: Int32Array, src: Uint8Array, so: int, ss: int, t: Uint8Array, ma: int, mb: int) {
+ const ka = ma * 8
+ const kb = mb * 8
+ const r0 = diff2(src, so, t, ROW8[ka]!, ROW8[kb]!)
+ const r1 = diff2(src, so + ss, t, ROW8[ka + 1]!, ROW8[kb + 1]!)
+ const r2 = diff2(src, so + 2 * ss, t, ROW8[ka + 2]!, ROW8[kb + 2]!)
+ const r3 = diff2(src, so + 3 * ss, t, ROW8[ka + 3]!, ROW8[kb + 3]!)
+ const r4 = diff2(src, so + 4 * ss, t, ROW8[ka + 4]!, ROW8[kb + 4]!)
+ const r5 = diff2(src, so + 5 * ss, t, ROW8[ka + 5]!, ROW8[kb + 5]!)
+ const r6 = diff2(src, so + 6 * ss, t, ROW8[ka + 6]!, ROW8[kb + 6]!)
+ const r7 = diff2(src, so + 7 * ss, t, ROW8[ka + 7]!, ROW8[kb + 7]!)
+ const s = sa8dMax2(r0, r1, r2, r3, r4, r5, r6, r7).addPairs()
+ const h = u32x4.hadd(s.low(), s.high())
+ const r = u32x4.hadd(h, h)
+ costs[ma] = (int(r.lane(0)) + 1) >> 1
+ costs[mb] = (int(r.lane(1)) + 1) >> 1
+}
+
+export function pred8v(dst: Uint8Array, dO: int, t: Uint8Array, mode: int) {
+ const k = mode * 8
+ for (let y = 0; y < 8; y += 2) {
+ u8x16.packSat(i16x8.loadU8(t, ROW8[k + y]!), i16x8.loadU8(t, ROW8[k + y + 1]!)).store(dst, dO + y * 8)
+ }
+}
+
+export function pred16v(dst: Uint8Array, dO: int, ds: int, p: Uint8Array, stride: int, x: int, y: int, mode: int, av: int) {
+ if (mode === I16_V) {
+ const v = u8x16.load(p, (y - 1) * stride + x)
+ for (let j = 0; j < 16; j++) v.store(dst, dO + j * ds)
+ return
+ }
+ if (mode === I16_H) {
+ for (let j = 0; j < 16; j++) u8x16.splat(p[(y + j) * stride + x - 1]!).store(dst, dO + j * ds)
+ return
+ }
+ if (mode === I16_DC) {
+ const top = (av & AV_TOP) !== 0
+ const left = (av & AV_LEFT) !== 0
+ let sum = 0
+ if (top) sum += u8x16.sad(u8x16.load(p, (y - 1) * stride + x), u8x16.splat(0))
+ if (left) {
+ for (let j = 0; j < 16; j++) sum += int(p[(y + j) * stride + x - 1]!)
+ }
+ let dc = 128
+ if (top && left) {
+ dc = (sum + 16) >> 5
+ } else if (top || left) {
+ dc = (sum + 8) >> 4
+ }
+ const v = u8x16.splat(dc)
+ for (let j = 0; j < 16; j++) v.store(dst, dO + j * ds)
+ return
+ }
+ const to = (y - 1) * stride + x
+ const hd = i16x8.loadU8(p, to + 8) - i16x8.loadU8(p, to - 1).swizzle([7, 6, 5, 4, 3, 2, 1, 0])
+ const hh = i16x8.madd(hd, i16x8(1, 2, 3, 4, 5, 6, 7, 8)).sum()
+ let vv = 0
+ for (let k = 0; k < 8; k++) {
+ vv += (k + 1) * (int(p[(y + 8 + k) * stride + x - 1]!) - int(p[(y + 6 - k) * stride + x - 1]!))
+ }
+ const a = 16 * (int(p[(y + 15) * stride + x - 1]!) + int(p[to + 15]!))
+ const b = (5 * hh + 32) >> 6
+ const c = (5 * vv + 32) >> 6
+ const bl = i16x8(-7, -6, -5, -4, -3, -2, -1, 0) * i16x8.splat(b)
+ const bh = i16x8(1, 2, 3, 4, 5, 6, 7, 8) * i16x8.splat(b)
+ for (let j = 0; j < 16; j++) {
+ const base = i16x8.splat(a + c * (j - 7) + 16)
+ u8x16.packSat((base + bl) >> 5, (base + bh) >> 5).store(dst, dO + j * ds)
+ }
+}
+
+function dcQuad(p: Uint8Array, stride: int, x: int, y: int, bx: int, by: int, top: bool, left: bool): int {
+ let st = 0
+ let sl = 0
+ if (top) {
+ const o = (y - 1) * stride + x + bx * 4
+ for (let i = 0; i < 4; i++) st += int(p[o + i]!)
+ }
+ if (left) {
+ for (let j = 0; j < 4; j++) sl += int(p[(y + by * 4 + j) * stride + x - 1]!)
+ }
+ if (bx === by) {
+ if (top && left) return (st + sl + 4) >> 3
+ if (left) return (sl + 2) >> 2
+ if (top) return (st + 2) >> 2
+ } else if (bx === 1) {
+ if (top) return (st + 2) >> 2
+ if (left) return (sl + 2) >> 2
+ } else {
+ if (left) return (sl + 2) >> 2
+ if (top) return (st + 2) >> 2
+ }
+ return 128
+}
+
+export function predChromaV(dst: Uint8Array, dO: int, ds: int, p: Uint8Array, stride: int, x: int, y: int, mode: int, av: int) {
+ const top = (av & AV_TOP) !== 0
+ const left = (av & AV_LEFT) !== 0
+ if (mode === C_V) {
+ const b = u8x16.loadLow(p, (y - 1) * stride + x)
+ for (let j = 0; j < 8; j++) b.storeLow(dst, dO + j * ds)
+ return
+ }
+ if (mode === C_H) {
+ for (let j = 0; j < 8; j++) u8x16.splat(p[(y + j) * stride + x - 1]!).storeLow(dst, dO + j * ds)
+ return
+ }
+ if (mode === C_DC) {
+ const d00 = dcQuad(p, stride, x, y, 0, 0, top, left)
+ const d10 = dcQuad(p, stride, x, y, 1, 0, top, left)
+ const d01 = dcQuad(p, stride, x, y, 0, 1, top, left)
+ const d11 = dcQuad(p, stride, x, y, 1, 1, top, left)
+ const r0 = i16x8(d00, d00, d00, d00, d10, d10, d10, d10)
+ const r1 = i16x8(d01, d01, d01, d01, d11, d11, d11, d11)
+ const b = u8x16.packSat(r0, r1)
+ for (let j = 0; j < 4; j++) b.storeLow(dst, dO + j * ds)
+ const c = b.swizzle([8, 9, 10, 11, 12, 13, 14, 15, 8, 9, 10, 11, 12, 13, 14, 15])
+ for (let j = 4; j < 8; j++) c.storeLow(dst, dO + j * ds)
+ return
+ }
+ const to = (y - 1) * stride + x
+ let hh = 0
+ let vv = 0
+ for (let k = 0; k < 4; k++) {
+ hh += (k + 1) * (int(p[to + 4 + k]!) - int(p[to + 2 - k]!))
+ vv += (k + 1) * (int(p[(y + 4 + k) * stride + x - 1]!) - int(p[(y + 2 - k) * stride + x - 1]!))
+ }
+ const a = 16 * (int(p[(y + 7) * stride + x - 1]!) + int(p[to + 7]!))
+ const b = (34 * hh + 32) >> 6
+ const c = (34 * vv + 32) >> 6
+ const bx = i16x8(-3, -2, -1, 0, 1, 2, 3, 4) * i16x8.splat(b)
+ for (let j = 0; j < 8; j++) {
+ const r = (i16x8.splat(a + c * (j - 3) + 16) + bx) >> 5
+ r.storeU8(dst, dO + j * ds)
+ }
+}
+
+export function i16Satd(costs: Int32Array, s: Uint8Array, so: int, ss: int, p: Uint8Array, stride: int, x: int, y: int, av: int) {
+ const top = (av & AV_TOP) !== 0
+ const left = (av & AV_LEFT) !== 0
+ const m0 = i16x16(-1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0)
+ const zero = i16x16.splat(0)
+ const to = (y - 1) * stride + x
+ let tv = zero
+ let sum = 0
+ if (top) {
+ tv = h4x4(i16x16.loadU8(p, to)) * i16x16.splat(4)
+ sum += u8x16.sad(u8x16.load(p, to), u8x16.splat(0))
+ }
+ if (left) {
+ for (let j = 0; j < 16; j++) sum += int(p[(y + j) * stride + x - 1]!)
+ }
+ let dc = 128
+ if (top && left) {
+ dc = (sum + 16) >> 5
+ } else if (top || left) {
+ dc = (sum + 8) >> 4
+ }
+ const dcv = i16x16.splat(16 * dc) & m0
+ let accV = u16x16.splat(0)
+ let accH = u16x16.splat(0)
+ let accD = u16x16.splat(0)
+ for (let by = 0; by < 16; by += 4) {
+ const o = so + by * ss
+ const r0 = i16x16.loadU8(s, o)
+ const r1 = i16x16.loadU8(s, o + ss)
+ const r2 = i16x16.loadU8(s, o + 2 * ss)
+ const r3 = i16x16.loadU8(s, o + 3 * ss)
+ const s01 = r0 + r1
+ const m01 = r0 - r1
+ const s23 = r2 + r3
+ const m23 = r2 - r3
+ const h0 = h4x4(s01 + s23)
+ const h1 = h4x4(s01 - s23)
+ const h2 = h4x4(m01 + m23)
+ const h3 = h4x4(m01 - m23)
+ const rest = h1.abs() + h2.abs() + h3.abs()
+ accD += u16x16.bitcast((h0 - dcv).abs() + rest)
+ if (top) accV += u16x16.bitcast((h0 - tv).abs() + rest)
+ if (left) {
+ const lo = (y + by) * stride + x - 1
+ const l0 = int(p[lo]!)
+ const l1 = int(p[lo + stride]!)
+ const l2 = int(p[lo + 2 * stride]!)
+ const l3 = int(p[lo + 3 * stride]!)
+ const e0 = i16x16.splat(4 * (l0 + l1 + l2 + l3)) & m0
+ const e1 = i16x16.splat(4 * (l0 + l1 - l2 - l3)) & m0
+ const e2 = i16x16.splat(4 * (l0 - l1 + l2 - l3)) & m0
+ const e3 = i16x16.splat(4 * (l0 - l1 - l2 + l3)) & m0
+ accH += u16x16.bitcast((h0 - e0).abs() + (h1 - e1).abs() + (h2 - e2).abs() + (h3 - e3).abs())
+ }
+ }
+ costs[I16_V] = accV.sum() >> 1
+ costs[I16_H] = accH.sum() >> 1
+ costs[I16_DC] = accD.sum() >> 1
+}
+
+export function i16PlaneSatd(s: Uint8Array, so: int, ss: int, p: Uint8Array, stride: int, x: int, y: int): int {
+ const zero = i16x16.splat(0)
+ const hi = i16x16.splat(255)
+ const to = (y - 1) * stride + x
+ const hd = i16x8.loadU8(p, to + 8) - i16x8.loadU8(p, to - 1).swizzle([7, 6, 5, 4, 3, 2, 1, 0])
+ const hh = i16x8.madd(hd, i16x8(1, 2, 3, 4, 5, 6, 7, 8)).sum()
+ let vv = 0
+ for (let k = 0; k < 8; k++) {
+ vv += (k + 1) * (int(p[(y + 8 + k) * stride + x - 1]!) - int(p[(y + 6 - k) * stride + x - 1]!))
+ }
+ const pa = 16 * (int(p[(y + 15) * stride + x - 1]!) + int(p[to + 15]!)) + 16
+ const pc = (5 * vv + 32) >> 6
+ const pb = i16x16(-7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8) * i16x16.splat((5 * hh + 32) >> 6)
+ let acc = u16x16.splat(0)
+ for (let by = 0; by < 16; by += 4) {
+ const o = so + by * ss
+ const base = pa + pc * (by - 7)
+ const d0 = i16x16.loadU8(s, o) - ((i16x16.splat(base) + pb) >> 5).max(zero).min(hi)
+ const d1 = i16x16.loadU8(s, o + ss) - ((i16x16.splat(base + pc) + pb) >> 5).max(zero).min(hi)
+ const d2 = i16x16.loadU8(s, o + 2 * ss) - ((i16x16.splat(base + 2 * pc) + pb) >> 5).max(zero).min(hi)
+ const d3 = i16x16.loadU8(s, o + 3 * ss) - ((i16x16.splat(base + 3 * pc) + pb) >> 5).max(zero).min(hi)
+ const t01 = d0 + d1
+ const u01 = d0 - d1
+ const t23 = d2 + d3
+ const u23 = d2 - d3
+ acc += u16x16.bitcast(h4x4(t01 + t23).abs() + h4x4(t01 - t23).abs() + h4x4(u01 + u23).abs() + h4x4(u01 - u23).abs())
+ }
+ return acc.sum() >> 1
+}
+
+export const UV_TOP = 128
+export const UV_LEFT = 144
+export const UV_DC = 160
+export const UV_SIZE = 176
+
+function dcQuads(st0: int, st1: int, sl0: int, sl1: int, top: bool, left: bool): int {
+ if (top && left) {
+ return ((st0 + sl0 + 4) >> 3) | (((st1 + 2) >> 2) << 8) | (((sl1 + 2) >> 2) << 16) | (((st1 + sl1 + 4) >> 3) << 24)
+ }
+ if (top) {
+ const d0 = (st0 + 2) >> 2
+ const d1 = (st1 + 2) >> 2
+ return d0 | (d1 << 8) | (d0 << 16) | (d1 << 24)
+ }
+ if (left) {
+ const d0 = (sl0 + 2) >> 2
+ const d1 = (sl1 + 2) >> 2
+ return d0 | (d0 << 8) | (d1 << 16) | (d1 << 24)
+ }
+ return 0x80808080
+}
+
+export function chromaSatd(costs: Int32Array, su: Uint8Array, sv: Uint8Array, so: int, ss: int, pu: Uint8Array, pv: Uint8Array, stride: int, x: int, y: int, av: int, uv: Uint8Array) {
+ const top = (av & AV_TOP) !== 0
+ const left = (av & AV_LEFT) !== 0
+ const m0 = i16x16(-1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0, -1, 0, 0, 0)
+ const zero = i16x16.splat(0)
+ // Exactly 8 bytes per row: on the rightmost macroblock a 16-byte load reaches into the next macroblock row's
+ // source, which another wavefront worker may be writing.
+ for (let j = 0; j < 8; j++) {
+ u8x16.packSat(i16x8.loadU8(su, so + j * ss), i16x8.loadU8(sv, so + j * ss)).store(uv, j * 16)
+ }
+ let tv = zero
+ let stU0 = 0
+ let stU1 = 0
+ let stV0 = 0
+ let stV1 = 0
+ if (top) {
+ const to = (y - 1) * stride + x
+ u8x16.shuffle(u8x16.load(pu, to), u8x16.load(pv, to), [0, 1, 2, 3, 4, 5, 6, 7, 16, 17, 18, 19, 20, 21, 22, 23]).store(uv, 128)
+ const ht = h4x4(i16x16.loadU8(uv, 128))
+ stU0 = ht.lane(0)
+ stU1 = ht.lane(4)
+ stV0 = ht.lane(8)
+ stV1 = ht.lane(12)
+ tv = ht * i16x16.splat(4)
+ }
+ let hl = zero
+ if (left) {
+ const lo = y * stride + x - 1
+ const lv = i16x16(
+ int(pu[lo]!), int(pu[lo + stride]!), int(pu[lo + 2 * stride]!), int(pu[lo + 3 * stride]!),
+ int(pu[lo + 4 * stride]!), int(pu[lo + 5 * stride]!), int(pu[lo + 6 * stride]!), int(pu[lo + 7 * stride]!),
+ int(pv[lo]!), int(pv[lo + stride]!), int(pv[lo + 2 * stride]!), int(pv[lo + 3 * stride]!),
+ int(pv[lo + 4 * stride]!), int(pv[lo + 5 * stride]!), int(pv[lo + 6 * stride]!), int(pv[lo + 7 * stride]!),
+ )
+ u8x16.packSat(lv.low(), lv.high()).store(uv, UV_LEFT)
+ hl = h4x4(lv)
+ }
+ const dU = dcQuads(stU0, stU1, hl.lane(0), hl.lane(4), top, left)
+ const dV = dcQuads(stV0, stV1, hl.lane(8), hl.lane(12), top, left)
+ u8x16.bitcast(i32x4(dU, dV, 0, 0)).store(uv, UV_DC)
+ const hl4 = hl * i16x16.splat(4)
+ let accV = u16x16.splat(0)
+ let accH = u16x16.splat(0)
+ let accD = u16x16.splat(0)
+ for (let g = 0; g < 2; g++) {
+ const r0 = i16x16.loadU8(uv, g * 64)
+ const r1 = i16x16.loadU8(uv, g * 64 + 16)
+ const r2 = i16x16.loadU8(uv, g * 64 + 32)
+ const r3 = i16x16.loadU8(uv, g * 64 + 48)
+ const s01 = r0 + r1
+ const m01 = r0 - r1
+ const s23 = r2 + r3
+ const m23 = r2 - r3
+ const h0 = h4x4(s01 + s23)
+ const h1 = h4x4(s01 - s23)
+ const h2 = h4x4(m01 + m23)
+ const h3 = h4x4(m01 - m23)
+ const rest = h1.abs() + h2.abs() + h3.abs()
+ const sh = g * 16
+ const dc = i16x16(
+ 16 * ((dU >> sh) & 255), 0, 0, 0, 16 * ((dU >> (sh + 8)) & 255), 0, 0, 0,
+ 16 * ((dV >> sh) & 255), 0, 0, 0, 16 * ((dV >> (sh + 8)) & 255), 0, 0, 0,
+ )
+ accD += u16x16.bitcast((h0 - dc).abs() + rest)
+ if (top) accV += u16x16.bitcast((h0 - tv).abs() + rest)
+ if (left) {
+ let e0 = zero
+ let e1 = zero
+ let e2 = zero
+ let e3 = zero
+ if (g === 0) {
+ e0 = hl4.swizzle([0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8]) & m0
+ e1 = hl4.swizzle([2, 2, 2, 2, 2, 2, 2, 2, 10, 10, 10, 10, 10, 10, 10, 10]) & m0
+ e2 = hl4.swizzle([1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9]) & m0
+ e3 = hl4.swizzle([3, 3, 3, 3, 3, 3, 3, 3, 11, 11, 11, 11, 11, 11, 11, 11]) & m0
+ } else {
+ e0 = hl4.swizzle([4, 4, 4, 4, 4, 4, 4, 4, 12, 12, 12, 12, 12, 12, 12, 12]) & m0
+ e1 = hl4.swizzle([6, 6, 6, 6, 6, 6, 6, 6, 14, 14, 14, 14, 14, 14, 14, 14]) & m0
+ e2 = hl4.swizzle([5, 5, 5, 5, 5, 5, 5, 5, 13, 13, 13, 13, 13, 13, 13, 13]) & m0
+ e3 = hl4.swizzle([7, 7, 7, 7, 7, 7, 7, 7, 15, 15, 15, 15, 15, 15, 15, 15]) & m0
+ }
+ accH += u16x16.bitcast((h0 - e0).abs() + (h1 - e1).abs() + (h2 - e2).abs() + (h3 - e3).abs())
+ }
+ }
+ const d = accD.addPairs()
+ const h = accH.addPairs()
+ const v = accV.addPairs()
+ const dv = d.low() + d.high()
+ const vv = v.low() + v.high()
+ const r = u32x4.hadd(u32x4.hadd(dv, h.low() + h.high()), u32x4.hadd(vv, vv))
+ costs[C_DC] = int(r.lane(0)) >> 1
+ costs[C_H] = int(r.lane(1)) >> 1
+ costs[C_V] = int(r.lane(2)) >> 1
+}
+
+const PLANE_REV = [0, 1, 2, 3, 2, 1, 0, 7, 8, 9, 10, 11, 10, 9, 8, 15]
+const PLANE_W = i16x16(0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 0, 1, 2, 3, 4)
+const PLANE_X = i16x16(-3, -2, -1, 0, 1, 2, 3, 4, -3, -2, -1, 0, 1, 2, 3, 4)
+
+// Both planes at once from the rows, edges and DC quads chromaSatd left in `uv` (U in the low 8 lanes, V in the
+// high 8). The plane's first row and its per-row step go to `pl` for predChromaUv; i16 lanes wrap as the scalar
+// definition's sums do when it splats them, so stepping a row at a time gives the same lanes.
+export function chromaPlaneSatd(uv: Uint8Array, pu: Uint8Array, pv: Uint8Array, stride: int, x: int, y: int, pl: Int16Array): int {
+ const tl = (y - 1) * stride + x - 1
+ const t = i16x16.loadU8(uv, UV_TOP)
+ const l = i16x16.loadU8(uv, UV_LEFT)
+ const cu = int(pu[tl]!)
+ const cv = int(pv[tl]!)
+ const dh = t - t.swizzle(PLANE_REV).withLane(7, cu).withLane(15, cv)
+ const dv = l - l.swizzle(PLANE_REV).withLane(7, cu).withLane(15, cv)
+ const hv = i32x8.hadd(i16x16.madd(dh, PLANE_W), i16x16.madd(dv, PLANE_W))
+ const bu = (34 * int(hv.lane(1)) + 32) >> 6
+ const bv = (34 * int(hv.lane(3)) + 32) >> 6
+ const ccu = (34 * int(hv.lane(5)) + 32) >> 6
+ const ccv = (34 * int(hv.lane(7)) + 32) >> 6
+ const rowU = 16 * (int(l.lane(7)) + int(t.lane(7))) + 16 - 3 * ccu
+ const rowV = 16 * (int(l.lane(15)) + int(t.lane(15))) + 16 - 3 * ccv
+ const c = i16x16.concat(i16x8.splat(ccu), i16x8.splat(ccv))
+ const p0 = i16x16.concat(i16x8.splat(rowU), i16x8.splat(rowV)) + PLANE_X * i16x16.concat(i16x8.splat(bu), i16x8.splat(bv))
+ p0.store(pl, 0)
+ c.store(pl, 16)
+ const zero = i16x16.splat(0)
+ const hi = i16x16.splat(255)
+ let p = p0
+ let acc = u16x16.splat(0)
+ for (let by = 0; by < 128; by += 64) {
+ const d0 = i16x16.loadU8(uv, by) - (p >> 5).max(zero).min(hi)
+ p += c
+ const d1 = i16x16.loadU8(uv, by + 16) - (p >> 5).max(zero).min(hi)
+ p += c
+ const d2 = i16x16.loadU8(uv, by + 32) - (p >> 5).max(zero).min(hi)
+ p += c
+ const d3 = i16x16.loadU8(uv, by + 48) - (p >> 5).max(zero).min(hi)
+ p += c
+ const t01 = d0 + d1
+ const u01 = d0 - d1
+ const t23 = d2 + d3
+ const u23 = d2 - d3
+ acc += u16x16.bitcast(h4x4(t01 + t23).abs() + h4x4(t01 - t23).abs() + h4x4(u01 + u23).abs() + h4x4(u01 - u23).abs())
+ }
+ return acc.sum() >> 1
+}
+
+// U's 8x8 prediction at dO and V's at dO + 64, from what chromaSatd (and, for the plane, chromaPlaneSatd) of the
+// same macroblock left in `uv` and `pl`.
+export function predChromaUv(dst: Uint8Array, dO: int, uv: Uint8Array, pl: Int16Array, mode: int) {
+ if (mode === C_DC) {
+ const d = u8x16.load(uv, UV_DC)
+ const ut = d.swizzle([0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1])
+ const ub = d.swizzle([2, 2, 2, 2, 3, 3, 3, 3, 2, 2, 2, 2, 3, 3, 3, 3])
+ const vt = d.swizzle([4, 4, 4, 4, 5, 5, 5, 5, 4, 4, 4, 4, 5, 5, 5, 5])
+ const vb = d.swizzle([6, 6, 6, 6, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7])
+ ut.store(dst, dO)
+ ut.store(dst, dO + 16)
+ ub.store(dst, dO + 32)
+ ub.store(dst, dO + 48)
+ vt.store(dst, dO + 64)
+ vt.store(dst, dO + 80)
+ vb.store(dst, dO + 96)
+ vb.store(dst, dO + 112)
+ return
+ }
+ if (mode === C_H) {
+ const l = u8x16.load(uv, UV_LEFT)
+ l.swizzle([0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1]).store(dst, dO)
+ l.swizzle([2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3]).store(dst, dO + 16)
+ l.swizzle([4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5]).store(dst, dO + 32)
+ l.swizzle([6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7]).store(dst, dO + 48)
+ l.swizzle([8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9]).store(dst, dO + 64)
+ l.swizzle([10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11]).store(dst, dO + 80)
+ l.swizzle([12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13]).store(dst, dO + 96)
+ l.swizzle([14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15]).store(dst, dO + 112)
+ return
+ }
+ if (mode === C_V) {
+ const t = u8x16.load(uv, UV_TOP)
+ const u = t.swizzle([0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7])
+ const v = t.swizzle([8, 9, 10, 11, 12, 13, 14, 15, 8, 9, 10, 11, 12, 13, 14, 15])
+ for (let k = 0; k < 64; k += 16) {
+ u.store(dst, dO + k)
+ v.store(dst, dO + 64 + k)
+ }
+ return
+ }
+ const c = i16x16.load(pl, 16)
+ let p = i16x16.load(pl, 0)
+ for (let k = 0; k < 64; k += 16) {
+ const r0 = p >> 5
+ p += c
+ const r1 = p >> 5
+ p += c
+ u8x16.packSat(r0.low(), r1.low()).store(dst, dO + k)
+ u8x16.packSat(r0.high(), r1.high()).store(dst, dO + 64 + k)
+ }
+}
+
+function pixels(seed: int, n: int): Uint8Array {
+ let out: u8[] = []
+ let x = seed
+ for (let i = 0; i < n; i++) {
+ x = (x * 1103515245 + 12345) & 0x7fffffff
+ const v = i % 9 === 0 ? 255 : i % 13 === 0 ? 0 : (x >> 9) & 255
+ out.push(u8(v))
+ }
+ return new Uint8Array(out)
+}
+
+function same(a: Uint8Array, ao: int, as: int, b: Uint8Array, bo: int, bs: int, n: int): int {
+ let bad = 0
+ for (let y = 0; y < n; y++) {
+ for (let x = 0; x < n; x++) {
+ if (a[ao + y * as + x]! !== b[bo + y * bs + x]!) bad++
+ }
+ }
+ return bad
+}
+
+function decide4(c: Int32Array, pm: int, bias: int, out: Int32Array) {
+ let bm = I4_V
+ let bc = c[I4_V]! - (pm === I4_V ? bias : 0)
+ for (let m = I4_H; m <= I4_DC; m++) {
+ const v = c[m]! - (pm === m ? bias : 0)
+ if (v < bc) {
+ bc = v
+ bm = m
+ }
+ }
+ if (bc > 0) {
+ for (let m = I4_DDL; m < 9; m++) {
+ const v = c[m]! - (pm === m ? bias : 0)
+ if (v < bc) {
+ bc = v
+ bm = m
+ }
+ }
+ } else if (pm > I4_DC && bc > -bias && c[pm]! - bias < bc) {
+ bc = c[pm]! - bias
+ bm = pm
+ }
+ out[0] = bm
+ out[1] = bc
+}
+
+const BIASES: int[] = [0, 1, 6, 24, 90, 400]
+
+function decideBad(costs: Int32Array, want: Int32Array, ref: Int32Array, blk: Uint8Array, bo: int, xb: Uint8Array, av: int, pb: Uint8Array, seed: int): int {
+ let bad = 0
+ for (let k = 0; k < 18; k++) {
+ const pm = (seed * 5 + av * 3 + k) % 9
+ const bias = BIASES[(seed + k) % BIASES.length]!
+ i4Costs(costs, blk, bo, xb, av, pb, pm, bias)
+ decide4(want, pm, bias, ref)
+ if (costs[I4_BEST_MODE]! !== ref[0]! || costs[I4_BEST_COST]! !== ref[1]!) bad++
+ }
+ return bad
+}
+
+test("vector intra predictions and mode costs match the scalar ones for every mode and neighbour availability", () => {
+ let bad = 0
+ const stride = 48
+ const e = new Int32Array(32)
+ const f = new Int32Array(32)
+ const xb = new Uint8Array(16)
+ const pb = new Uint8Array(144)
+ const t = new Uint8Array(T8_SIZE)
+ const a = new Uint8Array(256)
+ const b = new Uint8Array(256)
+ const costs = new Int32Array(16)
+ const want = new Int32Array(9)
+ const ref = new Int32Array(2)
+ const blk = new Uint8Array(256)
+ const uv = new Uint8Array(UV_SIZE)
+ const pl = new Int16Array(32)
+ const c2 = new Uint8Array(128)
+ for (let seed = 1; seed <= 120; seed++) {
+ const p = pixels(seed, stride * 40)
+ if (seed % 4 === 0) {
+ for (let i = 0; i < stride * 40; i++) p[i] = 100 + (int(p[i]!) & 7)
+ }
+ const src = pixels(seed * 7 + 3, stride * 40)
+ const x = 8 + (seed % 3) * 4
+ const y = 8 + (seed % 5)
+ for (let av = 0; av < 16; av++) {
+ gather4(e, p, stride, x, y, av)
+ edge4(xb, p, stride, x, y, av)
+ blocks4(blk, src, y * stride + x - (seed % 4) * 4, stride)
+ const bo = (seed % 4) * 16
+ i4Costs(costs, blk, bo, xb, av, pb, I4_HU, 1)
+ for (let m = 0; m < 9; m++) {
+ const got = costs[m]! + (m === I4_HU ? 1 : 0)
+ want[m] = COST_NA
+ if (!modeAvailable(m, av)) {
+ if (got !== COST_NA) bad++
+ continue
+ }
+ pred4(a, 0, 4, e, m, av)
+ pred4v(xb, m, av).store(b, 0)
+ bad += same(a, 0, 4, b, 0, 4, 4)
+ bad += same(a, 0, 4, pb, m * 16, 4, 4)
+ want[m] = satd4(src, y * stride + x, stride, a, 0, 4)
+ if (got !== want[m]!) bad++
+ }
+ bad += decideBad(costs, want, ref, blk, bo, xb, av, pb, seed)
+ i4Costs(costs, blk, bo, xb, av, pb, I4_DC, 0)
+ for (let m = 0; m <= I4_DC; m++) {
+ if (!modeAvailable(m, av)) continue
+ pred4(a, 0, 4, e, m, av)
+ if (costs[m]! !== satd4(src, y * stride + x, stride, a, 0, 4)) bad++
+ }
+ gather8(e, f, p, stride, x, y, av)
+ edge8m(t, p, stride, x, y, av, blk, 0)
+ i8SrcCosts(costs, src, y * stride + x, stride, t, av)
+ for (let m = 0; m < 9; m++) {
+ if (((modeMask(av) >> m) & 1) !== (modeAvailable(m, av) ? 1 : 0)) bad++
+ if (!modeAvailable(m, av)) continue
+ pred8(a, 0, 16, f, m, av)
+ pred8v(b, 3, t, m)
+ bad += same(a, 0, 16, b, 3, 8, 8)
+ const want = sa8d(src, y * stride + x, stride, a, 0, 16)
+ if (i8Cost(src, y * stride + x, stride, t, m) !== want) bad++
+ if (m <= I4_DC && costs[m]! !== want) bad++
+ }
+ for (let m = I4_DDL; m < I4_HU; m++) {
+ const n = m + 1 + (seed % (I4_HU - m))
+ if (!modeAvailable(m, av) || !modeAvailable(n, av)) continue
+ i8Cost2(costs, src, y * stride + x, stride, t, m, n)
+ if (costs[m]! !== i8Cost(src, y * stride + x, stride, t, m)) bad++
+ if (costs[n]! !== i8Cost(src, y * stride + x, stride, t, n)) bad++
+ }
+ i16Satd(costs, src, y * stride + x, stride, p, stride, x, y, av)
+ for (let m = 0; m < 4; m++) {
+ if (!mode16Available(m, av)) continue
+ pred16(a, 0, 16, p, stride, x, y, m, av)
+ pred16v(b, 0, 16, p, stride, x, y, m, av)
+ bad += same(a, 0, 16, b, 0, 16, 16)
+ const got = m === I16_PLANE ? i16PlaneSatd(src, y * stride + x, stride, p, stride, x, y) : costs[m]!
+ if (got !== satd16(src, y * stride + x, stride, a, 0, 16)) bad++
+ }
+ chromaSatd(costs, src, p, y * stride + x, stride, p, src, stride, x, y, av, uv)
+ for (let m = 0; m < 4; m++) {
+ if (!chromaModeAvailable(m, av)) continue
+ predChroma(a, 0, 8, p, stride, x, y, m, av)
+ predChromaV(b, 0, 8, p, stride, x, y, m, av)
+ bad += same(a, 0, 8, b, 0, 8, 8)
+ predChroma(b, 0, 8, src, stride, x, y, m, av)
+ const want = satd8(src, y * stride + x, stride, a, 0, 8) + satd8(p, y * stride + x, stride, b, 0, 8)
+ const got = m === C_PLANE ? chromaPlaneSatd(uv, p, src, stride, x, y, pl) : costs[m]!
+ if (got !== want) bad++
+ predChromaUv(c2, 0, uv, pl, m)
+ bad += same(a, 0, 8, c2, 0, 8, 8) + same(b, 0, 8, c2, 64, 8, 8)
+ }
+ }
+ }
+ expect(bad).toBe(0)
+})
+
+test("I4 mode costs match satd4 of the prediction on extreme 0/255 blocks and edges", () => {
+ let bad = 0
+ const stride = 32
+ const e = new Int32Array(32)
+ const xb = new Uint8Array(16)
+ const pb = new Uint8Array(144)
+ const a = new Uint8Array(16)
+ const costs = new Int32Array(16)
+ const want = new Int32Array(9)
+ const ref = new Int32Array(2)
+ for (let pat = 0; pat < 1024; pat++) {
+ const p = new Uint8Array(stride * 16)
+ const src = new Uint8Array(16)
+ for (let i = 0; i < stride * 16; i++) p[i] = ((pat >> 8) & 1) * 255
+ for (let i = 0; i < 16; i++) {
+ const on = ((pat >> (i & 7)) & 1) !== 0 ? (i & 1) === 0 : ((i >> 2) & 1) === 0
+ const v: int = (pat & 512) !== 0 ? (on ? 255 : 0) : on ? 0 : 255
+ src[i] = v
+ }
+ for (let k = 0; k < 13; k++) {
+ const v: int = ((pat >> (k % 10)) & 1) !== 0 ? 0 : 255
+ if (k < 9) p[7 * stride + 7 + k] = v
+ else p[(8 + k - 9) * stride + 7] = v
+ }
+ for (let av = 0; av < 16; av++) {
+ gather4(e, p, stride, 8, 8, av)
+ edge4(xb, p, stride, 8, 8, av)
+ i4Costs(costs, src, 0, xb, av, pb, I4_HU, 1)
+ for (let m = 0; m < 9; m++) {
+ want[m] = COST_NA
+ if (!modeAvailable(m, av)) continue
+ pred4(a, 0, 4, e, m, av)
+ want[m] = satd4(src, 0, 4, a, 0, 4)
+ if (costs[m]! + (m === I4_HU ? 1 : 0) !== want[m]!) bad++
+ }
+ bad += decideBad(costs, want, ref, src, 0, xb, av, pb, pat)
+ }
+ }
+ expect(bad).toBe(0)
+})
+
+test("I8 mode costs match sa8d of the prediction on extreme 0/255 blocks and edges", () => {
+ let bad = 0
+ const stride = 48
+ const e = new Int32Array(32)
+ const f = new Int32Array(32)
+ const t = new Uint8Array(T8_SIZE)
+ const a = new Uint8Array(256)
+ const blk = new Uint8Array(256)
+ const costs = new Int32Array(9)
+ const so = 8 * stride + 8
+ for (let pat = 0; pat < 48; pat++) {
+ const p = new Uint8Array(stride * 40)
+ const src = new Uint8Array(stride * 40)
+ for (let y = 0; y < 40; y++) {
+ for (let x = 0; x < stride; x++) {
+ const hx = ((x >> (pat & 1)) ^ (x >> ((pat >> 1) & 1))) & 1
+ const hy = ((y >> ((pat >> 2) & 1)) ^ (y >> ((pat >> 3) & 1))) & 1
+ const on = (pat & 16) !== 0 ? (hx ^ hy) === 0 : (pat & 32) !== 0 ? hy === 0 || hx === 0 : hx === 0
+ const v: int = pat >= 40 ? (pat & 1) * 255 : on ? 255 : 0
+ const k = (pat >> 1) % 3
+ const q: int = k === 0 ? 255 - v : k === 1 ? 0 : 255
+ src[y * stride + x] = v
+ p[y * stride + x] = q
+ }
+ }
+ for (let av = 0; av < 16; av++) {
+ gather8(e, f, p, stride, 8, 8, av)
+ edge8m(t, p, stride, 8, 8, av, blk, 0)
+ i8SrcCosts(costs, src, so, stride, t, av)
+ for (let m = 0; m < 9; m++) {
+ if (!modeAvailable(m, av)) continue
+ pred8(a, 0, 16, f, m, av)
+ const want = sa8d(src, so, stride, a, 0, 16)
+ if (m <= I4_DC && costs[m]! !== want) bad++
+ if (i8Cost(src, so, stride, t, m) !== want) bad++
+ if (m < I4_DDL) continue
+ for (let n = I4_DDL; n < 9; n++) {
+ if (n === m || !modeAvailable(n, av)) continue
+ i8Cost2(costs, src, so, stride, t, m, n)
+ if (costs[m]! !== want) bad++
+ }
+ }
+ }
+ }
+ expect(bad).toBe(0)
+})
+
+test("I4 edges from the block-major macroblock scratch match those from the picture, and unblocks4 restores it", () => {
+ let bad = 0
+ const stride = 64
+ const xb = new Uint8Array(16)
+ const xm = new Uint8Array(16)
+ const rb = new Uint8Array(256)
+ for (let seed = 1; seed <= 40; seed++) {
+ const p = pixels(seed * 13 + 5, stride * 48)
+ const q = pixels(seed * 29 + 1, stride * 48)
+ const mx = 16 + (seed % 3) * 8
+ const my = 16 + (seed % 2) * 8
+ blocks4(rb, p, my * stride + mx, stride)
+ for (let i = 0; i < stride * 48; i++) {
+ const inside = i % stride >= mx && i % stride < mx + 16 && i >= my * stride && i < (my + 16) * stride
+ if (!inside) q[i] = p[i]!
+ }
+ for (let r = 0; r < 16; r++) {
+ const bx = r & 3
+ const by = r >> 2
+ for (let av = 0; av < 16; av++) {
+ if (bx > 0 && (av & AV_LEFT) === 0) continue
+ if (by > 0 && (av & AV_TOP) === 0) continue
+ if (by > 0 && bx === 3 && (av & AV_TR) !== 0) continue
+ edge4(xb, p, stride, mx + bx * 4, my + by * 4, av)
+ edge4m(xm, q, stride, mx + bx * 4, my + by * 4, av, rb, r)
+ for (let m = 0; m < 9; m++) {
+ if (modeAvailable(m, av) && pred4v(xb, m, av) !== pred4v(xm, m, av)) bad++
+ }
+ }
+ }
+ unblocks4(q, my * stride + mx, stride, rb)
+ for (let i = 0; i < stride * 48; i++) {
+ if (q[i]! !== p[i]!) bad++
+ }
+ }
+ expect(bad).toBe(0)
+})
+
+test("I8 predictions from edges in the block-major macroblock scratch match the picture's, and unblocks8 restores it", () => {
+ let bad = 0
+ const stride = 64
+ const e = new Int32Array(32)
+ const f = new Int32Array(32)
+ const t = new Uint8Array(T8_SIZE)
+ const a = new Uint8Array(64)
+ const b = new Uint8Array(64)
+ const rb = new Uint8Array(256)
+ for (let seed = 1; seed <= 40; seed++) {
+ const p = pixels(seed * 17 + 3, stride * 48)
+ const q = pixels(seed * 31 + 7, stride * 48)
+ const mx = 16 + (seed % 3) * 8
+ const my = 16 + (seed % 2) * 8
+ for (let i = 0; i < 256; i++) {
+ const bk = i >> 6
+ const j = i & 15
+ const row = (bk >> 1) * 8 + ((i >> 4) & 3) * 2 + (j >> 3)
+ rb[i] = p[(my + row) * stride + mx + (bk & 1) * 8 + (j & 7)]!
+ }
+ for (let i = 0; i < stride * 48; i++) {
+ const inside = i % stride >= mx && i % stride < mx + 16 && i >= my * stride && i < (my + 16) * stride
+ if (!inside) q[i] = p[i]!
+ }
+ for (let b8 = 0; b8 < 4; b8++) {
+ const bx = b8 & 1
+ const by = b8 >> 1
+ for (let av = 0; av < 16; av++) {
+ if (bx > 0 && (av & AV_LEFT) === 0) continue
+ if (by > 0 && (av & AV_TOP) === 0) continue
+ if (b8 === 3 && (av & AV_TR) !== 0) continue
+ gather8(e, f, p, stride, mx + bx * 8, my + by * 8, av)
+ edge8m(t, q, stride, mx + bx * 8, my + by * 8, av, rb, b8)
+ for (let m = 0; m < 9; m++) {
+ if (!modeAvailable(m, av)) continue
+ pred8(a, 0, 8, f, m, av)
+ pred8v(b, 0, t, m)
+ bad += same(a, 0, 8, b, 0, 8, 8)
+ }
+ }
+ }
+ unblocks8(q, my * stride + mx, stride, rb)
+ for (let i = 0; i < stride * 48; i++) {
+ if (q[i]! !== p[i]!) bad++
+ }
+ }
+ expect(bad).toBe(0)
+})
diff --git a/capcodec/src/lookahead.tov b/capcodec/src/lookahead.tov
new file mode 100644
index 000000000..a2ae4dcad
--- /dev/null
+++ b/capcodec/src/lookahead.tov
@@ -0,0 +1,566 @@
+import { SideInfo, changeMap, markRects } from "./analysis"
+
+export const LIFE_ONE = 16
+export const KEEP_ONE = 64
+const INTRA_BIAS = 32
+const TAIL_POW = 12.0
+const BIG = 1 << 30
+
+export type LookaheadState = {
+ changed: Uint8Array, intra: Int32Array, keep: Uint8Array, refX: Int16Array, refY: Int16Array, coded: Int32Array,
+ nCoded: Int32Array, mvx: Int32Array, mvy: Int32Array, mvAt: Int32Array, carry: Float64Array, until: Int32Array,
+ seen: Int32Array, amount: Float64Array, epoch: Int32Array, video: Uint8Array, maps: Uint8Array, mapAt: Int32Array,
+}
+
+export class Lookahead {
+ readonly w: int
+ readonly h: int
+ readonly mbw: int
+ readonly mbh: int
+ readonly slots: int
+ readonly mapSlots: int
+ noise = 0
+ geometricTail = false
+ windowTail = false
+ pushed = 0
+ taken = 0
+ total = -1
+ changed: Uint8Array
+ intra: Int32Array
+ keep: Uint8Array
+ refX: Int16Array
+ refY: Int16Array
+ coded: Int32Array
+ nCoded: Int32Array
+ mvx: Int32Array
+ mvy: Int32Array
+ mvAt: Int32Array
+ carry: Float64Array
+ until: Int32Array
+ seen: Int32Array
+ amount: Float64Array
+ epoch: Int32Array
+ video: Uint8Array
+ maps: Uint8Array
+ mapAt: Int32Array
+ life: Int32Array
+ tailW: Float64Array = new Float64Array(KEEP_ONE + 1)
+ geoW: Float64Array = new Float64Array(KEEP_ONE + 1)
+ scX0 = 0
+ scY0 = 0
+ scX1 = 0
+ scY1 = 0
+ scDx = 0
+ scDy = 0
+
+ constructor(w: int, h: int, depth: int, worker: bool) {
+ this.w = w
+ this.h = h
+ this.mbw = (w + 15) >> 4
+ this.mbh = (h + 15) >> 4
+ this.slots = depth + 1
+ this.mapSlots = depth + 2
+ const mbs = worker ? 0 : this.mbw * this.mbh
+ const slotMbs = worker ? 0 : mbs * this.slots
+ this.changed = new Uint8Array(mbs)
+ this.intra = new Int32Array(slotMbs)
+ this.keep = new Uint8Array(slotMbs)
+ this.refX = new Int16Array(slotMbs)
+ this.refY = new Int16Array(slotMbs)
+ this.coded = new Int32Array(slotMbs)
+ this.nCoded = new Int32Array(worker ? 0 : this.slots)
+ this.mvx = new Int32Array(mbs)
+ this.mvy = new Int32Array(mbs)
+ this.mvAt = new Int32Array(mbs)
+ this.carry = new Float64Array(mbs)
+ this.until = new Int32Array(mbs)
+ this.seen = new Int32Array(mbs)
+ this.amount = new Float64Array(mbs)
+ this.epoch = new Int32Array(worker ? 0 : 1)
+ this.video = new Uint8Array(worker ? 0 : this.slots)
+ this.maps = new Uint8Array(mbs * this.mapSlots)
+ this.mapAt = new Int32Array(worker ? 0 : this.mapSlots)
+ this.mapAt.fill(-1)
+ this.life = new Int32Array(mbs)
+ for (let k = 0; k <= KEEP_ONE; k++) this.tailW[k] = Math.pow(f64(k) / f64(KEEP_ONE), TAIL_POW)
+ }
+
+ share(): LookaheadState {
+ return {
+ changed: this.changed, intra: this.intra, keep: this.keep, refX: this.refX, refY: this.refY, coded: this.coded,
+ nCoded: this.nCoded, mvx: this.mvx, mvy: this.mvy, mvAt: this.mvAt, carry: this.carry, until: this.until,
+ seen: this.seen, amount: this.amount, epoch: this.epoch, video: this.video, maps: this.maps, mapAt: this.mapAt,
+ }
+ }
+
+ attach(st: LookaheadState, pushed: int, noise: int, geometricTail: bool, windowTail: bool) {
+ this.changed = st.changed
+ this.intra = st.intra
+ this.keep = st.keep
+ this.refX = st.refX
+ this.refY = st.refY
+ this.coded = st.coded
+ this.nCoded = st.nCoded
+ this.mvx = st.mvx
+ this.mvy = st.mvy
+ this.mvAt = st.mvAt
+ this.carry = st.carry
+ this.until = st.until
+ this.seen = st.seen
+ this.amount = st.amount
+ this.epoch = st.epoch
+ this.video = st.video
+ this.maps = st.maps
+ this.mapAt = st.mapAt
+ this.pushed = pushed
+ this.noise = noise
+ this.geometricTail = geometricTail
+ this.windowTail = windowTail
+ }
+
+ push(frame: Uint8Array, off: int, prevOff: int, side: SideInfo | undefined) {
+ const mbs = this.mbw * this.mbh
+ const slot = this.pushed % this.slots
+ const ko = slot * mbs
+ if (this.pushed === 0) {
+ for (let mb = 0; mb < mbs; mb++) this.intra[ko + mb] = this.intraOf(frame, off, (mb % this.mbw) * 16, Math.trunc(mb / this.mbw) * 16)
+ this.nCoded[slot] = 0
+ this.pushed++
+ return
+ }
+ let rowLo = 0
+ let rowHi = this.mbh - 1
+ const sided = side !== undefined
+ let changed = this.changed
+ if (side !== undefined) {
+ rowLo = this.mbh
+ rowHi = -1
+ for (let i = 0; i + 3 < side.dirty.length; i += 4) {
+ if (side.dirty[i + 2]! <= 0 || side.dirty[i + 3]! <= 0) continue
+ const y0 = side.dirty[i + 1]! >> 4
+ const y1 = (side.dirty[i + 1]! + side.dirty[i + 3]! - 1) >> 4
+ if (y0 < rowLo) rowLo = y0
+ if (y1 > rowHi) rowHi = y1
+ }
+ for (const sc of side.scroll) {
+ if (sc.w <= 0 || sc.h <= 0) continue
+ if (sc.y >> 4 < rowLo) rowLo = sc.y >> 4
+ if ((sc.y + sc.h - 1) >> 4 > rowHi) rowHi = (sc.y + sc.h - 1) >> 4
+ }
+ if (rowLo < 0) rowLo = 0
+ if (rowHi >= this.mbh) rowHi = this.mbh - 1
+ markRects(this.changed, this.mbw, this.mbh, side.dirty)
+ for (const sc of side.scroll) markRects(this.changed, this.mbw, this.mbh, [sc.x, sc.y, sc.w, sc.h])
+ this.mapAt[this.pushed % this.mapSlots] = -1
+ } else {
+ changed = this.diffFrames(frame, off, prevOff)
+ }
+ this.scDx = 0
+ this.scDy = 0
+ if (side !== undefined && side.scroll.length > 0) {
+ const sc = side.scroll[0]!
+ this.scDx = sc.dx
+ this.scDy = sc.dy
+ this.scX0 = sc.x
+ this.scY0 = sc.y
+ this.scX1 = sc.x + sc.w
+ this.scY1 = sc.y + sc.h
+ }
+ const po = ((this.pushed - 1) % this.slots) * mbs
+ this.intra.set(this.intra.subarray(po, po + mbs), ko)
+ if (this.geometricTail) {
+ let cnt = 0
+ for (let mb = rowLo * this.mbw; mb < (rowHi + 1) * this.mbw; mb++) {
+ if (changed[mb]! === 1) cnt++
+ }
+ this.video[slot] = cnt * 2 >= mbs ? 1 : 0
+ }
+ let n = 0
+ for (let mby = rowLo; mby <= rowHi; mby++) {
+ for (let mbx = 0; mbx < this.mbw; mbx++) {
+ const mb = mby * this.mbw + mbx
+ if (changed[mb]! !== 1) continue
+ if (sided) this.changed[mb] = 0
+ const k = this.keepOf(frame, off, prevOff, mb, mbx * 16, mby * 16, ko + mb)
+ if (k === KEEP_ONE && this.mvx[mb]! === 0 && this.mvy[mb]! === 0) continue
+ this.keep[ko + mb] = k
+ this.refX[ko + mb] = mbx * 16 + this.mvx[mb]!
+ this.refY[ko + mb] = mby * 16 + this.mvy[mb]!
+ this.coded[ko + n] = mb
+ n++
+ }
+ }
+ this.nCoded[slot] = n
+ this.pushed++
+ }
+
+ intraOf(frame: Uint8Array, off: int, px: int, py: int): int {
+ const w = this.w
+ if (px + 16 > w) return INTRA_BIAS
+ const bh = py + 16 <= this.h ? 16 : this.h - py
+ const rows = (bh + 1) >> 1
+ const w2 = w * 2
+ const o = off + py * w + px
+ let acc = u32x4.splat(0)
+ for (let y = 0; y < rows; y++) acc = acc + u8x16.sadParts(u8x16.load(frame, o + y * w2), u8x16.splat(0))
+ const sum = acc.sum()
+ const mean = rows === 8 ? (sum + 64) >> 7 : Math.trunc((sum + rows * 8) / (rows * 16))
+ const m = u8x16.splat(mean)
+ let dev = u32x4.splat(0)
+ for (let y = 0; y < rows; y++) dev = dev + u8x16.sadParts(u8x16.load(frame, o + y * w2), m)
+ return INTRA_BIAS + dev.sum()
+ }
+
+ rowsSad(frame: Uint8Array, o: int, r: int, rows: int): int {
+ const w2 = this.w * 2
+ let acc = u32x4.splat(0)
+ for (let y = 0; y < rows; y++) acc = acc + u8x16.sadParts(u8x16.load(frame, o + y * w2), u8x16.load(frame, r + y * w2))
+ return acc.sum()
+ }
+
+ candCost(frame: Uint8Array, o: int, prevOff: int, px: int, py: int, bh: int, dx: int, dy: int): int {
+ const qx = px + dx
+ const qy = py + dy
+ if (qx < 0 || qy < 0 || qx + 16 > this.w || qy + bh > this.h) return BIG
+ return this.rowsSad(frame, o, prevOff + qy * this.w + qx, (bh + 1) >> 1)
+ }
+
+ keepOf(frame: Uint8Array, off: int, prevOff: int, mb: int, px: int, py: int, io: int): int {
+ const w = this.w
+ const intra = this.intraOf(frame, off, px, py)
+ this.intra[io] = intra
+ if (px + 16 > w) {
+ this.mvx[mb] = 0
+ this.mvy[mb] = 0
+ return 0
+ }
+ const bh = py + 16 <= this.h ? 16 : this.h - py
+ const o = off + py * w + px
+ let bx = 0
+ let by = 0
+ let best = this.candCost(frame, o, prevOff, px, py, bh, 0, 0)
+ if ((this.scDx !== 0 || this.scDy !== 0) && px >= this.scX0 && py >= this.scY0 && px + 16 <= this.scX1 &&
+ py + bh <= this.scY1) {
+ const c = this.candCost(frame, o, prevOff, px, py, bh, -this.scDx, -this.scDy)
+ if (c < best) {
+ best = c
+ bx = -this.scDx
+ by = -this.scDy
+ }
+ }
+ if (best * 8 > intra - INTRA_BIAS) {
+ for (let k = 0; k < 3; k++) {
+ const n = k === 0 ? (px > 0 ? mb - 1 : -1) : k === 1 ? (py > 0 ? mb - this.mbw : -1) : mb
+ if (n < 0) continue
+ const at = k === 2 ? this.pushed - 1 : this.pushed
+ const cx = this.mvAt[n]! === at ? this.mvx[n]! : 0
+ const cy = this.mvAt[n]! === at ? this.mvy[n]! : 0
+ if (cx === bx && cy === by) continue
+ const c = this.candCost(frame, o, prevOff, px, py, bh, cx, cy)
+ if (c < best) {
+ best = c
+ bx = cx
+ by = cy
+ }
+ }
+ for (let step = 2; step >= 1; step--) {
+ for (let it = 0; it < 2; it++) {
+ let nx = bx
+ let ny = by
+ let c = this.candCost(frame, o, prevOff, px, py, bh, bx + step, by)
+ if (c < best) {
+ best = c
+ nx = bx + step
+ ny = by
+ }
+ c = this.candCost(frame, o, prevOff, px, py, bh, bx - step, by)
+ if (c < best) {
+ best = c
+ nx = bx - step
+ ny = by
+ }
+ c = this.candCost(frame, o, prevOff, px, py, bh, bx, by + step)
+ if (c < best) {
+ best = c
+ nx = bx
+ ny = by + step
+ }
+ c = this.candCost(frame, o, prevOff, px, py, bh, bx, by - step)
+ if (c < best) {
+ best = c
+ nx = bx
+ ny = by - step
+ }
+ if (nx === bx && ny === by) break
+ bx = nx
+ by = ny
+ }
+ }
+ }
+ this.mvx[mb] = bx
+ this.mvy[mb] = by
+ this.mvAt[mb] = this.pushed
+ if (best === 0) return KEEP_ONE
+ const k = KEEP_ONE - Math.trunc(KEEP_ONE * (best + INTRA_BIAS) / intra)
+ return k < 0 ? 0 : k
+ }
+
+ diffFrames(frame: Uint8Array, off: int, prevOff: int): Uint8Array {
+ const w = this.w
+ const h = this.h
+ const cw = w >> 1
+ const uo = w * h
+ const vo = uo + cw * (h >> 1)
+ const mbs = this.mbw * this.mbh
+ const slot = this.pushed % this.mapSlots
+ const map = this.maps.subarray(slot * mbs, (slot + 1) * mbs)
+ map.fill(0)
+ changeMap(frame, prevOff, w, frame, prevOff + uo, frame, prevOff + vo, cw, frame, off, w, off + uo, off + vo, cw, w, h,
+ this.noise, map)
+ this.mapAt[slot] = this.pushed
+ return map
+ }
+
+ changesOf(index: int): Uint8Array {
+ const slot = index % this.mapSlots
+ if (index < 0 || this.mapAt[slot]! !== index) return new Uint8Array(0)
+ const mbs = this.mbw * this.mbh
+ return this.maps.subarray(slot * mbs, (slot + 1) * mbs)
+ }
+
+ finish() {
+ this.total = this.pushed
+ }
+
+ take(horizon: int): Int32Array {
+ return this.takeInto(horizon, this.life)
+ }
+
+ takeAhead(target: int, horizon: int, life: Int32Array, keep: Uint8Array) {
+ this.taken = target
+ this.takeInto(horizon, life)
+ if (keep.length > 0) this.keepMap(keep)
+ }
+
+ takeInto(horizon: int, life: Int32Array): Int32Array {
+ const mbs = this.mbw * this.mbh
+ const mbw = this.mbw
+ const mbh = this.mbh
+ const slots = this.slots
+ const t = this.taken
+ let lim = t + horizon
+ if (this.total >= 0 && this.total < lim) lim = this.total
+ const last = lim < this.pushed ? lim - 1 : this.pushed - 1
+ const carry = this.carry
+ const until = this.until
+ const seen = this.seen
+ const amount = this.amount
+ const geoW = this.geoW
+ const tag = this.epoch[0]! + 1
+ this.epoch[0] = tag
+ for (let j = last; j > t; j--) {
+ const jo = (j % slots) * mbs
+ const n = this.nCoded[j % slots]!
+ const video = this.video[j % slots]! !== 0
+ if (video && !this.windowTail) {
+ const rest = f64(lim - 1 - j)
+ for (let k = 0; k < KEEP_ONE; k++) {
+ const q = f64(k) / f64(KEEP_ONE)
+ geoW[k] = q * (1.0 - Math.pow(q, rest)) / (1.0 - q)
+ }
+ geoW[KEEP_ONE] = rest * this.tailW[KEEP_ONE]!
+ }
+ for (let i = 0; i < n; i++) {
+ const mb = this.coded[jo + i]!
+ const ib = f64(this.intra[jo + mb]!)
+ const live = seen[mb]! === tag
+ const c = live ? carry[mb]! : 0.0
+ const end = live ? until[mb]! : lim - 1
+ const k = int(this.keep[jo + mb]!)
+ const tail = live ? f64(end - j) : video ? (this.windowTail ? f64(last - j) : geoW[k]!) :
+ f64(end - j) * this.tailW[k]!
+ amount[i] = (ib + c + ib * tail) * f64(k) / f64(KEEP_ONE)
+ carry[mb] = 0
+ until[mb] = j - 1
+ seen[mb] = tag
+ }
+ for (let i = 0; i < n; i++) {
+ const a = amount[i]!
+ if (a === 0) continue
+ const mb = this.coded[jo + i]!
+ const x0 = int(this.refX[jo + mb]!)
+ const y0 = int(this.refY[jo + mb]!)
+ const bx = x0 >> 4
+ const by = y0 >> 4
+ const fx = x0 & 15
+ const fy = y0 & 15
+ for (let q = 0; q < 4; q++) {
+ const cx = bx + (q & 1)
+ const cy = by + (q >> 1)
+ const wx = (q & 1) === 0 ? 16 - fx : fx
+ const wy = (q >> 1) === 0 ? 16 - fy : fy
+ if (wx === 0 || wy === 0 || cx >= mbw || cy >= mbh) continue
+ const r = cy * mbw + cx
+ if (seen[r]! !== tag) {
+ seen[r] = tag
+ carry[r] = 0
+ until[r] = lim - 1
+ }
+ carry[r] = carry[r]! + a * f64(wx * wy) / 256.0
+ }
+ }
+ }
+ const to = (t % slots) * mbs
+ const whole = (lim - t) * LIFE_ONE
+ for (let mb = 0; mb < mbs; mb++) {
+ if (seen[mb]! !== tag) {
+ life[mb] = whole
+ continue
+ }
+ const span = until[mb]! - t + 1
+ const c = carry[mb]!
+ life[mb] = c === 0 ? span * LIFE_ONE : Math.trunc(f64(LIFE_ONE) * (f64(span) + c / f64(this.intra[to + mb]!)))
+ }
+ this.taken++
+ return life
+ }
+
+ keepMap(out: Uint8Array) {
+ const mbs = this.mbw * this.mbh
+ const t = this.taken - 1
+ const to = (t % this.slots) * mbs
+ out.fill(KEEP_ONE)
+ const n = this.nCoded[t % this.slots]!
+ for (let i = 0; i < n; i++) {
+ const mb = this.coded[to + i]!
+ out[mb] = this.keep[to + mb]!
+ }
+ }
+}
+
+test("lifetimes end where content is replaced", () => {
+ const w = 32
+ const fb = (w * 16 * 3) >> 1
+ const frames = new Uint8Array(fb * 4)
+ const vals = [10, 10, 10, 90, 50, 90, 50, 90]
+ for (let f = 0; f < 4; f++) {
+ for (let y = 0; y < 16; y++) {
+ for (let x = 0; x < w; x++) frames[f * fb + y * w + x] = vals[f * 2 + (x >> 4)]!
+ }
+ }
+ const la = new Lookahead(w, 16, 3, false)
+ for (let f = 0; f < 4; f++) la.push(frames, f * fb, f > 0 ? (f - 1) * fb : 0, undefined)
+ const seen: int[] = []
+ const l = la.take(60)
+ seen.push(l[0]!)
+ seen.push(l[1]!)
+ la.finish()
+ for (let f = 1; f < 4; f++) {
+ const m = la.take(60)
+ seen.push(m[0]!)
+ seen.push(m[1]!)
+ }
+ expect(seen.join(",")).toBe([32, 16, 16, 48, 32, 32, 16, 16].join(","))
+})
+
+test("unchanged content is assumed to stay until the horizon past the window", () => {
+ const w = 32
+ const fb = (w * 16 * 3) >> 1
+ const frames = new Uint8Array(fb * 2)
+ for (let y = 0; y < 16; y++) frames.fill(200, fb + y * w + 16, fb + y * w + 32)
+ const la = new Lookahead(w, 16, 1, false)
+ la.push(frames, 0, 0, undefined)
+ la.push(frames, fb, 0, undefined)
+ const l = la.take(30)
+ expect([l[0]!, l[1]!].join(",")).toBe([30 * 16, 16].join(","))
+})
+
+test("moved content passes its lifetime back to where it came from", () => {
+ const w = 48
+ const fb = (w * 16 * 3) >> 1
+ const frames = new Uint8Array(fb * 4)
+ for (let f = 0; f < 4; f++) {
+ const x0 = f === 0 ? 0 : 16
+ for (let y = 0; y < 16; y++) {
+ for (let x = 0; x < 16; x++) frames[f * fb + y * w + x0 + x] = (x * 29 + y * 47 + x * y * 3) & 255
+ }
+ }
+ const moved = new SideInfo()
+ moved.dirty = [0, 0, 32, 16]
+ moved.scroll = [{ x: 0, y: 0, w: 48, h: 16, dx: 16, dy: 0 }]
+ const la = new Lookahead(w, 16, 3, false)
+ for (let f = 0; f < 4; f++) la.push(frames, f * fb, f > 0 ? (f - 1) * fb : 0, f === 1 ? moved : new SideInfo())
+ la.finish()
+ const l = la.take(60)
+ expect([l[0]!, l[1]!, l[2]!].join(",")).toBe("64,16,64")
+})
+
+test("the geometric tail applies only past frames where most macroblocks change", () => {
+ const w = 48
+ const fb = (w * 16 * 3) >> 1
+ const lives: int[][] = []
+ for (let moving = 1; moving <= 3; moving += 2) {
+ const frames = new Uint8Array(fb * 2)
+ for (let y = 0; y < 16; y++) {
+ for (let x = 0; x < w; x++) {
+ const v = (x * 29 + y * 47 + x * y * 3) & 255
+ frames[y * w + x] = v
+ frames[fb + y * w + x] = x < moving * 16 && (x & 1) === 0 ? (v < 248 ? v + 8 : v - 8) : v
+ }
+ }
+ for (let g = 0; g < 2; g++) {
+ const la = new Lookahead(w, 16, 1, false)
+ la.geometricTail = g === 1
+ la.push(frames, 0, 0, undefined)
+ la.push(frames, fb, 0, undefined)
+ const l = la.take(60)
+ lives.push([l[0]!, l[1]!, l[2]!])
+ }
+ }
+ const shorter = lives[3]!.every((v, i) => v > LIFE_ONE && v < lives[2]![i]!)
+ expect(`${lives[0]!.join(",") === lives[1]!.join(",")} ${shorter}`).toBe("true true")
+})
+
+test("the window tail ends content past a video frame at the window edge", () => {
+ const w = 48
+ const fb = (w * 16 * 3) >> 1
+ const lives: int[][] = []
+ for (let moving = 1; moving <= 3; moving += 2) {
+ const frames = new Uint8Array(fb * 2)
+ for (let y = 0; y < 16; y++) {
+ for (let x = 0; x < w; x++) {
+ const v = (x * 29 + y * 47 + x * y * 3) & 255
+ frames[y * w + x] = v
+ frames[fb + y * w + x] = x < moving * 16 && (x & 1) === 0 ? (v < 248 ? v + 8 : v - 8) : v
+ }
+ }
+ for (let g = 0; g < 2; g++) {
+ const la = new Lookahead(w, 16, 1, false)
+ la.geometricTail = true
+ la.windowTail = g === 1
+ la.push(frames, 0, 0, undefined)
+ la.push(frames, fb, 0, undefined)
+ const l = la.take(60)
+ lives.push([l[0]!, l[1]!, l[2]!])
+ }
+ }
+ const shorter = lives[3]!.every((v, i) => v >= LIFE_ONE && v < lives[2]![i]!)
+ expect(`${lives[0]!.join(",") === lives[1]!.join(",")} ${shorter}`).toBe("true true")
+})
+
+test("pixel comparison marks the macroblocks that differ and those within the noise", () => {
+ const w = 48
+ const h = 18
+ const fb = (w * h * 3) >> 1
+ const frames = new Uint8Array(fb * 2)
+ frames[fb + 17 * w + 40] = 9
+ frames[fb + w * h + 3] = 5
+ frames[fb + 20] = 2
+ const la = new Lookahead(w, h, 2, false)
+ const exact = la.diffFrames(frames, fb, 0).join(",")
+ la.noise = 3
+ la.pushed = 1
+ const noisy = la.diffFrames(frames, fb, 0).join(",")
+ expect(`${exact} ${noisy} ${la.changesOf(0).join(",")} ${la.changesOf(2).length} ${la.changesOf(4).length}`)
+ .toBe("1,1,0,0,0,1 1,2,0,0,0,1 1,1,0,0,0,1 0 0")
+})
diff --git a/capcodec/src/mux/bytes.tov b/capcodec/src/mux/bytes.tov
new file mode 100644
index 000000000..043b4b06e
--- /dev/null
+++ b/capcodec/src/mux/bytes.tov
@@ -0,0 +1,104 @@
+const ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ."
+const CODES: int[] = [
+ 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, 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, 48,
+ 49, 50, 51, 52, 53, 54, 55, 56, 57, 32, 46,
+]
+
+export function asciiBytes(s: string): u8[] {
+ const letters = ALPHABET.chars()
+ let out: u8[] = []
+ for (const c of s.chars()) {
+ const i = letters.indexOf(c)
+ const code = i >= 0 ? CODES[i]! : 63
+ out.push(u8(code))
+ }
+ return out
+}
+
+export class ByteWriter {
+ buf: u8[] = []
+
+ u8(v: int) {
+ this.buf.push(u8(v & 255))
+ }
+
+ u16(v: int) {
+ this.buf.push(u8((v >> 8) & 255))
+ this.buf.push(u8(v & 255))
+ }
+
+ u24(v: int) {
+ this.buf.push(u8((v >> 16) & 255))
+ this.buf.push(u8((v >> 8) & 255))
+ this.buf.push(u8(v & 255))
+ }
+
+ u32(v: int) {
+ this.buf.push(u8((v >> 24) & 255))
+ this.buf.push(u8((v >> 16) & 255))
+ this.buf.push(u8((v >> 8) & 255))
+ this.buf.push(u8(v & 255))
+ }
+
+ u64(v: int) {
+ this.u32((v >> 32) & 0xffffffff)
+ this.u32(v & 0xffffffff)
+ }
+
+ zeros(n: int) {
+ for (let i = 0; i < n; i++) this.buf.push(u8(0))
+ }
+
+ bytes(b: u8[], off: int, len: int) {
+ for (let i = 0; i < len; i++) this.buf.push(b[off + i]!)
+ }
+
+ fourcc(s: string) {
+ const b = asciiBytes(s)
+ for (let i = 0; i < 4; i++) this.buf.push(i < b.length ? b[i]! : u8(32))
+ }
+
+ begin(kind: string): int {
+ const at = this.buf.length
+ this.u32(0)
+ this.fourcc(kind)
+ return at
+ }
+
+ beginFull(kind: string, version: int, flags: int): int {
+ const at = this.begin(kind)
+ this.u8(version)
+ this.u24(flags)
+ return at
+ }
+
+ end(at: int) {
+ const size = this.buf.length - at
+ this.buf[at] = u8((size >> 24) & 255)
+ this.buf[at + 1] = u8((size >> 16) & 255)
+ this.buf[at + 2] = u8((size >> 8) & 255)
+ this.buf[at + 3] = u8(size & 255)
+ }
+
+ patch32(at: int, v: int) {
+ this.buf[at] = u8((v >> 24) & 255)
+ this.buf[at + 1] = u8((v >> 16) & 255)
+ this.buf[at + 2] = u8((v >> 8) & 255)
+ this.buf[at + 3] = u8(v & 255)
+ }
+
+ length(): int {
+ return this.buf.length
+ }
+}
+
+test("boxes carry their size", () => {
+ const w = new ByteWriter()
+ const at = w.begin("free")
+ w.u32(7)
+ w.end(at)
+ expect(w.buf.length).toBe(12)
+ expect(int(w.buf[3]!)).toBe(12)
+ expect(int(w.buf[4]!)).toBe(0x66)
+})
diff --git a/capcodec/src/mux/hls.tov b/capcodec/src/mux/hls.tov
new file mode 100644
index 000000000..98fb8e5c5
--- /dev/null
+++ b/capcodec/src/mux/hls.tov
@@ -0,0 +1,45 @@
+export function segmentName(i: int): string {
+ let s = `${i}`
+ while (s.byteLength < 5) s = "0" + s
+ return `seg_${s}.m4s`
+}
+
+export function mediaPlaylist(durations: f64[], initName: string): string {
+ let target = 1
+ for (const d of durations) {
+ const c = Math.ceil(d)
+ if (c > target) target = c
+ }
+ let lines: string[] = [
+ "#EXTM3U",
+ "#EXT-X-VERSION:7",
+ `#EXT-X-TARGETDURATION:${target}`,
+ "#EXT-X-MEDIA-SEQUENCE:0",
+ "#EXT-X-PLAYLIST-TYPE:VOD",
+ "#EXT-X-INDEPENDENT-SEGMENTS",
+ `#EXT-X-MAP:URI="${initName}"`,
+ ]
+ for (let i = 0; i < durations.length; i++) {
+ lines.push(`#EXTINF:${durations[i]!.toFixed(5)},`)
+ lines.push(segmentName(i + 1))
+ }
+ lines.push("#EXT-X-ENDLIST")
+ return lines.join("\n") + "\n"
+}
+
+export function masterPlaylist(media: string, bandwidth: int, codecs: string, width: int, height: int, fps: f64): string {
+ return [
+ "#EXTM3U",
+ "#EXT-X-VERSION:7",
+ "#EXT-X-INDEPENDENT-SEGMENTS",
+ `#EXT-X-STREAM-INF:BANDWIDTH=${bandwidth},CODECS="${codecs}",RESOLUTION=${width}x${height},FRAME-RATE=${fps.toFixed(3)}`,
+ media,
+ ].join("\n") + "\n"
+}
+
+test("playlist lists segments with rounded-up target duration", () => {
+ const p = mediaPlaylist([2.0, 2.0, 1.4], "init.mp4")
+ expect(p.includes("#EXT-X-TARGETDURATION:2")).toBe(true)
+ expect(p.includes("seg_00003.m4s")).toBe(true)
+ expect(p.includes("#EXT-X-ENDLIST")).toBe(true)
+})
diff --git a/capcodec/src/mux/mp4.tov b/capcodec/src/mux/mp4.tov
new file mode 100644
index 000000000..df114bbc5
--- /dev/null
+++ b/capcodec/src/mux/mp4.tov
@@ -0,0 +1,606 @@
+import { ByteWriter, asciiBytes } from "./bytes"
+
+export const TIMESCALE = 90000
+
+export function nalUnits(s: u8[]): int[] {
+ let out: int[] = []
+ const n = s.length
+ let i = 0
+ let start = -1
+ while (i + 2 < n) {
+ if (s[i]! === u8(0) && s[i + 1]! === u8(0) && s[i + 2]! === u8(1)) {
+ if (start >= 0) {
+ let end = i
+ while (end > start && s[end - 1]! === u8(0)) end--
+ out.push(start)
+ out.push(end - start)
+ }
+ i += 3
+ start = i
+ } else {
+ i++
+ }
+ }
+ if (start >= 0 && start < n) {
+ out.push(start)
+ out.push(n - start)
+ }
+ return out
+}
+
+function writeMatrix(w: ByteWriter) {
+ w.u32(0x00010000)
+ w.u32(0)
+ w.u32(0)
+ w.u32(0)
+ w.u32(0x00010000)
+ w.u32(0)
+ w.u32(0)
+ w.u32(0)
+ w.u32(0x40000000)
+}
+
+export class Mp4Muxer {
+ readonly width: int
+ readonly height: int
+ readonly fpsNum: int
+ readonly fpsDen: int
+ sps: u8[] = []
+ pps: u8[] = []
+ data: u8[] = []
+ sizes: int[] = []
+ frameIdx: int[] = []
+ sync: int[] = []
+ disposable: int[] = []
+ reorder = false
+ reorderFrames = 1
+ fragStart = 0
+ dataStart = 0
+ seq = 0
+ lastFragmentTicks = 0
+ lastFragmentStart = 0
+
+ constructor(width: int, height: int, fpsNum: int, fpsDen: int) {
+ this.width = width
+ this.height = height
+ this.fpsNum = fpsNum
+ this.fpsDen = fpsDen
+ }
+
+ ts(frame: int): int {
+ return Math.trunc(f64(frame) * f64(TIMESCALE) * f64(this.fpsDen) / f64(this.fpsNum))
+ }
+
+ addSample(annexb: u8[], inputIndex: int, idr: bool) {
+ const nals = nalUnits(annexb)
+ let size = 0
+ let refIdc = 0
+ for (let k = 0; k < nals.length; k += 2) {
+ const o = nals[k]!
+ const len = nals[k + 1]!
+ if (len <= 0) continue
+ const t = int(annexb[o]!) & 31
+ if ((t === 1 || t === 5) && ((int(annexb[o]!) >> 5) & 3) > refIdc) refIdc = (int(annexb[o]!) >> 5) & 3
+ if (t === 7) {
+ if (this.sps.length === 0) this.sps = annexb.slice(o, o + len)
+ continue
+ }
+ if (t === 8) {
+ if (this.pps.length === 0) this.pps = annexb.slice(o, o + len)
+ continue
+ }
+ if (t === 9) continue
+ this.data.push(u8((len >> 24) & 255))
+ this.data.push(u8((len >> 16) & 255))
+ this.data.push(u8((len >> 8) & 255))
+ this.data.push(u8(len & 255))
+ for (let i = 0; i < len; i++) this.data.push(annexb[o + i]!)
+ size += 4 + len
+ }
+ this.sizes.push(size)
+ this.frameIdx.push(inputIndex)
+ this.sync.push(idr ? 1 : 0)
+ this.disposable.push(refIdc === 0 ? 1 : 0)
+ }
+
+ decodeFrames(a: int, b: int): int[] {
+ let s: int[] = []
+ for (let k = a; k < b; k++) {
+ const v = this.frameIdx[k]!
+ let j = s.length
+ s.push(v)
+ while (j > 0 && s[j - 1]! > v) {
+ s[j] = s[j - 1]!
+ j--
+ }
+ s[j] = v
+ }
+ return s
+ }
+
+ duration(dec: int[], i: int, nextFrame: int): int {
+ const next = i + 1 < dec.length ? dec[i + 1]! : nextFrame
+ return this.ts(next) - this.ts(dec[i]!)
+ }
+
+ sampleFlags(k: int): int {
+ if (this.sync[k]! === 1) return 0x02000000
+ return this.disposable[k]! === 1 ? 0x01810000 : 0x01010000
+ }
+
+ writeAvcC(w: ByteWriter) {
+ const at = w.begin("avcC")
+ w.u8(1)
+ w.u8(int(this.sps[1]!))
+ w.u8(int(this.sps[2]!))
+ w.u8(int(this.sps[3]!))
+ w.u8(0xff)
+ w.u8(0xe1)
+ w.u16(this.sps.length)
+ w.bytes(this.sps, 0, this.sps.length)
+ w.u8(1)
+ w.u16(this.pps.length)
+ w.bytes(this.pps, 0, this.pps.length)
+ const profile = int(this.sps[1]!)
+ if (profile === 100 || profile === 110 || profile === 122 || profile === 244) {
+ w.u8(0xfc | 1)
+ w.u8(0xf8)
+ w.u8(0xf8)
+ w.u8(0)
+ }
+ w.end(at)
+ }
+
+ writeStsd(w: ByteWriter) {
+ const at = w.beginFull("stsd", 0, 0)
+ w.u32(1)
+ const e = w.begin("avc1")
+ w.zeros(6)
+ w.u16(1)
+ w.zeros(16)
+ w.u16(this.width)
+ w.u16(this.height)
+ w.u32(0x00480000)
+ w.u32(0x00480000)
+ w.u32(0)
+ w.u16(1)
+ w.u8(8)
+ w.fourcc("capc")
+ w.fourcc("odec")
+ w.zeros(23)
+ w.u16(0x18)
+ w.u16(0xffff)
+ this.writeAvcC(w)
+ const c = w.begin("colr")
+ w.fourcc("nclx")
+ w.u16(1)
+ w.u16(1)
+ w.u16(1)
+ w.u8(0)
+ w.end(c)
+ const p = w.begin("pasp")
+ w.u32(1)
+ w.u32(1)
+ w.end(p)
+ w.end(e)
+ w.end(at)
+ }
+
+ writeMoovHead(w: ByteWriter, durTicks: int) {
+ const mv = w.beginFull("mvhd", 0, 0)
+ w.u32(0)
+ w.u32(0)
+ w.u32(TIMESCALE)
+ w.u32(durTicks)
+ w.u32(0x00010000)
+ w.u16(0x0100)
+ w.zeros(10)
+ writeMatrix(w)
+ w.zeros(24)
+ w.u32(2)
+ w.end(mv)
+ }
+
+ writeTrackHead(w: ByteWriter, durTicks: int) {
+ const tk = w.beginFull("tkhd", 0, 3)
+ w.u32(0)
+ w.u32(0)
+ w.u32(1)
+ w.u32(0)
+ w.u32(durTicks)
+ w.zeros(8)
+ w.u16(0)
+ w.u16(0)
+ w.u16(0)
+ w.u16(0)
+ writeMatrix(w)
+ w.u32(this.width << 16)
+ w.u32(this.height << 16)
+ w.end(tk)
+ }
+
+ writeEditList(w: ByteWriter, durTicks: int, mediaTime: int) {
+ const edts = w.begin("edts")
+ const elst = w.beginFull("elst", 0, 0)
+ w.u32(1)
+ w.u32(durTicks)
+ w.u32(mediaTime)
+ w.u16(1)
+ w.u16(0)
+ w.end(elst)
+ w.end(edts)
+ }
+
+ fragmentDelay(): int {
+ return Math.ceil(f64(this.reorderFrames) * f64(TIMESCALE) * f64(this.fpsDen) / f64(this.fpsNum))
+ }
+
+ writeMdiaHead(w: ByteWriter, durTicks: int) {
+ const md = w.beginFull("mdhd", 0, 0)
+ w.u32(0)
+ w.u32(0)
+ w.u32(TIMESCALE)
+ w.u32(durTicks)
+ w.u16(0x55c4)
+ w.u16(0)
+ w.end(md)
+ const hd = w.beginFull("hdlr", 0, 0)
+ w.u32(0)
+ w.fourcc("vide")
+ w.zeros(12)
+ const name = asciiBytes("capcodec video")
+ w.bytes(name, 0, name.length)
+ w.u8(0)
+ w.end(hd)
+ }
+
+ writeMinfHead(w: ByteWriter) {
+ const vm = w.beginFull("vmhd", 0, 1)
+ w.zeros(8)
+ w.end(vm)
+ const di = w.begin("dinf")
+ const dr = w.beginFull("dref", 0, 0)
+ w.u32(1)
+ const u = w.beginFull("url ", 0, 1)
+ w.end(u)
+ w.end(dr)
+ w.end(di)
+ }
+
+ writeFtyp(w: ByteWriter, fragmented: bool) {
+ const ft = w.begin("ftyp")
+ w.fourcc(fragmented ? "iso6" : "isom")
+ w.u32(0x200)
+ w.fourcc("isom")
+ w.fourcc(fragmented ? "iso6" : "iso2")
+ w.fourcc("avc1")
+ w.fourcc("mp41")
+ w.end(ft)
+ }
+
+ progressive(totalFrames: int): u8[] {
+ const n = this.sizes.length
+ const dec = this.decodeFrames(0, n)
+ let total = 0
+ for (let k = 0; k < n; k++) total += this.duration(dec, k, totalFrames)
+ let shift = 0
+ for (let k = 0; k < n; k++) {
+ const s = this.ts(dec[k]!) - this.ts(this.frameIdx[k]!)
+ if (s > shift) shift = s
+ }
+ const large = this.data.length > 0x7fff0000
+ let moovSize = 0
+ let w = new ByteWriter()
+ for (let pass = 0; pass < 2; pass++) {
+ w = new ByteWriter()
+ this.writeFtyp(w, false)
+ const ftypSize = w.length()
+ const moov = w.begin("moov")
+ this.writeMoovHead(w, total)
+ const trak = w.begin("trak")
+ this.writeTrackHead(w, total)
+ if (this.reorder) this.writeEditList(w, total, shift)
+ const mdia = w.begin("mdia")
+ this.writeMdiaHead(w, total)
+ const minf = w.begin("minf")
+ this.writeMinfHead(w)
+ const stbl = w.begin("stbl")
+ this.writeStsd(w)
+ const stts = w.beginFull("stts", 0, 0)
+ const cntAt = w.length()
+ w.u32(0)
+ let runs = 0
+ let k = 0
+ while (k < n) {
+ const d = this.duration(dec, k, totalFrames)
+ let j = k + 1
+ while (j < n && this.duration(dec, j, totalFrames) === d) j++
+ w.u32(j - k)
+ w.u32(d)
+ runs++
+ k = j
+ }
+ w.patch32(cntAt, runs)
+ w.end(stts)
+ if (this.reorder) {
+ const ctts = w.beginFull("ctts", 0, 0)
+ const ctAt = w.length()
+ w.u32(0)
+ let cruns = 0
+ let c = 0
+ while (c < n) {
+ const o = this.ts(this.frameIdx[c]!) - this.ts(dec[c]!) + shift
+ let j = c + 1
+ while (j < n && this.ts(this.frameIdx[j]!) - this.ts(dec[j]!) + shift === o) j++
+ w.u32(j - c)
+ w.u32(o)
+ cruns++
+ c = j
+ }
+ w.patch32(ctAt, cruns)
+ w.end(ctts)
+ }
+ const stss = w.beginFull("stss", 0, 0)
+ let ns = 0
+ for (let i = 0; i < n; i++) ns += this.sync[i]!
+ w.u32(ns)
+ for (let i = 0; i < n; i++) {
+ if (this.sync[i]! === 1) w.u32(i + 1)
+ }
+ w.end(stss)
+ const stsc = w.beginFull("stsc", 0, 0)
+ w.u32(1)
+ w.u32(1)
+ w.u32(1)
+ w.u32(1)
+ w.end(stsc)
+ const stsz = w.beginFull("stsz", 0, 0)
+ w.u32(0)
+ w.u32(n)
+ for (let i = 0; i < n; i++) w.u32(this.sizes[i]!)
+ w.end(stsz)
+ const co = w.beginFull(large ? "co64" : "stco", 0, 0)
+ w.u32(n)
+ let off = ftypSize + moovSize + (large ? 16 : 8)
+ for (let i = 0; i < n; i++) {
+ if (large) {
+ w.u64(off)
+ } else {
+ w.u32(off)
+ }
+ off += this.sizes[i]!
+ }
+ w.end(co)
+ w.end(stbl)
+ w.end(minf)
+ w.end(mdia)
+ w.end(trak)
+ w.end(moov)
+ moovSize = w.length() - ftypSize
+ }
+ if (large) {
+ w.u32(1)
+ w.fourcc("mdat")
+ w.u64(this.data.length + 16)
+ } else {
+ w.u32(this.data.length + 8)
+ w.fourcc("mdat")
+ }
+ w.bytes(this.data, 0, this.data.length)
+ return w.buf
+ }
+
+ initSegment(): u8[] {
+ const w = new ByteWriter()
+ this.writeFtyp(w, true)
+ const moov = w.begin("moov")
+ this.writeMoovHead(w, 0)
+ const trak = w.begin("trak")
+ this.writeTrackHead(w, 0)
+ if (this.reorder) this.writeEditList(w, 0, this.fragmentDelay())
+ const mdia = w.begin("mdia")
+ this.writeMdiaHead(w, 0)
+ const minf = w.begin("minf")
+ this.writeMinfHead(w)
+ const stbl = w.begin("stbl")
+ this.writeStsd(w)
+ for (const kind of ["stts", "stsc", "stsz", "stco"]) {
+ const b = w.beginFull(kind, 0, 0)
+ if (kind === "stsz") w.u32(0)
+ w.u32(0)
+ w.end(b)
+ }
+ w.end(stbl)
+ w.end(minf)
+ w.end(mdia)
+ w.end(trak)
+ const mvex = w.begin("mvex")
+ const trex = w.beginFull("trex", 0, 0)
+ w.u32(1)
+ w.u32(1)
+ w.u32(0)
+ w.u32(0)
+ w.u32(0)
+ w.end(trex)
+ w.end(mvex)
+ w.end(moov)
+ return w.buf
+ }
+
+ pendingSamples(): int {
+ return this.sizes.length - this.fragStart
+ }
+
+ fragment(endExclusive: int, totalFrames: int): u8[] {
+ const a = this.fragStart
+ const b = endExclusive
+ const w = new ByteWriter()
+ this.seq++
+ const moof = w.begin("moof")
+ const mfhd = w.beginFull("mfhd", 0, 0)
+ w.u32(this.seq)
+ w.end(mfhd)
+ const traf = w.begin("traf")
+ const tfhd = w.beginFull("tfhd", 0, 0x020000)
+ w.u32(1)
+ w.end(tfhd)
+ const dec = this.decodeFrames(a, b)
+ const tfdt = w.beginFull("tfdt", 1, 0)
+ w.u64(this.ts(dec[0]!))
+ w.end(tfdt)
+ const trun = w.beginFull("trun", 0, this.reorder ? 0x000f01 : 0x000701)
+ w.u32(b - a)
+ const doff = w.length()
+ w.u32(0)
+ const delay = this.fragmentDelay()
+ let ticks = 0
+ let bytes = 0
+ for (let k = a; k < b; k++) {
+ const d = this.duration(dec, k - a, totalFrames)
+ ticks += d
+ bytes += this.sizes[k]!
+ w.u32(d)
+ w.u32(this.sizes[k]!)
+ w.u32(this.sampleFlags(k))
+ if (this.reorder) w.u32(this.ts(this.frameIdx[k]!) - this.ts(dec[k - a]!) + delay)
+ }
+ w.end(trun)
+ w.end(traf)
+ w.end(moof)
+ w.patch32(doff, w.length() - moof + 8)
+ w.u32(bytes + 8)
+ w.fourcc("mdat")
+ w.bytes(this.data, this.dataStart, bytes)
+ this.lastFragmentTicks = ticks
+ this.lastFragmentStart = this.ts(dec[0]!)
+ this.data = this.data.slice(this.dataStart + bytes)
+ this.dataStart = 0
+ this.fragStart = b
+ return w.buf
+ }
+}
+
+function boxAt(buf: u8[], kind: string): int {
+ const k = asciiBytes(kind)
+ for (let i = 4; i + 4 <= buf.length; i++) {
+ if (buf[i]! === k[0]! && buf[i + 1]! === k[1]! && buf[i + 2]! === k[2]! && buf[i + 3]! === k[3]!) return i - 4
+ }
+ return -1
+}
+
+function be32(buf: u8[], at: int): int {
+ const v = (int(buf[at]!) << 24) | (int(buf[at + 1]!) << 16) | (int(buf[at + 2]!) << 8) | int(buf[at + 3]!)
+ return v >= 0x80000000 ? v - 0x100000000 : v
+}
+
+test("reordered fragments get sorted decode times and composition offsets delayed by the init edit list", () => {
+ const m = new Mp4Muxer(16, 16, 30, 1)
+ m.reorder = true
+ const idr: u8[] = [u8(0), u8(0), u8(1), u8(0x67), u8(0x64), u8(0), u8(0x28), u8(0), u8(0), u8(1), u8(0x68), u8(0xee),
+ u8(0), u8(0), u8(1), u8(0x65), u8(0x88)]
+ const p: u8[] = [u8(0), u8(0), u8(1), u8(0x41), u8(0x9a)]
+ const b: u8[] = [u8(0), u8(0), u8(1), u8(0x01), u8(0x9e)]
+ m.addSample(idr, 0, true)
+ m.addSample(p, 3, false)
+ m.addSample(b, 1, false)
+ m.addSample(b, 2, false)
+ expect(m.decodeFrames(0, 4)).toEqual([0, 1, 2, 3])
+ expect(m.disposable).toEqual([0, 0, 1, 1])
+ const init = m.initSegment()
+ const elst = boxAt(init, "elst")
+ expect(be32(init, elst + 12)).toBe(1)
+ expect(be32(init, elst + 16)).toBe(0)
+ expect(be32(init, elst + 20)).toBe(3000)
+ m.reorder = false
+ expect(boxAt(m.initSegment(), "edts")).toBe(-1)
+ m.reorder = true
+ const frag = m.fragment(4, 4)
+ const trun = boxAt(frag, "trun")
+ expect(int(frag[trun + 8]!)).toBe(0)
+ expect(be32(frag, trun + 8) & 0xffffff).toBe(0x000f01)
+ let offsets: int[] = []
+ let flags: int[] = []
+ for (let k = 0; k < 4; k++) {
+ flags.push(be32(frag, trun + 20 + k * 16 + 8))
+ offsets.push(be32(frag, trun + 20 + k * 16 + 12))
+ }
+ expect(offsets).toEqual([3000, 9000, 0, 0])
+ expect(flags).toEqual([0x02000000, 0x01010000, 0x01810000, 0x01810000])
+ const tfdt = boxAt(frag, "tfdt")
+ expect(be32(frag, tfdt + 16)).toBe(0)
+})
+
+test("fractional frame rates keep fragment composition offsets non-negative and presentation exact", () => {
+ const m = new Mp4Muxer(16, 16, 24000, 1001)
+ m.reorder = true
+ const idr: u8[] = [u8(0), u8(0), u8(1), u8(0x65), u8(0x88)]
+ const p: u8[] = [u8(0), u8(0), u8(1), u8(0x41), u8(0x9a)]
+ const order = [0, 2, 1, 5, 3, 4, 7, 6]
+ m.addSample(idr, 0, true)
+ for (let k = 1; k < order.length; k++) m.addSample(p, order[k]!, false)
+ const delay = m.fragmentDelay()
+ expect(delay).toBe(3754)
+ const frag = m.fragment(order.length, 8)
+ const trun = boxAt(frag, "trun")
+ let dts = be32(frag, boxAt(frag, "tfdt") + 16)
+ for (let k = 0; k < order.length; k++) {
+ const off = be32(frag, trun + 20 + k * 16 + 12)
+ expect(off >= 0).toBe(true)
+ expect(dts + off - delay).toBe(m.ts(order[k]!))
+ dts += be32(frag, trun + 20 + k * 16)
+ }
+})
+
+test("b-pyramid fragments delay composition by two frames and keep the reference b-frame", () => {
+ const m = new Mp4Muxer(16, 16, 30, 1)
+ m.reorder = true
+ m.reorderFrames = 2
+ const idr: u8[] = [u8(0), u8(0), u8(1), u8(0x65), u8(0x88)]
+ const ref: u8[] = [u8(0), u8(0), u8(1), u8(0x41), u8(0x9a)]
+ const b: u8[] = [u8(0), u8(0), u8(1), u8(0x01), u8(0x9e)]
+ const order = [0, 4, 2, 1, 3, 8, 6, 5, 7]
+ m.addSample(idr, 0, true)
+ for (let k = 1; k < order.length; k++) m.addSample(order[k]! % 2 === 0 ? ref : b, order[k]!, false)
+ expect(m.disposable).toEqual([0, 0, 0, 1, 1, 0, 0, 1, 1])
+ const delay = m.fragmentDelay()
+ expect(delay).toBe(6000)
+ const frag = m.fragment(order.length, 9)
+ const trun = boxAt(frag, "trun")
+ let dts = be32(frag, boxAt(frag, "tfdt") + 16)
+ let least = delay
+ for (let k = 0; k < order.length; k++) {
+ const off = be32(frag, trun + 20 + k * 16 + 12)
+ if (off < least) least = off
+ expect(dts + off - delay).toBe(m.ts(order[k]!))
+ dts += be32(frag, trun + 20 + k * 16)
+ }
+ expect(least).toBe(0)
+})
+
+test("progressive files shift reordered composition offsets with an edit list", () => {
+ const m = new Mp4Muxer(16, 16, 30, 1)
+ m.reorder = true
+ const idr: u8[] = [u8(0), u8(0), u8(1), u8(0x67), u8(0x64), u8(0), u8(0x28), u8(0), u8(0), u8(1), u8(0x68), u8(0xee),
+ u8(0), u8(0), u8(1), u8(0x65), u8(0x88)]
+ const p: u8[] = [u8(0), u8(0), u8(1), u8(0x41), u8(0x9a)]
+ const b: u8[] = [u8(0), u8(0), u8(1), u8(0x01), u8(0x9e)]
+ m.addSample(idr, 0, true)
+ m.addSample(p, 2, false)
+ m.addSample(b, 1, false)
+ const file = m.progressive(3)
+ const elst = boxAt(file, "elst")
+ expect(be32(file, elst + 12)).toBe(1)
+ expect(be32(file, elst + 16)).toBe(9000)
+ expect(be32(file, elst + 20)).toBe(3000)
+ const ctts = boxAt(file, "ctts")
+ expect(be32(file, ctts + 12)).toBe(3)
+ expect(be32(file, ctts + 20)).toBe(3000)
+ expect(be32(file, ctts + 28)).toBe(6000)
+ expect(be32(file, ctts + 36)).toBe(0)
+})
+
+test("annex b splitting finds each nal", () => {
+ const s: u8[] = [u8(0), u8(0), u8(0), u8(1), u8(0x67), u8(1), u8(0), u8(0), u8(1), u8(0x68), u8(2), u8(0), u8(0), u8(1), u8(0x65), u8(9)]
+ const n = nalUnits(s)
+ expect(n).toEqual([4, 2, 9, 2, 14, 2])
+})
diff --git a/capcodec/src/pixel.tov b/capcodec/src/pixel.tov
new file mode 100644
index 000000000..2b8508586
--- /dev/null
+++ b/capcodec/src/pixel.tov
@@ -0,0 +1,36 @@
+export function clip255(v: int): int {
+ return v < 0 ? 0 : v > 255 ? 255 : v
+}
+
+export function copyPadded(dst: Uint8Array, dstStride: int, dstH: int, src: Uint8Array, srcOff: int, srcStride: int, w: int, h: int) {
+ for (let y = 0; y < dstH; y++) {
+ const sy = y < h ? y : h - 1
+ const so = srcOff + sy * srcStride
+ const d = y * dstStride
+ for (let x = 0; x < w; x++) dst[d + x] = src[so + x]!
+ const last = src[so + w - 1]!
+ for (let x = w; x < dstStride; x++) dst[d + x] = last
+ }
+}
+
+export function residual(inout blk: int[], bo: int, n: int, src: Uint8Array, so: int, sstride: int, pred: Uint8Array, po: int, pstride: int) {
+ for (let y = 0; y < n; y++) {
+ for (let x = 0; x < n; x++) {
+ blk[bo + y * n + x] = int(src[so + y * sstride + x]!) - int(pred[po + y * pstride + x]!)
+ }
+ }
+}
+
+export function reconAdd(rec: Uint8Array, ro: int, rstride: int, n: int, blk: int[], bo: int, pred: Uint8Array, po: int, pstride: int) {
+ for (let y = 0; y < n; y++) {
+ for (let x = 0; x < n; x++) {
+ rec[ro + y * rstride + x] = clip255(int(pred[po + y * pstride + x]!) + blk[bo + y * n + x]!)
+ }
+ }
+}
+
+export function copyBlock(dst: Uint8Array, dO: int, ds: int, src: Uint8Array, so: int, ss: int, w: int, h: int) {
+ for (let y = 0; y < h; y++) {
+ for (let x = 0; x < w; x++) dst[dO + y * ds + x] = src[so + y * ss + x]!
+ }
+}
diff --git a/capcodec/src/ratecontrol.tov b/capcodec/src/ratecontrol.tov
new file mode 100644
index 000000000..ebfbaa254
--- /dev/null
+++ b/capcodec/src/ratecontrol.tov
@@ -0,0 +1,280 @@
+export const RC_CQP = 0
+export const RC_CRF = 1
+export const RC_VBR = 2
+
+export function qstep(qp: f64): f64 {
+ return 0.625 * Math.pow(2.0, qp / 6.0)
+}
+
+export class RateControl {
+ mode: int
+ base: f64
+ ipOffset: int
+ targetBps: f64
+ maxBps: f64
+ bufferBits: f64
+ fill: f64
+ fps: f64
+ gopSec: f64
+ bankBits: f64
+ longHalf = 1.0
+ shortHalf = 0.15
+ firstShare = 0.5
+ cheapShare = 0.35
+ logKI = 0.0
+ alphaI = 0.55
+ actI = 0.0
+ act = 1.0
+ haveI = false
+ probed = false
+ probeQp = 0
+ probeBits = 0.0
+ lastQpI = -1
+ cplxMb = 0.0
+ frameMbs = 1
+ warmMbs = 0
+ longK = 0.0
+ longT = 0.0
+ shortK = 0.0
+ shortT = 0.0
+ haveP = false
+ stepDt = 0.0
+ spent = 0.0
+ wanted = 0.0
+ elapsed = 0.0
+ minQp = 10
+ maxQp = 51
+ vbrMinQp = 8
+ cheapQp = 12
+
+ constructor(mode: int, base: f64, ipOffset: int, targetKbps: int, maxKbps: int, bufferKbits: int, fps: f64, keyint: int) {
+ this.mode = mode
+ this.base = base
+ this.ipOffset = ipOffset
+ this.targetBps = f64(targetKbps) * 1000.0
+ this.maxBps = f64(maxKbps > 0 ? maxKbps : targetKbps) * 1000.0
+ const buf = bufferKbits > 0 ? f64(bufferKbits) * 1000.0 : this.maxBps * 2.0
+ this.bufferBits = buf
+ this.fill = buf * 0.9
+ this.fps = fps
+ this.gopSec = (keyint > 0 ? f64(keyint) : 1.0) / fps
+ this.bankBits = this.targetBps
+ }
+
+ wantsProbe(act: f64): bool {
+ if (this.mode !== RC_VBR) return false
+ return !this.haveI || Math.abs(Math.log(Math.max(1.0, act) / this.actI)) > 0.22
+ }
+
+ probeQpValue(): int {
+ const q = this.vbrMinQp - this.ipOffset
+ return q < 0 ? 0 : q
+ }
+
+ seedIntra(qp: int, bits: int) {
+ this.probed = true
+ this.probeQp = qp
+ this.probeBits = Math.max(1.0, f64(bits))
+ }
+
+ predictIntra(qp: f64, act: f64): f64 {
+ if (!this.haveI && !this.probed) return -1.0
+ return Math.exp(this.logKI - this.alphaI * Math.log(qstep(qp))) * act
+ }
+
+ predictBits(intra: bool, qp: int, mbs: int): f64 {
+ if (intra) return this.predictIntra(f64(qp), this.act)
+ if (this.cplxMb <= 0.0) return -1.0
+ return this.cplxMb * f64(mbs) / qstep(f64(qp))
+ }
+
+ rateAt(qP: f64, k: f64, t: f64): f64 {
+ let r = t > 0.0 ? k / t / qstep(qP) : 0.0
+ const i = this.predictIntra(qP - f64(this.ipOffset), this.actI)
+ if (i > 0.0) r += i / this.gopSec
+ return r
+ }
+
+ warm(): bool {
+ return this.warmMbs >= this.frameMbs
+ }
+
+ solveQp(want: f64, k: f64, t: f64): f64 {
+ let lo = 0.0
+ let hi = 51.0
+ for (let n = 0; n < 24; n++) {
+ const mid = (lo + hi) * 0.5
+ if (this.rateAt(mid, k, t) > want) {
+ lo = mid
+ } else {
+ hi = mid
+ }
+ }
+ return hi
+ }
+
+ frameQp(intra: bool, act: f64, mbs: int, dtFrames: int): int {
+ if (this.mode !== RC_VBR) {
+ const qp = Math.round(this.base) - (intra ? this.ipOffset : 0)
+ return qp < this.minQp ? this.minQp : qp > this.maxQp ? this.maxQp : qp
+ }
+ const dt = f64(dtFrames) / this.fps
+ this.elapsed += dt
+ this.stepDt = dt
+ this.fill = Math.min(this.bufferBits, this.fill + this.maxBps * dt)
+ if (intra) {
+ this.act = Math.max(1.0, act)
+ this.frameMbs = mbs
+ if (this.probed) {
+ this.logKI = Math.log(this.probeBits / this.act) + this.alphaI * Math.log(qstep(f64(this.probeQp)))
+ this.warmMbs = 0
+ }
+ this.actI = this.act
+ }
+ const floorQ = f64(this.vbrMinQp)
+ const warm = this.warm()
+ let qP = this.base
+ if (intra && !warm && this.probed) {
+ qP = floorQ
+ const share = this.firstShare * this.targetBps * this.gopSec
+ for (let n = 0; n < 51; n++) {
+ if (this.predictIntra(qP - f64(this.ipOffset), this.act) <= share || qP >= 51.0) break
+ qP += 1.0
+ }
+ } else if (this.haveI || this.haveP) {
+ const abrBuf = 2.0 * this.targetBps * Math.max(1.0, Math.sqrt(this.elapsed))
+ const over = Math.max(0.5, Math.min(2.0, 1.0 + (this.spent - this.wanted) / abrBuf))
+ const kp = !intra && this.cplxMb > 0.0 ? this.cplxMb * f64(mbs) : 0.0
+ const dl = Math.pow(0.5, dt / this.longHalf)
+ const ds = Math.pow(0.5, dt / this.shortHalf)
+ qP = this.solveQp(this.targetBps / over, this.longK * dl + kp, this.longT * dl + dt)
+ const qs = this.solveQp(this.maxBps, this.shortK * ds + kp, this.shortT * ds + dt)
+ if (qs > qP) qP = qs
+ if (!warm && this.lastQpI >= 0 && qP < f64(this.lastQpI + this.ipOffset)) qP = f64(this.lastQpI + this.ipOffset)
+ }
+ if (qP < floorQ) qP = floorQ
+ if (this.fill < this.bufferBits * 0.5) qP -= 6.0 * Math.log2(Math.max(0.5, 2.0 * this.fill / this.bufferBits))
+ let q = Math.round(qP) - (intra ? this.ipOffset : 0)
+ if (intra) {
+ const cheap = this.cheapShare * this.targetBps * this.gopSec
+ while (q < this.cheapQp - this.ipOffset && this.predictIntra(f64(q), this.act) > cheap) q++
+ }
+ for (let n = 0; n < 51; n++) {
+ const p = this.predictBits(intra, q, mbs)
+ if (p < 0.0 || p <= this.fill * 0.5 || q >= this.maxQp) break
+ q++
+ }
+ return q < 0 ? 0 : q > this.maxQp ? this.maxQp : q
+ }
+
+ peekQp(mbs: int, dtFrames: int): int {
+ const elapsed = this.elapsed
+ const fill = this.fill
+ const stepDt = this.stepDt
+ const q = this.frameQp(false, 0.0, mbs, dtFrames)
+ this.elapsed = elapsed
+ this.fill = fill
+ this.stepDt = stepDt
+ return q
+ }
+
+ spend(bits: int) {
+ this.spent += f64(bits)
+ this.fill -= f64(bits)
+ if (this.fill < 0.0) this.fill = 0.0
+ }
+
+ addWindow(k: f64, t: f64) {
+ const dl = Math.pow(0.5, t / this.longHalf)
+ this.longK = this.longK * dl + k
+ this.longT = this.longT * dl + t
+ const ds = Math.pow(0.5, t / this.shortHalf)
+ this.shortK = this.shortK * ds + k
+ this.shortT = this.shortT * ds + t
+ }
+
+ update(intra: bool, qp: int, bits: int, codedMbs: int) {
+ this.spend(bits)
+ if (this.mode !== RC_VBR) return
+ const b = Math.max(1.0, f64(bits))
+ const ls = Math.log(qstep(f64(qp)))
+ if (intra) {
+ if (this.probed && Math.abs(qp - this.probeQp) >= 2) {
+ const a = Math.log(this.probeBits / b) / (ls - Math.log(qstep(f64(this.probeQp))))
+ this.alphaI = Math.max(0.3, Math.min(1.5, a))
+ }
+ const c = Math.log(b / this.act) + this.alphaI * ls
+ this.logKI = this.haveI && !this.probed ? this.logKI * 0.5 + c * 0.5 : c
+ this.haveI = true
+ this.probed = false
+ this.lastQpI = qp
+ this.addWindow(0.0, this.stepDt)
+ } else {
+ const k = b * qstep(f64(qp))
+ if (codedMbs > 0) {
+ const per = k / f64(codedMbs)
+ const w = Math.max(0.05, Math.min(0.6, 2.0 * f64(codedMbs) / f64(this.frameMbs)))
+ this.cplxMb = this.cplxMb <= 0.0 ? per : this.cplxMb * (1.0 - w) + per * w
+ this.warmMbs += codedMbs
+ }
+ this.haveP = true
+ this.addWindow(k, this.stepDt)
+ }
+ this.wanted = Math.min(this.wanted + this.targetBps * this.stepDt, this.spent + this.bankBits)
+ }
+
+ updateB(anchorQp: int, bits: int) {
+ this.spend(bits)
+ if (this.mode !== RC_VBR) return
+ const k = f64(bits) * qstep(f64(anchorQp))
+ this.longK += k
+ this.shortK += k
+ }
+}
+
+test("qstep doubles every 6 qp", () => {
+ expect(qstep(28.0) / qstep(22.0)).toBeCloseTo(2.0)
+})
+
+test("vbr raises qp when the buffer cannot hold the predicted frame", () => {
+ const rc = new RateControl(RC_VBR, 26.0, 3, 500, 800, 800, 30.0, 60)
+ rc.frameQp(false, 0.0, 8000, 1)
+ rc.update(false, 26, 400000, 8000)
+ const q = rc.frameQp(false, 0.0, 8000, 1)
+ expect(q > 26).toBe(true)
+})
+
+test("vbr sizes the first idr to its share of the gop budget", () => {
+ const rc = new RateControl(RC_VBR, 26.0, 3, 1000, 1500, 0, 30.0, 60)
+ rc.seedIntra(9, 8000000)
+ const q = rc.frameQp(true, 1000.0, 8160, 1)
+ expect(q > 9).toBe(true)
+ expect(rc.predictIntra(f64(q), 1000.0) <= 0.5 * 1000000.0 * 2.0).toBe(true)
+})
+
+test("vbr lets an idr below the cheap qp take only a bounded share of the gop budget", () => {
+ const costly = new RateControl(RC_VBR, 26.0, 3, 1000, 1500, 0, 30.0, 60)
+ costly.seedIntra(9, 800000)
+ expect(costly.frameQp(true, 1000.0, 8160, 1)).toBe(9)
+ const cheap = new RateControl(RC_VBR, 26.0, 3, 1000, 1500, 0, 30.0, 60)
+ cheap.seedIntra(9, 200000)
+ expect(cheap.frameQp(true, 1000.0, 8160, 1) < 9).toBe(true)
+})
+
+test("vbr peek answers like the next frame without advancing the controller", () => {
+ const rc = new RateControl(RC_VBR, 26.0, 3, 1000, 1500, 0, 30.0, 60)
+ rc.seedIntra(9, 400000)
+ rc.update(true, rc.frameQp(true, 1000.0, 8160, 1), 400000, 8160)
+ rc.update(false, rc.frameQp(false, 0.0, 4000, 1), 300000, 4000)
+ const q = rc.peekQp(4000, 15)
+ expect(rc.peekQp(4000, 15)).toBe(q)
+ expect(rc.frameQp(false, 0.0, 4000, 15)).toBe(q)
+})
+
+test("vbr idle time banks at most one second of target", () => {
+ const rc = new RateControl(RC_VBR, 26.0, 3, 1000, 1500, 0, 30.0, 60)
+ rc.seedIntra(9, 400000)
+ rc.update(true, rc.frameQp(true, 1000.0, 8160, 1), 400000, 8160)
+ rc.update(false, rc.frameQp(false, 0.0, 10, 300), 2000, 10)
+ expect(rc.wanted - rc.spent <= 1000000.0).toBe(true)
+})
diff --git a/capcodec/src/satd.tov b/capcodec/src/satd.tov
new file mode 100644
index 000000000..6c79e4a95
--- /dev/null
+++ b/capcodec/src/satd.tov
@@ -0,0 +1,441 @@
+export function h4x2(v: i16x8): i16x8 {
+ const p = v.swizzle([1, 0, 3, 2, 5, 4, 7, 6])
+ const t = i16x8.select(i16x8(-1, 0, -1, 0, -1, 0, -1, 0), v + p, p - v)
+ const q = t.swizzle([2, 3, 0, 1, 6, 7, 4, 5])
+ return i16x8.select(i16x8(-1, -1, 0, 0, -1, -1, 0, 0), t + q, q - t)
+}
+
+function h8(v: i16x8): i16x8 {
+ const u = h4x2(v)
+ const r = u.swizzle([4, 5, 6, 7, 0, 1, 2, 3])
+ return i16x8.select(i16x8(-1, -1, -1, -1, 0, 0, 0, 0), u + r, r - u)
+}
+
+function h4(v: i32x4): i32x4 {
+ const p = v.swizzle([1, 0, 3, 2])
+ const t = i32x4.select(i32x4(-1, 0, -1, 0), v + p, p - v)
+ const q = t.swizzle([2, 3, 0, 1])
+ return i32x4.select(i32x4(-1, -1, 0, 0), t + q, q - t)
+}
+
+function satdPair(a: Uint8Array, ao: int, as: int, b: Uint8Array, bo: int, bs: int): int {
+ const d0 = i16x8.loadU8(a, ao) - i16x8.loadU8(b, bo)
+ const d1 = i16x8.loadU8(a, ao + as) - i16x8.loadU8(b, bo + bs)
+ const d2 = i16x8.loadU8(a, ao + 2 * as) - i16x8.loadU8(b, bo + 2 * bs)
+ const d3 = i16x8.loadU8(a, ao + 3 * as) - i16x8.loadU8(b, bo + 3 * bs)
+ const s01 = d0 + d1
+ const m01 = d0 - d1
+ const s23 = d2 + d3
+ const m23 = d2 - d3
+ const v = h4x2(s01 + s23).abs() + h4x2(s01 - s23).abs() + h4x2(m01 + m23).abs() + h4x2(m01 - m23).abs()
+ return v.sum() >> 1
+}
+
+export function satd4(a: Uint8Array, ao: int, as: int, b: Uint8Array, bo: int, bs: int): int {
+ const d0 = i32x4.loadU8(a, ao) - i32x4.loadU8(b, bo)
+ const d1 = i32x4.loadU8(a, ao + as) - i32x4.loadU8(b, bo + bs)
+ const d2 = i32x4.loadU8(a, ao + 2 * as) - i32x4.loadU8(b, bo + 2 * bs)
+ const d3 = i32x4.loadU8(a, ao + 3 * as) - i32x4.loadU8(b, bo + 3 * bs)
+ const s01 = d0 + d1
+ const m01 = d0 - d1
+ const s23 = d2 + d3
+ const m23 = d2 - d3
+ const v = h4(s01 + s23).abs() + h4(s01 - s23).abs() + h4(m01 + m23).abs() + h4(m01 - m23).abs()
+ return v.sum() >> 1
+}
+
+export function h4x4(v: i16x16): i16x16 {
+ const p = v.swizzle([1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14])
+ const t = i16x16.select(i16x16(-1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0), v + p, p - v)
+ const q = t.swizzle([2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13])
+ return i16x16.select(i16x16(-1, -1, 0, 0, -1, -1, 0, 0, -1, -1, 0, 0, -1, -1, 0, 0), t + q, q - t)
+}
+
+function h4x4AbsMax(v: i16x16): i16x16 {
+ const p = v.swizzle([1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14])
+ const t = i16x16.select(i16x16(-1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0, -1, 0), v + p, p - v).abs()
+ return t.max(t.swizzle([2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13]))
+}
+
+export function satd16(a: Uint8Array, ao: int, as: int, b: Uint8Array, bo: int, bs: int): int {
+ // The last butterfly stage folds into |a + b| + |a - b| = 2 * max(|a|, |b|), and each pair's max sits in both of
+ // its lanes. A lane adds half of eight coefficients of one 4x4 block per band, at most sqrt(8) * 16 * 255 / 2 < 5800
+ // (Cauchy-Schwarz with Parseval), so the four bands stay within 16 bits.
+ let acc = i16x16.splat(0)
+ for (let by = 0; by < 16; by += 4) {
+ const oa = ao + by * as
+ const ob = bo + by * bs
+ const d0 = i16x16.loadU8(a, oa) - i16x16.loadU8(b, ob)
+ const d1 = i16x16.loadU8(a, oa + as) - i16x16.loadU8(b, ob + bs)
+ const d2 = i16x16.loadU8(a, oa + 2 * as) - i16x16.loadU8(b, ob + 2 * bs)
+ const d3 = i16x16.loadU8(a, oa + 3 * as) - i16x16.loadU8(b, ob + 3 * bs)
+ const s01 = d0 + d1
+ const m01 = d0 - d1
+ const s23 = d2 + d3
+ const m23 = d2 - d3
+ acc += h4x4AbsMax(s01 + s23) + h4x4AbsMax(s01 - s23) + h4x4AbsMax(m01 + m23) + h4x4AbsMax(m01 - m23)
+ }
+ return acc.sum() >> 1
+}
+
+function avgRow(p: Uint8Array, po: int, q: Uint8Array, qo: int): i16x16 {
+ return i16x16.bitcast(u16x16.loadU8(p, po).avg(u16x16.loadU8(q, qo)))
+}
+
+export function satdAvg16(a: Uint8Array, ao: int, as: int, p: Uint8Array, po: int, q: Uint8Array, qo: int, ps: int): int {
+ let acc = i16x16.splat(0)
+ for (let by = 0; by < 16; by += 4) {
+ const oa = ao + by * as
+ const op = po + by * ps
+ const oq = qo + by * ps
+ const d0 = i16x16.loadU8(a, oa) - avgRow(p, op, q, oq)
+ const d1 = i16x16.loadU8(a, oa + as) - avgRow(p, op + ps, q, oq + ps)
+ const d2 = i16x16.loadU8(a, oa + 2 * as) - avgRow(p, op + 2 * ps, q, oq + 2 * ps)
+ const d3 = i16x16.loadU8(a, oa + 3 * as) - avgRow(p, op + 3 * ps, q, oq + 3 * ps)
+ const s01 = d0 + d1
+ const m01 = d0 - d1
+ const s23 = d2 + d3
+ const m23 = d2 - d3
+ acc += h4x4AbsMax(s01 + s23) + h4x4AbsMax(s01 - s23) + h4x4AbsMax(m01 + m23) + h4x4AbsMax(m01 - m23)
+ }
+ return acc.sum() >> 1
+}
+
+export function satd8(a: Uint8Array, ao: int, as: int, b: Uint8Array, bo: int, bs: int): int {
+ return satdPair(a, ao, as, b, bo, bs) + satdPair(a, ao + 4 * as, as, b, bo + 4 * bs, bs)
+}
+
+export function sa8d(a: Uint8Array, ao: int, as: int, b: Uint8Array, bo: int, bs: int): int {
+ const r0 = i16x8.loadU8(a, ao) - i16x8.loadU8(b, bo)
+ const r1 = i16x8.loadU8(a, ao + as) - i16x8.loadU8(b, bo + bs)
+ const r2 = i16x8.loadU8(a, ao + 2 * as) - i16x8.loadU8(b, bo + 2 * bs)
+ const r3 = i16x8.loadU8(a, ao + 3 * as) - i16x8.loadU8(b, bo + 3 * bs)
+ const r4 = i16x8.loadU8(a, ao + 4 * as) - i16x8.loadU8(b, bo + 4 * bs)
+ const r5 = i16x8.loadU8(a, ao + 5 * as) - i16x8.loadU8(b, bo + 5 * bs)
+ const r6 = i16x8.loadU8(a, ao + 6 * as) - i16x8.loadU8(b, bo + 6 * bs)
+ const r7 = i16x8.loadU8(a, ao + 7 * as) - i16x8.loadU8(b, bo + 7 * bs)
+ const a0 = r0 + r1
+ const a1 = r0 - r1
+ const a2 = r2 + r3
+ const a3 = r2 - r3
+ const a4 = r4 + r5
+ const a5 = r4 - r5
+ const a6 = r6 + r7
+ const a7 = r6 - r7
+ const b0 = a0 + a2
+ const b1 = a1 + a3
+ const b2 = a0 - a2
+ const b3 = a1 - a3
+ const b4 = a4 + a6
+ const b5 = a5 + a7
+ const b6 = a4 - a6
+ const b7 = a5 - a7
+ const lo = u16x8.bitcast(h8(b0 + b4).abs()) + u16x8.bitcast(h8(b1 + b5).abs()) +
+ u16x8.bitcast(h8(b2 + b6).abs()) + u16x8.bitcast(h8(b3 + b7).abs())
+ const hi = u16x8.bitcast(h8(b0 - b4).abs()) + u16x8.bitcast(h8(b1 - b5).abs()) +
+ u16x8.bitcast(h8(b2 - b6).abs()) + u16x8.bitcast(h8(b3 - b7).abs())
+ return (lo.sum() + hi.sum() + 2) >> 2
+}
+
+export function sa8dPair(a: Uint8Array, ao: int, as: int, b: Uint8Array, bo: int, bs: int): int {
+ const r0 = i16x16.loadU8(a, ao) - i16x16.loadU8(b, bo)
+ const r1 = i16x16.loadU8(a, ao + as) - i16x16.loadU8(b, bo + bs)
+ const r2 = i16x16.loadU8(a, ao + 2 * as) - i16x16.loadU8(b, bo + 2 * bs)
+ const r3 = i16x16.loadU8(a, ao + 3 * as) - i16x16.loadU8(b, bo + 3 * bs)
+ const r4 = i16x16.loadU8(a, ao + 4 * as) - i16x16.loadU8(b, bo + 4 * bs)
+ const r5 = i16x16.loadU8(a, ao + 5 * as) - i16x16.loadU8(b, bo + 5 * bs)
+ const r6 = i16x16.loadU8(a, ao + 6 * as) - i16x16.loadU8(b, bo + 6 * bs)
+ const r7 = i16x16.loadU8(a, ao + 7 * as) - i16x16.loadU8(b, bo + 7 * bs)
+ const t = sa8dMax2(r0, r1, r2, r3, r4, r5, r6, r7).addPairs()
+ return ((t.low().sum() + 1) >> 1) + ((t.high().sum() + 1) >> 1)
+}
+
+export const T16_LO = [0, 8, 1, 9, 2, 10, 3, 11]
+export const T16_HI = [4, 12, 5, 13, 6, 14, 7, 15]
+export const T32_LO = [0, 1, 8, 9, 2, 3, 10, 11]
+export const T32_HI = [4, 5, 12, 13, 6, 7, 14, 15]
+export const T64_LO = [0, 1, 2, 3, 8, 9, 10, 11]
+export const T64_HI = [4, 5, 6, 7, 12, 13, 14, 15]
+const W16_LO = [0, 16, 1, 17, 2, 18, 3, 19, 8, 24, 9, 25, 10, 26, 11, 27]
+const W16_HI = [4, 20, 5, 21, 6, 22, 7, 23, 12, 28, 13, 29, 14, 30, 15, 31]
+const W32_LO = [0, 1, 16, 17, 2, 3, 18, 19, 8, 9, 24, 25, 10, 11, 26, 27]
+const W32_HI = [4, 5, 20, 21, 6, 7, 22, 23, 12, 13, 28, 29, 14, 15, 30, 31]
+const W64_LO = [0, 1, 2, 3, 16, 17, 18, 19, 8, 9, 10, 11, 24, 25, 26, 27]
+const W64_HI = [4, 5, 6, 7, 20, 21, 22, 23, 12, 13, 14, 15, 28, 29, 30, 31]
+
+// Rows are transformed, transposed and transformed again; the last butterfly folds into |a + b| + |a - b| =
+// 2 * max(|a|, |b|), so a lane holds half of the |coefficients| of eight positions, at most 4 * 32 * 255 < 32768.
+export function sa8dMax(r0: i16x8, r1: i16x8, r2: i16x8, r3: i16x8, r4: i16x8, r5: i16x8, r6: i16x8, r7: i16x8): u16x8 {
+ const a0 = r0 + r1
+ const a1 = r0 - r1
+ const a2 = r2 + r3
+ const a3 = r2 - r3
+ const a4 = r4 + r5
+ const a5 = r4 - r5
+ const a6 = r6 + r7
+ const a7 = r6 - r7
+ const b0 = a0 + a2
+ const b1 = a1 + a3
+ const b2 = a0 - a2
+ const b3 = a1 - a3
+ const b4 = a4 + a6
+ const b5 = a5 + a7
+ const b6 = a4 - a6
+ const b7 = a5 - a7
+ const c0 = b0 + b4
+ const c1 = b1 + b5
+ const c2 = b2 + b6
+ const c3 = b3 + b7
+ const c4 = b0 - b4
+ const c5 = b1 - b5
+ const c6 = b2 - b6
+ const c7 = b3 - b7
+ const t0 = i16x8.shuffle(c0, c1, T16_LO)
+ const t1 = i16x8.shuffle(c0, c1, T16_HI)
+ const t2 = i16x8.shuffle(c2, c3, T16_LO)
+ const t3 = i16x8.shuffle(c2, c3, T16_HI)
+ const t4 = i16x8.shuffle(c4, c5, T16_LO)
+ const t5 = i16x8.shuffle(c4, c5, T16_HI)
+ const t6 = i16x8.shuffle(c6, c7, T16_LO)
+ const t7 = i16x8.shuffle(c6, c7, T16_HI)
+ const u0 = i16x8.shuffle(t0, t2, T32_LO)
+ const u1 = i16x8.shuffle(t0, t2, T32_HI)
+ const u2 = i16x8.shuffle(t1, t3, T32_LO)
+ const u3 = i16x8.shuffle(t1, t3, T32_HI)
+ const u4 = i16x8.shuffle(t4, t6, T32_LO)
+ const u5 = i16x8.shuffle(t4, t6, T32_HI)
+ const u6 = i16x8.shuffle(t5, t7, T32_LO)
+ const u7 = i16x8.shuffle(t5, t7, T32_HI)
+ const v0 = i16x8.shuffle(u0, u4, T64_LO)
+ const v1 = i16x8.shuffle(u0, u4, T64_HI)
+ const v2 = i16x8.shuffle(u1, u5, T64_LO)
+ const v3 = i16x8.shuffle(u1, u5, T64_HI)
+ const v4 = i16x8.shuffle(u2, u6, T64_LO)
+ const v5 = i16x8.shuffle(u2, u6, T64_HI)
+ const v6 = i16x8.shuffle(u3, u7, T64_LO)
+ const v7 = i16x8.shuffle(u3, u7, T64_HI)
+ const e0 = v0 + v1
+ const e1 = v0 - v1
+ const e2 = v2 + v3
+ const e3 = v2 - v3
+ const e4 = v4 + v5
+ const e5 = v4 - v5
+ const e6 = v6 + v7
+ const e7 = v6 - v7
+ const f0 = e0 + e2
+ const f1 = e1 + e3
+ const f2 = e0 - e2
+ const f3 = e1 - e3
+ const f4 = e4 + e6
+ const f5 = e5 + e7
+ const f6 = e4 - e6
+ const f7 = e5 - e7
+ return u16x8.bitcast(f0.abs().max(f4.abs()) + f1.abs().max(f5.abs()) + f2.abs().max(f6.abs()) + f3.abs().max(f7.abs()))
+}
+
+export function sa8dMax2(r0: i16x16, r1: i16x16, r2: i16x16, r3: i16x16, r4: i16x16, r5: i16x16, r6: i16x16, r7: i16x16): u16x16 {
+ const a0 = r0 + r1
+ const a1 = r0 - r1
+ const a2 = r2 + r3
+ const a3 = r2 - r3
+ const a4 = r4 + r5
+ const a5 = r4 - r5
+ const a6 = r6 + r7
+ const a7 = r6 - r7
+ const b0 = a0 + a2
+ const b1 = a1 + a3
+ const b2 = a0 - a2
+ const b3 = a1 - a3
+ const b4 = a4 + a6
+ const b5 = a5 + a7
+ const b6 = a4 - a6
+ const b7 = a5 - a7
+ const c0 = b0 + b4
+ const c1 = b1 + b5
+ const c2 = b2 + b6
+ const c3 = b3 + b7
+ const c4 = b0 - b4
+ const c5 = b1 - b5
+ const c6 = b2 - b6
+ const c7 = b3 - b7
+ const t0 = i16x16.shuffle(c0, c1, W16_LO)
+ const t1 = i16x16.shuffle(c0, c1, W16_HI)
+ const t2 = i16x16.shuffle(c2, c3, W16_LO)
+ const t3 = i16x16.shuffle(c2, c3, W16_HI)
+ const t4 = i16x16.shuffle(c4, c5, W16_LO)
+ const t5 = i16x16.shuffle(c4, c5, W16_HI)
+ const t6 = i16x16.shuffle(c6, c7, W16_LO)
+ const t7 = i16x16.shuffle(c6, c7, W16_HI)
+ const u0 = i16x16.shuffle(t0, t2, W32_LO)
+ const u1 = i16x16.shuffle(t0, t2, W32_HI)
+ const u2 = i16x16.shuffle(t1, t3, W32_LO)
+ const u3 = i16x16.shuffle(t1, t3, W32_HI)
+ const u4 = i16x16.shuffle(t4, t6, W32_LO)
+ const u5 = i16x16.shuffle(t4, t6, W32_HI)
+ const u6 = i16x16.shuffle(t5, t7, W32_LO)
+ const u7 = i16x16.shuffle(t5, t7, W32_HI)
+ const v0 = i16x16.shuffle(u0, u4, W64_LO)
+ const v1 = i16x16.shuffle(u0, u4, W64_HI)
+ const v2 = i16x16.shuffle(u1, u5, W64_LO)
+ const v3 = i16x16.shuffle(u1, u5, W64_HI)
+ const v4 = i16x16.shuffle(u2, u6, W64_LO)
+ const v5 = i16x16.shuffle(u2, u6, W64_HI)
+ const v6 = i16x16.shuffle(u3, u7, W64_LO)
+ const v7 = i16x16.shuffle(u3, u7, W64_HI)
+ const e0 = v0 + v1
+ const e1 = v0 - v1
+ const e2 = v2 + v3
+ const e3 = v2 - v3
+ const e4 = v4 + v5
+ const e5 = v4 - v5
+ const e6 = v6 + v7
+ const e7 = v6 - v7
+ const f0 = e0 + e2
+ const f1 = e1 + e3
+ const f2 = e0 - e2
+ const f3 = e1 - e3
+ const f4 = e4 + e6
+ const f5 = e5 + e7
+ const f6 = e4 - e6
+ const f7 = e5 - e7
+ return u16x16.bitcast(f0.abs().max(f4.abs()) + f1.abs().max(f5.abs()) + f2.abs().max(f6.abs()) + f3.abs().max(f7.abs()))
+}
+
+function rows2(p: Uint8Array, o: int, s: int): u8x32 {
+ return u8x32.concat(u8x16.load(p, o), u8x16.load(p, o + s))
+}
+
+export function sad16(a: Uint8Array, ao: int, as: int, b: Uint8Array, bo: int, bs: int): int {
+ let acc = u32x8.splat(0)
+ for (let y = 0; y < 16; y += 2) acc += u8x32.sadParts(rows2(a, ao + y * as, as), rows2(b, bo + y * bs, bs))
+ return acc.sum()
+}
+
+export function sadAvg16(a: Uint8Array, ao: int, as: int, p: Uint8Array, po: int, q: Uint8Array, qo: int, ps: int): int {
+ let acc = u32x8.splat(0)
+ for (let y = 0; y < 16; y += 2) {
+ acc += u8x32.sadParts(rows2(a, ao + y * as, as), rows2(p, po + y * ps, ps).avg(rows2(q, qo + y * ps, ps)))
+ }
+ return acc.sum()
+}
+
+function abs(v: int): int {
+ return v < 0 ? -v : v
+}
+
+function hadamardRef(inout t: int[], o: int, s: int, n: int) {
+ for (let len = 1; len < n; len = len * 2) {
+ for (let i = 0; i < n; i += 2 * len) {
+ for (let j = i; j < i + len; j++) {
+ const x = t[o + j * s]!
+ const y = t[o + (j + len) * s]!
+ t[o + j * s] = x + y
+ t[o + (j + len) * s] = x - y
+ }
+ }
+ }
+}
+
+function hadamardSumRef(a: Uint8Array, ao: int, as: int, b: Uint8Array, bo: int, bs: int, n: int): int {
+ let t: int[] = []
+ for (let y = 0; y < n; y++) {
+ for (let x = 0; x < n; x++) t.push(int(a[ao + y * as + x]!) - int(b[bo + y * bs + x]!))
+ }
+ for (let y = 0; y < n; y++) hadamardRef(&t, y * n, 1, n)
+ for (let x = 0; x < n; x++) hadamardRef(&t, x, n, n)
+ let s = 0
+ for (const v of t) s += abs(v)
+ return s
+}
+
+function noise(seed: int, n: int): Uint8Array {
+ let out: u8[] = []
+ let x = seed
+ for (let i = 0; i < n; i++) {
+ x = (x * 1103515245 + 12345) & 0x7fffffff
+ const v = (x >> 9) & 255
+ const w = i % 7 === 0 ? 255 - v : v
+ out.push(u8(w))
+ }
+ return new Uint8Array(out)
+}
+
+test("satd of identical blocks is zero and of a DC offset is 16*offset/2", () => {
+ let a: u8[] = []
+ let b: u8[] = []
+ for (let i = 0; i < 16; i++) {
+ a.push(u8(100))
+ b.push(u8(90))
+ }
+ const ta = new Uint8Array(a)
+ const tb = new Uint8Array(b)
+ expect(satd4(ta, 0, 4, ta, 0, 4)).toBe(0)
+ expect(satd4(ta, 0, 4, tb, 0, 4)).toBe(80)
+ expect(sad16(ta, 0, 0, tb, 0, 0)).toBe(2560)
+})
+
+test("vector satd, sa8d and sad agree with the scalar Hadamard definitions on random blocks", () => {
+ let bad = 0
+ for (let seed = 1; seed <= 60; seed++) {
+ const a = noise(seed, 40 * 40)
+ const b = seed % 3 === 0 ? noise(seed * 31 + 7, 40 * 40) : noise(seed + 1000, 40 * 40)
+ const ao = seed % 5
+ const bo = 41 + seed % 3
+ let ref4 = 0
+ for (let by = 0; by < 16; by += 4) {
+ for (let bx = 0; bx < 16; bx += 4) {
+ const r = hadamardSumRef(a, ao + by * 40 + bx, 40, b, bo + by * 40 + bx, 40, 4) >> 1
+ if (satd4(a, ao + by * 40 + bx, 40, b, bo + by * 40 + bx, 40) !== r) bad++
+ ref4 += r
+ }
+ }
+ if (satd16(a, ao, 40, b, bo, 40) !== ref4) bad++
+ const avg = new Uint8Array(16 * 16)
+ for (let y = 0; y < 16; y++) {
+ for (let x = 0; x < 16; x++) avg[y * 16 + x] = (int(a[bo + y * 40 + x + 1]!) + int(b[bo + y * 40 + x]!) + 1) >> 1
+ }
+ if (satdAvg16(b, ao, 40, a, bo + 1, b, bo, 40) !== satd16(b, ao, 40, avg, 0, 16)) bad++
+ if (sadAvg16(b, ao, 40, a, bo + 1, b, bo, 40) !== sad16(b, ao, 40, avg, 0, 16)) bad++
+ let ref8 = 0
+ for (let by = 0; by < 8; by += 4) {
+ for (let bx = 0; bx < 8; bx += 4) ref8 += hadamardSumRef(a, ao + by * 40 + bx, 40, b, bo + by * 40 + bx, 40, 4) >> 1
+ }
+ if (satd8(a, ao, 40, b, bo, 40) !== ref8) bad++
+ const left = (hadamardSumRef(a, ao, 40, b, bo, 40, 8) + 2) >> 2
+ if (sa8d(a, ao, 40, b, bo, 40) !== left) bad++
+ if (sa8dPair(a, ao, 40, b, bo, 40) !== left + ((hadamardSumRef(a, ao + 8, 40, b, bo + 8, 40, 8) + 2) >> 2)) bad++
+ let s16 = 0
+ for (let y = 0; y < 16; y++) {
+ for (let x = 0; x < 16; x++) s16 += abs(int(a[ao + y * 40 + x]!) - int(b[bo + y * 40 + x]!))
+ }
+ if (sad16(a, ao, 40, b, bo, 40) !== s16) bad++
+ }
+ expect(bad).toBe(0)
+})
+
+test("satd16 and sa8dPair equal the per-block sums on extreme 0/255 patterns", () => {
+ let bad = 0
+ for (let pat = 0; pat < 64; pat++) {
+ const a = new Uint8Array(16 * 16)
+ const b = new Uint8Array(16 * 16)
+ for (let y = 0; y < 16; y++) {
+ for (let x = 0; x < 16; x++) {
+ const hx = ((x >> (pat & 1)) ^ (x >> ((pat >> 1) & 1))) & 1
+ const hy = ((y >> ((pat >> 2) & 1)) ^ (y >> ((pat >> 3) & 1))) & 1
+ const on = (pat & 16) !== 0 ? (hx ^ hy) === 0 : (pat & 32) !== 0 ? hy === 0 || hx === 0 : hx === 0
+ a[y * 16 + x] = on ? 255 : 0
+ b[y * 16 + x] = on ? 0 : 255
+ }
+ }
+ let ref = 0
+ for (let by = 0; by < 16; by += 4) {
+ for (let bx = 0; bx < 16; bx += 4) ref += satd4(a, by * 16 + bx, 16, b, by * 16 + bx, 16)
+ }
+ if (satd16(a, 0, 16, b, 0, 16) !== ref) bad++
+ for (let by = 0; by < 16; by += 8) {
+ const o = by * 16
+ if (sa8dPair(a, o, 16, b, o, 16) !== sa8d(a, o, 16, b, o, 16) + sa8d(a, o + 8, 16, b, o + 8, 16)) bad++
+ }
+ }
+ expect(bad).toBe(0)
+})
diff --git a/capcodec/src/tables.tov b/capcodec/src/tables.tov
new file mode 100644
index 000000000..c6703b21d
--- /dev/null
+++ b/capcodec/src/tables.tov
@@ -0,0 +1,527 @@
+// Generated by tools/gen_tables.py from the JM 19 reference software and FFmpeg's h264_cabac.c
+// (H.264 Tables 8-14..8-17, 9-5, 9-7..9-10, 9-12..9-33, 9-44). Do not edit.
+
+export const CABAC_INIT_I: i8[] = [
+ 20, -15, 2, 54, 3, 74, 20, -15, 2, 54, 3, 74, -28, 127, -23, 104, -6, 53, -1, 54, 7, 51, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 41, 0, 63, 0, 63, 0, 63,
+ -9, 83, 4, 86, 0, 97, -7, 72, 13, 41, 3, 62, 0, 11, 1, 55, 0, 69, -17, 127, -13, 102, 0, 82, -7, 74, -21, 107, -27, 127, -31, 127,
+ -24, 127, -18, 95, -27, 127, -21, 114, -30, 127, -17, 123, -12, 115, -16, 122, -11, 115, -12, 63, -2, 68, -15, 84, -13, 104, -3, 70, -8, 93, -10, 90,
+ -30, 127, -1, 74, -6, 97, -7, 91, -20, 127, -4, 56, -5, 82, -7, 76, -22, 125, -7, 93, -11, 87, -3, 77, -5, 71, -4, 63, -4, 68, -12, 84,
+ -7, 62, -7, 65, 8, 61, 5, 56, -2, 66, 1, 64, 0, 61, -2, 78, 1, 50, 7, 52, 10, 35, 0, 44, 11, 38, 1, 45, 0, 46, 5, 44,
+ 31, 17, 1, 51, 7, 50, 28, 19, 16, 33, 14, 62, -13, 108, -15, 100, -13, 101, -13, 91, -12, 94, -10, 88, -16, 84, -10, 86, -7, 83, -13, 87,
+ -19, 94, 1, 70, 0, 72, -5, 74, 18, 59, -8, 102, -15, 100, 0, 95, -4, 75, 2, 72, -11, 75, -3, 71, 15, 46, -13, 69, 0, 62, 0, 65,
+ 21, 37, -15, 72, 9, 57, 16, 54, 0, 62, 12, 72, 24, 0, 15, 9, 8, 25, 13, 18, 15, 9, 13, 19, 10, 37, 12, 18, 6, 29, 20, 33,
+ 15, 30, 4, 45, 1, 58, 0, 62, 7, 61, 12, 38, 11, 45, 15, 39, 11, 42, 13, 44, 16, 45, 12, 41, 10, 49, 30, 34, 18, 42, 10, 55,
+ 17, 51, 17, 46, 0, 89, 26, -19, 22, -17, 26, -17, 30, -25, 28, -20, 33, -23, 37, -27, 33, -23, 40, -28, 38, -17, 33, -11, 40, -15, 41, -6,
+ 38, 1, 41, 17, 30, -6, 27, 3, 26, 22, 37, -16, 35, -4, 38, -8, 38, -3, 37, 3, 38, 5, 42, 0, 35, 16, 39, 22, 14, 48, 27, 37,
+ 21, 60, 12, 68, 2, 97, -3, 71, -6, 42, -5, 50, -3, 54, -2, 62, 0, 58, 1, 63, -2, 72, -1, 74, -9, 91, -5, 67, -5, 27, -3, 39,
+ -2, 44, 0, 46, -16, 64, -8, 68, -10, 78, -6, 77, -10, 86, -12, 92, -15, 55, -10, 60, -6, 62, -4, 65, -12, 73, -8, 76, -7, 80, -9, 88,
+ -17, 110, -11, 97, -20, 84, -11, 79, -6, 73, -4, 74, -13, 86, -13, 96, -11, 97, -19, 117, -8, 78, -5, 33, -4, 48, -2, 53, -3, 62, -13, 71,
+ -10, 79, -12, 86, -13, 90, -14, 97, 0, 0, -6, 93, -6, 84, -8, 79, 0, 66, -1, 71, 0, 62, -2, 60, -2, 59, -5, 75, -3, 62, -4, 58,
+ -9, 66, -1, 79, 0, 71, 3, 68, 10, 44, -7, 62, 15, 36, 14, 40, 16, 27, 12, 29, 1, 44, 20, 36, 18, 32, 5, 42, 1, 48, 10, 62,
+ 17, 46, 9, 64, -12, 104, -11, 97, -16, 96, -7, 88, -8, 85, -7, 85, -9, 85, -13, 88, 4, 66, -3, 77, -3, 76, -6, 76, 10, 58, -1, 76,
+ -1, 83, -7, 99, -14, 95, 2, 95, 0, 76, -5, 74, 0, 70, -11, 75, 1, 68, 0, 65, -14, 73, 3, 62, 4, 62, -1, 68, -13, 75, 11, 55,
+ 5, 64, 12, 70, 15, 6, 6, 19, 7, 16, 12, 14, 18, 13, 13, 11, 13, 15, 15, 16, 12, 23, 13, 23, 15, 20, 14, 26, 14, 44, 17, 40,
+ 17, 47, 24, 17, 21, 21, 25, 22, 31, 27, 22, 29, 19, 35, 14, 50, 10, 57, 7, 63, -2, 77, -4, 82, -3, 94, 9, 69, -12, 109, 36, -35,
+ 36, -34, 32, -26, 37, -30, 44, -32, 34, -18, 34, -15, 40, -15, 33, -7, 35, -5, 33, 0, 38, 2, 33, 13, 23, 35, 13, 58, 29, -3, 26, 0,
+ 22, 30, 31, -7, 35, -15, 34, -3, 34, 3, 36, -1, 34, 5, 32, 11, 35, 5, 34, 12, 39, 11, 30, 29, 34, 26, 29, 39, 19, 66, 31, 21,
+ 31, 31, 25, 50, -17, 120, -20, 112, -18, 114, -11, 85, -15, 92, -14, 89, -26, 71, -15, 81, -14, 80, 0, 68, -14, 70, -24, 56, -23, 68, -24, 50,
+ -11, 74, 23, -13, 26, -13, 40, -15, 49, -14, 44, 3, 45, 6, 44, 34, 33, 54, 19, 82, -3, 75, -1, 23, 1, 34, 1, 43, 0, 54, -2, 55,
+ 0, 61, 1, 64, 0, 68, -9, 92, -14, 106, -13, 97, -15, 90, -12, 90, -18, 88, -10, 73, -9, 79, -14, 86, -10, 73, -10, 70, -10, 69, -5, 66,
+ -9, 64, -5, 58, 2, 59, 21, -10, 24, -11, 28, -8, 28, -1, 29, 3, 29, 9, 35, 20, 29, 36, 14, 67, -17, 123, -12, 115, -16, 122, -11, 115,
+ -12, 63, -2, 68, -15, 84, -13, 104, -3, 70, -8, 93, -10, 90, -30, 127, -17, 123, -12, 115, -16, 122, -11, 115, -12, 63, -2, 68, -15, 84, -13, 104,
+ -3, 70, -8, 93, -10, 90, -30, 127, -7, 93, -11, 87, -3, 77, -5, 71, -4, 63, -4, 68, -12, 84, -7, 62, -7, 65, 8, 61, 5, 56, -2, 66,
+ 1, 64, 0, 61, -2, 78, 1, 50, 7, 52, 10, 35, 0, 44, 11, 38, 1, 45, 0, 46, 5, 44, 31, 17, 1, 51, 7, 50, 28, 19, 16, 33,
+ 14, 62, -13, 108, -15, 100, -13, 101, -13, 91, -12, 94, -10, 88, -16, 84, -10, 86, -7, 83, -13, 87, -19, 94, 1, 70, 0, 72, -5, 74, 18, 59,
+ -7, 93, -11, 87, -3, 77, -5, 71, -4, 63, -4, 68, -12, 84, -7, 62, -7, 65, 8, 61, 5, 56, -2, 66, 1, 64, 0, 61, -2, 78, 1, 50,
+ 7, 52, 10, 35, 0, 44, 11, 38, 1, 45, 0, 46, 5, 44, 31, 17, 1, 51, 7, 50, 28, 19, 16, 33, 14, 62, -13, 108, -15, 100, -13, 101,
+ -13, 91, -12, 94, -10, 88, -16, 84, -10, 86, -7, 83, -13, 87, -19, 94, 1, 70, 0, 72, -5, 74, 18, 59, 24, 0, 15, 9, 8, 25, 13, 18,
+ 15, 9, 13, 19, 10, 37, 12, 18, 6, 29, 20, 33, 15, 30, 4, 45, 1, 58, 0, 62, 7, 61, 12, 38, 11, 45, 15, 39, 11, 42, 13, 44,
+ 16, 45, 12, 41, 10, 49, 30, 34, 18, 42, 10, 55, 17, 51, 17, 46, 0, 89, 26, -19, 22, -17, 26, -17, 30, -25, 28, -20, 33, -23, 37, -27,
+ 33, -23, 40, -28, 38, -17, 33, -11, 40, -15, 41, -6, 38, 1, 41, 17, 24, 0, 15, 9, 8, 25, 13, 18, 15, 9, 13, 19, 10, 37, 12, 18,
+ 6, 29, 20, 33, 15, 30, 4, 45, 1, 58, 0, 62, 7, 61, 12, 38, 11, 45, 15, 39, 11, 42, 13, 44, 16, 45, 12, 41, 10, 49, 30, 34,
+ 18, 42, 10, 55, 17, 51, 17, 46, 0, 89, 26, -19, 22, -17, 26, -17, 30, -25, 28, -20, 33, -23, 37, -27, 33, -23, 40, -28, 38, -17, 33, -11,
+ 40, -15, 41, -6, 38, 1, 41, 17, -17, 120, -20, 112, -18, 114, -11, 85, -15, 92, -14, 89, -26, 71, -15, 81, -14, 80, 0, 68, -14, 70, -24, 56,
+ -23, 68, -24, 50, -11, 74, -14, 106, -13, 97, -15, 90, -12, 90, -18, 88, -10, 73, -9, 79, -14, 86, -10, 73, -10, 70, -10, 69, -5, 66, -9, 64,
+ -5, 58, 2, 59, 23, -13, 26, -13, 40, -15, 49, -14, 44, 3, 45, 6, 44, 34, 33, 54, 19, 82, 21, -10, 24, -11, 28, -8, 28, -1, 29, 3,
+ 29, 9, 35, 20, 29, 36, 14, 67, -3, 75, -1, 23, 1, 34, 1, 43, 0, 54, -2, 55, 0, 61, 1, 64, 0, 68, -9, 92, -17, 120, -20, 112,
+ -18, 114, -11, 85, -15, 92, -14, 89, -26, 71, -15, 81, -14, 80, 0, 68, -14, 70, -24, 56, -23, 68, -24, 50, -11, 74, -14, 106, -13, 97, -15, 90,
+ -12, 90, -18, 88, -10, 73, -9, 79, -14, 86, -10, 73, -10, 70, -10, 69, -5, 66, -9, 64, -5, 58, 2, 59, 23, -13, 26, -13, 40, -15, 49, -14,
+ 44, 3, 45, 6, 44, 34, 33, 54, 19, 82, 21, -10, 24, -11, 28, -8, 28, -1, 29, 3, 29, 9, 35, 20, 29, 36, 14, 67, -3, 75, -1, 23,
+ 1, 34, 1, 43, 0, 54, -2, 55, 0, 61, 1, 64, 0, 68, -9, 92, -6, 93, -6, 84, -8, 79, 0, 66, -1, 71, 0, 62, -2, 60, -2, 59,
+ -5, 75, -3, 62, -4, 58, -9, 66, -1, 79, 0, 71, 3, 68, 10, 44, -7, 62, 15, 36, 14, 40, 16, 27, 12, 29, 1, 44, 20, 36, 18, 32,
+ 5, 42, 1, 48, 10, 62, 17, 46, 9, 64, -12, 104, -11, 97, -16, 96, -7, 88, -8, 85, -7, 85, -9, 85, -13, 88, 4, 66, -3, 77, -3, 76,
+ -6, 76, 10, 58, -1, 76, -1, 83, -6, 93, -6, 84, -8, 79, 0, 66, -1, 71, 0, 62, -2, 60, -2, 59, -5, 75, -3, 62, -4, 58, -9, 66,
+ -1, 79, 0, 71, 3, 68, 10, 44, -7, 62, 15, 36, 14, 40, 16, 27, 12, 29, 1, 44, 20, 36, 18, 32, 5, 42, 1, 48, 10, 62, 17, 46,
+ 9, 64, -12, 104, -11, 97, -16, 96, -7, 88, -8, 85, -7, 85, -9, 85, -13, 88, 4, 66, -3, 77, -3, 76, -6, 76, 10, 58, -1, 76, -1, 83,
+ 15, 6, 6, 19, 7, 16, 12, 14, 18, 13, 13, 11, 13, 15, 15, 16, 12, 23, 13, 23, 15, 20, 14, 26, 14, 44, 17, 40, 17, 47, 24, 17,
+ 21, 21, 25, 22, 31, 27, 22, 29, 19, 35, 14, 50, 10, 57, 7, 63, -2, 77, -4, 82, -3, 94, 9, 69, -12, 109, 36, -35, 36, -34, 32, -26,
+ 37, -30, 44, -32, 34, -18, 34, -15, 40, -15, 33, -7, 35, -5, 33, 0, 38, 2, 33, 13, 23, 35, 13, 58, 15, 6, 6, 19, 7, 16, 12, 14,
+ 18, 13, 13, 11, 13, 15, 15, 16, 12, 23, 13, 23, 15, 20, 14, 26, 14, 44, 17, 40, 17, 47, 24, 17, 21, 21, 25, 22, 31, 27, 22, 29,
+ 19, 35, 14, 50, 10, 57, 7, 63, -2, 77, -4, 82, -3, 94, 9, 69, -12, 109, 36, -35, 36, -34, 32, -26, 37, -30, 44, -32, 34, -18, 34, -15,
+ 40, -15, 33, -7, 35, -5, 33, 0, 38, 2, 33, 13, 23, 35, 13, 58, -3, 71, -6, 42, -5, 50, -3, 54, -2, 62, 0, 58, 1, 63, -2, 72,
+ -1, 74, -9, 91, -5, 67, -5, 27, -3, 39, -2, 44, 0, 46, -16, 64, -8, 68, -10, 78, -6, 77, -10, 86, -12, 92, -15, 55, -10, 60, -6, 62,
+ -4, 65, -12, 73, -8, 76, -7, 80, -9, 88, -17, 110, -3, 71, -6, 42, -5, 50, -3, 54, -2, 62, 0, 58, 1, 63, -2, 72, -1, 74, -9, 91,
+ -5, 67, -5, 27, -3, 39, -2, 44, 0, 46, -16, 64, -8, 68, -10, 78, -6, 77, -10, 86, -12, 92, -15, 55, -10, 60, -6, 62, -4, 65, -12, 73,
+ -8, 76, -7, 80, -9, 88, -17, 110, -3, 70, -8, 93, -10, 90, -30, 127, -3, 70, -8, 93, -10, 90, -30, 127, -3, 70, -8, 93, -10, 90, -30, 127,
+]
+
+export const CABAC_INIT_P: i8[] = [
+ 20, -15, 2, 54, 3, 74, 20, -15, 2, 54, 3, 74, -28, 127, -23, 104, -6, 53, -1, 54, 7, 51, 23, 33, 23, 2, 21, 0, 1, 9, 0, 49,
+ -37, 118, 5, 57, -13, 78, -11, 65, 1, 62, 12, 49, -4, 73, 17, 50, 18, 64, 9, 43, 29, 0, 26, 67, 16, 90, 9, 104, -46, 127, -20, 104,
+ 1, 67, -13, 78, -11, 65, 1, 62, -6, 86, -17, 95, -6, 61, 9, 45, -3, 69, -6, 81, -11, 96, 6, 55, 7, 67, -5, 86, 2, 88, 0, 58,
+ -3, 76, -10, 94, 5, 54, 4, 69, -3, 81, 0, 88, -7, 67, -5, 74, -4, 74, -5, 80, -7, 72, 1, 58, 0, 41, 0, 63, 0, 63, 0, 63,
+ -9, 83, 4, 86, 0, 97, -7, 72, 13, 41, 3, 62, 0, 45, -4, 78, -3, 96, -27, 126, -28, 98, -25, 101, -23, 67, -28, 82, -20, 94, -16, 83,
+ -22, 110, -21, 91, -18, 102, -13, 93, -29, 127, -7, 92, -5, 89, -7, 96, -13, 108, -3, 46, -1, 65, -1, 57, -9, 93, -3, 74, -9, 92, -8, 87,
+ -23, 126, 5, 54, 6, 60, 6, 59, 6, 69, -1, 48, 0, 68, -4, 69, -8, 88, -2, 85, -6, 78, -1, 75, -7, 77, 2, 54, 5, 50, -3, 68,
+ 1, 50, 6, 42, -4, 81, 1, 63, -4, 70, 0, 67, 2, 57, -2, 76, 11, 35, 4, 64, 1, 61, 11, 35, 18, 25, 12, 24, 13, 29, 13, 36,
+ -10, 93, -7, 73, -2, 73, 13, 46, 9, 49, -7, 100, 9, 53, 2, 53, 5, 53, -2, 61, 0, 56, 0, 56, -13, 63, -5, 60, -1, 62, 4, 57,
+ -6, 69, 4, 57, 14, 39, 4, 51, 13, 68, 3, 64, 1, 61, 9, 63, 7, 50, 16, 39, 5, 44, 4, 52, 11, 48, -5, 60, -1, 59, 0, 59,
+ 22, 33, 5, 44, 14, 43, -1, 78, 0, 60, 9, 69, 11, 28, 2, 40, 3, 44, 0, 49, 0, 46, 2, 44, 2, 51, 0, 47, 4, 39, 2, 62,
+ 6, 46, 0, 54, 3, 54, 2, 58, 4, 63, 6, 51, 6, 57, 7, 53, 6, 52, 6, 55, 11, 45, 14, 36, 8, 53, -1, 82, 7, 55, -3, 78,
+ 15, 46, 22, 31, -1, 84, 25, 7, 30, -7, 28, 3, 28, 4, 32, 0, 34, -1, 30, 6, 30, 6, 32, 9, 31, 19, 26, 27, 26, 30, 37, 20,
+ 28, 34, 17, 70, 1, 67, 5, 59, 9, 67, 16, 30, 18, 32, 18, 35, 22, 29, 24, 31, 23, 38, 18, 43, 20, 41, 11, 63, 9, 59, 9, 64,
+ -1, 94, -2, 89, -9, 108, -6, 76, -2, 44, 0, 45, 0, 52, -3, 64, -2, 59, -4, 70, -4, 75, -8, 82, -17, 102, -9, 77, 3, 24, 0, 42,
+ 0, 48, 0, 55, -6, 59, -7, 71, -12, 83, -11, 87, -30, 119, 1, 58, -3, 29, -1, 36, 1, 38, 2, 43, -6, 55, 0, 58, 0, 64, -3, 74,
+ -10, 90, 0, 70, -4, 29, 5, 31, 7, 42, 1, 59, -2, 58, -3, 72, -3, 81, -11, 97, 0, 58, 8, 5, 10, 14, 14, 18, 13, 27, 2, 40,
+ 0, 58, -3, 70, -6, 79, -8, 85, 0, 0, -13, 106, -16, 106, -10, 87, -21, 114, -18, 110, -14, 98, -22, 110, -21, 106, -18, 103, -21, 107, -23, 108,
+ -26, 112, -10, 96, -12, 95, -5, 91, -9, 93, -22, 94, -5, 86, 9, 67, -4, 80, -10, 85, -1, 70, 7, 60, 9, 58, 5, 61, 12, 50, 15, 50,
+ 18, 49, 17, 54, 10, 41, 7, 46, -1, 51, 7, 49, 8, 52, 9, 41, 6, 47, 2, 55, 13, 41, 10, 44, 6, 50, 5, 53, 13, 49, 4, 63,
+ 6, 64, -2, 69, -2, 59, 6, 70, 10, 44, 9, 31, 12, 43, 3, 53, 14, 34, 10, 38, -3, 52, 13, 40, 17, 32, 7, 44, 7, 38, 13, 50,
+ 10, 57, 26, 43, 14, 11, 11, 14, 9, 11, 18, 11, 21, 9, 23, -2, 32, -15, 32, -15, 34, -21, 39, -23, 42, -33, 41, -31, 46, -28, 38, -12,
+ 21, 29, 45, -24, 53, -45, 48, -26, 65, -43, 43, -19, 39, -10, 30, 9, 18, 26, 20, 27, 0, 57, -14, 82, -5, 75, -19, 97, -35, 125, 27, 0,
+ 28, 0, 31, -4, 27, 6, 34, 8, 30, 10, 24, 22, 33, 19, 22, 32, 26, 31, 21, 41, 26, 44, 23, 47, 16, 65, 14, 71, 8, 60, 6, 63,
+ 17, 65, 21, 24, 23, 20, 26, 23, 27, 32, 28, 23, 28, 24, 23, 40, 24, 32, 28, 29, 23, 42, 19, 57, 22, 53, 22, 61, 11, 86, 12, 40,
+ 11, 51, 14, 59, -4, 79, -7, 71, -5, 69, -9, 70, -8, 66, -10, 68, -19, 73, -12, 69, -16, 70, -15, 67, -20, 62, -19, 70, -16, 66, -22, 65,
+ -20, 63, 9, -2, 26, -9, 33, -9, 39, -7, 41, -2, 45, 3, 49, 9, 45, 27, 36, 59, -6, 66, -7, 35, -7, 42, -8, 45, -5, 48, -12, 56,
+ -6, 60, -5, 62, -8, 66, -8, 76, -5, 85, -6, 81, -10, 77, -7, 81, -17, 80, -18, 73, -4, 74, -10, 83, -9, 71, -9, 67, -1, 61, -8, 66,
+ -14, 66, 0, 59, 2, 59, 21, -13, 33, -14, 39, -7, 46, -2, 51, 2, 60, 6, 61, 17, 55, 34, 42, 62, -7, 92, -5, 89, -7, 96, -13, 108,
+ -3, 46, -1, 65, -1, 57, -9, 93, -3, 74, -9, 92, -8, 87, -23, 126, -7, 92, -5, 89, -7, 96, -13, 108, -3, 46, -1, 65, -1, 57, -9, 93,
+ -3, 74, -9, 92, -8, 87, -23, 126, -2, 85, -6, 78, -1, 75, -7, 77, 2, 54, 5, 50, -3, 68, 1, 50, 6, 42, -4, 81, 1, 63, -4, 70,
+ 0, 67, 2, 57, -2, 76, 11, 35, 4, 64, 1, 61, 11, 35, 18, 25, 12, 24, 13, 29, 13, 36, -10, 93, -7, 73, -2, 73, 13, 46, 9, 49,
+ -7, 100, 9, 53, 2, 53, 5, 53, -2, 61, 0, 56, 0, 56, -13, 63, -5, 60, -1, 62, 4, 57, -6, 69, 4, 57, 14, 39, 4, 51, 13, 68,
+ -2, 85, -6, 78, -1, 75, -7, 77, 2, 54, 5, 50, -3, 68, 1, 50, 6, 42, -4, 81, 1, 63, -4, 70, 0, 67, 2, 57, -2, 76, 11, 35,
+ 4, 64, 1, 61, 11, 35, 18, 25, 12, 24, 13, 29, 13, 36, -10, 93, -7, 73, -2, 73, 13, 46, 9, 49, -7, 100, 9, 53, 2, 53, 5, 53,
+ -2, 61, 0, 56, 0, 56, -13, 63, -5, 60, -1, 62, 4, 57, -6, 69, 4, 57, 14, 39, 4, 51, 13, 68, 11, 28, 2, 40, 3, 44, 0, 49,
+ 0, 46, 2, 44, 2, 51, 0, 47, 4, 39, 2, 62, 6, 46, 0, 54, 3, 54, 2, 58, 4, 63, 6, 51, 6, 57, 7, 53, 6, 52, 6, 55,
+ 11, 45, 14, 36, 8, 53, -1, 82, 7, 55, -3, 78, 15, 46, 22, 31, -1, 84, 25, 7, 30, -7, 28, 3, 28, 4, 32, 0, 34, -1, 30, 6,
+ 30, 6, 32, 9, 31, 19, 26, 27, 26, 30, 37, 20, 28, 34, 17, 70, 11, 28, 2, 40, 3, 44, 0, 49, 0, 46, 2, 44, 2, 51, 0, 47,
+ 4, 39, 2, 62, 6, 46, 0, 54, 3, 54, 2, 58, 4, 63, 6, 51, 6, 57, 7, 53, 6, 52, 6, 55, 11, 45, 14, 36, 8, 53, -1, 82,
+ 7, 55, -3, 78, 15, 46, 22, 31, -1, 84, 25, 7, 30, -7, 28, 3, 28, 4, 32, 0, 34, -1, 30, 6, 30, 6, 32, 9, 31, 19, 26, 27,
+ 26, 30, 37, 20, 28, 34, 17, 70, -4, 79, -7, 71, -5, 69, -9, 70, -8, 66, -10, 68, -19, 73, -12, 69, -16, 70, -15, 67, -20, 62, -19, 70,
+ -16, 66, -22, 65, -20, 63, -5, 85, -6, 81, -10, 77, -7, 81, -17, 80, -18, 73, -4, 74, -10, 83, -9, 71, -9, 67, -1, 61, -8, 66, -14, 66,
+ 0, 59, 2, 59, 9, -2, 26, -9, 33, -9, 39, -7, 41, -2, 45, 3, 49, 9, 45, 27, 36, 59, 21, -13, 33, -14, 39, -7, 46, -2, 51, 2,
+ 60, 6, 61, 17, 55, 34, 42, 62, -6, 66, -7, 35, -7, 42, -8, 45, -5, 48, -12, 56, -6, 60, -5, 62, -8, 66, -8, 76, -4, 79, -7, 71,
+ -5, 69, -9, 70, -8, 66, -10, 68, -19, 73, -12, 69, -16, 70, -15, 67, -20, 62, -19, 70, -16, 66, -22, 65, -20, 63, -5, 85, -6, 81, -10, 77,
+ -7, 81, -17, 80, -18, 73, -4, 74, -10, 83, -9, 71, -9, 67, -1, 61, -8, 66, -14, 66, 0, 59, 2, 59, 9, -2, 26, -9, 33, -9, 39, -7,
+ 41, -2, 45, 3, 49, 9, 45, 27, 36, 59, 21, -13, 33, -14, 39, -7, 46, -2, 51, 2, 60, 6, 61, 17, 55, 34, 42, 62, -6, 66, -7, 35,
+ -7, 42, -8, 45, -5, 48, -12, 56, -6, 60, -5, 62, -8, 66, -8, 76, -13, 106, -16, 106, -10, 87, -21, 114, -18, 110, -14, 98, -22, 110, -21, 106,
+ -18, 103, -21, 107, -23, 108, -26, 112, -10, 96, -12, 95, -5, 91, -9, 93, -22, 94, -5, 86, 9, 67, -4, 80, -10, 85, -1, 70, 7, 60, 9, 58,
+ 5, 61, 12, 50, 15, 50, 18, 49, 17, 54, 10, 41, 7, 46, -1, 51, 7, 49, 8, 52, 9, 41, 6, 47, 2, 55, 13, 41, 10, 44, 6, 50,
+ 5, 53, 13, 49, 4, 63, 6, 64, -13, 106, -16, 106, -10, 87, -21, 114, -18, 110, -14, 98, -22, 110, -21, 106, -18, 103, -21, 107, -23, 108, -26, 112,
+ -10, 96, -12, 95, -5, 91, -9, 93, -22, 94, -5, 86, 9, 67, -4, 80, -10, 85, -1, 70, 7, 60, 9, 58, 5, 61, 12, 50, 15, 50, 18, 49,
+ 17, 54, 10, 41, 7, 46, -1, 51, 7, 49, 8, 52, 9, 41, 6, 47, 2, 55, 13, 41, 10, 44, 6, 50, 5, 53, 13, 49, 4, 63, 6, 64,
+ 14, 11, 11, 14, 9, 11, 18, 11, 21, 9, 23, -2, 32, -15, 32, -15, 34, -21, 39, -23, 42, -33, 41, -31, 46, -28, 38, -12, 21, 29, 45, -24,
+ 53, -45, 48, -26, 65, -43, 43, -19, 39, -10, 30, 9, 18, 26, 20, 27, 0, 57, -14, 82, -5, 75, -19, 97, -35, 125, 27, 0, 28, 0, 31, -4,
+ 27, 6, 34, 8, 30, 10, 24, 22, 33, 19, 22, 32, 26, 31, 21, 41, 26, 44, 23, 47, 16, 65, 14, 71, 14, 11, 11, 14, 9, 11, 18, 11,
+ 21, 9, 23, -2, 32, -15, 32, -15, 34, -21, 39, -23, 42, -33, 41, -31, 46, -28, 38, -12, 21, 29, 45, -24, 53, -45, 48, -26, 65, -43, 43, -19,
+ 39, -10, 30, 9, 18, 26, 20, 27, 0, 57, -14, 82, -5, 75, -19, 97, -35, 125, 27, 0, 28, 0, 31, -4, 27, 6, 34, 8, 30, 10, 24, 22,
+ 33, 19, 22, 32, 26, 31, 21, 41, 26, 44, 23, 47, 16, 65, 14, 71, -6, 76, -2, 44, 0, 45, 0, 52, -3, 64, -2, 59, -4, 70, -4, 75,
+ -8, 82, -17, 102, -9, 77, 3, 24, 0, 42, 0, 48, 0, 55, -6, 59, -7, 71, -12, 83, -11, 87, -30, 119, 1, 58, -3, 29, -1, 36, 1, 38,
+ 2, 43, -6, 55, 0, 58, 0, 64, -3, 74, -10, 90, -6, 76, -2, 44, 0, 45, 0, 52, -3, 64, -2, 59, -4, 70, -4, 75, -8, 82, -17, 102,
+ -9, 77, 3, 24, 0, 42, 0, 48, 0, 55, -6, 59, -7, 71, -12, 83, -11, 87, -30, 119, 1, 58, -3, 29, -1, 36, 1, 38, 2, 43, -6, 55,
+ 0, 58, 0, 64, -3, 74, -10, 90, -3, 74, -9, 92, -8, 87, -23, 126, -3, 74, -9, 92, -8, 87, -23, 126, -3, 74, -9, 92, -8, 87, -23, 126,
+ 20, -15, 2, 54, 3, 74, 20, -15, 2, 54, 3, 74, -28, 127, -23, 104, -6, 53, -1, 54, 7, 51, 22, 25, 34, 0, 16, 0, -2, 9, 4, 41,
+ -29, 118, 2, 65, -6, 71, -13, 79, 5, 52, 9, 50, -3, 70, 10, 54, 26, 34, 19, 22, 40, 0, 57, 2, 41, 36, 26, 69, -45, 127, -15, 101,
+ -4, 76, -6, 71, -13, 79, 5, 52, 6, 69, -13, 90, 0, 52, 8, 43, -2, 69, -5, 82, -10, 96, 2, 59, 2, 75, -3, 87, -3, 100, 1, 56,
+ -3, 74, -6, 85, 0, 59, -3, 81, -7, 86, -5, 95, -1, 66, -1, 77, 1, 70, -2, 86, -5, 72, 0, 61, 0, 41, 0, 63, 0, 63, 0, 63,
+ -9, 83, 4, 86, 0, 97, -7, 72, 13, 41, 3, 62, 13, 15, 7, 51, 2, 80, -39, 127, -18, 91, -17, 96, -26, 81, -35, 98, -24, 102, -23, 97,
+ -27, 119, -24, 99, -21, 110, -18, 102, -36, 127, 0, 80, -5, 89, -7, 94, -4, 92, 0, 39, 0, 65, -15, 84, -35, 127, -2, 73, -12, 104, -9, 91,
+ -31, 127, 3, 55, 7, 56, 7, 55, 8, 61, -3, 53, 0, 68, -7, 74, -9, 88, -13, 103, -13, 91, -9, 89, -14, 92, -8, 76, -12, 87, -23, 110,
+ -24, 105, -10, 78, -20, 112, -17, 99, -78, 127, -70, 127, -50, 127, -46, 127, -4, 66, -5, 78, -4, 71, -8, 72, 2, 59, -1, 55, -7, 70, -6, 75,
+ -8, 89, -34, 119, -3, 75, 32, 20, 30, 22, -44, 127, 0, 54, -5, 61, 0, 58, -1, 60, -3, 61, -8, 67, -25, 84, -14, 74, -5, 65, 5, 52,
+ 2, 57, 0, 61, -9, 69, -11, 70, 18, 55, -4, 71, 0, 58, 7, 61, 9, 41, 18, 25, 9, 32, 5, 43, 9, 47, 0, 44, 0, 51, 2, 46,
+ 19, 38, -4, 66, 15, 38, 12, 42, 9, 34, 0, 89, 4, 45, 10, 28, 10, 31, 33, -11, 52, -43, 18, 15, 28, 0, 35, -22, 38, -25, 34, 0,
+ 39, -18, 32, -12, 102, -94, 0, 0, 56, -15, 33, -4, 29, 10, 37, -5, 51, -29, 39, -9, 52, -34, 69, -58, 67, -63, 44, -5, 32, 7, 55, -29,
+ 32, 1, 0, 0, 27, 36, 33, -25, 34, -30, 36, -28, 38, -28, 38, -27, 34, -18, 35, -16, 34, -14, 32, -8, 37, -6, 35, 0, 30, 10, 28, 18,
+ 26, 25, 29, 41, 0, 75, 2, 72, 8, 77, 14, 35, 18, 31, 17, 35, 21, 30, 17, 45, 20, 42, 18, 45, 27, 26, 16, 54, 7, 66, 16, 56,
+ 11, 73, 10, 67, -10, 116, -23, 112, -15, 71, -7, 61, 0, 53, -5, 66, -11, 77, -9, 80, -9, 84, -10, 87, -34, 127, -21, 101, -3, 39, -5, 53,
+ -7, 61, -11, 75, -15, 77, -17, 91, -25, 107, -25, 111, -28, 122, -11, 76, -10, 44, -10, 52, -10, 57, -9, 58, -16, 72, -7, 69, -4, 69, -5, 74,
+ -9, 86, 2, 66, -9, 34, 1, 32, 11, 31, 5, 52, -2, 55, -2, 67, 0, 73, -8, 89, 3, 52, 7, 4, 10, 8, 17, 8, 16, 19, 3, 37,
+ -1, 61, -5, 73, -1, 70, -4, 78, 0, 0, -21, 126, -23, 124, -20, 110, -26, 126, -25, 124, -17, 105, -27, 121, -27, 117, -17, 102, -26, 117, -27, 116,
+ -33, 122, -10, 95, -14, 100, -8, 95, -17, 111, -28, 114, -6, 89, -2, 80, -4, 82, -9, 85, -8, 81, -1, 72, 5, 64, 1, 67, 9, 56, 0, 69,
+ 1, 69, 7, 69, -7, 69, -6, 67, -16, 77, -2, 64, 2, 61, -6, 67, -3, 64, 2, 57, -3, 65, -3, 66, 0, 62, 9, 51, -1, 66, -2, 71,
+ -2, 75, -1, 70, -9, 72, 14, 60, 16, 37, 0, 47, 18, 35, 11, 37, 12, 41, 10, 41, 2, 48, 12, 41, 13, 41, 0, 59, 3, 50, 19, 40,
+ 3, 66, 18, 50, 19, -6, 18, -6, 14, 0, 26, -12, 31, -16, 33, -25, 33, -22, 37, -28, 39, -30, 42, -30, 47, -42, 45, -36, 49, -34, 41, -17,
+ 32, 9, 69, -71, 63, -63, 66, -64, 77, -74, 54, -39, 52, -35, 41, -10, 36, 0, 40, -1, 30, 14, 28, 26, 23, 37, 12, 55, 11, 65, 37, -33,
+ 39, -36, 40, -37, 38, -30, 46, -33, 42, -30, 40, -24, 49, -29, 38, -12, 40, -10, 38, -3, 46, -5, 31, 20, 29, 30, 25, 44, 12, 48, 11, 49,
+ 26, 45, 22, 22, 23, 22, 27, 21, 33, 20, 26, 28, 30, 24, 27, 34, 18, 42, 25, 39, 18, 50, 12, 70, 21, 54, 14, 71, 11, 83, 25, 32,
+ 21, 49, 21, 54, -5, 85, -6, 81, -10, 77, -7, 81, -17, 80, -18, 73, -4, 74, -10, 83, -9, 71, -9, 67, -1, 61, -8, 66, -14, 66, 0, 59,
+ 2, 59, 17, -10, 32, -13, 42, -9, 49, -5, 53, 0, 64, 3, 68, 10, 66, 27, 47, 57, -5, 71, 0, 24, -1, 36, -2, 42, -2, 52, -9, 57,
+ -6, 63, -4, 65, -4, 67, -7, 82, -3, 81, -3, 76, -7, 72, -6, 78, -12, 72, -14, 68, -3, 70, -6, 76, -5, 66, -5, 62, 0, 57, -4, 61,
+ -9, 60, 1, 54, 2, 58, 17, -10, 32, -13, 42, -9, 49, -5, 53, 0, 64, 3, 68, 10, 66, 27, 47, 57, 0, 80, -5, 89, -7, 94, -4, 92,
+ 0, 39, 0, 65, -15, 84, -35, 127, -2, 73, -12, 104, -9, 91, -31, 127, 0, 80, -5, 89, -7, 94, -4, 92, 0, 39, 0, 65, -15, 84, -35, 127,
+ -2, 73, -12, 104, -9, 91, -31, 127, -13, 103, -13, 91, -9, 89, -14, 92, -8, 76, -12, 87, -23, 110, -24, 105, -10, 78, -20, 112, -17, 99, -78, 127,
+ -70, 127, -50, 127, -46, 127, -4, 66, -5, 78, -4, 71, -8, 72, 2, 59, -1, 55, -7, 70, -6, 75, -8, 89, -34, 119, -3, 75, 32, 20, 30, 22,
+ -44, 127, 0, 54, -5, 61, 0, 58, -1, 60, -3, 61, -8, 67, -25, 84, -14, 74, -5, 65, 5, 52, 2, 57, 0, 61, -9, 69, -11, 70, 18, 55,
+ -13, 103, -13, 91, -9, 89, -14, 92, -8, 76, -12, 87, -23, 110, -24, 105, -10, 78, -20, 112, -17, 99, -78, 127, -70, 127, -50, 127, -46, 127, -4, 66,
+ -5, 78, -4, 71, -8, 72, 2, 59, -1, 55, -7, 70, -6, 75, -8, 89, -34, 119, -3, 75, 32, 20, 30, 22, -44, 127, 0, 54, -5, 61, 0, 58,
+ -1, 60, -3, 61, -8, 67, -25, 84, -14, 74, -5, 65, 5, 52, 2, 57, 0, 61, -9, 69, -11, 70, 18, 55, 4, 45, 10, 28, 10, 31, 33, -11,
+ 52, -43, 18, 15, 28, 0, 35, -22, 38, -25, 34, 0, 39, -18, 32, -12, 102, -94, 0, 0, 56, -15, 33, -4, 29, 10, 37, -5, 51, -29, 39, -9,
+ 52, -34, 69, -58, 67, -63, 44, -5, 32, 7, 55, -29, 32, 1, 0, 0, 27, 36, 33, -25, 34, -30, 36, -28, 38, -28, 38, -27, 34, -18, 35, -16,
+ 34, -14, 32, -8, 37, -6, 35, 0, 30, 10, 28, 18, 26, 25, 29, 41, 4, 45, 10, 28, 10, 31, 33, -11, 52, -43, 18, 15, 28, 0, 35, -22,
+ 38, -25, 34, 0, 39, -18, 32, -12, 102, -94, 0, 0, 56, -15, 33, -4, 29, 10, 37, -5, 51, -29, 39, -9, 52, -34, 69, -58, 67, -63, 44, -5,
+ 32, 7, 55, -29, 32, 1, 0, 0, 27, 36, 33, -25, 34, -30, 36, -28, 38, -28, 38, -27, 34, -18, 35, -16, 34, -14, 32, -8, 37, -6, 35, 0,
+ 30, 10, 28, 18, 26, 25, 29, 41, -5, 85, -6, 81, -10, 77, -7, 81, -17, 80, -18, 73, -4, 74, -10, 83, -9, 71, -9, 67, -1, 61, -8, 66,
+ -14, 66, 0, 59, 2, 59, -3, 81, -3, 76, -7, 72, -6, 78, -12, 72, -14, 68, -3, 70, -6, 76, -5, 66, -5, 62, 0, 57, -4, 61, -9, 60,
+ 1, 54, 2, 58, 17, -10, 32, -13, 42, -9, 49, -5, 53, 0, 64, 3, 68, 10, 66, 27, 47, 57, 17, -10, 32, -13, 42, -9, 49, -5, 53, 0,
+ 64, 3, 68, 10, 66, 27, 47, 57, -5, 71, 0, 24, -1, 36, -2, 42, -2, 52, -9, 57, -6, 63, -4, 65, -4, 67, -7, 82, -5, 85, -6, 81,
+ -10, 77, -7, 81, -17, 80, -18, 73, -4, 74, -10, 83, -9, 71, -9, 67, -1, 61, -8, 66, -14, 66, 0, 59, 2, 59, -3, 81, -3, 76, -7, 72,
+ -6, 78, -12, 72, -14, 68, -3, 70, -6, 76, -5, 66, -5, 62, 0, 57, -4, 61, -9, 60, 1, 54, 2, 58, 17, -10, 32, -13, 42, -9, 49, -5,
+ 53, 0, 64, 3, 68, 10, 66, 27, 47, 57, 17, -10, 32, -13, 42, -9, 49, -5, 53, 0, 64, 3, 68, 10, 66, 27, 47, 57, -5, 71, 0, 24,
+ -1, 36, -2, 42, -2, 52, -9, 57, -6, 63, -4, 65, -4, 67, -7, 82, -21, 126, -23, 124, -20, 110, -26, 126, -25, 124, -17, 105, -27, 121, -27, 117,
+ -17, 102, -26, 117, -27, 116, -33, 122, -10, 95, -14, 100, -8, 95, -17, 111, -28, 114, -6, 89, -2, 80, -4, 82, -9, 85, -8, 81, -1, 72, 5, 64,
+ 1, 67, 9, 56, 0, 69, 1, 69, 7, 69, -7, 69, -6, 67, -16, 77, -2, 64, 2, 61, -6, 67, -3, 64, 2, 57, -3, 65, -3, 66, 0, 62,
+ 9, 51, -1, 66, -2, 71, -2, 75, -21, 126, -23, 124, -20, 110, -26, 126, -25, 124, -17, 105, -27, 121, -27, 117, -17, 102, -26, 117, -27, 116, -33, 122,
+ -10, 95, -14, 100, -8, 95, -17, 111, -28, 114, -6, 89, -2, 80, -4, 82, -9, 85, -8, 81, -1, 72, 5, 64, 1, 67, 9, 56, 0, 69, 1, 69,
+ 7, 69, -7, 69, -6, 67, -16, 77, -2, 64, 2, 61, -6, 67, -3, 64, 2, 57, -3, 65, -3, 66, 0, 62, 9, 51, -1, 66, -2, 71, -2, 75,
+ 19, -6, 18, -6, 14, 0, 26, -12, 31, -16, 33, -25, 33, -22, 37, -28, 39, -30, 42, -30, 47, -42, 45, -36, 49, -34, 41, -17, 32, 9, 69, -71,
+ 63, -63, 66, -64, 77, -74, 54, -39, 52, -35, 41, -10, 36, 0, 40, -1, 30, 14, 28, 26, 23, 37, 12, 55, 11, 65, 37, -33, 39, -36, 40, -37,
+ 38, -30, 46, -33, 42, -30, 40, -24, 49, -29, 38, -12, 40, -10, 38, -3, 46, -5, 31, 20, 29, 30, 25, 44, 19, -6, 18, -6, 14, 0, 26, -12,
+ 31, -16, 33, -25, 33, -22, 37, -28, 39, -30, 42, -30, 47, -42, 45, -36, 49, -34, 41, -17, 32, 9, 69, -71, 63, -63, 66, -64, 77, -74, 54, -39,
+ 52, -35, 41, -10, 36, 0, 40, -1, 30, 14, 28, 26, 23, 37, 12, 55, 11, 65, 37, -33, 39, -36, 40, -37, 38, -30, 46, -33, 42, -30, 40, -24,
+ 49, -29, 38, -12, 40, -10, 38, -3, 46, -5, 31, 20, 29, 30, 25, 44, -23, 112, -15, 71, -7, 61, 0, 53, -5, 66, -11, 77, -9, 80, -9, 84,
+ -10, 87, -34, 127, -21, 101, -3, 39, -5, 53, -7, 61, -11, 75, -15, 77, -17, 91, -25, 107, -25, 111, -28, 122, -11, 76, -10, 44, -10, 52, -10, 57,
+ -9, 58, -16, 72, -7, 69, -4, 69, -5, 74, -9, 86, -23, 112, -15, 71, -7, 61, 0, 53, -5, 66, -11, 77, -9, 80, -9, 84, -10, 87, -34, 127,
+ -21, 101, -3, 39, -5, 53, -7, 61, -11, 75, -15, 77, -17, 91, -25, 107, -25, 111, -28, 122, -11, 76, -10, 44, -10, 52, -10, 57, -9, 58, -16, 72,
+ -7, 69, -4, 69, -5, 74, -9, 86, -2, 73, -12, 104, -9, 91, -31, 127, -2, 73, -12, 104, -9, 91, -31, 127, -2, 73, -12, 104, -9, 91, -31, 127,
+ 20, -15, 2, 54, 3, 74, 20, -15, 2, 54, 3, 74, -28, 127, -23, 104, -6, 53, -1, 54, 7, 51, 29, 16, 25, 0, 14, 0, -10, 51, -3, 62,
+ -27, 99, 26, 16, -4, 85, -24, 102, 5, 57, 6, 57, -17, 73, 14, 57, 20, 40, 20, 10, 29, 0, 54, 0, 37, 42, 12, 97, -32, 127, -22, 117,
+ -2, 74, -4, 85, -24, 102, 5, 57, -6, 93, -14, 88, -6, 44, 4, 55, -11, 89, -15, 103, -21, 116, 19, 57, 20, 58, 4, 84, 6, 96, 1, 63,
+ -5, 85, -13, 106, 5, 63, 6, 75, -3, 90, -1, 101, 3, 55, -4, 79, -2, 75, -12, 97, -7, 50, 1, 60, 0, 41, 0, 63, 0, 63, 0, 63,
+ -9, 83, 4, 86, 0, 97, -7, 72, 13, 41, 3, 62, 7, 34, -9, 88, -20, 127, -36, 127, -17, 91, -14, 95, -25, 84, -25, 86, -12, 89, -17, 91,
+ -31, 127, -14, 76, -18, 103, -13, 90, -37, 127, 11, 80, 5, 76, 2, 84, 5, 78, -6, 55, 4, 61, -14, 83, -37, 127, -5, 79, -11, 104, -11, 91,
+ -30, 127, 0, 65, -2, 79, 0, 72, -4, 92, -6, 56, 3, 68, -8, 71, -13, 98, -4, 86, -12, 88, -5, 82, -3, 72, -4, 67, -8, 72, -16, 89,
+ -9, 69, -1, 59, 5, 66, 4, 57, -4, 71, -2, 71, 2, 58, -1, 74, -4, 44, -1, 69, 0, 62, -7, 51, -4, 47, -6, 42, -3, 41, -6, 53,
+ 8, 76, -9, 78, -11, 83, 9, 52, 0, 67, -5, 90, 1, 67, -15, 72, -5, 75, -8, 80, -21, 83, -21, 64, -13, 31, -25, 64, -29, 94, 9, 75,
+ 17, 63, -8, 74, -5, 35, -2, 27, 13, 91, 3, 65, -7, 69, 8, 77, -10, 66, 3, 62, -3, 68, -20, 81, 0, 30, 1, 7, -3, 23, -21, 74,
+ 16, 66, -23, 124, 17, 37, 44, -18, 50, -34, -22, 127, 4, 39, 0, 42, 7, 34, 11, 29, 8, 31, 6, 37, 7, 42, 3, 40, 8, 33, 13, 43,
+ 13, 36, 4, 47, 3, 55, 2, 58, 6, 60, 8, 44, 11, 44, 14, 42, 7, 48, 4, 56, 4, 52, 13, 37, 9, 49, 19, 58, 10, 48, 12, 45,
+ 0, 69, 20, 33, 8, 63, 35, -18, 33, -25, 28, -3, 24, 10, 27, 0, 34, -14, 52, -44, 39, -24, 19, 17, 31, 25, 36, 29, 24, 33, 34, 15,
+ 30, 20, 22, 73, 20, 34, 19, 31, 27, 44, 19, 16, 15, 36, 15, 36, 21, 28, 25, 21, 30, 20, 31, 12, 27, 16, 24, 42, 0, 93, 14, 56,
+ 15, 57, 26, 38, -24, 127, -24, 115, -22, 82, -9, 62, 0, 53, 0, 59, -14, 85, -13, 89, -13, 94, -11, 92, -29, 127, -21, 100, -14, 57, -12, 67,
+ -11, 71, -10, 77, -21, 85, -16, 88, -23, 104, -15, 98, -37, 127, -10, 82, -8, 48, -8, 61, -8, 66, -7, 70, -14, 75, -10, 79, -9, 83, -12, 92,
+ -18, 108, -4, 79, -22, 69, -16, 75, -2, 58, 1, 58, -13, 78, -9, 83, -4, 81, -13, 99, -13, 81, -6, 38, -13, 62, -6, 58, -2, 59, -16, 73,
+ -10, 76, -13, 86, -9, 83, -10, 87, 0, 0, -22, 127, -25, 127, -25, 120, -27, 127, -19, 114, -23, 117, -25, 118, -26, 117, -24, 113, -28, 118, -31, 120,
+ -37, 124, -10, 94, -15, 102, -10, 99, -13, 106, -50, 127, -5, 92, 17, 57, -5, 86, -13, 94, -12, 91, -2, 77, 0, 71, -1, 73, 4, 64, -7, 81,
+ 5, 64, 15, 57, 1, 67, 0, 68, -10, 67, 1, 68, 0, 77, 2, 64, 0, 68, -5, 78, 7, 55, 5, 59, 2, 65, 14, 54, 15, 44, 5, 60,
+ 2, 70, -2, 76, -18, 86, 12, 70, 5, 64, -12, 70, 11, 55, 5, 56, 0, 69, 2, 65, -6, 74, 5, 54, 7, 54, -6, 76, -11, 82, -2, 77,
+ -2, 77, 25, 42, 17, -13, 16, -9, 17, -12, 27, -21, 37, -30, 41, -40, 42, -41, 48, -47, 39, -32, 46, -40, 52, -51, 46, -41, 52, -39, 43, -19,
+ 32, 11, 61, -55, 56, -46, 62, -50, 81, -67, 45, -20, 35, -2, 28, 15, 34, 1, 39, 1, 30, 17, 20, 38, 18, 45, 15, 54, 0, 79, 36, -16,
+ 37, -14, 37, -17, 32, 1, 34, 15, 29, 15, 24, 25, 34, 22, 31, 16, 35, 18, 31, 28, 33, 41, 36, 28, 27, 47, 21, 62, 18, 31, 19, 26,
+ 36, 24, 24, 23, 27, 16, 24, 30, 31, 29, 22, 41, 22, 42, 16, 60, 15, 52, 14, 60, 3, 78, -16, 123, 21, 53, 22, 56, 25, 61, 21, 33,
+ 19, 50, 17, 61, -3, 78, -8, 74, -9, 72, -10, 72, -18, 75, -12, 71, -11, 63, -5, 70, -17, 75, -14, 72, -16, 67, -8, 53, -14, 59, -9, 52,
+ -11, 68, 9, -2, 30, -10, 31, -4, 33, -1, 33, 7, 31, 12, 37, 23, 31, 38, 20, 64, -9, 71, -7, 37, -8, 44, -11, 49, -10, 56, -12, 59,
+ -8, 63, -9, 67, -6, 68, -10, 79, -3, 78, -8, 74, -9, 72, -10, 72, -18, 75, -12, 71, -11, 63, -5, 70, -17, 75, -14, 72, -16, 67, -8, 53,
+ -14, 59, -9, 52, -11, 68, 9, -2, 30, -10, 31, -4, 33, -1, 33, 7, 31, 12, 37, 23, 31, 38, 20, 64, 11, 80, 5, 76, 2, 84, 5, 78,
+ -6, 55, 4, 61, -14, 83, -37, 127, -5, 79, -11, 104, -11, 91, -30, 127, 11, 80, 5, 76, 2, 84, 5, 78, -6, 55, 4, 61, -14, 83, -37, 127,
+ -5, 79, -11, 104, -11, 91, -30, 127, -4, 86, -12, 88, -5, 82, -3, 72, -4, 67, -8, 72, -16, 89, -9, 69, -1, 59, 5, 66, 4, 57, -4, 71,
+ -2, 71, 2, 58, -1, 74, -4, 44, -1, 69, 0, 62, -7, 51, -4, 47, -6, 42, -3, 41, -6, 53, 8, 76, -9, 78, -11, 83, 9, 52, 0, 67,
+ -5, 90, 1, 67, -15, 72, -5, 75, -8, 80, -21, 83, -21, 64, -13, 31, -25, 64, -29, 94, 9, 75, 17, 63, -8, 74, -5, 35, -2, 27, 13, 91,
+ -4, 86, -12, 88, -5, 82, -3, 72, -4, 67, -8, 72, -16, 89, -9, 69, -1, 59, 5, 66, 4, 57, -4, 71, -2, 71, 2, 58, -1, 74, -4, 44,
+ -1, 69, 0, 62, -7, 51, -4, 47, -6, 42, -3, 41, -6, 53, 8, 76, -9, 78, -11, 83, 9, 52, 0, 67, -5, 90, 1, 67, -15, 72, -5, 75,
+ -8, 80, -21, 83, -21, 64, -13, 31, -25, 64, -29, 94, 9, 75, 17, 63, -8, 74, -5, 35, -2, 27, 13, 91, 4, 39, 0, 42, 7, 34, 11, 29,
+ 8, 31, 6, 37, 7, 42, 3, 40, 8, 33, 13, 43, 13, 36, 4, 47, 3, 55, 2, 58, 6, 60, 8, 44, 11, 44, 14, 42, 7, 48, 4, 56,
+ 4, 52, 13, 37, 9, 49, 19, 58, 10, 48, 12, 45, 0, 69, 20, 33, 8, 63, 35, -18, 33, -25, 28, -3, 24, 10, 27, 0, 34, -14, 52, -44,
+ 39, -24, 19, 17, 31, 25, 36, 29, 24, 33, 34, 15, 30, 20, 22, 73, 4, 39, 0, 42, 7, 34, 11, 29, 8, 31, 6, 37, 7, 42, 3, 40,
+ 8, 33, 13, 43, 13, 36, 4, 47, 3, 55, 2, 58, 6, 60, 8, 44, 11, 44, 14, 42, 7, 48, 4, 56, 4, 52, 13, 37, 9, 49, 19, 58,
+ 10, 48, 12, 45, 0, 69, 20, 33, 8, 63, 35, -18, 33, -25, 28, -3, 24, 10, 27, 0, 34, -14, 52, -44, 39, -24, 19, 17, 31, 25, 36, 29,
+ 24, 33, 34, 15, 30, 20, 22, 73, -3, 78, -8, 74, -9, 72, -10, 72, -18, 75, -12, 71, -11, 63, -5, 70, -17, 75, -14, 72, -16, 67, -8, 53,
+ -14, 59, -9, 52, -11, 68, -3, 78, -8, 74, -9, 72, -10, 72, -18, 75, -12, 71, -11, 63, -5, 70, -17, 75, -14, 72, -16, 67, -8, 53, -14, 59,
+ -9, 52, -11, 68, 9, -2, 30, -10, 31, -4, 33, -1, 33, 7, 31, 12, 37, 23, 31, 38, 20, 64, 9, -2, 30, -10, 31, -4, 33, -1, 33, 7,
+ 31, 12, 37, 23, 31, 38, 20, 64, -9, 71, -7, 37, -8, 44, -11, 49, -10, 56, -12, 59, -8, 63, -9, 67, -6, 68, -10, 79, -3, 78, -8, 74,
+ -9, 72, -10, 72, -18, 75, -12, 71, -11, 63, -5, 70, -17, 75, -14, 72, -16, 67, -8, 53, -14, 59, -9, 52, -11, 68, -3, 78, -8, 74, -9, 72,
+ -10, 72, -18, 75, -12, 71, -11, 63, -5, 70, -17, 75, -14, 72, -16, 67, -8, 53, -14, 59, -9, 52, -11, 68, 9, -2, 30, -10, 31, -4, 33, -1,
+ 33, 7, 31, 12, 37, 23, 31, 38, 20, 64, 9, -2, 30, -10, 31, -4, 33, -1, 33, 7, 31, 12, 37, 23, 31, 38, 20, 64, -9, 71, -7, 37,
+ -8, 44, -11, 49, -10, 56, -12, 59, -8, 63, -9, 67, -6, 68, -10, 79, -22, 127, -25, 127, -25, 120, -27, 127, -19, 114, -23, 117, -25, 118, -26, 117,
+ -24, 113, -28, 118, -31, 120, -37, 124, -10, 94, -15, 102, -10, 99, -13, 106, -50, 127, -5, 92, 17, 57, -5, 86, -13, 94, -12, 91, -2, 77, 0, 71,
+ -1, 73, 4, 64, -7, 81, 5, 64, 15, 57, 1, 67, 0, 68, -10, 67, 1, 68, 0, 77, 2, 64, 0, 68, -5, 78, 7, 55, 5, 59, 2, 65,
+ 14, 54, 15, 44, 5, 60, 2, 70, -22, 127, -25, 127, -25, 120, -27, 127, -19, 114, -23, 117, -25, 118, -26, 117, -24, 113, -28, 118, -31, 120, -37, 124,
+ -10, 94, -15, 102, -10, 99, -13, 106, -50, 127, -5, 92, 17, 57, -5, 86, -13, 94, -12, 91, -2, 77, 0, 71, -1, 73, 4, 64, -7, 81, 5, 64,
+ 15, 57, 1, 67, 0, 68, -10, 67, 1, 68, 0, 77, 2, 64, 0, 68, -5, 78, 7, 55, 5, 59, 2, 65, 14, 54, 15, 44, 5, 60, 2, 70,
+ 17, -13, 16, -9, 17, -12, 27, -21, 37, -30, 41, -40, 42, -41, 48, -47, 39, -32, 46, -40, 52, -51, 46, -41, 52, -39, 43, -19, 32, 11, 61, -55,
+ 56, -46, 62, -50, 81, -67, 45, -20, 35, -2, 28, 15, 34, 1, 39, 1, 30, 17, 20, 38, 18, 45, 15, 54, 0, 79, 36, -16, 37, -14, 37, -17,
+ 32, 1, 34, 15, 29, 15, 24, 25, 34, 22, 31, 16, 35, 18, 31, 28, 33, 41, 36, 28, 27, 47, 21, 62, 17, -13, 16, -9, 17, -12, 27, -21,
+ 37, -30, 41, -40, 42, -41, 48, -47, 39, -32, 46, -40, 52, -51, 46, -41, 52, -39, 43, -19, 32, 11, 61, -55, 56, -46, 62, -50, 81, -67, 45, -20,
+ 35, -2, 28, 15, 34, 1, 39, 1, 30, 17, 20, 38, 18, 45, 15, 54, 0, 79, 36, -16, 37, -14, 37, -17, 32, 1, 34, 15, 29, 15, 24, 25,
+ 34, 22, 31, 16, 35, 18, 31, 28, 33, 41, 36, 28, 27, 47, 21, 62, -24, 115, -22, 82, -9, 62, 0, 53, 0, 59, -14, 85, -13, 89, -13, 94,
+ -11, 92, -29, 127, -21, 100, -14, 57, -12, 67, -11, 71, -10, 77, -21, 85, -16, 88, -23, 104, -15, 98, -37, 127, -10, 82, -8, 48, -8, 61, -8, 66,
+ -7, 70, -14, 75, -10, 79, -9, 83, -12, 92, -18, 108, -24, 115, -22, 82, -9, 62, 0, 53, 0, 59, -14, 85, -13, 89, -13, 94, -11, 92, -29, 127,
+ -21, 100, -14, 57, -12, 67, -11, 71, -10, 77, -21, 85, -16, 88, -23, 104, -15, 98, -37, 127, -10, 82, -8, 48, -8, 61, -8, 66, -7, 70, -14, 75,
+ -10, 79, -9, 83, -12, 92, -18, 108, -5, 79, -11, 104, -11, 91, -30, 127, -5, 79, -11, 104, -11, 91, -30, 127, -5, 79, -11, 104, -11, 91, -30, 127,
+]
+
+export const CABAC_RANGE_LPS: u8[] = [
+ 128, 176, 208, 240, 128, 167, 197, 227, 128, 158, 187, 216, 123, 150, 178, 205, 116, 142, 169, 195, 111, 135, 160, 185, 105, 128, 152, 175, 100, 122, 144, 166,
+ 95, 116, 137, 158, 90, 110, 130, 150, 85, 104, 123, 142, 81, 99, 117, 135, 77, 94, 111, 128, 73, 89, 105, 122, 69, 85, 100, 116, 66, 80, 95, 110,
+ 62, 76, 90, 104, 59, 72, 86, 99, 56, 69, 81, 94, 53, 65, 77, 89, 51, 62, 73, 85, 48, 59, 69, 80, 46, 56, 66, 76, 43, 53, 63, 72,
+ 41, 50, 59, 69, 39, 48, 56, 65, 37, 45, 54, 62, 35, 43, 51, 59, 33, 41, 48, 56, 32, 39, 46, 53, 30, 37, 43, 50, 29, 35, 41, 48,
+ 27, 33, 39, 45, 26, 31, 37, 43, 24, 30, 35, 41, 23, 28, 33, 39, 22, 27, 32, 37, 21, 26, 30, 35, 20, 24, 29, 33, 19, 23, 27, 31,
+ 18, 22, 26, 30, 17, 21, 25, 28, 16, 20, 23, 27, 15, 19, 22, 25, 14, 18, 21, 24, 14, 17, 20, 23, 13, 16, 19, 22, 12, 15, 18, 21,
+ 12, 14, 17, 20, 11, 14, 16, 19, 11, 13, 15, 18, 10, 12, 15, 17, 10, 12, 14, 16, 9, 11, 13, 15, 9, 11, 12, 14, 8, 10, 12, 14,
+ 8, 9, 11, 13, 7, 9, 11, 12, 7, 9, 10, 12, 7, 8, 10, 11, 6, 8, 9, 11, 6, 7, 9, 10, 6, 7, 8, 9, 2, 2, 2, 2,
+]
+
+export const CABAC_NEXT_MPS: u8[] = [
+ 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, 62, 63,
+]
+
+export const CABAC_NEXT_LPS: u8[] = [
+ 0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12, 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, 21, 22, 22, 23, 24,
+ 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33, 33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63,
+]
+
+export const COEFF_TOKEN_LEN: u8[] = [
+ 1, 6, 8, 9, 10, 11, 13, 13, 13, 14, 14, 15, 15, 16, 16, 16, 16, 0, 2, 6, 8, 9, 10, 11, 13, 13, 14, 14, 15, 15, 15, 16,
+ 16, 16, 0, 0, 3, 7, 8, 9, 10, 11, 13, 13, 14, 14, 15, 15, 16, 16, 16, 0, 0, 0, 5, 6, 7, 8, 9, 10, 11, 13, 14, 14,
+ 15, 15, 16, 16, 2, 6, 6, 7, 8, 8, 9, 11, 11, 12, 12, 12, 13, 13, 13, 14, 14, 0, 2, 5, 6, 6, 7, 8, 9, 11, 11, 12,
+ 12, 13, 13, 14, 14, 14, 0, 0, 3, 6, 6, 7, 8, 9, 11, 11, 12, 12, 13, 13, 13, 14, 14, 0, 0, 0, 4, 4, 5, 6, 6, 7,
+ 9, 11, 11, 12, 13, 13, 13, 14, 4, 6, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 10, 10, 10, 10, 0, 4, 5, 5, 5, 5, 6,
+ 6, 7, 8, 8, 9, 9, 9, 10, 10, 10, 0, 0, 4, 5, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 10, 0, 0, 0, 4, 4,
+ 4, 4, 4, 5, 6, 7, 8, 8, 9, 10, 10, 10,
+]
+
+export const COEFF_TOKEN_CODE: u8[] = [
+ 1, 5, 7, 7, 7, 7, 15, 11, 8, 15, 11, 15, 11, 15, 11, 7, 4, 0, 1, 4, 6, 6, 6, 6, 14, 10, 14, 10, 14, 10, 1, 14,
+ 10, 6, 0, 0, 1, 5, 5, 5, 5, 5, 13, 9, 13, 9, 13, 9, 13, 9, 5, 0, 0, 0, 3, 3, 4, 4, 4, 4, 4, 12, 12, 8,
+ 12, 8, 12, 8, 3, 11, 7, 7, 7, 4, 7, 15, 11, 15, 11, 8, 15, 11, 7, 9, 7, 0, 2, 7, 10, 6, 6, 6, 6, 14, 10, 14,
+ 10, 14, 10, 11, 8, 6, 0, 0, 3, 9, 5, 5, 5, 5, 13, 9, 13, 9, 13, 9, 6, 10, 5, 0, 0, 0, 5, 4, 6, 8, 4, 4,
+ 4, 12, 8, 12, 12, 8, 1, 4, 15, 15, 11, 8, 15, 11, 9, 8, 15, 11, 15, 11, 8, 13, 9, 5, 1, 0, 14, 15, 12, 10, 8, 14,
+ 10, 14, 14, 10, 14, 10, 7, 12, 8, 4, 0, 0, 13, 14, 11, 9, 13, 9, 13, 10, 13, 9, 13, 9, 11, 7, 3, 0, 0, 0, 12, 11,
+ 10, 9, 8, 13, 12, 12, 12, 8, 12, 10, 6, 2,
+]
+
+export const COEFF_TOKEN_DC_LEN: u8[] = [
+ 2, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 3, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0,
+]
+
+export const COEFF_TOKEN_DC_CODE: u8[] = [
+ 1, 7, 4, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 6, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 1, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0,
+]
+
+export const TOTAL_ZEROS_LEN: u8[] = [
+ 1, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 6, 6, 6, 6, 0,
+ 4, 3, 3, 3, 4, 4, 3, 3, 4, 5, 5, 6, 5, 6, 0, 0, 5, 3, 4, 4, 3, 3, 3, 4, 3, 4, 5, 5, 5, 0, 0, 0,
+ 4, 4, 4, 3, 3, 3, 3, 3, 4, 5, 4, 5, 0, 0, 0, 0, 6, 5, 3, 3, 3, 3, 3, 3, 4, 3, 6, 0, 0, 0, 0, 0,
+ 6, 5, 3, 3, 3, 2, 3, 4, 3, 6, 0, 0, 0, 0, 0, 0, 6, 4, 5, 3, 2, 2, 3, 3, 6, 0, 0, 0, 0, 0, 0, 0,
+ 6, 6, 4, 2, 2, 3, 2, 5, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 3, 2, 2, 2, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 4, 4, 3, 3, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 2, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 3, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+]
+
+export const TOTAL_ZEROS_CODE: u8[] = [
+ 1, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 1, 7, 6, 5, 4, 3, 5, 4, 3, 2, 3, 2, 3, 2, 1, 0, 0,
+ 5, 7, 6, 5, 4, 3, 4, 3, 2, 3, 2, 1, 1, 0, 0, 0, 3, 7, 5, 4, 6, 5, 4, 3, 3, 2, 2, 1, 0, 0, 0, 0,
+ 5, 4, 3, 7, 6, 5, 4, 3, 2, 1, 1, 0, 0, 0, 0, 0, 1, 1, 7, 6, 5, 4, 3, 2, 1, 1, 0, 0, 0, 0, 0, 0,
+ 1, 1, 5, 4, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 3, 3, 2, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0,
+ 1, 0, 1, 3, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 3, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 1, 1, 2, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+]
+
+export const TOTAL_ZEROS_DC_LEN: u8[] = [
+ 1, 2, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+]
+
+export const TOTAL_ZEROS_DC_CODE: u8[] = [
+ 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+]
+
+export const RUN_BEFORE_LEN: u8[] = [
+ 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 2, 2, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 3, 3, 3, 3, 3, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+]
+
+export const RUN_BEFORE_CODE: u8[] = [
+ 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 3, 2, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 1, 3, 2, 5, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 7, 6, 5, 4, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+]
+
+export const DEBLOCK_ALPHA: int[] = [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 5, 6, 7, 8, 9, 10, 12, 13, 15, 17, 20, 22, 25, 28,
+ 32, 36, 40, 45, 50, 56, 63, 71, 80, 90, 101, 113, 127, 144, 162, 182, 203, 226, 255, 255,
+]
+
+export const DEBLOCK_BETA: int[] = [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 6, 6, 7, 7, 8, 8,
+ 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15, 16, 16, 17, 17, 18, 18,
+]
+
+export const DEBLOCK_TC0: int[] = [
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0,
+ 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1,
+ 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 2, 2, 0, 1, 1, 2, 2, 0, 1, 1, 2, 2, 0, 1, 1, 2, 2, 0, 1, 2, 3, 3,
+ 0, 1, 2, 3, 3, 0, 2, 2, 3, 3, 0, 2, 2, 4, 4, 0, 2, 3, 4, 4, 0, 2, 3, 4, 4, 0, 3, 3, 5, 5, 0, 3,
+ 4, 6, 6, 0, 3, 4, 6, 6, 0, 4, 5, 7, 7, 0, 4, 5, 8, 8, 0, 4, 6, 9, 9, 0, 5, 7, 10, 10, 0, 6, 8, 11,
+ 11, 0, 6, 8, 13, 13, 0, 7, 10, 14, 14, 0, 8, 11, 16, 16, 0, 9, 12, 18, 18, 0, 10, 13, 20, 20, 0, 11, 15, 23, 23, 0,
+ 13, 17, 25, 25,
+]
+
+export const CHROMA_QP: u8[] = [
+ 0, 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, 29, 30,
+ 31, 32, 32, 33, 34, 34, 35, 35, 36, 36, 37, 37, 37, 38, 38, 38, 39, 39, 39, 39,
+]
+
+export const ZIGZAG4: int[] = [
+ 0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15,
+]
+
+export const ZIGZAG8: int[] = [
+ 0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28,
+ 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
+]
+
+export const SIG8_FRAME: u8[] = [
+ 0, 1, 2, 3, 4, 5, 5, 4, 4, 3, 3, 4, 4, 4, 5, 5, 4, 4, 4, 4, 3, 3, 6, 7, 7, 7, 8, 9, 10, 9, 8, 7,
+ 7, 6, 11, 12, 13, 11, 6, 7, 8, 9, 14, 10, 9, 8, 6, 11, 12, 13, 11, 6, 9, 14, 10, 9, 11, 12, 13, 11, 14, 10, 12,
+]
+
+export const LAST8: u8[] = [
+ 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
+ 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8,
+]
+
+export const CBP_CODE_INTRA: u8[] = [
+ 3, 29, 30, 17, 31, 18, 37, 8, 32, 38, 19, 9, 20, 10, 11, 2, 16, 33, 34, 21, 35, 22, 39, 4, 36, 40, 23, 5, 24, 6, 7, 1,
+ 41, 42, 43, 25, 44, 26, 46, 12, 45, 47, 27, 13, 28, 14, 15, 0,
+]
+
+export const CBP_CODE_INTER: u8[] = [
+ 0, 2, 3, 7, 4, 8, 17, 13, 5, 18, 9, 14, 10, 15, 16, 11, 1, 32, 33, 36, 34, 37, 44, 40, 35, 45, 38, 41, 39, 42, 43, 19,
+ 6, 24, 25, 20, 26, 21, 46, 28, 27, 47, 22, 29, 23, 30, 31, 12,
+]
+
+export const QUANT4: i32[] = [
+ 13107, 8066, 13107, 8066, 8066, 5243, 8066, 5243, 13107, 8066, 13107, 8066, 8066, 5243, 8066, 5243, 11916, 7490, 11916, 7490, 7490, 4660, 7490, 4660, 11916, 7490, 11916, 7490, 7490, 4660, 7490, 4660,
+ 10082, 6554, 10082, 6554, 6554, 4194, 6554, 4194, 10082, 6554, 10082, 6554, 6554, 4194, 6554, 4194, 9362, 5825, 9362, 5825, 5825, 3647, 5825, 3647, 9362, 5825, 9362, 5825, 5825, 3647, 5825, 3647,
+ 8192, 5243, 8192, 5243, 5243, 3355, 5243, 3355, 8192, 5243, 8192, 5243, 5243, 3355, 5243, 3355, 7282, 4559, 7282, 4559, 4559, 2893, 4559, 2893, 7282, 4559, 7282, 4559, 4559, 2893, 4559, 2893,
+]
+
+export const DEQUANT4: i32[] = [
+ 10, 13, 10, 13, 13, 16, 13, 16, 10, 13, 10, 13, 13, 16, 13, 16, 11, 14, 11, 14, 14, 18, 14, 18, 11, 14, 11, 14, 14, 18, 14, 18,
+ 13, 16, 13, 16, 16, 20, 16, 20, 13, 16, 13, 16, 16, 20, 16, 20, 14, 18, 14, 18, 18, 23, 18, 23, 14, 18, 14, 18, 18, 23, 18, 23,
+ 16, 20, 16, 20, 20, 25, 20, 25, 16, 20, 16, 20, 20, 25, 20, 25, 18, 23, 18, 23, 23, 29, 23, 29, 18, 23, 18, 23, 23, 29, 23, 29,
+]
+
+export const QUANT8: i32[] = [
+ 13107, 12222, 16777, 12222, 13107, 12222, 16777, 12222, 12222, 11428, 15481, 11428, 12222, 11428, 15481, 11428, 16777, 15481, 20972, 15481, 16777, 15481, 20972, 15481, 12222, 11428, 15481, 11428, 12222, 11428, 15481, 11428,
+ 13107, 12222, 16777, 12222, 13107, 12222, 16777, 12222, 12222, 11428, 15481, 11428, 12222, 11428, 15481, 11428, 16777, 15481, 20972, 15481, 16777, 15481, 20972, 15481, 12222, 11428, 15481, 11428, 12222, 11428, 15481, 11428,
+ 11916, 11058, 14980, 11058, 11916, 11058, 14980, 11058, 11058, 10826, 14290, 10826, 11058, 10826, 14290, 10826, 14980, 14290, 19174, 14290, 14980, 14290, 19174, 14290, 11058, 10826, 14290, 10826, 11058, 10826, 14290, 10826,
+ 11916, 11058, 14980, 11058, 11916, 11058, 14980, 11058, 11058, 10826, 14290, 10826, 11058, 10826, 14290, 10826, 14980, 14290, 19174, 14290, 14980, 14290, 19174, 14290, 11058, 10826, 14290, 10826, 11058, 10826, 14290, 10826,
+ 10082, 9675, 12710, 9675, 10082, 9675, 12710, 9675, 9675, 8943, 11985, 8943, 9675, 8943, 11985, 8943, 12710, 11985, 15978, 11985, 12710, 11985, 15978, 11985, 9675, 8943, 11985, 8943, 9675, 8943, 11985, 8943,
+ 10082, 9675, 12710, 9675, 10082, 9675, 12710, 9675, 9675, 8943, 11985, 8943, 9675, 8943, 11985, 8943, 12710, 11985, 15978, 11985, 12710, 11985, 15978, 11985, 9675, 8943, 11985, 8943, 9675, 8943, 11985, 8943,
+ 9362, 8931, 11984, 8931, 9362, 8931, 11984, 8931, 8931, 8228, 11259, 8228, 8931, 8228, 11259, 8228, 11984, 11259, 14913, 11259, 11984, 11259, 14913, 11259, 8931, 8228, 11259, 8228, 8931, 8228, 11259, 8228,
+ 9362, 8931, 11984, 8931, 9362, 8931, 11984, 8931, 8931, 8228, 11259, 8228, 8931, 8228, 11259, 8228, 11984, 11259, 14913, 11259, 11984, 11259, 14913, 11259, 8931, 8228, 11259, 8228, 8931, 8228, 11259, 8228,
+ 8192, 7740, 10486, 7740, 8192, 7740, 10486, 7740, 7740, 7346, 9777, 7346, 7740, 7346, 9777, 7346, 10486, 9777, 13159, 9777, 10486, 9777, 13159, 9777, 7740, 7346, 9777, 7346, 7740, 7346, 9777, 7346,
+ 8192, 7740, 10486, 7740, 8192, 7740, 10486, 7740, 7740, 7346, 9777, 7346, 7740, 7346, 9777, 7346, 10486, 9777, 13159, 9777, 10486, 9777, 13159, 9777, 7740, 7346, 9777, 7346, 7740, 7346, 9777, 7346,
+ 7282, 6830, 9118, 6830, 7282, 6830, 9118, 6830, 6830, 6428, 8640, 6428, 6830, 6428, 8640, 6428, 9118, 8640, 11570, 8640, 9118, 8640, 11570, 8640, 6830, 6428, 8640, 6428, 6830, 6428, 8640, 6428,
+ 7282, 6830, 9118, 6830, 7282, 6830, 9118, 6830, 6830, 6428, 8640, 6428, 6830, 6428, 8640, 6428, 9118, 8640, 11570, 8640, 9118, 8640, 11570, 8640, 6830, 6428, 8640, 6428, 6830, 6428, 8640, 6428,
+]
+
+export const DEQUANT8: i32[] = [
+ 20, 19, 25, 19, 20, 19, 25, 19, 19, 18, 24, 18, 19, 18, 24, 18, 25, 24, 32, 24, 25, 24, 32, 24, 19, 18, 24, 18, 19, 18, 24, 18,
+ 20, 19, 25, 19, 20, 19, 25, 19, 19, 18, 24, 18, 19, 18, 24, 18, 25, 24, 32, 24, 25, 24, 32, 24, 19, 18, 24, 18, 19, 18, 24, 18,
+ 22, 21, 28, 21, 22, 21, 28, 21, 21, 19, 26, 19, 21, 19, 26, 19, 28, 26, 35, 26, 28, 26, 35, 26, 21, 19, 26, 19, 21, 19, 26, 19,
+ 22, 21, 28, 21, 22, 21, 28, 21, 21, 19, 26, 19, 21, 19, 26, 19, 28, 26, 35, 26, 28, 26, 35, 26, 21, 19, 26, 19, 21, 19, 26, 19,
+ 26, 24, 33, 24, 26, 24, 33, 24, 24, 23, 31, 23, 24, 23, 31, 23, 33, 31, 42, 31, 33, 31, 42, 31, 24, 23, 31, 23, 24, 23, 31, 23,
+ 26, 24, 33, 24, 26, 24, 33, 24, 24, 23, 31, 23, 24, 23, 31, 23, 33, 31, 42, 31, 33, 31, 42, 31, 24, 23, 31, 23, 24, 23, 31, 23,
+ 28, 26, 35, 26, 28, 26, 35, 26, 26, 25, 33, 25, 26, 25, 33, 25, 35, 33, 45, 33, 35, 33, 45, 33, 26, 25, 33, 25, 26, 25, 33, 25,
+ 28, 26, 35, 26, 28, 26, 35, 26, 26, 25, 33, 25, 26, 25, 33, 25, 35, 33, 45, 33, 35, 33, 45, 33, 26, 25, 33, 25, 26, 25, 33, 25,
+ 32, 30, 40, 30, 32, 30, 40, 30, 30, 28, 38, 28, 30, 28, 38, 28, 40, 38, 51, 38, 40, 38, 51, 38, 30, 28, 38, 28, 30, 28, 38, 28,
+ 32, 30, 40, 30, 32, 30, 40, 30, 30, 28, 38, 28, 30, 28, 38, 28, 40, 38, 51, 38, 40, 38, 51, 38, 30, 28, 38, 28, 30, 28, 38, 28,
+ 36, 34, 46, 34, 36, 34, 46, 34, 34, 32, 43, 32, 34, 32, 43, 32, 46, 43, 58, 43, 46, 43, 58, 43, 34, 32, 43, 32, 34, 32, 43, 32,
+ 36, 34, 46, 34, 36, 34, 46, 34, 34, 32, 43, 32, 34, 32, 43, 32, 46, 43, 58, 43, 46, 43, 58, 43, 34, 32, 43, 32, 34, 32, 43, 32,
+]
+
+export const CABAC_TRANSITION: u8[] = [
+ 2, 1, 0, 3, 4, 0, 1, 5, 6, 2, 3, 7, 8, 4, 5, 9, 10, 4, 5, 11, 12, 8, 9, 13, 14, 8, 9, 15, 16, 10, 11, 17,
+ 18, 12, 13, 19, 20, 14, 15, 21, 22, 16, 17, 23, 24, 18, 19, 25, 26, 18, 19, 27, 28, 22, 23, 29, 30, 22, 23, 31, 32, 24, 25, 33,
+ 34, 26, 27, 35, 36, 26, 27, 37, 38, 30, 31, 39, 40, 30, 31, 41, 42, 32, 33, 43, 44, 32, 33, 45, 46, 36, 37, 47, 48, 36, 37, 49,
+ 50, 38, 39, 51, 52, 38, 39, 53, 54, 42, 43, 55, 56, 42, 43, 57, 58, 44, 45, 59, 60, 44, 45, 61, 62, 46, 47, 63, 64, 48, 49, 65,
+ 66, 48, 49, 67, 68, 50, 51, 69, 70, 52, 53, 71, 72, 52, 53, 73, 74, 54, 55, 75, 76, 54, 55, 77, 78, 56, 57, 79, 80, 58, 59, 81,
+ 82, 58, 59, 83, 84, 60, 61, 85, 86, 60, 61, 87, 88, 60, 61, 89, 90, 62, 63, 91, 92, 64, 65, 93, 94, 64, 65, 95, 96, 66, 67, 97,
+ 98, 66, 67, 99, 100, 66, 67, 101, 102, 68, 69, 103, 104, 68, 69, 105, 106, 70, 71, 107, 108, 70, 71, 109, 110, 70, 71, 111, 112, 72, 73, 113,
+ 114, 72, 73, 115, 116, 72, 73, 117, 118, 74, 75, 119, 120, 74, 75, 121, 122, 74, 75, 123, 124, 76, 77, 125, 124, 76, 77, 125, 126, 126, 127, 127,
+]
+
+export const CABAC_SIG_CTX: u16[] = [
+ 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,
+ 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,
+ 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,
+ 149, 150, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151,
+ 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 151, 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,
+ 402, 403, 404, 405, 406, 407, 407, 406, 406, 405, 405, 406, 406, 406, 407, 407, 406, 406, 406, 406, 405, 405, 408, 409, 409, 409, 410, 411, 412, 411, 410, 409,
+ 409, 408, 413, 414, 415, 413, 408, 409, 410, 411, 416, 412, 411, 410, 408, 413, 414, 415, 413, 408, 411, 416, 412, 411, 413, 414, 415, 413, 416, 412, 414, 402,
+]
+
+export const CABAC_LAST_CTX: u16[] = [
+ 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,
+ 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,
+ 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,
+ 210, 211, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212,
+ 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 212, 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,
+ 417, 418, 418, 418, 418, 418, 418, 418, 418, 418, 418, 418, 418, 418, 418, 418, 419, 419, 419, 419, 419, 419, 419, 419, 419, 419, 419, 419, 419, 419, 419, 419,
+ 420, 420, 420, 420, 420, 420, 420, 420, 421, 421, 421, 421, 421, 421, 421, 421, 422, 422, 422, 422, 423, 423, 423, 423, 424, 424, 424, 424, 425, 425, 425, 417,
+]
+
+export const CABAC_RENORM_SHIFT: u8[] = [
+ 6, 5, 4, 4, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+]
diff --git a/capcodec/src/tq.tov b/capcodec/src/tq.tov
new file mode 100644
index 000000000..81ef1bd55
--- /dev/null
+++ b/capcodec/src/tq.tov
@@ -0,0 +1,1148 @@
+import { DEQUANT4, DEQUANT8, QUANT4, QUANT8, ZIGZAG4, ZIGZAG8 } from "./tables"
+import {
+ dequant4, dequant8, dequantChromaDc, dequantLumaDc, fdct4, fdct8, hadamard2, hadamard4, idct4, idct8, qpDiv6, qpMod6,
+ quant4, quant8, quantDc, quantOffset,
+} from "./transform"
+import { reconAdd } from "./pixel"
+
+export function fwd4(src: Uint8Array, so: int, ss: int, pred: Uint8Array, po: int, ps: int, out: Int32Array, oo: int) {
+ const d0 = i32x4.loadU8(src, so) - i32x4.loadU8(pred, po)
+ const d1 = i32x4.loadU8(src, so + ss) - i32x4.loadU8(pred, po + ps)
+ const d2 = i32x4.loadU8(src, so + 2 * ss) - i32x4.loadU8(pred, po + 2 * ps)
+ const d3 = i32x4.loadU8(src, so + 3 * ss) - i32x4.loadU8(pred, po + 3 * ps)
+ const a0 = i32x4.shuffle(d0, d1, [0, 4, 1, 5])
+ const a1 = i32x4.shuffle(d0, d1, [2, 6, 3, 7])
+ const a2 = i32x4.shuffle(d2, d3, [0, 4, 1, 5])
+ const a3 = i32x4.shuffle(d2, d3, [2, 6, 3, 7])
+ const c0 = i32x4.shuffle(a0, a2, [0, 1, 4, 5])
+ const c1 = i32x4.shuffle(a0, a2, [2, 3, 6, 7])
+ const c2 = i32x4.shuffle(a1, a3, [0, 1, 4, 5])
+ const c3 = i32x4.shuffle(a1, a3, [2, 3, 6, 7])
+ const hs0 = c0 + c3
+ const hs1 = c1 + c2
+ const hd0 = c0 - c3
+ const hd1 = c1 - c2
+ const h0 = hs0 + hs1
+ const h1 = (hd0 << 1) + hd1
+ const h2 = hs0 - hs1
+ const h3 = hd0 - (hd1 << 1)
+ const b0 = i32x4.shuffle(h0, h1, [0, 4, 1, 5])
+ const b1 = i32x4.shuffle(h0, h1, [2, 6, 3, 7])
+ const b2 = i32x4.shuffle(h2, h3, [0, 4, 1, 5])
+ const b3 = i32x4.shuffle(h2, h3, [2, 6, 3, 7])
+ const r0 = i32x4.shuffle(b0, b2, [0, 1, 4, 5])
+ const r1 = i32x4.shuffle(b0, b2, [2, 3, 6, 7])
+ const r2 = i32x4.shuffle(b1, b3, [0, 1, 4, 5])
+ const r3 = i32x4.shuffle(b1, b3, [2, 3, 6, 7])
+ const s0 = r0 + r3
+ const s1 = r1 + r2
+ const t0 = r0 - r3
+ const t1 = r1 - r2
+ const y0 = s0 + s1
+ const y1 = (t0 << 1) + t1
+ const y2 = s0 - s1
+ const y3 = t0 - (t1 << 1)
+ y0.store(out, oo)
+ y1.store(out, oo + 4)
+ y2.store(out, oo + 8)
+ y3.store(out, oo + 12)
+}
+
+const ZIP32_LO = [0, 8, 1, 9, 4, 12, 5, 13]
+const ZIP32_HI = [2, 10, 3, 11, 6, 14, 7, 15]
+const ZIP64_LO = [0, 1, 8, 9, 4, 5, 12, 13]
+const ZIP64_HI = [2, 3, 10, 11, 6, 7, 14, 15]
+
+export function fwd4x2(src: Uint8Array, so: int, ss: int, pred: Uint8Array, po: int, ps: int, out: Int32Array, oo: int) {
+ const d0 = i32x8.loadU8(src, so) - i32x8.loadU8(pred, po)
+ const d1 = i32x8.loadU8(src, so + ss) - i32x8.loadU8(pred, po + ps)
+ const d2 = i32x8.loadU8(src, so + 2 * ss) - i32x8.loadU8(pred, po + 2 * ps)
+ const d3 = i32x8.loadU8(src, so + 3 * ss) - i32x8.loadU8(pred, po + 3 * ps)
+ const a0 = i32x8.shuffle(d0, d1, ZIP32_LO)
+ const a1 = i32x8.shuffle(d0, d1, ZIP32_HI)
+ const a2 = i32x8.shuffle(d2, d3, ZIP32_LO)
+ const a3 = i32x8.shuffle(d2, d3, ZIP32_HI)
+ const c0 = i32x8.shuffle(a0, a2, ZIP64_LO)
+ const c1 = i32x8.shuffle(a0, a2, ZIP64_HI)
+ const c2 = i32x8.shuffle(a1, a3, ZIP64_LO)
+ const c3 = i32x8.shuffle(a1, a3, ZIP64_HI)
+ const hs0 = c0 + c3
+ const hs1 = c1 + c2
+ const hd0 = c0 - c3
+ const hd1 = c1 - c2
+ const h0 = hs0 + hs1
+ const h1 = (hd0 << 1) + hd1
+ const h2 = hs0 - hs1
+ const h3 = hd0 - (hd1 << 1)
+ const b0 = i32x8.shuffle(h0, h1, ZIP32_LO)
+ const b1 = i32x8.shuffle(h0, h1, ZIP32_HI)
+ const b2 = i32x8.shuffle(h2, h3, ZIP32_LO)
+ const b3 = i32x8.shuffle(h2, h3, ZIP32_HI)
+ const r0 = i32x8.shuffle(b0, b2, ZIP64_LO)
+ const r1 = i32x8.shuffle(b0, b2, ZIP64_HI)
+ const r2 = i32x8.shuffle(b1, b3, ZIP64_LO)
+ const r3 = i32x8.shuffle(b1, b3, ZIP64_HI)
+ const s0 = r0 + r3
+ const s1 = r1 + r2
+ const t0 = r0 - r3
+ const t1 = r1 - r2
+ const y0 = s0 + s1
+ const y1 = (t0 << 1) + t1
+ const y2 = s0 - s1
+ const y3 = t0 - (t1 << 1)
+ y0.low().store(out, oo)
+ y1.low().store(out, oo + 4)
+ y2.low().store(out, oo + 8)
+ y3.low().store(out, oo + 12)
+ y0.high().store(out, oo + 16)
+ y1.high().store(out, oo + 20)
+ y2.high().store(out, oo + 24)
+ y3.high().store(out, oo + 28)
+}
+
+export function quant4v(c: Int32Array, o: int, qp: int, intra: bool, startPos: int): int {
+ const qbits = 15 + qpDiv6(qp)
+ const qm = qpMod6(qp) * 16
+ const f = i32x8.splat(quantOffset(qbits, intra))
+ const zero = i32x8.splat(0)
+ const v0 = i32x8.load(c, o)
+ const v1 = i32x8.load(c, o + 8)
+ const l0 = (v0.abs() * i32x8.load(QUANT4, qm) + f) >> qbits
+ const l1 = (v1.abs() * i32x8.load(QUANT4, qm + 8) + f) >> qbits
+ let q0 = i32x8.select(v0.lt(zero), zero - l0, l0)
+ const q1 = i32x8.select(v1.lt(zero), zero - l1, l1)
+ if (startPos > 0) q0 = q0.withLane(0, v0.lane(0))
+ q0.store(c, o)
+ q1.store(c, o + 8)
+ const nz = q0.ne(zero).mask() | (q1.ne(zero).mask() << 8)
+ return Math.popcount32(startPos > 0 ? nz & 0xfffe : nz)
+}
+
+// QUANT4's first factor of each qp % 6 row is the row's largest, so a zero level for the largest AC magnitude
+// under it means quant4v with startPos 1 would leave all four blocks' AC at zero.
+export function chromaAcZero(c: Int32Array, o: int, qp: int, intra: bool): bool {
+ const qbits = 15 + qpDiv6(qp)
+ let m = i32x8.load(c, o).withLane(0, 0).abs().max(i32x8.load(c, o + 8).abs())
+ m = m.max(i32x8.load(c, o + 16).withLane(0, 0).abs()).max(i32x8.load(c, o + 24).abs())
+ m = m.max(i32x8.load(c, o + 32).withLane(0, 0).abs()).max(i32x8.load(c, o + 40).abs())
+ m = m.max(i32x8.load(c, o + 48).withLane(0, 0).abs()).max(i32x8.load(c, o + 56).abs())
+ const l = (m * i32x8.splat(int(QUANT4[qpMod6(qp) * 16]!)) + i32x8.splat(quantOffset(qbits, intra))) >> qbits
+ return l.eq(i32x8.splat(0)).mask() === 0xff
+}
+
+const K12 = i16x8(1, 1, 1, 1, 2, 2, 2, 2)
+const ROW_SWAP = [4, 5, 6, 7, 0, 1, 2, 3]
+const ROW_REV = [3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, 15, 14, 13, 12]
+const ROW_TT = [0, 1, 3, 2, 4, 5, 7, 6, 8, 9, 11, 10, 12, 13, 15, 14]
+const ROW_UU = [1, 0, 2, 0, 5, 4, 6, 4, 9, 8, 10, 8, 13, 12, 14, 12]
+const ZZ4_EO = [0, 8, 2, 4, 10, 1, 9, 3, 12, 6, 14, 5, 11, 13, 7, 15]
+const EVEN_ODD: int[] = [0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15]
+
+function quantPairs(keep: int): Int16Array {
+ const t = new Int16Array(96)
+ for (let i = 0; i < 96; i++) {
+ if ((i & 1) === keep) t[i] = int(QUANT4[i]!)
+ }
+ return t
+}
+
+function dequantPairs(keep: int): Int16Array {
+ const t = new Int16Array(96)
+ for (let i = 0; i < 96; i++) {
+ if ((i & 1) === keep) t[i] = int(DEQUANT4[(i & ~15) + EVEN_ODD[i & 15]!]!)
+ }
+ return t
+}
+
+const QUANT4_EVEN = quantPairs(0)
+const QUANT4_ODD = quantPairs(1)
+const DEQUANT4_COLS_A = dequantPairs(0)
+const DEQUANT4_COLS_B = dequantPairs(1)
+const ROWS_A = [0, 4, 12, 8, 1, 5, 13, 9]
+const ROWS_B = [2, 6, 14, 10, 3, 7, 15, 11]
+
+export function code4(s: u8x16, p: u8x16, qp: int, intra: bool, coef: Int16Array, zo: int, blk: Uint8Array, bo: int): int {
+ const p01 = p.widenLow()
+ const p23 = p.widenHigh()
+ const lo = s.widenLow() - p01
+ const hi = (s.widenHigh() - p23).swizzle(ROW_SWAP)
+ const vs = lo + hi
+ const vd = lo - hi
+ const x = i16x8.shuffle(vs, vd, [0, 1, 2, 3, 8, 9, 10, 11])
+ const z = i16x8.shuffle(vs, vd, [4, 5, 6, 7, 12, 13, 14, 15])
+ const y = i16x16.concat(x * K12 + z, x - z * K12)
+ const yr = y.swizzle(ROW_REV)
+ const hs = y + yr
+ const hd = y - yr
+ const mt = i16x16(-1, 0, 0, -1, -1, 0, 0, -1, -1, 0, 0, -1, -1, 0, 0, -1)
+ const t = i16x16.select(mt, hs, hd).swizzle(ROW_TT)
+ const u = i16x16.select(mt, hd, hs).swizzle(ROW_UU)
+ const c = t * i16x16(1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2) +
+ u * i16x16(1, 2, -1, 1, 1, 2, -1, 1, 1, 2, -1, 1, 1, 2, -1, 1)
+ const qbits = 15 + qpDiv6(qp)
+ const qm = qpMod6(qp) * 16
+ const f = i32x8.splat(quantOffset(qbits, intra))
+ const a = c.abs()
+ const ci = i32x8.bitcast(c)
+ const signEven = (ci << 16) >> 31
+ const signOdd = ci >> 31
+ const levelEven = (i16x16.madd(a, i16x16.load(QUANT4_EVEN, qm)) + f) >> qbits
+ const levelOdd = (i16x16.madd(a, i16x16.load(QUANT4_ODD, qm)) + f) >> qbits
+ const q = i16x16.packSat((levelEven ^ signEven) - signEven, (levelOdd ^ signOdd) - signOdd)
+ q.swizzle(ZZ4_EO).store(coef, zo)
+ const zeros = u8x32.bitcast(q.eq(i16x16.splat(0))).mask()
+ if (zeros === 0xffffffff) {
+ p.store(blk, bo)
+ return 0
+ }
+ const nz = (32 - Math.popcount32(zeros)) >> 1
+ const sh = qpDiv6(qp)
+ const ca = i16x16.madd(q, i16x16.load(DEQUANT4_COLS_A, qm)) << sh
+ const cb = i16x16.madd(q, i16x16.load(DEQUANT4_COLS_B, qm)) << sh
+ const ef = i32x8.concat((ca + cb).low(), (ca - cb).low())
+ const hg = i32x8.concat((ca + (cb >> 1)).high(), ((ca >> 1) - cb).high())
+ const xa = ef + hg
+ const xb = ef - hg
+ const ra = i32x8.shuffle(xa, xb, ROWS_A)
+ const rb = i32x8.shuffle(xa, xb, ROWS_B)
+ const ef2 = i32x8.concat((ra + rb).low(), (ra - rb).low())
+ const hg2 = i32x8.concat((ra + (rb >> 1)).high(), ((ra >> 1) - rb).high())
+ const r32 = i32x8.splat(32)
+ const o01 = (ef2 + hg2 + r32) >> 6
+ const o32 = (ef2 - hg2 + r32) >> 6
+ const r = i16x16.packSat(o01, o32).addSat(i16x16.concat(p01, p23.swizzle(ROW_SWAP)))
+ u8x16.bitcast(i32x4.bitcast(u8x16.packSat(r.low(), r.high())).swizzle([0, 1, 3, 2])).store(blk, bo)
+ return nz
+}
+
+export function dequant4v(c: Int32Array, o: int, qp: int) {
+ const sh = qpDiv6(qp)
+ const qm = qpMod6(qp) * 16
+ ((i32x8.load(c, o) * i32x8.load(DEQUANT4, qm)) << sh).store(c, o)
+ ((i32x8.load(c, o + 8) * i32x8.load(DEQUANT4, qm + 8)) << sh).store(c, o + 8)
+}
+
+export function idct4v(c: Int32Array, o: int) {
+ const d0 = i32x4.load(c, o)
+ const d1 = i32x4.load(c, o + 4)
+ const d2 = i32x4.load(c, o + 8)
+ const d3 = i32x4.load(c, o + 12)
+ const a0 = i32x4.shuffle(d0, d1, [0, 4, 1, 5])
+ const a1 = i32x4.shuffle(d0, d1, [2, 6, 3, 7])
+ const a2 = i32x4.shuffle(d2, d3, [0, 4, 1, 5])
+ const a3 = i32x4.shuffle(d2, d3, [2, 6, 3, 7])
+ const t0 = i32x4.shuffle(a0, a2, [0, 1, 4, 5])
+ const t1 = i32x4.shuffle(a0, a2, [2, 3, 6, 7])
+ const t2 = i32x4.shuffle(a1, a3, [0, 1, 4, 5])
+ const t3 = i32x4.shuffle(a1, a3, [2, 3, 6, 7])
+ const he = t0 + t2
+ const hf = t0 - t2
+ const hg = (t1 >> 1) - t3
+ const hh = t1 + (t3 >> 1)
+ const x0 = he + hh
+ const x1 = hf + hg
+ const x2 = hf - hg
+ const x3 = he - hh
+ const b0 = i32x4.shuffle(x0, x1, [0, 4, 1, 5])
+ const b1 = i32x4.shuffle(x0, x1, [2, 6, 3, 7])
+ const b2 = i32x4.shuffle(x2, x3, [0, 4, 1, 5])
+ const b3 = i32x4.shuffle(x2, x3, [2, 6, 3, 7])
+ const f0 = i32x4.shuffle(b0, b2, [0, 1, 4, 5])
+ const f1 = i32x4.shuffle(b0, b2, [2, 3, 6, 7])
+ const f2 = i32x4.shuffle(b1, b3, [0, 1, 4, 5])
+ const f3 = i32x4.shuffle(b1, b3, [2, 3, 6, 7])
+ const e = f0 + f2
+ const ff = f0 - f2
+ const g = (f1 >> 1) - f3
+ const h = f1 + (f3 >> 1)
+ const r = i32x4.splat(32)
+ const o0 = (e + h + r) >> 6
+ const o1 = (ff + g + r) >> 6
+ const o2 = (ff - g + r) >> 6
+ const o3 = (e - h + r) >> 6
+ o0.store(c, o)
+ o1.store(c, o + 4)
+ o2.store(c, o + 8)
+ o3.store(c, o + 12)
+}
+
+export function recon4(rec: Uint8Array, ro: int, rs: int, c: Int32Array, o: int, pred: Uint8Array, po: int, ps: int) {
+ for (let y = 0; y < 4; y++) {
+ const v = i32x4.loadU8(pred, po + y * ps) + i32x4.load(c, o + y * 4)
+ v.storeU8(rec, ro + y * rs)
+ }
+}
+
+export function copy4(dst: Uint8Array, d: int, ds: int, src: Uint8Array, s: int, ss: int) {
+ for (let y = 0; y < 4; y++) i32x4.loadU8(src, s + y * ss).storeU8(dst, d + y * ds)
+}
+
+export function copy8(dst: Uint8Array, d: int, ds: int, src: Uint8Array, s: int, ss: int) {
+ for (let y = 0; y < 8; y++) u8x16.loadLow(src, s + y * ss).storeLow(dst, d + y * ds)
+}
+
+export function reconC8(rec: Uint8Array, ro: int, rs: int, c: Int32Array, o: int, pred: Uint8Array, po: int, ps: int) {
+ for (let y = 0; y < 8; y++) {
+ const bo = o + (y >> 2) * 32 + (y & 3) * 4
+ const r = i16x8.packSat(i32x4.load(c, bo), i32x4.load(c, bo + 16)).addSat(i16x8.loadU8(pred, po + y * ps))
+ r.storeU8(rec, ro + y * rs)
+ }
+}
+
+function reconRow8(rec: Uint8Array, ro: int, v: i32x8, pred: Uint8Array, po: int) {
+ i16x8.packSat(v.low(), v.high()).addSat(i16x8.loadU8(pred, po)).storeU8(rec, ro)
+}
+
+export function idctC8(c: Int32Array, o: int, rec: Uint8Array, ro: int, rs: int, pred: Uint8Array, po: int) {
+ for (let h = 0; h < 2; h++) {
+ const b = o + h * 32
+ const d0 = i32x8.concat(i32x4.load(c, b), i32x4.load(c, b + 16))
+ const d1 = i32x8.concat(i32x4.load(c, b + 4), i32x4.load(c, b + 20))
+ const d2 = i32x8.concat(i32x4.load(c, b + 8), i32x4.load(c, b + 24))
+ const d3 = i32x8.concat(i32x4.load(c, b + 12), i32x4.load(c, b + 28))
+ const a0 = i32x8.shuffle(d0, d1, ZIP32_LO)
+ const a1 = i32x8.shuffle(d0, d1, ZIP32_HI)
+ const a2 = i32x8.shuffle(d2, d3, ZIP32_LO)
+ const a3 = i32x8.shuffle(d2, d3, ZIP32_HI)
+ const t0 = i32x8.shuffle(a0, a2, ZIP64_LO)
+ const t1 = i32x8.shuffle(a0, a2, ZIP64_HI)
+ const t2 = i32x8.shuffle(a1, a3, ZIP64_LO)
+ const t3 = i32x8.shuffle(a1, a3, ZIP64_HI)
+ const he = t0 + t2
+ const hf = t0 - t2
+ const hg = (t1 >> 1) - t3
+ const hh = t1 + (t3 >> 1)
+ const x0 = he + hh
+ const x1 = hf + hg
+ const x2 = hf - hg
+ const x3 = he - hh
+ const b0 = i32x8.shuffle(x0, x1, ZIP32_LO)
+ const b1 = i32x8.shuffle(x0, x1, ZIP32_HI)
+ const b2 = i32x8.shuffle(x2, x3, ZIP32_LO)
+ const b3 = i32x8.shuffle(x2, x3, ZIP32_HI)
+ const f0 = i32x8.shuffle(b0, b2, ZIP64_LO)
+ const f1 = i32x8.shuffle(b0, b2, ZIP64_HI)
+ const f2 = i32x8.shuffle(b1, b3, ZIP64_LO)
+ const f3 = i32x8.shuffle(b1, b3, ZIP64_HI)
+ const e = f0 + f2
+ const ff = f0 - f2
+ const g = (f1 >> 1) - f3
+ const hv = f1 + (f3 >> 1)
+ const r = i32x8.splat(32)
+ const y = ro + h * 4 * rs
+ const p = po + h * 32
+ reconRow8(rec, y, (e + hv + r) >> 6, pred, p)
+ reconRow8(rec, y + rs, (ff + g + r) >> 6, pred, p + 8)
+ reconRow8(rec, y + 2 * rs, (ff - g + r) >> 6, pred, p + 16)
+ reconRow8(rec, y + 3 * rs, (e - hv + r) >> 6, pred, p + 24)
+ }
+}
+
+export function recon16(rec: Uint8Array, ro: int, rs: int, c: Int32Array, pred: Uint8Array, po: int) {
+ for (let y = 0; y < 16; y++) {
+ const bo = (y >> 2) * 64 + (y & 3) * 4
+ const lo = i16x8.packSat(i32x4.load(c, bo), i32x4.load(c, bo + 16))
+ const hi = i16x8.packSat(i32x4.load(c, bo + 32), i32x4.load(c, bo + 48))
+ const p = u8x16.load(pred, po + y * 16)
+ u8x16.packSat(lo.addSat(p.widenLow()), hi.addSat(p.widenHigh())).store(rec, ro + y * rs)
+ }
+}
+
+export function reconDc16(rec: Uint8Array, ro: int, rs: int, dc: Int32Array, pred: Uint8Array, po: int) {
+ const r32 = i32x4.splat(32)
+ for (let by = 0; by < 4; by++) {
+ const d = (i32x4.load(dc, by * 4) + r32) >> 6
+ const k = i16x8.packSat(d, d)
+ const lo = k.swizzle([0, 0, 0, 0, 1, 1, 1, 1])
+ const hi = k.swizzle([2, 2, 2, 2, 3, 3, 3, 3])
+ for (let y = by * 4; y < by * 4 + 4; y++) {
+ const p = u8x16.load(pred, po + y * 16)
+ u8x16.packSat(lo.addSat(p.widenLow()), hi.addSat(p.widenHigh())).store(rec, ro + y * rs)
+ }
+ }
+}
+
+export function copy16(dst: Uint8Array, d: int, ds: int, src: Uint8Array, s: int) {
+ for (let y = 0; y < 16; y++) u8x16.load(src, s + y * 16).store(dst, d + y * ds)
+}
+
+export function reconDcC8(rec: Uint8Array, ro: int, rs: int, dc: Int32Array, o: int, pred: Uint8Array, po: int) {
+ const d = (i32x4.load(dc, o) + i32x4.splat(32)) >> 6
+ const k = i16x8.packSat(d, d)
+ const k0 = k.swizzle([0, 0, 0, 0, 1, 1, 1, 1])
+ const k1 = k.swizzle([2, 2, 2, 2, 3, 3, 3, 3])
+ for (let y = 0; y < 4; y++) {
+ const r = k0.addSat(i16x8.loadU8(pred, po + y * 8))
+ r.storeU8(rec, ro + y * rs)
+ }
+ for (let y = 4; y < 8; y++) {
+ const r = k1.addSat(i16x8.loadU8(pred, po + y * 8))
+ r.storeU8(rec, ro + y * rs)
+ }
+}
+
+export function zigzag4(c: Int32Array, o: int, coef: Int16Array, d: int) {
+ const a = i16x8.packSat(i32x4.load(c, o), i32x4.load(c, o + 4))
+ const b = i16x8.packSat(i32x4.load(c, o + 8), i32x4.load(c, o + 12))
+ i16x8.shuffle(a, b, [0, 1, 4, 8, 5, 2, 3, 6]).store(coef, d)
+ i16x8.shuffle(a, b, [9, 12, 13, 10, 7, 11, 14, 15]).store(coef, d + 8)
+}
+
+export function zigzagAc4(c: Int32Array, o: int, coef: Int16Array, d: int) {
+ const a = i16x8.packSat(i32x4.load(c, o), i32x4.load(c, o + 4))
+ const b = i16x8.packSat(i32x4.load(c, o + 8), i32x4.load(c, o + 12))
+ i16x8.shuffle(a, b, [1, 4, 8, 5, 2, 3, 6, 9]).store(coef, d)
+ i16x8.shuffle(a, b, [12, 13, 10, 7, 11, 14, 15, 0]).withLane(7, 0).store(coef, d + 8)
+}
+
+const ZZ8_A0 = [0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 0, 25, 18, 11, 4, 5]
+const ZZ8_A1 = [12, 19, 26, 0, 0, 0, 0, 0, 27, 20, 13, 6, 7, 14, 21, 28]
+const ZZ8_B1 = [0, 0, 0, 1, 8, 16, 9, 2, 0, 0, 0, 0, 0, 0, 0, 0]
+const ZZ8_M1 = i16x16(-1, -1, -1, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1)
+const ZZ8_A2 = [0, 0, 0, 0, 0, 0, 0, 0, 29, 22, 15, 23, 30, 0, 0, 0]
+const ZZ8_B2 = [3, 10, 17, 24, 25, 18, 11, 4, 0, 0, 0, 0, 0, 5, 12, 19]
+const ZZ8_M2 = i16x16(0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, 0, 0, 0)
+const ZZ8_B3 = [26, 27, 20, 13, 6, 0, 7, 14, 21, 28, 29, 22, 15, 23, 30, 31]
+
+// Quantised 8x8 levels fit in 16 bits (fwd8 works in 16-bit lanes), so packSat keeps them exactly.
+export function zigzag8(c: Int32Array, o: int, coef: Int16Array, d: int) {
+ const r01 = i16x16.packSat(i32x8.load(c, o), i32x8.load(c, o + 8))
+ const r23 = i16x16.packSat(i32x8.load(c, o + 16), i32x8.load(c, o + 24))
+ const r45 = i16x16.packSat(i32x8.load(c, o + 32), i32x8.load(c, o + 40))
+ const r67 = i16x16.packSat(i32x8.load(c, o + 48), i32x8.load(c, o + 56))
+ i16x16.shuffle(r01, r23, ZZ8_A0).withLane(10, r45.lane(0)).store(coef, d)
+ i16x16.select(ZZ8_M1, i16x16.shuffle(r01, r23, ZZ8_A1), i16x16.shuffle(r45, r67, ZZ8_B1)).store(coef, d + 16)
+ i16x16.select(ZZ8_M2, i16x16.shuffle(r01, r23, ZZ8_A2), i16x16.shuffle(r45, r67, ZZ8_B2)).store(coef, d + 32)
+ i16x16.shuffle(r45, r67, ZZ8_B3).withLane(5, r23.lane(15)).store(coef, d + 48)
+}
+
+export function nonzeroMask(c: Int16Array, o: int, n: int): int {
+ const zero = i16x16.splat(0)
+ const m = i16x16.load(c, o).ne(zero).mask()
+ if (n <= 16) return m & ((1 << n) - 1)
+ return m | (i16x16.load(c, o + 16).ne(zero).mask() << 16) | (i16x16.load(c, o + 32).ne(zero).mask() << 32) |
+ (i16x16.load(c, o + 48).ne(zero).mask() << 48)
+}
+
+function h4row(v: i32x4): i32x4 {
+ const p = v.swizzle([1, 0, 3, 2])
+ const t = i32x4.select(i32x4(-1, 0, -1, 0), v + p, p - v)
+ const q = t.swizzle([2, 3, 0, 1])
+ return i32x4.select(i32x4(-1, -1, 0, 0), t + q, q - t).swizzle([0, 2, 3, 1])
+}
+
+export function hadamard4v(c: Int32Array, o: int, forward: bool) {
+ const a0 = h4row(i32x4.load(c, o))
+ const a1 = h4row(i32x4.load(c, o + 4))
+ const a2 = h4row(i32x4.load(c, o + 8))
+ const a3 = h4row(i32x4.load(c, o + 12))
+ const s0 = a0 + a1
+ const s1 = a2 + a3
+ const d0 = a0 - a1
+ const d1 = a2 - a3
+ const sh = forward ? 1 : 0
+ ((s0 + s1) >> sh).store(c, o)
+ ((s0 - s1) >> sh).store(c, o + 4)
+ ((d0 - d1) >> sh).store(c, o + 8)
+ ((d0 + d1) >> sh).store(c, o + 12)
+}
+
+export function quantDcv(c: Int32Array, o: int, n: int, qp: int, intra: bool): int {
+ const qbits = 16 + qpDiv6(qp)
+ const f = i32x4.splat(quantOffset(qbits, intra))
+ const mf = i32x4.splat(int(QUANT4[qpMod6(qp) * 16]!))
+ const zero = i32x4.splat(0)
+ let nz = 0
+ for (let k = 0; k < n; k += 4) {
+ const v = i32x4.load(c, o + k)
+ const l = (v.abs() * mf + f) >> qbits
+ const q = i32x4.select(v.lt(zero), zero - l, l)
+ nz += Math.popcount32(q.ne(zero).mask())
+ q.store(c, o + k)
+ }
+ return nz
+}
+
+export function dequantLumaDcv(c: Int32Array, o: int, qp: int) {
+ const ls = i32x4.splat(16 * int(DEQUANT4[qpMod6(qp) * 16]!))
+ const q6 = qpDiv6(qp)
+ if (qp >= 36) {
+ for (let k = 0; k < 16; k += 4) ((i32x4.load(c, o + k) * ls) << (q6 - 6)).store(c, o + k)
+ return
+ }
+ const r = i32x4.splat(1 << (5 - q6))
+ for (let k = 0; k < 16; k += 4) ((i32x4.load(c, o + k) * ls + r) >> (6 - q6)).store(c, o + k)
+}
+
+export function hadamard2v(c: Int32Array, o: int) {
+ const c0 = c[o]!
+ const c1 = c[o + 1]!
+ const c2 = c[o + 2]!
+ const c3 = c[o + 3]!
+ c[o] = c0 + c1 + c2 + c3
+ c[o + 1] = c0 - c1 + c2 - c3
+ c[o + 2] = c0 + c1 - c2 - c3
+ c[o + 3] = c0 - c1 - c2 + c3
+}
+
+export function dequantChromaDcv(c: Int32Array, o: int, qp: int) {
+ const ls = i32x4.splat(16 * int(DEQUANT4[qpMod6(qp) * 16]!))
+ (((i32x4.load(c, o) * ls) << qpDiv6(qp)) >> 5).store(c, o)
+}
+
+export function fwd8(src: Uint8Array, so: int, ss: int, pred: Uint8Array, po: int, ps: int, out: Int32Array, oo: int) {
+ const r0 = i16x8.loadU8(src, so + 0 * ss) - i16x8.loadU8(pred, po + 0 * ps)
+ const r1 = i16x8.loadU8(src, so + 1 * ss) - i16x8.loadU8(pred, po + 1 * ps)
+ const r2 = i16x8.loadU8(src, so + 2 * ss) - i16x8.loadU8(pred, po + 2 * ps)
+ const r3 = i16x8.loadU8(src, so + 3 * ss) - i16x8.loadU8(pred, po + 3 * ps)
+ const r4 = i16x8.loadU8(src, so + 4 * ss) - i16x8.loadU8(pred, po + 4 * ps)
+ const r5 = i16x8.loadU8(src, so + 5 * ss) - i16x8.loadU8(pred, po + 5 * ps)
+ const r6 = i16x8.loadU8(src, so + 6 * ss) - i16x8.loadU8(pred, po + 6 * ps)
+ const r7 = i16x8.loadU8(src, so + 7 * ss) - i16x8.loadU8(pred, po + 7 * ps)
+ const ct0 = i16x8.shuffle(r0, r1, [0, 8, 1, 9, 2, 10, 3, 11])
+ const ct1 = i16x8.shuffle(r0, r1, [4, 12, 5, 13, 6, 14, 7, 15])
+ const ct2 = i16x8.shuffle(r2, r3, [0, 8, 1, 9, 2, 10, 3, 11])
+ const ct3 = i16x8.shuffle(r2, r3, [4, 12, 5, 13, 6, 14, 7, 15])
+ const ct4 = i16x8.shuffle(r4, r5, [0, 8, 1, 9, 2, 10, 3, 11])
+ const ct5 = i16x8.shuffle(r4, r5, [4, 12, 5, 13, 6, 14, 7, 15])
+ const ct6 = i16x8.shuffle(r6, r7, [0, 8, 1, 9, 2, 10, 3, 11])
+ const ct7 = i16x8.shuffle(r6, r7, [4, 12, 5, 13, 6, 14, 7, 15])
+ const cu0 = i16x8.shuffle(ct0, ct2, [0, 1, 8, 9, 2, 3, 10, 11])
+ const cu1 = i16x8.shuffle(ct0, ct2, [4, 5, 12, 13, 6, 7, 14, 15])
+ const cu2 = i16x8.shuffle(ct1, ct3, [0, 1, 8, 9, 2, 3, 10, 11])
+ const cu3 = i16x8.shuffle(ct1, ct3, [4, 5, 12, 13, 6, 7, 14, 15])
+ const cu4 = i16x8.shuffle(ct4, ct6, [0, 1, 8, 9, 2, 3, 10, 11])
+ const cu5 = i16x8.shuffle(ct4, ct6, [4, 5, 12, 13, 6, 7, 14, 15])
+ const cu6 = i16x8.shuffle(ct5, ct7, [0, 1, 8, 9, 2, 3, 10, 11])
+ const cu7 = i16x8.shuffle(ct5, ct7, [4, 5, 12, 13, 6, 7, 14, 15])
+ const c0 = i16x8.shuffle(cu0, cu4, [0, 1, 2, 3, 8, 9, 10, 11])
+ const c1 = i16x8.shuffle(cu0, cu4, [4, 5, 6, 7, 12, 13, 14, 15])
+ const c2 = i16x8.shuffle(cu1, cu5, [0, 1, 2, 3, 8, 9, 10, 11])
+ const c3 = i16x8.shuffle(cu1, cu5, [4, 5, 6, 7, 12, 13, 14, 15])
+ const c4 = i16x8.shuffle(cu2, cu6, [0, 1, 2, 3, 8, 9, 10, 11])
+ const c5 = i16x8.shuffle(cu2, cu6, [4, 5, 6, 7, 12, 13, 14, 15])
+ const c6 = i16x8.shuffle(cu3, cu7, [0, 1, 2, 3, 8, 9, 10, 11])
+ const c7 = i16x8.shuffle(cu3, cu7, [4, 5, 6, 7, 12, 13, 14, 15])
+ const hs07 = c0 + c7
+ const hs16 = c1 + c6
+ const hs25 = c2 + c5
+ const hs34 = c3 + c4
+ const ha0 = hs07 + hs34
+ const ha1 = hs16 + hs25
+ const ha2 = hs07 - hs34
+ const ha3 = hs16 - hs25
+ const hd07 = c0 - c7
+ const hd16 = c1 - c6
+ const hd25 = c2 - c5
+ const hd34 = c3 - c4
+ const ha4 = hd16 + hd25 + (hd07 + (hd07 >> 1))
+ const ha5 = hd07 - hd34 - (hd25 + (hd25 >> 1))
+ const ha6 = hd07 + hd34 - (hd16 + (hd16 >> 1))
+ const ha7 = hd16 - hd25 + (hd34 + (hd34 >> 1))
+ const h0 = ha0 + ha1
+ const h4 = ha0 - ha1
+ const h2 = ha2 + (ha3 >> 1)
+ const h6 = (ha2 >> 1) - ha3
+ const h1 = ha4 + (ha7 >> 2)
+ const h3 = ha5 + (ha6 >> 2)
+ const h5 = ha6 - (ha5 >> 2)
+ const h7 = (ha4 >> 2) - ha7
+ const wt0 = i16x8.shuffle(h0, h1, [0, 8, 1, 9, 2, 10, 3, 11])
+ const wt1 = i16x8.shuffle(h0, h1, [4, 12, 5, 13, 6, 14, 7, 15])
+ const wt2 = i16x8.shuffle(h2, h3, [0, 8, 1, 9, 2, 10, 3, 11])
+ const wt3 = i16x8.shuffle(h2, h3, [4, 12, 5, 13, 6, 14, 7, 15])
+ const wt4 = i16x8.shuffle(h4, h5, [0, 8, 1, 9, 2, 10, 3, 11])
+ const wt5 = i16x8.shuffle(h4, h5, [4, 12, 5, 13, 6, 14, 7, 15])
+ const wt6 = i16x8.shuffle(h6, h7, [0, 8, 1, 9, 2, 10, 3, 11])
+ const wt7 = i16x8.shuffle(h6, h7, [4, 12, 5, 13, 6, 14, 7, 15])
+ const wu0 = i16x8.shuffle(wt0, wt2, [0, 1, 8, 9, 2, 3, 10, 11])
+ const wu1 = i16x8.shuffle(wt0, wt2, [4, 5, 12, 13, 6, 7, 14, 15])
+ const wu2 = i16x8.shuffle(wt1, wt3, [0, 1, 8, 9, 2, 3, 10, 11])
+ const wu3 = i16x8.shuffle(wt1, wt3, [4, 5, 12, 13, 6, 7, 14, 15])
+ const wu4 = i16x8.shuffle(wt4, wt6, [0, 1, 8, 9, 2, 3, 10, 11])
+ const wu5 = i16x8.shuffle(wt4, wt6, [4, 5, 12, 13, 6, 7, 14, 15])
+ const wu6 = i16x8.shuffle(wt5, wt7, [0, 1, 8, 9, 2, 3, 10, 11])
+ const wu7 = i16x8.shuffle(wt5, wt7, [4, 5, 12, 13, 6, 7, 14, 15])
+ const w0 = i16x8.shuffle(wu0, wu4, [0, 1, 2, 3, 8, 9, 10, 11])
+ const w1 = i16x8.shuffle(wu0, wu4, [4, 5, 6, 7, 12, 13, 14, 15])
+ const w2 = i16x8.shuffle(wu1, wu5, [0, 1, 2, 3, 8, 9, 10, 11])
+ const w3 = i16x8.shuffle(wu1, wu5, [4, 5, 6, 7, 12, 13, 14, 15])
+ const w4 = i16x8.shuffle(wu2, wu6, [0, 1, 2, 3, 8, 9, 10, 11])
+ const w5 = i16x8.shuffle(wu2, wu6, [4, 5, 6, 7, 12, 13, 14, 15])
+ const w6 = i16x8.shuffle(wu3, wu7, [0, 1, 2, 3, 8, 9, 10, 11])
+ const w7 = i16x8.shuffle(wu3, wu7, [4, 5, 6, 7, 12, 13, 14, 15])
+ const vs07 = w0 + w7
+ const vs16 = w1 + w6
+ const vs25 = w2 + w5
+ const vs34 = w3 + w4
+ const va0 = vs07 + vs34
+ const va1 = vs16 + vs25
+ const va2 = vs07 - vs34
+ const va3 = vs16 - vs25
+ const vd07 = w0 - w7
+ const vd16 = w1 - w6
+ const vd25 = w2 - w5
+ const vd34 = w3 - w4
+ const va4 = vd16 + vd25 + (vd07 + (vd07 >> 1))
+ const va5 = vd07 - vd34 - (vd25 + (vd25 >> 1))
+ const va6 = vd07 + vd34 - (vd16 + (vd16 >> 1))
+ const va7 = vd16 - vd25 + (vd34 + (vd34 >> 1))
+ const v0 = va0 + va1
+ const v4 = va0 - va1
+ const v2 = va2 + (va3 >> 1)
+ const v6 = (va2 >> 1) - va3
+ const v1 = va4 + (va7 >> 2)
+ const v3 = va5 + (va6 >> 2)
+ const v5 = va6 - (va5 >> 2)
+ const v7 = (va4 >> 2) - va7
+ i32x8.convert(v0).store(out, oo + 0)
+ i32x8.convert(v1).store(out, oo + 8)
+ i32x8.convert(v2).store(out, oo + 16)
+ i32x8.convert(v3).store(out, oo + 24)
+ i32x8.convert(v4).store(out, oo + 32)
+ i32x8.convert(v5).store(out, oo + 40)
+ i32x8.convert(v6).store(out, oo + 48)
+ i32x8.convert(v7).store(out, oo + 56)
+}
+
+export function idct8v(c: Int32Array, o: int) {
+ const rnd = i32x8.splat(32)
+ const d0 = i32x8.load(c, o + 0)
+ const d1 = i32x8.load(c, o + 8)
+ const d2 = i32x8.load(c, o + 16)
+ const d3 = i32x8.load(c, o + 24)
+ const d4 = i32x8.load(c, o + 32)
+ const d5 = i32x8.load(c, o + 40)
+ const d6 = i32x8.load(c, o + 48)
+ const d7 = i32x8.load(c, o + 56)
+ const ta0 = i32x8.shuffle(d0, d1, [0, 8, 1, 9, 4, 12, 5, 13])
+ const ta1 = i32x8.shuffle(d0, d1, [2, 10, 3, 11, 6, 14, 7, 15])
+ const ta2 = i32x8.shuffle(d2, d3, [0, 8, 1, 9, 4, 12, 5, 13])
+ const ta3 = i32x8.shuffle(d2, d3, [2, 10, 3, 11, 6, 14, 7, 15])
+ const ta4 = i32x8.shuffle(d4, d5, [0, 8, 1, 9, 4, 12, 5, 13])
+ const ta5 = i32x8.shuffle(d4, d5, [2, 10, 3, 11, 6, 14, 7, 15])
+ const ta6 = i32x8.shuffle(d6, d7, [0, 8, 1, 9, 4, 12, 5, 13])
+ const ta7 = i32x8.shuffle(d6, d7, [2, 10, 3, 11, 6, 14, 7, 15])
+ const tb0 = i32x8.shuffle(ta0, ta2, [0, 1, 8, 9, 4, 5, 12, 13])
+ const tb1 = i32x8.shuffle(ta0, ta2, [2, 3, 10, 11, 6, 7, 14, 15])
+ const tb2 = i32x8.shuffle(ta1, ta3, [0, 1, 8, 9, 4, 5, 12, 13])
+ const tb3 = i32x8.shuffle(ta1, ta3, [2, 3, 10, 11, 6, 7, 14, 15])
+ const tb4 = i32x8.shuffle(ta4, ta6, [0, 1, 8, 9, 4, 5, 12, 13])
+ const tb5 = i32x8.shuffle(ta4, ta6, [2, 3, 10, 11, 6, 7, 14, 15])
+ const tb6 = i32x8.shuffle(ta5, ta7, [0, 1, 8, 9, 4, 5, 12, 13])
+ const tb7 = i32x8.shuffle(ta5, ta7, [2, 3, 10, 11, 6, 7, 14, 15])
+ const t0 = i32x8.shuffle(tb0, tb4, [0, 1, 2, 3, 8, 9, 10, 11])
+ const t4 = i32x8.shuffle(tb0, tb4, [4, 5, 6, 7, 12, 13, 14, 15])
+ const t1 = i32x8.shuffle(tb1, tb5, [0, 1, 2, 3, 8, 9, 10, 11])
+ const t5 = i32x8.shuffle(tb1, tb5, [4, 5, 6, 7, 12, 13, 14, 15])
+ const t2 = i32x8.shuffle(tb2, tb6, [0, 1, 2, 3, 8, 9, 10, 11])
+ const t6 = i32x8.shuffle(tb2, tb6, [4, 5, 6, 7, 12, 13, 14, 15])
+ const t3 = i32x8.shuffle(tb3, tb7, [0, 1, 2, 3, 8, 9, 10, 11])
+ const t7 = i32x8.shuffle(tb3, tb7, [4, 5, 6, 7, 12, 13, 14, 15])
+ const ga0 = t0 + t4
+ const ga4 = t0 - t4
+ const ga2 = (t2 >> 1) - t6
+ const ga6 = t2 + (t6 >> 1)
+ const gb0 = ga0 + ga6
+ const gb2 = ga4 + ga2
+ const gb4 = ga4 - ga2
+ const gb6 = ga0 - ga6
+ const ga1 = t5 - t3 - t7 - (t7 >> 1)
+ const ga3 = t1 + t7 - t3 - (t3 >> 1)
+ const ga5 = t7 - t1 + t5 + (t5 >> 1)
+ const ga7 = t3 + t5 + t1 + (t1 >> 1)
+ const gb1 = ga1 + (ga7 >> 2)
+ const gb7 = ga7 - (ga1 >> 2)
+ const gb3 = ga3 + (ga5 >> 2)
+ const gb5 = (ga3 >> 2) - ga5
+ const g0 = gb0 + gb7
+ const g1 = gb2 + gb5
+ const g2 = gb4 + gb3
+ const g3 = gb6 + gb1
+ const g4 = gb6 - gb1
+ const g5 = gb4 - gb3
+ const g6 = gb2 - gb5
+ const g7 = gb0 - gb7
+ const qa0 = i32x8.shuffle(g0, g1, [0, 8, 1, 9, 4, 12, 5, 13])
+ const qa1 = i32x8.shuffle(g0, g1, [2, 10, 3, 11, 6, 14, 7, 15])
+ const qa2 = i32x8.shuffle(g2, g3, [0, 8, 1, 9, 4, 12, 5, 13])
+ const qa3 = i32x8.shuffle(g2, g3, [2, 10, 3, 11, 6, 14, 7, 15])
+ const qa4 = i32x8.shuffle(g4, g5, [0, 8, 1, 9, 4, 12, 5, 13])
+ const qa5 = i32x8.shuffle(g4, g5, [2, 10, 3, 11, 6, 14, 7, 15])
+ const qa6 = i32x8.shuffle(g6, g7, [0, 8, 1, 9, 4, 12, 5, 13])
+ const qa7 = i32x8.shuffle(g6, g7, [2, 10, 3, 11, 6, 14, 7, 15])
+ const qb0 = i32x8.shuffle(qa0, qa2, [0, 1, 8, 9, 4, 5, 12, 13])
+ const qb1 = i32x8.shuffle(qa0, qa2, [2, 3, 10, 11, 6, 7, 14, 15])
+ const qb2 = i32x8.shuffle(qa1, qa3, [0, 1, 8, 9, 4, 5, 12, 13])
+ const qb3 = i32x8.shuffle(qa1, qa3, [2, 3, 10, 11, 6, 7, 14, 15])
+ const qb4 = i32x8.shuffle(qa4, qa6, [0, 1, 8, 9, 4, 5, 12, 13])
+ const qb5 = i32x8.shuffle(qa4, qa6, [2, 3, 10, 11, 6, 7, 14, 15])
+ const qb6 = i32x8.shuffle(qa5, qa7, [0, 1, 8, 9, 4, 5, 12, 13])
+ const qb7 = i32x8.shuffle(qa5, qa7, [2, 3, 10, 11, 6, 7, 14, 15])
+ const q0 = i32x8.shuffle(qb0, qb4, [0, 1, 2, 3, 8, 9, 10, 11])
+ const q4 = i32x8.shuffle(qb0, qb4, [4, 5, 6, 7, 12, 13, 14, 15])
+ const q1 = i32x8.shuffle(qb1, qb5, [0, 1, 2, 3, 8, 9, 10, 11])
+ const q5 = i32x8.shuffle(qb1, qb5, [4, 5, 6, 7, 12, 13, 14, 15])
+ const q2 = i32x8.shuffle(qb2, qb6, [0, 1, 2, 3, 8, 9, 10, 11])
+ const q6 = i32x8.shuffle(qb2, qb6, [4, 5, 6, 7, 12, 13, 14, 15])
+ const q3 = i32x8.shuffle(qb3, qb7, [0, 1, 2, 3, 8, 9, 10, 11])
+ const q7 = i32x8.shuffle(qb3, qb7, [4, 5, 6, 7, 12, 13, 14, 15])
+ const za0 = q0 + q4
+ const za4 = q0 - q4
+ const za2 = (q2 >> 1) - q6
+ const za6 = q2 + (q6 >> 1)
+ const zb0 = za0 + za6
+ const zb2 = za4 + za2
+ const zb4 = za4 - za2
+ const zb6 = za0 - za6
+ const za1 = q5 - q3 - q7 - (q7 >> 1)
+ const za3 = q1 + q7 - q3 - (q3 >> 1)
+ const za5 = q7 - q1 + q5 + (q5 >> 1)
+ const za7 = q3 + q5 + q1 + (q1 >> 1)
+ const zb1 = za1 + (za7 >> 2)
+ const zb7 = za7 - (za1 >> 2)
+ const zb3 = za3 + (za5 >> 2)
+ const zb5 = (za3 >> 2) - za5
+ const z0 = (zb0 + zb7 + rnd) >> 6
+ const z1 = (zb2 + zb5 + rnd) >> 6
+ const z2 = (zb4 + zb3 + rnd) >> 6
+ const z3 = (zb6 + zb1 + rnd) >> 6
+ const z4 = (zb6 - zb1 + rnd) >> 6
+ const z5 = (zb4 - zb3 + rnd) >> 6
+ const z6 = (zb2 - zb5 + rnd) >> 6
+ const z7 = (zb0 - zb7 + rnd) >> 6
+ z0.store(c, o + 0)
+ z1.store(c, o + 8)
+ z2.store(c, o + 16)
+ z3.store(c, o + 24)
+ z4.store(c, o + 32)
+ z5.store(c, o + 40)
+ z6.store(c, o + 48)
+ z7.store(c, o + 56)
+}
+
+export function quant8v(c: Int32Array, o: int, qp: int, intra: bool): int {
+ const qbits = 16 + qpDiv6(qp)
+ const qm = qpMod6(qp) * 64
+ const f = i32x8.splat(quantOffset(qbits, intra))
+ const zero = i32x8.splat(0)
+ let nzv = zero
+ for (let k = 0; k < 8; k++) {
+ const v = i32x8.load(c, o + k * 8)
+ const l = (v.abs() * i32x8.load(QUANT8, qm + k * 8) + f) >> qbits
+ const q = i32x8.select(v.lt(zero), zero - l, l)
+ nzv += q.ne(zero)
+ q.store(c, o + k * 8)
+ }
+ return -nzv.sum()
+}
+
+export function dequant8v(c: Int32Array, o: int, out: Int32Array, oo: int, qp: int) {
+ const q6 = qpDiv6(qp)
+ const qm = qpMod6(qp) * 64
+ const s16 = i32x8.splat(16)
+ if (q6 >= 6) {
+ for (let k = 0; k < 8; k++) {
+ const d = (i32x8.load(c, o + k * 8) * i32x8.load(DEQUANT8, qm + k * 8) * s16) << (q6 - 6)
+ d.store(out, oo + k * 8)
+ }
+ return
+ }
+ const r = i32x8.splat(1 << (5 - q6))
+ for (let k = 0; k < 8; k++) {
+ const d = (i32x8.load(c, o + k * 8) * i32x8.load(DEQUANT8, qm + k * 8) * s16 + r) >> (6 - q6)
+ d.store(out, oo + k * 8)
+ }
+}
+
+export function recon8(rec: Uint8Array, ro: int, rs: int, c: Int32Array, o: int, pred: Uint8Array, po: int, ps: int) {
+ for (let y = 0; y < 8; y++) {
+ const r = i16x8.packSat(i32x4.load(c, o + y * 8), i32x4.load(c, o + y * 8 + 4)).addSat(i16x8.loadU8(pred, po + y * ps))
+ r.storeU8(rec, ro + y * rs)
+ }
+}
+
+export function recon8b(blk: Uint8Array, bo: int, c: Int32Array, o: int, pred: Uint8Array, po: int) {
+ for (let y = 0; y < 8; y += 2) {
+ const r0 = i16x8.packSat(i32x4.load(c, o + y * 8), i32x4.load(c, o + y * 8 + 4)).addSat(i16x8.loadU8(pred, po + y * 8))
+ const r1 = i16x8.packSat(i32x4.load(c, o + y * 8 + 8), i32x4.load(c, o + y * 8 + 12)).addSat(i16x8.loadU8(pred, po + y * 8 + 8))
+ u8x16.packSat(r0, r1).store(blk, bo + y * 8)
+ }
+}
+
+function pixels(seed: int, n: int): Uint8Array {
+ let out: u8[] = []
+ let x = seed
+ for (let i = 0; i < n; i++) {
+ x = (x * 1103515245 + 12345) & 0x7fffffff
+ const v = i % 9 === 0 ? 255 : i % 13 === 0 ? 0 : (x >> 9) & 255
+ out.push(u8(v))
+ }
+ return new Uint8Array(out)
+}
+
+test("vector 4x4 transform, quantisation and inverse match the scalar ones exactly", () => {
+ let bad = 0
+ for (let seed = 1; seed <= 200; seed++) {
+ const src = pixels(seed, 64)
+ const pred = seed % 4 === 0 ? pixels(seed + 1, 64) : pixels(seed * 7 + 3, 64)
+ const qp = seed % 52
+ const intra = seed % 3 === 0
+ const start = seed % 5 === 0 ? 1 : 0
+ let ref: int[] = []
+ for (let y = 0; y < 4; y++) {
+ for (let x = 0; x < 4; x++) ref.push(int(src[y * 8 + x]!) - int(pred[y * 8 + x]!))
+ }
+ fdct4(&ref, 0)
+ const v = new Int32Array(16)
+ fwd4(src, 0, 8, pred, 0, 8, v, 0)
+ for (let i = 0; i < 16; i++) {
+ if (int(v[i]!) !== ref[i]!) bad++
+ }
+ const nzRef = quant4(&ref, 0, qp, intra, start)
+ const nzV = quant4v(v, 0, qp, intra, start)
+ if (nzRef !== nzV) bad++
+ for (let i = 0; i < 16; i++) {
+ if (int(v[i]!) !== ref[i]!) bad++
+ }
+ dequant4(&ref, 0, qp, start)
+ dequant4v(v, 0, qp)
+ if (start > 0) v[0] = ref[0]!
+ for (let i = 0; i < 16; i++) {
+ if (int(v[i]!) !== ref[i]!) bad++
+ }
+ idct4(&ref, 0)
+ idct4v(v, 0)
+ for (let i = 0; i < 16; i++) {
+ if (int(v[i]!) !== ref[i]!) bad++
+ }
+ }
+ expect(bad).toBe(0)
+})
+
+test("chromaAcZero only reports a plane whose four blocks' AC all quantise to zero", () => {
+ let bad = 0
+ let zero = 0
+ let coded = 0
+ for (let seed = 1; seed <= 600; seed++) {
+ const src = pixels(seed, 64)
+ const noise = pixels(seed * 3 + 1, 64)
+ const amp = seed % 7 === 0 ? 255 : seed % 13
+ const pred = new Uint8Array(64)
+ for (let i = 0; i < 64; i++) {
+ const p = int(src[i]!) + int(noise[i]!) % (2 * amp + 1) - amp
+ pred[i] = p < 0 ? 0 : p > 255 ? 255 : p
+ }
+ const qp = seed % 40
+ const intra = seed % 2 === 0
+ const c = new Int32Array(64)
+ fwd4x2(src, 0, 8, pred, 0, 8, c, 0)
+ fwd4x2(src, 32, 8, pred, 32, 8, c, 32)
+ const az = chromaAcZero(c, 0, qp, intra)
+ let nz = 0
+ for (let b = 0; b < 4; b++) nz += quant4v(c, b * 16, qp, intra, 1)
+ if (az && nz > 0) bad++
+ if (az) zero++
+ if (nz > 0) coded++
+ }
+ expect(bad).toBe(0)
+ expect(zero > 50).toBe(true)
+ expect(coded > 50).toBe(true)
+})
+
+test("chromaAcZero is exact for one AC coefficient at a largest-factor position", () => {
+ let bad = 0
+ for (let qp = 0; qp < 52; qp++) {
+ for (let k = 0; k < 2; k++) {
+ const intra = k === 1
+ let lo = 0
+ let hi = 9200
+ while (hi - lo > 1) {
+ const mid = (lo + hi) >> 1
+ const t = new Int32Array(16)
+ t[2] = mid
+ if (quant4v(t, 0, qp, intra, 1) > 0) {
+ hi = mid
+ } else {
+ lo = mid
+ }
+ }
+ for (let b = 0; b < 4; b++) {
+ const pos = b * 16 + (b % 2 === 0 ? 2 : 8)
+ for (let s = -1; s <= 1; s += 2) {
+ const c = new Int32Array(64)
+ c[b * 16] = 5000
+ c[pos] = s * lo
+ if (!chromaAcZero(c, 0, qp, intra)) bad++
+ c[pos] = s * hi
+ if (chromaAcZero(c, 0, qp, intra)) bad++
+ }
+ }
+ }
+ }
+ expect(bad).toBe(0)
+})
+
+test("paired 4x4 transform equals two single ones", () => {
+ let bad = 0
+ for (let seed = 1; seed <= 100; seed++) {
+ const src = pixels(seed * 11, 96)
+ const pred = seed % 4 === 0 ? pixels(seed + 5, 96) : pixels(seed * 3 + 7, 96)
+ const a = new Int32Array(40)
+ const b = new Int32Array(40)
+ a.fill(seed)
+ b.fill(seed)
+ fwd4(src, 1, 24, pred, 2, 20, a, 3)
+ fwd4(src, 5, 24, pred, 6, 20, a, 19)
+ fwd4x2(src, 1, 24, pred, 2, 20, b, 3)
+ for (let i = 0; i < 40; i++) {
+ if (a[i]! !== b[i]!) bad++
+ }
+ }
+ expect(bad).toBe(0)
+})
+
+test("fused 4x4 coding matches transform, quantisation, zigzag and reconstruction one step at a time", () => {
+ let bad = 0
+ for (let seed = 1; seed <= 400; seed++) {
+ const src = pixels(seed * 11 + 7, 16)
+ const pred = seed % 3 === 0 ? pixels(seed * 5 + 2, 16) : pixels(seed * 17 + 9, 16)
+ if (seed % 7 === 0) {
+ for (let i = 0; i < 16; i++) src[i] = Math.min(255, Math.max(0, int(pred[i]!) + (i % 3) - 1))
+ }
+ const qp = seed % 52
+ const intra = seed % 4 !== 0
+ const v = new Int32Array(16)
+ fwd4(src, 0, 4, pred, 0, 4, v, 0)
+ const nzRef = quant4v(v, 0, qp, intra, 0)
+ const zRef = new Int16Array(20)
+ zigzag4(v, 0, zRef, 2)
+ const a = pixels(seed * 3 + 1, 40 * 8)
+ const b = pixels(seed * 5 + 3, 24)
+ const keep = new Uint8Array(b)
+ if (nzRef > 0) {
+ dequant4v(v, 0, qp)
+ idct4v(v, 0)
+ recon4(a, 45, 40, v, 0, pred, 0, 4)
+ } else {
+ copy4(a, 45, 40, pred, 0, 4)
+ }
+ const z = new Int16Array(20)
+ const nz = code4(u8x16.load(src, 0), u8x16.load(pred, 0), qp, intra, z, 2, b, 5)
+ if (nz !== nzRef) bad++
+ for (let i = 0; i < 20; i++) {
+ if (z[i]! !== zRef[i]!) bad++
+ }
+ for (let i = 0; i < 16; i++) {
+ if (b[5 + i]! !== a[45 + (i >> 2) * 40 + (i & 3)]!) bad++
+ }
+ for (let i = 0; i < 24; i++) {
+ if ((i < 5 || i >= 21) && b[i]! !== keep[i]!) bad++
+ }
+ }
+ expect(bad).toBe(0)
+})
+
+test("chroma 8x8 inverse transform matches four 4x4 inverses and the chroma reconstruction", () => {
+ let bad = 0
+ for (let seed = 1; seed <= 200; seed++) {
+ const pred = seed % 5 === 0 ? pixels(seed * 3 + 8, 64) : pixels(seed * 23 + 1, 64)
+ const px = pixels(seed * 29 + 6, 64)
+ const scale = seed % 7 === 0 ? 700 : seed % 3 + 1
+ const a = new Int32Array(80)
+ const b = new Int32Array(80)
+ for (let i = 0; i < 64; i++) a[9 + i] = (int(px[i]!) - 128) * scale
+ for (let i = 0; i < 64; i++) b[9 + i] = a[9 + i]!
+ for (let k = 0; k < 4; k++) idct4v(a, 9 + k * 16)
+ const ra = pixels(seed * 31 + 2, 8 * 24 + 16)
+ const rb = new Uint8Array(ra)
+ reconC8(ra, 5, 24, a, 9, pred, 0, 8)
+ idctC8(b, 9, rb, 5, 24, pred, 0)
+ for (let i = 0; i < ra.length; i++) {
+ if (ra[i]! !== rb[i]!) bad++
+ }
+ }
+ expect(bad).toBe(0)
+})
+
+test("DC-only luma 16x16 and chroma 8x8 reconstruction match the inverse transform of DC-only blocks", () => {
+ let bad = 0
+ for (let seed = 1; seed <= 300; seed++) {
+ const pred = pixels(seed * 19 + 4, 256)
+ const px = pixels(seed * 37 + 2, 16)
+ const scale = seed % 5 === 0 ? 2000 : seed % 4 + 1
+ const dc = new Int32Array(20)
+ for (let i = 0; i < 16; i++) dc[i] = (int(px[i]!) - 128) * scale
+ const c = new Int32Array(256)
+ for (let b = 0; b < 16; b++) {
+ c[b * 16] = dc[b]!
+ idct4v(c, b * 16)
+ }
+ const a = pixels(seed * 41 + 9, 20 * 24)
+ const b = new Uint8Array(a)
+ recon16(a, 3, 20, c, pred, 0)
+ reconDc16(b, 3, 20, dc, pred, 0)
+ for (let i = 0; i < a.length; i++) {
+ if (a[i]! !== b[i]!) bad++
+ }
+ const cc = new Int32Array(80)
+ for (let k = 0; k < 4; k++) cc[9 + k * 16] = dc[2 + k]!
+ const ca = pixels(seed * 43 + 1, 10 * 16)
+ const cb = new Uint8Array(ca)
+ idctC8(cc, 9, ca, 1, 16, pred, 64)
+ reconDcC8(cb, 1, 16, dc, 2, pred, 64)
+ for (let i = 0; i < ca.length; i++) {
+ if (ca[i]! !== cb[i]!) bad++
+ }
+ const za = pixels(seed * 47 + 3, 20 * 18)
+ const zb = new Uint8Array(za)
+ copy16(za, 21, 20, pred, 0)
+ for (let y = 0; y < 16; y++) {
+ for (let x = 0; x < 16; x++) zb[21 + y * 20 + x] = pred[y * 16 + x]!
+ }
+ for (let i = 0; i < za.length; i++) {
+ if (za[i]! !== zb[i]!) bad++
+ }
+ }
+ expect(bad).toBe(0)
+})
+
+test("vector 8x8 transform, quantisation and inverse match the scalar ones exactly", () => {
+ let bad = 0
+ for (let seed = 1; seed <= 150; seed++) {
+ const src = pixels(seed * 3, 128)
+ const pred = seed % 4 === 0 ? pixels(seed + 11, 128) : pixels(seed * 5 + 1, 128)
+ const qp = seed % 52
+ const intra = seed % 3 === 0
+ let ref: int[] = []
+ for (let y = 0; y < 8; y++) {
+ for (let x = 0; x < 8; x++) ref.push(int(src[y * 16 + x]!) - int(pred[y * 16 + x]!))
+ }
+ fdct8(&ref, 0)
+ const v = new Int32Array(64)
+ fwd8(src, 0, 16, pred, 0, 16, v, 0)
+ for (let i = 0; i < 64; i++) {
+ if (int(v[i]!) !== ref[i]!) bad++
+ }
+ const nzRef = quant8(&ref, 0, qp, intra)
+ if (quant8v(v, 0, qp, intra) !== nzRef) bad++
+ for (let i = 0; i < 64; i++) {
+ if (int(v[i]!) !== ref[i]!) bad++
+ }
+ dequant8(&ref, 0, qp)
+ dequant8v(v, 0, v, 0, qp)
+ for (let i = 0; i < 64; i++) {
+ if (int(v[i]!) !== ref[i]!) bad++
+ }
+ idct8(&ref, 0)
+ idct8v(v, 0)
+ for (let i = 0; i < 64; i++) {
+ if (int(v[i]!) !== ref[i]!) bad++
+ }
+ }
+ expect(bad).toBe(0)
+})
+
+function sameAs(v: Int32Array, o: int, ref: int[], ro: int, n: int): int {
+ let bad = 0
+ for (let i = 0; i < n; i++) {
+ if (int(v[o + i]!) !== ref[ro + i]!) bad++
+ }
+ return bad
+}
+
+test("vector DC transforms, reconstruction, copies and zigzag scans match the scalar ones exactly", () => {
+ let bad = 0
+ for (let seed = 1; seed <= 300; seed++) {
+ const qp = seed % 52
+ const qpc = seed % 40
+ const intra = seed % 3 !== 0
+ const px = pixels(seed * 13 + 5, 1024)
+ let ref: int[] = []
+ for (let i = 0; i < 16; i++) ref.push((int(px[i]!) - 128) * 32)
+ const v = new Int32Array(ref)
+ hadamard4(&ref, 0, true)
+ hadamard4v(v, 0, true)
+ bad += sameAs(v, 0, ref, 0, 16)
+ if (quantDc(&ref, 0, 16, qp, intra) !== quantDcv(v, 0, 16, qp, intra)) bad++
+ bad += sameAs(v, 0, ref, 0, 16)
+ hadamard4(&ref, 0, false)
+ hadamard4v(v, 0, false)
+ bad += sameAs(v, 0, ref, 0, 16)
+ dequantLumaDc(&ref, 0, qp)
+ dequantLumaDcv(v, 0, qp)
+ bad += sameAs(v, 0, ref, 0, 16)
+ let cr: int[] = []
+ for (let i = 0; i < 4; i++) cr.push((int(px[16 + i]!) - 128) * 32)
+ const cv = new Int32Array(cr)
+ hadamard2(&cr, 0)
+ hadamard2v(cv, 0)
+ bad += sameAs(cv, 0, cr, 0, 4)
+ if (quantDc(&cr, 0, 4, qpc, intra) !== quantDcv(cv, 0, 4, qpc, intra)) bad++
+ bad += sameAs(cv, 0, cr, 0, 4)
+ hadamard2(&cr, 0)
+ hadamard2v(cv, 0)
+ dequantChromaDc(&cr, 0, qpc)
+ dequantChromaDcv(cv, 0, qpc)
+ bad += sameAs(cv, 0, cr, 0, 4)
+ let res: int[] = []
+ for (let i = 0; i < 256; i++) res.push((int(px[256 + i]!) - 128) * (seed % 4 + 1))
+ const rv = new Int32Array(res)
+ const pred = pixels(seed * 7 + 1, 256)
+ const a = new Uint8Array(512)
+ const b = new Uint8Array(512)
+ for (let blk = 0; blk < 16; blk++) {
+ const o = (blk >> 2) * 64 + (blk & 3) * 4
+ reconAdd(a, o, 16, 4, res, blk * 16, pred, o, 16)
+ }
+ recon16(b, 0, 16, rv, pred, 0)
+ for (let i = 0; i < 512; i++) {
+ if (a[i]! !== b[i]!) bad++
+ }
+ a.fill(0)
+ b.fill(0)
+ reconAdd(a, 3, 24, 4, res, 32, pred, 5, 16)
+ recon4(b, 3, 24, rv, 32, pred, 5, 16)
+ reconAdd(a, 200, 24, 8, res, 64, pred, 17, 16)
+ recon8(b, 200, 24, rv, 64, pred, 17, 16)
+ reconAdd(a, 400, 8, 8, res, 128, pred, 40, 8)
+ recon8b(b, 400, rv, 128, pred, 40)
+ for (let i = 0; i < 512; i++) {
+ if (a[i]! !== b[i]!) bad++
+ }
+ a.fill(0)
+ b.fill(0)
+ for (let blk = 0; blk < 4; blk++) {
+ const o = (blk >> 1) * 32 + (blk & 1) * 4
+ reconAdd(a, (blk >> 1) * 4 * 20 + (blk & 1) * 4 + 1, 20, 4, res, 128 + blk * 16, pred, o, 8)
+ }
+ reconC8(b, 1, 20, rv, 128, pred, 0, 8)
+ copy4(a, 300, 24, pred, 9, 16)
+ copy8(a, 340, 21, pred, 40, 16)
+ for (let y = 0; y < 4; y++) {
+ for (let x = 0; x < 4; x++) b[300 + y * 24 + x] = pred[9 + y * 16 + x]!
+ }
+ for (let y = 0; y < 8; y++) {
+ for (let x = 0; x < 8; x++) b[340 + y * 21 + x] = pred[40 + y * 16 + x]!
+ }
+ for (let i = 0; i < 512; i++) {
+ if (a[i]! !== b[i]!) bad++
+ }
+ const zz = new Int16Array(32)
+ zigzag4(rv, 48, zz, 0)
+ zigzagAc4(rv, 80, zz, 16)
+ for (let k = 0; k < 16; k++) {
+ if (int(zz[k]!) !== res[48 + ZIGZAG4[k]!]!) bad++
+ }
+ for (let k = 1; k < 16; k++) {
+ if (int(zz[16 + k - 1]!) !== res[80 + ZIGZAG4[k]!]!) bad++
+ }
+ if (zz[31]! !== 0) bad++
+ const z8 = new Int16Array(70)
+ zigzag8(rv, 128, z8, 3)
+ for (let k = 0; k < 64; k++) {
+ if (int(z8[3 + k]!) !== res[128 + ZIGZAG8[k]!]!) bad++
+ }
+ }
+ expect(bad).toBe(0)
+})
diff --git a/capcodec/src/transform.tov b/capcodec/src/transform.tov
new file mode 100644
index 000000000..80e1edd1b
--- /dev/null
+++ b/capcodec/src/transform.tov
@@ -0,0 +1,384 @@
+import { QUANT4, DEQUANT4, QUANT8, DEQUANT8 } from "./tables"
+
+// Exact for 0 <= qp < 80 and qbits <= 30; Math.trunc of a division costs a float division and a conversion call per block,
+// and a signed 64-bit `qp % 6` a magic multiply with sign fix-ups.
+export function qpDiv6(qp: int): int {
+ return (qp * 43) >> 8
+}
+
+export function qpMod6(qp: int): int {
+ return qp - 6 * qpDiv6(qp)
+}
+
+export function quantOffset(qbits: int, intra: bool): int {
+ return ((1 << qbits) * (intra ? 0x55555556 : 0x2AAAAAAB)) >> 32
+}
+
+function dct8line(inout b: int[], o: int, s: int) {
+ const x0 = b[o]!
+ const x1 = b[o + s]!
+ const x2 = b[o + 2 * s]!
+ const x3 = b[o + 3 * s]!
+ const x4 = b[o + 4 * s]!
+ const x5 = b[o + 5 * s]!
+ const x6 = b[o + 6 * s]!
+ const x7 = b[o + 7 * s]!
+ const s07 = x0 + x7
+ const s16 = x1 + x6
+ const s25 = x2 + x5
+ const s34 = x3 + x4
+ const a0 = s07 + s34
+ const a1 = s16 + s25
+ const a2 = s07 - s34
+ const a3 = s16 - s25
+ const d07 = x0 - x7
+ const d16 = x1 - x6
+ const d25 = x2 - x5
+ const d34 = x3 - x4
+ const a4 = d16 + d25 + (d07 + (d07 >> 1))
+ const a5 = d07 - d34 - (d25 + (d25 >> 1))
+ const a6 = d07 + d34 - (d16 + (d16 >> 1))
+ const a7 = d16 - d25 + (d34 + (d34 >> 1))
+ b[o] = a0 + a1
+ b[o + 4 * s] = a0 - a1
+ b[o + 2 * s] = a2 + (a3 >> 1)
+ b[o + 6 * s] = (a2 >> 1) - a3
+ b[o + s] = a4 + (a7 >> 2)
+ b[o + 3 * s] = a5 + (a6 >> 2)
+ b[o + 5 * s] = a6 - (a5 >> 2)
+ b[o + 7 * s] = (a4 >> 2) - a7
+}
+
+function idct8line(inout b: int[], o: int, s: int, last: bool) {
+ const d0 = b[o]!
+ const d1 = b[o + s]!
+ const d2 = b[o + 2 * s]!
+ const d3 = b[o + 3 * s]!
+ const d4 = b[o + 4 * s]!
+ const d5 = b[o + 5 * s]!
+ const d6 = b[o + 6 * s]!
+ const d7 = b[o + 7 * s]!
+ const a0 = d0 + d4
+ const a4 = d0 - d4
+ const a2 = (d2 >> 1) - d6
+ const a6 = d2 + (d6 >> 1)
+ const b0 = a0 + a6
+ const b2 = a4 + a2
+ const b4 = a4 - a2
+ const b6 = a0 - a6
+ const a1 = -d3 + d5 - d7 - (d7 >> 1)
+ const a3 = d1 + d7 - d3 - (d3 >> 1)
+ const a5 = -d1 + d7 + d5 + (d5 >> 1)
+ const a7 = d3 + d5 + d1 + (d1 >> 1)
+ const b1 = a1 + (a7 >> 2)
+ const b7 = a7 - (a1 >> 2)
+ const b3 = a3 + (a5 >> 2)
+ const b5 = (a3 >> 2) - a5
+ const r = last ? 32 : 0
+ const sh = last ? 6 : 0
+ b[o] = (b0 + b7 + r) >> sh
+ b[o + s] = (b2 + b5 + r) >> sh
+ b[o + 2 * s] = (b4 + b3 + r) >> sh
+ b[o + 3 * s] = (b6 + b1 + r) >> sh
+ b[o + 4 * s] = (b6 - b1 + r) >> sh
+ b[o + 5 * s] = (b4 - b3 + r) >> sh
+ b[o + 6 * s] = (b2 - b5 + r) >> sh
+ b[o + 7 * s] = (b0 - b7 + r) >> sh
+}
+
+export function fdct8(inout blk: int[], o: int) {
+ for (let i = 0; i < 8; i++) dct8line(&blk, o + i * 8, 1)
+ for (let i = 0; i < 8; i++) dct8line(&blk, o + i, 8)
+}
+
+export function idct8(inout blk: int[], o: int) {
+ for (let i = 0; i < 8; i++) idct8line(&blk, o + i * 8, 1, false)
+ for (let i = 0; i < 8; i++) idct8line(&blk, o + i, 8, true)
+}
+
+export function quant8(inout blk: int[], o: int, qp: int, intra: bool): int {
+ const qbits = 16 + qpDiv6(qp)
+ const fi = quantOffset(qbits, intra)
+ const qm = (qp % 6) * 64
+ let nz = 0
+ for (let i = 0; i < 64; i++) {
+ const c = blk[o + i]!
+ if (c === 0) continue
+ const mf = int(QUANT8[qm + i]!)
+ const l = c > 0 ? (c * mf + fi) >> qbits : -(((-c) * mf + fi) >> qbits)
+ blk[o + i] = l
+ if (l !== 0) nz++
+ }
+ return nz
+}
+
+export function dequant8(inout blk: int[], o: int, qp: int) {
+ const q6 = qpDiv6(qp)
+ const qm = (qp % 6) * 64
+ for (let i = 0; i < 64; i++) {
+ const c = blk[o + i]!
+ if (c === 0) continue
+ const ls = 16 * int(DEQUANT8[qm + i]!)
+ if (q6 >= 6) {
+ blk[o + i] = (c * ls) << (q6 - 6)
+ } else {
+ blk[o + i] = (c * ls + (1 << (5 - q6))) >> (6 - q6)
+ }
+ }
+}
+
+export function fdct4(inout blk: int[], o: int) {
+ for (let i = 0; i < 4; i++) {
+ const r = o + i * 4
+ const x0 = blk[r]!
+ const x1 = blk[r + 1]!
+ const x2 = blk[r + 2]!
+ const x3 = blk[r + 3]!
+ const s0 = x0 + x3
+ const s1 = x1 + x2
+ const d0 = x0 - x3
+ const d1 = x1 - x2
+ blk[r] = s0 + s1
+ blk[r + 2] = s0 - s1
+ blk[r + 1] = 2 * d0 + d1
+ blk[r + 3] = d0 - 2 * d1
+ }
+ for (let i = 0; i < 4; i++) {
+ const c = o + i
+ const x0 = blk[c]!
+ const x1 = blk[c + 4]!
+ const x2 = blk[c + 8]!
+ const x3 = blk[c + 12]!
+ const s0 = x0 + x3
+ const s1 = x1 + x2
+ const d0 = x0 - x3
+ const d1 = x1 - x2
+ blk[c] = s0 + s1
+ blk[c + 8] = s0 - s1
+ blk[c + 4] = 2 * d0 + d1
+ blk[c + 12] = d0 - 2 * d1
+ }
+}
+
+export function idct4(inout blk: int[], o: int) {
+ for (let i = 0; i < 4; i++) {
+ const r = o + i * 4
+ const d0 = blk[r]!
+ const d1 = blk[r + 1]!
+ const d2 = blk[r + 2]!
+ const d3 = blk[r + 3]!
+ const e = d0 + d2
+ const f = d0 - d2
+ const g = (d1 >> 1) - d3
+ const h = d1 + (d3 >> 1)
+ blk[r] = e + h
+ blk[r + 1] = f + g
+ blk[r + 2] = f - g
+ blk[r + 3] = e - h
+ }
+ for (let i = 0; i < 4; i++) {
+ const c = o + i
+ const d0 = blk[c]!
+ const d1 = blk[c + 4]!
+ const d2 = blk[c + 8]!
+ const d3 = blk[c + 12]!
+ const e = d0 + d2
+ const f = d0 - d2
+ const g = (d1 >> 1) - d3
+ const h = d1 + (d3 >> 1)
+ blk[c] = (e + h + 32) >> 6
+ blk[c + 4] = (f + g + 32) >> 6
+ blk[c + 8] = (f - g + 32) >> 6
+ blk[c + 12] = (e - h + 32) >> 6
+ }
+}
+
+export function hadamard4(inout blk: int[], o: int, forward: bool) {
+ for (let i = 0; i < 4; i++) {
+ const r = o + i * 4
+ const x0 = blk[r]!
+ const x1 = blk[r + 1]!
+ const x2 = blk[r + 2]!
+ const x3 = blk[r + 3]!
+ const s0 = x0 + x1
+ const s1 = x2 + x3
+ const d0 = x0 - x1
+ const d1 = x2 - x3
+ blk[r] = s0 + s1
+ blk[r + 1] = s0 - s1
+ blk[r + 2] = d0 - d1
+ blk[r + 3] = d0 + d1
+ }
+ for (let i = 0; i < 4; i++) {
+ const c = o + i
+ const x0 = blk[c]!
+ const x1 = blk[c + 4]!
+ const x2 = blk[c + 8]!
+ const x3 = blk[c + 12]!
+ const s0 = x0 + x1
+ const s1 = x2 + x3
+ const d0 = x0 - x1
+ const d1 = x2 - x3
+ if (forward) {
+ blk[c] = (s0 + s1) >> 1
+ blk[c + 4] = (s0 - s1) >> 1
+ blk[c + 8] = (d0 - d1) >> 1
+ blk[c + 12] = (d0 + d1) >> 1
+ } else {
+ blk[c] = s0 + s1
+ blk[c + 4] = s0 - s1
+ blk[c + 8] = d0 - d1
+ blk[c + 12] = d0 + d1
+ }
+ }
+}
+
+export function quantScale(qp: int, pos: int): int {
+ return int(QUANT4[(qp % 6) * 16 + pos]!)
+}
+
+export function dequantScale(qp: int, pos: int): int {
+ return int(DEQUANT4[(qp % 6) * 16 + pos]!)
+}
+
+export function quant4(inout blk: int[], o: int, qp: int, intra: bool, startPos: int): int {
+ const qbits = 15 + qpDiv6(qp)
+ const fi = quantOffset(qbits, intra)
+ const qm = (qp % 6) * 16
+ let nz = 0
+ for (let i = startPos; i < 16; i++) {
+ const c = blk[o + i]!
+ const mf = int(QUANT4[qm + i]!)
+ if (c >= 0) {
+ const l = (c * mf + fi) >> qbits
+ blk[o + i] = l
+ if (l !== 0) nz++
+ } else {
+ const l = ((-c) * mf + fi) >> qbits
+ blk[o + i] = -l
+ if (l !== 0) nz++
+ }
+ }
+ return nz
+}
+
+export function dequant4(inout blk: int[], o: int, qp: int, startPos: int) {
+ const shift = qpDiv6(qp)
+ const qm = (qp % 6) * 16
+ for (let i = startPos; i < 16; i++) {
+ const c = blk[o + i]!
+ if (c !== 0) blk[o + i] = (c * int(DEQUANT4[qm + i]!)) << shift
+ }
+}
+
+export function quantDc(inout blk: int[], o: int, n: int, qp: int, intra: bool): int {
+ const qbits = 16 + qpDiv6(qp)
+ const f = quantOffset(qbits, intra)
+ const mf = int(QUANT4[(qp % 6) * 16]!)
+ let nz = 0
+ for (let i = 0; i < n; i++) {
+ const c = blk[o + i]!
+ const l = c >= 0 ? (c * mf + f) >> qbits : -(((-c) * mf + f) >> qbits)
+ blk[o + i] = l
+ if (l !== 0) nz++
+ }
+ return nz
+}
+
+export function dequantLumaDc(inout blk: int[], o: int, qp: int) {
+ const ls = 16 * int(DEQUANT4[(qp % 6) * 16]!)
+ const q6 = qpDiv6(qp)
+ for (let i = 0; i < 16; i++) {
+ const f = blk[o + i]!
+ if (qp >= 36) {
+ blk[o + i] = (f * ls) << (q6 - 6)
+ } else {
+ blk[o + i] = (f * ls + (1 << (5 - q6))) >> (6 - q6)
+ }
+ }
+}
+
+export function hadamard2(inout blk: int[], o: int) {
+ const c0 = blk[o]!
+ const c1 = blk[o + 1]!
+ const c2 = blk[o + 2]!
+ const c3 = blk[o + 3]!
+ blk[o] = c0 + c1 + c2 + c3
+ blk[o + 1] = c0 - c1 + c2 - c3
+ blk[o + 2] = c0 + c1 - c2 - c3
+ blk[o + 3] = c0 - c1 - c2 + c3
+}
+
+export function dequantChromaDc(inout blk: int[], o: int, qp: int) {
+ const ls = 16 * int(DEQUANT4[(qp % 6) * 16]!)
+ const q6 = qpDiv6(qp)
+ for (let i = 0; i < 4; i++) {
+ blk[o + i] = ((blk[o + i]! * ls) << q6) >> 5
+ }
+}
+
+test("integer quantiser helpers match the float definitions", () => {
+ let bad = 0
+ for (let qp = 0; qp < 80; qp++) {
+ if (qpDiv6(qp) !== Math.trunc(qp / 6)) bad++
+ if (qpMod6(qp) !== qp % 6) bad++
+ }
+ for (let qbits = 0; qbits <= 30; qbits++) {
+ if (quantOffset(qbits, true) !== Math.trunc((1 << qbits) / 3)) bad++
+ if (quantOffset(qbits, false) !== Math.trunc((1 << qbits) / 6)) bad++
+ }
+ expect(bad).toBe(0)
+})
+
+test("forward then inverse 4x4 transform with flat dequant reconstructs a residual", () => {
+ let b: int[] = []
+ for (let i = 0; i < 16; i++) b.push(((i * 37) % 23) - 11)
+ const orig = b.slice()
+ fdct4(&b, 0)
+ quant4(&b, 0, 0, true, 0)
+ dequant4(&b, 0, 0, 0)
+ idct4(&b, 0)
+ let maxErr = 0
+ for (let i = 0; i < 16; i++) maxErr = Math.max(maxErr, Math.abs(b[i]! - orig[i]!))
+ expect(maxErr <= 1).toBe(true)
+})
+
+test("transform of a flat block has only DC", () => {
+ let b: int[] = []
+ for (let i = 0; i < 16; i++) b.push(5)
+ fdct4(&b, 0)
+ expect(b[0]!).toBe(80)
+ let rest = 0
+ for (let i = 1; i < 16; i++) rest += Math.abs(b[i]!)
+ expect(rest).toBe(0)
+})
+
+test("quantisation at qp 28 matches the reference formula", () => {
+ let b: int[] = [1000, -1000, 37, -37, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
+ quant4(&b, 0, 28, false, 0)
+ expect(b[0]!).toBe(Math.trunc((1000 * 8192 + Math.trunc(524288 / 6)) / 524288))
+ expect(b[1]!).toBe(-Math.trunc((1000 * 5243 + Math.trunc(524288 / 6)) / 524288))
+ expect(b[2]!).toBe(Math.trunc((37 * 8192 + Math.trunc(524288 / 6)) / 524288))
+})
+
+test("hadamard 4x4 inverse of forward is 8x identity before the encoder's halving", () => {
+ let b: int[] = []
+ for (let i = 0; i < 16; i++) b.push(i * 2)
+ const orig = b.slice()
+ hadamard4(&b, 0, false)
+ hadamard4(&b, 0, false)
+ for (let i = 0; i < 16; i++) expect(b[i]!).toBe(16 * orig[i]!)
+})
+
+test("8x8 transform round trip at qp 0", () => {
+ let b: int[] = []
+ for (let i = 0; i < 64; i++) b.push(((i * 53) % 41) - 20)
+ const orig = b.slice()
+ fdct8(&b, 0)
+ quant8(&b, 0, 0, true)
+ dequant8(&b, 0, 0)
+ idct8(&b, 0)
+ let maxErr = 0
+ for (let i = 0; i < 64; i++) maxErr = Math.max(maxErr, Math.abs(b[i]! - orig[i]!))
+ expect(maxErr <= 1).toBe(true)
+})
diff --git a/capcodec/tools/backup.sh b/capcodec/tools/backup.sh
new file mode 100755
index 000000000..b824d7c15
--- /dev/null
+++ b/capcodec/tools/backup.sh
@@ -0,0 +1,14 @@
+#!/usr/bin/env bash
+set -euo pipefail
+DEST="${CAPCODEC_BACKUP:-/cursor/stores/self/backups}"
+mkdir -p "$DEST"
+cd "$(dirname "$0")/.."
+git bundle create "$DEST/capcodec.bundle" --all >/dev/null 2>&1
+git -C "$HOME/work/tov" bundle create "$DEST/tov-encoder-features.bundle" --branches >/dev/null 2>&1 || true
+CAP="${CAP_REPO:-/workspace}"
+if git -C "$CAP" rev-parse --verify -q cursor/capcodec-integration-aa45 >/dev/null; then
+ git -C "$CAP" bundle create "$DEST/cap-integration.bundle" origin/main..cursor/capcodec-integration-aa45 >/dev/null 2>&1 || true
+fi
+cp PROGRESS.md "$DEST/PROGRESS.md"
+date -u +%Y-%m-%dT%H:%M:%SZ > "$DEST/last_backup.txt"
+ls -la "$DEST"
diff --git a/capcodec/tools/gen_tables.py b/capcodec/tools/gen_tables.py
new file mode 100644
index 000000000..70ae33035
--- /dev/null
+++ b/capcodec/tools/gen_tables.py
@@ -0,0 +1,201 @@
+#!/usr/bin/env python3
+import re
+import sys
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parents[1]
+JM = Path.home() / "tools" / "JM-master" / "source"
+FF = Path.home() / "work" / "refsrc"
+OUT = ROOT / "src" / "tables.tov"
+# Tables wider than their values need: the quantisers are loaded as i32 vectors, and byte loads
+# of the zigzag and deblocking tables cost instructions in their hot loops (callgrind).
+ELEM = {
+ "QUANT4": "i32", "DEQUANT4": "i32", "QUANT8": "i32", "DEQUANT8": "i32",
+ "ZIGZAG4": "int", "ZIGZAG8": "int", "DEBLOCK_ALPHA": "int", "DEBLOCK_BETA": "int", "DEBLOCK_TC0": "int",
+}
+
+
+def strip_comments(text: str) -> str:
+ text = re.sub(r"/\*.*?\*/", " ", text, flags=re.S)
+ return re.sub(r"//[^\n]*", " ", text)
+
+
+def parse_init(text: str, start: int):
+ i = text.index("{", start)
+ tokens = re.findall(r"\{|\}|-?\d+|CTX_UNUSED|,", text[i:])
+ pos = 0
+
+ def parse():
+ nonlocal pos
+ assert tokens[pos] == "{"
+ pos += 1
+ items = []
+ while tokens[pos] != "}":
+ t = tokens[pos]
+ if t == ",":
+ pos += 1
+ continue
+ if t == "{":
+ items.append(parse())
+ elif t == "CTX_UNUSED":
+ items.append([0, 0])
+ pos += 1
+ else:
+ items.append(int(t))
+ pos += 1
+ pos += 1
+ return items
+
+ return parse()
+
+
+def shape_fill(v, shape):
+ if not shape:
+ return v if isinstance(v, int) else 0
+ out = []
+ v = v if isinstance(v, list) else []
+ for k in range(shape[0]):
+ out.append(shape_fill(v[k] if k < len(v) else 0, shape[1:]))
+ return out
+
+
+def flat(v):
+ if isinstance(v, int):
+ return [v]
+ out = []
+ for x in v:
+ out += flat(x)
+ return out
+
+
+def table(path: Path, decl: str, shape, after: str | None = None):
+ text = strip_comments(path.read_text(errors="replace"))
+ start = 0
+ if after:
+ start = text.index(after)
+ m = re.compile(re.escape(decl)).search(text, start)
+ if not m:
+ raise SystemExit(f"{decl} not found in {path}")
+ return flat(shape_fill(parse_init(text, m.end()), shape))
+
+
+def narrowest(values: list[int]) -> str:
+ lo, hi = min(values), max(values)
+ for elem, a, b in (("u8", 0, 255), ("i8", -128, 127), ("u16", 0, 65535), ("i16", -32768, 32767)):
+ if a <= lo and hi <= b:
+ return elem
+ return "i32"
+
+
+def emit(name: str, values: list[int], per_line: int = 32, elem: str | None = None) -> str:
+ elem = elem or narrowest(values)
+ lines = []
+ for i in range(0, len(values), per_line):
+ lines.append(" " + ", ".join(str(v) for v in values[i:i + per_line]) + ",")
+ return f"export const {name}: {elem}[] = [\n" + "\n".join(lines) + "\n]\n"
+
+
+def main() -> int:
+ vlc = JM / "app" / "lencod" / "vlc.c"
+ t = {}
+ t["CABAC_INIT_I"] = table(FF / "h264_cabac.c", "cabac_context_init_I[1024][2] =", [1024, 2])
+ t["CABAC_INIT_P"] = table(FF / "h264_cabac.c", "cabac_context_init_PB[3][1024][2] =", [3, 1024, 2])
+ bia = JM / "app" / "lencod" / "biariencode.c"
+ t["CABAC_RANGE_LPS"] = table(bia, "rLPS_table_64x4[64][4]=", [64, 4])
+ t["CABAC_NEXT_MPS"] = table(bia, "AC_next_state_MPS_64[64] =", [64])
+ t["CABAC_NEXT_LPS"] = table(bia, "AC_next_state_LPS_64[64] =", [64])
+ t["COEFF_TOKEN_LEN"] = table(vlc, "lentab[3][4][17] =", [3, 4, 17], "writeSyntaxElement_NumCoeffTrailingOnes(")
+ t["COEFF_TOKEN_CODE"] = table(vlc, "codtab[3][4][17] =", [3, 4, 17], "writeSyntaxElement_NumCoeffTrailingOnes(")
+ t["COEFF_TOKEN_DC_LEN"] = table(vlc, "lentab[3][4][17] =", [3, 4, 17],
+ "writeSyntaxElement_NumCoeffTrailingOnesChromaDC(")[:68]
+ t["COEFF_TOKEN_DC_CODE"] = table(vlc, "codtab[3][4][17] =", [3, 4, 17],
+ "writeSyntaxElement_NumCoeffTrailingOnesChromaDC(")[:68]
+ t["TOTAL_ZEROS_LEN"] = table(vlc, "lentab[TOTRUN_NUM][16] =", [15, 16], "writeSyntaxElement_TotalZeros(")
+ t["TOTAL_ZEROS_CODE"] = table(vlc, "codtab[TOTRUN_NUM][16] =", [15, 16], "writeSyntaxElement_TotalZeros(")
+ t["TOTAL_ZEROS_DC_LEN"] = table(vlc, "lentab[3][TOTRUN_NUM][16] =", [3, 15, 16],
+ "writeSyntaxElement_TotalZerosChromaDC(")[:240]
+ t["TOTAL_ZEROS_DC_CODE"] = table(vlc, "codtab[3][TOTRUN_NUM][16] =", [3, 15, 16],
+ "writeSyntaxElement_TotalZerosChromaDC(")[:240]
+ t["RUN_BEFORE_LEN"] = table(vlc, "lentab[TOTRUN_NUM][16] =", [15, 16], "writeSyntaxElement_Run(")
+ t["RUN_BEFORE_CODE"] = table(vlc, "codtab[TOTRUN_NUM][16] =", [15, 16], "writeSyntaxElement_Run(")
+ lf = JM / "app" / "lencod" / "loop_filter.h"
+ t["DEBLOCK_ALPHA"] = table(lf, "ALPHA_TABLE[52]", [52])
+ t["DEBLOCK_BETA"] = table(lf, "BETA_TABLE[52]", [52])
+ t["DEBLOCK_TC0"] = table(lf, "CLIP_TAB[52][5]", [52, 5])
+ t["CHROMA_QP"] = table(JM / "app" / "lencod" / "block.h", "QP_SCALE_CR[52]=", [52])
+ scan4 = table(JM / "app" / "lencod" / "block.c", "SNGL_SCAN[16][2] =", [16, 2])
+ t["ZIGZAG4"] = [scan4[2 * i] + 4 * scan4[2 * i + 1] for i in range(16)]
+ scan8 = table(JM / "app" / "lencod" / "transform8x8.c", "SNGL_SCAN8x8[64][2] =", [64, 2])
+ t["ZIGZAG8"] = [scan8[2 * i] + 8 * scan8[2 * i + 1] for i in range(64)]
+ qm = JM / "app" / "lencod" / "q_matrix.c"
+ t["SIG8_FRAME"] = table(FF / "h264_cabac.c", "significant_coeff_flag_offset_8x8[2][63] =", [2, 63])[:63]
+ cab = (FF / "cabac.c").read_text()
+ i = cab.index("// last_coeff_flag_offset_8x8")
+ t["LAST8"] = [int(x) for x in re.findall(r"\d+", cab[i + len("// last_coeff_flag_offset_8x8"):cab.index("}", i)])][:63]
+ ncbp = table(vlc, "NCBP[2][48][2]=", [2, 48, 2])
+ t["CBP_CODE_INTRA"] = [ncbp[96 + 2 * i] for i in range(48)]
+ t["CBP_CODE_INTER"] = [ncbp[96 + 2 * i + 1] for i in range(48)]
+ t["QUANT4"] = table(qm, "quant_coef[NUM_MATRIX_TYPES][4][4] =", [6, 4, 4])
+ t["DEQUANT4"] = table(qm, "dequant_coef[NUM_MATRIX_TYPES][4][4] =", [6, 4, 4])
+ t["QUANT8"] = table(qm, "quant_coef8[NUM_MATRIX_TYPES][8][8] =", [6, 8, 8])
+ t["DEQUANT8"] = table(qm, "dequant_coef8[NUM_MATRIX_TYPES][8][8] =", [6, 8, 8])
+
+ ctx = JM / "lib" / "lcommon" / "ctx_tables.h"
+ jm_mb_i = table(ctx, "INIT_MB_TYPE_I[1][3][11][2] =", [1, 3, 11, 2])
+ ff_i = t["CABAC_INIT_I"]
+ assert jm_mb_i[22:44] == ff_i[0:22], "SI/I mb_type contexts differ between JM and FFmpeg"
+ jm_mb_p = table(ctx, "INIT_MB_TYPE_P[3][3][11][2] =", [3, 3, 11, 2])
+ ff_p = t["CABAC_INIT_P"]
+ for idc in range(3):
+ row = jm_mb_p[idc * 66 + 22: idc * 66 + 44]
+ base = idc * 2048
+ assert row[0:6] == ff_p[base + 2 * 11: base + 2 * 14], f"P mb_skip_flag contexts idc {idc}"
+ assert row[8:22] == ff_p[base + 2 * 14: base + 2 * 21], f"P mb_type contexts idc {idc}"
+ assert t["ZIGZAG4"] == [0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15], t["ZIGZAG4"]
+ assert t["QUANT4"][:3] == [13107, 8066, 13107] and t["DEQUANT4"][:3] == [10, 13, 10]
+ assert t["CABAC_RANGE_LPS"][:4] == [128, 176, 208, 240]
+ assert t["CBP_CODE_INTRA"][47] == 0 and t["CBP_CODE_INTER"][0] == 0 and t["CBP_CODE_INTRA"][0] == 3
+ assert len(t["LAST8"]) == 63 and t["LAST8"][-1] == 8 and t["SIG8_FRAME"][-1] == 12
+ assert len(t["CABAC_INIT_I"]) == 2048 and len(t["CABAC_INIT_P"]) == 6144
+
+ transition = []
+ for s in range(128):
+ state, mps = s >> 1, s & 1
+ for b in range(2):
+ if b == mps:
+ transition.append(t["CABAC_NEXT_MPS"][state] * 2 + mps)
+ else:
+ transition.append(t["CABAC_NEXT_LPS"][state] * 2 + (1 - mps if state == 0 else mps))
+ t["CABAC_TRANSITION"] = transition
+ sig_base = [105, 120, 134, 149, 152, 402]
+ last_base = [166, 181, 195, 210, 213, 417]
+ sig_ctx, last_ctx = [], []
+ for cat in range(6):
+ for i in range(64):
+ if cat == 3:
+ si = li = min(i, 2)
+ elif cat == 5:
+ si = t["SIG8_FRAME"][i] if i < 63 else 0
+ li = t["LAST8"][i] if i < 63 else 0
+ else:
+ si = li = i
+ sig_ctx.append(sig_base[cat] + si)
+ last_ctx.append(last_base[cat] + li)
+ t["CABAC_SIG_CTX"] = sig_ctx
+ t["CABAC_LAST_CTX"] = last_ctx
+ t["CABAC_RENORM_SHIFT"] = [6] + [next(s for s in range(9) if ((i << 3) << s) >= 256) for i in range(1, 64)]
+ assert t["CABAC_RENORM_SHIFT"][:4] == [6, 5, 4, 4] and t["CABAC_RENORM_SHIFT"][31] == 1
+ assert t["CABAC_RENORM_SHIFT"][32] == 0 and t["CABAC_TRANSITION"][0:2] == [2, 1]
+
+ parts = ["// Generated by tools/gen_tables.py from the JM 19 reference software and FFmpeg's h264_cabac.c\n"
+ "// (H.264 Tables 8-14..8-17, 9-5, 9-7..9-10, 9-12..9-33, 9-44). Do not edit.\n"]
+ for name, vals in t.items():
+ parts.append(emit(name, vals, elem=ELEM.get(name)))
+ OUT.parent.mkdir(parents=True, exist_ok=True)
+ OUT.write_text("\n".join(parts))
+ print(f"wrote {OUT} ({sum(len(v) for v in t.values())} values)")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/capcodec/tools/profile.py b/capcodec/tools/profile.py
new file mode 100644
index 000000000..53bfe4264
--- /dev/null
+++ b/capcodec/tools/profile.py
@@ -0,0 +1,105 @@
+#!/usr/bin/env python3
+import argparse
+import json
+import os
+import resource
+import subprocess
+import sys
+import time
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "bench"))
+
+from harness.corpus import load_manifest, prepare_source # noqa: E402
+
+STAGES = ["analysis", "motion", "mode", "tq", "entropy", "deblock"]
+
+
+def child_cpu() -> float:
+ r = resource.getrusage(resource.RUSAGE_CHILDREN)
+ return r.ru_utime + r.ru_stime
+
+
+def run_capcodec(binary: str, src, preset: str, crf: float, extra: list[str], frames: int, side: bool) -> dict:
+ stats = Path(f"/tmp/profile_{src.clip.name}_{preset}.json")
+ cmd = [binary, "encode", "--input", str(src.path), "--output", "/tmp/profile_out.264",
+ "--width", str(src.width), "--height", str(src.height), "--fps", src.fps_arg,
+ "--preset", preset, "--crf", str(crf), "--stats", str(stats), "--frames", str(frames)] + extra
+ if side and src.sideinfo:
+ cmd += ["--sideinfo", str(src.sideinfo)]
+ c0 = child_cpu()
+ t0 = time.perf_counter()
+ r = subprocess.run(cmd, capture_output=True)
+ wall = time.perf_counter() - t0
+ cpu = child_cpu() - c0
+ if r.returncode != 0:
+ raise RuntimeError(r.stderr.decode(errors="replace"))
+ s = json.loads(stats.read_text())
+ s["wall_s"] = wall
+ s["cpu_s"] = cpu
+ return s
+
+
+def run_x264(src, preset: str, crf: float, threads: int, frames: int) -> dict:
+ ffmpeg = os.environ.get("FFMPEG", "ffmpeg")
+ cmd = [ffmpeg, "-hide_banner", "-loglevel", "error", "-y", "-f", "rawvideo", "-pix_fmt", "yuv420p",
+ "-s", f"{src.width}x{src.height}", "-r", src.fps_arg, "-i", str(src.path), "-frames:v", str(frames),
+ "-c:v", "libx264", "-preset", preset, "-crf", str(crf), "-threads", str(threads), "-f", "h264",
+ "/tmp/profile_x264.264"]
+ c0 = child_cpu()
+ t0 = time.perf_counter()
+ r = subprocess.run(cmd, capture_output=True)
+ wall = time.perf_counter() - t0
+ cpu = child_cpu() - c0
+ if r.returncode != 0:
+ raise RuntimeError(r.stderr.decode(errors="replace"))
+ return {"wall_s": wall, "cpu_s": cpu, "bytes": Path("/tmp/profile_x264.264").stat().st_size}
+
+
+def report(name: str, s: dict, frames: int) -> None:
+ fr = s["frames"]
+ full = [f for f in fr if f["changed_mbs"] >= 0.9 * s["mbs"] and f["type"] == "P"]
+ t = s["time_ms"]
+ line = (f"{name:<28} wall {frames / s['wall_s']:7.1f} fps cpu {frames / s['cpu_s']:7.1f} fps "
+ f"{s['bytes'] / 1024:8.0f} KB coded {s['frames_coded']}/{s['frames_in']}")
+ print(line)
+ per = " ".join(f"{k} {t[k] / max(1, len(fr)):6.2f}" for k in STAGES)
+ print(f"{'':<28} ms/coded frame: {per}")
+ if full:
+ avg = {k: sum(f["ms"][k] for f in full) / len(full) for k in STAGES + ["total"]}
+ print(f"{'':<28} full-change P ({len(full)}): " + " ".join(f"{k} {avg[k]:6.2f}" for k in STAGES + ["total"]))
+
+
+def main() -> None:
+ ap = argparse.ArgumentParser()
+ ap.add_argument("clips", nargs="+")
+ ap.add_argument("--height", type=int, default=1080)
+ ap.add_argument("--seconds", type=float, default=10.0)
+ ap.add_argument("--presets", default="live,fast,medium")
+ ap.add_argument("--crf", type=float, default=26.0)
+ ap.add_argument("--x264", default="veryfast")
+ ap.add_argument("--x264-crf", type=float, default=23.0)
+ ap.add_argument("--binary", default=str(ROOT / "build" / "capcodec-unchecked"))
+ ap.add_argument("--extra", default="")
+ ap.add_argument("--no-sideinfo", action="store_true")
+ args = ap.parse_args()
+ clips = {c.name: c for c in load_manifest()}
+ for name in args.clips:
+ src = prepare_source(clips[name], args.height, args.seconds)
+ frames = src.frames
+ print(f"== {name} {src.width}x{src.height} {frames} frames")
+ for p in args.presets.split(","):
+ s = run_capcodec(args.binary, src, p, args.crf, args.extra.split() if args.extra else [], frames,
+ not args.no_sideinfo)
+ report(f"capcodec-{p}", s, frames)
+ if args.x264:
+ for threads in (1, 0):
+ x = run_x264(src, args.x264, args.x264_crf, threads, frames)
+ label = f"x264-{args.x264} t{threads or 'auto'}"
+ print(f"{label:<28} wall {frames / x['wall_s']:7.1f} fps cpu {frames / x['cpu_s']:7.1f} fps "
+ f"{x['bytes'] / 1024:8.0f} KB")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/capcodec/tools/verify.py b/capcodec/tools/verify.py
new file mode 100644
index 000000000..a6e9db5a4
--- /dev/null
+++ b/capcodec/tools/verify.py
@@ -0,0 +1,72 @@
+#!/usr/bin/env python3
+import argparse
+import hashlib
+import os
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+ROOT = Path(__file__).resolve().parent.parent
+sys.path.insert(0, str(ROOT / "bench"))
+
+from harness.corpus import load_manifest, prepare_source # noqa: E402
+
+FFMPEG = os.environ.get("FFMPEG", "ffmpeg")
+LDECOD = os.environ.get("LDECOD", "ldecod")
+
+
+def md5_frames(path: Path, frame_bytes: int) -> list[str]:
+ out = []
+ with open(path, "rb") as f:
+ while True:
+ b = f.read(frame_bytes)
+ if len(b) < frame_bytes:
+ break
+ out.append(hashlib.md5(b).hexdigest())
+ return out
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description="encode a corpus clip and check ffmpeg and JM decodes against the recon")
+ ap.add_argument("clip")
+ ap.add_argument("--height", type=int, default=1080)
+ ap.add_argument("--seconds", type=float, default=10.0)
+ ap.add_argument("--binary", default=str(ROOT / "build" / "capcodec"))
+ ap.add_argument("--no-sideinfo", action="store_true")
+ a, extra = ap.parse_known_args()
+ clips = {c.name: c for c in load_manifest()}
+ src = prepare_source(clips[a.clip], a.height, a.seconds)
+ fb = src.width * src.height * 3 // 2
+ with tempfile.TemporaryDirectory() as td:
+ t = Path(td)
+ cmd = [a.binary, "encode", "--input", str(src.path), "--output", str(t / "o.264"), "--recon", str(t / "rec.yuv"),
+ "--width", str(src.width), "--height", str(src.height), "--fps", src.fps_arg] + extra
+ if src.sideinfo and not a.no_sideinfo:
+ cmd += ["--sideinfo", str(src.sideinfo)]
+ r = subprocess.run(cmd, capture_output=True)
+ if r.returncode != 0:
+ print(r.stderr.decode(errors="replace"))
+ return 1
+ print(r.stderr.decode().strip())
+ rec = md5_frames(t / "rec.yuv", fb)
+ subprocess.run([FFMPEG, "-hide_banner", "-loglevel", "error", "-y", "-i", str(t / "o.264"), "-f", "rawvideo",
+ "-pix_fmt", "yuv420p", str(t / "ff.yuv")], check=True)
+ ff = md5_frames(t / "ff.yuv", fb)
+ jr = subprocess.run([LDECOD, "-p", f"InputFile={t / 'o.264'}", "-p", f"OutputFile={t / 'jm.yuv'}",
+ "-p", "WriteUV=1"], capture_output=True, cwd=td)
+ text = (jr.stdout + jr.stderr).decode(errors="replace")
+ bad = [ln for ln in text.splitlines() if "error" in ln.lower() or "warning" in ln.lower()]
+ jm = md5_frames(t / "jm.yuv", fb) if (t / "jm.yuv").exists() else []
+ ok_ff = ff == rec and len(rec) > 0
+ ok_jm = jm == rec and not bad
+ first_ff = next((i for i, (x, y) in enumerate(zip(ff, rec)) if x != y), None)
+ first_jm = next((i for i, (x, y) in enumerate(zip(jm, rec)) if x != y), None)
+ stream_md5 = hashlib.md5((t / "o.264").read_bytes()).hexdigest()
+ print(f"frames recon {len(rec)} ffmpeg {len(ff)} jm {len(jm)}; ffmpeg match {ok_ff} (first diff {first_ff}); "
+ f"jm match {ok_jm} (first diff {first_jm}) {bad[:3]}; stream md5 {stream_md5}")
+ return 0 if ok_ff and ok_jm else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())