From 238dc2a3543642cac26b4a6b4f94c27800aea9d2 Mon Sep 17 00:00:00 2001 From: harry Date: Tue, 24 Nov 2026 21:29:34 +0900 Subject: [PATCH 1/2] refactor: split emberwave-wgpu out of emberwave-core (D75, steps 1 and 2) The core's public API showed about thirty wgpu types, which a new major version of wgpu would break, so a 1.0 of the core could not promise a stable Rust API (#165). D75 decided to move the GPU code into a crate of its own. - `crates/emberwave-core/src/gpu` moves to `crates/emberwave-wgpu/src` with git mv (`mod.rs` becomes `lib.rs`), with the GPU tests (`gpu.rs`, `gpu_encoder.rs`, `gpu_hooks.rs`, `shaders.rs`); the shared test helpers are included from the core's tests by `#[path]`, with the GPU's own beside them. - The core loses its `gpu` feature, `pub use wgpu` and its wgpu, pollster and bytemuck dependencies. `emberwave-wgpu` re-exports wgpu and takes the core at its exact version. - The core opens, as `#[doc(hidden)] pub`, what the GPU encoder shares with the CPU one: the modules `encode::{fdwt, quant, rate}`, `Bands`, `Block32`, the helpers of the stream's headers and of the planes' checks, the CPU encoder's `transform` and `quantise`, and `color::check_rgb`. The compiler named them; D75's search had found six. - The GPU code handles an RGB order it does not know (`RgbOrder` is non_exhaustive) with `GpuError::InvalidArgument`; its tests build the core's non_exhaustive structs field by field. - `emberwave-cli`, `emberwave-ffi` and `emberwave-web` take the GPU types from `emberwave_wgpu`; the C API does not change. - CI checks that the core does not depend on wgpu, lints the new crate for the browser, and reports the adapter from its tests; CONTRIBUTING, the README's layout tables and D75 follow. The rest of the docs is the next step. The workspace's tests pass in the same numbers as before. Claude-Session: https://claude.ai/code/session_019fJGoCTvP5e7n599q3ZQ42 --- .github/workflows/ci.yml | 15 +++-- ARCHITECTURE.md | 2 + CONTRIBUTING.md | 14 ++--- Cargo.lock | 20 +++++-- Cargo.toml | 6 +- README.ko.md | 3 +- README.md | 3 +- crates/emberwave-cli/Cargo.toml | 1 + crates/emberwave-cli/src/bench.rs | 2 +- crates/emberwave-cli/src/bench_encode.rs | 2 +- crates/emberwave-cli/src/decode.rs | 2 +- crates/emberwave-cli/src/encode.rs | 2 +- crates/emberwave-cli/src/main.rs | 2 +- crates/emberwave-core/Cargo.toml | 19 +----- crates/emberwave-core/src/color.rs | 8 +-- crates/emberwave-core/src/cpu/mod.rs | 2 +- crates/emberwave-core/src/encode/fdwt.rs | 10 ++-- crates/emberwave-core/src/encode/mod.rs | 43 +++++++++----- crates/emberwave-core/src/encode/quant.rs | 38 +++++------- crates/emberwave-core/src/encode/rate.rs | 14 ++--- crates/emberwave-core/src/lib.rs | 24 +++----- crates/emberwave-core/tests/common/mod.rs | 56 ------------------ crates/emberwave-ffi/Cargo.toml | 1 + crates/emberwave-ffi/src/lib.rs | 20 +++---- crates/emberwave-ffi/tests/api.rs | 2 +- crates/emberwave-ffi/tests/encoder.rs | 2 +- crates/emberwave-web/Cargo.toml | 1 + crates/emberwave-web/src/bench.rs | 2 +- crates/emberwave-web/src/lib.rs | 2 +- crates/emberwave-wgpu/Cargo.toml | 29 ++++++++++ .../src/gpu => emberwave-wgpu/src}/context.rs | 0 .../src/gpu => emberwave-wgpu/src}/decoder.rs | 18 +++--- .../src/gpu => emberwave-wgpu/src}/encoder.rs | 25 +++++--- .../src}/encoder/tests.rs | 29 +++++----- .../src/gpu => emberwave-wgpu/src}/error.rs | 4 +- .../src/gpu => emberwave-wgpu/src}/layout.rs | 36 ++++++------ .../gpu/mod.rs => emberwave-wgpu/src/lib.rs} | 11 +++- .../gpu => emberwave-wgpu/src}/pipelines.rs | 2 +- .../gpu => emberwave-wgpu/src}/resources.rs | 0 .../src}/shaders/conceal.wgsl | 0 .../src}/shaders/dequant.wgsl | 0 .../src}/shaders/draw.wgsl | 0 .../src}/shaders/equant.wgsl | 0 .../src}/shaders/fdwt.wgsl | 0 .../src}/shaders/gather.wgsl | 0 .../src}/shaders/gather_rgb.wgsl | 0 .../src}/shaders/idwt.wgsl | 0 .../src}/shaders/idwt_packed.wgsl | 0 .../src}/shaders/idwt_planes.wgsl | 0 .../src}/shaders/pack.wgsl | 0 .../src}/shaders/quantise.wgsl | 0 .../src}/shaders/rate.wgsl | 0 .../src}/shaders/scan.wgsl | 0 .../src}/shaders/yuv2rgb.wgsl | 0 crates/emberwave-wgpu/tests/common/mod.rs | 58 +++++++++++++++++++ .../tests/gpu.rs | 16 +++-- .../tests/gpu_encoder.rs | 4 +- .../tests/gpu_hooks.rs | 4 +- .../tests/shaders.rs | 4 +- scripts/soak.sh | 2 +- 60 files changed, 302 insertions(+), 258 deletions(-) create mode 100644 crates/emberwave-wgpu/Cargo.toml rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/context.rs (100%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/decoder.rs (99%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/encoder.rs (98%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/encoder/tests.rs (97%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/error.rs (95%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/layout.rs (97%) rename crates/{emberwave-core/src/gpu/mod.rs => emberwave-wgpu/src/lib.rs} (90%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/pipelines.rs (99%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/resources.rs (100%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/shaders/conceal.wgsl (100%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/shaders/dequant.wgsl (100%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/shaders/draw.wgsl (100%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/shaders/equant.wgsl (100%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/shaders/fdwt.wgsl (100%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/shaders/gather.wgsl (100%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/shaders/gather_rgb.wgsl (100%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/shaders/idwt.wgsl (100%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/shaders/idwt_packed.wgsl (100%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/shaders/idwt_planes.wgsl (100%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/shaders/pack.wgsl (100%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/shaders/quantise.wgsl (100%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/shaders/rate.wgsl (100%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/shaders/scan.wgsl (100%) rename crates/{emberwave-core/src/gpu => emberwave-wgpu/src}/shaders/yuv2rgb.wgsl (100%) create mode 100644 crates/emberwave-wgpu/tests/common/mod.rs rename crates/{emberwave-core => emberwave-wgpu}/tests/gpu.rs (99%) rename crates/{emberwave-core => emberwave-wgpu}/tests/gpu_encoder.rs (99%) rename crates/{emberwave-core => emberwave-wgpu}/tests/gpu_hooks.rs (97%) rename crates/{emberwave-core => emberwave-wgpu}/tests/shaders.rs (99%) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3d92537..5345806 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -70,9 +70,14 @@ jobs: # The crates carry copies of LICENSE and THIRD_PARTY_NOTICES.md (decision D75). - run: scripts/check_license_copies.sh - run: cargo clippy --workspace --all-targets -- -D warnings - # The parser and the CPU decoder alone, which emberwave-core is without - # its default `gpu` feature. - - run: cargo clippy -p emberwave-core --no-default-features --all-targets -- -D warnings + # emberwave-core has no wgpu in its dependencies, so none in its API: the + # GPU code is emberwave-wgpu (decision D75). + - name: The core does not depend on wgpu + run: | + if cargo tree -p emberwave-core -e normal --prefix none | grep -E '^(wgpu|naga) '; then + echo "emberwave-core depends on wgpu: the GPU code belongs to emberwave-wgpu" >&2 + exit 1 + fi # The README's figures are drawn by a script: they must be what it draws. - run: python3 -B scripts/readme_figures.py && git diff --exit-code docs/images @@ -112,7 +117,7 @@ jobs: - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 # The browser player, and the core as the browser sees it: no blocking # calls, no clock. - - run: cargo clippy --target wasm32-unknown-unknown -p emberwave-web -p emberwave-core -- -D warnings + - run: cargo clippy --target wasm32-unknown-unknown -p emberwave-web -p emberwave-wgpu -p emberwave-core -- -D warnings # wasm-bindgen-cli has to be the version of the wasm-bindgen crate in # Cargo.lock, so the cache follows the lock file, as in pages.yml. - name: Cache wasm-bindgen-cli @@ -181,7 +186,7 @@ jobs: # Prints which adapter the GPU tests run on, how long creating a decoder # takes (shader compilation) and how close the GPU is to the CPU. - name: Report the GPU adapter - run: cargo test -p emberwave-core --test gpu inverse_transform -- --nocapture + run: cargo test -p emberwave-wgpu --test gpu inverse_transform -- --nocapture - run: cargo test --workspace # The C example, built with CMake against the shared library that the # build above made, decodes every test vector. diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index c7d1645..7f0d4b8 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1930,5 +1930,7 @@ The last frame's detail, always, gains everything on a still picture and loses u **Risks.** The hidden surface drifts between the two crates; the tests' relative paths to `testdata` stay valid, as the new crate sits at the same depth; rustdoc links from `cpu` to `gpu` become plain text; the move is large (about 14,000 lines) but mechanical, which `git mv` keeps in the history; a published `emberwave-core` 0.18.1 has the `gpu` feature that later versions do not, which no known user has used. +**Steps 1 and 2, done together (2026-11-24).** The move came first, so that the compiler named what the core has to open, and then one pull request took both steps. The core opens more than the six items found by searching: the modules `encode::{fdwt, quant, rate}` (all their items), `encode::{Bands, Block32, pristine_blocks, stream_header, next_sequence, start_of_frame, check_planes, check_strided_planes}`, the CPU encoder's `transform` and `quantise`, and `color::check_rgb`, every one `#[doc(hidden)] pub`. The GPU code matches `RgbOrder`, which is `non_exhaustive`, so it now has an arm for an order it does not know, which returns `GpuError::InvalidArgument`; its tests build `Signalling` and `ColorParams` field by field or through `ColorParams::new`, as a crate outside the core has to. The shaders are 15, not 13. `emberwave-core` and `emberwave-wgpu` take each other's exact version (`=` in the workspace), and CI checks that the core does not depend on wgpu. The workspace's tests pass in the same number as before the move (the core's 141 unit tests are now 109 in the core and 32 in `emberwave-wgpu`). + **Consequence.** The checklist item "stable C and Rust APIs" in the README can close when the library's name carries its version and the split has landed, or earlier, if the maintainer decides to ship 1.0 with option 1's plain statement instead; the data above is what that choice would weigh. No code moves with this entry. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 579cc24..0785cdf 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,11 +16,11 @@ cargo clippy --workspace --all-targets -- -D warnings cargo test --workspace ``` -CI runs two more lints, for code that builds only without the `gpu` feature or only for the browser, and a check on Rust 1.87. The lints need the `wasm32-unknown-unknown` target (`rustup target add wasm32-unknown-unknown`): +CI runs one more lint, for code that builds only for the browser, a check that `emberwave-core` does not depend on wgpu (the GPU code is `emberwave-wgpu`, decision D75), and a check on Rust 1.87. The lint needs the `wasm32-unknown-unknown` target (`rustup target add wasm32-unknown-unknown`): ```sh -cargo clippy -p emberwave-core --no-default-features --all-targets -- -D warnings -cargo clippy --target wasm32-unknown-unknown -p emberwave-web -p emberwave-core -- -D warnings +cargo clippy --target wasm32-unknown-unknown -p emberwave-web -p emberwave-wgpu -p emberwave-core -- -D warnings +cargo tree -p emberwave-core -e normal --prefix none | grep -E '^(wgpu|naga) ' # must print nothing ``` ## Tests @@ -30,13 +30,13 @@ cargo clippy --target wasm32-unknown-unknown -p emberwave-web -p emberwave-core | Unit tests | `src/` of each crate | Parser, CPU decoder, colour conversion, CLI helpers | | Vectors | `crates/emberwave-core/tests/vectors.rs` | The CPU decoder against upstream's decodes of the committed vectors | | Robustness | `crates/emberwave-core/tests/robustness.rs` | Malformed input never panics (proptest) | -| Shaders | `crates/emberwave-core/tests/shaders.rs` | The WGSL validates with naga without any optional capability, and the workgroup variables are the reviewed ones, without a GPU | -| GPU | `crates/emberwave-core/tests/gpu.rs` | The GPU decoder against the CPU decoder and against upstream, on a real adapter | +| Shaders | `crates/emberwave-wgpu/tests/shaders.rs` | The WGSL validates with naga without any optional capability, and the workgroup variables are the reviewed ones, without a GPU | +| GPU | `crates/emberwave-wgpu/tests/gpu.rs` | The GPU decoder against the CPU decoder and against upstream, on a real adapter | | CLI | `crates/emberwave-cli/tests/cli.rs` | The `emberwave-cli` binary end to end | | C API | `crates/emberwave-ffi/tests/api.rs`, `tests/encoder.rs`, `tests/header.rs`, `tests/exports.rs`, `tests/thread_end.rs` | The C functions called through raw pointers against the Rust decoder and encoder; the committed header against cbindgen's output; the shared library's export table against the header (macOS and Linux, needs `nm`; it builds the library through cargo); threads that end while contexts live | -| GPU interop | `crates/emberwave-ffi/tests/metal.rs`, `tests/vulkan.rs`, `tests/d3d12.rs`, `crates/emberwave-core/tests/gpu_hooks.rs` | The C API on a client's own Metal queue and textures (macOS), Vulkan device and images (Linux's lavapipe, under the validation layer), and Direct3D 11 textures and fences (Windows' WARP); the order of the submission hooks on every backend | +| GPU interop | `crates/emberwave-ffi/tests/metal.rs`, `tests/vulkan.rs`, `tests/d3d12.rs`, `crates/emberwave-wgpu/tests/gpu_hooks.rs` | The C API on a client's own Metal queue and textures (macOS), Vulkan device and images (Linux's lavapipe, under the validation layer), and Direct3D 11 textures and fences (Windows' WARP); the order of the submission hooks on every backend | | Encoder | `crates/emberwave-core/tests/encoder.rs`, `src/encode/` | The encoder makes the committed bytes again, its frames fit their budgets, and emberwave decodes them as upstream does | -| GPU encoder | `crates/emberwave-core/tests/gpu_encoder.rs`, `src/gpu/encoder/tests.rs` | Each stage of the GPU encoder given the CPU encoder's input, against the CPU's output; whole frames against the committed vectors, on a real adapter; pictures in textures against the same pictures in CPU memory | +| GPU encoder | `crates/emberwave-wgpu/tests/gpu_encoder.rs`, `src/encoder/tests.rs` | Each stage of the GPU encoder given the CPU encoder's input, against the CPU's output; whole frames against the committed vectors, on a real adapter; pictures in textures against the same pictures in CPU memory | | C example | `scripts/check_c_example.sh` | The C examples, built with CMake against the shared library: one decodes every vector, the other encodes two of the encoder's sources and decodes its packets again (CI runs it after the tests) | | iPhone app | `scripts/check_ios_app.sh` | The benchmark app of `examples/ios`, built for iPhones and for the iOS Simulator, where it runs a short benchmark and reads a texture of `emberwave_decoder_decode_texture` back through Metal (CI's macOS job `XCFramework`) | | XCFramework | `scripts/check_xcframework.sh` | The C examples and the Swift example, linked with each static library of the XCFramework, on the Mac and in an iOS Simulator, as `check_c_example.sh` runs them; for iPhones and iPads they are linked only (CI's macOS job `XCFramework`) | diff --git a/Cargo.lock b/Cargo.lock index 15b060d..4821e76 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -292,6 +292,7 @@ version = "0.19.0" dependencies = [ "clap", "emberwave-core", + "emberwave-wgpu", "png", "serde_json", "wgpu", @@ -301,12 +302,8 @@ dependencies = [ name = "emberwave-core" version = "0.19.0" dependencies = [ - "bytemuck", - "naga", - "pollster", "proptest", "thiserror", - "wgpu", ] [[package]] @@ -316,6 +313,7 @@ dependencies = [ "ash", "cbindgen", "emberwave-core", + "emberwave-wgpu", "objc2", "objc2-metal", "pollster", @@ -328,12 +326,26 @@ name = "emberwave-web" version = "0.19.0" dependencies = [ "emberwave-core", + "emberwave-wgpu", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", "wgpu", ] +[[package]] +name = "emberwave-wgpu" +version = "0.19.0" +dependencies = [ + "bytemuck", + "emberwave-core", + "naga", + "pollster", + "proptest", + "thiserror", + "wgpu", +] + [[package]] name = "equivalent" version = "1.0.3" diff --git a/Cargo.toml b/Cargo.toml index 75a02b0..d60e0a7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,7 @@ resolver = "3" members = [ "crates/emberwave-core", + "crates/emberwave-wgpu", "crates/emberwave-cli", "crates/emberwave-ffi", "crates/emberwave-web", @@ -19,7 +20,10 @@ rust-version = "1.87" publish = false [workspace.dependencies] -emberwave-core = { path = "crates/emberwave-core", version = "0.19.0" } +# emberwave-wgpu uses hidden items of the core, so the two go together: the +# exact version. +emberwave-core = { path = "crates/emberwave-core", version = "=0.19.0" } +emberwave-wgpu = { path = "crates/emberwave-wgpu", version = "=0.19.0" } thiserror = "2" proptest = "1" # Native backends only: GLES would need EGL and the browser backend is for the diff --git a/README.ko.md b/README.ko.md index 4a1ee0c..87f4d60 100644 --- a/README.ko.md +++ b/README.ko.md @@ -166,7 +166,8 @@ iPhone 17의 Safari에서는 [벤치마크 페이지](https://with-developer.git | 경로 | 내용 | |---|---| -| `crates/emberwave-core` | 비트스트림 파서, CPU 레퍼런스 디코더, 색 변환, wgpu/WGSL 디코더, CPU·GPU 인코더 | +| `crates/emberwave-core` | 비트스트림 파서, CPU 레퍼런스 디코더, 색 변환, CPU 인코더(GPU 없이) | +| `crates/emberwave-wgpu` | wgpu/WGSL 디코더와 GPU 인코더(결정 D75) | | `crates/emberwave-cli` | 명령줄 도구 `emberwave-cli` | | `crates/emberwave-ffi` | C API: 헤더, 라이브러리, C 예제 | | `crates/emberwave-web`, `web/` | 브라우저 플레이어와 벤치마크: WebAssembly 모듈과 페이지 | diff --git a/README.md b/README.md index 53f641f..26f0b67 100644 --- a/README.md +++ b/README.md @@ -164,7 +164,8 @@ Next, each in a release when it is ready: | Path | Purpose | |---|---| -| `crates/emberwave-core` | Bitstream parser, CPU reference decoder, colour conversion, the wgpu/WGSL decoder, and the encoder on the CPU and the GPU | +| `crates/emberwave-core` | Bitstream parser, CPU reference decoder, colour conversion and the CPU encoder, without a GPU | +| `crates/emberwave-wgpu` | The wgpu/WGSL decoder and the GPU encoder (decision D75) | | `crates/emberwave-cli` | `emberwave-cli` command line tool | | `crates/emberwave-ffi` | The C API: header, library and C examples | | `crates/emberwave-web`, `web/` | The browser player and its benchmark: WebAssembly module and pages | diff --git a/crates/emberwave-cli/Cargo.toml b/crates/emberwave-cli/Cargo.toml index 5226f3f..e1b3d7f 100644 --- a/crates/emberwave-cli/Cargo.toml +++ b/crates/emberwave-cli/Cargo.toml @@ -12,6 +12,7 @@ categories = ["multimedia::video", "command-line-utilities"] [dependencies] emberwave-core.workspace = true +emberwave-wgpu.workspace = true clap.workspace = true png.workspace = true # For pictures in textures (bench-encode --textures). diff --git a/crates/emberwave-cli/src/bench.rs b/crates/emberwave-cli/src/bench.rs index dc46d83..1020f04 100644 --- a/crates/emberwave-cli/src/bench.rs +++ b/crates/emberwave-cli/src/bench.rs @@ -6,7 +6,7 @@ use std::time::{Duration, Instant}; use clap::ValueEnum; use emberwave_core::bitstream::Pwv1File; -use emberwave_core::gpu::{Decoder, TimedOutput, Timings}; +use emberwave_wgpu::{Decoder, TimedOutput, Timings}; use crate::stats::Summary; use crate::{ColorArgs, GpuArgs, Result, chroma_name}; diff --git a/crates/emberwave-cli/src/bench_encode.rs b/crates/emberwave-cli/src/bench_encode.rs index e015b5e..882a866 100644 --- a/crates/emberwave-cli/src/bench_encode.rs +++ b/crates/emberwave-cli/src/bench_encode.rs @@ -7,7 +7,7 @@ use emberwave_core::bitstream::consts::HEADER_BYTES; use emberwave_core::bitstream::{ChromaSubsampling, Component, FrameLayout}; use emberwave_core::color::{RgbOrder, yuv_to_rgb8}; use emberwave_core::encode::{self, Signalling}; -use emberwave_core::gpu; +use emberwave_wgpu as gpu; use crate::bench::{Series, json_object, ms, parse_seconds, print_table, quote, warm_up}; use crate::{Backend, GpuArgs, Result, chroma_name, y4m}; diff --git a/crates/emberwave-cli/src/decode.rs b/crates/emberwave-cli/src/decode.rs index c995f42..1d7f4ef 100644 --- a/crates/emberwave-cli/src/decode.rs +++ b/crates/emberwave-cli/src/decode.rs @@ -7,7 +7,7 @@ use std::time::Instant; use clap::ValueEnum; use emberwave_core::bitstream::Pwv1File; -use emberwave_core::gpu::Decoder; +use emberwave_wgpu::Decoder; use crate::stats::Summary; use crate::{ColorArgs, GpuArgs, MatrixChoice, RangeChoice, Result, read_file, y4m}; diff --git a/crates/emberwave-cli/src/encode.rs b/crates/emberwave-cli/src/encode.rs index e7d09b6..a9f0ab4 100644 --- a/crates/emberwave-cli/src/encode.rs +++ b/crates/emberwave-cli/src/encode.rs @@ -12,7 +12,7 @@ use emberwave_core::bitstream::{ ChromaSubsampling, ColorPrimaries, Pwv1Header, SequenceHeader, TransferFunction, YcbcrTransform, }; use emberwave_core::encode::{self, Signalling}; -use emberwave_core::gpu; +use emberwave_wgpu as gpu; use crate::stats::Summary; use crate::{Backend, GpuArgs, Result, chroma_name, siting_name, y4m}; diff --git a/crates/emberwave-cli/src/main.rs b/crates/emberwave-cli/src/main.rs index 2487988..4b42a93 100644 --- a/crates/emberwave-cli/src/main.rs +++ b/crates/emberwave-cli/src/main.rs @@ -34,7 +34,7 @@ use std::process::ExitCode; use clap::{Args, Parser, Subcommand, ValueEnum}; use emberwave_core::bitstream::{ChromaSiting, SequenceHeader, YcbcrRange}; use emberwave_core::color::{ColorMatrix, ColorParams}; -use emberwave_core::gpu::{GpuContext, GpuOptions, parse_backends}; +use emberwave_wgpu::{GpuContext, GpuOptions, parse_backends}; /// The error type of the command line tool: anything that can be printed. pub type Result = std::result::Result>; diff --git a/crates/emberwave-core/Cargo.toml b/crates/emberwave-core/Cargo.toml index 98c0e97..c29d6fa 100644 --- a/crates/emberwave-core/Cargo.toml +++ b/crates/emberwave-core/Cargo.toml @@ -1,33 +1,20 @@ [package] name = "emberwave-core" -description = "PyroWave bitstream parser, and wgpu/WGSL decoder and encoder" +description = "PyroWave bitstream parser, CPU decoder and encoder, without a GPU: the GPU decoder and encoder are emberwave-wgpu" version.workspace = true edition.workspace = true license.workspace = true repository.workspace = true rust-version.workspace = true readme = "../../README.md" -keywords = ["pyrowave", "video", "codec", "wavelet", "wgpu"] -categories = ["multimedia::video", "multimedia::encoding", "graphics"] - -[features] -default = ["gpu"] -# The wgpu decoder and encoder. Without it only the bitstream parser, the CPU -# reference decoder and the CPU encoder are built. -gpu = ["dep:wgpu", "dep:pollster", "dep:bytemuck"] +keywords = ["pyrowave", "video", "codec", "wavelet"] +categories = ["multimedia::video", "multimedia::encoding"] [dependencies] thiserror.workspace = true -wgpu = { workspace = true, optional = true } -pollster = { workspace = true, optional = true } -bytemuck = { workspace = true, optional = true } [dev-dependencies] proptest.workspace = true -naga.workspace = true -# The tests count wgpu's live resources to show that decoding allocates -# nothing per frame; the counters cost a little, so only tests turn them on. -wgpu = { workspace = true, features = ["counters"] } [lints] workspace = true diff --git a/crates/emberwave-core/src/color.rs b/crates/emberwave-core/src/color.rs index b296e2f..326457c 100644 --- a/crates/emberwave-core/src/color.rs +++ b/crates/emberwave-core/src/color.rs @@ -388,12 +388,8 @@ impl ForwardMatrix { /// An error if `bytes` of an RGB picture of `width` x `height` pixels, four /// bytes each, with rows `stride` bytes apart, do not hold it. -pub(crate) fn check_rgb( - bytes: usize, - stride: usize, - width: u32, - height: u32, -) -> Result<(), ColorError> { +#[doc(hidden)] +pub fn check_rgb(bytes: usize, stride: usize, width: u32, height: u32) -> Result<(), ColorError> { let row = u64::from(width) * 4; if (stride as u64) < row && height > 1 { return Err(ColorError::StrideTooSmall { stride, row }); diff --git a/crates/emberwave-core/src/cpu/mod.rs b/crates/emberwave-core/src/cpu/mod.rs index 0daaf9c..8ecb8e7 100644 --- a/crates/emberwave-core/src/cpu/mod.rs +++ b/crates/emberwave-core/src/cpu/mod.rs @@ -107,7 +107,7 @@ pub const CONCEALMENT_THRESHOLD: f32 = 0.03; /// them, and keeps what the last decode left of the frame's detail, so that /// a frame drawn in part conceals the blocks it lacks where the picture is /// still (decision D66). The GPU decoder does the same with -/// [`set_concealment`](crate::gpu::Decoder::set_concealment). +/// `emberwave_wgpu::Decoder::set_concealment`. #[derive(Debug, Clone, Default)] pub struct Concealer { /// The coefficients the last decode left, and the layout of its frames. diff --git a/crates/emberwave-core/src/encode/fdwt.rs b/crates/emberwave-core/src/encode/fdwt.rs index 4924b32..80fcd2e 100644 --- a/crates/emberwave-core/src/encode/fdwt.rs +++ b/crates/emberwave-core/src/encode/fdwt.rs @@ -12,7 +12,7 @@ use crate::cpu::idwt::{ALPHA, BETA, DELTA, GAMMA, INV_K, K, PADDING, mirror}; /// hold the low-pass and odd positions the high-pass samples, as the inverse /// transform takes them. The line length must be even and larger than the /// padding, which holds for every level of a valid frame. -pub(crate) fn forward_line(line: &mut [f32], extended: &mut Vec) { +pub fn forward_line(line: &mut [f32], extended: &mut Vec) { let len = line.len(); debug_assert!( len > PADDING && len.is_multiple_of(2), @@ -54,7 +54,7 @@ pub(crate) fn forward_line(line: &mut [f32], extended: &mut Vec) { /// The four bands of one level, each half the width and height of its input. #[derive(Debug, Clone, PartialEq)] -pub(crate) struct Level { +pub struct Level { /// Low-pass in both directions; the next level's input. pub ll: Vec, /// High-pass horizontally (odd columns). @@ -68,7 +68,7 @@ pub(crate) struct Level { /// One level of the 2-D forward transform of a `width` x `height` image, /// row-major: rows first, then columns, then the samples sorted into the four /// bands, as [`crate::cpu::idwt::inverse_2d`] expects them. -pub(crate) fn forward_2d(mut image: Vec, width: usize, height: usize) -> Level { +pub fn forward_2d(mut image: Vec, width: usize, height: usize) -> Level { let mut extended = Vec::new(); for row in image.chunks_exact_mut(width) { forward_line(row, &mut extended); @@ -104,7 +104,7 @@ pub(crate) fn forward_2d(mut image: Vec, width: usize, height: usize) -> Le /// An 8-bit sample as the transform takes it: scaled to `[0, 1]`, less the DC /// shift that the decoder adds back. -pub(crate) fn sample_level(sample: u8) -> f32 { +pub fn sample_level(sample: u8) -> f32 { f32::from(sample) / 255.0 - DC_SHIFT } @@ -112,7 +112,7 @@ pub(crate) fn sample_level(sample: u8) -> f32 { /// ([`sample_level`]), padded to `aligned_width` x `aligned_height` by /// repeating the last column and the last row. Repeating the edge keeps the /// padding from adding detail that would cost bits. -pub(crate) fn pad_plane( +pub fn pad_plane( samples: &[u8], width: usize, height: usize, diff --git a/crates/emberwave-core/src/encode/mod.rs b/crates/emberwave-core/src/encode/mod.rs index 5db9a31..f022b67 100644 --- a/crates/emberwave-core/src/encode/mod.rs +++ b/crates/emberwave-core/src/encode/mod.rs @@ -18,10 +18,15 @@ //! //! A frame decodes with any decoder of bitstream v1, upstream's included. -pub(crate) mod fdwt; +// The stages that emberwave-wgpu's GPU encoder shares with this one: hidden, +// not part of the API (decision D75). +#[doc(hidden)] +pub mod fdwt; pub(crate) mod pack; -pub(crate) mod quant; -pub(crate) mod rate; +#[doc(hidden)] +pub mod quant; +#[doc(hidden)] +pub mod rate; mod weights; use thiserror::Error; @@ -128,7 +133,8 @@ pub enum EncodeError { /// levels. They come first in block index order, every level's bands /// before those of the next finer level, so they are the blocks below the /// index returned (decision D58). -pub(crate) fn pristine_blocks(layout: &FrameLayout) -> u32 { +#[doc(hidden)] +pub fn pristine_blocks(layout: &FrameLayout) -> u32 { const { // One band would be the coarsest LL band alone, whose blocks the // detail bands of each component interleave: not a prefix. @@ -146,11 +152,13 @@ pub(crate) fn pristine_blocks(layout: &FrameLayout) -> u32 { /// The wavelet coefficients of a picture: `[component][level][band]`, /// row-major at the size of the level's bands; empty where a component has /// no such band. -pub(crate) type Bands = [[[Vec; 4]; DECOMPOSITION_LEVELS]; NUM_COMPONENTS]; +#[doc(hidden)] +pub type Bands = [[[Vec; 4]; DECOMPOSITION_LEVELS]; NUM_COMPONENTS]; /// One quantised 32x32 block and what the rate control needs to know of it. #[derive(Debug, Clone)] -pub(crate) struct Block32 { +#[doc(hidden)] +pub struct Block32 { pub index: u32, pub quant: BandQuant, pub blocks8: Blocks8, @@ -272,7 +280,8 @@ impl Encoder { } /// The forward transform of a picture whose planes have the right sizes. - pub(crate) fn transform(&self, planes: [&[u8]; 3]) -> Bands { + #[doc(hidden)] + pub fn transform(&self, planes: [&[u8]; 3]) -> Bands { let layout = &self.layout; let mut bands: Bands = Default::default(); for (component, plane) in Component::ALL.into_iter().zip(planes) { @@ -307,7 +316,8 @@ impl Encoder { /// Quantises the coefficients: every block of the frame, in block index /// order, with its costs. - pub(crate) fn quantise(&self, bands: &Bands) -> Vec { + #[doc(hidden)] + pub fn quantise(&self, bands: &Bands) -> Vec { let layout = &self.layout; let pristine = pristine_blocks(layout); let mut blocks = Vec::with_capacity(layout.block_count() as usize); @@ -354,7 +364,8 @@ impl Encoder { } /// The header of a PWV1 file of a stream of `layout` with `signalling`. -pub(crate) fn stream_header(layout: &FrameLayout, signalling: &Signalling) -> SequenceHeader { +#[doc(hidden)] +pub fn stream_header(layout: &FrameLayout, signalling: &Signalling) -> SequenceHeader { SequenceHeader { width: layout.width(), height: layout.height(), @@ -372,13 +383,15 @@ pub(crate) fn stream_header(layout: &FrameLayout, signalling: &Signalling) -> Se /// The sequence number of the frame after one numbered `sequence`. The first /// frame is number 1, as with upstream's encoder. -pub(crate) fn next_sequence(sequence: u8) -> u8 { +#[doc(hidden)] +pub fn next_sequence(sequence: u8) -> u8 { (sequence + 1) & 0x7 } /// The start of frame header of frame `sequence` of `stream`, which carries /// `total_blocks` blocks. -pub(crate) fn start_of_frame( +#[doc(hidden)] +pub fn start_of_frame( stream: &SequenceHeader, sequence: u8, total_blocks: u32, @@ -396,7 +409,8 @@ pub(crate) fn start_of_frame( } /// An error unless `planes` have the sizes of [`FrameLayout::plane_size`]. -pub(crate) fn check_planes(layout: &FrameLayout, planes: [&[u8]; 3]) -> Result<(), EncodeError> { +#[doc(hidden)] +pub fn check_planes(layout: &FrameLayout, planes: [&[u8]; 3]) -> Result<(), EncodeError> { for (component, plane) in Component::ALL.into_iter().zip(planes) { let (width, height) = layout.plane_size(component); let expected = width as usize * height as usize; @@ -415,9 +429,8 @@ pub(crate) fn check_planes(layout: &FrameLayout, planes: [&[u8]; 3]) -> Result<( /// with their rows `strides` bytes apart: each at least its width, and at /// least `(height - 1) * stride + width` bytes in the plane. For the GPU /// encoder's strided input. -#[cfg(feature = "gpu")] -#[cfg_attr(target_arch = "wasm32", allow(dead_code))] -pub(crate) fn check_strided_planes( +#[doc(hidden)] +pub fn check_strided_planes( layout: &FrameLayout, planes: [&[u8]; 3], strides: [usize; 3], diff --git a/crates/emberwave-core/src/encode/quant.rs b/crates/emberwave-core/src/encode/quant.rs index 2bc592d..84934ed 100644 --- a/crates/emberwave-core/src/encode/quant.rs +++ b/crates/emberwave-core/src/encode/quant.rs @@ -16,10 +16,10 @@ use crate::bitstream::consts::{ use crate::bitstream::{Band, BandLayout, ChromaSubsampling, Component}; /// Numbers of dropped bit-planes the rate control chooses from: 0 to 15. -pub(crate) const DROP_STEPS: usize = 16; +pub const DROP_STEPS: usize = 16; /// Coefficients of an 8x8 block. -pub(crate) const BLOCK8_VALUES: usize = SUBBLOCKS_PER_BLOCK8 * VALUES_PER_SUBBLOCK; +pub const BLOCK8_VALUES: usize = SUBBLOCKS_PER_BLOCK8 * VALUES_PER_SUBBLOCK; /// The largest bit exponent of a band: coefficients are scaled by at most /// `2^12` before quantisation, which keeps every block within 15 base @@ -56,7 +56,7 @@ const INVERSE_SCALES: [f32; MAX_SCALE_CODE as usize + 1] = { /// in `c * 2^b` costs about the same in the picture in every band, as `4^b` /// follows the energy the inverse transform gives a coefficient of the band. /// Low-pass bands and coarser levels get more bits, chroma one bit less. -pub(crate) fn band_exponent(component: Component, level: usize, band: Band) -> i32 { +pub fn band_exponent(component: Component, level: usize, band: Band) -> i32 { let band_bits = match band { Band::Ll => 2, Band::Hl | Band::Lh => 1, @@ -67,7 +67,7 @@ pub(crate) fn band_exponent(component: Component, level: usize, band: Band) -> i /// How a band is quantised: its capped exponent and its distortion weight. #[derive(Debug, Clone, Copy, PartialEq)] -pub(crate) struct BandQuant { +pub struct BandQuant { /// The capped bit exponent: coefficients are quantised as `c * 2^exponent`. pub exponent: i32, /// What a squared coefficient error of the band counts for in the rate @@ -76,12 +76,7 @@ pub(crate) struct BandQuant { } impl BandQuant { - pub(crate) fn new( - chroma: ChromaSubsampling, - component: Component, - level: usize, - band: Band, - ) -> Self { + pub fn new(chroma: ChromaSubsampling, component: Component, level: usize, band: Band) -> Self { let class = match (component, chroma) { (Component::Y, _) => 0, (_, ChromaSubsampling::Yuv420) => 1, @@ -96,13 +91,13 @@ impl BandQuant { /// The most bit-planes a block of the band may drop: the decoder's block /// scale is `2^(4 - (quant_code >> 3))`, and the exponent `4 + b - q` of /// the quant code cannot go below zero. - pub(crate) fn max_drop(&self) -> u8 { + pub fn max_drop(&self) -> u8 { (self.exponent + MAX_SCALE_EXP).clamp(0, DROP_STEPS as i32 - 1) as u8 } /// The quant code of a block of the band that drops `drop` bit-planes: /// block scale `2^(drop - b)`, mantissa zero. - pub(crate) fn quant_code(&self, drop: u8) -> u8 { + pub fn quant_code(&self, drop: u8) -> u8 { ((self.exponent + MAX_SCALE_EXP - i32::from(drop)) as u8) << QUANT_MANTISSA_BITS } } @@ -110,7 +105,7 @@ impl BandQuant { /// The position of coefficient `index` (subblock, then value) in its 8x8 /// block: subblocks run down two columns of four, values down the two rows /// of a subblock's four columns (`bitstream.md`, "Decoding 8x8 blocks"). -pub(crate) fn value_position(index: usize) -> (usize, usize) { +pub fn value_position(index: usize) -> (usize, usize) { let (subblock, value) = (index / VALUES_PER_SUBBLOCK, index % VALUES_PER_SUBBLOCK); let x = subblock / 4 * SUBBLOCK_WIDTH + value / SUBBLOCK_HEIGHT; let y = subblock % 4 * SUBBLOCK_HEIGHT + value % SUBBLOCK_HEIGHT; @@ -120,7 +115,7 @@ pub(crate) fn value_position(index: usize) -> (usize, usize) { /// The coefficients of the 8x8 block `raster` (0 to 15, row-major) of the /// 32x32 block at (`block_x`, `block_y`) of a band, in coefficient order. /// Positions outside the band are zero. -pub(crate) fn gather_block8( +pub fn gather_block8( band: &[f32], layout: &BandLayout, block_x: u32, @@ -143,7 +138,7 @@ pub(crate) fn gather_block8( /// One quantised 8x8 block and what dropping bit-planes does to it. #[derive(Debug, Clone, PartialEq)] -pub(crate) struct Block8 { +pub struct Block8 { /// The 8x8 scale code, so that the scale is `code / 8 + 0.25`. pub scale_code: u8, /// Magnitudes in coefficient order, with no plane dropped. @@ -166,17 +161,17 @@ pub(crate) struct Block8 { impl Block8 { /// Whether the block is coded with `drop` planes dropped: some subblock /// keeps a plane above the base. Otherwise every magnitude is zero. - pub(crate) fn active(&self, drop: u8) -> bool { + pub fn active(&self, drop: u8) -> bool { self.plane_bytes[usize::from(drop)] != 0 } /// Bit-planes of subblock `subblock` with `drop` planes dropped. - pub(crate) fn subblock_planes(&self, subblock: usize, drop: u8) -> u8 { + pub fn subblock_planes(&self, subblock: usize, drop: u8) -> u8 { self.planes[subblock].saturating_sub(drop) } /// Base bit-planes with `drop` planes dropped. - pub(crate) fn base_planes(&self, drop: u8) -> u8 { + pub fn base_planes(&self, drop: u8) -> u8 { self.base.saturating_sub(drop) } } @@ -191,10 +186,7 @@ impl Block8 { /// puts the reconstruction in the middle of each step. The base bit-planes /// are all but the top three of the largest magnitude, and each 4x2 /// subblock has as many more as its own largest magnitude needs, 0 to 3. -pub(crate) fn analyse_block8( - coefficients: &[f32; BLOCK8_VALUES], - quant: &BandQuant, -) -> Option { +pub fn analyse_block8(coefficients: &[f32; BLOCK8_VALUES], quant: &BandQuant) -> Option { let resolution = exact_pow2(quant.exponent); let scaled = coefficients.map(|c| (c * resolution).abs()); let largest = scaled.iter().copied().fold(0.0f32, f32::max); @@ -298,7 +290,7 @@ pub(crate) fn analyse_block8( } /// The 8x8 blocks of one 32x32 block, those that carry anything. -pub(crate) type Blocks8 = [Option; BLOCK8_PER_BLOCK]; +pub type Blocks8 = [Option; BLOCK8_PER_BLOCK]; #[cfg(test)] mod tests { diff --git a/crates/emberwave-core/src/encode/rate.rs b/crates/emberwave-core/src/encode/rate.rs index aa83555..09f314b 100644 --- a/crates/emberwave-core/src/encode/rate.rs +++ b/crates/emberwave-core/src/encode/rate.rs @@ -17,7 +17,7 @@ use super::quant::DROP_STEPS; /// Number of keys. -pub(crate) const KEYS: usize = 512; +pub const KEYS: usize = 512; /// 2^`exponent` as an exact `f32`, for exponents in the normal range. fn exact_pow2(exponent: i32) -> f32 { @@ -37,7 +37,7 @@ fn threshold(key: usize) -> f32 { /// The key of a step that adds `distortion` and saves `saving` words: the /// highest threshold it reaches, 0 for none (including a step that adds no /// distortion at all). -pub(crate) fn key(distortion: f32, saving: u16) -> u16 { +pub fn key(distortion: f32, saving: u16) -> u16 { let saving = f32::from(saving); let reaches = |key: usize| distortion >= saving * threshold(key); // The thresholds increase: find the first one above 0 not reached. @@ -55,7 +55,7 @@ pub(crate) fn key(distortion: f32, saving: u16) -> u16 { /// What the rate control knows of one 32x32 block. #[derive(Debug, Clone, PartialEq)] -pub(crate) struct BlockCost { +pub struct BlockCost { /// Size in words with 0 to 15 planes dropped; 0 when nothing is left to /// send, except for the blocks of the coarsest level, which every frame /// carries: at least `pack::EMPTY_BLOCK_WORDS` (decision D58). Never @@ -70,7 +70,7 @@ pub(crate) struct BlockCost { /// A step of a block: drop planes up to `drop`, saving `saving` words. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) struct Step { +pub struct Step { pub key: u16, pub block: u32, pub drop: u8, @@ -80,7 +80,7 @@ pub(crate) struct Step { /// The numbers of planes a block may drop that are worth considering: for /// each size the block can have, the one with the least distortion (the /// fewest planes on a tie). Sizes decrease along the list. -pub(crate) fn points(cost: &BlockCost) -> Vec { +pub fn points(cost: &BlockCost) -> Vec { let mut points: Vec = Vec::new(); for drop in 0..=cost.max_drop.min(DROP_STEPS as u8 - 1) { let (words, distortion) = ( @@ -102,7 +102,7 @@ pub(crate) fn points(cost: &BlockCost) -> Vec { /// Appends the steps of block `block` in the order they must be applied: /// from each of its [`points`] to the next. A step's key is at least that of /// the step before it. -pub(crate) fn steps(block: u32, cost: &BlockCost, out: &mut Vec) { +pub fn steps(block: u32, cost: &BlockCost, out: &mut Vec) { let mut previous_key = 0u16; for pair in points(cost).windows(2) { let (from, to) = (usize::from(pair[0]), usize::from(pair[1])); @@ -122,7 +122,7 @@ pub(crate) fn steps(block: u32, cost: &BlockCost, out: &mut Vec) { /// How many planes each block drops so that all of them together take at /// most `budget_words`, or `None` if they do not fit even with every block /// dropping all it may. -pub(crate) fn choose(costs: &[BlockCost], budget_words: u64) -> Option> { +pub fn choose(costs: &[BlockCost], budget_words: u64) -> Option> { // Each block starts at the best drop that costs what dropping none does. let mut drops: Vec = costs.iter().map(|cost| points(cost)[0]).collect(); let total: u64 = costs.iter().map(|cost| u64::from(cost.words[0])).sum(); diff --git a/crates/emberwave-core/src/lib.rs b/crates/emberwave-core/src/lib.rs index cb004b1..3a1e382 100644 --- a/crates/emberwave-core/src/lib.rs +++ b/crates/emberwave-core/src/lib.rs @@ -1,33 +1,23 @@ //! Core library of emberwave, a portable (wgpu) port of the PyroWave -//! low-latency intra-frame wavelet video codec. +//! low-latency intra-frame wavelet video codec: everything that needs no GPU. //! //! - [`bitstream`]: the PyroWave v1 bitstream (pure Rust, GPU independent). //! - [`cpu`]: a slow reference decoder used as a test oracle. //! - [`color`]: YCbCr to RGB conversion, shared by the CPU and GPU paths. //! - [`encode`]: an encoder on the CPU, the reference of the GPU's. -//! - [`gpu`] (feature `gpu`, on by default): the wgpu/WGSL decoder and -//! encoder. //! -//! See `ARCHITECTURE.md` for the design. +//! The wgpu/WGSL decoder and encoder are the crate `emberwave-wgpu`, whose +//! version follows wgpu's: this crate has no wgpu type in its API (decision +//! D75). See `ARCHITECTURE.md` for the design. //! -//! Items hidden from this documentation are there for emberwave's own tests -//! and tools: they are not part of the API, and any release may change them. -//! With the `gpu` feature, [`wgpu`] is the version emberwave is built with, -//! whose types the GPU calls take: use it to share a device or a texture. - -// The docs link to the calls that wait for the GPU, which the browser build -// leaves out (decision D70). -#![cfg_attr(target_arch = "wasm32", allow(rustdoc::broken_intra_doc_links))] - -#[cfg(feature = "gpu")] -pub use wgpu; +//! Items hidden from this documentation are there for emberwave's own crates, +//! tests and tools, `emberwave-wgpu` among them: they are not part of the API, +//! and any release may change them. pub mod bitstream; pub mod color; pub mod cpu; pub mod encode; -#[cfg(feature = "gpu")] -pub mod gpu; /// Version of the `emberwave-core` crate. pub const VERSION: &str = env!("CARGO_PKG_VERSION"); diff --git a/crates/emberwave-core/tests/common/mod.rs b/crates/emberwave-core/tests/common/mod.rs index 4275496..937ca73 100644 --- a/crates/emberwave-core/tests/common/mod.rs +++ b/crates/emberwave-core/tests/common/mod.rs @@ -5,62 +5,6 @@ use std::path::{Path, PathBuf}; -/// Whether a missing GPU is a failure rather than a reason to skip. An empty -/// value counts as unset so a CI matrix can leave it blank. -#[cfg(feature = "gpu")] -pub fn gpu_required() -> bool { - std::env::var_os("EMBERWAVE_REQUIRE_GPU").is_some_and(|value| !value.is_empty()) -} - -/// Creates a context, or returns `None` if there is no GPU and none is required. -#[cfg(feature = "gpu")] -pub fn create_context( - options: &emberwave_core::gpu::GpuOptions, -) -> Option { - match emberwave_core::gpu::GpuContext::new(options) { - Ok(context) => { - eprintln!("GPU tests run on {:?}", context.adapter_info()); - Some(context) - } - Err(error) => { - assert!( - !gpu_required(), - "a GPU is required but none is available: {error}" - ); - eprintln!("no GPU available, skipping: {error}"); - None - } - } -} - -/// Every count of live GPU objects and memory that wgpu keeps for a context's -/// device (the tests build wgpu with its `counters` feature), as text: buffers, -/// textures and their views, bind groups and their layouts, pipelines, -/// samplers, command encoders, shader modules, query sets, fences, memory. -/// wgpu 30 keeps the object counts on Vulkan, Metal and DX12; Metal leaves the -/// memory at zero, and no backend counts memory allocations. -#[cfg(feature = "gpu")] -pub fn live_resources(context: &emberwave_core::gpu::GpuContext) -> String { - format!("{:?}", context.device().get_internal_counters().hal) -} - -/// The options the tests start from: the defaults, with the backends that -/// `EMBERWAVE_BACKEND` names, so that a run can force a backend, as the -/// command line tool does. A value that names none is ignored. -#[cfg(feature = "gpu")] -pub fn options() -> emberwave_core::gpu::GpuOptions { - emberwave_core::gpu::GpuOptions::from_env().unwrap_or_default() -} - -/// The GPU context shared by the tests of one test binary, or `None` if -/// there is no GPU and none is required. -#[cfg(feature = "gpu")] -pub fn shared_context() -> Option<&'static emberwave_core::gpu::GpuContext> { - static CONTEXT: std::sync::OnceLock> = - std::sync::OnceLock::new(); - CONTEXT.get_or_init(|| create_context(&options())).as_ref() -} - /// Directory with the committed vectors and their reference decodes. pub fn testdata_dir() -> PathBuf { Path::new(env!("CARGO_MANIFEST_DIR")).join("../../testdata") diff --git a/crates/emberwave-ffi/Cargo.toml b/crates/emberwave-ffi/Cargo.toml index cc2997c..812919f 100644 --- a/crates/emberwave-ffi/Cargo.toml +++ b/crates/emberwave-ffi/Cargo.toml @@ -15,6 +15,7 @@ crate-type = ["cdylib", "rlib"] [dependencies] emberwave-core.workspace = true +emberwave-wgpu.workspace = true wgpu.workspace = true # A context on the caller's own Metal device and queue diff --git a/crates/emberwave-ffi/src/lib.rs b/crates/emberwave-ffi/src/lib.rs index 5af9aaf..9254ab3 100644 --- a/crates/emberwave-ffi/src/lib.rs +++ b/crates/emberwave-ffi/src/lib.rs @@ -46,7 +46,7 @@ use emberwave_core::bitstream::{ }; use emberwave_core::color::{ColorMatrix, ColorParams, RgbOrder}; use emberwave_core::encode::{self, EncodeError, Signalling}; -use emberwave_core::gpu::{ +use emberwave_wgpu::{ Decoder, Encoder, GpuContext, GpuError, GpuOptions, QueueTurns, TexturePicture, }; @@ -2880,7 +2880,7 @@ unsafe fn d3d12_fences( sync: *const EmberwaveD3D12Sync, context_id: u64, textures: &[&EmberwaveTexture], -) -> Result, Failure> { +) -> Result, Failure> { // SAFETY: as the caller promises. let sync = unsafe { read_struct(sync, "sync") }?.unwrap_or_default(); // SAFETY: as the caller promises. @@ -2909,7 +2909,7 @@ fn d3d12_hooks( wait: Option<(&EmberwaveD3D12Fence, u64)>, signal: Option<(&EmberwaveD3D12Fence, u64)>, shared: Vec, -) -> Box { +) -> Box { Box::new(d3d12::Fences::new(wait, signal, shared)) } @@ -2920,9 +2920,9 @@ fn d3d12_hooks( _wait: Option<(&EmberwaveD3D12Fence, u64)>, _signal: Option<(&EmberwaveD3D12Fence, u64)>, _shared: Vec, -) -> Box { +) -> Box { struct Nothing; - impl emberwave_core::gpu::SubmissionHooks for Nothing { + impl emberwave_wgpu::SubmissionHooks for Nothing { fn before_submit(&mut self, _queue: &wgpu::Queue) {} fn after_submit(&mut self, _queue: &wgpu::Queue, _submitted: bool) {} } @@ -3088,9 +3088,9 @@ fn vulkan_semaphores(sync: EmberwaveVulkanSync) -> vulkan::Semaphores { target_os = "android", all(windows, target_pointer_width = "64") )))] -fn vulkan_semaphores(_sync: EmberwaveVulkanSync) -> impl emberwave_core::gpu::SubmissionHooks { +fn vulkan_semaphores(_sync: EmberwaveVulkanSync) -> impl emberwave_wgpu::SubmissionHooks { struct Nothing; - impl emberwave_core::gpu::SubmissionHooks for Nothing { + impl emberwave_wgpu::SubmissionHooks for Nothing { fn before_submit(&mut self, _queue: &wgpu::Queue) {} fn after_submit(&mut self, _queue: &wgpu::Queue, _submitted: bool) {} } @@ -3165,7 +3165,7 @@ mod vulkan { use std::ffi::{CStr, c_char, c_void}; use ash::vk::{self, Handle}; - use emberwave_core::gpu::{ + use emberwave_wgpu::{ CallerQueueLock, GpuContext, GpuOptions, PLANE_FORMAT, QueueTurns, SubmissionHooks, }; use wgpu::hal::api::Vulkan; @@ -3773,7 +3773,7 @@ mod d3d12 { use std::ffi::c_void; use std::sync::Arc; - use emberwave_core::gpu::{GpuContext, GpuOptions, PLANE_FORMAT, QueueTurns, SubmissionHooks}; + use emberwave_wgpu::{GpuContext, GpuOptions, PLANE_FORMAT, QueueTurns, SubmissionHooks}; use wgpu::hal::api::Dx12; use windows::Win32::Foundation::{HANDLE, LUID}; use windows::Win32::Graphics::Direct3D12::{ @@ -4848,7 +4848,7 @@ unsafe fn metal_import( let (width, height) = wrapping.size(); let format = metal.pixelFormat(); let format = match wrapping.holds { - Holds::Plane(_) if format == MTLPixelFormat::R8Unorm => emberwave_core::gpu::PLANE_FORMAT, + Holds::Plane(_) if format == MTLPixelFormat::R8Unorm => emberwave_wgpu::PLANE_FORMAT, Holds::Chroma if format == MTLPixelFormat::RG8Unorm => wgpu::TextureFormat::Rg8Unorm, Holds::Picture if format == MTLPixelFormat::RGBA8Unorm => wgpu::TextureFormat::Rgba8Unorm, Holds::Picture if format == MTLPixelFormat::BGRA8Unorm => wgpu::TextureFormat::Bgra8Unorm, diff --git a/crates/emberwave-ffi/tests/api.rs b/crates/emberwave-ffi/tests/api.rs index 890832f..a3c27fb 100644 --- a/crates/emberwave-ffi/tests/api.rs +++ b/crates/emberwave-ffi/tests/api.rs @@ -11,8 +11,8 @@ use std::ptr; use emberwave_core::bitstream::consts::DECOMPOSITION_LEVELS; use emberwave_core::bitstream::{FrameLayout, Header, Pwv1File}; use emberwave_core::color::ColorParams; -use emberwave_core::gpu::{Decoder, GpuContext, GpuOptions}; use emberwave_ffi::*; +use emberwave_wgpu::{Decoder, GpuContext, GpuOptions}; fn testdata(name: &str) -> Vec { let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")) diff --git a/crates/emberwave-ffi/tests/encoder.rs b/crates/emberwave-ffi/tests/encoder.rs index e90b612..b70319b 100644 --- a/crates/emberwave-ffi/tests/encoder.rs +++ b/crates/emberwave-ffi/tests/encoder.rs @@ -14,8 +14,8 @@ use emberwave_core::bitstream::{ }; use emberwave_core::color::{ColorMatrix, ColorParams, RgbOrder, rgb_to_ycbcr8}; use emberwave_core::encode::{self, Signalling}; -use emberwave_core::gpu::{Encoder, GpuContext, GpuOptions}; use emberwave_ffi::*; +use emberwave_wgpu::{Encoder, GpuContext, GpuOptions}; fn last_error() -> String { // SAFETY: emberwave_last_error always returns a C string. diff --git a/crates/emberwave-web/Cargo.toml b/crates/emberwave-web/Cargo.toml index d332b1d..63dc15f 100644 --- a/crates/emberwave-web/Cargo.toml +++ b/crates/emberwave-web/Cargo.toml @@ -15,6 +15,7 @@ crate-type = ["cdylib", "rlib"] # The versions follow what wgpu 30 itself requires. [target.'cfg(target_arch = "wasm32")'.dependencies] emberwave-core.workspace = true +emberwave-wgpu.workspace = true wgpu = { workspace = true, features = ["webgpu"] } wasm-bindgen = "0.2.127" wasm-bindgen-futures = "0.4.77" diff --git a/crates/emberwave-web/src/bench.rs b/crates/emberwave-web/src/bench.rs index bc98435..ba66af0 100644 --- a/crates/emberwave-web/src/bench.rs +++ b/crates/emberwave-web/src/bench.rs @@ -11,7 +11,7 @@ use std::task::{Context, Poll, Waker}; use emberwave_core::bitstream::ChromaSubsampling; use emberwave_core::color::ColorParams; use emberwave_core::encode::{self, Signalling}; -use emberwave_core::gpu::{Decoder, GpuContext, GpuOptions}; +use emberwave_wgpu::{Decoder, GpuContext, GpuOptions}; use wasm_bindgen::prelude::*; use wasm_bindgen_futures::js_sys::Promise; diff --git a/crates/emberwave-web/src/lib.rs b/crates/emberwave-web/src/lib.rs index 6e0bbf9..e2f79c2 100644 --- a/crates/emberwave-web/src/lib.rs +++ b/crates/emberwave-web/src/lib.rs @@ -14,7 +14,7 @@ use std::sync::{Arc, Mutex}; use emberwave_core::bitstream::{ChromaSubsampling, Pwv1File, YcbcrRange, consts, pwv1}; use emberwave_core::color::{ColorMatrix, ColorParams}; use emberwave_core::encode; -use emberwave_core::gpu::{Decoder, GpuContext, GpuOptions, TEXTURE_FORMATS}; +use emberwave_wgpu::{Decoder, GpuContext, GpuOptions, TEXTURE_FORMATS}; use wasm_bindgen::prelude::*; mod bench; diff --git a/crates/emberwave-wgpu/Cargo.toml b/crates/emberwave-wgpu/Cargo.toml new file mode 100644 index 0000000..5537b6f --- /dev/null +++ b/crates/emberwave-wgpu/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "emberwave-wgpu" +description = "PyroWave decoder and encoder on the GPU, in wgpu/WGSL, on top of emberwave-core" +version.workspace = true +edition.workspace = true +license.workspace = true +repository.workspace = true +rust-version.workspace = true +# Not on crates.io until the maintainer takes the name (decision D75). +publish.workspace = true + +[dependencies] +# The hidden items of the core that this crate uses may change in any release, +# so it takes exactly its own version of the core. +emberwave-core = { workspace = true } +thiserror.workspace = true +wgpu.workspace = true +pollster.workspace = true +bytemuck.workspace = true + +[dev-dependencies] +proptest.workspace = true +naga.workspace = true +# The tests count wgpu's live resources to show that decoding allocates +# nothing per frame; the counters cost a little, so only tests turn them on. +wgpu = { workspace = true, features = ["counters"] } + +[lints] +workspace = true diff --git a/crates/emberwave-core/src/gpu/context.rs b/crates/emberwave-wgpu/src/context.rs similarity index 100% rename from crates/emberwave-core/src/gpu/context.rs rename to crates/emberwave-wgpu/src/context.rs diff --git a/crates/emberwave-core/src/gpu/decoder.rs b/crates/emberwave-wgpu/src/decoder.rs similarity index 99% rename from crates/emberwave-core/src/gpu/decoder.rs rename to crates/emberwave-wgpu/src/decoder.rs index 49bfc06..255d4ef 100644 --- a/crates/emberwave-core/src/gpu/decoder.rs +++ b/crates/emberwave-wgpu/src/decoder.rs @@ -9,12 +9,12 @@ use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; -use crate::bitstream::consts::DECOMPOSITION_LEVELS; -use crate::bitstream::packet::{DEFAULT_MINIMUM_PACKET_RATIO, DEFAULT_PRISTINE_BANDS}; -use crate::bitstream::{ +use emberwave_core::bitstream::consts::DECOMPOSITION_LEVELS; +use emberwave_core::bitstream::packet::{DEFAULT_MINIMUM_PACKET_RATIO, DEFAULT_PRISTINE_BANDS}; +use emberwave_core::bitstream::{ Band, ChromaSubsampling, Component, FrameAssembler, FrameLayout, SequenceHeader, }; -use crate::color::ColorParams; +use emberwave_core::color::ColorParams; use super::context::{ AfterSubmit, ConcealPipeline, GpuContext, QueueTurns, SubmissionHooks, notice_loss, submit, @@ -847,11 +847,11 @@ impl Decoder { /// lacks, off by default (decision D66). Where the coarsest level /// around such a block, which every frame drawn in part has whole, /// changed by at most - /// [`CONCEALMENT_THRESHOLD`](crate::cpu::CONCEALMENT_THRESHOLD) since + /// [`CONCEALMENT_THRESHOLD`](emberwave_core::cpu::CONCEALMENT_THRESHOLD) since /// the last decode, the picture is taken to be still there, and the /// block keeps the last frame's coefficients: the frame shows the detail /// it lost. Elsewhere the block is zero, as without concealment. Whole - /// frames decode as before. [`cpu::Concealer`](crate::cpu::Concealer) + /// frames decode as before. [`cpu::Concealer`](emberwave_core::cpu::Concealer) /// does the same on the CPU, to the last bit of the coefficients. /// /// Measured with the CPU's, frames drawn from 40 to 60 % of their blocks @@ -2146,7 +2146,7 @@ mod tests { use wgpu::util::DeviceExt; use super::*; - use crate::gpu::context::test_context; + use crate::context::test_context; /// Runs `to_unorm8` of `idwt.wgsl`, the rounding of the last level, on /// `values` on the GPU and returns the 8-bit levels. The function is cut out @@ -2432,8 +2432,8 @@ mod tests { if test_context().is_none() { return; } - let context = GpuContext::new(&crate::gpu::GpuOptions::from_env().unwrap_or_default()) - .expect("a context"); + let context = + GpuContext::new(&crate::GpuOptions::from_env().unwrap_or_default()).expect("a context"); let chroma = ChromaSubsampling::Yuv420; let mut decoder = Decoder::new(&context, 64, 32, chroma).unwrap(); decoder diff --git a/crates/emberwave-core/src/gpu/encoder.rs b/crates/emberwave-wgpu/src/encoder.rs similarity index 98% rename from crates/emberwave-core/src/gpu/encoder.rs rename to crates/emberwave-wgpu/src/encoder.rs index 2191592..bae0957 100644 --- a/crates/emberwave-core/src/gpu/encoder.rs +++ b/crates/emberwave-wgpu/src/encoder.rs @@ -1,4 +1,4 @@ -//! The wgpu encoder: the CPU encoder's stages ([`crate::encode`]) as compute +//! The wgpu encoder: the CPU encoder's stages ([`emberwave_core::encode`]) as compute //! shaders, so that a picture goes up once and its frame comes back once. //! //! The picture comes from CPU memory through an upload buffer, or from @@ -19,11 +19,11 @@ use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; -use crate::bitstream::consts::{DECOMPOSITION_LEVELS, HEADER_BYTES}; -use crate::bitstream::{ChromaSubsampling, Component, FrameLayout, SequenceHeader}; -use crate::color::{RgbOrder, check_rgb}; -use crate::encode::fdwt::sample_level; -use crate::encode::{ +use emberwave_core::bitstream::consts::{DECOMPOSITION_LEVELS, HEADER_BYTES}; +use emberwave_core::bitstream::{ChromaSubsampling, Component, FrameLayout, SequenceHeader}; +use emberwave_core::color::{RgbOrder, check_rgb}; +use emberwave_core::encode::fdwt::sample_level; +use emberwave_core::encode::{ EncodeError, Signalling, check_planes, check_strided_planes, next_sequence, start_of_frame, stream_header, }; @@ -115,7 +115,7 @@ pub enum TexturePicture<'a> { /// texture of the picture's size, as a screen capture holds it; alpha is /// not read. The encoder converts it to Y'CbCr as it reads it, by the /// matrix, range and chroma siting of its [`Signalling`], into the planes - /// that [`rgb_to_ycbcr8`](crate::color::rgb_to_ycbcr8) makes of the same + /// that [`rgb_to_ycbcr8`](emberwave_core::color::rgb_to_ycbcr8) makes of the same /// picture in CPU memory (decision D65). R', G' and B' are taken as the /// texture stores them, with their transfer function: a texture of an /// sRGB format, whose reads undo it, is not taken. Nor is a view of @@ -171,6 +171,13 @@ impl RgbUpload { let format = match order { RgbOrder::Rgba => wgpu::TextureFormat::Rgba8Unorm, RgbOrder::Bgra => wgpu::TextureFormat::Bgra8Unorm, + // A later core could add an order; this crate takes its own + // version of the core, so there is none it does not know. + other => { + return Err(GpuError::InvalidArgument(format!( + "the RGB order {other:?} is not one this encoder knows" + ))); + } }; with_error_scope(device, || Self { order, @@ -251,7 +258,7 @@ const MIN_PAYLOAD_WORDS: u64 = 16 * 1024; const SUMMARY_BYTES: u64 = std::mem::size_of::() as u64 + 8; /// Encodes pictures of one size and chroma format into PyroWave frames on -/// the GPU, as [`crate::encode::Encoder`] does on the CPU. +/// the GPU, as [`emberwave_core::encode::Encoder`] does on the CPU. /// /// All GPU memory is allocated up front and reused for every picture, apart /// from the payload buffer, which grows when a frame's budget needs more. @@ -596,7 +603,7 @@ impl Encoder { /// Encodes one picture into a frame of at most `budget` bytes: a start of /// frame header and the coded blocks in block index order, as a PWV1 file - /// stores a frame and as [`crate::encode::Encoder::encode`] makes it. + /// stores a frame and as [`emberwave_core::encode::Encoder::encode`] makes it. /// /// `planes` are the Y, Cb and Cr samples, row-major without padding, at /// the sizes of [`FrameLayout::plane_size`]. A picture that cannot fit diff --git a/crates/emberwave-core/src/gpu/encoder/tests.rs b/crates/emberwave-wgpu/src/encoder/tests.rs similarity index 97% rename from crates/emberwave-core/src/gpu/encoder/tests.rs rename to crates/emberwave-wgpu/src/encoder/tests.rs index 0a59893..5e4ca52 100644 --- a/crates/emberwave-core/src/gpu/encoder/tests.rs +++ b/crates/emberwave-wgpu/src/encoder/tests.rs @@ -1,12 +1,12 @@ //! The GPU encoder's stages against the CPU encoder's (decision D29). use super::*; -use crate::bitstream::{Band, FrameAssembler}; -use crate::cpu::decode_frame; -use crate::encode::rate::{self, BlockCost}; -use crate::encode::{Bands, Encoder as CpuEncoder}; -use crate::gpu::context::test_context; -use crate::gpu::resources::{entry, read_back, uniform_buffer}; +use crate::context::test_context; +use crate::resources::{entry, read_back, uniform_buffer}; +use emberwave_core::bitstream::{Band, FrameAssembler}; +use emberwave_core::cpu::decode_frame; +use emberwave_core::encode::rate::{self, BlockCost}; +use emberwave_core::encode::{Bands, Encoder as CpuEncoder}; use ChromaSubsampling::{Yuv420, Yuv444}; @@ -782,6 +782,7 @@ fn rgb_picture(width: u32, height: u32, stride: usize, order: RgbOrder, seed: u3 let pixel = match order { RgbOrder::Rgba => [r, g, b, (noise >> 24) as u8], RgbOrder::Bgra => [b, g, r, (noise >> 24) as u8], + other => unreachable!("an RGB order the tests do not know: {other:?}"), }; bytes[y * stride + 4 * x..][..4].copy_from_slice(&pixel); } @@ -798,17 +799,17 @@ fn gathering_rgb_writes_the_words_of_its_converted_planes() { let Some(context) = test_context() else { return; }; - use crate::bitstream::{ChromaSiting, YcbcrRange, YcbcrTransform}; + use emberwave_core::bitstream::{ChromaSiting, YcbcrRange, YcbcrTransform}; let mut signallings = Vec::new(); for ycbcr_transform in [YcbcrTransform::Bt709, YcbcrTransform::Bt2020] { for ycbcr_range in [YcbcrRange::Limited, YcbcrRange::Full] { for chroma_siting in [ChromaSiting::Center, ChromaSiting::Left] { - signallings.push(Signalling { - ycbcr_transform, - ycbcr_range, - chroma_siting, - ..Signalling::default() - }); + // Signalling is non_exhaustive in the core: set its fields. + let mut signalling = Signalling::default(); + signalling.ycbcr_transform = ycbcr_transform; + signalling.ycbcr_range = ycbcr_range; + signalling.chroma_siting = chroma_siting; + signallings.push(signalling); } } } @@ -817,7 +818,7 @@ fn gathering_rgb_writes_the_words_of_its_converted_planes() { let mut gpu = Encoder::new(context, width, height, chroma, signalling).unwrap(); let seed = (shape * 8 + index) as u32; let rgba = rgb_picture(width, height, 4 * width as usize, RgbOrder::Rgba, seed); - let planes = crate::color::rgb_to_ycbcr8( + let planes = emberwave_core::color::rgb_to_ycbcr8( &rgba, 4 * width as usize, RgbOrder::Rgba, diff --git a/crates/emberwave-core/src/gpu/error.rs b/crates/emberwave-wgpu/src/error.rs similarity index 95% rename from crates/emberwave-core/src/gpu/error.rs rename to crates/emberwave-wgpu/src/error.rs index 5c92448..9f9bb17 100644 --- a/crates/emberwave-core/src/gpu/error.rs +++ b/crates/emberwave-wgpu/src/error.rs @@ -58,11 +58,11 @@ pub enum GpuError { /// The bitstream is malformed. #[error(transparent)] - Bitstream(#[from] crate::bitstream::Error), + Bitstream(#[from] emberwave_core::bitstream::Error), /// The planes or the budget do not suit the encoder. #[error(transparent)] - Encode(#[from] crate::encode::EncodeError), + Encode(#[from] emberwave_core::encode::EncodeError), /// A texture of a [`TexturePicture`](super::TexturePicture) cannot hold /// its plane: its format, size, dimension, samples or usage. #[error("unsuitable texture: {0}")] diff --git a/crates/emberwave-core/src/gpu/layout.rs b/crates/emberwave-wgpu/src/layout.rs similarity index 97% rename from crates/emberwave-core/src/gpu/layout.rs rename to crates/emberwave-wgpu/src/layout.rs index b2c2f7e..dd2df92 100644 --- a/crates/emberwave-core/src/gpu/layout.rs +++ b/crates/emberwave-wgpu/src/layout.rs @@ -6,12 +6,14 @@ use bytemuck::{Pod, Zeroable}; -use crate::bitstream::consts::{BANDS_PER_LEVEL, DECOMPOSITION_LEVELS, NUM_COMPONENTS}; -use crate::bitstream::{Band, ChromaSiting, ChromaSubsampling, Component, FrameLayout, YcbcrRange}; -use crate::color::{ +use emberwave_core::bitstream::consts::{BANDS_PER_LEVEL, DECOMPOSITION_LEVELS, NUM_COMPONENTS}; +use emberwave_core::bitstream::{ + Band, ChromaSiting, ChromaSubsampling, Component, FrameLayout, YcbcrRange, +}; +use emberwave_core::color::{ CHROMA_CENTRE, CHROMA_SCALE, ColorParams, ForwardMatrix, INV_255, LUMA_BLACK, LUMA_SCALE, }; -use crate::encode::quant::{BandQuant, DROP_STEPS}; +use emberwave_core::encode::quant::{BandQuant, DROP_STEPS}; use super::GpuError; @@ -224,7 +226,7 @@ pub(crate) struct ConcealParams { /// component. pub coarse_width: u32, pub coarse_height: u32, - /// [`CONCEALMENT_THRESHOLD`](crate::cpu::CONCEALMENT_THRESHOLD). + /// [`CONCEALMENT_THRESHOLD`](emberwave_core::cpu::CONCEALMENT_THRESHOLD). pub threshold: f32, pub pad: u32, } @@ -257,7 +259,7 @@ impl ConcealParams { } params.coarse_width = width; params.coarse_height = height; - params.threshold = crate::cpu::CONCEALMENT_THRESHOLD; + params.threshold = emberwave_core::cpu::CONCEALMENT_THRESHOLD; params } @@ -323,7 +325,7 @@ impl QuantParams { params.band_count = count as u32; params.block_count = layout.block_count(); params.grid_width = grid_for(u64::from(layout.block_count())).0; - params.pristine_blocks = crate::encode::pristine_blocks(layout); + params.pristine_blocks = emberwave_core::encode::pristine_blocks(layout); params } @@ -334,7 +336,7 @@ impl QuantParams { } /// What `equant.wgsl` writes for every block: the CPU encoder's -/// [`BlockCost`](crate::encode::rate::BlockCost) in 32-bit words. +/// [`BlockCost`](emberwave_core::encode::rate::BlockCost) in 32-bit words. #[repr(C)] #[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)] pub(crate) struct CostRecord { @@ -347,12 +349,12 @@ pub(crate) struct CostRecord { impl CostRecord { /// The record as the CPU encoder's rate control takes it, or `None` if a /// number does not fit its type, which no shader writes. - pub(crate) fn to_cost(self) -> Option { + pub(crate) fn to_cost(self) -> Option { let mut words = [0u16; DROP_STEPS]; for (word, &value) in words.iter_mut().zip(&self.words) { *word = u16::try_from(value).ok()?; } - Some(crate::encode::rate::BlockCost { + Some(emberwave_core::encode::rate::BlockCost { words, distortion: self.distortion, max_drop: u8::try_from(self.max_drop).ok()?, @@ -360,7 +362,7 @@ impl CostRecord { } /// The CPU encoder's record in 32-bit words. - pub(crate) fn from_cost(cost: &crate::encode::rate::BlockCost) -> Self { + pub(crate) fn from_cost(cost: &emberwave_core::encode::rate::BlockCost) -> Self { Self { words: cost.words.map(u32::from), distortion: cost.distortion, @@ -728,7 +730,7 @@ mod tests { use std::mem::size_of; use super::*; - use crate::bitstream::ChromaSubsampling; + use emberwave_core::bitstream::ChromaSubsampling; fn layout_420() -> FrameLayout { FrameLayout::new(200, 120, ChromaSubsampling::Yuv420).unwrap() @@ -972,16 +974,12 @@ mod tests { #[test] fn yuv_params_describe_the_packed_planes_and_the_conversion() { - use crate::bitstream::{ChromaSiting, YcbcrRange}; - use crate::color::ColorMatrix; + use emberwave_core::bitstream::{ChromaSiting, YcbcrRange}; + use emberwave_core::color::ColorMatrix; let layout = layout_420(); // 200x120, chroma 100x60 let buffers = BufferLayout::new(&layout).unwrap(); - let color = ColorParams { - matrix: ColorMatrix::Bt2020, - range: YcbcrRange::Full, - chroma_siting: ChromaSiting::Left, - }; + let color = ColorParams::new(ColorMatrix::Bt2020, YcbcrRange::Full, ChromaSiting::Left); let p = YuvParams::new(&layout, &buffers, &color); assert_eq!((p.width, p.height, p.chroma_420), (200, 120, 1)); diff --git a/crates/emberwave-core/src/gpu/mod.rs b/crates/emberwave-wgpu/src/lib.rs similarity index 90% rename from crates/emberwave-core/src/gpu/mod.rs rename to crates/emberwave-wgpu/src/lib.rs index 7d0792d..149f35c 100644 --- a/crates/emberwave-core/src/gpu/mod.rs +++ b/crates/emberwave-wgpu/src/lib.rs @@ -1,4 +1,11 @@ -//! The wgpu pipelines. +//! The GPU decoder and encoder of emberwave, a portable port of the PyroWave +//! low-latency intra-frame wavelet video codec, in wgpu and WGSL, on top of +//! `emberwave-core`'s bitstream, CPU reference and colour code. +//! +//! [`wgpu`] is the version this crate is built with, whose types the GPU +//! calls take: use it to share a device or a texture. A new major version of +//! wgpu changes them, and this crate's major version with it; the core has no +//! wgpu type in its API (decision D75). //! //! [`GpuContext`] creates the device, [`Decoder`] decodes frames on it and //! [`Encoder`] encodes pictures. The shaders are plain WGSL that uses only what @@ -16,6 +23,8 @@ // the native builds check for code that is dead everywhere. #![cfg_attr(target_arch = "wasm32", allow(dead_code, unused_imports))] +pub use wgpu; + mod context; mod decoder; mod encoder; diff --git a/crates/emberwave-core/src/gpu/pipelines.rs b/crates/emberwave-wgpu/src/pipelines.rs similarity index 99% rename from crates/emberwave-core/src/gpu/pipelines.rs rename to crates/emberwave-wgpu/src/pipelines.rs index 5004274..9901112 100644 --- a/crates/emberwave-core/src/gpu/pipelines.rs +++ b/crates/emberwave-wgpu/src/pipelines.rs @@ -5,7 +5,7 @@ //! most of all), so a [`GpuContext`](super::GpuContext) builds them on first //! use and hands out the same ones afterwards. -use crate::bitstream::ChromaSubsampling; +use emberwave_core::bitstream::ChromaSubsampling; use super::decoder::PLANE_FORMAT; use super::error::GpuError; diff --git a/crates/emberwave-core/src/gpu/resources.rs b/crates/emberwave-wgpu/src/resources.rs similarity index 100% rename from crates/emberwave-core/src/gpu/resources.rs rename to crates/emberwave-wgpu/src/resources.rs diff --git a/crates/emberwave-core/src/gpu/shaders/conceal.wgsl b/crates/emberwave-wgpu/src/shaders/conceal.wgsl similarity index 100% rename from crates/emberwave-core/src/gpu/shaders/conceal.wgsl rename to crates/emberwave-wgpu/src/shaders/conceal.wgsl diff --git a/crates/emberwave-core/src/gpu/shaders/dequant.wgsl b/crates/emberwave-wgpu/src/shaders/dequant.wgsl similarity index 100% rename from crates/emberwave-core/src/gpu/shaders/dequant.wgsl rename to crates/emberwave-wgpu/src/shaders/dequant.wgsl diff --git a/crates/emberwave-core/src/gpu/shaders/draw.wgsl b/crates/emberwave-wgpu/src/shaders/draw.wgsl similarity index 100% rename from crates/emberwave-core/src/gpu/shaders/draw.wgsl rename to crates/emberwave-wgpu/src/shaders/draw.wgsl diff --git a/crates/emberwave-core/src/gpu/shaders/equant.wgsl b/crates/emberwave-wgpu/src/shaders/equant.wgsl similarity index 100% rename from crates/emberwave-core/src/gpu/shaders/equant.wgsl rename to crates/emberwave-wgpu/src/shaders/equant.wgsl diff --git a/crates/emberwave-core/src/gpu/shaders/fdwt.wgsl b/crates/emberwave-wgpu/src/shaders/fdwt.wgsl similarity index 100% rename from crates/emberwave-core/src/gpu/shaders/fdwt.wgsl rename to crates/emberwave-wgpu/src/shaders/fdwt.wgsl diff --git a/crates/emberwave-core/src/gpu/shaders/gather.wgsl b/crates/emberwave-wgpu/src/shaders/gather.wgsl similarity index 100% rename from crates/emberwave-core/src/gpu/shaders/gather.wgsl rename to crates/emberwave-wgpu/src/shaders/gather.wgsl diff --git a/crates/emberwave-core/src/gpu/shaders/gather_rgb.wgsl b/crates/emberwave-wgpu/src/shaders/gather_rgb.wgsl similarity index 100% rename from crates/emberwave-core/src/gpu/shaders/gather_rgb.wgsl rename to crates/emberwave-wgpu/src/shaders/gather_rgb.wgsl diff --git a/crates/emberwave-core/src/gpu/shaders/idwt.wgsl b/crates/emberwave-wgpu/src/shaders/idwt.wgsl similarity index 100% rename from crates/emberwave-core/src/gpu/shaders/idwt.wgsl rename to crates/emberwave-wgpu/src/shaders/idwt.wgsl diff --git a/crates/emberwave-core/src/gpu/shaders/idwt_packed.wgsl b/crates/emberwave-wgpu/src/shaders/idwt_packed.wgsl similarity index 100% rename from crates/emberwave-core/src/gpu/shaders/idwt_packed.wgsl rename to crates/emberwave-wgpu/src/shaders/idwt_packed.wgsl diff --git a/crates/emberwave-core/src/gpu/shaders/idwt_planes.wgsl b/crates/emberwave-wgpu/src/shaders/idwt_planes.wgsl similarity index 100% rename from crates/emberwave-core/src/gpu/shaders/idwt_planes.wgsl rename to crates/emberwave-wgpu/src/shaders/idwt_planes.wgsl diff --git a/crates/emberwave-core/src/gpu/shaders/pack.wgsl b/crates/emberwave-wgpu/src/shaders/pack.wgsl similarity index 100% rename from crates/emberwave-core/src/gpu/shaders/pack.wgsl rename to crates/emberwave-wgpu/src/shaders/pack.wgsl diff --git a/crates/emberwave-core/src/gpu/shaders/quantise.wgsl b/crates/emberwave-wgpu/src/shaders/quantise.wgsl similarity index 100% rename from crates/emberwave-core/src/gpu/shaders/quantise.wgsl rename to crates/emberwave-wgpu/src/shaders/quantise.wgsl diff --git a/crates/emberwave-core/src/gpu/shaders/rate.wgsl b/crates/emberwave-wgpu/src/shaders/rate.wgsl similarity index 100% rename from crates/emberwave-core/src/gpu/shaders/rate.wgsl rename to crates/emberwave-wgpu/src/shaders/rate.wgsl diff --git a/crates/emberwave-core/src/gpu/shaders/scan.wgsl b/crates/emberwave-wgpu/src/shaders/scan.wgsl similarity index 100% rename from crates/emberwave-core/src/gpu/shaders/scan.wgsl rename to crates/emberwave-wgpu/src/shaders/scan.wgsl diff --git a/crates/emberwave-core/src/gpu/shaders/yuv2rgb.wgsl b/crates/emberwave-wgpu/src/shaders/yuv2rgb.wgsl similarity index 100% rename from crates/emberwave-core/src/gpu/shaders/yuv2rgb.wgsl rename to crates/emberwave-wgpu/src/shaders/yuv2rgb.wgsl diff --git a/crates/emberwave-wgpu/tests/common/mod.rs b/crates/emberwave-wgpu/tests/common/mod.rs new file mode 100644 index 0000000..338a1bf --- /dev/null +++ b/crates/emberwave-wgpu/tests/common/mod.rs @@ -0,0 +1,58 @@ +//! Helpers shared by the GPU tests: those of `emberwave-core`'s tests +//! (locating the committed test vectors, reading reference decodes, PSNR), +//! included from there, and the GPU's own. + +#![allow(dead_code)] // each test binary uses a different subset + +#[path = "../../../emberwave-core/tests/common/mod.rs"] +mod core_common; +pub use core_common::*; + +/// Whether a missing GPU is a failure rather than a reason to skip. An empty +/// value counts as unset so a CI matrix can leave it blank. +pub fn gpu_required() -> bool { + std::env::var_os("EMBERWAVE_REQUIRE_GPU").is_some_and(|value| !value.is_empty()) +} + +/// Creates a context, or returns `None` if there is no GPU and none is required. +pub fn create_context(options: &emberwave_wgpu::GpuOptions) -> Option { + match emberwave_wgpu::GpuContext::new(options) { + Ok(context) => { + eprintln!("GPU tests run on {:?}", context.adapter_info()); + Some(context) + } + Err(error) => { + assert!( + !gpu_required(), + "a GPU is required but none is available: {error}" + ); + eprintln!("no GPU available, skipping: {error}"); + None + } + } +} + +/// Every count of live GPU objects and memory that wgpu keeps for a context's +/// device (the tests build wgpu with its `counters` feature), as text: buffers, +/// textures and their views, bind groups and their layouts, pipelines, +/// samplers, command encoders, shader modules, query sets, fences, memory. +/// wgpu 30 keeps the object counts on Vulkan, Metal and DX12; Metal leaves the +/// memory at zero, and no backend counts memory allocations. +pub fn live_resources(context: &emberwave_wgpu::GpuContext) -> String { + format!("{:?}", context.device().get_internal_counters().hal) +} + +/// The options the tests start from: the defaults, with the backends that +/// `EMBERWAVE_BACKEND` names, so that a run can force a backend, as the +/// command line tool does. A value that names none is ignored. +pub fn options() -> emberwave_wgpu::GpuOptions { + emberwave_wgpu::GpuOptions::from_env().unwrap_or_default() +} + +/// The GPU context shared by the tests of one test binary, or `None` if +/// there is no GPU and none is required. +pub fn shared_context() -> Option<&'static emberwave_wgpu::GpuContext> { + static CONTEXT: std::sync::OnceLock> = + std::sync::OnceLock::new(); + CONTEXT.get_or_init(|| create_context(&options())).as_ref() +} diff --git a/crates/emberwave-core/tests/gpu.rs b/crates/emberwave-wgpu/tests/gpu.rs similarity index 99% rename from crates/emberwave-core/tests/gpu.rs rename to crates/emberwave-wgpu/tests/gpu.rs index e8e94c7..de728ac 100644 --- a/crates/emberwave-core/tests/gpu.rs +++ b/crates/emberwave-wgpu/tests/gpu.rs @@ -4,8 +4,6 @@ //! skip, unless `EMBERWAVE_REQUIRE_GPU` is set, which turns a missing adapter //! into a failure; CI sets it on the job that installs lavapipe. -#![cfg(feature = "gpu")] - mod common; use common::{ @@ -21,7 +19,7 @@ use emberwave_core::bitstream::{ }; use emberwave_core::color::{ColorMatrix, ColorParams, yuv_to_rgb8}; use emberwave_core::cpu; -use emberwave_core::gpu::{Decoder, Frame, GpuContext, GpuError, TEXTURE_FORMATS, TimedOutput}; +use emberwave_wgpu::{Decoder, Frame, GpuContext, GpuError, TEXTURE_FORMATS, TimedOutput}; /// Skips the current test when there is no GPU. macro_rules! gpu_or_return { @@ -535,7 +533,7 @@ fn planes_drawn_into_textures_are_the_decoded_planes() { mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, - format: emberwave_core::gpu::PLANE_FORMAT, + format: emberwave_wgpu::PLANE_FORMAT, usage: wgpu::TextureUsages::COPY_DST | wgpu::TextureUsages::COPY_SRC, view_formats: &[], }) @@ -678,7 +676,7 @@ fn plane_texture( mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, - format: emberwave_core::gpu::PLANE_FORMAT, + format: emberwave_wgpu::PLANE_FORMAT, usage, view_formats: &[], }) @@ -1100,7 +1098,7 @@ fn an_incomplete_frame_is_an_error_until_it_is_allowed_to_be_partial() { let error = decoder.decode(&cut[..end]).unwrap_err(); assert!( - matches!(error, emberwave_core::gpu::GpuError::IncompleteFrame { .. }), + matches!(error, emberwave_wgpu::GpuError::IncompleteFrame { .. }), "{error}" ); @@ -1959,8 +1957,8 @@ fn timing_a_frame_reports_where_the_time_goes() { let mut decoder = decoder_for(&context, &layout); for output in [ - emberwave_core::gpu::TimedOutput::Yuv, - emberwave_core::gpu::TimedOutput::Rgb(ColorParams::default()), + emberwave_wgpu::TimedOutput::Yuv, + emberwave_wgpu::TimedOutput::Rgb(ColorParams::default()), ] { let timings = decoder.time_frame(&frames[0], output).unwrap(); assert!(timings.gpu_wall > std::time::Duration::ZERO); @@ -1972,7 +1970,7 @@ fn timing_a_frame_reports_where_the_time_goes() { // A short stage can be below the timer's resolution and read as // zero, but the whole decode cannot. assert!(stages.total() > std::time::Duration::ZERO); - let rgb = matches!(output, emberwave_core::gpu::TimedOutput::Rgb(_)); + let rgb = matches!(output, emberwave_wgpu::TimedOutput::Rgb(_)); assert_eq!(stages.yuv2rgb.is_some(), rgb); // The GPU cannot take longer than the wall clock around it. assert!(stages.total() <= timings.gpu_wall + timings.prepare); diff --git a/crates/emberwave-core/tests/gpu_encoder.rs b/crates/emberwave-wgpu/tests/gpu_encoder.rs similarity index 99% rename from crates/emberwave-core/tests/gpu_encoder.rs rename to crates/emberwave-wgpu/tests/gpu_encoder.rs index ee7ba16..ba0ddae 100644 --- a/crates/emberwave-core/tests/gpu_encoder.rs +++ b/crates/emberwave-wgpu/tests/gpu_encoder.rs @@ -7,8 +7,6 @@ //! Like `tests/gpu.rs`, they skip without a GPU unless //! `EMBERWAVE_REQUIRE_GPU` is set. -#![cfg(feature = "gpu")] - mod common; use common::{ @@ -21,7 +19,7 @@ use emberwave_core::bitstream::{ use emberwave_core::color::{ColorError, RgbOrder, rgb_to_ycbcr8, yuv_to_rgb8}; use emberwave_core::cpu::decode_frame; use emberwave_core::encode::{self, EncodeError, Signalling}; -use emberwave_core::gpu::{Decoder, Encoder, GpuContext, GpuError, TexturePicture}; +use emberwave_wgpu::{Decoder, Encoder, GpuContext, GpuError, TexturePicture}; /// Skips the current test when there is no GPU. macro_rules! gpu_or_return { diff --git a/crates/emberwave-core/tests/gpu_hooks.rs b/crates/emberwave-wgpu/tests/gpu_hooks.rs similarity index 97% rename from crates/emberwave-core/tests/gpu_hooks.rs rename to crates/emberwave-wgpu/tests/gpu_hooks.rs index 25a9370..3b8335d 100644 --- a/crates/emberwave-core/tests/gpu_hooks.rs +++ b/crates/emberwave-wgpu/tests/gpu_hooks.rs @@ -6,14 +6,12 @@ //! They need a GPU or a software Vulkan driver (lavapipe), and skip without //! one unless `EMBERWAVE_REQUIRE_GPU` is set. -#![cfg(feature = "gpu")] - mod common; use common::{shared_context, vector_frames}; use emberwave_core::bitstream::Component; use emberwave_core::encode::Signalling; -use emberwave_core::gpu::{Decoder, Encoder, SubmissionHooks, TexturePicture}; +use emberwave_wgpu::{Decoder, Encoder, SubmissionHooks, TexturePicture}; /// Notes what the call ran, in order. #[derive(Default)] diff --git a/crates/emberwave-core/tests/shaders.rs b/crates/emberwave-wgpu/tests/shaders.rs similarity index 99% rename from crates/emberwave-core/tests/shaders.rs rename to crates/emberwave-wgpu/tests/shaders.rs index 930c1d5..36e7711 100644 --- a/crates/emberwave-core/tests/shaders.rs +++ b/crates/emberwave-wgpu/tests/shaders.rs @@ -4,9 +4,7 @@ //! optional feature: no subgroup operations, no 16-bit floats or integers, no //! atomics on floats and so on. -#![cfg(feature = "gpu")] - -use emberwave_core::gpu::shader_sources; +use emberwave_wgpu::shader_sources; use naga::valid::{Capabilities, ValidationFlags, Validator}; fn validate(name: &str, source: &str) -> naga::Module { diff --git a/scripts/soak.sh b/scripts/soak.sh index 2287c8f..046e659 100755 --- a/scripts/soak.sh +++ b/scripts/soak.sh @@ -2,7 +2,7 @@ # Decodes 1000 4K frames and watches the memory of the process: half of the # leak check of milestone M5. The other half, which counts the GPU resources, # is the ignored test a_thousand_4k_frames_leave_no_trace in -# crates/emberwave-core/tests/gpu.rs. +# crates/emberwave-wgpu/tests/gpu.rs. # # Usage: scripts/soak.sh [frames] (default 1000) # From f2e3bd55cf9e8ed5ef37cb3d15f6e1c5e1dbab66 Mon Sep 17 00:00:00 2001 From: harry Date: Tue, 24 Nov 2026 21:54:13 +0900 Subject: [PATCH 2/2] refactor: narrow the core's hidden surface, harden the CI check, follow the docs A review of the split found it sound and six small things, all taken: - The core had made all 27 items of `encode::{fdwt, quant, rate}` public; 18 of them are not used by emberwave-wgpu and are crate-private again. What stays open: `fdwt::sample_level`, `quant::{DROP_STEPS, BandQuant::{new, max_drop}, Block8, Blocks8}` and `rate::{BlockCost, choose}`. - The CI check that the core does not depend on wgpu matched only `wgpu` and `naga` and passed when `cargo tree` failed; it now reads the tree first, for every target, and matches the whole family (`wgpu-types` holds the API types). - The browser build of the docs links to calls it leaves out: the allow that the core had for it moves to emberwave-wgpu. - The soak test's command names emberwave-wgpu; two comments name the right crate. - CONTRIBUTING's release step: emberwave-cli cannot be published until emberwave-wgpu has a name on crates.io, the order then, and that the next release is a minor version. - The docs: ARCHITECTURE's status line, its table of modules and the GPU paths of its other sections, the README's 1.0 checklist in both languages, and an Unreleased entry in the CHANGELOG for the change of the Rust paths. Claude-Session: https://claude.ai/code/session_019fJGoCTvP5e7n599q3ZQ42 --- .github/workflows/ci.yml | 5 ++++- ARCHITECTURE.md | 19 +++++++++++-------- CHANGELOG.md | 5 +++++ CONTRIBUTING.md | 4 ++-- README.ko.md | 2 +- README.md | 2 +- crates/emberwave-core/src/cpu/mod.rs | 2 +- crates/emberwave-core/src/encode/fdwt.rs | 8 ++++---- crates/emberwave-core/src/encode/quant.rs | 21 ++++++++++++--------- crates/emberwave-core/src/encode/rate.rs | 10 +++++----- crates/emberwave-ffi/Cargo.toml | 2 +- crates/emberwave-wgpu/src/lib.rs | 10 +++++++--- crates/emberwave-wgpu/tests/gpu.rs | 2 +- 13 files changed, 55 insertions(+), 37 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5345806..0fe6f11 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -74,7 +74,10 @@ jobs: # GPU code is emberwave-wgpu (decision D75). - name: The core does not depend on wgpu run: | - if cargo tree -p emberwave-core -e normal --prefix none | grep -E '^(wgpu|naga) '; then + # The tree first, so that a failing cargo stops the step; then any + # crate of wgpu's or naga's family (wgpu-types holds the API types). + tree=$(cargo tree -p emberwave-core -e normal --target all --prefix none) + if grep -E '^(wgpu|naga)[ -]' <<< "$tree"; then echo "emberwave-core depends on wgpu: the GPU code belongs to emberwave-wgpu" >&2 exit 1 fi diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 7f0d4b8..6603bcf 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -1,6 +1,6 @@ # Architecture -> **Status (v0.19.0).** The bitstream format is documented below and implemented by `emberwave_core::bitstream`, with a slow CPU reference decoder in `emberwave_core::cpu`, the wgpu/WGSL decoder in `emberwave_core::gpu` and the colour conversion in `emberwave_core::color`. The encoder runs on the CPU (`emberwave_core::encode`) and on the GPU (`emberwave_core::gpu`). `emberwave-cli` decodes and encodes files with them, `emberwave-web` plays them in a browser, also packet by packet as a stream arrives, and `emberwave-ffi` offers the decoder and the GPU encoder to C, also as an XCFramework for iPhone, iPad and Mac apps, and hands Metal clients the decoded picture in a texture, or its planes in three, also into the client's own textures and on its own queue without waiting, where calls take turns at its command buffers; it runs on a client's own Vulkan device and images as well, shares textures and fences with Direct3D 12 and 11 devices on Windows, and encodes a host's pictures straight from its textures, in RGB as captures hold them too; on Metal the planes are stored straight into the textures, and on Apple silicon the frames are written where the shaders read them. A decoder can keep the last frame's detail in the blocks a frame drawn in part lacks, where the picture is still. Decode and encode times are in `BENCHMARKS.md`. The decision log at the end is kept up to date. +> **Status (v0.19.0).** The bitstream format is documented below and implemented by `emberwave_core::bitstream`, with a slow CPU reference decoder in `emberwave_core::cpu`, the wgpu/WGSL decoder in the crate `emberwave-wgpu` and the colour conversion in `emberwave_core::color`. The encoder runs on the CPU (`emberwave_core::encode`) and on the GPU (`emberwave-wgpu`). `emberwave-core` has no wgpu in its dependencies or its API, so that its version need not follow wgpu's (D75). `emberwave-cli` decodes and encodes files with them, `emberwave-web` plays them in a browser, also packet by packet as a stream arrives, and `emberwave-ffi` offers the decoder and the GPU encoder to C, also as an XCFramework for iPhone, iPad and Mac apps, and hands Metal clients the decoded picture in a texture, or its planes in three, also into the client's own textures and on its own queue without waiting, where calls take turns at its command buffers; it runs on a client's own Vulkan device and images as well, shares textures and fences with Direct3D 12 and 11 devices on Windows, and encodes a host's pictures straight from its textures, in RGB as captures hold them too; on Metal the planes are stored straight into the textures, and on Apple silicon the frames are written where the shaders read them. A decoder can keep the last frame's detail in the blocks a frame drawn in part lacks, where the picture is still. Decode and encode times are in `BENCHMARKS.md`. The decision log at the end is kept up to date. ## Overview @@ -22,13 +22,16 @@ bytes ──► [CPU] packet parser ──► block table + payload words Steps that upstream runs on the CPU stay on the CPU, and steps that upstream runs on the GPU stay on the GPU. Parity with the reference comes before any optimisation. +The crate `emberwave-core`: + | Module | What it is | |---|---| | `bitstream` | Pure Rust, GPU independent: headers, block layout, packet assembly, PWV1 files. Never panics on malformed input. This is the CPU stage. | | `cpu` | Dequantisation and inverse DWT as plain sequential Rust, following `bitstream.md` literally. A test oracle and the yardstick for shader stages, not a product feature. | | `color` | The YCbCr to RGB conversion: matrices, range handling and chroma siting, with a CPU implementation that the shader is tested against. And the encoder's RGB to Y'CbCr conversion in integers (`rgb_to_ycbcr8`, `ForwardMatrix`, `RgbOrder`, D65), which `gather_rgb.wgsl` matches to the bit. | | `encode` | The encoder on the CPU, plain sequential Rust: forward DWT, quantisation, rate control and packing, the reference of the GPU encoder; and `packets`, which splits a frame at its blocks for a network. | -| `gpu` | wgpu pipelines and WGSL shaders for the GPU stages (cargo feature `gpu`, on by default). | + +The crate `emberwave-wgpu` (until D75, the `gpu` module of `emberwave-core`) holds the wgpu pipelines and the WGSL shaders of the GPU stages: `GpuContext`, the GPU `Decoder` and `Encoder`, and `wgpu` re-exported, the version it is built with. It uses some items of the core that are hidden from its documentation, and the two crates take each other's exact version. ## Bitstream format @@ -300,7 +303,7 @@ The gap to the default precision is the reference decoder's own FP16 storage. In ## GPU pipeline -`gpu::Decoder` decodes frames of one size and chroma format. The memory every decode uses, the pyramid, the block offsets and the packed planes, is allocated when it is created and reused for every frame, and the payload buffer grows when a frame needs more room. What only some decodes need, the upload and read-back buffers, the RGB picture and concealment's copy of the coarsest level, is made by the first decode that needs it and then reused. The encoder's GPU pipeline, `gpu::Encoder`, is described under [Encoder](#on-the-gpu). +`emberwave_wgpu::Decoder` decodes frames of one size and chroma format. The memory every decode uses, the pyramid, the block offsets and the packed planes, is allocated when it is created and reused for every frame, and the payload buffer grows when a frame needs more room. What only some decodes need, the upload and read-back buffers, the RGB picture and concealment's copy of the coarsest level, is made by the first decode that needs it and then reused. The encoder's GPU pipeline, `emberwave_wgpu::Encoder`, is described under [Encoder](#on-the-gpu). ### Stages @@ -424,7 +427,7 @@ The shaders, the decoder's and the encoder's, use only what WebGPU guarantees: n - `tests/shaders.rs` validates the WGSL of every shader with naga using an empty capability set, without a GPU, and checks the entry points, the workgroup sizes and memory. - `tests/gpu.rs` and `tests/gpu_encoder.rs` create a device with `InstanceFlags::STRICT_WEBGPU_COMPLIANCE` and the default limits and decode a vector on it, and encode pictures on it. -- The rounding rule of the last level is checked on the real backend against the CPU's, on inputs that are exact ties: a unit test of `gpu::decoder` cuts `to_unorm8` out of `idwt.wgsl` and runs it. +- The rounding rule of the last level is checked on the real backend against the CPU's, on inputs that are exact ties: a unit test of `emberwave_wgpu`'s decoder module cuts `to_unorm8` out of `idwt.wgsl` and runs it. Outside those tests a context asks for the default limits with two exceptions. Buffers and textures may be as large as the adapter allows. No limit goes beyond the adapter's, since some adapters fall short of a default the shaders do not need. Metal gives the iOS Simulator, and Apple GPUs before the A11, 15 inter-stage variables, one fewer than WebGPU's default, and the shaders use none (D36). @@ -512,7 +515,7 @@ CI builds the module as Pages does and instantiates it in Node (`scripts/check_w |---|---|---| | `EmberwaveContext` | `GpuContext` | A GPU device and the compiled shaders, shared by its decoders and encoders | | `EmberwaveDecoder` | `Decoder` | Assembles the packets of one stream and decodes its frames | -| `EmberwaveEncoder` | `gpu::Encoder` | Encodes the pictures of one stream into frames within a byte budget | +| `EmberwaveEncoder` | `emberwave_wgpu::Encoder` | Encodes the pictures of one stream into frames within a byte budget | A decoder or an encoder holds the device it was made on, so it may outlive its context. The functions: @@ -556,7 +559,7 @@ Frames from upstream's Metal encoder signal BT.709, full range and centred chrom ## Encoder -`emberwave_core::encode` turns 8-bit pictures into frames of bitstream v1 within a byte budget, on the CPU, and `gpu::Encoder` does the same on the GPU ([On the GPU](#on-the-gpu)); `emberwave-cli encode` runs either on a Y4M file. The CPU encoder is the reference for the GPU's, as `emberwave_core::cpu` is for the GPU decoder, and like that it is plain sequential Rust. Its frames decode with any decoder of the format: the tests check emberwave's against upstream's, and the vectors in `testdata/encoder/` carry upstream's decode of emberwave's streams. +`emberwave_core::encode` turns 8-bit pictures into frames of bitstream v1 within a byte budget, on the CPU, and `emberwave_wgpu::Encoder` does the same on the GPU ([On the GPU](#on-the-gpu)); `emberwave-cli encode` runs either on a Y4M file. The CPU encoder is the reference for the GPU's, as `emberwave_core::cpu` is for the GPU decoder, and like that it is plain sequential Rust. Its frames decode with any decoder of the format: the tests check emberwave's against upstream's, and the vectors in `testdata/encoder/` carry upstream's decode of emberwave's streams. The format fixes the transform and what the decoder does with the numbers; the rest is the encoder's choice: @@ -591,7 +594,7 @@ PSNR is not what either encoder minimises: both minimise the squared error of th ### On the GPU -`gpu::Encoder` runs the same steps as compute shaders, so that a picture goes to the GPU once and its frame comes back once. The CPU writes the planes into an upload buffer the encoder keeps from frame to frame and maps again before each, or on Apple silicon into the planes buffer itself (D54), the passes below run in one submission after the copy of the planes, if there is one, and the summary of the rate control and the payload come back in one read-back. The CPU writes the start of frame header in front of the payload. A picture that is in GPU memory already, in textures (`Encoder::encode_textures`), takes the place of the upload: `gather.wgsl` packs the textures into the same planes at the start of the transform's pass, so the frame is the same bytes (decision D32). A picture in RGB, in a texture or uploaded into one from CPU memory, is converted into those planes by `gather_rgb.wgsl` in its place (decision D65). +`emberwave_wgpu::Encoder` runs the same steps as compute shaders, so that a picture goes to the GPU once and its frame comes back once. The CPU writes the planes into an upload buffer the encoder keeps from frame to frame and maps again before each, or on Apple silicon into the planes buffer itself (D54), the passes below run in one submission after the copy of the planes, if there is one, and the summary of the rate control and the payload come back in one read-back. The CPU writes the start of frame header in front of the payload. A picture that is in GPU memory already, in textures (`Encoder::encode_textures`), takes the place of the upload: `gather.wgsl` packs the textures into the same planes at the start of the transform's pass, so the frame is the same bytes (decision D32). A picture in RGB, in a texture or uploaded into one from CPU memory, is converted into those planes by `gather_rgb.wgsl` in its place (decision D65). | Stage | Shaders | Dispatches | What it does | |---|---|---|---| @@ -1820,7 +1823,7 @@ The last frame's detail, always, gains everything on a still picture and loses u - the colour module's constants, siting taps and forward matrix; - `GpuOptions`' `strict_webgpu`, `plane_stores` and `shared_uploads`. - **Not in the browser build.** The calls that wait for the GPU are not built for wasm32: the decoder's `decode`, `decode_rgb`, `time_frame`, `decode_assembled` and its forms, and `read_band`, and every encode of the GPU encoder. Their helpers may go unused there, which the GPU module allows on wasm32 only. -- **`wgpu` re-exported** as `emberwave_core::wgpu`: the version emberwave is built with. +- **`wgpu` re-exported** as `emberwave_core::wgpu`: the version emberwave is built with. (Since D75, as `emberwave_wgpu::wgpu`.) **Not done.** About thirty public items take or return wgpu's types, so a new major version of wgpu breaks emberwave's Rust API. Two answers remain for 1.0: follow wgpu's major versions, or split a crate without wgpu types from the interop (#152). diff --git a/CHANGELOG.md b/CHANGELOG.md index f3c32e7..2404f2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,11 @@ All notable changes to emberwave. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and versions follow [Semantic Versioning](https://semver.org/). +## [Unreleased] + +### Changed +- **A change for Rust users of the GPU decoder and encoder**: they are the crate `emberwave-wgpu` now, `emberwave_wgpu::Decoder` where it was `emberwave_core::gpu::Decoder`, with the same names, and `emberwave_wgpu::wgpu` where it was `emberwave_core::wgpu`. `emberwave-core` has no `gpu` feature and no wgpu in its dependencies or its API, so that its version need not follow wgpu's (decision D75). The C API, the CLI and the browser player do not change. `emberwave-wgpu` is not on crates.io yet. + ## [0.19.0] - 2026-11-19 The shared library's name carries the major version, and the road to 1.0 is written down. **A change for programs that link the shared library**: the library now names itself `libemberwave_ffi.so.0` on Linux and `@rpath/libemberwave_ffi.0.dylib` on macOS (the 0 is emberwave's major version, 1 from 1.0.0, when it starts to mean the ABI), so a program linked from this version on records that name and needs that file at run time. The release archives hold it, with `libemberwave_ffi.so` and `.dylib` as links to it, so programs linked before still find the unversioned name. Windows, the static libraries and the XCFramework are unchanged. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 0785cdf..cbae9a1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -52,7 +52,7 @@ On Linux with a Vulkan loader from 1.3.284 to 1.4.344 (Debian 13, Ubuntu 25.04 t After a deliberate change to what the encoder writes, `scripts/gen_encoder_vectors.sh` makes its vectors again (macOS), and `scripts/gen_encoder_weights.py` writes its weight table, which is generated rather than written by hand. After a change to the C API, `EMBERWAVE_BLESS=1 cargo test -p emberwave-ffi --test header` writes `crates/emberwave-ffi/include/emberwave.h` anew; commit it with the change. `scripts/check_c_example.sh` needs CMake and a C compiler, and `cargo build -p emberwave-ffi -p emberwave-cli` first. `scripts/build_xcframework.sh` builds the XCFramework for iOS and macOS on a Mac with Xcode, after `rustup target add aarch64-apple-ios aarch64-apple-ios-sim`; `scripts/build_xcframework.sh macos-arm64` builds the Mac's library alone, which needs no extra target. `scripts/check_xcframework.sh target/debug/emberwave-cli` then checks what was built, the iOS Simulator's library in a simulator, which needs an iOS Simulator runtime (Xcode > Settings > Components). -`scripts/build_web.sh` builds the browser player into `web/` (it needs `rustup target add wasm32-unknown-unknown` and `cargo install wasm-bindgen-cli` at the version of the `wasm-bindgen` crate in `Cargo.lock`), and `node scripts/check_web.mjs` then checks that the module instantiates, as CI does; serve `web/` with any static file server, for example `python3 -m http.server -d web 8000`, and open it in a browser with WebGPU. `scripts/verify_4k.sh` is the 4K acceptance check, and [`BENCHMARKS.md`](BENCHMARKS.md) explains the benchmark scripts. Two leak checks run on request, both on the 4K stream of `scripts/gen_bench_data.sh`: `cargo test --release -p emberwave-core --test gpu -- --ignored` counts the GPU resources over 1000 frames, and `scripts/soak.sh` watches the memory of `emberwave-cli` over as many. The README is in English, `README.md`, and in Korean, `README.ko.md` (decision D50): change both together. Write the Korean as Korean prose rather than a sentence-by-sentence translation of the English: the same facts, numbers and links, in sentences built the Korean way. `scripts/bench.sh` rewrites the summary of the benchmarks in each. `scripts/readme_figures.py` draws the READMEs' banner and charts into `docs/images/`, and CI checks that the files are what it draws. Their numbers are copied from `BENCHMARKS.md`, as are those of the READMEs' highlights and of the figures' alt texts: when a benchmark run changes them, change them in the script and in both READMEs and run the script again. `scripts/quality_figure.py` makes the READMEs' picture of the quality, `docs/images/quality.png`, and the first table of [Picture quality](BENCHMARKS.md#picture-quality), by hand: it needs the frame, which the repository does not have, numpy, Pillow and a release build of `emberwave-cli`. The HEVC table there comes from a scratch program that was not kept. The quality numbers are also copied into both READMEs' paragraph and alt text and into decision D49: change them together. +`scripts/build_web.sh` builds the browser player into `web/` (it needs `rustup target add wasm32-unknown-unknown` and `cargo install wasm-bindgen-cli` at the version of the `wasm-bindgen` crate in `Cargo.lock`), and `node scripts/check_web.mjs` then checks that the module instantiates, as CI does; serve `web/` with any static file server, for example `python3 -m http.server -d web 8000`, and open it in a browser with WebGPU. `scripts/verify_4k.sh` is the 4K acceptance check, and [`BENCHMARKS.md`](BENCHMARKS.md) explains the benchmark scripts. Two leak checks run on request, both on the 4K stream of `scripts/gen_bench_data.sh`: `cargo test --release -p emberwave-wgpu --test gpu -- --ignored` counts the GPU resources over 1000 frames, and `scripts/soak.sh` watches the memory of `emberwave-cli` over as many. The README is in English, `README.md`, and in Korean, `README.ko.md` (decision D50): change both together. Write the Korean as Korean prose rather than a sentence-by-sentence translation of the English: the same facts, numbers and links, in sentences built the Korean way. `scripts/bench.sh` rewrites the summary of the benchmarks in each. `scripts/readme_figures.py` draws the READMEs' banner and charts into `docs/images/`, and CI checks that the files are what it draws. Their numbers are copied from `BENCHMARKS.md`, as are those of the READMEs' highlights and of the figures' alt texts: when a benchmark run changes them, change them in the script and in both READMEs and run the script again. `scripts/quality_figure.py` makes the READMEs' picture of the quality, `docs/images/quality.png`, and the first table of [Picture quality](BENCHMARKS.md#picture-quality), by hand: it needs the frame, which the repository does not have, numpy, Pillow and a release build of `emberwave-cli`. The HEVC table there comes from a scratch program that was not kept. The quality numbers are also copied into both READMEs' paragraph and alt text and into decision D49: change them together. ## Test vectors and acceptance bars @@ -73,7 +73,7 @@ After a deliberate change to what the encoder writes, `scripts/gen_encoder_vecto - **No "fix later" comments.** Open an issue instead. - **New dependencies** need a reason in the pull request. - **The C API's structs.** A struct the C API takes or fills in through a pointer starts with `struct_size` (decision D69). A member is added at the end, only, and its zero is its default; the struct's `FIRST_SIZE` stays the size it had before. The calls read and write a struct through `read_struct` and `write_struct`, never by dereferencing the pointer. -- **A release** changes the version in `Cargo.toml` and `EMBERWAVE_VERSION_MAJOR`, `_MINOR`, `_PATCH` and `EMBERWAVE_VERSION` in `crates/emberwave-ffi/src/lib.rs` together, as the build fails otherwise, and regenerates the header. Once its tag's release is out, `cargo publish -p emberwave-core` and then `cargo publish -p emberwave-cli` put the two crates on crates.io; `emberwave-ffi` and `emberwave-web` are not published. The release workflow packages the C library with `scripts/package_ffi.sh`, which gives the shared library the versioned name it carries (D75); at the 1.0.0 release the `.so.0` and `.0.dylib` that `crates/emberwave-ffi/README.md` names become `.so.1` and `.1.dylib`. `LICENSE` and `THIRD_PARTY_NOTICES.md` are copied into both crates, and `scripts/check_license_copies.sh` (a step of the lint job) checks that they are the root's, so a change to either goes into the copies too. +- **A release** changes the version in `Cargo.toml` and `EMBERWAVE_VERSION_MAJOR`, `_MINOR`, `_PATCH` and `EMBERWAVE_VERSION` in `crates/emberwave-ffi/src/lib.rs` together, as the build fails otherwise, and regenerates the header. Once its tag's release is out, `cargo publish -p emberwave-core` and then `cargo publish -p emberwave-cli` put the two crates on crates.io; `emberwave-ffi` and `emberwave-web` are not published. Since D75 `emberwave-cli` depends on `emberwave-wgpu`, which is `publish = false` until the maintainer takes its name on crates.io: until then neither crate is published (publish `emberwave-core` alone and the cli cannot follow), and then the order is core, wgpu, cli, with `emberwave-wgpu` added to `scripts/check_license_copies.sh`. The first release after the split is a minor version, as `emberwave_core::gpu` and the `gpu` feature are gone. The release workflow packages the C library with `scripts/package_ffi.sh`, which gives the shared library the versioned name it carries (D75); at the 1.0.0 release the `.so.0` and `.0.dylib` that `crates/emberwave-ffi/README.md` names become `.so.1` and `.1.dylib`. `LICENSE` and `THIRD_PARTY_NOTICES.md` are copied into both crates, and `scripts/check_license_copies.sh` (a step of the lint job) checks that they are the root's, so a change to either goes into the copies too. ## Commits and pull requests diff --git a/README.ko.md b/README.ko.md index 87f4d60..e0230b4 100644 --- a/README.ko.md +++ b/README.ko.md @@ -155,7 +155,7 @@ iPhone 17의 Safari에서는 [벤치마크 페이지](https://with-developer.git 1.0.0의 날짜는 정하지 않았습니다. 1.0.0은 C·Rust API를 호환되게 유지하겠다는 약속이고, 아래 네 가지가 갖춰지면 태그를 달며, 그 판단은 관리자가 합니다. -- [ ] **안정된 C·Rust API.** 정리된 것: C API가 프로그램을 깨지 않고 늘어나는 규칙(결정 D69), Rust API의 모양(D70), 공유 라이브러리가 헤더의 함수만 내보내는 것(macOS에서 Objective-C 이름 4개만 예외, D73)와 공유 라이브러리 이름에 주 버전이 들어 있는 것(D75). 정했고 아직 할 일([D75](ARCHITECTURE.md), [#165](https://github.com/with-developer/emberwave/issues/165)): GPU 코드를 `emberwave-wgpu`라는 별도 크레이트로 옮겨 `emberwave-core`의 API에는 wgpu 타입이 없게 합니다(지금은 공개 항목 약 서른 개가 wgpu 타입을 받거나 돌려주므로 wgpu의 새 주 버전이 나오면 깨집니다). 남은 것: 클라이언트 자신의 Metal·Vulkan·Direct3D 객체를 받는 호출은 실제로 쓰이기 전까지 잠정입니다. +- [ ] **안정된 C·Rust API.** 정리된 것: C API가 프로그램을 깨지 않고 늘어나는 규칙(결정 D69), Rust API의 모양(D70), 공유 라이브러리가 헤더의 함수만 내보내는 것(macOS에서 Objective-C 이름 4개만 예외, D73)와 공유 라이브러리 이름에 주 버전이 들어 있는 것(D75). GPU 코드는 `emberwave-wgpu`라는 별도 크레이트로 옮겨서, `emberwave-core`의 API에는 wgpu 타입이 없습니다([D75](ARCHITECTURE.md), [#165](https://github.com/with-developer/emberwave/issues/165)). `emberwave-wgpu`의 버전은 wgpu를 따라가며, 아직 crates.io에는 없습니다. 남은 것: 클라이언트 자신의 Metal·Vulkan·Direct3D 객체를 받는 호출은 실제로 쓰이기 전까지 잠정입니다. - [ ] **실제로 쓰이는 클라이언트 하나.** 별도 저장소의 브라우저 클라이언트 `emberwave-stream`이 Mac의 화면을 같은 Mac의 탭으로 스트리밍하는 것까지 됩니다. 로컬 네트워크를 건너는 것은 아직 보이지 못했습니다. 두 번째 기기가 필요하거나, 루프백 에뮬레이터로 대신해도 된다는 판단이 필요합니다. - [ ] **스트림 속도에서 업스트림과 같은 수준의 디코딩.** 4K는 도달했고, 1080p는 0.15~0.3 ms 느립니다([#150](https://github.com/with-developer/emberwave/issues/150)). - [ ] **패키지.** crates.io에는 `emberwave-core`와 `emberwave-cli` 0.19.0이 올라가 있습니다. 아직 없는 것은 브라우저 플레이어용 패키지와, Swift용으로 저장소 루트에 두는 `Package.swift`입니다(결정 D64: 릴리스 워크플로를 바꿔야 합니다). diff --git a/README.md b/README.md index 26f0b67..735c7b6 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ Next, each in a release when it is ready: 1.0.0 has no date. It is the promise that the C and Rust APIs stay compatible, and it will be tagged when the four things below are true; the maintainer makes that call. -- [ ] **Stable C and Rust APIs.** Settled: the rules by which the C API grows without breaking programs (decision D69), the shape of the Rust API (D70), and the shared library exporting the header's functions and nothing else, apart from four Objective-C names on macOS (D73), and the shared library's name carrying the major version (D75). Decided and still to do ([D75](ARCHITECTURE.md), [#165](https://github.com/with-developer/emberwave/issues/165)): the GPU code will move into a crate of its own, `emberwave-wgpu`, so that `emberwave-core` has no wgpu type in its API (about thirty public items take or return wgpu's types today, which a new major version of wgpu would break). Open: the calls on a client's own Metal, Vulkan and Direct3D objects are provisional until a client has used them. +- [ ] **Stable C and Rust APIs.** Settled: the rules by which the C API grows without breaking programs (decision D69), the shape of the Rust API (D70), and the shared library exporting the header's functions and nothing else, apart from four Objective-C names on macOS (D73), and the shared library's name carrying the major version (D75). The GPU code is a crate of its own, `emberwave-wgpu`, so that `emberwave-core` has no wgpu type in its API ([D75](ARCHITECTURE.md), [#165](https://github.com/with-developer/emberwave/issues/165)); `emberwave-wgpu`'s version follows wgpu's, and it is not on crates.io yet. Open: the calls on a client's own Metal, Vulkan and Direct3D objects are provisional until a client has used them. - [ ] **One client in real use.** `emberwave-stream`, the browser client in a repository of its own, streams a Mac's screen to a tab on the same Mac. Across a local network it is not shown yet: that needs a second device, or the loopback emulator accepted in its place. - [ ] **Decoding at a stream's pace level with upstream's.** 4K is there; 1080p is 0.15 to 0.3 ms behind ([#150](https://github.com/with-developer/emberwave/issues/150)). - [ ] **Packages.** On crates.io: `emberwave-core` and `emberwave-cli`, 0.19.0. Not yet: a package for the browser player, and a `Package.swift` at the root of the repository for Swift (decision D64: the release workflow would have to change). diff --git a/crates/emberwave-core/src/cpu/mod.rs b/crates/emberwave-core/src/cpu/mod.rs index 8ecb8e7..d04ff79 100644 --- a/crates/emberwave-core/src/cpu/mod.rs +++ b/crates/emberwave-core/src/cpu/mod.rs @@ -122,7 +122,7 @@ impl Concealer { /// The coefficients the last decode left, concealment included, as the /// GPU decoder's pyramid holds them after the same decode - /// (`gpu::Decoder::read_band` reads the bands that are not LL, and the + /// (`emberwave_wgpu::Decoder::read_band` reads the bands that are not LL, and the /// coarsest LL). For tests: its type is the dequantiser's. #[doc(hidden)] pub fn bands(&self) -> Option<&Bands> { diff --git a/crates/emberwave-core/src/encode/fdwt.rs b/crates/emberwave-core/src/encode/fdwt.rs index 80fcd2e..fc77ea4 100644 --- a/crates/emberwave-core/src/encode/fdwt.rs +++ b/crates/emberwave-core/src/encode/fdwt.rs @@ -12,7 +12,7 @@ use crate::cpu::idwt::{ALPHA, BETA, DELTA, GAMMA, INV_K, K, PADDING, mirror}; /// hold the low-pass and odd positions the high-pass samples, as the inverse /// transform takes them. The line length must be even and larger than the /// padding, which holds for every level of a valid frame. -pub fn forward_line(line: &mut [f32], extended: &mut Vec) { +pub(crate) fn forward_line(line: &mut [f32], extended: &mut Vec) { let len = line.len(); debug_assert!( len > PADDING && len.is_multiple_of(2), @@ -54,7 +54,7 @@ pub fn forward_line(line: &mut [f32], extended: &mut Vec) { /// The four bands of one level, each half the width and height of its input. #[derive(Debug, Clone, PartialEq)] -pub struct Level { +pub(crate) struct Level { /// Low-pass in both directions; the next level's input. pub ll: Vec, /// High-pass horizontally (odd columns). @@ -68,7 +68,7 @@ pub struct Level { /// One level of the 2-D forward transform of a `width` x `height` image, /// row-major: rows first, then columns, then the samples sorted into the four /// bands, as [`crate::cpu::idwt::inverse_2d`] expects them. -pub fn forward_2d(mut image: Vec, width: usize, height: usize) -> Level { +pub(crate) fn forward_2d(mut image: Vec, width: usize, height: usize) -> Level { let mut extended = Vec::new(); for row in image.chunks_exact_mut(width) { forward_line(row, &mut extended); @@ -112,7 +112,7 @@ pub fn sample_level(sample: u8) -> f32 { /// ([`sample_level`]), padded to `aligned_width` x `aligned_height` by /// repeating the last column and the last row. Repeating the edge keeps the /// padding from adding detail that would cost bits. -pub fn pad_plane( +pub(crate) fn pad_plane( samples: &[u8], width: usize, height: usize, diff --git a/crates/emberwave-core/src/encode/quant.rs b/crates/emberwave-core/src/encode/quant.rs index 84934ed..b98ed6c 100644 --- a/crates/emberwave-core/src/encode/quant.rs +++ b/crates/emberwave-core/src/encode/quant.rs @@ -19,7 +19,7 @@ use crate::bitstream::{Band, BandLayout, ChromaSubsampling, Component}; pub const DROP_STEPS: usize = 16; /// Coefficients of an 8x8 block. -pub const BLOCK8_VALUES: usize = SUBBLOCKS_PER_BLOCK8 * VALUES_PER_SUBBLOCK; +pub(crate) const BLOCK8_VALUES: usize = SUBBLOCKS_PER_BLOCK8 * VALUES_PER_SUBBLOCK; /// The largest bit exponent of a band: coefficients are scaled by at most /// `2^12` before quantisation, which keeps every block within 15 base @@ -56,7 +56,7 @@ const INVERSE_SCALES: [f32; MAX_SCALE_CODE as usize + 1] = { /// in `c * 2^b` costs about the same in the picture in every band, as `4^b` /// follows the energy the inverse transform gives a coefficient of the band. /// Low-pass bands and coarser levels get more bits, chroma one bit less. -pub fn band_exponent(component: Component, level: usize, band: Band) -> i32 { +pub(crate) fn band_exponent(component: Component, level: usize, band: Band) -> i32 { let band_bits = match band { Band::Ll => 2, Band::Hl | Band::Lh => 1, @@ -97,7 +97,7 @@ impl BandQuant { /// The quant code of a block of the band that drops `drop` bit-planes: /// block scale `2^(drop - b)`, mantissa zero. - pub fn quant_code(&self, drop: u8) -> u8 { + pub(crate) fn quant_code(&self, drop: u8) -> u8 { ((self.exponent + MAX_SCALE_EXP - i32::from(drop)) as u8) << QUANT_MANTISSA_BITS } } @@ -105,7 +105,7 @@ impl BandQuant { /// The position of coefficient `index` (subblock, then value) in its 8x8 /// block: subblocks run down two columns of four, values down the two rows /// of a subblock's four columns (`bitstream.md`, "Decoding 8x8 blocks"). -pub fn value_position(index: usize) -> (usize, usize) { +pub(crate) fn value_position(index: usize) -> (usize, usize) { let (subblock, value) = (index / VALUES_PER_SUBBLOCK, index % VALUES_PER_SUBBLOCK); let x = subblock / 4 * SUBBLOCK_WIDTH + value / SUBBLOCK_HEIGHT; let y = subblock % 4 * SUBBLOCK_HEIGHT + value % SUBBLOCK_HEIGHT; @@ -115,7 +115,7 @@ pub fn value_position(index: usize) -> (usize, usize) { /// The coefficients of the 8x8 block `raster` (0 to 15, row-major) of the /// 32x32 block at (`block_x`, `block_y`) of a band, in coefficient order. /// Positions outside the band are zero. -pub fn gather_block8( +pub(crate) fn gather_block8( band: &[f32], layout: &BandLayout, block_x: u32, @@ -161,17 +161,17 @@ pub struct Block8 { impl Block8 { /// Whether the block is coded with `drop` planes dropped: some subblock /// keeps a plane above the base. Otherwise every magnitude is zero. - pub fn active(&self, drop: u8) -> bool { + pub(crate) fn active(&self, drop: u8) -> bool { self.plane_bytes[usize::from(drop)] != 0 } /// Bit-planes of subblock `subblock` with `drop` planes dropped. - pub fn subblock_planes(&self, subblock: usize, drop: u8) -> u8 { + pub(crate) fn subblock_planes(&self, subblock: usize, drop: u8) -> u8 { self.planes[subblock].saturating_sub(drop) } /// Base bit-planes with `drop` planes dropped. - pub fn base_planes(&self, drop: u8) -> u8 { + pub(crate) fn base_planes(&self, drop: u8) -> u8 { self.base.saturating_sub(drop) } } @@ -186,7 +186,10 @@ impl Block8 { /// puts the reconstruction in the middle of each step. The base bit-planes /// are all but the top three of the largest magnitude, and each 4x2 /// subblock has as many more as its own largest magnitude needs, 0 to 3. -pub fn analyse_block8(coefficients: &[f32; BLOCK8_VALUES], quant: &BandQuant) -> Option { +pub(crate) fn analyse_block8( + coefficients: &[f32; BLOCK8_VALUES], + quant: &BandQuant, +) -> Option { let resolution = exact_pow2(quant.exponent); let scaled = coefficients.map(|c| (c * resolution).abs()); let largest = scaled.iter().copied().fold(0.0f32, f32::max); diff --git a/crates/emberwave-core/src/encode/rate.rs b/crates/emberwave-core/src/encode/rate.rs index 09f314b..7f5c079 100644 --- a/crates/emberwave-core/src/encode/rate.rs +++ b/crates/emberwave-core/src/encode/rate.rs @@ -17,7 +17,7 @@ use super::quant::DROP_STEPS; /// Number of keys. -pub const KEYS: usize = 512; +pub(crate) const KEYS: usize = 512; /// 2^`exponent` as an exact `f32`, for exponents in the normal range. fn exact_pow2(exponent: i32) -> f32 { @@ -37,7 +37,7 @@ fn threshold(key: usize) -> f32 { /// The key of a step that adds `distortion` and saves `saving` words: the /// highest threshold it reaches, 0 for none (including a step that adds no /// distortion at all). -pub fn key(distortion: f32, saving: u16) -> u16 { +pub(crate) fn key(distortion: f32, saving: u16) -> u16 { let saving = f32::from(saving); let reaches = |key: usize| distortion >= saving * threshold(key); // The thresholds increase: find the first one above 0 not reached. @@ -70,7 +70,7 @@ pub struct BlockCost { /// A step of a block: drop planes up to `drop`, saving `saving` words. #[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Step { +pub(crate) struct Step { pub key: u16, pub block: u32, pub drop: u8, @@ -80,7 +80,7 @@ pub struct Step { /// The numbers of planes a block may drop that are worth considering: for /// each size the block can have, the one with the least distortion (the /// fewest planes on a tie). Sizes decrease along the list. -pub fn points(cost: &BlockCost) -> Vec { +pub(crate) fn points(cost: &BlockCost) -> Vec { let mut points: Vec = Vec::new(); for drop in 0..=cost.max_drop.min(DROP_STEPS as u8 - 1) { let (words, distortion) = ( @@ -102,7 +102,7 @@ pub fn points(cost: &BlockCost) -> Vec { /// Appends the steps of block `block` in the order they must be applied: /// from each of its [`points`] to the next. A step's key is at least that of /// the step before it. -pub fn steps(block: u32, cost: &BlockCost, out: &mut Vec) { +pub(crate) fn steps(block: u32, cost: &BlockCost, out: &mut Vec) { let mut previous_key = 0u16; for pair in points(cost).windows(2) { let (from, to) = (usize::from(pair[0]), usize::from(pair[1])); diff --git a/crates/emberwave-ffi/Cargo.toml b/crates/emberwave-ffi/Cargo.toml index 812919f..19ef704 100644 --- a/crates/emberwave-ffi/Cargo.toml +++ b/crates/emberwave-ffi/Cargo.toml @@ -21,7 +21,7 @@ wgpu.workspace = true # A context on the caller's own Metal device and queue # (emberwave_context_create_metal), and the caller's own textures # (emberwave_texture_from_metal). wgpu uses these crates on Apple systems -# already, and the core uses pollster. +# already, and emberwave-wgpu uses pollster. [target.'cfg(any(target_os = "macos", target_os = "ios"))'.dependencies] objc2 = "0.6" objc2-metal = { version = "0.3", default-features = false, features = [ diff --git a/crates/emberwave-wgpu/src/lib.rs b/crates/emberwave-wgpu/src/lib.rs index 149f35c..a651275 100644 --- a/crates/emberwave-wgpu/src/lib.rs +++ b/crates/emberwave-wgpu/src/lib.rs @@ -19,9 +19,13 @@ //! [`Decoder::decode`] and the [`Encoder`]'s encodes, are not built for //! wasm32; the decoder's `record_*` and `submit_*` calls are. -// The calls left out of the browser build leave their helpers unused there; -// the native builds check for code that is dead everywhere. -#![cfg_attr(target_arch = "wasm32", allow(dead_code, unused_imports))] +// The calls left out of the browser build leave their helpers unused there, +// and the docs link to them (decision D70); the native builds check for code +// that is dead everywhere and for broken links. +#![cfg_attr( + target_arch = "wasm32", + allow(dead_code, unused_imports, rustdoc::broken_intra_doc_links) +)] pub use wgpu; diff --git a/crates/emberwave-wgpu/tests/gpu.rs b/crates/emberwave-wgpu/tests/gpu.rs index de728ac..85ed459 100644 --- a/crates/emberwave-wgpu/tests/gpu.rs +++ b/crates/emberwave-wgpu/tests/gpu.rs @@ -2137,7 +2137,7 @@ fn a_lost_device_is_an_error_rather_than_a_stale_result() { /// every way in turn, leave the GPU resources as they were after the first /// frames. It needs the streams of `scripts/gen_bench_data.sh` and takes a /// while, so it only runs on request: -/// `cargo test --release -p emberwave-core --test gpu -- --ignored --nocapture`. +/// `cargo test --release -p emberwave-wgpu --test gpu -- --ignored --nocapture`. /// `scripts/soak.sh` watches the memory of the process for the same purpose. #[test] #[ignore = "decodes 1000 4K frames; needs scripts/gen_bench_data.sh"]