diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index df5218e..4bc337f 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 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 21d2817..3681ba8 100644 --- a/BENCHMARKS.md +++ b/BENCHMARKS.md @@ -439,3 +439,83 @@ 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, 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 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 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, 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 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. **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 | 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: 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: 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 + +```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 10 minutes; writes target/chrome-codecs/*.json +node scripts/chrome_codecs.mjs summary # the tables above; `report` lists every run +``` + +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/README.ko.md b/README.ko.md index 423435c..b942028 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.0에 필요한 것 diff --git a/README.md b/README.md index c9f94ad..dabdb51 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. ### What 1.0.0 needs diff --git a/scripts/chrome_codecs.mjs b/scripts/chrome_codecs.mjs new file mode 100755 index 0000000..0e50860 --- /dev/null +++ b/scripts/chrome_codecs.mjs @@ -0,0 +1,401 @@ +#!/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 [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 +// +// 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) +// +// `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, sep } 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 }, +}; +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 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); +} + +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) => { + let file = null; + 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; + } + 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, 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-')); + 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}`); + }; + 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; + } +} + +// 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 { + 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(); + server.close(); + } +} + +// 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. 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 === 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 || 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 }; +} + +function parseArgs(argv) { + const positional = []; + const options = {}; + for (let i = 0; i < argv.length; 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((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 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(',').map((x) => x.toLowerCase()); + const scenes = (options.scenes || SCENES.join(',')).split(','); + const frames = 20; + const only = options.codecs ? options.codecs.split(',') : null; + // 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), 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) { + 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 || !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.values()) { + const file = join(out, `emberwave-${scene}-${size}-${bytes}.json`); + if (done(file)) continue; + console.error(`emberwave ${scene} ${size} ${bytes} bytes a frame`); + writeFileSync(file, JSON.stringify(emberwave(scene, size, bytes, frames, out))); + } +} else if (command === 'report' || command === 'summary') { + const dir = resolve(positional[1] || join(root, 'target/chrome-codecs')); + 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; + 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] }); + } + 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 { + // 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)} |`); + } + } + 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 [options] | all [options] | 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..c0533c3 --- /dev/null +++ b/scripts/chrome_codecs/page.html @@ -0,0 +1,267 @@ + + +emberwave: Chrome's WebCodecs on a Y4M + +