diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0fe6f11..866ee8e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,9 +18,10 @@ env: jobs: # Whether the change is more than documentation. A pull request that only - # changes Markdown files and the pictures under docs/ skips the jobs that - # build and run the code; the lint job still checks the documents' figures and - # copies. A push to main runs everything. + # changes Markdown files, other than the npm package's README, and the + # pictures under docs/ skips the jobs that build and run the code; the lint + # job still checks the documents' figures and copies. A push to main runs + # everything. changes: name: what changed runs-on: ubuntu-latest @@ -42,8 +43,11 @@ jobs: echo "code=true" >> "$GITHUB_OUTPUT" exit 0 fi - # Everything that is not a Markdown file or a picture of docs/. - other=$(git diff --name-only "$BASE...$HEAD" | grep -v -E '(\.md$|^docs/images/)' || true) + # Everything that is not a Markdown file or a picture of docs/, and + # the npm package's README, which ships in the package and which + # its build checks (decision D76). + other=$(git diff --name-only "$BASE...$HEAD" | + awk '/^crates\/emberwave-web\/npm\// || !/(\.md$|^docs\/images\/)/') if [ -n "$other" ]; then echo "code=true" >> "$GITHUB_OUTPUT" echo "changed beyond the documentation:" @@ -138,6 +142,12 @@ jobs: # broken one would otherwise show only once it is published. - run: scripts/build_web.sh - run: node scripts/check_web.mjs + # The same module as an npm package, ready to publish but not published + # (decision D76): what it would ship, and that it installs from its + # archive and instantiates as a page's dependency. The build above + # leaves cargo nothing to do. + - run: scripts/build_npm.sh + - run: scripts/check_npm.sh build-test: needs: changes diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 6603bcf..b05a197 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -507,6 +507,8 @@ The player also decodes a stream packet by packet, as a client of a live stream CI builds the module as Pages does and instantiates it in Node (`scripts/check_web.mjs`), so that a module whose glue does not load fails a pull request rather than the published page. The check also encodes two of the demo's pictures and splits a frame with `packet_ends`. +The same module is also built as an npm package for other pages, with TypeScript declarations (`scripts/build_npm.sh`, decision D76). It is ready to publish and not published. CI checks it as a page's project would take it: packed, installed from the archive, imported by its name, and then put through the same check. + ## C API `crates/emberwave-ffi` is the decoder and the GPU encoder for C programs. It builds a shared library (and, for releases, a static one) with the functions of `include/emberwave.h`, which cbindgen generates from `src/lib.rs`; `tests/header.rs` fails when the committed header falls behind the source. [`crates/emberwave-ffi/README.md`](crates/emberwave-ffi/README.md) is the guide for C programmers. The objects are those of the Rust API: @@ -1937,3 +1939,22 @@ The last frame's detail, always, gains everything on a still picture and loses u **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. +### 2026-11-24 — D76: The browser player as an npm package + +**Context.** The README's checklist for 1.0.0 lists packages, and the browser had none. D74 left it to the web build: a page other than the player's own took the module by building emberwave, or by copying `web/pkg/` from a build, which has no TypeScript declarations. npm is where a web project looks for such a module. Publishing there, as on crates.io (D74), is the maintainer's call: a version once published cannot be published again, even after it is unpublished, and the first publish takes the name. + +**Decision.** The module is built as an npm package, ready to publish, and not published. +- `scripts/build_npm.sh` builds the crate as `scripts/build_web.sh` does and runs wasm-bindgen with the pages' target, `--target web`, this time with TypeScript declarations, into `target/npm/emberwave-web/`. It adds a `package.json`, the package's README (`crates/emberwave-web/npm/README.md`, with examples that use the module's real API) and copies of `LICENSE` and `THIRD_PARTY_NOTICES.md` made at build time, so `scripts/check_license_copies.sh` has no new copy to keep equal. `emberwave_web_bg.wasm.d.ts`, which declares the wasm's raw exports for importing the wasm directly, does not ship. +- `package.json`: the crate's version, which is the workspace's; `"type": "module"`; `main`, `module` and `types` on the glue and its declarations; `exports` with `.` (declarations, then the glue), the wasm file, for a page whose bundler needs the file's URL to pass to `init`, and `package.json`; `files` naming the six files that ship beside it; `"sideEffects": false`, as the glue only defines its exports when imported; MIT, the repository with the crate's directory, keywords. It has no dependencies. In 0.19.0 the archive is 200.4 kB, 659.6 kB unpacked, of which the wasm is 551.8 kB. +- The pages' target, so that the package is the module the pages test, and a page uses it as `web/main.js` uses `web/pkg/`: `init()` fetches the wasm from beside the module, or takes the file or its URL, so the wasm needs no bundler's help; a page without a bundler maps the package's name to the glue with an import map. Not chosen: `--target bundler`, whose module imports the wasm as an ES module and needs a bundler that supports that (webpack's async WebAssembly, a plugin for Vite), and wasm-pack, which writes a `package.json` too but is one more tool to install and pin for what wasm-bindgen and a few lines of shell do. +- The paths of the source files, which panic messages name and which on a personal machine lie under the user's home directory (16 of them in the first build here), are remapped: the home directory to `/home`, cargo's sources to `/cargo`, the repository to `/emberwave`, so that a package built on the maintainer's machine says nothing about it. `build_npm.sh` fails if the wasm still names the home directory, cargo's sources, the repository or the target directory. `scripts/build_web.sh` builds with the same flags, so that the pages' wasm and the package's are the same bytes and cargo builds them once; the pages' panic messages name the remapped paths where they named the CI runner's. +- `scripts/check_npm.sh` prints what `npm pack --dry-run` lists, packs the package, installs the archive into a scratch project offline, as a page's project would take it, and runs `scripts/check_web.mjs` on that project. Given a project, the check finds the package's files through its `exports`, checks that they are exactly those of `files`, that `type` is `module`, that every path of `main`, `module`, `types` and `exports`, under every condition, is one of them, that `exports` gives the declarations first and the same as `types`, and that they declare the module's exports; it then imports the package by its name from a module in the project, through Node's ES module resolution, and puts it through the checks of the pages' module. CI's wasm job runs both scripts after the pages' build, when cargo has nothing left to build; the check took about a second on an Apple M3 Max. CI does not take the package's README for documentation, though it is Markdown: a pull request that changes it alone runs the jobs that build the code, as for any other change. + +**The name, which the maintainer confirms before the first publish.** Proposed: `emberwave-web`, without a scope. It is the crate's name, it sits beside `emberwave-core` and `emberwave-cli` on crates.io, it is the shortest to install, and it needs only the maintainer's npm account. On 2026-11-24 the registry had no package `emberwave-web` or `emberwave`, and no scope `@with-developer` ("Scope not found"). Not chosen, and the maintainer's to prefer: `@with-developer/emberwave-web`, which ties the name to the GitHub organisation and under which no one else can publish, but needs an npm organisation `with-developer` made first, and a first publish with `--access public`. The name is `NAME` in `scripts/build_npm.sh` and the package's README's examples, which the script checks agree; the READMEs and this entry name it too. + +**Not done.** Nothing is published: no npm account, organisation or token was made, and no name is held on the registry. `npm publish --dry-run`, without a login, is as far as it went. The release workflow does not publish to npm. Not tried here: a bundler building a page with the package, and a TypeScript compiler on the declarations (the check reads them as text); the module in a browser is what the player's page shows. + +**Consequence.** +- A release can publish the package after the maintainer's approval, which holds for one version, as for the crates (`CONTRIBUTING.md`): `scripts/build_npm.sh`, `scripts/check_npm.sh`, `npm publish target/npm/emberwave-web`. npm's Trusted Publishing from the release workflow would publish without a long-lived token; it is not set up. +- The package's API is the module's: a change to `Player`, `Demo`, `Bench` or `packet_ends` changes it. The package carries emberwave's version, but the 1.0 promise is for the C and Rust APIs; whether it covers this one is open. +- To revert, remove the two scripts, the package's README, the two CI steps, the README's exception in CI's documentation filter, the project argument of `scripts/check_web.mjs` and the remapped paths of `scripts/build_web.sh`; nothing outside the repository changed. diff --git a/CHANGELOG.md b/CHANGELOG.md index 2404f2b..88eb84f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ All notable changes to emberwave. The format follows [Keep a Changelog](https:// ## [Unreleased] +### Added +- The browser player's module as an npm package, ready to publish and not published (decision D76): `scripts/build_npm.sh` builds it into `target/npm/emberwave-web`, with TypeScript declarations and a README for web pages, and `scripts/check_npm.sh`, which CI runs, installs its archive into a scratch project and checks it there. The name proposed for npm is `emberwave-web`; the maintainer confirms it before the first publish. The package and the pages' module are built with the source paths that panic messages name remapped, so that the wasm names no directory of the machine that built it. + ### 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. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index cbae9a1..96c9dea 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-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. +`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/build_npm.sh` builds the same module as an npm package into `target/npm/emberwave-web` (it also needs Node), and `scripts/check_npm.sh` lists what the package would ship, installs its archive into a scratch project and runs `check_web.mjs` on it there, as CI does (decision D76). `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. 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. +- **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; the crates `emberwave-ffi` and `emberwave-web` are not published. The browser player's npm package (D76) is not published yet. Once the maintainer approves, for one version at a time as for the crates, it would be published from the tag: `scripts/build_npm.sh`, `scripts/check_npm.sh`, then `npm publish target/npm/emberwave-web` by the maintainer's own npm login. The first publish takes the package's name on npm, which the maintainer confirms before it (`NAME` in `build_npm.sh` and the package's README). 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 e0230b4..0f48180 100644 --- a/README.ko.md +++ b/README.ko.md @@ -109,6 +109,10 @@ C API를 쓰면 클라이언트는 패킷을 받는 대로 넘겨 호출자의 iPhone, iPad, Mac 앱을 위해서는 릴리스마다 정적 라이브러리를 XCFramework(`Emberwave.xcframework`)로도 제공하며, Swift에서는 `import Emberwave`로 씁니다. Metal 클라이언트는 그림을 GPU 텍스처 한 장에 그리게 하거나 Y, Cb, Cr 평면을 텍스처 세 장에 담게 한 뒤, 그 `id`를 읽을 수 있습니다([GPU의 그림](crates/emberwave-ffi/README.md#pictures-on-the-gpu-metal)). [`examples/swift`](crates/emberwave-ffi/examples/swift)는 이 프레임워크로 Swift에서 파일을 디코딩하는 예제이고, [`examples/ios`](crates/emberwave-ffi/examples/ios)는 iPhone·iPad용 벤치마크 앱입니다. CI는 예제와 앱을 이 프레임워크로 iOS 시뮬레이터에서 실행합니다([iPhone, iPad, Mac 앱](crates/emberwave-ffi/README.md#iphone-ipad-and-mac-apps)). +### 웹 페이지에서 쓰기 + +[브라우저 플레이어](https://with-developer.github.io/emberwave/)는 WebGPU로 디코딩해 캔버스에 그리는 WebAssembly 모듈입니다([`ARCHITECTURE.md`](ARCHITECTURE.md#browser-player)). 플레이어 페이지(`web/`)용으로는 `scripts/build_web.sh`가 빌드합니다. 다른 페이지에서 쓸 수 있도록 `scripts/build_npm.sh`가 같은 모듈을 TypeScript 선언과 함께 npm 패키지로 묶어 `target/npm/emberwave-web`에 만들고, `scripts/check_npm.sh`가 이를 검사합니다. 페이지에서 쓰는 방법은 [패키지의 README](crates/emberwave-web/npm/README.md)에 있습니다. 이 패키지는 아직 npm에 올리지 않았습니다. npm에서 쓸 이름과 게시 여부는 관리자가 정합니다(결정 D76). 그전까지는 `npm pack target/npm/emberwave-web --pack-destination target/npm`으로 만든 압축 파일을 프로젝트에 설치해 쓸 수 있습니다. + ## 성능 @@ -158,7 +162,7 @@ iPhone 17의 Safari에서는 [벤치마크 페이지](https://with-developer.git - [ ] **안정된 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: 릴리스 워크플로를 바꿔야 합니다). +- [ ] **패키지.** crates.io에는 `emberwave-core`와 `emberwave-cli` 0.19.0이 올라가 있습니다. 브라우저 플레이어 모듈은 npm 패키지 `emberwave-web`으로 준비되어 있고 CI가 빌드와 검사를 하지만, 아직 올리지 않았습니다. 패키지 이름과 첫 게시는 관리자가 정합니다(결정 D76). 아직 없는 것은 Swift용으로 저장소 루트에 두는 `Package.swift`입니다(결정 D64: 릴리스 워크플로를 바꿔야 합니다). ## 저장소 구성 diff --git a/README.md b/README.md index 735c7b6..56e7bff 100644 --- a/README.md +++ b/README.md @@ -109,6 +109,10 @@ The C API decodes packets as a client receives them, into the caller's memory, a For apps on iPhones, iPads and Macs, each release also has the static library as an XCFramework, `Emberwave.xcframework`, which Swift imports as `Emberwave`; Metal clients can have the picture drawn into a texture on the GPU, or its Y, Cb and Cr planes put into three, and read the `id` ([Pictures on the GPU](crates/emberwave-ffi/README.md#pictures-on-the-gpu-metal)). [`examples/swift`](crates/emberwave-ffi/examples/swift) decodes a file with it from Swift, [`examples/ios`](crates/emberwave-ffi/examples/ios) is a benchmark app for iPhones and iPads, and CI runs the examples and the app with it in an iOS Simulator ([iPhone, iPad and Mac apps](crates/emberwave-ffi/README.md#iphone-ipad-and-mac-apps)). +### In a web page + +The [browser player](https://with-developer.github.io/emberwave/) is a WebAssembly module that decodes with WebGPU and draws on a canvas ([`ARCHITECTURE.md`](ARCHITECTURE.md#browser-player)). `scripts/build_web.sh` builds it for the player's page in `web/`. For other pages, `scripts/build_npm.sh` builds the same module as an npm package, with TypeScript declarations, into `target/npm/emberwave-web`, and `scripts/check_npm.sh` checks it; [its README](crates/emberwave-web/npm/README.md) shows how a page uses it. The package is not on npm yet: its name there and its publishing are the maintainer's to decide (decision D76). Until then, a project can install the archive that `npm pack target/npm/emberwave-web --pack-destination target/npm` makes. + ## Performance @@ -158,7 +162,7 @@ Next, each in a release when it is ready: - [ ] **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). +- [ ] **Packages.** On crates.io: `emberwave-core` and `emberwave-cli`, 0.19.0. The browser player's module is ready as an npm package, `emberwave-web`, built and checked by CI but not published: its name and the first publish wait for the maintainer (decision D76). Not yet: a `Package.swift` at the root of the repository for Swift (decision D64: the release workflow would have to change). ## Repository layout diff --git a/crates/emberwave-web/npm/README.md b/crates/emberwave-web/npm/README.md new file mode 100644 index 0000000..b5b255b --- /dev/null +++ b/crates/emberwave-web/npm/README.md @@ -0,0 +1,78 @@ + + +# emberwave-web + +Decode [PyroWave](https://github.com/Themaister/pyrowave) video in a web page, on the GPU through WebGPU. This is the WebAssembly module of [emberwave](https://github.com/with-developer/emberwave)'s browser player: it plays PWV1 files (`.pwv1`), or a stream packet by packet as a client receives it, and draws the pictures on a canvas. [Try the player](https://with-developer.github.io/emberwave/). + +It needs a browser with WebGPU: `Player.create` fails without it. The pictures are decoded on the GPU and drawn there, straight onto the canvas. + +## Install + +```sh +npm install emberwave-web +``` + +## Play a file + +```js +import init, { Player } from "emberwave-web"; + +// Fetches emberwave_web_bg.wasm from beside the module. Where a bundler moves +// the module, pass the file's URL: init({ module_or_path: url }); the package +// exports the file as "emberwave-web/emberwave_web_bg.wasm". +await init(); + +const canvas = document.querySelector("canvas"); +const player = await Player.create(canvas); +const bytes = new Uint8Array(await (await fetch("stream.pwv1")).arrayBuffer()); +// Sizes the canvas to the pictures, and describes the stream. +console.log(player.load(bytes)); + +// The file's frames in turn, at the stream's frame rate, looping. +const interval = 1000 / player.frame_rate(); +let due = 0; +requestAnimationFrame(function frame(now) { + if (now >= due) { + due += interval; + if (due < now) { + due = now + interval; // after a pause, start again rather than catch up + } + player.draw_next(); + } + requestAnimationFrame(frame); +}); +``` + +## Play a stream as packets arrive + +```js +// 4:2:0 (true for 4:4:4) at 60 frames a second; sizes the canvas too. +player.open_stream(1920, 1080, false, 60); + +// For each packet of the frame being assembled, in any order. The transport +// numbers its frames: it ignores packets of frames older than this one. +player.push_packet(packet); + +// Before the first packet of a newer frame: draw this one, whole, or in part +// if enough of it arrived, then let go of its packets. +if (player.is_ready(true)) { + player.draw_assembled(); +} +player.drop_packets(); +``` + +`packet_ends(frame, maxBytes)` says where a host would split an encoded frame into packets. `set_partial_share` and `set_concealment` choose how a frame that lost packets is drawn, and `received_blocks` and `total_blocks` count what arrived of it. + +## Good to know + +- Methods throw an `Error` with a message for a file, a packet or a call they cannot take. +- A player holds GPU memory: call `player.free()` when done with it. Loading another file or opening another stream lets go of the last one's. +- If `player.is_lost()`, the GPU device is gone: make a new player. +- `Demo` draws and encodes a demo stream on the CPU, and `Bench` times the decoding on the browser's GPU, as the player's pages do. +- The TypeScript declarations, `emberwave_web.d.ts`, document every method. +- The version is emberwave's. This module's API may change between minor versions; [the changelog](https://github.com/with-developer/emberwave/blob/main/CHANGELOG.md) says what changed. +- The examples import the package by its name, as a bundler resolves it; a page without one maps the name to `emberwave_web.js` with an import map. + +## License + +MIT, in `LICENSE`. `THIRD_PARTY_NOTICES.md` holds PyroWave's license. diff --git a/scripts/build_npm.sh b/scripts/build_npm.sh new file mode 100755 index 0000000..13785d3 --- /dev/null +++ b/scripts/build_npm.sh @@ -0,0 +1,146 @@ +#!/usr/bin/env bash +# Builds the browser player's module as an npm package into +# target/npm/emberwave-web/, for web pages that take it as a dependency: the +# module and its JavaScript glue, as scripts/build_web.sh builds them for the +# pages, with TypeScript declarations this time, a package.json at the crate's +# version, the package's README (crates/emberwave-web/npm/README.md), LICENSE +# and THIRD_PARTY_NOTICES.md. scripts/check_npm.sh checks what it built. +# +# The package is ready to publish, and not published: publishing it, and the +# name it takes on npm, are the maintainer's (decision D76). +# +# Usage: scripts/build_npm.sh +# +# Needs what scripts/build_web.sh needs (the wasm32-unknown-unknown target and +# wasm-bindgen-cli at the version of the wasm-bindgen crate in Cargo.lock), +# and Node. +set -euo pipefail + +# The name proposed for npm (D76), which the maintainer confirms before the +# first publish. The package's README names it too, which is checked below. +NAME=emberwave-web + +ROOT=$(cd "$(dirname "$0")/.." && pwd) +OUT=$ROOT/target/npm/emberwave-web +README=$ROOT/crates/emberwave-web/npm/README.md + +# Where cargo puts what it builds, however that is configured, and the +# crate's version, which is the workspace's. +TARGET_DIR= +VERSION= +{ IFS= read -r TARGET_DIR; IFS= read -r VERSION; } < <( + cargo metadata --format-version 1 --no-deps --manifest-path "$ROOT/Cargo.toml" | + node -e 'const metadata = JSON.parse(require("fs").readFileSync(0, "utf8")); + console.log(metadata.target_directory); + console.log(metadata.packages.find((p) => p.name === "emberwave-web").version);' +) || true +if [ -z "$TARGET_DIR" ] || [ -z "$VERSION" ]; then + echo "found no target directory or version in cargo's metadata (needs cargo and node)" >&2 + exit 1 +fi + +WANT=$(awk '/^name = "wasm-bindgen"$/ { getline; gsub(/"/, "", $3); print $3 }' "$ROOT/Cargo.lock") +HAVE=$(wasm-bindgen --version 2>/dev/null | awk '{ print $2 }' || true) +if [ "$HAVE" != "$WANT" ]; then + echo "needs wasm-bindgen-cli $WANT (found ${HAVE:-none}):" \ + "cargo install wasm-bindgen-cli --version $WANT" >&2 + exit 1 +fi + +# The examples of the README import the package by its name. +if ! grep -q "^npm install $NAME\$" "$README" || ! grep -q "from \"$NAME\";" "$README"; then + echo "$README does not name the package $NAME in its examples" >&2 + exit 1 +fi + +# The wasm keeps the paths of the source files its panic messages name, +# which on a personal machine are under the user's home directory. The +# package is built with them remapped, so that it says nothing about the +# machine that built it; the check after wasm-bindgen fails if one is left. +# scripts/build_web.sh remaps them alike, so that the pages' wasm is this +# one and cargo builds it once. Last match wins: the home directory, then +# cargo's sources, then this repository. Separated by 0x1f, so that a path +# may hold spaces; this replaces RUSTFLAGS for this build. +CARGO_SOURCES=${CARGO_HOME:-$HOME/.cargo} +SEP=$'\x1f' +export CARGO_ENCODED_RUSTFLAGS="--remap-path-prefix=$HOME=/home${SEP}--remap-path-prefix=$CARGO_SOURCES=/cargo${SEP}--remap-path-prefix=$ROOT=/emberwave" +cargo build --release --locked --target wasm32-unknown-unknown -p emberwave-web \ + --manifest-path "$ROOT/Cargo.toml" +unset CARGO_ENCODED_RUSTFLAGS + +rm -rf "$OUT" +# The pages' target, an ES module whose default export fetches the wasm from +# beside it or takes it from the caller, so that a page uses the package as +# web/main.js uses web/pkg. The declarations of the wasm's own exports, +# emberwave_web_bg.wasm.d.ts, are for importing the wasm directly, which +# this target does not do: they do not ship. +wasm-bindgen --target web --out-dir "$OUT" \ + "$TARGET_DIR/wasm32-unknown-unknown/release/emberwave_web.wasm" +rm "$OUT/emberwave_web_bg.wasm.d.ts" +# The directories of this machine that the wasm must not name, but for one +# that is a replacement itself, as a repository mounted at /emberwave is. +for path in "$HOME" "$CARGO_SOURCES" "$ROOT" "$TARGET_DIR"; do + case $path in + / | /home | /cargo | /emberwave) continue ;; + esac + if LC_ALL=C grep -q -a -F -- "$path/" "$OUT/emberwave_web_bg.wasm"; then + echo "the wasm names $path/, which the package must not ship" >&2 + rm -rf "$OUT" + exit 1 + fi +done + +cp "$README" "$OUT/README.md" +cp "$ROOT/LICENSE" "$ROOT/THIRD_PARTY_NOTICES.md" "$OUT/" + +# "files" is what ships, beside package.json; check_npm.sh checks the archive +# against the same list. The glue has no effect on import beyond defining +# its exports, hence "sideEffects": false. +cat > "$OUT/package.json" <&2 + exit 1 +fi +WORK=$(mktemp -d) +trap 'rm -rf "$WORK"' EXIT + +# What would ship, and the sizes. +(cd "$PACKAGE" && npm pack --dry-run) + +ARCHIVE=$(cd "$PACKAGE" && npm pack --silent --pack-destination "$WORK") +mkdir "$WORK/project" +echo '{ "private": true }' > "$WORK/project/package.json" +(cd "$WORK/project" && + npm install --offline --ignore-scripts --no-audit --no-fund "$WORK/$ARCHIVE") +node "$ROOT/scripts/check_web.mjs" "$WORK/project" diff --git a/scripts/check_web.mjs b/scripts/check_web.mjs index 368ae5c..8087425 100644 --- a/scripts/check_web.mjs +++ b/scripts/check_web.mjs @@ -5,18 +5,114 @@ // shows before it is published. // // node scripts/check_web.mjs +// +// Given a scratch project's directory, it checks the npm package installed +// there instead, the project's one dependency (decision D76): its files are +// those that ship, every file its package.json points to is one of them, its +// declarations declare the module's exports, and the module, imported by the +// package's name as a page's code would, does what the pages' does. +// scripts/check_npm.sh makes such a project; the check writes one file into +// it, the module that imports the package. +// +// node scripts/check_web.mjs PROJECT_DIR + +import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs"; +import { createRequire } from "node:module"; +import { dirname, join } from "node:path"; +import { pathToFileURL } from "node:url"; + +// What the package ships, as its package.json's "files" says, with +// package.json itself. +const PACKAGE_FILES = [ + "LICENSE", + "README.md", + "THIRD_PARTY_NOTICES.md", + "emberwave_web.d.ts", + "emberwave_web.js", + "emberwave_web_bg.wasm", + "package.json", +]; -import { readFileSync } from "node:fs"; +// The module of the pages, from web/pkg/. +async function pagesModule() { + const pkg = new URL("../web/pkg/", import.meta.url); + // The glue is an ES module in a .js file, which Node takes for CommonJS + // without a package.json saying otherwise: imported from its text instead. + const glue = readFileSync(new URL("emberwave_web.js", pkg)); + const module = await import(`data:text/javascript;base64,${glue.toString("base64")}`); + module.initSync({ module: readFileSync(new URL("emberwave_web_bg.wasm", pkg)) }); + return module; +} + +// The module of the npm package installed in `project`. +async function packageModule(project) { + const manifest = JSON.parse(readFileSync(join(project, "package.json"), "utf8")); + const names = Object.keys(manifest.dependencies ?? {}); + if (names.length !== 1) { + throw new Error(`${project} has ${names.length} dependencies, not the package alone`); + } + const [name] = names; + // Node resolves these through the package's "exports". + const require = createRequire(join(project, "package.json")); + const wasm = require.resolve(`${name}/emberwave_web_bg.wasm`); + const own = require.resolve(`${name}/package.json`); + const root = dirname(own); + const files = readdirSync(root).sort(); + if (files.join() !== PACKAGE_FILES.join()) { + throw new Error(`the package holds ${files.join(", ")}, not ${PACKAGE_FILES.join(", ")}`); + } + const shipped = JSON.parse(readFileSync(own, "utf8")); + // Checked here, as Node since 20.19 and 22.7 loads the glue as an ES module + // without it too, by its syntax; bundlers and older Node do not. + if (shipped.type !== "module") { + throw new Error(`the package's "type" is ${shipped.type}, not "module"`); + } + // Every path that package.json gives, "exports" included, under any + // condition, is one of the files. + const leaves = (value) => + typeof value === "string" ? [value] : Object.values(value ?? {}).flatMap(leaves); + for (const path of [shipped.main, shipped.module, shipped.types, ...leaves(shipped.exports)]) { + if (typeof path !== "string" || !existsSync(join(root, path))) { + throw new Error(`the package's package.json points to ${path}, which it does not hold`); + } + } + // TypeScript takes the first condition that applies, so "types" comes + // first, and it is the declarations that are checked below. + const main = shipped.exports?.["."] ?? {}; + if (Object.keys(main)[0] !== "types" || main.types !== shipped.types) { + throw new Error(`the package's exports["."] does not start with "types": ${JSON.stringify(shipped.types)}`); + } + const text = readFileSync(join(root, shipped.types), "utf8"); + for (const declaration of [ + "export class Player ", + "export class Demo ", + "export class Bench ", + "export function packet_ends(", + "export function initSync(", + "export default function ", + ]) { + if (!text.includes(declaration)) { + throw new Error(`${shipped.types} lacks "${declaration.trim()}"`); + } + } + // Imported by its name, from a module in the project, so that Node's ES + // module resolution finds it as it would a page's import. + const importer = join(project, "check-import.mjs"); + writeFileSync(importer, `export * from ${JSON.stringify(name)};\n` + + `export { default } from ${JSON.stringify(name)};\n`); + const module = await import(pathToFileURL(importer).href); + module.initSync({ module: readFileSync(wasm) }); + console.log(`the npm package ${name} ${shipped.version} installs with its ${files.length} files and declarations`); + return module; +} -const pkg = new URL("../web/pkg/", import.meta.url); -// The glue is an ES module in a .js file, which Node takes for CommonJS -// without a package.json saying otherwise: imported from its text instead. -const glue = readFileSync(new URL("emberwave_web.js", pkg)); -const module = await import(`data:text/javascript;base64,${glue.toString("base64")}`); -module.initSync({ module: readFileSync(new URL("emberwave_web_bg.wasm", pkg)) }); +const project = process.argv[2]; +const module = project ? await packageModule(project) : await pagesModule(); const { Demo, Player, Bench, packet_ends } = module; for (const [name, value] of [ + ["init", module.default], + ["initSync", module.initSync], ["Player.create", Player?.create], ["Player.max_file_bytes", Player?.max_file_bytes], ["Player.prototype.set_partial_share", Player?.prototype.set_partial_share],