Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: keep bench checks honest and format the capcodec scripts

Richie McIlroy204db3105834
diff --git a/apps/media-server/capcodec-benchmarks.md b/apps/media-server/capcodec-benchmarks.md
index 1fb29651a..e6ae9ecc6 100644
--- a/apps/media-server/capcodec-benchmarks.md
+++ b/apps/media-server/capcodec-benchmarks.md
@@ -22,7 +22,7 @@ Quality measured 2026-10-09 on main `fff504d`. Speed remeasured the same day on
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`.
+- Speed: `bench/lane.sh start`, then `bench/lane.sh run "python3 bench/speedcmp.py --binary <binary> --clips all --modes medium,live,zerolatency --out <dir>"`. A fresh run matches each clip to x264 CRF 23 by VMAF, then times 5 shuffled rounds at 1 and 4 threads with other processes stopped. code_4k runs at native 4K for 5 s. The published table reused an earlier CRF match; that results file is not in the repository.
- 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)
diff --git a/biome.json b/biome.json
index 997ea30a3..189cd4a74 100644
--- a/biome.json
+++ b/biome.json
@@ -14,7 +14,13 @@
"!apps/desktop/src/global.d.ts",
"!apps/web/public/gif.worker.js",
"!packages/ui-solid/src/auto-imports.d.ts",
- "!capcodec"
+ "!capcodec/**/*.tov",
+ "!capcodec/**/*.py",
+ "!capcodec/**/*.md",
+ "!capcodec/**/*.sh",
+ "!capcodec/**/*.jsonl",
+ "!capcodec/**/*.pyc",
+ "!capcodec/capcodec.bundle"
],
"ignoreUnknown": false
},
diff --git a/capcodec/SCOREBOARD.md b/capcodec/SCOREBOARD.md
index 68e14f770..3c5f1a640 100644
--- a/capcodec/SCOREBOARD.md
+++ b/capcodec/SCOREBOARD.md
@@ -5,7 +5,7 @@ Quality measured 2026-10-09 on main `fff504d`. Speed remeasured the same day on
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`.
+- Speed: `bench/lane.sh start`, then `bench/lane.sh run "python3 bench/speedcmp.py --binary <binary> --clips all --modes medium,live,zerolatency --out <dir>"`. A fresh run matches each clip to x264 CRF 23 by VMAF, then times 5 shuffled rounds at 1 and 4 threads with other processes stopped. code_4k runs at native 4K for 5 s. The published table reused an earlier CRF match; that results file is not in the repository.
- 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)
diff --git a/capcodec/bench/best.json b/capcodec/bench/best.json
index 1e9504012..75f9d0290 100644
--- a/capcodec/bench/best.json
+++ b/capcodec/bench/best.json
@@ -1,11 +1,7 @@
{
- "bd_psnr_yuv": 1.5927990279928197,
- "clips": [
- "code_editor",
- "text_scroll",
- "slides"
- ],
- "commit": "1c82bfaeb12e-dirty",
- "cpu_fps": 291.64864116037273,
- "tier": "smoke"
+ "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/corpus/generate.py b/capcodec/bench/corpus/generate.py
index b3b22f3e6..bd1811148 100644
--- a/capcodec/bench/corpus/generate.py
+++ b/capcodec/bench/corpus/generate.py
@@ -1,17 +1,4 @@
#!/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
@@ -1431,7 +1418,7 @@ def outputs_exist(clip):
def main():
- ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap = argparse.ArgumentParser(description="Generate the screen-recording benchmark corpus.")
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")
diff --git a/capcodec/bench/corpus/manifest.json b/capcodec/bench/corpus/manifest.json
index 4d70898d4..60b649803 100644
--- a/capcodec/bench/corpus/manifest.json
+++ b/capcodec/bench/corpus/manifest.json
@@ -1,1464 +1,1148 @@
{
- "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"
- }
+ "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-5,
+ "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/common/board.css b/capcodec/bench/corpus/pages/common/board.css
index c1e1d3419..058232bd9 100644
--- a/capcodec/bench/corpus/pages/common/board.css
+++ b/capcodec/bench/corpus/pages/common/board.css
@@ -368,7 +368,9 @@ svg.i {
margin-bottom: 8px;
box-shadow: 0 1px 1px #0000000a;
position: relative;
- transition: box-shadow 0.12s ease, border-color 0.12s ease;
+ transition:
+ box-shadow 0.12s ease,
+ border-color 0.12s ease;
}
.card:hover {
border-color: #cbcdd3;
@@ -485,7 +487,9 @@ svg.i {
pointer-events: none;
z-index: 100;
transform: rotate(2.5deg);
- box-shadow: 0 16px 40px #0000002e, 0 2px 6px #0000001f !important;
+ box-shadow:
+ 0 16px 40px #0000002e,
+ 0 2px 6px #0000001f !important;
border-color: #b9bbff !important;
margin: 0;
}
@@ -605,7 +609,9 @@ svg.i {
background: #fff;
border: 1px solid #e3e4e8;
border-radius: 10px;
- box-shadow: 0 12px 32px #0000001f, 0 2px 6px #00000012;
+ box-shadow:
+ 0 12px 32px #0000001f,
+ 0 2px 6px #00000012;
padding: 5px;
z-index: 150;
}
diff --git a/capcodec/bench/corpus/pages/common/board.js b/capcodec/bench/corpus/pages/common/board.js
index 02c3f3fd5..edc16d569 100644
--- a/capcodec/bench/corpus/pages/common/board.js
+++ b/capcodec/bench/corpus/pages/common/board.js
@@ -1,58 +1,70 @@
(() => {
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\"/>",
+ 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>",
+ 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>`;
+ 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>";
+ 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"];
@@ -136,7 +148,9 @@
}
function updateCounts() {
- for (const col of board.querySelectorAll(".col")) col.querySelector(".cnt").textContent = col.querySelectorAll(".list .card").length;
+ for (const col of board.querySelectorAll(".col"))
+ col.querySelector(".cnt").textContent =
+ col.querySelectorAll(".list .card").length;
}
const tooltip = document.getElementById("tooltip");
@@ -227,16 +241,19 @@
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;
+ 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(".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");
+ for (const n of document.querySelectorAll(".ni.active"))
+ n.classList.remove("active");
k.classList.add("active");
setTimeout(() => {
k.classList.remove("active");
@@ -247,14 +264,26 @@
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 };
+ 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) {
+ 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");
@@ -273,7 +302,8 @@
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");
+ 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")];
@@ -286,7 +316,8 @@
}
}
if (before) {
- if (dragging.ph.nextSibling !== before) list.insertBefore(dragging.ph, before);
+ if (dragging.ph.nextSibling !== before)
+ list.insertBefore(dragging.ph, before);
} else if (list.lastElementChild !== dragging.ph) {
list.append(dragging.ph);
}
@@ -296,14 +327,18 @@
const { card, ghost, ph } = dragging;
ph.replaceWith(card);
ghost.remove();
- for (const l of document.querySelectorAll(".list.over")) l.classList.remove("over");
+ 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>`);
+ 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;
@@ -323,7 +358,12 @@
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)];
+ 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;
@@ -332,14 +372,21 @@
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 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.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")];
diff --git a/capcodec/bench/corpus/pages/common/cap.js b/capcodec/bench/corpus/pages/common/cap.js
index abd36e9fa..5bf4b2f32 100644
--- a/capcodec/bench/corpus/pages/common/cap.js
+++ b/capcodec/bench/corpus/pages/common/cap.js
@@ -23,12 +23,20 @@
return [0, 0, de.clientWidth, de.clientHeight];
}
const r = el.getBoundingClientRect();
- return [r.left + el.clientLeft, r.top + el.clientTop, el.clientWidth, el.clientHeight];
+ 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 });
+ tracked.set(el, {
+ id: name || el.dataset.scrollId || `s${nextId++}`,
+ last: null,
+ });
}
function sample(src) {
@@ -64,16 +72,43 @@
for (const el of document.querySelectorAll("[data-scroll-id]")) track(el);
}
- document.addEventListener("scroll", () => sample("scroll"), { capture: true, passive: true });
+ 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 });
+ 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(
+ 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 }),
+ (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 },
);
@@ -84,9 +119,11 @@
sample("ready");
event("ready", { w: innerWidth, h: innerHeight, dpr: devicePixelRatio });
document.fonts.ready.then(() => {
- requestAnimationFrame(() => requestAnimationFrame(() => {
- window.capReady = true;
- }));
+ requestAnimationFrame(() =>
+ requestAnimationFrame(() => {
+ window.capReady = true;
+ }),
+ );
});
};
requestAnimationFrame(onFrame);
diff --git a/capcodec/bench/corpus/pages/common/dashboard.js b/capcodec/bench/corpus/pages/common/dashboard.js
index cf8c84a43..3d966a552 100644
--- a/capcodec/bench/corpus/pages/common/dashboard.js
+++ b/capcodec/bench/corpus/pages/common/dashboard.js
@@ -9,8 +9,16 @@
};
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 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;
@@ -38,19 +46,25 @@
}
function drawSpark(c, data, color, fill) {
- if (!c._ctx) Object.assign(c, (({ ctx, w, h }) => ({ _ctx: ctx, _w: w, _h: h }))(sizeCanvas(c)));
+ 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);
+ const 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))));
+ 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);
@@ -63,7 +77,9 @@
ctx.fill();
ctx.restore();
ctx.beginPath();
- data.forEach((v, i) => (i ? ctx.lineTo(xs(i), ys(v)) : ctx.moveTo(xs(i), ys(v))));
+ data.forEach((v, i) =>
+ i ? ctx.lineTo(xs(i), ys(v)) : ctx.moveTo(xs(i), ys(v)),
+ );
}
ctx.strokeStyle = color;
ctx.lineWidth = 1.5;
@@ -83,12 +99,66 @@
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 },
+ {
+ 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");
@@ -101,7 +171,14 @@
hist.unshift(v);
}
hist[hist.length - 1] = d.v;
- return { d, p, val: p.querySelector(".val"), canvas: p.querySelector("canvas"), hist, v: d.v };
+ return {
+ d,
+ p,
+ val: p.querySelector(".val"),
+ canvas: p.querySelector("canvas"),
+ hist,
+ v: d.v,
+ };
});
function renderKpi(k) {
@@ -137,7 +214,12 @@
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.hover = {
+ x: e.clientX - r.left,
+ y: e.clientY - r.top,
+ cx: e.clientX,
+ cy: e.clientY,
+ };
this.dirty = true;
});
this.canvas.addEventListener("mouseleave", () => {
@@ -149,7 +231,8 @@
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);
+ 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;
}
@@ -161,7 +244,12 @@
});
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.anim = {
+ t0: performance.now(),
+ dur: 420,
+ from: this.yMax,
+ to: this.targetMax(),
+ };
this.dirty = true;
}
@@ -180,7 +268,7 @@
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.font = '11px "Noto Sans", "Liberation Sans", sans-serif';
ctx.textBaseline = "middle";
const yTicks = 5;
for (let i = 0; i <= yTicks; i++) {
@@ -206,7 +294,9 @@
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))));
+ 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);
@@ -219,7 +309,9 @@
ctx.fill();
ctx.restore();
ctx.beginPath();
- s.data.forEach((v, i) => (i ? ctx.lineTo(xOf(i), yOf(v)) : ctx.moveTo(xOf(i), yOf(v))));
+ 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;
@@ -243,7 +335,13 @@
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) {
+ 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++) {
@@ -276,7 +374,10 @@
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;
+ 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`;
}
@@ -307,7 +408,11 @@
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)];
+ return [
+ ok,
+ ok * rand(0.035, 0.06),
+ ok * rand(0.002, 0.009) * (rng() < 0.05 ? 4 : 1),
+ ];
};
let latBase = 62;
const latGen = () => {
@@ -315,20 +420,31 @@
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 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 = [
@@ -377,12 +493,15 @@
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));
+ 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.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;
@@ -410,7 +529,8 @@
}
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";
+ r.barI.style.background =
+ r.apdex > 0.85 ? "#22c55e" : r.apdex > 0.7 ? "#f59e0b" : "#ef4444";
drawSpark(r.canvas, r.hist, "#6366f1", false);
}
@@ -425,7 +545,11 @@
["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>`);
+ 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") };
});
@@ -444,24 +568,78 @@
}
}
- 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 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`],
+ [
+ "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)`],
+ [
+ "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>`);
+ 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 });
@@ -497,7 +675,11 @@
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 === 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();
@@ -514,9 +696,13 @@
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));
+ 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.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);
@@ -524,7 +710,8 @@
});
if (tickNo % 2 === 0) {
later(500, () => {
- for (const e of errTypes) e.c += Math.floor(rand(0, 6) * (rng() < 0.15 ? 4 : 1));
+ for (const e of errTypes)
+ e.c += Math.floor(rand(0, 6) * (rng() < 0.15 ? 4 : 1));
renderErrs();
});
}
diff --git a/capcodec/bench/corpus/pages/common/editor.js b/capcodec/bench/corpus/pages/common/editor.js
index b0b33d547..54e76f0ad 100644
--- a/capcodec/bench/corpus/pages/common/editor.js
+++ b/capcodec/bench/corpus/pages/common/editor.js
@@ -1,21 +1,35 @@
(() => {
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(" "),
+ "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(" "),
+ "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(" "),
+ "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_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(" "),
+ "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(" "),
+ "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) {
@@ -140,7 +154,9 @@
continue;
}
}
- const sm = (lang === "py" ? /^[rRbBuUfF]{0,2}("|")/ : /^(\"|")/).exec(rest);
+ const sm = (lang === "py" ? /^[rRbBuUfF]{0,2}("|")/ : /^("|")/).exec(
+ rest,
+ );
if (sm) {
const q = sm[1];
let j = i + sm[0].length;
@@ -152,7 +168,10 @@
i = Math.min(len, j + 1);
continue;
}
- const nm = /^(0[xX][0-9a-fA-F]+[uUlL]*|\d+(\.\d+)?([eE][+-]?\d+)?[uUlLj]*)/.exec(rest);
+ 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;
@@ -183,7 +202,8 @@
return { tokens: out, state: {} };
}
- const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+ const esc = (s) =>
+ s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
class CodeEditor {
constructor(host, opts) {
@@ -227,7 +247,13 @@
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.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";
@@ -264,8 +290,10 @@
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);
+ 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) {
@@ -290,7 +318,7 @@
let guides = "";
let k = 0;
while (k + 4 <= take) {
- guides += "<span class=\"ig\"> </span>";
+ guides += '<span class="ig"> </span>';
k += 4;
}
if (k < take) guides += " ".repeat(take - k);
@@ -299,10 +327,15 @@
col += take;
if (!t) continue;
}
- html += cls === "plain" ? esc(t) : `<span class="tk-${cls}">${esc(t)}</span>`;
+ 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" : "";
+ 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>`;
}
@@ -333,7 +366,7 @@
insertRow(at) {
const d = document.createElement("div");
d.className = "ce-row";
- d.innerHTML = "<span class=\"ln\"></span><span class=\"code\"> </span>";
+ 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);
@@ -354,7 +387,8 @@
}
renumber(from) {
- for (let i = from; i < this.rowEls.length; i++) this.rowEls[i].firstChild.textContent = i + 1;
+ for (let i = from; i < this.rowEls.length; i++)
+ this.rowEls[i].firstChild.textContent = i + 1;
}
shiftSets(at, delta) {
@@ -384,8 +418,20 @@
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)));
+ 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();
@@ -414,7 +460,10 @@
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)];
+ return [
+ Math.round(r.left + this.gutter + c * this.cw),
+ Math.round(r.top + l * this.lineHeight + this.lineHeight / 2),
+ ];
}
scrollTo(y) {
@@ -457,9 +506,18 @@
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(/^ +/, ""));
+ 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);
@@ -474,7 +532,7 @@
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)) {
+ 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);
@@ -506,17 +564,22 @@
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 };
+ 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 };
+ 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.caret = {
+ line: l,
+ col: Math.min(this.lines[l].length, this.goalCol),
+ };
this.hideSuggest();
this.updateCaret(true, true);
this.renderRows(this.dirtyRows);
@@ -549,17 +612,32 @@
const text = this.lines[line];
const next = text[col] || "";
const closers = { "(": ")", "[": "]" };
- if ((ch === ")" || ch === "]" || ch === "\"" || ch === "'") && next === ch) {
+ 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;
+ 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) {
+ if (
+ this.lang === "c" &&
+ ch === "}" &&
+ /^ +$/.test(text.slice(0, col)) &&
+ col >= 4
+ ) {
newText = text.slice(0, col - 4) + "}" + text.slice(col);
newCol = col - 3;
}
@@ -582,16 +660,24 @@
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]);
+ 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);
+ 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];
+ 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("");
@@ -634,9 +720,13 @@
this.caretEl.classList.remove("blink");
void this.caretEl.offsetWidth;
clearTimeout(this.blinkTimer);
- this.blinkTimer = setTimeout(() => this.caretEl.classList.add("blink"), 550);
+ 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 (this.curLnEl && this.curLnEl !== ln)
+ this.curLnEl.classList.remove("cur");
if (ln) ln.classList.add("cur");
this.curLnEl = ln;
if (reveal) {
@@ -675,7 +765,12 @@
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);
+ ctx.fillRect(
+ x + start * 1,
+ y,
+ seg.length * 1,
+ this.miniLineH - 0.5,
+ );
}
start += seg.length;
}
@@ -685,7 +780,10 @@
renderMinimapRows(rows) {
if (!rows || !rows.size || !this.miniCtx) return;
- if (this.lines.length * this.miniLineH + 200 > this.mini.height / (window.devicePixelRatio || 1)) {
+ if (
+ this.lines.length * this.miniLineH + 200 >
+ this.mini.height / (window.devicePixelRatio || 1)
+ ) {
this.renderMinimapFull();
} else {
const first = Math.min(...rows);
@@ -709,12 +807,28 @@
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;
+ 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.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));
+ ctx.fillRect(
+ 0,
+ Math.round((firstLine * this.miniLineH - miniTop) * dpr),
+ this.minimap.width,
+ Math.round(visLines * this.miniLineH * dpr),
+ );
}
}
diff --git a/capcodec/bench/corpus/pages/common/slides.css b/capcodec/bench/corpus/pages/common/slides.css
index bbdf6df2d..f1b03a505 100644
--- a/capcodec/bench/corpus/pages/common/slides.css
+++ b/capcodec/bench/corpus/pages/common/slides.css
@@ -105,7 +105,10 @@ body {
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);
+ 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;
}
@@ -358,7 +361,9 @@ table.rm td {
}
.build.on {
opacity: 1;
- transition: opacity 0.35s ease, transform 0.35s ease;
+ transition:
+ opacity 0.35s ease,
+ transform 0.35s ease;
transform: none;
}
.photo-cap {
@@ -389,7 +394,9 @@ table.rm td {
height: 320px;
border-radius: 50%;
overflow: hidden;
- box-shadow: 0 10px 40px #0000004d, 0 0 0 4px #ffffff;
+ box-shadow:
+ 0 10px 40px #0000004d,
+ 0 0 0 4px #ffffff;
z-index: 50;
cursor: grab;
left: 72px;
@@ -400,7 +407,9 @@ table.rm td {
}
#webcam.drag {
cursor: grabbing;
- box-shadow: 0 18px 60px #00000066, 0 0 0 4px #ffffff;
+ box-shadow:
+ 0 18px 60px #00000066,
+ 0 0 0 4px #ffffff;
}
#cam {
width: 320px;
diff --git a/capcodec/bench/corpus/pages/common/slides.js b/capcodec/bench/corpus/pages/common/slides.js
index b5d660f96..3626d0410 100644
--- a/capcodec/bench/corpus/pages/common/slides.js
+++ b/capcodec/bench/corpus/pages/common/slides.js
@@ -1,7 +1,8 @@
(() => {
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>`;
+ 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 = [
@@ -58,12 +59,16 @@
}
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(" ");
+ 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>`;
+ 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>`;
@@ -81,7 +86,7 @@
["720p and below", 10, "#f59e0b"],
];
let a0 = -Math.PI / 2;
- let s = "<svg width=\"620\" height=\"620\" viewBox=\"-310 -310 620 620\">";
+ 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;
@@ -90,9 +95,13 @@
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>";
+ 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>`)
+ .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>`;
}
@@ -107,7 +116,10 @@
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;
+ 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";
@@ -145,7 +157,10 @@ ${[
["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>`)
+ .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>`,
},
{
@@ -206,7 +221,10 @@ ${[
["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>`)
+ .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>`,
},
{
@@ -255,7 +273,11 @@ ${[
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 opts = {
+ duration: tr === "fade" ? 600 : 650,
+ easing: "cubic-bezier(.2,.7,.2,1)",
+ fill: "both",
+ };
const done = () => {
from.classList.remove("show");
from.style.zIndex = "";
@@ -273,14 +295,26 @@ ${[
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));
+ 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);
+ 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();
+ for (const x of [from, to])
+ for (const an of x.getAnimations()) an.cancel();
done();
});
}
diff --git a/capcodec/bench/corpus/pages/common/terminal.js b/capcodec/bench/corpus/pages/common/terminal.js
index e2f60c2e4..dc90f07dc 100644
--- a/capcodec/bench/corpus/pages/common/terminal.js
+++ b/capcodec/bench/corpus/pages/common/terminal.js
@@ -11,7 +11,8 @@
}
window.mulberry32 = mulberry32;
- const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
+ const esc = (s) =>
+ s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
class Terminal {
constructor(host, opts) {
@@ -53,7 +54,8 @@
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);
+ 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();
diff --git a/capcodec/bench/corpus/pages/common/video.js b/capcodec/bench/corpus/pages/common/video.js
index 508547c13..865559959 100644
--- a/capcodec/bench/corpus/pages/common/video.js
+++ b/capcodec/bench/corpus/pages/common/video.js
@@ -29,10 +29,15 @@
}
video.addEventListener("error", () => {
- cap.event("video_error", { code: video.error?.code, message: video.error?.message });
+ 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 }));
+ video.addEventListener(type, () =>
+ cap.event(`video_${type}`, { current_time: video.currentTime }),
+ );
}
window.capStats = () => {
@@ -54,12 +59,16 @@
recent.length = 0;
window.capReady = false;
video.currentTime = 0;
- video.play().catch((e) => cap.event("video_play_error", { message: String(e) }));
+ video
+ .play()
+ .catch((e) => cap.event("video_play_error", { message: String(e) }));
};
window.capTextRegions = () => [];
video.requestVideoFrameCallback(onFrame);
const src = window.capVideoSrc;
if (typeof src === "string") video.src = src;
- video.play().catch((e) => cap.event("video_play_error", { message: String(e) }));
+ 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
index b5b96775e..741d5ac07 100644
--- a/capcodec/bench/corpus/pages/common/webcam.js
+++ b/capcodec/bench/corpus/pages/common/webcam.js
@@ -35,13 +35,27 @@
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 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)}%)`);
+ 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);
+ 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;
@@ -58,7 +72,14 @@
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);
+ 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;
@@ -126,11 +147,19 @@
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;
+ 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.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)";
@@ -147,7 +176,10 @@
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));
+ 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);
diff --git a/capcodec/bench/corpus/pages/common/wiki.css b/capcodec/bench/corpus/pages/common/wiki.css
index c3e0d1c95..d5f322750 100644
--- a/capcodec/bench/corpus/pages/common/wiki.css
+++ b/capcodec/bench/corpus/pages/common/wiki.css
@@ -452,7 +452,9 @@ ul.fr {
display: none;
width: 450px;
background: #fff;
- box-shadow: 0 30px 90px -20px #00000052, 0 0 1px #a2a9b1;
+ box-shadow:
+ 0 30px 90px -20px #00000052,
+ 0 0 1px #a2a9b1;
border-radius: 2px;
z-index: 10;
font-size: 14px;
diff --git a/capcodec/bench/corpus/pages/common/wiki.js b/capcodec/bench/corpus/pages/common/wiki.js
index cdf6d2e01..5db9a55cc 100644
--- a/capcodec/bench/corpus/pages/common/wiki.js
+++ b/capcodec/bench/corpus/pages/common/wiki.js
@@ -86,10 +86,19 @@ ${Array.from({ length: 5 }, (_, r) => {
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\"/>";
+ 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>`;
@@ -98,13 +107,18 @@ ${Array.from({ length: 5 }, (_, r) => {
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>`;
+ 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>";
+ 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;
})(),
},
@@ -131,7 +145,10 @@ ${[
["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>`)
+ .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: {
@@ -140,7 +157,7 @@ ${[
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\"/>";
+ let s = '<rect width="330" height="128" fill="#f4f4f4"/>';
rows.forEach((r, ri) => {
[...r].forEach((ch, ci) => {
const x = 10 + ri * 9 + ci * 27;
@@ -148,7 +165,8 @@ ${[
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\"/>";
+ s +=
+ '<rect x="80" y="116" width="170" height="10" rx="3" fill="#fff" stroke="#888"/>';
return s;
})(),
},
@@ -158,17 +176,65 @@ ${[
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"],
+ [
+ "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"],
+ [
+ "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"],
+ [
+ "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"],
+ [
+ "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>`)
@@ -177,12 +243,27 @@ ${[
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"],
+ [
+ "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"],
+ [
+ "JCUKEN",
+ "Russia and other Cyrillic users",
+ "Й Ц У К Е Н Г Ш Щ З",
+ "c. 1900",
+ ],
]
.map((r) => `<tr>${r.map((c) => `<td>${c}</td>`).join("")}</tr>`)
.join("")}
@@ -191,29 +272,72 @@ ${[
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",
+ "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 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>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"],
+ [
+ '"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>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>"],
+ ['"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>"],
+ ['"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++) {
@@ -221,9 +345,17 @@ ${[
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>`);
+ 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>`;
}
@@ -233,19 +365,53 @@ ${[
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"]],
+ [
+ "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>`)
+ .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>`;
+ 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");
@@ -253,9 +419,9 @@ ${[
let h2n = 0;
let h3n = 0;
let html = "";
- const tocItems = ["<li class=\"top\">(Top)</li>"];
+ const tocItems = ['<li class="top">(Top)</li>'];
for (const sec of window.ARTICLE) {
- let body = sec.html
+ const body = sec.html
.replace(/\{fig:(\w+)\}/g, (_, k) => figure(k))
.replace(/\{table:(\w+)\}/g, (_, k) => TABLES[k])
.replace("{refs}", refs())
@@ -272,7 +438,9 @@ ${[
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>`);
+ 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}`;
}
}
@@ -296,9 +464,12 @@ ${[
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.",
+ "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");
diff --git a/capcodec/bench/corpus/pages/common/workbench.js b/capcodec/bench/corpus/pages/common/workbench.js
index 1a5d9d95a..c04148662 100644
--- a/capcodec/bench/corpus/pages/common/workbench.js
+++ b/capcodec/bench/corpus/pages/common/workbench.js
@@ -1,35 +1,45 @@
(() => {
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\"/>",
+ 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>`;
+ const icon = (name, extra) =>
+ `<svg class="ic ${extra || ""}" viewBox="0 0 24 24">${ICONS[name] || ""}</svg>`;
window.wbIcon = icon;
const FILE_BADGES = {
@@ -58,14 +68,19 @@
}
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(" ");
+ 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");
+ document.body.classList.add(
+ cfg.theme === "dark" ? "theme-dark" : "theme-light",
+ );
const tabs = cfg.tabs
.map((t) => {
const ext = t.name.split(".").pop();
@@ -73,7 +88,12 @@
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("");
+ 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">
@@ -105,7 +125,7 @@
<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>" : ""}
+ ${cfg.panel ? '<div id="panel"></div>' : ""}
</div>
</div>
<div id="statusbar">
diff --git a/capcodec/bench/corpus/pages/data/article_text.js b/capcodec/bench/corpus/pages/data/article_text.js
index 2dfb91960..6d6d1bddc 100644
--- a/capcodec/bench/corpus/pages/data/article_text.js
+++ b/capcodec/bench/corpus/pages/data/article_text.js
@@ -116,5 +116,9 @@ window.ARTICLE = [
<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}` },
+ {
+ 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
index f7f54bd35..dd6f2a87d 100644
--- a/capcodec/bench/corpus/pages/data/board_data.js
+++ b/capcodec/bench/corpus/pages/data/board_data.js
@@ -26,16 +26,106 @@ window.BOARD = {
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],
+ [
+ "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,
+ ],
],
},
{
@@ -43,12 +133,66 @@ window.BOARD = {
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],
+ [
+ "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,
+ ],
],
},
{
@@ -56,11 +200,56 @@ window.BOARD = {
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],
+ [
+ "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,
+ ],
],
},
{
@@ -68,9 +257,36 @@ window.BOARD = {
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],
+ [
+ "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,
+ ],
],
},
{
@@ -78,10 +294,46 @@ window.BOARD = {
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-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],
],
},
diff --git a/capcodec/bench/corpus/pages/data/difflib_py.js b/capcodec/bench/corpus/pages/data/difflib_py.js
index 4bfbd4c18..d94118ba7 100644
--- a/capcodec/bench/corpus/pages/data/difflib_py.js
+++ b/capcodec/bench/corpus/pages/data/difflib_py.js
@@ -1 +1,2 @@
-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";
+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
index 3fa9cd72e..243111dc6 100644
--- a/capcodec/bench/corpus/pages/data/inflate_c.js
+++ b/capcodec/bench/corpus/pages/data/inflate_c.js
@@ -1 +1,2 @@
-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";
+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/scenarios.py b/capcodec/bench/corpus/scenarios.py
index 4537b2e1d..26c49cdf9 100644
--- a/capcodec/bench/corpus/scenarios.py
+++ b/capcodec/bench/corpus/scenarios.py
@@ -1,9 +1,4 @@
-"""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.
-"""
+"""Scenarios run on a worker thread. Pointer and keyboard input is injected there; ctx.js() runs on the Playwright thread."""
import math
import re
diff --git a/capcodec/bench/harness/adapters/base.py b/capcodec/bench/harness/adapters/base.py
index ce2a34333..495e1d71b 100644
--- a/capcodec/bench/harness/adapters/base.py
+++ b/capcodec/bench/harness/adapters/base.py
@@ -80,8 +80,6 @@ def raw_input_args(src: Source) -> list[str]:
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"
diff --git a/capcodec/bench/harness/runner.py b/capcodec/bench/harness/runner.py
index 74616e8f8..0483a3bff 100644
--- a/capcodec/bench/harness/runner.py
+++ b/capcodec/bench/harness/runner.py
@@ -588,7 +588,7 @@ def summarize(rows: list[dict], tier: Tier, refs: list[str]) -> dict:
"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")),
+ "errors": sum(1 for r in rows if r["encoder"] == e and (r.get("error") or r.get("metrics_error"))),
}
for k, t in tables.items():
for ref in refs:
@@ -642,6 +642,9 @@ def gate(summary: dict, best: dict | None) -> tuple[bool, list[str]]:
return ok, msgs
bd = s.get(f"bd_psnr_yuv_vs_{REFERENCE}")
fps = s.get("cpu_fps_median")
+ if bd is None:
+ ok = False
+ msgs.append(f"FAIL no BD-rate for {GATE_ENCODER} vs {REFERENCE}")
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:
diff --git a/capcodec/bench/integration/media-server-driver.ts b/capcodec/bench/integration/media-server-driver.ts
index 44852d663..53b43eb29 100644
--- a/capcodec/bench/integration/media-server-driver.ts
+++ b/capcodec/bench/integration/media-server-driver.ts
@@ -1,5 +1,5 @@
-import { processVideo } from "../../../apps/media-server/src/lib/media-video";
import { probeVideoFile } from "../../../apps/media-server/src/lib/media-probe";
+import { processVideo } from "../../../apps/media-server/src/lib/media-video";
const [input, output] = process.argv.slice(2);
if (!input || !output) {
@@ -12,4 +12,10 @@ 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 }));
+console.log(
+ JSON.stringify({
+ encoder: process.env.CAP_MEDIA_VIDEO_ENCODER ?? "libx264",
+ elapsedMs: elapsed,
+ metadata,
+ }),
+);
diff --git a/capcodec/bench/speedcmp.py b/capcodec/bench/speedcmp.py
index a08493a1e..645fd4e98 100644
--- a/capcodec/bench/speedcmp.py
+++ b/capcodec/bench/speedcmp.py
@@ -145,6 +145,7 @@ class Quiet:
self.done = threading.Event()
self.lock = threading.Lock()
self.watcher: threading.Thread | None = None
+ self.resumed = False
def stop(self, pids: list[int]) -> None:
with self.lock:
@@ -171,8 +172,19 @@ class Quiet:
if fresh:
self.stop(fresh)
+ def resume(self) -> None:
+ self.done.set()
+ if self.watcher is not None:
+ self.watcher.join()
+ self.watcher = None
+ if not self.resumed:
+ thaw(self.pids)
+ self.resumed = True
+
def __enter__(self):
- if self.enabled:
+ if not self.enabled:
+ return self
+ try:
for _ in range(20):
new = [p for p in freezable() if p not in self.stopped]
if not new:
@@ -182,14 +194,14 @@ class Quiet:
self.watcher = threading.Thread(target=self.watch, args=(spawners(), ancestors(os.getpid())), daemon=True)
self.watcher.start()
time.sleep(0.3)
+ except BaseException:
+ self.resume()
+ raise
return self
def __exit__(self, *exc):
if self.enabled:
- self.done.set()
- if self.watcher:
- self.watcher.join()
- thaw(self.pids)
+ self.resume()
return False
@@ -376,7 +388,8 @@ def write_report(results: dict, path: Path, threads: list[int]) -> None:
head = "| clip | mode | VMAF | capcodec crf | kbps vs x264 |"
sep = "|---|---|---|---|---|"
for t in threads:
- head += f" CPU {t}t | wall {t}t |"
+ x264 = "1t" if t == 1 else "auto"
+ head += f" CPU cap {t}t / x264 {x264} | wall cap {t}t / x264 {x264} |"
sep += "---|---|"
lines += [head, sep]
for e in results.values():