Compare commits
117
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb6b6fa9e3 | ||
|
|
9646eef487 | ||
|
|
6f67ddb709 | ||
|
|
2cbc35f181 | ||
|
|
4f66ddb515 | ||
|
|
b14972f657 | ||
|
|
77eb2c2d33 | ||
|
|
4f58edf436 | ||
|
|
01b20165cc | ||
|
|
4b2802076b | ||
|
|
943ff7c15f | ||
|
|
f13a127c9d | ||
|
|
a0ac4f2d35 | ||
|
|
b8419778a5 | ||
|
|
08b6aa0139 | ||
|
|
87263489c0 | ||
|
|
f2cb516e8a | ||
|
|
b25e639a1c | ||
|
|
01fe14f197 | ||
|
|
3b39e80e40 | ||
|
|
0e3c437d50 | ||
|
|
76e7963f03 | ||
|
|
597697d0a6 | ||
|
|
0c59ed8b4b | ||
|
|
79f063d00c | ||
|
|
5ee2df5db7 | ||
|
|
da0b39fef0 | ||
|
|
fd582828c2 | ||
|
|
58a3c829d7 | ||
|
|
9717289271 | ||
|
|
b301c63387 | ||
|
|
1fa4d744be | ||
|
|
5869e3ced1 | ||
|
|
69939c066d | ||
|
|
5bc117c518 | ||
|
|
fffcf0679c | ||
|
|
02566d571b | ||
|
|
701b57bfe8 | ||
|
|
ca9a70e10a | ||
|
|
bb3369b709 | ||
|
|
33dec6f327 | ||
|
|
41e4f3b12b | ||
|
|
28b14b2ad0 | ||
|
|
7c2ac0e4d8 | ||
|
|
83410bd4b4 | ||
|
|
6c8cb5b9e0 | ||
|
|
b76eefb404 | ||
|
|
ff490ab9ae | ||
|
|
6348e57de0 | ||
|
|
1c537d99da | ||
|
|
1848c920d9 | ||
|
|
863edc80fc | ||
|
|
7909b51df1 | ||
|
|
ca612d7807 | ||
|
|
255e16434e | ||
|
|
9411145ce9 | ||
|
|
f1fba186c1 | ||
|
|
aa7d3a3bf4 | ||
|
|
7525a604f2 | ||
|
|
e7c239f203 | ||
|
|
7ebd64391c | ||
|
|
05b5bf5f85 | ||
|
|
5bed2e8adb | ||
|
|
911d896610 | ||
|
|
ecfa192245 | ||
|
|
2bce5e93a6 | ||
|
|
3e4f29c297 | ||
|
|
a00e73c4b3 | ||
|
|
ba897eaea2 | ||
|
|
5917ce7921 | ||
|
|
da65b63bdf | ||
|
|
2564d807a0 | ||
|
|
70ac0cde00 | ||
|
|
5844a0f070 | ||
|
|
ce151ffd61 | ||
|
|
34eee3a620 | ||
|
|
5f0d5354ed | ||
|
|
bf4331eed4 | ||
|
|
273862c882 | ||
|
|
a3f18bdab6 | ||
|
|
2c40858663 | ||
|
|
149760e9c0 | ||
|
|
1cb821f05b | ||
|
|
8223593649 | ||
|
|
83057b754a | ||
|
|
3c3a482e2e | ||
|
|
5fd04b5dd5 | ||
|
|
a1acecf396 | ||
|
|
1dd5de4617 | ||
|
|
0d1f62ccce | ||
|
|
87bcffd427 | ||
|
|
39978e59b3 | ||
|
|
0d253d9629 | ||
|
|
0914818808 | ||
|
|
b292e0e6e6 | ||
|
|
4e9cacb789 | ||
|
|
0a0d7cd0a9 | ||
|
|
5f3cb41c18 | ||
|
|
6a788a432e | ||
|
|
0883c77e2b | ||
|
|
3d0a334014 | ||
|
|
d05cbfcde5 | ||
|
|
fcc8102a9d | ||
|
|
7a150fb5c5 | ||
|
|
2f3b0d7790 | ||
|
|
aad2d5c515 | ||
|
|
6fc3a131a6 | ||
|
|
659bc5fb02 | ||
|
|
6c9fcb1921 | ||
|
|
aea26f6192 | ||
|
|
c936078850 | ||
|
|
7445ee919f | ||
|
|
10b4aa481e | ||
|
|
c2c7aefad1 | ||
|
|
78109cda93 | ||
|
|
4dc937f9c0 | ||
|
|
53cae1bfe5 |
+61
-10
@@ -71,6 +71,7 @@ jobs:
|
||||
libx11-dev libxkbcommon-dev libxcb-shape0-dev libxcb-xfixes0-dev \
|
||||
libxdo-dev libglib2.0-dev libgtk-3-dev libvulkan-dev \
|
||||
yasm libx264-dev libx265-dev libvpx-dev libmp3lame-dev libopus-dev \
|
||||
libva-dev libdrm-dev \
|
||||
libpulse-dev squashfs-tools dpkg rpm
|
||||
|
||||
- name: Install cargo packaging tools (Linux)
|
||||
@@ -88,7 +89,20 @@ jobs:
|
||||
- name: Install dependencies (Windows)
|
||||
if: matrix.platform == 'windows-latest'
|
||||
shell: pwsh
|
||||
run: choco install cmake llvm --installargs 'ADD_CMAKE_TO_PATH=System' -y
|
||||
run: |
|
||||
choco install cmake llvm --installargs 'ADD_CMAKE_TO_PATH=System' -y
|
||||
# Ninja: build NeuralAudio with it instead of a Visual Studio generator,
|
||||
# so the cmake crate doesn't need to recognize the runner's VS version.
|
||||
choco install ninja -y
|
||||
|
||||
# Activate the MSVC developer environment (runs vcvars) so the cmake crate
|
||||
# building nam-ffi/NeuralAudio can determine the Visual Studio generator.
|
||||
# Without this, cmake-rs panics with "couldn't determine visual studio generator".
|
||||
- name: Set up MSVC developer environment (Windows)
|
||||
if: matrix.platform == 'windows-latest'
|
||||
uses: ilammy/msvc-dev-cmd@v1
|
||||
with:
|
||||
arch: x64
|
||||
|
||||
# ── Common build steps ──
|
||||
- name: Extract version
|
||||
@@ -104,6 +118,19 @@ jobs:
|
||||
run: |
|
||||
sed -i.bak 's/ffmpeg-next = { version = "8.0", features = \["static"\] }/ffmpeg-next = { version = "8.0", features = ["build", "static"] }/' lightningbeam-ui/lightningbeam-editor/Cargo.toml
|
||||
|
||||
# ffmpeg-sys-next configures FFmpeg with --disable-autodetect and only passes --enable-vaapi
|
||||
# when its build-vaapi feature is set; ffmpeg-next 8.0 doesn't forward it, so depend on the
|
||||
# sys crate directly. Linux only (the feature is a no-op elsewhere and we only ship VAAPI on
|
||||
# Linux). With it set, a missing libva-dev makes FFmpeg configure fail loudly instead of
|
||||
# silently shipping a software-only build.
|
||||
- name: Enable VAAPI in FFmpeg build (Linux)
|
||||
if: matrix.platform == 'ubuntu-24.04'
|
||||
shell: bash
|
||||
run: |
|
||||
sed -i '/^ffmpeg-next = /a ffmpeg-sys-next = { version = "8.0", features = ["build-vaapi"] }' \
|
||||
lightningbeam-ui/lightningbeam-editor/Cargo.toml
|
||||
grep -n 'ffmpeg-sys-next' lightningbeam-ui/lightningbeam-editor/Cargo.toml
|
||||
|
||||
- name: Setup FFmpeg (Windows)
|
||||
if: matrix.platform == 'windows-latest'
|
||||
shell: pwsh
|
||||
@@ -117,14 +144,6 @@ jobs:
|
||||
# LLVM/libclang for bindgen
|
||||
echo "LIBCLANG_PATH=C:\Program Files\LLVM\bin" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
|
||||
|
||||
- name: Setup icons
|
||||
shell: bash
|
||||
run: |
|
||||
mkdir -p lightningbeam-ui/lightningbeam-editor/assets/icons
|
||||
cp -f src-tauri/icons/32x32.png lightningbeam-ui/lightningbeam-editor/assets/icons/
|
||||
cp -f src-tauri/icons/128x128.png lightningbeam-ui/lightningbeam-editor/assets/icons/
|
||||
cp -f src-tauri/icons/icon.png lightningbeam-ui/lightningbeam-editor/assets/icons/256x256.png
|
||||
|
||||
- name: Stage factory presets
|
||||
shell: bash
|
||||
run: |
|
||||
@@ -161,6 +180,7 @@ jobs:
|
||||
echo "MACOSX_DEPLOYMENT_TARGET=11.0" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Build release binary
|
||||
if: matrix.platform != 'windows-latest'
|
||||
shell: bash
|
||||
env:
|
||||
FFMPEG_STATIC: "1"
|
||||
@@ -172,6 +192,23 @@ jobs:
|
||||
fi
|
||||
cargo build --release --bin lightningbeam-editor $TARGET_FLAG
|
||||
|
||||
# Windows must build under pwsh, not Git Bash: Git for Windows puts its
|
||||
# usr\bin on PATH ahead of the MSVC tools, so its coreutils `link.exe`
|
||||
# shadows MSVC's linker and rustc fails with "extra operand". pwsh keeps
|
||||
# the MSVC environment (set by msvc-dev-cmd) at the front of PATH.
|
||||
- name: Build release binary (Windows)
|
||||
if: matrix.platform == 'windows-latest'
|
||||
shell: pwsh
|
||||
env:
|
||||
FFMPEG_STATIC: "1"
|
||||
# Force Ninja for the cmake crate (nam-ffi/NeuralAudio): cmake-rs 0.1.54
|
||||
# panics on "unknown VisualStudio version: 18.0" when it auto-detects the
|
||||
# runner's VS generator. Ninja sidesteps that lookup entirely.
|
||||
CMAKE_GENERATOR: Ninja
|
||||
run: |
|
||||
cd lightningbeam-ui
|
||||
cargo build --release --bin lightningbeam-editor
|
||||
|
||||
- name: Copy cross-compiled binary to release dir
|
||||
if: matrix.target != ''
|
||||
shell: bash
|
||||
@@ -179,6 +216,20 @@ jobs:
|
||||
mkdir -p lightningbeam-ui/target/release
|
||||
cp lightningbeam-ui/target/${{ matrix.target }}/release/lightningbeam-editor lightningbeam-ui/target/release/
|
||||
|
||||
# Guard: the zero-copy export needs the static ffmpeg to have h264_vaapi, which only
|
||||
# happens if libva headers were present at ffmpeg configure time. ffmpeg autodetects it,
|
||||
# so a missing libva-dev silently ships a software-only build. A vaapi-enabled binary
|
||||
# links libva — assert that, so the dep can never regress unnoticed.
|
||||
- name: Verify VAAPI is compiled in (Linux)
|
||||
if: matrix.platform == 'ubuntu-24.04'
|
||||
shell: bash
|
||||
run: |
|
||||
if ! ldd lightningbeam-ui/target/release/lightningbeam-editor | grep -q 'libva\.so'; then
|
||||
echo "::error::Release binary does not link libva — ffmpeg was built without VAAPI (is libva-dev installed?)."
|
||||
exit 1
|
||||
fi
|
||||
echo "VAAPI OK: binary links libva."
|
||||
|
||||
# ── Stage presets next to binary for packaging ──
|
||||
- name: Stage presets in target dir
|
||||
shell: bash
|
||||
@@ -296,7 +347,7 @@ jobs:
|
||||
mkdir -p "$APP/Contents/Resources/presets"
|
||||
|
||||
cp lightningbeam-ui/target/release/lightningbeam-editor "$APP/Contents/MacOS/"
|
||||
cp src-tauri/icons/icon.icns "$APP/Contents/Resources/lightningbeam-editor.icns"
|
||||
cp lightningbeam-ui/lightningbeam-editor/assets/icons/icon.icns "$APP/Contents/Resources/lightningbeam-editor.icns"
|
||||
cp -r lightningbeam-ui/lightningbeam-editor/assets/presets/* "$APP/Contents/Resources/presets/"
|
||||
|
||||
cat > "$APP/Contents/Info.plist" << EOF
|
||||
|
||||
@@ -28,8 +28,6 @@ dist-ssr
|
||||
.gitignore
|
||||
|
||||
# Build
|
||||
src-tauri/gen
|
||||
src-tauri/target
|
||||
lightningbeam-core/target
|
||||
daw-backend/target
|
||||
target/
|
||||
|
||||
+2
-3
@@ -52,7 +52,7 @@ Lightningbeam is a 2D multimedia editor combining vector animation, audio produc
|
||||
|
||||
Lightningbeam is undergoing a rewrite from a Tauri/JavaScript prototype to pure Rust. The original architecture hit IPC bandwidth limitations when streaming decoded video frames. The new Rust UI eliminates this bottleneck by handling all rendering natively.
|
||||
|
||||
**Current Status**: Active development on the `rust-ui` branch. Core UI, tools, and undo system are implemented. Audio integration in progress.
|
||||
**Current Status**: Active development on the `main` branch. Core UI, tools, undo system, and audio integration are implemented.
|
||||
|
||||
## Technology Stack
|
||||
|
||||
@@ -486,8 +486,7 @@ lightningbeam-2/
|
||||
│ ├── synth/ # Synthesizers
|
||||
│ └── midi/ # MIDI handling
|
||||
│
|
||||
├── src-tauri/ # Legacy Tauri backend
|
||||
├── src/ # Legacy JavaScript frontend
|
||||
├── src/ # Legacy JavaScript frontend (browser-only)
|
||||
├── CONTRIBUTING.md # Contributor guide
|
||||
├── ARCHITECTURE.md # This file
|
||||
├── README.md # Project overview
|
||||
|
||||
@@ -0,0 +1,484 @@
|
||||
# `.beam` File Format Specification
|
||||
|
||||
**Status:** Normative.
|
||||
**Container schema version:** `1` (`meta.schema_version`).
|
||||
**Project payload version:** `1.0.0` (`BeamProject.version` / `meta.version`).
|
||||
**Last updated:** 2026-06-21.
|
||||
|
||||
This document specifies the on-disk format of Lightningbeam `.beam` project files
|
||||
precisely enough that an independent implementation can read and write them. It
|
||||
describes the **current** format — a SQLite database — and the **legacy** format
|
||||
(a ZIP archive) that current readers still accept and migrate.
|
||||
|
||||
> An earlier revision of this document described the ZIP container as the current
|
||||
> format. That is now historical; see [§11 Legacy ZIP format](#11-legacy-zip-format-pre-sqlite).
|
||||
|
||||
## 1. Notational conventions
|
||||
|
||||
The key words **MUST**, **MUST NOT**, **SHOULD**, **SHOULD NOT**, and **MAY** are
|
||||
to be interpreted as described in RFC 2119.
|
||||
|
||||
Byte sizes use binary units: `KiB = 1024`, `MiB = 1024²`, `GiB = 1024³`.
|
||||
|
||||
"UUID" means an RFC 4122 128-bit identifier. Unless stated otherwise, a UUID is
|
||||
serialized in JSON as its canonical hyphenated lowercase string, and stored in
|
||||
SQLite as its 16 raw bytes in **network (big-endian) byte order** — i.e. the byte
|
||||
sequence returned by `Uuid::as_bytes`, most significant byte first.
|
||||
|
||||
## 2. Overview
|
||||
|
||||
A `.beam` file is a **single SQLite 3 database** (default rollback journal; no WAL,
|
||||
no special pragmas) containing:
|
||||
|
||||
- one JSON document, `project.json`, holding all project state that is small and
|
||||
structural (the document/scene tree, audio project, asset metadata); and
|
||||
- zero or more **media** items (audio, raster frames, image assets, and derived
|
||||
blobs such as waveforms and thumbnails), each either **packed** into the database
|
||||
in chunks or **referenced** by an external file path.
|
||||
|
||||
The design goals are: a single beginner-friendly file (no project folder);
|
||||
streaming reads of large media via SQLite blob I/O; transactional, crash-safe,
|
||||
**in-place** saves that do not rewrite unchanged media; and inspectability with the
|
||||
ordinary `sqlite3` CLI.
|
||||
|
||||
## 3. File identification
|
||||
|
||||
A reader MUST determine the container type from the first 16 bytes of the file:
|
||||
|
||||
- If the first 16 bytes equal the ASCII string `SQLite format 3\0` (i.e.
|
||||
`53 51 4C 69 74 65 20 66 6F 72 6D 61 74 20 33 00`), the file is a SQLite
|
||||
`.beam` and MUST be read per [§4](#4-container-the-sqlite-schema)–[§10](#10-load-semantics).
|
||||
- Otherwise the file is treated as a [legacy ZIP `.beam`](#11-legacy-zip-format-pre-sqlite)
|
||||
(ZIP local-file-header magic `50 4B 03 04`).
|
||||
|
||||
The `.beam` extension is used for both container types; the magic bytes — not the
|
||||
extension — are authoritative.
|
||||
|
||||
## 4. Container: the SQLite schema
|
||||
|
||||
A conforming SQLite `.beam` MUST contain exactly these four tables (DDL as created;
|
||||
column order and types are normative):
|
||||
|
||||
```sql
|
||||
CREATE TABLE media (
|
||||
id BLOB PRIMARY KEY, -- 16-byte UUID (big-endian)
|
||||
kind INTEGER NOT NULL, -- MediaKind (§6.1)
|
||||
codec TEXT NOT NULL, -- original codec/container, e.g. "flac","mp3","png"
|
||||
storage INTEGER NOT NULL, -- MediaStorage (§6.2): 0=Packed, 1=Referenced
|
||||
ext_path TEXT, -- external path, set iff storage=Referenced
|
||||
total_len INTEGER NOT NULL DEFAULT 0, -- payload length in bytes (packed); 0 if referenced
|
||||
channels INTEGER, -- audio: channel count (nullable)
|
||||
sample_rate INTEGER, -- audio: sample rate in Hz (nullable)
|
||||
width INTEGER, -- visual media: pixel width (nullable)
|
||||
height INTEGER -- visual media: pixel height (nullable)
|
||||
);
|
||||
|
||||
CREATE TABLE media_chunk (
|
||||
id INTEGER PRIMARY KEY, -- rowid (used as the handle for blob streaming)
|
||||
media_id BLOB NOT NULL, -- → media.id
|
||||
chunk_index INTEGER NOT NULL, -- 0-based ordinal of this chunk
|
||||
bytes BLOB NOT NULL, -- chunk payload
|
||||
UNIQUE (media_id, chunk_index)
|
||||
);
|
||||
|
||||
CREATE TABLE project_json (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 0), -- exactly one row, id 0
|
||||
data TEXT NOT NULL -- the serialized BeamProject (§8)
|
||||
);
|
||||
|
||||
CREATE TABLE meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
```
|
||||
|
||||
There is no foreign-key constraint between `media_chunk.media_id` and `media.id`;
|
||||
referential integrity is maintained by the writer. A reader MUST NOT assume SQLite
|
||||
enforces it.
|
||||
|
||||
### 4.1 The `meta` table
|
||||
|
||||
Defined keys (all values are strings):
|
||||
|
||||
| Key | Value | Meaning |
|
||||
|------------------|--------------------|---------|
|
||||
| `schema_version` | `"1"` | Container schema version. Set once at creation. |
|
||||
| `version` | `"1.0.0"` | Project payload version (mirrors `project.json`'s `version`). |
|
||||
| `created` | RFC 3339 timestamp | Creation time. Preserved across in-place re-saves. |
|
||||
| `modified` | RFC 3339 timestamp | Last save time. Updated on every save. |
|
||||
|
||||
Writers MAY add additional keys; readers MUST ignore unknown keys.
|
||||
|
||||
### 4.2 Two independent version numbers
|
||||
|
||||
The format carries **two** version numbers with different compatibility rules:
|
||||
|
||||
- **`meta.schema_version`** (`INTEGER`, currently `1`) — versions the SQLite
|
||||
container/table layout. A reader MUST reject a file whose `schema_version` is
|
||||
**greater** than the highest it supports, and SHOULD accept any value less than
|
||||
or equal to its maximum (forward-compatible for older files).
|
||||
- **`BeamProject.version`** / `meta.version` (currently `"1.0.0"`) — versions the
|
||||
`project.json` payload. The current implementation requires **exact string
|
||||
equality** and rejects any other value. A future revision MAY relax this to a
|
||||
semantic-version range; until then, writers MUST emit exactly `"1.0.0"` and
|
||||
readers reject anything else.
|
||||
|
||||
These two numbers are orthogonal and MUST both be checked.
|
||||
|
||||
## 5. UUIDs and identity
|
||||
|
||||
Every media item is identified by a UUID. In `project.json` UUIDs appear as
|
||||
canonical strings; in the `media`/`media_chunk` tables they appear as 16 raw
|
||||
big-endian bytes (`media.id`, `media_chunk.media_id`). A reader MUST treat the two
|
||||
representations as equal by their 128-bit value.
|
||||
|
||||
`media_chunk.id` is the SQLite rowid and is the handle a reader uses to open a blob
|
||||
for streaming (`sqlite3_blob_open` on table `media_chunk`, column `bytes`). It has
|
||||
no meaning beyond row identity and MUST NOT be relied upon to be stable across
|
||||
re-saves.
|
||||
|
||||
## 6. Media model
|
||||
|
||||
### 6.1 `MediaKind` (`media.kind`)
|
||||
|
||||
| Value | Kind | `codec` examples | Notes |
|
||||
|-------|---------------|------------------|-------|
|
||||
| `0` | `Audio` | `flac`, `mp3`, `wav`, `ogg`, `opus`, `aac`, `m4a`, `alac`, `caf`, `aiff` | Source audio for a pool entry. |
|
||||
| `1` | `Video` | `mp4`, `mov`, … | A video clip's container bytes, keyed by the clip id. Packed under the large-media policy (referenced above 2 GiB unless `Pack`). Frames **and** the embedded audio stream are decoded directly from this blob. |
|
||||
| `2` | `Raster` | `png` | Full-resolution pixels of a raster keyframe (PNG-encoded RGBA). |
|
||||
| `3` | `ImageAsset` | `png`, `jpg`, … | An imported image asset's original bytes. |
|
||||
| `4` | `Waveform` | `lbwf` | Precomputed waveform LOD pyramid for an audio item. Opaque blob owned by `daw_backend::audio::waveform_pyramid`. |
|
||||
| `5` | `Thumbnail` | `lbtn` | A pack of precomputed video thumbnails for a clip. Opaque blob owned by the editor. |
|
||||
| `6` | `RasterProxy` | `png` | Low-resolution PNG proxy of a raster keyframe, shown during cold scrubs while full-res pages in. |
|
||||
|
||||
A reader MUST reject a `kind` value it does not recognise only if it needs that
|
||||
item; unknown kinds MAY otherwise be ignored.
|
||||
|
||||
### 6.2 `MediaStorage` (`media.storage`)
|
||||
|
||||
| Value | Storage | Bytes location | `total_len` | `ext_path` |
|
||||
|-------|--------------|----------------|-------------|------------|
|
||||
| `0` | `Packed` | `media_chunk` rows in this DB | payload length | `NULL` |
|
||||
| `1` | `Referenced` | external file at `ext_path` | `0` | path string |
|
||||
|
||||
### 6.3 Packed storage and chunking
|
||||
|
||||
Packed bytes are split into chunks of **`CHUNK_SIZE = 4 MiB`** and stored one chunk
|
||||
per `media_chunk` row, ordered by `chunk_index` ascending starting at `0`. The
|
||||
writer MUST:
|
||||
|
||||
1. set `media.total_len` to the exact total byte length of the payload;
|
||||
2. write `ceil(total_len / CHUNK_SIZE)` chunk rows (zero rows iff `total_len == 0`);
|
||||
3. make every chunk exactly `CHUNK_SIZE` bytes **except the last**, which holds the
|
||||
remainder `total_len − (n−1)·CHUNK_SIZE`.
|
||||
|
||||
Because chunk lengths are fully determined by `total_len` and `CHUNK_SIZE`, a reader
|
||||
performing random access MUST compute, for a byte offset `pos < total_len`:
|
||||
|
||||
```
|
||||
chunk_index = pos / CHUNK_SIZE
|
||||
offset_in_chunk = pos % CHUNK_SIZE
|
||||
chunk_len = min(CHUNK_SIZE, total_len − chunk_index·CHUNK_SIZE)
|
||||
```
|
||||
|
||||
and read from the row with that `chunk_index`. A reader MAY stream the whole payload
|
||||
by concatenating chunk `bytes` in `chunk_index` order. The chunk size MAY differ in
|
||||
files written by other tools; a robust reader SHOULD derive chunk boundaries from
|
||||
actual row lengths rather than assuming 4 MiB. (The reference reader assumes uniform
|
||||
`CHUNK_SIZE` except for the last chunk; writers targeting it MUST keep chunks
|
||||
uniform.)
|
||||
|
||||
### 6.4 Referenced storage
|
||||
|
||||
A referenced item stores only `ext_path` (with `total_len = 0` and no chunk rows).
|
||||
The path is resolved relative to the directory containing the `.beam` file unless it
|
||||
is absolute. If the file is absent at load time, the item is reported as a *missing
|
||||
file* ([§10.4](#104-missing-referenced-files)) — this is non-fatal.
|
||||
|
||||
## 7. Derived media IDs
|
||||
|
||||
Three media kinds are keyed by UUIDs **derived** from another id rather than by an
|
||||
independent random UUID. A reader/writer MUST compute them exactly as follows
|
||||
(`from_u128` constructs a UUID from a 128-bit big-endian integer):
|
||||
|
||||
| Kind | Derived from | Formula |
|
||||
|---------------|---------------------|---------|
|
||||
| `Waveform` | audio pool **index** `i` (`usize`) | `from_u128((0x4C42_5746 << 96) \| (i as u128))` — high 32 bits = `0x4C425746` ("LBWF"), low 96 bits = the pool index. |
|
||||
| `Thumbnail` | video clip UUID `c` | `from_u128(c.as_u128() ^ 0x4C42_544E_4C42_544E_4C42_544E_4C42_544E)` — full-width XOR with "LBTN" repeated 4×. |
|
||||
| `RasterProxy` | raster keyframe UUID `k` | `from_u128(k.as_u128() ^ 0x4C42_5058_4C42_5058_4C42_5058_4C42_5058)` — full-width XOR with "LBPX" repeated 4×. |
|
||||
|
||||
The full-resolution `Raster` row is keyed by the keyframe's **own** UUID (no
|
||||
derivation); an `ImageAsset` row is keyed by the asset's own UUID; a packed `Audio`
|
||||
row is keyed by the pool entry's `media_id`.
|
||||
|
||||
> Note the asymmetry: the waveform id ORs the pool index into the high bits, while
|
||||
> thumbnail/proxy ids XOR a 128-bit sentinel with a source UUID. This is intentional
|
||||
> (waveforms are keyed by *index*, not by a UUID) but is a sharp edge for
|
||||
> implementers.
|
||||
|
||||
## 8. `project.json`
|
||||
|
||||
`project_json.data` is a UTF-8 JSON document: the serde serialization of a
|
||||
`BeamProject`. This section specifies the top-level structure and the entities a
|
||||
reader needs to resolve media; the deep UI/scene tree is defined by the
|
||||
corresponding Rust types (serde field names match struct field names unless a
|
||||
`#[serde(rename)]` is noted) and is intentionally **not** enumerated exhaustively
|
||||
here.
|
||||
|
||||
### 8.1 `BeamProject` (root)
|
||||
|
||||
| Field | Type | Notes |
|
||||
|-----------------|---------------------------|-------|
|
||||
| `version` | string | MUST be `"1.0.0"`. |
|
||||
| `created` | string (RFC 3339) | |
|
||||
| `modified` | string (RFC 3339) | |
|
||||
| `ui_state` | `Document` | The scene/document tree (§8.2). |
|
||||
| `audio_backend` | `SerializedAudioBackend` | Audio engine state (§8.3). |
|
||||
|
||||
### 8.2 `Document` (top-level fields)
|
||||
|
||||
Collections that carry media linkage are **bold**:
|
||||
|
||||
- `id: Uuid`, `name: string`, `background_color`, `width: f64`, `height: f64`,
|
||||
`framerate: f64`, `duration: f64`
|
||||
- `time_signature`, `master_layer`, `timeline_mode` — all `#[serde(default)]`
|
||||
- `root: GraphicsObject` — the layer tree; raster keyframes live here and inside
|
||||
nested group/clip layers
|
||||
- **`image_assets: map<Uuid, ImageAsset>`** — keyed by asset UUID (= the media id)
|
||||
- **`video_clips: map<Uuid, VideoClip>`** — when `VideoClip.media_id` is set the
|
||||
video is packed (a `Video` media row at the clip id); otherwise `file_path` points
|
||||
at the external video file. Thumbnails are derived media (§7)
|
||||
- `vector_clips`, `audio_clips`, `instance_groups`, `effect_definitions`,
|
||||
`script_definitions`, the various `*_folders` asset trees — structural, no direct
|
||||
media-row linkage
|
||||
- `ui_layout`, `ui_layout_base` — `Option`, skipped when `None`
|
||||
- `current_time`, `layer_to_clip_map` — `#[serde(skip)]` (not persisted)
|
||||
|
||||
`RasterKeyframe` (within the layer tree) has `id: Uuid` (= its full-res `Raster`
|
||||
media id and the seed for its `RasterProxy` id), `time`, `width`, `height`,
|
||||
`tween_after`, and `stroke_log`. Pixel buffers are `#[serde(skip)]` and faulted in
|
||||
from media rows. (The legacy ZIP entry path `media/raster/<id>.png` is derived from
|
||||
`id`; older files may also carry a now-ignored `media_path` field.)
|
||||
|
||||
### 8.3 `SerializedAudioBackend`
|
||||
|
||||
| Field | Type | Notes |
|
||||
|----------------------|---------------------|-------|
|
||||
| `sample_rate` | `u32` | The project's system sample rate (mirrors `AudioProject.sample_rate`). Per-file rates are on each `AudioPoolEntry.sample_rate`. |
|
||||
| `project` | `AudioProject` | Tracks + MIDI clip pool (§8.4). |
|
||||
| `audio_pool_entries` | `[AudioPoolEntry]` | Audio source registry (§8.5). |
|
||||
| `layer_to_track_map` | `map<Uuid, u32>` | UI layer UUID → engine track id. `#[serde(default)]`. |
|
||||
|
||||
### 8.4 `AudioProject` (top-level fields)
|
||||
|
||||
`tracks: map<TrackId, TrackNode>`, `root_tracks: [TrackId]`, `next_track_id`,
|
||||
`sample_rate: u32`, `midi_clip_pool`, `next_midi_clip_instance_id`. DSP graphs are
|
||||
not serialized; they are rebuilt on load.
|
||||
|
||||
### 8.5 `AudioPoolEntry` (media linkage)
|
||||
|
||||
| Field | Type | Role |
|
||||
|-----------------|----------------------------|------|
|
||||
| `pool_index` | `usize` | Stable index; seeds the `Waveform` media id (§7). |
|
||||
| `name` | string | |
|
||||
| `media_id` | `Option<string>` (UUID) | Set ⇔ audio bytes are **packed** in this DB under that id. `#[serde(default, skip_serializing_if=None)]`. |
|
||||
| `relative_path` | `Option<string>` | Set ⇔ audio is **referenced** (external file) or missing. |
|
||||
| `embedded_data` | `Option<EmbeddedAudioData>`| Legacy/inline: `{ data_base64, format }`. Used when bytes are neither packed nor referenced. |
|
||||
| `sample_rate` | `u32` | Authoritative sample rate. |
|
||||
| `channels` | `u32` | Channel count. |
|
||||
| `duration` | `f64` | Seconds. |
|
||||
| `is_video_audio`| `bool` | If set, the entry is the audio track of a video. Referenced when the video is external; when the video is **packed**, `media_id` points at the video's `Video` row and the audio streams from that same blob. `#[serde(default, skip_if=false)]`. |
|
||||
| `waveform_blob` | (transient) | `#[serde(skip)]`; carries waveform bytes in memory only. |
|
||||
|
||||
### 8.6 Media linkage summary
|
||||
|
||||
| Media kind | Referenced from `project.json` by | Media-row id |
|
||||
|--------------------|-----------------------------------|--------------|
|
||||
| Audio (packed) | `AudioPoolEntry.media_id` | that UUID |
|
||||
| Audio (referenced) | `AudioPoolEntry.relative_path` | — (external) |
|
||||
| Audio (embedded) | `AudioPoolEntry.embedded_data` | — (inline base64) |
|
||||
| Raster (full) | `RasterKeyframe.id` | that UUID |
|
||||
| Raster proxy | derived from `RasterKeyframe.id` | §7 |
|
||||
| Image asset | `Document.image_assets` key / `ImageAsset.id` | that UUID |
|
||||
| Video (packed) | `VideoClip.media_id` (= clip id) | that UUID |
|
||||
| Video (referenced) | `VideoClip.file_path` | — (external) |
|
||||
| Video thumbnails | derived from `video_clips` key | §7 |
|
||||
| Waveform | derived from `AudioPoolEntry.pool_index` | §7 |
|
||||
|
||||
## 9. Save semantics
|
||||
|
||||
A conforming writer MUST perform all media, `project.json`, and `meta` writes for a
|
||||
save inside **one** SQLite transaction.
|
||||
|
||||
### 9.1 In-place vs. create
|
||||
|
||||
- If the target path exists **and** is already a SQLite `.beam`, the writer opens it
|
||||
and writes in place. Unchanged packed media MUST NOT be rewritten (§9.3); this is
|
||||
the central performance/crash-safety property, and writers MUST NOT use a
|
||||
copy-to-temp-and-rename flow for in-place saves.
|
||||
- Otherwise (new file, or migrating a legacy ZIP), the writer creates a fresh DB at
|
||||
`<path>.beam.tmp`, writes everything, commits, then atomically `rename`s it over
|
||||
the target.
|
||||
|
||||
### 9.2 Order of operations within the transaction
|
||||
|
||||
1. Audio pool entries → `Audio` (+ `Waveform`) media rows.
|
||||
2. Raster keyframes → `Raster` (+ `RasterProxy`) media rows.
|
||||
3. Video thumbnail packs → `Thumbnail` media rows.
|
||||
4. Video clips → `Video` media rows (packed/referenced per the large-media policy);
|
||||
when a clip is packed, its linked video-audio pool entry's `media_id` is set to
|
||||
the clip's `Video` row so the audio streams from the same blob.
|
||||
5. Image assets → `ImageAsset` media rows.
|
||||
6. **Garbage-collect**: delete every `media` row (and its chunks) whose id is **not**
|
||||
in the set of live ids accumulated in steps 1–5.
|
||||
7. Write `project.json` and the `meta` keys (`version`, `created`, `modified`).
|
||||
8. Commit; then (create path only) rename the temp file over the target.
|
||||
|
||||
### 9.3 Packed vs. referenced decision (audio)
|
||||
|
||||
For each audio pool entry, in order:
|
||||
|
||||
- If a packed row for its `media_id` already exists in the archive, keep it untouched
|
||||
(do not rewrite the bytes) and keep the entry packed.
|
||||
- Else if its external file resolves and exists: store **referenced** if the entry is
|
||||
video audio, *or* the file is `≥ LARGE_MEDIA_THRESHOLD` (2 GiB) and the large-media
|
||||
mode is not `Pack`; otherwise **pack** it (streamed from disk chunk-by-chunk).
|
||||
- Else if it has `embedded_data`: base64-decode and pack it.
|
||||
- Else: leave its references as-is (it will be reported missing on load).
|
||||
|
||||
Raster, image, and thumbnail media follow the same "write if present, else keep the
|
||||
existing row" rule so that paged-out content survives a save without being held in
|
||||
memory.
|
||||
|
||||
## 10. Load semantics
|
||||
|
||||
### 10.1 Dispatch and version checks
|
||||
|
||||
Open the file, read `project.json`, parse `BeamProject`. Reject unless
|
||||
`version == "1.0.0"` (§4.2). The container's `schema_version` is verified on open
|
||||
(`≤` the reader's maximum).
|
||||
|
||||
### 10.2 Audio resolution
|
||||
|
||||
Per pool entry with a `media_id`: look up the media row. If its `codec` is a
|
||||
**streamable** audio codec (`mp3`, `flac`, `ogg`/`oga`, `wav`/`wave`, `aiff`/`aif`,
|
||||
`aac`, `m4a`, `opus`, `alac`, `caf`), the bytes are **streamed lazily** from the blob
|
||||
at playback time (the entry keeps `media_id`, with `embedded_data`/`path` cleared).
|
||||
Otherwise the bytes are read eagerly into `embedded_data`. A precomputed `Waveform`
|
||||
blob, if present, is read into the entry.
|
||||
|
||||
### 10.3 Visual media paging
|
||||
|
||||
- **Raster** full-res pixels are **not** eagerly decoded; each keyframe is flagged
|
||||
for fault-in and its pixels are paged from its `Raster` row on demand. Its
|
||||
`RasterProxy` PNG **is** read and decoded eagerly so cold scrubs show a low-res
|
||||
frame immediately.
|
||||
- **Image assets** are **not** eagerly read; they page from their `ImageAsset` rows
|
||||
on demand.
|
||||
- **Thumbnail** packs are read eagerly per video clip.
|
||||
|
||||
### 10.4 Missing referenced files
|
||||
|
||||
A pool entry that is neither packed nor embedded, whose `relative_path` resolves to a
|
||||
non-existent file, MUST be reported as a missing file (non-fatal). The host
|
||||
application prompts the user to relocate it.
|
||||
|
||||
## 11. Legacy ZIP format (pre-SQLite)
|
||||
|
||||
Files whose magic is not `SQLite format 3\0` are read as a ZIP archive with this
|
||||
internal layout:
|
||||
|
||||
- `project.json` — the same serialized `BeamProject` (`version` must be `"1.0.0"`).
|
||||
- `media/audio/<name>.<ext>` — audio source files. The codec is taken from the
|
||||
extension. **FLAC entries are decoded to PCM `f32` and re-encoded in memory as
|
||||
IEEE-float WAV (WAV format tag 3)** before being base64-embedded; other formats are
|
||||
embedded as-is. The entry's `relative_path` is cleared after extraction.
|
||||
- `media/raster/<uuid>.png` — raster keyframe pixels, named `media/raster/<id>.png`
|
||||
after the keyframe's `id`.
|
||||
|
||||
A reader MUST NOT modify a legacy ZIP on open; it loads into memory only. **The next
|
||||
save migrates the project to SQLite** (the save sees a non-SQLite target, so it takes
|
||||
the create-and-rename path and writes a fresh `.beam` database).
|
||||
|
||||
> Known limitation of the legacy reader: raster pixels are loaded only for
|
||||
> **top-level** layers; raster keyframes nested inside groups/clips are not populated
|
||||
> from a ZIP. The SQLite path recurses correctly. Re-saving to SQLite is the remedy.
|
||||
|
||||
## 12. Large-media policy
|
||||
|
||||
- `LARGE_MEDIA_THRESHOLD = 2 GiB`. Files at or above it trigger the packed-vs-
|
||||
referenced decision below; smaller files are always packed (unless video audio,
|
||||
which is always referenced).
|
||||
- `LargeMediaMode` ∈ `{ Ask, Pack, Reference }`:
|
||||
- `Pack` — pack large files into the database.
|
||||
- `Reference` — store large files by external path.
|
||||
- `Ask` (default) — prompt the user on the first large import, then persist their
|
||||
choice; treated as `Reference` at save time until answered.
|
||||
- **The chosen mode is an application preference, not part of the `.beam` file.** It
|
||||
is stored in the editor's `config.json` (`AppConfig.large_media_default`) under the
|
||||
platform config directory, not in the project. Readers/writers of the format need
|
||||
not consult it except to drive the packed/referenced save decision.
|
||||
|
||||
## 13. Conformance summary
|
||||
|
||||
A conforming **reader** MUST:
|
||||
|
||||
1. dispatch on the 16-byte magic (§3);
|
||||
2. reject `schema_version` greater than supported and `version != "1.0.0"` (§4.2);
|
||||
3. resolve packed media via `media`/`media_chunk` (§6.3) and referenced media
|
||||
relative to the file (§6.4), reporting missing referenced files non-fatally;
|
||||
4. compute derived media ids exactly as in §7.
|
||||
|
||||
A conforming **writer** MUST:
|
||||
|
||||
1. produce the four tables of §4 with `schema_version="1"` and `version="1.0.0"`;
|
||||
2. store UUIDs as 16 big-endian bytes and chunk packed media at a uniform size with a
|
||||
remainder final chunk, setting `total_len` correctly (§6.3);
|
||||
3. perform each save in a single transaction and garbage-collect orphaned media (§9),
|
||||
and prefer in-place writes that do not rewrite unchanged packed media.
|
||||
|
||||
## 14. Security considerations
|
||||
|
||||
- **Path traversal:** referenced media and legacy ZIP entries carry filesystem paths.
|
||||
Readers SHOULD resolve relative paths against the project directory and SHOULD
|
||||
reject or sandbox paths that escape it (`..`, absolute paths) when opening
|
||||
untrusted files.
|
||||
- **Resource limits:** `project.json` and packed blobs are attacker-controllable in
|
||||
an untrusted file. Readers SHOULD bound JSON size and avoid loading entire large
|
||||
blobs into memory (stream via §6.3) to resist memory-exhaustion.
|
||||
- **Decoder safety:** audio/image bytes are handed to media decoders (Symphonia,
|
||||
image, FFmpeg); keep those dependencies current, as they parse untrusted input.
|
||||
- **Legacy ZIP bombs:** the ZIP path SHOULD enforce sane decompression-ratio/size
|
||||
limits.
|
||||
|
||||
## 15. Non-normative notes / known quirks
|
||||
|
||||
These reflect the current reference implementation and are flagged for implementers
|
||||
and future spec revisions:
|
||||
|
||||
- The project `version` check is exact-match with no compatibility window; a future
|
||||
revision should define semantic-version tolerance before bumping it.
|
||||
|
||||
(Earlier revisions of this section flagged a hardcoded save sample rate, a vestigial
|
||||
`RasterKeyframe.media_path` field, and unused `SaveSettings` fields; these have since
|
||||
been fixed/removed.)
|
||||
|
||||
## 16. Inspecting a `.beam` file
|
||||
|
||||
Because the container is plain SQLite, any `.beam` (SQLite variant) can be inspected
|
||||
with standard tooling, e.g.:
|
||||
|
||||
```sh
|
||||
sqlite3 project.beam '.tables'
|
||||
sqlite3 project.beam 'SELECT key,value FROM meta;'
|
||||
sqlite3 project.beam 'SELECT hex(id),kind,codec,storage,total_len FROM media;'
|
||||
sqlite3 project.beam 'SELECT data FROM project_json;' | jq .
|
||||
```
|
||||
|
||||
## 17. References
|
||||
|
||||
- Container: `lightningbeam-ui/lightningbeam-core/src/beam_archive.rs`
|
||||
- Save/load orchestration & `BeamProject`: `lightningbeam-ui/lightningbeam-core/src/file_io.rs`
|
||||
- Audio pool entry: `daw-backend/src/audio/pool.rs`
|
||||
- Document / scene tree: `lightningbeam-ui/lightningbeam-core/src/document.rs`
|
||||
- RFC 2119 (requirement keywords), RFC 4122 (UUID), RFC 3339 (timestamps)
|
||||
+7
-9
@@ -122,25 +122,23 @@ lightningbeam-2/
|
||||
│ │ ├── track.rs # Track management
|
||||
│ │ └── project.rs # Project state
|
||||
│ └── effects/ # Audio effects
|
||||
├── src-tauri/ # Legacy Tauri backend
|
||||
└── src/ # Legacy JavaScript frontend
|
||||
└── src/ # Legacy JavaScript frontend (browser-only)
|
||||
```
|
||||
|
||||
## Making Changes
|
||||
|
||||
### Branching Strategy
|
||||
|
||||
- `main` - Stable branch
|
||||
- `rust-ui` - Active development branch for Rust UI rewrite
|
||||
- Feature branches - Create from `rust-ui` for new features
|
||||
- `main` - Main development branch
|
||||
- Feature branches - Create from `main` for new features
|
||||
|
||||
### Before You Start
|
||||
|
||||
1. Check existing issues or create a new one to discuss your change
|
||||
2. Make sure you're on the latest `rust-ui` branch:
|
||||
2. Make sure you're on the latest `main` branch:
|
||||
```bash
|
||||
git checkout rust-ui
|
||||
git pull origin rust-ui
|
||||
git checkout main
|
||||
git pull origin main
|
||||
```
|
||||
3. Create a feature branch:
|
||||
```bash
|
||||
@@ -241,7 +239,7 @@ this solution.
|
||||
### Pull Request Process
|
||||
|
||||
1. Push your branch to GitHub or Gitea
|
||||
2. Open a pull request against `rust-ui` branch
|
||||
2. Open a pull request against `main` branch
|
||||
- GitHub: https://github.com/skykooler/lightningbeam
|
||||
- Gitea: https://git.skyler.io/skyler/lightningbeam
|
||||
3. Provide a clear description of:
|
||||
|
||||
@@ -1,3 +1,64 @@
|
||||
# 1.0.7-alpha:
|
||||
Changes:
|
||||
- HDR video support: PQ/HLG/BT.2020 video is now read correctly (decoded to scene-linear), with a per-document output mode (clip vs highlight rolloff) and 10-bit HDR export (HEVC Main10, PQ or HLG)
|
||||
- Hardware-accelerated video decode (VAAPI) for both playback and export, including a GPU NV12 preview path; the editor now runs on a shared VAAPI-capable GPU device so decode → composite → encode stay GPU-resident
|
||||
- SVG import and export for vector layers: export the current frame to .svg, and import .svg as a new vector layer (Ctrl+I)
|
||||
- Export fit modes: choose Stretch, Letterbox, or Crop when the export resolution's aspect ratio differs from the document (video and image export)
|
||||
- Videos imported directly and dragged in from the asset library now use the same placement, so they no longer end up with different aspect ratios
|
||||
- Resizing the document now leaves raster layers untouched; the Info Panel shows the active raster layer's size and a "Layer to document size" button (scale or expand/crop)
|
||||
- The active raster layer now shows a dashed outline on the canvas
|
||||
- H.264 export gained a color-range option (Limited/TV or Full/PC)
|
||||
- Hide/Show Layer now works
|
||||
|
||||
Bugfixes:
|
||||
- Fix sped-up and jerky 4K video playback (frame-index frame cache + request-based seeking)
|
||||
- Fix washed-out HDR/10-bit video (propagate stream color tags to hardware frames, P010 import)
|
||||
- Fix the final frame(s) of a clip occasionally failing to render at the end of the stream
|
||||
- Fix the CPU export color path producing shifted colors on unusual resolutions (BT.709 + honor the chosen range)
|
||||
- Fix fills occasionally vanishing after a paint-bucket or lasso cut
|
||||
- Fix silent gaps in exported audio
|
||||
- Fix black video thumbnails and decoder thrashing
|
||||
- Fix file-descriptor and GPU-memory leaks on hardware-import error paths
|
||||
- SVG export now omits hidden layers; SVG import respects gradient opacity
|
||||
- Fix the macOS/Windows build (hardware export is Linux-only)
|
||||
|
||||
# 1.0.6-alpha:
|
||||
Changes:
|
||||
- Hardware-accelerated H.264 video export: each frame is rendered and encoded on the GPU (zero-copy VAAPI), roughly 2x faster, with automatic fallback to software encoding when hardware acceleration isn't available (Linux, Intel/AMD only for now)
|
||||
- Video export now runs on a background thread, so the UI stays responsive during export and edits made while exporting no longer affect the output
|
||||
- Grouped and nested video clips now composite on the GPU path
|
||||
- Video is now packed into and streamed from the .beam project container
|
||||
|
||||
Bugfixes:
|
||||
- Fix an export hang when a video's audio track is shorter than the video
|
||||
- Fix a sample key-range overlap bug in instruments
|
||||
|
||||
# 1.0.5-alpha:
|
||||
Changes:
|
||||
- Add shape tweens (morph vector geometry between keyframes)
|
||||
- Add motion tweens for groups and movie clips
|
||||
- Group geometry and Convert to Movie Clip now work on DCEL vector shapes
|
||||
- Region/lasso select now cuts the shape and feeds the normal selection, so Group, Convert, Delete and Properties all work from a lasso (hold shift to add to the selection)
|
||||
- Clip instances now draw on top of a layer's loose shapes
|
||||
- Add onion skinning for raster and vector layers, with tinted ghosts and settings in the Info Panel
|
||||
- Images can now fill vector shapes (None / Solid / Gradient / Image fill types)
|
||||
- Imported images can be placed on the canvas
|
||||
- Add a raster keyframe timeline UI with explicit keyframe creation; click a keyframe diamond to snap the playhead to it
|
||||
- Stream audio, video and images to and from the project file instead of holding them in memory, supporting arbitrarily long media
|
||||
- Persist (and resume) waveforms and video thumbnails in the project file
|
||||
- Use low-res proxies for fast cold scrubbing of raster frames
|
||||
- Bound memory use for raster pixels, GPU textures, video frames and decoded images on large projects
|
||||
- Video export is roughly 4x faster
|
||||
- Downmix surround video audio to stereo
|
||||
|
||||
Bugfixes:
|
||||
- Fix video export resolution scaling and a post-export UI hang
|
||||
- Fix gamma handling and improve brush canvas performance
|
||||
- Fix a save crash on projects with zero or sparse audio
|
||||
- Fix raster strokes vanishing when committed
|
||||
- Fix image fill mapping (anchor to the fill's bounding box)
|
||||
- Fix video thumbnail strip bugs
|
||||
|
||||
# 1.0.4-alpha:
|
||||
Changes:
|
||||
- Beats are now the canonical time representation (replacing seconds)
|
||||
|
||||
@@ -48,7 +48,7 @@ A free and open-source 2D multimedia editor combining vector animation, audio pr
|
||||
|
||||
## Project Status
|
||||
|
||||
Lightningbeam is under active development on the `rust-ui` branch. The project has been rewritten from a Tauri/JavaScript prototype to a pure Rust application to eliminate IPC bottlenecks and achieve better performance for real-time video and audio processing.
|
||||
Lightningbeam is developed on the `main` branch. The project has been rewritten from a Tauri/JavaScript prototype to a pure Rust application to eliminate IPC bottlenecks and achieve better performance for real-time video and audio processing.
|
||||
|
||||
**Current Status:**
|
||||
- ✅ Core UI panes (Stage, Timeline, Asset Library, Info Panel, Toolbar)
|
||||
|
||||
+116
-26
@@ -22,16 +22,13 @@ is now part of this plan.
|
||||
timestamp, and the cache keys on that — so a tile picks up a new texture when a closer thumbnail
|
||||
finishes generating. Existing `retain`-by-visible-clip cleanup keeps it bounded. *(Needs in-app check.)*
|
||||
|
||||
## Deferred raster-keyframe-UI bugs (pre-existing; found during Phase 3 testing)
|
||||
Both stem from the **timeline having no model for raster keyframes** — it renders *clip
|
||||
instances* (`layer_clips`/`collect_clip_instances` return `&[ClipInstance]`), but raster layers use
|
||||
`keyframes: Vec<RasterKeyframe>`; every raster arm in timeline.rs is a stub (`Raster => &[]`/`{}`).
|
||||
- **(a) `Timeline > New Keyframe` doesn't refresh the canvas** until you draw. The menu action
|
||||
creates a blank raster keyframe but doesn't trigger a canvas repaint / GPU-cache invalidation for
|
||||
the new (different) `kf.id`, so the stale previous-frame texture stays until a stroke dirties it.
|
||||
- **(b) Raster keyframes never render on the timeline** — no code walks `RasterLayer::keyframes` to
|
||||
draw markers. Needs a raster-keyframe strip (display + click-to-navigate + insert).
|
||||
Confirmed not paging regressions (same before 3a-1). A focused "raster keyframe timeline UI" task.
|
||||
## Raster-keyframe-UI bugs — **[DONE]** (built the raster keyframe timeline UI, 2026-06-20)
|
||||
Both resolved by the raster-keyframe-timeline-UI work: timeline now draws a diamond per
|
||||
`RasterKeyframe` (mirrors vector), `K`/New Keyframe inserts a blank cel via `AddRasterKeyframeAction`
|
||||
(canvas refreshes), paint tools edit the active keyframe instead of lazily creating, diamonds are
|
||||
click-to-seek (pointing-hand cursor), playback prefetches frames, and onion skinning (raster+vector,
|
||||
tinted, Info-Panel settings) is in. (a) canvas-refresh-on-new-keyframe and (b) keyframes-on-timeline
|
||||
are both fixed.
|
||||
|
||||
## Noted enhancements (later, after the phases)
|
||||
- [x] **Surround → stereo downmix (DONE).** Done uniformly in `render_from_file` (`pool.rs`) so it
|
||||
@@ -44,10 +41,32 @@ Confirmed not paging regressions (same before 3a-1). A focused "raster keyframe
|
||||
paths (only when `dst==2 && src>2`; unknown layouts fall back to front L/R). Compiles clean.
|
||||
*(Needs in-app check: a 5.1 file now has centre/dialog present and isn't thin; not distorted/clipping.)*
|
||||
Native multichannel support remains a separate, larger project.
|
||||
- **Export speed:** a 1:14 1080p MP4 took ~9:06 to export (~7.4x slower than realtime). The video
|
||||
export pipeline re-seeks + decodes per output frame (see `[Video Seek]`/`[Video Timing]` logs) and
|
||||
does CPU YUV conversion; likely wins from sequential decode (avoid per-frame seeks), reusing the
|
||||
decode cache, and/or GPU-side color conversion. Profile before optimizing.
|
||||
- **Export speed (audited 2026-06-21):** a 1:14 1080p MP4 took ~9:06 (~7.4x realtime, ~135 ms/frame).
|
||||
Audit **refuted** the per-frame-seek theory — export decodes the source *sequentially*
|
||||
(`video.rs` `need_seek` is false once advancing forward), and readback is already async +
|
||||
triple-buffered. Real hotspots:
|
||||
- **[DONE] #1 — per-frame renderer rebuild.** The export pump built a fresh `vello::Renderer`
|
||||
(full wgpu pipeline init) + empty `ImageCache` *every egui repaint* (`main.rs` ~6218). Now built
|
||||
once per export and reused; also fixed lazy-image export (the throwaway cache had no container
|
||||
path). **Expected the dominant win.**
|
||||
- **[DONE] #2a — encode swscale rebuilt per frame.** `CpuYuvConverter::convert` now caches the
|
||||
RGBA→YUV420p `scaling::Context` + frames in `new()` instead of per call.
|
||||
- **[TODO] #2b — decode swscale + stride-repack** per frame in `video.rs:294-320` (shared with
|
||||
scrubbing; cache the YUV→RGBA scaler on the decoder). Small win, modest risk.
|
||||
- **Result of #1+#2a (measured):** ~7.4x → **~1.74x realtime** (130.7 s for 4488 frames @ 60 fps;
|
||||
34 fps). Per-stage avg: Render(CPU build) 15 ms, **Readback(GPU latency) 42 ms**, Extract 1.3 ms,
|
||||
Convert 5.7 ms.
|
||||
- **Now GPU-bound.** Per ~87 ms poll cycle the CPU does ~66 ms (3× build 45 + convert 17 + extract 4)
|
||||
but the GPU does ~87 ms (3 × ~29 ms composite) → GPU saturated at ~29 ms/frame; "Readback 42 ms" is
|
||||
queue latency, not transfer (8 MB is sub-ms).
|
||||
- **[SKIP] #3 GPU YUV / #5 pacing** — both only trim the CPU side, which is already *under* the GPU.
|
||||
Won't move a GPU-bound throughput.
|
||||
- **[TODO, big] Reduce the GPU composite (~29 ms/frame).** The per-layer HDR pipeline (Vello render →
|
||||
linear → composite, ×layers) is the wall, shared with live rendering. Options: batch composite
|
||||
passes; a fast-path skipping HDR compositing for simple single-layer/no-blend docs; cache unchanged
|
||||
layers' scenes (CPU-side, only helps if it later becomes CPU-bound). Render-architecture project.
|
||||
- Non-issues: per-frame seek, blocking readback, audio. (`video.rs:237` container-reopen-on-seek is
|
||||
a latent cost but doesn't fire on forward export.)
|
||||
- **AAC export NaN guard (done):** `convert_chunk_to_planar_f32` now sanitizes non-finite samples
|
||||
(NaN/Inf → 0, finite clamped to [-1,1]) like the integer paths, with a one-time warning — a stray
|
||||
non-finite render sample no longer fails the whole export. Upstream NaN source (effect/automation/
|
||||
@@ -395,6 +414,56 @@ dirty never evicted. 4. 3c GPU bound. 5. 3d undo diffs reproduce pre-stroke buff
|
||||
|
||||
---
|
||||
|
||||
## Phase 3.5 — Image textures in vector scenes **[DONE 2026-06-21]** *(prereq for Phase 4; fixed DCEL-broken image import)*
|
||||
|
||||
**Done:** 3.5a — import/drop places an image as a borderless image-filled rectangle
|
||||
(`AddShapeAction::image_rect`), centered (direct import) or at the drop point (library drag);
|
||||
renderer now maps the image brush onto the fill's bounding box (was anchored at world origin →
|
||||
only a corner showed); `SetImageFillAction` + an **Image** fill-type tab (None|Solid|Gradient|Image)
|
||||
with an asset picker in the Info Panel. 3.5b — image bytes persist as `MediaKind::ImageAsset` rows in
|
||||
the `.beam` (kept-in-place; `ImageAsset.data` is `skip_serializing` + container-backed; old base64
|
||||
projects migrate on re-save); eager-read on load. *(ImageCache still unbounded — Phase 4 adds the
|
||||
usage-based LRU/lazy paging.)*
|
||||
|
||||
### (original plan below)
|
||||
## Phase 3.5 — Image textures in vector scenes *(prereq for testing Phase 4; fixes DCEL-broken image import)*
|
||||
|
||||
**Why:** Phase 4 pages *image assets*, but there's currently no way to get an image asset into a
|
||||
vector scene — so nothing to page. This also repairs image import, half-broken since the DCEL switch.
|
||||
|
||||
**Current state (audited 2026-06-21):**
|
||||
- *Works:* `import_image` (`main.rs`) decodes dims + creates an `ImageAsset` (raw bytes embedded in
|
||||
`Document::image_assets`, serialized as **base64 in project JSON**). The renderer's image-fill paths
|
||||
are **complete** — GPU/Vello (`renderer.rs:~1160`, `ImageBrush` via `ImageCache.get_or_decode`) and
|
||||
CPU/tiny-skia (`renderer.rs:~1486`). `Fill::image_fill` (`vector_graph/mod.rs:110`) and
|
||||
`Face::image_fill` (`dcel2/mod.rs:117`) fields exist and render when set.
|
||||
- *Broken/missing (the workflow):*
|
||||
1. **Drop image → canvas is stubbed:** `stage.rs:~11782` and `main.rs:~4924` both just print
|
||||
"Image drag to stage not yet supported with DCEL backend". Nothing is added to the scene.
|
||||
2. **No way to assign an image fill:** no `SetImageFillAction` (only `SetFillPaintAction` for
|
||||
color/gradient); no Info-Panel picker. `Fill`/`Face.image_fill` are never populated.
|
||||
3. **DCEL faces never get `image_fill`** (`dcel2/import.rs:275` always `None`; topology copies from
|
||||
parent which is also `None`).
|
||||
4. **Not in the container:** `MediaKind::ImageAsset` exists but is **dead** — image bytes live only
|
||||
as base64 in project JSON. Not chunked, not pageable (so Phase 4 can't page them).
|
||||
|
||||
**Tasks:**
|
||||
- **3.5a — Place + assign.** Replace the two drop stubs: dropping an image onto a vector layer creates
|
||||
a rectangle face sized to the image at the drop point with `image_fill = asset_id`. Add
|
||||
`SetImageFillAction` (set/clear an image fill on the selected face/shape; mirrors `SetFillPaintAction`)
|
||||
+ an Info-Panel image-asset picker for the selected shape's fill. Populate `Face.image_fill` in DCEL
|
||||
(and keep it through topology ops — already copied from parent).
|
||||
- **3.5b — Persist in the container.** Write image assets as `MediaKind::ImageAsset` rows in the `.beam`
|
||||
SQLite (like raster/audio: write on save kept-in-place on re-save; read on load), keyed by asset id;
|
||||
drop the base64-in-JSON embedding (or keep a tiny ref). This is the storage Phase 4 pages from.
|
||||
- **3.5c — Lazy decode hook.** Image bytes load from the container into `ImageCache` on first render
|
||||
(decode → `ImageBrush`/`Pixmap`). Leave `ImageCache` **unbounded for now**; Phase 4 adds the
|
||||
usage-based LRU/eviction (this phase just makes there *be* real, container-backed image assets to page).
|
||||
- **Tests:** import→drop→render round-trip; save/reload preserves the image fill + reads bytes from the
|
||||
container (not JSON); CPU and GPU render paths both show the image.
|
||||
|
||||
---
|
||||
|
||||
## Phase 4 — Asset paging by usage + LRU *(vector's real cost is assets, not geometry)*
|
||||
|
||||
Vector geometry is compact flat POD (tens of KB/frame, no cached tessellation/DCEL) — leave
|
||||
@@ -414,6 +483,22 @@ it resident. The heavy, evictable thing is the **image assets** referenced by fi
|
||||
from blob row or external `path`); Tier 2 = decoded pixels (`ImageCache` + GPU textures —
|
||||
the heavy one).
|
||||
|
||||
**Progress (2026-06-21):**
|
||||
- **[DONE] Tier 2 — bound the decoded `ImageCache`.** 256 MB **usage-LRU**: every
|
||||
`get_or_decode`/`_cpu` bumps the asset's recency; inserts past budget evict the least-recently-used
|
||||
(a miss re-decodes from `asset.data`). Achieves usage-based eviction via render-access recency
|
||||
(simpler than the frame→asset enumeration below; that enumeration is only needed for *prefetch*).
|
||||
- **[DONE] Tier 1 — lazy compressed bytes.** `ImageCache` holds the container path (threaded
|
||||
App.current_file_path → SharedPaneState → VelloRenderContext) and pages bytes on a decode miss via
|
||||
`read_packed_media_readonly`; `load_beam_sqlite` no longer eager-reads → instant load, compressed
|
||||
bytes don't accumulate. `asset.data` is still used when resident (fresh import / old base64 project).
|
||||
*(Refinement: persistent read connection vs open-per-miss.)*
|
||||
- **[DONE] Prefetch.** `assets_needed_at(document, time)` enumerates image ids in the visible vector
|
||||
layers' active keyframes; during playback the stage decodes the ~0.5s-ahead set into the cache.
|
||||
*(Refinements: nested clip-instance recursion; background-thread decode.)*
|
||||
|
||||
**Phase 4 = DONE** (image asset paging by usage + LRU).
|
||||
|
||||
### 4a. Frame→asset enumeration (incl. nested clips — see note below)
|
||||
A function `assets_needed_at(time) -> HashSet<Uuid>`: walk each visible vector layer's active
|
||||
`ShapeKeyframe`, collect `fill.image_fill` across its `VectorGraph.fills`, **recursing into
|
||||
@@ -601,11 +686,17 @@ Phase 1a and Phase 2 can ship now; everything else waits on Phase 0 (the contain
|
||||
`load_file_into_pool`'s full decode with the `do_import_audio` branching (PCM → mmap, compressed
|
||||
→ `from_compressed` placeholder). Higher risk (touches the working referenced path); packed
|
||||
covers the common <2GB case first.
|
||||
- [ ] **Deferred (follow-up): packed video streaming.** Let small videos be packed into the `.beam`
|
||||
(a `MediaKind::Video` blob, `VideoClip` referencing it by id) and stream **both frames and audio**
|
||||
from the DB blob via FFmpeg. ffmpeg-next has no custom-I/O wrapper, so this needs an
|
||||
`AVIOContext`-over-`BlobReader` shim via raw FFI. **Decision (user):** that FFI wrapper lives in
|
||||
its **own crate, version-pinned to the ffmpeg version**, isolating the unsafe + the ABI coupling.
|
||||
- [x] **DONE: packed video streaming.** Small videos pack into the `.beam`
|
||||
(a `MediaKind::Video` blob at the clip id, `VideoClip.media_id` referencing it) and stream **both
|
||||
frames and audio** from the DB blob via FFmpeg. The `AVIOContext`-over-`Read+Seek` shim lives in
|
||||
the new `ffmpeg-blob-io` crate (`BlobInput`, version-pinned `=8.0.0`/`=8.0.1`), isolating the
|
||||
unsafe + ABI coupling. Frames: `video.rs` `VideoSource{Path,Packed}` opens a fresh `BlobReader`
|
||||
per decoder/seek/scan. Audio: `VideoAudioReader::open_source` over the same blob (the
|
||||
`disk_reader.rs` `StreamSource` blocker is removed); save points the linked video-audio pool
|
||||
entry's `media_id` at the video row so it streams from the same blob. Tests: ffmpeg-blob-io AVIO
|
||||
unit tests (WAV via Cursor + seek + open/drop loop), core `packed_video_stream` (blob→AVIO→Input),
|
||||
`beam_archive` packed-video round-trip, daw-backend `open_source` (compiles; can't link in the
|
||||
container — user runtime-verifies actual A/V playback).
|
||||
- [~] Phase 1c — video embedded-audio track ← **stopgap shipped; proper design next**
|
||||
- [x] Stopgap: `extract_audio_from_video_to_wav` streams to a temp WAV → `import_audio_sync`
|
||||
(mmap). Fixed the ~2.8GB-`Vec<f32>` OOM. But writes the whole WAV to `/tmp` (fills
|
||||
@@ -753,13 +844,12 @@ viewports of fine tiles; persist pyramid in `.beam`.
|
||||
packet per stream (O(1) memory vs O(duration)). Same tie-break (`v_us <= a_us`) and drain-on-EOF
|
||||
behavior; output is byte-identical. Editor compiles clean. *(Not yet runtime-verified — needs an
|
||||
in-app export to confirm A/V sync.)*
|
||||
- [ ] Phase 3a — lazy raster fault-in from blob store
|
||||
- [ ] Phase 3b — raster residency window + eviction
|
||||
- [ ] Phase 3c — bound raster GPU/CPU caches
|
||||
- [ ] Phase 3d — spill undo snapshots
|
||||
- [ ] Phase 4a — frame→asset enumeration (recursive)
|
||||
- [ ] Phase 4b — usage bookkeeping + LRU residency
|
||||
- [ ] Phase 4c — bound decoded image tier
|
||||
- [x] Phase 3a — lazy + async raster fault-in (`RasterStore` + background thread + image proxy)
|
||||
- [x] Phase 3b — raster residency LRU + eviction (dirty-flag data-loss safety)
|
||||
- [x] Phase 3c — bound raster GPU texture cache (recency LRU + F3 VRAM readout)
|
||||
- [x] Phase 3d — raster undo dirty-rect diffs (+ fault-in-before-undo)
|
||||
- [x] Phase 3.5 — image textures in vector scenes (fixed DCEL-broken image import; image-fill tab + picker; container-persisted)
|
||||
- [x] Phase 4 — image asset paging: Tier 2 decoded-cache byte-LRU, Tier 1 lazy container bytes, playback prefetch
|
||||
- [x] Phase 5 — fixed the broken `#[cfg(test)]` unit tests; **`cargo test --lib` green again**
|
||||
(daw-backend 17 passed, lightningbeam-core 264 passed). Wrapped stale raw-`f64` time literals
|
||||
in `Beats(...)` / passed `&TempoMap` to changed signatures (automation.rs, clip.rs,
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
# Lightningbeam TODO
|
||||
|
||||
> ⚠️ **Stale entries:** Lightningbeam was rewritten from JavaScript to Rust. Any entry below
|
||||
> that cites `src/*.js` / `main.js` / `animation.js` predates that migration — the *issue* may
|
||||
> or may not still exist in the Rust codebase, but the file/line references are obsolete.
|
||||
> **Re-verify against the current Rust code before acting** (this covers the "Animation System
|
||||
> Refactoring" section and the JS-referencing "Known Issues" entries — node editor, default
|
||||
> interpolation, etc.). Items with no `.js` references are current.
|
||||
|
||||
## Animation System Refactoring *(STALE — JS-era migration notes; superseded by the Rust DCEL/keyframe system)*
|
||||
|
||||
### Completed
|
||||
- ✅ Implement AnimationData curve-based system (Keyframe, AnimationCurve, AnimationData classes)
|
||||
- ✅ Add GraphicsObject.currentTime property
|
||||
- ✅ Migrate shape rendering to use AnimationData curves (exists, zOrder)
|
||||
- ✅ Binary search optimization for keyframe lookups
|
||||
|
||||
### In Progress
|
||||
- Migrating from Frame-based to AnimationData curve-based system throughout codebase
|
||||
|
||||
### Pending Features
|
||||
|
||||
#### Animation Curve Enhancements
|
||||
- [ ] Implement extrapolation modes (separate for start vs end):
|
||||
- "hold" (default) - hold value at first/last keyframe
|
||||
- "extend" - linearly extend the curve beyond keyframes
|
||||
- "repeat" - repeat the animation
|
||||
- "decay" - exponential decay to a target value
|
||||
- [ ] Add position, scale, rotation animation curves for shapes
|
||||
- [ ] Add shape morphing/tweening between keyframes
|
||||
|
||||
#### Keyframing Behavior
|
||||
- [ ] Add user preference for keyframing behavior when editing objects:
|
||||
- Auto-keyframe (current default): create/update keyframe at current time
|
||||
- Edit previous (Flash-style): update most recent keyframe before current time
|
||||
- Ephemeral (Blender-style): changes don't persist without manual keyframe
|
||||
- Optional: Add modifier key (e.g. Shift) to toggle between modes
|
||||
|
||||
#### Shape Ordering
|
||||
- [ ] Add "Bring Forward" menu option (swap zOrder with shape in front)
|
||||
- [ ] Add "Send Backward" menu option (swap zOrder with shape behind)
|
||||
- [ ] Add "Bring to Front" menu option (set zOrder to max + 1)
|
||||
- [ ] Add "Send to Back" menu option (set zOrder to min - 1)
|
||||
|
||||
#### Code Cleanup
|
||||
- [ ] Remove all remaining references to Frame-based system
|
||||
- [ ] Remove legacy Frame class once migration is complete
|
||||
- [ ] Clean up GraphicsObject.shapes[] array (shapes should only live in Layers)
|
||||
|
||||
## Known Issues / Platform Limitations
|
||||
|
||||
### Animation: Tweens are broken (Rust codebase) — LOW PRIORITY
|
||||
- **Issue**: Animation tweening between keyframes (shape/vector interpolation, and the
|
||||
`tween_after` behavior on keyframes) does not work correctly in the current Rust app.
|
||||
Needs investigation + fix. Not urgent — revisit later.
|
||||
- (Older JS-codebase animation entries below reference `src/*.js` and are stale.)
|
||||
|
||||
### Audio: Oscillator Timbre Drift (Phase Accumulation Error)
|
||||
- **Issue**: Oscillators exhibit timbre changes over time due to floating-point phase accumulation errors
|
||||
- **Affected Files**:
|
||||
- `daw-backend/src/effects/synth.rs:117-120` (SimpleSynth)
|
||||
- `daw-backend/src/audio/node_graph/nodes/oscillator.rs:167-170` (OscillatorNode)
|
||||
- **Root Cause**: Current phase wrapping uses conditional subtraction (`if phase >= 1.0 { phase -= 1.0 }`), which accumulates f32 rounding errors over time, especially for long-playing notes
|
||||
- **Current Code**:
|
||||
```rust
|
||||
self.phase += frequency / sample_rate;
|
||||
if self.phase >= 1.0 {
|
||||
self.phase -= 1.0;
|
||||
}
|
||||
```
|
||||
- **Recommended Fix**: Replace with `.fract()` for numerically stable wraparound:
|
||||
```rust
|
||||
self.phase += frequency / sample_rate;
|
||||
self.phase = self.phase.fract();
|
||||
```
|
||||
- **Impact**: Medium - affects audio quality for sustained notes, becomes noticeable after several seconds
|
||||
- **Priority**: Medium - should be addressed before production use
|
||||
|
||||
### UI: Node Connections Render Behind VoiceAllocator Child Nodes
|
||||
- **Issue**: Connection lines (SVG paths) inside expanded VoiceAllocator nodes render behind child nodes due to z-index stacking
|
||||
- **Affected File**: `src/styles.css:1128`
|
||||
- **Root Cause**: Child nodes have `z-index: 10` while connection SVG paths have default/lower z-index
|
||||
- **Current Code**:
|
||||
```css
|
||||
.drawflow .drawflow-node.child-node {
|
||||
opacity: 0.9;
|
||||
border: 1px solid #5a5aaa !important;
|
||||
box-shadow: 0 2px 8px rgba(90, 90, 170, 0.3);
|
||||
z-index: 10;
|
||||
}
|
||||
```
|
||||
- **Recommended Fix**: Either:
|
||||
1. Remove `z-index: 10` from `.child-node` (simplest), or
|
||||
2. Add higher z-index to connection SVG paths, or
|
||||
3. Use CSS `isolation: isolate` on the VoiceAllocator contents area to create a new stacking context
|
||||
- **Impact**: Low - visual issue only, connections still function but appear to go "behind" nodes
|
||||
- **Priority**: Low - cosmetic issue that doesn't affect functionality
|
||||
|
||||
### UI: VoiceAllocator Child Nodes Don't Move with Parent
|
||||
- **Issue**: When a VoiceAllocator node is moved, its child nodes remain in their original positions instead of moving with the parent
|
||||
- **Affected File**: `src/main.js:6202-6207`
|
||||
- **Root Cause**: The `nodeMoved` event handler only handles the case where a child node is moved (resizes parent), but doesn't handle when the VoiceAllocator itself is moved
|
||||
- **Current Code**:
|
||||
```javascript
|
||||
editor.on("nodeMoved", (nodeId) => {
|
||||
const node = editor.getNodeFromId(nodeId);
|
||||
if (node && node.data.parentNodeId) {
|
||||
resizeVoiceAllocatorToFit(node.data.parentNodeId);
|
||||
}
|
||||
});
|
||||
```
|
||||
- **Recommended Fix**: Add logic to detect when a VoiceAllocator is moved and update all child node positions:
|
||||
```javascript
|
||||
editor.on("nodeMoved", (nodeId) => {
|
||||
const node = editor.getNodeFromId(nodeId);
|
||||
|
||||
// Case 1: A child node was moved - resize parent
|
||||
if (node && node.data.parentNodeId) {
|
||||
resizeVoiceAllocatorToFit(node.data.parentNodeId);
|
||||
}
|
||||
|
||||
// Case 2: A VoiceAllocator was moved - move all children
|
||||
if (node && node.data.nodeType === 'VoiceAllocator') {
|
||||
// Calculate delta from previous position (need to track)
|
||||
// Update all child node positions by the delta
|
||||
// Call editor.updateConnectionNodes() for parent and all children
|
||||
}
|
||||
});
|
||||
```
|
||||
- **Impact**: High - child nodes become disconnected from parent visually
|
||||
- **Priority**: High - breaks expected behavior of grouped nodes
|
||||
|
||||
### UI: VoiceAllocator Expansion Doesn't Update Connection Positions
|
||||
- **Issue**: When expanding/collapsing a VoiceAllocator, connection endpoints don't update to match the new port positions
|
||||
- **Affected File**: `src/main.js:6496-6555` (handleNodeDoubleClick function)
|
||||
- **Root Cause**: The expand/collapse logic shows/hides child nodes and resizes the container, but never calls `editor.updateConnectionNodes()` to refresh connection positions
|
||||
- **Current Code**: In `handleNodeDoubleClick()`, after expanding or collapsing:
|
||||
```javascript
|
||||
// Expand
|
||||
expandedNodes.add(nodeId);
|
||||
nodeElement.classList.add('expanded');
|
||||
nodeElement.style.width = '600px';
|
||||
nodeElement.style.height = '400px';
|
||||
// ... shows child nodes ...
|
||||
// Missing: editor.updateConnectionNodes(`node-${nodeId}`)
|
||||
```
|
||||
- **Recommended Fix**: Call `editor.updateConnectionNodes()` after resizing:
|
||||
```javascript
|
||||
// After expanding
|
||||
expandedNodes.add(nodeId);
|
||||
nodeElement.classList.add('expanded');
|
||||
// ... resize and show children ...
|
||||
|
||||
// Update connection positions for VoiceAllocator and all children
|
||||
editor.updateConnectionNodes(`node-${nodeId}`);
|
||||
for (const [childId, parentId] of nodeParents.entries()) {
|
||||
if (parentId === nodeId) {
|
||||
editor.updateConnectionNodes(`node-${childId}`);
|
||||
}
|
||||
}
|
||||
```
|
||||
- **Impact**: Medium - connections appear in wrong positions until manually moved
|
||||
- **Priority**: Medium - visual issue that affects usability
|
||||
|
||||
### UI: Node Editor Allows Editing Without MIDI Layer Selected
|
||||
- **Issue**: The node editor pane allows adding/editing instrument nodes even when no MIDI layer is selected, and always uses hardcoded `trackId: 0`
|
||||
- **Affected File**: `src/main.js:6045-6920` (nodeEditor function)
|
||||
- **Root Cause**: The node editor never checks if `context.activeObject.activeLayer` exists or is a MIDI track, and all backend commands use hardcoded `trackId: 0`
|
||||
- **Current Code**: All graph commands hardcode track 0:
|
||||
```javascript
|
||||
const commandArgs = parentNodeId
|
||||
? {
|
||||
trackId: 0, // HARDCODED!
|
||||
voiceAllocatorId: editor.getNodeFromId(parentNodeId).data.backendId,
|
||||
nodeType: nodeType,
|
||||
x: x,
|
||||
y: y
|
||||
}
|
||||
: {
|
||||
trackId: 0, // HARDCODED!
|
||||
nodeType: nodeType,
|
||||
x: x,
|
||||
y: y
|
||||
};
|
||||
```
|
||||
- **Recommended Fix**:
|
||||
1. Check if activeLayer is a MIDI track before allowing edits:
|
||||
```javascript
|
||||
function getSelectedMidiTrack() {
|
||||
const activeLayer = context.activeObject?.activeLayer;
|
||||
if (!activeLayer || activeLayer.type !== 'midi') {
|
||||
return null;
|
||||
}
|
||||
return activeLayer;
|
||||
}
|
||||
```
|
||||
2. Show placeholder when no MIDI track selected:
|
||||
```javascript
|
||||
function nodeEditor() {
|
||||
const container = document.createElement("div");
|
||||
const midiTrack = getSelectedMidiTrack();
|
||||
|
||||
if (!midiTrack) {
|
||||
container.innerHTML = '<div class="placeholder">Select a MIDI layer to edit instruments</div>';
|
||||
return container;
|
||||
}
|
||||
// ... rest of node editor code ...
|
||||
}
|
||||
```
|
||||
3. Use actual track ID instead of hardcoded 0:
|
||||
```javascript
|
||||
const trackId = midiTrack.audioTrackId || 0;
|
||||
const commandArgs = { trackId, nodeType, x, y };
|
||||
```
|
||||
4. Add listener to refresh node editor when layer selection changes
|
||||
- **Impact**: High - allows editing wrong track's instrument graph, data corruption risk
|
||||
- **Priority**: High - can cause confusion and data loss
|
||||
|
||||
### Animation: Wrong Default Interpolation for Shape and Object Keyframes
|
||||
- **Issue**: Shape index and object transform keyframes default to "linear" interpolation but should default to "hold" (step function), and there's no UI to change interpolation after creation
|
||||
- **Affected Files**:
|
||||
- `src/models/animation.js:124` (Keyframe constructor defaults to "linear")
|
||||
- `src/main.js:2161` (shapeIndex keyframes default to "linear")
|
||||
- `src/main.js:2198` (object position/rotation/scale keyframes default to "linear")
|
||||
- `src/main.js:5910` (Timeline menu - missing tween options)
|
||||
- **Root Cause**:
|
||||
1. The Keyframe constructor defaults interpolation to "linear"
|
||||
2. Shape index keyframes preserve existing interpolation or default to "linear"
|
||||
3. Object transform keyframes explicitly use "linear"
|
||||
4. No menu options exist to change interpolation mode after keyframe creation
|
||||
- **Current Code**:
|
||||
- Keyframe constructor (animation.js:124):
|
||||
```javascript
|
||||
constructor(time, value, interpolation = "linear", uuid = undefined) {
|
||||
```
|
||||
- Shape index keyframes (main.js:2161):
|
||||
```javascript
|
||||
const interpolationType = existingShapeIndexKf ? existingShapeIndexKf.interpolation : 'linear';
|
||||
const shapeIndexKeyframe = new Keyframe(currentTime, newShapeIndex, interpolationType);
|
||||
```
|
||||
- Object keyframes (main.js:2198):
|
||||
```javascript
|
||||
const newKeyframe = new Keyframe(
|
||||
currentTime,
|
||||
currentValue,
|
||||
'linear' // Default to linear interpolation
|
||||
);
|
||||
```
|
||||
- **Expected Behavior**:
|
||||
- Shape index keyframes should default to "hold" (shapes shouldn't morph between versions)
|
||||
- Object transforms should default to "hold" (objects shouldn't move/rotate/scale between keyframes unless explicitly tweened)
|
||||
- Timeline menu should have options to convert between interpolation modes
|
||||
- **Recommended Fix**:
|
||||
1. Change shapeIndex default to "hold" (main.js:2161):
|
||||
```javascript
|
||||
const interpolationType = existingShapeIndexKf ? existingShapeIndexKf.interpolation : 'hold';
|
||||
```
|
||||
2. Change object keyframe default to "hold" (main.js:2198):
|
||||
```javascript
|
||||
const newKeyframe = new Keyframe(currentTime, currentValue, 'hold');
|
||||
```
|
||||
3. Add Timeline menu options (main.js:5910, in timelineSubmenu):
|
||||
```javascript
|
||||
{
|
||||
text: "Add Shape Tween",
|
||||
enabled: /* check if shape is selected and has keyframes */,
|
||||
action: () => {
|
||||
// Find shapeIndex curve for selected shape
|
||||
// Change interpolation between keyframes to "linear"
|
||||
}
|
||||
},
|
||||
{
|
||||
text: "Add Motion Tween",
|
||||
enabled: /* check if object is selected and has transform keyframes */,
|
||||
action: () => {
|
||||
// Find position/rotation/scale curves for selected object
|
||||
// Change interpolation between keyframes to "linear" or "bezier"
|
||||
}
|
||||
}
|
||||
```
|
||||
- **Note**: exists and zOrder keyframes already correctly use "hold" (main.js:2139, 2150)
|
||||
- **Impact**: High - causes unwanted interpolation, shapes morph unexpectedly, objects move when they shouldn't
|
||||
- **Priority**: High - fundamental animation behavior is incorrect
|
||||
|
||||
### Tauri Pinch-Zoom on Linux
|
||||
- **Issue**: Two-finger pinch gestures zoom the entire Tauri window instead of individual canvases
|
||||
- **Status**: Known Tauri limitation on Linux/GTK with no cross-platform solution
|
||||
- **Tracking**: https://github.com/tauri-apps/tauri/discussions/3843
|
||||
- **Workaround attempts**: Tried `zoomHotkeysEnabled: false`, `touch-action: none`, viewport meta tags - none worked
|
||||
- **Resolution**: Monitor Tauri releases for official fix
|
||||
|
||||
## Notes
|
||||
|
||||
### Architecture
|
||||
- **GraphicsObject** contains Layers and has `currentTime` (continuous time)
|
||||
- **Layer** contains `shapes[]` array and `animationData` (AnimationData instance)
|
||||
- **AnimationData** contains curves dictionary, each curve identified by parameter name
|
||||
- Shape curves: `shape.{uuid}.exists`, `shape.{uuid}.zOrder`
|
||||
- Future: `shape.{uuid}.x`, `shape.{uuid}.y`, `shape.{uuid}.rotation`, etc.
|
||||
- **Shapes render based on curves**: Layer.draw checks exists > 0, sorts by zOrder, draws in order
|
||||
|
||||
### Interpolation Types
|
||||
- `linear` - Linear interpolation between keyframes
|
||||
- `bezier` - Cubic Bezier with easing control points
|
||||
- `step`/`hold` - Step function (jumps to next value)
|
||||
Executable
+701
@@ -0,0 +1,701 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Lightningbeam .beam File Inspector
|
||||
|
||||
A command-line tool to inspect .beam project files.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import sqlite3
|
||||
import sys
|
||||
import uuid as uuidlib
|
||||
import zipfile
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
|
||||
# First 16 bytes of any SQLite 3 database.
|
||||
SQLITE_MAGIC = b"SQLite format 3\x00"
|
||||
|
||||
# media.kind values (see BEAM_FILE_FORMAT.md §6.1).
|
||||
MEDIA_KIND_NAMES = {
|
||||
0: "Audio", 1: "Video", 2: "Raster", 3: "ImageAsset",
|
||||
4: "Waveform", 5: "Thumbnail", 6: "RasterProxy",
|
||||
}
|
||||
# media.storage values (§6.2).
|
||||
MEDIA_STORAGE_NAMES = {0: "Packed", 1: "Referenced"}
|
||||
|
||||
|
||||
def _is_sqlite(path: Path) -> bool:
|
||||
"""True if the file begins with the SQLite 3 header magic."""
|
||||
try:
|
||||
with open(path, "rb") as f:
|
||||
return f.read(16) == SQLITE_MAGIC
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def _human_size(n: int) -> str:
|
||||
f = float(n)
|
||||
for unit in ("B", "KiB", "MiB", "GiB", "TiB"):
|
||||
if f < 1024 or unit == "TiB":
|
||||
return f"{f:.0f} {unit}" if unit == "B" else f"{f:.1f} {unit}"
|
||||
f /= 1024
|
||||
return f"{n} B"
|
||||
|
||||
|
||||
class BeamInspector:
|
||||
"""Inspector for .beam project files (SQLite container, or legacy ZIP)."""
|
||||
|
||||
def __init__(self, beam_file: Path):
|
||||
self.beam_file = beam_file
|
||||
self.project_data: Optional[Dict[str, Any]] = None
|
||||
# SQLite (current) vs ZIP (legacy) container.
|
||||
self.is_sqlite = _is_sqlite(beam_file)
|
||||
# Populated for SQLite files by load():
|
||||
self.meta: Dict[str, str] = {}
|
||||
self.media: List[Dict[str, Any]] = [] # rows from the media table
|
||||
self.media_by_id: Dict[str, Dict[str, Any]] = {} # uuid-string -> row
|
||||
|
||||
def _connect(self) -> sqlite3.Connection:
|
||||
"""Open the SQLite container read-only."""
|
||||
uri = self.beam_file.resolve().as_uri() + "?mode=ro"
|
||||
return sqlite3.connect(uri, uri=True)
|
||||
|
||||
def load(self) -> bool:
|
||||
"""Load and parse the .beam file (container-agnostic)."""
|
||||
try:
|
||||
if self.is_sqlite:
|
||||
return self._load_sqlite()
|
||||
return self._load_zip()
|
||||
except Exception as e:
|
||||
print(f"Error loading .beam file: {e}", file=sys.stderr)
|
||||
return False
|
||||
|
||||
def _load_zip(self) -> bool:
|
||||
with zipfile.ZipFile(self.beam_file, 'r') as zip_ref:
|
||||
with zip_ref.open('project.json') as f:
|
||||
self.project_data = json.load(f)
|
||||
return True
|
||||
|
||||
def _load_sqlite(self) -> bool:
|
||||
con = self._connect()
|
||||
try:
|
||||
cur = con.cursor()
|
||||
row = cur.execute("SELECT data FROM project_json WHERE id = 0").fetchone()
|
||||
if not row:
|
||||
raise ValueError("archive has no project.json row")
|
||||
self.project_data = json.loads(row[0])
|
||||
|
||||
self.meta = {k: v for (k, v) in cur.execute("SELECT key, value FROM meta")}
|
||||
|
||||
for (idb, kind, codec, storage, ext_path, total_len,
|
||||
channels, sample_rate, width, height) in cur.execute(
|
||||
"SELECT id, kind, codec, storage, ext_path, total_len, "
|
||||
"channels, sample_rate, width, height FROM media"
|
||||
):
|
||||
uid = str(uuidlib.UUID(bytes=bytes(idb)))
|
||||
info = {
|
||||
"uuid": uid,
|
||||
"kind": kind,
|
||||
"codec": codec,
|
||||
"storage": storage,
|
||||
"ext_path": ext_path,
|
||||
"total_len": total_len or 0,
|
||||
"channels": channels,
|
||||
"sample_rate": sample_rate,
|
||||
"width": width,
|
||||
"height": height,
|
||||
}
|
||||
self.media.append(info)
|
||||
self.media_by_id[uid] = info
|
||||
finally:
|
||||
con.close()
|
||||
return True
|
||||
|
||||
def show_info(self):
|
||||
"""Display basic project information."""
|
||||
if not self.project_data:
|
||||
return
|
||||
|
||||
print("=" * 60)
|
||||
print("PROJECT INFORMATION")
|
||||
print("=" * 60)
|
||||
|
||||
print(f"Container: {'SQLite' if self.is_sqlite else 'Legacy ZIP'}")
|
||||
if self.is_sqlite:
|
||||
print(f"Schema Ver: {self.meta.get('schema_version', 'Unknown')}")
|
||||
print(f"Version: {self.project_data.get('version', 'Unknown')}")
|
||||
print(f"Created: {self.project_data.get('created', 'Unknown')}")
|
||||
print(f"Modified: {self.project_data.get('modified', 'Unknown')}")
|
||||
|
||||
ui_state = self.project_data.get('ui_state', {})
|
||||
print(f"\nProject Name: {ui_state.get('name', 'Unnamed')}")
|
||||
print(f"ID: {ui_state.get('id', 'Unknown')}")
|
||||
print(f"Dimensions: {ui_state.get('width', 0):.0f} x {ui_state.get('height', 0):.0f}")
|
||||
print(f"Framerate: {ui_state.get('framerate', 0):.1f} fps")
|
||||
print(f"Duration: {ui_state.get('duration', 0):.2f} seconds")
|
||||
|
||||
bg = ui_state.get('background_color', {})
|
||||
print(f"Background: rgba({bg.get('r', 0)}, {bg.get('g', 0)}, {bg.get('b', 0)}, {bg.get('a', 255)})")
|
||||
|
||||
audio_backend = self.project_data.get('audio_backend', {})
|
||||
print(f"\nSample Rate: {audio_backend.get('sample_rate', 0)} Hz")
|
||||
|
||||
def show_clips(self):
|
||||
"""Display clips information."""
|
||||
if not self.project_data:
|
||||
return
|
||||
|
||||
ui_state = self.project_data.get('ui_state', {})
|
||||
|
||||
vector_clips = ui_state.get('vector_clips', {})
|
||||
video_clips = ui_state.get('video_clips', {})
|
||||
audio_clips = ui_state.get('audio_clips', {})
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("CLIPS")
|
||||
print("=" * 60)
|
||||
|
||||
print(f"Vector Clips: {len(vector_clips)}")
|
||||
print(f"Video Clips: {len(video_clips)}")
|
||||
print(f"Audio Clips: {len(audio_clips)}")
|
||||
|
||||
if vector_clips:
|
||||
print("\nVector Clips:")
|
||||
for clip_id, clip in vector_clips.items():
|
||||
print(f" - {clip.get('name', 'Unnamed')} (ID: {clip_id[:8]}...)")
|
||||
|
||||
if video_clips:
|
||||
print("\nVideo Clips:")
|
||||
for clip_id, clip in video_clips.items():
|
||||
print(f" - {clip.get('name', 'Unnamed')} (ID: {clip_id[:8]}...)")
|
||||
|
||||
if audio_clips:
|
||||
print("\nAudio Clips:")
|
||||
for clip_id, clip in audio_clips.items():
|
||||
print(f" - {clip.get('name', 'Unnamed')} (ID: {clip_id[:8]}...)")
|
||||
|
||||
def show_layers(self):
|
||||
"""Display layer hierarchy."""
|
||||
if not self.project_data:
|
||||
return
|
||||
|
||||
ui_state = self.project_data.get('ui_state', {})
|
||||
root = ui_state.get('root', {})
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("LAYER HIERARCHY")
|
||||
print("=" * 60)
|
||||
|
||||
def print_layer(layer: Dict[str, Any], indent: int = 0):
|
||||
# Handle case where layer might not be a dictionary
|
||||
if not isinstance(layer, dict):
|
||||
prefix = " " * indent
|
||||
print(f"{prefix}- ERROR: Layer is {type(layer).__name__}, not a dict: {repr(layer)[:50]}")
|
||||
return
|
||||
|
||||
layer_type = layer.get('type', 'Unknown')
|
||||
layer_name = layer.get('name', 'Unnamed')
|
||||
layer_id = layer.get('id', 'Unknown')
|
||||
|
||||
prefix = " " * indent
|
||||
# Handle layer_id that might not be a string
|
||||
id_str = layer_id[:8] + "..." if isinstance(layer_id, str) and len(layer_id) > 8 else str(layer_id)
|
||||
print(f"{prefix}- [{layer_type}] {layer_name} (ID: {id_str})")
|
||||
|
||||
# Recursively print children
|
||||
children = layer.get('children', [])
|
||||
for child in children:
|
||||
print_layer(child, indent + 1)
|
||||
|
||||
print_layer(root)
|
||||
|
||||
def show_tracks(self):
|
||||
"""Display audio tracks information."""
|
||||
if not self.project_data:
|
||||
return
|
||||
|
||||
audio_backend = self.project_data.get('audio_backend', {})
|
||||
project = audio_backend.get('project', {})
|
||||
tracks_dict = project.get('tracks', {})
|
||||
root_tracks = project.get('root_tracks', [])
|
||||
master_track = project.get('master_track', {})
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("AUDIO TRACKS")
|
||||
print("=" * 60)
|
||||
|
||||
print(f"Total Tracks: {len(tracks_dict)}")
|
||||
|
||||
# Iterate through root_tracks in order
|
||||
for track_id in root_tracks:
|
||||
track_id_str = str(track_id)
|
||||
if track_id_str not in tracks_dict:
|
||||
print(f"\n Track {track_id}: ERROR - Track ID not found in tracks dict")
|
||||
continue
|
||||
|
||||
track_node = tracks_dict[track_id_str]
|
||||
|
||||
# TrackNode is an enum with variants like {"Audio": {...}} or {"Midi": {...}}
|
||||
if not isinstance(track_node, dict):
|
||||
print(f"\n Track {track_id}: ERROR - Track node is {type(track_node).__name__}, not a dict")
|
||||
continue
|
||||
|
||||
# Extract the variant (Audio, Midi, or Group)
|
||||
if len(track_node) != 1:
|
||||
print(f"\n Track {track_id}: ERROR - Track node has unexpected structure")
|
||||
continue
|
||||
|
||||
track_type, track_data = list(track_node.items())[0]
|
||||
|
||||
if not isinstance(track_data, dict):
|
||||
print(f"\n Track {track_id}: ERROR - Track data is {type(track_data).__name__}, not a dict")
|
||||
continue
|
||||
|
||||
track_name = track_data.get('name', f'Track {track_id}')
|
||||
muted = track_data.get('muted', False)
|
||||
solo = track_data.get('solo', False)
|
||||
volume = track_data.get('volume', 1.0)
|
||||
pan = track_data.get('pan', 0.0)
|
||||
|
||||
status = []
|
||||
if muted:
|
||||
status.append('MUTED')
|
||||
if solo:
|
||||
status.append('SOLO')
|
||||
status_str = f" [{', '.join(status)}]" if status else ""
|
||||
|
||||
print(f"\n Track {track_id}: {track_name}{status_str}")
|
||||
print(f" Type: {track_type}")
|
||||
print(f" Volume: {volume:.2f}")
|
||||
print(f" Pan: {pan:.2f}")
|
||||
|
||||
if track_type == "Midi":
|
||||
print(f" Instrument: {track_data.get('instrument', 'Unknown')}")
|
||||
notes = track_data.get('notes', [])
|
||||
print(f" Notes: {len(notes)}")
|
||||
preset = track_data.get('instrument_graph_preset')
|
||||
if preset:
|
||||
nodes = preset.get('nodes', [])
|
||||
conns = preset.get('connections', [])
|
||||
print(f" Graph: {len(nodes)} nodes, {len(conns)} connections")
|
||||
else:
|
||||
print(f" Graph: (no preset saved)")
|
||||
elif track_type == "Audio":
|
||||
clips = track_data.get('clips', [])
|
||||
print(f" Clips: {len(clips)}")
|
||||
preset = track_data.get('effects_graph_preset')
|
||||
if preset:
|
||||
nodes = preset.get('nodes', [])
|
||||
conns = preset.get('connections', [])
|
||||
print(f" Graph: {len(nodes)} nodes, {len(conns)} connections")
|
||||
else:
|
||||
print(f" Graph: (no preset saved)")
|
||||
|
||||
print(f"\nMaster Track:")
|
||||
print(f" Volume: {master_track.get('volume', 1.0):.2f}")
|
||||
|
||||
def show_graphs(self):
|
||||
"""Display detailed node graph information for all tracks."""
|
||||
if not self.project_data:
|
||||
return
|
||||
|
||||
audio_backend = self.project_data.get('audio_backend', {})
|
||||
project = audio_backend.get('project', {})
|
||||
tracks_dict = project.get('tracks', {})
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("NODE GRAPHS")
|
||||
print("=" * 60)
|
||||
|
||||
for track_id_str, track_node in tracks_dict.items():
|
||||
if not isinstance(track_node, dict) or len(track_node) != 1:
|
||||
continue
|
||||
|
||||
track_type, track_data = list(track_node.items())[0]
|
||||
track_name = track_data.get('name', f'Track {track_id_str}')
|
||||
|
||||
# Get the appropriate preset
|
||||
if track_type == "Audio":
|
||||
preset = track_data.get('effects_graph_preset')
|
||||
graph_label = "Effects Graph"
|
||||
elif track_type == "Midi":
|
||||
preset = track_data.get('instrument_graph_preset')
|
||||
graph_label = "Instrument Graph"
|
||||
else:
|
||||
continue
|
||||
|
||||
print(f"\n Track {track_id_str}: {track_name} ({track_type}) - {graph_label}")
|
||||
|
||||
if not preset:
|
||||
print(f" ** NO PRESET SAVED **")
|
||||
continue
|
||||
|
||||
nodes = preset.get('nodes', [])
|
||||
connections = preset.get('connections', [])
|
||||
output_node = preset.get('output_node')
|
||||
midi_targets = preset.get('midi_targets', [])
|
||||
metadata = preset.get('metadata', {})
|
||||
|
||||
if metadata:
|
||||
print(f" Preset Name: {metadata.get('name', 'Unknown')}")
|
||||
|
||||
print(f" Nodes ({len(nodes)}):")
|
||||
for i, node in enumerate(nodes):
|
||||
node_type = node.get('node_type', '?')
|
||||
node_name = node.get('name', node_type)
|
||||
params = node.get('parameters', {})
|
||||
pos_x = node.get('position_x', 0)
|
||||
pos_y = node.get('position_y', 0)
|
||||
|
||||
markers = []
|
||||
if output_node is not None and i == output_node:
|
||||
markers.append("OUTPUT")
|
||||
if i in midi_targets:
|
||||
markers.append("MIDI TARGET")
|
||||
marker_str = f" [{', '.join(markers)}]" if markers else ""
|
||||
|
||||
print(f" [{i}] {node_type}{marker_str} (name={node_name}, pos={pos_x:.0f},{pos_y:.0f})")
|
||||
|
||||
if params:
|
||||
for param_name, param_val in params.items():
|
||||
print(f" {param_name} = {param_val}")
|
||||
|
||||
print(f" Connections ({len(connections)}):")
|
||||
for conn in connections:
|
||||
src = conn.get('from_node', '?')
|
||||
src_port = conn.get('from_output', '?')
|
||||
dst = conn.get('to_node', '?')
|
||||
dst_port = conn.get('to_input', '?')
|
||||
print(f" [{src}]:{src_port} -> [{dst}]:{dst_port}")
|
||||
|
||||
# Also show layer_to_track_map if present
|
||||
track_map = audio_backend.get('layer_to_track_map', {})
|
||||
if track_map:
|
||||
print(f"\n Layer-to-Track Mapping ({len(track_map)} entries):")
|
||||
for layer_id, track_id in track_map.items():
|
||||
print(f" {layer_id[:8]}... -> Track {track_id}")
|
||||
else:
|
||||
print(f"\n Layer-to-Track Mapping: (none saved)")
|
||||
|
||||
def show_audio_pool(self):
|
||||
"""Display audio pool entries."""
|
||||
if not self.project_data:
|
||||
return
|
||||
|
||||
audio_backend = self.project_data.get('audio_backend', {})
|
||||
pool_entries = audio_backend.get('audio_pool_entries', [])
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("AUDIO POOL")
|
||||
print("=" * 60)
|
||||
|
||||
print(f"Total Entries: {len(pool_entries)}")
|
||||
|
||||
for entry in pool_entries:
|
||||
pool_index = entry.get('pool_index', '?')
|
||||
name = entry.get('name', 'Unnamed')
|
||||
relative_path = entry.get('relative_path')
|
||||
media_id = entry.get('media_id')
|
||||
channels = entry.get('channels', 0)
|
||||
sample_rate = entry.get('sample_rate', 0)
|
||||
has_embedded = entry.get('embedded_data') is not None
|
||||
|
||||
# Storage precedence matches the loader (§8.5/§9.3):
|
||||
# packed (media_id) > external (relative_path) > embedded > unresolved.
|
||||
row = self.media_by_id.get(media_id) if media_id else None
|
||||
if media_id:
|
||||
size = f", {_human_size(row['total_len'])}" if row else ""
|
||||
codec = f", {row['codec']}" if row else ""
|
||||
storage_type = f"Packed in DB{codec}{size}"
|
||||
elif relative_path and not self.is_sqlite and relative_path.startswith("media/audio/"):
|
||||
# Legacy ZIP: media/audio/* lives inside the archive, not external.
|
||||
storage_type = "Embedded (in ZIP)"
|
||||
elif relative_path:
|
||||
storage_type = "External reference"
|
||||
elif has_embedded:
|
||||
storage_type = "Embedded (inline base64)"
|
||||
else:
|
||||
storage_type = "Unresolved (missing)"
|
||||
|
||||
print(f"\n [{pool_index}] {name}")
|
||||
if media_id:
|
||||
print(f" Media ID: {media_id}")
|
||||
print(f" Path: {relative_path if relative_path else 'N/A'}")
|
||||
print(f" Storage: {storage_type}")
|
||||
print(f" Channels: {channels}")
|
||||
print(f" Sample Rate: {sample_rate} Hz")
|
||||
|
||||
def show_media(self):
|
||||
"""Display the SQLite media store (the `media` table)."""
|
||||
if not self.is_sqlite:
|
||||
print("\n(media table view applies to SQLite .beam files; "
|
||||
"use --zip for legacy archives)", file=sys.stderr)
|
||||
return
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("MEDIA STORE")
|
||||
print("=" * 60)
|
||||
|
||||
print(f"Total media rows: {len(self.media)}")
|
||||
|
||||
# Summary by kind.
|
||||
by_kind: Dict[str, List[Dict[str, Any]]] = {}
|
||||
for m in self.media:
|
||||
by_kind.setdefault(MEDIA_KIND_NAMES.get(m["kind"], f"Kind {m['kind']}"), []).append(m)
|
||||
if by_kind:
|
||||
print("\nBy kind:")
|
||||
for kind_name, rows in sorted(by_kind.items()):
|
||||
packed = sum(r["total_len"] for r in rows if r["storage"] == 0)
|
||||
print(f" {kind_name:<12} {len(rows):>4} ({_human_size(packed)} packed)")
|
||||
|
||||
print(f"\n{'Kind':<12} {'Storage':<11} {'Codec':<6} {'Size':>10} UUID / details")
|
||||
print("-" * 78)
|
||||
for m in self.media:
|
||||
kind = MEDIA_KIND_NAMES.get(m["kind"], f"Kind {m['kind']}")
|
||||
storage = MEDIA_STORAGE_NAMES.get(m["storage"], f"Stor {m['storage']}")
|
||||
size = _human_size(m["total_len"]) if m["storage"] == 0 else "-"
|
||||
detail = m["uuid"]
|
||||
extra = []
|
||||
if m["channels"] is not None:
|
||||
extra.append(f"{m['channels']}ch@{m['sample_rate']}Hz")
|
||||
if m["width"] is not None:
|
||||
extra.append(f"{m['width']}x{m['height']}")
|
||||
if m["storage"] == 1 and m["ext_path"]:
|
||||
extra.append(f"-> {m['ext_path']}")
|
||||
if extra:
|
||||
detail += " " + " ".join(extra)
|
||||
print(f"{kind:<12} {storage:<11} {m['codec']:<6} {size:>10} {detail}")
|
||||
|
||||
def show_container(self):
|
||||
"""Show whichever container structure applies to this file."""
|
||||
if self.is_sqlite:
|
||||
self.show_media()
|
||||
else:
|
||||
self.show_zip_structure()
|
||||
|
||||
def show_zip_structure(self):
|
||||
"""Display the ZIP file structure."""
|
||||
if self.is_sqlite:
|
||||
print("\n(this is a SQLite .beam; use --media for the media store)",
|
||||
file=sys.stderr)
|
||||
return
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("ZIP ARCHIVE STRUCTURE")
|
||||
print("=" * 60)
|
||||
|
||||
try:
|
||||
with zipfile.ZipFile(self.beam_file, 'r') as zip_ref:
|
||||
total_size = 0
|
||||
compressed_size = 0
|
||||
|
||||
print(f"{'File':<40} {'Size':>12} {'Compressed':>12} {'Method':<10}")
|
||||
print("-" * 80)
|
||||
|
||||
for info in zip_ref.infolist():
|
||||
size = info.file_size
|
||||
comp_size = info.compress_size
|
||||
method = "DEFLATE" if info.compress_type == 8 else "STORED" if info.compress_type == 0 else f"Type {info.compress_type}"
|
||||
|
||||
total_size += size
|
||||
compressed_size += comp_size
|
||||
|
||||
print(f"{info.filename:<40} {size:>12,} {comp_size:>12,} {method:<10}")
|
||||
|
||||
print("-" * 80)
|
||||
print(f"{'TOTAL':<40} {total_size:>12,} {compressed_size:>12,}")
|
||||
|
||||
if total_size > 0:
|
||||
ratio = (1 - compressed_size / total_size) * 100
|
||||
print(f"\nCompression Ratio: {ratio:.1f}%")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error reading ZIP structure: {e}", file=sys.stderr)
|
||||
|
||||
def extract_json(self, output_path: Optional[Path] = None):
|
||||
"""Extract project.json to a file or stdout."""
|
||||
try:
|
||||
if self.is_sqlite:
|
||||
con = self._connect()
|
||||
try:
|
||||
row = con.execute("SELECT data FROM project_json WHERE id = 0").fetchone()
|
||||
finally:
|
||||
con.close()
|
||||
if not row:
|
||||
raise ValueError("archive has no project.json row")
|
||||
json_data = row[0].encode("utf-8") if isinstance(row[0], str) else row[0]
|
||||
else:
|
||||
with zipfile.ZipFile(self.beam_file, 'r') as zip_ref:
|
||||
json_data = zip_ref.read('project.json')
|
||||
|
||||
if output_path:
|
||||
output_path.write_bytes(json_data)
|
||||
print(f"Extracted project.json to: {output_path}")
|
||||
else:
|
||||
data = json.loads(json_data)
|
||||
print(json.dumps(data, indent=2))
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error extracting project.json: {e}", file=sys.stderr)
|
||||
|
||||
def extract_media(self, output_dir: Path):
|
||||
"""Extract all media to a directory.
|
||||
|
||||
SQLite: each packed media row is reassembled from its chunks and written
|
||||
as ``<uuid>.<codec>``; referenced rows are reported, not copied.
|
||||
ZIP (legacy): the ``media/`` entries are extracted preserving paths.
|
||||
"""
|
||||
try:
|
||||
if self.is_sqlite:
|
||||
self._extract_media_sqlite(output_dir)
|
||||
else:
|
||||
self._extract_media_zip(output_dir)
|
||||
except Exception as e:
|
||||
print(f"Error extracting media: {e}", file=sys.stderr)
|
||||
|
||||
def _extract_media_sqlite(self, output_dir: Path):
|
||||
con = self._connect()
|
||||
try:
|
||||
rows = con.execute(
|
||||
"SELECT id, kind, codec, storage, ext_path, total_len FROM media"
|
||||
).fetchall()
|
||||
if not rows:
|
||||
print("No media rows found in archive.")
|
||||
return
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
written = 0
|
||||
for (idb, kind, codec, storage, ext_path, total_len) in rows:
|
||||
uid = str(uuidlib.UUID(bytes=bytes(idb)))
|
||||
kind_name = MEDIA_KIND_NAMES.get(kind, f"kind{kind}")
|
||||
if storage == 1: # Referenced
|
||||
print(f"Referenced (not copied): {uid} [{kind_name}] -> {ext_path}")
|
||||
continue
|
||||
chunks = con.execute(
|
||||
"SELECT bytes FROM media_chunk WHERE media_id = ? ORDER BY chunk_index",
|
||||
(idb,),
|
||||
).fetchall()
|
||||
data = b"".join(bytes(c[0]) for c in chunks)
|
||||
out = output_dir / f"{uid}.{codec}"
|
||||
out.write_bytes(data)
|
||||
print(f"Extracted: {out.name} [{kind_name}] {_human_size(len(data))}")
|
||||
written += 1
|
||||
print(f"\nExtracted {written} packed media item(s) to: {output_dir}")
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
def _extract_media_zip(self, output_dir: Path):
|
||||
with zipfile.ZipFile(self.beam_file, 'r') as zip_ref:
|
||||
media_files = [f for f in zip_ref.namelist() if f.startswith('media/')]
|
||||
if not media_files:
|
||||
print("No media files found in archive.")
|
||||
return
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
for media_file in media_files:
|
||||
output_path = output_dir / media_file
|
||||
output_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with zip_ref.open(media_file) as source:
|
||||
output_path.write_bytes(source.read())
|
||||
print(f"Extracted: {media_file}")
|
||||
print(f"\nExtracted {len(media_files)} media file(s) to: {output_dir}")
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Inspect Lightningbeam .beam project files",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="""
|
||||
Examples:
|
||||
%(prog)s project.beam # Show all information
|
||||
%(prog)s project.beam --info # Show only basic info
|
||||
%(prog)s project.beam --tracks # Show only tracks
|
||||
%(prog)s project.beam --media # Show the SQLite media store
|
||||
%(prog)s project.beam --zip # Show legacy ZIP structure
|
||||
%(prog)s project.beam --extract-json # Print project.json to stdout
|
||||
%(prog)s project.beam --extract-json out.json # Save project.json
|
||||
%(prog)s project.beam --extract-media ./media # Extract media files
|
||||
|
||||
Handles both current SQLite .beam files and legacy ZIP .beam files
|
||||
(detected automatically by the file's magic bytes).
|
||||
"""
|
||||
)
|
||||
|
||||
parser.add_argument('beam_file', type=Path, help='.beam file to inspect')
|
||||
parser.add_argument('--info', action='store_true', help='Show project information')
|
||||
parser.add_argument('--clips', action='store_true', help='Show clips')
|
||||
parser.add_argument('--layers', action='store_true', help='Show layer hierarchy')
|
||||
parser.add_argument('--tracks', action='store_true', help='Show audio tracks')
|
||||
parser.add_argument('--graphs', action='store_true', help='Show node graph details for all tracks')
|
||||
parser.add_argument('--pool', action='store_true', help='Show audio pool')
|
||||
parser.add_argument('--media', action='store_true', help='Show the SQLite media store')
|
||||
parser.add_argument('--zip', action='store_true', help='Show legacy ZIP structure')
|
||||
parser.add_argument('--extract-json', nargs='?', const=True, metavar='OUTPUT',
|
||||
help='Extract project.json (to file or stdout)')
|
||||
parser.add_argument('--extract-media', type=Path, metavar='DIR',
|
||||
help='Extract media files to directory')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
# Validate input file
|
||||
if not args.beam_file.exists():
|
||||
print(f"Error: File not found: {args.beam_file}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if not args.beam_file.suffix == '.beam':
|
||||
print(f"Warning: File does not have .beam extension: {args.beam_file}", file=sys.stderr)
|
||||
|
||||
# Create inspector
|
||||
inspector = BeamInspector(args.beam_file)
|
||||
|
||||
# Handle extract operations (don't need to load project.json)
|
||||
if args.extract_json:
|
||||
if args.extract_json is True:
|
||||
inspector.extract_json()
|
||||
else:
|
||||
inspector.extract_json(Path(args.extract_json))
|
||||
return
|
||||
|
||||
if args.extract_media:
|
||||
inspector.extract_media(args.extract_media)
|
||||
return
|
||||
|
||||
# Load the beam file
|
||||
if not inspector.load():
|
||||
sys.exit(1)
|
||||
|
||||
# If no specific flags, show everything
|
||||
show_all = not any([args.info, args.clips, args.layers, args.tracks,
|
||||
args.graphs, args.pool, args.media, args.zip])
|
||||
|
||||
if show_all or args.info:
|
||||
inspector.show_info()
|
||||
|
||||
if show_all or args.clips:
|
||||
inspector.show_clips()
|
||||
|
||||
if show_all or args.layers:
|
||||
inspector.show_layers()
|
||||
|
||||
if show_all or args.tracks:
|
||||
inspector.show_tracks()
|
||||
|
||||
if show_all or args.graphs:
|
||||
inspector.show_graphs()
|
||||
|
||||
if show_all or args.pool:
|
||||
inspector.show_audio_pool()
|
||||
|
||||
if show_all:
|
||||
# Show whichever container structure applies to this file.
|
||||
inspector.show_container()
|
||||
elif args.media:
|
||||
inspector.show_media()
|
||||
elif args.zip:
|
||||
inspector.show_zip_structure()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,210 @@
|
||||
# Lightningbeam .beam File Inspector
|
||||
|
||||
A Python command-line tool to inspect and analyze `.beam` project files.
|
||||
|
||||
Handles **both** container formats automatically (detected by the file's magic
|
||||
bytes): the current **SQLite** `.beam` and the **legacy ZIP** `.beam`. See
|
||||
[BEAM_FILE_FORMAT.md](./BEAM_FILE_FORMAT.md) for the format specification.
|
||||
|
||||
## Features
|
||||
|
||||
- **Project Information**: Container type, schema version, metadata, dimensions, framerate, duration, background color
|
||||
- **Clips Analysis**: List all vector, video, and audio clips
|
||||
- **Layer Hierarchy**: Display the complete layer tree structure
|
||||
- **Audio Tracks**: Show all audio/MIDI tracks with their settings
|
||||
- **Audio Pool**: List all audio files and their storage details
|
||||
- **Media Store** (SQLite): List the `media` table — kinds, storage, codecs, sizes
|
||||
- **ZIP Structure** (legacy): Examine the internal ZIP archive structure and compression
|
||||
- **Extraction**: Extract `project.json` or media files
|
||||
|
||||
## Installation
|
||||
|
||||
The tool requires Python 3.6+ with no external dependencies (uses only the standard
|
||||
library; `sqlite3` ships with Python).
|
||||
|
||||
```bash
|
||||
chmod +x beam_inspector.py
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
### Show All Information
|
||||
```bash
|
||||
./beam_inspector.py project.beam
|
||||
```
|
||||
|
||||
### Show Specific Sections
|
||||
```bash
|
||||
# Basic project info only
|
||||
./beam_inspector.py project.beam --info
|
||||
|
||||
# Audio tracks only
|
||||
./beam_inspector.py project.beam --tracks
|
||||
|
||||
# Audio pool entries
|
||||
./beam_inspector.py project.beam --pool
|
||||
|
||||
# Layer hierarchy
|
||||
./beam_inspector.py project.beam --layers
|
||||
|
||||
# Clips summary
|
||||
./beam_inspector.py project.beam --clips
|
||||
|
||||
# Media store (SQLite files): the media table — kinds, storage, codecs, sizes
|
||||
./beam_inspector.py project.beam --media
|
||||
|
||||
# ZIP archive structure (legacy ZIP files only)
|
||||
./beam_inspector.py project.beam --zip
|
||||
```
|
||||
|
||||
When run with no section flags, the tool shows everything and automatically
|
||||
picks the media-store view (SQLite) or ZIP-structure view (legacy) for the file.
|
||||
|
||||
### Extract Files
|
||||
```bash
|
||||
# Print project.json to stdout (pretty-printed)
|
||||
./beam_inspector.py project.beam --extract-json
|
||||
|
||||
# Save project.json to a file
|
||||
./beam_inspector.py project.beam --extract-json output.json
|
||||
|
||||
# Extract all media files to a directory
|
||||
./beam_inspector.py project.beam --extract-media ./extracted_media
|
||||
```
|
||||
|
||||
## Example Output
|
||||
|
||||
```
|
||||
============================================================
|
||||
PROJECT INFORMATION
|
||||
============================================================
|
||||
Container: SQLite
|
||||
Schema Ver: 1
|
||||
Version: 1.0.0
|
||||
Created: 2025-12-01T12:00:00Z
|
||||
Modified: 2025-12-01T12:30:00Z
|
||||
|
||||
Project Name: My Animation
|
||||
ID: 550e8400-e29b-41d4-a716-446655440000
|
||||
Dimensions: 1920 x 1080
|
||||
Framerate: 60.0 fps
|
||||
Duration: 10.00 seconds
|
||||
Background: rgba(255, 255, 255, 255)
|
||||
|
||||
Sample Rate: 48000 Hz
|
||||
|
||||
============================================================
|
||||
AUDIO TRACKS
|
||||
============================================================
|
||||
Total Tracks: 2
|
||||
|
||||
Track 0: Piano [SOLO]
|
||||
Type: Midi
|
||||
Volume: 0.80
|
||||
Pan: 0.00
|
||||
Instrument: Piano
|
||||
Notes: 24
|
||||
|
||||
Track 1: Background Music
|
||||
Type: Audio
|
||||
Volume: 0.60
|
||||
Pan: 0.00
|
||||
Clips: 3
|
||||
|
||||
Master Track:
|
||||
Volume: 1.00
|
||||
|
||||
============================================================
|
||||
AUDIO POOL
|
||||
============================================================
|
||||
Total Entries: 2
|
||||
|
||||
[0] C2.mp3
|
||||
Media ID: e7e555a6-85f1-4faa-bfd4-c6e4b790986a
|
||||
Path: N/A
|
||||
Storage: Packed in DB, mp3, 412.0 KiB
|
||||
Channels: 2
|
||||
Sample Rate: 44100 Hz
|
||||
|
||||
[1] Background.flac
|
||||
Media ID: a18c0e22-1d3b-4c77-9f0a-2b5e6c4d8e10
|
||||
Path: N/A
|
||||
Storage: Packed in DB, flac, 6.4 MiB
|
||||
Channels: 2
|
||||
Sample Rate: 48000 Hz
|
||||
```
|
||||
|
||||
## Understanding the Output
|
||||
|
||||
### Storage Types
|
||||
- **Packed in DB**: Audio bytes are chunked into the SQLite `media` table (the entry's `media_id` resolves to a packed row). Current default for most audio.
|
||||
- **External reference**: File is referenced from the filesystem by `relative_path` (e.g. large media or video audio).
|
||||
- **Embedded (inline base64)**: Bytes stored directly in `project.json` (`embedded_data`) — legacy/fallback.
|
||||
- **Embedded (in ZIP)**: Legacy ZIP files only — bytes stored inside the archive under `media/audio/`.
|
||||
- **Unresolved (missing)**: No packed row, external file, or embedded data — reported as a missing file on load.
|
||||
|
||||
### Track Types
|
||||
- **Audio**: Traditional audio track with clips from the audio pool
|
||||
- **Midi**: MIDI track with note events and virtual instrument
|
||||
|
||||
### Layer Types
|
||||
Based on the `AnyLayer` enum:
|
||||
- **Group**: Container for other layers
|
||||
- **Vector**: Vector graphics layer
|
||||
- **Video**: Video clip layer
|
||||
- **Audio**: Audio waveform layer
|
||||
- **Image**: Raster image layer
|
||||
- **Text**: Text layer
|
||||
|
||||
## Advanced Usage
|
||||
|
||||
### Combine with Other Tools
|
||||
```bash
|
||||
# Pretty-print and page through JSON
|
||||
./beam_inspector.py project.beam --extract-json | less
|
||||
|
||||
# Search for specific content in JSON
|
||||
./beam_inspector.py project.beam --extract-json | grep "sample_rate"
|
||||
|
||||
# Count total audio files
|
||||
./beam_inspector.py project.beam --pool | grep "^\[" | wc -l
|
||||
|
||||
# Extract and process media files
|
||||
# SQLite: writes flat <uuid>.<codec> files; ZIP: preserves media/ paths
|
||||
./beam_inspector.py project.beam --extract-media /tmp/media
|
||||
ls -lh /tmp/media/
|
||||
```
|
||||
|
||||
### Scripting
|
||||
```python
|
||||
from beam_inspector import BeamInspector
|
||||
from pathlib import Path
|
||||
|
||||
inspector = BeamInspector(Path("project.beam"))
|
||||
if inspector.load():
|
||||
# Access parsed data
|
||||
version = inspector.project_data['version']
|
||||
tracks = inspector.project_data['audio_backend']['project']['tracks']
|
||||
print(f"Found {len(tracks)} tracks in version {version}")
|
||||
```
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "Error loading .beam file"
|
||||
- Ensure the file is a valid SQLite database (current) or ZIP archive (legacy)
|
||||
- Check that `project.json` exists (the `project_json` table for SQLite, or a top-level entry for ZIP)
|
||||
- Verify the JSON is well-formed
|
||||
|
||||
### "File not found"
|
||||
- Provide the full path to the .beam file
|
||||
- Check file permissions
|
||||
|
||||
### Missing media files
|
||||
- External references may point to files that don't exist
|
||||
- Use `--extract-media` to see what's actually in the archive
|
||||
- Check the `relative_path` values in `--pool` output
|
||||
|
||||
## See Also
|
||||
|
||||
- [BEAM_FILE_FORMAT.md](./BEAM_FILE_FORMAT.md) - Complete .beam file format specification
|
||||
- [Lightningbeam Documentation](./README.md) - Main project documentation
|
||||
+3
-1
@@ -26,7 +26,9 @@ echo "Merging $MAIN_BRANCH into $RELEASE_BRANCH..."
|
||||
git merge $MAIN_BRANCH --no-ff -m "Release $VERSION"
|
||||
|
||||
echo "Pushing $RELEASE_BRANCH..."
|
||||
git push origin $RELEASE_BRANCH
|
||||
# Push to the 'all' remote so the release branch lands on both GitHub and Gitea.
|
||||
# CI (GitHub Actions) still triggers via the GitHub pushurl.
|
||||
git push all $RELEASE_BRANCH
|
||||
|
||||
git checkout $MAIN_BRANCH
|
||||
|
||||
|
||||
@@ -23,6 +23,8 @@ memmap2 = "0.9"
|
||||
# Audio export
|
||||
hound = "3.5"
|
||||
ffmpeg-next = "8.0" # For MP3/AAC encoding
|
||||
# AVIO-over-Read+Seek shim: stream a packed video's audio track from the SQLite blob.
|
||||
ffmpeg-blob-io = { path = "../ffmpeg-blob-io" }
|
||||
|
||||
# Node-based audio graph dependencies
|
||||
dasp_graph = "0.11"
|
||||
|
||||
@@ -77,6 +77,12 @@ pub struct ReadAheadBuffer {
|
||||
/// When true, `render_from_file` will block-wait for frames instead of
|
||||
/// returning silence on buffer miss. Used during offline export.
|
||||
export_mode: AtomicBool,
|
||||
/// Set by the disk reader when the source reaches EOF (no more frames will
|
||||
/// ever be decoded past the current valid range). Lets export-mode block-waits
|
||||
/// give up immediately for frames past the end of the audio (e.g. a video whose
|
||||
/// audio track is shorter than the video) instead of timing out per chunk.
|
||||
/// Cleared on `reset` (a seek may decode fresh data again).
|
||||
finished: AtomicBool,
|
||||
}
|
||||
|
||||
// SAFETY: See the doc comment on ReadAheadBuffer for the full safety argument.
|
||||
@@ -112,6 +118,7 @@ impl ReadAheadBuffer {
|
||||
sample_rate,
|
||||
target_frame: AtomicU64::new(0),
|
||||
export_mode: AtomicBool::new(false),
|
||||
finished: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,11 +223,24 @@ impl ReadAheadBuffer {
|
||||
self.export_mode.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// Mark that the source has reached EOF (set by the disk reader).
|
||||
pub fn set_finished(&self, finished: bool) {
|
||||
self.finished.store(finished, Ordering::Release);
|
||||
}
|
||||
|
||||
/// True once the source hit EOF: no frames past the current valid range
|
||||
/// will ever be decoded (until a `reset`/seek).
|
||||
pub fn is_finished(&self) -> bool {
|
||||
self.finished.load(Ordering::Acquire)
|
||||
}
|
||||
|
||||
/// Reset the buffer to start at `new_start` with zero valid frames.
|
||||
/// Called by the **disk reader thread** (producer) after a seek.
|
||||
pub fn reset(&self, new_start: u64) {
|
||||
self.valid_frames.store(0, Ordering::Release);
|
||||
self.start_frame.store(new_start, Ordering::Release);
|
||||
// A seek may decode fresh data past the previous EOF position.
|
||||
self.finished.store(false, Ordering::Release);
|
||||
}
|
||||
|
||||
/// Write interleaved samples into the buffer, extending the valid range.
|
||||
@@ -571,8 +591,37 @@ impl CompressedReader {
|
||||
///
|
||||
/// Public (vs. the private `CompressedReader`) only so integration tests can
|
||||
/// exercise it directly; treat it as crate-internal.
|
||||
/// Adapts a host `MediaByteSource` (Read+Seek+Send+Sync) to the `ffmpeg-blob-io`
|
||||
/// `BlobSource` (Read+Seek+Send) so a packed video can be demuxed from a blob.
|
||||
struct ByteSourceAdapter(Box<dyn MediaByteSource>);
|
||||
impl std::io::Read for ByteSourceAdapter {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
self.0.read(buf)
|
||||
}
|
||||
}
|
||||
impl std::io::Seek for ByteSourceAdapter {
|
||||
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
|
||||
self.0.seek(pos)
|
||||
}
|
||||
}
|
||||
|
||||
/// A demuxer input for video-audio: a video file path, or a container blob streamed
|
||||
/// via the AVIO shim. Both expose the same ffmpeg `Input`.
|
||||
enum AudioInput {
|
||||
Path(ffmpeg_next::format::context::Input),
|
||||
Blob(ffmpeg_blob_io::BlobInput),
|
||||
}
|
||||
impl AudioInput {
|
||||
fn get(&mut self) -> &mut ffmpeg_next::format::context::Input {
|
||||
match self {
|
||||
AudioInput::Path(i) => i,
|
||||
AudioInput::Blob(b) => b.input_mut(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct VideoAudioReader {
|
||||
input: ffmpeg_next::format::context::Input,
|
||||
input: AudioInput,
|
||||
decoder: ffmpeg_next::decoder::Audio,
|
||||
/// Built lazily from the first decoded frame's format/layout → interleaved f32.
|
||||
resampler: Option<ffmpeg_next::software::resampling::Context>,
|
||||
@@ -605,15 +654,30 @@ impl VideoAudioReader {
|
||||
self.total_frames
|
||||
}
|
||||
|
||||
/// Open the audio track of a video **file**.
|
||||
pub fn open(path: &Path) -> Result<Self, String> {
|
||||
ffmpeg_next::init().map_err(|e| e.to_string())?;
|
||||
let input = ffmpeg_next::format::input(&path)
|
||||
.map_err(|e| format!("Failed to open media: {}", e))?;
|
||||
Self::from_input(AudioInput::Path(input))
|
||||
}
|
||||
|
||||
/// Open the audio track of a video streamed from a **byte source** (a packed
|
||||
/// `.beam` video blob), via the `ffmpeg-blob-io` AVIO shim. `ext` is a container
|
||||
/// hint (e.g. `"mp4"`).
|
||||
pub fn open_source(src: Box<dyn MediaByteSource>, ext: Option<&str>) -> Result<Self, String> {
|
||||
ffmpeg_next::init().map_err(|e| e.to_string())?;
|
||||
let blob = ffmpeg_blob_io::BlobInput::open(Box::new(ByteSourceAdapter(src)), ext)
|
||||
.map_err(|e| format!("Failed to open packed video audio: {}", e))?;
|
||||
Self::from_input(AudioInput::Blob(blob))
|
||||
}
|
||||
|
||||
fn from_input(mut input: AudioInput) -> Result<Self, String> {
|
||||
// Pull stream scalars + build the decoder inside a scope so the stream
|
||||
// borrow of `input` ends before we use `input` again.
|
||||
let (stream_index, time_base, stream_duration, decoder) = {
|
||||
let stream = input
|
||||
.get()
|
||||
.streams()
|
||||
.best(ffmpeg_next::media::Type::Audio)
|
||||
.ok_or_else(|| "No audio stream found".to_string())?;
|
||||
@@ -631,8 +695,8 @@ impl VideoAudioReader {
|
||||
|
||||
let duration_secs = if stream_duration > 0 {
|
||||
stream_duration as f64 * time_base
|
||||
} else if input.duration() > 0 {
|
||||
input.duration() as f64 / f64::from(ffmpeg_next::ffi::AV_TIME_BASE)
|
||||
} else if input.get().duration() > 0 {
|
||||
input.get().duration() as f64 / f64::from(ffmpeg_next::ffi::AV_TIME_BASE)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
@@ -659,6 +723,7 @@ impl VideoAudioReader {
|
||||
// Seek to at-or-before the target (max_ts = ts_av) so we can decode
|
||||
// forward to it exactly. ffmpeg-next's `seek` wants a bounded range.
|
||||
self.input
|
||||
.get()
|
||||
.seek(ts_av, 0..(ts_av + 1))
|
||||
.map_err(|e| format!("Seek failed: {}", e))?;
|
||||
self.decoder.flush();
|
||||
@@ -684,7 +749,7 @@ impl VideoAudioReader {
|
||||
}
|
||||
|
||||
// Read one packet (owned), releasing the `input` borrow before decoding.
|
||||
let packet = self.input.packets().next().map(|(_, p)| p);
|
||||
let packet = self.input.get().packets().next().map(|(_, p)| p);
|
||||
match packet {
|
||||
Some(packet) => {
|
||||
if packet.stream() == self.stream_index {
|
||||
@@ -827,8 +892,8 @@ impl StreamSource {
|
||||
(SourceKind::VideoAudio, StreamOpen::Path(p)) => {
|
||||
Ok(StreamSource::Video(VideoAudioReader::open(&p)?))
|
||||
}
|
||||
(SourceKind::VideoAudio, StreamOpen::Source { .. }) => {
|
||||
Err("VideoAudio cannot be opened from a packed byte source".to_string())
|
||||
(SourceKind::VideoAudio, StreamOpen::Source { src, ext }) => {
|
||||
Ok(StreamSource::Video(VideoAudioReader::open_source(src, ext.as_deref())?))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1093,7 +1158,12 @@ impl DiskReader {
|
||||
|
||||
// Decode more data into the buffer.
|
||||
match reader.decode_next(&mut decode_buf) {
|
||||
Ok(0) => {} // EOF
|
||||
Ok(0) => {
|
||||
// EOF: no more frames will be decoded for this buffer until a
|
||||
// seek. Tell export-mode waiters so they stop blocking on
|
||||
// past-the-end frames (e.g. video longer than its audio).
|
||||
buffer.set_finished(true);
|
||||
}
|
||||
Ok(frames) => {
|
||||
let was_empty = buffer.valid_frames_count() == 0;
|
||||
buffer.write_samples(&decode_buf, frames);
|
||||
|
||||
@@ -116,7 +116,6 @@ pub struct Engine {
|
||||
|
||||
// Current tempo map — kept in sync with SetTempo/SetTempoMap commands.
|
||||
tempo_map: crate::TempoMap,
|
||||
current_fps: f64,
|
||||
// Current time signature — updated by SetTempo, used when SetTempoMap fires.
|
||||
time_sig: (u32, u32),
|
||||
}
|
||||
@@ -197,7 +196,6 @@ impl Engine {
|
||||
timing_sum_total_us: 0,
|
||||
timing_overrun_count: 0,
|
||||
tempo_map: crate::TempoMap::constant(120.0),
|
||||
current_fps: 30.0,
|
||||
time_sig: (4, 4),
|
||||
}
|
||||
}
|
||||
@@ -2434,6 +2432,7 @@ impl Engine {
|
||||
channels,
|
||||
sample_rate,
|
||||
total_frames,
|
||||
None, // imported from an external video file; packing happens on save
|
||||
);
|
||||
let pool_index = self.audio_pool.add_file(audio_file);
|
||||
|
||||
|
||||
@@ -164,11 +164,11 @@ impl AudioNode for OscillatorNode {
|
||||
output[frame * 2] = sample; // Left
|
||||
output[frame * 2 + 1] = sample; // Right
|
||||
|
||||
// Update phase once per frame
|
||||
self.phase += freq_mod / sample_rate_f32;
|
||||
if self.phase >= 1.0 {
|
||||
self.phase -= 1.0;
|
||||
}
|
||||
// Update phase once per frame. `rem_euclid(1.0)` gives a numerically stable
|
||||
// wraparound into [0, 1): repeated conditional subtraction accumulates f32
|
||||
// rounding error over long-held notes (timbre drift), and FM can drive
|
||||
// `freq_mod` negative, which a one-sided `if >= 1.0` wouldn't wrap at all.
|
||||
self.phase = (self.phase + freq_mod / sample_rate_f32).rem_euclid(1.0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -244,12 +244,15 @@ impl AudioFile {
|
||||
|
||||
/// Create a placeholder AudioFile for a video's audio track. `path` is the
|
||||
/// source video file; the audio is streamed on demand by the disk reader's
|
||||
/// FFmpeg-backed `VideoAudioReader`.
|
||||
/// FFmpeg-backed `VideoAudioReader`. `packed_media_id` is `Some` when the video
|
||||
/// bytes are packed in the `.beam` container (audio streams from the same blob
|
||||
/// via the host factory); `None` when the audio comes from an external video file.
|
||||
pub fn from_video_audio(
|
||||
path: PathBuf,
|
||||
channels: u32,
|
||||
sample_rate: u32,
|
||||
total_frames: u64,
|
||||
packed_media_id: Option<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
path,
|
||||
@@ -263,7 +266,7 @@ impl AudioFile {
|
||||
frames: total_frames,
|
||||
original_format: None,
|
||||
original_bytes: None,
|
||||
packed_media_id: None,
|
||||
packed_media_id,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -574,6 +577,27 @@ impl AudioClipPool {
|
||||
// Spin-wait with small sleeps until the disk reader fills the buffer
|
||||
let mut wait_iters = 0u64;
|
||||
while !ra.has_range(src_start, frames_needed) {
|
||||
// The source reached EOF and these frames are past the end of the
|
||||
// audio (e.g. a video whose audio track is shorter than the video,
|
||||
// or a container without exact stream duration). They will never
|
||||
// arrive — stop waiting and let the render fill silence, instead of
|
||||
// burning the 10s safety valve on every remaining chunk.
|
||||
//
|
||||
// BUT `finished` may be stale: we just moved the target with
|
||||
// `set_target_frame`, and on a forward jump past the buffer the reader
|
||||
// will reset()+seek() (clearing `finished`) on its next poll. The reader
|
||||
// re-seeks when `target < buf_start || target > buf_end + sample_rate`
|
||||
// (see disk_reader.rs), so only trust EOF when the target is inside the
|
||||
// current window — otherwise a stale flag from the previous region would
|
||||
// make us render silence over audio that's about to be decoded.
|
||||
if ra.is_finished() {
|
||||
let (buf_start, buf_end) = ra.snapshot();
|
||||
let sr = audio_file.sample_rate as u64;
|
||||
let seek_pending = src_start < buf_start || src_start > buf_end + sr;
|
||||
if !seek_pending {
|
||||
break;
|
||||
}
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_micros(100));
|
||||
wait_iters += 1;
|
||||
if wait_iters > 100_000 {
|
||||
@@ -1168,7 +1192,27 @@ impl AudioClipPool {
|
||||
let entry_start = std::time::Instant::now();
|
||||
eprintln!("📊 [LOAD_SERIALIZED] Processing entry {}/{}: '{}'", i + 1, entries.len(), entry.name);
|
||||
|
||||
let success = if entry.is_video_audio {
|
||||
let success = if entry.is_video_audio && entry.media_id.is_some() {
|
||||
// Packed video: the audio track lives in the same container blob as
|
||||
// the video. Build a streaming VideoAudio entry from the saved
|
||||
// metadata (no probe needed); playback opens the blob via the host
|
||||
// factory at clip-activation time → VideoAudioReader::open_source.
|
||||
let media_id = entry.media_id.clone().unwrap();
|
||||
let total_frames = (entry.duration * entry.sample_rate as f64).ceil() as u64;
|
||||
let file = AudioFile::from_video_audio(
|
||||
PathBuf::new(),
|
||||
entry.channels,
|
||||
entry.sample_rate,
|
||||
total_frames,
|
||||
Some(media_id),
|
||||
);
|
||||
if entry.pool_index < self.files.len() {
|
||||
self.files[entry.pool_index] = file;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else if entry.is_video_audio {
|
||||
// Re-probe the video's audio track via FFmpeg → a streaming
|
||||
// VideoAudio entry (keeps full 5.1/7.1; no decode-to-RAM).
|
||||
match entry.relative_path.as_ref() {
|
||||
@@ -1186,6 +1230,7 @@ impl AudioClipPool {
|
||||
reader.channels(),
|
||||
reader.sample_rate(),
|
||||
reader.total_frames(),
|
||||
None,
|
||||
);
|
||||
if entry.pool_index < self.files.len() {
|
||||
self.files[entry.pool_index] = file;
|
||||
|
||||
@@ -41,6 +41,11 @@ impl Project {
|
||||
}
|
||||
}
|
||||
|
||||
/// The project's system sample rate in Hz.
|
||||
pub fn sample_rate(&self) -> u32 {
|
||||
self.sample_rate
|
||||
}
|
||||
|
||||
/// Generate a new unique track ID
|
||||
fn next_id(&mut self) -> TrackId {
|
||||
let id = self.next_track_id;
|
||||
|
||||
@@ -113,11 +113,10 @@ impl SynthVoice {
|
||||
// Simple sine wave
|
||||
let sample = (self.phase * 2.0 * PI).sin() * (self.velocity as f32 / 127.0) * 0.3;
|
||||
|
||||
// Update phase
|
||||
self.phase += self.frequency / sample_rate;
|
||||
if self.phase >= 1.0 {
|
||||
self.phase -= 1.0;
|
||||
}
|
||||
// Update phase. Use `.fract()` for a numerically stable wraparound: repeated
|
||||
// conditional subtraction accumulates f32 rounding error over long-held notes,
|
||||
// which drifts the timbre.
|
||||
self.phase = (self.phase + self.frequency / sample_rate).fract();
|
||||
|
||||
self.age += 1;
|
||||
|
||||
|
||||
@@ -251,3 +251,69 @@ fn seek_is_sample_accurate() {
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
// ── Stage 3: stream video-audio from a byte source (packed .beam blob) ──────────
|
||||
|
||||
/// A `MediaByteSource` over an in-memory buffer (stands in for a SQLite BlobReader).
|
||||
struct VecSource(std::io::Cursor<Vec<u8>>, u64);
|
||||
impl std::io::Read for VecSource {
|
||||
fn read(&mut self, b: &mut [u8]) -> std::io::Result<usize> { self.0.read(b) }
|
||||
}
|
||||
impl std::io::Seek for VecSource {
|
||||
fn seek(&mut self, p: std::io::SeekFrom) -> std::io::Result<u64> { self.0.seek(p) }
|
||||
}
|
||||
impl daw_backend::audio::disk_reader::MediaByteSource for VecSource {
|
||||
fn byte_len(&self) -> u64 { self.1 }
|
||||
}
|
||||
|
||||
fn ramp_wav_bytes(n: u32, sample_rate: u32) -> Vec<u8> {
|
||||
let channels = 1u16;
|
||||
let bps = 4u32;
|
||||
let data_size = n * bps;
|
||||
let mut buf = Vec::with_capacity(44 + data_size as usize);
|
||||
buf.extend_from_slice(b"RIFF");
|
||||
buf.extend_from_slice(&(36 + data_size).to_le_bytes());
|
||||
buf.extend_from_slice(b"WAVE");
|
||||
buf.extend_from_slice(b"fmt ");
|
||||
buf.extend_from_slice(&16u32.to_le_bytes());
|
||||
buf.extend_from_slice(&3u16.to_le_bytes()); // IEEE float
|
||||
buf.extend_from_slice(&channels.to_le_bytes());
|
||||
buf.extend_from_slice(&sample_rate.to_le_bytes());
|
||||
buf.extend_from_slice(&(sample_rate * channels as u32 * bps).to_le_bytes());
|
||||
buf.extend_from_slice(&((channels as u32 * bps) as u16).to_le_bytes());
|
||||
buf.extend_from_slice(&32u16.to_le_bytes());
|
||||
buf.extend_from_slice(b"data");
|
||||
buf.extend_from_slice(&data_size.to_le_bytes());
|
||||
for i in 0..n {
|
||||
buf.extend_from_slice(&((i as f32) / (n as f32)).to_le_bytes());
|
||||
}
|
||||
buf
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn video_audio_open_source_streams_from_bytes() {
|
||||
let sr = 8000;
|
||||
let n = 4000;
|
||||
let bytes = ramp_wav_bytes(n, sr);
|
||||
let len = bytes.len() as u64;
|
||||
let src = Box::new(VecSource(std::io::Cursor::new(bytes), len));
|
||||
|
||||
// Open the audio track by streaming from the byte source (no file path).
|
||||
let mut reader = VideoAudioReader::open_source(src, Some("wav")).unwrap();
|
||||
assert_eq!(reader.channels(), 1);
|
||||
assert_eq!(reader.sample_rate(), sr);
|
||||
|
||||
let mut all: Vec<f32> = Vec::new();
|
||||
let mut buf: Vec<f32> = Vec::new();
|
||||
loop {
|
||||
let frames = reader.decode_next(&mut buf).unwrap();
|
||||
if frames == 0 {
|
||||
break;
|
||||
}
|
||||
all.extend_from_slice(&buf);
|
||||
}
|
||||
assert!(all.len() as u32 >= n - 4, "decoded most of the ramp: {} of {}", all.len(), n);
|
||||
// The ramp rises monotonically; sample 0 ≈ 0.0 and the last is near 1.0.
|
||||
assert!(all[0].abs() < 1e-3, "first sample ~0, got {}", all[0]);
|
||||
assert!(*all.last().unwrap() > 0.9, "last sample ~1.0, got {}", all.last().unwrap());
|
||||
}
|
||||
|
||||
Generated
+287
@@ -0,0 +1,287 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bindgen"
|
||||
version = "0.72.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"cexpr",
|
||||
"clang-sys",
|
||||
"itertools",
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"regex",
|
||||
"rustc-hash",
|
||||
"shlex 1.3.0",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.2.63"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "556e016178bb5662a08681bbe0f00f8e17631781a4dfc8c45e466e4b185ec27f"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex 2.0.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cexpr"
|
||||
version = "0.6.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766"
|
||||
dependencies = [
|
||||
"nom",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
|
||||
[[package]]
|
||||
name = "clang-sys"
|
||||
version = "1.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b023947811758c97c59bf9d1c188fd619ad4718dcaa767947df1cadb14f39f4"
|
||||
dependencies = [
|
||||
"glob",
|
||||
"libc",
|
||||
"libloading",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "either"
|
||||
version = "1.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
|
||||
|
||||
[[package]]
|
||||
name = "ffmpeg-blob-io"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"ffmpeg-next",
|
||||
"ffmpeg-sys-next",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ffmpeg-next"
|
||||
version = "8.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d658424d233cbd993a972dd73a66ca733acd12a494c68995c9ac32ae1fe65b40"
|
||||
dependencies = [
|
||||
"bitflags",
|
||||
"ffmpeg-sys-next",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ffmpeg-sys-next"
|
||||
version = "8.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9bca20aa4ee774fe384c2490096c122b0b23cf524a9910add0686691003d797b"
|
||||
dependencies = [
|
||||
"bindgen",
|
||||
"cc",
|
||||
"libc",
|
||||
"num_cpus",
|
||||
"pkg-config",
|
||||
"vcpkg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
|
||||
|
||||
[[package]]
|
||||
name = "glob"
|
||||
version = "0.3.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
|
||||
|
||||
[[package]]
|
||||
name = "hermit-abi"
|
||||
version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.13.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
|
||||
dependencies = [
|
||||
"either",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.186"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
|
||||
|
||||
[[package]]
|
||||
name = "libloading"
|
||||
version = "0.8.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "memchr"
|
||||
version = "2.8.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8"
|
||||
|
||||
[[package]]
|
||||
name = "minimal-lexical"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
|
||||
|
||||
[[package]]
|
||||
name = "nom"
|
||||
version = "7.1.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
"minimal-lexical",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num_cpus"
|
||||
version = "1.17.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "91df4bbde75afed763b708b7eee1e8e7651e02d97f6d5dd763e89367e957b23b"
|
||||
dependencies = [
|
||||
"hermit-abi",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.33"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"
|
||||
|
||||
[[package]]
|
||||
name = "proc-macro2"
|
||||
version = "1.0.106"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
|
||||
dependencies = [
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quote"
|
||||
version = "1.0.45"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex"
|
||||
version = "1.12.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-automata",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-automata"
|
||||
version = "0.4.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
|
||||
dependencies = [
|
||||
"aho-corasick",
|
||||
"memchr",
|
||||
"regex-syntax",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "regex-syntax"
|
||||
version = "0.8.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "2.1.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "1.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "syn"
|
||||
version = "2.0.117"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"unicode-ident",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.24"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
||||
|
||||
[[package]]
|
||||
name = "vcpkg"
|
||||
version = "0.2.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||
@@ -0,0 +1,22 @@
|
||||
# Standalone crate (own workspace root) — depended on by daw-backend and
|
||||
# lightningbeam-core via relative path, like daw-backend itself.
|
||||
[workspace]
|
||||
|
||||
[package]
|
||||
name = "ffmpeg-blob-io"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "Custom AVIOContext-over-Read+Seek shim for ffmpeg-next: lets a demuxer stream from an arbitrary byte source (e.g. a SQLite blob) instead of a file path. Isolates the unsafe FFI + ffmpeg ABI coupling."
|
||||
|
||||
# ABI-PINNED. This crate dereferences raw AVFormatContext / AVIOContext fields
|
||||
# (`pb`, `flags`, `buffer`, `opaque`) and wraps the result back into ffmpeg-next's
|
||||
# `Input`, so it MUST link the exact same libavformat ABI as the rest of the
|
||||
# workspace. The `=` pins match what lightningbeam-core / daw-backend resolve;
|
||||
# bump all three together when upgrading ffmpeg.
|
||||
[dependencies]
|
||||
ffmpeg-next = "=8.0.0"
|
||||
ffmpeg-sys-next = "=8.0.1"
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
ffmpeg-next = "=8.0.0"
|
||||
@@ -0,0 +1,240 @@
|
||||
//! Stream a demuxer from an arbitrary `Read + Seek` byte source via a custom
|
||||
//! FFmpeg `AVIOContext`.
|
||||
//!
|
||||
//! `ffmpeg-next`'s high-level API can only open inputs by filesystem path. This
|
||||
//! crate builds an `AVFormatContext` whose I/O is backed by a Rust reader (e.g. a
|
||||
//! SQLite `BlobReader`), then hands back a normal [`ffmpeg_next::format::context::Input`]
|
||||
//! that the rest of the codebase decodes exactly as a file-backed input.
|
||||
//!
|
||||
//! All of the `unsafe` FFI and ffmpeg ABI coupling lives here, isolated behind the
|
||||
//! safe [`BlobInput`] type. See `BEAM_FILE_FORMAT.md` / `STREAMING_TO_DISK_PLAN.md`.
|
||||
//!
|
||||
//! # Safety model
|
||||
//! - The reader is boxed and leaked to FFmpeg as the AVIO `opaque` pointer; the
|
||||
//! read/seek callbacks reconstitute it as `&mut`. It is never aliased — only the
|
||||
//! owning [`BlobInput`] (on one thread) drives it.
|
||||
//! - [`BlobInput`] is `Send` but **not** `Sync`: the typical reader (`BlobReader`)
|
||||
//! owns a `!Sync` SQLite connection. Each decoder / seek-reopen / off-thread scan
|
||||
//! must construct its **own** `BlobInput` from a **fresh** reader.
|
||||
//! - `Drop` tears down in the one correct order (Input first, then the AVIO buffer +
|
||||
//! context, then the reader) so there is no use-after-free, double-free, or leak.
|
||||
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
use std::os::raw::{c_char, c_int, c_void};
|
||||
use std::ptr;
|
||||
|
||||
use ffmpeg_next::format::context::Input;
|
||||
use ffmpeg_sys_next as sys;
|
||||
|
||||
/// A byte source FFmpeg can stream from. Blanket-implemented for any
|
||||
/// `Read + Seek + Send` (e.g. `std::io::Cursor`, a SQLite `BlobReader`).
|
||||
pub trait BlobSource: Read + Seek + Send {}
|
||||
impl<T: Read + Seek + Send> BlobSource for T {}
|
||||
|
||||
// Stable FFmpeg ABI constants (avoid depending on whether bindgen exported the
|
||||
// corresponding `#define`s). These are fixed across the libavformat 58–61 ABIs.
|
||||
const AVSEEK_SIZE: c_int = 0x10000;
|
||||
const AVSEEK_FORCE: c_int = 0x20000;
|
||||
const AVFMT_FLAG_CUSTOM_IO: c_int = 0x0080;
|
||||
|
||||
/// Size of the AVIO read buffer handed to FFmpeg. FFmpeg may grow/replace it.
|
||||
const IO_BUFFER_SIZE: usize = 32 * 1024;
|
||||
|
||||
/// A demuxer input streaming from a boxed `Read + Seek` source.
|
||||
///
|
||||
/// Deref to [`Input`] for the usual ffmpeg-next decode API.
|
||||
pub struct BlobInput {
|
||||
// Dropped FIRST in `Drop` (avformat_close_input). `Option` so we can drop it
|
||||
// explicitly before freeing the AVIO resources it points at.
|
||||
input: Option<Input>,
|
||||
// The custom AVIOContext. With AVFMT_FLAG_CUSTOM_IO set, avformat_close_input
|
||||
// does NOT free this — we own it. Its `opaque` field is the boxed reader.
|
||||
avio: *mut sys::AVIOContext,
|
||||
}
|
||||
|
||||
// The reader is `Send` and never aliased; we manage its lifetime manually.
|
||||
unsafe impl Send for BlobInput {}
|
||||
// Intentionally NOT `Sync`: see the module-level safety notes.
|
||||
|
||||
impl BlobInput {
|
||||
/// Open a demuxer over `src`.
|
||||
///
|
||||
/// `format_hint` is an optional container short-name / extension (e.g. `"mp4"`,
|
||||
/// `"mov"`, `"matroska"`) passed to `av_find_input_format` to skip probe
|
||||
/// ambiguity; `None` lets FFmpeg probe from the stream.
|
||||
pub fn open(src: Box<dyn BlobSource>, format_hint: Option<&str>) -> Result<Self, String> {
|
||||
ffmpeg_next::init().map_err(|e| format!("ffmpeg init failed: {e}"))?;
|
||||
|
||||
unsafe {
|
||||
// 1. IO buffer, allocated with FFmpeg's allocator (freed with av_freep).
|
||||
let buffer = sys::av_malloc(IO_BUFFER_SIZE) as *mut u8;
|
||||
if buffer.is_null() {
|
||||
return Err("av_malloc failed for AVIO buffer".into());
|
||||
}
|
||||
|
||||
// 2. Box the reader and leak it as the opaque pointer. Double-box so the
|
||||
// raw pointer is thin (a `*mut dyn` would be a fat pointer).
|
||||
let opaque = Box::into_raw(Box::new(src)) as *mut c_void;
|
||||
|
||||
// 3. AVIOContext over our callbacks (read-only: write_flag = 0).
|
||||
let avio = sys::avio_alloc_context(
|
||||
buffer,
|
||||
IO_BUFFER_SIZE as c_int,
|
||||
0,
|
||||
opaque,
|
||||
Some(read_cb),
|
||||
None,
|
||||
Some(seek_cb),
|
||||
);
|
||||
if avio.is_null() {
|
||||
sys::av_free(buffer as *mut c_void);
|
||||
drop(Box::from_raw(opaque as *mut Box<dyn BlobSource>));
|
||||
return Err("avio_alloc_context failed".into());
|
||||
}
|
||||
|
||||
// 4. Format context wired to the custom IO.
|
||||
let mut fmt = sys::avformat_alloc_context();
|
||||
if fmt.is_null() {
|
||||
destroy_io(avio);
|
||||
return Err("avformat_alloc_context failed".into());
|
||||
}
|
||||
(*fmt).pb = avio;
|
||||
(*fmt).flags |= AVFMT_FLAG_CUSTOM_IO;
|
||||
|
||||
// 5. Optional format hint.
|
||||
let hint_cstr = format_hint.and_then(|s| std::ffi::CString::new(s).ok());
|
||||
let infmt: *const sys::AVInputFormat = match &hint_cstr {
|
||||
Some(c) => sys::av_find_input_format(c.as_ptr() as *const c_char),
|
||||
None => ptr::null(),
|
||||
};
|
||||
|
||||
// 6. Open. On failure avformat_open_input frees `fmt` itself (and, with
|
||||
// CUSTOM_IO, leaves our pb), so we still own avio+buffer+reader.
|
||||
let ret = sys::avformat_open_input(&mut fmt, ptr::null(), infmt, ptr::null_mut());
|
||||
if ret < 0 {
|
||||
destroy_io(avio);
|
||||
return Err(format!("avformat_open_input failed (error {ret})"));
|
||||
}
|
||||
|
||||
// 7. Probe streams. On failure close the now-open input, then free IO.
|
||||
let ret = sys::avformat_find_stream_info(fmt, ptr::null_mut());
|
||||
if ret < 0 {
|
||||
sys::avformat_close_input(&mut fmt);
|
||||
destroy_io(avio);
|
||||
return Err(format!("avformat_find_stream_info failed (error {ret})"));
|
||||
}
|
||||
|
||||
// 8. Hand ownership of `fmt` to ffmpeg-next's Input (closes on drop).
|
||||
let input = Input::wrap(fmt);
|
||||
Ok(BlobInput { input: Some(input), avio })
|
||||
}
|
||||
}
|
||||
|
||||
/// The underlying demuxer input.
|
||||
pub fn input(&self) -> &Input {
|
||||
self.input.as_ref().expect("BlobInput input present until drop")
|
||||
}
|
||||
|
||||
/// The underlying demuxer input, mutably (for `seek`, `packets`, …).
|
||||
pub fn input_mut(&mut self) -> &mut Input {
|
||||
self.input.as_mut().expect("BlobInput input present until drop")
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for BlobInput {
|
||||
type Target = Input;
|
||||
fn deref(&self) -> &Input {
|
||||
self.input()
|
||||
}
|
||||
}
|
||||
impl std::ops::DerefMut for BlobInput {
|
||||
fn deref_mut(&mut self) -> &mut Input {
|
||||
self.input_mut()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for BlobInput {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
// 1. Drop the Input first: avformat_close_input. With CUSTOM_IO this does
|
||||
// NOT touch self.avio or its buffer.
|
||||
self.input = None;
|
||||
// 2..4. Free the AVIO buffer + context and reclaim the boxed reader.
|
||||
if !self.avio.is_null() {
|
||||
destroy_io(self.avio);
|
||||
self.avio = ptr::null_mut();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Free a standalone custom AVIOContext: its (possibly reallocated) buffer, the
|
||||
/// boxed reader behind `opaque`, then the context itself — in that order. Only
|
||||
/// call when the owning AVFormatContext has already been closed (or never opened).
|
||||
unsafe fn destroy_io(avio: *mut sys::AVIOContext) {
|
||||
if avio.is_null() {
|
||||
return;
|
||||
}
|
||||
// Reclaim the reader box *before* freeing the context (we need `opaque`).
|
||||
let opaque = (*avio).opaque;
|
||||
// Free the current IO buffer (FFmpeg may have replaced the original).
|
||||
sys::av_freep(&mut (*avio).buffer as *mut _ as *mut c_void);
|
||||
// Free the AVIOContext struct (nulls the local).
|
||||
let mut avio = avio;
|
||||
sys::avio_context_free(&mut avio);
|
||||
// Drop the reader last — no callback can fire now.
|
||||
if !opaque.is_null() {
|
||||
drop(Box::from_raw(opaque as *mut Box<dyn BlobSource>));
|
||||
}
|
||||
}
|
||||
|
||||
/// FFmpeg read callback: fill `buf` from the Rust reader. Returns bytes read,
|
||||
/// `AVERROR_EOF` at end of stream, or a negative error.
|
||||
unsafe extern "C" fn read_cb(opaque: *mut c_void, buf: *mut u8, buf_size: c_int) -> c_int {
|
||||
if opaque.is_null() || buf.is_null() || buf_size <= 0 {
|
||||
return sys::AVERROR_EOF;
|
||||
}
|
||||
let reader = &mut *(opaque as *mut Box<dyn BlobSource>);
|
||||
let slice = std::slice::from_raw_parts_mut(buf, buf_size as usize);
|
||||
match reader.read(slice) {
|
||||
Ok(0) => sys::AVERROR_EOF,
|
||||
Ok(n) => n as c_int,
|
||||
// AVERROR(EIO) == -EIO on Unix; a negative value signals a read error.
|
||||
Err(_) => -(libc::EIO as c_int),
|
||||
}
|
||||
}
|
||||
|
||||
/// FFmpeg seek callback. Handles `SEEK_SET/CUR/END` and `AVSEEK_SIZE` (report total
|
||||
/// length). Returns the new position, the size, or `-1` on error.
|
||||
unsafe extern "C" fn seek_cb(opaque: *mut c_void, offset: i64, whence: c_int) -> i64 {
|
||||
if opaque.is_null() {
|
||||
return -1;
|
||||
}
|
||||
let reader = &mut *(opaque as *mut Box<dyn BlobSource>);
|
||||
let whence = whence & !AVSEEK_FORCE;
|
||||
if whence & AVSEEK_SIZE != 0 {
|
||||
// Report total length WITHOUT moving the logical position. FFmpeg does not
|
||||
// restore the position after an AVSEEK_SIZE query, so we must: measure by
|
||||
// seeking to the end, then seek back. (Failing to restore corrupts reads of
|
||||
// containers whose index lives at the end of the file, e.g. MP4 `moov`.)
|
||||
let cur = match reader.stream_position() {
|
||||
Ok(p) => p,
|
||||
Err(_) => return -1,
|
||||
};
|
||||
let size = match reader.seek(SeekFrom::End(0)) {
|
||||
Ok(s) => s,
|
||||
Err(_) => return -1,
|
||||
};
|
||||
if reader.seek(SeekFrom::Start(cur)).is_err() {
|
||||
return -1;
|
||||
}
|
||||
return size as i64;
|
||||
}
|
||||
let from = match whence {
|
||||
libc::SEEK_SET => SeekFrom::Start(offset as u64),
|
||||
libc::SEEK_CUR => SeekFrom::Current(offset),
|
||||
libc::SEEK_END => SeekFrom::End(offset),
|
||||
_ => return -1,
|
||||
};
|
||||
reader.seek(from).map(|n| n as i64).unwrap_or(-1)
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//! Exercises the custom AVIO shim end to end against a hand-built WAV, fed through
|
||||
//! an in-memory `Cursor` (a `Read + Seek` source). FFmpeg can only demux it by
|
||||
//! calling our `read_cb`/`seek_cb`, so a successful open proves the shim works.
|
||||
|
||||
use ffmpeg_blob_io::BlobInput;
|
||||
use std::io::Cursor;
|
||||
|
||||
/// Build a minimal 16-bit PCM WAV in memory.
|
||||
fn make_wav(sample_rate: u32, channels: u16, samples: &[i16]) -> Vec<u8> {
|
||||
let bits: u16 = 16;
|
||||
let block_align: u16 = channels * (bits / 8);
|
||||
let byte_rate: u32 = sample_rate * block_align as u32;
|
||||
let data_len: u32 = (samples.len() * 2) as u32;
|
||||
|
||||
let mut v = Vec::new();
|
||||
v.extend_from_slice(b"RIFF");
|
||||
v.extend_from_slice(&(36 + data_len).to_le_bytes());
|
||||
v.extend_from_slice(b"WAVE");
|
||||
v.extend_from_slice(b"fmt ");
|
||||
v.extend_from_slice(&16u32.to_le_bytes()); // fmt chunk size
|
||||
v.extend_from_slice(&1u16.to_le_bytes()); // PCM
|
||||
v.extend_from_slice(&channels.to_le_bytes());
|
||||
v.extend_from_slice(&sample_rate.to_le_bytes());
|
||||
v.extend_from_slice(&byte_rate.to_le_bytes());
|
||||
v.extend_from_slice(&block_align.to_le_bytes());
|
||||
v.extend_from_slice(&bits.to_le_bytes());
|
||||
v.extend_from_slice(b"data");
|
||||
v.extend_from_slice(&data_len.to_le_bytes());
|
||||
for s in samples {
|
||||
v.extend_from_slice(&s.to_le_bytes());
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn sample_wav() -> Vec<u8> {
|
||||
let samples: Vec<i16> = (0..1600).map(|i| ((i % 100) as i16 - 50) * 200).collect();
|
||||
make_wav(8000, 1, &samples)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opens_from_reader_and_reports_stream() {
|
||||
let input = BlobInput::open(Box::new(Cursor::new(sample_wav())), Some("wav"))
|
||||
.expect("open WAV through the blob shim");
|
||||
|
||||
let stream = input
|
||||
.streams()
|
||||
.best(ffmpeg_next::media::Type::Audio)
|
||||
.expect("an audio stream");
|
||||
let ctx = ffmpeg_next::codec::context::Context::from_parameters(stream.parameters())
|
||||
.expect("codec context");
|
||||
let decoder = ctx.decoder().audio().expect("audio decoder");
|
||||
|
||||
assert_eq!(decoder.rate(), 8000, "sample rate read via AVIO");
|
||||
assert_eq!(decoder.channels(), 1, "channel count read via AVIO");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_packets_through_callbacks() {
|
||||
let mut input = BlobInput::open(Box::new(Cursor::new(sample_wav())), Some("wav"))
|
||||
.expect("open WAV");
|
||||
let mut packets = 0usize;
|
||||
let mut bytes = 0usize;
|
||||
for (_stream, packet) in input.packets() {
|
||||
packets += 1;
|
||||
bytes += packet.size();
|
||||
}
|
||||
assert!(packets > 0, "demuxer produced packets via read_cb");
|
||||
assert!(bytes > 0, "packets carried PCM payload");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seek_then_read() {
|
||||
let mut input = BlobInput::open(Box::new(Cursor::new(sample_wav())), Some("wav"))
|
||||
.expect("open WAV");
|
||||
// Seek back to the start (exercises seek_cb SEEK_SET + AVSEEK_SIZE).
|
||||
input.seek(0, ..).expect("seek to start");
|
||||
let got_packet = input.packets().next().is_some();
|
||||
assert!(got_packet, "can still read after seek");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_drop_loop_is_clean() {
|
||||
// Repeated open+drop surfaces double-free / leak in the Drop teardown
|
||||
// (run under `RUSTFLAGS=-Zsanitizer=address` on nightly for full coverage).
|
||||
for _ in 0..200 {
|
||||
let input = BlobInput::open(Box::new(Cursor::new(sample_wav())), Some("wav"))
|
||||
.expect("open WAV");
|
||||
assert!(input.streams().count() >= 1);
|
||||
drop(input);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_format_hint_errors_without_leak() {
|
||||
// Garbage bytes with a real hint: open should fail cleanly (error path frees
|
||||
// buffer + avio + reader), not panic or leak.
|
||||
let garbage = vec![0u8; 4096];
|
||||
let res = BlobInput::open(Box::new(Cursor::new(garbage)), Some("wav"));
|
||||
assert!(res.is_err(), "non-WAV bytes should fail to open as WAV");
|
||||
}
|
||||
@@ -15,3 +15,8 @@
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Local, machine-specific cargo config (e.g. PKG_CONFIG_PATH for a local ffmpeg).
|
||||
# CI/packaging build ffmpeg from source (see .github/workflows/build.yml), so this
|
||||
# must never leak into a commit.
|
||||
.cargo/config.toml
|
||||
|
||||
Generated
+437
-147
File diff suppressed because it is too large
Load Diff
@@ -4,6 +4,7 @@ members = [
|
||||
"lightningbeam-editor",
|
||||
"lightningbeam-core",
|
||||
"beamdsp",
|
||||
"gpu-video-encoder",
|
||||
]
|
||||
|
||||
[workspace.dependencies]
|
||||
@@ -23,6 +24,11 @@ vello = { git = "https://github.com/linebender/vello", branch = "main" }
|
||||
wgpu = { version = "27", features = ["vulkan", "metal", "gles"] }
|
||||
kurbo = { version = "0.12", features = ["serde"] }
|
||||
peniko = "0.5"
|
||||
# Text layout/shaping for text layers. Pinned to git main to match the peniko 0.5
|
||||
# / skrifa 0.37 that vello's git-main resolves to — a released parley still pins
|
||||
# peniko 0.4, which would split `peniko::Font` into two incompatible types at the
|
||||
# vello `draw_glyphs` boundary.
|
||||
parley = { git = "https://github.com/linebender/parley", branch = "main" }
|
||||
|
||||
# Windowing
|
||||
winit = "0.30"
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
# GPU-resident video decode + dynamic decode resolution
|
||||
|
||||
## Context
|
||||
|
||||
Profiling the zero-copy H.264 export (single Group[Video, Audio] clip, `LB_RENDER_PROFILE=1`)
|
||||
broke the per-frame CPU "render" bucket down as:
|
||||
|
||||
| Cost (ms/frame) | 1080p | 4K | What it is |
|
||||
|-------------------------|-------|-------|-----------------------------------------------------|
|
||||
| decode | 3.1 | 19.0 | software ffmpeg decode (`video.rs::get_frame`) |
|
||||
| background re-render | 3.6 | 7.5 | static background pushed through Vello *every frame* |
|
||||
| video upload + blit | 4.1 | 4.2 | per-frame transient texture alloc + `write_texture` |
|
||||
| srgb | 0.4 | 0.4 | linear→sRGB pass |
|
||||
|
||||
The video correctly takes the GPU Video-instance path (not Vello-baked) — `LB_LAYER_DEBUG=1`
|
||||
shows `Video (1 instance)`. So the cost is **the video frame itself**: software decode, then an
|
||||
8 MB `write_texture` upload of the decoded RGBA every frame. At 4K, software decode (19 ms)
|
||||
dominates everything.
|
||||
|
||||
### Two correctness problems found alongside the perf issue
|
||||
|
||||
1. **Decode resolution is frozen to document size at import.** `load_video(clip, src, doc_w, doc_h)`
|
||||
(`main.rs:4302`) sizes the decoder's swscale output to the document, capped to never upscale
|
||||
(`video.rs:149`). Export *reuses that decoder*, so exporting **above** document resolution yields
|
||||
video that was decoded to ≤document res and then GPU-**up**scaled — real source detail thrown away.
|
||||
2. **It can't follow the consumer or a document resize.** Preview wants small/fast frames; export
|
||||
wants full res; changing the document size should re-target the decode. None of that works with a
|
||||
size frozen at import.
|
||||
|
||||
## Goal
|
||||
|
||||
Decouple **decode resolution** from import/document size: the renderer requests a frame *at a target
|
||||
resolution*, and the decode path produces it. Hardware-decode H.264 (and later HEVC/AV1) into a GPU
|
||||
surface and keep it GPU-resident through composite into the encoder — no CPU frame copy in either
|
||||
direction. Software decode stays a **first-class** path (codecs/platforms without HW support), decoding
|
||||
at the requested target res. This fixes the 4K decode wall, the 8 MB upload, *and* the resolution bugs.
|
||||
|
||||
## Design principles
|
||||
|
||||
- **Decode native, scale to the consumer's target.**
|
||||
- *Hardware path:* decode into a native VAAPI surface → import as a wgpu texture (reuse the
|
||||
`gpu-video-encoder` `dmabuf.rs` / `vk_device.rs` plumbing, read direction) → the GPU blit that
|
||||
already composites the Video instance scales native→target for free. Handles any target res and
|
||||
document resizes inherently; the cached frame is a native GPU texture.
|
||||
- *Software path:* decode native → `swscale` to the requested target (the reusable scaler is keyed
|
||||
on input format/size **and** output size — rebuilt when the target changes). Preview requests
|
||||
preview res (cheap); export requests export res (full quality).
|
||||
- **`VideoManager::get_frame` takes a target `(w, h)`** instead of relying on a frozen output size.
|
||||
The frame cache is keyed to handle multiple live targets (preview + export) — either cache native
|
||||
frames and scale on demand, or key by `(clip, ts, target)`; decide in Stage 2 by measuring cache
|
||||
hit/scale tradeoff.
|
||||
- **Software is not optional.** Hardware decode is an acceleration of the same `get_frame` contract,
|
||||
selected per source when the codec/driver supports it; everything falls back to software cleanly.
|
||||
|
||||
## Approach (staged; each stage compiles + is independently useful)
|
||||
|
||||
### Stage 0 — independent quick wins (not blocked on decode)
|
||||
- **Cache the static background** (`composite_document_to_hdr`): render once, reuse via a persistent
|
||||
HDR texture (copy-in each frame) instead of a full Vello render + 2 passes/submits every frame.
|
||||
Recovers ~3.6 ms (1080p) / ~7.5 ms (4K) per frame on *every* export. (In flight.)
|
||||
|
||||
### Stage 1 — software: decode at the requested target res (testable; fixes the quality bug now)
|
||||
- Change `VideoManager::get_frame(clip, ts)` → `get_frame(clip, ts, target_w, target_h)`; thread the
|
||||
target from the renderer (preview = current doc/preview res, export = export res). Cap at native.
|
||||
- Rework `VideoDecoder` so output size is per-request, not frozen at construction; cache the swscale
|
||||
context per output size (already cached per stream — extend the key). Adjust the frame cache key.
|
||||
- Result: software exports are full-quality at any export res, and document resizes re-target decode.
|
||||
No hardware needed; this is the correctness fix for the codecs HW can't handle anyway.
|
||||
|
||||
### Stage 2 — hardware decode primitive (headless-testable here, like the 8 encode tests)
|
||||
- In `gpu-video-encoder` (rename → `gpu-video-codec`): `h264_vaapi`-style **decode** → VAAPI surface →
|
||||
export DMA-BUF → import as a wgpu texture. Hardware test: decode a known file, verify dims/contents.
|
||||
|
||||
### Stage 3 — wire hardware decode into `get_frame` (blind; user-verifies)
|
||||
- When the source codec/driver is HW-decodable, `get_frame` returns a **GPU texture** (native res)
|
||||
instead of `Arc<Vec<u8>>`; the compositor uses it directly (no `write_texture`), GPU-scaling to the
|
||||
target. For the zero-copy export the frame never leaves the GPU: **decode → composite → encode** on
|
||||
one device. Software path is the fallback for everything else.
|
||||
|
||||
## Critical files
|
||||
- `lightningbeam-core/src/video.rs` — `VideoDecoder` (per-request output size, scaler cache),
|
||||
`VideoManager::get_frame` (target param, cache key).
|
||||
- `lightningbeam-core/src/renderer.rs` — pass the render target res into the video-instance build.
|
||||
- `lightningbeam-editor/src/export/video_exporter.rs` — background cache (Stage 0); consume a GPU
|
||||
texture instead of uploading RGBA (Stage 3).
|
||||
- `gpu-video-encoder/` (→ `gpu-video-codec`) — `dmabuf.rs`/`vk_device.rs` reused for the decode import.
|
||||
|
||||
## Risks
|
||||
- **Codec coverage** — only some codecs are HW-decodable per GPU/driver; software must stay correct
|
||||
and well-tested. Selection must probe support per source, not assume.
|
||||
- **Cache memory** — native-res GPU textures (esp. 4K) are large; the frame cache budget needs revisiting.
|
||||
- **Colorspace/format** — VAAPI decode surfaces are NV12/tiled; the existing import handles NV12, but
|
||||
10-bit/HDR sources (P010) need format handling.
|
||||
- **Preview vs export sharing** — two live targets (preview res + export res) from the same source; the
|
||||
cache/scaler design must serve both without thrashing.
|
||||
|
||||
## Verification
|
||||
- Stage 0/1: visual — export above document res is now full-quality (not upscaled); profile shows
|
||||
background ≈ 0 and (Stage 1) software export correct at the chosen res.
|
||||
- Stage 2: headless hardware test in `gpu-video-codec` (decode → wgpu texture, ffprobe/byte checks).
|
||||
- Stage 3 (user): 1080p + 4K H.264 export — decode/upload buckets collapse; software fallback for a
|
||||
non-HW codec (e.g. ProRes) still produces correct full-res output.
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "gpu-video-encoder"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
description = "Zero-copy GPU video encoding (RGBA->NV12 compute + hardware encoder interop). Unsafe FFI isolated here."
|
||||
|
||||
[dependencies]
|
||||
wgpu = { workspace = true }
|
||||
# Raw Vulkan access for the DMA-BUF import. Versions MUST match what wgpu links
|
||||
# (wgpu-hal 27.0.4 / ash 0.38) so the hal/ash types unify across the boundary.
|
||||
wgpu-hal = { version = "27", features = ["vulkan"] }
|
||||
wgpu-types = "27"
|
||||
ash = "0.38"
|
||||
# Raw FFmpeg FFI for VAAPI hwcontext + hardware encode. Matches the editor's
|
||||
# ffmpeg-next 8.0 / static link so cargo unifies to one libav* across the build.
|
||||
ffmpeg-sys-next = { version = "8.0", features = ["static"] }
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
pollster = "0.4"
|
||||
@@ -0,0 +1,217 @@
|
||||
//! VAAPI hardware video decode → wgpu textures. The mirror of [`crate::encoder`]: the codec
|
||||
//! decodes into a VAAPI NV12 surface, which is mapped to a DRM-PRIME DMA-BUF and imported as two
|
||||
//! wgpu plane textures via [`crate::dmabuf::import_raw`] — the exact same path the encoder uses,
|
||||
//! in the read direction. Stays GPU-resident: no CPU frame copy.
|
||||
|
||||
use crate::dmabuf::{self, ImportedNv12, Nv12DmaBuf};
|
||||
use crate::vk_device::{self, DrmDevice};
|
||||
use ffmpeg_sys_next as ff;
|
||||
use std::ffi::CString;
|
||||
use std::path::Path;
|
||||
use std::ptr;
|
||||
|
||||
#[inline]
|
||||
fn averror(e: i32) -> i32 {
|
||||
-e
|
||||
}
|
||||
|
||||
/// `get_format` callback: pick VAAPI surfaces so the decoder outputs hardware frames. With
|
||||
/// `hw_device_ctx` set, FFmpeg auto-allocates the matching frames context.
|
||||
unsafe extern "C" fn get_vaapi_format(
|
||||
_ctx: *mut ff::AVCodecContext,
|
||||
mut fmts: *const ff::AVPixelFormat,
|
||||
) -> ff::AVPixelFormat {
|
||||
while *fmts != ff::AVPixelFormat::AV_PIX_FMT_NONE {
|
||||
if *fmts == ff::AVPixelFormat::AV_PIX_FMT_VAAPI {
|
||||
return ff::AVPixelFormat::AV_PIX_FMT_VAAPI;
|
||||
}
|
||||
fmts = fmts.add(1);
|
||||
}
|
||||
ff::AVPixelFormat::AV_PIX_FMT_NONE
|
||||
}
|
||||
|
||||
/// Hardware decoder for a single video file/stream. Frames come back as importable NV12 textures
|
||||
/// on [`Self::device`].
|
||||
pub struct VaapiDecoder {
|
||||
drm: DrmDevice,
|
||||
hw_device: *mut ff::AVBufferRef,
|
||||
fmt: *mut ff::AVFormatContext,
|
||||
dec: *mut ff::AVCodecContext,
|
||||
pkt: *mut ff::AVPacket,
|
||||
frame: *mut ff::AVFrame,
|
||||
stream_index: i32,
|
||||
flushing: bool,
|
||||
}
|
||||
|
||||
// Owns its FFmpeg/Vulkan handles exclusively; only moved, never shared (same as the encoder).
|
||||
unsafe impl Send for VaapiDecoder {}
|
||||
|
||||
impl VaapiDecoder {
|
||||
/// Open `input_path` and set up VAAPI hardware decoding of its best video stream.
|
||||
pub fn new(input_path: &Path) -> Result<Self, String> {
|
||||
let drm = vk_device::create()?;
|
||||
unsafe {
|
||||
let mut hw_device = crate::vaapi::create_device()?;
|
||||
let cleanup_hw = |hw: *mut ff::AVBufferRef| {
|
||||
let mut h = hw;
|
||||
ff::av_buffer_unref(&mut h);
|
||||
};
|
||||
|
||||
let path_c = CString::new(input_path.to_string_lossy().as_ref()).unwrap();
|
||||
let mut fmt: *mut ff::AVFormatContext = ptr::null_mut();
|
||||
if ff::avformat_open_input(&mut fmt, path_c.as_ptr(), ptr::null_mut(), ptr::null_mut()) < 0 {
|
||||
cleanup_hw(hw_device);
|
||||
return Err(format!("avformat_open_input {input_path:?} failed"));
|
||||
}
|
||||
if ff::avformat_find_stream_info(fmt, ptr::null_mut()) < 0 {
|
||||
ff::avformat_close_input(&mut fmt);
|
||||
cleanup_hw(hw_device);
|
||||
return Err("avformat_find_stream_info failed".into());
|
||||
}
|
||||
|
||||
let mut decoder: *const ff::AVCodec = ptr::null();
|
||||
let stream_index = ff::av_find_best_stream(
|
||||
fmt,
|
||||
ff::AVMediaType::AVMEDIA_TYPE_VIDEO,
|
||||
-1,
|
||||
-1,
|
||||
&mut decoder,
|
||||
0,
|
||||
);
|
||||
if stream_index < 0 || decoder.is_null() {
|
||||
ff::avformat_close_input(&mut fmt);
|
||||
cleanup_hw(hw_device);
|
||||
return Err("no decodable video stream".into());
|
||||
}
|
||||
|
||||
let dec = ff::avcodec_alloc_context3(decoder);
|
||||
let stream = *(*fmt).streams.add(stream_index as usize);
|
||||
if ff::avcodec_parameters_to_context(dec, (*stream).codecpar) < 0 {
|
||||
ff::avcodec_free_context(&mut (dec as *mut _));
|
||||
ff::avformat_close_input(&mut fmt);
|
||||
cleanup_hw(hw_device);
|
||||
return Err("avcodec_parameters_to_context failed".into());
|
||||
}
|
||||
(*dec).hw_device_ctx = ff::av_buffer_ref(hw_device);
|
||||
(*dec).get_format = Some(get_vaapi_format);
|
||||
|
||||
if ff::avcodec_open2(dec, decoder, ptr::null_mut()) < 0 {
|
||||
ff::avcodec_free_context(&mut (dec as *mut _));
|
||||
ff::avformat_close_input(&mut fmt);
|
||||
cleanup_hw(hw_device);
|
||||
return Err("avcodec_open2 (vaapi decode) failed".into());
|
||||
}
|
||||
|
||||
// `mut` only to satisfy the move into the struct; the binding above is consumed.
|
||||
let _ = &mut hw_device;
|
||||
Ok(Self {
|
||||
drm,
|
||||
hw_device,
|
||||
fmt,
|
||||
dec,
|
||||
pkt: ff::av_packet_alloc(),
|
||||
frame: ff::av_frame_alloc(),
|
||||
stream_index,
|
||||
flushing: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The wgpu device the decoded textures live on (the DMA-BUF-import device).
|
||||
pub fn device(&self) -> &wgpu::Device {
|
||||
&self.drm.device
|
||||
}
|
||||
pub fn queue(&self) -> &wgpu::Queue {
|
||||
&self.drm.queue
|
||||
}
|
||||
|
||||
/// Decode the next frame and import it as NV12 plane textures, or `Ok(None)` at end of stream.
|
||||
pub fn next_frame(&mut self) -> Result<Option<ImportedNv12>, String> {
|
||||
unsafe {
|
||||
loop {
|
||||
let r = ff::avcodec_receive_frame(self.dec, self.frame);
|
||||
if r == 0 {
|
||||
let imported = self.map_current();
|
||||
ff::av_frame_unref(self.frame);
|
||||
return imported.map(Some);
|
||||
}
|
||||
if r == ff::AVERROR_EOF {
|
||||
return Ok(None);
|
||||
}
|
||||
if r != averror(libc::EAGAIN) {
|
||||
return Err(format!("avcodec_receive_frame failed: {r}"));
|
||||
}
|
||||
if self.flushing {
|
||||
return Ok(None); // already drained the flush
|
||||
}
|
||||
|
||||
// Decoder wants more input: pump one packet (or signal EOF to flush).
|
||||
let rp = ff::av_read_frame(self.fmt, self.pkt);
|
||||
if rp < 0 {
|
||||
self.flushing = true;
|
||||
ff::avcodec_send_packet(self.dec, ptr::null());
|
||||
continue;
|
||||
}
|
||||
if (*self.pkt).stream_index == self.stream_index {
|
||||
let rs = ff::avcodec_send_packet(self.dec, self.pkt);
|
||||
ff::av_packet_unref(self.pkt);
|
||||
if rs < 0 && rs != averror(libc::EAGAIN) {
|
||||
return Err(format!("avcodec_send_packet failed: {rs}"));
|
||||
}
|
||||
} else {
|
||||
ff::av_packet_unref(self.pkt);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Map the just-decoded VAAPI surface (`self.frame`) to a DRM-PRIME DMA-BUF and import it.
|
||||
unsafe fn map_current(&self) -> Result<ImportedNv12, String> {
|
||||
let drm_f = ff::av_frame_alloc();
|
||||
(*drm_f).format = ff::AVPixelFormat::AV_PIX_FMT_DRM_PRIME as i32;
|
||||
let flags = ff::AV_HWFRAME_MAP_DIRECT as i32 | ff::AV_HWFRAME_MAP_READ as i32;
|
||||
if ff::av_hwframe_map(drm_f, self.frame, flags) < 0 {
|
||||
ff::av_frame_free(&mut (drm_f as *mut _));
|
||||
return Err("av_hwframe_map failed".into());
|
||||
}
|
||||
let desc = (*drm_f).data[0] as *const ff::AVDRMFrameDescriptor;
|
||||
let obj = &(*desc).objects[0];
|
||||
let width = (*self.frame).width as u32;
|
||||
let height = (*self.frame).height as u32;
|
||||
// NV12: Y then UV — either as two layers (one plane each) or one layer with two planes.
|
||||
let (y_pl, uv_pl) = if (*desc).nb_layers >= 2 {
|
||||
(&(*desc).layers[0].planes[0], &(*desc).layers[1].planes[0])
|
||||
} else {
|
||||
(&(*desc).layers[0].planes[0], &(*desc).layers[0].planes[1])
|
||||
};
|
||||
let buf = Nv12DmaBuf {
|
||||
fd: obj.fd,
|
||||
size: obj.size as u64,
|
||||
modifier: obj.format_modifier,
|
||||
width,
|
||||
height,
|
||||
y_offset: y_pl.offset as u64,
|
||||
y_pitch: y_pl.pitch as u64,
|
||||
uv_offset: uv_pl.offset as u64,
|
||||
uv_pitch: uv_pl.pitch as u64,
|
||||
ten_bit: false,
|
||||
};
|
||||
let imported = dmabuf::import_raw(&self.drm.device, &self.drm.adapter, &buf);
|
||||
ff::av_frame_free(&mut (drm_f as *mut _)); // the fd was dup'd into Vulkan
|
||||
imported
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for VaapiDecoder {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
ff::av_frame_free(&mut (self.frame as *mut _));
|
||||
ff::av_packet_free(&mut (self.pkt as *mut _));
|
||||
ff::avcodec_free_context(&mut (self.dec as *mut _));
|
||||
if !self.fmt.is_null() {
|
||||
ff::avformat_close_input(&mut self.fmt);
|
||||
}
|
||||
ff::av_buffer_unref(&mut self.hw_device);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
//! Import a tiled VAAPI NV12 DMA-BUF as two wgpu textures (Y = R8, UV = RG8), aliasing
|
||||
//! the one imported `VkDeviceMemory` at the plane offsets. Two single-format images are
|
||||
//! used instead of one multi-planar image so each is an ordinary wgpu render target.
|
||||
|
||||
use crate::vaapi::MappedSurface;
|
||||
use crate::vk_device::DrmDevice;
|
||||
use ash::vk;
|
||||
|
||||
/// Plane layout for a single-object NV12/P010 DMA-BUF (the common VAAPI case).
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Nv12DmaBuf {
|
||||
pub fd: i32,
|
||||
pub size: u64,
|
||||
pub modifier: u64,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub y_offset: u64,
|
||||
pub y_pitch: u64,
|
||||
pub uv_offset: u64,
|
||||
pub uv_pitch: u64,
|
||||
/// True for 10/12/16-bit content (P010 etc.): planes are 16-bit (R16/Rg16) rather than 8-bit
|
||||
/// (R8/Rg8). The sampled float is normalized either way, so the consumer needs no change.
|
||||
pub ten_bit: bool,
|
||||
}
|
||||
|
||||
/// Frees the shared imported `VkDeviceMemory` once both plane images are gone. Held by
|
||||
/// both textures' drop callbacks (via `Arc`); the last one to run frees the memory —
|
||||
/// after wgpu has destroyed the images, in its wait-idle'd deferred-destruction pass.
|
||||
struct MemoryGuard {
|
||||
device: ash::Device,
|
||||
memory: vk::DeviceMemory,
|
||||
}
|
||||
impl Drop for MemoryGuard {
|
||||
fn drop(&mut self) {
|
||||
unsafe { self.device.free_memory(self.memory, None) };
|
||||
}
|
||||
}
|
||||
|
||||
/// Frees the duplicated dma-buf fd and any partially-created Vulkan objects when an import
|
||||
/// errors out before ownership has been handed to wgpu/`MemoryGuard`. `commit()` disarms it on
|
||||
/// the success path; `fd_consumed()` is called once `vkAllocateMemory` has taken the fd.
|
||||
struct ImportGuard {
|
||||
device: ash::Device,
|
||||
fd: libc::c_int,
|
||||
img_y: vk::Image,
|
||||
img_uv: vk::Image,
|
||||
memory: vk::DeviceMemory,
|
||||
armed: bool,
|
||||
}
|
||||
impl ImportGuard {
|
||||
fn fd_consumed(&mut self) {
|
||||
self.fd = -1; // vkAllocateMemory owns the fd now; don't close it ourselves
|
||||
}
|
||||
fn commit(&mut self) {
|
||||
self.armed = false;
|
||||
}
|
||||
}
|
||||
impl Drop for ImportGuard {
|
||||
fn drop(&mut self) {
|
||||
if !self.armed {
|
||||
return;
|
||||
}
|
||||
unsafe {
|
||||
if self.img_uv != vk::Image::null() {
|
||||
self.device.destroy_image(self.img_uv, None);
|
||||
}
|
||||
if self.img_y != vk::Image::null() {
|
||||
self.device.destroy_image(self.img_y, None);
|
||||
}
|
||||
if self.memory != vk::DeviceMemory::null() {
|
||||
self.device.free_memory(self.memory, None);
|
||||
}
|
||||
if self.fd >= 0 {
|
||||
libc::close(self.fd);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A VAAPI surface imported as two wgpu plane textures. The underlying Vulkan image/
|
||||
/// memory are destroyed by wgpu (via drop callbacks) when these textures drop.
|
||||
pub struct ImportedNv12 {
|
||||
y: wgpu::Texture,
|
||||
uv: wgpu::Texture,
|
||||
}
|
||||
|
||||
impl ImportedNv12 {
|
||||
pub fn y(&self) -> &wgpu::Texture {
|
||||
&self.y
|
||||
}
|
||||
pub fn uv(&self) -> &wgpu::Texture {
|
||||
&self.uv
|
||||
}
|
||||
/// Consume into the `(Y, UV)` plane textures (for handing to a longer-lived owner).
|
||||
pub fn into_planes(self) -> (wgpu::Texture, wgpu::Texture) {
|
||||
(self.y, self.uv)
|
||||
}
|
||||
}
|
||||
|
||||
/// Convenience: map a freshly-allocated `MappedSurface` and import it onto `drm`.
|
||||
pub fn import(drm: &DrmDevice, surf: &MappedSurface) -> Result<ImportedNv12, String> {
|
||||
import_raw(
|
||||
&drm.device,
|
||||
&drm.adapter,
|
||||
&Nv12DmaBuf {
|
||||
fd: surf.fd,
|
||||
size: surf.size,
|
||||
modifier: surf.modifier,
|
||||
width: surf.width,
|
||||
height: surf.height,
|
||||
y_offset: surf.y_offset,
|
||||
y_pitch: surf.y_pitch,
|
||||
uv_offset: surf.uv_offset,
|
||||
uv_pitch: surf.uv_pitch,
|
||||
ten_bit: false,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// Import an NV12 DMA-BUF (described by `buf`) as two wgpu plane textures **on `device`**. The raw
|
||||
/// Vulkan handles are extracted from `device`/`adapter` via `as_hal`, so this works with any
|
||||
/// DMA-BUF-import-capable wgpu device — the encoder/decoder's own `DrmDevice` *or* the editor's
|
||||
/// shared device. The fd is duplicated, so the caller keeps ownership of theirs.
|
||||
pub fn import_raw(
|
||||
device: &wgpu::Device,
|
||||
adapter: &wgpu::Adapter,
|
||||
buf: &Nv12DmaBuf,
|
||||
) -> Result<ImportedNv12, String> {
|
||||
use wgpu_hal::vulkan::Api as Vk;
|
||||
unsafe {
|
||||
let hal_device = device
|
||||
.as_hal::<Vk>()
|
||||
.ok_or("device is not Vulkan")?;
|
||||
let raw_device = hal_device.raw_device().clone();
|
||||
let raw_instance = adapter
|
||||
.as_hal::<Vk>()
|
||||
.ok_or("adapter is not Vulkan")?
|
||||
.shared_instance()
|
||||
.raw_instance()
|
||||
.clone();
|
||||
let instance = &raw_instance;
|
||||
|
||||
let dup_fd = libc::dup(buf.fd);
|
||||
if dup_fd < 0 {
|
||||
return Err("dup(dma-buf fd) failed".into());
|
||||
}
|
||||
// Owns the fd + any Vk objects created below until ownership transfers to wgpu; on any
|
||||
// early `?`/return before that, its Drop frees them (was leaking on every failed import).
|
||||
let mut guard = ImportGuard {
|
||||
device: raw_device.clone(),
|
||||
fd: dup_fd,
|
||||
img_y: vk::Image::null(),
|
||||
img_uv: vk::Image::null(),
|
||||
memory: vk::DeviceMemory::null(),
|
||||
armed: true,
|
||||
};
|
||||
|
||||
// 16-bit-norm plane formats (P010) are NOT renderable, so the import is sample-only for
|
||||
// those (decode path). 8-bit planes keep COLOR_ATTACHMENT for the encoder's RGBA→NV12 write.
|
||||
let vk_usage = if buf.ten_bit {
|
||||
vk::ImageUsageFlags::SAMPLED
|
||||
| vk::ImageUsageFlags::TRANSFER_SRC
|
||||
| vk::ImageUsageFlags::TRANSFER_DST
|
||||
} else {
|
||||
vk::ImageUsageFlags::COLOR_ATTACHMENT
|
||||
| vk::ImageUsageFlags::SAMPLED
|
||||
| vk::ImageUsageFlags::TRANSFER_SRC
|
||||
| vk::ImageUsageFlags::TRANSFER_DST
|
||||
};
|
||||
let make_image = |format: vk::Format, w: u32, h: u32, pitch: u64| -> Result<vk::Image, String> {
|
||||
let mut ext = vk::ExternalMemoryImageCreateInfo::default()
|
||||
.handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT);
|
||||
let plane_layouts = [vk::SubresourceLayout::default().offset(0).row_pitch(pitch)];
|
||||
let mut drm_info = vk::ImageDrmFormatModifierExplicitCreateInfoEXT::default()
|
||||
.drm_format_modifier(buf.modifier)
|
||||
.plane_layouts(&plane_layouts);
|
||||
let info = vk::ImageCreateInfo::default()
|
||||
.image_type(vk::ImageType::TYPE_2D)
|
||||
.format(format)
|
||||
.extent(vk::Extent3D { width: w, height: h, depth: 1 })
|
||||
.mip_levels(1)
|
||||
.array_layers(1)
|
||||
.samples(vk::SampleCountFlags::TYPE_1)
|
||||
.tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT)
|
||||
.usage(vk_usage)
|
||||
.sharing_mode(vk::SharingMode::EXCLUSIVE)
|
||||
.initial_layout(vk::ImageLayout::UNDEFINED)
|
||||
.push_next(&mut ext)
|
||||
.push_next(&mut drm_info);
|
||||
raw_device
|
||||
.create_image(&info, None)
|
||||
.map_err(|e| format!("vkCreateImage(modifier) failed: {e:?}"))
|
||||
};
|
||||
|
||||
// 8-bit NV12 → R8/Rg8 planes; 10/12/16-bit P010-style → R16/Rg16 (sampled value is
|
||||
// normalized either way, so the NV12→RGB consumer is unchanged).
|
||||
let (vk_y, vk_uv) = if buf.ten_bit {
|
||||
(vk::Format::R16_UNORM, vk::Format::R16G16_UNORM)
|
||||
} else {
|
||||
(vk::Format::R8_UNORM, vk::Format::R8G8_UNORM)
|
||||
};
|
||||
let (wgpu_y, wgpu_uv) = if buf.ten_bit {
|
||||
(wgpu::TextureFormat::R16Unorm, wgpu::TextureFormat::Rg16Unorm)
|
||||
} else {
|
||||
(wgpu::TextureFormat::R8Unorm, wgpu::TextureFormat::Rg8Unorm)
|
||||
};
|
||||
|
||||
let img_y = make_image(vk_y, buf.width, buf.height, buf.y_pitch)?;
|
||||
guard.img_y = img_y;
|
||||
let img_uv = make_image(vk_uv, buf.width / 2, buf.height / 2, buf.uv_pitch)?;
|
||||
guard.img_uv = img_uv;
|
||||
|
||||
let fd_dev = ash::khr::external_memory_fd::Device::new(instance, &raw_device);
|
||||
let mut fd_props = vk::MemoryFdPropertiesKHR::default();
|
||||
fd_dev
|
||||
.get_memory_fd_properties(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT, dup_fd, &mut fd_props)
|
||||
.map_err(|e| format!("vkGetMemoryFdPropertiesKHR failed: {e:?}"))?;
|
||||
let req_y = raw_device.get_image_memory_requirements(img_y);
|
||||
let req_uv = raw_device.get_image_memory_requirements(img_uv);
|
||||
let type_bits = fd_props.memory_type_bits & req_y.memory_type_bits & req_uv.memory_type_bits;
|
||||
if type_bits == 0 {
|
||||
return Err("no memory type compatible with dma-buf + both plane images".into());
|
||||
}
|
||||
let mem_type = type_bits.trailing_zeros();
|
||||
|
||||
let mut import_info = vk::ImportMemoryFdInfoKHR::default()
|
||||
.handle_type(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)
|
||||
.fd(dup_fd);
|
||||
let alloc = vk::MemoryAllocateInfo::default()
|
||||
.allocation_size(buf.size)
|
||||
.memory_type_index(mem_type)
|
||||
.push_next(&mut import_info);
|
||||
let memory = raw_device
|
||||
.allocate_memory(&alloc, None)
|
||||
.map_err(|e| format!("vkAllocateMemory(import dma-buf) failed: {e:?}"))?;
|
||||
guard.fd_consumed(); // the import transferred fd ownership to Vulkan
|
||||
guard.memory = memory;
|
||||
|
||||
raw_device
|
||||
.bind_image_memory(img_y, memory, buf.y_offset)
|
||||
.map_err(|e| format!("bind Y plane: {e:?}"))?;
|
||||
raw_device
|
||||
.bind_image_memory(img_uv, memory, buf.uv_offset)
|
||||
.map_err(|e| format!("bind UV plane: {e:?}"))?;
|
||||
|
||||
// Shared guard: frees `memory` once both images' drop callbacks have run.
|
||||
let mem_guard = std::sync::Arc::new(MemoryGuard { device: raw_device.clone(), memory });
|
||||
|
||||
// Match the Vulkan usage: 16-bit-norm planes (P010) are sample-only (not renderable).
|
||||
let (hal_usage, wgpu_usage) = if buf.ten_bit {
|
||||
(
|
||||
wgpu_types::TextureUses::RESOURCE | wgpu_types::TextureUses::COPY_SRC,
|
||||
wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC,
|
||||
)
|
||||
} else {
|
||||
(
|
||||
wgpu_types::TextureUses::COLOR_TARGET
|
||||
| wgpu_types::TextureUses::RESOURCE
|
||||
| wgpu_types::TextureUses::COPY_SRC,
|
||||
wgpu::TextureUsages::RENDER_ATTACHMENT
|
||||
| wgpu::TextureUsages::TEXTURE_BINDING
|
||||
| wgpu::TextureUsages::COPY_SRC,
|
||||
)
|
||||
};
|
||||
let wrap = |img: vk::Image, format: wgpu::TextureFormat, w: u32, h: u32| -> wgpu::Texture {
|
||||
// wgpu destroys the image (after wait-idle) when the texture drops; the
|
||||
// captured Arc<MemoryGuard> frees the shared memory once both have run.
|
||||
let dev = raw_device.clone();
|
||||
let guard = mem_guard.clone();
|
||||
let cb: wgpu_hal::DropCallback = Box::new(move || {
|
||||
dev.destroy_image(img, None);
|
||||
drop(guard);
|
||||
});
|
||||
let hal_desc = wgpu_hal::TextureDescriptor {
|
||||
label: Some("vaapi-plane"),
|
||||
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: hal_usage,
|
||||
memory_flags: wgpu_hal::MemoryFlags::empty(),
|
||||
view_formats: vec![],
|
||||
};
|
||||
let hal_tex = hal_device.texture_from_raw(img, &hal_desc, Some(cb));
|
||||
device.create_texture_from_hal::<wgpu_hal::vulkan::Api>(
|
||||
hal_tex,
|
||||
&wgpu::TextureDescriptor {
|
||||
label: Some("vaapi-plane"),
|
||||
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format,
|
||||
usage: wgpu_usage,
|
||||
view_formats: &[],
|
||||
},
|
||||
)
|
||||
};
|
||||
// Ownership of the images (→ texture drop callbacks) and memory (→ MemoryGuard) has now
|
||||
// transferred to wgpu; disarm the cleanup guard so it doesn't double-free them.
|
||||
guard.commit();
|
||||
let y = wrap(img_y, wgpu_y, buf.width, buf.height);
|
||||
let uv = wrap(img_uv, wgpu_uv, buf.width / 2, buf.height / 2);
|
||||
drop(hal_device);
|
||||
|
||||
Ok(ImportedNv12 { y, uv })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
//! End-to-end zero-copy H.264 encoder: render an RGBA wgpu texture straight into a VAAPI
|
||||
//! NV12 surface (no CPU copy) and encode it with `h264_vaapi`. The caller renders frames
|
||||
//! on [`ZeroCopyEncoder::device`] (the custom Vulkan device with DMA-BUF import enabled).
|
||||
//!
|
||||
//! Imports are cached by VASurface id, so the pooled surfaces are imported once each.
|
||||
|
||||
use crate::dmabuf::{self, ImportedNv12, Nv12DmaBuf};
|
||||
use crate::render_nv12::Rgba2Nv12;
|
||||
use crate::vk_device;
|
||||
use ffmpeg_sys_next as ff;
|
||||
use std::collections::HashMap;
|
||||
use std::ffi::CString;
|
||||
use std::path::Path;
|
||||
use std::ptr;
|
||||
|
||||
#[inline]
|
||||
fn averror(e: i32) -> i32 {
|
||||
-e
|
||||
}
|
||||
|
||||
pub struct ZeroCopyEncoder {
|
||||
/// wgpu handles the NV12 render runs on — either an own `DrmDevice`'s (via `new`) or the
|
||||
/// editor's shared device (via `new_on_device`). Cloned (Arc-backed) so the source can drop.
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
adapter: wgpu::Adapter,
|
||||
renderer: Rgba2Nv12,
|
||||
hw_device: *mut ff::AVBufferRef,
|
||||
frames_ref: *mut ff::AVBufferRef,
|
||||
enc: *mut ff::AVCodecContext,
|
||||
pkt: *mut ff::AVPacket,
|
||||
/// Output container (e.g. `.mp4`); packets are muxed into it directly.
|
||||
oc: *mut ff::AVFormatContext,
|
||||
enc_tb: ff::AVRational,
|
||||
stream_tb: ff::AVRational,
|
||||
width: u32,
|
||||
height: u32,
|
||||
pts: i64,
|
||||
cache: HashMap<usize, ImportedNv12>,
|
||||
}
|
||||
|
||||
// The encoder owns its FFmpeg contexts (raw `*mut`) and Vulkan/wgpu handles exclusively; it is
|
||||
// never shared, only moved. Sending it to a dedicated export thread is sound.
|
||||
unsafe impl Send for ZeroCopyEncoder {}
|
||||
|
||||
impl ZeroCopyEncoder {
|
||||
/// Build a zero-copy `h264_vaapi` encoder writing to `output_path` (container inferred
|
||||
/// from the extension, e.g. `.mp4`). `Err` if VAAPI/the device is unavailable.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
width: u32,
|
||||
height: u32,
|
||||
framerate: i32,
|
||||
bitrate_kbps: u32,
|
||||
output_path: &Path,
|
||||
full_range: bool,
|
||||
) -> Result<Self, String> {
|
||||
// Build a dedicated DMA-BUF-import device and run the encoder on it.
|
||||
let drm = vk_device::create()?;
|
||||
Self::new_on_device(
|
||||
drm.device, drm.queue, drm.adapter,
|
||||
width, height, framerate, bitrate_kbps, output_path, full_range,
|
||||
)
|
||||
}
|
||||
|
||||
/// Build the encoder running its NV12 render + DMA-BUF import on an existing wgpu device (the
|
||||
/// editor's shared device), so decode→composite→encode stay GPU-resident on one device. The
|
||||
/// device must have the DMA-BUF import extensions (a `DrmDevice` / `vk_device::create_windowed`).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new_on_device(
|
||||
device: wgpu::Device,
|
||||
queue: wgpu::Queue,
|
||||
adapter: wgpu::Adapter,
|
||||
width: u32,
|
||||
height: u32,
|
||||
framerate: i32,
|
||||
bitrate_kbps: u32,
|
||||
output_path: &Path,
|
||||
full_range: bool,
|
||||
) -> Result<Self, String> {
|
||||
let renderer = Rgba2Nv12::new(&device, full_range);
|
||||
unsafe {
|
||||
let mut hw_device = crate::vaapi::create_device()?;
|
||||
let name = CString::new("h264_vaapi").unwrap();
|
||||
let codec = ff::avcodec_find_encoder_by_name(name.as_ptr());
|
||||
if codec.is_null() {
|
||||
ff::av_buffer_unref(&mut hw_device);
|
||||
return Err("h264_vaapi not found".into());
|
||||
}
|
||||
let enc = ff::avcodec_alloc_context3(codec);
|
||||
(*enc).width = width as i32;
|
||||
(*enc).height = height as i32;
|
||||
(*enc).time_base = ff::AVRational { num: 1, den: framerate };
|
||||
(*enc).framerate = ff::AVRational { num: framerate, den: 1 };
|
||||
(*enc).pix_fmt = ff::AVPixelFormat::AV_PIX_FMT_VAAPI;
|
||||
(*enc).bit_rate = (bitrate_kbps as i64) * 1000;
|
||||
// Color signalling for the H.264 VUI. The Rgba2Nv12 shader produces BT.709 luma/chroma
|
||||
// in the matching range; without these tags players assume limited range and a
|
||||
// full-range stream looks dark + oversaturated.
|
||||
(*enc).color_range = if full_range {
|
||||
ff::AVColorRange::AVCOL_RANGE_JPEG
|
||||
} else {
|
||||
ff::AVColorRange::AVCOL_RANGE_MPEG
|
||||
};
|
||||
(*enc).colorspace = ff::AVColorSpace::AVCOL_SPC_BT709;
|
||||
(*enc).color_primaries = ff::AVColorPrimaries::AVCOL_PRI_BT709;
|
||||
(*enc).color_trc = ff::AVColorTransferCharacteristic::AVCOL_TRC_BT709;
|
||||
|
||||
let frames_ref = ff::av_hwframe_ctx_alloc(hw_device);
|
||||
{
|
||||
let fctx = (*frames_ref).data as *mut ff::AVHWFramesContext;
|
||||
(*fctx).format = ff::AVPixelFormat::AV_PIX_FMT_VAAPI;
|
||||
(*fctx).sw_format = ff::AVPixelFormat::AV_PIX_FMT_NV12;
|
||||
(*fctx).width = width as i32;
|
||||
(*fctx).height = height as i32;
|
||||
(*fctx).initial_pool_size = 16;
|
||||
}
|
||||
if ff::av_hwframe_ctx_init(frames_ref) < 0 {
|
||||
let mut fr = frames_ref;
|
||||
ff::av_buffer_unref(&mut fr);
|
||||
ff::avcodec_free_context(&mut (enc as *mut _));
|
||||
ff::av_buffer_unref(&mut hw_device);
|
||||
return Err("av_hwframe_ctx_init failed".into());
|
||||
}
|
||||
(*enc).hw_frames_ctx = ff::av_buffer_ref(frames_ref);
|
||||
|
||||
// Output container (format inferred from the path's extension).
|
||||
let cleanup = |frames_ref: *mut ff::AVBufferRef, enc: *mut ff::AVCodecContext, hw: *mut ff::AVBufferRef| {
|
||||
let mut fr = frames_ref;
|
||||
ff::av_buffer_unref(&mut fr);
|
||||
ff::avcodec_free_context(&mut (enc as *mut _));
|
||||
let mut h = hw;
|
||||
ff::av_buffer_unref(&mut h);
|
||||
};
|
||||
let path_c = CString::new(output_path.to_string_lossy().as_ref()).unwrap();
|
||||
let mut oc: *mut ff::AVFormatContext = ptr::null_mut();
|
||||
if ff::avformat_alloc_output_context2(&mut oc, ptr::null(), ptr::null(), path_c.as_ptr()) < 0
|
||||
|| oc.is_null()
|
||||
{
|
||||
cleanup(frames_ref, enc, hw_device);
|
||||
return Err(format!("avformat_alloc_output_context2 for {output_path:?} failed"));
|
||||
}
|
||||
// mp4/mov want SPS/PPS in extradata, not inline — set before opening the encoder.
|
||||
if (*(*oc).oformat).flags & ff::AVFMT_GLOBALHEADER as i32 != 0 {
|
||||
(*enc).flags |= ff::AV_CODEC_FLAG_GLOBAL_HEADER as i32;
|
||||
}
|
||||
|
||||
if ff::avcodec_open2(enc, codec, ptr::null_mut()) < 0 {
|
||||
ff::avformat_free_context(oc);
|
||||
cleanup(frames_ref, enc, hw_device);
|
||||
return Err("avcodec_open2(h264_vaapi) failed".into());
|
||||
}
|
||||
|
||||
let stream = ff::avformat_new_stream(oc, codec);
|
||||
if stream.is_null() {
|
||||
ff::avformat_free_context(oc);
|
||||
cleanup(frames_ref, enc, hw_device);
|
||||
return Err("avformat_new_stream failed".into());
|
||||
}
|
||||
if ff::avcodec_parameters_from_context((*stream).codecpar, enc) < 0 {
|
||||
ff::avformat_free_context(oc);
|
||||
cleanup(frames_ref, enc, hw_device);
|
||||
return Err("avcodec_parameters_from_context failed".into());
|
||||
}
|
||||
(*stream).time_base = (*enc).time_base;
|
||||
|
||||
if ff::avio_open(&mut (*oc).pb, path_c.as_ptr(), ff::AVIO_FLAG_WRITE as i32) < 0 {
|
||||
ff::avformat_free_context(oc);
|
||||
cleanup(frames_ref, enc, hw_device);
|
||||
return Err(format!("avio_open {output_path:?} failed"));
|
||||
}
|
||||
if ff::avformat_write_header(oc, ptr::null_mut()) < 0 {
|
||||
ff::avio_closep(&mut (*oc).pb);
|
||||
ff::avformat_free_context(oc);
|
||||
cleanup(frames_ref, enc, hw_device);
|
||||
return Err("avformat_write_header failed".into());
|
||||
}
|
||||
// The muxer may rewrite the stream time_base in write_header.
|
||||
let stream_tb = (*stream).time_base;
|
||||
|
||||
Ok(Self {
|
||||
device,
|
||||
queue,
|
||||
adapter,
|
||||
renderer,
|
||||
hw_device,
|
||||
frames_ref,
|
||||
enc,
|
||||
pkt: ff::av_packet_alloc(),
|
||||
oc,
|
||||
enc_tb: (*enc).time_base,
|
||||
stream_tb,
|
||||
width,
|
||||
height,
|
||||
pts: 0,
|
||||
cache: HashMap::new(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The wgpu device frames must be rendered on (so the RGBA texture is importable).
|
||||
pub fn device(&self) -> &wgpu::Device {
|
||||
&self.device
|
||||
}
|
||||
pub fn queue(&self) -> &wgpu::Queue {
|
||||
&self.queue
|
||||
}
|
||||
|
||||
/// Render `rgba` (an `Rgba8Unorm` texture on [`Self::device`], `TEXTURE_BINDING`)
|
||||
/// into a VAAPI surface and encode it. Appends any produced packets internally.
|
||||
pub fn encode_rgba(&mut self, rgba: &wgpu::Texture) -> Result<(), String> {
|
||||
unsafe {
|
||||
let surf = ff::av_frame_alloc();
|
||||
if ff::av_hwframe_get_buffer(self.frames_ref, surf, 0) < 0 {
|
||||
ff::av_frame_free(&mut (surf as *mut _));
|
||||
return Err("av_hwframe_get_buffer failed".into());
|
||||
}
|
||||
let id = (*surf).data[3] as usize; // VASurfaceID
|
||||
|
||||
if !self.cache.contains_key(&id) {
|
||||
let drm_f = ff::av_frame_alloc();
|
||||
(*drm_f).format = ff::AVPixelFormat::AV_PIX_FMT_DRM_PRIME as i32;
|
||||
let flags = ff::AV_HWFRAME_MAP_DIRECT as i32
|
||||
| ff::AV_HWFRAME_MAP_READ as i32
|
||||
| ff::AV_HWFRAME_MAP_WRITE as i32;
|
||||
if ff::av_hwframe_map(drm_f, surf, flags) < 0 {
|
||||
ff::av_frame_free(&mut (drm_f as *mut _));
|
||||
ff::av_frame_free(&mut (surf as *mut _));
|
||||
return Err("av_hwframe_map failed".into());
|
||||
}
|
||||
let desc = (*drm_f).data[0] as *const ff::AVDRMFrameDescriptor;
|
||||
let obj = &(*desc).objects[0];
|
||||
let y = &(*desc).layers[0].planes[0];
|
||||
let uv = &(*desc).layers[1].planes[0];
|
||||
let buf = Nv12DmaBuf {
|
||||
fd: obj.fd,
|
||||
size: obj.size as u64,
|
||||
modifier: obj.format_modifier,
|
||||
width: self.width,
|
||||
height: self.height,
|
||||
y_offset: y.offset as u64,
|
||||
y_pitch: y.pitch as u64,
|
||||
uv_offset: uv.offset as u64,
|
||||
uv_pitch: uv.pitch as u64,
|
||||
ten_bit: false,
|
||||
};
|
||||
let imported = match dmabuf::import_raw(&self.device, &self.adapter, &buf) {
|
||||
Ok(i) => i,
|
||||
Err(e) => {
|
||||
ff::av_frame_free(&mut (drm_f as *mut _));
|
||||
ff::av_frame_free(&mut (surf as *mut _));
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
ff::av_frame_free(&mut (drm_f as *mut _)); // fd was dup'd into Vulkan
|
||||
self.cache.insert(id, imported);
|
||||
}
|
||||
|
||||
// Render RGBA -> NV12 directly into the surface planes.
|
||||
let imp = self.cache.get(&id).unwrap();
|
||||
let rgba_view = rgba.create_view(&Default::default());
|
||||
let y_view = imp.y().create_view(&Default::default());
|
||||
let uv_view = imp.uv().create_view(&Default::default());
|
||||
let mut cmd = self.device.create_command_encoder(&Default::default());
|
||||
self.renderer.convert(&self.device, &mut cmd, &rgba_view, &y_view, &uv_view);
|
||||
self.queue.submit(Some(cmd.finish()));
|
||||
let _ = self.device.poll(wgpu::PollType::wait_indefinitely());
|
||||
|
||||
// Encode the surface.
|
||||
(*surf).pts = self.pts;
|
||||
self.pts += 1;
|
||||
let r = ff::avcodec_send_frame(self.enc, surf);
|
||||
ff::av_frame_free(&mut (surf as *mut _));
|
||||
if r < 0 {
|
||||
return Err(format!("avcodec_send_frame failed: {r}"));
|
||||
}
|
||||
self.drain()
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn drain(&mut self) -> Result<(), String> {
|
||||
loop {
|
||||
let r = ff::avcodec_receive_packet(self.enc, self.pkt);
|
||||
if r == averror(libc::EAGAIN) || r == ff::AVERROR_EOF {
|
||||
break;
|
||||
}
|
||||
if r < 0 {
|
||||
return Err(format!("avcodec_receive_packet failed: {r}"));
|
||||
}
|
||||
ff::av_packet_rescale_ts(self.pkt, self.enc_tb, self.stream_tb);
|
||||
(*self.pkt).stream_index = 0;
|
||||
// Takes ownership of the packet's buffer (unrefs it for us).
|
||||
let w = ff::av_interleaved_write_frame(self.oc, self.pkt);
|
||||
if w < 0 {
|
||||
return Err(format!("av_interleaved_write_frame failed: {w}"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Flush the encoder, write the container trailer, and close the output file.
|
||||
pub fn finish(mut self) -> Result<(), String> {
|
||||
unsafe {
|
||||
ff::avcodec_send_frame(self.enc, ptr::null_mut());
|
||||
self.drain()?;
|
||||
if ff::av_write_trailer(self.oc) < 0 {
|
||||
return Err("av_write_trailer failed".into());
|
||||
}
|
||||
ff::avio_closep(&mut (*self.oc).pb);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ZeroCopyEncoder {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
self.cache.clear(); // frees imported Vulkan resources first
|
||||
ff::av_packet_free(&mut (self.pkt as *mut _));
|
||||
ff::avcodec_free_context(&mut (self.enc as *mut _));
|
||||
let mut fr = self.frames_ref;
|
||||
ff::av_buffer_unref(&mut fr);
|
||||
ff::av_buffer_unref(&mut self.hw_device);
|
||||
if !self.oc.is_null() {
|
||||
// `finish` nulls pb via avio_closep; close here too if it wasn't called.
|
||||
if !(*self.oc).pb.is_null() {
|
||||
ff::avio_closep(&mut (*self.oc).pb);
|
||||
}
|
||||
ff::avformat_free_context(self.oc);
|
||||
self.oc = ptr::null_mut();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
//! Zero-copy GPU video encoding.
|
||||
//!
|
||||
//! Converts a rendered RGBA texture to the encoder's pixel format (NV12) on the GPU
|
||||
//! and feeds it to a hardware video encoder without a CPU round-trip. All the unsafe
|
||||
//! GPU↔encoder interop (Vulkan external memory / DMA-BUF → VAAPI on Linux, etc.) is
|
||||
//! isolated in this crate.
|
||||
//!
|
||||
//! Status: scaffolding. Headless GPU probe + (next) NV12 compute live here first so
|
||||
//! the GPU-side conversion can be validated against a CPU reference before any unsafe
|
||||
//! interop is written. See `lightningbeam-ui/ZEROCOPY_GPU_ENCODE_PLAN.md`.
|
||||
|
||||
pub mod nv12;
|
||||
|
||||
/// Fragment-shader RGBA→NV12 conversion that renders into plane textures.
|
||||
pub mod render_nv12;
|
||||
|
||||
/// VAAPI hardware encode (Linux-only; libva).
|
||||
#[cfg(target_os = "linux")]
|
||||
pub mod vaapi;
|
||||
|
||||
/// Custom Vulkan device with DMA-BUF import extensions (Linux).
|
||||
#[cfg(target_os = "linux")]
|
||||
pub mod vk_device;
|
||||
|
||||
/// Import a VAAPI NV12 DMA-BUF as wgpu textures (Linux).
|
||||
#[cfg(target_os = "linux")]
|
||||
pub mod dmabuf;
|
||||
|
||||
/// End-to-end zero-copy `h264_vaapi` encoder (Linux).
|
||||
#[cfg(target_os = "linux")]
|
||||
pub mod encoder;
|
||||
|
||||
/// VAAPI hardware decode → wgpu textures (Linux).
|
||||
#[cfg(target_os = "linux")]
|
||||
pub mod decoder;
|
||||
|
||||
#[cfg(test)]
|
||||
mod probe_tests {
|
||||
/// Confirm a headless GPU adapter is reachable (Vulkan on Linux/Intel). This gates
|
||||
/// whether the GPU-side conversion can be tested on real hardware in this env.
|
||||
#[test]
|
||||
fn headless_adapter_available() {
|
||||
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
|
||||
backends: wgpu::Backends::VULKAN | wgpu::Backends::GL,
|
||||
..Default::default()
|
||||
});
|
||||
let adapter = pollster::block_on(instance.request_adapter(
|
||||
&wgpu::RequestAdapterOptions {
|
||||
power_preference: wgpu::PowerPreference::HighPerformance,
|
||||
force_fallback_adapter: false,
|
||||
compatible_surface: None,
|
||||
},
|
||||
));
|
||||
match adapter {
|
||||
Ok(a) => {
|
||||
let info = a.get_info();
|
||||
eprintln!(
|
||||
"[gpu-probe] adapter: {} | backend={:?} | type={:?} | driver={}",
|
||||
info.name, info.backend, info.device_type, info.driver
|
||||
);
|
||||
}
|
||||
Err(e) => panic!("no GPU adapter available headless: {e:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
//! GPU RGBA→NV12 conversion (BT.709 full-range), the pixel format hardware video
|
||||
//! encoders (VAAPI/QSV/NVENC/VideoToolbox) consume.
|
||||
//!
|
||||
//! NV12 layout (what this writes, tight-packed into a storage buffer):
|
||||
//! - `[0, W*H)` Y plane, one byte/pixel, row stride `W`
|
||||
//! - `[W*H, W*H + W*H/2)` UV plane, interleaved `U,V` at 4:2:0, row stride `W`
|
||||
//! (`W/2` chroma columns × 2 bytes), `H/2` rows
|
||||
//!
|
||||
//! Same BT.709 full-range matrix as the editor's planar YUV420p path, so colors match.
|
||||
//! Requires `W % 8 == 0 && H % 2 == 0` (the shader packs 4 bytes per `u32`).
|
||||
|
||||
/// `true` when [`Nv12Converter`] can handle these dimensions (else caller pads/falls back).
|
||||
pub fn supports(width: u32, height: u32) -> bool {
|
||||
width % 8 == 0 && height % 2 == 0 && width > 0 && height > 0
|
||||
}
|
||||
|
||||
/// Tight NV12 byte length for `width`×`height`.
|
||||
pub fn nv12_len(width: u32, height: u32) -> usize {
|
||||
(width * height + width * (height / 2)) as usize
|
||||
}
|
||||
|
||||
/// Compute pipeline: `Rgba8Unorm` texture → tight NV12 storage buffer.
|
||||
pub struct Nv12Converter {
|
||||
y_pipeline: wgpu::ComputePipeline,
|
||||
uv_pipeline: wgpu::ComputePipeline,
|
||||
bind_group_layout: wgpu::BindGroupLayout,
|
||||
}
|
||||
|
||||
impl Nv12Converter {
|
||||
pub fn new(device: &wgpu::Device) -> Self {
|
||||
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("nv12_bgl"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: false },
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("nv12_pl"),
|
||||
bind_group_layouts: &[&bind_group_layout],
|
||||
push_constant_ranges: &[],
|
||||
});
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("nv12_shader"),
|
||||
source: wgpu::ShaderSource::Wgsl(SHADER.into()),
|
||||
});
|
||||
let mk = |entry: &str| {
|
||||
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("nv12_pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &shader,
|
||||
entry_point: Some(entry),
|
||||
compilation_options: wgpu::PipelineCompilationOptions::default(),
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
Self {
|
||||
y_pipeline: mk("y_main"),
|
||||
uv_pipeline: mk("uv_main"),
|
||||
bind_group_layout,
|
||||
}
|
||||
}
|
||||
|
||||
/// Record RGBA→NV12 into `encoder`. `out_buffer` must be `STORAGE | COPY_SRC` of at
|
||||
/// least [`nv12_len`] bytes. Caller must ensure [`supports`]`(width, height)`.
|
||||
pub fn convert(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
rgba_view: &wgpu::TextureView,
|
||||
out_buffer: &wgpu::Buffer,
|
||||
width: u32,
|
||||
height: u32,
|
||||
) {
|
||||
debug_assert!(supports(width, height));
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("nv12_bg"),
|
||||
layout: &self.bind_group_layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(rgba_view) },
|
||||
wgpu::BindGroupEntry { binding: 1, resource: out_buffer.as_entire_binding() },
|
||||
],
|
||||
});
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("nv12_pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
pass.set_bind_group(0, &bind_group, &[]);
|
||||
let wg = 8u32;
|
||||
// Y: one thread per 4 horizontal luma samples.
|
||||
pass.set_pipeline(&self.y_pipeline);
|
||||
pass.dispatch_workgroups(((width / 4) + wg - 1) / wg, (height + wg - 1) / wg, 1);
|
||||
// UV: one thread per 4 interleaved UV bytes = 2 chroma columns; (W/4)×(H/2) threads.
|
||||
pass.set_pipeline(&self.uv_pipeline);
|
||||
pass.dispatch_workgroups(((width / 4) + wg - 1) / wg, ((height / 2) + wg - 1) / wg, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// CPU reference producing the exact bytes the shader should — used by tests to verify
|
||||
/// the GPU output on real hardware.
|
||||
pub fn cpu_reference(rgba: &[u8], width: u32, height: u32) -> Vec<u8> {
|
||||
let w = width as usize;
|
||||
let h = height as usize;
|
||||
let mut out = vec![0u8; nv12_len(width, height)];
|
||||
let to_byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
|
||||
let px = |x: usize, y: usize| {
|
||||
let i = (y * w + x) * 4;
|
||||
[rgba[i] as f32 / 255.0, rgba[i + 1] as f32 / 255.0, rgba[i + 2] as f32 / 255.0]
|
||||
};
|
||||
// Y
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
let p = px(x, y);
|
||||
out[y * w + x] = to_byte(0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]);
|
||||
}
|
||||
}
|
||||
// Interleaved UV (2x2 box average)
|
||||
let y_size = w * h;
|
||||
for cy in 0..h / 2 {
|
||||
for cx in 0..w / 2 {
|
||||
let mut acc = [0.0f32; 3];
|
||||
for (dx, dy) in [(0, 0), (1, 0), (0, 1), (1, 1)] {
|
||||
let p = px(2 * cx + dx, 2 * cy + dy);
|
||||
acc[0] += p[0]; acc[1] += p[1]; acc[2] += p[2];
|
||||
}
|
||||
let a = [acc[0] / 4.0, acc[1] / 4.0, acc[2] / 4.0];
|
||||
let u = -0.1146 * a[0] - 0.3854 * a[1] + 0.5000 * a[2] + 0.5;
|
||||
let v = 0.5000 * a[0] - 0.4542 * a[1] - 0.0458 * a[2] + 0.5;
|
||||
out[y_size + cy * w + 2 * cx] = to_byte(u);
|
||||
out[y_size + cy * w + 2 * cx + 1] = to_byte(v);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
const SHADER: &str = r#"
|
||||
@group(0) @binding(0) var input_rgba: texture_2d<f32>;
|
||||
@group(0) @binding(1) var<storage, read_write> out_buf: array<u32>;
|
||||
|
||||
fn to_byte(v: f32) -> u32 { return u32(clamp(v, 0.0, 1.0) * 255.0 + 0.5); }
|
||||
|
||||
// Y plane: pack 4 horizontal luma bytes.
|
||||
@compute @workgroup_size(8, 8, 1)
|
||||
fn y_main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
let dims = textureDimensions(input_rgba);
|
||||
let w = dims.x;
|
||||
let h = dims.y;
|
||||
let x4 = gid.x * 4u;
|
||||
let y = gid.y;
|
||||
if (x4 >= w || y >= h) { return; }
|
||||
var packed: u32 = 0u;
|
||||
for (var i = 0u; i < 4u; i = i + 1u) {
|
||||
let c = textureLoad(input_rgba, vec2<u32>(x4 + i, y), 0).rgb;
|
||||
let yy = 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
|
||||
packed = packed | (to_byte(yy) << (8u * i));
|
||||
}
|
||||
out_buf[(y * w + x4) / 4u] = packed;
|
||||
}
|
||||
|
||||
// UV plane: each thread writes 4 interleaved bytes = U0 V0 U1 V1 for 2 chroma columns.
|
||||
@compute @workgroup_size(8, 8, 1)
|
||||
fn uv_main(@builtin(global_invocation_id) gid: vec3<u32>) {
|
||||
let dims = textureDimensions(input_rgba);
|
||||
let w = dims.x;
|
||||
let h = dims.y;
|
||||
let k = gid.x; // chroma-column pair index: covers columns 2k, 2k+1
|
||||
let cy = gid.y;
|
||||
if (k * 2u >= w / 2u || cy >= h / 2u) { return; }
|
||||
let y_size = w * h;
|
||||
|
||||
var packed: u32 = 0u;
|
||||
for (var j = 0u; j < 2u; j = j + 1u) {
|
||||
let cx = 2u * k + j; // chroma column
|
||||
let sx = 2u * cx;
|
||||
let sy = 2u * cy;
|
||||
let p00 = textureLoad(input_rgba, vec2<u32>(sx, sy), 0).rgb;
|
||||
let p10 = textureLoad(input_rgba, vec2<u32>(sx + 1u, sy), 0).rgb;
|
||||
let p01 = textureLoad(input_rgba, vec2<u32>(sx, sy + 1u), 0).rgb;
|
||||
let p11 = textureLoad(input_rgba, vec2<u32>(sx + 1u, sy + 1u), 0).rgb;
|
||||
let a = (p00 + p10 + p01 + p11) * 0.25;
|
||||
let u = -0.1146 * a.r - 0.3854 * a.g + 0.5000 * a.b + 0.5;
|
||||
let v = 0.5000 * a.r - 0.4542 * a.g - 0.0458 * a.b + 0.5;
|
||||
packed = packed | (to_byte(u) << (16u * j)); // byte 0 or 2
|
||||
packed = packed | (to_byte(v) << (16u * j + 8u)); // byte 1 or 3
|
||||
}
|
||||
// UV row stride is w bytes; this thread writes 4 bytes at column 4k.
|
||||
out_buf[(y_size + cy * w + 4u * k) / 4u] = packed;
|
||||
}
|
||||
"#;
|
||||
@@ -0,0 +1,189 @@
|
||||
//! Fragment-shader RGBA→NV12 conversion that **renders** luma/chroma into the encoder
|
||||
//! surface's plane textures (R8 Y, RG8 UV). Render targets (not compute storage) so it
|
||||
//! works with the DMA-BUF-imported plane images, which aren't storage-writable.
|
||||
//!
|
||||
//! BT.709 matrix; the Y/chroma scale+offset are chosen by `full_range` — limited (TV, 16–235)
|
||||
//! is the H.264 convention most players assume, full (PC, 0–255) needs the matching color tag.
|
||||
|
||||
/// Converts a bound RGBA texture into a Y plane (R8) and a UV plane (RG8) via two passes.
|
||||
pub struct Rgba2Nv12 {
|
||||
y_pipeline: wgpu::RenderPipeline,
|
||||
uv_pipeline: wgpu::RenderPipeline,
|
||||
bgl: wgpu::BindGroupLayout,
|
||||
params_buf: wgpu::Buffer,
|
||||
}
|
||||
|
||||
impl Rgba2Nv12 {
|
||||
/// `full_range`: true → full/PC range (Y 0–255, no scaling); false → limited/TV range
|
||||
/// (Y 16–235, chroma 16–240), the H.264 default. The encoder must tag the stream to match.
|
||||
pub fn new(device: &wgpu::Device, full_range: bool) -> Self {
|
||||
// (y_offset, y_scale, chroma_offset, chroma_scale). The shader applies these to the
|
||||
// BT.709 luma/chroma dot products.
|
||||
let params: [f32; 4] = if full_range {
|
||||
[0.0, 1.0, 128.0 / 255.0, 1.0]
|
||||
} else {
|
||||
[16.0 / 255.0, 219.0 / 255.0, 128.0 / 255.0, 224.0 / 255.0]
|
||||
};
|
||||
let params_bytes: Vec<u8> = params.iter().flat_map(|f| f.to_le_bytes()).collect();
|
||||
let params_buf = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("rgba2nv12_params"),
|
||||
size: params_bytes.len() as u64,
|
||||
usage: wgpu::BufferUsages::UNIFORM,
|
||||
mapped_at_creation: true,
|
||||
});
|
||||
params_buf.slice(..).get_mapped_range_mut().copy_from_slice(¶ms_bytes);
|
||||
params_buf.unmap();
|
||||
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("rgba2nv12_bgl"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: false },
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Uniform,
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("rgba2nv12_pl"),
|
||||
bind_group_layouts: &[&bgl],
|
||||
push_constant_ranges: &[],
|
||||
});
|
||||
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
|
||||
label: Some("rgba2nv12_shader"),
|
||||
source: wgpu::ShaderSource::Wgsl(SHADER.into()),
|
||||
});
|
||||
let mk = |fs: &str, fmt: wgpu::TextureFormat| {
|
||||
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
|
||||
label: Some("rgba2nv12_pipeline"),
|
||||
layout: Some(&layout),
|
||||
vertex: wgpu::VertexState {
|
||||
module: &shader,
|
||||
entry_point: Some("vs_main"),
|
||||
buffers: &[],
|
||||
compilation_options: Default::default(),
|
||||
},
|
||||
fragment: Some(wgpu::FragmentState {
|
||||
module: &shader,
|
||||
entry_point: Some(fs),
|
||||
targets: &[Some(fmt.into())],
|
||||
compilation_options: Default::default(),
|
||||
}),
|
||||
primitive: wgpu::PrimitiveState {
|
||||
topology: wgpu::PrimitiveTopology::TriangleList,
|
||||
..Default::default()
|
||||
},
|
||||
depth_stencil: None,
|
||||
multisample: Default::default(),
|
||||
multiview: None,
|
||||
cache: None,
|
||||
})
|
||||
};
|
||||
Self {
|
||||
y_pipeline: mk("y_fs", wgpu::TextureFormat::R8Unorm),
|
||||
uv_pipeline: mk("uv_fs", wgpu::TextureFormat::Rg8Unorm),
|
||||
bgl,
|
||||
params_buf,
|
||||
}
|
||||
}
|
||||
|
||||
/// Record both plane passes. `y_view`/`uv_view` are the R8/RG8 plane render targets.
|
||||
pub fn convert(
|
||||
&self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
rgba_view: &wgpu::TextureView,
|
||||
y_view: &wgpu::TextureView,
|
||||
uv_view: &wgpu::TextureView,
|
||||
) {
|
||||
let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("rgba2nv12_bg"),
|
||||
layout: &self.bgl,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(rgba_view),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: self.params_buf.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
for (pipeline, view) in [(&self.y_pipeline, y_view), (&self.uv_pipeline, uv_view)] {
|
||||
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("rgba2nv12_pass"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
});
|
||||
pass.set_pipeline(pipeline);
|
||||
pass.set_bind_group(0, &bg, &[]);
|
||||
pass.draw(0..3, 0..1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const SHADER: &str = r#"
|
||||
@group(0) @binding(0) var input_rgba: texture_2d<f32>;
|
||||
// (y_offset, y_scale, chroma_offset, chroma_scale) — selects limited vs full range.
|
||||
@group(0) @binding(1) var<uniform> params: vec4<f32>;
|
||||
|
||||
// Fullscreen triangle.
|
||||
@vertex
|
||||
fn vs_main(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {
|
||||
let x = f32((vi << 1u) & 2u);
|
||||
let y = f32(vi & 2u);
|
||||
return vec4<f32>(x * 2.0 - 1.0, 1.0 - y * 2.0, 0.0, 1.0);
|
||||
}
|
||||
|
||||
fn load(p: vec2<i32>) -> vec3<f32> {
|
||||
return textureLoad(input_rgba, p, 0).rgb;
|
||||
}
|
||||
|
||||
// Y plane (full res): one luma byte per pixel.
|
||||
@fragment
|
||||
fn y_fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let c = load(vec2<i32>(i32(pos.x), i32(pos.y)));
|
||||
let luma = 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
|
||||
let y = params.x + params.y * luma;
|
||||
return vec4<f32>(y, 0.0, 0.0, 1.0);
|
||||
}
|
||||
|
||||
// UV plane (half res): 2x2 box-averaged chroma, interleaved into RG.
|
||||
@fragment
|
||||
fn uv_fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let sx = 2 * i32(pos.x);
|
||||
let sy = 2 * i32(pos.y);
|
||||
let a = (load(vec2<i32>(sx, sy)) + load(vec2<i32>(sx + 1, sy))
|
||||
+ load(vec2<i32>(sx, sy + 1)) + load(vec2<i32>(sx + 1, sy + 1))) * 0.25;
|
||||
let cb = -0.1146 * a.r - 0.3854 * a.g + 0.5000 * a.b;
|
||||
let cr = 0.5000 * a.r - 0.4542 * a.g - 0.0458 * a.b;
|
||||
let u = params.z + params.w * cb;
|
||||
let v = params.z + params.w * cr;
|
||||
return vec4<f32>(u, v, 0.0, 1.0);
|
||||
}
|
||||
"#;
|
||||
@@ -0,0 +1,521 @@
|
||||
//! VAAPI hardware H.264 encoding (Linux/Intel/AMD).
|
||||
//!
|
||||
//! Level 1 (this module first): a CPU-fed encoder — upload NV12 frames to VAAPI
|
||||
//! surfaces (`av_hwframe_transfer_data`) and encode with `h264_vaapi`. This proves the
|
||||
//! encoder works and establishes the FFI scaffolding. Level 2 (zero-copy: GPU writes
|
||||
//! NV12 straight into the VAAPI surface via DMA-BUF) builds on this.
|
||||
//!
|
||||
//! All `unsafe` FFmpeg FFI is contained here.
|
||||
|
||||
use ffmpeg_sys_next as ff;
|
||||
use std::ffi::CString;
|
||||
use std::ptr;
|
||||
|
||||
#[inline]
|
||||
fn averror(e: i32) -> i32 {
|
||||
-e
|
||||
}
|
||||
|
||||
/// Create a VAAPI hwdevice on `/dev/dri/renderD128`, trying driver names in turn.
|
||||
///
|
||||
/// libva's auto-selection can pick a driver that doesn't support the GPU — notably it
|
||||
/// chooses the legacy `i965` driver on newer Intel parts (Gen 11+) where the modern `iHD`
|
||||
/// driver is required. Each `av_hwdevice_ctx_create` opens a fresh VADisplay, so
|
||||
/// `LIBVA_DRIVER_NAME` is re-read per attempt. We try `iHD` first (modern Intel), then the
|
||||
/// caller's original setting, then `i965` (older Intel) and `radeonsi` (AMD). On success the
|
||||
/// working driver name is left in the env; on total failure the original value is restored.
|
||||
pub fn create_device() -> Result<*mut ff::AVBufferRef, String> {
|
||||
unsafe {
|
||||
let node = CString::new("/dev/dri/renderD128").unwrap();
|
||||
let original = std::env::var_os("LIBVA_DRIVER_NAME");
|
||||
let attempts: [Option<&str>; 4] = [Some("iHD"), None, Some("i965"), Some("radeonsi")];
|
||||
for drv in attempts {
|
||||
match drv {
|
||||
Some(d) => std::env::set_var("LIBVA_DRIVER_NAME", d),
|
||||
// `None` = the caller's original setting (or libva auto if unset).
|
||||
None => match &original {
|
||||
Some(v) => std::env::set_var("LIBVA_DRIVER_NAME", v),
|
||||
None => std::env::remove_var("LIBVA_DRIVER_NAME"),
|
||||
},
|
||||
}
|
||||
let mut hw: *mut ff::AVBufferRef = ptr::null_mut();
|
||||
if ff::av_hwdevice_ctx_create(
|
||||
&mut hw,
|
||||
ff::AVHWDeviceType::AV_HWDEVICE_TYPE_VAAPI,
|
||||
node.as_ptr(),
|
||||
ptr::null_mut(),
|
||||
0,
|
||||
) >= 0
|
||||
{
|
||||
return Ok(hw);
|
||||
}
|
||||
}
|
||||
match &original {
|
||||
Some(v) => std::env::set_var("LIBVA_DRIVER_NAME", v),
|
||||
None => std::env::remove_var("LIBVA_DRIVER_NAME"),
|
||||
}
|
||||
Err("av_hwdevice_ctx_create(VAAPI) failed for all drivers (iHD/i965/radeonsi)".into())
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy tight NV12 (`Y` then interleaved `UV`) into an AVFrame's planes, respecting
|
||||
/// each plane's linesize (which FFmpeg may pad).
|
||||
unsafe fn fill_nv12(frame: *mut ff::AVFrame, nv12: &[u8], width: u32, height: u32) {
|
||||
let w = width as usize;
|
||||
let h = height as usize;
|
||||
// Y plane: h rows of w bytes.
|
||||
let dst_y = (*frame).data[0];
|
||||
let ls_y = (*frame).linesize[0] as usize;
|
||||
for row in 0..h {
|
||||
let src = &nv12[row * w..row * w + w];
|
||||
ptr::copy_nonoverlapping(src.as_ptr(), dst_y.add(row * ls_y), w);
|
||||
}
|
||||
// UV plane: h/2 rows of w bytes (interleaved U,V), source offset starts at w*h.
|
||||
let dst_uv = (*frame).data[1];
|
||||
let ls_uv = (*frame).linesize[1] as usize;
|
||||
let uv_off = w * h;
|
||||
for row in 0..h / 2 {
|
||||
let src = &nv12[uv_off + row * w..uv_off + row * w + w];
|
||||
ptr::copy_nonoverlapping(src.as_ptr(), dst_uv.add(row * ls_uv), w);
|
||||
}
|
||||
}
|
||||
|
||||
/// A VAAPI NV12 surface mapped to a DMA-BUF, with its layout extracted for Vulkan import.
|
||||
/// Keeps the FFmpeg handles alive; the `fd` stays valid until drop (dup it for Vulkan).
|
||||
pub struct MappedSurface {
|
||||
hw_device: *mut ff::AVBufferRef,
|
||||
frames_ref: *mut ff::AVBufferRef,
|
||||
surf: *mut ff::AVFrame,
|
||||
drm: *mut ff::AVFrame,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub fd: i32,
|
||||
pub size: u64,
|
||||
pub modifier: u64,
|
||||
pub y_offset: u64,
|
||||
pub y_pitch: u64,
|
||||
pub uv_offset: u64,
|
||||
pub uv_pitch: u64,
|
||||
}
|
||||
|
||||
impl MappedSurface {
|
||||
/// Allocate a VAAPI NV12 surface and map it to DRM-PRIME.
|
||||
pub fn alloc(width: u32, height: u32) -> Result<Self, String> {
|
||||
unsafe {
|
||||
let mut hw_device: *mut ff::AVBufferRef = ptr::null_mut();
|
||||
let node = CString::new("/dev/dri/renderD128").unwrap();
|
||||
if ff::av_hwdevice_ctx_create(
|
||||
&mut hw_device,
|
||||
ff::AVHWDeviceType::AV_HWDEVICE_TYPE_VAAPI,
|
||||
node.as_ptr(),
|
||||
ptr::null_mut(),
|
||||
0,
|
||||
) < 0
|
||||
{
|
||||
return Err("av_hwdevice_ctx_create failed".into());
|
||||
}
|
||||
let frames_ref = ff::av_hwframe_ctx_alloc(hw_device);
|
||||
if frames_ref.is_null() {
|
||||
ff::av_buffer_unref(&mut hw_device);
|
||||
return Err("av_hwframe_ctx_alloc failed".into());
|
||||
}
|
||||
{
|
||||
let fctx = (*frames_ref).data as *mut ff::AVHWFramesContext;
|
||||
(*fctx).format = ff::AVPixelFormat::AV_PIX_FMT_VAAPI;
|
||||
(*fctx).sw_format = ff::AVPixelFormat::AV_PIX_FMT_NV12;
|
||||
(*fctx).width = width as i32;
|
||||
(*fctx).height = height as i32;
|
||||
(*fctx).initial_pool_size = 4;
|
||||
}
|
||||
if ff::av_hwframe_ctx_init(frames_ref) < 0 {
|
||||
let mut fr = frames_ref;
|
||||
ff::av_buffer_unref(&mut fr);
|
||||
ff::av_buffer_unref(&mut hw_device);
|
||||
return Err("av_hwframe_ctx_init failed".into());
|
||||
}
|
||||
let surf = ff::av_frame_alloc();
|
||||
if ff::av_hwframe_get_buffer(frames_ref, surf, 0) < 0 {
|
||||
ff::av_frame_free(&mut (surf as *mut _));
|
||||
let mut fr = frames_ref;
|
||||
ff::av_buffer_unref(&mut fr);
|
||||
ff::av_buffer_unref(&mut hw_device);
|
||||
return Err("av_hwframe_get_buffer failed".into());
|
||||
}
|
||||
let drm = ff::av_frame_alloc();
|
||||
(*drm).format = ff::AVPixelFormat::AV_PIX_FMT_DRM_PRIME as i32;
|
||||
let flags = ff::AV_HWFRAME_MAP_DIRECT as i32
|
||||
| ff::AV_HWFRAME_MAP_READ as i32
|
||||
| ff::AV_HWFRAME_MAP_WRITE as i32;
|
||||
if ff::av_hwframe_map(drm, surf, flags) < 0 {
|
||||
ff::av_frame_free(&mut (drm as *mut _));
|
||||
ff::av_frame_free(&mut (surf as *mut _));
|
||||
let mut fr = frames_ref;
|
||||
ff::av_buffer_unref(&mut fr);
|
||||
ff::av_buffer_unref(&mut hw_device);
|
||||
return Err("av_hwframe_map failed".into());
|
||||
}
|
||||
let desc = (*drm).data[0] as *const ff::AVDRMFrameDescriptor;
|
||||
// Expect 1 object, 2 layers (Y=R8, UV=GR88).
|
||||
if (*desc).nb_objects != 1 || (*desc).nb_layers != 2 {
|
||||
let msg = format!(
|
||||
"unexpected DRM layout: {} objects, {} layers",
|
||||
(*desc).nb_objects, (*desc).nb_layers
|
||||
);
|
||||
// Free everything mapped/allocated above (this path was leaking the device,
|
||||
// frames context, and both AVFrames on every odd-layout surface).
|
||||
ff::av_frame_free(&mut (drm as *mut _));
|
||||
ff::av_frame_free(&mut (surf as *mut _));
|
||||
let mut fr = frames_ref;
|
||||
ff::av_buffer_unref(&mut fr);
|
||||
ff::av_buffer_unref(&mut hw_device);
|
||||
return Err(msg);
|
||||
}
|
||||
let obj = &(*desc).objects[0];
|
||||
let y = &(*desc).layers[0].planes[0];
|
||||
let uv = &(*desc).layers[1].planes[0];
|
||||
Ok(MappedSurface {
|
||||
hw_device,
|
||||
frames_ref,
|
||||
surf,
|
||||
drm,
|
||||
width,
|
||||
height,
|
||||
fd: obj.fd,
|
||||
size: obj.size as u64,
|
||||
modifier: obj.format_modifier,
|
||||
y_offset: y.offset as u64,
|
||||
y_pitch: y.pitch as u64,
|
||||
uv_offset: uv.offset as u64,
|
||||
uv_pitch: uv.pitch as u64,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The underlying VASurface AVFrame (to hand to the encoder).
|
||||
pub fn av_frame(&self) -> *mut ff::AVFrame {
|
||||
self.surf
|
||||
}
|
||||
|
||||
/// Read the surface back to tight CPU NV12 (for verifying what the GPU wrote).
|
||||
pub fn readback_nv12(&self) -> Result<Vec<u8>, String> {
|
||||
unsafe {
|
||||
let sw = ff::av_frame_alloc();
|
||||
(*sw).format = ff::AVPixelFormat::AV_PIX_FMT_NV12 as i32;
|
||||
(*sw).width = self.width as i32;
|
||||
(*sw).height = self.height as i32;
|
||||
if ff::av_frame_get_buffer(sw, 0) < 0 {
|
||||
ff::av_frame_free(&mut (sw as *mut _));
|
||||
return Err("av_frame_get_buffer failed".into());
|
||||
}
|
||||
if ff::av_hwframe_transfer_data(sw, self.surf, 0) < 0 {
|
||||
ff::av_frame_free(&mut (sw as *mut _));
|
||||
return Err("av_hwframe_transfer_data (download) failed".into());
|
||||
}
|
||||
let w = self.width as usize;
|
||||
let h = self.height as usize;
|
||||
let mut out = vec![0u8; w * h + w * (h / 2)];
|
||||
let ls_y = (*sw).linesize[0] as usize;
|
||||
for row in 0..h {
|
||||
let src = (*sw).data[0].add(row * ls_y);
|
||||
ptr::copy_nonoverlapping(src, out.as_mut_ptr().add(row * w), w);
|
||||
}
|
||||
let ls_uv = (*sw).linesize[1] as usize;
|
||||
let uv_off = w * h;
|
||||
for row in 0..h / 2 {
|
||||
let src = (*sw).data[1].add(row * ls_uv);
|
||||
ptr::copy_nonoverlapping(src, out.as_mut_ptr().add(uv_off + row * w), w);
|
||||
}
|
||||
ff::av_frame_free(&mut (sw as *mut _));
|
||||
Ok(out)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MappedSurface {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
ff::av_frame_free(&mut (self.drm as *mut _));
|
||||
ff::av_frame_free(&mut (self.surf as *mut _));
|
||||
let mut fr = self.frames_ref;
|
||||
ff::av_buffer_unref(&mut fr);
|
||||
ff::av_buffer_unref(&mut self.hw_device);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Allocate one VAAPI NV12 surface, map it to a DRM-PRIME descriptor, and return a
|
||||
/// human-readable dump of its DMA-BUF layout (object fds/size/modifier; layer fourcc;
|
||||
/// per-plane object/offset/pitch). The format **modifier** decides the zero-copy path:
|
||||
/// `0` = LINEAR (compute can write a linear NV12 buffer/image), anything else = tiled
|
||||
/// (needs a GPU copy into the tiled surface, or a linear import VAAPI accepts).
|
||||
pub fn probe_surface_drm(width: u32, height: u32) -> Result<String, String> {
|
||||
unsafe {
|
||||
let mut hw_device: *mut ff::AVBufferRef = ptr::null_mut();
|
||||
let node = CString::new("/dev/dri/renderD128").unwrap();
|
||||
if ff::av_hwdevice_ctx_create(
|
||||
&mut hw_device,
|
||||
ff::AVHWDeviceType::AV_HWDEVICE_TYPE_VAAPI,
|
||||
node.as_ptr(),
|
||||
ptr::null_mut(),
|
||||
0,
|
||||
) < 0
|
||||
{
|
||||
return Err("av_hwdevice_ctx_create(VAAPI) failed".into());
|
||||
}
|
||||
|
||||
let frames_ref = ff::av_hwframe_ctx_alloc(hw_device);
|
||||
if frames_ref.is_null() {
|
||||
ff::av_buffer_unref(&mut hw_device);
|
||||
return Err("av_hwframe_ctx_alloc failed".into());
|
||||
}
|
||||
{
|
||||
let fctx = (*frames_ref).data as *mut ff::AVHWFramesContext;
|
||||
(*fctx).format = ff::AVPixelFormat::AV_PIX_FMT_VAAPI;
|
||||
(*fctx).sw_format = ff::AVPixelFormat::AV_PIX_FMT_NV12;
|
||||
(*fctx).width = width as i32;
|
||||
(*fctx).height = height as i32;
|
||||
(*fctx).initial_pool_size = 2;
|
||||
}
|
||||
if ff::av_hwframe_ctx_init(frames_ref) < 0 {
|
||||
let mut fr = frames_ref;
|
||||
ff::av_buffer_unref(&mut fr);
|
||||
ff::av_buffer_unref(&mut hw_device);
|
||||
return Err("av_hwframe_ctx_init failed".into());
|
||||
}
|
||||
|
||||
let surf = ff::av_frame_alloc();
|
||||
if ff::av_hwframe_get_buffer(frames_ref, surf, 0) < 0 {
|
||||
ff::av_frame_free(&mut (surf as *mut _));
|
||||
let mut fr = frames_ref;
|
||||
ff::av_buffer_unref(&mut fr);
|
||||
ff::av_buffer_unref(&mut hw_device);
|
||||
return Err("av_hwframe_get_buffer failed".into());
|
||||
}
|
||||
|
||||
let drm = ff::av_frame_alloc();
|
||||
(*drm).format = ff::AVPixelFormat::AV_PIX_FMT_DRM_PRIME as i32;
|
||||
let flags = ff::AV_HWFRAME_MAP_DIRECT as i32
|
||||
| ff::AV_HWFRAME_MAP_READ as i32
|
||||
| ff::AV_HWFRAME_MAP_WRITE as i32;
|
||||
let r = ff::av_hwframe_map(drm, surf, flags);
|
||||
if r < 0 {
|
||||
ff::av_frame_free(&mut (drm as *mut _));
|
||||
ff::av_frame_free(&mut (surf as *mut _));
|
||||
let mut fr = frames_ref;
|
||||
ff::av_buffer_unref(&mut fr);
|
||||
ff::av_buffer_unref(&mut hw_device);
|
||||
return Err(format!("av_hwframe_map(DRM_PRIME) failed: {r}"));
|
||||
}
|
||||
|
||||
let desc = (*drm).data[0] as *const ff::AVDRMFrameDescriptor;
|
||||
let mut s = format!("VAAPI NV12 {width}x{height} surface as DRM-PRIME:\n");
|
||||
s += &format!(" nb_objects = {}\n", (*desc).nb_objects);
|
||||
for o in 0..(*desc).nb_objects as usize {
|
||||
let obj = &(*desc).objects[o];
|
||||
s += &format!(
|
||||
" object[{o}]: fd={} size={} format_modifier=0x{:016x}{}\n",
|
||||
obj.fd,
|
||||
obj.size,
|
||||
obj.format_modifier,
|
||||
if obj.format_modifier == 0 { " (LINEAR)" } else { " (tiled)" },
|
||||
);
|
||||
}
|
||||
s += &format!(" nb_layers = {}\n", (*desc).nb_layers);
|
||||
for l in 0..(*desc).nb_layers as usize {
|
||||
let lay = &(*desc).layers[l];
|
||||
let f = lay.format;
|
||||
let fourcc = [(f & 0xff) as u8, ((f >> 8) & 0xff) as u8, ((f >> 16) & 0xff) as u8, ((f >> 24) & 0xff) as u8];
|
||||
s += &format!(
|
||||
" layer[{l}]: format='{}' (0x{:08x}) nb_planes={}\n",
|
||||
String::from_utf8_lossy(&fourcc),
|
||||
f,
|
||||
lay.nb_planes,
|
||||
);
|
||||
for p in 0..lay.nb_planes as usize {
|
||||
let pl = &lay.planes[p];
|
||||
s += &format!(
|
||||
" plane[{p}]: object_index={} offset={} pitch={}\n",
|
||||
pl.object_index, pl.offset, pl.pitch,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
ff::av_frame_free(&mut (drm as *mut _));
|
||||
ff::av_frame_free(&mut (surf as *mut _));
|
||||
let mut fr = frames_ref;
|
||||
ff::av_buffer_unref(&mut fr);
|
||||
ff::av_buffer_unref(&mut hw_device);
|
||||
Ok(s)
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode NV12 frames with `h264_vaapi` and write the raw Annex-B H.264 to `out_path`.
|
||||
/// Returns the number of encoded packets. `Err` (rather than panic) when VAAPI/the
|
||||
/// encoder is unavailable, so callers can fall back.
|
||||
pub fn encode_nv12_to_file(
|
||||
width: u32,
|
||||
height: u32,
|
||||
frames: &[Vec<u8>],
|
||||
framerate: i32,
|
||||
out_path: &str,
|
||||
) -> Result<usize, String> {
|
||||
unsafe {
|
||||
// 1. VAAPI device.
|
||||
let mut hw_device: *mut ff::AVBufferRef = ptr::null_mut();
|
||||
let node = CString::new("/dev/dri/renderD128").unwrap();
|
||||
let r = ff::av_hwdevice_ctx_create(
|
||||
&mut hw_device,
|
||||
ff::AVHWDeviceType::AV_HWDEVICE_TYPE_VAAPI,
|
||||
node.as_ptr(),
|
||||
ptr::null_mut(),
|
||||
0,
|
||||
);
|
||||
if r < 0 {
|
||||
return Err(format!("av_hwdevice_ctx_create(VAAPI) failed: {r}"));
|
||||
}
|
||||
|
||||
let cleanup_dev = |dev: *mut ff::AVBufferRef| {
|
||||
let mut d = dev;
|
||||
ff::av_buffer_unref(&mut d);
|
||||
};
|
||||
|
||||
// 2. Encoder.
|
||||
let name = CString::new("h264_vaapi").unwrap();
|
||||
let codec = ff::avcodec_find_encoder_by_name(name.as_ptr());
|
||||
if codec.is_null() {
|
||||
cleanup_dev(hw_device);
|
||||
return Err("encoder h264_vaapi not found in this FFmpeg build".into());
|
||||
}
|
||||
let enc = ff::avcodec_alloc_context3(codec);
|
||||
if enc.is_null() {
|
||||
cleanup_dev(hw_device);
|
||||
return Err("avcodec_alloc_context3 failed".into());
|
||||
}
|
||||
(*enc).width = width as i32;
|
||||
(*enc).height = height as i32;
|
||||
(*enc).time_base = ff::AVRational { num: 1, den: framerate };
|
||||
(*enc).framerate = ff::AVRational { num: framerate, den: 1 };
|
||||
(*enc).pix_fmt = ff::AVPixelFormat::AV_PIX_FMT_VAAPI;
|
||||
|
||||
// 3. HW frames context (VAAPI surfaces with NV12 sw layout).
|
||||
let frames_ref = ff::av_hwframe_ctx_alloc(hw_device);
|
||||
if frames_ref.is_null() {
|
||||
ff::avcodec_free_context(&mut (enc as *mut _));
|
||||
cleanup_dev(hw_device);
|
||||
return Err("av_hwframe_ctx_alloc failed".into());
|
||||
}
|
||||
{
|
||||
let fctx = (*frames_ref).data as *mut ff::AVHWFramesContext;
|
||||
(*fctx).format = ff::AVPixelFormat::AV_PIX_FMT_VAAPI;
|
||||
(*fctx).sw_format = ff::AVPixelFormat::AV_PIX_FMT_NV12;
|
||||
(*fctx).width = width as i32;
|
||||
(*fctx).height = height as i32;
|
||||
(*fctx).initial_pool_size = 8;
|
||||
}
|
||||
let r = ff::av_hwframe_ctx_init(frames_ref);
|
||||
if r < 0 {
|
||||
let mut fr = frames_ref;
|
||||
ff::av_buffer_unref(&mut fr);
|
||||
ff::avcodec_free_context(&mut (enc as *mut _));
|
||||
cleanup_dev(hw_device);
|
||||
return Err(format!("av_hwframe_ctx_init failed: {r}"));
|
||||
}
|
||||
(*enc).hw_frames_ctx = ff::av_buffer_ref(frames_ref);
|
||||
|
||||
// 4. Open.
|
||||
let r = ff::avcodec_open2(enc, codec, ptr::null_mut());
|
||||
if r < 0 {
|
||||
let mut fr = frames_ref;
|
||||
ff::av_buffer_unref(&mut fr);
|
||||
ff::avcodec_free_context(&mut (enc as *mut _));
|
||||
cleanup_dev(hw_device);
|
||||
return Err(format!("avcodec_open2(h264_vaapi) failed: {r}"));
|
||||
}
|
||||
|
||||
let mut out: Vec<u8> = Vec::new();
|
||||
let pkt = ff::av_packet_alloc();
|
||||
let mut count = 0usize;
|
||||
|
||||
// Drain helper: pull packets and append to `out`.
|
||||
let drain = |enc: *mut ff::AVCodecContext, out: &mut Vec<u8>, count: &mut usize| -> Result<(), String> {
|
||||
loop {
|
||||
let r = ff::avcodec_receive_packet(enc, pkt);
|
||||
if r == averror(libc::EAGAIN) || r == ff::AVERROR_EOF {
|
||||
break;
|
||||
}
|
||||
if r < 0 {
|
||||
return Err(format!("avcodec_receive_packet failed: {r}"));
|
||||
}
|
||||
let data = std::slice::from_raw_parts((*pkt).data, (*pkt).size as usize);
|
||||
out.extend_from_slice(data);
|
||||
*count += 1;
|
||||
ff::av_packet_unref(pkt);
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
|
||||
let mut err: Option<String> = None;
|
||||
for (i, nv12) in frames.iter().enumerate() {
|
||||
// Software NV12 frame.
|
||||
let sw = ff::av_frame_alloc();
|
||||
(*sw).format = ff::AVPixelFormat::AV_PIX_FMT_NV12 as i32;
|
||||
(*sw).width = width as i32;
|
||||
(*sw).height = height as i32;
|
||||
if ff::av_frame_get_buffer(sw, 0) < 0 {
|
||||
err = Some("av_frame_get_buffer(sw) failed".into());
|
||||
ff::av_frame_free(&mut (sw as *mut _));
|
||||
break;
|
||||
}
|
||||
fill_nv12(sw, nv12, width, height);
|
||||
|
||||
// VAAPI surface frame + upload.
|
||||
let hw = ff::av_frame_alloc();
|
||||
if ff::av_hwframe_get_buffer(frames_ref, hw, 0) < 0 {
|
||||
err = Some("av_hwframe_get_buffer failed".into());
|
||||
ff::av_frame_free(&mut (sw as *mut _));
|
||||
ff::av_frame_free(&mut (hw as *mut _));
|
||||
break;
|
||||
}
|
||||
if ff::av_hwframe_transfer_data(hw, sw, 0) < 0 {
|
||||
err = Some("av_hwframe_transfer_data failed".into());
|
||||
ff::av_frame_free(&mut (sw as *mut _));
|
||||
ff::av_frame_free(&mut (hw as *mut _));
|
||||
break;
|
||||
}
|
||||
(*hw).pts = i as i64;
|
||||
|
||||
let r = ff::avcodec_send_frame(enc, hw);
|
||||
ff::av_frame_free(&mut (sw as *mut _));
|
||||
ff::av_frame_free(&mut (hw as *mut _));
|
||||
if r < 0 {
|
||||
err = Some(format!("avcodec_send_frame failed: {r}"));
|
||||
break;
|
||||
}
|
||||
if let Err(e) = drain(enc, &mut out, &mut count) {
|
||||
err = Some(e);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Flush.
|
||||
if err.is_none() {
|
||||
ff::avcodec_send_frame(enc, ptr::null_mut());
|
||||
if let Err(e) = drain(enc, &mut out, &mut count) {
|
||||
err = Some(e);
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup.
|
||||
ff::av_packet_free(&mut (pkt as *mut _));
|
||||
let mut fr = frames_ref;
|
||||
ff::av_buffer_unref(&mut fr);
|
||||
ff::avcodec_free_context(&mut (enc as *mut _));
|
||||
cleanup_dev(hw_device);
|
||||
|
||||
if let Some(e) = err {
|
||||
return Err(e);
|
||||
}
|
||||
std::fs::write(out_path, &out).map_err(|e| format!("write {out_path}: {e}"))?;
|
||||
Ok(count)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
//! Custom wgpu Vulkan device that additionally enables `VK_EXT_image_drm_format_modifier`
|
||||
//! (plus the external-memory extensions wgpu-hal already turns on), so we can import a
|
||||
//! tiled VAAPI NV12 DMA-BUF as a Vulkan image. wgpu's safe API can't add arbitrary device
|
||||
//! extensions, so we build the `VkDevice` ourselves and wrap it via `device_from_raw`.
|
||||
//!
|
||||
//! All `unsafe` is contained here. Returns owned handles the caller must keep alive
|
||||
//! together (instance → adapter → device/queue).
|
||||
|
||||
use ash::vk;
|
||||
use std::ffi::CStr;
|
||||
|
||||
/// A wgpu device/queue backed by a hand-built Vulkan device with DMA-BUF import enabled.
|
||||
pub struct DrmDevice {
|
||||
// Order matters for drop; wgpu handles refcount internally but we keep these owned.
|
||||
pub device: wgpu::Device,
|
||||
pub queue: wgpu::Queue,
|
||||
pub adapter: wgpu::Adapter,
|
||||
pub instance: wgpu::Instance,
|
||||
/// The raw VkDevice (for the ash image-import calls in `dmabuf.rs`).
|
||||
pub raw_device: ash::Device,
|
||||
pub raw_physical_device: vk::PhysicalDevice,
|
||||
pub raw_instance: ash::Instance,
|
||||
}
|
||||
|
||||
/// Create a headless DMA-BUF-import device (encoder/decoder), or `Err` if Vulkan/the extension
|
||||
/// isn't available (caller falls back).
|
||||
pub fn create() -> Result<DrmDevice, String> {
|
||||
unsafe { create_inner(false) }
|
||||
}
|
||||
|
||||
/// Like [`create`] but also enables `VK_KHR_swapchain` so the device can present to a window —
|
||||
/// for use as the editor's **shared** wgpu device (eframe + compositor + decode + encode all on
|
||||
/// one device, so hardware-decoded DMA-BUF textures are usable by the preview compositor).
|
||||
pub fn create_windowed() -> Result<DrmDevice, String> {
|
||||
unsafe { create_inner(true) }
|
||||
}
|
||||
|
||||
unsafe fn create_inner(windowed: bool) -> Result<DrmDevice, String> {
|
||||
use wgpu_hal::vulkan::Api as Vk;
|
||||
// Bring the HAL Instance trait into scope for `init` / `enumerate_adapters`.
|
||||
use wgpu_hal::Instance as _;
|
||||
|
||||
// 1. HAL instance.
|
||||
let hal_instance = wgpu_hal::vulkan::Instance::init(&wgpu_hal::InstanceDescriptor {
|
||||
name: "gpu-video-encoder",
|
||||
flags: wgpu::InstanceFlags::empty(),
|
||||
memory_budget_thresholds: Default::default(),
|
||||
backend_options: Default::default(),
|
||||
})
|
||||
.map_err(|e| format!("vulkan instance init failed: {e:?}"))?;
|
||||
|
||||
let ash_instance = hal_instance.shared_instance().raw_instance().clone();
|
||||
|
||||
// 2. Pick an adapter (prefer the integrated/discrete GPU).
|
||||
let mut exposed_adapters = hal_instance.enumerate_adapters(None);
|
||||
if exposed_adapters.is_empty() {
|
||||
return Err("no Vulkan adapters".into());
|
||||
}
|
||||
// Prefer a real GPU over CPU/llvmpipe.
|
||||
exposed_adapters.sort_by_key(|a| match a.info.device_type {
|
||||
wgpu::DeviceType::DiscreteGpu => 0,
|
||||
wgpu::DeviceType::IntegratedGpu => 1,
|
||||
_ => 2,
|
||||
});
|
||||
let exposed = exposed_adapters.into_iter().next().unwrap();
|
||||
let phys = exposed.adapter.raw_physical_device();
|
||||
|
||||
// 3. Queue family with graphics + compute.
|
||||
let qf_props = ash_instance.get_physical_device_queue_family_properties(phys);
|
||||
let family_index = qf_props
|
||||
.iter()
|
||||
.position(|p| {
|
||||
p.queue_flags
|
||||
.contains(vk::QueueFlags::GRAPHICS | vk::QueueFlags::COMPUTE)
|
||||
})
|
||||
.ok_or("no graphics+compute queue family")? as u32;
|
||||
|
||||
// 4. Extensions: what wgpu-hal wants + DRM modifier import set.
|
||||
let mut ext_names: Vec<&'static CStr> =
|
||||
exposed.adapter.required_device_extensions(exposed.features);
|
||||
// Only the genuine extensions; external_memory / bind_memory2 / ycbcr / format_list
|
||||
// are core in Vulkan 1.1+ (this device is 1.3) so they need no enabling.
|
||||
let mut extra: Vec<&'static CStr> = vec![
|
||||
ash::ext::image_drm_format_modifier::NAME,
|
||||
ash::khr::external_memory_fd::NAME,
|
||||
ash::ext::external_memory_dma_buf::NAME,
|
||||
ash::ext::queue_family_foreign::NAME,
|
||||
];
|
||||
// Presentation (windowed shared device only): the WSI surface instance extensions are already
|
||||
// enabled by `Instance::init`; the device needs the swapchain extension to present.
|
||||
if windowed {
|
||||
extra.push(ash::khr::swapchain::NAME);
|
||||
}
|
||||
for e in extra {
|
||||
if !ext_names.contains(&e) {
|
||||
ext_names.push(e);
|
||||
}
|
||||
}
|
||||
let ext_ptrs: Vec<*const i8> = ext_names.iter().map(|c| c.as_ptr()).collect();
|
||||
|
||||
// 5. Enable all supported physical-device features (so wgpu has what it needs) plus
|
||||
// sampler YCbCr conversion (required for the NV12 multi-planar image).
|
||||
let supported = ash_instance.get_physical_device_features(phys);
|
||||
let mut ycbcr =
|
||||
vk::PhysicalDeviceSamplerYcbcrConversionFeatures::default().sampler_ycbcr_conversion(true);
|
||||
|
||||
let priorities = [1.0f32];
|
||||
let queue_info = vk::DeviceQueueCreateInfo::default()
|
||||
.queue_family_index(family_index)
|
||||
.queue_priorities(&priorities);
|
||||
let queue_infos = [queue_info];
|
||||
|
||||
let create_info = vk::DeviceCreateInfo::default()
|
||||
.queue_create_infos(&queue_infos)
|
||||
.enabled_extension_names(&ext_ptrs)
|
||||
.enabled_features(&supported)
|
||||
.push_next(&mut ycbcr);
|
||||
|
||||
let ash_device = ash_instance
|
||||
.create_device(phys, &create_info, None)
|
||||
.map_err(|e| format!("vkCreateDevice failed: {e:?}"))?;
|
||||
|
||||
// 6. Wrap the raw device into a hal OpenDevice, then a wgpu device.
|
||||
let open_device = exposed
|
||||
.adapter
|
||||
.device_from_raw(
|
||||
ash_device.clone(),
|
||||
None,
|
||||
&ext_names,
|
||||
exposed.features,
|
||||
&wgpu::MemoryHints::default(),
|
||||
family_index,
|
||||
0,
|
||||
)
|
||||
.map_err(|e| format!("device_from_raw failed: {e:?}"))?;
|
||||
|
||||
let raw_physical_device = phys;
|
||||
|
||||
let wgpu_instance = wgpu::Instance::from_hal::<Vk>(hal_instance);
|
||||
let wgpu_adapter = wgpu_instance.create_adapter_from_hal::<Vk>(exposed);
|
||||
let (device, queue) = wgpu_adapter
|
||||
.create_device_from_hal::<Vk>(
|
||||
open_device,
|
||||
&wgpu::DeviceDescriptor {
|
||||
label: Some("drm-import-device"),
|
||||
// R16/Rg16 plane textures for P010 (10-bit HDR) import need this; request it only
|
||||
// when the adapter supports it (else 10-bit falls back to software decode).
|
||||
required_features: wgpu_adapter.features()
|
||||
& wgpu::Features::TEXTURE_FORMAT_16BIT_NORM,
|
||||
// Vello's compute pipelines need more than downlevel limits (e.g.
|
||||
// max_storage_buffers_per_shader_stage >= 5). This device only ever runs on a
|
||||
// real VAAPI-capable GPU, so request the adapter's full limits.
|
||||
required_limits: wgpu_adapter.limits(),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.map_err(|e| format!("create_device_from_hal failed: {e:?}"))?;
|
||||
|
||||
Ok(DrmDevice {
|
||||
device,
|
||||
queue,
|
||||
adapter: wgpu_adapter,
|
||||
instance: wgpu_instance,
|
||||
raw_device: ash_device,
|
||||
raw_physical_device,
|
||||
raw_instance: ash_instance,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Round-trip: encode solid frames with the zero-copy encoder, then hardware-decode them back
|
||||
//! into a wgpu texture and read the Y plane. Verifies the VAAPI decode → DMA-BUF → wgpu import
|
||||
//! path produces real pixels on the GPU. Skips when VAAPI is unavailable.
|
||||
|
||||
#![cfg(target_os = "linux")]
|
||||
|
||||
use gpu_video_encoder::decoder::VaapiDecoder;
|
||||
use gpu_video_encoder::encoder::ZeroCopyEncoder;
|
||||
|
||||
#[test]
|
||||
fn vaapi_decode_roundtrip() {
|
||||
// 256-wide so the R8 Y readback row (256 B) is already 256-aligned.
|
||||
let (w, h) = (256u32, 256u32);
|
||||
let out = std::env::temp_dir().join("gpu_video_encoder_decode_rt.mp4");
|
||||
let _ = std::fs::remove_file(&out);
|
||||
|
||||
// --- Encode 10 frames of solid mid-gray. Full range → Y == luma ≈ 128. ---
|
||||
{
|
||||
let mut enc = match ZeroCopyEncoder::new(w, h, 30, 4000, &out, true) {
|
||||
Ok(e) => e,
|
||||
Err(e) => {
|
||||
eprintln!("[decode-rt] encode unavailable, skipping: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let device = enc.device();
|
||||
let src = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("gray"),
|
||||
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
let gray = vec![128u8; (w * h * 4) as usize];
|
||||
enc.queue().write_texture(
|
||||
wgpu::TexelCopyTextureInfo { texture: &src, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
&gray,
|
||||
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 4), rows_per_image: Some(h) },
|
||||
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
);
|
||||
for _ in 0..10 {
|
||||
enc.encode_rgba(&src).expect("encode_rgba");
|
||||
}
|
||||
enc.finish().expect("finish");
|
||||
}
|
||||
|
||||
// --- Decode it back on the GPU. ---
|
||||
let mut dec = match VaapiDecoder::new(&out) {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
eprintln!("[decode-rt] decode unavailable, skipping: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let frame = dec.next_frame().expect("next_frame").expect("expected at least one frame");
|
||||
assert_eq!(frame.y().width(), w, "decoded Y width");
|
||||
assert_eq!(frame.y().height(), h, "decoded Y height");
|
||||
|
||||
// Read back the Y plane (R8) and check it's ≈ the gray we encoded.
|
||||
let device = dec.device();
|
||||
let buf = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("y_readback"),
|
||||
size: (w * h) as u64,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut cmd = device.create_command_encoder(&Default::default());
|
||||
cmd.copy_texture_to_buffer(
|
||||
wgpu::TexelCopyTextureInfo { texture: frame.y(), mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
wgpu::TexelCopyBufferInfo {
|
||||
buffer: &buf,
|
||||
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w), rows_per_image: Some(h) },
|
||||
},
|
||||
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
);
|
||||
dec.queue().submit(Some(cmd.finish()));
|
||||
buf.slice(..).map_async(wgpu::MapMode::Read, |_| {});
|
||||
let _ = device.poll(wgpu::PollType::wait_indefinitely());
|
||||
|
||||
let data = buf.slice(..).get_mapped_range();
|
||||
let mean = data.iter().map(|&b| b as f64).sum::<f64>() / data.len() as f64;
|
||||
eprintln!("[decode-rt] decoded {w}x{h}, mean Y = {mean:.1}");
|
||||
assert!(
|
||||
(mean - 128.0).abs() < 12.0,
|
||||
"mean Y {mean} not ≈ 128 — decode produced wrong pixels"
|
||||
);
|
||||
eprintln!("[decode-rt] ✅ VAAPI decode → wgpu texture verified");
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Step 1 of zero-copy: the custom Vulkan device with DMA-BUF import extensions builds
|
||||
//! and can do a trivial GPU op. Skips (passes) when Vulkan is unavailable.
|
||||
|
||||
#![cfg(target_os = "linux")]
|
||||
|
||||
#[test]
|
||||
fn drm_device_creates_and_works() {
|
||||
let dev = match gpu_video_encoder::vk_device::create() {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
eprintln!("[drm-device] unavailable, skipping: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
eprintln!("[drm-device] created custom Vulkan device OK");
|
||||
|
||||
// Trivial sanity op: write+read a small buffer, proving the wrapped device is usable.
|
||||
let data: Vec<u8> = (0..256u32).map(|i| i as u8).collect();
|
||||
let src = wgpu::util::DeviceExt::create_buffer_init(
|
||||
&dev.device,
|
||||
&wgpu::util::BufferInitDescriptor {
|
||||
label: Some("src"),
|
||||
contents: &data,
|
||||
usage: wgpu::BufferUsages::COPY_SRC,
|
||||
},
|
||||
);
|
||||
let dst = dev.device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("dst"),
|
||||
size: 256,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let mut enc = dev.device.create_command_encoder(&Default::default());
|
||||
enc.copy_buffer_to_buffer(&src, 0, &dst, 0, 256);
|
||||
dev.queue.submit(Some(enc.finish()));
|
||||
let slice = dst.slice(..);
|
||||
slice.map_async(wgpu::MapMode::Read, |_| {});
|
||||
let _ = dev.device.poll(wgpu::PollType::wait_indefinitely());
|
||||
let got = slice.get_mapped_range().to_vec();
|
||||
assert_eq!(got, data, "round-trip through custom device failed");
|
||||
eprintln!("[drm-device] buffer round-trip OK on custom device");
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//! Real-hardware test: run the RGBA→NV12 compute on the GPU and check it byte-matches
|
||||
//! the CPU reference. Skips (passes) if no GPU adapter is available.
|
||||
|
||||
use gpu_video_encoder::nv12::{cpu_reference, nv12_len, Nv12Converter};
|
||||
|
||||
fn device_queue() -> Option<(wgpu::Device, wgpu::Queue)> {
|
||||
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
|
||||
backends: wgpu::Backends::VULKAN | wgpu::Backends::GL,
|
||||
..Default::default()
|
||||
});
|
||||
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
|
||||
power_preference: wgpu::PowerPreference::HighPerformance,
|
||||
force_fallback_adapter: false,
|
||||
compatible_surface: None,
|
||||
}))
|
||||
.ok()?;
|
||||
pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
|
||||
label: Some("nv12-test"),
|
||||
required_features: wgpu::Features::empty(),
|
||||
required_limits: wgpu::Limits::downlevel_defaults(),
|
||||
..Default::default()
|
||||
}))
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// A deterministic, varied RGBA pattern so luma and 2x2 chroma subsampling are exercised.
|
||||
fn pattern(w: u32, h: u32) -> Vec<u8> {
|
||||
let mut v = Vec::with_capacity((w * h * 4) as usize);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
v.push(((x * 37 + y * 11) % 256) as u8); // R
|
||||
v.push(((x * 5 + y * 53) % 256) as u8); // G
|
||||
v.push(((x * 97 + y * 17) % 256) as u8); // B
|
||||
v.push(255);
|
||||
}
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gpu_nv12_matches_cpu_reference() {
|
||||
let Some((device, queue)) = device_queue() else {
|
||||
eprintln!("[gpu_nv12] no GPU adapter; skipping");
|
||||
return;
|
||||
};
|
||||
|
||||
let (w, h) = (64u32, 16u32);
|
||||
let rgba = pattern(w, h);
|
||||
|
||||
// Source RGBA texture.
|
||||
let tex = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("src_rgba"),
|
||||
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo {
|
||||
texture: &tex,
|
||||
mip_level: 0,
|
||||
origin: wgpu::Origin3d::ZERO,
|
||||
aspect: wgpu::TextureAspect::All,
|
||||
},
|
||||
&rgba,
|
||||
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 4), rows_per_image: Some(h) },
|
||||
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
);
|
||||
let view = tex.create_view(&Default::default());
|
||||
|
||||
let len = nv12_len(w, h) as u64;
|
||||
let out = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("nv12_out"),
|
||||
size: len,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let staging = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("nv12_staging"),
|
||||
size: len,
|
||||
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
|
||||
let conv = Nv12Converter::new(&device);
|
||||
let mut enc = device.create_command_encoder(&Default::default());
|
||||
conv.convert(&device, &mut enc, &view, &out, w, h);
|
||||
enc.copy_buffer_to_buffer(&out, 0, &staging, 0, len);
|
||||
queue.submit(Some(enc.finish()));
|
||||
|
||||
let slice = staging.slice(..);
|
||||
slice.map_async(wgpu::MapMode::Read, |_| {});
|
||||
let _ = device.poll(wgpu::PollType::wait_indefinitely());
|
||||
let gpu = slice.get_mapped_range().to_vec();
|
||||
|
||||
let cpu = cpu_reference(&rgba, w, h);
|
||||
assert_eq!(gpu.len(), cpu.len(), "length mismatch");
|
||||
|
||||
// Allow ±1 for rounding differences between GPU and CPU float paths.
|
||||
let mut max_diff = 0i32;
|
||||
let mut nbad = 0;
|
||||
for (i, (g, c)) in gpu.iter().zip(cpu.iter()).enumerate() {
|
||||
let d = (*g as i32 - *c as i32).abs();
|
||||
max_diff = max_diff.max(d);
|
||||
if d > 1 {
|
||||
nbad += 1;
|
||||
if nbad <= 8 {
|
||||
eprintln!("[gpu_nv12] byte {i}: gpu={g} cpu={c} (diff {d})");
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!("[gpu_nv12] {}x{} NV12, max byte diff = {max_diff}", w, h);
|
||||
assert_eq!(nbad, 0, "{nbad} bytes differ from CPU reference by >1");
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//! Level-1 spike: prove `h264_vaapi` encodes NV12 in this environment. Skips (passes)
|
||||
//! when VAAPI isn't available so it's a no-op on CI/macOS/Windows.
|
||||
|
||||
#![cfg(target_os = "linux")]
|
||||
|
||||
use gpu_video_encoder::nv12::{cpu_reference, nv12_len};
|
||||
use gpu_video_encoder::vaapi::encode_nv12_to_file;
|
||||
|
||||
/// A moving-gradient RGBA pattern → NV12 via the CPU reference, so we feed valid frames.
|
||||
fn nv12_frames(w: u32, h: u32, n: usize) -> Vec<Vec<u8>> {
|
||||
(0..n)
|
||||
.map(|f| {
|
||||
let mut rgba = Vec::with_capacity((w * h * 4) as usize);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
rgba.push(((x + f as u32 * 4) % 256) as u8);
|
||||
rgba.push(((y + f as u32 * 2) % 256) as u8);
|
||||
rgba.push(((x + y) % 256) as u8);
|
||||
rgba.push(255);
|
||||
}
|
||||
}
|
||||
let v = cpu_reference(&rgba, w, h);
|
||||
assert_eq!(v.len(), nv12_len(w, h));
|
||||
v
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vaapi_surface_drm_layout() {
|
||||
match gpu_video_encoder::vaapi::probe_surface_drm(1920, 1088) {
|
||||
Ok(s) => eprintln!("[vaapi-drm]\n{s}"),
|
||||
Err(e) => eprintln!("[vaapi-drm] unavailable, skipping: {e}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vaapi_h264_encode_smoke() {
|
||||
let (w, h) = (320u32, 240u32);
|
||||
let frames = nv12_frames(w, h, 30);
|
||||
let out = std::env::temp_dir().join("gpu_video_encoder_vaapi_smoke.h264");
|
||||
let out_str = out.to_str().unwrap();
|
||||
|
||||
match encode_nv12_to_file(w, h, &frames, 30, out_str) {
|
||||
Ok(packets) => {
|
||||
let meta = std::fs::metadata(&out).expect("output file missing");
|
||||
eprintln!(
|
||||
"[vaapi] encoded {} packets, {} bytes -> {}",
|
||||
packets,
|
||||
meta.len(),
|
||||
out_str
|
||||
);
|
||||
assert!(packets > 0, "no packets produced");
|
||||
assert!(meta.len() > 0, "empty output file");
|
||||
// First frame should be an IDR; Annex-B starts with a start code.
|
||||
let head = std::fs::read(&out).unwrap();
|
||||
assert!(
|
||||
head.starts_with(&[0, 0, 0, 1]) || head.starts_with(&[0, 0, 1]),
|
||||
"output is not Annex-B H.264 (no start code)"
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("[vaapi] unavailable, skipping: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
//! End-to-end zero-copy proof: import a VAAPI NV12 surface as wgpu textures, render
|
||||
//! known values into them via Vulkan, read the surface back, and verify the bytes —
|
||||
//! proving the GPU wrote straight into the encoder's surface with no CPU upload.
|
||||
|
||||
#![cfg(target_os = "linux")]
|
||||
|
||||
use gpu_video_encoder::{dmabuf, nv12, render_nv12, vaapi, vk_device};
|
||||
|
||||
/// Render a real RGBA frame into the VAAPI surface (zero-copy) and verify the surface's
|
||||
/// NV12 matches the CPU reference for that frame.
|
||||
#[test]
|
||||
fn zerocopy_real_frame_render() {
|
||||
let drm = match vk_device::create() {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
eprintln!("[zerocopy-real] no Vulkan, skipping: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let (w, h) = (640u32, 480u32);
|
||||
let surf = match vaapi::MappedSurface::alloc(w, h) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("[zerocopy-real] no VAAPI, skipping: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let imported = dmabuf::import(&drm, &surf).expect("import");
|
||||
|
||||
// A varied RGBA pattern.
|
||||
let mut rgba = Vec::with_capacity((w * h * 4) as usize);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
rgba.push(((x * 3 + y) % 256) as u8);
|
||||
rgba.push(((x + y * 2) % 256) as u8);
|
||||
rgba.push(((x * 2 + y * 3) % 256) as u8);
|
||||
rgba.push(255);
|
||||
}
|
||||
}
|
||||
let src = drm.device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("rgba_src"),
|
||||
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
drm.queue.write_texture(
|
||||
wgpu::TexelCopyTextureInfo { texture: &src, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
&rgba,
|
||||
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 4), rows_per_image: Some(h) },
|
||||
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
);
|
||||
|
||||
let conv = render_nv12::Rgba2Nv12::new(&drm.device, true);
|
||||
let src_view = src.create_view(&Default::default());
|
||||
let y_view = imported.y().create_view(&Default::default());
|
||||
let uv_view = imported.uv().create_view(&Default::default());
|
||||
let mut enc = drm.device.create_command_encoder(&Default::default());
|
||||
conv.convert(&drm.device, &mut enc, &src_view, &y_view, &uv_view);
|
||||
drm.queue.submit(Some(enc.finish()));
|
||||
let _ = drm.device.poll(wgpu::PollType::wait_indefinitely());
|
||||
|
||||
let got = surf.readback_nv12().expect("readback");
|
||||
let want = nv12::cpu_reference(&rgba, w, h);
|
||||
assert_eq!(got.len(), want.len());
|
||||
let mut max_diff = 0i32;
|
||||
let mut nbad = 0;
|
||||
for (g, c) in got.iter().zip(want.iter()) {
|
||||
let d = (*g as i32 - *c as i32).abs();
|
||||
max_diff = max_diff.max(d);
|
||||
if d > 2 {
|
||||
nbad += 1;
|
||||
}
|
||||
}
|
||||
eprintln!("[zerocopy-real] {}x{} real-frame render, max diff={max_diff}, bad={nbad}/{}", w, h, got.len());
|
||||
assert!(nbad * 100 < got.len(), "too many bytes differ from CPU NV12 reference");
|
||||
eprintln!("[zerocopy-real] ✅ real RGBA frame rendered into VAAPI surface, NV12 matches reference");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zerocopy_render_into_vaapi_surface() {
|
||||
let drm = match vk_device::create() {
|
||||
Ok(d) => d,
|
||||
Err(e) => {
|
||||
eprintln!("[zerocopy] no Vulkan device, skipping: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let surf = match vaapi::MappedSurface::alloc(640, 480) {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("[zerocopy] no VAAPI surface, skipping: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
eprintln!(
|
||||
"[zerocopy] surface: modifier=0x{:016x} y(off={},pitch={}) uv(off={},pitch={}) size={}",
|
||||
surf.modifier, surf.y_offset, surf.y_pitch, surf.uv_offset, surf.uv_pitch, surf.size
|
||||
);
|
||||
|
||||
let imported = match dmabuf::import(&drm, &surf) {
|
||||
Ok(i) => i,
|
||||
Err(e) => panic!("dma-buf import failed: {e}"),
|
||||
};
|
||||
eprintln!("[zerocopy] imported surface as wgpu Y(R8) + UV(RG8) textures");
|
||||
|
||||
// Render known constants via clear: Y=0.5(->128), U=0.25(->64), V=0.75(->191).
|
||||
let y_view = imported.y().create_view(&Default::default());
|
||||
let uv_view = imported.uv().create_view(&Default::default());
|
||||
let mut enc = drm.device.create_command_encoder(&Default::default());
|
||||
{
|
||||
enc.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("clear-y"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &y_view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.5, g: 0.0, b: 0.0, a: 0.0 }),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
});
|
||||
enc.begin_render_pass(&wgpu::RenderPassDescriptor {
|
||||
label: Some("clear-uv"),
|
||||
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
|
||||
view: &uv_view,
|
||||
resolve_target: None,
|
||||
depth_slice: None,
|
||||
ops: wgpu::Operations {
|
||||
load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.25, g: 0.75, b: 0.0, a: 0.0 }),
|
||||
store: wgpu::StoreOp::Store,
|
||||
},
|
||||
})],
|
||||
depth_stencil_attachment: None,
|
||||
timestamp_writes: None,
|
||||
occlusion_query_set: None,
|
||||
});
|
||||
}
|
||||
drm.queue.submit(Some(enc.finish()));
|
||||
let _ = drm.device.poll(wgpu::PollType::wait_indefinitely());
|
||||
|
||||
// Read the VAAPI surface back and check what the GPU wrote.
|
||||
let nv12 = surf.readback_nv12().expect("readback");
|
||||
let (w, h) = (640usize, 480usize);
|
||||
let y_plane = &nv12[..w * h];
|
||||
let uv_plane = &nv12[w * h..];
|
||||
|
||||
let near = |v: u8, t: i32| (v as i32 - t).abs() <= 3;
|
||||
let y_ok = y_plane.iter().filter(|&&v| near(v, 128)).count();
|
||||
let u_ok = uv_plane.iter().step_by(2).filter(|&&v| near(v, 64)).count();
|
||||
let v_ok = uv_plane.iter().skip(1).step_by(2).filter(|&&v| near(v, 191)).count();
|
||||
eprintln!(
|
||||
"[zerocopy] Y~128: {}/{}, U~64: {}/{}, V~191: {}/{}",
|
||||
y_ok, w * h, u_ok, uv_plane.len() / 2, v_ok, uv_plane.len() / 2
|
||||
);
|
||||
|
||||
let frac = |ok: usize, n: usize| ok as f64 / n as f64;
|
||||
assert!(frac(y_ok, w * h) > 0.98, "Y plane not the rendered value (sample {:?})", &y_plane[..8]);
|
||||
assert!(frac(u_ok, uv_plane.len() / 2) > 0.98, "U not rendered value");
|
||||
assert!(frac(v_ok, uv_plane.len() / 2) > 0.98, "V not rendered value");
|
||||
eprintln!("[zerocopy] ✅ GPU rendered straight into the VAAPI surface (verified via readback)");
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
//! Capstone: encode RGBA frames fully zero-copy (GPU render → VAAPI surface → h264_vaapi)
|
||||
//! and verify the output is real H.264. Skips when VAAPI is unavailable.
|
||||
|
||||
#![cfg(target_os = "linux")]
|
||||
|
||||
use gpu_video_encoder::encoder::ZeroCopyEncoder;
|
||||
|
||||
#[test]
|
||||
fn zerocopy_encode_h264() {
|
||||
let (w, h) = (640u32, 480u32);
|
||||
let out = std::env::temp_dir().join("gpu_video_encoder_zerocopy.mp4");
|
||||
let _ = std::fs::remove_file(&out);
|
||||
let mut enc = match ZeroCopyEncoder::new(w, h, 30, 4000, &out, false) {
|
||||
Ok(e) => e,
|
||||
Err(e) => {
|
||||
eprintln!("[zc-encode] unavailable, skipping: {e}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// Build one reusable RGBA source texture; update it per frame with a moving pattern.
|
||||
let device = enc.device();
|
||||
let src = device.create_texture(&wgpu::TextureDescriptor {
|
||||
label: Some("rgba"),
|
||||
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
mip_level_count: 1,
|
||||
sample_count: 1,
|
||||
dimension: wgpu::TextureDimension::D2,
|
||||
format: wgpu::TextureFormat::Rgba8Unorm,
|
||||
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
|
||||
view_formats: &[],
|
||||
});
|
||||
|
||||
let n = 30;
|
||||
for f in 0..n {
|
||||
let mut rgba = Vec::with_capacity((w * h * 4) as usize);
|
||||
for y in 0..h {
|
||||
for x in 0..w {
|
||||
rgba.push(((x + f * 8) % 256) as u8);
|
||||
rgba.push(((y + f * 4) % 256) as u8);
|
||||
rgba.push(((x + y) % 256) as u8);
|
||||
rgba.push(255);
|
||||
}
|
||||
}
|
||||
enc.queue().write_texture(
|
||||
wgpu::TexelCopyTextureInfo { texture: &src, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
|
||||
&rgba,
|
||||
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 4), rows_per_image: Some(h) },
|
||||
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
|
||||
);
|
||||
enc.encode_rgba(&src).expect("encode_rgba");
|
||||
}
|
||||
|
||||
enc.finish().expect("finish");
|
||||
let meta = std::fs::metadata(&out).expect("output .mp4 missing");
|
||||
eprintln!("[zc-encode] {} frames -> {} bytes mp4 at {}", n, meta.len(), out.display());
|
||||
assert!(meta.len() > 1000, "implausibly small output");
|
||||
|
||||
// ffprobe-verify the container: H.264 stream, right dims, ~n frames.
|
||||
let o = std::process::Command::new("ffprobe")
|
||||
.args([
|
||||
"-hide_banner", "-v", "error", "-count_frames",
|
||||
"-show_entries", "stream=codec_name,width,height,nb_read_frames",
|
||||
"-of", "default=noprint_wrappers=1",
|
||||
])
|
||||
.arg(&out)
|
||||
.output()
|
||||
.expect("run ffprobe");
|
||||
let s = String::from_utf8_lossy(&o.stdout);
|
||||
eprintln!("[zc-encode] ffprobe:\n{s}");
|
||||
assert!(s.contains("codec_name=h264"), "ffprobe didn't see H.264");
|
||||
assert!(s.contains(&format!("width={w}")), "wrong width");
|
||||
assert!(s.contains(&format!("height={h}")), "wrong height");
|
||||
assert!(s.contains(&format!("nb_read_frames={n}")), "expected {n} frames");
|
||||
eprintln!("[zc-encode] ✅ zero-copy H.264 mp4 encode verified");
|
||||
}
|
||||
@@ -18,6 +18,9 @@ bytemuck = { version = "1.14", features = ["derive"] }
|
||||
kurbo = { workspace = true }
|
||||
vello = { workspace = true }
|
||||
|
||||
# Text layout/shaping (text layers)
|
||||
parley = { workspace = true }
|
||||
|
||||
# Image decoding for image fills
|
||||
image = { workspace = true }
|
||||
|
||||
@@ -29,6 +32,8 @@ daw-backend = { path = "../../daw-backend" }
|
||||
|
||||
# Video decoding
|
||||
ffmpeg-next = "8.0"
|
||||
# AVIO-over-Read+Seek shim: decode packed video by streaming from the SQLite blob.
|
||||
ffmpeg-blob-io = { path = "../../ffmpeg-blob-io" }
|
||||
lru = "0.12"
|
||||
|
||||
# File I/O
|
||||
@@ -73,3 +78,6 @@ windows-sys = { version = "0.60", features = [
|
||||
version = "0.11"
|
||||
|
||||
[dev-dependencies]
|
||||
# For the packed-video streaming integration test (blob -> AVIO -> ffmpeg Input).
|
||||
ffmpeg-blob-io = { path = "../../ffmpeg-blob-io" }
|
||||
ffmpeg-next = "8.0"
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,14 @@
|
||||
Bundled fonts for Lightningbeam text layers
|
||||
===========================================
|
||||
|
||||
These are the Liberation fonts, used as the built-in serif / sans-serif / monospaced
|
||||
families so text renders deterministically without depending on system fonts:
|
||||
|
||||
LiberationSans-Regular.ttf
|
||||
LiberationSerif-Regular.ttf
|
||||
LiberationMono-Regular.ttf
|
||||
|
||||
License: SIL Open Font License, Version 1.1.
|
||||
Copyright (c) Red Hat, Inc., with Reserved Font Name "Liberation".
|
||||
Full license text: https://openfontlicense.org/ (also distributed with the Liberation
|
||||
fonts package as its OFL.txt / LICENSE).
|
||||
@@ -104,7 +104,7 @@ impl Action for AddClipInstanceAction {
|
||||
AnyLayer::Group(_) => {
|
||||
return Err("Cannot add clip instances directly to group layers".to_string());
|
||||
}
|
||||
AnyLayer::Raster(_) => {
|
||||
AnyLayer::Raster(_) | AnyLayer::Text(_) => {
|
||||
return Err("Cannot add clip instances directly to group layers".to_string());
|
||||
}
|
||||
}
|
||||
@@ -145,8 +145,8 @@ impl Action for AddClipInstanceAction {
|
||||
AnyLayer::Group(_) => {
|
||||
// Group layers don't have clip instances, nothing to rollback
|
||||
}
|
||||
AnyLayer::Raster(_) => {
|
||||
// Raster layers don't have clip instances, nothing to rollback
|
||||
AnyLayer::Raster(_) | AnyLayer::Text(_) => {
|
||||
// Raster/text layers don't have clip instances, nothing to rollback
|
||||
}
|
||||
}
|
||||
self.executed = false;
|
||||
|
||||
@@ -138,6 +138,7 @@ impl Action for AddLayerAction {
|
||||
AnyLayer::Effect(_) => "Add effect layer",
|
||||
AnyLayer::Group(_) => "Add group layer",
|
||||
AnyLayer::Raster(_) => "Add raster layer",
|
||||
AnyLayer::Text(_) => "Add text layer",
|
||||
}
|
||||
.to_string()
|
||||
}
|
||||
|
||||
@@ -23,6 +23,9 @@ pub struct AddShapeAction {
|
||||
stroke_color: Option<ShapeColor>,
|
||||
fill_color: Option<ShapeColor>,
|
||||
is_closed: bool,
|
||||
/// When set, the enclosed region is filled with this image asset (instead of a
|
||||
/// solid colour). The renderer prioritises `image_fill` over colour/gradient.
|
||||
image_fill: Option<Uuid>,
|
||||
description_text: String,
|
||||
/// Snapshot of the graph before insertion (for undo).
|
||||
graph_before: Option<VectorGraph>,
|
||||
@@ -46,15 +49,53 @@ impl AddShapeAction {
|
||||
stroke_color,
|
||||
fill_color,
|
||||
is_closed,
|
||||
image_fill: None,
|
||||
description_text: "Add shape".to_string(),
|
||||
graph_before: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A borderless, axis-aligned rectangle filled with an image asset — the result
|
||||
/// of importing/dropping an image onto a vector layer.
|
||||
pub fn image_rect(
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
x: f64,
|
||||
y: f64,
|
||||
w: f64,
|
||||
h: f64,
|
||||
asset_id: Uuid,
|
||||
) -> Self {
|
||||
let mut path = BezPath::new();
|
||||
path.move_to((x, y));
|
||||
path.line_to((x + w, y));
|
||||
path.line_to((x + w, y + h));
|
||||
path.line_to((x, y + h));
|
||||
path.close_path();
|
||||
Self {
|
||||
layer_id,
|
||||
time,
|
||||
path,
|
||||
stroke_style: None, // invisible edges — just the image
|
||||
stroke_color: None,
|
||||
fill_color: None,
|
||||
is_closed: true,
|
||||
image_fill: Some(asset_id),
|
||||
description_text: "Add image".to_string(),
|
||||
graph_before: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_description(mut self, desc: impl Into<String>) -> Self {
|
||||
self.description_text = desc.into();
|
||||
self
|
||||
}
|
||||
|
||||
/// Fill the created region with an image asset (image takes render priority).
|
||||
pub fn with_image_fill(mut self, asset_id: Uuid) -> Self {
|
||||
self.image_fill = Some(asset_id);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for AddShapeAction {
|
||||
@@ -87,16 +128,25 @@ impl Action for AddShapeAction {
|
||||
DEFAULT_SNAP_EPSILON,
|
||||
);
|
||||
|
||||
// Apply fill if this is a closed shape with fill
|
||||
if self.is_closed {
|
||||
if let Some(ref fill) = self.fill_color {
|
||||
// Compute centroid of the path's bounding box and paint-bucket fill
|
||||
let bbox = self.path.bounding_box();
|
||||
let centroid = kurbo::Point::new(
|
||||
(bbox.x0 + bbox.x1) / 2.0,
|
||||
(bbox.y0 + bbox.y1) / 2.0,
|
||||
);
|
||||
graph.paint_bucket(centroid, fill.clone(), FillRule::NonZero, 0.0);
|
||||
// Apply fill if this is a closed shape with a colour and/or image fill.
|
||||
if self.is_closed && (self.fill_color.is_some() || self.image_fill.is_some()) {
|
||||
// Compute centroid of the path's bounding box and paint-bucket fill.
|
||||
let bbox = self.path.bounding_box();
|
||||
let centroid = kurbo::Point::new(
|
||||
(bbox.x0 + bbox.x1) / 2.0,
|
||||
(bbox.y0 + bbox.y1) / 2.0,
|
||||
);
|
||||
// paint_bucket needs a colour; an image-only fill uses a placeholder
|
||||
// that the image overrides (cleared below).
|
||||
let color = self.fill_color.clone().unwrap_or_else(|| ShapeColor::rgba(255, 255, 255, 255));
|
||||
if let Some(fid) = graph.paint_bucket(centroid, color, FillRule::NonZero, 0.0) {
|
||||
if let Some(asset_id) = self.image_fill {
|
||||
let fill = graph.fill_mut(fid);
|
||||
fill.image_fill = Some(asset_id);
|
||||
if self.fill_color.is_none() {
|
||||
fill.color = None; // image-only: don't double-paint a colour
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//! Shared logic for the "Group" and "Convert to Movie Clip" actions: extract the
|
||||
//! selected DCEL geometry from a vector layer's active keyframe into a new `VectorClip`
|
||||
//! and drop a `ClipInstance` in its place (so it can then be motion-tweened).
|
||||
//!
|
||||
//! A *group* (`is_group = true`) is a static container; a *movie clip* (`is_group =
|
||||
//! false`) has its own timeline. Both are tweenable via the clip instance's transform.
|
||||
//!
|
||||
//! Both the Select tool and the (cut-and-select) RegionSelect tool populate the same
|
||||
//! `Selection` ID sets, so a single entry point — [`extract_geometry_to_clip`] — handles
|
||||
//! Group and Convert-to-Movie-Clip from whatever is selected.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::clip::{ClipInstance, VectorClip};
|
||||
use crate::document::Document;
|
||||
use crate::layer::{AnyLayer, ShapeKeyframe, VectorLayer};
|
||||
use crate::object::Transform;
|
||||
use crate::vector_graph::{EdgeId, FillId, VectorGraph};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Build a clip holding `sub_graph` and place a `ClipInstance` (with `transform`) on the
|
||||
/// layer. Shared by both extraction paths. Does **not** touch the source graph — the
|
||||
/// caller is responsible for having removed the moved geometry first.
|
||||
fn assemble_clip_from_graph(
|
||||
document: &mut Document,
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
sub_graph: VectorGraph,
|
||||
transform: Transform,
|
||||
clip_id: Uuid,
|
||||
instance_id: Uuid,
|
||||
is_group: bool,
|
||||
clip_name: &str,
|
||||
) {
|
||||
let (doc_w, doc_h, doc_dur) = (document.width, document.height, document.duration.max(1.0));
|
||||
|
||||
// A vector layer whose single keyframe holds the extracted graph (in the source's
|
||||
// coordinate space, so an identity/translation placement renders it in place).
|
||||
let mut inner = VectorLayer::new("Layer 1");
|
||||
let mut kf = ShapeKeyframe::new(0.0);
|
||||
kf.graph = sub_graph;
|
||||
inner.keyframes.push(kf);
|
||||
let mut clip = VectorClip::with_id(clip_id, clip_name, doc_w, doc_h, doc_dur);
|
||||
clip.is_group = is_group;
|
||||
clip.layers.add_root(AnyLayer::Vector(inner));
|
||||
document.add_vector_clip(clip);
|
||||
|
||||
let mut instance = ClipInstance::with_id(instance_id, clip_id);
|
||||
instance.transform = transform;
|
||||
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
|
||||
// Groups gate visibility by the active keyframe's clip_instance_ids; movie
|
||||
// clips render unconditionally.
|
||||
if is_group {
|
||||
if let Some(kf) = vl.keyframe_at_mut(time) {
|
||||
kf.clip_instance_ids.push(instance_id);
|
||||
}
|
||||
}
|
||||
vl.clip_instances.push(instance);
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the selected geometry into a new clip + place a `ClipInstance`. Returns the
|
||||
/// pre-extraction graph snapshot for undo. `clip_id`/`instance_id` are caller-provided
|
||||
/// so undo/redo is stable. The selection sets come straight from the editor selection
|
||||
/// (`select_fill` already includes each fill's boundary edges); `extract_subgraph`
|
||||
/// derives which of those edges are shared with non-selected shapes.
|
||||
pub fn extract_geometry_to_clip(
|
||||
document: &mut Document,
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
fills: &HashSet<FillId>,
|
||||
edges: &HashSet<EdgeId>,
|
||||
clip_id: Uuid,
|
||||
instance_id: Uuid,
|
||||
is_group: bool,
|
||||
clip_name: &str,
|
||||
) -> Result<VectorGraph, String> {
|
||||
if fills.is_empty() && edges.is_empty() {
|
||||
return Err("No geometry selected".to_string());
|
||||
}
|
||||
|
||||
// 1. Extract from the source graph (extract_subgraph removes the moved geometry).
|
||||
let (graph_before, sub_graph) = {
|
||||
let layer = document.get_layer_mut(&layer_id).ok_or("Layer not found")?;
|
||||
let vl = match layer {
|
||||
AnyLayer::Vector(vl) => vl,
|
||||
_ => return Err("Not a vector layer".to_string()),
|
||||
};
|
||||
let graph = vl.graph_at_time_mut(time).ok_or("No keyframe at time")?;
|
||||
let before = graph.clone();
|
||||
// No explicit cut boundary — extract_subgraph derives shared-fill boundaries.
|
||||
let (sub, _, _) = graph.extract_subgraph(edges, fills, &HashSet::new());
|
||||
(before, sub)
|
||||
};
|
||||
|
||||
// 2 & 3. Build the clip + place an identity-transform instance (geometry stays put).
|
||||
assemble_clip_from_graph(
|
||||
document, layer_id, time, sub_graph, Transform::default(),
|
||||
clip_id, instance_id, is_group, clip_name,
|
||||
);
|
||||
|
||||
Ok(graph_before)
|
||||
}
|
||||
|
||||
/// Reverse `extract_geometry_to_clip`: remove the clip + instance and restore the graph.
|
||||
pub fn undo_extract_geometry(
|
||||
document: &mut Document,
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
clip_id: Uuid,
|
||||
instance_id: Uuid,
|
||||
graph_before: &VectorGraph,
|
||||
) {
|
||||
document.vector_clips.remove(&clip_id);
|
||||
document.rebuild_layer_to_clip_map();
|
||||
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&layer_id) {
|
||||
vl.clip_instances.retain(|ci| ci.id != instance_id);
|
||||
if let Some(kf) = vl.keyframe_at_mut(time) {
|
||||
kf.clip_instance_ids.retain(|id| *id != instance_id);
|
||||
}
|
||||
if let Some(graph) = vl.graph_at_time_mut(time) {
|
||||
*graph = graph_before.clone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,55 +1,57 @@
|
||||
//! Convert to Movie Clip action — STUB: needs DCEL rewrite
|
||||
//! Convert to Movie Clip — extract selected geometry into a movie-clip `VectorClip`
|
||||
//! (its own timeline) + a `ClipInstance` that can be motion-tweened.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::clip::ClipInstance;
|
||||
use crate::actions::clip_from_geometry::{extract_geometry_to_clip, undo_extract_geometry};
|
||||
use crate::document::Document;
|
||||
use crate::vector_graph::{EdgeId, FillId, VectorGraph};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Action that converts selected items to a Movie Clip
|
||||
/// TODO: Rewrite for DCEL
|
||||
#[allow(dead_code)]
|
||||
pub struct ConvertToMovieClipAction {
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
shape_ids: Vec<Uuid>,
|
||||
clip_instance_ids: Vec<Uuid>,
|
||||
fills: Vec<FillId>,
|
||||
edges: Vec<EdgeId>,
|
||||
clip_id: Uuid,
|
||||
instance_id: Uuid,
|
||||
created_clip_id: Option<Uuid>,
|
||||
removed_clip_instances: Vec<ClipInstance>,
|
||||
graph_before: Option<VectorGraph>,
|
||||
}
|
||||
|
||||
impl ConvertToMovieClipAction {
|
||||
pub fn new(
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
shape_ids: Vec<Uuid>,
|
||||
clip_instance_ids: Vec<Uuid>,
|
||||
fills: Vec<FillId>,
|
||||
edges: Vec<EdgeId>,
|
||||
clip_id: Uuid,
|
||||
instance_id: Uuid,
|
||||
) -> Self {
|
||||
Self {
|
||||
layer_id,
|
||||
time,
|
||||
shape_ids,
|
||||
clip_instance_ids,
|
||||
instance_id,
|
||||
created_clip_id: None,
|
||||
removed_clip_instances: Vec::new(),
|
||||
}
|
||||
Self { layer_id, time, fills, edges, clip_id, instance_id, graph_before: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for ConvertToMovieClipAction {
|
||||
fn execute(&mut self, _document: &mut Document) -> Result<(), String> {
|
||||
let _ = (&self.layer_id, self.time, &self.shape_ids, &self.clip_instance_ids, self.instance_id);
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let fills: HashSet<FillId> = self.fills.iter().copied().collect();
|
||||
let edges: HashSet<EdgeId> = self.edges.iter().copied().collect();
|
||||
let before = extract_geometry_to_clip(
|
||||
document, self.layer_id, self.time, &fills, &edges,
|
||||
self.clip_id, self.instance_id, false, "Movie Clip",
|
||||
)?;
|
||||
self.graph_before = Some(before);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, _document: &mut Document) -> Result<(), String> {
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
if let Some(before) = &self.graph_before {
|
||||
undo_extract_geometry(document, self.layer_id, self.time, self.clip_id, self.instance_id, before);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
let count = self.shape_ids.len() + self.clip_instance_ids.len();
|
||||
format!("Convert {} object(s) to Movie Clip", count)
|
||||
"Convert to Movie Clip".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Create-text-clip action
|
||||
//!
|
||||
//! Used by the text tool when the active layer is a **vector** layer: it creates a
|
||||
//! VectorClip containing a single text layer, registers it, and places a clip
|
||||
//! instance in the parent vector layer. The editor then enters that clip so the
|
||||
//! text is directly editable. All of this is one undoable step so undo never
|
||||
//! leaves an orphan clip.
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::clip::{ClipInstance, VectorClip};
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::text_layer::TextLayer;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Minimum clip duration (seconds) when the document has no duration set yet.
|
||||
const FALLBACK_DURATION: f64 = 10.0;
|
||||
|
||||
pub struct CreateTextClipAction {
|
||||
/// The vector layer to place the clip instance in.
|
||||
parent_layer_id: Uuid,
|
||||
/// The text layer to embed (its id is stable across redo).
|
||||
text_layer: TextLayer,
|
||||
/// Instance position in the parent layer's space.
|
||||
position: (f64, f64),
|
||||
|
||||
// Assigned on first execute; reused on redo so ids are stable.
|
||||
clip_id: Option<Uuid>,
|
||||
instance_id: Option<Uuid>,
|
||||
executed: bool,
|
||||
}
|
||||
|
||||
impl CreateTextClipAction {
|
||||
pub fn new(parent_layer_id: Uuid, text_layer: TextLayer, position: (f64, f64)) -> Self {
|
||||
Self {
|
||||
parent_layer_id,
|
||||
text_layer,
|
||||
position,
|
||||
clip_id: None,
|
||||
instance_id: None,
|
||||
executed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Preset the clip + instance ids (so the caller knows them up-front for
|
||||
/// entering the clip immediately after execute). Ids stay stable across redo.
|
||||
pub fn with_ids(mut self, clip_id: Uuid, instance_id: Uuid) -> Self {
|
||||
self.clip_id = Some(clip_id);
|
||||
self.instance_id = Some(instance_id);
|
||||
self
|
||||
}
|
||||
|
||||
/// The vector clip id (after execute).
|
||||
pub fn clip_id(&self) -> Option<Uuid> {
|
||||
self.clip_id
|
||||
}
|
||||
|
||||
/// The clip instance id placed in the parent layer (after execute).
|
||||
pub fn instance_id(&self) -> Option<Uuid> {
|
||||
self.instance_id
|
||||
}
|
||||
|
||||
/// The embedded text layer's id.
|
||||
pub fn text_layer_id(&self) -> Uuid {
|
||||
self.text_layer.layer.id
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for CreateTextClipAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let clip_id = self.clip_id.unwrap_or_else(Uuid::new_v4);
|
||||
self.clip_id = Some(clip_id);
|
||||
let instance_id = self.instance_id.unwrap_or_else(Uuid::new_v4);
|
||||
self.instance_id = Some(instance_id);
|
||||
|
||||
let duration = if document.duration > 0.0 { document.duration } else { FALLBACK_DURATION };
|
||||
|
||||
// Build the clip with the text layer as its single root layer.
|
||||
let mut clip = VectorClip::with_id(
|
||||
clip_id,
|
||||
"Text",
|
||||
self.text_layer.box_width.max(1.0),
|
||||
self.text_layer.box_height.max(1.0),
|
||||
duration,
|
||||
);
|
||||
// A movie clip (not keyframe-gated) so the text persists across the timeline.
|
||||
clip.is_group = false;
|
||||
clip.layers.add_root(AnyLayer::Text(self.text_layer.clone()));
|
||||
// Registers the clip and its layers in layer_to_clip_map for O(1) lookup.
|
||||
document.add_vector_clip(clip);
|
||||
|
||||
// Place an instance of the clip in the parent vector layer.
|
||||
let layer = document
|
||||
.get_layer_mut(&self.parent_layer_id)
|
||||
.ok_or_else(|| format!("Parent layer {} not found", self.parent_layer_id))?;
|
||||
let AnyLayer::Vector(vector_layer) = layer else {
|
||||
return Err("Text clip can only be created inside a vector layer".to_string());
|
||||
};
|
||||
let mut instance = ClipInstance::with_id(instance_id, clip_id);
|
||||
instance.transform.x = self.position.0;
|
||||
instance.transform.y = self.position.1;
|
||||
vector_layer.clip_instances.push(instance);
|
||||
|
||||
self.executed = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
if !self.executed {
|
||||
return Ok(());
|
||||
}
|
||||
// Remove the clip instance from the parent layer.
|
||||
if let (Some(instance_id), Some(AnyLayer::Vector(vector_layer))) =
|
||||
(self.instance_id, document.get_layer_mut(&self.parent_layer_id))
|
||||
{
|
||||
vector_layer.clip_instances.retain(|ci| ci.id != instance_id);
|
||||
}
|
||||
// Remove the clip and its layer_to_clip_map registrations.
|
||||
if let Some(clip_id) = self.clip_id {
|
||||
if let Some(clip) = document.vector_clips.remove(&clip_id) {
|
||||
for node in &clip.layers.roots {
|
||||
document.layer_to_clip_map.remove(&node.data.id());
|
||||
}
|
||||
}
|
||||
}
|
||||
self.executed = false;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
"Add text".to_string()
|
||||
}
|
||||
}
|
||||
@@ -1,56 +1,58 @@
|
||||
//! Group action — STUB: needs DCEL rewrite
|
||||
//! Group action — extract selected geometry into a group `VectorClip` + a `ClipInstance`.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::clip::ClipInstance;
|
||||
use crate::actions::clip_from_geometry::{extract_geometry_to_clip, undo_extract_geometry};
|
||||
use crate::document::Document;
|
||||
use crate::vector_graph::{EdgeId, FillId, VectorGraph};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Action that groups selected shapes and/or clip instances into a VectorClip
|
||||
/// TODO: Rewrite for DCEL (group DCEL faces/edges into a sub-clip)
|
||||
#[allow(dead_code)]
|
||||
/// Groups the selected DCEL geometry (fills/edges) of a vector layer's active keyframe
|
||||
/// into a new group clip, placing a clip instance in its place (which can be tweened).
|
||||
pub struct GroupAction {
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
shape_ids: Vec<Uuid>,
|
||||
clip_instance_ids: Vec<Uuid>,
|
||||
fills: Vec<FillId>,
|
||||
edges: Vec<EdgeId>,
|
||||
clip_id: Uuid,
|
||||
instance_id: Uuid,
|
||||
created_clip_id: Option<Uuid>,
|
||||
removed_clip_instances: Vec<ClipInstance>,
|
||||
graph_before: Option<VectorGraph>,
|
||||
}
|
||||
|
||||
impl GroupAction {
|
||||
pub fn new(
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
shape_ids: Vec<Uuid>,
|
||||
clip_instance_ids: Vec<Uuid>,
|
||||
fills: Vec<FillId>,
|
||||
edges: Vec<EdgeId>,
|
||||
clip_id: Uuid,
|
||||
instance_id: Uuid,
|
||||
) -> Self {
|
||||
Self {
|
||||
layer_id,
|
||||
time,
|
||||
shape_ids,
|
||||
clip_instance_ids,
|
||||
instance_id,
|
||||
created_clip_id: None,
|
||||
removed_clip_instances: Vec::new(),
|
||||
}
|
||||
Self { layer_id, time, fills, edges, clip_id, instance_id, graph_before: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for GroupAction {
|
||||
fn execute(&mut self, _document: &mut Document) -> Result<(), String> {
|
||||
let _ = (&self.layer_id, self.time, &self.shape_ids, &self.clip_instance_ids, self.instance_id);
|
||||
// TODO: Implement DCEL-aware grouping
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let fills: HashSet<FillId> = self.fills.iter().copied().collect();
|
||||
let edges: HashSet<EdgeId> = self.edges.iter().copied().collect();
|
||||
let before = extract_geometry_to_clip(
|
||||
document, self.layer_id, self.time, &fills, &edges,
|
||||
self.clip_id, self.instance_id, true, "Group",
|
||||
)?;
|
||||
self.graph_before = Some(before);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, _document: &mut Document) -> Result<(), String> {
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
if let Some(before) = &self.graph_before {
|
||||
undo_extract_geometry(document, self.layer_id, self.time, self.clip_id, self.instance_id, before);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
let count = self.shape_ids.len() + self.clip_instance_ids.len();
|
||||
format!("Group {} objects", count)
|
||||
"Group".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ impl Action for LoopClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
for (instance_id, _old_dur, new_dur, _old_lb, new_lb) in loops {
|
||||
@@ -61,6 +62,7 @@ impl Action for LoopClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
for (instance_id, old_dur, _new_dur, old_lb, _new_lb) in loops {
|
||||
|
||||
@@ -11,6 +11,7 @@ pub mod add_layer;
|
||||
pub mod add_shape;
|
||||
pub mod modify_shape_path;
|
||||
pub mod move_clip_instances;
|
||||
pub mod reorder_clip_instances;
|
||||
pub mod paint_bucket;
|
||||
pub mod remove_effect;
|
||||
pub mod set_document_properties;
|
||||
@@ -29,17 +30,24 @@ pub mod update_midi_events;
|
||||
pub mod loop_clip_instances;
|
||||
pub mod remove_clip_instances;
|
||||
pub mod set_keyframe;
|
||||
pub mod set_tween;
|
||||
pub mod group_shapes;
|
||||
pub mod convert_to_movie_clip;
|
||||
pub mod region_split;
|
||||
pub mod toggle_group_expansion;
|
||||
pub mod group_layers;
|
||||
pub mod clip_from_geometry;
|
||||
pub mod raster_diff;
|
||||
pub mod raster_stroke;
|
||||
pub mod raster_fill;
|
||||
pub mod add_raster_keyframe;
|
||||
pub mod resize_raster_layer;
|
||||
pub mod move_layer;
|
||||
pub mod set_fill_paint;
|
||||
pub mod set_image_fill;
|
||||
pub mod create_text_clip;
|
||||
pub mod set_text_content;
|
||||
pub mod resize_text_box;
|
||||
|
||||
pub use add_clip_instance::AddClipInstanceAction;
|
||||
pub use add_effect::AddEffectAction;
|
||||
@@ -47,6 +55,7 @@ pub use add_layer::AddLayerAction;
|
||||
pub use add_shape::AddShapeAction;
|
||||
pub use modify_shape_path::ModifyGraphAction;
|
||||
pub use move_clip_instances::MoveClipInstancesAction;
|
||||
pub use reorder_clip_instances::ReorderClipInstancesAction;
|
||||
pub use paint_bucket::PaintBucketAction;
|
||||
pub use remove_effect::RemoveEffectAction;
|
||||
pub use set_document_properties::SetDocumentPropertiesAction;
|
||||
@@ -65,6 +74,7 @@ pub use update_midi_events::UpdateMidiEventsAction;
|
||||
pub use loop_clip_instances::LoopClipInstancesAction;
|
||||
pub use remove_clip_instances::RemoveClipInstancesAction;
|
||||
pub use set_keyframe::SetKeyframeAction;
|
||||
pub use set_tween::SetTweenAction;
|
||||
pub use group_shapes::GroupAction;
|
||||
pub use convert_to_movie_clip::ConvertToMovieClipAction;
|
||||
pub use region_split::RegionSplitAction;
|
||||
@@ -73,7 +83,12 @@ pub use group_layers::GroupLayersAction;
|
||||
pub use raster_stroke::RasterStrokeAction;
|
||||
pub use raster_fill::RasterFillAction;
|
||||
pub use add_raster_keyframe::AddRasterKeyframeAction;
|
||||
pub use resize_raster_layer::ResizeRasterLayerAction;
|
||||
pub use move_layer::MoveLayerAction;
|
||||
pub use set_fill_paint::SetFillPaintAction;
|
||||
pub use set_image_fill::SetImageFillAction;
|
||||
pub use change_bpm::ChangeBpmAction;
|
||||
pub use change_fps::ChangeFpsAction;
|
||||
pub use create_text_clip::CreateTextClipAction;
|
||||
pub use set_text_content::SetTextContentAction;
|
||||
pub use resize_text_box::ResizeTextBoxAction;
|
||||
|
||||
@@ -58,6 +58,7 @@ impl Action for MoveClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
if let Some(instance) = clip_instances.iter().find(|ci| ci.id == *member_instance_id) {
|
||||
@@ -97,6 +98,7 @@ impl Action for MoveClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
let group: Vec<(Uuid, f64, f64)> = moves.iter().filter_map(|(id, old_start, _)| {
|
||||
@@ -132,6 +134,7 @@ impl Action for MoveClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
// Update timeline_start for each clip instance
|
||||
@@ -159,6 +162,7 @@ impl Action for MoveClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
// Restore original timeline_start for each clip instance
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
//! correct). If the base is somehow not resident we skip rather than corrupt.
|
||||
|
||||
/// Normalize a buffer to full length `n`; an empty/short buffer becomes transparent.
|
||||
fn normalize(buf: &[u8], n: usize) -> std::borrow::Cow<[u8]> {
|
||||
fn normalize(buf: &[u8], n: usize) -> std::borrow::Cow<'_, [u8]> {
|
||||
if buf.len() == n {
|
||||
std::borrow::Cow::Borrowed(buf)
|
||||
} else {
|
||||
@@ -98,11 +98,16 @@ impl RasterDiff {
|
||||
self.before_region.len() + self.after_region.len()
|
||||
}
|
||||
|
||||
/// Restore the pre-edit pixels into `raw` (undo / first-execute rollback).
|
||||
pub fn apply_before(&self, raw: &mut Vec<u8>) {
|
||||
/// Restore the pre-edit pixels into `raw` (undo / first-execute rollback). `cur_w`/`cur_h`
|
||||
/// are the keyframe's current dimensions; if they differ from the diff's captured size the
|
||||
/// diff predates a resize and is skipped rather than applied at mismatched dims.
|
||||
pub fn apply_before(&self, raw: &mut Vec<u8>, cur_w: u32, cur_h: u32) {
|
||||
if self.bbox.is_none() {
|
||||
return; // no change
|
||||
}
|
||||
if cur_w != self.full_width || cur_h != self.full_height {
|
||||
return; // diff predates a keyframe resize
|
||||
}
|
||||
if self.before_blank {
|
||||
// The frame was blank before this edit (it was the first stroke); undoing
|
||||
// it returns to blank regardless of the current buffer.
|
||||
@@ -112,11 +117,16 @@ impl RasterDiff {
|
||||
self.stamp_resident(&self.before_region, raw);
|
||||
}
|
||||
|
||||
/// Apply the post-edit pixels into `raw` (commit / redo).
|
||||
pub fn apply_after(&self, raw: &mut Vec<u8>) {
|
||||
/// Apply the post-edit pixels into `raw` (commit / redo). `cur_w`/`cur_h` are the keyframe's
|
||||
/// current dimensions; a mismatch with the captured size means the diff predates a resize, so
|
||||
/// it's skipped rather than rebuilding the buffer at stale dimensions.
|
||||
pub fn apply_after(&self, raw: &mut Vec<u8>, cur_w: u32, cur_h: u32) {
|
||||
if self.bbox.is_none() {
|
||||
return; // no change
|
||||
}
|
||||
if cur_w != self.full_width || cur_h != self.full_height {
|
||||
return; // diff predates a keyframe resize
|
||||
}
|
||||
if self.before_blank {
|
||||
// Base was blank: build a full transparent buffer then stamp the bbox. The
|
||||
// commit/redo path frequently starts from empty `raw_pixels` here.
|
||||
@@ -175,9 +185,9 @@ mod tests {
|
||||
assert_eq!(diff.bbox, Some((3, 2, 2, 2)));
|
||||
|
||||
let mut buf = after.clone();
|
||||
diff.apply_before(&mut buf);
|
||||
diff.apply_before(&mut buf, w, h);
|
||||
assert_eq!(buf, before, "undo must reproduce the pre-edit buffer exactly");
|
||||
diff.apply_after(&mut buf);
|
||||
diff.apply_after(&mut buf, w, h);
|
||||
assert_eq!(buf, after, "redo must reproduce the post-edit buffer exactly");
|
||||
}
|
||||
|
||||
@@ -195,15 +205,15 @@ mod tests {
|
||||
// First execute / redo from EMPTY raw_pixels (the real commit path): builds
|
||||
// the full buffer from transparent + the stroke.
|
||||
let mut buf: Vec<u8> = Vec::new();
|
||||
diff.apply_after(&mut buf);
|
||||
diff.apply_after(&mut buf, w, h);
|
||||
assert_eq!(buf, after, "commit/redo must build the frame from a blank base");
|
||||
|
||||
// Undo the first stroke → back to blank (empty).
|
||||
diff.apply_before(&mut buf);
|
||||
diff.apply_before(&mut buf, w, h);
|
||||
assert!(buf.is_empty(), "undoing the first stroke restores the blank keyframe");
|
||||
|
||||
// Redo again from the now-empty buffer.
|
||||
diff.apply_after(&mut buf);
|
||||
diff.apply_after(&mut buf, w, h);
|
||||
assert_eq!(buf, after);
|
||||
}
|
||||
|
||||
@@ -215,7 +225,7 @@ mod tests {
|
||||
assert_eq!(diff.bbox, None);
|
||||
assert_eq!(diff.byte_size(), 0);
|
||||
let mut b = buf.clone();
|
||||
diff.apply_before(&mut b);
|
||||
diff.apply_before(&mut b, w, h);
|
||||
assert_eq!(b, buf);
|
||||
}
|
||||
|
||||
@@ -226,7 +236,7 @@ mod tests {
|
||||
let after = solid(w, h, [1, 2, 3, 255]);
|
||||
let diff = RasterDiff::compute(&before, &after, w, h);
|
||||
let mut empty: Vec<u8> = Vec::new();
|
||||
diff.apply_before(&mut empty); // base not resident
|
||||
diff.apply_before(&mut empty, w, h); // base not resident
|
||||
assert!(empty.is_empty(), "must not resize/corrupt a non-resident base");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ impl Action for RasterFillAction {
|
||||
if let Some(full) = self.full_after.take() {
|
||||
kf.raw_pixels = full;
|
||||
} else {
|
||||
self.diff.apply_after(&mut kf.raw_pixels);
|
||||
self.diff.apply_after(&mut kf.raw_pixels, kf.width, kf.height);
|
||||
}
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
@@ -71,7 +71,7 @@ impl Action for RasterFillAction {
|
||||
let kf = raster
|
||||
.keyframe_at_mut(self.time)
|
||||
.ok_or_else(|| format!("No raster keyframe at/before t={}", self.time))?;
|
||||
self.diff.apply_before(&mut kf.raw_pixels);
|
||||
self.diff.apply_before(&mut kf.raw_pixels, kf.width, kf.height);
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
Ok(())
|
||||
|
||||
@@ -61,7 +61,7 @@ impl Action for RasterStrokeAction {
|
||||
kf.raw_pixels = full;
|
||||
} else {
|
||||
// Redo: replay via the diff onto the (resident) base.
|
||||
self.diff.apply_after(&mut kf.raw_pixels);
|
||||
self.diff.apply_after(&mut kf.raw_pixels, kf.width, kf.height);
|
||||
}
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
@@ -70,7 +70,7 @@ impl Action for RasterStrokeAction {
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let kf = get_keyframe_mut(document, &self.layer_id, self.time, self.width, self.height)?;
|
||||
self.diff.apply_before(&mut kf.raw_pixels);
|
||||
self.diff.apply_before(&mut kf.raw_pixels, kf.width, kf.height);
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
Ok(())
|
||||
|
||||
@@ -46,6 +46,7 @@ impl Action for RemoveClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
// Find and remove the instance, saving it for rollback
|
||||
@@ -72,6 +73,7 @@ impl Action for RemoveClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
clip_instances.push(instance);
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
//! Reorder clip instances within a layer's stacking order (Send to Back / Bring to Front).
|
||||
//!
|
||||
//! A layer's `clip_instances` Vec order *is* the stacking order — the last element renders on top
|
||||
//! (hit-testing walks it in reverse). Geometry renders underneath and is unaffected. This action
|
||||
//! moves the selected instances to the front (end) or back (start) of that Vec.
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::clip::ClipInstance;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct ReorderClipInstancesAction {
|
||||
layer_id: Uuid,
|
||||
instance_ids: Vec<Uuid>,
|
||||
/// `true` = bring to front (top), `false` = send to back (bottom).
|
||||
to_front: bool,
|
||||
/// Full instance order captured on `execute`, for `rollback`.
|
||||
old_order: Option<Vec<Uuid>>,
|
||||
}
|
||||
|
||||
impl ReorderClipInstancesAction {
|
||||
pub fn new(layer_id: Uuid, instance_ids: Vec<Uuid>, to_front: bool) -> Self {
|
||||
Self { layer_id, instance_ids, to_front, old_order: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// The clip-instance stack for a layer, if it has one (Group/Raster/Text don't).
|
||||
fn clip_instances_mut<'a>(document: &'a mut Document, layer_id: &Uuid) -> Option<&'a mut Vec<ClipInstance>> {
|
||||
match document.get_layer_mut(layer_id)? {
|
||||
AnyLayer::Vector(l) => Some(&mut l.clip_instances),
|
||||
AnyLayer::Audio(l) => Some(&mut l.clip_instances),
|
||||
AnyLayer::Video(l) => Some(&mut l.clip_instances),
|
||||
AnyLayer::Effect(l) => Some(&mut l.clip_instances),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for ReorderClipInstancesAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let instances = clip_instances_mut(document, &self.layer_id)
|
||||
.ok_or_else(|| "Layer has no clip-instance stack".to_string())?;
|
||||
self.old_order = Some(instances.iter().map(|c| c.id).collect());
|
||||
|
||||
let mut selected = Vec::new();
|
||||
let mut rest = Vec::new();
|
||||
for ci in instances.drain(..) {
|
||||
if self.instance_ids.contains(&ci.id) {
|
||||
selected.push(ci);
|
||||
} else {
|
||||
rest.push(ci);
|
||||
}
|
||||
}
|
||||
if self.to_front {
|
||||
rest.extend(selected); // selected last → rendered on top
|
||||
*instances = rest;
|
||||
} else {
|
||||
selected.extend(rest); // selected first → rendered at the bottom (of the stack)
|
||||
*instances = selected;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let Some(order) = self.old_order.clone() else {
|
||||
return Ok(());
|
||||
};
|
||||
let instances = clip_instances_mut(document, &self.layer_id)
|
||||
.ok_or_else(|| "Layer has no clip-instance stack".to_string())?;
|
||||
let rank = |id: &Uuid| order.iter().position(|o| o == id).unwrap_or(usize::MAX);
|
||||
instances.sort_by(|a, b| rank(&a.id).cmp(&rank(&b.id)));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
if self.to_front { "Bring to Front".to_string() } else { "Send to Back".to_string() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Resize every keyframe of a raster layer to a new canvas size (Scale or Canvas mode), with undo.
|
||||
//!
|
||||
//! Used by the info panel's "Layer to document size" button. Pixels must be resident (the editor
|
||||
//! faults them in first) so the resample/copy is exact and a later page-in won't mismatch the size.
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::raster_layer::RasterResizeMode;
|
||||
use crate::raster_store::RasterStore;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Per-keyframe state captured for undo.
|
||||
struct OldKeyframe {
|
||||
id: Uuid,
|
||||
width: u32,
|
||||
height: u32,
|
||||
pixels: Vec<u8>,
|
||||
}
|
||||
|
||||
pub struct ResizeRasterLayerAction {
|
||||
layer_id: Uuid,
|
||||
new_w: u32,
|
||||
new_h: u32,
|
||||
mode: RasterResizeMode,
|
||||
/// Read-only page-in for keyframes whose pixels aren't resident. (No incremental write exists, so
|
||||
/// resized keyframes stay resident + dirty and persist on the next full save.)
|
||||
store: RasterStore,
|
||||
/// Captured on first execute for rollback.
|
||||
old: Option<Vec<OldKeyframe>>,
|
||||
}
|
||||
|
||||
impl ResizeRasterLayerAction {
|
||||
pub fn new(layer_id: Uuid, new_w: u32, new_h: u32, mode: RasterResizeMode, store: RasterStore) -> Self {
|
||||
Self { layer_id, new_w, new_h, mode, store, old: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for ResizeRasterLayerAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let Some(AnyLayer::Raster(rl)) = document.get_layer_mut(&self.layer_id) else {
|
||||
return Err("ResizeRasterLayerAction: layer is not a raster layer".into());
|
||||
};
|
||||
let capture = self.old.is_none();
|
||||
let mut old = Vec::new();
|
||||
for kf in rl.keyframes.iter_mut() {
|
||||
// Page the keyframe in one at a time so we never hold the whole layer in memory at once.
|
||||
if kf.raw_pixels.is_empty() {
|
||||
if let Some(px) = self.store.load_pixels(kf.id) {
|
||||
kf.raw_pixels = px;
|
||||
kf.needs_fault_in = false;
|
||||
}
|
||||
}
|
||||
if capture {
|
||||
old.push(OldKeyframe { id: kf.id, width: kf.width, height: kf.height, pixels: kf.raw_pixels.clone() });
|
||||
}
|
||||
kf.resize_to(self.new_w, self.new_h, self.mode);
|
||||
}
|
||||
if capture {
|
||||
self.old = Some(old);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let Some(AnyLayer::Raster(rl)) = document.get_layer_mut(&self.layer_id) else {
|
||||
return Err("ResizeRasterLayerAction: layer is not a raster layer".into());
|
||||
};
|
||||
if let Some(old) = &self.old {
|
||||
for o in old {
|
||||
if let Some(kf) = rl.keyframes.iter_mut().find(|kf| kf.id == o.id) {
|
||||
kf.width = o.width;
|
||||
kf.height = o.height;
|
||||
kf.raw_pixels = o.pixels.clone();
|
||||
kf.proxy = None;
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
match self.mode {
|
||||
RasterResizeMode::Scale => "Scale raster layer".into(),
|
||||
RasterResizeMode::Canvas => "Resize raster canvas".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
//! Resize-text-box action
|
||||
//!
|
||||
//! Updates a text layer's box origin and dimensions (which changes the wrap
|
||||
//! width, so parley re-wraps the text). One undoable step.
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use kurbo::Point;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct ResizeTextBoxAction {
|
||||
layer_id: Uuid,
|
||||
new_origin: Point,
|
||||
new_width: f64,
|
||||
new_height: f64,
|
||||
old: Option<(Point, f64, f64)>,
|
||||
}
|
||||
|
||||
impl ResizeTextBoxAction {
|
||||
pub fn new(layer_id: Uuid, new_origin: Point, new_width: f64, new_height: f64) -> Self {
|
||||
Self { layer_id, new_origin, new_width, new_height, old: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for ResizeTextBoxAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let layer = document
|
||||
.get_layer_mut(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
|
||||
let AnyLayer::Text(text_layer) = layer else {
|
||||
return Err("ResizeTextBoxAction target is not a text layer".to_string());
|
||||
};
|
||||
if self.old.is_none() {
|
||||
self.old = Some((text_layer.box_origin, text_layer.box_width, text_layer.box_height));
|
||||
}
|
||||
text_layer.box_origin = self.new_origin;
|
||||
text_layer.box_width = self.new_width.max(1.0);
|
||||
text_layer.box_height = self.new_height.max(1.0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let Some((origin, w, h)) = self.old else { return Ok(()) };
|
||||
let layer = document
|
||||
.get_layer_mut(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
|
||||
if let AnyLayer::Text(text_layer) = layer {
|
||||
text_layer.box_origin = origin;
|
||||
text_layer.box_width = w;
|
||||
text_layer.box_height = h;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
"Resize text box".to_string()
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
//! with undo/redo support.
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::document::Document;
|
||||
use crate::document::{Document, HdrOutputMode};
|
||||
use crate::shape::ShapeColor;
|
||||
|
||||
/// Individual property change for a document
|
||||
@@ -15,6 +15,7 @@ pub enum DocumentPropertyChange {
|
||||
Duration(f64),
|
||||
Framerate(f64),
|
||||
BackgroundColor(ShapeColor),
|
||||
HdrOutputMode(HdrOutputMode),
|
||||
}
|
||||
|
||||
/// Stored old value for undo (either f64 or color)
|
||||
@@ -22,6 +23,7 @@ pub enum DocumentPropertyChange {
|
||||
enum OldValue {
|
||||
F64(f64),
|
||||
Color(ShapeColor),
|
||||
Hdr(HdrOutputMode),
|
||||
}
|
||||
|
||||
/// Action that sets a property on the document
|
||||
@@ -72,6 +74,14 @@ impl SetDocumentPropertiesAction {
|
||||
old_value: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a new action to set the HDR→SDR output mode
|
||||
pub fn set_hdr_output_mode(mode: HdrOutputMode) -> Self {
|
||||
Self {
|
||||
property: DocumentPropertyChange::HdrOutputMode(mode),
|
||||
old_value: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for SetDocumentPropertiesAction {
|
||||
@@ -83,6 +93,7 @@ impl Action for SetDocumentPropertiesAction {
|
||||
DocumentPropertyChange::Duration(_) => OldValue::F64(document.duration),
|
||||
DocumentPropertyChange::Framerate(_) => OldValue::F64(document.framerate),
|
||||
DocumentPropertyChange::BackgroundColor(_) => OldValue::Color(document.background_color),
|
||||
DocumentPropertyChange::HdrOutputMode(_) => OldValue::Hdr(document.hdr_output_mode),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -92,6 +103,7 @@ impl Action for SetDocumentPropertiesAction {
|
||||
DocumentPropertyChange::Duration(v) => document.duration = *v,
|
||||
DocumentPropertyChange::Framerate(v) => document.framerate = *v,
|
||||
DocumentPropertyChange::BackgroundColor(c) => document.background_color = *c,
|
||||
DocumentPropertyChange::HdrOutputMode(m) => document.hdr_output_mode = *m,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -106,11 +118,15 @@ impl Action for SetDocumentPropertiesAction {
|
||||
DocumentPropertyChange::Duration(_) => document.duration = v,
|
||||
DocumentPropertyChange::Framerate(_) => document.framerate = v,
|
||||
DocumentPropertyChange::BackgroundColor(_) => {}
|
||||
DocumentPropertyChange::HdrOutputMode(_) => {}
|
||||
}
|
||||
}
|
||||
Some(OldValue::Color(c)) => {
|
||||
document.background_color = *c;
|
||||
}
|
||||
Some(OldValue::Hdr(m)) => {
|
||||
document.hdr_output_mode = *m;
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
Ok(())
|
||||
@@ -123,6 +139,7 @@ impl Action for SetDocumentPropertiesAction {
|
||||
DocumentPropertyChange::Duration(_) => "duration",
|
||||
DocumentPropertyChange::Framerate(_) => "framerate",
|
||||
DocumentPropertyChange::BackgroundColor(_) => "background color",
|
||||
DocumentPropertyChange::HdrOutputMode(_) => "HDR output mode",
|
||||
};
|
||||
format!("Set {}", property_name)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
//! Action that sets or clears the image fill on one or more VectorGraph fills.
|
||||
//!
|
||||
//! `image_fill` is an asset id the renderer maps onto the fill's bounding box; it
|
||||
//! takes priority over colour/gradient. Setting `None` clears it (the colour/gradient
|
||||
//! underneath shows again).
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::vector_graph::FillId;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct SetImageFillAction {
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
fill_ids: Vec<FillId>,
|
||||
/// `Some(asset_id)` to set, `None` to clear.
|
||||
new_image: Option<Uuid>,
|
||||
/// Per-fill previous `image_fill`, for undo.
|
||||
old: Vec<(FillId, Option<Uuid>)>,
|
||||
}
|
||||
|
||||
impl SetImageFillAction {
|
||||
pub fn new(layer_id: Uuid, time: f64, fill_ids: Vec<FillId>, image: Option<Uuid>) -> Self {
|
||||
Self { layer_id, time, fill_ids, new_image: image, old: Vec::new() }
|
||||
}
|
||||
|
||||
fn get_graph_mut<'a>(
|
||||
document: &'a mut Document,
|
||||
layer_id: &Uuid,
|
||||
time: f64,
|
||||
) -> Result<&'a mut crate::vector_graph::VectorGraph, String> {
|
||||
let layer = document
|
||||
.get_layer_mut(layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", layer_id))?;
|
||||
match layer {
|
||||
AnyLayer::Vector(vl) => vl
|
||||
.graph_at_time_mut(time)
|
||||
.ok_or_else(|| format!("No keyframe at time {}", time)),
|
||||
_ => Err("Not a vector layer".to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for SetImageFillAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let graph = Self::get_graph_mut(document, &self.layer_id, self.time)?;
|
||||
self.old.clear();
|
||||
for &fid in &self.fill_ids {
|
||||
self.old.push((fid, graph.fill(fid).image_fill));
|
||||
graph.fill_mut(fid).image_fill = self.new_image;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let graph = Self::get_graph_mut(document, &self.layer_id, self.time)?;
|
||||
for &(fid, old) in &self.old {
|
||||
graph.fill_mut(fid).image_fill = old;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
if self.new_image.is_some() { "Set image fill" } else { "Clear image fill" }.to_string()
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ use crate::action::Action;
|
||||
use crate::animation::{AnimationCurve, AnimationTarget, Keyframe, TransformProperty};
|
||||
use crate::document::Document;
|
||||
use crate::layer::{AnyLayer, ShapeKeyframe};
|
||||
use crate::object::Transform;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Undo info for a clip animation curve
|
||||
@@ -54,11 +55,17 @@ const TRANSFORM_PROPERTIES: &[TransformProperty] = &[
|
||||
TransformProperty::Opacity,
|
||||
];
|
||||
|
||||
fn transform_default(prop: &TransformProperty) -> f64 {
|
||||
/// The clip instance's own value for a property (its base transform / opacity).
|
||||
fn transform_prop_value(t: &Transform, opacity: f64, prop: &TransformProperty) -> f64 {
|
||||
match prop {
|
||||
TransformProperty::ScaleX | TransformProperty::ScaleY => 1.0,
|
||||
TransformProperty::Opacity => 1.0,
|
||||
_ => 0.0,
|
||||
TransformProperty::X => t.x,
|
||||
TransformProperty::Y => t.y,
|
||||
TransformProperty::Rotation => t.rotation,
|
||||
TransformProperty::ScaleX => t.scale_x,
|
||||
TransformProperty::ScaleY => t.scale_y,
|
||||
TransformProperty::SkewX => t.skew_x,
|
||||
TransformProperty::SkewY => t.skew_y,
|
||||
TransformProperty::Opacity => opacity,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,6 +74,21 @@ impl Action for SetKeyframeAction {
|
||||
self.clip_undo_entries.clear();
|
||||
self.shape_keyframe_created = false;
|
||||
|
||||
// Phase 1 (immutable): for each clip instance, gather its base transform and the
|
||||
// start time of its visibility region, so a brand-new curve can be anchored there.
|
||||
let mut clip_info: std::collections::HashMap<Uuid, (Transform, f64, f64)> =
|
||||
std::collections::HashMap::new(); // id -> (base transform, opacity, start time)
|
||||
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&self.layer_id) {
|
||||
for clip_id in &self.clip_instance_ids {
|
||||
if let Some(ci) = vl.clip_instances.iter().find(|c| c.id == *clip_id) {
|
||||
let start = vl
|
||||
.group_visibility_start(clip_id, self.time)
|
||||
.unwrap_or(ci.timeline_start);
|
||||
clip_info.insert(*clip_id, (ci.transform.clone(), ci.opacity, start));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let layer = document
|
||||
.get_layer_mut(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
|
||||
@@ -82,23 +104,37 @@ impl Action for SetKeyframeAction {
|
||||
|
||||
// Add clip animation keyframes
|
||||
for clip_id in &self.clip_instance_ids {
|
||||
let (base_transform, base_opacity, start) = clip_info
|
||||
.get(clip_id)
|
||||
.cloned()
|
||||
.unwrap_or((Transform::new(), 1.0, 0.0));
|
||||
for prop in TRANSFORM_PROPERTIES {
|
||||
let target = AnimationTarget::Object {
|
||||
id: *clip_id,
|
||||
property: *prop,
|
||||
};
|
||||
let default = transform_default(prop);
|
||||
let value = vl.layer.animation_data.eval(&target, self.time, default);
|
||||
// Fall back to the clip's OWN value (not a generic default) so a brand-new
|
||||
// keyframe captures the actual on-stage position, not (0,0)/identity.
|
||||
let base = transform_prop_value(&base_transform, base_opacity, prop);
|
||||
let value = vl.layer.animation_data.eval(&target, self.time, base);
|
||||
|
||||
let curve_created = vl.layer.animation_data.get_curve(&target).is_none();
|
||||
if curve_created {
|
||||
vl.layer
|
||||
.animation_data
|
||||
.set_curve(AnimationCurve::new(target.clone(), default));
|
||||
.set_curve(AnimationCurve::new(target.clone(), base));
|
||||
}
|
||||
|
||||
let curve = vl.layer.animation_data.get_curve_mut(&target).unwrap();
|
||||
let old_keyframe = curve.get_keyframe_at(self.time, 0.001).cloned();
|
||||
|
||||
// When this is the first keyframe of the curve and the clip already existed
|
||||
// before `time`, anchor a keyframe at its start with the original value.
|
||||
// Otherwise a single keyframe would Hold-extrapolate backward and move the
|
||||
// clip on every earlier frame too (the motion-tween first-keyframe bug).
|
||||
if curve_created && start < self.time - 0.001 {
|
||||
curve.set_keyframe(Keyframe::linear(start, base));
|
||||
}
|
||||
curve.set_keyframe(Keyframe::linear(self.time, value));
|
||||
|
||||
self.clip_undo_entries.push(ClipUndoEntry {
|
||||
@@ -145,3 +181,86 @@ impl Action for SetKeyframeAction {
|
||||
"New keyframe".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::actions::TransformClipInstancesAction;
|
||||
use crate::clip::ClipInstance;
|
||||
use crate::layer::VectorLayer;
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn x_curve_eval(document: &Document, layer_id: Uuid, instance_id: Uuid, time: f64) -> f64 {
|
||||
let target = AnimationTarget::Object { id: instance_id, property: TransformProperty::X };
|
||||
match document.get_layer(&layer_id) {
|
||||
Some(AnyLayer::Vector(vl)) => vl.layer.animation_data.eval(&target, time, f64::NAN),
|
||||
_ => panic!("no layer"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_keyframe_then_move_does_not_disturb_earlier_frames() {
|
||||
// Group created at frame 0 (clip at x=50), keyframe + move at frame 10 → x=200.
|
||||
// Frame 0 must keep x=50 (the motion-tween first-keyframe bug: it used to become 200).
|
||||
let mut document = Document::new("Test");
|
||||
let mut layer = VectorLayer::new("Layer");
|
||||
let clip_id = Uuid::new_v4();
|
||||
let instance_id = Uuid::new_v4();
|
||||
let mut instance = ClipInstance::with_id(instance_id, clip_id);
|
||||
instance.transform = Transform::with_position(50.0, 50.0);
|
||||
layer.clip_instances.push(instance);
|
||||
// The group's visibility starts at a keyframe at time 0 containing the instance.
|
||||
layer.ensure_keyframe_at(0.0).clip_instance_ids.push(instance_id);
|
||||
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
|
||||
|
||||
// Create a keyframe at frame 10.
|
||||
SetKeyframeAction::new(layer_id, 10.0, vec![instance_id])
|
||||
.execute(&mut document)
|
||||
.unwrap();
|
||||
|
||||
// The new curve must be anchored at the start (two keyframes, both at x=50 so far).
|
||||
assert!((x_curve_eval(&document, layer_id, instance_id, 0.0) - 50.0).abs() < 1e-6);
|
||||
assert!((x_curve_eval(&document, layer_id, instance_id, 10.0) - 50.0).abs() < 1e-6);
|
||||
|
||||
// Move the clip at frame 10 to x=200.
|
||||
let mut transforms = HashMap::new();
|
||||
transforms.insert(
|
||||
instance_id,
|
||||
(Transform::with_position(50.0, 50.0), Transform::with_position(200.0, 200.0)),
|
||||
);
|
||||
TransformClipInstancesAction::new(layer_id, 10.0, transforms)
|
||||
.execute(&mut document)
|
||||
.unwrap();
|
||||
|
||||
// Frame 0 unchanged; frame 10 moved; midpoint tweens.
|
||||
assert!((x_curve_eval(&document, layer_id, instance_id, 0.0) - 50.0).abs() < 1e-6, "frame 0 must stay 50");
|
||||
assert!((x_curve_eval(&document, layer_id, instance_id, 10.0) - 200.0).abs() < 1e-6, "frame 10 must be 200");
|
||||
assert!((x_curve_eval(&document, layer_id, instance_id, 5.0) - 125.0).abs() < 1e-6, "midpoint tweens");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_keyframe_at_clip_start_is_not_double_anchored() {
|
||||
// When the keyframe is created at the clip's own start, there's nothing earlier to
|
||||
// anchor — a single keyframe is correct.
|
||||
let mut document = Document::new("Test");
|
||||
let mut layer = VectorLayer::new("Layer");
|
||||
let clip_id = Uuid::new_v4();
|
||||
let instance_id = Uuid::new_v4();
|
||||
let mut instance = ClipInstance::with_id(instance_id, clip_id);
|
||||
instance.transform = Transform::with_position(10.0, 0.0);
|
||||
layer.clip_instances.push(instance);
|
||||
layer.ensure_keyframe_at(0.0).clip_instance_ids.push(instance_id);
|
||||
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
|
||||
|
||||
SetKeyframeAction::new(layer_id, 0.0, vec![instance_id])
|
||||
.execute(&mut document)
|
||||
.unwrap();
|
||||
|
||||
let target = AnimationTarget::Object { id: instance_id, property: TransformProperty::X };
|
||||
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
|
||||
let curve = vl.layer.animation_data.get_curve(&target).unwrap();
|
||||
assert_eq!(curve.keyframes.len(), 1, "keyframe at clip start needs no anchor");
|
||||
assert!((curve.eval(0.0) - 10.0).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Set-text-content action
|
||||
//!
|
||||
//! Replaces a text layer's [`TextContent`] (text string, font size, color, family,
|
||||
//! alignment) as one undoable step. Used both by in-place editing (text changes)
|
||||
//! and the info panel (style changes).
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::text_layer::TextContent;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct SetTextContentAction {
|
||||
layer_id: Uuid,
|
||||
new: TextContent,
|
||||
old: Option<TextContent>,
|
||||
}
|
||||
|
||||
impl SetTextContentAction {
|
||||
pub fn new(layer_id: Uuid, new: TextContent) -> Self {
|
||||
Self { layer_id, new, old: None }
|
||||
}
|
||||
|
||||
/// Construct with an explicit `old` value. Used by in-place editing, which mutates
|
||||
/// the document live for preview and then records one undoable step capturing the
|
||||
/// content as it was *before* editing began.
|
||||
pub fn with_old(layer_id: Uuid, old: TextContent, new: TextContent) -> Self {
|
||||
Self { layer_id, new, old: Some(old) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for SetTextContentAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let layer = document
|
||||
.get_layer_mut(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
|
||||
let AnyLayer::Text(text_layer) = layer else {
|
||||
return Err("SetTextContentAction target is not a text layer".to_string());
|
||||
};
|
||||
if self.old.is_none() {
|
||||
self.old = Some(text_layer.content.clone());
|
||||
}
|
||||
text_layer.content = self.new.clone();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let Some(old) = self.old.clone() else { return Ok(()) };
|
||||
let layer = document
|
||||
.get_layer_mut(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
|
||||
if let AnyLayer::Text(text_layer) = layer {
|
||||
text_layer.content = old;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
"Edit text".to_string()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//! Set the tween type on the keyframe at-or-before a time (e.g. "Add Shape Tween").
|
||||
//!
|
||||
//! The keyframe's `tween_after` controls how the span between it and the next keyframe is
|
||||
//! rendered: `None` holds, `Shape` morphs the geometry (when the two keyframes share
|
||||
//! topology — otherwise rendering falls back to holding).
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::document::Document;
|
||||
use crate::layer::{AnyLayer, TweenType};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct SetTweenAction {
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
new_tween: TweenType,
|
||||
old_tween: Option<TweenType>,
|
||||
}
|
||||
|
||||
impl SetTweenAction {
|
||||
pub fn new(layer_id: Uuid, time: f64, new_tween: TweenType) -> Self {
|
||||
Self { layer_id, time, new_tween, old_tween: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for SetTweenAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&self.layer_id) {
|
||||
if let Some(kf) = vl.keyframe_at_mut(self.time) {
|
||||
self.old_tween = Some(kf.tween_after);
|
||||
kf.tween_after = self.new_tween;
|
||||
} else {
|
||||
return Err("No keyframe at-or-before this time".to_string());
|
||||
}
|
||||
} else {
|
||||
return Err("Not a vector layer".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
if let (Some(old), Some(AnyLayer::Vector(vl))) =
|
||||
(self.old_tween, document.get_layer_mut(&self.layer_id))
|
||||
{
|
||||
if let Some(kf) = vl.keyframe_at_mut(self.time) {
|
||||
kf.tween_after = old;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
match self.new_tween {
|
||||
TweenType::Shape => "Add shape tween".to_string(),
|
||||
TweenType::None => "Remove tween".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -114,6 +114,7 @@ impl Action for SplitClipInstanceAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => return Err("Cannot split clip instances on group layers".to_string()),
|
||||
AnyLayer::Raster(_) => return Err("Cannot split clip instances on group layers".to_string()),
|
||||
AnyLayer::Text(_) => return Err("Cannot split clip instances on group layers".to_string()),
|
||||
};
|
||||
|
||||
let instance = clip_instances
|
||||
@@ -233,7 +234,7 @@ impl Action for SplitClipInstanceAction {
|
||||
AnyLayer::Group(_) => {
|
||||
return Err("Cannot split clip instances on group layers".to_string());
|
||||
}
|
||||
AnyLayer::Raster(_) => {
|
||||
AnyLayer::Raster(_) | AnyLayer::Text(_) => {
|
||||
return Err("Cannot split clip instances on group layers".to_string());
|
||||
}
|
||||
}
|
||||
@@ -294,8 +295,8 @@ impl Action for SplitClipInstanceAction {
|
||||
AnyLayer::Group(_) => {
|
||||
// Group layers don't have clip instances, nothing to rollback
|
||||
}
|
||||
AnyLayer::Raster(_) => {
|
||||
// Raster layers don't have clip instances, nothing to rollback
|
||||
AnyLayer::Raster(_) | AnyLayer::Text(_) => {
|
||||
// Raster/text layers don't have clip instances, nothing to rollback
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -101,6 +101,7 @@ impl Action for TransformClipInstancesAction {
|
||||
AnyLayer::Effect(_) => {}
|
||||
AnyLayer::Group(_) => {}
|
||||
AnyLayer::Raster(_) => {}
|
||||
AnyLayer::Text(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -140,6 +141,7 @@ impl Action for TransformClipInstancesAction {
|
||||
AnyLayer::Effect(_) => {}
|
||||
AnyLayer::Group(_) => {}
|
||||
AnyLayer::Raster(_) => {}
|
||||
AnyLayer::Text(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -101,6 +101,7 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
if let Some(instance) = clip_instances.iter().find(|ci| ci.id == *member_instance_id) {
|
||||
@@ -138,6 +139,7 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
if let Some(instance) = clip_instances.iter().find(|ci| ci.id == *member_instance_id) {
|
||||
@@ -182,6 +184,7 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
let instance = clip_instances.iter()
|
||||
@@ -275,6 +278,7 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
// Apply trims
|
||||
@@ -315,6 +319,7 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
// Restore original trim values
|
||||
|
||||
@@ -322,6 +322,20 @@ impl AnimationCurve {
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `time` lies strictly between two keyframes — an in-between frame of a
|
||||
/// tween (not on a keyframe, not in the pre/post-extrapolation tails).
|
||||
pub fn is_tween_inbetween(&self, time: f64, tol: f64) -> bool {
|
||||
if self.keyframes.len() < 2 {
|
||||
return false;
|
||||
}
|
||||
let first = self.keyframes.first().unwrap().time;
|
||||
let last = self.keyframes.last().unwrap().time;
|
||||
if time <= first + tol || time >= last - tol {
|
||||
return false;
|
||||
}
|
||||
!self.keyframes.iter().any(|kf| (kf.time - time).abs() <= tol)
|
||||
}
|
||||
|
||||
/// Extrapolate before the first keyframe
|
||||
fn extrapolate_pre(&self, time: f64, first_kf: &Keyframe) -> f64 {
|
||||
match self.pre_extrapolation {
|
||||
@@ -516,6 +530,17 @@ impl AnimationData {
|
||||
self.curves.remove(target)
|
||||
}
|
||||
|
||||
/// True when the object (e.g. a clip instance) is mid motion-tween at `time` — any of
|
||||
/// its curves has `time` strictly between two keyframes. Used to lock out editing on
|
||||
/// in-between frames (editing there would silently insert a keyframe and disturb the tween).
|
||||
pub fn is_object_tweened_at(&self, id: uuid::Uuid, time: f64) -> bool {
|
||||
const TOL: f64 = 0.001;
|
||||
self.curves.iter().any(|(target, curve)| {
|
||||
matches!(target, AnimationTarget::Object { id: oid, .. } if *oid == id)
|
||||
&& curve.is_tween_inbetween(time, TOL)
|
||||
})
|
||||
}
|
||||
|
||||
/// Evaluate a property at a given time
|
||||
pub fn eval(&self, target: &AnimationTarget, time: f64, default: f64) -> f64 {
|
||||
self.curves
|
||||
@@ -545,3 +570,51 @@ impl AnimationData {
|
||||
(t, opacity)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tween_lock_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn curve_in_between_detection() {
|
||||
let mut c = AnimationCurve::new(
|
||||
AnimationTarget::Object { id: uuid::Uuid::nil(), property: TransformProperty::X },
|
||||
0.0,
|
||||
);
|
||||
c.set_keyframe(Keyframe::linear(0.0, 0.0));
|
||||
c.set_keyframe(Keyframe::linear(10.0, 100.0));
|
||||
|
||||
assert!(c.is_tween_inbetween(5.0, 0.001), "strictly between keyframes");
|
||||
assert!(!c.is_tween_inbetween(0.0, 0.001), "on a keyframe");
|
||||
assert!(!c.is_tween_inbetween(10.0, 0.001), "on a keyframe");
|
||||
assert!(!c.is_tween_inbetween(15.0, 0.001), "past the last keyframe (extrapolation tail)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_keyframe_is_never_in_between() {
|
||||
let mut c = AnimationCurve::new(
|
||||
AnimationTarget::Object { id: uuid::Uuid::nil(), property: TransformProperty::X },
|
||||
0.0,
|
||||
);
|
||||
c.set_keyframe(Keyframe::linear(10.0, 100.0));
|
||||
assert!(!c.is_tween_inbetween(5.0, 0.001));
|
||||
assert!(!c.is_tween_inbetween(20.0, 0.001));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_tweened_when_any_curve_is_in_between() {
|
||||
let id = uuid::Uuid::new_v4();
|
||||
let mut data = AnimationData::new();
|
||||
let mut cx = AnimationCurve::new(
|
||||
AnimationTarget::Object { id, property: TransformProperty::X },
|
||||
0.0,
|
||||
);
|
||||
cx.set_keyframe(Keyframe::linear(0.0, 0.0));
|
||||
cx.set_keyframe(Keyframe::linear(10.0, 100.0));
|
||||
data.set_curve(cx);
|
||||
|
||||
assert!(data.is_object_tweened_at(id, 5.0));
|
||||
assert!(!data.is_object_tweened_at(id, 0.0));
|
||||
assert!(!data.is_object_tweened_at(uuid::Uuid::new_v4(), 5.0), "different object");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +62,10 @@ pub enum MediaKind {
|
||||
/// the keyframe id). Decoded eagerly on load and shown while the full-res pixels
|
||||
/// page in, so cold scrubs don't flash blank. See `raster_proxy_media_id`.
|
||||
RasterProxy = 6,
|
||||
/// An embedded font file (TTF/OTF) used by a text layer (keyed by a content hash
|
||||
/// of the bytes so identical fonts dedupe). Registered into the font collection
|
||||
/// on load so documents render faithfully on machines lacking the font.
|
||||
Font = 7,
|
||||
}
|
||||
|
||||
impl MediaKind {
|
||||
@@ -74,6 +78,7 @@ impl MediaKind {
|
||||
4 => Some(Self::Waveform),
|
||||
5 => Some(Self::Thumbnail),
|
||||
6 => Some(Self::RasterProxy),
|
||||
7 => Some(Self::Font),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -374,7 +379,11 @@ impl BeamArchive {
|
||||
let rows = stmt
|
||||
.query_map([&id_bytes], |r| r.get::<_, Vec<u8>>(0))
|
||||
.map_err(map_sql)?;
|
||||
let mut out = Vec::with_capacity(info.total_len as usize);
|
||||
// `total_len` is an untrusted DB field; cap the preallocation so a corrupt/oversized
|
||||
// value can't trigger a multi-GB eager allocation (or, on 32-bit, a truncated `as usize`).
|
||||
// The Vec still grows to fit the actual chunk bytes regardless.
|
||||
const PREALLOC_CAP: u64 = 64 * 1024 * 1024;
|
||||
let mut out = Vec::with_capacity(info.total_len.min(PREALLOC_CAP) as usize);
|
||||
for row in rows {
|
||||
out.extend_from_slice(&row.map_err(map_sql)?);
|
||||
}
|
||||
|
||||
@@ -122,6 +122,7 @@ impl VectorClip {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
for ci in clip_instances {
|
||||
// Compute end position of this clip instance in beats
|
||||
@@ -223,6 +224,17 @@ impl VectorClip {
|
||||
Some(existing) => existing.union(transformed_bounds),
|
||||
});
|
||||
}
|
||||
} else if let AnyLayer::Text(text_layer) = &layer_node.data {
|
||||
// Text layers contribute their box bounds (so a text-only clip is
|
||||
// selectable/draggable, not a degenerate point).
|
||||
let r = Rect::from_origin_size(
|
||||
text_layer.box_origin,
|
||||
(text_layer.box_width, text_layer.box_height),
|
||||
);
|
||||
combined_bounds = Some(match combined_bounds {
|
||||
None => r,
|
||||
Some(existing) => existing.union(r),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -263,9 +275,11 @@ pub struct ImageAsset {
|
||||
/// Image height in pixels
|
||||
pub height: u32,
|
||||
|
||||
/// Embedded image data (for project portability)
|
||||
/// If None, the image will be loaded from path when needed
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
/// Raw image file bytes. NOT serialized to project JSON — persisted as a
|
||||
/// `MediaKind::ImageAsset` row in the `.beam` container (chunked, pageable) and
|
||||
/// read back on load. `default` so new projects (bytes in the container, not JSON)
|
||||
/// deserialize; old projects with base64-embedded `data` still load via deserialize.
|
||||
#[serde(default, skip_serializing)]
|
||||
pub data: Option<Vec<u8>>,
|
||||
|
||||
/// Folder this asset belongs to (None = root of category)
|
||||
@@ -341,6 +355,13 @@ pub struct VideoClip {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub linked_audio_clip_id: Option<Uuid>,
|
||||
|
||||
/// When set, the video bytes are packed into the `.beam` container under this
|
||||
/// media id (== the clip id) and decoded by streaming from the SQLite blob.
|
||||
/// `None` means the video is referenced externally via [`Self::file_path`].
|
||||
/// Reconstructed from the archive on load (see `load_beam_sqlite`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub media_id: Option<Uuid>,
|
||||
|
||||
/// Folder this clip belongs to (None = root of category)
|
||||
#[serde(default)]
|
||||
pub folder_id: Option<Uuid>,
|
||||
@@ -365,6 +386,7 @@ impl VideoClip {
|
||||
duration,
|
||||
frame_rate,
|
||||
linked_audio_clip_id: None,
|
||||
media_id: None,
|
||||
folder_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +62,7 @@ impl ClipboardLayerType {
|
||||
AnyLayer::Effect(_) => ClipboardLayerType::Effect,
|
||||
AnyLayer::Group(_) => ClipboardLayerType::Vector,
|
||||
AnyLayer::Raster(_) => ClipboardLayerType::Vector,
|
||||
AnyLayer::Text(_) => ClipboardLayerType::Vector,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -449,6 +450,13 @@ fn regen_any_layer(layer: &AnyLayer, id_map: &mut HashMap<Uuid, Uuid>) -> AnyLay
|
||||
nl.layer.id = new_layer_id;
|
||||
AnyLayer::Raster(nl)
|
||||
}
|
||||
AnyLayer::Text(tl) => {
|
||||
let new_layer_id = Uuid::new_v4();
|
||||
id_map.insert(tl.layer.id, new_layer_id);
|
||||
let mut nl = tl.clone();
|
||||
nl.layer.id = new_layer_id;
|
||||
AnyLayer::Text(nl)
|
||||
}
|
||||
AnyLayer::Group(gl) => {
|
||||
let new_layer_id = Uuid::new_v4();
|
||||
id_map.insert(gl.layer.id, new_layer_id);
|
||||
|
||||
@@ -145,6 +145,26 @@ pub enum TimelineMode {
|
||||
Frames,
|
||||
}
|
||||
|
||||
/// How super-white (HDR) values are mapped to the SDR display/export output at the final
|
||||
/// linear→sRGB encode. SDR content sits in [0,1] and is unaffected by either mode.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum HdrOutputMode {
|
||||
/// Hard-clip values above 1.0 (the historical behaviour). SDR-exact; HDR highlights blow out.
|
||||
#[default]
|
||||
Clip,
|
||||
/// Roll highlights above a knee smoothly toward 1.0 to recover detail. Slightly dims near-white.
|
||||
HighlightRolloff,
|
||||
}
|
||||
|
||||
impl HdrOutputMode {
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
HdrOutputMode::Clip => "Clip",
|
||||
HdrOutputMode::HighlightRolloff => "Highlight rolloff",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Asset category for folder tree access
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AssetCategory {
|
||||
@@ -244,6 +264,10 @@ pub struct Document {
|
||||
#[serde(default)]
|
||||
pub timeline_mode: TimelineMode,
|
||||
|
||||
/// How HDR (super-white) values are mapped to the SDR output at the final encode.
|
||||
#[serde(default)]
|
||||
pub hdr_output_mode: HdrOutputMode,
|
||||
|
||||
/// Current UI layout state (serialized for save/load)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub ui_layout: Option<LayoutNode>,
|
||||
@@ -278,6 +302,7 @@ impl Default for Document {
|
||||
ml
|
||||
},
|
||||
duration: 10.0,
|
||||
hdr_output_mode: HdrOutputMode::default(),
|
||||
root: GraphicsObject::default(),
|
||||
vector_clips: HashMap::new(),
|
||||
video_clips: HashMap::new(),
|
||||
@@ -464,8 +489,8 @@ impl Document {
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::layer::AnyLayer::Raster(_) => {
|
||||
// Raster layers don't have clip instances
|
||||
crate::layer::AnyLayer::Raster(_) | crate::layer::AnyLayer::Text(_) => {
|
||||
// Raster and text layers don't have clip instances
|
||||
}
|
||||
crate::layer::AnyLayer::Group(group) => {
|
||||
// Recurse into group children to find their clip instance endpoints
|
||||
@@ -505,8 +530,8 @@ impl Document {
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::layer::AnyLayer::Raster(_) => {
|
||||
// Raster layers don't have clip instances
|
||||
crate::layer::AnyLayer::Raster(_) | crate::layer::AnyLayer::Text(_) => {
|
||||
// Raster and text layers don't have clip instances
|
||||
}
|
||||
crate::layer::AnyLayer::Group(g) => {
|
||||
process_group_children(&g.children, doc, max_end, calc_end);
|
||||
@@ -912,6 +937,7 @@ impl Document {
|
||||
AnyLayer::Effect(effect) => &effect.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
let instance = instances.iter().find(|inst| &inst.id == instance_id)?;
|
||||
@@ -952,6 +978,7 @@ impl Document {
|
||||
AnyLayer::Effect(effect) => &effect.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
for instance in instances {
|
||||
@@ -1014,6 +1041,7 @@ impl Document {
|
||||
AnyLayer::Vector(_) => return Some(desired_start), // Shouldn't reach here
|
||||
AnyLayer::Group(_) => return Some(desired_start), // Groups don't have own clips
|
||||
AnyLayer::Raster(_) => return Some(desired_start), // Raster layers don't have own clips
|
||||
AnyLayer::Text(_) => return Some(desired_start), // Text layers don't have own clips
|
||||
};
|
||||
|
||||
let mut occupied_ranges: Vec<(f64, f64, Uuid)> = Vec::new();
|
||||
@@ -1109,6 +1137,7 @@ impl Document {
|
||||
AnyLayer::Vector(v) => &v.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
// Collect non-group clip ranges
|
||||
@@ -1180,6 +1209,7 @@ impl Document {
|
||||
AnyLayer::Vector(vector) => &vector.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
for other in instances {
|
||||
@@ -1228,6 +1258,7 @@ impl Document {
|
||||
AnyLayer::Vector(vector) => &vector.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
let mut nearest_start = f64::MAX;
|
||||
@@ -1275,6 +1306,7 @@ impl Document {
|
||||
AnyLayer::Vector(vector) => &vector.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
let mut nearest_end = 0.0;
|
||||
|
||||
@@ -265,6 +265,84 @@ impl VideoCodec {
|
||||
}
|
||||
}
|
||||
|
||||
/// YUV color range for the encoded video (currently H.264). Limited/TV (16–235) is what nearly
|
||||
/// every player assumes; Full/PC (0–255) keeps a bit more precision but only looks right in players
|
||||
/// that honor the full-range tag — so Limited is the safe default.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ColorRange {
|
||||
Limited,
|
||||
Full,
|
||||
}
|
||||
|
||||
impl Default for ColorRange {
|
||||
fn default() -> Self { ColorRange::Limited }
|
||||
}
|
||||
|
||||
impl ColorRange {
|
||||
pub fn is_full(&self) -> bool { matches!(self, ColorRange::Full) }
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
ColorRange::Limited => "Limited (TV, 16–235)",
|
||||
ColorRange::Full => "Full (PC, 0–255)",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// HDR output mode for video export. SDR encodes BT.709 8-bit as before; the HDR modes encode
|
||||
/// 10-bit BT.2020 with the PQ (HDR10) or HLG transfer, preserving super-white highlights from the
|
||||
/// linear compositor. HDR requires a 10-bit codec (HEVC Main10) — the exporter forces H.265.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum HdrExportMode {
|
||||
#[default]
|
||||
Sdr,
|
||||
/// PQ (SMPTE ST 2084) — HDR10. Graphics white at 203 nits (matches the compositor convention).
|
||||
Pq,
|
||||
/// HLG (ARIB STD-B67) — broadcast HDR, also displayable as SDR.
|
||||
Hlg,
|
||||
}
|
||||
|
||||
impl HdrExportMode {
|
||||
pub fn is_hdr(&self) -> bool { !matches!(self, HdrExportMode::Sdr) }
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
HdrExportMode::Sdr => "SDR (BT.709, 8-bit)",
|
||||
HdrExportMode::Pq => "HDR10 / PQ (BT.2020, 10-bit)",
|
||||
HdrExportMode::Hlg => "HLG (BT.2020, 10-bit)",
|
||||
}
|
||||
}
|
||||
/// FFmpeg transfer-characteristic name for the color tags.
|
||||
pub fn transfer_name(&self) -> &'static str {
|
||||
match self {
|
||||
HdrExportMode::Sdr => "bt709",
|
||||
HdrExportMode::Pq => "smpte2084",
|
||||
HdrExportMode::Hlg => "arib-std-b67",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How the document is fit into the export frame when the export resolution's aspect ratio differs
|
||||
/// from the document's. Applied as the export `base_transform` (document space → export pixels).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum ExportFitMode {
|
||||
/// Scale each axis independently to fill the frame — distorts when aspects differ.
|
||||
Stretch,
|
||||
/// Scale uniformly to fit, centered, with black bars (letterbox/pillarbox). Preserves aspect.
|
||||
#[default]
|
||||
Letterbox,
|
||||
/// Scale uniformly to fill, centered, cropping the overflow. Preserves aspect, no bars.
|
||||
Crop,
|
||||
}
|
||||
|
||||
impl ExportFitMode {
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
ExportFitMode::Stretch => "Stretch (distort to fill)",
|
||||
ExportFitMode::Letterbox => "Letterbox (fit, black bars)",
|
||||
ExportFitMode::Crop => "Crop (fill, trim edges)",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Video quality presets
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum VideoQuality {
|
||||
@@ -322,6 +400,18 @@ pub struct VideoExportSettings {
|
||||
/// Video quality
|
||||
pub quality: VideoQuality,
|
||||
|
||||
/// YUV color range (H.264 only; ignored by other codecs).
|
||||
#[serde(default)]
|
||||
pub color_range: ColorRange,
|
||||
|
||||
/// HDR output mode. HDR forces 10-bit HEVC (BT.2020 + PQ/HLG); SDR is the default.
|
||||
#[serde(default)]
|
||||
pub hdr: HdrExportMode,
|
||||
|
||||
/// How the document is fit into the export frame when aspect ratios differ (default Letterbox).
|
||||
#[serde(default)]
|
||||
pub fit: ExportFitMode,
|
||||
|
||||
/// Audio settings (None = no audio)
|
||||
pub audio: Option<AudioExportSettings>,
|
||||
|
||||
@@ -340,6 +430,9 @@ impl Default for VideoExportSettings {
|
||||
height: None,
|
||||
framerate: 60.0,
|
||||
quality: VideoQuality::High,
|
||||
color_range: ColorRange::Limited,
|
||||
hdr: HdrExportMode::Sdr,
|
||||
fit: ExportFitMode::Letterbox,
|
||||
audio: Some(AudioExportSettings::high_quality_aac()),
|
||||
start_time: 0.0,
|
||||
end_time: 60.0,
|
||||
@@ -431,11 +524,14 @@ pub struct ImageExportSettings {
|
||||
/// When false, the image is composited onto an opaque background before encoding.
|
||||
/// Only meaningful for formats that support alpha (PNG, WebP).
|
||||
pub allow_transparency: bool,
|
||||
/// How the document is fit into the output frame when aspect ratios differ (default Letterbox).
|
||||
#[serde(default)]
|
||||
pub fit: ExportFitMode,
|
||||
}
|
||||
|
||||
impl Default for ImageExportSettings {
|
||||
fn default() -> Self {
|
||||
Self { format: ImageFormat::Png, time: 0.0, width: None, height: None, quality: 90, allow_transparency: false }
|
||||
Self { format: ImageFormat::Png, time: 0.0, width: None, height: None, quality: 90, allow_transparency: false, fit: ExportFitMode::Letterbox }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
//! too (via [`load_beam_zip_legacy`]). Saving always writes the SQLite form, so
|
||||
//! opening a legacy file and saving migrates it.
|
||||
|
||||
use crate::beam_archive::{BeamArchive, MediaKind, MediaMeta, LARGE_MEDIA_THRESHOLD};
|
||||
use crate::beam_archive::{BeamArchive, MediaKind, MediaMeta, MediaStorage, LARGE_MEDIA_THRESHOLD};
|
||||
use crate::document::Document;
|
||||
use daw_backend::audio::pool::AudioPoolEntry;
|
||||
use daw_backend::audio::project::Project as AudioProject;
|
||||
@@ -88,15 +88,6 @@ impl Default for LargeMediaMode {
|
||||
/// Settings for saving a project
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SaveSettings {
|
||||
/// Automatically embed files smaller than this size (in bytes)
|
||||
pub auto_embed_threshold_bytes: u64,
|
||||
|
||||
/// Force embedding all media files
|
||||
pub force_embed_all: bool,
|
||||
|
||||
/// Force linking all media files (don't embed any)
|
||||
pub force_link_all: bool,
|
||||
|
||||
/// How to store files at/above [`LARGE_MEDIA_THRESHOLD`] (pack vs reference).
|
||||
/// `Ask` behaves as `Reference` here (safe default: don't bloat the DB).
|
||||
pub large_media_mode: LargeMediaMode,
|
||||
@@ -105,9 +96,6 @@ pub struct SaveSettings {
|
||||
impl Default for SaveSettings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
auto_embed_threshold_bytes: 10_000_000, // 10 MB
|
||||
force_embed_all: false,
|
||||
force_link_all: false,
|
||||
large_media_mode: LargeMediaMode::Ask,
|
||||
}
|
||||
}
|
||||
@@ -254,6 +242,21 @@ fn thumbnail_media_id(clip_id: Uuid) -> Uuid {
|
||||
Uuid::from_u128(clip_id.as_u128() ^ SENTINEL)
|
||||
}
|
||||
|
||||
/// Content-hash id for an embedded font row, so identical font files dedupe to one
|
||||
/// row regardless of which / how many text layers use them. A 128-bit id is built
|
||||
/// from two salted 64-bit hashes of the bytes.
|
||||
fn font_media_id(bytes: &[u8]) -> Uuid {
|
||||
use std::hash::{Hash, Hasher};
|
||||
let mut h1 = std::collections::hash_map::DefaultHasher::new();
|
||||
bytes.hash(&mut h1);
|
||||
let mut h2 = std::collections::hash_map::DefaultHasher::new();
|
||||
0xF0E1_D2C3_B4A5_9687u64.hash(&mut h2);
|
||||
bytes.hash(&mut h2);
|
||||
let hi = h1.finish() as u128;
|
||||
let lo = h2.finish() as u128;
|
||||
Uuid::from_u128((hi << 64) | lo)
|
||||
}
|
||||
|
||||
/// Derived id for a raster keyframe's low-res proxy row (distinct from the keyframe's
|
||||
/// own full-res `Raster` row, which is keyed by the raw keyframe id).
|
||||
fn raster_proxy_media_id(kf_id: Uuid) -> Uuid {
|
||||
@@ -269,7 +272,7 @@ pub fn save_beam(
|
||||
audio_pool_entries: Vec<AudioPoolEntry>,
|
||||
layer_to_track_map: &std::collections::HashMap<uuid::Uuid, u32>,
|
||||
thumbnail_blobs: &std::collections::HashMap<uuid::Uuid, Vec<u8>>,
|
||||
_settings: &SaveSettings,
|
||||
settings: &SaveSettings,
|
||||
) -> Result<(), String> {
|
||||
let fn_start = std::time::Instant::now();
|
||||
eprintln!("📊 [SAVE_BEAM] Starting save_beam() (SQLite container)...");
|
||||
@@ -349,7 +352,7 @@ pub fn save_beam(
|
||||
// (`Ask` == reference); smaller files are always packed.
|
||||
let reference_it = entry.is_video_audio
|
||||
|| (size >= LARGE_MEDIA_THRESHOLD
|
||||
&& _settings.large_media_mode != LargeMediaMode::Pack);
|
||||
&& settings.large_media_mode != LargeMediaMode::Pack);
|
||||
if reference_it {
|
||||
referenced = Some(rel.clone());
|
||||
} else {
|
||||
@@ -462,6 +465,117 @@ pub fn save_beam(
|
||||
}
|
||||
}
|
||||
|
||||
// --- video clips -> media rows (Video bytes), keyed by the clip id ---
|
||||
// Mirror the audio pack/reference decision: pack unless the file is
|
||||
// >= LARGE_MEDIA_THRESHOLD and the user didn't choose Pack. Packed video is
|
||||
// decoded by streaming from the blob (see video.rs `VideoSource` + ffmpeg-blob-io).
|
||||
for (clip_id, clip) in &document.video_clips {
|
||||
// In-place re-save: an unchanged packed video keeps its row, never re-streamed.
|
||||
if clip.media_id == Some(*clip_id) && txn.media_exists(*clip_id)? {
|
||||
live_media.insert(*clip_id);
|
||||
continue;
|
||||
}
|
||||
if clip.file_path.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let full = if Path::new(&clip.file_path).is_absolute() {
|
||||
PathBuf::from(&clip.file_path)
|
||||
} else {
|
||||
project_dir.join(&clip.file_path)
|
||||
};
|
||||
if !full.is_file() {
|
||||
continue; // source gone — reported missing on load
|
||||
}
|
||||
let size = std::fs::metadata(&full).map(|m| m.len()).unwrap_or(0);
|
||||
let codec = full
|
||||
.extension()
|
||||
.and_then(|x| x.to_str())
|
||||
.unwrap_or("mp4")
|
||||
.to_lowercase();
|
||||
let meta = MediaMeta {
|
||||
width: Some(clip.width as u32),
|
||||
height: Some(clip.height as u32),
|
||||
..Default::default()
|
||||
};
|
||||
let reference_it =
|
||||
size >= LARGE_MEDIA_THRESHOLD && settings.large_media_mode != LargeMediaMode::Pack;
|
||||
if reference_it {
|
||||
txn.put_media_referenced(*clip_id, MediaKind::Video, &codec, &clip.file_path, meta)?;
|
||||
} else {
|
||||
txn.put_media_packed_from_path(*clip_id, MediaKind::Video, &codec, &full, meta)?;
|
||||
// The video's audio track lives in this same blob. Point the linked
|
||||
// video-audio pool entry at the video's media row so its audio streams
|
||||
// from the blob too (instead of re-probing the external file on load).
|
||||
if let Some(aid) = clip.linked_audio_clip_id {
|
||||
if let Some(crate::clip::AudioClipType::Sampled { audio_pool_index }) =
|
||||
document.audio_clips.get(&aid).map(|c| &c.clip_type)
|
||||
{
|
||||
if let Some(e) = modified_entries
|
||||
.iter_mut()
|
||||
.find(|e| e.pool_index == *audio_pool_index)
|
||||
{
|
||||
e.media_id = Some(clip_id.to_string());
|
||||
e.relative_path = None;
|
||||
e.embedded_data = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
live_media.insert(*clip_id);
|
||||
}
|
||||
|
||||
// --- image assets -> media rows (original file bytes), keyed by asset id ---
|
||||
let mut image_count = 0usize;
|
||||
for (id, asset) in &document.image_assets {
|
||||
if let Some(ref data) = asset.data {
|
||||
let ext = asset
|
||||
.path
|
||||
.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.unwrap_or("img")
|
||||
.to_lowercase();
|
||||
txn.put_media_packed(
|
||||
*id,
|
||||
MediaKind::ImageAsset,
|
||||
&ext,
|
||||
data,
|
||||
MediaMeta { width: Some(asset.width), height: Some(asset.height), ..Default::default() },
|
||||
)?;
|
||||
live_media.insert(*id);
|
||||
image_count += 1;
|
||||
} else if txn.media_exists(*id)? {
|
||||
// Bytes not resident (paged out) but already stored — keep the row.
|
||||
live_media.insert(*id);
|
||||
}
|
||||
}
|
||||
let _ = image_count;
|
||||
|
||||
// --- embedded fonts -> media rows (Font), keyed by content hash so identical
|
||||
// fonts dedupe. Embed every non-bundled family used by a text layer so the
|
||||
// document renders faithfully on machines lacking the font. The bundled
|
||||
// three ship with the app and are never embedded. ---
|
||||
{
|
||||
use crate::layer::AnyLayer;
|
||||
let mut families: HashSet<String> = HashSet::new();
|
||||
for layer in document.all_layers() {
|
||||
if let AnyLayer::Text(tl) = layer {
|
||||
let fam = &tl.content.font_family;
|
||||
if !fam.is_empty() && !crate::fonts::is_bundled(fam) {
|
||||
families.insert(fam.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
for fam in families {
|
||||
if let Some(bytes) = crate::fonts::family_font_bytes(&fam) {
|
||||
let id = font_media_id(&bytes);
|
||||
if !txn.media_exists(id)? {
|
||||
txn.put_media_packed(id, MediaKind::Font, &fam, &bytes, MediaMeta::default())?;
|
||||
}
|
||||
live_media.insert(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- orphan cleanup: drop media for removed clips/keyframes ---
|
||||
let removed = txn.retain_media(&live_media)?;
|
||||
|
||||
@@ -472,7 +586,7 @@ pub fn save_beam(
|
||||
modified: now.clone(),
|
||||
ui_state: document.clone(),
|
||||
audio_backend: SerializedAudioBackend {
|
||||
sample_rate: 48000, // TODO: Get from audio engine
|
||||
sample_rate: audio_project.sample_rate(),
|
||||
project: audio_project.clone(),
|
||||
audio_pool_entries: modified_entries,
|
||||
layer_to_track_map: layer_to_track_map.clone(),
|
||||
@@ -525,6 +639,17 @@ fn load_beam_sqlite(path: &Path) -> Result<LoadedProject, String> {
|
||||
eprintln!("📊 [LOAD_BEAM] Starting load_beam() (SQLite container)...");
|
||||
|
||||
let archive = BeamArchive::open(path)?;
|
||||
|
||||
// Register document-embedded fonts into the runtime font collection so text
|
||||
// layers referencing them render faithfully even if the host lacks the font.
|
||||
if let Ok(font_ids) = archive.media_ids_of_kind(MediaKind::Font) {
|
||||
for id in font_ids {
|
||||
if let Ok(bytes) = archive.read_media_full(id) {
|
||||
crate::fonts::register_embedded(bytes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let json = archive.get_project_json()?;
|
||||
let beam_project: BeamProject = serde_json::from_str(&json)
|
||||
.map_err(|e| format!("Failed to deserialize project.json: {}", e))?;
|
||||
@@ -625,9 +750,14 @@ fn load_beam_sqlite(path: &Path) -> Result<LoadedProject, String> {
|
||||
}
|
||||
let _ = proxy_load_count;
|
||||
|
||||
// Image-asset bytes are NOT eagerly read (Phase 4 Tier 1 paging): `ImageAsset.data`
|
||||
// stays empty and the renderer's ImageCache pages bytes from the container on a
|
||||
// decode miss (keyed by asset id). Old base64 projects keep their deserialized
|
||||
// `data` (no container row). Loading is instant; only rendered images touch disk.
|
||||
|
||||
// Missing external files (referenced entries whose file no longer exists).
|
||||
let project_dir = path.parent().unwrap_or_else(|| Path::new("."));
|
||||
let missing_files: Vec<MissingFileInfo> = restored_entries
|
||||
let mut missing_files: Vec<MissingFileInfo> = restored_entries
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(idx, entry)| {
|
||||
@@ -651,6 +781,42 @@ fn load_beam_sqlite(path: &Path) -> Result<LoadedProject, String> {
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Resolve packed/referenced video bytes per clip (mirrors audio resolution).
|
||||
// A `MediaKind::Video` row keyed by the clip id means the bytes are in the
|
||||
// container; the decoder streams from the blob. Referenced rows update the
|
||||
// external path and report a missing source. Old projects (no Video row) stay
|
||||
// referenced via their existing `file_path`.
|
||||
for (clip_id, clip) in document.video_clips.iter_mut() {
|
||||
match archive.media_info(*clip_id) {
|
||||
Ok(Some(info)) if info.kind == MediaKind::Video => match info.storage {
|
||||
MediaStorage::Packed => {
|
||||
clip.media_id = Some(*clip_id);
|
||||
}
|
||||
MediaStorage::Referenced => {
|
||||
clip.media_id = None;
|
||||
if let Some(p) = info.ext_path.clone() {
|
||||
clip.file_path = p;
|
||||
}
|
||||
let full = if Path::new(&clip.file_path).is_absolute() {
|
||||
PathBuf::from(&clip.file_path)
|
||||
} else {
|
||||
project_dir.join(&clip.file_path)
|
||||
};
|
||||
if !clip.file_path.is_empty() && !full.exists() {
|
||||
missing_files.push(MissingFileInfo {
|
||||
pool_index: 0,
|
||||
original_path: full,
|
||||
file_type: MediaFileType::Video,
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
clip.media_id = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Persisted video thumbnail packs (opaque LBTN blobs), keyed by clip id. The
|
||||
// editor decodes + inserts them and skips regeneration for these clips.
|
||||
let mut thumbnail_blobs = std::collections::HashMap::new();
|
||||
@@ -848,8 +1014,11 @@ fn load_beam_zip_legacy(path: &Path) -> Result<LoadedProject, String> {
|
||||
for layer in document.root.children.iter_mut() {
|
||||
if let crate::layer::AnyLayer::Raster(rl) = layer {
|
||||
for kf in &mut rl.keyframes {
|
||||
if !kf.media_path.is_empty() {
|
||||
match zip.by_name(&kf.media_path) {
|
||||
// Legacy ZIP raster entries are named "media/raster/<uuid>.png",
|
||||
// derivable from the keyframe id (the old `media_path` field).
|
||||
let entry_path = format!("media/raster/{}.png", kf.id);
|
||||
{
|
||||
match zip.by_name(&entry_path) {
|
||||
Ok(mut png_file) => {
|
||||
let mut png_bytes = Vec::new();
|
||||
let _ = png_file.read_to_end(&mut png_bytes);
|
||||
@@ -859,7 +1028,7 @@ fn load_beam_zip_legacy(path: &Path) -> Result<LoadedProject, String> {
|
||||
kf.raw_pixels = rgba.into_raw();
|
||||
raster_load_count += 1;
|
||||
}
|
||||
Err(e) => eprintln!("⚠️ [LOAD_BEAM] Failed to decode raster PNG {}: {}", kf.media_path, e),
|
||||
Err(e) => eprintln!("⚠️ [LOAD_BEAM] Failed to decode raster PNG {}: {}", entry_path, e),
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
|
||||
@@ -15,7 +15,9 @@ pub const VIDEO_EXTENSIONS: &[&str] = &["mp4", "mov", "avi", "mkv", "webm", "m4v
|
||||
/// Supported MIDI file extensions
|
||||
pub const MIDI_EXTENSIONS: &[&str] = &["mid", "midi"];
|
||||
|
||||
// Note: SVG import deferred to future task
|
||||
/// Supported vector file extensions (imported as a new vector layer, not an asset)
|
||||
pub const VECTOR_EXTENSIONS: &[&str] = &["svg"];
|
||||
|
||||
// Note: .beam project files handled separately in file save/load feature
|
||||
|
||||
/// File type categories for import routing
|
||||
@@ -25,6 +27,7 @@ pub enum FileType {
|
||||
Audio,
|
||||
Video,
|
||||
Midi,
|
||||
Vector,
|
||||
}
|
||||
|
||||
/// Detect file type from extension string
|
||||
@@ -53,6 +56,9 @@ pub fn get_file_type(extension: &str) -> Option<FileType> {
|
||||
if MIDI_EXTENSIONS.contains(&ext.as_str()) {
|
||||
return Some(FileType::Midi);
|
||||
}
|
||||
if VECTOR_EXTENSIONS.contains(&ext.as_str()) {
|
||||
return Some(FileType::Vector);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
@@ -65,6 +71,7 @@ pub fn all_supported_extensions() -> Vec<&'static str> {
|
||||
all.extend_from_slice(AUDIO_EXTENSIONS);
|
||||
all.extend_from_slice(VIDEO_EXTENSIONS);
|
||||
all.extend_from_slice(MIDI_EXTENSIONS);
|
||||
all.extend_from_slice(VECTOR_EXTENSIONS);
|
||||
all
|
||||
}
|
||||
|
||||
@@ -90,7 +97,8 @@ mod tests {
|
||||
assert_eq!(get_file_type("midi"), Some(FileType::Midi));
|
||||
|
||||
assert_eq!(get_file_type("unknown"), None);
|
||||
assert_eq!(get_file_type("svg"), None); // SVG deferred
|
||||
assert_eq!(get_file_type("svg"), Some(FileType::Vector));
|
||||
assert_eq!(get_file_type("SVG"), Some(FileType::Vector));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,296 @@
|
||||
//! Font registry + text layout for text layers.
|
||||
//!
|
||||
//! Wraps a thread-local parley [`FontContext`]/[`LayoutContext`]. Three fonts are
|
||||
//! bundled (serif, sans-serif, monospaced) so text renders deterministically even
|
||||
//! offline; system fonts are also enumerated (parley's fontique source) and
|
||||
//! document-embedded fonts can be registered at load time (see `file_io`).
|
||||
//!
|
||||
//! The same `linebender_resource_handle` crate (0.1.1) backs both vello's
|
||||
//! `peniko::FontData` and parley's `FontData`, so a glyph run's `run.font()` can be
|
||||
//! handed straight to `vello::Scene::draw_glyphs` with no conversion.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::cell::RefCell;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use parley::{
|
||||
Alignment, AlignmentOptions, FontContext, FontFamily, FontFamilyName, Layout, LayoutContext,
|
||||
PositionedLayoutItem, StyleProperty,
|
||||
};
|
||||
use vello::peniko::Blob;
|
||||
|
||||
use crate::text_layer::{TextAlign, TextContent};
|
||||
|
||||
// ── Bundled fonts (SIL OFL; vendored under assets/fonts) ─────────────────────
|
||||
static BUNDLED_SANS: &[u8] = include_bytes!("../assets/fonts/LiberationSans-Regular.ttf");
|
||||
static BUNDLED_SERIF: &[u8] = include_bytes!("../assets/fonts/LiberationSerif-Regular.ttf");
|
||||
static BUNDLED_MONO: &[u8] = include_bytes!("../assets/fonts/LiberationMono-Regular.ttf");
|
||||
|
||||
/// Parley requires a brush type, but glyph color is applied by vello at draw time,
|
||||
/// so we use a zero-sized placeholder.
|
||||
#[derive(Clone, Copy, PartialEq, Default, Debug)]
|
||||
pub struct NoBrush;
|
||||
|
||||
struct FontStore {
|
||||
fcx: FontContext,
|
||||
lcx: LayoutContext<NoBrush>,
|
||||
/// Registered family names of the three bundled fonts (sans, serif, mono).
|
||||
bundled: Vec<String>,
|
||||
/// The default family (bundled sans-serif), used when `font_family` is empty.
|
||||
default_family: String,
|
||||
}
|
||||
|
||||
impl FontStore {
|
||||
fn new() -> Self {
|
||||
let mut fcx = FontContext::new();
|
||||
let mut bundled = Vec::new();
|
||||
for bytes in [BUNDLED_SANS, BUNDLED_SERIF, BUNDLED_MONO] {
|
||||
let blob = Blob::new(Arc::new(bytes) as Arc<dyn AsRef<[u8]> + Send + Sync>);
|
||||
for (family_id, _) in fcx.collection.register_fonts(blob, None) {
|
||||
if let Some(name) = fcx.collection.family_name(family_id) {
|
||||
let name = name.to_string();
|
||||
if !bundled.contains(&name) {
|
||||
bundled.push(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let default_family = bundled.first().cloned().unwrap_or_else(|| "sans-serif".to_string());
|
||||
Self { fcx, lcx: LayoutContext::new(), bundled, default_family }
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static STORE: RefCell<FontStore> = RefCell::new(FontStore::new());
|
||||
}
|
||||
|
||||
/// The default family name (bundled sans-serif), used when a text layer's
|
||||
/// `font_family` is empty.
|
||||
pub fn default_family() -> String {
|
||||
STORE.with(|s| s.borrow().default_family.clone())
|
||||
}
|
||||
|
||||
/// Whether `family` is one of the three bundled families (which therefore must
|
||||
/// never be embedded into a `.beam`).
|
||||
pub fn is_bundled(family: &str) -> bool {
|
||||
STORE.with(|s| s.borrow().bundled.iter().any(|f| f == family))
|
||||
}
|
||||
|
||||
/// True if a shorter word-prefix of `name` is itself a family in `set` — i.e. `name`
|
||||
/// is a variant of a base family (e.g. "Noto Sans Arabic" when "Noto Sans" exists).
|
||||
/// Used to collapse the many script/region-specific fonts (mostly Noto) into their
|
||||
/// base family in the picker; parley's fallback still resolves the right script font
|
||||
/// automatically when rendering non-Latin text.
|
||||
fn is_variant_of_listed_base(name: &str, set: &std::collections::HashSet<&str>) -> bool {
|
||||
let words: Vec<&str> = name.split(' ').collect();
|
||||
for k in 1..words.len() {
|
||||
if set.contains(words[..k].join(" ").as_str()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
/// Available family names for the info-panel picker: the three bundled families first,
|
||||
/// then a consolidated, alphabetical list of system families — script/region variants
|
||||
/// whose base family is present are dropped (monospace variants are kept).
|
||||
pub fn families() -> Vec<String> {
|
||||
STORE.with(|s| {
|
||||
let s = &mut *s.borrow_mut();
|
||||
|
||||
let mut system: Vec<String> =
|
||||
s.fcx.collection.family_names().map(|n| n.to_string()).collect();
|
||||
system.sort();
|
||||
system.dedup();
|
||||
let set: std::collections::HashSet<&str> = system.iter().map(|x| x.as_str()).collect();
|
||||
|
||||
let mut out = s.bundled.clone();
|
||||
for name in &system {
|
||||
if out.iter().any(|b| b == name) {
|
||||
continue;
|
||||
}
|
||||
// Keep base families and monospace variants; drop script/region variants
|
||||
// whose base family is already in the list.
|
||||
if name.contains("Mono") || !is_variant_of_listed_base(name, &set) {
|
||||
out.push(name.clone());
|
||||
}
|
||||
}
|
||||
out
|
||||
})
|
||||
}
|
||||
|
||||
/// Register a document-embedded font (raw TTF/OTF bytes) into the runtime font
|
||||
/// collection so text layers referencing its family resolve to it. Returns the
|
||||
/// registered family names.
|
||||
pub fn register_embedded(bytes: Vec<u8>) -> Vec<String> {
|
||||
STORE.with(|s| {
|
||||
let s = &mut *s.borrow_mut();
|
||||
let blob = Blob::new(Arc::new(bytes) as Arc<dyn AsRef<[u8]> + Send + Sync>);
|
||||
let mut names = Vec::new();
|
||||
for (family_id, _) in s.fcx.collection.register_fonts(blob, None) {
|
||||
if let Some(name) = s.fcx.collection.family_name(family_id) {
|
||||
names.push(name.to_string());
|
||||
}
|
||||
}
|
||||
names
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether `family` currently resolves to a registered family (bundled, system,
|
||||
/// or embedded). Used to flag "missing font" on load.
|
||||
pub fn family_available(family: &str) -> bool {
|
||||
if family.is_empty() {
|
||||
return true;
|
||||
}
|
||||
STORE.with(|s| {
|
||||
let s = &mut *s.borrow_mut();
|
||||
s.fcx.collection.family_id(family).is_some()
|
||||
})
|
||||
}
|
||||
|
||||
/// The raw bytes of the font file that `family` resolves to (for embedding into a
|
||||
/// `.beam`). Returns `None` if the family resolves to no glyphs. Lays out a single
|
||||
/// glyph and reads the resolved run's font blob (the same `linebender_resource_handle`
|
||||
/// blob vello uses).
|
||||
pub fn family_font_bytes(family: &str) -> Option<Vec<u8>> {
|
||||
let content = TextContent {
|
||||
text: "A".to_string(),
|
||||
font_family: family.to_string(),
|
||||
..TextContent::default()
|
||||
};
|
||||
with_layout(&content, 10_000.0, |layout| {
|
||||
for line in layout.lines() {
|
||||
for item in line.items() {
|
||||
if let PositionedLayoutItem::GlyphRun(run) = item {
|
||||
return Some(run.run().font().data.data().to_vec());
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
})
|
||||
}
|
||||
|
||||
// ── Background font preloading ───────────────────────────────────────────────
|
||||
//
|
||||
// Loading a family's bytes (`family_font_bytes`) is the expensive part (font file IO +
|
||||
// shaping). Doing it for the whole picker on the UI thread causes hitches, so a
|
||||
// background thread (started at app launch) loads every picker family's bytes ahead of
|
||||
// time into a shared map. The UI then only has to *register* them with its renderer
|
||||
// (cheap), and synchronously loads the few stragglers only if needed before they're ready.
|
||||
|
||||
struct PreloadState {
|
||||
loaded: HashMap<String, Vec<u8>>,
|
||||
started: bool,
|
||||
done: bool,
|
||||
}
|
||||
|
||||
fn preload() -> &'static Mutex<PreloadState> {
|
||||
static P: OnceLock<Mutex<PreloadState>> = OnceLock::new();
|
||||
P.get_or_init(|| Mutex::new(PreloadState {
|
||||
loaded: HashMap::new(),
|
||||
started: false,
|
||||
done: false,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Start (once) a background thread that loads every picker font's bytes. Idempotent;
|
||||
/// safe to call every frame or from app startup.
|
||||
pub fn start_preload() {
|
||||
{
|
||||
let mut p = preload().lock().unwrap();
|
||||
if p.started {
|
||||
return;
|
||||
}
|
||||
p.started = true;
|
||||
}
|
||||
let _ = std::thread::Builder::new()
|
||||
.name("font-preload".into())
|
||||
.spawn(|| {
|
||||
// This thread gets its own thread-local FontContext (enumerates system fonts
|
||||
// off the UI thread). Bytes are plain `Vec<u8>` (Send) handed back via the map.
|
||||
for fam in families() {
|
||||
if let Some(bytes) = family_font_bytes(&fam) {
|
||||
preload().lock().unwrap().loaded.insert(fam, bytes);
|
||||
}
|
||||
}
|
||||
preload().lock().unwrap().done = true;
|
||||
});
|
||||
}
|
||||
|
||||
/// Remove and return a preloaded font's bytes if the background thread has them ready.
|
||||
pub fn take_preloaded(family: &str) -> Option<Vec<u8>> {
|
||||
preload().lock().unwrap().loaded.remove(family)
|
||||
}
|
||||
|
||||
/// Whether the background preloader has finished loading every family.
|
||||
pub fn preload_done() -> bool {
|
||||
preload().lock().unwrap().done
|
||||
}
|
||||
|
||||
/// Caret rectangle (x0, y0, x1, y1, in layout space relative to the box origin) for
|
||||
/// `byte_index` into `content.text`, wrapped to `max_width`.
|
||||
pub fn caret_geometry(content: &TextContent, max_width: f32, byte_index: usize) -> Option<(f64, f64, f64, f64)> {
|
||||
let caret_w = (content.font_size as f32 * 0.06).max(1.0);
|
||||
with_layout(content, max_width, |layout| {
|
||||
let cur = parley::Cursor::from_byte_index(layout, byte_index, parley::Affinity::Downstream);
|
||||
let bb = cur.geometry(layout, caret_w);
|
||||
Some((bb.x0, bb.y0, bb.x1, bb.y1))
|
||||
})
|
||||
}
|
||||
|
||||
/// Selection highlight rectangles (each x0, y0, x1, y1 in layout space) for the byte
|
||||
/// range `[start, end)` into `content.text`, wrapped to `max_width`.
|
||||
pub fn selection_geometry(content: &TextContent, max_width: f32, start: usize, end: usize) -> Vec<(f64, f64, f64, f64)> {
|
||||
if start == end {
|
||||
return Vec::new();
|
||||
}
|
||||
with_layout(content, max_width, |layout| {
|
||||
let anchor = parley::Cursor::from_byte_index(layout, start, parley::Affinity::Downstream);
|
||||
let focus = parley::Cursor::from_byte_index(layout, end, parley::Affinity::Downstream);
|
||||
let sel = parley::Selection::new(anchor, focus);
|
||||
sel.geometry(layout)
|
||||
.into_iter()
|
||||
.map(|(bb, _)| (bb.x0, bb.y0, bb.x1, bb.y1))
|
||||
.collect()
|
||||
})
|
||||
}
|
||||
|
||||
fn alignment_of(a: TextAlign) -> Alignment {
|
||||
match a {
|
||||
TextAlign::Left => Alignment::Left,
|
||||
TextAlign::Center => Alignment::Center,
|
||||
TextAlign::Right => Alignment::Right,
|
||||
TextAlign::Justify => Alignment::Justify,
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a parley layout for `content` wrapped to `max_width` (document units),
|
||||
/// then invoke `f` with it. The layout is rebuilt on each call (v1: no cache).
|
||||
pub fn with_layout<R>(
|
||||
content: &TextContent,
|
||||
max_width: f32,
|
||||
f: impl FnOnce(&Layout<NoBrush>) -> R,
|
||||
) -> R {
|
||||
STORE.with(|s| {
|
||||
let s = &mut *s.borrow_mut();
|
||||
let default_family = s.default_family.clone();
|
||||
let FontStore { fcx, lcx, .. } = s;
|
||||
|
||||
let mut builder = lcx.ranged_builder(fcx, &content.text, 1.0, true);
|
||||
builder.push_default(StyleProperty::FontSize(content.font_size as f32));
|
||||
|
||||
let family_name = if content.font_family.is_empty() {
|
||||
default_family
|
||||
} else {
|
||||
content.font_family.clone()
|
||||
};
|
||||
let family = FontFamily::Single(FontFamilyName::Named(Cow::Owned(family_name)));
|
||||
builder.push_default(StyleProperty::FontFamily(family));
|
||||
|
||||
let mut layout = builder.build(&content.text);
|
||||
layout.break_all_lines(Some(max_width));
|
||||
layout.align(alignment_of(content.align), AlignmentOptions::default());
|
||||
f(&layout)
|
||||
})
|
||||
}
|
||||
@@ -105,6 +105,9 @@ pub struct CompositorLayer {
|
||||
pub opacity: f32,
|
||||
/// Blend mode for this layer
|
||||
pub blend_mode: BlendMode,
|
||||
/// Screen-blend RGB tint; `[0,0,0,0]` (the default) is a no-op. Used by
|
||||
/// onion-skin ghosts (warm = past, cool = future).
|
||||
pub tint: [f32; 4],
|
||||
}
|
||||
|
||||
impl CompositorLayer {
|
||||
@@ -113,12 +116,19 @@ impl CompositorLayer {
|
||||
buffer,
|
||||
opacity: opacity.clamp(0.0, 1.0),
|
||||
blend_mode,
|
||||
tint: [0.0; 4],
|
||||
}
|
||||
}
|
||||
|
||||
pub fn normal(buffer: BufferHandle, opacity: f32) -> Self {
|
||||
Self::new(buffer, opacity, BlendMode::Normal)
|
||||
}
|
||||
|
||||
/// Screen-blend the layer toward an RGB tint (for onion-skin ghosts).
|
||||
pub fn with_tint(mut self, r: f32, g: f32, b: f32) -> Self {
|
||||
self.tint = [r, g, b, 0.0];
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Uniform data for the composite shader
|
||||
@@ -129,8 +139,10 @@ pub struct CompositeUniforms {
|
||||
pub opacity: f32,
|
||||
/// Blend mode index
|
||||
pub blend_mode: u32,
|
||||
/// Padding for alignment
|
||||
/// Padding to 16 bytes before the vec4 tint
|
||||
pub _padding: [u32; 2],
|
||||
/// Screen-blend tint ((0,0,0) = none); `.w` unused.
|
||||
pub tint: [f32; 4],
|
||||
}
|
||||
|
||||
/// Compositor for blending layers
|
||||
@@ -323,6 +335,7 @@ impl Compositor {
|
||||
opacity: layer.opacity,
|
||||
blend_mode: layer.blend_mode.to_index(),
|
||||
_padding: [0, 0],
|
||||
tint: layer.tint,
|
||||
};
|
||||
queue.write_buffer(&uniforms_buffer, 0, bytemuck::bytes_of(&uniforms));
|
||||
|
||||
@@ -382,6 +395,8 @@ struct Uniforms {
|
||||
opacity: f32,
|
||||
blend_mode: u32,
|
||||
_padding: vec2<u32>,
|
||||
// Screen-blend tint ((0,0,0) = no tint). Used by onion-skin ghosts.
|
||||
tint: vec4<f32>,
|
||||
}
|
||||
|
||||
@group(0) @binding(0) var source_tex: texture_2d<f32>;
|
||||
@@ -526,7 +541,11 @@ fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {
|
||||
// Apply opacity
|
||||
let src_alpha = src.a * uniforms.opacity;
|
||||
|
||||
// Screen-blend tint (recolors blacks toward the tint; no-op at tint=0).
|
||||
let t = uniforms.tint.rgb;
|
||||
let tinted = src.rgb + t - src.rgb * t;
|
||||
|
||||
// Output premultiplied alpha in linear color space
|
||||
return vec4<f32>(src.rgb * src_alpha, src_alpha);
|
||||
return vec4<f32>(tinted * src_alpha, src_alpha);
|
||||
}
|
||||
"#;
|
||||
|
||||
@@ -9,6 +9,7 @@ use crate::vector_graph::VectorGraph;
|
||||
use crate::effect_layer::EffectLayer;
|
||||
use crate::object::ShapeInstance;
|
||||
use crate::raster_layer::RasterLayer;
|
||||
use crate::text_layer::TextLayer;
|
||||
use crate::shape::Shape;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
@@ -31,6 +32,8 @@ pub enum LayerType {
|
||||
Group,
|
||||
/// Raster pixel-buffer painting layer
|
||||
Raster,
|
||||
/// Text layer (a single editable text box)
|
||||
Text,
|
||||
}
|
||||
|
||||
/// Common trait for all layer types
|
||||
@@ -382,6 +385,29 @@ impl VectorLayer {
|
||||
self.keyframe_at(time).map(|kf| &kf.graph)
|
||||
}
|
||||
|
||||
/// The VectorGraph to *render* at `time`. When the keyframe at-or-before `time` has
|
||||
/// `tween_after == Shape` and the next keyframe shares its topology, returns an owned
|
||||
/// graph morphed between them; otherwise borrows the held keyframe's graph. Editing
|
||||
/// should keep using `graph_at_time`/`graph_at_time_mut` (the held keyframe).
|
||||
pub fn tweened_graph_at(&self, time: f64) -> Option<std::borrow::Cow<'_, VectorGraph>> {
|
||||
use std::borrow::Cow;
|
||||
let idx = self.keyframes.partition_point(|kf| kf.time <= time);
|
||||
if idx == 0 {
|
||||
return None;
|
||||
}
|
||||
let a = &self.keyframes[idx - 1];
|
||||
if a.tween_after == TweenType::Shape && idx < self.keyframes.len() {
|
||||
let b = &self.keyframes[idx];
|
||||
if b.time > a.time {
|
||||
let t = ((time - a.time) / (b.time - a.time)).clamp(0.0, 1.0);
|
||||
if let Some(g) = a.graph.interpolated(&b.graph, t) {
|
||||
return Some(Cow::Owned(g));
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Cow::Borrowed(&a.graph))
|
||||
}
|
||||
|
||||
/// Get a mutable VectorGraph at a given time
|
||||
pub fn graph_at_time_mut(&mut self, time: f64) -> Option<&mut VectorGraph> {
|
||||
self.keyframe_at_mut(time).map(|kf| &mut kf.graph)
|
||||
@@ -433,6 +459,25 @@ impl VectorLayer {
|
||||
time + frame_duration
|
||||
}
|
||||
|
||||
/// Start time of the group clip instance's visibility region that contains `time`:
|
||||
/// the time of the earliest keyframe reachable by walking back through consecutive
|
||||
/// keyframes that all contain the clip instance. Returns `None` if the clip instance
|
||||
/// isn't a keyframe-gated group visible at `time` (e.g. a movie clip).
|
||||
pub fn group_visibility_start(&self, clip_instance_id: &Uuid, time: f64) -> Option<f64> {
|
||||
let after = self.keyframes.partition_point(|kf| kf.time <= time);
|
||||
if after == 0 {
|
||||
return None;
|
||||
}
|
||||
let mut idx = after - 1; // keyframe at-or-before `time`
|
||||
if !self.keyframes[idx].clip_instance_ids.contains(clip_instance_id) {
|
||||
return None;
|
||||
}
|
||||
while idx > 0 && self.keyframes[idx - 1].clip_instance_ids.contains(clip_instance_id) {
|
||||
idx -= 1;
|
||||
}
|
||||
Some(self.keyframes[idx].time)
|
||||
}
|
||||
|
||||
// Shape-based methods removed — use DCEL methods instead.
|
||||
// - shapes_at_time_mut → graph_at_time_mut
|
||||
// - get_shape_in_keyframe → use DCEL vertex/edge/face accessors
|
||||
@@ -451,30 +496,53 @@ impl VectorLayer {
|
||||
&mut self.keyframes[insert_idx]
|
||||
}
|
||||
|
||||
/// Insert a new keyframe at time by cloning the DCEL from the active keyframe.
|
||||
/// Insert a new keyframe at time, taking the geometry the layer shows there.
|
||||
/// If a keyframe already exists at the exact time, does nothing and returns it.
|
||||
///
|
||||
/// Inside a shape-tween span this captures the *interpolated* geometry at `time` (not
|
||||
/// the left keyframe's), and inherits the span's `tween_after` so the new keyframe keeps
|
||||
/// tweening toward the next one — i.e. splitting a tween in two leaves the motion intact.
|
||||
pub fn insert_keyframe_from_current(&mut self, time: f64) -> &mut ShapeKeyframe {
|
||||
let tolerance = 0.001;
|
||||
if let Some(idx) = self.keyframe_index_at_exact(time, tolerance) {
|
||||
return &mut self.keyframes[idx];
|
||||
}
|
||||
|
||||
// Clone graph and clip instance IDs from the active keyframe
|
||||
let (cloned_graph, cloned_clip_ids) = self
|
||||
// Geometry shown at `time` (interpolated if mid-tween, else the held keyframe).
|
||||
let cloned_graph = self
|
||||
.tweened_graph_at(time)
|
||||
.map(|g| g.into_owned())
|
||||
.unwrap_or_else(VectorGraph::new);
|
||||
// Inherit tween + clip instances from the active (left) keyframe.
|
||||
let (tween_after, cloned_clip_ids) = self
|
||||
.keyframe_at(time)
|
||||
.map(|kf| {
|
||||
(kf.graph.clone(), kf.clip_instance_ids.clone())
|
||||
})
|
||||
.unwrap_or_else(|| (VectorGraph::new(), Vec::new()));
|
||||
.map(|kf| (kf.tween_after, kf.clip_instance_ids.clone()))
|
||||
.unwrap_or((TweenType::None, Vec::new()));
|
||||
|
||||
let insert_idx = self.keyframes.partition_point(|kf| kf.time < time);
|
||||
let mut kf = ShapeKeyframe::new(time);
|
||||
kf.graph = cloned_graph;
|
||||
kf.tween_after = tween_after;
|
||||
kf.clip_instance_ids = cloned_clip_ids;
|
||||
self.keyframes.insert(insert_idx, kf);
|
||||
&mut self.keyframes[insert_idx]
|
||||
}
|
||||
|
||||
/// True when `time` falls strictly inside a shape-tween span — i.e. an in-between frame
|
||||
/// (the left keyframe has `tween_after == Shape` and `time` is not on either keyframe).
|
||||
/// Editing such a frame would silently modify the left keyframe, so the editor blocks it.
|
||||
pub fn is_tween_inbetween(&self, time: f64) -> bool {
|
||||
let tol = 0.001;
|
||||
let idx = self.keyframes.partition_point(|kf| kf.time <= time);
|
||||
if idx == 0 || idx >= self.keyframes.len() {
|
||||
return false;
|
||||
}
|
||||
let (a, b) = (&self.keyframes[idx - 1], &self.keyframes[idx]);
|
||||
a.tween_after == TweenType::Shape
|
||||
&& (time - a.time).abs() > tol
|
||||
&& (b.time - time).abs() > tol
|
||||
}
|
||||
|
||||
/// Remove a keyframe at the exact time (within tolerance).
|
||||
/// Returns the removed keyframe if found.
|
||||
pub(crate) fn remove_keyframe_at(&mut self, time: f64, tolerance: f64) -> Option<ShapeKeyframe> {
|
||||
@@ -801,6 +869,7 @@ impl GroupLayer {
|
||||
AnyLayer::Effect(l) => &l.clip_instances,
|
||||
AnyLayer::Group(_) => &[], // no nested groups
|
||||
AnyLayer::Raster(_) => &[], // raster layers have no clip instances
|
||||
AnyLayer::Text(_) => &[], // raster layers have no clip instances
|
||||
};
|
||||
for ci in instances {
|
||||
result.push((child_id, ci));
|
||||
@@ -819,6 +888,7 @@ pub enum AnyLayer {
|
||||
Effect(EffectLayer),
|
||||
Group(GroupLayer),
|
||||
Raster(RasterLayer),
|
||||
Text(TextLayer),
|
||||
}
|
||||
|
||||
impl LayerTrait for AnyLayer {
|
||||
@@ -830,6 +900,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.id(),
|
||||
AnyLayer::Group(l) => l.id(),
|
||||
AnyLayer::Raster(l) => l.id(),
|
||||
AnyLayer::Text(l) => l.id(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -841,6 +912,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.name(),
|
||||
AnyLayer::Group(l) => l.name(),
|
||||
AnyLayer::Raster(l) => l.name(),
|
||||
AnyLayer::Text(l) => l.name(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -852,6 +924,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.set_name(name),
|
||||
AnyLayer::Group(l) => l.set_name(name),
|
||||
AnyLayer::Raster(l) => l.set_name(name),
|
||||
AnyLayer::Text(l) => l.set_name(name),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -863,6 +936,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.has_custom_name(),
|
||||
AnyLayer::Group(l) => l.has_custom_name(),
|
||||
AnyLayer::Raster(l) => l.has_custom_name(),
|
||||
AnyLayer::Text(l) => l.has_custom_name(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -874,6 +948,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.set_has_custom_name(custom),
|
||||
AnyLayer::Group(l) => l.set_has_custom_name(custom),
|
||||
AnyLayer::Raster(l) => l.set_has_custom_name(custom),
|
||||
AnyLayer::Text(l) => l.set_has_custom_name(custom),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -885,6 +960,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.visible(),
|
||||
AnyLayer::Group(l) => l.visible(),
|
||||
AnyLayer::Raster(l) => l.visible(),
|
||||
AnyLayer::Text(l) => l.visible(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -896,6 +972,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.set_visible(visible),
|
||||
AnyLayer::Group(l) => l.set_visible(visible),
|
||||
AnyLayer::Raster(l) => l.set_visible(visible),
|
||||
AnyLayer::Text(l) => l.set_visible(visible),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -907,6 +984,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.opacity(),
|
||||
AnyLayer::Group(l) => l.opacity(),
|
||||
AnyLayer::Raster(l) => l.opacity(),
|
||||
AnyLayer::Text(l) => l.opacity(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -918,6 +996,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.set_opacity(opacity),
|
||||
AnyLayer::Group(l) => l.set_opacity(opacity),
|
||||
AnyLayer::Raster(l) => l.set_opacity(opacity),
|
||||
AnyLayer::Text(l) => l.set_opacity(opacity),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -929,6 +1008,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.volume(),
|
||||
AnyLayer::Group(l) => l.volume(),
|
||||
AnyLayer::Raster(l) => l.volume(),
|
||||
AnyLayer::Text(l) => l.volume(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -940,6 +1020,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.set_volume(volume),
|
||||
AnyLayer::Group(l) => l.set_volume(volume),
|
||||
AnyLayer::Raster(l) => l.set_volume(volume),
|
||||
AnyLayer::Text(l) => l.set_volume(volume),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -951,6 +1032,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.muted(),
|
||||
AnyLayer::Group(l) => l.muted(),
|
||||
AnyLayer::Raster(l) => l.muted(),
|
||||
AnyLayer::Text(l) => l.muted(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -962,6 +1044,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.set_muted(muted),
|
||||
AnyLayer::Group(l) => l.set_muted(muted),
|
||||
AnyLayer::Raster(l) => l.set_muted(muted),
|
||||
AnyLayer::Text(l) => l.set_muted(muted),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -973,6 +1056,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.soloed(),
|
||||
AnyLayer::Group(l) => l.soloed(),
|
||||
AnyLayer::Raster(l) => l.soloed(),
|
||||
AnyLayer::Text(l) => l.soloed(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -984,6 +1068,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.set_soloed(soloed),
|
||||
AnyLayer::Group(l) => l.set_soloed(soloed),
|
||||
AnyLayer::Raster(l) => l.set_soloed(soloed),
|
||||
AnyLayer::Text(l) => l.set_soloed(soloed),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -995,6 +1080,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.locked(),
|
||||
AnyLayer::Group(l) => l.locked(),
|
||||
AnyLayer::Raster(l) => l.locked(),
|
||||
AnyLayer::Text(l) => l.locked(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1006,6 +1092,7 @@ impl LayerTrait for AnyLayer {
|
||||
AnyLayer::Effect(l) => l.set_locked(locked),
|
||||
AnyLayer::Group(l) => l.set_locked(locked),
|
||||
AnyLayer::Raster(l) => l.set_locked(locked),
|
||||
AnyLayer::Text(l) => l.set_locked(locked),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1020,6 +1107,7 @@ impl AnyLayer {
|
||||
AnyLayer::Effect(l) => &l.layer,
|
||||
AnyLayer::Group(l) => &l.layer,
|
||||
AnyLayer::Raster(l) => &l.layer,
|
||||
AnyLayer::Text(l) => &l.layer,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1032,6 +1120,7 @@ impl AnyLayer {
|
||||
AnyLayer::Effect(l) => &mut l.layer,
|
||||
AnyLayer::Group(l) => &mut l.layer,
|
||||
AnyLayer::Raster(l) => &mut l.layer,
|
||||
AnyLayer::Text(l) => &mut l.layer,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1050,6 +1139,97 @@ impl AnyLayer {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn tweened_graph_at_morphs_between_shape_keyframes() {
|
||||
use crate::vector_graph::{Direction, FillRule, ShapeColor};
|
||||
use kurbo::{CubicBez, Point};
|
||||
|
||||
// Build a single-vertex-ish graph at a given x via one degenerate fill is overkill;
|
||||
// use one vertex + one edge (a loop) is also odd. Use two vertices + one edge and
|
||||
// just check the vertex lerp through the layer's tween path.
|
||||
let mk = |x: f64| {
|
||||
let mut g = VectorGraph::new();
|
||||
let v0 = g.alloc_vertex(Point::new(x, 0.0));
|
||||
let v1 = g.alloc_vertex(Point::new(x + 10.0, 0.0));
|
||||
let c = CubicBez::new(
|
||||
Point::new(x, 0.0),
|
||||
Point::new(x + 3.0, 0.0),
|
||||
Point::new(x + 7.0, 0.0),
|
||||
Point::new(x + 10.0, 0.0),
|
||||
);
|
||||
g.alloc_edge(c, v0, v1, None, Some(ShapeColor::rgb(0, 0, 0)));
|
||||
g.alloc_fill(vec![(crate::vector_graph::EdgeId(0), Direction::Forward)],
|
||||
ShapeColor::rgb(255, 0, 0), FillRule::NonZero);
|
||||
g
|
||||
};
|
||||
|
||||
let mut layer = VectorLayer::new("L");
|
||||
layer.keyframes.clear();
|
||||
let mut kf0 = ShapeKeyframe::new(0.0);
|
||||
kf0.graph = mk(0.0);
|
||||
kf0.tween_after = TweenType::Shape;
|
||||
let mut kf10 = ShapeKeyframe::new(10.0);
|
||||
kf10.graph = mk(100.0);
|
||||
layer.keyframes.push(kf0);
|
||||
layer.keyframes.push(kf10);
|
||||
|
||||
// Midway through the tween, vertex 0 is halfway (x=50).
|
||||
let g = layer.tweened_graph_at(5.0).unwrap();
|
||||
assert!((g.vertices[0].position.x - 50.0).abs() < 1e-6);
|
||||
|
||||
// Without the tween flag, it holds the left keyframe (x=0).
|
||||
layer.keyframes[0].tween_after = TweenType::None;
|
||||
let g = layer.tweened_graph_at(5.0).unwrap();
|
||||
assert!((g.vertices[0].position.x - 0.0).abs() < 1e-6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inserting_keyframe_mid_tween_captures_interpolated_geometry_and_inherits_tween() {
|
||||
use crate::vector_graph::{Direction, FillRule, ShapeColor};
|
||||
use kurbo::{CubicBez, Point};
|
||||
|
||||
let mk = |x: f64| {
|
||||
let mut g = VectorGraph::new();
|
||||
let v0 = g.alloc_vertex(Point::new(x, 0.0));
|
||||
let v1 = g.alloc_vertex(Point::new(x + 10.0, 0.0));
|
||||
let c = CubicBez::new(
|
||||
Point::new(x, 0.0),
|
||||
Point::new(x + 3.0, 0.0),
|
||||
Point::new(x + 7.0, 0.0),
|
||||
Point::new(x + 10.0, 0.0),
|
||||
);
|
||||
g.alloc_edge(c, v0, v1, None, Some(ShapeColor::rgb(0, 0, 0)));
|
||||
g.alloc_fill(vec![(crate::vector_graph::EdgeId(0), Direction::Forward)],
|
||||
ShapeColor::rgb(255, 0, 0), FillRule::NonZero);
|
||||
g
|
||||
};
|
||||
|
||||
let mut layer = VectorLayer::new("L");
|
||||
layer.keyframes.clear();
|
||||
let mut kf_a = ShapeKeyframe::new(0.0);
|
||||
kf_a.graph = mk(0.0);
|
||||
kf_a.tween_after = TweenType::Shape;
|
||||
let mut kf_b = ShapeKeyframe::new(10.0);
|
||||
kf_b.graph = mk(100.0);
|
||||
layer.keyframes.push(kf_a);
|
||||
layer.keyframes.push(kf_b);
|
||||
|
||||
// Insert keyframe C at the midpoint of the A→B shape tween.
|
||||
layer.insert_keyframe_from_current(5.0);
|
||||
|
||||
let c = layer.keyframe_at(5.0).expect("keyframe C exists");
|
||||
// C took the interpolated geometry (x=50), not A's geometry (x=0).
|
||||
assert!((c.graph.vertices[0].position.x - 50.0).abs() < 1e-6,
|
||||
"C should hold interpolated geometry, got {}", c.graph.vertices[0].position.x);
|
||||
// C inherits the shape tween so it still morphs toward B.
|
||||
assert_eq!(c.tween_after, TweenType::Shape, "C should inherit the shape tween");
|
||||
|
||||
// The frame between C and B is still an in-between (tween continues past C).
|
||||
assert!(layer.is_tween_inbetween(7.0));
|
||||
// C itself is a keyframe, not an in-between.
|
||||
assert!(!layer.is_tween_inbetween(5.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_layer_creation() {
|
||||
let layer = Layer::new(LayerType::Vector, "Test Layer");
|
||||
|
||||
@@ -54,6 +54,8 @@ pub mod svg_export;
|
||||
pub mod snap;
|
||||
pub mod webcam;
|
||||
pub mod raster_layer;
|
||||
pub mod text_layer;
|
||||
pub mod fonts;
|
||||
pub mod raster_store;
|
||||
pub mod brush_settings;
|
||||
pub mod brush_engine;
|
||||
|
||||
@@ -47,6 +47,21 @@ impl Transform {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Set scale + position so `content_w × content_h` is fit **uniformly and centered** within
|
||||
/// `doc_w × doc_h`, preserving aspect ratio (letterbox/pillarbox). The single shared way to
|
||||
/// place a media clip (video/image) on the document — both import paths use this so a clip
|
||||
/// looks identical however it was added. No-op for non-positive content dimensions.
|
||||
pub fn fit_centered(&mut self, content_w: f64, content_h: f64, doc_w: f64, doc_h: f64) {
|
||||
if content_w <= 0.0 || content_h <= 0.0 {
|
||||
return;
|
||||
}
|
||||
let scale = (doc_w / content_w).min(doc_h / content_h);
|
||||
self.scale_x = scale;
|
||||
self.scale_y = scale;
|
||||
self.x = (doc_w - content_w * scale) / 2.0;
|
||||
self.y = (doc_h - content_h * scale) / 2.0;
|
||||
}
|
||||
|
||||
/// Create a transform with position
|
||||
pub fn with_position(x: f64, y: f64) -> Self {
|
||||
Self {
|
||||
|
||||
@@ -111,8 +111,6 @@ pub struct RasterKeyframe {
|
||||
pub time: f64,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// ZIP-relative path: `"media/raster/<uuid>.png"`
|
||||
pub media_path: String,
|
||||
/// Stroke history (for potential replay / future non-destructive editing)
|
||||
pub stroke_log: Vec<StrokeRecord>,
|
||||
pub tween_after: TweenType,
|
||||
@@ -157,13 +155,11 @@ impl RasterKeyframe {
|
||||
|
||||
pub fn new(time: f64, width: u32, height: u32) -> Self {
|
||||
let id = Uuid::new_v4();
|
||||
let media_path = format!("media/raster/{}.png", id);
|
||||
Self {
|
||||
id,
|
||||
time,
|
||||
width,
|
||||
height,
|
||||
media_path,
|
||||
stroke_log: Vec::new(),
|
||||
tween_after: TweenType::Hold,
|
||||
raw_pixels: Vec::new(),
|
||||
@@ -173,6 +169,57 @@ impl RasterKeyframe {
|
||||
proxy: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Change the canvas to `(new_w, new_h)`. `Scale` resamples the content (Lanczos3) to fill the
|
||||
/// new size; `Canvas` keeps the content at native resolution anchored top-left, padding with
|
||||
/// transparent (expand) or trimming (crop). No-op if the size is unchanged. If pixels aren't
|
||||
/// resident the buffer is left empty and only the declared size changes — the caller must fault
|
||||
/// pixels in first (a later load would otherwise mismatch the new size).
|
||||
pub fn resize_to(&mut self, new_w: u32, new_h: u32, mode: RasterResizeMode) {
|
||||
if new_w == 0 || new_h == 0 || (self.width == new_w && self.height == new_h) {
|
||||
return;
|
||||
}
|
||||
// Resample/recanvas the buffer only when pixels are resident. A blank keyframe (no content
|
||||
// and no store row) just takes the new declared size — there's nothing to corrupt. Paged-out
|
||||
// keyframes are loaded by the caller (ResizeRasterLayerAction) before this runs.
|
||||
if !self.raw_pixels.is_empty() {
|
||||
let old = std::mem::take(&mut self.raw_pixels);
|
||||
self.raw_pixels = match mode {
|
||||
RasterResizeMode::Scale => match image::RgbaImage::from_raw(self.width, self.height, old) {
|
||||
Some(img) => image::imageops::resize(&img, new_w, new_h, image::imageops::FilterType::Lanczos3).into_raw(),
|
||||
None => vec![0u8; (new_w as usize) * (new_h as usize) * 4],
|
||||
},
|
||||
RasterResizeMode::Canvas => {
|
||||
// Copy the old pixels into a transparent new buffer, anchored top-left (matching
|
||||
// the raster's (0,0) document anchor); right/bottom is padded or trimmed.
|
||||
let mut buf = vec![0u8; (new_w as usize) * (new_h as usize) * 4];
|
||||
let copy_w = self.width.min(new_w) as usize;
|
||||
let copy_h = self.height.min(new_h) as usize;
|
||||
let (ow, nw) = (self.width as usize, new_w as usize);
|
||||
for y in 0..copy_h {
|
||||
let src = y * ow * 4;
|
||||
let dst = y * nw * 4;
|
||||
buf[dst..dst + copy_w * 4].copy_from_slice(&old[src..src + copy_w * 4]);
|
||||
}
|
||||
buf
|
||||
}
|
||||
};
|
||||
self.proxy = None; // invalidate any downsampled proxy
|
||||
}
|
||||
self.width = new_w;
|
||||
self.height = new_h;
|
||||
self.texture_dirty = true;
|
||||
self.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// How a raster canvas resize treats existing pixels.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum RasterResizeMode {
|
||||
/// Resample the content to fill the new size (changes pixel resolution).
|
||||
Scale,
|
||||
/// Keep content at native resolution, anchored top-left; pad/trim the canvas.
|
||||
Canvas,
|
||||
}
|
||||
|
||||
/// A pixel-buffer painting layer
|
||||
@@ -264,10 +311,6 @@ impl RasterLayer {
|
||||
.map(|pos| self.keyframes.remove(pos))
|
||||
}
|
||||
|
||||
/// Return the ZIP-relative PNG path for the active keyframe at `time`, or `None`.
|
||||
pub fn buffer_path_at_time(&self, time: f64) -> Option<&str> {
|
||||
self.keyframe_at(time).map(|kf| kf.media_path.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
// Delegate all LayerTrait methods to self.layer
|
||||
|
||||
@@ -22,43 +22,111 @@ use vello::peniko::{Blob, Fill, ImageAlphaType, ImageBrush, ImageData, ImageForm
|
||||
use vello::Scene;
|
||||
|
||||
/// Cache for decoded image data to avoid re-decoding every frame
|
||||
/// Decoded-image cache, bounded by a byte budget with usage-LRU eviction (Phase 4
|
||||
/// asset paging). The decoded RGBA (~`w·h·4` per image) is the heavy, evictable cost;
|
||||
/// a miss re-decodes from `asset.data`. Recency is bumped on every access, so images
|
||||
/// actually rendered each frame stay resident and unused ones age out under pressure.
|
||||
pub struct ImageCache {
|
||||
cache: HashMap<Uuid, Arc<ImageBrush>>,
|
||||
/// CPU path: tiny-skia pixmaps decoded from the same assets (premultiplied RGBA8)
|
||||
cpu_cache: HashMap<Uuid, Arc<tiny_skia::Pixmap>>,
|
||||
/// Recency order (least-recent first) of resident asset ids.
|
||||
lru: Vec<Uuid>,
|
||||
/// Decoded bytes per resident asset (counted once; GPU/CPU are ~equal and a render
|
||||
/// session uses one path) and the running total.
|
||||
sizes: HashMap<Uuid, usize>,
|
||||
bytes: usize,
|
||||
/// `.beam` container path for lazily loading compressed `ImageAsset` bytes on a
|
||||
/// decode miss (Tier 1 paging) when `asset.data` isn't resident.
|
||||
container_path: Option<std::path::PathBuf>,
|
||||
}
|
||||
|
||||
impl ImageCache {
|
||||
/// Max decoded-image bytes kept resident before LRU eviction.
|
||||
const BUDGET: usize = 256 * 1024 * 1024;
|
||||
|
||||
/// Create a new empty image cache
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
cache: HashMap::new(),
|
||||
cpu_cache: HashMap::new(),
|
||||
lru: Vec::new(),
|
||||
sizes: HashMap::new(),
|
||||
bytes: 0,
|
||||
container_path: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the `.beam` container path used to lazily load image bytes that aren't
|
||||
/// resident in `asset.data` (Tier 1 paging). Cheap to call each frame.
|
||||
pub fn set_container_path(&mut self, path: Option<std::path::PathBuf>) {
|
||||
self.container_path = path;
|
||||
}
|
||||
|
||||
/// Resolve an asset's compressed bytes: prefer the resident `asset.data` (imported
|
||||
/// this session, or an old base64 project), else page from the container.
|
||||
fn resolve_bytes<'a>(&self, asset: &'a ImageAsset) -> Option<std::borrow::Cow<'a, [u8]>> {
|
||||
if let Some(d) = &asset.data {
|
||||
return Some(std::borrow::Cow::Borrowed(d.as_slice()));
|
||||
}
|
||||
let path = self.container_path.as_ref()?;
|
||||
crate::beam_archive::read_packed_media_readonly(path, asset.id)
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(std::borrow::Cow::Owned)
|
||||
}
|
||||
|
||||
/// Mark `id` (size `size` bytes) as most-recently-used; evict LRU entries over budget.
|
||||
fn touch(&mut self, id: Uuid, size: usize) {
|
||||
if !self.sizes.contains_key(&id) {
|
||||
self.sizes.insert(id, size);
|
||||
self.bytes += size;
|
||||
}
|
||||
if let Some(pos) = self.lru.iter().position(|x| *x == id) {
|
||||
self.lru.remove(pos);
|
||||
}
|
||||
self.lru.push(id);
|
||||
// Keep at least the just-touched entry resident.
|
||||
while self.bytes > Self::BUDGET && self.lru.len() > 1 {
|
||||
let old = self.lru.remove(0);
|
||||
self.cache.remove(&old);
|
||||
self.cpu_cache.remove(&old);
|
||||
if let Some(sz) = self.sizes.remove(&old) {
|
||||
self.bytes -= sz;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Get or decode an image, caching the result
|
||||
pub fn get_or_decode(&mut self, asset: &ImageAsset) -> Option<Arc<ImageBrush>> {
|
||||
if let Some(cached) = self.cache.get(&asset.id) {
|
||||
return Some(Arc::clone(cached));
|
||||
let size = (asset.width as usize) * (asset.height as usize) * 4;
|
||||
if let Some(cached) = self.cache.get(&asset.id).map(Arc::clone) {
|
||||
self.touch(asset.id, size);
|
||||
return Some(cached);
|
||||
}
|
||||
|
||||
// Decode and cache
|
||||
let image = decode_image_asset(asset)?;
|
||||
// Decode and cache (bytes from asset.data or paged from the container).
|
||||
let bytes = self.resolve_bytes(asset)?;
|
||||
let image = decode_image_brush(&bytes)?;
|
||||
let arc_image = Arc::new(image);
|
||||
self.cache.insert(asset.id, Arc::clone(&arc_image));
|
||||
self.touch(asset.id, size);
|
||||
Some(arc_image)
|
||||
}
|
||||
|
||||
/// Get or decode an image as a premultiplied tiny-skia Pixmap (CPU render path).
|
||||
pub fn get_or_decode_cpu(&mut self, asset: &ImageAsset) -> Option<Arc<tiny_skia::Pixmap>> {
|
||||
if let Some(cached) = self.cpu_cache.get(&asset.id) {
|
||||
return Some(Arc::clone(cached));
|
||||
let size = (asset.width as usize) * (asset.height as usize) * 4;
|
||||
if let Some(cached) = self.cpu_cache.get(&asset.id).map(Arc::clone) {
|
||||
self.touch(asset.id, size);
|
||||
return Some(cached);
|
||||
}
|
||||
|
||||
let pixmap = decode_image_to_pixmap(asset)?;
|
||||
let bytes = self.resolve_bytes(asset)?;
|
||||
let pixmap = decode_image_to_pixmap(&bytes)?;
|
||||
let arc = Arc::new(pixmap);
|
||||
self.cpu_cache.insert(asset.id, Arc::clone(&arc));
|
||||
self.touch(asset.id, size);
|
||||
Some(arc)
|
||||
}
|
||||
|
||||
@@ -66,12 +134,21 @@ impl ImageCache {
|
||||
pub fn invalidate(&mut self, id: &Uuid) {
|
||||
self.cache.remove(id);
|
||||
self.cpu_cache.remove(id);
|
||||
if let Some(pos) = self.lru.iter().position(|x| x == id) {
|
||||
self.lru.remove(pos);
|
||||
}
|
||||
if let Some(sz) = self.sizes.remove(id) {
|
||||
self.bytes -= sz;
|
||||
}
|
||||
}
|
||||
|
||||
/// Clear all cached images
|
||||
pub fn clear(&mut self) {
|
||||
self.cache.clear();
|
||||
self.cpu_cache.clear();
|
||||
self.lru.clear();
|
||||
self.sizes.clear();
|
||||
self.bytes = 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -81,12 +158,34 @@ impl Default for ImageCache {
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode an image asset to a premultiplied tiny-skia Pixmap (CPU render path).
|
||||
fn decode_image_to_pixmap(asset: &ImageAsset) -> Option<tiny_skia::Pixmap> {
|
||||
let data = asset.data.as_ref()?;
|
||||
/// Image asset ids referenced by the visible vector layers' active keyframes at `time`
|
||||
/// (top-level + group children). Used to prefetch/decode images ahead during playback.
|
||||
/// (Recursing into nested clip instances is a refinement.)
|
||||
pub fn assets_needed_at(document: &Document, time: f64) -> Vec<Uuid> {
|
||||
let mut ids = Vec::new();
|
||||
for layer in document.all_layers() {
|
||||
if let crate::layer::AnyLayer::Vector(vl) = layer {
|
||||
if !vl.layer.visible {
|
||||
continue;
|
||||
}
|
||||
if let Some(kf) = vl.keyframe_at(time) {
|
||||
for fill in &kf.graph.fills {
|
||||
if let Some(id) = fill.image_fill {
|
||||
ids.push(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ids
|
||||
}
|
||||
|
||||
/// Decode image bytes to a premultiplied tiny-skia Pixmap (CPU render path).
|
||||
fn decode_image_to_pixmap(data: &[u8]) -> Option<tiny_skia::Pixmap> {
|
||||
let img = image::load_from_memory(data).ok()?;
|
||||
let rgba = img.to_rgba8();
|
||||
let mut pixmap = tiny_skia::Pixmap::new(asset.width, asset.height)?;
|
||||
let (iw, ih) = rgba.dimensions();
|
||||
let mut pixmap = tiny_skia::Pixmap::new(iw, ih)?;
|
||||
for (dst, src) in pixmap.pixels_mut().iter_mut().zip(rgba.pixels()) {
|
||||
let [r, g, b, a] = src.0;
|
||||
// Convert straight alpha (image crate output) to premultiplied (tiny-skia internal format)
|
||||
@@ -100,21 +199,17 @@ fn decode_image_to_pixmap(asset: &ImageAsset) -> Option<tiny_skia::Pixmap> {
|
||||
Some(pixmap)
|
||||
}
|
||||
|
||||
/// Decode an image asset to peniko ImageBrush
|
||||
fn decode_image_asset(asset: &ImageAsset) -> Option<ImageBrush> {
|
||||
// Get the raw file data
|
||||
let data = asset.data.as_ref()?;
|
||||
|
||||
// Decode using the image crate
|
||||
/// Decode image bytes to a peniko ImageBrush (GPU render path).
|
||||
fn decode_image_brush(data: &[u8]) -> Option<ImageBrush> {
|
||||
let img = image::load_from_memory(data).ok()?;
|
||||
let rgba = img.to_rgba8();
|
||||
let (iw, ih) = rgba.dimensions();
|
||||
|
||||
// Create peniko ImageData then ImageBrush
|
||||
let image_data = ImageData {
|
||||
data: Blob::from(rgba.into_raw()),
|
||||
format: ImageFormat::Rgba8,
|
||||
width: asset.width,
|
||||
height: asset.height,
|
||||
width: iw,
|
||||
height: ih,
|
||||
alpha_type: ImageAlphaType::Alpha,
|
||||
};
|
||||
Some(ImageBrush::new(image_data))
|
||||
@@ -126,8 +221,11 @@ fn decode_image_asset(asset: &ImageAsset) -> Option<ImageBrush> {
|
||||
|
||||
/// A single decoded video frame ready for GPU upload, with its document-space transform.
|
||||
pub struct VideoRenderInstance {
|
||||
/// sRGB RGBA8 pixel data (straight alpha — as decoded by ffmpeg).
|
||||
/// sRGB RGBA8 pixel data (straight alpha — as decoded by ffmpeg). Empty when `gpu` is `Some`.
|
||||
pub rgba_data: Arc<Vec<u8>>,
|
||||
/// Hardware-decoded frame as GPU NV12 textures (preview path). When `Some`, the compositor
|
||||
/// samples it directly (NV12→RGB) instead of uploading `rgba_data`.
|
||||
pub gpu: Option<crate::video::GpuVideoFrame>,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Affine transform that maps from video-pixel space to document space.
|
||||
@@ -137,6 +235,21 @@ pub struct VideoRenderInstance {
|
||||
pub opacity: f32,
|
||||
}
|
||||
|
||||
/// Sink for pulling video frames out of a container layer's scene recursion, so
|
||||
/// they composite via the fast GPU Video path instead of baking into Vello.
|
||||
///
|
||||
/// Threaded as `Option<&mut VideoExtract>` through the isolated-render scene
|
||||
/// functions. When present, [`render_video_layer`] pushes a [`VideoRenderInstance`]
|
||||
/// instead of drawing into the Vello scene. `drew_other` is set whenever any
|
||||
/// non-video primitive (vector graph, image asset, raster) is emitted; that forces
|
||||
/// the safe Vello fallback because the container mixes video with other content
|
||||
/// and we can't preserve z-order by extraction alone.
|
||||
#[derive(Default)]
|
||||
struct VideoExtract {
|
||||
instances: Vec<VideoRenderInstance>,
|
||||
drew_other: bool,
|
||||
}
|
||||
|
||||
/// Type of rendered layer for compositor handling
|
||||
pub enum RenderedLayerType {
|
||||
/// Vector / group layer — Vello scene in `RenderedLayer::scene` is used.
|
||||
@@ -256,6 +369,20 @@ pub struct CompositeRenderResult {
|
||||
/// and effects in the GPU compositor.
|
||||
///
|
||||
/// Layers are returned in bottom-to-top order for compositing.
|
||||
/// Decode-target resolution for video clips = the output (export/preview) resolution, derived from
|
||||
/// the document→output `base_transform` scale. The decoder caps this to the source's native size,
|
||||
/// so it means "decode at the size we'll actually display, never upscaling": full detail when
|
||||
/// exporting above document res (instead of upscaling a document-res frame), and cheap small frames
|
||||
/// for the canvas. Stable per render pass, so it doesn't thrash the decoder's scaler/cache.
|
||||
fn video_decode_target(document: &Document, base_transform: Affine) -> (u32, u32) {
|
||||
let c = base_transform.as_coeffs(); // [a, b, c, d, e, f]
|
||||
let sx = (c[0] * c[0] + c[1] * c[1]).sqrt();
|
||||
let sy = (c[2] * c[2] + c[3] * c[3]).sqrt();
|
||||
let w = (document.width * sx).ceil().max(1.0) as u32;
|
||||
let h = (document.height * sy).ceil().max(1.0) as u32;
|
||||
(w, h)
|
||||
}
|
||||
|
||||
pub fn render_document_for_compositing(
|
||||
document: &Document,
|
||||
base_transform: Affine,
|
||||
@@ -333,6 +460,30 @@ pub fn render_document_for_compositing(
|
||||
}
|
||||
}
|
||||
|
||||
// One-shot diagnostic: dump what the compositor actually receives. Set
|
||||
// LB_LAYER_DEBUG=1 to print a single snapshot of each layer's resolved type.
|
||||
if std::env::var("LB_LAYER_DEBUG").is_ok() {
|
||||
static ONCE: std::sync::Once = std::sync::Once::new();
|
||||
ONCE.call_once(|| {
|
||||
eprintln!("[LB_LAYER_DEBUG] composite layers = {}", rendered_layers.len());
|
||||
for (i, l) in rendered_layers.iter().enumerate() {
|
||||
let desc = match &l.layer_type {
|
||||
RenderedLayerType::Vector =>
|
||||
format!("Vector (has_content={}, scene_empty={})", l.has_content, l.cpu_pixmap.is_none()),
|
||||
RenderedLayerType::Raster { width, height, dirty, .. } =>
|
||||
format!("Raster {width}x{height} dirty={dirty}"),
|
||||
RenderedLayerType::Video { instances } =>
|
||||
format!("Video ({} instance(s))", instances.len()),
|
||||
RenderedLayerType::Float { width, height, .. } =>
|
||||
format!("Float {width}x{height}"),
|
||||
RenderedLayerType::Effect { effect_instances } =>
|
||||
format!("Effect ({} instance(s))", effect_instances.len()),
|
||||
};
|
||||
eprintln!("[LB_LAYER_DEBUG] layer[{i}] id={} type={desc}", l.layer_id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
CompositeRenderResult {
|
||||
background,
|
||||
background_cpu: None,
|
||||
@@ -367,6 +518,9 @@ pub fn render_layer_isolated(
|
||||
// Render layer content with full opacity (1.0) - opacity applied during compositing
|
||||
match layer {
|
||||
AnyLayer::Vector(vector_layer) => {
|
||||
// Render into the scene with an extraction sink so a clip that is purely
|
||||
// video (no vector geometry) composites via the fast GPU Video path.
|
||||
let mut ex = VideoExtract::default();
|
||||
render_vector_layer_to_scene(
|
||||
document,
|
||||
time,
|
||||
@@ -376,10 +530,28 @@ pub fn render_layer_isolated(
|
||||
1.0, // Full opacity - layer opacity handled in compositing
|
||||
image_cache,
|
||||
video_manager,
|
||||
Some(&mut ex),
|
||||
);
|
||||
rendered.has_content = vector_layer.graph_at_time(time)
|
||||
.map_or(false, |graph| !graph.edges.iter().all(|e| e.deleted) || !graph.fills.iter().all(|f| f.deleted))
|
||||
|| !vector_layer.clip_instances.is_empty();
|
||||
if !ex.instances.is_empty() && !ex.drew_other {
|
||||
// Pure video: discard the (now-empty) scene and emit GPU instances.
|
||||
rendered.scene = Scene::new();
|
||||
rendered.has_content = true;
|
||||
rendered.layer_type = RenderedLayerType::Video { instances: ex.instances };
|
||||
} else {
|
||||
if !ex.instances.is_empty() {
|
||||
// Mixed video + vector: the first pass diverted the video out of
|
||||
// the scene, so re-render with no sink to bake it back in (correct
|
||||
// z-order; Vello path). Rare — fast-splitting is deferred.
|
||||
rendered.scene = Scene::new();
|
||||
render_vector_layer_to_scene(
|
||||
document, time, vector_layer, &mut rendered.scene,
|
||||
base_transform, 1.0, image_cache, video_manager, None,
|
||||
);
|
||||
}
|
||||
rendered.has_content = vector_layer.graph_at_time(time)
|
||||
.map_or(false, |graph| !graph.edges.iter().all(|e| e.deleted) || !graph.fills.iter().all(|f| f.deleted))
|
||||
|| !vector_layer.clip_instances.is_empty();
|
||||
}
|
||||
}
|
||||
AnyLayer::Audio(_) => {
|
||||
// Audio layers don't render visually
|
||||
@@ -390,12 +562,13 @@ pub fn render_layer_isolated(
|
||||
let layer_opacity = layer.opacity();
|
||||
let mut video_mgr = video_manager.lock().unwrap();
|
||||
let mut instances = Vec::new();
|
||||
let (target_w, target_h) = video_decode_target(document, base_transform);
|
||||
|
||||
let tempo_map = document.tempo_map();
|
||||
for clip_instance in &video_layer.clip_instances {
|
||||
let Some(video_clip) = document.video_clips.get(&clip_instance.clip_id) else { continue };
|
||||
let Some(clip_time) = clip_instance.remap_time(time, video_clip.duration, tempo_map) else { continue };
|
||||
let Some(frame) = video_mgr.get_frame(&clip_instance.clip_id, clip_time) else { continue };
|
||||
let Some(frame) = video_mgr.get_frame(&clip_instance.clip_id, clip_time, target_w, target_h) else { continue };
|
||||
|
||||
// Evaluate animated transform properties.
|
||||
let anim = &video_layer.layer.animation_data;
|
||||
@@ -439,6 +612,7 @@ pub fn render_layer_isolated(
|
||||
};
|
||||
instances.push(VideoRenderInstance {
|
||||
rgba_data: frame.rgba_data.clone(),
|
||||
gpu: frame.gpu.clone(),
|
||||
width: frame.width,
|
||||
height: frame.height,
|
||||
transform: base_transform * clip_transform * frame_to_clip,
|
||||
@@ -459,6 +633,7 @@ pub fn render_layer_isolated(
|
||||
* Affine::scale(scale);
|
||||
instances.push(VideoRenderInstance {
|
||||
rgba_data: frame.rgba_data.clone(),
|
||||
gpu: None, // webcam frames are always CPU
|
||||
width: frame.width,
|
||||
height: frame.height,
|
||||
transform: cam_transform,
|
||||
@@ -482,15 +657,34 @@ pub fn render_layer_isolated(
|
||||
return RenderedLayer::effect_layer(layer_id, opacity, active_effects);
|
||||
}
|
||||
AnyLayer::Group(group_layer) => {
|
||||
// Render each child layer's content into the group's scene
|
||||
// Render each child into the group's scene with an extraction sink. The
|
||||
// common imported-video case is a Group[Video, Audio] — audio draws
|
||||
// nothing, so it's pure video and composites via the GPU Video path.
|
||||
let mut ex = VideoExtract::default();
|
||||
for child in &group_layer.children {
|
||||
render_layer(
|
||||
document, time, child, &mut rendered.scene, base_transform,
|
||||
1.0, // Full opacity - layer opacity handled in compositing
|
||||
image_cache, video_manager, camera_frame,
|
||||
image_cache, video_manager, camera_frame, Some(&mut ex),
|
||||
);
|
||||
}
|
||||
rendered.has_content = !group_layer.children.is_empty();
|
||||
if !ex.instances.is_empty() && !ex.drew_other {
|
||||
rendered.scene = Scene::new();
|
||||
rendered.has_content = true;
|
||||
rendered.layer_type = RenderedLayerType::Video { instances: ex.instances };
|
||||
} else {
|
||||
if !ex.instances.is_empty() {
|
||||
// Mixed: re-render with no sink to bake the video back into the scene.
|
||||
rendered.scene = Scene::new();
|
||||
for child in &group_layer.children {
|
||||
render_layer(
|
||||
document, time, child, &mut rendered.scene, base_transform,
|
||||
1.0, image_cache, video_manager, camera_frame, None,
|
||||
);
|
||||
}
|
||||
}
|
||||
rendered.has_content = !group_layer.children.is_empty();
|
||||
}
|
||||
}
|
||||
AnyLayer::Raster(raster_layer) => {
|
||||
if let Some(kf) = raster_layer.keyframe_at(time) {
|
||||
@@ -504,6 +698,11 @@ pub fn render_layer_isolated(
|
||||
};
|
||||
}
|
||||
}
|
||||
AnyLayer::Text(text_layer) => {
|
||||
// Text composites as vector geometry (glyphs in the Vello scene).
|
||||
rendered.has_content =
|
||||
render_text_layer_to_scene(text_layer, time, &mut rendered.scene, base_transform);
|
||||
}
|
||||
}
|
||||
|
||||
rendered
|
||||
@@ -519,6 +718,7 @@ fn render_vector_layer_to_scene(
|
||||
parent_opacity: f64,
|
||||
image_cache: &mut ImageCache,
|
||||
video_manager: &std::sync::Arc<std::sync::Mutex<crate::video::VideoManager>>,
|
||||
extract: Option<&mut VideoExtract>,
|
||||
) {
|
||||
render_vector_layer(
|
||||
document,
|
||||
@@ -529,6 +729,7 @@ fn render_vector_layer_to_scene(
|
||||
parent_opacity,
|
||||
image_cache,
|
||||
video_manager,
|
||||
extract,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -561,6 +762,57 @@ fn render_raster_layer_to_scene(
|
||||
scene.fill(Fill::NonZero, base_transform, &brush, None, &canvas_rect);
|
||||
}
|
||||
|
||||
/// Render a text layer's glyphs into a Vello scene.
|
||||
///
|
||||
/// Text is laid out with parley (wrapped to the box width) and drawn via
|
||||
/// `Scene::draw_glyphs`. The box origin offsets the whole layout; `base_transform`
|
||||
/// carries the layer/clip-instance transform and camera. Returns whether anything
|
||||
/// was drawn.
|
||||
fn render_text_layer_to_scene(
|
||||
layer: &crate::text_layer::TextLayer,
|
||||
time: f64,
|
||||
scene: &mut Scene,
|
||||
base_transform: Affine,
|
||||
) -> bool {
|
||||
let content = layer.content_at(time);
|
||||
if content.text.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let color = vello::peniko::Color::new(content.color);
|
||||
let origin = Affine::translate((layer.box_origin.x, layer.box_origin.y));
|
||||
let mut drew = false;
|
||||
crate::fonts::with_layout(content, layer.box_width as f32, |layout| {
|
||||
for line in layout.lines() {
|
||||
for item in line.items() {
|
||||
let parley::PositionedLayoutItem::GlyphRun(glyph_run) = item else { continue };
|
||||
let run = glyph_run.run();
|
||||
let font = run.font();
|
||||
let font_size = run.font_size();
|
||||
let synthesis = run.synthesis();
|
||||
let glyph_xform = synthesis
|
||||
.skew()
|
||||
.map(|angle| Affine::skew((angle as f64).to_radians().tan(), 0.0));
|
||||
drew = true;
|
||||
scene
|
||||
.draw_glyphs(font)
|
||||
.font_size(font_size)
|
||||
.brush(color)
|
||||
.transform(base_transform * origin)
|
||||
.glyph_transform(glyph_xform)
|
||||
.draw(
|
||||
Fill::NonZero,
|
||||
glyph_run.positioned_glyphs().map(|g| vello::Glyph {
|
||||
id: g.id as u32,
|
||||
x: g.x,
|
||||
y: g.y,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
drew
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Legacy Single-Scene Rendering (kept for backwards compatibility)
|
||||
// ============================================================================
|
||||
@@ -596,10 +848,10 @@ pub fn render_document_with_transform(
|
||||
for layer in document.visible_layers() {
|
||||
if any_soloed {
|
||||
if layer.soloed() {
|
||||
render_layer(document, time, layer, scene, base_transform, 1.0, image_cache, video_manager, None);
|
||||
render_layer(document, time, layer, scene, base_transform, 1.0, image_cache, video_manager, None, None);
|
||||
}
|
||||
} else {
|
||||
render_layer(document, time, layer, scene, base_transform, 1.0, image_cache, video_manager, None);
|
||||
render_layer(document, time, layer, scene, base_transform, 1.0, image_cache, video_manager, None, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -660,10 +912,11 @@ fn render_layer(
|
||||
image_cache: &mut ImageCache,
|
||||
video_manager: &std::sync::Arc<std::sync::Mutex<crate::video::VideoManager>>,
|
||||
camera_frame: Option<&crate::webcam::CaptureFrame>,
|
||||
mut extract: Option<&mut VideoExtract>,
|
||||
) {
|
||||
match layer {
|
||||
AnyLayer::Vector(vector_layer) => {
|
||||
render_vector_layer(document, time, vector_layer, scene, base_transform, parent_opacity, image_cache, video_manager)
|
||||
render_vector_layer(document, time, vector_layer, scene, base_transform, parent_opacity, image_cache, video_manager, extract)
|
||||
}
|
||||
AnyLayer::Audio(_) => {
|
||||
// Audio layers don't render visually
|
||||
@@ -671,20 +924,27 @@ fn render_layer(
|
||||
AnyLayer::Video(video_layer) => {
|
||||
let mut video_mgr = video_manager.lock().unwrap();
|
||||
let layer_camera_frame = if video_layer.camera_enabled { camera_frame } else { None };
|
||||
render_video_layer(document, time, video_layer, scene, base_transform, parent_opacity, &mut video_mgr, layer_camera_frame);
|
||||
render_video_layer(document, time, video_layer, scene, base_transform, parent_opacity, &mut video_mgr, layer_camera_frame, extract);
|
||||
}
|
||||
AnyLayer::Effect(_) => {
|
||||
// Effect layers are processed during GPU compositing, not rendered to scene
|
||||
}
|
||||
AnyLayer::Group(group_layer) => {
|
||||
// Render each child layer in the group
|
||||
// Render each child layer in the group, passing the extract sink down.
|
||||
for child in &group_layer.children {
|
||||
render_layer(document, time, child, scene, base_transform, parent_opacity, image_cache, video_manager, camera_frame);
|
||||
render_layer(document, time, child, scene, base_transform, parent_opacity, image_cache, video_manager, camera_frame, extract.as_deref_mut());
|
||||
}
|
||||
}
|
||||
AnyLayer::Raster(raster_layer) => {
|
||||
// Raster is non-video content — force the Vello fallback if extracting.
|
||||
if let Some(ex) = extract.as_deref_mut() { ex.drew_other = true; }
|
||||
render_raster_layer_to_scene(raster_layer, time, scene, base_transform);
|
||||
}
|
||||
AnyLayer::Text(text_layer) => {
|
||||
// Text is non-video content — force the Vello fallback if extracting.
|
||||
if let Some(ex) = extract.as_deref_mut() { ex.drew_other = true; }
|
||||
render_text_layer_to_scene(text_layer, time, scene, base_transform);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -721,6 +981,7 @@ pub fn render_single_clip_instance(
|
||||
render_clip_instance(
|
||||
document, time, clip_instance, layer_opacity, scene, base_transform,
|
||||
&vector_layer.layer.animation_data, image_cache, video_manager, group_end_time,
|
||||
None, // edit-inside-clip overlay keeps the Vello path
|
||||
);
|
||||
}
|
||||
|
||||
@@ -736,6 +997,7 @@ fn render_clip_instance(
|
||||
image_cache: &mut ImageCache,
|
||||
video_manager: &std::sync::Arc<std::sync::Mutex<crate::video::VideoManager>>,
|
||||
group_end_time: Option<f64>,
|
||||
mut extract: Option<&mut VideoExtract>,
|
||||
) {
|
||||
// Try to find the clip in the document's clip libraries
|
||||
// For now, only handle VectorClips (VideoClip and AudioClip rendering not yet implemented)
|
||||
@@ -877,7 +1139,7 @@ fn render_clip_instance(
|
||||
if !layer_node.data.visible() {
|
||||
continue;
|
||||
}
|
||||
render_layer(document, clip_time, &layer_node.data, scene, instance_transform, clip_opacity, image_cache, video_manager, None);
|
||||
render_layer(document, clip_time, &layer_node.data, scene, instance_transform, clip_opacity, image_cache, video_manager, None, extract.as_deref_mut());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -891,6 +1153,7 @@ fn render_video_layer(
|
||||
parent_opacity: f64,
|
||||
video_manager: &mut crate::video::VideoManager,
|
||||
camera_frame: Option<&crate::webcam::CaptureFrame>,
|
||||
mut extract: Option<&mut VideoExtract>,
|
||||
) {
|
||||
use crate::animation::TransformProperty;
|
||||
|
||||
@@ -913,8 +1176,9 @@ fn render_video_layer(
|
||||
continue; // Clip instance not active at this time
|
||||
};
|
||||
|
||||
// Get video frame from VideoManager
|
||||
let Some(frame) = video_manager.get_frame(&clip_instance.clip_id, clip_time) else {
|
||||
// Get video frame from VideoManager at the output (export/preview) resolution.
|
||||
let (target_w, target_h) = video_decode_target(document, base_transform);
|
||||
let Some(frame) = video_manager.get_frame(&clip_instance.clip_id, clip_time, target_w, target_h) else {
|
||||
continue; // Frame not available
|
||||
};
|
||||
|
||||
@@ -1056,14 +1320,27 @@ fn render_video_layer(
|
||||
Affine::IDENTITY
|
||||
};
|
||||
|
||||
// Render video frame as image fill
|
||||
scene.fill(
|
||||
Fill::NonZero,
|
||||
instance_transform,
|
||||
&image_with_alpha,
|
||||
Some(brush_transform),
|
||||
&video_rect,
|
||||
);
|
||||
// Extract to the GPU Video path when a sink is present; otherwise bake into
|
||||
// the Vello scene. The combined frame-pixel → document transform is
|
||||
// instance_transform * brush_transform (matching the top-level Video path).
|
||||
if let Some(ex) = extract.as_deref_mut() {
|
||||
ex.instances.push(VideoRenderInstance {
|
||||
rgba_data: frame.rgba_data.clone(),
|
||||
gpu: frame.gpu.clone(),
|
||||
width: frame.width,
|
||||
height: frame.height,
|
||||
transform: instance_transform * brush_transform,
|
||||
opacity: final_opacity,
|
||||
});
|
||||
} else {
|
||||
scene.fill(
|
||||
Fill::NonZero,
|
||||
instance_transform,
|
||||
&image_with_alpha,
|
||||
Some(brush_transform),
|
||||
&video_rect,
|
||||
);
|
||||
}
|
||||
clip_rendered = true;
|
||||
}
|
||||
|
||||
@@ -1099,13 +1376,26 @@ fn render_video_layer(
|
||||
* Affine::translate((offset_x, offset_y))
|
||||
* Affine::scale(uniform_scale);
|
||||
|
||||
scene.fill(
|
||||
Fill::NonZero,
|
||||
preview_transform,
|
||||
&image_with_alpha,
|
||||
None,
|
||||
&frame_rect,
|
||||
);
|
||||
// preview_transform maps frame-pixel space → document directly, so it
|
||||
// is exactly the instance transform for the GPU path.
|
||||
if let Some(ex) = extract.as_deref_mut() {
|
||||
ex.instances.push(VideoRenderInstance {
|
||||
rgba_data: frame.rgba_data.clone(),
|
||||
gpu: None, // webcam frames are always CPU
|
||||
width: frame.width,
|
||||
height: frame.height,
|
||||
transform: preview_transform,
|
||||
opacity: final_opacity,
|
||||
});
|
||||
} else {
|
||||
scene.fill(
|
||||
Fill::NonZero,
|
||||
preview_transform,
|
||||
&image_with_alpha,
|
||||
None,
|
||||
&frame_rect,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1115,7 +1405,7 @@ fn render_video_layer(
|
||||
/// The axis is centred on the bbox midpoint and oriented at `angle_deg` degrees
|
||||
/// (0 = left→right, 90 = top→bottom). The axis extends ± half the bbox diagonal
|
||||
/// so the gradient covers the entire shape regardless of angle.
|
||||
fn gradient_bbox_endpoints(angle_deg: f32, bbox: kurbo::Rect) -> (kurbo::Point, kurbo::Point) {
|
||||
pub(crate) fn gradient_bbox_endpoints(angle_deg: f32, bbox: kurbo::Rect) -> (kurbo::Point, kurbo::Point) {
|
||||
let cx = bbox.center().x;
|
||||
let cy = bbox.center().y;
|
||||
let dx = bbox.width();
|
||||
@@ -1162,7 +1452,15 @@ pub fn render_vector_graph(
|
||||
if let Some(image_asset) = document.get_image_asset(&image_asset_id) {
|
||||
if let Some(image) = image_cache.get_or_decode(image_asset) {
|
||||
let image_with_alpha = (*image).clone().with_alpha(opacity_f32);
|
||||
scene.fill(fill_rule, base_transform, &image_with_alpha, None, &path);
|
||||
// Map the image (native pixel space, origin 0,0) onto the fill's
|
||||
// bounding box, so it sits where the shape is and scales to fit
|
||||
// (1:1 for an image-sized rectangle).
|
||||
let bbox = vello::kurbo::Shape::bounding_box(&path);
|
||||
let iw = (image_asset.width.max(1)) as f64;
|
||||
let ih = (image_asset.height.max(1)) as f64;
|
||||
let brush_transform = Affine::translate((bbox.x0, bbox.y0))
|
||||
* Affine::scale_non_uniform(bbox.width() / iw, bbox.height() / ih);
|
||||
scene.fill(fill_rule, base_transform, &image_with_alpha, Some(brush_transform), &path);
|
||||
filled = true;
|
||||
}
|
||||
}
|
||||
@@ -1249,11 +1547,21 @@ fn render_vector_layer(
|
||||
parent_opacity: f64,
|
||||
image_cache: &mut ImageCache,
|
||||
video_manager: &std::sync::Arc<std::sync::Mutex<crate::video::VideoManager>>,
|
||||
mut extract: Option<&mut VideoExtract>,
|
||||
) {
|
||||
// Cascade opacity: parent_opacity × layer.opacity
|
||||
let layer_opacity = parent_opacity * layer.layer.opacity;
|
||||
|
||||
// Render clip instances first (they appear under shape instances)
|
||||
// Render the layer's own VectorGraph (loose shapes) first, then clip instances
|
||||
// (groups / movie clips) on top. Shape tweens are applied here.
|
||||
if let Some(graph) = layer.tweened_graph_at(time) {
|
||||
// Loose vector geometry (and any image-asset fills) is non-video content —
|
||||
// force the Vello fallback. Conservative: a present-but-empty graph still
|
||||
// trips this, which only costs the fallback, never correctness.
|
||||
if let Some(ex) = extract.as_deref_mut() { ex.drew_other = true; }
|
||||
render_vector_graph(&graph, scene, base_transform, layer_opacity, document, image_cache);
|
||||
}
|
||||
|
||||
for clip_instance in &layer.clip_instances {
|
||||
// For groups, compute the visibility end from keyframe data
|
||||
let group_end_time = document.vector_clips.get(&clip_instance.clip_id)
|
||||
@@ -1262,12 +1570,7 @@ fn render_vector_layer(
|
||||
let frame_duration = 1.0 / document.framerate;
|
||||
layer.group_visibility_end(&clip_instance.id, clip_instance.timeline_start, frame_duration)
|
||||
});
|
||||
render_clip_instance(document, time, clip_instance, layer_opacity, scene, base_transform, &layer.layer.animation_data, image_cache, video_manager, group_end_time);
|
||||
}
|
||||
|
||||
// Render VectorGraph from active keyframe
|
||||
if let Some(graph) = layer.graph_at_time(time) {
|
||||
render_vector_graph(graph, scene, base_transform, layer_opacity, document, image_cache);
|
||||
render_clip_instance(document, time, clip_instance, layer_opacity, scene, base_transform, &layer.layer.animation_data, image_cache, video_manager, group_end_time, extract.as_deref_mut());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1486,12 +1789,21 @@ fn render_vector_graph_cpu(
|
||||
if let Some(image_asset_id) = fill.image_fill {
|
||||
if let Some(asset) = document.get_image_asset(&image_asset_id) {
|
||||
if let Some(img_pixmap) = image_cache.get_or_decode_cpu(asset) {
|
||||
// Map the image's native pixel space onto the fill's bounding box.
|
||||
let bbox: kurbo::Rect = vello::kurbo::Shape::bounding_box(&path);
|
||||
let iw = (asset.width.max(1)) as f32;
|
||||
let ih = (asset.height.max(1)) as f32;
|
||||
let sx = (bbox.width() as f32) / iw;
|
||||
let sy = (bbox.height() as f32) / ih;
|
||||
let pat_tf = tiny_skia::Transform::from_row(
|
||||
sx, 0.0, 0.0, sy, bbox.x0 as f32, bbox.y0 as f32,
|
||||
);
|
||||
let pattern = tiny_skia::Pattern::new(
|
||||
tiny_skia::Pixmap::as_ref(&img_pixmap),
|
||||
tiny_skia::SpreadMode::Pad,
|
||||
tiny_skia::FilterQuality::Bilinear,
|
||||
opacity,
|
||||
tiny_skia::Transform::identity(),
|
||||
pat_tf,
|
||||
);
|
||||
let mut paint = tiny_skia::Paint::default();
|
||||
paint.shader = pattern;
|
||||
@@ -1555,6 +1867,11 @@ fn render_vector_layer_cpu(
|
||||
) {
|
||||
let layer_opacity = parent_opacity * layer.layer.opacity;
|
||||
|
||||
// Loose shapes first, then clip instances (groups / movie clips) on top.
|
||||
if let Some(graph) = layer.tweened_graph_at(time) {
|
||||
render_vector_graph_cpu(&graph, pixmap, affine_to_ts(base_transform), layer_opacity as f32, document, image_cache);
|
||||
}
|
||||
|
||||
for clip_instance in &layer.clip_instances {
|
||||
let group_end_time = document.vector_clips.get(&clip_instance.clip_id)
|
||||
.filter(|vc| vc.is_group)
|
||||
@@ -1567,10 +1884,6 @@ fn render_vector_layer_cpu(
|
||||
&layer.layer.animation_data, image_cache, group_end_time,
|
||||
);
|
||||
}
|
||||
|
||||
if let Some(graph) = layer.graph_at_time(time) {
|
||||
render_vector_graph_cpu(graph, pixmap, affine_to_ts(base_transform), layer_opacity as f32, document, image_cache);
|
||||
}
|
||||
}
|
||||
|
||||
/// Render a clip instance (and its nested layers) to a CPU pixmap.
|
||||
@@ -1648,7 +1961,9 @@ fn render_vector_content_cpu(
|
||||
render_vector_content_cpu(document, time, child, pixmap, base_transform, parent_opacity, image_cache);
|
||||
}
|
||||
}
|
||||
AnyLayer::Audio(_) | AnyLayer::Video(_) | AnyLayer::Effect(_) | AnyLayer::Raster(_) => {}
|
||||
// Text is not rendered in the tiny-skia CPU fallback (GPU path only) for v1.
|
||||
AnyLayer::Audio(_) | AnyLayer::Video(_) | AnyLayer::Effect(_) | AnyLayer::Raster(_)
|
||||
| AnyLayer::Text(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,9 +4,8 @@
|
||||
|
||||
use crate::vector_graph::{VectorGraph, EdgeId, FillId, VertexId};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashSet;
|
||||
use uuid::Uuid;
|
||||
use vello::kurbo::{Affine, BezPath};
|
||||
|
||||
/// Shape of a raster pixel selection, in canvas pixel coordinates.
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -440,42 +439,6 @@ impl Selection {
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a temporary region-based selection.
|
||||
///
|
||||
/// When a region select is active, the region boundary is inserted into the
|
||||
/// DCEL as invisible edges, splitting existing geometry. Faces inside the
|
||||
/// region are added to the normal `Selection`. If the user performs an
|
||||
/// operation, the selection is committed; if they deselect, the DCEL is
|
||||
/// restored from the snapshot.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RegionSelection {
|
||||
/// The clipping region as a closed BezPath (polygon or rect)
|
||||
pub region_path: BezPath,
|
||||
/// Layer containing the affected elements
|
||||
pub layer_id: Uuid,
|
||||
/// Keyframe time
|
||||
pub time: f64,
|
||||
/// Snapshot of the graph before region boundary insertion, for revert
|
||||
pub graph_snapshot: VectorGraph,
|
||||
/// The extracted graph containing geometry inside the region
|
||||
pub selected_graph: VectorGraph,
|
||||
/// Transform applied to the selected graph (e.g. from dragging)
|
||||
pub transform: Affine,
|
||||
/// Whether the selection has been committed (via an operation on the selection)
|
||||
pub committed: bool,
|
||||
/// IDs of the invisible edges inserted for the region boundary stroke.
|
||||
/// These exist in the main graph (remainder side). Deleted during merge-back.
|
||||
pub region_edge_ids: Vec<EdgeId>,
|
||||
/// Action epoch recorded when this selection was created.
|
||||
/// Compared against `ActionExecutor::epoch()` on deselect to decide
|
||||
/// whether merge-back is needed or a clean snapshot restore suffices.
|
||||
pub action_epoch_at_selection: u64,
|
||||
/// selected_graph VID → main graph VID for boundary vertices (shared between both graphs).
|
||||
pub boundary_vertex_map: HashMap<VertexId, VertexId>,
|
||||
/// selected_graph boundary EID → main graph boundary EID (duplicated edges to skip on merge).
|
||||
pub boundary_edge_map: HashMap<EdgeId, EdgeId>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -218,3 +218,274 @@ fn cubic_to_svg_path(curve: &CubicBez) -> String {
|
||||
curve.p3.x, curve.p3.y,
|
||||
)
|
||||
}
|
||||
|
||||
// ===========================================================================
|
||||
// Document / VectorGraph → SVG (the current model). The functions above target
|
||||
// the legacy DCEL and are kept only for the clipboard stub.
|
||||
// ===========================================================================
|
||||
|
||||
use crate::document::Document;
|
||||
use crate::gradient::{GradientExtend, GradientType, ShapeGradient};
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::shape::{Cap, FillRule, Join, ShapeColor};
|
||||
use crate::vector_graph::{FillId, VectorGraph};
|
||||
use kurbo::{BezPath, PathEl, Rect, Shape};
|
||||
|
||||
/// Serialize the document's **vector** content to a standalone SVG string, at document time `time`.
|
||||
/// Vector layers (and groups of them) only — raster/video/audio/effect layers are skipped (a later
|
||||
/// pass can rasterize them to `<image>`). Animation is a single static frame at `time`.
|
||||
pub fn document_to_svg(document: &Document, time: f64) -> String {
|
||||
let (w, h) = (document.width, document.height);
|
||||
let mut defs = String::new();
|
||||
let mut body = String::new();
|
||||
let mut grad_n = 0usize;
|
||||
|
||||
// Opaque background rect (skip if the document background is transparent).
|
||||
let bg = document.background_color;
|
||||
if bg.a > 0 {
|
||||
body.push_str(&format!(
|
||||
r#"<rect x="0" y="0" width="{w:.3}" height="{h:.3}" {}/>"#,
|
||||
fill_attrs(&bg)
|
||||
));
|
||||
}
|
||||
|
||||
for layer in &document.root.children {
|
||||
layer_to_svg(layer, time, 1.0, &mut body, &mut defs, &mut grad_n);
|
||||
}
|
||||
|
||||
format!(
|
||||
concat!(
|
||||
r#"<svg xmlns="http://www.w3.org/2000/svg" width="{:.0}" height="{:.0}" "#,
|
||||
r#"viewBox="0 0 {:.3} {:.3}"><defs>{}</defs>{}</svg>"#
|
||||
),
|
||||
w, h, w, h, defs, body
|
||||
)
|
||||
}
|
||||
|
||||
/// Append one layer's SVG. Recurses into groups (`<g>`); other non-vector layer types are skipped.
|
||||
fn layer_to_svg(layer: &AnyLayer, time: f64, parent_opacity: f64, body: &mut String, defs: &mut String, grad_n: &mut usize) {
|
||||
match layer {
|
||||
AnyLayer::Vector(vl) => {
|
||||
if !vl.layer.visible {
|
||||
return; // hidden layers are not rendered, so don't export them
|
||||
}
|
||||
let opacity = parent_opacity * vl.layer.opacity;
|
||||
if let Some(graph) = vl.tweened_graph_at(time) {
|
||||
let wrap = opacity < 0.999;
|
||||
if wrap {
|
||||
body.push_str(&format!(r#"<g opacity="{opacity:.4}">"#));
|
||||
}
|
||||
vector_graph_to_svg(&graph, body, defs, grad_n);
|
||||
if wrap {
|
||||
body.push_str("</g>");
|
||||
}
|
||||
}
|
||||
// NOTE: placed clip instances (nested clips with their own transform) are not yet
|
||||
// exported — a refinement once loose-geometry export is verified.
|
||||
}
|
||||
AnyLayer::Group(g) => {
|
||||
if !g.layer.visible {
|
||||
return;
|
||||
}
|
||||
// Render children first; only emit the <g> wrapper if it has exportable content
|
||||
// (avoids empty groups when every child is a non-vector/hidden layer).
|
||||
let mut inner = String::new();
|
||||
for child in &g.children {
|
||||
layer_to_svg(child, time, 1.0, &mut inner, defs, grad_n);
|
||||
}
|
||||
if !inner.is_empty() {
|
||||
let opacity = parent_opacity * g.layer.opacity;
|
||||
body.push_str(&format!(r#"<g opacity="{opacity:.4}">"#));
|
||||
body.push_str(&inner);
|
||||
body.push_str("</g>");
|
||||
}
|
||||
}
|
||||
// Raster/Video/Audio/Effect have no lossless vector representation — skipped this pass.
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Emit a vector graph's fills (`<path fill>`) and stroked edges (`<path stroke>`) into `body`,
|
||||
/// accumulating any gradients into `defs`. Geometry is in document space (no per-layer transform).
|
||||
fn vector_graph_to_svg(graph: &VectorGraph, body: &mut String, defs: &mut String, grad_n: &mut usize) {
|
||||
// Fills first (drawn under strokes, matching the renderer).
|
||||
for (i, fill) in graph.fills.iter().enumerate() {
|
||||
if fill.deleted {
|
||||
continue;
|
||||
}
|
||||
let path = graph.fill_to_bezpath(FillId(i as u32));
|
||||
let d = bezpath_to_d(&path);
|
||||
if d.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let rule = match fill.fill_rule {
|
||||
FillRule::NonZero => "nonzero",
|
||||
FillRule::EvenOdd => "evenodd",
|
||||
};
|
||||
|
||||
if let Some(grad) = &fill.gradient_fill {
|
||||
let id = format!("grad{}", *grad_n);
|
||||
*grad_n += 1;
|
||||
defs.push_str(&gradient_to_svg(grad, &id, path.bounding_box()));
|
||||
body.push_str(&format!(r#"<path fill="url(#{id})" fill-rule="{rule}" d="{d}"/>"#));
|
||||
} else if fill.image_fill.is_some() {
|
||||
// Image fills need <image>/<pattern> + asset embedding — skipped this (vector-only) pass.
|
||||
continue;
|
||||
} else if let Some(c) = &fill.color {
|
||||
body.push_str(&format!(r#"<path {} fill-rule="{rule}" d="{d}"/>"#, fill_attrs(c)));
|
||||
}
|
||||
}
|
||||
|
||||
// Strokes: one <path> per stroked edge (each edge may carry its own style).
|
||||
for edge in &graph.edges {
|
||||
if edge.deleted {
|
||||
continue;
|
||||
}
|
||||
if let (Some(style), Some(color)) = (&edge.stroke_style, &edge.stroke_color) {
|
||||
let d = cubic_to_svg_path(&edge.curve);
|
||||
body.push_str(&format!(
|
||||
r#"<path fill="none" {} stroke-width="{:.3}" stroke-linecap="{}" stroke-linejoin="{}" stroke-miterlimit="{:.3}" d="{d}"/>"#,
|
||||
stroke_attrs(color), style.width, cap_str(style.cap), join_str(style.join), style.miter_limit
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `<linearGradient>` / `<radialGradient>` definition matching the renderer's start/end semantics.
|
||||
fn gradient_to_svg(grad: &ShapeGradient, id: &str, bbox: Rect) -> String {
|
||||
use kurbo::Point;
|
||||
// Mirror renderer.rs: explicit world endpoints if present (radial reflects the edge through the
|
||||
// center so midpoint(start,end) == center), else derive from angle + bbox.
|
||||
let (start, end) = match (grad.start_world, grad.end_world) {
|
||||
(Some((sx, sy)), Some((ex, ey))) => match grad.kind {
|
||||
GradientType::Linear => (Point::new(sx, sy), Point::new(ex, ey)),
|
||||
GradientType::Radial => (Point::new(2.0 * sx - ex, 2.0 * sy - ey), Point::new(ex, ey)),
|
||||
},
|
||||
_ => crate::renderer::gradient_bbox_endpoints(grad.angle, bbox),
|
||||
};
|
||||
|
||||
let stops: String = grad
|
||||
.stops
|
||||
.iter()
|
||||
.map(|s| {
|
||||
format!(
|
||||
r##"<stop offset="{:.4}" stop-color="#{:02x}{:02x}{:02x}" stop-opacity="{:.4}"/>"##,
|
||||
s.position, s.color.r, s.color.g, s.color.b, s.color.a as f32 / 255.0
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let spread = match grad.extend {
|
||||
GradientExtend::Pad => "pad",
|
||||
GradientExtend::Reflect => "reflect",
|
||||
GradientExtend::Repeat => "repeat",
|
||||
};
|
||||
|
||||
match grad.kind {
|
||||
GradientType::Linear => format!(
|
||||
r#"<linearGradient id="{id}" gradientUnits="userSpaceOnUse" x1="{:.3}" y1="{:.3}" x2="{:.3}" y2="{:.3}" spreadMethod="{spread}">{stops}</linearGradient>"#,
|
||||
start.x, start.y, end.x, end.y
|
||||
),
|
||||
GradientType::Radial => {
|
||||
let (cx, cy) = ((start.x + end.x) * 0.5, (start.y + end.y) * 0.5);
|
||||
let r = (((end.x - start.x).powi(2) + (end.y - start.y).powi(2)).sqrt()) * 0.5;
|
||||
format!(
|
||||
r#"<radialGradient id="{id}" gradientUnits="userSpaceOnUse" cx="{cx:.3}" cy="{cy:.3}" r="{r:.3}" spreadMethod="{spread}">{stops}</radialGradient>"#
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// kurbo `BezPath` → SVG path-data string (`M/L/Q/C/Z`).
|
||||
fn bezpath_to_d(path: &BezPath) -> String {
|
||||
let mut d = String::new();
|
||||
for el in path.elements() {
|
||||
match el {
|
||||
PathEl::MoveTo(p) => d.push_str(&format!("M{:.3} {:.3} ", p.x, p.y)),
|
||||
PathEl::LineTo(p) => d.push_str(&format!("L{:.3} {:.3} ", p.x, p.y)),
|
||||
PathEl::QuadTo(p1, p) => d.push_str(&format!("Q{:.3} {:.3} {:.3} {:.3} ", p1.x, p1.y, p.x, p.y)),
|
||||
PathEl::CurveTo(p1, p2, p) => d.push_str(&format!(
|
||||
"C{:.3} {:.3} {:.3} {:.3} {:.3} {:.3} ",
|
||||
p1.x, p1.y, p2.x, p2.y, p.x, p.y
|
||||
)),
|
||||
PathEl::ClosePath => d.push_str("Z "),
|
||||
}
|
||||
}
|
||||
d.trim_end().to_string()
|
||||
}
|
||||
|
||||
// sRGB color → SVG attributes. Hex color + a separate `*-opacity` for max compatibility (Inkscape).
|
||||
fn fill_attrs(c: &ShapeColor) -> String {
|
||||
if c.a == 255 {
|
||||
format!(r##"fill="#{:02x}{:02x}{:02x}""##, c.r, c.g, c.b)
|
||||
} else {
|
||||
format!(r##"fill="#{:02x}{:02x}{:02x}" fill-opacity="{:.4}""##, c.r, c.g, c.b, c.a as f32 / 255.0)
|
||||
}
|
||||
}
|
||||
fn stroke_attrs(c: &ShapeColor) -> String {
|
||||
if c.a == 255 {
|
||||
format!(r##"stroke="#{:02x}{:02x}{:02x}""##, c.r, c.g, c.b)
|
||||
} else {
|
||||
format!(r##"stroke="#{:02x}{:02x}{:02x}" stroke-opacity="{:.4}""##, c.r, c.g, c.b, c.a as f32 / 255.0)
|
||||
}
|
||||
}
|
||||
fn cap_str(cap: Cap) -> &'static str {
|
||||
match cap {
|
||||
Cap::Butt => "butt",
|
||||
Cap::Round => "round",
|
||||
Cap::Square => "square",
|
||||
}
|
||||
}
|
||||
fn join_str(join: Join) -> &'static str {
|
||||
match join {
|
||||
Join::Miter => "miter",
|
||||
Join::Round => "round",
|
||||
Join::Bevel => "bevel",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod export_tests {
|
||||
use super::*;
|
||||
use crate::shape::{ShapeColor, StrokeStyle};
|
||||
use crate::vector_graph::{Direction, VectorGraph};
|
||||
use kurbo::{CubicBez, Point};
|
||||
|
||||
fn line(a: Point, b: Point) -> CubicBez {
|
||||
// Degenerate cubic representing a straight segment (matches our model).
|
||||
CubicBez::new(a, a.lerp(b, 1.0 / 3.0), a.lerp(b, 2.0 / 3.0), b)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn solid_triangle_fill_and_stroke() {
|
||||
let mut g = VectorGraph::new();
|
||||
let p0 = Point::new(10.0, 10.0);
|
||||
let p1 = Point::new(90.0, 10.0);
|
||||
let p2 = Point::new(50.0, 80.0);
|
||||
let v0 = g.alloc_vertex(p0);
|
||||
let v1 = g.alloc_vertex(p1);
|
||||
let v2 = g.alloc_vertex(p2);
|
||||
let stroke = Some(StrokeStyle { width: 2.0, ..Default::default() });
|
||||
let scol = Some(ShapeColor::rgb(0, 0, 0));
|
||||
let e0 = g.alloc_edge(line(p0, p1), v0, v1, stroke.clone(), scol);
|
||||
let e1 = g.alloc_edge(line(p1, p2), v1, v2, stroke.clone(), scol);
|
||||
let e2 = g.alloc_edge(line(p2, p0), v2, v0, stroke.clone(), scol);
|
||||
g.alloc_fill(
|
||||
vec![(e0, Direction::Forward), (e1, Direction::Forward), (e2, Direction::Forward)],
|
||||
ShapeColor::rgb(255, 0, 0),
|
||||
crate::shape::FillRule::NonZero,
|
||||
);
|
||||
|
||||
let mut body = String::new();
|
||||
let mut defs = String::new();
|
||||
let mut n = 0;
|
||||
vector_graph_to_svg(&g, &mut body, &mut defs, &mut n);
|
||||
|
||||
assert!(body.contains(r##"fill="#ff0000""##), "fill color missing: {body}");
|
||||
assert!(body.contains(r#"fill-rule="nonzero""#), "fill-rule missing: {body}");
|
||||
assert!(body.contains(r#"fill="none""#), "stroke path missing: {body}");
|
||||
assert!(body.contains(r#"stroke-width="2.000""#), "stroke width missing: {body}");
|
||||
assert!(defs.is_empty(), "no gradients expected: {defs}");
|
||||
// 1 fill path + 3 stroked edges = 4 <path> elements.
|
||||
assert_eq!(body.matches("<path").count(), 4, "{body}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
//! Text layer for Lightningbeam
|
||||
//!
|
||||
//! A text layer holds a single editable text field inside a resizable box,
|
||||
//! with editable size, color, and font. Text is rendered as vector glyphs
|
||||
//! (via parley + Vello) so it composites through the same path as vector art.
|
||||
//!
|
||||
//! The text/style fields are grouped in [`TextContent`] so they can move to a
|
||||
//! per-keyframe model later without touching call sites; v1 stores a single
|
||||
//! static instance and reads it through [`TextLayer::content_at`].
|
||||
|
||||
use crate::layer::{Layer, LayerTrait, LayerType};
|
||||
use kurbo::Point;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::hash::{Hash, Hasher};
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Horizontal alignment of text within the box.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum TextAlign {
|
||||
Left,
|
||||
Center,
|
||||
Right,
|
||||
Justify,
|
||||
}
|
||||
|
||||
impl Default for TextAlign {
|
||||
fn default() -> Self {
|
||||
TextAlign::Left
|
||||
}
|
||||
}
|
||||
|
||||
/// The text content + styling for a text layer.
|
||||
///
|
||||
/// Grouped as its own struct so a future keyframed model can store
|
||||
/// `Vec<TextKeyframe>` of these without changing the layer's public shape.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct TextContent {
|
||||
/// The text string.
|
||||
pub text: String,
|
||||
/// Font size in pixels (document space).
|
||||
pub font_size: f64,
|
||||
/// Fill color, linear RGBA in 0..=1.
|
||||
pub color: [f32; 4],
|
||||
/// Logical font family name. Empty string = the bundled default font.
|
||||
pub font_family: String,
|
||||
/// Horizontal alignment within the box.
|
||||
pub align: TextAlign,
|
||||
}
|
||||
|
||||
impl Default for TextContent {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
text: String::new(),
|
||||
font_size: 48.0,
|
||||
color: [1.0, 1.0, 1.0, 1.0],
|
||||
font_family: String::new(),
|
||||
align: TextAlign::Left,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TextContent {
|
||||
/// A stable hash of everything that affects shaped layout (everything except
|
||||
/// `color`, which only affects the brush, not glyph positions). Used to key
|
||||
/// the renderer's external parley-layout cache, including the wrap width.
|
||||
pub fn layout_hash(&self, box_width: f64) -> u64 {
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
self.text.hash(&mut h);
|
||||
self.font_size.to_bits().hash(&mut h);
|
||||
self.font_family.hash(&mut h);
|
||||
self.align.hash(&mut h);
|
||||
box_width.to_bits().hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Hash for TextAlign {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
(*self as u8).hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
/// A text layer: a single resizable text box.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct TextLayer {
|
||||
/// Base layer properties (id, name, opacity, visibility, animation data, …).
|
||||
pub layer: Layer,
|
||||
/// Top-left of the text box, in layer/clip-local space.
|
||||
pub box_origin: Point,
|
||||
/// Box width in document units (drives text wrapping).
|
||||
pub box_width: f64,
|
||||
/// Box height in document units.
|
||||
pub box_height: f64,
|
||||
/// The text content + styling (single static instance for v1).
|
||||
pub content: TextContent,
|
||||
}
|
||||
|
||||
impl TextLayer {
|
||||
/// Default text-box dimensions for a freshly created layer.
|
||||
pub const DEFAULT_WIDTH: f64 = 300.0;
|
||||
pub const DEFAULT_HEIGHT: f64 = 100.0;
|
||||
|
||||
/// Create a new, empty text layer with the given name, positioned at `origin`.
|
||||
pub fn new(name: impl Into<String>, origin: Point) -> Self {
|
||||
Self {
|
||||
layer: Layer::new(LayerType::Text, name),
|
||||
box_origin: origin,
|
||||
box_width: Self::DEFAULT_WIDTH,
|
||||
box_height: Self::DEFAULT_HEIGHT,
|
||||
content: TextContent::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Read the active text content at `time`. v1 is static, so `time` is unused;
|
||||
/// a future keyframed model will select the active keyframe here.
|
||||
pub fn content_at(&self, _time: f64) -> &TextContent {
|
||||
&self.content
|
||||
}
|
||||
|
||||
/// Mutable access to the active text content at `time`.
|
||||
pub fn content_at_mut(&mut self, _time: f64) -> &mut TextContent {
|
||||
&mut self.content
|
||||
}
|
||||
}
|
||||
|
||||
// Delegate all LayerTrait methods to self.layer (mirrors RasterLayer).
|
||||
impl LayerTrait for TextLayer {
|
||||
fn id(&self) -> Uuid { self.layer.id }
|
||||
fn name(&self) -> &str { &self.layer.name }
|
||||
fn set_name(&mut self, name: String) { self.layer.name = name; }
|
||||
fn has_custom_name(&self) -> bool { self.layer.has_custom_name }
|
||||
fn set_has_custom_name(&mut self, custom: bool) { self.layer.has_custom_name = custom; }
|
||||
fn visible(&self) -> bool { self.layer.visible }
|
||||
fn set_visible(&mut self, visible: bool) { self.layer.visible = visible; }
|
||||
fn opacity(&self) -> f64 { self.layer.opacity }
|
||||
fn set_opacity(&mut self, opacity: f64) { self.layer.opacity = opacity; }
|
||||
fn volume(&self) -> f64 { self.layer.volume }
|
||||
fn set_volume(&mut self, volume: f64) { self.layer.volume = volume; }
|
||||
fn muted(&self) -> bool { self.layer.muted }
|
||||
fn set_muted(&mut self, muted: bool) { self.layer.muted = muted; }
|
||||
fn soloed(&self) -> bool { self.layer.soloed }
|
||||
fn set_soloed(&mut self, soloed: bool) { self.layer.soloed = soloed; }
|
||||
fn locked(&self) -> bool { self.layer.locked }
|
||||
fn set_locked(&mut self, locked: bool) { self.layer.locked = locked; }
|
||||
}
|
||||
@@ -381,7 +381,9 @@ impl Tool {
|
||||
use crate::layer::LayerType;
|
||||
match layer_type {
|
||||
None | Some(LayerType::Vector) => Tool::all(),
|
||||
Some(LayerType::Audio) | Some(LayerType::Video) => &[Tool::Select, Tool::Split],
|
||||
// The Text tool is available on audio/video/raster too: clicking the
|
||||
// stage with it there creates a new top-level text layer.
|
||||
Some(LayerType::Audio) | Some(LayerType::Video) => &[Tool::Select, Tool::Split, Tool::Text],
|
||||
Some(LayerType::Raster) => &[
|
||||
// Brush tools
|
||||
Tool::Draw, Tool::Pencil, Tool::Pen, Tool::Airbrush,
|
||||
@@ -397,9 +399,10 @@ impl Tool {
|
||||
// Transform
|
||||
Tool::Transform, Tool::Warp, Tool::Liquify,
|
||||
// Utility
|
||||
Tool::Eyedropper,
|
||||
Tool::Eyedropper, Tool::Text,
|
||||
],
|
||||
_ => &[Tool::Select],
|
||||
Some(LayerType::Text) => &[Tool::Select, Tool::Text, Tool::Transform],
|
||||
_ => &[Tool::Select, Tool::Text],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -351,6 +351,29 @@ impl VectorGraph {
|
||||
}
|
||||
}
|
||||
|
||||
/// Free any vertex no longer referenced by a non-deleted edge (e.g. after deleting a shape's
|
||||
/// edges), so stale vertices don't linger as snap targets.
|
||||
pub fn gc_isolated_vertices(&mut self) {
|
||||
let mut referenced = vec![false; self.vertices.len()];
|
||||
for e in &self.edges {
|
||||
if e.deleted {
|
||||
continue;
|
||||
}
|
||||
for v in e.vertices.iter() {
|
||||
if !v.is_none() {
|
||||
referenced[v.idx()] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
let to_free: Vec<VertexId> = (0..self.vertices.len())
|
||||
.filter(|&i| !self.vertices[i].deleted && !referenced[i])
|
||||
.map(|i| VertexId(i as u32))
|
||||
.collect();
|
||||
for vid in to_free {
|
||||
self.free_vertex(vid);
|
||||
}
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// Fill / hit-test queries
|
||||
// -------------------------------------------------------------------
|
||||
@@ -417,6 +440,152 @@ impl VectorGraph {
|
||||
self.boundary_to_bezpath(&fill.boundary)
|
||||
}
|
||||
|
||||
/// Interpolate toward `other` by `t` ∈ [0,1] for a same-topology shape tween.
|
||||
///
|
||||
/// Returns `None` if the two graphs don't share identical topology — same vertex,
|
||||
/// edge and fill structure (counts, deleted flags, edge endpoints, fill boundaries).
|
||||
/// In that case the caller should hold the source keyframe instead of morphing.
|
||||
/// Vertex positions, edge curves, stroke widths and stroke/fill colours are lerped.
|
||||
pub fn interpolated(&self, other: &VectorGraph, t: f64) -> Option<VectorGraph> {
|
||||
if self.vertices.len() != other.vertices.len()
|
||||
|| self.edges.len() != other.edges.len()
|
||||
|| self.fills.len() != other.fills.len()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
for (a, b) in self.vertices.iter().zip(&other.vertices) {
|
||||
if a.deleted != b.deleted {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
for (a, b) in self.edges.iter().zip(&other.edges) {
|
||||
if a.deleted != b.deleted || a.vertices != b.vertices {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
for (a, b) in self.fills.iter().zip(&other.fills) {
|
||||
if a.deleted != b.deleted || a.boundary != b.boundary {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
let lf = |x: f64, y: f64| x + (y - x) * t;
|
||||
let lp = |p: Point, q: Point| Point::new(lf(p.x, q.x), lf(p.y, q.y));
|
||||
let lc = |a: Option<ShapeColor>, b: Option<ShapeColor>| match (a, b) {
|
||||
(Some(a), Some(b)) => {
|
||||
let c = |x: u8, y: u8| (lf(x as f64, y as f64)).round().clamp(0.0, 255.0) as u8;
|
||||
Some(ShapeColor::new(c(a.r, b.r), c(a.g, b.g), c(a.b, b.b), c(a.a, b.a)))
|
||||
}
|
||||
(a, _) => a,
|
||||
};
|
||||
|
||||
let mut g = self.clone();
|
||||
for (i, v) in g.vertices.iter_mut().enumerate() {
|
||||
v.position = lp(self.vertices[i].position, other.vertices[i].position);
|
||||
}
|
||||
for (i, e) in g.edges.iter_mut().enumerate() {
|
||||
let (a, b) = (self.edges[i].curve, other.edges[i].curve);
|
||||
e.curve = CubicBez::new(lp(a.p0, b.p0), lp(a.p1, b.p1), lp(a.p2, b.p2), lp(a.p3, b.p3));
|
||||
if let (Some(s), Some(sa), Some(sb)) = (
|
||||
e.stroke_style.as_mut(),
|
||||
self.edges[i].stroke_style.as_ref(),
|
||||
other.edges[i].stroke_style.as_ref(),
|
||||
) {
|
||||
s.width = lf(sa.width, sb.width);
|
||||
}
|
||||
e.stroke_color = lc(self.edges[i].stroke_color, other.edges[i].stroke_color);
|
||||
}
|
||||
for (i, f) in g.fills.iter_mut().enumerate() {
|
||||
f.color = lc(self.fills[i].color, other.fills[i].color);
|
||||
}
|
||||
Some(g)
|
||||
}
|
||||
|
||||
/// A point guaranteed to lie inside the fill — for point-in-region classification
|
||||
/// (e.g. deciding whether a fill is inside a lasso). Prefers the polygon area-centroid,
|
||||
/// but for a non-convex fill (e.g. an L-shape, where the area-centroid can fall in the
|
||||
/// concavity *outside* the shape) it steps just inward from a boundary edge instead.
|
||||
/// The naive average of boundary-edge midpoints is NOT reliable here — it can land
|
||||
/// outside a non-convex fill and misclassify it.
|
||||
pub fn fill_interior_point(&self, fill_id: FillId) -> Point {
|
||||
let boundary = self.fills[fill_id.idx()].boundary.clone();
|
||||
self.boundary_interior_point(&boundary)
|
||||
}
|
||||
|
||||
/// A point guaranteed to lie inside the region enclosed by a `(edge, direction)`
|
||||
/// boundary loop. See [`fill_interior_point`].
|
||||
pub fn boundary_interior_point(&self, boundary: &[(EdgeId, Direction)]) -> Point {
|
||||
use kurbo::{ParamCurve, Shape, Vec2};
|
||||
let path = self.boundary_to_bezpath(boundary);
|
||||
|
||||
// Ordered polygon corners: the directed start point of each boundary edge.
|
||||
let mut pts: Vec<Point> = Vec::new();
|
||||
for &(eid, dir) in boundary {
|
||||
if eid.is_none() {
|
||||
continue;
|
||||
}
|
||||
let c = self.edges[eid.idx()].curve;
|
||||
pts.push(match dir {
|
||||
Direction::Forward => c.p0,
|
||||
Direction::Backward => c.p3,
|
||||
});
|
||||
}
|
||||
if pts.len() < 3 {
|
||||
if pts.is_empty() {
|
||||
return Point::ZERO;
|
||||
}
|
||||
let (sx, sy) = pts.iter().fold((0.0, 0.0), |(x, y), p| (x + p.x, y + p.y));
|
||||
return Point::new(sx / pts.len() as f64, sy / pts.len() as f64);
|
||||
}
|
||||
|
||||
// Shoelace area-centroid.
|
||||
let (mut a2, mut cx, mut cy) = (0.0, 0.0, 0.0);
|
||||
for i in 0..pts.len() {
|
||||
let p0 = pts[i];
|
||||
let p1 = pts[(i + 1) % pts.len()];
|
||||
let cross = p0.x * p1.y - p1.x * p0.y;
|
||||
a2 += cross;
|
||||
cx += (p0.x + p1.x) * cross;
|
||||
cy += (p0.y + p1.y) * cross;
|
||||
}
|
||||
if a2.abs() > 1e-9 {
|
||||
let c = Point::new(cx / (3.0 * a2), cy / (3.0 * a2));
|
||||
if path.winding(c) != 0 {
|
||||
return c;
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: step a small distance inward from a boundary edge midpoint.
|
||||
let (mut minx, mut miny, mut maxx, mut maxy) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
|
||||
for p in &pts {
|
||||
minx = minx.min(p.x);
|
||||
miny = miny.min(p.y);
|
||||
maxx = maxx.max(p.x);
|
||||
maxy = maxy.max(p.y);
|
||||
}
|
||||
let eps = ((maxx - minx).min(maxy - miny) * 1e-3).max(1e-4);
|
||||
for &(eid, _) in boundary {
|
||||
if eid.is_none() {
|
||||
continue;
|
||||
}
|
||||
let c = self.edges[eid.idx()].curve;
|
||||
let mid = c.eval(0.5);
|
||||
let tangent = c.eval(0.5001) - c.eval(0.4999);
|
||||
let len = tangent.hypot();
|
||||
if len < 1e-12 {
|
||||
continue;
|
||||
}
|
||||
let n = Vec2::new(-tangent.y / len, tangent.x / len);
|
||||
for s in [1.0_f64, -1.0] {
|
||||
let cand = mid + n * (s * eps);
|
||||
if path.winding(cand) != 0 {
|
||||
return cand;
|
||||
}
|
||||
}
|
||||
}
|
||||
pts[0]
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------
|
||||
// Vertex editing
|
||||
// -------------------------------------------------------------------
|
||||
@@ -653,6 +822,10 @@ impl VectorGraph {
|
||||
}
|
||||
|
||||
let mut all_new_edges = Vec::new();
|
||||
// Sub-edges produced when a stroke segment splits an existing edge (incl. an earlier
|
||||
// segment of this same stroke). Tracked separately so they reach the fill re-tracer
|
||||
// without polluting the returned edge list.
|
||||
let mut split_products: Vec<EdgeId> = Vec::new();
|
||||
let mut prev_end_vertex: Option<VertexId> = None;
|
||||
|
||||
for (seg_idx, seg) in expanded_segments.iter().enumerate() {
|
||||
@@ -706,7 +879,14 @@ impl VectorGraph {
|
||||
let remapped_t = original_edge_t / head_end;
|
||||
let remapped_t = remapped_t.clamp(ENDPOINT_T_MARGIN, 1.0 - ENDPOINT_T_MARGIN);
|
||||
|
||||
let (mid_v, _sub_a, _sub_b) = self.split_edge(eid, remapped_t);
|
||||
let (mid_v, sub_a, sub_b) = self.split_edge(eid, remapped_t);
|
||||
// Track the split products so the fill re-tracer sees them: when a later
|
||||
// stroke segment crosses an earlier one, these sub-edges are part of the
|
||||
// stroke's arrangement but would otherwise be invisible to the re-trace.
|
||||
// (Kept out of `all_new_edges` so the returned edge list stays the stroke's
|
||||
// own edges only.)
|
||||
split_products.push(sub_a);
|
||||
split_products.push(sub_b);
|
||||
// Snap vertex to intersection point
|
||||
self.vertices[mid_v.idx()].position = point;
|
||||
// Merge with nearby existing vertex if within snap distance
|
||||
@@ -791,127 +971,513 @@ impl VectorGraph {
|
||||
prev_end_vertex = Some(end_v);
|
||||
}
|
||||
|
||||
// Fill splitting pass: for each new edge, check if both endpoints
|
||||
// lie on any fill's boundary — if so, split that fill.
|
||||
let edges_to_check = all_new_edges.clone();
|
||||
for &eid in &edges_to_check {
|
||||
let v0 = self.edges[eid.idx()].vertices[0];
|
||||
let v1 = self.edges[eid.idx()].vertices[1];
|
||||
// Weld dangling stroke endpoints onto a near-coincident existing vertex. A
|
||||
// self-intersecting freehand stroke can create an intersection vertex a fraction of
|
||||
// a pixel away from a segment endpoint that should be the same point; if they don't
|
||||
// merge, the stroke's loop is broken by a degree-1 stub and the cut is lost.
|
||||
self.weld_dangling_endpoints(&all_new_edges, snap_epsilon.max(1.0));
|
||||
|
||||
// Find fills where both v0 and v1 appear as boundary vertices
|
||||
let fill_ids: Vec<FillId> = self.fills
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, f)| !f.deleted)
|
||||
.filter(|(_, f)| {
|
||||
let has_v0 = f.boundary.iter().any(|&(be, _)| {
|
||||
let e = &self.edges[be.idx()];
|
||||
e.vertices[0] == v0 || e.vertices[1] == v0
|
||||
});
|
||||
let has_v1 = f.boundary.iter().any(|&(be, _)| {
|
||||
let e = &self.edges[be.idx()];
|
||||
e.vertices[0] == v1 || e.vertices[1] == v1
|
||||
});
|
||||
has_v0 && has_v1
|
||||
})
|
||||
.map(|(i, _)| FillId(i as u32))
|
||||
.collect();
|
||||
// Coincident-edge cleanup: a new edge that lands exactly on an existing edge
|
||||
// between the same two vertices (e.g. drawing a shape whose edge snaps onto an
|
||||
// existing one) must not be duplicated — duplicates produce zero-area "sliver"
|
||||
// fills. Merge such duplicates before splitting/filling.
|
||||
self.dedupe_coincident_new_edges(&all_new_edges);
|
||||
|
||||
for fid in fill_ids {
|
||||
self.split_fill_by_edge(fid, eid);
|
||||
}
|
||||
}
|
||||
// Re-derive the fills touched by the new edges. Rather than incrementally splitting
|
||||
// along single cut edges (which can't handle a lasso whose path is interrupted by a
|
||||
// hole/notch in a non-convex fill), we re-trace the planar faces of the affected
|
||||
// sub-arrangement and rebuild the fills from them. This is robust for arbitrary
|
||||
// holed/concave fills (e.g. cutting across geometry left behind by a prior group).
|
||||
// Include split products so a self-crossing stroke's full arrangement is seen.
|
||||
let mut retrace_edges = all_new_edges.clone();
|
||||
retrace_edges.extend(split_products);
|
||||
self.retrace_fills_after_cut(&retrace_edges);
|
||||
|
||||
// Drop any zero-area fills (e.g. slivers left between coincident edges).
|
||||
self.remove_degenerate_fills();
|
||||
|
||||
all_new_edges
|
||||
}
|
||||
|
||||
/// When a new edge splits a fill (both endpoints on the fill's boundary),
|
||||
/// split the fill into two fills.
|
||||
pub fn split_fill_by_edge(
|
||||
&mut self,
|
||||
fill_id: FillId,
|
||||
splitting_edge: EdgeId,
|
||||
) -> Option<(FillId, FillId)> {
|
||||
let fill = &self.fills[fill_id.idx()];
|
||||
if fill.deleted {
|
||||
return None;
|
||||
/// Merge edges from the latest stroke that are geometrically coincident with an
|
||||
/// existing edge between the same two vertices (drawing a shape whose edge lands exactly
|
||||
/// on an existing edge). Keeps the existing edge, redirects fill references, and frees
|
||||
/// the duplicate — preventing zero-area "sliver" fills between the two copies.
|
||||
/// Weld degree-1 endpoints of freshly inserted edges onto a near-coincident existing
|
||||
/// vertex. A self-intersecting freehand stroke can create an intersection vertex a
|
||||
/// fraction of a pixel from a segment endpoint that should be the same point; if they
|
||||
/// don't merge, the stroke's loop is broken by a degree-1 stub and the cut is lost.
|
||||
fn weld_dangling_endpoints(&mut self, new_edges: &[EdgeId], eps: f64) {
|
||||
// Repeatedly weld the closest dangling new endpoint to its nearest neighbour.
|
||||
loop {
|
||||
let mut to_merge: Option<(VertexId, VertexId)> = None; // (keep, merge)
|
||||
'scan: for &e in new_edges {
|
||||
if self.edges[e.idx()].deleted {
|
||||
continue;
|
||||
}
|
||||
for &v in &self.edges[e.idx()].vertices {
|
||||
if self.vertices[v.idx()].deleted || self.edges_at_vertex(v).len() != 1 {
|
||||
continue;
|
||||
}
|
||||
let pv = self.vertices[v.idx()].position;
|
||||
let mut best: Option<(f64, VertexId)> = None;
|
||||
for ui in 0..self.vertices.len() {
|
||||
if ui == v.idx() || self.vertices[ui].deleted {
|
||||
continue;
|
||||
}
|
||||
let pu = self.vertices[ui].position;
|
||||
let d = (pu.x - pv.x).hypot(pu.y - pv.y);
|
||||
if d < eps && best.map_or(true, |(bd, _)| d < bd) {
|
||||
best = Some((d, VertexId(ui as u32)));
|
||||
}
|
||||
}
|
||||
if let Some((_, keep)) = best {
|
||||
to_merge = Some((keep, v));
|
||||
break 'scan;
|
||||
}
|
||||
}
|
||||
}
|
||||
match to_merge {
|
||||
Some((keep, merge)) => self.merge_vertices(keep, merge),
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
// Drop any edges that collapsed to zero length (both endpoints welded together).
|
||||
let degenerate: Vec<EdgeId> = self
|
||||
.edges
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, e)| !e.deleted && e.vertices[0] == e.vertices[1])
|
||||
.map(|(i, _)| EdgeId(i as u32))
|
||||
.collect();
|
||||
for e in degenerate {
|
||||
for fill in &mut self.fills {
|
||||
if !fill.deleted {
|
||||
fill.boundary.retain(|&(fe, _)| fe != e);
|
||||
}
|
||||
}
|
||||
self.free_edge(e);
|
||||
}
|
||||
}
|
||||
|
||||
fn dedupe_coincident_new_edges(&mut self, new_edges: &[EdgeId]) {
|
||||
for &ne in new_edges {
|
||||
if self.edges[ne.idx()].deleted {
|
||||
continue;
|
||||
}
|
||||
let va = self.edges[ne.idx()].vertices[0];
|
||||
let vb = self.edges[ne.idx()].vertices[1];
|
||||
let candidates: Vec<EdgeId> = self
|
||||
.edges_at_vertex(va)
|
||||
.into_iter()
|
||||
.filter(|&e| e != ne && !self.edges[e.idx()].deleted)
|
||||
.filter(|&e| {
|
||||
let v = self.edges[e.idx()].vertices;
|
||||
(v[0] == va && v[1] == vb) || (v[0] == vb && v[1] == va)
|
||||
})
|
||||
.collect();
|
||||
for c in candidates {
|
||||
if self.edges[c.idx()].deleted {
|
||||
continue;
|
||||
}
|
||||
if self.curves_coincident(ne, c) {
|
||||
self.redirect_edge_in_fills(ne, c);
|
||||
self.free_edge(ne);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether two edges (already known to share both endpoints) trace the same path.
|
||||
/// Coincident duplicates in practice are straight collinear segments (a shape edge
|
||||
/// snapping onto an existing edge), so we treat "both are straight lines between the
|
||||
/// same endpoints" as coincident. Comparing curve `eval(t)` directly is unreliable —
|
||||
/// split sub-edges are non-uniformly parameterised, so equal `t` ≠ equal point.
|
||||
fn curves_coincident(&self, a: EdgeId, b: EdgeId) -> bool {
|
||||
let is_straight = |c: kurbo::CubicBez| {
|
||||
let chord = c.p3 - c.p0;
|
||||
let len = chord.hypot();
|
||||
if len < 1e-9 {
|
||||
return true; // zero-length chord — degenerate, treat as coincident
|
||||
}
|
||||
// Perpendicular distance of each control point from the p0→p3 chord.
|
||||
let dist = |p: Point| ((p - c.p0).cross(chord)).abs() / len;
|
||||
dist(c.p1) < 1e-2 && dist(c.p2) < 1e-2
|
||||
};
|
||||
is_straight(self.edges[a.idx()].curve) && is_straight(self.edges[b.idx()].curve)
|
||||
}
|
||||
|
||||
/// Replace every `from` boundary reference with `to`, preserving traversal direction.
|
||||
fn redirect_edge_in_fills(&mut self, from: EdgeId, to: EdgeId) {
|
||||
let f = self.edges[from.idx()].vertices;
|
||||
let t = self.edges[to.idx()].vertices;
|
||||
let same_dir = t[0] == f[0] && t[1] == f[1];
|
||||
for fill in &mut self.fills {
|
||||
if fill.deleted {
|
||||
continue;
|
||||
}
|
||||
for entry in &mut fill.boundary {
|
||||
if entry.0 == from {
|
||||
entry.1 = match (entry.1, same_dir) {
|
||||
(Direction::Forward, true) | (Direction::Backward, false) => {
|
||||
Direction::Forward
|
||||
}
|
||||
(Direction::Backward, true) | (Direction::Forward, false) => {
|
||||
Direction::Backward
|
||||
}
|
||||
};
|
||||
entry.0 = to;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Drop fills that enclose ~zero area (degenerate slivers from coincident edges).
|
||||
fn remove_degenerate_fills(&mut self) {
|
||||
for i in 0..self.fills.len() {
|
||||
if self.fills[i].deleted {
|
||||
continue;
|
||||
}
|
||||
let mut pts: Vec<Point> = Vec::new();
|
||||
for &(eid, dir) in &self.fills[i].boundary {
|
||||
if eid.is_none() {
|
||||
continue;
|
||||
}
|
||||
let c = self.edges[eid.idx()].curve;
|
||||
pts.push(match dir {
|
||||
Direction::Forward => c.p0,
|
||||
Direction::Backward => c.p3,
|
||||
});
|
||||
}
|
||||
let area = if pts.len() < 3 {
|
||||
0.0
|
||||
} else {
|
||||
let mut a2 = 0.0;
|
||||
for k in 0..pts.len() {
|
||||
let p0 = pts[k];
|
||||
let p1 = pts[(k + 1) % pts.len()];
|
||||
a2 += p0.x * p1.y - p1.x * p0.y;
|
||||
}
|
||||
(a2 * 0.5).abs()
|
||||
};
|
||||
if area < 1e-6 {
|
||||
self.fills[i].deleted = true;
|
||||
self.free_fills.push(i as u32);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Directed end vertex of a `(edge, direction)` boundary entry.
|
||||
#[inline]
|
||||
fn entry_end_vertex(&self, eid: EdgeId, dir: Direction) -> VertexId {
|
||||
match dir {
|
||||
Direction::Forward => self.edges[eid.idx()].vertices[1],
|
||||
Direction::Backward => self.edges[eid.idx()].vertices[0],
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-derive the fills touched by a freshly inserted stroke by re-tracing the planar
|
||||
/// faces of the affected sub-arrangement. This replaces incremental "split a fill by a
|
||||
/// cut edge" logic, which can't handle a cut whose path is interrupted by a hole/notch
|
||||
/// in a non-convex fill. Each affected fill is deleted and rebuilt from the traced
|
||||
/// faces that lie inside it (inheriting its colour/rule); faces outside it — or in a
|
||||
/// hole — are dropped.
|
||||
fn retrace_fills_after_cut(&mut self, new_edges: &[EdgeId]) {
|
||||
use kurbo::Shape;
|
||||
let new_set: HashSet<EdgeId> = new_edges
|
||||
.iter()
|
||||
.filter(|&&e| !e.is_none() && !self.edges[e.idx()].deleted)
|
||||
.copied()
|
||||
.collect();
|
||||
if new_set.is_empty() {
|
||||
return;
|
||||
}
|
||||
let new_verts: HashSet<VertexId> =
|
||||
new_set.iter().flat_map(|&e| self.edges[e.idx()].vertices).collect();
|
||||
|
||||
// Affected fills: any non-deleted fill that shares a vertex with a new edge.
|
||||
let affected: Vec<FillId> = (0..self.fills.len())
|
||||
.filter(|&i| !self.fills[i].deleted)
|
||||
.filter(|&i| {
|
||||
self.fills[i].boundary.iter().any(|&(e, _)| {
|
||||
!e.is_none()
|
||||
&& self.edges[e.idx()].vertices.iter().any(|v| new_verts.contains(v))
|
||||
})
|
||||
})
|
||||
.map(|i| FillId(i as u32))
|
||||
.collect();
|
||||
if affected.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let split_v0 = self.edges[splitting_edge.idx()].vertices[0];
|
||||
let split_v1 = self.edges[splitting_edge.idx()].vertices[1];
|
||||
// Snapshot each affected fill's path + attributes before we delete them.
|
||||
let originals: Vec<(kurbo::BezPath, Option<ShapeColor>, FillRule)> = affected
|
||||
.iter()
|
||||
.map(|&f| {
|
||||
(
|
||||
self.fill_to_bezpath(f),
|
||||
self.fills[f.idx()].color,
|
||||
self.fills[f.idx()].fill_rule,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
|
||||
// Find the positions in the boundary where the splitting edge's
|
||||
// endpoint vertices appear as the "arrival" vertex of a directed edge.
|
||||
let boundary = fill.boundary.clone();
|
||||
// Edge set for the local arrangement: every affected fill's boundary edges plus the
|
||||
// ENTIRE inserted stroke. We include the whole stroke (not just the segments whose
|
||||
// midpoint is inside a fill) because a wiggly freehand lasso has segments that dip
|
||||
// just outside the fill; excluding them would break the inside-arc chain into
|
||||
// dangling fragments that then get pruned away, losing the cut entirely. The stroke
|
||||
// forms closed loops, so it contributes no dangling edges; faces that end up outside
|
||||
// every affected fill are discarded by the classification below.
|
||||
let mut edge_set: HashSet<EdgeId> = HashSet::new();
|
||||
for &f in &affected {
|
||||
for &(e, _) in &self.fills[f.idx()].boundary {
|
||||
if !e.is_none() && !self.edges[e.idx()].deleted {
|
||||
edge_set.insert(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
edge_set.extend(new_set.iter().copied());
|
||||
|
||||
// Helper: get the "end" vertex of a directed boundary edge
|
||||
let end_vertex = |eid: EdgeId, dir: Direction| -> VertexId {
|
||||
match dir {
|
||||
Direction::Forward => self.edges[eid.idx()].vertices[1],
|
||||
Direction::Backward => self.edges[eid.idx()].vertices[0],
|
||||
// Expand to the induced subgraph on the covered vertices. A self-intersecting
|
||||
// freehand stroke splits its own edges via `split_edge`, whose sub-edges aren't in
|
||||
// `new_edges`; without them the local arrangement has gaps and the stroke's loop
|
||||
// looks like dangling fragments. Adding every edge whose endpoints are both already
|
||||
// covered closes those gaps (the sub-edges connect already-covered stroke vertices).
|
||||
loop {
|
||||
let verts: HashSet<VertexId> = edge_set
|
||||
.iter()
|
||||
.flat_map(|&e| self.edges[e.idx()].vertices)
|
||||
.collect();
|
||||
let added: Vec<EdgeId> = (0..self.edges.len())
|
||||
.map(|i| EdgeId(i as u32))
|
||||
.filter(|&e| !self.edges[e.idx()].deleted && !edge_set.contains(&e))
|
||||
.filter(|&e| {
|
||||
let [a, b] = self.edges[e.idx()].vertices;
|
||||
verts.contains(&a) && verts.contains(&b)
|
||||
})
|
||||
.collect();
|
||||
if added.is_empty() {
|
||||
break;
|
||||
}
|
||||
edge_set.extend(added);
|
||||
}
|
||||
|
||||
// Prune dangling edges (a vertex with degree < 2 in the local arrangement). They
|
||||
// form spikes, never real face boundaries — a freehand lasso that wiggles or nearly
|
||||
// self-touches leaves such stubs, and tracing them produces a face that runs out and
|
||||
// back along the same edge (a degenerate self-touching boundary). Iterate, since
|
||||
// removing one stub can expose another.
|
||||
loop {
|
||||
let mut degree: HashMap<VertexId, usize> = HashMap::new();
|
||||
for &e in &edge_set {
|
||||
for &v in &self.edges[e.idx()].vertices {
|
||||
*degree.entry(v).or_default() += 1;
|
||||
}
|
||||
}
|
||||
let dangling: Vec<EdgeId> = edge_set
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|&e| {
|
||||
let [a, b] = self.edges[e.idx()].vertices;
|
||||
a == b || degree[&a] < 2 || degree[&b] < 2
|
||||
})
|
||||
.collect();
|
||||
if dangling.is_empty() {
|
||||
break;
|
||||
}
|
||||
for e in dangling {
|
||||
edge_set.remove(&e);
|
||||
}
|
||||
}
|
||||
|
||||
let faces = self.trace_faces(&edge_set);
|
||||
|
||||
// Replace the affected fills with the re-traced bounded faces that fall inside them.
|
||||
for &f in &affected {
|
||||
self.fills[f.idx()].deleted = true;
|
||||
self.free_fills.push(f.0);
|
||||
}
|
||||
for mut face in faces {
|
||||
// Collapse degenerate "spikes" — a sequence that runs out to a point and back
|
||||
// (e.g. across near-coincident duplicate tiny edges from a dense freehand path).
|
||||
self.collapse_boundary_spikes(&mut face);
|
||||
if face.len() < 3 {
|
||||
continue;
|
||||
}
|
||||
// Only bounded (counter-clockwise, positive-area) faces are real regions; the
|
||||
// outer face is clockwise/negative.
|
||||
if self.face_signed_area(&face) <= 1e-6 {
|
||||
continue;
|
||||
}
|
||||
let sample = self.boundary_interior_point(&face);
|
||||
if let Some((_, color, rule)) =
|
||||
originals.iter().find(|(p, _, _)| p.winding(sample) != 0)
|
||||
{
|
||||
self.alloc_fill(face, *color, *rule);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove out-and-back "spikes" from a face boundary: consecutive entries where the
|
||||
/// second exactly reverses the first (the boundary returns to where it started, e.g.
|
||||
/// bouncing across near-coincident duplicate edges). These are zero-area and would make
|
||||
/// `boundary_to_bezpath` render a stray hair; collapsing them yields a simple loop.
|
||||
fn collapse_boundary_spikes(&self, face: &mut Vec<(EdgeId, Direction)>) {
|
||||
// The four control points of an entry's curve in its traversal order.
|
||||
let traversed = |entry: &(EdgeId, Direction)| -> [Point; 4] {
|
||||
let c = self.edges[entry.0.idx()].curve;
|
||||
match entry.1 {
|
||||
Direction::Forward => [c.p0, c.p1, c.p2, c.p3],
|
||||
Direction::Backward => [c.p3, c.p2, c.p1, c.p0],
|
||||
}
|
||||
};
|
||||
|
||||
// Find positions where boundary edges arrive at split_v0 and split_v1
|
||||
let mut pos_v0: Option<usize> = None;
|
||||
let mut pos_v1: Option<usize> = None;
|
||||
|
||||
for (i, &(eid, dir)) in boundary.iter().enumerate() {
|
||||
let ev = end_vertex(eid, dir);
|
||||
if ev == split_v0 && pos_v0.is_none() {
|
||||
pos_v0 = Some(i);
|
||||
}
|
||||
if ev == split_v1 && pos_v1.is_none() {
|
||||
pos_v1 = Some(i);
|
||||
}
|
||||
}
|
||||
|
||||
let pos_v0 = pos_v0?;
|
||||
let pos_v1 = pos_v1?;
|
||||
|
||||
// Ensure we have two distinct positions
|
||||
if pos_v0 == pos_v1 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Walk boundary in two halves:
|
||||
// Half A: from pos_v0+1 to pos_v1 (inclusive), then splitting_edge Forward
|
||||
// Half B: from pos_v1+1 to pos_v0 (wrapping), then splitting_edge Backward
|
||||
let n = boundary.len();
|
||||
let color = fill.color;
|
||||
let fill_rule = fill.fill_rule;
|
||||
|
||||
let mut half_a = Vec::new();
|
||||
let mut idx = (pos_v0 + 1) % n;
|
||||
const EPS: f64 = 0.5;
|
||||
// Entries i and j cancel only when j is the *exact reverse* of i — every control point of
|
||||
// j matches the mirror of i. Testing endpoints alone would also collapse a genuine
|
||||
// lens/sliver (two distinct edges that merely share near-coincident endpoints), silently
|
||||
// deleting real boundary geometry and dropping the fill.
|
||||
let reverses = |a: &(EdgeId, Direction), b: &(EdgeId, Direction)| -> bool {
|
||||
let (ca, cb) = (traversed(a), traversed(b));
|
||||
(0..4).all(|k| {
|
||||
let (p, q) = (ca[k], cb[3 - k]);
|
||||
(p.x - q.x).hypot(p.y - q.y) < EPS
|
||||
})
|
||||
};
|
||||
loop {
|
||||
half_a.push(boundary[idx]);
|
||||
if idx == pos_v1 {
|
||||
let n = face.len();
|
||||
if n < 2 {
|
||||
break;
|
||||
}
|
||||
idx = (idx + 1) % n;
|
||||
}
|
||||
half_a.push((splitting_edge, Direction::Forward));
|
||||
|
||||
let mut half_b = Vec::new();
|
||||
idx = (pos_v1 + 1) % n;
|
||||
loop {
|
||||
half_b.push(boundary[idx]);
|
||||
if idx == pos_v0 {
|
||||
let mut collapsed = false;
|
||||
for i in 0..n {
|
||||
let j = (i + 1) % n;
|
||||
if reverses(&face[i], &face[j]) {
|
||||
let (hi, lo) = if i > j { (i, j) } else { (j, i) };
|
||||
face.remove(hi);
|
||||
face.remove(lo);
|
||||
collapsed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !collapsed {
|
||||
break;
|
||||
}
|
||||
idx = (idx + 1) % n;
|
||||
}
|
||||
half_b.push((splitting_edge, Direction::Backward));
|
||||
}
|
||||
|
||||
// Delete the original fill
|
||||
self.fills[fill_id.idx()].deleted = true;
|
||||
self.free_fills.push(fill_id.0);
|
||||
/// Trace all faces of the planar arrangement formed by `edge_set`, using the standard
|
||||
/// angular next-edge rule (turn to the clockwise-adjacent dart of the twin at each
|
||||
/// vertex). Returns each face as an ordered `(edge, direction)` loop. Bounded faces
|
||||
/// come out counter-clockwise (positive signed area); the outer face clockwise.
|
||||
fn trace_faces(&self, edge_set: &HashSet<EdgeId>) -> Vec<Vec<(EdgeId, Direction)>> {
|
||||
// Outgoing darts per vertex, sorted by outgoing angle (CCW).
|
||||
let mut out: HashMap<VertexId, Vec<(f64, (EdgeId, Direction))>> = HashMap::new();
|
||||
for &e in edge_set {
|
||||
if self.edges[e.idx()].deleted {
|
||||
continue;
|
||||
}
|
||||
let [a, b] = self.edges[e.idx()].vertices;
|
||||
out.entry(a)
|
||||
.or_default()
|
||||
.push((self.dart_angle(e, Direction::Forward), (e, Direction::Forward)));
|
||||
out.entry(b)
|
||||
.or_default()
|
||||
.push((self.dart_angle(e, Direction::Backward), (e, Direction::Backward)));
|
||||
}
|
||||
for darts in out.values_mut() {
|
||||
darts.sort_by(|x, y| x.0.partial_cmp(&y.0).unwrap_or(std::cmp::Ordering::Equal));
|
||||
}
|
||||
|
||||
// Create two new fills
|
||||
let fill_a = self.alloc_fill(half_a, color, fill_rule);
|
||||
let fill_b = self.alloc_fill(half_b, color, fill_rule);
|
||||
let mut visited: HashSet<(EdgeId, Direction)> = HashSet::new();
|
||||
let mut faces: Vec<Vec<(EdgeId, Direction)>> = Vec::new();
|
||||
let cap = edge_set.len() * 2 + 4;
|
||||
for &e in edge_set {
|
||||
if self.edges[e.idx()].deleted {
|
||||
continue;
|
||||
}
|
||||
for dir in [Direction::Forward, Direction::Backward] {
|
||||
let start = (e, dir);
|
||||
if visited.contains(&start) {
|
||||
continue;
|
||||
}
|
||||
let mut face: Vec<(EdgeId, Direction)> = Vec::new();
|
||||
let mut d = start;
|
||||
loop {
|
||||
visited.insert(d);
|
||||
face.push(d);
|
||||
// Next dart: at the end vertex, the dart clockwise-adjacent to the twin.
|
||||
let end_v = self.entry_end_vertex(d.0, d.1);
|
||||
let twin = (
|
||||
d.0,
|
||||
match d.1 {
|
||||
Direction::Forward => Direction::Backward,
|
||||
Direction::Backward => Direction::Forward,
|
||||
},
|
||||
);
|
||||
let darts = match out.get(&end_v) {
|
||||
Some(d) => d,
|
||||
None => break,
|
||||
};
|
||||
let Some(idx) = darts.iter().position(|&(_, dd)| dd == twin) else {
|
||||
break;
|
||||
};
|
||||
let next = darts[(idx + darts.len() - 1) % darts.len()].1;
|
||||
if next == start {
|
||||
break;
|
||||
}
|
||||
if visited.contains(&next) || face.len() > cap {
|
||||
break;
|
||||
}
|
||||
d = next;
|
||||
}
|
||||
if face.len() >= 3 {
|
||||
faces.push(face);
|
||||
}
|
||||
}
|
||||
}
|
||||
faces
|
||||
}
|
||||
|
||||
Some((fill_a, fill_b))
|
||||
/// Outgoing direction angle of a dart at its start vertex.
|
||||
fn dart_angle(&self, e: EdgeId, dir: Direction) -> f64 {
|
||||
let c = self.edges[e.idx()].curve;
|
||||
let (base, cands) = match dir {
|
||||
Direction::Forward => (c.p0, [c.p1, c.p2, c.p3]),
|
||||
Direction::Backward => (c.p3, [c.p2, c.p1, c.p0]),
|
||||
};
|
||||
for cand in cands {
|
||||
let d = cand - base;
|
||||
if d.hypot() > 1e-9 {
|
||||
return d.y.atan2(d.x);
|
||||
}
|
||||
}
|
||||
0.0
|
||||
}
|
||||
|
||||
/// Signed area of a face given as an ordered `(edge, direction)` loop (CCW positive).
|
||||
fn face_signed_area(&self, face: &[(EdgeId, Direction)]) -> f64 {
|
||||
let pts: Vec<Point> = face
|
||||
.iter()
|
||||
.map(|&(e, dir)| {
|
||||
let c = self.edges[e.idx()].curve;
|
||||
match dir {
|
||||
Direction::Forward => c.p0,
|
||||
Direction::Backward => c.p3,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
if pts.len() < 3 {
|
||||
return 0.0;
|
||||
}
|
||||
let mut a2 = 0.0;
|
||||
for i in 0..pts.len() {
|
||||
let p0 = pts[i];
|
||||
let p1 = pts[(i + 1) % pts.len()];
|
||||
a2 += p0.x * p1.y - p1.x * p0.y;
|
||||
}
|
||||
a2 * 0.5
|
||||
}
|
||||
|
||||
/// Merge two fills that share a boundary edge (e.g., after edge deletion).
|
||||
@@ -1101,21 +1667,6 @@ impl VectorGraph {
|
||||
// Boundary tracing internals
|
||||
// -------------------------------------------------------------------
|
||||
|
||||
/// Find the nearest non-deleted edge to a point. Returns (EdgeId, t, distance).
|
||||
fn nearest_edge_to_point(&self, point: Point) -> Option<(EdgeId, f64, f64)> {
|
||||
let mut best: Option<(EdgeId, f64, f64)> = None;
|
||||
for (i, e) in self.edges.iter().enumerate() {
|
||||
if e.deleted {
|
||||
continue;
|
||||
}
|
||||
let eid = EdgeId(i as u32);
|
||||
let (t, dist) = nearest_point_on_cubic(&e.curve, point);
|
||||
if best.is_none() || dist < best.unwrap().2 {
|
||||
best = Some((eid, t, dist));
|
||||
}
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Build a BezPath from a boundary (without storing it as a fill).
|
||||
/// Handles `EdgeId::NONE` separators to start new contours (holes).
|
||||
@@ -1458,11 +2009,14 @@ impl VectorGraph {
|
||||
|
||||
// ── Region selection: extract / merge subgraph ──────────────────────
|
||||
|
||||
/// Extract a subgraph containing `inside_edges` and `inside_fills`.
|
||||
/// Extract a subgraph containing `inside_edges` and `inside_fills` (typically a
|
||||
/// geometry selection — `select_fill` already includes each fill's boundary edges).
|
||||
///
|
||||
/// Boundary edges (`boundary_edge_ids`) are **duplicated** — they exist in
|
||||
/// both the returned graph and `self`, so both sides have closed fill
|
||||
/// boundaries when the selection is moved.
|
||||
/// **Boundary edges** are *duplicated* (copied into the returned graph but kept in
|
||||
/// `self`, so remaining shapes keep closed boundaries). They are `explicit_boundary`
|
||||
/// (a cut the caller knows about, e.g. a lasso region — pass an empty set if none)
|
||||
/// UNION any inside edge still shared with a non-extracted fill (derived here, so a
|
||||
/// plain geometry selection needs no boundary analysis from the caller).
|
||||
///
|
||||
/// Returns `(new_graph, vertex_map, edge_map)` where the maps go from
|
||||
/// old (self) IDs to new (returned graph) IDs.
|
||||
@@ -1470,17 +2024,58 @@ impl VectorGraph {
|
||||
&mut self,
|
||||
inside_edges: &HashSet<EdgeId>,
|
||||
inside_fills: &HashSet<FillId>,
|
||||
boundary_edge_ids: &HashSet<EdgeId>,
|
||||
explicit_boundary: &HashSet<EdgeId>,
|
||||
) -> (VectorGraph, HashMap<VertexId, VertexId>, HashMap<EdgeId, EdgeId>) {
|
||||
let mut new_graph = VectorGraph::new();
|
||||
let mut vtx_map: HashMap<VertexId, VertexId> = HashMap::new();
|
||||
let mut edge_map: HashMap<EdgeId, EdgeId> = HashMap::new();
|
||||
|
||||
// Collect all edge IDs we need to copy into the new graph
|
||||
let edges_to_copy: HashSet<EdgeId> = inside_edges
|
||||
.union(boundary_edge_ids)
|
||||
.copied()
|
||||
.collect();
|
||||
// Augment the inside set with every boundary edge of an extracted fill. A
|
||||
// selection might not enumerate them all (e.g. lasso/region selection populates
|
||||
// edges differently than `select_fill`); without this an extracted fill would be
|
||||
// copied with `EdgeId::NONE` standing in for a missing edge, and that NONE later
|
||||
// panics any code that indexes `fill.boundary` (e.g. `insert_stroke`).
|
||||
let inside_edges: HashSet<EdgeId> = {
|
||||
let mut s = inside_edges.clone();
|
||||
for &fid in inside_fills {
|
||||
if fid.is_none() {
|
||||
continue;
|
||||
}
|
||||
if let Some(fill) = self.fills.get(fid.idx()) {
|
||||
if fill.deleted {
|
||||
continue;
|
||||
}
|
||||
for &(eid, _) in &fill.boundary {
|
||||
if !eid.is_none() {
|
||||
s.insert(eid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
s
|
||||
};
|
||||
let inside_edges = &inside_edges;
|
||||
|
||||
// Boundary = `explicit_boundary` (e.g. a region/lasso cut the caller knows about)
|
||||
// UNION any inside edge still referenced by a fill we're NOT extracting (a shared
|
||||
// DCEL edge — must be duplicated, not moved, or that fill dangles). Deriving the
|
||||
// latter here means a plain geometry selection needs no boundary analysis.
|
||||
let mut boundary_edge_ids: HashSet<EdgeId> = explicit_boundary.clone();
|
||||
for (i, fill) in self.fills.iter().enumerate() {
|
||||
if fill.deleted || inside_fills.contains(&FillId(i as u32)) {
|
||||
continue;
|
||||
}
|
||||
for &(eid, _) in &fill.boundary {
|
||||
if !eid.is_none() && inside_edges.contains(&eid) {
|
||||
boundary_edge_ids.insert(eid);
|
||||
}
|
||||
}
|
||||
}
|
||||
let boundary_edge_ids = &boundary_edge_ids;
|
||||
|
||||
// Copy all inside edges + any boundary edges (the explicit ones may not be in
|
||||
// inside_edges); boundary edges are kept in self below.
|
||||
let edges_to_copy: HashSet<EdgeId> = inside_edges.union(boundary_edge_ids).copied().collect();
|
||||
|
||||
// Collect all vertices referenced by edges we're copying
|
||||
let mut referenced_vids: HashSet<VertexId> = HashSet::new();
|
||||
@@ -1493,16 +2088,21 @@ impl VectorGraph {
|
||||
}
|
||||
}
|
||||
|
||||
// Determine which vertices are interior (exclusively owned by the
|
||||
// extracted subgraph) vs boundary (shared with remaining geometry).
|
||||
// A vertex is interior if ALL of its incident edges are either in
|
||||
// inside_edges or boundary_edge_ids.
|
||||
// Determine which vertices are safe to free from `self`. A vertex can only be
|
||||
// freed if EVERY one of its incident edges is actually being removed from `self`,
|
||||
// i.e. is an inside edge that is NOT a boundary edge. Boundary edges are kept
|
||||
// (duplicated) in `self`, so a vertex touching one is still referenced and must
|
||||
// remain — otherwise it becomes a freed-but-referenced vertex whose slot a later
|
||||
// `alloc_vertex` reuses, corrupting the remaining fill.
|
||||
let mut interior_vertices: HashSet<VertexId> = HashSet::new();
|
||||
let mut boundary_vertices: HashSet<VertexId> = HashSet::new();
|
||||
for &vid in &referenced_vids {
|
||||
let incident = self.edges_at_vertex(vid);
|
||||
let all_inside = incident.iter().all(|&eid| edges_to_copy.contains(&eid));
|
||||
if all_inside {
|
||||
let all_removed = !incident.is_empty()
|
||||
&& incident
|
||||
.iter()
|
||||
.all(|&eid| inside_edges.contains(&eid) && !boundary_edge_ids.contains(&eid));
|
||||
if all_removed {
|
||||
interior_vertices.insert(vid);
|
||||
} else {
|
||||
boundary_vertices.insert(vid);
|
||||
@@ -1566,9 +2166,10 @@ impl VectorGraph {
|
||||
new_graph.fills[new_fid.idx()].image_fill = fill.image_fill;
|
||||
}
|
||||
|
||||
// Remove inside_edges from self (but NOT boundary edges — those are duplicated)
|
||||
// Remove inside_edges from self, EXCEPT boundary edges (those are duplicated —
|
||||
// a non-extracted fill still needs them).
|
||||
for &eid in inside_edges {
|
||||
if !eid.is_none() && !self.edges[eid.idx()].deleted {
|
||||
if !eid.is_none() && !boundary_edge_ids.contains(&eid) && !self.edges[eid.idx()].deleted {
|
||||
self.free_edge(eid);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,3 +10,7 @@ mod editing;
|
||||
mod gap_close;
|
||||
#[cfg(test)]
|
||||
mod region;
|
||||
#[cfg(test)]
|
||||
mod region_cut_select;
|
||||
#[cfg(test)]
|
||||
mod tween;
|
||||
|
||||
@@ -0,0 +1,660 @@
|
||||
//! Reproduces the unified region-select behaviour at the graph level: cutting a shape
|
||||
//! along a lasso outline (`insert_stroke`) and classifying which resulting fills/edges
|
||||
//! fall inside the lasso — the same logic the editor's `execute_region_select` runs.
|
||||
//!
|
||||
//! The shape is built exactly as the editor builds a rectangle: `insert_stroke` of a
|
||||
//! closed rect loop, then `paint_bucket` to create the fill (NOT a hand-rolled
|
||||
//! `alloc_fill`), because the bug is in how that traced fill's boundary survives being
|
||||
//! split by the lasso cut.
|
||||
|
||||
use super::super::*;
|
||||
use kurbo::{BezPath, CubicBez, ParamCurve, Point, Shape};
|
||||
|
||||
/// Straight-line cubic from a to b.
|
||||
fn line(a: Point, b: Point) -> CubicBez {
|
||||
CubicBez::new(
|
||||
a,
|
||||
Point::new(a.x + (b.x - a.x) / 3.0, a.y + (b.y - a.y) / 3.0),
|
||||
Point::new(a.x + 2.0 * (b.x - a.x) / 3.0, a.y + 2.0 * (b.y - a.y) / 3.0),
|
||||
b,
|
||||
)
|
||||
}
|
||||
|
||||
fn closed_rect_path(min_x: f64, min_y: f64, max_x: f64, max_y: f64) -> BezPath {
|
||||
let mut p = BezPath::new();
|
||||
p.move_to((min_x, min_y));
|
||||
p.line_to((max_x, min_y));
|
||||
p.line_to((max_x, max_y));
|
||||
p.line_to((min_x, max_y));
|
||||
p.close_path();
|
||||
p
|
||||
}
|
||||
|
||||
/// Draw a filled rectangle into an existing graph the way the editor's rectangle tool does.
|
||||
fn draw_filled_rect(g: &mut VectorGraph, min_x: f64, min_y: f64, max_x: f64, max_y: f64) {
|
||||
let style = StrokeStyle { width: 1.0, ..Default::default() };
|
||||
let color = ShapeColor::rgb(0, 0, 0);
|
||||
for segs in bezpath_to_cubic_segments(&closed_rect_path(min_x, min_y, max_x, max_y)) {
|
||||
g.insert_stroke(&segs, Some(style.clone()), Some(color), 0.5);
|
||||
}
|
||||
let centroid = Point::new((min_x + max_x) / 2.0, (min_y + max_y) / 2.0);
|
||||
g.paint_bucket(centroid, ShapeColor::rgb(255, 0, 0), FillRule::NonZero, 0.0)
|
||||
.expect("paint_bucket should create a fill");
|
||||
}
|
||||
|
||||
/// Build a filled rectangle the way the editor's rectangle tool does.
|
||||
fn editor_filled_rect(min_x: f64, min_y: f64, max_x: f64, max_y: f64) -> VectorGraph {
|
||||
let mut g = VectorGraph::new();
|
||||
draw_filled_rect(&mut g, min_x, min_y, max_x, max_y);
|
||||
g
|
||||
}
|
||||
|
||||
/// Closed rectangular lasso: cubic segments (for insert_stroke) + BezPath (for winding).
|
||||
fn rect_lasso(min_x: f64, min_y: f64, max_x: f64, max_y: f64) -> (Vec<CubicBez>, BezPath) {
|
||||
let p = [
|
||||
Point::new(min_x, min_y),
|
||||
Point::new(max_x, min_y),
|
||||
Point::new(max_x, max_y),
|
||||
Point::new(min_x, max_y),
|
||||
];
|
||||
let segs = vec![line(p[0], p[1]), line(p[1], p[2]), line(p[2], p[3]), line(p[3], p[0])];
|
||||
let mut path = BezPath::new();
|
||||
path.move_to(p[0]);
|
||||
for pt in &p[1..] {
|
||||
path.line_to(*pt);
|
||||
}
|
||||
path.close_path();
|
||||
(segs, path)
|
||||
}
|
||||
|
||||
// Classify-against-lasso uses the same guaranteed-interior probe point the editor uses.
|
||||
fn fill_centroid(g: &VectorGraph, fid: FillId) -> Point {
|
||||
g.fill_interior_point(fid)
|
||||
}
|
||||
|
||||
/// Directed start/end points of a boundary entry.
|
||||
fn dir_start(g: &VectorGraph, eid: EdgeId, dir: Direction) -> Point {
|
||||
let c = g.edge(eid).curve;
|
||||
match dir {
|
||||
Direction::Forward => c.p0,
|
||||
Direction::Backward => c.p3,
|
||||
}
|
||||
}
|
||||
fn dir_end(g: &VectorGraph, eid: EdgeId, dir: Direction) -> Point {
|
||||
let c = g.edge(eid).curve;
|
||||
match dir {
|
||||
Direction::Forward => c.p3,
|
||||
Direction::Backward => c.p0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Describe a fill's boundary as an ordered list of (start → end) segments for diagnostics.
|
||||
fn describe_boundary(g: &VectorGraph, fid: FillId) -> Vec<(EdgeId, Point, Point)> {
|
||||
g.fill(fid)
|
||||
.boundary
|
||||
.iter()
|
||||
.filter(|(e, _)| !e.is_none())
|
||||
.map(|&(e, d)| (e, dir_start(g, e, d), dir_end(g, e, d)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Assert no fill boundary uses the same edge twice (the signature of a degenerate
|
||||
/// "spike" where the trace runs out and back along a dangling edge).
|
||||
fn assert_no_spikes(g: &VectorGraph) {
|
||||
for (fi, f) in g.fills.iter().enumerate() {
|
||||
if f.deleted { continue; }
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for &(e, _) in &f.boundary {
|
||||
if e.is_none() { continue; }
|
||||
assert!(seen.insert(e.0), "fill {fi} uses edge {} twice (spike)", e.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Assert every non-deleted fill's boundary is a connected closed loop.
|
||||
fn assert_all_fills_connected(g: &VectorGraph) {
|
||||
for (i, f) in g.fills.iter().enumerate() {
|
||||
if f.deleted {
|
||||
continue;
|
||||
}
|
||||
let fid = FillId(i as u32);
|
||||
let b = describe_boundary(g, fid);
|
||||
if b.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let n = b.len();
|
||||
for k in 0..n {
|
||||
let (_, _, end) = b[k];
|
||||
let (_, next_start, _) = b[(k + 1) % n];
|
||||
// Tolerance well below any real gap (pixels) but above accumulated float drift.
|
||||
assert!(
|
||||
(end.x - next_start.x).abs() < 1e-2 && (end.y - next_start.y).abs() < 1e-2,
|
||||
"fill {i} boundary disconnected between edge {k} (ends {end:?}) and \
|
||||
edge {} (starts {next_start:?}); boundary = {b:#?}",
|
||||
(k + 1) % n
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_vertical_cut_produces_two_connected_fills() {
|
||||
// Rectangle (0,0)-(200,100), one vertical cut at x=100.
|
||||
let mut g = editor_filled_rect(0.0, 0.0, 200.0, 100.0);
|
||||
let cut = vec![line(Point::new(100.0, -10.0), Point::new(100.0, 110.0))];
|
||||
g.insert_stroke(&cut, None, None, 1.0);
|
||||
|
||||
let live = g.fills.iter().filter(|f| !f.deleted).count();
|
||||
assert_eq!(live, 2, "one cut should split the rect into 2 fills, got {live}");
|
||||
assert_all_fills_connected(&g);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lasso_over_second_of_two_rects_splits_that_rect() {
|
||||
// Two separate rectangles; lasso a vertical strip over the SECOND one.
|
||||
let mut g = editor_filled_rect(0.0, 0.0, 200.0, 100.0);
|
||||
draw_filled_rect(&mut g, 0.0, 150.0, 200.0, 250.0);
|
||||
assert_eq!(g.fills.iter().filter(|f| !f.deleted).count(), 2, "two rects → two fills");
|
||||
|
||||
let (segs, lasso_path) = rect_lasso(50.0, 120.0, 150.0, 300.0); // crosses rect B only
|
||||
g.insert_stroke(&segs, None, None, 1.0);
|
||||
g.gc_invisible_edges();
|
||||
|
||||
// Rect B should now be split into 3 fills (left/middle/right strips); rect A is untouched.
|
||||
// So 1 (rect A) + 3 (rect B pieces) = 4 fills total.
|
||||
let live = g.fills.iter().filter(|f| !f.deleted).count();
|
||||
let inside_fills: Vec<FillId> = g
|
||||
.fills
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, f)| !f.deleted)
|
||||
.map(|(i, _)| FillId(i as u32))
|
||||
.filter(|&fid| lasso_path.winding(fill_centroid(&g, fid)) != 0)
|
||||
.collect();
|
||||
|
||||
let dump = || {
|
||||
g.fills
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, f)| !f.deleted)
|
||||
.map(|(i, _)| (i, fill_centroid(&g, FillId(i as u32))))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
assert_eq!(live, 4, "rect B should split into 3 (total 4 fills); got {live}: {:#?}", dump());
|
||||
assert_eq!(
|
||||
inside_fills.len(),
|
||||
1,
|
||||
"exactly the center strip of rect B should be inside; got {:#?}",
|
||||
dump()
|
||||
);
|
||||
assert_all_fills_connected(&g);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lasso_strip_through_side_by_side_second_rect() {
|
||||
// Two rectangles side by side; lasso a vertical strip through the SECOND (right) one.
|
||||
let mut g = editor_filled_rect(0.0, 0.0, 100.0, 100.0);
|
||||
draw_filled_rect(&mut g, 150.0, 0.0, 250.0, 100.0);
|
||||
|
||||
let (segs, lasso_path) = rect_lasso(180.0, -50.0, 220.0, 150.0);
|
||||
g.insert_stroke(&segs, None, None, 1.0);
|
||||
g.gc_invisible_edges();
|
||||
assert_all_fills_connected(&g);
|
||||
|
||||
let inside: Vec<FillId> = g.fills.iter().enumerate()
|
||||
.filter(|(_, f)| !f.deleted).map(|(i, _)| FillId(i as u32))
|
||||
.filter(|&fid| lasso_path.winding(fill_centroid(&g, fid)) != 0).collect();
|
||||
let dump: Vec<_> = g.fills.iter().enumerate().filter(|(_, f)| !f.deleted)
|
||||
.map(|(i, _)| (i, fill_centroid(&g, FillId(i as u32)), describe_boundary(&g, FillId(i as u32)).len())).collect();
|
||||
assert_eq!(inside.len(), 1, "one strip of the right rect should be inside; got {dump:#?}");
|
||||
}
|
||||
|
||||
/// No live fill may reference a freed edge or vertex (whose slot a later alloc reuses).
|
||||
fn assert_no_freed_but_referenced(g: &VectorGraph) {
|
||||
let freed_v: std::collections::HashSet<u32> = g.free_vertices.iter().copied().collect();
|
||||
let freed_e: std::collections::HashSet<u32> = g.free_edges.iter().copied().collect();
|
||||
for (fi, f) in g.fills.iter().enumerate() {
|
||||
if f.deleted { continue; }
|
||||
for &(e, _) in &f.boundary {
|
||||
if e.is_none() { continue; }
|
||||
assert!(!freed_e.contains(&e.0), "live fill {fi} references freed edge {}", e.0);
|
||||
for &v in &g.edge(e).vertices {
|
||||
assert!(!freed_v.contains(&v.0), "live fill {fi} references freed vertex {}", v.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_after_cut_keeps_remaining_fill_intact() {
|
||||
// Cut a rectangle's corner with a lasso, then extract (Group) the clipped corner. The
|
||||
// extraction must not free vertices/edges still referenced by the L-shaped remainder —
|
||||
// previously it freed the shared cut vertices, and a later `alloc_vertex` reused those
|
||||
// slots and corrupted the remainder (the "second lasso deletes all faces" bug).
|
||||
let mut g = editor_filled_rect(0.0, 0.0, 200.0, 100.0);
|
||||
let (segs, lasso) = rect_lasso(100.0, -50.0, 300.0, 50.0); // clips the top-right corner
|
||||
g.insert_stroke(&segs, None, None, 1.0);
|
||||
g.gc_invisible_edges();
|
||||
|
||||
// Pick the fill inside the lasso (the clipped corner) and extract it.
|
||||
let inside: Vec<FillId> = g.fills.iter().enumerate()
|
||||
.filter(|(_, f)| !f.deleted).map(|(i, _)| FillId(i as u32))
|
||||
.filter(|&fid| lasso.winding(g.fill_interior_point(fid)) != 0).collect();
|
||||
assert_eq!(inside.len(), 1, "one corner fill should be inside the lasso");
|
||||
let inside_fills: HashSet<FillId> = inside.iter().copied().collect();
|
||||
let inside_edges: HashSet<EdgeId> = g.fill(inside[0]).boundary.iter()
|
||||
.filter_map(|&(e, _)| (!e.is_none()).then_some(e)).collect();
|
||||
|
||||
let _ = g.extract_subgraph(&inside_edges, &inside_fills, &HashSet::new());
|
||||
|
||||
assert_no_freed_but_referenced(&g);
|
||||
assert_all_fills_connected(&g);
|
||||
|
||||
// Simulate the next lasso allocating vertices, then re-validate: a corrupted (freed but
|
||||
// referenced) vertex would now be at a bogus position.
|
||||
let (segs2, _) = rect_lasso(20.0, 20.0, 60.0, 80.0);
|
||||
g.insert_stroke(&segs2, None, None, 1.0);
|
||||
g.gc_invisible_edges();
|
||||
assert_all_fills_connected(&g);
|
||||
}
|
||||
|
||||
/// Captured region-select cases (`LIGHTNINGBEAM_DUMP_REGION=1`), embedded so the regression
|
||||
/// survives `/tmp` being cleared. Each is `{ "graph": <VectorGraph>, "segments": [[[x,y]*4]*] }`.
|
||||
/// They span: two separate rects, side-by-side, overlapping, a notched post-group fill, and
|
||||
/// dense self-intersecting freehand lassos (dump 3 is the boundary-spike repro).
|
||||
const REGION_DUMPS: &[&str] = &[
|
||||
include_str!("region_dumps/dump0.json"),
|
||||
include_str!("region_dumps/dump1.json"),
|
||||
include_str!("region_dumps/dump2.json"),
|
||||
include_str!("region_dumps/dump3.json"),
|
||||
include_str!("region_dumps/dump4.json"),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn dumped_region_selects_are_valid() {
|
||||
// Replays each captured region-select cut and asserts it yields only valid, non-corrupt
|
||||
// geometry (no freed-but-referenced refs, no spikes, every fill a connected loop).
|
||||
for json in REGION_DUMPS {
|
||||
let v: serde_json::Value = serde_json::from_str(json).unwrap();
|
||||
let mut g: VectorGraph = serde_json::from_value(v["graph"].clone()).unwrap();
|
||||
let segs: Vec<CubicBez> = v["segments"].as_array().unwrap().iter().map(|s| {
|
||||
let p = |i: usize| { let a = s[i].as_array().unwrap(); Point::new(a[0].as_f64().unwrap(), a[1].as_f64().unwrap()) };
|
||||
CubicBez::new(p(0), p(1), p(2), p(3))
|
||||
}).collect();
|
||||
g.insert_stroke(&segs, None, None, 1.0);
|
||||
g.gc_invisible_edges();
|
||||
assert_no_freed_but_referenced(&g);
|
||||
assert_no_spikes(&g);
|
||||
assert_all_fills_connected(&g);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn near_coincident_needle_does_not_spike() {
|
||||
// Smoke test: a stroke poking into a fill and returning along a near-coincident path
|
||||
// must still yield valid, non-corrupt geometry. (The dense-freehand accordion that the
|
||||
// boundary-spike collapse specifically fixes is only reliably reproduced by the captured
|
||||
// region dumps; this is a lightweight portable guard for the same family of inputs.)
|
||||
let mut g = editor_filled_rect(0.0, 0.0, 100.0, 100.0);
|
||||
g.insert_stroke(
|
||||
&[
|
||||
line(Point::new(50.0, -10.0), Point::new(50.0, 50.0)),
|
||||
line(Point::new(50.0, 50.0), Point::new(50.0003, -10.0)),
|
||||
],
|
||||
None, None, 1.0,
|
||||
);
|
||||
g.gc_invisible_edges();
|
||||
assert_no_spikes(&g);
|
||||
assert_all_fills_connected(&g);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn second_stroke_crossing_first_splits_into_quadrants() {
|
||||
// A later stroke that crosses an earlier stroke's edge inside a fill triggers an
|
||||
// edge-domain `split_edge`, whose sub-edges aren't tracked in the second stroke's new
|
||||
// edges. The retrace must still see them (induced-subgraph expansion) or the cut breaks
|
||||
// and unravels. Two crossing cuts through a rectangle must yield four connected quadrants.
|
||||
let mut g = editor_filled_rect(0.0, 0.0, 100.0, 100.0);
|
||||
g.insert_stroke(&[line(Point::new(-10.0, 50.0), Point::new(110.0, 50.0))], None, None, 1.0); // horizontal
|
||||
assert_eq!(g.fills.iter().filter(|f| !f.deleted).count(), 2, "horizontal cut → 2");
|
||||
g.insert_stroke(&[line(Point::new(50.0, -10.0), Point::new(50.0, 110.0))], None, None, 1.0); // vertical, crosses it
|
||||
g.gc_invisible_edges();
|
||||
|
||||
let live: Vec<FillId> = g.fills.iter().enumerate()
|
||||
.filter(|(_, f)| !f.deleted).map(|(i, _)| FillId(i as u32)).collect();
|
||||
assert_eq!(live.len(), 4, "two crossing cuts → four quadrants; got {}", live.len());
|
||||
assert_all_fills_connected(&g);
|
||||
assert_no_spikes(&g);
|
||||
for &fid in &live {
|
||||
assert!((polygon_area(&g, fid) - 2500.0).abs() < 1.0, "each quadrant is 50x50, got {}", polygon_area(&g, fid));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stroke_dead_ending_inside_fill_does_not_spike() {
|
||||
// A stroke (e.g. a freehand lasso that wiggles or nearly self-touches) can leave a
|
||||
// dangling stub: an edge whose inner endpoint has degree 1. Re-tracing must not run out
|
||||
// and back along it (a self-touching "spike" boundary); the fill stays a clean loop.
|
||||
let mut g = editor_filled_rect(0.0, 0.0, 200.0, 100.0);
|
||||
// Open stroke entering the top edge and dead-ending inside at (100,50).
|
||||
let stub = vec![line(Point::new(50.0, -20.0), Point::new(100.0, 50.0))];
|
||||
g.insert_stroke(&stub, None, None, 1.0);
|
||||
g.gc_invisible_edges();
|
||||
|
||||
let live: Vec<FillId> = g.fills.iter().enumerate()
|
||||
.filter(|(_, f)| !f.deleted).map(|(i, _)| FillId(i as u32)).collect();
|
||||
assert_eq!(live.len(), 1, "a dead-end stub must not split the fill; got {}", live.len());
|
||||
assert_all_fills_connected(&g);
|
||||
assert_no_spikes(&g);
|
||||
// The fill is still the full rectangle.
|
||||
assert!((polygon_area(&g, live[0]) - 20000.0).abs() < 1.0,
|
||||
"fill should remain the 200x100 rectangle, area {}", polygon_area(&g, live[0]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groupfail_two_notched_fills_second_lasso() {
|
||||
// Faithful reconstruction of the captured post-group state (dump_1): two adjacent
|
||||
// fills sharing the x=337 column, each with an invisible notch (the hole left by the
|
||||
// first lasso+group). A second lasso (398,249)-(495,327) clips fill 3's corner.
|
||||
use std::collections::HashMap;
|
||||
let mut g = VectorGraph::new();
|
||||
let vp = [
|
||||
(130.0, 232.0), (337.0, 232.0), (337.0, 362.0), (130.0, 362.0), (337.0, 297.0),
|
||||
(535.0, 297.0), (535.0, 417.0), (337.0, 417.0), (0.0, 0.0), (337.0, 315.0),
|
||||
(220.0, 315.0), (456.0, 315.0), (456.0, 345.0), (337.0, 345.0), (220.0, 345.0),
|
||||
];
|
||||
let vs: Vec<_> = vp.iter().map(|&(x, y)| g.alloc_vertex(Point::new(x, y))).collect();
|
||||
let style = StrokeStyle { width: 3.0, ..Default::default() };
|
||||
let color = ShapeColor::rgb(0, 0, 0);
|
||||
// (name, v_start, v_end, visible)
|
||||
let edge_defs: &[(&str, usize, usize, bool)] = &[
|
||||
("e0", 0, 1, true), ("e1", 4, 5, true), ("e2", 2, 3, true), ("e3", 3, 0, true),
|
||||
("e4", 1, 4, true), ("e5", 7, 2, true), ("e6", 5, 6, true), ("e7", 6, 7, true),
|
||||
("e8", 10, 9, false), ("e9", 12, 13, false), ("e11", 4, 9, true), ("e12", 9, 11, false),
|
||||
("e13", 11, 12, false), ("e15", 13, 2, true), ("e16", 13, 14, false), ("e17", 14, 10, false),
|
||||
];
|
||||
let mut em: HashMap<&str, EdgeId> = HashMap::new();
|
||||
for &(name, a, b, vis) in edge_defs {
|
||||
let (ss, sc) = if vis { (Some(style.clone()), Some(color)) } else { (None, None) };
|
||||
let e = g.alloc_edge(line(vp[a].into(), vp[b].into()), vs[a], vs[b], ss, sc);
|
||||
em.insert(name, e);
|
||||
}
|
||||
let mk = |spec: &[(&str, Direction)]| -> Vec<(EdgeId, Direction)> {
|
||||
spec.iter().map(|&(n, d)| (em[n], d)).collect()
|
||||
};
|
||||
use Direction::{Backward as B, Forward as F};
|
||||
g.alloc_fill(mk(&[("e11", B), ("e4", B), ("e0", B), ("e3", B), ("e2", B), ("e15", B), ("e16", F), ("e17", F), ("e8", F)]),
|
||||
ShapeColor::rgb(100, 100, 255), FillRule::NonZero);
|
||||
g.alloc_fill(mk(&[("e15", F), ("e5", B), ("e7", B), ("e6", B), ("e1", B), ("e11", F), ("e12", F), ("e13", F), ("e9", F)]),
|
||||
ShapeColor::rgb(100, 100, 255), FillRule::NonZero);
|
||||
|
||||
assert_eq!(g.fills.iter().filter(|f| !f.deleted).count(), 2, "starts with 2 fills");
|
||||
let (segs, lasso) = rect_lasso(398.0, 249.0, 495.0, 327.0);
|
||||
g.insert_stroke(&segs, None, None, 1.0);
|
||||
g.gc_invisible_edges();
|
||||
|
||||
let live = g.fills.iter().filter(|f| !f.deleted).count();
|
||||
let inside: Vec<FillId> = g.fills.iter().enumerate()
|
||||
.filter(|(_, f)| !f.deleted).map(|(i, _)| FillId(i as u32))
|
||||
.filter(|&fid| lasso.winding(g.fill_interior_point(fid)) != 0).collect();
|
||||
eprintln!("groupfail: {live} live fills, {} inside lasso", inside.len());
|
||||
for (i, f) in g.fills.iter().enumerate() {
|
||||
if f.deleted { continue; }
|
||||
let fid = FillId(i as u32);
|
||||
eprintln!(" fill {i}: bbox {:?} area {:.0}", fill_bbox(&g, fid), polygon_area(&g, fid));
|
||||
}
|
||||
assert_all_fills_connected(&g);
|
||||
// The two original shapes must survive (no faces wrongly deleted); the lasso adds a cut.
|
||||
assert!(live >= 2, "must keep both shapes plus the cut; got {live}");
|
||||
assert_eq!(inside.len(), 1, "exactly the clipped corner of fill 3 should be selected");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lasso_across_notched_fill_never_corrupts_boundaries() {
|
||||
// A rectangle with a rectangular notch bitten out of its top edge — the shape a fill
|
||||
// is left as after grouping a lasso selection (the notch is the extracted region's
|
||||
// hole). A second lasso crossing the notch must never produce disconnected/corrupt
|
||||
// fill boundaries (it previously incorporated the lasso's out-of-shape edges, drawing
|
||||
// stray diagonals). It may under-select on such complex geometry, but must stay valid.
|
||||
let mut g = VectorGraph::new();
|
||||
let pts = [
|
||||
Point::new(0.0, 0.0), Point::new(80.0, 0.0), Point::new(80.0, 40.0),
|
||||
Point::new(120.0, 40.0), Point::new(120.0, 0.0), Point::new(200.0, 0.0),
|
||||
Point::new(200.0, 100.0), Point::new(0.0, 100.0),
|
||||
];
|
||||
let style = StrokeStyle { width: 1.0, ..Default::default() };
|
||||
let color = ShapeColor::rgb(0, 0, 0);
|
||||
let v: Vec<_> = pts.iter().map(|&p| g.alloc_vertex(p)).collect();
|
||||
let mut boundary = Vec::new();
|
||||
for i in 0..pts.len() {
|
||||
let e = g.alloc_edge(line(pts[i], pts[(i + 1) % pts.len()]), v[i], v[(i + 1) % pts.len()],
|
||||
Some(style.clone()), Some(color));
|
||||
boundary.push((e, Direction::Forward));
|
||||
}
|
||||
g.alloc_fill(boundary, ShapeColor::rgb(255, 0, 0), FillRule::NonZero);
|
||||
|
||||
// Lasso a rectangle that straddles the notch and the shape body. Inside the fill it
|
||||
// covers (60..140, 0..60) minus the notch (80..120, 0..40) — an arch shape — which the
|
||||
// cut must isolate as one connected fill, with the remainder outside.
|
||||
let (segs, lasso) = rect_lasso(60.0, -20.0, 140.0, 60.0);
|
||||
g.insert_stroke(&segs, None, None, 1.0);
|
||||
g.gc_invisible_edges();
|
||||
|
||||
// Every resulting fill is a valid connected loop (never corrupt).
|
||||
assert_all_fills_connected(&g);
|
||||
|
||||
// Exactly one fill lies inside the lasso, and it is the arch (area = 80*60 - 40*40).
|
||||
let inside: Vec<FillId> = g.fills.iter().enumerate()
|
||||
.filter(|(_, f)| !f.deleted).map(|(i, _)| FillId(i as u32))
|
||||
.filter(|&fid| lasso.winding(g.fill_interior_point(fid)) != 0).collect();
|
||||
assert_eq!(inside.len(), 1, "the arch (lasso ∩ notched fill) should be one selected fill");
|
||||
let area = polygon_area(&g, inside[0]);
|
||||
assert!((area - 3200.0).abs() < 1.0, "arch area should be 3200, got {area}");
|
||||
}
|
||||
|
||||
/// Absolute polygon area of a fill from its boundary corner points.
|
||||
fn polygon_area(g: &VectorGraph, fid: FillId) -> f64 {
|
||||
let pts: Vec<Point> = g.fill(fid).boundary.iter()
|
||||
.filter(|(e, _)| !e.is_none())
|
||||
.map(|&(e, d)| dir_start(g, e, d))
|
||||
.collect();
|
||||
if pts.len() < 3 { return 0.0; }
|
||||
let mut a2 = 0.0;
|
||||
for i in 0..pts.len() {
|
||||
let p0 = pts[i]; let p1 = pts[(i + 1) % pts.len()];
|
||||
a2 += p0.x * p1.y - p1.x * p0.y;
|
||||
}
|
||||
(a2 * 0.5).abs()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_edge_adjacent_rects_make_two_clean_fills() {
|
||||
// Two rectangles sharing the x=100 edge. The second's left edge lands exactly on the
|
||||
// first's right edge; without coincident-edge cleanup this produced duplicate edges and
|
||||
// zero-area "sliver" fills (4 fills instead of 2) before any lasso.
|
||||
let mut g = editor_filled_rect(0.0, 0.0, 100.0, 100.0);
|
||||
draw_filled_rect(&mut g, 100.0, 0.0, 200.0, 100.0);
|
||||
let live: Vec<_> = g.fills.iter().enumerate().filter(|(_, f)| !f.deleted)
|
||||
.map(|(i, _)| (i, fill_bbox(&g, FillId(i as u32)))).collect();
|
||||
assert_eq!(live.len(), 2, "two adjacent rects should make exactly two fills; got {live:?}");
|
||||
assert_all_fills_connected(&g);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lasso_strip_through_adjacent_second_rect() {
|
||||
// Two rectangles sharing an edge (snapped adjacent), lasso a strip through the second.
|
||||
let mut g = editor_filled_rect(0.0, 0.0, 100.0, 100.0);
|
||||
draw_filled_rect(&mut g, 100.0, 0.0, 200.0, 100.0); // shares the x=100 edge with the first
|
||||
|
||||
let (segs, lasso_path) = rect_lasso(130.0, -50.0, 170.0, 150.0); // strip through 2nd
|
||||
g.insert_stroke(&segs, None, None, 1.0);
|
||||
g.gc_invisible_edges();
|
||||
assert_all_fills_connected(&g);
|
||||
|
||||
let inside: Vec<FillId> = g.fills.iter().enumerate()
|
||||
.filter(|(_, f)| !f.deleted).map(|(i, _)| FillId(i as u32))
|
||||
.filter(|&fid| lasso_path.winding(fill_centroid(&g, fid)) != 0).collect();
|
||||
let dump: Vec<_> = g.fills.iter().enumerate().filter(|(_, f)| !f.deleted)
|
||||
.map(|(i, _)| (i, fill_centroid(&g, FillId(i as u32)), describe_boundary(&g, FillId(i as u32)).len())).collect();
|
||||
assert_eq!(inside.len(), 1, "one strip of the 2nd rect should be inside; got {dump:#?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lasso_strip_through_overlapping_second_rect() {
|
||||
// Second rectangle overlaps the first; lasso a strip through the second's free part.
|
||||
let mut g = editor_filled_rect(0.0, 0.0, 100.0, 100.0);
|
||||
draw_filled_rect(&mut g, 60.0, 60.0, 200.0, 160.0);
|
||||
|
||||
let (segs, _lasso) = rect_lasso(120.0, 40.0, 160.0, 180.0);
|
||||
g.insert_stroke(&segs, None, None, 1.0);
|
||||
g.gc_invisible_edges();
|
||||
assert_all_fills_connected(&g);
|
||||
}
|
||||
|
||||
/// Bounding box of a fill's boundary edge endpoints.
|
||||
fn fill_bbox(g: &VectorGraph, fid: FillId) -> (f64, f64, f64, f64) {
|
||||
let (mut minx, mut miny, mut maxx, mut maxy) = (f64::MAX, f64::MAX, f64::MIN, f64::MIN);
|
||||
for &(eid, _) in &g.fill(fid).boundary {
|
||||
if eid.is_none() {
|
||||
continue;
|
||||
}
|
||||
for &vid in &g.edge(eid).vertices {
|
||||
let p = g.vertex(vid).position;
|
||||
minx = minx.min(p.x);
|
||||
miny = miny.min(p.y);
|
||||
maxx = maxx.max(p.x);
|
||||
maxy = maxy.max(p.y);
|
||||
}
|
||||
}
|
||||
(minx, miny, maxx, maxy)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lasso_corner_clip_of_second_rect_splits_off_corner() {
|
||||
// Captured repro (/tmp dump): two separate rects; the lasso clips the top-left CORNER
|
||||
// of the second rect, so the cut path turns a corner at a vertex INTERIOR to the rect.
|
||||
let mut g = editor_filled_rect(128.37, 255.97, 290.91, 336.55); // rect 1
|
||||
draw_filled_rect(&mut g, 417.39, 311.62, 620.25, 442.55); // rect 2
|
||||
let (segs, lasso) = rect_lasso(360.12, 277.92, 537.32, 397.14); // clips rect-2 corner
|
||||
g.insert_stroke(&segs, None, None, 1.0);
|
||||
g.gc_invisible_edges();
|
||||
assert_all_fills_connected(&g);
|
||||
|
||||
let inside: Vec<FillId> = g.fills.iter().enumerate()
|
||||
.filter(|(_, f)| !f.deleted).map(|(i, _)| FillId(i as u32))
|
||||
.filter(|&fid| lasso.winding(fill_centroid(&g, fid)) != 0).collect();
|
||||
let dump: Vec<_> = g.fills.iter().enumerate().filter(|(_, f)| !f.deleted)
|
||||
.map(|(i, _)| (i, fill_centroid(&g, FillId(i as u32)), fill_bbox(&g, FillId(i as u32)), describe_boundary(&g, FillId(i as u32)).len())).collect();
|
||||
assert_eq!(inside.len(), 1, "exactly the clipped corner should be inside; fills = {dump:#?}");
|
||||
|
||||
// The selected fill must be the clipped CORNER, not the whole rect 2.
|
||||
let (minx, miny, maxx, maxy) = fill_bbox(&g, inside[0]);
|
||||
let eps = 1.0;
|
||||
assert!(
|
||||
(minx - 417.39).abs() < eps && (miny - 311.62).abs() < eps
|
||||
&& (maxx - 537.32).abs() < eps && (maxy - 397.14).abs() < eps,
|
||||
"expected clipped-corner bbox (417.4,311.6)-(537.3,397.1), got ({minx:.1},{miny:.1})-({maxx:.1},{maxy:.1}) \
|
||||
— whole rect2 is (417,311)-(620,442); the fill wasn't split"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lasso_over_middle_of_rect_selects_clean_center_strip() {
|
||||
// Rectangle (0,0)-(200,100); lasso a vertical strip (50,-50)-(150,150).
|
||||
let mut g = editor_filled_rect(0.0, 0.0, 200.0, 100.0);
|
||||
let (segs, lasso_path) = rect_lasso(50.0, -50.0, 150.0, 150.0);
|
||||
|
||||
g.insert_stroke(&segs, None, None, 1.0);
|
||||
// The editor runs this right after the cut: the lasso's top/bottom edges and the
|
||||
// out-of-shape extensions of its sides are invisible and unreferenced — they must be
|
||||
// collected so they can't be selected/edited later.
|
||||
g.gc_invisible_edges();
|
||||
for (i, e) in g.edges.iter().enumerate() {
|
||||
if e.deleted || e.stroke_style.is_some() || e.stroke_color.is_some() {
|
||||
continue;
|
||||
}
|
||||
let eid = EdgeId(i as u32);
|
||||
let in_a_fill = g
|
||||
.fills
|
||||
.iter()
|
||||
.any(|f| !f.deleted && f.boundary.iter().any(|&(fe, _)| fe == eid));
|
||||
assert!(
|
||||
in_a_fill,
|
||||
"stray invisible edge {i} ({:?}) survived gc — not part of any fill",
|
||||
e.curve
|
||||
);
|
||||
}
|
||||
|
||||
// Classify fills by centroid winding (the editor's logic).
|
||||
let inside_fills: Vec<FillId> = g
|
||||
.fills
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, f)| !f.deleted)
|
||||
.map(|(i, _)| FillId(i as u32))
|
||||
.filter(|&fid| lasso_path.winding(fill_centroid(&g, fid)) != 0)
|
||||
.collect();
|
||||
|
||||
let dump = || {
|
||||
g.fills
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, f)| !f.deleted)
|
||||
.map(|(i, _)| {
|
||||
let fid = FillId(i as u32);
|
||||
(i, fill_centroid(&g, fid), describe_boundary(&g, fid))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
inside_fills.len(),
|
||||
1,
|
||||
"expected exactly one inside fill (the center strip); live fills = {:#?}",
|
||||
dump()
|
||||
);
|
||||
|
||||
let fid = inside_fills[0];
|
||||
let boundary = describe_boundary(&g, fid);
|
||||
|
||||
// The center strip is a rectangle: it must have 4 boundary edges that form a
|
||||
// *connected closed loop* (each edge's directed end == the next edge's directed start).
|
||||
// Before the fix, the split produced a 2-edge boundary (left cut + top segment) whose
|
||||
// bbox is still (50,0)-(150,100) but which `fill_to_bezpath` renders as left+top edges
|
||||
// plus a diagonal close — the artifact the user reported.
|
||||
assert_eq!(
|
||||
boundary.len(),
|
||||
4,
|
||||
"center strip should have 4 boundary edges, got {}: {:#?}",
|
||||
boundary.len(),
|
||||
boundary
|
||||
);
|
||||
|
||||
let eps = 1e-6;
|
||||
let n = boundary.len();
|
||||
for i in 0..n {
|
||||
let (_, _, end) = boundary[i];
|
||||
let (_, next_start, _) = boundary[(i + 1) % n];
|
||||
assert!(
|
||||
(end.x - next_start.x).abs() < eps && (end.y - next_start.y).abs() < eps,
|
||||
"boundary is disconnected between edge {i} (ends {end:?}) and edge {} \
|
||||
(starts {next_start:?}); full boundary = {boundary:#?}",
|
||||
(i + 1) % n
|
||||
);
|
||||
}
|
||||
|
||||
// And the loop should visit the four expected corners.
|
||||
let corners = [
|
||||
Point::new(50.0, 0.0),
|
||||
Point::new(150.0, 0.0),
|
||||
Point::new(150.0, 100.0),
|
||||
Point::new(50.0, 100.0),
|
||||
];
|
||||
for c in corners {
|
||||
let hit = boundary
|
||||
.iter()
|
||||
.any(|&(_, s, _)| (s.x - c.x).abs() < 0.5 && (s.y - c.y).abs() < 0.5);
|
||||
assert!(hit, "center strip boundary should pass through corner {c:?}: {boundary:#?}");
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user