From db7311f8741ed34931210577a7e660880c555135 Mon Sep 17 00:00:00 2001 From: harry Date: Wed, 18 Nov 2026 18:25:12 +0900 Subject: [PATCH 1/2] bench: AV1, HEVC and H.264 in Chrome as a stand-in for NVENC (#82, first stage) The user's PC and its NVENC are not at hand, so Chrome's WebCodecs encoders on the Mac stand in. scripts/chrome_codecs.mjs drives headless Chrome over the DevTools protocol (mock keychain, a profile of its own, a page served on 127.0.0.1 only): a page encodes a Y4M with VideoEncoder in real-time mode at a constant bit rate, a key frame first and predicted frames after it, decodes the chunks with VideoDecoder and compares every decoded frame with its source. emberwave encodes the same pictures at the bytes each Chrome stream used, and emberwave-cli quality measures it. Two sets of pictures, both synthetic: the benchmark scene, and a copy with fresh noise in every frame (make_grainy.py). The results are in BENCHMARKS.md: at the same bytes the codecs with predicted frames lead in PSNR, by 15 to 18 dB on the scene and 3 to 5 dB on the noisy copy, decode in 1.0 to 5.9 ms at Moonlight's rates, and say little about D67's chroma weights, which stay. Rows that Chrome could not make are listed. Claude-Session: https://claude.ai/code/session_019fJGoCTvP5e7n599q3ZQ42 --- ARCHITECTURE.md | 1 + BENCHMARKS.md | 79 +++++++ README.ko.md | 2 +- README.md | 2 +- scripts/chrome_codecs.mjs | 330 +++++++++++++++++++++++++++ scripts/chrome_codecs/make_grainy.py | 47 ++++ scripts/chrome_codecs/page.html | 248 ++++++++++++++++++++ 7 files changed, 707 insertions(+), 2 deletions(-) create mode 100755 scripts/chrome_codecs.mjs create mode 100755 scripts/chrome_codecs/make_grainy.py create mode 100644 scripts/chrome_codecs/page.html diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index df5218e..9a5aeea 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1717,6 +1717,7 @@ The last frame's detail, always, gains everything on a still picture and loses u - #136 is closed. Within its objective the encoder has under 1 % left, and measured by a metric of perceived quality, the objective itself has a few percent of bytes left. - If game footage of more than one frame, such as #82's, shows the chroma tilt's gain, the tilt goes into `gen_encoder_weights.py` as chroma's own sensitivity, for both encoders, and D57's measure keeps upstream's weights. - SSIMULACRA2 stays out of the repository. In `emberwave-cli quality` it would add a dependency, and its BSD-2-Clause notice to every release, for a study that ran once. +- **Follow-up of 2026-11-18 (#82, first stage).** Chrome's WebCodecs encoders, on synthetic pictures, say little about the tilt (BENCHMARKS.md, "Against AV1 and HEVC in Chrome"): at the same bytes emberwave's chroma PSNR sits further above its luma PSNR than that of AV1, HEVC and H.264 with predicted frames, 4.2 to 12.6 dB against 2.9 to 9.5 on the benchmark scene, which is the direction the tilt would move bits, but PSNR counts every band alike and the pictures are neither game footage nor perceptually measured. The weights stay upstream's; game footage and SSIMULACRA2 are still what would change that. ### 2026-10-31 — D68: The transforms read their rows straight from the bands diff --git a/BENCHMARKS.md b/BENCHMARKS.md index 21d2817..27bab94 100644 --- a/BENCHMARKS.md +++ b/BENCHMARKS.md @@ -439,3 +439,82 @@ What a frame's budget buys, on a hard picture: a 4K frame of the game Crimson De | 2.5 MB | 2,319,594 bytes | 1113 Mbit/s | 36.34 | 37.87 | 37.85 | 32.87 | - **How firm the numbers are.** One picture, and PSNR, which follows what the eye sees only roughly. The HEVC numbers come from a scratch program that was not kept. + +## Against AV1 and HEVC in Chrome (stand-in for NVENC) + +Issue #82 asks for the streams of a PC's NVENC, HEVC and AV1, decoded beside emberwave's. This is its first stage, made on the Mac alone with the encoders that Chrome offers through WebCodecs: it says how emberwave compares in picture quality, bytes and decoding time with HEVC and AV1 with predicted frames at the same bytes a frame, without the PC and without game footage. NVENC's own streams, and moving game footage, are still to come, and the iPhone's half. + +**How.** `scripts/chrome_codecs.mjs` drives headless Chrome over the DevTools protocol. A page encodes a Y4M with `VideoEncoder`, one frame at a time, in real-time mode at a constant bit rate, 60 frames a second, a key frame first and predicted frames after it, no B frames, then decodes the chunks with `VideoDecoder` (the hardware decoder where Chrome has one) and compares every decoded frame with its source in the page, plane by plane. emberwave encodes the same pictures with `emberwave-cli encode --gpu` at the bytes each Chrome stream used on average, and `emberwave-cli quality` measures it. Two bit rates a size: Moonlight's default for it (20, 40 and 80 Mbit/s for 1080p, 1440p and 4K at 60 frames a second), and the bit rate of emberwave's own budget (192, 336 and 576 Mbit/s). + +**Pictures: synthetic, not game footage.** Twenty frames of the benchmark scene of the other tables (colour bars, a gradient, a moving shaded disc, a fine grid and a little grain; 78 % of its pixels change from one frame to the next, 30.9 dB between frames), and a copy with fresh Gaussian noise added to every frame, 6 levels on luma and 3 on chroma (`scripts/chrome_codecs/make_grainy.py`), which a codec that predicts cannot predict. Neither is a game. The scene's motion is easy to predict, which flatters the codecs with predicted frames; the grainy copy is the hard end. + +**What Chrome has.** Chrome 157.0.8103.79, headless, on the Mac of the tables above. It encodes AV1 in software only (and decodes it in hardware), HEVC and H.264 in hardware, through VideoToolbox, and in software. The hardware H.264 encoder returned no frames at 336 and 576 Mbit/s, the stream of the hardware HEVC encoder at 336 Mbit/s and 1440p could not be decoded ("EncodingError: Decoding error"), and the software H.264 encoder is refused at those rates; those rows are missing. VP9 was left out: NVENC does not encode it. + +Measured on 2026-11-18 from 18:14 to 18:23 on the Apple M3 Max of the tables above, macOS 27.0.1, on mains power, with the load average at 5.0 to 7.7: other programs ran, and the Mac was not quiet. One run of each: repeat it before relying on a difference of a decibel. + +Each row is a Chrome stream and, beside it, emberwave at the same bytes a frame (the mean of all 20 frames, the key frame included, rounded to 50 bytes). **kB a frame** is that mean. **Y dB**, **Cb / Cr dB** are the PSNR of the 19 frames after the key frame, averaged. **Decode ms** is the median time from handing a chunk to `VideoDecoder` until its frame is out, one frame at a time, and **queued** is the time a frame takes when all 20 are handed over at once; the frame is not copied out in either. The run's HEVC and H.264 encoders are the hardware's, AV1's is software. + +### The benchmark scene + +| Size | Codec | asked Mbit/s | kB a frame | codec Y dB | emberwave Y dB | codec Cb / Cr dB | emberwave Cb / Cr dB | decode ms | decode, queued ms | +|---|---|---|---|---|---|---|---|---|---| +| 1080p | AV1 | 20 | 8.0 | 44.43 | 27.07 | 47.36 / 46.51 | 31.74 / 33.20 | 1.00 | 0.91 | +| 1080p | HEVC | 20 | 13.7 | 45.87 | 28.18 | 53.18 / 53.89 | 34.69 / 36.37 | 1.30 | 1.01 | +| 1080p | H.264 | 20 | 39.8 | 45.79 | 29.26 | 50.79 / 51.48 | 40.63 / 41.50 | 2.00 | 1.19 | +| 1080p | AV1 | 192 | 9.7 | 45.08 | 27.78 | 49.03 / 47.89 | 31.96 / 33.51 | 1.00 | 1.05 | +| 1080p | HEVC | 192 | 18.6 | 45.94 | 28.43 | 54.27 / 54.81 | 35.06 / 37.42 | 1.40 | 1.10 | +| 1080p | H.264 | 192 | 60.4 | 46.13 | 30.67 | 51.40 / 52.94 | 41.24 / 42.61 | 2.60 | 1.46 | +| 1440p | AV1 | 40 | 13.5 | 44.62 | 27.26 | 48.27 / 47.96 | 33.38 / 34.59 | 1.50 | 1.26 | +| 1440p | HEVC | 40 | 23.6 | 45.90 | 28.22 | 53.76 / 54.74 | 37.05 / 38.59 | 1.70 | 1.09 | +| 1440p | H.264 | 40 | 81.2 | 45.44 | 30.02 | 51.12 / 51.92 | 41.42 / 42.64 | 3.40 | 2.08 | +| 1440p | AV1 | 336 | 17.4 | 45.16 | 27.95 | 49.85 / 49.61 | 34.54 / 36.27 | 1.40 | 1.43 | +| 4k | AV1 | 80 | 29.1 | 44.50 | 27.38 | 48.14 / 48.10 | 34.07 / 35.35 | 2.40 | 2.73 | +| 4k | HEVC | 80 | 46.9 | 45.90 | 28.27 | 54.25 / 54.96 | 37.37 / 38.85 | 2.80 | 2.67 | +| 4k | H.264 | 80 | 160.5 | 45.57 | 29.73 | 51.71 / 52.69 | 42.33 / 43.60 | 5.90 | 3.80 | +| 4k | AV1 | 576 | 37.5 | 45.21 | 28.07 | 50.59 / 50.04 | 35.41 / 37.29 | 2.30 | 3.32 | +| 4k | HEVC | 576 | 65.9 | 45.97 | 28.55 | 55.51 / 56.24 | 38.06 / 39.46 | 2.90 | 2.85 | + +### The scene with fresh noise in every frame + +| Size | Codec | asked Mbit/s | kB a frame | codec Y dB | emberwave Y dB | codec Cb / Cr dB | emberwave Cb / Cr dB | decode ms | decode, queued ms | +|---|---|---|---|---|---|---|---|---|---| +| 1080p | AV1 | 20 | 42.2 | 32.28 | 27.64 | 37.71 / 37.77 | 36.47 / 36.91 | 1.80 | 1.39 | +| 1080p | HEVC | 20 | 55.7 | 32.70 | 28.26 | 37.94 / 37.99 | 36.73 / 37.02 | 1.10 | 0.94 | +| 1080p | H.264 | 20 | 56.7 | 32.43 | 28.32 | 37.71 / 37.83 | 36.73 / 37.02 | 1.60 | 1.51 | +| 1080p | AV1 | 192 | 173.6 | 33.96 | 29.68 | 38.23 / 38.29 | 37.16 / 37.55 | 2.40 | 3.61 | +| 1080p | HEVC | 192 | 418.0 | 37.87 | 33.86 | 39.13 / 39.14 | 38.80 / 38.70 | 4.00 | 1.68 | +| 1080p | H.264 | 192 | 416.4 | 37.59 | 33.85 | 38.95 / 38.98 | 38.80 / 38.70 | 7.40 | 3.42 | +| 1440p | AV1 | 40 | 85.6 | 32.41 | 28.16 | 37.97 / 38.02 | 36.81 / 37.18 | 2.60 | 2.47 | +| 1440p | HEVC | 40 | 115.6 | 32.81 | 28.83 | 38.04 / 38.09 | 36.97 / 37.36 | 1.80 | 1.56 | +| 1440p | H.264 | 40 | 120.0 | 32.53 | 28.93 | 37.76 / 37.90 | 36.97 / 37.36 | 2.70 | 2.49 | +| 1440p | AV1 | 336 | 290.6 | 33.87 | 29.67 | 38.27 / 38.31 | 37.29 / 37.65 | 3.90 | 6.27 | +| 4k | AV1 | 80 | 168.9 | 32.41 | 27.98 | 37.98 / 38.08 | 37.04 / 37.34 | 5.00 | 5.90 | +| 4k | HEVC | 80 | 217.4 | 32.71 | 28.51 | 38.06 / 38.11 | 37.11 / 37.55 | 3.50 | 3.35 | +| 4k | H.264 | 80 | 224.7 | 32.43 | 28.60 | 37.78 / 37.91 | 37.11 / 37.55 | 4.50 | 4.95 | +| 4k | AV1 | 576 | 723.6 | 34.20 | 29.83 | 38.47 / 38.51 | 37.58 / 37.83 | 11.80 | 15.39 | +| 4k | HEVC | 576 | 1259.5 | 36.37 | 33.27 | 38.68 / 38.69 | 38.22 / 38.20 | 12.60 | 5.41 | + +- **The encoders do not fill the rate they are asked for on the scene.** At Moonlight's rates a 1080p stream came to 3.8 Mbit/s with AV1, 6.6 with HEVC and 19.1 with H.264 against 20 asked; at 4K 14.0, 22.5 and 77.0 against 80. Real-time mode keeps to a quality ceiling, and a scene that predicts well needs few bytes. The rows are compared at the bytes they used, not the rates they were asked for. +- **At the same bytes the codecs with predicted frames lead in PSNR.** On the scene by 15.4 to 17.7 dB of luma, on the noisy copy by 3.1 to 4.6 dB, at every size and rate that ran. The scene's motion is easy to predict: the codecs hold 44.0 to 46.1 dB of luma on it from 8 kB to 160 kB a frame, where emberwave needs 400 kB for 46.8 dB at 1080p. The noisy copy leaves the codecs only the noise to code, and they lead by about 4 dB. The earlier comparison on a single key frame of a game, [above](#picture-quality), had HEVC 1.9 to 3.5 dB ahead of emberwave on luma with 2 to 10 % fewer bytes, where nothing could be predicted: the lead here is the prediction's. +- **That is what emberwave trades for.** Every frame of it stands alone, so a lost frame costs nothing after it, a decode needs no earlier frame, and the GPU encoder takes 0.8 to 1.9 ms a frame on this Mac ([encoding above](#results)) where Chrome's hardware encoders took 6 ms at 1080p and 22 to 24 ms at 4K and its software HEVC encoder 112 to 606 ms. The table does not say what the codecs' lead is worth to a viewer: PSNR counts every pixel alike, the pictures are synthetic, and the encoders were in real-time mode. +- **Decoding in Chrome.** At Moonlight's rates a frame took 1.0 to 5.9 ms to come out of `VideoDecoder`, 2.4 to 2.8 ms at 4K with AV1 and HEVC and 5.9 ms with H.264; at emberwave's bytes it took up to 12.6 ms (4K, HEVC, the noisy copy). emberwave's own decode in earlier Chrome versions on this Mac, through WebGPU, took 0.70 to 1.00 ms at 1080p and 1.69 to 1.88 ms at 4K into an RGB texture, frame after frame ([In the browser](#in-the-browser-phones-included)), and 4.50 to 5.67 ms at 4K at a stream's pace. The two do different work: `VideoDecoder`'s hardware decoders run beside the GPU and hand over video frames that are not yet drawn, and the page measures the time to the frame, not to the screen. +- **For D67's chroma weights these numbers say little.** At the same bytes emberwave's chroma PSNR sits further above its luma PSNR (4.2 to 12.6 dB on the scene, 4.9 to 9.1 on the noisy copy) than the codecs' (2.9 to 9.5, 1.3 to 5.6). That is the direction in which D67's tilt would move bits at low budgets, from chroma to luma, but PSNR counts every band alike and the pictures are synthetic, with the chroma of bars and a gradient and noise that is the same in both up to its scale. Game footage and a perceptual metric are what D67 asks for; the weights stay upstream's. +- **Not measured.** NVENC's own streams, which differ from VideoToolbox's and libaom's; moving game footage; a second run; the iPhone; the rows listed below. + +Rows that did not run: +- scene 1440p HEVC 336 Mbit/s: EncodingError: Decoding error. +- scene 1440p H.264 336 Mbit/s: 0 chunks for 20 frames +- scene 4k H.264 576 Mbit/s: 0 chunks for 20 frames +- grainy 1440p HEVC 336 Mbit/s: EncodingError: Decoding error. +- grainy 1440p H.264 336 Mbit/s: 0 chunks for 20 frames +- grainy 4k H.264 576 Mbit/s: 0 chunks for 20 frames + +```sh +scripts/gen_bench_data.sh --sources # the scene's pictures, once +for s in 1080p 1440p 4k; do scripts/chrome_codecs/make_grainy.py testdata/generated/scene_${s}_420.y4m testdata/generated/grainy_${s}_420.y4m; done +cargo build --release -p emberwave-cli +node scripts/chrome_codecs.mjs all # about 8 minutes; writes target/chrome-codecs/*.json +node scripts/chrome_codecs.mjs summary # the tables above; `report` lists every run +``` + +It needs Google Chrome, Node 20 or later and numpy. Chrome runs with a mock keychain and a profile of its own, and its page is served on 127.0.0.1 only. diff --git a/README.ko.md b/README.ko.md index 1c12573..e1108aa 100644 --- a/README.ko.md +++ b/README.ko.md @@ -148,7 +148,7 @@ iPhone 17의 Safari에서는 [벤치마크 페이지](https://with-developer.git 앞으로 할 일입니다. 준비되는 대로 각각 릴리스합니다. -- **실사용 환경에서 측정.** 클라이언트의 화면 출력 루프 안에서 디코딩해, 화면에 나오기까지의 시간을 Mac과 iPhone에서 잽니다([#81](https://github.com/with-developer/emberwave/issues/81), Mac 쪽은 끝났고 결정 D72에 기록했습니다). NVENC로 만든 HEVC와 AV1 스트림을 emberwave 스트림과 나란히 디코딩하고, 움직이는 게임 영상의 화질을 같은 비트레이트에서 예측 프레임을 쓰는 HEVC와 비교합니다([#82](https://github.com/with-developer/emberwave/issues/82)). 이 비교로 색차 대역 가중치를 바꿀지도 정합니다(결정 D67). 스트림 속도에서 4K는 upstream의 FP32 디코더를 따라잡았지만 1080p는 아직 0.15~0.3 ms 느리며, 이 차이를 줄입니다([#150](https://github.com/with-developer/emberwave/issues/150)). +- **실사용 환경에서 측정.** 클라이언트의 화면 출력 루프 안에서 디코딩해, 화면에 나오기까지의 시간을 Mac과 iPhone에서 잽니다([#81](https://github.com/with-developer/emberwave/issues/81), Mac 쪽은 끝났고 결정 D72에 기록했습니다). NVENC로 만든 HEVC와 AV1 스트림을 emberwave 스트림과 나란히 디코딩하고, 움직이는 게임 영상의 화질을 같은 비트레이트에서 예측 프레임을 쓰는 HEVC와 비교합니다([#82](https://github.com/with-developer/emberwave/issues/82)). 이 비교로 색차 대역 가중치를 바꿀지도 정합니다(결정 D67). 1단계로, 합성 영상에 Chrome의 인코더를 쓴 결과는 [BENCHMARKS.md](BENCHMARKS.md#against-av1-and-hevc-in-chrome-stand-in-for-nvenc)에 있습니다. 스트림 속도에서 4K는 upstream의 FP32 디코더를 따라잡았지만 1080p는 아직 0.15~0.3 ms 느리며, 이 차이를 줄입니다([#150](https://github.com/with-developer/emberwave/issues/150)). - **1.0을 향해: 클라이언트.** emberwave가 코덱으로 남도록, 브라우저 스트리밍은 별도 저장소에서 만듭니다. 호스트 화면을 GPU에서 인코딩해 로컬 네트워크로 보내고, 브라우저 탭에서 WebGPU로 디코딩합니다. 지연 시간부터 잽니다. 그다음에는 PyroWave로 스트리밍하는 호스트들에 emberwave 인코더를 제안합니다. 1.0이 되려면 안정된 C·Rust API, 실제로 쓰이는 클라이언트 하나, 그리고 프레임이 실제 스트림의 간격으로 들어올 때 업스트림만큼 빠른 디코딩이 필요합니다. ## 저장소 구성 diff --git a/README.md b/README.md index 7b3eae7..6f184e3 100644 --- a/README.md +++ b/README.md @@ -148,7 +148,7 @@ Done: the milestones to the first release, M0 to M5 ([#1](https://github.com/wit Next, each in a release when it is ready: -- **Measured in real use.** Decoding inside a client's display loop, timed to the screen, on a Mac and an iPhone ([#81](https://github.com/with-developer/emberwave/issues/81); the Mac's half is done, decision D72); NVENC's HEVC and AV1 streams decoded beside emberwave's, and the quality of moving game footage against HEVC with predicted frames at the same bit rate, which also tells whether chroma's band weights should change ([#82](https://github.com/with-developer/emberwave/issues/82), decision D67); and 1080p at a stream's pace, still 0.15 to 0.3 ms behind upstream's FP32 decoder where 4K has caught up ([#150](https://github.com/with-developer/emberwave/issues/150)). +- **Measured in real use.** Decoding inside a client's display loop, timed to the screen, on a Mac and an iPhone ([#81](https://github.com/with-developer/emberwave/issues/81); the Mac's half is done, decision D72); NVENC's HEVC and AV1 streams decoded beside emberwave's, and the quality of moving game footage against HEVC with predicted frames at the same bit rate, which also tells whether chroma's band weights should change ([#82](https://github.com/with-developer/emberwave/issues/82), decision D67; a first stage with Chrome's encoders on synthetic pictures is in [BENCHMARKS.md](BENCHMARKS.md#against-av1-and-hevc-in-chrome-stand-in-for-nvenc)); and 1080p at a stream's pace, still 0.15 to 0.3 ms behind upstream's FP32 decoder where 4K has caught up ([#150](https://github.com/with-developer/emberwave/issues/150)). - **Toward 1.0, clients.** Streaming to a browser, in a repository of its own so that emberwave stays a codec: a host's screen encoded on its GPU, sent over the local network and decoded with WebGPU in a tab, its latency measured first. After that, emberwave's encoder offered to the hosts that stream PyroWave. 1.0 needs stable C and Rust APIs, one client in real use, and decoding at a stream's pace level with upstream's. ## Repository layout diff --git a/scripts/chrome_codecs.mjs b/scripts/chrome_codecs.mjs new file mode 100755 index 0000000..f674dcf --- /dev/null +++ b/scripts/chrome_codecs.mjs @@ -0,0 +1,330 @@ +#!/usr/bin/env node +// Chrome's WebCodecs as a stand-in for NVENC (issue #82): encodes a Y4M with +// the codecs this Chrome has, decodes the streams again, and compares picture +// quality, size and time with emberwave's frames of the same size. +// +// node scripts/chrome_codecs.mjs probe [1080p|1440p|4k] +// node scripts/chrome_codecs.mjs run SIZE CODEC MBIT [--hw H] [--frames N] +// node scripts/chrome_codecs.mjs all [--sizes 1080p,1440p,4k] [--out DIR] +// node scripts/chrome_codecs.mjs report [DIR] every run +// node scripts/chrome_codecs.mjs summary [DIR] the tables of BENCHMARKS.md +// +// `all` writes one JSON file per run into DIR (target/chrome-codecs by +// default), `report` turns those into the tables of BENCHMARKS.md. It needs +// Google Chrome, Node 20 or later with --experimental-websocket (the script +// re-runs itself with the flag), the Y4M files of scripts/gen_bench_data.sh +// --sources in testdata/generated, and a release build of emberwave-cli. +// +// Chrome runs headless, with a mock keychain and a profile of its own, and its +// page is served on 127.0.0.1 only, so that nothing asks the user for a +// permission. Everything it starts is stopped at the end. + +import { spawn, spawnSync } from 'node:child_process'; +import { createServer } from 'node:http'; +import { createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const CHROME = process.env.CHROME || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +const CLI = join(root, 'target/release/emberwave-cli'); + +// The sizes of the other comparisons (BENCHMARKS.md): Moonlight's default bit +// rate at 60 frames a second, and emberwave's bytes per frame. +const SIZES = { + '1080p': { moonlight: 20, emberwaveBytes: 400_000 }, + '1440p': { moonlight: 40, emberwaveBytes: 700_000 }, + '4k': { moonlight: 80, emberwaveBytes: 1_200_000 }, +}; +// The pictures: the benchmark scene (scripts/gen_bench_data.sh --sources), and +// a copy of it with fresh noise in every frame (chrome_codecs/make_grainy.py). +const SCENES = ['scene', 'grainy']; +const sceneFile = (scene, size) => `${scene}_${size}_420.y4m`; +const FRAMERATE = 60; + +if (typeof WebSocket === 'undefined') { + const again = spawnSync(process.execPath, ['--experimental-websocket', ...process.argv.slice(1)], { stdio: 'inherit' }); + process.exit(again.status ?? 1); +} + +// A static server on loopback: the page and the Y4M files. +function serve(directory) { + const server = createServer((request, response) => { + const path = decodeURIComponent(new URL(request.url, 'http://x').pathname); + let file = null; + if (path === '/' || path === '/page.html') file = join(root, 'scripts/chrome_codecs/page.html'); + else if (path.startsWith('/data/')) file = join(directory, path.slice(6)); + if (!file || file.includes('..') || !existsSync(file)) { + response.writeHead(404).end(); + return; + } + response.writeHead(200, { 'content-length': statSync(file).size, 'content-type': file.endsWith('.html') ? 'text/html' : 'application/octet-stream' }); + createReadStream(file).pipe(response); + }); + return new Promise((done) => server.listen(0, '127.0.0.1', () => done(server))); +} + +// Chrome, headless, and a DevTools connection to a page. +async function launch(url) { + const profile = mkdtempSync(join(tmpdir(), 'emberwave-chrome-')); + const chrome = spawn(CHROME, [ + '--headless=new', '--use-mock-keychain', '--password-store=basic', `--user-data-dir=${profile}`, + '--remote-debugging-port=0', '--no-first-run', '--no-default-browser-check', '--disable-extensions', + '--autoplay-policy=no-user-gesture-required', + // The page is never in front: do not let Chrome slow its timers or its tasks down. + '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows', + 'about:blank', + ], { stdio: ['ignore', 'ignore', 'pipe'] }); + const version = await new Promise((done, fail) => { + let text = ''; + chrome.stderr.on('data', (chunk) => { + text += chunk; + const match = /DevTools listening on (ws:\/\/\S+)/.exec(text); + if (match) done(match[1]); + }); + chrome.on('exit', () => fail(new Error('Chrome ended before it listened'))); + setTimeout(() => fail(new Error('Chrome did not start')), 30000); + }); + const port = new URL(version).port; + const target = await (await fetch(`http://127.0.0.1:${port}/json/new?${url}`, { method: 'PUT' })).json(); + const socket = new WebSocket(target.webSocketDebuggerUrl); + await new Promise((done, fail) => { socket.onopen = done; socket.onerror = fail; }); + let id = 0; + const waiting = new Map(); + socket.onmessage = (message) => { + const data = JSON.parse(message.data); + if (data.id && waiting.has(data.id)) { + waiting.get(data.id)(data); + waiting.delete(data.id); + } + }; + const send = (method, params = {}) => new Promise((done) => { + waiting.set(++id, done); + socket.send(JSON.stringify({ id, method, params })); + }); + const evaluate = async (expression) => { + const reply = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true, timeout: 3_600_000 }); + if (reply.error) throw new Error(JSON.stringify(reply.error)); + if (reply.result.exceptionDetails) throw new Error(reply.result.exceptionDetails.exception?.description || JSON.stringify(reply.result.exceptionDetails)); + return reply.result.result.value; + }; + // Chrome writes to its profile until it has ended: wait for it, then remove it. + const close = async () => { + try { socket.close(); } catch { /* already closed */ } + const ended = new Promise((done) => chrome.once('exit', done)); + chrome.kill('SIGTERM'); + const killer = setTimeout(() => chrome.kill('SIGKILL'), 5000); + await ended; + clearTimeout(killer); + rmSync(profile, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); + }; + return { evaluate, close }; +} + +async function withPage(directory, body) { + const server = await serve(directory); + const page = await launch(`http://127.0.0.1:${server.address().port}/page.html`); + try { + for (let i = 0; i < 100 && !(await page.evaluate('window.ready === true')); i++) await new Promise((r) => setTimeout(r, 100)); + return await body(page, `http://127.0.0.1:${server.address().port}/data/`); + } finally { + await page.close(); + server.close(); + } +} + +const dataDir = join(root, 'testdata/generated'); +const sizeInfo = (name) => { + const info = SIZES[name.toLowerCase()]; + if (!info) throw new Error(`unknown size ${name}: 1080p, 1440p or 4k`); + return info; +}; +const dims = { '1080p': [1920, 1080], '1440p': [2560, 1440], '4k': [3840, 2160] }; + +// emberwave on the same pictures at a number of bytes per frame: the CLI +// encodes (on the GPU: the CPU's bytes are the same up to a few blocks) and +// `quality` compares each frame with the source. +function emberwave(scene, size, bytesPerFrame, frames, work) { + const input = join(dataDir, sceneFile(scene, size)); + const stream = join(work, `emberwave-${scene}-${size}-${bytesPerFrame}.pwv1`); + const encode = spawnSync(CLI, ['encode', input, '--out', stream, '--bytes-per-frame', String(bytesPerFrame), '--frames', String(frames), '--gpu'], { encoding: 'utf8' }); + if (encode.status !== 0) throw new Error(`emberwave-cli encode: ${encode.stderr}`); + const quality = spawnSync(CLI, ['quality', input, stream, '--frames', String(frames)], { encoding: 'utf8' }); + if (quality.status !== 0) throw new Error(`emberwave-cli quality: ${quality.stderr}`); + const rows = []; + for (const line of quality.stdout.split('\n')) { + const m = /^frame\s+(\d+):\s+(\d+) bytes\s+Y\s+([\d.]+) dB\s+Cb\s+([\d.]+) dB\s+Cr\s+([\d.]+) dB/.exec(line); + if (m) rows.push({ bytes: Number(m[2]), psnr: [Number(m[3]), Number(m[4]), Number(m[5])] }); + } + return { name: 'emberwave', scene, size, bytesPerFrame, rows }; +} + +const mean = (values) => values.reduce((a, b) => a + b, 0) / values.length; +const median = (values) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]; + +function parseArgs(argv) { + const positional = []; + const options = {}; + for (let i = 0; i < argv.length; i++) { + if (argv[i].startsWith('--')) options[argv[i].slice(2)] = argv[++i]; + else positional.push(argv[i]); + } + return { positional, options }; +} + +const { positional, options } = parseArgs(process.argv.slice(2)); +const command = positional[0]; + +if (command === 'probe') { + const size = (positional[1] || '1080p').toLowerCase(); + const [width, height] = dims[size]; + const result = await withPage(dataDir, (page) => page.evaluate(`window.probe(${width}, ${height}, ${sizeInfo(size).moonlight * 1e6}, ${FRAMERATE})`)); + console.log(JSON.stringify(result, null, 2)); +} else if (command === 'run') { + const [size, codec, mbit] = positional.slice(1); + const hw = options.hw || 'no-preference'; + const frames = Number(options.frames || 20); + const result = await withPage(dataDir, (page, base) => page.evaluate(`window.run(${JSON.stringify({ + url: base + sceneFile(options.scene || 'scene', size), codec, bitrate: Number(mbit) * 1e6, hw, decodeHw: options['decode-hw'] || hw, frames, framerate: FRAMERATE, name: options.name || codec, + })})`)); + console.log(JSON.stringify(result)); +} else if (command === 'all') { + const out = resolve(options.out || join(root, 'target/chrome-codecs')); + mkdirSync(out, { recursive: true }); + const sizes = (options.sizes || '1080p,1440p,4k').split(','); + const scenes = (options.scenes || SCENES.join(',')).split(','); + const frames = Number(options.frames || 20); + const only = options.codecs ? options.codecs.split(',') : null; + await withPage(dataDir, async (page, base) => { + for (const size of sizes) { + const info = sizeInfo(size); + const [width, height] = dims[size]; + const probe = await page.evaluate(`window.probe(${width}, ${height}, ${info.moonlight * 1e6}, ${FRAMERATE})`); + writeFileSync(join(out, `probe-${size}.json`), JSON.stringify(probe, null, 1)); + const rates = [info.moonlight, Math.round(info.emberwaveBytes * 8 * FRAMERATE / 1e6)]; + for (const scene of scenes) { + for (const [name, entry] of Object.entries(probe.codecs)) { + // The codecs of NVENC: H.264, HEVC and AV1. + if (name === 'VP9' || (only && !only.includes(name))) continue; + // Encode in hardware where there is an encoder and in software too; decode + // where a client would, in hardware if there is a decoder. + const decodeHw = entry.decode['prefer-hardware'] === true ? 'prefer-hardware' : 'prefer-software'; + const modes = ['prefer-hardware', 'prefer-software'].filter((hw) => entry.encode[hw] === true && (entry.decode[decodeHw] === true)); + for (const hw of modes) { + for (const mbit of rates) { + const file = join(out, `${scene}-${size}-${name.replace(/[^A-Za-z0-9]/g, '')}-${hw.replace('prefer-', '')}-${mbit}.json`); + if (existsSync(file) && !options.force) continue; + console.error(`${scene} ${size} ${name} ${hw} ${mbit} Mbit/s`); + let result; + try { + result = await page.evaluate(`window.run(${JSON.stringify({ url: base + sceneFile(scene, size), codec: entry.codec, bitrate: mbit * 1e6, hw, decodeHw, frames, framerate: FRAMERATE, name })})`); + } catch (error) { + result = { name, codec: entry.codec, hw, bitrate: mbit * 1e6, error: String(error.message || error) }; + } + result.size = size; + result.scene = scene; + writeFileSync(file, JSON.stringify(result)); + } + } + } + } + } + }); + // emberwave at the bytes each run actually used (all frames of the stream, + // the key frame included), where it can make a frame that small, and at the + // budgets of the other comparisons. + const budgets = new Map(); + for (const size of sizes) { + const info = sizeInfo(size); + for (const scene of scenes) { + budgets.set(`${scene}-${size}-${Math.round(info.moonlight * 1e6 / 8 / FRAMERATE)}`, { scene, size, bytes: Math.round(info.moonlight * 1e6 / 8 / FRAMERATE) }); + budgets.set(`${scene}-${size}-${info.emberwaveBytes}`, { scene, size, bytes: info.emberwaveBytes }); + } + } + for (const file of readdirSync(out)) { + if (file.startsWith('probe') || file.startsWith('emberwave') || !file.endsWith('.json')) continue; + const run = JSON.parse(readFileSync(join(out, file), 'utf8')); + if (!run.chunkBytes) continue; + const bytes = Math.round(mean(run.chunkBytes) / 50) * 50; + budgets.set(`${run.scene}-${run.size}-${bytes}`, { scene: run.scene, size: run.size, bytes }); + } + for (const [, { scene, size, bytes }] of budgets) { + const file = join(out, `emberwave-${scene}-${size}-${bytes}.json`); + if (existsSync(file) && !options.force) continue; + console.error(`emberwave ${scene} ${size} ${bytes} bytes a frame`); + try { + writeFileSync(file, JSON.stringify(emberwave(scene, size, bytes, frames, out))); + } catch (error) { + // A budget below the smallest frame the pictures' size allows. + writeFileSync(file, JSON.stringify({ name: 'emberwave', scene, size, bytesPerFrame: bytes, error: String(error.message).slice(0, 200) })); + } + } +} else if (command === 'report') { + const dir = resolve(positional[1] || join(root, 'target/chrome-codecs')); + const runs = readdirSync(dir).filter((f) => f.endsWith('.json') && !f.startsWith('probe')).map((f) => JSON.parse(readFileSync(join(dir, f), 'utf8'))); + const rows = []; + for (const run of runs) { + if (run.name === 'emberwave') { + if (run.error) continue; + const all = run.rows; + const steady = all.slice(1); + rows.push({ scene: run.scene, size: run.size, who: 'emberwave', order: 1, asked: null, bytes: mean(all.map((r) => r.bytes)), steadyBytes: mean(steady.map((r) => r.bytes)), y: mean(steady.map((r) => r.psnr[0])), yMin: Math.min(...steady.map((r) => r.psnr[0])), cb: mean(steady.map((r) => r.psnr[1])), cr: mean(steady.map((r) => r.psnr[2])), key: all[0].psnr[0] }); + } else if (run.psnr) { + const steady = run.psnr.slice(1); + rows.push({ scene: run.scene, size: run.size, who: `${run.name} (${run.hw.replace('prefer-', '')} enc)`, order: 2, asked: Math.round(run.bitrate / 1e6), bytes: mean(run.chunkBytes), steadyBytes: mean(run.chunkBytes.slice(1)), keyBytes: run.chunkBytes[0], y: mean(steady.map((p) => p[0])), yMin: Math.min(...steady.map((p) => p[0])), cb: mean(steady.map((p) => p[1])), cr: mean(steady.map((p) => p[2])), key: run.psnr[0][0], decode: median(run.decodeMs.slice(1)), queue: run.decodeQueueMsPerFrame, held: run.decoderHeld, encode: median(run.encodeMs.slice(1)), keyframes: run.chunkTypes.filter((t) => t === 'key').length, decodeHw: run.decodeHw, sourceChange: mean(run.sourceChange) }); + } else { + rows.push({ scene: run.scene, size: run.size, who: `${run.name} (${String(run.hw).replace('prefer-', '')} enc)`, order: 2, asked: Math.round(run.bitrate / 1e6), error: run.error || run.encoderError || run.decoderError || (run.encoderSupported === false ? 'encoder not supported' : run.decoderSupported === false ? 'decoder not supported' : 'no result') }); + } + } + const f = (v, d = 2) => (v === undefined || v === null || Number.isNaN(v) ? '' : v.toFixed(d)); + for (const scene of SCENES) { + for (const size of Object.keys(SIZES)) { + const part = rows.filter((r) => r.scene === scene && r.size === size); + if (!part.length) continue; + // Each codec's rows follow the emberwave row nearest to its bytes. + part.sort((a, b) => a.bytes - b.bytes || a.order - b.order); + console.log(`\n${scene}, ${size}\n`); + console.log('| | asked Mbit/s | kB a frame (all) | kB after the key frame | Y dB | Cb dB | Cr dB | worst Y dB | key frame Y dB | decode ms | decode queue ms | encode ms |'); + console.log('|---|---|---|---|---|---|---|---|---|---|---|---|'); + for (const r of part) { + if (r.error) console.log(`| ${r.who} | ${r.asked ?? ''} | ${r.error} | | | | | | | | | |`); + else console.log(`| ${r.who} | ${r.asked ?? ''} | ${f(r.bytes / 1000, 1)} | ${f(r.steadyBytes / 1000, 1)} | ${f(r.y)} | ${f(r.cb)} | ${f(r.cr)} | ${f(r.yMin)} | ${f(r.key)} | ${f(r.decode)}${r.held ? ' (held)' : ''} | ${f(r.queue)} | ${f(r.encode)} |`); + } + } + } +} else if (command === 'summary') { + // The tables of BENCHMARKS.md: the encoders a host would use (the hardware + // ones, and AV1, which Chrome encodes in software only), each next to + // emberwave at the same bytes a frame. + const dir = resolve(positional[1] || join(root, 'target/chrome-codecs')); + const load = (f) => JSON.parse(readFileSync(join(dir, f), 'utf8')); + const files = readdirSync(dir).filter((f) => f.endsWith('.json') && !f.startsWith('probe') && !f.startsWith('emberwave')); + const order = { AV1: 0, HEVC: 1, 'H.264': 2 }; + const picked = files.map(load).filter((r) => r.hw === 'prefer-hardware' || r.name === 'AV1'); + picked.sort((a, b) => SCENES.indexOf(a.scene) - SCENES.indexOf(b.scene) || Object.keys(SIZES).indexOf(a.size) - Object.keys(SIZES).indexOf(b.size) || a.bitrate - b.bitrate || order[a.name] - order[b.name]); + const f = (v, d = 2) => (v === undefined || v === null || Number.isNaN(v) ? '' : v.toFixed(d)); + const failures = []; + for (const scene of SCENES) { + console.log(`\n${scene}\n`); + console.log('| Size | Codec | asked Mbit/s | kB a frame | codec Y dB | emberwave Y dB | codec Cb / Cr dB | emberwave Cb / Cr dB | decode ms | decode, queued ms |'); + console.log('|---|---|---|---|---|---|---|---|---|---|'); + for (const run of picked.filter((r) => r.scene === scene)) { + if (!run.psnr) { + failures.push(`${scene} ${run.size} ${run.name} ${Math.round(run.bitrate / 1e6)} Mbit/s: ${run.error || run.encoderError || run.decoderError || 'no result'}`); + continue; + } + const bytes = Math.round(mean(run.chunkBytes) / 50) * 50; + const match = load(`emberwave-${scene}-${run.size}-${bytes}.json`); + if (match.error) { failures.push(`${scene} ${run.size} ${run.name}: emberwave could not make frames of ${bytes} bytes`); continue; } + const steady = (rows) => rows.slice(1); + const ey = mean(steady(match.rows).map((r) => r.psnr[0])), ecb = mean(steady(match.rows).map((r) => r.psnr[1])), ecr = mean(steady(match.rows).map((r) => r.psnr[2])); + const cy = mean(steady(run.psnr).map((p) => p[0])), ccb = mean(steady(run.psnr).map((p) => p[1])), ccr = mean(steady(run.psnr).map((p) => p[2])); + console.log(`| ${run.size} | ${run.name} | ${Math.round(run.bitrate / 1e6)} | ${f(mean(run.chunkBytes) / 1000, 1)} | ${f(cy)} | ${f(ey)} | ${f(ccb)} / ${f(ccr)} | ${f(ecb)} / ${f(ecr)} | ${f(median(run.decodeMs.slice(1)))} | ${f(run.decodeQueueMsPerFrame)} |`); + } + } + if (failures.length) console.log('\nNot measured:\n' + failures.map((x) => `- ${x}`).join('\n')); +} else { + console.error('usage: chrome_codecs.mjs probe [SIZE] | run SIZE CODEC MBIT [--hw H] [--frames N] | all [--sizes S] [--codecs C] [--out DIR] | report [DIR] | summary [DIR]'); + process.exit(2); +} diff --git a/scripts/chrome_codecs/make_grainy.py b/scripts/chrome_codecs/make_grainy.py new file mode 100755 index 0000000..cb6feeb --- /dev/null +++ b/scripts/chrome_codecs/make_grainy.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""A harder copy of a benchmark Y4M: the same pictures with fresh noise in +every frame, as a stand-in for the grain and the dithering of a game's frames. + + scripts/chrome_codecs/make_grainy.py IN.y4m OUT.y4m [LUMA_SIGMA] + +The noise is Gaussian, seeded by the frame's number, with the standard +deviation LUMA_SIGMA (6 by default) on luma and half of it on chroma, added +to the 8-bit planes and clamped. A codec that predicts from the frame before +cannot predict it. Needs numpy. +""" +import sys + +import numpy as np + + +def main(): + source, target = sys.argv[1], sys.argv[2] + sigma = float(sys.argv[3]) if len(sys.argv) > 3 else 6.0 + with open(source, "rb") as src, open(target, "wb") as out: + header = src.readline() + out.write(header) + fields = dict((f[0], f[1:]) for f in header.decode().split()[1:]) + width, height = int(fields["W"]), int(fields["H"]) + luma = width * height + chroma = luma // 4 + index = 0 + while True: + line = src.readline() + if not line: + break + raw = src.read(luma + 2 * chroma) + if len(raw) < luma + 2 * chroma: + break + rng = np.random.default_rng(index) + planes = np.frombuffer(raw, dtype=np.uint8).astype(np.float32) + noise = np.empty_like(planes) + noise[:luma] = rng.normal(0.0, sigma, luma) + noise[luma:] = rng.normal(0.0, sigma / 2, 2 * chroma) + out.write(line) + out.write(np.clip(np.rint(planes + noise), 0, 255).astype(np.uint8).tobytes()) + index += 1 + print(f"{target}: {index} frames, sigma {sigma}") + + +if __name__ == "__main__": + main() diff --git a/scripts/chrome_codecs/page.html b/scripts/chrome_codecs/page.html new file mode 100644 index 0000000..2be4663 --- /dev/null +++ b/scripts/chrome_codecs/page.html @@ -0,0 +1,248 @@ + + +emberwave: Chrome's WebCodecs on a Y4M + + From 138aca596164338e4b468502dc4ccf9741e0c4cd Mon Sep 17 00:00:00 2001 From: harry Date: Wed, 18 Nov 2026 19:12:25 +0900 Subject: [PATCH 2/2] bench: time decoding without the copy, clean up Chrome, say what the data says A review of the Chrome comparison found that the "queued" decode time included the decoder's start and the key frame, that the frames were copied out while the one-at-a-time decode was timed, that the driver could leave Chrome and its profile behind (on a failed start, a signal, or a shutdown that raced the profile's writes) and could wait for a stuck page for good, and several sentences of BENCHMARKS.md and D67 that said more than the data. The page decodes three times now: one chunk at a time, timed, frames not copied; all at once, timed from the first frame out to the last; and once more with the frames copied out for the comparison. A decoder that fails keeps what the encoder made in the result. The driver gives every run a Chrome of its own in a process group that it ends, on a timeout and on SIGINT and SIGTERM too, serves only the Y4M files of testdata/generated, parses its flags (--force is a flag), and does not keep a failed run. The tables are measured again with it. The bytes and the PSNR of the 50 streams that ran twice agree exactly; the milliseconds do not, and say so. The text now gives the key frame's share of the bytes and that emberwave gets more bytes than the predicted frames cost, the scene's grain ceiling of about 46 dB, the chroma gap row by row, and each range from the new data. Claude-Session: https://claude.ai/code/session_019fJGoCTvP5e7n599q3ZQ42 --- ARCHITECTURE.md | 2 +- BENCHMARKS.md | 109 ++++---- scripts/chrome_codecs.mjs | 475 ++++++++++++++++++-------------- scripts/chrome_codecs/page.html | 127 +++++---- 4 files changed, 402 insertions(+), 311 deletions(-) diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 9a5aeea..4bc337f 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1717,7 +1717,7 @@ The last frame's detail, always, gains everything on a still picture and loses u - #136 is closed. Within its objective the encoder has under 1 % left, and measured by a metric of perceived quality, the objective itself has a few percent of bytes left. - If game footage of more than one frame, such as #82's, shows the chroma tilt's gain, the tilt goes into `gen_encoder_weights.py` as chroma's own sensitivity, for both encoders, and D57's measure keeps upstream's weights. - SSIMULACRA2 stays out of the repository. In `emberwave-cli quality` it would add a dependency, and its BSD-2-Clause notice to every release, for a study that ran once. -- **Follow-up of 2026-11-18 (#82, first stage).** Chrome's WebCodecs encoders, on synthetic pictures, say little about the tilt (BENCHMARKS.md, "Against AV1 and HEVC in Chrome"): at the same bytes emberwave's chroma PSNR sits further above its luma PSNR than that of AV1, HEVC and H.264 with predicted frames, 4.2 to 12.6 dB against 2.9 to 9.5 on the benchmark scene, which is the direction the tilt would move bits, but PSNR counts every band alike and the pictures are neither game footage nor perceptually measured. The weights stay upstream's; game footage and SSIMULACRA2 are still what would change that. +- **Follow-up of 2026-11-18 (#82, first stage).** Chrome's WebCodecs encoders, on synthetic pictures, say little about the tilt (BENCHMARKS.md, "Against AV1 and HEVC in Chrome"): at the same bytes emberwave's chroma PSNR sits further above its luma PSNR than that of AV1, HEVC and H.264 with predicted frames in most rows (Cb in 12 of 15 rows of the benchmark scene, 4.2 to 12.6 dB against 2.9 to 9.5, and in all 15 of its noisy copy; Cr in all 30), which is the direction the tilt would move bits, but PSNR counts every band alike, the scene's grain is in luma only, and the pictures are neither game footage nor perceptually measured. The weights stay upstream's; game footage and SSIMULACRA2 are still what would change that. ### 2026-10-31 — D68: The transforms read their rows straight from the bands diff --git a/BENCHMARKS.md b/BENCHMARKS.md index 27bab94..3681ba8 100644 --- a/BENCHMARKS.md +++ b/BENCHMARKS.md @@ -442,70 +442,71 @@ What a frame's budget buys, on a hard picture: a 4K frame of the game Crimson De ## Against AV1 and HEVC in Chrome (stand-in for NVENC) -Issue #82 asks for the streams of a PC's NVENC, HEVC and AV1, decoded beside emberwave's. This is its first stage, made on the Mac alone with the encoders that Chrome offers through WebCodecs: it says how emberwave compares in picture quality, bytes and decoding time with HEVC and AV1 with predicted frames at the same bytes a frame, without the PC and without game footage. NVENC's own streams, and moving game footage, are still to come, and the iPhone's half. +Issue #82 asks for the streams of a PC's NVENC, HEVC and AV1, decoded beside emberwave's. This is its first stage, made on the Mac alone with the encoders that Chrome offers through WebCodecs: it says how emberwave compares in picture quality, bytes and decoding time with HEVC, H.264 and AV1 with predicted frames at the same bytes a frame, without the PC and without game footage. NVENC's own streams and moving game footage are still to come, and the iPhone's half. -**How.** `scripts/chrome_codecs.mjs` drives headless Chrome over the DevTools protocol. A page encodes a Y4M with `VideoEncoder`, one frame at a time, in real-time mode at a constant bit rate, 60 frames a second, a key frame first and predicted frames after it, no B frames, then decodes the chunks with `VideoDecoder` (the hardware decoder where Chrome has one) and compares every decoded frame with its source in the page, plane by plane. emberwave encodes the same pictures with `emberwave-cli encode --gpu` at the bytes each Chrome stream used on average, and `emberwave-cli quality` measures it. Two bit rates a size: Moonlight's default for it (20, 40 and 80 Mbit/s for 1080p, 1440p and 4K at 60 frames a second), and the bit rate of emberwave's own budget (192, 336 and 576 Mbit/s). +**How.** `scripts/chrome_codecs.mjs` drives headless Chrome over the DevTools protocol, a Chrome for each run. A page encodes a Y4M with `VideoEncoder`, one frame at a time, in real-time mode at a constant bit rate, 60 frames a second, a key frame first and predicted frames after it, no B frames. It then decodes the chunks with `VideoDecoder` (the hardware decoder where Chrome has one) three times: one chunk at a time, which gives **decode ms**, the median time from handing a chunk over until its frame is out; all at once, which gives **queued**, the time from the first frame out to the last divided by the frames between them, so that the decoder's start and the key frame are not in it; and once more with the frames copied out, which is not timed and is what is compared with the source, plane by plane. emberwave encodes the same pictures with `emberwave-cli encode --gpu` at the bytes each Chrome stream used on average, and `emberwave-cli quality` measures it. Two bit rates a size: Moonlight's default for it (20, 40 and 80 Mbit/s for 1080p, 1440p and 4K at 60 frames a second), and the bit rate of emberwave's own budget (192, 336 and 576 Mbit/s). -**Pictures: synthetic, not game footage.** Twenty frames of the benchmark scene of the other tables (colour bars, a gradient, a moving shaded disc, a fine grid and a little grain; 78 % of its pixels change from one frame to the next, 30.9 dB between frames), and a copy with fresh Gaussian noise added to every frame, 6 levels on luma and 3 on chroma (`scripts/chrome_codecs/make_grainy.py`), which a codec that predicts cannot predict. Neither is a game. The scene's motion is easy to predict, which flatters the codecs with predicted frames; the grainy copy is the hard end. +**Pictures: synthetic, not game footage.** Twenty frames of the benchmark scene of the other tables (colour bars, a gradient, a moving shaded disc, a fine grid and grain that is fresh in every frame), and a copy with more fresh Gaussian noise added to every frame, 6 levels on luma and 3 on chroma (`scripts/chrome_codecs/make_grainy.py`), which a codec that predicts cannot predict. Neither is a game. The scene's motion is easy to predict, which flatters the codecs with predicted frames; the noisy copy is the hard end. Between two frames of the scene the luma changes by 30.9 to 43.2 dB of PSNR (33.7 on average), mostly the grain, which sets a ceiling: two neighbouring frames of it differ by a mean square of 3.1, a grain of about 1.25 levels, so a codec that predicts everything but the grain cannot pass about 46 dB. The noisy copy's changes are 27.2 to 29.4 dB, and its ceiling is 32.4 dB. -**What Chrome has.** Chrome 157.0.8103.79, headless, on the Mac of the tables above. It encodes AV1 in software only (and decodes it in hardware), HEVC and H.264 in hardware, through VideoToolbox, and in software. The hardware H.264 encoder returned no frames at 336 and 576 Mbit/s, the stream of the hardware HEVC encoder at 336 Mbit/s and 1440p could not be decoded ("EncodingError: Decoding error"), and the software H.264 encoder is refused at those rates; those rows are missing. VP9 was left out: NVENC does not encode it. +**What Chrome has.** Chrome 157.0.8103.79, headless, on the Mac of the tables above. It encodes AV1 in software only (and decodes it in hardware), HEVC and H.264 in hardware, through VideoToolbox, and in software. The hardware H.264 encoder returned no frames at 336 and 576 Mbit/s, the stream of the hardware HEVC encoder at 336 Mbit/s and 1440p could not be decoded, and the software H.264 encoder is refused at those rates; those rows are missing. VP9 was left out: NVENC does not encode it. -Measured on 2026-11-18 from 18:14 to 18:23 on the Apple M3 Max of the tables above, macOS 27.0.1, on mains power, with the load average at 5.0 to 7.7: other programs ran, and the Mac was not quiet. One run of each: repeat it before relying on a difference of a decibel. +Measured on 2026-11-18 on the Apple M3 Max of the tables above, macOS 27.0.1, on mains power, with the load average at 5 to 9 and other programs running, in two complete runs, 18:14 and 19:01 (the second, below, after a review of the harness changed how decoding is timed). The encoders gave the same bytes and the same pictures in both: the bytes and the PSNR of the 50 streams that ran in both agree exactly. The times do not: the median decode times of the two runs differ by 0.2 ms on average and up to 1.4 ms, so the milliseconds, which Chrome gives in steps of 0.1, need a repeat before a difference of a few tenths is read as one. -Each row is a Chrome stream and, beside it, emberwave at the same bytes a frame (the mean of all 20 frames, the key frame included, rounded to 50 bytes). **kB a frame** is that mean. **Y dB**, **Cb / Cr dB** are the PSNR of the 19 frames after the key frame, averaged. **Decode ms** is the median time from handing a chunk to `VideoDecoder` until its frame is out, one frame at a time, and **queued** is the time a frame takes when all 20 are handed over at once; the frame is not copied out in either. The run's HEVC and H.264 encoders are the hardware's, AV1's is software. +Each row is a Chrome stream and, beside it, emberwave at the same bytes a frame. **kB a frame** is the mean of all 20 frames, the key frame included, and what emberwave is given, rounded to 50 bytes; **after the key frame** is the mean of the other 19, which is what the predicted frames cost. The key frame is 12 to 89 % of the bytes of the stream, so emberwave's frames are 1.1 to 8.3 times the codecs' predicted frames in size (1.1 to 1.7 times on the noisy copy), and the comparison favours emberwave. **Y dB**, **Cb / Cr dB** are the PSNR of the 19 frames after the key frame, averaged. The run's HEVC and H.264 encoders are the hardware's, AV1's is software. ### The benchmark scene -| Size | Codec | asked Mbit/s | kB a frame | codec Y dB | emberwave Y dB | codec Cb / Cr dB | emberwave Cb / Cr dB | decode ms | decode, queued ms | -|---|---|---|---|---|---|---|---|---|---| -| 1080p | AV1 | 20 | 8.0 | 44.43 | 27.07 | 47.36 / 46.51 | 31.74 / 33.20 | 1.00 | 0.91 | -| 1080p | HEVC | 20 | 13.7 | 45.87 | 28.18 | 53.18 / 53.89 | 34.69 / 36.37 | 1.30 | 1.01 | -| 1080p | H.264 | 20 | 39.8 | 45.79 | 29.26 | 50.79 / 51.48 | 40.63 / 41.50 | 2.00 | 1.19 | -| 1080p | AV1 | 192 | 9.7 | 45.08 | 27.78 | 49.03 / 47.89 | 31.96 / 33.51 | 1.00 | 1.05 | -| 1080p | HEVC | 192 | 18.6 | 45.94 | 28.43 | 54.27 / 54.81 | 35.06 / 37.42 | 1.40 | 1.10 | -| 1080p | H.264 | 192 | 60.4 | 46.13 | 30.67 | 51.40 / 52.94 | 41.24 / 42.61 | 2.60 | 1.46 | -| 1440p | AV1 | 40 | 13.5 | 44.62 | 27.26 | 48.27 / 47.96 | 33.38 / 34.59 | 1.50 | 1.26 | -| 1440p | HEVC | 40 | 23.6 | 45.90 | 28.22 | 53.76 / 54.74 | 37.05 / 38.59 | 1.70 | 1.09 | -| 1440p | H.264 | 40 | 81.2 | 45.44 | 30.02 | 51.12 / 51.92 | 41.42 / 42.64 | 3.40 | 2.08 | -| 1440p | AV1 | 336 | 17.4 | 45.16 | 27.95 | 49.85 / 49.61 | 34.54 / 36.27 | 1.40 | 1.43 | -| 4k | AV1 | 80 | 29.1 | 44.50 | 27.38 | 48.14 / 48.10 | 34.07 / 35.35 | 2.40 | 2.73 | -| 4k | HEVC | 80 | 46.9 | 45.90 | 28.27 | 54.25 / 54.96 | 37.37 / 38.85 | 2.80 | 2.67 | -| 4k | H.264 | 80 | 160.5 | 45.57 | 29.73 | 51.71 / 52.69 | 42.33 / 43.60 | 5.90 | 3.80 | -| 4k | AV1 | 576 | 37.5 | 45.21 | 28.07 | 50.59 / 50.04 | 35.41 / 37.29 | 2.30 | 3.32 | -| 4k | HEVC | 576 | 65.9 | 45.97 | 28.55 | 55.51 / 56.24 | 38.06 / 39.46 | 2.90 | 2.85 | - -### The scene with fresh noise in every frame - -| Size | Codec | asked Mbit/s | kB a frame | codec Y dB | emberwave Y dB | codec Cb / Cr dB | emberwave Cb / Cr dB | decode ms | decode, queued ms | -|---|---|---|---|---|---|---|---|---|---| -| 1080p | AV1 | 20 | 42.2 | 32.28 | 27.64 | 37.71 / 37.77 | 36.47 / 36.91 | 1.80 | 1.39 | -| 1080p | HEVC | 20 | 55.7 | 32.70 | 28.26 | 37.94 / 37.99 | 36.73 / 37.02 | 1.10 | 0.94 | -| 1080p | H.264 | 20 | 56.7 | 32.43 | 28.32 | 37.71 / 37.83 | 36.73 / 37.02 | 1.60 | 1.51 | -| 1080p | AV1 | 192 | 173.6 | 33.96 | 29.68 | 38.23 / 38.29 | 37.16 / 37.55 | 2.40 | 3.61 | -| 1080p | HEVC | 192 | 418.0 | 37.87 | 33.86 | 39.13 / 39.14 | 38.80 / 38.70 | 4.00 | 1.68 | -| 1080p | H.264 | 192 | 416.4 | 37.59 | 33.85 | 38.95 / 38.98 | 38.80 / 38.70 | 7.40 | 3.42 | -| 1440p | AV1 | 40 | 85.6 | 32.41 | 28.16 | 37.97 / 38.02 | 36.81 / 37.18 | 2.60 | 2.47 | -| 1440p | HEVC | 40 | 115.6 | 32.81 | 28.83 | 38.04 / 38.09 | 36.97 / 37.36 | 1.80 | 1.56 | -| 1440p | H.264 | 40 | 120.0 | 32.53 | 28.93 | 37.76 / 37.90 | 36.97 / 37.36 | 2.70 | 2.49 | -| 1440p | AV1 | 336 | 290.6 | 33.87 | 29.67 | 38.27 / 38.31 | 37.29 / 37.65 | 3.90 | 6.27 | -| 4k | AV1 | 80 | 168.9 | 32.41 | 27.98 | 37.98 / 38.08 | 37.04 / 37.34 | 5.00 | 5.90 | -| 4k | HEVC | 80 | 217.4 | 32.71 | 28.51 | 38.06 / 38.11 | 37.11 / 37.55 | 3.50 | 3.35 | -| 4k | H.264 | 80 | 224.7 | 32.43 | 28.60 | 37.78 / 37.91 | 37.11 / 37.55 | 4.50 | 4.95 | -| 4k | AV1 | 576 | 723.6 | 34.20 | 29.83 | 38.47 / 38.51 | 37.58 / 37.83 | 11.80 | 15.39 | -| 4k | HEVC | 576 | 1259.5 | 36.37 | 33.27 | 38.68 / 38.69 | 38.22 / 38.20 | 12.60 | 5.41 | - -- **The encoders do not fill the rate they are asked for on the scene.** At Moonlight's rates a 1080p stream came to 3.8 Mbit/s with AV1, 6.6 with HEVC and 19.1 with H.264 against 20 asked; at 4K 14.0, 22.5 and 77.0 against 80. Real-time mode keeps to a quality ceiling, and a scene that predicts well needs few bytes. The rows are compared at the bytes they used, not the rates they were asked for. -- **At the same bytes the codecs with predicted frames lead in PSNR.** On the scene by 15.4 to 17.7 dB of luma, on the noisy copy by 3.1 to 4.6 dB, at every size and rate that ran. The scene's motion is easy to predict: the codecs hold 44.0 to 46.1 dB of luma on it from 8 kB to 160 kB a frame, where emberwave needs 400 kB for 46.8 dB at 1080p. The noisy copy leaves the codecs only the noise to code, and they lead by about 4 dB. The earlier comparison on a single key frame of a game, [above](#picture-quality), had HEVC 1.9 to 3.5 dB ahead of emberwave on luma with 2 to 10 % fewer bytes, where nothing could be predicted: the lead here is the prediction's. -- **That is what emberwave trades for.** Every frame of it stands alone, so a lost frame costs nothing after it, a decode needs no earlier frame, and the GPU encoder takes 0.8 to 1.9 ms a frame on this Mac ([encoding above](#results)) where Chrome's hardware encoders took 6 ms at 1080p and 22 to 24 ms at 4K and its software HEVC encoder 112 to 606 ms. The table does not say what the codecs' lead is worth to a viewer: PSNR counts every pixel alike, the pictures are synthetic, and the encoders were in real-time mode. -- **Decoding in Chrome.** At Moonlight's rates a frame took 1.0 to 5.9 ms to come out of `VideoDecoder`, 2.4 to 2.8 ms at 4K with AV1 and HEVC and 5.9 ms with H.264; at emberwave's bytes it took up to 12.6 ms (4K, HEVC, the noisy copy). emberwave's own decode in earlier Chrome versions on this Mac, through WebGPU, took 0.70 to 1.00 ms at 1080p and 1.69 to 1.88 ms at 4K into an RGB texture, frame after frame ([In the browser](#in-the-browser-phones-included)), and 4.50 to 5.67 ms at 4K at a stream's pace. The two do different work: `VideoDecoder`'s hardware decoders run beside the GPU and hand over video frames that are not yet drawn, and the page measures the time to the frame, not to the screen. -- **For D67's chroma weights these numbers say little.** At the same bytes emberwave's chroma PSNR sits further above its luma PSNR (4.2 to 12.6 dB on the scene, 4.9 to 9.1 on the noisy copy) than the codecs' (2.9 to 9.5, 1.3 to 5.6). That is the direction in which D67's tilt would move bits at low budgets, from chroma to luma, but PSNR counts every band alike and the pictures are synthetic, with the chroma of bars and a gradient and noise that is the same in both up to its scale. Game footage and a perceptual metric are what D67 asks for; the weights stay upstream's. -- **Not measured.** NVENC's own streams, which differ from VideoToolbox's and libaom's; moving game footage; a second run; the iPhone; the rows listed below. +| Size | Codec | asked Mbit/s | kB a frame | kB after the key frame | codec Y dB | emberwave Y dB | codec Cb / Cr dB | emberwave Cb / Cr dB | decode ms | decode, queued ms | +|---|---|---|---|---|---|---|---|---|---|---| +| 1080p | AV1 | 20 | 8.0 | 3.5 | 44.43 | 27.07 | 47.36 / 46.51 | 31.74 / 33.20 | 1.00 | 0.38 | +| 1080p | HEVC | 20 | 13.7 | 9.6 | 45.87 | 28.18 | 53.18 / 53.89 | 34.69 / 36.37 | 0.90 | 0.35 | +| 1080p | H.264 | 20 | 39.8 | 36.4 | 45.79 | 29.26 | 50.79 / 51.48 | 40.63 / 41.50 | 1.60 | 0.48 | +| 1080p | AV1 | 192 | 9.7 | 1.2 | 45.08 | 27.78 | 49.03 / 47.89 | 31.96 / 33.51 | 1.00 | 0.40 | +| 1080p | HEVC | 192 | 18.6 | 9.5 | 45.94 | 28.43 | 54.27 / 54.81 | 35.06 / 37.42 | 1.10 | 0.36 | +| 1080p | H.264 | 192 | 60.4 | 51.5 | 46.13 | 30.67 | 51.40 / 52.94 | 41.24 / 42.61 | 2.20 | 0.55 | +| 1440p | AV1 | 40 | 13.5 | 5.2 | 44.62 | 27.26 | 48.27 / 47.96 | 33.38 / 34.59 | 1.30 | 0.60 | +| 1440p | HEVC | 40 | 23.6 | 15.9 | 45.90 | 28.22 | 53.76 / 54.74 | 37.05 / 38.59 | 1.60 | 0.56 | +| 1440p | H.264 | 40 | 81.2 | 75.2 | 45.44 | 30.02 | 51.12 / 51.92 | 41.42 / 42.64 | 3.20 | 0.88 | +| 1440p | AV1 | 336 | 17.4 | 2.8 | 45.16 | 27.95 | 49.85 / 49.61 | 34.54 / 36.27 | 1.20 | 0.59 | +| 4k | AV1 | 80 | 29.1 | 12.0 | 44.50 | 27.38 | 48.14 / 48.10 | 34.07 / 35.35 | 2.10 | 1.39 | +| 4k | HEVC | 80 | 46.9 | 30.7 | 45.90 | 28.27 | 54.25 / 54.96 | 37.37 / 38.85 | 2.60 | 1.22 | +| 4k | H.264 | 80 | 160.5 | 147.7 | 45.57 | 29.73 | 51.71 / 52.69 | 42.33 / 43.60 | 5.30 | 1.93 | +| 4k | AV1 | 576 | 37.5 | 5.4 | 45.21 | 28.07 | 50.59 / 50.04 | 35.41 / 37.29 | 2.00 | 1.35 | +| 4k | HEVC | 576 | 65.9 | 30.4 | 45.97 | 28.55 | 55.51 / 56.24 | 38.06 / 39.46 | 2.70 | 1.34 | + +### The scene with more noise in every frame + +| Size | Codec | asked Mbit/s | kB a frame | kB after the key frame | codec Y dB | emberwave Y dB | codec Cb / Cr dB | emberwave Cb / Cr dB | decode ms | decode, queued ms | +|---|---|---|---|---|---|---|---|---|---|---| +| 1080p | AV1 | 20 | 42.2 | 33.2 | 32.28 | 27.64 | 37.71 / 37.77 | 36.47 / 36.91 | 1.50 | 0.80 | +| 1080p | HEVC | 20 | 55.7 | 33.1 | 32.70 | 28.26 | 37.94 / 37.99 | 36.73 / 37.02 | 1.20 | 0.43 | +| 1080p | H.264 | 20 | 56.7 | 33.9 | 32.43 | 28.32 | 37.71 / 37.83 | 36.73 / 37.02 | 1.30 | 0.48 | +| 1080p | AV1 | 192 | 173.6 | 143.0 | 33.96 | 29.68 | 38.23 / 38.29 | 37.16 / 37.55 | 2.20 | 2.92 | +| 1080p | HEVC | 192 | 418.0 | 388.5 | 37.87 | 33.86 | 39.13 / 39.14 | 38.80 / 38.70 | 4.20 | 1.08 | +| 1080p | H.264 | 192 | 416.4 | 385.7 | 37.59 | 33.85 | 38.95 / 38.98 | 38.80 / 38.70 | 7.10 | 2.16 | +| 1440p | AV1 | 40 | 85.6 | 66.0 | 32.41 | 28.16 | 37.97 / 38.02 | 36.81 / 37.18 | 2.40 | 1.62 | +| 1440p | HEVC | 40 | 115.6 | 71.1 | 32.81 | 28.83 | 38.04 / 38.09 | 36.97 / 37.36 | 1.60 | 0.77 | +| 1440p | H.264 | 40 | 120.0 | 73.2 | 32.53 | 28.93 | 37.76 / 37.90 | 36.97 / 37.36 | 2.50 | 1.06 | +| 1440p | AV1 | 336 | 290.6 | 235.8 | 33.87 | 29.67 | 38.27 / 38.31 | 37.29 / 37.65 | 4.00 | 5.00 | +| 4k | AV1 | 80 | 168.9 | 134.1 | 32.41 | 27.98 | 37.98 / 38.08 | 37.04 / 37.34 | 4.70 | 3.55 | +| 4k | HEVC | 80 | 217.4 | 128.4 | 32.71 | 28.51 | 38.06 / 38.11 | 37.11 / 37.55 | 3.20 | 1.48 | +| 4k | H.264 | 80 | 224.7 | 134.9 | 32.43 | 28.60 | 37.78 / 37.91 | 37.11 / 37.55 | 4.20 | 1.89 | +| 4k | AV1 | 576 | 723.6 | 604.6 | 34.20 | 29.83 | 38.47 / 38.51 | 37.58 / 37.83 | 11.50 | 12.27 | +| 4k | HEVC | 576 | 1259.5 | 1121.4 | 36.37 | 33.27 | 38.68 / 38.69 | 38.22 / 38.20 | 12.60 | 3.09 | + +- **The encoders do not fill the rate they are asked for on the scene.** At Moonlight's rates a 1080p stream came to 3.8 Mbit/s with AV1, 6.6 with HEVC and 19.1 with H.264 against 20 asked, and only 1.7, 4.6 and 17.5 after the key frame; at 4K 14.0, 22.5 and 77.0 against 80. A scene that predicts well needs few bytes, and these encoders do not spend what they are not asked for. On the noisy copy they came to the rate or above it (20.2 to 27.2 Mbit/s at 1080p, up to 107.8 at 4K against 80). The rows are compared at the bytes they used, not the rates they were asked for. +- **At the same bytes the codecs with predicted frames lead in PSNR.** On the scene by 15.4 to 17.7 dB of luma, on the noisy copy by 3.1 to 4.6 dB, at every size and rate that ran, with emberwave given more bytes than the predicted frames cost. On the scene the codecs sit at 44.4 to 46.1 dB, at the ceiling that the scene's grain sets, from 8 kB a frame on (3.5 kB after the key frame); emberwave needs 400 kB a 1080p frame to reach 46.8 dB. The noisy copy leaves the codecs only the noise to code, and they lead by about 4 dB. The earlier comparison on a single key frame of a game, [above](#picture-quality), had HEVC 1.9 to 3.5 dB ahead of emberwave on luma with 2 to 10 % fewer bytes, where nothing could be predicted: the lead here is the prediction's. +- **That is what emberwave trades for.** Every frame of it stands alone, so a lost frame costs nothing after it and a decode needs no earlier frame, and the GPU encoder takes 0.8 to 1.9 ms a frame on this Mac ([encoding above](#results)) where Chrome's encoders took 6 to 9 ms at 1080p and 21 to 24 ms at 4K with the hardware ones, 1.9 to 17 ms with its software AV1 and H.264 encoders in real-time mode, and 114 to 610 ms with its software HEVC encoder. The table does not say what the codecs' lead is worth to a viewer: PSNR counts every pixel alike, the pictures are synthetic, and the encoders were in real-time mode. +- **Decoding in Chrome.** At Moonlight's rates a frame took 0.9 to 5.3 ms to come out of `VideoDecoder` one at a time on the scene, and 1.2 to 4.7 ms on the noisy copy, with all frames at once 0.4 to 1.9 and 0.4 to 3.6 ms; at emberwave's bytes, 1.0 to 2.7 ms on the scene and 2.2 to 12.6 ms on the noisy copy. emberwave's own decode in earlier Chrome versions on this Mac, through WebGPU, took 0.70 to 1.00 ms at 1080p and 1.69 to 1.88 ms at 4K into an RGB texture, frame after frame ([In the browser](#in-the-browser-phones-included)), and 4.50 to 5.67 ms at 4K at a stream's pace. The two do different work: `VideoDecoder`'s hardware decoders run beside the GPU and hand over video frames that are not yet drawn, and the page measures the time to the frame, not to the screen. +- **For D67's chroma weights these numbers say little.** At the same bytes emberwave's chroma PSNR sits further above its luma PSNR than the codecs' in most rows: Cb in 12 of the 15 rows of the scene and all 15 of the noisy copy, Cr in all 30. On the scene the gap of Cb over luma is 4.2 to 12.6 dB for emberwave and 2.9 to 9.5 for the codecs, on the noisy copy 4.9 to 9.1 against 1.3 to 5.6; HEVC at 1080p is the exception on the scene (6.5 and 6.6 dB against 7.3 and 8.3). That is the direction in which D67's tilt would move bits at low budgets, from chroma to luma. But PSNR counts every band alike, the scene's grain is in luma only, which widens every codec's gap, and the pictures are synthetic, with the chroma of bars and a gradient: this is not evidence that the tilt is worth it. Game footage and a perceptual metric are what D67 asks for; the weights stay upstream's. +- **Not measured.** NVENC's own streams, which differ from VideoToolbox's and libaom's; moving game footage; the iPhone; that AV1 decoded in hardware (the page asks for it, and Chrome does not say); the rows listed below. Rows that did not run: -- scene 1440p HEVC 336 Mbit/s: EncodingError: Decoding error. + +- scene 1440p HEVC 336 Mbit/s: its stream could not be decoded: EncodingError: Decoding error. - scene 1440p H.264 336 Mbit/s: 0 chunks for 20 frames - scene 4k H.264 576 Mbit/s: 0 chunks for 20 frames -- grainy 1440p HEVC 336 Mbit/s: EncodingError: Decoding error. +- grainy 1440p HEVC 336 Mbit/s: its stream could not be decoded: EncodingError: Decoding error. - grainy 1440p H.264 336 Mbit/s: 0 chunks for 20 frames - grainy 4k H.264 576 Mbit/s: 0 chunks for 20 frames @@ -513,8 +514,8 @@ Rows that did not run: scripts/gen_bench_data.sh --sources # the scene's pictures, once for s in 1080p 1440p 4k; do scripts/chrome_codecs/make_grainy.py testdata/generated/scene_${s}_420.y4m testdata/generated/grainy_${s}_420.y4m; done cargo build --release -p emberwave-cli -node scripts/chrome_codecs.mjs all # about 8 minutes; writes target/chrome-codecs/*.json +node scripts/chrome_codecs.mjs all # about 10 minutes; writes target/chrome-codecs/*.json node scripts/chrome_codecs.mjs summary # the tables above; `report` lists every run ``` -It needs Google Chrome, Node 20 or later and numpy. Chrome runs with a mock keychain and a profile of its own, and its page is served on 127.0.0.1 only. +It needs Google Chrome (the `CHROME` variable names another binary), Node 20 or later and numpy. Every run has a Chrome of its own, with a mock keychain and a profile of its own, and its page is served on 127.0.0.1 only; Chrome and its profile are removed at the end of the run, when it times out, and on SIGINT and SIGTERM. diff --git a/scripts/chrome_codecs.mjs b/scripts/chrome_codecs.mjs index f674dcf..0e50860 100755 --- a/scripts/chrome_codecs.mjs +++ b/scripts/chrome_codecs.mjs @@ -3,27 +3,41 @@ // the codecs this Chrome has, decodes the streams again, and compares picture // quality, size and time with emberwave's frames of the same size. // -// node scripts/chrome_codecs.mjs probe [1080p|1440p|4k] -// node scripts/chrome_codecs.mjs run SIZE CODEC MBIT [--hw H] [--frames N] -// node scripts/chrome_codecs.mjs all [--sizes 1080p,1440p,4k] [--out DIR] -// node scripts/chrome_codecs.mjs report [DIR] every run -// node scripts/chrome_codecs.mjs summary [DIR] the tables of BENCHMARKS.md +// node scripts/chrome_codecs.mjs probe [1080p|1440p|4k] +// node scripts/chrome_codecs.mjs run SIZE CODEC MBIT [options] +// node scripts/chrome_codecs.mjs all [options] +// node scripts/chrome_codecs.mjs report [DIR] every run, one table a scene and size +// node scripts/chrome_codecs.mjs summary [DIR] the tables of BENCHMARKS.md // -// `all` writes one JSON file per run into DIR (target/chrome-codecs by -// default), `report` turns those into the tables of BENCHMARKS.md. It needs -// Google Chrome, Node 20 or later with --experimental-websocket (the script -// re-runs itself with the flag), the Y4M files of scripts/gen_bench_data.sh -// --sources in testdata/generated, and a release build of emberwave-cli. +// Options: +// run: CODEC is a WebCodecs codec string (av01.0.08M.08, hvc1.1.6.L123.B0, +// avc1.640028); --hw no-preference|prefer-hardware|prefer-software for +// the encoder; --decode-hw for the decoder (default: as --hw; HEVC has +// no software decoder in Chrome); --scene scene|grainy; --frames N; +// --name LABEL +// all: --sizes 1080p,1440p,4k --scenes scene,grainy --codecs AV1,HEVC,H.264 +// --out DIR (default target/chrome-codecs) --force (rerun what is +// there) --timeout MINUTES (a run's longest time, default 15) // -// Chrome runs headless, with a mock keychain and a profile of its own, and its -// page is served on 127.0.0.1 only, so that nothing asks the user for a -// permission. Everything it starts is stopped at the end. +// `all` writes one JSON file per run into DIR and, beside them, emberwave's +// results at the bytes each Chrome stream used; `summary` and `report` read +// them. It needs Google Chrome (CHROME names another binary than the macOS +// default), Node 20 or later (the script starts itself again with +// --experimental-websocket), the Y4M files of scripts/gen_bench_data.sh +// --sources and of scripts/chrome_codecs/make_grainy.py in testdata/generated, +// and a release build of emberwave-cli. +// +// Every run has a Chrome of its own: headless, with a mock keychain and a +// profile of its own, its page served on 127.0.0.1 only, so that nothing asks +// the user for a permission and a codec that hangs or crashes ends one run. +// Chrome, its server and its profile are removed at the end of the run, when +// the run times out, and on SIGINT and SIGTERM. import { spawn, spawnSync } from 'node:child_process'; import { createServer } from 'node:http'; import { createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; -import { dirname, join, resolve } from 'node:path'; +import { dirname, join, resolve, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; const root = resolve(dirname(fileURLToPath(import.meta.url)), '..'); @@ -37,25 +51,53 @@ const SIZES = { '1440p': { moonlight: 40, emberwaveBytes: 700_000 }, '4k': { moonlight: 80, emberwaveBytes: 1_200_000 }, }; +const DIMS = { '1080p': [1920, 1080], '1440p': [2560, 1440], '4k': [3840, 2160] }; // The pictures: the benchmark scene (scripts/gen_bench_data.sh --sources), and // a copy of it with fresh noise in every frame (chrome_codecs/make_grainy.py). const SCENES = ['scene', 'grainy']; -const sceneFile = (scene, size) => `${scene}_${size}_420.y4m`; const FRAMERATE = 60; +const BOOLEAN_OPTIONS = new Set(['force']); if (typeof WebSocket === 'undefined') { const again = spawnSync(process.execPath, ['--experimental-websocket', ...process.argv.slice(1)], { stdio: 'inherit' }); process.exit(again.status ?? 1); } -// A static server on loopback: the page and the Y4M files. -function serve(directory) { +const dataDir = join(root, 'testdata/generated'); +const sceneFile = (scene, size) => `${scene}_${size}_420.y4m`; +const sizeInfo = (name) => { + const info = SIZES[name.toLowerCase()]; + if (!info) throw new Error(`unknown size ${name}: 1080p, 1440p or 4k`); + return info; +}; +const mean = (values) => values.reduce((a, b) => a + b, 0) / values.length; +const median = (values) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]; + +// What is running, so that a signal can end it. +const cleanups = new Set(); +for (const signal of ['SIGINT', 'SIGTERM']) { + process.on(signal, async () => { + for (const cleanup of [...cleanups]) await cleanup(); + process.exit(130); + }); +} + +// A static server on loopback: the page and the Y4M files, nothing else. +function serve() { const server = createServer((request, response) => { - const path = decodeURIComponent(new URL(request.url, 'http://x').pathname); let file = null; - if (path === '/' || path === '/page.html') file = join(root, 'scripts/chrome_codecs/page.html'); - else if (path.startsWith('/data/')) file = join(directory, path.slice(6)); - if (!file || file.includes('..') || !existsSync(file)) { + try { + const path = decodeURIComponent(new URL(request.url, 'http://x').pathname); + if (path === '/' || path === '/page.html') { + file = join(root, 'scripts/chrome_codecs/page.html'); + } else if (path.startsWith('/data/')) { + const candidate = resolve(dataDir, path.slice(6)); + if (candidate.startsWith(dataDir + sep) && candidate.endsWith('.y4m')) file = candidate; + } + } catch { + file = null; + } + if (!file || !existsSync(file)) { response.writeHead(404).end(); return; } @@ -65,266 +107,295 @@ function serve(directory) { return new Promise((done) => server.listen(0, '127.0.0.1', () => done(server))); } -// Chrome, headless, and a DevTools connection to a page. +// Chrome, headless, with a DevTools connection to a page. Everything it starts +// is ended by `close`, whatever fails after the start. async function launch(url) { const profile = mkdtempSync(join(tmpdir(), 'emberwave-chrome-')); - const chrome = spawn(CHROME, [ - '--headless=new', '--use-mock-keychain', '--password-store=basic', `--user-data-dir=${profile}`, - '--remote-debugging-port=0', '--no-first-run', '--no-default-browser-check', '--disable-extensions', - '--autoplay-policy=no-user-gesture-required', - // The page is never in front: do not let Chrome slow its timers or its tasks down. - '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows', - 'about:blank', - ], { stdio: ['ignore', 'ignore', 'pipe'] }); - const version = await new Promise((done, fail) => { - let text = ''; - chrome.stderr.on('data', (chunk) => { - text += chunk; - const match = /DevTools listening on (ws:\/\/\S+)/.exec(text); - if (match) done(match[1]); - }); - chrome.on('exit', () => fail(new Error('Chrome ended before it listened'))); - setTimeout(() => fail(new Error('Chrome did not start')), 30000); - }); - const port = new URL(version).port; - const target = await (await fetch(`http://127.0.0.1:${port}/json/new?${url}`, { method: 'PUT' })).json(); - const socket = new WebSocket(target.webSocketDebuggerUrl); - await new Promise((done, fail) => { socket.onopen = done; socket.onerror = fail; }); - let id = 0; - const waiting = new Map(); - socket.onmessage = (message) => { - const data = JSON.parse(message.data); - if (data.id && waiting.has(data.id)) { - waiting.get(data.id)(data); - waiting.delete(data.id); + let chrome = null; + let socket = null; + let closing = null; + const failPending = []; + // Every call waits for the one that does the work: a failure that comes of + // closing must not end the process before the profile is gone. + const close = () => { closing ??= closeNow(); return closing; }; + const closeNow = async () => { + cleanups.delete(close); + for (const fail of failPending) fail(new Error('Chrome was closed')); + try { socket?.close(); } catch { /* already closed */ } + if (chrome && chrome.exitCode === null) { + const ended = new Promise((done) => chrome.once('exit', done)); + // Chrome is a tree of processes: end the group it leads. + try { process.kill(-chrome.pid, 'SIGTERM'); } catch { chrome.kill('SIGTERM'); } + const killer = setTimeout(() => { try { process.kill(-chrome.pid, 'SIGKILL'); } catch { /* gone */ } }, 5000); + await ended; + clearTimeout(killer); } + // Its helpers write to the profile until they have ended: try again. + for (let attempt = 0; attempt < 20; attempt++) { + try { + rmSync(profile, { recursive: true, force: true }); + return; + } catch { + await new Promise((r) => setTimeout(r, 300)); + } + } + console.error(`could not remove ${profile}`); }; - const send = (method, params = {}) => new Promise((done) => { - waiting.set(++id, done); - socket.send(JSON.stringify({ id, method, params })); - }); - const evaluate = async (expression) => { - const reply = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true, timeout: 3_600_000 }); - if (reply.error) throw new Error(JSON.stringify(reply.error)); - if (reply.result.exceptionDetails) throw new Error(reply.result.exceptionDetails.exception?.description || JSON.stringify(reply.result.exceptionDetails)); - return reply.result.result.value; - }; - // Chrome writes to its profile until it has ended: wait for it, then remove it. - const close = async () => { - try { socket.close(); } catch { /* already closed */ } - const ended = new Promise((done) => chrome.once('exit', done)); - chrome.kill('SIGTERM'); - const killer = setTimeout(() => chrome.kill('SIGKILL'), 5000); - await ended; - clearTimeout(killer); - rmSync(profile, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 }); - }; - return { evaluate, close }; + cleanups.add(close); + try { + chrome = spawn(CHROME, [ + '--headless=new', '--use-mock-keychain', '--password-store=basic', `--user-data-dir=${profile}`, + '--remote-debugging-port=0', '--no-first-run', '--no-default-browser-check', '--disable-extensions', + '--autoplay-policy=no-user-gesture-required', + // The page is never in front: do not let Chrome slow its timers or its tasks down. + '--disable-background-timer-throttling', '--disable-renderer-backgrounding', '--disable-backgrounding-occluded-windows', + 'about:blank', + ], { stdio: ['ignore', 'ignore', 'pipe'], detached: true }); + const listening = await new Promise((done, fail) => { + let text = ''; + const timer = setTimeout(() => fail(new Error('Chrome did not start in 30 s')), 30000); + chrome.on('error', (error) => { clearTimeout(timer); fail(error); }); + chrome.on('exit', () => { clearTimeout(timer); fail(new Error('Chrome ended before it listened')); }); + chrome.stderr.on('data', (chunk) => { + text += chunk; + const match = /DevTools listening on (ws:\/\/\S+)/.exec(text); + if (match) { clearTimeout(timer); done(match[1]); } + }); + }); + const port = new URL(listening).port; + const target = await (await fetch(`http://127.0.0.1:${port}/json/new?${url}`, { method: 'PUT' })).json(); + socket = new WebSocket(target.webSocketDebuggerUrl); + await new Promise((done, fail) => { socket.onopen = done; socket.onerror = fail; }); + let id = 0; + const waiting = new Map(); + socket.onmessage = (message) => { + const data = JSON.parse(message.data); + if (data.id && waiting.has(data.id)) { + waiting.get(data.id)(data); + waiting.delete(data.id); + } + }; + socket.onclose = () => { for (const fail of failPending) fail(new Error('the DevTools connection closed')); }; + // Evaluates an expression and waits for its promise, for at most `ms`. + const evaluate = (expression, ms) => new Promise((done, fail) => { + failPending.push(fail); + const timer = ms ? setTimeout(() => fail(new Error(`no answer in ${Math.round(ms / 60000)} minutes`)), ms) : null; + waiting.set(++id, (reply) => { + clearTimeout(timer); + if (reply.error) fail(new Error(JSON.stringify(reply.error))); + else if (reply.result.exceptionDetails) fail(new Error(reply.result.exceptionDetails.exception?.description || JSON.stringify(reply.result.exceptionDetails))); + else done(reply.result.result.value); + }); + socket.send(JSON.stringify({ id, method: 'Runtime.evaluate', params: { expression, awaitPromise: true, returnByValue: true } })); + }); + return { evaluate, close }; + } catch (error) { + await close(); + throw error; + } } -async function withPage(directory, body) { - const server = await serve(directory); - const page = await launch(`http://127.0.0.1:${server.address().port}/page.html`); +// A page of its own for `body`, on a server of its own. +async function withPage(body) { + const server = await serve(); + let page = null; try { - for (let i = 0; i < 100 && !(await page.evaluate('window.ready === true')); i++) await new Promise((r) => setTimeout(r, 100)); - return await body(page, `http://127.0.0.1:${server.address().port}/data/`); + const base = `http://127.0.0.1:${server.address().port}`; + page = await launch(`${base}/page.html`); + for (let i = 0; i < 100 && !(await page.evaluate('window.ready === true', 5000)); i++) await new Promise((r) => setTimeout(r, 100)); + return await body(page, `${base}/data/`); } finally { - await page.close(); + await page?.close(); server.close(); } } -const dataDir = join(root, 'testdata/generated'); -const sizeInfo = (name) => { - const info = SIZES[name.toLowerCase()]; - if (!info) throw new Error(`unknown size ${name}: 1080p, 1440p or 4k`); - return info; -}; -const dims = { '1080p': [1920, 1080], '1440p': [2560, 1440], '4k': [3840, 2160] }; - // emberwave on the same pictures at a number of bytes per frame: the CLI // encodes (on the GPU: the CPU's bytes are the same up to a few blocks) and -// `quality` compares each frame with the source. +// `quality` compares each frame with the source. A budget the pictures' size +// does not allow is a result; a CLI that is missing or cannot run is not. function emberwave(scene, size, bytesPerFrame, frames, work) { const input = join(dataDir, sceneFile(scene, size)); const stream = join(work, `emberwave-${scene}-${size}-${bytesPerFrame}.pwv1`); const encode = spawnSync(CLI, ['encode', input, '--out', stream, '--bytes-per-frame', String(bytesPerFrame), '--frames', String(frames), '--gpu'], { encoding: 'utf8' }); - if (encode.status !== 0) throw new Error(`emberwave-cli encode: ${encode.stderr}`); + if (encode.status === null) throw new Error(`emberwave-cli did not run: ${encode.error?.message || encode.signal}`); + if (encode.status !== 0) return { name: 'emberwave', scene, size, bytesPerFrame, error: `emberwave-cli encode: ${encode.stderr.trim().slice(0, 200)}` }; const quality = spawnSync(CLI, ['quality', input, stream, '--frames', String(frames)], { encoding: 'utf8' }); - if (quality.status !== 0) throw new Error(`emberwave-cli quality: ${quality.stderr}`); + if (quality.status !== 0) throw new Error(`emberwave-cli quality: ${quality.stderr || quality.error?.message}`); const rows = []; for (const line of quality.stdout.split('\n')) { const m = /^frame\s+(\d+):\s+(\d+) bytes\s+Y\s+([\d.]+) dB\s+Cb\s+([\d.]+) dB\s+Cr\s+([\d.]+) dB/.exec(line); if (m) rows.push({ bytes: Number(m[2]), psnr: [Number(m[3]), Number(m[4]), Number(m[5])] }); } + if (rows.length !== frames) throw new Error(`emberwave-cli quality gave ${rows.length} frames, not ${frames}`); return { name: 'emberwave', scene, size, bytesPerFrame, rows }; } -const mean = (values) => values.reduce((a, b) => a + b, 0) / values.length; -const median = (values) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]; - function parseArgs(argv) { const positional = []; const options = {}; for (let i = 0; i < argv.length; i++) { - if (argv[i].startsWith('--')) options[argv[i].slice(2)] = argv[++i]; - else positional.push(argv[i]); + if (!argv[i].startsWith('--')) positional.push(argv[i]); + else if (BOOLEAN_OPTIONS.has(argv[i].slice(2))) options[argv[i].slice(2)] = true; + else options[argv[i].slice(2)] = argv[++i]; } return { positional, options }; } +// Why a run has no picture quality. +function failure(run) { + if (run.error) return run.error; + if (run.encoderError) return `encoder: ${run.encoderError}`; + if (run.decoderError) return `its stream could not be decoded: ${run.decoderError}`; + if (run.encoderSupported === false) return 'encoder not supported'; + if (run.decoderSupported === false) return 'decoder not supported'; + return 'no result'; +} + +const f = (v, d = 2) => (v === undefined || v === null || Number.isNaN(v) ? '' : v.toFixed(d)); const { positional, options } = parseArgs(process.argv.slice(2)); const command = positional[0]; +const timeoutMs = Number(options.timeout || 15) * 60000; if (command === 'probe') { const size = (positional[1] || '1080p').toLowerCase(); - const [width, height] = dims[size]; - const result = await withPage(dataDir, (page) => page.evaluate(`window.probe(${width}, ${height}, ${sizeInfo(size).moonlight * 1e6}, ${FRAMERATE})`)); + const [width, height] = DIMS[size]; + const result = await withPage((page) => page.evaluate(`window.probe(${width}, ${height}, ${sizeInfo(size).moonlight * 1e6}, ${FRAMERATE})`, 60000)); console.log(JSON.stringify(result, null, 2)); } else if (command === 'run') { const [size, codec, mbit] = positional.slice(1); + if (!size || !codec || !mbit) throw new Error('run SIZE CODEC MBIT'); const hw = options.hw || 'no-preference'; - const frames = Number(options.frames || 20); - const result = await withPage(dataDir, (page, base) => page.evaluate(`window.run(${JSON.stringify({ - url: base + sceneFile(options.scene || 'scene', size), codec, bitrate: Number(mbit) * 1e6, hw, decodeHw: options['decode-hw'] || hw, frames, framerate: FRAMERATE, name: options.name || codec, - })})`)); + const result = await withPage((page, base) => page.evaluate(`window.run(${JSON.stringify({ + url: base + sceneFile(options.scene || 'scene', size.toLowerCase()), codec, bitrate: Number(mbit) * 1e6, hw, + decodeHw: options['decode-hw'] || hw, frames: Number(options.frames || 20), framerate: FRAMERATE, name: options.name || codec, + })})`, timeoutMs)); console.log(JSON.stringify(result)); } else if (command === 'all') { + if (!existsSync(CLI)) throw new Error(`${CLI} is missing: cargo build --release -p emberwave-cli`); const out = resolve(options.out || join(root, 'target/chrome-codecs')); mkdirSync(out, { recursive: true }); - const sizes = (options.sizes || '1080p,1440p,4k').split(','); + const sizes = (options.sizes || '1080p,1440p,4k').split(',').map((x) => x.toLowerCase()); const scenes = (options.scenes || SCENES.join(',')).split(','); - const frames = Number(options.frames || 20); + const frames = 20; const only = options.codecs ? options.codecs.split(',') : null; - await withPage(dataDir, async (page, base) => { - for (const size of sizes) { - const info = sizeInfo(size); - const [width, height] = dims[size]; - const probe = await page.evaluate(`window.probe(${width}, ${height}, ${info.moonlight * 1e6}, ${FRAMERATE})`); - writeFileSync(join(out, `probe-${size}.json`), JSON.stringify(probe, null, 1)); - const rates = [info.moonlight, Math.round(info.emberwaveBytes * 8 * FRAMERATE / 1e6)]; - for (const scene of scenes) { - for (const [name, entry] of Object.entries(probe.codecs)) { - // The codecs of NVENC: H.264, HEVC and AV1. - if (name === 'VP9' || (only && !only.includes(name))) continue; - // Encode in hardware where there is an encoder and in software too; decode - // where a client would, in hardware if there is a decoder. - const decodeHw = entry.decode['prefer-hardware'] === true ? 'prefer-hardware' : 'prefer-software'; - const modes = ['prefer-hardware', 'prefer-software'].filter((hw) => entry.encode[hw] === true && (entry.decode[decodeHw] === true)); - for (const hw of modes) { - for (const mbit of rates) { - const file = join(out, `${scene}-${size}-${name.replace(/[^A-Za-z0-9]/g, '')}-${hw.replace('prefer-', '')}-${mbit}.json`); - if (existsSync(file) && !options.force) continue; - console.error(`${scene} ${size} ${name} ${hw} ${mbit} Mbit/s`); - let result; - try { - result = await page.evaluate(`window.run(${JSON.stringify({ url: base + sceneFile(scene, size), codec: entry.codec, bitrate: mbit * 1e6, hw, decodeHw, frames, framerate: FRAMERATE, name })})`); - } catch (error) { - result = { name, codec: entry.codec, hw, bitrate: mbit * 1e6, error: String(error.message || error) }; - } - result.size = size; - result.scene = scene; - writeFileSync(file, JSON.stringify(result)); + // A result is kept if it has pictures to compare; a run that failed is tried again. + const done = (file) => !options.force && existsSync(file) && ('psnr' in JSON.parse(readFileSync(file, 'utf8')) || 'rows' in JSON.parse(readFileSync(file, 'utf8'))); + for (const size of sizes) { + const info = sizeInfo(size); + const [width, height] = DIMS[size]; + const probe = await withPage((page) => page.evaluate(`window.probe(${width}, ${height}, ${info.moonlight * 1e6}, ${FRAMERATE})`, 60000)); + writeFileSync(join(out, `probe-${size}.json`), JSON.stringify(probe, null, 1)); + const rates = [info.moonlight, Math.round(info.emberwaveBytes * 8 * FRAMERATE / 1e6)]; + for (const scene of scenes) { + for (const [name, entry] of Object.entries(probe.codecs)) { + // The codecs of NVENC: H.264, HEVC and AV1. + if (name === 'VP9' || (only && !only.includes(name))) continue; + // Encode in hardware where there is an encoder, and in software too; + // decode where a client would, in hardware if there is a decoder. + const decodeHw = entry.decode['prefer-hardware'] === true ? 'prefer-hardware' : 'prefer-software'; + const modes = ['prefer-hardware', 'prefer-software'].filter((hw) => entry.encode[hw] === true && entry.decode[decodeHw] === true); + for (const hw of modes) { + for (const mbit of rates) { + const file = join(out, `${scene}-${size}-${name.replace(/[^A-Za-z0-9]/g, '')}-${hw.replace('prefer-', '')}-${mbit}.json`); + if (done(file)) continue; + console.error(`${scene} ${size} ${name} ${hw} ${mbit} Mbit/s`); + let result; + try { + result = await withPage((page, base) => page.evaluate(`window.run(${JSON.stringify({ url: base + sceneFile(scene, size), codec: entry.codec, bitrate: mbit * 1e6, hw, decodeHw, frames, framerate: FRAMERATE, name })})`, timeoutMs)); + } catch (error) { + result = { name, codec: entry.codec, hw, bitrate: mbit * 1e6, error: String(error.message || error) }; } + writeFileSync(file, JSON.stringify({ ...result, size, scene })); } } } } - }); + } // emberwave at the bytes each run actually used (all frames of the stream, - // the key frame included), where it can make a frame that small, and at the - // budgets of the other comparisons. + // the key frame included), and at the budgets of the other comparisons. const budgets = new Map(); for (const size of sizes) { const info = sizeInfo(size); for (const scene of scenes) { - budgets.set(`${scene}-${size}-${Math.round(info.moonlight * 1e6 / 8 / FRAMERATE)}`, { scene, size, bytes: Math.round(info.moonlight * 1e6 / 8 / FRAMERATE) }); - budgets.set(`${scene}-${size}-${info.emberwaveBytes}`, { scene, size, bytes: info.emberwaveBytes }); + for (const bytes of [Math.round(info.moonlight * 1e6 / 8 / FRAMERATE), info.emberwaveBytes]) budgets.set(`${scene}-${size}-${bytes}`, { scene, size, bytes }); } } for (const file of readdirSync(out)) { if (file.startsWith('probe') || file.startsWith('emberwave') || !file.endsWith('.json')) continue; const run = JSON.parse(readFileSync(join(out, file), 'utf8')); - if (!run.chunkBytes) continue; + if (!run.chunkBytes || !sizes.includes(run.size) || !scenes.includes(run.scene)) continue; const bytes = Math.round(mean(run.chunkBytes) / 50) * 50; budgets.set(`${run.scene}-${run.size}-${bytes}`, { scene: run.scene, size: run.size, bytes }); } - for (const [, { scene, size, bytes }] of budgets) { + for (const { scene, size, bytes } of budgets.values()) { const file = join(out, `emberwave-${scene}-${size}-${bytes}.json`); - if (existsSync(file) && !options.force) continue; + if (done(file)) continue; console.error(`emberwave ${scene} ${size} ${bytes} bytes a frame`); - try { - writeFileSync(file, JSON.stringify(emberwave(scene, size, bytes, frames, out))); - } catch (error) { - // A budget below the smallest frame the pictures' size allows. - writeFileSync(file, JSON.stringify({ name: 'emberwave', scene, size, bytesPerFrame: bytes, error: String(error.message).slice(0, 200) })); - } + writeFileSync(file, JSON.stringify(emberwave(scene, size, bytes, frames, out))); } -} else if (command === 'report') { +} else if (command === 'report' || command === 'summary') { const dir = resolve(positional[1] || join(root, 'target/chrome-codecs')); - const runs = readdirSync(dir).filter((f) => f.endsWith('.json') && !f.startsWith('probe')).map((f) => JSON.parse(readFileSync(join(dir, f), 'utf8'))); - const rows = []; - for (const run of runs) { - if (run.name === 'emberwave') { + const load = (file) => JSON.parse(readFileSync(join(dir, file), 'utf8')); + const files = readdirSync(dir).filter((file) => file.endsWith('.json') && !file.startsWith('probe')); + const chromeRuns = files.filter((file) => !file.startsWith('emberwave')).map(load); + const steady = (rows) => rows.slice(1); + const emberwaveAt = (run) => { + const match = load(`emberwave-${run.scene}-${run.size}-${Math.round(mean(run.chunkBytes) / 50) * 50}.json`); + return match.error ? null : match; + }; + + if (command === 'report') { + // Every run, with emberwave at the bytes of each. + const rows = []; + for (const file of files.filter((x) => x.startsWith('emberwave'))) { + const run = load(file); if (run.error) continue; - const all = run.rows; - const steady = all.slice(1); - rows.push({ scene: run.scene, size: run.size, who: 'emberwave', order: 1, asked: null, bytes: mean(all.map((r) => r.bytes)), steadyBytes: mean(steady.map((r) => r.bytes)), y: mean(steady.map((r) => r.psnr[0])), yMin: Math.min(...steady.map((r) => r.psnr[0])), cb: mean(steady.map((r) => r.psnr[1])), cr: mean(steady.map((r) => r.psnr[2])), key: all[0].psnr[0] }); - } else if (run.psnr) { - const steady = run.psnr.slice(1); - rows.push({ scene: run.scene, size: run.size, who: `${run.name} (${run.hw.replace('prefer-', '')} enc)`, order: 2, asked: Math.round(run.bitrate / 1e6), bytes: mean(run.chunkBytes), steadyBytes: mean(run.chunkBytes.slice(1)), keyBytes: run.chunkBytes[0], y: mean(steady.map((p) => p[0])), yMin: Math.min(...steady.map((p) => p[0])), cb: mean(steady.map((p) => p[1])), cr: mean(steady.map((p) => p[2])), key: run.psnr[0][0], decode: median(run.decodeMs.slice(1)), queue: run.decodeQueueMsPerFrame, held: run.decoderHeld, encode: median(run.encodeMs.slice(1)), keyframes: run.chunkTypes.filter((t) => t === 'key').length, decodeHw: run.decodeHw, sourceChange: mean(run.sourceChange) }); - } else { - rows.push({ scene: run.scene, size: run.size, who: `${run.name} (${String(run.hw).replace('prefer-', '')} enc)`, order: 2, asked: Math.round(run.bitrate / 1e6), error: run.error || run.encoderError || run.decoderError || (run.encoderSupported === false ? 'encoder not supported' : run.decoderSupported === false ? 'decoder not supported' : 'no result') }); + rows.push({ scene: run.scene, size: run.size, who: 'emberwave', bytes: mean(run.rows.map((r) => r.bytes)), steadyBytes: mean(steady(run.rows).map((r) => r.bytes)), y: mean(steady(run.rows).map((r) => r.psnr[0])), yMin: Math.min(...steady(run.rows).map((r) => r.psnr[0])), cb: mean(steady(run.rows).map((r) => r.psnr[1])), cr: mean(steady(run.rows).map((r) => r.psnr[2])), key: run.rows[0].psnr[0] }); } - } - const f = (v, d = 2) => (v === undefined || v === null || Number.isNaN(v) ? '' : v.toFixed(d)); - for (const scene of SCENES) { - for (const size of Object.keys(SIZES)) { - const part = rows.filter((r) => r.scene === scene && r.size === size); - if (!part.length) continue; - // Each codec's rows follow the emberwave row nearest to its bytes. - part.sort((a, b) => a.bytes - b.bytes || a.order - b.order); - console.log(`\n${scene}, ${size}\n`); - console.log('| | asked Mbit/s | kB a frame (all) | kB after the key frame | Y dB | Cb dB | Cr dB | worst Y dB | key frame Y dB | decode ms | decode queue ms | encode ms |'); - console.log('|---|---|---|---|---|---|---|---|---|---|---|---|'); - for (const r of part) { - if (r.error) console.log(`| ${r.who} | ${r.asked ?? ''} | ${r.error} | | | | | | | | | |`); - else console.log(`| ${r.who} | ${r.asked ?? ''} | ${f(r.bytes / 1000, 1)} | ${f(r.steadyBytes / 1000, 1)} | ${f(r.y)} | ${f(r.cb)} | ${f(r.cr)} | ${f(r.yMin)} | ${f(r.key)} | ${f(r.decode)}${r.held ? ' (held)' : ''} | ${f(r.queue)} | ${f(r.encode)} |`); + for (const run of chromeRuns) { + const who = `${run.name} (${String(run.hw).replace('prefer-', '')} enc)`; + if (!run.psnr) { rows.push({ scene: run.scene, size: run.size, who, asked: Math.round(run.bitrate / 1e6), error: failure(run), bytes: Infinity }); continue; } + rows.push({ scene: run.scene, size: run.size, who, asked: Math.round(run.bitrate / 1e6), bytes: mean(run.chunkBytes), steadyBytes: mean(run.chunkBytes.slice(1)), y: mean(steady(run.psnr).map((p) => p[0])), yMin: Math.min(...steady(run.psnr).map((p) => p[0])), cb: mean(steady(run.psnr).map((p) => p[1])), cr: mean(steady(run.psnr).map((p) => p[2])), key: run.psnr[0][0], decode: median(run.decodeMs.slice(1)), queue: run.decodeQueueMsPerFrame, held: run.decoderHeld, encode: median(run.encodeMs.slice(1)) }); + } + for (const scene of SCENES) { + for (const size of Object.keys(SIZES)) { + const part = rows.filter((r) => r.scene === scene && r.size === size).sort((a, b) => a.bytes - b.bytes || (a.asked ?? 0) - (b.asked ?? 0)); + if (!part.length) continue; + console.log(`\n${scene}, ${size}\n`); + console.log('| | asked Mbit/s | kB a frame (all) | kB after the key frame | Y dB | Cb dB | Cr dB | worst Y dB | key frame Y dB | decode ms | decode, queued ms | encode ms |'); + console.log('|---|---|---|---|---|---|---|---|---|---|---|---|'); + for (const r of part) { + if (r.error) console.log(`| ${r.who} | ${r.asked ?? ''} | ${r.error} | | | | | | | | | |`); + else console.log(`| ${r.who} | ${r.asked ?? ''} | ${f(r.bytes / 1000, 1)} | ${f(r.steadyBytes / 1000, 1)} | ${f(r.y)} | ${f(r.cb)} | ${f(r.cr)} | ${f(r.yMin)} | ${f(r.key)} | ${f(r.decode)}${r.held ? ' (held)' : ''} | ${f(r.queue)} | ${f(r.encode)} |`); + } } } - } -} else if (command === 'summary') { - // The tables of BENCHMARKS.md: the encoders a host would use (the hardware - // ones, and AV1, which Chrome encodes in software only), each next to - // emberwave at the same bytes a frame. - const dir = resolve(positional[1] || join(root, 'target/chrome-codecs')); - const load = (f) => JSON.parse(readFileSync(join(dir, f), 'utf8')); - const files = readdirSync(dir).filter((f) => f.endsWith('.json') && !f.startsWith('probe') && !f.startsWith('emberwave')); - const order = { AV1: 0, HEVC: 1, 'H.264': 2 }; - const picked = files.map(load).filter((r) => r.hw === 'prefer-hardware' || r.name === 'AV1'); - picked.sort((a, b) => SCENES.indexOf(a.scene) - SCENES.indexOf(b.scene) || Object.keys(SIZES).indexOf(a.size) - Object.keys(SIZES).indexOf(b.size) || a.bitrate - b.bitrate || order[a.name] - order[b.name]); - const f = (v, d = 2) => (v === undefined || v === null || Number.isNaN(v) ? '' : v.toFixed(d)); - const failures = []; - for (const scene of SCENES) { - console.log(`\n${scene}\n`); - console.log('| Size | Codec | asked Mbit/s | kB a frame | codec Y dB | emberwave Y dB | codec Cb / Cr dB | emberwave Cb / Cr dB | decode ms | decode, queued ms |'); - console.log('|---|---|---|---|---|---|---|---|---|---|'); - for (const run of picked.filter((r) => r.scene === scene)) { - if (!run.psnr) { - failures.push(`${scene} ${run.size} ${run.name} ${Math.round(run.bitrate / 1e6)} Mbit/s: ${run.error || run.encoderError || run.decoderError || 'no result'}`); - continue; + } else { + // The encoders a host would use (the hardware ones, and AV1, which Chrome + // encodes in software only), each next to emberwave at the same bytes a + // frame, the key frame included. + const order = { AV1: 0, HEVC: 1, 'H.264': 2 }; + const picked = chromeRuns.filter((r) => r.hw === 'prefer-hardware' || r.name === 'AV1'); + picked.sort((a, b) => SCENES.indexOf(a.scene) - SCENES.indexOf(b.scene) || Object.keys(SIZES).indexOf(a.size) - Object.keys(SIZES).indexOf(b.size) || a.bitrate - b.bitrate || order[a.name] - order[b.name]); + const failures = []; + for (const scene of SCENES) { + console.log(`\n${scene}\n`); + console.log('| Size | Codec | asked Mbit/s | kB a frame | kB after the key frame | codec Y dB | emberwave Y dB | codec Cb / Cr dB | emberwave Cb / Cr dB | decode ms | decode, queued ms |'); + console.log('|---|---|---|---|---|---|---|---|---|---|---|'); + for (const run of picked.filter((r) => r.scene === scene)) { + const label = `${scene} ${run.size} ${run.name} ${Math.round(run.bitrate / 1e6)} Mbit/s`; + if (!run.psnr) { failures.push(`${label}: ${failure(run)}`); continue; } + const match = emberwaveAt(run); + if (!match) { failures.push(`${label}: emberwave could not make frames of that size`); continue; } + const e = (k) => mean(steady(match.rows).map((r) => r.psnr[k])); + const c = (k) => mean(steady(run.psnr).map((p) => p[k])); + console.log(`| ${run.size} | ${run.name} | ${Math.round(run.bitrate / 1e6)} | ${f(mean(run.chunkBytes) / 1000, 1)} | ${f(mean(run.chunkBytes.slice(1)) / 1000, 1)} | ${f(c(0))} | ${f(e(0))} | ${f(c(1))} / ${f(c(2))} | ${f(e(1))} / ${f(e(2))} | ${f(median(run.decodeMs.slice(1)))} | ${f(run.decodeQueueMsPerFrame)} |`); } - const bytes = Math.round(mean(run.chunkBytes) / 50) * 50; - const match = load(`emberwave-${scene}-${run.size}-${bytes}.json`); - if (match.error) { failures.push(`${scene} ${run.size} ${run.name}: emberwave could not make frames of ${bytes} bytes`); continue; } - const steady = (rows) => rows.slice(1); - const ey = mean(steady(match.rows).map((r) => r.psnr[0])), ecb = mean(steady(match.rows).map((r) => r.psnr[1])), ecr = mean(steady(match.rows).map((r) => r.psnr[2])); - const cy = mean(steady(run.psnr).map((p) => p[0])), ccb = mean(steady(run.psnr).map((p) => p[1])), ccr = mean(steady(run.psnr).map((p) => p[2])); - console.log(`| ${run.size} | ${run.name} | ${Math.round(run.bitrate / 1e6)} | ${f(mean(run.chunkBytes) / 1000, 1)} | ${f(cy)} | ${f(ey)} | ${f(ccb)} / ${f(ccr)} | ${f(ecb)} / ${f(ecr)} | ${f(median(run.decodeMs.slice(1)))} | ${f(run.decodeQueueMsPerFrame)} |`); } + if (failures.length) console.log('\nNot measured:\n' + failures.map((x) => `- ${x}`).join('\n')); } - if (failures.length) console.log('\nNot measured:\n' + failures.map((x) => `- ${x}`).join('\n')); } else { - console.error('usage: chrome_codecs.mjs probe [SIZE] | run SIZE CODEC MBIT [--hw H] [--frames N] | all [--sizes S] [--codecs C] [--out DIR] | report [DIR] | summary [DIR]'); + console.error('usage: chrome_codecs.mjs probe [SIZE] | run SIZE CODEC MBIT [options] | all [options] | report [DIR] | summary [DIR]'); process.exit(2); } diff --git a/scripts/chrome_codecs/page.html b/scripts/chrome_codecs/page.html index 2be4663..c0533c3 100644 --- a/scripts/chrome_codecs/page.html +++ b/scripts/chrome_codecs/page.html @@ -13,7 +13,9 @@ // One 8-bit 4:2:0 Y4M, fetched whole: its header, then FRAME and the planes. async function loadY4M(url, maxFrames) { - const data = new Uint8Array(await (await fetch(url)).arrayBuffer()); + const response = await fetch(url); + if (!response.ok) throw new Error(`${url}: ${response.status}`); + const data = new Uint8Array(await response.arrayBuffer()); let end = data.indexOf(10); const header = new TextDecoder().decode(data.subarray(0, end)); const width = Number(/ W(\d+)/.exec(header)[1]); @@ -146,7 +148,6 @@ out.encoderSupported = support.supported; if (!support.supported) return out; encoder.configure(config); - const t0 = performance.now(); out.encoderHeld = 0; for (let i = 0; i < frames.length; i++) { const frame = new VideoFrame(frames[i], { format: 'I420', codedWidth: width, codedHeight: height, timestamp: timestampOf(i), duration: Math.round(step) }); @@ -161,75 +162,93 @@ } await encoder.flush(); encoder.close(); - out.encodeWallMs = performance.now() - t0; if (chunks.some((c) => c === null)) { out.error = `${chunks.filter((c) => c).length} chunks for ${frames.length} frames`; return out; } out.encodeMs = encodeMs; out.chunkBytes = chunks.map((c) => c.data.length); out.chunkTypes = chunks.map((c) => c.type); - // Decoding, one chunk at a time, the time from decode() until its frame, - // held back frames as above (no flush in between: a decoder needs a key - // frame after one). - const decoded = new Array(frames.length).fill(null); - const decodeMs = new Array(frames.length).fill(null); - const decodeSubmitted = new Map(); - const decodeArrivals = new Map(); - let decoderError = null; - const decoder = new VideoDecoder({ - output: async (frame) => { - const at = performance.now(); - const index = indexOf(frame.timestamp); - decodeMs[index] = at - decodeSubmitted.get(index); - if (decodeArrivals.has(index)) decodeArrivals.get(index)(); - decoded[index] = await planes(frame, width, height); - frame.close(); - }, - error: (e) => { decoderError = e; for (const r of decodeArrivals.values()) r(); }, - }); - const dconfig = { codec, codedWidth: width, codedHeight: height, hardwareAcceleration: decodeHw }; + // The chunks are decoded three times, so that what is timed is not copied + // out of the decoder and what is compared is not timed. const description = chunks.find((c) => c.description)?.description; + const dconfig = { codec, codedWidth: width, codedHeight: height, hardwareAcceleration: decodeHw }; if (description) dconfig.description = description; const dsupport = await VideoDecoder.isConfigSupported(dconfig); out.decoderSupported = dsupport.supported; if (!dsupport.supported) return out; - decoder.configure(dconfig); - out.decoderHeld = 0; - const d0 = performance.now(); - for (let i = 0; i < chunks.length; i++) { - const c = chunks[i]; - const got = new Promise((resolve) => { decodeArrivals.set(i, resolve); }); - decodeSubmitted.set(i, performance.now()); - decoder.decode(new EncodedVideoChunk({ type: c.type, timestamp: c.timestamp, data: c.data })); - if ((await within(got, 1000)) === null) out.decoderHeld++; - if (decoderError) { out.decoderError = String(decoderError); return out; } + const chunkOf = (c) => new EncodedVideoChunk({ type: c.type, timestamp: c.timestamp, data: c.data }); + const decoded = new Array(frames.length).fill(null); + try { + // 1. One chunk at a time: the time from decode() until its frame is out, + // matched by the frame's timestamp, as for the encoder. A decoder that holds + // frames back is not waited for longer than a second, and no flush comes + // in between: a decoder needs a key frame after one. + const decodeMs = new Array(frames.length).fill(null); + const submittedAt = new Map(); + const arrivalOf = new Map(); + let decoderError = null; + const serial = new VideoDecoder({ + output: (frame) => { + const at = performance.now(); + const index = indexOf(frame.timestamp); + decodeMs[index] = at - submittedAt.get(index); + frame.close(); + if (arrivalOf.has(index)) arrivalOf.get(index)(); + }, + error: (e) => { decoderError = e; for (const r of arrivalOf.values()) r(); }, + }); + serial.configure(dconfig); + out.decoderHeld = 0; + for (let i = 0; i < chunks.length; i++) { + const got = new Promise((resolve) => { arrivalOf.set(i, resolve); }); + submittedAt.set(i, performance.now()); + serial.decode(chunkOf(chunks[i])); + if ((await within(got, 1000)) === null) out.decoderHeld++; + if (decoderError) throw decoderError; + } + await serial.flush(); + serial.close(); + out.decodeMs = decodeMs; + + // 2. All chunks at once: the time from the first frame out to the last, + // divided by the frames between them, which leaves out the decoder's start + // and the key frame. + const outAt = []; + const queued = new VideoDecoder({ output: (frame) => { outAt.push(performance.now()); frame.close(); }, error: (e) => { decoderError = e; } }); + queued.configure(dconfig); + for (const c of chunks) queued.decode(chunkOf(c)); + await queued.flush(); + queued.close(); + if (decoderError) throw decoderError; + out.decodeQueueFrames = outAt.length; + out.decodeQueueMsPerFrame = outAt.length > 1 ? (outAt[outAt.length - 1] - outAt[0]) / (outAt.length - 1) : null; + + // 3. For the comparison: the frames are copied out, untimed. + const compared = new VideoDecoder({ + output: async (frame) => { + const index = indexOf(frame.timestamp); + decoded[index] = await planes(frame, width, height); + frame.close(); + }, + error: (e) => { decoderError = e; }, + }); + compared.configure(dconfig); + for (const c of chunks) compared.decode(chunkOf(c)); + await compared.flush(); + // The last frames' copies out of the decoder may still be under way. + for (let i = 0; i < 100 && decoded.some((d) => d === null) && !decoderError; i++) await sleep(50); + compared.close(); + if (decoderError) throw decoderError; + } catch (e) { + // What the encoder made stays in the result. + out.decoderError = String(e); + return out; } - await decoder.flush(); - // The last frames' copies out of the decoder may still be under way. - for (let i = 0; i < 100 && decoded.some((d) => d === null); i++) await sleep(50); - decoder.close(); - out.decodeWallMs = performance.now() - d0; - out.decodeMs = decodeMs; out.decodedFrames = decoded.filter((d) => d).length; - // The same chunks again, all given at once: how fast a decoder works - // through a queue, for decoders that hold frames back one at a time. Without - // copying the pictures out. - let counted = 0; - const queue = new VideoDecoder({ output: (frame) => { counted++; frame.close(); }, error: (e) => { decoderError = e; } }); - queue.configure(dconfig); - const q0 = performance.now(); - for (const c of chunks) queue.decode(new EncodedVideoChunk({ type: c.type, timestamp: c.timestamp, data: c.data })); - await queue.flush(); - out.decodeQueueMsPerFrame = (performance.now() - q0) / chunks.length; - out.decodeQueueFrames = counted; - queue.close(); - // How much the source itself changes from one frame to the next, as a PSNR // of the change: the hardness of the sequence for a codec that predicts. out.sourceChange = []; for (let i = 1; i < frames.length; i++) out.sourceChange.push(psnr(frames[i].subarray(0, width * height), frames[i - 1].subarray(0, width * height))); - out.decodedChange = []; - for (let i = 1; i < decoded.length; i++) if (decoded[i] && decoded[i - 1]) out.decodedChange.push(psnr(decoded[i][0], decoded[i - 1][0])); // Picture quality of each decoded frame against its source. const cw = width >> 1, ch = height >> 1;