diff --git a/.coderabbit.yaml b/.coderabbit.yaml index 2408084cf..fa5c645f7 100644 --- a/.coderabbit.yaml +++ b/.coderabbit.yaml @@ -1,6 +1,6 @@ -# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json -reviews: - auto_review: - # Dependabot bumps are checked by CI; skip CodeRabbit reviews on them. - ignore_usernames: - - "dependabot[bot]" +# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json +reviews: + auto_review: + # Dependabot bumps are checked by CI; skip CodeRabbit reviews on them. + ignore_usernames: + - "dependabot[bot]" diff --git a/.config/nextest.toml b/.config/nextest.toml index 2a4cd2cb9..38f939c31 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -1,3 +1,14 @@ # Minimum cargo-nextest for this repository: GHSA-vc25-qg58-w57c is fixed in 0.9.150 and CI # installs exactly that version, so an older nextest refuses to run (exit 92 REQUIRED_VERSION_NOT_MET). nextest-version = "0.9.150" + +[test-groups] +gpu = { max-threads = 1 } + +# Coverage runs each test in a separate process, so the GPU suite's in-process lock +# cannot protect software adapters from competing devices and readback timeouts. +# UI harnesses can create a device lazily when rendering a screenshot, so include +# the whole UI package instead of an incomplete list of GPU-named tests. +[[profile.default.overrides]] +filter = 'package(effectcraft-gpu) | package(effectcraft-ui-egui) | package(effectcraft-sam2) | (package(effectcraft-cli) & test(/^cli::gpu_adapter_name_/))' +test-group = 'gpu' diff --git a/.gitignore b/.gitignore index ff6ad2397..7ce8c8c55 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,11 @@ -*~ -plan/ -target/ -/dist -/log -.DS_Store -.claude/worktrees/ -__pycache__/ - -# After Effects test corpus fetched by `cargo xtask aep-corpus` -/corpus/ +*~ +plan/ +target/ +/dist +/log +.DS_Store +.claude/worktrees/ +__pycache__/ + +# After Effects test corpus fetched by `cargo xtask aep-corpus` +/corpus/ diff --git a/.mcp.json b/.mcp.json index caff41c9b..96e62feac 100644 --- a/.mcp.json +++ b/.mcp.json @@ -1,12 +1,12 @@ -{ - "mcpServers": { - "effectcraft": { - "command": "cargo", - "args": ["run", "--quiet", "--release", "-p", "effectcraft-cli", "--", "mcp", "--demo"] - }, - "effectcraft-app": { - "command": "cargo", - "args": ["run", "--quiet", "--release", "-p", "effectcraft-cli", "--", "mcp", "--bridge", "9877"] - } - } -} +{ + "mcpServers": { + "effectcraft": { + "command": "cargo", + "args": ["run", "--quiet", "--release", "-p", "effectcraft-cli", "--", "mcp", "--demo"] + }, + "effectcraft-app": { + "command": "cargo", + "args": ["run", "--quiet", "--release", "-p", "effectcraft-cli", "--", "mcp", "--bridge", "9877"] + } + } +} diff --git a/AGENTS.md b/AGENTS.md index ba48c1a97..b666f5c87 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,210 +1,210 @@ - -## House rules - -These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy. - -1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments. -2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish. -3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location. -4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix. -5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true. -6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why. -7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready. -8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception. -9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop. -10. **Keep secrets and personal details out** of the repository, logs and requests. -11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there. -12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it. -13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it. -14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit. -15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that. - - -## Rust Craft repositories - -These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib). - -1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix. -2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it. -3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository. -4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build. -5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md). -6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`. - -## Licence allowlist - -Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules. - -- `ISC` -- `MIT` -- `BSD-2-Clause` -- `BSD-3-Clause` -- `Apache-2.0` -- `OFL-1.1` -- `Ubuntu-font-1.0` -- `Bitstream-Vera` -- `CC0-1.0` -- `CC-BY-4.0` -- `CC-BY-SA-4.0` -- `LicenseRef-Public-Domain` - -`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so. - - -# EffectCraft — rules for agents and contributors - -These rules apply to every human and AI contributor. `CLAUDE.md` holds the working instructions; this -file holds the rules that must never be broken. When the two disagree, this file wins. - -## Never crash - -People trust EffectCraft with hours of work. A malformed project, PSD, SVG, Lottie or media file, a bad -expression or script, a broken plug-in, a bad control-channel or MCP argument, a corrupt preferences file -or a full disk must produce an error the user (or agent) can act on, never a crash and never lost work. -**This rule outranks feature work:** don't ship a feature by adding a panic path, and fix a crash before -building on top of it. - -- **Fail with `Result`** through the crate's error type and propagate with `?`; add context - (`map_err`, an error variant) rather than discarding it. Lenient readers fall back and record the repair. -- **No panicking shortcuts in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, - `todo!` or `unimplemented!`. Use `?`, `ok_or(..)?`, `let … else`, `if let`, or `unwrap_or*` where a - fallback is genuinely correct (never where it would silently corrupt a document). Unfinished features - return an "unsupported" error. The only exception is a provably infallible literal, written as - `#[allow(clippy::expect_used)]` + `.expect("why this cannot fail")`. -- **No `unsafe`** (`unsafe_code = "forbid"` for the workspace). -- **Every input-derived number is hostile.** Use `get()` instead of `[i]`/`[a..b]` when the position - comes from a file, a user, an agent or arithmetic on those; slice strings only at char boundaries; use - checked or saturating arithmetic for lengths, offsets and counts; guard division by zero and NaN/inf - casts; cap allocations sized by input. -- **Bound recursion:** projects, precomps, expressions and SVG/PSD trees can be cyclic or deeply nested; - walk them with seen-sets or depth limits. -- **Don't cascade:** handle lock poisoning (`lock().unwrap_or_else(PoisonError::into_inner)` or an - error), and treat worker-thread join results as `Result`s. -- **Last-resort guard:** the app wraps command execution and file import/export in a panic hook / - `catch_unwind` boundary that turns an escaped panic into an error and keeps the document. It is a - safety net, not a substitute for the rules above; keep `panic = "unwind"`. -- **Prove it:** every crash fix comes with a small synthetic regression test that panicked before the fix. - -Tests, benches, fuzz targets and `xtask` may `unwrap()`; `clippy.toml` allows it in tests. Crates that are -clean carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, -clippy::todo, clippy::unreachable)]`; new crates start with it. - -## 1. Assets: no Adobe artwork, every asset licensed and attributed - -This rule is absolute. Breaking it is the most serious mistake a contributor can make on this project. - -**What counts as an asset:** any image, icon, cursor, logo, illustration, screenshot, font, colour LUT, -preset, template, sound, music, video, 3D model, or other non-code media. This covers files in the -repository, bytes embedded in code (`include_bytes!`, base64, data URIs), and data hard-coded to -reproduce an image (for example, point lists traced from someone else's icon). - -1. **Never use Adobe iconography, images or other Adobe assets**, in any form: - - no icons, cursors, logos, splash screens, UI artwork or screenshots from any Adobe product; - - no Adobe fonts, LUTs, presets, templates, sound effects, stock media or sample projects; - - no traced, redrawn, recoloured or "inspired-by" copies of Adobe icons. Our icons may follow generic - conventions (a play triangle, a razor blade, a stopwatch), but each must be drawn from scratch - without reference to Adobe's artwork. -2. **Every asset must be open**: open-source licensed (MIT, Apache-2.0, BSD, ISC, zlib, SIL OFL…), - public domain / CC0, or Creative Commons (CC BY or CC BY-SA; no NC/ND licences), **or** created by a - contributor who owns it and licenses it to the project under the project licence (MIT OR Apache-2.0). - If the licence is unknown or unclear, the asset does not go in. -3. **Every asset needs an attribution sidecar.** Next to each asset file `X`, add `X.attribution` with: - ```text - asset: - title: - author: - source: - license: - license-file: - added: by - notes: - ``` - Also add one line for the asset to [`ATTRIBUTION.md`](ATTRIBUTION.md). `cargo xtask assets` (part of - `cargo xtask ci`) fails if any asset lacks a sidecar or index entry. -4. **Screenshots** in the repo may show only EffectCraft (or other open projects), with media we generated - or media that is itself openly licensed. Never commit screenshots of Adobe products. -5. **Local reference material stays local.** After Effects reference screenshots and notes live only in - `plan/aftereffects/` (gitignored). They must never be committed, bundled, embedded, traced or shipped. -6. **Code-drawn assets** (icons in `crates/ui-egui/src/icons.rs`, procedural demo content in - `crates/engine/src/demo.rs`, generators in `crates/effects`) are original work under the project licence - and are listed in `ATTRIBUTION.md`. -7. **When in doubt, leave it out** and draw or generate it yourself. -8. **The one exception: first-party ArtCraft brand marks.** The ArtCraft name and logos in `docs/brand/` - are trademarks of the ArtCraft Team, not open source, usable only unmodified and only in the context of - EffectCraft under `docs/brand/LICENSE-brand.txt` (forks and modified versions must remove them). They still - need a sidecar and an `ATTRIBUTION.md` row (licence `LicenseRef-ArtCraft-Trademark`). No other - non-open asset is allowed, and this exception never covers third-party marks (Adobe, Discord, GitHub - and other logos stay out; draw a generic icon instead). - -## 2. Clean-room code - -- Never read, disassemble or copy anything inside Adobe application bundles; file names and listings only. - Observe behaviour by using the app; never capture its Home screen, recent projects, account info or - file browsers. -- Never copy GPL/LGPL/AGPL code (FFmpeg, Natron, Blender, Glaxnimate, Synfig, Friction, Olive, MLT, frei0r, G'MIC…). -- Never read or copy Adobe expression/scripting implementations, `.ffx` presets or effect plug-ins; the public Expression Language Reference and Scripting Guide describe *behaviour* only. -- Implement codecs and formats from public specifications (ITU-T/ISO/IEC standards, IETF RFCs, the VP9 - and AV1 bitstream specs, SMPTE documents, published container specs). Do not read the source of - reference or third-party decoders/encoders while implementing a format, even permissively licensed - ones (libvpx, libopus, libaom, dav1d, openh264…); spec text and conformance vectors only. Record the - spec edition used in the crate README. -- ffmpeg/ffprobe may be used only as external test oracles and fixture generators. They are never - linked, bundled or shipped. -- Dependencies must use permissive licences: MIT/Apache-2.0/BSD/ISC/Zlib/Unicode/CC0/BSL-1.0, or - MPL-2.0 used unmodified. - -## 3. Engineering rules - -- **Layering** (`cargo xtask layers`): nothing below L5 depends on egui/eframe/winit/rfd/cpal; L0–L4 build for wasm32. -- **Exact time:** `effectcraft_time::Tick` (254 016 000 000/s). Keyframe times are layer time. -- **Property tree:** everything animatable is a `Property` in the layer's `PropGroup` tree, addressed by paths (`transform/position`, `effects/#1/blurriness`, `@uid`). -- **Everything is a command** (`crates/engine`): id, label, menu path, shortcut, params, enabled(), run(). UI, CLI, control channel and MCP dispatch by id. -- **Everything is agent-drivable:** every interactive widget registers an automation id; UI state is serde. -- **Community links** (Help menu, About, header Discord button): https://discord.gg/artcraft, https://getartcraft.com, https://getartcraft.com/apps/effectcraft, https://github.com/storytold/effectcraft. -- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, wasm). -- New workspace crates include `[lints] workspace = true` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them. -- **Commits:** one task id per commit (`M6.3: trim paths`). Only green states. -- `cargo run -p effectcraft -- --control 9877` opens the desktop app with the JSON-lines control server (`docs/control-protocol.md`). For UI work, look at the result, including the headless `snapshot` example. -- `plan/` is an optional gitignored notebook (`plan/aftereffects/` may hold reference notes and captures). Do not ask for it, do not stop when it is absent, and never commit those captures. -- Read [`docs/gaps.md`](docs/gaps.md) and [`docs/target-app-parity.md`](docs/target-app-parity.md) before choosing work. Fidelity, reliability and stability (G1–G3) come before new features. -- Some workflow files still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task. - - -Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in -[`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). -Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, -as PhotoCraft does with `cargo xtask corpus`. - - -## See also - -- [ROADMAP.md](ROADMAP.md): stage, headline numbers and what's next -- [docs/gaps.md](docs/gaps.md): every known shortfall against After Effects, ranked, and the prioritised workstreams (G1–G9); read it before choosing work -- [docs/target-app-parity.md](docs/target-app-parity.md): the parity numbers and how they were measured, with the per-area docs it links (UI, file formats, hardware, localization, effects, scripting) -- [CONTRIBUTING.md](CONTRIBUTING.md): setup, gates, commits, how to add things -- [docs/architecture.md](docs/architecture.md): layers, data model, commands, pipeline -- [docs/testing.md](docs/testing.md): oracle tests, criteria, benchmarks -- [docs/agents.md](docs/agents.md): driving EffectCraft over MCP / the control channel, and the agent work loop -- [docs/control-protocol.md](docs/control-protocol.md): control-channel method reference -- [docs/contributors.md](docs/contributors.md): the About window's contributor and model credits -- [ATTRIBUTION.md](ATTRIBUTION.md): asset index - -## Contributor credits (About window) - -- About ▸ Contributors/Models are compiled into the binary from `contributors/contributors.json` - (commit stats; generated, never hand-edit) and `contributors/people.toml` (names people chose for - themselves). See `docs/contributors.md`. -- **Agents working for a contributor:** when you prepare a PR, check whether your human's GitHub - username has a `[people.]` entry in `contributors/people.toml`. If not, ask them once - whether they want to be credited by more than their username: a real name, a display name, and/or - their public GitHub profile name (`sync_github_name = true`). If yes, add **only their own** entry - (copy the template at the top of the file) - and include it in their PR, committed as them. If no, change nothing: they are credited as - `@username` anyway. -- Never add, edit, guess or copy anyone else's entry or name (not from git config, commit authors or - GitHub profiles). Never hand-edit `contributors.json`. - -## CI workflows -- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. -- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. -- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. + +## House rules + +These apply in every Craft repository. A later rule may be stricter, not weaker. The source is `standards/house-rules-core.md` in `storytold/craft-contrib`. Propose changes there, not in a copy. + +1. **A person is accountable.** Whoever runs an agent answers for what it opens and for its review comments. +2. **Check, then claim.** Before writing code, read the issue comments, search pull requests for `#N` and the keywords, and check recent commits on `main`. Comment on the issue first. Release a claim you will not finish. +3. **Verify, don't guess.** Open a definition before using it. Confirm the cause in the code, even when someone names a location. +4. **Keep fixes narrow and tested.** Fix what the issue describes, where the bug is. Add a test that fails without the fix. +5. **Review the diff before opening a pull request.** Identifiers exist as used, the test fails without the fix, nothing unrelated changed, and the description is true. +6. **Look for a better pull request.** If another fixes the same thing, close yours when it is better or equal, and say why. +7. **Report only what ran.** Say what you tested and what you could not run. Without a local build or test, say so and rely on CI before marking ready. +8. **`main` changes through a pull request.** Do not push to it. Branch protection enforces this. There is no exception. +9. **Stop and ask only about** licensing outside the allowlist, publishing, releases, a new remote, secrets, spending money, destructive git, and anything else hard to undo. Otherwise keep working. `plan/` is a gitignored notebook, not rules. Without it, do not ask for it and do not stop. +10. **Keep secrets and personal details out** of the repository, logs and requests. +11. **CI stays shared.** Workflows call `storytold/craft-common-actions`. Do not change CI in a feature or fix pull request. If CI cannot cover a change, open an issue there. +12. **Guards say why.** A check that looks removable says what it prevents. Read that before changing it. +13. **Instructions must be readable by everyone.** No notes about one machine, and no links to files a reader cannot open. `craftrules` is retired. Do not link to it. +14. **Keep pull requests moving.** Concurrent pull requests are fine; unanswered actionable feedback is not. Respond in 7 days, a reminder at 14, closure eligible at 30, from when an actionable request waits on the author. Suggestions and unconfirmed bot findings do not start the clock. A fix, explanation or agreed plan resets it; unrelated activity does not. Waiting on a reviewer or maintainer pauses it and does not count against the author. A maintainer decides closure; it is never automatic. Reuse search results, do not poll, and stop at a rate limit. +15. **No agent attribution.** A pull request does not say an agent wrote it. A repository rule may not require that. + + +## Rust Craft repositories + +These apply to native Craft apps and to shared Rust libraries. Select them by repository type. A repository that merely contains some Rust does not take this block. Rules later in a repository's file may be stricter, but not weaker. The source is `standards/house-rules-rust.md` in [storytold/craft-contrib](https://github.com/storytold/craft-contrib). + +1. **Never crash.** Non-test code does not panic and has no `unsafe`, except where the repository file names an exception. Return errors, treat input as hostile, and bound recursion and allocations. New production crate roots copy the `deny` attribute from an existing crate: `clippy::unwrap_used`, `clippy::expect_used`, `clippy::panic`, `clippy::unimplemented`, `clippy::todo`, `clippy::unreachable`. Every crash fix comes with a test that panicked before the fix. +2. **Clean room.** Learn from observed behaviour and public specifications. Do not copy another product's code, assets, strings or artwork. Check a dependency's licence before adding it. +3. **Assets and fonts.** Every asset is original or suitably licensed, and is recorded in `ATTRIBUTION.md` in the same change. Font files live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts), not in the app repository. +4. **Rust only for native Craft apps.** No handwritten JavaScript or TypeScript, and no Tauri, Electron or webview shell, in those apps. Shared tooling follows its documented technical scope and maintainer-approved exceptions. Craft PR Review's existing Tauri and TypeScript UI is one such exception. It does not relax this rule for native apps. Preserve any existing web build. +5. **Time goes through `chrono`.** Do not hand-roll calendar conversion. For dates beyond what `chrono` can represent, follow [standards/time.md](https://github.com/storytold/craft-contrib/blob/main/standards/time.md). +6. **Contributor credits.** Add or edit only your own person's entry in `contributors/people.toml`, and only after asking them. Never guess a name or hand-edit `contributors.json`. + +## Licence allowlist + +Dependencies and assets use SPDX identifiers. An expression is allowed when every identifier is in this list. A repository may name a shorter list. It may not add an identifier here by editing its own copy of these rules. + +- `ISC` +- `MIT` +- `BSD-2-Clause` +- `BSD-3-Clause` +- `Apache-2.0` +- `OFL-1.1` +- `Ubuntu-font-1.0` +- `Bitstream-Vera` +- `CC0-1.0` +- `CC-BY-4.0` +- `CC-BY-SA-4.0` +- `LicenseRef-Public-Domain` + +`LicenseRef-Storyteller-Trademark` is not in this list. It covers Storyteller brand marks only, where a repository already says so. + + +# EffectCraft — rules for agents and contributors + +These rules apply to every human and AI contributor. `CLAUDE.md` holds the working instructions; this +file holds the rules that must never be broken. When the two disagree, this file wins. + +## Never crash + +People trust EffectCraft with hours of work. A malformed project, PSD, SVG, Lottie or media file, a bad +expression or script, a broken plug-in, a bad control-channel or MCP argument, a corrupt preferences file +or a full disk must produce an error the user (or agent) can act on, never a crash and never lost work. +**This rule outranks feature work:** don't ship a feature by adding a panic path, and fix a crash before +building on top of it. + +- **Fail with `Result`** through the crate's error type and propagate with `?`; add context + (`map_err`, an error variant) rather than discarding it. Lenient readers fall back and record the repair. +- **No panicking shortcuts in non-test code:** no `unwrap()`, `expect()`, `panic!`, `unreachable!`, + `todo!` or `unimplemented!`. Use `?`, `ok_or(..)?`, `let … else`, `if let`, or `unwrap_or*` where a + fallback is genuinely correct (never where it would silently corrupt a document). Unfinished features + return an "unsupported" error. The only exception is a provably infallible literal, written as + `#[allow(clippy::expect_used)]` + `.expect("why this cannot fail")`. +- **No `unsafe`** (`unsafe_code = "forbid"` for the workspace). +- **Every input-derived number is hostile.** Use `get()` instead of `[i]`/`[a..b]` when the position + comes from a file, a user, an agent or arithmetic on those; slice strings only at char boundaries; use + checked or saturating arithmetic for lengths, offsets and counts; guard division by zero and NaN/inf + casts; cap allocations sized by input. +- **Bound recursion:** projects, precomps, expressions and SVG/PSD trees can be cyclic or deeply nested; + walk them with seen-sets or depth limits. +- **Don't cascade:** handle lock poisoning (`lock().unwrap_or_else(PoisonError::into_inner)` or an + error), and treat worker-thread join results as `Result`s. +- **Last-resort guard:** the app wraps command execution and file import/export in a panic hook / + `catch_unwind` boundary that turns an escaped panic into an error and keeps the document. It is a + safety net, not a substitute for the rules above; keep `panic = "unwind"`. +- **Prove it:** every crash fix comes with a small synthetic regression test that panicked before the fix. + +Tests, benches, fuzz targets and `xtask` may `unwrap()`; `clippy.toml` allows it in tests. Crates that are +clean carry `#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, +clippy::todo, clippy::unreachable)]`; new crates start with it. + +## 1. Assets: no Adobe artwork, every asset licensed and attributed + +This rule is absolute. Breaking it is the most serious mistake a contributor can make on this project. + +**What counts as an asset:** any image, icon, cursor, logo, illustration, screenshot, font, colour LUT, +preset, template, sound, music, video, 3D model, or other non-code media. This covers files in the +repository, bytes embedded in code (`include_bytes!`, base64, data URIs), and data hard-coded to +reproduce an image (for example, point lists traced from someone else's icon). + +1. **Never use Adobe iconography, images or other Adobe assets**, in any form: + - no icons, cursors, logos, splash screens, UI artwork or screenshots from any Adobe product; + - no Adobe fonts, LUTs, presets, templates, sound effects, stock media or sample projects; + - no traced, redrawn, recoloured or "inspired-by" copies of Adobe icons. Our icons may follow generic + conventions (a play triangle, a razor blade, a stopwatch), but each must be drawn from scratch + without reference to Adobe's artwork. +2. **Every asset must be open**: open-source licensed (MIT, Apache-2.0, BSD, ISC, zlib, SIL OFL…), + public domain / CC0, or Creative Commons (CC BY or CC BY-SA; no NC/ND licences), **or** created by a + contributor who owns it and licenses it to the project under the project licence (MIT OR Apache-2.0). + If the licence is unknown or unclear, the asset does not go in. +3. **Every asset needs an attribution sidecar.** Next to each asset file `X`, add `X.attribution` with: + ```text + asset: + title: + author: + source: + license: + license-file: + added: by + notes: + ``` + Also add one line for the asset to [`ATTRIBUTION.md`](ATTRIBUTION.md). `cargo xtask assets` (part of + `cargo xtask ci`) fails if any asset lacks a sidecar or index entry. +4. **Screenshots** in the repo may show only EffectCraft (or other open projects), with media we generated + or media that is itself openly licensed. Never commit screenshots of Adobe products. +5. **Local reference material stays local.** After Effects reference screenshots and notes live only in + `plan/aftereffects/` (gitignored). They must never be committed, bundled, embedded, traced or shipped. +6. **Code-drawn assets** (icons in `crates/ui-egui/src/icons.rs`, procedural demo content in + `crates/engine/src/demo.rs`, generators in `crates/effects`) are original work under the project licence + and are listed in `ATTRIBUTION.md`. +7. **When in doubt, leave it out** and draw or generate it yourself. +8. **The one exception: first-party ArtCraft brand marks.** The ArtCraft name and logos in `docs/brand/` + are trademarks of the ArtCraft Team, not open source, usable only unmodified and only in the context of + EffectCraft under `docs/brand/LICENSE-brand.txt` (forks and modified versions must remove them). They still + need a sidecar and an `ATTRIBUTION.md` row (licence `LicenseRef-ArtCraft-Trademark`). No other + non-open asset is allowed, and this exception never covers third-party marks (Adobe, Discord, GitHub + and other logos stay out; draw a generic icon instead). + +## 2. Clean-room code + +- Never read, disassemble or copy anything inside Adobe application bundles; file names and listings only. + Observe behaviour by using the app; never capture its Home screen, recent projects, account info or + file browsers. +- Never copy GPL/LGPL/AGPL code (FFmpeg, Natron, Blender, Glaxnimate, Synfig, Friction, Olive, MLT, frei0r, G'MIC…). +- Never read or copy Adobe expression/scripting implementations, `.ffx` presets or effect plug-ins; the public Expression Language Reference and Scripting Guide describe *behaviour* only. +- Implement codecs and formats from public specifications (ITU-T/ISO/IEC standards, IETF RFCs, the VP9 + and AV1 bitstream specs, SMPTE documents, published container specs). Do not read the source of + reference or third-party decoders/encoders while implementing a format, even permissively licensed + ones (libvpx, libopus, libaom, dav1d, openh264…); spec text and conformance vectors only. Record the + spec edition used in the crate README. +- ffmpeg/ffprobe may be used only as external test oracles and fixture generators. They are never + linked, bundled or shipped. +- Dependencies must use permissive licences: MIT/Apache-2.0/BSD/ISC/Zlib/Unicode/CC0/BSL-1.0, or + MPL-2.0 used unmodified. + +## 3. Engineering rules + +- **Layering** (`cargo xtask layers`): nothing below L5 depends on egui/eframe/winit/rfd/cpal; L0–L4 build for wasm32. +- **Exact time:** `effectcraft_time::Tick` (254 016 000 000/s). Keyframe times are layer time. +- **Property tree:** everything animatable is a `Property` in the layer's `PropGroup` tree, addressed by paths (`transform/position`, `effects/#1/blurriness`, `@uid`). +- **Everything is a command** (`crates/engine`): id, label, menu path, shortcut, params, enabled(), run(). UI, CLI, control channel and MCP dispatch by id. +- **Everything is agent-drivable:** every interactive widget registers an automation id; UI state is serde. +- **Community links** (Help menu, About, header Discord button): https://discord.gg/artcraft, https://getartcraft.com, https://getartcraft.com/apps/effectcraft, https://github.com/storytold/effectcraft. +- **Quality gates** before every commit: `cargo xtask ci` (fmt, clippy -D warnings, tests, layers, assets, wasm). +- New workspace crates include `[lints] workspace = true` in `Cargo.toml`. Production crate roots declare the crate-level lint attributes before modules; crate-level `//!` documentation may precede them. +- **Commits:** one task id per commit (`M6.3: trim paths`). Only green states. +- `cargo run -p effectcraft -- --control 9877` opens the desktop app with the JSON-lines control server (`docs/control-protocol.md`). For UI work, look at the result, including the headless `snapshot` example. +- `plan/` is an optional gitignored notebook (`plan/aftereffects/` may hold reference notes and captures). Do not ask for it, do not stop when it is absent, and never commit those captures. +- Read [`docs/gaps.md`](docs/gaps.md) and [`docs/target-app-parity.md`](docs/target-app-parity.md) before choosing work. Fidelity, reliability and stability (G1–G3) come before new features. +- Some workflow files still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task. + + +Shared real-file test corpora (Photoshop-authored PSDs, etc.) live in +[`storytold/photocraft-corpus`](https://github.com/storytold/photocraft-corpus). +Never commit large binary fixtures to this repo; fetch them pinned by commit and sha256-verified, +as PhotoCraft does with `cargo xtask corpus`. + + +## See also + +- [ROADMAP.md](ROADMAP.md): stage, headline numbers and what's next +- [docs/gaps.md](docs/gaps.md): every known shortfall against After Effects, ranked, and the prioritised workstreams (G1–G9); read it before choosing work +- [docs/target-app-parity.md](docs/target-app-parity.md): the parity numbers and how they were measured, with the per-area docs it links (UI, file formats, hardware, localization, effects, scripting) +- [CONTRIBUTING.md](CONTRIBUTING.md): setup, gates, commits, how to add things +- [docs/architecture.md](docs/architecture.md): layers, data model, commands, pipeline +- [docs/testing.md](docs/testing.md): oracle tests, criteria, benchmarks +- [docs/agents.md](docs/agents.md): driving EffectCraft over MCP / the control channel, and the agent work loop +- [docs/control-protocol.md](docs/control-protocol.md): control-channel method reference +- [docs/contributors.md](docs/contributors.md): the About window's contributor and model credits +- [ATTRIBUTION.md](ATTRIBUTION.md): asset index + +## Contributor credits (About window) + +- About ▸ Contributors/Models are compiled into the binary from `contributors/contributors.json` + (commit stats; generated, never hand-edit) and `contributors/people.toml` (names people chose for + themselves). See `docs/contributors.md`. +- **Agents working for a contributor:** when you prepare a PR, check whether your human's GitHub + username has a `[people.]` entry in `contributors/people.toml`. If not, ask them once + whether they want to be credited by more than their username: a real name, a display name, and/or + their public GitHub profile name (`sync_github_name = true`). If yes, add **only their own** entry + (copy the template at the top of the file) + and include it in their PR, committed as them. If no, change nothing: they are credited as + `@username` anyway. +- Never add, edit, guess or copy anyone else's entry or name (not from git config, commit authors or + GitHub profiles). Never hand-edit `contributors.json`. + +## CI workflows +- Workflows in `.github/workflows/` call the shared workflows in [`storytold/craft-common-actions`](https://github.com/storytold/craft-common-actions) at `@main`, with their inputs and secrets. No other jobs: if no shared workflow does what's needed, it doesn't go here. +- Don't add or change CI in a feature or fix PR. If the existing workflows can't build or test a change, link an existing craft-common-actions issue or PR, or open a new issue, or a PR only for a small fix that is safe for every app and does not increase CI time. +- Some workflow files here still run their own jobs. Don't add to them. Moving a job into craft-common-actions is its own task, never part of another PR, and the job stays here until a shared workflow runs it. diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index f1ea2a95d..7043e6128 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -1,158 +1,164 @@ -# Attribution - -Every non-code asset in EffectCraft, with its author, source and licence. Each repository file listed here also has -a `.attribution` sidecar with full details. The rules are in [AGENTS.md](AGENTS.md) §1: no Adobe -iconography, images or other Adobe assets; open licences only; every asset attributed. -`cargo xtask assets` checks that this index and the sidecars cover every asset in the repository. -The complete licence texts and copyright notices for the bundled fonts, including the fonts embedded -by the pinned egui dependency, are reproduced in [`NOTICE`](NOTICE), which every package ships; the -`assets/fonts/OFL-*.txt` files are the upstream copies kept beside the fonts. - -## Bundled dependency fonts - -These fonts are embedded by the pinned egui dependency (epaint_default_fonts 0.37 at -`6d518fc799681571963842f95b55a6b68431b15a`); no font file is added to this repository. -egui-icons is always embedded, `default_fonts` adds Ubuntu Light and Hack, and -`monochrome_emoji_fonts` adds Noto Emoji and emoji-icon-font. The complete copyright notices -and licence texts are in [`NOTICE`](NOTICE). - -| Asset | Author | Source | Licence | -|---|---|---|---| -| `epaint_default_fonts/fonts/egui-icons.ttf` | John Slegers (emoji-icon-font) | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/egui-icons.txt; original https://github.com/jslegers/emoji-icon-font | MIT (complete copyright and permission text in `NOTICE`) | -| `epaint_default_fonts/fonts/emoji-icon-font.ttf` | John Slegers | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/emoji-icon-font-mit-license.txt; original https://github.com/jslegers/emoji-icon-font | MIT (complete copyright and permission text in `NOTICE`) | -| `epaint_default_fonts/fonts/NotoEmoji-Regular.ttf` | Google Inc. (The Noto Project Authors) | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/OFL.txt | OFL-1.1 (complete text in `NOTICE`) | -| `epaint_default_fonts/fonts/Ubuntu-Light.ttf` | Canonical Ltd. and Dalton Maag | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/UFL.txt | Ubuntu Font Licence 1.0 (complete text in `NOTICE`) | -| `epaint_default_fonts/fonts/Hack-Regular.ttf` | Source Foundry Authors; Bitstream Inc. | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/Hack-Regular.txt; original https://github.com/source-foundry/Hack | MIT AND Bitstream-Vera (complete texts in `NOTICE`) | - -## Asset files - -| Asset | Author | Source | Licence | -|---|---|---|---| -| `assets/fonts/Inter-Regular.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | -| `assets/fonts/Inter-Medium.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | -| `assets/fonts/Inter-SemiBold.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | -| `assets/fonts/Inter-Bold.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | -| `assets/fonts/Inter-Italic.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | -| `assets/fonts/NotoSerif-Regular.ttf` | The Noto Project Authors | https://github.com/notofonts/latin-greek-cyrillic | OFL-1.1 (`assets/fonts/OFL-NotoSerif.txt`) | -| `assets/fonts/NotoSansSymbols2-Regular.ttf` | The Noto Project Authors | https://github.com/notofonts/symbols | OFL-1.1 (`assets/fonts/OFL-NotoSansSymbols2.txt`) | -| `assets/fonts/JetBrainsMono-Regular.ttf` | The JetBrains Mono Project Authors | https://github.com/JetBrains/JetBrainsMono | OFL-1.1 (`assets/fonts/OFL-JetBrainsMono.txt`) | -| `apps/effectcraft-web/web/favicon.svg` | EffectCraft contributors | Original work: web app icon, a copy of `assets/app-icon/effectcraft-small.svg` (the unicorn app icon) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | -| `packaging/macos/dmg/background.svg` | @XusBadia | Original work: macOS DMG Finder window background, derived from the EffectCraft app icon (`assets/app-icon/effectcraft.svg`); rendered to a TIFF by `packaging/macos/package.sh` at package time | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | -| `assets/app-icon/effectcraft-1024.png` | EffectCraft contributors | Original work: effectCraft app icon, 1024 px (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | -| `assets/app-icon/effectcraft-macos-512.png` | EffectCraft contributors | Original work: effectCraft runtime Dock icon (macOS) (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | -| `assets/app-icon/effectcraft-small.svg` | EffectCraft contributors | Original work: effectCraft app icon, light vector (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | -| `assets/app-icon/effectcraft.icns` | EffectCraft contributors | Original work: effectCraft macOS app icon (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | -| `assets/app-icon/effectcraft.ico` | EffectCraft contributors | Original work: effectCraft Windows app icon (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | -| `assets/app-icon/effectcraft.svg` | EffectCraft contributors | Original work: effectCraft app icon, master vector (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | -| `assets/app-icon/hicolor/128x128/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 128x128 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | -| `assets/app-icon/hicolor/16x16/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 16x16 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | -| `assets/app-icon/hicolor/24x24/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 24x24 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | -| `assets/app-icon/hicolor/256x256/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 256x256 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | -| `assets/app-icon/hicolor/32x32/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 32x32 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | -| `assets/app-icon/hicolor/48x48/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 48x48 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | -| `assets/app-icon/hicolor/512x512/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 512x512 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | -| `assets/app-icon/hicolor/64x64/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 64x64 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | -| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.effectcraft.svg` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor scalable (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | -| `crates/lottie/tests/fixtures/bouncing-ball.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (bouncing ball, eased position keys) | MIT OR Apache-2.0 | -| `crates/lottie/tests/fixtures/shapes-gradient.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (star, rectangle, gradient fill, dashed stroke, trim paths) | MIT OR Apache-2.0 | -| `crates/lottie/tests/fixtures/precomp-matte-text.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (precomp, track matte, parented text) | MIT OR Apache-2.0 | -| `crates/lottie/tests/fixtures/legacy-masks.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (legacy keyframes, masks) | MIT OR Apache-2.0 | -| `crates/svg/tests/fixtures/basic-shapes.svg` | EffectCraft contributors | Original work: hand-written SVG test fixture (basic shapes, groups, transforms) | MIT OR Apache-2.0 | -| `crates/svg/tests/fixtures/paths-gradients.svg` | EffectCraft contributors | Original work: hand-written SVG test fixture (path data, gradients, CSS, use) | MIT OR Apache-2.0 | -| `crates/model/tests/fixtures/quad.gltf` | EffectCraft contributors | Original work: glTF 2.0 test fixture (textured quad, node hierarchy, translation animation; data URIs) | MIT OR Apache-2.0 | -| `crates/model/tests/fixtures/quad.glb` | EffectCraft contributors | Original work: binary glTF test fixture (the same quad with its texture in the BIN chunk) | MIT OR Apache-2.0 | -| `crates/model/tests/fixtures/cube.obj` | EffectCraft contributors | Original work: Wavefront OBJ test fixture (unit cube, two materials) | MIT OR Apache-2.0 | -| `crates/model/tests/fixtures/cube.mtl` | EffectCraft contributors | Original work: MTL test fixture (materials of cube.obj) | MIT OR Apache-2.0 | - -Two small After Effects test projects of `crates/aep` are in this repository: `crates/aep/tests/fixtures/synthetic.aep` (original work, made with After Effects 2026 from own data, working space None, the embedded colour profile removed; MIT OR Apache-2.0, with its `.attribution` sidecar) and `crates/aep/tests/fixtures/ai-mask-3099.aep` (original work, made with After Effects 2026 from four hand-written one-page PDFs named `.ai`, footage paths and host name neutralised, the embedded colour profiles replaced by stubs made with `crates/aep/examples/stubicc.rs`; MIT OR Apache-2.0, with its `.attribution` sidecar). The other After Effects test projects of `crates/aep` are not in this repository. They are original work of an EffectCraft contributor, generated with After Effects 2026 as own test data (MIT OR Apache-2.0, each file with its `.attribution` sidecar); they are in [storytold/effectcraft-corpus](https://github.com/storytold/effectcraft-corpus) with their sidecars, fetched by `cargo xtask aep-corpus` (commit-pinned, SHA-256-verified), and the tests read them only from the folder named by `EFFECTCRAFT_AEP_FIXTURES` (opt-in). Their embedded colour profiles are replaced by stubs made with `crates/aep/examples/stubicc.rs` (a header and a description, no colour data), so no vendor profile data is in them. - -## Screenshots - -Screenshots of EffectCraft itself, rendered headlessly, showing only procedurally generated demo content. - -| Asset | Author | Source | Licence | -|---|---|---|---| -| `docs/images/effectcraft-hero.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft main window) | MIT OR Apache-2.0 | -| `docs/images/effectcraft-3d.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft Classic 3D) | MIT OR Apache-2.0 | -| `docs/images/effectcraft-graph-editor.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft Graph Editor) | MIT OR Apache-2.0 | -| `docs/images/effectcraft-effects.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft effects) | MIT OR Apache-2.0 | -| `docs/images/effectcraft-render-queue.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft Render Queue panel with the demo compositions queued for H.264 and ProRes export) | MIT OR Apache-2.0 | - -## Code-drawn assets (original work, MIT OR Apache-2.0) - -- UI icons drawn in code: `crates/ui-egui/src/icons.rs`, including the original filled favorite star (2026-10-11, EffectCraft contributors). -- Procedural demo content (solids, shapes, gradients, text animations): `crates/engine/src/demo.rs`. -- Built-in project templates (Lower Third, Title Card, Logo Reveal, Kinetic Type, Social Square, Vertical Story, - Slideshow, 3D Text Orbit) built from engine commands, and their thumbnails rendered by our own renderer: - `crates/engine/src/templates.rs`. -- Text animator presets (Typewriter, Fade Up Characters, Bounce In Words, Tracking In, Scramble, Blur In, Jitter, - Drop In Lines): `crates/engine/presets/text_animators.json` (sidecar `.attribution`). -- Transition animation presets (23: wipes, clock and fan reveals, blinds, dissolves, card flips, CC wipes, fades): - `crates/engine/presets/transitions.json` (sidecar `.attribution`). -- Backgrounds animation presets (23: drifting gradients, fog, cloud and smoke, plasma and magma, cells and crystals, scrolling grids - and checks, pulse rings, bokeh, light sweep): `crates/engine/presets/backgrounds.json` (sidecar `.attribution`). -- Behaviors animation presets (22: wiggle, shake, float, orbit, bounce, drift, pendulum, spin, pulse, heartbeat, blink, strobe, flicker): - `crates/engine/presets/behaviors.json` (sidecar `.attribution`). -- Sample scripts (File ▸ Scripts) and ScriptUI panel: `crates/engine/scripts/Rename Layers.jsx`, - `crates/engine/scripts/Sort Layers by In Point.jsx`, `crates/engine/scripts/Create Null at Selected Layers.jsx`, - `crates/engine/scripts/Render Queue Batch.jsx`, `crates/engine/scripts/ScriptUI Panels/Layer Tools.jsx` - (sidecars `.attribution`). -- Bundled extension (ScriptUI panel) with its twelve built-in ease presets: - `extensions/scriptui-panels/Ease Presets.jsx` (sidecar `.attribution`). -- Example effect plug-in: `examples/plugins/posterize-bands` (WebAssembly ABI 1). - -## Trained models (optional downloads, not bundled) - -The repository and the installers contain no model weights. These models are downloaded only when -a user asks (Settings ▸ Roto Brush, Settings ▸ Face Tracking, or the `roto.model.*` / -`face.model.*` commands), unmodified from their authors' official location, checked against a -pinned SHA-256 and stored in the user's `models` folder with a `.NOTICE.txt` naming their -authors, licence and source. EffectCraft runs them with its own Rust implementation and is not -affiliated with or endorsed by their authors. - -| Model | Authors | Source | Licence | -|---|---|---|---| -| MobileSAM (`mobile_sam.pt`) | Chaoning Zhang et al., building on Meta AI's Segment Anything and Microsoft's TinyViT | https://github.com/ChaoningZhang/MobileSAM | Apache-2.0 | -| MediaPipe Face Landmarker (`face_landmarker.task`: BlazeFace short-range detector, Face Mesh V2, blendshapes) | Google LLC | https://developers.google.com/edge/mediapipe/solutions/vision/face_landmarker (model cards: https://storage.googleapis.com/mediapipe-assets/MediaPipe%20BlazeFace%20Model%20Card%20(Short%20Range).pdf, https://storage.googleapis.com/mediapipe-assets/Model%20Card%20MediaPipe%20Face%20Mesh%20V2.pdf) | Apache-2.0 | - -## Formats and parameters from other open-source projects - -Written in Rust for EffectCraft; no code is copied. They follow published specifications and -configuration from these Apache-2.0 projects: - -- `crates/segment/src/tflite.rs` reads TensorFlow Lite files using the field layout of TensorFlow - Lite's `schema.fbs` (The TensorFlow Authors, https://github.com/tensorflow/tensorflow, - Apache-2.0). -- `crates/segment/src/mediapipe.rs` follows MediaPipe's published face landmarker graph: the SSD - anchor layout, detection decoding, crop sizes and the face-mesh point indices it uses (Google - LLC, https://github.com/google-ai-edge/mediapipe, Apache-2.0). -- `crates/segment/src/mobilesam.rs` follows the MobileSAM, TinyViT and Segment Anything - architectures and their Apache-2.0 reference code. - -## Frozen matte regression fixture - -| Asset | Author | Source | Licence | -|---|---|---|---| -| `crates/engine/src/tests/fixtures/analysed-0.24.ecproj` | arnav-hiwarkar | Original work, synthetic project keyed by EffectCraft 0.24.1 | MIT OR Apache-2.0 | -| `crates/engine/src/tests/fixtures/object-matte-0.22.ecproj` | lisn0 | Original work, synthetic project saved by EffectCraft 0.22.0 | MIT OR Apache-2.0 | -| `crates/engine/src/tests/fixtures/tracked-0.22.ecproj` | arnav-hiwarkar | Original work, synthetic project saved by EffectCraft 0.22.0 | MIT OR Apache-2.0 | - -## First-party brand marks - -The ArtCraft name, wordmark and logos are trademarks of the ArtCraft Team. They are not open source and are not -covered by the project licence; they may be used only unmodified and only as part of this repository and EffectCraft, -under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt). Forks and modified versions must remove them -(AGENTS.md §1.8). - -| File | Author | Source | Licence | -|---|---|---|---| -| `docs/brand/artcraft-logo-white.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft wordmark, light ink for dark backgrounds) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) | -| `docs/brand/artcraft-logo-white.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft wordmark, light ink for dark backgrounds) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) | -| `docs/brand/artcraft-logo.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft wordmark (symbol + "ARTCRAFT"), dark ink for light backgrounds) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) | -| `docs/brand/artcraft-logo.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft wordmark (symbol + "ARTCRAFT"), dark ink for light backgrounds) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) | -| `docs/brand/artcraft-mark-black.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), black) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) | -| `docs/brand/artcraft-mark-black.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), black) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) | -| `docs/brand/artcraft-mark.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), blue) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) | -| `docs/brand/artcraft-mark.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), blue) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) | - +# Attribution + +Every non-code asset in EffectCraft, with its author, source and licence. Each repository file listed here also has +a `.attribution` sidecar with full details. The rules are in [AGENTS.md](AGENTS.md) §1: no Adobe +iconography, images or other Adobe assets; open licences only; every asset attributed. +`cargo xtask assets` checks that this index and the sidecars cover every asset in the repository. +The complete licence texts and copyright notices for the bundled fonts, including the fonts embedded +by the pinned egui dependency, are reproduced in [`NOTICE`](NOTICE), which every package ships; the +`assets/fonts/OFL-*.txt` files are the upstream copies kept beside the fonts. + +## Bundled dependency fonts + +These fonts are embedded by the pinned egui dependency (epaint_default_fonts 0.37 at +`6d518fc799681571963842f95b55a6b68431b15a`); no font file is added to this repository. +egui-icons is always embedded, `default_fonts` adds Ubuntu Light and Hack, and +`monochrome_emoji_fonts` adds Noto Emoji and emoji-icon-font. The complete copyright notices +and licence texts are in [`NOTICE`](NOTICE). + +| Asset | Author | Source | Licence | +|---|---|---|---| +| `epaint_default_fonts/fonts/egui-icons.ttf` | John Slegers (emoji-icon-font) | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/egui-icons.txt; original https://github.com/jslegers/emoji-icon-font | MIT (complete copyright and permission text in `NOTICE`) | +| `epaint_default_fonts/fonts/emoji-icon-font.ttf` | John Slegers | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/emoji-icon-font-mit-license.txt; original https://github.com/jslegers/emoji-icon-font | MIT (complete copyright and permission text in `NOTICE`) | +| `epaint_default_fonts/fonts/NotoEmoji-Regular.ttf` | Google Inc. (The Noto Project Authors) | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/OFL.txt | OFL-1.1 (complete text in `NOTICE`) | +| `epaint_default_fonts/fonts/Ubuntu-Light.ttf` | Canonical Ltd. and Dalton Maag | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/UFL.txt | Ubuntu Font Licence 1.0 (complete text in `NOTICE`) | +| `epaint_default_fonts/fonts/Hack-Regular.ttf` | Source Foundry Authors; Bitstream Inc. | https://github.com/storytold/egui/blob/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts/Hack-Regular.txt; original https://github.com/source-foundry/Hack | MIT AND Bitstream-Vera (complete texts in `NOTICE`) | + +## Asset files + +| Asset | Author | Source | Licence | +|---|---|---|---| +| `assets/fonts/Inter-Regular.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | +| `assets/fonts/Inter-Medium.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | +| `assets/fonts/Inter-SemiBold.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | +| `assets/fonts/Inter-Bold.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | +| `assets/fonts/Inter-Italic.ttf` | The Inter Project Authors | https://github.com/rsms/inter | OFL-1.1 (`assets/fonts/OFL-Inter.txt`) | +| `assets/fonts/NotoSerif-Regular.ttf` | The Noto Project Authors | https://github.com/notofonts/latin-greek-cyrillic | OFL-1.1 (`assets/fonts/OFL-NotoSerif.txt`) | +| `assets/fonts/NotoSansSymbols2-Regular.ttf` | The Noto Project Authors | https://github.com/notofonts/symbols | OFL-1.1 (`assets/fonts/OFL-NotoSansSymbols2.txt`) | +| `assets/fonts/JetBrainsMono-Regular.ttf` | The JetBrains Mono Project Authors | https://github.com/JetBrains/JetBrainsMono | OFL-1.1 (`assets/fonts/OFL-JetBrainsMono.txt`) | +| `apps/effectcraft-web/web/favicon.svg` | EffectCraft contributors | Original work: web app icon, a copy of `assets/app-icon/effectcraft-small.svg` (the unicorn app icon) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `packaging/macos/dmg/background.svg` | @XusBadia | Original work: macOS DMG Finder window background, derived from the EffectCraft app icon (`assets/app-icon/effectcraft.svg`); rendered to a TIFF by `packaging/macos/package.sh` at package time | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | +| `assets/app-icon/effectcraft-1024.png` | EffectCraft contributors | Original work: effectCraft app icon, 1024 px (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `assets/app-icon/effectcraft-macos-512.png` | EffectCraft contributors | Original work: effectCraft runtime Dock icon (macOS) (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `assets/app-icon/effectcraft-small.svg` | EffectCraft contributors | Original work: effectCraft app icon, light vector (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `assets/app-icon/effectcraft.icns` | EffectCraft contributors | Original work: effectCraft macOS app icon (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `assets/app-icon/effectcraft.ico` | EffectCraft contributors | Original work: effectCraft Windows app icon (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `assets/app-icon/effectcraft.svg` | EffectCraft contributors | Original work: effectCraft app icon, master vector (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `assets/app-icon/hicolor/128x128/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 128x128 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `assets/app-icon/hicolor/16x16/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 16x16 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `assets/app-icon/hicolor/24x24/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 24x24 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `assets/app-icon/hicolor/256x256/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 256x256 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `assets/app-icon/hicolor/32x32/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 32x32 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `assets/app-icon/hicolor/48x48/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 48x48 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `assets/app-icon/hicolor/512x512/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 512x512 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `assets/app-icon/hicolor/64x64/apps/ai.storyteller.effectcraft.png` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor 64x64 (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.effectcraft.svg` | EffectCraft contributors | Original work: effectCraft app icon, Linux hicolor scalable (owner's ArtCraft unicorn drawing, vectorised) | MIT OR Apache-2.0 (`assets/app-icon/LICENSE.txt`) | +| `crates/lottie/tests/fixtures/bouncing-ball.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (bouncing ball, eased position keys) | MIT OR Apache-2.0 | +| `crates/lottie/tests/fixtures/shapes-gradient.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (star, rectangle, gradient fill, dashed stroke, trim paths) | MIT OR Apache-2.0 | +| `crates/lottie/tests/fixtures/precomp-matte-text.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (precomp, track matte, parented text) | MIT OR Apache-2.0 | +| `crates/lottie/tests/fixtures/legacy-masks.json` | EffectCraft contributors | Original work: hand-written Lottie test fixture (legacy keyframes, masks) | MIT OR Apache-2.0 | +| `crates/svg/tests/fixtures/basic-shapes.svg` | EffectCraft contributors | Original work: hand-written SVG test fixture (basic shapes, groups, transforms) | MIT OR Apache-2.0 | +| `crates/svg/tests/fixtures/paths-gradients.svg` | EffectCraft contributors | Original work: hand-written SVG test fixture (path data, gradients, CSS, use) | MIT OR Apache-2.0 | +| `crates/model/tests/fixtures/quad.gltf` | EffectCraft contributors | Original work: glTF 2.0 test fixture (textured quad, node hierarchy, translation animation; data URIs) | MIT OR Apache-2.0 | +| `crates/model/tests/fixtures/quad.glb` | EffectCraft contributors | Original work: binary glTF test fixture (the same quad with its texture in the BIN chunk) | MIT OR Apache-2.0 | +| `crates/model/tests/fixtures/cube.obj` | EffectCraft contributors | Original work: Wavefront OBJ test fixture (unit cube, two materials) | MIT OR Apache-2.0 | +| `crates/model/tests/fixtures/cube.mtl` | EffectCraft contributors | Original work: MTL test fixture (materials of cube.obj) | MIT OR Apache-2.0 | + +Three small After Effects test projects of `crates/aep` are in this repository: `crates/aep/tests/fixtures/synthetic.aep` (original work, made with After Effects 2026 from own data, working space None, the embedded colour profile removed; MIT OR Apache-2.0, with its `.attribution` sidecar), `crates/aep/tests/fixtures/ai-mask-3099.aep` (original work, made with After Effects 2026 from four hand-written one-page PDFs named `.ai`, footage paths and host name neutralised, the embedded colour profiles replaced by stubs made with `crates/aep/examples/stubicc.rs`; MIT OR Apache-2.0, with its `.attribution` sidecar) and `crates/aep/tests/fixtures/text-synthetic.aep` (original work, made with After Effects 2026 by script from own data, working space None, no colour profile embedded, nothing changed after the save; MIT OR Apache-2.0, with its `.attribution` sidecar). The other After Effects test projects of `crates/aep` are not in this repository. They are original work of an EffectCraft contributor, generated with After Effects 2026 as own test data (MIT OR Apache-2.0, each file with its `.attribution` sidecar); they are in [storytold/effectcraft-corpus](https://github.com/storytold/effectcraft-corpus) with their sidecars, fetched by `cargo xtask aep-corpus` (commit-pinned, SHA-256-verified), and the tests read them only from the folder named by `EFFECTCRAFT_AEP_FIXTURES` (opt-in). Their embedded colour profiles are replaced by stubs made with `crates/aep/examples/stubicc.rs` (a header and a description, no colour data), so no vendor profile data is in them. + +## Screenshots + +Screenshots of EffectCraft itself, rendered headlessly, showing only procedurally generated demo content. + +| Asset | Author | Source | Licence | +|---|---|---|---| +| `docs/images/effectcraft-hero.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft main window) | MIT OR Apache-2.0 | +| `docs/images/effectcraft-3d.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft Classic 3D) | MIT OR Apache-2.0 | +| `docs/images/effectcraft-graph-editor.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft Graph Editor) | MIT OR Apache-2.0 | +| `docs/images/effectcraft-effects.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft effects) | MIT OR Apache-2.0 | +| `docs/images/effectcraft-render-queue.png` | EffectCraft contributors | Original work: screenshot of EffectCraft (EffectCraft Render Queue panel with the demo compositions queued for H.264 and ProRes export) | MIT OR Apache-2.0 | + +## Code-drawn assets (original work, MIT OR Apache-2.0) + +- UI icons drawn in code: `crates/ui-egui/src/icons.rs`, including the original filled favorite star (2026-10-11, EffectCraft contributors). +- Procedural demo content (solids, shapes, gradients, text animations): `crates/engine/src/demo.rs`. +- Built-in project templates (Lower Third, Title Card, Logo Reveal, Kinetic Type, Social Square, Vertical Story, + Slideshow, 3D Text Orbit) built from engine commands, and their thumbnails rendered by our own renderer: + `crates/engine/src/templates.rs`. +- Text animator presets (Typewriter, Fade Up Characters, Bounce In Words, Tracking In, Scramble, Blur In, Jitter, + Drop In Lines): `crates/engine/presets/text_animators.json` (sidecar `.attribution`). +- Transition animation presets (23: wipes, clock and fan reveals, blinds, dissolves, card flips, CC wipes, fades): + `crates/engine/presets/transitions.json` (sidecar `.attribution`). +- Backgrounds animation presets (23: drifting gradients, fog, cloud and smoke, plasma and magma, cells and crystals, scrolling grids + and checks, pulse rings, bokeh, light sweep): `crates/engine/presets/backgrounds.json` (sidecar `.attribution`). +- Behaviors animation presets (22: wiggle, shake, float, orbit, bounce, drift, pendulum, spin, pulse, heartbeat, blink, strobe, flicker): + `crates/engine/presets/behaviors.json` (sidecar `.attribution`). +- Sample scripts (File ▸ Scripts) and ScriptUI panel: `crates/engine/scripts/Rename Layers.jsx`, + `crates/engine/scripts/Sort Layers by In Point.jsx`, `crates/engine/scripts/Create Null at Selected Layers.jsx`, + `crates/engine/scripts/Render Queue Batch.jsx`, `crates/engine/scripts/ScriptUI Panels/Layer Tools.jsx` + (sidecars `.attribution`). +- Bundled extension (ScriptUI panel) with its twelve built-in ease presets: + `extensions/scriptui-panels/Ease Presets.jsx` (sidecar `.attribution`). +- Example effect plug-in: `examples/plugins/posterize-bands` (WebAssembly ABI 1). + +## Trained models (optional downloads, not bundled) + +The repository and the installers contain no model weights. These models are downloaded only when +a user asks (Settings ▸ Roto Brush, Settings ▸ Face Tracking, or the `roto.model.*` / +`face.model.*` commands), unmodified from their authors' official location, checked against a +pinned SHA-256 and stored in the user's `models` folder with a `.NOTICE.txt` naming their +authors, licence and source. EffectCraft runs them with its own Rust implementation and is not +affiliated with or endorsed by their authors. + +| Model | Authors | Source | Licence | +|---|---|---|---| +| MobileSAM (`mobile_sam.pt`) | Chaoning Zhang et al., building on Meta AI's Segment Anything and Microsoft's TinyViT | https://github.com/ChaoningZhang/MobileSAM | Apache-2.0 | +| MediaPipe Face Landmarker (`face_landmarker.task`: BlazeFace short-range detector, Face Mesh V2, blendshapes) | Google LLC | https://developers.google.com/edge/mediapipe/solutions/vision/face_landmarker (model cards: https://storage.googleapis.com/mediapipe-assets/MediaPipe%20BlazeFace%20Model%20Card%20(Short%20Range).pdf, https://storage.googleapis.com/mediapipe-assets/Model%20Card%20MediaPipe%20Face%20Mesh%20V2.pdf) | Apache-2.0 | + +## Formats and parameters from other open-source projects + +Written in Rust for EffectCraft; no code is copied. They follow published specifications and +configuration from these Apache-2.0 projects: + +- `crates/segment/src/tflite.rs` reads TensorFlow Lite files using the field layout of TensorFlow + Lite's `schema.fbs` (The TensorFlow Authors, https://github.com/tensorflow/tensorflow, + Apache-2.0). +- `crates/segment/src/mediapipe.rs` follows MediaPipe's published face landmarker graph: the SSD + anchor layout, detection decoding, crop sizes and the face-mesh point indices it uses (Google + LLC, https://github.com/google-ai-edge/mediapipe, Apache-2.0). +- `crates/segment/src/mobilesam.rs` follows the MobileSAM, TinyViT and Segment Anything + architectures and their Apache-2.0 reference code. + +## Frozen matte regression fixture + +| Asset | Author | Source | Licence | +|---|---|---|---| +| `crates/engine/src/tests/fixtures/analysed-0.24.ecproj` | arnav-hiwarkar | Original work, synthetic project keyed by EffectCraft 0.24.1 | MIT OR Apache-2.0 | +| `crates/engine/src/tests/fixtures/object-matte-0.22.ecproj` | lisn0 | Original work, synthetic project saved by EffectCraft 0.22.0 | MIT OR Apache-2.0 | +| `crates/engine/src/tests/fixtures/tracked-0.22.ecproj` | arnav-hiwarkar | Original work, synthetic project saved by EffectCraft 0.22.0 | MIT OR Apache-2.0 | + +## First-party brand marks + +The ArtCraft name, wordmark and logos are trademarks of the ArtCraft Team. They are not open source and are not +covered by the project licence; they may be used only unmodified and only as part of this repository and EffectCraft, +under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt). Forks and modified versions must remove them +(AGENTS.md §1.8). + +| File | Author | Source | Licence | +|---|---|---|---| +| `docs/brand/artcraft-logo-white.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft wordmark, light ink for dark backgrounds) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) | +| `docs/brand/artcraft-logo-white.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft wordmark, light ink for dark backgrounds) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) | +| `docs/brand/artcraft-logo.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft wordmark (symbol + "ARTCRAFT"), dark ink for light backgrounds) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) | +| `docs/brand/artcraft-logo.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft wordmark (symbol + "ARTCRAFT"), dark ink for light backgrounds) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) | +| `docs/brand/artcraft-mark-black.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), black) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) | +| `docs/brand/artcraft-mark-black.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), black) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) | +| `docs/brand/artcraft-mark.png` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), blue) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) | +| `docs/brand/artcraft-mark.svg` | ArtCraft Team | Original work: first-party ArtCraft brand mark (ArtCraft symbol ("A" mark), blue) | ArtCraft brand terms, not open source (`docs/brand/LICENSE-brand.txt`) | + - Appearance theme previews, drawn procedurally from original shapes: `crates/ui-egui/src/panels/settings.rs` (original work, MIT OR Apache-2.0). + +## Synthetic test audio + +| Asset | Author | Source | Licence | +|---|---|---|---| +| `crates/media/tests/fixtures/pce61-ffmpeg.aac-fixture` | Dylan M. Taylor | Original sine waves; reproducible recipe in `crates/media/tests/fixtures/README.md` | MIT OR Apache-2.0 | diff --git a/CLAUDE.md b/CLAUDE.md index 43c994c2d..fd25442bf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1 +1 @@ -@AGENTS.md +@AGENTS.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8ce4b85aa..8d0027664 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,109 +1,109 @@ -# Contributing to EffectCraft - -Thanks for helping. Please read [AGENTS.md](AGENTS.md) first: its rules on assets and clean-room -work apply to everyone, people and AI agents alike, and they are not negotiable. - -## Setup - -You need [Rust](https://rustup.rs/) 1.95 or newer. - -On Linux the desktop app plays preview sound through `cpal`, so the build needs a usable ALSA -pkg-config package: an `alsa.pc` that pkg-config can find, naming the linkable ALSA runtime -library (usually `libasound.so.2`). `alsa-sys` runs pkg-config at build time; it does not compile -ALSA's headers. Without a usable package the build fails at link time with an unrelated-looking -error; `cargo xtask ci` probes pkg-config up front and names the package: - -```sh -sudo dnf install alsa-lib-devel # Fedora -sudo apt install libasound2-dev # Debian / Ubuntu -sudo pacman -S alsa-lib # Arch -``` - -If you cannot install the package, point `PKG_CONFIG_PATH` at a directory holding an `alsa.pc` -whose `Libs` line names your system's `libasound` (usually `libasound.so.2`); every CI run needs -that variable set. - -```sh -cargo run -p effectcraft -- --demo # the desktop app, with the demo project -cargo test --workspace -cargo xtask ci # what every commit must pass (dev-profile checks and tests) -``` - -The default `dev` profile keeps debug info to line tables: builds are fast and panics/backtraces -still name the file and line, but a debugger cannot show local variables. For an interactive -debugger session use the `dev-full` profile, which is the same build with full debug info: - -```sh -cargo run --profile dev-full -p effectcraft -- --demo -``` - -### Windows - -The MSVC toolchain, rustup's default on Windows, is what the releases use: with the Visual Studio -C++ build tools installed, the commands above work as they are. - -The GNU toolchain (`x86_64-pc-windows-gnu`) needs a current mingw-w64 GCC and binutils first on -`PATH`. They provide the linker and the Windows import libraries, such as `libshlwapi.a` for -opening links from the app. With MSYS2: - -```powershell -C:\msys64\usr\bin\pacman.exe -S --needed mingw-w64-x86_64-gcc -$env:PATH = "C:\msys64\mingw64\bin;$env:PATH" -cargo +stable-x86_64-pc-windows-gnu run -p effectcraft -- --demo -``` - -An older MinGW earlier on `PATH` can break the build: CodeBlocks' GCC 8.1 fails to link -`boa_engine` ([#1882](https://github.com/storytold/effectcraft/issues/1882)). - -Rust's bundled LLD and self-contained libraries don't include every import library EffectCraft -needs, so on their own they stop with `unable to find library` for `-lshlwapi`, `-lktmw32`, -`-lpropsys` and `-lversion` ([#1886](https://github.com/storytold/effectcraft/issues/1886)). To -link that way, copy those four from mingw-w64 into a folder of its own and add that folder to the -search path in your own Cargo config (`%USERPROFILE%\.cargo\config.toml`). Don't add all of -mingw-w64's `lib` folder: its C runtime clashes with Rust's bundled one -(`undefined symbol: DllEntryPoint`). - -```powershell -New-Item -ItemType Directory -Force C:\gnu-import-libs -foreach ($lib in "shlwapi", "ktmw32", "propsys", "version") { - Copy-Item "C:\msys64\mingw64\lib\lib$lib.a" C:\gnu-import-libs\ -} -``` - -```toml -[target.x86_64-pc-windows-gnu] -linker = "rust-lld" -rustflags = ["-C", "link-self-contained=yes", "-L", "native=C:/gnu-import-libs"] -``` - -## Ground rules - -- **Clean room.** Work from After Effects' public documentation and its observable behaviour only. - Never use Adobe artwork, presets or code, and never copy GPL/LGPL/AGPL code. -- **Every asset is attributed.** Add a `.attribution` sidecar and an [ATTRIBUTION.md](ATTRIBUTION.md) - row; `cargo xtask assets` checks it. -- **Layering.** Nothing below the interface layer depends on UI or OS crates; see - [docs/architecture.md](docs/architecture.md). -- **Everything is a command.** New features are engine commands with an id, label, menu path, - shortcut and parameters, so the UI, the CLI and the MCP server get them at once. Interactive - widgets register an automation id. -- **Never crash.** Non-test code returns errors instead of panicking: no `unwrap()`, `expect()`, - `panic!`, `unreachable!`, `todo!`, `unimplemented!` or `unsafe`, checked indexing and arithmetic on - input-derived values, and a regression test with every crash fix. See the "Never crash" section of - [AGENTS.md](AGENTS.md). -- **Tests with every change**, and green `cargo xtask ci` before every commit. One task per commit. - -## How to add… - -- **An effect:** add an `EffectSpec` in `crates/effects` (AE display name, category, parameters - with AE's names, defaults and ranges) and its render function, with a determinism test and a - behaviour test. If it reads the clock directly, add it to `TIME_DEPENDENT`. -- **A command:** register it with `cmd!` in `crates/engine/src/commands/`, place it in the menu - tree in `crates/engine/src/menus.rs`, and test it including undo. -- **A panel or dialog:** `crates/ui-egui/src/panels/`; look at the result with the headless - snapshot tool described in [docs/testing.md](docs/testing.md). - -## Talk to us - -Questions, ideas and bug reports are welcome on [Discord](https://discord.gg/artcraft) and in -GitHub issues. +# Contributing to EffectCraft + +Thanks for helping. Please read [AGENTS.md](AGENTS.md) first: its rules on assets and clean-room +work apply to everyone, people and AI agents alike, and they are not negotiable. + +## Setup + +You need [Rust](https://rustup.rs/) 1.95 or newer. + +On Linux the desktop app plays preview sound through `cpal`, so the build needs a usable ALSA +pkg-config package: an `alsa.pc` that pkg-config can find, naming the linkable ALSA runtime +library (usually `libasound.so.2`). `alsa-sys` runs pkg-config at build time; it does not compile +ALSA's headers. Without a usable package the build fails at link time with an unrelated-looking +error; `cargo xtask ci` probes pkg-config up front and names the package: + +```sh +sudo dnf install alsa-lib-devel # Fedora +sudo apt install libasound2-dev # Debian / Ubuntu +sudo pacman -S alsa-lib # Arch +``` + +If you cannot install the package, point `PKG_CONFIG_PATH` at a directory holding an `alsa.pc` +whose `Libs` line names your system's `libasound` (usually `libasound.so.2`); every CI run needs +that variable set. + +```sh +cargo run -p effectcraft -- --demo # the desktop app, with the demo project +cargo test --workspace +cargo xtask ci # what every commit must pass (dev-profile checks and tests) +``` + +The default `dev` profile keeps debug info to line tables: builds are fast and panics/backtraces +still name the file and line, but a debugger cannot show local variables. For an interactive +debugger session use the `dev-full` profile, which is the same build with full debug info: + +```sh +cargo run --profile dev-full -p effectcraft -- --demo +``` + +### Windows + +The MSVC toolchain, rustup's default on Windows, is what the releases use: with the Visual Studio +C++ build tools installed, the commands above work as they are. + +The GNU toolchain (`x86_64-pc-windows-gnu`) needs a current mingw-w64 GCC and binutils first on +`PATH`. They provide the linker and the Windows import libraries, such as `libshlwapi.a` for +opening links from the app. With MSYS2: + +```powershell +C:\msys64\usr\bin\pacman.exe -S --needed mingw-w64-x86_64-gcc +$env:PATH = "C:\msys64\mingw64\bin;$env:PATH" +cargo +stable-x86_64-pc-windows-gnu run -p effectcraft -- --demo +``` + +An older MinGW earlier on `PATH` can break the build: CodeBlocks' GCC 8.1 fails to link +`boa_engine` ([#1882](https://github.com/storytold/effectcraft/issues/1882)). + +Rust's bundled LLD and self-contained libraries don't include every import library EffectCraft +needs, so on their own they stop with `unable to find library` for `-lshlwapi`, `-lktmw32`, +`-lpropsys` and `-lversion` ([#1886](https://github.com/storytold/effectcraft/issues/1886)). To +link that way, copy those four from mingw-w64 into a folder of its own and add that folder to the +search path in your own Cargo config (`%USERPROFILE%\.cargo\config.toml`). Don't add all of +mingw-w64's `lib` folder: its C runtime clashes with Rust's bundled one +(`undefined symbol: DllEntryPoint`). + +```powershell +New-Item -ItemType Directory -Force C:\gnu-import-libs +foreach ($lib in "shlwapi", "ktmw32", "propsys", "version") { + Copy-Item "C:\msys64\mingw64\lib\lib$lib.a" C:\gnu-import-libs\ +} +``` + +```toml +[target.x86_64-pc-windows-gnu] +linker = "rust-lld" +rustflags = ["-C", "link-self-contained=yes", "-L", "native=C:/gnu-import-libs"] +``` + +## Ground rules + +- **Clean room.** Work from After Effects' public documentation and its observable behaviour only. + Never use Adobe artwork, presets or code, and never copy GPL/LGPL/AGPL code. +- **Every asset is attributed.** Add a `.attribution` sidecar and an [ATTRIBUTION.md](ATTRIBUTION.md) + row; `cargo xtask assets` checks it. +- **Layering.** Nothing below the interface layer depends on UI or OS crates; see + [docs/architecture.md](docs/architecture.md). +- **Everything is a command.** New features are engine commands with an id, label, menu path, + shortcut and parameters, so the UI, the CLI and the MCP server get them at once. Interactive + widgets register an automation id. +- **Never crash.** Non-test code returns errors instead of panicking: no `unwrap()`, `expect()`, + `panic!`, `unreachable!`, `todo!`, `unimplemented!` or `unsafe`, checked indexing and arithmetic on + input-derived values, and a regression test with every crash fix. See the "Never crash" section of + [AGENTS.md](AGENTS.md). +- **Tests with every change**, and green `cargo xtask ci` before every commit. One task per commit. + +## How to add… + +- **An effect:** add an `EffectSpec` in `crates/effects` (AE display name, category, parameters + with AE's names, defaults and ranges) and its render function, with a determinism test and a + behaviour test. If it reads the clock directly, add it to `TIME_DEPENDENT`. +- **A command:** register it with `cmd!` in `crates/engine/src/commands/`, place it in the menu + tree in `crates/engine/src/menus.rs`, and test it including undo. +- **A panel or dialog:** `crates/ui-egui/src/panels/`; look at the result with the headless + snapshot tool described in [docs/testing.md](docs/testing.md). + +## Talk to us + +Questions, ideas and bug reports are welcome on [Discord](https://discord.gg/artcraft) and in +GitHub issues. diff --git a/Cargo.lock b/Cargo.lock index 79691772a..f5b87bf7e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -129,6 +129,15 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "aligned" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685" +dependencies = [ + "as-slice", +] + [[package]] name = "aligned-vec" version = "0.6.4" @@ -200,6 +209,18 @@ dependencies = [ "libc", ] +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" + [[package]] name = "arboard" version = "3.6.1" @@ -221,6 +242,17 @@ dependencies = [ "x11rb", ] +[[package]] +name = "arg_enum_proc_macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "arrayref" version = "0.3.9" @@ -242,6 +274,15 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" +[[package]] +name = "as-slice" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516" +dependencies = [ + "stable_deref_trait", +] + [[package]] name = "ash" version = "0.38.0+1.3.281" @@ -431,6 +472,40 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "av-scenechange" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394" +dependencies = [ + "aligned", + "anyhow", + "arg_enum_proc_macro", + "arrayvec", + "log", + "num-rational", + "num-traits", + "pastey 0.1.1", + "rayon", + "thiserror 2.0.21", + "v_frame", + "y4m", +] + +[[package]] +name = "av1-grain" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8" +dependencies = [ + "anyhow", + "arrayvec", + "log", + "nom", + "num-rational", + "v_frame", +] + [[package]] name = "base64" version = "0.23.1" @@ -489,6 +564,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "bitstream-io" +version = "4.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f" +dependencies = [ + "no_std_io2", +] + [[package]] name = "block-buffer" version = "0.10.4" @@ -540,7 +624,7 @@ dependencies = [ "boa_macros", "boa_string", "indexmap", - "num-bigint", + "num-bigint 0.5.1", "rustc-hash 2.1.3", "strum", ] @@ -574,13 +658,13 @@ dependencies = [ "icu_normalizer", "indexmap", "intrusive-collections", - "itertools", - "num-bigint", + "itertools 0.15.0", + "num-bigint 0.5.1", "num-integer", "num-traits", "num_enum", "oneshot", - "pastey", + "pastey 0.2.3", "portable-atomic", "rand 0.10.3", "regress", @@ -653,7 +737,7 @@ dependencies = [ "boa_macros", "fast-float2", "icu_properties", - "num-bigint", + "num-bigint 0.5.1", "num-traits", "regress", "rustc-hash 2.1.3", @@ -667,7 +751,7 @@ checksum = "30bf86c2bcff5bf2547acbfc516c5d3108ca527cb131511d749bf6fbef762c0e" dependencies = [ "fast-float2", "itoa", - "pastey", + "pastey 0.2.3", "rustc-hash 2.1.3", "ryu-js", "static_assertions", @@ -697,6 +781,12 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "built" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9" + [[package]] name = "bumpalo" version = "3.20.3" @@ -1089,39 +1179,159 @@ dependencies = [ "libc", ] +[[package]] +name = "craft-aaf" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d" +dependencies = [ + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)", + "craft-cfb 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)", + "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-aep" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" + [[package]] name = "craft-audio" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-audio" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab" +dependencies = [ + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", + "log", + "rayon", + "symphonia 0.6.1", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-audio" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d" +dependencies = [ + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)", + "log", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-cfb" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93#7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93" + +[[package]] +name = "craft-cfb" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d" + +[[package]] +name = "craft-cms" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=58964adec11197594d9b6b79a94ae6232221211a#58964adec11197594d9b6b79a94ae6232221211a" +dependencies = [ + "md-5", + "rayon", +] + +[[package]] +name = "craft-codepage" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" + +[[package]] +name = "craft-doc" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +dependencies = [ + "craft-ecproj-format", + "craft-pcraft-format", + "craft-vectorcraft-format", + "flate2", + "serde", + "serde_json", "thiserror 2.0.21", ] [[package]] name = "craft-docpath" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" + +[[package]] +name = "craft-dpx" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-dpx" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab" +dependencies = [ + "thiserror 2.0.21", +] [[package]] name = "craft-ecproj-format" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" dependencies = [ "serde", "serde_json", "thiserror 2.0.21", ] +[[package]] +name = "craft-eps" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae" + +[[package]] +name = "craft-exr" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +dependencies = [ + "exr", + "flate2", + "half", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-fonts-build" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" + +[[package]] +name = "craft-gif" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +dependencies = [ + "gif", + "image", +] [[package]] name = "craft-i18n" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" dependencies = [ "fixed_decimal", "icu_decimal", @@ -1141,10 +1351,28 @@ dependencies = [ "writeable", ] +[[package]] +name = "craft-jpeg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=937ac93c5cf3cd4b6a81e195b078fe161eb081b9#937ac93c5cf3cd4b6a81e195b078fe161eb081b9" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-lottie" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +dependencies = [ + "craft-zip", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" dependencies = [ "thiserror 2.0.21", ] @@ -1152,24 +1380,87 @@ dependencies = [ [[package]] name = "craft-media" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=f0ad6c1e1d297908915f4be315b0fcfc9be7b5d4#f0ad6c1e1d297908915f4be315b0fcfc9be7b5d4" +source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab" dependencies = [ + "chrono", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-media" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-mesh" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +dependencies = [ + "miniz_oxide 0.9.1", + "serde_json", +] + +[[package]] +name = "craft-mime" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +dependencies = [ + "chrono", + "craft-codepage", + "encoding_rs", +] + +[[package]] +name = "craft-pcraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +dependencies = [ + "flate2", + "serde", + "serde_json", "thiserror 2.0.21", ] [[package]] name = "craft-pdf" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae" dependencies = [ "hayro-syntax", "thiserror 2.0.21", ] +[[package]] +name = "craft-ps" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae" +dependencies = [ + "craft-eps", + "kurbo", + "miniz_oxide 0.8.9", + "pdf-writer", + "skrifa 0.47.0", + "weezl", +] + +[[package]] +name = "craft-psd" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=ce2ec507c2e6a6a078a5f450f641487f8931816d#ce2ec507c2e6a6a078a5f450f641487f8931816d" +dependencies = [ + "encoding_rs", + "flate2", + "rayon", + "thiserror 2.0.21", +] + [[package]] name = "craft-quit" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" dependencies = [ "dispatch2", "egui", @@ -1177,10 +1468,110 @@ dependencies = [ "objc2-app-kit 0.3.2", ] +[[package]] +name = "craft-raw" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac#bea91b1861eea3889bec9d26338076f2ff31c4ac" +dependencies = [ + "craft-tiff", + "miniz_oxide 0.9.1", + "rayon", + "serde", + "thiserror 2.0.21", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "craft-svg" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=e52cd9a889adbeeda447c75a546133960cf3382d#e52cd9a889adbeeda447c75a546133960cf3382d" +dependencies = [ + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e52cd9a889adbeeda447c75a546133960cf3382d)", + "flate2", + "kurbo", + "quick-xml 0.41.0", + "roxmltree", + "thiserror 2.0.21", + "vectorcraft-geom", + "vectorcraft-pathops", +] + +[[package]] +name = "craft-tga" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-tiff" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=bea91b1861eea3889bec9d26338076f2ff31c4ac#bea91b1861eea3889bec9d26338076f2ff31c4ac" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-time" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0d6dd8bed815b8366869a800d2bf22588ca62dcb#0d6dd8bed815b8366869a800d2bf22588ca62dcb" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-time" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0#57288edafdc45552e30481cc649021de446abfa0" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-time" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d" +dependencies = [ + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-timeline" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=0d6dd8bed815b8366869a800d2bf22588ca62dcb#0d6dd8bed815b8366869a800d2bf22588ca62dcb" +dependencies = [ + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0d6dd8bed815b8366869a800d2bf22588ca62dcb)", +] + +[[package]] +name = "craft-timeline" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0#57288edafdc45552e30481cc649021de446abfa0" +dependencies = [ + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0)", + "craft-xml 0.1.0 (git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0)", + "serde", + "serde_json", +] + +[[package]] +name = "craft-timeline" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d" +dependencies = [ + "craft-time 0.1.0 (git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d)", +] + [[package]] name = "craft-ui" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" dependencies = [ "craft-fonts-build", "craft-i18n", @@ -1192,7 +1583,7 @@ dependencies = [ "objc2-app-kit 0.3.2", "objc2-foundation 0.3.2", "serde", - "skrifa", + "skrifa 0.44.0", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", @@ -1201,7 +1592,7 @@ dependencies = [ [[package]] name = "craft-update" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" dependencies = [ "chrono", "dunce", @@ -1225,16 +1616,105 @@ dependencies = [ "zip 9.1.3", ] +[[package]] +name = "craft-vectorcraft-format" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +dependencies = [ + "flate2", + "serde", + "serde_json", + "thiserror 2.0.21", +] + [[package]] name = "craft-video" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", "rayon", "thiserror 2.0.21", ] +[[package]] +name = "craft-video" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab" +dependencies = [ + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", + "rav1e", + "rayon", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-webp" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +dependencies = [ + "image", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0#57288edafdc45552e30481cc649021de446abfa0" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab#82062077bba679ba5236e2d1a391f02d1533cbab" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=b3643af6477326e840f86be78c89357f5308ba1d#b3643af6477326e840f86be78c89357f5308ba1d" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-xml" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=e52cd9a889adbeeda447c75a546133960cf3382d#e52cd9a889adbeeda447c75a546133960cf3382d" +dependencies = [ + "quick-xml 0.41.0", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "craft-y4m" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=25c7a8959cf70cf8c3f076d05baadb0990710569#25c7a8959cf70cf8c3f076d05baadb0990710569" +dependencies = [ + "thiserror 2.0.21", +] + +[[package]] +name = "craft-zip" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87#5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" +dependencies = [ + "flate2", + "thiserror 2.0.21", + "zip 9.1.3", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -1469,6 +1949,7 @@ dependencies = [ "serde", "serde_json", "sysinfo", + "tempfile", "winit", "winresource", "zbus", @@ -1478,11 +1959,14 @@ dependencies = [ name = "effectcraft-aep" version = "0.24.1" dependencies = [ + "craft-aep", + "craft-mime", "effectcraft-color", "effectcraft-effects", "effectcraft-keyframe", "effectcraft-project", "effectcraft-time", + "log", "serde", "serde_json", "thiserror 2.0.21", @@ -1492,6 +1976,7 @@ dependencies = [ name = "effectcraft-automation" version = "0.24.1" dependencies = [ + "craft-mime", "effectcraft-engine", "effectcraft-host", "effectcraft-model", @@ -1534,6 +2019,7 @@ name = "effectcraft-effects" version = "0.24.1" dependencies = [ "chrono", + "craft-cms", "effectcraft-color", "effectcraft-geom", "effectcraft-keyframe", @@ -1590,22 +2076,19 @@ dependencies = [ name = "effectcraft-export" version = "0.24.1" dependencies = [ - "craft-audio", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4)", - "craft-video", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", + "craft-gif", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", + "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", "effectcraft-color", "effectcraft-effects", "effectcraft-keyframe", "effectcraft-media", - "effectcraft-opusenc", "effectcraft-project", "effectcraft-raster", "effectcraft-render", "effectcraft-time", "exr", - "filmcraft-av1", - "filmcraft-hevc", - "filmcraft-vp9", "gif", "image", "log", @@ -1678,6 +2161,7 @@ dependencies = [ name = "effectcraft-host" version = "0.24.1" dependencies = [ + "craft-vectorcraft-format", "effectcraft-engine", "effectcraft-export", "effectcraft-expr", @@ -1705,6 +2189,7 @@ dependencies = [ name = "effectcraft-interchange" version = "0.24.1" dependencies = [ + "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=0d6dd8bed815b8366869a800d2bf22588ca62dcb)", "effectcraft-color", "effectcraft-keyframe", "effectcraft-project", @@ -1737,6 +2222,7 @@ name = "effectcraft-lottie" version = "0.24.1" dependencies = [ "craft-docpath", + "craft-lottie", "effectcraft-color", "effectcraft-effects", "effectcraft-keyframe", @@ -1754,9 +2240,13 @@ dependencies = [ name = "effectcraft-media" version = "0.24.1" dependencies = [ - "craft-audio", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", "craft-docpath", - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4)", + "craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", + "craft-exr", + "craft-gif", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87)", + "craft-webp", "effectcraft-color", "effectcraft-effects", "effectcraft-model", @@ -1772,7 +2262,6 @@ dependencies = [ "filmcraft-color", "filmcraft-frame", "filmcraft-media", - "filmcraft-mpegts", "filmcraft-time", "gif", "image", @@ -1787,22 +2276,14 @@ dependencies = [ name = "effectcraft-model" version = "0.24.1" dependencies = [ + "craft-mesh", "effectcraft-geom", "image", "log", - "miniz_oxide 0.9.1", "serde", - "serde_json", "thiserror 2.0.21", ] -[[package]] -name = "effectcraft-opusenc" -version = "0.24.1" -dependencies = [ - "craft-audio", -] - [[package]] name = "effectcraft-path" version = "0.24.1" @@ -1812,6 +2293,7 @@ dependencies = [ "effectcraft-raster", "kurbo", "linesweeper", + "log", "tiny-skia 0.12.0", ] @@ -1819,14 +2301,19 @@ dependencies = [ name = "effectcraft-pdf" version = "0.24.1" dependencies = [ + "craft-doc", "craft-pdf", + "craft-ps", + "craft-vectorcraft-format", "effectcraft-raster", "effectcraft-svg", "effectcraft-text", + "flate2", "image", "kurbo", "miniz_oxide 0.9.1", - "skrifa", + "serde_json", + "skrifa 0.44.0", "wasm-bindgen-test", "zune-jpeg", ] @@ -1861,6 +2348,7 @@ dependencies = [ name = "effectcraft-psd" version = "0.24.1" dependencies = [ + "craft-psd", "miniz_oxide 0.9.1", ] @@ -1868,6 +2356,7 @@ dependencies = [ name = "effectcraft-raster" version = "0.24.1" dependencies = [ + "craft-exr", "effectcraft-color", "effectcraft-geom", "rayon", @@ -1943,6 +2432,7 @@ dependencies = [ name = "effectcraft-svg" version = "0.24.1" dependencies = [ + "craft-svg", "effectcraft-geom", "effectcraft-path", "effectcraft-raster", @@ -1959,7 +2449,7 @@ dependencies = [ "effectcraft-keyframe", "harfrust", "kurbo", - "skrifa", + "skrifa 0.44.0", "unicode-bidi", "unicode-linebreak", ] @@ -1976,6 +2466,7 @@ dependencies = [ name = "effectcraft-track" version = "0.24.1" dependencies = [ + "craft-mime", "effectcraft-raster", "effectcraft-segment", "rayon", @@ -1990,6 +2481,7 @@ version = "0.24.1" dependencies = [ "bytemuck", "chrono", + "craft-mime", "craft-quit", "craft-ui", "craft-update", @@ -2006,6 +2498,7 @@ dependencies = [ "effectcraft-segment", "effectcraft-text", "effectcraft-time", + "effectcraft-ui-egui", "eframe", "egui", "egui_extras", @@ -2093,7 +2586,7 @@ dependencies = [ "bitflags 2.13.2", "emath", "epaint", - "itertools", + "itertools 0.15.0", "log", "nohash-hasher", "profiling", @@ -2155,7 +2648,7 @@ dependencies = [ "ahash", "egui", "enum-map", - "itertools", + "itertools 0.15.0", "log", "profiling", ] @@ -2294,7 +2787,7 @@ dependencies = [ "parking_lot", "profiling", "self_cell", - "skrifa", + "skrifa 0.44.0", "smallvec", "unicode-bidi", "unicode-general-category", @@ -2445,129 +2938,70 @@ dependencies = [ "libc", ] -[[package]] -name = "filmcraft-aac" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" -dependencies = [ - "filmcraft-bitstream", - "thiserror 2.0.21", -] - -[[package]] -name = "filmcraft-ac3" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" -dependencies = [ - "thiserror 2.0.21", -] - -[[package]] -name = "filmcraft-apv" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" -dependencies = [ - "filmcraft-bitstream", - "rayon", - "thiserror 2.0.21", -] - -[[package]] -name = "filmcraft-av1" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" -dependencies = [ - "filmcraft-bitstream", - "rayon", - "thiserror 2.0.21", -] - -[[package]] -name = "filmcraft-avi" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" - [[package]] name = "filmcraft-bitstream" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" +version = "0.20.1" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0ad6c1e1d297908915f4be315b0fcfc9be7b5d4)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", ] [[package]] name = "filmcraft-cfb" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" +version = "0.20.1" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" +dependencies = [ + "craft-cfb 0.1.0 (git+https://github.com/storytold/craft-libs?rev=7f3fdc0dfebd03f33a241f91f916e9a78d3e5c93)", +] [[package]] name = "filmcraft-codecs" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" +version = "0.20.1" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ - "filmcraft-aac", - "filmcraft-ac3", - "filmcraft-apv", - "filmcraft-av1", - "filmcraft-avi", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", + "craft-jpeg", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", + "craft-video 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", + "craft-y4m", "filmcraft-bitstream", "filmcraft-color", - "filmcraft-dnx", "filmcraft-frame", - "filmcraft-h264", - "filmcraft-hevc", "filmcraft-isobmff", "filmcraft-matroska", "filmcraft-media", - "filmcraft-mpa", - "filmcraft-mpeg2v", - "filmcraft-mpegts", - "filmcraft-mxf", - "filmcraft-ogg", - "filmcraft-opus", - "filmcraft-prores", "filmcraft-time", - "filmcraft-vp8", - "filmcraft-vp9", - "image", "log", "rayon", - "symphonia", + "symphonia 0.5.5", "thiserror 2.0.21", "web-time", ] [[package]] name = "filmcraft-color" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" +version = "0.20.1" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "serde", ] [[package]] name = "filmcraft-dng" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" +version = "0.20.1" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ - "rayon", - "thiserror 2.0.21", -] - -[[package]] -name = "filmcraft-dnx" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" -dependencies = [ - "filmcraft-bitstream", + "craft-raw", + "craft-tiff", + "image", "rayon", "thiserror 2.0.21", ] [[package]] name = "filmcraft-frame" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" +version = "0.20.1" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "filmcraft-color", "filmcraft-time", @@ -2577,44 +3011,26 @@ dependencies = [ [[package]] name = "filmcraft-geom" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" +version = "0.20.1" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "serde", ] -[[package]] -name = "filmcraft-h264" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" -dependencies = [ - "filmcraft-bitstream", - "rayon", - "thiserror 2.0.21", -] - -[[package]] -name = "filmcraft-hevc" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" -dependencies = [ - "filmcraft-bitstream", - "rayon", - "thiserror 2.0.21", -] - [[package]] name = "filmcraft-interchange" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" +version = "0.20.1" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ + "craft-aaf", + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", + "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0)", "filmcraft-cfb", "filmcraft-color", "filmcraft-geom", "filmcraft-media", "filmcraft-project", "filmcraft-time", - "roxmltree", "serde", "serde_json", "thiserror 2.0.21", @@ -2622,25 +3038,29 @@ dependencies = [ [[package]] name = "filmcraft-isobmff" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" +version = "0.20.1" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0ad6c1e1d297908915f4be315b0fcfc9be7b5d4)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", ] [[package]] name = "filmcraft-matroska" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" +version = "0.20.1" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ - "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=f0ad6c1e1d297908915f4be315b0fcfc9be7b5d4)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", ] [[package]] name = "filmcraft-media" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" +version = "0.20.1" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ + "craft-audio 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", + "craft-dpx 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", + "craft-media 0.1.0 (git+https://github.com/storytold/craft-libs?rev=82062077bba679ba5236e2d1a391f02d1533cbab)", + "craft-tga", "filmcraft-color", "filmcraft-dng", "filmcraft-frame", @@ -2651,54 +3071,10 @@ dependencies = [ "thiserror 2.0.21", ] -[[package]] -name = "filmcraft-mpa" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" -dependencies = [ - "filmcraft-bitstream", - "thiserror 2.0.21", -] - -[[package]] -name = "filmcraft-mpeg2v" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" -dependencies = [ - "rayon", - "thiserror 2.0.21", -] - -[[package]] -name = "filmcraft-mpegts" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" -dependencies = [ - "thiserror 2.0.21", -] - -[[package]] -name = "filmcraft-mxf" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" -dependencies = [ - "chrono", -] - -[[package]] -name = "filmcraft-ogg" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" - -[[package]] -name = "filmcraft-opus" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" - [[package]] name = "filmcraft-project" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" +version = "0.20.1" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ "filmcraft-color", "filmcraft-geom", @@ -2707,42 +3083,15 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", -] - -[[package]] -name = "filmcraft-prores" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" -dependencies = [ - "filmcraft-bitstream", - "rayon", - "thiserror 2.0.21", + "url", ] [[package]] name = "filmcraft-time" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" +version = "0.20.1" +source = "git+https://github.com/storytold/filmcraft?rev=3f137a7ed420cac79b32145f5243b7f98b31f71c#3f137a7ed420cac79b32145f5243b7f98b31f71c" dependencies = [ - "serde", -] - -[[package]] -name = "filmcraft-vp8" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" -dependencies = [ - "thiserror 2.0.21", -] - -[[package]] -name = "filmcraft-vp9" -version = "0.12.0" -source = "git+https://github.com/storytold/filmcraft?rev=d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5#d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" -dependencies = [ - "filmcraft-bitstream", - "rayon", - "thiserror 2.0.21", + "craft-timeline 0.1.0 (git+https://github.com/storytold/craft-libs?rev=57288edafdc45552e30481cc649021de446abfa0)", ] [[package]] @@ -3141,7 +3490,7 @@ dependencies = [ "hashbrown 0.17.1", "log", "peniko", - "skrifa", + "skrifa 0.44.0", "smallvec", "vello_common", ] @@ -3270,7 +3619,7 @@ checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" dependencies = [ "bitflags 2.13.2", "bytemuck", - "read-fonts", + "read-fonts 0.41.0", "smallvec", ] @@ -3322,7 +3671,7 @@ checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" [[package]] name = "hayro-jbig2" version = "0.3.0" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae" dependencies = [ "hayro-ccitt", ] @@ -3336,7 +3685,7 @@ checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" [[package]] name = "hayro-syntax" version = "0.7.2" -source = "git+https://github.com/storytold/craft-libs?rev=e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4#e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" +source = "git+https://github.com/storytold/craft-libs?rev=808730f49b9637b7909fe2ae56f9d63fdb100cae#808730f49b9637b7909fe2ae56f9d63fdb100cae" dependencies = [ "hayro-jbig2", "hayro-jpeg2000", @@ -3618,12 +3967,32 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "interpolate_name" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "intrusive-collections" version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4275b20e6057cd7733fd8df8a5a31701e4fe44497dad0f3fa0e1c4fb971506be" +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.15.0" @@ -3808,6 +4177,16 @@ version = "0.2.189" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +[[package]] +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" +dependencies = [ + "arbitrary", + "cc", +] + [[package]] name = "libloading" version = "0.8.9" @@ -3922,6 +4301,26 @@ dependencies = [ "rawpointer", ] +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", + "rayon", +] + +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + [[package]] name = "memchr" version = "2.8.3" @@ -4094,6 +4493,12 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + [[package]] name = "nix" version = "0.31.3" @@ -4106,6 +4511,15 @@ dependencies = [ "libc", ] +[[package]] +name = "no_std_io2" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003" +dependencies = [ + "memchr", +] + [[package]] name = "nohash-hasher" version = "0.2.0" @@ -4121,6 +4535,12 @@ dependencies = [ "memchr", ] +[[package]] +name = "noop_proc_macro" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" + [[package]] name = "ntapi" version = "0.4.3" @@ -4139,6 +4559,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-bigint" version = "0.5.1" @@ -4186,6 +4616,17 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint 0.4.8", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -4655,7 +5096,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.61.2", + "windows-sys 0.45.0", ] [[package]] @@ -4693,12 +5134,30 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" +[[package]] +name = "pastey" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" + [[package]] name = "pastey" version = "0.2.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" +[[package]] +name = "pdf-writer" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5e456864a7a304047bff84977dc6fb162bd956475d40ba50b2dcecaada7f753" +dependencies = [ + "bitflags 2.13.2", + "itoa", + "memchr", + "ryu", +] + [[package]] name = "peniko" version = "0.6.1" @@ -4962,6 +5421,19 @@ name = "profiling" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +dependencies = [ + "profiling-procmacros", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb" +dependencies = [ + "quote", + "syn 2.0.119", +] [[package]] name = "proptest" @@ -5134,6 +5606,40 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" +[[package]] +name = "rav1e" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b" +dependencies = [ + "aligned-vec", + "arbitrary", + "arg_enum_proc_macro", + "arrayvec", + "av-scenechange", + "av1-grain", + "bitstream-io", + "built", + "cfg-if", + "interpolate_name", + "itertools 0.14.0", + "libc", + "libfuzzer-sys", + "log", + "maybe-rayon", + "new_debug_unreachable", + "noop_proc_macro", + "num-derive", + "num-traits", + "paste", + "profiling", + "rand 0.9.5", + "rand_chacha", + "simd_helpers", + "thiserror 2.0.21", + "v_frame", +] + [[package]] name = "raw-cpuid" version = "11.6.0" @@ -5198,6 +5704,17 @@ dependencies = [ "once_cell", ] +[[package]] +name = "read-fonts" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + [[package]] name = "reborrow" version = "0.5.5" @@ -5231,6 +5748,12 @@ dependencies = [ "bitflags 2.13.2", ] +[[package]] +name = "regex-lite" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" + [[package]] name = "regex-syntax" version = "0.8.11" @@ -5441,6 +5964,12 @@ dependencies = [ "wait-timeout", ] +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + [[package]] name = "ryu-js" version = "1.0.3" @@ -5656,6 +6185,15 @@ dependencies = [ "simdutf8", ] +[[package]] +name = "simd_helpers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" +dependencies = [ + "quote", +] + [[package]] name = "simdutf8" version = "0.1.5" @@ -5675,7 +6213,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" dependencies = [ "bytemuck", - "read-fonts", + "read-fonts 0.41.0", +] + +[[package]] +name = "skrifa" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "526e654b303ff4ad73a5a40b25de2b3ce3d039c5e3b6da5f89ae6e57004cb40f" +dependencies = [ + "bytemuck", + "read-fonts 0.44.0", ] [[package]] @@ -5881,17 +6429,40 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5773a4c030a19d9bfaa090f49746ff35c75dfddfa700df7a5939d5e076a57039" dependencies = [ "lazy_static", - "symphonia-bundle-flac", - "symphonia-bundle-mp3", - "symphonia-codec-aac", - "symphonia-codec-alac", - "symphonia-codec-pcm", - "symphonia-codec-vorbis", - "symphonia-core", - "symphonia-format-isomp4", - "symphonia-format-ogg", - "symphonia-format-riff", - "symphonia-metadata", + "symphonia-bundle-flac 0.5.5", + "symphonia-bundle-mp3 0.5.5", + "symphonia-codec-aac 0.5.5", + "symphonia-codec-alac 0.5.5", + "symphonia-codec-pcm 0.5.5", + "symphonia-codec-vorbis 0.5.5", + "symphonia-core 0.5.5", + "symphonia-format-isomp4 0.5.5", + "symphonia-format-ogg 0.5.5", + "symphonia-format-riff 0.5.5", + "symphonia-metadata 0.5.5", +] + +[[package]] +name = "symphonia" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7edef6a96b696d4e0cab5ee9ebb7ca155ed95f30a6b45bbb8b97d2727f02424" +dependencies = [ + "lazy_static", + "symphonia-bundle-flac 0.6.1", + "symphonia-bundle-mp3 0.6.1", + "symphonia-codec-aac 0.6.1", + "symphonia-codec-adpcm", + "symphonia-codec-alac 0.6.1", + "symphonia-codec-pcm 0.6.1", + "symphonia-codec-vorbis 0.6.1", + "symphonia-core 0.6.1", + "symphonia-format-caf", + "symphonia-format-isomp4 0.6.1", + "symphonia-format-mkv", + "symphonia-format-ogg 0.6.1", + "symphonia-format-riff 0.6.1", + "symphonia-metadata 0.6.1", ] [[package]] @@ -5901,11 +6472,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c91565e180aea25d9b80a910c546802526ffd0072d0b8974e3ebe59b686c9976" dependencies = [ "log", - "symphonia-core", - "symphonia-metadata", + "symphonia-core 0.5.5", + "symphonia-metadata 0.5.5", "symphonia-utils-xiph", ] +[[package]] +name = "symphonia-bundle-flac" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6405d5c34ff6f8f7ca08a4101efe66d21e180f7322ef9359900a0e55698a7892" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core 0.6.1", + "symphonia-metadata 0.6.1", +] + [[package]] name = "symphonia-bundle-mp3" version = "0.5.5" @@ -5914,8 +6497,19 @@ checksum = "4872dd6bb56bf5eac799e3e957aa1981086c3e613b27e0ac23b176054f7c57ed" dependencies = [ "lazy_static", "log", - "symphonia-core", - "symphonia-metadata", + "symphonia-core 0.5.5", + "symphonia-metadata 0.5.5", +] + +[[package]] +name = "symphonia-bundle-mp3" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98ea5ffc8716bff677dfb3b01b420c7b758de901a72b8c330bf2040ab74b4add" +dependencies = [ + "lazy_static", + "log", + "symphonia-core 0.6.1", ] [[package]] @@ -5926,7 +6520,29 @@ checksum = "4c263845aa86881416849c1729a54c7f55164f8b96111dba59de46849e73a790" dependencies = [ "lazy_static", "log", - "symphonia-core", + "symphonia-core 0.5.5", +] + +[[package]] +name = "symphonia-codec-aac" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5bf8e39552d34a3c4c98333370e62f48c92456d2e814f273b5c3ad7c4a5f45c" +dependencies = [ + "lazy_static", + "log", + "symphonia-common", + "symphonia-core 0.6.1", +] + +[[package]] +name = "symphonia-codec-adpcm" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "445932ecb0c59362fde9c082dd63a75380650c5077fdb8b80b8cac850442a74c" +dependencies = [ + "log", + "symphonia-core 0.6.1", ] [[package]] @@ -5936,7 +6552,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8413fa754942ac16a73634c9dfd1500ed5c61430956b33728567f667fdd393ab" dependencies = [ "log", - "symphonia-core", + "symphonia-core 0.5.5", +] + +[[package]] +name = "symphonia-codec-alac" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "920a78f96f3cf62932d0c497959c0cc2100ef36b03c7ca1417b260f432a482d8" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core 0.6.1", ] [[package]] @@ -5946,7 +6573,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e89d716c01541ad3ebe7c91ce4c8d38a7cf266a3f7b2f090b108fb0cb031d95" dependencies = [ "log", - "symphonia-core", + "symphonia-core 0.5.5", +] + +[[package]] +name = "symphonia-codec-pcm" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e04ba75686acbe43542fdd374571195f0530c0b7785ca25cc6840e9c6c4b6eea" +dependencies = [ + "log", + "symphonia-core 0.6.1", ] [[package]] @@ -5956,10 +6593,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f025837c309cd69ffef572750b4a2257b59552c5399a5e49707cc5b1b85d1c73" dependencies = [ "log", - "symphonia-core", + "symphonia-core 0.5.5", "symphonia-utils-xiph", ] +[[package]] +name = "symphonia-codec-vorbis" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73d90b4fcf796137cc683c538282804ff9629f8ad9dbfd881fcbba331ac4e986" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core 0.6.1", +] + +[[package]] +name = "symphonia-common" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acc3fcc18ec9b8cdd48614e259c4cf0d27b71d41e5d9b120b42c5adab12d7c4" +dependencies = [ + "log", + "symphonia-core 0.6.1", + "symphonia-metadata 0.6.1", +] + [[package]] name = "symphonia-core" version = "0.5.5" @@ -5973,6 +6632,31 @@ dependencies = [ "log", ] +[[package]] +name = "symphonia-core" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c412864d599d4750d0c3d684d7e093ec05e5309681ef5252cc1096a437f6e0" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "lazy_static", + "log", + "num-complex", + "smallvec", +] + +[[package]] +name = "symphonia-format-caf" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab64327ee1920531c5bf86cf7e9cd1a599d57013ddc30691da62683cefc65191" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core 0.6.1", +] + [[package]] name = "symphonia-format-isomp4" version = "0.5.5" @@ -5981,11 +6665,35 @@ checksum = "243739585d11f81daf8dac8d9f3d18cc7898f6c09a259675fc364b382c30e0a5" dependencies = [ "encoding_rs", "log", - "symphonia-core", - "symphonia-metadata", + "symphonia-core 0.5.5", + "symphonia-metadata 0.5.5", "symphonia-utils-xiph", ] +[[package]] +name = "symphonia-format-isomp4" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e681a70e1870d34e02abf1dbc51e4267c3f1827801474e8870be8c689fc4dc3" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core 0.6.1", + "symphonia-metadata 0.6.1", +] + +[[package]] +name = "symphonia-format-mkv" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d015c5c0558864665894b3f4cbd95e10abb01b9c868e751c72670f326a56360e" +dependencies = [ + "lazy_static", + "log", + "symphonia-common", + "symphonia-core 0.6.1", +] + [[package]] name = "symphonia-format-ogg" version = "0.5.5" @@ -5993,11 +6701,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b4955c67c1ed3aa8ae8428d04ca8397fbef6a19b2b051e73b5da8b1435639cb" dependencies = [ "log", - "symphonia-core", - "symphonia-metadata", + "symphonia-core 0.5.5", + "symphonia-metadata 0.5.5", "symphonia-utils-xiph", ] +[[package]] +name = "symphonia-format-ogg" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5495e7f7e3c7035328d82b6d6e377eef289bb0c4105bdeb557fc93a833f994" +dependencies = [ + "log", + "symphonia-common", + "symphonia-core 0.6.1", + "symphonia-metadata 0.6.1", +] + [[package]] name = "symphonia-format-riff" version = "0.5.5" @@ -6006,8 +6726,20 @@ checksum = "c2d7c3df0e7d94efb68401d81906eae73c02b40d5ec1a141962c592d0f11a96f" dependencies = [ "extended", "log", - "symphonia-core", - "symphonia-metadata", + "symphonia-core 0.5.5", + "symphonia-metadata 0.5.5", +] + +[[package]] +name = "symphonia-format-riff" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ff70929083a8c1a5f6cd7c904b6071c7914ad04739b510c2f7239dfc9b7dabe" +dependencies = [ + "extended", + "log", + "symphonia-core 0.6.1", + "symphonia-metadata 0.6.1", ] [[package]] @@ -6019,7 +6751,20 @@ dependencies = [ "encoding_rs", "lazy_static", "log", - "symphonia-core", + "symphonia-core 0.5.5", +] + +[[package]] +name = "symphonia-metadata" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83713a97705d77bdef7cdbc0768fd6e5a54e4cd7e48d60a806ae85639e2c87c6" +dependencies = [ + "lazy_static", + "log", + "regex-lite", + "smallvec", + "symphonia-core 0.6.1", ] [[package]] @@ -6028,8 +6773,8 @@ version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee27c85ab799a338446b68eec77abf42e1a6f1bb490656e121c6e27bfbab9f16" dependencies = [ - "symphonia-core", - "symphonia-metadata", + "symphonia-core 0.5.5", + "symphonia-metadata 0.5.5", ] [[package]] @@ -6583,6 +7328,38 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "v_frame" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2" +dependencies = [ + "aligned-vec", + "num-traits", + "wasm-bindgen", +] + +[[package]] +name = "vectorcraft-geom" +version = "0.18.0" +source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e" +dependencies = [ + "kurbo", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "vectorcraft-pathops" +version = "0.18.0" +source = "git+https://github.com/storytold/vectorcraft.git?rev=6b3a6b8788ebcb420d69449199cbdf323888d27e#6b3a6b8788ebcb420d69449199cbdf323888d27e" +dependencies = [ + "kurbo", + "linesweeper", + "thiserror 2.0.21", + "vectorcraft-geom", +] + [[package]] name = "vello_common" version = "0.2.0" @@ -7843,6 +8620,12 @@ dependencies = [ "tempfile", ] +[[package]] +name = "y4m" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" + [[package]] name = "yoke" version = "0.8.3" diff --git a/Cargo.toml b/Cargo.toml index c812a3294..54158cd1c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,12 +11,26 @@ rust-version = "1.95" repository = "https://github.com/storytold/effectcraft" [workspace.dependencies] -craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", version = "=0.1.0", default-features = false, features = ["read"] } -craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" } -craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" } -craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4" } +craft-timeline = { git = "https://github.com/storytold/craft-libs", rev = "0d6dd8bed815b8366869a800d2bf22588ca62dcb", default-features = false } +craft-mime = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } +craft-pdf = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.1.0", default-features = false, features = ["read"] } +craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } +craft-quit = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } +craft-ecproj-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } +craft-dpx = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } +craft-ps = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", default-features = false, features = ["read"] } +craft-exr = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } +craft-gif = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } +craft-psd = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "ce2ec507c2e6a6a078a5f450f641487f8931816d" } +craft-svg = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e52cd9a889adbeeda447c75a546133960cf3382d" } +craft-webp = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } +craft-lottie = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } +craft-mesh = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", default-features = false, features = ["stl", "obj", "gltf", "fbx"] } +craft-aep = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } +craft-doc = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } +craft-vectorcraft-format = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87" } # craft-update: app-specific pretend versions apply to startup and manual checks. -craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", features = ["egui"] } +craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", features = ["egui"] } # internal effectcraft-time = { path = "crates/time" } effectcraft-geom = { path = "crates/geom" } @@ -46,7 +60,6 @@ effectcraft-engine = { path = "crates/engine" } effectcraft-host = { path = "crates/host" } effectcraft-ui-egui = { path = "crates/ui-egui" } effectcraft-automation = { path = "crates/automation" } -effectcraft-opusenc = { path = "crates/opusenc" } effectcraft-script = { path = "crates/script" } effectcraft-plugin = { path = "crates/plugin" } effectcraft-helper-host = { path = "crates/helper-host" } @@ -80,28 +93,21 @@ same-file = "1.0" tempfile = "3.27" # codecs + containers shared by the Craft apps (crates/media, crates/export); keep all three on one rev. -craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", default-features = false, features = ["isobmff", "matroska"] } -craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", default-features = false, features = ["aac-decode", "aac-encode", "opus-decode"] } -craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", features = ["h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] } +craft-media = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", default-features = false, features = ["isobmff", "matroska"] } +craft-audio = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", default-features = false, features = ["aac-decode", "aac-encode", "opus-decode", "opus-encode"] } +craft-video = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", features = ["h264-encode", "prores", "hevc-encode", "vp9-encode", "av1", "threads"] } # footage decoding: FilmCraft's pure-Rust crates, pinned to a revision (plan/adr/0001). # Only `crates/media`, `crates/export` and `crates/interchange` may depend on these. -filmcraft-codecs = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } -filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } -filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } -filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } -filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } -# MPEG TS / PS headers read for AAC channel layouts (crates/media); craft-media has no MPEG TS reader -filmcraft-mpegts = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } -# decoders used as the round-trip oracles of craft-video's VP9, HEVC and AV1 encoders (crates/export -# dev-dependencies only); craft-video has no decoder for them -filmcraft-vp9 = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } -filmcraft-hevc = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } -filmcraft-av1 = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } +filmcraft-codecs = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" } +filmcraft-media = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" } +filmcraft-frame = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" } +filmcraft-color = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" } +filmcraft-time = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" } # timeline interchange (EDL, FCP7 XML, FCPXML, OTIO) for Premiere Pro interop (crates/interchange only) -filmcraft-interchange = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } -filmcraft-project = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } -filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "d5ead4ba1ee2f1cd13cb86a4239aee2730a3d9f5" } +filmcraft-interchange = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" } +filmcraft-project = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" } +filmcraft-geom = { git = "https://github.com/storytold/filmcraft", rev = "3f137a7ed420cac79b32145f5243b7f98b31f71c" } # gpu (the same wgpu eframe / egui-wgpu use) wgpu = { version = "30.0.1", features = ["fragile-send-sync-non-atomic-wasm"] } @@ -112,7 +118,7 @@ half = "2.7" # ui # Shared frontend components; keep this dependency above the engine boundary. # Shared UI and the complete egui family select reviewed immutable commits below. -craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", features = ["serde"] } +craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "5a7a63a21dd03dd1a2bc6c308a3a6ce818caae87", features = ["serde"] } # `default_fonts` and `monochrome_emoji_fonts` are explicit: the app's `FontDefinitions::default()` # and its `✔`/`▣` chrome glyphs need both, and kittest's own dev-dependencies do not propagate. egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] } @@ -132,7 +138,6 @@ sys-locale = "0.3" # filmcraft-frame = { path = "../filmcraft/crates/frame" } # filmcraft-color = { path = "../filmcraft/crates/color" } # filmcraft-time = { path = "../filmcraft/crates/time" } -# filmcraft-mpegts = { path = "../filmcraft/crates/mpegts" } [workspace.lints.rust] unsafe_code = "forbid" @@ -184,9 +189,6 @@ opt-level = 3 [profile.dev.package.effectcraft-media] opt-level = 3 -[profile.dev.package.effectcraft-opusenc] -opt-level = 3 - [profile.dev.package.effectcraft-export] opt-level = 3 @@ -221,8 +223,8 @@ lto = "thin" codegen-units = 1 [patch.crates-io] -hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", version = "=0.7.2" } -hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4", version = "=0.3.0" } +hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.7.2" } +hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "808730f49b9637b7909fe2ae56f9d63fdb100cae", version = "=0.3.0" } ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } emath = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } epaint = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/LICENSE-APACHE b/LICENSE-APACHE index f433b1a53..ade750b16 100644 --- a/LICENSE-APACHE +++ b/LICENSE-APACHE @@ -1,177 +1,177 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/LICENSE-MIT b/LICENSE-MIT index 633fe3051..86fac3264 100644 --- a/LICENSE-MIT +++ b/LICENSE-MIT @@ -1,21 +1,21 @@ -MIT License - -Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. +MIT License + +Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/NOTICE b/NOTICE index 4a79e69fd..efb0eb7cd 100644 --- a/NOTICE +++ b/NOTICE @@ -1,322 +1,322 @@ -EffectCraft -Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors. -Licensed under the MIT License or the Apache License, Version 2.0, at your option -(LICENSE-MIT, LICENSE-APACHE). - -The ArtCraft name, wordmark and logos in docs/brand/ are trademarks of the ArtCraft Team. They are -not open source and are not covered by the license above; their terms are in -docs/brand/LICENSE-brand.txt. - -Third-party material - -This product bundles third-party material under its own licenses, listed below. The per-file -list (author, source, license) is in ATTRIBUTION.md. - -Bundled fonts - -EffectCraft embeds Inter, Noto Serif, JetBrains Mono and Noto Sans Symbols 2 from -assets/fonts/. The pinned egui dependency (epaint_default_fonts, revision -6d518fc799681571963842f95b55a6b68431b15a) additionally embeds Ubuntu Light, Hack, -Noto Emoji, egui-icons and emoji-icon-font through EffectCraft's enabled `default_fonts` -and `monochrome_emoji_fonts` features; no font file from that dependency is added to -this repository. The complete copyright notices and licence texts required for all of -these fonts follow. - -The optional PDF document reader uses craft-pdf and Hayro-syntax 0.7.2, MIT OR Apache-2.0. -The shared patched syntax source is centralized in storytold/craft-libs, transferred from -PdfCraft revision 9ed3abe4907a127d36b12fbfeee71d7e26248da1. This parser-only use embeds no -Hayro fonts, CMaps or image codecs; EffectCraft keeps its existing fonts and drawing filters. - -Linux Wayland window decorations -------------------------------- -sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita, -commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux -for vector window controls. Its title-font features are disabled: no Cantarell -font is embedded by this dependency and no font file is added to this repo. - -sctk-adwaita's MIT licence: - -MIT License - -Copyright (c) 2022 Bartłomiej Maryńczak - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - -SIL Open Font License 1.1 - -Applies to Inter (assets/fonts/Inter-*.ttf), Noto Serif (assets/fonts/NotoSerif-Regular.ttf), -JetBrains Mono (assets/fonts/JetBrainsMono-Regular.ttf), Noto Sans Symbols 2 -(assets/fonts/NotoSansSymbols2-Regular.ttf) and Noto Emoji (NotoEmoji-Regular.ttf). -Copyright notices: - -Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter) -Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic) -Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) -Copyright 2022 The Noto Project Authors (https://github.com/notofonts/symbols) -Copyright 2013 Google Inc. All Rights Reserved. - -The fonts in assets/fonts/ also keep their upstream licence files at -assets/fonts/OFL-.txt. The complete licence text follows. - -This Font Software is licensed under the SIL Open Font License, -Version 1.1. - -This license is copied below, and is also available with a FAQ at: -http://scripts.sil.org/OFL - ------------------------------------------------------------ -SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ------------------------------------------------------------ - -PREAMBLE -The goals of the Open Font License (OFL) are to stimulate worldwide -development of collaborative font projects, to support the font -creation efforts of academic and linguistic communities, and to -provide a free and open framework in which fonts may be shared and -improved in partnership with others. - -The OFL allows the licensed fonts to be used, studied, modified and -redistributed freely as long as they are not sold by themselves. The -fonts, including any derivative works, can be bundled, embedded, -redistributed and/or sold with any software provided that any reserved -names are not used by derivative works. The fonts and derivatives, -however, cannot be released under any other type of license. The -requirement for fonts to remain under this license does not apply to -any document created using the fonts or their derivatives. - -DEFINITIONS -"Font Software" refers to the set of files released by the Copyright -Holder(s) under this license and clearly marked as such. This may -include source files, build scripts and documentation. - -"Reserved Font Name" refers to any names specified as such after the -copyright statement(s). - -"Original Version" refers to the collection of Font Software -components as distributed by the Copyright Holder(s). - -"Modified Version" refers to any derivative made by adding to, -deleting, or substituting -- in part or in whole -- any of the -components of the Original Version, by changing formats or by porting -the Font Software to a new environment. - -"Author" refers to any designer, engineer, programmer, technical -writer or other person who contributed to the Font Software. - -PERMISSION & CONDITIONS -Permission is hereby granted, free of charge, to any person obtaining -a copy of the Font Software, to use, study, copy, merge, embed, -modify, redistribute, and sell modified and unmodified copies of the -Font Software, subject to the following conditions: - -1) Neither the Font Software nor any of its individual components, in -Original or Modified Versions, may be sold by itself. - -2) Original or Modified Versions of the Font Software may be bundled, -redistributed and/or sold with any software, provided that each copy -contains the above copyright notice and this license. These can be -included either as stand-alone text files, human-readable headers or -in the appropriate machine-readable metadata fields within text or -binary files as long as those fields can be easily viewed by the user. - -3) No Modified Version of the Font Software may use the Reserved Font -Name(s) unless explicit written permission is granted by the -corresponding Copyright Holder. This restriction only applies to the -primary font name as presented to the users. - -4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font -Software shall not be used to promote, endorse or advertise any -Modified Version, except to acknowledge the contribution(s) of the -Copyright Holder(s) and the Author(s) or with their explicit written -permission. - -5) The Font Software, modified or unmodified, in part or in whole, -must be distributed entirely under this license, and must not be -distributed under any other license. The requirement for fonts to -remain under this license does not apply to any document created using -the Font Software. - -TERMINATION -This license becomes null and void if any of the above conditions are -not met. - -DISCLAIMER -THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT -OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE -COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL -DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM -OTHER DEALINGS IN THE FONT SOFTWARE. - -Ubuntu Font Licence 1.0 - -Applies to Ubuntu Light (Ubuntu-Light.ttf). Copyright notice: - -Copyright 2011 Canonical Ltd. Licensed under the Ubuntu Font Licence 1.0 - -------------------------------- -UBUNTU FONT LICENCE Version 1.0 -------------------------------- - -PREAMBLE -This licence allows the licensed fonts to be used, studied, modified and -redistributed freely. The fonts, including any derivative works, can be -bundled, embedded, and redistributed provided the terms of this licence -are met. The fonts and derivatives, however, cannot be released under -any other licence. The requirement for fonts to remain under this -licence does not require any document created using the fonts or their -derivatives to be published under this licence, as long as the primary -purpose of the document is not to be a vehicle for the distribution of -the fonts. - -DEFINITIONS -"Font Software" refers to the set of files released by the Copyright -Holder(s) under this licence and clearly marked as such. This may -include source files, build scripts and documentation. - -"Original Version" refers to the collection of Font Software components -as received under this licence. - -"Modified Version" refers to any derivative made by adding to, deleting, -or substituting -- in part or in whole -- any of the components of the -Original Version, by changing formats or by porting the Font Software to -a new environment. - -"Copyright Holder(s)" refers to all individuals and companies who have a -copyright ownership of the Font Software. - -"Substantially Changed" refers to Modified Versions which can be easily -identified as dissimilar to the Font Software by users of the Font -Software comparing the Original Version with the Modified Version. - -To "Propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification and with or without charging -a redistribution fee), making available to the public, and in some -countries other activities as well. - -PERMISSION & CONDITIONS -This licence does not grant any rights under trademark law and all such -rights are reserved. - -Permission is hereby granted, free of charge, to any person obtaining a -copy of the Font Software, to propagate the Font Software, subject to -the below conditions: - -1) Each copy of the Font Software must contain the above copyright -notice and this licence. These can be included either as stand-alone -text files, human-readable headers or in the appropriate machine- -readable metadata fields within text or binary files as long as those -fields can be easily viewed by the user. - -2) The font name complies with the following: -(a) The Original Version must retain its name, unmodified. -(b) Modified Versions which are Substantially Changed must be renamed to -avoid use of the name of the Original Version or similar names entirely. -(c) Modified Versions which are not Substantially Changed must be -renamed to both (i) retain the name of the Original Version and (ii) add -additional naming elements to distinguish the Modified Version from the -Original Version. The name of such Modified Versions must be the name of -the Original Version, with "derivative X" where X represents the name of -the new work, appended to that name. - -3) The name(s) of the Copyright Holder(s) and any contributor to the -Font Software shall not be used to promote, endorse or advertise any -Modified Version, except (i) as required by this licence, (ii) to -acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with -their explicit written permission. - -4) The Font Software, modified or unmodified, in part or in whole, must -be distributed entirely under this licence, and must not be distributed -under any other licence. The requirement for fonts to remain under this -licence does not affect any document created using the Font Software, -except any version of the Font Software extracted from a document -created using the Font Software may only be distributed under this -licence. - -TERMINATION -This licence becomes null and void if any of the above conditions are -not met. - -DISCLAIMER -THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF -COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE -COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL -DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER -DEALINGS IN THE FONT SOFTWARE. - -Hack: MIT License and Bitstream Vera License - -Applies to Hack (Hack-Regular.ttf). Upstream notice and both licence texts: - -The work in the Hack project is Copyright 2018 Source Foundry Authors and licensed under the MIT License - -The work in the DejaVu project was committed to the public domain. - -Bitstream Vera Sans Mono Copyright 2003 Bitstream Inc. and licensed under the Bitstream Vera License with Reserved Font Names "Bitstream" and "Vera" -MIT License - -Copyright (c) 2018 Source Foundry Authors - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -BITSTREAM VERA LICENSE - -Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc. - -Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and associated documentation files (the "Font Software"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions: - -The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font Software typefaces. - -The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either the words "Bitstream" or the word "Vera". - -This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the "Bitstream Vera" names. - -The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself. - -THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. - -Except as contained in this notice, the names of Gnome, the Gnome Foundation, and Bitstream Inc., shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from the Gnome Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org. - -MIT License (egui-icons and emoji-icon-font) - -Applies to egui-icons.ttf, a five-glyph subset of emoji-icon-font, and the parent -emoji-icon-font.ttf, both by John Slegers, https://github.com/jslegers/emoji-icon-font. - -MIT License - -Copyright (c) 2014 John Slegers - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +EffectCraft +Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors. +Licensed under the MIT License or the Apache License, Version 2.0, at your option +(LICENSE-MIT, LICENSE-APACHE). + +The ArtCraft name, wordmark and logos in docs/brand/ are trademarks of the ArtCraft Team. They are +not open source and are not covered by the license above; their terms are in +docs/brand/LICENSE-brand.txt. + +Third-party material + +This product bundles third-party material under its own licenses, listed below. The per-file +list (author, source, license) is in ATTRIBUTION.md. + +Bundled fonts + +EffectCraft embeds Inter, Noto Serif, JetBrains Mono and Noto Sans Symbols 2 from +assets/fonts/. The pinned egui dependency (epaint_default_fonts, revision +6d518fc799681571963842f95b55a6b68431b15a) additionally embeds Ubuntu Light, Hack, +Noto Emoji, egui-icons and emoji-icon-font through EffectCraft's enabled `default_fonts` +and `monochrome_emoji_fonts` features; no font file from that dependency is added to +this repository. The complete copyright notices and licence texts required for all of +these fonts follow. + +The optional PDF document reader uses craft-pdf and Hayro-syntax 0.7.2, MIT OR Apache-2.0. +The shared patched syntax source is centralized in storytold/craft-libs, transferred from +PdfCraft revision 9ed3abe4907a127d36b12fbfeee71d7e26248da1. This parser-only use embeds no +Hayro fonts, CMaps or image codecs; EffectCraft keeps its existing fonts and drawing filters. + +Linux Wayland window decorations +------------------------------- +sctk-adwaita 0.10.1 (https://github.com/PolyMeilex/sctk-adwaita, +commit d5f343c45c04d4a026db57f76760819b7325db00) is used by winit on Linux +for vector window controls. Its title-font features are disabled: no Cantarell +font is embedded by this dependency and no font file is added to this repo. + +sctk-adwaita's MIT licence: + +MIT License + +Copyright (c) 2022 Bartłomiej Maryńczak + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + +SIL Open Font License 1.1 + +Applies to Inter (assets/fonts/Inter-*.ttf), Noto Serif (assets/fonts/NotoSerif-Regular.ttf), +JetBrains Mono (assets/fonts/JetBrainsMono-Regular.ttf), Noto Sans Symbols 2 +(assets/fonts/NotoSansSymbols2-Regular.ttf) and Noto Emoji (NotoEmoji-Regular.ttf). +Copyright notices: + +Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter) +Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic) +Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono) +Copyright 2022 The Noto Project Authors (https://github.com/notofonts/symbols) +Copyright 2013 Google Inc. All Rights Reserved. + +The fonts in assets/fonts/ also keep their upstream licence files at +assets/fonts/OFL-.txt. The complete licence text follows. + +This Font Software is licensed under the SIL Open Font License, +Version 1.1. + +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font +creation efforts of academic and linguistic communities, and to +provide a free and open framework in which fonts may be shared and +improved in partnership with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply to +any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software +components as distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, +deleting, or substituting -- in part or in whole -- any of the +components of the Original Version, by changing formats or by porting +the Font Software to a new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, +modify, redistribute, and sell modified and unmodified copies of the +Font Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, in +Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the +corresponding Copyright Holder. This restriction only applies to the +primary font name as presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created using +the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. + +Ubuntu Font Licence 1.0 + +Applies to Ubuntu Light (Ubuntu-Light.ttf). Copyright notice: + +Copyright 2011 Canonical Ltd. Licensed under the Ubuntu Font Licence 1.0 + +------------------------------- +UBUNTU FONT LICENCE Version 1.0 +------------------------------- + +PREAMBLE +This licence allows the licensed fonts to be used, studied, modified and +redistributed freely. The fonts, including any derivative works, can be +bundled, embedded, and redistributed provided the terms of this licence +are met. The fonts and derivatives, however, cannot be released under +any other licence. The requirement for fonts to remain under this +licence does not require any document created using the fonts or their +derivatives to be published under this licence, as long as the primary +purpose of the document is not to be a vehicle for the distribution of +the fonts. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this licence and clearly marked as such. This may +include source files, build scripts and documentation. + +"Original Version" refers to the collection of Font Software components +as received under this licence. + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to +a new environment. + +"Copyright Holder(s)" refers to all individuals and companies who have a +copyright ownership of the Font Software. + +"Substantially Changed" refers to Modified Versions which can be easily +identified as dissimilar to the Font Software by users of the Font +Software comparing the Original Version with the Modified Version. + +To "Propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification and with or without charging +a redistribution fee), making available to the public, and in some +countries other activities as well. + +PERMISSION & CONDITIONS +This licence does not grant any rights under trademark law and all such +rights are reserved. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of the Font Software, to propagate the Font Software, subject to +the below conditions: + +1) Each copy of the Font Software must contain the above copyright +notice and this licence. These can be included either as stand-alone +text files, human-readable headers or in the appropriate machine- +readable metadata fields within text or binary files as long as those +fields can be easily viewed by the user. + +2) The font name complies with the following: +(a) The Original Version must retain its name, unmodified. +(b) Modified Versions which are Substantially Changed must be renamed to +avoid use of the name of the Original Version or similar names entirely. +(c) Modified Versions which are not Substantially Changed must be +renamed to both (i) retain the name of the Original Version and (ii) add +additional naming elements to distinguish the Modified Version from the +Original Version. The name of such Modified Versions must be the name of +the Original Version, with "derivative X" where X represents the name of +the new work, appended to that name. + +3) The name(s) of the Copyright Holder(s) and any contributor to the +Font Software shall not be used to promote, endorse or advertise any +Modified Version, except (i) as required by this licence, (ii) to +acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with +their explicit written permission. + +4) The Font Software, modified or unmodified, in part or in whole, must +be distributed entirely under this licence, and must not be distributed +under any other licence. The requirement for fonts to remain under this +licence does not affect any document created using the Font Software, +except any version of the Font Software extracted from a document +created using the Font Software may only be distributed under this +licence. + +TERMINATION +This licence becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF +COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER +DEALINGS IN THE FONT SOFTWARE. + +Hack: MIT License and Bitstream Vera License + +Applies to Hack (Hack-Regular.ttf). Upstream notice and both licence texts: + +The work in the Hack project is Copyright 2018 Source Foundry Authors and licensed under the MIT License + +The work in the DejaVu project was committed to the public domain. + +Bitstream Vera Sans Mono Copyright 2003 Bitstream Inc. and licensed under the Bitstream Vera License with Reserved Font Names "Bitstream" and "Vera" +MIT License + +Copyright (c) 2018 Source Foundry Authors + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +BITSTREAM VERA LICENSE + +Copyright (c) 2003 by Bitstream, Inc. All Rights Reserved. Bitstream Vera is a trademark of Bitstream, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy of the fonts accompanying this license ("Fonts") and associated documentation files (the "Font Software"), to reproduce and distribute the Font Software, including without limitation the rights to use, copy, merge, publish, distribute, and/or sell copies of the Font Software, and to permit persons to whom the Font Software is furnished to do so, subject to the following conditions: + +The above copyright and trademark notices and this permission notice shall be included in all copies of one or more of the Font Software typefaces. + +The Font Software may be modified, altered, or added to, and in particular the designs of glyphs or characters in the Fonts may be modified and additional glyphs or characters may be added to the Fonts, only if the fonts are renamed to names not containing either the words "Bitstream" or the word "Vera". + +This License becomes null and void to the extent applicable to Fonts or Font Software that has been modified and is distributed under the "Bitstream Vera" names. + +The Font Software may be sold as part of a larger software package but no copy of one or more of the Font Software typefaces may be sold by itself. + +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL BITSTREAM OR THE GNOME FOUNDATION BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER DEALINGS IN THE FONT SOFTWARE. + +Except as contained in this notice, the names of Gnome, the Gnome Foundation, and Bitstream Inc., shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Font Software without prior written authorization from the Gnome Foundation or Bitstream Inc., respectively. For further information, contact: fonts at gnome dot org. + +MIT License (egui-icons and emoji-icon-font) + +Applies to egui-icons.ttf, a five-glyph subset of emoji-icon-font, and the parent +emoji-icon-font.ttf, both by John Slegers, https://github.com/jslegers/emoji-icon-font. + +MIT License + +Copyright (c) 2014 John Slegers + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md index 57eddebdc..6aa5e5ce4 100644 --- a/README.md +++ b/README.md @@ -1,399 +1,399 @@ -

- - - - ArtCraft - - -

- - -

- EffectCraft icon: an engraved unicorn on a pink tile -

- -

EffectCraft

- -

- Motion graphics and visual effects; an open-source, professional motion graphics and visual effects studio, built in pure Rust. -

- -

- A free, open-source compositor: compositions, layers, - keyframes, 308 effects, layer styles, expressions, 3D cameras and lights, and a render queue, native on macOS, - Windows and Linux, and in the browser. Young, moving fast, and already usable. -

- -

- Status: young and moving fast - Written in Rust - License: MIT OR Apache-2.0 -
- Scanned by SonarCloud - Reviewed by CodeRabbit -

- -

- Join the ArtCraft community on Discord -

- -

- EffectCraft on getartcraft.com · - ArtCraft · - All Crafting Apps -

- -
- -

- EffectCraft's main window: the animated demo composition in the Composition panel, the Project panel, a Timeline with text, shape and solid layers, and the Properties panel showing the selected text layer's transform, font and paragraph settings -

- -> [!NOTE] -> **ArtCraft is a community of artists from all walks of life.** Digital, generative, music, -> games — if you make things, you're one of us. **[Come say hi on Discord](https://discord.gg/artcraft).** - -

- What it is · - Animate · - Effects · - 3D · - Export · - Agents · - Get started · - Status · - How it's made · - Downloads · - The Crafting Apps · - License -

- -## What EffectCraft is - -EffectCraft is for animated titles, motion graphics and compositing work: the kind of thing -motion designers and VFX artists need. You build a composition out of layers (solids, shapes, -text, footage, other compositions), animate their properties with keyframes, stack effects on -them and render the result. - -The interface feels natural and responsive, with dedicated panels (Project, Composition, Timeline, -Layer, Footage, Effect Controls, Tools, Preview, Effects & Presets, Audio, Info, Paragraph, -Character, Align, Progress, Render Queue) and standard motion graphics shortcuts, going further in -a few places where it matters to us: - -- **Lottie import and export built in**, so animations can go straight to the web and apps - without a plugin. -- **A project file you can read.** Projects are versioned JSON (`.ecproj`), so they diff cleanly - in version control. -- **Everything is scriptable.** Menu actions, timeline edits and property changes are exposed as - commands. Engine commands are available through the CLI, JSON control channel and MCP; - UI-only commands use the frontend dispatcher and can be invoked through the control channel - or an attached MCP bridge. -- **No FFmpeg.** Video and audio decoding and encoding are pure Rust: FilmCraft's codecs and - EffectCraft's own VP9, AV1, HEVC and Opus encoders. - -## Animate - -The panels, menus and shortcuts follow standard motion design conventions: -Project, Composition, Timeline, Effect Controls, Properties, Effects & Presets, Character, -Paragraph, Align, Info, Preview, Audio and the Render Queue, docked the way you expect. Drag -footage, comps and effects between them: onto the comp viewer, where they land under the pointer, -or into the Timeline, between layers and at the time you point to. - -- **Layers of every kind:** solids, shapes, text, footage, nested compositions, nulls, - adjustment layers, cameras and lights; parenting, track mattes, all 38 blend modes, motion blur. -- **Keyframes that behave the same:** linear, Bezier, hold, auto and continuous Bezier, roving - keys, Easy Ease (F9), Keyframe Velocity and Interpolation dialogs, copy and paste at the current - time, and a **Graph Editor** with value and speed graphs and draggable handles. -- **Time:** time remapping, time stretch, time-reverse, freeze frame, work area, markers, exact - frame-accurate timing at every frame rate including 29.97 drop-frame. -- **Shapes and masks:** shape layers with trim paths, repeaters, round corners, offset, zig zag, - twist, wiggle, merge paths and gradient strokes; masks drawn with the pen tool, with modes, - feather, expansion and vertex editing in the viewer. -- **Text:** point and paragraph text with real shaping in any font installed on your machine, the - Character and Paragraph panels, and text animators with range selectors. -- **Expressions:** JavaScript with the standard motion expressions model (`wiggle`, `loopOut`, - `thisComp.layer("…")`, vector maths on arrays), an inline editor and the pick-whip. -- **Timeline like you know it:** twirl layers open to Transform, masks, effects and the rest; drag - rows to reorder layers; rename with Enter or a double-click; the property shortcuts (A, P, S, - R, T, M, F, E, L, U and their double presses AA, PP, SS, RR, TT, MM, FF, EE, LL, UU), Shift to - add properties, Alt+Shift+A/P/S/R/T to key the current time, Ctrl+` to twirl selected layers. -- **Puppet tools:** Position, Advanced, Bend, Starch and Overlap pins on a mesh built from the - layer, real-time pin recording, rotate/scale handles, pins driven by (or carrying) nulls for - rigging, and follow-through for hair and cloth. - -

- The Graph Editor showing an eased value curve for a text animator's Range Start, with the graph editor's button bar for hold, linear, auto Bezier and Easy Ease -

- -## Effects - -308 built-in effects across its categories, each with its parameter names, order and -defaults: blur and sharpen, channel, color correction (Curves, Levels, Hue/Saturation, a full -color-grading panel…), distort (Warp, Bulge, Turbulent Displace, Perspective Pin…), generate (Fractal Noise, -Gradient Ramp, Stroke, Write-on, Audio Spectrum…), keying, matte, noise and grain, perspective, -**simulation** (Particle Emitter 3D, Rainfall, Shatter, Card Dance, Caustics, Wave World…), -stylize (Glow, Glass Relief…), **time** (Echo, Posterize Time, Timewarp, Time Displacement…), -**audio** (Reverb, Parametric EQ, Delay, Stereo Mixer…), text, transitions, utility and expression -controls. All nine **Layer Styles** (Drop Shadow, Inner/Outer Glow, Bevel and Emboss, Satin, -overlays, Stroke) with Global Light. Preview plays audio in sync, with meters and waveforms. - -## 3D - -Classic 3D compositing: 3D layers with orientation and material options, -one- and two-node **cameras** with depth of field, **lights** (parallel, spot, point, ambient) -with soft ray-traced shadows, layers that intersect correctly, orbit, pan and dolly camera -tools, and Front, Top, Left and Custom views. - -

- The 3D Showcase demo in Custom View 1: intersecting cards lit by a spot light with soft shadows on a gridded floor, with the camera frustum and light drawn as wireframes -

- -## Export - -A dedicated Render Queue, with Render Settings and Output Modules: **H.264** MP4 and -**ProRes** MOV (Proxy to 4444 XQ with alpha) with audio, **HEVC** (Main / Main 10) and **AV1** -MP4, **WebM** (VP9 with inter frames and alpha, or AV1; Opus audio), PNG, JPEG, TIFF, Targa and 32-bit EXR sequences, animated GIF and WAV/AIFF. Field -rendering with 3:2 pulldown, effect/solo/guide/depth overrides, crop, region of interest and -resize, Render Settings and Output Module templates with defaults, post-render actions, storage -overflow and render logs. The same queue runs from the command line. Every encoder is pure -Rust (craft-libs' H.264, ProRes, HEVC, VP9, AV1 and AAC; EffectCraft's own Opus); there is no -FFmpeg inside. - -**Lottie** goes both ways: File ▸ Export ▸ Lottie JSON… writes a composition (precomps, shape, -solid, image, text and null layers, eased and spatial keyframes, masks, track mattes, blend -modes, time remapping, optionally expressions) as `.json` or `.lottie`, and lists anything Lottie -cannot express; File ▸ Import ▸ Lottie… opens one as a new composition. - -

- The Render Queue panel with two compositions queued -

- -## Built for agents - -Engine commands are available through the CLI, JSON control channel and MCP. UI-only commands -need the running app's frontend dispatcher: complete menu access requires the app's control -channel or an attached MCP bridge. Headless MCP sessions expose supported engine commands, -but not UI-only commands or bridge-only `ui_*` tools. - -- **MCP server:** `effectcraft-cli mcp` speaks the Model Context Protocol over stdio, headless - or bridged to the running app (`--bridge 9877`). Tools cover commands, the project and property - tree, keyframes and rendered frames. This repository ships a ready [`.mcp.json`](.mcp.json). -- **Command line:** one-shot calls with JSON output, for example - `effectcraft-cli set Main '#1' transform/position '[100,360]' --time 0 main.ecproj --save` - or `effectcraft-cli render --comp Main --out main.mp4`, or - `effectcraft-cli exec file.exportLottie '{"comp":"Main","path":"main.json"}' main.ecproj`. -- **Control channel:** `effectcraft --control 9877` accepts JSON lines to run commands, inspect - and click any widget by its automation id, and take screenshots. - -See [docs/agents.md](docs/agents.md) and [docs/control-protocol.md](docs/control-protocol.md). - -## Get started - -Installers for each version are on the [Releases](https://github.com/storytold/effectcraft/releases) -page: a universal macOS app; Windows MSIs and portable zips for x64, x86 and ARM64; Linux -AppImage, Flatpak, deb, rpm and tar.gz for x86_64 and aarch64, plus a riscv64 tar.gz; a FreeBSD x86_64 tarball; and the -web build. [Downloads](#downloads) lists every file. The Windows ARM64 build runs natively on -Windows on ARM, without x64 emulation. CI installs that MSI on Windows 11 ARM64 hardware, checks -both programs are ARM64 and runs the command-line tool there, but it doesn't open the app's window -or run the test suite natively on ARM64 yet, so please report anything that behaves differently. - -On Gentoo, the community [::snakebyte overlay](https://github.com/switch87/snakebyte-overlay) packages -the Linux release as `media-video/effectcraft-bin` (not maintained by the EffectCraft team): - -```sh -eselect repository add snakebyte git https://github.com/switch87/snakebyte-overlay.git -emaint sync -r snakebyte -echo 'media-video/effectcraft-bin ~amd64' >> /etc/portage/package.accept_keywords/effectcraft -emerge --ask media-video/effectcraft-bin -``` - -To build it yourself you need [Rust](https://rustup.rs/) 1.95 or newer. - -```sh -git clone https://github.com/storytold/effectcraft -cd effectcraft -cargo run --release -p effectcraft # the app (add `-- --demo` to open the demo project) -cargo run --release -p effectcraft-cli -- render --out intro.mp4 # render the demo headless -cargo xtask web --serve 8765 # the browser build on http://127.0.0.1:8765/ (docs/web.md) -``` - -New to it? [docs/footage.md](docs/footage.md) covers importing footage and image sequences and -Interpret Footage. - -To work on it: `cargo test --workspace`, and `cargo xtask ci` before every commit (format, lints, -tests, layering, asset attribution and the WebAssembly build). See [CONTRIBUTING.md](CONTRIBUTING.md), -[docs/architecture.md](docs/architecture.md) and [docs/testing.md](docs/testing.md). - -## Where it stands - -EffectCraft is young: its first commit was on 1 October 2026. A comprehensive feature set -exists, including 308 effects, but breadth is not the same as full maturity across every edge -case. Today it's a good place to try things and to tell us what breaks. It isn't yet recommended -for production client work. In particular: - -- **Native project format.** Projects are saved as `.ecproj`, readable versioned JSON. Proprietary - project formats and After Effects SDK plug-ins are not supported. -- **Fidelity is still being refined.** Automated rendering tests currently focus on small - compositions, so please report visual discrepancies or unexpected behaviour. -- **macOS is the most tested platform.** Linux and Windows users have hit basic interaction - bugs, which we're fixing first. -- **The trained models are new.** Roto Brush can use MobileSAM (an optional 40 MB download in - Settings ▸ Roto Brush) and face tracking can use Google's MediaPipe Face Landmarker (an optional - 3.8 MB download in Settings ▸ Face Tracking). Both are actively undergoing evaluation and tuning. - -EffectCraft is in **alpha**: about 91% of the features tracked in -[docs/target-app-parity.md](docs/target-app-parity.md) exist, and we estimate it is about 45% of the -way to being ready for full professional production work. The [ROADMAP](ROADMAP.md) has the plan, -[docs/target-app-parity.md](docs/target-app-parity.md) the measurement and [docs/gaps.md](docs/gaps.md) -every known shortfall. The web build ([docs/web.md](docs/web.md)) runs the full app in the browser. -[Bug reports](https://github.com/storytold/effectcraft/issues) are the most useful thing you can -send us right now. - -## How it's made - -- **Engine first.** A stack of small crates with strict layering. The interface (egui) sits on - top and nothing underneath depends on it. -- **Clean room.** We work from public documentation and observable behavior, never - from proprietary files, icons, presets or code. No code is copied from GPL projects. The full rules - are in [AGENTS.md](AGENTS.md). -- **Private by default.** No telemetry, and no network access unless you ask for it. -- **One family.** EffectCraft shares its time model and text engine design with FilmCraft, and - gets its video and audio codecs from it. - -## Downloads - -**New to EffectCraft?** Download it from the [EffectCraft page on getartcraft.com](https://getartcraft.com/apps/effectcraft). That's the easiest way to install it. - -**Want a specific build or format?** On GitHub, the [latest release](https://github.com/storytold/effectcraft/releases/latest) has every build listed below, and [all releases](https://github.com/storytold/effectcraft/releases) has earlier versions and their notes. `` in the file names is the version number, and `SHA256SUMS.txt` lists a checksum for every file. - -### Windows - -| Build | Installer | Portable | -|---|---|---| -| x64 (64-bit Intel/AMD) | `effectcraft--windows-x64.msi` | `effectcraft--windows-x64-portable.zip` | -| arm64 (Snapdragon and other ARM PCs) | `effectcraft--windows-arm64.msi` | `effectcraft--windows-arm64-portable.zip` | -| x86 (32-bit) | `effectcraft--windows-x86.msi` | `effectcraft--windows-x86-portable.zip` | - -Installers and executables are code-signed. The installer asks who to install EffectCraft for and where. By default it installs for your -account only, into `%LOCALAPPDATA%\Programs\ArtCraft\EffectCraft`, without an administrator prompt; -"Everyone on this computer" installs into `C:\Program Files\ArtCraft\EffectCraft` (`Program Files (x86)` for the 32-bit build). Later versions -install into the same folder. To install silently -into a folder of your choice: `msiexec /i effectcraft--windows-x64.msi /qn INSTALLFOLDER="D:\Apps\EffectCraft"`. -A silent install is per-user by default. `INSTALLFOLDER` chooses the folder, not who it is installed for; -add `ALLUSERS=1`, from an elevated terminal or deployment tool, for an all-users install. - -### macOS - -| Build | File | Notes | -|---|---|---| -| App, universal (Apple silicon + Intel) | `effectcraft--macos-universal.dmg` | Signed and notarized | -| Command-line tool, universal | `effectcraft-cli--macos-universal.zip` | Signed and notarized | - -### Linux - -| Format | x86_64 | aarch64 (ARM64) | Notes | -|---|---|---|---| -| AppImage | `effectcraft--linux-x86_64.AppImage` | `effectcraft--linux-aarch64.AppImage` | Runs anywhere; updates itself with [AppImageUpdate](https://github.com/AppImageCommunity/AppImageUpdate) (`.zsync` files) | -| Flatpak | `effectcraft--linux-x86_64.flatpak` | `effectcraft--linux-aarch64.flatpak` | Sandboxed; `flatpak install --user ` | -| Debian/Ubuntu | `effectcraft--linux-x86_64.deb` | `effectcraft--linux-aarch64.deb` | | -| Fedora/RHEL/openSUSE | `effectcraft--linux-x86_64.rpm` | `effectcraft--linux-aarch64.rpm` | | -| Tarball | `effectcraft--linux-x86_64.tar.gz` | `effectcraft--linux-aarch64.tar.gz` | Unpack anywhere | - -RISC-V 64-bit: `effectcraft--linux-riscv64.tar.gz` (tarball only; needs glibc 2.39+, e.g. Ubuntu 24.04+ or Debian 13+). - -**File drag-and-drop on Linux:** The current eframe/winit 0.30 native Wayland backend does not -deliver file-hover or file-drop events. On Hyprland and other native Wayland sessions, use -**File ▸ Import ▸ File…** (which accepts multiple files), or start EffectCraft via XWayland if -XWayland is installed and `DISPLAY` is set: - -```sh -env -u WAYLAND_DISPLAY effectcraft -``` - -When the backend delivers events (X11/XWayland, Windows and macOS), dropping media anywhere -in the window imports it, and a drop-target hint appears while hovering. On native Wayland the -app cannot detect an attempt that generates no event; it shows a startup notice with the -File ▸ Import fallback instead. - -### FreeBSD - -| Build | File | -|---|---| -| x86_64 | `effectcraft--freebsd-x86_64.tar.gz` | - -### Web (WebAssembly) - -| Build | File | Notes | -|---|---|---| -| Static site | `effectcraft-web-.zip` | Runs in a modern browser; host it on any static server | - -## The Crafting Apps - -EffectCraft is one of the **Crafting Apps**: free, open-source creative tools from the -[ArtCraft](https://getartcraft.com/) team, each written from scratch in Rust and each able to -stand on its own. - -| | App | What it's for | Code | Learn more | -|:-:|---|---|---|---| -| | **PhotoCraft** | Image editing: layers, masks, type and real PSD files | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) | -| | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) | -| | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) | -| | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) | -| | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) | -| | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) | -| | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) | -| | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) | -| | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) | -| | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) | -| | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) | -| | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) | -| | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) | -| | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) | -| | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) | -| | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | | - -And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control. - -
- -

- Join the ArtCraft community on Discord -

- -

Come make things with us

- -

- Our Discord is where artists of every kind hang out: people who paint, shoot, draw, cut film, - set type, and people still figuring out what they like to make. Share what you're working on, - ask for help, tell us what's broken, or tell us what you wish these tools could do. - Whatever your medium and however long you've been at it, you're welcome here. -

- -

- discord.gg/artcraft · - getartcraft.com · - The Crafting Apps · - EffectCraft -

- -## License and credits - -EffectCraft is dual-licensed under [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE), at your option. -Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors. Required notices are in [NOTICE](NOTICE). - -Bundled fonts, icons, images and other assets keep their own open licenses; each one is listed -with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md). - -The ArtCraft name, wordmark and logos in [`docs/brand/`](docs/brand/) are trademarks of the -ArtCraft Team and are not covered by this license. They may be used only unmodified, and only as -part of this repository and EffectCraft, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt). -Forks and modified versions must remove them. - -

- ArtCraft
- Made by the ArtCraft team and community. -

- -## Star history - -[![Star History Chart](https://api.star-history.com/svg?repos=storytold/effectcraft&type=Date&legend=top-left)](https://www.star-history.com/?repos=storytold%2Feffectcraft&type=date&legend=top-left) +

+ + + + ArtCraft + + +

+ + +

+ EffectCraft icon: an engraved unicorn on a pink tile +

+ +

EffectCraft

+ +

+ Motion graphics and visual effects; an open-source, professional motion graphics and visual effects studio, built in pure Rust. +

+ +

+ A free, open-source compositor: compositions, layers, + keyframes, 308 effects, layer styles, expressions, 3D cameras and lights, and a render queue, native on macOS, + Windows and Linux, and in the browser. Young, moving fast, and already usable. +

+ +

+ Status: young and moving fast + Written in Rust + License: MIT OR Apache-2.0 +
+ Scanned by SonarCloud + Reviewed by CodeRabbit +

+ +

+ Join the ArtCraft community on Discord +

+ +

+ EffectCraft on getartcraft.com · + ArtCraft · + All Crafting Apps +

+ +
+ +

+ EffectCraft's main window: the animated demo composition in the Composition panel, the Project panel, a Timeline with text, shape and solid layers, and the Properties panel showing the selected text layer's transform, font and paragraph settings +

+ +> [!NOTE] +> **ArtCraft is a community of artists from all walks of life.** Digital, generative, music, +> games — if you make things, you're one of us. **[Come say hi on Discord](https://discord.gg/artcraft).** + +

+ What it is · + Animate · + Effects · + 3D · + Export · + Agents · + Get started · + Status · + How it's made · + Downloads · + The Crafting Apps · + License +

+ +## What EffectCraft is + +EffectCraft is for animated titles, motion graphics and compositing work: the kind of thing +motion designers and VFX artists need. You build a composition out of layers (solids, shapes, +text, footage, other compositions), animate their properties with keyframes, stack effects on +them and render the result. + +The interface feels natural and responsive, with dedicated panels (Project, Composition, Timeline, +Layer, Footage, Effect Controls, Tools, Preview, Effects & Presets, Audio, Info, Paragraph, +Character, Align, Progress, Render Queue) and standard motion graphics shortcuts, going further in +a few places where it matters to us: + +- **Lottie import and export built in**, so animations can go straight to the web and apps + without a plugin. +- **A project file you can read.** Projects are versioned JSON (`.ecproj`), so they diff cleanly + in version control. +- **Everything is scriptable.** Menu actions, timeline edits and property changes are exposed as + commands. Engine commands are available through the CLI, JSON control channel and MCP; + UI-only commands use the frontend dispatcher and can be invoked through the control channel + or an attached MCP bridge. +- **No FFmpeg.** Video and audio decoding and encoding are pure Rust: FilmCraft's codecs and + EffectCraft's own VP9, AV1, HEVC and Opus encoders. + +## Animate + +The panels, menus and shortcuts follow standard motion design conventions: +Project, Composition, Timeline, Effect Controls, Properties, Effects & Presets, Character, +Paragraph, Align, Info, Preview, Audio and the Render Queue, docked the way you expect. Drag +footage, comps and effects between them: onto the comp viewer, where they land under the pointer, +or into the Timeline, between layers and at the time you point to. + +- **Layers of every kind:** solids, shapes, text, footage, nested compositions, nulls, + adjustment layers, cameras and lights; parenting, track mattes, all 38 blend modes, motion blur. +- **Keyframes that behave the same:** linear, Bezier, hold, auto and continuous Bezier, roving + keys, Easy Ease (F9), Keyframe Velocity and Interpolation dialogs, copy and paste at the current + time, and a **Graph Editor** with value and speed graphs and draggable handles. +- **Time:** time remapping, time stretch, time-reverse, freeze frame, work area, markers, exact + frame-accurate timing at every frame rate including 29.97 drop-frame. +- **Shapes and masks:** shape layers with trim paths, repeaters, round corners, offset, zig zag, + twist, wiggle, merge paths and gradient strokes; masks drawn with the pen tool, with modes, + feather, expansion and vertex editing in the viewer. +- **Text:** point and paragraph text with real shaping in any font installed on your machine, the + Character and Paragraph panels, and text animators with range selectors. +- **Expressions:** JavaScript with the standard motion expressions model (`wiggle`, `loopOut`, + `thisComp.layer("…")`, vector maths on arrays), an inline editor and the pick-whip. +- **Timeline like you know it:** twirl layers open to Transform, masks, effects and the rest; drag + rows to reorder layers; rename with Enter or a double-click; the property shortcuts (A, P, S, + R, T, M, F, E, L, U and their double presses AA, PP, SS, RR, TT, MM, FF, EE, LL, UU), Shift to + add properties, Alt+Shift+A/P/S/R/T to key the current time, Ctrl+` to twirl selected layers. +- **Puppet tools:** Position, Advanced, Bend, Starch and Overlap pins on a mesh built from the + layer, real-time pin recording, rotate/scale handles, pins driven by (or carrying) nulls for + rigging, and follow-through for hair and cloth. + +

+ The Graph Editor showing an eased value curve for a text animator's Range Start, with the graph editor's button bar for hold, linear, auto Bezier and Easy Ease +

+ +## Effects + +308 built-in effects across its categories, each with its parameter names, order and +defaults: blur and sharpen, channel, color correction (Curves, Levels, Hue/Saturation, a full +color-grading panel…), distort (Warp, Bulge, Turbulent Displace, Perspective Pin…), generate (Fractal Noise, +Gradient Ramp, Stroke, Write-on, Audio Spectrum…), keying, matte, noise and grain, perspective, +**simulation** (Particle Emitter 3D, Rainfall, Shatter, Card Dance, Caustics, Wave World…), +stylize (Glow, Glass Relief…), **time** (Echo, Posterize Time, Timewarp, Time Displacement…), +**audio** (Reverb, Parametric EQ, Delay, Stereo Mixer…), text, transitions, utility and expression +controls. All nine **Layer Styles** (Drop Shadow, Inner/Outer Glow, Bevel and Emboss, Satin, +overlays, Stroke) with Global Light. Preview plays audio in sync, with meters and waveforms. + +## 3D + +Classic 3D compositing: 3D layers with orientation and material options, +one- and two-node **cameras** with depth of field, **lights** (parallel, spot, point, ambient) +with soft ray-traced shadows, layers that intersect correctly, orbit, pan and dolly camera +tools, and Front, Top, Left and Custom views. + +

+ The 3D Showcase demo in Custom View 1: intersecting cards lit by a spot light with soft shadows on a gridded floor, with the camera frustum and light drawn as wireframes +

+ +## Export + +A dedicated Render Queue, with Render Settings and Output Modules: **H.264** MP4 and +**ProRes** MOV (Proxy to 4444 XQ with alpha) with audio, **HEVC** (Main / Main 10) and **AV1** +MP4, **WebM** (VP9 with inter frames and alpha, or AV1; Opus audio), PNG, JPEG, TIFF, Targa and 32-bit EXR sequences, animated GIF and WAV/AIFF. Field +rendering with 3:2 pulldown, effect/solo/guide/depth overrides, crop, region of interest and +resize, Render Settings and Output Module templates with defaults, post-render actions, storage +overflow and render logs. The same queue runs from the command line. Every encoder is pure +Rust (craft-libs' H.264, ProRes, HEVC, VP9, AV1 and AAC; EffectCraft's own Opus); there is no +FFmpeg inside. + +**Lottie** goes both ways: File ▸ Export ▸ Lottie JSON… writes a composition (precomps, shape, +solid, image, text and null layers, eased and spatial keyframes, masks, track mattes, blend +modes, time remapping, optionally expressions) as `.json` or `.lottie`, and lists anything Lottie +cannot express; File ▸ Import ▸ Lottie… opens one as a new composition. + +

+ The Render Queue panel with two compositions queued +

+ +## Built for agents + +Engine commands are available through the CLI, JSON control channel and MCP. UI-only commands +need the running app's frontend dispatcher: complete menu access requires the app's control +channel or an attached MCP bridge. Headless MCP sessions expose supported engine commands, +but not UI-only commands or bridge-only `ui_*` tools. + +- **MCP server:** `effectcraft-cli mcp` speaks the Model Context Protocol over stdio, headless + or bridged to the running app (`--bridge 9877`). Tools cover commands, the project and property + tree, keyframes and rendered frames. This repository ships a ready [`.mcp.json`](.mcp.json). +- **Command line:** one-shot calls with JSON output, for example + `effectcraft-cli set Main '#1' transform/position '[100,360]' --time 0 main.ecproj --save` + or `effectcraft-cli render --comp Main --out main.mp4`, or + `effectcraft-cli exec file.exportLottie '{"comp":"Main","path":"main.json"}' main.ecproj`. +- **Control channel:** `effectcraft --control 9877` accepts JSON lines to run commands, inspect + and click any widget by its automation id, and take screenshots. + +See [docs/agents.md](docs/agents.md) and [docs/control-protocol.md](docs/control-protocol.md). + +## Get started + +Installers for each version are on the [Releases](https://github.com/storytold/effectcraft/releases) +page: a universal macOS app; Windows MSIs and portable zips for x64, x86 and ARM64; Linux +AppImage, Flatpak, deb, rpm and tar.gz for x86_64 and aarch64, plus a riscv64 tar.gz; a FreeBSD x86_64 tarball; and the +web build. [Downloads](#downloads) lists every file. The Windows ARM64 build runs natively on +Windows on ARM, without x64 emulation. CI installs that MSI on Windows 11 ARM64 hardware, checks +both programs are ARM64 and runs the command-line tool there, but it doesn't open the app's window +or run the test suite natively on ARM64 yet, so please report anything that behaves differently. + +On Gentoo, the community [::snakebyte overlay](https://github.com/switch87/snakebyte-overlay) packages +the Linux release as `media-video/effectcraft-bin` (not maintained by the EffectCraft team): + +```sh +eselect repository add snakebyte git https://github.com/switch87/snakebyte-overlay.git +emaint sync -r snakebyte +echo 'media-video/effectcraft-bin ~amd64' >> /etc/portage/package.accept_keywords/effectcraft +emerge --ask media-video/effectcraft-bin +``` + +To build it yourself you need [Rust](https://rustup.rs/) 1.95 or newer. + +```sh +git clone https://github.com/storytold/effectcraft +cd effectcraft +cargo run --release -p effectcraft # the app (add `-- --demo` to open the demo project) +cargo run --release -p effectcraft-cli -- render --out intro.mp4 # render the demo headless +cargo xtask web --serve 8765 # the browser build on http://127.0.0.1:8765/ (docs/web.md) +``` + +New to it? [docs/footage.md](docs/footage.md) covers importing footage and image sequences and +Interpret Footage. + +To work on it: `cargo test --workspace`, and `cargo xtask ci` before every commit (format, lints, +tests, layering, asset attribution and the WebAssembly build). See [CONTRIBUTING.md](CONTRIBUTING.md), +[docs/architecture.md](docs/architecture.md) and [docs/testing.md](docs/testing.md). + +## Where it stands + +EffectCraft is young: its first commit was on 1 October 2026. A comprehensive feature set +exists, including 308 effects, but breadth is not the same as full maturity across every edge +case. Today it's a good place to try things and to tell us what breaks. It isn't yet recommended +for production client work. In particular: + +- **Native project format.** Projects are saved as `.ecproj`, readable versioned JSON. Proprietary + project formats and After Effects SDK plug-ins are not supported. +- **Fidelity is still being refined.** Automated rendering tests currently focus on small + compositions, so please report visual discrepancies or unexpected behaviour. +- **macOS is the most tested platform.** Linux and Windows users have hit basic interaction + bugs, which we're fixing first. +- **The trained models are new.** Roto Brush can use MobileSAM (an optional 40 MB download in + Settings ▸ Roto Brush) and face tracking can use Google's MediaPipe Face Landmarker (an optional + 3.8 MB download in Settings ▸ Face Tracking). Both are actively undergoing evaluation and tuning. + +EffectCraft is in **alpha**: about 91% of the features tracked in +[docs/target-app-parity.md](docs/target-app-parity.md) exist, and we estimate it is about 45% of the +way to being ready for full professional production work. The [ROADMAP](ROADMAP.md) has the plan, +[docs/target-app-parity.md](docs/target-app-parity.md) the measurement and [docs/gaps.md](docs/gaps.md) +every known shortfall. The web build ([docs/web.md](docs/web.md)) runs the full app in the browser. +[Bug reports](https://github.com/storytold/effectcraft/issues) are the most useful thing you can +send us right now. + +## How it's made + +- **Engine first.** A stack of small crates with strict layering. The interface (egui) sits on + top and nothing underneath depends on it. +- **Clean room.** We work from public documentation and observable behavior, never + from proprietary files, icons, presets or code. No code is copied from GPL projects. The full rules + are in [AGENTS.md](AGENTS.md). +- **Private by default.** No telemetry, and no network access unless you ask for it. +- **One family.** EffectCraft shares its time model and text engine design with FilmCraft, and + gets its video and audio codecs from it. + +## Downloads + +**New to EffectCraft?** Download it from the [EffectCraft page on getartcraft.com](https://getartcraft.com/apps/effectcraft). That's the easiest way to install it. + +**Want a specific build or format?** On GitHub, the [latest release](https://github.com/storytold/effectcraft/releases/latest) has every build listed below, and [all releases](https://github.com/storytold/effectcraft/releases) has earlier versions and their notes. `` in the file names is the version number, and `SHA256SUMS.txt` lists a checksum for every file. + +### Windows + +| Build | Installer | Portable | +|---|---|---| +| x64 (64-bit Intel/AMD) | `effectcraft--windows-x64.msi` | `effectcraft--windows-x64-portable.zip` | +| arm64 (Snapdragon and other ARM PCs) | `effectcraft--windows-arm64.msi` | `effectcraft--windows-arm64-portable.zip` | +| x86 (32-bit) | `effectcraft--windows-x86.msi` | `effectcraft--windows-x86-portable.zip` | + +Installers and executables are code-signed. The installer asks who to install EffectCraft for and where. By default it installs for your +account only, into `%LOCALAPPDATA%\Programs\ArtCraft\EffectCraft`, without an administrator prompt; +"Everyone on this computer" installs into `C:\Program Files\ArtCraft\EffectCraft` (`Program Files (x86)` for the 32-bit build). Later versions +install into the same folder. To install silently +into a folder of your choice: `msiexec /i effectcraft--windows-x64.msi /qn INSTALLFOLDER="D:\Apps\EffectCraft"`. +A silent install is per-user by default. `INSTALLFOLDER` chooses the folder, not who it is installed for; +add `ALLUSERS=1`, from an elevated terminal or deployment tool, for an all-users install. + +### macOS + +| Build | File | Notes | +|---|---|---| +| App, universal (Apple silicon + Intel) | `effectcraft--macos-universal.dmg` | Signed and notarized | +| Command-line tool, universal | `effectcraft-cli--macos-universal.zip` | Signed and notarized | + +### Linux + +| Format | x86_64 | aarch64 (ARM64) | Notes | +|---|---|---|---| +| AppImage | `effectcraft--linux-x86_64.AppImage` | `effectcraft--linux-aarch64.AppImage` | Runs anywhere; updates itself with [AppImageUpdate](https://github.com/AppImageCommunity/AppImageUpdate) (`.zsync` files) | +| Flatpak | `effectcraft--linux-x86_64.flatpak` | `effectcraft--linux-aarch64.flatpak` | Sandboxed; `flatpak install --user ` | +| Debian/Ubuntu | `effectcraft--linux-x86_64.deb` | `effectcraft--linux-aarch64.deb` | | +| Fedora/RHEL/openSUSE | `effectcraft--linux-x86_64.rpm` | `effectcraft--linux-aarch64.rpm` | | +| Tarball | `effectcraft--linux-x86_64.tar.gz` | `effectcraft--linux-aarch64.tar.gz` | Unpack anywhere | + +RISC-V 64-bit: `effectcraft--linux-riscv64.tar.gz` (tarball only; needs glibc 2.39+, e.g. Ubuntu 24.04+ or Debian 13+). + +**File drag-and-drop on Linux:** The current eframe/winit 0.30 native Wayland backend does not +deliver file-hover or file-drop events. On Hyprland and other native Wayland sessions, use +**File ▸ Import ▸ File…** (which accepts multiple files), or start EffectCraft via XWayland if +XWayland is installed and `DISPLAY` is set: + +```sh +env -u WAYLAND_DISPLAY effectcraft +``` + +When the backend delivers events (X11/XWayland, Windows and macOS), dropping media anywhere +in the window imports it, and a drop-target hint appears while hovering. On native Wayland the +app cannot detect an attempt that generates no event; it shows a startup notice with the +File ▸ Import fallback instead. + +### FreeBSD + +| Build | File | +|---|---| +| x86_64 | `effectcraft--freebsd-x86_64.tar.gz` | + +### Web (WebAssembly) + +| Build | File | Notes | +|---|---|---| +| Static site | `effectcraft-web-.zip` | Runs in a modern browser; host it on any static server | + +## The Crafting Apps + +EffectCraft is one of the **Crafting Apps**: free, open-source creative tools from the +[ArtCraft](https://getartcraft.com/) team, each written from scratch in Rust and each able to +stand on its own. + +| | App | What it's for | Code | Learn more | +|:-:|---|---|---|---| +| | **PhotoCraft** | Image editing: layers, masks, type and real PSD files | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) | +| | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) | +| | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) | +| | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) | +| | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) | +| | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) | +| | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) | +| | **FigCraft** | Interface design and prototyping | [GitHub](https://github.com/storytold/figcraft) | [Website](https://getartcraft.com/apps/figcraft) | +| | **WordCraft** | Word processing and documents | [GitHub](https://github.com/storytold/wordcraft) | [Website](https://getartcraft.com/apps/wordcraft) | +| | **SoundCraft** | Audio recording and editing | [GitHub](https://github.com/storytold/soundcraft) | [Website](https://getartcraft.com/apps/soundcraft) | +| | **DeckCraft** | Presentations and slide decks | [GitHub](https://github.com/storytold/deckcraft) | [Website](https://getartcraft.com/apps/deckcraft) | +| | **CADCraft** | Computer-aided design | [GitHub](https://github.com/storytold/cadcraft) | [Website](https://getartcraft.com/apps/cadcraft) | +| | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) | +| | **TextureCraft** | 3D texture painting | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) | +| | **Craft Anything** | See how any software works, then build your own | [GitHub](https://github.com/storytold/craft-anything) | [Website](https://getartcraft.com/apps/craft-anything) | +| | **SolidCraft** | Parametric 3D CAD by Tangency Labs (community app) | [GitHub](https://github.com/tangency-labs/solidcraft) | | + +And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control. + +
+ +

+ Join the ArtCraft community on Discord +

+ +

Come make things with us

+ +

+ Our Discord is where artists of every kind hang out: people who paint, shoot, draw, cut film, + set type, and people still figuring out what they like to make. Share what you're working on, + ask for help, tell us what's broken, or tell us what you wish these tools could do. + Whatever your medium and however long you've been at it, you're welcome here. +

+ +

+ discord.gg/artcraft · + getartcraft.com · + The Crafting Apps · + EffectCraft +

+ +## License and credits + +EffectCraft is dual-licensed under [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE), at your option. +Copyright (c) 2026 ArtCraft Team and the EffectCraft contributors. Required notices are in [NOTICE](NOTICE). + +Bundled fonts, icons, images and other assets keep their own open licenses; each one is listed +with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md). + +The ArtCraft name, wordmark and logos in [`docs/brand/`](docs/brand/) are trademarks of the +ArtCraft Team and are not covered by this license. They may be used only unmodified, and only as +part of this repository and EffectCraft, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt). +Forks and modified versions must remove them. + +

+ ArtCraft
+ Made by the ArtCraft team and community. +

+ +## Star history + +[![Star History Chart](https://api.star-history.com/svg?repos=storytold/effectcraft&type=Date&legend=top-left)](https://www.star-history.com/?repos=storytold%2Feffectcraft&type=date&legend=top-left) diff --git a/ROADMAP.md b/ROADMAP.md index e41cbe2f1..88fa7335e 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -1,193 +1,194 @@ -# EffectCraft Roadmap - -**Stage: alpha** · next: beta, ~30 points of "ready for real work" and ~350–620 h away - -> **Last reviewed:** 2026-10-22 · **Last updated:** 2026-11-05 · **Change:** minor (ProRes alpha final-run conformance; previously: features of 30 October in the progress log: text Line Join, Timeline drag-reorder and multi-select of effects, viewer edge pan, ScriptUI drag capture and dock size; previously: localization recount after #1774) · **Target:** Adobe After Effects 2026 (26.5.0.89) - -EffectCraft aims to do what After Effects does, with the same panels, menus and behaviour, written -from scratch in Rust. This page is the one-page summary; the evidence is in -[docs/target-app-parity.md](docs/target-app-parity.md), the work list in -[docs/gaps.md](docs/gaps.md), and the plan in [docs/roadmap.md](docs/roadmap.md). - -## Headline numbers - -| | Value | Kind | -|---|---|---| -| **Feature breadth** | **≈ 91%** | Estimated, weighted by area; the self-graded 92-item checklist says ≈ 99% | -| **Ready for real work** | **≈ 45%** (40–50%) | Estimated; one live fidelity measurement so far | -| **Mainstream practitioner** | **≈ 47%** | Estimated: the typical motion designer's weekly work ([how](docs/target-app-parity.md#mainstream-practitioner-and-essentials-user)) | -| **Essentials user** | **≈ 52%** | Estimated: core features only ([how](docs/target-app-parity.md#essentials-user)) | -| Remaining to **beta** | **≈ 350–620 Opus 5.5 agent-hours** | Estimated | -| Remaining to **full parity** | **≈ 850–1,500 Opus 5.5 agent-hours** | Estimated; ≈ 70% parallelises | - -| Audience | Ready % | Hours to ~95% | Work that dominates | -|---|---:|---:|---| -| Full target | ≈ 45% | ≈ 850–1,500 h | `.aep`, fidelity corpus, bug backlog, performance, formats, hardware, localization | -| Mainstream practitioner | ≈ 47% | ≈ 280–530 h | `.aep` exchange, stability, everyday fidelity and bugs, preview speed | -| Essentials user | ≈ 52% | ≈ 150–300 h | Opening tutorial `.aep` files, start-up stability, core bugs, preview with sound | - -About 60–70% of these hours parallelise ([detail](docs/target-app-parity.md#readiness-by-audience)). - -Hours are one Opus 5.5 agent working sequentially, calibrated on this repository's history -([how](docs/target-app-parity.md#calibration-of-the-hours)). - -### Stage - -**Alpha**, because all six core workflows of the [alpha gate](docs/roadmap.md#alpha-gate) -(set up, animate, text and shapes, composite, preview, save and deliver) work end to end on macOS -and the work saves and reopens, and ready for real work (≈ 45%) is above the ≈ 40% bar. But: After Effects projects (`.aep`) can't be opened, which -alone rules out beta; fidelity against After Effects is measured for one narrow case (scalar ease, -168 samples); 216 issues are open on 12 October, six of them crash reports (#580, #501, #426, #341, #234, #879). Beta needs ≈ 75% ready and `.aep` -opening reliably: the `.aep` owner decision and importer (80–160 h), the fidelity harness and -P0/P1 corpus (60–100 h), the crash and bug backlog (40–80 h), performance (40–70 h), -Linux/Windows reliability (30–50 h) and depth in animation, masks, effects and text (100–160 h). - -## By dimension - -| Dimension | % | Hours | Doc | -|---|---:|---:|---| -| Features: breadth | 91% | — | [target-app-parity.md](docs/target-app-parity.md#by-feature-area) | -| Features: ready for real work | 50% | 360–660 | [target-app-parity.md](docs/target-app-parity.md#by-feature-area) | -| UI/UX fidelity | 65% | 60–120 | [ui-parity.md](docs/ui-parity.md) | -| File formats | 50% | 130–230 | [file-format-parity.md](docs/file-format-parity.md) | -| Hardware | 40% | 60–120 | [hardware-parity.md](docs/hardware-parity.md) | -| Localization | 24% | 60–110 + review | [localization-parity.md](docs/localization-parity.md) | -| Performance | 35% | 50–100 | [gaps.md](docs/gaps.md#g5-performance-at-real-world-scale) | -| Stability | 45% | 40–80 | [gaps.md](docs/gaps.md#g3-stability-and-a-green-main) | -| Platforms | 65% | 30–60 | [gaps.md](docs/gaps.md#g2-real-user-reliability-on-every-platform) | -| Ecosystem and plug-ins | 20% | 40–80 | [plugins.md](docs/plugins.md), [scripting-parity.md](docs/scripting-parity.md) | -| AI features | 35% | 40–80 | [gaps.md](docs/gaps.md) | -| Agent control (beyond After Effects) | ahead | — | [agents.md](docs/agents.md) | - -## Features - -| Area | Breadth | Ready | Hours | -|---|---:|---:|---:| -| Project, footage and import | 92% | 55% | 25–45 | -| Compositions, layers and compositing | 98% | 60% | 30–55 | -| Animation: keyframes, graph editor, motion paths, puppet | 97% | 55% | 35–60 | -| Expressions and scripting ([detail](docs/scripting-parity.md)) | 93% | 65% | 20–40 | -| Shapes, masks and roto | 93% | 45% | 30–50 | -| Text and typography | 94% | 50% | 20–35 | -| Effects and animation presets ([detail](docs/effects-parity.md)) | 85% | 40% | 70–130 | -| 3D (Classic and Advanced) | 82% | 35% | 35–65 | -| Tracking and AI-assisted tools | 80% | 35% | 35–70 | -| Preview and cache | 92% | 40% | 25–50 | -| Render queue and export | 85% | 55% | 25–45 | -| Audio | 85% | 45% | 6–12 | - -Weights and evidence per row: [target-app-parity.md](docs/target-app-parity.md#by-feature-area). - -## Languages - -UI strings translated out of ≈ 4,200 (detail: [localization-parity.md](docs/localization-parity.md)). - -| Language | Status | % | -|---|---|---:| -| English | full | 100% | -| Simplified Chinese | partial (menus, most of the panels) | 46% | -| Spanish | menus only | 29% | -| Hindi | none | 0% | -| Arabic | none | 0% | -| French | menus only | 16% | -| Portuguese (Brazil) | partial (menus, part of the panels) | 34% | -| Indonesian | none | 0% | -| Japanese | partial (menus, most of the panels) | 46% | -| German | menus only | 16% | -| Korean | none | 0% | -| Vietnamese | none | 0% | - -Also shipped: Traditional Chinese (partial, 38%), Ukrainian (partial, 29%), Czech (partial, 29%), Polish (partial, 34%), Georgian (partial, 39%; native-speaker reviewed), Russian (menus only, 15%) and Swedish (menus, panels and effect names; not yet measured). No other language has had -native-speaker review. - -## Upcoming - -Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gaps.md). - -| | Next | Hours | -|---|---|---:| -| 1 | Fix the open crash reports; run `cargo xtask ci` on every pull request (G3) | 15–30 | -| 2 | Fidelity harness against After Effects: rendered frames, a corpus case per P0/P1 feature (G1) | 60–100 | -| 3 | Real-user reliability on Linux and Windows; the open mask, effect, text and 3D bugs (G2) | 100–190 | -| 4 | `.aep` / `.aepx` import, after the owner's clean-room decision (G4) | 80–160 | -| 5 | Performance: benchmarks at 1080p / 4K, real-time cached playback, hardware video (G5) | 50–100 | -| 6 | Localization depth: effect names, all panels, Korean / Italian (G9) | 60–110 | - -Come tell us what matters most to you on [Discord](https://discord.gg/artcraft). - -## Progress log - -- 2026-11-05: ProRes 4444 and XQ exports write the required run after the final alpha - difference. The FilmCraft encoder pin fixes alpha movies rejected by native macOS - decoding; an export regression checks the stored bytes for both profiles, alpha modes, - and motion-blur settings (#293). Resolve itself still needs confirmation. -- 2026-10-30: Text strokes take a Line Join (Miter, Round or Bevel) in the Character panel, - Miter for new text as in After Effects (#2077). In the Timeline, effects, masks and shape items - drag to a new place in their stack (#2210) and Shift-click adds them to the selection, so one - animation preset can hold several (#2552). The Composition panel pans while a mask vertex is - held at its edge (#999). Effect buffers that pad a small layer stay within a memory budget - (#2261); an MP4 lasts as long as its edit list shows (#2592); the Render Queue's times tick - between frames (#2593). ScriptUI drags keep their control past the window edge with - `MouseEvent.buttons` (#2584), and docked panels get their dock's size and `onResize` (#2585). -- 2026-10-28: A shape layer's Rectangle and Ellipse Size get the Constrain Proportions chain - that Scale has, so a circle stays a circle while its size is typed, scrubbed or keyed; it - starts off, so existing shapes behave as before (#2489). -- 2026-10-24: Shape layers have the Wiggle Transform path operation (Contents ▸ Add, or - `layer.addShapeItem {kind: "wiggler"}`): it wiggles the anchor point, position, scale and - rotation of the paths above it by random amounts that change over time, up to the Transform - values it holds. The copies of a Repeater above it wiggle independently as far as its - Correlation allows; with the Repeater below it, they wiggle together. -- 2026-10-22: Localization: the panel/dialog catalogs gain 303 rows in Japanese, Simplified - Chinese and Traditional Chinese — panel tabs, form and dialog labels, panel context menus, - tracker/graph/text-panel controls, File-panel footers and credits. Recounted after #1774: - Japanese is 1,923 of ≈ 4,200 interface strings (46%, with 297 effect names); the Chinese - panel catalogs hold 998 (Simplified) and 951 (Traditional) rows, and Simplified Chinese is - 46% with its 307 effect names; the overall share is ≈ 24%. -- 2026-10-16: Convert To Bezier Path turns a shape layer's Rectangle, Ellipse or Polystar - path into an editable Path 1 with the same geometry, as After Effects does; it used to - apply to mask RotoBezier only, so a parametric shape path could not be converted at all - and its vertices could not be edited or animated (#932). -- 2026-10-14: Georgian (`ka`): every menu row, every panel-catalog row the Chinese catalogs have plus 195 Georgian-only ones, and the effect names and categories; Match System for `ka` / `ka-GE` / `ka_GE.UTF-8` locales. Reviewed by a native speaker. -- 2026-10-12: Roto Brush span edits report strokes outside a trimmed layer without panicking; - strokes and undo history are preserved so restoring the timing allows the span edit again. -- 2026-10-11: Ukrainian panels caught up with the Chinese catalogs. The 95 rows the panel - catalog gained since 9 October are translated: the Home screen (recent files, their Kind and - Opened columns, the empty and no-match states), the viewer's toolbar tooltips, magnification, - resolution, grid, channel and Fast Previews popups, the Appearance settings, the solid dialog - and the project, import, export and colour-management forms. `uk` now carries 495 of the 496 - panel rows — `RGB` reads the same in Ukrainian, so it falls back to the English source by - design — alongside its 618/618 menus. -- 2026-10-10: Full parity re-measure against After Effects 2026 26.5 (installed bundle, 26.2–26.5 - release notes, repository counts): breadth ≈ 91%, ready ≈ 45%, stage alpha. Progress docs - restructured: `docs/parity.md` became `docs/target-app-parity.md`; new - `docs/roadmap.md`, `localization-parity.md`, `file-format-parity.md`, `hardware-parity.md`, - `ui-parity.md`, `effects-parity.md` and `scripting-parity.md`. -- 2026-10-10: Spanish (#460) and Brazilian Portuguese (#217) menu translations. -- 2026-10-10: Japanese now translates the interface below the menu bar too: `crates/ui-egui/src/i18n/ui.rs` has a Japanese table with the same 396 rows as the Chinese ones (panels, dialogs, buttons and tooltips; the shape test keeps the three catalogs listing the same source strings). Menus were already Japanese. -- 2026-10-09: Ukrainian now covers all 396 current panel-catalog strings, including dialogs, buttons and tooltips, alongside its menu translation. The catalog keeps the same source keys and placeholder counts as the Chinese catalogs; missing or engine-generated text still falls back to English. - -- UI.6: Viewer breadcrumbs use theme colors for readable active text. The bottom control row scrolls horizontally at compact widths; keyboard focus reveals the selected control while dropdowns, exposure adjustments and snapshot holds retain their behavior. -- UI.3: Shared docking transactions and pointer targets now handle panel moves, splits, tab ordering and floating groups, preserving accordion metadata and the saved workspace schema. Dock dividers use bounded shared geometry and keyboard-accessible resize handles. Tiny layouts no longer reach an invalid floating-point clamp; workspace trees and saved layouts are retained. - -- 2026-10-09: Settings ▸ General ▸ Language now translates the interface below the menu bar as well: panels, dialogs, buttons and tooltips read their text through `crates/ui-egui/src/i18n/ui.rs`, keyed by the English source string. Simplified and Traditional Chinese are complete (384 strings); Japanese rows can follow in the same file. A test fails when a converted panel gains a hard-coded string, and another keeps the catalog free of unused rows. -- 2026-10-08: `effectcraft-cli render --out` resolves a relative path against the working directory, like `--project` (it used the project's folder, which doubled a path that already named it). Render Queue outputs set in a project are unchanged. -- 2026-10-08: Long-press a grouped toolbar button to choose its tools, including Horizontal/Vertical Type; releasing the hold keeps the menu open. Existing point/paragraph text creation is unchanged. -- 2026-10-06: Settings ▸ General ▸ Language persists English/Japanese menu labels (`general.language`); native UI reuses installed Japanese font fallback, with no bundled CJK font. Dialog and panel contents remain English. -- 2026-10-05: Honest assessment ([docs/gaps.md](docs/gaps.md)): breadth ≈ 99% by our own checklist, real use ≈ 30–50%; workstreams G1–G9. -- 2026-10-04: Checklist audit at `d39c0e8`: 89 done / 3 partial / 0 missing of 92 features. -- 2026-10-01: First commit. - -## Revision history - -| Date | Change | Summary | -|---|---|---| -| 2026-10-30 | minor | Progress log: text Line Join, Timeline drag-reorder and Shift multi-select of effects, viewer edge pan, effect padding budget, MP4 edit-list duration, Render Queue clock, ScriptUI drag capture and docked-panel size | -| 2026-10-22 | minor | Localization: 300 more panel/dialog rows in Japanese and the Chinese catalogs, plus the review's three missing rows (Basic, Advanced, Play/Stop) — panel tabs, form and dialog labels, context menus, tracker/graph/text-panel controls, File-panel footers, credits; language shares recounted after #1774 (Japanese 27% → 46% with 297 effect names, Simplified Chinese 29% → 46% with 307 effect names, Traditional Chinese 29% → 38%, overall 18% → 24%) | -| 2026-10-12 | minor | Open-issue count (134 to 216), crash list and localization share (12% to 18%) updated to match docs/gaps.md | -| 2026-10-12 | patch | Roto Brush span validation after trimming; command regressions for both layer edges | -| 2026-10-12 | minor | Shared PDF object/xref parsing with bounded app-owned conversion and preserved stream budgets; drawing, EPS and image/font policy remain unchanged | -| 2026-10-10 | minor | Hours to ≈ 95% for each audience | -| 2026-10-10 | minor | Headline adds mainstream practitioner (≈ 47%) and essentials user (≈ 52%) | -| 2026-10-10 | major | Progress docs restructured: stage, two numbers, dimensions, features, languages, upcoming, progress log; milestones moved to docs/roadmap.md | -| 2026-10-10 | minor | Stage checked against the new core-workflow gate (all six pass; still alpha) | -| 2026-10-05 | major | Two numbers (breadth vs real use) and workstreams G1–G9 | +# EffectCraft Roadmap + +**Stage: alpha** · next: beta, ~30 points of "ready for real work" and ~350–620 h away + +> **Last reviewed:** 2026-11-15 · **Last updated:** 2026-11-15 · **Change:** minor (releases v0.22.0 through v0.24.1; .aep gained project export (#2594), drag-and-drop import (#3103), an audit of hostile inputs with every loss reported (#3299, #3300, #3319, #3365), placeholders for unmapped effects (#3087), Lumetri Color, Puppet, CC Color Neutralizer, EXtractoR/IDentifier, HDR Highlight Compression, Echo, Linear Wipe, Offset and Color Stabilizer mappings, text-animator and Source Text expressions (#3170) and twice the import speed (#3302); GPU rendering 2.6× faster with one upload per frame and single-copy readback (#3335), smooth preview lanes (#3345), bounded GPU memory (#3028), shared multi-layer EXR decode (#474), EXR output options (#2915, #2916) and a WebAssembly ABI 2 plug-in path (#3329); eighteen effect parameters now take After Effects' ranges (#3470–#3480, #3483–#3484, #3487–#3491), with Color Stabilizer sampling (#3125), masked Grid/Checkerboard/Circle (#3121), Cryptomatte selection and Matte Only (#2839, #3130), fast-conformed frame blending (#3180) and bounded Levels and time-stretch math; number-field arithmetic (#3195), expressionError (#3219), prop.get with footage (#3231), reversed-layer audio (#3239), keyframed audio waveforms (#1722), Effect Controls lock and rename selection (#3193, #3198), viewer snapping (#2681, #3229), Graph Editor theming (#3202), Convert To Bezier Path (#3237), stopwatch Add Expression (#3192), Shift-drag timeline snapping (#1828), anchored marquee (#2859), Go to Time (#3373), text layers whose names follow their text (#3233), mute-aware audio preview (#2104), ScriptUI panel bars (#2796), Closed-path and Effect Controls arrow fixes (#2817, #2869) and accessible Info, Flowchart, Script Console and 3D Camera Tracker blocks (#1341); a file-dialog crash fix (#3084), crash diagnostics and replayable repros (#3357, #1224), Flatpak updater and nightly release fixes (#3516, #3520), craft-libs format and update cutovers, and CI test stabilisation (#3650, #3689, #3704); readiness estimates unchanged) · **Target:** Adobe After Effects 2026 (26.5.0.89) +> **Last reviewed:** 2026-10-22 · **Last updated:** 2026-11-05 · **Change:** minor (ProRes alpha final-run conformance; previously: features of 30 October in the progress log: text Line Join, Timeline drag-reorder and multi-select of effects, viewer edge pan, ScriptUI drag capture and dock size; previously: localization recount after #1774) · **Target:** Adobe After Effects 2026 (26.5.0.89) + +EffectCraft aims to do what After Effects does, with the same panels, menus and behaviour, written +from scratch in Rust. This page is the one-page summary; the evidence is in +[docs/target-app-parity.md](docs/target-app-parity.md), the work list in +[docs/gaps.md](docs/gaps.md), and the plan in [docs/roadmap.md](docs/roadmap.md). + +## Headline numbers + +| | Value | Kind | +|---|---|---| +| **Feature breadth** | **≈ 91%** | Estimated, weighted by area; the self-graded 92-item checklist says ≈ 99% | +| **Ready for real work** | **≈ 45%** (40–50%) | Estimated; one live fidelity measurement so far | +| **Mainstream practitioner** | **≈ 47%** | Estimated: the typical motion designer's weekly work ([how](docs/target-app-parity.md#mainstream-practitioner-and-essentials-user)) | +| **Essentials user** | **≈ 52%** | Estimated: core features only ([how](docs/target-app-parity.md#essentials-user)) | +| Remaining to **beta** | **≈ 350–620 Opus 5.5 agent-hours** | Estimated | +| Remaining to **full parity** | **≈ 850–1,500 Opus 5.5 agent-hours** | Estimated; ≈ 70% parallelises | + +| Audience | Ready % | Hours to ~95% | Work that dominates | +|---|---:|---:|---| +| Full target | ≈ 45% | ≈ 850–1,500 h | `.aep`, fidelity corpus, bug backlog, performance, formats, hardware, localization | +| Mainstream practitioner | ≈ 47% | ≈ 280–530 h | `.aep` exchange, stability, everyday fidelity and bugs, preview speed | +| Essentials user | ≈ 52% | ≈ 150–300 h | Opening tutorial `.aep` files, start-up stability, core bugs, preview with sound | + +About 60–70% of these hours parallelise ([detail](docs/target-app-parity.md#readiness-by-audience)). + +Hours are one Opus 5.5 agent working sequentially, calibrated on this repository's history +([how](docs/target-app-parity.md#calibration-of-the-hours)). + +### Stage + +**Alpha**, because all six core workflows of the [alpha gate](docs/roadmap.md#alpha-gate) +(set up, animate, text and shapes, composite, preview, save and deliver) work end to end on macOS +and the work saves and reopens, and ready for real work (≈ 45%) is above the ≈ 40% bar. But: After Effects projects (`.aep`) can't be opened, which +alone rules out beta; fidelity against After Effects is measured for one narrow case (scalar ease, +168 samples); 216 issues are open on 12 October, six of them crash reports (#580, #501, #426, #341, #234, #879). Beta needs ≈ 75% ready and `.aep` +opening reliably: the `.aep` owner decision and importer (80–160 h), the fidelity harness and +P0/P1 corpus (60–100 h), the crash and bug backlog (40–80 h), performance (40–70 h), +Linux/Windows reliability (30–50 h) and depth in animation, masks, effects and text (100–160 h). + +## By dimension + +| Dimension | % | Hours | Doc | +|---|---:|---:|---| +| Features: breadth | 91% | — | [target-app-parity.md](docs/target-app-parity.md#by-feature-area) | +| Features: ready for real work | 50% | 360–660 | [target-app-parity.md](docs/target-app-parity.md#by-feature-area) | +| UI/UX fidelity | 65% | 60–120 | [ui-parity.md](docs/ui-parity.md) | +| File formats | 50% | 130–230 | [file-format-parity.md](docs/file-format-parity.md) | +| Hardware | 40% | 60–120 | [hardware-parity.md](docs/hardware-parity.md) | +| Localization | 24% | 60–110 + review | [localization-parity.md](docs/localization-parity.md) | +| Performance | 35% | 50–100 | [gaps.md](docs/gaps.md#g5-performance-at-real-world-scale) | +| Stability | 45% | 40–80 | [gaps.md](docs/gaps.md#g3-stability-and-a-green-main) | +| Platforms | 65% | 30–60 | [gaps.md](docs/gaps.md#g2-real-user-reliability-on-every-platform) | +| Ecosystem and plug-ins | 20% | 40–80 | [plugins.md](docs/plugins.md), [scripting-parity.md](docs/scripting-parity.md) | +| AI features | 35% | 40–80 | [gaps.md](docs/gaps.md) | +| Agent control (beyond After Effects) | ahead | — | [agents.md](docs/agents.md) | + +## Features + +| Area | Breadth | Ready | Hours | +|---|---:|---:|---:| +| Project, footage and import | 92% | 55% | 25–45 | +| Compositions, layers and compositing | 98% | 60% | 30–55 | +| Animation: keyframes, graph editor, motion paths, puppet | 97% | 55% | 35–60 | +| Expressions and scripting ([detail](docs/scripting-parity.md)) | 93% | 65% | 20–40 | +| Shapes, masks and roto | 93% | 45% | 30–50 | +| Text and typography | 94% | 50% | 20–35 | +| Effects and animation presets ([detail](docs/effects-parity.md)) | 85% | 40% | 70–130 | +| 3D (Classic and Advanced) | 82% | 35% | 35–65 | +| Tracking and AI-assisted tools | 80% | 35% | 35–70 | +| Preview and cache | 92% | 40% | 25–50 | +| Render queue and export | 85% | 55% | 25–45 | +| Audio | 85% | 45% | 6–12 | + +Weights and evidence per row: [target-app-parity.md](docs/target-app-parity.md#by-feature-area). + +## Languages + +UI strings translated out of ≈ 4,200 (detail: [localization-parity.md](docs/localization-parity.md)). + +| Language | Status | % | +|---|---|---:| +| English | full | 100% | +| Simplified Chinese | partial (menus, most of the panels) | 46% | +| Spanish | menus only | 29% | +| Hindi | none | 0% | +| Arabic | none | 0% | +| French | menus only | 16% | +| Portuguese (Brazil) | partial (menus, part of the panels) | 34% | +| Indonesian | none | 0% | +| Japanese | partial (menus, most of the panels) | 46% | +| German | menus only | 16% | +| Korean | none | 0% | +| Vietnamese | none | 0% | + +Also shipped: Traditional Chinese (partial, 38%), Ukrainian (partial, 29%), Czech (partial, 29%), Polish (partial, 34%), Georgian (partial, 39%; native-speaker reviewed), Russian (menus only, 15%) and Swedish (menus, panels and effect names; not yet measured). No other language has had +native-speaker review. + +## Upcoming + +Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gaps.md). + +| | Next | Hours | +|---|---|---:| +| 1 | Fix the open crash reports; run `cargo xtask ci` on every pull request (G3) | 15–30 | +| 2 | Fidelity harness against After Effects: rendered frames, a corpus case per P0/P1 feature (G1) | 60–100 | +| 3 | Real-user reliability on Linux and Windows; the open mask, effect, text and 3D bugs (G2) | 100–190 | +| 4 | `.aep` / `.aepx` import, after the owner's clean-room decision (G4) | 80–160 | +| 5 | Performance: benchmarks at 1080p / 4K, real-time cached playback, hardware video (G5) | 50–100 | +| 6 | Localization depth: effect names, all panels, Korean / Italian (G9) | 60–110 | + +Come tell us what matters most to you on [Discord](https://discord.gg/artcraft). + +## Progress log + +- 2026-11-05: ProRes 4444 and XQ exports write the required run after the final alpha + difference. The FilmCraft encoder pin fixes alpha movies rejected by native macOS + decoding; an export regression checks the stored bytes for both profiles, alpha modes, + and motion-blur settings (#293). Resolve itself still needs confirmation. +- 2026-10-30: Text strokes take a Line Join (Miter, Round or Bevel) in the Character panel, + Miter for new text as in After Effects (#2077). In the Timeline, effects, masks and shape items + drag to a new place in their stack (#2210) and Shift-click adds them to the selection, so one + animation preset can hold several (#2552). The Composition panel pans while a mask vertex is + held at its edge (#999). Effect buffers that pad a small layer stay within a memory budget + (#2261); an MP4 lasts as long as its edit list shows (#2592); the Render Queue's times tick + between frames (#2593). ScriptUI drags keep their control past the window edge with + `MouseEvent.buttons` (#2584), and docked panels get their dock's size and `onResize` (#2585). +- 2026-10-28: A shape layer's Rectangle and Ellipse Size get the Constrain Proportions chain + that Scale has, so a circle stays a circle while its size is typed, scrubbed or keyed; it + starts off, so existing shapes behave as before (#2489). +- 2026-10-24: Shape layers have the Wiggle Transform path operation (Contents ▸ Add, or + `layer.addShapeItem {kind: "wiggler"}`): it wiggles the anchor point, position, scale and + rotation of the paths above it by random amounts that change over time, up to the Transform + values it holds. The copies of a Repeater above it wiggle independently as far as its + Correlation allows; with the Repeater below it, they wiggle together. +- 2026-10-22: Localization: the panel/dialog catalogs gain 303 rows in Japanese, Simplified + Chinese and Traditional Chinese — panel tabs, form and dialog labels, panel context menus, + tracker/graph/text-panel controls, File-panel footers and credits. Recounted after #1774: + Japanese is 1,923 of ≈ 4,200 interface strings (46%, with 297 effect names); the Chinese + panel catalogs hold 998 (Simplified) and 951 (Traditional) rows, and Simplified Chinese is + 46% with its 307 effect names; the overall share is ≈ 24%. +- 2026-10-16: Convert To Bezier Path turns a shape layer's Rectangle, Ellipse or Polystar + path into an editable Path 1 with the same geometry, as After Effects does; it used to + apply to mask RotoBezier only, so a parametric shape path could not be converted at all + and its vertices could not be edited or animated (#932). +- 2026-10-14: Georgian (`ka`): every menu row, every panel-catalog row the Chinese catalogs have plus 195 Georgian-only ones, and the effect names and categories; Match System for `ka` / `ka-GE` / `ka_GE.UTF-8` locales. Reviewed by a native speaker. +- 2026-10-12: Roto Brush span edits report strokes outside a trimmed layer without panicking; + strokes and undo history are preserved so restoring the timing allows the span edit again. +- 2026-10-11: Ukrainian panels caught up with the Chinese catalogs. The 95 rows the panel + catalog gained since 9 October are translated: the Home screen (recent files, their Kind and + Opened columns, the empty and no-match states), the viewer's toolbar tooltips, magnification, + resolution, grid, channel and Fast Previews popups, the Appearance settings, the solid dialog + and the project, import, export and colour-management forms. `uk` now carries 495 of the 496 + panel rows — `RGB` reads the same in Ukrainian, so it falls back to the English source by + design — alongside its 618/618 menus. +- 2026-10-10: Full parity re-measure against After Effects 2026 26.5 (installed bundle, 26.2–26.5 + release notes, repository counts): breadth ≈ 91%, ready ≈ 45%, stage alpha. Progress docs + restructured: `docs/parity.md` became `docs/target-app-parity.md`; new + `docs/roadmap.md`, `localization-parity.md`, `file-format-parity.md`, `hardware-parity.md`, + `ui-parity.md`, `effects-parity.md` and `scripting-parity.md`. +- 2026-10-10: Spanish (#460) and Brazilian Portuguese (#217) menu translations. +- 2026-10-10: Japanese now translates the interface below the menu bar too: `crates/ui-egui/src/i18n/ui.rs` has a Japanese table with the same 396 rows as the Chinese ones (panels, dialogs, buttons and tooltips; the shape test keeps the three catalogs listing the same source strings). Menus were already Japanese. +- 2026-10-09: Ukrainian now covers all 396 current panel-catalog strings, including dialogs, buttons and tooltips, alongside its menu translation. The catalog keeps the same source keys and placeholder counts as the Chinese catalogs; missing or engine-generated text still falls back to English. + +- UI.6: Viewer breadcrumbs use theme colors for readable active text. The bottom control row scrolls horizontally at compact widths; keyboard focus reveals the selected control while dropdowns, exposure adjustments and snapshot holds retain their behavior. +- UI.3: Shared docking transactions and pointer targets now handle panel moves, splits, tab ordering and floating groups, preserving accordion metadata and the saved workspace schema. Dock dividers use bounded shared geometry and keyboard-accessible resize handles. Tiny layouts no longer reach an invalid floating-point clamp; workspace trees and saved layouts are retained. + +- 2026-10-09: Settings ▸ General ▸ Language now translates the interface below the menu bar as well: panels, dialogs, buttons and tooltips read their text through `crates/ui-egui/src/i18n/ui.rs`, keyed by the English source string. Simplified and Traditional Chinese are complete (384 strings); Japanese rows can follow in the same file. A test fails when a converted panel gains a hard-coded string, and another keeps the catalog free of unused rows. +- 2026-10-08: `effectcraft-cli render --out` resolves a relative path against the working directory, like `--project` (it used the project's folder, which doubled a path that already named it). Render Queue outputs set in a project are unchanged. +- 2026-10-08: Long-press a grouped toolbar button to choose its tools, including Horizontal/Vertical Type; releasing the hold keeps the menu open. Existing point/paragraph text creation is unchanged. +- 2026-10-06: Settings ▸ General ▸ Language persists English/Japanese menu labels (`general.language`); native UI reuses installed Japanese font fallback, with no bundled CJK font. Dialog and panel contents remain English. +- 2026-10-05: Honest assessment ([docs/gaps.md](docs/gaps.md)): breadth ≈ 99% by our own checklist, real use ≈ 30–50%; workstreams G1–G9. +- 2026-10-04: Checklist audit at `d39c0e8`: 89 done / 3 partial / 0 missing of 92 features. +- 2026-10-01: First commit. + +## Revision history + +| Date | Change | Summary | +|---|---|---| +| 2026-10-30 | minor | Progress log: text Line Join, Timeline drag-reorder and Shift multi-select of effects, viewer edge pan, effect padding budget, MP4 edit-list duration, Render Queue clock, ScriptUI drag capture and docked-panel size | +| 2026-10-22 | minor | Localization: 300 more panel/dialog rows in Japanese and the Chinese catalogs, plus the review's three missing rows (Basic, Advanced, Play/Stop) — panel tabs, form and dialog labels, context menus, tracker/graph/text-panel controls, File-panel footers, credits; language shares recounted after #1774 (Japanese 27% → 46% with 297 effect names, Simplified Chinese 29% → 46% with 307 effect names, Traditional Chinese 29% → 38%, overall 18% → 24%) | +| 2026-10-12 | minor | Open-issue count (134 to 216), crash list and localization share (12% to 18%) updated to match docs/gaps.md | +| 2026-10-12 | patch | Roto Brush span validation after trimming; command regressions for both layer edges | +| 2026-10-12 | minor | Shared PDF object/xref parsing with bounded app-owned conversion and preserved stream budgets; drawing, EPS and image/font policy remain unchanged | +| 2026-10-10 | minor | Hours to ≈ 95% for each audience | +| 2026-10-10 | minor | Headline adds mainstream practitioner (≈ 47%) and essentials user (≈ 52%) | +| 2026-10-10 | major | Progress docs restructured: stage, two numbers, dimensions, features, languages, upcoming, progress log; milestones moved to docs/roadmap.md | +| 2026-10-10 | minor | Stage checked against the new core-workflow gate (all six pass; still alpha) | +| 2026-10-05 | major | Two numbers (breadth vs real use) and workstreams G1–G9 | diff --git a/apps/effectcraft/Cargo.toml b/apps/effectcraft/Cargo.toml index 21bd46755..2c8224f65 100644 --- a/apps/effectcraft/Cargo.toml +++ b/apps/effectcraft/Cargo.toml @@ -41,6 +41,9 @@ zbus = "5.19" # Icon + VERSIONINFO for effectcraft.exe; build.rs only uses it when targeting Windows. winresource = "0.1" +[dev-dependencies] +tempfile = { workspace = true } + [target.'cfg(target_os = "macos")'.dependencies] # Keep the control channel responsive when the window is covered (App Nap / occlusion throttling). objc2-foundation = { version = "0.3", default-features = false, features = ["std", "NSProcessInfo", "NSString", "NSObject"] } diff --git a/apps/effectcraft/src/crash_report.rs b/apps/effectcraft/src/crash_report.rs index 6ca42aab7..3080c12bb 100644 --- a/apps/effectcraft/src/crash_report.rs +++ b/apps/effectcraft/src/crash_report.rs @@ -426,6 +426,7 @@ mod tests { } fn helper_mode(dir: &Path, id: &str, interactive: bool) -> Reporter { + let _spawn_lock = crate::test_child_spawn_lock(); let mut child = Command::new(std::env::current_exe().unwrap()) .args(["--exact", &test_name("reporter_process"), "--ignored", "--nocapture"]) .env(ROLE, "reporter") @@ -550,6 +551,7 @@ mod tests { #[test] fn accepted_native_close_finishes_before_process_termination() { let dir = folder(); + let _spawn_lock = crate::test_child_spawn_lock(); let status = Command::new(std::env::current_exe().unwrap()) .args(["--exact", &test_name("aborting_parent"), "--ignored", "--nocapture"]) .env(ROLE, "native-close") @@ -595,6 +597,7 @@ mod tests { #[test] fn an_aborting_parent_leaves_one_diagnostic_report() { let dir = folder(); + let _spawn_lock = crate::test_child_spawn_lock(); let status = Command::new(std::env::current_exe().unwrap()) .args(["--exact", &test_name("aborting_parent"), "--ignored", "--nocapture"]) .env(ROLE, "abort") @@ -616,6 +619,7 @@ mod tests { fn an_unrelated_child_does_not_keep_the_control_pipe_open() { let dir = folder(); let r = helper(&dir, "5-1"); + let _spawn_lock = crate::test_child_spawn_lock(); let mut unrelated = Command::new(std::env::current_exe().unwrap()) .args(["--exact", &test_name("lingering_child"), "--ignored", "--nocapture"]) .env(ROLE, "linger") @@ -632,6 +636,7 @@ mod tests { #[test] fn an_unresponsive_helper_cannot_hang_clean_shutdown() { + let _spawn_lock = crate::test_child_spawn_lock(); let mut child = Command::new(std::env::current_exe().unwrap()) .args(["--exact", &test_name("lingering_child"), "--ignored", "--nocapture"]) .env(ROLE, "linger") @@ -704,6 +709,7 @@ mod tests { #[cfg(windows)] fn windows_report_preserves_real_unsigned_exit_bits() { let dir = folder(); + let _spawn_lock = crate::test_child_spawn_lock(); let status = Command::new(std::env::current_exe().unwrap()) .args(["--exact", &test_name("aborting_parent"), "--ignored", "--nocapture"]) .env(ROLE, "windows-status") diff --git a/apps/effectcraft/src/file_dialogs.rs b/apps/effectcraft/src/file_dialogs.rs new file mode 100644 index 000000000..9f3114367 --- /dev/null +++ b/apps/effectcraft/src/file_dialogs.rs @@ -0,0 +1,375 @@ +//! Every native dialog the desktop app opens (rfd), through one path: [`guarded`]. +//! +//! [`guarded`] opens a dialog only on the main thread and catches a panic while it is made, so a +//! dialog that can't open becomes an error in the status line instead of taking the app, and +//! the open project, down with it. On macOS rfd makes the panel with `+[NSOpenPanel openPanel]`, +//! and objc2's binding panics when AppKit returns nil there (#3084). That panic used to unwind +//! out of the frame into winit's AppKit callback, which stops the app and re-raises it: the app +//! quit. The engine's last-resort guard (`effectcraft_engine::guard`) didn't catch it because it +//! wraps the commands only; a command that needs a path returns at once and its dialog opens +//! later, at the end of the frame ([`show_asked`]), outside any command. +//! +//! The commands' dialogs don't block the frame (macOS and Linux, `Hooks::file_dialog_async`). +//! A blocking `rfd::FileDialog` runs a nested modal event loop inside eframe's frame, that is +//! inside winit's event handler. On macOS a file dragged over the window while that loop ran +//! re-entered winit's handler, which panics across the Objective-C boundary and aborts the app +//! (#511). On Linux the blocking dialog is worse than slow: rfd uses the XDG desktop portal, so +//! the main thread sits waiting on the portal's answer and never pumps winit's events — the +//! window stops answering the compositor and the desktop offers to force-quit the app while the +//! Open dialog is up (#1275). `rfd::AsyncFileDialog` shows the dialog as a sheet on the window +//! (macOS) or through the portal from a worker thread (Linux) and returns at once; the answer +//! arrives when the dialog closes, outside the frame, and the app runs the command then. +//! +//! The panels' own pickers (Settings paths, Effect Controls, the shortcut editor) still use the +//! blocking hooks [`install_pickers`] sets; they go through [`guarded`] as well. + +use effectcraft_ui_egui::{DialogDone, EffectcraftApp, FileDialog}; +use rfd::{AsyncFileDialog, FileHandle}; +use std::future::Future; +use std::panic::AssertUnwindSafe; +use std::pin::Pin; +use std::sync::mpsc::{Receiver, Sender}; +use std::sync::{Arc, Mutex, PoisonError}; + +type Answer = Pin> + Send>>; + +/// A command's dialog waiting for [`show_asked`]. +pub type Asked = (FileDialog, DialogDone); + +/// Open dialog `what` (its title, for the error) with `open`: on the main thread only, and a +/// panic while it opens is an error instead of a crash (#3084). +pub fn guarded(what: &str, open: impl FnOnce() -> T) -> Result { + guarded_on(on_main_thread(), what, open) +} + +/// Whether this is the thread AppKit's panels belong to. AppKit makes panels on the main thread +/// only, and rfd would block this thread on the main one to get there; the hooks aren't `Send`, +/// so the app only ever asks from the main thread. Other platforms' dialogs open on any thread. +fn on_main_thread() -> bool { + #[cfg(target_os = "macos")] + { + objc2::MainThreadMarker::new().is_some() + } + #[cfg(not(target_os = "macos"))] + { + true + } +} + +fn guarded_on(main_thread: bool, what: &str, open: impl FnOnce() -> T) -> Result { + if !main_thread { + log::error!("{what} dialog: asked for off the main thread"); + return Err(couldnt_open(what, "it was asked for off the main thread")); + } + std::panic::catch_unwind(AssertUnwindSafe(open)).map_err(|payload| { + // The panic hook has logged the panic and where it happened. + let why = panic_message(payload.as_ref()); + log::error!("{what} dialog: {why}"); + couldnt_open(what, &why) + }) +} + +fn couldnt_open(what: &str, why: &str) -> String { + format!("The system's {what} dialog couldn't be created ({why}). Your project is still open.") +} + +fn panic_message(payload: &(dyn std::any::Any + Send)) -> String { + payload.downcast_ref::<&str>().map(|s| s.to_string()).or_else(|| payload.downcast_ref::().cloned()).unwrap_or_else(|| "internal error".into()) +} + +/// Where a blocking picker's error goes: the status line, through `Desktop`, which `ctx` +/// wakes so it shows without waiting for input. +#[derive(Clone)] +struct Errors { + tx: Sender, + ctx: egui::Context, +} + +/// Run blocking dialog `what`; one that can't open sends why to `errors` and counts as +/// cancelled (the blocking hooks can't return an error). +fn blocking(errors: &Errors, what: &str, open: impl FnOnce() -> Option) -> Option { + blocking_on(errors, what, on_main_thread(), open) +} + +fn blocking_on(errors: &Errors, what: &str, main_thread: bool, open: impl FnOnce() -> Option) -> Option { + guarded_on(main_thread, what, open).unwrap_or_else(|e| { + let _ = errors.tx.send(e); + errors.ctx.request_repaint(); + None + }) +} + +fn path_string(p: std::path::PathBuf) -> String { + p.to_string_lossy().to_string() +} + +/// Install the blocking pickers (`Hooks::pick_files` and friends), each through [`guarded`]. +/// Returns where the errors of those that couldn't open arrive, for the status line; `ctx` is +/// woken when one does. +pub fn install_pickers(app: &mut EffectcraftApp, ctx: &egui::Context) -> Receiver { + let (tx, rx) = std::sync::mpsc::channel::(); + let tx = Errors { tx, ctx: ctx.clone() }; + let errors = tx.clone(); + app.hooks.pick_files = Some(Box::new(move |exts: &[&str]| { + blocking(&errors, "Open", || rfd::FileDialog::new().add_filter("Media", exts).pick_files()).unwrap_or_default().into_iter().map(path_string).collect() + })); + let errors = tx.clone(); + app.hooks.pick_save = Some(Box::new(move |name: &str| { + blocking(&errors, "Save", || rfd::FileDialog::new().add_filter("EffectCraft Project", &["ecproj"]).set_file_name(name).save_file()).map(path_string) + })); + let errors = tx.clone(); + app.hooks.pick_open_project = Some(Box::new(move || { + blocking(&errors, "Open", || rfd::FileDialog::new().add_filter("EffectCraft Project", &["ecproj", "ecprojx"]).pick_file()).map(path_string) + })); + let errors = tx.clone(); + app.hooks.pick_folder = Some(Box::new(move || blocking(&errors, "Choose Folder", || rfd::FileDialog::new().pick_folder()).map(path_string))); + let errors = tx; + app.hooks.pick_save_file = Some(Box::new(move |name: &str, ext: &str| { + blocking(&errors, "Save", || { + // A default with a folder that exists opens the dialog there. + let path = std::path::Path::new(name); + // (No filter for a name without an extension, such as a folder to create.) + let mut d = if ext.is_empty() { rfd::FileDialog::new() } else { rfd::FileDialog::new().add_filter(ext, &[ext]) }; + if let Some(dir) = path.parent().filter(|d| d.is_dir()) { + d = d.set_directory(dir); + } + let file = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + d.set_file_name(file).save_file() + }) + .map(path_string) + })); + rx +} + +/// An error message box, through [`guarded`] (one that can't open is logged). +pub fn message(title: &str, description: String) { + let shown = guarded("message", || rfd::MessageDialog::new().set_level(rfd::MessageLevel::Error).set_title(title).set_description(description).show()); + if let Err(e) = shown { + // The diagnostic helper runs before logging is installed. + if log::log_enabled!(log::Level::Error) { + log::error!("{e}"); + } else { + eprintln!("effectcraft: {e}"); + } + } +} + +/// Show the dialogs the commands asked for in this frame (on the main thread: a sheet opens +/// here) and hand each one's paths to its `done` once it closes, then wake the UI. +/// +/// On macOS the sheet goes on the main window (`frame`'s). Without a parent rfd puts it on +/// AppKit's main window, which is a floating panel's OS window after a click in one; that +/// window hides while the app has no focused window, and a sheet whose window goes away ends +/// without answering, with later sheets queued behind it on the same window. +pub fn show_asked(asked: &Receiver, frame: &eframe::Frame, ctx: &egui::Context) { + while let Ok((dialog, done)) = asked.try_recv() { + show(dialog, done, ctx.clone(), |dialog| open(dialog, frame)); + } +} + +/// The dialog's title, for errors. +fn title(dialog: &FileDialog) -> &'static str { + match dialog { + FileDialog::Open { .. } | FileDialog::OpenProject => "Open", + FileDialog::Folder => "Choose Folder", + FileDialog::Save { .. } => "Save", + } +} + +/// Open `dialog` with `open` through [`guarded`] and wait for its answer on a worker thread. +/// `done` always gets an answer: the paths, or why the dialog couldn't open or answer. +fn show(dialog: FileDialog, done: DialogDone, ctx: egui::Context, open: impl FnOnce(FileDialog) -> Answer) { + show_on(dialog, done, ctx, on_main_thread(), open); +} + +fn show_on(dialog: FileDialog, done: DialogDone, ctx: egui::Context, main_thread: bool, open: impl FnOnce(FileDialog) -> Answer) { + let what = title(&dialog); + let answer = match guarded_on(main_thread, what, || open(dialog)) { + Ok(answer) => answer, + Err(e) => { + done(Err(e)); + ctx.request_repaint(); + return; + } + }; + // Kept here too, so a worker that can't start still answers. + let done = Arc::new(Mutex::new(Some(done))); + let take = |done: &Mutex>| done.lock().unwrap_or_else(PoisonError::into_inner).take(); + let (worker_done, worker_ctx) = (done.clone(), ctx.clone()); + let spawned = std::thread::Builder::new().name("ec-file-dialog".into()).spawn(move || { + let paths = std::panic::catch_unwind(AssertUnwindSafe(|| pollster::block_on(answer))).map_err(|payload| { + let why = panic_message(payload.as_ref()); + log::error!("{what} dialog: {why}"); + format!("The system's {what} dialog stopped without an answer ({why}). Your project is still open.") + }); + if let Some(done) = take(&worker_done) { + done(paths); + } + worker_ctx.request_repaint(); + }); + if let Err(e) = spawned { + log::error!("file dialog: {e}"); + if let Some(done) = take(&done) { + done(Err(couldnt_open(what, &e.to_string()))); + } + ctx.request_repaint(); + } +} + +/// A dialog on the main window. Linux keeps the portal's dialog unparented: rfd exports the +/// window for the portal from the dialog's worker thread there. +fn parented(frame: &eframe::Frame) -> AsyncFileDialog { + let d = AsyncFileDialog::new(); + if cfg!(target_os = "macos") { d.set_parent(frame) } else { d } +} + +fn paths(files: Option>) -> Vec { + files.unwrap_or_default().into_iter().map(|f| f.path().to_string_lossy().to_string()).collect() +} + +fn path(file: Option) -> Vec { + paths(file.map(|f| vec![f])) +} + +/// The dialog, as the blocking hooks show it. On macOS rfd makes the panel here, before the +/// future is returned, so a panel AppKit can't make panics here, inside [`guarded`]. +/// +/// No blocking fallback when that fails: rfd's app-modal dialog makes its panel with the same +/// `+[NSOpenPanel openPanel]`, so it would fail the same way, and it would bring back the +/// nested modal loop of #511. What [`guarded`] can't reach: rfd's own panics inside AppKit's +/// completion handler (its `URL().unwrap()`, or a poisoned lock of its future's state) run +/// under an Objective-C callback and still abort; only rfd can fix those. +fn open(dialog: FileDialog, frame: &eframe::Frame) -> Answer { + match dialog { + FileDialog::Open { exts, many } => { + let d = parented(frame).add_filter("Media", &exts); + if many { + let f = d.pick_files(); + Box::pin(async move { paths(f.await) }) + } else { + let f = d.pick_file(); + Box::pin(async move { path(f.await) }) + } + } + FileDialog::OpenProject => { + let f = parented(frame).add_filter("EffectCraft Project", &["ecproj", "ecprojx"]).pick_file(); + Box::pin(async move { path(f.await) }) + } + FileDialog::Folder => { + let f = parented(frame).pick_folder(); + Box::pin(async move { path(f.await) }) + } + FileDialog::Save { default, ext, project } => { + let at = std::path::Path::new(&default); + let name = at.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); + let mut d = if project { + parented(frame).add_filter("EffectCraft Project", &["ecproj"]) + } else if ext.is_empty() { + parented(frame) + } else { + parented(frame).add_filter(&ext, &[ext.as_str()]) + }; + // A default with a folder that exists opens the dialog there. + if let Some(dir) = at.parent().filter(|d| d.is_dir()) { + d = d.set_directory(dir); + } + let f = d.set_file_name(name).save_file(); + Box::pin(async move { path(f.await) }) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::mpsc::channel; + use std::time::Duration; + + /// The panic objc2 raises when AppKit returns nil for the panel (#3084). + const NIL_PANEL: &str = "unexpected NULL returned from +[NSOpenPanel openPanel]"; + + fn answered(dialog: FileDialog, open: impl FnOnce(FileDialog) -> Answer) -> Result, String> { + let (tx, rx) = channel(); + show_on(dialog, Box::new(move |r| tx.send(r).unwrap()), egui::Context::default(), true, open); + rx.recv_timeout(Duration::from_secs(10)).expect("the dialog answers") + } + + /// #3084: a panel AppKit can't make panics inside rfd; the command's dialog answers with + /// the error instead, and the panic doesn't leave the frame. + #[test] + fn a_panel_that_cannot_be_made_answers_with_an_error() { + let r = answered(FileDialog::Open { exts: vec!["aep".into(), "aepx".into()], many: false }, |_| panic!("{NIL_PANEL}")); + let e = r.unwrap_err(); + assert!(e.starts_with("The system's Open dialog couldn't be created") && e.contains(NIL_PANEL) && e.contains("still open"), "{e}"); + let e = answered(FileDialog::Folder, |_| std::panic::panic_any(7_u8)).unwrap_err(); + assert!(e.contains("Choose Folder") && e.contains("internal error"), "{e}"); + } + + /// A dialog that opens answers with its paths from the worker thread; one whose answer + /// panics answers with an error rather than never. + #[test] + fn a_dialog_that_opens_answers_with_its_paths() { + let r = answered(FileDialog::OpenProject, |_| Box::pin(async { vec!["/a/b.ecproj".to_string()] })); + assert_eq!(r, Ok(vec!["/a/b.ecproj".to_string()])); + assert_eq!(answered(FileDialog::save("Frame.png"), |_| Box::pin(async { Vec::new() })), Ok(Vec::new()), "cancelled"); + fn lost() -> Vec { + panic!("lost the sheet") + } + let e = answered(FileDialog::OpenProject, |_| Box::pin(async { lost() })).unwrap_err(); + assert!(e.contains("stopped without an answer") && e.contains("lost the sheet"), "{e}"); + } + + /// Off the main thread a dialog isn't opened at all (AppKit makes panels on the main thread + /// only); a panic while one opens is an error; an answer passes through. + #[test] + fn guarded_opens_on_the_main_thread_and_catches_panics() { + let mut opened = false; + let e = guarded_on(false, "Open", || opened = true).unwrap_err(); + assert!(!opened && e.contains("off the main thread"), "{e}"); + assert_eq!(guarded_on(true, "Open", || 5), Ok(5)); + let e = guarded_on(true, "Save", || -> u8 { panic!("{NIL_PANEL}") }).unwrap_err(); + assert!(e.contains("Save") && e.contains(NIL_PANEL), "{e}"); + } + + /// A blocking picker that can't open counts as cancelled and reports why. + #[test] + fn a_blocking_picker_that_cannot_open_reports_why() { + let (tx, rx) = channel(); + let tx = Errors { tx, ctx: egui::Context::default() }; + assert_eq!(blocking_on(&tx, "Open", true, || -> Option { panic!("{NIL_PANEL}") }), None); + assert!(rx.try_recv().is_ok_and(|e| e.contains(NIL_PANEL))); + assert_eq!(blocking_on(&tx, "Open", true, || Some(3)), Some(3)); + assert!(rx.try_recv().is_err(), "nothing to report"); + assert_eq!(blocking_on(&tx, "Open", false, || Some(5)), None); + assert!(rx.try_recv().is_ok_and(|e| e.contains("off the main thread"))); + } + + /// #3084: every rfd dialog in the desktop app goes through this module (and so through + /// [`guarded`]); no other source file opens one directly. + #[test] + fn every_dialog_opens_through_this_module() { + let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src"); + let mut files = vec![]; + let mut dirs = vec![src]; + while let Some(dir) = dirs.pop() { + for entry in std::fs::read_dir(dir).unwrap() { + let path = entry.unwrap().path(); + if path.is_dir() { + dirs.push(path); + } else if path.extension().is_some_and(|e| e == "rs") { + files.push(path); + } + } + } + assert!(files.len() > 3, "{files:?}"); + let exempt = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src").join("file_dialogs.rs"); + assert!(files.contains(&exempt)); + // `rfd` as a word: a path, a `use`, an alias or `extern crate`. + let word = |c: Option| c.is_some_and(|c| c.is_alphanumeric() || c == '_'); + for file in files.iter().filter(|f| **f != exempt) { + let text = std::fs::read_to_string(file).unwrap(); + let named = text.match_indices("rfd").any(|(i, _)| !word(text[..i].chars().next_back()) && !word(text[i + 3..].chars().next())); + assert!(!named, "{}: open dialogs through `file_dialogs` (#3084)", file.display()); + } + } +} diff --git a/apps/effectcraft/src/launch_guard.rs b/apps/effectcraft/src/launch_guard.rs index 2656179ac..85d1fdd57 100644 --- a/apps/effectcraft/src/launch_guard.rs +++ b/apps/effectcraft/src/launch_guard.rs @@ -214,8 +214,8 @@ mod tests { /// A launch that never drew switches the next one to OpenGL, which then stays (#243). #[test] fn a_launch_that_never_drew_switches_the_next_to_opengl() { - let dir = std::env::temp_dir().join(format!("ec-launch-guard-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let _spawn_lock = crate::test_child_spawn_lock(); + let dir = fresh_dir("never-drew"); // A first launch that draws: nothing changes. Its first frames don't settle it (a driver // may still crash as the window is shown); frames for `SETTLE` do. let mut l = Launch::begin(Some(&dir), false); @@ -259,8 +259,8 @@ mod tests { /// normal quit in that time doesn't. #[test] fn a_launch_that_stops_after_its_first_frame_switches_the_next_to_opengl() { - let dir = std::env::temp_dir().join(format!("ec-launch-guard-3-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let _spawn_lock = crate::test_child_spawn_lock(); + let dir = fresh_dir("first-frame"); let mut l = Launch::begin(Some(&dir), false); assert!(l.frame_drawn().is_some()); drop(l); @@ -286,8 +286,8 @@ mod tests { /// open a window either goes back to Automatic instead of failing every launch. #[test] fn a_second_copy_or_failed_opengl_doesnt_strand_window_graphics() { - let dir = std::env::temp_dir().join(format!("ec-launch-guard-2-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); + let _spawn_lock = crate::test_child_spawn_lock(); + let dir = fresh_dir("second-copy"); let _first = Launch::begin(Some(&dir), false); assert_eq!(Launch::begin(Some(&dir), false).backends, None); assert_eq!(window_graphics(&dir), "auto"); @@ -303,10 +303,7 @@ mod tests { /// A fresh settings folder for one test. fn fresh_dir(case: &str) -> PathBuf { - let dir = std::env::temp_dir().join(format!("ec-launch-guard-{case}-{}", std::process::id())); - let _ = std::fs::remove_dir_all(&dir); - std::fs::create_dir_all(&dir).unwrap(); - dir + tempfile::Builder::new().prefix(&format!("ec-launch-guard-{case}-")).tempdir().unwrap().keep() } /// Window Graphics saved as OpenGL. @@ -318,6 +315,7 @@ mod tests { #[test] fn a_second_copy_reports_the_saved_backend_without_owning_the_guard() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("second-source"); save_opengl(&dir); let mut first = Launch::begin(Some(&dir), false); @@ -333,6 +331,7 @@ mod tests { /// one's marker (#477). #[test] fn a_second_copy_quitting_leaves_the_running_launchs_marker() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("second-quits"); let mut first = Launch::begin(Some(&dir), false); let mut second = Launch::begin(Some(&dir), false); @@ -346,6 +345,7 @@ mod tests { /// A second copy whose OpenGL window fails doesn't remove a running launch's marker. #[test] fn failed_opengl_in_a_second_copy_leaves_the_running_launchs_marker() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("second-gl-fails"); let mut first = Launch::begin(Some(&dir), false); let second = Launch::begin(Some(&dir), false); @@ -360,6 +360,7 @@ mod tests { /// With `WGPU_BACKEND` set, a stale marker and a saved OpenGL choice are left as they are. #[test] fn wgpu_backend_leaves_a_stale_marker_and_saved_opengl_alone() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("env-override"); save_opengl(&dir); std::fs::write(dir.join(MARKER), b"stale-marker").unwrap(); @@ -376,6 +377,7 @@ mod tests { /// After OpenGL fails to open a window, the next launch is back on Automatic, without a notice. #[test] fn failed_opengl_puts_the_next_launch_back_on_automatic() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("gl-recovers"); save_opengl(&dir); let l = Launch::begin(Some(&dir), false); @@ -396,6 +398,7 @@ mod tests { #[cfg(unix)] #[test] fn the_guard_file_stays_the_same_file_across_launches() { + let _spawn_lock = crate::test_child_spawn_lock(); use std::os::unix::fs::MetadataExt; let dir = fresh_dir("guard-identity"); let mut a = Launch::begin(Some(&dir), false); @@ -417,6 +420,7 @@ mod tests { /// A second copy's frames and quit neither settle nor unlock the running launch. #[test] fn a_second_copys_frames_dont_settle_the_running_launch() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("second-frames"); let mut a = Launch::begin(Some(&dir), false); std::fs::write(dir.join(MARKER), b"owner-marker").unwrap(); @@ -438,6 +442,7 @@ mod tests { /// once it has stopped without settling the next launch still switches to OpenGL. #[test] fn a_running_older_version_holding_the_marker_is_left_alone() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("older-version"); std::fs::write(dir.join(MARKER), b"old-owner").unwrap(); std::fs::write(dir.join(PREFS_FILE), Prefs::default().to_json()).unwrap(); @@ -468,6 +473,7 @@ mod tests { #[cfg(windows)] #[test] fn an_unopenable_marker_leaves_settings_and_marker_alone() { + let _spawn_lock = crate::test_child_spawn_lock(); use std::os::windows::fs::OpenOptionsExt; let dir = fresh_dir("marker-unopenable"); @@ -491,6 +497,7 @@ mod tests { /// A guard file that can't be opened leaves Window Graphics and the marker as they are. #[test] fn an_unusable_guard_file_leaves_settings_and_marker_alone() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("guard-unusable"); std::fs::create_dir(dir.join(LOCK)).unwrap(); std::fs::write(dir.join(MARKER), b"stale-marker").unwrap(); @@ -512,6 +519,7 @@ mod tests { /// Window Graphics to Automatic and removes the marker. #[test] fn failed_opengl_cleanup_waits_for_the_running_launch() { + let _spawn_lock = crate::test_child_spawn_lock(); let dir = fresh_dir("gl-cleanup-waits"); save_opengl(&dir); let launch = Launch::begin(Some(&dir), false); diff --git a/apps/effectcraft/src/main.rs b/apps/effectcraft/src/main.rs index 5a602adcb..61554858f 100644 --- a/apps/effectcraft/src/main.rs +++ b/apps/effectcraft/src/main.rs @@ -27,14 +27,26 @@ mod diagnostic_state; mod launch_guard; #[cfg(target_os = "macos")] mod native_menu; -// Built everywhere so it stays checked; the macOS and Linux apps use it. +// Every native dialog. Built everywhere; only the macOS and Linux apps show the commands' +// dialogs without blocking the frame. #[cfg_attr(not(any(target_os = "macos", target_os = "linux")), allow(dead_code))] -mod sheet_dialogs; +mod file_dialogs; mod window; use effectcraft_ui_egui::EffectcraftApp; use serde_json::json; +// On Unix, a subprocess briefly inherits every non-CLOFORK descriptor between fork and exec. +// The app's guard-lock tests hold an advisory lock while crash-reporter tests spawn child +// processes; coordinate just those intervals so an unrelated test child cannot extend a lock. +#[cfg(test)] +static TEST_CHILD_SPAWN_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +#[cfg(test)] +fn test_child_spawn_lock() -> std::sync::MutexGuard<'static, ()> { + TEST_CHILD_SPAWN_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner) +} + /// The app icon for the window, taskbar and Dock (assets/app-icon, regenerated by /// `packaging/icons.sh`). macOS gets the padded variant so it sits on Apple's icon grid in the Dock. /// The 256 px app icon (Windows, Linux; the AppImage's desktop integration installs it too). @@ -139,12 +151,12 @@ fn control_port(name: &str, value: Option<&str>) -> Result { /// answer without pumping events, so the window stops answering the compositor and the desktop /// offers to force-quit it while the Open dialog is up (#1275). Windows' blocking dialog pumps /// its own messages, so it keeps [`effectcraft_ui_egui::Hooks::pick_files`] and friends. -/// The dialogs asked for in a frame show at its end ([`sheet_dialogs::show_asked`]), where the +/// The dialogs asked for in a frame show at its end ([`file_dialogs::show_asked`]), where the /// main window's handle is at hand. -fn install_file_dialogs(app: &mut EffectcraftApp) -> Option> { +fn install_file_dialogs(app: &mut EffectcraftApp) -> Option> { #[cfg(any(target_os = "macos", target_os = "linux"))] { - let (tx, rx) = std::sync::mpsc::channel::(); + let (tx, rx) = std::sync::mpsc::channel::(); app.hooks.file_dialog_async = Some(Box::new(move |dialog, done| { if tx.send((dialog, done)).is_err() { log::error!("file dialog: the window is gone"); @@ -184,7 +196,7 @@ fn start_helpers_if_opted_in(session: &mut effectcraft_engine::Session) { fn main() -> eframe::Result { let args: Vec<_> = std::env::args_os().skip(1).collect(); if crash_report::maybe_run(&args, |description| { - rfd::MessageDialog::new().set_level(rfd::MessageLevel::Error).set_title("EffectCraft diagnostic report").set_description(description).show(); + file_dialogs::message("EffectCraft diagnostic report", description.to_owned()); }) { return Ok(()); } @@ -390,12 +402,9 @@ fn run_desktop(reporter: &crash_report::Shutdown) -> eframe::Result { { app.ui.status = note.into(); } - app.hooks.pick_files = Some(Box::new(|exts: &[&str]| { - rfd::FileDialog::new().add_filter("Media", exts).pick_files().unwrap_or_default().into_iter().map(|p| p.to_string_lossy().to_string()).collect() - })); - app.hooks.pick_save = Some(Box::new(|name: &str| { - rfd::FileDialog::new().add_filter("EffectCraft Project", &["ecproj"]).set_file_name(name).save_file().map(|p| p.to_string_lossy().to_string()) - })); + // Every dialog opens through `file_dialogs::guarded`: one that can't open is an error + // in the status line, not a crash (#3084). + let dialog_errors = file_dialogs::install_pickers(&mut app, &cc.egui_ctx); // The window closes after a lost graphics device (#591); say why, unless an agent drives // the app through the control channel. if control_port.is_none() { @@ -405,31 +414,15 @@ fn run_desktop(reporter: &crash_report::Shutdown) -> eframe::Result { Some(Err(e)) => format!("\n\nYour unsaved changes could not be saved ({e})."), None => String::new(), }; - rfd::MessageDialog::new() - .set_level(rfd::MessageLevel::Error) - .set_title("EffectCraft: graphics device lost") - .set_description(format!("The graphics driver stopped responding, so EffectCraft has to close.{saved}")) - .show(); + file_dialogs::message( + "EffectCraft: graphics device lost", + format!("The graphics driver stopped responding, so EffectCraft has to close.{saved}"), + ); })); } - app.hooks.pick_open_project = Some(Box::new(|| { - rfd::FileDialog::new().add_filter("EffectCraft Project", &["ecproj", "ecprojx"]).pick_file().map(|p| p.to_string_lossy().to_string()) - })); app.hooks.system_theme = appearance::service(); app.hooks.audio_device = Some(Box::new(audio_out::open)); app.hooks.audio_devices = Some(Box::new(audio_out::devices)); - app.hooks.pick_folder = Some(Box::new(|| rfd::FileDialog::new().pick_folder().map(|p| p.to_string_lossy().to_string()))); - app.hooks.pick_save_file = Some(Box::new(|name: &str, ext: &str| { - // A default with a folder that exists opens the dialog there. - let path = std::path::Path::new(name); - // (No filter for a name without an extension, such as a folder to create.) - let mut d = if ext.is_empty() { rfd::FileDialog::new() } else { rfd::FileDialog::new().add_filter(ext, &[ext]) }; - if let Some(dir) = path.parent().filter(|d| d.is_dir()) { - d = d.set_directory(dir); - } - let file = path.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); - d.set_file_name(file).save_file().map(|p| p.to_string_lossy().to_string()) - })); // The commands' file dialogs don't block the frame where the platform's backend // would (#511, #1275); see [`install_file_dialogs`]. let file_dialogs = install_file_dialogs(&mut app); @@ -451,6 +444,7 @@ fn run_desktop(reporter: &crash_report::Shutdown) -> eframe::Result { apple_events: apple_events.connect(&cc.egui_ctx), app, file_dialogs, + dialog_errors, window: window::Tracker::new(opened, saved_window, control_port.is_none()), launch, drawn: false, @@ -525,19 +519,16 @@ fn startup_failed(e: &eframe::Error, gl_next: bool) { } else { eprintln!("effectcraft: {message}"); } - let _ = rfd::MessageDialog::new() - .set_level(rfd::MessageLevel::Error) - .set_title("EffectCraft") - .set_description(message) - .set_buttons(rfd::MessageButtons::Ok) - .show(); + file_dialogs::message("EffectCraft", message); } /// The desktop app: the egui app plus, on macOS, the system menu bar. struct Desktop { app: EffectcraftApp, /// The commands' file dialogs, shown at the end of the frame that asked for them. - file_dialogs: Option>, + file_dialogs: Option>, + /// Why a blocking picker couldn't open (#3084), for the status line. + dialog_errors: std::sync::mpsc::Receiver, #[cfg(target_os = "macos")] menu: native_menu::NativeBar, /// Documents opened from Finder, the Dock or `open` (macOS). @@ -559,8 +550,11 @@ impl eframe::App for Desktop { self.menu.update(&mut self.app, ctx); self.app.tick(ctx, frame); self.app.finish_ime_logic(ctx); + while let Ok(e) = self.dialog_errors.try_recv() { + self.app.ui.status = e; + } if let Some(asked) = &self.file_dialogs { - sheet_dialogs::show_asked(asked, frame, ctx); + file_dialogs::show_asked(asked, frame, ctx); } effectcraft_ui_egui::panels::unsaved::quit_on_close(ctx); } @@ -568,7 +562,7 @@ impl eframe::App for Desktop { fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) { self.app.ui(ui, frame); if let Some(asked) = &self.file_dialogs { - sheet_dialogs::show_asked(asked, frame, ui.ctx()); + file_dialogs::show_asked(asked, frame, ui.ctx()); } self.window.frame(ui.ctx(), self.app.session.config.as_deref()); if !self.drawn { diff --git a/apps/effectcraft/src/sheet_dialogs.rs b/apps/effectcraft/src/sheet_dialogs.rs deleted file mode 100644 index 911870190..000000000 --- a/apps/effectcraft/src/sheet_dialogs.rs +++ /dev/null @@ -1,101 +0,0 @@ -//! File dialogs that don't block the frame (macOS and Linux), for `Hooks::file_dialog_async`. -//! -//! A blocking `rfd::FileDialog` runs a nested modal event loop inside eframe's frame, that is -//! inside winit's event handler. On macOS a file dragged over the window while that loop ran -//! re-entered winit's handler, which panics across the Objective-C boundary and aborts the app -//! (#511). On Linux the blocking dialog is worse than slow: rfd uses the XDG desktop portal, so -//! the main thread sits waiting on the portal's answer and never pumps winit's events — the -//! window stops answering the compositor and the desktop offers to force-quit the app while the -//! Open dialog is up (#1275). `rfd::AsyncFileDialog` shows the dialog as a sheet on the window -//! (macOS) or through the portal from a worker thread (Linux) and returns at once; the answer -//! arrives when the dialog closes, outside the frame, and the app runs the command then. - -use effectcraft_ui_egui::{DialogDone, FileDialog}; -use rfd::{AsyncFileDialog, FileHandle}; -use std::future::Future; -use std::pin::Pin; - -type Answer = Pin> + Send>>; - -/// A command's dialog waiting for [`show_asked`]. -pub type Asked = (FileDialog, DialogDone); - -/// Show the dialogs the commands asked for in this frame (on the main thread: a sheet opens -/// here) and hand each one's paths to its `done` once it closes, then wake the UI. -/// -/// On macOS the sheet goes on the main window (`frame`'s). Without a parent rfd puts it on -/// AppKit's main window, which is a floating panel's OS window after a click in one; that -/// window hides while the app has no focused window, and a sheet whose window goes away ends -/// without answering, with later sheets queued behind it on the same window. -pub fn show_asked(asked: &std::sync::mpsc::Receiver, frame: &eframe::Frame, ctx: &egui::Context) { - while let Ok((dialog, done)) = asked.try_recv() { - show(dialog, done, frame, ctx.clone()); - } -} - -fn show(dialog: FileDialog, done: DialogDone, frame: &eframe::Frame, ctx: egui::Context) { - let answer = open(dialog, frame); - let spawned = std::thread::Builder::new().name("ec-file-dialog".into()).spawn(move || { - done(pollster::block_on(answer)); - ctx.request_repaint(); - }); - if let Err(e) = spawned { - log::error!("file dialog: {e}"); - } -} - -/// A dialog on the main window. Linux keeps the portal's dialog unparented: rfd exports the -/// window for the portal from the dialog's worker thread there. -fn parented(frame: &eframe::Frame) -> AsyncFileDialog { - let d = AsyncFileDialog::new(); - if cfg!(target_os = "macos") { d.set_parent(frame) } else { d } -} - -fn paths(files: Option>) -> Vec { - files.unwrap_or_default().into_iter().map(|f| f.path().to_string_lossy().to_string()).collect() -} - -fn path(file: Option) -> Vec { - paths(file.map(|f| vec![f])) -} - -/// The dialog, as the blocking hooks in `main.rs` show it. -fn open(dialog: FileDialog, frame: &eframe::Frame) -> Answer { - match dialog { - FileDialog::Open { exts, many } => { - let d = parented(frame).add_filter("Media", &exts); - if many { - let f = d.pick_files(); - Box::pin(async move { paths(f.await) }) - } else { - let f = d.pick_file(); - Box::pin(async move { path(f.await) }) - } - } - FileDialog::OpenProject => { - let f = parented(frame).add_filter("EffectCraft Project", &["ecproj", "ecprojx"]).pick_file(); - Box::pin(async move { path(f.await) }) - } - FileDialog::Folder => { - let f = parented(frame).pick_folder(); - Box::pin(async move { path(f.await) }) - } - FileDialog::Save { default, ext, project } => { - let at = std::path::Path::new(&default); - let name = at.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); - let mut d = if project { - parented(frame).add_filter("EffectCraft Project", &["ecproj"]) - } else if ext.is_empty() { - parented(frame) - } else { - parented(frame).add_filter(&ext, &[ext.as_str()]) - }; - // A default with a folder that exists opens the dialog there. - if let Some(dir) = at.parent().filter(|d| d.is_dir()) { - d = d.set_directory(dir); - } - let f = d.set_file_name(name).save_file(); - Box::pin(async move { path(f.await) }) - } - } -} diff --git a/clippy.toml b/clippy.toml index 3522a15b6..a4200a0e1 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1,8 +1,8 @@ -allow-unwrap-in-tests = true -allow-expect-in-tests = true -allow-panic-in-tests = true -allow-indexing-slicing-in-tests = true -disallowed-types = [ - { path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" }, -] -cognitive-complexity-threshold = 30 +allow-unwrap-in-tests = true +allow-expect-in-tests = true +allow-panic-in-tests = true +allow-indexing-slicing-in-tests = true +disallowed-types = [ + { path = "egui::ComboBox", reason = "use craft_ui::ComboBox: egui's combo box menu can't grow back while open (egui#5225)" }, +] +cognitive-complexity-threshold = 30 diff --git a/contributors/people.toml b/contributors/people.toml index e9144f9ea..beb91a413 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -135,3 +135,6 @@ display_name = "Jonathan Cardoso" [people.nazar-gavrylyk] sync_github_name = true + +[people.andreaaazo] +sync_github_name = true diff --git a/crates/aep/Cargo.toml b/crates/aep/Cargo.toml index b1bf3f9fe..1189df8dc 100644 --- a/crates/aep/Cargo.toml +++ b/crates/aep/Cargo.toml @@ -10,18 +10,16 @@ rust-version.workspace = true workspace = true [dependencies] +craft-mime = { workspace = true } +craft-aep = { workspace = true } effectcraft-time = { workspace = true } effectcraft-color = { workspace = true } effectcraft-keyframe = { workspace = true } effectcraft-project = { workspace = true } effectcraft-effects = { workspace = true } +log = { workspace = true } serde = { workspace = true } thiserror = { workspace = true } [dev-dependencies] serde_json = { workspace = true } - -# The tool's own tests run with the crate's (examples are only built by default). -[[example]] -name = "stubicc" -test = true diff --git a/crates/aep/README.md b/crates/aep/README.md index 5e8035d8f..0e65d86f8 100644 --- a/crates/aep/README.md +++ b/crates/aep/README.md @@ -3,7 +3,9 @@ After Effects projects (`.aep`, `.aepx`) in one crate, the way `effectcraft-lottie` handles Lottie: - `container`: reads and writes the container as a lossless chunk tree, with a typed, read-only - view (below; its API is re-exported at the crate root); + view (below). This is `craft-aep` from [storytold/craft-libs](https://github.com/storytold/craft-libs), + re-exported at the crate root; its container tests and the `aepdump`/`stubicc` tools are there. + Only `effect_map` and `style_map` (After Effects effects and layer styles to EffectCraft's) are here; - `import`: maps the typed view into an EffectCraft project and reports everything it does not import ([`docs/aep-import.md`](../../docs/aep-import.md)); - `export`: writes an EffectCraft project as an `.aep` with every chunk built in code, and reports everything it does not export @@ -21,7 +23,9 @@ tree; pad bytes, odd bodies and the bytes after the container, an XMP packet, ar The XML form of a project (`.aepx`) is read into the same tree by `read_aepx` (a small bounded XML tokenizer, no dependency); `parse_any` picks the reader by content, so the typed view and the -importer take either form. The mapping is in `docs/aep-format.md`, section 1. +importer take either form. The mapping is in `docs/aep-format.md`, section 1. The importer, which +only reads, does not build the owned tree: it reads either form through the flat index +`TreeIndex`, an `.aep` in place and an `.aepx` decoded into one buffer first. Bodies that look like lists but are not chunk sequences (for example `LIST btdk`, raw text) stay opaque rather than failing the parse. Input is untrusted: sizes are checked against the remaining @@ -75,6 +79,10 @@ solid, a folder, a Levels and a Glow effect with expressions). Every After Effec the working space's ICC profile (HP sRGB IEC61966-2.1 for the default) in a JSON settings chunk; the one `Utf8` chunk of this file that held a profile was replaced by `{}`, and nothing else was changed. The tests in `tests/it/import/synthetic.rs` damage copies of it and need no other file. +`tests/fixtures/text-synthetic.aep` is the other: made in After Effects 2026 the same way (working +space None, nothing changed after the save), one composition with two text layers that hold a +text animator's Stroke Opacity (static and keyed) and Source Text expressions (enabled and +disabled); `tests/it/import/text_synthetic.rs` reads it (#3170). `tests/fixtures/ai-mask-3099.aep` (131 KB, #3099) is the second: four hand-written one-page PDFs named `.ai` with distinct page boxes, placed in a composition, one of them with two masks under a @@ -86,14 +94,9 @@ the import against After Effects' read-back, and the host's `vector_import` test - `tests/fixtures/tools/`: the generator of the test projects (regenerates the corpus with After Effects; its README says how). -- `examples/aepdump.rs`: prints the chunk tree of a file (ids, sizes, short data, match names): - `cargo run -p effectcraft-aep --example aepdump -- file.aep`. -- `examples/stubicc.rs`: replaces every embedded ICC profile of a saved project by a stub that keeps - only the profile's description: the JSON `colorProfileData` of the working space (any white space - around the colon, `\/` escapes, quotes as `"`) in an `.aep` chunk or the `.aepx` text, and a raw - profile of an imported image (an `.aep` chunk, or the `bdata` hex of an `.aepx`): - `cargo run -p effectcraft-aep --example stubicc -- in.aep out.aep`. A profile it cannot replace - stops it before anything is written. The importer reads the working space's name from the - description only, so the project imports the same; no vendor colour data stays in the test - project. Check the result independently, not by the tool's count (the corpus repository has - `tools/aep/inspect-embedded.py`, which scans the raw bytes, base64 and hex). +- `aepdump` (prints the chunk tree of a file) and `stubicc` (replaces every embedded ICC profile of a + saved project by a stub) are examples of `craft-aep` in + [storytold/craft-libs](https://github.com/storytold/craft-libs): + `cargo run -p craft-aep --example stubicc -- in.aep out.aep` there. Check the result independently, + not by the tool's count (the corpus repository has `tools/aep/inspect-embedded.py`, which scans the + raw bytes, base64 and hex). diff --git a/crates/aep/examples/aepdump.rs b/crates/aep/examples/aepdump.rs deleted file mode 100644 index 2fe492696..000000000 --- a/crates/aep/examples/aepdump.rs +++ /dev/null @@ -1,75 +0,0 @@ -//! Developer tool: prints the chunk tree of an .aep (ids, sizes, short data), match names inline. -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -use effectcraft_aep::{Body, Chunk}; - -/// Ends this developer tool with a message instead of a panic. -trait OrExit { - fn or_exit(self, what: &str) -> T; -} - -impl OrExit for Option { - fn or_exit(self, what: &str) -> T { - match self { - Some(v) => v, - None => exit(what), - } - } -} - -impl OrExit for Result { - fn or_exit(self, what: &str) -> T { - match self { - Ok(v) => v, - Err(e) => exit(&format!("{what}: {e:?}")), - } - } -} - -fn exit(msg: &str) -> ! { - eprintln!("{msg}"); - std::process::exit(1) -} - -fn show(c: &Chunk<'_>, depth: usize, max: usize, hex: usize) { - let ind = " ".repeat(depth); - let id = String::from_utf8_lossy(&c.id).to_string(); - match &c.body { - Body::Data(d) if &c.id == b"tdmn" => { - let n: String = d.iter().take_while(|b| **b != 0).map(|b| *b as char).collect(); - println!("{ind}tdmn {n}"); - } - Body::Data(d) => { - let h: String = d.iter().take(hex).map(|b| format!("{b:02x}")).collect(); - let a: String = d.iter().take(hex).map(|b| if (32..127).contains(b) { *b as char } else { '.' }).collect(); - println!("{ind}{id} [{}] {h} |{a}|", d.len()); - } - Body::Chunks(k) => { - println!("{ind}{id} (nested)"); - if depth < max { - for x in k { - show(x, depth + 1, max, hex); - } - } - } - Body::List { list_type, children } => { - println!("{ind}LIST {} ({} children)", String::from_utf8_lossy(list_type), children.len()); - if depth < max { - for x in children { - show(x, depth + 1, max, hex); - } - } - } - Body::OpaqueList { list_type, data } => println!("{ind}LIST {} opaque [{}]", String::from_utf8_lossy(list_type), data.len()), - } -} -fn main() { - let a: Vec = std::env::args().collect(); - let bytes = std::fs::read(a.get(1).or_exit("usage: see the comment at the top of this file")).or_exit("read"); - let max: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(4); - let hex: usize = a.get(3).and_then(|s| s.parse().ok()).unwrap_or(32); - let f = effectcraft_aep::parse(&bytes).or_exit("parse"); - for c in &f.chunks { - show(c, 0, max, hex); - } - println!("trailer {} bytes", f.trailer.len()); -} diff --git a/crates/aep/examples/stubicc.rs b/crates/aep/examples/stubicc.rs deleted file mode 100644 index 9438da06d..000000000 --- a/crates/aep/examples/stubicc.rs +++ /dev/null @@ -1,359 +0,0 @@ -//! Developer tool: replaces every embedded ICC profile of an .aep / .aepx by a stub that keeps only the -//! profile's description. Fixture hygiene: a saved project carries the vendor's working-space profile -//! (a few KB of colour data); the importer reads only the profile's name, the `desc` tag, so the stub -//! (a 128-byte header, one `desc` tag, no colour data, made here) imports identically. -//! -//! `cargo run -p effectcraft-aep --example stubicc -- in.aep out.aep` -//! -//! It handles: -//! - the JSON value `"colorProfileData": ""` in any chunk of an .aep and anywhere in the text -//! of an .aepx (white space around the colon, `\/` escapes and quotes written as `"` allowed); -//! - a raw ICC profile stored as a chunk of its own (the profile of an imported image), in an .aep -//! as the chunk's bytes and in an .aepx as its `bdata=""` attribute. -//! -//! A profile it cannot replace (no readable description, data that does not decode) stops the tool -//! before anything is written. Check the result independently (the corpus has -//! `tools/aep/inspect-embedded.py`), not by this tool's own count. -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] -use effectcraft_aep::{Body, Chunk}; - -const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -/// Ends this developer tool with a message instead of a panic. -trait OrExit { - fn or_exit(self, what: &str) -> T; -} - -impl OrExit for Option { - fn or_exit(self, what: &str) -> T { - match self { - Some(v) => v, - None => exit(what), - } - } -} - -impl OrExit for Result { - fn or_exit(self, what: &str) -> T { - match self { - Ok(v) => v, - Err(e) => exit(&format!("{what}: {e:?}")), - } - } -} - -fn exit(msg: &str) -> ! { - eprintln!("{msg}"); - std::process::exit(1) -} - -fn b64_decode(text: &[u8]) -> Option> { - let (mut out, mut acc, mut bits) = (Vec::new(), 0u32, 0u32); - for &c in text.iter().filter(|c| **c != b'=') { - let v = u32::try_from(B64.iter().position(|b| *b == c)?).ok()?; - acc = (acc << 6 | v) & 0x00ff_ffff; - bits += 6; - if bits >= 8 { - bits -= 8; - out.push(((acc >> bits) & 0xff) as u8); - } - } - Some(out) -} - -fn b64_encode(data: &[u8]) -> Vec { - let mut out = Vec::new(); - for ch in data.chunks(3) { - let at = |i: usize| u32::from(ch.get(i).copied().unwrap_or(0)); - let n = (at(0) << 16) | (at(1) << 8) | at(2); - for i in 0..4usize { - if i <= ch.len() { - out.push(B64.get(((n >> (18 - 6 * i)) & 63) as usize).copied().unwrap_or(b'A')); - } else { - out.push(b'='); - } - } - } - out -} - -fn be32(d: &[u8], at: usize) -> Option { - let b: [u8; 4] = d.get(at..at.checked_add(4)?)?.try_into().ok()?; - usize::try_from(u32::from_be_bytes(b)).ok() -} - -/// The profile description (ICC.1 `desc`: v2 ASCII or v4 `mluc`, first record). -fn description(icc: &[u8]) -> Option { - let count = be32(icc, 128)?; - let tag = (0..count.min(1024)).find_map(|i| { - let at = 132usize.checked_add(i.checked_mul(12)?)?; - (icc.get(at..at.checked_add(4)?)? == b"desc").then_some(at) - })?; - let off = be32(icc, tag.checked_add(4)?)?; - let body = icc.get(off..off.checked_add(be32(icc, tag.checked_add(8)?)?)?)?; - let text = match body.get(..4)? { - b"desc" => { - let n = be32(body, 8)?; - String::from_utf8_lossy(body.get(12..12usize.checked_add(n)?)?.split(|b| *b == 0).next()?).into_owned() - } - b"mluc" => { - let (n, at) = (be32(body, 20)?, be32(body, 24)?); - let units: Vec = body.get(at..at.checked_add(n)?)?.chunks(2).filter_map(|p| Some(u16::from_be_bytes([*p.first()?, *p.get(1)?]))).collect(); - String::from_utf16_lossy(&units) - } - _ => return None, - }; - Some(text.trim_end_matches('\0').trim().to_owned()) -} - -/// A profile with a header, one `desc` tag and no colour data. -fn stub(desc: &str) -> Option> { - let mut body = b"desc\0\0\0\0".to_vec(); - body.extend_from_slice(&u32::try_from(desc.len().checked_add(1)?).ok()?.to_be_bytes()); - body.extend_from_slice(desc.as_bytes()); - body.push(0); - body.extend_from_slice(&[0; 4 + 4 + 2 + 1 + 67]); - let mut p = vec![0u8; 128]; - for (at, v) in [(8, &0x0240_0000u32.to_be_bytes()[..]), (12, b"mntr"), (16, b"RGB "), (20, b"XYZ "), (36, b"acsp")] { - p.get_mut(at..at + v.len())?.copy_from_slice(v); - } - p.extend_from_slice(&1u32.to_be_bytes()); - p.extend_from_slice(b"desc"); - p.extend_from_slice(&144u32.to_be_bytes()); - p.extend_from_slice(&u32::try_from(body.len()).ok()?.to_be_bytes()); - p.extend_from_slice(&body); - let size = u32::try_from(p.len()).ok()?.to_be_bytes(); - p.get_mut(..4)?.copy_from_slice(&size); - Some(p) -} - -/// The JSON key, without its quotes. -const KEY: &[u8] = b"colorProfileData"; -/// How a JSON quote is written: as is (a `Utf8` chunk, the `` text of an .aepx) and as an -/// XML entity (JSON inside an attribute of an .aepx). -const QUOTES: [&[u8]; 2] = [b"\"", b"""]; - -/// What the tool did, counted. -#[derive(Default)] -struct Tally { - stubbed: usize, - /// Values too short to be a profile (no ICC header), kept as they are. - kept_short: usize, - /// Profiles that could not be replaced (no readable description, undecodable data): the tool - /// fails, so no profile is ever left behind silently. - failed: Vec, -} - -fn is_profile(d: &[u8]) -> bool { - d.len() > 132 && d.get(36..40) == Some(b"acsp") -} - -/// The stub for the bytes `d` of a value, or `None` (counted) when it holds no profile or the -/// profile has no readable description. -fn stub_of(d: &[u8], at: usize, tally: &mut Tally) -> Option> { - if !is_profile(d) { - tally.kept_short += 1; - return None; - } - let s = description(d).and_then(|t| stub(&t)); - if s.is_none() { - tally.failed.push(format!("profile at byte {at}: no readable description")); - } - s -} - -/// At the start of `t`: the key in quotes, optional white space, a colon, optional white space and -/// the opening quote of the value. Returns the length up to and including that quote, and the quote. -fn value_start(t: &[u8]) -> Option<(usize, &'static [u8])> { - let ws = |mut i: usize| { - while t.get(i).is_some_and(u8::is_ascii_whitespace) { - i += 1; - } - i - }; - QUOTES.into_iter().find_map(|q| { - let key_end = q.len().checked_mul(2)?.checked_add(KEY.len())?; - let quoted = t.get(..key_end)?; - if !(quoted.starts_with(q) && quoted.get(q.len()..q.len() + KEY.len())? == KEY && quoted.ends_with(q)) { - return None; - } - let colon = ws(key_end); - if t.get(colon) != Some(&b':') { - return None; - } - let open = ws(colon + 1); - t.get(open..)?.starts_with(q).then_some((open + q.len(), q)) - }) -} - -fn hex_decode(h: &[u8]) -> Option> { - if !h.len().is_multiple_of(2) { - return None; - } - h.chunks(2).map(|p| u8::from_str_radix(std::str::from_utf8(p).ok()?, 16).ok()).collect() -} - -fn hex_encode(d: &[u8], upper: bool) -> Vec { - d.iter().flat_map(|b| if upper { format!("{b:02X}") } else { format!("{b:02x}") }.into_bytes()).collect() -} - -/// Replaces, in `text`, every `colorProfileData` JSON value (base64; `\/` escapes, white space -/// around the colon and quotes written as `"` allowed) and every .aepx `bdata=""` -/// attribute that holds a raw profile. -fn stub_text(text: &[u8], tally: &mut Tally) -> Vec { - const BDATA: &[u8] = b"bdata=\""; - let (mut out, mut i) = (Vec::with_capacity(text.len()), 0); - while let Some(&b) = text.get(i) { - let rest = text.get(i..).unwrap_or_default(); - if let Some((open, q)) = value_start(rest) - && let Some(len) = rest.get(open..).and_then(|v| v.windows(q.len()).position(|w| w == q)) - { - let raw = rest.get(open..open + len).unwrap_or_default(); - let unescaped: Vec = raw.iter().copied().filter(|c| *c != b'\\').collect(); - let replaced = match b64_decode(&unescaped) { - Some(d) => stub_of(&d, i, tally).map(|s| b64_encode(&s)), - None => { - tally.failed.push(format!("colorProfileData at byte {i}: not base64")); - None - } - }; - out.extend_from_slice(rest.get(..open).unwrap_or_default()); - match replaced { - Some(enc) => { - out.extend_from_slice(&enc); - tally.stubbed += 1; - } - None => out.extend_from_slice(raw), - } - i += open + len; - continue; - } - if rest.starts_with(BDATA) - && let Some(len) = rest.get(BDATA.len()..).and_then(|v| v.iter().position(|c| *c == b'"')) - { - let hex = rest.get(BDATA.len()..BDATA.len() + len).unwrap_or_default(); - let replaced = hex_decode(hex).filter(|d| is_profile(d)).and_then(|d| stub_of(&d, i, tally)); - out.extend_from_slice(BDATA); - match replaced { - Some(s) => { - out.extend_from_slice(&hex_encode(&s, hex.iter().any(u8::is_ascii_uppercase))); - tally.stubbed += 1; - } - None => out.extend_from_slice(hex), - } - i += BDATA.len() + len; - continue; - } - out.push(b); - i += 1; - } - out -} - -fn walk(chunks: &mut [Chunk<'_>], tally: &mut Tally) { - for c in chunks.iter_mut() { - // Only a data chunk is rewritten as one: an opaque `LIST` also has bytes, but replacing it by - // a data chunk would drop its list type. - let data = if let Body::Data(d) = &c.body { Some(d.to_vec()) } else { None }; - match data { - Some(d) if d.windows(KEY.len()).any(|w| w == KEY) => { - let new = stub_text(&d, tally); - *c = Chunk::data(c.id, new); - } - Some(d) if is_profile(&d) => { - if let Some(s) = stub_of(&d, 0, tally) { - *c = Chunk::data(c.id, s); - tally.stubbed += 1; - } - } - _ => { - if let Body::List { children, .. } | Body::Chunks(children) = &mut c.body { - walk(children, tally); - } - } - } - } -} - -fn main() { - let args: Vec = std::env::args().collect(); - let (Some(input), Some(output)) = (args.get(1), args.get(2)) else { exit("usage: stubicc ") }; - let bytes = std::fs::read(input).or_exit("read the input"); - let mut tally = Tally::default(); - let out = if input.ends_with(".aepx") { - stub_text(&bytes, &mut tally) - } else { - let mut file = effectcraft_aep::parse(&bytes).or_exit("parse the input"); - walk(&mut file.chunks, &mut tally); - effectcraft_aep::write(&file).or_exit("write the output") - }; - if !tally.failed.is_empty() { - exit(&format!("nothing written: {} profile(s) could not be replaced:\n{}", tally.failed.len(), tally.failed.join("\n"))); - } - std::fs::write(output, out).or_exit("write the output"); - println!("stubbed {} profile(s); kept {} short value(s) that hold no profile", tally.stubbed, tally.kept_short); -} - -#[cfg(test)] -#[allow(clippy::unwrap_used)] -mod tests { - use super::*; - - fn profile(desc: &str) -> Vec { - // A profile with colour data after the description (like a real one): the stub of `desc` - // plus 3000 bytes, its size field updated. - let mut p = stub(desc).unwrap(); - p.extend(std::iter::repeat_n(0x5a, 3000)); - let size = u32::try_from(p.len()).unwrap().to_be_bytes(); - p[..4].copy_from_slice(&size); - p - } - - fn stubbed(text: &[u8]) -> (Vec, Tally) { - let mut tally = Tally::default(); - (stub_text(text, &mut tally), tally) - } - - #[test] - fn json_values_in_every_spelling_are_replaced() { - let b64 = String::from_utf8(b64_encode(&profile("sRGB IEC61966-2.1"))).unwrap(); - let want = String::from_utf8(b64_encode(&stub("sRGB IEC61966-2.1").unwrap())).unwrap(); - for (before, after) in [ - (format!("{{\"colorProfileData\":\"{b64}\"}}"), format!("{{\"colorProfileData\":\"{want}\"}}")), - (format!("{{\"colorProfileData\" : \n\t\"{b64}\"}}"), format!("{{\"colorProfileData\" : \n\t\"{want}\"}}")), - (format!("{{\"colorProfileData\":\"{}\"}}", b64.replace('/', "\\/")), format!("{{\"colorProfileData\":\"{want}\"}}")), - (format!("{{"colorProfileData": "{b64}"}}"), format!("{{"colorProfileData": "{want}"}}")), - ] { - let (out, tally) = stubbed(before.as_bytes()); - assert_eq!(String::from_utf8(out).unwrap(), after); - assert_eq!((tally.stubbed, tally.failed.len()), (1, 0)); - } - } - - #[test] - fn a_raw_profile_in_aepx_hex_is_replaced_and_other_hex_kept() { - let hex = String::from_utf8(hex_encode(&profile("Rec.709 Gamma 2.4"), false)).unwrap(); - let want = String::from_utf8(hex_encode(&stub("Rec.709 Gamma 2.4").unwrap(), false)).unwrap(); - let text = format!("", "ab".repeat(200)); - let (out, tally) = stubbed(text.as_bytes()); - assert_eq!(String::from_utf8(out).unwrap(), format!("", "ab".repeat(200))); - assert_eq!((tally.stubbed, tally.failed.len()), (1, 0)); - // Upper-case hex stays upper case. - let (out, _) = stubbed(format!("bdata=\"{}\"", hex.to_uppercase()).as_bytes()); - assert_eq!(String::from_utf8(out).unwrap(), format!("bdata=\"{}\"", want.to_uppercase())); - } - - #[test] - fn a_profile_that_cannot_be_replaced_is_a_failure_not_a_silent_copy() { - // An ICC header whose tag table has no `desc`. - let mut p = profile("x"); - p[132..136].copy_from_slice(b"wtpt"); - let (_, tally) = stubbed(format!("\"colorProfileData\":\"{}\"", String::from_utf8(b64_encode(&p)).unwrap()).as_bytes()); - assert_eq!((tally.stubbed, tally.failed.len()), (0, 1)); - let (_, tally) = stubbed(b"\"colorProfileData\":\"not*base64\""); - assert_eq!(tally.failed.len(), 1); - // A short value holds no profile: kept and counted, not a failure. - let (out, tally) = stubbed(b"\"colorProfileData\":\"AAAA\""); - assert_eq!((out.as_slice(), tally.kept_short, tally.failed.len()), (&b"\"colorProfileData\":\"AAAA\""[..], 1, 0)); - } -} diff --git a/crates/aep/src/container.rs b/crates/aep/src/container.rs index 77511fcf1..d9dbcfb14 100644 --- a/crates/aep/src/container.rs +++ b/crates/aep/src/container.rs @@ -1,61 +1,7 @@ -//! After Effects project (`.aep`) container reader and writer. -//! -//! An `.aep` is a `RIFX` container (big-endian RIFF) with form type `Egg!`. This crate reads it -//! into a lossless chunk tree ([`AepFile`]) and writes it back byte for byte. The XML form of a -//! project (`.aepx`) is read into the same tree by [`read_aepx`]; [`parse_any`] picks the reader -//! by content. See -//! `docs/aep-format.md` for the observed format and how it was established (clean room: only -//! files we generated ourselves, one change per file). -//! -//! [`Project::new`] opens a typed, read-only view over the tree: items, compositions -//! ([`CompHeader`]), layers ([`LayerHeader`], [`Transform`], effects, masks, text documents, -//! markers), properties, keyframes and footage. Only fields whose layout was verified against the -//! values the test files were made with are decoded; every accessor returns `None` (or an empty -//! list) on damaged data instead of failing. +//! The `.aep` / `.aepx` container and its typed view come from `craft-aep`; only the tables that map +//! After Effects effects and layer styles onto EffectCraft's are kept here. -mod aepx; -mod arbitrary; -mod bytes; -mod camera; -mod chunk; pub mod effect_map; -mod effects; -mod error; -mod footage; -mod header; -mod keys; -mod masks; -mod matte; -mod read; -mod settings; -mod shapes; pub mod style_map; -mod textdoc; -mod typed; -mod values; -mod version; -mod write; -pub use aepx::{is_aepx, parse_any, read_aepx, read_aepx_with_limits}; -pub use arbitrary::{ - CURVE_IDENTITY, CryptomatteData, CurvesData, ExtractorChannels, HueSaturationData, LevelsData, MeshData, curve_lut, identifier_channel_type, -}; -pub use camera::{CameraPosition, DEFAULT_CAMERA_ZOOM}; -pub use chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS, Walk}; -pub use effects::{DefinitionSource, Effect, EffectDefinitions, EffectParam, LayerRef, ParamKind, ParamValue}; -pub use error::AepError; -pub use footage::{Footage, PsdLayer, SequenceInfo}; -pub use header::{BlendMode, CompHeader, LayerHeader, LayerType, LightType, Quality, Rational, Renderer}; -pub use keys::{ExpressionFlags, Interpolation, KeyEase, KeyframeKind, SpatialKey}; -pub use masks::{Mask, MaskAtom, MaskMode, PathVertex, ShapePath}; -pub use matte::{MatteMode, TrackMatte}; -pub use read::{Limits, parse, parse_with_limits}; -pub use settings::{ProjectSettings, TimeDisplay, WorkingSpace}; -pub use shapes::{GradientType, PolystarType, ShapeDetail, ShapeGroup, ShapeItem, Stroke, StrokeCap, StrokeJoin}; -pub use textdoc::{ - AutoKern, Caps, CueType, FontBaseline, Justification, KernRun, Marker, ParagraphRun, StyleRun, TextBox, TextDocument, TextValue, parse_text_dict, -}; -pub use typed::{Comp, Item, ItemKind, KeyLayout, KeyList, Keyframe, Layer, ListHeader, Project, PropEntry, PropGroup, PropNode, Property, TimeBase}; -pub use values::{Orientation, OrientationKey, TimeRemap, TimeRemapKey, Tracked, Transform, ValueSource}; -pub use version::AeVersion; -pub use write::{write, write_to}; +pub use craft_aep::*; diff --git a/crates/aep/src/container/aepx.rs b/crates/aep/src/container/aepx.rs deleted file mode 100644 index a45cbae1d..000000000 --- a/crates/aep/src/container/aepx.rs +++ /dev/null @@ -1,640 +0,0 @@ -//! Reading the XML form of a project (`.aepx`) into the same chunk tree as an `.aep`. -//! -//! An `.aepx` is the `RIFX` chunk tree written as XML: one element per chunk, named by the chunk -//! id (or the list type of a `LIST`), with the body as hex in a `bdata` attribute. A few chunks -//! are written as text instead (`Utf8` as ``, the numbers `numS` and `ppSn`, the footage -//! alias `alas` as ``), and the XMP packet that follows the container of an `.aep` -//! is the element ``. The mapping, with the cases it was found on, is in -//! `docs/aep-format.md` (section 1.1). -//! -//! The reader is a small XML tokenizer for exactly that subset: elements, attributes, text, the -//! five predefined entities and character references, CDATA, comments and processing -//! instructions. A document type declaration is refused (no entity expansion). It runs without -//! recursion; the nesting depth and the element count are bounded by [`Limits`], and everything -//! it allocates is bounded by the size of the input. - -use std::borrow::Cow; - -use crate::container::chunk::{AepFile, Body, Chunk, LIST, NESTED_IDS}; -use crate::container::error::AepError; -use crate::container::read::{Limits, parse}; - -/// The root element of an `.aepx`. -const ROOT: &[u8] = b"AfterEffectsProject"; -/// The element that holds the XMP packet (the trailer of an `.aep`). -const XMP: &[u8] = b"ProjectXMPMetadata"; -/// The element of a `Utf8` chunk. -const STRING: &[u8] = b"string"; -/// The element of an `alas` chunk (footage alias), written as attributes instead of JSON. -const FILE_REFERENCE: &[u8] = b"fileReference"; - -/// List types whose body is not a chunk sequence: the `.aepx` writes them like data chunks (with -/// `bdata`), the `.aep` as an opaque `LIST`. -const OPAQUE_LIST_TYPES: [[u8; 4]; 1] = [*b"btdk"]; - -/// True when `data` looks like an `.aepx`: optional UTF-8 byte order mark and white space, then -/// an XML declaration or the `AfterEffectsProject` root element. -pub fn is_aepx(data: &[u8]) -> bool { - let rest = data.strip_prefix(&[0xef, 0xbb, 0xbf][..]).unwrap_or(data); - let start = rest.iter().position(|b| !b.is_ascii_whitespace()).unwrap_or(rest.len()); - let rest = rest.get(start..).unwrap_or(&[]); - rest.starts_with(b" Result, AepError> { - if is_aepx(data) { read_aepx(data) } else { parse(data) } -} - -/// Reads an `.aepx` with the default [`Limits`] into the chunk tree an `.aep` of the same project -/// gives. -/// -/// # Errors -/// [`AepError::Xml`] for input that is not well-formed XML of the `.aepx` subset (bad UTF-8, an -/// unknown entity, an unclosed or mismatched tag, invalid or odd-length hex, a number that does -/// not parse, a document type declaration, a root element other than `AfterEffectsProject`); -/// [`AepError::TooDeep`] / [`AepError::TooManyChunks`] beyond the limits. -pub fn read_aepx(data: &[u8]) -> Result, AepError> { - read_aepx_with_limits(data, Limits::default()) -} - -/// Like [`read_aepx`] with explicit [`Limits`]: `max_depth` bounds the element nesting (the root -/// element's children are depth 1), `max_chunks` the number of elements. -/// -/// # Errors -/// See [`read_aepx`]. -pub fn read_aepx_with_limits(data: &[u8], limits: Limits) -> Result, AepError> { - let text = match std::str::from_utf8(data) { - Ok(t) => t.as_bytes(), - Err(e) => return Err(xml(e.valid_up_to(), "the file is not valid UTF-8")), - }; - Reader { data: text, pos: 0, limits, count: 0, stack: Vec::new(), top: None, trailer: None }.run() -} - -fn xml(offset: usize, what: &'static str) -> AepError { - AepError::Xml { offset, what } -} - -/// What an open element becomes when it closes. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum Kind { - /// The root element: its children are the top-level chunks. - Root, - /// A chunk with this id (or a `LIST` with this list type). - Chunk([u8; 4]), - /// A `Utf8` chunk. - Utf8, - /// An `alas` chunk built from the attributes. - Alias, - /// The XMP packet (only directly below the root). - Xmp, - /// An element without a chunk counterpart (a name that is no chunk id); skipped with its content. - Skip, -} - -struct Frame { - kind: Kind, - /// Offset of the start tag (for errors). - at: usize, - /// The name as written, to match the end tag. - name: (usize, usize), - /// The decoded `bdata` attribute. - bdata: Option>, - /// The attributes of a `fileReference`, in document order. - attrs: Vec<(String, String)>, - /// Collected text (only for `string` and the XMP packet). - text: Vec, - children: Vec>, -} - -struct Reader<'d> { - data: &'d [u8], - pos: usize, - limits: Limits, - count: usize, - stack: Vec, - /// The top-level chunks once the root element has closed. - top: Option>>, - trailer: Option>, -} - -impl Reader<'_> { - fn run(mut self) -> Result, AepError> { - if self.data.starts_with(&[0xef, 0xbb, 0xbf]) { - self.pos = 3; - } - while self.pos < self.data.len() { - if self.rest().starts_with(b"<") { - self.markup()?; - } else { - self.text()?; - } - } - if let Some(open) = self.stack.last() { - return Err(xml(open.at, "an element is not closed before the end of the file")); - } - let chunks = self.top.ok_or_else(|| xml(self.data.len(), "no AfterEffectsProject root element"))?; - Ok(AepFile { chunks, trailer: Cow::Owned(self.trailer.unwrap_or_default()) }) - } - - fn rest(&self) -> &[u8] { - self.data.get(self.pos..).unwrap_or(&[]) - } - - /// The offset of `needle` at or after `from`. - fn find(&self, from: usize, needle: &[u8]) -> Option { - let hay = self.data.get(from..)?; - if needle.is_empty() || hay.len() < needle.len() { - return None; - } - let first = *needle.first()?; - let mut i = 0; - while let Some(p) = hay.get(i..)?.iter().position(|b| *b == first) { - let at = i.checked_add(p)?; - if hay.get(at..)?.starts_with(needle) { - return from.checked_add(at); - } - i = at.checked_add(1)?; - } - None - } - - /// Skips to just after `close`, which must follow. - fn skip_past(&mut self, close: &[u8], what: &'static str) -> Result { - let at = self.find(self.pos, close).ok_or(xml(self.pos, what))?; - self.pos = at.saturating_add(close.len()); - Ok(at) - } - - fn markup(&mut self) -> Result<(), AepError> { - let rest = self.rest(); - if rest.starts_with(b"", "a processing instruction is not closed")?; - } else if rest.starts_with(b"", "a comment is not closed")?; - } else if rest.starts_with(b"", "a CDATA section is not closed")?; - let content = self.data.get(start..end).unwrap_or(&[]); - let at = start; - match self.stack.last_mut() { - Some(frame) => { - if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) { - frame.text.extend_from_slice(content); - } - } - None => return Err(xml(at, "CDATA outside the root element")), - } - } else if rest.starts_with(b" bool { - !(b.is_ascii_whitespace() || matches!(b, b'<' | b'>' | b'/' | b'=' | b'"' | b'\'' | b'&')) - } - - fn name(&mut self) -> Result<(usize, usize), AepError> { - let start = self.pos; - let len = self.rest().iter().position(|b| !Self::is_name_byte(*b)).unwrap_or(self.rest().len()); - if len == 0 { - return Err(xml(start, "a tag or attribute has no name")); - } - self.pos = start.saturating_add(len); - Ok((start, self.pos)) - } - - fn skip_ws(&mut self) { - let n = self.rest().iter().position(|b| !b.is_ascii_whitespace()).unwrap_or(self.rest().len()); - self.pos = self.pos.saturating_add(n); - } - - fn slice(&self, (a, b): (usize, usize)) -> &[u8] { - self.data.get(a..b).unwrap_or(&[]) - } - - fn start_tag(&mut self) -> Result<(), AepError> { - let at = self.pos; - self.pos = self.pos.saturating_add(1); - let name = self.name()?; - let mut attrs: Vec<((usize, usize), Vec)> = Vec::new(); - let self_closing = loop { - self.skip_ws(); - let rest = self.rest(); - if rest.starts_with(b"/>") { - self.pos = self.pos.saturating_add(2); - break true; - } - if rest.starts_with(b">") { - self.pos = self.pos.saturating_add(1); - break false; - } - if rest.is_empty() { - return Err(xml(at, "a start tag is not closed")); - } - let key = self.name()?; - self.skip_ws(); - if !self.rest().starts_with(b"=") { - return Err(xml(self.pos, "an attribute has no value")); - } - self.pos = self.pos.saturating_add(1); - self.skip_ws(); - let quote = *self.rest().first().ok_or(xml(self.pos, "a start tag is not closed"))?; - if quote != b'"' && quote != b'\'' { - return Err(xml(self.pos, "an attribute value is not quoted")); - } - let vstart = self.pos.saturating_add(1); - let vend = self.find(vstart, &[quote]).ok_or(xml(vstart, "an attribute value is not closed"))?; - let raw = self.data.get(vstart..vend).unwrap_or(&[]); - if raw.contains(&b'<') { - return Err(xml(vstart, "`<` inside an attribute value")); - } - let mut value = Vec::new(); - decode_entities(raw, vstart, &mut value)?; - self.pos = vend.saturating_add(1); - attrs.push((key, value)); - }; - let kind = self.kind_of(name, at)?; - if kind != Kind::Root { - self.count = self.count.saturating_add(1); - if self.count > self.limits.max_chunks { - return Err(AepError::TooManyChunks); - } - // The root's children are depth 1, like the top-level chunks of an `.aep`. - if self.stack.len() > self.limits.max_depth { - return Err(AepError::TooDeep); - } - } - let mut frame = Frame { kind, at, name, bdata: None, attrs: Vec::new(), text: Vec::new(), children: Vec::new() }; - if matches!(kind, Kind::Chunk(_)) { - if let Some((key, value)) = attrs.iter().find(|(k, _)| self.slice(*k) == b"bdata") { - frame.bdata = Some(decode_hex(value, key.1)?); - } - } else if kind == Kind::Alias { - frame.attrs = attrs.iter().map(|(k, v)| (String::from_utf8_lossy(self.slice(*k)).into_owned(), String::from_utf8_lossy(v).into_owned())).collect(); - } - self.stack.push(frame); - if self_closing { - self.close()?; - } - Ok(()) - } - - /// Classifies an element by its name and where it is. - fn kind_of(&self, name: (usize, usize), at: usize) -> Result { - let n = self.slice(name); - let parent = match self.stack.last() { - None => { - if self.top.is_some() { - return Err(xml(at, "a second root element")); - } - if n != ROOT { - return Err(xml(at, "the root element is not AfterEffectsProject")); - } - return Ok(Kind::Root); - } - Some(p) => p.kind, - }; - Ok(match parent { - Kind::Skip | Kind::Utf8 | Kind::Xmp | Kind::Alias => Kind::Skip, - Kind::Root | Kind::Chunk(_) => { - if n == STRING { - Kind::Utf8 - } else if n == FILE_REFERENCE { - Kind::Alias - } else if n == XMP && parent == Kind::Root { - Kind::Xmp - } else if let Some(id) = chunk_id(n) { - Kind::Chunk(id) - } else { - Kind::Skip - } - } - }) - } - - fn end_tag(&mut self) -> Result<(), AepError> { - let at = self.pos; - self.pos = self.pos.saturating_add(2); - let name = self.name()?; - self.skip_ws(); - if !self.rest().starts_with(b">") { - return Err(xml(at, "an end tag is not closed")); - } - self.pos = self.pos.saturating_add(1); - let open = self.stack.last().ok_or(xml(at, "an end tag without a start tag"))?; - if self.slice(open.name) != self.slice(name) { - return Err(xml(at, "an end tag does not match its start tag")); - } - self.close() - } - - /// Closes the innermost element and hands its chunk to the parent. - fn close(&mut self) -> Result<(), AepError> { - let frame = self.stack.pop().ok_or(xml(self.pos, "an end tag without a start tag"))?; - let chunk = match frame.kind { - Kind::Root => { - self.top = Some(frame.children); - return Ok(()); - } - Kind::Skip => return Ok(()), - Kind::Xmp => { - if self.trailer.is_none() { - self.trailer = Some(frame.text); - } - return Ok(()); - } - Kind::Utf8 => Chunk::data(*b"Utf8", frame.text), - Kind::Alias => Chunk::data(*b"alas", alias_json(&frame.attrs).into_bytes()), - Kind::Chunk(id) => chunk_of(id, frame)?, - }; - if let Some(parent) = self.stack.last_mut() { - parent.children.push(chunk); - } - Ok(()) - } - - fn text(&mut self) -> Result<(), AepError> { - let start = self.pos; - let len = self.rest().iter().position(|b| *b == b'<').unwrap_or(self.rest().len()); - let end = start.saturating_add(len); - self.pos = end; - let raw = self.data.get(start..end).unwrap_or(&[]); - match self.stack.last_mut() { - Some(frame) if matches!(frame.kind, Kind::Utf8 | Kind::Xmp) => decode_entities(raw, start, &mut frame.text), - Some(_) => Ok(()), - None if raw.iter().all(u8::is_ascii_whitespace) => Ok(()), - None => Err(xml(start, "text outside the root element")), - } - } -} - -/// The chunk id of an element name: 1 to 4 printable ASCII bytes, padded with spaces (`Pin` is -/// the list type `Pin `). -fn chunk_id(name: &[u8]) -> Option<[u8; 4]> { - if name.is_empty() || name.len() > 4 || !name.iter().all(|b| b.is_ascii_graphic()) { - return None; - } - let mut id = [b' '; 4]; - for (d, s) in id.iter_mut().zip(name) { - *d = *s; - } - Some(id) -} - -/// The chunk of a closed element named by a chunk id. -fn chunk_of(id: [u8; 4], frame: Frame) -> Result, AepError> { - if let Some(bytes) = frame.bdata { - if OPAQUE_LIST_TYPES.contains(&id) { - let pad = if bytes.len() % 2 == 1 { Some(0) } else { None }; - return Ok(Chunk { id: LIST, body: Body::OpaqueList { list_type: id, data: Cow::Owned(bytes) }, pad }); - } - return Ok(Chunk::data(id, bytes)); - } - // Numbers written as text: `0` and `150.000000000`. - if &id == b"numS" || &id == b"ppSn" { - let text = match frame.children.as_slice() { - [only] if only.is(b"Utf8") => only.bytes().unwrap_or(&[]), - _ => return Err(xml(frame.at, "a numS or ppSn element without its number")), - }; - let text = std::str::from_utf8(text).map_err(|_| xml(frame.at, "a number is not text"))?.trim(); - let body = if &id == b"numS" { - // Only `0` is sampled, so whether the field is signed is open: accept both readings of 4 bytes. - let n = text.parse::().ok().filter(|n| (i64::from(i32::MIN)..=i64::from(u32::MAX)).contains(n)); - let n = n.ok_or(xml(frame.at, "numS is not a 32-bit integer"))?; - (n as u32).to_be_bytes().to_vec() - } else { - text.parse::().map_err(|_| xml(frame.at, "ppSn is not a number"))?.to_be_bytes().to_vec() - }; - return Ok(Chunk::data(id, body)); - } - if NESTED_IDS.contains(&id) { - if frame.children.is_empty() { - return Ok(Chunk::data(id, Vec::new())); - } - return Ok(Chunk { id, body: Body::Chunks(frame.children), pad: None }); - } - Ok(Chunk::list(id, frame.children)) -} - -/// Appends `raw` with the predefined entities and character references decoded. -fn decode_entities(raw: &[u8], offset: usize, out: &mut Vec) -> Result<(), AepError> { - let mut i = 0; - while let Some(rest) = raw.get(i..) { - let Some(amp) = rest.iter().position(|b| *b == b'&') else { - out.extend_from_slice(rest); - break; - }; - out.extend_from_slice(rest.get(..amp).unwrap_or(&[])); - let at = offset.saturating_add(i).saturating_add(amp); - let after = rest.get(amp.saturating_add(1)..).unwrap_or(&[]); - let semi = after.iter().take(12).position(|b| *b == b';').ok_or(xml(at, "an entity is not terminated"))?; - let name = after.get(..semi).unwrap_or(&[]); - let ch = match name { - b"amp" => '&', - b"lt" => '<', - b"gt" => '>', - b"quot" => '"', - b"apos" => '\'', - _ => { - let code = if let Some(hex) = name.strip_prefix(b"#x").or_else(|| name.strip_prefix(b"#X")) { - std::str::from_utf8(hex).ok().and_then(|h| u32::from_str_radix(h, 16).ok()) - } else if let Some(dec) = name.strip_prefix(b"#") { - std::str::from_utf8(dec).ok().and_then(|d| d.parse::().ok()) - } else { - return Err(xml(at, "an unknown entity")); - }; - code.filter(|c| *c != 0).and_then(char::from_u32).ok_or(xml(at, "an invalid character reference"))? - } - }; - let mut buf = [0u8; 4]; - out.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes()); - i = i.saturating_add(amp).saturating_add(semi).saturating_add(2); - } - Ok(()) -} - -/// Decodes a `bdata` value (hex digits, two per byte). -fn decode_hex(text: &[u8], offset: usize) -> Result, AepError> { - if text.len() % 2 == 1 { - return Err(xml(offset, "bdata has an odd number of hex digits")); - } - let digit = |b: u8| match b { - b'0'..=b'9' => Some(b - b'0'), - b'a'..=b'f' => Some(b - b'a' + 10), - b'A'..=b'F' => Some(b - b'A' + 10), - _ => None, - }; - let (pairs, _) = text.as_chunks::<2>(); - pairs - .iter() - .map(|[hi, lo]| digit(*hi).zip(digit(*lo)).map(|(h, l)| (h << 4) | l)) - .collect::>>() - .ok_or(xml(offset, "bdata holds a character that is not a hex digit")) -} - -/// The JSON body of an `alas` chunk from the attributes of a `fileReference`, keys in document -/// order (alphabetical in every sample, as in the `.aep`): the two `ascendcount_*` values as -/// numbers, `platform` `Win` as `1`, `target_is_folder` `0` / `1` as `false` / `true`, everything -/// else as a string. -fn alias_json(attrs: &[(String, String)]) -> String { - let mut out = String::from("{"); - for (i, (key, value)) in attrs.iter().enumerate() { - if i > 0 { - out.push(','); - } - json_str(&mut out, key); - out.push(':'); - let number = value.parse::().ok(); - match (key.as_str(), value.as_str()) { - ("ascendcount_base" | "ascendcount_target", _) if number.is_some() => out.push_str(value), - ("platform", "Win") => out.push('1'), - ("platform", _) if number.is_some() => out.push_str(value), - ("target_is_folder", "0" | "false") => out.push_str("false"), - ("target_is_folder", "1" | "true") => out.push_str("true"), - _ => json_str(&mut out, value), - } - } - out.push('}'); - out -} - -fn json_str(out: &mut String, s: &str) { - out.push('"'); - for c in s.chars() { - match c { - '"' => out.push_str("\\\""), - '\\' => out.push_str("\\\\"), - '\n' => out.push_str("\\n"), - '\r' => out.push_str("\\r"), - '\t' => out.push_str("\\t"), - c if u32::from(c) < 0x20 => out.push_str(&format!("\\u{:04x}", u32::from(c))), - c => out.push(c), - } - } - out.push('"'); -} - -#[cfg(test)] -mod tests { - use super::*; - - fn doc(body: &str) -> String { - format!("\n{body}\n") - } - - #[test] - fn maps_elements_to_chunks() { - let x = doc(concat!( - "\n", - "A & BA-3", - "150.000000000x", - "]]>" - )); - let f = read_aepx(x.as_bytes()).unwrap(); - assert_eq!(f.trailer.as_ref(), b""); - let ids: Vec<_> = f.chunks.iter().map(|c| (c.id, c.list_type())).collect(); - assert_eq!( - ids, - vec![ - (*b"head", None), - (LIST, Some(*b"Pin ")), - (LIST, Some(*b"Pefl")), - (*b"tdsn", None), - (*b"numS", None), - (*b"ppSn", None), - (LIST, Some(*b"btdk")) - ] - ); - assert_eq!(f.chunks[1].children()[0].bytes(), Some(&[1u8][..])); - assert_eq!(f.chunks[1].children()[0].pad, Some(0)); - assert_eq!(f.chunks[3].children()[0].bytes(), Some(&b"A & BA"[..])); - assert_eq!(f.chunks[4].bytes(), Some(&(-3i32).to_be_bytes()[..])); - assert_eq!(f.chunks[5].bytes(), Some(&150f64.to_be_bytes()[..])); - assert_eq!(f.chunks[6].bytes(), Some(&b"ABC"[..])); - // The tree writes as a valid `.aep` that parses back to itself. - let bin = crate::container::write(&f).unwrap(); - assert_eq!(parse(&bin).unwrap(), f); - } - - #[test] - fn file_reference_becomes_alias_json() { - let x = doc(concat!( - "" - )); - let f = read_aepx(x.as_bytes()).unwrap(); - let alas = f.chunks[0].children()[0].bytes().unwrap(); - assert_eq!( - std::str::from_utf8(alas).unwrap(), - r#"{"ascendcount_base":1,"ascendcount_target":1,"fullpath":"C:\\a\\\"b.png","platform":1,"server_name":"N","server_volume_name":"V","target_is_folder":false}"# - ); - } - - #[test] - fn nums_takes_signed_and_unsigned_32_bit_values() { - for (text, bytes) in [("-2147483648", [0x80, 0, 0, 0]), ("4294967295", [0xff; 4]), (" 7 ", [0, 0, 0, 7])] { - let f = read_aepx(doc(&format!("{text}")).as_bytes()).unwrap(); - assert_eq!(f.chunks[0].bytes(), Some(&bytes[..]), "{text}"); - } - for text in ["-2147483649", "4294967296", "1.5"] { - assert!(read_aepx(doc(&format!("{text}")).as_bytes()).is_err(), "{text}"); - } - } - - #[test] - fn detection() { - assert!(is_aepx(b"\xef\xbb\xbf ")); - assert!(is_aepx(b"")); - assert!(!is_aepx(b"RIFX\0\0\0\x04Egg!")); - assert!(parse_any(b"RIFX\0\0\0\x04Egg!").is_ok()); - assert!(parse_any(doc("").as_bytes()).is_ok()); - } - - #[test] - fn bad_input_is_an_error() { - let bad = [ - doc(""), - doc(""), - doc(" "), - doc("�"), - doc("&"), - doc(""), - doc(""), - doc("x"), - doc(""), - doc(""), - doc(""), - "]>".into(), - "".into(), - "".into(), - "".into(), - "junk".into(), - ""); - } else if rest.starts_with(b""); - } else if rest.starts_with(b""); - } else if rest.starts_with(b""); - } else if rest.starts_with(b""); - } else { - // A start tag: find its end outside quotes; `/>` closes it at once. - let mut j = i + 1; - let mut quote = None; - while let Some(&c) = b.get(j) { - match quote { - Some(q) if c == q => quote = None, - Some(_) => {} - None if c == b'"' || c == b'\'' => quote = Some(c), - None if c == b'>' => break, - None => {} - } - j += 1; - } - if b.get(j.wrapping_sub(1)) != Some(&b'/') { - depth += 1; - max = max.max(depth); - } - i = j + 1; - } - } - max -} - -/// The deepest array / object nesting of a JSON document (strings skipped). -pub(crate) fn json_depth(b: &[u8]) -> usize { - let (mut depth, mut max, mut in_str, mut esc) = (0usize, 0usize, false, false); - for &c in b { - if in_str { - if esc { - esc = false; - } else if c == b'\\' { - esc = true; - } else if c == b'"' { - in_str = false; - } - continue; - } - match c { - b'"' => in_str = true, - b'[' | b'{' => { - depth += 1; - max = max.max(depth); - } - b']' | b'}' => depth = depth.saturating_sub(1), - _ => {} - } - } - max -} +pub(crate) use craft_timeline::preflight::{json_depth, xml_depth}; pub fn import( project: &mut Project, @@ -201,8 +130,8 @@ const EDL_MEDIA_TIME_NOTE: &str = "EDL source timecodes were imported as media t /// The largest start timecode, in frames, a file may have: a day at 1000 fps. const MAX_FILE_TIMECODE: i64 = 24 * 3600 * 1000; -/// The paths an EDL reader guessed (media it flags offline: a line without `SOURCE FILE` names -/// only its clip) that are not inside the list's folder: a clip name of `../x.mov` or an absolute +/// The paths an EDL reader guessed (identified by its `Tape Name` metadata: a line without +/// `SOURCE FILE` names only its clip) that are not inside the list's folder: a clip name of `../x.mov` or an absolute /// one would link a file elsewhere on the disk. They stay placeholders. A `SOURCE FILE` path is /// the list's own choice and is kept, also when another clip guesses the same path. fn guessed_outside(project: &fp::Project, base_dir: Option<&str>) -> HashSet { @@ -219,7 +148,9 @@ fn guessed_outside(project: &fp::Project, base_dir: Option<&str>) -> HashSet filmcraft codec: "png".into(), pixel_format: String::new(), color: Default::default(), + color_assumed: None, has_alpha: false, bitrate: None, hdr: None, @@ -60,7 +61,7 @@ fn media(p: &mut fp::Project, name: &str, path: &str, kind: filmcraft_media::Med proxy: None, identity: None, }; - p.add_item(name, fp::Label::Iris, fp::ItemKind::Media(clip), bin) + p.add_item(name, fp::Label::Iris, fp::ItemKind::Media(Box::new(clip)), bin) } fn rate() -> filmcraft_time::FrameRate { @@ -882,3 +883,17 @@ fn import_finds_each_clips_transitions_without_scanning_the_track() { let mid = m.layers.iter().find(|l| near(l.in_point, t(100.0 - 0.08))).expect("clip 250 extended into its incoming transition"); assert!(near(mid.out_point, t(100.4 + 0.08)), "{}", mid.out_point.seconds()); } + +#[test] +fn edl_explicit_source_file_allows_the_same_path_as_an_outside_guess() { + let edl = b"TITLE: CUT\nFCM: NON-DROP FRAME\n\n001 A001 V C 00:00:00:00 00:00:01:00 00:00:00:00 00:00:01:00\n* FROM CLIP NAME: ../shared.mov\n\n002 A002 V C 00:00:00:00 00:00:01:00 00:00:01:00 00:00:02:00\n* FROM CLIP NAME: named.mov\n* SOURCE FILE: /shared.mov\n"; + let mut asked = Vec::new(); + let mut probe_all = |path: &str| { + asked.push(path.to_string()); + probe(path) + }; + let mut p = Project::default(); + let opts = ImportOptions { name: "hand.edl".into(), edl_frame_rate: Some(25.0), base_dir: Some("/work".into()) }; + import(&mut p, edl, None, &opts, &mut probe_all).unwrap(); + assert_eq!(asked, ["/shared.mov"], "explicit SOURCE FILE permits the shared path, probed once"); +} diff --git a/crates/keyframe/src/text_doc.rs b/crates/keyframe/src/text_doc.rs index f91d8be4d..e8fcb52be 100644 --- a/crates/keyframe/src/text_doc.rs +++ b/crates/keyframe/src/text_doc.rs @@ -85,13 +85,13 @@ impl Justify { } pub fn parse(s: &str) -> Option { Some(match s.to_ascii_lowercase().replace(['_', ' ', '-'], "").as_str() { - "left" | "leftjustify" => Justify::Left, - "center" | "centre" | "centerjustify" => Justify::Center, - "right" | "rightjustify" => Justify::Right, + "left" | "leftjustify" | "alignleft" => Justify::Left, + "center" | "centre" | "centerjustify" | "aligncenter" => Justify::Center, + "right" | "rightjustify" | "alignright" => Justify::Right, "justify" | "justifyleft" | "justifylastleft" | "fulljustifylastlineleft" => Justify::JustifyLastLeft, "justifycenter" | "justifylastcenter" | "fulljustifylastlinecenter" => Justify::JustifyLastCenter, "justifyright" | "justifylastright" | "fulljustifylastlineright" => Justify::JustifyLastRight, - "justifyall" | "fulljustifylastlinefull" | "fulljustify" => Justify::JustifyAll, + "justifyall" | "justifyfull" | "fulljustifylastlinefull" | "fulljustify" => Justify::JustifyAll, _ => return None, }) } diff --git a/crates/lottie/Cargo.toml b/crates/lottie/Cargo.toml index a9f64b3ba..9a95dca13 100644 --- a/crates/lottie/Cargo.toml +++ b/crates/lottie/Cargo.toml @@ -10,6 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] +craft-lottie = { workspace = true } craft-docpath = { workspace = true } effectcraft-time = { workspace = true } effectcraft-color = { workspace = true } diff --git a/crates/lottie/src/anim.rs b/crates/lottie/src/anim.rs index 40a56a7eb..62550f86f 100644 --- a/crates/lottie/src/anim.rs +++ b/crates/lottie/src/anim.rs @@ -1,23 +1,14 @@ -//! Animated properties: EffectCraft keyframes ↔ Lottie keyframes. -//! -//! A Lottie keyframe holds the start value `s` of a segment and the segment's normalised cubic -//! Bezier ease: `o` (out tangent of this key) and `i` (in tangent of the next key), each with `x` -//! (time fraction) and `y` (value progress fraction), per dimension. After Effects' temporal ease -//! is speed (units/s) and influence (fraction of the segment): for a segment of duration `d` and -//! value change `Δv`, -//! -//! ```text -//! o.x = influence_out o.y = speed_out · influence_out · d / Δv -//! i.x = 1 − influence_in i.y = 1 − speed_in · influence_in · d / Δv -//! ``` -//! -//! which is exactly the Bezier the keyframe evaluator uses. Spatial properties ease along the -//! motion path (Δv = arc length, one dimension) and carry `to`/`ti` spatial tangents. Hold keys -//! set `h: 1`. +//! Animated properties: EffectCraft keyframes ↔ Lottie keyframes, through `craft-lottie`'s +//! property encoding ([`craft_lottie::read_prop`], [`craft_lottie::write_prop`]) and its +//! conversion between a segment's normalised Bezier ease and After Effects' speed and influence +//! ([`Tangents`]). Spatial properties ease along the motion path (Δv = arc length, one +//! dimension) and carry `to`/`ti` spatial tangents. +pub(crate) use craft_lottie::nums; +use craft_lottie::{Animated, Json, KeyOut, PropValue, Tangents, read_prop, round6}; use effectcraft_keyframe::{self as kf, Ease, Interp, Keyframe, Value}; use effectcraft_project::{Expression, Property}; -use serde_json::{Value as Json, json}; +use serde_json::json; use crate::Timebase; @@ -62,15 +53,11 @@ fn secs(t: effectcraft_time::Tick) -> f64 { } fn r6(v: f64) -> f64 { - if v.is_finite() { (v * 1e6).round() / 1e6 } else { 0.0 } + round6(v) } -/// A key value as Lottie's `s` (numbers wrapped in an array, objects in a one-element array). -fn wrap(j: Json) -> Json { - match j { - Json::Array(_) => j, - other => json!([other]), - } +fn lottie_ease(e: Ease) -> craft_lottie::Ease { + craft_lottie::Ease { speed: e.speed, influence: e.influence } } fn is_spatial(p: &Property) -> bool { @@ -80,7 +67,7 @@ fn is_spatial(p: &Property) -> bool { /// Export a property as a Lottie animatable property (`{a, k}` plus `x` for expressions). /// `label` names the property in warnings. Muted keys are omitted: Lottie has no mute state, and /// the remaining keys carry the animation the renderer shows. -pub(crate) fn export_prop(ex: &mut Ex, p: &Property, conv: &dyn Fn(&Value) -> Json, label: &str) -> Json { +pub(crate) fn export_prop(ex: &mut Ex, p: &Property, conv: &dyn Fn(&Value) -> Json, label: &str) -> Animated { let muted = p.keys.iter().any(|k| k.muted); if muted { ex.warn(format!("{label}: muted keyframes are not exported")); @@ -92,146 +79,102 @@ pub(crate) fn export_prop(ex: &mut Ex, p: &Property, conv: &dyn Fn(&Value) -> Js } else { &p.keys }; - let mut out = - if keys.is_empty() { json!({"a": 0, "k": conv(&p.value)}) } else { json!({"a": 1, "k": export_keys(ex, keys, is_spatial(p), p.hold_only, conv)}) }; + let mut expression = None; if let Some(e) = p.expr.as_ref().filter(|e| e.enabled && !e.text.trim().is_empty()) { if ex.include_expressions { - out["x"] = json!(e.text); + expression = Some(e.text.as_str()); } else { ex.warn(format!("{label}: expression not exported (enable includeExpressions to export it as `x`)")); } } - out + if keys.is_empty() { + return Animated(craft_lottie::write_prop(conv(&p.value), &[], expression)); + } + Animated::keyed(&export_keys(ex, keys, is_spatial(p), p.hold_only, conv), expression) } -fn export_keys(ex: &Ex, keys: &[Keyframe], spatial: bool, hold_only: bool, conv: &dyn Fn(&Value) -> Json) -> Vec { +fn export_keys(ex: &Ex, keys: &[Keyframe], spatial: bool, hold_only: bool, conv: &dyn Fn(&Value) -> Json) -> Vec { let mut out = Vec::with_capacity(keys.len()); for (i, k) in keys.iter().enumerate() { - let mut o = json!({"t": r6(ex.tb.frame(k.time)), "s": wrap(conv(&k.value))}); - if i + 1 == keys.len() { - if k.out_interp == Interp::Hold || hold_only { - o["h"] = json!(1); + let mut o = KeyOut { t: ex.tb.frame(k.time), s: conv(&k.value), hold: false, ease: vec![], spatial: None }; + let last = i + 1 == keys.len(); + if k.out_interp == Interp::Hold || hold_only || (!last && !k.value.interpolates()) { + o.hold = true; + } else if !last { + o.ease = segment_ease(keys, i, spatial); + if spatial { + let (_, to) = kf::spatial_tangents(keys, i); + let (ti, _) = kf::spatial_tangents(keys, i + 1); + let n = if matches!(k.value, Value::Vec2(_)) { 2 } else { conv(&k.value).as_array().map(Vec::len).unwrap_or(3).min(3) }; + o.spatial = Some((to.get(..n).unwrap_or_default().to_vec(), ti.get(..n).unwrap_or_default().to_vec())); } - out.push(o); - continue; - } - if k.out_interp == Interp::Hold || hold_only || !k.value.interpolates() { - o["h"] = json!(1); - out.push(o); - continue; - } - let (ox, oy, ix, iy) = segment_ease(keys, i, spatial); - o["o"] = json!({"x": ox, "y": oy}); - o["i"] = json!({"x": ix, "y": iy}); - if spatial { - let (_, to) = kf::spatial_tangents(keys, i); - let (ti, _) = kf::spatial_tangents(keys, i + 1); - let n = if matches!(k.value, Value::Vec2(_)) { 2 } else { conv(&k.value).as_array().map(Vec::len).unwrap_or(3).min(3) }; - o["to"] = json!(to[..n].iter().map(|v| r6(*v)).collect::>()); - o["ti"] = json!(ti[..n].iter().map(|v| r6(*v)).collect::>()); } out.push(o); } out } -/// Normalised ease of segment `i → i+1`: (o.x, o.y, i.x, i.y) per dimension. -fn segment_ease(keys: &[Keyframe], i: usize, spatial: bool) -> (Vec, Vec, Vec, Vec) { - let (a, b) = (&keys[i], &keys[i + 1]); +/// Normalised ease of segment `i → i+1`, one entry per dimension. +fn segment_ease(keys: &[Keyframe], i: usize, spatial: bool) -> Vec { + let (Some(a), Some(b)) = (keys.get(i), keys.get(i + 1)) else { return vec![] }; let dur = (secs(b.time) - secs(a.time)).max(1e-12); let ca = a.value.components(); let cb = b.value.components(); let numeric = !ca.is_empty() && ca.len() == cb.len(); let dims = if spatial || !numeric { 1 } else { ca.len() }; - let (mut ox, mut oy, mut ix, mut iy) = (vec![], vec![], vec![], vec![]); - for d in 0..dims { - let (dv, eo, ei) = if spatial { - let len = kf::spatial_segment_length(keys, i); - (len, kf::side_ease(keys, i, 0, true, true), kf::side_ease(keys, i + 1, 0, true, false)) - } else if numeric { - (cb[d] - ca[d], kf::side_ease(keys, i, d, false, true), kf::side_ease(keys, i + 1, d, false, false)) - } else { - // Paths, gradients: overall progress 0 → 1. - let side = |k: &Keyframe, out: bool| { - let interp = if out { k.out_interp } else { k.in_interp }; - let list = if out { &k.out_ease } else { &k.in_ease }; - if interp == Interp::Bezier { - list.first().copied().unwrap_or_default() - } else { - Ease { speed: 1.0 / dur, influence: kf::LINEAR_SIDE_INFLUENCE } - } + (0..dims) + .map(|d| { + let (dv, eo, ei) = if spatial { + let len = kf::spatial_segment_length(keys, i); + (len, kf::side_ease(keys, i, 0, true, true), kf::side_ease(keys, i + 1, 0, true, false)) + } else if numeric { + (cb[d] - ca[d], kf::side_ease(keys, i, d, false, true), kf::side_ease(keys, i + 1, d, false, false)) + } else { + // Paths, gradients: overall progress 0 → 1. + let side = |k: &Keyframe, out: bool| { + let interp = if out { k.out_interp } else { k.in_interp }; + let list = if out { &k.out_ease } else { &k.in_ease }; + if interp == Interp::Bezier { + list.first().copied().unwrap_or_default() + } else { + Ease { speed: 1.0 / dur, influence: kf::LINEAR_SIDE_INFLUENCE } + } + }; + (1.0, Some(side(a, true)), Some(side(b, false))) }; - (1.0, Some(side(a, true)), Some(side(b, false))) - }; - let lin = Ease { speed: dv / dur, influence: kf::LINEAR_SIDE_INFLUENCE }; - let (eo, ei) = (eo.unwrap_or(lin), ei.unwrap_or(lin)); - // Crossing time handles must retain the independently specified influences. - let (i0, i1) = (eo.influence.clamp(0.0, 1.0), ei.influence.clamp(0.0, 1.0)); - let (y0, y1) = if dv.abs() > 1e-12 { (eo.speed * i0 * dur / dv, 1.0 - ei.speed * i1 * dur / dv) } else { (0.0, 1.0) }; - ox.push(r6(i0)); - oy.push(r6(y0)); - ix.push(r6(1.0 - i1)); - iy.push(r6(y1)); - } - (ox, oy, ix, iy) + let lin = Ease { speed: dv / dur, influence: kf::LINEAR_SIDE_INFLUENCE }; + // Crossing time handles keep the independently specified influences. + Tangents::from_speed(lottie_ease(eo.unwrap_or(lin)), lottie_ease(ei.unwrap_or(lin)), dv, dur) + }) + .collect() } // ---------------------------------------------------------------- import -/// Whether a Lottie property value is keyframed. -pub(crate) fn is_animated(j: &Json) -> bool { - if j.get("a").and_then(Json::as_i64) == Some(1) { - return true; - } - j.get("k").and_then(Json::as_array).and_then(|a| a.first()).is_some_and(|f| f.get("t").is_some()) -} - -/// Component `d` of an ease tangent field (`x` / `y` may be a number or an array). -fn comp(j: &Json, field: &str, d: usize) -> Option { - match j.get(field)? { - Json::Number(n) => n.as_f64(), - Json::Array(a) => a.get(d).or(a.first()).and_then(Json::as_f64), - _ => None, - } -} - -fn vec3_of(j: Option<&Json>) -> [f64; 3] { - let a = j.and_then(Json::as_array); - let g = |i: usize| a.and_then(|a| a.get(i)).and_then(Json::as_f64).unwrap_or(0.0); - [g(0), g(1), g(2)] -} - /// Import a Lottie animatable property into `p` (value, keys, expression). `conv` turns a Lottie /// value (as found in `k` or a key's `s`, possibly wrapped in a one-element array) into a value of /// the property's type. pub(crate) fn import_prop(im: &Im, j: &Json, p: &mut Property, conv: &dyn Fn(&Json) -> Option) { - if !j.is_object() { - if let Some(v) = conv(j) { - p.value = v; - } - return; - } - if let Some(x) = j.get("x").and_then(Json::as_str).filter(|x| !x.trim().is_empty()) { + let prop = read_prop(j); + if let Some(x) = prop.expression { p.expr = Some(Expression { text: x.to_string(), enabled: true }); } - let Some(k) = j.get("k") else { return }; - if !is_animated(j) { - if let Some(v) = conv(k) { - p.value = v; + let list = match prop.value { + PropValue::None => return, + PropValue::Static(v) => { + if let Some(v) = conv(v) { + p.value = v; + } + return; } - return; - } - let Some(list) = k.as_array() else { return }; + PropValue::Keys(list) => list, + }; let spatial = is_spatial(p); let mut keys: Vec = Vec::with_capacity(list.len()); - let mut kept: Vec<&Json> = Vec::with_capacity(list.len()); - let mut prev_end: Option<&Json> = None; + let mut kept = Vec::with_capacity(list.len()); for kj in list { - let t = kj.get("t").and_then(Json::as_f64).unwrap_or(0.0); - let sv = kj.get("s").or(prev_end); - prev_end = kj.get("e"); - let Some(v) = sv.and_then(conv) else { continue }; - let mut key = Keyframe::new(im.tb.tick(t), v); + let Some(v) = kj.s.and_then(conv) else { continue }; + let mut key = Keyframe::new(im.tb.tick(kj.t), v); key.spatial_auto = false; if p.hold_only || !key.value.interpolates() { key = key.hold(); @@ -245,16 +188,14 @@ pub(crate) fn import_prop(im: &Im, j: &Json, p: &mut Property, conv: &dyn Fn(&Js let n = keys.len(); for i in 0..n.saturating_sub(1) { let Some(kj) = kept.get(i) else { break }; - if kj.get("h").and_then(Json::as_i64) == Some(1) || p.hold_only { + if kj.hold || p.hold_only { keys[i].out_interp = Interp::Hold; keys[i + 1].in_interp = Interp::Hold; continue; } if spatial { - let to = vec3_of(kj.get("to")); - let ti = vec3_of(kj.get("ti")); - keys[i].spatial_out = to; - keys[i + 1].spatial_in = ti; + keys[i].spatial_out = kj.to; + keys[i + 1].spatial_in = kj.ti; } } // Eases need the spatial tangents (arc length), so they come second. @@ -263,7 +204,7 @@ pub(crate) fn import_prop(im: &Im, j: &Json, p: &mut Property, conv: &dyn Fn(&Js if keys[i].out_interp == Interp::Hold { continue; } - let (Some(o), Some(ii)) = (kj.get("o"), kj.get("i")) else { + let (Some(o), Some(ii)) = (kj.o, kj.i) else { keys[i].out_interp = Interp::Linear; keys[i + 1].in_interp = Interp::Linear; continue; @@ -277,13 +218,8 @@ pub(crate) fn import_prop(im: &Im, j: &Json, p: &mut Property, conv: &dyn Fn(&Js let mut outs = vec![]; let mut ins = vec![]; for d in 0..dims { - let ox = comp(o, "x", d).unwrap_or(1.0 / 3.0).clamp(0.0, 1.0); - let oy = comp(o, "y", d).unwrap_or(ox); - let ix = comp(ii, "x", d).unwrap_or(2.0 / 3.0).clamp(0.0, 1.0); - let iy = comp(ii, "y", d).unwrap_or(ix); - if (ox - oy).abs() > 1e-4 || (ix - iy).abs() > 1e-4 { - linear = false; - } + let t = Tangents::read(o, ii, d); + linear &= t.is_linear(); let dv = if spatial { kf::spatial_segment_length(&keys, i) } else if numeric { @@ -291,10 +227,9 @@ pub(crate) fn import_prop(im: &Im, j: &Json, p: &mut Property, conv: &dyn Fn(&Js } else { 1.0 }; - let inf_o = ox.max(0.001); - let inf_i = (1.0 - ix).max(0.001); - outs.push(Ease { speed: oy * dv / (inf_o * dur), influence: inf_o }); - ins.push(Ease { speed: (1.0 - iy) * dv / (inf_i * dur), influence: inf_i }); + let (out, into) = t.to_speed(dv, dur); + outs.push(Ease { speed: out.speed, influence: out.influence }); + ins.push(Ease { speed: into.speed, influence: into.influence }); } if linear { keys[i].out_interp = Interp::Linear; @@ -310,6 +245,13 @@ pub(crate) fn import_prop(im: &Im, j: &Json, p: &mut Property, conv: &dyn Fn(&Js p.keys = keys; } +/// [`import_prop`] for a property of the model ([`Animated`]). +pub(crate) fn import_animated(im: &Im, a: Option<&Animated>, p: &mut Property, conv: &dyn Fn(&Json) -> Option) { + if let Some(a) = a { + import_prop(im, &a.0, p, conv); + } +} + // ---------------------------------------------------------------- value converters pub(crate) fn num(v: &Value) -> Json { @@ -335,23 +277,6 @@ pub(crate) fn arr3(v: &Value) -> Json { json!([r6(*c.first().unwrap_or(&0.0)), r6(*c.get(1).unwrap_or(&0.0)), r6(*c.get(2).unwrap_or(&0.0))]) } -/// Numbers of a Lottie value (`5`, `[5]`, `[1, 2, 3]`). -pub(crate) fn nums(j: &Json) -> Option> { - match j { - Json::Number(n) => Some(vec![n.as_f64()?]), - Json::Array(a) => { - // `[[x, y]]`-style wrapping. - if a.len() == 1 - && let Some(inner @ Json::Array(_)) = a.first() - { - return nums(inner); - } - a.iter().map(Json::as_f64).collect() - } - _ => None, - } -} - pub(crate) fn to_scalar(j: &Json) -> Option { nums(j).and_then(|v| v.first().copied()).map(Value::Scalar) } @@ -368,15 +293,8 @@ pub(crate) fn to_vec3(j: &Json, z: f64) -> Option { } pub(crate) fn to_color(j: &Json) -> Option { - let v = nums(j)?; - let mut c = [*v.first()?, *v.get(1).unwrap_or(&0.0), *v.get(2).unwrap_or(&0.0), *v.get(3).unwrap_or(&1.0)]; - // Some files use 0–255. - if c[..3].iter().any(|x| *x > 1.0) { - for x in &mut c[..3] { - *x /= 255.0; - } - } - Some(Value::Color(c)) + // Some files use 0–255: `craft_lottie::color` divides those. + craft_lottie::color(j).map(Value::Color) } pub(crate) fn to_bool(j: &Json) -> Option { diff --git a/crates/lottie/src/base64.rs b/crates/lottie/src/base64.rs deleted file mode 100644 index b45f86d4a..000000000 --- a/crates/lottie/src/base64.rs +++ /dev/null @@ -1,69 +0,0 @@ -//! Standard base64 (RFC 4648 §4) for embedded image assets. - -const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; - -pub fn encode(data: &[u8]) -> String { - let mut out = String::with_capacity(data.len().div_ceil(3) * 4); - for chunk in data.chunks(3) { - let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)]; - let n = (b[0] as u32) << 16 | (b[1] as u32) << 8 | b[2] as u32; - for i in 0..4 { - if i <= chunk.len() { - out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char); - } else { - out.push('='); - } - } - } - out -} - -pub fn decode(s: &str) -> Option> { - let val = |c: u8| -> Option { - Some(match c { - b'A'..=b'Z' => c - b'A', - b'a'..=b'z' => c - b'a' + 26, - b'0'..=b'9' => c - b'0' + 52, - b'+' | b'-' => 62, - b'/' | b'_' => 63, - _ => return None, - } as u32) - }; - let clean: Vec = s.bytes().filter(|c| !c.is_ascii_whitespace() && *c != b'=').collect(); - let mut out = Vec::with_capacity(clean.len() * 3 / 4); - for chunk in clean.chunks(4) { - let mut n = 0u32; - for (i, &c) in chunk.iter().enumerate() { - n |= val(c)? << (18 - 6 * i); - } - let bytes = [(n >> 16) as u8, (n >> 8) as u8, n as u8]; - match chunk.len() { - 4 => out.extend_from_slice(&bytes), - 3 => out.extend_from_slice(&bytes[..2]), - 2 => out.push(bytes[0]), - _ => return None, - } - } - Some(out) -} - -/// Split a `data:;base64,` URI into (mime, bytes). -pub fn data_uri(s: &str) -> Option<(String, Vec)> { - let rest = s.strip_prefix("data:")?; - let (head, payload) = rest.split_once(',')?; - let mime = head.strip_suffix(";base64")?; - Some((mime.to_string(), decode(payload)?)) -} - -#[cfg(test)] -mod tests { - #[test] - fn roundtrip() { - for s in ["", "f", "fo", "foo", "foob", "fooba", "foobar"] { - let e = super::encode(s.as_bytes()); - assert_eq!(super::decode(&e).unwrap(), s.as_bytes()); - } - assert_eq!(super::encode(b"foobar"), "Zm9vYmFy"); - assert_eq!(super::encode(b"fo"), "Zm8="); - } -} diff --git a/crates/lottie/src/export.rs b/crates/lottie/src/export.rs index 88dcf4ed4..094196007 100644 --- a/crates/lottie/src/export.rs +++ b/crates/lottie/src/export.rs @@ -2,11 +2,14 @@ use std::collections::BTreeSet; +use craft_lottie::model::{Asset, Effect, Font, Fonts, Layer as LottieLayer, LayerContent, Marker, Mask, PrecompLayer, SolidLayer, Transform}; +use craft_lottie::{Animated, Animation, Json}; use effectcraft_keyframe::Value; use effectcraft_project::{Comp, FootageKind, GroupKind, ItemId, ItemKind, Layer, LayerSource, MaskMode, MatteKind, Project, PropGroup}; -use serde_json::{Map, Value as Json, json}; +use serde_json::json; use crate::anim::{self, Ex, export_prop}; +use crate::shapes::fixed; use crate::{LottieError, Timebase, shapes, text}; /// Export settings. @@ -134,30 +137,15 @@ struct Doc<'a> { opts: &'a ExportOptions, read: &'a dyn Fn(&str) -> Option>, ex: Ex, - assets: Vec, + assets: Vec, done: BTreeSet, - fonts: Vec, + fonts: Vec, any_3d: bool, } -fn hex(c: [f32; 3]) -> String { - let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - format!("#{:02x}{:02x}{:02x}", b(c[0]), b(c[1]), b(c[2])) -} - /// The image type `bytes` hold, by their signature; `None` for anything else. pub(crate) fn image_mime(bytes: &[u8]) -> Option<&'static str> { - if bytes.starts_with(b"\x89PNG\r\n\x1a\n") { - Some("image/png") - } else if bytes.starts_with(&[0xff, 0xd8, 0xff]) { - Some("image/jpeg") - } else if bytes.starts_with(b"GIF87a") || bytes.starts_with(b"GIF89a") { - Some("image/gif") - } else if bytes.starts_with(b"RIFF") && bytes.get(8..12) == Some(b"WEBP") { - Some("image/webp") - } else { - None - } + craft_lottie::image_mime(bytes) } impl Doc<'_> { @@ -165,84 +153,68 @@ impl Doc<'_> { self.ex.tb.frame(t) } - fn prop(&mut self, g: &PropGroup, m: &str, conv: &dyn Fn(&Value) -> Json, label: &str) -> Option { + fn prop(&mut self, g: &PropGroup, m: &str, conv: &dyn Fn(&Value) -> Json, label: &str) -> Option { let p = g.get(m)?; Some(export_prop(&mut self.ex, p, conv, &format!("{label} ▸ {}", p.name))) } - fn transform(&mut self, l: &Layer) -> Json { - let mut ks = Map::new(); - let Some(tr) = l.transform() else { return json!({}) }; + fn transform(&mut self, l: &Layer) -> Transform { + let mut ks = Transform::default(); + let Some(tr) = l.transform() else { return ks }; let label = format!("{} ▸ Transform", l.name); let three = l.is_3d(); - if let Some(a) = self.prop(tr, "anchor", &anim::arr3, &label) { - ks.insert("a".into(), a); - } + ks.anchor = self.prop(tr, "anchor", &anim::arr3, &label); if tr.get("positionX").is_some() { let mut p = json!({"s": true}); for (k, m) in [("x", "positionX"), ("y", "positionY"), ("z", "positionZ")] { if (k != "z" || three) && let Some(v) = self.prop(tr, m, &anim::num, &label) { - p[k] = v; + p[k] = v.0; } } - ks.insert("p".into(), p); - } else if let Some(p) = self.prop(tr, "position", &anim::arr3, &label) { - ks.insert("p".into(), p); - } - if let Some(s) = self.prop(tr, "scale", &anim::arr3, &label) { - ks.insert("s".into(), s); + ks.position = Some(Animated(p)); + } else { + ks.position = self.prop(tr, "position", &anim::arr3, &label); } + ks.scale = self.prop(tr, "scale", &anim::arr3, &label); if three { - for (k, m) in [("rx", "rotationX"), ("ry", "rotationY"), ("rz", "rotation")] { - if let Some(v) = self.prop(tr, m, &anim::num, &label) { - ks.insert(k.into(), v); - } - } - if let Some(v) = self.prop(tr, "orientation", &anim::arr3, &label) { - ks.insert("or".into(), v); - } - } else if let Some(r) = self.prop(tr, "rotation", &anim::num, &label) { - ks.insert("r".into(), r); + ks.rotation_x = self.prop(tr, "rotationX", &anim::num, &label); + ks.rotation_y = self.prop(tr, "rotationY", &anim::num, &label); + ks.rotation_z = self.prop(tr, "rotation", &anim::num, &label); + ks.orientation = self.prop(tr, "orientation", &anim::arr3, &label); + } else { + ks.rotation = self.prop(tr, "rotation", &anim::num, &label); } - if let Some(o) = self.prop(tr, "opacity", &anim::num, &label) { - ks.insert("o".into(), o); - } - Json::Object(ks) + ks.opacity = self.prop(tr, "opacity", &anim::num, &label); + ks } - fn masks(&mut self, l: &Layer) -> Vec { + fn masks(&mut self, l: &Layer) -> Vec { let Some(masks) = l.masks() else { return vec![] }; let mut out = vec![]; for m in masks.groups() { let GroupKind::Mask { mode, inverted, .. } = m.kind else { continue }; let label = format!("{} ▸ {}", l.name, m.name); - let mut o = json!({"nm": m.name, "mode": mask_mode(mode), "inv": inverted}); - if let Some(v) = self.prop(m, "path", &shapes::path_value, &label) { - o["pt"] = v; - } - if let Some(v) = self.prop(m, "opacity", &anim::num, &label) { - o["o"] = v; - } - if let Some(v) = self.prop(m, "expansion", &anim::num, &label) { - o["x"] = v; - } + let mut o = Mask { name: Some(m.name.clone()), mode: Some(mask_mode(mode).into()), inverted: Some(inverted), ..Default::default() }; + o.path = self.prop(m, "path", &shapes::path_value, &label); + o.opacity = self.prop(m, "opacity", &anim::num, &label); + o.expansion = self.prop(m, "expansion", &anim::num, &label); if let Some(f) = m.get("feather") { if f.is_animated() || f.value.components().iter().any(|v| *v != 0.0) { self.ex.warn(format!("{label}: mask feather is exported as `f` (not every Lottie player renders it)")); } - o["f"] = export_prop(&mut self.ex, f, &anim::arr2, &format!("{label} ▸ Mask Feather")); + o.extra.insert("f".into(), export_prop(&mut self.ex, f, &anim::arr2, &format!("{label} ▸ Mask Feather")).0); } if !m.enabled { - o["mode"] = json!("n"); + o.mode = Some("n".into()); } out.push(o); } out } - fn effects(&mut self, l: &Layer) -> Vec { + fn effects(&mut self, l: &Layer) -> Vec { let Some(fx) = l.effects() else { return vec![] }; let mut out = vec![]; for (i, g) in fx.groups().enumerate() { @@ -268,11 +240,27 @@ impl Doc<'_> { }; (p.name.clone(), export_prop(&mut self.ex, p, &conv, &format!("{label} ▸ {}", p.name))) } - None => (format!("Param {}", pi + 1), json!({"a": 0, "k": konst})), + None => (format!("Param {}", pi + 1), fixed(json!(konst))), }; - params.push(json!({"ty": ty, "nm": nm, "mn": m, "ix": pi + 1, "v": v})); + params.push(Effect { + kind: Some(i64::from(*ty)), + name: Some(nm), + match_name: Some((*m).into()), + index: Some(pi as i64 + 1), + value: Some(v), + ..Default::default() + }); } - out.push(json!({"ty": map.ty, "nm": g.name, "mn": effect, "ix": i + 1, "en": g.enabled as u8, "np": params.len(), "ef": params})); + out.push(Effect { + kind: Some(i64::from(map.ty)), + name: Some(g.name.clone()), + match_name: Some(effect.clone()), + index: Some(i as i64 + 1), + enabled: Some(i64::from(g.enabled)), + count: Some(params.len() as i64), + values: Some(params), + ..Default::default() + }); } out } @@ -294,8 +282,16 @@ impl Doc<'_> { self.ex.warn(format!("{}: `{}` is not a PNG, JPEG, GIF or WebP image (layer exported as a null)", l.name, f.path)); return None; }; - let uri = format!("data:{mime};base64,{}", crate::base64::encode(&bytes)); - self.assets.push(json!({"id": id, "nm": it.name, "w": f.width, "h": f.height, "u": "", "p": uri, "e": 1})); + self.assets.push(Asset { + id: Some(id.clone()), + name: Some(it.name.clone()), + width: Some(f64::from(f.width)), + height: Some(f64::from(f.height)), + dir: Some(String::new()), + path: Some(craft_lottie::base64::to_data_uri(mime, &bytes)), + embedded: Some(1), + ..Default::default() + }); self.done.insert(id.clone()); Some(id) } @@ -309,11 +305,19 @@ impl Doc<'_> { let c = it.as_comp()?; self.done.insert(id.clone()); let layers = self.layers(c); - self.assets.push(json!({"id": id, "nm": it.name, "fr": c.frame_rate.as_f64(), "w": c.width, "h": c.height, "layers": layers})); + self.assets.push(Asset { + id: Some(id.clone()), + name: Some(it.name.clone()), + frame_rate: Some(c.frame_rate.as_f64()), + width: Some(f64::from(c.width)), + height: Some(f64::from(c.height)), + layers: Some(layers), + ..Default::default() + }); Some(id) } - fn layers(&mut self, comp: &Comp) -> Vec { + fn layers(&mut self, comp: &Comp) -> Vec { let mattes: BTreeSet<_> = comp.layers.iter().filter_map(|l| l.track_matte.map(|m| m.layer)).collect(); let mut out = vec![]; for (idx, l) in comp.layers.iter().enumerate() { @@ -322,11 +326,9 @@ impl Doc<'_> { out } - fn layer(&mut self, comp: &Comp, idx: usize, l: &Layer, is_matte: bool) -> Json { + fn layer(&mut self, comp: &Comp, idx: usize, l: &Layer, is_matte: bool) -> LottieLayer { let name = l.name.clone(); - let mut o = Map::new(); - o.insert("ind".into(), json!(idx + 1)); - o.insert("nm".into(), json!(name)); + let mut o = LottieLayer { index: Some(idx as i64 + 1), name: Some(name.clone()), ..Default::default() }; let three = l.is_3d(); if three { self.any_3d = true; @@ -334,34 +336,30 @@ impl Doc<'_> { self.ex.warn(format!("{name}: 3D layer exported with ddd: 1 (most Lottie players render 2D only)")); } } - o.insert("ddd".into(), json!(three as u8)); + o.three_d = Some(i64::from(three)); let mut hidden = !l.switches.video || l.switches.guide; - let mut ty = 3; + o.content = LayerContent::Null; match &l.source { LayerSource::Shape => { - ty = 4; let items = l.props.sub("contents").map(|c| shapes::export_items(&mut self.ex, c, &name)).unwrap_or_default(); - o.insert("shapes".into(), json!(items)); + o.content = LayerContent::Shape(items); } LayerSource::Text => { if self.opts.text_as_shapes { - ty = 4; - let items = text::glyph_shapes(&mut self.ex, l); - o.insert("shapes".into(), json!(items)); + o.content = LayerContent::Shape(text::glyph_shapes(&mut self.ex, l)); } else { - ty = 5; - let t = text::export_text(&mut self.ex, l, &mut self.fonts); - o.insert("t".into(), t); + o.content = LayerContent::Text(Box::new(text::export_text(&mut self.ex, l, &mut self.fonts))); } } LayerSource::Solid { item } => { let sol = self.project.item(*item).and_then(|i| if let ItemKind::Solid(s) = &i.kind { Some(s.clone()) } else { None }); match sol { Some(s) if !l.switches.adjustment => { - ty = 1; - o.insert("sc".into(), json!(hex(s.color))); - o.insert("sw".into(), json!(s.width)); - o.insert("sh".into(), json!(s.height)); + o.content = LayerContent::Solid(SolidLayer { + color: Some(craft_lottie::to_hex(s.color)), + width: Some(f64::from(s.width)), + height: Some(f64::from(s.height)), + }); } _ => { self.ex.warn(format!("{name}: adjustment layers are not part of Lottie (exported as a null)")); @@ -371,15 +369,9 @@ impl Doc<'_> { } LayerSource::Comp { item } => { if let Some(id) = self.precomp_asset(*item) { - ty = 0; let (w, h) = self.project.comp(*item).map(|c| (c.width, c.height)).unwrap_or((comp.width, comp.height)); - o.insert("refId".into(), json!(id)); - o.insert("w".into(), json!(w)); - o.insert("h".into(), json!(h)); - if let Some(tm) = l.props.get("timeRemap") { - let v = export_prop(&mut self.ex, tm, &anim::num, &format!("{name} ▸ Time Remap")); - o.insert("tm".into(), v); - } + let time_remap = l.props.get("timeRemap").map(|tm| export_prop(&mut self.ex, tm, &anim::num, &format!("{name} ▸ Time Remap"))); + o.content = LayerContent::Precomp(PrecompLayer { ref_id: Some(id), width: Some(f64::from(w)), height: Some(f64::from(h)), time_remap }); } } LayerSource::Footage { item } => { @@ -387,8 +379,7 @@ impl Doc<'_> { match kind { Some((FootageKind::Still, true)) => { if let Some(id) = self.image_asset(*item, l) { - ty = 2; - o.insert("refId".into(), json!(id)); + o.content = LayerContent::Image(Some(id)); } else { hidden = true; } @@ -413,20 +404,16 @@ impl Doc<'_> { hidden = true; } } - o.insert("ty".into(), json!(ty)); - if let Some(p) = l.parent.and_then(|p| comp.index_of(p)) { - o.insert("parent".into(), json!(p)); - } - o.insert("sr".into(), json!(l.stretch / 100.0)); + o.parent = l.parent.and_then(|p| comp.index_of(p)).map(|p| p as i64); + o.stretch = Some(l.stretch / 100.0); if l.stretch < 0.0 { self.ex.warn(format!("{name}: reversed time stretch is not supported by most Lottie players")); } - let ks = self.transform(l); - o.insert("ks".into(), ks); - o.insert("ao".into(), json!((l.auto_orient == effectcraft_project::AutoOrient::AlongPath) as u8)); - o.insert("ip".into(), json!(self.frame(l.in_point))); - o.insert("op".into(), json!(self.frame(l.out_point))); - o.insert("st".into(), json!(self.frame(l.start_time))); + o.transform = Some(self.transform(l)); + o.auto_orient = Some(i64::from(l.auto_orient == effectcraft_project::AutoOrient::AlongPath)); + o.in_point = Some(self.frame(l.in_point)); + o.out_point = Some(self.frame(l.out_point)); + o.start_time = Some(self.frame(l.start_time)); let bm = match crate::blend_to_lottie(l.blend_mode) { Some(b) => b, None => { @@ -434,32 +421,32 @@ impl Doc<'_> { 0 } }; - o.insert("bm".into(), json!(bm)); + o.blend_mode = Some(i64::from(bm)); let masks = self.masks(l); if !masks.is_empty() { - o.insert("hasMask".into(), json!(true)); - o.insert("masksProperties".into(), json!(masks)); + o.has_mask = Some(true); + o.masks = Some(masks); } let ef = self.effects(l); if !ef.is_empty() { - o.insert("ef".into(), json!(ef)); + o.effects = Some(ef); } if let Some(tm) = l.track_matte && let Some(mi) = comp.index_of(tm.layer) { - o.insert("tt".into(), json!(matte_code(tm.kind))); - o.insert("tp".into(), json!(mi)); + o.matte_mode = Some(i64::from(matte_code(tm.kind))); + o.matte_parent = Some(mi as i64); if mi != idx { self.ex.warn(format!("{name}: track matte layer is not directly above (players without `tp` support use the layer above)")); } } if is_matte { - o.insert("td".into(), json!(1)); + o.is_matte = Some(1); if l.switches.video { self.ex.warn(format!("{name}: visible track matte layer (Lottie always hides matte layers)")); } } else if hidden { - o.insert("hd".into(), json!(true)); + o.hidden = Some(true); } if !l.markers.is_empty() { self.ex.warn(format!("{name}: layer markers are not part of Lottie (composition markers are exported)")); @@ -471,7 +458,7 @@ impl Doc<'_> { if l.preserve_transparency { self.ex.warn(format!("{name}: Preserve Underlying Transparency is not part of Lottie")); } - Json::Object(o) + o } } @@ -493,33 +480,42 @@ pub fn export_comp(project: &Project, comp: ItemId, opts: &ExportOptions, read: }; doc.done.insert(format!("comp_{}", comp.0)); let layers = doc.layers(c); - let markers: Vec = c.markers.iter().map(|m| json!({"tm": doc.frame(m.time), "cm": m.comment, "dr": doc.frame(m.duration)})).collect(); - let mut out = json!({ - "v": "5.12.0", - "fr": c.frame_rate.as_f64(), - "ip": 0, - "op": doc.frame(c.duration), - "w": c.width, - "h": c.height, - "nm": item.name, - "ddd": doc.any_3d as u8, - "assets": doc.assets, - "layers": layers, - "markers": markers, - }); - if !doc.fonts.is_empty() { - out["fonts"] = json!({"list": doc.fonts}); - } - Ok(ExportResult { json: out, warnings: doc.ex.warnings }) + let markers: Vec = c + .markers + .iter() + .map(|m| Marker { time: Some(doc.frame(m.time)), comment: Some(m.comment.clone()), duration: Some(doc.frame(m.duration)), ..Default::default() }) + .collect(); + let animation = Animation { + version: Some("5.12.0".into()), + frame_rate: Some(c.frame_rate.as_f64()), + in_point: Some(0.0), + out_point: Some(doc.frame(c.duration)), + width: Some(f64::from(c.width)), + height: Some(f64::from(c.height)), + name: Some(item.name.clone()), + three_d: Some(i64::from(doc.any_3d)), + assets: Some(doc.assets), + layers: Some(layers), + markers: Some(markers), + fonts: (!doc.fonts.is_empty()).then(|| Fonts { list: Some(doc.fonts), ..Default::default() }), + ..Default::default() + }; + Ok(ExportResult { json: animation.to_json(), warnings: doc.ex.warnings }) } /// Package an export as a dotLottie archive (`manifest.json` + `animations/.json`). pub fn to_dotlottie(res: &ExportResult, id: &str) -> Vec { + try_to_dotlottie(res, id).unwrap_or_default() +} + +/// Package an export, reporting serialization or ZIP failures before any output is written. +pub fn try_to_dotlottie(res: &ExportResult, id: &str) -> Result, LottieError> { let id: String = id.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' || c == '-' { c } else { '_' }).collect(); let id = if id.is_empty() { "animation".to_string() } else { id }; let manifest = json!({"version": "1", "generator": "EffectCraft", "author": "", "animations": [{"id": id, "speed": 1, "loop": true}]}); - crate::zip::store(&[ - ("manifest.json".into(), serde_json::to_vec(&manifest).unwrap_or_default()), - (format!("animations/{id}.json"), serde_json::to_vec(&res.json).unwrap_or_default()), + crate::zip::try_store(&[ + ("manifest.json".into(), serde_json::to_vec(&manifest).map_err(|e| LottieError::Invalid(e.to_string()))?), + (format!("animations/{id}.json"), serde_json::to_vec(&res.json).map_err(|e| LottieError::Invalid(e.to_string()))?), ]) + .map_err(|e| LottieError::Invalid(format!("dotLottie ZIP: {e}"))) } diff --git a/crates/lottie/src/import.rs b/crates/lottie/src/import.rs index 1e1430e12..22dd8ad21 100644 --- a/crates/lottie/src/import.rs +++ b/crates/lottie/src/import.rs @@ -3,6 +3,8 @@ use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; +use craft_lottie::model::{Asset, Effect, Layer as LottieLayer, LayerContent, Mask, Transform}; +use craft_lottie::{Animated, Animation, Json}; use effectcraft_color::Label; use effectcraft_keyframe::{ShapePath, Value}; use effectcraft_project::build::{self, Ids}; @@ -11,9 +13,8 @@ use effectcraft_project::{ PropGroup, Property, Solid, TrackMatte, }; use effectcraft_time::{FrameRate, Tick}; -use serde_json::Value as Json; -use crate::anim::{self, Im, import_prop}; +use crate::anim::{self, Im, import_animated, import_prop}; use crate::export::{fx_by_id, fx_by_type, fx_params, mask_mode_from}; use crate::{LottieError, Timebase, shapes, text}; @@ -40,34 +41,25 @@ pub struct ImportResult { pub warnings: Vec, } -fn f(j: &Json, k: &str) -> Option { - j.get(k).and_then(Json::as_f64) -} - -fn s<'a>(j: &'a Json, k: &str) -> Option<&'a str> { - j.get(k).and_then(Json::as_str) -} - -fn hex_color(sc: &str) -> [f32; 3] { - let h = sc.trim_start_matches('#'); - let c = |i: usize| { - h.get(i..i + 2).filter(|x| x.bytes().all(|b| b.is_ascii_hexdigit())).and_then(|x| u8::from_str_radix(x, 16).ok()).unwrap_or(0) as f32 / 255.0 +/// The Lottie document inside raw bytes (plain JSON, or a dotLottie archive), read into +/// `craft-lottie`'s model within its default limits. +fn document(bytes: &[u8]) -> Result { + let read = |b: &[u8]| { + Animation::read(b).map_err(|e| match e { + craft_lottie::LottieError::Parse(m) => LottieError::Parse(m), + other => LottieError::Invalid(other.to_string()), + }) }; - [c(0), c(2), c(4)] -} - -/// The Lottie JSON inside raw bytes (plain JSON, or a stored dotLottie archive). -fn document(bytes: &[u8]) -> Result { if bytes.starts_with(b"PK") { - let entries = crate::zip::read_stored(bytes); + let entries = crate::zip::read_entries(bytes).map_err(|e| LottieError::Parse(format!("dotLottie ZIP: {e}")))?; let anim = entries .iter() .find(|(n, _)| n.starts_with("animations/") && n.ends_with(".json")) .or_else(|| entries.iter().find(|(n, _)| n.ends_with(".json") && n != "manifest.json")) - .ok_or_else(|| LottieError::Parse("dotLottie archive without an uncompressed animation".into()))?; - return serde_json::from_slice(&anim.1).map_err(|e| LottieError::Parse(e.to_string())); + .ok_or_else(|| LottieError::Parse("dotLottie archive without a JSON animation".into()))?; + return read(&anim.1); } - serde_json::from_slice(bytes).map_err(|e| LottieError::Parse(e.to_string())) + read(bytes) } struct Ctx<'a> { @@ -110,7 +102,7 @@ fn external_image(stored: &str, base_dir: &str) -> Result { } } -/// Import a Lottie document (JSON or a stored `.lottie` archive) into `project` as a new +/// Import a Lottie document (JSON or a `.lottie` archive) into `project` as a new /// composition. `store` saves embedded images and returns the file path to use; /// `base_dir` resolves external image references. pub fn import( @@ -121,30 +113,28 @@ pub fn import( store: &mut dyn FnMut(&ImportedImage) -> Option, ) -> Result { let doc = document(bytes)?; - let (Some(w), Some(h)) = (f(&doc, "w"), f(&doc, "h")) else { return Err(LottieError::Parse("missing `w`/`h`".into())) }; - let fr = f(&doc, "fr").filter(|v| *v > 0.0).unwrap_or(30.0); + let (Some(w), Some(h)) = (doc.width, doc.height) else { return Err(LottieError::Parse("missing `w`/`h`".into())) }; + let fr = doc.frame_rate.filter(|v| *v > 0.0).unwrap_or(30.0); let rate = FrameRate::from_f64(fr); let tb = Timebase { rate }; - let name = s(&doc, "nm").filter(|n| !n.is_empty()).unwrap_or(fallback_name).to_string(); - let ip = f(&doc, "ip").unwrap_or(0.0); - let op = f(&doc, "op").unwrap_or(ip + fr).max(ip + 1.0); + let name = doc.name.as_deref().filter(|n| !n.is_empty()).unwrap_or(fallback_name).to_string(); + let ip = doc.in_point.unwrap_or(0.0); + let op = doc.out_point.unwrap_or(ip + fr).max(ip + 1.0); let mut cx = Ctx { im: Im { tb, warnings: vec![] }, assets: BTreeMap::new(), fonts: vec![], store, base_dir, items: vec![], folder: None, name: name.clone() }; - if let Some(list) = doc.get("fonts").and_then(|f| f.get("list")).and_then(Json::as_array) { - for fo in list { - // Every text key referring to the font copies its family and style: keep them to - // a font name's length. - let short = |v: &str| v.chars().take(MAX_FONT_NAME_CHARS).collect::(); - let n = s(fo, "fName").unwrap_or("").to_string(); - let fam = short(s(fo, "fFamily").unwrap_or(&n)); - let st = short(s(fo, "fStyle").unwrap_or("Regular")); - cx.fonts.push((n, fam, st)); - } + for fo in doc.fonts.as_ref().and_then(|f| f.list.as_deref()).unwrap_or_default() { + // Every text key referring to the font copies its family and style: keep them to + // a font name's length. + let short = |v: &str| v.chars().take(MAX_FONT_NAME_CHARS).collect::(); + let n = fo.name.clone().unwrap_or_default(); + let fam = short(fo.family.as_deref().unwrap_or(&n)); + let st = short(fo.style.as_deref().unwrap_or("Regular")); + cx.fonts.push((n, fam, st)); } // Glyph outlines embedded for players without the fonts. Text is set in installed fonts. - if let Some(chars) = doc.get("chars").and_then(Json::as_array).filter(|c| !c.is_empty()) { + if let Some(chars) = doc.chars.as_deref().filter(|c| !c.is_empty()) { let mut fams: Vec<&str> = vec![]; - for fam in chars.iter().filter_map(|c| s(c, "fFamily")).filter(|f| !f.trim().is_empty()) { + for fam in chars.iter().filter_map(|c| c.family.as_deref()).filter(|f| !f.trim().is_empty()) { if !fams.contains(&fam) { fams.push(fam); } @@ -155,25 +145,27 @@ pub fn import( let (w, h) = (w.round().max(1.0) as u32, h.round().max(1.0) as u32); let duration = tb.tick(op); // Pass 1: asset items (precomps empty for now, images stored). - let assets = doc.get("assets").and_then(Json::as_array).cloned().unwrap_or_default(); - let layer_sizes = precomp_layer_sizes(&doc, &assets); - for a in &assets { - let Some(id) = s(a, "id") else { continue }; - if a.get("layers").is_some() { + let assets: &[Asset] = doc.assets.as_deref().unwrap_or_default(); + let top: &[LottieLayer] = doc.layers.as_deref().unwrap_or_default(); + let layer_sizes = precomp_layer_sizes(top, assets); + for a in assets { + let Some(id) = a.id.as_deref() else { continue }; + let size = a.width.zip(a.height).map(|(x, y)| (x as u32, y as u32)); + if a.layers.is_some() { let folder = cx.folder(project); let layer = layer_sizes.get(id).copied(); - let aw = f(a, "w").map(|v| v as u32).or(layer.map(|l| l.0)).unwrap_or(w); - let ah = f(a, "h").map(|v| v as u32).or(layer.map(|l| l.1)).unwrap_or(h); - let arate = f(a, "fr").map(FrameRate::from_f64).unwrap_or(rate); + let aw = a.width.map(|v| v as u32).or(layer.map(|l| l.0)).unwrap_or(w); + let ah = a.height.map(|v| v as u32).or(layer.map(|l| l.1)).unwrap_or(h); + let arate = a.frame_rate.map(FrameRate::from_f64).unwrap_or(rate); let c = Comp::new(aw, ah, arate, duration); - let nm = s(a, "nm").unwrap_or(id).to_string(); + let nm = a.name.as_deref().unwrap_or(id).to_string(); let item = project.add_item(&nm, Label::Sandstone, Some(folder), ItemKind::Comp(Arc::new(c))); cx.items.push(item); - cx.assets.insert(id.to_string(), (item, f(a, "w").zip(f(a, "h")).map(|(x, y)| (x as u32, y as u32)))); - } else if let Some(p) = s(a, "p") { - let (aw, ah) = (f(a, "w").unwrap_or(0.0) as u32, f(a, "h").unwrap_or(0.0) as u32); - let nm = s(a, "nm").unwrap_or(id).to_string(); - let path = if let Some((mime, data)) = crate::base64::data_uri(p) { + cx.assets.insert(id.to_string(), (item, size)); + } else if let Some(p) = a.path.as_deref() { + let (aw, ah) = (a.width.unwrap_or(0.0) as u32, a.height.unwrap_or(0.0) as u32); + let nm = a.name.as_deref().unwrap_or(id).to_string(); + let path = if let Some((mime, data)) = craft_lottie::base64::data_uri(p) { let ext = match mime.as_str() { "image/jpeg" | "image/jpg" => "jpg", "image/webp" => "webp", @@ -183,7 +175,7 @@ pub fn import( }; (cx.store)(&ImportedImage { id: id.to_string(), name: nm.clone(), bytes: data, ext: ext.into() }) } else { - let u = s(a, "u").unwrap_or(""); + let u = a.dir.as_deref().unwrap_or(""); match external_image(&format!("{u}{p}"), cx.base_dir) { Ok(path) => Some(path), Err(why) => { @@ -225,11 +217,11 @@ pub fn import( } } // Pass 2: precomp contents. - for a in &assets { - let (Some(id), Some(layers)) = (s(a, "id"), a.get("layers").and_then(Json::as_array)) else { continue }; + for a in assets { + let (Some(id), Some(layers)) = (a.id.as_deref(), a.layers.as_deref()) else { continue }; let Some((item, _)) = cx.assets.get(id).copied() else { continue }; let Some(mut c) = project.comp(item).cloned() else { continue }; - let end = layers.iter().filter_map(|l| f(l, "op")).fold(0.0f64, f64::max); + let end = layers.iter().filter_map(|l| l.out_point).fold(0.0f64, f64::max); if end > 0.0 { c.duration = tb.tick(end); c.work_area = (Tick::ZERO, c.duration); @@ -244,18 +236,15 @@ pub fn import( if ip > 0.0 { comp.work_area = (tb.tick(ip), duration); } - if let Some(ms) = doc.get("markers").and_then(Json::as_array) { - for m in ms { - comp.markers.push(Marker { - time: tb.tick(f(m, "tm").unwrap_or(0.0)), - duration: tb.tick(f(m, "dr").unwrap_or(0.0)), - comment: s(m, "cm").unwrap_or("").to_string(), - ..Default::default() - }); - } + for m in doc.markers.as_deref().unwrap_or_default() { + comp.markers.push(Marker { + time: tb.tick(m.time.unwrap_or(0.0)), + duration: tb.tick(m.duration.unwrap_or(0.0)), + comment: m.comment.clone().unwrap_or_default(), + ..Default::default() + }); } - let layers = doc.get("layers").and_then(Json::as_array).cloned().unwrap_or_default(); - build_layers(&mut cx, project, &mut comp, &layers); + build_layers(&mut cx, project, &mut comp, top); let id = project.add_item(&name, Label::Sandstone, None, ItemKind::Comp(Arc::new(comp))); cx.items.push(id); project.fix_next_id(); @@ -265,44 +254,46 @@ pub fn import( /// By asset id, the `w`/`h` of the first precomp layer, in the main comp or in any asset, that /// shows it. lottie-spec gives a precomposition asset no size: the layer's `w`/`h` are its /// clipping rect. One pass over all layers, not one per asset. -fn precomp_layer_sizes<'a>(doc: &'a Json, assets: &'a [Json]) -> HashMap<&'a str, (u32, u32)> { +fn precomp_layer_sizes<'a>(top: &'a [LottieLayer], assets: &'a [Asset]) -> HashMap<&'a str, (u32, u32)> { let mut out = HashMap::new(); - let lists = doc.get("layers").into_iter().chain(assets.iter().filter_map(|a| a.get("layers"))); - for l in lists.filter_map(Json::as_array).flatten() { - if l.get("ty").and_then(Json::as_u64) != Some(0) { - continue; - } - let (Some(id), Some((lw, lh))) = (s(l, "refId"), f(l, "w").zip(f(l, "h"))) else { continue }; + let lists = std::iter::once(top).chain(assets.iter().filter_map(|a| a.layers.as_deref())); + for l in lists.flatten() { + let LayerContent::Precomp(p) = &l.content else { continue }; + let (Some(id), Some((lw, lh))) = (p.ref_id.as_deref(), p.width.zip(p.height)) else { continue }; out.entry(id).or_insert((lw.round().max(1.0) as u32, lh.round().max(1.0) as u32)); } out } -fn transform(im: &Im, ks: &Json, tr: &mut PropGroup, next: &mut u64) { - let set = |tr: &mut PropGroup, m: &str, j: Option<&Json>, conv: &dyn Fn(&Json) -> Option| { - if let (Some(j), Some(p)) = (j, tr.get_mut(m)) { - import_prop(im, j, p, conv); +fn transform(im: &Im, ks: &Transform, tr: &mut PropGroup, next: &mut u64) { + let set = |tr: &mut PropGroup, m: &str, j: Option<&Animated>, conv: &dyn Fn(&Json) -> Option| { + if let Some(p) = tr.get_mut(m) { + import_animated(im, j, p, conv); } }; - set(tr, "anchor", ks.get("a"), &|v| anim::to_vec3(v, 0.0)); - set(tr, "scale", ks.get("s"), &|v| anim::to_vec3(v, 100.0)); - set(tr, "rotation", ks.get("r").or(ks.get("rz")), &anim::to_scalar); - set(tr, "rotationX", ks.get("rx"), &anim::to_scalar); - set(tr, "rotationY", ks.get("ry"), &anim::to_scalar); - set(tr, "orientation", ks.get("or"), &|v| anim::to_vec3(v, 0.0)); - set(tr, "opacity", ks.get("o"), &anim::to_scalar); - let Some(p) = ks.get("p") else { return }; - if p.get("s").and_then(Json::as_bool) == Some(true) { + set(tr, "anchor", ks.anchor.as_ref(), &|v| anim::to_vec3(v, 0.0)); + set(tr, "scale", ks.scale.as_ref(), &|v| anim::to_vec3(v, 100.0)); + set(tr, "rotation", ks.rotation.as_ref().or(ks.rotation_z.as_ref()), &anim::to_scalar); + set(tr, "rotationX", ks.rotation_x.as_ref(), &anim::to_scalar); + set(tr, "rotationY", ks.rotation_y.as_ref(), &anim::to_scalar); + set(tr, "orientation", ks.orientation.as_ref(), &|v| anim::to_vec3(v, 0.0)); + set(tr, "opacity", ks.opacity.as_ref(), &anim::to_scalar); + let Some(p) = &ks.position else { return }; + if let Some(dims) = p.split() { // Separated dimensions: X/Y/Z Position after Position. let at = tr.children.iter().position(|c| c.match_id() == "position").map(|i| i + 1).unwrap_or(tr.children.len()); let base = tr.get("position").map(|p| p.value.as_vec3()).unwrap_or([0.0; 3]); - for (d, (key, m, name)) in - [("x", "positionX", "X Position"), ("y", "positionY", "Y Position"), ("z", "positionZ", "Z Position")].iter().enumerate().rev() + for (d, (j, m, name)) in dims + .iter() + .zip([("positionX", "X Position"), ("positionY", "Y Position"), ("positionZ", "Z Position")]) + .map(|(j, (m, n))| (j, m, n)) + .enumerate() + .rev() { let mut pr = Property::new(*next, m, name, Value::Scalar(base[d])).with_ui(ParamUi::Number); *next += 1; pr.three_d_only = d == 2; - if let Some(j) = p.get(*key) { + if let Some(j) = j { import_prop(im, j, &mut pr, &anim::to_scalar); } tr.children.insert(at, Node::Prop(pr)); @@ -312,50 +303,50 @@ fn transform(im: &Im, ks: &Json, tr: &mut PropGroup, next: &mut u64) { } } -fn masks(im: &Im, ids: &mut Ids, list: &[Json], g: &mut PropGroup) { +fn masks(im: &Im, ids: &mut Ids, list: &[Mask], g: &mut PropGroup) { for (i, m) in list.iter().enumerate() { - let mode = mask_mode_from(s(m, "mode").unwrap_or("a")); - let name = s(m, "nm").map(str::to_string).unwrap_or(format!("Mask {}", i + 1)); + let mode = mask_mode_from(m.mode.as_deref().unwrap_or("a")); + let name = m.name.clone().unwrap_or(format!("Mask {}", i + 1)); let color = build::MASK_COLORS[i % build::MASK_COLORS.len()]; let mut mg = build::mask(ids, &name, ShapePath::default(), mode, color); if let GroupKind::Mask { inverted, .. } = &mut mg.kind { - *inverted = m.get("inv").and_then(Json::as_bool).unwrap_or(false); + *inverted = m.inverted.unwrap_or(false); } - let mut set = |k: &str, mid: &str, conv: &dyn Fn(&Json) -> Option| { - if let (Some(j), Some(p)) = (m.get(k), mg.get_mut(mid)) { + let mut set = |j: Option<&Json>, mid: &str, conv: &dyn Fn(&Json) -> Option| { + if let (Some(j), Some(p)) = (j, mg.get_mut(mid)) { import_prop(im, j, p, conv); } }; - let closed = m.get("cl").and_then(Json::as_bool).unwrap_or(false); - set("pt", "path", &|v| shapes::to_path(v, closed)); - set("o", "opacity", &anim::to_scalar); - set("x", "expansion", &anim::to_scalar); - set("f", "feather", &anim::to_vec2); + let closed = m.closed.unwrap_or(false); + set(m.path.as_ref().map(|a| &a.0), "path", &|v| shapes::to_path(v, closed)); + set(m.opacity.as_ref().map(|a| &a.0), "opacity", &anim::to_scalar); + set(m.expansion.as_ref().map(|a| &a.0), "expansion", &anim::to_scalar); + set(m.extra.get("f"), "feather", &anim::to_vec2); g.children.push(Node::Group(mg)); } } -fn effects(im: &mut Im, ids: &mut Ids, list: &[Json], g: &mut PropGroup, size: [f64; 2]) { +fn effects(im: &mut Im, ids: &mut Ids, list: &[Effect], g: &mut PropGroup, size: [f64; 2]) { for e in list { - let ty = e.get("ty").and_then(Json::as_u64).unwrap_or(0); - let params = e.get("ef").and_then(Json::as_array).cloned().unwrap_or_default(); - let inner_ty = params.first().and_then(|p| p.get("ty")).and_then(Json::as_u64); - let map = s(e, "mn").and_then(fx_by_id).or_else(|| fx_by_type(ty, inner_ty)); - let nm = s(e, "nm").unwrap_or("Effect"); + let ty = e.kind.and_then(|t| u64::try_from(t).ok()).unwrap_or(0); + let params: &[Effect] = e.values.as_deref().unwrap_or_default(); + let inner_ty = params.first().and_then(|p| p.kind).and_then(|t| u64::try_from(t).ok()); + let map = e.match_name.as_deref().and_then(fx_by_id).or_else(|| fx_by_type(ty, inner_ty)); + let nm = e.name.as_deref().unwrap_or("Effect"); let Some(map) = map else { im.warn(format!("effect `{nm}` (type {ty}) is not supported (skipped)")); continue; }; let Some(spec) = effectcraft_effects::find(map.id) else { continue }; let mut fg = effectcraft_effects::instantiate(spec, ids, nm, size); - if e.get("en").and_then(Json::as_u64) == Some(0) { + if e.enabled == Some(0) { fg.enabled = false; } for (i, (m, pty, scale, _)) in fx_params(map).iter().enumerate() { if m.is_empty() { continue; } - let Some(pj) = params.get(i).and_then(|p| p.get("v")) else { continue }; + let Some(pj) = params.get(i).and_then(|p| p.value.as_ref()) else { continue }; let Some(p) = fg.get_mut(m) else { continue }; let (pty, scale) = (*pty, *scale); let conv = move |v: &Json| -> Option { @@ -367,79 +358,84 @@ fn effects(im: &mut Im, ids: &mut Ids, list: &[Json], g: &mut PropGroup, size: [ _ => anim::to_scalar(v).map(|x| Value::Scalar(x.as_f64() / scale)), } }; - import_prop(im, pj, p, &conv); + import_prop(im, &pj.0, p, &conv); } g.children.push(Node::Group(fg)); } } -fn layer_source(cx: &mut Ctx, project: &mut Project, comp: &Comp, j: &Json) -> Option<(LayerSource, (u32, u32))> { - let ty = j.get("ty").and_then(Json::as_u64).unwrap_or(99); +fn layer_source(cx: &mut Ctx, project: &mut Project, comp: &Comp, j: &LottieLayer) -> Option<(LayerSource, (u32, u32))> { let full = (comp.width, comp.height); - let asset = |cx: &Ctx| s(j, "refId").and_then(|r| cx.assets.get(r).copied()); - Some(match ty { - 0 => { - let Some((item, _)) = asset(cx) else { - cx.im.warn(format!("{}: missing precomp asset", s(j, "nm").unwrap_or("layer"))); + let nm = j.name.as_deref(); + let asset = |cx: &Ctx, r: Option<&str>| r.and_then(|r| cx.assets.get(r).copied()); + Some(match &j.content { + LayerContent::Precomp(p) => { + let Some((item, _)) = asset(cx, p.ref_id.as_deref()) else { + cx.im.warn(format!("{}: missing precomp asset", nm.unwrap_or("layer"))); return None; }; let size = project.comp(item).map(|c| (c.width, c.height)).unwrap_or(full); (LayerSource::Comp { item }, size) } - 1 => { - let sw = f(j, "sw").unwrap_or(comp.width as f64).round().max(1.0) as u32; - let sh = f(j, "sh").unwrap_or(comp.height as f64).round().max(1.0) as u32; - let color = hex_color(s(j, "sc").unwrap_or("#000000")); - let name = s(j, "nm").unwrap_or("Solid"); + LayerContent::Solid(sl) => { + let sw = sl.width.unwrap_or(comp.width as f64).round().max(1.0) as u32; + let sh = sl.height.unwrap_or(comp.height as f64).round().max(1.0) as u32; + let color = craft_lottie::hex_color(sl.color.as_deref().unwrap_or("#000000")); + let name = nm.unwrap_or("Solid"); let folder = cx.folder(project); let item = project.add_item(name, Label::Red, Some(folder), ItemKind::Solid(Solid { color, width: sw, height: sh, pixel_aspect: 1.0 })); cx.items.push(item); (LayerSource::Solid { item }, (sw, sh)) } - 2 => { - let Some((item, size)) = asset(cx) else { - cx.im.warn(format!("{}: missing image asset", s(j, "nm").unwrap_or("layer"))); + LayerContent::Image(r) => { + let Some((item, size)) = asset(cx, r.as_deref()) else { + cx.im.warn(format!("{}: missing image asset", nm.unwrap_or("layer"))); return None; }; (LayerSource::Footage { item }, size.unwrap_or(full)) } - 3 => (LayerSource::Null, (100, 100)), - 4 => (LayerSource::Shape, full), - 5 => (LayerSource::Text, full), - 13 => { - cx.im.warn(format!("{}: camera layers are not imported", s(j, "nm").unwrap_or("camera"))); - return None; - } - other => { - cx.im.warn(format!("{}: layer type {other} is not supported (skipped)", s(j, "nm").unwrap_or("layer"))); - return None; - } + LayerContent::Null => (LayerSource::Null, (100, 100)), + LayerContent::Shape(_) => (LayerSource::Shape, full), + LayerContent::Text(_) => (LayerSource::Text, full), + LayerContent::Other(ty) => match ty.as_u64().unwrap_or(99) { + // A shape or text layer whose content is missing or unreadable is an empty one. + 4 => (LayerSource::Shape, full), + 5 => (LayerSource::Text, full), + 13 => { + cx.im.warn(format!("{}: camera layers are not imported", nm.unwrap_or("camera"))); + return None; + } + other => { + cx.im.warn(format!("{}: layer type {other} is not supported (skipped)", nm.unwrap_or("layer"))); + return None; + } + }, }) } /// Build the layers of a comp (Lottie order: first = top = layer #1). -fn build_layers(cx: &mut Ctx, project: &mut Project, comp: &mut Comp, layers: &[Json]) { +fn build_layers(cx: &mut Ctx, project: &mut Project, comp: &mut Comp, layers: &[LottieLayer]) { let tb = cx.im.tb; let mut by_ind: BTreeMap = BTreeMap::new(); // (layer id, its index in `comp.layers`, parent ind, matte: (kind, explicit tp ind), json position) let mut pending: Vec<(LayerId, usize, Option, Option<(MatteKind, Option)>, usize)> = vec![]; let mut pos_ind: Vec> = vec![]; for (ji, j) in layers.iter().enumerate() { - let ind = j.get("ind").and_then(Json::as_i64); + let ind = j.index; pos_ind.push(ind); let Some((source, size)) = layer_source(cx, project, comp, j) else { continue }; - let name = s(j, "nm").unwrap_or(source.type_name()).to_string(); + let name = j.name.clone().unwrap_or_else(|| source.type_name().to_string()); let mut l: Layer = build::layer(project, comp, &name, source.clone(), size, None); if let Some(i) = ind { by_ind.insert(i, l.id); } - let ip = f(j, "ip").unwrap_or(0.0); - let op = f(j, "op").unwrap_or(tb.frame(comp.duration)); + let ip = j.in_point.unwrap_or(0.0); + let op = j.out_point.unwrap_or(tb.frame(comp.duration)); l.in_point = tb.tick(ip); l.out_point = tb.tick(op.max(ip)); - l.start_time = tb.tick(f(j, "st").unwrap_or(0.0)); + l.start_time = tb.tick(j.start_time.unwrap_or(0.0)); // Below 1 % (or 0) the layer time divides by ~0, and layer.timeStretch refuses it too. - let sr = f(j, "sr").unwrap_or(1.0); + let sr = j.stretch.unwrap_or(1.0); l.stretch = if sr.is_finite() && sr.abs() >= 0.01 { // Past ±9900 % too (#3247): the largest stretch a layer supports, sign kept. let pct = effectcraft_project::limits::stretch(sr * 100.0); @@ -451,73 +447,70 @@ fn build_layers(cx: &mut Ctx, project: &mut Project, comp: &mut Comp, layers: &[ cx.im.warn(format!("{name}: a time stretch of {} % is not supported (100 % used)", sr * 100.0)); 100.0 }; - if j.get("ddd").and_then(Json::as_u64) == Some(1) { + if j.three_d == Some(1) { l.switches.three_d = true; } - if let Some(bm) = j.get("bm").and_then(Json::as_u64) { + if let Some(bm) = j.blend_mode.and_then(|b| u64::try_from(b).ok()) { l.blend_mode = crate::blend_from_lottie(bm); } - if j.get("ao").and_then(Json::as_u64) == Some(1) { + if j.auto_orient == Some(1) { l.auto_orient = AutoOrient::AlongPath; } - if j.get("hd").and_then(Json::as_bool) == Some(true) { + if j.hidden == Some(true) { l.switches.video = false; } - if j.get("td").and_then(Json::as_u64) == Some(1) { + if j.is_matte == Some(1) { l.switches.video = false; } let mut next = project.next_id; - if let (Some(ks), Some(tr)) = (j.get("ks"), l.props.sub_mut("transform")) { + if let (Some(ks), Some(tr)) = (&j.transform, l.props.sub_mut("transform")) { transform(&cx.im, ks, tr, &mut next); } let mut ids = Ids(&mut next); - match &source { - LayerSource::Shape => { - let mut items = j.get("shapes").and_then(Json::as_array).into_iter().flatten(); - let groups = shapes::import_items(&mut cx.im, &mut ids, &mut items); + match (&source, &j.content) { + (LayerSource::Shape, LayerContent::Shape(items)) => { + let groups = shapes::import_items(&mut cx.im, &mut ids, &mut items.iter()); if let Some(c) = l.props.sub_mut("contents") { c.children.extend(groups.into_iter().map(Node::Group)); } } - LayerSource::Text => { - if let (Some(t), Some(tg)) = (j.get("t"), l.props.sub_mut("text")) { + (LayerSource::Text, LayerContent::Text(t)) => { + if let Some(tg) = l.props.sub_mut("text") { text::import_text(&mut cx.im, &mut ids, t, tg, &cx.fonts); } } - LayerSource::Comp { .. } => { - if let Some(tm) = j.get("tm") { + (LayerSource::Comp { .. }, LayerContent::Precomp(p)) => { + if let Some(tm) = &p.time_remap { let mut pr = ids.prop("timeRemap", "Time Remap", Value::Scalar(0.0)).with_ui(ParamUi::Number); - import_prop(&cx.im, tm, &mut pr, &anim::to_scalar); + import_prop(&cx.im, &tm.0, &mut pr, &anim::to_scalar); l.props.children.insert(0, Node::Prop(pr)); } } _ => {} } - if let Some(list) = j.get("masksProperties").and_then(Json::as_array) + if let Some(list) = &j.masks && let Some(g) = l.props.sub_mut("masks") { masks(&cx.im, &mut ids, list, g); } - if let Some(list) = j.get("ef").and_then(Json::as_array) + if let Some(list) = &j.effects && let Some(g) = l.props.sub_mut("effects") { effects(&mut cx.im, &mut ids, list, g, [size.0 as f64, size.1 as f64]); } - if j.get("sy").and_then(Json::as_array).is_some_and(|a| !a.is_empty()) { + if j.extra.get("sy").and_then(Json::as_array).is_some_and(|a| !a.is_empty()) { cx.im.warn(format!("{name}: layer styles are not imported")); } project.next_id = next; - let parent = j.get("parent").and_then(Json::as_i64); - let tt = j.get("tt").and_then(Json::as_u64).unwrap_or(0); - let matte = match tt { + let matte = match j.matte_mode.unwrap_or(0) { 1 => Some(MatteKind::Alpha), 2 => Some(MatteKind::AlphaInverted), 3 => Some(MatteKind::Luma), 4 => Some(MatteKind::LumaInverted), _ => None, } - .map(|k| (k, j.get("tp").and_then(Json::as_i64))); - pending.push((l.id, comp.layers.len(), parent, matte, ji)); + .map(|k| (k, j.matte_parent)); + pending.push((l.id, comp.layers.len(), j.parent, matte, ji)); comp.layers.push(l); } for (id, at, parent, matte, ji) in pending { @@ -536,15 +529,3 @@ fn build_layers(cx: &mut Ctx, project: &mut Project, comp: &mut Comp, layers: &[ } } } - -#[cfg(test)] -mod hex_color_tests { - use super::hex_color; - - #[test] - fn hex_color_rejects_plus_sign() { - assert_eq!(hex_color("#+f0000"), [0.0, 0.0, 0.0]); - assert_eq!(hex_color("#zz0000"), [0.0, 0.0, 0.0]); - assert_eq!(hex_color("#ff0000"), [1.0, 0.0, 0.0]); - } -} diff --git a/crates/lottie/src/lib.rs b/crates/lottie/src/lib.rs index 1b12cc8be..7ce4d9063 100644 --- a/crates/lottie/src/lib.rs +++ b/crates/lottie/src/lib.rs @@ -1,7 +1,7 @@ //! Lottie JSON import and export. //! -//! Implemented from the public Lottie format description (the lottie-spec 1.0 schema and the -//! LottieFiles format documentation); no player or exporter source was used. +//! The format itself (the document model, property and keyframe encoding, paths, gradients, +//! embedded images) is `craft-lottie`; this crate maps it onto EffectCraft's project. //! //! **Export** ([`export_comp`]) turns a composition into a Lottie document: nested compositions //! become precomp assets, still footage becomes embedded base64 image assets, and shape, solid, @@ -21,7 +21,6 @@ #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] mod anim; -mod base64; mod export; mod import; mod shapes; @@ -31,7 +30,7 @@ pub mod zip; use effectcraft_color::BlendMode; use effectcraft_time::{FrameRate, TICKS_PER_SECOND, Tick}; -pub use export::{ExportOptions, ExportResult, export_comp, to_dotlottie}; +pub use export::{ExportOptions, ExportResult, export_comp, to_dotlottie, try_to_dotlottie}; pub use import::{ImportResult, ImportedImage, import}; #[derive(Debug, thiserror::Error)] diff --git a/crates/lottie/src/shapes.rs b/crates/lottie/src/shapes.rs index 6cd1f09cc..f28e73a04 100644 --- a/crates/lottie/src/shapes.rs +++ b/crates/lottie/src/shapes.rs @@ -1,23 +1,27 @@ //! Shape layer contents ↔ Lottie shape items (`gr`, `rc`, `el`, `sr`, `sh`, `fl`, `st`, `gf`, -//! `gs`, `tm`, `rp`, `rd`, `op`, `pb`, `tw`, `zz`, `mm`, `tr`). +//! `gs`, `tm`, `rp`, `rd`, `op`, `pb`, `tw`, `zz`, `mm`, `tr`), on `craft-lottie`'s model. +use craft_lottie::model::{ + Dash, Ellipse, Fill, GradientColors, GradientFill, GradientStroke, Group, Map, Merge, OffsetPath, Path, PolyStar, PuckerBloat, Rect, Repeater, + RepeaterTransform, RoundCorners, Shape, ShapeKind, Stroke, Transform, Trim, Twist, ZigZag, +}; +use craft_lottie::{Animated, Bezier, Json}; use effectcraft_color::BlendMode; use effectcraft_keyframe::{Gradient, ShapePath, Value}; use effectcraft_project::build::{self, EXTRA_DASHES, Ids}; use effectcraft_project::{Node, ParamUi, PropGroup}; -use serde_json::{Map, Value as Json, json}; +use serde_json::json; use crate::anim::{self, Ex, Im, export_prop, import_prop}; // ---------------------------------------------------------------- shared value converters -pub(crate) fn shape_json(p: &ShapePath) -> Json { - let pts = |v: &[[f64; 2]]| v.iter().map(|q| json!([r(q[0]), r(q[1])])).collect::>(); - json!({"c": p.closed, "v": pts(&p.vertices), "i": pts(&p.in_tangents), "o": pts(&p.out_tangents)}) +pub(crate) fn bezier(p: &ShapePath) -> Bezier { + Bezier { closed: p.closed, vertices: p.vertices.clone(), in_tangents: p.in_tangents.clone(), out_tangents: p.out_tangents.clone() } } -fn r(v: f64) -> f64 { - (v * 1e6).round() / 1e6 +pub(crate) fn shape_json(p: &ShapePath) -> Json { + bezier(p).to_json() } pub(crate) fn path_value(v: &Value) -> Json { @@ -30,29 +34,8 @@ pub(crate) fn path_value(v: &Value) -> Json { /// A Lottie path. `closed` is used when the path has no `c`: Bodymovin 3.x and early 4.x keep the /// flag outside the path, as `cl` on a mask and `closed` on an `sh` item. pub(crate) fn to_path(j: &Json, closed: bool) -> Option { - let o = match j { - Json::Array(a) => a.first()?, - o => o, - }; - let pts = |k: &str| -> Vec<[f64; 2]> { - o.get(k) - .and_then(Json::as_array) - .map(|a| a.iter().map(|p| anim::nums(p).map(|v| [*v.first().unwrap_or(&0.0), *v.get(1).unwrap_or(&0.0)]).unwrap_or([0.0; 2])).collect()) - .unwrap_or_default() - }; - let vertices = pts("v"); - let n = vertices.len(); - let fit = |mut v: Vec<[f64; 2]>| { - v.resize(n, [0.0; 2]); - v - }; - Some(Value::Path(ShapePath { - in_tangents: fit(pts("i")), - out_tangents: fit(pts("o")), - vertices, - closed: o.get("c").and_then(Json::as_bool).unwrap_or(closed), - feather: Vec::new(), - })) + let b = Bezier::from_json(j, closed)?; + Some(Value::Path(ShapePath { vertices: b.vertices, in_tangents: b.in_tangents, out_tangents: b.out_tangents, closed: b.closed, feather: Vec::new() })) } /// Gradient as Lottie's flat stop list: `[pos, r, g, b]…` then `[pos, alpha]…`. @@ -61,29 +44,19 @@ pub(crate) fn gradient_flat(v: &Value) -> Json { Value::Gradient(g) => g.clone(), _ => Gradient::default(), }; - let mut out = vec![]; - for (p, c) in &g.colors { - out.extend([r(*p), r(c[0] as f64), r(c[1] as f64), r(c[2] as f64)]); + craft_lottie::Gradient { + colors: g.colors.iter().map(|(p, c)| (*p, [f64::from(c[0]), f64::from(c[1]), f64::from(c[2])])).collect(), + opacities: g.opacities.iter().map(|(p, a)| (*p, f64::from(*a))).collect(), } - let plain = g.opacities.iter().all(|(_, a)| (*a - 1.0).abs() < 1e-6); - if !plain { - for (p, a) in &g.opacities { - out.extend([r(*p), r(*a as f64)]); - } - } - json!(out) + .to_flat() } pub(crate) fn to_gradient(j: &Json, ncolors: usize) -> Option { - let v = anim::nums(j)?; - let n = ncolors.min(v.len() / 4); - let colors: Vec<(f64, [f32; 4])> = (0..n).map(|i| (v[i * 4], [v[i * 4 + 1] as f32, v[i * 4 + 2] as f32, v[i * 4 + 3] as f32, 1.0])).collect(); - let rest = &v[n * 4..]; - let mut opacities: Vec<(f64, f32)> = rest.chunks(2).filter(|c| c.len() == 2).map(|c| (c[0], c[1] as f32)).collect(); - if opacities.is_empty() { - opacities = vec![(0.0, 1.0), (1.0, 1.0)]; - } - Some(Value::Gradient(Gradient { colors, opacities })) + let g = craft_lottie::Gradient::from_flat(j, ncolors)?; + Some(Value::Gradient(Gradient { + colors: g.colors.iter().map(|(p, [r, gr, b])| (*p, [*r as f32, *gr as f32, *b as f32, 1.0])).collect(), + opacities: g.opacities.iter().map(|(p, a)| (*p, *a as f32)).collect(), + })) } fn blend_index(m: BlendMode) -> u32 { @@ -92,22 +65,18 @@ fn blend_index(m: BlendMode) -> u32 { // ---------------------------------------------------------------- export +/// A group's properties, exported with the warnings they need. struct Out<'a, 'b> { ex: &'a mut Ex, g: &'b PropGroup, - o: Map, label: String, } impl Out<'_, '_> { - fn put(&mut self, key: &str, m: &str, conv: &dyn Fn(&Value) -> Json) { - if let Some(p) = self.g.get(m) { - let v = export_prop(self.ex, p, conv, &format!("{} ▸ {}", self.label, p.name)); - self.o.insert(key.into(), v); - } - } - fn raw(&mut self, key: &str, v: Json) { - self.o.insert(key.into(), v); + /// The property `m` of the group, when it has one. + fn put(&mut self, m: &str, conv: &dyn Fn(&Value) -> Json) -> Option { + let p = self.g.get(m)?; + Some(export_prop(self.ex, p, conv, &format!("{} ▸ {}", self.label, p.name))) } fn e(&self, m: &str) -> u32 { self.g.get(m).map(|p| p.value.as_enum()).unwrap_or(0) @@ -121,34 +90,46 @@ impl Out<'_, '_> { fn animated(&self, m: &str) -> bool { self.g.get(m).is_some_and(|p| p.is_animated() || p.has_expression()) } - fn blend(&mut self) { + fn blend(&mut self) -> i64 { let i = self.e("blend"); let m = BlendMode::ALL.get(i as usize).copied().unwrap_or_default(); match crate::blend_to_lottie(m) { - Some(bm) => self.raw("bm", json!(bm)), + Some(bm) => i64::from(bm), None => { self.ex.warn(format!("{}: blend mode {m:?} has no Lottie equivalent (Normal used)", self.label)); - self.raw("bm", json!(0)); + 0 } } } - fn done(self) -> Json { - Json::Object(self.o) + fn direction(&self) -> i64 { + if self.e("direction") == 1 { 3 } else { 1 } } } -/// Stroke fields shared by `st` and `gs`. -fn stroke_fields(o: &mut Out) { - o.put("w", "width", &anim::num); - o.raw("lc", json!(o.e("cap") + 1)); - o.raw("lj", json!(o.e("join") + 1)); - o.raw("ml", json!(o.f("miter"))); +/// A static property (`{a: 0, k}`). +pub(crate) fn fixed(k: Json) -> Animated { + Animated(json!({"a": 0, "k": k})) +} + +/// Stroke fields shared by `st` and `gs`: width, cap, join, miter limit, dashes. +struct StrokeOut { + width: Option, + cap: i64, + join: i64, + miter: f64, + dashes: Option>, +} + +fn stroke_fields(o: &mut Out) -> StrokeOut { + let width = o.put("width", &anim::num); + let (cap, join, miter) = (i64::from(o.e("cap")) + 1, i64::from(o.e("join")) + 1, o.f("miter")); let used = |g: Option<&PropGroup>, m: &str| g.and_then(|g| g.get(m)).is_some_and(|p| p.is_animated() || p.value.as_f64().abs() > 1e-9); let (taper, wave) = (o.g.sub("taper"), o.g.sub("wave")); if used(taper, "startLength") || used(taper, "endLength") || used(wave, "amount") { let msg = format!("{}: stroke Taper and Wave have no Lottie equivalent (uniform width exported)", o.label); o.ex.warn(msg); } + let mut dashes = None; if let Some(d) = o.g.sub("dashes") { let dash = d.get("dash").map(|p| p.value.as_f64()).unwrap_or(0.0); if dash > 0.0 || d.any_animated() { @@ -156,202 +137,257 @@ fn stroke_fields(o: &mut Out) { for (n, m) in [("d", "dash"), ("g", "gap"), ("d", "dash2"), ("g", "gap2"), ("d", "dash3"), ("g", "gap3"), ("o", "offset")] { if let Some(p) = d.get(m) { let v = export_prop(o.ex, p, &anim::num, &format!("{} ▸ Dashes ▸ {}", o.label, p.name)); - list.push(json!({"n": n, "nm": p.name, "v": v})); + list.push(Dash { kind: Some(n.into()), name: Some(p.name.clone()), length: Some(v), ..Default::default() }); } } - o.raw("d", json!(list)); + dashes = Some(list); } } + StrokeOut { width, cap, join, miter, dashes } } -fn shape_transform(ex: &mut Ex, tr: &PropGroup, label: &str) -> Json { - let mut o = Out { ex, g: tr, o: Map::new(), label: format!("{label} ▸ Transform") }; - o.raw("ty", json!("tr")); - o.put("a", "anchor", &anim::arr2); - o.put("p", "position", &anim::arr2); - o.put("s", "scale", &anim::arr2); - o.put("r", "rotation", &anim::num); - o.put("o", "opacity", &anim::num); - o.put("sk", "skew", &anim::num); - o.put("sa", "skewAxis", &anim::num); - o.put("so", "startOpacity", &anim::num); - o.put("eo", "endOpacity", &anim::num); - o.done() +/// The `tr` of a group or a repeater: anchor, position, scale, rotation, opacity, skew, and the +/// repeater's start and end opacity, by their Lottie keys. +fn shape_transform(ex: &mut Ex, tr: &PropGroup, label: &str) -> Vec<(&'static str, Animated)> { + let mut o = Out { ex, g: tr, label: format!("{label} ▸ Transform") }; + let mut out = vec![]; + for (k, m, conv) in [ + ("a", "anchor", anim::arr2 as fn(&Value) -> Json), + ("p", "position", anim::arr2), + ("s", "scale", anim::arr2), + ("r", "rotation", anim::num), + ("o", "opacity", anim::num), + ("sk", "skew", anim::num), + ("sa", "skewAxis", anim::num), + ("so", "startOpacity", anim::num), + ("eo", "endOpacity", anim::num), + ] { + if let Some(v) = o.put(m, &conv) { + out.push((k, v)); + } + } + out +} + +/// The `tr` item that ends a group's items. +fn group_transform(keys: Vec<(&'static str, Animated)>) -> Shape { + let (mut t, mut extra) = (Transform::default(), Map::new()); + for (k, v) in keys { + match k { + "a" => t.anchor = Some(v), + "p" => t.position = Some(v), + "s" => t.scale = Some(v), + "r" => t.rotation = Some(v), + "o" => t.opacity = Some(v), + "sk" => t.skew = Some(v), + "sa" => t.skew_axis = Some(v), + _ => { + extra.insert(k.into(), v.0); + } + } + } + Shape { kind: ShapeKind::Transform(Box::new(t)), extra, ..Default::default() } +} + +/// A repeater's `tr`, which players read with `ty: "tr"` like a group's. +fn repeater_transform(keys: Vec<(&'static str, Animated)>) -> RepeaterTransform { + let mut t = RepeaterTransform::default(); + t.extra.insert("ty".into(), json!("tr")); + for (k, v) in keys { + match k { + "a" => t.anchor = Some(v), + "p" => t.position = Some(v), + "s" => t.scale = Some(v), + "r" => t.rotation = Some(v), + "so" => t.start_opacity = Some(v), + "eo" => t.end_opacity = Some(v), + "sk" => t.skew = Some(v), + "sa" => t.skew_axis = Some(v), + _ => { + t.extra.insert(k.into(), v.0); + } + } + } + t } /// Export a contents group's items (first item = top, as in the timeline). -pub(crate) fn export_items(ex: &mut Ex, contents: &PropGroup, label: &str) -> Vec { +pub(crate) fn export_items(ex: &mut Ex, contents: &PropGroup, label: &str) -> Vec { let mut out = vec![]; for node in &contents.children { let Node::Group(g) = node else { continue }; let lbl = format!("{label} ▸ {}", g.name); - let ty = match g.match_id.as_str() { - "group" => "gr", - "rect" => "rc", - "ellipse" => "el", - "star" => "sr", - "path" => "sh", - "fill" => "fl", - "stroke" => "st", - "gfill" => "gf", - "gstroke" => "gs", - "trim" => "tm", - "repeater" => "rp", - "round" => "rd", - "offset" => "op", - "pucker" => "pb", - "twist" => "tw", - "zigzag" => "zz", - "merge" => "mm", - other => { - ex.warn(format!("{lbl}: shape item `{other}` has no Lottie equivalent (skipped)")); - continue; + let mut o = Out { ex, g, label: lbl.clone() }; + let mut blend = None; + let kind = match g.match_id.as_str() { + "group" => { + let mut items = g.sub("contents").map(|c| export_items(o.ex, c, &lbl)).unwrap_or_default(); + items.push(match g.sub("transform") { + Some(t) => group_transform(shape_transform(o.ex, t, &lbl)), + None => group_transform(vec![ + ("a", fixed(json!([0, 0]))), + ("p", fixed(json!([0, 0]))), + ("s", fixed(json!([100, 100]))), + ("r", fixed(json!(0))), + ("o", fixed(json!(100))), + ]), + }); + blend = Some(o.blend()); + ShapeKind::Group(Group { count: Some(items.len() as f64), items: Some(items) }) } - }; - let mut o = Out { ex, g, o: Map::new(), label: lbl.clone() }; - o.raw("ty", json!(ty)); - o.raw("nm", json!(g.name)); - if !g.enabled { - o.raw("hd", json!(true)); - } - let dir = |o: &mut Out| { - let d = if o.e("direction") == 1 { 3 } else { 1 }; - o.raw("d", json!(d)); - }; - match ty { - "gr" => { - let items = g.sub("contents").map(|c| export_items(o.ex, c, &lbl)).unwrap_or_default(); - let mut items = items; - let tr = match g.sub("transform") { - Some(t) => shape_transform(o.ex, t, &lbl), - None => { - json!({"ty": "tr", "a": {"a": 0, "k": [0, 0]}, "p": {"a": 0, "k": [0, 0]}, "s": {"a": 0, "k": [100, 100]}, "r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}}) - } - }; - items.push(tr); - o.raw("np", json!(items.len())); - o.raw("it", json!(items)); - o.blend(); - } - "rc" => { - dir(&mut o); - o.put("s", "size", &anim::arr2); - o.put("p", "position", &anim::arr2); - if o.flag("perCorner") { + "rect" => { + let direction = Some(o.direction()); + let size = o.put("size", &anim::arr2); + let position = o.put("position", &anim::arr2); + let roundness = if o.flag("perCorner") { let names = ["topLeftRoundness", "topRightRoundness", "bottomRightRoundness", "bottomLeftRoundness"]; let radii = names.map(|m| o.f(m)); // Lottie `rc` has one `r`: four equal static radii export as that value. // `r` is a property (`{a, k}`) like the uniform branch writes, not a bare number. if radii.iter().all(|v| (v - radii[0]).abs() < 1e-6) && !names.iter().any(|m| o.animated(m)) && radii[0] >= 0.0 { - o.raw("r", json!({"a": 0, "k": r(radii[0])})); + Some(fixed(json!(craft_lottie::round6(radii[0])))) } else { o.ex.warn(format!("{}: per-corner roundness has no Lottie rectangle equivalent (roundness 0 exported)", o.label)); - o.raw("r", json!({"a": 0, "k": 0})); + Some(fixed(json!(0))) } } else { - o.put("r", "roundness", &anim::num); - } + o.put("roundness", &anim::num) + }; + ShapeKind::Rect(Rect { direction, position, size, roundness }) } - "el" => { - dir(&mut o); - o.put("s", "size", &anim::arr2); - o.put("p", "position", &anim::arr2); + "ellipse" => { + let direction = Some(o.direction()); + let size = o.put("size", &anim::arr2); + ShapeKind::Ellipse(Ellipse { direction, position: o.put("position", &anim::arr2), size }) } - "sr" => { - dir(&mut o); - o.raw("sy", json!(o.e("type") + 1)); - o.put("pt", "points", &anim::num); - o.put("p", "position", &anim::arr2); - o.put("r", "rotation", &anim::num); - o.put("ir", "innerRadius", &anim::num); - o.put("or", "outerRadius", &anim::num); - o.put("is", "innerRoundness", &anim::num); - o.put("os", "outerRoundness", &anim::num); + "star" => ShapeKind::PolyStar(PolyStar { + direction: Some(o.direction()), + star_type: Some(i64::from(o.e("type")) + 1), + points: o.put("points", &anim::num), + position: o.put("position", &anim::arr2), + rotation: o.put("rotation", &anim::num), + inner_radius: o.put("innerRadius", &anim::num), + outer_radius: o.put("outerRadius", &anim::num), + inner_roundness: o.put("innerRoundness", &anim::num), + outer_roundness: o.put("outerRoundness", &anim::num), + }), + "path" => ShapeKind::Path(Path { direction: Some(o.direction()), path: o.put("path", &path_value), closed: None }), + "fill" => { + let f = Fill { color: o.put("color", &anim::arr), opacity: o.put("opacity", &anim::num), rule: Some(i64::from(o.e("rule")) + 1) }; + blend = Some(o.blend()); + ShapeKind::Fill(f) } - "sh" => { - dir(&mut o); - o.put("ks", "path", &path_value); + "stroke" => { + let (color, opacity) = (o.put("color", &anim::arr), o.put("opacity", &anim::num)); + let st = stroke_fields(&mut o); + blend = Some(o.blend()); + ShapeKind::Stroke(Stroke { + color, + opacity, + width: st.width, + cap: Some(st.cap), + join: Some(st.join), + miter_limit: Some(st.miter), + miter_limit_animated: None, + dashes: st.dashes, + }) } - "fl" => { - o.put("c", "color", &anim::arr); - o.put("o", "opacity", &anim::num); - o.raw("r", json!(o.e("rule") + 1)); - o.blend(); - } - "st" => { - o.put("c", "color", &anim::arr); - o.put("o", "opacity", &anim::num); - stroke_fields(&mut o); - o.blend(); - } - "gf" | "gs" => { - o.put("o", "opacity", &anim::num); - o.put("s", "start", &anim::arr2); - o.put("e", "end", &anim::arr2); - o.raw("t", json!(o.e("type") + 1)); - o.put("h", "highlightLength", &anim::num); - o.put("a", "highlightAngle", &anim::num); + m @ ("gfill" | "gstroke") => { + let opacity = o.put("opacity", &anim::num); + let (start, end) = (o.put("start", &anim::arr2), o.put("end", &anim::arr2)); + let gradient_type = Some(i64::from(o.e("type")) + 1); + let (highlight_length, highlight_angle) = (o.put("highlightLength", &anim::num), o.put("highlightAngle", &anim::num)); let ncolors = match g.get("colors").map(|p| &p.value) { Some(Value::Gradient(gr)) => gr.colors.len(), _ => 2, }; - if let Some(p) = g.get("colors") { - let k = export_prop(o.ex, p, &gradient_flat, &format!("{lbl} ▸ Colors")); - o.raw("g", json!({"p": ncolors, "k": k})); - } - if ty == "gf" { - o.raw("r", json!(o.e("rule") + 1)); + let colors = g.get("colors").map(|p| GradientColors { + count: Some(ncolors as i64), + stops: Some(export_prop(o.ex, p, &gradient_flat, &format!("{lbl} ▸ Colors"))), + ..Default::default() + }); + let kind = if m == "gfill" { + ShapeKind::GradientFill(GradientFill { + colors, + start, + end, + gradient_type, + highlight_length, + highlight_angle, + opacity, + rule: Some(i64::from(o.e("rule")) + 1), + }) } else { - stroke_fields(&mut o); - } - o.blend(); + let st = stroke_fields(&mut o); + ShapeKind::GradientStroke(GradientStroke { + colors, + start, + end, + gradient_type, + highlight_length, + highlight_angle, + opacity, + width: st.width, + cap: Some(st.cap), + join: Some(st.join), + miter_limit: Some(st.miter), + miter_limit_animated: None, + dashes: st.dashes, + }) + }; + blend = Some(o.blend()); + kind } - "tm" => { - o.put("s", "start", &anim::num); - o.put("e", "end", &anim::num); - o.put("o", "offset", &anim::num); - o.raw("m", json!(o.e("mode") + 1)); - } - "rp" => { - o.put("c", "copies", &anim::num); - o.put("o", "offset", &anim::num); + "trim" => ShapeKind::Trim(Trim { + start: o.put("start", &anim::num), + end: o.put("end", &anim::num), + offset: o.put("offset", &anim::num), + multiple: Some(i64::from(o.e("mode")) + 1), + }), + "repeater" => { + let (copies, offset) = (o.put("copies", &anim::num), o.put("offset", &anim::num)); // Lottie: 1 = Above, 2 = Below; EffectCraft: 0 = Below, 1 = Above. - o.raw("m", json!(if o.e("composite") == 1 { 1 } else { 2 })); - if let Some(t) = g.sub("transform") { - let tr = shape_transform(o.ex, t, &lbl); - o.raw("tr", tr); - } + let composite = Some(if o.e("composite") == 1 { 1 } else { 2 }); + let transform = g.sub("transform").map(|t| repeater_transform(shape_transform(o.ex, t, &lbl))); + ShapeKind::Repeater(Repeater { copies, offset, composite, transform }) } - "rd" => o.put("r", "radius", &anim::num), - "op" => { - o.put("a", "amount", &anim::num); - o.raw("lj", json!(o.e("join") + 1)); - o.put("ml", "miter", &anim::num); + "round" => ShapeKind::RoundCorners(RoundCorners { radius: o.put("radius", &anim::num) }), + "offset" => { + let amount = o.put("amount", &anim::num); + let join = Some(i64::from(o.e("join")) + 1); + let miter_limit = o.put("miter", &anim::num); if (o.f("copies") - 1.0).abs() > 1e-9 || o.animated("copies") || o.f("copyOffset") != 0.0 { o.ex.warn(format!("{lbl}: Offset Paths copies are not part of Lottie (one copy exported)")); } + ShapeKind::OffsetPath(OffsetPath { amount, join, miter_limit }) } - "pb" => o.put("a", "amount", &anim::num), - "tw" => { - o.put("a", "angle", &anim::num); - o.put("c", "center", &anim::arr2); + "pucker" => ShapeKind::PuckerBloat(PuckerBloat { amount: o.put("amount", &anim::num) }), + "twist" => ShapeKind::Twist(Twist { angle: o.put("angle", &anim::num), center: o.put("center", &anim::arr2) }), + "zigzag" => ShapeKind::ZigZag(ZigZag { + frequency: o.put("size", &anim::num), + amount: o.put("ridges", &anim::num), + point_type: Some(fixed(json!(o.e("points") + 1))), + }), + "merge" => ShapeKind::Merge(Merge { mode: Some(i64::from(o.e("mode")) + 1) }), + other => { + o.ex.warn(format!("{lbl}: shape item `{other}` has no Lottie equivalent (skipped)")); + continue; } - "zz" => { - o.put("s", "size", &anim::num); - o.put("r", "ridges", &anim::num); - o.raw("pt", json!({"a": 0, "k": o.e("points") + 1})); - } - "mm" => o.raw("mm", json!(o.e("mode") + 1)), - _ => {} - } - out.push(o.done()); + }; + out.push(Shape { name: Some(g.name.clone()), hidden: (!g.enabled).then_some(true), blend_mode: blend, kind, ..Default::default() }); } out } // ---------------------------------------------------------------- import -fn set(im: &Im, g: &mut PropGroup, m: &str, j: Option<&Json>, conv: &dyn Fn(&Json) -> Option) { +fn set(im: &Im, g: &mut PropGroup, m: &str, j: Option<&Animated>, conv: &dyn Fn(&Json) -> Option) { + if let (Some(j), Some(p)) = (j, g.get_mut(m)) { + import_prop(im, &j.0, p, conv); + } +} + +fn set_json(im: &Im, g: &mut PropGroup, m: &str, j: Option<&Json>, conv: &dyn Fn(&Json) -> Option) { if let (Some(j), Some(p)) = (j, g.get_mut(m)) { import_prop(im, j, p, conv); } @@ -363,43 +399,60 @@ fn set_enum(g: &mut PropGroup, m: &str, v: u32) { } } -fn int(j: &Json, k: &str) -> Option { - let v = j.get(k)?; +/// A whole number however a file writes it: `2`, `2.0`, `2.4` (rounded) or a property `{k: 2}`. +fn int_json(v: Option<&Json>) -> Option { + let v = v?; v.as_i64().or_else(|| v.as_f64().map(|f| f.round() as i64)).or_else(|| v.get("k").and_then(anim::nums).and_then(|n| n.first().map(|f| f.round() as i64))) } -fn import_blend(j: &Json, g: &mut PropGroup) { - if let Some(bm) = j.get("bm").and_then(Json::as_u64) { +/// An integer key of the model, or the value the model kept in `extra` when it was written +/// another way. +fn int(field: Option, extra: &Map, key: &str) -> Option { + field.or_else(|| int_json(extra.get(key))) +} + +fn import_blend(s: &Shape, g: &mut PropGroup) { + if let Some(bm) = int(s.blend_mode, &s.extra, "bm").and_then(|b| u64::try_from(b).ok()) { set_enum(g, "blend", blend_index(crate::blend_from_lottie(bm))); } } -fn import_stroke(im: &Im, ids: &mut Ids, j: &Json, g: &mut PropGroup) { - set(im, g, "width", j.get("w"), &anim::to_scalar); - if let Some(lc) = int(j, "lc") { +/// The stroke keys of `st` and `gs`. +struct StrokeIn<'a> { + width: Option<&'a Animated>, + cap: Option, + join: Option, + miter: Option, + miter_animated: Option<&'a Animated>, + dashes: Option<&'a [Dash]>, +} + +fn import_stroke(im: &Im, ids: &mut Ids, st: StrokeIn<'_>, g: &mut PropGroup) { + set(im, g, "width", st.width, &anim::to_scalar); + if let Some(lc) = st.cap { set_enum(g, "cap", lc.saturating_sub(1).clamp(0, 2) as u32); } - if let Some(lj) = int(j, "lj") { + if let Some(lj) = st.join { set_enum(g, "join", lj.saturating_sub(1).clamp(0, 2) as u32); } if let Some(p) = g.get_mut("miter") { - if let Some(ml) = j.get("ml").and_then(Json::as_f64) { + if let Some(ml) = st.miter { p.value = Value::Scalar(ml); - } else if let Some(ml2) = j.get("ml2") { - import_prop(im, ml2, p, &anim::to_scalar); + } else if let Some(ml2) = st.miter_animated { + import_prop(im, &ml2.0, p, &anim::to_scalar); } } - if let Some(list) = j.get("d").and_then(Json::as_array) + if let Some(list) = st.dashes && let Some(d) = g.sub_mut("dashes") { // The n-th `d` and `g` are the n-th Dash/Gap pair; the extra pairs are created as the Dashes "+" does. let (mut dashes, mut gaps) = (0, 0); for e in list { - let (n, pair) = match e.get("n").and_then(Json::as_str) { + let (n, pair) = match e.kind.as_deref() { Some("d") => (&mut dashes, 0), Some("g") => (&mut gaps, 1), Some("o") => { - set(im, d, "offset", e.get("v"), &anim::to_scalar); + set(im, d, "offset", e.length.as_ref(), &anim::to_scalar); continue; } _ => continue, @@ -418,206 +471,299 @@ fn import_stroke(im: &Im, ids: &mut Ids, j: &Json, g: &mut PropGroup) { [dm, gm][pair] } }; - set(im, d, m, e.get("v"), &anim::to_scalar); + set(im, d, m, e.length.as_ref(), &anim::to_scalar); } } } -fn import_shape_transform(im: &Im, j: &Json, tr: &mut PropGroup) { - set(im, tr, "anchor", j.get("a"), &anim::to_vec2); - set(im, tr, "position", j.get("p"), &anim::to_vec2); - set(im, tr, "scale", j.get("s"), &anim::to_vec2); - set(im, tr, "rotation", j.get("r"), &anim::to_scalar); - set(im, tr, "opacity", j.get("o"), &anim::to_scalar); - set(im, tr, "skew", j.get("sk"), &anim::to_scalar); - set(im, tr, "skewAxis", j.get("sa"), &anim::to_scalar); - set(im, tr, "startOpacity", j.get("so"), &anim::to_scalar); - set(im, tr, "endOpacity", j.get("eo"), &anim::to_scalar); +/// A `tr` (of a group or a repeater), looked up by its Lottie keys. +fn import_shape_transform(im: &Im, get: &dyn Fn(&str) -> Option, tr: &mut PropGroup) { + for (k, m, conv) in [ + ("a", "anchor", anim::to_vec2 as fn(&Json) -> Option), + ("p", "position", anim::to_vec2), + ("s", "scale", anim::to_vec2), + ("r", "rotation", anim::to_scalar), + ("o", "opacity", anim::to_scalar), + ("sk", "skew", anim::to_scalar), + ("sa", "skewAxis", anim::to_scalar), + ("so", "startOpacity", anim::to_scalar), + ("eo", "endOpacity", anim::to_scalar), + ] { + set_json(im, tr, m, get(k).as_ref(), &conv); + } +} + +/// A named key of the model, or the same key kept in `extra`. +fn key(a: Option<&Animated>, extra: &Map, k: &str) -> Option { + a.map(|a| a.0.clone()).or_else(|| extra.get(k).cloned()) +} + +fn group_tr_get<'a>(t: &'a Transform, item: &'a Map) -> impl Fn(&str) -> Option + 'a { + move |k| { + let named = match k { + "a" => t.anchor.as_ref(), + "p" => t.position.as_ref(), + "s" => t.scale.as_ref(), + "r" => t.rotation.as_ref(), + "o" => t.opacity.as_ref(), + "sk" => t.skew.as_ref(), + "sa" => t.skew_axis.as_ref(), + _ => None, + }; + key(named, &t.extra, k).or_else(|| item.get(k).cloned()) + } +} + +fn repeater_tr_get(t: &RepeaterTransform) -> impl Fn(&str) -> Option + '_ { + move |k| { + let named = match k { + "a" => t.anchor.as_ref(), + "p" => t.position.as_ref(), + "s" => t.scale.as_ref(), + "r" => t.rotation.as_ref(), + "so" => t.start_opacity.as_ref(), + "eo" => t.end_opacity.as_ref(), + "sk" => t.skew.as_ref(), + "sa" => t.skew_axis.as_ref(), + _ => None, + }; + key(named, &t.extra, k) + } } /// Import Lottie shape items into shape contents groups. -pub(crate) fn import_items(im: &mut Im, ids: &mut Ids, items: &mut dyn Iterator) -> Vec { +pub(crate) fn import_items(im: &mut Im, ids: &mut Ids, items: &mut dyn Iterator) -> Vec { let mut out = vec![]; - for j in items { - let ty = j.get("ty").and_then(Json::as_str).unwrap_or(""); - let dir = |g: &mut PropGroup| { - if int(j, "d") == Some(3) { + for s in items { + let x = &s.extra; + let dir = |g: &mut PropGroup, d: Option| { + if int(d, x, "d") == Some(3) { set_enum(g, "direction", 1); } }; - let mut g = match ty { - "gr" => { + let mut g = match &s.kind { + ShapeKind::Group(gr) => { + let list = gr.items.as_deref().unwrap_or_default(); // Borrowed, not cloned: each nesting level copying its subtree costs memory // quadratic in the depth. - let list = j.get("it").and_then(Json::as_array).map(Vec::as_slice).unwrap_or_default(); - let children = import_items(im, ids, &mut list.iter().filter(|i| i.get("ty").and_then(Json::as_str) != Some("tr"))); + let children = import_items(im, ids, &mut list.iter().filter(|i| !matches!(i.kind, ShapeKind::Transform(_)))); let mut g = build::shape_group(ids, "Group 1", children); - if let Some(tr) = list.iter().find(|i| i.get("ty").and_then(Json::as_str) == Some("tr")) - && let Some(t) = g.sub_mut("transform") + if let Some(tr) = list.iter().find(|i| matches!(i.kind, ShapeKind::Transform(_))) + && let ShapeKind::Transform(t) = &tr.kind + && let Some(tg) = g.sub_mut("transform") { - import_shape_transform(im, tr, t); + import_shape_transform(im, &group_tr_get(t, &tr.extra), tg); } - import_blend(j, &mut g); + import_blend(s, &mut g); g } - "rc" => { + ShapeKind::Rect(r) => { let mut g = build::shape_rect(ids, [100.0, 100.0], [0.0, 0.0], 0.0); - dir(&mut g); - set(im, &mut g, "size", j.get("s"), &anim::to_vec2); - set(im, &mut g, "position", j.get("p"), &anim::to_vec2); - set(im, &mut g, "roundness", j.get("r"), &anim::to_scalar); + dir(&mut g, r.direction); + set(im, &mut g, "size", r.size.as_ref(), &anim::to_vec2); + set(im, &mut g, "position", r.position.as_ref(), &anim::to_vec2); + set(im, &mut g, "roundness", r.roundness.as_ref(), &anim::to_scalar); // Lottie has one roundness: keep the per-corner values in step so ticking the box // on an imported rectangle keeps the shape. for m in ["topLeftRoundness", "topRightRoundness", "bottomRightRoundness", "bottomLeftRoundness"] { - set(im, &mut g, m, j.get("r"), &anim::to_scalar); + set(im, &mut g, m, r.roundness.as_ref(), &anim::to_scalar); } g } - "el" => { + ShapeKind::Ellipse(e) => { let mut g = build::shape_ellipse(ids, [100.0, 100.0], [0.0, 0.0]); - dir(&mut g); - set(im, &mut g, "size", j.get("s"), &anim::to_vec2); - set(im, &mut g, "position", j.get("p"), &anim::to_vec2); + dir(&mut g, e.direction); + set(im, &mut g, "size", e.size.as_ref(), &anim::to_vec2); + set(im, &mut g, "position", e.position.as_ref(), &anim::to_vec2); g } - "sr" => { - let star = int(j, "sy").unwrap_or(1) != 2; + ShapeKind::PolyStar(p) => { + let star = int(p.star_type, x, "sy").unwrap_or(1) != 2; let mut g = build::shape_star(ids, star, 5.0, [0.0, 0.0], 100.0, 50.0); - dir(&mut g); - set(im, &mut g, "points", j.get("pt"), &anim::to_scalar); - set(im, &mut g, "position", j.get("p"), &anim::to_vec2); - set(im, &mut g, "rotation", j.get("r"), &anim::to_scalar); - set(im, &mut g, "innerRadius", j.get("ir"), &anim::to_scalar); - set(im, &mut g, "outerRadius", j.get("or"), &anim::to_scalar); - set(im, &mut g, "innerRoundness", j.get("is"), &anim::to_scalar); - set(im, &mut g, "outerRoundness", j.get("os"), &anim::to_scalar); + dir(&mut g, p.direction); + set(im, &mut g, "points", p.points.as_ref(), &anim::to_scalar); + set(im, &mut g, "position", p.position.as_ref(), &anim::to_vec2); + set(im, &mut g, "rotation", p.rotation.as_ref(), &anim::to_scalar); + set(im, &mut g, "innerRadius", p.inner_radius.as_ref(), &anim::to_scalar); + set(im, &mut g, "outerRadius", p.outer_radius.as_ref(), &anim::to_scalar); + set(im, &mut g, "innerRoundness", p.inner_roundness.as_ref(), &anim::to_scalar); + set(im, &mut g, "outerRoundness", p.outer_roundness.as_ref(), &anim::to_scalar); g } - "sh" => { + ShapeKind::Path(p) => { let mut g = build::shape_path(ids, ShapePath::default()); - dir(&mut g); - let closed = j.get("closed").and_then(Json::as_bool).unwrap_or(false); - set(im, &mut g, "path", j.get("ks"), &|v| to_path(v, closed)); + dir(&mut g, p.direction); + let closed = p.closed.unwrap_or(false); + set(im, &mut g, "path", p.path.as_ref(), &|v| to_path(v, closed)); g } - "fl" => { + ShapeKind::Fill(f) => { let mut g = build::shape_fill(ids, [1.0, 1.0, 1.0, 1.0]); - set(im, &mut g, "color", j.get("c"), &anim::to_color); - set(im, &mut g, "opacity", j.get("o"), &anim::to_scalar); - if int(j, "r") == Some(2) { + set(im, &mut g, "color", f.color.as_ref(), &anim::to_color); + set(im, &mut g, "opacity", f.opacity.as_ref(), &anim::to_scalar); + if int(f.rule, x, "r") == Some(2) { set_enum(&mut g, "rule", 1); } - import_blend(j, &mut g); + import_blend(s, &mut g); g } - "st" => { + ShapeKind::Stroke(st) => { let mut g = build::shape_stroke(ids, [1.0, 1.0, 1.0, 1.0], 2.0); - set(im, &mut g, "color", j.get("c"), &anim::to_color); - set(im, &mut g, "opacity", j.get("o"), &anim::to_scalar); - import_stroke(im, ids, j, &mut g); - import_blend(j, &mut g); - g - } - "gf" | "gs" => { - let radial = int(j, "t") == Some(2); - let mut g = if ty == "gf" { - build::shape_gradient_fill(ids, radial, [0.0, 0.0], [100.0, 0.0], Gradient::default()) - } else { - build::shape_gradient_stroke(ids, radial, [0.0, 0.0], [100.0, 0.0], Gradient::default(), 2.0) + set(im, &mut g, "color", st.color.as_ref(), &anim::to_color); + set(im, &mut g, "opacity", st.opacity.as_ref(), &anim::to_scalar); + let fields = StrokeIn { + width: st.width.as_ref(), + cap: int(st.cap, x, "lc"), + join: int(st.join, x, "lj"), + miter: st.miter_limit, + miter_animated: st.miter_limit_animated.as_ref(), + dashes: st.dashes.as_deref(), }; - set(im, &mut g, "opacity", j.get("o"), &anim::to_scalar); - set(im, &mut g, "start", j.get("s"), &anim::to_vec2); - set(im, &mut g, "end", j.get("e"), &anim::to_vec2); - set(im, &mut g, "highlightLength", j.get("h"), &anim::to_scalar); - set(im, &mut g, "highlightAngle", j.get("a"), &anim::to_scalar); - if let Some(gj) = j.get("g") { - let n = gj.get("p").and_then(Json::as_u64).unwrap_or(2) as usize; - if let Some(k) = gj.get("k") { - set(im, &mut g, "colors", Some(k), &move |v| to_gradient(v, n)); - } - } - if ty == "gf" { - if int(j, "r") == Some(2) { - set_enum(&mut g, "rule", 1); - } - } else { - import_stroke(im, ids, j, &mut g); - } - import_blend(j, &mut g); + import_stroke(im, ids, fields, &mut g); + import_blend(s, &mut g); g } - "tm" => { + ShapeKind::GradientFill(gf) => { + let radial = int(gf.gradient_type, x, "t") == Some(2); + let mut g = build::shape_gradient_fill(ids, radial, [0.0, 0.0], [100.0, 0.0], Gradient::default()); + gradient_common( + im, + &mut g, + gf.opacity.as_ref(), + gf.start.as_ref(), + gf.end.as_ref(), + gf.highlight_length.as_ref(), + gf.highlight_angle.as_ref(), + gf.colors.as_ref(), + ); + if int(gf.rule, x, "r") == Some(2) { + set_enum(&mut g, "rule", 1); + } + import_blend(s, &mut g); + g + } + ShapeKind::GradientStroke(gs) => { + let radial = int(gs.gradient_type, x, "t") == Some(2); + let mut g = build::shape_gradient_stroke(ids, radial, [0.0, 0.0], [100.0, 0.0], Gradient::default(), 2.0); + gradient_common( + im, + &mut g, + gs.opacity.as_ref(), + gs.start.as_ref(), + gs.end.as_ref(), + gs.highlight_length.as_ref(), + gs.highlight_angle.as_ref(), + gs.colors.as_ref(), + ); + let fields = StrokeIn { + width: gs.width.as_ref(), + cap: int(gs.cap, x, "lc"), + join: int(gs.join, x, "lj"), + miter: gs.miter_limit, + miter_animated: gs.miter_limit_animated.as_ref(), + dashes: gs.dashes.as_deref(), + }; + import_stroke(im, ids, fields, &mut g); + import_blend(s, &mut g); + g + } + ShapeKind::Trim(t) => { let mut g = build::shape_trim(ids, 0.0, 100.0, 0.0); - set(im, &mut g, "start", j.get("s"), &anim::to_scalar); - set(im, &mut g, "end", j.get("e"), &anim::to_scalar); - set(im, &mut g, "offset", j.get("o"), &anim::to_scalar); - if int(j, "m") == Some(2) { + set(im, &mut g, "start", t.start.as_ref(), &anim::to_scalar); + set(im, &mut g, "end", t.end.as_ref(), &anim::to_scalar); + set(im, &mut g, "offset", t.offset.as_ref(), &anim::to_scalar); + if int(t.multiple, x, "m") == Some(2) { set_enum(&mut g, "mode", 1); } g } - "rp" => { + ShapeKind::Repeater(r) => { let mut g = build::shape_repeater(ids, 3.0, [100.0, 0.0]); - set(im, &mut g, "copies", j.get("c"), &anim::to_scalar); - set(im, &mut g, "offset", j.get("o"), &anim::to_scalar); - set_enum(&mut g, "composite", if int(j, "m") == Some(1) { 1 } else { 0 }); - if let (Some(tr), Some(t)) = (j.get("tr"), g.sub_mut("transform")) { - import_shape_transform(im, tr, t); + set(im, &mut g, "copies", r.copies.as_ref(), &anim::to_scalar); + set(im, &mut g, "offset", r.offset.as_ref(), &anim::to_scalar); + set_enum(&mut g, "composite", if int(r.composite, x, "m") == Some(1) { 1 } else { 0 }); + if let (Some(tr), Some(t)) = (r.transform.as_ref(), g.sub_mut("transform")) { + import_shape_transform(im, &repeater_tr_get(tr), t); } g } - "rd" | "op" | "pb" | "tw" | "zz" | "mm" => { - let kind = match ty { - "rd" => "round", - "op" => "offset", - "pb" => "pucker", - "tw" => "twist", - "zz" => "zigzag", - _ => "merge", - }; - let Some(mut g) = build::shape_simple_op(ids, kind) else { continue }; - match ty { - "rd" => set(im, &mut g, "radius", j.get("r"), &anim::to_scalar), - "op" => { - set(im, &mut g, "amount", j.get("a"), &anim::to_scalar); - if let Some(lj) = int(j, "lj") { - set_enum(&mut g, "join", lj.saturating_sub(1).clamp(0, 2) as u32); - } - set(im, &mut g, "miter", j.get("ml"), &anim::to_scalar); - } - "pb" => set(im, &mut g, "amount", j.get("a"), &anim::to_scalar), - "tw" => { - set(im, &mut g, "angle", j.get("a"), &anim::to_scalar); - set(im, &mut g, "center", j.get("c"), &anim::to_vec2); - } - "zz" => { - set(im, &mut g, "size", j.get("s"), &anim::to_scalar); - set(im, &mut g, "ridges", j.get("r"), &anim::to_scalar); - if int(j, "pt") == Some(2) { - set_enum(&mut g, "points", 1); - } - } - _ => { - if let Some(m) = int(j, "mm") { - set_enum(&mut g, "mode", m.saturating_sub(1).clamp(0, 4) as u32); - } - } + ShapeKind::RoundCorners(r) => { + let Some(mut g) = build::shape_simple_op(ids, "round") else { continue }; + set(im, &mut g, "radius", r.radius.as_ref(), &anim::to_scalar); + g + } + ShapeKind::OffsetPath(op) => { + let Some(mut g) = build::shape_simple_op(ids, "offset") else { continue }; + set(im, &mut g, "amount", op.amount.as_ref(), &anim::to_scalar); + if let Some(lj) = int(op.join, x, "lj") { + set_enum(&mut g, "join", lj.saturating_sub(1).clamp(0, 2) as u32); + } + set(im, &mut g, "miter", op.miter_limit.as_ref(), &anim::to_scalar); + g + } + ShapeKind::PuckerBloat(pb) => { + let Some(mut g) = build::shape_simple_op(ids, "pucker") else { continue }; + set(im, &mut g, "amount", pb.amount.as_ref(), &anim::to_scalar); + g + } + ShapeKind::Twist(tw) => { + let Some(mut g) = build::shape_simple_op(ids, "twist") else { continue }; + set(im, &mut g, "angle", tw.angle.as_ref(), &anim::to_scalar); + set(im, &mut g, "center", tw.center.as_ref(), &anim::to_vec2); + g + } + ShapeKind::ZigZag(zz) => { + let Some(mut g) = build::shape_simple_op(ids, "zigzag") else { continue }; + set(im, &mut g, "size", zz.frequency.as_ref(), &anim::to_scalar); + set(im, &mut g, "ridges", zz.amount.as_ref(), &anim::to_scalar); + if int_json(zz.point_type.as_ref().map(|a| &a.0)) == Some(2) { + set_enum(&mut g, "points", 1); } g } - "tr" => continue, - other => { - im.warn(format!("shape item `{other}` is not supported (skipped)")); + ShapeKind::Merge(mm) => { + let Some(mut g) = build::shape_simple_op(ids, "merge") else { continue }; + if let Some(m) = int(mm.mode, x, "mm") { + set_enum(&mut g, "mode", m.saturating_sub(1).clamp(0, 4) as u32); + } + g + } + ShapeKind::Transform(_) => continue, + ShapeKind::Other(ty) => { + im.warn(format!("shape item `{}` is not supported (skipped)", ty.as_str().unwrap_or(""))); continue; } }; - if let Some(nm) = j.get("nm").and_then(Json::as_str) { - g.name = nm.to_string(); + if let Some(nm) = &s.name { + g.name = nm.clone(); } - if j.get("hd").and_then(Json::as_bool) == Some(true) { + if s.hidden == Some(true) { g.enabled = false; } out.push(g); } out } + +/// The keys `gf` and `gs` share. +#[allow(clippy::too_many_arguments)] +fn gradient_common( + im: &Im, + g: &mut PropGroup, + opacity: Option<&Animated>, + start: Option<&Animated>, + end: Option<&Animated>, + highlight_length: Option<&Animated>, + highlight_angle: Option<&Animated>, + colors: Option<&GradientColors>, +) { + set(im, g, "opacity", opacity, &anim::to_scalar); + set(im, g, "start", start, &anim::to_vec2); + set(im, g, "end", end, &anim::to_vec2); + set(im, g, "highlightLength", highlight_length, &anim::to_scalar); + set(im, g, "highlightAngle", highlight_angle, &anim::to_scalar); + if let Some(c) = colors { + let n = c.count.and_then(|n| usize::try_from(n).ok()).unwrap_or(2); + set(im, g, "colors", c.stops.as_ref(), &move |v| to_gradient(v, n)); + } +} diff --git a/crates/lottie/src/tests.rs b/crates/lottie/src/tests.rs index 8656852de..189642210 100644 --- a/crates/lottie/src/tests.rs +++ b/crates/lottie/src/tests.rs @@ -12,7 +12,7 @@ use effectcraft_render::render_frame; use effectcraft_time::{FrameRate, Tick}; use serde_json::{Value as Json, json}; -use crate::{ExportOptions, export_comp, import}; +use crate::{ExportOptions, LottieError, export_comp, import}; fn s(x: f64) -> Tick { Tick::from_seconds_f64(x) @@ -381,7 +381,7 @@ fn offset_paths_miter_uses_animatable_lottie_value() { assert_eq!(shapes[0]["ml"]["k"][1]["s"], json!([9.0])); assert_eq!(shapes[1]["ml"], json!({"a": 0, "k": 6.0})); assert_eq!(shapes[2]["ty"], "st"); - assert_eq!(shapes[2]["ml"], json!(7.0)); + assert_eq!(shapes[2]["ml"].as_f64(), Some(7.0)); assert!(compare_comps(&p, cid, &q, nc) > 10); let restored = &q.comp(nc).unwrap().layers[0]; assert_eq!(restored.props.group("contents/offset").unwrap().get("miter").unwrap().keys.len(), 2); @@ -799,6 +799,32 @@ fn dotlottie_archive_roundtrip() { assert_eq!(q.comp(imp.comp).unwrap().layers.len(), 1); } +#[test] +fn dotlottie_archive_without_animation_is_rejected() { + let zip = craft_lottie::zip::try_store(&[("manifest.json".into(), b"{}".to_vec())]).unwrap(); + let mut project = Project::default(); + let err = import(&mut project, &zip, "empty archive", "", &mut |_| None).unwrap_err(); + assert!(matches!(err, LottieError::Parse(message) if message.contains("without a JSON animation"))); +} + +#[test] +fn deflated_dotlottie_archive_imports() { + let (mut p, cid) = setup(); + let l = solid_layer(&mut p, cid, [0.0, 1.0, 0.0], 40, 40); + push(&mut p, cid, l); + let res = export_comp(&p, cid, &ExportOptions::default(), &no_read).unwrap(); + let manifest = serde_json::to_vec(&serde_json::json!({"version":"1","animations":[{"id":"main"}]})).unwrap(); + let animation = serde_json::to_vec(&res.json).unwrap(); + let zip = craft_lottie::zip::try_store_with_compression( + &[("manifest.json".into(), manifest), ("animations/main.json".into(), animation)], + craft_lottie::zip::Compression::Deflated, + ) + .unwrap(); + let mut q = Project::default(); + let imp = import(&mut q, &zip, "compressed", "", &mut |_| None).unwrap(); + assert_eq!(q.comp(imp.comp).unwrap().layers.len(), 1); +} + // ---------------------------------------------------------------- hand-written fixtures fn fixture(name: &str) -> (Project, ItemId, Vec) { @@ -1062,3 +1088,12 @@ fn only_image_bytes_are_embedded() { assert!(res.json["assets"].as_array().is_none_or(|a| a.is_empty()), "{}", res.json["assets"]); assert!(res.warnings.iter().any(|w| w.contains("not a PNG")), "{:?}", res.warnings); } + +#[test] +fn dotlottie_export_rejects_an_unrepresentable_entry_name() { + let (p, cid) = setup(); + let res = export_comp(&p, cid, &ExportOptions::default(), &no_read).unwrap(); + let err = crate::try_to_dotlottie(&res, &"a".repeat(usize::from(u16::MAX))).unwrap_err(); + assert!(matches!(err, LottieError::Invalid(message) if message.contains("dotLottie ZIP"))); + assert_eq!(crate::try_to_dotlottie(&res, "Main").unwrap(), crate::to_dotlottie(&res, "Main")); +} diff --git a/crates/lottie/src/text.rs b/crates/lottie/src/text.rs index 4e50b461d..39199cfb3 100644 --- a/crates/lottie/src/text.rs +++ b/crates/lottie/src/text.rs @@ -1,14 +1,18 @@ //! Text layers ↔ Lottie text data (`t`: document keys `d`, animators `a`, more options `m`), //! and text converted to glyph shapes. +use craft_lottie::model::{ + Font, Map, Path, Shape, ShapeKind, TextAlign, TextData, TextDocKey, TextDocs, TextDocument, TextFollowPath, TextRange, TextSelector, TextStyle, +}; +use craft_lottie::{Animated, Json}; use effectcraft_keyframe::{Justify, TextDoc, Value}; use effectcraft_project::build::{self, Ids}; use effectcraft_project::{Layer, Node, PropGroup}; use effectcraft_time::Tick; -use serde_json::{Map, Value as Json, json}; +use serde_json::json; use crate::anim::{self, Ex, Im, export_prop, import_prop}; -use crate::shapes; +use crate::shapes::{self, fixed}; const JUSTIFY: [Justify; 7] = [Justify::Left, Justify::Right, Justify::Center, Justify::JustifyLastLeft, Justify::JustifyLastRight, Justify::JustifyLastCenter, Justify::JustifyAll]; @@ -18,47 +22,49 @@ pub(crate) fn font_name(family: &str, style: &str) -> String { format!("{}-{}", family.replace(' ', ""), style.replace(' ', "")) } -fn rgb(c: [f32; 4]) -> Json { - json!([c[0] as f64, c[1] as f64, c[2] as f64]) +fn rgb(c: [f32; 4]) -> Vec { + vec![f64::from(c[0]), f64::from(c[1]), f64::from(c[2])] } -fn doc_json(d: &TextDoc) -> Json { - let mut o = json!({ - "t": d.text.replace("\r\n", "\r").replace('\n', "\r"), - "f": font_name(&d.font, &d.style), - "s": d.size, - "j": JUSTIFY.iter().position(|j| *j == d.justify).unwrap_or(0), - "tr": d.tracking, - "lh": d.leading.unwrap_or(d.size * 1.2), - "ls": d.baseline_shift, - "of": d.stroke_over_fill, - }); - if d.apply_fill { - o["fc"] = rgb(d.fill); +fn doc_json(d: &TextDoc) -> TextDocument { + let stroke = d.apply_stroke && d.stroke_width > 0.0; + TextDocument { + text: Some(d.text.replace("\r\n", "\r").replace('\n', "\r")), + font: Some(font_name(&d.font, &d.style)), + size: Some(d.size), + justify: Some(JUSTIFY.iter().position(|j| *j == d.justify).unwrap_or(0) as i64), + tracking: Some(d.tracking), + line_height: Some(d.leading.unwrap_or(d.size * 1.2)), + baseline_shift: Some(d.baseline_shift), + stroke_over_fill: Some(d.stroke_over_fill), + fill: d.apply_fill.then(|| rgb(d.fill)), + stroke: stroke.then(|| rgb(d.stroke)), + stroke_width: stroke.then_some(d.stroke_width), + caps: if d.all_caps { + Some(1) + } else if d.small_caps { + Some(2) + } else { + None + }, + box_size: d.box_size.map(|b| b.to_vec()), + box_position: d.box_size.map(|_| d.box_pos.to_vec()), + ..Default::default() } - if d.apply_stroke && d.stroke_width > 0.0 { - o["sc"] = rgb(d.stroke); - o["sw"] = json!(d.stroke_width); - } - if d.all_caps { - o["ca"] = json!(1); - } else if d.small_caps { - o["ca"] = json!(2); - } - if let Some(b) = d.box_size { - o["sz"] = json!(b); - o["ps"] = json!(d.box_pos); - } - o } -fn doc_from(j: &Json, fonts: &[(String, String, String)]) -> TextDoc { +/// A colour of a text document (`fc`, `sc`), 0..=1 or 0..=255. +fn doc_color(c: Option<&Vec>, extra: &Map, key: &str) -> Option<[f32; 4]> { + let j = c.filter(|c| !c.is_empty()).map(|c| json!(c)).or_else(|| extra.get(key).cloned())?; + anim::to_color(&j).map(|v| v.as_color()) +} + +fn doc_from(j: &TextDocument, fonts: &[(String, String, String)]) -> TextDoc { let mut d = TextDoc::default(); - let f = |k: &str| j.get(k).and_then(Json::as_f64); - if let Some(t) = j.get("t").and_then(Json::as_str) { + if let Some(t) = &j.text { d.text = t.replace(['\r', '\u{3}'], "\n"); } - if let Some(name) = j.get("f").and_then(Json::as_str) { + if let Some(name) = &j.font { match fonts.iter().find(|(n, _, _)| n == name) { Some((_, fam, st)) => { d.font = fam.clone(); @@ -71,40 +77,39 @@ fn doc_from(j: &Json, fonts: &[(String, String, String)]) -> TextDoc { } } } - if let Some(s) = f("s") { + if let Some(s) = j.size { d.size = s; } - let col = |k: &str| j.get(k).and_then(anim::to_color).map(|v| v.as_color()); - match col("fc") { + match doc_color(j.fill.as_ref(), &j.extra, "fc") { Some(c) => d.fill = c, None => d.apply_fill = false, } - if let Some(c) = col("sc") { + if let Some(c) = doc_color(j.stroke.as_ref(), &j.extra, "sc") { d.stroke = c; d.apply_stroke = true; - d.stroke_width = f("sw").unwrap_or(1.0); + d.stroke_width = j.stroke_width.unwrap_or(1.0); } - if let Some(of) = j.get("of").and_then(Json::as_bool) { + if let Some(of) = j.stroke_over_fill { d.stroke_over_fill = of; } - if let Some(i) = j.get("j").and_then(Json::as_u64) { - d.justify = JUSTIFY.get(i as usize).copied().unwrap_or_default(); + if let Some(i) = j.justify.and_then(|i| usize::try_from(i).ok()) { + d.justify = JUSTIFY.get(i).copied().unwrap_or_default(); } - d.tracking = f("tr").unwrap_or(0.0); - if let Some(lh) = f("lh") + d.tracking = j.tracking.unwrap_or(0.0); + if let Some(lh) = j.line_height && (lh - d.size * 1.2).abs() > 1e-6 { d.leading = Some(lh); } - d.baseline_shift = f("ls").unwrap_or(0.0); - match j.get("ca").and_then(Json::as_u64) { + d.baseline_shift = j.baseline_shift.unwrap_or(0.0); + match j.caps { Some(1) => d.all_caps = true, Some(2) => d.small_caps = true, _ => {} } - if let Some(sz) = j.get("sz").and_then(anim::nums).filter(|v| v.len() >= 2) { + if let Some(sz) = j.box_size.as_deref().filter(|v| v.len() >= 2) { d.box_size = Some([sz[0], sz[1]]); - if let Some(ps) = j.get("ps").and_then(anim::nums).filter(|v| v.len() >= 2) { + if let Some(ps) = j.box_position.as_deref().filter(|v| v.len() >= 2) { d.box_pos = [ps[0], ps[1]]; } } @@ -136,28 +141,86 @@ fn conv_for(v: &Value) -> fn(&Value) -> Json { } } +/// The field of a range animator's style for a Lottie key. +fn style_field<'a>(st: &'a mut TextStyle, key: &str) -> Option<&'a mut Option> { + Some(match key { + "p" => &mut st.position, + "a" => &mut st.anchor, + "s" => &mut st.scale, + "r" => &mut st.rotation, + "rx" => &mut st.rotation_x, + "ry" => &mut st.rotation_y, + "sk" => &mut st.skew, + "sa" => &mut st.skew_axis, + "o" => &mut st.opacity, + "fc" => &mut st.fill, + "fh" => &mut st.fill_hue, + "fs" => &mut st.fill_saturation, + "fb" => &mut st.fill_brightness, + "fo" => &mut st.fill_opacity, + "sc" => &mut st.stroke, + "sw" => &mut st.stroke_width, + "so" => &mut st.stroke_opacity, + "t" => &mut st.tracking, + "ls" => &mut st.line_spacing, + "bl" => &mut st.blur, + _ => return None, + }) +} + +fn style_set(st: &mut TextStyle, key: &str, v: Animated) { + match style_field(st, key) { + Some(f) => *f = Some(v), + None => { + st.extra.insert(key.into(), v.0); + } + } +} + +fn style_get(st: &TextStyle, key: &str) -> Option { + let named = match key { + "p" => &st.position, + "a" => &st.anchor, + "s" => &st.scale, + "r" => &st.rotation, + "sk" => &st.skew, + "sa" => &st.skew_axis, + "o" => &st.opacity, + "fc" => &st.fill, + "fh" => &st.fill_hue, + "fs" => &st.fill_saturation, + "fb" => &st.fill_brightness, + "sc" => &st.stroke, + "sw" => &st.stroke_width, + "t" => &st.tracking, + _ => &None, + }; + named.as_ref().map(|a| a.0.clone()).or_else(|| st.extra.get(key).cloned()) +} + /// Export a text layer's `t` object. Fonts used are added to `fonts`. -pub(crate) fn export_text(ex: &mut Ex, layer: &Layer, fonts: &mut Vec) -> Json { - let Some(tg) = layer.props.sub("text") else { return json!({}) }; +pub(crate) fn export_text(ex: &mut Ex, layer: &Layer, fonts: &mut Vec) -> TextData { + let Some(tg) = layer.props.sub("text") else { return TextData::default() }; let label = &layer.name; let mut docs = vec![]; let mut add_font = |d: &TextDoc| { let n = font_name(&d.font, &d.style); - if !fonts.iter().any(|f| f["fName"] == json!(n)) { - fonts.push(json!({"fName": n, "fFamily": d.font, "fStyle": d.style, "ascent": 75})); + if !fonts.iter().any(|f| f.name.as_deref() == Some(n.as_str())) { + fonts.push(Font { name: Some(n), family: Some(d.font.clone()), style: Some(d.style.clone()), ascent: Some(75.0), ..Default::default() }); } }; + let key = |t: f64, d: &TextDoc| TextDocKey { time: Some(t), document: Some(doc_json(d)), ..Default::default() }; if let Some(st) = tg.get("sourceText") { if st.keys.is_empty() { if let Value::Text(d) = &st.value { add_font(d); - docs.push(json!({"t": 0, "s": doc_json(d)})); + docs.push(key(0.0, d)); } } else { for k in &st.keys { if let Value::Text(d) = &k.value { add_font(d); - docs.push(json!({"t": ex.tb.frame(k.time), "s": doc_json(d)})); + docs.push(key(ex.tb.frame(k.time), d)); } } } @@ -184,22 +247,28 @@ pub(crate) fn export_text(ex: &mut Ex, layer: &Layer, fonts: &mut Vec) -> animators.push(export_animator(ex, a, &format!("{label} ▸ {}", a.name))); } } - let mut m = json!({"g": 1, "a": {"a": 0, "k": [0, 0]}}); + let mut m = TextAlign { grouping: Some(1), anchor: Some(fixed(json!([0, 0]))), ..Default::default() }; if let Some(more) = tg.sub("moreOptions") { - m["g"] = json!(more.get("anchorGrouping").map(|p| p.value.as_enum()).unwrap_or(0) + 1); + m.grouping = Some(i64::from(more.get("anchorGrouping").map(|p| p.value.as_enum()).unwrap_or(0)) + 1); if let Some(p) = more.get("groupingAlignment") { - m["a"] = export_prop(ex, p, &anim::arr2, &format!("{label} ▸ Grouping Alignment")); + m.anchor = Some(export_prop(ex, p, &anim::arr2, &format!("{label} ▸ Grouping Alignment"))); } } if tg.sub("pathOptions").and_then(|p| p.get("path")).is_some_and(|p| p.value.as_enum() > 0) { ex.warn(format!("{label}: text on a path is not exported")); } - json!({"d": {"k": docs}, "a": animators, "m": m, "p": {}}) + TextData { + documents: Some(TextDocs { keys: Some(docs), ..Default::default() }), + ranges: Some(animators), + alignment: Some(m), + follow_path: Some(TextFollowPath::default()), + ..Default::default() + } } /// Text animators reproducing the style runs of `d` (fill, stroke, stroke width, size, /// tracking, baseline shift) over their character ranges. -fn style_run_animators(ex: &mut Ex, d: &TextDoc, label: &str) -> Vec { +fn style_run_animators(ex: &mut Ex, d: &TextDoc, label: &str) -> Vec { let base = d.base_style(); let mut out = vec![]; let mut start = 0usize; @@ -211,63 +280,71 @@ fn style_run_animators(ex: &mut Ex, d: &TextDoc, label: &str) -> Vec { if *s == base || run.len == 0 { continue; } - let k = |v: Json| json!({"a": 0, "k": v}); - let mut props = Map::new(); + let k = fixed; + let mut props = TextStyle::default(); if s.apply_fill && s.fill != base.fill { - props.insert("fc".into(), k(json!([s.fill[0] as f64, s.fill[1] as f64, s.fill[2] as f64, 1.0]))); + props.fill = Some(k(json!([s.fill[0] as f64, s.fill[1] as f64, s.fill[2] as f64, 1.0]))); } if s.apply_stroke && s.stroke != base.stroke { - props.insert("sc".into(), k(json!([s.stroke[0] as f64, s.stroke[1] as f64, s.stroke[2] as f64, 1.0]))); + props.stroke = Some(k(json!([s.stroke[0] as f64, s.stroke[1] as f64, s.stroke[2] as f64, 1.0]))); } if (s.stroke_width - base.stroke_width).abs() > 1e-9 { - props.insert("sw".into(), k(json!(s.stroke_width - base.stroke_width))); + props.stroke_width = Some(k(json!(s.stroke_width - base.stroke_width))); } if (s.size - base.size).abs() > 1e-9 && base.size > 0.0 { let p = s.size / base.size * 100.0; - props.insert("s".into(), k(json!([p, p, 100.0]))); + props.scale = Some(k(json!([p, p, 100.0]))); } if (s.tracking - base.tracking).abs() > 1e-9 { // Lottie tracking is in 1/1000 em like the Character panel's. - props.insert("t".into(), k(json!(s.tracking - base.tracking))); + props.tracking = Some(k(json!(s.tracking - base.tracking))); } if (s.baseline_shift - base.baseline_shift).abs() > 1e-9 { - props.insert("p".into(), k(json!([0.0, -(s.baseline_shift - base.baseline_shift), 0.0]))); + props.position = Some(k(json!([0.0, -(s.baseline_shift - base.baseline_shift), 0.0]))); } let lost = s.font != base.font || s.style != base.style || s.faux_bold != base.faux_bold || s.faux_italic != base.faux_italic; if lost && !warned { ex.warn(format!("{label}: per-character fonts and faux styles are not part of Lottie text (base font used)")); warned = true; } - if props.is_empty() { + if props == TextStyle::default() { continue; } - out.push(json!({ - "nm": format!("Style {a}–{b}"), - "s": { - "t": 0, "xe": k(json!(0)), "ne": k(json!(0)), "a": k(json!(100)), "b": 1, "rn": 0, "sh": 1, - "r": 2, "m": k(json!(1)), "s": k(json!(a)), "e": k(json!(b)), "o": k(json!(0)), - }, - "a": Json::Object(props), - })); + let mut sel = TextSelector { + kind: Some(0), + ease_high: Some(k(json!(0))), + ease_low: Some(k(json!(0))), + amount: Some(k(json!(100))), + based_on: Some(1), + randomize: Some(0), + shape: Some(1), + units: Some(2), + start: Some(k(json!(a))), + end: Some(k(json!(b))), + offset: Some(k(json!(0))), + ..Default::default() + }; + sel.extra.insert("m".into(), k(json!(1)).0); + out.push(TextRange { name: Some(format!("Style {a}–{b}")), selector: Some(sel), style: Some(props), ..Default::default() }); } out } -fn export_animator(ex: &mut Ex, a: &PropGroup, label: &str) -> Json { - let mut props = Map::new(); +fn export_animator(ex: &mut Ex, a: &PropGroup, label: &str) -> TextRange { + let mut props = TextStyle::default(); if let Some(pg) = a.sub("properties") { for p in pg.props() { match ANIM_PROPS.iter().find(|(_, _, m)| *m == p.match_id) { Some((key, _, _)) => { let v = export_prop(ex, p, &conv_for(&p.value), &format!("{label} ▸ {}", p.name)); - props.insert((*key).into(), v); + style_set(&mut props, key, v); } None if matches!(p.match_id.as_str(), "trackingType") => {} None => ex.warn(format!("{label} ▸ {}: text animator property not supported by Lottie", p.name)), } } } - let mut sel = json!({"t": 0}); + let mut sel = TextSelector { kind: Some(0), ..Default::default() }; let sels: Vec<&PropGroup> = a.sub("selectors").map(|s| s.groups().collect()).unwrap_or_default(); if sels.len() > 1 { ex.warn(format!("{label}: only the first selector is exported (Lottie animators have one)")); @@ -276,36 +353,29 @@ fn export_animator(ex: &mut Ex, a: &PropGroup, label: &str) -> Json { if s.match_id != "rangeSelector" { ex.warn(format!("{label}: {} is not supported by Lottie", s.name)); } else { - for (k, m) in [("s", "start"), ("e", "end"), ("o", "offset")] { - if let Some(p) = s.get(m) { - sel[k] = export_prop(ex, p, &anim::num, &format!("{label} ▸ {}", p.name)); - } - } + let mut prop = |m: &str| s.get(m).map(|p| export_prop(ex, p, &anim::num, &format!("{label} ▸ {}", p.name))); + (sel.start, sel.end, sel.offset) = (prop("start"), prop("end"), prop("offset")); if let Some(adv) = s.sub("advanced") { - let e = |m: &str| adv.get(m).map(|p| p.value.as_enum()).unwrap_or(0) + 1; - sel["r"] = json!(e("units")); - sel["b"] = json!(e("basedOn")); - sel["m"] = json!({"a": 0, "k": e("mode")}); - sel["sh"] = json!(e("shape")); - sel["rn"] = json!(adv.get("randomize").is_some_and(|p| p.value.as_bool()) as u8); - for (k, m) in [("a", "amount"), ("sm", "smoothness"), ("xe", "easeHigh"), ("ne", "easeLow")] { - if let Some(p) = adv.get(m) { - sel[k] = export_prop(ex, p, &anim::num, &format!("{label} ▸ {}", p.name)); - } - } + let e = |m: &str| i64::from(adv.get(m).map(|p| p.value.as_enum()).unwrap_or(0)) + 1; + sel.units = Some(e("units")); + sel.based_on = Some(e("basedOn")); + sel.extra.insert("m".into(), json!({"a": 0, "k": e("mode")})); + sel.shape = Some(e("shape")); + sel.randomize = Some(i64::from(adv.get("randomize").is_some_and(|p| p.value.as_bool()))); + let mut prop = |m: &str| adv.get(m).map(|p| export_prop(ex, p, &anim::num, &format!("{label} ▸ {}", p.name))); + (sel.amount, sel.smoothness, sel.ease_high, sel.ease_low) = (prop("amount"), prop("smoothness"), prop("easeHigh"), prop("easeLow")); } } } - json!({"nm": a.name, "s": sel, "a": Json::Object(props)}) + TextRange { name: Some(a.name.clone()), selector: Some(sel), style: Some(props), ..Default::default() } } /// Import Lottie text data into a text layer's `text` group. -pub(crate) fn import_text(im: &mut Im, ids: &mut Ids, t: &Json, tg: &mut PropGroup, fonts: &[(String, String, String)]) { - if let Some(list) = t.get("d").and_then(|d| d.get("k")).and_then(Json::as_array) +pub(crate) fn import_text(im: &mut Im, ids: &mut Ids, t: &TextData, tg: &mut PropGroup, fonts: &[(String, String, String)]) { + if let Some(list) = t.documents.as_ref().and_then(|d| d.keys.as_deref()) && let Some(st) = tg.get_mut("sourceText") { - let docs: Vec<(f64, TextDoc)> = - list.iter().filter_map(|k| Some((k.get("t").and_then(Json::as_f64).unwrap_or(0.0), doc_from(k.get("s")?, fonts)))).collect(); + let docs: Vec<(f64, TextDoc)> = list.iter().filter_map(|k| Some((k.time.unwrap_or(0.0), doc_from(k.document.as_ref()?, fonts)))).collect(); if let Some((_, first)) = docs.first() { st.value = Value::Text(Box::new(first.clone())); } @@ -314,24 +384,25 @@ pub(crate) fn import_text(im: &mut Im, ids: &mut Ids, t: &Json, tg: &mut PropGro st.keys = docs.into_iter().map(|(f, d)| effectcraft_keyframe::Keyframe::new(im.tb.tick(f), Value::Text(Box::new(d))).hold()).collect(); } } - if let Some(m) = t.get("m") + if let Some(m) = &t.alignment && let Some(more) = tg.sub_mut("moreOptions") { - if let (Some(g), Some(p)) = (m.get("g").and_then(Json::as_u64), more.get_mut("anchorGrouping")) { + let grouping = m.grouping.or_else(|| m.extra.get("g").and_then(Json::as_i64)).and_then(|g| u64::try_from(g).ok()); + if let (Some(g), Some(p)) = (grouping, more.get_mut("anchorGrouping")) { p.value = Value::Enum((g.max(1) - 1).min(3) as u32); } - if let (Some(a), Some(p)) = (m.get("a"), more.get_mut("groupingAlignment")) { - import_prop(im, a, p, &anim::to_vec2); + if let (Some(a), Some(p)) = (&m.anchor, more.get_mut("groupingAlignment")) { + import_prop(im, &a.0, p, &anim::to_vec2); } } - let Some(list) = t.get("a").and_then(Json::as_array) else { return }; + let Some(list) = &t.ranges else { return }; let mut animators = vec![]; for (i, a) in list.iter().enumerate() { - let name = a.get("nm").and_then(Json::as_str).map(str::to_string).unwrap_or(format!("Animator {}", i + 1)); - let props_j = a.get("a").cloned().unwrap_or(json!({})); + let name = a.name.clone().unwrap_or(format!("Animator {}", i + 1)); + let style = a.style.clone().unwrap_or_default(); let mut kinds: Vec<&str> = vec![]; for (key, kind, _) in ANIM_PROPS { - if props_j.get(*key).is_some() && !kinds.contains(kind) { + if style_get(&style, key).is_some() && !kinds.contains(kind) { kinds.push(kind); } } @@ -339,7 +410,7 @@ pub(crate) fn import_text(im: &mut Im, ids: &mut Ids, t: &Json, tg: &mut PropGro let mut g = build::text_animator(ids, &name, props); if let Some(pg) = g.sub_mut("properties") { for (key, _, m) in ANIM_PROPS { - let (Some(j), Some(p)) = (props_j.get(*key), pg.get_mut(m)) else { continue }; + let (Some(j), Some(p)) = (style_get(&style, key), pg.get_mut(m)) else { continue }; let conv: Box Option> = match &p.value { Value::Vec3(d) => { let z = d[2]; @@ -349,34 +420,38 @@ pub(crate) fn import_text(im: &mut Im, ids: &mut Ids, t: &Json, tg: &mut PropGro Value::Color(_) => Box::new(anim::to_color), _ => Box::new(anim::to_scalar), }; - import_prop(im, j, p, &*conv); + import_prop(im, &j, p, &*conv); } } - if let Some(s) = a.get("s") + if let Some(s) = &a.selector && let Some(sel) = g.sub_mut("selectors").and_then(|s| s.groups_mut_first()) { - for (k, m) in [("s", "start"), ("e", "end"), ("o", "offset")] { - if let (Some(j), Some(p)) = (s.get(k), sel.get_mut(m)) { - import_prop(im, j, p, &anim::to_scalar); + for (m, j) in [("start", &s.start), ("end", &s.end), ("offset", &s.offset)] { + if let (Some(j), Some(p)) = (j, sel.get_mut(m)) { + import_prop(im, &j.0, p, &anim::to_scalar); } } if let Some(adv) = sel.sub_mut("advanced") { - let mut en = |m: &str, key: &str, max: u32| { - let v = s.get(key).and_then(|v| if v.is_object() { v.get("k") } else { Some(v) }).and_then(anim::nums).and_then(|n| n.first().copied()); + let mut en = |m: &str, field: Option, key: &str, max: u32| { + let v = field.map(|f| f as f64).or_else(|| { + let v = s.extra.get(key)?; + let v = if v.is_object() { v.get("k")? } else { v }; + anim::nums(v).and_then(|n| n.first().copied()) + }); if let (Some(v), Some(p)) = (v, adv.get_mut(m)) { p.value = Value::Enum((((v.round() as i64).saturating_sub(1)).max(0) as u32).min(max)); } }; - en("units", "r", 1); - en("basedOn", "b", 3); - en("mode", "m", 5); - en("shape", "sh", 5); - if let (Some(rn), Some(p)) = (s.get("rn").and_then(Json::as_u64), adv.get_mut("randomize")) { + en("units", s.units, "r", 1); + en("basedOn", s.based_on, "b", 3); + en("mode", None, "m", 5); + en("shape", s.shape, "sh", 5); + if let (Some(rn), Some(p)) = (s.randomize.and_then(|r| u64::try_from(r).ok()), adv.get_mut("randomize")) { p.value = Value::Bool(rn != 0); } - for (k, m) in [("a", "amount"), ("sm", "smoothness"), ("xe", "easeHigh"), ("ne", "easeLow")] { - if let (Some(j), Some(p)) = (s.get(k), adv.get_mut(m)) { - import_prop(im, j, p, &anim::to_scalar); + for (m, j) in [("amount", &s.amount), ("smoothness", &s.smoothness), ("easeHigh", &s.ease_high), ("easeLow", &s.ease_low)] { + if let (Some(j), Some(p)) = (j, adv.get_mut(m)) { + import_prop(im, &j.0, p, &anim::to_scalar); } } } @@ -400,7 +475,7 @@ impl FirstGroup for PropGroup { /// Text converted to glyph shapes: one group with every glyph outline (at layer time 0's /// Source Text), a fill and a stroke, as Lottie shape items. -pub(crate) fn glyph_shapes(ex: &mut Ex, layer: &Layer) -> Vec { +pub(crate) fn glyph_shapes(ex: &mut Ex, layer: &Layer) -> Vec { let Some(tg) = layer.props.sub("text") else { return vec![] }; let Some(st) = tg.get("sourceText") else { return vec![] }; let Value::Text(doc) = st.value_at(Tick::ZERO) else { return vec![] }; @@ -412,14 +487,29 @@ pub(crate) fn glyph_shapes(ex: &mut Ex, layer: &Layer) -> Vec { for g in &lay.glyphs { let p = kurbo::Affine::translate((g.origin.x, g.origin.y)) * g.path.clone(); for sp in effectcraft_path::from_kurbo(&p) { - items.push(json!({"ty": "sh", "nm": g.ch.to_string(), "d": 1, "ks": {"a": 0, "k": shapes::shape_json(&sp)}})); + let path = Path { direction: Some(1), path: Some(fixed(shapes::shape_json(&sp))), closed: None }; + items.push(Shape { name: Some(g.ch.to_string()), kind: ShapeKind::Path(path), ..Default::default() }); } } - let col = |c: [f32; 4]| json!({"a": 0, "k": [c[0] as f64, c[1] as f64, c[2] as f64, 1.0]}); - let stroke = (doc.apply_stroke && doc.stroke_width > 0.0).then( - || json!({"ty": "st", "nm": "Stroke", "c": col(doc.stroke), "o": {"a": 0, "k": 100}, "w": {"a": 0, "k": doc.stroke_width}, "lc": 2, "lj": 2, "ml": 4}), - ); - let fill = doc.apply_fill.then(|| json!({"ty": "fl", "nm": "Fill", "c": col(doc.fill), "o": {"a": 0, "k": 100}, "r": 1})); + let col = |c: [f32; 4]| fixed(json!([c[0] as f64, c[1] as f64, c[2] as f64, 1.0])); + let stroke = (doc.apply_stroke && doc.stroke_width > 0.0).then(|| Shape { + name: Some("Stroke".into()), + kind: ShapeKind::Stroke(craft_lottie::model::Stroke { + color: Some(col(doc.stroke)), + opacity: Some(fixed(json!(100))), + width: Some(fixed(json!(doc.stroke_width))), + cap: Some(2), + join: Some(2), + miter_limit: Some(4.0), + ..Default::default() + }), + ..Default::default() + }); + let fill = doc.apply_fill.then(|| Shape { + name: Some("Fill".into()), + kind: ShapeKind::Fill(craft_lottie::model::Fill { color: Some(col(doc.fill)), opacity: Some(fixed(json!(100))), rule: Some(1) }), + ..Default::default() + }); // Items above draw on top: stroke over fill puts the stroke first. if doc.stroke_over_fill { items.extend(stroke); @@ -429,6 +519,15 @@ pub(crate) fn glyph_shapes(ex: &mut Ex, layer: &Layer) -> Vec { items.extend(stroke); } let n = items.len() + 1; - items.push(json!({"ty": "tr", "a": {"a": 0, "k": [0, 0]}, "p": {"a": 0, "k": [0, 0]}, "s": {"a": 0, "k": [100, 100]}, "r": {"a": 0, "k": 0}, "o": {"a": 0, "k": 100}})); - vec![json!({"ty": "gr", "nm": layer.name, "np": n, "it": items})] + let tr = craft_lottie::model::Transform { + anchor: Some(fixed(json!([0, 0]))), + position: Some(fixed(json!([0, 0]))), + scale: Some(fixed(json!([100, 100]))), + rotation: Some(fixed(json!(0))), + opacity: Some(fixed(json!(100))), + ..Default::default() + }; + items.push(Shape { kind: ShapeKind::Transform(Box::new(tr)), ..Default::default() }); + let group = craft_lottie::model::Group { count: Some(n as f64), items: Some(items) }; + vec![Shape { name: Some(layer.name.clone()), kind: ShapeKind::Group(group), ..Default::default() }] } diff --git a/crates/lottie/src/zip.rs b/crates/lottie/src/zip.rs index 2a11dfa25..b47e7cab2 100644 --- a/crates/lottie/src/zip.rs +++ b/crates/lottie/src/zip.rs @@ -1,121 +1,3 @@ -//! A minimal ZIP writer (stored entries, PKWARE APPNOTE 6.3 local headers + central directory) -//! for `.lottie` (dotLottie) archives. +//! Shared stored-entry ZIP functions used by dotLottie imports and exports. -fn crc32(data: &[u8]) -> u32 { - let mut crc = 0xFFFF_FFFFu32; - for &b in data { - crc ^= b as u32; - for _ in 0..8 { - crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 }; - } - } - !crc -} - -/// Build a ZIP archive with the given (name, bytes) entries, uncompressed. -pub fn store(entries: &[(String, Vec)]) -> Vec { - let mut out = Vec::new(); - let mut central = Vec::new(); - let put16 = |v: &mut Vec, x: u16| v.extend_from_slice(&x.to_le_bytes()); - let put32 = |v: &mut Vec, x: u32| v.extend_from_slice(&x.to_le_bytes()); - for (name, data) in entries { - let offset = out.len() as u32; - let crc = crc32(data); - let n = name.as_bytes(); - // Local file header. - put32(&mut out, 0x0403_4b50); - put16(&mut out, 20); // version needed - put16(&mut out, 0x0800); // flags: UTF-8 names - put16(&mut out, 0); // stored - put16(&mut out, 0); // time - put16(&mut out, 0x21); // date (1980-01-01) - put32(&mut out, crc); - put32(&mut out, data.len() as u32); - put32(&mut out, data.len() as u32); - put16(&mut out, n.len() as u16); - put16(&mut out, 0); - out.extend_from_slice(n); - out.extend_from_slice(data); - // Central directory record. - put32(&mut central, 0x0201_4b50); - put16(&mut central, 20); // made by - put16(&mut central, 20); - put16(&mut central, 0x0800); - put16(&mut central, 0); - put16(&mut central, 0); - put16(&mut central, 0x21); - put32(&mut central, crc); - put32(&mut central, data.len() as u32); - put32(&mut central, data.len() as u32); - put16(&mut central, n.len() as u16); - put16(&mut central, 0); // extra - put16(&mut central, 0); // comment - put16(&mut central, 0); // disk - put16(&mut central, 0); // internal attrs - put32(&mut central, 0); // external attrs - put32(&mut central, offset); - central.extend_from_slice(n); - } - let cd_offset = out.len() as u32; - let cd_len = central.len() as u32; - out.extend_from_slice(¢ral); - put32(&mut out, 0x0605_4b50); - put16(&mut out, 0); - put16(&mut out, 0); - put16(&mut out, entries.len() as u16); - put16(&mut out, entries.len() as u16); - put32(&mut out, cd_len); - put32(&mut out, cd_offset); - put16(&mut out, 0); - out -} - -/// Whether an entry name is a relative path inside the archive: not absolute (`/…`, `\…`), no -/// drive (`C:…`) and no `..` component. -fn is_relative_name(name: &str) -> bool { - let drive = name.as_bytes().get(1) == Some(&b':'); - !name.starts_with(['/', '\\']) && !drive && !name.split(['/', '\\']).any(|c| c == "..") -} - -/// Read the stored (uncompressed) entries of a ZIP archive written by [`store`] or any other -/// writer that did not compress. Compressed entries and entries whose names are not relative -/// paths inside the archive are skipped. -pub fn read_stored(data: &[u8]) -> Vec<(String, Vec)> { - let mut out = vec![]; - let mut i = 0usize; - let u16_at = |p: usize| data.get(p..p + 2).map(|b| u16::from_le_bytes([b[0], b[1]]) as usize); - let u32_at = |p: usize| data.get(p..p + 4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize); - while u32_at(i) == Some(0x0403_4b50) { - let (Some(method), Some(size), Some(nlen), Some(xlen)) = (u16_at(i + 8), u32_at(i + 18), u16_at(i + 26), u16_at(i + 28)) else { break }; - let name_start = i + 30; - let body = name_start + nlen + xlen; - let (Some(name), Some(bytes)) = (data.get(name_start..name_start + nlen), data.get(body..body + size)) else { break }; - let name = String::from_utf8_lossy(name).to_string(); - if method == 0 && is_relative_name(&name) { - out.push((name, bytes.to_vec())); - } - i = body + size; - } - out -} - -#[cfg(test)] -mod tests { - #[test] - fn crc_and_roundtrip() { - assert_eq!(super::crc32(b"123456789"), 0xCBF4_3926); - let z = super::store(&[("a.json".into(), b"{}".to_vec()), ("b/c.txt".into(), b"hello".to_vec())]); - let back = super::read_stored(&z); - assert_eq!(back.len(), 2); - assert_eq!(back[1].0, "b/c.txt"); - assert_eq!(back[1].1, b"hello"); - } - - #[test] - fn entries_outside_the_archive_root_are_skipped() { - let names = ["../up.txt", "a/../../up.txt", "/abs/x", "\\abs\\x", "C:\\x", "c:x", "a\\..\\x", "ok/x.txt", "ok/..x"]; - let z = super::store(&names.iter().map(|n| (n.to_string(), b"x".to_vec())).collect::>()); - let back: Vec = super::read_stored(&z).into_iter().map(|(n, _)| n).collect(); - assert_eq!(back, ["ok/x.txt", "ok/..x"]); - } -} +pub use craft_lottie::zip::{Limits, read_entries, read_entries_with_limits, read_stored, store, try_store, try_store_with_compression}; diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml index 76cce90fa..ff98229cb 100644 --- a/crates/media/Cargo.toml +++ b/crates/media/Cargo.toml @@ -22,14 +22,15 @@ effectcraft-pdf = { workspace = true } effectcraft-model = { workspace = true } filmcraft-codecs = { workspace = true } filmcraft-media = { workspace = true } -craft-audio = { workspace = true } -craft-media = { workspace = true } -filmcraft-mpegts = { workspace = true } +craft-dpx = { workspace = true } +craft-exr = { workspace = true, features = ["decode"] } +craft-gif = { workspace = true, features = ["frames"] } +craft-webp = { workspace = true, features = ["frames"] } +craft-audio = { workspace = true, features = ["aac-decode"] } +craft-media = { workspace = true, features = ["mpegts"] } filmcraft-frame = { workspace = true } filmcraft-color = { workspace = true } filmcraft-time = { workspace = true } -exr = { workspace = true } -gif = { workspace = true } image = { workspace = true, features = ["gif", "webp", "tiff", "bmp", "exr", "tga", "hdr"] } rayon = { workspace = true } serde_json = { workspace = true } @@ -37,6 +38,9 @@ thiserror = { workspace = true } log = { workspace = true } [dev-dependencies] +exr = { workspace = true } +# Writes the animated GIFs of the tests. +gif = { workspace = true } tempfile = { workspace = true } # (tests render comps that read layers through effects; already a dependency of effectcraft-render) effectcraft-effects = { workspace = true } diff --git a/crates/media/src/aac.rs b/crates/media/src/aac.rs index a1793b7af..356a8dff5 100644 --- a/crates/media/src/aac.rs +++ b/crates/media/src/aac.rs @@ -62,15 +62,15 @@ fn matroska(file: &dyn ByteReader) -> Option> { /// first unit it can read. Only AAC is asked about, so the streams before that one were refused /// whatever their codec, and an ADTS stream played has no configuration outside its frames. fn latm(file: &dyn ByteReader) -> Option> { - use filmcraft_mpegts::Codec; + use craft_media::mpegts::{self, Codec}; let head = Head(file, file.len().min(MPEG_HEAD)); - let mpeg = filmcraft_mpegts::open(&head).ok()?; - let audio = mpeg.streams.iter().enumerate().filter(|(_, s)| s.kind() == filmcraft_mpegts::Kind::Audio && !s.units.is_empty()); + let mpeg = mpegts::open(&head).ok()?; + let audio = mpeg.streams.iter().enumerate().filter(|(_, s)| s.kind() == mpegts::Kind::Audio && !s.units.is_empty()); let played = audio.take(filmcraft_media::MAX_AUDIO_STREAMS).find_map(|(i, s)| { let first = mpeg.read_unit(&head, i, 0).ok()?; match s.codec { - Codec::AacAdts => filmcraft_mpegts::frame_info(&s.codec, &first).map(|_| None), - Codec::AacLatm => filmcraft_codecs::audio::latm_config(&first).map(|c| Some(c.asc)), + Codec::AacAdts => mpegts::frame_info(&s.codec, &first).map(|_| None), + Codec::AacLatm => craft_audio::aac::latm_config(&first).map(|c| Some(c.asc)), _ => None, } }); @@ -97,12 +97,3 @@ impl craft_media::ByteSource for Head<'_> { self.read(offset, buf) } } - -impl filmcraft_mpegts::ByteSource for Head<'_> { - fn len(&self) -> u64 { - self.1 - } - fn read_at(&self, offset: u64, buf: &mut [u8]) -> io::Result<()> { - self.read(offset, buf) - } -} diff --git a/crates/media/src/dpx.rs b/crates/media/src/dpx.rs index a5b2abdaf..f08f1344d 100644 --- a/crates/media/src/dpx.rs +++ b/crates/media/src/dpx.rs @@ -1,17 +1,11 @@ -//! DPX (SMPTE 268M) and Kodak Cineon stills, the film-scan interchange formats, read from the -//! public specifications. +//! DPX (SMPTE 268M) and Kodak Cineon stills, the film-scan interchange formats, read with +//! `craft-dpx`; this module maps a frame onto footage and 16-bit pixels. //! -//! Supported: luma, RGB, RGBA and ABGR (DPX) or one / three channels (Cineon), 8-, 10-, 12- and -//! 16-bit unsigned samples, 10-bit filled into 32-bit words with the pad bits low (DPX method A, -//! Cineon "32-bit left justified") or high (method B, "right justified"), 12-bit in 16-bit words, -//! big- and little-endian files, the four unrotated image orientations and the pixel aspect ratio. //! Code values are shown as stored (a log scan looks flat, as in After Effects without a Cineon -//! conversion); the codec names the transfer (`log`, `linear`, …). Anything else (run-length -//! encoding, signed or float samples, Y'CbCr, packed 10/12-bit, transposed images) is refused -//! with an error naming it. Every field is read with bounds checks. +//! conversion); the codec names the transfer (`log`, `linear`, …). Y'CbCr elements and transposed +//! images are refused with an error naming them; so is everything `craft-dpx` does not read. use effectcraft_project::{AlphaMode, Footage}; -use rayon::prelude::*; use crate::{MediaError, Result}; @@ -21,391 +15,110 @@ pub(crate) const EXTENSIONS: &[&str] = &["dpx", "cin"]; /// Largest image accepted (8192 × 8192): bigger headers are refused before allocating. const MAX_PIXELS: u64 = 1 << 26; -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum Kind { - Dpx, - Cineon, +fn limits() -> craft_dpx::Limits { + let mut l = craft_dpx::Limits::default(); + l.max_pixels = MAX_PIXELS; + l } -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum Layout { - Luma, - Rgb, - Rgba, - Abgr, -} - -impl Layout { - fn components(self) -> usize { - match self { - Layout::Luma => 1, - Layout::Rgb => 3, - Layout::Rgba | Layout::Abgr => 4, - } - } - fn name(self) -> &'static str { - match self { - Layout::Luma => "luma", - Layout::Rgb => "RGB", - Layout::Rgba => "RGBA", - Layout::Abgr => "ABGR", - } +fn error(path: &str, e: craft_dpx::Error) -> MediaError { + match e { + craft_dpx::Error::Unsupported(_) => MediaError::Unsupported(format!("{path}: {e}")), + _ => MediaError::Decode(format!("{path}: {e}")), } } -/// How samples are stored in a line. -#[derive(Clone, Copy, PartialEq, Eq, Debug)] -enum Packing { - /// One byte per sample. - Bytes8, - /// One 16-bit word per sample. - Words16, - /// Three 10-bit samples per 32-bit word, first in the high bits, two pad bits low. - Filled10A, - /// Three 10-bit samples per 32-bit word, two pad bits high. - Filled10B, - /// One 12-bit sample per 16-bit word, four pad bits low. - Filled12A, - /// One 12-bit sample per 16-bit word, four pad bits high. - Filled12B, +/// The header of a DPX or Cineon file this module shows (`None` for other formats). +fn info(path: &str, bytes: &[u8]) -> Result> { + if craft_dpx::sniff(bytes).is_none() { + return Ok(None); + } + let info = craft_dpx::probe(bytes, &limits()).map_err(|e| error(path, e))?; + if info.layout.is_ycbcr() { + return Err(MediaError::Unsupported(format!("{path}: DPX with Y'CbCr samples is not supported"))); + } + if info.flips().is_none() { + return Err(MediaError::Unsupported(format!("{path}: DPX orientation {} (transposed image) is not supported", info.orientation))); + } + Ok(Some(info)) } -impl Packing { - fn max(self) -> u32 { - match self { - Packing::Bytes8 => 0xff, - Packing::Words16 => 0xffff, - Packing::Filled10A | Packing::Filled10B => 0x3ff, - Packing::Filled12A | Packing::Filled12B => 0xfff, - } - } - fn bits(self) -> u32 { - match self { - Packing::Bytes8 => 8, - Packing::Words16 => 16, - Packing::Filled10A | Packing::Filled10B => 10, - Packing::Filled12A | Packing::Filled12B => 12, - } - } - /// Bytes holding `n` samples, padded to a 32-bit word (lines start on word boundaries). - fn line_bytes(self, n: u64) -> u64 { - match self { - Packing::Bytes8 => n.div_ceil(4) * 4, - Packing::Words16 | Packing::Filled12A | Packing::Filled12B => (n * 2).div_ceil(4) * 4, - Packing::Filled10A | Packing::Filled10B => n.div_ceil(3) * 4, - } +fn layout_name(info: &craft_dpx::Info) -> &'static str { + match info.layout { + craft_dpx::Layout::Luma => "luma", + craft_dpx::Layout::Rgb => "RGB", + _ if info.descriptor == 52 => "ABGR", + _ => "RGBA", } } -/// What a header says about the picture. -#[derive(Clone, Debug)] -struct Header { - kind: Kind, - big_endian: bool, - width: u32, - height: u32, - layout: Layout, - packing: Packing, - /// Byte offset of the first line. - offset: u64, - /// Bytes from one line's start to the next. - stride: u64, - flip_x: bool, - flip_y: bool, - pixel_aspect: f64, - /// Transfer characteristic for the codec name (`log`, `linear`, …), empty when unstated. - transfer: &'static str, -} - -/// Bounds-checked reads in the file's byte order. -struct Reader<'a> { - b: &'a [u8], - big: bool, -} - -impl Reader<'_> { - fn u8(&self, o: usize) -> Option { - self.b.get(o).copied() +/// The transfer characteristic for the codec name, empty when unstated. +fn transfer(info: &craft_dpx::Info) -> &'static str { + if info.kind == craft_dpx::Kind::Cineon { + return "log"; } - fn u16(&self, o: usize) -> Option { - let s: [u8; 2] = self.b.get(o..o.checked_add(2)?)?.try_into().ok()?; - Some(if self.big { u16::from_be_bytes(s) } else { u16::from_le_bytes(s) }) - } - fn u32(&self, o: usize) -> Option { - let s: [u8; 4] = self.b.get(o..o.checked_add(4)?)?.try_into().ok()?; - Some(if self.big { u32::from_be_bytes(s) } else { u32::from_le_bytes(s) }) - } -} - -const UNDEFINED32: u32 = u32::MAX; - -/// DPX or Cineon, and the byte order, from the magic number. -fn sniff(bytes: &[u8]) -> Option<(Kind, bool)> { - match bytes.get(..4)? { - b"SDPX" => Some((Kind::Dpx, true)), - b"XPDS" => Some((Kind::Dpx, false)), - [0x80, 0x2a, 0x5f, 0xd7] => Some((Kind::Cineon, true)), - [0xd7, 0x5f, 0x2a, 0x80] => Some((Kind::Cineon, false)), - _ => None, - } -} - -fn unsupported(path: &str, what: impl std::fmt::Display) -> MediaError { - MediaError::Unsupported(format!("{path}: {what}")) -} - -fn truncated(path: &str, kind: Kind) -> MediaError { - let name = if kind == Kind::Dpx { "DPX" } else { "Cineon" }; - MediaError::Decode(format!("{path}: truncated {name} header")) -} - -fn parse(path: &str, bytes: &[u8]) -> Result> { - let Some((kind, big_endian)) = sniff(bytes) else { return Ok(None) }; - let r = Reader { b: bytes, big: big_endian }; - let h = match kind { - Kind::Dpx => parse_dpx(path, &r)?, - Kind::Cineon => parse_cineon(path, &r)?, - }; - let pixels = u64::from(h.width) * u64::from(h.height); - if h.width == 0 || h.height == 0 || pixels > MAX_PIXELS { - return Err(MediaError::Decode(format!("{path}: image size {} × {} out of range", h.width, h.height))); - } - let need = h.offset.saturating_add(h.stride.saturating_mul(u64::from(h.height))); - if (bytes.len() as u64) < need { - return Err(MediaError::Decode(format!("{path}: truncated image data ({} of {need} bytes)", bytes.len()))); - } - Ok(Some(h)) -} - -fn parse_dpx(path: &str, r: &Reader) -> Result
{ - let t = || truncated(path, Kind::Dpx); - let image_offset = r.u32(4).ok_or_else(t)?; - let orientation = r.u16(768).ok_or_else(t)?; - let elements = r.u16(770).ok_or_else(t)?; - let width = r.u32(772).ok_or_else(t)?; - let height = r.u32(776).ok_or_else(t)?; - // The first image element (the picture; further elements are alternative views). - let sign = r.u32(780).ok_or_else(t)?; - let descriptor = r.u8(800).ok_or_else(t)?; - let transfer = r.u8(801).ok_or_else(t)?; - let bits = r.u8(803).ok_or_else(t)?; - let packing = r.u16(804).ok_or_else(t)?; - let encoding = r.u16(806).ok_or_else(t)?; - let data_offset = r.u32(808).ok_or_else(t)?; - let eol_padding = r.u32(812).ok_or_else(t)?; - if elements == 0 || elements == u16::MAX { - return Err(unsupported(path, "DPX file without an image element")); - } - if sign == 1 { - return Err(unsupported(path, "DPX with signed samples is not supported")); - } - if encoding == 1 { - return Err(unsupported(path, "run-length encoded DPX is not supported")); - } - let layout = match descriptor { - 6 => Layout::Luma, - 50 => Layout::Rgb, - 51 => Layout::Rgba, - 52 => Layout::Abgr, - 100..=103 => return Err(unsupported(path, "DPX with Y'CbCr samples is not supported")), - d => return Err(unsupported(path, format!("DPX image element descriptor {d} is not supported (luma, RGB, RGBA and ABGR are)"))), - }; - let packing = match (bits, packing) { - (8, _) => Packing::Bytes8, - (16, _) => Packing::Words16, - (10, 1) => Packing::Filled10A, - (10, 2) => Packing::Filled10B, - (12, 1) => Packing::Filled12A, - (12, 2) => Packing::Filled12B, - (10 | 12, _) => return Err(unsupported(path, format!("DPX with packed {bits}-bit samples (packing {packing}) is not supported"))), - (b, _) => return Err(unsupported(path, format!("DPX with {b}-bit samples is not supported (8, 10, 12 and 16 are)"))), - }; - let (flip_x, flip_y) = match orientation { - 0 | u16::MAX => (false, false), - 1 => (true, false), - 2 => (false, true), - 3 => (true, true), - o => return Err(unsupported(path, format!("DPX orientation {o} (transposed image) is not supported"))), - }; - let offset = if data_offset == 0 || data_offset == UNDEFINED32 { image_offset } else { data_offset }; - let eol = if eol_padding == UNDEFINED32 { 0 } else { eol_padding }; - let samples = u64::from(width) * layout.components() as u64; - // Pixel aspect ratio (orientation header), when stated. - let pixel_aspect = match (r.u32(1628), r.u32(1632)) { - (Some(h), Some(v)) if h != 0 && v != 0 && h != UNDEFINED32 && v != UNDEFINED32 => { - let a = f64::from(h) / f64::from(v); - if (0.1..=10.0).contains(&a) { a } else { 1.0 } - } - _ => 1.0, - }; - let transfer = match transfer { - 1 => "log (printing density)", - 2 => "linear", - 3 => "log", - 5 | 6 => "Rec. 709", - 13 => "ADX", + match info.transfer { + Some(1) => "log (printing density)", + Some(2) => "linear", + Some(3) => "log", + Some(5 | 6) => "Rec. 709", + Some(13) => "ADX", _ => "", - }; - Ok(Header { - kind: Kind::Dpx, - big_endian: r.big, - width, - height, - layout, - packing, - offset: u64::from(offset), - stride: packing.line_bytes(samples) + u64::from(eol), - flip_x, - flip_y, - pixel_aspect, - transfer, - }) -} - -fn parse_cineon(path: &str, r: &Reader) -> Result
{ - let t = || truncated(path, Kind::Cineon); - let offset = r.u32(4).ok_or_else(t)?; - let orientation = r.u8(192).ok_or_else(t)?; - let channels = r.u8(193).ok_or_else(t)?; - // Channel 0's description; every channel must match it. - let bits = r.u8(198).ok_or_else(t)?; - let width = r.u32(200).ok_or_else(t)?; - let height = r.u32(204).ok_or_else(t)?; - let interleave = r.u8(680).ok_or_else(t)?; - let packing = r.u8(681).ok_or_else(t)?; - let signed = r.u8(682).ok_or_else(t)?; - let eol_padding = r.u32(684).ok_or_else(t)?; - let layout = match channels { - 1 => Layout::Luma, - 3 => Layout::Rgb, - c => return Err(unsupported(path, format!("Cineon with {c} channels is not supported (1 and 3 are)"))), - }; - for c in 1..usize::from(channels) { - let base = 196 + 28 * c; - if r.u8(base + 2) != Some(bits) || r.u32(base + 4) != Some(width) || r.u32(base + 8) != Some(height) { - return Err(unsupported(path, "Cineon channels of different sizes or depths are not supported")); - } } - if interleave != 0 { - return Err(unsupported(path, "Cineon with line or channel interleave is not supported")); - } - if signed == 1 { - return Err(unsupported(path, "Cineon with signed samples is not supported")); - } - let packing = match (bits, packing) { - (8, _) => Packing::Bytes8, - (16, _) => Packing::Words16, - (10, 5) => Packing::Filled10A, - (10, 6) => Packing::Filled10B, - (10, p) => return Err(unsupported(path, format!("Cineon with 10-bit packing {p} is not supported (32-bit words are)"))), - (b, _) => return Err(unsupported(path, format!("Cineon with {b}-bit samples is not supported (8, 10 and 16 are)"))), - }; - let (flip_x, flip_y) = match orientation { - 0 | u8::MAX => (false, false), - 1 => (false, true), - 2 => (true, false), - 3 => (true, true), - o => return Err(unsupported(path, format!("Cineon orientation {o} (transposed image) is not supported"))), - }; - let eol = if eol_padding == UNDEFINED32 { 0 } else { eol_padding }; - let samples = u64::from(width) * layout.components() as u64; - Ok(Header { - kind: Kind::Cineon, - big_endian: r.big, - width, - height, - layout, - packing, - offset: u64::from(offset), - stride: packing.line_bytes(samples) + u64::from(eol), - flip_x, - flip_y, - pixel_aspect: 1.0, - transfer: "log", - }) } /// Footage for a DPX or Cineon file (`None` for other formats). pub(crate) fn probe(path: &str, bytes: &[u8]) -> Result> { - let Some(h) = parse(path, bytes)? else { return Ok(None) }; - let alpha = matches!(h.layout, Layout::Rgba | Layout::Abgr); + let Some(h) = info(path, bytes)? else { return Ok(None) }; + let alpha = h.layout.has_alpha(); let mut f = crate::probe::still_footage(path, h.width, h.height, image::ImageFormat::Png, alpha); f.alpha = if alpha { AlphaMode::Straight } else { AlphaMode::Ignore }; - f.pixel_aspect = h.pixel_aspect; - let name = if h.kind == Kind::Dpx { "DPX" } else { "Cineon" }; - f.codec = format!("{name} {}-bit {}", h.packing.bits(), h.layout.name()); - if !h.transfer.is_empty() { - f.codec = format!("{}, {}", f.codec, h.transfer); + f.pixel_aspect = + h.pixel_aspect.map(|(x, y)| f64::from(x) / f64::from(y)).filter(|a| (0.1..=10.0).contains(a) && h.kind == craft_dpx::Kind::Dpx).unwrap_or(1.0); + let name = if h.kind == craft_dpx::Kind::Dpx { "DPX" } else { "Cineon" }; + f.codec = format!("{name} {}-bit {}", h.bits, layout_name(&h)); + let t = transfer(&h); + if !t.is_empty() { + f.codec = format!("{}, {t}", f.codec); } Ok(Some(f)) } -/// The picture of a DPX or Cineon file as 16-bit samples (`None` for other formats). +/// The picture of a DPX or Cineon file as 16-bit samples, upright (`None` for other formats). pub(crate) fn decode(path: &str, bytes: &[u8]) -> Result> { - let Some(h) = parse(path, bytes)? else { return Ok(None) }; - let (w, ht) = (h.width as usize, h.height as usize); - // Output components: luma, RGB or RGBA (ABGR reordered). - let nc = h.layout.components(); - let row_len = w * nc; - let mut out = vec![0u16; row_len * ht]; - let max = h.packing.max(); - out.par_chunks_mut(row_len).enumerate().for_each(|(y, row)| { - let sy = if h.flip_y { ht - 1 - y } else { y }; - let start = h.offset.saturating_add(h.stride.saturating_mul(sy as u64)); - let line = usize::try_from(start).ok().and_then(|s| bytes.get(s..)).unwrap_or(&[]); - for x in 0..w { - let sx = if h.flip_x { w - 1 - x } else { x }; - for c in 0..nc { - // ABGR stores alpha first and colour reversed. - let sc = if h.layout == Layout::Abgr { 3 - c } else { c }; - let v = sample(line, h.packing, h.big_endian, sx * nc + sc); - if let Some(o) = row.get_mut(x * nc + c) { - *o = ((u64::from(v.min(max)) * 0xffff + u64::from(max) / 2) / u64::from(max)) as u16; + let Some(h) = info(path, bytes)? else { return Ok(None) }; + let (flip_x, flip_y) = h.flips().unwrap_or_default(); + let frame = craft_dpx::decode(bytes, &limits()).map_err(|e| error(path, e))?; + let (w, ht, nc) = (h.width as usize, h.height as usize, h.layout.components()); + let row_len = w.checked_mul(nc).ok_or_else(|| MediaError::Decode(format!("{path}: image dimensions overflow")))?; + let mut out = frame.codes; + if flip_y { + for y in 0..ht / 2 { + for x in 0..row_len { + out.swap(y * row_len + x, (ht - 1 - y) * row_len + x); + } + } + } + if flip_x { + for row in out.chunks_exact_mut(row_len) { + for x in 0..w / 2 { + let (a, b) = (x * nc, (w - 1 - x) * nc); + for c in 0..nc { + row.swap(a + c, b + c); } } } - }); + } + out.iter_mut().for_each(|c| *c = craft_dpx::widen(*c, h.bits)); let (w32, h32) = (h.width, h.height); let img = match h.layout { - Layout::Luma => image::ImageBuffer::from_raw(w32, h32, out).map(image::DynamicImage::ImageLuma16), - Layout::Rgb => image::ImageBuffer::from_raw(w32, h32, out).map(image::DynamicImage::ImageRgb16), - Layout::Rgba | Layout::Abgr => image::ImageBuffer::from_raw(w32, h32, out).map(image::DynamicImage::ImageRgba16), + craft_dpx::Layout::Luma => image::ImageBuffer::from_raw(w32, h32, out).map(image::DynamicImage::ImageLuma16), + craft_dpx::Layout::Rgb => image::ImageBuffer::from_raw(w32, h32, out).map(image::DynamicImage::ImageRgb16), + _ => image::ImageBuffer::from_raw(w32, h32, out).map(image::DynamicImage::ImageRgba16), }; img.map(Some).ok_or_else(|| MediaError::Decode(format!("{path}: image buffer size mismatch"))) } -/// Sample `i` of a line (0 past its end; the header check makes that unreachable for valid -/// headers). -#[inline] -fn sample(line: &[u8], packing: Packing, big: bool, i: usize) -> u32 { - let word16 = |o: usize| -> u32 { - match line.get(o..o + 2) { - Some(&[a, b]) => u32::from(if big { u16::from_be_bytes([a, b]) } else { u16::from_le_bytes([a, b]) }), - _ => 0, - } - }; - let word32 = |o: usize| -> u32 { - match line.get(o..o + 4) { - Some(&[a, b, c, d]) => { - if big { - u32::from_be_bytes([a, b, c, d]) - } else { - u32::from_le_bytes([a, b, c, d]) - } - } - _ => 0, - } - }; - match packing { - Packing::Bytes8 => line.get(i).copied().map_or(0, u32::from), - Packing::Words16 => word16(i * 2), - Packing::Filled12A => word16(i * 2) >> 4, - Packing::Filled12B => word16(i * 2) & 0xfff, - Packing::Filled10A => (word32(i / 3 * 4) >> (22 - 10 * (i % 3) as u32)) & 0x3ff, - Packing::Filled10B => (word32(i / 3 * 4) >> (20 - 10 * (i % 3) as u32)) & 0x3ff, - } -} - #[cfg(test)] mod tests { use super::*; @@ -452,7 +165,7 @@ mod tests { #[test] fn hostile_headers_never_panic() { - assert!(parse("x", b"not a dpx").expect("other").is_none()); + assert!(info("x", b"not a dpx").expect("other").is_none()); let good = { let mut a = dpx_header(4, 4, 50, 10, 1, 0); a.extend(std::iter::repeat_n(0x5a, 64)); @@ -462,14 +175,18 @@ mod tests { for n in [4, 8, 600, 790, 805, 2047, 2048, 2100] { assert!(decode("t.dpx", good.get(..n).expect("cut")).is_err(), "{n}"); } - // huge, zero, unsupported + // huge, zero, Y'CbCr, unsupported depth, transposed for (w, h, d, bits, p, o) in - [(u32::MAX, u32::MAX, 50, 10, 1, 0), (0, 4, 50, 10, 1, 0), (4, 4, 102, 10, 1, 0), (4, 4, 50, 10, 0, 0), (4, 4, 50, 32, 0, 0), (4, 4, 50, 10, 1, 5)] + [(u32::MAX, u32::MAX, 50, 10, 1, 0), (0, 4, 50, 10, 1, 0), (4, 4, 102, 10, 1, 0), (4, 4, 50, 32, 0, 0), (4, 4, 50, 10, 1, 5)] { let mut b = dpx_header(w, h, d, bits, p, o); b.extend(std::iter::repeat_n(0, 64)); - assert!(probe("h.dpx", &b).is_err() && decode("h.dpx", &b).is_err()); + assert!(probe("h.dpx", &b).is_err() && decode("h.dpx", &b).is_err(), "{w}x{h} {d} {bits} {p} {o}"); } + // 8192 × 8193 is past this module's own cap, which is below craft-dpx's default. + let mut big = dpx_header(8192, 8193, 6, 8, 0, 0); + big.extend(std::iter::repeat_n(0, 64)); + assert!(probe("big.dpx", &big).is_err()); // run-length encoding and offsets past the end are refused let mut rle = good.clone(); rle[806..808].copy_from_slice(&1u16.to_be_bytes()); diff --git a/crates/media/src/exr_channels.rs b/crates/media/src/exr_channels.rs index d0acf590f..3463cf663 100644 --- a/crates/media/src/exr_channels.rs +++ b/crates/media/src/exr_channels.rs @@ -1,5 +1,5 @@ //! Auxiliary channels from multi-layer OpenEXR files (depth, object / material IDs, normals, -//! Cryptomatte, …) for the 3D Channel effects, read with the pure-Rust `exr` crate. +//! Cryptomatte, …) for the 3D Channel effects, read through the shared `craft-exr` decoder. //! //! Every channel of every layer becomes a plane named `layer.channel` (or just `channel` for //! the unnamed layer), placed in the display window (pixels outside a layer's data window are @@ -18,12 +18,6 @@ use std::sync::{Arc, Mutex, OnceLock, PoisonError}; use effectcraft_raster::channels3d::{BACKGROUND_DEPTH, split_channel}; use effectcraft_raster::{AuxChannels, Image}; use effectcraft_render::reads::{ReadFile, ReadFiles}; -use exr::block::UncompressedBlock; -use exr::block::chunk::TileCoordinates; -use exr::image::read::image::ReadImage; -use exr::image::read::layers::{ChannelsReader, ReadAllLayers, ReadChannels}; -use exr::meta::attribute::SampleType; -use exr::meta::header::Header; use crate::convert::{AlphaOp, float_to_image}; @@ -31,203 +25,24 @@ use crate::convert::{AlphaOp, float_to_image}; /// stop at the same size). const MAX_DISPLAY_PIXELS: usize = 1 << 28; -fn is_depth(name: &str) -> bool { - let last = name.rsplit('.').next().unwrap_or(name); - last.eq_ignore_ascii_case("z") || name.to_ascii_lowercase().contains("depth") -} - -/// Full plane name of a channel in a part: `part.channel`, except that Blender 5 writes one part -/// per pass whose channels already carry the full name (part `ViewLayer.Depth` holds -/// `ViewLayer.Depth.Z`), which is kept as is instead of doubling the prefix. -fn channel_name(part: Option<&str>, channel: &str) -> String { - match part { - Some(p) if channel.strip_prefix(p).is_some_and(|rest| rest.starts_with('.')) => channel.to_string(), - Some(p) => format!("{p}.{channel}"), - None => channel.to_string(), - } -} - -/// The part name channels are prefixed with (`None`: unnamed). -fn part_name(header: &Header) -> Option { - header.own_attributes.layer_name.as_ref().map(|t| t.to_string()).filter(|s| !s.is_empty()) -} - -/// Parse a Cryptomatte manifest (`{"name": "hexhash", …}`). -pub fn parse_manifest(json: &str) -> Vec<(String, u32)> { - let Ok(serde_json::Value::Object(m)) = serde_json::from_str::(json) else { return vec![] }; - let mut v: Vec<(String, u32)> = m.iter().filter_map(|(k, h)| Some((k.clone(), u32::from_str_radix(h.as_str()?.trim(), 16).ok()?))).collect(); - v.sort(); - v -} +// Channel naming and the Cryptomatte manifest are `craft-exr`'s. +use craft_exr::channels::{is_depth, part_channel_name as channel_name}; +pub use craft_exr::cryptomatte::parse_manifest; /// Why an OpenEXR file's pixels can't be decoded when its headers name a compression this build /// can't decompress (HTJ2K, OpenEXR 3.4's High-Throughput JPEG 2000): the decoders only said /// "no non-deep rgb channels" or showed a transparent frame (#482). `None` for other files. pub fn unsupported_compression(bytes: &[u8]) -> Option<&'static str> { - use exr::compression::Compression; - let meta = exr::meta::MetaData::read_from_buffered(std::io::Cursor::new(bytes), false).ok()?; - meta.headers + let mut limits = craft_exr::decode::Limits::default(); + limits.max_pixels = u64::MAX; + limits.max_bytes = u64::MAX; + craft_exr::decode::parts(bytes, &limits) + .ok()? .iter() - .any(|h| matches!(h.compression, Compression::HTJ2K32 | Compression::HTJ2K256)) + .any(|part| matches!(part.compression.as_str(), "HTJ2K32" | "HTJ2K256")) .then_some("OpenEXR HTJ2K compression isn't supported yet: re-save the file with ZIP, PIZ or DWAA compression") } -/// Which channels a decode keeps, by plane name, and the display window they are placed in -/// (the first part's, as the `exr` crate reports the image's). -struct Planes<'k> { - keep: &'k dyn Fn(&str) -> bool, - display: exr::meta::attribute::IntegerBounds, -} - -/// One part's kept channels while it is decoded: each line of samples goes straight into its -/// channel's display-window plane (no copy of the part's samples in their own type first). -struct PlanesReader { - /// Per channel of the part: its plane name, sample type and plane (`None`: not kept). - planes: Vec)>>, - /// The data window's position in the display window, and the data window's and display - /// window's sizes. - offset: (i64, i64), - layer: (usize, usize), - display: (usize, usize), - f16s: Vec, - u32s: Vec, - f32s: Vec, - /// The part's channel indices of exact `R`, `G`, `B` and `A`, when it has R, G and B. - rgb: Option<([usize; 3], Option)>, - /// The part's display window differs from the first part's. - own_display: bool, -} - -/// A decoded part: its kept planes (in channel order) and what [`PlanesReader`] found. -struct PartPlanes { - planes: Vec<(String, Vec)>, - /// Positions in `planes` of the part's R, G, B (and A) channels, when it has them and keeps - /// them all. - rgb: Option<([usize; 3], Option)>, - has_rgb: bool, - exact: bool, -} - -impl<'s> ReadChannels<'s> for Planes<'_> { - type Reader = PlanesReader; - - fn create_channels_reader(&'s self, header: &Header) -> exr::error::Result { - if header.deep { - return Err(exr::error::Error::NotSupported("deep data".into())); - } - let dw = self.display; - let display = (dw.size.0, dw.size.1); - // Each channel is a display-window plane: a 60000² window over a 1×1 data window was a - // multi-gigabyte allocation per channel (#2141). - let n = display.0.checked_mul(display.1).filter(|n| *n > 0 && *n <= MAX_DISPLAY_PIXELS).ok_or(exr::error::Error::Invalid("display window".into()))?; - let prefix = part_name(header); - let pos = header.own_attributes.layer_position; - let offset = (i64::from(pos.0) - i64::from(dw.position.0), i64::from(pos.1) - i64::from(dw.position.1)); - let planes = header - .channels - .list - .iter() - .map(|ch| { - let name = channel_name(prefix.as_deref(), &ch.name.to_string()); - let fill = if is_depth(&name) { BACKGROUND_DEPTH } else { 0.0 }; - (self.keep)(&name).then(|| (name, ch.sample_type, vec![fill; n])) - }) - .collect(); - let find = |c: &str| header.channels.find_index_of_channel(&exr::meta::attribute::Text::from(c)); - let rgb = match (find("R"), find("G"), find("B")) { - (Some(r), Some(g), Some(b)) => Some(([r, g, b], find("A"))), - _ => None, - }; - Ok(PlanesReader { - planes, - offset, - layer: (header.layer_size.0, header.layer_size.1), - display, - f16s: vec![], - u32s: vec![], - f32s: vec![], - rgb, - own_display: header.shared_attributes.display_window != dw, - }) - } -} - -impl ChannelsReader for PlanesReader { - type Channels = PartPlanes; - - fn filter_block(&self, tile: TileCoordinates) -> bool { - tile.is_largest_resolution_level() && self.planes.iter().any(Option::is_some) - } - - fn read_block(&mut self, header: &Header, block: UncompressedBlock) -> exr::error::UnitResult { - let ((lw, lh), (w, h)) = (self.layer, self.display); - for line in block.lines(&header.channels) { - let Some(Some((_, kind, plane))) = self.planes.get_mut(line.location.channel) else { continue }; - let (x0, y, count) = (line.location.position.0, line.location.position.1, line.location.sample_count); - // The samples of data-window row `y`, columns `x0..x0 + count`, at display row `ty` - // from display column `tx0`; clipped to the display window. - if y >= lh || x0.checked_add(count).is_none_or(|end| end > lw) { - continue; - } - let Some(ty) = usize::try_from(y as i64 + self.offset.1).ok().filter(|ty| *ty < h) else { continue }; - let tx0 = x0 as i64 + self.offset.0; - let skip = usize::try_from(-tx0).unwrap_or(0).min(count); - let tx = usize::try_from(tx0.max(0)).unwrap_or(usize::MAX); - let take = (count - skip).min(w.saturating_sub(tx)); - let start = ty.checked_mul(w).and_then(|row| row.checked_add(tx)); - let Some(dst) = start.filter(|_| take > 0).and_then(|s| plane.get_mut(s..s.checked_add(take)?)) else { continue }; - match kind { - SampleType::F16 => { - self.f16s.resize(count, exr::prelude::f16::ZERO); - line.read_samples_into_slice(&mut self.f16s)?; - for (d, s) in dst.iter_mut().zip(self.f16s.iter().skip(skip)) { - *d = s.to_f32(); - } - } - SampleType::F32 => { - self.f32s.resize(count, 0.0); - line.read_samples_into_slice(&mut self.f32s)?; - for (d, s) in dst.iter_mut().zip(self.f32s.iter().skip(skip)) { - *d = *s; - } - } - SampleType::U32 => { - self.u32s.resize(count, 0); - line.read_samples_into_slice(&mut self.u32s)?; - for (d, s) in dst.iter_mut().zip(self.u32s.iter().skip(skip)) { - *d = *s as f32; - } - } - } - } - Ok(()) - } - - fn into_channels(self) -> PartPlanes { - // Positions of the kept channels among the kept planes. - let mut at = vec![None; self.planes.len()]; - let mut planes = Vec::with_capacity(self.planes.len()); - for (i, p) in self.planes.into_iter().enumerate() { - if let Some((name, _, data)) = p { - if let Some(slot) = at.get_mut(i) { - *slot = Some(planes.len()); - } - planes.push((name, data)); - } - } - let kept = |i: usize| at.get(i).copied().flatten(); - let has_rgb = self.rgb.is_some(); - let rgb = self.rgb.and_then(|([r, g, b], a)| { - let a = match a { - Some(a) => Some(kept(a)?), - None => None, - }; - Some(([kept(r)?, kept(g)?, kept(b)?], a)) - }); - PartPlanes { planes, rgb, has_rgb, exact: !self.own_display } - } -} - /// How the `image` crate's OpenEXR decoder would show a file: the first part with exact `R`, `G` /// and `B` channels (alpha `A` when it has one, else opaque), placed in the display window with /// 0 outside the data window. @@ -273,73 +88,117 @@ enum Refused { TooLarge(String), } -/// Bytes the planes of the channels `keep` names would take (`None`: not a readable header). -fn planes_bytes(meta: &exr::meta::MetaData, keep: &dyn Fn(&str) -> bool) -> Option { - let dw = meta.headers.first()?.shared_attributes.display_window; - let n = dw.size.0.checked_mul(dw.size.1)?; - let mut kept = 0usize; - for header in meta.headers.iter() { - let prefix = part_name(header); - kept = kept.saturating_add(header.channels.list.iter().filter(|ch| keep(&channel_name(prefix.as_deref(), &ch.name.to_string()))).count()); - } - Some(n.saturating_mul(kept).saturating_mul(std::mem::size_of::())) +/// Bytes the selected channels occupy in each part's own display window. The channel cache +/// reserves this before decoding so concurrent imports cannot exceed its soft budget. +fn planes_bytes(infos: &[craft_exr::decode::PartInfo], keep: &dyn Fn(&str) -> bool) -> Option { + infos.first()?; + let total = infos.iter().try_fold(0u64, |total, part| { + let count = part.channels.iter().filter(|channel| keep(&channel_name(part.name.as_deref(), &channel.name))).count() as u64; + if count == 0 { + return Some(total); + } + let pixels = u64::from(part.display_window.width).checked_mul(u64::from(part.display_window.height))?; + total.checked_add(pixels.checked_mul(count)?.checked_mul(4)?) + })?; + usize::try_from(total).ok() } -/// Decode the channels of an EXR file's bytes that `keep` names (by plane name). +/// Decode selected EXR channels through craft-exr, which places each selected block directly +/// into its bounded display-window plane. fn decode(bytes: &[u8], keep: &dyn Fn(&str) -> bool) -> Result { - let meta = exr::meta::MetaData::read_from_buffered(std::io::Cursor::new(bytes), false).map_err(|_| Refused::Unreadable)?; - let display = meta.headers.first().ok_or(Refused::Unreadable)?.shared_attributes.display_window; - let need = planes_bytes(&meta, keep).ok_or(Refused::Unreadable)?; - if need > MAX_DECODE_BYTES { - let gb = |b: usize| b as f64 / f64::from(1u32 << 30); + use craft_exr::decode::{self, Error as ExrError, Limits}; + + let mut limits = Limits::default(); + limits.max_pixels = MAX_DISPLAY_PIXELS as u64; + limits.max_bytes = MAX_DECODE_BYTES as u64; + // Header-only checks must not charge channels this caller does not decode. The shared display + // decoder independently checks the exact selected display planes before allocating them. It + // also bounds a selected part's data window across all of its channels (decoded blocks carry + // every channel before the unused ones are dropped), so a part whose full channel set exceeds + // `max_bytes` is refused even when the kept planes alone would fit. + let mut header_limits = limits; + header_limits.max_width = u32::MAX; + header_limits.max_height = u32::MAX; + header_limits.max_pixels = u64::MAX; + header_limits.max_bytes = u64::MAX; + let infos = decode::parts(bytes, &header_limits).map_err(|e| match e { + ExrError::LimitExceeded(message) => Refused::TooLarge(message), + _ => Refused::Unreadable, + })?; + let display = infos.first().ok_or(Refused::Unreadable)?.display_window; + let needed = planes_bytes(&infos, keep).filter(|bytes| *bytes > 0).ok_or(Refused::Unreadable)?; + if needed > MAX_DECODE_BYTES { + let gb = |b: u64| b as f64 / f64::from(1u32 << 30); return Err(Refused::TooLarge(format!( "its {}×{} OpenEXR channels need {:.1} GB of memory, more than the {:.1} GB one file may use", - display.size.0, - display.size.1, - gb(need), - gb(MAX_DECODE_BYTES) + display.width, + display.height, + gb(needed as u64), + gb(MAX_DECODE_BYTES as u64), ))); } - let read = ReadImage::new(ReadAllLayers { read_channels: Planes { keep, display } }, |_| {}); - let img = read.from_buffered(std::io::Cursor::new(bytes)).map_err(|_| Refused::Unreadable)?; - let dw = img.attributes.display_window; - let mut aux = AuxChannels::new(dw.size.0 as u32, dw.size.1 as u32, 1.0); + + let mut aux = AuxChannels::new(display.width, display.height, 1.0); let mut crypto: HashMap, Option)> = HashMap::new(); - let mut collect_meta = |other: &HashMap| { - for (k, v) in other { - let key = k.to_string(); + let mut rgb = Rgb::None; + for info in infos { + for (key, value) in &info.text_attributes { let Some(rest) = key.strip_prefix("cryptomatte/") else { continue }; let Some((id, field)) = rest.split_once('/') else { continue }; - let exr::meta::attribute::AttributeValue::Text(t) = v else { continue }; - let e = crypto.entry(id.to_string()).or_default(); + let entry = crypto.entry(id.to_string()).or_default(); match field { - "name" => e.0 = Some(t.to_string()), - "manifest" => e.1 = Some(t.to_string()), + "name" => entry.0 = Some(value.clone()), + "manifest" => entry.1 = Some(value.clone()), _ => {} } } - }; - collect_meta(&img.attributes.other); - let mut rgb = Rgb::None; - for layer in img.layer_data { - collect_meta(&layer.attributes.other); - let part = layer.channel_data; - if rgb == Rgb::None && part.has_rgb { + let prefix = info.name.as_deref(); + let exact = info.display_window == display; + let rgb_indices = ["R", "G", "B"].map(|wanted| info.channels.iter().position(|channel| channel.name == wanted)); + let has_rgb = rgb_indices.iter().all(Option::is_some); + let alpha_index = info.channels.iter().position(|channel| channel.name == "A"); + // Metadata above still belongs to the file, but an ignored part must not allocate or + // impose its pixel/deep-data limits on the selected picture channels. + if !info.channels.iter().any(|channel| keep(&channel_name(prefix, &channel.name))) { + if rgb == Rgb::None && has_rgb { + rgb = Rgb::Unsupported; + } + continue; + } + let mut part = decode::decode_display_part( + bytes, + info.index, + keep, + &|name| { + if is_depth(name) { BACKGROUND_DEPTH } else { 0.0 } + }, + &limits, + ) + .map_err(|error| match error { + ExrError::LimitExceeded(message) => Refused::TooLarge(message), + _ => Refused::Unreadable, + })?; + if rgb == Rgb::None && has_rgb { let base = aux.channels.len(); - rgb = match part.rgb { - Some(([r, g, b], a)) if part.exact => { - let picked = [Some(r), Some(g), Some(b), a]; - let depth = picked.iter().flatten().any(|i| part.planes.get(*i).is_some_and(|(n, _)| is_depth(n))); - if depth { Rgb::Unsupported } else { Rgb::Planes([base + r, base + g, base + b], a.map(|a| base + a)) } + let locate = |raw: usize| { + let name = channel_name(prefix, &info.channels.get(raw)?.name); + part.channels.iter().position(|channel| channel.name == name) + }; + rgb = match (rgb_indices[0].and_then(locate), rgb_indices[1].and_then(locate), rgb_indices[2].and_then(locate)) { + (Some(r), Some(g), Some(b)) if exact => { + let a = alpha_index.and_then(locate); + let depth = + [Some(r), Some(g), Some(b), a].into_iter().flatten().any(|i| part.channels.get(i).is_some_and(|channel| is_depth(&channel.name))); + if depth { Rgb::Unsupported } else { Rgb::Planes([base + r, base + g, base + b], a.map(|i| base + i)) } } _ => Rgb::Unsupported, }; } - aux.channels.extend(part.planes); + aux.channels.extend(part.channels.drain(..).map(|channel| (channel.name, channel.samples))); } for (_, (name, manifest)) in crypto { - if let (Some(n), Some(m)) = (name, manifest) { - aux.manifests.push((n, parse_manifest(&m))); + if let (Some(name), Some(manifest)) = (name, manifest) { + aux.manifests.push((name, parse_manifest(&manifest))); } } aux.manifests.sort(); @@ -409,11 +268,16 @@ fn picture_names(aux: &AuxChannels) -> Option<([String; 3], Option)> { /// headers, then only those channels decoded; in a multi-part file the other parts' pixels are /// not even decompressed), with the names of its planes. fn picture_only(bytes: &[u8]) -> Result<(Decoded, [String; 3], Option), Refused> { - let meta = exr::meta::MetaData::read_from_buffered(std::io::Cursor::new(bytes), false).map_err(|_| Refused::Unreadable)?; + let mut limits = craft_exr::decode::Limits::default(); + limits.max_width = u32::MAX; + limits.max_height = u32::MAX; + limits.max_pixels = u64::MAX; + limits.max_bytes = u64::MAX; + let meta = craft_exr::decode::parts(bytes, &limits).map_err(|_| Refused::Unreadable)?; let mut names = AuxChannels::new(0, 0, 1.0); - for header in meta.headers.iter() { - let prefix = part_name(header); - names.channels.extend(header.channels.list.iter().map(|ch| (channel_name(prefix.as_deref(), &ch.name.to_string()), vec![]))); + for part in meta { + let prefix = part.name.as_deref(); + names.channels.extend(part.channels.iter().map(|ch| (channel_name(prefix, &ch.name), vec![]))); } let (rgb, a) = picture_names(&names).ok_or(Refused::Unreadable)?; // Planes are looked up by name ignoring case, so every channel that could answer is kept. @@ -559,8 +423,15 @@ struct Entry { impl Entry { /// Dropping it would free nothing or lose a decode in progress: an effect (or a picture - /// waiting for its effects) still holds its planes, or it is decoding. + /// waiting for its effects) still holds its planes, someone is using the slot, or it is decoding. fn in_use(&self) -> bool { + // `get_or_init` hands an active caller a borrow of the OnceLock value before that caller + // can clone the decoded Arc. Keep the entry while any caller still holds this slot, or a + // concurrent account/eviction can remove it in that gap and make the next request decode + // the same file again. + if Arc::strong_count(&self.slot) > 1 { + return true; + } match self.slot.get() { None => true, Some((None, _)) => false, @@ -692,8 +563,13 @@ impl ChannelCache { /// Decode the file at `path` whose bytes are `bytes` for `slot` (see [`ChannelCache::get`]). fn decode_file(&self, path: &str, slot: &Slot, bytes: &[u8]) -> Option> { // The planes it will allocate count against the budget while it decodes. - if let Ok(meta) = exr::meta::MetaData::read_from_buffered(std::io::Cursor::new(bytes), false) - && let Some(need) = planes_bytes(&meta, &|_| true) + let mut limits = craft_exr::decode::Limits::default(); + limits.max_width = u32::MAX; + limits.max_height = u32::MAX; + limits.max_pixels = u64::MAX; + limits.max_bytes = u64::MAX; + if let Ok(infos) = craft_exr::decode::parts(bytes, &limits) + && let Some(need) = planes_bytes(&infos, &|_| true) { self.account(slot, need.min(MAX_DECODE_BYTES)); } @@ -987,6 +863,21 @@ mod tests { assert_eq!(reads.load(Ordering::Relaxed), frames as u64); } + #[test] + fn cache_does_not_evict_a_slot_while_a_caller_is_using_it() { + let bytes: Arc<[u8]> = flat(&["R", "G", "B", "A"], (32, 32), 0.25).into(); + let one = 4 * 32 * 32 * 4 + 4; + let cache = ChannelCache::new(one); + drop(cache.get("/active.exr", Use::Channels, || Some(bytes.clone()))); + let active_slot = cache.lock().entries.iter().find(|entry| entry.path == "/active.exr").unwrap().slot.clone(); + drop(cache.get("/next.exr", Use::Channels, || Some(bytes.clone()))); + assert!(cache.cached().contains(&"/active.exr".to_string()), "an active caller pins the slot"); + + drop(active_slot); + drop(cache.get("/newest.exr", Use::Channels, || Some(bytes.clone()))); + assert!(!cache.cached().contains(&"/active.exr".to_string()), "an idle slot is eligible for eviction"); + } + /// #474: a decode that panics doesn't leave its file "decoding" in the cache (never dropped, /// its planes counted): the entry goes, and the next request decodes the file. #[test] @@ -1262,6 +1153,69 @@ mod tests { assert!(aux.get("ViewLayer.Combined.R").is_some()); } + #[test] + fn multipart_fallback_filters_channels_and_reserves_display_planes() { + use exr::prelude::*; + let part = |name: &str, pos: (i32, i32), size: (usize, usize), channels: Vec>| { + let attrs = LayerAttributes { layer_name: Some(Text::from(name)), layer_position: Vec2(pos.0, pos.1), ..Default::default() }; + Layer::new(size, attrs, Encoding::FAST_LOSSLESS, AnyChannels::sort(channels.into())) + }; + let (w, h) = (2usize, 1usize); + let bytes = file( + vec![ + part("Depth", (0, 0), (1, 1), vec![AnyChannel::new("Z", FlatSamples::F32(vec![7.0]))]), + part( + "Beauty", + (1, 1), + (w, h), + vec![ + AnyChannel::new("R", FlatSamples::F32(vec![0.1; w * h])), + AnyChannel::new("G", FlatSamples::F32(vec![0.2; w * h])), + AnyChannel::new("B", FlatSamples::F32(vec![0.3; w * h])), + ], + ), + ], + IntegerBounds::from_dimensions((3, 2)), + ); + let mut limits = craft_exr::decode::Limits::default(); + limits.max_width = u32::MAX; + limits.max_height = u32::MAX; + limits.max_pixels = u64::MAX; + limits.max_bytes = u64::MAX; + let parts = craft_exr::decode::parts(&bytes, &limits).unwrap(); + assert_eq!(planes_bytes(&parts, &|name| name == "Beauty.R"), Some(3 * 2 * 4)); + assert_eq!(planes_bytes(&parts, &|_| false), Some(0)); + + // Different display windows must not reserve every part at the first part's size. + let mut varied = parts.clone(); + varied[0].display_window.width = 1; + varied[0].display_window.height = 1; + varied[1].display_window.width = 10; + varied[1].display_window.height = 20; + assert_eq!(planes_bytes(&varied, &|_| true), Some(4 + 10 * 20 * 3 * 4)); + assert_eq!(planes_bytes(&varied, &|name| name == "Beauty.R"), Some(10 * 20 * 4)); + varied[1].display_window.width = u32::MAX; + varied[1].display_window.height = u32::MAX; + assert_eq!(planes_bytes(&varied, &|_| true), None); + assert_eq!(planes_bytes(&varied, &|name| name == "Depth.Z"), Some(4)); + + // Skipping the RGB part preserves the first-RGB fallback state and depth samples. + let depth = decode(&bytes, &|name| name == "Depth.Z").unwrap(); + assert_eq!(depth.rgb, Rgb::Unsupported); + assert_eq!(depth.aux.channels.len(), 1); + assert_eq!(depth.aux.get("Depth.Z").unwrap()[0], 7.0); + + let selected = decode(&bytes, &|name| name == "Beauty.R").unwrap(); + assert_eq!(selected.aux.channels.iter().map(|(name, _)| name.as_str()).collect::>(), ["Beauty.R"]); + assert_eq!(selected.aux.get("Beauty.R").unwrap(), [0.0, 0.0, 0.0, 0.0, 0.1, 0.1]); + + // The old app decoder selected the named beauty part when the first part was depth-only, + // and placed its data into the shared display window; retain that layered-picture result. + let image = layered_image(&bytes).unwrap().to_rgba32f(); + assert_eq!(image.get_pixel(1, 1).0, [0.1, 0.2, 0.3, 1.0]); + assert_eq!(image.get_pixel(0, 0).0, [0.0, 0.0, 0.0, 1.0]); + } + /// Straight RGBA of [`layered_image`] at pixel 0 for a file of single-value channels. fn picture>(channels: &[(S, f32)]) -> Vec { use exr::prelude::*; diff --git a/crates/media/src/gif_anim.rs b/crates/media/src/gif_anim.rs index d201c8b7e..dc5f55e27 100644 --- a/crates/media/src/gif_anim.rs +++ b/crates/media/src/gif_anim.rs @@ -5,11 +5,9 @@ //! delays), so uneven timing is kept exactly; [`Anim::frame_at`] looks the frame up by time. //! Animated WebP ([`crate::webp_anim`]) shares [`Anim`] and this decode path. -use std::io::Cursor; - use effectcraft_project::{AlphaMode, Footage, FootageKind}; use effectcraft_time::{FrameRate, Tick}; -use image::{AnimationDecoder, DynamicImage, codecs::gif::GifDecoder}; +use image::DynamicImage; use crate::{MediaError, Result}; @@ -26,6 +24,10 @@ pub(crate) const MAX_BYTES: usize = 256 << 20; /// Frames read from a GIF's or animated WebP's headers when probing. pub(crate) const MAX_FRAMES: usize = 100_000; +/// Frames kept when decoding a GIF or animated WebP: all of them. Only [`MAX_BYTES`] and the +/// canvas budget bound decoding, as before the shared frame readers; [`MAX_FRAMES`] bounds probing. +pub(crate) const DECODE_FRAMES: usize = usize::MAX; + /// Whether `f` is an animated GIF or WebP imported by [`probe`] or [`crate::webp_anim::probe`]: /// its frames come from an [`Anim`]. pub(crate) fn is_animated(f: &Footage) -> bool { @@ -43,18 +45,11 @@ pub(crate) fn gcd(a: u32, b: u32) -> u32 { } /// Describe an animated GIF as a movie. `None` for a GIF with fewer than two frames (a still) or -/// one whose headers can't be read. +/// one whose headers can't be read. A damaged tail keeps the frames before it. pub(crate) fn probe(path: &str, bytes: &[u8]) -> Option { - let mut dec = gif::DecodeOptions::new().read_info(Cursor::new(bytes)).ok()?; - let (width, height) = (u32::from(dec.width()), u32::from(dec.height())); - let mut delays: Vec = Vec::new(); - while delays.len() < MAX_FRAMES { - match dec.next_frame_info() { - Ok(Some(f)) => delays.push(delay_cs(u32::from(f.delay))), - // The end, or a damaged tail: keep the frames before it. - _ => break, - } - } + let info = craft_gif::scan(bytes, MAX_FRAMES)?; + let (width, height) = (u32::from(info.width), u32::from(info.height)); + let delays: Vec = info.frames.iter().map(|f| delay_cs(u32::from(f.delay_cs))).collect(); if delays.len() < 2 || width == 0 || height == 0 { return None; } @@ -93,43 +88,57 @@ impl Anim { if crate::webp_anim::is_webp(bytes) { return crate::webp_anim::load(bytes); } - let mut dec = GifDecoder::new(Cursor::new(bytes)).map_err(|e| MediaError::Decode(format!("GIF: {e}")))?; - // A frame may be far larger than the canvas, and the decoder allocates its buffer before - // decoding it: no single buffer may pass what all the frames may hold. - let mut limits = image::Limits::no_limits(); - limits.max_alloc = Some(MAX_BYTES as u64); - image::ImageDecoder::set_limits(&mut dec, limits).map_err(|e| MediaError::Decode(format!("GIF: {e}")))?; - // The decoder allocates the full logical canvas for the first frame, however small the - // frames themselves are: check it before decoding any. - let (w, h) = image::ImageDecoder::dimensions(&dec); - if u64::from(w) * u64::from(h) * 4 > MAX_BYTES as u64 { - return Err(MediaError::Unsupported(format!("GIF canvas of {w}×{h} is too large to hold in memory"))); - } - let (mut frames, mut starts) = (Vec::new(), Vec::new()); - let (mut at, mut size) = (0i64, 0usize); - for frame in dec.into_frames() { - let frame = match frame { - Ok(f) => f, - Err(e) if frames.is_empty() => return Err(MediaError::Decode(format!("GIF: {e}"))), - Err(e) => { - log::warn!("media: GIF stops after {} frames: {e}", frames.len()); - break; - } - }; - let (numer, denom) = frame.delay().numer_denom_ms(); - let cs = delay_cs(numer.checked_div(denom).unwrap_or(0) / 10); - let buf = frame.into_buffer(); - size = size.saturating_add(buf.as_raw().len()); - if size > MAX_BYTES { - return Err(MediaError::Unsupported("GIF is too large to hold in memory".into())); + // The frame reader scans every image descriptor before it checks the canvas: refuse a + // logical screen too large to hold first, as the former decoder did. + if let Some(&[w0, w1, h0, h1]) = bytes.get(6..10).filter(|_| bytes.starts_with(b"GIF8")) { + let (w, h) = (u16::from_le_bytes([w0, w1]), u16::from_le_bytes([h0, h1])); + if u64::from(w) * u64::from(h) * 4 > MAX_BYTES as u64 { + return Err(MediaError::Unsupported(format!("GIF canvas of {w}×{h} is too large to hold in memory"))); } + } + let mut limits = craft_gif::frames::FrameLimits::default(); + limits.max_frames = DECODE_FRAMES; + limits.max_bytes = MAX_BYTES as u64; + limits.max_canvas_bytes = MAX_BYTES as u64; + limits.max_decode_bytes = Some(MAX_BYTES as u64); + let decoded = craft_gif::frames::read_frames(bytes, &limits).map_err(|e| match e { + craft_gif::frames::FrameError::Malformed(m) => MediaError::Decode(format!("GIF: {m}")), + craft_gif::frames::FrameError::LimitExceeded(m) + if m.contains("cannot hold") || m.contains("decode-allocation limit") || m.to_ascii_lowercase().contains("memory limit") => + { + MediaError::Unsupported("GIF is too large to hold in memory".into()) + } + craft_gif::frames::FrameError::LimitExceeded(m) if m.contains("canvas is over") => { + MediaError::Unsupported("GIF canvas is too large to hold in memory".into()) + } + craft_gif::frames::FrameError::LimitExceeded(m) => MediaError::Unsupported(format!("GIF: {m}")), + })?; + if matches!(&decoded.stop, craft_gif::frames::Stop::ByteLimit | craft_gif::frames::Stop::FrameLimit) { + return Err(MediaError::Unsupported("GIF is too large to hold in memory".into())); + } + if let craft_gif::frames::Stop::Damaged(ref e) = decoded.stop { + log::warn!("media: GIF stops after {} frames: {e}", decoded.frames.len()); + } + let mut frames = Vec::with_capacity(decoded.frames.len()); + let mut starts = Vec::with_capacity(decoded.frames.len()); + let mut at = 0i64; + for frame in decoded.frames { + let cs = delay_cs(frame.delay_ms / 10); + let image = image::RgbaImage::from_raw(decoded.width, decoded.height, frame.rgba) + .ok_or_else(|| MediaError::Decode("GIF: invalid decoded frame dimensions".into()))?; starts.push(Tick::from_units(at, 100)); at = at.saturating_add(i64::from(cs)); - frames.push(DynamicImage::ImageRgba8(buf)); + frames.push(DynamicImage::ImageRgba8(image)); } Anim::new(frames, starts).ok_or_else(|| MediaError::Decode("GIF: no frames".into())) } + /// How many frames were decoded. + #[cfg(test)] + pub(crate) fn len(&self) -> usize { + self.frames.len() + } + /// The frame shown at source time `t` (the first one before the start, the last one past the /// end). pub(crate) fn frame_at(&self, t: Tick) -> Option<&DynamicImage> { @@ -140,9 +149,13 @@ impl Anim { #[cfg(test)] mod tests { + use std::io::Cursor; + use effectcraft_project::{Footage, FootageKind}; use effectcraft_time::{FrameRate, Tick}; + use image::AnimationDecoder; + use super::MAX_FRAMES; use crate::{MediaPool, probe_bytes}; /// A 2×2 GIF with one solid-colour frame per `(rgb, delay)`. @@ -159,6 +172,15 @@ mod tests { out } + /// Preserve the old consumer path as a test oracle while the frame API is shared. + fn legacy_gif_frames(bytes: &[u8]) -> Vec { + image::codecs::gif::GifDecoder::new(Cursor::new(bytes)).unwrap().into_frames().map(|frame| frame.unwrap().into_buffer()).collect() + } + + fn legacy_gif_frames_until_error(bytes: &[u8]) -> Vec { + image::codecs::gif::GifDecoder::new(Cursor::new(bytes)).unwrap().into_frames().map_while(|frame| frame.ok()).map(|frame| frame.into_buffer()).collect() + } + const RED: [u8; 3] = [255, 0, 0]; const GREEN: [u8; 3] = [0, 255, 0]; const BLUE: [u8; 3] = [0, 0, 255]; @@ -208,6 +230,62 @@ mod tests { assert_eq!(f.duration, Tick::from_units(20, 100)); } + #[test] + fn shared_gif_frames_match_legacy_compositing_and_disposal() { + let mut bytes = Vec::new(); + { + let palette = [255, 0, 0, 0, 255, 0, 0, 0, 255, 0, 0, 0]; + let mut enc = gif::Encoder::new(&mut bytes, 3, 2, &palette).unwrap(); + let first = gif::Frame { + width: 3, + height: 2, + buffer: vec![0; 6].into(), // red background + delay: 5, + dispose: gif::DisposalMethod::Keep, + ..gif::Frame::default() + }; + enc.write_frame(&first).unwrap(); + + let second = gif::Frame { + left: 1, + width: 1, + height: 1, + buffer: vec![1].into(), // green patch + delay: 7, + dispose: gif::DisposalMethod::Background, + ..gif::Frame::default() + }; + enc.write_frame(&second).unwrap(); + + let third = gif::Frame { + left: 2, + width: 1, + height: 1, + buffer: vec![2].into(), // blue patch after disposal + delay: 9, + dispose: gif::DisposalMethod::Previous, + ..gif::Frame::default() + }; + enc.write_frame(&third).unwrap(); + + let fourth = gif::Frame { + width: 1, + height: 1, + buffer: vec![3].into(), // black patch after restoring the previous canvas + delay: 11, + ..gif::Frame::default() + }; + enc.write_frame(&fourth).unwrap(); + } + let expected = legacy_gif_frames(&bytes); + let actual = super::Anim::load(&bytes).unwrap(); + assert_eq!(actual.frames.len(), expected.len()); + for (frame, old) in actual.frames.iter().zip(expected) { + assert_eq!(frame.to_rgba8(), old); + } + assert_eq!(actual.starts, vec![Tick::from_units(0, 100), Tick::from_units(5, 100), Tick::from_units(12, 100), Tick::from_units(21, 100)]); + } + #[test] fn a_single_frame_gif_stays_a_still() { let f = probe_bytes("a.gif", gif(&[(RED, 10)]).into()).unwrap(); @@ -235,6 +313,20 @@ mod tests { let _ = probe_bytes("a.gif", bytes.into()); } + #[test] + fn a_damaged_gif_tail_keeps_frames_already_decoded() { + let mut bytes = gif(&[(RED, 5), (GREEN, 5), (BLUE, 5)]); + let info = craft_gif::scan(&bytes, MAX_FRAMES).unwrap(); + assert_eq!(info.frames.len(), 3); + bytes.truncate(info.frames[1].offset); + + let legacy = legacy_gif_frames_until_error(&bytes); + assert_eq!(legacy.len(), 1); + let actual = super::Anim::load(&bytes).unwrap(); + assert_eq!(actual.frames.len(), legacy.len()); + assert_eq!(actual.frames[0].to_rgba8(), legacy[0]); + } + #[test] fn a_huge_canvas_is_refused_before_decoding() { // A 65535×65535 logical screen (16 GiB of RGBA) holding one 1×1 frame. @@ -246,6 +338,28 @@ mod tests { } } let e = super::Anim::load(&out).err().unwrap(); - assert!(e.to_string().contains("too large"), "{e}"); + assert!(e.to_string().contains("GIF canvas of 65535×65535 is too large"), "{e}"); + } + + /// A 1×1 GIF of `n` frames. + fn tiny_gif(n: usize) -> Vec { + let mut out = Vec::new(); + { + let mut enc = gif::Encoder::new(&mut out, 1, 1, &[]).unwrap(); + let frame = gif::Frame::from_rgb(1, 1, &RED); + for _ in 0..n { + enc.write_frame(&frame).unwrap(); + } + } + out + } + + #[test] + fn decoding_keeps_every_frame_past_the_probe_frame_count() { + // 1×1 frames fit the byte budget however many there are: the frame count refuses none. + for n in [MAX_FRAMES, MAX_FRAMES + 1] { + let anim = super::Anim::load(&tiny_gif(n)).unwrap(); + assert_eq!(anim.len(), n); + } } } diff --git a/crates/media/src/layered.rs b/crates/media/src/layered.rs index 64ade9394..68edd9808 100644 --- a/crates/media/src/layered.rs +++ b/crates/media/src/layered.rs @@ -1,7 +1,7 @@ //! Layered and vector stills: Photoshop documents (`effectcraft-psd`: the merged image, or one //! layer for footage imported as a composition) and vector files rasterised at any scale: SVG -//! (`effectcraft-svg`), PDF / Illustrator / EPS (`effectcraft-pdf`; one layer of the file for -//! footage imported as a composition). +//! (`effectcraft-svg`), PDF / Illustrator / EPS and the PDF a VectorCraft document carries +//! (`effectcraft-pdf`; one layer of the file for footage imported as a composition). use effectcraft_project::{AlphaMode, Footage}; use effectcraft_raster::Image; @@ -119,7 +119,7 @@ pub(crate) fn decode(path: &str, bytes: &[u8], footage: &Footage, op: AlphaOp) - if u64::from(w) * u64::from(h) > u64::from(MAX_VECTOR_SIDE) * u64::from(MAX_VECTOR_SIDE) { return Err(MediaError::Decode(format!("{path}: {w}×{h} pixels is larger than vector footage can be drawn ({MAX_VECTOR_SIDE}×{MAX_VECTOR_SIDE})"))); } - let img = effectcraft_svg::rasterize_with(&doc, w, h, to_image); + let img = effectcraft_svg::try_rasterize_with(&doc, w, h, to_image).map_err(|e| MediaError::Decode(format!("{path}: {e}")))?; // The rasteriser produces premultiplied pixels already. let _ = op; return Ok(Some(img)); @@ -132,10 +132,15 @@ const MAX_VECTOR_SIDE: u32 = 16384; /// The vector footage `footage` (of the file `path` with these `bytes`) rasterised at `scale` × /// its size as [`effectcraft_render::vector_fit`] draws it (Continuously Rasterize). -pub(crate) fn rasterize_vector(path: &str, bytes: &[u8], footage: &Footage, scale: f64) -> Option { +/// +/// `None` when the file cannot be read as a vector document. `Some(Err(_))` when a render budget +/// refused part of the drawing (for example a layer scaled past the surface limit), so the caller +/// can report it instead of showing a partial or empty image as if it were complete. +pub(crate) fn rasterize_vector(path: &str, bytes: &[u8], footage: &Footage, scale: f64) -> Option> { let doc = footage_doc(path, bytes, footage)?.ok()?; let ((sw, sh), to_image) = fit(&doc, footage, scale); - Some(effectcraft_svg::rasterize_with(&doc, sw.clamp(1, MAX_VECTOR_SIDE), sh.clamp(1, MAX_VECTOR_SIDE), to_image)) + let drawn = effectcraft_svg::try_rasterize_with(&doc, sw.clamp(1, MAX_VECTOR_SIDE), sh.clamp(1, MAX_VECTOR_SIDE), to_image); + Some(drawn.map_err(|e| MediaError::Decode(format!("{path}: {e}")))) } /// The page framing of vector footage: as After Effects places it for footage from an After @@ -173,6 +178,18 @@ mod tests { assert_eq!((img.width, img.height), (40, 20)); } + /// Continuously Rasterize reports a layer scaled past the render budget as an error instead of + /// returning a partial or empty image, and still draws the same layer at an ordinary scale. + #[test] + fn rasterizing_vector_footage_past_the_budget_is_reported() { + let svg = br#""#; + let footage = probe("scaled.svg", svg).unwrap().unwrap(); + let ok = rasterize_vector("scaled.svg", svg, &footage, 1.0).unwrap().unwrap(); + assert_eq!((ok.width, ok.height), (100, 100)); + let e = rasterize_vector("scaled.svg", svg, &footage, 1000.0).unwrap().err().map(|e| e.to_string()).unwrap_or_default(); + assert!(e.contains("scaled.svg"), "{e}"); + } + /// A 200 × 100 pt page: red left half, blue right half. fn halves_pdf() -> Vec { effectcraft_pdf::write::pdf( @@ -214,7 +231,7 @@ mod tests { (footage.width, footage.height) = (100, 80); let unplaced = decode("art.ai", &pdf, &footage, op).unwrap().unwrap(); assert!(unplaced == own, "not placed: drawn as before"); - assert_eq!(rasterize_vector("art.ai", &pdf, &footage, 0.5).map(|i| (i.width, i.height)), Some((100, 50))); + assert_eq!(rasterize_vector("art.ai", &pdf, &footage, 0.5).and_then(|r| r.ok()).map(|i| (i.width, i.height)), Some((100, 50))); footage.placed_page = true; let img = decode("art.ai", &pdf, &footage, op).unwrap().unwrap(); @@ -226,7 +243,7 @@ mod tests { assert!(is_blue(img.get(x, y)), "blue at ({x}, {y}): {:?}", img.get(x, y)); } - let sharp = rasterize_vector("art.ai", &pdf, &footage, 2.0).unwrap(); + let sharp = rasterize_vector("art.ai", &pdf, &footage, 2.0).unwrap().unwrap(); assert_eq!((sharp.width, sharp.height), (200, 160)); assert!(is_red(sharp.get(50, 155)) && is_blue(sharp.get(150, 155))); // Placed at the page's own size: 1:1. diff --git a/crates/media/src/lib.rs b/crates/media/src/lib.rs index 454c3705f..b2bf1563b 100644 --- a/crates/media/src/lib.rs +++ b/crates/media/src/lib.rs @@ -65,7 +65,7 @@ impl From for MediaError { /// File extensions recognised as stills. pub const STILL_EXTENSIONS: &[&str] = - &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "tga", "hdr", "psd", "psb", "svg", "pdf", "ai", "eps"]; + &["png", "jpg", "jpeg", "gif", "webp", "tif", "tiff", "bmp", "exr", "tga", "hdr", "psd", "psb", "svg", "pdf", "ai", "eps", "vectorcraft"]; /// File extensions recognised as audio-only files. pub const AUDIO_EXTENSIONS: &[&str] = filmcraft_media::AUDIO_EXTENSIONS; pub use effectcraft_project::VIDEO_EXTENSIONS; diff --git a/crates/media/src/pool.rs b/crates/media/src/pool.rs index 872e4fdfa..90e31a0e7 100644 --- a/crates/media/src/pool.rs +++ b/crates/media/src/pool.rs @@ -208,6 +208,10 @@ struct CacheState { last: HashMap, i64>, /// Movies whose frames can't be kept as 8-bit levels (more bits, or shown turned). wide: HashSet>, + /// Counts [`MediaPool::forget`]s and frame clears: a decode keeps its frame only when none + /// came while it ran, so one in flight when a file is forgotten (a closed project's, or one + /// changed on disk) can't bring the frame back. + forgets: u64, } /// A movie/audio source by path ([`Opened`]), opened by the first caller while the others wait @@ -406,6 +410,7 @@ impl MediaPool { let mut c = lock(&self.inner.cache); c.lru = Lru::default(); c.last.clear(); + c.forgets = c.forgets.wrapping_add(1); drop(c); // Decoded GIFs sit outside the frame budget; Purge frees them too. lock(&self.inner.gifs).clear(); @@ -418,7 +423,9 @@ impl MediaPool { lock(&self.inner.problems).clear(); } - /// Forget a file (after it changed on disk, or to retry a file that failed to open). + /// Forget a file (after it changed on disk or its project closed, or to retry a file that + /// failed to open). A decode of any file in flight meanwhile keeps nothing (see + /// [`CacheState::forgets`]). pub fn forget(&self, path: &str) { lock(&self.inner.sources).remove(path); lock(&self.inner.models).remove(path); @@ -431,6 +438,7 @@ impl MediaPool { } c.last.remove(path); c.wide.remove(path); + c.forgets = c.forgets.wrapping_add(1); drop(c); crate::exr_channels::forget(path); } @@ -455,7 +463,7 @@ impl MediaPool { if lock(&self.inner.cache).wide.contains(footage.path.as_str()) { return None; } - match Inner::frame_px(&self.inner, footage, t, true, None, float, true) { + match Inner::frame_px(&self.inner, footage, t, true, None, float, true, None) { Ok(Pixels::Q8(f)) => Some(f), _ => None, } @@ -850,7 +858,7 @@ impl Inner { /// The frame of `footage` at `t`, resampled to `size` (see [`FootageSource::frame_at_size`]): /// a movie's made at that size directly, a still's resampled once and kept at that size. fn frame_at(self: &Arc, footage: &Footage, t: Tick, playback: bool, size: Option<(u32, u32)>, float: FloatCurve) -> Result> { - match Self::frame_px(self, footage, t, playback, size, float, false)? { + match Self::frame_px(self, footage, t, playback, size, float, false, None)? { Pixels::F32(img) => Ok(img), // (a float request's key never holds 8-bit levels) Pixels::Q8(_) => Err(MediaError::Decode(format!("{}: 8-bit frame for a float request", footage.path))), @@ -859,8 +867,20 @@ impl Inner { /// [`Self::frame_at`], kept as 8-bit levels when `q8` is set and the frame has 8 bits (a /// float frame under the float key otherwise, and the movie is remembered as `wide`). + /// `since`: the [`CacheState::forgets`] count the read was asked at (a read-ahead's, when it + /// was queued); a read that missed is not decoded once a forget came after it, and a frame + /// decoded while one came is not kept. #[allow(clippy::too_many_arguments)] - fn frame_px(self: &Arc, footage: &Footage, t: Tick, playback: bool, size: Option<(u32, u32)>, float: FloatCurve, q8: bool) -> Result { + fn frame_px( + self: &Arc, + footage: &Footage, + t: Tick, + playback: bool, + size: Option<(u32, u32)>, + float: FloatCurve, + q8: bool, + since: Option, + ) -> Result { if !footage.has_video { return Err(MediaError::Unsupported(format!("{}: no video", footage.path))); } @@ -909,6 +929,10 @@ impl Inner { } c = self.done.wait(c).unwrap_or_else(std::sync::PoisonError::into_inner); } + let since = since.unwrap_or(c.forgets); + if c.forgets != since { + return Err(MediaError::Cancelled); + } self.misses.fetch_add(1, Ordering::Relaxed); c.inflight.insert(loc.key.clone()); drop(c); @@ -917,6 +941,9 @@ impl Inner { reads::note_all(&files); let img = img?; let mut c = lock(&self.cache); + if c.forgets != since { + return Ok(img); + } if q8 && let Pixels::F32(_) = img { // not 8-bit: kept as the float frame it is, which the renderer asks for next c.wide.insert(loc.key.path.clone()); @@ -935,23 +962,23 @@ impl Inner { next.key.size = loc.key.size; next.key.q8 = loc.key.q8; if next.key != loc.key && !c.lru.map.contains_key(&next.key) && !c.inflight.contains(&next.key) { - self.prefetch(footage, next_t, size, float, loc.key.q8); + self.prefetch(footage, next_t, size, float, loc.key.q8, c.forgets); } } } #[cfg(not(target_arch = "wasm32"))] - fn prefetch(self: &Arc, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve, q8: bool) { + fn prefetch(self: &Arc, footage: &Footage, t: Tick, size: Option<(u32, u32)>, float: FloatCurve, q8: bool, since: u64) { let (me, f) = (self.clone(), footage.clone()); self.prefetched.fetch_add(1, Ordering::Relaxed); // A plain thread, not a rayon job: the decode below parallelises with rayon itself. std::thread::spawn(move || { - let _ = me.frame_px(&f, t, false, size, float, q8); + let _ = me.frame_px(&f, t, false, size, float, q8, Some(since)); }); } #[cfg(target_arch = "wasm32")] - fn prefetch(self: &Arc, _footage: &Footage, _t: Tick, _size: Option<(u32, u32)>, _float: FloatCurve, _q8: bool) {} + fn prefetch(self: &Arc, _footage: &Footage, _t: Tick, _size: Option<(u32, u32)>, _float: FloatCurve, _q8: bool, _since: u64) {} /// A still (image file or sequence frame) at `loc.key.size` when one is set: resampled as the /// renderer would ([`FootageSource::frame_at_size`]), so the pool keeps the reduced frame and a @@ -1110,7 +1137,7 @@ impl FootageSource for MediaPool { } fn problem(&self, footage: &Footage) -> Option { - if footage.missing || footage.kind != FootageKind::Video { + if footage.missing || (footage.kind != FootageKind::Video && !effectcraft_render::is_vector_footage(footage)) { return None; } lock(&self.inner.problems).get(footage.path.as_str()).cloned() @@ -1121,7 +1148,19 @@ impl FootageSource for MediaPool { return None; } let bytes = self.inner.read(&footage.path).ok()?; - crate::layered::rasterize_vector(&footage.path, &bytes, footage, scale).map(Arc::new) + let path: Arc = footage.path.as_str().into(); + match crate::layered::rasterize_vector(&footage.path, &bytes, footage, scale)? { + Ok(img) => { + lock(&self.inner.problems).remove(&path); + Some(Arc::new(img)) + } + // Refused by a render budget (a layer scaled too far): no frame, with the reason + // reported through `problem` rather than showing a partial image as complete. + Err(e) => { + self.inner.note_problem(&path, "", &e); + None + } + } } fn set_aux_footage(&self, paths: &[String]) { @@ -1203,6 +1242,25 @@ fn lock(m: &Mutex) -> std::sync::MutexGuard<'_, T> { mod tests { use super::*; + /// #2042: a read queued before its file was forgotten (as a read-ahead of a closed project's + /// movie is, by the read of the frame before) decodes nothing and keeps nothing; a read asked + /// after the forget decodes and keeps its frame. (A still stands in for the movie.) + #[test] + fn reads_queued_before_a_forget_keep_nothing() { + let mut png = std::io::Cursor::new(Vec::new()); + image::RgbaImage::new(2, 2).write_to(&mut png, image::ImageFormat::Png).unwrap(); + let pool = MediaPool::new(); + pool.add_bytes("/a.png", png.into_inner().into()); + let f = Footage { path: "/a.png".into(), kind: FootageKind::Still, width: 2, height: 2, has_video: true, ..Default::default() }; + let queued = lock(&pool.inner.cache).forgets; + pool.forget("/a.png"); + let read = Inner::frame_px(&pool.inner, &f, Tick::ZERO, false, None, FloatCurve::Srgb, false, Some(queued)); + assert!(matches!(read, Err(MediaError::Cancelled)), "{:?}", read.err()); + assert_eq!(pool.stats().frames, 0, "the forgotten file's frame came back"); + pool.frame_at(&f, Tick::ZERO).unwrap(); + assert_eq!(pool.stats().frames, 1); + } + /// Conforming a long file's audio reads every chunk at its own time: the sample index times /// ticks per second overflowed `i64` past 12:36 at 48 kHz, and later chunks came out silent /// (#172). diff --git a/crates/media/src/webp_anim.rs b/crates/media/src/webp_anim.rs index f0784d1e3..bb2fdcc69 100644 --- a/crates/media/src/webp_anim.rs +++ b/crates/media/src/webp_anim.rs @@ -9,13 +9,11 @@ //! every delay is a whole number of frames at (1000 / the greatest common divisor of the delays), //! so it is kept exactly. A still WebP (no animation flag, or a single frame) stays a still. -use std::io::Cursor; - use effectcraft_project::{AlphaMode, Footage, FootageKind}; use effectcraft_time::{FrameRate, Tick}; -use image::{AnimationDecoder, DynamicImage, codecs::webp::WebPDecoder}; +use image::DynamicImage; -use crate::gif_anim::{Anim, MAX_BYTES, MAX_FRAMES, gcd}; +use crate::gif_anim::{Anim, DECODE_FRAMES, MAX_BYTES, MAX_FRAMES, gcd}; use crate::{MediaError, Result}; /// The `Footage::codec` of an animated WebP. @@ -23,7 +21,7 @@ pub(crate) const CODEC: &str = "WebP"; /// Whether `bytes` start like a WebP file. pub(crate) fn is_webp(bytes: &[u8]) -> bool { - bytes.get(0..4) == Some(b"RIFF") && bytes.get(8..12) == Some(b"WEBP") + craft_webp::is_webp(bytes) } /// What the chunk headers of an animated WebP say. @@ -35,46 +33,11 @@ struct Header { delays: Vec, } -fn u24(b: &[u8]) -> Option { - match b { - [a, b, c, ..] => Some(u32::from(*a) | u32::from(*b) << 8 | u32::from(*c) << 16), - _ => None, - } -} - /// Read the `VP8X` header and the `ANMF` frame headers. `None` when the file isn't an animated /// WebP. A truncated tail keeps the frames before it. fn header(bytes: &[u8]) -> Option
{ - if !is_webp(bytes) { - return None; - } - let riff = bytes.get(4..8).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)?; - let end = usize::try_from(riff).ok()?.saturating_add(8).min(bytes.len()); - let (mut at, mut canvas, mut delays) = (12usize, None, Vec::new()); - while delays.len() < MAX_FRAMES { - let Some(head) = bytes.get(at..at.saturating_add(8)).filter(|_| at.saturating_add(8) <= end) else { break }; - let size = head.get(4..8).and_then(|b| b.try_into().ok()).map(u32::from_le_bytes)?; - let size = usize::try_from(size).ok()?; - let body_end = at.saturating_add(8).saturating_add(size); - let Some(body) = bytes.get(at.saturating_add(8)..body_end).filter(|_| body_end <= end) else { break }; - match head.get(0..4) { - Some(b"VP8X") => { - let flags = *body.first()?; - if flags & 0x02 == 0 { - // No animation flag: a still. - return None; - } - let w = u24(body.get(4..)?)?.saturating_add(1); - let h = u24(body.get(7..)?)?.saturating_add(1); - canvas = Some((w, h, flags & 0x10 != 0)); - } - Some(b"ANMF") if body.len() >= 16 => delays.push(u24(body.get(12..)?)?), - _ => {} - } - at = body_end.saturating_add(size & 1); - } - let (width, height, alpha) = canvas?; - Some(Header { width, height, alpha, delays }) + let info = craft_webp::scan(bytes, MAX_FRAMES).filter(|i| i.animated)?; + Some(Header { width: info.width, height: info.height, alpha: info.alpha, delays: info.frames.iter().map(|f| f.duration_ms).collect() }) } /// The delay of a frame in milliseconds. Browsers show delays of 10 ms or less (that encoders @@ -156,29 +119,29 @@ pub(crate) fn load(bytes: &[u8]) -> Result { if frame_bytes.saturating_mul(h.delays.len()) > MAX_BYTES { return Err(MediaError::Unsupported(format!("animated WebP of {} frames of {}×{} is too large to hold in memory", h.delays.len(), h.width, h.height))); } - let dec = WebPDecoder::new(Cursor::new(bytes)).map_err(|e| MediaError::Decode(format!("WebP: {e}")))?; - // The budget above used the canvas this file's header scan found; the decoder must agree, or - // a second VP8X header could make it allocate a far larger canvas. - if image::ImageDecoder::dimensions(&dec) != (h.width, h.height) { + let mut limits = craft_webp::frames::FrameLimits::default(); + limits.max_frames = DECODE_FRAMES; + limits.max_bytes = MAX_BYTES as u64; + limits.max_canvas_bytes = MAX_BYTES as u64; + let decoded = craft_webp::frames::read_frames(bytes, &limits).map_err(|e| match e { + craft_webp::frames::FrameError::Malformed(m) => MediaError::Decode(format!("WebP: {m}")), + craft_webp::frames::FrameError::LimitExceeded(m) => MediaError::Unsupported(format!("WebP: {m}")), + })?; + if matches!(&decoded.stop, craft_webp::frames::Stop::ByteLimit | craft_webp::frames::Stop::FrameLimit) { + return Err(MediaError::Unsupported("animated WebP is too large to hold in memory".into())); + } + if let craft_webp::frames::Stop::Damaged(ref e) = decoded.stop { + log::warn!("media: WebP stops after {} frames: {e}", decoded.frames.len()); + } + if (decoded.width, decoded.height) != (h.width, h.height) { return Err(MediaError::Decode("WebP: conflicting canvas sizes".into())); } - let (mut frames, mut delays, mut size) = (Vec::new(), Vec::new(), 0usize); - for frame in dec.into_frames() { - let frame = match frame { - Ok(f) => f, - Err(e) if frames.is_empty() => return Err(MediaError::Decode(format!("WebP: {e}"))), - Err(e) => { - log::warn!("media: WebP stops after {} frames: {e}", frames.len()); - break; - } - }; - let (numer, denom) = frame.delay().numer_denom_ms(); - delays.push(numer.checked_div(denom).unwrap_or(0)); - let buf = frame.into_buffer(); - size = size.saturating_add(buf.as_raw().len()); - if size > MAX_BYTES { - return Err(MediaError::Unsupported("animated WebP is too large to hold in memory".into())); - } + let mut frames = Vec::with_capacity(decoded.frames.len()); + let mut delays = Vec::with_capacity(decoded.frames.len()); + for frame in decoded.frames { + delays.push(frame.delay_ms); + let buf = image::RgbaImage::from_raw(decoded.width, decoded.height, frame.rgba) + .ok_or_else(|| MediaError::Decode("WebP: invalid decoded frame dimensions".into()))?; frames.push(DynamicImage::ImageRgba8(buf)); } let starts = timing(&delays).starts; @@ -187,9 +150,11 @@ pub(crate) fn load(bytes: &[u8]) -> Result { #[cfg(test)] mod tests { + use std::io::Cursor; + use effectcraft_project::{AlphaMode, Footage, FootageKind}; use effectcraft_time::{FrameRate, Tick}; - use image::{ExtendedColorType, ImageEncoder, codecs::webp::WebPEncoder}; + use image::{AnimationDecoder, ExtendedColorType, ImageEncoder, codecs::webp::WebPDecoder, codecs::webp::WebPEncoder}; use super::timing; use crate::{MediaPool, probe_bytes}; @@ -239,6 +204,43 @@ mod tests { chunk(b"RIFF", &body) } + /// Build an animation whose frames may cover only part of the canvas. `x` and `y` are even, + /// as required by ANMF; bit 1 of `flags` selects no-blend and bit 0 selects disposal. + fn webp_subframes(canvas: (u32, u32), frames: &[(u32, u32, u32, u32, [u8; 4], u32, u8)]) -> Vec { + let (w, h) = canvas; + let mut vp8x = vec![0x12, 0, 0, 0]; + vp8x.extend_from_slice(&u24(w - 1)); + vp8x.extend_from_slice(&u24(h - 1)); + let mut body = b"WEBP".to_vec(); + body.extend(chunk(b"VP8X", &vp8x)); + body.extend(chunk(b"ANIM", &[0; 6])); + for &(x, y, fw, fh, rgba, delay, flags) in frames { + let mut anmf = Vec::new(); + anmf.extend_from_slice(&u24(x / 2)); + anmf.extend_from_slice(&u24(y / 2)); + anmf.extend_from_slice(&u24(fw - 1)); + anmf.extend_from_slice(&u24(fh - 1)); + anmf.extend_from_slice(&u24(delay)); + anmf.push(flags); + anmf.extend(vp8l(fw, fh, rgba)); + body.extend(chunk(b"ANMF", &anmf)); + } + chunk(b"RIFF", &body) + } + + fn anmf_offsets(bytes: &[u8]) -> Vec { + let mut offsets = Vec::new(); + let mut at = 12usize; + while at + 8 <= bytes.len() { + let size = u32::from_le_bytes(bytes[at + 4..at + 8].try_into().unwrap()) as usize; + if &bytes[at..at + 4] == b"ANMF" { + offsets.push(at); + } + at = at.saturating_add(8).saturating_add(size).saturating_add(size & 1); + } + offsets + } + const RED: [u8; 4] = [255, 0, 0, 255]; const GREEN: [u8; 4] = [0, 255, 0, 255]; const BLUE: [u8; 4] = [0, 0, 255, 128]; @@ -273,6 +275,38 @@ mod tests { assert_eq!(pixel_at(&pool, &f, 5.0), last); } + #[test] + fn shared_webp_frames_match_legacy_subrect_blending_and_disposal() { + // Includes a blended alpha patch, then a no-blend patch disposed to the background. + let bytes = + webp_subframes((4, 2), &[(0, 0, 4, 2, RED, 50, 0b10), (2, 0, 2, 2, BLUE, 60, 0b00), (0, 0, 2, 2, GREEN, 70, 0b11), (2, 0, 2, 2, RED, 80, 0b10)]); + let expected = WebPDecoder::new(Cursor::new(&bytes)).unwrap().into_frames().map(|frame| frame.unwrap().into_buffer()).collect::>(); + let actual = super::load(&bytes).unwrap(); + assert_eq!(expected.len(), 4); + for (index, (start_ms, old)) in [(0, &expected[0]), (50, &expected[1]), (110, &expected[2]), (180, &expected[3])].into_iter().enumerate() { + let tick = Tick::from_units(start_ms, 1000); + let frame = actual.frame_at(tick).unwrap().to_rgba8(); + assert_eq!(frame, *old, "frame {index} at {start_ms} ms"); + } + } + + #[test] + fn a_damaged_webp_tail_keeps_frames_already_decoded() { + let mut bytes = webp(4, 2, &[(RED, 50), (GREEN, 60), (BLUE, 70)]); + let offsets = anmf_offsets(&bytes); + assert_eq!(offsets.len(), 3); + bytes.truncate(offsets[2]); + + let legacy = + WebPDecoder::new(Cursor::new(&bytes)).unwrap().into_frames().map_while(|frame| frame.ok()).map(|frame| frame.into_buffer()).collect::>(); + assert_eq!(legacy.len(), 2); + let actual = super::load(&bytes).unwrap(); + for (index, old) in legacy.iter().enumerate() { + let tick = Tick::from_units(if index == 0 { 0 } else { 50 }, 1000); + assert_eq!(actual.frame_at(tick).unwrap().to_rgba8(), *old); + } + } + #[test] fn delays_rounded_to_milliseconds_read_as_the_standard_rate() { // 24 frames a second rounded to whole milliseconds, as ffmpeg writes them. @@ -347,4 +381,34 @@ mod tests { bytes[4..8].copy_from_slice(&riff.to_le_bytes()); assert!(super::load(&bytes).is_err()); } + + /// A 1×1 animated WebP of `n` identical frames. + fn tiny_webp(n: usize) -> Vec { + let mut anmf = vec![0; 6]; + anmf.extend_from_slice(&u24(0)); + anmf.extend_from_slice(&u24(0)); + anmf.extend_from_slice(&u24(50)); + anmf.push(0b10); + anmf.extend(vp8l(1, 1, RED)); + let frame = chunk(b"ANMF", &anmf); + let mut vp8x = vec![0x12, 0, 0, 0]; + vp8x.extend_from_slice(&u24(0)); + vp8x.extend_from_slice(&u24(0)); + let mut body = b"WEBP".to_vec(); + body.extend(chunk(b"VP8X", &vp8x)); + body.extend(chunk(b"ANIM", &[0; 6])); + for _ in 0..n { + body.extend_from_slice(&frame); + } + chunk(b"RIFF", &body) + } + + #[test] + fn decoding_keeps_every_frame_past_the_probe_frame_count() { + // 1×1 frames fit the byte budget however many there are: the frame count refuses none. + for n in [crate::gif_anim::MAX_FRAMES, crate::gif_anim::MAX_FRAMES + 1] { + let anim = super::load(&tiny_webp(n)).unwrap(); + assert_eq!(anim.len(), n); + } + } } diff --git a/crates/media/tests/fixtures/README.md b/crates/media/tests/fixtures/README.md new file mode 100644 index 000000000..1e9b6bf45 --- /dev/null +++ b/crates/media/tests/fixtures/README.md @@ -0,0 +1,31 @@ +# Synthetic AAC layout fixture + +`pce61-ffmpeg.aac-fixture` contains only original mathematical sine tones generated for these tests by Dylan M. Taylor. No recorded audio or third-party source/assets were copied; the generated fixture is covered by this repository's license. FFmpeg is a generation tool, not a runtime test dependency. + +Generator: FFmpeg 7.1.5 (Debian 7.1.5-0+deb13u1, AAC encoder Lavc61.19.101). +SHA-256: `07c460636dce4aa4163df8ef35f3b76f1214c38bf217aacd23243e608d87071e`. + +The seven PCM inputs are FL500Hz, FR700Hz, FC300Hz, LFE60Hz, BC900Hz, SL1100Hz, SR1300Hz, each amplitude0.25 at48kHz for2seconds. The real encoder emits its own PCE and matching element tags; unlike the previous synthetic configuration rewrite, no LFE element is mislabeled as an unlisted SCE. + +Reproduce using FFmpeg/ffprobe and Python3: + +```sh +ffmpeg -hide_banner -loglevel error -f lavfi -i 'aevalsrc=0.25*sin(2*PI*500*t)|0.25*sin(2*PI*700*t)|0.25*sin(2*PI*300*t)|0.25*sin(2*PI*60*t)|0.25*sin(2*PI*900*t)|0.25*sin(2*PI*1100*t)|0.25*sin(2*PI*1300*t):s=48000:d=2:c=6.1' -c:a aac -b:a 672k pce61.m4a +ffprobe -v error -show_streams -show_packets -show_data -of json pce61.m4a > pce61.json +python3 - <<'PY' +import json, struct +x = json.load(open('pce61.json')) +def raw(text): + return bytes.fromhex(''.join(line.split(': ', 1)[1].split(' ', 1)[0].replace(' ', '') + for line in text.strip().splitlines())) +asc = raw(x['streams'][0]['extradata']) +units = [raw(p['data']) for p in x['packets']] +assert len(units) == 95 +output = bytearray(b'PCE1') +for record in [asc, *units]: + output += struct.pack('>I', len(record)) + record +open('pce61-ffmpeg.aac-fixture', 'wb').write(output) +PY +``` + +Envelope: ASCII `PCE1`, then a big-endian32-bit length and ASC bytes, then95 length-prefixed raw AAC access units. Container priming trim is deliberately not retained, matching the existing tests' encoder units; measurements start0.5seconds into decoded audio. Other encoder versions can yield different bytes; preserve actual PCE/AU consistency and all existing tone-gain assertions. diff --git a/crates/media/tests/fixtures/pce61-ffmpeg.aac-fixture b/crates/media/tests/fixtures/pce61-ffmpeg.aac-fixture new file mode 100644 index 000000000..d2894ff82 Binary files /dev/null and b/crates/media/tests/fixtures/pce61-ffmpeg.aac-fixture differ diff --git a/crates/media/tests/fixtures/pce61-ffmpeg.aac-fixture.attribution b/crates/media/tests/fixtures/pce61-ffmpeg.aac-fixture.attribution new file mode 100644 index 000000000..3f385a1e4 --- /dev/null +++ b/crates/media/tests/fixtures/pce61-ffmpeg.aac-fixture.attribution @@ -0,0 +1,7 @@ +asset: pce61-ffmpeg.aac-fixture +title: Synthetic seven-channel AAC PCE tone fixture +author: Dylan M. Taylor +source: crates/media/tests/fixtures/README.md (reproducible generation recipe) +license: MIT OR Apache-2.0 +added: 2026-11-16 +notes: Original sine-wave signals, no recorded audio or copied assets. Encoded using FFmpeg 7.1.5. SHA-256 07c460636dce4aa4163df8ef35f3b76f1214c38bf217aacd23243e608d87071e. diff --git a/crates/media/tests/it/aac_layout.rs b/crates/media/tests/it/aac_layout.rs index 896e4f0a7..5adf762b2 100644 --- a/crates/media/tests/it/aac_layout.rs +++ b/crates/media/tests/it/aac_layout.rs @@ -1,7 +1,8 @@ //! Multichannel AAC reaches stereo by where each channel plays, whatever order its channel -//! configuration decodes in (#1701). Fixtures are tones encoded with craft-audio's AAC encoder (no -//! ffmpeg needed, so nothing is skipped), with the configuration rewritten where the coded -//! elements fit another: configurations 11 and 12 code the same elements as the encoder's 7- and +//! configuration decodes in (#1701). Fixtures are tones encoded with craft-audio's AAC encoder, +//! plus a checked-in genuine FFmpeg-generated 6.1-channel fixture (no external tool at test time, nothing skipped). +//! The configuration is rewritten only where the coded elements fit another: configurations 11 +//! and 12 code the same elements as the encoder's 7- and //! 8-channel output, and a program config element can name any of them. use std::f64::consts::PI; @@ -9,7 +10,7 @@ use std::io::Cursor; use std::path::PathBuf; use std::sync::Arc; -use craft_audio::aac::{AudioSpecificConfig, Encoder, EncoderConfig, ProgramConfig}; +use craft_audio::aac::{AudioSpecificConfig, Encoder, EncoderConfig}; use effectcraft_media::{MediaPool, probe, probe_bytes}; use effectcraft_time::Tick; @@ -59,13 +60,6 @@ fn lc(config: u8) -> Option { Some(AudioSpecificConfig::lc(3, config)) } -fn pce(front: Vec<(bool, u8)>, side: Vec<(bool, u8)>, back: Vec<(bool, u8)>, lfe: Vec, comment: &[u8]) -> Option { - let pce = ProgramConfig { object_type: 1, sf_index: 3, front, side, back, lfe, comment: comment.to_vec(), ..Default::default() }; - let mut asc = AudioSpecificConfig::lc(3, 0); - asc.pce = Some(pce); - Some(asc) -} - use Ch::*; fn cases() -> Vec { @@ -80,15 +74,9 @@ fn cases() -> Vec { Case { name: "config12", content: &[C, L, R, Ls, Rs, Ls, Rs, Lfe], asc: lc(12) }, // the encoder's own 6.1: a PCE listing the centre first Case { name: "pce61-centre-first", content: &[C, L, R, Ls, Rs, Cs, Lfe], asc: None }, - // ffmpeg's 6.1 PCE: front pair and centre, a side SCE, a back pair and SCE, no LFE - // element, its channels in ffmpeg's order L R C LFE Cs Ls Rs. The decoder places the - // encoder's SCE 0 in the front SCE, pair 0 front, pair 1 back, SCE 1 in the back SCE (tag - // 1) and the LFE in the side SCE left over (tag 5). - Case { - name: "pce61-ffmpeg", - content: &[C, L, R, Cs, Ls, Rs, Lfe], - asc: pce(vec![(true, 0), (false, 0)], vec![(false, 5)], vec![(true, 1), (false, 1)], vec![], b"Lavc62.28.102"), - }, + // A genuine FFmpeg-generated 6.1-channel PCE and matching coded elements; rewriting only the ASC of + // our encoder's LFE0 stream to claim a side SCE5 would make an invalid access unit. + Case { name: "pce61-ffmpeg", content: &[C, L, R, Cs, Ls, Rs, Lfe], asc: None }, ] } @@ -110,6 +98,32 @@ fn encode(content: &[Ch], adts: bool) -> (Vec, Vec>) { (enc.audio_specific_config(), units) } +/// Preserve the fixture's real element types/tags instead of changing only its ASC. +/// The envelope and reproducible tone-generation recipe are in `tests/fixtures/README.md`. +fn encode_case(case: &Case) -> (Vec, Vec>) { + if case.name == "pce61-ffmpeg" { + let bytes = include_bytes!("../fixtures/pce61-ffmpeg.aac-fixture"); + assert_eq!(&bytes[..4], b"PCE1"); + let mut rest = &bytes[4..]; + let mut record = || { + let len = u32::from_be_bytes(rest[..4].try_into().unwrap()) as usize; + let (data, tail) = rest[4..].split_at(len); + rest = tail; + data.to_vec() + }; + let asc = record(); + let mut units = Vec::new(); + // The generated fixture contains 95 access units (including encoder priming). + for _ in 0..95 { + units.push(record()); + } + assert!(rest.is_empty(), "fixture has no unparsed records"); + return (asc, units); + } + let (asc, units) = encode(case.content, false); + (case.asc.as_ref().map_or(asc, |a| a.to_bytes().expect("ASC")), units) +} + fn mp4(asc: Vec, channels: u32, units: &[Vec]) -> Vec { mp4_after(None, asc, channels, units) } @@ -211,8 +225,7 @@ fn lfe_is_coded(case: &Case, bytes: Vec) { #[test] fn every_aac_layout_mixes_by_speaker_in_mp4() { for case in cases() { - let (asc, units) = encode(case.content, false); - let asc = case.asc.as_ref().map_or(asc, |a| a.to_bytes().expect("ASC")); + let (asc, units) = encode_case(&case); let bytes = mp4(asc, case.content.len() as u32, &units); lfe_is_coded(&case, bytes.clone()); let p = write(&format!("{}.mp4", case.name), &bytes); @@ -228,8 +241,7 @@ fn every_aac_layout_mixes_by_speaker_in_mp4() { #[test] fn matroska_aac_layouts_mix_by_speaker() { for case in cases().into_iter().filter(|c| matches!(c.name, "config12" | "pce61-centre-first" | "pce61-ffmpeg")) { - let (asc, units) = encode(case.content, false); - let asc = case.asc.as_ref().map_or(asc, |a| a.to_bytes().expect("ASC")); + let (asc, units) = encode_case(&case); let p = write(&format!("{}.mkv", case.name), &mkv(asc, case.content.len() as u32, &units)); check(case.name, case.content, &mix(&MediaPool::new(), &probe(&p).expect("probe"))); } @@ -254,8 +266,7 @@ fn an_empty_audio_track_lends_its_configuration_to_no_other() { let case = cases().into_iter().find(|c| c.name == name).expect("case"); let n = case.content.len() as u32; let empty = Some((AudioSpecificConfig::lc(3, empty).to_bytes().expect("ASC"), n)); - let (asc, units) = encode(case.content, false); - let asc = case.asc.as_ref().map_or(asc, |a| a.to_bytes().expect("ASC")); + let (asc, units) = encode_case(&case); let p = write(&format!("{name}-after-empty.mp4"), &mp4_after(empty.clone(), asc.clone(), n, &units)); check(&format!("{name} MP4"), case.content, &mix(&MediaPool::new(), &probe(&p).expect("probe"))); let p = write(&format!("{name}-after-empty.mkv"), &mkv_after(empty, asc, n, &units)); diff --git a/crates/model/Cargo.toml b/crates/model/Cargo.toml index ebe7da7e8..1dfa79430 100644 --- a/crates/model/Cargo.toml +++ b/crates/model/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "effectcraft-model" -description = "3D models: glTF 2.0 (.gltf/.glb), Wavefront OBJ/MTL, STL and FBX 7.x (binary and ASCII) import, PBR metallic-roughness materials, node hierarchy, skinning and animation, parametric primitives, and extruded/bevelled outline meshes" +description = "3D models: glTF 2.0 (.gltf/.glb), Wavefront OBJ/MTL, STL and FBX 6.x/7.x (binary and ASCII) import through craft-mesh, PBR metallic-roughness materials, node hierarchy, skinning and animation, parametric primitives, and extruded/bevelled outline meshes" version.workspace = true edition.workspace = true license.workspace = true @@ -10,10 +10,9 @@ rust-version.workspace = true workspace = true [dependencies] +craft-mesh = { workspace = true } effectcraft-geom = { workspace = true } serde = { workspace = true } -serde_json = { workspace = true } thiserror = { workspace = true } log = { workspace = true } image = { workspace = true } -miniz_oxide = "0.9" diff --git a/crates/model/src/fbx.rs b/crates/model/src/fbx.rs index 4f952847c..fead03b21 100644 --- a/crates/model/src/fbx.rs +++ b/crates/model/src/fbx.rs @@ -1,1017 +1,34 @@ -//! FBX 7.x scenes, binary and ASCII. -//! -//! Written from public descriptions of the format (the binary node-record layout, the ASCII -//! syntax, and the scene objects of the Autodesk FBX SDK documentation): no importer source was -//! read. -//! -//! - **Binary**: the `Kaydara FBX Binary` header and version, node records with 32-bit (before -//! 7.5) or 64-bit offsets, every property type (`Y C I F D L S R` and the `f d l i b` arrays, -//! zlib-compressed or not). Object names `Name\0\x01Class` become `Class::Name` as in ASCII. -//! - **ASCII**: `Key: value, value { children }` with `;` comments and `*N { a: … }` arrays. -//! - **Scene**: `Geometry` meshes (`Vertices`, `PolygonVertexIndex` polygons fan-triangulated, -//! the first `LayerElementNormal`, `LayerElementUV` and `LayerElementMaterial` with every -//! mapping and reference mode), `Model` nodes with the SDK transform (translation, rotation -//! offset and pivot, pre/post rotation, Euler rotation in its order, scaling offset and pivot, -//! scaling) and geometric transforms, `Material` (Lambert/Phong mapped onto -//! metallic-roughness), `Texture` and `Video` (embedded or relative image files), joined by -//! `Connections`. `GlobalSettings` axes turn the scene to +Y up. -//! -//! Not imported: FBX 6.x and older, animation stacks, skin deformers, blend shapes, cameras and -//! lights, NURBS and patches. Units stay the file's own (like OBJ). +//! FBX 6.x and 7.x scenes, binary and ASCII, read with `craft-mesh` (`craft_mesh::fbx`): +//! `Geometry` meshes, `Model` nodes with the SDK transform and geometric transforms, `Material` +//! (Lambert/Phong mapped onto metallic-roughness), embedded or relative `Texture` images, +//! joined by `Connections`. A root node turns the file's `GlobalSettings` axes to +Y up; units +//! stay the file's own (like OBJ). Meshes without normals get smooth ones. -use std::collections::HashMap; -use std::sync::Arc; +use crate::scene::{MissingNormals, error, limits, mat4, to_model}; +use crate::{Model, ModelError, Node, Result}; -use crate::obj::srgb_to_linear; -use crate::{AlphaMode, Mat4, Material, Mesh, Model, ModelError, Node, Primitive, Result, TexRef, Texture, perr, vec3}; +pub use craft_mesh::fbx::BINARY_MAGIC; -/// The binary file's magic (`Kaydara FBX Binary`, two spaces, NUL, 0x1A, 0x00). -pub const BINARY_MAGIC: &[u8] = b"Kaydara FBX Binary \0\x1a\0"; - -/// Deepest node nesting accepted (real files nest well under 10 levels). -const MAX_DEPTH: usize = 64; -/// Largest decoded array accepted (bytes). -const MAX_ARRAY_BYTES: usize = 1 << 30; -/// Most memory one import may keep: parsed arrays as stored (8 bytes per element, whatever the -/// wire type) plus the meshes built from them (#1234). -const MAX_IMPORT_BYTES: usize = 1 << 31; - -/// Most pixels one texture may hold (8192 × 8192) and all the textures of one import together -/// (2^29: 8 GiB as float RGBA, thirty-two 4K maps). A texture past a limit is left out and the -/// import says so. -const MAX_TEXTURE_PIXELS: u64 = 1 << 26; -const MAX_TEXTURE_IMPORT_PIXELS: u64 = 1 << 29; - -/// What is left of an import's memory budget. -struct Budget(std::cell::Cell); - -impl Budget { - fn new(bytes: usize) -> Budget { - Budget(std::cell::Cell::new(bytes)) - } - /// Take `bytes` (None: a size that overflowed) from the budget, or fail the import before - /// anything that large is allocated. - fn take(&self, bytes: Option, what: &str) -> Result<()> { - let left = self.0.get(); - match bytes.filter(|&b| b <= left) { - Some(b) => { - self.0.set(left - b); - Ok(()) - } - None => Err(perr(format!("FBX: {what} would take the import past its {} MiB memory limit", MAX_IMPORT_BYTES >> 20))), - } - } -} - -/// Bytes a mesh keeps. -fn mesh_bytes(m: &Mesh) -> Option { - m.primitives.iter().try_fold(0usize, |acc, p| { - let n = p.positions.len().checked_mul(12)?.checked_add(p.normals.len().checked_mul(12)?)?.checked_add(p.uvs.len().checked_mul(8)?)?; - let n = n.checked_add(p.tangents.len().checked_mul(16)?)?.checked_add(p.joints.len().checked_mul(8)?)?.checked_add(p.weights.len().checked_mul(16)?)?; - acc.checked_add(n)?.checked_add(p.indices.len().checked_mul(4)?) - }) -} - -/// Bytes the values under `nodes` keep. Used for ASCII files, which hold array elements as -/// one `Prop` each and are parsed before they can be counted (the text itself bounds them). -fn value_bytes(nodes: &[FbxNode]) -> Option { - nodes.iter().try_fold(0usize, |acc, n| { - let own = n.props.iter().try_fold(0usize, |a, p| { - let extra = match p { - Prop::Ints(v) => v.len().checked_mul(8)?, - Prop::Floats(v) => v.len().checked_mul(8)?, - Prop::Str(v) => v.len(), - Prop::Bytes(v) => v.len(), - Prop::Int(_) | Prop::Float(_) => 0, - }; - a.checked_add(std::mem::size_of::())?.checked_add(extra) - })?; - acc.checked_add(own)?.checked_add(value_bytes(&n.children)?) - }) -} - -/// One property value of an FBX node. -#[derive(Clone, Debug, PartialEq)] -pub enum Prop { - Int(i64), - Float(f64), - Str(String), - Bytes(Vec), - Ints(Vec), - Floats(Vec), -} - -impl Prop { - fn as_f64(&self) -> Option { - match self { - Prop::Int(i) => Some(*i as f64), - Prop::Float(f) => Some(*f), - _ => None, - } - } - fn as_i64(&self) -> Option { - match self { - Prop::Int(i) => Some(*i), - Prop::Float(f) if f.is_finite() => Some(*f as i64), - _ => None, - } - } - fn as_str(&self) -> Option<&str> { - match self { - Prop::Str(s) => Some(s), - _ => None, - } - } -} - -/// A node of the FBX document tree (the same for binary and ASCII files). -#[derive(Clone, Debug, Default, PartialEq)] -pub struct FbxNode { - pub name: String, - pub props: Vec, - pub children: Vec, -} - -impl FbxNode { - pub fn child(&self, name: &str) -> Option<&FbxNode> { - self.children.iter().find(|c| c.name == name) - } - pub fn children_named<'a>(&'a self, name: &'a str) -> impl Iterator + 'a { - self.children.iter().filter(move |c| c.name == name) - } - fn prop(&self, i: usize) -> Option<&Prop> { - self.props.get(i) - } - fn str_at(&self, i: usize) -> Option<&str> { - self.prop(i).and_then(Prop::as_str) - } - /// The node's array as floats: a binary array property, an ASCII `a:` child, or the plain - /// value list. - pub fn floats(&self) -> Vec { - if let Some(a) = self.child("a") { - return a.floats(); - } - let mut out = vec![]; - for p in &self.props { - match p { - Prop::Floats(v) => out.extend_from_slice(v), - Prop::Ints(v) => out.extend(v.iter().map(|&i| i as f64)), - Prop::Int(i) => out.push(*i as f64), - Prop::Float(f) => out.push(*f), - _ => {} - } - } - out - } - /// The node's array as integers (see [`FbxNode::floats`]). - pub fn ints(&self) -> Vec { - if let Some(a) = self.child("a") { - return a.ints(); - } - let mut out = vec![]; - for p in &self.props { - match p { - Prop::Ints(v) => out.extend_from_slice(v), - Prop::Floats(v) => out.extend(v.iter().filter(|f| f.is_finite()).map(|&f| f as i64)), - p => out.extend(p.as_i64()), - } - } - out - } -} - -/// Read an FBX file (binary or ASCII) into its top-level nodes and the file version -/// (e.g. 7400). -pub fn read(bytes: &[u8]) -> Result<(u32, Vec)> { - read_within(bytes, &Budget::new(MAX_IMPORT_BYTES)) -} - -fn read_within(bytes: &[u8], budget: &Budget) -> Result<(u32, Vec)> { - if bytes.starts_with(BINARY_MAGIC) { - read_binary(bytes, budget) - } else { - let (version, nodes) = read_ascii(&String::from_utf8_lossy(bytes))?; - budget.take(value_bytes(&nodes), "its values")?; - Ok((version, nodes)) - } -} - -// --------------------------------------------------------------------------------------------- -// Binary - -struct Bin<'a> { - d: &'a [u8], - /// 64-bit record offsets (version 7500 and later). - wide: bool, - budget: &'a Budget, -} - -impl Bin<'_> { - fn take(&self, pos: &mut usize, n: usize) -> Result<&[u8]> { - let end = pos.checked_add(n).ok_or_else(|| perr("FBX: offset overflow"))?; - let s = self.d.get(*pos..end).ok_or_else(|| perr(format!("FBX: truncated at byte {pos}")))?; - *pos = end; - Ok(s) - } - fn arr(&self, pos: &mut usize) -> Result<[u8; N]> { - let s = self.take(pos, N)?; - let mut a = [0u8; N]; - a.copy_from_slice(s); - Ok(a) - } - fn u32(&self, pos: &mut usize) -> Result { - Ok(u32::from_le_bytes(self.arr(pos)?)) - } - fn offset(&self, pos: &mut usize) -> Result { - if self.wide { Ok(u64::from_le_bytes(self.arr(pos)?)) } else { Ok(self.u32(pos)? as u64) } - } - fn to_usize(v: u64) -> Result { - usize::try_from(v).map_err(|_| perr("FBX: offset out of range")) - } - - /// Records until `end` or a null record. - fn list(&self, pos: &mut usize, end: usize, depth: usize) -> Result> { - if depth > MAX_DEPTH { - return Err(perr("FBX: nodes nested too deeply")); - } - let mut out = vec![]; - while *pos < end { - match self.record(pos, end, depth)? { - Some(n) => out.push(n), - None => break, - } - } - Ok(out) - } - - /// One node record ending within `limit` (the enclosing record's end); `None` for the null - /// record that closes a list. - fn record(&self, pos: &mut usize, limit: usize, depth: usize) -> Result> { - let start = *pos; - let end = Self::to_usize(self.offset(pos)?)?; - let nprops = self.offset(pos)?; - let plen = Self::to_usize(self.offset(pos)?)?; - let nlen = self.arr::<1>(pos)?[0] as usize; - if end == 0 && nprops == 0 && plen == 0 && nlen == 0 { - return Ok(None); - } - // A child reaching past its parent would be parsed again once the parent's end is - // restored. - if end <= start || end > limit.min(self.d.len()) { - return Err(perr(format!("FBX: bad record end {end} at byte {start}"))); - } - let name = String::from_utf8_lossy(self.take(pos, nlen)?).into_owned(); - let pstart = *pos; - let pend = pstart.checked_add(plen).filter(|&e| e <= end).ok_or_else(|| perr(format!("FBX: `{name}`: property list past the record")))?; - // Every property is at least one byte, so a count above the list length is corrupt. - if nprops > plen as u64 { - return Err(perr(format!("FBX: `{name}`: {nprops} properties in {plen} bytes"))); - } - let mut props = Vec::with_capacity(nprops as usize); - for _ in 0..nprops { - props.push(self.prop(pos, pend)?); - } - *pos = pend; - let children = if *pos < end { self.list(pos, end, depth + 1)? } else { vec![] }; - *pos = end; - Ok(Some(FbxNode { name, props, children })) - } - - fn prop(&self, pos: &mut usize, pend: usize) -> Result { - let sub = Bin { d: self.d.get(..pend).ok_or_else(|| perr("FBX: truncated property"))?, wide: self.wide, budget: self.budget }; - let t = sub.arr::<1>(pos)?[0]; - Ok(match t { - b'Y' => Prop::Int(i16::from_le_bytes(sub.arr(pos)?) as i64), - b'C' => Prop::Int((sub.arr::<1>(pos)?[0] != 0) as i64), - b'I' => Prop::Int(i32::from_le_bytes(sub.arr(pos)?) as i64), - b'L' => Prop::Int(i64::from_le_bytes(sub.arr(pos)?)), - b'F' => Prop::Float(f32::from_le_bytes(sub.arr(pos)?) as f64), - b'D' => Prop::Float(f64::from_le_bytes(sub.arr(pos)?)), - b'S' => { - let n = sub.u32(pos)? as usize; - Prop::Str(object_name(sub.take(pos, n)?)) - } - b'R' => { - let n = sub.u32(pos)? as usize; - Prop::Bytes(sub.take(pos, n)?.to_vec()) - } - b'f' | b'd' | b'l' | b'i' | b'b' => { - let len = sub.u32(pos)? as usize; - let enc = sub.u32(pos)?; - let clen = sub.u32(pos)? as usize; - let size = match t { - b'd' | b'l' => 8, - b'f' | b'i' => 4, - _ => 1, - }; - let want = len.checked_mul(size).filter(|&n| n <= MAX_ARRAY_BYTES).ok_or_else(|| perr("FBX: array too large"))?; - // Elements are kept as f64/i64 (booleans and 32-bit values widen), so the budget - // is charged for what is kept, not for the wire bytes. - sub.budget.take(len.checked_mul(8), "an array")?; - let data = sub.take(pos, clen)?; - let raw = match enc { - 0 => data.to_vec(), - // The status only: the error's Debug form prints what was decompressed. - 1 => miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(data, want).map_err(|e| perr(format!("FBX: array zlib: {:?}", e.status)))?, - e => return Err(perr(format!("FBX: unknown array encoding {e}"))), - }; - let raw = raw.get(..want).ok_or_else(|| perr("FBX: array shorter than its length"))?; - match t { - b'f' => Prop::Floats(raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect()), - b'd' => Prop::Floats(raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect()), - b'l' => Prop::Ints(raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c)).collect()), - b'i' => Prop::Ints(raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as i64).collect()), - _ => Prop::Ints(raw.iter().map(|&b| (b != 0) as i64).collect()), - } - } - t => return Err(perr(format!("FBX: unknown property type 0x{t:02x}"))), - }) - } -} - -/// Binary object names are `Name\0\x01Class`; ASCII writes `Class::Name`. -fn object_name(b: &[u8]) -> String { - let s = String::from_utf8_lossy(b); - match s.split_once("\0\x01") { - Some((name, class)) => format!("{class}::{name}"), - None => s.into_owned(), - } -} - -fn read_binary(bytes: &[u8], budget: &Budget) -> Result<(u32, Vec)> { - let mut pos = BINARY_MAGIC.len(); - let version = Bin { d: bytes, wide: false, budget }.u32(&mut pos)?; - let bin = Bin { d: bytes, wide: version >= 7500, budget }; - let mut nodes = vec![]; - while pos < bytes.len() { - match bin.record(&mut pos, bytes.len(), 0) { - Ok(Some(n)) => nodes.push(n), - Ok(None) => break, - // A damaged tail (footer, padding) after complete sections is ignored. - Err(_) if nodes.iter().any(|n| n.name == "Objects") => break, - Err(e) => return Err(e), - } - } - Ok((version, nodes)) -} - -// --------------------------------------------------------------------------------------------- -// ASCII - -#[derive(Clone, Debug, PartialEq)] -enum Tok { - Key(String), - Val(Prop), - /// `*N` array length (the values follow in an `a:` child). - Count, - Comma, - Open, - Close, -} - -fn tokenize(text: &str) -> Vec { - let mut out = vec![]; - let mut it = text.char_indices().peekable(); - while let Some(&(i, c)) = it.peek() { - match c { - c if c.is_whitespace() => { - it.next(); - } - ';' => { - for (_, c) in it.by_ref() { - if c == '\n' { - break; - } - } - } - ',' => { - it.next(); - out.push(Tok::Comma); - } - '{' => { - it.next(); - out.push(Tok::Open); - } - '}' => { - it.next(); - out.push(Tok::Close); - } - '"' => { - it.next(); - let start = i + 1; - let mut end = text.len(); - for (j, c) in it.by_ref() { - if c == '"' { - end = j; - break; - } - } - out.push(Tok::Val(Prop::Str(text.get(start..end).unwrap_or("").replace(""", "\"")))); - } - _ => { - let start = i; - let mut end = text.len(); - while let Some(&(j, c)) = it.peek() { - if c.is_whitespace() || matches!(c, ',' | '{' | '}' | '"' | ';' | ':') { - end = j; - break; - } - it.next(); - } - let word = text.get(start..end).unwrap_or(""); - if it.peek().is_some_and(|&(_, c)| c == ':') { - it.next(); - out.push(Tok::Key(word.to_string())); - } else if word.starts_with('*') { - out.push(Tok::Count); - } else if let Ok(i) = word.parse::() { - out.push(Tok::Val(Prop::Int(i))); - } else if let Ok(f) = word.parse::() { - out.push(Tok::Val(Prop::Float(f))); - } else if !word.is_empty() { - out.push(Tok::Val(Prop::Str(word.to_string()))); - } else { - // A stray `:` with no key. - it.next(); - } - } - } - } - out -} - -fn ascii_list(toks: &[Tok], i: &mut usize, depth: usize) -> Result> { - if depth > MAX_DEPTH { - return Err(perr("FBX: nodes nested too deeply")); - } - let mut out = vec![]; - while let Some(t) = toks.get(*i) { - *i += 1; - match t { - Tok::Close if depth > 0 => return Ok(out), - Tok::Key(name) => { - let mut node = FbxNode { name: name.clone(), ..FbxNode::default() }; - loop { - match toks.get(*i) { - Some(Tok::Val(v)) => node.props.push(v.clone()), - Some(Tok::Count | Tok::Comma) => {} - _ => break, - } - *i += 1; - } - if toks.get(*i) == Some(&Tok::Open) { - *i += 1; - node.children = ascii_list(toks, i, depth + 1)?; - } - out.push(node); - } - _ => {} - } - } - Ok(out) -} - -fn read_ascii(text: &str) -> Result<(u32, Vec)> { - let toks = tokenize(text); - let mut i = 0; - let nodes = ascii_list(&toks, &mut i, 0)?; - let version = nodes - .iter() - .find(|n| n.name == "FBXHeaderExtension") - .and_then(|h| h.child("FBXVersion")) - .and_then(|v| v.prop(0)) - .and_then(Prop::as_i64) - .and_then(|v| u32::try_from(v).ok()) - .unwrap_or(0); - Ok((version, nodes)) -} - -// --------------------------------------------------------------------------------------------- -// Scene - -/// `Properties70` entries by name (`P: name, type, label, flags, values…`). -struct Props70<'a>(HashMap<&'a str, &'a FbxNode>); - -impl<'a> Props70<'a> { - fn of(node: &'a FbxNode) -> Props70<'a> { - let mut m = HashMap::new(); - if let Some(p) = node.child("Properties70") { - for e in p.children_named("P") { - if let Some(name) = e.str_at(0) { - m.entry(name).or_insert(e); - } - } - } - Props70(m) - } - fn values(&self, name: &str) -> Vec { - self.0.get(name).map(|e| e.props.iter().skip(4).filter_map(Prop::as_f64).collect()).unwrap_or_default() - } - fn f(&self, name: &str) -> Option { - self.values(name).first().copied().filter(|v| v.is_finite()) - } - fn v3(&self, name: &str, default: [f64; 3]) -> [f64; 3] { - match self.values(name).as_slice() { - [x, y, z, ..] if x.is_finite() && y.is_finite() && z.is_finite() => [*x, *y, *z], - _ => default, - } - } -} - -/// An Euler rotation (degrees) in FBX rotation order (`eEulerXYZ` = 0 rotates about X first). -fn euler(d: [f64; 3], order: i64) -> Mat4 { - let (x, y, z) = (Mat4::rotate_x(d[0]), Mat4::rotate_y(d[1]), Mat4::rotate_z(d[2])); - match order { - 1 => y * z * x, - 2 => x * z * y, - 3 => z * x * y, - 4 => y * x * z, - 5 => x * y * z, - _ => z * y * x, - } -} - -fn translate(t: [f64; 3]) -> Mat4 { - Mat4::translate(vec3(t[0], t[1], t[2])) -} - -/// A Model's local transform: `T · Roff · Rp · Rpre · R · Rpost⁻¹ · Rp⁻¹ · Soff · Sp · S · Sp⁻¹`. -fn model_local(p: &Props70) -> Mat4 { - let order = p.f("RotationOrder").map_or(0, |o| o as i64); - let active = p.f("RotationActive").is_some_and(|a| a != 0.0); - let (pre, post) = - if active { (euler(p.v3("PreRotation", [0.0; 3]), 0), euler(p.v3("PostRotation", [0.0; 3]), 0).transpose()) } else { (Mat4::IDENTITY, Mat4::IDENTITY) }; - let rp = p.v3("RotationPivot", [0.0; 3]); - let sp = p.v3("ScalingPivot", [0.0; 3]); - let s = p.v3("Lcl Scaling", [1.0; 3]); - translate(p.v3("Lcl Translation", [0.0; 3])) - * translate(p.v3("RotationOffset", [0.0; 3])) - * translate(rp) - * pre - * euler(p.v3("Lcl Rotation", [0.0; 3]), order) - * post - * translate([-rp[0], -rp[1], -rp[2]]) - * translate(p.v3("ScalingOffset", [0.0; 3])) - * translate(sp) - * Mat4::scale(vec3(s[0], s[1], s[2])) - * translate([-sp[0], -sp[1], -sp[2]]) -} - -/// The geometric transform of a Model (applies to its geometry, not to its children). -fn geometric(p: &Props70) -> Option { - let t = p.v3("GeometricTranslation", [0.0; 3]); - let r = p.v3("GeometricRotation", [0.0; 3]); - let s = p.v3("GeometricScaling", [1.0; 3]); - if t == [0.0; 3] && r == [0.0; 3] && s == [1.0; 3] { - return None; - } - Some(translate(t) * euler(r, 0) * Mat4::scale(vec3(s[0], s[1], s[2]))) -} - -/// The file's axis system → +Y up, +Z front, +X right. -fn axis_matrix(settings: Option<&FbxNode>) -> Mat4 { - let p = settings.map(Props70::of); - let get = |name: &str, d: f64| p.as_ref().and_then(|p| p.f(name)).unwrap_or(d); - let axis = |a: f64, s: f64| -> Option<[f64; 4]> { - let a = a as i64; - let sign = if s < 0.0 { -1.0 } else { 1.0 }; - let mut v = [0.0; 4]; - *v.get_mut(usize::try_from(a).ok().filter(|&a| a < 3)?)? = sign; - Some(v) - }; - let (Some(right), Some(up), Some(front)) = ( - axis(get("CoordAxis", 0.0), get("CoordAxisSign", 1.0)), - axis(get("UpAxis", 1.0), get("UpAxisSign", 1.0)), - axis(get("FrontAxis", 2.0), get("FrontAxisSign", 1.0)), - ) else { - return Mat4::IDENTITY; - }; - let m = Mat4([right, up, front, [0.0, 0.0, 0.0, 1.0]]); - // Two axes on the same file axis: not a rotation. - let used = |k: usize| right[k] != 0.0 || up[k] != 0.0 || front[k] != 0.0; - if (0..3).all(used) { m } else { Mat4::IDENTITY } -} - -#[derive(Clone, Copy, PartialEq, Eq)] -enum Mapping { - PolygonVertex, - Vertex, - Polygon, - AllSame, -} - -/// A geometry layer element (normals, UVs, material indices). -struct LayerData { - mapping: Mapping, - data: Vec, - index: Option>, - width: usize, -} - -impl LayerData { - fn of(geom: &FbxNode, element: &str, data: &str, index: &str, width: usize) -> Option { - let e = geom.child(element)?; - let mapping = match e.child("MappingInformationType").and_then(|m| m.str_at(0)).unwrap_or("ByPolygonVertex") { - "ByPolygonVertex" => Mapping::PolygonVertex, - "ByVertex" | "ByVertice" | "ByControlPoint" => Mapping::Vertex, - "ByPolygon" => Mapping::Polygon, - "AllSame" => Mapping::AllSame, - _ => return None, - }; - let reference = e.child("ReferenceInformationType").and_then(|m| m.str_at(0)).unwrap_or("Direct"); - let index = (reference != "Direct").then(|| e.child(index).map(FbxNode::ints)).flatten(); - Some(LayerData { mapping, data: e.child(data)?.floats(), index, width }) - } - fn get(&self, pv: usize, v: usize, poly: usize) -> Option<&[f64]> { - let i = match self.mapping { - Mapping::PolygonVertex => pv, - Mapping::Vertex => v, - Mapping::Polygon => poly, - Mapping::AllSame => 0, - }; - let j = match &self.index { - Some(ix) => usize::try_from(*ix.get(i)?).ok()?, - None => i, - }; - let a = j.checked_mul(self.width)?; - self.data.get(a..a.checked_add(self.width)?) - } -} - -fn f32s(s: &[f64]) -> [f32; N] { - let mut a = [0.0f32; N]; - for (o, v) in a.iter_mut().zip(s) { - *o = if v.is_finite() { *v as f32 } else { 0.0 }; - } - a -} - -/// A Mesh geometry with its polygons triangulated; `materials[k]` is the model-level material -/// index of the geometry's material slot `k`. -fn build_mesh(name: &str, geom: &FbxNode, materials: &[usize], with_normal_maps: &dyn Fn(usize) -> bool) -> Option { - let positions: Vec<[f32; 3]> = geom.child("Vertices")?.floats().as_chunks::<3>().0.iter().map(|c| f32s::<3>(c)).collect(); - let pvi = geom.child("PolygonVertexIndex")?.ints(); - let normals = LayerData::of(geom, "LayerElementNormal", "Normals", "NormalsIndex", 3); - let uvs = LayerData::of(geom, "LayerElementUV", "UV", "UVIndex", 2); - let mats = geom.child("LayerElementMaterial").and_then(|e| { - let mapping = e.child("MappingInformationType").and_then(|m| m.str_at(0)).unwrap_or("AllSame"); - let ids = e.child("Materials")?.ints(); - Some((mapping == "ByPolygon", ids)) - }); - - type Key = (u32, [u32; 3], [u32; 2]); - let mut prims: Vec<(Option, Primitive, HashMap, Vec)> = vec![]; - let mut prim_of: HashMap, usize> = HashMap::new(); - let mut corners: Vec<(usize, usize)> = vec![]; - let mut poly = 0usize; - for (pv, &raw) in pvi.iter().enumerate() { - // The last corner of a polygon is stored as `-index - 1`. - let (v, last) = if raw < 0 { (!raw, true) } else { (raw, false) }; - corners.push((pv, usize::try_from(v).unwrap_or(usize::MAX))); - if !last { - continue; - } - let poly_corners = std::mem::take(&mut corners); - let p_index = poly; - poly += 1; - if poly_corners.len() < 3 || poly_corners.iter().any(|&(_, v)| v >= positions.len()) { - continue; - } - let slot = mats.as_ref().and_then(|(by_poly, ids)| { - let k = if *by_poly { *ids.get(p_index)? } else { *ids.first()? }; - materials.get(usize::try_from(k).ok()?).copied() - }); - let slot = slot.or_else(|| materials.first().copied()); - let at = *prim_of.entry(slot).or_insert_with(|| { - prims.push((slot, Primitive { material: slot, ..Default::default() }, HashMap::new(), vec![])); - prims.len() - 1 - }); - let Some((_, prim, map, need)) = prims.get_mut(at) else { continue }; - let mut ids = Vec::with_capacity(poly_corners.len()); - for &(pv, v) in &poly_corners { - let n = normals.as_ref().and_then(|l| l.get(pv, v, p_index)).map(f32s::<3>); - let t = uvs.as_ref().and_then(|l| l.get(pv, v, p_index)).map(f32s::<2>); - let key: Key = (v as u32, n.unwrap_or([f32::NAN; 3]).map(f32::to_bits), t.unwrap_or([f32::NAN; 2]).map(f32::to_bits)); - let id = *map.entry(key).or_insert_with(|| { - prim.positions.push(positions.get(v).copied().unwrap_or_default()); - prim.normals.push(n.unwrap_or_default()); - prim.uvs.push(t.unwrap_or_default()); - need.push(n.is_none()); - (prim.positions.len() - 1) as u32 - }); - ids.push(id); - } - for i in 2..ids.len() { - prim.indices.extend([ids[0], ids[i - 1], ids[i]]); - } - } - let mut mesh = Mesh { name: name.to_string(), primitives: vec![] }; - for (_, mut p, _, need) in prims { - if p.indices.is_empty() { - continue; - } - if need.iter().any(|&b| b) { - let given = p.normals.clone(); - p.compute_normals(); - for ((n, g), need) in p.normals.iter_mut().zip(given).zip(&need) { - if !need { - *n = g; - } - } - } - if uvs.is_none() { - p.uvs.clear(); - } else { - // FBX's v axis points up the image; textures are stored top row first. - for uv in p.uvs.iter_mut() { - uv[1] = 1.0 - uv[1]; - } - } - if p.material.is_some_and(with_normal_maps) { - p.compute_tangents(); - } - mesh.primitives.push(p); - } - (!mesh.primitives.is_empty()).then_some(mesh) -} - -/// Lambert/Phong surface properties onto metallic-roughness. -fn material(name: &str, node: &FbxNode) -> Material { - let p = Props70::of(node); - let phong = node.child("ShadingModel").and_then(|s| s.str_at(0)).is_some_and(|s| s.eq_ignore_ascii_case("phong")); - let factor = p.f("DiffuseFactor").unwrap_or(1.0); - let d = p.v3("DiffuseColor", p.v3("Diffuse", [0.8; 3])); - let alpha = match p.f("Opacity") { - Some(o) => o, - None => { - let tc = p.v3("TransparentColor", [0.0; 3]); - 1.0 - (tc[0] + tc[1] + tc[2]) / 3.0 * p.f("TransparencyFactor").unwrap_or(0.0) - } - } - .clamp(0.0, 1.0); - let lin = |c: f64| srgb_to_linear((c * factor).clamp(0.0, 1.0) as f32); - let e = p.v3("EmissiveColor", [0.0; 3]); - let ef = p.f("EmissiveFactor").unwrap_or(1.0); - let roughness = if phong { - let ns = p.f("ShininessExponent").or_else(|| p.f("Shininess")).unwrap_or(20.0).max(0.0); - (2.0 / (ns + 2.0)).sqrt() as f32 - } else { - 1.0 - }; - Material { - name: name.to_string(), - base_color: [lin(d[0]), lin(d[1]), lin(d[2]), alpha as f32], - metallic: 0.0, - roughness, - emissive: e.map(|c| srgb_to_linear((c * ef).clamp(0.0, 1.0) as f32)), - alpha_mode: if alpha < 0.999 { AlphaMode::Blend } else { AlphaMode::Opaque }, - ..Material::default() - } -} - -/// Decode standard base64 (ASCII FBX embeds `Video` content this way); `None` on bad input. -fn base64(s: &str) -> Option> { - let mut out = Vec::with_capacity(s.len() / 4 * 3); - let (mut acc, mut bits) = (0u32, 0u32); - for c in s.bytes() { - let v = match c { - b'A'..=b'Z' => c - b'A', - b'a'..=b'z' => c - b'a' + 26, - b'0'..=b'9' => c - b'0' + 52, - b'+' => 62, - b'/' => 63, - b'=' => break, - c if c.is_ascii_whitespace() => continue, - _ => return None, - }; - acc = (acc << 6) | v as u32; - bits += 6; - if bits >= 8 { - bits -= 8; - out.push((acc >> bits) as u8); - acc &= (1 << bits) - 1; - } - } - Some(out) -} - -fn short_name(full: &str) -> &str { - full.split_once("::").map_or(full, |(_, n)| n) -} - -/// Parse an FBX file into a model. `resolve(uri)` reads texture files next to it. +/// Parse an FBX file; `resolve(path)` reads texture files the file names but does not embed. pub fn parse(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>) -> Result { - parse_within(bytes, resolve, MAX_IMPORT_BYTES) -} - -/// [`parse`] keeping at most `limit` bytes of arrays and meshes. -fn parse_within(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>, limit: usize) -> Result { - let budget = Budget::new(limit); - let (version, doc) = read_within(bytes, &budget)?; - if version != 0 && version < 7000 { - return Err(ModelError::Unsupported(format!("FBX {}.{} (only FBX 7.x files are read)", version / 1000, version % 1000 / 100))); + let limits = limits(); + let doc = craft_mesh::fbx::read_document(bytes, &limits).map_err(error)?; + let mut textures = |path: &str| resolve(path); + let scene = doc.scene(&limits, &mut textures).map_err(error)?; + if scene.meshes.is_empty() { + return Err(ModelError::Parse("FBX file without meshes".into())); } - let top = |name: &str| doc.iter().find(|n| n.name == name); - let objects = top("Objects").ok_or_else(|| perr("FBX: no Objects section"))?; - let by_id: HashMap = objects.children.iter().filter_map(|o| Some((o.prop(0)?.as_i64()?, o))).collect(); - let kind = |id: i64| by_id.get(&id).map(|n| n.name.as_str()); - - // Connections: (child, parent, property) in file order. - let mut links: Vec<(i64, i64, Option<&str>)> = vec![]; - if let Some(c) = top("Connections") { - for e in c.children_named("C") { - let (Some(a), Some(b)) = (e.prop(1).and_then(Prop::as_i64), e.prop(2).and_then(Prop::as_i64)) else { continue }; - links.push((a, b, e.str_at(3))); - } + let mut m = to_model(scene, MissingNormals::Smooth, &|_| None)?; + // The axes node goes first: every node index moves up by one. + for n in &mut m.nodes { + n.children.iter_mut().for_each(|c| *c += 1); } - // The same links by parent, so each object finds its children without scanning them all. - let mut children_of: HashMap)>> = HashMap::new(); - for &(a, b, prop) in &links { - children_of.entry(b).or_default().push((a, prop)); - } - let children_of = |id: i64| children_of.get(&id).map(Vec::as_slice).unwrap_or_default().iter().copied(); - - let model_ids: Vec = objects.children.iter().filter(|o| o.name == "Model").filter_map(|o| o.prop(0)?.as_i64()).collect(); - let mut node_of: HashMap = HashMap::new(); - let mut nodes = vec![Node { name: "FBX axes".into(), matrix: Some(axis_matrix(top("GlobalSettings"))), ..Node::default() }]; - for &id in &model_ids { - if node_of.contains_key(&id) { - continue; - } - let Some(o) = by_id.get(&id) else { continue }; - let name = short_name(o.str_at(1).unwrap_or("")).to_string(); - node_of.insert(id, nodes.len()); - nodes.push(Node { name, matrix: Some(model_local(&Props70::of(o))), ..Node::default() }); - } - - // Hierarchy: the first Model→Model link is the parent; anything else hangs off the root. - let mut parent: HashMap = HashMap::new(); - for &(c, p, _) in &links { - if let (Some(&ci), Some(&pi)) = (node_of.get(&c), node_of.get(&p)) - && ci != pi - { - parent.entry(ci).or_insert(pi); - } - } - for i in 1..nodes.len() { - let p = parent.get(&i).copied().unwrap_or(0); - if let Some(n) = nodes.get_mut(p) { - n.children.push(i); - } - } - - // Materials (in first-use order) and their textures. - let mut materials: Vec = vec![]; - let mut textures: Vec> = vec![]; - let mut material_of: HashMap = HashMap::new(); - let mut texture_of: HashMap> = HashMap::new(); - // Decoded images by the source actually used (embedded Video id, else the resolved file - // name): Texture objects aliasing one image share its pixels instead of each keeping a copy. - let mut image_of: HashMap<(Option, String), Option> = HashMap::new(); - // Textures have their own allowance (pixels, as `Texture::decode_within` counts them); the - // memory budget is for the file's own records. - let mut texture_pixels_left = MAX_TEXTURE_IMPORT_PIXELS; - let mut warnings: Vec = vec![]; - // Ok(None): no usable image (the material goes untextured). Err: the memory budget ran out. - let mut load_texture = |tid: i64, textures: &mut Vec>| -> Result> { - if let Some(t) = texture_of.get(&tid) { - return Ok(*t); - } - let Some(tex) = by_id.get(&tid) else { - texture_of.insert(tid, None); - return Ok(None); - }; - let videos: Vec = children_of(tid).filter(|l| kind(l.0) == Some("Video")).map(|l| l.0).collect(); - let files: Vec = ["RelativeFilename", "FileName"].iter().filter_map(|k| Some(tex.child(k)?.str_at(0)?.replace('\\', "/"))).collect(); - let embedded = videos.iter().find_map(|&v| { - let content = by_id.get(&v)?.child("Content")?; - let bytes = match content.props.first()? { - Prop::Bytes(b) if !b.is_empty() => Some(b.clone()), - Prop::Str(_) => { - let s: String = content.props.iter().filter_map(Prop::as_str).collect(); - base64(&s).filter(|b| !b.is_empty()) - } - _ => None, - }?; - Some(((Some(v), String::new()), bytes)) - }); - let source = embedded.or_else(|| { - files.iter().find_map(|f| { - let g = resolve(f).map(|b| (f.clone(), b)).or_else(|| { - let base = f.rsplit('/').next()?; - Some((base.to_string(), resolve(base)?)) - })?; - Some(((None, g.0), g.1)) - }) - }); - let t = match source { - None => None, - Some((key, bytes)) => match image_of.get(&key) { - Some(i) => *i, - None => { - // Charge the decoded size before decoding, so a small file claiming huge - // dimensions is refused before its pixels are allocated. A texture past the - // limits is left out (the material goes untextured) and the import says so. - let loaded = Texture::dimensions(&bytes).and_then(|(w, h)| { - let pixels = u64::from(w) * u64::from(h); - if pixels > MAX_TEXTURE_PIXELS { - return Err(perr(format!("a {w}×{h} texture (at most {MAX_TEXTURE_PIXELS} pixels)"))); - } - if pixels > texture_pixels_left { - return Err(perr(format!("a {w}×{h} texture: the model's textures would hold more than {MAX_TEXTURE_IMPORT_PIXELS} pixels"))); - } - let t = Texture::decode(&bytes)?; - texture_pixels_left -= pixels; - Ok(t) - }); - let i = match loaded { - Ok(t) => { - textures.push(Arc::new(t)); - Some(textures.len() - 1) - } - Err(e) => { - log::warn!("model: FBX texture left out: {e}"); - warnings.push(format!("texture left out: {e}")); - None - } - }; - image_of.insert(key, i); - i - } - }, - }; - texture_of.insert(tid, t); - Ok(t) - }; - let mut material_index = |mid: i64, materials: &mut Vec, textures: &mut Vec>| -> Result> { - if let Some(&m) = material_of.get(&mid) { - return Ok(Some(m)); - } - let Some(node) = by_id.get(&mid) else { return Ok(None) }; - let mut m = material(short_name(node.str_at(1).unwrap_or("")), node); - for (tid, prop) in children_of(mid).filter(|l| kind(l.0) == Some("Texture")) { - let slot = match prop { - Some("DiffuseColor") => &mut m.base_color_tex, - Some("NormalMap") => &mut m.normal_tex, - Some("EmissiveColor") => &mut m.emissive_tex, - _ => continue, - }; - if slot.is_none() { - *slot = load_texture(tid, textures)?.map(|texture| TexRef { texture, uv_set: 0 }); - } - } - if m.emissive_tex.is_some() && m.emissive == [0.0; 3] { - m.emissive = [1.0; 3]; - } - materials.push(m); - material_of.insert(mid, materials.len() - 1); - Ok(Some(materials.len() - 1)) - }; - - // One mesh per Model with Mesh geometry (material slots are per Model). Models instancing the - // same geometry with the same materials share one mesh rather than each building a copy. - let mut meshes: Vec = vec![]; - let mut mesh_of: HashMap<(i64, Vec), usize> = HashMap::new(); - for &id in &model_ids { - let Some(&ni) = node_of.get(&id) else { continue }; - let Some(gid) = children_of(id).find(|l| kind(l.0) == Some("Geometry")).map(|l| l.0) else { continue }; - let Some(geom) = by_id.get(&gid) else { continue }; - let mut mats: Vec = vec![]; - for (mid, _) in children_of(id).filter(|l| kind(l.0) == Some("Material")) { - mats.extend(material_index(mid, &mut materials, &mut textures)?); - } - let name = nodes.get(ni).map(|n| n.name.clone()).unwrap_or_default(); - let mesh_index = match mesh_of.get(&(gid, mats.clone())) { - Some(&i) => i, - None => { - let normal_mapped: Vec = materials.iter().map(|m| m.normal_tex.is_some()).collect(); - let Some(mesh) = build_mesh(&name, geom, &mats, &|m| normal_mapped.get(m).copied().unwrap_or(false)) else { continue }; - budget.take(mesh_bytes(&mesh), &format!("mesh `{name}`"))?; - meshes.push(mesh); - mesh_of.insert((gid, mats), meshes.len() - 1); - meshes.len() - 1 - } - }; - let geo = by_id.get(&id).and_then(|o| geometric(&Props70::of(o))); - match geo { - Some(matrix) => { - nodes.push(Node { name: format!("{name} geometry"), matrix: Some(matrix), mesh: Some(mesh_index), ..Node::default() }); - let gi = nodes.len() - 1; - if let Some(n) = nodes.get_mut(ni) { - n.children.push(gi); - } - } - None => { - if let Some(n) = nodes.get_mut(ni) { - n.mesh = Some(mesh_index); - } - } - } - } - if meshes.is_empty() { - return Err(perr("FBX file without meshes")); - } - Ok(Model { meshes, nodes, roots: vec![0], materials, textures, warnings, ..Model::default() }) + m.skins.iter_mut().flat_map(|s| s.joints.iter_mut()).for_each(|j| *j += 1); + m.animations.iter_mut().flat_map(|a| a.channels.iter_mut()).for_each(|c| c.node += 1); + let roots = m.roots.iter().map(|r| r + 1).collect(); + m.nodes.insert(0, Node { name: "FBX axes".into(), matrix: Some(mat4(&doc.axes_to_y_up())), children: roots, ..Node::default() }); + m.roots = vec![0]; + Ok(m) } #[cfg(test)] diff --git a/crates/model/src/fbx/tests.rs b/crates/model/src/fbx/tests.rs index fcd34c4f0..399b16e2d 100644 --- a/crates/model/src/fbx/tests.rs +++ b/crates/model/src/fbx/tests.rs @@ -1,5 +1,5 @@ use super::*; -use crate::load; +use crate::{AlphaMode, load, vec3}; /// A Z-up scene: a Null parent with a mesh child (rotated, scaled, with a geometric offset) /// holding a quad and a triangle with a material each. @@ -131,116 +131,12 @@ fn check_scene(m: &Model) { assert!(close(lo, [8.0, 2.0, -2.0]) && close(hi, [10.0, 4.0, 0.0]), "{lo:?} {hi:?}"); } -/// A binary FBX of the same node tree (`a:` children become typed arrays). -fn write_binary(nodes: &[FbxNode], version: u32, compress: bool) -> Vec { - fn prop(out: &mut Vec, p: &Prop, compress: bool) { - let array = |out: &mut Vec, t: u8, len: usize, raw: Vec| { - out.push(t); - out.extend((len as u32).to_le_bytes()); - let data = if compress { miniz_oxide::deflate::compress_to_vec_zlib(&raw, 6) } else { raw }; - out.extend((compress as u32).to_le_bytes()); - out.extend((data.len() as u32).to_le_bytes()); - out.extend(data); - }; - match p { - Prop::Int(i) => match i32::try_from(*i) { - Ok(v) => { - out.push(b'I'); - out.extend(v.to_le_bytes()); - } - Err(_) => { - out.push(b'L'); - out.extend(i.to_le_bytes()); - } - }, - Prop::Float(f) => { - out.push(b'D'); - out.extend(f.to_le_bytes()); - } - Prop::Str(s) => { - let s = match s.split_once("::") { - Some((class, name)) => format!("{name}\0\x01{class}"), - None => s.clone(), - }; - out.push(b'S'); - out.extend((s.len() as u32).to_le_bytes()); - out.extend(s.as_bytes()); - } - Prop::Bytes(b) => { - out.push(b'R'); - out.extend((b.len() as u32).to_le_bytes()); - out.extend(b); - } - Prop::Ints(v) => array(out, b'i', v.len(), v.iter().flat_map(|&i| (i as i32).to_le_bytes()).collect()), - Prop::Floats(v) => array(out, b'd', v.len(), v.iter().flat_map(|f| f.to_le_bytes()).collect()), - } - } - fn record(out: &mut Vec, n: &FbxNode, wide: bool, compress: bool) { - let w = if wide { 8 } else { 4 }; - let start = out.len(); - out.extend(vec![0u8; 3 * w]); - out.push(n.name.len() as u8); - out.extend(n.name.as_bytes()); - let props = match n.child("a") { - Some(a) if a.props.iter().all(|p| matches!(p, Prop::Int(_))) => vec![Prop::Ints(a.ints())], - Some(a) => vec![Prop::Floats(a.floats())], - None => n.props.clone(), - }; - let pstart = out.len(); - for p in &props { - prop(out, p, compress); - } - let plen = out.len() - pstart; - let kids: Vec<&FbxNode> = n.children.iter().filter(|c| c.name != "a").collect(); - if !kids.is_empty() { - for k in kids { - record(out, k, wide, compress); - } - out.extend(vec![0u8; 3 * w + 1]); - } - let end = out.len(); - for (k, v) in [end, props.len(), plen].into_iter().enumerate() { - let at = start + k * w; - if wide { - out[at..at + 8].copy_from_slice(&(v as u64).to_le_bytes()); - } else { - out[at..at + 4].copy_from_slice(&(v as u32).to_le_bytes()); - } - } - } - let wide = version >= 7500; - let mut out = BINARY_MAGIC.to_vec(); - out.extend(version.to_le_bytes()); - for n in nodes { - record(&mut out, n, wide, compress); - } - out.extend(vec![0u8; if wide { 25 } else { 13 }]); - // Footer bytes after the closing null record. - out.extend([0xfa; 16]); - out -} - #[test] fn ascii_fbx_scene() { let m = load("scene.fbx", ASCII.as_bytes(), &|_| None).unwrap(); check_scene(&m); } -#[test] -fn binary_fbx_matches_ascii() { - let (_, doc) = read(ASCII.as_bytes()).unwrap(); - let ascii = parse(ASCII.as_bytes(), &|_| None).unwrap(); - for (version, compress) in [(7400, false), (7400, true), (7500, true)] { - let bin = write_binary(&doc, version, compress); - let (v, nodes) = read(&bin).unwrap(); - assert_eq!(v, version); - assert_eq!(nodes.iter().map(|n| n.name.as_str()).collect::>(), ["FBXHeaderExtension", "GlobalSettings", "Objects", "Connections"]); - // Found by its magic even without the extension. - let m = load("scene.bin", &bin, &|_| None).unwrap(); - assert_eq!(m, ascii, "version {version}, compressed {compress}"); - } -} - #[test] fn embedded_and_relative_textures() { let png = { @@ -291,91 +187,6 @@ fn b64(b: &[u8]) -> String { s } -#[test] -fn hostile_fbx_files_fail_cleanly() { - let (_, doc) = read(ASCII.as_bytes()).unwrap(); - let bin = write_binary(&doc, 7500, true); - // Every truncation and every single-byte corruption returns (no panic, no runaway). - for n in 0..bin.len() { - let _ = parse(&bin[..n], &|_| None); - } - for i in 0..bin.len() { - let mut b = bin.clone(); - b[i] ^= 0xff; - let _ = parse(&b, &|_| None); - } - // An array claiming 4 G elements. - let mut huge = BINARY_MAGIC.to_vec(); - huge.extend(7400u32.to_le_bytes()); - let body: Vec = b"d".iter().copied().chain(u32::MAX.to_le_bytes()).chain(0u32.to_le_bytes()).chain(8u32.to_le_bytes()).chain([0u8; 8]).collect(); - let start = huge.len(); - let end = start + 13 + 1 + body.len(); - huge.extend((end as u32).to_le_bytes()); - huge.extend(1u32.to_le_bytes()); - huge.extend((body.len() as u32).to_le_bytes()); - huge.push(1); - huge.push(b'V'); - huge.extend(body); - assert!(read(&huge).is_err()); - // Deep nesting, both encodings. - assert!(read("A: {".repeat(100_000).as_bytes()).is_err()); - // Not an FBX scene at all, an old FBX version, and a scene without meshes. - assert!(parse(b"\x00\x01garbage", &|_| None).is_err()); - let v6 = "FBXHeaderExtension: {\n FBXVersion: 6100\n}\nObjects: {\n}\n"; - assert!(matches!(parse(v6.as_bytes(), &|_| None), Err(ModelError::Unsupported(_)))); - assert!(parse(b"Objects: {\n Model: 1, \"Model::Empty\", \"Null\" {\n }\n}\n", &|_| None).is_err()); -} - -/// A version-7400 binary FBX holding one top-level node `A` with uncompressed arrays of type -/// `t` (`b'b'`, `b'i'`, `b'f'`, `b'd'`, `b'l'`) and `len` elements each. -fn binary_arrays(arrays: &[(u8, usize)]) -> Vec { - let mut props = vec![]; - for &(t, len) in arrays { - let size = match t { - b'd' | b'l' => 8, - b'f' | b'i' => 4, - _ => 1, - }; - props.push(t); - props.extend((len as u32).to_le_bytes()); - props.extend(0u32.to_le_bytes()); - props.extend(((len * size) as u32).to_le_bytes()); - props.extend(std::iter::repeat_n(1u8, len * size)); - } - let mut out = BINARY_MAGIC.to_vec(); - out.extend(7400u32.to_le_bytes()); - let end = out.len() + 13 + 1 + props.len(); - out.extend((end as u32).to_le_bytes()); - out.extend((arrays.len() as u32).to_le_bytes()); - out.extend((props.len() as u32).to_le_bytes()); - out.push(1); - out.push(b'A'); - out.extend(props); - out -} - -#[test] -fn fbx_arrays_are_charged_for_the_memory_they_keep() { - // A boolean array is one byte per element on the wire but eight once kept as `Prop::Ints`: - // the budget counts the eight (#1234). - let n = 10_000; - let bin = binary_arrays(&[(b'b', n)]); - assert!(read_within(&bin, &Budget::new(n * 8)).is_ok()); - let e = read_within(&bin, &Budget::new(n * 8 - 1)).unwrap_err(); - assert!(e.to_string().contains("memory limit"), "{e}"); - // 32-bit floats widen to f64 the same way. - assert!(read_within(&binary_arrays(&[(b'f', n)]), &Budget::new(n * 4)).is_err()); - // Several arrays each within the budget but not together. - let bin = binary_arrays(&[(b'i', n), (b'd', n), (b'b', n)]); - assert!(read_within(&bin, &Budget::new(n * 24)).is_ok()); - assert!(read_within(&bin, &Budget::new(n * 20)).is_err()); - // ASCII values count too. - let (_, doc) = read(ASCII.as_bytes()).unwrap(); - let values = value_bytes(&doc).unwrap(); - assert!(values > 45 * std::mem::size_of::(), "{values}"); - assert!(parse_within(ASCII.as_bytes(), &|_| None, values - 1).unwrap_err().to_string().contains("memory limit")); -} - /// [`ASCII`] with two more Models instancing its geometry: `Copy` with the same two materials, /// `Red only` with just the first. fn instanced_scene() -> String { @@ -401,27 +212,6 @@ fn fbx_models_instancing_one_geometry_share_its_mesh() { assert_eq!(mesh_of("Shape"), mesh_of("Copy"), "same geometry and materials: one mesh"); assert_ne!(mesh_of("Shape"), mesh_of("Red only"), "different materials: its own mesh"); assert_eq!(m.meshes.len(), 2); - // A budget with room for one copy of the geometry's mesh, but not three, still imports. - let one = parse(ASCII.as_bytes(), &|_| None).unwrap(); - let mesh = mesh_bytes(&one.meshes[0]).unwrap(); - let (_, doc) = read(instanced_scene().as_bytes()).unwrap(); - let values = value_bytes(&doc).unwrap(); - assert!(parse_within(instanced_scene().as_bytes(), &|_| None, values + 2 * mesh).is_ok()); - assert!(parse_within(instanced_scene().as_bytes(), &|_| None, values + mesh).is_err()); -} - -#[test] -fn binary_child_record_past_its_parent_is_an_error() { - let parent = FbxNode { name: "P".into(), props: vec![], children: vec![FbxNode { name: "C".into(), props: vec![], children: vec![] }] }; - let after = FbxNode { name: "Q".into(), props: vec![Prop::Int(1)], children: vec![] }; - let mut bin = write_binary(&[parent, after], 7400, false); - assert_eq!(read(&bin).unwrap().1.len(), 2); - // `P` starts after the magic and version; `C` after P's 12-byte header, name length and name. - let p = BINARY_MAGIC.len() + 4; - let p_end = u32::from_le_bytes(bin[p..p + 4].try_into().unwrap()); - let c = p + 14; - bin[c..c + 4].copy_from_slice(&(p_end + 1).to_le_bytes()); - assert!(read(&bin).unwrap_err().to_string().contains("bad record end")); } #[test] @@ -448,11 +238,6 @@ Connections: {"#; let m = parse(doc.as_bytes(), &resolve).unwrap(); assert_eq!(m.textures.len(), 1); assert!(m.materials.iter().all(|x| x.base_color_tex.map(|t| t.texture) == Some(0))); - // Textures have their own allowance: a tight record budget does not drop them. - let (_, nodes) = read(doc.as_bytes()).unwrap(); - let values = value_bytes(&nodes).unwrap(); - let mesh = mesh_bytes(&m.meshes[0]).unwrap(); - assert_eq!(parse_within(doc.as_bytes(), &resolve, values + mesh).unwrap().textures.len(), 1); assert!(m.warnings.is_empty()); } diff --git a/crates/model/src/gltf.rs b/crates/model/src/gltf.rs index d55c39455..68bc86764 100644 --- a/crates/model/src/gltf.rs +++ b/crates/model/src/gltf.rs @@ -1,738 +1,26 @@ -//! glTF 2.0 import, written from the Khronos glTF 2.0 specification. -//! -//! Supports `.gltf` (JSON with external `.bin`/image files or `data:` URIs) and `.glb` (binary -//! container: a JSON chunk and a BIN chunk). Imports the default scene's node hierarchy (TRS or -//! matrix), triangle primitives (`TRIANGLES`, `TRIANGLE_STRIP`, `TRIANGLE_FAN`) with POSITION, -//! NORMAL, TANGENT, TEXCOORD_0, JOINTS_0 and WEIGHTS_0, PBR metallic-roughness materials -//! (base colour, metallic-roughness, normal, occlusion and emissive textures; alpha modes; -//! double-sided; `KHR_materials_emissive_strength`, `KHR_materials_unlit`), embedded or -//! external PNG/JPEG images with sampler wrap modes, skins and animations (step, linear and -//! cubic-spline translation/rotation/scale), perspective and orthographic cameras, and -//! `KHR_lights_punctual` lights (directional, point, spot). Sparse accessors and morph targets -//! are ignored. +//! glTF 2.0 import (`.gltf` with external or embedded buffers, `.glb`), read with `craft-mesh` +//! (`craft_mesh::gltf`): meshes, PBR metallic-roughness materials, the node hierarchy, skins, +//! animations, cameras and `KHR_lights_punctual` lights. External buffers and images are read +//! through the caller's resolver by their percent-decoded URI. Primitives without normals get +//! flat normals (glTF 2.0 §3.7.2.1); normal-mapped ones get tangents from their UVs. -use std::collections::HashMap; -use std::{cell::Cell, sync::Arc}; +use crate::scene::{MissingNormals, error, limits, to_model}; +use crate::{Model, Result}; -use serde_json::Value; +pub use craft_mesh::base64_decode; +pub use craft_mesh::gltf::{split_glb, uri_decode}; -use crate::{ - AlphaMode, Animation, Channel, ChannelPath, Interp, MAX_IMPORT_TEXTURE_PIXELS, Mat4, Material, Mesh, Model, ModelError, Node, Primitive, Result, Skin, - TexRef, Texture, Wrap, perr, -}; - -const GLB_MAGIC: u32 = 0x4654_6C67; -const CHUNK_JSON: u32 = 0x4E4F_534A; -const CHUNK_BIN: u32 = 0x004E_4942; - -/// Split a GLB container into its JSON text and BIN chunk. -pub fn split_glb(b: &[u8]) -> Result<(&[u8], Option<&[u8]>)> { - let u32_at = |o: usize| -> Option { b.get(o..o + 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])) }; - if u32_at(0) != Some(GLB_MAGIC) { - return Err(perr("not a GLB file")); - } - if u32_at(4) != Some(2) { - return Err(ModelError::Unsupported(format!("GLB version {}", u32_at(4).unwrap_or(0)))); - } - let total = (u32_at(8).unwrap_or(0) as usize).min(b.len()); - let mut o = 12; - let mut json = None; - let mut bin = None; - while o + 8 <= total { - let len = u32_at(o).unwrap_or(0) as usize; - let ty = u32_at(o + 4).unwrap_or(0); - let past_end = || perr("GLB chunk runs past the end of the file"); - let end = (o + 8).checked_add(len).ok_or_else(past_end)?; - let data = b.get(o + 8..end).ok_or_else(past_end)?; - match ty { - CHUNK_JSON if json.is_none() => json = Some(data), - CHUNK_BIN if bin.is_none() => bin = Some(data), - _ => {} - } - o = end; - } - Ok((json.ok_or_else(|| perr("GLB without a JSON chunk"))?, bin)) -} - -/// Decode standard base64 (with or without padding; whitespace ignored). -pub fn base64_decode(s: &str) -> Option> { - let mut out = Vec::with_capacity(s.len() * 3 / 4); - let mut acc = 0u32; - let mut bits = 0; - for c in s.bytes() { - let v = match c { - b'A'..=b'Z' => c - b'A', - b'a'..=b'z' => c - b'a' + 26, - b'0'..=b'9' => c - b'0' + 52, - b'+' | b'-' => 62, - b'/' | b'_' => 63, - b'=' => break, - b' ' | b'\n' | b'\r' | b'\t' => continue, - _ => return None, - } as u32; - acc = (acc << 6) | v; - bits += 6; - if bits >= 8 { - bits -= 8; - out.push((acc >> bits) as u8); - acc &= (1 << bits) - 1; - } - } - Some(out) -} - -/// Percent-decode a relative URI. -pub fn uri_decode(s: &str) -> String { - let b = s.as_bytes(); - let mut out = Vec::with_capacity(b.len()); - let mut i = 0; - while i < b.len() { - if b[i] == b'%' - && i + 2 < b.len() - && b[i + 1].is_ascii_hexdigit() - && b[i + 2].is_ascii_hexdigit() - && let Ok(v) = u8::from_str_radix(std::str::from_utf8(&b[i + 1..i + 3]).unwrap_or("zz"), 16) - { - out.push(v); - i += 3; - continue; - } - out.push(b[i]); - i += 1; - } - String::from_utf8_lossy(&out).into_owned() -} - -/// Bytes of a `data:` URI or an external resource. -fn load_uri(uri: &str, resolve: &dyn Fn(&str) -> Option>) -> Result> { - if let Some(rest) = uri.strip_prefix("data:") { - let (meta, data) = rest.split_once(',').ok_or_else(|| perr("malformed data URI"))?; - return if meta.ends_with(";base64") { base64_decode(data).ok_or_else(|| perr("bad base64 in data URI")) } else { Ok(uri_decode(data).into_bytes()) }; - } - let name = uri_decode(uri); - resolve(&name).ok_or(ModelError::Missing(name)) -} - -struct Doc<'a> { - j: &'a Value, - buffers: Vec>, - /// Zero components that buffer-less accessors may still allocate, across the whole file: - /// nothing backs them, so many references to one capped accessor must not multiply (#2139). - zero_left: Cell, - /// Components every accessor read may still allocate, across the whole file: each primitive - /// that references an accessor keeps its own copy, so references must not multiply memory. - read_left: Cell, - /// The budget `read_left` started from, for the error message. - read_cap: usize, -} - -fn arr<'v>(v: &'v Value, k: &str) -> &'v [Value] { - v.get(k).and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]) -} -/// A non-negative integer field; one too large for `usize` counts as absent (#1235). -fn idx(v: &Value, k: &str) -> Option { - v.get(k).and_then(Value::as_u64).and_then(|x| usize::try_from(x).ok()) -} -/// Node indices in an array field (out-of-range ones are dropped). -fn indices(v: &Value, k: &str) -> Vec { - arr(v, k).iter().filter_map(Value::as_u64).filter_map(|c| usize::try_from(c).ok()).collect() -} - -/// The most components accessors without a buffer view (all zeros) may have, together: nothing -/// in the file backs their counts, so they are capped instead of checked against a buffer -/// (#1235, #2139). -const MAX_ZERO_COMPONENTS: usize = 1 << 24; - -/// The most components all accessor reads in one file may allocate together (about 1 GiB as -/// `f32`/`u32`). Each primitive keeps its own copy of what it reads, so an accessor referenced -/// N times costs N times; this bounds that by a fixed amount rather than by buffer size, because -/// real assets legitimately share one vertex buffer across many primitives. A 10M-triangle scan -/// (5M vertices with position, normal, UV and tangent, 30M indices) reads about 90M. -const MAX_READ_COMPONENTS: usize = 1 << 28; - -/// Where an accessor's elements lie in its buffer: `count` elements of `elem` bytes, `stride` -/// apart from `base`, all checked to be inside `buf`. -struct Span<'b> { - buf: &'b [u8], - base: usize, - stride: usize, -} -fn num(v: &Value, k: &str, d: f64) -> f64 { - v.get(k).and_then(Value::as_f64).unwrap_or(d) -} -fn nums(v: &Value, k: &str, d: [f64; N]) -> [f64; N] { - let mut out = d; - if let Some(a) = v.get(k).and_then(Value::as_array) { - for (i, x) in a.iter().take(N).enumerate() { - out[i] = x.as_f64().unwrap_or(d[i]); - } - } - out -} - -/// Bytes of component `c` of element `i`, with checked offsets (the span was validated, but -/// nothing derived from the file is indexed unchecked). -fn component(buf: &[u8], base: usize, stride: usize, i: usize, c: usize, csize: usize) -> Result<&[u8]> { - let o = i.checked_mul(stride).and_then(|o| o.checked_add(base)).and_then(|o| o.checked_add(c.checked_mul(csize)?)); - o.and_then(|o| buf.get(o..o.checked_add(csize)?)).ok_or_else(|| perr("accessor reads past its buffer")) -} - -impl Doc<'_> { - /// Charge `total` components to the file's read budget before allocating them. - fn charge(&self, total: usize) -> Result<()> { - let left = self.read_left.get(); - let Some(rest) = left.checked_sub(total) else { - let cap = self.read_cap; - return Err(perr(format!("accessor reads need more than {cap} components in total ({total} requested, {left} left)"))); - }; - self.read_left.set(rest); - Ok(()) - } - - /// Charge `count` items of `per` components each. - fn charge_each(&self, count: usize, per: usize) -> Result<()> { - self.charge(count.checked_mul(per).ok_or_else(|| perr("primitive is too large"))?) - } - - /// The accessor's element count and total components (`count * n`), checked; and its span in - /// the buffer, validated before anything is allocated from the count. `None` for an - /// accessor without a buffer view, whose components are all zero. - fn layout(&self, acc: &Value, n: usize, csize: usize) -> Result<(usize, usize, Option>)> { - let count = match acc.get("count") { - None => 0, - Some(c) => c.as_u64().and_then(|c| usize::try_from(c).ok()).ok_or_else(|| perr("accessor count is not a valid size"))?, - }; - let total = count.checked_mul(n).ok_or_else(|| perr("accessor count is too large"))?; - let Some(bv) = idx(acc, "bufferView") else { - let left = self.zero_left.get(); - let Some(rest) = left.checked_sub(total) else { - return Err(perr(format!("accessors without a bufferView have more than {MAX_ZERO_COMPONENTS} components ({total} requested, {left} left)"))); - }; - self.zero_left.set(rest); - self.charge(total)?; - return Ok((count, total, None)); - }; - let view = arr(self.j, "bufferViews").get(bv).ok_or_else(|| perr(format!("no bufferView {bv}")))?; - let buf = self.buffers.get(idx(view, "buffer").unwrap_or(0)).ok_or_else(|| perr("bufferView buffer out of range"))?; - let past = || perr("accessor reads past its buffer"); - let base = idx(view, "byteOffset").unwrap_or(0).checked_add(idx(acc, "byteOffset").unwrap_or(0)).ok_or_else(past)?; - let elem = csize.checked_mul(n).ok_or_else(past)?; - let stride = idx(view, "byteStride").filter(|s| *s > 0).unwrap_or(elem); - if stride < elem { - return Err(perr(format!("bufferView byteStride {stride} is smaller than its {elem}-byte elements"))); - } - if count > 0 { - let end = (count - 1).checked_mul(stride).and_then(|o| o.checked_add(base)).and_then(|o| o.checked_add(elem)).ok_or_else(past)?; - if end > buf.len() { - return Err(past()); - } - } - self.charge(total)?; - Ok((count, total, Some(Span { buf, base, stride }))) - } - - /// An accessor as `f32` rows of `n` components (normalised integers mapped to 0..1 / -1..1). - fn floats(&self, a: usize) -> Result<(Vec, usize)> { - let acc = arr(self.j, "accessors").get(a).ok_or_else(|| perr(format!("no accessor {a}")))?; - let n = match acc.get("type").and_then(Value::as_str).unwrap_or("") { - "SCALAR" => 1, - "VEC2" => 2, - "VEC3" => 3, - "VEC4" => 4, - "MAT2" => 4, - "MAT3" => 9, - "MAT4" => 16, - t => return Err(perr(format!("accessor type `{t}`"))), - }; - let ct = idx(acc, "componentType").unwrap_or(5126); - let norm = acc.get("normalized").and_then(Value::as_bool).unwrap_or(false); - let csize = match ct { - 5120 | 5121 => 1, - 5122 | 5123 => 2, - 5125 | 5126 => 4, - _ => return Err(perr(format!("componentType {ct}"))), - }; - let (count, total, span) = self.layout(acc, n, csize)?; - let mut out = vec![0.0f32; total]; - let Some(Span { buf, base, stride }) = span else { - // No buffer view: all zeros (sparse substitution is not supported). - return Ok((out, n)); - }; - // Matrices of 1/2-byte components pad columns to 4 bytes; ignored (rare). - for i in 0..count { - for c in 0..n { - let s = component(buf, base, stride, i, c, csize)?; - out[i * n + c] = match ct { - 5126 => f32::from_le_bytes([s[0], s[1], s[2], s[3]]), - 5125 => u32::from_le_bytes([s[0], s[1], s[2], s[3]]) as f32, - 5123 => { - let v = u16::from_le_bytes([s[0], s[1]]) as f32; - if norm { v / 65535.0 } else { v } - } - 5122 => { - let v = i16::from_le_bytes([s[0], s[1]]) as f32; - if norm { (v / 32767.0).max(-1.0) } else { v } - } - 5121 => { - let v = s[0] as f32; - if norm { v / 255.0 } else { v } - } - _ => { - let v = s[0] as i8 as f32; - if norm { (v / 127.0).max(-1.0) } else { v } - } - }; - } - } - Ok((out, n)) - } - - /// Integer accessor (indices, joints) read exactly. - fn ints(&self, a: usize) -> Result> { - let acc = arr(self.j, "accessors").get(a).ok_or_else(|| perr(format!("no accessor {a}")))?; - let ct = idx(acc, "componentType").unwrap_or(5125); - if ct == 5126 { - return Ok(self.floats(a)?.0.into_iter().map(|v| v as u32).collect()); - } - let n = match acc.get("type").and_then(Value::as_str).unwrap_or("SCALAR") { - "VEC4" => 4, - "VEC3" => 3, - "VEC2" => 2, - _ => 1, - }; - let csize = match ct { - 5120 | 5121 => 1, - 5122 | 5123 => 2, - _ => 4, - }; - let (count, total, span) = self.layout(acc, n, csize)?; - let Some(Span { buf, base, stride }) = span else { return Ok(vec![0; total]) }; - let mut out = Vec::with_capacity(total); - for i in 0..count { - for c in 0..n { - let s = component(buf, base, stride, i, c, csize)?; - out.push(match csize { - 1 => s[0] as u32, - 2 => u16::from_le_bytes([s[0], s[1]]) as u32, - _ => u32::from_le_bytes([s[0], s[1], s[2], s[3]]), - }); - } - } - Ok(out) - } -} - -/// Parse a `.gltf` (JSON) or `.glb` file. +/// Parse a `.gltf` (JSON) or `.glb` file; `resolve(uri)` reads external buffers and images. pub fn parse(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>) -> Result { - parse_with_budget(bytes, resolve, MAX_READ_COMPONENTS) -} - -/// [`parse`] with a read budget of `read_budget` accessor components for the whole file. -pub(crate) fn parse_with_budget(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>, read_budget: usize) -> Result { - let (json, bin) = if bytes.starts_with(b"glTF") { split_glb(bytes)? } else { (bytes, None) }; - let j: Value = serde_json::from_slice(json).map_err(|e| perr(format!("glTF JSON: {e}")))?; - let ver = j.get("asset").and_then(|a| a.get("version")).and_then(Value::as_str).unwrap_or(""); - if !ver.starts_with('2') { - return Err(ModelError::Unsupported(format!("glTF version `{ver}` (2.0 required)"))); - } - for ext in arr(&j, "extensionsRequired") { - let e = ext.as_str().unwrap_or(""); - if !matches!(e, "KHR_materials_unlit" | "KHR_materials_emissive_strength") { - return Err(ModelError::Unsupported(format!("required extension {e}"))); - } - } - let mut buffers = vec![]; - for (i, b) in arr(&j, "buffers").iter().enumerate() { - let data = match b.get("uri").and_then(Value::as_str) { - Some(u) => load_uri(u, resolve)?, - None if i == 0 => bin.map(<[u8]>::to_vec).ok_or_else(|| perr("buffer 0 has no uri and the file has no BIN chunk"))?, - None => vec![], - }; - buffers.push(data); - } - let d = Doc { j: &j, buffers, zero_left: Cell::new(MAX_ZERO_COMPONENTS), read_left: Cell::new(read_budget), read_cap: read_budget }; - - // Images → textures (decoded once per image; samplers set the wrap modes). - let mut images: Vec>> = vec![]; - // Images naming one source decode once, and all of them within one pixel budget. - let mut image_of: HashMap>> = HashMap::new(); - let mut pixels_left = MAX_IMPORT_TEXTURE_PIXELS; - let mut warnings: Vec = vec![]; - for (n, im) in arr(&j, "images").iter().enumerate() { - let (uri, view) = (im.get("uri").and_then(Value::as_str), idx(im, "bufferView")); - let key = match (uri, view) { - (Some(u), _) => format!("uri:{u}"), - (None, Some(bv)) => format!("bufferView:{bv}"), - (None, None) => { - images.push(None); - continue; - } - }; - let image = image_of.entry(key).or_insert_with(|| { - let data = if let Some(u) = uri { - load_uri(u, resolve).ok() - } else { - arr(&j, "bufferViews").get(view.unwrap_or(usize::MAX)).and_then(|v| { - let b = d.buffers.get(idx(v, "buffer").unwrap_or(0))?; - let o = idx(v, "byteOffset").unwrap_or(0); - b.get(o..o.checked_add(idx(v, "byteLength").unwrap_or(0))?).map(<[u8]>::to_vec) - }) - }; - match data.map(|b| Texture::decode_within(&b, &mut pixels_left)) { - Some(Ok(t)) => Some(Arc::new(t)), - Some(Err(e)) => { - log::warn!("model: glTF image {n} left out: {e}"); - warnings.push(format!("image {n} left out: {e}")); - None - } - None => None, - } - }); - images.push(image.clone()); - } - let wrap = |v: u64| match v { - 33071 => Wrap::Clamp, - 33648 => Wrap::Mirror, - _ => Wrap::Repeat, - }; - let mut textures: Vec> = vec![]; - let mut tex_map: Vec> = vec![]; - // One texture per decoded image and wrapping: repeated references share it instead of copying - // the pixels. The image is keyed by its allocation, so image entries naming the same file - // (which share one decode) also share their wrap variants. - let mut texture_of: HashMap<(usize, [Wrap; 2]), usize> = HashMap::new(); - for t in arr(&j, "textures") { - let Some(img) = idx(t, "source").and_then(|s| images.get(s).cloned().flatten()) else { - tex_map.push(None); - continue; - }; - let src = Arc::as_ptr(&img) as usize; - let samp = idx(t, "sampler").and_then(|s| arr(&j, "samplers").get(s)); - let ws = samp.and_then(|s| s.get("wrapS")).and_then(Value::as_u64).unwrap_or(10497); - let wt = samp.and_then(|s| s.get("wrapT")).and_then(Value::as_u64).unwrap_or(10497); - let w = [wrap(ws), wrap(wt)]; - let i = match texture_of.get(&(src, w)) { - Some(&i) => i, - None => { - let tex = if img.wrap == w { - img - } else { - // A wrap variant copies the pixels, so it is charged to the import budget too; - // one that does not fit is left out like an undecodable image. - let cost = u64::from(img.width) * u64::from(img.height); - if cost > pixels_left { - warnings.push(format!( - "a texture with another wrap mode left out: the model's textures would hold more than {MAX_IMPORT_TEXTURE_PIXELS} pixels" - )); - tex_map.push(None); - continue; - } - pixels_left -= cost; - Arc::new(Texture { wrap: w, ..(*img).clone() }) - }; - textures.push(tex); - texture_of.insert((src, w), textures.len() - 1); - textures.len() - 1 - } - }; - tex_map.push(Some(i)); - } - let tref = |v: Option<&Value>| -> Option { - let v = v?; - let t = tex_map.get(idx(v, "index")?).copied().flatten()?; - Some(TexRef { texture: t, uv_set: idx(v, "texCoord").unwrap_or(0) as u32 }) - }; - - let mut materials = vec![]; - for m in arr(&j, "materials") { - let pbr = m.get("pbrMetallicRoughness").cloned().unwrap_or(Value::Null); - let bc = nums(&pbr, "baseColorFactor", [1.0; 4]); - let ext = m.get("extensions"); - let strength = ext.and_then(|e| e.get("KHR_materials_emissive_strength")).map_or(1.0, |e| num(e, "emissiveStrength", 1.0)); - let em = nums(m, "emissiveFactor", [0.0; 3]); - materials.push(Material { - name: m.get("name").and_then(Value::as_str).unwrap_or("").to_string(), - base_color: bc.map(|v| v as f32), - base_color_tex: tref(pbr.get("baseColorTexture")), - metallic: num(&pbr, "metallicFactor", 1.0) as f32, - roughness: num(&pbr, "roughnessFactor", 1.0) as f32, - metallic_roughness_tex: tref(pbr.get("metallicRoughnessTexture")), - normal_tex: tref(m.get("normalTexture")), - normal_scale: m.get("normalTexture").map_or(1.0, |n| num(n, "scale", 1.0)) as f32, - occlusion_tex: tref(m.get("occlusionTexture")), - occlusion_strength: m.get("occlusionTexture").map_or(1.0, |n| num(n, "strength", 1.0)) as f32, - emissive: [(em[0] * strength) as f32, (em[1] * strength) as f32, (em[2] * strength) as f32], - emissive_tex: tref(m.get("emissiveTexture")), - alpha_mode: match m.get("alphaMode").and_then(Value::as_str) { - Some("MASK") => AlphaMode::Mask, - Some("BLEND") => AlphaMode::Blend, - _ => AlphaMode::Opaque, - }, - alpha_cutoff: num(m, "alphaCutoff", 0.5) as f32, - double_sided: m.get("doubleSided").and_then(Value::as_bool).unwrap_or(false), - unlit: ext.and_then(|e| e.get("KHR_materials_unlit")).is_some(), - }); - } - - let mut meshes = vec![]; - for m in arr(&j, "meshes") { - let mut mesh = Mesh { name: m.get("name").and_then(Value::as_str).unwrap_or("").to_string(), primitives: vec![] }; - for p in arr(m, "primitives") { - if let Some(prim) = primitive(&d, p, &materials)? { - mesh.primitives.push(prim); - } - } - meshes.push(mesh); - } - - let mut nodes = vec![]; - for n in arr(&j, "nodes") { - let matrix = n.get("matrix").and_then(Value::as_array).filter(|a| a.len() == 16).map(|a| { - // Column-major in the file. - let v: Vec = a.iter().map(|x| x.as_f64().unwrap_or(0.0)).collect(); - let mut m = [[0.0; 4]; 4]; - for c in 0..4 { - for r in 0..4 { - m[r][c] = v[c * 4 + r]; - } - } - Mat4(m) - }); - nodes.push(Node { - name: n.get("name").and_then(Value::as_str).unwrap_or("").to_string(), - translation: nums(n, "translation", [0.0; 3]), - rotation: nums(n, "rotation", [0.0, 0.0, 0.0, 1.0]), - scale: nums(n, "scale", [1.0; 3]), - matrix, - mesh: idx(n, "mesh").filter(|&m| m < meshes.len()), - skin: idx(n, "skin"), - camera: idx(n, "camera"), - light: n.get("extensions").and_then(|e| e.get("KHR_lights_punctual")).and_then(|e| idx(e, "light")), - children: indices(n, "children"), - }); - } - - let scene = idx(&j, "scene").unwrap_or(0); - let roots: Vec = match arr(&j, "scenes").get(scene) { - Some(s) => indices(s, "nodes"), - None => { - // No scene: every node that is nobody's child. - let mut child = vec![false; nodes.len()]; - for n in &nodes { - for &c in &n.children { - if c < child.len() { - child[c] = true; - } - } - } - (0..nodes.len()).filter(|&i| !child[i]).collect() - } - }; - - let mut skins = vec![]; - for s in arr(&j, "skins") { - let joints: Vec = indices(s, "joints"); - let inverse_bind = match idx(s, "inverseBindMatrices") { - Some(a) => { - let (f, _) = d.floats(a)?; - f.as_chunks::<16>() - .0 - .iter() - .map(|v| { - let mut m = [[0.0; 4]; 4]; - for c in 0..4 { - for r in 0..4 { - m[r][c] = v[c * 4 + r] as f64; - } - } - Mat4(m) - }) - .collect() - } - None => vec![Mat4::IDENTITY; joints.len()], - }; - skins.push(Skin { joints, inverse_bind }); - } - - let mut animations = vec![]; - for a in arr(&j, "animations") { - let samplers = arr(a, "samplers"); - let mut anim = Animation { name: a.get("name").and_then(Value::as_str).unwrap_or("").to_string(), channels: vec![] }; - for c in arr(a, "channels") { - let Some(t) = c.get("target") else { continue }; - let Some(node) = idx(t, "node") else { continue }; - let path = match t.get("path").and_then(Value::as_str) { - Some("translation") => ChannelPath::Translation, - Some("rotation") => ChannelPath::Rotation, - Some("scale") => ChannelPath::Scale, - _ => continue, - }; - let Some(s) = idx(c, "sampler").and_then(|s| samplers.get(s)) else { continue }; - let interp = match s.get("interpolation").and_then(Value::as_str) { - Some("STEP") => Interp::Step, - Some("CUBICSPLINE") => Interp::CubicSpline, - _ => Interp::Linear, - }; - let (Some(input), Some(output)) = (idx(s, "input"), idx(s, "output")) else { continue }; - let (times, _) = d.floats(input)?; - let (values, _) = d.floats(output)?; - anim.channels.push(Channel { node, path, interp, times, values }); - } - animations.push(anim); - } - - let cameras = arr(&j, "cameras").iter().enumerate().map(|(i, c)| camera(c, i)).collect(); - let lights = j - .get("extensions") - .and_then(|e| e.get("KHR_lights_punctual")) - .map(|e| arr(e, "lights").iter().enumerate().map(|(i, l)| light(l, i)).collect()) - .unwrap_or_default(); - Ok(Model { meshes, nodes, roots, materials, textures, skins, animations, cameras, lights, warnings }) -} - -fn name_or(v: &Value, d: String) -> String { - v.get("name").and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string).unwrap_or(d) -} - -/// A glTF camera (glTF 2.0 §5.12): `perspective` {yfov, aspectRatio?, znear} or -/// `orthographic` {xmag, ymag}. -fn camera(c: &Value, i: usize) -> crate::ModelCamera { - let projection = match (c.get("type").and_then(Value::as_str), c.get("orthographic")) { - (Some("orthographic"), Some(o)) => crate::CameraProjection::Orthographic { xmag: num(o, "xmag", 1.0), ymag: num(o, "ymag", 1.0) }, - _ => { - let p = c.get("perspective").cloned().unwrap_or(Value::Null); - crate::CameraProjection::Perspective { - yfov: num(&p, "yfov", 0.8).clamp(1e-3, 3.1), - aspect: p.get("aspectRatio").and_then(Value::as_f64), - znear: num(&p, "znear", 0.01), - } - } - }; - crate::ModelCamera { name: name_or(c, format!("Camera {}", i + 1)), projection } -} - -/// A `KHR_lights_punctual` light: type, color, intensity, range, spot cone angles. -fn light(l: &Value, i: usize) -> crate::ModelLight { - let kind = match l.get("type").and_then(Value::as_str) { - Some("directional") => crate::ModelLightKind::Directional, - Some("spot") => { - let s = l.get("spot").cloned().unwrap_or(Value::Null); - let outer = num(&s, "outerConeAngle", std::f64::consts::FRAC_PI_4).clamp(1e-3, std::f64::consts::FRAC_PI_2); - crate::ModelLightKind::Spot { inner: num(&s, "innerConeAngle", 0.0).clamp(0.0, outer), outer } - } - _ => crate::ModelLightKind::Point, - }; - crate::ModelLight { - name: name_or(l, format!("Light {}", i + 1)), - kind, - color: nums(l, "color", [1.0; 3]), - intensity: num(l, "intensity", 1.0).max(0.0), - range: l.get("range").and_then(Value::as_f64), - } -} - -fn primitive(d: &Doc, p: &Value, materials: &[Material]) -> Result> { - let mode = idx(p, "mode").unwrap_or(4); - if !matches!(mode, 4..=6) { - return Ok(None); - } - let attrs = p.get("attributes").ok_or_else(|| perr("primitive without attributes"))?; - let Some(pa) = idx(attrs, "POSITION") else { return Ok(None) }; - let (pos, _) = d.floats(pa)?; - let positions: Vec<[f32; 3]> = pos.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect(); - let n = positions.len(); - let vec3s = |a: Option| -> Result> { - Ok(match a { - Some(a) => d.floats(a)?.0.as_chunks::<3>().0.iter().map(|c| [c[0], c[1], c[2]]).collect(), - None => vec![], - }) - }; - let mut normals = vec3s(idx(attrs, "NORMAL"))?; - let uvs: Vec<[f32; 2]> = match idx(attrs, "TEXCOORD_0") { - Some(a) => d.floats(a)?.0.as_chunks::<2>().0.iter().map(|c| [c[0], c[1]]).collect(), - None => vec![], - }; - let tangents: Vec<[f32; 4]> = match idx(attrs, "TANGENT") { - Some(a) => d.floats(a)?.0.as_chunks::<4>().0.iter().map(|c| [c[0], c[1], c[2], c[3]]).collect(), - None => vec![], - }; - let joints: Vec<[u16; 4]> = match idx(attrs, "JOINTS_0") { - Some(a) => d.ints(a)?.as_chunks::<4>().0.iter().map(|c| [c[0] as u16, c[1] as u16, c[2] as u16, c[3] as u16]).collect(), - None => vec![], - }; - let weights: Vec<[f32; 4]> = match idx(attrs, "WEIGHTS_0") { - Some(a) => d.floats(a)?.0.as_chunks::<4>().0.iter().map(|c| [c[0], c[1], c[2], c[3]]).collect(), - None => vec![], - }; - let raw: Vec = match idx(p, "indices") { - Some(a) => d.ints(a)?, - None => { - // Generated indices are allocated like a read, once per referencing primitive. - d.charge(n)?; - (0..n as u32).collect() - } - }; - if raw.iter().any(|&i| i as usize >= n) { - return Err(perr("index out of range")); - } - let mut indices = Vec::with_capacity(raw.len()); - match mode { - 5 => { - for i in 2..raw.len() { - let (a, b, c) = (raw[i - 2], raw[i - 1], raw[i]); - if i % 2 == 0 { indices.extend([a, b, c]) } else { indices.extend([b, a, c]) } - } - } - 6 => { - for i in 2..raw.len() { - indices.extend([raw[0], raw[i - 1], raw[i]]); - } - } - _ => indices.extend(raw.as_chunks::<3>().0.iter().flatten()), - } - // The triangle list is kept besides the raw indices (a strip or fan of k indices becomes - // 3(k-2)), so it is charged like a read. - d.charge(indices.len())?; - if normals.len() != n { - normals.clear(); - } - let material = idx(p, "material").filter(|&m| m < materials.len()); - let skinned = joints.len() == n && weights.len() == n; - if normals.is_empty() { - // Flat normals unshare every vertex: position and normal, plus UVs and joints/weights. - let per = 6 + if uvs.len() == n { 2 } else { 0 } + if skinned { 8 } else { 0 }; - d.charge_each(indices.len(), per)?; - } - let mut prim = Primitive { - positions, - normals, - uvs: if uvs.len() == n { uvs } else { vec![] }, - tangents: if tangents.len() == n { tangents } else { vec![] }, - joints: if skinned { joints } else { vec![] }, - weights: if skinned { weights } else { vec![] }, - indices, - material, - }; - if prim.normals.is_empty() { - prim.flat_normals(); - prim.tangents.clear(); - } - let needs_tangents = material.is_some_and(|m| materials[m].normal_tex.is_some()); - if needs_tangents && prim.tangents.is_empty() { - d.charge_each(prim.positions.len(), 4)?; - prim.compute_tangents(); - } - Ok(Some(prim)) -} - -#[cfg(test)] -mod tests { - use super::uri_decode; - - #[test] - fn uri_decode_rejects_signed_hex_pair() { - assert_eq!(uri_decode("a%+1b"), "a%+1b"); - assert_eq!(uri_decode("a%-1b"), "a%-1b"); - assert_eq!(uri_decode("a%41b"), "aAb"); - } + let mut buffers = |uri: &str| resolve(uri); + let scene = craft_mesh::gltf::read(bytes, &limits(), &mut buffers).map_err(error)?; + to_model(scene, MissingNormals::Flat, &|im| { + let uri = im.uri.as_deref()?; + match uri.strip_prefix("data:") { + Some(_) => None, + // craft-mesh decodes external image URIs while constructing the scene. Decode only + // once here; a second pass changes literal percent escapes in valid filenames. + None => resolve(uri), + } + }) } diff --git a/crates/model/src/lib.rs b/crates/model/src/lib.rs index b95a9f487..0f25570eb 100644 --- a/crates/model/src/lib.rs +++ b/crates/model/src/lib.rs @@ -1,12 +1,14 @@ //! 3D models for the Advanced 3D renderer. //! -//! - [`gltf`]: glTF 2.0 import (`.gltf` with external or embedded buffers, `.glb`), written from -//! the Khronos glTF 2.0 specification: meshes, PBR metallic-roughness materials (base colour, -//! metallic-roughness, normal, occlusion and emissive maps), the node hierarchy, skins and -//! animations. +//! The file formats are read with `craft-mesh` (storytold/craft-libs); this crate maps its +//! scene onto [`Model`], decodes the textures and adds the normals and tangents a file leaves out. +//! +//! - [`gltf`]: glTF 2.0 import (`.gltf` with external or embedded buffers, `.glb`): meshes, PBR +//! metallic-roughness materials (base colour, metallic-roughness, normal, occlusion and +//! emissive maps), the node hierarchy, skins, animations, cameras and lights. //! - [`obj`]: Wavefront OBJ geometry with MTL materials (mapped onto the metallic-roughness model). //! - [`stl`]: STL meshes (binary and ASCII, with the binary per-facet and part colours). -//! - [`fbx`]: FBX 7.x scenes, binary and ASCII: meshes, the Model hierarchy, Lambert/Phong +//! - [`fbx`]: FBX 6.x and 7.x scenes, binary and ASCII: meshes, the Model hierarchy, Lambert/Phong //! materials and their textures. //! - [`prim`]: parametric primitives (cube, sphere, plane, torus, cone, cylinder). //! - [`extrude`]: extruded, bevelled meshes from 2D outlines (text and shape layers), with @@ -22,6 +24,7 @@ pub mod fbx; pub mod gltf; pub mod obj; pub mod prim; +mod scene; pub mod stl; pub mod triangulate; @@ -227,6 +230,9 @@ impl Primitive { if !self.uvs.is_empty() { p.uvs.push(self.uvs[i]); } + if !self.tangents.is_empty() { + p.tangents.push(self.tangents[i]); + } if !self.joints.is_empty() { p.joints.push(self.joints[i]); p.weights.push(self.weights[i]); diff --git a/crates/model/src/obj.rs b/crates/model/src/obj.rs index c9d364fc7..c305cf23f 100644 --- a/crates/model/src/obj.rs +++ b/crates/model/src/obj.rs @@ -1,33 +1,21 @@ -//! Wavefront OBJ geometry and MTL materials. +//! Wavefront OBJ geometry and MTL materials, read with `craft-mesh` (`craft_mesh::obj`). //! -//! OBJ: `v` (optional vertex colours ignored), `vt`, `vn`, `f` with `v`, `v/vt`, `v//vn`, -//! `v/vt/vn` references (negative = relative), polygons fan-triangulated, `o`/`g` groups, `s` -//! smoothing (normals computed per smoothing state when a face has none), `usemtl`, `mtllib`. -//! -//! MTL materials map onto metallic-roughness: `Kd` → base colour, `d`/`Tr` → alpha, `Ke` → -//! emissive, `Pr`/`Pm` (the PBR extension) → roughness/metallic, otherwise roughness from the -//! Phong exponent `Ns` (`sqrt(2 / (Ns + 2))`) and metallic 0; `map_Kd`, `map_Ke`, -//! `map_Bump`/`bump`/`norm` load base colour, emissive and normal textures. +//! The material library and the textures it names are read through the caller's resolver: a +//! texture is looked up by the name as written (a name containing spaces is one name), then by +//! its file name (an absolute path from another machine, #1274), then by the final token (the +//! options convention, `-bm 1 file.png`). Faces without normals get smooth normals within a +//! smoothing group and flat ones where smoothing is off. -use std::collections::{HashMap, HashSet}; -use std::sync::Arc; +use crate::scene::{MissingNormals, error, limits, to_model}; +use crate::{Model, Result}; -use crate::{AlphaMode, MAX_IMPORT_TEXTURE_PIXELS, Material, Mesh, Model, Primitive, Result, TexRef, Texture, perr}; +pub use craft_mesh::srgb_to_linear; -/// The last component of a referenced path, treating `\` as a separator too: a path from a -/// machine of another kind (`C:\textures\checker.png`) still finds `checker.png` next to the -/// model (#1274). `None` when the name carries no path at all. -fn sibling_name(name: &str) -> Option<&str> { - let file = name.rsplit(['/', '\\']).next()?; - (!file.is_empty() && file.len() < name.len()).then_some(file) -} - -/// A material reference resolved against the model's folder: the name as written (a name -/// containing spaces is one name), then its file name (an absolute path from another machine, -/// #1274), then the final token (the options convention, `-bm 1 file.png`). +/// A material reference resolved against the model's folder: the name as written, then its file +/// name, then the final token. fn resolve_reference(resolve: &dyn Fn(&str) -> Option>, name: &str) -> Option> { let mut tried: Vec<&str> = vec![]; - for candidate in [name, sibling_name(name).unwrap_or(name), name.split_whitespace().last().unwrap_or(name)] { + for candidate in [name, craft_mesh::obj::sibling_name(name).unwrap_or(name), name.split_whitespace().last().unwrap_or(name)] { if tried.contains(&candidate) { continue; } @@ -39,289 +27,11 @@ fn resolve_reference(resolve: &dyn Fn(&str) -> Option>, name: &str) -> O None } -/// The textures an OBJ import has decoded, by reference, and the pixels it may still decode. -pub struct TextureCache { - loaded: HashMap>, - pixels_left: u64, - /// Textures left out, for the user. - pub warnings: Vec, -} - -impl Default for TextureCache { - fn default() -> Self { - TextureCache { loaded: HashMap::new(), pixels_left: MAX_IMPORT_TEXTURE_PIXELS, warnings: vec![] } - } -} - -/// Parse MTL text into named materials (textures appended to `textures`, decoded once per -/// reference through `cache`). -pub fn parse_mtl(text: &str, resolve: &dyn Fn(&str) -> Option>, textures: &mut Vec>, cache: &mut TextureCache) -> Vec { - let mut out: Vec = vec![]; - let TextureCache { loaded, pixels_left, warnings } = cache; - let mut tex = |name: &str, textures: &mut Vec>| -> Option { - let key = name.trim().to_string(); - let t = *loaded.entry(key.clone()).or_insert_with(|| { - let Some(b) = resolve_reference(resolve, &key) else { - log::warn!("model: texture `{key}` was not found next to the model"); - warnings.push(format!("texture `{key}` was not found next to the model")); - return None; - }; - match Texture::decode_within(&b, pixels_left) { - Ok(t) => { - textures.push(Arc::new(t)); - Some(textures.len() - 1) - } - Err(e) => { - log::warn!("model: cannot decode texture `{key}`: {e}"); - warnings.push(format!("texture `{key}` left out: {e}")); - None - } - } - }); - t.map(|texture| TexRef { texture, uv_set: 0 }) - }; - let mut ns_seen = false; - let mut pr_seen = false; - for line in text.lines() { - let line = line.trim(); - let (key, rest) = line.split_once(char::is_whitespace).map(|(k, r)| (k, r.trim())).unwrap_or((line, "")); - let f3 = || -> [f32; 3] { - let v: Vec = rest.split_whitespace().filter_map(|x| x.parse().ok()).collect(); - match v.len() { - 0 => [0.0; 3], - 1 | 2 => [v[0]; 3], - _ => [v[0], v[1], v[2]], - } - }; - let f1 = || rest.split_whitespace().next().and_then(|x| x.parse::().ok()); - if key == "newmtl" { - if let Some(m) = out.last_mut() { - finish(m, ns_seen, pr_seen); - } - ns_seen = false; - pr_seen = false; - out.push(Material { name: rest.to_string(), metallic: 0.0, roughness: 0.5, ..Material::default() }); - continue; - } - let Some(m) = out.last_mut() else { continue }; - match key { - "Kd" => { - let c = f3(); - m.base_color = [srgb_to_linear(c[0]), srgb_to_linear(c[1]), srgb_to_linear(c[2]), m.base_color[3]]; - } - "Ke" => m.emissive = f3().map(srgb_to_linear), - "d" => m.base_color[3] = f1().unwrap_or(1.0), - "Tr" => m.base_color[3] = 1.0 - f1().unwrap_or(0.0), - "Ns" => { - let ns = f1().unwrap_or(0.0).max(0.0); - if !pr_seen { - m.roughness = (2.0 / (ns + 2.0)).sqrt(); - } - ns_seen = true; - } - "Pr" => { - m.roughness = f1().unwrap_or(0.5).clamp(0.0, 1.0); - pr_seen = true; - } - "Pm" => m.metallic = f1().unwrap_or(0.0).clamp(0.0, 1.0), - "map_Kd" => m.base_color_tex = tex(rest, textures), - "map_Ke" => { - m.emissive_tex = tex(rest, textures); - if m.emissive == [0.0; 3] { - m.emissive = [1.0; 3]; - } - } - "map_Bump" | "map_bump" | "bump" | "norm" => m.normal_tex = tex(rest, textures), - _ => {} - } - } - if let Some(m) = out.last_mut() { - finish(m, ns_seen, pr_seen); - } - out -} - -fn finish(m: &mut Material, _ns: bool, _pr: bool) { - if m.base_color[3] < 0.999 { - m.alpha_mode = AlphaMode::Blend; - } -} - -/// sRGB-encoded component → linear (MTL colours are display colours). -pub fn srgb_to_linear(c: f32) -> f32 { - if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) } -} - -#[derive(Clone, Copy, PartialEq, Eq, Hash)] -struct Key { - v: u32, - t: u32, - n: u32, - /// Smoothing state (faces without normals get computed normals per state). - s: u32, -} - -/// Parse OBJ text (and its MTL libraries through `resolve`). +/// Parse OBJ text (and its MTL libraries and textures through `resolve`). pub fn parse(bytes: &[u8], resolve: &dyn Fn(&str) -> Option>) -> Result { - let text = String::from_utf8_lossy(bytes); - let mut v: Vec<[f32; 3]> = vec![]; - let mut vt: Vec<[f32; 2]> = vec![]; - let mut vn: Vec<[f32; 3]> = vec![]; - let mut materials: Vec = vec![]; - let mut material_of: HashMap = HashMap::new(); - let mut textures: Vec> = vec![]; - let mut cache = TextureCache::default(); - let mut libraries: HashSet = HashSet::new(); - // One primitive per material, in order of first use. - let mut prims: Vec<(Option, Primitive, HashMap, Vec)> = vec![]; - let mut prim_of: HashMap, usize> = HashMap::new(); - let mut current: Option = None; - let mut smooth = 0u32; - let mut flat_id = 1u32 << 31; - let mut faces = 0usize; - // Join `\` line continuations. - let joined = text.replace("\\\r\n", " ").replace("\\\n", " "); - for (ln, line) in joined.lines().enumerate() { - let line = line.split('#').next().unwrap_or("").trim(); - if line.is_empty() { - continue; - } - let mut it = line.split_whitespace(); - let key = it.next().unwrap_or(""); - let rest: Vec<&str> = it.collect(); - let fl = |i: usize| rest.get(i).and_then(|x| x.parse::().ok()); - match key { - "v" => v.push([fl(0).unwrap_or(0.0), fl(1).unwrap_or(0.0), fl(2).unwrap_or(0.0)]), - "vt" => vt.push([fl(0).unwrap_or(0.0), fl(1).unwrap_or(0.0)]), - "vn" => vn.push([fl(0).unwrap_or(0.0), fl(1).unwrap_or(0.0), fl(2).unwrap_or(1.0)]), - "s" => { - smooth = match rest.first().copied() { - None | Some("off") | Some("0") => 0, - Some(x) => x.parse().unwrap_or(1).max(1), - } - } - "mtllib" => { - let name = line["mtllib".len()..].trim(); - // A library named again is already loaded. - if !libraries.insert(name.to_string()) { - continue; - } - let mut found = false; - for file in std::iter::once(name).chain(name.split_whitespace()).chain(sibling_name(name)) { - if let Some(b) = resolve(file) { - let ms = parse_mtl(&String::from_utf8_lossy(&b), resolve, &mut textures, &mut cache); - for m in ms { - material_of.entry(m.name.clone()).or_insert(materials.len()); - materials.push(m); - } - found = true; - break; - } - } - if !found && !name.is_empty() { - log::warn!("model: material library `{name}` was not found next to the model"); - } - } - "usemtl" => { - let name = line["usemtl".len()..].trim(); - current = Some(*material_of.entry(name.to_string()).or_insert_with(|| { - // Unknown material: a named grey default. - materials.push(Material { name: name.to_string(), metallic: 0.0, roughness: 0.5, base_color: [0.8, 0.8, 0.8, 1.0], ..Material::default() }); - materials.len() - 1 - })); - } - "f" => { - if rest.len() < 3 { - continue; - } - faces += 1; - let resolve_i = |s: &str, len: usize| -> Option { - if s.is_empty() { - return None; - } - let i: i64 = s.parse().ok()?; - let k = if i < 0 { len as i64 + i } else { i - 1 }; - (k >= 0 && (k as usize) < len).then_some(k as u32) - }; - let mut refs = vec![]; - for r in &rest { - let mut parts = r.split('/'); - let vi = resolve_i(parts.next().unwrap_or(""), v.len()).ok_or_else(|| perr(format!("line {}: bad vertex index `{r}`", ln + 1)))?; - let ti = parts.next().and_then(|s| resolve_i(s, vt.len())); - let ni = parts.next().and_then(|s| resolve_i(s, vn.len())); - refs.push((vi, ti, ni)); - } - let has_n = refs.iter().all(|r| r.2.is_some()); - // Faces without normals: shared within a smoothing group, unique otherwise. - let s = if has_n { - 0 - } else if smooth == 0 { - flat_id += 1; - flat_id - } else { - smooth - }; - let slot = *prim_of.entry(current).or_insert_with(|| { - prims.push((current, Primitive { material: current, ..Default::default() }, HashMap::new(), vec![])); - prims.len() - 1 - }); - let (_, prim, map, need) = &mut prims[slot]; - let mut ids = vec![]; - for (vi, ti, ni) in refs { - let k = Key { v: vi, t: ti.unwrap_or(u32::MAX), n: ni.unwrap_or(u32::MAX), s }; - let id = *map.entry(k).or_insert_with(|| { - prim.positions.push(v[vi as usize]); - prim.uvs.push(ti.map_or([0.0, 0.0], |t| vt[t as usize])); - prim.normals.push(ni.map_or([0.0; 3], |n| vn[n as usize])); - need.push(ni.is_none()); - (prim.positions.len() - 1) as u32 - }); - ids.push(id); - } - for i in 2..ids.len() { - prim.indices.extend([ids[0], ids[i - 1], ids[i]]); - } - } - _ => {} - } - } - if faces == 0 { - return Err(perr("OBJ file without faces")); - } - let any_uv = !vt.is_empty(); - let mut mesh = Mesh { name: String::new(), primitives: vec![] }; - for (_, mut p, _, need) in prims { - if need.iter().any(|&b| b) { - // Fill missing normals from the triangles (area weighted), keep given ones. - let given = p.normals.clone(); - p.compute_normals(); - for (i, n) in p.normals.iter_mut().enumerate() { - if !need[i] { - *n = given[i]; - } - } - } - if !any_uv { - p.uvs.clear(); - } else { - // OBJ's v axis points up the image; textures are stored top row first. - for uv in p.uvs.iter_mut() { - uv[1] = 1.0 - uv[1]; - } - } - if p.material.is_some_and(|m| materials[m].normal_tex.is_some()) { - p.compute_tangents(); - } - mesh.primitives.push(p); - } - let mut model = Model::single(mesh, materials).with_textures(textures); - model.warnings = cache.warnings; - Ok(model) -} - -impl Model { - fn with_textures(mut self, t: Vec>) -> Model { - self.textures = t; - self - } + // `craft-mesh` splits `mtllib` names and tries each complete library path itself. Applying + // texture-option fallback here first can mistake the last library for the whole directive. + let mut library = |name: &str| resolve(name); + let scene = craft_mesh::obj::read(bytes, &limits(), &mut library).map_err(error)?; + to_model(scene, MissingNormals::BySmoothing, &|im| resolve_reference(resolve, im.uri.as_deref()?.trim())) } diff --git a/crates/model/src/scene.rs b/crates/model/src/scene.rs new file mode 100644 index 000000000..07fee0397 --- /dev/null +++ b/crates/model/src/scene.rs @@ -0,0 +1,459 @@ +//! A `craft-mesh` scene (glTF, OBJ, STL or FBX, read there) as a [`Model`]: one primitive per +//! part with one index per vertex, decoded textures, and the normals and tangents the renderer +//! needs where the file has none. + +use std::collections::HashMap; +use std::sync::Arc; + +use craft_mesh as cm; + +use crate::{ + AlphaMode, Animation, CameraProjection, Channel, ChannelPath, Interp, MAX_IMPORT_TEXTURE_PIXELS, Mat4, Material, Mesh, Model, ModelCamera, ModelError, + ModelLight, ModelLightKind, Node, Primitive, Result, Skin, TexRef, Texture, Wrap, +}; + +/// The bounds every reader keeps: `craft-mesh`'s defaults, with up to 2 GiB of buffers, +/// arrays and embedded images in one import. +pub(crate) fn limits() -> cm::Limits { + cm::Limits { max_data_bytes: 2 << 30, ..cm::Limits::default() } +} + +pub(crate) fn error(e: cm::Error) -> ModelError { + match e { + cm::Error::Missing(name) => ModelError::Missing(name), + cm::Error::Unsupported(m) => ModelError::Unsupported(m), + cm::Error::Malformed(m) | cm::Error::TooLarge(m) => ModelError::Parse(m), + } +} + +/// What a primitive without normals gets. +#[derive(Clone, Copy, PartialEq, Eq)] +pub(crate) enum MissingNormals { + /// Every triangle its own vertices and face normal (glTF 2.0 §3.7.2.1). + Flat, + /// Area-weighted vertex normals (FBX). + Smooth, + /// Smooth within an OBJ smoothing group, flat where smoothing is off. + BySmoothing, +} + +/// A column-major `craft-mesh` matrix as a [`Mat4`]. +pub(crate) fn mat4(m: &cm::Mat4) -> Mat4 { + let mut out = [[0.0; 4]; 4]; + for (c, col) in m.as_chunks::<4>().0.iter().enumerate() { + for (r, v) in col.iter().enumerate() { + out[r][c] = *v; + } + } + Mat4(out) +} + +fn wrap(w: cm::Wrap) -> Wrap { + match w { + cm::Wrap::Repeat => Wrap::Repeat, + cm::Wrap::Clamp => Wrap::Clamp, + cm::Wrap::Mirror => Wrap::Mirror, + } +} + +/// The scene as a model. `image` gives the bytes of an image the scene names but does not hold +/// (OBJ, which only names its textures); an image that cannot be read or decoded leaves its +/// material untextured, with a log line. +pub(crate) fn to_model(mut scene: cm::Scene, missing: MissingNormals, image: &dyn Fn(&cm::Image) -> Option>) -> Result { + let mut warnings = std::mem::take(&mut scene.warnings); + for w in &warnings { + log::warn!("model: {w}"); + } + // Images decode once; each (image, wrap) a material uses is one texture. + let mut pixels_left = MAX_IMPORT_TEXTURE_PIXELS; + let mut decoded_by_name: HashMap>> = HashMap::new(); + let decoded: Vec>> = scene + .images + .iter() + .enumerate() + .map(|(index, im)| { + let key = image_key(im, index); + if let Some(decoded) = decoded_by_name.get(&key) { + return decoded.clone(); + } + let external; + let bytes = if let Some(data) = im.data.as_deref() { + Some(data) + } else { + external = image(im); + external.as_deref() + }; + let decoded = match bytes.map(|b| Texture::decode_within(b, &mut pixels_left)) { + Some(Ok(t)) => Some(Arc::new(t)), + Some(Err(e)) => { + let warning = format!("texture `{}` was left out: {e}", im.uri.as_deref().unwrap_or(&im.name)); + log::warn!("model: {warning}"); + warnings.push(warning); + None + } + None => { + let warning = format!("texture `{}` was not found next to the model", im.uri.as_deref().unwrap_or(&im.name)); + log::warn!("model: {warning}"); + warnings.push(warning); + None + } + }; + decoded_by_name.insert(key, decoded.clone()); + decoded + }) + .collect(); + let mut textures: Vec> = vec![]; + let mut texture_of: HashMap<(String, [Wrap; 2]), usize> = HashMap::new(); + for texture in &scene.texture_variants { + ensure_texture(&scene, &decoded, *texture, &mut textures, &mut texture_of, &mut pixels_left, &mut warnings); + } + let mut tref = |t: Option| -> Option { + let t = t?; + let texture = ensure_texture(&scene, &decoded, t, &mut textures, &mut texture_of, &mut pixels_left, &mut warnings)?; + Some(TexRef { texture, uv_set: t.uv_set }) + }; + let materials: Vec = scene + .materials + .iter() + .map(|m| Material { + name: m.name.clone(), + base_color: m.base_color, + base_color_tex: tref(m.base_color_texture), + metallic: m.metallic, + roughness: m.roughness, + metallic_roughness_tex: tref(m.metallic_roughness_texture), + normal_tex: tref(m.normal_texture), + normal_scale: m.normal_scale, + occlusion_tex: tref(m.occlusion_texture), + occlusion_strength: m.occlusion_strength, + emissive: m.emissive, + emissive_tex: tref(m.emissive_texture), + alpha_mode: match m.alpha_mode { + cm::AlphaMode::Opaque => AlphaMode::Opaque, + cm::AlphaMode::Mask(_) => AlphaMode::Mask, + cm::AlphaMode::Blend => AlphaMode::Blend, + }, + alpha_cutoff: if let cm::AlphaMode::Mask(c) = m.alpha_mode { c } else { 0.5 }, + double_sided: m.double_sided, + unlit: m.unlit, + }) + .collect(); + let mut adapter_bytes = 0u64; + let meshes = scene.meshes.iter().map(|m| mesh(m, &materials, missing, &mut adapter_bytes)).collect::>>()?; + let nodes = scene + .nodes + .iter() + .map(|n| { + let (translation, rotation, scale, matrix) = match n.trs { + Some(t) => (t.translation, t.rotation, t.scale, None), + None => ([0.0; 3], [0.0, 0.0, 0.0, 1.0], [1.0; 3], Some(mat4(&n.transform))), + }; + Node { + name: n.name.clone(), + translation, + rotation, + scale, + matrix, + mesh: n.mesh.filter(|&m| m < scene.meshes.len()), + skin: n.skin, + camera: n.camera, + light: n.light, + children: n.children.clone(), + } + }) + .collect(); + let skins = scene + .skins + .iter() + .map(|s| Skin { + joints: s.joints.clone(), + inverse_bind: if s.inverse_bind.is_empty() { vec![Mat4::IDENTITY; s.joints.len()] } else { s.inverse_bind.iter().map(mat4).collect() }, + }) + .collect(); + let animations = scene + .animations + .iter() + .map(|a| Animation { + name: a.name.clone(), + channels: a + .channels + .iter() + .map(|c| Channel { + node: c.node, + path: match c.path { + cm::ChannelPath::Translation => ChannelPath::Translation, + cm::ChannelPath::Rotation => ChannelPath::Rotation, + cm::ChannelPath::Scale => ChannelPath::Scale, + }, + interp: match c.interpolation { + cm::Interpolation::Step => Interp::Step, + cm::Interpolation::Linear => Interp::Linear, + cm::Interpolation::CubicSpline => Interp::CubicSpline, + }, + times: c.times.clone(), + values: c.values.clone(), + }) + .collect(), + }) + .collect(); + let name_or = |n: &str, d: String| if n.is_empty() { d } else { n.to_string() }; + let cameras = scene + .cameras + .iter() + .enumerate() + .map(|(i, c)| ModelCamera { + name: name_or(&c.name, format!("Camera {}", i + 1)), + projection: match c.projection { + cm::Projection::Perspective { yfov, aspect, znear, .. } => CameraProjection::Perspective { yfov: yfov.clamp(1e-3, 3.1), aspect, znear }, + cm::Projection::Orthographic { xmag, ymag, .. } => CameraProjection::Orthographic { xmag, ymag }, + }, + }) + .collect(); + let lights = scene + .lights + .iter() + .enumerate() + .map(|(i, l)| ModelLight { + name: name_or(&l.name, format!("Light {}", i + 1)), + kind: match l.kind { + cm::LightKind::Directional => ModelLightKind::Directional, + cm::LightKind::Point => ModelLightKind::Point, + cm::LightKind::Spot { inner, outer } => { + let outer = outer.clamp(1e-3, std::f64::consts::FRAC_PI_2); + ModelLightKind::Spot { inner: inner.clamp(0.0, outer), outer } + } + }, + color: l.color, + intensity: l.intensity.max(0.0), + range: l.range, + }) + .collect(); + Ok(Model { meshes, nodes, roots: scene.roots, materials, textures, skins, animations, cameras, lights, warnings }) +} + +fn image_key(image: &cm::Image, index: usize) -> String { + image.uri.as_deref().or_else(|| (!image.name.is_empty()).then_some(image.name.as_str())).map(str::to_string).unwrap_or_else(|| format!("image:{index}")) +} + +fn ensure_texture( + scene: &cm::Scene, + decoded: &[Option>], + reference: cm::TextureRef, + textures: &mut Vec>, + texture_of: &mut HashMap<(String, [Wrap; 2]), usize>, + pixels_left: &mut u64, + warnings: &mut Vec, +) -> Option { + let image = decoded.get(reference.image)?.as_ref()?; + let wrap_mode = reference.wrap.map(wrap); + let key = (image_key(scene.images.get(reference.image)?, reference.image), wrap_mode); + if let Some(&index) = texture_of.get(&key) { + return Some(index); + } + if image.wrap != wrap_mode { + let cost = (image.width as u64).checked_mul(image.height as u64); + let Some(cost) = cost.filter(|&cost| cost <= *pixels_left) else { + let source = scene.images.get(reference.image)?; + let warning = format!("texture `{}` wrap variant exceeds the model texture pixel limit", source.uri.as_deref().unwrap_or(&source.name)); + log::warn!("model: {warning}"); + warnings.push(warning); + return None; + }; + *pixels_left -= cost; + textures.push(Arc::new(Texture { wrap: wrap_mode, ..(**image).clone() })); + } else { + textures.push(image.clone()); + } + let index = textures.len() - 1; + texture_of.insert(key, index); + Some(index) +} + +/// One primitive per part, each with one vertex per distinct corner of its triangles. Normals +/// and UVs are kept for a part when every corner of it has them; a triangle naming a vertex +/// that is not there is left out. +fn mesh(m: &cm::Mesh, materials: &[Material], missing: MissingNormals, adapter_bytes: &mut u64) -> Result { + let skinned = !m.joints.is_empty() && m.joints.len() == m.positions.len() && m.weights.len() == m.positions.len(); + let uv_set = m.uv_sets.first(); + // Include temporary hash keys, smoothing maps and the peak duplicate produced by + // flat-normal expansion. + // Account against the whole scene before building any primitive arrays. + let projected = m + .parts + .iter() + .try_fold(0u64, |sum, part| { + let has_missing = part.corners.iter().any(|c| (c.normal as usize) >= m.normals.len()); + let flat = missing == MissingNormals::Flat || (missing == MissingNormals::BySmoothing && part.smoothing == 0); + let vertices = if flat && has_missing { (part.triangle_count() as u64).checked_mul(3)? } else { part.corners.len() as u64 }; + let bytes_per_vertex = if missing == MissingNormals::Flat { 64 } else { 128 }; + sum.checked_add(vertices.checked_mul(bytes_per_vertex)?) + }) + .ok_or_else(|| ModelError::Parse("expanded mesh size overflow".into()))?; + *adapter_bytes = adapter_bytes.checked_add(projected).ok_or_else(|| ModelError::Parse("expanded mesh size overflow".into()))?; + if *adapter_bytes > (2u64 << 30) { + return Err(ModelError::Parse("expanded mesh data exceeds the 2 GiB import limit".into())); + } + let smooth = smooth_normals(m, missing); + let mut primitives = vec![]; + for part in &m.parts { + let normals = part.corners.iter().any(|c| (c.normal as usize) < m.normals.len()); + let tangents = part.has_tangents && m.tangents.len() == m.positions.len(); + let uvs = uv_set.filter(|set| part.corners.iter().any(|c| (c.uv as usize) < set.len())); + let flat_missing = missing == MissingNormals::BySmoothing && part.smoothing == 0; + let mut authored_normals = vec![]; + let mut ids: HashMap<(cm::Corner, Option), u32> = HashMap::new(); + let mut p = Primitive { material: part.material.filter(|&i| i < materials.len()), ..Primitive::default() }; + for (face, t) in part.triangles().enumerate() { + if t.iter().any(|c| c.position as usize >= m.positions.len()) { + continue; + } + let flat_face_normal = (normals && flat_missing).then(|| face_normal(m, t)); + for c in t { + let has_normal = (c.normal as usize) < m.normals.len(); + let has_uv = uvs.is_some_and(|set| (c.uv as usize) < set.len()); + let key = ( + cm::Corner { position: c.position, normal: if has_normal { c.normal } else { cm::NONE }, uv: if has_uv { c.uv } else { cm::NONE } }, + (!has_normal && flat_face_normal.is_some()).then_some(face), + ); + let next = p.positions.len() as u32; + let id = *ids.entry(key).or_insert_with(|| { + let at = c.position as usize; + p.positions.push(m.positions.get(at).copied().unwrap_or_default().map(|x| x as f32)); + if normals { + let authored = m.normals.get(c.normal as usize).copied().map(|n| n.map(|x| x as f32)); + let fallback = flat_face_normal.or_else(|| smooth.get(&(c.position, part.material, smooth_group(part, missing))).copied()); + authored_normals.push(authored.or(fallback)); + p.normals.push(authored.or(fallback).unwrap_or([0.0, 0.0, 1.0])); + } else if let Some(n) = smooth.get(&(c.position, part.material, smooth_group(part, missing))) { + p.normals.push(*n); + } + if tangents { + p.tangents.push(m.tangents.get(at).copied().unwrap_or_default().map(|x| x as f32)); + } + if let Some(set) = uvs { + p.uvs.push(set.get(c.uv as usize).copied().unwrap_or_default()); + } + if skinned { + p.joints.push(m.joints.get(at).copied().unwrap_or_default()); + p.weights.push(m.weights.get(at).copied().unwrap_or_default()); + } + next + }); + p.indices.push(id); + } + } + if p.indices.is_empty() { + continue; + } + if normals && authored_normals.iter().any(Option::is_none) { + // Keep authored corner normals, and fill only absent ones from the surrounding + // triangles. The generated normals are smooth in a mixed-authorship part. + if authored_normals.iter().any(Option::is_none) { + p.compute_normals(); + for (n, authored) in p.normals.iter_mut().zip(authored_normals) { + if let Some(authored) = authored { + *n = authored; + } + } + } + } else if p.normals.is_empty() { + match missing { + MissingNormals::Flat => p.flat_normals(), + MissingNormals::BySmoothing if part.smoothing == 0 => p.flat_normals(), + MissingNormals::Smooth | MissingNormals::BySmoothing => p.compute_normals(), + } + } + if p.tangents.is_empty() && p.material.is_some_and(|i| materials.get(i).is_some_and(|mat| mat.normal_tex.is_some())) { + p.compute_tangents(); + } + primitives.push(p); + } + Ok(Mesh { name: m.name.clone(), primitives }) +} + +fn smooth_group(part: &cm::Part, missing: MissingNormals) -> u32 { + match missing { + MissingNormals::Smooth => 1, + MissingNormals::BySmoothing => part.smoothing, + MissingNormals::Flat => 0, + } +} + +fn face_normal(m: &cm::Mesh, tri: [cm::Corner; 3]) -> [f32; 3] { + let [a, b, c] = tri.map(|corner| m.positions.get(corner.position as usize).copied().unwrap_or_default()); + let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]]; + let n = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; + let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt(); + if len > 0.0 { n.map(|x| (x / len) as f32) } else { [0.0, 0.0, 1.0] } +} + +/// Area weighted generated normals across parts with the same material and smoothing state. +fn smooth_normals(m: &cm::Mesh, missing: MissingNormals) -> HashMap<(u32, Option, u32), [f32; 3]> { + let mut sums: HashMap<(u32, Option, u32), [f64; 3]> = HashMap::new(); + if missing == MissingNormals::Flat { + return HashMap::new(); + } + for part in &m.parts { + let group = smooth_group(part, missing); + if group == 0 { + continue; + } + for tri in part.triangles() { + let Some(a) = m.positions.get(tri[0].position as usize) else { continue }; + let Some(b) = m.positions.get(tri[1].position as usize) else { continue }; + let Some(c) = m.positions.get(tri[2].position as usize) else { continue }; + let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]]; + let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]]; + let face = [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]; + for corner in tri { + if (corner.normal as usize) < m.normals.len() { + continue; + } + let n = sums.entry((corner.position, part.material, group)).or_default(); + for i in 0..3 { + n[i] += face[i]; + } + } + } + } + sums.into_iter() + .map(|(key, n)| { + let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt(); + let n = if len > 0.0 { n.map(|x| (x / len) as f32) } else { [0.0, 0.0, 1.0] }; + (key, n) + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn wrap_variants_share_and_charge_the_import_pixel_budget() { + let scene = cm::Scene { images: vec![cm::Image { name: "texture.png".into(), ..cm::Image::default() }], ..cm::Scene::default() }; + let texture = Arc::new(Texture { width: 2, height: 2, data: vec![[1.0; 4]; 4], wrap: [Wrap::Repeat; 2] }); + let decoded = vec![Some(texture)]; + let mut textures = vec![]; + let mut texture_of = HashMap::new(); + // The decoded image has already taken four pixels from this budget. + let mut pixels_left = 4; + let mut warnings = vec![]; + let clamped = cm::TextureRef { image: 0, uv_set: 0, wrap: [cm::Wrap::Clamp; 2] }; + + let first = ensure_texture(&scene, &decoded, clamped, &mut textures, &mut texture_of, &mut pixels_left, &mut warnings).unwrap(); + let shared = ensure_texture(&scene, &decoded, clamped, &mut textures, &mut texture_of, &mut pixels_left, &mut warnings).unwrap(); + assert_eq!(first, shared); + assert_eq!(pixels_left, 0); + + let repeated = cm::TextureRef { wrap: [cm::Wrap::Repeat; 2], ..clamped }; + assert!(ensure_texture(&scene, &decoded, repeated, &mut textures, &mut texture_of, &mut pixels_left, &mut warnings).is_some()); + assert_eq!(pixels_left, 0); + + let mirrored = cm::TextureRef { wrap: [cm::Wrap::Mirror; 2], ..clamped }; + assert!(ensure_texture(&scene, &decoded, mirrored, &mut textures, &mut texture_of, &mut pixels_left, &mut warnings).is_none()); + assert_eq!(textures.len(), 2); + assert_eq!(warnings.len(), 1); + } +} diff --git a/crates/model/src/stl.rs b/crates/model/src/stl.rs index 34e9a7f06..4fb8ee084 100644 --- a/crates/model/src/stl.rs +++ b/crates/model/src/stl.rs @@ -1,201 +1,23 @@ -//! STL (stereolithography) meshes, binary and ASCII. +//! STL (stereolithography) meshes, binary and ASCII, read with `craft-mesh` +//! (`craft_mesh::stl`): every facet keeps its own three vertices and its face normal, and binary +//! colour extensions become one plain material per colour. //! -//! Written from the public description of the format (3D Systems' StereoLithography Interface -//! Specification, 1989, and its widely documented colour extensions): -//! -//! - Binary: an 80-byte header, a little-endian `u32` facet count, then 50 bytes per facet: a -//! normal and three vertices (12 `f32`) and a 16-bit attribute word. Bytes after the last -//! facet are ignored. -//! - ASCII: `solid name`, then `facet normal nx ny nz` / `outer loop` / `vertex x y z`… / -//! `endloop` / `endfacet`, closed by `endsolid`; several solids may follow each other. -//! Loops with more than three vertices are fan-triangulated. -//! - Colour (binary only): with `COLOR=r g b a` (four bytes) in the header (Materialise Magics), -//! that is the part's colour and a facet whose attribute has bit 15 clear has its own colour -//! (red in bits 0–4, green 5–9, blue 10–14); otherwise (VisCAM / SolidView) a facet with bit 15 -//! set has its own colour (blue in bits 0–4, green 5–9, red 10–14). Each colour becomes a -//! plain dielectric material; uncoloured files get none (the renderer's default material). -//! -//! STL has no units, no UVs and no shared vertices: every facet keeps its own three vertices -//! with the face normal from its counter-clockwise winding (the stored normal is only used when -//! the triangle is degenerate), which gives the faceted look of an STL part. STL files are -//! Z-up (3D printing and CAD); they are turned to the +Y-up convention of [`crate::Model`] -//! (`(x, y, z)` → `(x, z, −y)`, a proper rotation, so winding is kept). Facets with non-finite -//! coordinates are skipped. +//! STL files are Z-up (3D printing and CAD); they are turned to the +Y-up convention of +//! [`crate::Model`] (`(x, y, z)` → `(x, z, −y)`, a proper rotation, so winding is kept). -use std::collections::HashMap; - -use crate::{Material, Mesh, Model, Primitive, Result, cross, normalize, obj::srgb_to_linear, perr, sub}; - -/// Header (80) plus facet count (4). -const HEADER: usize = 84; -/// Bytes per binary facet. -const FACET: usize = 50; - -/// Parse an STL file (binary or ASCII, detected from the contents). -pub fn parse(bytes: &[u8]) -> Result { - let count = bytes.get(80..HEADER).and_then(|b| <[u8; 4]>::try_from(b).ok()).map(u32::from_le_bytes); - let needed = count.and_then(|n| (n as usize).checked_mul(FACET)).and_then(|n| n.checked_add(HEADER)); - // A binary file's size is exact; many binary headers still begin with `solid`, so the size - // decides first, then the ASCII keyword. - if needed.is_some_and(|n| n == bytes.len()) { - return binary(bytes); - } - if looks_ascii(bytes) { - return ascii(bytes); - } - if needed.is_some_and(|n| n <= bytes.len()) { - return binary(bytes); - } - Err(perr("not an STL file (truncated binary facets or no `solid` keyword)")) -} - -fn looks_ascii(bytes: &[u8]) -> bool { - let head = bytes.get(..bytes.len().min(512)).unwrap_or(&[]); - let text = String::from_utf8_lossy(head); - let t = text.trim_start(); - t.get(..5).is_some_and(|k| k.eq_ignore_ascii_case("solid")) && (t.contains("facet") || t.contains("endsolid")) -} +use crate::scene::{MissingNormals, error, limits, to_model}; +use crate::{Model, Result}; /// The Z-up → Y-up turn. -fn y_up(v: [f32; 3]) -> [f32; 3] { +fn y_up(v: [f64; 3]) -> [f64; 3] { [v[0], v[2], -v[1]] } -/// Facets grouped into primitives by colour, in order of first use. -#[derive(Default)] -struct Builder { - /// (colour key, primitive); `None` = uncoloured. - prims: Vec<(Option<[u8; 3]>, Primitive)>, - /// Colour → index into `prims` (up to 32 768 colours, so not a linear search). - slots: HashMap, usize>, - facets: usize, -} - -impl Builder { - /// Add one triangle (file coordinates); `stored` is the file's facet normal. - fn tri(&mut self, color: Option<[u8; 3]>, stored: [f32; 3], v: [[f32; 3]; 3]) { - if v.iter().flatten().any(|c| !c.is_finite()) { - return; - } - let v = v.map(y_up); - let n = normalize(cross(sub(v[1], v[0]), sub(v[2], v[0]))) - .or_else(|| stored.iter().all(|c| c.is_finite()).then(|| normalize(y_up(stored))).flatten()) - .unwrap_or([0.0, 1.0, 0.0]); - let slot = *self.slots.entry(color).or_insert_with(|| { - self.prims.push((color, Primitive::default())); - self.prims.len() - 1 - }); - let Some((_, p)) = self.prims.get_mut(slot) else { return }; - for c in v { - p.indices.push(p.positions.len() as u32); - p.positions.push(c); - p.normals.push(n); - } - self.facets += 1; - } - - fn finish(self, name: String) -> Result { - if self.facets == 0 { - return Err(perr("STL file without facets")); - } - let mut materials = vec![]; - let mut mesh = Mesh { name, primitives: vec![] }; - for (color, mut p) in self.prims { - if let Some(c) = color { - let lin = c.map(|x| srgb_to_linear(x as f32 / 255.0)); - let name = format!("#{:02X}{:02X}{:02X}", c[0], c[1], c[2]); - materials.push(Material { name, ..Material::plain([lin[0], lin[1], lin[2], 1.0], 0.0, 0.5) }); - p.material = Some(materials.len() - 1); - } - mesh.primitives.push(p); - } - // Uncoloured facets next to coloured ones: a neutral grey of their own. - if !materials.is_empty() { - for p in mesh.primitives.iter_mut().filter(|p| p.material.is_none()) { - materials.push(Material { name: "STL".into(), ..Material::plain([0.6, 0.6, 0.6, 1.0], 0.0, 0.5) }); - p.material = Some(materials.len() - 1); - } - } - Ok(Model::single(mesh, materials)) +/// Parse an STL file (binary or ASCII, detected from the contents). +pub fn parse(bytes: &[u8]) -> Result { + let mut scene = craft_mesh::stl::read(bytes, &limits()).map_err(error)?; + for m in &mut scene.meshes { + m.positions.iter_mut().chain(m.normals.iter_mut()).for_each(|v| *v = y_up(*v)); } -} - -fn f32_at(b: &[u8], at: usize) -> f32 { - b.get(at..at + 4).and_then(|s| <[u8; 4]>::try_from(s).ok()).map_or(f32::NAN, f32::from_le_bytes) -} - -/// A 5-bit channel expanded to 8 bits. -fn five(x: u16) -> u8 { - let x = (x & 31) as u8; - (x << 3) | (x >> 2) -} - -/// The Magics `COLOR=` part colour in the header (RGB; alpha is ignored). -fn header_color(header: &[u8]) -> Option<[u8; 3]> { - let at = header.windows(6).position(|w| w == b"COLOR=")?; - let c = header.get(at + 6..at + 10)?; - Some([*c.first()?, *c.get(1)?, *c.get(2)?]) -} - -fn binary(bytes: &[u8]) -> Result { - let header = bytes.get(..80).ok_or_else(|| perr("STL header truncated"))?; - let magics = header_color(header); - let body = bytes.get(HEADER..).unwrap_or(&[]); - let count = bytes.get(80..HEADER).and_then(|b| <[u8; 4]>::try_from(b).ok()).map_or(0, u32::from_le_bytes) as usize; - let mut b = Builder::default(); - for f in body.as_chunks::().0.iter().take(count) { - let n = [f32_at(f, 0), f32_at(f, 4), f32_at(f, 8)]; - let v = [0usize, 1, 2].map(|k| [f32_at(f, 12 + 12 * k), f32_at(f, 16 + 12 * k), f32_at(f, 20 + 12 * k)]); - let attr = f.get(48..50).and_then(|a| <[u8; 2]>::try_from(a).ok()).map_or(0, u16::from_le_bytes); - let color = match magics { - Some(part) => Some(if attr & 0x8000 == 0 { [five(attr), five(attr >> 5), five(attr >> 10)] } else { part }), - None => (attr & 0x8000 != 0).then(|| [five(attr >> 10), five(attr >> 5), five(attr)]), - }; - b.tri(color, n, v); - } - let text = String::from_utf8_lossy(header); - let name = text.trim_matches(|c: char| c == '\0' || c.is_whitespace()); - b.finish(name.strip_prefix("solid").unwrap_or(name).trim().to_string()) -} - -/// Three numbers from the rest of an ASCII line. -fn three<'a>(it: &mut impl Iterator) -> Option<[f32; 3]> { - Some([it.next()?.parse().ok()?, it.next()?.parse().ok()?, it.next()?.parse().ok()?]) -} - -fn ascii(bytes: &[u8]) -> Result { - let text = String::from_utf8_lossy(bytes); - let mut b = Builder::default(); - let mut name: Option = None; - let mut normal = [0.0f32; 3]; - let mut loop_v: Vec<[f32; 3]> = vec![]; - for (ln, line) in text.lines().enumerate() { - let line = line.trim(); - let mut it = line.split_whitespace(); - let Some(key) = it.next() else { continue }; - let bad = || perr(format!("STL line {}: expected three numbers", ln + 1)); - match key.to_ascii_lowercase().as_str() { - "solid" if name.is_none() => { - name = Some(line.get(5..).unwrap_or("").trim().to_string()); - } - "facet" => { - // `facet normal nx ny nz` - normal = it.next().and_then(|_| three(&mut it)).unwrap_or([0.0; 3]); - loop_v.clear(); - } - "vertex" => loop_v.push(three(&mut it).ok_or_else(bad)?), - "endloop" | "endfacet" => { - if let Some((&first, rest)) = loop_v.split_first() { - for w in rest.windows(2) { - if let [a, c] = w { - b.tri(None, normal, [first, *a, *c]); - } - } - } - loop_v.clear(); - } - _ => {} - } - } - b.finish(name.unwrap_or_default()) + to_model(scene, MissingNormals::Flat, &|_| None) } diff --git a/crates/model/src/tests.rs b/crates/model/src/tests.rs index fd3576afe..8c6a347fb 100644 --- a/crates/model/src/tests.rs +++ b/crates/model/src/tests.rs @@ -119,6 +119,22 @@ fn obj_without_normals_gets_them() { assert!(obj::parse(b"v 0 0 0\n", &|_| None).is_err()); } +#[test] +fn obj_mixed_authored_normals_keep_flat_missing_corners() { + let src = b"v 0 0 0\nv 1 0 0\nv 0 1 0\nv 0 0 1\nvn 0 1 0\ns off\nf 1//1 2 3\nf 1 3 4\n"; + let m = obj::parse(src, &|_| None).unwrap(); + let corners: Vec<_> = m.meshes[0] + .primitives + .iter() + .flat_map(|p| p.positions.iter().zip(&p.normals)) + .filter(|(position, _)| **position == [0.0, 1.0, 0.0]) + .map(|(_, normal)| *normal) + .collect(); + assert!(corners.contains(&[0.0, 0.0, 1.0]), "{corners:?}"); + assert!(corners.contains(&[1.0, 0.0, 0.0]), "{corners:?}"); + assert!(m.meshes[0].primitives.iter().any(|p| p.normals.contains(&[0.0, 1.0, 0.0]))); +} + #[test] fn obj_textures_from_another_machine_find_the_file_next_to_the_model() { // No committed media: the material file and its textures are written by the test itself. @@ -649,9 +665,9 @@ fn gltf_accessor_counts_are_checked_against_the_buffer_before_allocating() { let view = r#"{"buffer": 0, "byteLength": 36}"#; let cases = [ // A count far beyond the 36-byte buffer. - (r#"{"bufferView": 0, "componentType": 5126, "type": "VEC3", "count": 4000000000}"#, view, "past its buffer"), + (r#"{"bufferView": 0, "componentType": 5126, "type": "VEC3", "count": 4000000000}"#, view, "limit allows"), // count * components overflows. - (r#"{"bufferView": 0, "componentType": 5126, "type": "MAT4", "count": 9223372036854775807}"#, view, "too large"), + (r#"{"bufferView": 0, "componentType": 5126, "type": "MAT4", "count": 9223372036854775807}"#, view, "limit allows"), // Offsets that overflow when added. ( r#"{"bufferView": 0, "componentType": 5126, "type": "VEC3", "count": 3, "byteOffset": 16}"#, @@ -659,11 +675,11 @@ fn gltf_accessor_counts_are_checked_against_the_buffer_before_allocating() { "past its buffer", ), // A stride that overflows with the count. - (r#"{"bufferView": 0, "componentType": 5126, "type": "VEC3", "count": 3000000000}"#, r#"{"buffer": 0, "byteStride": 252}"#, "past its buffer"), + (r#"{"bufferView": 0, "componentType": 5126, "type": "VEC3", "count": 3000000000}"#, r#"{"buffer": 0, "byteStride": 252}"#, "limit allows"), // A stride smaller than an element would re-read the same bytes for a huge count. (r#"{"bufferView": 0, "componentType": 5126, "type": "MAT4", "count": 30}"#, r#"{"buffer": 0, "byteStride": 1}"#, "smaller than"), // No buffer view: nothing backs the count, so it is capped. - (r#"{"componentType": 5126, "type": "VEC3", "count": 1000000000}"#, view, "without a bufferView"), + (r#"{"componentType": 5126, "type": "VEC3", "count": 1000000000}"#, view, "limit allows"), ]; let t0 = std::time::Instant::now(); for (acc, v, want) in cases { @@ -721,67 +737,15 @@ fn gltf_issue_2139_huge_mat4_count_is_an_error() { } #[test] -fn gltf_buffer_less_accessors_share_one_zero_budget() { - // Each buffer-less accessor is capped, but nothing backs any of them, so referencing a capped - // one from many primitives must not multiply the allocation (#2139). +fn gltf_reused_buffer_less_accessor_is_read_once() { + // The shared reader parses a repeated accessor only once, so referencing it from several + // primitives does not multiply its one bounded allocation. let acc = r#"{"componentType": 5126, "type": "VEC3", "count": 5000000}"#; let prims = [r#"{"attributes": {"POSITION": 0}}"#; 4].join(", "); let doc = gltf_doc(acc, r#"{"buffer": 0}"#, 3).replace(r#"[{"attributes": {"POSITION": 0}}]"#, &format!("[{prims}]")); assert_eq!(doc.matches(r#""POSITION": 0"#).count(), 4); - let e = crate::gltf::parse(doc.as_bytes(), &|_| None).err().unwrap_or_else(|| panic!("imported")); - assert!(e.to_string().contains("without a bufferView"), "{e}"); - // One such accessor read once still imports. - let doc = gltf_doc(acc, r#"{"buffer": 0}"#, 3); - assert!(crate::gltf::parse(doc.as_bytes(), &|_| None).is_ok()); -} - -/// `refs` primitives sharing one buffer-backed `verts`-vertex POSITION accessor, without indices. -fn gltf_shared_positions(verts: usize, refs: usize) -> String { - let acc = format!(r#"{{"bufferView": 0, "componentType": 5126, "type": "VEC3", "count": {verts}}}"#); - let prims = vec![r#"{"attributes": {"POSITION": 0}}"#; refs].join(", "); - gltf_doc(&acc, r#"{"buffer": 0}"#, verts * 12).replace(r#"[{"attributes": {"POSITION": 0}}]"#, &format!("[{prims}]")) -} - -#[test] -fn gltf_buffer_backed_reads_share_one_read_budget() { - // A buffer-backed accessor is checked against its buffer, but each primitive that references - // it reads and keeps its own copy, so a small file listing many references must not ask for - // memory set by the reference count (#2139 review). Everything a primitive keeps is charged - // to one per-file budget: 1,000 vertices without indices or normals cost 3,000 position - // components, 1,000 generated indices, a 999-index triangle list and 999 flat-shaded - // vertices of 6 components, 10,993 in all. - let one = gltf_shared_positions(1000, 1); - let m = crate::gltf::parse_with_budget(one.as_bytes(), &|_| None, 20_000).unwrap(); - assert_eq!(m.meshes[0].primitives.len(), 1); - let three = gltf_shared_positions(1000, 3); - assert_eq!(three.matches(r#""POSITION": 0"#).count(), 3); - let e = crate::gltf::parse_with_budget(three.as_bytes(), &|_| None, 20_000).err().unwrap_or_else(|| panic!("imported")); - assert!(e.to_string().contains("more than 20000 components"), "{e}"); - // The real cap leaves room for legitimate sharing: many primitives over one vertex buffer. - let m = crate::gltf::parse(gltf_shared_positions(1000, 50).as_bytes(), &|_| None).unwrap(); - assert_eq!(m.meshes[0].primitives.len(), 50); -} - -#[test] -fn gltf_missing_indices_are_charged_to_the_read_budget() { - // Without `indices` every vertex gets a generated index, allocated like a read: after the - // 3,000 position components, 999 left is one short for the 1,000 indices. - let doc = gltf_shared_positions(1000, 1); - let e = crate::gltf::parse_with_budget(doc.as_bytes(), &|_| None, 3999).err().unwrap_or_else(|| panic!("imported")); - assert!(e.to_string().contains("(1000 requested, 999 left)"), "{e}"); -} - -#[test] -fn gltf_strip_expansion_is_charged_to_the_read_budget() { - // A strip of k indices becomes 3(k-2) triangle indices and as many flat-shaded vertices, so - // the output is charged, not only the 1,009 components read. - let doc = gltf_doc(r#"{"bufferView": 0, "componentType": 5126, "type": "VEC3", "count": 3}"#, r#"{"buffer": 0}"#, 1036) - .replace(r#""count": 3}]"#, r#""count": 3}, {"bufferView": 0, "componentType": 5121, "type": "SCALAR", "count": 1000}]"#) - .replace(r#""attributes": {"POSITION": 0}"#, r#""attributes": {"POSITION": 0}, "indices": 1, "mode": 5"#); - let m = crate::gltf::parse_with_budget(doc.as_bytes(), &|_| None, 30_000).unwrap(); - assert_eq!(m.meshes[0].primitives[0].indices.len(), 2994); - let e = crate::gltf::parse_with_budget(doc.as_bytes(), &|_| None, 5000).err().unwrap_or_else(|| panic!("imported")); - assert!(e.to_string().contains("more than 5000 components"), "{e}"); + let result = crate::gltf::parse(doc.as_bytes(), &|_| None); + assert!(result.is_ok(), "{result:?}"); } #[test] diff --git a/crates/opusenc/Cargo.toml b/crates/opusenc/Cargo.toml deleted file mode 100644 index db7f2b7f8..000000000 --- a/crates/opusenc/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[package] -name = "effectcraft-opusenc" -description = "Clean-room pure-Rust Opus encoder (RFC 6716 SILK NB/MB/WB, hybrid SWB/FB and CELT FB modes, 48 kHz, 20 ms; RFC 7845 OpusHead) for WebM export audio" -version.workspace = true -edition.workspace = true -license.workspace = true -rust-version.workspace = true - -[lints] -workspace = true - -[dependencies] - -[dev-dependencies] -craft-audio = { workspace = true } diff --git a/crates/opusenc/README.md b/crates/opusenc/README.md deleted file mode 100644 index 8a822ceac..000000000 --- a/crates/opusenc/README.md +++ /dev/null @@ -1,136 +0,0 @@ -# effectcraft-opusenc - -Clean-room, pure-Rust Opus encoder for EffectCraft's WebM export audio (layer L0, `std` only, -no `unsafe`, builds for `wasm32-unknown-unknown`). - -All three Opus modes, 20 ms packets (one frame per packet), 48 kHz float input, mono or stereo: - -- **CELT** (fullband): MDCT transform coding, constant packet size. -- **SILK** (narrowband 8 kHz, mediumband 12 kHz, wideband 16 kHz internal rate): linear - prediction with long-term (pitch) prediction; packet size varies around the target bitrate. -- **Hybrid** (super-wideband, fullband): SILK wideband codes 0–8 kHz and CELT codes bands 17 and - up (8 kHz and above) in the same range-coded frame; constant packet size. - -```rust -use effectcraft_opusenc::{Application, OpusEncoder}; -let mut enc = OpusEncoder::with_application(2, 48_000, Application::Voip); -let packet = enc.encode_float(&vec![0.0; OpusEncoder::FRAME_SIZE * 2]); -// enc.mode(), enc.bandwidth(), enc.pre_skip(), enc.opus_head() ... -``` - -`OpusEncoder::new(channels, bitrate)` is `with_application(.., Application::Audio)`. -`OpusEncoder::with_mode(channels, bitrate, mode, bandwidth)` forces a mode/bandwidth pair -(SILK: NB/MB/WB; hybrid: SWB/FB; CELT: FB). - -## Mode table - -Chosen once per stream (constant-bitrate export, no in-stream switching) from the bitrate per -channel (bitrate / channels; the total is clamped to 6 kb/s per channel … 510 kb/s): - -| per-channel bitrate | `Application::Voip` | `Application::Audio` (default) | -|---------------------|-------------------------|--------------------------------| -| < 10 kb/s | SILK narrowband (8 kHz) | SILK wideband | -| 10–12 kb/s | SILK mediumband (12 kHz)| SILK wideband | -| 12–16 kb/s | SILK wideband (16 kHz) | SILK wideband | -| 16–18 kb/s | SILK wideband | hybrid fullband | -| 18–28 kb/s | hybrid super-wideband | hybrid fullband | -| 28–36 kb/s | hybrid fullband | hybrid fullband | -| 36–40 kb/s | hybrid fullband | CELT fullband | -| ≥ 40 kb/s | CELT fullband | CELT fullband | - -TOC configurations (RFC 6716 §3.1, Table 2): SILK NB/MB/WB 20 ms = 1/5/9, hybrid SWB/FB 20 ms -= 13/15, CELT FB 20 ms = 31; the stereo bit is set for two channels; frame-count code 0. - -`pre_skip()` is 120 samples in every mode: the CELT MDCT overlap, and for SILK/hybrid the -decimator delay (83 samples at 48 kHz, 88 for narrowband) plus the decoder's SILK delay (one -internal-rate sample and the resampler delay of RFC 6716 Table 54). The SILK and CELT halves of a -hybrid frame are therefore aligned without extra buffering. - -## What is implemented - -**SILK** (RFC 6716 §4.2, encoder direction; own analysis and search design): - -- 48 kHz → 8/12/16 kHz decimation with a linear-phase Kaiser-windowed-sinc FIR. -- Per frame: energy VAD (inactive / unvoiced / voiced), open-loop pitch search (normalised - correlation with octave checks, joint lag + contour codebook choice, §4.2.7.6.1), windowed - autocorrelation LPC (Levinson, lag window, bandwidth expansion), LPC → NLSF by root search, - NLSF quantisation (stage-1 preselection by weighted distance, backwards-predictive stage-2 - scalar quantiser reproducing the decoder's dequantisation exactly, rate-distortion choice), - LTP codebook search over the three periodicity codebooks, independent + delta gain coding. -- Analysis-by-synthesis excitation: every sample is chosen by running the decoder's exact - fixed-point reconstruction (LTP from the decoder's own past output, LPC synthesis with the Q12 - coefficients of the *dequantised* NLSFs, gain rescaling between subframes, quantisation - offsets, the LCG sign sequence), so encoder and decoder never drift. A noise-feedback loop - shapes the coding noise by `1/A(z/γ)` (γ 0.75–0.9, coarser quantisation → more shaping), and a - small rate penalty biases pulses towards zero. -- Excitation coding: rate level, per-block pulse counts with LSB escapes, shell coding, LSBs and - signs (§4.2.7.8). -- Rate control: per-frame search over a gain offset (integer bracket, then bisection) to the - frame budget; SILK-only streams carry a bit reservoir across frames (packet sizes vary). -- Stereo: mid/side with the decoder's stereo prediction (§4.2.7.1, §4.2.8; ridge-regularised - least-squares weights, quantised to the decoder grid, interpolation mirrored), mid-only frames - when the predicted side is negligible, side gains floored at the mid gains. -- Not implemented: LBRR (in-band FEC), NLSF interpolation, 10/40/60 ms frames, DTX. - -**Hybrid** (§4.3 with start band 17): the SILK frame is written first, then the redundancy flag -(always 0) when there is room, then a CELT frame coding bands 17–18 (SWB) or 17–20 (FB) in the -same range coder with the remaining packet bytes (no silence flag or post-filter in hybrid -frames, decoder band-energy reset for uncoded bands mirrored). SILK gets 72 % (SWB) / 62 % (FB) -of the per-channel bitrate, at most the bitrate minus 6 kb/s, and never more than leaves CELT a -fifth of the packet (at least 80 bits). - -**CELT** (unchanged): forward MDCT with the low-overlap window, band energies with inter/intra -coarse prediction, fine and final energy bits, the decoder's exact bit allocation, spreading, -recursive band splitting, greedy PVQ search. Not implemented: transient frames, TF changes, -pitch post-filter, intensity stereo, dynamic allocation, VBR. All-zero CELT frames become 3-byte -silence packets. - -## Measured (tests in `tests/`, craft-audio's Opus decoder) - -Synthetic speech (glottal pulses 100–200 Hz through three moving formants, syllable envelopes, -pauses) and music (three-note harmonic chords); waveform SNR against the input band-limited to -the mode's bandwidth (full band for hybrid/CELT), residual delay 0 (±1 for narrowband) after the -pre-skip: - -| mode / bandwidth | bitrate target → actual | speech SNR | music SNR | -|--------------------|-------------------------|------------|-----------| -| SILK NB | 8 → 7.5 kb/s | 15.9 dB | 6.9 dB (9 kb/s) | -| SILK MB | 11 → 10.1 kb/s | 21.8 dB | 7.9 dB | -| SILK WB | 12 → 10.9 kb/s | 21.5 dB | 8.1 dB | -| SILK WB | 16 → 14.3 kb/s | 28.1 dB | 12.1 dB | -| SILK WB | 24 → 21.1 kb/s | 37.0 dB | 19.7 dB | -| hybrid SWB | 24 kb/s (CBR) | 28.7 dB | 13.0 dB | -| hybrid FB | 32 kb/s (CBR) | 32.1 dB | 15.6 dB | -| CELT FB | 12 kb/s (CBR) | 13.0 dB | — | - -At 12 kb/s mono, SILK wideband beats the CELT path on speech by ~8 dB (21.0 vs 13.0 dB -full-band SNR). SILK bitrates land within −13 % … 0 % of the target (speech spends little in -pauses), hybrid is exact. Stereo SILK WB at 32 kb/s: 41 dB dual-mono, 40/37 dB panned, 22/19 dB -for two independent speech signals. - -ffmpeg (external oracle, Ogg Opus written by the test) decodes every mode with both its native -`opus` decoder and `libopus` without errors, honouring pre-skip and end trimming, with the same -SNRs (libopus residual delay 0, ffmpeg's native decoder 0–4 samples). The only message tolerated -is ffmpeg's raw-PCM muxer timestamp complaint that its native decoder also prints for -narrowband files encoded by libopus itself. - -## Specifications - -- RFC 6716, *Definition of the Opus Audio Codec* (September 2012), with the RFC 8251 updates - (October 2017) as implemented by the decoder we round-trip against. -- RFC 7845, *Ogg Encapsulation for the Opus Audio Codec* (April 2016), §5.1 `OpusHead` and - §4.2 pre-skip. - -## Provenance - -Implemented from the RFC text. Constant tables (CELT band edges, `eMeans`, the coarse-energy -Laplace model, the allocation table, ICDFs; all SILK probability tables and codebooks: NLSF -stage-1/2 codebooks and prediction weights, gain, pitch, contour, LTP and pulse ICDFs, stereo -weights) and the decoder-side normative arithmetic the encoder must reproduce bit-exactly (CELT -allocation; SILK NLSF dequantisation and stabilisation, NLSF → LPC conversion, `log2lin`, the -fixed-point division/inverse helpers and the LPC analysis filter) are mirrored from FilmCraft's -first-party, spec-derived `filmcraft-opus` decoder (MIT OR Apache-2.0). That decoder, now -`craft_audio::opus` in craft-libs, is also the round-trip oracle in `tests/` and `crates/export/tests/it/opus_roundtrip.rs` (ffmpeg is a second, -external oracle when installed). All encoder-side analysis and search (pitch, LPC, NLSF and -LTP search, noise feedback, rate control, stereo prediction, the decimator) is our own design. -No third-party encoder or decoder source (libopus or otherwise) was consulted. diff --git a/crates/opusenc/src/bands.rs b/crates/opusenc/src/bands.rs deleted file mode 100644 index f90a554c4..000000000 --- a/crates/opusenc/src/bands.rs +++ /dev/null @@ -1,720 +0,0 @@ -//! Band shape coding: PVQ search and codeword indexing, spreading, recursive band splitting -//! (RFC 6716 §4.3.4, encoder direction). -//! -//! The encoder codes 20 ms long-block frames only (no transients, no TF changes), and stereo -//! as dual (independent L/R) stereo, so a band is always coded by `quant_partition` with a single -//! block. Every bit-budget computation mirrors the decoder so both sides take the same -//! split/pulse decisions. - -use crate::range::{BITRES, RangeEncoder, ilog}; -use crate::rate::{Mode, QTHETA_OFFSET, get_pulses}; -use crate::tables::EBANDS; -use crate::{CeltFrame, rate::Allocation}; - -pub const SPREAD_NORMAL: usize = 2; - -#[inline] -fn frac_mul16(a: i32, b: i32) -> i32 { - (16384 + (a as i16 as i32) * (b as i16 as i32)) >> 15 -} - -fn bitexact_cos(x: i32) -> i32 { - let tmp = (4096 + x * x) >> 13; - let x2 = tmp; - let x2 = (32767 - x2) + frac_mul16(x2, -7651 + frac_mul16(x2, 8277 + frac_mul16(-626, x2))); - 1 + x2 -} - -fn bitexact_log2tan(isin: i32, icos: i32) -> i32 { - let lc = ilog(icos as u32); - let ls = ilog(isin as u32); - let icos = icos << (15 - lc); - let isin = isin << (15 - ls); - (ls - lc) * (1 << 11) + frac_mul16(isin, frac_mul16(isin, -2597) + 7932) - frac_mul16(icos, frac_mul16(icos, -2597) + 7932) -} - -fn compute_qn(n: i32, b: i32, offset: i32, pulse_cap: i32, stereo: bool) -> i32 { - const EXP2_TABLE8: [i32; 8] = [16384, 17866, 19483, 21247, 23170, 25267, 27554, 30048]; - let mut n2 = 2 * n - 1; - if stereo && n == 2 { - n2 -= 1; - } - let mut qb = (b + n2 * offset) / n2; - qb = qb.min(b - pulse_cap - (4 << BITRES)); - qb = qb.min(8 << BITRES); - if qb < (1 << BITRES >> 1) { - 1 - } else { - let qn = EXP2_TABLE8[(qb & 0x7) as usize] >> (14 - (qb >> BITRES)); - (qn + 1) >> 1 << 1 - } -} - -/// One elementary pass of the spreading rotation, inverted (the decoder applies the forward -/// pass; the encoder undoes it before the pulse search). -fn exp_rotation1_inv(x: &mut [f32], len: usize, stride: usize, c: f32, s: f32) { - if len <= stride { - return; - } - if len > 2 * stride { - for i in 0..=len - 2 * stride - 1 { - let x1 = x[i]; - let x2 = x[i + stride]; - x[i + stride] = c * x2 - s * x1; - x[i] = c * x1 + s * x2; - } - } - for i in (0..len - stride).rev() { - let x1 = x[i]; - let x2 = x[i + stride]; - x[i + stride] = c * x2 - s * x1; - x[i] = c * x1 + s * x2; - } -} - -/// Inverse of the decoder's spreading rotation (§4.3.4.3) for one block of `len` samples. -pub fn exp_rotation_inv(x: &mut [f32], len: usize, k: usize, spread: usize) { - const SPREAD_FACTOR: [usize; 3] = [15, 10, 5]; - if 2 * k >= len || spread == 0 { - return; - } - let factor = SPREAD_FACTOR[spread - 1]; - let gain = len as f32 / (len + factor * k) as f32; - let theta = 0.5 * gain * gain; - let c = (0.5 * std::f32::consts::PI * theta).cos(); - let s = (0.5 * std::f32::consts::PI * (1.0 - theta)).cos(); - let mut stride2 = 0; - if len >= 8 { - stride2 = 1; - while stride2 * stride2 + stride2 < len { - stride2 += 1; - } - } - // The decoder applies (stride2: s, c) then (1: c, s); undo in reverse order. - exp_rotation1_inv(x, len, 1, c, s); - if stride2 != 0 { - exp_rotation1_inv(x, len, stride2, s, c); - } -} - -/// Relative slack for the pulse-candidate filter in [`pvq_search`]: far above the f32 rounding of -/// the filter score (a few 1e-7), far below the spread of real scores. -const PVQ_SCORE_SLACK: f32 = 1e-5; - -/// Greedy PVQ search: the integer vector `y` with `sum |y| = k` closest in direction to `x`. -pub fn pvq_search(x: &[f32], k: usize, y: &mut [i32]) { - let n = x.len(); - y[..n].fill(0); - // `abs`, `dy` (2 y + 1, infinite in the padding) and the per-pass scores `score`, each padded to - // whole 8-lane chunks. - let np = n.next_multiple_of(8); - let mut buf = vec![0f32; 3 * np]; - let (abs, rest) = buf.split_at_mut(np); - let (dy, score) = rest.split_at_mut(np); - for (a, v) in abs.iter_mut().zip(x) { - *a = v.abs(); - } - let sum: f32 = abs[..n].iter().sum(); - if !sum.is_finite() || sum <= 1e-15 { - y[0] = k as i32; - return; - } - let mut placed = 0usize; - let mut xy = 0f32; - let mut yy = 0f32; - if k > n / 2 { - // Pre-project onto the pyramid (rounding down) and place the rest greedily. - let r = (k as f32 - 1.0) / sum; - for j in 0..n { - // Non-negative and at most k, so the truncating cast is the floor. - let p = (abs[j] * r) as i32; - y[j] = p; - placed += p as usize; - xy += abs[j] * p as f32; - yy += (p * p) as f32; - } - } - for j in 0..np { - dy[j] = if j < n { 2.0 * y[j] as f32 + 1.0 } else { f32::INFINITY }; - } - while placed < k { - // Vectorisable scores (xy + |x_j|)^2 / (yy + 2 y_j + 1) and their maximum. - for ((sc, &a), &d) in score.iter_mut().zip(abs.iter()).zip(dy.iter()) { - let t = xy + a; - *sc = t * t / (yy + d); - } - let mut lane_max = [0f32; 8]; - for c in score.as_chunks::<8>().0 { - for i in 0..8 { - lane_max[i] = if c[i] > lane_max[i] { c[i] } else { lane_max[i] }; - } - } - let top = lane_max.iter().fold(0f32, |m, &v| if v > m { v } else { m }); - // The exact cross-multiplied test below, in index order with the first maximum winning, only - // matters for entries within rounding distance of the top score: every other entry is beaten - // by the top one whenever it is reached and never beats it afterwards. Running the test on - // those alone therefore picks the same pulse as running it on all of them. - let filter = top > 1e-30 && top.is_finite(); - let lo = top * (1.0 - PVQ_SCORE_SLACK); - // Usually exactly one entry qualifies; its index falls out of a lane-wise count. - let mut count = [0u32; 8]; - let mut index = [0u32; 8]; - for (ci, c) in score.as_chunks::<8>().0.iter().enumerate() { - for i in 0..8 { - let hit = u32::from(c[i] >= lo); - count[i] += hit; - index[i] += hit * (ci * 8 + i) as u32; - } - } - let mut best = 0usize; - if filter && count.iter().sum::() == 1 { - best = index.iter().sum::() as usize; - } else { - let mut best_num = -1f32; - let mut best_den = 1f32; - for j in 0..n { - if !filter || score[j] >= lo { - let num = xy + abs[j]; - let num = num * num; - let den = yy + 2.0 * y[j] as f32 + 1.0; - if num * best_den > best_num * den { - best_num = num; - best_den = den; - best = j; - } - } - } - } - xy += abs[best]; - yy += 2.0 * y[best] as f32 + 1.0; - y[best] += 1; - dy[best] = 2.0 * y[best] as f32 + 1.0; - placed += 1; - } - for j in 0..n { - if x[j] < 0.0 { - y[j] = -y[j]; - } - } -} - -/// Largest band width and pulse count the encoder codes (176 coefficients, `get_pulses(40)` = 128). -const PVQ_MAX_N: usize = 176; -const PVQ_MAX_K: usize = 128; - -/// Row-major `V(n, k)` for `n <= max_n`, `k <= max_k` with row stride `max_k + 1`, saturated at -/// `u32::MAX` (a codebook that large is never coded, see `rate::fits_in32`). -fn build_pvq_table(max_n: usize, max_k: usize) -> Vec { - let w = max_k + 1; - let mut v = vec![0u32; (max_n + 1) * w]; - v[0] = 1; - for nn in 1..=max_n { - v[nn * w] = 1; - for kk in 1..=max_k { - let sum = v[(nn - 1) * w + kk] as u64 + v[nn * w + kk - 1] as u64 + v[(nn - 1) * w + kk - 1] as u64; - v[nn * w + kk] = sum.min(u32::MAX as u64) as u32; - } - } - v -} - -fn pvq_table() -> &'static [u32] { - static TABLE: std::sync::OnceLock> = std::sync::OnceLock::new(); - TABLE.get_or_init(|| build_pvq_table(PVQ_MAX_N, PVQ_MAX_K)) -} - -/// Encodes the PVQ codeword `y` (`sum |y| = k`) as the index the RFC 6716 §4.3.4.2 decoder maps -/// back to `y`. -pub fn encode_pulses(y: &[i32], k: usize, enc: &mut RangeEncoder) { - let n = y.len(); - // Shapes outside the coded range (never produced by the band layout) get a local table. - let local; - let (v, w) = if n <= PVQ_MAX_N && k <= PVQ_MAX_K { - (pvq_table(), PVQ_MAX_K + 1) - } else { - local = build_pvq_table(n, k); - (&local[..], k + 1) - }; - let row = |nn: usize| &v[nn * w..(nn + 1) * w]; - let total = row(n)[k] as u64; - let mut index = 0u64; - let mut kk = k; - for j in 0..n { - if kk == 0 { - break; - } - let rem = n - j; - let t = y[j].unsigned_abs() as usize; - let below = row(rem - 1); - // Codewords with |y_j| = t start at sum_{m < kk - t} V(rem-1, m) within their sign half. - let mut base: u64 = below[..kk - t].iter().map(|&x| x as u64).sum(); - if y[j] < 0 { - base += (below[kk] as u64 + row(rem)[kk] as u64) / 2; - } - index += base; - kk -= t; - } - debug_assert!(total <= u32::MAX as u64); - if total >= 2 { - enc.uint(index as u32, total as u32); - } -} - -pub struct BandEnc<'m, 'e> { - pub m: &'m Mode, - pub enc: &'e mut RangeEncoder, - pub i: usize, - pub spread: usize, - pub remaining_bits: i32, - iy: Vec, - tmp: Vec, -} - -impl BandEnc<'_, '_> { - /// `compute_theta` for a mono split (single block): measures the energy split between the - /// two halves and codes the quantised angle with the triangular pdf. - fn compute_theta_split(&mut self, xa: &[f32], xb: &[f32], b: &mut i32, lm: i32) -> (i32, i32, i32) { - let n = xa.len() as i32; - let i = self.i; - let pulse_cap = self.m.log_n[i] + lm * (1 << BITRES); - let offset = (pulse_cap >> 1) - QTHETA_OFFSET; - let qn = compute_qn(n, *b, offset, pulse_cap, false); - let tell = self.enc.tell_frac(); - let mut itheta = 0i32; - if qn != 1 { - let mid = xa.iter().map(|v| v * v).sum::().sqrt(); - let side = xb.iter().map(|v| v * v).sum::().sqrt(); - let ang = (side as f64).atan2(mid as f64) * std::f64::consts::FRAC_2_PI; - let it = ((ang * qn as f64 + 0.5).floor() as i32).clamp(0, qn) as u32; - let q = qn as u32; - let half = q >> 1; - let ft = (half + 1) * (half + 1); - let (fl, fs) = if it <= half { ((it * (it + 1)) >> 1, it + 1) } else { (ft - (((q + 1 - it) * (q + 2 - it)) >> 1), q + 1 - it) }; - self.enc.encode(fl, fl + fs, ft); - itheta = ((it * 16384) / q) as i32; - } - let qalloc = self.enc.tell_frac() - tell; - *b -= qalloc; - let delta = if itheta == 0 { - -16384 - } else if itheta == 16384 { - 16384 - } else { - let imid = bitexact_cos(itheta); - let iside = bitexact_cos(16384 - itheta); - frac_mul16((n - 1) << 7, bitexact_log2tan(iside, imid)) - }; - (itheta, delta, qalloc) - } - - /// `quant_partition` (single block, encoder side). - pub fn quant_partition(&mut self, x: &[f32], mut b: i32, mut lm: i32) { - let n = x.len(); - let i = self.i; - let cache = self.m.cache(lm, i); - let cache_max = cache[cache[0] as usize] as i32; - if lm != -1 && b > cache_max + 12 && n > 2 { - let half = n >> 1; - let (xa, xb) = x.split_at(half); - lm -= 1; - let (itheta, delta, qalloc) = self.compute_theta_split(xa, xb, &mut b, lm); - let mut mbits = 0.max(b.min((b - delta) / 2)); - let mut sbits = b - mbits; - self.remaining_bits -= qalloc; - let mut rebalance = self.remaining_bits; - if mbits >= sbits { - self.quant_partition(xa, mbits, lm); - rebalance = mbits - (rebalance - self.remaining_bits); - if rebalance > 3 << BITRES && itheta != 0 { - sbits += rebalance - (3 << BITRES); - } - self.quant_partition(xb, sbits, lm); - } else { - self.quant_partition(xb, sbits, lm); - rebalance = sbits - (rebalance - self.remaining_bits); - if rebalance > 3 << BITRES && itheta != 16384 { - mbits += rebalance - (3 << BITRES); - } - self.quant_partition(xa, mbits, lm); - } - return; - } - let m = self.m; - let mut q = m.bits2pulses(i, lm, b); - let mut curr_bits = m.pulses2bits(i, lm, q); - self.remaining_bits -= curr_bits; - while self.remaining_bits < 0 && q > 0 { - self.remaining_bits += curr_bits; - q -= 1; - curr_bits = m.pulses2bits(i, lm, q); - self.remaining_bits -= curr_bits; - } - if q != 0 { - let k = get_pulses(q) as usize; - let mut tmp = std::mem::take(&mut self.tmp); - tmp.clear(); - tmp.extend_from_slice(x); - exp_rotation_inv(&mut tmp, n, k, self.spread); - let mut iy = std::mem::take(&mut self.iy); - iy.clear(); - iy.resize(n, 0); - pvq_search(&tmp, k, &mut iy); - encode_pulses(&iy, k, self.enc); - self.iy = iy; - self.tmp = tmp; - } - } -} - -/// Shape-coding controls, independent of the selected band allocation. -pub struct BandCoding { - pub spread: usize, - pub total_bits: i32, -} - -/// Codes all band shapes (`quant_all_bands`, encoder side, long blocks). `x` holds -/// `frame.channels` channels of `n_total` normalised MDCT coefficients each. -pub fn quant_all_bands(m: &Mode, frame: CeltFrame, x: &[f32], n_total: usize, allocation: &Allocation, coding: BandCoding, enc: &mut RangeEncoder) { - let CeltFrame { start, end, channels: c, lm } = frame; - let Allocation { pulses, dual_stereo, intensity, coded_bands, balance, .. } = allocation; - let (dual_stereo, intensity, coded_bands, mut balance) = (*dual_stereo, *intensity, *coded_bands, *balance); - let BandCoding { spread, total_bits } = coding; - let mm = 1usize << lm; - debug_assert!(c == 1 || dual_stereo || intensity <= start, "stereo frames are coded as dual stereo"); - let mut ctx = BandEnc { m, enc, i: 0, spread, remaining_bits: 0, iy: Vec::new(), tmp: Vec::new() }; - for i in start..end { - ctx.i = i; - let xo = mm * EBANDS[i] as usize; - let n = mm * EBANDS[i + 1] as usize - xo; - let tell = ctx.enc.tell_frac(); - if i != start { - balance -= tell; - } - let remaining_bits = total_bits - tell - 1; - ctx.remaining_bits = remaining_bits; - let b = if i < coded_bands { - let curr_balance = balance / 3.min(coded_bands as i32 - i as i32); - 0.max(16383.min((remaining_bits + 1).min(pulses[i] + curr_balance))) - } else { - 0 - }; - // Bands at and above `intensity` (= coded_bands) carry no bits, so they emit no symbols. - if i < coded_bands || c == 1 { - if c == 2 && dual_stereo && i < intensity { - ctx.quant_partition(&x[xo..xo + n], b / 2, lm as i32); - ctx.quant_partition(&x[n_total + xo..n_total + xo + n], b / 2, lm as i32); - } else { - ctx.quant_partition(&x[xo..xo + n], b, lm as i32); - } - } - balance += pulses[i] + tell; - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::range::dec::RangeDecoder; - - fn exp_rotation1(x: &mut [f32], len: usize, stride: usize, c: f32, s: f32) { - let ms = -s; - if len <= stride { - return; - } - for i in 0..len - stride { - let x1 = x[i]; - let x2 = x[i + stride]; - x[i + stride] = c * x2 + s * x1; - x[i] = c * x1 + ms * x2; - } - if len > 2 * stride { - for i in (0..=len - 2 * stride - 1).rev() { - let x1 = x[i]; - let x2 = x[i + stride]; - x[i + stride] = c * x2 + s * x1; - x[i] = c * x1 + ms * x2; - } - } - } - - /// The decoder's spreading rotation (single block). - fn exp_rotation(x: &mut [f32], len: usize, k: usize, spread: usize) { - const SPREAD_FACTOR: [usize; 3] = [15, 10, 5]; - if 2 * k >= len || spread == 0 { - return; - } - let factor = SPREAD_FACTOR[spread - 1]; - let gain = len as f32 / (len + factor * k) as f32; - let theta = 0.5 * gain * gain; - let c = (0.5 * std::f32::consts::PI * theta).cos(); - let s = (0.5 * std::f32::consts::PI * (1.0 - theta)).cos(); - let mut stride2 = 0; - if len >= 8 { - stride2 = 1; - while stride2 * stride2 + stride2 < len { - stride2 += 1; - } - } - if stride2 != 0 { - exp_rotation1(x, len, stride2, s, c); - } - exp_rotation1(x, len, 1, c, s); - } - - #[test] - fn spreading_inverse_is_exact() { - for &len in &[8usize, 16, 24, 48, 96, 176] { - for k in [1usize, 2, 3, 5] { - let orig: Vec = (0..len).map(|i| ((i * 31 % 17) as f32 - 8.0) / 8.0).collect(); - let mut x = orig.clone(); - exp_rotation_inv(&mut x, len, k, SPREAD_NORMAL); - exp_rotation(&mut x, len, k, SPREAD_NORMAL); - for (a, b) in x.iter().zip(&orig) { - assert!((a - b).abs() < 1e-4, "len={len} k={k}"); - } - } - } - } - - /// PVQ decoder of RFC 6716 §4.3.4.2 (as in FilmCraft's decoder). - fn decode_pulses(n: usize, k: usize, dec: &mut RangeDecoder) -> Vec { - let w = k + 1; - let mut v = vec![0u64; (n + 1) * w]; - v[0] = 1; - for nn in 1..=n { - v[nn * w] = 1; - for kk in 1..=k { - v[nn * w + kk] = v[(nn - 1) * w + kk].saturating_add(v[nn * w + kk - 1]).saturating_add(v[(nn - 1) * w + kk - 1]); - } - } - let total = v[n * w + k]; - let mut i = if total >= 2 { dec.uint(total as u32) as u64 } else { 0 }; - let mut y = vec![0i32; n]; - let mut kk = k; - for j in 0..n { - let rem = n - j; - if kk == 0 { - break; - } - let vv = |nn: usize, kx: usize| v[nn * w + kx]; - let mut p = (vv(rem - 1, kk) + vv(rem, kk)) / 2; - let neg = i >= p; - if neg { - i -= p; - } - let k0 = kk; - p -= vv(rem - 1, kk); - while p > i && kk > 0 { - kk -= 1; - p -= vv(rem - 1, kk); - } - let mag = (k0 - kk) as i32; - y[j] = if neg { -mag } else { mag }; - i -= p.min(i); - } - y - } - - fn all_codewords(n: usize, k: usize) -> Vec> { - if n == 0 { - return if k == 0 { vec![vec![]] } else { vec![] }; - } - let mut out = Vec::new(); - for t in -(k as i32)..=(k as i32) { - for mut rest in all_codewords(n - 1, k - t.unsigned_abs() as usize) { - rest.insert(0, t); - out.push(rest); - } - } - out - } - - #[test] - fn pvq_index_roundtrip_exhaustive() { - for n in 1..6usize { - for k in 1..6usize { - for y in all_codewords(n, k) { - let mut e = RangeEncoder::new(); - encode_pulses(&y, k, &mut e); - let buf = e.done(16); - let mut d = RangeDecoder::new(&buf); - assert_eq!(decode_pulses(n, k, &mut d), y, "n={n} k={k}"); - } - } - } - } - - /// The per-call table encoder this module used before the shared table. - fn encode_pulses_reference(y: &[i32], k: usize, enc: &mut RangeEncoder) { - let n = y.len(); - let w = k + 1; - let mut v = vec![0u64; (n + 1) * w]; - v[0] = 1; - for nn in 1..=n { - v[nn * w] = 1; - for kk in 1..=k { - let a = v[(nn - 1) * w + kk]; - let b = v[nn * w + kk - 1]; - let c = v[(nn - 1) * w + kk - 1]; - v[nn * w + kk] = a.saturating_add(b).saturating_add(c); - } - } - let total = v[n * w + k]; - let vv = |nn: usize, kx: usize| v[nn * w + kx]; - let mut index = 0u64; - let mut kk = k; - for j in 0..n { - if kk == 0 { - break; - } - let rem = n - j; - let t = y[j].unsigned_abs() as usize; - let mut base: u64 = (0..kk - t).map(|m| vv(rem - 1, m)).sum(); - if y[j] < 0 { - base += (vv(rem - 1, kk) + vv(rem, kk)) / 2; - } - index += base; - kk -= t; - } - if total >= 2 { - enc.uint(index as u32, total as u32); - } - } - - #[test] - fn pvq_table_encode_matches_per_call_table() { - let mut seed = 0x9E37_79B9_7F4A_7C15u64; - let mut next = move |m: u64| { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - seed % m - }; - let mut checked = 0; - for n in (1..=PVQ_MAX_N).step_by(5).chain([PVQ_MAX_N]) { - for k in (1..=PVQ_MAX_K).step_by(3).chain([PVQ_MAX_K]) { - if crate::rate::pvq_v(n, k) > u32::MAX as u128 { - continue; - } - for _ in 0..4 { - let mut y = vec![0i32; n]; - for _ in 0..k { - let at = next(n as u64) as usize; - y[at] += if next(2) == 0 { 1 } else { -1 }; - } - // Opposite pulses cancel; top up so that sum |y| = k again. - let mut have: usize = y.iter().map(|v| v.unsigned_abs() as usize).sum(); - while have < k { - let at = next(n as u64) as usize; - y[at] += if y[at] < 0 { -1 } else { 1 }; - have += 1; - } - let (mut a, mut b) = (RangeEncoder::new(), RangeEncoder::new()); - encode_pulses(&y, k, &mut a); - encode_pulses_reference(&y, k, &mut b); - assert_eq!(a.done(16), b.done(16), "n={n} k={k}"); - checked += 1; - } - } - } - assert!(checked > 100, "{checked}"); - } - - /// The scalar greedy search the vectorised one replaced. - fn pvq_search_ref(x: &[f32], k: usize, y: &mut [i32]) { - let n = x.len(); - y[..n].fill(0); - let abs: Vec = x.iter().map(|v| v.abs()).collect(); - let sum: f32 = abs.iter().sum(); - if !sum.is_finite() || sum <= 1e-15 { - y[0] = k as i32; - return; - } - let mut placed = 0usize; - let mut xy = 0f32; - let mut yy = 0f32; - if k > n / 2 { - let r = (k as f32 - 1.0) / sum; - for j in 0..n { - let p = (abs[j] * r).floor() as i32; - y[j] = p; - placed += p as usize; - xy += abs[j] * p as f32; - yy += (p * p) as f32; - } - } - while placed < k { - let mut best = 0usize; - let mut best_num = -1f32; - let mut best_den = 1f32; - for j in 0..n { - let num = xy + abs[j]; - let num = num * num; - let den = yy + 2.0 * y[j] as f32 + 1.0; - if num * best_den > best_num * den { - best_num = num; - best_den = den; - best = j; - } - } - xy += abs[best]; - yy += 2.0 * y[best] as f32 + 1.0; - y[best] += 1; - placed += 1; - } - for j in 0..n { - if x[j] < 0.0 { - y[j] = -y[j]; - } - } - } - - #[test] - fn pvq_search_matches_scalar_reference() { - let mut state = 0x9e3779b97f4a7c15u64; - let mut rnd = move || { - state ^= state << 13; - state ^= state >> 7; - state ^= state << 17; - (state >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0 - }; - let mut a = vec![0i32; 200]; - let mut b = vec![0i32; 200]; - let mut cases = 0; - for round in 0..6000 { - let n = 1 + (round * 37 + (rnd().abs() * 176.0) as usize) % 176; - let k = 1 + (rnd().abs() * 127.0) as usize; - let scale = [1.0f32, 1e-9, 1e6, 3e-3][round % 4]; - let x: Vec = (0..n) - .map(|_| match round % 6 { - 0 => rnd(), - 1 => if rnd() > 0.8 { rnd() } else { 0.0 }, - 2 => (rnd() * 4.0).round() / 4.0, - 3 => if rnd() > 0.0 { 1.0 } else { -1.0 }, - 4 => rnd().powi(5), - _ => if rnd() > 0.95 { 3.0 * rnd() } else { 1e-4 * rnd() }, - } * scale) - .collect(); - pvq_search(&x, k, &mut a); - pvq_search_ref(&x, k, &mut b); - assert_eq!(a[..n], b[..n], "n={n} k={k} round={round}"); - cases += 1; - } - assert_eq!(cases, 6000); - } - - #[test] - fn pvq_search_finds_good_direction() { - let x: Vec = (0..32).map(|i| ((i as f32) * 0.7).sin()).collect(); - let mut y = vec![0i32; 32]; - for k in [1usize, 4, 16, 64] { - pvq_search(&x, k, &mut y); - assert_eq!(y.iter().map(|v| v.unsigned_abs() as usize).sum::(), k); - let xy: f32 = x.iter().zip(&y).map(|(a, &b)| a * b as f32).sum(); - let yy: f32 = y.iter().map(|&b| (b * b) as f32).sum(); - let xx: f32 = x.iter().map(|a| a * a).sum(); - let corr = xy / (xx * yy).sqrt(); - assert!(corr > if k >= 16 { 0.9 } else { 0.2 }, "k={k} corr={corr}"); - } - } -} diff --git a/crates/opusenc/src/energy.rs b/crates/opusenc/src/energy.rs deleted file mode 100644 index 1d4b12719..000000000 --- a/crates/opusenc/src/energy.rs +++ /dev/null @@ -1,212 +0,0 @@ -//! Band energy quantisation: Laplace-coded coarse energy with inter/intra prediction, fine -//! energy and the final refinement bits (RFC 6716 §4.3.2, encoder direction). -//! -//! The quantised energies are updated with exactly the decoder's arithmetic so the prediction -//! state never drifts between encoder and decoder. - -use crate::CeltFrame; -use crate::range::RangeEncoder; -use crate::rate::{Allocation, MAX_FINE_BITS}; -use crate::tables::{BETA_COEF, BETA_INTRA, E_PROB_MODEL, NB_EBANDS, PRED_COEF, SMALL_ENERGY_ICDF}; - -const LAPLACE_MINP: u32 = 1; -const LAPLACE_NMIN: u32 = 16; - -fn laplace_get_freq1(fs0: u32, decay: u32) -> u32 { - let ft = 32768 - LAPLACE_MINP * (2 * LAPLACE_NMIN) - fs0; - (ft * (16384 - decay)) >> 15 -} - -/// Encodes a Laplace-distributed integer (`fs` = probability of 0 in Q15, `decay` in Q14). -/// Returns the value actually coded (very large magnitudes are clamped to the representable -/// range). -pub fn laplace_encode(enc: &mut RangeEncoder, value: i32, mut fs: u32, decay: u32) -> i32 { - let mut fl = 0u32; - let mut coded = value; - if value != 0 { - let s: i32 = if value < 0 { -1 } else { 0 }; - let val = value.abs(); - fl = fs; - fs = laplace_get_freq1(fs, decay); - let mut i = 1; - while fs > 0 && i < val { - fs *= 2; - fl += fs + 2 * LAPLACE_MINP; - fs = (fs * decay) >> 15; - i += 1; - } - if fs == 0 { - let ndi_max = (32768 - fl + LAPLACE_MINP - 1) as i32; - let ndi_max = (ndi_max - s) >> 1; - let di = (val - i).min(ndi_max - 1); - fl = (fl as i32 + (2 * di + 1 + s) * LAPLACE_MINP as i32) as u32; - fs = LAPLACE_MINP.min(32768 - fl); - let mag = i + di; - coded = if s < 0 { -mag } else { mag }; - } else { - fs += LAPLACE_MINP; - if s == 0 { - fl += fs; - } - } - } - enc.encode_bin(fl, fl + fs, 15); - coded -} - -/// `quant_coarse_energy` for one prediction mode. `e` holds the target log2 energies (relative -/// to `E_MEANS`), `old_e` the quantised energies, updated in place. `budget` is the frame size in -/// bits. -pub fn quant_coarse_energy(frame: CeltFrame, e: &[f32; 2 * NB_EBANDS], old_e: &mut [f32; 2 * NB_EBANDS], intra: bool, enc: &mut RangeEncoder, budget: i32) { - let CeltFrame { start, end, channels: c, lm } = frame; - let prob = &E_PROB_MODEL[lm][intra as usize]; - let (coef, beta) = if intra { (0.0, BETA_INTRA) } else { (PRED_COEF[lm], BETA_COEF[lm]) }; - let mut prev = [0f32; 2]; - for i in start..end { - for ch in 0..c { - let idx = i + ch * NB_EBANDS; - let oldc = old_e[idx].max(-9.0); - let x = e[idx]; - let f = x - coef * oldc - prev[ch]; - let mut qi = (f + 0.5).floor().clamp(-64.0, 64.0) as i32; - let tell = enc.tell(); - // Keep a few bits per remaining band in reserve when the budget runs out. - let bits_left = budget - tell - 3 * c as i32 * (end - i) as i32; - if i != start && bits_left < 30 { - if bits_left < 24 { - qi = qi.min(1); - } - if bits_left < 16 { - qi = qi.max(-1); - } - } - if budget - tell >= 15 { - let pi = 2 * i.min(20); - qi = laplace_encode(enc, qi, (prob[pi] as u32) << 7, (prob[pi + 1] as u32) << 6); - } else if budget - tell >= 2 { - qi = qi.clamp(-1, 1); - enc.icdf(if qi < 0 { (-2 * qi - 1) as usize } else { (2 * qi) as usize }, &SMALL_ENERGY_ICDF, 2); - } else if budget - tell >= 1 { - qi = qi.clamp(-1, 0); - enc.bit_logp(qi == -1, 1); - } else { - qi = -1; - } - let q = qi as f32; - old_e[idx] = oldc; - let tmp = coef * old_e[idx] + prev[ch] + q; - old_e[idx] = tmp; - prev[ch] = prev[ch] + q - beta * q; - } - } -} - -/// `quant_fine_energy`: raw bits refining each band's quantised energy. -pub fn quant_fine_energy(frame: CeltFrame, e: &[f32; 2 * NB_EBANDS], old_e: &mut [f32; 2 * NB_EBANDS], fine_quant: &[i32; NB_EBANDS], enc: &mut RangeEncoder) { - let CeltFrame { start, end, channels: c, .. } = frame; - for i in start..end { - let fq = fine_quant[i]; - if fq <= 0 { - continue; - } - for ch in 0..c { - let idx = i + ch * NB_EBANDS; - let err = e[idx] - old_e[idx]; - let levels = 1i32 << fq; - let q2 = (((err + 0.5) * levels as f32).floor() as i32).clamp(0, levels - 1); - enc.bits(q2 as u32, fq as u32); - let offset = (q2 as f32 + 0.5) * (1 << (14 - fq)) as f32 / 16384.0 - 0.5; - old_e[idx] += offset; - } - } -} - -/// `quant_energy_finalise`: spends the bits left at the end of the frame on one more bit of -/// energy resolution per band, in priority order. -pub fn quant_energy_finalise( - frame: CeltFrame, - e: &[f32; 2 * NB_EBANDS], - old_e: &mut [f32; 2 * NB_EBANDS], - allocation: &Allocation, - mut bits_left: i32, - enc: &mut RangeEncoder, -) { - let CeltFrame { start, end, channels: c, .. } = frame; - let Allocation { fine_quant, fine_priority, .. } = allocation; - for prio in 0..2 { - let mut i = start; - while i < end && bits_left >= c as i32 { - if fine_quant[i] >= MAX_FINE_BITS || fine_priority[i] != prio { - i += 1; - continue; - } - for ch in 0..c { - let idx = i + ch * NB_EBANDS; - let q2 = (e[idx] - old_e[idx] >= 0.0) as u32; - enc.bits(q2, 1); - let offset = (q2 as f32 - 0.5) * (1 << (14 - fine_quant[i] - 1)) as f32 / 16384.0; - old_e[idx] += offset; - bits_left -= 1; - } - i += 1; - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::range::dec::RangeDecoder; - - /// Laplace decoder of RFC 6716 §4.3.2.1 (as in FilmCraft's decoder). - fn laplace_decode(dec: &mut RangeDecoder, mut fs: u32, decay: u32) -> i32 { - let mut val = 0i32; - let fm = dec.decode(32768); - let mut fl = 0u32; - if fm >= fs { - val += 1; - fl = fs; - fs = laplace_get_freq1(fs, decay) + LAPLACE_MINP; - while fs > LAPLACE_MINP && fm >= fl + 2 * fs { - fs *= 2; - fl += fs; - fs = (((fs - 2 * LAPLACE_MINP) * decay) >> 15) + LAPLACE_MINP; - val += 1; - } - if fs <= LAPLACE_MINP { - let di = (fm - fl) >> 1; - val += di as i32; - fl += 2 * di * LAPLACE_MINP; - } - if fm < fl + fs { - val = -val; - } else { - fl += fs; - } - } - dec.update(fl, (fl + fs).min(32768), 32768); - val - } - - #[test] - fn laplace_roundtrip_all_models() { - for lm in 0..4 { - for intra in 0..2 { - for band in 0..21 { - let prob = &E_PROB_MODEL[lm][intra]; - let (fs, decay) = ((prob[2 * band] as u32) << 7, (prob[2 * band + 1] as u32) << 6); - let vals: Vec = (-64..=64).collect(); - let mut e = RangeEncoder::new(); - let coded: Vec = vals.iter().map(|&v| laplace_encode(&mut e, v, fs, decay)).collect(); - let size = (e.tell() as usize).div_ceil(8); - let buf = e.done(size); - let mut d = RangeDecoder::new(&buf); - for (&v, &c) in vals.iter().zip(&coded) { - assert!(c == v || (c.signum() == v.signum() && c.abs() < v.abs()), "clamp {v} -> {c}"); - assert_eq!(laplace_decode(&mut d, fs, decay), c, "lm={lm} intra={intra} band={band} v={v}"); - } - } - } - } - } -} diff --git a/crates/opusenc/src/lib.rs b/crates/opusenc/src/lib.rs deleted file mode 100644 index b4346ebd6..000000000 --- a/crates/opusenc/src/lib.rs +++ /dev/null @@ -1,553 +0,0 @@ -//! Clean-room pure-Rust Opus encoder (RFC 6716 SILK, hybrid and CELT modes; RFC 7845 `OpusHead`). -//! -//! Produces 20 ms Opus packets from 48 kHz float input, mono or stereo. The coding mode and -//! audio bandwidth are chosen once per stream from the per-channel bitrate and the -//! [`Application`] (see the crate README for the table): -//! -//! - **SILK** (narrowband/mediumband/wideband): linear-predictive speech coding at an internal -//! rate of 8/12/16 kHz; packet sizes vary around the target bitrate. -//! - **Hybrid** (super-wideband/fullband): SILK wideband codes 0–8 kHz and CELT codes the bands -//! above in the same range-coded frame; constant packet size. -//! - **CELT** (fullband): MDCT transform coding; constant packet size. -//! -//! Layer L0: no dependencies beyond `std`; no `unsafe`; builds for `wasm32-unknown-unknown`. -//! -//! ``` -//! use effectcraft_opusenc::{Application, Mode, OpusEncoder}; -//! let mut enc = OpusEncoder::new(2, 128_000); -//! let pcm = vec![0.0f32; OpusEncoder::FRAME_SIZE * 2]; -//! let packet = enc.encode_float(&pcm); -//! assert_eq!(packet[0] >> 3, 31); // CELT-only, fullband, 20 ms -//! assert_eq!(enc.opus_head().len(), 19); -//! let voip = OpusEncoder::with_application(1, 16_000, Application::Voip); -//! assert_eq!(voip.mode(), Mode::Silk); -//! ``` - -#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] - -mod bands; -mod energy; -mod mdct; -mod range; -mod rate; -mod resample; -mod silk; -mod tables; - -use std::sync::OnceLock; - -use bands::{BandCoding, SPREAD_NORMAL, quant_all_bands}; -use energy::{quant_coarse_energy, quant_energy_finalise, quant_fine_energy}; -use mdct::Mdct; -use range::{BITRES, RangeEncoder}; -use rate::{AllocationInput, Mode as CeltMode, compute_allocation}; -use resample::Downsampler; -use silk::SilkEncoder; -use tables::{E_MEANS, EBANDS, NB_EBANDS, OVERLAP, PREEMPH, SPREAD_ICDF, TF_SELECT_TABLE, TRIM_ICDF}; - -/// Band range, channel count and transform size shared by CELT coding stages. -#[derive(Clone, Copy)] -struct CeltFrame { - start: usize, - end: usize, - channels: usize, - lm: usize, -} - -/// Samples per channel in one 20 ms frame at 48 kHz. -const N: usize = 960; -/// LM of a 20 ms frame (8 short blocks). -const LM: usize = 3; -/// Smallest CELT payload the encoder produces (bytes). -const MIN_FRAME_BYTES: usize = 16; -/// Largest payload allowed in one frame (RFC 6716 §3.4, R2). -const MAX_FRAME_BYTES: usize = 1275; -/// First CELT band coded in hybrid frames (8 kHz). -const HYBRID_START_BAND: usize = 17; - -fn celt_mode() -> &'static CeltMode { - static MODE: OnceLock = OnceLock::new(); - MODE.get_or_init(CeltMode::new) -} - -/// Intended use of the stream; selects the mode/bandwidth table. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] -pub enum Application { - /// General audio (music, mixed content): CELT unless the bitrate is low. - #[default] - Audio, - /// Speech: SILK and hybrid over a wider bitrate range, narrower bandwidths at low rates. - Voip, -} - -/// Opus coding mode (RFC 6716 §2). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum Mode { - /// MDCT transform coding only. - Celt, - /// Linear-prediction coding only. - Silk, - /// SILK below 8 kHz plus CELT above. - Hybrid, -} - -/// Coded audio bandwidth (RFC 6716 §2, Table 1). -#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum Bandwidth { - /// 4 kHz (8 kHz sampling). - Narrowband, - /// 6 kHz (12 kHz sampling). - Mediumband, - /// 8 kHz (16 kHz sampling). - Wideband, - /// 12 kHz (24 kHz sampling). - SuperWideband, - /// 20 kHz (48 kHz sampling). - Fullband, -} - -/// Mode and bandwidth for a per-channel bitrate (bits per second per channel). -fn choose_mode(app: Application, per_channel: u32) -> (Mode, Bandwidth) { - match app { - Application::Voip => match per_channel { - 0..10_000 => (Mode::Silk, Bandwidth::Narrowband), - 10_000..12_000 => (Mode::Silk, Bandwidth::Mediumband), - 12_000..18_000 => (Mode::Silk, Bandwidth::Wideband), - 18_000..28_000 => (Mode::Hybrid, Bandwidth::SuperWideband), - 28_000..40_000 => (Mode::Hybrid, Bandwidth::Fullband), - _ => (Mode::Celt, Bandwidth::Fullband), - }, - Application::Audio => match per_channel { - 0..16_000 => (Mode::Silk, Bandwidth::Wideband), - 16_000..36_000 => (Mode::Hybrid, Bandwidth::Fullband), - _ => (Mode::Celt, Bandwidth::Fullband), - }, - } -} - -/// SILK side of a SILK-only or hybrid stream. -struct SilkPath { - enc: SilkEncoder, - down: Vec, - /// Bits per frame aimed at (excluding the TOC byte in SILK-only mode). - target_bits: f64, - /// Bits saved (positive) or overspent by previous frames (SILK-only mode). - reservoir: f64, -} - -/// Opus encoder for one mono or stereo stream at 48 kHz. -pub struct OpusEncoder { - channels: usize, - application: Application, - mode: Mode, - bandwidth: Bandwidth, - /// Requested bitrate (clamped), bits per second. - bitrate_bps: u32, - /// Payload bytes per packet in CELT and hybrid modes (the packet is one byte longer: the - /// TOC). - frame_bytes: usize, - mdct: Mdct, - /// Last input sample of each channel (pre-emphasis filter memory, ×32768). - preemph_mem: [f32; 2], - /// Last `OVERLAP` pre-emphasised samples of each channel. - hist: Vec, - /// Quantised band energies, exactly as the decoder holds them. - old_band_e: [f32; 2 * NB_EBANDS], - block: Vec, - freq: Vec, - silk: Option, -} - -impl OpusEncoder { - /// Samples per channel per packet (20 ms at 48 kHz). - pub const FRAME_SIZE: usize = N; - - /// Creates a general-audio encoder ([`Application::Audio`]) for `channels` (1 or 2) - /// channels of 48 kHz audio at `bitrate_bps` (total for all channels). - pub fn new(channels: u8, bitrate_bps: u32) -> Self { - Self::with_application(channels, bitrate_bps, Application::Audio) - } - - /// Creates an encoder for `channels` (1 or 2) channels of 48 kHz audio at `bitrate_bps` - /// (total for all channels; clamped to 6 kb/s per channel – 510 kb/s), choosing the mode - /// and bandwidth for `application`. - pub fn with_application(channels: u8, bitrate_bps: u32, application: Application) -> Self { - let c = channels.max(1) as u32; - let (mode, bandwidth) = choose_mode(application, bitrate_bps.clamp(6_000 * c, 510_000) / c); - Self::build(channels, bitrate_bps, application, mode, bandwidth) - } - - /// Creates an encoder with an explicit mode and bandwidth instead of the application's - /// table. Valid combinations: SILK with narrowband, mediumband or wideband; hybrid with - /// super-wideband or fullband; CELT with fullband. - /// - /// # Panics - /// On any other combination, or when `channels` is not 1 or 2. - pub fn with_mode(channels: u8, bitrate_bps: u32, mode: Mode, bandwidth: Bandwidth) -> Self { - let ok = match mode { - Mode::Silk => bandwidth <= Bandwidth::Wideband, - Mode::Hybrid => bandwidth >= Bandwidth::SuperWideband, - Mode::Celt => bandwidth == Bandwidth::Fullband, - }; - assert!(ok, "unsupported mode/bandwidth combination {mode:?}/{bandwidth:?}"); - Self::build(channels, bitrate_bps, Application::Audio, mode, bandwidth) - } - - fn build(channels: u8, bitrate_bps: u32, application: Application, mode: Mode, bandwidth: Bandwidth) -> Self { - assert!(channels == 1 || channels == 2, "Opus family-0 streams have 1 or 2 channels"); - let c = channels as usize; - let bitrate_bps = bitrate_bps.clamp(6_000 * c as u32, 510_000); - let packet_bytes = (bitrate_bps as usize).div_ceil(400); - let frame_bytes = packet_bytes.saturating_sub(1).clamp(MIN_FRAME_BYTES, MAX_FRAME_BYTES); - let silk = match mode { - Mode::Celt => None, - Mode::Silk | Mode::Hybrid => { - let fs_khz = match bandwidth { - Bandwidth::Narrowband => 8, - Bandwidth::Mediumband => 12, - _ => 16, - }; - let target_bits = if mode == Mode::Silk { - bitrate_bps as f64 / 50.0 - 8.0 - } else { - // SILK gets most of a hybrid packet; CELT codes 8 kHz and up with the rest. - let per = (bitrate_bps / c as u32) as f64; - let share = if bandwidth == Bandwidth::SuperWideband { 0.72 } else { 0.62 }; - c as f64 * (per * share).min(per - 6_000.0).max(per * 0.5) / 50.0 - }; - Some(SilkPath { - enc: SilkEncoder::new(fs_khz, c), - down: (0..c).map(|_| Downsampler::new(fs_khz as u32 * 1000)).collect(), - target_bits, - reservoir: 0.0, - }) - } - }; - OpusEncoder { - channels: c, - application, - mode, - bandwidth, - bitrate_bps, - frame_bytes, - mdct: Mdct::new(N), - preemph_mem: [0.0; 2], - hist: vec![0.0; c * OVERLAP], - old_band_e: [0.0; 2 * NB_EBANDS], - block: vec![0.0; N + OVERLAP], - freq: vec![0.0; c * N], - silk, - } - } - - /// Number of channels. - pub fn channels(&self) -> u8 { - self.channels as u8 - } - - /// The application the encoder was created for. - pub fn application(&self) -> Application { - self.application - } - - /// Coding mode of every packet of the stream. - pub fn mode(&self) -> Mode { - self.mode - } - - /// Coded audio bandwidth of every packet of the stream. - pub fn bandwidth(&self) -> Bandwidth { - self.bandwidth - } - - /// Bitrate in bits per second: the constant packet size × 50 packets per second in CELT - /// and hybrid modes, the (average) target in SILK mode. - pub fn bitrate(&self) -> u32 { - match self.mode { - Mode::Silk => self.bitrate_bps, - _ => ((self.frame_bytes + 1) * 8 * 50) as u32, - } - } - - /// Samples at 48 kHz the decoder must discard from the start of the stream (the `OpusHead` - /// pre-skip): the encoder's total delay. CELT: the 120-sample MDCT overlap. SILK/hybrid: - /// the decimator (83 samples, 88 for narrowband) plus the decoder's SILK delay (one - /// internal-rate sample and the resampler delay of RFC 6716 Table 54), which also rounds - /// to 120 samples. - pub fn pre_skip(&self) -> u16 { - let (fs, table54_ms) = match (self.mode, self.bandwidth) { - (Mode::Celt, _) => return OVERLAP as u16, - (_, Bandwidth::Narrowband) => (8_000, 0.538), - (_, Bandwidth::Mediumband) => (12_000, 0.692), - _ => (16_000, 0.706), - }; - (resample::delay(fs) as f64 + 48_000.0 / fs as f64 + table54_ms * 48.0).round() as u16 - } - - /// The 19-byte `OpusHead` identification header (RFC 7845 §5.1): version 1, channel count, - /// pre-skip, input sample rate 48000, output gain 0, channel mapping family 0. - pub fn opus_head(&self) -> Vec { - let mut h = Vec::with_capacity(19); - h.extend_from_slice(b"OpusHead"); - h.push(1); - h.push(self.channels as u8); - h.extend_from_slice(&self.pre_skip().to_le_bytes()); - h.extend_from_slice(&48_000u32.to_le_bytes()); - h.extend_from_slice(&0i16.to_le_bytes()); - h.push(0); - h - } - - /// TOC byte (RFC 6716 §3.1, Table 2) of a 20 ms single-frame packet. - fn toc(&self) -> u8 { - let config: u8 = match (self.mode, self.bandwidth) { - (Mode::Silk, Bandwidth::Narrowband) => 1, - (Mode::Silk, Bandwidth::Mediumband) => 5, - (Mode::Silk, _) => 9, - (Mode::Hybrid, Bandwidth::SuperWideband) => 13, - (Mode::Hybrid, _) => 15, - (Mode::Celt, _) => 31, - }; - (config << 3) | if self.channels == 2 { 4 } else { 0 } - } - - /// Encodes one 20 ms frame of interleaved f32 samples in [-1, 1] (exactly - /// `FRAME_SIZE * channels` values) and returns one Opus packet. - pub fn encode_float(&mut self, pcm: &[f32]) -> Vec { - let c = self.channels; - assert_eq!(pcm.len(), N * c, "encode_float takes exactly FRAME_SIZE samples per channel"); - let mut packet = vec![self.toc()]; - match self.mode { - Mode::Celt => { - let (log_e, silence) = self.celt_analysis(pcm); - let len = self.frame_bytes; - packet.extend_from_slice(&self.encode_celt(RangeEncoder::new(), len, 0..NB_EBANDS, &log_e, silence)); - } - Mode::Silk => { - let x = self.silk_input(pcm); - // The SILK state exists whenever the mode uses SILK (set with the mode). - if let Some(sp) = self.silk.as_mut() { - let target = sp.target_bits + 0.25 * sp.reservoir; - let mut enc = RangeEncoder::new(); - sp.enc.encode(&x, target.max(24.0), (MAX_FRAME_BYTES * 8) as i32, &mut enc); - let bytes = (enc.tell() as usize).div_ceil(8).max(2); - let lim = 4.0 * sp.target_bits; - sp.reservoir = (sp.reservoir + sp.target_bits - (bytes * 8) as f64).clamp(-lim, lim); - packet.extend_from_slice(&enc.done(bytes)); - } - } - Mode::Hybrid => { - let x = self.silk_input(pcm); - let len = self.frame_bytes; - let total = (len * 8) as i32; - let celt_min = (total / 5).max(80); - let mut enc = RangeEncoder::new(); - if let Some(sp) = self.silk.as_mut() { - sp.enc.encode(&x, sp.target_bits, total - celt_min, &mut enc); - } - // No redundancy (RFC 6716 §4.5.1); the flag is present when there is room. - if enc.tell() + 17 + 20 <= total { - enc.bit_logp(false, 12); - } - let (log_e, _) = self.celt_analysis(pcm); - let end = if self.bandwidth == Bandwidth::SuperWideband { 19 } else { NB_EBANDS }; - packet.extend_from_slice(&self.encode_celt(enc, len, HYBRID_START_BAND..end, &log_e, false)); - } - } - packet - } - - /// Decimates the input to the SILK internal rate (16-bit scale), one vector per channel. - fn silk_input(&mut self, pcm: &[f32]) -> Vec> { - let c = self.channels; - let Some(sp) = self.silk.as_mut() else { return vec![vec![]; c] }; - let mut out = Vec::with_capacity(c); - let mut tmp = vec![0f32; N]; - for ch in 0..c { - for (j, t) in tmp.iter_mut().enumerate() { - let s = pcm[j * c + ch]; - *t = if s.is_finite() { s.clamp(-1.0, 1.0) * 32768.0 } else { 0.0 }; - } - let mut y = Vec::with_capacity(N / 3); - sp.down[ch].process(&tmp, &mut y); - out.push(y); - } - out - } - - /// Pre-emphasis, the MDCT, band energies (log2, relative to `E_MEANS`) and normalised - /// bands; returns the energies and whether the frame is digital silence. - fn celt_analysis(&mut self, pcm: &[f32]) -> ([f32; 2 * NB_EBANDS], bool) { - let c = self.channels; - let mut log_e = [0f32; 2 * NB_EBANDS]; - let mut peak = 0f32; - for ch in 0..c { - self.block[..OVERLAP].copy_from_slice(&self.hist[ch * OVERLAP..(ch + 1) * OVERLAP]); - let mut mem = self.preemph_mem[ch]; - for j in 0..N { - let s = pcm[j * c + ch]; - let s = if s.is_finite() { s.clamp(-2.0, 2.0) * 32768.0 } else { 0.0 }; - let v = s - PREEMPH * mem; - mem = s; - self.block[OVERLAP + j] = v; - } - self.preemph_mem[ch] = mem; - self.hist[ch * OVERLAP..(ch + 1) * OVERLAP].copy_from_slice(&self.block[N..]); - peak = self.block.iter().fold(peak, |p, v| p.max(v.abs())); - let freq = &mut self.freq[ch * N..(ch + 1) * N]; - self.mdct.forward(&self.block, freq); - for i in 0..NB_EBANDS { - let lo = (EBANDS[i] as usize) << LM; - let hi = (EBANDS[i + 1] as usize) << LM; - let e = (1e-27f32 + freq[lo..hi].iter().map(|v| v * v).sum::()).sqrt(); - log_e[ch * NB_EBANDS + i] = e.log2() - E_MEANS[i]; - let g = 1.0 / e; - for v in freq[lo..hi].iter_mut() { - *v *= g; - } - } - } - (log_e, peak < 1e-4) - } - - /// Codes one CELT frame (RFC 6716 §4.3, in bitstream order) of `len` bytes into `enc` - /// (which already holds the SILK frame in hybrid mode), coding bands `start..end`, and - /// finalises the frame. - fn encode_celt(&mut self, mut enc: RangeEncoder, len: usize, bands: std::ops::Range, log_e: &[f32; 2 * NB_EBANDS], silence: bool) -> Vec { - let m = celt_mode(); - let c = self.channels; - let frame = CeltFrame { start: bands.start, end: bands.end, channels: c, lm: LM }; - let CeltFrame { start, end, .. } = frame; - if c == 1 { - for i in 0..NB_EBANDS { - self.old_band_e[i] = self.old_band_e[i].max(self.old_band_e[NB_EBANDS + i]); - } - } - if silence && start == 0 { - // The silence flag; the decoder treats every remaining bit as consumed. - enc.bit_logp(true, 15); - self.old_band_e = [-28.0; 2 * NB_EBANDS]; - return enc.done(2); - } - let total_bits_raw = len as i32 * 8; - if enc.tell() == 1 { - enc.bit_logp(false, 15); - } - // No pitch post-filter (only signalled in CELT-only frames). - if start == 0 && enc.tell() + 16 <= total_bits_raw { - enc.bit_logp(false, 1); - } - // Long blocks only. - if enc.tell() + 3 <= total_bits_raw { - enc.bit_logp(false, 3); - } - // Coarse energy, choosing intra or inter prediction by trial (whichever is cheaper). - if enc.tell() + 3 <= total_bits_raw { - let mut enc_intra = enc.clone(); - let mut old_intra = self.old_band_e; - enc_intra.bit_logp(true, 3); - quant_coarse_energy(frame, log_e, &mut old_intra, true, &mut enc_intra, total_bits_raw); - enc.bit_logp(false, 3); - let mut old_inter = self.old_band_e; - quant_coarse_energy(frame, log_e, &mut old_inter, false, &mut enc, total_bits_raw); - if enc_intra.tell_frac() < enc.tell_frac() { - enc = enc_intra; - self.old_band_e = old_intra; - } else { - self.old_band_e = old_inter; - } - } else { - quant_coarse_energy(frame, log_e, &mut self.old_band_e, false, &mut enc, total_bits_raw); - } - // TF resolution: no changes. - { - let mut budget = total_bits_raw; - let mut tell = enc.tell(); - let mut logp = 4; - let tf_select_rsv = LM > 0 && tell + logp < budget; - budget -= tf_select_rsv as i32; - for _ in start..end { - if tell + logp <= budget { - enc.bit_logp(false, logp as u32); - tell = enc.tell(); - } - logp = 5; - } - if tf_select_rsv && TF_SELECT_TABLE[LM][0] != TF_SELECT_TABLE[LM][2] { - enc.bit_logp(false, 1); - } - } - if enc.tell() + 4 <= total_bits_raw { - enc.icdf(SPREAD_NORMAL, &SPREAD_ICDF, 5); - } - // Dynamic allocation: no boosts. - let cap = m.init_caps(LM, c); - let offsets = [0i32; NB_EBANDS]; - let total_bits = total_bits_raw << BITRES; - let mut tellf = enc.tell_frac(); - for &cp in cap.iter().take(end).skip(start) { - if tellf + (6 << BITRES) < total_bits && 0 < cp { - enc.bit_logp(false, 6); - tellf = enc.tell_frac(); - } - } - let alloc_trim = 5; - if tellf + (6 << BITRES) <= total_bits { - enc.icdf(alloc_trim as usize, &TRIM_ICDF, 7); - } - let bits = (total_bits_raw << BITRES) - enc.tell_frac() - 1; - let alloc = compute_allocation(m, frame, AllocationInput { offsets: &offsets, cap: &cap, trim: alloc_trim, bits }, &mut enc); - quant_fine_energy(frame, log_e, &mut self.old_band_e, &alloc.fine_quant, &mut enc); - quant_all_bands(m, frame, &self.freq, N, &alloc, BandCoding { spread: SPREAD_NORMAL, total_bits: total_bits_raw << BITRES }, &mut enc); - let bits_left = total_bits_raw - enc.tell(); - quant_energy_finalise(frame, log_e, &mut self.old_band_e, &alloc, bits_left, &mut enc); - debug_assert!(enc.tell() <= total_bits_raw, "frame overflow: {} > {}", enc.tell(), total_bits_raw); - if c == 1 { - let (a, b) = self.old_band_e.split_at_mut(NB_EBANDS); - b.copy_from_slice(a); - } - // The decoder forgets the energies of bands it did not code. - for ch in 0..2 { - for i in (0..start).chain(end..NB_EBANDS) { - self.old_band_e[ch * NB_EBANDS + i] = 0.0; - } - } - enc.done(len) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn opus_head_layout() { - let e = OpusEncoder::new(2, 96_000); - let h = e.opus_head(); - assert_eq!(&h[..8], b"OpusHead"); - assert_eq!(h[8], 1); - assert_eq!(h[9], 2); - assert_eq!(u16::from_le_bytes([h[10], h[11]]), e.pre_skip()); - assert_eq!(u32::from_le_bytes([h[12], h[13], h[14], h[15]]), 48_000); - assert_eq!(&h[16..], &[0, 0, 0]); - } - - #[test] - fn packet_sizes_follow_bitrate() { - for (ch, rate) in [(1u8, 64_000u32), (2, 128_000), (2, 256_000)] { - let mut e = OpusEncoder::new(ch, rate); - let pcm: Vec = (0..N * ch as usize).map(|i| (i as f32 * 0.05).sin() * 0.5).collect(); - let p = e.encode_float(&pcm); - assert_eq!(p.len(), rate as usize / 400); - assert_eq!(p[0], 0xF8 | if ch == 2 { 4 } else { 0 }); - assert_eq!(e.bitrate(), rate); - } - } - - #[test] - fn silence_is_a_tiny_packet() { - let mut e = OpusEncoder::new(1, 64_000); - let p = e.encode_float(&vec![0.0; N]); - assert_eq!(p.len(), 3); - } -} diff --git a/crates/opusenc/src/mdct.rs b/crates/opusenc/src/mdct.rs deleted file mode 100644 index 131c4a7a1..000000000 --- a/crates/opusenc/src/mdct.rs +++ /dev/null @@ -1,363 +0,0 @@ -//! Forward MDCT with the CELT low-overlap window (RFC 6716 §4.3.7, run in the analysis -//! direction). -//! -//! A 20 ms frame is a 1920-point MDCT (960 coefficients) whose window is zero for 420 samples, -//! rises over the 120-sample overlap, is flat for 840 samples, falls over the next 120 samples -//! and is zero again for the last 420. The input block is therefore the 120 overlap samples kept -//! from the previous frame followed by the 960 new samples. The MDCT is folded into a DCT-IV, -//! which is computed with an N/2-point complex FFT. - -use crate::tables::OVERLAP; - -#[derive(Clone, Copy, Default, Debug)] -pub struct Cpx { - pub re: f32, - pub im: f32, -} - -impl Cpx { - #[inline] - fn mul(self, o: Cpx) -> Cpx { - Cpx { re: self.re * o.re - self.im * o.im, im: self.re * o.im + self.im * o.re } - } - #[inline] - fn add(self, o: Cpx) -> Cpx { - Cpx { re: self.re + o.re, im: self.im + o.im } - } - #[inline] - fn sub(self, o: Cpx) -> Cpx { - Cpx { re: self.re - o.re, im: self.im - o.im } - } -} - -/// Mixed-radix (2, 3, 4, 5) forward complex FFT, unscaled (decimation in time, recursive). -pub struct Fft { - n: usize, - factors: Vec, - twiddle: Vec, -} - -impl Fft { - pub fn new(n: usize) -> Fft { - let mut factors = Vec::new(); - let mut m = n; - for p in [4usize, 2, 3, 5] { - while m.is_multiple_of(p) { - factors.push(p); - m /= p; - } - } - assert_eq!(m, 1, "unsupported FFT size {n}"); - let twiddle = (0..n) - .map(|k| { - let ph = -2.0 * std::f64::consts::PI * k as f64 / n as f64; - Cpx { re: ph.cos() as f32, im: ph.sin() as f32 } - }) - .collect(); - Fft { n, factors, twiddle } - } - - pub fn process(&self, data: &mut [Cpx], scratch: &mut Vec) { - scratch.clear(); - scratch.extend_from_slice(&data[..self.n]); - self.rec(&mut data[..self.n], scratch, 1, self.n, 0, 1); - } - - fn rec(&self, out: &mut [Cpx], inp: &[Cpx], in_stride: usize, n: usize, fi: usize, tw_stride: usize) { - let p = self.factors[fi]; - let m = n / p; - if m == 1 { - for (i, o) in out.iter_mut().enumerate().take(p) { - *o = inp[i * in_stride]; - } - } else { - for q in 0..p { - self.rec(&mut out[q * m..(q + 1) * m], &inp[q * in_stride..], in_stride * p, m, fi + 1, tw_stride * p); - } - } - // The twiddle index q * k * tw_stride is always below n, so no modulo is needed. - let tw = &self.twiddle; - match p { - 2 => { - for k in 0..m { - let a0 = out[k]; - let a1 = out[m + k].mul(tw[k * tw_stride]); - out[k] = a0.add(a1); - out[m + k] = a0.sub(a1); - } - } - 4 => { - for k in 0..m { - let t0 = out[k]; - let t1 = out[m + k].mul(tw[k * tw_stride]); - let t2 = out[2 * m + k].mul(tw[2 * k * tw_stride]); - let t3 = out[3 * m + k].mul(tw[3 * k * tw_stride]); - let (s0, d0) = (t0.add(t2), t0.sub(t2)); - let (s1, d1) = (t1.add(t3), t1.sub(t3)); - out[k] = s0.add(s1); - out[2 * m + k] = s0.sub(s1); - // The odd outputs combine d0 with -j * d1 = (d1.im, -d1.re) and its negative. - out[m + k] = Cpx { re: d0.re + d1.im, im: d0.im - d1.re }; - out[3 * m + k] = Cpx { re: d0.re - d1.im, im: d0.im + d1.re }; - } - } - 3 => { - // Imaginary part of exp(-2 pi i / 3) = -sqrt(3) / 2. - let h = tw[self.n / 3].im; - for k in 0..m { - let t0 = out[k]; - let t1 = out[m + k].mul(tw[k * tw_stride]); - let t2 = out[2 * m + k].mul(tw[2 * k * tw_stride]); - let (s, d) = (t1.add(t2), t1.sub(t2)); - let a = Cpx { re: t0.re - 0.5 * s.re, im: t0.im - 0.5 * s.im }; - out[k] = t0.add(s); - // j * h * d = (-h * d.im, h * d.re) - out[m + k] = Cpx { re: a.re - h * d.im, im: a.im + h * d.re }; - out[2 * m + k] = Cpx { re: a.re + h * d.im, im: a.im - h * d.re }; - } - } - _ => { - // Generic DFT butterfly (radix 5, once per transform). - let roots: [Cpx; 5] = std::array::from_fn(|q| if q < p { tw[q * (self.n / p)] } else { Cpx::default() }); - let mut t = [Cpx::default(); 5]; - for k in 0..m { - t[0] = out[k]; - for q in 1..p { - t[q] = out[q * m + k].mul(tw[q * k * tw_stride]); - } - for q2 in 0..p { - let mut acc = t[0]; - for q in 1..p { - acc = acc.add(t[q].mul(roots[(q * q2) % p])); - } - out[q2 * m + k] = acc; - } - } - } - } - } -} - -/// Forward MDCT producing `n` coefficients from a block of `n + OVERLAP` samples. -pub struct Mdct { - /// Number of coefficients (half the MDCT length). - n: usize, - fft: Fft, - pre: Vec, - post: Vec, - /// Rising half of the low-overlap window (RFC 6716 §4.3.7). - pub window: [f32; OVERLAP], - scale: f32, - z: Vec, - scratch: Vec, - v: Vec, -} - -impl Mdct { - pub fn new(n: usize) -> Mdct { - let n2 = n / 2; - let pi = std::f64::consts::PI; - let pre = (0..n2) - .map(|m| { - let ph = -pi * m as f64 / n as f64; - Cpx { re: ph.cos() as f32, im: ph.sin() as f32 } - }) - .collect(); - let post = (0..n2) - .map(|p| { - let ph = -pi * (p as f64 + 0.25) / n as f64; - Cpx { re: ph.cos() as f32, im: ph.sin() as f32 } - }) - .collect(); - let mut window = [0f32; OVERLAP]; - for (i, w) in window.iter_mut().enumerate() { - let x = std::f64::consts::FRAC_PI_2 * (i as f64 + 0.5) / OVERLAP as f64; - let s = x.sin(); - *w = (std::f64::consts::FRAC_PI_2 * s * s).sin() as f32; - } - Mdct { n, fft: Fft::new(n2), pre, post, window, scale: 2.0 / n as f32, z: Vec::new(), scratch: Vec::new(), v: vec![0.0; n] } - } - - /// Transforms `block` (`n + OVERLAP` samples: the previous frame's last `OVERLAP` samples, then - /// `n` new ones) into `out[..n]`, scaled so that the RFC 6716 decoder's inverse MDCT and - /// overlap-add reproduce the input. - pub fn forward(&mut self, block: &[f32], out: &mut [f32]) { - let n = self.n; - let n2 = n / 2; - debug_assert_eq!(block.len(), n + OVERLAP); - // Place the windowed block into the (virtual) 2n-sample MDCT input u at offset `pad`. - let pad = (n - OVERLAP) / 2; - let w = &self.window; - let u = |t: usize| -> f32 { - if t < pad || t >= pad + n + OVERLAP { - return 0.0; - } - let j = t - pad; - let g = if j < OVERLAP { - w[j] - } else if j >= n { - w[OVERLAP - 1 - (j - n)] - } else { - 1.0 - }; - block[j] * g - }; - // Fold to a DCT-IV input: v = (-c_r - d, a - b_r) over the four quarters of u. - for m in 0..n2 { - self.v[m] = -u(n + n2 - 1 - m) - u(n + n2 + m); - self.v[n2 + m] = u(m) - u(n2 + n2 - 1 - m); - } - // DCT-IV via an n/2-point complex FFT. - self.z.clear(); - for m in 0..n2 { - let wv = Cpx { re: self.v[2 * m], im: self.v[n - 1 - 2 * m] }; - self.z.push(wv.mul(self.pre[m])); - } - self.fft.process(&mut self.z, &mut self.scratch); - for p in 0..n2 { - let y = self.z[p].mul(self.post[p]); - out[2 * p] = y.re * self.scale; - out[n - 1 - 2 * p] = -y.im * self.scale; - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Direct MDCT definition X[k] = sum u[t] cos(pi/N (t + 1/2 + N/2)(k + 1/2)). - fn direct(block: &[f32], n: usize, window: &[f32; OVERLAP]) -> Vec { - let pad = (n - OVERLAP) / 2; - let mut u = vec![0f64; 2 * n]; - for (j, &b) in block.iter().enumerate() { - let g = if j < OVERLAP { - window[j] - } else if j >= n { - window[OVERLAP - 1 - (j - n)] - } else { - 1.0 - }; - u[pad + j] = (b * g) as f64; - } - (0..n) - .map(|k| { - (0..2 * n).map(|t| u[t] * (std::f64::consts::PI / n as f64 * (t as f64 + 0.5 + n as f64 / 2.0) * (k as f64 + 0.5)).cos()).sum::() * 2.0 - / n as f64 - }) - .collect() - } - - #[test] - fn fft_matches_dft() { - // Every radix combination, including the 480-point size of the 20 ms frame. - for &n in &[2usize, 3, 4, 5, 6, 8, 12, 15, 16, 20, 24, 30, 48, 60, 120, 240, 480] { - let fft = Fft::new(n); - let x: Vec = (0..n).map(|i| Cpx { re: ((i * 37 % 101) as f32 - 50.0) / 7.0, im: ((i * 53 % 89) as f32 - 44.0) / 9.0 }).collect(); - let mut y = x.clone(); - fft.process(&mut y, &mut Vec::new()); - for k in 0..n { - let (mut re, mut im) = (0f64, 0f64); - for (j, v) in x.iter().enumerate() { - let ph = -2.0 * std::f64::consts::PI * ((j * k) % n) as f64 / n as f64; - re += v.re as f64 * ph.cos() - v.im as f64 * ph.sin(); - im += v.re as f64 * ph.sin() + v.im as f64 * ph.cos(); - } - assert!((y[k].re as f64 - re).abs() < 2e-3 && (y[k].im as f64 - im).abs() < 2e-3, "n={n} k={k}: ({}, {}) vs ({re}, {im})", y[k].re, y[k].im); - } - } - } - - #[test] - fn matches_direct_formula() { - for &n in &[240usize, 960] { - let block: Vec = (0..n + OVERLAP).map(|i| ((i * 37 % 101) as f32 - 50.0) / 7.0).collect(); - let mut m = Mdct::new(n); - let mut out = vec![0f32; n]; - m.forward(&block, &mut out); - let d = direct(&block, n, &m.window); - for k in 0..n { - assert!((out[k] as f64 - d[k]).abs() < 1e-2, "n={n} k={k}: {} vs {}", out[k], d[k]); - } - } - } - - // ---- Replica of the RFC 6716 decoder inverse MDCT (as in FilmCraft's decoder) ---- - - fn imdct_backward(n_full: usize, input: &[f32], out: &mut [f32], window: &[f32]) { - let n2 = n_full >> 1; - let n4 = n_full >> 2; - let t: Vec = (0..n2).map(|i| (2.0 * std::f64::consts::PI * (i as f64 + 0.125) / n_full as f64).cos() as f32).collect(); - let fft = Fft::new(n4); - let mut z = Vec::new(); - for i in 0..n4 { - let x1 = input[2 * i]; - let x2 = input[n2 - 1 - 2 * i]; - let yr = x2 * t[i] + x1 * t[n4 + i]; - let yi = x1 * t[i] - x2 * t[n4 + i]; - z.push(Cpx { re: yi, im: yr }); - } - fft.process(&mut z, &mut Vec::new()); - let overlap = OVERLAP; - let base = overlap >> 1; - let y = &mut out[base..base + n2]; - for i in 0..n4.div_ceil(2) { - let front = z[i]; - let back = z[n4 - 1 - i]; - let (re, im) = (front.im, front.re); - let (t0, t1) = (t[i], t[n4 + i]); - let yr0 = re * t0 + im * t1; - let yi0 = re * t1 - im * t0; - let (re, im) = (back.im, back.re); - let (t0, t1) = (t[n4 - i - 1], t[n2 - i - 1]); - let yr1 = re * t0 + im * t1; - let yi1 = re * t1 - im * t0; - y[2 * i] = yr0; - y[n2 - 1 - 2 * i] = yi0; - y[n2 - 2 - 2 * i] = yr1; - y[2 * i + 1] = yi1; - } - for i in 0..overlap / 2 { - let x1 = out[overlap - 1 - i]; - let x2 = out[i]; - let w1 = window[i]; - let w2 = window[overlap - 1 - i]; - out[i] = x2 * w2 - x1 * w1; - out[overlap - 1 - i] = x2 * w1 + x1 * w2; - } - } - - /// MDCT analysis followed by the decoder's IMDCT + TDAC overlap-add reproduces the input - /// delayed by exactly `OVERLAP` samples. - #[test] - fn perfect_reconstruction_through_decoder_imdct() { - let n = 960; - let frames = 5; - let sig: Vec = (0..n * frames).map(|i| (i as f32 * 0.013).sin() * 1000.0 + ((i * 7919) % 211) as f32 - 105.0).collect(); - let mut m = Mdct::new(n); - let mut hist = vec![0f32; OVERLAP]; - // Decoder memory: [frame output n][folded tail OVERLAP/2] laid out like decode_mem. - let mut mem = vec![0f32; n + OVERLAP]; - let mut decoded = Vec::new(); - for f in 0..frames { - let mut block = hist.clone(); - block.extend_from_slice(&sig[f * n..(f + 1) * n]); - hist.copy_from_slice(&block[n..]); - let mut coefs = vec![0f32; n]; - m.forward(&block, &mut coefs); - // Shift: the previous folded tail (at n..n+OVERLAP/2) moves to 0..OVERLAP/2. - mem.copy_within(n..n + OVERLAP / 2, 0); - imdct_backward(2 * n, &coefs, &mut mem, &m.window); - decoded.extend_from_slice(&mem[..n]); - } - let mut err = 0f64; - let mut sum = 0f64; - for t in OVERLAP..n * frames { - let d = decoded[t] as f64 - sig[t - OVERLAP] as f64; - err += d * d; - sum += (sig[t - OVERLAP] as f64).powi(2); - } - let snr = 10.0 * (sum / err).log10(); - assert!(snr > 80.0, "reconstruction SNR {snr:.1} dB"); - } -} diff --git a/crates/opusenc/src/range.rs b/crates/opusenc/src/range.rs deleted file mode 100644 index daedd58ae..000000000 --- a/crates/opusenc/src/range.rs +++ /dev/null @@ -1,472 +0,0 @@ -//! Range encoder (RFC 6716 §5.1), the exact inverse of the §4.1 range decoder. -//! -//! Range-coded symbols are written from the front of the buffer and raw bits from the back; the -//! bit accounting ([`RangeEncoder::tell`], [`RangeEncoder::tell_frac`]) matches the decoder's, so -//! every budget decision the decoder takes can be mirrored exactly. - -const SYM_BITS: u32 = 8; -const CODE_BITS: u32 = 32; -const SYM_MAX: u32 = (1 << SYM_BITS) - 1; -const CODE_SHIFT: u32 = CODE_BITS - SYM_BITS - 1; -const CODE_TOP: u32 = 1 << (CODE_BITS - 1); -const CODE_BOT: u32 = CODE_TOP >> SYM_BITS; -/// Bit resolution of [`RangeEncoder::tell_frac`] (1/8 bit). -pub const BITRES: u32 = 3; - -/// Number of bits needed to represent `x` (0 for 0). -#[inline] -pub fn ilog(x: u32) -> i32 { - (32 - x.leading_zeros()) as i32 -} - -#[derive(Clone, Debug)] -pub struct RangeEncoder { - out: Vec, - end: Vec, - end_window: u32, - nend_bits: i32, - nbits_total: i32, - rng: u32, - low: u32, - rem: i32, - ext: u32, -} - -impl Default for RangeEncoder { - fn default() -> Self { - Self::new() - } -} - -impl RangeEncoder { - pub fn new() -> Self { - RangeEncoder { - out: Vec::new(), - end: Vec::new(), - end_window: 0, - nend_bits: 0, - nbits_total: (CODE_BITS + 1) as i32, - rng: CODE_TOP, - low: 0, - rem: -1, - ext: 0, - } - } - - /// Current range (equals the decoder's range after the same symbols). - #[cfg(test)] - pub fn rng(&self) -> u32 { - self.rng - } - - fn carry_out(&mut self, c: u32) { - if c != SYM_MAX { - let carry = c >> SYM_BITS; - if self.rem >= 0 { - self.out.push((self.rem as u32 + carry) as u8); - } - if self.ext > 0 { - let sym = (SYM_MAX + carry) & SYM_MAX; - for _ in 0..self.ext { - self.out.push(sym as u8); - } - self.ext = 0; - } - self.rem = (c & SYM_MAX) as i32; - } else { - self.ext += 1; - } - } - - #[inline] - fn normalize(&mut self) { - while self.rng <= CODE_BOT { - self.carry_out(self.low >> CODE_SHIFT); - self.low = (self.low << SYM_BITS) & (CODE_TOP - 1); - self.rng <<= SYM_BITS; - self.nbits_total += SYM_BITS as i32; - } - } - - /// Encodes the symbol with cumulative range `[fl, fh)` of total `ft`. - pub fn encode(&mut self, fl: u32, fh: u32, ft: u32) { - let r = self.rng / ft; - if fl > 0 { - self.low += self.rng - r * (ft - fl); - self.rng = r * (fh - fl); - } else { - self.rng -= r * (ft - fh); - } - self.normalize(); - } - - /// Like [`Self::encode`] with `ft = 1 << bits`. - pub fn encode_bin(&mut self, fl: u32, fh: u32, bits: u32) { - let r = self.rng >> bits; - let ft = 1u32 << bits; - if fl > 0 { - self.low += self.rng - r * (ft - fl); - self.rng = r * (fh - fl); - } else { - self.rng -= r * (ft - fh); - } - self.normalize(); - } - - /// Encodes a binary symbol whose probability of being 1 is `1/2^logp`. - pub fn bit_logp(&mut self, val: bool, logp: u32) { - let r = self.rng; - let s = r >> logp; - let r2 = r - s; - if val { - self.low += r2; - self.rng = s; - } else { - self.rng = r2; - } - self.normalize(); - } - - /// Encodes symbol `s` with an "inverse CDF" table (`ft = 1 << ftb`). - pub fn icdf(&mut self, s: usize, icdf: &[u8], ftb: u32) { - let r = self.rng >> ftb; - if s > 0 { - self.low += self.rng - r * icdf[s - 1] as u32; - self.rng = r * (icdf[s - 1] as u32 - icdf[s] as u32); - } else { - self.rng -= r * icdf[s] as u32; - } - self.normalize(); - } - - /// Encodes a uniformly distributed integer `fl` in `[0, ft)` (`ft >= 2`). - pub fn uint(&mut self, fl: u32, ft: u32) { - debug_assert!(ft > 1 && fl < ft); - let ft1 = ft - 1; - let ftb = ilog(ft1); - if ftb > 8 { - let ftb = (ftb - 8) as u32; - let top = (ft1 >> ftb) + 1; - let v = fl >> ftb; - self.encode(v, v + 1, top); - self.bits(fl & ((1 << ftb) - 1), ftb); - } else { - self.encode(fl, fl + 1, ft); - } - } - - /// Writes `bits` raw bits (0..=25) to the end of the buffer. - pub fn bits(&mut self, val: u32, bits: u32) { - if bits == 0 { - return; - } - let mut window = self.end_window; - let mut used = self.nend_bits; - if used as u32 + bits > CODE_BITS { - while used >= SYM_BITS as i32 { - self.end.push((window & SYM_MAX) as u8); - window >>= SYM_BITS; - used -= SYM_BITS as i32; - } - } - window |= val << used; - used += bits as i32; - self.end_window = window; - self.nend_bits = used; - self.nbits_total += bits as i32; - } - - /// Number of bits written so far (rounded up), identical to the decoder's `tell`. - #[inline] - pub fn tell(&self) -> i32 { - self.nbits_total - ilog(self.rng) - } - - /// Number of 1/8 bits written so far (rounded up), identical to the decoder's `tell_frac`. - pub fn tell_frac(&self) -> i32 { - let nbits = (self.nbits_total as u32) << BITRES; - let mut l = ilog(self.rng) as u32; - let mut r = self.rng >> (l - 16); - for _ in 0..BITRES { - r = (r * r) >> 15; - let b = r >> 16; - l = (l << 1) | b; - r >>= b; - } - nbits.wrapping_sub(l) as i32 - } - - /// Finalises the stream into a buffer of exactly `size` bytes (range data at the front, raw - /// bits at the back, zero padding in between; a partial raw-bit byte is merged into the byte - /// just before the full raw-bit bytes). - pub fn done(mut self, size: usize) -> Vec { - let mut l = CODE_BITS as i32 - ilog(self.rng); - let mut msk = (CODE_TOP - 1) >> l; - let mut end = (self.low.wrapping_add(msk)) & !msk; - if (end | msk) >= self.low.wrapping_add(self.rng) { - l += 1; - msk >>= 1; - end = (self.low.wrapping_add(msk)) & !msk; - } - while l > 0 { - self.carry_out(end >> CODE_SHIFT); - end = (end << SYM_BITS) & (CODE_TOP - 1); - l -= SYM_BITS as i32; - } - if self.rem >= 0 || self.ext > 0 { - self.carry_out(0); - } - let mut window = self.end_window; - let mut used = self.nend_bits; - while used >= SYM_BITS as i32 { - self.end.push((window & SYM_MAX) as u8); - window >>= SYM_BITS; - used -= SYM_BITS as i32; - } - let mut buf = vec![0u8; size]; - let full = self.end.len().min(size); - let room = size - full; - let n = self.out.len().min(room); - buf[..n].copy_from_slice(&self.out[..n]); - for (k, &b) in self.end.iter().take(full).enumerate() { - buf[size - 1 - k] = b; - } - if used > 0 && room > 0 { - buf[room - 1] |= window as u8; - } - buf - } -} - -#[cfg(test)] -pub(crate) mod dec { - //! Minimal range decoder (RFC 6716 §4.1) used to verify the encoder. - use super::*; - const CODE_EXTRA: u32 = (CODE_BITS - 2) % SYM_BITS + 1; - - pub struct RangeDecoder<'a> { - buf: &'a [u8], - offs: usize, - end_offs: usize, - end_window: u32, - nend_bits: i32, - nbits_total: i32, - rng: u32, - val: u32, - rem: u32, - } - - impl<'a> RangeDecoder<'a> { - pub fn new(buf: &'a [u8]) -> Self { - let mut d = RangeDecoder { - buf, - offs: 0, - end_offs: 0, - end_window: 0, - nend_bits: 0, - nbits_total: (CODE_BITS + 1 - ((CODE_BITS - CODE_EXTRA) / SYM_BITS) * SYM_BITS) as i32, - rng: 1 << CODE_EXTRA, - val: 0, - rem: 0, - }; - d.rem = d.read_byte(); - d.val = d.rng - 1 - (d.rem >> (SYM_BITS - CODE_EXTRA)); - d.normalize(); - d - } - fn read_byte(&mut self) -> u32 { - if self.offs < self.buf.len() { - self.offs += 1; - self.buf[self.offs - 1] as u32 - } else { - 0 - } - } - fn read_byte_from_end(&mut self) -> u32 { - if self.end_offs < self.buf.len() { - self.end_offs += 1; - self.buf[self.buf.len() - self.end_offs] as u32 - } else { - 0 - } - } - fn normalize(&mut self) { - while self.rng <= CODE_BOT { - self.nbits_total += SYM_BITS as i32; - self.rng <<= SYM_BITS; - let sym = self.rem; - self.rem = self.read_byte(); - let sym = ((sym << SYM_BITS) | self.rem) >> (SYM_BITS - CODE_EXTRA); - self.val = ((self.val << SYM_BITS).wrapping_add(SYM_MAX & !sym)) & (CODE_TOP - 1); - } - } - pub fn rng(&self) -> u32 { - self.rng - } - pub fn decode(&mut self, ft: u32) -> u32 { - let ext = self.rng / ft; - let s = self.val / ext; - ft - (s + 1).min(ft) - } - pub fn update(&mut self, fl: u32, fh: u32, ft: u32) { - let ext = self.rng / ft; - let s = ext * (ft - fh); - self.val = self.val.wrapping_sub(s); - self.rng = if fl > 0 { ext * (fh - fl) } else { self.rng - s }; - self.normalize(); - } - pub fn bit_logp(&mut self, logp: u32) -> bool { - let r = self.rng; - let d = self.val; - let s = r >> logp; - let ret = d < s; - if !ret { - self.val = d - s; - } - self.rng = if ret { s } else { r - s }; - self.normalize(); - ret - } - pub fn icdf(&mut self, icdf: &[u8], ftb: u32) -> usize { - let mut s = self.rng; - let d = self.val; - let r = s >> ftb; - let mut ret = 0usize; - let mut t; - loop { - t = s; - s = r * icdf[ret] as u32; - if d >= s { - break; - } - ret += 1; - } - self.val = d - s; - self.rng = t - s; - self.normalize(); - ret - } - pub fn uint(&mut self, ft: u32) -> u32 { - let ft1 = ft - 1; - let ftb = ilog(ft1); - if ftb > 8 { - let ftb = (ftb - 8) as u32; - let top = (ft1 >> ftb) + 1; - let s = self.decode(top); - self.update(s, s + 1, top); - (s << ftb) | self.bits(ftb) - } else { - let s = self.decode(ft); - self.update(s, s + 1, ft); - s - } - } - pub fn bits(&mut self, bits: u32) -> u32 { - let mut window = self.end_window; - let mut available = self.nend_bits; - if (available as u32) < bits { - loop { - window |= self.read_byte_from_end() << available; - available += SYM_BITS as i32; - if available > (CODE_BITS - SYM_BITS) as i32 { - break; - } - } - } - let ret = window & ((1u32 << bits) - 1); - self.end_window = window >> bits; - self.nend_bits = available - bits as i32; - self.nbits_total += bits as i32; - ret - } - pub fn tell(&self) -> i32 { - self.nbits_total - ilog(self.rng) - } - } -} - -#[cfg(test)] -mod tests { - use super::dec::RangeDecoder; - use super::*; - - struct Lcg(u32); - impl Lcg { - fn next(&mut self) -> u32 { - self.0 = self.0.wrapping_mul(1664525).wrapping_add(1013904223); - self.0 >> 8 - } - } - - #[test] - fn starts_at_one_bit() { - let e = RangeEncoder::new(); - assert_eq!(e.tell(), 1); - assert_eq!(e.tell_frac(), 8); - } - - #[test] - fn roundtrip_mixed_symbols_and_tell_matches() { - let mut rng = Lcg(7); - let icdf: [u8; 4] = [200, 120, 30, 0]; - for trial in 0..300 { - let n = 1 + (rng.next() % 300) as usize; - let mut ops = Vec::new(); - for _ in 0..n { - match rng.next() % 5 { - 0 => { - let ft = 2 + rng.next() % 1000; - ops.push((0u8, rng.next() % ft, ft)); - } - 1 => { - let logp = 1 + rng.next() % 15; - ops.push((1, rng.next().is_multiple_of(5) as u32, logp)); - } - 2 => { - let bits = 1 + rng.next() % 24; - ops.push((2, rng.next() & ((1 << bits) - 1), bits)); - } - 3 => { - let ft = 2 + rng.next() % 100_000_000; - ops.push((3, rng.next() % ft, ft)); - } - _ => ops.push((4, rng.next() % 4, 0)), - } - } - let mut e = RangeEncoder::new(); - let mut tells = Vec::new(); - for &(k, v, p) in &ops { - match k { - 0 => e.encode(v, v + 1, p), - 1 => e.bit_logp(v != 0, p), - 2 => e.bits(v, p), - 3 => e.uint(v, p), - _ => e.icdf(v as usize, &icdf, 8), - } - tells.push(e.tell()); - } - // Exactly the number of bytes `tell` says were used must suffice. - let size = (e.tell() as usize).div_ceil(8); - let final_rng = e.rng(); - let buf = e.done(size); - assert_eq!(buf.len(), size); - let mut d = RangeDecoder::new(&buf); - for (i, &(k, v, p)) in ops.iter().enumerate() { - let got = match k { - 0 => { - let s = d.decode(p); - d.update(s, s + 1, p); - s - } - 1 => d.bit_logp(p) as u32, - 2 => d.bits(p), - 3 => d.uint(p), - _ => d.icdf(&icdf, 8) as u32, - }; - assert_eq!(got, v, "trial {trial} op {i} kind {k}"); - assert_eq!(d.tell(), tells[i], "tell mismatch trial {trial} op {i}"); - } - assert_eq!(d.rng(), final_rng); - } - } -} diff --git a/crates/opusenc/src/rate.rs b/crates/opusenc/src/rate.rs deleted file mode 100644 index ff6ccae95..000000000 --- a/crates/opusenc/src/rate.rs +++ /dev/null @@ -1,560 +0,0 @@ -//! Pulse cache and bit allocation (RFC 6716 §4.3.3, §4.3.4.1). -//! -//! The allocation must be bit-identical to the decoder's, so this mirrors FilmCraft's -//! spec-derived `filmcraft-opus` decoder (first-party, MIT OR Apache-2.0) step by step; the only -//! difference is that the encoder *writes* the band-skip, intensity and dual-stereo symbols. - -use crate::CeltFrame; -use crate::range::{BITRES, RangeEncoder, ilog}; -use crate::tables::{ALLOC, EBANDS, LOG2_FRAC_TABLE, MAX_LM, NB_EBANDS}; - -const MAX_PSEUDO: i32 = 40; -const LOG_MAX_PSEUDO: i32 = 6; -pub const MAX_FINE_BITS: i32 = 8; -const FINE_OFFSET: i32 = 21; -pub const QTHETA_OFFSET: i32 = 4; -pub const QTHETA_OFFSET_TWOPHASE: i32 = 16; -const ALLOC_STEPS: i32 = 6; - -/// Number of pulses represented by pseudo-pulse index `i`. -pub fn get_pulses(i: i32) -> i32 { - if i < 8 { i } else { (8 + (i & 7)) << ((i >> 3) - 1) } -} - -/// Conservative (rounded up) log2 of `val` with `frac` fractional bits. -pub fn log2_frac(mut val: u32, mut frac: u32) -> i32 { - let mut l = ilog(val); - if val & val.wrapping_sub(1) != 0 { - if l > 16 { - val = ((val - 1) >> (l - 16)) + 1; - } else { - val <<= 16 - l; - } - let mut l = (l - 1) << frac; - loop { - let b = (val >> 16) as i32; - l += b << frac; - val = (val + b as u32) >> b; - val = (val * val + 0x7FFF) >> 15; - if frac == 0 { - break; - } - frac -= 1; - } - l + (val > 0x8000) as i32 - } else { - l -= 1; - l << frac - } -} - -/// PVQ codebook size V(N, K) (saturating far above 2^32). -pub fn pvq_v(n: usize, k: usize) -> u128 { - if k == 0 { - return 1; - } - if n == 0 { - return 0; - } - let mut row = vec![0u128; k + 1]; - row[0] = 1; - for _ in 0..n { - let mut prev_diag = row[0]; - for kk in 1..=k { - let up = row[kk]; - let v = up.saturating_add(row[kk - 1]).saturating_add(prev_diag); - prev_diag = up; - row[kk] = v.min(u128::MAX >> 8); - } - row[0] = 1; - } - row[k] -} - -fn fits_in32(n: usize, k: i32) -> bool { - pvq_v(n, k as usize) <= u32::MAX as u128 -} - -/// Precomputed per-mode data. -pub struct Mode { - /// log2 of band width in 1/8 bits. - pub log_n: [i32; NB_EBANDS], - cache_index: Vec, - cache_bits: Vec, - caps: Vec, -} - -impl Mode { - pub fn new() -> Mode { - let mut log_n = [0i32; NB_EBANDS]; - for (i, l) in log_n.iter_mut().enumerate() { - *l = log2_frac((EBANDS[i + 1] - EBANDS[i]) as u32, BITRES); - } - let (cache_index, cache_bits) = compute_pulse_cache(MAX_LM as i32); - let mut m = Mode { log_n, cache_index, cache_bits, caps: Vec::new() }; - m.caps = compute_caps(&m); - m - } - - #[inline] - pub fn cache(&self, lm: i32, band: usize) -> &[u8] { - let idx = self.cache_index[((lm + 1) as usize) * NB_EBANDS + band]; - &self.cache_bits[idx.max(0) as usize..] - } - - pub fn bits2pulses(&self, band: usize, lm: i32, bits: i32) -> i32 { - let cache = self.cache(lm, band); - let mut lo = 0i32; - let mut hi = cache[0] as i32; - let bits = bits - 1; - for _ in 0..LOG_MAX_PSEUDO { - let mid = (lo + hi + 1) >> 1; - if cache[mid as usize] as i32 >= bits { - hi = mid; - } else { - lo = mid; - } - } - let lo_bits = if lo == 0 { -1 } else { cache[lo as usize] as i32 }; - if bits - lo_bits <= cache[hi as usize] as i32 - bits { lo } else { hi } - } - - pub fn pulses2bits(&self, band: usize, lm: i32, pulses: i32) -> i32 { - if pulses == 0 { 0 } else { self.cache(lm, band)[pulses as usize] as i32 + 1 } - } - - /// Per-band allocation caps for this frame (`init_caps`). - pub fn init_caps(&self, lm: usize, c: usize) -> [i32; NB_EBANDS] { - let mut cap = [0i32; NB_EBANDS]; - for (i, cp) in cap.iter_mut().enumerate() { - let n = (EBANDS[i + 1] - EBANDS[i]) << lm; - *cp = ((self.caps[NB_EBANDS * (2 * lm + c - 1) + i] as i32 + 64) * c as i32 * n) >> 2; - } - cap - } -} - -fn compute_pulse_cache(lm_max: i32) -> (Vec, Vec) { - let nb = NB_EBANDS; - let rows = (lm_max + 2) as usize; - let mut index = vec![-1i16; nb * rows]; - let mut entries: Vec<(usize, i32, usize)> = Vec::new(); - let mut curr = 0usize; - for i in 0..rows { - for j in 0..nb { - let n = (((EBANDS[j + 1] - EBANDS[j]) << i) >> 1) as usize; - index[i * nb + j] = -1; - 'search: for k in 0..=i { - for nn in 0..nb { - if k == i && nn >= j { - break; - } - if n == (((EBANDS[nn + 1] - EBANDS[nn]) << k) >> 1) as usize { - index[i * nb + j] = index[k * nb + nn]; - break 'search; - } - } - } - if index[i * nb + j] == -1 && n != 0 { - let mut k = 0; - while k < MAX_PSEUDO && fits_in32(n, get_pulses(k + 1)) { - k += 1; - } - index[i * nb + j] = curr as i16; - entries.push((n, k, curr)); - curr += (k + 1) as usize; - } - } - } - let mut bits = vec![0u8; curr]; - for &(n, k, off) in &entries { - let maxk = get_pulses(k) as usize; - let tmp = required_bits(n, maxk, BITRES); - for j in 1..=k { - bits[off + j as usize] = (tmp[get_pulses(j) as usize] - 1) as u8; - } - bits[off] = k as u8; - } - (index, bits) -} - -fn required_bits(n: usize, maxk: usize, frac: u32) -> Vec { - let mut out = vec![0i32; maxk + 1]; - if n == 1 { - for o in out.iter_mut().skip(1) { - *o = 1 << frac; - } - } else { - for (k, o) in out.iter_mut().enumerate().skip(1) { - *o = log2_frac(pvq_v(n, k) as u32, frac); - } - } - out -} - -fn compute_caps(m: &Mode) -> Vec { - let nb = NB_EBANDS; - let mut caps = vec![0u8; (MAX_LM + 1) * 2 * nb]; - for i in 0..=MAX_LM as i32 { - for c in 1..=2i32 { - for j in 0..nb { - let mut n0 = EBANDS[j + 1] - EBANDS[j]; - - let max_bits = if n0 << i == 1 { - (c * (1 + MAX_FINE_BITS)) << BITRES - } else { - let mut lm0 = 0; - if n0 > 2 { - n0 >>= 1; - lm0 -= 1; - } else if n0 <= 1 { - lm0 = i.min(1); - n0 <<= lm0; - } - let pcache = m.cache(lm0, j); - let mut mb = pcache[pcache[0] as usize] as i32 + 1; - let mut n = n0; - for k in 0..(i - lm0) { - mb <<= 1; - let offset = ((m.log_n[j] + ((lm0 + k) << BITRES)) >> 1) - QTHETA_OFFSET; - let num = 459 * ((2 * n - 1) * offset + mb); - let den = ((2 * n - 1) << 9) - 459; - let qb = ((num + (den >> 1)) / den).min(57); - mb += qb; - n <<= 1; - } - if c == 2 { - mb <<= 1; - let offset = ((m.log_n[j] + (i << BITRES)) >> 1) - if n == 2 { QTHETA_OFFSET_TWOPHASE } else { QTHETA_OFFSET }; - let ndof = 2 * n - 1 - (n == 2) as i32; - let p = if n == 2 { 512 } else { 487 }; - let num = p * (mb + ndof * offset); - let den = (ndof << 9) - p; - let qb = ((num + (den >> 1)) / den).min(if n == 2 { 64 } else { 61 }); - mb += qb; - } - let ndof = c * n + if c == 2 && n > 2 { 1 } else { 0 }; - let mut offset = ((m.log_n[j] + (i << BITRES)) >> 1) - FINE_OFFSET; - if n == 2 { - offset += (1 << BITRES) >> 2; - } - let num = mb + ndof * offset; - let den = (ndof - 1) << BITRES; - let qb = ((num + (den >> 1)) / den).min(MAX_FINE_BITS); - mb += (c * qb) << BITRES; - mb - }; - let w = c * ((EBANDS[j + 1] - EBANDS[j]) << i); - let v = (4 * max_bits / w) - 64; - caps[((i * 2 + c - 1) as usize) * nb + j] = v.clamp(0, 255) as u8; - } - } - } - caps -} - -/// Result of the allocation process. -pub struct Allocation { - pub coded_bands: usize, - pub intensity: usize, - pub dual_stereo: bool, - pub balance: i32, - pub pulses: [i32; NB_EBANDS], - pub fine_quant: [i32; NB_EBANDS], - pub fine_priority: [i32; NB_EBANDS], -} - -/// Per-band limits, boosts and available budget for the allocation search. -pub struct AllocationInput<'a> { - pub offsets: &'a [i32; NB_EBANDS], - pub cap: &'a [i32; NB_EBANDS], - pub trim: i32, - pub bits: i32, -} - -/// `clt_compute_allocation`, encoder side. Stereo frames are always coded as dual (L/R) stereo -/// with no intensity bands, and no band is skipped voluntarily. -pub fn compute_allocation(m: &Mode, frame: CeltFrame, input: AllocationInput<'_>, enc: &mut RangeEncoder) -> Allocation { - let CeltFrame { start, end, channels: c, lm } = frame; - let AllocationInput { offsets, cap, trim: alloc_trim, bits: total } = input; - let ci = c as i32; - let lmi = lm as i32; - let mut total = total.max(0); - let mut skip_start = start; - let skip_rsv = if total >= 1 << BITRES { 1 << BITRES } else { 0 }; - total -= skip_rsv; - let mut intensity_rsv = 0; - let mut dual_stereo_rsv = 0; - if c == 2 { - intensity_rsv = LOG2_FRAC_TABLE[end - start]; - if intensity_rsv > total { - intensity_rsv = 0; - } else { - total -= intensity_rsv; - dual_stereo_rsv = if total >= 1 << BITRES { 1 << BITRES } else { 0 }; - total -= dual_stereo_rsv; - } - } - let mut bits1 = [0i32; NB_EBANDS]; - let mut bits2 = [0i32; NB_EBANDS]; - let mut thresh = [0i32; NB_EBANDS]; - let mut trim_offset = [0i32; NB_EBANDS]; - for j in start..end { - let w = EBANDS[j + 1] - EBANDS[j]; - thresh[j] = (ci << BITRES).max(((3 * w) << lmi << BITRES) >> 4); - trim_offset[j] = (ci * w * (alloc_trim - 5 - lmi) * (end as i32 - j as i32 - 1) * (1 << (lmi + BITRES as i32))) >> 6; - if w << lmi == 1 { - trim_offset[j] -= ci << BITRES; - } - } - let nb_alloc = ALLOC.len() as i32; - let mut lo = 1; - let mut hi = nb_alloc - 1; - loop { - let mut done = false; - let mut psum = 0; - let mid = (lo + hi) >> 1; - for j in (start..end).rev() { - let n = EBANDS[j + 1] - EBANDS[j]; - let mut bitsj = (ci * n * (ALLOC[mid as usize][j] as i32)) << lmi >> 2; - if bitsj > 0 { - bitsj = (bitsj + trim_offset[j]).max(0); - } - bitsj += offsets[j]; - if bitsj >= thresh[j] || done { - done = true; - psum += bitsj.min(cap[j]); - } else if bitsj >= ci << BITRES { - psum += ci << BITRES; - } - } - if psum > total { - hi = mid - 1; - } else { - lo = mid + 1; - } - if lo > hi { - break; - } - } - hi = lo; - lo -= 1; - for j in start..end { - let n = EBANDS[j + 1] - EBANDS[j]; - let mut bits1j = (ci * n * (ALLOC[lo as usize][j] as i32)) << lmi >> 2; - let mut bits2j = if hi >= nb_alloc { cap[j] } else { (ci * n * (ALLOC[hi as usize][j] as i32)) << lmi >> 2 }; - if bits1j > 0 { - bits1j = (bits1j + trim_offset[j]).max(0); - } - if bits2j > 0 { - bits2j = (bits2j + trim_offset[j]).max(0); - } - if lo > 0 { - bits1j += offsets[j]; - } - bits2j += offsets[j]; - if offsets[j] > 0 { - skip_start = j; - } - bits2j = (bits2j - bits1j).max(0); - bits1[j] = bits1j; - bits2[j] = bits2j; - } - let interpolation = - AllocationInterpolation { skip_start, bits1: &bits1, bits2: &bits2, thresh: &thresh, cap, total, skip_rsv, intensity_rsv, dual_stereo_rsv }; - interp_bits2pulses(m, frame, interpolation, enc) -} - -/// Bracketing allocation vectors and signalling reserves for the interpolation stage. -struct AllocationInterpolation<'a> { - skip_start: usize, - bits1: &'a [i32; NB_EBANDS], - bits2: &'a [i32; NB_EBANDS], - thresh: &'a [i32; NB_EBANDS], - cap: &'a [i32; NB_EBANDS], - total: i32, - skip_rsv: i32, - intensity_rsv: i32, - dual_stereo_rsv: i32, -} - -fn interp_bits2pulses(m: &Mode, frame: CeltFrame, interpolation: AllocationInterpolation<'_>, enc: &mut RangeEncoder) -> Allocation { - let CeltFrame { start, end, channels: c, lm } = frame; - let AllocationInterpolation { skip_start, bits1, bits2, thresh, cap, mut total, skip_rsv, mut intensity_rsv, mut dual_stereo_rsv } = interpolation; - let ci = c as i32; - let alloc_floor = ci << BITRES; - let stereo = (c > 1) as i32; - let log_m = (lm as i32) << BITRES; - let mut lo = 0; - let mut hi = 1 << ALLOC_STEPS; - for _ in 0..ALLOC_STEPS { - let mid = (lo + hi) >> 1; - let mut psum = 0; - let mut done = false; - for j in (start..end).rev() { - let tmp = bits1[j] + ((mid * bits2[j]) >> ALLOC_STEPS); - if tmp >= thresh[j] || done { - done = true; - psum += tmp.min(cap[j]); - } else if tmp >= alloc_floor { - psum += alloc_floor; - } - } - if psum > total { - hi = mid; - } else { - lo = mid; - } - } - let mut bits = [0i32; NB_EBANDS]; - let mut psum = 0; - let mut done = false; - for j in (start..end).rev() { - let mut tmp = bits1[j] + ((lo * bits2[j]) >> ALLOC_STEPS); - if tmp < thresh[j] && !done { - tmp = if tmp >= alloc_floor { alloc_floor } else { 0 }; - } else { - done = true; - } - tmp = tmp.min(cap[j]); - bits[j] = tmp; - psum += tmp; - } - let s = start; - let mut coded_bands = end; - loop { - let j = coded_bands - 1; - if j <= skip_start { - total += skip_rsv; - break; - } - let mut left = total - psum; - let span = EBANDS[coded_bands] - EBANDS[s]; - let percoeff = left / span; - left -= span * percoeff; - let rem = (left - (EBANDS[j] - EBANDS[s])).max(0); - let band_width = EBANDS[coded_bands] - EBANDS[j]; - let band_bits = bits[j] + percoeff * band_width + rem; - if band_bits >= thresh[j].max(alloc_floor + (1 << BITRES)) { - // Keep this band (and every band below it). - enc.bit_logp(true, 1); - break; - } - psum -= bits[j] + intensity_rsv; - if intensity_rsv > 0 { - intensity_rsv = LOG2_FRAC_TABLE[j - s]; - } - psum += intensity_rsv; - if band_bits >= alloc_floor { - psum += alloc_floor; - bits[j] = alloc_floor; - } else { - bits[j] = 0; - } - coded_bands -= 1; - } - let intensity = if intensity_rsv > 0 { - // No intensity stereo: every coded band is coded in full. - enc.uint((coded_bands - s) as u32, (coded_bands + 1 - s) as u32); - coded_bands - } else { - 0 - }; - if intensity <= s { - total += dual_stereo_rsv; - dual_stereo_rsv = 0; - } - let dual_stereo = if dual_stereo_rsv > 0 { - enc.bit_logp(true, 1); - true - } else { - false - }; - let mut left = total - psum; - let span = EBANDS[coded_bands] - EBANDS[s]; - let percoeff = left / span; - left -= span * percoeff; - for j in s..coded_bands { - bits[j] += percoeff * (EBANDS[j + 1] - EBANDS[j]); - } - for j in s..coded_bands { - let tmp = left.min(EBANDS[j + 1] - EBANDS[j]); - bits[j] += tmp; - left -= tmp; - } - let mut ebits = [0i32; NB_EBANDS]; - let mut fine_priority = [0i32; NB_EBANDS]; - let mut balance = 0; - for j in s..coded_bands { - let n0 = EBANDS[j + 1] - EBANDS[j]; - let n = n0 << lm; - let bit = bits[j] + balance; - let mut excess; - if n > 1 { - excess = (bit - cap[j]).max(0); - bits[j] = bit - excess; - let den = ci * n + if c == 2 && n > 2 && !dual_stereo && j < intensity { 1 } else { 0 }; - let nclogn = den * (m.log_n[j] + log_m); - let mut offset = (nclogn >> 1) - den * FINE_OFFSET; - if n == 2 { - offset += (den << BITRES) >> 2; - } - if bits[j] + offset < (den * 2) << BITRES { - offset += nclogn >> 2; - } else if bits[j] + offset < (den * 3) << BITRES { - offset += nclogn >> 3; - } - let mut eb = (bits[j] + offset + (den << (BITRES - 1))).max(0); - eb = (eb / den) >> BITRES; - if ci * eb > (bits[j] >> BITRES) { - eb = bits[j] >> stereo >> BITRES; - } - eb = eb.min(MAX_FINE_BITS); - ebits[j] = eb; - fine_priority[j] = (eb * (den << BITRES) >= bits[j] + offset) as i32; - bits[j] -= (ci * eb) << BITRES; - } else { - excess = (bit - (ci << BITRES)).max(0); - bits[j] = bit - excess; - ebits[j] = 0; - fine_priority[j] = 1; - } - if excess > 0 { - let extra_fine = (excess >> (stereo + BITRES as i32)).min(MAX_FINE_BITS - ebits[j]); - ebits[j] += extra_fine; - let extra_bits = (extra_fine * ci) << BITRES; - fine_priority[j] = (extra_bits >= excess - balance) as i32; - excess -= extra_bits; - } - balance = excess; - } - for j in coded_bands..end { - ebits[j] = bits[j] >> stereo >> BITRES; - bits[j] = 0; - fine_priority[j] = (ebits[j] < 1) as i32; - } - Allocation { coded_bands, intensity, dual_stereo, balance, pulses: bits, fine_quant: ebits, fine_priority } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn caps_match_decoder_reference() { - let m = Mode::new(); - let first_rows: [u8; 42] = [ - 224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134, 61, 37, 224, 224, 224, 224, 224, 224, 224, 224, 240, - 240, 240, 240, 207, 207, 207, 198, 198, 183, 144, 66, 40, - ]; - assert_eq!(&m.caps[..42], &first_rows[..]); - } - - #[test] - fn pvq_counts() { - assert_eq!(pvq_v(5, 1), 10); - assert_eq!(pvq_v(1, 7), 2); - assert_eq!(pvq_v(2, 9), 36); - assert_eq!(pvq_v(3, 2), 18); - } -} diff --git a/crates/opusenc/src/resample.rs b/crates/opusenc/src/resample.rs deleted file mode 100644 index 1acc9a4e7..000000000 --- a/crates/opusenc/src/resample.rs +++ /dev/null @@ -1,160 +0,0 @@ -//! 48 kHz → 8/12/16 kHz decimator feeding the SILK layer (own design). -//! -//! A linear-phase low-pass FIR (Kaiser-windowed sinc at 48 kHz) evaluated only at the retained -//! output phases. Its group delay ([`delay`]) is a whole number of 48 kHz samples, chosen so -//! that the SILK path (this filter + the decoder's internal-rate delay and resampler, RFC 6716 -//! Table 54) lands within a fraction of a sample of the CELT path's 120-sample MDCT overlap. - -/// Group delay of the decimator to `fs_out` in 48 kHz samples (the filter has `2 * delay + 1` -/// taps). -pub fn delay(fs_out: u32) -> usize { - if fs_out == 8_000 { 88 } else { 83 } -} - -/// Zeroth-order modified Bessel function of the first kind (power series). -fn bessel_i0(x: f64) -> f64 { - let mut sum = 1.0; - let mut term = 1.0; - let q = x * x / 4.0; - for k in 1..64 { - term *= q / (k * k) as f64; - sum += term; - if term < sum * 1e-17 { - break; - } - } - sum -} - -/// Windowed-sinc low-pass with cutoff `fc` (Hz at 48 kHz), unit DC gain. -fn design(fc: f64, beta: f64, delay: usize) -> Vec { - let wc = 2.0 * std::f64::consts::PI * fc / 48_000.0; - let i0b = bessel_i0(beta); - let mut h: Vec = (0..2 * delay + 1) - .map(|k| { - let m = k as f64 - delay as f64; - let sinc = if m == 0.0 { wc / std::f64::consts::PI } else { (wc * m).sin() / (std::f64::consts::PI * m) }; - let r = m / delay as f64; - sinc * bessel_i0(beta * (1.0 - r * r).max(0.0).sqrt()) / i0b - }) - .collect(); - let s: f64 = h.iter().sum(); - for v in h.iter_mut() { - *v /= s; - } - h.iter().map(|&v| v as f32).collect() -} - -/// Dot product with eight independent partial sums, which the compiler can vectorise (a single -/// running sum is bound by the latency of the float addition). The sums are combined pairwise. -#[inline] -fn dot8(a: &[f32], b: &[f32]) -> f32 { - let mut s = [0f32; 8]; - let (ca, ra) = a.as_chunks::<8>(); - let (cb, rb) = b.as_chunks::<8>(); - for (x, y) in ca.iter().zip(cb) { - for l in 0..8 { - s[l] += x[l] * y[l]; - } - } - let mut acc = ((s[0] + s[4]) + (s[1] + s[5])) + ((s[2] + s[6]) + (s[3] + s[7])); - for (x, y) in ra.iter().zip(rb) { - acc += x * y; - } - acc -} - -/// Decimates one channel of 48 kHz audio by 3, 4 or 6. -#[derive(Clone)] -pub struct Downsampler { - factor: usize, - h: Vec, - taps: usize, - /// The last `taps - 1` input samples followed by the current frame. - buf: Vec, -} - -impl Downsampler { - /// `fs_out` is 8000, 12000 or 16000. - pub fn new(fs_out: u32) -> Self { - let factor = (48_000 / fs_out) as usize; - // Cutoff at 95 % of the output Nyquist frequency (pass band to ~88 %, stop band from ~110 %). - let fc = 0.95 * fs_out as f64 / 2.0; - let d = delay(fs_out); - let taps = 2 * d + 1; - Downsampler { factor, h: design(fc, 6.5, d), taps, buf: vec![0.0; taps - 1] } - } - - /// Decimates `input` (a multiple of the factor long), appending to `out`. Output sample `j` - /// is the filtered input at frame position `factor * j`, delayed by [`delay`]. - pub fn process(&mut self, input: &[f32], out: &mut Vec) { - debug_assert!(input.len().is_multiple_of(self.factor)); - let taps = self.taps; - self.buf.truncate(taps - 1); - self.buf.extend_from_slice(input); - for j in 0..input.len() / self.factor { - let t = taps - 1 + self.factor * j; - let win = &self.buf[t + 1 - taps..=t]; - // h is symmetric, so the window can be taken in forward order. - out.push(dot8(win, &self.h)); - } - let n = self.buf.len(); - self.buf.copy_within(n - (taps - 1).., 0); - self.buf.truncate(taps - 1); - } -} - -#[cfg(test)] -mod tests { - use super::*; - - fn tone(f: f64, n: usize) -> Vec { - (0..n).map(|i| (2.0 * std::f64::consts::PI * f * i as f64 / 48_000.0).sin() as f32).collect() - } - - fn rms(x: &[f32]) -> f64 { - (x.iter().map(|&v| (v as f64).powi(2)).sum::() / x.len() as f64).sqrt() - } - - #[test] - fn dot8_matches_sequential_sum() { - for len in [0usize, 1, 7, 8, 9, 63, 167, 251] { - let a: Vec = (0..len).map(|i| ((i * 37 % 101) as f32 - 50.0) / 50.0).collect(); - let b: Vec = (0..len).map(|i| ((i * 53 % 89) as f32 - 44.0) / 44.0).collect(); - let exact: f64 = a.iter().zip(&b).map(|(&x, &y)| x as f64 * y as f64).sum(); - assert!((dot8(&a, &b) as f64 - exact).abs() < 1e-4, "len {len}"); - } - } - - #[test] - fn passes_band_and_rejects_aliases() { - for &(fs, pass, stop) in &[(16_000u32, 6_000.0, 8_600.0), (12_000, 4_500.0, 6_500.0), (8_000, 3_000.0, 4_500.0)] { - for &(f, want_pass) in &[(pass, true), (stop, false)] { - let mut d = Downsampler::new(fs); - let x = tone(f, 9600); - let mut y = Vec::new(); - for c in x.chunks(960) { - d.process(c, &mut y); - } - let r = rms(&y[y.len() / 2..]) * std::f64::consts::SQRT_2; - if want_pass { - assert!((r - 1.0).abs() < 0.02, "{fs}: {f} Hz gain {r}"); - } else { - assert!(r < 0.01, "{fs}: {f} Hz leaks {r}"); - } - } - } - } - - #[test] - fn delay_is_exact() { - let mut d = Downsampler::new(16_000); - let mut x = vec![0f32; 960]; - x[300] = 1.0; - let mut y = Vec::new(); - d.process(&x, &mut y); - // The impulse at 300 shows up centred at 48 kHz time 300 + 83 = 383 (output 127.67). - let peak = y.iter().enumerate().max_by(|a, b| a.1.total_cmp(b.1)).map(|(i, _)| i).unwrap_or(0); - assert!((peak as f64 - (300.0 + delay(16_000) as f64) / 3.0).abs() < 1.0, "peak at {peak}"); - } -} diff --git a/crates/opusenc/src/silk.rs b/crates/opusenc/src/silk.rs deleted file mode 100644 index 9e202c958..000000000 --- a/crates/opusenc/src/silk.rs +++ /dev/null @@ -1,858 +0,0 @@ -//! SILK layer encoder (RFC 6716 §4.2, encoder direction), 20 ms frames at 8, 12 or 16 kHz. -//! -//! Each frame is analysed (VAD, open-loop pitch, windowed-autocorrelation LPC, LTP codebook -//! search), its NLSFs are quantised, and the excitation is chosen sample by sample by running -//! the decoder's exact fixed-point reconstruction (LTP and LPC synthesis with the dequantised -//! Q12/Q14 coefficients, quantisation offsets and the pseudo-random sign sequence), so the -//! encoder always holds the decoder's state and there is no drift. A noise-feedback loop -//! shapes the coding noise with a bandwidth-expanded LPC envelope, and a per-frame search over -//! a gain offset hits the bit budget. Stereo input is coded as mid/side with the decoder's -//! stereo prediction (§4.2.8). No LBRR, no NLSF interpolation. - -pub(crate) mod analysis; -pub(crate) mod lpc; -mod nlsf; -mod pulses; -#[allow(dead_code)] -pub(crate) mod tables; - -use lpc::{MAX_LPC_ORDER, div32_varq, inverse32_varq, nlsf2a, rshift_round, sat16, smlawb, smulwb, smulww}; -use tables::{ - DELTA_GAIN, GAIN_MSB, LTP_FILTER, LTP_PERIODICITY, LTP_SCALE, LTP_TAPS_0, LTP_TAPS_1, LTP_TAPS_2, MID_ONLY, NLSF_EXT, NLSF_INTERP, NLSF_SEL_NBMB, - NLSF_SEL_WB, NLSF_STAGE1, NLSF_STAGE2, PITCH_CONTOUR, PITCH_HIGH, PITCH_LOW, STEREO_PRED_JOINT, STEREO_WEIGHTS_Q13, TYPE_ACTIVE, TYPE_INACTIVE, UNIFORM3, - UNIFORM4, UNIFORM5, UNIFORM8, -}; - -use crate::range::RangeEncoder; - -const MAX_FRAME: usize = 320; -const LTP_ORDER: usize = 5; -/// Frame RMS (16-bit scale) below which a frame is coded as inactive (VAD off). -const VAD_RMS: f32 = 30.0; -/// Normalised pitch correlation above which a frame is a voicing candidate. -const VOICING_THRESHOLD: f64 = 0.45; -/// Minimum LTP prediction gain (energy ratio) for a frame to be coded as voiced. -const MIN_LTP_GAIN: f64 = 1.3; -/// Rate penalty (squared pulse units per unit magnitude) of the excitation quantiser. -const RD_LAMBDA: f64 = 0.15; -/// Extra gain offset (log2) for inactive frames. -const INACTIVE_OFFSET: f64 = 1.0; -/// Noise feedback: the coding noise is shaped by `1 / A(z/γ)` (A the short-term predictor). -/// γ = 0 leaves it white (closed-loop DPCM, best waveform SNR at high rates), γ = 1 shapes it -/// like the spectral envelope (open-loop residual coding, needed at low rates). γ grows with the -/// gain offset, i.e. as the quantisation gets coarser. -fn nf_gamma(offset: f64) -> f64 { - (0.75 + 0.05 * offset).clamp(0.75, 0.9) -} - -/// `silk_log2lin` (decoder arithmetic). -fn log2lin(in_log_q7: i32) -> i32 { - if in_log_q7 < 0 { - return 0; - } - if in_log_q7 >= 3967 { - return i32::MAX; - } - let out = 1i32 << (in_log_q7 >> 7); - let frac = in_log_q7 & 0x7F; - if in_log_q7 < 2048 { out + ((out * smlawb(frac, frac * (128 - frac), -174)) >> 7) } else { out + (out >> 7) * smlawb(frac, frac * (128 - frac), -174) } -} - -fn gain_q16(index: i32) -> i32 { - log2lin((smulwb(0x1D1C71, index) + 2090).min(3967)) -} - -/// The decoder's LPC analysis filter on 16-bit samples. -fn lpc_analysis_filter(out: &mut [i16], input: &[i16], b: &[i32], d: usize) { - let len = out.len(); - for ix in d..len { - let mut acc: i32 = 0; - for j in 0..d { - acc = acc.wrapping_add((input[ix - 1 - j] as i32).wrapping_mul(b[j])); - } - let v = ((input[ix] as i32) << 12).wrapping_sub(acc); - out[ix] = sat16(rshift_round(v, 12)) as i16; - } - for v in out.iter_mut().take(d.min(len)) { - *v = 0; - } -} - -/// The part of the decoder's channel state that the reconstruction depends on. -#[derive(Clone)] -struct DecState { - prev_gain_q16: i32, - s_lpc_q14: [i32; MAX_LPC_ORDER], - out_buf: [i16; MAX_FRAME], - last_gain_index: i32, -} - -impl DecState { - fn new() -> Self { - DecState { prev_gain_q16: 65536, s_lpc_q14: [0; MAX_LPC_ORDER], out_buf: [0; MAX_FRAME], last_gain_index: 10 } - } - - /// The decoder's reset of the side channel when it is coded again after mid-only frames. - fn reset_side(&mut self) { - self.out_buf = [0; MAX_FRAME]; - self.s_lpc_q14 = [0; MAX_LPC_ORDER]; - self.last_gain_index = 10; - } -} - -/// Coded parameters of one frame (everything except gains and pulses). -#[derive(Clone, Default)] -struct Params { - vad: bool, - signal_type: usize, - quant_offset_type: usize, - nlsf_ix: [i32; 17], - a_q12: [i32; MAX_LPC_ORDER], - lag_index: i32, - contour: usize, - per_index: usize, - ltp_index: [usize; 4], - pitch_l: [i32; 4], - /// RMS (16-bit scale) of the open-loop prediction residual per subframe. - res_rms: [f32; 4], -} - -/// Gains, seed and pulses chosen by the quantiser. -struct Coded { - gain_ix: [i32; 4], - gains_q16: [i32; 4], - seed: usize, - pulses: Vec, -} - -/// Noise-feedback history (decoded − input), most recent first, as a double-length ring: each -/// sample is stored at `pos` and `pos + MAX_LPC_ORDER`, so `buf[pos..pos + MAX_LPC_ORDER]` is -/// always the contiguous window and a push costs two stores instead of a shift. -struct NfRing { - buf: [f64; 2 * MAX_LPC_ORDER], - /// Index of the most recent sample, always below `MAX_LPC_ORDER`. - pos: usize, -} - -impl NfRing { - fn new(hist: &[f64; MAX_LPC_ORDER]) -> Self { - let mut buf = [0.0; 2 * MAX_LPC_ORDER]; - buf[..MAX_LPC_ORDER].copy_from_slice(hist); - buf[MAX_LPC_ORDER..].copy_from_slice(hist); - NfRing { buf, pos: 0 } - } - - /// The history, most recent first. - fn window(&self) -> &[f64] { - self.buf.get(self.pos..self.pos + MAX_LPC_ORDER).unwrap_or(&[]) - } - - /// Makes `v` the most recent sample and drops the oldest. - fn push(&mut self, v: f64) { - self.pos = self.pos.checked_sub(1).unwrap_or(MAX_LPC_ORDER - 1); - for i in [self.pos, self.pos + MAX_LPC_ORDER] { - if let Some(slot) = self.buf.get_mut(i) { - *slot = v; - } - } - } - - /// The history as a plain array, most recent first. - fn to_array(&self) -> [f64; MAX_LPC_ORDER] { - let mut out = [0.0; MAX_LPC_ORDER]; - for (o, v) in out.iter_mut().zip(self.window()) { - *o = *v; - } - out - } -} - -#[derive(Clone)] -struct Channel { - fs_khz: usize, - len: usize, - sub: usize, - order: usize, - dec: DecState, - /// The last two frames of input (internal rate, 16-bit scale). - hist: Vec, - /// Recent output errors (decoded − input), most recent first, for noise feedback. - nf: [f64; MAX_LPC_ORDER], -} - -impl Channel { - fn new(fs_khz: usize) -> Self { - let len = 20 * fs_khz; - Channel { - fs_khz, - len, - sub: 5 * fs_khz, - order: if fs_khz == 16 { 16 } else { 10 }, - dec: DecState::new(), - hist: vec![0.0; 2 * len], - nf: [0.0; MAX_LPC_ORDER], - } - } - - fn push_history(&mut self, x: &[f32]) { - let l = self.len; - self.hist.copy_within(l.., 0); - self.hist[l..].copy_from_slice(x); - } - - /// Frame analysis: VAD, signal type, pitch, LPC/NLSF quantisation and LTP taps. - fn analyze(&self, x: &[f32]) -> Params { - let l = self.len; - let sub = self.sub; - let order = self.order; - let wb = order == 16; - let mut buf = self.hist.clone(); - buf.extend_from_slice(x); - let start = 2 * l; - let rms = (x.iter().map(|v| v * v).sum::() / l as f32).sqrt(); - let vad = rms > VAD_RMS; - let pitch = if vad { Some(analysis::pitch_search(&buf, start, l, self.fs_khz)) } else { None }; - let mut voiced = pitch.as_ref().is_some_and(|p| p.score > VOICING_THRESHOLD); - - let a = analysis::lpc(&buf[start - l / 4..], order, self.fs_khz); - let target: Vec = match analysis::a2nlsf(&a) { - Some(w) => w.iter().map(|v| v / std::f64::consts::PI * 32768.0).collect(), - None => (1..=order).map(|k| k as f64 * 32768.0 / (order + 1) as f64).collect(), - }; - let quant = |signal_type: usize| { - let (ix, nlsf) = nlsf::quantize(&target, signal_type, wb); - (ix, nlsf2a(&nlsf[..order])) - }; - let mut p = Params { vad, ..Default::default() }; - let (mut ix, mut a_q12) = quant(if voiced { 2 } else { 1 }); - // Open-loop residual with the quantised predictor. - let mut r = vec![0f64; buf.len()]; - for n in order..buf.len() { - let mut acc = buf[n] as f64; - for j in 0..order { - acc -= a_q12[j] as f64 / 4096.0 * buf[n - 1 - j] as f64; - } - r[n] = acc; - } - if voiced && let Some(pitch) = &pitch { - let ltp = analysis::ltp_search(&r, start, sub, &pitch.lags); - let gain = ltp.energy.iter().sum::() / ltp.err.iter().sum::().max(1e-9); - if gain >= MIN_LTP_GAIN { - p.lag_index = pitch.lag_index; - p.contour = pitch.contour; - p.pitch_l = pitch.lags; - p.per_index = ltp.per_index; - p.ltp_index = ltp.ltp_index; - } else { - voiced = false; - (ix, a_q12) = quant(1); - } - } - // Gains follow the short-term residual level (the long-term predictor then only - // reduces the number of pulses), which keeps the noise-to-signal ratio steady. - for k in 0..4 { - let e: f64 = r[start + k * sub..start + (k + 1) * sub].iter().map(|v| v * v).sum(); - p.res_rms[k] = (e / sub as f64).sqrt() as f32; - } - p.signal_type = if !vad { - 0 - } else if voiced { - 2 - } else { - 1 - }; - p.quant_offset_type = 0; - p.nlsf_ix = ix; - p.a_q12 = a_q12; - p - } - - /// Chooses gains and pulses for target `x` by running the decoder's reconstruction, and - /// advances the mirrored decoder state. `offset` scales the gains (log2), `floor` gives - /// minimum gains (Q16) per subframe. Returns the coded values and the decoded frame. - fn quantize(&mut self, p: &Params, x: &[f32], offset: f64, floor: Option<&[i32; 4]>, seed: usize) -> (Coded, Vec) { - let l = self.len; - let sub = self.sub; - let order = self.order; - let st = &mut self.dec; - let mut ring = NfRing::new(&self.nf); - let off = if p.signal_type == 0 { offset + INACTIVE_OFFSET } else { offset }; - let gamma = nf_gamma(off); - let mut nf_c = [0f64; MAX_LPC_ORDER]; - let mut gpow = 1.0; - for j in 0..order { - gpow *= gamma; - nf_c[j] = p.a_q12[j] as f64 / 4096.0 * gpow; - } - // Gains (independent coding of the first subframe, deltas for the rest). - let mut gain_ix = [0i32; 4]; - let mut gains_q16 = [0i32; 4]; - let mut prev = st.last_gain_index; - for k in 0..4 { - let mut g = p.res_rms[k] as f64 * off.exp2(); - if let Some(f) = floor { - g = g.max(f[k] as f64 / 65536.0); - } - let want = (((g * 65536.0).max(1.0).log2() * 128.0 - 2090.0) / (1_907_825.0 / 65536.0)).round().clamp(0.0, 63.0) as i32; - if k == 0 { - gain_ix[0] = want; - prev = want.max(prev - 16).clamp(0, 63); - } else { - let mut best = (i32::MAX, 0i32, prev); - for ind in 0..41 { - let tmp = ind - 4; - let thr = 2 * 36 - 64 + prev; - let d = if tmp > thr { prev + (tmp << 1) - thr } else { prev + tmp }.clamp(0, 63); - let e = (d - want).abs(); - if e < best.0 { - best = (e, ind, d); - } - } - gain_ix[k] = best.1; - prev = best.2; - } - gains_q16[k] = gain_q16(prev); - } - st.last_gain_index = prev; - - // Analysis-by-synthesis excitation quantisation through the decoder's exact synthesis. - let voiced = p.signal_type == 2; - let offset_q10 = [[100, 240], [32, 100]][p.signal_type >> 1][p.quant_offset_type]; - let off16 = offset_q10 << 4; - let mut seed_v = seed as i32; - let mut pulses = vec![0i32; l]; - let mut xq = vec![0i16; l]; - let mut s_lpc = [0i32; MAX_FRAME / 4 + MAX_LPC_ORDER]; - s_lpc[..MAX_LPC_ORDER].copy_from_slice(&st.s_lpc_q14); - let mut s_ltp = [0i16; MAX_FRAME]; - let mut s_ltp_q15 = [0i32; 2 * MAX_FRAME]; - let ltp_mem = l; - let mut ltp_buf_idx = ltp_mem; - let a_q12 = &p.a_q12; - let ltp_scale_q14 = 15565; - for k in 0..4 { - let mut b_q14 = [0i32; LTP_ORDER]; - if voiced { - let ix = p.ltp_index[k]; - let taps = match p.per_index { - 0 => LTP_TAPS_0[ix], - 1 => LTP_TAPS_1[ix], - _ => LTP_TAPS_2[ix], - }; - for i in 0..LTP_ORDER { - b_q14[i] = taps[i] << 7; - } - } - let gain_q10 = gains_q16[k] >> 6; - let mut inv_gain_q31 = inverse32_varq(gains_q16[k], 47); - let gain_adj_q16 = if gains_q16[k] != st.prev_gain_q16 { - let g = div32_varq(st.prev_gain_q16, gains_q16[k], 16); - for v in s_lpc[..MAX_LPC_ORDER].iter_mut() { - *v = smulww(g, *v); - } - g - } else { - 1 << 16 - }; - st.prev_gain_q16 = gains_q16[k]; - let lag = p.pitch_l[k]; - if voiced { - let lag_u = lag as usize; - if k == 0 { - let start_idx = (ltp_mem as isize - lag as isize - order as isize - (LTP_ORDER / 2) as isize).max(0) as usize; - lpc_analysis_filter(&mut s_ltp[start_idx..ltp_mem], &st.out_buf[start_idx..ltp_mem], a_q12, order); - inv_gain_q31 = smulwb(inv_gain_q31, ltp_scale_q14) << 2; - for i in 0..(lag_u + LTP_ORDER / 2).min(ltp_mem) { - s_ltp_q15[ltp_buf_idx - i - 1] = smulwb(inv_gain_q31, s_ltp[ltp_mem - i - 1] as i32); - } - } else if gain_adj_q16 != 1 << 16 { - for i in 0..(lag_u + LTP_ORDER / 2).min(ltp_buf_idx) { - let q = ltp_buf_idx - i - 1; - s_ltp_q15[q] = smulww(gain_adj_q16, s_ltp_q15[q]); - } - } - } - let inv_g = 16_777_216.0 / gain_q10.max(1) as f64; - for i in 0..sub { - let n = k * sub + i; - seed_v = seed_v.wrapping_mul(196_314_165).wrapping_add(907_633_515); - let ltp_q14 = if voiced { - let base = ltp_buf_idx as isize - lag as isize + (LTP_ORDER / 2) as isize; - let g = |o: isize| -> i32 { if base - o >= 0 { s_ltp_q15[(base - o) as usize] } else { 0 } }; - let mut pred = 2i32; - for o in 0..LTP_ORDER { - pred = smlawb(pred, g(o as isize), b_q14[o]); - } - pred << 1 - } else { - 0 - }; - let mut lpc_pred = (order >> 1) as i32; - for j in 0..order { - lpc_pred = smlawb(lpc_pred, s_lpc[MAX_LPC_ORDER + i - 1 - j], a_q12[j]); - } - let lpc_q14 = lpc_pred.saturating_mul(16); - // Target excitation (Q14) for this sample. - let fb: f64 = nf_c.iter().zip(ring.window()).take(order).map(|(c, e)| c * e).sum(); - let tgt = (x[n] as f64 + fb).clamp(-32768.0, 32767.0) * inv_g - lpc_q14 as f64 - ltp_q14 as f64; - let sgn = if seed_v < 0 { -1.0 } else { 1.0 }; - let u = sgn * tgt; - let pf = (u - off16 as f64) / 16384.0; - let p0 = if pf > 0.0 { (pf + 0.078_125).round() } else { (pf - 0.078_125).round() } as i32; - let level = |q: i32| -> i32 { - let mut e = q << 14; - if e > 0 { - e -= 80 << 4; - } else if e < 0 { - e += 80 << 4; - } - e + off16 - }; - let mut best = (f64::MAX, 0i32); - for q in [p0 - 1, p0, p0 + 1, 0] { - let q = q.clamp(-pulses::MAX_PULSE, pulses::MAX_PULSE); - let d = (level(q) as f64 - u) / 16384.0; - let cost = d * d + RD_LAMBDA * q.abs() as f64; - if cost < best.0 { - best = (cost, q); - } - } - let q = best.1; - pulses[n] = q; - let mut e = level(q); - if seed_v < 0 { - e = -e; - } - seed_v = seed_v.wrapping_add(q); - let res = e.wrapping_add(ltp_q14); - if voiced { - s_ltp_q15[ltp_buf_idx] = res << 1; - ltp_buf_idx += 1; - } - let v = res.saturating_add(lpc_q14); - s_lpc[MAX_LPC_ORDER + i] = v; - xq[n] = sat16(rshift_round(smulww(v, gain_q10), 8)) as i16; - ring.push(xq[n] as f64 - x[n] as f64); - } - s_lpc.copy_within(sub..sub + MAX_LPC_ORDER, 0); - } - self.nf = ring.to_array(); - st.s_lpc_q14.copy_from_slice(&s_lpc[..MAX_LPC_ORDER]); - st.out_buf[..l].copy_from_slice(&xq); - (Coded { gain_ix, gains_q16, seed, pulses }, xq) - } - - /// Writes the frame's indices and pulses (`decode_indices` + `decode_pulses` order, coded - /// independently). - fn write(&self, enc: &mut RangeEncoder, p: &Params, c: &Coded) { - let ix = p.signal_type * 2 + p.quant_offset_type; - if p.vad { - enc.icdf(ix - 2, &TYPE_ACTIVE, 8); - } else { - enc.icdf(ix, &TYPE_INACTIVE, 8); - } - enc.icdf((c.gain_ix[0] >> 3) as usize, GAIN_MSB[p.signal_type], 8); - enc.icdf((c.gain_ix[0] & 7) as usize, &UNIFORM8, 8); - for k in 1..4 { - enc.icdf(c.gain_ix[k] as usize, &DELTA_GAIN, 8); - } - let wb = self.order == 16; - let i1 = p.nlsf_ix[0] as usize; - enc.icdf(i1, NLSF_STAGE1[(p.signal_type >> 1) + if wb { 2 } else { 0 }], 8); - for i in 0..self.order { - let cb = if wb { 8 + NLSF_SEL_WB[i1][i] as usize } else { NLSF_SEL_NBMB[i1][i] as usize }; - let v = p.nlsf_ix[i + 1] + 4; - if v <= 0 { - enc.icdf(0, NLSF_STAGE2[cb], 8); - enc.icdf((-v) as usize, &NLSF_EXT, 8); - } else if v >= 8 { - enc.icdf(8, NLSF_STAGE2[cb], 8); - enc.icdf((v - 8) as usize, &NLSF_EXT, 8); - } else { - enc.icdf(v as usize, NLSF_STAGE2[cb], 8); - } - } - // No NLSF interpolation. - enc.icdf(4, &NLSF_INTERP, 8); - if p.signal_type == 2 { - let half = (self.fs_khz >> 1) as i32; - enc.icdf((p.lag_index / half) as usize, &PITCH_HIGH, 8); - let low = match self.fs_khz { - 8 => PITCH_LOW[0], - 12 => PITCH_LOW[1], - _ => PITCH_LOW[2], - }; - enc.icdf((p.lag_index % half) as usize, low, 8); - enc.icdf(p.contour, if self.fs_khz == 8 { PITCH_CONTOUR[1] } else { PITCH_CONTOUR[3] }, 8); - enc.icdf(p.per_index, <P_PERIODICITY, 8); - for k in 0..4 { - enc.icdf(p.ltp_index[k], LTP_FILTER[p.per_index], 8); - } - // LTP scaling index 0 (15565 in Q14), matching `quantize`. - enc.icdf(0, <P_SCALE, 8); - } - enc.icdf(c.seed, &UNIFORM4, 8); - pulses::encode(enc, &c.pulses, p.signal_type, p.quant_offset_type); - } -} - -/// Quantises a stereo prediction weight (Q13) to the decoder's grid (§4.2.7.1): returns the -/// (UNIFORM3, UNIFORM5, joint) indices and the reconstructed value. -fn quant_pred(w: f64) -> ([usize; 3], i32) { - let mut best = (f64::MAX, [0usize; 3], 0i32); - for i in 0..15 { - let low = STEREO_WEIGHTS_Q13[i]; - let step = smulwb(STEREO_WEIGHTS_Q13[i + 1] - low, 6554); - for j in 0..5 { - let v = low + step * (2 * j as i32 + 1); - let e = (v as f64 - w).abs(); - if e < best.0 { - best = (e, [i % 3, j, i / 3], v); - } - } - } - (best.1, best.2) -} - -/// Per-frame preparation shared by every rate-loop trial. -struct Prep { - x: [Vec; 2], - params: [Params; 2], - mid_only: bool, - pred_ix: [[usize; 3]; 2], - pred_q13: [i32; 2], -} - -/// One rate-loop trial: the frame coded at gain offset `offset`. -struct Trial { - offset: f64, - bits: i32, - state: SilkEncoder, - coder: RangeEncoder, -} - -/// SILK encoder for one mono or stereo (mid/side) stream. -#[derive(Clone)] -pub struct SilkEncoder { - fs_khz: usize, - channels: usize, - ch: [Channel; 2], - pred_prev_q13: [i32; 2], - prev_mid_only: bool, - /// Last mid sample of the previous frame (for the stereo predictor's low-pass). - prev_mid: f32, - frame: usize, - /// Gain offset chosen for the previous frame (search starting point). - pub last_offset: f64, -} - -impl SilkEncoder { - pub fn new(fs_khz: usize, channels: usize) -> Self { - SilkEncoder { - fs_khz, - channels, - ch: [Channel::new(fs_khz), Channel::new(fs_khz)], - pred_prev_q13: [0; 2], - prev_mid_only: false, - prev_mid: 0.0, - frame: 0, - last_offset: 1.0, - } - } - - /// Samples per channel of one 20 ms frame at the internal rate. - pub fn frame_len(&self) -> usize { - 20 * self.fs_khz - } - - fn prepare(&self, input: &[Vec]) -> Prep { - let l = self.frame_len(); - if self.channels == 1 { - let x = input[0].clone(); - let p = self.ch[0].analyze(&x); - return Prep { x: [x, vec![0.0; l]], params: [p, Params::default()], mid_only: true, pred_ix: [[0; 3]; 2], pred_q13: [0; 2] }; - } - let mid: Vec = (0..l).map(|i| 0.5 * (input[0][i] + input[1][i])).collect(); - let side: Vec = (0..l).map(|i| 0.5 * (input[0][i] - input[1][i])).collect(); - let lp = |j: usize| -> f64 { - let a = if j == 0 { self.prev_mid } else { mid[j - 1] }; - let c = if j + 1 < l { mid[j + 1] } else { mid[l - 1] }; - (a as f64 + 2.0 * mid[j] as f64 + c as f64) / 4.0 - }; - // Least-squares prediction of the side from the low-passed mid and the mid. - let (mut r00, mut r01, mut r11, mut c0, mut c1, mut ss, mut mm) = (0f64, 0f64, 0f64, 0f64, 0f64, 0f64, 0f64); - for j in 0..l { - let (a, b, s) = (lp(j), mid[j] as f64, side[j] as f64); - r00 += a * a; - r01 += a * b; - r11 += b * b; - c0 += a * s; - c1 += b * s; - ss += s * s; - mm += b * b; - } - // Ridge regularisation: the low-passed mid and the mid are nearly collinear. - let lam = 0.02 * 0.5 * (r00 + r11) + 1e-9; - let (a00, a11) = (r00 + lam, r11 + lam); - let det = a00 * a11 - r01 * r01; - let (p0, p1) = ((c0 * a11 - c1 * r01) / det, (c1 * a00 - c0 * r01) / det); - let lim = 13732.0; - let quant = |p0: f64, p1: f64| { - let (ix0, q0) = quant_pred(((p0 + p1) * 8192.0).clamp(-lim, lim)); - let (ix1, q1) = quant_pred((p1 * 8192.0).clamp(-lim, lim)); - ([ix0, ix1], [q0 - q1, q1]) - }; - // Side residual with the decoder's interpolated predictor. - let fs = self.fs_khz as i32; - let denom_q16 = (1 << 16) / (8 * fs); - let interp = 8 * self.fs_khz; - let residual = |pred_q13: [i32; 2]| -> Vec { - let d0 = rshift_round((pred_q13[0] - self.pred_prev_q13[0]) as i16 as i32 * denom_q16 as i16 as i32, 16); - let d1 = rshift_round((pred_q13[1] - self.pred_prev_q13[1]) as i16 as i32 * denom_q16 as i16 as i32, 16); - let (mut pp0, mut pp1) = (self.pred_prev_q13[0] + d0, self.pred_prev_q13[1] + d1); - (0..l) - .map(|j| { - if j + 1 < interp { - pp0 += d0; - pp1 += d1; - } else { - pp0 = pred_q13[0]; - pp1 = pred_q13[1]; - } - (side[j] as f64 - (pp0 as f64 * lp(j) + pp1 as f64 * mid[j] as f64) / 8192.0) as f32 - }) - .collect() - }; - let energy = |v: &[f32]| -> f64 { v.iter().map(|&x| (x as f64).powi(2)).sum() }; - let (mut pred_ix, mut pred_q13) = quant(p0, p1); - let mut res = residual(pred_q13); - let mut res_e = energy(&res); - // Never predict worse than not predicting at all. - if res_e > ss { - (pred_ix, pred_q13) = quant(0.0, 0.0); - res = residual(pred_q13); - res_e = energy(&res); - } - let res_rms = (res_e / l as f64).sqrt(); - let mid_rms = (mm / l as f64).sqrt(); - let mid_only = res_rms < 0.01 * mid_rms + 1.0; - let pm = self.ch[0].analyze(&mid); - let ps = if mid_only { Params::default() } else { self.ch[1].analyze(&res) }; - Prep { x: [mid, res], params: [pm, ps], mid_only, pred_ix, pred_q13 } - } - - /// Codes one frame into `enc` with gain offset `offset`. - fn code(&mut self, prep: &Prep, offset: f64, enc: &mut RangeEncoder) { - let stereo = self.channels == 2; - let side_vad = stereo && !prep.mid_only && prep.params[1].vad; - enc.bit_logp(prep.params[0].vad, 1); - enc.bit_logp(false, 1); - if stereo { - enc.bit_logp(side_vad, 1); - enc.bit_logp(false, 1); - let [a, b] = prep.pred_ix; - enc.icdf(5 * a[2] + b[2], &STEREO_PRED_JOINT, 8); - enc.icdf(a[0], &UNIFORM3, 8); - enc.icdf(a[1], &UNIFORM5, 8); - enc.icdf(b[0], &UNIFORM3, 8); - enc.icdf(b[1], &UNIFORM5, 8); - if !side_vad { - enc.icdf(prep.mid_only as usize, &MID_ONLY, 8); - } - } - let seed = self.frame & 3; - let (cm, _) = self.ch[0].quantize(&prep.params[0], &prep.x[0], offset, None, seed); - self.ch[0].write(enc, &prep.params[0], &cm); - if stereo { - if !prep.mid_only { - if self.prev_mid_only { - self.ch[1].dec.reset_side(); - } - let (cs, _) = self.ch[1].quantize(&prep.params[1], &prep.x[1], offset, Some(&cm.gains_q16), seed); - self.ch[1].write(enc, &prep.params[1], &cs); - } - self.pred_prev_q13 = prep.pred_q13; - self.prev_mid_only = prep.mid_only; - } - } - - /// Encodes one 20 ms frame (`input`: one internal-rate, 16-bit-scale vector per channel) - /// into `enc`, aiming at `target_bits` total and never exceeding `max_bits`. - pub fn encode(&mut self, input: &[Vec], target_bits: f64, max_bits: i32, enc: &mut RangeEncoder) { - let prep = self.prepare(input); - let start_bits = enc.tell(); - // Every trial codes the frame into a clone of the encoder and the range coder. The result - // is kept per offset: the hard-limit check below hits the memo for the chosen offset, and - // the final step adopts that trial instead of coding the frame once more. - let mut trials: Vec = Vec::new(); - let mut trial = |s: &Self, o: f64| -> i32 { - if let Some(t) = trials.iter().find(|t| t.offset == o) { - return t.bits; - } - let mut state = s.clone(); - let mut coder = enc.clone(); - state.code(&prep, o, &mut coder); - let bits = coder.tell() - start_bits; - trials.push(Trial { offset: o, bits, state, coder }); - bits - }; - // Bisection on the gain offset: the smallest offset (finest quantisation) within budget. - let target = target_bits.min(max_bits as f64); - // Bits are not strictly monotonic in the offset (very coarse quantisation feeds large - // errors back), so walk an integer grid from the previous frame's offset to find a - // bracket [infeasible, feasible], then bisect inside it. - const MIN_O: f64 = -3.0; - const MAX_O: f64 = 6.0; - let mut best_any = (i32::MAX, MAX_O); - let mut probe = |o: f64| -> bool { - let b = trial(self, o); - if b < best_any.0 { - best_any = (b, o); - } - b as f64 <= target - }; - let g0 = self.last_offset.round().clamp(MIN_O, MAX_O); - let mut bracket = None; - if probe(g0) { - let mut hi = g0; - loop { - if hi - 1.0 < MIN_O { - bracket = Some((None, hi)); - break; - } - if probe(hi - 1.0) { - hi -= 1.0; - } else { - bracket = Some((Some(hi - 1.0), hi)); - break; - } - } - } else { - let mut lo = g0; - while lo + 1.0 <= MAX_O { - if probe(lo + 1.0) { - bracket = Some((Some(lo), lo + 1.0)); - break; - } - lo += 1.0; - } - } - let mut o = match bracket { - Some((Some(mut lo), mut hi)) => { - for _ in 0..4 { - let m = 0.5 * (lo + hi); - if probe(m) { - hi = m; - } else { - lo = m; - } - } - hi - } - Some((None, hi)) => hi, - None => best_any.1, - }; - // Hard limit (hybrid packets must leave room for CELT). - while trial(self, o) > max_bits && o < 12.0 { - o += 1.0; - } - match trials.iter().position(|t| t.offset == o) { - Some(i) => { - let t = trials.swap_remove(i); - *self = t.state; - *enc = t.coder; - } - None => self.code(&prep, o, enc), - } - self.end_frame(&prep, o); - } - - /// Advances the input history and the frame counter after frame `prep` was coded at `o`. - fn end_frame(&mut self, prep: &Prep, o: f64) { - self.last_offset = o; - for ch in 0..self.channels { - self.ch[ch].push_history(&prep.x[ch]); - } - if self.channels == 2 { - self.prev_mid = prep.x[0][self.frame_len() - 1]; - } - self.frame += 1; - } -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Deterministic speech-like test input: two harmonics with a moving pitch, a syllable - /// envelope, noise and short silences, at the internal rate and 16-bit scale. - fn signal(len: usize, fs_khz: usize, seed: u32) -> Vec { - let mut s = seed; - let fs = (fs_khz * 1000) as f64; - (0..len) - .map(|i| { - s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - let noise = (s >> 8) as f64 / (1u32 << 24) as f64 - 0.5; - let t = i as f64 / fs; - let f0 = 140.0 + 40.0 * (t * 1.3).sin(); - let env = ((t * 4.0).sin().max(0.0)).powf(0.7); - let voiced = (std::f64::consts::TAU * f0 * t).sin() + 0.5 * (std::f64::consts::TAU * 2.0 * f0 * t).sin(); - (8000.0 * env * voiced + 600.0 * noise) as f32 - }) - .collect() - } - - #[test] - fn nf_ring_matches_a_shifted_history() { - let mut hist = [0f64; MAX_LPC_ORDER]; - for (i, h) in hist.iter_mut().enumerate() { - *h = i as f64 * 0.5 - 3.0; - } - let mut ring = NfRing::new(&hist); - assert_eq!(ring.window(), &hist[..]); - for n in 0..100 { - let v = (n as f64 * 0.37).sin() * 100.0; - hist.copy_within(0..MAX_LPC_ORDER - 1, 1); - hist[0] = v; - ring.push(v); - assert_eq!(ring.window(), &hist[..], "after push {n}"); - } - assert_eq!(ring.to_array(), hist); - } - - /// The rate loop adopts the memoised trial for the chosen offset. A second encoder that codes - /// every frame afresh at that offset (what the loop did before the memo) must produce the - /// same bytes, frame after frame, so the adopted encoder and range-coder states are exact. - #[test] - fn adopting_the_memoised_trial_equals_coding_the_frame_again() { - for (fs_khz, channels, target_bits, max_bits) in - [(8, 1, 200.0, 1000), (12, 1, 320.0, 1000), (16, 1, 480.0, 1000), (16, 2, 640.0, 1000), (16, 1, 900.0, 400), (8, 2, 120.0, 160)] - { - let mut memo = SilkEncoder::new(fs_khz, channels); - let mut fresh = memo.clone(); - let l = memo.frame_len(); - let frames = 40; - let left = signal(l * frames, fs_khz, 7); - let right: Vec = signal(l * frames + 37, fs_khz, 11)[37..].iter().map(|v| v * 0.6).collect(); - for f in 0..frames { - let mut input = vec![left[f * l..(f + 1) * l].to_vec()]; - if channels == 2 { - input.push(right[f * l..(f + 1) * l].to_vec()); - } - let mut enc = RangeEncoder::new(); - memo.encode(&input, target_bits, max_bits, &mut enc); - let o = memo.last_offset; - let prep = fresh.prepare(&input); - let mut enc_fresh = RangeEncoder::new(); - fresh.code(&prep, o, &mut enc_fresh); - fresh.end_frame(&prep, o); - assert_eq!(enc.tell(), enc_fresh.tell(), "{fs_khz} kHz {channels} ch frame {f}"); - assert_eq!(enc.done(1275), enc_fresh.done(1275), "{fs_khz} kHz {channels} ch frame {f}"); - for c in 0..channels { - assert_eq!(memo.ch[c].nf, fresh.ch[c].nf, "noise feedback, channel {c}, frame {f}"); - assert_eq!(memo.ch[c].dec.s_lpc_q14, fresh.ch[c].dec.s_lpc_q14, "LPC state, channel {c}, frame {f}"); - } - } - } - } -} diff --git a/crates/opusenc/src/silk/analysis.rs b/crates/opusenc/src/silk/analysis.rs deleted file mode 100644 index d80052046..000000000 --- a/crates/opusenc/src/silk/analysis.rs +++ /dev/null @@ -1,418 +0,0 @@ -//! Encoder-side signal analysis for SILK (own design): windowed autocorrelation LPC, LPC → NLSF -//! conversion, open-loop pitch search and LTP codebook search. - -use super::tables::{CB_NB_20, CB_WB_20, LTP_FILTER, LTP_PERIODICITY, LTP_TAPS_0, LTP_TAPS_1, LTP_TAPS_2}; - -/// Short-term prediction coefficients `a` (prediction `x[n] ≈ Σ a[j] x[n-1-j]`) from the -/// windowed segment `x`, with a Gaussian lag window and white-noise correction. -pub fn lpc(x: &[f32], order: usize, fs_khz: usize) -> Vec { - let n = x.len(); - // Asymmetric window: sin² rise over the first half, flat, cos fall over the last 1/8. - let rise = n / 2; - let fall = n / 8; - let w = |i: usize| -> f64 { - if i < rise { - let s = (std::f64::consts::FRAC_PI_2 * (i as f64 + 0.5) / rise as f64).sin(); - s * s - } else if i >= n - fall { - (std::f64::consts::FRAC_PI_2 * (i + fall - n) as f64 / fall as f64 + 0.0).cos() - } else { - 1.0 - } - }; - let xw: Vec = x.iter().enumerate().map(|(i, &v)| v as f64 * w(i)).collect(); - let mut r = vec![0f64; order + 1]; - for (k, rk) in r.iter_mut().enumerate() { - *rk = xw[k..].iter().zip(&xw).map(|(a, b)| a * b).sum(); - } - if r[0] <= 1e-6 { - return vec![0.0; order]; - } - // White-noise correction (-40 dB) and a 50 Hz Gaussian lag window. - r[0] *= 1.0 + 1e-4; - let f0 = 2.0 * std::f64::consts::PI * 50.0 / (fs_khz as f64 * 1000.0); - for (k, rk) in r.iter_mut().enumerate().skip(1) { - *rk *= (-0.5 * (f0 * k as f64).powi(2)).exp(); - } - let mut a = levinson(&r, order); - // Mild bandwidth expansion keeps the NLSFs apart. - let mut g = 1.0; - for v in a.iter_mut() { - g *= 0.996; - *v *= g; - } - a -} - -/// Levinson-Durbin recursion on autocorrelation `r` (predictor convention as in [`lpc`]). -pub fn levinson(r: &[f64], order: usize) -> Vec { - let mut a = vec![0f64; order]; - let mut err = r[0]; - let mut tmp = vec![0f64; order]; - for i in 0..order { - let mut acc = r[i + 1]; - for j in 0..i { - acc -= a[j] * r[i - j]; - } - let k = (acc / err).clamp(-0.9999, 0.9999); - tmp[..i].copy_from_slice(&a[..i]); - for j in 0..i { - a[j] = tmp[j] - k * tmp[i - 1 - j]; - } - a[i] = k; - err *= 1.0 - k * k; - if err <= 0.0 { - break; - } - } - a -} - -/// Evaluates the symmetric polynomial `p` (length `d + 1`, `d` even) as the cosine series -/// `e^{jωd/2} P(e^{jω})`, with `cos_m(m)` giving `cos(m ω)`. -#[inline] -fn cos_series_with(p: &[f64], cos_m: impl Fn(usize) -> f64) -> f64 { - let h = (p.len() - 1) / 2; - let mut s = p[h]; - for k in 0..h { - s += 2.0 * p[k] * cos_m(h - k); - } - s -} - -fn cos_series(p: &[f64], w: f64) -> f64 { - cos_series_with(p, |m| (m as f64 * w).cos()) -} - -/// Number of grid intervals the root search scans over `[0, π]`. -const GRID: usize = 1024; -/// Largest multiple of ω in the series (half the LPC order, at most 16 / 2). -const MAX_H: usize = 8; -/// Bisection steps per root: the bracket shrinks to 3e-9 rad, far below one Q15 NLSF step (9.6e-5 rad). -const BISECT_STEPS: usize = 20; - -/// `cos(m · π g / GRID)` for every grid point `g` and `m` in `0..=MAX_H`, computed with the same -/// expression as [`cos_series`], so the table values are bit-identical to calling `cos` there. -fn grid_cos() -> &'static [[f64; MAX_H + 1]] { - static TABLE: std::sync::OnceLock> = std::sync::OnceLock::new(); - TABLE.get_or_init(|| { - (0..=GRID) - .map(|g| { - let w = std::f64::consts::PI * g as f64 / GRID as f64; - std::array::from_fn(|m| (m as f64 * w).cos()) - }) - .collect() - }) -} - -fn roots(p: &[f64], out: &mut Vec) { - let grid = grid_cos(); - let at_grid = |g: usize| cos_series_with(p, |m| grid[g][m]); - let mut w0 = 0.0; - let mut f0 = at_grid(0); - for g in 1..=GRID { - let w1 = std::f64::consts::PI * g as f64 / GRID as f64; - let f1 = at_grid(g); - if f0 == 0.0 { - out.push(w0); - } else if f0 * f1 < 0.0 { - let (mut lo, mut hi, mut flo) = (w0, w1, f0); - for _ in 0..BISECT_STEPS { - let mid = 0.5 * (lo + hi); - let fm = cos_series(p, mid); - if fm * flo <= 0.0 { - hi = mid; - } else { - lo = mid; - flo = fm; - } - } - out.push(0.5 * (lo + hi)); - } - w0 = w1; - f0 = f1; - } -} - -/// LPC → normalised line spectral frequencies in radians (ascending, `order` values), or `None` -/// when the root search fails (unstable or degenerate filter). -pub fn a2nlsf(a: &[f64]) -> Option> { - let d = a.len(); - if d > 2 * MAX_H { - return None; - } - let mut c = vec![0f64; d + 2]; - c[0] = 1.0; - for k in 0..d { - c[k + 1] = -a[k]; - } - let mut p = vec![0f64; d + 2]; - let mut q = vec![0f64; d + 2]; - for k in 0..d + 2 { - p[k] = c[k] + c[d + 1 - k]; - q[k] = c[k] - c[d + 1 - k]; - } - // Remove the trivial roots at z = -1 (P) and z = +1 (Q). - let mut p1 = vec![0f64; d + 1]; - let mut q1 = vec![0f64; d + 1]; - p1[0] = p[0]; - q1[0] = q[0]; - for k in 1..=d { - p1[k] = p[k] - p1[k - 1]; - q1[k] = q[k] + q1[k - 1]; - } - let mut r = Vec::with_capacity(d); - roots(&p1, &mut r); - roots(&q1, &mut r); - if r.len() != d { - return None; - } - r.sort_by(f64::total_cmp); - Some(r) -} - -/// Normalised cross-correlation of `x[n]` and `x[n - lag]` over `n` in `range`. -fn ncorr(x: &[f32], range: std::ops::Range, lag: usize) -> f64 { - let (mut xy, mut xx, mut yy) = (0f64, 0f64, 0f64); - for n in range { - let a = x[n] as f64; - let b = x[n - lag] as f64; - xy += a * b; - xx += a * a; - yy += b * b; - } - if xy <= 0.0 { 0.0 } else { xy / (xx * yy + 1e-9).sqrt() } -} - -pub struct Pitch { - pub lag_index: i32, - pub contour: usize, - pub lags: [i32; 4], - pub score: f64, -} - -/// Open-loop pitch search on `x` (history followed by the frame starting at `start`, `len` -/// samples, four subframes) at `fs_khz`. -pub fn pitch_search(x: &[f32], start: usize, len: usize, fs_khz: usize) -> Pitch { - let fs = fs_khz as i32; - let min_lag = 2 * fs; - let max_lag = 18 * fs - 1; - let sub = len / 4; - let nl = (max_lag - min_lag + 1) as usize; - // Whole-frame score per lag. - let full: Vec = (0..nl).map(|i| ncorr(x, start..start + len, min_lag as usize + i)).collect(); - let mut best = 0usize; - for i in 0..nl { - // Slight preference for shorter lags. - if full[i] * (1.0 - 0.0004 * i as f64) > full[best] * (1.0 - 0.0004 * best as f64) { - best = i; - } - } - let mut lag = min_lag + best as i32; - // Prefer a sub-multiple when it explains the signal almost as well (octave errors). - for div in [4, 3, 2] { - let cand = (lag as f64 / div as f64).round() as i32; - let mut cbest = (0.0, 0); - for c in cand - 1..=cand + 1 { - if c >= min_lag && c <= max_lag { - let s = full[(c - min_lag) as usize]; - if s > cbest.0 { - cbest = (s, c); - } - } - } - if cbest.1 != 0 && cbest.0 > 0.9 * full[(lag - min_lag) as usize] { - lag = cbest.1; - break; - } - } - let score = full[(lag - min_lag) as usize]; - // Contour: per-subframe lag offsets around the chosen lag. - let cb: &[[i32; 4]] = if fs_khz == 8 { &CB_NB_20 } else { &CB_WB_20 }; - // The contour search revisits the same (subframe, lag) pairs for neighbouring base lags and - // codebook entries, so each correlation is computed once. - let span = (18 * fs - min_lag + 1) as usize; - let memo = std::cell::RefCell::new(vec![f64::NAN; 4 * span]); - let sub_score = |k: usize, l: i32| -> f64 { - let l = l.clamp(min_lag, 18 * fs); - let slot = k * span + (l - min_lag) as usize; - let cached = memo.borrow()[slot]; - if !cached.is_nan() { - return cached; - } - let v = ncorr(x, start + k * sub..start + (k + 1) * sub, l as usize); - memo.borrow_mut()[slot] = v; - v - }; - let mut best = (f64::MIN, lag, 0usize); - for l0 in (lag - 2).max(min_lag)..=(lag + 2).min(max_lag) { - for (ci, offs) in cb.iter().enumerate() { - let s: f64 = (0..4).map(|k| sub_score(k, l0 + offs[k])).sum::() - 0.002 * ci as f64; - if s > best.0 { - best = (s, l0, ci); - } - } - } - let (_, l0, ci) = best; - let mut lags = [0i32; 4]; - for k in 0..4 { - lags[k] = (l0 + cb[ci][k]).clamp(min_lag, 18 * fs); - } - Pitch { lag_index: l0 - min_lag, contour: ci, lags, score } -} - -/// Result of the LTP codebook search. -pub struct Ltp { - pub per_index: usize, - pub ltp_index: [usize; 4], - /// Residual energy after LTP prediction / before, per subframe. - pub err: [f64; 4], - pub energy: [f64; 4], -} - -fn icdf_bits(icdf: &[u8], s: usize) -> f64 { - let hi = if s == 0 { 256 } else { icdf[s - 1] as u32 }; - let p = (hi - icdf[s] as u32).max(1) as f64 / 256.0; - -p.log2() -} - -/// Searches the three LTP codebooks (RFC 6716 Tables 39–42) for the taps that best predict the -/// residual `r` (history + frame starting at `start`) from its past at the per-subframe `lags`. -pub fn ltp_search(r: &[f64], start: usize, sub: usize, lags: &[i32; 4]) -> Ltp { - let mut rr = [[0f64; 25]; 4]; - let mut cv = [[0f64; 5]; 4]; - let mut e = [0f64; 4]; - for k in 0..4 { - let s0 = start + k * sub; - let lag = lags[k] as usize; - for n in s0..s0 + sub { - let t = r[n]; - e[k] += t * t; - let base = n + 2 - lag; - for i in 0..5 { - let vi = r[base - i]; - cv[k][i] += t * vi; - for j in 0..5 { - rr[k][i * 5 + j] += vi * r[base - j]; - } - } - } - } - let books: [&[[i32; 5]]; 3] = [<P_TAPS_0, <P_TAPS_1, <P_TAPS_2]; - let mut best = (f64::MAX, 0usize, [0usize; 4], [0f64; 4]); - for (p, book) in books.iter().enumerate() { - let mut total = icdf_bits(<P_PERIODICITY, p) * 1e-3 * e.iter().sum::() / 4.0; - let mut idx = [0usize; 4]; - let mut errs = [0f64; 4]; - for k in 0..4 { - let mut bk = (f64::MAX, 0usize, 0f64); - for (i, taps) in book.iter().enumerate() { - let b: [f64; 5] = std::array::from_fn(|j| taps[j] as f64 / 128.0); - let mut err = e[k]; - for a in 0..5 { - err -= 2.0 * b[a] * cv[k][a]; - for c in 0..5 { - err += b[a] * b[c] * rr[k][a * 5 + c]; - } - } - let cost = err + icdf_bits(LTP_FILTER[p], i) * 1e-3 * e[k]; - if cost < bk.0 { - bk = (cost, i, err.max(0.0)); - } - } - total += bk.0; - idx[k] = bk.1; - errs[k] = bk.2; - } - if total < best.0 { - best = (total, p, idx, errs); - } - } - Ltp { per_index: best.1, ltp_index: best.2, err: best.3, energy: e } -} - -#[cfg(test)] -mod tests { - use super::super::lpc::nlsf2a; - use super::*; - - #[test] - fn nlsf_roundtrip_through_decoder_conversion() { - // A resonant 10th/16th-order predictor from a synthetic signal. - for &(order, fs) in &[(10usize, 8usize), (16, 16)] { - let mut st = [0f64; 4]; - let mut seed = 1u32; - let x: Vec = (0..400) - .map(|_| { - seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - let w = (seed >> 9) as f64 / (1u32 << 23) as f64 - 1.0; - let y = w + 1.6 * st[0] - 0.9 * st[1] + 0.3 * st[2] - 0.2 * st[3]; - st = [y, st[0], st[1], st[2]]; - (y * 1000.0) as f32 - }) - .collect(); - let a = lpc(&x, order, fs); - let nlsf = a2nlsf(&a).expect("roots"); - let q15: Vec = nlsf.iter().map(|w| (w / std::f64::consts::PI * 32768.0).round() as i32).collect(); - let a_q12 = nlsf2a(&q15); - for j in 0..order { - assert!((a_q12[j] as f64 / 4096.0 - a[j]).abs() < 0.02, "order {order} coef {j}: {} vs {}", a_q12[j] as f64 / 4096.0, a[j]); - } - } - } - - /// The root search as it was before the grid table: `cos` called for every evaluation. - fn roots_reference(p: &[f64], out: &mut Vec) { - let mut w0 = 0.0; - let mut f0 = cos_series(p, w0); - for g in 1..=GRID { - let w1 = std::f64::consts::PI * g as f64 / GRID as f64; - let f1 = cos_series(p, w1); - if f0 == 0.0 { - out.push(w0); - } else if f0 * f1 < 0.0 { - let (mut lo, mut hi, mut flo) = (w0, w1, f0); - for _ in 0..BISECT_STEPS { - let mid = 0.5 * (lo + hi); - let fm = cos_series(p, mid); - if fm * flo <= 0.0 { - hi = mid; - } else { - lo = mid; - flo = fm; - } - } - out.push(0.5 * (lo + hi)); - } - w0 = w1; - f0 = f1; - } - } - - #[test] - fn grid_table_roots_are_bit_identical_to_direct_cos() { - let mut seed = 7u64; - let mut rnd = move || { - seed ^= seed << 13; - seed ^= seed >> 7; - seed ^= seed << 17; - (seed >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0 - }; - let mut found = 0; - for len in [11usize, 17] { - for _ in 0..300 { - let mut p = vec![0f64; len]; - for k in 0..len / 2 + 1 { - p[k] = rnd(); - p[len - 1 - k] = p[k]; - } - let (mut a, mut b) = (Vec::new(), Vec::new()); - roots(&p, &mut a); - roots_reference(&p, &mut b); - assert_eq!(a.iter().map(|v| v.to_bits()).collect::>(), b.iter().map(|v| v.to_bits()).collect::>()); - found += a.len(); - } - } - assert!(found > 1000, "{found}"); - } -} diff --git a/crates/opusenc/src/silk/lpc.rs b/crates/opusenc/src/silk/lpc.rs deleted file mode 100644 index e0f8c107e..000000000 --- a/crates/opusenc/src/silk/lpc.rs +++ /dev/null @@ -1,370 +0,0 @@ -//! Fixed-point NLSF decoding, NLSF→LPC conversion and filter stabilisation -//! (RFC 6716 §4.2.7.5, with the RFC 8251 §6/§7 overflow fixes). -//! -//! This is the decoder's normative arithmetic, mirrored from FilmCraft's first-party, -//! spec-derived `filmcraft-opus` decoder (MIT OR Apache-2.0): the encoder must reconstruct the -//! quantised NLSFs and LPC coefficients bit-exactly as the decoder does. - -use super::tables::{ - COS_Q12, LSF_ORDER_NBMB, LSF_ORDER_WB, NLSF_CB_NBMB, NLSF_CB_WB, NLSF_MIN_SPACING_NBMB, NLSF_MIN_SPACING_WB, NLSF_PRED_NBMB, NLSF_PRED_WB, NLSF_PSEL_NBMB, - NLSF_PSEL_WB, -}; - -pub const MAX_LPC_ORDER: usize = 16; - -#[inline] -pub fn smulwb(a: i32, b: i32) -> i32 { - ((a as i64 * (b as i16) as i64) >> 16) as i32 -} -#[inline] -pub fn smlawb(a: i32, b: i32, c: i32) -> i32 { - a.wrapping_add(smulwb(b, c)) -} -#[inline] -pub fn smulww(a: i32, b: i32) -> i32 { - ((a as i64 * b as i64) >> 16) as i32 -} -#[inline] -pub fn smmul(a: i32, b: i32) -> i32 { - ((a as i64 * b as i64) >> 32) as i32 -} -#[inline] -pub fn rshift_round(a: i32, s: u32) -> i32 { - if s == 1 { (a >> 1) + (a & 1) } else { ((a >> (s - 1)) + 1) >> 1 } -} -#[inline] -pub fn rshift_round64(a: i64, s: u32) -> i64 { - if s == 1 { (a >> 1) + (a & 1) } else { ((a >> (s - 1)) + 1) >> 1 } -} -#[inline] -pub fn sat16(a: i32) -> i32 { - a.clamp(-32768, 32767) -} - -/// `silk_INVERSE32_varQ`: approximation of `(1 << q_res) / b32`. -pub fn inverse32_varq(b32: i32, q_res: i32) -> i32 { - let b_headrm = b32.unsigned_abs().leading_zeros() as i32 - 1; - let b32_nrm = b32.wrapping_shl(b_headrm as u32); - let b32_inv = (i32::MAX >> 2) / (b32_nrm >> 16); - let mut result = b32_inv << 16; - let err_q32 = ((1i32 << 29).wrapping_sub(smulwb(b32_nrm, b32_inv))).wrapping_shl(3); - result = result.wrapping_add(((err_q32 as i64 * b32_inv as i64) >> 16) as i32); - let lshift = 61 - b_headrm - q_res; - if lshift <= 0 { - let s = (-lshift) as u32; - let lim_hi = i32::MAX >> s; - let lim_lo = i32::MIN >> s; - result.clamp(lim_lo, lim_hi) << s - } else if lshift < 32 { - result >> lshift - } else { - 0 - } -} - -/// `silk_DIV32_varQ`: approximation of `(a32 << q_res) / b32`. -pub fn div32_varq(a32: i32, b32: i32, q_res: i32) -> i32 { - let a_headrm = a32.unsigned_abs().leading_zeros() as i32 - 1; - let a32_nrm = a32.wrapping_shl(a_headrm as u32); - let b_headrm = b32.unsigned_abs().leading_zeros() as i32 - 1; - let b32_nrm = b32.wrapping_shl(b_headrm as u32); - let b32_inv = (i32::MAX >> 2) / (b32_nrm >> 16); - let mut result = smulwb(a32_nrm, b32_inv); - let a32_nrm = a32_nrm.wrapping_sub(((smmul(b32_nrm, result) as i64) << 3) as i32); - result = smlawb(result, a32_nrm, b32_inv); - let lshift = 29 + a_headrm - b_headrm - q_res; - if lshift < 0 { - let s = (-lshift) as u32; - let lim_hi = i32::MAX >> s; - let lim_lo = i32::MIN >> s; - result.clamp(lim_lo, lim_hi) << s - } else if lshift < 32 { - result >> lshift - } else { - 0 - } -} - -pub fn sqrt_approx(x: i32) -> i32 { - if x <= 0 { - return 0; - } - let lz = x.leading_zeros() as i32; - let frac = (x.rotate_right((24 - lz).rem_euclid(32) as u32)) & 0x7f; - let mut y = if lz & 1 != 0 { 32768 } else { 46214 }; - y >>= lz >> 1; - smlawb(y, y, 213 * frac) -} - -/// Decodes the stage-1/stage-2 indices into stabilised NLSFs (Q15). -pub fn nlsf_decode(indices: &[i32], wb: bool) -> [i32; MAX_LPC_ORDER] { - let order = if wb { 16 } else { 10 }; - let i1 = indices[0] as usize; - let cb1: &[i32] = if wb { &NLSF_CB_WB[i1] } else { &NLSF_CB_NBMB[i1] }; - let qstep = if wb { 9830 } else { 11796 }; - // Residual dequantisation with backwards prediction. - let mut res_q10 = [0i32; MAX_LPC_ORDER]; - let mut out_q10 = 0i32; - for i in (0..order).rev() { - let pred = if i + 1 < order { - let sel = if wb { NLSF_PSEL_WB[i1][i] } else { NLSF_PSEL_NBMB[i1][i] } as usize; - let w = if wb { NLSF_PRED_WB[sel][i] } else { NLSF_PRED_NBMB[sel][i] }; - (out_q10 * w) >> 8 - } else { - 0 - }; - let mut v = indices[i + 1] << 10; - if v > 0 { - v -= 102; - } else if v < 0 { - v += 102; - } - out_q10 = smlawb(pred, v, qstep); - res_q10[i] = out_q10; - } - // Laroia weights. - let mut nlsf = [0i32; MAX_LPC_ORDER]; - for k in 0..order { - let prev = if k == 0 { 0 } else { cb1[k - 1] }; - let next = if k + 1 == order { 256 } else { cb1[k + 1] }; - let w = (1024 / (cb1[k] - prev).max(1) + 1024 / (next - cb1[k]).max(1)).min(32767); - let w_q9 = sqrt_approx(w << 16); - let v = (cb1[k] << 7) + (res_q10[k] << 14) / w_q9.max(1); - nlsf[k] = v.clamp(0, 32767); - } - let dmin: &[i32] = if wb { &NLSF_MIN_SPACING_WB } else { &NLSF_MIN_SPACING_NBMB }; - nlsf_stabilize(&mut nlsf[..order], dmin); - nlsf -} - -pub fn nlsf_stabilize(nlsf: &mut [i32], dmin: &[i32]) { - let l = nlsf.len(); - for _ in 0..20 { - let mut min_diff = nlsf[0] - dmin[0]; - let mut idx = 0; - for i in 1..l { - let d = nlsf[i] - (nlsf[i - 1] + dmin[i]); - if d < min_diff { - min_diff = d; - idx = i; - } - } - let d = 32768 - (nlsf[l - 1] + dmin[l]); - if d < min_diff { - min_diff = d; - idx = l; - } - if min_diff >= 0 { - return; - } - if idx == 0 { - nlsf[0] = dmin[0]; - } else if idx == l { - nlsf[l - 1] = 32768 - dmin[l]; - } else { - let mut min_center = dmin[..idx].iter().sum::(); - min_center += dmin[idx] >> 1; - let mut max_center = 32768 - dmin[idx + 1..=l].iter().sum::(); - max_center -= dmin[idx] >> 1; - let c = rshift_round(nlsf[idx - 1] + nlsf[idx], 1); - let c = if min_center > max_center { c.clamp(max_center, min_center) } else { c.clamp(min_center, max_center) }; - nlsf[idx - 1] = c - (dmin[idx] >> 1); - nlsf[idx] = nlsf[idx - 1] + dmin[idx]; - } - } - // Fallback. - nlsf.sort_unstable(); - nlsf[0] = nlsf[0].max(dmin[0]); - for i in 1..l { - nlsf[i] = nlsf[i].max(sat16(nlsf[i - 1] + dmin[i])); - } - nlsf[l - 1] = nlsf[l - 1].min(32768 - dmin[l]); - for i in (0..l - 1).rev() { - nlsf[i] = nlsf[i].min(nlsf[i + 1] - dmin[i + 1]); - } -} - -fn bwexpander_32(ar: &mut [i32], mut chirp_q16: i32) { - let d = ar.len(); - let chirp_minus_one = chirp_q16 - 65536; - for v in ar.iter_mut().take(d - 1) { - *v = smulww(chirp_q16, *v); - chirp_q16 += rshift_round(chirp_q16.wrapping_mul(chirp_minus_one), 16); - } - ar[d - 1] = smulww(chirp_q16, ar[d - 1]); -} - -fn lpc_inverse_pred_gain(a_q12: &[i32]) -> i32 { - const QA: u32 = 24; - const A_LIMIT: i32 = 16_773_022; - let order = a_q12.len(); - let mut a = [0i32; MAX_LPC_ORDER]; - let mut dc = 0; - for k in 0..order { - dc += a_q12[k]; - a[k] = a_q12[k] << (QA - 12); - } - if dc >= 4096 { - return 0; - } - let mut inv_gain: i32 = 1 << 30; - let mul32_frac_q31 = |x: i32, y: i32| rshift_round64(x as i64 * y as i64, 31) as i32; - for k in (1..order).rev() { - if a[k] > A_LIMIT || a[k] < -A_LIMIT { - return 0; - } - let rc_q31 = -(a[k] << (31 - QA)); - let rc_mult1 = (1i32 << 30) - smmul(rc_q31, rc_q31); - inv_gain = smmul(inv_gain, rc_mult1) << 2; - if inv_gain < 107_374 { - return 0; - } - let mult2q = 32 - rc_mult1.unsigned_abs().leading_zeros() as i32; - let rc_mult2 = inverse32_varq(rc_mult1, mult2q + 30); - for n in 0..(k + 1) >> 1 { - let t1 = a[n]; - let t2 = a[k - n - 1]; - let v1 = rshift_round64(t1.saturating_sub(mul32_frac_q31(t2, rc_q31)) as i64 * rc_mult2 as i64, mult2q as u32); - if v1 > i32::MAX as i64 || v1 < i32::MIN as i64 { - return 0; - } - let v2 = rshift_round64(t2.saturating_sub(mul32_frac_q31(t1, rc_q31)) as i64 * rc_mult2 as i64, mult2q as u32); - if v2 > i32::MAX as i64 || v2 < i32::MIN as i64 { - return 0; - } - a[n] = v1 as i32; - a[k - n - 1] = v2 as i32; - } - } - if a[0] > A_LIMIT || a[0] < -A_LIMIT { - return 0; - } - let rc_q31 = -(a[0] << (31 - QA)); - let rc_mult1 = (1i32 << 30) - smmul(rc_q31, rc_q31); - inv_gain = smmul(inv_gain, rc_mult1) << 2; - if inv_gain < 107_374 { - return 0; - } - inv_gain -} - -/// Converts NLSFs (Q15) to stable Q12 LPC coefficients (`silk_NLSF2A`). -pub fn nlsf2a(nlsf: &[i32]) -> [i32; MAX_LPC_ORDER] { - let d = nlsf.len(); - let ordering: &[usize] = if d == 16 { &LSF_ORDER_WB } else { &LSF_ORDER_NBMB }; - let mut c_q17 = [0i32; MAX_LPC_ORDER]; - for k in 0..d { - let i = (nlsf[k] >> 8) as usize; - let f = nlsf[k] & 255; - let c0 = COS_Q12[i]; - let c1 = COS_Q12[(i + 1).min(128)]; - c_q17[ordering[k]] = (c0 * 256 + (c1 - c0) * f + 4) >> 3; - } - let d2 = d / 2; - let find_poly = |off: usize| -> [i64; 10] { - let mut out = [0i64; 10]; - out[0] = 1 << 16; - out[1] = -(c_q17[off] as i64); - for k in 1..d2 { - let ftmp = c_q17[2 * k + off] as i64; - out[k + 1] = 2 * out[k - 1] - ((ftmp * out[k] + 32768) >> 16); - for n in (2..=k).rev() { - out[n] += out[n - 2] - ((ftmp * out[n - 1] + 32768) >> 16); - } - out[1] -= ftmp; - } - out - }; - let p = find_poly(0); - let q = find_poly(1); - let mut a32 = [0i32; MAX_LPC_ORDER]; - for k in 0..d2 { - let ptmp = p[k + 1] + p[k]; - let qtmp = q[k + 1] - q[k]; - a32[k] = (-qtmp - ptmp) as i32; - a32[d - k - 1] = (qtmp - ptmp) as i32; - } - let a32 = &mut a32[..d]; - // Limit the dynamic range (silk_LPC_fit with QIN = 17, QOUT = 12). - let mut a_q12 = [0i32; MAX_LPC_ORDER]; - let mut i = 0; - while i < 10 { - let mut maxabs = 0i32; - let mut idx = 0; - for (k, &v) in a32.iter().enumerate() { - let av = v.saturating_abs(); - if av > maxabs { - maxabs = av; - idx = k; - } - } - let maxabs = rshift_round(maxabs, 5); - if maxabs > 32767 { - let maxabs = maxabs.min(163_838); - let chirp = 65470 - ((maxabs - 32767) << 14) / ((maxabs * (idx as i32 + 1)) >> 2); - bwexpander_32(a32, chirp); - } else { - break; - } - i += 1; - } - if i == 10 { - for k in 0..d { - a_q12[k] = sat16(rshift_round(a32[k], 5)); - a32[k] = a_q12[k] << 5; - } - } else { - for k in 0..d { - a_q12[k] = rshift_round(a32[k], 5); - } - } - for i in 0..16 { - if lpc_inverse_pred_gain(&a_q12[..d]) == 0 { - bwexpander_32(a32, 65536 - (2 << i)); - for k in 0..d { - a_q12[k] = rshift_round(a32[k], 5); - } - } else { - break; - } - } - a_q12 -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn flat_nlsf_gives_small_lpc() { - // Uniformly spaced NLSFs correspond to an (almost) flat spectrum. - let nlsf: Vec = (1..=16).map(|k| k * 32768 / 17).collect(); - let a = nlsf2a(&nlsf); - assert!(a.iter().all(|v| v.abs() < 600), "{a:?}"); - let nlsf: Vec = (1..=10).map(|k| k * 32768 / 11).collect(); - let a = nlsf2a(&nlsf); - assert!(a[..10].iter().all(|v| v.abs() < 600), "{a:?}"); - } - - #[test] - fn stabilize_enforces_spacing() { - let mut v = [100, 90, 80, 30000, 30001, 30002, 31000, 32000, 32700, 32760]; - nlsf_stabilize(&mut v, &NLSF_MIN_SPACING_NBMB); - assert!(v[0] >= NLSF_MIN_SPACING_NBMB[0]); - for i in 1..10 { - assert!(v[i] - v[i - 1] >= NLSF_MIN_SPACING_NBMB[i], "{v:?}"); - } - assert!(32768 - v[9] >= NLSF_MIN_SPACING_NBMB[10]); - } - - #[test] - fn inverse_approximations() { - for &b in &[65536, 100_000, 1 << 20, 81920, 1_686_110_208] { - let inv = inverse32_varq(b, 47) as f64; - let exact = 2f64.powi(47) / b as f64; - assert!((inv - exact).abs() / exact < 1e-3, "{b}"); - } - let q = div32_varq(65536, 131072, 16) as f64; - assert!((q - 32768.0).abs() < 2.0); - } -} diff --git a/crates/opusenc/src/silk/nlsf.rs b/crates/opusenc/src/silk/nlsf.rs deleted file mode 100644 index 4695152ff..000000000 --- a/crates/opusenc/src/silk/nlsf.rs +++ /dev/null @@ -1,130 +0,0 @@ -//! NLSF quantisation (encoder side of RFC 6716 §4.2.7.5): stage-1 vector codebook preselection -//! and a backwards-predictive stage-2 scalar quantiser that reproduces the decoder's residual -//! dequantisation exactly. The search strategy is our own. - -use super::lpc::{MAX_LPC_ORDER, nlsf_decode, smlawb, sqrt_approx}; -use super::tables::{ - NLSF_CB_NBMB, NLSF_CB_WB, NLSF_EXT, NLSF_PRED_NBMB, NLSF_PRED_WB, NLSF_PSEL_NBMB, NLSF_PSEL_WB, NLSF_SEL_NBMB, NLSF_SEL_WB, NLSF_STAGE1, NLSF_STAGE2, -}; - -/// Number of stage-1 candidates refined with stage 2. -const SURVIVORS: usize = 8; -/// Rate weight (weighted squared Q15 error per bit). -const LAMBDA: f64 = 60.0; - -fn icdf_bits(icdf: &[u8], s: usize) -> f64 { - let hi = if s == 0 { 256 } else { icdf[s - 1] as u32 }; - let p = (hi - icdf[s] as u32).max(1) as f64 / 256.0; - -p.log2() -} - -/// Bits of a stage-2 index `q` (-10..=10) with stage-2 table `tab`. -fn stage2_bits(tab: &[u8], q: i32) -> f64 { - let v = q + 4; - if v <= 0 { - icdf_bits(tab, 0) + icdf_bits(&NLSF_EXT, (-v) as usize) - } else if v >= 8 { - icdf_bits(tab, 8) + icdf_bits(&NLSF_EXT, (v - 8) as usize) - } else { - icdf_bits(tab, v as usize) - } -} - -/// Quantises target NLSFs (`target`, Q15 as f64, ascending) and returns the 1 + order indices -/// in the decoder's layout (`[stage1, stage2...]`) together with the reconstructed NLSFs. -pub fn quantize(target: &[f64], signal_type: usize, wb: bool) -> ([i32; 17], [i32; MAX_LPC_ORDER]) { - let order = target.len(); - // Laroia-style weights. - let w: Vec = (0..order) - .map(|k| { - let prev = if k == 0 { 0.0 } else { target[k - 1] }; - let next = if k + 1 == order { 32768.0 } else { target[k + 1] }; - 1.0 / (target[k] - prev).max(50.0) + 1.0 / (next - target[k]).max(50.0) - }) - .collect(); - let s1_tab = NLSF_STAGE1[(signal_type >> 1) + if wb { 2 } else { 0 }]; - let n_cb = 32; - let mut cands: Vec<(f64, usize)> = (0..n_cb) - .map(|i1| { - let cb: &[i32] = if wb { &NLSF_CB_WB[i1] } else { &NLSF_CB_NBMB[i1] }; - let d: f64 = (0..order).map(|k| w[k] * ((cb[k] << 7) as f64 - target[k]).powi(2)).sum(); - (d + LAMBDA * icdf_bits(s1_tab, i1), i1) - }) - .collect(); - cands.sort_by(|a, b| a.0.total_cmp(&b.0)); - let qstep = if wb { 9830 } else { 11796 }; - let mut best = (f64::MAX, [0i32; 17], [0i32; MAX_LPC_ORDER]); - for &(_, i1) in cands.iter().take(SURVIVORS) { - let cb1: &[i32] = if wb { &NLSF_CB_WB[i1] } else { &NLSF_CB_NBMB[i1] }; - let mut ix = [0i32; 17]; - ix[0] = i1 as i32; - let mut bits = icdf_bits(s1_tab, i1); - // Exact decoder weights per coefficient. - let w_q9: Vec = (0..order) - .map(|k| { - let prev = if k == 0 { 0 } else { cb1[k - 1] }; - let next = if k + 1 == order { 256 } else { cb1[k + 1] }; - let ww = (1024 / (cb1[k] - prev).max(1) + 1024 / (next - cb1[k]).max(1)).min(32767); - sqrt_approx(ww << 16).max(1) - }) - .collect(); - let mut out_q10 = 0i32; - for i in (0..order).rev() { - let pred = if i + 1 < order { - let sel = if wb { NLSF_PSEL_WB[i1][i] } else { NLSF_PSEL_NBMB[i1][i] } as usize; - let wp = if wb { NLSF_PRED_WB[sel][i] } else { NLSF_PRED_NBMB[sel][i] }; - (out_q10 * wp) >> 8 - } else { - 0 - }; - let cb = if wb { 8 + NLSF_SEL_WB[i1][i] as usize } else { NLSF_SEL_NBMB[i1][i] as usize }; - let tab = NLSF_STAGE2[cb]; - let want_q10 = (target[i] - (cb1[i] << 7) as f64) * w_q9[i] as f64 / 16384.0; - let step = qstep as f64 * 1024.0 / 65536.0; - let q0 = ((want_q10 - pred as f64) / step).round() as i32; - let mut bq = (f64::MAX, 0i32, 0i32); - for q in (q0 - 1).max(-10)..=(q0 + 1).min(10) { - let mut v = q << 10; - if v > 0 { - v -= 102; - } else if v < 0 { - v += 102; - } - let o = smlawb(pred, v, qstep); - let nl = (cb1[i] << 7) as f64 + ((o << 14) / w_q9[i]) as f64; - let cost = w[i] * (nl - target[i]).powi(2) + LAMBDA * stage2_bits(tab, q); - if cost < bq.0 { - bq = (cost, q, o); - } - } - ix[i + 1] = bq.1; - out_q10 = bq.2; - bits += stage2_bits(tab, bq.1); - } - let nlsf = nlsf_decode(&ix, wb); - let d: f64 = (0..order).map(|k| w[k] * (nlsf[k] as f64 - target[k]).powi(2)).sum(); - let cost = d + LAMBDA * bits; - if cost < best.0 { - best = (cost, ix, nlsf); - } - } - (best.1, best.2) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn quantised_nlsfs_track_the_target() { - for wb in [false, true] { - let order = if wb { 16 } else { 10 }; - // A smooth, plausible NLSF vector. - let target: Vec = (0..order).map(|k| 32768.0 * (k as f64 + 0.8 + 0.3 * (k as f64).sin()) / (order as f64 + 1.0)).collect(); - let (ix, nlsf) = quantize(&target, 1, wb); - assert!(ix[1..=order].iter().all(|v| (-10..=10).contains(v))); - let max_err = (0..order).map(|k| (nlsf[k] as f64 - target[k]).abs()).fold(0.0, f64::max); - assert!(max_err < 1200.0, "wb={wb} max err {max_err}: {:?} vs {target:?}", &nlsf[..order]); - } - } -} diff --git a/crates/opusenc/src/silk/pulses.rs b/crates/opusenc/src/silk/pulses.rs deleted file mode 100644 index ba22b5ec5..000000000 --- a/crates/opusenc/src/silk/pulses.rs +++ /dev/null @@ -1,113 +0,0 @@ -//! Excitation coding (encoder side of RFC 6716 §4.2.7.8): rate level, per-block pulse counts -//! with LSB escapes, the recursive shell code, LSBs and signs, written in exactly the order the -//! decoder reads them. - -use super::tables::{EXC_LSB, EXC_SIGN, PULSE_COUNT, RATE_LEVEL, SHELL_2, SHELL_4, SHELL_8, SHELL_16}; -use crate::range::RangeEncoder; - -/// Largest pulse magnitude the quantiser produces (keeps every 16-sample block codable). -pub const MAX_PULSE: i32 = 500; - -pub fn icdf_bits(icdf: &[u8], s: usize) -> f32 { - let hi = if s == 0 { 256 } else { icdf[s - 1] as u32 }; - let p = (hi - icdf[s] as u32).max(1) as f32 / 256.0; - -p.log2() -} - -fn count_table(nls: usize) -> &'static [u8] { - if nls == 10 { PULSE_COUNT[10] } else { PULSE_COUNT[9] } -} - -fn shell(enc: &mut RangeEncoder, v: &[i32], count: i32) { - let n = v.len(); - if n == 1 || count == 0 { - return; - } - let tab = match n { - 16 => SHELL_16[(count - 1) as usize], - 8 => SHELL_8[(count - 1) as usize], - 4 => SHELL_4[(count - 1) as usize], - _ => SHELL_2[(count - 1) as usize], - }; - let (a, b) = v.split_at(n / 2); - let left: i32 = a.iter().sum(); - enc.icdf(left as usize, tab, 8); - shell(enc, a, left); - shell(enc, b, count - left); -} - -/// Codes the frame's pulses (`len` a multiple of 16). -pub fn encode(enc: &mut RangeEncoder, pulses: &[i32], signal_type: usize, quant_offset_type: usize) { - let nblk = pulses.len() / 16; - let mut nls = vec![0usize; nblk]; - let mut sums = vec![0i32; nblk]; - let mut hi = vec![0i32; pulses.len()]; - for b in 0..nblk { - let blk = &pulses[b * 16..(b + 1) * 16]; - let mut s = 0usize; - loop { - let sum: i32 = blk.iter().map(|p| p.abs() >> s).sum(); - if sum <= 16 || s == 10 { - sums[b] = sum.min(16); - break; - } - s += 1; - } - nls[b] = s; - for (h, p) in hi[b * 16..(b + 1) * 16].iter_mut().zip(blk) { - *h = p.abs() >> s; - } - } - // Rate level with the cheapest pulse-count symbols. - let rl_tab = RATE_LEVEL[signal_type >> 1]; - let mut best = (f32::MAX, 0usize); - for rl in 0..9 { - let mut bits = icdf_bits(rl_tab, rl); - for b in 0..nblk { - bits += if nls[b] == 0 { icdf_bits(PULSE_COUNT[rl], sums[b] as usize) } else { icdf_bits(PULSE_COUNT[rl], 17) }; - } - if bits < best.0 { - best = (bits, rl); - } - } - let rl = best.1; - enc.icdf(rl, rl_tab, 8); - for b in 0..nblk { - if nls[b] == 0 { - enc.icdf(sums[b] as usize, PULSE_COUNT[rl], 8); - } else { - enc.icdf(17, PULSE_COUNT[rl], 8); - for j in 1..nls[b] { - enc.icdf(17, count_table(j), 8); - } - enc.icdf(sums[b] as usize, count_table(nls[b]), 8); - } - } - for b in 0..nblk { - if sums[b] > 0 { - shell(enc, &hi[b * 16..(b + 1) * 16], sums[b]); - } - } - for b in 0..nblk { - if nls[b] > 0 { - for p in &pulses[b * 16..(b + 1) * 16] { - let a = p.abs(); - for j in (0..nls[b]).rev() { - enc.icdf(((a >> j) & 1) as usize, &EXC_LSB, 8); - } - } - } - } - let base = 7 * (quant_offset_type + (signal_type << 1)); - for b in 0..nblk { - let p = sums[b] | ((nls[b] as i32) << 5); - if p > 0 { - let tab = EXC_SIGN[base + ((p & 0x1F) as usize).min(6)]; - for &q in &pulses[b * 16..(b + 1) * 16] { - if q != 0 { - enc.icdf((q > 0) as usize, tab, 8); - } - } - } - } -} diff --git a/crates/opusenc/src/silk/tables.rs b/crates/opusenc/src/silk/tables.rs deleted file mode 100644 index 8b4727268..000000000 --- a/crates/opusenc/src/silk/tables.rs +++ /dev/null @@ -1,540 +0,0 @@ -//! SILK probability tables and codebooks, transcribed from RFC 6716 §4.2 (Tables 4–53). -//! -//! PDFs are written as in the RFC (`{...}/256`) and converted at compile time to the inverse-CDF -//! form consumed by the range coder. -//! -//! Copied from FilmCraft's first-party, spec-derived `filmcraft-opus` decoder (MIT OR -//! Apache-2.0) so encoder and decoder share exactly the same values. - -/// Converts a PDF (summing to 256) into an inverse CDF (`256 - cdf[i+1]`). -pub const fn icdf(pdf: &[u8; N]) -> [u8; N] { - let mut out = [0u8; N]; - let mut acc: u32 = 0; - let mut i = 0; - while i < N { - acc += pdf[i] as u32; - out[i] = (256 - acc) as u8; - i += 1; - } - out -} - -pub const STEREO_PRED_JOINT: [u8; 25] = icdf(&[7, 2, 1, 1, 1, 10, 24, 8, 1, 1, 3, 23, 92, 23, 3, 1, 1, 8, 24, 10, 1, 1, 1, 2, 7]); -pub const UNIFORM3: [u8; 3] = icdf(&[85, 86, 85]); -pub const UNIFORM5: [u8; 5] = icdf(&[51, 51, 52, 51, 51]); -pub const STEREO_WEIGHTS_Q13: [i32; 16] = [-13732, -10050, -8266, -7526, -6500, -5000, -2950, -820, 820, 2950, 5000, 6500, 7526, 8266, 10050, 13732]; -pub const MID_ONLY: [u8; 2] = icdf(&[192, 64]); -pub const TYPE_INACTIVE: [u8; 2] = icdf(&[26, 230]); -pub const TYPE_ACTIVE: [u8; 4] = icdf(&[24, 74, 148, 10]); -pub const GAIN_MSB: [&[u8]; 3] = - [&icdf::<8>(&[32, 112, 68, 29, 12, 1, 1, 1]), &icdf::<8>(&[2, 17, 45, 60, 62, 47, 19, 4]), &icdf::<8>(&[1, 3, 26, 71, 94, 50, 9, 2])]; -pub const UNIFORM8: [u8; 8] = icdf(&[32, 32, 32, 32, 32, 32, 32, 32]); -pub const DELTA_GAIN: [u8; 41] = - icdf(&[6, 5, 11, 31, 132, 21, 8, 4, 3, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]); -pub const NLSF_STAGE1: [&[u8]; 4] = [ - &icdf::<32>(&[44, 34, 30, 19, 21, 12, 11, 3, 3, 2, 16, 2, 2, 1, 5, 2, 1, 3, 3, 1, 1, 2, 2, 2, 3, 1, 9, 9, 2, 7, 2, 1]), - &icdf::<32>(&[1, 10, 1, 8, 3, 8, 8, 14, 13, 14, 1, 14, 12, 13, 11, 11, 12, 11, 10, 10, 11, 8, 9, 8, 7, 8, 1, 1, 6, 1, 6, 5]), - &icdf::<32>(&[31, 21, 3, 17, 1, 8, 17, 4, 1, 18, 16, 4, 2, 3, 1, 10, 1, 3, 16, 11, 16, 2, 2, 3, 2, 11, 1, 4, 9, 8, 7, 3]), - &icdf::<32>(&[1, 4, 16, 5, 18, 11, 5, 14, 15, 1, 3, 12, 13, 14, 14, 6, 14, 12, 2, 6, 1, 12, 12, 11, 10, 3, 10, 5, 1, 1, 1, 3]), -]; -pub const NLSF_STAGE2: [&[u8]; 16] = [ - &icdf::<9>(&[1, 1, 1, 15, 224, 11, 1, 1, 1]), - &icdf::<9>(&[1, 1, 2, 34, 183, 32, 1, 1, 1]), - &icdf::<9>(&[1, 1, 4, 42, 149, 55, 2, 1, 1]), - &icdf::<9>(&[1, 1, 8, 52, 123, 61, 8, 1, 1]), - &icdf::<9>(&[1, 3, 16, 53, 101, 74, 6, 1, 1]), - &icdf::<9>(&[1, 3, 17, 55, 90, 73, 15, 1, 1]), - &icdf::<9>(&[1, 7, 24, 53, 74, 67, 26, 3, 1]), - &icdf::<9>(&[1, 1, 18, 63, 78, 58, 30, 6, 1]), - &icdf::<9>(&[1, 1, 1, 9, 232, 9, 1, 1, 1]), - &icdf::<9>(&[1, 1, 2, 28, 186, 35, 1, 1, 1]), - &icdf::<9>(&[1, 1, 3, 42, 152, 53, 2, 1, 1]), - &icdf::<9>(&[1, 1, 10, 49, 126, 65, 2, 1, 1]), - &icdf::<9>(&[1, 4, 19, 48, 100, 77, 5, 1, 1]), - &icdf::<9>(&[1, 1, 14, 54, 100, 72, 12, 1, 1]), - &icdf::<9>(&[1, 1, 15, 61, 87, 61, 25, 4, 1]), - &icdf::<9>(&[1, 7, 21, 50, 77, 81, 17, 1, 1]), -]; -pub const NLSF_SEL_NBMB: [[u8; 10]; 32] = [ - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 3, 1, 2, 2, 1, 2, 1, 1, 1], - [2, 1, 1, 1, 1, 1, 1, 1, 1, 1], - [1, 2, 2, 2, 2, 1, 2, 1, 1, 1], - [2, 3, 3, 3, 3, 2, 2, 2, 2, 2], - [0, 5, 3, 3, 2, 2, 2, 2, 1, 1], - [0, 2, 2, 2, 2, 2, 2, 2, 2, 1], - [2, 3, 6, 4, 4, 4, 5, 4, 5, 5], - [2, 4, 5, 5, 4, 5, 4, 6, 4, 4], - [2, 4, 4, 7, 4, 5, 4, 5, 5, 4], - [4, 3, 3, 3, 2, 3, 2, 2, 2, 2], - [1, 5, 5, 6, 4, 5, 4, 5, 5, 5], - [2, 7, 4, 6, 5, 5, 5, 5, 5, 5], - [2, 7, 5, 5, 5, 5, 5, 6, 5, 4], - [3, 3, 5, 4, 4, 5, 4, 5, 4, 4], - [2, 3, 3, 5, 5, 4, 4, 4, 4, 4], - [2, 4, 4, 6, 4, 5, 4, 5, 5, 5], - [2, 5, 4, 6, 5, 5, 5, 4, 5, 4], - [2, 7, 4, 5, 4, 5, 4, 5, 5, 5], - [2, 5, 4, 6, 7, 6, 5, 6, 5, 4], - [3, 6, 7, 4, 6, 5, 5, 6, 4, 5], - [2, 7, 6, 4, 4, 4, 5, 4, 5, 5], - [4, 5, 5, 4, 6, 6, 5, 6, 5, 4], - [2, 5, 5, 6, 5, 6, 4, 6, 4, 4], - [4, 5, 5, 5, 3, 7, 4, 5, 5, 4], - [2, 3, 4, 5, 5, 6, 4, 5, 5, 4], - [2, 3, 2, 3, 3, 4, 2, 3, 3, 3], - [1, 1, 2, 2, 2, 2, 2, 3, 2, 2], - [4, 5, 5, 6, 6, 6, 5, 6, 4, 5], - [3, 5, 5, 4, 4, 4, 4, 3, 3, 2], - [2, 5, 3, 7, 5, 5, 4, 4, 5, 4], - [4, 4, 5, 4, 5, 6, 5, 6, 5, 4], -]; -pub const NLSF_SEL_WB: [[u8; 16]; 32] = [ - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [2, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 1, 1, 1, 0, 3], - [2, 5, 5, 3, 7, 4, 4, 5, 2, 5, 4, 5, 5, 4, 3, 3], - [0, 2, 1, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1], - [0, 6, 5, 4, 6, 4, 7, 5, 4, 4, 4, 5, 5, 4, 4, 3], - [0, 3, 5, 5, 4, 3, 3, 5, 3, 3, 3, 3, 3, 3, 2, 4], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 2, 6, 3, 7, 2, 5, 3, 4, 5, 5, 4, 3, 3, 2, 3], - [0, 6, 2, 6, 6, 4, 5, 4, 6, 5, 4, 4, 5, 3, 3, 3], - [2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [2, 2, 3, 4, 5, 3, 3, 3, 3, 3, 3, 3, 2, 2, 1, 3], - [2, 2, 3, 3, 4, 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 3], - [3, 4, 4, 4, 6, 4, 4, 5, 3, 5, 4, 4, 5, 4, 3, 4], - [0, 6, 4, 5, 4, 7, 5, 2, 6, 5, 7, 4, 4, 3, 5, 3], - [0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0], - [1, 6, 5, 7, 5, 4, 5, 3, 4, 5, 4, 4, 4, 3, 3, 4], - [1, 3, 3, 4, 4, 3, 3, 5, 2, 3, 3, 5, 5, 5, 3, 4], - [2, 3, 3, 2, 2, 2, 3, 2, 1, 2, 1, 2, 1, 1, 1, 4], - [0, 2, 3, 5, 3, 3, 2, 2, 2, 1, 1, 0, 0, 0, 0, 0], - [3, 4, 3, 5, 3, 3, 2, 2, 1, 1, 1, 1, 1, 2, 2, 4], - [2, 6, 3, 7, 7, 4, 5, 4, 5, 3, 5, 3, 3, 2, 3, 3], - [2, 3, 5, 6, 6, 3, 5, 3, 4, 4, 3, 3, 3, 3, 2, 4], - [1, 3, 3, 4, 4, 4, 4, 3, 5, 5, 5, 3, 1, 1, 1, 1], - [2, 5, 3, 6, 6, 4, 7, 4, 4, 5, 3, 4, 4, 3, 3, 3], - [0, 6, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 6, 6, 3, 5, 2, 5, 5, 3, 4, 4, 7, 7, 4, 4, 4], - [3, 3, 7, 3, 5, 4, 3, 3, 3, 2, 2, 3, 3, 3, 2, 3], - [0, 0, 1, 0, 0, 0, 2, 1, 2, 1, 1, 2, 2, 2, 1, 1], - [0, 3, 2, 5, 3, 3, 2, 3, 2, 1, 0, 0, 1, 0, 0, 1], - [3, 5, 5, 4, 7, 5, 3, 3, 2, 3, 2, 2, 1, 0, 1, 0], - [2, 3, 5, 3, 4, 3, 3, 3, 2, 1, 2, 6, 4, 0, 0, 0], -]; -pub const NLSF_EXT: [u8; 7] = icdf(&[156, 60, 24, 9, 4, 2, 1]); -pub const NLSF_PRED_NBMB: [[i32; 9]; 2] = [[179, 138, 140, 148, 151, 149, 153, 151, 163], [116, 67, 82, 59, 92, 72, 100, 89, 92]]; -pub const NLSF_PRED_WB: [[i32; 15]; 2] = - [[175, 148, 160, 176, 178, 173, 174, 164, 177, 174, 196, 182, 198, 192, 182], [68, 62, 66, 60, 72, 117, 85, 90, 118, 136, 151, 142, 160, 142, 155]]; -pub const NLSF_PSEL_NBMB: [[u8; 9]; 32] = [ - [0, 1, 0, 0, 0, 0, 0, 0, 0], - [1, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 1, 1, 0, 0, 0, 0, 1, 0], - [0, 1, 0, 0, 0, 0, 0, 0, 0], - [0, 1, 0, 0, 0, 0, 0, 0, 0], - [1, 0, 1, 1, 0, 0, 0, 1, 0], - [0, 1, 1, 0, 0, 1, 1, 0, 0], - [0, 0, 1, 1, 0, 1, 0, 1, 1], - [0, 0, 1, 1, 0, 0, 1, 1, 1], - [0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 1, 0, 1, 1, 1, 1, 1, 0], - [0, 1, 0, 1, 1, 1, 1, 1, 0], - [0, 1, 1, 1, 1, 1, 1, 1, 0], - [1, 0, 1, 1, 0, 1, 1, 1, 1], - [0, 1, 1, 1, 1, 1, 0, 1, 0], - [0, 0, 1, 1, 0, 1, 0, 1, 0], - [0, 0, 1, 1, 1, 0, 1, 1, 1], - [0, 1, 1, 0, 0, 1, 1, 1, 0], - [0, 0, 0, 1, 1, 1, 0, 1, 0], - [0, 1, 1, 0, 0, 1, 0, 1, 0], - [0, 1, 1, 0, 0, 0, 1, 1, 0], - [0, 0, 0, 0, 0, 1, 1, 1, 1], - [0, 0, 1, 1, 0, 0, 0, 1, 1], - [0, 0, 0, 1, 0, 1, 1, 1, 1], - [0, 1, 1, 1, 1, 1, 1, 1, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 1, 0, 1, 1, 0, 1, 0], - [1, 0, 0, 1, 0, 0, 0, 0, 0], - [0, 0, 0, 1, 1, 0, 1, 0, 1], - [1, 0, 1, 1, 0, 1, 1, 1, 1], -]; -pub const NLSF_PSEL_WB: [[u8; 15]; 32] = [ - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], - [0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0], - [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], - [0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1], - [0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0], - [0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0], - [0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0], - [0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1], - [0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0], - [0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0], - [0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], - [0, 1, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0], - [0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0], - [0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0], - [0, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1], - [0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], - [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0], - [0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0], -]; -pub const NLSF_CB_NBMB: [[i32; 10]; 32] = [ - [12, 35, 60, 83, 108, 132, 157, 180, 206, 228], - [15, 32, 55, 77, 101, 125, 151, 175, 201, 225], - [19, 42, 66, 89, 114, 137, 162, 184, 209, 230], - [12, 25, 50, 72, 97, 120, 147, 172, 200, 223], - [26, 44, 69, 90, 114, 135, 159, 180, 205, 225], - [13, 22, 53, 80, 106, 130, 156, 180, 205, 228], - [15, 25, 44, 64, 90, 115, 142, 168, 196, 222], - [19, 24, 62, 82, 100, 120, 145, 168, 190, 214], - [22, 31, 50, 79, 103, 120, 151, 170, 203, 227], - [21, 29, 45, 65, 106, 124, 150, 171, 196, 224], - [30, 49, 75, 97, 121, 142, 165, 186, 209, 229], - [19, 25, 52, 70, 93, 116, 143, 166, 192, 219], - [26, 34, 62, 75, 97, 118, 145, 167, 194, 217], - [25, 33, 56, 70, 91, 113, 143, 165, 196, 223], - [21, 34, 51, 72, 97, 117, 145, 171, 196, 222], - [20, 29, 50, 67, 90, 117, 144, 168, 197, 221], - [22, 31, 48, 66, 95, 117, 146, 168, 196, 222], - [24, 33, 51, 77, 116, 134, 158, 180, 200, 224], - [21, 28, 70, 87, 106, 124, 149, 170, 194, 217], - [26, 33, 53, 64, 83, 117, 152, 173, 204, 225], - [27, 34, 65, 95, 108, 129, 155, 174, 210, 225], - [20, 26, 72, 99, 113, 131, 154, 176, 200, 219], - [34, 43, 61, 78, 93, 114, 155, 177, 205, 229], - [23, 29, 54, 97, 124, 138, 163, 179, 209, 229], - [30, 38, 56, 89, 118, 129, 158, 178, 200, 231], - [21, 29, 49, 63, 85, 111, 142, 163, 193, 222], - [27, 48, 77, 103, 133, 158, 179, 196, 215, 232], - [29, 47, 74, 99, 124, 151, 176, 198, 220, 237], - [33, 42, 61, 76, 93, 121, 155, 174, 207, 225], - [29, 53, 87, 112, 136, 154, 170, 188, 208, 227], - [24, 30, 52, 84, 131, 150, 166, 186, 203, 229], - [37, 48, 64, 84, 104, 118, 156, 177, 201, 230], -]; -pub const NLSF_CB_WB: [[i32; 16]; 32] = [ - [7, 23, 38, 54, 69, 85, 100, 116, 131, 147, 162, 178, 193, 208, 223, 239], - [13, 25, 41, 55, 69, 83, 98, 112, 127, 142, 157, 171, 187, 203, 220, 236], - [15, 21, 34, 51, 61, 78, 92, 106, 126, 136, 152, 167, 185, 205, 225, 240], - [10, 21, 36, 50, 63, 79, 95, 110, 126, 141, 157, 173, 189, 205, 221, 237], - [17, 20, 37, 51, 59, 78, 89, 107, 123, 134, 150, 164, 184, 205, 224, 240], - [10, 15, 32, 51, 67, 81, 96, 112, 129, 142, 158, 173, 189, 204, 220, 236], - [8, 21, 37, 51, 65, 79, 98, 113, 126, 138, 155, 168, 179, 192, 209, 218], - [12, 15, 34, 55, 63, 78, 87, 108, 118, 131, 148, 167, 185, 203, 219, 236], - [16, 19, 32, 36, 56, 79, 91, 108, 118, 136, 154, 171, 186, 204, 220, 237], - [11, 28, 43, 58, 74, 89, 105, 120, 135, 150, 165, 180, 196, 211, 226, 241], - [6, 16, 33, 46, 60, 75, 92, 107, 123, 137, 156, 169, 185, 199, 214, 225], - [11, 19, 30, 44, 57, 74, 89, 105, 121, 135, 152, 169, 186, 202, 218, 234], - [12, 19, 29, 46, 57, 71, 88, 100, 120, 132, 148, 165, 182, 199, 216, 233], - [17, 23, 35, 46, 56, 77, 92, 106, 123, 134, 152, 167, 185, 204, 222, 237], - [14, 17, 45, 53, 63, 75, 89, 107, 115, 132, 151, 171, 188, 206, 221, 240], - [9, 16, 29, 40, 56, 71, 88, 103, 119, 137, 154, 171, 189, 205, 222, 237], - [16, 19, 36, 48, 57, 76, 87, 105, 118, 132, 150, 167, 185, 202, 218, 236], - [12, 17, 29, 54, 71, 81, 94, 104, 126, 136, 149, 164, 182, 201, 221, 237], - [15, 28, 47, 62, 79, 97, 115, 129, 142, 155, 168, 180, 194, 208, 223, 238], - [8, 14, 30, 45, 62, 78, 94, 111, 127, 143, 159, 175, 192, 207, 223, 239], - [17, 30, 49, 62, 79, 92, 107, 119, 132, 145, 160, 174, 190, 204, 220, 235], - [14, 19, 36, 45, 61, 76, 91, 108, 121, 138, 154, 172, 189, 205, 222, 238], - [12, 18, 31, 45, 60, 76, 91, 107, 123, 138, 154, 171, 187, 204, 221, 236], - [13, 17, 31, 43, 53, 70, 83, 103, 114, 131, 149, 167, 185, 203, 220, 237], - [17, 22, 35, 42, 58, 78, 93, 110, 125, 139, 155, 170, 188, 206, 224, 240], - [8, 15, 34, 50, 67, 83, 99, 115, 131, 146, 162, 178, 193, 209, 224, 239], - [13, 16, 41, 66, 73, 86, 95, 111, 128, 137, 150, 163, 183, 206, 225, 241], - [17, 25, 37, 52, 63, 75, 92, 102, 119, 132, 144, 160, 175, 191, 212, 231], - [19, 31, 49, 65, 83, 100, 117, 133, 147, 161, 174, 187, 200, 213, 227, 242], - [18, 31, 52, 68, 88, 103, 117, 126, 138, 149, 163, 177, 192, 207, 223, 239], - [16, 29, 47, 61, 76, 90, 106, 119, 133, 147, 161, 176, 193, 209, 224, 240], - [15, 21, 35, 50, 61, 73, 86, 97, 110, 119, 129, 141, 175, 198, 218, 237], -]; -pub const NLSF_MIN_SPACING_NBMB: [i32; 11] = [250, 3, 6, 3, 3, 3, 4, 3, 3, 3, 461]; -pub const NLSF_MIN_SPACING_WB: [i32; 17] = [100, 3, 40, 3, 3, 3, 5, 14, 14, 10, 11, 3, 8, 9, 7, 3, 347]; -pub const NLSF_INTERP: [u8; 5] = icdf(&[13, 22, 29, 11, 181]); -pub const LSF_ORDER_NBMB: [usize; 10] = [0, 9, 6, 3, 4, 5, 8, 1, 2, 7]; -pub const LSF_ORDER_WB: [usize; 16] = [0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1]; -pub const COS_Q12: [i32; 129] = [ - 4096, 4095, 4091, 4085, 4076, 4065, 4052, 4036, 4017, 3997, 3973, 3948, 3920, 3889, 3857, 3822, 3784, 3745, 3703, 3659, 3613, 3564, 3513, 3461, 3406, 3349, - 3290, 3229, 3166, 3102, 3035, 2967, 2896, 2824, 2751, 2676, 2599, 2520, 2440, 2359, 2276, 2191, 2106, 2019, 1931, 1842, 1751, 1660, 1568, 1474, 1380, 1285, - 1189, 1093, 995, 897, 799, 700, 601, 501, 401, 301, 201, 101, 0, -101, -201, -301, -401, -501, -601, -700, -799, -897, -995, -1093, -1189, -1285, -1380, - -1474, -1568, -1660, -1751, -1842, -1931, -2019, -2106, -2191, -2276, -2359, -2440, -2520, -2599, -2676, -2751, -2824, -2896, -2967, -3035, -3102, -3166, - -3229, -3290, -3349, -3406, -3461, -3513, -3564, -3613, -3659, -3703, -3745, -3784, -3822, -3857, -3889, -3920, -3948, -3973, -3997, -4017, -4036, -4052, - -4065, -4076, -4085, -4091, -4095, -4096, -]; -pub const PITCH_HIGH: [u8; 32] = icdf(&[3, 3, 6, 11, 21, 30, 32, 19, 11, 10, 12, 13, 13, 12, 11, 9, 8, 7, 6, 4, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1]); -pub const PITCH_LOW: [&[u8]; 3] = [&icdf::<4>(&[64, 64, 64, 64]), &icdf::<6>(&[43, 42, 43, 43, 42, 43]), &icdf::<8>(&[32, 32, 32, 32, 32, 32, 32, 32])]; -pub const PITCH_DELTA: [u8; 21] = icdf(&[46, 2, 2, 3, 4, 6, 10, 15, 26, 38, 30, 22, 15, 10, 7, 6, 4, 4, 2, 2, 2]); -pub const PITCH_CONTOUR: [&[u8]; 4] = [ - &icdf::<3>(&[143, 50, 63]), - &icdf::<11>(&[68, 12, 21, 17, 19, 22, 30, 24, 17, 16, 10]), - &icdf::<12>(&[91, 46, 39, 19, 14, 12, 8, 7, 6, 5, 5, 4]), - &icdf::<34>(&[33, 22, 18, 16, 15, 14, 14, 13, 13, 10, 9, 9, 8, 6, 6, 6, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1]), -]; -pub const CB_NB_10: [[i32; 2]; 3] = [[0, 0], [1, 0], [0, 1]]; -pub const CB_NB_20: [[i32; 4]; 11] = [ - [0, 0, 0, 0], - [2, 1, 0, -1], - [-1, 0, 1, 2], - [-1, 0, 0, 1], - [-1, 0, 0, 0], - [0, 0, 0, 1], - [0, 0, 1, 1], - [1, 1, 0, 0], - [1, 0, 0, 0], - [0, 0, 0, -1], - [1, 0, 0, -1], -]; -pub const CB_WB_10: [[i32; 2]; 12] = [[0, 0], [0, 1], [1, 0], [-1, 1], [1, -1], [-1, 2], [2, -1], [-2, 2], [2, -2], [-2, 3], [3, -2], [-3, 3]]; -pub const CB_WB_20: [[i32; 4]; 34] = [ - [0, 0, 0, 0], - [0, 0, 1, 1], - [1, 1, 0, 0], - [-1, 0, 0, 0], - [0, 0, 0, 1], - [1, 0, 0, 0], - [-1, 0, 0, 1], - [0, 0, 0, -1], - [-1, 0, 1, 2], - [1, 0, 0, -1], - [-2, -1, 1, 2], - [2, 1, 0, -1], - [-2, 0, 0, 2], - [-2, 0, 1, 3], - [2, 1, -1, -2], - [-3, -1, 1, 3], - [2, 0, 0, -2], - [3, 1, 0, -2], - [-3, -1, 2, 4], - [-4, -1, 1, 4], - [3, 1, -1, -3], - [-4, -1, 2, 5], - [4, 2, -1, -3], - [4, 1, -1, -4], - [-5, -1, 2, 6], - [5, 2, -1, -4], - [-6, -2, 2, 6], - [-5, -2, 2, 5], - [6, 2, -1, -5], - [-7, -2, 3, 8], - [6, 2, -2, -6], - [5, 2, -2, -5], - [8, 3, -2, -7], - [-9, -3, 3, 9], -]; -pub const LTP_PERIODICITY: [u8; 3] = icdf(&[77, 80, 99]); -pub const LTP_FILTER: [&[u8]; 3] = [ - &icdf::<8>(&[185, 15, 13, 13, 9, 9, 6, 6]), - &icdf::<16>(&[57, 34, 21, 20, 15, 13, 12, 13, 10, 10, 9, 10, 9, 8, 7, 8]), - &icdf::<32>(&[15, 16, 14, 12, 12, 12, 11, 11, 11, 10, 9, 9, 9, 9, 8, 8, 8, 8, 7, 7, 6, 6, 5, 4, 5, 4, 4, 4, 3, 4, 3, 2]), -]; -pub const LTP_TAPS_0: [[i32; 5]; 8] = [ - [4, 6, 24, 7, 5], - [0, 0, 2, 0, 0], - [12, 28, 41, 13, -4], - [-9, 15, 42, 25, 14], - [1, -2, 62, 41, -9], - [-10, 37, 65, -4, 3], - [-6, 4, 66, 7, -8], - [16, 14, 38, -3, 33], -]; -pub const LTP_TAPS_1: [[i32; 5]; 16] = [ - [13, 22, 39, 23, 12], - [-1, 36, 64, 27, -6], - [-7, 10, 55, 43, 17], - [1, 1, 8, 1, 1], - [6, -11, 74, 53, -9], - [-12, 55, 76, -12, 8], - [-3, 3, 93, 27, -4], - [26, 39, 59, 3, -8], - [2, 0, 77, 11, 9], - [-8, 22, 44, -6, 7], - [40, 9, 26, 3, 9], - [-7, 20, 101, -7, 4], - [3, -8, 42, 26, 0], - [-15, 33, 68, 2, 23], - [-2, 55, 46, -2, 15], - [3, -1, 21, 16, 41], -]; -pub const LTP_TAPS_2: [[i32; 5]; 32] = [ - [-6, 27, 61, 39, 5], - [-11, 42, 88, 4, 1], - [-2, 60, 65, 6, -4], - [-1, -5, 73, 56, 1], - [-9, 19, 94, 29, -9], - [0, 12, 99, 6, 4], - [8, -19, 102, 46, -13], - [3, 2, 13, 3, 2], - [9, -21, 84, 72, -18], - [-11, 46, 104, -22, 8], - [18, 38, 48, 23, 0], - [-16, 70, 83, -21, 11], - [5, -11, 117, 22, -8], - [-6, 23, 117, -12, 3], - [3, -8, 95, 28, 4], - [-10, 15, 77, 60, -15], - [-1, 4, 124, 2, -4], - [3, 38, 84, 24, -25], - [2, 13, 42, 13, 31], - [21, -4, 56, 46, -1], - [-1, 35, 79, -13, 19], - [-7, 65, 88, -9, -14], - [20, 4, 81, 49, -29], - [20, 0, 75, 3, -17], - [5, -9, 44, 92, -8], - [1, -3, 22, 69, 31], - [-6, 95, 41, -12, 5], - [39, 67, 16, -4, 1], - [0, -6, 120, 55, -36], - [-13, 44, 122, 4, -24], - [81, 5, 11, 3, 7], - [2, 0, 9, 10, 88], -]; -pub const LTP_SCALE: [u8; 3] = icdf(&[128, 64, 64]); -pub const UNIFORM4: [u8; 4] = icdf(&[64, 64, 64, 64]); -pub const RATE_LEVEL: [&[u8]; 2] = [&icdf::<9>(&[15, 51, 12, 46, 45, 13, 33, 27, 14]), &icdf::<9>(&[33, 30, 36, 17, 34, 49, 18, 21, 18])]; -pub const PULSE_COUNT: [&[u8]; 11] = [ - &icdf::<18>(&[131, 74, 25, 8, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), - &icdf::<18>(&[58, 93, 60, 23, 7, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), - &icdf::<18>(&[43, 51, 46, 33, 24, 16, 11, 8, 6, 3, 3, 3, 2, 1, 1, 2, 1, 2]), - &icdf::<18>(&[17, 52, 71, 57, 31, 12, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]), - &icdf::<18>(&[6, 21, 41, 53, 49, 35, 21, 11, 6, 3, 2, 2, 1, 1, 1, 1, 1, 1]), - &icdf::<18>(&[7, 14, 22, 28, 29, 28, 25, 20, 17, 13, 11, 9, 7, 5, 4, 4, 3, 10]), - &icdf::<18>(&[2, 5, 14, 29, 42, 46, 41, 31, 19, 11, 6, 3, 2, 1, 1, 1, 1, 1]), - &icdf::<18>(&[1, 2, 4, 10, 19, 29, 35, 37, 34, 28, 20, 14, 8, 5, 4, 2, 2, 2]), - &icdf::<18>(&[1, 2, 2, 5, 9, 14, 20, 24, 27, 28, 26, 23, 20, 15, 11, 8, 6, 15]), - &icdf::<18>(&[1, 1, 1, 6, 27, 58, 56, 39, 25, 14, 10, 6, 3, 3, 2, 1, 1, 2]), - &icdf::<18>(&[2, 1, 6, 27, 58, 56, 39, 25, 14, 10, 6, 3, 3, 2, 1, 1, 2, 0]), -]; -pub const SHELL_16: [&[u8]; 16] = [ - &icdf::<2>(&[126, 130]), - &icdf::<3>(&[56, 142, 58]), - &icdf::<4>(&[25, 101, 104, 26]), - &icdf::<5>(&[12, 60, 108, 64, 12]), - &icdf::<6>(&[7, 35, 84, 87, 37, 6]), - &icdf::<7>(&[4, 20, 59, 86, 63, 21, 3]), - &icdf::<8>(&[3, 12, 38, 72, 75, 42, 12, 2]), - &icdf::<9>(&[2, 8, 25, 54, 73, 59, 27, 7, 1]), - &icdf::<10>(&[2, 5, 17, 39, 63, 65, 42, 18, 4, 1]), - &icdf::<11>(&[1, 4, 12, 28, 49, 63, 54, 30, 11, 3, 1]), - &icdf::<12>(&[1, 4, 8, 20, 37, 55, 57, 41, 22, 8, 2, 1]), - &icdf::<13>(&[1, 3, 7, 15, 28, 44, 53, 48, 33, 16, 6, 1, 1]), - &icdf::<14>(&[1, 2, 6, 12, 21, 35, 47, 48, 40, 25, 12, 5, 1, 1]), - &icdf::<15>(&[1, 1, 4, 10, 17, 27, 37, 47, 43, 33, 21, 9, 4, 1, 1]), - &icdf::<16>(&[1, 1, 1, 8, 14, 22, 33, 40, 43, 38, 28, 16, 8, 1, 1, 1]), - &icdf::<17>(&[1, 1, 1, 1, 13, 18, 27, 36, 41, 41, 34, 24, 14, 1, 1, 1, 1]), -]; -pub const SHELL_8: [&[u8]; 16] = [ - &icdf::<2>(&[127, 129]), - &icdf::<3>(&[53, 149, 54]), - &icdf::<4>(&[22, 105, 106, 23]), - &icdf::<5>(&[11, 61, 111, 63, 10]), - &icdf::<6>(&[6, 35, 86, 88, 36, 5]), - &icdf::<7>(&[4, 20, 59, 87, 62, 21, 3]), - &icdf::<8>(&[3, 13, 40, 71, 73, 41, 13, 2]), - &icdf::<9>(&[3, 9, 27, 53, 70, 56, 28, 9, 1]), - &icdf::<10>(&[3, 8, 19, 37, 57, 61, 44, 20, 6, 1]), - &icdf::<11>(&[3, 7, 15, 28, 44, 54, 49, 33, 17, 5, 1]), - &icdf::<12>(&[1, 7, 13, 22, 34, 46, 48, 38, 28, 14, 4, 1]), - &icdf::<13>(&[1, 1, 11, 22, 27, 35, 42, 47, 33, 25, 10, 1, 1]), - &icdf::<14>(&[1, 1, 6, 14, 26, 37, 43, 43, 37, 26, 14, 6, 1, 1]), - &icdf::<15>(&[1, 1, 4, 10, 20, 31, 40, 42, 40, 31, 20, 10, 4, 1, 1]), - &icdf::<16>(&[1, 1, 3, 8, 16, 26, 35, 38, 38, 35, 26, 16, 8, 3, 1, 1]), - &icdf::<17>(&[1, 1, 2, 6, 12, 21, 30, 36, 38, 36, 30, 21, 12, 6, 2, 1, 1]), -]; -pub const SHELL_4: [&[u8]; 16] = [ - &icdf::<2>(&[127, 129]), - &icdf::<3>(&[49, 157, 50]), - &icdf::<4>(&[20, 107, 109, 20]), - &icdf::<5>(&[11, 60, 113, 62, 10]), - &icdf::<6>(&[7, 36, 84, 87, 36, 6]), - &icdf::<7>(&[6, 24, 57, 82, 60, 23, 4]), - &icdf::<8>(&[5, 18, 39, 64, 68, 42, 16, 4]), - &icdf::<9>(&[6, 14, 29, 47, 61, 52, 30, 14, 3]), - &icdf::<10>(&[1, 15, 23, 35, 51, 50, 40, 30, 10, 1]), - &icdf::<11>(&[1, 1, 21, 32, 42, 52, 46, 41, 18, 1, 1]), - &icdf::<12>(&[1, 6, 16, 27, 36, 42, 42, 36, 27, 16, 6, 1]), - &icdf::<13>(&[1, 5, 12, 21, 31, 38, 40, 38, 31, 21, 12, 5, 1]), - &icdf::<14>(&[1, 3, 9, 17, 26, 34, 38, 38, 34, 26, 17, 9, 3, 1]), - &icdf::<15>(&[1, 3, 7, 14, 22, 29, 34, 36, 34, 29, 22, 14, 7, 3, 1]), - &icdf::<16>(&[1, 2, 5, 11, 18, 25, 31, 35, 35, 31, 25, 18, 11, 5, 2, 1]), - &icdf::<17>(&[1, 1, 4, 9, 15, 21, 28, 32, 34, 32, 28, 21, 15, 9, 4, 1, 1]), -]; -pub const SHELL_2: [&[u8]; 16] = [ - &icdf::<2>(&[128, 128]), - &icdf::<3>(&[42, 172, 42]), - &icdf::<4>(&[21, 107, 107, 21]), - &icdf::<5>(&[12, 60, 112, 61, 11]), - &icdf::<6>(&[8, 34, 86, 86, 35, 7]), - &icdf::<7>(&[8, 23, 55, 90, 55, 20, 5]), - &icdf::<8>(&[5, 15, 38, 72, 72, 36, 15, 3]), - &icdf::<9>(&[6, 12, 27, 52, 77, 47, 20, 10, 5]), - &icdf::<10>(&[6, 19, 28, 35, 40, 40, 35, 28, 19, 6]), - &icdf::<11>(&[4, 14, 22, 31, 37, 40, 37, 31, 22, 14, 4]), - &icdf::<12>(&[3, 10, 18, 26, 33, 38, 38, 33, 26, 18, 10, 3]), - &icdf::<13>(&[2, 8, 13, 21, 29, 36, 38, 36, 29, 21, 13, 8, 2]), - &icdf::<14>(&[1, 5, 10, 17, 25, 32, 38, 38, 32, 25, 17, 10, 5, 1]), - &icdf::<15>(&[1, 4, 7, 13, 21, 29, 35, 36, 35, 29, 21, 13, 7, 4, 1]), - &icdf::<16>(&[1, 2, 5, 10, 17, 25, 32, 36, 36, 32, 25, 17, 10, 5, 2, 1]), - &icdf::<17>(&[1, 2, 4, 7, 13, 21, 28, 34, 36, 34, 28, 21, 13, 7, 4, 2, 1]), -]; -pub const EXC_LSB: [u8; 2] = icdf(&[136, 120]); -pub const EXC_SIGN: [&[u8]; 42] = [ - &icdf::<2>(&[2, 254]), - &icdf::<2>(&[207, 49]), - &icdf::<2>(&[189, 67]), - &icdf::<2>(&[179, 77]), - &icdf::<2>(&[174, 82]), - &icdf::<2>(&[163, 93]), - &icdf::<2>(&[157, 99]), - &icdf::<2>(&[58, 198]), - &icdf::<2>(&[245, 11]), - &icdf::<2>(&[238, 18]), - &icdf::<2>(&[232, 24]), - &icdf::<2>(&[225, 31]), - &icdf::<2>(&[220, 36]), - &icdf::<2>(&[211, 45]), - &icdf::<2>(&[1, 255]), - &icdf::<2>(&[210, 46]), - &icdf::<2>(&[190, 66]), - &icdf::<2>(&[178, 78]), - &icdf::<2>(&[169, 87]), - &icdf::<2>(&[162, 94]), - &icdf::<2>(&[152, 104]), - &icdf::<2>(&[48, 208]), - &icdf::<2>(&[242, 14]), - &icdf::<2>(&[235, 21]), - &icdf::<2>(&[224, 32]), - &icdf::<2>(&[214, 42]), - &icdf::<2>(&[205, 51]), - &icdf::<2>(&[190, 66]), - &icdf::<2>(&[1, 255]), - &icdf::<2>(&[162, 94]), - &icdf::<2>(&[152, 104]), - &icdf::<2>(&[147, 109]), - &icdf::<2>(&[144, 112]), - &icdf::<2>(&[141, 115]), - &icdf::<2>(&[138, 118]), - &icdf::<2>(&[8, 248]), - &icdf::<2>(&[203, 53]), - &icdf::<2>(&[187, 69]), - &icdf::<2>(&[176, 80]), - &icdf::<2>(&[168, 88]), - &icdf::<2>(&[161, 95]), - &icdf::<2>(&[154, 102]), -]; -pub const LBRR_FLAGS: [&[u8]; 2] = [&icdf::<3>(&[53, 53, 150]), &icdf::<7>(&[41, 20, 29, 41, 15, 28, 82])]; diff --git a/crates/opusenc/src/tables.rs b/crates/opusenc/src/tables.rs deleted file mode 100644 index 00d623af0..000000000 --- a/crates/opusenc/src/tables.rs +++ /dev/null @@ -1,122 +0,0 @@ -//! Constant tables of the 48 kHz CELT mode (RFC 6716 §4.3, Tables 55–58 and §4.3.2). -//! -//! Transcribed from RFC 6716; copied from FilmCraft's spec-derived `filmcraft-opus` decoder -//! (first-party, MIT OR Apache-2.0) so both sides share the exact same values. - -/// Number of energy bands. -pub const NB_EBANDS: usize = 21; -/// Band edges in units of 2.5 ms MDCT bins (Table 55). -pub const EBANDS: [i32; NB_EBANDS + 1] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 34, 40, 48, 60, 78, 100]; -/// Overlap of the low-overlap window (samples at 48 kHz). -pub const OVERLAP: usize = 120; -/// Largest LM (20 ms frames). -pub const MAX_LM: usize = 3; -/// Pre-emphasis coefficient. -pub const PREEMPH: f32 = 0.850_006_1; - -/// Static allocation table (Table 57), indexed `[quality][band]`, in 1/32 bit per MDCT bin. -pub const ALLOC: [[u8; NB_EBANDS]; 11] = transpose([ - [0, 90, 110, 118, 126, 134, 144, 152, 162, 172, 200], - [0, 80, 100, 110, 119, 127, 137, 145, 155, 165, 200], - [0, 75, 90, 103, 112, 120, 130, 138, 148, 158, 200], - [0, 69, 84, 93, 104, 114, 124, 132, 142, 152, 200], - [0, 63, 78, 86, 95, 103, 113, 123, 133, 143, 200], - [0, 56, 71, 80, 89, 97, 107, 117, 127, 137, 200], - [0, 49, 65, 75, 83, 91, 101, 111, 121, 131, 200], - [0, 40, 58, 70, 78, 85, 95, 105, 115, 125, 200], - [0, 34, 51, 65, 72, 78, 88, 98, 108, 118, 198], - [0, 29, 45, 59, 66, 72, 82, 92, 102, 112, 193], - [0, 20, 39, 53, 60, 66, 76, 86, 96, 106, 188], - [0, 18, 32, 47, 54, 60, 70, 80, 90, 100, 183], - [0, 10, 26, 40, 47, 54, 64, 74, 84, 94, 178], - [0, 0, 20, 31, 39, 47, 57, 67, 77, 87, 173], - [0, 0, 12, 23, 32, 41, 51, 61, 71, 81, 168], - [0, 0, 0, 15, 25, 35, 45, 55, 65, 75, 163], - [0, 0, 0, 4, 17, 29, 39, 49, 59, 69, 158], - [0, 0, 0, 0, 12, 23, 33, 43, 53, 63, 153], - [0, 0, 0, 0, 1, 16, 26, 36, 46, 56, 148], - [0, 0, 0, 0, 0, 10, 15, 20, 30, 45, 129], - [0, 0, 0, 0, 0, 1, 1, 1, 1, 20, 104], -]); - -const fn transpose(t: [[u8; 11]; NB_EBANDS]) -> [[u8; NB_EBANDS]; 11] { - let mut out = [[0u8; NB_EBANDS]; 11]; - let mut b = 0; - while b < NB_EBANDS { - let mut q = 0; - while q < 11 { - out[q][b] = t[b][q]; - q += 1; - } - b += 1; - } - out -} - -/// Mean band energy (log2 domain) removed before coarse quantisation. -pub const E_MEANS: [f32; 25] = [ - 6.4375, 6.25, 5.75, 5.3125, 5.0625, 4.8125, 4.5, 4.375, 4.875, 4.6875, 4.5625, 4.4375, 4.875, 4.625, 4.3125, 4.5, 4.375, 4.625, 4.75, 4.4375, 3.75, 3.75, - 3.75, 3.75, 3.75, -]; - -/// Inter-frame prediction coefficient (alpha) per LM, Q15. -pub const PRED_COEF: [f32; 4] = [29440.0 / 32768.0, 26112.0 / 32768.0, 21248.0 / 32768.0, 16384.0 / 32768.0]; -/// Inter-band prediction coefficient (beta) per LM for inter frames, Q15. -pub const BETA_COEF: [f32; 4] = [30147.0 / 32768.0, 22282.0 / 32768.0, 12124.0 / 32768.0, 6554.0 / 32768.0]; -/// Beta for intra frames. -pub const BETA_INTRA: f32 = 4915.0 / 32768.0; - -/// Laplace model parameters for coarse energy: `[LM][intra][2*band + {0: prob, 1: decay}]`. -pub const E_PROB_MODEL: [[[u8; 42]; 2]; 4] = [ - [ - [ - 72, 127, 65, 129, 66, 128, 65, 128, 64, 128, 62, 128, 64, 128, 64, 128, 92, 78, 92, 79, 92, 78, 90, 79, 116, 41, 115, 40, 114, 40, 132, 26, 132, - 26, 145, 17, 161, 12, 176, 10, 177, 11, - ], - [ - 24, 179, 48, 138, 54, 135, 54, 132, 53, 134, 56, 133, 55, 132, 55, 132, 61, 114, 70, 96, 74, 88, 75, 88, 87, 74, 89, 66, 91, 67, 100, 59, 108, 50, - 120, 40, 122, 37, 97, 43, 78, 50, - ], - ], - [ - [ - 83, 78, 84, 81, 88, 75, 86, 74, 87, 71, 90, 73, 93, 74, 93, 74, 109, 40, 114, 36, 117, 34, 117, 34, 143, 17, 145, 18, 146, 19, 162, 12, 165, 10, - 178, 7, 189, 6, 190, 8, 177, 9, - ], - [ - 23, 178, 54, 115, 63, 102, 66, 98, 69, 99, 74, 89, 71, 91, 73, 91, 78, 89, 86, 80, 92, 66, 93, 64, 102, 59, 103, 60, 104, 60, 117, 52, 123, 44, - 138, 35, 133, 31, 97, 38, 77, 45, - ], - ], - [ - [ - 61, 90, 93, 60, 105, 42, 107, 41, 110, 45, 116, 38, 113, 38, 112, 38, 124, 26, 132, 27, 136, 19, 140, 20, 155, 14, 159, 16, 158, 18, 170, 13, 177, - 10, 187, 8, 192, 6, 175, 9, 159, 10, - ], - [ - 21, 178, 59, 110, 71, 86, 75, 85, 84, 83, 91, 66, 88, 73, 87, 72, 92, 75, 98, 72, 105, 58, 107, 54, 115, 52, 114, 55, 112, 56, 129, 51, 132, 40, - 150, 33, 140, 29, 98, 35, 77, 42, - ], - ], - [ - [ - 42, 121, 96, 66, 108, 43, 111, 40, 117, 44, 123, 32, 120, 36, 119, 33, 127, 33, 134, 34, 139, 21, 147, 23, 152, 20, 158, 25, 154, 26, 166, 21, 173, - 16, 184, 13, 184, 10, 150, 13, 139, 15, - ], - [ - 22, 178, 63, 114, 74, 82, 84, 83, 92, 82, 103, 62, 96, 72, 96, 67, 101, 73, 107, 72, 113, 55, 118, 52, 125, 52, 118, 52, 117, 55, 135, 49, 137, 39, - 157, 32, 145, 29, 97, 33, 77, 40, - ], - ], -]; - -/// Inverse CDF for coarse energy when only a few bits remain. -pub const SMALL_ENERGY_ICDF: [u8; 3] = [2, 1, 0]; -/// Conservative log2 in 1/8 bits of the number of coded bands (intensity reservation). -pub const LOG2_FRAC_TABLE: [i32; 24] = [0, 8, 13, 16, 19, 21, 23, 24, 26, 27, 28, 29, 30, 31, 32, 32, 33, 34, 34, 35, 36, 36, 37, 37]; -/// TF resolution changes: `[LM][4*transient + 2*tf_select + tf_flag]`. -pub const TF_SELECT_TABLE: [[i8; 8]; 4] = [[0, -1, 0, -1, 0, -1, 0, -1], [0, -1, 0, -2, 1, 0, 1, -1], [0, -2, 0, -3, 2, 0, 1, -1], [0, -2, 0, -3, 3, 0, 1, -1]]; -/// Spreading decision `{7, 2, 21, 2}/32`. -pub const SPREAD_ICDF: [u8; 4] = [25, 23, 2, 0]; -/// Allocation trim (Table 58). -pub const TRIM_ICDF: [u8; 11] = [126, 124, 119, 109, 87, 41, 19, 9, 4, 2, 0]; diff --git a/crates/opusenc/tests/it/common/mod.rs b/crates/opusenc/tests/it/common/mod.rs deleted file mode 100644 index 8f00b88e9..000000000 --- a/crates/opusenc/tests/it/common/mod.rs +++ /dev/null @@ -1,285 +0,0 @@ -//! Shared helpers for the SILK/hybrid round-trip tests: synthetic signals, encoding, decoding -//! with FilmCraft's spec-derived decoder, delay-searched SNR and an Ogg Opus writer for ffmpeg. -#![allow(dead_code)] - -use effectcraft_opusenc::OpusEncoder; - -pub const SR: f64 = 48_000.0; -pub const FRAME: usize = OpusEncoder::FRAME_SIZE; - -/// Two-pole resonator state. -struct Reson { - y1: f64, - y2: f64, -} - -impl Reson { - fn run(&mut self, x: f64, f: f64, bw: f64) -> f64 { - let r = (-std::f64::consts::PI * bw / SR).exp(); - let a1 = 2.0 * r * (2.0 * std::f64::consts::PI * f / SR).cos(); - let a2 = -r * r; - let g = 1.0 - r; - let y = g * x + a1 * self.y1 + a2 * self.y2; - self.y2 = self.y1; - self.y1 = y; - y - } -} - -/// Speech-like test signal: a glottal pulse train (100–200 Hz, gliding pitch) through three -/// formant resonators whose frequencies change per syllable, with syllable envelopes, short -/// pauses and a little aspiration noise. -pub fn speech(len: usize, seed: u32) -> Vec { - let vowels: [[f64; 3]; 5] = [[730.0, 1090.0, 2440.0], [270.0, 2290.0, 3010.0], [530.0, 1840.0, 2480.0], [570.0, 840.0, 2410.0], [300.0, 870.0, 2240.0]]; - let syl = (0.24 * SR) as usize; - let mut out = Vec::with_capacity(len); - let mut res = [Reson { y1: 0.0, y2: 0.0 }, Reson { y1: 0.0, y2: 0.0 }, Reson { y1: 0.0, y2: 0.0 }]; - let mut phase = 0.0f64; - let mut s = seed; - let mut prev_glottal = 0.0; - for n in 0..len { - let t = n as f64 / SR; - let k = n / syl; - let pos = (n % syl) as f64 / syl as f64; - // Every fourth syllable is a pause. - let pause = k % 4 == 3; - let env = if pause { 0.0 } else { (std::f64::consts::PI * pos).sin().powf(0.7) }; - let f0 = 100.0 + 50.0 * (1.0 + (2.0 * std::f64::consts::PI * 0.9 * t).sin()) + 15.0 * ((k * 7) % 5) as f64 - 30.0 * pos; - phase += f0 / SR; - if phase >= 1.0 { - phase -= 1.0; - } - // Rosenberg-like glottal flow; its derivative excites the vocal tract. - let g = if phase < 0.4 { - 0.5 * (1.0 - (std::f64::consts::PI * phase / 0.4).cos()) - } else if phase < 0.56 { - (std::f64::consts::FRAC_PI_2 * (phase - 0.4) / 0.16).cos() - } else { - 0.0 - }; - let dg = (g - prev_glottal) * 40.0; - prev_glottal = g; - s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - let noise = ((s >> 8) as f64 / (1u32 << 24) as f64 - 0.5) * 0.02; - let v = vowels[(k * 3 + 1) % 5]; - let w = vowels[(k * 3 + 4) % 5]; - let mix = pos; - let mut x = dg + noise; - let mut y = 0.0; - for (i, r) in res.iter_mut().enumerate() { - let f = v[i] * (1.0 - mix) + w[i] * mix; - y += r.run(x, f, 60.0 + 40.0 * i as f64) * [1.0, 0.6, 0.3][i]; - } - x = y * env * 1.2; - out.push(x as f32); - } - let peak = out.iter().fold(0f32, |m, v| m.max(v.abs())); - let g = 0.5 / peak.max(1e-9); - out.iter().map(|v| v * g).collect() -} - -/// Music-like test signal: three-note chords of harmonic tones (six partials each), changing -/// every half second with soft attacks and releases. -pub fn music(len: usize) -> Vec { - let chords: [[f64; 3]; 4] = [[261.63, 329.63, 392.0], [220.0, 277.18, 329.63], [174.61, 220.0, 261.63], [196.0, 246.94, 293.66]]; - let seg = (0.5 * SR) as usize; - (0..len) - .map(|n| { - let t = n as f64 / SR; - let k = n / seg; - let pos = (n % seg) as f64 / seg as f64; - let env = (pos * 20.0).min(1.0) * ((1.0 - pos) * 10.0).min(1.0); - let mut x = 0.0; - for (j, &f) in chords[k % 4].iter().enumerate() { - for h in 1..=6 { - x += (2.0 * std::f64::consts::PI * f * h as f64 * t + j as f64).sin() / h as f64; - } - } - (0.12 * env * x) as f32 - }) - .collect() -} - -pub fn interleave(planar: &[Vec]) -> Vec { - let c = planar.len(); - let len = planar[0].len(); - let mut pcm = vec![0f32; len * c]; - for (ch, p) in planar.iter().enumerate() { - for (i, &v) in p.iter().enumerate() { - pcm[i * c + ch] = v; - } - } - pcm -} - -/// Encodes planar input (padding the tail so the encoder delay is flushed). -pub fn encode(mut enc: OpusEncoder, planar: &[Vec]) -> (OpusEncoder, Vec>) { - let c = planar.len(); - let len = planar[0].len(); - let total = len + enc.pre_skip() as usize + 16; - let frames = total.div_ceil(FRAME); - let mut pcm = interleave(planar); - pcm.resize(frames * FRAME * c, 0.0); - let packets = pcm.chunks(FRAME * c).map(|f| enc.encode_float(f)).collect(); - (enc, packets) -} - -/// Decodes with craft-audio, drops the pre-skip and returns planar channels (full length). -pub fn decode(head: &[u8], packets: &[Vec]) -> Vec> { - let mut dec = craft_audio::opus::Decoder::new(head).expect("OpusHead"); - dec.set_trim_pre_skip(true); - let mut out: Vec> = vec![Vec::new(); dec.channels()]; - for p in packets { - let planes = dec.decode(Some(p)).expect("decode"); - for (o, p) in out.iter_mut().zip(planes) { - o.extend_from_slice(&p); - } - } - out -} - -/// Waveform SNR (dB) of `dec[i + shift]` against `orig[i]`, excluding the first and last 20 ms. -pub fn snr_at(orig: &[f32], dec: &[f32], shift: isize) -> f64 { - let (mut s, mut e) = (0f64, 0f64); - for i in FRAME..orig.len() - FRAME { - let j = i as isize + shift; - let d = if j >= 0 && (j as usize) < dec.len() { dec[j as usize] as f64 } else { 0.0 }; - s += (orig[i] as f64).powi(2); - e += (orig[i] as f64 - d).powi(2); - } - 10.0 * (s / e.max(1e-30)).log10() -} - -/// Best SNR over residual delays of ±`range` samples: (SNR dB, delay). -pub fn snr_search(orig: &[f32], dec: &[f32], range: isize) -> (f64, isize) { - (-range..=range).map(|d| (snr_at(orig, dec, d), d)).fold((f64::MIN, 0), |a, b| if b.0 > a.0 { b } else { a }) -} - -/// Segmental SNR (dB): mean over 20 ms segments holding signal (each clamped to [-10, 40]). -pub fn seg_snr(orig: &[f32], dec: &[f32], shift: isize) -> f64 { - let mut acc = 0f64; - let mut n = 0; - let mut i = FRAME; - while i + FRAME <= orig.len() - FRAME { - let (mut s, mut e) = (0f64, 0f64); - for k in i..i + FRAME { - let j = k as isize + shift; - let d = if j >= 0 && (j as usize) < dec.len() { dec[j as usize] as f64 } else { 0.0 }; - s += (orig[k] as f64).powi(2); - e += (orig[k] as f64 - d).powi(2); - } - if s / FRAME as f64 > 1e-5 { - acc += (10.0 * (s / e.max(1e-30)).log10()).clamp(-10.0, 40.0); - n += 1; - } - i += FRAME; - } - acc / n.max(1) as f64 -} - -/// Average bitrate (bits per second) of a packet sequence of 20 ms packets. -pub fn bitrate(packets: &[Vec]) -> f64 { - packets.iter().map(|p| p.len() * 8).sum::() as f64 / (packets.len() as f64 * 0.02) -} - -/// Low-pass filtered copy (FFT brick wall) used to compare band-limited modes fairly. -pub fn lowpass(x: &[f32], fc: f64) -> Vec { - let n = x.len().next_power_of_two(); - let mut re: Vec = x.iter().map(|&v| v as f64).collect(); - re.resize(n, 0.0); - let mut im = vec![0f64; n]; - fft(&mut re, &mut im, false); - for k in 0..n { - let f = (k.min(n - k)) as f64 * SR / n as f64; - if f > fc { - re[k] = 0.0; - im[k] = 0.0; - } - } - fft(&mut re, &mut im, true); - re[..x.len()].iter().map(|&v| (v / n as f64) as f32).collect() -} - -pub fn fft(re: &mut [f64], im: &mut [f64], inverse: bool) { - let n = re.len(); - let mut j = 0; - for i in 1..n { - let mut bit = n >> 1; - while j & bit != 0 { - j ^= bit; - bit >>= 1; - } - j |= bit; - if i < j { - re.swap(i, j); - im.swap(i, j); - } - } - let mut len = 2; - while len <= n { - let ang = if inverse { 2.0 } else { -2.0 } * std::f64::consts::PI / len as f64; - for s in (0..n).step_by(len) { - for k in 0..len / 2 { - let (wr, wi) = ((ang * k as f64).cos(), (ang * k as f64).sin()); - let (a, b) = (s + k, s + k + len / 2); - let tr = re[b] * wr - im[b] * wi; - let ti = re[b] * wi + im[b] * wr; - re[b] = re[a] - tr; - im[b] = im[a] - ti; - re[a] += tr; - im[a] += ti; - } - } - len <<= 1; - } -} - -// ---- Ogg Opus (RFC 3533 + RFC 7845) for the ffmpeg oracle ---- - -fn ogg_crc(data: &[u8]) -> u32 { - let mut crc = 0u32; - for &b in data { - crc ^= (b as u32) << 24; - for _ in 0..8 { - crc = if crc & 0x8000_0000 != 0 { (crc << 1) ^ 0x04C1_1DB7 } else { crc << 1 }; - } - } - crc -} - -fn ogg_page(out: &mut Vec, packet: &[u8], header_type: u8, granule: u64, seq: u32) { - let mut lacing = vec![255u8; packet.len() / 255]; - lacing.push((packet.len() % 255) as u8); - let start = out.len(); - out.extend_from_slice(b"OggS"); - out.push(0); - out.push(header_type); - out.extend_from_slice(&granule.to_le_bytes()); - out.extend_from_slice(&0x4543_4F50u32.to_le_bytes()); - out.extend_from_slice(&seq.to_le_bytes()); - out.extend_from_slice(&0u32.to_le_bytes()); - out.push(lacing.len() as u8); - out.extend_from_slice(&lacing); - out.extend_from_slice(packet); - let crc = ogg_crc(&out[start..]); - out[start + 22..start + 26].copy_from_slice(&crc.to_le_bytes()); -} - -/// An Ogg Opus file holding `packets` for `len` samples of audio. -pub fn ogg_opus(enc: &OpusEncoder, packets: &[Vec], len: usize) -> Vec { - let mut out = Vec::new(); - ogg_page(&mut out, &enc.opus_head(), 0x02, 0, 0); - let vendor = b"effectcraft-opusenc"; - let mut tags = b"OpusTags".to_vec(); - tags.extend_from_slice(&(vendor.len() as u32).to_le_bytes()); - tags.extend_from_slice(vendor); - tags.extend_from_slice(&0u32.to_le_bytes()); - ogg_page(&mut out, &tags, 0, 0, 1); - let pre_skip = enc.pre_skip() as u64; - for (i, p) in packets.iter().enumerate() { - let last = i + 1 == packets.len(); - let granule = if last { pre_skip + len as u64 } else { ((i + 1) * FRAME) as u64 }; - ogg_page(&mut out, p, if last { 0x04 } else { 0 }, granule, i as u32 + 2); - } - out -} diff --git a/crates/opusenc/tests/it/ffmpeg.rs b/crates/opusenc/tests/it/ffmpeg.rs deleted file mode 100644 index 1294ed348..000000000 --- a/crates/opusenc/tests/it/ffmpeg.rs +++ /dev/null @@ -1,81 +0,0 @@ -//! ffmpeg as a second, external oracle: every mode/bandwidth written as Ogg Opus must decode -//! without errors with both ffmpeg's native `opus` decoder and `libopus`, honour the pre-skip -//! and end granule, and reproduce the input. Skipped when ffmpeg is not installed. - -use crate::common; - -use std::process::Command; - -use common::*; -use effectcraft_opusenc::{Bandwidth, Mode, OpusEncoder}; - -const FFMPEG: &str = "/opt/homebrew/bin/ffmpeg"; - -fn ffmpeg() -> Option<&'static str> { - [FFMPEG, "ffmpeg"].into_iter().find(|exe| Command::new(exe).arg("-version").output().is_ok_and(|o| o.status.success())) -} - -/// Decodes an Ogg Opus file with ffmpeg's decoder `codec`; returns interleaved f32 output. -fn ffmpeg_decode(exe: &str, codec: &str, file: &[u8], channels: usize, tag: &str) -> Option> { - let has = Command::new(exe).args(["-hide_banner", "-decoders"]).output().ok()?; - if !String::from_utf8_lossy(&has.stdout).lines().any(|l| l.split_whitespace().nth(1) == Some(codec)) { - eprintln!("ffmpeg has no {codec} decoder; skipping it"); - return None; - } - let path = std::env::temp_dir().join(format!("effectcraft-opusenc-{}-{tag}.opus", std::process::id())); - std::fs::write(&path, file).unwrap(); - let out = Command::new(exe) - .args(["-v", "error", "-c:a", codec, "-i"]) - .arg(&path) - .args(["-f", "f32le", "-ac", &channels.to_string(), "-ar", "48000", "-"]) - .output() - .expect("run ffmpeg"); - let _ = std::fs::remove_file(&path); - let stderr = String::from_utf8_lossy(&out.stderr); - assert!(out.status.success(), "ffmpeg ({codec}) failed: {stderr}"); - // ffmpeg's native decoder also makes its raw-PCM muxer print a timestamp complaint for - // narrowband SILK streams written by libopus itself; that line is about ffmpeg's own - // timestamping, not the bitstream, so it is the one message tolerated. - let errors: Vec<&str> = stderr.lines().filter(|l| !l.trim().is_empty() && !l.contains("non monotonically increasing dts to muxer")).collect(); - assert!(errors.is_empty(), "ffmpeg ({codec}) reported errors: {errors:?}"); - Some(out.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect()) -} - -#[test] -fn ffmpeg_decodes_every_mode() { - let Some(exe) = ffmpeg() else { - eprintln!("ffmpeg not installed; skipping the oracle test"); - return; - }; - let len = 48_000; - let sp = speech(len + 30_000, 3); - let left = sp[..len].to_vec(); - let right: Vec = sp[30_000..].iter().map(|v| v * 0.7).collect(); - let cases = [ - (1usize, Mode::Silk, Bandwidth::Narrowband, 8_000u32, 3_400.0, 8.0), - (1, Mode::Silk, Bandwidth::Mediumband, 11_000, 5_000.0, 10.0), - (1, Mode::Silk, Bandwidth::Wideband, 16_000, 7_000.0, 12.0), - (2, Mode::Silk, Bandwidth::Wideband, 32_000, 7_000.0, 12.0), - (1, Mode::Hybrid, Bandwidth::SuperWideband, 24_000, 24_000.0, 10.0), - (1, Mode::Hybrid, Bandwidth::Fullband, 32_000, 24_000.0, 10.0), - (2, Mode::Hybrid, Bandwidth::Fullband, 64_000, 24_000.0, 10.0), - (2, Mode::Celt, Bandwidth::Fullband, 96_000, 24_000.0, 10.0), - ]; - for (c, mode, bw, rate, fc, min_snr) in cases { - let planar: Vec> = if c == 1 { vec![left.clone()] } else { vec![left.clone(), right.clone()] }; - let (enc, packets) = encode(OpusEncoder::with_mode(c as u8, rate, mode, bw), &planar); - let file = ogg_opus(&enc, &packets, len); - for codec in ["opus", "libopus"] { - let Some(dec) = ffmpeg_decode(exe, codec, &file, c, &format!("{mode:?}{bw:?}{c}{codec}")) else { - continue; - }; - assert_eq!(dec.len(), len * c, "{codec}: pre-skip and end granule must be honoured"); - for (ch, x) in planar.iter().enumerate() { - let d: Vec = (0..len).map(|i| dec[i * c + ch]).collect(); - let (snr, delay) = snr_search(&lowpass(x, fc), &d, 6); - eprintln!("ffmpeg {codec:7} {mode:?}/{bw:?} {c} ch @ {} kb/s, channel {ch}: SNR {snr:.1} dB (residual delay {delay})", rate / 1000); - assert!(snr > min_snr, "{codec} {mode:?}/{bw:?}: SNR {snr:.1} dB"); - } - } - } -} diff --git a/crates/opusenc/tests/it/main.rs b/crates/opusenc/tests/it/main.rs deleted file mode 100644 index ba6a7895d..000000000 --- a/crates/opusenc/tests/it/main.rs +++ /dev/null @@ -1,5 +0,0 @@ -//! The crate's integration tests, one binary (each module is a former `tests/.rs`). - -mod common; -mod ffmpeg; -mod modes; diff --git a/crates/opusenc/tests/it/modes.rs b/crates/opusenc/tests/it/modes.rs deleted file mode 100644 index c01f64e69..000000000 --- a/crates/opusenc/tests/it/modes.rs +++ /dev/null @@ -1,272 +0,0 @@ -//! SILK, hybrid and CELT round trips through FilmCraft's spec-derived Opus decoder: every -//! mode/bandwidth decodes, waveform quality on speech-like and music-like signals, bitrate -//! tracking, stereo, the application tables and delay alignment. - -use crate::common; - -use common::*; -use effectcraft_opusenc::{Application, Bandwidth, Mode, OpusEncoder}; - -struct Run { - snr: f64, - seg: f64, - delay: isize, - kbps: f64, - packets: Vec>, -} - -/// Encodes `planar`, decodes, and measures each channel against `reference` (searching a -/// residual delay of up to ±6 samples). -fn run(enc: OpusEncoder, planar: &[Vec], reference: &[Vec]) -> Vec { - let (enc, packets) = encode(enc, planar); - let dec = decode(&enc.opus_head(), &packets); - let kbps = bitrate(&packets) / 1000.0; - reference - .iter() - .zip(&dec) - .map(|(r, d)| { - assert!(d.len() >= r.len(), "decoded {} < {}", d.len(), r.len()); - assert!(d.iter().all(|v| v.is_finite())); - let (snr, delay) = snr_search(r, d, 6); - Run { snr, seg: seg_snr(r, d, delay), delay, kbps, packets: packets.clone() } - }) - .collect() -} - -fn mono(mode: Mode, bw: Bandwidth, rate: u32, x: &[f32], fc: f64) -> Run { - let reference = if fc < 20_000.0 { lowpass(x, fc) } else { x.to_vec() }; - run(OpusEncoder::with_mode(1, rate, mode, bw), &[x.to_vec()], &[reference]).remove(0) -} - -/// Upper edge of the band a SILK bandwidth keeps (for band-limited references). -fn band_edge(bw: Bandwidth) -> f64 { - match bw { - Bandwidth::Narrowband => 3_400.0, - Bandwidth::Mediumband => 5_000.0, - Bandwidth::Wideband => 7_000.0, - _ => 24_000.0, - } -} - -const LEN: usize = 96_000; - -#[test] -fn every_mode_and_bandwidth_decodes() { - let sp = speech(LEN + 40_000, 11); - let left = sp[..LEN].to_vec(); - let right: Vec = sp[40_000..].iter().map(|v| v * 0.6).collect(); - for (mode, bw, config, rate) in [ - (Mode::Silk, Bandwidth::Narrowband, 1u8, 8_000u32), - (Mode::Silk, Bandwidth::Mediumband, 5, 11_000), - (Mode::Silk, Bandwidth::Wideband, 9, 16_000), - (Mode::Hybrid, Bandwidth::SuperWideband, 13, 24_000), - (Mode::Hybrid, Bandwidth::Fullband, 15, 32_000), - (Mode::Celt, Bandwidth::Fullband, 31, 64_000), - ] { - for c in [1usize, 2] { - let planar = if c == 1 { vec![left.clone()] } else { vec![left.clone(), right.clone()] }; - let reference: Vec> = planar.iter().map(|x| lowpass(x, band_edge(bw))).collect(); - let enc = OpusEncoder::with_mode(c as u8, rate * c as u32, mode, bw); - assert_eq!((enc.mode(), enc.bandwidth()), (mode, bw)); - let res = run(enc, &planar, &reference); - for p in &res[0].packets { - assert_eq!(p[0], (config << 3) | if c == 2 { 4 } else { 0 }, "TOC of {mode:?}/{bw:?}"); - assert!(p.len() >= 3 && p.len() <= 1276); - } - for (ch, r) in res.iter().enumerate() { - eprintln!( - "{mode:?}/{bw:?} {c} ch @ {} kb/s: {:.1} kb/s, channel {ch} SNR {:.1} dB, segSNR {:.1} dB, residual delay {}", - rate * c as u32 / 1000, - r.kbps, - r.snr, - r.seg, - r.delay - ); - assert!(r.snr > 8.0, "{mode:?}/{bw:?} {c} ch channel {ch}: SNR {:.1} dB", r.snr); - assert!(r.delay.abs() <= 1, "{mode:?}/{bw:?}: residual delay {} (pre-skip mismatch)", r.delay); - } - } - } -} - -#[test] -fn silk_speech_quality() { - let x = speech(LEN, 7); - for (bw, rate, min_snr) in [ - (Bandwidth::Narrowband, 8_000u32, 10.0), - (Bandwidth::Mediumband, 11_000, 14.0), - (Bandwidth::Wideband, 12_000, 14.0), - (Bandwidth::Wideband, 16_000, 18.0), - (Bandwidth::Wideband, 24_000, 24.0), - ] { - let r = mono(Mode::Silk, bw, rate, &x, band_edge(bw)); - eprintln!("SILK {bw:?} speech @ {} kb/s: {:.1} kb/s, SNR {:.1} dB, segSNR {:.1} dB", rate / 1000, r.kbps, r.snr, r.seg); - assert!(r.snr > min_snr && r.seg > min_snr - 3.0, "SILK {bw:?} @ {rate}: SNR {:.1} / seg {:.1}", r.snr, r.seg); - } -} - -#[test] -fn silk_beats_celt_on_speech_at_low_rate() { - let x = speech(LEN, 5); - // Both measured against the full-band input. - let silk = mono(Mode::Silk, Bandwidth::Wideband, 12_000, &x, 24_000.0); - let celt = mono(Mode::Celt, Bandwidth::Fullband, 12_000, &x, 24_000.0); - eprintln!( - "12 kb/s mono speech: SILK WB {:.1} dB (seg {:.1}) at {:.1} kb/s vs CELT {:.1} dB (seg {:.1}) at {:.1} kb/s", - silk.snr, silk.seg, silk.kbps, celt.snr, celt.seg, celt.kbps - ); - assert!(silk.snr > celt.snr + 3.0, "SILK {:.1} dB vs CELT {:.1} dB", silk.snr, celt.snr); - assert!(silk.seg > celt.seg + 3.0, "SILK seg {:.1} dB vs CELT seg {:.1} dB", silk.seg, celt.seg); -} - -#[test] -fn hybrid_quality() { - let sp = speech(LEN, 9); - let mu = music(LEN); - for (name, x, bw, rate, min_snr) in [ - ("speech", &sp, Bandwidth::SuperWideband, 24_000u32, 18.0), - ("speech", &sp, Bandwidth::Fullband, 32_000, 20.0), - ("music", &mu, Bandwidth::SuperWideband, 24_000, 9.0), - ("music", &mu, Bandwidth::Fullband, 32_000, 10.0), - ] { - let r = mono(Mode::Hybrid, bw, rate, x, 24_000.0); - eprintln!("hybrid {bw:?} {name} @ {} kb/s: {:.1} kb/s, SNR {:.1} dB, segSNR {:.1} dB", rate / 1000, r.kbps, r.snr, r.seg); - assert!(r.snr > min_snr, "hybrid {bw:?} {name}: SNR {:.1} dB", r.snr); - // Constant packet size. - assert!(r.packets.iter().all(|p| p.len() == rate as usize / 400)); - } -} - -#[test] -fn silk_music_quality() { - let x = music(LEN); - for (rate, min_snr) in [(12_000u32, 5.0), (16_000, 8.0), (24_000, 13.0)] { - let r = mono(Mode::Silk, Bandwidth::Wideband, rate, &x, 7_000.0); - eprintln!("SILK WB music @ {} kb/s: {:.1} kb/s, SNR {:.1} dB", rate / 1000, r.kbps, r.snr); - assert!(r.snr > min_snr, "SILK music @ {rate}: SNR {:.1} dB", r.snr); - } -} - -#[test] -fn bitrate_tracking() { - let sp = speech(LEN, 13); - let mu = music(LEN); - for (name, x) in [("speech", &sp), ("music", &mu)] { - for (mode, bw, rate) in [ - (Mode::Silk, Bandwidth::Narrowband, 6_000u32), - (Mode::Silk, Bandwidth::Narrowband, 9_000), - (Mode::Silk, Bandwidth::Mediumband, 11_000), - (Mode::Silk, Bandwidth::Wideband, 12_000), - (Mode::Silk, Bandwidth::Wideband, 20_000), - (Mode::Silk, Bandwidth::Wideband, 32_000), - (Mode::Hybrid, Bandwidth::SuperWideband, 20_000), - (Mode::Hybrid, Bandwidth::Fullband, 36_000), - ] { - let r = mono(mode, bw, rate, x, band_edge(bw)); - let ratio = r.kbps * 1000.0 / rate as f64; - eprintln!("{name} {mode:?}/{bw:?} target {} kb/s: actual {:.2} kb/s ({:+.0} %), SNR {:.1} dB", rate / 1000, r.kbps, (ratio - 1.0) * 100.0, r.snr); - assert!((0.75..=1.25).contains(&ratio), "{name} {mode:?}/{bw:?} @ {rate}: {:.2} kb/s", r.kbps); - } - } -} - -#[test] -fn stereo_silk_and_hybrid() { - let sp = speech(LEN + 40_000, 21); - let a = sp[..LEN].to_vec(); - let b: Vec = sp[40_000..].iter().map(|v| v * 0.7).collect(); - let mu = music(LEN); - let cases: Vec<(&str, Vec, Vec)> = vec![ - ("dual mono", a.clone(), a.clone()), - ("panned", a.iter().map(|v| v * 0.9).collect(), a.iter().map(|v| v * 0.35).collect()), - ("independent", a.clone(), b), - ("speech+music", a.iter().zip(&mu).map(|(x, y)| 0.8 * x + 0.3 * y).collect(), a.iter().zip(&mu).map(|(x, y)| 0.3 * x + 0.8 * y).collect()), - ]; - for (name, l, r) in &cases { - for (mode, bw, rate, min_snr) in [(Mode::Silk, Bandwidth::Wideband, 32_000u32, 9.0), (Mode::Hybrid, Bandwidth::Fullband, 64_000, 9.0)] { - let fc = band_edge(bw); - let res = run(OpusEncoder::with_mode(2, rate, mode, bw), &[l.clone(), r.clone()], &[lowpass(l, fc), lowpass(r, fc)]); - eprintln!("stereo {name} {mode:?}/{bw:?} @ {} kb/s: {:.1} kb/s, L {:.1} dB, R {:.1} dB", rate / 1000, res[0].kbps, res[0].snr, res[1].snr); - assert!(res[0].snr > min_snr && res[1].snr > min_snr, "stereo {name} {mode:?}: L {:.1} R {:.1}", res[0].snr, res[1].snr); - } - } -} - -#[test] -fn application_tables_and_pre_skip() { - let cases = [ - (Application::Voip, 1u8, 8_000u32, Mode::Silk, Bandwidth::Narrowband), - (Application::Voip, 1, 11_000, Mode::Silk, Bandwidth::Mediumband), - (Application::Voip, 1, 16_000, Mode::Silk, Bandwidth::Wideband), - (Application::Voip, 1, 24_000, Mode::Hybrid, Bandwidth::SuperWideband), - (Application::Voip, 1, 32_000, Mode::Hybrid, Bandwidth::Fullband), - (Application::Voip, 1, 48_000, Mode::Celt, Bandwidth::Fullband), - (Application::Voip, 2, 32_000, Mode::Silk, Bandwidth::Wideband), - (Application::Audio, 1, 12_000, Mode::Silk, Bandwidth::Wideband), - (Application::Audio, 1, 24_000, Mode::Hybrid, Bandwidth::Fullband), - (Application::Audio, 2, 48_000, Mode::Hybrid, Bandwidth::Fullband), - (Application::Audio, 1, 64_000, Mode::Celt, Bandwidth::Fullband), - (Application::Audio, 2, 128_000, Mode::Celt, Bandwidth::Fullband), - ]; - for (app, c, rate, mode, bw) in cases { - let e = OpusEncoder::with_application(c, rate, app); - assert_eq!((e.mode(), e.bandwidth(), e.application()), (mode, bw, app), "{app:?} {c} ch @ {rate}"); - assert_eq!(e.pre_skip(), 120, "every mode is aligned to a 120-sample delay"); - } - assert_eq!(OpusEncoder::new(2, 128_000).mode(), Mode::Celt); - assert_eq!(OpusEncoder::new(1, 12_000).application(), Application::Audio); -} - -#[test] -#[should_panic(expected = "unsupported mode/bandwidth")] -fn invalid_mode_bandwidth_panics() { - let _ = OpusEncoder::with_mode(1, 16_000, Mode::Silk, Bandwidth::Fullband); -} - -#[test] -fn extreme_inputs_stay_decodable() { - let len = 24_000; - let mut s = 1u32; - let noise: Vec = (0..len) - .map(|_| { - s = s.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); - (s >> 8) as f32 / (1u32 << 23) as f32 - 1.0 - }) - .collect(); - let square: Vec = (0..len).map(|i| if (i / 60) % 2 == 0 { 0.999 } else { -0.999 }).collect(); - let clicks: Vec = (0..len).map(|i| if i % 4_801 == 0 { 1.0 } else { 0.0 }).collect(); - let dc = vec![0.7f32; len]; - let nan: Vec = (0..len).map(|i| if i % 1000 == 0 { f32::NAN } else { 0.1 * (i as f32 * 0.01).sin() }).collect(); - for (name, x) in [("noise", &noise), ("square", &square), ("clicks", &clicks), ("dc", &dc), ("nan", &nan)] { - for (mode, bw, rate) in - [(Mode::Silk, Bandwidth::Narrowband, 6_000u32), (Mode::Silk, Bandwidth::Wideband, 40_000), (Mode::Hybrid, Bandwidth::Fullband, 24_000)] - { - for c in [1usize, 2] { - let planar: Vec> = if c == 1 { vec![x.clone()] } else { vec![x.clone(), x.iter().map(|v| -0.5 * v).collect()] }; - let (enc, packets) = encode(OpusEncoder::with_mode(c as u8, rate * c as u32, mode, bw), &planar); - assert!(packets.iter().all(|p| p.len() >= 3 && p.len() <= 1276), "{name} {mode:?}: packet sizes"); - let dec = decode(&enc.opus_head(), &packets); - let peak = dec.iter().flatten().fold(0f32, |m, v| m.max(v.abs())); - let snr = if name == "nan" { f64::NAN } else { snr_search(&planar[0], &dec[0], 2).0 }; - eprintln!("{name} {mode:?}/{bw:?} {c} ch: peak {peak:.2}, SNR {snr:.1} dB, {:.1} kb/s", bitrate(&packets) / 1000.0); - assert!(dec.iter().all(|ch| ch.iter().all(|v| v.is_finite() && v.abs() <= 4.0)), "{name} {mode:?}/{bw:?} {c} ch: bad output"); - } - } - } -} - -#[test] -fn silk_and_hybrid_silence() { - for (mode, bw, rate) in [(Mode::Silk, Bandwidth::Wideband, 16_000u32), (Mode::Hybrid, Bandwidth::Fullband, 32_000)] { - let x = vec![0f32; 48_000]; - let (enc, packets) = encode(OpusEncoder::with_mode(1, rate, mode, bw), std::slice::from_ref(&x)); - let dec = decode(&enc.opus_head(), &packets); - let peak = dec[0].iter().fold(0f32, |m, v| m.max(v.abs())); - let kbps = bitrate(&packets) / 1000.0; - eprintln!("{mode:?} silence: {kbps:.2} kb/s, decoded peak {peak:.2e}"); - assert!(peak < 1e-3, "{mode:?} silence decodes to peak {peak}"); - if mode == Mode::Silk { - assert!(kbps < 4.0, "SILK silence costs {kbps:.2} kb/s"); - } - } -} diff --git a/crates/path/Cargo.toml b/crates/path/Cargo.toml index 2e9bc85d9..122c37fe0 100644 --- a/crates/path/Cargo.toml +++ b/crates/path/Cargo.toml @@ -14,5 +14,6 @@ effectcraft-geom = { workspace = true } effectcraft-keyframe = { workspace = true } effectcraft-raster = { workspace = true } kurbo = { workspace = true } +log = { workspace = true } tiny-skia = { workspace = true } linesweeper = "0.5" diff --git a/crates/path/src/ops.rs b/crates/path/src/ops.rs index ba5349312..5c89ce6bc 100644 --- a/crates/path/src/ops.rs +++ b/crates/path/src/ops.rs @@ -351,14 +351,28 @@ fn round_sub(sub: &Sub, r: f64, out: &mut BezPath) { /// join. `copies` copies are made, copy *i* (0-based) offset by `amount · (i + 1 + copy_offset)`, /// all returned in the same compound path. pub fn offset(paths: &[BezPath], amount: f64, join: Join, miter_limit: f64, copies: f64, copy_offset: f64) -> Vec { - let n = copies.round().clamp(1.0, 1000.0) as usize; + offset_within(paths, amount, join, miter_limit, copies, copy_offset, MAX_OPERATOR_SEGMENTS) +} + +/// [`offset`] with each path's result held to `max` elements (its first copy aside). +fn offset_within(paths: &[BezPath], amount: f64, join: Join, miter_limit: f64, copies: f64, copy_offset: f64, max: usize) -> Vec { + let n = pieces_within_budget(paths, copies.round().clamp(1.0, 1000.0) as usize); paths .iter() .map(|p| { let mut out = BezPath::new(); for i in 0..n { let d = amount * (i as f64 + 1.0 + copy_offset); - out.extend(crate::offset::offset_path(p, d, join, miter_limit).elements().iter().copied()); + let copy = crate::offset::offset_path(p, d, join, miter_limit); + // The budget is spent on what `offset_path` returns (an open subpath comes back as + // a closed outline of many segments; a zero offset as the path itself): the first + // copy is always kept, and a copy that would pass the budget is not made, so the + // work stays within a small multiple of it. + if i > 0 && out.elements().len().saturating_add(copy.elements().len()) > max { + log::warn!("path: Offset Paths made {i} of {n} copies; more would pass {max} segments"); + break; + } + out.extend(copy.elements().iter().copied()); } out }) @@ -387,6 +401,14 @@ pub fn twist(paths: &[BezPath], angle_deg: f64, center: [f64; 2]) -> Vec Vec usize { + if sub.closed { 2 } else { 1 } +} + +/// `want` pieces (or copies) per input segment, reduced so the whole output (segments times +/// pieces, plus per-subpath overhead) stays within [`MAX_OPERATOR_SEGMENTS`] (never below 1, so the input itself always passes through). +fn pieces_within_budget(paths: &[BezPath], want: usize) -> usize { + // Count what is subdivided (drawn segments) and keep room for each subpath's own MoveTo/Close. + let (mut segs, mut overhead) = (0usize, 0usize); + for sub in paths.iter().flat_map(subs) { + segs = segs.saturating_add(sub.segs.len()); + overhead = overhead.saturating_add(overhead_of(&sub)); + } + want.min(MAX_OPERATOR_SEGMENTS.saturating_sub(overhead) / segs.max(1)).max(1) +} + /// Split every segment into `m` pieces of equal arc length. Original vertices get the average of /// their incoming and outgoing tangents (so a corner's normal is its bisector). fn resample(sub: &Sub, m: usize) -> Vec { @@ -503,7 +547,7 @@ fn emit(samples: &[Sample], disp: &[Vec2], closed: bool, smooth: bool, handle: f /// `smooth` makes rounded waves instead of sharp zig zags. A closed path with `n` segments ends up /// with `n · (ridges + 1)` vertices (open: one more). pub fn zigzag(paths: &[BezPath], size: f64, ridges: f64, smooth: bool) -> Vec { - let m = ridges.round().clamp(0.0, 1000.0) as usize + 1; + let m = pieces_within_budget(paths, ridges.round().clamp(0.0, 1000.0) as usize + 1); paths .iter() .map(|p| { @@ -586,7 +630,7 @@ pub fn wiggle(paths: &[BezPath], w: &WiggleParams, time_s: f64) -> Vec if w.size == 0.0 { return paths.to_vec(); } - let m = w.detail.round().clamp(0.0, 1000.0) as usize + 1; + let m = pieces_within_budget(paths, w.detail.round().clamp(0.0, 1000.0) as usize + 1); let seed = w.seed.round() as i64 as u64; let t = time_s * w.speed + w.phase_deg / 360.0; let corr = (w.correlation / 100.0).clamp(0.0, 1.0); diff --git a/crates/path/src/ops/tests.rs b/crates/path/src/ops/tests.rs index 1ebdcea5b..e64a55b47 100644 --- a/crates/path/src/ops/tests.rs +++ b/crates/path/src/ops/tests.rs @@ -182,6 +182,25 @@ fn offset_copies() { assert!(close(o[0].bounding_box().width(), 140.0, 1e-3)); } +#[test] +fn offset_copies_are_budgeted_by_the_output_they_return() { + // An open one-segment subpath comes back as a closed outline of several elements, so the copies + // stop when the returned elements pass the budget, not when the input segments would. + let line = || { + let mut p = BezPath::new(); + p.move_to((0.0, 0.0)); + p.line_to((50.0, 0.0)); + p + }; + let one = offset_within(&[line()], 5.0, Join::Round, 4.0, 1.0, 0.0, usize::MAX)[0].elements().len(); + assert!(one > 4, "{one}"); + let o = offset_within(&[line()], 5.0, Join::Round, 4.0, 50.0, 0.0, one * 3); + let moves = o[0].elements().iter().filter(|e| matches!(e, PathEl::MoveTo(_))).count(); + assert!((1..50).contains(&moves) && o[0].elements().len() <= one * 4, "{moves} contours, {} elements", o[0].elements().len()); + // The first copy always comes back, however small the budget. + assert!(!offset_within(&[line()], 5.0, Join::Round, 4.0, 5.0, 0.0, 0)[0].elements().is_empty()); +} + #[test] fn offset_open_path_outlines() { let mut l = BezPath::new(); @@ -246,6 +265,22 @@ fn twist_of_centred_circle_keeps_it_round() { assert_eq!(id[0], sq(0.0, 0.0, 5.0)); } +#[test] +fn twist_keeps_requested_detail_when_the_whole_request_fits_the_budget() { + // One long segment asks for 64 pieces; 20,000 tiny ones ask for one each. Together that is + // far under the budget, so the long one is not cut to what a uniform 64 per segment would allow. + let mut long = BezPath::new(); + long.move_to((0.0, 0.0)); + long.line_to((5000.0, 0.0)); + let mut tiny = BezPath::new(); + tiny.move_to((0.0, 1.0)); + for i in 1..=20_000 { + tiny.line_to((i as f64 * 1e-3, 1.0)); + } + let t = twist(&[long, tiny], 90.0, [0.0, 0.0]); + assert_eq!(t[0].elements().len(), 1 + 64); +} + // ---------------------------------------------------------------- zig zag #[test] @@ -417,3 +452,48 @@ fn normalize_and_filled_area() { let n = crate::boolean::normalize(&p, FillRule::EvenOdd); assert!(close(n.area().abs(), 10000.0, 1e-6)); } + +// ---------------------------------------------------------------- operator budget + +#[test] +fn stacked_expanding_operators_stay_within_the_segment_budget() { + // Three Zig Zags at 1000 ridges would turn a square into 4 · 1001³ segments; each output + // is held to the budget instead, and the last operators still pass the geometry through. + let mut p = vec![sq(0.0, 0.0, 100.0)]; + for _ in 0..3 { + p = zigzag(&p, 1.0, 1000.0, false); + let n: usize = p.iter().map(|q| q.elements().len()).sum(); + assert!(n <= 2 * MAX_OPERATOR_SEGMENTS, "{n}"); + } + let w = wiggle(&p, &WiggleParams { detail: 1000.0, ..Default::default() }, 0.0); + let n: usize = w.iter().map(|q| q.elements().len()).sum(); + assert!(n <= 2 * MAX_OPERATOR_SEGMENTS, "{n}"); + let o = offset(&[sq(0.0, 0.0, 100.0)], 1.0, Join::Miter, 4.0, 1000.0, 0.0); + assert!(!o[0].elements().is_empty()); + // Within the budget nothing changes: 4 segments × 11 pieces. + assert_eq!(vertex_count(&zigzag(&[sq(0.0, 0.0, 100.0)], 1.0, 10.0, false)[0]), 44); +} + +#[test] +fn many_short_open_paths_keep_their_requested_detail_within_the_budget() { + // 1000 open lines at 1000 ridges: 1,001,000 segments fit the budget, so nothing is reduced. + let lines: Vec = (0..1000) + .map(|i| { + let mut p = BezPath::new(); + p.move_to((0.0, i as f64)); + p.line_to((100.0, i as f64)); + p + }) + .collect(); + let z = zigzag(&lines, 1.0, 1000.0, false); + assert!(z.iter().all(|q| q.elements().len() == 1 + 1001)); +} + +#[test] +fn open_subpaths_reserve_one_element_of_overhead() { + // 349,525 open lines: the move-to is the only extra element, so 2 copies fit the budget + // (a closed subpath's extra close-path would leave room for 1). + let line = BezPath::from_vec(vec![PathEl::MoveTo((0.0, 0.0).into()), PathEl::LineTo((1.0, 0.0).into())]); + let lines = vec![line; 349_525]; + assert_eq!(pieces_within_budget(&lines, 3), 2); +} diff --git a/crates/pdf/Cargo.toml b/crates/pdf/Cargo.toml index bf6148569..a5fc2146c 100644 --- a/crates/pdf/Cargo.toml +++ b/crates/pdf/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "effectcraft-pdf" -description = "Vector footage import: PDF and PDF-compatible Illustrator (.ai) pages and EPS (a PostScript subset) parsed into the SVG render tree (paths, fills, strokes, shadings, tiling patterns, clipping, text with embedded fonts, images, blend modes, soft masks, optional-content layers)" +description = "Vector footage import: PDF and PDF-compatible Illustrator (.ai) pages, EPS (a PostScript subset) and the PDF a VectorCraft (.vectorcraft) document carries, parsed into the SVG render tree (paths, fills, strokes, shadings, tiling patterns, clipping, text with embedded fonts, images, blend modes, soft masks, optional-content layers)" version.workspace = true edition.workspace = true license.workspace = true @@ -10,7 +10,10 @@ rust-version.workspace = true workspace = true [dependencies] +craft-ps = { workspace = true } craft-pdf.workspace = true +# The PDF a VectorCraft document carries (Create PDF-Compatible File). +craft-doc = { workspace = true } effectcraft-svg = { workspace = true } kurbo = { workspace = true } effectcraft-text = { workspace = true } @@ -24,6 +27,10 @@ zune-jpeg = "0.5" # Encodes JPEG fixtures for the DCT image test. image = { workspace = true } effectcraft-raster = { workspace = true } +# Writes the VectorCraft documents the tests read. +craft-vectorcraft-format = { workspace = true } +flate2 = { version = "1", default-features = false, features = ["rust_backend"] } +serde_json = { workspace = true } [target.'cfg(target_arch = "wasm32")'.dev-dependencies] wasm-bindgen-test = "0.3" diff --git a/crates/pdf/README.md b/crates/pdf/README.md index a88adff0b..ff37aa93c 100644 --- a/crates/pdf/README.md +++ b/crates/pdf/README.md @@ -114,6 +114,10 @@ ffmpeg elsewhere) to check the code tables against an independent implementation stitching and PostScript calculator (type 4) functions. - **Pages:** any page ([`parse_page`], [`page_count`]); File ▸ Import takes `page` (from 1) and the Import dialog asks for it; footage remembers its page (`Footage::page`). +- **VectorCraft documents** (`.vectorcraft`, plain or compressed): the PDF the document carries + when VectorCraft saved it with Create PDF-Compatible File, one page per artboard, read through + `craft-doc` from craft-libs. The footage codec is `VectorCraft`. A document saved without that + option has no PDF, and importing it reports an error that names the option. ## Limitations @@ -144,7 +148,7 @@ ffmpeg elsewhere) to check the code tables against an independent implementation ## Shared parser setup and bounds The workspace pins `craft-pdf` to `craft-libs` Git revision -`e7c3dda7f3e339dd2c8d40fc4eb405472be1a1e4`, with `default-features = false` and only the explicit `read` +`091863e4a615f38743bfd5d6dc62a2e8f37cd5d5`, with `default-features = false` and only the explicit `read` feature. This excludes the backend's bundled fonts and Adobe CMaps and preserves EffectCraft's font and asset policies. The shared parser does not change the supported drawing operators, image codecs, continuously rasterized SVG tree, editable shapes, or EPS interpreter. diff --git a/crates/pdf/src/build.rs b/crates/pdf/src/build.rs index 0f295a045..3310bd9e0 100644 --- a/crates/pdf/src/build.rs +++ b/crates/pdf/src/build.rs @@ -10,6 +10,9 @@ pub(crate) const MAX_PATH: usize = 1 << 20; /// The deepest the open groups nest (the render tree and its consumers recurse through them). const MAX_DEPTH: usize = 256; +/// The most characters of a logical text label kept in a group name. +pub(crate) const MAX_LABEL: usize = 256; + #[derive(Clone, Copy, PartialEq, Eq)] enum Kind { Plain, @@ -19,6 +22,9 @@ enum Kind { pub(crate) struct Builder { stack: Vec<(Group, Kind)>, + /// Logical text labels never share the graphics-state group stack. + text_labels: Vec, + text_run: bool, /// Which of the finished top-level nodes are optional-content layers. pub top_layers: Vec, pub skipped: Vec, @@ -34,14 +40,14 @@ pub(crate) fn group(name: &str) -> Group { impl Builder { pub fn new() -> Builder { - Builder { stack: vec![(group("page"), Kind::Plain)], top_layers: vec![], skipped: vec![], shapes: 0, base: 0 } + Builder { stack: vec![(group("page"), Kind::Plain)], text_labels: vec![], text_run: false, top_layers: vec![], skipped: vec![], shapes: 0, base: 0 } } /// A builder for content that will be placed inside this one's open groups and `wrap` more /// groups (a pattern's `Pattern` and `Tile`, a soft mask's two), so its nesting limit counts /// them. pub fn nested(&self, wrap: usize) -> Builder { - Builder { base: self.base.saturating_add(self.stack.len()).saturating_add(wrap), ..Builder::new() } + Builder { base: self.base.saturating_add(self.stack.len()).saturating_add(self.text_labels.len()).saturating_add(wrap), ..Builder::new() } } pub fn depth(&self) -> usize { @@ -50,7 +56,7 @@ impl Builder { /// `wrap` more groups fit under the open ones within [`MAX_DEPTH`]. pub fn has_room(&self, wrap: usize) -> bool { - self.base.saturating_add(self.stack.len()).saturating_add(wrap) <= MAX_DEPTH + self.base.saturating_add(self.stack.len()).saturating_add(self.text_labels.len()).saturating_add(wrap) <= MAX_DEPTH } pub fn skip(&mut self, what: &str) { @@ -60,6 +66,7 @@ impl Builder { } fn add(&mut self, n: Node, layer: bool) { + self.text_run = false; if self.stack.len() == 1 { self.top_layers.push(layer); } @@ -70,6 +77,9 @@ impl Builder { /// Close every group opened above `depth`. pub fn close_to(&mut self, depth: usize) { + if self.stack.len() > depth.max(1) { + self.text_run = false; + } while self.stack.len() > depth.max(1) { let Some((g, k)) = self.stack.pop() else { break }; // Empty clipping groups draw nothing. @@ -83,6 +93,7 @@ impl Builder { /// Open `g` as the group drawn into from now on; past [`MAX_DEPTH`] the group is dropped /// (what would have been drawn inside it goes to the open group) and noted as skipped. fn push_group(&mut self, g: Group, kind: Kind) { + self.text_run = false; if self.base.saturating_add(self.stack.len()) >= MAX_DEPTH { self.skip("group nesting limit"); return; @@ -109,9 +120,74 @@ impl Builder { self.push_group(g, Kind::Plain); } + /// Start a bounded logical annotation independently of graphics-state nesting. + pub fn begin_text(&mut self, text: &str) -> bool { + self.text_run = false; + if self.text_labels.len() >= MAX_DEPTH { + self.skip("logical text nesting limit"); + return false; + } + // Every paint wrapped by the annotation carries its own copy of the label, so a long + // /ActualText is cut to MAX_LABEL characters rather than copied whole into each. + let text: String = text.chars().take(MAX_LABEL).collect(); + self.text_labels.push(format!("Text: {text}")); + true + } + + pub fn end_text(&mut self) { + self.text_run = false; + self.text_labels.pop(); + } + /// Add a finished node (an image, pattern tiles). - pub fn push(&mut self, n: Node) { + pub fn push(&mut self, mut n: Node) { + // Marked content is metadata, not a transparency boundary. Wrap only the + // painted node, without closing, splitting or reopening any live state group. + // Finished forms may already contain groups: metadata cannot extend the cap. + fn group_depth(n: &Node, at: usize) -> usize { + match n { + Node::Group(g) => { + if at >= MAX_DEPTH { + return MAX_DEPTH; + } + 1 + g.children.iter().map(|n| group_depth(n, at + 1)).max().unwrap_or(0) + } + _ => 0, + } + } + let contained = if self.text_labels.is_empty() { 0 } else { group_depth(&n, 0) }; + let room = MAX_DEPTH.saturating_sub(self.base.saturating_add(self.stack.len()).saturating_add(contained)); + if self.text_labels.len() > room { + self.skip("group nesting limit"); + } + // Keep consecutive glyphs of one annotation together only inside the same + // graphics-state container. A knockout parent's children must stay separate. + let coalesce = !self.text_labels.is_empty() && self.text_labels.len() <= room; + if self.text_run + && coalesce + && let Some((parent, _)) = self.stack.last_mut() + && !parent.knockout + { + let mut target = parent.children.last_mut(); + for _ in 1..self.text_labels.len() { + target = match target { + Some(Node::Group(g)) => g.children.first_mut(), + _ => None, + }; + } + if let Some(Node::Group(g)) = target { + g.children.push(n); + return; + } + } + for label in self.text_labels.iter().take(room).rev() { + let mut g = group(label); + g.isolated = false; + g.children.push(n); + n = Node::Group(g); + } self.add(n, false); + self.text_run = coalesce; } pub fn fill_stroke(&mut self, path: BezPath, transform: Affine, fill: Option<(Paint, f64, FillRule)>, stroke: Option) { @@ -128,7 +204,7 @@ impl Builder { None => (None, 1.0, FillRule::NonZero), }; let s = Shape { name: name.into(), geom: Geom::Path(path), transform, fill: f, fill_opacity: fo, fill_rule: rule, stroke, opacity: 1.0 }; - self.add(Node::Shape(s), false); + self.push(Node::Shape(s)); } /// The finished top-level nodes and their layer flags. @@ -139,3 +215,17 @@ impl Builder { (root, flags, self.skipped) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_long_logical_label_is_cut_once_at_begin_text() { + let mut b = Builder::new(); + assert!(b.begin_text(&"é".repeat(MAX_LABEL * 4))); + assert_eq!(b.text_labels[0].chars().count(), "Text: ".len() + MAX_LABEL); + assert!(b.begin_text("short")); + assert_eq!(b.text_labels[1], "Text: short"); + } +} diff --git a/crates/pdf/src/cff.rs b/crates/pdf/src/cff.rs index cb7214cc2..efc853caa 100644 --- a/crates/pdf/src/cff.rs +++ b/crates/pdf/src/cff.rs @@ -366,14 +366,6 @@ pub struct Cff { pub encoding: [u16; 256], } -/// The first font name in a CFF program's Name INDEX. -pub fn font_name(data: &[u8]) -> Option { - let hdr = *data.get(2)? as usize; - let (names, _) = index(data, hdr)?; - let r = names.first()?.clone(); - Some(String::from_utf8_lossy(data.get(r)?).into_owned()) -} - impl Cff { pub fn parse(data: &[u8]) -> Option { let d = data; diff --git a/crates/pdf/src/color.rs b/crates/pdf/src/color.rs index 5a7e9af86..8b150f907 100644 --- a/crates/pdf/src/color.rs +++ b/crates/pdf/src/color.rs @@ -779,7 +779,24 @@ impl Func { } } -/// PDF text string → Rust string (UTF-16BE with a byte-order mark, else PDFDocEncoding ≈ Latin-1). +/// PDFDocEncoding (ISO 32000-2 Annex D) where it differs from Latin-1: bytes 0x18–0x1F and +/// 0x80–0xA0 (0x9F is undefined). +const PDFDOC_LOW: [char; 8] = ['˘', 'ˇ', 'ˆ', '˙', '˝', '˛', '˚', '˜']; +const PDFDOC_HIGH: [char; 33] = [ + '•', '†', '‡', '…', '—', '–', 'ƒ', '⁄', '‹', '›', '−', '‰', '„', '“', '”', '‘', '’', '‚', '™', 'fi', 'fl', 'Ł', 'Œ', 'Š', 'Ÿ', 'Ž', 'ı', 'ł', 'œ', 'š', 'ž', + '\u{FFFD}', '€', +]; + +fn pdfdoc_char(c: u8) -> char { + match c { + 0x18..=0x1F => PDFDOC_LOW[usize::from(c - 0x18)], + 0x80..=0xA0 => PDFDOC_HIGH[usize::from(c - 0x80)], + _ => char::from(c), + } +} + +/// PDF text string → Rust string (UTF-16BE with a byte-order mark, UTF-8 with one, else +/// PDFDocEncoding). pub fn text_string(b: &[u8]) -> String { if b.starts_with(&[0xFE, 0xFF]) { let u: Vec = b[2..].as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect(); @@ -788,13 +805,19 @@ pub fn text_string(b: &[u8]) -> String { if let Some(rest) = b.strip_prefix(&[0xEF, 0xBB, 0xBF]) { return String::from_utf8_lossy(rest).into_owned(); } - b.iter().map(|&c| c as char).collect() + b.iter().map(|&c| pdfdoc_char(c)).collect() } #[cfg(test)] mod tests { use super::*; + #[test] + fn text_strings_without_a_bom_are_pdfdocencoding() { + assert_eq!(text_string(b"a\x80b\x92\xa0\x18\xe9"), "a•b™€˘é"); + assert_eq!(text_string(b"\xfe\xff\x00A\x20\x22"), "A•"); + } + #[test] fn sample_count_at_and_over_the_cap() { // 4 Mi entries × 4 outputs fill the cap exactly; a fifth output passes it. diff --git a/crates/pdf/src/font.rs b/crates/pdf/src/font.rs index 8bd91831e..2e9347a2c 100644 --- a/crates/pdf/src/font.rs +++ b/crates/pdf/src/font.rs @@ -350,36 +350,6 @@ impl Font { } } - /// A simple font outside a PDF (EPS text): `program` is an embedded font program (CFF when - /// the flag is set, else Type 1), otherwise the bundled stand-in for `name` is used; - /// `names` is the encoding (code → glyph name), else the program's built-in encoding or - /// StandardEncoding. Advances are the program's. - pub fn standalone(name: &str, program: Option<(&[u8], bool)>, names: Option>>) -> Font { - let mut f = Font::blank(name, false); - f.program = match program { - Some((data, true)) => Cff::parse(data).map(|c| Program::Cff(Box::new(c))), - Some((data, false)) => Type1::parse(data).map(|t| Program::Type1(Box::new(t))), - None => None, - } - .unwrap_or_else(|| Program::Fallback(fallback(name))); - match &f.program { - Program::Cff(c) => f.matrix = Affine::new(c.font_matrix), - Program::Type1(t) => f.matrix = t.font_matrix.map(Affine::new).unwrap_or(f.matrix), - _ => {} - } - let symbol = matches!(f.program, Program::Fallback(_)) && (name.contains("Symbol") || name.contains("Dingbats")); - f.names = match names { - // Unencoded codes draw .notdef (not the built-in encoding). - Some(n) => (0..256).map(|c| Some(n.get(c).cloned().flatten().unwrap_or_else(|| ".notdef".into()))).collect(), - None => match &f.program { - Program::Type1(t) if !t.encoding.is_empty() => (0..256).map(|c| t.encoding.get(&(c as u8)).cloned()).collect(), - _ if symbol => vec![None; 256], - _ => (0..256).map(|c| Base::Standard.name(c as u8)).collect(), - }, - }; - f - } - pub fn load(file: &File, d: &Dict, skipped: &mut Vec) -> Font { let subtype = file.get(d, "Subtype").and_then(Obj::name).unwrap_or("Type1").to_string(); let base_name = file.get(d, "BaseFont").and_then(Obj::name).unwrap_or("").to_string(); diff --git a/crates/pdf/src/lib.rs b/crates/pdf/src/lib.rs index ff914e759..4fd5d701c 100644 --- a/crates/pdf/src/lib.rs +++ b/crates/pdf/src/lib.rs @@ -18,7 +18,6 @@ mod font; mod image; mod object; mod page; -mod ps; mod read; mod shading; mod type1; @@ -34,6 +33,8 @@ pub enum Error { NoPages, PageOutOfRange(usize), NoBoundingBox, + /// A VectorCraft document saved without Create PDF-Compatible File. + NoCarriedPdf, Read(String), } @@ -45,6 +46,9 @@ impl std::fmt::Display for Error { Error::NoPages => write!(f, "the PDF has no pages"), Error::PageOutOfRange(n) => write!(f, "the PDF has no page {}", n.saturating_add(1)), Error::NoBoundingBox => write!(f, "the EPS file has no %%BoundingBox"), + Error::NoCarriedPdf => { + write!(f, "the VectorCraft document holds no PDF; save it in VectorCraft with Create PDF-Compatible File turned on") + } Error::Read(message) => f.write_str(message), } } @@ -53,17 +57,24 @@ impl std::fmt::Display for Error { impl std::error::Error for Error {} /// File extensions read as vector footage by this crate. -pub const EXTENSIONS: &[&str] = &["pdf", "ai", "eps", "epsf", "epsi"]; +pub const EXTENSIONS: &[&str] = &["pdf", "ai", "eps", "epsf", "epsi", "vectorcraft"]; /// The format of a file, by its first bytes. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Format { Pdf, Eps, + /// A VectorCraft document (`.vectorcraft`), read through the PDF it carries when it was + /// saved with Create PDF-Compatible File: one page per artboard. + VectorCraft, } -/// Sniff a PDF (`%PDF-` near the start, as PDF-compatible `.ai` files are) or an EPS file. +/// Sniff a VectorCraft document, a PDF (`%PDF-` near the start, as PDF-compatible `.ai` files +/// are) or an EPS file. The first 64 KiB suffice. pub fn sniff(bytes: &[u8]) -> Option { + if craft_doc::sniff(bytes) == Some(craft_doc::Kind::VectorCraft) { + return Some(Format::VectorCraft); + } let head = &bytes[..bytes.len().min(1024)]; if head.windows(5).any(|w| w == b"%PDF-") { return Some(Format::Pdf); @@ -74,11 +85,12 @@ pub fn sniff(bytes: &[u8]) -> Option { None } -/// A footage codec name for a sniffed file ("PDF", "AI", "EPS"). +/// A footage codec name for a sniffed file ("PDF", "AI", "EPS", "VectorCraft"). pub fn codec(path: &str, bytes: &[u8]) -> Option<&'static str> { let f = sniff(bytes)?; let ai = path.to_ascii_lowercase().ends_with(".ai"); Some(match (f, ai) { + (Format::VectorCraft, _) => "VectorCraft", (_, true) => "AI", (Format::Pdf, false) => "PDF", (Format::Eps, false) => "EPS", @@ -112,19 +124,47 @@ pub fn parse_page_framed(bytes: &[u8], index: usize, framing: Framing) -> Result match sniff(bytes) { Some(Format::Pdf) => parse_pdf(bytes, index, framing), Some(Format::Eps) => parse_eps(bytes), + Some(Format::VectorCraft) => parse_pdf(&carried_pdf(bytes)?, index, framing), None => Err(Error::NotVector), } } /// Number of pages (1 for EPS). pub fn page_count(bytes: &[u8]) -> usize { + let pdf_pages = |bytes: &[u8]| object::File::parse(bytes).map(|file| page::pages(&file).len()).unwrap_or(0); match sniff(bytes) { - Some(Format::Pdf) => object::File::parse(bytes).map(|file| page::pages(&file).len()).unwrap_or(0), + Some(Format::Pdf) => pdf_pages(bytes), Some(Format::Eps) => 1, + Some(Format::VectorCraft) => carried_pdf(bytes).map(|pdf| pdf_pages(&pdf)).unwrap_or(0), None => 0, } } +/// The PDF a VectorCraft document carries: [`Error::NoCarriedPdf`] when it was saved without +/// Create PDF-Compatible File. The preview is not read, so a damaged preview does not stop the +/// import. +fn carried_pdf(bytes: &[u8]) -> Result, Error> { + let pdf = craft_doc::rendition(bytes, craft_doc::RenditionKind::Pdf, &carried_limits()) + .map_err(|e| Error::Read(format!("VectorCraft document: {e}")))? + .ok_or(Error::NoCarriedPdf)?; + if sniff(&pdf.bytes) != Some(Format::Pdf) { + return Err(Error::Read("VectorCraft document: its PDF member is not a PDF".into())); + } + Ok(pdf.bytes) +} + +/// craft-doc's limits for [`carried_pdf`]: a PDF after the JSON (version 4) may be as large as a +/// PDF file this crate opens (`craft_pdf::MAX_INPUT_BYTES`); one inline in the JSON as base64 +/// (version 3) stays within `max_json`, about 192 MiB of PDF. `max_total` allows `max_json` (craft-doc's default) for a +/// compressed document's JSON, and twice `max_entry` for its data up to the PDF's end and the PDF +/// copied out, which caps what a hostile file can make the import allocate. +fn carried_limits() -> craft_doc::Limits { + let mut limits = craft_doc::Limits::default(); + limits.max_entry = u64::try_from(craft_pdf::MAX_INPUT_BYTES).unwrap_or(u64::MAX); + limits.max_total = limits.max_json.saturating_add(limits.max_entry.saturating_mul(2)); + limits +} + /// Build the document: `root` children become layer groups (see the crate docs). fn finish(nodes: Vec, flags: Vec, skipped: Vec, width: f64, height: f64, to_doc: Affine) -> Doc { let mut layers: Vec = vec![]; @@ -188,13 +228,58 @@ fn parse_pdf(bytes: &[u8], index: usize, framing: Framing) -> Result Ok(finish(nodes, flags, skipped, dw.max(1.0), dh.max(1.0), to_doc)) } +fn eps_fallback_font(name: &[u8]) -> Option<&'static [u8]> { + use effectcraft_text::fonts::{INTER_BOLD, INTER_ITALIC, INTER_REGULAR, INTER_SEMIBOLD, JETBRAINS_MONO_REGULAR, NOTO_SERIF_REGULAR}; + let name = String::from_utf8_lossy(name).to_ascii_lowercase(); + Some(if name.contains("courier") || name.contains("mono") || name.contains("consol") { + JETBRAINS_MONO_REGULAR + } else if name.contains("times") + || name.contains("serif") && !name.contains("sans") + || name.contains("georgia") + || name.contains("garamond") + || name.contains("minion") + || name.contains("roman") + { + NOTO_SERIF_REGULAR + } else if name.contains("semibold") || name.contains("demi") { + INTER_SEMIBOLD + } else if name.contains("bold") || name.contains("black") || name.contains("heavy") { + INTER_BOLD + } else if name.contains("italic") || name.contains("oblique") { + INTER_ITALIC + } else { + INTER_REGULAR + }) +} + fn parse_eps(bytes: &[u8]) -> Result { - let (ps, bb) = ps::eps_parts(bytes).ok_or(Error::NoBoundingBox)?; - let mut it = ps::Interp::new(bb); - it.run(ps); - let (nodes, flags, skipped) = it.b.finish(); - let to_doc = Affine::new([1.0, 0.0, 0.0, -1.0, -bb[0], bb[3]]); - Ok(finish(nodes, flags, skipped, (bb[2] - bb[0]).max(1.0), (bb[3] - bb[1]).max(1.0), to_doc)) + let limits = craft_ps::read::Limits { + // Preserve EffectCraft's established 8,000,000-unit PostScript execution budget. + steps: 8_000_000, + stack_overflow_noop: true, + skip_images: true, + keep_unpainted: true, + zero_division_zero: true, + fallback_font: Some(eps_fallback_font), + ..Default::default() + }; + let converted = craft_ps::read::eps_to_pdf(bytes, limits).map_err(|message| match message.as_str() { + "not PostScript" | "the EPS has no bounding box" => Error::NoBoundingBox, + _ => Error::Read(message), + })?; + let mut doc = parse_pdf(&converted.pdf, 0, Framing::Placed)?; + for skipped in &mut doc.skipped { + if skipped == "content (path limit)" { + *skipped = "PostScript (path limit)".to_string(); + } + } + doc.skipped.extend(converted.warnings.into_iter().map(|warning| match warning.as_str() { + "the program runs too long" | "out of memory" => "PostScript (operation limit)".to_string(), + "executable name resolution limit" => "PostScript (recursion limit)".to_string(), + "content (path limit)" => "PostScript (path limit)".to_string(), + _ => warning, + })); + Ok(doc) } /// The document's layer names (the root's children), bottom first. diff --git a/crates/pdf/src/object.rs b/crates/pdf/src/object.rs index df475a4bb..dbe1ca706 100644 --- a/crates/pdf/src/object.rs +++ b/crates/pdf/src/object.rs @@ -516,6 +516,7 @@ fn ascii_hex(data: &[u8], max: usize) -> Option> { Some(out) } +#[cfg(test)] pub fn ascii85(data: &[u8]) -> Vec { // The PostScript reader uses this unbounded entry point. No Vec can hold more // than usize::MAX bytes, so its output cannot exceed this bound. diff --git a/crates/pdf/src/page.rs b/crates/pdf/src/page.rs index ba67b39aa..cb8e02f88 100644 --- a/crates/pdf/src/page.rs +++ b/crates/pdf/src/page.rs @@ -209,7 +209,7 @@ pub(crate) struct Interp<'a> { cur: Option, start: Option, pending_clip: Option, - marked: Vec>, + marked: Vec, /// The page box in default user space (for `sh`). page_box: [f64; 4], budget: usize, @@ -237,6 +237,12 @@ enum TextItem { Adjust(f64), } +enum Marked { + None, + Layer(usize), + Text, +} + impl<'a> Interp<'a> { pub fn new(file: &'a File, page_box: [f64; 4]) -> Self { Interp { @@ -488,7 +494,7 @@ impl<'a> Interp<'a> { } "d1" => self.gs.lock_color = true, "BI" => self.inline_image(&mut lx, res), - "BMC" => self.marked.push(None), + "BMC" => self.marked.push(Marked::None), "BDC" => { let layer = match (args.first().and_then(Obj::name), args.get(1)) { (Some("OC"), Some(Obj::Name(prop))) => self @@ -499,19 +505,37 @@ impl<'a> Interp<'a> { (Some("OC"), Some(Obj::Dict(ocg))) => self.ocg_name(ocg), _ => None, }; - match layer { - Some(name) => { - self.marked.push(Some(self.b.depth())); + let props = match args.get(1) { + Some(Obj::Name(name)) => self.file.get_dict(res, "Properties").and_then(|p| self.file.get_dict(p, name)), + Some(obj) => self.file.resolve(obj).dict(), + None => None, + }; + let actual_text = + (args.first().and_then(Obj::name) == Some("Span")).then_some(props).flatten().and_then(|p| self.file.get(p, "ActualText")).and_then( + |v| match v { + Obj::Str(bytes) => Some(text_string(bytes)), + _ => None, + }, + ); + match (layer, actual_text) { + (Some(name), _) => { + self.marked.push(Marked::Layer(self.b.depth())); self.b.open(&name, true); } - None => self.marked.push(None), + (None, Some(text)) => { + let mark = if self.b.begin_text(&text) { Marked::Text } else { Marked::None }; + self.marked.push(mark); + } + (None, None) => self.marked.push(Marked::None), } } - "EMC" => { - if let Some(Some(d)) = self.marked.pop() { - self.close_to(d); + "EMC" => match self.marked.pop() { + Some(Marked::Layer(d)) => self.close_to(d), + Some(Marked::Text) => { + self.b.end_text(); } - } + _ => {} + }, _ => {} } // Colour operands set by the device-space shorthands. diff --git a/crates/pdf/src/ps.rs b/crates/pdf/src/ps.rs deleted file mode 100644 index 3d734e46c..000000000 --- a/crates/pdf/src/ps.rs +++ /dev/null @@ -1,49 +0,0 @@ -//! Encapsulated PostScript: a small PostScript interpreter (PostScript Language Reference, 3rd -//! edition, and the EPSF 3.0 specification) covering what exported vector EPS files use: the -//! operand and dictionary stacks, procedures and `def`, arithmetic, control flow, arrays and -//! dictionaries, the graphics state, path construction (including arcs) and painting, clipping -//! and device colours, and text (`findfont` / `selectfont`, `show` and its variants, `charpath`, -//! `stringwidth`, re-encoded fonts) with embedded Type 1 and CFF programs or the bundled -//! stand-in fonts. Images are skipped (their inline data is stepped over), as is -//! Level 3 smooth shading (`shfill`). - -use std::cell::RefCell; -use std::collections::HashMap; -use std::rc::Rc; - -use effectcraft_svg::{Affine, BezPath, Cap, FillRule, Join, Paint, Stroke}; -use kurbo::{PathEl, Point}; - -use crate::build::{Builder, MAX_PATH}; -use crate::font::Font; -use crate::object::{ascii85, is_white, parse_num}; - -mod builtin; -mod eps; -mod exec; -mod paths; -mod scanner; -mod text; -mod value; - -pub use eps::eps_parts; -use value::{DictRef, GState, V}; - -pub(crate) struct Interp { - pub b: Builder, - st: Vec, - dicts: Vec, - gs: GState, - saved: Vec, - budget: usize, - /// Nested procedure calls (recursion is cut off at [`MAX_CALL_DEPTH`]). - calls: usize, - /// Fonts by name: `definefont`d dictionaries. - font_dir: HashMap, - /// Embedded font programs found in the file (name → (program, CFF)). - embedded: HashMap>, bool)>, - /// Fonts built for drawing, by base font and encoding. - font_cache: HashMap>, - page: [f64; 4], - pub unknown: Vec, -} diff --git a/crates/pdf/src/ps/builtin.rs b/crates/pdf/src/ps/builtin.rs deleted file mode 100644 index a19aeb6da..000000000 --- a/crates/pdf/src/ps/builtin.rs +++ /dev/null @@ -1,1076 +0,0 @@ -use super::eps::find_from; -use super::exec::MAX_STACK; -use super::scanner::Src; -use super::text::encoding_array; -use super::value::{Flow, V, array, matrix_of, matrix_val, new_dict}; -use super::{Affine, BezPath, Cap, FillRule, Interp, Join, PathEl, Point, Rc, RefCell, parse_num}; - -impl Interp { - pub(super) fn builtin(&mut self, n: &str, src: &mut Src) -> Result<(), Flow> { - // Every handler leaves the stacks untouched when the operator is outside its family. - if self.try_stack_op(n) - || self.try_arithmetic_op(n) - || self.try_logic_op(n) - || self.try_control_op(n, src)? - || self.try_dictionary_op(n) - || self.try_collection_op(n) - || self.try_environment_op(n, src)? - || self.try_graphics_op(n)? - || self.try_coordinate_op(n) - || self.try_path_op(n)? - || self.try_paint_op(n)? - { - return Ok(()); - } - match n { - // Text (see `text_op`). - "scalefont" | "makefont" | "selectfont" | "setfont" | "show" | "charpath" | "glyphshow" | "rootfont" | "currentfont" | "setcachedevice" - | "setcharwidth" | "ashow" | "widthshow" | "awidthshow" | "xshow" | "yshow" | "xyshow" | "kshow" | "cshow" | "stringwidth" | "definefont" - | "StandardEncoding" | "ISOLatin1Encoding" | "eexec" | "StartData" | "undefinefont" => self.text_op(n, src)?, - // Images: operands popped, inline data skipped. - "image" | "imagemask" | "colorimage" => { - let mut reads_file = false; - let check = |v: &V, rf: &mut bool| { - if matches!(v, V::File) || matches!(v, V::Proc(p) if p.iter().any(|x| matches!(x, V::Name(n) if &**n == "currentfile"))) { - *rf = true; - } - }; - if n == "colorimage" { - let ncomp = self.popn().max(1.0) as usize; - let multi = matches!(self.pop(), V::Bool(true)); - for _ in 0..if multi { ncomp.min(4) } else { 1 } { - let v = self.pop(); - check(&v, &mut reads_file); - } - for _ in 0..4 { - self.pop(); - } - } else { - match self.pop() { - V::Dict(d) => { - if let Some(ds) = d.borrow().get("DataSource") { - check(ds, &mut reads_file); - } - } - top => { - check(&top, &mut reads_file); - for _ in 0..4 { - self.pop(); - } - } - } - } - if reads_file { - src.skip_image_data(); - } - self.b.skip("image"); - } - _ => { - if self.unknown.len() < 32 && !self.unknown.iter().any(|u| u == n) { - self.unknown.push(n.to_string()); - } - } - } - Ok(()) - } - - fn repeat_proc(&mut self, src: &mut Src) -> Result<(), Flow> { - let p = self.pop(); - let k = self.popn().clamp(0.0, 1e6) as usize; - for _ in 0..k { - self.spend(1)?; - match self.exec_obj(p.clone(), src) { - Err(Flow::Exit) => break, - r => r?, - } - } - - Ok(()) - } - - fn for_proc(&mut self, src: &mut Src) -> Result<(), Flow> { - let p = self.pop(); - let lim = self.popn(); - let inc = self.popn(); - let mut i = self.popn(); - let mut guard = 0; - while inc != 0.0 && ((inc > 0.0 && i <= lim) || (inc < 0.0 && i >= lim)) && guard < 1_000_000 { - self.spend(1)?; - self.push(V::Num(i)); - match self.exec_obj(p.clone(), src) { - Err(Flow::Exit) => break, - r => r?, - } - i += inc; - guard += 1; - } - - Ok(()) - } - - fn loop_proc(&mut self, src: &mut Src) -> Result<(), Flow> { - let p = self.pop(); - for _ in 0..1_000_000 { - self.spend(1)?; - match self.exec_obj(p.clone(), src) { - Err(Flow::Exit) => break, - r => r?, - } - } - - Ok(()) - } - - fn forall_proc(&mut self, src: &mut Src) -> Result<(), Flow> { - let p = self.pop(); - match self.pop() { - V::Dict(d) => { - let items: Vec<(String, V)> = d.borrow().iter().map(|(k, v)| (k.clone(), v.clone())).collect(); - for (k, v) in items { - self.spend(1)?; - self.push(V::Lit(k.into())); - self.push(v); - match self.exec_obj(p.clone(), src) { - Err(Flow::Exit) => break, - r => r?, - } - } - } - V::Str(s) => { - let bytes = s.borrow().clone(); - for c in bytes { - self.spend(1)?; - self.push(V::Num(c as f64)); - match self.exec_obj(p.clone(), src) { - Err(Flow::Exit) => break, - r => r?, - } - } - } - a => { - for v in a.items().unwrap_or_default() { - self.spend(1)?; - self.push(v); - match self.exec_obj(p.clone(), src) { - Err(Flow::Exit) => break, - r => r?, - } - } - } - } - - Ok(()) - } - - fn try_stack_op(&mut self, n: &str) -> bool { - match n { - // Stack. - "pop" => { - self.pop(); - } - "exch" => { - let b = self.pop(); - let a = self.pop(); - self.push(b); - self.push(a); - } - "dup" => { - let a = self.st.last().cloned().unwrap_or(V::Null); - self.push(a); - } - "copy" => { - match self.pop() { - V::Num(k) => { - let k = (k.max(0.0) as usize).min(self.st.len()); - // A copy past the operand limit copies nothing, and the values copied - // count as operations (one for eight): repeated doubling spends the budget. - if self.st.len().saturating_add(k) <= MAX_STACK { - self.charge(k / 8); - let tail: Vec = self.st[self.st.len() - k..].to_vec(); - self.st.extend(tail); - } - } - V::Array(dst) => { - let s = self.pop().items().unwrap_or_default(); - let mut d = dst.borrow_mut(); - for (i, v) in s.into_iter().enumerate() { - if i < d.len() { - d[i] = v; - } - } - drop(d); - self.push(V::Array(dst)); - } - other => self.push(other), - }; - } - "index" => { - let k = self.popn().max(0.0) as usize; - let v = if k < self.st.len() { self.st[self.st.len() - 1 - k].clone() } else { V::Null }; - self.push(v); - } - "roll" => { - let j = self.popn() as i64; - let k = (self.popn().max(0.0) as usize).min(self.st.len()); - if k > 0 { - let s = self.st.len() - k; - let r = j.rem_euclid(k as i64) as usize; - self.st[s..].rotate_right(r); - } - } - "clear" => self.st.clear(), - "count" => self.push(V::Num(self.st.len() as f64)), - "mark" | "[" | "<<" => self.push(V::Mark), - "cleartomark" => { - while let Some(v) = self.st.pop() { - if matches!(v, V::Mark) { - break; - } - } - } - "counttomark" => { - let k = self.st.iter().rev().position(|v| matches!(v, V::Mark)).unwrap_or(self.st.len()); - self.push(V::Num(k as f64)); - } - "]" => { - let k = self.st.iter().rev().position(|v| matches!(v, V::Mark)).unwrap_or(self.st.len()); - let items = self.st.split_off(self.st.len() - k); - self.st.pop(); - self.push(array(items)); - } - ">>" => { - let k = self.st.iter().rev().position(|v| matches!(v, V::Mark)).unwrap_or(self.st.len()); - let items = self.st.split_off(self.st.len() - k); - self.st.pop(); - let d = new_dict(); - for kv in items.as_chunks::<2>().0 { - d.borrow_mut().insert(kv[0].key(), kv[1].clone()); - } - self.push(V::Dict(d)); - } - _ => return false, - } - true - } - - fn try_arithmetic_op(&mut self, n: &str) -> bool { - match n { - // Arithmetic. - "add" | "sub" | "mul" | "div" | "idiv" | "mod" | "atan" | "exp" | "max" | "min" => { - let b = self.popn(); - let a = self.popn(); - let v = match n { - "add" => a + b, - "sub" => a - b, - "mul" => a * b, - "div" => { - if b == 0.0 { - 0.0 - } else { - a / b - } - } - // `checked_*` give 0 both for a zero divisor and for the one overflowing - // case, `i64::MIN / -1` (`/` and `%` panic on it in every build). - "idiv" => (a as i64).checked_div(b as i64).unwrap_or(0) as f64, - "mod" => (a as i64).checked_rem(b as i64).unwrap_or(0) as f64, - "atan" => a.atan2(b).to_degrees().rem_euclid(360.0), - "exp" => a.powf(b), - "max" => a.max(b), - _ => a.min(b), - }; - self.push(V::Num(if v.is_finite() { v } else { 0.0 })); - } - "neg" | "abs" | "sqrt" | "sin" | "cos" | "ln" | "log" | "cvi" | "cvr" | "round" | "floor" | "ceiling" | "truncate" => { - let a = match self.pop() { - V::Str(s) => parse_num(&s.borrow()).unwrap_or(0.0), - v => v.num().unwrap_or(0.0), - }; - let v = match n { - "neg" => -a, - "abs" => a.abs(), - "sqrt" => a.max(0.0).sqrt(), - "sin" => a.to_radians().sin(), - "cos" => a.to_radians().cos(), - "ln" => a.ln(), - "log" => a.log10(), - "cvi" | "truncate" => a.trunc(), - "round" => (a + 0.5).floor(), - "floor" => a.floor(), - "ceiling" => a.ceil(), - _ => a, - }; - self.push(V::Num(if v.is_finite() { v } else { 0.0 })); - } - _ => return false, - } - true - } - - fn try_logic_op(&mut self, n: &str) -> bool { - match n { - // Comparison and logic. - "eq" | "ne" => { - let b = self.pop(); - let a = self.pop(); - let eq = match (&a, &b) { - (V::Num(x), V::Num(y)) => x == y, - (V::Bool(x), V::Bool(y)) => x == y, - (V::Null, V::Null) => true, - (V::Array(x), V::Array(y)) => Rc::ptr_eq(x, y), - (V::Dict(x), V::Dict(y)) => Rc::ptr_eq(x, y), - (x, y) => !x.key().is_empty() && x.key() == y.key(), - }; - self.push(V::Bool(eq == (n == "eq"))); - } - "gt" | "ge" | "lt" | "le" => { - let b = self.popn(); - let a = self.popn(); - self.push(V::Bool(match n { - "gt" => a > b, - "ge" => a >= b, - "lt" => a < b, - _ => a <= b, - })); - } - "not" => match self.pop() { - V::Bool(b) => self.push(V::Bool(!b)), - v => self.push(V::Num(!(v.num().unwrap_or(0.0) as i64) as f64)), - }, - "and" | "or" | "xor" => { - let b = self.pop(); - let a = self.pop(); - match (a, b) { - (V::Bool(x), V::Bool(y)) => self.push(V::Bool(match n { - "and" => x && y, - "or" => x || y, - _ => x ^ y, - })), - (x, y) => { - let (x, y) = (x.num().unwrap_or(0.0) as i64, y.num().unwrap_or(0.0) as i64); - self.push(V::Num(match n { - "and" => x & y, - "or" => x | y, - _ => x ^ y, - } as f64)); - } - } - } - "true" => self.push(V::Bool(true)), - "false" => self.push(V::Bool(false)), - "null" => self.push(V::Null), - _ => return false, - } - true - } - - fn try_control_op(&mut self, n: &str, src: &mut Src) -> Result { - match n { - // Control. - "exec" => { - let v = self.pop(); - self.exec_obj(v, src)?; - } - "if" => { - let p = self.pop(); - if let V::Bool(true) = self.pop() { - self.exec_obj(p, src)?; - } - } - "ifelse" => { - let f = self.pop(); - let t = self.pop(); - let c = matches!(self.pop(), V::Bool(true)); - self.exec_obj(if c { t } else { f }, src)?; - } - // Each pass of a loop counts against the budget. - "repeat" => self.repeat_proc(src)?, - "for" => self.for_proc(src)?, - "loop" => self.loop_proc(src)?, - "forall" => self.forall_proc(src)?, - "exit" => return Err(Flow::Exit), - "stop" => return Err(Flow::Stop), - "stopped" => { - let p = self.pop(); - let stopped = match self.exec_obj(p, src) { - Err(Flow::Quit) => return Err(Flow::Quit), - Err(_) => true, - Ok(()) => false, - }; - self.push(V::Bool(stopped)); - } - "quit" => return Err(Flow::Quit), - "showpage" | "copypage" => {} - _ => return Ok(false), - } - Ok(true) - } - - fn try_dictionary_op(&mut self, n: &str) -> bool { - match n { - // Dictionaries. - "def" => { - let v = self.pop(); - let k = self.pop().key(); - if let Some(d) = self.dicts.last() { - d.borrow_mut().insert(k, v); - } - } - "store" => { - let v = self.pop(); - let k = self.pop().key(); - let d = self.dicts.iter().rev().find(|d| d.borrow().contains_key(&k)).or(self.dicts.last()).cloned(); - if let Some(d) = d { - d.borrow_mut().insert(k, v); - } - } - "load" => { - let k = self.pop().key(); - let v = self.lookup(&k).unwrap_or(V::Op(k.into())); - self.push(v); - } - "undef" => { - let k = self.pop().key(); - if let V::Dict(d) = self.pop() { - d.borrow_mut().remove(&k); - } - } - "dict" => { - self.pop(); - self.push(V::Dict(new_dict())); - } - "begin" => { - if let V::Dict(d) = self.pop() - && self.dicts.len() < 64 - { - self.dicts.push(d); - } - } - "end" => { - if self.dicts.len() > 1 { - self.dicts.pop(); - } - } - "currentdict" => { - let d = self.dicts.last().cloned().unwrap_or_else(new_dict); - self.push(V::Dict(d)); - } - "userdict" | "globaldict" | "systemdict" | "statusdict" | "errordict" | "$error" => { - let d = self.dicts[0].clone(); - self.push(V::Dict(d)); - } - "where" => { - let k = self.pop().key(); - match self.dicts.iter().rev().find(|d| d.borrow().contains_key(&k)).cloned() { - Some(d) => { - self.push(V::Dict(d)); - self.push(V::Bool(true)); - } - None => self.push(V::Bool(false)), - } - } - "known" => { - let k = self.pop().key(); - let v = match self.pop() { - V::Dict(d) => d.borrow().contains_key(&k), - _ => false, - }; - self.push(V::Bool(v)); - } - "countdictstack" => self.push(V::Num(self.dicts.len() as f64)), - "cleardictstack" => self.dicts.truncate(1), - "findresource" | "findfont" | "findencoding" => { - let category = if n == "findresource" { self.pop().key() } else { String::new() }; - let key = self.pop().key(); - match (n, category.as_str()) { - ("findfont", _) | (_, "Font") => { - let f = self.find_font(&key); - self.push(V::Dict(f)); - } - ("findencoding", _) | (_, "Encoding") => self.push(encoding_array(&key)), - _ => self.push(V::Dict(new_dict())), - } - } - "defineresource" => { - let category = self.pop().key(); - let v = self.pop(); - let key = self.pop().key(); - if let (V::Dict(d), "Font") = (&v, category.as_str()) { - self.font_dir.insert(key, d.clone()); - } - self.push(v); - } - "resourcestatus" => { - self.pop(); - self.pop(); - self.push(V::Bool(false)); - } - _ => return false, - } - true - } - - fn try_collection_op(&mut self, n: &str) -> bool { - match n { - // Arrays and strings. - // The storage made counts as operations (a value, or eight bytes, each), so a loop - // of large constructors spends the budget rather than the memory. - "array" => { - let k = self.popn().clamp(0.0, 1e6) as usize; - self.charge(k); - self.push(array(vec![V::Null; k])); - } - "string" => { - let k = self.popn().clamp(0.0, 1e7) as usize; - self.charge(k / 8); - self.push(V::Str(Rc::new(RefCell::new(vec![0; k])))); - } - "length" => { - let l = match self.pop() { - V::Str(s) => s.borrow().len(), - V::Dict(d) => d.borrow().len(), - V::Name(s) | V::Lit(s) => s.len(), - v => v.items().map_or(0, |i| i.len()), - }; - self.push(V::Num(l as f64)); - } - "get" => { - let k = self.pop(); - let v = match self.pop() { - V::Dict(d) => d.borrow().get(&k.key()).cloned().unwrap_or(V::Null), - V::Str(s) => V::Num(s.borrow().get(k.num().unwrap_or(0.0) as usize).copied().unwrap_or(0) as f64), - a => a.items().and_then(|i| i.get(k.num().unwrap_or(0.0) as usize).cloned()).unwrap_or(V::Null), - }; - self.push(v); - } - "put" => { - let v = self.pop(); - let k = self.pop(); - match self.pop() { - V::Dict(d) => { - d.borrow_mut().insert(k.key(), v); - } - V::Array(a) => { - let i = k.num().unwrap_or(0.0) as usize; - if let Some(slot) = a.borrow_mut().get_mut(i) { - *slot = v; - } - } - V::Str(s) => { - let i = k.num().unwrap_or(0.0) as usize; - if let Some(slot) = s.borrow_mut().get_mut(i) { - *slot = v.num().unwrap_or(0.0) as u8; - } - } - _ => {} - } - } - "getinterval" => { - let c = self.popn().max(0.0) as usize; - let i = self.popn().max(0.0) as usize; - match self.pop() { - V::Str(s) => { - let b = s.borrow(); - let part = b.get(i.min(b.len())..(i + c).min(b.len())).unwrap_or(&[]).to_vec(); - drop(b); - self.push(V::Str(Rc::new(RefCell::new(part)))); - } - a => { - let items = a.items().unwrap_or_default(); - let part = items.get(i.min(items.len())..(i + c).min(items.len())).unwrap_or(&[]).to_vec(); - self.push(array(part)); - } - } - } - "putinterval" => { - self.pop(); - self.pop(); - self.pop(); - } - "aload" => { - let a = self.pop(); - for v in a.items().unwrap_or_default() { - self.push(v); - } - self.push(a); - } - "astore" => { - let a = self.pop(); - if let V::Array(arr) = &a { - let k = arr.borrow().len().min(self.st.len()); - let items = self.st.split_off(self.st.len() - k); - *arr.borrow_mut() = items; - } - self.push(a); - } - "cvx" => match self.pop() { - V::Array(a) => self.push(V::Proc(Rc::new(a.borrow().clone()))), - V::Lit(s) => self.push(V::Name(s)), - V::Str(s) => { - // Executable string: tokenize it as a procedure. - let bytes = s.borrow().clone(); - let mut sub = Src { d: &bytes, pos: 0 }; - let mut body = vec![]; - while let Some(t) = sub.token(0) { - body.push(t); - } - self.push(V::Proc(Rc::new(body))); - } - v => self.push(v), - }, - "cvlit" => match self.pop() { - V::Proc(p) => self.push(array(p.as_ref().clone())), - V::Name(s) => self.push(V::Lit(s)), - v => self.push(v), - }, - "cvn" => { - let k = self.pop().key(); - self.push(V::Lit(k.into())); - } - "cvs" => { - self.pop(); - let k = self.pop().key(); - self.push(V::Str(Rc::new(RefCell::new(k.into_bytes())))); - } - "xcheck" => { - let v = self.pop(); - self.push(V::Bool(matches!(v, V::Proc(_) | V::Name(_) | V::Op(_)))); - } - "type" => { - let t = match self.pop() { - V::Num(_) => "realtype", - V::Bool(_) => "booleantype", - V::Name(_) | V::Lit(_) => "nametype", - V::Op(_) => "operatortype", - V::Str(_) => "stringtype", - V::Proc(_) | V::Array(_) => "arraytype", - V::Dict(_) => "dicttype", - V::Mark => "marktype", - V::Null => "nulltype", - V::File => "filetype", - }; - self.push(V::Name(t.into())); - } - "bind" | "readonly" | "executeonly" | "noaccess" => {} - _ => return false, - } - true - } - - fn try_environment_op(&mut self, n: &str, src: &mut Src) -> Result { - match n { - "languagelevel" => self.push(V::Num(3.0)), - "version" | "product" => self.push(V::Str(Rc::new(RefCell::new(b"3010".to_vec())))), - "save" => { - self.spend(self.gs.path.elements().len())?; - self.saved.push(self.gs.clone()); - self.gs.depth = self.b.depth(); - self.push(V::Null); - } - "restore" => { - self.pop(); - self.grestore(); - } - "currentfile" => self.push(V::File), - "readstring" | "readhexstring" | "readline" => { - self.pop(); - self.pop(); - self.push(V::Str(Rc::new(RefCell::new(vec![])))); - self.push(V::Bool(false)); - } - "flushfile" | "closefile" | "print" | "==" | "=" | "pstack" | "setpagedevice" | "setglobal" | "setpacking" | "setshared" | "setobjectformat" - | "setsmoothness" => { - if !matches!(n, "pstack") { - self.pop(); - } - } - "currentglobal" | "currentpacking" | "currentshared" => self.push(V::Bool(false)), - // Operators that return values must push them, or the rest of the program reads a - // shifted stack: Illustrator's EPS prolog queries the device this way and then drew - // nothing (#955). Values are a plain device's defaults (PostScript Language - // Reference, 3rd ed., chapter 8). - "currentflat" => self.push(V::Num(1.0)), - "currentscreen" => { - self.push(V::Num(60.0)); - self.push(V::Num(45.0)); - self.push(V::Proc(Rc::new(vec![]))); - } - "currentblackgeneration" | "currentundercolorremoval" | "currenttransfer" => self.push(V::Proc(Rc::new(vec![]))), - "currentcolortransfer" => { - for _ in 0..4 { - self.push(V::Proc(Rc::new(vec![]))); - } - } - "currentpagedevice" | "currenthalftone" | "currentsystemparams" | "currentuserparams" | "currentdevparams" => { - if n == "currentdevparams" { - self.pop(); - } - self.push(V::Dict(new_dict())); - } - "setuserparams" | "setsystemparams" | "setcolortransfer" | "setblackgeneration" | "setundercolorremoval" => { - let k = if n == "setcolortransfer" { 4 } else { 1 }; - for _ in 0..k { - self.pop(); - } - } - // `file status` → false; `string status` → false (no such file). - "status" => { - self.pop(); - self.push(V::Bool(false)); - } - "dictstack" => { - self.pop(); - let ds: Vec = self.dicts.iter().map(|d| V::Dict(d.clone())).collect(); - self.push(array(ds)); - } - "maxlength" => { - let k = match self.pop() { - V::Dict(d) => d.borrow().len(), - _ => 0, - }; - self.push(V::Num(k.saturating_add(16) as f64)); - } - "internaldict" => { - self.pop(); - let d = self.dicts[0].clone(); - self.push(V::Dict(d)); - } - "undefineresource" => { - self.pop(); - self.pop(); - } - // `[ … /Name pdfmark`: a Distiller annotation; other interpreters discard it. - "pdfmark" => { - while let Some(v) = self.st.pop() { - if matches!(v, V::Mark) { - break; - } - } - } - // `source [params] /Name filter`. A SubFileDecode of the current file with a count of - // 0 reads to its end-of-data string: skip that data (an embedded XMP packet, which - // otherwise ran as PostScript). Other filters read what their source reads. - "filter" => { - let name = self.pop().key(); - let mut skipped = false; - let source = if name == "SubFileDecode" && !matches!(self.st.last(), Some(V::Dict(_))) { - let eod = match self.pop() { - V::Str(s) => s.borrow().clone(), - _ => vec![], - }; - let count = self.popn(); - let source = self.pop(); - if matches!(source, V::File) && count == 0.0 && !eod.is_empty() { - src.pos = match find_from(src.d, &eod, src.pos) { - Some(p) => p.saturating_add(eod.len()), - None => src.d.len(), - }; - skipped = true; - } - source - } else { - if matches!(self.st.last(), Some(V::Dict(_))) { - self.pop(); - } - self.pop() - }; - // Data already stepped over leaves nothing for `image` to skip. - self.push(if skipped { V::Null } else { source }); - } - "vmstatus" => { - for _ in 0..3 { - self.push(V::Num(0.0)); - } - } - _ => return Ok(false), - } - Ok(true) - } - - fn try_graphics_op(&mut self, n: &str) -> Result { - match n { - // Graphics state. - "gsave" => { - self.spend(self.gs.path.elements().len())?; - let mut g = self.gs.clone(); - g.depth = self.b.depth(); - self.saved.push(g); - } - "grestore" => self.grestore(), - "grestoreall" => { - while !self.saved.is_empty() { - self.grestore(); - } - } - "initgraphics" => { - self.gs.ctm = Affine::IDENTITY; - self.gs.lw = 1.0; - self.gs.color = [0.0; 3]; - } - "setlinewidth" => self.gs.lw = self.popn(), - "currentlinewidth" => self.push(V::Num(self.gs.lw)), - "setlinecap" => self.gs.cap = [Cap::Butt, Cap::Round, Cap::Square][(self.popn().max(0.0) as usize).min(2)], - "setlinejoin" => self.gs.join = [Join::Miter, Join::Round, Join::Bevel][(self.popn().max(0.0) as usize).min(2)], - "setmiterlimit" => self.gs.miter = self.popn(), - "setdash" => { - let off = self.popn(); - let a: Vec = self.pop().items().unwrap_or_default().iter().filter_map(V::num).collect(); - self.gs.dash = (!a.is_empty() && a.iter().any(|v| *v > 0.0)).then_some((a, off)); - } - "setflat" | "setstrokeadjust" | "setoverprint" | "setrenderingintent" | "setcolorrendering" | "sethalftone" | "settransfer" => { - self.pop(); - } - // frequency angle proc - "setscreen" => { - for _ in 0..3 { - self.pop(); - } - } - "setgray" => { - let g = self.popn().clamp(0.0, 1.0); - self.gs.color = [g; 3]; - } - "setrgbcolor" => { - let b = self.popn(); - let g = self.popn(); - let r = self.popn(); - self.gs.color = [r, g, b].map(|v| v.clamp(0.0, 1.0)); - } - "sethsbcolor" => { - let v = self.popn().clamp(0.0, 1.0); - let s = self.popn().clamp(0.0, 1.0); - let h = self.popn().rem_euclid(1.0) * 6.0; - let (i, f) = (h.floor() as i32, h.fract()); - let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f))); - self.gs.color = match i { - 0 => [v, t, p], - 1 => [q, v, p], - 2 => [p, v, t], - 3 => [p, q, v], - 4 => [t, p, v], - _ => [v, p, q], - }; - } - "setcmykcolor" => { - let k = self.popn().clamp(0.0, 1.0); - let y = self.popn().clamp(0.0, 1.0); - let m = self.popn().clamp(0.0, 1.0); - let c = self.popn().clamp(0.0, 1.0); - self.gs.color = [(1.0 - c) * (1.0 - k), (1.0 - m) * (1.0 - k), (1.0 - y) * (1.0 - k)]; - } - "setcolorspace" => { - self.pop(); - } - "setcolor" => { - // Device colour by operand count (patterns are not drawn). - let k = self.st.iter().rev().take_while(|v| matches!(v, V::Num(_))).count().min(4); - let c: Vec = self.st.split_off(self.st.len() - k).iter().filter_map(V::num).collect(); - self.gs.color = match c.len() { - 1 => [c[0]; 3], - 3 => [c[0], c[1], c[2]], - 4 => [(1.0 - c[0]) * (1.0 - c[3]), (1.0 - c[1]) * (1.0 - c[3]), (1.0 - c[2]) * (1.0 - c[3])], - _ => self.gs.color, - }; - } - "currentgray" => self.push(V::Num((self.gs.color[0] + self.gs.color[1] + self.gs.color[2]) / 3.0)), - "currentrgbcolor" => { - for c in self.gs.color { - self.push(V::Num(c)); - } - } - _ => return Ok(false), - } - Ok(true) - } - - fn try_coordinate_op(&mut self, n: &str) -> bool { - match n { - // Coordinates. - "matrix" => self.push(matrix_val(Affine::IDENTITY)), - "identmatrix" | "defaultmatrix" => { - self.pop(); - self.push(matrix_val(Affine::IDENTITY)); - } - "currentmatrix" => { - self.pop(); - self.push(matrix_val(self.gs.ctm)); - } - "setmatrix" => { - let m = self.pop(); - self.gs.ctm = matrix_of(&m).unwrap_or(Affine::IDENTITY); - } - "concat" => { - let m = self.pop(); - if let Some(m) = matrix_of(&m) { - self.gs.ctm *= m; - } - } - "concatmatrix" => { - self.pop(); - let b = self.pop(); - let a = self.pop(); - let (a, b) = (matrix_of(&a).unwrap_or(Affine::IDENTITY), matrix_of(&b).unwrap_or(Affine::IDENTITY)); - self.push(matrix_val(b * a)); - } - "invertmatrix" => { - self.pop(); - let a = self.pop(); - self.push(matrix_val(matrix_of(&a).unwrap_or(Affine::IDENTITY).inverse())); - } - "translate" | "scale" => { - let top = self.pop(); - let (m_out, y) = match top { - V::Array(_) => (Some(top), self.popn()), - v => (None, v.num().unwrap_or(0.0)), - }; - let x = self.popn(); - let t = if n == "translate" { Affine::translate((x, y)) } else { Affine::scale_non_uniform(x, y) }; - match m_out { - Some(_) => self.push(matrix_val(t)), - None => self.gs.ctm *= t, - } - } - "rotate" => { - let top = self.pop(); - match top { - V::Array(_) => { - let a = self.popn(); - self.push(matrix_val(Affine::rotate(a.to_radians()))); - } - v => self.gs.ctm *= Affine::rotate(v.num().unwrap_or(0.0).to_radians()), - } - } - "transform" | "itransform" | "dtransform" | "idtransform" => { - let top = self.pop(); - let (m, y) = match top { - V::Array(_) | V::Proc(_) => (matrix_of(&top).unwrap_or(Affine::IDENTITY), self.popn()), - v => (self.gs.ctm, v.num().unwrap_or(0.0)), - }; - let x = self.popn(); - let m = if n.starts_with('i') { m.inverse() } else { m }; - let p = if n.contains('d') { - let c = m.as_coeffs(); - Point::new(c[0] * x + c[2] * y, c[1] * x + c[3] * y) - } else { - m * Point::new(x, y) - }; - self.push(V::Num(p.x)); - self.push(V::Num(p.y)); - } - _ => return false, - } - true - } - - fn try_path_op(&mut self, n: &str) -> Result { - match n { - // Paths. - "newpath" => { - self.gs.path = BezPath::new(); - self.gs.cur = None; - self.gs.start = None; - } - "moveto" => { - let p = self.user_point(); - self.move_to(p)?; - } - "rmoveto" => { - let d = self.user_point(); - let c = self.current_user(); - self.move_to(Point::new(c.x + d.x, c.y + d.y))?; - } - "lineto" => { - let p = self.user_point(); - self.line_to(p)?; - } - "rlineto" => { - let d = self.user_point(); - let c = self.current_user(); - self.line_to(Point::new(c.x + d.x, c.y + d.y))?; - } - "curveto" | "rcurveto" => { - let p3 = self.user_point(); - let p2 = self.user_point(); - let p1 = self.user_point(); - if n == "rcurveto" { - let c = self.current_user(); - let o = |p: Point| Point::new(c.x + p.x, c.y + p.y); - self.curve_to(o(p1), o(p2), o(p3))?; - } else { - self.curve_to(p1, p2, p3)?; - } - } - "closepath" => { - if self.gs.cur.is_some() { - self.room(1)?; - self.gs.path.close_path(); - self.gs.cur = self.gs.start; - } - } - "arc" => self.arc(false)?, - "arcn" => self.arc(true)?, - "currentpoint" => { - let c = self.current_user(); - self.push(V::Num(c.x)); - self.push(V::Num(c.y)); - } - "pathbbox" => { - self.spend(self.gs.path.elements().len())?; - let r = kurbo::Shape::bounding_box(&self.gs.path); - let inv = self.gs.ctm.inverse(); - let (a, b) = (inv * Point::new(r.x0, r.y0), inv * Point::new(r.x1, r.y1)); - for v in [a.x.min(b.x), a.y.min(b.y), a.x.max(b.x), a.y.max(b.y)] { - self.push(V::Num(v)); - } - } - "flattenpath" | "reversepath" | "strokepath" | "initclip" => {} - "clippath" => { - let p = self.page; - self.gs.path = kurbo::Shape::to_path(&kurbo::Rect::new(p[0], p[1], p[2], p[3]), 0.1); - } - _ => return Ok(false), - } - Ok(true) - } - - fn try_paint_op(&mut self, n: &str) -> Result { - match n { - // Painting. - "fill" => self.paint(Some(FillRule::NonZero), false), - "eofill" => self.paint(Some(FillRule::EvenOdd), false), - "stroke" => self.paint(None, true), - "clip" | "eoclip" => { - let rule = if n == "clip" { FillRule::NonZero } else { FillRule::EvenOdd }; - self.spend(self.gs.path.elements().len())?; - let p = self.gs.path.clone(); - if !p.elements().iter().all(|e| matches!(e, PathEl::MoveTo(_))) { - self.b.clip(p, rule); - } - } - "rectfill" | "rectstroke" | "rectclip" => { - let paths = self.rect_path()?; - if n == "rectstroke" && matches!(self.st.last(), Some(V::Array(_))) { - self.pop(); - } - let mut all = BezPath::new(); - for p in paths { - all.extend(p); - } - match n { - "rectclip" => self.b.clip(all, FillRule::NonZero), - _ => { - let saved = std::mem::replace(&mut self.gs.path, all); - self.paint(if n == "rectfill" { Some(FillRule::NonZero) } else { None }, n == "rectstroke"); - self.gs.path = saved; - } - } - } - "shfill" => { - self.pop(); - self.b.skip("smooth shading (shfill)"); - } - _ => return Ok(false), - } - Ok(true) - } -} diff --git a/crates/pdf/src/ps/eps.rs b/crates/pdf/src/ps/eps.rs deleted file mode 100644 index 8fb72698a..000000000 --- a/crates/pdf/src/ps/eps.rs +++ /dev/null @@ -1,120 +0,0 @@ -use super::{HashMap, Rc, is_white}; - -/// The PostScript section of an EPS file (DOS EPS binary header handled) and its bounding box -/// (`%%HiResBoundingBox` preferred). -pub fn eps_parts(bytes: &[u8]) -> Option<(&[u8], [f64; 4])> { - let ps = if bytes.starts_with(&[0xC5, 0xD0, 0xD3, 0xC6]) && bytes.len() >= 12 { - let off = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize; - let len = u32::from_le_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]) as usize; - bytes.get(off..off.checked_add(len)?.min(bytes.len()))? - } else { - bytes - }; - let find_box = |key: &[u8]| -> Option<[f64; 4]> { - let mut from = 0; - while let Some(p) = ps[from..].windows(key.len()).position(|w| w == key) { - let s = from + p + key.len(); - let e = ps[s..].iter().position(|c| matches!(c, b'\n' | b'\r')).map_or(ps.len(), |q| s + q); - let v: Vec = String::from_utf8_lossy(&ps[s..e]).split_whitespace().filter_map(|t| t.parse().ok()).collect(); - if v.len() == 4 && v[2] > v[0] && v[3] > v[1] { - return Some([v[0], v[1], v[2], v[3]]); - } - // A rejected comment is done with: the scan goes on past its line, not over it again. - from = e; - } - None - }; - let bbox = find_box(b"%%HiResBoundingBox:").or_else(|| find_box(b"%%BoundingBox:"))?; - Some((ps, bbox)) -} - -pub(super) fn find_from(hay: &[u8], needle: &[u8], from: usize) -> Option { - hay.get(from..)?.windows(needle.len()).position(|w| w == needle).map(|p| p + from) -} - -/// Every position of `needle` in `hay`, in order (one pass over the file). -fn positions(hay: &[u8], needle: &[u8]) -> Vec { - let mut out = vec![]; - let mut from = 0; - while let Some(p) = find_from(hay, needle, from) { - out.push(p); - from = p + needle.len(); - } - out -} - -/// The name after `key` (`/FontName /Name`). -fn name_after(b: &[u8], key: &[u8]) -> Option { - let p = find_from(b, key, 0)? + key.len(); - let rest = &b[p..]; - let s = rest.iter().position(|c| *c == b'/')? + 1; - let e = rest[s..].iter().position(|c| is_white(*c) || matches!(c, b'/' | b'[' | b'(' | b'{')).map_or(rest.len(), |q| s + q); - (e > s).then(|| String::from_utf8_lossy(&rest[s..e]).into_owned()) -} - -/// Embedded font programs of an EPS file: Type 1 fonts (`… /FontName /X … currentfile eexec -/// … cleartomark`, hexadecimal or binary) and CFF font sets (`… StartData `). -pub(super) fn embedded_fonts(ps: &[u8]) -> HashMap>, bool)> { - let mut out = HashMap::new(); - // The headers are found once, in one pass each; every `eexec` then takes the last header - // before it that no earlier `eexec` has used, so no prefix of the file is searched again. - let mut heads = positions(ps, b"%!PS-AdobeFont"); - heads.extend(positions(ps, b"%!FontType1")); - heads.sort_unstable(); - let names = positions(ps, b"/FontName"); - let mut from = 0; - let mut used = 0; - while let Some(ee) = find_from(ps, b"eexec", from) { - from = ee + 5; - let last_before = |v: &[usize]| v[..v.partition_point(|&p| p < ee)].last().copied().filter(|&p| p >= used); - // The fallback look-back stops at the previous font's end, so it cannot pick up its header. - let start = last_before(&heads).or_else(|| last_before(&names).map(|p| p.saturating_sub(512).max(used))); - let Some(start) = start else { continue }; - let end = find_from(ps, b"cleartomark", ee).map_or(ps.len(), |p| p + 11); - if let Some(name) = name_after(&ps[start..ee], b"/FontName") { - out.insert(name, (Rc::new(ps[start..end].to_vec()), false)); - } - from = end; - used = end; - } - let mut from = 0; - while let Some(sd) = find_from(ps, b"StartData", from) { - from = sd + 9; - let head = String::from_utf8_lossy(&ps[sd.saturating_sub(64)..sd]).into_owned(); - let Some(len) = head.split_whitespace().last().and_then(|t| t.parse::().ok()) else { continue }; - let s = sd + 10; - let Some(data) = ps.get(s..s.saturating_add(len)) else { continue }; - if let Some(name) = crate::cff::font_name(data) { - out.insert(name, (Rc::new(data.to_vec()), true)); - } - from = s + len; - } - out -} - -#[cfg(test)] -mod tests { - use super::embedded_fonts; - - #[test] - fn font_discovery_looks_back_once_per_header() { - // 20,000 `eexec` words before any font header: each used to search the whole prefix - // for a header again. The font after them is still found. - let mut ps = b"%!PS-Adobe-3.0 EPSF-3.0\n".to_vec(); - ps.extend_from_slice("eexec ".repeat(20_000).as_bytes()); - ps.extend_from_slice(b"\n%!PS-AdobeFont-1.0: Real\n/FontName /Real def\ncurrentfile eexec\n0000\ncleartomark\n"); - let fonts = embedded_fonts(&ps); - assert_eq!(fonts.len(), 1); - assert!(fonts.contains_key("Real")); - } - - #[test] - fn header_less_font_after_a_short_one_does_not_take_its_header() { - let a = "%!PS-AdobeFont-1.0: A\n/FontName /A def\ncurrentfile eexec\n0000\ncleartomark\n"; - let b = "/FontName /B def\ncurrentfile eexec\n0000\ncleartomark\n"; - let ps = format!("%!PS-Adobe-3.0 EPSF-3.0\n{a}{b}"); - let fonts = embedded_fonts(ps.as_bytes()); - let (data, _) = fonts.get("B").expect("second font found"); - assert!(!String::from_utf8_lossy(data).contains("AdobeFont"), "{}", String::from_utf8_lossy(data)); - } -} diff --git a/crates/pdf/src/ps/exec.rs b/crates/pdf/src/ps/exec.rs deleted file mode 100644 index 233ff82b0..000000000 --- a/crates/pdf/src/ps/exec.rs +++ /dev/null @@ -1,182 +0,0 @@ -use super::eps::embedded_fonts; -use super::scanner::Src; -use super::value::{Flow, GState, V, new_dict}; -use super::{Affine, BezPath, Builder, Cap, HashMap, Interp, Join}; - -/// The deepest procedure nesting run (deeper recursion stops the program). -const MAX_CALL_DEPTH: usize = 256; - -/// The most values the operand stack holds: a push past it is dropped, and `copy` copies -/// nothing rather than grow the stack past it. -pub(super) const MAX_STACK: usize = 100_000; - -impl Interp { - pub fn new(page: [f64; 4]) -> Interp { - Interp { - b: Builder::new(), - st: vec![], - dicts: vec![new_dict()], - gs: GState { - ctm: Affine::IDENTITY, - color: [0.0; 3], - lw: 1.0, - cap: Cap::Butt, - join: Join::Miter, - miter: 10.0, - dash: None, - path: BezPath::new(), - cur: None, - start: None, - depth: 1, - font: None, - }, - saved: vec![], - budget: 8_000_000, - calls: 0, - font_dir: HashMap::new(), - embedded: HashMap::new(), - font_cache: HashMap::new(), - page, - unknown: vec![], - } - } - - pub fn run(&mut self, data: &[u8]) { - self.embedded = embedded_fonts(data); - let mut src = Src { d: data, pos: 0 }; - while let Some(t) = src.token(0) { - if let Err(Flow::Quit) = self.exec_token(t, &mut src) { - break; - } - } - } - - pub(super) fn pop(&mut self) -> V { - self.st.pop().unwrap_or(V::Null) - } - - pub(super) fn popn(&mut self) -> f64 { - self.pop().num().unwrap_or(0.0) - } - - pub(super) fn push(&mut self, v: V) { - if self.st.len() < MAX_STACK { - self.st.push(v); - } - } - - /// Count `n` units of work (values copied, storage allocated) against the budget without - /// stopping the program here: once it is spent, the next operator stops it. - pub(super) fn charge(&mut self, n: usize) { - self.budget = self.budget.saturating_sub(n); - } - - pub(super) fn lookup(&self, k: &str) -> Option { - self.dicts.iter().rev().find_map(|d| d.borrow().get(k).cloned()) - } - - /// A token read from the file: procedures are pushed, names executed. - fn exec_token(&mut self, t: V, src: &mut Src) -> Result<(), Flow> { - match t { - V::Name(n) => self.exec_name(&n, src), - other => { - self.push(other); - Ok(()) - } - } - } - - /// Execute a value as an object (procedures run). - pub(super) fn exec_obj(&mut self, v: V, src: &mut Src) -> Result<(), Flow> { - match v { - V::Proc(p) => { - if self.calls >= MAX_CALL_DEPTH { - self.b.skip("PostScript (recursion limit)"); - return Err(Flow::Quit); - } - self.calls += 1; - let mut r = Ok(()); - for x in p.iter() { - match x { - V::Name(n) => { - r = self.exec_name(n, src); - if r.is_err() { - break; - } - } - V::Op(op) => { - r = self.spend(1).and_then(|()| self.builtin(op, src)); - if r.is_err() { - break; - } - } - // Other items count against the budget as names do. - other => { - r = self.spend(1); - if r.is_err() { - break; - } - self.push(other.clone()); - } - } - } - self.calls -= 1; - r - } - // An executable name can run another (`exec` of `/exec cvx`), so names count too. - V::Name(n) => { - if self.calls >= MAX_CALL_DEPTH { - self.b.skip("PostScript (recursion limit)"); - return Err(Flow::Quit); - } - self.calls += 1; - let r = self.exec_name(&n, src); - self.calls -= 1; - r - } - V::Op(op) => { - self.spend(1)?; - self.builtin(&op, src) - } - other => { - self.push(other); - Ok(()) - } - } - } - - fn exec_name(&mut self, n: &str, src: &mut Src) -> Result<(), Flow> { - self.spend(1)?; - if let Some(v) = self.lookup(n) { - return match v { - V::Proc(_) => self.exec_obj(v, src), - // An operator stored under another name (`/mo /moveto load def`, as Illustrator's - // EPS prolog does for every path operator) runs that operator. It pushed the - // operator's name instead, so such files drew nothing (#955). - V::Op(op) => self.builtin(&op, src), - // An executable name (`/y /x cvx def`) runs what that name is bound to. - V::Name(_) => self.exec_obj(v, src), - other => { - self.push(other); - Ok(()) - } - }; - } - self.builtin(n, src) - } - - /// Count `n` operations against the budget, and stop the program when fewer are left. An - /// operator that makes, reads or copies path elements counts each one as an operation. - pub(super) fn spend(&mut self, n: usize) -> Result<(), Flow> { - match self.budget.checked_sub(n) { - Some(left) => { - self.budget = left; - Ok(()) - } - None => { - self.b.skip("PostScript (operation limit)"); - Err(Flow::Quit) - } - } - } -} diff --git a/crates/pdf/src/ps/paths.rs b/crates/pdf/src/ps/paths.rs deleted file mode 100644 index 30b5a7087..000000000 --- a/crates/pdf/src/ps/paths.rs +++ /dev/null @@ -1,187 +0,0 @@ -use super::value::{Flow, V}; -use super::{Affine, BezPath, FillRule, Interp, MAX_PATH, Paint, PathEl, Point, Stroke}; - -/// The angle from `a` counterclockwise to `b` (degrees, 0 to 360), worked out from what is left -/// of each after whole turns. -fn ccw_turn(a: f64, b: f64) -> f64 { - (b % 360.0 - a % 360.0).rem_euclid(360.0) -} - -/// The most turns one `arc` or `arcn` draws. -const MAX_ARC_TURNS: f64 = 1024.0; - -impl Interp { - fn device_scale(&self) -> f64 { - self.gs.ctm.determinant().abs().sqrt() - } - - pub(super) fn user_point(&mut self) -> Point { - let y = self.popn(); - let x = self.popn(); - Point::new(x, y) - } - - /// Stop the program when a path of `len` elements would be longer than [`MAX_PATH`]. - pub(super) fn path_fits(&mut self, len: usize) -> Result<(), Flow> { - if len <= MAX_PATH { - return Ok(()); - } - self.b.skip("PostScript (path limit)"); - Err(Flow::Quit) - } - - /// [`Self::path_fits`] for the current path with `n` more elements. - pub(super) fn room(&mut self, n: usize) -> Result<(), Flow> { - self.path_fits(self.gs.path.elements().len().saturating_add(n)) - } - - pub(super) fn move_to(&mut self, p: Point) -> Result<(), Flow> { - // A moveto right after a moveto replaces it (PostScript Language Reference §8.2, `moveto`). - if matches!(self.gs.path.elements().last(), Some(PathEl::MoveTo(_))) { - self.gs.path.pop(); - } - self.room(1)?; - let q = self.gs.ctm * p; - self.gs.path.move_to(q); - self.gs.cur = Some(q); - self.gs.start = Some(q); - Ok(()) - } - - pub(super) fn line_to(&mut self, p: Point) -> Result<(), Flow> { - self.room(1 + usize::from(self.gs.cur.is_none()))?; - let q = self.gs.ctm * p; - if self.gs.cur.is_none() { - self.gs.path.move_to(q); - self.gs.start = Some(q); - } - self.gs.path.line_to(q); - self.gs.cur = Some(q); - Ok(()) - } - - pub(super) fn curve_to(&mut self, a: Point, b: Point, c: Point) -> Result<(), Flow> { - self.room(1 + usize::from(self.gs.cur.is_none()))?; - let m = self.gs.ctm; - if self.gs.cur.is_none() { - self.gs.path.move_to(m * a); - } - self.gs.path.curve_to(m * a, m * b, m * c); - self.gs.cur = Some(m * c); - Ok(()) - } - - pub(super) fn current_user(&self) -> Point { - self.gs.ctm.inverse() * self.gs.cur.unwrap_or_default() - } - - pub(super) fn arc(&mut self, neg: bool) -> Result<(), Flow> { - let a2 = self.popn(); - let a1 = self.popn(); - let r = self.popn(); - let c = self.user_point(); - // `arc` raises `a2` by multiples of 360 until it is at least `a1`, and `arcn` lowers it - // until it is at most `a1` (PostScript Language Reference §8.2, `arc` and `arcn`). Those - // sweeps, and the first endpoint, are worked out from what is left of each angle after - // whole turns. - let sweep = if !neg && a2 < a1 { - ccw_turn(a1, a2) - } else if neg && a2 > a1 { - -ccw_turn(a2, a1) - } else { - a2 - a1 - }; - // A sweep of more than `MAX_ARC_TURNS` turns is shortened by whole pairs of turns to - // between `MAX_ARC_TURNS - 2` and `MAX_ARC_TURNS` turns, with a skip note. The arc still - // ends at `a2`, and an even-odd fill or clip of it covers the same area as the full sweep. - let max = MAX_ARC_TURNS * 360.0; - let sweep = if sweep.abs() > max { - self.b.skip("arc (too many turns)"); - let s = sweep.signum(); - s * (max - 720.0 + (s * (a2 % 720.0 - a1 % 720.0)).rem_euclid(720.0)) - } else { - sweep - }; - let (a1, sweep) = ((a1 % 360.0).to_radians(), sweep.to_radians()); - let start = Point::new(c.x + r * a1.cos(), c.y + r * a1.sin()); - if self.gs.cur.is_some() { - self.line_to(start)?; - } else { - self.move_to(start)?; - } - let arc = kurbo::Arc::new(c, (r, r), a1, sweep, 0.0); - let m = self.gs.ctm; - // kurbo divides an arc into more curves the larger the radius (about 3.7 × 10^49 for a - // quarter turn at a radius of 10^300, more than a usize can count), so each one counts - // against the budget and the path limit. - let mut curves = arc.append_iter(0.1); - while let Some(PathEl::CurveTo(p1, p2, p3)) = curves.next() { - self.room(1)?; - self.spend(1)?; - self.gs.path.curve_to(m * p1, m * p2, m * p3); - self.gs.cur = Some(m * p3); - } - Ok(()) - } - - pub(super) fn paint(&mut self, fill: Option, stroke: bool) { - let path = std::mem::take(&mut self.gs.path); - self.gs.cur = None; - self.gs.start = None; - let s = self.device_scale(); - let st = stroke.then(|| Stroke { - paint: Paint::Color(self.gs.color), - opacity: 1.0, - width: if self.gs.lw <= 0.0 { 1.0 } else { self.gs.lw * s }, - cap: self.gs.cap, - join: self.gs.join, - miter: self.gs.miter.max(1.0), - dash: self.gs.dash.as_ref().map(|(a, o)| (a.iter().map(|v| v * s).collect(), o * s)), - }); - self.b.fill_stroke(path, Affine::IDENTITY, fill.map(|r| (Paint::Color(self.gs.color), 1.0, r)), st); - } - - pub(super) fn rect_path(&mut self) -> Result, Flow> { - // x y w h, or an array / string of numbers. - let top = self.pop(); - let nums: Vec = match &top { - V::Array(_) | V::Proc(_) => { - let items = top.items().unwrap_or_default(); - // An array's rectangles count against the budget, five path elements each. - self.spend(items.len() / 4 * 5)?; - items.iter().filter_map(V::num).collect() - } - V::Num(h) => { - let w = self.popn(); - let y = self.popn(); - let x = self.popn(); - vec![x, y, w, *h] - } - _ => vec![], - }; - self.path_fits(nums.len() / 4 * 5)?; - let m = self.gs.ctm; - Ok(nums - .as_chunks::<4>() - .0 - .iter() - .map(|r| { - let mut p = BezPath::new(); - p.move_to(m * Point::new(r[0], r[1])); - p.line_to(m * Point::new(r[0] + r[2], r[1])); - p.line_to(m * Point::new(r[0] + r[2], r[1] + r[3])); - p.line_to(m * Point::new(r[0], r[1] + r[3])); - p.close_path(); - p - }) - .collect()) - } - - pub(super) fn grestore(&mut self) { - if let Some(g) = self.saved.pop() { - let d = g.depth; - self.gs = g; - self.b.close_to(d); - } - } -} diff --git a/crates/pdf/src/ps/scanner.rs b/crates/pdf/src/ps/scanner.rs deleted file mode 100644 index 59933e214..000000000 --- a/crates/pdf/src/ps/scanner.rs +++ /dev/null @@ -1,223 +0,0 @@ -use super::value::V; -use super::{Rc, RefCell, ascii85, is_white, parse_num}; - -/// Source tokenizer (the data source for `currentfile`). -pub(super) struct Src<'a> { - pub(super) d: &'a [u8], - pub(crate) pos: usize, -} - -impl Src<'_> { - fn skip_ws(&mut self) { - while self.pos < self.d.len() { - let c = self.d[self.pos]; - if is_white(c) { - self.pos += 1; - } else if c == b'%' { - let s = self.pos; - while self.pos < self.d.len() && !matches!(self.d[self.pos], b'\n' | b'\r') { - self.pos += 1; - } - // DSC: skip embedded binary / data sections. - let line = &self.d[s..self.pos]; - if line.starts_with(b"%%BeginData:") || line.starts_with(b"%%BeginBinary:") || line.starts_with(b"%%BeginPreview") { - let end: &[u8] = if line.starts_with(b"%%BeginData:") { - b"%%EndData" - } else if line.starts_with(b"%%BeginBinary:") { - b"%%EndBinary" - } else { - b"%%EndPreview" - }; - match self.d[self.pos..].windows(end.len()).position(|w| w == end) { - Some(p) => self.pos += p, - None => self.pos = self.d.len(), - } - } - } else { - break; - } - } - } - - fn word(&mut self) -> &[u8] { - let s = self.pos; - while self.pos < self.d.len() { - let c = self.d[self.pos]; - if is_white(c) || matches!(c, b'(' | b')' | b'<' | b'>' | b'[' | b']' | b'{' | b'}' | b'/' | b'%') { - break; - } - self.pos += 1; - } - &self.d[s..self.pos] - } - - /// The next token; `{ … }` comes back as a whole procedure. - pub(super) fn token(&mut self, depth: usize) -> Option { - self.skip_ws(); - let c = *self.d.get(self.pos)?; - Some(match c { - b'{' => { - self.pos += 1; - let mut body = vec![]; - loop { - self.skip_ws(); - match self.d.get(self.pos) { - None => break, - Some(b'}') => { - self.pos += 1; - break; - } - _ => { - if depth > 100 { - return None; - } - match self.token(depth + 1) { - Some(t) => body.push(t), - None => break, - } - } - } - } - V::Proc(Rc::new(body)) - } - b'}' => { - self.pos += 1; - V::Null - } - b'/' => { - self.pos += 1; - let imm = self.d.get(self.pos) == Some(&b'/'); - if imm { - self.pos += 1; - } - let w = String::from_utf8_lossy(self.word()).into_owned(); - // `//name` (immediately evaluated) is treated like a plain name. - if imm { V::Name(w.into()) } else { V::Lit(w.into()) } - } - b'(' => { - self.pos += 1; - let mut out = vec![]; - let mut depth = 1; - while self.pos < self.d.len() { - let c = self.d[self.pos]; - self.pos += 1; - match c { - b'\\' => { - let e = self.d.get(self.pos).copied().unwrap_or(b'\\'); - self.pos += 1; - match e { - b'n' => out.push(b'\n'), - b'r' => out.push(b'\r'), - b't' => out.push(b'\t'), - b'0'..=b'7' => { - let mut v = (e - b'0') as u32; - for _ in 0..2 { - match self.d.get(self.pos) { - Some(d @ b'0'..=b'7') => { - v = v * 8 + (d - b'0') as u32; - self.pos += 1; - } - _ => break, - } - } - out.push(v as u8); - } - b'\n' | b'\r' => {} - o => out.push(o), - } - } - b'(' => { - depth += 1; - out.push(c); - } - b')' => { - depth -= 1; - if depth == 0 { - break; - } - out.push(c); - } - _ => out.push(c), - } - } - V::Str(Rc::new(RefCell::new(out))) - } - b'<' if self.d.get(self.pos + 1) == Some(&b'<') => { - self.pos += 2; - V::Name("<<".into()) - } - b'>' if self.d.get(self.pos + 1) == Some(&b'>') => { - self.pos += 2; - V::Name(">>".into()) - } - b'<' if self.d.get(self.pos + 1) == Some(&b'~') => { - let s = self.pos; - while self.pos + 1 < self.d.len() && !(self.d[self.pos] == b'~' && self.d[self.pos + 1] == b'>') { - self.pos += 1; - } - self.pos = (self.pos + 2).min(self.d.len()); - V::Str(Rc::new(RefCell::new(ascii85(&self.d[s..self.pos])))) - } - b'<' => { - self.pos += 1; - let mut hex = vec![]; - while self.pos < self.d.len() && self.d[self.pos] != b'>' { - if self.d[self.pos].is_ascii_hexdigit() { - hex.push(self.d[self.pos]); - } - self.pos += 1; - } - self.pos += 1; - if hex.len() % 2 == 1 { - hex.push(b'0'); - } - let h = |c: u8| (c as char).to_digit(16).unwrap_or(0) as u8; - V::Str(Rc::new(RefCell::new(hex.chunks(2).map(|p| (h(p[0]) << 4) | h(p[1])).collect()))) - } - b'[' | b']' => { - self.pos += 1; - V::Name(if c == b'[' { "[" } else { "]" }.into()) - } - b')' | b'>' => { - self.pos += 1; - V::Null - } - _ => { - let w = self.word(); - if w.is_empty() { - self.pos += 1; - return Some(V::Null); - } - match parse_num(w) { - Some(n) => V::Num(n), - None => { - // Radix numbers (16#FF). - let s = String::from_utf8_lossy(w).into_owned(); - match s.split_once('#').and_then(|(r, v)| i64::from_str_radix(v, r.parse::().ok().filter(|r| (2..=36).contains(r))?).ok()) { - Some(n) => V::Num(n as f64), - None => V::Name(s.into()), - } - } - } - } - }) - } - - /// Step over inline image data that follows an `image` operator reading `currentfile`. - pub(super) fn skip_image_data(&mut self) { - self.skip_ws(); - if self.d[self.pos..].starts_with(b"<~") || self.d.get(self.pos).is_some_and(|c| (b'!'..=b'u').contains(c) && !c.is_ascii_hexdigit()) { - match self.d[self.pos..].windows(2).position(|w| w == b"~>") { - Some(p) => self.pos += p + 2, - None => self.pos = self.d.len(), - } - return; - } - while self.pos < self.d.len() && (self.d[self.pos].is_ascii_hexdigit() || is_white(self.d[self.pos])) { - self.pos += 1; - } - if self.d.get(self.pos) == Some(&b'>') { - self.pos += 1; - } - } -} diff --git a/crates/pdf/src/ps/text.rs b/crates/pdf/src/ps/text.rs deleted file mode 100644 index d4cee07f8..000000000 --- a/crates/pdf/src/ps/text.rs +++ /dev/null @@ -1,329 +0,0 @@ -use super::scanner::Src; -use super::value::{DictRef, Flow, V, array, matrix_of, matrix_val, new_dict}; -use super::{Affine, BezPath, FillRule, Font, HashMap, Interp, Paint, Point, Rc, RefCell}; - -// ------------------------------------------------------------------ text - -/// An encoding array of glyph names (`StandardEncoding`; `ISOLatin1Encoding` and others are -/// approximated by WinAnsi, which agrees with ISO Latin-1 on the printable codes). -pub(super) fn encoding_array(name: &str) -> V { - let base = if name == "StandardEncoding" { crate::encoding::Base::Standard } else { crate::encoding::Base::WinAnsi }; - array((0..256).map(|c| V::Lit(base.name(c as u8).unwrap_or_else(|| ".notdef".into()).into())).collect()) -} - -fn dict_matrix(d: &DictRef, key: &str) -> Affine { - d.borrow().get(key).and_then(matrix_of).unwrap_or(Affine::IDENTITY) -} - -/// A copy of a font dictionary with `m` applied after its matrix (`scalefont`, `makefont`). -fn transformed(font: &DictRef, m: Affine) -> DictRef { - let copy: HashMap = font.borrow().clone(); - let d = Rc::new(RefCell::new(copy)); - let old = dict_matrix(&d, "__m"); - d.borrow_mut().insert("__m".into(), matrix_val(m * old)); - d -} - -impl Interp { - /// A font dictionary by name: one `definefont` made, else a new dictionary for an - /// embedded program or a bundled stand-in. - pub(super) fn find_font(&mut self, key: &str) -> DictRef { - if let Some(d) = self.font_dir.get(key) { - return d.clone(); - } - let d = new_dict(); - { - let mut m = d.borrow_mut(); - m.insert("FontName".into(), V::Lit(key.into())); - m.insert("FontType".into(), V::Num(1.0)); - m.insert("FontMatrix".into(), matrix_val(Affine::scale(0.001))); - m.insert("FID".into(), V::Null); - m.insert("__base".into(), V::Lit(key.into())); - m.insert("__m".into(), matrix_val(Affine::IDENTITY)); - } - self.font_dir.insert(key.to_string(), d.clone()); - d - } - - /// The drawable font of a font dictionary (its base program and encoding) and the matrix - /// from text space (font size 1) to user space. - fn font_of(&mut self, d: &DictRef) -> Option<(Rc, Affine)> { - if matches!(d.borrow().get("FontType"), Some(V::Num(t)) if *t == 3.0) { - // Type 3 fonts (glyph procedures) are not run. - self.b.skip("EPS Type 3 font"); - return None; - } - let (base, names) = { - let m = d.borrow(); - let base = m.get("__base").or_else(|| m.get("FontName")).map(V::key)?; - let names: Option>> = m.get("Encoding").and_then(V::items).map(|a| { - a.iter() - .map(|v| match v { - V::Lit(n) | V::Name(n) if &**n != ".notdef" => Some(n.to_string()), - _ => None, - }) - .collect() - }); - (base, names) - }; - let key = match &names { - Some(n) => format!("{base}\u{0}{}", n.iter().map(|x| x.as_deref().unwrap_or("")).collect::>().join(" ")), - None => base.clone(), - }; - let font = match self.font_cache.get(&key) { - Some(f) => f.clone(), - None => { - // Not embedded: a bundled stand-in, as for PDF. - let prog = self.embedded.get(&base).cloned(); - let f = Rc::new(Font::standalone(&base, prog.as_ref().map(|(d, cff)| (d.as_slice(), *cff)), names)); - self.font_cache.insert(key, f.clone()); - f - } - }; - Some((font, dict_matrix(d, "__m"))) - } - - /// A string's glyph outlines (device space) from the current point, with an extra - /// displacement `extra(index, code)` (user space) after each glyph; moves the current - /// point. - fn text_path(&mut self, bytes: &[u8], mut extra: impl FnMut(usize, u32) -> (f64, f64)) -> Result, Flow> { - let Some(d) = self.gs.font.clone() else { return Ok(None) }; - let Some((font, m)) = self.font_of(&d) else { return Ok(None) }; - let mut p = self.current_user(); - let mut path = BezPath::new(); - let mut text = String::new(); - let ctm = self.gs.ctm; - for (i, &code) in bytes.iter().enumerate() { - let code = code as u32; - // Every input character costs at least one unit, so empty outlines are not free. - self.spend(1)?; - if let Some(g) = font.glyph(code) { - // Each outline element counts against the path limit and the budget before it - // is copied, so a long string cannot expand into unbounded geometry. - let n = g.elements().len(); - self.path_fits(path.elements().len().saturating_add(n))?; - self.spend(n)?; - path.extend(ctm * Affine::translate(p.to_vec2()) * m * (*g).clone()); - } - text.push_str(&font.unicode(code)); - let adv = m * Point::new(font.width(code), 0.0) - m * Point::ZERO; - let (ex, ey) = extra(i, code); - p += adv + kurbo::Vec2::new(ex, ey); - } - self.move_to(p)?; - Ok(Some((path, text))) - } - - fn fill_text(&mut self, path: BezPath, text: &str) { - let label: String = text.chars().filter(|c| !c.is_control()).take(40).collect(); - let name = if label.trim().is_empty() { "Text".to_string() } else { format!("Text: {}", label.trim()) }; - self.b.fill_stroke_named(&name, path, Affine::IDENTITY, Some((Paint::Color(self.gs.color), 1.0, FillRule::NonZero)), None); - } - - fn pop_string(&mut self) -> Vec { - match self.pop() { - V::Str(s) => s.borrow().clone(), - _ => vec![], - } - } - - fn show_with(&mut self, s: &[u8], extra: impl FnMut(usize, u32) -> (f64, f64)) -> Result<(), Flow> { - match self.text_path(s, extra)? { - Some((path, text)) => self.fill_text(path, &text), - None => self.b.skip("text (no font)"), - } - Ok(()) - } - - /// Text and font operators (PostScript Language Reference §5.1, §8.2). - pub(super) fn text_op(&mut self, n: &str, src: &mut Src) -> Result<(), Flow> { - match n { - "scalefont" | "makefont" => { - let m = if n == "scalefont" { - Affine::scale(self.popn()) - } else { - let v = self.pop(); - matrix_of(&v).unwrap_or(Affine::IDENTITY) - }; - let font = match self.pop() { - V::Dict(d) => d, - _ => self.find_font("Helvetica"), - }; - self.push(V::Dict(transformed(&font, m))); - } - "selectfont" => { - let size = self.pop(); - let key = self.pop().key(); - let font = self.find_font(&key); - let m = match &size { - V::Num(s) => Affine::scale(*s), - other => matrix_of(other).unwrap_or(Affine::IDENTITY), - }; - self.gs.font = Some(transformed(&font, m)); - } - "setfont" => { - if let V::Dict(d) = self.pop() { - self.gs.font = Some(d); - } - } - "currentfont" | "rootfont" => { - let d = self.gs.font.clone().unwrap_or_else(new_dict); - self.push(V::Dict(d)); - } - "definefont" => { - let v = self.pop(); - let key = self.pop().key(); - if let V::Dict(d) = &v { - if !d.borrow().contains_key("__base") { - // A font the file defines itself: its embedded program, by name. - d.borrow_mut().insert("__base".into(), V::Lit(key.as_str().into())); - d.borrow_mut().insert("__m".into(), matrix_val(Affine::IDENTITY)); - } - self.font_dir.insert(key, d.clone()); - } - self.push(v); - } - "undefinefont" => { - let key = self.pop().key(); - self.font_dir.remove(&key); - } - "StandardEncoding" | "ISOLatin1Encoding" => self.push(encoding_array(n)), - "show" => { - let s = self.pop_string(); - self.show_with(&s, |_, _| (0.0, 0.0))?; - } - "ashow" => { - let s = self.pop_string(); - let ay = self.popn(); - let ax = self.popn(); - self.show_with(&s, |_, _| (ax, ay))?; - } - "widthshow" => { - let s = self.pop_string(); - let ch = self.popn() as u32; - let cy = self.popn(); - let cx = self.popn(); - self.show_with(&s, |_, c| if c == ch { (cx, cy) } else { (0.0, 0.0) })?; - } - "awidthshow" => { - let s = self.pop_string(); - let ay = self.popn(); - let ax = self.popn(); - let ch = self.popn() as u32; - let cy = self.popn(); - let cx = self.popn(); - self.show_with(&s, |_, c| if c == ch { (cx + ax, cy + ay) } else { (ax, ay) })?; - } - "kshow" | "cshow" => { - // The procedure between characters is not run. - let s = self.pop_string(); - self.pop(); - self.show_with(&s, |_, _| (0.0, 0.0))?; - } - "xshow" | "yshow" | "xyshow" => { - let disp: Vec = self.pop().items().unwrap_or_default().iter().filter_map(V::num).collect(); - let s = self.pop_string(); - self.explicit_show(&s, &disp, n)?; - } - "glyphshow" => { - let name = self.pop().key(); - let Some(d) = self.gs.font.clone() else { return Ok(()) }; - // Drawn through a one-glyph encoding. - let mut e: Vec = (0..256).map(|_| V::Lit(".notdef".into())).collect(); - e[65] = V::Lit(name.as_str().into()); - let tmp = transformed(&d, Affine::IDENTITY); - tmp.borrow_mut().insert("Encoding".into(), array(e)); - self.gs.font = Some(tmp); - self.show_with(b"A", |_, _| (0.0, 0.0))?; - self.gs.font = Some(d); - } - "charpath" => { - self.pop(); - let s = self.pop_string(); - let saved = std::mem::take(&mut self.gs.path); - let start = self.gs.start; - match self.text_path(&s, |_, _| (0.0, 0.0))? { - Some((glyphs, _)) => { - // The outlines join the path: each element counts against the budget and - // the path limit. - self.gs.path = saved; - self.room(glyphs.elements().len() + 1)?; - self.spend(glyphs.elements().len())?; - self.gs.path.extend(glyphs); - if let Some(c) = self.gs.cur { - self.gs.path.move_to(c); - } - self.gs.start = start; - } - None => self.gs.path = saved, - } - } - "stringwidth" => { - let s = self.pop_string(); - let (mut w, mut h) = (0.0, 0.0); - if let Some(d) = self.gs.font.clone() - && let Some((font, m)) = self.font_of(&d) - { - for &c in &s { - let v = m * Point::new(font.width(c as u32), 0.0) - m * Point::ZERO; - w += v.x; - h += v.y; - } - } - self.push(V::Num(w)); - self.push(V::Num(h)); - } - "setcachedevice" => { - for _ in 0..6 { - self.pop(); - } - } - "setcharwidth" => { - self.pop(); - self.pop(); - } - // An embedded Type 1 program's encrypted part (read by `embedded_fonts`). - "eexec" => { - if matches!(self.pop(), V::File) { - let rest = &src.d[src.pos.min(src.d.len())..]; - src.pos += rest.windows(11).position(|w| w == b"cleartomark").map_or(rest.len(), |p| p + 11); - } - } - // A CFF font set's binary data (read by `embedded_fonts`). - "StartData" => { - let len = self.popn().max(0.0) as usize; - self.pop(); - src.pos = src.pos.saturating_add(1).saturating_add(len).min(src.d.len()); - } - _ => {} - } - Ok(()) - } - - /// `xshow` / `yshow` / `xyshow`: glyph displacements from a number array instead of the - /// advances. - fn explicit_show(&mut self, s: &[u8], disp: &[f64], n: &str) -> Result<(), Flow> { - let step = if n == "xyshow" { 2 } else { 1 }; - let d: Vec<(f64, f64)> = (0..s.len()) - .map(|k| { - let i = k * step; - let v = |j: usize| disp.get(j).copied().unwrap_or(0.0); - match n { - "xshow" => (v(i), 0.0), - "yshow" => (0.0, v(i)), - _ => (v(i), v(i + 1)), - } - }) - .collect(); - let Some(fd) = self.gs.font.clone() else { - self.b.skip("text (no font)"); - return Ok(()); - }; - let Some((font, m)) = self.font_of(&fd) else { return Ok(()) }; - self.show_with(s, move |k, c| { - let adv = m * Point::new(font.width(c), 0.0) - m * Point::ZERO; - let (dx, dy) = d.get(k).copied().unwrap_or((0.0, 0.0)); - (dx - adv.x, dy - adv.y) - }) - } -} diff --git a/crates/pdf/src/ps/value.rs b/crates/pdf/src/ps/value.rs deleted file mode 100644 index 3cfafed6e..000000000 --- a/crates/pdf/src/ps/value.rs +++ /dev/null @@ -1,88 +0,0 @@ -use super::{Affine, BezPath, Cap, HashMap, Join, Point, Rc, RefCell}; - -pub(crate) type DictRef = Rc>>; - -#[derive(Clone)] -pub(crate) enum V { - Num(f64), - Bool(bool), - /// An executable name. - Name(Rc), - /// A literal name (`/name`). - Lit(Rc), - /// A built-in operator, as `load` returns it for a name no dictionary defines. - Op(Rc), - Str(Rc>>), - Proc(Rc>), - Array(Rc>>), - Dict(DictRef), - Mark, - Null, - /// `currentfile`. - File, -} - -impl V { - pub(super) fn num(&self) -> Option { - match self { - V::Num(n) => Some(*n), - _ => None, - } - } - pub(super) fn key(&self) -> String { - match self { - V::Name(n) | V::Lit(n) | V::Op(n) => n.to_string(), - V::Str(s) => String::from_utf8_lossy(&s.borrow()).into_owned(), - V::Num(n) => format!("{n}"), - V::Bool(b) => format!("{b}"), - _ => String::new(), - } - } - pub(super) fn items(&self) -> Option> { - match self { - V::Array(a) => Some(a.borrow().clone()), - V::Proc(p) => Some(p.as_ref().clone()), - _ => None, - } - } -} - -pub(super) enum Flow { - Exit, - Stop, - Quit, -} - -#[derive(Clone)] -pub(super) struct GState { - pub(crate) ctm: Affine, - pub(crate) color: [f64; 3], - pub(crate) lw: f64, - pub(crate) cap: Cap, - pub(crate) join: Join, - pub(crate) miter: f64, - pub(crate) dash: Option<(Vec, f64)>, - pub(crate) path: BezPath, - pub(crate) cur: Option, - pub(crate) start: Option, - pub(crate) depth: usize, - /// The current font dictionary. - pub(crate) font: Option, -} - -pub(super) fn new_dict() -> DictRef { - Rc::new(RefCell::new(HashMap::new())) -} - -pub(super) fn array(v: Vec) -> V { - V::Array(Rc::new(RefCell::new(v))) -} - -pub(super) fn matrix_of(v: &V) -> Option { - let a: Vec = v.items()?.iter().filter_map(V::num).collect(); - (a.len() == 6).then(|| Affine::new([a[0], a[1], a[2], a[3], a[4], a[5]])) -} - -pub(super) fn matrix_val(m: Affine) -> V { - array(m.as_coeffs().iter().map(|c| V::Num(*c)).collect()) -} diff --git a/crates/pdf/src/tests.rs b/crates/pdf/src/tests.rs index b4b04d2ac..c1f519595 100644 --- a/crates/pdf/src/tests.rs +++ b/crates/pdf/src/tests.rs @@ -8,6 +8,7 @@ mod groups; mod import; mod reader; mod shading; +mod vectorcraft; const CONTENT: &str = "/OC /MC0 BDC\n0 1 0 rg 0 0 200 100 re f\nEMC\n\ /OC /MC1 BDC\nq 10 10 80 80 re W n\n1 0 0 rg 0 0 50 100 re f\nQ\n\ @@ -82,6 +83,28 @@ fn pdf_paths_clip_gradient_and_layers() { } } +#[test] +fn pdf_actual_text_is_exposed_as_a_logical_group() { + let content = "/Span << /ActualText (Logical text) >> BDC\n1 0 0 rg 10 10 20 20 re f\nEMC"; + let objs = vec![ + (1, "<< /Type /Catalog /Pages 2 0 R >>".to_string(), None), + (2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(), None), + (3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Resources << >> /Contents 4 0 R >>".to_string(), None), + (4, "<< >>".to_string(), Some(content.as_bytes().to_vec())), + ]; + + let doc = parse(&pdf(&objs, 1)).unwrap(); + + assert_eq!(shape_names(&doc), vec!["Text: Logical text"]); +} + +#[test] +fn pdf_actual_text_without_a_bom_is_pdfdocencoding_in_the_label() { + // 0x80 is a bullet in PDFDocEncoding, 0x92 a trade mark sign, not C1 control characters. + let data = page_pdf("/Span << /ActualText <80204192> >> BDC 1 0 0 rg 10 10 20 20 re f EMC", "", vec![]); + assert_eq!(shape_names(&parse(&data).unwrap()), vec!["Text: \u{2022} A\u{2122}"]); +} + #[test] fn pdf_forms_rotation_cmyk_and_alpha() { let content = "q 2 0 0 2 0 0 cm /Fm0 Do Q\n/GS0 gs 0 0 0 1 k 0 0 10 10 re f\n"; @@ -231,6 +254,12 @@ fn eps_postscript_subset() { assert_eq!(parse(b"hello"), Err(Error::NotVector)); } +#[test] +fn eps_without_a_bounding_box_keeps_the_public_error_variant() { + let eps = b"%!PS-Adobe-3.0 EPSF-3.0\n%%EndComments\n0 0 10 10 rectfill\n"; + assert_eq!(parse(eps), Err(Error::NoBoundingBox)); +} + #[test] fn filters_decode() { assert_eq!(object::ascii85(b"<~87cURD]i,\"Ebo80~>"), b"Hello World!".to_vec()); @@ -450,6 +479,9 @@ pub(crate) fn shape_names(doc: &Doc) -> Vec { fn walk(g: &effectcraft_svg::Group, out: &mut Vec) { for c in &g.children { match c { + // Marked text from the shared PostScript adapter is a logical text object whose + // outlined glyph paths remain children for rendering and editing. + Node::Group(s) if s.name.starts_with("Text: ") => out.push(s.name.clone()), Node::Group(s) => walk(s, out), Node::Shape(s) => out.push(s.name.clone()), Node::Image(i) => out.push(i.name.clone()), @@ -1305,3 +1337,101 @@ fn cmap_entries_at_the_top_of_the_code_range_do_not_overflow() { // Code 0 is CID u32::MAX; code 2 would be past it, so it falls back to CID 0 like an unmapped code. assert_eq!((f.width(0), f.width(2)), (0.5, 0.7)); } + +/// Never crash: a crafted page nests `q … W n` twenty thousand deep. The document is a tree +/// that is drawn, measured and dropped recursively, so groups past the nesting limit are left +/// out (said in the skip notes) and the page parses, draws and drops on a thread with a small +/// stack; the artwork inside them still draws, clipped by the groups that were kept. +#[test] +fn clip_groups_nested_without_end_are_capped() { + let run = std::thread::Builder::new().stack_size(2 << 20).spawn(|| { + let n = 20_000; + let mut content = "q 0 0 50 50 re W n\n".repeat(n); + content.push_str("0 0 1 rg 0 0 50 50 re f\n"); + content.push_str(&"Q\n".repeat(n)); + let bytes = pdf( + &[ + (1, "<< /Type /Catalog /Pages 2 0 R >>".to_string(), None), + (2, "<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_string(), None), + (3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 100] /Contents 4 0 R >>".to_string(), None), + (4, "<< >>".to_string(), Some(content.into_bytes())), + ], + 1, + ); + let doc = parse(&bytes).unwrap(); + (doc.skipped.clone(), px(&doc, 25, 75), px(&doc, 75, 25)) + }); + let (skipped, inside, outside) = run.unwrap().join().unwrap(); + assert!(skipped.iter().any(|s| s.contains("nesting limit")), "{skipped:?}"); + assert!(inside[2] > 0.99 && inside[3] > 0.99, "the artwork draws inside the clips: {inside:?}"); + assert!(outside[3] < 0.01, "and is clipped: {outside:?}"); +} + +#[test] +fn actual_text_named_properties_and_fallback_weights() { + let data = + page_pdf("/Span /P BDC 1 0 0 rg 10 10 20 20 re f EMC", "/Properties << /P 10 0 R >>", vec![(10, "<< /ActualText (Logical text) >>".into(), None)]); + assert_eq!(shape_names(&parse(&data).unwrap()), vec!["Text: Logical text"]); + use effectcraft_text::fonts::{INTER_BOLD, INTER_SEMIBOLD}; + for name in [b"Inter-Semibold".as_slice(), b"Inter-Demi"] { + assert_eq!(eps_fallback_font(name), Some(INTER_SEMIBOLD)); + } + for name in [b"Inter-Bold".as_slice(), b"Inter-Black", b"Inter-Heavy"] { + assert_eq!(eps_fallback_font(name), Some(INTER_BOLD)); + } +} + +#[test] +fn actual_text_does_not_change_graphics_state_or_compositing() { + let resources = "/ExtGState << /M << /BM /Multiply >> /N << /BM /Normal >> >>"; + // Compare every pixel to the same operators without marked content. In particular, + // Multiply and the clip survive EMC, and a later graphics-state change still works. + for (marked, plain) in [ + ( + "/Span << /ActualText (A) >> BDC /M gs 0 1 1 rg 0 0 60 100 re f EMC 50 0 60 100 re f /N gs 0 0 1 rg 150 0 50 100 re f", + "/M gs 0 1 1 rg 0 0 60 100 re f 50 0 60 100 re f /N gs 0 0 1 rg 150 0 50 100 re f", + ), + ( + "/Span << /ActualText (A) >> BDC 0 0 100 100 re W n /M gs 0 1 1 rg 0 0 60 100 re f EMC 50 0 150 100 re f", + "0 0 100 100 re W n /M gs 0 1 1 rg 0 0 60 100 re f 50 0 150 100 re f", + ), + ( + "/Span << /ActualText (A) >> BDC q /M gs 0 1 1 rg 0 0 60 100 re f Q EMC 0 0 1 rg 100 0 100 100 re f", + "q /M gs 0 1 1 rg 0 0 60 100 re f Q 0 0 1 rg 100 0 100 100 re f", + ), + ] { + let draw = |ops| render(&parse(&page_pdf(&format!("1 1 0 rg 0 0 200 100 re f {ops}"), resources, vec![])).unwrap()); + let (a, b) = (draw(marked), draw(plain)); + for y in 0..100 { + for x in 0..200 { + assert_eq!(a.get(x, y), b.get(x, y), "pixel {x},{y}"); + } + } + } +} + +#[test] +fn logical_text_cannot_extend_finished_node_depth_limit() { + use crate::build::Builder; + use effectcraft_svg::Group; + let mut b = Builder::new(); + assert!(b.begin_text("label")); + assert!(!b.nested(0).has_room(254)); + let mut node = Node::Group(Group::new("leaf")); + for _ in 1..255 { + let mut parent = Group::new("nested"); + parent.children.push(node); + node = Node::Group(parent); + } + b.push(node); + b.end_text(); + let (nodes, _, skipped) = b.finish(); + assert!(skipped.iter().any(|s| s == "group nesting limit")); + let mut current = nodes.first(); + let mut depth = 1; + while let Some(Node::Group(g)) = current { + depth += 1; + current = g.children.first(); + } + assert_eq!(depth, 256); +} diff --git a/crates/pdf/src/tests/groups.rs b/crates/pdf/src/tests/groups.rs index 14b6a4b09..d39f7f4db 100644 --- a/crates/pdf/src/tests/groups.rs +++ b/crates/pdf/src/tests/groups.rs @@ -151,3 +151,40 @@ fn vertical_metrics_w2_and_dw2() { let dw2 = doc("/DW2 [780 -1000]"); assert!(((base.1 - dw2.1) - 2).abs() <= 1, "vy 780 → 2 pt higher: {base:?} {dw2:?}"); } + +#[test] +fn actual_text_does_not_combine_knockout_children() { + let plain = "1 0 0 rg 0 0 100 100 re f /H gs 0 0 1 rg 50 0 100 100 re f"; + let marked = format!("/Span << /ActualText (Label) >> BDC {plain} EMC"); + let a = render(&group_page("/Fm Do", "", "/Group << /S /Transparency /I true /K true >>", plain)); + let b = render(&group_page("/Fm Do", "", "/Group << /S /Transparency /I true /K true >>", &marked)); + for y in 0..100 { + for x in 0..200 { + assert!(near(a.get(x, y), b.get(x, y)), "pixel {x},{y}"); + } + } +} + +#[test] +fn actual_text_end_keeps_soft_mask_and_overlapping_paints() { + let plain = "/GS1 gs 1 0 0 rg 0 0 100 100 re f 0 0 1 rg 50 0 100 100 re f"; + let marked = "/Span << /ActualText (Label) >> BDC /GS1 gs 1 0 0 rg 0 0 100 100 re f EMC 0 0 1 rg 50 0 100 100 re f"; + let draw = |ops| { + let bytes = page_pdf( + ops, + "/ExtGState << /GS1 << /SMask << /S /Luminosity /G 10 0 R >> >> >>", + vec![( + 10, + "<< /Type /XObject /Subtype /Form /BBox [0 0 200 100] /Group << /S /Transparency /CS /DeviceGray >> >>".into(), + Some(b"0.5 g 0 0 200 100 re f".to_vec()), + )], + ); + render(&parse(&bytes).unwrap()) + }; + let (a, b) = (draw(plain), draw(marked)); + for y in 0..100 { + for x in 0..200 { + assert!(near(a.get(x, y), b.get(x, y)), "pixel {x},{y}"); + } + } +} diff --git a/crates/pdf/src/tests/import.rs b/crates/pdf/src/tests/import.rs index 516ff054d..80be350f6 100644 --- a/crates/pdf/src/tests/import.rs +++ b/crates/pdf/src/tests/import.rs @@ -563,7 +563,8 @@ fn bounding_box_comments_are_scanned_once() { // A rejected `%%BoundingBox:` comment is not scanned again from each later marker on its // line: 20,000 markers on one line would otherwise take quadratic work. let mut src = b"%!PS-Adobe-3.0 EPSF-3.0\n".to_vec(); - src.extend_from_slice("%%BoundingBox: x ".repeat(20_000).as_bytes()); + // Keep the valid comment inside craft-eps's bounded header window. + src.extend_from_slice("%%BoundingBox: x ".repeat(3_000).as_bytes()); src.extend_from_slice(b"\n%%BoundingBox: 0 0 50 50\n0 0 10 10 rectfill\n"); let doc = parse(&src).unwrap(); assert_eq!((doc.width, doc.height), (50.0, 50.0)); @@ -626,3 +627,19 @@ fn postscript_idiv_and_mod_of_i64_min_by_minus_one_give_zero() { assert_eq!(shape_names(&doc).len(), 1, "{prog}"); } } + +#[test] +fn eps_unembedded_reencoded_accent_uses_bundled_glyph() { + let doc = eps(b"/Helvetica findfont dup length dict begin {1 index /FID ne {def} {pop pop} ifelse} forall /Encoding 256 array def 0 1 255 {Encoding exch /.notdef put} for Encoding 65 /eacute put currentdict end /Accent exch definefont 40 scalefont setfont 10 30 moveto (A) show\n"); + assert_eq!(shape_names(&doc), vec!["Text: é"]); + let reference = parse(&page_pdf( + "BT /F1 40 Tf 10 30 Td Tj ET", + "/Font << /F1 << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> >>", + vec![], + )) + .unwrap(); + let (a, b) = (render(&doc), render(&reference)); + let (ia, ib) = (coverage(&a, 0, 0, 200, 100), coverage(&b, 0, 0, 200, 100)); + assert!(ia > 50.0 && (ia - ib).abs() < 1.0, "EPS accent {ia} vs PDF accent {ib}"); + assert_eq!(ink_x(&a), ink_x(&b)); +} diff --git a/crates/pdf/src/tests/vectorcraft.rs b/crates/pdf/src/tests/vectorcraft.rs new file mode 100644 index 000000000..d4a3b73ad --- /dev/null +++ b/crates/pdf/src/tests/vectorcraft.rs @@ -0,0 +1,140 @@ +//! VectorCraft documents read through the PDF they carry (Create PDF-Compatible File), written +//! with craft-vectorcraft-format's envelope types: plain and compressed, the PDF inline as base64 +//! (version 3) and after the JSON (version 4). + +use std::io::Write; + +use craft_vectorcraft_format::{BLOB_MAGIC, File, INLINE_MAX, Image}; + +use crate::write::pdf; +use crate::*; + +/// Two artboards: a 200×100 page with the layers "Background" (green) and "Art" (a red left +/// half), and a 100×50 blue page. `pad` adds an unused object so the PDF is long enough to go +/// after the JSON. +fn artboards_pdf(pad: bool) -> Vec { + let first = "/OC /L0 BDC\n0 1 0 rg 0 0 200 100 re f\nEMC\n/OC /L1 BDC\n1 0 0 rg 0 0 100 100 re f\nEMC\n"; + let mut objs = vec![ + (1, "<< /Type /Catalog /Pages 2 0 R >>".to_string(), None), + (2, "<< /Type /Pages /Kids [3 0 R 8 0 R] /Count 2 >>".to_string(), None), + (3, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 100] /Resources << /Properties << /L0 5 0 R /L1 6 0 R >> >> /Contents 4 0 R >>".to_string(), None), + (4, "<< >>".to_string(), Some(first.as_bytes().to_vec())), + (5, "<< /Type /OCG /Name (Background) >>".to_string(), None), + (6, "<< /Type /OCG /Name (Art) >>".to_string(), None), + (7, "<< >>".to_string(), Some(b"0 0 1 rg 0 0 100 50 re f\n".to_vec())), + (8, "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 100 50] /Contents 7 0 R >>".to_string(), None), + ]; + if pad { + // Written as given (the writer compresses streams without a `/Filter`); never read. + objs.push((9, "<< /Filter /ASCIIHexDecode >>".to_string(), Some(vec![b'0'; INLINE_MAX + 1024]))); + } + pdf(&objs, 1) +} + +/// A `.vectorcraft` file of `version` holding an empty document and `carried` as its `pdf` +/// member, gzip-compressed when `gzip` is set (Use Compression). +fn vectorcraft(carried: Option<&[u8]>, version: u32, gzip: bool) -> Vec { + vectorcraft_with_preview(carried, None, version, gzip) +} + +/// [`vectorcraft`] with `preview` as the file's `preview` member. +fn vectorcraft_with_preview(carried: Option<&[u8]>, preview: Option, version: u32, gzip: bool) -> Vec { + let mut file = File::new(serde_json::json!({"artboards": [], "layers": []})); + file.version = version; + file.generator = Some("VectorCraft 0.1.0".into()); + file.preview = preview; + let mut tail = file.tail(); + file.pdf = carried.map(|b| tail.image("application/pdf", b, false)); + let mut out = serde_json::to_vec(&file).unwrap(); + tail.write_to(&mut out).unwrap(); + if !gzip { + return out; + } + let mut gz = flate2::write::GzEncoder::new(vec![], flate2::Compression::default()); + gz.write_all(&out).unwrap(); + gz.finish().unwrap() +} + +fn pixels(doc: &Doc) -> Vec<[f32; 4]> { + let (w, h) = doc.pixel_size(); + effectcraft_svg::rasterize(doc, w, h, 1.0).data +} + +#[test] +fn a_vectorcraft_document_reads_as_the_pdf_it_carries() { + for (version, gzip, pad) in [(3, false, false), (3, true, false), (4, false, true), (4, true, true)] { + let carried = artboards_pdf(pad); + let file = vectorcraft(Some(&carried), version, gzip); + let case = format!("version {version}, gzip {gzip}"); + if !gzip { + let after_json = file.windows(BLOB_MAGIC.len()).any(|w| w == BLOB_MAGIC); + assert_eq!(after_json, version == 4, "{case}: the PDF goes after the JSON in version 4"); + } + assert_eq!(sniff(&file), Some(Format::VectorCraft), "{case}"); + assert_eq!(codec("art.vectorcraft", &file), Some("VectorCraft"), "{case}"); + assert_eq!(page_count(&file), 2, "{case}"); + let doc = parse(&file).unwrap(); + assert_eq!((doc.width, doc.height), (200.0, 100.0), "{case}"); + assert_eq!(layer_names(&doc), vec!["Background", "Art"], "{case}"); + assert_eq!(pixels(&doc), pixels(&parse(&carried).unwrap()), "{case}: drawn as the PDF itself"); + let second = parse_page(&file, 1).unwrap(); + assert_eq!((second.width, second.height), (100.0, 50.0), "{case}"); + assert_eq!(parse_page(&file, 2).err(), Some(Error::PageOutOfRange(2)), "{case}"); + } +} + +#[test] +fn a_vectorcraft_document_without_a_pdf_names_create_pdf_compatible_file() { + for gzip in [false, true] { + let file = vectorcraft(None, 4, gzip); + assert_eq!(sniff(&file), Some(Format::VectorCraft)); + assert_eq!(page_count(&file), 0); + let e = parse(&file).err(); + assert_eq!(e, Some(Error::NoCarriedPdf)); + assert!(e.map(|e| e.to_string()).unwrap_or_default().contains("Create PDF-Compatible File")); + } +} + +#[test] +fn a_damaged_preview_does_not_stop_the_carried_pdf_from_reading() { + let mut not_base64 = Image::default(); + not_base64.mime = "image/png".into(); + not_base64.data = "not base64!".into(); + let mut past_the_end = Image::default(); + past_the_end.mime = "image/png".into(); + past_the_end.blob = Some([u64::MAX / 2, 16]); + for (preview, what) in [(not_base64, "not base64"), (past_the_end, "past the end")] { + for (version, gzip, pad) in [(3, false, false), (4, false, true), (4, true, true)] { + let carried = artboards_pdf(pad); + let file = vectorcraft_with_preview(Some(&carried), Some(preview.clone()), version, gzip); + let case = format!("{what}, version {version}, gzip {gzip}"); + assert_eq!(page_count(&file), 2, "{case}"); + let doc = parse(&file).unwrap_or_else(|e| panic!("{case}: {e}")); + assert_eq!(layer_names(&doc), vec!["Background", "Art"], "{case}"); + } + } +} + +#[test] +fn a_carried_pdf_may_be_as_large_as_a_pdf_file() { + let limits = carried_limits(); + assert_eq!(limits.max_entry, craft_pdf::MAX_INPUT_BYTES as u64); + assert_eq!(limits.max_json, craft_doc::Limits::default().max_json); + assert_eq!(limits.max_total, limits.max_json + 2 * limits.max_entry); +} + +#[test] +fn a_vectorcraft_document_read_wrongly_is_an_error() { + // A newer format version. + let newer = vectorcraft(Some(&artboards_pdf(false)), craft_vectorcraft_format::VERSION + 1, false); + let e = parse(&newer).err().map(|e| e.to_string()).unwrap_or_default(); + assert!(e.contains("newer"), "{e}"); + // A `pdf` member that holds something else. + let not_pdf = vectorcraft(Some(b"not a PDF"), 4, false); + assert!(matches!(parse(¬_pdf), Err(Error::Read(_)))); + // A cut-off file. + let file = vectorcraft(Some(&artboards_pdf(true)), 4, true); + assert!(parse(&file[..file.len() / 2]).is_err()); + // Other JSON is not a VectorCraft document. + assert_eq!(sniff(br#"{"format":"other","version":1}"#), None); +} diff --git a/crates/project/src/footage.rs b/crates/project/src/footage.rs index eeace5e81..462772dc4 100644 --- a/crates/project/src/footage.rs +++ b/crates/project/src/footage.rs @@ -172,12 +172,12 @@ impl CineonSettings { } } -/// Cineon log to linear, shared by Interpret Footage ▸ Cineon Settings and the Cineon Converter -/// effect. `v` is a code value as 0–1 of the 10-bit range; `black` and `white` are the 10 Bit +/// Cineon log to linear for Interpret Footage ▸ Cineon Settings and version 1 Cineon Converter +/// effects. `v` is a code value as 0–1 of the 10-bit range; `black` and `white` are the 10 Bit /// Black and White Points. The result is 0 at the black point and 1 at the white point, raised to /// `scale / gamma`, with values above `1 - rolloff / 100` ramped off toward 1 (Highlight Rolloff /// 0–100; 0 keeps over-range values). A Gamma below 0.01 is raised to 0.01. Cineon Settings passes -/// a `scale` of 1 (Gamma 1 gives linear light) and the Cineon Converter passes 1.7 (its default +/// a `scale` of 1 (Gamma 1 gives linear light) and a version 1 Cineon Converter passes 1.7 (its /// Gamma 1.7 gives linear light). pub fn cineon_log_to_lin(v: f32, black: f32, white: f32, scale: f32, gamma: f32, rolloff: f32) -> f32 { // Kodak printing density: 0.002 density per code value, negative gamma 0.6. diff --git a/crates/psd/Cargo.toml b/crates/psd/Cargo.toml index b6849041b..818331cce 100644 --- a/crates/psd/Cargo.toml +++ b/crates/psd/Cargo.toml @@ -10,4 +10,8 @@ rust-version.workspace = true workspace = true [dependencies] +craft-psd = { workspace = true } miniz_oxide = "0.9" + +[dev-dependencies] +craft-psd = { workspace = true, features = ["testgen"] } diff --git a/crates/psd/src/engine_data.rs b/crates/psd/src/engine_data.rs index 20fa1676d..43dec23d5 100644 --- a/crates/psd/src/engine_data.rs +++ b/crates/psd/src/engine_data.rs @@ -1,316 +1,9 @@ -//! The text engine data of type layers (`EngineData` in the `TySh` descriptor): a PostScript-like -//! tree of dictionaries (`<< /Key value >>`), arrays (`[ ]`), numbers, names, booleans and -//! strings (`(þÿ` + UTF-16BE with backslash escapes `)`). Read best-effort. +//! Engine data (the text engine document of type layers, `TySh`): `craft-psd`'s +//! `engine_data`, re-exported. [`text_style`] is its typed view of the first style run. -/// Bytes that end a bare token or a `/Name` (besides whitespace). -const DELIMITERS: &[u8] = b"[]<>/("; +pub use craft_psd::engine_data::{TextStyle, Value, minimal, parse, parse_lossy, write}; -#[derive(Clone, Debug, PartialEq)] -pub enum EValue { - Dict(Vec<(String, EValue)>), - Array(Vec), - Num(f64), - Bool(bool), - Name(String), - Str(String), -} - -impl EValue { - pub fn get(&self, key: &str) -> Option<&EValue> { - match self { - EValue::Dict(v) => v.iter().find(|(k, _)| k == key).map(|(_, v)| v), - _ => None, - } - } - pub fn idx(&self, i: usize) -> Option<&EValue> { - match self { - EValue::Array(v) => v.get(i), - _ => None, - } - } - /// Follow a `/`-separated path; numeric segments index arrays. - pub fn path(&self, p: &str) -> Option<&EValue> { - let mut cur = self; - for seg in p.split('/').filter(|s| !s.is_empty()) { - cur = match seg.parse::() { - Ok(i) => cur.idx(i)?, - Err(_) => cur.get(seg)?, - }; - } - Some(cur) - } - pub fn num(&self) -> Option { - match self { - EValue::Num(n) => Some(*n), - _ => None, - } - } - pub fn str(&self) -> Option<&str> { - match self { - EValue::Str(s) | EValue::Name(s) => Some(s), - _ => None, - } - } -} - -struct P<'a> { - b: &'a [u8], - i: usize, -} - -impl P<'_> { - fn ws(&mut self) { - while self.i < self.b.len() && (self.b[self.i].is_ascii_whitespace() || self.b[self.i] == 0) { - self.i += 1; - } - } - fn peek(&self, s: &[u8]) -> bool { - self.b[self.i..].starts_with(s) - } - fn value(&mut self, depth: usize) -> Option { - if depth > 128 { - return None; - } - self.ws(); - if self.i >= self.b.len() { - return None; - } - if self.peek(b"<<") { - self.i += 2; - let mut v = vec![]; - loop { - self.ws(); - if self.i >= self.b.len() { - return Some(EValue::Dict(v)); - } - if self.peek(b">>") { - self.i += 2; - return Some(EValue::Dict(v)); - } - if self.b[self.i] != b'/' { - // Unexpected token: skip it. - self.i += 1; - continue; - } - let key = self.name(); - let val = self.value(depth + 1)?; - v.push((key, val)); - } - } - match self.b[self.i] { - b'[' => { - self.i += 1; - let mut v = vec![]; - loop { - self.ws(); - if self.i >= self.b.len() { - return Some(EValue::Array(v)); - } - if self.b[self.i] == b']' { - self.i += 1; - return Some(EValue::Array(v)); - } - let start = self.i; - match self.value(depth + 1) { - Some(x) => v.push(x), - None => return Some(EValue::Array(v)), - } - if self.i == start { - self.i += 1; - } - } - } - b'/' => Some(EValue::Name(self.name())), - b'(' => Some(EValue::Str(self.string())), - _ => { - let start = self.i; - while self.i < self.b.len() && !self.b[self.i].is_ascii_whitespace() && !DELIMITERS.contains(&self.b[self.i]) { - self.i += 1; - } - let tok = std::str::from_utf8(&self.b[start..self.i]).unwrap_or(""); - if self.i == start { - self.i += 1; - return Some(EValue::Name(String::new())); - } - Some(match tok { - "true" => EValue::Bool(true), - "false" => EValue::Bool(false), - // "nan", "inf" and overflowing literals parse as f64 but are not numbers here. - t => match t.parse::() { - Ok(n) if n.is_finite() => EValue::Num(n), - _ => EValue::Name(t.to_string()), - }, - }) - } - } - } - fn name(&mut self) -> String { - self.i += 1; // '/' - let start = self.i; - while self.i < self.b.len() && !self.b[self.i].is_ascii_whitespace() && !DELIMITERS.contains(&self.b[self.i]) { - self.i += 1; - } - String::from_utf8_lossy(&self.b[start..self.i]).into_owned() - } - fn string(&mut self) -> String { - self.i += 1; // '(' - let mut raw = vec![]; - while self.i < self.b.len() { - let c = self.b[self.i]; - self.i += 1; - match c { - b'\\' if self.i < self.b.len() => { - let e = self.b[self.i]; - self.i += 1; - raw.push(match e { - b'n' => b'\n', - b'r' => b'\r', - b't' => b'\t', - other => other, - }); - } - b')' => break, - _ => raw.push(c), - } - } - if raw.starts_with(&[0xFE, 0xFF]) { - let u: Vec = raw[2..].as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect(); - String::from_utf16_lossy(&u).trim_end_matches('\0').to_string() - } else { - String::from_utf8_lossy(&raw).into_owned() - } - } -} - -/// Parse engine data (returns an empty dictionary on garbage). -pub fn parse(b: &[u8]) -> EValue { - let mut p = P { b, i: 0 }; - p.value(0).unwrap_or(EValue::Dict(vec![])) -} - -/// Encode a string the way engine data stores it (UTF-16BE with a BOM, escaped). -pub fn encode_string(s: &str) -> Vec { - let mut out = vec![b'(', 0xFE, 0xFF]; - for u in s.encode_utf16() { - for b in u.to_be_bytes() { - if matches!(b, b'(' | b')' | b'\\') { - out.push(b'\\'); - } - out.push(b); - } - } - out.push(b')'); - out -} - -/// The first style run's character attributes. -#[derive(Clone, Debug, Default, PartialEq)] -pub struct TextStyle { - pub font: Option, - pub size: Option, - /// RGB 0..1. - pub color: Option<[f64; 3]>, - /// 0 left, 1 right, 2 centre, 3+ justified variants. - pub justification: Option, - pub tracking: Option, - pub leading: Option, - pub faux_bold: bool, - pub faux_italic: bool, - /// Paragraph (box) text rather than point text. - pub box_text: bool, -} - -/// Sane upper bound for a font size in points (Photoshop's own limit is 1296 pt). -const MAX_FONT_SIZE: f64 = 10_000.0; -/// Sane bound for tracking (1/1000 em) and leading (points). -const MAX_SPACING: f64 = 100_000.0; - -pub fn text_style(ed: &EValue) -> TextStyle { - let engine = ed.get("EngineDict").unwrap_or(ed); - let resources = ed.get("ResourceDict").or_else(|| ed.get("DocumentResources")); - let run = engine.path("StyleRun/RunArray/0/StyleSheet/StyleSheetData"); - let normal = resources.and_then(|r| r.path("StyleSheetSet/0/StyleSheetData")); - let attr = |k: &str| run.and_then(|r| r.get(k)).or_else(|| normal.and_then(|n| n.get(k))); - let font = - attr("Font").and_then(EValue::num).and_then(|i| resources?.path(&format!("FontSet/{}/Name", i as usize))).and_then(EValue::str).map(str::to_string); - let color = attr("FillColor").and_then(|c| c.get("Values")).and_then(|v| match v { - EValue::Array(a) if a.len() >= 4 => Some([a[1].num()?, a[2].num()?, a[3].num()?]), - _ => None, - }); - let para = engine.path("ParagraphRun/RunArray/0/ParagraphSheet/Properties"); - let para_normal = resources.and_then(|r| r.path("ParagraphSheetSet/0/Properties")); - let justification = - para.and_then(|p| p.get("Justification")).or_else(|| para_normal.and_then(|p| p.get("Justification"))).and_then(EValue::num).map(|n| n as u8); - let auto_leading = attr("AutoLeading").is_none_or(|v| *v != EValue::Bool(false)); - let box_text = engine.path("Rendered/Shapes/Children/0/ShapeType").and_then(EValue::num) == Some(1.0); - TextStyle { - font, - size: attr("FontSize").and_then(EValue::num).filter(|s| *s > 0.0).map(|s| s.min(MAX_FONT_SIZE)), - color, - justification, - tracking: attr("Tracking").and_then(EValue::num).map(|t| t.clamp(-MAX_SPACING, MAX_SPACING)), - leading: if auto_leading { None } else { attr("Leading").and_then(EValue::num).map(|l| l.clamp(-MAX_SPACING, MAX_SPACING)) }, - faux_bold: attr("FauxBold") == Some(&EValue::Bool(true)), - faux_italic: attr("FauxItalic") == Some(&EValue::Bool(true)), - box_text, - } -} - -/// Minimal engine data for a type layer with one style run (fixtures, and what a writer needs). -pub fn minimal(text: &str, font: &str, size: f64, color: [f64; 3], justification: u8) -> Vec { - let mut out = Vec::new(); - out.extend_from_slice(b"\n\n<<\n\t/EngineDict\n\t<<\n\t\t/Editor << /Text "); - out.extend_from_slice(&encode_string(&format!("{text}\r"))); - out.extend_from_slice(b" >>\n\t\t/ParagraphRun << /RunArray [ << /ParagraphSheet << /Properties << /Justification "); - out.extend_from_slice(justification.to_string().as_bytes()); - out.extend_from_slice(b" >> >> >> ] >>\n\t\t/StyleRun << /RunArray [ << /StyleSheet << /StyleSheetData << /Font 0 /FontSize "); - out.extend_from_slice(format!("{size:.1}").as_bytes()); - out.extend_from_slice( - format!(" /FillColor << /Type 1 /Values [ 1.0 {:.5} {:.5} {:.5} ] >> /AutoLeading true >> >> >> ] >>\n\t>>\n", color[0], color[1], color[2]).as_bytes(), - ); - out.extend_from_slice(b"\t/ResourceDict << /FontSet [ << /Name "); - out.extend_from_slice(&encode_string(font)); - out.extend_from_slice(b" /Type 0 >> ] >>\n>>"); - out -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn parses_minimal() { - let b = minimal("Hi (there)", "Arial-BoldMT", 36.0, [1.0, 0.5, 0.0], 2); - let v = parse(&b); - assert_eq!(v.path("EngineDict/Editor/Text").and_then(EValue::str), Some("Hi (there)\r")); - let st = text_style(&v); - assert_eq!(st.font.as_deref(), Some("Arial-BoldMT")); - assert_eq!(st.size, Some(36.0)); - assert_eq!(st.color, Some([1.0, 0.5, 0.0])); - assert_eq!(st.justification, Some(2)); - assert!(!st.box_text); - } - - #[test] - fn garbage_is_harmless() { - let _ = parse(b"<< /A [ 1 2 << /B (unterminated"); - let _ = parse(b"]]]>>>> /x"); - let _ = parse(&[0xFF; 64]); - } - - #[test] - fn non_finite_and_out_of_range_numbers_are_not_numbers() { - let b = b"<< /FontSize nan /Tracking inf /Leading -inf /Other 1e999 >>"; - let v = parse(b); - assert_eq!(v.get("FontSize").and_then(EValue::num), None); - assert_eq!(v.get("Other").and_then(EValue::num), None); - let ed = parse(b"<< /EngineDict << /StyleRun << /RunArray [ << /StyleSheet << /StyleSheetData << /FontSize nan /Tracking inf /Leading -inf /AutoLeading false >> >> >> ] >> >> >>"); - let st = text_style(&ed); - assert_eq!((st.size, st.tracking, st.leading), (None, None, None)); - let ed = parse(b"<< /EngineDict << /StyleRun << /RunArray [ << /StyleSheet << /StyleSheetData << /FontSize 1e300 /Tracking -1e300 /AutoLeading false /Leading 1e300 >> >> >> ] >> >> >>"); - let st = text_style(&ed); - assert_eq!(st.size, Some(MAX_FONT_SIZE)); - assert_eq!(st.tracking, Some(-MAX_SPACING)); - assert_eq!(st.leading, Some(MAX_SPACING)); - } +/// The first style run's character and paragraph attributes of a parsed document. +pub fn text_style(ed: &Value) -> TextStyle { + craft_psd::engine_data::first_style(ed) } diff --git a/crates/psd/src/lib.rs b/crates/psd/src/lib.rs index 91792a837..f24ddf286 100644 --- a/crates/psd/src/lib.rs +++ b/crates/psd/src/lib.rs @@ -1,8 +1,8 @@ //! Photoshop document (PSD / PSB) reader, implemented from Adobe's public *Photoshop File Formats //! Specification* (see README.md), and a minimal writer ([`mod@write`]) for fixtures. //! -//! [`Psd::parse`] reads the structure (header, layer records and their additional information, -//! the layer tree) without decoding pixels; [`Psd::composite`] decodes the merged image and +//! [`Psd::parse`] reads the structure with `craft_psd` (header, layer records and their +//! additional information, the layer tree) without decoding pixels; [`Psd::composite`] decodes the merged image and //! [`Psd::layer_pixels`] one layer (with its layer mask applied to alpha) on demand. Pixels come //! out as straight (unpremultiplied) RGBA `f32` in 0..1, display-encoded (32-bit documents, //! which are linear, are encoded to sRGB). @@ -32,7 +32,6 @@ pub use model::{ Adjustment, ChannelInfo, ColorMode, Layer, LayerMask, LinkedFile, MAX_GROUP_DEPTH, Node, Pixels, Rect, Section, SmartObject, SubPath, TextInfo, VectorMask, }; pub use parse::is_psd; -pub(crate) use pixels::pack_bits; #[cfg(test)] use pixels::{lab_to_rgb, srgb_encode, unpack_bits}; diff --git a/crates/psd/src/parse.rs b/crates/psd/src/parse.rs index d221b9044..3f70a67b5 100644 --- a/crates/psd/src/parse.rs +++ b/crates/psd/src/parse.rs @@ -11,102 +11,114 @@ pub fn is_psd(bytes: &[u8]) -> bool { } impl Psd { + /// Reads the structure with [`craft_psd::PsdFile::from_source`]: header, colour mode data, + /// layer records with their additional information and the global blocks. Channel data and + /// the merged image stay in `data` (as ranges), decoded on demand. pub fn parse(data: impl Into>) -> Result { let data: Arc<[u8]> = data.into(); - let mut r = Reader::new(&data); - if r.bytes(4).ok() != Some(b"8BPS") { + if !is_psd(&data) { return Err(Error::NotPsd); } - let version = r.u16()?; - let psb = match version { - 1 => false, - 2 => true, - _ => return Err(Error::NotPsd), + let (read, splice) = read_file(&data); + let (head, file, warnings) = match read { + Ok(file) => { + // The compression field before the merged image's data. + let merged = file.image_data.stored.as_ref().map_or(data.len(), |s| (splice.map(s.offset) as usize).saturating_sub(2)); + ((file.header.clone(), file.color_mode_data.clone(), merged), Some(file), vec![]) + } + // A damaged layer section must not discard the document: keep the header and the + // merged image, drop the layers and say so. Without a merged image there is nothing to + // fall back to, so the original error stands. + Err(e) => match flattened(&data) { + Some(head) => (head, None, vec![format!("Layers could not be read ({}); only the flattened image is available", error(&e))]), + None => return Err(error(&e)), + }, }; - r.skip(6)?; - let channels = r.u16()?; - let height = r.u32()?; - let width = r.u32()?; - let depth = r.u16()?; - let mode_v = r.u16()?; + let (h, palette, merged_offset) = head; + let mode_v = h.color_mode.as_u16(); let mode = ColorMode::from_u16(mode_v).ok_or_else(|| Error::Unsupported(format!("colour mode {mode_v}")))?; - if !matches!(depth, 1 | 8 | 16 | 32) { - return Err(Error::Unsupported(format!("{depth}-bit"))); + if !matches!(h.depth, 1 | 8 | 16 | 32) { + return Err(Error::Unsupported(format!("{}-bit", h.depth))); } - if width == 0 || height == 0 || width > 300_000 || height > 300_000 { - return Err(Error::Invalid(format!("size {width}x{height}"))); + if h.width == 0 || h.height == 0 || h.width > 300_000 || h.height > 300_000 { + return Err(Error::Invalid(format!("size {}x{}", h.width, h.height))); } - // Colour mode data. - let n = r.u32()? as usize; - let palette = r.bytes(n)?.to_vec(); - // Image resources. - let n = r.u32()? as usize; - r.skip(n)?; - // Layer and mask information. let mut psd = Psd { - psb, - width, - height, - channels, - depth, + psb: h.version.is_psb(), + width: h.width, + height: h.height, + channels: h.channels, + depth: h.depth, mode, layers: vec![], merged_alpha: false, palette, linked: vec![], - warnings: vec![], + warnings, data: data.clone(), - merged_offset: 0, + merged_offset, }; - let lm_len = r.length(psb)?; - let lm_end = r.pos.checked_add(lm_len).filter(|&e| e <= data.len()).ok_or(Error::Truncated)?; - if lm_len > 0 { - let li_len = r.length(psb)?; - let li_end = r.pos.checked_add(li_len).filter(|&e| e <= lm_end).ok_or(Error::Truncated)?; - if li_len > 0 - && let Err(e) = psd.layer_info(&data, r.pos, li_end) - { - // A damaged layer section must not discard the document: keep the header and the - // merged image, drop the layers and say so. Without a merged image there is - // nothing to fall back to, so the original error stands. - if lm_end.checked_add(2).is_none_or(|n| n > data.len()) { - return Err(e); - } - psd.layers.clear(); - psd.warnings.push(format!("Layers could not be read ({e}); only the flattened image is available")); - } - r.pos = li_end; - if r.pos + 4 <= lm_end { - let g = r.u32()? as usize; - r.pos = (r.pos + g).min(lm_end); - } - // Global additional layer information (16/32-bit layer info lives here). - while let Some((key, start, end)) = next_block(&data, &mut r.pos, lm_end, psb) { - if matches!(&key, b"lnk2" | b"lnkD" | b"lnk3" | b"lnkE") { - psd.linked_files(&data, start, end); - } - if matches!(&key, b"Lr16" | b"Lr32" | b"Layr") && psd.layers.is_empty() && end > start { - // The block holds the layer info, normally without its length field; accept - // both layouts. - if psd.layer_info(&data, start, end).is_err() || psd.layers.is_empty() { - psd.layers.clear(); - let skip = if psb { 8 } else { 4 }; - if start + skip < end && psd.layer_info(&data, start + skip, end).is_err() { - psd.layers.clear(); - } - } - } - r.pos = end; + let Some(file) = file else { + psd.merged_alpha = section_merged_alpha(&data); + return Ok(psd); + }; + if let Some((block, e)) = file.unreadable_layer_block() { + // A 16/32-bit file's layers live in a global block; when it is damaged the file reads + // as flattened. Its layer count still says whether the merged image has alpha. + psd.merged_alpha = block.data.get(..2).is_some_and(|c| i16::from_be_bytes([c[0], c[1]]) < 0); + psd.warnings.push(format!("Layers could not be read ({}); only the flattened image is available", error(&e))); + } + if let Some(info) = &file.layer_info { + psd.merged_alpha = info.merged_alpha; + psd.layers = info.layers.iter().enumerate().map(|(i, rec)| psd.layer(rec, i, splice)).collect(); + } + for b in &file.global_blocks { + if let Some(stored) = b.stored.as_ref().filter(|_| linked(&b.key, 0)) { + let start = splice.map(stored.offset) as usize; + psd.linked_files(&data, start, start.saturating_add(stored.len as usize).min(data.len())); } } - if !psd.layers.is_empty() { - // A 16/32-bit layer block recovered the layers. - psd.warnings.clear(); - } - psd.merged_offset = lm_end; Ok(psd) } + /// One layer record of the model, its additional information read into [`Layer`]. + /// `splice` maps craft-psd's offsets back into `self.data` (see [`read_file`]). + fn layer(&self, rec: &craft_psd::LayerRecord, index: usize, splice: Splice) -> Layer { + let channels = rec + .channels + .iter() + .map(|c| match &c.stored { + // `ChannelInfo` covers the compression field and the data after it. + Some(s) => ChannelInfo { id: c.id, offset: (splice.map(s.offset) as usize).saturating_sub(2), len: s.len as usize + 2 }, + None => ChannelInfo { id: c.id, offset: 0, len: 0 }, + }) + .collect(); + let r = rec.rect; + let mut l = Layer { + index, + rect: Rect { top: r.top, left: r.left, bottom: r.bottom, right: r.right }, + blend: rec.blend_mode.key(), + opacity: rec.opacity, + fill_opacity: 255, + clipping: rec.clipping != 0, + hidden: rec.flags.hidden(), + protect_transparency: rec.flags.transparency_protected(), + channels, + name: mac_roman_string(&rec.name), + ..Default::default() + }; + if let craft_psd::MaskData::Mask(m) = &rec.mask { + let rect = Rect { top: m.rect.top, left: m.rect.left, bottom: m.rect.bottom, right: m.rect.right }; + l.mask = Some(LayerMask { rect, default_color: m.default_color, disabled: m.flags & 2 != 0, inverted: m.flags & 4 != 0 }); + } + for b in &rec.blocks { + l.keys.push(b.key); + // A malformed block only loses that block's information. + let _ = self.layer_block(&mut l, &b.key, &b.data); + } + l + } + /// The embedded bytes of linked file `uuid`. pub fn linked_data(&self, uuid: &str) -> Option<&[u8]> { let f = self.linked.iter().find(|f| f.uuid == uuid)?; @@ -116,140 +128,15 @@ impl Psd { /// Linked layer data records (spec: "Linked Layer"): length, kind (`liFD` embedded data, /// `liFE` external file, `liFA` alias), version, unique id, original file name, type, /// creator, data length, optional descriptors, then the data. A damaged record ends the list. + /// Ranges in [`LinkedFile::data`] are in the document bytes (`self.data`); craft-psd reports + /// them relative to the block, so the block's start is added back. fn linked_files(&mut self, data: &[u8], start: usize, end: usize) { - let mut pos = start; - while pos + 8 <= end { - let mut r = Reader::at(&data[..end], pos); - let Ok(len) = r.u64() else { break }; - let body = r.pos; - let Some(rec_end) = body.checked_add(len as usize).filter(|e| *e <= end) else { break }; - let mut r = Reader::at(&data[..rec_end], body); - let rec = (|| -> Result { - let kind = r.tag()?; - let version = r.u32()?; - let n = r.u8()? as usize; - let uuid = String::from_utf8_lossy(r.bytes(n)?).into_owned(); - let name = descriptor::read_unicode(&mut r)?; - let file_type = String::from_utf8_lossy(&r.tag()?).trim().to_string(); - let _creator = r.tag()?; - let dlen = r.u64()? as usize; - if r.u8()? != 0 { - let _v = r.u32()?; - descriptor::read_descriptor(&mut r)?; - } - let mut out = LinkedFile { uuid, name, file_type, data: None }; - match &kind { - b"liFD" => { - let s = r.pos; - r.skip(dlen)?; - out.data = Some(s..s + dlen); - } - b"liFE" => { - let _v = r.u32()?; - descriptor::read_descriptor(&mut r)?; - if version > 3 { - r.skip(4 + 4 + 8)?; - } - let _size = r.u64()?; - if version > 2 && r.remaining() >= dlen && dlen > 0 { - let s = r.pos; - out.data = Some(s..s + dlen); - } - } - _ => {} - } - Ok(out) - })(); - match rec { - Ok(f) => self.linked.push(f), - Err(_) => break, - } - pos = rec_end.div_ceil(4) * 4; + let Some(block) = data.get(start..end) else { return }; + for f in craft_psd::smart::linked_files(block) { + self.linked.push(LinkedFile { uuid: f.uuid, name: f.name, file_type: f.file_type, data: f.data.map(|r| (start + r.start)..(start + r.end)) }); } } - fn layer_info(&mut self, data: &[u8], start: usize, end: usize) -> Result<()> { - let mut r = Reader::at(&data[..end], start); - let count = r.i16()?; - self.merged_alpha = count < 0; - let n = count.unsigned_abs() as usize; - let mut layers = Vec::with_capacity(n); - for i in 0..n { - layers.push(self.layer_record(&mut r, i)?); - } - // Channel image data follows in record order. - for l in &mut layers { - for c in &mut l.channels { - c.offset = r.pos; - r.skip(c.len)?; - } - } - self.layers = layers; - Ok(()) - } - - fn layer_record(&self, r: &mut Reader, index: usize) -> Result { - let psb = self.psb; - let (top, left, bottom, right) = (r.i32()?, r.i32()?, r.i32()?, r.i32()?); - let nch = r.u16()? as usize; - if nch > 64 { - return Err(Error::Invalid("channel count".into())); - } - let mut channels = Vec::with_capacity(nch); - for _ in 0..nch { - let id = r.i16()?; - let len = r.length(psb)?; - channels.push(ChannelInfo { id, offset: 0, len }); - } - if r.bytes(4)? != b"8BIM" { - return Err(Error::Invalid("layer record signature".into())); - } - let blend = r.tag()?; - let opacity = r.u8()?; - let clipping = r.u8()? != 0; - let flags = r.u8()?; - r.skip(1)?; - let extra = r.u32()? as usize; - let extra_end = r.pos.checked_add(extra).filter(|&e| e <= r.data.len()).ok_or(Error::Truncated)?; - let mut l = Layer { - index, - rect: Rect { top, left, bottom, right }, - blend, - opacity, - fill_opacity: 255, - clipping, - hidden: flags & 2 != 0, - protect_transparency: flags & 1 != 0, - channels, - ..Default::default() - }; - // Layer mask data. - let mlen = r.u32()? as usize; - let mstart = r.pos; - if mlen >= 18 { - let rect = Rect { top: r.i32()?, left: r.i32()?, bottom: r.i32()?, right: r.i32()? }; - let default_color = r.u8()?; - let mflags = r.u8()?; - l.mask = Some(LayerMask { rect, default_color, disabled: mflags & 2 != 0, inverted: mflags & 4 != 0 }); - } - r.pos = mstart + mlen; - // Blending ranges. - let blen = r.u32()? as usize; - r.skip(blen)?; - l.name = r.pascal(4)?; - let mut pos = r.pos; - let data = r.data; - while let Some((key, start, end)) = next_block(data, &mut pos, extra_end, psb) { - l.keys.push(key); - let block = &data[start..end]; - // A malformed block only loses that block's information. - let _ = self.layer_block(&mut l, &key, block); - pos = end; - } - r.pos = extra_end; - Ok(l) - } - fn layer_block(&self, l: &mut Layer, key: &[u8; 4], b: &[u8]) -> Result<()> { let mut r = Reader::new(b); match key { @@ -287,7 +174,7 @@ impl Psd { let d = descriptor::read_descriptor(&mut r)?; let text = d.text("Txt ").unwrap_or_default().replace("\r\n", "\n").replace('\r', "\n"); let text = text.strip_suffix('\n').map(str::to_string).unwrap_or(text); - let style = d.raw("EngineData").map(|e| engine_data::text_style(&engine_data::parse(e))).unwrap_or_default(); + let style = d.raw("EngineData").map(|e| engine_data::text_style(&engine_data::parse_lossy(e))).unwrap_or_default(); let bounds = d.obj("bounds").or_else(|| d.obj("boundingBox")).and_then(|o| Some([o.num("Left")?, o.num("Top ")?, o.num("Rght")?, o.num("Btom")?])); l.text = Some(TextInfo { text, transform: t, style, bounds }); @@ -482,33 +369,166 @@ impl Psd { } } -/// The next additional-information block at `*pos` (signature `8BIM`/`8B64`, key, length): -/// returns (key, data start, data end). Skips up to 3 padding bytes before a signature. -fn next_block(data: &[u8], pos: &mut usize, end: usize, psb: bool) -> Option<([u8; 4], usize, usize)> { - let mut p = *pos; - for _ in 0..4 { - if p + 12 > end { - return None; +/// The header, colour mode data and merged image offset of a document whose layer and mask +/// section cannot be read: `None` when the merged image cannot be reached either. +fn flattened(data: &[u8]) -> Option<(craft_psd::Header, Vec, usize)> { + let head = craft_psd::head::HeadView::from_bytes(data).ok()?; + let at = usize::try_from(head.layer_section_offset).ok()?; + let len = if head.header.version.is_psb() { + u64::from_be_bytes(data.get(at..at + 8)?.try_into().ok()?) + } else { + u64::from(u32::from_be_bytes(data.get(at..at + 4)?.try_into().ok()?)) + }; + let field = if head.header.version.is_psb() { 8 } else { 4 }; + let merged = at.checked_add(field)?.checked_add(usize::try_from(len).ok()?)?; + (merged.checked_add(2)? <= data.len()).then(|| (head.header.clone(), head.color_mode_data.to_vec(), merged)) +} + +/// Linked-file blocks can be most of a file: leave them in the source, read in place. +fn linked(key: &[u8; 4], _len: u64) -> bool { + craft_psd::smart::is_linked_layer_key(key) +} + +/// Reads `data` with craft-psd. Where that loses what the old reader kept, it reads a copy with +/// the obstacle taken out, and the [`Splice`] maps the copy's offsets back into `data`: +/// - a damaged image resource (resources are not part of the model): no resources; +/// - damaged layer records in the section: none there, so a global `Lr16`/`Lr32`/`Layr` block +/// can still give the layers; +/// - a global layer block that starts with its own length (both layouts are accepted), or +/// that follows up to three stray bytes: the block without them. +fn read_file(data: &Arc<[u8]>) -> (std::result::Result, Splice) { + let read = |d: Arc<[u8]>| craft_psd::PsdFile::from_source_deferring(craft_psd::source::Source::new(d), linked, |_| Ok(false), |_| false).map(|(f, _)| f); + let layered = |f: &craft_psd::PsdFile| f.layer_info.as_ref().is_some_and(|i| !i.layers.is_empty()); + let retry = |copy: Option<(Vec, Splice)>, accept: &dyn Fn(&craft_psd::PsdFile) -> bool| { + let (copy, splice) = copy?; + read(copy.into()).ok().filter(|f| accept(f)).map(|f| (f, splice)) + }; + let first = read(data.clone()); + let got = match &first { + Ok(f) if layered(f) => None, + Ok(_) => retry(prefixed_layer_block(data), &layered), + Err(_) => retry(without_resources(data), &|_| true).or_else(|| retry(without_section_layers(data), &layered)), + }; + match got { + Some((file, splice)) => (Ok(file), splice), + None => (first, Splice::default()), + } +} + +/// A big-endian unsigned field of `width` bytes at `at`. +fn be(data: &[u8], at: usize, width: usize) -> Option { + let b = data.get(at..at.checked_add(width)?)?; + usize::try_from(b.iter().fold(0u64, |v, &b| v << 8 | u64::from(b))).ok() +} + +/// The length-field width of the layer section and its long blocks. +fn field(data: &[u8]) -> usize { + if data.get(4..6) == Some(&[0, 2]) { 8 } else { 4 } +} + +fn without_resources(data: &[u8]) -> Option<(Vec, Splice)> { + let res_at = be(data, 26, 4)?.checked_add(30)?; + let res_len = be(data, res_at, 4).filter(|&n| n > 0)?; + Splice::apply(data, res_at + 4, res_len, &[(res_at, 4)]) +} + +fn without_section_layers(data: &[u8]) -> Option<(Vec, Splice)> { + let head = craft_psd::head::HeadView::from_bytes(data).ok()?; + let ls = usize::try_from(head.layer_section_offset).ok()?; + let w = field(data); + let li_at = ls.checked_add(w)?; + let li_len = be(data, li_at, w).filter(|&n| n > 0)?; + Splice::apply(data, li_at + w, li_len, &[(li_at, w), (ls, w)]) +} + +/// The global layer block's repair, found by walking the top-level global blocks by their +/// declared lengths (so a linked file's payload is never searched): up to three stray bytes +/// before the first block, or the block's payload starting with its own length. +fn prefixed_layer_block(data: &[u8]) -> Option<(Vec, Splice)> { + let head = craft_psd::head::HeadView::from_bytes(data).ok()?; + let ls = usize::try_from(head.layer_section_offset).ok()?; + let w = field(data); + let end = be(data, ls, w)?.checked_add(ls + w)?.min(data.len()); + let li_at = ls + w; + let gm_at = be(data, li_at, w)?.checked_add(li_at + w)?; + let blocks = be(data, gm_at, 4)?.checked_add(gm_at + 4)?; + let mut pos = blocks; + let is_sig = |i: usize| matches!(data.get(i..i + 4), Some(b"8BIM" | b"8B64")); + // Stray bytes before the first block hide every block from craft-psd. + let mut lead = None; + while pos < end { + let skip = (0..=3).find(|&k| is_sig(pos + k))?; + let at = pos + skip; + // Leading bytes before the first block are recorded before its key is looked at. + if lead.is_none() && pos == blocks && skip > 0 { + lead = Some((pos, skip)); } - if &data[p..p + 4] == b"8BIM" || &data[p..p + 4] == b"8B64" { - break; + let key: [u8; 4] = data.get(at + 4..at + 8)?.try_into().ok()?; + let width = if craft_psd::tagged::uses_long_length(head.header.version, &key) { 8 } else { 4 }; + let len = be(data, at + 8, width)?; + let body = at + 8 + width; + if matches!(&key, b"Lr16" | b"Lr32" | b"Layr") { + if let Some((at, n)) = lead { + return Splice::apply(data, at, n, &[(ls, w)]); + } + // The payload's first field reads as a length that fits in it. + be(data, body, w).filter(|&n| n > 0 && n.checked_add(w).is_some_and(|e| e <= len))?; + return Splice::apply(data, body, w, &[(at + 8, width), (ls, w)]); } - p += 1; + pos = body.checked_add(len)?; + } + None +} + +/// A copy of the file with one range taken out, and the way from the copy's offsets back to the +/// original's. +#[derive(Debug, Clone, Copy, Default)] +struct Splice { + at: u64, + removed: u64, +} + +impl Splice { + fn map(self, offset: u64) -> u64 { + if offset >= self.at { offset + self.removed } else { offset } } - if p + 12 > end || !(&data[p..p + 4] == b"8BIM" || &data[p..p + 4] == b"8B64") { - return None; + + /// `data` without the `removed` bytes at `at`, the length fields at `fixes` (offset, width; + /// all before `at`) shortened to match. + fn apply(data: &[u8], at: usize, removed: usize, fixes: &[(usize, usize)]) -> Option<(Vec, Splice)> { + let tail = data.get(at.checked_add(removed)?..)?; + let mut copy = Vec::with_capacity(at + tail.len()); + copy.extend_from_slice(data.get(..at)?); + copy.extend_from_slice(tail); + for &(f, width) in fixes { + let v = (be(©, f, width)?.checked_sub(removed)? as u64).to_be_bytes(); + copy.get_mut(f..f + width)?.copy_from_slice(&v[8 - width..]); + } + Some((copy, Splice { at: at as u64, removed: removed as u64 })) } - let mut key = [0u8; 4]; - key.copy_from_slice(&data[p + 4..p + 8]); - let wide = - psb && matches!(&key, b"LMsk" | b"Lr16" | b"Lr32" | b"Layr" | b"Mt16" | b"Mt32" | b"Mtrn" | b"Alph" | b"FMsk" | b"lnk2" | b"FEid" | b"FXid" | b"PxSD"); - let mut r = Reader::at(&data[..end], p + 8); - let len = r.length(wide).ok()?; - let start = r.pos; - let stop = start.checked_add(len)?; - if stop > end { - return None; +} + +/// Whether the layer section's (unreadable) layer count is negative, which marks the merged +/// image's first extra channel as its transparency. +fn section_merged_alpha(data: &[u8]) -> bool { + let Ok(head) = craft_psd::head::HeadView::from_bytes(data) else { return false }; + let field = if head.header.version.is_psb() { 8 } else { 4 }; + let Some(at) = usize::try_from(head.layer_section_offset).ok().and_then(|a| a.checked_add(2 * field)) else { return false }; + let has_info = data.get(at - field..at).is_some_and(|l| l.iter().any(|&b| b != 0)); + has_info && data.get(at..at + 2).is_some_and(|c| i16::from_be_bytes([c[0], c[1]]) < 0) +} + +/// This crate's error for one from craft-psd. +fn error(e: &craft_psd::PsdError) -> Error { + match e { + craft_psd::PsdError::UnexpectedEof { .. } => Error::Truncated, + craft_psd::PsdError::InvalidSignature { .. } | craft_psd::PsdError::UnsupportedVersion(_) => Error::NotPsd, + craft_psd::PsdError::Unsupported(s) => Error::Unsupported(s.clone()), + other => Error::Invalid(other.to_string()), } - *pos = stop; - Some((key, start, stop)) +} + +/// A Pascal string's bytes in the system (Mac Roman) encoding; ASCII covers the common case. +fn mac_roman_string(b: &[u8]) -> String { + b.iter().map(|&b| if b < 0x80 { b as char } else { super::read::mac_roman(b) }).collect() } diff --git a/crates/psd/src/pixels.rs b/crates/psd/src/pixels.rs index 290a7b6f4..f9b7ca6f3 100644 --- a/crates/psd/src/pixels.rs +++ b/crates/psd/src/pixels.rs @@ -134,46 +134,36 @@ impl Psd { /// Undo ZIP prediction in place; the 32-bit scratch row is charged to `budget`. pub(crate) fn unpredict(&self, v: &mut [u8], w: usize, h: usize, budget: &mut Budget) -> Result<()> { - match self.depth { - 16 => { - for row in v.chunks_exact_mut(w * 2).take(h) { - let mut prev = 0u16; - for c in row.as_chunks_mut::<2>().0 { - let x = u16::from_be_bytes([c[0], c[1]]).wrapping_add(prev); - c.copy_from_slice(&x.to_be_bytes()); - prev = x; - } - } - } - 32 => { - // One scratch row for the whole plane, charged: a wide, short layer passes the - // decode's peak check and would otherwise allocate it on top. - let mut planar = budget.filled(w.checked_mul(4).ok_or_else(|| too_large(w, h))?, 0u8)?; - #[cfg(test)] - counters::bump(&counters::SCRATCH); - for row in v.chunks_exact_mut(w * 4).take(h) { - for i in 1..row.len() { - row[i] = row[i].wrapping_add(row[i - 1]); - } - // Bytes are stored plane by plane (all first bytes, then all second bytes…). - planar.copy_from_slice(row); - for x in 0..w { - for b in 0..4 { - row[x * 4 + b] = planar[b * w + x]; - } - } - } - budget.release(planar.len() as u64); - } - _ => { - for row in v.chunks_exact_mut(w).take(h) { - for i in 1..row.len() { - row[i] = row[i].wrapping_add(row[i - 1]); - } - } - } + // Preserve the reader's recovery behavior: decode only complete rows, at most h. + // The fallback depths historically used byte-wise prediction rather than packed bits. + let depth = match self.depth { + 16 => 16, + 32 => 32, + _ => 8, + }; + let rowb = w.checked_mul(usize::from(depth / 8)).ok_or_else(|| too_large(w, h))?; + if rowb == 0 { + return Ok(()); } - Ok(()) + let rows = (v.len() / rowb).min(h); + let layout = craft_psd::compression::PlaneLayout { + planes: 1, + width: w, + height: rows, + depth, + version: if self.psb { craft_psd::Version::Psb } else { craft_psd::Version::Psd }, + }; + let mut scratch = if depth == 32 { + let scratch = budget.filled(rowb, 0u8)?; + #[cfg(test)] + counters::bump(&counters::SCRATCH); + scratch + } else { + Vec::new() + }; + let result = craft_psd::compression::unpredict_with_scratch(&mut v[..rows * rowb], &layout, &mut scratch); + budget.release(scratch.len() as u64); + result.map_err(|e| Error::Invalid(e.to_string())) } /// Hand every sample of `raw` (`w`×`h`, row-major, in order) to `f` as a float. Samples a short @@ -505,42 +495,6 @@ pub(crate) fn unpack_bits(src: &[u8], row: usize, out: &mut Vec) -> Result<( Ok(()) } -/// PackBits encoding of one row. -pub(crate) fn pack_bits(src: &[u8]) -> Vec { - let mut out = vec![]; - let mut i = 0; - while i < src.len() { - // run of identical bytes - let mut run = 1; - while i + run < src.len() && src[i + run] == src[i] && run < 128 { - run += 1; - } - if run >= 2 { - out.push((1 - run as isize) as i8 as u8); - out.push(src[i]); - i += run; - continue; - } - // literal run - let start = i; - let mut n = 0; - while i < src.len() && n < 128 { - if i + 1 < src.len() && src[i + 1] == src[i] { - break; - } - i += 1; - n += 1; - } - if n == 0 { - i += 1; - n = 1; - } - out.push((n - 1) as u8); - out.extend_from_slice(&src[start..start + n]); - } - out -} - pub(crate) fn srgb_encode(v: f32) -> f32 { if v <= 0.003_130_8 { v * 12.92 } else { 1.055 * v.powf(1.0 / 2.4) - 0.055 } } diff --git a/crates/psd/src/read.rs b/crates/psd/src/read.rs index 9df7d8b63..307998066 100644 --- a/crates/psd/src/read.rs +++ b/crates/psd/src/read.rs @@ -85,7 +85,7 @@ impl<'a> Reader<'a> { } /// Mac OS Roman upper half (0x80..=0xFF), as published by the Unicode Consortium mapping table. -fn mac_roman(b: u8) -> char { +pub(crate) fn mac_roman(b: u8) -> char { const T: &str = "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄€‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ\u{F8FF}ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"; T.chars().nth((b - 0x80) as usize).unwrap_or('?') } diff --git a/crates/psd/src/tests.rs b/crates/psd/src/tests.rs index fd041138a..1f84f27b7 100644 --- a/crates/psd/src/tests.rs +++ b/crates/psd/src/tests.rs @@ -1,8 +1,10 @@ use super::write::*; use super::*; +use crate::pixels::srgb_encode; mod integration; mod opt; +mod shared_corpus; fn gradient(w: u32, h: u32) -> Vec<[f32; 4]> { (0..w * h).map(|i| [(i % w) as f32 / (w - 1).max(1) as f32, (i / w) as f32 / (h - 1).max(1) as f32, 0.25, 1.0]).collect() @@ -171,7 +173,7 @@ fn text_effects_fill_and_adjustments() { #[test] fn packbits_round_trip() { for src in [vec![], vec![1u8], vec![5; 300], (0..=255).collect::>(), vec![1, 1, 2, 3, 3, 3, 4, 5, 5]] { - let enc = pack_bits(&src); + let enc = craft_psd::compression::packbits::encode_vec(&src); let mut out = vec![]; unpack_bits(&enc, src.len(), &mut out).unwrap(); assert_eq!(out, src); @@ -519,3 +521,77 @@ fn a_failed_inflate_reports_its_status_not_its_output() { let Err(Error::Invalid(msg)) = crate::limits::inflate(&z, 1 << 21) else { panic!("the checksum fails") }; assert!(msg.len() < 100, "{} bytes", msg.len()); } + +#[test] +fn written_32_bit_documents_decode() { + // 32-bit samples are written as floats, raw or RLE, so both read back whole. + for rle in [true, false] { + let p = Psd::parse(write(&doc_with_layers(32, ColorMode::Rgb, rle))).expect("parse"); + assert_eq!(p.depth, 32); + assert!(p.composite().is_ok(), "rle={rle}"); + for i in 0..p.layers.len() { + assert!(p.layer_pixels(i, false).is_ok(), "rle={rle} layer {i}"); + } + } +} + +#[test] +fn deep_layers_go_in_their_global_block() { + for (depth, key) in [(16, b"Lr16"), (32, b"Lr32")] { + let bytes = write(&doc_with_layers(depth, ColorMode::Rgb, true)); + let file = craft_psd::PsdFile::from_bytes(&bytes).expect("parse"); + assert!( + matches!(file.layer_info_placement, craft_psd::LayerInfoPlacement::GlobalBlock { key: k, .. } if &k == key), + "{depth}-bit: {:?}", + file.layer_info_placement + ); + assert_eq!(Psd::parse(bytes).expect("parse").layers.len(), doc_with_layers(depth, ColorMode::Rgb, true).layers.len()); + } +} + +#[test] +fn rows_too_wide_for_rle_are_written_raw() { + // 20000 32-bit samples are 80000 bytes per row, past the 65535 an RLE row count holds. + let doc = |w: u32| { + let mut d = WDoc::new(w, 1); + d.depth = 32; + d.composite = Some(vec![[0.5, 0.25, 0.75, 1.0]; w as usize]); + d.layers.push(WLayer::solid("Wide", Rect::new(0, 0, w as i32, 1), [0.5, 0.25, 0.75, 1.0])); + d + }; + let want = Psd::parse(write(&doc(100))).expect("narrow").composite().expect("composite").data[0]; + let p = Psd::parse(write(&doc(20_000))).expect("parse"); + let c = p.composite().expect("composite"); + assert_eq!(c.data.len(), 20_000); + assert!(c.data.iter().all(|px| *px == want), "{:?} vs {want:?}", c.data[0]); + assert!(p.layer_pixels(0, false).is_ok()); +} + +#[test] +fn written_32_bit_color_samples_keep_their_range() { + // The reader keeps finite 32-bit samples outside 0..1; the writer must be able to + // produce those fixtures. Integer depths stay clamped. A layer is present so the + // merged transparency flag is set and alpha is read back. + let want = [2.0, -0.5, 0.25, 1.5]; + let mut d = WDoc::new(1, 1); + d.depth = 32; + d.rle = false; + d.composite = Some(vec![want]); + d.layers.push(WLayer::solid("HDR", Rect::new(0, 0, 1, 1), want)); + let bytes = write(&d); + for v in want { + assert!(bytes.windows(4).any(|w| w == v.to_be_bytes()), "missing the {v} sample"); + } + let p = Psd::parse(bytes).expect("parse"); + assert!(p.merged_alpha); + let c = p.composite().expect("composite"); + assert_eq!(c.data[0], [srgb_encode(2.0), srgb_encode(-0.5), srgb_encode(0.25), 1.5]); + assert_eq!(p.layer_pixels(0, false).expect("layer").data[0], c.data[0]); + + let mut d8 = WDoc::new(1, 1); + d8.composite = Some(vec![want]); + d8.layers.push(WLayer::solid("HDR", Rect::new(0, 0, 1, 1), want)); + let p8 = Psd::parse(write(&d8)).expect("parse 8-bit"); + let q = |x: f32| (x.clamp(0.0, 1.0) * 255.0).round() / 255.0; + assert_eq!(p8.composite().expect("composite").data[0], [q(2.0), q(-0.5), q(0.25), q(1.5)]); +} diff --git a/crates/psd/src/tests/opt.rs b/crates/psd/src/tests/opt.rs index 44bcec071..79e05a41b 100644 --- a/crates/psd/src/tests/opt.rs +++ b/crates/psd/src/tests/opt.rs @@ -385,7 +385,7 @@ fn stream(planes: &[Vec], w: usize, h: usize, depth: u16, comp: u16) -> Vec< match comp { 0 => planes.iter().for_each(|p| out.extend(p)), 1 => { - let rows: Vec> = planes.iter().flat_map(|p| p.chunks(rowb.max(1)).map(pack_bits)).collect(); + let rows: Vec> = planes.iter().flat_map(|p| p.chunks(rowb.max(1)).map(craft_psd::compression::packbits::encode_vec)).collect(); rows.iter().for_each(|r| out.extend((r.len() as u16).to_be_bytes())); rows.iter().for_each(|r| out.extend(r)); } @@ -650,3 +650,21 @@ fn placed_bake_solves_the_quad_once() { so.map([1.0, 1.0], 20.0, 10.0); assert_eq!(counters::take(&QUAD), 1); } + +#[test] +fn shared_unpredict_keeps_tail_bytes_and_refuses_unbudgeted_scratch() { + for depth in [8u16, 16, 32] { + let p = Psd { depth, ..base() }; + let (w, h) = (3, 2); + let row = w * usize::from(depth / 8); + let mut actual: Vec = (0..row * 3 + 1).map(|i| (i * 31 % 251) as u8).collect(); + let mut expected = actual.clone(); + ref_unpredict(depth, &mut expected, w, h); + p.unpredict(&mut actual, w, h, &mut Budget::new(u64::MAX)).unwrap(); + assert_eq!(actual, expected, "complete extra rows and partial tails stay untouched"); + } + let p = Psd { depth: 32, ..base() }; + let mut bytes = vec![0x31; 24]; + assert!(p.unpredict(&mut bytes, 3, 2, &mut Budget::new(11)).is_err()); + assert_eq!(bytes, vec![0x31; 24], "budget refusal precedes mutation"); +} diff --git a/crates/psd/src/tests/shared_corpus.rs b/crates/psd/src/tests/shared_corpus.rs new file mode 100644 index 000000000..1f5659187 --- /dev/null +++ b/crates/psd/src/tests/shared_corpus.rs @@ -0,0 +1,192 @@ +//! The reader over craft-psd's generated corpus (every colour mode, depth, compression and PSB): +//! the model matches the shared reader's records and its channel ranges hold the stored bytes. + +use crate::*; + +#[test] +fn every_generated_case_reads_like_craft_psd() { + let mut decoded = 0; + for (i, case) in craft_psd::testgen::all_cases().into_iter().enumerate() { + let bytes = case.file.to_bytes().expect("write"); + let shared = craft_psd::PsdFile::from_bytes(&bytes).expect("shared parse"); + let p = match Psd::parse(bytes.clone()) { + Ok(p) => p, + // Modes this reader does not show are refused cleanly, never half-read. + Err(Error::Unsupported(_)) => continue, + Err(e) => panic!("case {i}: {e}"), + }; + assert_eq!( + (p.width, p.height, p.depth, p.psb), + (shared.header.width, shared.header.height, shared.header.depth, shared.header.version.is_psb()), + "case {i}" + ); + let records = shared.layer_info.as_ref().map_or(&[][..], |l| &l.layers[..]); + assert_eq!(p.layers.len(), records.len(), "case {i}"); + for (l, rec) in p.layers.iter().zip(records) { + assert_eq!(l.blend, rec.blend_mode.key(), "case {i}"); + assert_eq!(l.channels.len(), rec.channels.len(), "case {i}"); + for (c, rc) in l.channels.iter().zip(&rec.channels) { + assert_eq!(c.id, rc.id, "case {i}"); + // The range covers the compression field and the stored bytes after it. + assert!(c.len == 0 || c.len == rc.data.len() + 2, "case {i}"); + assert!(c.len == 0 || bytes[c.offset + 2..c.offset + c.len] == rc.data[..], "case {i}"); + } + } + // Decoding reads those ranges: it ends in pixels or a clean error, as before the cutover. + if p.composite().is_ok() { + decoded += 1; + } + for li in 0..p.layers.len() { + let _ = p.layer_pixels(li, false); + } + } + assert!(decoded > 100, "{decoded} composites decoded"); +} + +#[test] +fn a_damaged_layer_section_keeps_the_merged_image() { + let case = craft_psd::testgen::all_cases().into_iter().find(|c| c.file.layer_info.as_ref().is_some_and(|l| !l.layers.is_empty())).expect("a layered case"); + let mut bytes = case.file.to_bytes().expect("write"); + let head = craft_psd::head::HeadView::from_bytes(&bytes).expect("head"); + // Overwrite the first layer record's signature. + let at = head.layer_section_offset as usize + if head.header.version.is_psb() { 16 } else { 8 } + 2 + 16; + let channels = usize::from(u16::from_be_bytes([bytes[at], bytes[at + 1]])); + let sig = at + 2 + channels * if head.header.version.is_psb() { 10 } else { 6 }; + assert_eq!(&bytes[sig..sig + 4], b"8BIM"); + bytes[sig..sig + 4].copy_from_slice(b"XXXX"); + let p = Psd::parse(bytes).expect("flattened"); + assert!(p.layers.is_empty()); + assert!(p.warnings.iter().any(|w| w.contains("Layers could not be read")), "{:?}", p.warnings); + assert!(p.composite().is_ok()); +} + +/// The first generated case that is layered and passes `keep`, with its bytes. +fn layered(keep: impl Fn(&craft_psd::PsdFile) -> bool) -> Vec { + let case = craft_psd::testgen::all_cases() + .into_iter() + .find(|c| c.file.layer_info.as_ref().is_some_and(|l| !l.layers.is_empty()) && keep(&c.file)) + .expect("a layered case"); + case.file.to_bytes().expect("write") +} + +#[test] +fn a_damaged_resource_keeps_the_layers() { + let intact = layered(|f| f.header.depth == 8 && !f.resources.is_empty()); + let want = Psd::parse(intact.clone()).expect("intact"); + let mut bytes = intact; + // The first resource: signature, id, padded Pascal name, then its length, made to run off the end. + let res_at = 30 + u32::from_be_bytes(bytes[26..30].try_into().unwrap()) as usize; + let name = 1 + usize::from(bytes[res_at + 4 + 6]); + let len_at = res_at + 4 + 6 + name + name % 2; + bytes[len_at..len_at + 4].copy_from_slice(&0x7fff_fff0u32.to_be_bytes()); + let p = Psd::parse(bytes).expect("parse"); + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + assert_eq!(p.layers.len(), want.layers.len()); + assert_eq!(p.merged_alpha, want.merged_alpha); + assert_eq!(p.composite().expect("composite").data, want.composite().expect("composite").data); + for i in 0..p.layers.len() { + assert_eq!(p.layers[i].name, want.layers[i].name); + assert_eq!(p.layer_pixels(i, false).map(|l| l.data).ok(), want.layer_pixels(i, false).map(|l| l.data).ok(), "layer {i}"); + } +} + +#[test] +fn a_damaged_16_bit_layer_block_is_reported() { + let intact = layered(|f| f.header.depth == 16 && matches!(f.layer_info_placement, craft_psd::LayerInfoPlacement::GlobalBlock { .. })); + let want = Psd::parse(intact.clone()).expect("intact"); + assert!(want.merged_alpha, "the generated 16-bit cases carry merged alpha"); + let mut bytes = intact; + let at = bytes.windows(8).position(|w| w == b"8BIMLr16").expect("Lr16 block"); + let psb = want.psb; + // Block header, then the layer count and the first record's rect: its channel count follows. + let channels = at + 8 + if psb { 8 } else { 4 } + 2 + 16; + bytes[channels..channels + 2].copy_from_slice(&u16::MAX.to_be_bytes()); + let p = Psd::parse(bytes).expect("flattened"); + assert!(p.layers.is_empty()); + assert!(p.warnings.iter().any(|w| w.contains("Layers could not be read")), "{:?}", p.warnings); + assert_eq!(p.merged_alpha, want.merged_alpha); + assert_eq!(p.composite().expect("composite").data, want.composite().expect("composite").data); +} + +/// `bytes` with `insert` put at `at`, the length fields at `fixes` (offset, width) grown to match. +fn insert(bytes: &[u8], at: usize, insert: &[u8], fixes: &[(usize, usize)]) -> Vec { + let mut out = [&bytes[..at], insert, &bytes[at..]].concat(); + for &(f, w) in fixes { + let v = out[f..f + w].iter().fold(0u64, |v, &b| v << 8 | u64::from(b)) + insert.len() as u64; + out[f..f + w].copy_from_slice(&v.to_be_bytes()[8 - w..]); + } + out +} + +/// A 16-bit layered case (layers in `Lr16`), its parse, the layer section offset, the length +/// field width and the `Lr16` block's offset. +fn deep() -> (Vec, Psd, usize, usize, usize) { + let bytes = layered(|f| f.header.depth == 16 && matches!(f.layer_info_placement, craft_psd::LayerInfoPlacement::GlobalBlock { .. })); + let want = Psd::parse(bytes.clone()).expect("intact"); + let ls = craft_psd::head::HeadView::from_bytes(&bytes).expect("head").layer_section_offset as usize; + let w = if want.psb { 8 } else { 4 }; + let at = bytes.windows(8).position(|x| x[4..] == *b"Lr16" && matches!(&x[..4], b"8BIM" | b"8B64")).expect("Lr16"); + (bytes, want, ls, w, at) +} + +fn same_layers(p: &Psd, want: &Psd) { + assert!(p.warnings.is_empty(), "{:?}", p.warnings); + assert_eq!(p.layers.len(), want.layers.len()); + assert_eq!(p.merged_alpha, want.merged_alpha); + assert_eq!(p.composite().expect("composite").data, want.composite().expect("composite").data); + for i in 0..p.layers.len() { + assert_eq!(p.layers[i].name, want.layers[i].name); + assert_eq!(p.layer_pixels(i, false).map(|l| l.data).ok(), want.layer_pixels(i, false).map(|l| l.data).ok(), "layer {i}"); + } +} + +#[test] +fn a_length_prefixed_16_bit_layer_block_reads() { + let (bytes, want, ls, w, at) = deep(); + let body = at + 8 + w; + let len = u64::try_from(bytes.len()).unwrap().min(u64::from(u32::MAX)); + let block_len = bytes[at + 8..body].iter().fold(0u64, |v, &b| v << 8 | u64::from(b)); + assert!(block_len < len); + let prefix = &block_len.to_be_bytes()[8 - w..]; + let p = Psd::parse(insert(&bytes, body, prefix, &[(at + 8, w), (ls, w)])).expect("parse"); + same_layers(&p, &want); +} + +#[test] +fn damaged_section_records_fall_back_to_the_16_bit_block() { + let (bytes, want, ls, w, _) = deep(); + // A section layer info claiming one record that is cut short. + let li_at = ls + w; + assert!(bytes[li_at..li_at + w].iter().all(|&b| b == 0), "the generated file keeps its layers only in Lr16"); + let p = Psd::parse(insert(&bytes, li_at + w, &[0, 1, 0, 0, 0, 0], &[(li_at, w), (ls, w)])).expect("parse"); + same_layers(&p, &want); +} + +#[test] +fn a_stray_byte_before_the_global_blocks_is_skipped() { + let (bytes, want, ls, w, _) = deep(); + // Section layer info (empty) and global mask, then the first global block. + let li_at = ls + w; + let gm_at = li_at + w + bytes[li_at..li_at + w].iter().fold(0usize, |v, &b| v << 8 | usize::from(b)); + let first = gm_at + 4 + u32::from_be_bytes(bytes[gm_at..gm_at + 4].try_into().unwrap()) as usize; + assert_eq!(&bytes[first..first + 4], b"8BIM"); + let p = Psd::parse(insert(&bytes, first, &[0], &[(ls, w)])).expect("parse"); + same_layers(&p, &want); +} + +#[test] +fn stray_bytes_before_a_leading_16_bit_block_are_skipped() { + let (bytes, want, ls, w, at) = deep(); + let li_at = ls + w; + let gm_at = li_at + w + bytes[li_at..li_at + w].iter().fold(0usize, |v, &b| v << 8 | usize::from(b)); + let first = gm_at + 4 + u32::from_be_bytes(bytes[gm_at..gm_at + 4].try_into().unwrap()) as usize; + // Drop the blocks before `Lr16` so it comes first, then put 1 to 3 stray bytes before it. + let mut lead = [&bytes[..first], &bytes[at..]].concat(); + let lm = lead[ls..ls + w].iter().fold(0u64, |v, &b| v << 8 | u64::from(b)) - (at - first) as u64; + lead[ls..ls + w].copy_from_slice(&lm.to_be_bytes()[8 - w..]); + assert_eq!(&lead[first + 4..first + 8], b"Lr16"); + for n in 1..=3 { + let p = Psd::parse(insert(&lead, first, &vec![0; n], &[(ls, w)])).expect("parse"); + same_layers(&p, &want); + } +} diff --git a/crates/psd/src/write.rs b/crates/psd/src/write.rs index a92e76dcd..e5ec285b8 100644 --- a/crates/psd/src/write.rs +++ b/crates/psd/src/write.rs @@ -1,10 +1,18 @@ //! A minimal Photoshop document writer, per the same specification as the reader: RGB, CMYK or //! Grayscale, 8 or 16 bits, raw or RLE channels, pixel layers with layer masks, groups and any //! additional-information blocks (helpers below build text, effects, fill and adjustment -//! blocks). Used to generate test fixtures; not a full exporter. +//! blocks). Used to generate test fixtures; not a full exporter. The file itself is laid out and +//! encoded by craft-psd ([`craft_psd::PsdFile::to_bytes`]). + +use craft_psd::layer::{LayerInfo, LayerRecord}; +use craft_psd::tagged::{SectionType, TaggedBlock}; +use craft_psd::{ + BlendMode, BlendingRanges, ChannelData, Compression, GlobalLayerMask, Header, ImageData, LayerFlags, LayerInfoPlacement, MaskData, PsdFile, Version, +}; use crate::descriptor::{self, DValue, Descriptor, put_u16, put_u32, put_utf16}; -use crate::{ColorMode, Rect, Section, engine_data, pack_bits}; +use crate::limits::finite_sample; +use crate::{ColorMode, Rect, Section, engine_data}; /// A layer mask for [`WLayer`]. #[derive(Clone, Debug)] @@ -93,7 +101,7 @@ impl WLayer { pub struct WDoc { pub width: u32, pub height: u32, - /// 8 or 16. + /// 8, 16 or 32 (32-bit samples are written as floats). pub depth: u16, /// Rgb, Cmyk or Grayscale. pub mode: ColorMode, @@ -128,10 +136,14 @@ fn mode_channels(mode: ColorMode, p: [f32; 4]) -> Vec { } fn encode_samples(v: &[f32], depth: u16) -> Vec { - let mut out = Vec::with_capacity(v.len() * if depth == 16 { 2 } else { 1 }); + let mut out = Vec::with_capacity(v.len() * usize::from(depth.div_ceil(8))); for &x in v { - let x = x.clamp(0.0, 1.0); - if depth == 16 { + // Integer depths are stored in 0..1. 32-bit documents keep finite samples + // outside that range (HDR); NaN and infinities use the reader's mapping. + let x = if depth == 32 { finite_sample(x) } else { x.clamp(0.0, 1.0) }; + if depth == 32 { + out.extend_from_slice(&x.to_be_bytes()); + } else if depth == 16 { put_u16(&mut out, (x * 65535.0).round() as u16); } else { out.push((x * 255.0).round() as u8); @@ -140,139 +152,81 @@ fn encode_samples(v: &[f32], depth: u16) -> Vec { out } -/// One channel's data (compression field + data) for a `w`×`h` plane. -fn channel_data(v: &[f32], w: usize, h: usize, depth: u16, rle: bool) -> Vec { - let raw = encode_samples(v, depth); - let mut out = vec![]; - let rowb = raw.len() / h.max(1); - if !rle || w == 0 || h == 0 { - put_u16(&mut out, 0); - out.extend_from_slice(&raw); - return out; - } - put_u16(&mut out, 1); - let rows: Vec> = raw.chunks(rowb.max(1)).map(pack_bits).collect(); - for r in &rows { - put_u16(&mut out, r.len() as u16); - } - for r in rows { - out.extend_from_slice(&r); - } - out +/// The layer and merged-image compression of `doc`. +fn compression(doc: &WDoc) -> Compression { + if doc.rle { Compression::Rle } else { Compression::Raw } } -fn pascal4(out: &mut Vec, s: &str) { - let b: Vec = s.bytes().map(|c| if c < 0x80 { c } else { b'?' }).take(255).collect(); - out.push(b.len() as u8); - out.extend_from_slice(&b); - let total = 1 + b.len(); - out.resize(out.len() + total.div_ceil(4) * 4 - total, 0); +/// One channel of a `w`×`h` plane, encoded by craft-psd. An empty plane is written raw. +fn channel(id: i16, v: &[f32], w: usize, h: usize, doc: &WDoc) -> craft_psd::Result { + let c = if w == 0 || h == 0 { Compression::Raw } else { compression(doc) }; + let samples = encode_samples(v, doc.depth); + // A PSD RLE row holds at most 65535 bytes; a wider plane is written raw. + ChannelData::encode(id, c, &samples, w, h, doc.depth, Version::Psd) + .or_else(|_| ChannelData::encode(id, Compression::Raw, &samples, w, h, doc.depth, Version::Psd)) } -fn block(out: &mut Vec, key: &[u8; 4], data: &[u8]) { - out.extend_from_slice(b"8BIM"); - out.extend_from_slice(key); - let padded = data.len().div_ceil(2) * 2; - put_u32(out, padded as u32); - out.extend_from_slice(data); - out.resize(out.len() + padded - data.len(), 0); +/// The `luni` block: the UTF-16 length and code units, unpadded, as this writer has always +/// written it (`TaggedBlock::unicode_name` adds a terminator, which would change exported files). +fn unicode_name(name: &str) -> TaggedBlock { + let units: Vec = name.encode_utf16().collect(); + let mut data = (units.len() as u32).to_be_bytes().to_vec(); + data.extend(units.iter().flat_map(|u| u.to_be_bytes())); + TaggedBlock::new(*b"luni", data) } -fn layer_info(doc: &WDoc) -> Vec { - let mut out = vec![]; - out.extend_from_slice(&(-(doc.layers.len() as i16)).to_be_bytes()); - let mut chan_data: Vec)>> = vec![]; - for l in &doc.layers { - let (w, h) = (l.rect.width() as usize, l.rect.height() as usize); - let mut chans: Vec<(i16, Vec)> = vec![]; - let n = w * h; - let alpha: Vec = l.pixels.iter().take(n).map(|p| p[3]).collect(); - chans.push((-1, channel_data(&alpha, w, h, doc.depth, doc.rle))); - let cc = doc.mode.color_channels(); - let planes: Vec> = l.pixels.iter().take(n).map(|p| mode_channels(doc.mode, *p)).collect(); - for c in 0..cc { - let plane: Vec = planes.iter().map(|v| v[c]).collect(); - chans.push((c as i16, channel_data(&plane, w, h, doc.depth, doc.rle))); - } - if let Some(m) = &l.mask { - chans.push((-2, channel_data(&m.data, m.rect.width() as usize, m.rect.height() as usize, doc.depth, doc.rle))); - } - // record - for v in [l.rect.top, l.rect.left, l.rect.bottom, l.rect.right] { - out.extend_from_slice(&v.to_be_bytes()); - } - put_u16(&mut out, chans.len() as u16); - for (id, d) in &chans { - out.extend_from_slice(&id.to_be_bytes()); - put_u32(&mut out, d.len() as u32); - } - out.extend_from_slice(b"8BIM"); - out.extend_from_slice(&l.blend); - out.push(l.opacity); - out.push(l.clipping as u8); - let mut flags = 8u8; - if l.hidden { - flags |= 2; - } - out.push(flags); - out.push(0); - let mut extra = vec![]; - match &l.mask { - Some(m) => { - put_u32(&mut extra, 20); - for v in [m.rect.top, m.rect.left, m.rect.bottom, m.rect.right] { - extra.extend_from_slice(&v.to_be_bytes()); - } - extra.push(m.default_color); - extra.push(if m.disabled { 2 } else { 0 }); - extra.extend_from_slice(&[0, 0]); - } - None => put_u32(&mut extra, 0), - } - put_u32(&mut extra, 0); // blending ranges - pascal4(&mut extra, &l.name); - let luni = unicode_plain(&l.name); - block(&mut extra, b"luni", &luni); - match l.section { - Section::Layer => {} - s => { - let mut d = vec![]; - put_u32( - &mut d, - match s { - Section::OpenFolder => 1, - Section::ClosedFolder => 2, - _ => 3, - }, - ); - d.extend_from_slice(b"8BIM"); - d.extend_from_slice(&l.blend); - block(&mut extra, b"lsct", &d); - } - } - for (k, d) in &l.blocks { - block(&mut extra, k, d); - } - put_u32(&mut out, extra.len() as u32); - out.extend_from_slice(&extra); - chan_data.push(chans); - } - for chans in chan_data { - for (_, d) in chans { - out.extend_from_slice(&d); - } - } - if out.len() % 2 == 1 { - out.push(0); - } - out +/// A legacy Pascal name: ASCII, anything else as `?`, at most 255 bytes. +fn legacy_name(s: &str) -> Vec { + s.bytes().map(|c| if c < 0x80 { c } else { b'?' }).take(255).collect() } -/// A Unicode string without the terminating NUL (the layer-name `luni` form). -fn unicode_plain(s: &str) -> Vec { - let mut out = vec![]; - put_utf16(&mut out, s, false); - out +fn psd_rect(r: Rect) -> craft_psd::Rect { + craft_psd::Rect { top: r.top, left: r.left, bottom: r.bottom, right: r.right } +} + +/// The layer record of `l`: pixels, mask, name, section and blocks. +fn record(l: &WLayer, doc: &WDoc) -> craft_psd::Result { + let (w, h) = (l.rect.width() as usize, l.rect.height() as usize); + let n = w * h; + let alpha: Vec = l.pixels.iter().take(n).map(|p| p[3]).collect(); + let mut channels = vec![channel(-1, &alpha, w, h, doc)?]; + let planes: Vec> = l.pixels.iter().take(n).map(|p| mode_channels(doc.mode, *p)).collect(); + for c in 0..doc.mode.color_channels() { + let plane: Vec = planes.iter().map(|v| v[c]).collect(); + channels.push(channel(c as i16, &plane, w, h, doc)?); + } + let mut mask = MaskData::None; + if let Some(m) = &l.mask { + channels.push(channel(-2, &m.data, m.rect.width() as usize, m.rect.height() as usize, doc)?); + mask = MaskData::Mask(craft_psd::LayerMask::new(psd_rect(m.rect), m.default_color, if m.disabled { 2 } else { 0 })); + } + let mut flags = LayerFlags(8); + flags.set_hidden(l.hidden); + let mut blocks = vec![unicode_name(&l.name)]; + let kind = match l.section { + Section::Layer => None, + Section::OpenFolder => Some(SectionType::OpenFolder), + Section::ClosedFolder => Some(SectionType::ClosedFolder), + Section::Divider => Some(SectionType::BoundingDivider), + }; + if let Some(kind) = kind { + blocks.push(TaggedBlock::section_divider(kind, Some(BlendMode::from_key(l.blend)), None)); + } + blocks.extend(l.blocks.iter().map(|(k, d)| TaggedBlock::new(*k, d.clone()))); + Ok(LayerRecord { + rect: psd_rect(l.rect), + channels, + blend_mode: BlendMode::from_key(l.blend), + opacity: l.opacity, + clipping: u8::from(l.clipping), + flags, + filler: 0, + mask, + blending_ranges: BlendingRanges::default(), + name: legacy_name(&l.name), + blocks, + extra_trailing: vec![], + }) } /// Normal "over" of the visible pixel layers (groups ignored), straight alpha. @@ -298,76 +252,55 @@ fn flatten(doc: &WDoc) -> Vec<[f32; 4]> { acc } -/// Serialise a document. +/// Serialise a document with craft-psd. pub fn write(doc: &WDoc) -> Vec { + // Every input `WDoc` describes is in range for the writer; a failure is a bug in the caller. + #[allow(clippy::expect_used)] + build(doc).and_then(|f| f.to_bytes()).expect("a WDoc is always writable") +} + +fn build(doc: &WDoc) -> craft_psd::Result { let cc = doc.mode.color_channels(); - let mut out = vec![]; - out.extend_from_slice(b"8BPS"); - put_u16(&mut out, 1); - out.extend_from_slice(&[0; 6]); - put_u16(&mut out, (cc + 1) as u16); - put_u32(&mut out, doc.height); - put_u32(&mut out, doc.width); - put_u16(&mut out, doc.depth); - put_u16(&mut out, doc.mode.to_u16()); - put_u32(&mut out, 0); // colour mode data - put_u32(&mut out, 0); // image resources - // Layer and mask information. - let mut lm = vec![]; - if !doc.layers.is_empty() { - let li = layer_info(doc); - if doc.depth == 16 { - put_u32(&mut lm, 0); - put_u32(&mut lm, 0); // global layer mask info - let mut padded = li; - while !padded.len().is_multiple_of(4) { - padded.push(0); - } - lm.extend_from_slice(b"8BIM"); - lm.extend_from_slice(b"Lr16"); - put_u32(&mut lm, padded.len() as u32); - lm.extend_from_slice(&padded); - } else { - put_u32(&mut lm, li.len() as u32); - lm.extend_from_slice(&li); - put_u32(&mut lm, 0); - } - if !doc.linked.is_empty() { - let d = linked_block(&doc.linked); - lm.extend_from_slice(b"8BIM"); - lm.extend_from_slice(b"lnk2"); - put_u32(&mut lm, d.len() as u32); - lm.extend_from_slice(&d); - } + let header = Header::new(Version::Psd, doc.width, doc.height, (cc + 1) as u16, doc.depth, craft_psd::ColorMode::from_u16(doc.mode.to_u16())); + let layers = doc.layers.iter().map(|l| record(l, doc)).collect::>>()?; + let has_layers = !layers.is_empty(); + let mut global_blocks = vec![]; + if has_layers && !doc.linked.is_empty() { + global_blocks.push(TaggedBlock::new(*b"lnk2", linked_block(&doc.linked))); } - put_u32(&mut out, lm.len() as u32); - out.extend_from_slice(&lm); // Merged image. let comp = doc.composite.clone().unwrap_or_else(|| flatten(doc)); - let w = doc.width as usize; let planes: Vec> = comp.iter().map(|p| mode_channels(doc.mode, *p)).collect(); - let mut chans: Vec> = (0..cc).map(|c| planes.iter().map(|v| v[c]).collect()).collect(); - chans.push(comp.iter().map(|p| p[3]).collect()); - if doc.rle { - put_u16(&mut out, 1); - let rows: Vec>> = - chans.iter().map(|c| encode_samples(c, doc.depth).chunks((w * if doc.depth == 16 { 2 } else { 1 }).max(1)).map(pack_bits).collect()).collect(); - for c in &rows { - for r in c { - put_u16(&mut out, r.len() as u16); - } - } - for c in rows { - for r in c { - out.extend_from_slice(&r); - } - } - } else { - put_u16(&mut out, 0); - for c in &chans { - out.extend_from_slice(&encode_samples(c, doc.depth)); - } + let mut merged = vec![]; + for c in 0..cc { + merged.extend(encode_samples(&planes.iter().map(|v| v[c]).collect::>(), doc.depth)); } + merged.extend(encode_samples(&comp.iter().map(|p| p[3]).collect::>(), doc.depth)); + let image_data = ImageData::encode(compression(doc), &merged, &header).or_else(|_| ImageData::encode(Compression::Raw, &merged, &header))?; + Ok(PsdFile { + header, + color_mode_data: vec![], + resources: vec![], + layer_info: has_layers.then_some(LayerInfo { merged_alpha: true, layers, padding: None }), + // 16- and 32-bit layers go in an `Lr16` / `Lr32` block, as Photoshop writes them. + layer_info_placement: match doc.depth { + 16 | 32 if has_layers => { + LayerInfoPlacement::GlobalBlock { index: 0, signature: *b"8BIM", key: craft_psd::tiff::layer_info_key(doc.depth), padding: None } + } + _ => LayerInfoPlacement::Section, + }, + global_layer_mask: has_layers.then(GlobalLayerMask::default), + global_blocks, + layer_mask_trailing: vec![], + image_data, + write_as_psb: false, + }) +} + +/// A Unicode string without the terminating NUL (the layer-name `luni` form). +fn unicode_plain(s: &str) -> Vec { + let mut out = vec![]; + put_utf16(&mut out, s, false); out } diff --git a/crates/raster/Cargo.toml b/crates/raster/Cargo.toml index 7cd4fbe5a..9e11b781d 100644 --- a/crates/raster/Cargo.toml +++ b/crates/raster/Cargo.toml @@ -10,6 +10,7 @@ rust-version.workspace = true workspace = true [dependencies] +craft-exr = { workspace = true } effectcraft-geom = { workspace = true } effectcraft-color = { workspace = true } rayon = { workspace = true } diff --git a/crates/raster/src/channels3d.rs b/crates/raster/src/channels3d.rs index ae2d38303..05473ca80 100644 --- a/crates/raster/src/channels3d.rs +++ b/crates/raster/src/channels3d.rs @@ -66,36 +66,19 @@ impl AuxChannels { /// The layers of the channels (OpenEXR layers: the name before the last `.`; `""` for the /// unnamed layer), in channel order. pub fn layers(&self) -> Vec<&str> { - let mut out: Vec<&str> = vec![]; - for (n, _) in &self.channels { - let (layer, _) = split_channel(n); - if !out.contains(&layer) { - out.push(layer); - } - } - out + craft_exr::channels::layers(self.channels.iter().map(|(n, _)| n.as_str())) } /// A layer's channels as the names to show in red, green, blue and alpha (`""` = none): /// its R, G, B, A channels (or red / green / blue / alpha, X / Y / Z, U / V); a layer of one /// channel (depth, an ID) shows it in all three colours. pub fn layer_rgba(&self, layer: &str) -> [String; 4] { - let chans: Vec<&str> = self.channels.iter().map(|(n, _)| n.as_str()).filter(|n| split_channel(n).0 == layer).collect(); - let pick = |names: &[&str]| -> String { - chans.iter().find(|c| names.iter().any(|n| split_channel(c).1.eq_ignore_ascii_case(n))).map_or(String::new(), |c| c.to_string()) - }; - if let [one] = chans.as_slice() { - return [one.to_string(), one.to_string(), one.to_string(), String::new()]; - } - [pick(&["R", "red", "X", "U"]), pick(&["G", "green", "Y", "V"]), pick(&["B", "blue", "Z"]), pick(&["A", "alpha"])] + craft_exr::channels::layer_rgba(self.channels.iter().map(|(n, _)| n.as_str()), layer) + .map(|i| i.and_then(|i| self.channels.get(i)).map_or(String::new(), |(n, _)| n.clone())) } } -/// A channel name's layer and channel: `diffuse.R` → (`diffuse`, `R`), `ViewLayer.Combined.R` -/// → (`ViewLayer.Combined`, `R`), `Z` → (`""`, `Z`). -pub fn split_channel(name: &str) -> (&str, &str) { - name.rsplit_once('.').unwrap_or(("", name)) -} +pub use craft_exr::channels::split_channel; impl AuxChannels { pub fn depth(&self) -> Option<&[f32]> { @@ -206,42 +189,7 @@ impl AuxChannels { } } -/// MurmurHash3 x86 32-bit (public-domain algorithm by Austin Appleby). -pub fn murmur3_32(data: &[u8], seed: u32) -> u32 { - const C1: u32 = 0xcc9e_2d51; - const C2: u32 = 0x1b87_3593; - let mut h = seed; - let (chunks, tail) = data.as_chunks::<4>(); - for c in chunks { - let mut k = u32::from_le_bytes([c[0], c[1], c[2], c[3]]); - k = k.wrapping_mul(C1).rotate_left(15).wrapping_mul(C2); - h ^= k; - h = h.rotate_left(13).wrapping_mul(5).wrapping_add(0xe654_6b64); - } - let mut k = 0u32; - for (i, b) in tail.iter().enumerate() { - k ^= (*b as u32) << (8 * i); - } - if !tail.is_empty() { - k = k.wrapping_mul(C1).rotate_left(15).wrapping_mul(C2); - h ^= k; - } - h ^= data.len() as u32; - h ^= h >> 16; - h = h.wrapping_mul(0x85eb_ca6b); - h ^= h >> 13; - h = h.wrapping_mul(0xc2b2_ae35); - h ^= h >> 16; - h -} - -/// Cryptomatte hash of a name (the manifest value). -pub fn crypto_hash(name: &str) -> u32 { - let h = murmur3_32(name.as_bytes(), 0); - // Keep the float finite and normal: flip the low exponent bit when it is all 0s or 1s. - let e = (h >> 23) & 0xff; - if e == 0 || e == 255 { h ^ (1 << 23) } else { h } -} +pub use craft_exr::cryptomatte::{hash as crypto_hash, murmur3_32}; /// The ID float stored in Cryptomatte channels for a hash. pub fn crypto_float(hash: u32) -> f32 { diff --git a/crates/render/src/audio.rs b/crates/render/src/audio.rs index 2c1538133..a19802eb7 100644 --- a/crates/render/src/audio.rs +++ b/crates/render/src/audio.rs @@ -12,8 +12,11 @@ //! pre-roll of earlier audio and only the block's tail is kept — so preview playback and export //! produce identical samples. //! -//! Time-stretched layers are resampled nearest-sample; reversed (negative stretch) layers are -//! silent for now. +//! Time-stretched layers are resampled linearly, so pitch follows the speed. A reversed layer +//! (negative stretch, Layer > Time > Time-Reverse Layer) plays its audio backwards at the same +//! speed: comp sample `k` plays the source just before layer time `layer_time(k)`, so at -100 % +//! with the start at the out point (After Effects' layout) it is the exact mirror of the +//! layer's span. Backwards on a reversed layer plays it forwards again. use effectcraft_effects::Params; use effectcraft_effects::audio_fx; @@ -24,9 +27,18 @@ use crate::{EvalCtx, ExprHost, FootageSource}; const MAX_DEPTH: usize = 16; -/// The fastest a layer's audio plays (a Stretch of 1%). +/// Fastest a layer's audio plays (source samples per comp sample): 1 % stretch, the smallest +/// Time Stretch accepts. The mix plays the clamped stretch (`Layer::effective_stretch`, #3247), +/// so a layer is never faster; a faster speed would be silent instead of reading unbounded +/// source: a last-resort guard. const MAX_SPEED: f64 = 100.0; +/// Most source sample frames one read asks a footage item or precomp for; a longer read is made +/// in pieces, so memory stays bounded however fast a layer plays and however deep stretched +/// precomps nest. The work is not bounded: each 1 % precomp level still reads 100 times its +/// span. +pub(crate) const MAX_READ: usize = 1 << 18; + /// The most effect preroll (history before a block) mixed, in seconds, across a layer's effects. const MAX_PREROLL_SECONDS: f64 = 30.0; @@ -82,6 +94,11 @@ fn generates(l: &Layer) -> bool { audio_effect_groups(l).any(|(id, _)| audio_fx::generates_audio(id)) } +/// Does an enabled audio effect (Backwards) play the layer's [in, out) span reversed? +pub fn plays_backwards(l: &Layer) -> bool { + audio_effect_groups(l).any(|(id, _)| audio_fx::reverses(id)) +} + /// Does the layer contribute to the mix (Audio switch on and something to hear)? pub fn audible(project: &Project, l: &Layer) -> bool { l.switches.audio @@ -118,6 +135,13 @@ fn animated(g: &effectcraft_project::PropGroup) -> bool { }) } +/// The clock (seconds) a layer's audio effects run on at comp time `t` (oscillator phase): comp +/// time since the layer's start. It advances one sample per sample at any stretch, forwards or +/// reversed, so blocks join up; at 100 % it is the layer time. +fn fx_clock(l: &Layer, t: Tick) -> f64 { + Tick(t.0.saturating_sub(l.start_time.0)).seconds() +} + fn sample_tick(i: i64, rate: u32) -> Tick { // Keep the requested sample when the rate does not divide the tick clock. let t = Tick::from_units(i, i64::from(rate)); @@ -143,7 +167,7 @@ impl MixEnv<'_> { /// The layer's own (pre-effect) audio for comp sample indices `i0 .. i0 + n`, silent /// outside its [in, out) span. Comp sample index `k` maps to `in + out − 1 − k` when - /// `reversed`. + /// `reversed` (the Backwards effect). fn layer_raw(&self, l: &Layer, i0: i64, n: usize, reversed: bool) -> Vec { let rate = self.rate; let mut out = vec![0.0f32; n * 2]; @@ -170,42 +194,86 @@ impl MixEnv<'_> { if a >= b { return out; } - let m = b - a; // Within ±1 % to ±9900 % (#3247): a stretch of 1e-300 % set in memory read about - // usize::MAX source samples for one block. - let speed = (100.0 / l.effective_stretch()).min(MAX_SPEED); - let src_n = ((m as f64 * speed).ceil() as usize).max(1); - let lt = l.layer_time(sample_tick(i0 + a as i64, rate)); + // usize::MAX source samples for one block. A negative stretch plays backwards (#3239). + let speed = 100.0 / l.effective_stretch(); + let aspeed = speed.abs(); + // The clamped stretch keeps the speed within MAX_SPEED; NaN is checked anyway. The + // tolerance keeps exactly 1 % audible whatever the float noise in the stretch. + if aspeed.is_nan() || aspeed > MAX_SPEED * (1.0 + 1e-9) { + return out; + } + let backwards = speed < 0.0; + // Comp samples per piece, so that one piece reads at most MAX_READ source frames (its + // span, the fraction it starts past a source sample, and the sample after its end). + let piece = (((MAX_READ - 4) as f64 / aspeed) as usize).clamp(1, b - a); + let mut p0 = a; + while p0 < b { + let p1 = p0.saturating_add(piece).min(b); + // Forwards a piece reads the source from the layer time of its first sample. Backwards + // it reads from the layer time of its end and plays what it read last to first, so + // comp sample `k` plays the source just before `layer_time(k)` — at -100 % the exact + // mirror Backwards gives a forward layer. + let origin = sample_tick(i0.saturating_add((if backwards { p1 } else { p0 }) as i64), rate); + let Some(run) = self.source_run(l, l.layer_time(origin), p1 - p0, aspeed) else { return out }; + for (i, f) in run.as_chunks::<2>().0.iter().take(p1 - p0).enumerate() { + let k = if backwards { (p1 - 1).saturating_sub(i) } else { p0 + i }; + if let Some(o) = out.get_mut(k * 2..k * 2 + 2) { + o.copy_from_slice(f); + } + } + p0 = p1; + } + out + } + + /// `m` sample frames of the layer's source audio from layer time `lt` on, played at `speed` + /// (≥ 0) source samples per comp sample: blended linearly between source samples, or copied + /// as they are at speed 1. `None` when the layer has no source audio. + /// + /// Sources deliver samples on their sample grid (from the sample at or before the time asked + /// for), so a resampled run reads from that grid sample and starts `x` at `lt`'s exact + /// position past it: a run then continues where the previous block or piece left off. + fn source_run(&self, l: &Layer, lt: Tick, m: usize, speed: f64) -> Option> { + let rate = self.rate; + let same = (speed - 1.0).abs() < 1e-9; + let s0 = lt.to_units_floor(i64::from(rate)); + let from = sample_tick(s0, rate); + // `lt`'s position past sample s0, in samples (0 ≤ frac < 1); copies ignore it. + let tps = TICKS_PER_SECOND as i128; + let frac = if same { 0.0 } else { (i128::from(lt.0) * i128::from(rate)).rem_euclid(tps) as f64 / tps as f64 }; + // Resampled, one more source sample than the run covers: the last sample blends with it. + let src_n = ((frac + m as f64 * speed).ceil() as usize).saturating_add(usize::from(!same)).max(1); let buf = match &l.source { LayerSource::Footage { item } => match self.project.item(*item).map(|i| &i.kind) { - Some(ItemKind::Footage(f)) if f.has_audio => self.footage.audio(*item, f, lt, src_n, rate).unwrap_or_else(|| vec![0.0; src_n * 2]), - _ => return out, + Some(ItemKind::Footage(f)) if f.has_audio => self.footage.audio(*item, f, from, src_n, rate).unwrap_or_else(|| vec![0.0; src_n * 2]), + _ => return None, }, LayerSource::Comp { item } => { if self.project.comp_contains(*item, self.comp_id) { - return out; + return None; } let mut sub = vec![0.0f32; src_n * 2]; - mix_into(&AudioSources { project: self.project, footage: self.footage, expr: self.expr, rate }, *item, lt, &mut sub, self.depth + 1); + mix_into(&AudioSources { project: self.project, footage: self.footage, expr: self.expr, rate }, *item, from, &mut sub, self.depth + 1); sub } - _ => return out, + _ => return None, }; - let same = (speed - 1.0).abs() < 1e-9; + let mut out = vec![0.0f32; m * 2]; for i in 0..m { // The source sample at fractional index `x`, blended linearly with the next one unless the // layer plays at its own speed (then the samples are copied as they are). - let x = i as f64 * speed; + let x = frac + i as f64 * speed; let j = if same { i } else { (x as usize).min(src_n - 1) }; if j * 2 + 1 >= buf.len() { break; } let k = if same || (j + 1) * 2 + 1 >= buf.len() { j } else { j + 1 }; let f = if same { 0.0 } else { ((x - j as f64) as f32).clamp(0.0, 1.0) }; - out[(a + i) * 2] = buf[j * 2] + (buf[k * 2] - buf[j * 2]) * f; - out[(a + i) * 2 + 1] = buf[j * 2 + 1] + (buf[k * 2 + 1] - buf[j * 2 + 1]) * f; + out[i * 2] = buf[j * 2] + (buf[k * 2] - buf[j * 2]) * f; + out[i * 2 + 1] = buf[j * 2 + 1] + (buf[k * 2 + 1] - buf[j * 2 + 1]) * f; } - out + Some(out) } /// Effect parameters at comp time `t`. @@ -228,12 +296,12 @@ impl MixEnv<'_> { if fx.is_empty() { return self.layer_raw(l, i0, n, false); } - let reversed = fx.iter().any(|(id, _, _)| audio_fx::reverses(id)); + let reversed = plays_backwards(l); let pre_s: f64 = fx.iter().map(|(id, _, p)| audio_fx::preroll(id, p)).sum::().clamp(0.0, MAX_PREROLL_SECONDS); let pre = (pre_s * self.rate as f64).ceil() as usize; let b0 = i0 - pre as i64; let mut buf = self.layer_raw(l, b0, n + pre, reversed); - let start = l.layer_time(sample_tick(b0, self.rate)).seconds(); + let start = fx_clock(l, sample_tick(b0, self.rate)); for (id, g, p) in &fx { if audio_fx::per_sample(id) && animated(g) { self.process_stepped(l, id, g, &mut buf, b0); @@ -257,7 +325,7 @@ impl MixEnv<'_> { let end = usize::try_from(next.saturating_sub(b0)).unwrap_or(frames).clamp(k + 1, frames); let t = sample_tick(i, self.rate); if let Some(piece) = buf.get_mut(k * 2..end * 2) { - audio_fx::process(id, &self.params(l, g, t), piece, self.rate, l.layer_time(t).seconds()); + audio_fx::process(id, &self.params(l, g, t), piece, self.rate, fx_clock(l, t)); } k = end; } @@ -309,8 +377,9 @@ fn mix_into(sources: &AudioSources<'_>, comp_id: ItemId, start: Tick, out: &mut let any_solo = comp.layers.iter().any(|l| l.switches.solo && audible(project, l)); let s0 = start.to_units_floor(rate as i64); for l in &comp.layers { - // The stretch the layer's time uses (#3247): 0 and NaN play at 100 %, as `layer_time`. - if !audible(project, l) || (any_solo && !l.switches.solo) || l.effective_stretch() <= 0.0 { + // The stretch the layer's time uses (#3247): 0 and NaN play at 100 %, as `layer_time`; + // a negative one plays backwards (#3239). + if !audible(project, l) || (any_solo && !l.switches.solo) { continue; } // Sample range of the block that falls inside the layer's [in, out). @@ -552,6 +621,11 @@ mod tests { let base = Comp::new(64, 64, FrameRate::new(25, 1), Tick::from_seconds_f64(2.0)); let mut tone = build::layer(&mut p, &base, "tone", LayerSource::Footage { item: fid }, (0, 0), None); tone.stretch = stretch; + // A reversed layer as After Effects lays it out: over [0, 2) s, starting at its out point. + let end = if stretch < 0.0 { 2.0 } else { 0.0 }; + if stretch < 0.0 { + (tone.in_point, tone.out_point, tone.start_time) = (Tick::ZERO, Tick::from_seconds_f64(2.0), Tick::from_seconds_f64(2.0)); + } let mut comp = base.clone(); comp.layers = vec![tone].into(); let cid = p.add_item("C", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(comp.into())); @@ -561,8 +635,11 @@ mod tests { let speed = 100.0 / stretch; let (mut worst, mut sq) = (0.0f64, 0.0f64); for i in 0..n { - // The source plays `speed` times as fast as the comp: source time = speed * comp time. - let ideal = (std::f64::consts::TAU * 440.0 * speed * (t.seconds() + i as f64 / rate as f64)).sin() * 0.5; + // The source plays `speed` times as fast as the comp: source time = speed * (comp time − + // start). Reversed, a comp sample plays the source sample just before that time. + let back = if stretch < 0.0 { speed / rate as f64 } else { 0.0 }; + let src = speed * (t.seconds() + i as f64 / rate as f64 - end) + back; + let ideal = (std::f64::consts::TAU * 440.0 * src).sin() * 0.5; let e = (m[i * 2] as f64 - ideal).abs(); worst = worst.max(e); sq += e * e; @@ -581,4 +658,18 @@ mod tests { assert!(worst < 1e-2, "stretch {stretch}%: error {worst} at 8 kHz"); } } + + /// A reversed layer plays its tone backwards with the same resampling quality as forwards + /// (it was silent, #3239); at -100 % the samples are copied exactly. + #[test] + fn reversed_layers_resample_a_tone_with_small_error() { + for stretch in [-70.0, -33.0] { + let (worst, _) = stretch_error(stretch, 48_000); + assert!(worst < 1e-3, "stretch {stretch}%: error {worst} at 48 kHz"); + let (worst, _) = stretch_error(stretch, 8_000); + assert!(worst < 1e-2, "stretch {stretch}%: error {worst} at 8 kHz"); + } + let (worst, _) = stretch_error(-100.0, 48_000); + assert!(worst < 1e-5, "stretch -100%: error {worst}"); + } } diff --git a/crates/render/src/cache.rs b/crates/render/src/cache.rs index 4f72e79fa..d58301185 100644 --- a/crates/render/src/cache.rs +++ b/crates/render/src/cache.rs @@ -630,6 +630,15 @@ fn group_has(g: &PropGroup, match_id: &str) -> bool { }) } +/// A frame-blended layer's pixels also depend on how far its source runs during the comp frame: +/// a fast-conformed clip mixes every source frame the comp frame spans (#3180), so a time +/// stretch or remap change can alter the pixels at an unchanged source time. +fn hash_blend_spans(h: &mut KeyHasher, ctx: &EvalCtx, layer: &Layer) { + if crate::frames::frame_blend_mode(ctx, layer) != effectcraft_project::FrameBlend::Off { + crate::frames::blend_spans(ctx, layer).hash(h); + } +} + /// Feed every property of `g` that can change over time (keyframes or expression) as its value /// at the context time. The static structure is hashed separately. /// Mix the collapsed-instance overrides that target `id` into a cache key. They replace values @@ -801,6 +810,7 @@ fn key_any(ctx: &EvalCtx, layer: &Layer, scale: f64, draft: bool, blur: bool, fo } // Frame blending mixes neighbouring source frames. ctx.comp.enable_frame_blending.hash(&mut h); + hash_blend_spans(&mut h, ctx, layer); } _ => return None, } diff --git a/crates/render/src/cache/dependencies.rs b/crates/render/src/cache/dependencies.rs index 6f14ddcde..9b9b5e79a 100644 --- a/crates/render/src/cache/dependencies.rs +++ b/crates/render/src/cache/dependencies.rs @@ -124,6 +124,8 @@ impl Dependencies<'_> { Some(()) } + /// Folds what the layer contributes at this time into the dependency cache key, including its source, effects and frame blend state. + /// Returns `None` when the layer cannot be keyed: past the depth limit, in a reference cycle, or with expressions that read other times. fn layer(&mut self, ctx: &EvalCtx, layer: &Layer) -> Option<()> { let id = (ctx.comp_id, layer.id); if self.path.len() > crate::MAX_FX_DEPTH || self.path.contains(&id) { @@ -167,7 +169,10 @@ impl Dependencies<'_> { hash_debug(self.h, &source); if let Some(source) = source { match &source.kind { - ItemKind::Footage(_) => ctx.source_time(layer).0.hash(self.h), + ItemKind::Footage(_) => { + ctx.source_time(layer).0.hash(self.h); + super::hash_blend_spans(self.h, ctx, layer); + } ItemKind::Comp(comp) => { let time = ctx.source_time(layer); time.0.hash(self.h); diff --git a/crates/render/src/footage.rs b/crates/render/src/footage.rs index c14961d0f..25a5ef608 100644 --- a/crates/render/src/footage.rs +++ b/crates/render/src/footage.rs @@ -73,9 +73,9 @@ pub trait FootageSource: Send + Sync { /// Drop the decoded frames it keeps (Edit ▸ Purge ▸ All Memory / Image Cache Memory): the /// next reads decode again. Sources without a cache ignore it. fn purge(&self) {} - /// The file at `path` changed on disk (Reload Footage): drop what it keeps of it (decoded - /// frames, open decoders, parsed models), so the next reads see the new contents. Sources - /// without a cache ignore it. + /// The file at `path` changed on disk (Reload Footage), or the project showing it closed: + /// drop what it keeps of it (decoded frames, open decoders, parsed models), so the next reads + /// see the new contents. Sources without a cache ignore it. fn forget(&self, _path: &str) {} /// Settings ▸ Disk ▸ Conformed Audio Folder: where decoded audio is kept between reads /// (`None` = off); sources that don't decode audio ignore it. @@ -205,7 +205,7 @@ impl FootageSource for CancellableFootage<'_> { self.inner.cache_budget() } fn vector_frame(&self, item: ItemId, footage: &Footage, scale: f64) -> Option> { - self.inner.vector_frame(item, footage, scale) + self.read(|| self.inner.vector_frame(item, footage, scale)) } fn cancellable(&self, cancel: &Arc, f: &mut dyn FnMut()) { self.inner.cancellable(cancel, f) @@ -231,7 +231,7 @@ impl FootageSource for CancellableFootage<'_> { /// Footage that can be rasterised at any scale: SVG, PDF, Illustrator and EPS files, and a /// placed page of an After Effects project (its codec is not stored there). pub fn is_vector_footage(f: &Footage) -> bool { - matches!(f.codec.as_str(), "SVG" | "PDF" | "AI" | "EPS") || f.placed_page + matches!(f.codec.as_str(), "SVG" | "PDF" | "AI" | "EPS" | "VectorCraft") || f.placed_page } /// How vector footage `f` is drawn at `scale` × its size: the image size, and the x and y scale diff --git a/crates/render/src/frames.rs b/crates/render/src/frames.rs index 20c655694..7d072438c 100644 --- a/crates/render/src/frames.rs +++ b/crates/render/src/frames.rs @@ -89,6 +89,84 @@ pub fn frame_position(t: Tick, rate: FrameRate) -> (i64, f64) { (num.div_euclid(den) as i64, num.rem_euclid(den) as f64 / den as f64) } +/// The fewest source frames one comp frame must run through before frame blending averages all +/// of them ([`mix_window`]); below this the two neighbouring frames blend as they always have. +/// Conservative on purpose: common footage (60p in a 30, 25 or 24 fps comp, 50p in 25) keeps +/// its familiar look, while fast-conformed footage (600 fps in a 25 fps comp, #3180) gets the +/// mix. Pending a comparison with After Effects, whose exact threshold is not documented. +pub const MIN_MIX_FRAMES: f64 = 4.0; + +/// The most source frames one comp frame mixes; a wider span is sampled at this many evenly +/// spaced frames (After Effects is reported to blend about a dozen; this also bounds the +/// decoding per comp frame). Pending a comparison with After Effects. +pub const MAX_MIX_FRAMES: usize = 16; + +/// A span of more source frames than this in one comp frame is a jump (a time remap cut), not +/// motion to blur. +pub const MAX_MIX_SPAN: f64 = 1000.0; + +/// How finely [`blend_spans`] probes the source's speed: at 1/16 of a comp frame. +const SPEED_PROBE: i64 = 16; + +/// How far a frame-blended layer's source runs during one comp frame from the context time +/// (Interpret Footage's conformed rate, time stretch and time remap all show up in it), as +/// `(local, whole)`: the local speed just after the comp frame's time scaled to a whole frame, +/// and the actual difference to the next comp frame. They disagree across a time remap jump +/// (a hold keyframe followed by a cut, a `loopOut` wrapping back), which then does not mix. +/// Measured on the shown source time ([`EvalCtx::nested_time`]: a precomp proxy that preserves +/// its frame rate is floored to its frames). +pub(crate) fn blend_spans(ctx: &EvalCtx, layer: &Layer) -> (Tick, Tick) { + let frame = ctx.comp.frame_duration(); + let t0 = ctx.nested_time(layer); + let probe = Tick(frame.0 / SPEED_PROBE); + let local = ctx.at(ctx.time + probe).nested_time(layer) - t0; + let whole = ctx.at(ctx.time + frame).nested_time(layer) - t0; + (Tick(local.0.saturating_mul(SPEED_PROBE)), whole) +} + +/// The source frames a frame-blended comp frame averages when the layer runs through many +/// source frames per comp frame (footage interpreted at a much higher frame rate than the comp, +/// a sped-up time stretch or time remap), so a comp frame skips whole source frames: the frames +/// at `rate` that one comp frame's worth of source from `t` overlaps, each weighted by the share +/// of a frame it covers. `spans` is [`blend_spans`]' `(local, whole)`; playing forwards the span +/// is `[t, t + span)`, backwards it ends with the frame at `t` (the unblended frame). `None` — +/// the two neighbouring frames then blend ([`frame_position`], [`blend_frames`]) — when the span +/// is shorter than [`MIN_MIX_FRAMES`], longer than [`MAX_MIX_SPAN`], or the local speed and the +/// whole frame's difference disagree by more than a source frame (a time remap jump). +pub fn mix_window(t: Tick, spans: (Tick, Tick), rate: FrameRate) -> Option> { + if rate.num <= 0 || rate.den <= 0 { + return None; + } + let frames_of = |s: Tick| s.0 as f64 * rate.num as f64 / (TICKS_PER_SECOND as f64 * rate.den as f64); + let width = frames_of(spans.0); + let whole = frames_of(spans.1); + if !width.is_finite() || !whole.is_finite() || (width - whole).abs() > 1.0 + 1e-9 { + return None; + } + if width.abs() < MIN_MIX_FRAMES - 1e-9 || width.abs() > MAX_MIX_SPAN { + return None; + } + let (i, w) = frame_position(t, rate); + let p = i as f64 + w; + let lo = if width < 0.0 { p + 1.0 + width } else { p }; + let width = width.abs(); + let hi = lo + width; + let first = lo.floor(); + let n = hi.ceil() - first; + if n <= MAX_MIX_FRAMES as f64 { + let frames = (0..n as usize) + .filter_map(|k| { + let j = first + k as f64; + let cover = (j + 1.0).min(hi) - j.max(lo); + (cover > 1e-9).then_some((j as i64, cover)) + }) + .collect(); + return Some(frames); + } + let m = MAX_MIX_FRAMES as f64; + Some((0..MAX_MIX_FRAMES).map(|k| ((lo + width * (k as f64 + 0.5) / m).floor() as i64, 1.0)).collect()) +} + /// Blend two neighbouring frames `w` of the way from `a` to `b`: a cross-fade (Frame Mix) or a /// motion-compensated interpolation (Pixel Motion). pub fn blend_frames(mode: FrameBlend, a: &Image, b: &Image, w: f32) -> Image { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index f47443b18..1a3822f48 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -50,7 +50,7 @@ pub use accel::{Accelerator, Backend, FrameMemory, FxStep, FxTarget}; pub use footage::{CancellableFootage, FloatCurve, FootageSource, NoFootage, is_vector_footage, missing_item_problem, vector_fit}; pub use frames::{ adaptive_samples, blend_frames, cineon_frame, content_bounds, extended_region, field_frame, frame_position, frame_size, interpret_pixels, kurbo_path, - render_frame, roi_inside, + mix_window, render_frame, roi_inside, }; #[cfg(test)] use fx_host::FxHost; diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index c0f4c8dd9..042dc198c 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -93,6 +93,26 @@ pub struct Collapsed { pub(crate) media_overrides: Vec, } +/// Cache key of a frame-blended footage frame: `seed` (which frames, how they mix, the footage +/// file) and the Interpret Footage settings that change the decoded pixels. +fn blended_frame_key(f: &Footage, seed: impl std::hash::Hash) -> u64 { + use std::hash::{Hash, Hasher}; + let mut h = std::collections::hash_map::DefaultHasher::new(); + seed.hash(&mut h); + // Every file of a sequence: the key must tell two projects apart whose items share an id + // and a first frame (on disk, no project-wide salt does, #3184). + f.sequence.hash(&mut h); + (f.alpha as u8).hash(&mut h); + if f.alpha == effectcraft_project::AlphaMode::Premultiplied { + f.premul_color.map(f32::to_bits).hash(&mut h); + } + if f.cineon_applies() { + let c = &f.cineon; + [c.converted_black, c.converted_white, c.black, c.white, c.gamma, c.rolloff].map(f32::to_bits).hash(&mut h); + } + h.finish() +} + /// The property and media overrides of a collapsed precomp layer. `None` when its Essential /// Properties group or the source comp's definitions are missing (the flattened path then /// preserves the old behaviour). @@ -1223,26 +1243,16 @@ impl<'a> Renderer<'a> { let mode = frame_blend_mode(ctx, layer); let float = self.pipe.float_curve(f); if mode != FrameBlend::Off && matches!(f.kind, FootageKind::Video | FootageKind::Sequence) { + // Many source frames per comp frame (footage interpreted much faster than the comp, + // #3180): the frames the comp frame spans are averaged. + if let Some(img) = self.mixed_span_frame(ctx, layer, item, f, t, size) { + return Some(img); + } let (i, w) = frame_position(t, f.frame_rate); if w > 1e-6 { // Blended frames are cached (Pixel Motion is expensive). - let key = self.cache.map(|_| { - use std::hash::{Hash, Hasher}; - let mut h = std::collections::hash_map::DefaultHasher::new(); - (0x00f8_a3e5_u64, item, i, (w as f32).to_bits(), mode as u8, f.frame_rate.num, f.frame_rate.den, &f.path, float).hash(&mut h); - // Every file of a sequence: the key must tell two projects apart whose items - // share an id and a first frame (on disk, no project-wide salt does, #3184). - f.sequence.hash(&mut h); - (f.alpha as u8).hash(&mut h); - if f.alpha == effectcraft_project::AlphaMode::Premultiplied { - f.premul_color.map(f32::to_bits).hash(&mut h); - } - if f.cineon_applies() { - let c = &f.cineon; - [c.converted_black, c.converted_white, c.black, c.white, c.gamma, c.rolloff].map(f32::to_bits).hash(&mut h); - } - h.finish() - }); + let seed = (0x00f8_a3e5_u64, item, i, (w as f32).to_bits(), mode as u8, f.frame_rate.num, f.frame_rate.den, &f.path, float); + let key = self.cache.map(|_| blended_frame_key(f, seed)); if let Some((b, _)) = self.cached(key) { return Some(Arc::new(b.img.clone())); } @@ -1261,6 +1271,58 @@ impl<'a> Renderer<'a> { self.read(|| self.footage.frame_with(item, f, t, size, float)).map(|img| cineon_frame(img, f)) } + /// A frame-blended footage frame at source time `t` when one comp frame runs through many + /// source frames: the average of the source frames the comp frame spans, each weighted by + /// the share of it the span covers ([`super::frames::mix_window`]). Both Frame Mix and + /// Pixel Motion average real frames here (there is no in-between frame to synthesise). + /// `size`: the frames may come resampled to it ([`FootageSource::frame_at_size`]). `None` + /// when the span is too short (or a jump) to mix, or no frame decodes. + fn mixed_span_frame(&self, ctx: &EvalCtx, layer: &Layer, item: ItemId, f: &Footage, t: Tick, size: Option<(u32, u32)>) -> Option> { + use rayon::prelude::*; + let float = self.pipe.float_curve(f); + let spans = super::frames::blend_spans(ctx, layer); + let frames = super::frames::mix_window(t, spans, f.frame_rate)?; + let seed = (0x00f8_a3e6_u64, item, t.0, spans, size, f.frame_rate.num, f.frame_rate.den, &f.path, float); + let key = self.cache.map(|_| blended_frame_key(f, seed)); + if let Some((b, _)) = self.cached(key) { + return Some(Arc::new(b.img.clone())); + } + // A weighted sum in one buffer, divided by the total weight at the end. A frame that does + // not decode, or has another size than the first (a sequence of mixed sizes), is left + // out and the mix renormalises over the rest. Log scans are converted before they mix. + let ((acc, total), files) = self.recorded(key, |r| { + let mut acc: Option = None; + let mut total = 0.0; + for (j, w) in frames { + let Some(img) = r.read(|| r.footage.frame_with(item, f, f.frame_rate.tick_of(j), size, float)).map(|a| cineon_frame(a, f)) else { continue }; + let sum = acc.get_or_insert_with(|| Image::new(img.width, img.height)); + if (sum.width, sum.height) != (img.width, img.height) { + continue; + } + let wf = w as f32; + sum.data.par_iter_mut().zip(img.data.par_iter()).for_each(|(s, p)| { + for (a, b) in s.iter_mut().zip(p) { + *a += b * wf; + } + }); + total += w; + } + (acc, total) + }); + let mut img = acc?; + if total <= 1e-9 { + return None; + } + let norm = (1.0 / total) as f32; + img.data.par_iter_mut().for_each(|s| { + for c in s.iter_mut() { + *c *= norm; + } + }); + let _kept = self.keep(key, Arc::new(Buf { img: img.clone(), offset: [0.0; 2], scale: 1.0 }), &files); + Some(Arc::new(img)) + } + /// Source → masks, clamped/quantised to the project depth. fn masked_source(&self, ctx: &EvalCtx, layer: &Layer) -> Option { let (mut buf, quantized) = match self.content_times(ctx, layer) { diff --git a/crates/render/src/reads.rs b/crates/render/src/reads.rs index 73b7ce830..af0535e5a 100644 --- a/crates/render/src/reads.rs +++ b/crates/render/src/reads.rs @@ -35,9 +35,10 @@ impl FileStamp { } /// The identity of the file at `path` now: one `metadata` call. `None` when the file system - /// can't describe it (missing, or a path served from memory). + /// can't describe it (missing, not a regular file, or a path served from memory). pub fn native(path: &str) -> Option { - std::fs::metadata(path).ok().map(|md| FileStamp::of_metadata(&md)) + let md = std::fs::metadata(path).ok()?; + md.is_file().then(|| FileStamp::of_metadata(&md)) } } @@ -355,6 +356,15 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn a_directory_is_not_a_native_file_stamp() { + let dir = std::env::temp_dir().join(format!("effectcraft-stamp-directory-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + assert_eq!(FileStamp::native(&dir.to_string_lossy()), None); + let _ = std::fs::remove_dir_all(&dir); + } + #[test] fn the_list_is_bounded() { let files: ReadFiles = (0..MAX_READ_FILES + 3).map(|i| file(&format!("/f{i:06}"), 1)).collect(); diff --git a/crates/render/src/tests.rs b/crates/render/src/tests.rs index 2d0f90ac5..fd60f31a1 100644 --- a/crates/render/src/tests.rs +++ b/crates/render/src/tests.rs @@ -927,6 +927,30 @@ fn effects_see_layer_masks() { assert!(img.get(150, 50)[3] > 0.99, "mode None mask does not cut the layer"); } +/// Masks come before effects: Grid (Blending Mode None) draws only inside a masked solid (#3121). +#[test] +fn grid_stays_inside_the_layer_mask() { + let (mut p, cid, comp) = setup(); + let mut l = solid(&mut p, &comp, [1.0, 1.0, 1.0], 200, 100); + let mut next = p.next_id; + let m = build::mask(&mut Ids(&mut next), "Mask 1", ShapePath::rect([50.0, 50.0], 40.0, 40.0), MaskMode::Add, [255, 255, 0]); + p.next_id = next; + l.props.sub_mut("masks").unwrap().children.push(m.into()); + // Inverted, the grid covers nearly every pixel, so the check does not depend on where the + // lines fall. + let set = [("width", Value::Scalar(10.0)), ("border", Value::Scalar(2.0)), ("invertGrid", Value::Bool(true))]; + add_effect(&mut p, &mut l, "ec.generate.grid", [200.0, 100.0], &set); + p.comp_mut(cid).unwrap().layers.push(l); + let img = render_frame(&p, cid, Tick::ZERO, 1.0); + for y in 0..100 { + for x in 100..200 { + assert!(img.get(x, y)[3] < 0.01, "grid outside the mask at ({x}, {y}): {:?}", img.get(x, y)); + } + } + assert!(img.get(15, 15)[3] < 0.01, "grid left of and above the mask: {:?}", img.get(15, 15)); + assert!(img.get(55, 55)[3] > 0.5, "grid inside the mask: {:?}", img.get(55, 55)); +} + /// An open mask (the Pen still drawing it) leaves the layer whole; closed, it masks (#290). #[test] fn open_masks_make_no_transparency() { diff --git a/crates/render/src/tests/audio_fx.rs b/crates/render/src/tests/audio_fx.rs index a6c85f2de..5ef2949e5 100644 --- a/crates/render/src/tests/audio_fx.rs +++ b/crates/render/src/tests/audio_fx.rs @@ -1,13 +1,14 @@ //! Audio effects through the mixdown (the path preview playback and export share). use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; use effectcraft_keyframe::{Keyframe, Value}; use effectcraft_project::build::{self, Ids}; use effectcraft_project::{Comp, Footage, FootageKind, ItemId, ItemKind, LayerSource, Project, Solid}; use effectcraft_time::{FrameRate, Tick}; -use crate::audio::{comp_has_audio, footage_peaks, mix_comp, peak_summary}; +use crate::audio::{MAX_READ, comp_has_audio, footage_peaks, mix_comp, peak_summary}; use crate::{FootageSource, Image}; const SR: u32 = 8000; @@ -109,6 +110,221 @@ fn backwards_reverses_the_layer_span() { assert!((m[4000 * 2] - 0.5).abs() < 1e-3); } +/// `comp_with`, its layer reversed at `stretch` (< 0) the way After Effects lays it out: in 0, +/// out `out` s, starting at the out point. +fn reversed(id: Option<&str>, vals: &[(&str, Value)], solid: bool, stretch: f64, out: f64) -> (Project, ItemId) { + let (mut p, cid) = comp_with(id, vals, solid); + let l = &mut p.comp_mut(cid).unwrap().layers[0]; + l.stretch = stretch; + (l.in_point, l.out_point, l.start_time) = (Tick::ZERO, Tick::from_seconds_f64(out), Tick::from_seconds_f64(out)); + (p, cid) +} + +/// A time-reversed layer plays its audio backwards instead of being silent (#3239): at -100 % +/// sample for sample what Backwards plays on the forward layer, in any block size. +#[test] +fn a_reversed_layer_plays_its_audio_backwards() { + let n = SR as usize; + let (p, cid) = reversed(None, &[], false, -100.0, 1.0); + let m = mix(&p, &Signal(ramp), cid, 0.0, n); + // Comp sample k plays source sample n − 1 − k. + for k in [0usize, 1, 2000, 4000, 7000] { + let want = (n - 1 - k) as f32 / SR as f32; + assert!((m[k * 2] - want).abs() < 1e-6 && (m[k * 2 + 1] + want).abs() < 1e-6, "k={k}: {} {}, want {want}", m[k * 2], m[k * 2 + 1]); + } + let (bp, bcid) = comp_with(Some("ec.audio.backwards"), &[], false); + assert_eq!(m, mix(&bp, &Signal(ramp), bcid, 0.0, n), "not the mirror Backwards plays"); + let mut blocks = vec![]; + for k in 0..n / 320 { + blocks.extend(mix(&p, &Signal(ramp), cid, (k * 320) as f64 / SR as f64, 320)); + } + let worst = m.iter().zip(&blocks).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(worst < 1e-6, "block size changes the result by {worst}"); +} + +/// The speed of a reversed layer follows its stretch as a forward one's does: -50 % plays the +/// source twice as fast, -200 % at half speed, both backwards. +#[test] +fn a_reversed_layer_plays_at_its_stretch() { + // -50 % over 0.5 s: comp sample k plays source sample 2 (n − 1 − k), n = 4000. + let (p, cid) = reversed(None, &[], false, -50.0, 0.5); + let m = mix(&p, &Signal(ramp), cid, 0.0, 4000); + for k in [0usize, 1000, 3000] { + let want = 2.0 * (3999 - k) as f32 / SR as f32; + assert!((m[k * 2] - want).abs() < 1e-6, "-50 %, k={k}: {}, want {want}", m[k * 2]); + } + // -200 % over 2 s: comp sample k plays source sample (n − 1 − k) / 2, n = 16000, blended. + let (p, cid) = reversed(None, &[], false, -200.0, 2.0); + let m = mix(&p, &Signal(ramp), cid, 0.0, 16_000); + for k in [0usize, 1, 5001, 12_000] { + let want = (15_999 - k) as f32 / 2.0 / SR as f32; + assert!((m[k * 2] - want).abs() < 1e-5, "-200 %, k={k}: {}, want {want}", m[k * 2]); + } +} + +/// Backwards on a reversed layer plays it forwards: the two reversals cancel. +#[test] +fn backwards_on_a_reversed_layer_plays_forwards() { + let (p, cid) = reversed(Some("ec.audio.backwards"), &[], false, -100.0, 1.0); + let (fp, fcid) = comp_with(None, &[], false); + for (from, frames) in [(0.0, SR as usize), (0.25, 2000)] { + let m = mix(&p, &Signal(ramp), cid, from, frames); + assert!(m.iter().any(|v| v.abs() > 0.1), "silent from {from} s"); + assert_eq!(m, mix(&fp, &Signal(ramp), fcid, from, frames), "from {from} s"); + } +} + +/// Effects on a reversed layer run on a clock that moves forwards with the samples at comp speed, +/// so a Tone joins up across blocks (preview's frame blocks and export's one-second blocks +/// agree), at -50 % too. On the layer-time clock, block k at -100 % would start 0.08 k s off: +/// 35.2 k cycles at 440 Hz, a phase jump. +#[test] +fn tone_on_a_reversed_layer_joins_up_across_blocks() { + let mut vals: Vec<(&str, Value)> = vec![("frequency1", Value::Scalar(440.0))]; + for k in ["frequency2", "frequency3", "frequency4", "frequency5"] { + vals.push((k, Value::Scalar(0.0))); + } + for stretch in [-100.0, -50.0] { + let (p, cid) = reversed(Some("ec.audio.tone"), &vals, true, stretch, 1.0); + let long = mix(&p, &Signal(ramp), cid, 0.2, 1600); + assert!(rms(&long) > 0.05, "{stretch} %: silent: {}", rms(&long)); + let mut blocks = vec![]; + for k in 0..5 { + blocks.extend(mix(&p, &Signal(ramp), cid, 0.2 + k as f64 * 0.04, 320)); + } + let worst = long.iter().zip(&blocks).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(worst < 1e-3, "{stretch} %: block size changes the tone by {worst}"); + } +} + +/// Footage audio on its sample grid, as the media pool decodes it: a read from any time starts +/// at the sample at or before it. Sample n is `f(n / rate)` over [0, 2) s. +struct Grid(fn(f64) -> (f32, f32)); +impl FootageSource for Grid { + fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option> { + None + } + fn audio(&self, _: ItemId, _: &Footage, start: Tick, frames: usize, rate: u32) -> Option> { + let s0 = start.to_units_floor(i64::from(rate)); + Some( + (0..frames as i64) + .flat_map(|i| { + let t = (s0 + i) as f64 / rate as f64; + let (l, r) = if (0.0..2.0).contains(&t) { (self.0)(t) } else { (0.0, 0.0) }; + [l, r] + }) + .collect(), + ) + } +} + +/// A stretched layer, forwards or reversed, gives the same samples mixed in one block as in +/// blocks of any size (preview's video-frame blocks, export's seconds): each block resamples +/// from the exact source position, not from the source sample a block happens to start on. +#[test] +fn stretched_layers_join_up_across_blocks() { + // (stretch, out point, start): the reversed layers start at their out point, the -50 % one + // off the sample grid (a third of a sample late), so its source positions are fractional. + let third = Tick(Tick::from_seconds_f64(1.0 / SR as f64).0 / 3); + for (stretch, out, start) in [ + (200.0, 2.0, Tick::ZERO), + (-70.0, 0.7, Tick::from_seconds_f64(0.7)), + (-50.0, 0.5, Tick(Tick::from_seconds_f64(0.5).0 + third.0)), + (-200.0, 2.0, Tick::from_seconds_f64(2.0)), + ] { + let (mut p, cid) = comp_with(None, &[], false); + let l = &mut p.comp_mut(cid).unwrap().layers[0]; + l.stretch = stretch; + (l.in_point, l.out_point, l.start_time) = (Tick::ZERO, Tick::from_seconds_f64(out), start); + let n = 3210; + let long = mix(&p, &Grid(ramp), cid, 0.1, n); + assert!(long.iter().any(|v| v.abs() > 0.05), "{stretch} %: silent"); + for block in [321, 107] { + let mut blocks = vec![]; + for k in 0..n / block { + blocks.extend(mix(&p, &Grid(ramp), cid, 0.1 + (k * block) as f64 / SR as f64, block)); + } + let worst = long.iter().zip(&blocks).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); + assert!(worst < 1e-6, "{stretch} %, blocks of {block}: off by {worst}"); + } + } +} + +/// At 200 % the last sample of a block blends with the source sample after it, as inside the +/// block, instead of holding the one before. +#[test] +fn a_stretched_block_ends_on_a_blended_sample() { + let (mut p, cid) = comp_with(None, &[], false); + let l = &mut p.comp_mut(cid).unwrap().layers[0]; + l.stretch = 200.0; + (l.in_point, l.out_point, l.start_time) = (Tick::ZERO, Tick::from_seconds_f64(2.0), Tick::ZERO); + let m = mix(&p, &Grid(ramp), cid, 0.0, 320); + // Comp sample 319 plays source position 159.5. + let want = 159.5 / SR as f32; + assert!((m[319 * 2] - want).abs() < 1e-6, "{}, want {want}", m[319 * 2]); +} + +/// Records the longest audio read and answers with a short run, so an unbounded request fails +/// the assert below instead of allocating. +struct Longest(AtomicUsize); +impl FootageSource for Longest { + fn frame(&self, _: ItemId, _: &Footage, _: Tick) -> Option> { + None + } + fn audio(&self, _: ItemId, _: &Footage, _: Tick, frames: usize, _: u32) -> Option> { + self.0.fetch_max(frames, Ordering::Relaxed); + Some(vec![0.25; frames.min(4096) * 2]) + } +} + +/// Tiny, huge, zero and non-finite stretches, and fast precomps nested in fast precomps, read +/// at most MAX_READ source frames at a time and mix to finite samples (a tiny positive stretch +/// asked for 10⁸ times the block, and its precomp buffer could abort the process). +#[test] +fn extreme_stretches_read_bounded_source() { + let stretches = [1e-6, -1e-6, 0.5, -0.5, 1.0, -1.0, 1e12, -1e12, f64::MIN_POSITIVE, 0.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY]; + for stretch in stretches { + let (mut p, cid) = comp_with(None, &[], false); + p.comp_mut(cid).unwrap().layers[0].stretch = stretch; + let src = Longest(AtomicUsize::new(0)); + let m = mix(&p, &src, cid, 0.0, 800); + let longest = src.0.load(Ordering::Relaxed); + assert!(longest <= MAX_READ, "stretch {stretch}: read {longest} frames at once"); + assert!(m.iter().all(|v| v.is_finite()), "stretch {stretch}"); + } + // Exactly 1 %, give or take float noise, stays audible. + let (mut p, cid) = comp_with(None, &[], false); + p.comp_mut(cid).unwrap().layers[0].stretch = 1.0 - 1e-12; + let m = mix(&p, &Longest(AtomicUsize::new(0)), cid, 0.0, 800); + assert!(m.iter().any(|v| *v != 0.0), "1 % is silent"); + // A 1 % footage layer in a 1 % precomp: 10⁴ source samples per comp sample. The precomp layer + // lasts 0.02 s, which plays the inner layer's 2 s once (backwards from its out point at -1 %). + for sign in [1.0, -1.0] { + let mut p = Project::default(); + let base = Comp::new(64, 64, FrameRate::new(25, 1), Tick::from_seconds_f64(2.0)); + let fid = p.add_item("x.wav", effectcraft_color::Label::SeaFoam, None, ItemKind::Footage(audio_footage())); + let mut inner_l = build::layer(&mut p, &base, "a", LayerSource::Footage { item: fid }, (64, 64), None); + inner_l.stretch = sign; + (inner_l.in_point, inner_l.out_point, inner_l.start_time) = + (Tick::ZERO, Tick::from_seconds_f64(2.0), if sign < 0.0 { Tick::from_seconds_f64(2.0) } else { Tick::ZERO }); + let mut inner = base.clone(); + inner.layers = vec![inner_l].into(); + let inner_id = p.add_item("Inner", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(inner.into())); + let mut pre = build::layer(&mut p, &base, "pre", LayerSource::Comp { item: inner_id }, (64, 64), None); + pre.stretch = sign; + let pre_out = Tick::from_seconds_f64(0.02); + (pre.in_point, pre.out_point, pre.start_time) = (Tick::ZERO, pre_out, if sign < 0.0 { pre_out } else { Tick::ZERO }); + let mut outer = base.clone(); + outer.layers = vec![pre].into(); + let outer_id = p.add_item("Outer", effectcraft_color::Label::Sandstone, None, ItemKind::Comp(outer.into())); + let src = Longest(AtomicUsize::new(0)); + let m = mix(&p, &src, outer_id, 0.0, 800); + let longest = src.0.load(Ordering::Relaxed); + assert!(longest > 0 && longest <= MAX_READ, "nested {sign}%: read {longest} frames at once"); + assert!(m.iter().all(|v| v.is_finite())); + } +} + #[test] fn high_low_pass_attenuates() { fn hi(t: f64) -> (f32, f32) { diff --git a/crates/render/src/tests/frame_blend.rs b/crates/render/src/tests/frame_blend.rs index ac3555af1..ecee73b6d 100644 --- a/crates/render/src/tests/frame_blend.rs +++ b/crates/render/src/tests/frame_blend.rs @@ -5,12 +5,13 @@ use std::sync::Arc; use rayon::prelude::*; use effectcraft_color::Label; -use effectcraft_keyframe::{Keyframe, Value}; +use effectcraft_keyframe::{Interp, Keyframe, Value}; use effectcraft_project::build; use effectcraft_project::{AlphaMode, BitDepth, Comp, Footage, FootageKind, FrameBlend, ItemId, ItemKind, LayerSource, Project, Solid}; use effectcraft_time::{FrameRate, Tick}; -use crate::{FootageSource, Image, RenderOpts, Renderer, frame_position}; +use crate::frames::MAX_MIX_FRAMES; +use crate::{FootageSource, Image, RenderOpts, Renderer, frame_position, mix_window}; #[test] fn frame_mix_weights_for_24_to_30_conform() { @@ -57,7 +58,13 @@ impl FootageSource for Frames { } } +/// [`setup_rated`] with 24 fps footage and no recorded native rate. fn setup(mode: FrameBlend, size: (u32, u32)) -> (Project, ItemId) { + setup_rated(mode, size, FrameRate::FPS_24, None) +} + +/// [`setup`] with footage at `rate` (its Interpret Footage frame rate) recorded at `native`. +fn setup_rated(mode: FrameBlend, size: (u32, u32), rate: FrameRate, native: Option) -> (Project, ItemId) { let mut p = Project::default(); p.settings.bit_depth = BitDepth::Bpc32; let comp = Comp::new(size.0, size.1, FrameRate::FPS_30, Tick::from_seconds_f64(2.0)); @@ -68,8 +75,8 @@ fn setup(mode: FrameBlend, size: (u32, u32)) -> (Project, ItemId) { width: size.0, height: size.1, pixel_aspect: 1.0, - frame_rate: FrameRate::FPS_24, - native_rate: None, + frame_rate: rate, + native_rate: native, duration: Tick::from_seconds_f64(2.0), has_video: true, has_audio: false, @@ -168,6 +175,172 @@ fn time_stretched_precomp_frame_mixes() { assert!(img.get(12, 10)[3] < 1e-3 && (img.get(17, 10)[3] - 1.0).abs() < 1e-3 && (img.get(22, 10)[3] - 1.0).abs() < 1e-3 && img.get(27, 10)[3] < 1e-3); } +/// Fast-conformed footage (30 fps interpreted as 300 fps) averages every source frame a comp frame spans, for Frame Mix and Pixel Motion. +#[test] +fn frame_mix_averages_every_frame_of_fast_conformed_footage() { + // #3180: 30 fps footage interpreted as 300 fps in a 30 fps comp. Every comp frame lands + // exactly on a source frame, but it spans ten of them: frame blending averages all ten + // (greys 0.0 … 0.9 → 0.45), not just the frame it starts on (0.0). + let fast = FrameRate::new(300, 1); + let (p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), fast, Some(FrameRate::FPS_30)); + let v = frame(&p, cid, 0, false).get(4, 4)[0]; + assert!((v - 0.45).abs() < 1e-5, "{v}"); + // Pixel Motion has no in-between frame to make either: it averages the same frames. + let (p, cid) = setup_rated(FrameBlend::PixelMotion, (16, 8), fast, Some(FrameRate::FPS_30)); + let v = frame(&p, cid, 0, false).get(4, 4)[0]; + assert!((v - 0.45).abs() < 1e-5, "{v}"); + // Off (layer switch or comp switch): the one frame at the comp frame's time. + let (p, cid) = setup_rated(FrameBlend::Off, (16, 8), fast, Some(FrameRate::FPS_30)); + assert!(frame(&p, cid, 0, false).get(4, 4)[0].abs() < 1e-6); + let (mut p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), fast, Some(FrameRate::FPS_30)); + p.comp_mut(cid).unwrap().enable_frame_blending = false; + assert!(frame(&p, cid, 0, false).get(4, 4)[0].abs() < 1e-6); +} + +/// Footage at the comp's rate, or only mildly faster, renders as before. +#[test] +fn frame_mix_of_common_footage_is_unchanged() { + // Footage at the comp's rate: each comp frame is exactly one source frame, blended or not. + let (p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), FrameRate::FPS_30, None); + for k in 0..4 { + let v = frame(&p, cid, k, false).get(4, 4)[0]; + assert!((v - k as f32 / 10.0).abs() < 1e-6, "comp frame {k}: {v}"); + } + // A mild speed-up (36 fps footage in a 30 fps comp) keeps the two-frame cross-fade: comp + // frame 1 → source frame 1.2, 0.8·frame 1 + 0.2·frame 2 = 0.12. + let (p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), FrameRate::new(36, 1), None); + let v = frame(&p, cid, 1, false).get(4, 4)[0]; + assert!((v - 0.12).abs() < 1e-6, "{v}"); + // 60 and 90 fps in a 30 fps comp (two and three source frames per comp frame) stay crisp: + // comp frame 1 is source frame 2 or 3, as before. + for (rate, want) in [(FrameRate::FPS_60, 0.2), (FrameRate::new(90, 1), 0.3)] { + let (p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), rate, None); + let v = frame(&p, cid, 1, false).get(4, 4)[0]; + assert!((v - want).abs() < 1e-6, "{rate:?}: {v}"); + } +} + +/// Adds Time Remap with `keys` (layer time → source seconds) to the comp's footage layer. +fn remap(p: &mut Project, cid: ItemId, keys: Vec) { + let mut next = p.next_id; + let mut tr = build::Ids(&mut next).prop("timeRemap", "Time Remap", Value::Scalar(0.0)); + p.next_id = next; + tr.keys = keys; + p.comp_mut(cid).unwrap().layers[0].props.children.push(effectcraft_project::Node::Prop(tr)); +} + +/// Time remap holds and cuts do not smear: a still frame stays a single source frame. +#[test] +fn time_remap_jumps_stay_crisp() { + let fast = FrameRate::new(300, 1); + let s = |frames: f64| Value::Scalar(frames / 300.0); + let at = |k: i64| FrameRate::FPS_30.tick_of(k); + // Hold on source frame 0, then cut to source frame 10 at comp frame 1: comp frame 0 is a + // still frame, not a smear of the ten frames the cut skips. + let (mut p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), fast, Some(FrameRate::FPS_30)); + remap(&mut p, cid, vec![Keyframe::new(at(0), s(0.0)).hold(), Keyframe::new(at(1), s(10.0)).hold()]); + let v = frame(&p, cid, 0, false).get(4, 4)[0]; + assert!(v.abs() < 1e-6, "hold then cut: {v}"); + // A loop wrapping back (like `loopOut("cycle")`): from source frame 10 at normal speed, + // back to frame 0 by the next comp frame. Comp frame 0 shows frame 10 (grey 1.0), not + // frames 1 … 10 run backwards. + let (mut p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), fast, Some(FrameRate::FPS_30)); + let mut top = Keyframe::new(FrameRate::FPS_60.tick_of(1), s(15.0)); + top.out_interp = Interp::Hold; + remap(&mut p, cid, vec![Keyframe::new(at(0), s(10.0)), top, Keyframe::new(at(1), s(0.0))]); + let v = frame(&p, cid, 0, false).get(4, 4)[0]; + assert!((v - 1.0).abs() < 1e-6, "loop wrap: {v}"); + // A remap running at normal speed through fast-conformed footage still mixes its frames. + let (mut p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), fast, Some(FrameRate::FPS_30)); + remap(&mut p, cid, vec![Keyframe::new(at(0), s(0.0)), Keyframe::new(at(30), s(300.0))]); + let v = frame(&p, cid, 0, false).get(4, 4)[0]; + assert!((v - 0.45).abs() < 1e-5, "steady remap: {v}"); +} + +/// A frame-blended dependency changes its owner's cache key when its source goes from holding to running at speed. +#[test] +fn a_frame_blended_dependency_keys_how_far_its_source_runs() { + // A footage layer selected by another layer's effect: at comp frames 0 and 1 its source time + // is the same (0), but at frame 0 it holds and at frame 1 it runs at speed, which mixes ten + // source frames. The owner's cache key must tell the two apart. + let fast = FrameRate::new(300, 1); + let (mut p, cid) = setup_rated(FrameBlend::FrameMix, (16, 8), fast, Some(FrameRate::FPS_30)); + let at = |k: i64| FrameRate::FPS_30.tick_of(k); + let keys = vec![Keyframe::new(at(0), Value::Scalar(0.0)).hold(), Keyframe::new(at(1), Value::Scalar(0.0)), Keyframe::new(at(31), Value::Scalar(1.0))]; + remap(&mut p, cid, keys); + let comp = p.comp(cid).unwrap().clone(); + let footage = comp.layers[0].id; + let sid = p.add_item("Solid", Label::Red, None, ItemKind::Solid(Solid { color: [1.0; 3], width: 16, height: 8, pixel_aspect: 1.0 })); + let mut owner = build::layer(&mut p, &comp, "Solid", LayerSource::Solid { item: sid }, (16, 8), None); + super::add_effect(&mut p, &mut owner, "ec.channel.setmatte", [16.0, 8.0], &[("takeMatteFromLayer", Value::Layer(Some(footage.0)))]); + p.comp_mut(cid).unwrap().layers.push(owner); + let key = |k: i64| { + let c = p.comp(cid).unwrap(); + crate::cache::layer_key(&crate::EvalCtx::new(&p, cid, c, at(k)), &c.layers[1], 1.0, false, false).unwrap() + }; + assert_ne!(key(0), key(1)); +} + +/// The mix window is the source span of one comp frame, and falls back to the two-frame blend below four source frames per comp frame. +#[test] +fn mix_window_covers_the_source_span_of_one_comp_frame() { + let comp_frame = |r: FrameRate| r.frame_duration(); + let steady = |r: FrameRate| (comp_frame(r), comp_frame(r)); + // Fewer than four source frames per comp frame (slow-down, same rate, 60p in 30, 24 or 25, + // 50p in 25, 90 in 30): the two-frame blend applies, as before. + for (comp, footage) in [ + (FrameRate::FPS_30, FrameRate::FPS_30), + (FrameRate::FPS_30, FrameRate::FPS_24), + (FrameRate::FPS_30, FrameRate::new(36, 1)), + (FrameRate::FPS_25, FrameRate::FPS_30), + (FrameRate::FPS_30, FrameRate::FPS_60), + (FrameRate::FPS_24, FrameRate::FPS_60), + (FrameRate::FPS_25, FrameRate::FPS_60), + (FrameRate::FPS_25, FrameRate::FPS_50), + (FrameRate::FPS_29_97, FrameRate::FPS_59_94), + (FrameRate::FPS_30, FrameRate::new(90, 1)), + ] { + assert_eq!(mix_window(Tick::ZERO, steady(comp), footage), None, "{footage:?} in {comp:?}"); + } + // Four source frames per comp frame: 120 fps in a 30 fps comp mixes all four. + assert_eq!(mix_window(Tick::ZERO, steady(FrameRate::FPS_30), FrameRate::FPS_120), Some(vec![(0, 1.0), (1, 1.0), (2, 1.0), (3, 1.0)])); + // The report's case: 600 fps in a 25 fps comp, 24 source frames per comp frame, sampled at + // 16 evenly spread frames. + let w = mix_window(FrameRate::FPS_25.tick_of(3), steady(FrameRate::FPS_25), FrameRate::new(600, 1)).unwrap(); + assert_eq!(w.len(), MAX_MIX_FRAMES); + assert!(w.iter().all(|x| (72..96).contains(&x.0) && x.1 == 1.0), "{w:?}"); + assert!(w.windows(2).all(|p| p[0].0 < p[1].0), "{w:?}"); + // 150 fps in a 30 fps comp: comp frame 1 spans source frames 5 … 10. + let w = mix_window(FrameRate::FPS_30.tick_of(1), steady(FrameRate::FPS_30), FrameRate::new(150, 1)); + assert_eq!(w, Some((5..10).map(|j| (j, 1.0)).collect())); + // 135 fps in a 30 fps comp: comp frame 1 spans source frames 4.5 … 9.0. + let w = mix_window(FrameRate::FPS_30.tick_of(1), steady(FrameRate::FPS_30), FrameRate::new(135, 1)).unwrap(); + assert_eq!(w.iter().map(|x| x.0).collect::>(), vec![4, 5, 6, 7, 8]); + for (got, want) in w.iter().map(|x| x.1).zip([0.5, 1.0, 1.0, 1.0, 1.0]) { + assert!((got - want).abs() < 1e-9, "{w:?}"); + } + // Playing backwards: the span ends with the comp frame's own source frame. + let back = -comp_frame(FrameRate::FPS_30); + let w = mix_window(FrameRate::FPS_30.tick_of(1), (back, back), FrameRate::new(300, 1)).unwrap(); + assert_eq!(w.iter().map(|x| x.0).collect::>(), (1..=10).collect::>()); + // A hold (no local speed) or a jump (local speed and the whole frame disagree) does not mix. + let f = comp_frame(FrameRate::FPS_30); + assert_eq!(mix_window(Tick::ZERO, (Tick::ZERO, f), FrameRate::new(300, 1)), None); + assert_eq!(mix_window(Tick::ZERO, (f, -f), FrameRate::new(300, 1)), None); + // A long span is sampled at a bounded number of frames; a span beyond any footage's speed is + // a jump. + let ten = Tick::from_seconds_f64(10.0); + let w = mix_window(Tick::ZERO, (ten, ten), FrameRate::FPS_60).unwrap(); + assert_eq!(w.len(), MAX_MIX_FRAMES); + assert!(w.iter().all(|x| (0..600).contains(&x.0))); + let far = Tick::from_seconds_f64(100.0); + assert_eq!(mix_window(Tick::ZERO, (far, far), FrameRate::FPS_60), None); + // Degenerate rates and huge spans don't panic. + assert_eq!(mix_window(Tick::ZERO, (Tick::MAX, Tick::MAX), FrameRate { num: 0, den: 1 }), None); + assert_eq!(mix_window(Tick::MIN, (Tick::MAX, Tick::MAX), FrameRate::FPS_60), None); + assert_eq!(mix_window(Tick::MAX, (Tick::MIN, Tick::MAX), FrameRate::FPS_60), None); +} + #[test] fn frame_position_survives_degenerate_rates() { for rate in [FrameRate { num: 24, den: 0 }, FrameRate { num: 0, den: 1 }, FrameRate { num: -24, den: 1 }] { diff --git a/crates/script/src/model.rs b/crates/script/src/model.rs index 62f3a8557..c7307e642 100644 --- a/crates/script/src/model.rs +++ b/crates/script/src/model.rs @@ -33,6 +33,7 @@ fn layer_of<'a>(s: &'a Session, a: &J) -> Result<(ItemId, &'a Comp, &'a Layer), Ok((cid, c, l)) } +/// Answers a script model query of the given `kind` against the session, dispatching to the matching reader, and errors on an unknown kind. pub fn query(s: &mut Session, kind: &str, a: &J) -> R { match kind { "project" => Ok(project(s)), @@ -52,13 +53,7 @@ pub fn query(s: &mut Session, kind: &str, a: &J) -> R { let i = u(a, "index").unwrap_or(0) as usize; Ok(effectcraft_engine::command_specs().get(i.wrapping_sub(1)).map(|c| json!(c.id)).unwrap_or(J::Null)) } - "exprError" => { - let code = a.get("code").and_then(J::as_str).unwrap_or(""); - Ok(match s.expr_check { - Some(check) => json!(check(code).err().unwrap_or_default()), - None => json!(""), - }) - } + "exprError" => expr_error(s, a), "labels" => Ok(json!(Label::ALL.iter().map(|l| l.name()).collect::>())), "effects" => Ok(json!( effectcraft_engine::effects::all() @@ -532,6 +527,7 @@ fn text_json(d: &TextDoc) -> J { doc } +/// Returns the property's value at the requested time, evaluating its expression unless `pre` is set. fn value(s: &Session, a: &J) -> R { let (cid, c, l) = layer_of(s, a)?; let uid = u(a, "uid").ok_or("missing uid")?; @@ -541,16 +537,28 @@ fn value(s: &Session, a: &J) -> R { let v = if pre || !p.has_expression() { p.value_at(l.layer_time(t)) } else { - let mut ctx = EvalCtx::new(&s.project, cid, c, t); - ctx.expr = s.expr.as_deref(); // Sample expressions (`sampleImage`) read footage through the session's source; without // it footage layers sample as transparent (#1000). - ctx.footage = Some(s.footage.as_ref()); - ctx.value(l, p) + effectcraft_engine::commands::expr_tools::eval_ctx(s, cid, c, t).value(l, p) }; Ok(js_value(c, &v)) } +/// `Property.expressionError`: why the property's expression fails at the comp's current time +/// (where After Effects evaluates it; the prelude sends no `time`, a direct query may give one +/// in comp seconds). The message is the one `expr.errors` gives: an evaluation error (an +/// exception or a non-finite result) or the syntax error that disabled it; `""` when it +/// evaluates (#3219). +fn expr_error(s: &Session, a: &J) -> R { + let (cid, c, l) = layer_of(s, a)?; + let uid = u(a, "uid").ok_or("missing uid")?; + let p = l.props.find(uid).ok_or("the property no longer exists (it was deleted)")?; + let t = f(a, "time").map(Tick::from_seconds_f64).unwrap_or_else(|| s.time_of(cid)); + // With the footage source, like `value`: `sampleImage` must not fail for want of it (#1000). + let ctx = EvalCtx { footage: Some(s.footage.as_ref()), expr: s.expr.as_deref(), ..EvalCtx::new(&s.project, cid, c, t) }; + Ok(json!(effectcraft_engine::commands::expr_tools::property_error(&ctx, s.expr_check, l, p).unwrap_or_default())) +} + fn interp(i: Interp) -> &'static str { match i { Interp::Linear => "LINEAR", diff --git a/crates/script/src/prelude.js b/crates/script/src/prelude.js index 4b65a5298..f33da7091 100644 --- a/crates/script/src/prelude.js +++ b/crates/script/src/prelude.js @@ -79,9 +79,10 @@ BlendingMode.SILHOUETTE_ALPHA = BlendingMode.SILHOUETE_ALPHA; var KeyframeInterpolationType = __enum("KeyframeInterpolationType", ["LINEAR", "BEZIER", "HOLD"], 6612); var TrackMatteType = __enum("TrackMatteType", ["NO_TRACK_MATTE", "ALPHA", "ALPHA_INVERTED", "LUMA", "LUMA_INVERTED"], 5012); var LightType = __enum("LightType", ["PARALLEL", "SPOT", "POINT", "AMBIENT", "ENVIRONMENT"], 4412); +// In After Effects' order and numbers (26.3): right comes before centre. var ParagraphJustification = __enum("ParagraphJustification", [ - "LEFT_JUSTIFY", "CENTER_JUSTIFY", "RIGHT_JUSTIFY", "FULL_JUSTIFY_LASTLINE_LEFT", "FULL_JUSTIFY_LASTLINE_CENTER", - "FULL_JUSTIFY_LASTLINE_RIGHT", "FULL_JUSTIFY_LASTLINE_FULL", "MULTIPLE_JUSTIFICATIONS"], 7413); + "MULTIPLE_JUSTIFICATIONS", "LEFT_JUSTIFY", "RIGHT_JUSTIFY", "CENTER_JUSTIFY", "FULL_JUSTIFY_LASTLINE_LEFT", + "FULL_JUSTIFY_LASTLINE_RIGHT", "FULL_JUSTIFY_LASTLINE_CENTER", "FULL_JUSTIFY_LASTLINE_FULL"], 7412); var PropertyValueType = __enum("PropertyValueType", [ "NO_VALUE", "ThreeD_SPATIAL", "ThreeD", "TwoD_SPATIAL", "TwoD", "OneD", "COLOR", "CUSTOM_VALUE", "MARKER", "LAYER_INDEX", "MASK_INDEX", "SHAPE", "TEXT_DOCUMENT"], 6412); @@ -120,7 +121,14 @@ function __blendLabel(v) { var __interpKey = { 6612: "linear", 6613: "bezier", 6614: "hold" }; var __matteKind = { 5013: "alpha", 5014: "alphaInverted", 5015: "luma", 5016: "lumaInverted" }; var __matteEnum = { Alpha: 5013, AlphaInverted: 5014, Luma: 5015, LumaInverted: 5016 }; -var __justKey = { 7413: "left", 7414: "center", 7415: "right", 7416: "justifyLeft", 7417: "justifyCenter", 7418: "justifyRight", 7419: "justifyAll" }; +var __justKey = {}; +__justKey[ParagraphJustification.LEFT_JUSTIFY] = "left"; +__justKey[ParagraphJustification.CENTER_JUSTIFY] = "center"; +__justKey[ParagraphJustification.RIGHT_JUSTIFY] = "right"; +__justKey[ParagraphJustification.FULL_JUSTIFY_LASTLINE_LEFT] = "justifyLeft"; +__justKey[ParagraphJustification.FULL_JUSTIFY_LASTLINE_CENTER] = "justifyCenter"; +__justKey[ParagraphJustification.FULL_JUSTIFY_LASTLINE_RIGHT] = "justifyRight"; +__justKey[ParagraphJustification.FULL_JUSTIFY_LASTLINE_FULL] = "justifyAll"; // ------------------------------------------------------------------ output, $ and dialogs @@ -860,8 +868,8 @@ Property.prototype.property = function () { return null; }; __call("prop.setExpression", this.__ref({ enabled: !!v })); }); def("expressionError", function () { - var e = this.expression; - return e ? __get("exprError", { code: e }) : ""; + // Evaluated at the comp's current time, so a runtime error or a non-finite result shows too. + return this.expression ? __get("exprError", { comp: this.__layer.__comp, layer: this.__layer.__id, uid: this.__uid }) : ""; }); def("canSetExpression", function () { return !!this.__info().canSetExpression; }); def("canVaryOverTime", function () { return !!this.__info().canVaryOverTime; }); diff --git a/crates/script/src/tests.rs b/crates/script/src/tests.rs index 8995b8202..52b338e31 100644 --- a/crates/script/src/tests.rs +++ b/crates/script/src/tests.rs @@ -16,6 +16,7 @@ mod ease_presets; mod evalfile; mod include; mod panels; +mod paragraph_justification; #[cfg(not(target_arch = "wasm32"))] mod render_wait; #[cfg(not(windows))] @@ -1305,6 +1306,41 @@ fn sample_image_reads_footage_pixels_in_scripts() { assert_eq!(out.result, json!([0, 1, 0, 1, ""]), "green footage sampled, not transparent black"); } +/// `expressionError` reports what evaluating the expression at the comp's current time does, as +/// After Effects: a non-finite result and an exception, not only a syntax error (#3219). +#[test] +fn expression_error_reports_evaluation_errors() { + let mut s = session(); + let out = ok( + &mut s, + r#" + var c = app.project.items.addComp("E", 320, 240, 1, 5, 30); + var p = c.layers.addSolid([1, 1, 1], "S", 320, 240, 1).transform.opacity; + p.expression = "Math.sqrt(-1)"; + var nan = p.expressionError; + p.expression = 'throw new Error("boom")'; + var thrown = p.expressionError; + p.expression = "value"; + var fine = p.expressionError; + p.expression = "thisLayer.nope("; + var syntax = p.expressionError; + p.expression = "time > 1 ? Math.sqrt(-1) : value"; + c.time = 0; + var early = p.expressionError; + c.time = 2; + var late = p.expressionError; + [nan, thrown, fine, syntax.length > 0, early, late]; + "#, + ); + let v = out.result; + assert!(v[0].as_str().is_some_and(|e| e.contains("not a finite number")), "{v}"); + assert!(v[1].as_str().is_some_and(|e| e.contains("boom")), "{v}"); + assert_eq!(v[2], json!(""), "{v}"); + assert_eq!(v[3], json!(true), "a syntax error is still reported: {v}"); + assert_eq!(v[4], json!(""), "evaluated at the current time (0), where it is fine: {v}"); + assert!(v[5].as_str().is_some_and(|e| e.contains("not a finite number")), "evaluated at the current time (2): {v}"); +} + #[test] fn binary_file_io_preserves_all_byte_values() { let dir = std::env::temp_dir().join(format!("ec-script-binary-{}", std::process::id())); diff --git a/crates/script/src/tests/paragraph_justification.rs b/crates/script/src/tests/paragraph_justification.rs new file mode 100644 index 000000000..3b618170c --- /dev/null +++ b/crates/script/src/tests/paragraph_justification.rs @@ -0,0 +1,48 @@ +//! `ParagraphJustification` has After Effects' numbers (26.3): MULTIPLE_JUSTIFICATIONS 7412, +//! LEFT 7413, RIGHT 7414, CENTER 7415, then the justified variants with the last line left (7416), +//! right (7417), centred (7418) and full (7419). A script that stores or compares the numbers gets +//! the same paragraph in both applications. + +use serde_json::json; + +use super::{comp_named, ok, session}; +use effectcraft_engine::keyframe::{Justify, Value as KV}; + +#[test] +fn the_numbers_are_after_effects() { + let mut s = session(); + let o = ok( + &mut s, + r#" + var P = ParagraphJustification; + [P.MULTIPLE_JUSTIFICATIONS, P.LEFT_JUSTIFY, P.RIGHT_JUSTIFY, P.CENTER_JUSTIFY, P.FULL_JUSTIFY_LASTLINE_LEFT, + P.FULL_JUSTIFY_LASTLINE_RIGHT, P.FULL_JUSTIFY_LASTLINE_CENTER, P.FULL_JUSTIFY_LASTLINE_FULL] + "#, + ); + assert_eq!(o.result, json!([7412, 7413, 7414, 7415, 7416, 7417, 7418, 7419])); +} + +#[test] +fn each_number_sets_and_reads_its_paragraph() { + let mut s = session(); + let o = ok( + &mut s, + r#" + var c = app.project.items.addComp("J", 200, 100, 1, 2, 30); + var t = c.layers.addText("ab"); + var st = t.property("ADBE Text Properties").property("ADBE Text Document"); + var back = []; + for (var n = 7413; n <= 7419; n++) { + var d = st.value; d.justification = n; st.setValue(d); + back.push(st.value.justification); + } + var d = st.value; d.justification = 7414; st.setValue(d); + back + "#, + ); + assert_eq!(o.result, json!([7413, 7414, 7415, 7416, 7417, 7418, 7419])); + // 7414 is right-aligned, as in After Effects. + let (_, c) = comp_named(&s, "J"); + let KV::Text(d) = &c.layers[0].props.prop("text/sourceText").unwrap().value else { panic!("not text") }; + assert_eq!(d.justify, Justify::Right); +} diff --git a/crates/svg/Cargo.toml b/crates/svg/Cargo.toml index 03cacaa7b..8b011879b 100644 --- a/crates/svg/Cargo.toml +++ b/crates/svg/Cargo.toml @@ -1,19 +1,20 @@ -[package] -name = "effectcraft-svg" -description = "SVG import: parses SVG 1.1 / SVG 2 static vector content (paths, basic shapes, groups, transforms, use, CSS styles, solid and gradient fills/strokes, opacity) and rasterises it at any scale" -version.workspace = true -edition.workspace = true -license.workspace = true -rust-version.workspace = true - -[lints] -workspace = true - -[dependencies] -effectcraft-geom = { workspace = true } -effectcraft-raster = { workspace = true } -effectcraft-path = { workspace = true } -kurbo = { workspace = true } -roxmltree = "0.21" -rayon = { workspace = true } -log = { workspace = true } +[package] +name = "effectcraft-svg" +description = "SVG import: parses SVG 1.1 / SVG 2 static vector content (paths, basic shapes, groups, transforms, use, CSS styles, solid, gradient and pattern fills/strokes, opacity) and rasterises it at any scale" +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true + +[lints] +workspace = true + +[dependencies] +craft-svg = { workspace = true } +effectcraft-geom = { workspace = true } +effectcraft-raster = { workspace = true } +effectcraft-path = { workspace = true } +kurbo = { workspace = true } +roxmltree = "0.21" +rayon = { workspace = true } +log = { workspace = true } diff --git a/crates/svg/README.md b/crates/svg/README.md index 862bd01d0..8496bb9f0 100644 --- a/crates/svg/README.md +++ b/crates/svg/README.md @@ -1,26 +1,48 @@ -# effectcraft-svg - -SVG import for EffectCraft: `.svg` files import as footage (rasterised at any scale, so -Continuously Rasterize stays sharp) and Layer ▸ Create ▸ Create Shapes from Vector Layer turns -them into editable shape layers. - -Implemented from the W3C **Scalable Vector Graphics (SVG) 1.1 (Second Edition)** recommendation -(16 August 2011) and the **SVG 2** candidate recommendation (4 October 2018) for the parts listed -here, plus **CSS Color Module Level 3** for colour keywords and functions: - -- document: `svg` (width/height, `viewBox`, `preserveAspectRatio`), nested `svg`, `g`, `defs`, - `use` (x/y, `href` / `xlink:href`), `symbol` (through `use`), `title`/`desc`/`metadata` ignored; -- shapes: `path` (all path data commands incl. elliptical arcs), `rect` (rx/ry), `circle`, - `ellipse`, `line`, `polyline`, `polygon`; -- `transform` lists (matrix, translate, scale, rotate with centre, skewX, skewY); -- painting: `fill`, `fill-rule`, `fill-opacity`, `stroke`, `stroke-width`, `stroke-linecap`, - `stroke-linejoin`, `stroke-miterlimit`, `stroke-dasharray`, `stroke-dashoffset`, - `stroke-opacity`, `opacity`, `display`, `visibility`, `color`/`currentColor`; -- `linearGradient` and `radialGradient` (with `fx`/`fy` focal point), `gradientUnits`, - `gradientTransform`, `spreadMethod`, `href` inheritance of stops and attributes; -- styling through presentation attributes, the `style` attribute and `{rects}"#).into_bytes() -} - -#[test] -fn comma_selector_lists_share_one_declaration_block() { - // Before #2140 every selector of a comma list got its own copy of the declaration block, so - // `a,a,a…{…}` stored selectors × declarations strings; one selector past the cap is refused. - let sels = vec!["rect"; MAX_CSS_SELECTORS + 1].join(","); - let decls: String = (0..10).map(|i| format!("p{i}:v;")).collect(); - let svg = styled(&format!("{sels}{{fill:red;{decls}}}"), &[""]); - let e = parse(&svg).unwrap_err(); - assert!(e.to_string().contains("selectors"), "{e}"); -} - -#[test] -fn a_style_sheet_with_too_many_declarations_errors() { - let decls: String = (0..=MAX_CSS_DECLARATIONS).map(|i| format!("p{i}:v;")).collect(); - let svg = styled(&format!("rect{{{decls}}}"), &[""]); - let e = parse(&svg).unwrap_err(); - assert!(e.to_string().contains("declarations"), "{e}"); -} - -#[test] -fn selector_lists_keep_the_css_cascade() { - let green = Some(Paint::Color([0.0, 1.0, 0.0])); - let blue = Some(Paint::Color([0.0, 0.0, 1.0])); - let red = Some(Paint::Color([1.0, 0.0, 0.0])); - let css = "rect, .b, #c { fill: #00ff00 } .b, .d { fill: #0000ff; stroke: #000000; stroke-width: 3 } rect.e, #c { fill: #ff0000 }"; - let svg = styled(css, &["", r#"class="b""#, r#"id="c" class="b""#, r#"class="b" style="fill:#00ff00""#, r##"class="e" fill="#0000ff""##, r#"class="d""#]); - let doc = parse(&svg).unwrap(); - let shapes = doc.flatten(); - let fills: Vec<_> = shapes.iter().map(|s| s.2.fill.clone()).collect(); - // Type selector; class beats type; id beats class; inline style beats every rule; a later, - // more specific rule beats the presentation attribute. - assert_eq!(fills, vec![green.clone(), blue.clone(), red.clone(), green, red, blue]); - assert!(shapes[0].2.stroke.is_none()); - // The second list's block reaches both of its selectors. - for i in [1, 5] { - assert_eq!(shapes[i].2.stroke.as_ref().map(|s| s.width), Some(3.0), "shape {i}"); - } -} - -#[test] -fn a_comma_list_stores_its_declarations_once() { - let sels = vec!["rect"; 1000].join(","); - let decls: String = (0..50).map(|i| format!("p{i}:v;")).collect(); - let mut sheet = StyleSheet::default(); - parse_css(&format!("{sels}{{{decls}}}"), &mut sheet).unwrap(); - assert_eq!(sheet.rules.len(), 1000); - assert_eq!(sheet.blocks.len(), 1); - assert_eq!(sheet.decls, 50); -} - -#[test] -fn rules_of_unsupported_selectors_store_no_blocks() { - let mut sheet = StyleSheet::default(); - parse_css(&"a b{}".repeat(100_000), &mut sheet).unwrap(); - parse_css("a b{fill:red} a>b, rect{fill:blue} c:hover, d{fill:red}", &mut sheet).unwrap(); - assert_eq!(sheet.rules.len(), 2); - assert_eq!(sheet.blocks.len(), 2); - assert!(sheet.rules.iter().all(|r| sheet.blocks.get(r.block).is_some_and(|b| b.len() == 1))); -} - -#[test] -fn huge_class_lists_count_against_the_matching_budget() { - // One rule, but a 1 MB class attribute re-split on each of 100 `` copies (#2140). - let class = "a ".repeat(500_000); - let uses: String = (0..100).map(|i| format!(r##""##)).collect(); - let svg = |uses: &str| { - format!( - r##"{uses}"## - ) - }; - let e = parse(svg(&uses).as_bytes()).unwrap_err(); - assert!(e.to_string().contains("{uses}"## - ) - }; - let e = parse(svg(&uses).as_bytes()).unwrap_err(); - assert!(e.to_string().contains("{rects}"#).into_bytes() +} + +#[test] +fn comma_selector_lists_share_one_declaration_block() { + // Before #2140 every selector of a comma list got its own copy of the declaration block, so + // `a,a,a…{…}` stored selectors × declarations strings; one selector past the cap is refused. + let sels = vec!["rect"; MAX_CSS_SELECTORS + 1].join(","); + let decls: String = (0..10).map(|i| format!("p{i}:v;")).collect(); + let svg = styled(&format!("{sels}{{fill:red;{decls}}}"), &[""]); + let e = parse(&svg).unwrap_err(); + assert!(e.to_string().contains("selectors"), "{e}"); +} + +#[test] +fn a_style_sheet_with_too_many_declarations_errors() { + let decls: String = (0..=MAX_CSS_DECLARATIONS).map(|i| format!("p{i}:v;")).collect(); + let svg = styled(&format!("rect{{{decls}}}"), &[""]); + let e = parse(&svg).unwrap_err(); + assert!(e.to_string().contains("declarations"), "{e}"); +} + +#[test] +fn selector_lists_keep_the_css_cascade() { + let green = Some(Paint::Color([0.0, 1.0, 0.0])); + let blue = Some(Paint::Color([0.0, 0.0, 1.0])); + let red = Some(Paint::Color([1.0, 0.0, 0.0])); + let css = "rect, .b, #c { fill: #00ff00 } .b, .d { fill: #0000ff; stroke: #000000; stroke-width: 3 } rect.e, #c { fill: #ff0000 }"; + let svg = styled(css, &["", r#"class="b""#, r#"id="c" class="b""#, r#"class="b" style="fill:#00ff00""#, r##"class="e" fill="#0000ff""##, r#"class="d""#]); + let doc = parse(&svg).unwrap(); + let shapes = doc.flatten(); + let fills: Vec<_> = shapes.iter().map(|s| s.2.fill.clone()).collect(); + // Type selector; class beats type; id beats class; inline style beats every rule; a later, + // more specific rule beats the presentation attribute. + assert_eq!(fills, vec![green.clone(), blue.clone(), red.clone(), green, red, blue]); + assert!(shapes[0].2.stroke.is_none()); + // The second list's block reaches both of its selectors. + for i in [1, 5] { + assert_eq!(shapes[i].2.stroke.as_ref().map(|s| s.width), Some(3.0), "shape {i}"); + } +} + +#[test] +fn a_comma_list_stores_its_declarations_once() { + let sels = vec!["rect"; 1000].join(","); + let decls: String = (0..50).map(|i| format!("p{i}:v;")).collect(); + let mut sheet = StyleSheet::default(); + parse_css(&format!("{sels}{{{decls}}}"), &mut sheet).unwrap(); + assert_eq!(sheet.rules.len(), 1000); + assert_eq!(sheet.blocks.len(), 1); + assert_eq!(sheet.decls, 50); +} + +#[test] +fn rules_of_unsupported_selectors_store_no_blocks() { + let mut sheet = StyleSheet::default(); + parse_css(&"a b{}".repeat(100_000), &mut sheet).unwrap(); + parse_css("a b{fill:red} a>b, rect{fill:blue} c:hover, d{fill:red}", &mut sheet).unwrap(); + assert_eq!(sheet.rules.len(), 2); + assert_eq!(sheet.blocks.len(), 2); + assert!(sheet.rules.iter().all(|r| sheet.blocks.get(r.block).is_some_and(|b| b.len() == 1))); +} + +#[test] +fn huge_class_lists_count_against_the_matching_budget() { + // One rule, but a 1 MB class attribute re-split on each of 100 `` copies (#2140). + let class = "a ".repeat(500_000); + let uses: String = (0..100).map(|i| format!(r##""##)).collect(); + let svg = |uses: &str| { + format!( + r##"{uses}"## + ) + }; + let e = parse(svg(&uses).as_bytes()).unwrap_err(); + assert!(e.to_string().contains("{uses}"## + ) + }; + let e = parse(svg(&uses).as_bytes()).unwrap_err(); + assert!(e.to_string().contains("