Compare commits
157
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 | ||
|
|
f585c370e8 | ||
|
|
ed022995bd | ||
|
|
3188fc8bb6 | ||
|
|
2cbaf67583 | ||
|
|
31e23b0fc7 | ||
|
|
c627533185 | ||
|
|
aae51e3b3c | ||
|
|
4cb43d670b | ||
|
|
a35cc6fa9f | ||
|
|
3c302f0215 | ||
|
|
1bfd09f151 | ||
|
|
a1e3cc841f | ||
|
|
17d7395229 | ||
|
|
62d6cd0c84 | ||
|
|
d001ca1083 | ||
|
|
39dc402ba3 | ||
|
|
2e07a88905 | ||
|
|
4228864259 | ||
|
|
6d386a884e | ||
|
|
4ad95e6755 | ||
|
|
097345be76 | ||
|
|
c784816615 | ||
|
|
3d7cff9ad0 | ||
|
|
83609cc9dc | ||
|
|
318720f89d | ||
|
|
7257cdf9c4 | ||
|
|
d6c6c0d72d | ||
|
|
d7de5ce3f1 | ||
|
|
2a0c7da5ea | ||
|
|
37f4abd1f5 | ||
|
|
a36553ccbb | ||
|
|
45955dbbec | ||
|
|
54d5764bd0 | ||
|
|
f372a84313 | ||
|
|
ae146533d9 | ||
|
|
3fc4773ec3 | ||
|
|
cfb8e4462b | ||
|
|
65a550d8f4 | ||
|
|
123fe3f21a | ||
|
|
fa40173562 |
+74
-22
@@ -14,7 +14,7 @@ jobs:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- platform: ubuntu-22.04
|
||||
- platform: ubuntu-24.04
|
||||
target: ''
|
||||
artifact-name: linux-x86_64
|
||||
- platform: macos-latest
|
||||
@@ -62,7 +62,7 @@ jobs:
|
||||
|
||||
# ── Linux dependencies ──
|
||||
- name: Install dependencies (Linux)
|
||||
if: matrix.platform == 'ubuntu-22.04'
|
||||
if: matrix.platform == 'ubuntu-24.04'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
@@ -71,10 +71,11 @@ 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)
|
||||
if: matrix.platform == 'ubuntu-22.04'
|
||||
if: matrix.platform == 'ubuntu-24.04'
|
||||
uses: taiki-e/install-action@v2
|
||||
with:
|
||||
tool: cargo-deb,cargo-generate-rpm
|
||||
@@ -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: |
|
||||
@@ -135,7 +154,7 @@ jobs:
|
||||
rm -f lightningbeam-ui/lightningbeam-editor/assets/presets/README.md
|
||||
|
||||
- name: Inject preset entries into RPM metadata (Linux)
|
||||
if: matrix.platform == 'ubuntu-22.04'
|
||||
if: matrix.platform == 'ubuntu-24.04'
|
||||
shell: bash
|
||||
run: |
|
||||
cd lightningbeam-ui
|
||||
@@ -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
|
||||
@@ -190,7 +241,7 @@ jobs:
|
||||
# Linux Packaging
|
||||
# ══════════════════════════════════════════════
|
||||
- name: Build .deb package
|
||||
if: matrix.platform == 'ubuntu-22.04'
|
||||
if: matrix.platform == 'ubuntu-24.04'
|
||||
shell: bash
|
||||
run: |
|
||||
cd lightningbeam-ui
|
||||
@@ -206,14 +257,15 @@ jobs:
|
||||
rm -rf "$WORK"
|
||||
|
||||
- name: Build .rpm package
|
||||
if: matrix.platform == 'ubuntu-22.04'
|
||||
if: matrix.platform == 'ubuntu-24.04'
|
||||
shell: bash
|
||||
run: |
|
||||
cd lightningbeam-ui
|
||||
cargo generate-rpm -p lightningbeam-editor
|
||||
RPM_VERSION=$(grep '^version' lightningbeam-editor/Cargo.toml | sed 's/.*"\(.*\)"/\1/' | tr '-' '~')
|
||||
cargo generate-rpm -p lightningbeam-editor --set-metadata="version = \"$RPM_VERSION\""
|
||||
|
||||
- name: Build AppImage
|
||||
if: matrix.platform == 'ubuntu-22.04'
|
||||
if: matrix.platform == 'ubuntu-24.04'
|
||||
shell: bash
|
||||
run: |
|
||||
cd lightningbeam-ui
|
||||
@@ -259,7 +311,7 @@ jobs:
|
||||
chmod +x "Lightningbeam_Editor-${VERSION}-x86_64.AppImage"
|
||||
|
||||
- name: Upload .deb
|
||||
if: matrix.platform == 'ubuntu-22.04'
|
||||
if: matrix.platform == 'ubuntu-24.04'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: deb-package
|
||||
@@ -267,7 +319,7 @@ jobs:
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Upload .rpm
|
||||
if: matrix.platform == 'ubuntu-22.04'
|
||||
if: matrix.platform == 'ubuntu-24.04'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: rpm-package
|
||||
@@ -275,7 +327,7 @@ jobs:
|
||||
if-no-files-found: error
|
||||
|
||||
- name: Upload AppImage
|
||||
if: matrix.platform == 'ubuntu-22.04'
|
||||
if: matrix.platform == 'ubuntu-24.04'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: appimage
|
||||
@@ -295,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
|
||||
@@ -380,7 +432,7 @@ jobs:
|
||||
|
||||
release:
|
||||
needs: build
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
|
||||
@@ -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,85 @@
|
||||
# 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)
|
||||
- Tempo can now be non-constant (variable BPM)
|
||||
- All events now have time references in seconds, measures/beats, and frames
|
||||
- Add piano roll note snapping
|
||||
- Snap to beats in measures mode
|
||||
- Add velocity and modulation editing
|
||||
- Add pitch bend support
|
||||
- Add automation inputs for audio graphs
|
||||
- Add automatable volume and pan controls to default instruments
|
||||
- Add count-in and metronome
|
||||
- Add drawing tablet input support
|
||||
- Set default timeline mode based on activity
|
||||
- Tweaked automation lane appearance
|
||||
- Double CPU rendering performance by switching to tiny-skia
|
||||
|
||||
Bugfixes:
|
||||
- Fix MIDI track recording previews
|
||||
- Fix timeline elements not updating on BPM changes
|
||||
|
||||
# 1.0.3-alpha:
|
||||
Changes:
|
||||
- Add gradient support to vector graphics
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,859 @@
|
||||
# Streaming Media To/From Disk — Plan
|
||||
|
||||
**Goal:** Lightningbeam must handle audio and video files (and raster animation, and
|
||||
image assets) of *arbitrary length/size*. Anywhere we touch media we should stream from
|
||||
and to disk when the data is too large to fit comfortably in memory, rather than loading
|
||||
the entire file regardless of size.
|
||||
|
||||
**Scope of this document:** audio, video, raster frames, image-asset paging, **and the
|
||||
`.beam` container format** — these turned out to be one problem, not two. Streaming on load
|
||||
is impossible while the container forces a full decode, so the container decision (below)
|
||||
is now part of this plan.
|
||||
|
||||
## Deferred bugs (do at the end)
|
||||
- [x] **Timeline thumbnail scroll (FIXED):** the strip tiled from the *clamped* visible-left of the
|
||||
clip, so when a clip was scrolled partly off the left it showed the clip's start content at the
|
||||
viewport edge. Now tiled from the clip's **true (unclamped) origin** over its full width, drawing
|
||||
only the tiles intersecting the visible rect (`draw_video_thumbnail_strip` in timeline.rs). Both
|
||||
render sites (collapsed-group + expanded-track) share the helper. *(Compiles; needs in-app check.)*
|
||||
- [x] **Clip thumbnails stop updating (FIXED):** the GPU texture cache was keyed by the *requested*
|
||||
content time, so once a tile cached the first (often far-off) thumbnail it never refreshed as
|
||||
closer ones loaded. `VideoManager::get_thumbnail_at` now also returns the **actual** thumbnail
|
||||
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.)*
|
||||
|
||||
## 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
|
||||
covers every storage type (PCM/InMemory, compressed via symphonia, video-audio via ffmpeg — all
|
||||
flow through this mixer with the source kept multichannel in the read-ahead buffer). New
|
||||
`stereo_downmix_matrix(src_channels)` gives `[L][src]`/`[R][src]` coefficients for the conventional
|
||||
interleave order (FL FR FC LFE BL BR SL SR…) for 3/4/5/5.1/6.1/7.1: full level for the matching
|
||||
front, `1/√2` for centre + each surround, LFE dropped; each row normalized so |coef| sum ≤ 1 to
|
||||
prevent clipping (matches ffmpeg's default). Applied in both the direct-copy and sinc-resample
|
||||
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 (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/
|
||||
decode) still worth chasing if it recurs.
|
||||
- [x] **Persist video thumbnails (DONE).** Mirrors waveform persistence: each clip's thumbnails are
|
||||
PNG-encoded + packed into one opaque `LBTN` blob (editor owns the format; `encode/decode_thumbnail_blob`
|
||||
in main.rs), stored as a `MediaKind::Thumbnail` row keyed by `thumbnail_media_id(clip_id)` (clip id XOR
|
||||
a fixed sentinel). Save: a cheap Arc-clone snapshot (`VideoManager::snapshot_all_thumbnails`) rides the
|
||||
`FileCommand::Save`, PNG-encoded off the UI thread in the worker, written by `save_beam` (kept in place
|
||||
on re-save). Load: `load_beam_sqlite` reads the packs into `LoadedProject.thumbnail_blobs`; the editor
|
||||
decodes + `insert_thumbnail`s them on a background thread and **gates regeneration** (`register_loaded_videos`
|
||||
skips clips with persisted thumbnails). Bonus: thumbnails show even if the source video file is missing.
|
||||
**Partial sets are persisted and resumed** (not thrown away): the `LBTN` blob (v2) carries a `complete`
|
||||
flag (`VideoManager.thumbnails_complete`, marked when the keyframe pass finishes). On load, complete
|
||||
packs are restored + skip regeneration; *partial* packs are restored AND generation is resumed —
|
||||
`generate_keyframe_thumbnails` takes a `should_skip` predicate (`has_thumbnail_near`) so it only decodes
|
||||
the keyframes not already covered. `insert_thumbnail` is now sorted + idempotent (fixes a latent
|
||||
unsorted-`binary_search` bug and makes concurrent restore + resume race-safe). So a save 50 min into a
|
||||
2 h video keeps that work and continues from there on reload.
|
||||
Container tests still green; all crates compile. *(Needs in-app check: reload = instant thumbnails for
|
||||
complete clips; a mid-generation save resumes from where it left off on reload.)*
|
||||
**Size assessment (done):** thumbnails are 128px wide, height by aspect (72px at 16:9 →
|
||||
128×72×4 ≈ **36 KB raw** each; 4:3 ≈ 49 KB), generated **one per ~5 s** (capped `interval_secs`,
|
||||
at keyframes — so ~12/min). Raw: ~0.5 MB per 1:14 clip, ~26 MB/hour, ~52 MB/2 h. Compressed for
|
||||
on-disk: JPEG ~3–6 KB/thumb → **~6 MB/2 h**; PNG ~8–15 KB → ~14 MB/2 h. So persistence is cheap
|
||||
(≤ the waveform's ~36 MB/2 h), especially as JPEG. Plan: encode each clip's thumbnails (JPEG) +
|
||||
their timestamps into one blob, a new `MediaKind::Thumbnail` row keyed by the clip/media id (mirror
|
||||
the waveform persistence: write on save, restore via `insert_thumbnail` on load, regenerate if
|
||||
absent). The 5 s interval already bounds count; no extra budget needed.
|
||||
- **Progressive waveform on first import:** generation streams the whole file before the
|
||||
waveform appears (several seconds for large files). Since `build_waveform_pyramid` already
|
||||
streams, emit partial floors as it advances (e.g. flush every N seconds of decoded audio via
|
||||
the existing `waveform_result` channel + chunked GPU upload) so the overview fills in across
|
||||
the clip left-to-right instead of appearing all at once. Persistence saves only the final
|
||||
complete pyramid.
|
||||
|
||||
## Guiding principle
|
||||
Three subsystems already have the right streaming primitive; most of the work is wiring,
|
||||
bounding caches, and adding a residency window. The recurring pattern:
|
||||
|
||||
> Keep tiny metadata always-resident, fault the heavy payload in on demand keyed by a
|
||||
> stable ID, and evict everything outside a window around the playhead.
|
||||
|
||||
---
|
||||
|
||||
## Audit summary (where we stand today)
|
||||
|
||||
### Correctly streaming / bounded
|
||||
- Video frame decode/seek/playback (`lightningbeam-core/src/video.rs:191` `get_frame` —
|
||||
keyframe-index seek + decode-until-target, one frame resident).
|
||||
- WAV/AIFF import via mmap (`daw-backend/src/audio/engine.rs:2328`).
|
||||
- Webcam capture encodes directly to disk (`lightningbeam-core/src/webcam.rs`).
|
||||
- `WaveformCache` (100MB cap), decoder `LruCache` (20 frames), export render loop (≤3
|
||||
frames in flight).
|
||||
- The compressed-audio disk reader `daw-backend/src/audio/disk_reader.rs`
|
||||
(`CompressedReader` + 3s `ReadAheadBuffer`) — **correct but never activated** (Phase 1a).
|
||||
|
||||
### Fully-loaded, unbounded by file length (the problems)
|
||||
| Site | Issue |
|
||||
|---|---|
|
||||
| `daw-backend/src/io/audio_file.rs:344` `decode_progressive` | Decodes whole compressed file into a `Vec<f32>`; de-facto playback source. |
|
||||
| `daw-backend/src/audio/pool.rs:1071` `load_file_into_pool` | Every audio file in a saved project fully decoded to `InMemory` on open. |
|
||||
| `lightningbeam-core/src/video.rs:711` `extract_audio_from_video` | Whole video audio track into one `Vec<f32>`. |
|
||||
| `lightningbeam-core/src/video.rs:412` `VideoManager.frame_cache` | Unbounded `HashMap` of full-res RGBA frames; grows while scrubbing. |
|
||||
| `export/mod.rs:388-400` | Mux step buffers all compressed packets into `Vec`s; O(duration). |
|
||||
| `lightningbeam-core/src/raster_layer.rs:115` `RasterKeyframe.raw_pixels` | ~8MB/frame at 1080p; all keyframes decoded from PNG at load (`file_io.rs:611-640`), never evicted. |
|
||||
| `lightningbeam-editor/src/gpu_brush.rs:1051` `raster_layer_cache` | Unbounded GPU texture `HashMap`. |
|
||||
| `lightningbeam-core/src/renderer.rs:25` `ImageCache` | Unbounded decoded image cache (asset textures). |
|
||||
| `Document.image_assets` (`document.rs:206`) | Every image asset's compressed bytes resident for document life. |
|
||||
|
||||
---
|
||||
|
||||
## Container format decision: `.beam` → SQLite *(DECIDED)*
|
||||
|
||||
The `.beam` container moves from a **ZIP archive** to a **SQLite database file** (same
|
||||
`.beam` extension). This is the foundation the rest of the plan builds on.
|
||||
|
||||
### Why
|
||||
ZIP can stream `Stored` entries in place (via `data_start()`), but it has **no in-place
|
||||
mutation** — every save and every raster frame write-back rewrites the whole archive — and
|
||||
embedded PCM is rarely mmap-aligned. The current load path is even worse: it reads each
|
||||
ZIP audio entry fully, decodes FLAC → re-encodes WAV → base64 → base64-decodes → temp file
|
||||
→ full Symphonia decode → resident `Vec<f32>` (`file_io.rs:513-604`, `pool.rs:1071`).
|
||||
|
||||
SQLite dissolves the single-file-vs-performance tension:
|
||||
- **Single file** — beginner-friendly, behaves like a file on every OS (no package-folder
|
||||
confusion; we have no bundle magic on Linux/Windows).
|
||||
- **Streaming reads** — `sqlite3_blob_open` / `blob_read(offset, len)` gives seekable,
|
||||
chunked reads through the pager (mmap mode for the DB). For chunked streaming the
|
||||
pager-copy is negligible vs. decode cost, so the lack of zero-copy mmap doesn't matter.
|
||||
- **Cheap, crash-safe mutation** — raster frame write-back is a transactional `UPDATE`;
|
||||
save is a metadata write + dirty-blob updates. **ACID** means a force-quit / power loss /
|
||||
crash mid-save can't corrupt the project (ZIP and package-dirs both have to hand-roll
|
||||
atomicity).
|
||||
- **Inspectable / scriptable** — `sqlite3` CLI; `beam_inspector.py` can read it directly.
|
||||
|
||||
**Net effect: there is no scratch directory anywhere in this plan.** Media stream via blob
|
||||
reads (or external paths); raster frames live in blob rows and write back transactionally.
|
||||
|
||||
### Large-media policy: packed OR referenced
|
||||
Two storage modes per media item, both supported:
|
||||
- **Packed** — bytes live in the DB. To stay under SQLite's ~2GB per-blob ceiling (and to
|
||||
make reads naturally chunked), large media is split into **multiple blob-chunk rows**
|
||||
(e.g. 64 MB/chunk); streaming reads address `(chunk_index, offset)`.
|
||||
- **Referenced** — the DB stores only a path; bytes stay on disk (useful for shared media
|
||||
on a network drive, or media too large/volatile to pack).
|
||||
|
||||
**Default-mode preference for files over the per-blob limit (~2GB):**
|
||||
- A user preference `large_media_default: Pack | Reference` controls what happens to
|
||||
imports above the threshold.
|
||||
- The **first time** the user imports a media file over the limit, **prompt** them
|
||||
(Pack vs Reference), apply it, and **persist the choice** as the preference for future
|
||||
large imports (changeable later in settings).
|
||||
- Files under the limit are packed by default (chunked only if needed).
|
||||
|
||||
### Schema sketch
|
||||
```
|
||||
media(
|
||||
id BLOB PRIMARY KEY, -- stable Uuid
|
||||
kind INTEGER, -- audio | video | raster | image-asset
|
||||
codec TEXT, -- "flac","mp3","png",... (original, lossless-preserving)
|
||||
storage INTEGER, -- 0 = packed, 1 = referenced
|
||||
ext_path TEXT, -- set when storage = referenced
|
||||
total_len INTEGER, -- bytes (packed) for chunk math
|
||||
channels INTEGER, sample_rate INTEGER, width INTEGER, height INTEGER -- kind-specific meta
|
||||
)
|
||||
media_chunk(
|
||||
media_id BLOB, chunk_index INTEGER, bytes BLOB,
|
||||
PRIMARY KEY (media_id, chunk_index)
|
||||
)
|
||||
project_json(id INTEGER PRIMARY KEY CHECK (id = 0), data TEXT) -- existing project.json, verbatim
|
||||
meta(key TEXT PRIMARY KEY, value TEXT) -- version, created, modified
|
||||
```
|
||||
`project.json` stays the same serialized `BeamProject` for now — only its container and the
|
||||
media storage change. A migration reads a legacy ZIP `.beam` and writes the SQLite form on
|
||||
first open/save.
|
||||
|
||||
### Streaming reads from packed media
|
||||
A `BlobReader` implementing `Read + Seek` over `media_chunk` rows feeds the existing
|
||||
streaming consumers unchanged: `CompressedReader` (audio) decodes from it instead of a
|
||||
`File`; the video decoder seeks within it; raster `UPDATE`s a chunk. Referenced media uses a
|
||||
plain `File` exactly as `do_import_audio` already does for originals today.
|
||||
|
||||
---
|
||||
|
||||
## Phase 1 — Audio: activate what already exists *(highest impact, lowest effort)*
|
||||
|
||||
### 1a. Turn on the compressed-audio disk reader
|
||||
The `CompressedReader` + 3-second `ReadAheadBuffer` in `disk_reader.rs` is complete but
|
||||
never invoked (`DiskReaderCommand::ActivateFile` / `DiskReader::create_buffer` are never
|
||||
called; `AudioClip::read_ahead` at `clip.rs:63` is hard-wired to `None`).
|
||||
- On compressed import (`engine.rs:2381`) and during playback setup, activate the file and
|
||||
assign `AudioClip::read_ahead`.
|
||||
- Change `decode_progressive` (`io/audio_file.rs:344`) to produce only the downsampled
|
||||
waveform overview (min/max peaks) the UI needs, then drop decoded PCM. Playback comes
|
||||
from the ring buffer, not RAM.
|
||||
- Verify `render_from_file` (`pool.rs:449`) reads from `read_ahead` when `data()` is empty.
|
||||
|
||||
**Risk:** the real-time thread must never block on disk. The ring buffer prefetches ~2s
|
||||
ahead; underruns degrade to silence (live) or block-wait (export), which `disk_reader.rs`
|
||||
already distinguishes.
|
||||
|
||||
### 1b. Stream on project load *(depends on the SQLite container)*
|
||||
Three coupled changes (none works alone):
|
||||
1. Replace `load_file_into_pool`'s full decode (`pool.rs:1071`) with the same branching as
|
||||
`do_import_audio`: PCM → mmap (referenced) or in-memory for tiny packed PCM; compressed
|
||||
(incl. FLAC) → `from_compressed` placeholder backed by a `BlobReader` (packed) or `File`
|
||||
(referenced). The claxon FLAC→WAV→base64 round-trip in `file_io.rs:533-591` is deleted.
|
||||
2. **Bulk read-ahead activation:** loaded clips are deserialized directly
|
||||
(`audio_backend.project`), bypassing `AddAudioClip`, so the Phase 1a wiring never fires
|
||||
for them. After the engine installs the project, walk all audio clips and
|
||||
`create_buffer` + `ActivateFile` + set `read_ahead` for every clip referencing a
|
||||
`Compressed` pool entry. (`CompressedReader::open` needs a variant that takes a
|
||||
`BlobReader` instead of a path for packed media.)
|
||||
3. Pool entries carry storage mode (packed-chunks vs referenced path) from the `media`
|
||||
table instead of base64 `embedded_data`.
|
||||
|
||||
### 1c. Video's embedded audio track — stream from the video via ffmpeg
|
||||
|
||||
**Interim stopgap (shipped):** `extract_audio_from_video_to_wav` streams the decoded audio to
|
||||
a temp WAV, imported via `import_audio_sync` (mmap). Fixes the RAM OOM but writes the whole
|
||||
uncompressed track to `/tmp` (fills small temp partitions) and the temp path doesn't survive
|
||||
save/reload. **Superseded by the design below.**
|
||||
|
||||
**Proper design — stream the video's audio track on demand, never materialized.**
|
||||
|
||||
*Enabler:* `daw-backend` already depends on `ffmpeg-next` (used for MP3/AAC encoding), so the
|
||||
ffmpeg audio decoder lives beside `CompressedReader` in `daw-backend/src/audio/`. No
|
||||
cross-crate work (`core → daw-backend` is one-way). `CompressedReader` already has the needed
|
||||
interface.
|
||||
|
||||
1. **`VideoAudioReader` (ffmpeg)** — mirrors `CompressedReader`:
|
||||
`open(path)`, `decode_next(&mut Vec<f32>) -> frames` (resample → interleaved f32 at native
|
||||
rate; reuse the old extraction resampler), `seek(target_frame) -> actual`,
|
||||
`sample_rate`/`channels`/`total_frames`.
|
||||
2. **Source dispatch:** `enum StreamSource { Compressed(CompressedReader), Video(VideoAudioReader) }`
|
||||
(or a small `trait AudioFrameSource`) held by the reader thread; ring buffer / prefetch /
|
||||
export-blocking unchanged. `DiskReaderCommand::ActivateFile` gains a `kind: SourceKind`.
|
||||
3. **Pool model:** `AudioStorage::VideoAudio { video_path, decoded_for_waveform, decoded_frames,
|
||||
total_frames }` (near-copy of `Compressed`); `data()` empty, playback via `read_ahead`. Pool
|
||||
entry `path` = the video file.
|
||||
4. **Engine API:** `EngineController::add_video_audio_sync(video_path) -> usize` — ffmpeg-probe
|
||||
the audio track (rate/channels/frames/duration, no decode), build the pool entry, return index.
|
||||
5. **Clip activation:** extend the Phase 1a `AddAudioClip` wiring — if entry is `VideoAudio`,
|
||||
make the buffer + `ActivateFile{kind:VideoAudio, path:video_path}` + set `clip.read_ahead`.
|
||||
One ffmpeg context + 3 s buffer per active clip instance.
|
||||
6. **Import flow:** `import_video` calls `add_video_audio_sync(video_path)` →
|
||||
`AudioClip::new_sampled`. **Remove** `extract_audio_from_video_to_wav`, the temp-WAV
|
||||
handling, and the now-dead `add_audio_file_sync`. No WAV / `/tmp` / RAM.
|
||||
7. **Save/load:** the `VideoAudio` entry serializes as a path reference to the video (no media
|
||||
bytes — the video is already referenced by its `VideoClip`); reconstruct on load by
|
||||
re-probing. Fixes the stopgap's reload fragility (nothing to persist).
|
||||
8. **Waveform overview:** background ffmpeg pass emitting **downsampled peaks only** (bounded
|
||||
memory) into the existing waveform path — shared with the Phase 1a `decode_progressive`
|
||||
cleanup.
|
||||
|
||||
**Sample accuracy (required — video audio must stay frame-synced with other clips):**
|
||||
Coarse ffmpeg seeks are NOT sufficient. `VideoAudioReader::seek(target_frame)` must:
|
||||
- coarse-seek to a point ≤ target, then **decode-and-discard** to land exactly on
|
||||
`target_frame`, tracking the absolute sample position from decoded-frame PTS (discard whole
|
||||
frames before target; for the frame straddling target, drop its leading samples). After
|
||||
`seek`, `decode_next` yields samples starting at exactly `target_frame`.
|
||||
- This makes frame N of the video-audio pool entry correspond to the exact timeline position,
|
||||
so it mixes sample-aligned with mmap/InMemory clips. Continuous decode advances frame-exact.
|
||||
- *Consistency note:* `CompressedReader` should get the same decode-discard alignment (its
|
||||
current coarse-seek-then-write-at-target can misalign by up to a GOP after a seek). Fold in
|
||||
while here, or at least flag.
|
||||
|
||||
*Model decision (confirmed):* the video's audio stays a **separate, editable `AudioClip`** on
|
||||
an audio track, backed by the `VideoAudio` pool entry — users can move/trim/mute/detach it.
|
||||
|
||||
*Build order:* `VideoAudioReader` + `StreamSource` → pool `VideoAudio` variant →
|
||||
`add_video_audio_sync` + activation → swap `import_video` (remove WAV path) → sample-accurate
|
||||
seek (both readers) → waveform-peaks pass.
|
||||
|
||||
---
|
||||
|
||||
## Phase 2 — Video: bound the caches *(small, isolated)*
|
||||
|
||||
### 2a. Bound `VideoManager.frame_cache`
|
||||
`video.rs:412` — convert the unbounded `HashMap<(Uuid,i64), Arc<VideoFrame>>` to an LRU
|
||||
mirroring the decoder-level cache (`video.rs:34`). Frame-count or byte budget.
|
||||
|
||||
### 2b. Stream the export mux
|
||||
`export/mod.rs:388-400` — interleave-write packets to the output as produced (compare PTS,
|
||||
write the earlier stream) instead of collecting all then writing. O(duration) → O(1).
|
||||
|
||||
---
|
||||
|
||||
## Phase 3 — Raster: disk-backed keyframe paging *(the heavy one)* **[locked design]**
|
||||
|
||||
Today `load_beam_sqlite` (`file_io.rs:564`) eagerly `decode_png`s **every** raster keyframe's
|
||||
`Raster` media row into `RasterKeyframe.raw_pixels` (`raster_layer.rs:115`, `w·h·4` ≈ 8 MB @
|
||||
1080p, `#[serde(skip)]`), never evicts, has an unbounded GPU texture cache, and holds full-frame
|
||||
undo snapshots. `raw_pixels` is the working rep (edits write it, save reads it, render reads it),
|
||||
`has_pixels()` = `!raw_pixels.is_empty()`, `keyframe_at` is a `partition_point` binary search, and
|
||||
the container is opened only at load/save (no live handle).
|
||||
|
||||
**Design (confirmed with user):** keep `raw_pixels` as the working rep; make residency explicit
|
||||
via a `RasterStore` + an editor-run fault-in/evict pass *before* the immutable render. Async
|
||||
fault-in (no scrub hitch), with a **low-res image proxy** shown until the full frame lands.
|
||||
Decisions: small window (±~2 keyframes); **dirty (edited-unsaved) frames stay fully resident**
|
||||
(spill-to-scratch deferred); fault-in is **async**; proxy is a **per-keyframe low-res RGBA image**
|
||||
(PNG/WebP, correct alpha), NOT a video (VP9-alpha was rejected as finicky for negligible disk win).
|
||||
|
||||
### Drive-by (Arc pixels): DROPPED
|
||||
Investigated and rejected: `raw_pixels` has ~64 access sites, and most `.clone()`s genuinely need
|
||||
an owned `Vec<u8>` (undo buffers, export, GPU readback) so `Arc<Vec<u8>>` would force `(*p).clone()`
|
||||
and still copy. The only beneficiary, the per-frame `renderer.rs:550` Vello clone, is on the
|
||||
**legacy/dead** path — the live HDR canvas renders raster as `RenderedLayerType::Raster` → GPU
|
||||
upload in `stage.rs` which passes a `&[u8]` slice and uploads only on cache-miss (no per-frame
|
||||
clone). Not worth 64 edits. Start at 3a.
|
||||
|
||||
### 3a. Lazy async fault-in + image proxy
|
||||
- **[DONE 3a-1]** Lazy load: full-decode removed; `raw_pixels` empty on load, `needs_fault_in`
|
||||
armed recursively; canvas records misses → App pages in via `RasterStore.load_pixels`.
|
||||
- **[DONE 3a-2]** Async: page-in runs on a background thread (deduped via `raster_loads_inflight`);
|
||||
results applied at top of `update()`. No UI block on cold scrub.
|
||||
- **[DONE 3a-3]** Image proxy: `MediaKind::RasterProxy` (≤192px PNG, derived id), written
|
||||
beside each resident full PNG on save + eager-decoded on load into `RasterKeyframe::proxy`.
|
||||
Separate `proxy_layer_cache` (own LRU, budget 64); the raster render blits the proxy mapped to
|
||||
the keyframe's FULL logical dims (upscales via sampler) when the full texture isn't resident.
|
||||
*(Proxies exist only after a save+reload; eager decode → lazy/paged is a refinement for huge
|
||||
paint projects.)*
|
||||
|
||||
- **`RasterStore`** (core): current `.beam` path + a read-only connection; `load_pixels(kf_id,w,h)`
|
||||
reads the `Raster` row and `decode_png`s it. Set/cleared by the editor on load + save-as.
|
||||
- **Save:** alongside the full PNG, write a low-res RGBA proxy per resident keyframe
|
||||
(`MediaKind::RasterProxy`, ≤~480px long edge, keyed by `kf.id`).
|
||||
- **Load:** stop eager full-decode; decode **proxies** eagerly (cheap → instant scrub everywhere);
|
||||
leave full `raw_pixels` empty.
|
||||
- **Fault-in pass** (editor, `&mut document` + store, each frame before render): for each raster
|
||||
layer ensure the active keyframe ±N is requested; load full PNGs on a **background thread pool**;
|
||||
on arrival, set `raw_pixels` + `texture_dirty`. Render uses full `raw_pixels` if resident, else the
|
||||
upscaled proxy. Reused by the exporter (already frame-by-frame).
|
||||
|
||||
### 3b. Residency window + eviction **[DONE]**
|
||||
- Added `#[serde(skip)] dirty: bool` (edited-since-persist; distinct from `texture_dirty`). Set on
|
||||
stroke/fill/paint-bucket/floating-lift commits + undo/redo; cleared on save (which re-arms the LRU).
|
||||
- Implemented as a fault-in-recency **LRU** (`RASTER_RESIDENT_MAX = 12`), not a strict ±N window:
|
||||
evict the oldest **clean** frame (drop `raw_pixels`, re-arm `needs_fault_in`); the shown frame is
|
||||
always most-recent so it's protected; **dirty frames never evicted**. Save preserves evicted frames'
|
||||
rows via `media_exists` (no data loss) and walks all layers to match load.
|
||||
*(Refinement deferred: count budget → byte budget for 4K resolution-robustness.)*
|
||||
|
||||
### 3c. Bound the GPU cache **[DONE for raster_layer_cache]**
|
||||
`raster_layer_cache` (`gpu_brush.rs`, `HashMap<Uuid,CanvasPair>`, Rgba16Float ping-pong
|
||||
≈ `w·h·16`/entry, was **unbounded**) → recency LRU (`RASTER_LAYER_CACHE_MAX = 12`) in
|
||||
`ensure_layer_texture`: bump-to-most-recent + evict oldest; shown frames protected. F3 overlay
|
||||
now shows tracked VRAM (raster cache MB + count). *(Refinements: count→byte budget; raise/headroom
|
||||
if >12 raster layers are visible at once. Export `raster_cache` lives one export — fine. Vello
|
||||
`ImageCache` is image *assets* → Phase 4.)*
|
||||
|
||||
### 3d. Undo memory **[DONE]**
|
||||
`RasterStrokeAction`/`RasterFillAction` stored `buffer_before`+`buffer_after` full frames.
|
||||
Now store a `RasterDiff` (`actions/raster_diff.rs`) — changed bbox before/after only, computed in
|
||||
`new()`, full buffers dropped. Undo/redo apply onto the keyframe's resident pixels; the editor
|
||||
faults the target frame in first (`Action::raster_resident_hint` + `peek_undo/redo_raster_hint`),
|
||||
correct because a clean evicted frame's container bytes == its logical state. Non-resident base ⇒
|
||||
skip (no corruption). Unit-tested round-trip. *(Refinement: compress full-canvas-fill diffs, whose
|
||||
bbox is the whole frame.)*
|
||||
|
||||
### 3e. Prefetch frames **[DONE for playback]**
|
||||
Implemented for playback: each update during playback, page in the next `PREFETCH_AHEAD=4`
|
||||
upcoming keyframes per raster layer (reusing the async worker + `raster_loads_inflight` dedup), so
|
||||
full frames are resident before the playhead arrives — fixes "proxy on every frame"/flicker during
|
||||
playback. *(Caveat: with many simultaneous raster layers the 12-frame resident budget may evict a
|
||||
prefetched frame before it's shown — raise budget or scale prefetch if that surfaces. Scrub-direction
|
||||
prefetch still TODO.)*
|
||||
|
||||
Original note: *(future, after 3d — pure latency win, no correctness need)*
|
||||
Fault-in is reactive (page in only on a render miss), so a never-visited frame still shows the
|
||||
proxy for a beat before the full lands. **Prefetch the full pixels for frames about to be shown**:
|
||||
on scrub/playback, dispatch background page-ins for the active keyframe ±N in the direction of
|
||||
playhead motion (and during playback, the next K keyframes), reusing the 3a-2 async worker +
|
||||
`raster_loads_inflight` dedup. Keep prefetched frames in the 3b LRU so they're still bounded; cap
|
||||
concurrent prefetch loads so scrubbing fast doesn't thrash the disk. Optional: also prewarm the GPU
|
||||
texture (3c cache) for the immediate next frame. Net effect: cold scrubbing/playback shows full-res
|
||||
frames with no proxy flicker. Proxy stays as the instant fallback when prefetch can't keep up.
|
||||
|
||||
### Build order & tests
|
||||
1. Arc drive-by — COW make_mut test. 2. 3a fault-in + store + proxy — load→empty-until-faulted,
|
||||
PNG round-trip, proxy-then-swap. 3. 3b window/evict/dirty — residency ≤ window while scrubbing,
|
||||
dirty never evicted. 4. 3c GPU bound. 5. 3d undo diffs reproduce pre-stroke buffer exactly.
|
||||
|
||||
---
|
||||
|
||||
## 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
|
||||
it resident. The heavy, evictable thing is the **image assets** referenced by fills.
|
||||
|
||||
**Data model.**
|
||||
- `ImageAsset` (`clip.rs:250`): `path: PathBuf` + `data: Option<Vec<u8>>` (whole compressed
|
||||
file bytes) + dims. Imported fully into `data` at `main.rs:3936`.
|
||||
- All assets resident in `Document.image_assets: HashMap<Uuid, ImageAsset>` (`document.rs:206`).
|
||||
- Decoded form in `ImageCache` (`renderer.rs:25`): `HashMap<Uuid, Arc<ImageBrush>>` + CPU
|
||||
`Pixmap` map, keyed by asset id, **unbounded**.
|
||||
- A `Fill` references an asset by `image_fill: Option<Uuid>` (`vector_graph/mod.rs:110`).
|
||||
Same UUID may appear in many fills/keyframes/layers and recursively through clip instances.
|
||||
**No asset→frame or frame→asset index exists today.**
|
||||
|
||||
**Two evictable tiers:** Tier 1 = compressed bytes (`ImageAsset.data`, droppable, reload
|
||||
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
|
||||
clip instances** with the outer→inner local-time mapping. This is "needed now". Scanning
|
||||
upcoming keyframes (and upcoming nested-clip keyframes) gives "needed soon" for prefetch.
|
||||
|
||||
### 4b. Usage bookkeeping (the multi-frame problem)
|
||||
Maintain a reverse index `asset_id → usage count` (fills referencing it across the whole
|
||||
document), updated incrementally as edits add/remove `image_fill`s (hook the fill-mutation
|
||||
paths in `vector_graph` and the relevant actions).
|
||||
- count 0 → dead, fully evictable / GC candidate.
|
||||
- count > 0 → keep metadata; residency of `data`/decoded pixels driven by **proximity to
|
||||
playhead**, not by count (a high-count asset far from the playhead is still evicted).
|
||||
|
||||
Residency decision: `resident = needed-now ∪ needed-soon`; beyond that, an **LRU with a byte
|
||||
budget** for referenced-but-distant assets (covers scrubbing back without a reload).
|
||||
Eviction never touches an asset in needed-now.
|
||||
|
||||
### 4c. Bound the decoded tier
|
||||
Convert `ImageCache`'s two maps to LRU/byte-budgeted (`renderer.rs:25`) and bound the GPU
|
||||
image-texture cache the same way, keyed to the residency window.
|
||||
|
||||
### Nested-clip prefetch (important)
|
||||
A clip instance placed on an outer frame has its **own internal timeline of keyframes**,
|
||||
each of which can reference its own image assets. Prefetch must therefore:
|
||||
- Recurse through clip instances when computing both needed-now and needed-soon.
|
||||
- Map outer playhead time → each nested clip's local time, and look ahead along the
|
||||
**nested** timeline (not just the outer one) so assets used by an upcoming *inner*
|
||||
keyframe are loaded before the nested clip reaches it.
|
||||
- Deduplicate across the whole recursion (an asset shared by outer and inner frames counts
|
||||
once); the usage index handles refcounting.
|
||||
|
||||
---
|
||||
|
||||
## Cross-cutting: a shared residency abstraction
|
||||
|
||||
A generic **`PagedStore<Id, Payload>`** with three consumers — always-resident metadata,
|
||||
disk backing, residency = window/needed-set around playhead + LRU byte budget:
|
||||
|
||||
| Consumer | Metadata kept | Paged payload | Backing | "Needed now" key |
|
||||
|---|---|---|---|---|
|
||||
| Raster keyframes (Ph 3) | id, dims, time | `raw_pixels` + GPU texture | SQLite blob row (`UPDATE` on write-back) | active keyframe per layer |
|
||||
| Image assets (Ph 4) | id, dims, storage | `data` bytes + decoded pixels/texture | SQLite blob row or external path | fills' `image_fill` set at time (recursive) |
|
||||
| Video frames (Ph 2a) | — | RGBA frame | source via ffmpeg seek | requested timestamps |
|
||||
|
||||
Audio stays separate (real-time ring buffer, different constraints). The frame→asset
|
||||
enumeration + usage index is unique to Phase 4.
|
||||
|
||||
---
|
||||
|
||||
## Sequencing
|
||||
1. **Phase 1a** — done; independent of the container, works with the current ZIP loader.
|
||||
2. **Phase 2** — small, isolated, independently shippable; container-independent.
|
||||
3. **Phase 0 (container)** — `.beam` ZIP → SQLite + `BlobReader` + large-media policy +
|
||||
legacy-ZIP migration. Prerequisite for 1b/1c/3/4.
|
||||
4. **Phase 1b** — streaming pool loader + bulk read-ahead activation (on the SQLite store).
|
||||
5. **Phase 1c** — depends on 1b's pool path.
|
||||
6. **Phase 3** — the substantial build; implement `PagedStore` over blob rows.
|
||||
7. **Phase 4** — thin layer on the same abstraction + the frame→asset/usage index.
|
||||
|
||||
Phase 1a and Phase 2 can ship now; everything else waits on Phase 0 (the container).
|
||||
|
||||
---
|
||||
|
||||
## Status
|
||||
- [~] Phase 1a — activate compressed-audio disk reader ← **in progress**
|
||||
- [x] Wire `ActivateFile` + assign `clip.read_ahead` on `AddAudioClip` for compressed
|
||||
pool files (`engine.rs:909`). Per-clip reader keyed by `clip_id`; matches the
|
||||
existing `DeactivateFile` convention in `RemoveAudioClip`. Compiles clean.
|
||||
- [ ] Stop `decode_progressive` (`io/audio_file.rs:344`) from accumulating/streaming the
|
||||
full PCM; emit only the downsampled waveform overview. (Crosses into the UI
|
||||
waveform pipeline — `AudioDecodeProgress` consumer — so handled as its own step.)
|
||||
- [ ] Runtime verification: confirm a compressed clip actually plays from the ring
|
||||
buffer (was effectively silent before, since `read_ahead` was always `None`).
|
||||
- [~] **Phase 0 — container migration `.beam` ZIP → SQLite** ← **in progress**
|
||||
- [x] SQLite schema (`media`, `media_chunk`, `project_json`, `meta`) + `rusqlite` dep
|
||||
(bundled) — `lightningbeam-core/src/beam_archive.rs`
|
||||
- [x] `BlobReader` (`Read + Seek` over `media_chunk`, owns its own read-only connection,
|
||||
opens a blob handle per read with rowids resolved once) — for `CompressedReader` /
|
||||
video decoder in 1b. 5 integration tests pass (`tests/beam_archive.rs`): json
|
||||
round-trip, packed full read, streaming reads + seeks across chunk boundaries,
|
||||
referenced-path, overwrite-replaces-chunks.
|
||||
- [x] Packed (chunked) + referenced media write/read API; `is_sqlite()` format detection;
|
||||
`MediaKind`/`MediaStorage`/`MediaMeta`/`MediaInfo`.
|
||||
- [x] `BeamArchive::transaction()` / `BeamTxn` — in-place transactional save (only
|
||||
changed rows written; unchanged large media never rewritten); orphan cleanup via
|
||||
`retain_media`. 7 archive tests pass (added txn-grouping + rollback). Per user: save
|
||||
must NOT copy+rename for existing SQLite files.
|
||||
- [x] Wire `save_beam` to `BeamArchive` — in-place txn for existing SQLite, temp+rename
|
||||
only for new/migrated files. Audio → packed (or referenced ≥2GB) `media` rows;
|
||||
raster → PNG `media` rows keyed by keyframe id. FLAC→WAV→base64 save round-trip
|
||||
deleted (now packs original bytes with their codec).
|
||||
- [x] Wire `load_beam` — format dispatch: SQLite (`load_beam_sqlite`) vs legacy ZIP
|
||||
(`load_beam_zip_legacy`, kept verbatim). SQLite load reconstitutes packed audio into
|
||||
`embedded_data` so the existing pool loader is unchanged (streaming = Phase 1b).
|
||||
- [x] Legacy ZIP `.beam` → SQLite migration: `is_sqlite()` routes load; saving a
|
||||
ZIP-loaded project writes SQLite (migrates on save). Editor compiles end-to-end.
|
||||
- [x] Large-media policy: packed (chunked) vs referenced — `LargeMediaMode {Ask,Pack,
|
||||
Reference}`; save honors it for files ≥`LARGE_MEDIA_THRESHOLD`. Packing streams from
|
||||
disk via `put_media_packed_from_path` (chunk-by-chunk, never loads the whole file).
|
||||
`Ask` behaves as `Reference` at save time.
|
||||
- [x] `large_media_default` user preference: persisted in `AppConfig`, editable in
|
||||
Preferences → Advanced (incl. resetting to `Ask` to re-trigger the prompt).
|
||||
- [x] First-import-over-threshold prompt: `note_possible_large_media` (hooked into
|
||||
import_audio/video/image) queues a one-time modal; choice persists to config.
|
||||
Threshold shown in the modal is derived from the constant.
|
||||
- [ ] Runtime verification: save a real project, reopen it, confirm audio + raster survive
|
||||
round-trip; confirm an old ZIP `.beam` still opens and migrates on save.
|
||||
- [ ] (Optimization, later) FLAC-compress packed PCM/WAV audio; raster disk-dirty flag to
|
||||
skip unchanged frames on in-place save (Phase 3).
|
||||
|
||||
> Note: the crate's internal `#[cfg(test)]` modules (`clip.rs`, `effect_layer.rs`) have
|
||||
> pre-existing compile breakage (old `Beats`/`TempoMap` API) unrelated to this work; it
|
||||
> blocks `cargo test --lib`, so `beam_archive` tests live in `tests/` (integration) which
|
||||
> build the lib in normal mode. Worth fixing separately.
|
||||
- [x] Phase 1b — stream on project load (PACKED audio path complete & user-verified: streams on load,
|
||||
waveform generates + persists, sample-accurate seeking). Referenced-path streaming + MP3 seek index
|
||||
+ proper video-audio reload remain as noted follow-ups.
|
||||
- **Decision (user):** cross-crate packed streaming via an **inversion-of-control factory** —
|
||||
daw-backend defines the interface, core implements it over `BlobReader`. Keeps the audio
|
||||
engine container-agnostic. (Alternatives rejected: daw-backend owning rusqlite = layering
|
||||
violation; referenced-only-first = leaves packed <2GB in RAM.)
|
||||
- **Current load reality (why this is needed):** *nothing* streams on load today — every entry
|
||||
is fully decoded to a PCM `Vec<f32>`. Packed audio is base64-reconstituted into `embedded_data`
|
||||
(`load_beam_sqlite`) → written to a temp file → `load_file_into_pool` full-decodes; referenced
|
||||
audio also full-decodes via `load_file_into_pool`; and the Phase 1a/1c disk-reader activation
|
||||
never fires for loaded clips (they bypass `AddAudioClip`).
|
||||
- [x] **B1/B2 foundation (DONE, headless-tested):** in `disk_reader.rs` — `trait MediaByteSource:
|
||||
Read+Seek+Send+Sync { byte_len }` + `trait AudioBlobSourceFactory: Send+Sync { open(media_id)
|
||||
-> Box<dyn MediaByteSource> }`; `SymphoniaByteSource` adapter (impl `MediaSource`,
|
||||
is_seekable/byte_len); `CompressedReader::open_source(src, ext)` sharing probe via a
|
||||
refactored `from_mss`; `enum StreamOpen { Path, Source{src,ext} }`; `StreamSource::open` and
|
||||
`DiskReaderCommand::ActivateFile` now take `StreamOpen` (engine site wraps `Path`); re-exported
|
||||
`AudioBlobSourceFactory`/`MediaByteSource` at `daw_backend::audio`. Test
|
||||
`tests/compressed_source_stream.rs` decodes an in-memory WAV through a `Cursor`-backed
|
||||
`MediaByteSource` (proves probe+decode+seek over a byte stream). daw-backend compiles clean.
|
||||
- [x] **B3 (engine, DONE):** `Engine.blob_source_factory: Option<Arc<dyn AudioBlobSourceFactory>>` +
|
||||
`EngineController::set_blob_source_factory` (via `Query::SetBlobSourceFactory`, ordered before
|
||||
`SetProject` on the same queue). `AudioFile.packed_media_id: Option<String>` (Some ⇒ open via
|
||||
factory using `original_format` as the ext hint; None ⇒ `StreamOpen::Path`). Activation factored
|
||||
into `Engine::activate_streaming_for(reader_id, pool_index)`, used by `AddAudioClip` and bulk.
|
||||
- [x] **C (core factory, DONE):** `file_io::blob_source_factory(beam_path)` → `BeamBlobFactory`
|
||||
implementing `AudioBlobSourceFactory` over `BeamArchive::open_blob_reader`. `BlobReader` holds a
|
||||
`!Sync` rusqlite `Connection`, so it's wrapped in `SyncBlobReader` (a `Mutex` used via `get_mut`
|
||||
on the hot path — no runtime locking) to satisfy Symphonia's `MediaSource: Send + Sync`. Installed
|
||||
by the editor between `load_audio_pool` and `set_project`.
|
||||
- [x] **D (load-path, DONE — packed audio):** `load_beam_sqlite` now streams packed audio whose codec
|
||||
is recognized (`is_streamable_audio_codec`) — leaves `embedded_data` empty so the pool builds a
|
||||
Compressed placeholder with `packed_media_id`; no base64, no temp file, no decode. `serialize`
|
||||
round-trips packed entries by media id (so in-place re-save keeps the row). Non-audio codecs
|
||||
(video-container audio tracks) keep the legacy reconstitution path → **no regression**.
|
||||
- [x] **E (bulk activation, DONE):** `SetProject` calls `Engine::activate_all_streaming_clips` —
|
||||
walks every loaded audio clip and `activate_streaming_for` (create_buffer + `ActivateFile` + set
|
||||
`read_ahead`), the loaded-clip equivalent of the Phase 1a wiring.
|
||||
- [x] **Waveform-on-load for streamed audio (DONE):** streaming broke the old waveform path (it came
|
||||
from the full in-RAM decode, which no longer happens). Added
|
||||
`disk_reader::build_waveform_pyramid_from_source(Box<dyn MediaByteSource>, ext, B)` (load-time
|
||||
counterpart of the path-based builder). On load, the editor background-generates a pyramid for any
|
||||
streamed entry lacking a persisted one (opens the packed blob via a local factory), sending the
|
||||
floor through the same `waveform_result` channel `update()` drains; the next save persists it.
|
||||
Verified in-app: packed MP3 **streams + plays** (`Activated reader=0, kind=CompressedAudio`); the
|
||||
overview now fills in shortly after load.
|
||||
- **Headless tests pass** (compressed_source_stream, video_audio_stream, waveform_pyramid); all three
|
||||
crates compile clean. **Needs in-app verification:** the waveform appears after load (background gen),
|
||||
then instantly on subsequent loads once saved; RAM stays flat on a big project.
|
||||
- [x] **Seek alignment fix (DONE):** streamed compressed audio was ~1.2s off *after seeking*
|
||||
(fine from the start). `CompressedReader::seek` used `SeekMode::Coarse`, which for MP3
|
||||
byte-estimates the position and seeds the timestamp from that estimate — wrong for VBR / files
|
||||
whose header padding the estimate ignores, so `actual_ts` (and thus the buffer's frame labels)
|
||||
landed ~1.2s early. Switched to `SeekMode::Accurate`: Symphonia counts frame *headers* (no
|
||||
decode) from a true anchor (current pos, or rewind-to-0 for backward seeks) → exact `actual_ts`;
|
||||
the existing sub-frame `pending_discard` finishes the job. FLAC/OGG seek cheaply (seek tables);
|
||||
a long MP3 backward seek walks headers from 0 (I/O, not decode). Tests still green.
|
||||
- [ ] **Deferred (follow-up):** per-file **seek index** for elementary streams (MP3) — a one-time
|
||||
header scan (ts↔byte map) to make far seeks O(1) instead of an Accurate header-walk from the
|
||||
anchor. Matters for multi-hour MP3s; song-length files are fine as-is.
|
||||
- [x] **Proper video-audio reload (DONE):** a video's audio is now stored as a **path reference** to
|
||||
the video (never packed/embedded as audio media) and **re-probed via FFmpeg** on load into a
|
||||
streaming `VideoAudio` entry — `AudioPoolEntry.is_video_audio` flag drives both `serialize`
|
||||
(reference, not pack), `save_beam` (`reference_it |= is_video_audio`), and `load_from_serialized`
|
||||
(`VideoAudioReader::open` → `from_video_audio`). Fixes 5.1 audio losing its channels on reload
|
||||
(the old Symphonia reconstitution collapsed it); also no more decode-whole-video-to-RAM / temp
|
||||
files on load. Old saves (video mis-packed as audio) self-heal on the next save.
|
||||
- [ ] **Deferred (follow-up):** stream *referenced* (external-path) **audio** on load too — replace
|
||||
`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.
|
||||
- [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
|
||||
small temp partitions) and the temp path doesn't survive reload.
|
||||
- [~] **Proper design** (see "Phase 1c" body): stream the video's audio on demand via a new
|
||||
ffmpeg `VideoAudioReader` in the disk reader — no extraction, no `/tmp`, no RAM; path
|
||||
reference survives save/load.
|
||||
- [x] **Step 1 (DONE):** `VideoAudioReader` (ffmpeg) + `StreamSource` enum + `SourceKind`
|
||||
in `disk_reader.rs`. Sample-accurate seek (coarse seek + decode-discard to exact
|
||||
frame via PTS). 2 integration tests pass (`daw-backend/tests/video_audio_stream.rs`):
|
||||
in-order decode + sample-exact seek at several targets. (Found: mono frames have an
|
||||
empty channel layout → must `set_channel_layout` before resampling, else swr returns
|
||||
AVERROR_INPUT_CHANGED.) Lib compiles clean; `StreamSource` `#[allow(dead_code)]`
|
||||
until wired. `VideoAudioReader` made `pub` for the integration test.
|
||||
- [x] **Step 2 (DONE):** `AudioStorage::VideoAudio { decoded_for_waveform, decoded_frames,
|
||||
total_frames }` + `AudioFile::from_video_audio` (path = the video file). `data()`
|
||||
empty / `read_samples()` 0 (streamed). `Query::AddVideoAudioSync` +
|
||||
`do_add_video_audio` (probes via `VideoAudioReader::open`, no decode) +
|
||||
`EngineController::add_video_audio_sync`. `GetPoolAudioSamples` surfaces VideoAudio's
|
||||
waveform overview too. daw-backend compiles clean; probe `total_frames` test passes.
|
||||
- [x] **Step 3 (DONE):** reader thread now holds `StreamSource` (opens via
|
||||
`StreamSource::open(path, kind)`, dispatches `sample_rate()/channels()/seek/decode_next`);
|
||||
`ActivateFile` carries `kind: SourceKind`; `#[allow(dead_code)]` removed. `AddAudioClip`
|
||||
activation maps `Compressed`→`CompressedAudio`, `VideoAudio`→`VideoAudio`, creates the
|
||||
read-ahead buffer + `ActivateFile{kind}` + sets `clip.read_ahead`. Compressed path is
|
||||
behaviorally identical (StreamSource::Compressed wraps the same CompressedReader).
|
||||
daw-backend + editor compile clean; VideoAudioReader tests still pass.
|
||||
⚠️ Not runtime-verified — needs in-app check that compressed audio still plays (no
|
||||
regression) and that an activated VideoAudio clip produces sound.
|
||||
- [x] **Step 4 (DONE):** `import_video` now calls `add_video_audio_sync(video_path)` →
|
||||
pool index, fetches channels/sample_rate via `get_pool_file_info`, makes the
|
||||
`AudioClip` with the video's duration. **No WAV / /tmp / RAM.** Removed the stopgap
|
||||
(`extract_audio_from_video_to_wav` + WAV helpers + `ExtractedAudioInfo`), dead
|
||||
`add_audio_file_sync` (+ `Query::AddAudioFileSync` / `QueryResponse::AudioFileAddedSync`
|
||||
/ handler), and the now-unreachable `AudioExtractionResult::NoAudio`. Kept
|
||||
`import_audio_sync` (still used by normal audio import). daw-backend + editor clean.
|
||||
**→ Feature is live end-to-end; ready for in-app testing.**
|
||||
- [x] **Step 5 (DONE):** `CompressedReader` now seeks sample-accurately too — coarse
|
||||
symphonia seek + decode-discard (`pending_discard` set from `seeked.actual_ts` in
|
||||
`seek`, applied in `decode_next`, which continues rather than reporting EOF when a
|
||||
whole packet is discarded). So compressed clips no longer drift vs video audio after
|
||||
a seek. Test `compressed_reader_seek_is_sample_accurate` passes (the WAV coarse seek
|
||||
lands pre-target, exercising the discard). `CompressedReader` made `pub` for the test.
|
||||
- [~] Step 6: **bounded waveform overview** — replaces today's full-resolution
|
||||
`raw_audio_cache`/GPU waveform (which doesn't scale: it stores every sample at mip 0,
|
||||
so a long file is multi-GB on GPU + RAM — the same memory issue, and the Phase 1a
|
||||
`decode_progressive` leftover). Design below. Slices: (1a) streaming pyramid builder
|
||||
+ (1b) persistence + (1c) min/max GPU upload, then (2) LRU tile cache + re-decode floor.
|
||||
- [x] **Slice 1a (DONE):** `daw-backend/src/audio/waveform_pyramid.rs` —
|
||||
`WaveformPyramidBuilder` streams interleaved samples, accumulates the floor, and
|
||||
reduces `BRANCH(4):1` at `finish` into a root-first pyramid (convention B:
|
||||
`levels[0]`=root envelope, `levels.last()`=floor, `.root()`/`.floor()` accessors).
|
||||
Ragged last buckets reduce over available children (no value padding). Bounded
|
||||
(~22 MB/2 h @ B=256). 7 integration tests pass (`tests/waveform_pyramid.rs`):
|
||||
bucket min/max, partial flush, multi-level envelope == global min/max, root-first
|
||||
ordering, stereo channels, size bound, chunk-agnostic.
|
||||
- [~] **Slice 1b (data layer DONE; orchestration folded into 1c):**
|
||||
- [x] Generation bridge `disk_reader::build_waveform_pyramid(path, kind, B)` — streams
|
||||
a decode (`StreamSource` over symphonia/ffmpeg) into the builder; bounded
|
||||
memory (one chunk + the pyramid). Test: envelope matches the signal through
|
||||
both backends.
|
||||
- [x] Serialization `WaveformPyramid::to_bytes`/`from_bytes` (LBWF blob; f32 texels —
|
||||
f16 a later size optimization). Round-trip test + rejects truncated/garbage.
|
||||
- [x] `MediaKind::Waveform` in the SQLite container (keyed by the audio item's id).
|
||||
- [ ] Orchestration (with 1c).
|
||||
- [~] **Slice 1c (in-memory floor overview DONE; persistence next):**
|
||||
- [x] `waveform_gpu`: `PendingUpload.minmax` flag + `pack_texel` helper; `upload_audio`
|
||||
threads `minmax` (frame_stride 4, packs `(Lmin,Lmax,Rmin,Rmax)` directly).
|
||||
The texture is already Rgba16Float and the GPU mipgen builds zoom-out levels, so
|
||||
only the texel-packing differs. Render the floor at **effective rate `sr/B`** (so
|
||||
time→texel maps B samples/texel) and `total_frames = floor_texel_count`.
|
||||
- [x] `AppConfig.waveform_floor_samples_per_texel` (default 256, user-configurable).
|
||||
- [x] App: `waveform_minmax_pools: HashMap<usize, u32>` (pool → `B`, carries the floor rate
|
||||
with full float precision) + a `(pool, packed_floor, sr, channels, B)` results channel;
|
||||
drained in `update()` → `raw_audio_cache.insert(floor)` + flag pool + `waveform_gpu_dirty`.
|
||||
- [x] Generation: on video-audio import Success, the same bg thread streams
|
||||
`disk_reader::build_waveform_pyramid(path, VideoAudio, B)` once and sends the packed
|
||||
`floor()`. (Video-audio has no in-RAM samples, so this is what makes its waveform appear.)
|
||||
- [x] Threaded `waveform_minmax_pools` through the pane-context (`panes/mod.rs` +
|
||||
main.rs construction) → `render_layers` → **both** render sites (collapsed-group
|
||||
~timeline.rs:3048 AND expanded-track ~3613): compute `total_frames = len/4`,
|
||||
`eff_sr = sr/B`, set `minmax`. Compiles clean (editor `cargo check` = 0 errors).
|
||||
- [x] Shader fix: `waveform.wgsl` now reads the **nearest integer LOD via `textureLoad`**
|
||||
instead of sampling a fractional mip. Trilinear blends two levels whose row-major
|
||||
linearizations differ → horizontal shift that flips each 0.5 of `mip_f` (= each 2x
|
||||
zoom step), the "every other zoom level is offset" artifact. **User-confirmed fixed:**
|
||||
features hold position at every zoom and line up with playback.
|
||||
See memory `waveform-shader-fractional-mip-offset`.
|
||||
- [x] **Persistence (done):** the full pyramid is serialized (`to_bytes`) on generation and
|
||||
kept in `App.waveform_pyramid_blobs`. `save_beam` writes it as a `MediaKind::Waveform`
|
||||
row keyed by a **deterministic id derived from the pool index** (`file_io::waveform_media_id`,
|
||||
"LBWF" sentinel in the high 32 bits) — independent of how the audio bytes are stored, so
|
||||
it works for packed/referenced/video-audio alike, and an in-place re-save reuses the row.
|
||||
Carried in/out via a transient `#[serde(skip)] AudioPoolEntry.waveform_blob` and a
|
||||
`waveform_blobs` field on `FileCommand::Save`. `load_beam_sqlite` reads the row back;
|
||||
the editor restores `raw_audio_cache`/`waveform_minmax_pools`/`waveform_pyramid_blobs`
|
||||
+ flags `waveform_gpu_dirty` after the backend loads the pool (using each entry's
|
||||
`sample_rate` for `eff_sr`, the stored `B` for the rate). No re-decode on load.
|
||||
`register_loaded_videos` only loads frames (not audio), so there is no redundant
|
||||
regeneration to suppress. Compiles clean across all three crates.
|
||||
|
||||
### Waveform LOD pyramid design (step 6)
|
||||
A min/max LOD pyramid (tree of zoom-level textures): fully zoomed out → envelope; fully zoomed
|
||||
in → per-sample; seamless between.
|
||||
|
||||
- **One streaming decode pass** builds the whole pyramid down to a configurable **floor**
|
||||
`B` samples/texel (default 256), via a hierarchical reduction (each sample updates a running
|
||||
per-level min/max accumulator; a filled bucket emits a texel and folds into its parent —
|
||||
`branch` 4:1). Bounded memory: holds only the pyramid (~`N/B·4/3` texels ≈ **~14 MB / 2 h
|
||||
stereo @ B=256**), never the full samples. Full-res (B=1 ≈ 2.7 GB) is the only level NOT
|
||||
stored.
|
||||
- **Persist the pyramid** in the `.beam` SQLite container (a `waveform` media kind; session
|
||||
temp before first save). `B` is stored with it (preference is just the default for new gen).
|
||||
Persistence is load-bearing: it makes mid-zoom a cheap **disk read**, not a re-decode.
|
||||
- **Runtime = LRU tile cache** (GPU textures) loaded from the persisted pyramid on demand.
|
||||
Eviction is **ancestor-closed**: only evict an LRU node with no resident children ("a node is
|
||||
cleared only after its children") — so rendering can always walk up to a resident ancestor;
|
||||
detail sharpens in, never blanks. Root is tiny/hot → effectively pinned for free.
|
||||
- **Re-decode only below the floor** (texel < `B` samples): by then the visible window spans a
|
||||
tiny time range, so decoding it (via the sample-accurate seekable readers from steps 1–5 —
|
||||
the payoff) for true per-sample detail is cheap. This removes the large-span re-decode gap:
|
||||
above the floor it's a disk read; below it the span is already small.
|
||||
- **Why a deep floor (not a coarse cutoff):** a coarse-only pinned set would force the first
|
||||
on-demand level to re-reduce a huge time span per tile. Persisting deep makes every level a
|
||||
disk read; `B` is a size-vs-crossover knob (smaller B = bigger pyramid, cheaper re-decode).
|
||||
- `waveform_gpu` needs a **min/max texel upload** (`Lmin,Lmax,Rmin,Rmax` per texel) instead of
|
||||
min=max-per-sample; the existing compute mipgen still builds the mip chain *within* a tile.
|
||||
|
||||
**Decisions (locked):** branch 4:1; floor `B≈256` samples/texel, **user-configurable**
|
||||
(`AppConfig.waveform_floor_samples_per_texel`, stored per-pyramid); 8192-wide tiles; LRU ~4
|
||||
viewports of fine tiles; persist pyramid in `.beam`.
|
||||
- [x] Video decoder concurrency (movie-length lag/freeze): keyframe-index scan now runs
|
||||
holding no VideoManager/decoder lock (brief locks only bracket it) → no more multi-second
|
||||
UI freeze on import/load; thumbnail generation uses a **dedicated** decoder and samples
|
||||
at keyframes (≈1 frame each vs whole-GOP) → no playback contention. Removed dead
|
||||
`VideoManager::build_keyframe_index`, `build_and_set_keyframe_index`, `downsample_rgba*`.
|
||||
- [x] Phase 2a — bound video frame cache. `VideoManager.frame_cache` (was an unbounded
|
||||
`HashMap<(Uuid,i64), Arc<VideoFrame>>` that grew per distinct frame during playback) is now an
|
||||
`LruCache` evicted by a **byte budget** (`FRAME_CACHE_BYTE_BUDGET` = 256 MB) rather than a frame
|
||||
count — robust across resolutions (a 4K frame is ~33 MB vs ~2 MB at 800×600). Byte total tracked
|
||||
on insert/evict/remove; `unload_video` pops per-clip keys (LruCache has no `retain`). Decoder-level
|
||||
cache was already LRU. Editor compiles clean. *(Not yet runtime-verified.)*
|
||||
- [x] Phase 2b — stream export mux. `export/mod.rs::mux_video_and_audio` no longer collects every
|
||||
packet into two `Vec`s before interleaving; it stream-merges the two inputs by PTS with one pending
|
||||
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.)*
|
||||
- [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,
|
||||
effect_layer.rs); fixed stale test setup (register a vector clip so `get_clip_duration` resolves)
|
||||
and a stale default expectation (shape `fill_color` defaults `None`). Surfaced + fixed one **real
|
||||
undo bug**: `DeleteFolderAction(MoveToParent)` reparented child subfolders but never restored them
|
||||
on rollback (orphaned them) — now tracked and restored. Production code otherwise untouched.
|
||||
@@ -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
|
||||
+13
-13
@@ -1,34 +1,34 @@
|
||||
#!/bin/bash
|
||||
|
||||
# Ensure the script stops on error
|
||||
set -e
|
||||
|
||||
# Check if a version argument was passed
|
||||
if [ -z "$1" ]; then
|
||||
echo "Usage: ./create-release.sh <version>"
|
||||
echo "Usage: ./create_release.sh <version>"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
VERSION=$1
|
||||
RELEASE_BRANCH="release"
|
||||
MAIN_BRANCH="main"
|
||||
CONFIG_FILE="src-tauri/tauri.conf.json"
|
||||
MAIN_BRANCH=$(git rev-parse --abbrev-ref HEAD)
|
||||
CARGO_TOML="lightningbeam-ui/lightningbeam-editor/Cargo.toml"
|
||||
|
||||
echo "Updating version to $VERSION in $CONFIG_FILE..."
|
||||
jq --arg version "$VERSION" '.version = $version' $CONFIG_FILE > tmp.json && mv tmp.json $CONFIG_FILE
|
||||
echo "Updating version to $VERSION in $CARGO_TOML..."
|
||||
sed -i "0,/^version = .*/s/^version = .*/version = \"$VERSION\"/" "$CARGO_TOML"
|
||||
|
||||
echo "Committing to main..."
|
||||
git add $CONFIG_FILE
|
||||
git commit -m "Bump version to $VERSION"
|
||||
echo "Committing to $MAIN_BRANCH..."
|
||||
git add "$CARGO_TOML" Changelog.md
|
||||
git diff --cached --quiet || git commit -m "Bump version to $VERSION"
|
||||
|
||||
echo "Checking out the release branch..."
|
||||
git checkout $RELEASE_BRANCH
|
||||
|
||||
echo "Merging the main branch into $RELEASE_BRANCH..."
|
||||
echo "Merging $MAIN_BRANCH into $RELEASE_BRANCH..."
|
||||
git merge $MAIN_BRANCH --no-ff -m "Release $VERSION"
|
||||
|
||||
echo "Pushing changes to the release branch..."
|
||||
git push origin $RELEASE_BRANCH
|
||||
echo "Pushing $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
|
||||
|
||||
|
||||
Generated
+366
-1
@@ -2,6 +2,23 @@
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "adler2"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||
|
||||
[[package]]
|
||||
name = "aes"
|
||||
version = "0.8.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cipher",
|
||||
"cpufeatures",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "aho-corasick"
|
||||
version = "1.1.3"
|
||||
@@ -69,6 +86,12 @@ version = "0.22.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
||||
|
||||
[[package]]
|
||||
name = "base64ct"
|
||||
version = "1.8.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||
|
||||
[[package]]
|
||||
name = "beamdsp"
|
||||
version = "0.1.0"
|
||||
@@ -106,6 +129,15 @@ version = "2.9.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2261d10cca569e4643e526d8dc2e62e433cc8aba21ab764233731f8d369bf394"
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block2"
|
||||
version = "0.6.2"
|
||||
@@ -127,12 +159,38 @@ version = "1.24.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbdf580320f38b612e485521afda1ee26d10cc9884efaaa750d383e13e3c5f4"
|
||||
|
||||
[[package]]
|
||||
name = "byteorder"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
||||
|
||||
[[package]]
|
||||
name = "bytes"
|
||||
version = "1.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a"
|
||||
|
||||
[[package]]
|
||||
name = "bzip2"
|
||||
version = "0.4.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "bdb116a6ef3f6c3698828873ad02c3014b3c85cadb88496095628e3ef1e347f8"
|
||||
dependencies = [
|
||||
"bzip2-sys",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "bzip2-sys"
|
||||
version = "0.1.13+1.0.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cassowary"
|
||||
version = "0.3.0"
|
||||
@@ -155,6 +213,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ac9fe6cdbb24b6ade63616c0a0688e45bb56732262c158df3c0c4bea4ca47cb7"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"jobserver",
|
||||
"libc",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
@@ -179,6 +239,16 @@ version = "1.0.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
||||
|
||||
[[package]]
|
||||
name = "cipher"
|
||||
version = "0.4.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"
|
||||
dependencies = [
|
||||
"crypto-common",
|
||||
"inout",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "clang-sys"
|
||||
version = "1.8.1"
|
||||
@@ -222,6 +292,12 @@ dependencies = [
|
||||
"static_assertions",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "constant_time_eq"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "245097e9a4535ee1e3e3931fcfcd55a796a44c643e8596ff6566d68f09b87bbc"
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation"
|
||||
version = "0.9.4"
|
||||
@@ -302,6 +378,24 @@ dependencies = [
|
||||
"windows 0.62.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cpufeatures"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
||||
dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crc32fast"
|
||||
version = "1.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-deque"
|
||||
version = "0.8.6"
|
||||
@@ -352,6 +446,16 @@ dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crypto-common"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
"typenum",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "dasp_envelope"
|
||||
version = "0.11.0"
|
||||
@@ -497,6 +601,27 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"symphonia",
|
||||
"zip",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
|
||||
dependencies = [
|
||||
"powerfmt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||
dependencies = [
|
||||
"block-buffer",
|
||||
"crypto-common",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -579,12 +704,32 @@ version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
|
||||
|
||||
[[package]]
|
||||
name = "flate2"
|
||||
version = "1.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c"
|
||||
dependencies = [
|
||||
"crc32fast",
|
||||
"miniz_oxide",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "foldhash"
|
||||
version = "0.1.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||
dependencies = [
|
||||
"typenum",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.2.16"
|
||||
@@ -596,6 +741,18 @@ dependencies = [
|
||||
"wasi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.3.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"r-efi",
|
||||
"wasip2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "glob"
|
||||
version = "0.3.3"
|
||||
@@ -637,6 +794,15 @@ version = "0.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "fc0fef456e4baa96da950455cd02c081ca953b141298e41db3fc7e36b1da849c"
|
||||
|
||||
[[package]]
|
||||
name = "hmac"
|
||||
version = "0.12.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
||||
dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "hound"
|
||||
version = "3.5.1"
|
||||
@@ -663,6 +829,15 @@ dependencies = [
|
||||
"hashbrown 0.16.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "inout"
|
||||
version = "0.1.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01"
|
||||
dependencies = [
|
||||
"generic-array",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "itertools"
|
||||
version = "0.12.1"
|
||||
@@ -709,6 +884,16 @@ version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130"
|
||||
|
||||
[[package]]
|
||||
name = "jobserver"
|
||||
version = "0.1.34"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"
|
||||
dependencies = [
|
||||
"getrandom 0.3.4",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "js-sys"
|
||||
version = "0.3.81"
|
||||
@@ -820,6 +1005,16 @@ version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
|
||||
|
||||
[[package]]
|
||||
name = "miniz_oxide"
|
||||
version = "0.8.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
|
||||
dependencies = [
|
||||
"adler2",
|
||||
"simd-adler32",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "mio"
|
||||
version = "0.8.11"
|
||||
@@ -889,6 +1084,12 @@ dependencies = [
|
||||
"minimal-lexical",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "cf97ec579c3c42f953ef76dbf8d55ac91fb219dde70e49aa4a6b7d74e9919050"
|
||||
|
||||
[[package]]
|
||||
name = "num-derive"
|
||||
version = "0.4.2"
|
||||
@@ -1059,6 +1260,17 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "password-hash"
|
||||
version = "0.4.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7676374caaee8a325c9e7a2ae557f216c5563a171d6997b0ef8a65af35147700"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"rand_core",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "paste"
|
||||
version = "1.0.15"
|
||||
@@ -1071,6 +1283,18 @@ version = "0.2.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"
|
||||
|
||||
[[package]]
|
||||
name = "pbkdf2"
|
||||
version = "0.11.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "83a0692ec44e4cf1ef28ca317f14f8f07da2d95ec3fa01f86e4467b725e60917"
|
||||
dependencies = [
|
||||
"digest",
|
||||
"hmac",
|
||||
"password-hash",
|
||||
"sha2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "petgraph"
|
||||
version = "0.5.1"
|
||||
@@ -1097,6 +1321,12 @@ version = "0.3.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"
|
||||
|
||||
[[package]]
|
||||
name = "powerfmt"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
@@ -1133,6 +1363,12 @@ dependencies = [
|
||||
"proc-macro2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "r-efi"
|
||||
version = "5.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
||||
|
||||
[[package]]
|
||||
name = "rand"
|
||||
version = "0.8.5"
|
||||
@@ -1160,7 +1396,7 @@ version = "0.6.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
|
||||
dependencies = [
|
||||
"getrandom",
|
||||
"getrandom 0.2.16",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -1323,6 +1559,28 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha1"
|
||||
version = "0.10.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sha2"
|
||||
version = "0.10.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"cpufeatures",
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "1.3.0"
|
||||
@@ -1359,6 +1617,12 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "simd-adler32"
|
||||
version = "0.3.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2"
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.15.1"
|
||||
@@ -1403,6 +1667,12 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "symphonia"
|
||||
version = "0.5.5"
|
||||
@@ -1629,6 +1899,25 @@ dependencies = [
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time"
|
||||
version = "0.3.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c"
|
||||
dependencies = [
|
||||
"deranged",
|
||||
"num-conv",
|
||||
"powerfmt",
|
||||
"serde_core",
|
||||
"time-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time-core"
|
||||
version = "0.1.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"
|
||||
|
||||
[[package]]
|
||||
name = "toml_datetime"
|
||||
version = "0.7.3"
|
||||
@@ -1659,6 +1948,12 @@ dependencies = [
|
||||
"winnow",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "typenum"
|
||||
version = "1.19.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb"
|
||||
|
||||
[[package]]
|
||||
name = "unicode-ident"
|
||||
version = "1.0.19"
|
||||
@@ -1694,6 +1989,12 @@ version = "0.2.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
|
||||
|
||||
[[package]]
|
||||
name = "version_check"
|
||||
version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "walkdir"
|
||||
version = "2.5.0"
|
||||
@@ -1710,6 +2011,15 @@ version = "0.11.1+wasi-snapshot-preview1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||
|
||||
[[package]]
|
||||
name = "wasip2"
|
||||
version = "1.0.2+wasi-0.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"
|
||||
dependencies = [
|
||||
"wit-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wasm-bindgen"
|
||||
version = "0.2.104"
|
||||
@@ -2098,6 +2408,12 @@ dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "wit-bindgen"
|
||||
version = "0.51.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
|
||||
|
||||
[[package]]
|
||||
name = "zerocopy"
|
||||
version = "0.8.27"
|
||||
@@ -2117,3 +2433,52 @@ dependencies = [
|
||||
"quote",
|
||||
"syn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zip"
|
||||
version = "0.6.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "760394e246e4c28189f19d488c058bf16f564016aefac5d32bb1f3b51d5e9261"
|
||||
dependencies = [
|
||||
"aes",
|
||||
"byteorder",
|
||||
"bzip2",
|
||||
"constant_time_eq",
|
||||
"crc32fast",
|
||||
"crossbeam-utils",
|
||||
"flate2",
|
||||
"hmac",
|
||||
"pbkdf2",
|
||||
"sha1",
|
||||
"time",
|
||||
"zstd",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zstd"
|
||||
version = "0.11.2+zstd.1.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "20cc960326ece64f010d2d2107537f26dc589a6573a316bd5b1dba685fa5fde4"
|
||||
dependencies = [
|
||||
"zstd-safe",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zstd-safe"
|
||||
version = "5.0.2+zstd.1.5.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1d2a5585e04f9eea4b2a3d1eca508c4dee9592a89ef6f450c11719da0726f4db"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"zstd-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "zstd-sys"
|
||||
version = "2.0.16+zstd.1.5.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "91e19ebc2adc8f83e43039e79776e3fda8ca919132d68a1fed6a5faca2683748"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"pkg-config",
|
||||
]
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
/// Automation system for parameter modulation over time
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::time::Beats;
|
||||
|
||||
/// Unique identifier for automation lanes
|
||||
pub type AutomationLaneId = u32;
|
||||
@@ -35,17 +36,13 @@ pub enum CurveType {
|
||||
/// A single automation point
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AutomationPoint {
|
||||
/// Time in seconds
|
||||
pub time: f64,
|
||||
/// Parameter value (normalized 0.0 to 1.0, or actual value depending on parameter)
|
||||
pub time: Beats,
|
||||
pub value: f32,
|
||||
/// Curve type to next point
|
||||
pub curve: CurveType,
|
||||
}
|
||||
|
||||
impl AutomationPoint {
|
||||
/// Create a new automation point
|
||||
pub fn new(time: f64, value: f32, curve: CurveType) -> Self {
|
||||
pub fn new(time: Beats, value: f32, curve: CurveType) -> Self {
|
||||
Self { time, value, curve }
|
||||
}
|
||||
}
|
||||
@@ -93,8 +90,7 @@ impl AutomationLane {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove point at specific time
|
||||
pub fn remove_point_at_time(&mut self, time: f64, tolerance: f64) -> bool {
|
||||
pub fn remove_point_at_time(&mut self, time: Beats, tolerance: Beats) -> bool {
|
||||
if let Some(idx) = self.points.iter().position(|p| (p.time - time).abs() < tolerance) {
|
||||
self.points.remove(idx);
|
||||
true
|
||||
@@ -113,8 +109,7 @@ impl AutomationLane {
|
||||
&self.points
|
||||
}
|
||||
|
||||
/// Get value at a specific time with interpolation
|
||||
pub fn evaluate(&self, time: f64) -> Option<f32> {
|
||||
pub fn evaluate(&self, time: Beats) -> Option<f32> {
|
||||
if !self.enabled || self.points.is_empty() {
|
||||
return None;
|
||||
}
|
||||
@@ -148,14 +143,12 @@ impl AutomationLane {
|
||||
}
|
||||
}
|
||||
|
||||
/// Interpolate between two automation points based on curve type
|
||||
fn interpolate(p1: &AutomationPoint, p2: &AutomationPoint, time: f64) -> f32 {
|
||||
// Calculate normalized position between points (0.0 to 1.0)
|
||||
fn interpolate(p1: &AutomationPoint, p2: &AutomationPoint, time: Beats) -> f32 {
|
||||
let t = if p2.time == p1.time {
|
||||
0.0
|
||||
0.0f64
|
||||
} else {
|
||||
((time - p1.time) / (p2.time - p1.time)) as f32
|
||||
};
|
||||
(time - p1.time) / (p2.time - p1.time)
|
||||
} as f32;
|
||||
|
||||
// Apply curve
|
||||
let curved_t = match p1.curve {
|
||||
@@ -196,22 +189,22 @@ mod tests {
|
||||
fn test_add_points_sorted() {
|
||||
let mut lane = AutomationLane::new(0, ParameterId::TrackVolume);
|
||||
|
||||
lane.add_point(AutomationPoint::new(2.0, 0.5, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(1.0, 0.3, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(3.0, 0.8, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(Beats(2.0), 0.5, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(Beats(1.0), 0.3, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(Beats(3.0), 0.8, CurveType::Linear));
|
||||
|
||||
assert_eq!(lane.points().len(), 3);
|
||||
assert_eq!(lane.points()[0].time, 1.0);
|
||||
assert_eq!(lane.points()[1].time, 2.0);
|
||||
assert_eq!(lane.points()[2].time, 3.0);
|
||||
assert_eq!(lane.points()[0].time, Beats(1.0));
|
||||
assert_eq!(lane.points()[1].time, Beats(2.0));
|
||||
assert_eq!(lane.points()[2].time, Beats(3.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_replace_point_at_same_time() {
|
||||
let mut lane = AutomationLane::new(0, ParameterId::TrackVolume);
|
||||
|
||||
lane.add_point(AutomationPoint::new(1.0, 0.3, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(1.0, 0.5, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(Beats(1.0), 0.3, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(Beats(1.0), 0.5, CurveType::Linear));
|
||||
|
||||
assert_eq!(lane.points().len(), 1);
|
||||
assert_eq!(lane.points()[0].value, 0.5);
|
||||
@@ -221,59 +214,59 @@ mod tests {
|
||||
fn test_linear_interpolation() {
|
||||
let mut lane = AutomationLane::new(0, ParameterId::TrackVolume);
|
||||
|
||||
lane.add_point(AutomationPoint::new(0.0, 0.0, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(1.0, 1.0, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(Beats(0.0), 0.0, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(Beats(1.0), 1.0, CurveType::Linear));
|
||||
|
||||
assert_eq!(lane.evaluate(0.0), Some(0.0));
|
||||
assert_eq!(lane.evaluate(0.5), Some(0.5));
|
||||
assert_eq!(lane.evaluate(1.0), Some(1.0));
|
||||
assert_eq!(lane.evaluate(Beats(0.0)), Some(0.0));
|
||||
assert_eq!(lane.evaluate(Beats(0.5)), Some(0.5));
|
||||
assert_eq!(lane.evaluate(Beats(1.0)), Some(1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_step_interpolation() {
|
||||
let mut lane = AutomationLane::new(0, ParameterId::TrackVolume);
|
||||
|
||||
lane.add_point(AutomationPoint::new(0.0, 0.5, CurveType::Step));
|
||||
lane.add_point(AutomationPoint::new(1.0, 1.0, CurveType::Step));
|
||||
lane.add_point(AutomationPoint::new(Beats(0.0), 0.5, CurveType::Step));
|
||||
lane.add_point(AutomationPoint::new(Beats(1.0), 1.0, CurveType::Step));
|
||||
|
||||
assert_eq!(lane.evaluate(0.0), Some(0.5));
|
||||
assert_eq!(lane.evaluate(0.5), Some(0.5));
|
||||
assert_eq!(lane.evaluate(0.99), Some(0.5));
|
||||
assert_eq!(lane.evaluate(1.0), Some(1.0));
|
||||
assert_eq!(lane.evaluate(Beats(0.0)), Some(0.5));
|
||||
assert_eq!(lane.evaluate(Beats(0.5)), Some(0.5));
|
||||
assert_eq!(lane.evaluate(Beats(0.99)), Some(0.5));
|
||||
assert_eq!(lane.evaluate(Beats(1.0)), Some(1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_evaluate_outside_range() {
|
||||
let mut lane = AutomationLane::new(0, ParameterId::TrackVolume);
|
||||
|
||||
lane.add_point(AutomationPoint::new(1.0, 0.5, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(2.0, 1.0, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(Beats(1.0), 0.5, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(Beats(2.0), 1.0, CurveType::Linear));
|
||||
|
||||
// Before first point
|
||||
assert_eq!(lane.evaluate(0.0), Some(0.5));
|
||||
assert_eq!(lane.evaluate(Beats(0.0)), Some(0.5));
|
||||
// After last point
|
||||
assert_eq!(lane.evaluate(3.0), Some(1.0));
|
||||
assert_eq!(lane.evaluate(Beats(3.0)), Some(1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_disabled_lane() {
|
||||
let mut lane = AutomationLane::new(0, ParameterId::TrackVolume);
|
||||
|
||||
lane.add_point(AutomationPoint::new(0.0, 0.5, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(Beats(0.0), 0.5, CurveType::Linear));
|
||||
lane.enabled = false;
|
||||
|
||||
assert_eq!(lane.evaluate(0.0), None);
|
||||
assert_eq!(lane.evaluate(Beats(0.0)), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_remove_point() {
|
||||
let mut lane = AutomationLane::new(0, ParameterId::TrackVolume);
|
||||
|
||||
lane.add_point(AutomationPoint::new(1.0, 0.5, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(2.0, 0.8, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(Beats(1.0), 0.5, CurveType::Linear));
|
||||
lane.add_point(AutomationPoint::new(Beats(2.0), 0.8, CurveType::Linear));
|
||||
|
||||
assert!(lane.remove_point_at_time(1.0, 0.001));
|
||||
assert!(lane.remove_point_at_time(Beats(1.0), Beats(0.001)));
|
||||
assert_eq!(lane.points().len(), 1);
|
||||
assert_eq!(lane.points()[0].time, 2.0);
|
||||
assert_eq!(lane.points()[0].time, Beats(2.0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
use std::sync::Arc;
|
||||
use serde::{Serialize, Deserialize};
|
||||
use crate::time::{Beats, Seconds};
|
||||
use crate::tempo_map::TempoMap;
|
||||
|
||||
/// Audio clip instance ID type
|
||||
pub type AudioClipInstanceId = u32;
|
||||
@@ -9,38 +11,31 @@ pub type ClipId = AudioClipInstanceId;
|
||||
|
||||
/// Audio clip instance that references content in the AudioClipPool
|
||||
///
|
||||
/// This represents a placed instance of audio content on the timeline.
|
||||
/// The actual audio data is stored in the AudioClipPool and referenced by `audio_pool_index`.
|
||||
///
|
||||
/// ## Timing Model
|
||||
/// - `internal_start` / `internal_end`: Define the region of the source audio to play (trimming)
|
||||
/// - `external_start` / `external_duration`: Define where the clip appears on the timeline and how long
|
||||
/// - `internal_start` / `internal_end`: Region of the source audio to play (seconds — audio file seek positions)
|
||||
/// - `external_start` / `external_duration`: Where the clip appears on the timeline (**beats**)
|
||||
///
|
||||
/// ## Looping
|
||||
/// If `external_duration` is greater than `internal_end - internal_start`,
|
||||
/// the clip will seamlessly loop back to `internal_start` when it reaches `internal_end`.
|
||||
/// If `external_duration_secs(bpm)` > `internal_end - internal_start`, the clip loops.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AudioClipInstance {
|
||||
pub id: AudioClipInstanceId,
|
||||
pub audio_pool_index: usize,
|
||||
|
||||
/// Start position within the audio content (seconds)
|
||||
pub internal_start: f64,
|
||||
/// End position within the audio content (seconds)
|
||||
pub internal_end: f64,
|
||||
/// Start position within the audio content
|
||||
pub internal_start: Seconds,
|
||||
/// End position within the audio content
|
||||
pub internal_end: Seconds,
|
||||
|
||||
/// Start position on the timeline (seconds)
|
||||
pub external_start: f64,
|
||||
/// Duration on the timeline (seconds) - can be longer than internal duration for looping
|
||||
pub external_duration: f64,
|
||||
/// Start position on the timeline
|
||||
pub external_start: Beats,
|
||||
/// Duration on the timeline
|
||||
pub external_duration: Beats,
|
||||
|
||||
/// Clip-level gain
|
||||
pub gain: f32,
|
||||
|
||||
/// Per-instance read-ahead buffer for compressed audio streaming.
|
||||
/// Each clip instance gets its own buffer so multiple instances of the
|
||||
/// same file (on different tracks or at different positions) don't fight
|
||||
/// over a single target_frame.
|
||||
#[serde(skip)]
|
||||
pub read_ahead: Option<Arc<super::disk_reader::ReadAheadBuffer>>,
|
||||
}
|
||||
@@ -49,14 +44,13 @@ pub struct AudioClipInstance {
|
||||
pub type Clip = AudioClipInstance;
|
||||
|
||||
impl AudioClipInstance {
|
||||
/// Create a new audio clip instance
|
||||
pub fn new(
|
||||
id: AudioClipInstanceId,
|
||||
audio_pool_index: usize,
|
||||
internal_start: f64,
|
||||
internal_end: f64,
|
||||
external_start: f64,
|
||||
external_duration: f64,
|
||||
internal_start: Seconds,
|
||||
internal_end: Seconds,
|
||||
external_start: Beats,
|
||||
external_duration: Beats,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
@@ -70,80 +64,50 @@ impl AudioClipInstance {
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a clip instance from legacy parameters (for backwards compatibility)
|
||||
/// Maps old start_time/duration/offset to new timing model
|
||||
pub fn from_legacy(
|
||||
id: AudioClipInstanceId,
|
||||
audio_pool_index: usize,
|
||||
start_time: f64,
|
||||
duration: f64,
|
||||
offset: f64,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
audio_pool_index,
|
||||
internal_start: offset,
|
||||
internal_end: offset + duration,
|
||||
external_start: start_time,
|
||||
external_duration: duration,
|
||||
gain: 1.0,
|
||||
read_ahead: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Check if this clip instance is active at a given timeline position
|
||||
pub fn is_active_at(&self, time_seconds: f64) -> bool {
|
||||
time_seconds >= self.external_start && time_seconds < self.external_end()
|
||||
}
|
||||
|
||||
/// Get the end time of this clip instance on the timeline
|
||||
pub fn external_end(&self) -> f64 {
|
||||
pub fn external_end(&self) -> Beats {
|
||||
self.external_start + self.external_duration
|
||||
}
|
||||
|
||||
/// Get the end time of this clip instance on the timeline
|
||||
/// (Alias for external_end(), for backwards compatibility)
|
||||
pub fn end_time(&self) -> f64 {
|
||||
self.external_end()
|
||||
pub fn external_start_secs(&self, tempo_map: &TempoMap) -> Seconds {
|
||||
tempo_map.beats_to_seconds(self.external_start)
|
||||
}
|
||||
|
||||
/// Get the start time on the timeline
|
||||
/// (Alias for external_start, for backwards compatibility)
|
||||
pub fn start_time(&self) -> f64 {
|
||||
self.external_start
|
||||
pub fn external_end_secs(&self, tempo_map: &TempoMap) -> Seconds {
|
||||
tempo_map.beats_to_seconds(self.external_end())
|
||||
}
|
||||
|
||||
/// Get the internal (content) duration
|
||||
pub fn internal_duration(&self) -> f64 {
|
||||
pub fn external_duration_secs(&self, tempo_map: &TempoMap) -> Seconds {
|
||||
tempo_map.beats_to_seconds(self.external_end()) - tempo_map.beats_to_seconds(self.external_start)
|
||||
}
|
||||
|
||||
pub fn is_active_at(&self, time: Seconds, tempo_map: &TempoMap) -> bool {
|
||||
time >= self.external_start_secs(tempo_map) && time < self.external_end_secs(tempo_map)
|
||||
}
|
||||
|
||||
pub fn internal_duration(&self) -> Seconds {
|
||||
self.internal_end - self.internal_start
|
||||
}
|
||||
|
||||
/// Check if this clip instance loops
|
||||
pub fn is_looping(&self) -> bool {
|
||||
self.external_duration > self.internal_duration()
|
||||
pub fn is_looping(&self, tempo_map: &TempoMap) -> bool {
|
||||
self.external_duration_secs(tempo_map) > self.internal_duration()
|
||||
}
|
||||
|
||||
/// Get the position within the audio content for a given timeline position
|
||||
/// Returns None if the timeline position is outside this clip instance
|
||||
/// Handles looping automatically
|
||||
pub fn get_content_position(&self, timeline_pos: f64) -> Option<f64> {
|
||||
if timeline_pos < self.external_start || timeline_pos >= self.external_end() {
|
||||
/// Get the audio content position for a given timeline position. Handles looping.
|
||||
pub fn get_content_position(&self, timeline_pos: Seconds, tempo_map: &TempoMap) -> Option<Seconds> {
|
||||
let start_secs = self.external_start_secs(tempo_map);
|
||||
let end_secs = self.external_end_secs(tempo_map);
|
||||
if timeline_pos < start_secs || timeline_pos >= end_secs {
|
||||
return None;
|
||||
}
|
||||
|
||||
let relative_pos = timeline_pos - self.external_start;
|
||||
let relative_pos = timeline_pos - start_secs;
|
||||
let internal_duration = self.internal_duration();
|
||||
|
||||
if internal_duration <= 0.0 {
|
||||
if internal_duration.0 <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Wrap around for looping
|
||||
let content_offset = relative_pos % internal_duration;
|
||||
Some(self.internal_start + content_offset)
|
||||
}
|
||||
|
||||
/// Set clip gain
|
||||
pub fn set_gain(&mut self, gain: f32) {
|
||||
self.gain = gain.max(0.0);
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
@@ -307,23 +327,96 @@ impl ReadAheadBuffer {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Wraps a Symphonia decoder for streaming a single compressed audio file.
|
||||
struct CompressedReader {
|
||||
///
|
||||
/// Public (like [`VideoAudioReader`]) only so integration tests can exercise it
|
||||
/// directly; treat it as crate-internal.
|
||||
pub struct CompressedReader {
|
||||
format_reader: Box<dyn symphonia::core::formats::FormatReader>,
|
||||
decoder: Box<dyn symphonia::core::codecs::Decoder>,
|
||||
track_id: u32,
|
||||
/// Current decoder position in frames.
|
||||
current_frame: u64,
|
||||
/// Frames still to drop from the front of decoded output, so that after a
|
||||
/// (coarse) seek the next emitted sample lands exactly on the target frame.
|
||||
pending_discard: u64,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
#[allow(dead_code)]
|
||||
total_frames: u64,
|
||||
/// Temporary decode buffer.
|
||||
sample_buf: Option<SampleBuffer<f32>>,
|
||||
}
|
||||
|
||||
/// A seekable byte stream for packed media held in the host's project container.
|
||||
///
|
||||
/// `daw-backend` stays container-agnostic: it never references the `.beam` SQLite
|
||||
/// store directly. Instead the host (lightningbeam-core) implements this trait over
|
||||
/// its incremental blob reader and installs a factory ([`AudioBlobSourceFactory`])
|
||||
/// into the engine, so packed compressed audio can be stream-decoded without ever
|
||||
/// being fully loaded into RAM.
|
||||
pub trait MediaByteSource: std::io::Read + std::io::Seek + Send + Sync {
|
||||
/// Total length of the stream in bytes (Symphonia needs this for seeking).
|
||||
fn byte_len(&self) -> u64;
|
||||
}
|
||||
|
||||
/// Opens fresh byte streams for packed media by id. Installed into the engine by
|
||||
/// the host; invoked when activating a clip backed by container-packed audio.
|
||||
/// (`Debug` so it can ride in the `Query` enum, which derives `Debug`.)
|
||||
pub trait AudioBlobSourceFactory: Send + Sync + std::fmt::Debug {
|
||||
/// Open a new independent reader for the packed media item `media_id`
|
||||
/// (the UUID string stored on the audio pool entry).
|
||||
fn open(&self, media_id: &str) -> Result<Box<dyn MediaByteSource>, String>;
|
||||
}
|
||||
|
||||
/// Adapts a [`MediaByteSource`] to Symphonia's `MediaSource` (adds the seekable +
|
||||
/// byte-length metadata Symphonia's probe/seek require).
|
||||
struct SymphoniaByteSource(Box<dyn MediaByteSource>);
|
||||
|
||||
impl std::io::Read for SymphoniaByteSource {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
self.0.read(buf)
|
||||
}
|
||||
}
|
||||
impl std::io::Seek for SymphoniaByteSource {
|
||||
fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
|
||||
self.0.seek(pos)
|
||||
}
|
||||
}
|
||||
impl symphonia::core::io::MediaSource for SymphoniaByteSource {
|
||||
fn is_seekable(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn byte_len(&self) -> Option<u64> {
|
||||
Some(self.0.byte_len())
|
||||
}
|
||||
}
|
||||
|
||||
/// How to open a streaming audio source: a filesystem path (referenced media or a
|
||||
/// video file) or a host-provided byte stream (container-packed media).
|
||||
pub enum StreamOpen {
|
||||
Path(PathBuf),
|
||||
Source {
|
||||
src: Box<dyn MediaByteSource>,
|
||||
/// Codec/extension hint for the Symphonia probe (e.g. `"mp3"`, `"flac"`).
|
||||
ext: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
impl CompressedReader {
|
||||
pub fn sample_rate(&self) -> u32 {
|
||||
self.sample_rate
|
||||
}
|
||||
|
||||
pub fn channels(&self) -> u32 {
|
||||
self.channels
|
||||
}
|
||||
|
||||
/// Total frames from the codec header (0 if the format doesn't report it).
|
||||
pub fn total_frames(&self) -> u64 {
|
||||
self.total_frames
|
||||
}
|
||||
|
||||
/// Open a compressed audio file and prepare for streaming decode.
|
||||
fn open(path: &Path) -> Result<Self, String> {
|
||||
pub fn open(path: &Path) -> Result<Self, String> {
|
||||
let file =
|
||||
std::fs::File::open(path).map_err(|e| format!("Failed to open file: {}", e))?;
|
||||
let mss = MediaSourceStream::new(Box::new(file), Default::default());
|
||||
@@ -332,7 +425,21 @@ impl CompressedReader {
|
||||
if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
|
||||
hint.with_extension(ext);
|
||||
}
|
||||
Self::from_mss(mss, hint)
|
||||
}
|
||||
|
||||
/// Open a compressed stream from a host-provided byte source (packed media).
|
||||
pub fn open_source(src: Box<dyn MediaByteSource>, ext: Option<&str>) -> Result<Self, String> {
|
||||
let mss = MediaSourceStream::new(Box::new(SymphoniaByteSource(src)), Default::default());
|
||||
let mut hint = Hint::new();
|
||||
if let Some(ext) = ext {
|
||||
hint.with_extension(ext);
|
||||
}
|
||||
Self::from_mss(mss, hint)
|
||||
}
|
||||
|
||||
/// Shared probe + decoder setup over an already-built media stream.
|
||||
fn from_mss(mss: MediaSourceStream, hint: Hint) -> Result<Self, String> {
|
||||
let probed = symphonia::default::get_probe()
|
||||
.format(
|
||||
&hint,
|
||||
@@ -368,6 +475,7 @@ impl CompressedReader {
|
||||
decoder,
|
||||
track_id,
|
||||
current_frame: 0,
|
||||
pending_discard: 0,
|
||||
sample_rate,
|
||||
channels,
|
||||
total_frames,
|
||||
@@ -375,9 +483,17 @@ impl CompressedReader {
|
||||
})
|
||||
}
|
||||
|
||||
/// Seek to a specific frame. Returns the actual frame reached (may differ
|
||||
/// for compressed formats that can only seek to keyframes).
|
||||
fn seek(&mut self, target_frame: u64) -> Result<u64, String> {
|
||||
/// Seek to `target_frame`, **sample-accurately**. Uses `SeekMode::Accurate`:
|
||||
/// for an elementary stream like MP3 a *coarse* seek byte-estimates the
|
||||
/// position and seeds the timestamp from that estimate — which for VBR (or a
|
||||
/// file whose header padding the estimate ignores) lands off by up to ~1s.
|
||||
/// Accurate mode instead counts frame *headers* (no decode) from a true anchor
|
||||
/// (the current position, or a rewind to the start for backward seeks), so the
|
||||
/// returned `actual_ts` is exact; the small residual to `target_frame` is then
|
||||
/// dropped in `decode_next`. Container formats with seek tables (FLAC/OGG) seek
|
||||
/// cheaply; a long MP3 walks headers from the anchor (I/O, not decode) — a
|
||||
/// per-file seek index would make that O(1) (future work).
|
||||
pub fn seek(&mut self, target_frame: u64) -> Result<u64, String> {
|
||||
let seek_to = SeekTo::TimeStamp {
|
||||
ts: target_frame,
|
||||
track_id: self.track_id,
|
||||
@@ -385,21 +501,23 @@ impl CompressedReader {
|
||||
|
||||
let seeked = self
|
||||
.format_reader
|
||||
.seek(SeekMode::Coarse, seek_to)
|
||||
.seek(SeekMode::Accurate, seek_to)
|
||||
.map_err(|e| format!("Seek failed: {}", e))?;
|
||||
|
||||
let actual_frame = seeked.actual_ts;
|
||||
self.current_frame = actual_frame;
|
||||
// Drop the frames between where the coarse seek landed and the target.
|
||||
self.pending_discard = target_frame.saturating_sub(actual_frame);
|
||||
|
||||
// Reset the decoder after seeking.
|
||||
self.decoder.reset();
|
||||
|
||||
Ok(actual_frame)
|
||||
Ok(target_frame)
|
||||
}
|
||||
|
||||
/// Decode the next chunk of audio into `out`. Returns the number of frames
|
||||
/// decoded. Returns `Ok(0)` at end-of-file.
|
||||
fn decode_next(&mut self, out: &mut Vec<f32>) -> Result<usize, String> {
|
||||
pub fn decode_next(&mut self, out: &mut Vec<f32>) -> Result<usize, String> {
|
||||
out.clear();
|
||||
|
||||
loop {
|
||||
@@ -428,10 +546,22 @@ impl CompressedReader {
|
||||
if let Some(ref mut buf) = self.sample_buf {
|
||||
buf.copy_interleaved_ref(decoded);
|
||||
let samples = buf.samples();
|
||||
out.extend_from_slice(samples);
|
||||
let frames = samples.len() / self.channels as usize;
|
||||
self.current_frame += frames as u64;
|
||||
return Ok(frames);
|
||||
let ch = self.channels as usize;
|
||||
let frames = samples.len() / ch;
|
||||
|
||||
// Drop leading frames for sample-accurate seek alignment.
|
||||
let discard = self.pending_discard.min(frames as u64) as usize;
|
||||
self.pending_discard -= discard as u64;
|
||||
out.extend_from_slice(&samples[discard * ch..]);
|
||||
let emitted = frames - discard;
|
||||
self.current_frame += emitted as u64;
|
||||
|
||||
if emitted > 0 {
|
||||
return Ok(emitted);
|
||||
}
|
||||
// Whole packet discarded for alignment — keep decoding so
|
||||
// we never falsely report EOF (Ok(0)).
|
||||
continue;
|
||||
}
|
||||
|
||||
return Ok(0);
|
||||
@@ -445,16 +575,428 @@ impl CompressedReader {
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// VideoAudioReader
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Streams the audio track out of a media file (a video container, or any audio
|
||||
/// file) using FFmpeg, decoding on demand. Mirrors [`CompressedReader`]'s
|
||||
/// interface so the disk reader can drive either through [`StreamSource`].
|
||||
///
|
||||
/// Seeking is **sample-accurate**: after `seek(target)`, the next `decode_next`
|
||||
/// yields samples beginning at exactly `target`. FFmpeg's container seek only
|
||||
/// lands at-or-before the target, so we decode forward and discard the leading
|
||||
/// samples to hit the frame precisely — this keeps video audio frame-synced with
|
||||
/// other (mmap/in-memory) clips.
|
||||
///
|
||||
/// 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: 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>,
|
||||
stream_index: usize,
|
||||
/// Seconds per stream-timestamp unit.
|
||||
time_base: f64,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
total_frames: u64,
|
||||
/// Absolute frame index of the next sample `decode_next` will output.
|
||||
current_frame: u64,
|
||||
/// Frames still to drop from the front of decoded output (seek alignment).
|
||||
pending_discard: u64,
|
||||
/// When set, the next decoded frame establishes the discard needed to land on
|
||||
/// this absolute target frame (sample-accurate seek).
|
||||
align_to: Option<u64>,
|
||||
}
|
||||
|
||||
impl VideoAudioReader {
|
||||
pub fn sample_rate(&self) -> u32 {
|
||||
self.sample_rate
|
||||
}
|
||||
|
||||
pub fn channels(&self) -> u32 {
|
||||
self.channels
|
||||
}
|
||||
|
||||
/// Estimated total audio frames (from the stream/container duration).
|
||||
pub fn total_frames(&self) -> u64 {
|
||||
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())?;
|
||||
let stream_index = stream.index();
|
||||
let time_base = f64::from(stream.time_base());
|
||||
let stream_duration = stream.duration();
|
||||
let ctx = ffmpeg_next::codec::context::Context::from_parameters(stream.parameters())
|
||||
.map_err(|e| e.to_string())?;
|
||||
let decoder = ctx.decoder().audio().map_err(|e| e.to_string())?;
|
||||
(stream_index, time_base, stream_duration, decoder)
|
||||
};
|
||||
|
||||
let sample_rate = decoder.rate();
|
||||
let channels = decoder.channels() as u32;
|
||||
|
||||
let duration_secs = if stream_duration > 0 {
|
||||
stream_duration as f64 * time_base
|
||||
} else if input.get().duration() > 0 {
|
||||
input.get().duration() as f64 / f64::from(ffmpeg_next::ffi::AV_TIME_BASE)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
let total_frames = (duration_secs * sample_rate as f64).max(0.0) as u64;
|
||||
|
||||
Ok(Self {
|
||||
input,
|
||||
decoder,
|
||||
resampler: None,
|
||||
stream_index,
|
||||
time_base,
|
||||
sample_rate,
|
||||
channels,
|
||||
total_frames,
|
||||
current_frame: 0,
|
||||
pending_discard: 0,
|
||||
align_to: None,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn seek(&mut self, target_frame: u64) -> Result<u64, String> {
|
||||
let seconds = target_frame as f64 / self.sample_rate.max(1) as f64;
|
||||
let ts_av = (seconds * f64::from(ffmpeg_next::ffi::AV_TIME_BASE)) as i64;
|
||||
// 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();
|
||||
self.pending_discard = 0;
|
||||
self.align_to = Some(target_frame);
|
||||
self.current_frame = target_frame;
|
||||
// We align to the exact frame below, so the effective position IS target.
|
||||
Ok(target_frame)
|
||||
}
|
||||
|
||||
pub fn decode_next(&mut self, out: &mut Vec<f32>) -> Result<usize, String> {
|
||||
out.clear();
|
||||
loop {
|
||||
// Drain a decoded frame if one is ready.
|
||||
let mut decoded = ffmpeg_next::frame::Audio::empty();
|
||||
if self.decoder.receive_frame(&mut decoded).is_ok() {
|
||||
self.ensure_layout(&mut decoded);
|
||||
let n = self.emit(&decoded, out);
|
||||
if n > 0 {
|
||||
return Ok(n);
|
||||
}
|
||||
continue; // frame fully discarded by seek-alignment; keep going
|
||||
}
|
||||
|
||||
// Read one packet (owned), releasing the `input` borrow before decoding.
|
||||
let packet = self.input.get().packets().next().map(|(_, p)| p);
|
||||
match packet {
|
||||
Some(packet) => {
|
||||
if packet.stream() == self.stream_index {
|
||||
self.decoder
|
||||
.send_packet(&packet)
|
||||
.map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
// EOF: flush and drain whatever remains.
|
||||
let _ = self.decoder.send_eof();
|
||||
let mut decoded = ffmpeg_next::frame::Audio::empty();
|
||||
if self.decoder.receive_frame(&mut decoded).is_ok() {
|
||||
self.ensure_layout(&mut decoded);
|
||||
return Ok(self.emit(&decoded, out));
|
||||
}
|
||||
return Ok(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Decoders for some formats (e.g. raw mono WAV) leave the frame's channel
|
||||
/// layout unset. The resampler needs a concrete layout that matches the
|
||||
/// frame, so fill one in from the channel count when it's missing.
|
||||
fn ensure_layout(&self, frame: &mut ffmpeg_next::frame::Audio) {
|
||||
if frame.channel_layout().is_empty() {
|
||||
frame.set_channel_layout(
|
||||
ffmpeg_next::channel_layout::ChannelLayout::default(self.channels as i32),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Resample one decoded frame to interleaved f32, apply any pending
|
||||
/// seek-alignment discard, append to `out`, return frames emitted.
|
||||
fn emit(&mut self, frame: &ffmpeg_next::frame::Audio, out: &mut Vec<f32>) -> usize {
|
||||
// `frame` already has a non-empty channel layout (set by `ensure_layout`
|
||||
// before this call), so the resampler config and the actual frame agree
|
||||
// — otherwise swr fails with AVERROR_INPUT_CHANGED.
|
||||
if self.resampler.is_none() {
|
||||
match ffmpeg_next::software::resampling::Context::get(
|
||||
frame.format(),
|
||||
frame.channel_layout(),
|
||||
self.sample_rate,
|
||||
ffmpeg_next::format::Sample::F32(ffmpeg_next::format::sample::Type::Packed),
|
||||
frame.channel_layout(),
|
||||
self.sample_rate,
|
||||
) {
|
||||
Ok(r) => self.resampler = Some(r),
|
||||
Err(_) => return 0,
|
||||
}
|
||||
}
|
||||
|
||||
let mut resampled = ffmpeg_next::frame::Audio::empty();
|
||||
if self
|
||||
.resampler
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.run(frame, &mut resampled)
|
||||
.is_err()
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
// The output is packed (interleaved) f32. Read it from the raw byte plane
|
||||
// `data(0)` — its length is correct (`frames * channels * 4`), whereas
|
||||
// `plane::<f32>(0)` is a known ffmpeg-next footgun that reports only
|
||||
// `samples()` elements (ignoring channels) and would slice out of range
|
||||
// for multi-channel audio.
|
||||
let ch = self.channels.max(1) as usize;
|
||||
let bytes = resampled.data(0);
|
||||
let n_frames = (bytes.len() / 4) / ch;
|
||||
if n_frames == 0 {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// On the first frame after a seek, compute how many leading frames to
|
||||
// drop so output begins exactly at the seek target.
|
||||
if let Some(target) = self.align_to.take() {
|
||||
let frame_start = self.pts_to_frame(frame.pts());
|
||||
self.pending_discard = target.saturating_sub(frame_start);
|
||||
}
|
||||
|
||||
let discard = (self.pending_discard.min(n_frames as u64)) as usize;
|
||||
self.pending_discard -= discard as u64;
|
||||
|
||||
let start_byte = discard * ch * 4;
|
||||
let end_byte = n_frames * ch * 4;
|
||||
out.extend(
|
||||
bytes[start_byte..end_byte]
|
||||
.chunks_exact(4)
|
||||
.map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])),
|
||||
);
|
||||
let emitted = n_frames - discard;
|
||||
self.current_frame += emitted as u64;
|
||||
emitted
|
||||
}
|
||||
|
||||
/// Convert a stream PTS to an absolute audio frame index.
|
||||
fn pts_to_frame(&self, pts: Option<i64>) -> u64 {
|
||||
match pts {
|
||||
Some(p) if p >= 0 => {
|
||||
((p as f64 * self.time_base) * self.sample_rate as f64).round() as u64
|
||||
}
|
||||
_ => self.current_frame,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// StreamSource — dispatches the disk reader over either decoder backend.
|
||||
// (Wired into the reader thread in a later step.)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Which decoder backend a streaming source uses.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum SourceKind {
|
||||
/// Symphonia, for compressed audio files (MP3, FLAC, OGG, …).
|
||||
CompressedAudio,
|
||||
/// FFmpeg, for the audio track of a video container.
|
||||
VideoAudio,
|
||||
}
|
||||
|
||||
/// A streaming audio source backing one active clip: either Symphonia
|
||||
/// ([`CompressedReader`]) or FFmpeg ([`VideoAudioReader`]).
|
||||
enum StreamSource {
|
||||
Compressed(CompressedReader),
|
||||
Video(VideoAudioReader),
|
||||
}
|
||||
|
||||
impl StreamSource {
|
||||
fn open(open: StreamOpen, kind: SourceKind) -> Result<Self, String> {
|
||||
match (kind, open) {
|
||||
(SourceKind::CompressedAudio, StreamOpen::Path(p)) => {
|
||||
Ok(StreamSource::Compressed(CompressedReader::open(&p)?))
|
||||
}
|
||||
(SourceKind::CompressedAudio, StreamOpen::Source { src, ext }) => {
|
||||
Ok(StreamSource::Compressed(CompressedReader::open_source(src, ext.as_deref())?))
|
||||
}
|
||||
(SourceKind::VideoAudio, StreamOpen::Path(p)) => {
|
||||
Ok(StreamSource::Video(VideoAudioReader::open(&p)?))
|
||||
}
|
||||
(SourceKind::VideoAudio, StreamOpen::Source { src, ext }) => {
|
||||
Ok(StreamSource::Video(VideoAudioReader::open_source(src, ext.as_deref())?))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sample_rate(&self) -> u32 {
|
||||
match self {
|
||||
StreamSource::Compressed(r) => r.sample_rate,
|
||||
StreamSource::Video(r) => r.sample_rate,
|
||||
}
|
||||
}
|
||||
|
||||
fn channels(&self) -> u32 {
|
||||
match self {
|
||||
StreamSource::Compressed(r) => r.channels,
|
||||
StreamSource::Video(r) => r.channels,
|
||||
}
|
||||
}
|
||||
|
||||
fn seek(&mut self, target_frame: u64) -> Result<u64, String> {
|
||||
match self {
|
||||
StreamSource::Compressed(r) => r.seek(target_frame),
|
||||
StreamSource::Video(r) => r.seek(target_frame),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_next(&mut self, out: &mut Vec<f32>) -> Result<usize, String> {
|
||||
match self {
|
||||
StreamSource::Compressed(r) => r.decode_next(out),
|
||||
StreamSource::Video(r) => r.decode_next(out),
|
||||
}
|
||||
}
|
||||
|
||||
fn total_frames(&self) -> u64 {
|
||||
match self {
|
||||
StreamSource::Compressed(r) => r.total_frames(),
|
||||
StreamSource::Video(r) => r.total_frames(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode a media source end-to-end and build its [`WaveformPyramid`] overview,
|
||||
/// streaming — only one decode chunk plus the (bounded) pyramid are ever in
|
||||
/// memory, never the full sample buffer. `floor_samples_per_texel` is the
|
||||
/// finest-level resolution (see [`crate::audio::waveform_pyramid`]).
|
||||
pub fn build_waveform_pyramid(
|
||||
path: &Path,
|
||||
kind: SourceKind,
|
||||
floor_samples_per_texel: u32,
|
||||
) -> Result<crate::audio::waveform_pyramid::WaveformPyramid, String> {
|
||||
let src = StreamSource::open(StreamOpen::Path(path.to_path_buf()), kind)?;
|
||||
build_pyramid_from_streamsource(src, floor_samples_per_texel)
|
||||
}
|
||||
|
||||
/// Build a waveform pyramid from a host-provided byte source (container-packed
|
||||
/// compressed audio) — the load-time counterpart of [`build_waveform_pyramid`]
|
||||
/// for media that has no filesystem path.
|
||||
pub fn build_waveform_pyramid_from_source(
|
||||
src: Box<dyn MediaByteSource>,
|
||||
ext: Option<&str>,
|
||||
floor_samples_per_texel: u32,
|
||||
) -> Result<crate::audio::waveform_pyramid::WaveformPyramid, String> {
|
||||
let src = StreamSource::open(
|
||||
StreamOpen::Source { src, ext: ext.map(|s| s.to_string()) },
|
||||
SourceKind::CompressedAudio,
|
||||
)?;
|
||||
build_pyramid_from_streamsource(src, floor_samples_per_texel)
|
||||
}
|
||||
|
||||
fn build_pyramid_from_streamsource(
|
||||
mut src: StreamSource,
|
||||
floor_samples_per_texel: u32,
|
||||
) -> Result<crate::audio::waveform_pyramid::WaveformPyramid, String> {
|
||||
use crate::audio::waveform_pyramid::WaveformPyramidBuilder;
|
||||
|
||||
let channels = src.channels();
|
||||
let mut builder = WaveformPyramidBuilder::new(channels, floor_samples_per_texel);
|
||||
builder.reserve_for_frames(src.total_frames());
|
||||
|
||||
let mut buf = Vec::new();
|
||||
loop {
|
||||
let frames = src.decode_next(&mut buf)?;
|
||||
if frames == 0 {
|
||||
break;
|
||||
}
|
||||
builder.push_interleaved(&buf);
|
||||
}
|
||||
Ok(builder.finish())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// DiskReaderCommand
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Commands sent from the engine to the disk reader thread.
|
||||
pub enum DiskReaderCommand {
|
||||
/// Start streaming a compressed file for a clip instance.
|
||||
/// Start streaming a file for a clip instance, using the decoder backend
|
||||
/// selected by `kind` (compressed audio vs. a video's audio track). `open`
|
||||
/// is either a filesystem path (referenced media / video) or a host-provided
|
||||
/// byte stream (container-packed media).
|
||||
ActivateFile {
|
||||
reader_id: u64,
|
||||
path: PathBuf,
|
||||
open: StreamOpen,
|
||||
kind: SourceKind,
|
||||
buffer: Arc<ReadAheadBuffer>,
|
||||
},
|
||||
/// Stop streaming for a clip instance.
|
||||
@@ -529,7 +1071,7 @@ impl DiskReader {
|
||||
mut command_rx: rtrb::Consumer<DiskReaderCommand>,
|
||||
running: Arc<AtomicBool>,
|
||||
) {
|
||||
let mut active_files: HashMap<u64, (CompressedReader, Arc<ReadAheadBuffer>)> =
|
||||
let mut active_files: HashMap<u64, (StreamSource, Arc<ReadAheadBuffer>)> =
|
||||
HashMap::new();
|
||||
let mut decode_buf = Vec::with_capacity(8192);
|
||||
|
||||
@@ -539,18 +1081,19 @@ impl DiskReader {
|
||||
match cmd {
|
||||
DiskReaderCommand::ActivateFile {
|
||||
reader_id,
|
||||
path,
|
||||
open,
|
||||
kind,
|
||||
buffer,
|
||||
} => match CompressedReader::open(&path) {
|
||||
} => match StreamSource::open(open, kind) {
|
||||
Ok(reader) => {
|
||||
eprintln!("[DiskReader] Activated reader={}, ch={}, sr={}, path={:?}",
|
||||
reader_id, reader.channels, reader.sample_rate, path);
|
||||
eprintln!("[DiskReader] Activated reader={}, kind={:?}, ch={}, sr={}",
|
||||
reader_id, kind, reader.channels(), reader.sample_rate());
|
||||
active_files.insert(reader_id, (reader, buffer));
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!(
|
||||
"[DiskReader] Failed to open compressed file {:?}: {}",
|
||||
path, e
|
||||
"[DiskReader] Failed to open reader={} ({:?}): {}",
|
||||
reader_id, kind, e
|
||||
);
|
||||
}
|
||||
},
|
||||
@@ -588,7 +1131,7 @@ impl DiskReader {
|
||||
|
||||
// If the target has jumped behind or far ahead of the buffer,
|
||||
// seek the decoder and reset.
|
||||
if target < buf_start || target > buf_end + reader.sample_rate as u64 {
|
||||
if target < buf_start || target > buf_end + reader.sample_rate() as u64 {
|
||||
buffer.reset(target);
|
||||
let _ = reader.seek(target);
|
||||
continue;
|
||||
@@ -607,7 +1150,7 @@ impl DiskReader {
|
||||
let buf_valid = buffer.valid_frames_count();
|
||||
let buf_end = buf_start + buf_valid;
|
||||
let prefetch_target =
|
||||
target + (PREFETCH_SECONDS * reader.sample_rate as f64) as u64;
|
||||
target + (PREFETCH_SECONDS * reader.sample_rate() as f64) as u64;
|
||||
|
||||
if buf_end >= prefetch_target {
|
||||
continue; // Already filled far enough ahead.
|
||||
@@ -615,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);
|
||||
@@ -649,3 +1197,7 @@ impl Drop for DiskReader {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tests for VideoAudioReader live in `daw-backend/tests/video_audio_stream.rs`
|
||||
// (integration tests) so they build the lib in normal mode, independent of
|
||||
// pre-existing breakage in the crate's `#[cfg(test)]` unit tests (automation.rs).
|
||||
|
||||
+357
-190
File diff suppressed because it is too large
Load Diff
@@ -2,6 +2,8 @@ use super::buffer_pool::BufferPool;
|
||||
use super::pool::AudioPool;
|
||||
use super::project::Project;
|
||||
use crate::command::AudioEvent;
|
||||
use crate::tempo_map::TempoMap;
|
||||
use crate::time::Seconds;
|
||||
use std::path::Path;
|
||||
|
||||
/// Render chunk size for offline export. Matches the real-time playback buffer size
|
||||
@@ -42,10 +44,12 @@ pub struct ExportSettings {
|
||||
pub bit_depth: u16,
|
||||
/// MP3 bitrate in kbps (128, 192, 256, 320)
|
||||
pub mp3_bitrate: u32,
|
||||
/// Start time in seconds
|
||||
pub start_time: f64,
|
||||
/// End time in seconds
|
||||
pub end_time: f64,
|
||||
/// Start time
|
||||
pub start_time: Seconds,
|
||||
/// End time
|
||||
pub end_time: Seconds,
|
||||
/// Tempo map for beat-position scheduling
|
||||
pub tempo_map: TempoMap,
|
||||
}
|
||||
|
||||
impl Default for ExportSettings {
|
||||
@@ -56,8 +60,9 @@ impl Default for ExportSettings {
|
||||
channels: 2,
|
||||
bit_depth: 16,
|
||||
mp3_bitrate: 320,
|
||||
start_time: 0.0,
|
||||
end_time: 60.0,
|
||||
start_time: Seconds::ZERO,
|
||||
end_time: Seconds(60.0),
|
||||
tempo_map: TempoMap::constant(120.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -79,15 +84,15 @@ pub fn export_audio<P: AsRef<Path>>(
|
||||
{
|
||||
// Validate duration
|
||||
let duration = settings.end_time - settings.start_time;
|
||||
if duration <= 0.0 {
|
||||
if duration <= Seconds::ZERO {
|
||||
return Err(format!(
|
||||
"Export duration is zero or negative (start={:.3}s, end={:.3}s). \
|
||||
Check that the timeline has content.",
|
||||
settings.start_time, settings.end_time
|
||||
settings.start_time.seconds_to_f64(), settings.end_time.seconds_to_f64()
|
||||
));
|
||||
}
|
||||
|
||||
let total_frames = (duration * settings.sample_rate as f64).round() as usize;
|
||||
let total_frames = (duration.seconds_to_f64() * settings.sample_rate as f64).round() as usize;
|
||||
if total_frames == 0 {
|
||||
return Err("Export would produce zero audio frames".to_string());
|
||||
}
|
||||
@@ -148,11 +153,11 @@ pub fn render_to_memory(
|
||||
{
|
||||
// Calculate total number of frames
|
||||
let duration = settings.end_time - settings.start_time;
|
||||
let total_frames = (duration * settings.sample_rate as f64).round() as usize;
|
||||
let total_frames = (duration.seconds_to_f64() * settings.sample_rate as f64).round() as usize;
|
||||
let total_samples = total_frames * settings.channels as usize;
|
||||
|
||||
println!("Export: duration={:.3}s, total_frames={}, total_samples={}, channels={}",
|
||||
duration, total_frames, total_samples, settings.channels);
|
||||
duration.seconds_to_f64(), total_frames, total_samples, settings.channels);
|
||||
|
||||
let chunk_samples = EXPORT_CHUNK_FRAMES * settings.channels as usize;
|
||||
|
||||
@@ -178,6 +183,7 @@ pub fn render_to_memory(
|
||||
pool,
|
||||
&mut buffer_pool,
|
||||
playhead,
|
||||
&settings.tempo_map,
|
||||
settings.sample_rate,
|
||||
settings.channels,
|
||||
false,
|
||||
@@ -185,9 +191,9 @@ pub fn render_to_memory(
|
||||
|
||||
// Calculate how many samples we actually need from this chunk
|
||||
let remaining_time = settings.end_time - playhead;
|
||||
let samples_needed = if remaining_time < chunk_duration {
|
||||
let samples_needed = if remaining_time.seconds_to_f64() < chunk_duration {
|
||||
// Calculate frames needed and ensure it's a whole number
|
||||
let frames_needed = (remaining_time * settings.sample_rate as f64).round() as usize;
|
||||
let frames_needed = (remaining_time.seconds_to_f64() * settings.sample_rate as f64).round() as usize;
|
||||
let samples = frames_needed * settings.channels as usize;
|
||||
// Ensure we don't exceed chunk size
|
||||
samples.min(chunk_samples)
|
||||
@@ -207,7 +213,7 @@ pub fn render_to_memory(
|
||||
});
|
||||
}
|
||||
|
||||
playhead += chunk_duration;
|
||||
playhead = playhead + Seconds(chunk_duration);
|
||||
}
|
||||
|
||||
println!("Export: rendered {} samples total", all_samples.len());
|
||||
@@ -361,7 +367,7 @@ fn export_mp3<P: AsRef<Path>>(
|
||||
|
||||
// Calculate rendering parameters
|
||||
let duration = settings.end_time - settings.start_time;
|
||||
let total_frames = (duration * settings.sample_rate as f64).round() as usize;
|
||||
let total_frames = (duration.seconds_to_f64() * settings.sample_rate as f64).round() as usize;
|
||||
|
||||
let chunk_samples = EXPORT_CHUNK_FRAMES * settings.channels as usize;
|
||||
let chunk_duration = EXPORT_CHUNK_FRAMES as f64 / settings.sample_rate as f64;
|
||||
@@ -396,6 +402,7 @@ fn export_mp3<P: AsRef<Path>>(
|
||||
pool,
|
||||
&mut buffer_pool,
|
||||
playhead,
|
||||
&settings.tempo_map,
|
||||
settings.sample_rate,
|
||||
settings.channels,
|
||||
false,
|
||||
@@ -403,8 +410,8 @@ fn export_mp3<P: AsRef<Path>>(
|
||||
|
||||
// Calculate how many samples we need from this chunk
|
||||
let remaining_time = settings.end_time - playhead;
|
||||
let samples_needed = if remaining_time < chunk_duration {
|
||||
((remaining_time * settings.sample_rate as f64) as usize * settings.channels as usize)
|
||||
let samples_needed = if remaining_time.seconds_to_f64() < chunk_duration {
|
||||
((remaining_time.seconds_to_f64() * settings.sample_rate as f64) as usize * settings.channels as usize)
|
||||
.min(chunk_samples)
|
||||
} else {
|
||||
chunk_samples
|
||||
@@ -445,7 +452,7 @@ fn export_mp3<P: AsRef<Path>>(
|
||||
}
|
||||
}
|
||||
|
||||
playhead += chunk_duration;
|
||||
playhead = playhead + Seconds(chunk_duration);
|
||||
}
|
||||
|
||||
// Encode any remaining samples as the final frame
|
||||
@@ -529,7 +536,7 @@ fn export_aac<P: AsRef<Path>>(
|
||||
|
||||
// Calculate rendering parameters
|
||||
let duration = settings.end_time - settings.start_time;
|
||||
let total_frames = (duration * settings.sample_rate as f64).round() as usize;
|
||||
let total_frames = (duration.seconds_to_f64() * settings.sample_rate as f64).round() as usize;
|
||||
|
||||
let chunk_samples = EXPORT_CHUNK_FRAMES * settings.channels as usize;
|
||||
let chunk_duration = EXPORT_CHUNK_FRAMES as f64 / settings.sample_rate as f64;
|
||||
@@ -564,6 +571,7 @@ fn export_aac<P: AsRef<Path>>(
|
||||
pool,
|
||||
&mut buffer_pool,
|
||||
playhead,
|
||||
&settings.tempo_map,
|
||||
settings.sample_rate,
|
||||
settings.channels,
|
||||
false,
|
||||
@@ -571,8 +579,8 @@ fn export_aac<P: AsRef<Path>>(
|
||||
|
||||
// Calculate how many samples we need from this chunk
|
||||
let remaining_time = settings.end_time - playhead;
|
||||
let samples_needed = if remaining_time < chunk_duration {
|
||||
((remaining_time * settings.sample_rate as f64) as usize * settings.channels as usize)
|
||||
let samples_needed = if remaining_time.seconds_to_f64() < chunk_duration {
|
||||
((remaining_time.seconds_to_f64() * settings.sample_rate as f64) as usize * settings.channels as usize)
|
||||
.min(chunk_samples)
|
||||
} else {
|
||||
chunk_samples
|
||||
@@ -613,7 +621,7 @@ fn export_aac<P: AsRef<Path>>(
|
||||
}
|
||||
}
|
||||
|
||||
playhead += chunk_duration;
|
||||
playhead = playhead + Seconds(chunk_duration);
|
||||
}
|
||||
|
||||
// Encode any remaining samples as the final frame
|
||||
@@ -663,14 +671,39 @@ fn convert_chunk_to_planar_i16(interleaved: &[f32], channels: u32) -> Vec<Vec<i1
|
||||
planar
|
||||
}
|
||||
|
||||
/// Convert a chunk of interleaved f32 samples to planar f32 format
|
||||
/// Convert a chunk of interleaved f32 samples to planar f32 format.
|
||||
///
|
||||
/// Non-finite samples (NaN/±Inf) are replaced with `0.0` and finite samples are
|
||||
/// clamped to `[-1.0, 1.0]`: the float encoders (e.g. AAC, which takes `fltp`)
|
||||
/// reject a frame outright on "(near) NaN/+-Inf", failing the whole export, so we
|
||||
/// sanitize here exactly as the integer paths already clamp.
|
||||
fn convert_chunk_to_planar_f32(interleaved: &[f32], channels: u32) -> Vec<Vec<f32>> {
|
||||
let num_frames = interleaved.len() / channels as usize;
|
||||
let mut planar = vec![vec![0.0f32; num_frames]; channels as usize];
|
||||
|
||||
let mut non_finite = 0u64;
|
||||
for (i, chunk) in interleaved.chunks(channels as usize).enumerate() {
|
||||
for (ch, &sample) in chunk.iter().enumerate() {
|
||||
planar[ch][i] = sample;
|
||||
planar[ch][i] = if sample.is_finite() {
|
||||
sample.clamp(-1.0, 1.0)
|
||||
} else {
|
||||
non_finite += 1;
|
||||
0.0
|
||||
};
|
||||
}
|
||||
}
|
||||
if non_finite > 0 {
|
||||
// One-time warning: we sanitized rather than failed, but a non-finite
|
||||
// sample reaching here means something upstream (an effect, automation,
|
||||
// or a source decode) produced NaN/Inf — worth chasing if audio is wrong.
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
static WARNED: AtomicBool = AtomicBool::new(false);
|
||||
if !WARNED.swap(true, Ordering::Relaxed) {
|
||||
eprintln!(
|
||||
"⚠️ [EXPORT] sanitized {} non-finite (NaN/Inf) audio sample(s) in a chunk — \
|
||||
check effects/automation/source decode",
|
||||
non_finite
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+57
-149
@@ -1,8 +1,10 @@
|
||||
use crate::time::Beats;
|
||||
|
||||
/// MIDI event representing a single MIDI message
|
||||
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MidiEvent {
|
||||
/// Time position within the clip in seconds (sample-rate independent)
|
||||
pub timestamp: f64,
|
||||
/// Time position in beats (quarter-note beats)
|
||||
pub timestamp: Beats,
|
||||
/// MIDI status byte (includes channel)
|
||||
pub status: u8,
|
||||
/// First data byte (note number, CC number, etc.)
|
||||
@@ -12,55 +14,28 @@ pub struct MidiEvent {
|
||||
}
|
||||
|
||||
impl MidiEvent {
|
||||
/// Create a new MIDI event
|
||||
pub fn new(timestamp: f64, status: u8, data1: u8, data2: u8) -> Self {
|
||||
Self {
|
||||
timestamp,
|
||||
status,
|
||||
data1,
|
||||
data2,
|
||||
}
|
||||
pub fn new(timestamp: Beats, status: u8, data1: u8, data2: u8) -> Self {
|
||||
Self { timestamp, status, data1, data2 }
|
||||
}
|
||||
|
||||
/// Create a note on event
|
||||
pub fn note_on(timestamp: f64, channel: u8, note: u8, velocity: u8) -> Self {
|
||||
Self {
|
||||
timestamp,
|
||||
status: 0x90 | (channel & 0x0F),
|
||||
data1: note,
|
||||
data2: velocity,
|
||||
}
|
||||
pub fn note_on(timestamp: Beats, channel: u8, note: u8, velocity: u8) -> Self {
|
||||
Self { timestamp, status: 0x90 | (channel & 0x0F), data1: note, data2: velocity }
|
||||
}
|
||||
|
||||
/// Create a note off event
|
||||
pub fn note_off(timestamp: f64, channel: u8, note: u8, velocity: u8) -> Self {
|
||||
Self {
|
||||
timestamp,
|
||||
status: 0x80 | (channel & 0x0F),
|
||||
data1: note,
|
||||
data2: velocity,
|
||||
}
|
||||
pub fn note_off(timestamp: Beats, channel: u8, note: u8, velocity: u8) -> Self {
|
||||
Self { timestamp, status: 0x80 | (channel & 0x0F), data1: note, data2: velocity }
|
||||
}
|
||||
|
||||
/// Check if this is a note on event (with non-zero velocity)
|
||||
pub fn is_note_on(&self) -> bool {
|
||||
(self.status & 0xF0) == 0x90 && self.data2 > 0
|
||||
}
|
||||
|
||||
/// Check if this is a note off event (or note on with zero velocity)
|
||||
pub fn is_note_off(&self) -> bool {
|
||||
(self.status & 0xF0) == 0x80 || ((self.status & 0xF0) == 0x90 && self.data2 == 0)
|
||||
}
|
||||
|
||||
/// Get the MIDI channel (0-15)
|
||||
pub fn channel(&self) -> u8 {
|
||||
self.status & 0x0F
|
||||
}
|
||||
|
||||
/// Get the message type (upper 4 bits of status)
|
||||
pub fn message_type(&self) -> u8 {
|
||||
self.status & 0xF0
|
||||
}
|
||||
pub fn channel(&self) -> u8 { self.status & 0x0F }
|
||||
pub fn message_type(&self) -> u8 { self.status & 0xF0 }
|
||||
}
|
||||
|
||||
/// MIDI clip ID type (for clips stored in the pool)
|
||||
@@ -69,179 +44,118 @@ pub type MidiClipId = u32;
|
||||
/// MIDI clip instance ID type (for instances placed on tracks)
|
||||
pub type MidiClipInstanceId = u32;
|
||||
|
||||
/// MIDI clip content - stores the actual MIDI events
|
||||
///
|
||||
/// This represents the content data stored in the MidiClipPool.
|
||||
/// Events have timestamps relative to the start of the clip (0.0 = clip beginning).
|
||||
/// MIDI clip content — stores the actual MIDI events.
|
||||
/// `duration` is in beats.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MidiClip {
|
||||
pub id: MidiClipId,
|
||||
pub events: Vec<MidiEvent>,
|
||||
pub duration: f64, // Total content duration in seconds
|
||||
/// Total content duration in beats
|
||||
pub duration: Beats,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
impl MidiClip {
|
||||
/// Create a new MIDI clip with content
|
||||
pub fn new(id: MidiClipId, events: Vec<MidiEvent>, duration: f64, name: String) -> Self {
|
||||
let mut clip = Self {
|
||||
id,
|
||||
events,
|
||||
duration,
|
||||
name,
|
||||
};
|
||||
// Sort events by timestamp
|
||||
pub fn new(id: MidiClipId, events: Vec<MidiEvent>, duration: Beats, name: String) -> Self {
|
||||
let mut clip = Self { id, events, duration, name };
|
||||
clip.events.sort_by(|a, b| a.timestamp.partial_cmp(&b.timestamp).unwrap());
|
||||
clip
|
||||
}
|
||||
|
||||
/// Create an empty MIDI clip
|
||||
pub fn empty(id: MidiClipId, duration: f64, name: String) -> Self {
|
||||
Self {
|
||||
id,
|
||||
events: Vec::new(),
|
||||
duration,
|
||||
name,
|
||||
}
|
||||
pub fn empty(id: MidiClipId, duration: Beats, name: String) -> Self {
|
||||
Self { id, events: Vec::new(), duration, name }
|
||||
}
|
||||
|
||||
/// Add a MIDI event to the clip
|
||||
pub fn add_event(&mut self, event: MidiEvent) {
|
||||
self.events.push(event);
|
||||
// Keep events sorted by timestamp
|
||||
self.events.sort_by(|a, b| a.timestamp.partial_cmp(&b.timestamp).unwrap());
|
||||
}
|
||||
|
||||
/// Get events within a time range (relative to clip start)
|
||||
/// This is used by MidiClipInstance to fetch events for a given portion
|
||||
pub fn get_events_in_range(&self, start: f64, end: f64) -> Vec<MidiEvent> {
|
||||
self.events
|
||||
.iter()
|
||||
/// Get events within a beat range (relative to clip start)
|
||||
pub fn get_events_in_range(&self, start: Beats, end: Beats) -> Vec<MidiEvent> {
|
||||
self.events.iter()
|
||||
.filter(|e| e.timestamp >= start && e.timestamp < end)
|
||||
.copied()
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// MIDI clip instance - a reference to MidiClip content with timeline positioning
|
||||
/// MIDI clip instance — a reference to MidiClip content with timeline positioning.
|
||||
///
|
||||
/// ## Timing Model
|
||||
/// - `internal_start` / `internal_end`: Define the region of the source clip to play (trimming)
|
||||
/// - `external_start` / `external_duration`: Define where the instance appears on the timeline and how long
|
||||
///
|
||||
/// ## Looping
|
||||
/// If `external_duration` is greater than `internal_end - internal_start`,
|
||||
/// the instance will seamlessly loop back to `internal_start` when it reaches `internal_end`.
|
||||
/// All timing fields are in beats.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MidiClipInstance {
|
||||
pub id: MidiClipInstanceId,
|
||||
pub clip_id: MidiClipId, // Reference to MidiClip in pool
|
||||
pub clip_id: MidiClipId,
|
||||
|
||||
/// Start position within the clip content (seconds)
|
||||
pub internal_start: f64,
|
||||
/// End position within the clip content (seconds)
|
||||
pub internal_end: f64,
|
||||
/// Start of the trimmed region within the clip content (beats)
|
||||
pub internal_start: Beats,
|
||||
/// End of the trimmed region within the clip content (beats)
|
||||
pub internal_end: Beats,
|
||||
|
||||
/// Start position on the timeline (seconds)
|
||||
pub external_start: f64,
|
||||
/// Duration on the timeline (seconds) - can be longer than internal duration for looping
|
||||
pub external_duration: f64,
|
||||
/// Start position on the timeline (beats)
|
||||
pub external_start: Beats,
|
||||
/// Duration on the timeline (beats); > internal duration = looping
|
||||
pub external_duration: Beats,
|
||||
}
|
||||
|
||||
impl MidiClipInstance {
|
||||
/// Create a new MIDI clip instance
|
||||
pub fn new(
|
||||
id: MidiClipInstanceId,
|
||||
clip_id: MidiClipId,
|
||||
internal_start: f64,
|
||||
internal_end: f64,
|
||||
external_start: f64,
|
||||
external_duration: f64,
|
||||
internal_start: Beats,
|
||||
internal_end: Beats,
|
||||
external_start: Beats,
|
||||
external_duration: Beats,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
clip_id,
|
||||
internal_start,
|
||||
internal_end,
|
||||
external_start,
|
||||
external_duration,
|
||||
}
|
||||
Self { id, clip_id, internal_start, internal_end, external_start, external_duration }
|
||||
}
|
||||
|
||||
/// Create an instance that uses the full clip content (no trimming, no looping)
|
||||
/// Create an instance covering the full clip with no trim
|
||||
pub fn from_full_clip(
|
||||
id: MidiClipInstanceId,
|
||||
clip_id: MidiClipId,
|
||||
clip_duration: f64,
|
||||
external_start: f64,
|
||||
clip_duration: Beats,
|
||||
external_start: Beats,
|
||||
) -> Self {
|
||||
Self {
|
||||
id,
|
||||
clip_id,
|
||||
internal_start: 0.0,
|
||||
internal_start: Beats::ZERO,
|
||||
internal_end: clip_duration,
|
||||
external_start,
|
||||
external_duration: clip_duration,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the internal (content) duration
|
||||
pub fn internal_duration(&self) -> f64 {
|
||||
self.internal_end - self.internal_start
|
||||
}
|
||||
pub fn internal_duration(&self) -> Beats { self.internal_end - self.internal_start }
|
||||
pub fn external_end(&self) -> Beats { self.external_start + self.external_duration }
|
||||
pub fn is_looping(&self) -> bool { self.external_duration > self.internal_duration() }
|
||||
|
||||
/// Get the end time on the timeline
|
||||
pub fn external_end(&self) -> f64 {
|
||||
self.external_start + self.external_duration
|
||||
}
|
||||
|
||||
/// Check if this instance loops
|
||||
pub fn is_looping(&self) -> bool {
|
||||
self.external_duration > self.internal_duration()
|
||||
}
|
||||
|
||||
/// Get the end time on the timeline (for backwards compatibility)
|
||||
pub fn end_time(&self) -> f64 {
|
||||
self.external_end()
|
||||
}
|
||||
|
||||
/// Get the start time on the timeline (for backwards compatibility)
|
||||
pub fn start_time(&self) -> f64 {
|
||||
self.external_start
|
||||
}
|
||||
|
||||
/// Check if this instance overlaps with a time range
|
||||
pub fn overlaps_range(&self, range_start: f64, range_end: f64) -> bool {
|
||||
/// Check if this instance overlaps with a beat range
|
||||
pub fn overlaps_range(&self, range_start: Beats, range_end: Beats) -> bool {
|
||||
self.external_start < range_end && self.external_end() > range_start
|
||||
}
|
||||
|
||||
/// Get events that should be triggered in a given timeline range
|
||||
///
|
||||
/// This handles:
|
||||
/// - Trimming (internal_start/internal_end)
|
||||
/// - Looping (when external duration > internal duration)
|
||||
/// - Time mapping from timeline to clip content
|
||||
///
|
||||
/// Returns events with timestamps adjusted to timeline time (not clip-relative)
|
||||
/// Get events that should fire in a given beat range on the timeline.
|
||||
/// Returns events with `timestamp` set to their global timeline beat position.
|
||||
pub fn get_events_in_range(
|
||||
&self,
|
||||
clip: &MidiClip,
|
||||
range_start_seconds: f64,
|
||||
range_end_seconds: f64,
|
||||
range_start: Beats,
|
||||
range_end: Beats,
|
||||
) -> Vec<MidiEvent> {
|
||||
let mut result = Vec::new();
|
||||
|
||||
// Check if instance overlaps with the range
|
||||
if !self.overlaps_range(range_start_seconds, range_end_seconds) {
|
||||
if !self.overlaps_range(range_start, range_end) {
|
||||
return result;
|
||||
}
|
||||
|
||||
let internal_duration = self.internal_duration();
|
||||
if internal_duration <= 0.0 {
|
||||
if internal_duration <= Beats::ZERO {
|
||||
return result;
|
||||
}
|
||||
|
||||
// Calculate how many complete loops fit in the external duration
|
||||
let num_loops = if self.external_duration > internal_duration {
|
||||
(self.external_duration / internal_duration).ceil() as usize
|
||||
} else {
|
||||
@@ -251,24 +165,18 @@ impl MidiClipInstance {
|
||||
let external_end = self.external_end();
|
||||
|
||||
for loop_idx in 0..num_loops {
|
||||
let loop_offset = loop_idx as f64 * internal_duration;
|
||||
let loop_offset = internal_duration * loop_idx as f64;
|
||||
|
||||
// Get events from the clip that fall within the internal range
|
||||
for event in &clip.events {
|
||||
// Skip events outside the trimmed region
|
||||
// Use > (not >=) for internal_end so note-offs at the clip boundary are included
|
||||
if event.timestamp < self.internal_start || event.timestamp > self.internal_end {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Convert to timeline time
|
||||
let relative_content_time = event.timestamp - self.internal_start;
|
||||
let timeline_time = self.external_start + loop_offset + relative_content_time;
|
||||
|
||||
// Check if within current buffer range and instance bounds
|
||||
// Use <= for external_end so note-offs at the clip boundary are included
|
||||
if timeline_time >= range_start_seconds
|
||||
&& timeline_time < range_end_seconds
|
||||
if timeline_time >= range_start
|
||||
&& timeline_time < range_end
|
||||
&& timeline_time <= external_end
|
||||
{
|
||||
let mut adjusted_event = *event;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use serde::{Serialize, Deserialize};
|
||||
use std::collections::HashMap;
|
||||
use super::midi::{MidiClip, MidiClipId, MidiEvent};
|
||||
use crate::time::Beats;
|
||||
|
||||
/// Pool for storing MIDI clip content
|
||||
/// Similar to AudioClipPool but for MIDI data
|
||||
@@ -21,7 +22,7 @@ impl MidiClipPool {
|
||||
|
||||
/// Add a new clip to the pool with the given events and duration
|
||||
/// Returns the ID of the newly created clip
|
||||
pub fn add_clip(&mut self, events: Vec<MidiEvent>, duration: f64, name: String) -> MidiClipId {
|
||||
pub fn add_clip(&mut self, events: Vec<MidiEvent>, duration: Beats, name: String) -> MidiClipId {
|
||||
let id = self.next_id;
|
||||
self.next_id += 1;
|
||||
|
||||
|
||||
@@ -15,10 +15,12 @@ pub mod recording;
|
||||
pub mod sample_loader;
|
||||
pub mod track;
|
||||
pub mod waveform_cache;
|
||||
pub mod waveform_pyramid;
|
||||
|
||||
pub use automation::{AutomationLane, AutomationLaneId, AutomationPoint, CurveType, ParameterId};
|
||||
pub use buffer_pool::BufferPool;
|
||||
pub use clip::{AudioClipInstance, AudioClipInstanceId, Clip, ClipId};
|
||||
pub use disk_reader::{AudioBlobSourceFactory, MediaByteSource};
|
||||
pub use engine::{AudioClipSnapshot, Engine, EngineController};
|
||||
pub use export::{export_audio, ExportFormat, ExportSettings};
|
||||
pub use metronome::Metronome;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::node_trait::AudioNode;
|
||||
use super::types::{ConnectionError, SignalType};
|
||||
use crate::audio::midi::MidiEvent;
|
||||
use crate::time::Beats;
|
||||
use petgraph::algo::has_path_connecting;
|
||||
use petgraph::stable_graph::{NodeIndex, StableGraph};
|
||||
use petgraph::visit::{EdgeRef, IntoEdgeReferences};
|
||||
@@ -93,8 +94,8 @@ pub struct AudioGraph {
|
||||
/// UI positions for nodes (node_index -> (x, y))
|
||||
node_positions: std::collections::HashMap<u32, (f32, f32)>,
|
||||
|
||||
/// Current playback time (for automation nodes)
|
||||
playback_time: f64,
|
||||
/// Current playback time in beats (for automation nodes)
|
||||
playback_time: Beats,
|
||||
|
||||
/// Project tempo (synced from Engine via SetTempo)
|
||||
bpm: f32,
|
||||
@@ -123,7 +124,7 @@ impl AudioGraph {
|
||||
// Pre-allocate MIDI input buffers (max 128 events per port)
|
||||
midi_input_buffers: (0..16).map(|_| Vec::with_capacity(128)).collect(),
|
||||
node_positions: std::collections::HashMap::new(),
|
||||
playback_time: 0.0,
|
||||
playback_time: Beats::ZERO,
|
||||
bpm: 120.0,
|
||||
beats_per_bar: 4,
|
||||
topo_cache: None,
|
||||
@@ -475,7 +476,7 @@ impl AudioGraph {
|
||||
}
|
||||
|
||||
/// Process the graph and produce audio output
|
||||
pub fn process(&mut self, output_buffer: &mut [f32], midi_events: &[MidiEvent], playback_time: f64) {
|
||||
pub fn process(&mut self, output_buffer: &mut [f32], midi_events: &[MidiEvent], playback_time: Beats) {
|
||||
// Update playback time
|
||||
self.playback_time = playback_time;
|
||||
|
||||
@@ -484,6 +485,7 @@ impl AudioGraph {
|
||||
for node in self.graph.node_weights_mut() {
|
||||
if let Some(auto_node) = node.node.as_any_mut().downcast_mut::<AutomationInputNode>() {
|
||||
auto_node.set_playback_time(playback_time);
|
||||
auto_node.set_bpm(self.bpm as f64);
|
||||
} else if let Some(beat_node) = node.node.as_any_mut().downcast_mut::<BeatNode>() {
|
||||
beat_node.set_playback_time(playback_time);
|
||||
beat_node.set_tempo(self.bpm, self.beats_per_bar);
|
||||
@@ -1009,6 +1011,29 @@ impl AudioGraph {
|
||||
}
|
||||
}
|
||||
|
||||
// For AutomationInput nodes, serialize display name and keyframes
|
||||
if node.node_type() == "AutomationInput" {
|
||||
use crate::audio::node_graph::nodes::{AutomationInputNode, InterpolationType};
|
||||
use crate::audio::node_graph::preset::SerializedKeyframe;
|
||||
if let Some(auto_node) = node.as_any().downcast_ref::<AutomationInputNode>() {
|
||||
serialized.automation_display_name = Some(auto_node.display_name().to_string());
|
||||
serialized.automation_keyframes = auto_node.keyframes().iter().map(|kf| {
|
||||
SerializedKeyframe {
|
||||
time: kf.time.0,
|
||||
value: kf.value,
|
||||
interpolation: match kf.interpolation {
|
||||
InterpolationType::Linear => "linear",
|
||||
InterpolationType::Bezier => "bezier",
|
||||
InterpolationType::Step => "step",
|
||||
InterpolationType::Hold => "hold",
|
||||
}.to_string(),
|
||||
ease_out: kf.ease_out,
|
||||
ease_in: kf.ease_in,
|
||||
}
|
||||
}).collect();
|
||||
}
|
||||
}
|
||||
|
||||
// For AmpSim nodes, serialize the model path
|
||||
if node.node_type() == "AmpSim" {
|
||||
use crate::audio::node_graph::nodes::AmpSimNode;
|
||||
@@ -1322,6 +1347,35 @@ impl AudioGraph {
|
||||
}
|
||||
}
|
||||
|
||||
// Restore AutomationInput display name and keyframes
|
||||
if serialized_node.node_type == "AutomationInput" {
|
||||
use crate::audio::node_graph::nodes::{AutomationInputNode, AutomationKeyframe, InterpolationType};
|
||||
if let Some(graph_node) = graph.graph.node_weight_mut(node_idx) {
|
||||
if let Some(auto_node) = graph_node.node.as_any_mut().downcast_mut::<AutomationInputNode>() {
|
||||
if let Some(ref name) = serialized_node.automation_display_name {
|
||||
auto_node.set_display_name(name.clone());
|
||||
}
|
||||
if !serialized_node.automation_keyframes.is_empty() {
|
||||
auto_node.clear_keyframes();
|
||||
for kf in &serialized_node.automation_keyframes {
|
||||
auto_node.add_keyframe(AutomationKeyframe {
|
||||
time: crate::time::Beats(kf.time),
|
||||
value: kf.value,
|
||||
interpolation: match kf.interpolation.as_str() {
|
||||
"bezier" => InterpolationType::Bezier,
|
||||
"step" => InterpolationType::Step,
|
||||
"hold" => InterpolationType::Hold,
|
||||
_ => InterpolationType::Linear,
|
||||
},
|
||||
ease_out: kf.ease_out,
|
||||
ease_in: kf.ease_in,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Restore position
|
||||
graph.set_node_position(node_idx, serialized_node.position.0, serialized_node.position.1);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, SignalType};
|
||||
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
|
||||
use crate::audio::midi::MidiEvent;
|
||||
use crate::time::Beats;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
@@ -16,8 +17,7 @@ pub enum InterpolationType {
|
||||
/// A single keyframe in an automation curve
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AutomationKeyframe {
|
||||
/// Time in seconds (absolute project time)
|
||||
pub time: f64,
|
||||
pub time: Beats,
|
||||
/// CV output value
|
||||
pub value: f32,
|
||||
/// Interpolation type to next keyframe
|
||||
@@ -29,7 +29,7 @@ pub struct AutomationKeyframe {
|
||||
}
|
||||
|
||||
impl AutomationKeyframe {
|
||||
pub fn new(time: f64, value: f32) -> Self {
|
||||
pub fn new(time: Beats, value: f32) -> Self {
|
||||
Self {
|
||||
time,
|
||||
value,
|
||||
@@ -47,8 +47,10 @@ pub struct AutomationInputNode {
|
||||
keyframes: Vec<AutomationKeyframe>,
|
||||
outputs: Vec<NodePort>,
|
||||
parameters: Vec<Parameter>,
|
||||
/// Shared playback time (set by the graph before processing)
|
||||
playback_time: Arc<RwLock<f64>>,
|
||||
/// Shared playback time in beats (set by the graph before processing)
|
||||
playback_time: Arc<RwLock<Beats>>,
|
||||
/// Current BPM (set by the graph before processing, used for per-sample beat advancement)
|
||||
bpm: f64,
|
||||
/// Minimum output value (for UI display range)
|
||||
pub value_min: f32,
|
||||
/// Maximum output value (for UI display range)
|
||||
@@ -63,25 +65,34 @@ impl AutomationInputNode {
|
||||
NodePort::new("CV Out", SignalType::CV, 0),
|
||||
];
|
||||
|
||||
let parameters = vec![
|
||||
Parameter::new(0, "Min", f32::NEG_INFINITY, f32::INFINITY, -1.0, ParameterUnit::Generic),
|
||||
Parameter::new(1, "Max", f32::NEG_INFINITY, f32::INFINITY, 1.0, ParameterUnit::Generic),
|
||||
];
|
||||
|
||||
Self {
|
||||
name: name.clone(),
|
||||
display_name: "Automation".to_string(),
|
||||
keyframes: vec![AutomationKeyframe::new(0.0, 0.0)],
|
||||
keyframes: vec![AutomationKeyframe::new(Beats::ZERO, 0.0)],
|
||||
outputs,
|
||||
parameters: Vec::new(),
|
||||
playback_time: Arc::new(RwLock::new(0.0)),
|
||||
parameters,
|
||||
playback_time: Arc::new(RwLock::new(Beats::ZERO)),
|
||||
bpm: 120.0,
|
||||
value_min: -1.0,
|
||||
value_max: 1.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the playback time (called by graph before processing)
|
||||
pub fn set_playback_time(&mut self, time: f64) {
|
||||
pub fn set_playback_time(&mut self, time: Beats) {
|
||||
if let Ok(mut playback) = self.playback_time.write() {
|
||||
*playback = time;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_bpm(&mut self, bpm: f64) {
|
||||
self.bpm = bpm;
|
||||
}
|
||||
|
||||
/// Get the display name (shown in UI)
|
||||
pub fn display_name(&self) -> &str {
|
||||
&self.display_name
|
||||
@@ -111,8 +122,7 @@ impl AutomationInputNode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove keyframe at specific time (with tolerance)
|
||||
pub fn remove_keyframe_at_time(&mut self, time: f64, tolerance: f64) -> bool {
|
||||
pub fn remove_keyframe_at_time(&mut self, time: Beats, tolerance: Beats) -> bool {
|
||||
if let Some(idx) = self.keyframes.iter().position(|kf| (kf.time - time).abs() < tolerance) {
|
||||
self.keyframes.remove(idx);
|
||||
true
|
||||
@@ -121,10 +131,8 @@ impl AutomationInputNode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Update an existing keyframe
|
||||
pub fn update_keyframe(&mut self, keyframe: AutomationKeyframe) {
|
||||
// Remove old keyframe at this time, then add new one
|
||||
self.remove_keyframe_at_time(keyframe.time, 0.001);
|
||||
self.remove_keyframe_at_time(keyframe.time, Beats(0.001));
|
||||
self.add_keyframe(keyframe);
|
||||
}
|
||||
|
||||
@@ -138,24 +146,20 @@ impl AutomationInputNode {
|
||||
self.keyframes.clear();
|
||||
}
|
||||
|
||||
/// Evaluate curve at a specific time
|
||||
fn evaluate_at_time(&self, time: f64) -> f32 {
|
||||
fn evaluate_at_time(&self, time: Beats) -> f32 {
|
||||
if self.keyframes.is_empty() {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
// Before first keyframe
|
||||
if time <= self.keyframes[0].time {
|
||||
return self.keyframes[0].value;
|
||||
}
|
||||
|
||||
// After last keyframe
|
||||
let last_idx = self.keyframes.len() - 1;
|
||||
if time >= self.keyframes[last_idx].time {
|
||||
return self.keyframes[last_idx].value;
|
||||
}
|
||||
|
||||
// Find bracketing keyframes
|
||||
for i in 0..self.keyframes.len() - 1 {
|
||||
let kf1 = &self.keyframes[i];
|
||||
let kf2 = &self.keyframes[i + 1];
|
||||
@@ -168,14 +172,12 @@ impl AutomationInputNode {
|
||||
0.0
|
||||
}
|
||||
|
||||
/// Interpolate between two keyframes
|
||||
fn interpolate(&self, kf1: &AutomationKeyframe, kf2: &AutomationKeyframe, time: f64) -> f32 {
|
||||
// Calculate normalized position between keyframes (0.0 to 1.0)
|
||||
fn interpolate(&self, kf1: &AutomationKeyframe, kf2: &AutomationKeyframe, time: Beats) -> f32 {
|
||||
let t = if kf2.time == kf1.time {
|
||||
0.0
|
||||
0.0f64
|
||||
} else {
|
||||
((time - kf1.time) / (kf2.time - kf1.time)) as f32
|
||||
};
|
||||
(time - kf1.time) / (kf2.time - kf1.time)
|
||||
} as f32;
|
||||
|
||||
match kf1.interpolation {
|
||||
InterpolationType::Linear => {
|
||||
@@ -221,12 +223,20 @@ impl AudioNode for AutomationInputNode {
|
||||
&self.parameters
|
||||
}
|
||||
|
||||
fn set_parameter(&mut self, _id: u32, _value: f32) {
|
||||
// No parameters
|
||||
fn set_parameter(&mut self, id: u32, value: f32) {
|
||||
match id {
|
||||
0 => self.value_min = value,
|
||||
1 => self.value_max = value,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn get_parameter(&self, _id: u32) -> f32 {
|
||||
0.0
|
||||
fn get_parameter(&self, id: u32) -> f32 {
|
||||
match id {
|
||||
0 => self.value_min,
|
||||
1 => self.value_max,
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
fn process(
|
||||
@@ -244,19 +254,17 @@ impl AudioNode for AutomationInputNode {
|
||||
let output = &mut outputs[0];
|
||||
let length = output.len();
|
||||
|
||||
// Get the starting playback time
|
||||
let playhead = if let Ok(playback) = self.playback_time.read() {
|
||||
*playback
|
||||
} else {
|
||||
0.0
|
||||
Beats::ZERO
|
||||
};
|
||||
|
||||
// Calculate time per sample
|
||||
let sample_duration = 1.0 / sample_rate as f64;
|
||||
// Advance per sample in beats: beats_per_sample = bpm / 60 / sample_rate
|
||||
let beats_per_sample = self.bpm / 60.0 / sample_rate as f64;
|
||||
|
||||
// Evaluate curve for each sample
|
||||
for i in 0..length {
|
||||
let time = playhead + (i as f64 * sample_duration);
|
||||
let time = playhead + Beats(i as f64 * beats_per_sample);
|
||||
output[i] = self.evaluate_at_time(time);
|
||||
}
|
||||
}
|
||||
@@ -280,7 +288,8 @@ impl AudioNode for AutomationInputNode {
|
||||
keyframes: self.keyframes.clone(),
|
||||
outputs: self.outputs.clone(),
|
||||
parameters: self.parameters.clone(),
|
||||
playback_time: Arc::new(RwLock::new(0.0)),
|
||||
playback_time: Arc::new(RwLock::new(Beats::ZERO)),
|
||||
bpm: self.bpm,
|
||||
value_min: self.value_min,
|
||||
value_max: self.value_max,
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType};
|
||||
use crate::audio::midi::MidiEvent;
|
||||
use crate::time::Beats;
|
||||
|
||||
const PARAM_RESOLUTION: u32 = 0;
|
||||
|
||||
@@ -61,12 +62,12 @@ pub struct BeatNode {
|
||||
bpm: f32,
|
||||
beats_per_bar: u32,
|
||||
resolution: BeatResolution,
|
||||
/// Playback time in seconds, set by the graph before process()
|
||||
playback_time: f64,
|
||||
/// Playback time in beats, set by the graph before process()
|
||||
playback_time: Beats,
|
||||
/// Previous playback_time to detect paused state
|
||||
prev_playback_time: f64,
|
||||
/// Free-running time accumulator for when playback is stopped
|
||||
free_run_time: f64,
|
||||
prev_playback_time: Beats,
|
||||
/// Free-running beat accumulator for when playback is stopped
|
||||
free_run_time: Beats,
|
||||
inputs: Vec<NodePort>,
|
||||
outputs: Vec<NodePort>,
|
||||
parameters: Vec<Parameter>,
|
||||
@@ -92,16 +93,16 @@ impl BeatNode {
|
||||
bpm: DEFAULT_BPM,
|
||||
beats_per_bar: DEFAULT_BEATS_PER_BAR,
|
||||
resolution: BeatResolution::Quarter,
|
||||
playback_time: 0.0,
|
||||
prev_playback_time: -1.0,
|
||||
free_run_time: 0.0,
|
||||
playback_time: Beats::ZERO,
|
||||
prev_playback_time: Beats(-1.0),
|
||||
free_run_time: Beats::ZERO,
|
||||
inputs,
|
||||
outputs,
|
||||
parameters,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_playback_time(&mut self, time: f64) {
|
||||
pub fn set_playback_time(&mut self, time: Beats) {
|
||||
self.playback_time = time;
|
||||
}
|
||||
|
||||
@@ -169,8 +170,8 @@ impl AudioNode for BeatNode {
|
||||
let base_time = if paused { self.free_run_time } else { self.playback_time };
|
||||
|
||||
for i in 0..len {
|
||||
let time = base_time + i as f64 * sample_period;
|
||||
let beat_pos = time * beats_per_second;
|
||||
// base_time is already in beats; advance by beats_per_second per second
|
||||
let beat_pos = base_time.0 + i as f64 * beats_per_second * sample_period;
|
||||
|
||||
// Beat subdivision phase: 0→1 sawtooth
|
||||
let sub_phase = ((beat_pos * subs_per_beat) % 1.0) as f32;
|
||||
@@ -188,13 +189,13 @@ impl AudioNode for BeatNode {
|
||||
}
|
||||
|
||||
// Advance free-run time (always ticks, so it's ready when playback stops)
|
||||
self.free_run_time += len as f64 * sample_period;
|
||||
self.free_run_time += Beats(len as f64 * beats_per_second * sample_period);
|
||||
}
|
||||
|
||||
fn reset(&mut self) {
|
||||
self.playback_time = 0.0;
|
||||
self.prev_playback_time = -1.0;
|
||||
self.free_run_time = 0.0;
|
||||
self.playback_time = Beats::ZERO;
|
||||
self.prev_playback_time = Beats(-1.0);
|
||||
self.free_run_time = Beats::ZERO;
|
||||
}
|
||||
|
||||
fn node_type(&self) -> &str {
|
||||
@@ -211,9 +212,9 @@ impl AudioNode for BeatNode {
|
||||
bpm: self.bpm,
|
||||
beats_per_bar: self.beats_per_bar,
|
||||
resolution: self.resolution,
|
||||
playback_time: 0.0,
|
||||
prev_playback_time: -1.0,
|
||||
free_run_time: 0.0,
|
||||
playback_time: Beats::ZERO,
|
||||
prev_playback_time: Beats(-1.0),
|
||||
free_run_time: Beats::ZERO,
|
||||
inputs: self.inputs.clone(),
|
||||
outputs: self.outputs.clone(),
|
||||
parameters: self.parameters.clone(),
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -113,10 +113,8 @@ impl AudioNode for PanNode {
|
||||
let frames_to_process = frames.min(output_frames);
|
||||
|
||||
for frame in 0..frames_to_process {
|
||||
// Pan CV input: when connected, replaces parameter; when unconnected, uses parameter
|
||||
// CV is in 0-1 range, mapped to -1 to +1 pan range
|
||||
let cv_raw = cv_input_or_default(inputs, 1, frame, (self.pan + 1.0) * 0.5);
|
||||
let pan = (cv_raw * 2.0 - 1.0).clamp(-1.0, 1.0);
|
||||
// Pan CV input: -1..+1 directly (0 = center), defaults to parameter value when unconnected
|
||||
let pan = cv_input_or_default(inputs, 1, frame, self.pan).clamp(-1.0, 1.0);
|
||||
|
||||
// Calculate gains using constant-power panning law
|
||||
let angle = (pan + 1.0) * 0.5 * PI / 2.0;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
use crate::audio::node_graph::{AudioNode, NodeCategory, NodePort, Parameter, ParameterUnit, SignalType, cv_input_or_default};
|
||||
use crate::audio::midi::MidiEvent;
|
||||
use crate::time::Beats;
|
||||
|
||||
const PARAM_MODE: u32 = 0;
|
||||
const PARAM_STEPS: u32 = 1;
|
||||
@@ -244,14 +245,14 @@ impl AudioNode for SequencerNode {
|
||||
// Note-off for notes no longer active
|
||||
for ¬e in &self.prev_active_notes {
|
||||
if !new_notes.contains(¬e) {
|
||||
midi_outputs[0].push(MidiEvent::note_off(0.0, 0, note, 0));
|
||||
midi_outputs[0].push(MidiEvent::note_off(Beats::ZERO, 0, note, 0));
|
||||
}
|
||||
}
|
||||
|
||||
// Note-on for newly active notes
|
||||
for ¬e in &new_notes {
|
||||
if !self.prev_active_notes.contains(¬e) {
|
||||
midi_outputs[0].push(MidiEvent::note_on(0.0, 0, note, self.velocity));
|
||||
midi_outputs[0].push(MidiEvent::note_on(Beats::ZERO, 0, note, self.velocity));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -348,7 +348,7 @@ impl AudioNode for VoiceAllocatorNode {
|
||||
|
||||
// Process this voice's graph with its MIDI events
|
||||
// Note: playback_time is 0.0 since voice allocator doesn't track time
|
||||
self.voice_instances[voice_idx].process(mix_slice, &midi_events, 0.0);
|
||||
self.voice_instances[voice_idx].process(mix_slice, &midi_events, crate::time::Beats::ZERO);
|
||||
|
||||
// Auto-deactivate releasing voices that have gone silent
|
||||
if voice_state.releasing {
|
||||
|
||||
@@ -100,6 +100,16 @@ fn default_version() -> u32 {
|
||||
1
|
||||
}
|
||||
|
||||
/// Serialized keyframe for AutomationInput nodes
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SerializedKeyframe {
|
||||
pub time: f64,
|
||||
pub value: f32,
|
||||
pub interpolation: String,
|
||||
pub ease_out: (f32, f32),
|
||||
pub ease_in: (f32, f32),
|
||||
}
|
||||
|
||||
/// Serialized node representation
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SerializedNode {
|
||||
@@ -141,6 +151,14 @@ pub struct SerializedNode {
|
||||
/// Allows the UI to display actual track names on the node's output ports.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub port_names: Vec<String>,
|
||||
|
||||
/// For AutomationInput nodes: user-visible display name
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub automation_display_name: Option<String>,
|
||||
|
||||
/// For AutomationInput nodes: saved keyframes
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub automation_keyframes: Vec<SerializedKeyframe>,
|
||||
}
|
||||
|
||||
/// Serialized group definition (frontend-only visual grouping, stored opaquely by backend)
|
||||
@@ -239,6 +257,8 @@ impl SerializedNode {
|
||||
nam_model_path: None,
|
||||
num_ports: None,
|
||||
port_names: Vec::new(),
|
||||
automation_display_name: None,
|
||||
automation_keyframes: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+336
-36
@@ -2,6 +2,47 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::f32::consts::PI;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use crate::time::Seconds;
|
||||
|
||||
/// Per-output-channel mix coefficients to fold a multichannel source down to
|
||||
/// stereo, indexed `[out_channel(0=L,1=R)][src_channel]`.
|
||||
///
|
||||
/// Assumes the conventional interleave order for each channel count (FL, FR, FC,
|
||||
/// LFE, BL, BR, SL, SR …). Uses standard ITU/AC-3-style coefficients: full level
|
||||
/// for the matching front channel, `1/√2` (≈ −3 dB) for centre and each surround,
|
||||
/// LFE dropped. Each row is then normalized so its absolute-coefficient sum ≤ 1,
|
||||
/// which prevents clipping (matching FFmpeg's default `normalize` behaviour).
|
||||
///
|
||||
/// Returns `None` for layouts we don't special-case (caller falls back to taking
|
||||
/// the front L/R pair).
|
||||
fn stereo_downmix_matrix(src_channels: usize) -> Option<[Vec<f32>; 2]> {
|
||||
const C: f32 = std::f32::consts::FRAC_1_SQRT_2; // ≈ 0.7071
|
||||
// (L row, R row); each entry is the gain applied to that source channel.
|
||||
let (l, r): (Vec<f32>, Vec<f32>) = match src_channels {
|
||||
3 => (vec![1.0, 0.0, C], vec![0.0, 1.0, C]), // FL FR FC
|
||||
4 => (vec![1.0, 0.0, C, 0.0], vec![0.0, 1.0, 0.0, C]), // quad: FL FR BL BR
|
||||
5 => (vec![1.0, 0.0, C, C, 0.0], vec![0.0, 1.0, C, 0.0, C]), // FL FR FC BL BR
|
||||
// 5.1: FL FR FC LFE BL BR (LFE dropped)
|
||||
6 => (vec![1.0, 0.0, C, 0.0, C, 0.0], vec![0.0, 1.0, C, 0.0, 0.0, C]),
|
||||
// 6.1: FL FR FC LFE BC SL SR (BC → both)
|
||||
7 => (vec![1.0, 0.0, C, 0.0, C, C, 0.0], vec![0.0, 1.0, C, 0.0, C, 0.0, C]),
|
||||
// 7.1: FL FR FC LFE BL BR SL SR
|
||||
8 => (
|
||||
vec![1.0, 0.0, C, 0.0, C, 0.0, C, 0.0],
|
||||
vec![0.0, 1.0, C, 0.0, 0.0, C, 0.0, C],
|
||||
),
|
||||
_ => return None,
|
||||
};
|
||||
let normalize = |row: Vec<f32>| -> Vec<f32> {
|
||||
let sum: f32 = row.iter().map(|c| c.abs()).sum();
|
||||
if sum > 1.0 {
|
||||
row.into_iter().map(|c| c / sum).collect()
|
||||
} else {
|
||||
row
|
||||
}
|
||||
};
|
||||
Some([normalize(l), normalize(r)])
|
||||
}
|
||||
|
||||
/// Windowed sinc interpolation for high-quality time stretching
|
||||
/// This is stateless and can handle arbitrary fractional positions
|
||||
@@ -82,6 +123,16 @@ pub enum AudioStorage {
|
||||
decoded_frames: u64,
|
||||
total_frames: u64,
|
||||
},
|
||||
|
||||
/// Audio track of a video container, decoded on demand via FFmpeg
|
||||
/// (`VideoAudioReader`). The source video file is `AudioFile::path`. Like
|
||||
/// `Compressed`, playback is streamed through the disk reader and
|
||||
/// `decoded_for_waveform` is filled progressively for the overview.
|
||||
VideoAudio {
|
||||
decoded_for_waveform: Vec<f32>,
|
||||
decoded_frames: u64,
|
||||
total_frames: u64,
|
||||
},
|
||||
}
|
||||
|
||||
/// Audio file stored in the pool
|
||||
@@ -97,6 +148,10 @@ pub struct AudioFile {
|
||||
pub original_format: Option<String>,
|
||||
/// Original compressed file bytes (preserved across save/load to avoid re-encoding)
|
||||
pub original_bytes: Option<Vec<u8>>,
|
||||
/// When `Some`, this entry's bytes are packed in the project container (not on
|
||||
/// disk at `path`); the disk reader opens them via the host's
|
||||
/// `AudioBlobSourceFactory` using this media id. `None` ⇒ stream from `path`.
|
||||
pub packed_media_id: Option<String>,
|
||||
}
|
||||
|
||||
impl AudioFile {
|
||||
@@ -111,6 +166,7 @@ impl AudioFile {
|
||||
frames,
|
||||
original_format: None,
|
||||
original_bytes: None,
|
||||
packed_media_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -125,6 +181,7 @@ impl AudioFile {
|
||||
frames,
|
||||
original_format,
|
||||
original_bytes: None,
|
||||
packed_media_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,6 +214,7 @@ impl AudioFile {
|
||||
frames: total_frames,
|
||||
original_format: Some("wav".to_string()),
|
||||
original_bytes: None,
|
||||
packed_media_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,6 +238,35 @@ impl AudioFile {
|
||||
frames: total_frames,
|
||||
original_format,
|
||||
original_bytes: None,
|
||||
packed_media_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// 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`. `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,
|
||||
storage: AudioStorage::VideoAudio {
|
||||
decoded_for_waveform: Vec::new(),
|
||||
decoded_frames: 0,
|
||||
total_frames,
|
||||
},
|
||||
channels,
|
||||
sample_rate,
|
||||
frames: total_frames,
|
||||
original_format: None,
|
||||
original_bytes: None,
|
||||
packed_media_id,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -273,8 +360,8 @@ impl AudioFile {
|
||||
}
|
||||
written
|
||||
}
|
||||
AudioStorage::Compressed { .. } => {
|
||||
// Compressed files are read through the disk reader
|
||||
AudioStorage::Compressed { .. } | AudioStorage::VideoAudio { .. } => {
|
||||
// Streamed through the disk reader, not via read_samples().
|
||||
0
|
||||
}
|
||||
}
|
||||
@@ -442,19 +529,20 @@ impl AudioClipPool {
|
||||
}
|
||||
|
||||
/// Render audio from a file in the pool with high-quality windowed sinc interpolation
|
||||
/// start_time_seconds: position in the audio file to start reading from (in seconds)
|
||||
/// start_time: position in the audio file to start reading from (in seconds)
|
||||
/// clip_read_ahead: per-clip-instance read-ahead buffer for compressed audio streaming
|
||||
/// Returns the number of samples actually rendered
|
||||
pub fn render_from_file(
|
||||
&self,
|
||||
pool_index: usize,
|
||||
output: &mut [f32],
|
||||
start_time_seconds: f64,
|
||||
start_time: Seconds,
|
||||
gain: f32,
|
||||
engine_sample_rate: u32,
|
||||
engine_channels: u32,
|
||||
clip_read_ahead: Option<&super::disk_reader::ReadAheadBuffer>,
|
||||
) -> usize {
|
||||
let start_time_seconds = start_time.0;
|
||||
let Some(audio_file) = self.files.get(pool_index) else {
|
||||
return 0;
|
||||
};
|
||||
@@ -489,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 {
|
||||
@@ -535,6 +644,15 @@ impl AudioClipPool {
|
||||
let dst_channels = engine_channels as usize;
|
||||
let output_frames = output.len() / dst_channels;
|
||||
|
||||
// Fold a multichannel source (5.1, 7.1, …) down to stereo with proper
|
||||
// coefficients (centre + surrounds mixed in, LFE dropped) instead of just
|
||||
// taking the front L/R pair. `None` ⇒ no downmix needed / unknown layout.
|
||||
let downmix = if dst_channels == 2 && src_channels > 2 {
|
||||
stereo_downmix_matrix(src_channels)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let src_start_position = start_time_seconds * audio_file.sample_rate as f64;
|
||||
|
||||
// Tell the disk reader where we're reading so it buffers the right region.
|
||||
@@ -580,6 +698,15 @@ impl AudioClipPool {
|
||||
sum += get_sample!(sf, src_ch);
|
||||
}
|
||||
sum / src_channels as f32
|
||||
} else if let Some(ref mat) = downmix {
|
||||
// Surround → stereo with proper coefficients.
|
||||
let mut s = 0.0f32;
|
||||
for (src_ch, &c) in mat[dst_ch].iter().enumerate() {
|
||||
if c != 0.0 {
|
||||
s += c * get_sample!(sf, src_ch);
|
||||
}
|
||||
}
|
||||
s
|
||||
} else {
|
||||
get_sample!(sf, dst_ch % src_channels)
|
||||
};
|
||||
@@ -604,39 +731,45 @@ impl AudioClipPool {
|
||||
break;
|
||||
}
|
||||
|
||||
for dst_ch in 0..dst_channels {
|
||||
let src_ch = if src_channels == dst_channels {
|
||||
dst_ch
|
||||
} else if src_channels == 1 {
|
||||
0
|
||||
} else if dst_channels == 1 {
|
||||
usize::MAX // sentinel: average all channels below
|
||||
} else {
|
||||
dst_ch % src_channels
|
||||
};
|
||||
|
||||
let sample = if src_ch == usize::MAX {
|
||||
let mut sum = 0.0;
|
||||
for ch in 0..src_channels {
|
||||
let mut channel_samples = [0.0f32; KERNEL_SIZE];
|
||||
for (j, i) in (-(HALF_KERNEL as i32)..(HALF_KERNEL as i32)).enumerate() {
|
||||
let idx = src_frame + i;
|
||||
if idx >= 0 && (idx as usize) < audio_file.frames as usize {
|
||||
channel_samples[j] = get_sample!(idx as usize, ch);
|
||||
}
|
||||
}
|
||||
sum += windowed_sinc_interpolate(&channel_samples, frac);
|
||||
}
|
||||
sum / src_channels as f32
|
||||
} else {
|
||||
// Sinc-interpolate a single source channel at the current position.
|
||||
macro_rules! sinc_ch {
|
||||
($ch:expr) => {{
|
||||
let mut channel_samples = [0.0f32; KERNEL_SIZE];
|
||||
for (j, i) in (-(HALF_KERNEL as i32)..(HALF_KERNEL as i32)).enumerate() {
|
||||
let idx = src_frame + i;
|
||||
if idx >= 0 && (idx as usize) < audio_file.frames as usize {
|
||||
channel_samples[j] = get_sample!(idx as usize, src_ch);
|
||||
channel_samples[j] = get_sample!(idx as usize, $ch);
|
||||
}
|
||||
}
|
||||
windowed_sinc_interpolate(&channel_samples, frac)
|
||||
}};
|
||||
}
|
||||
|
||||
for dst_ch in 0..dst_channels {
|
||||
let sample = if let Some(ref mat) = downmix {
|
||||
// Surround → stereo: interpolate each contributing channel.
|
||||
let mut s = 0.0f32;
|
||||
for (ch, &c) in mat[dst_ch].iter().enumerate() {
|
||||
if c != 0.0 {
|
||||
s += c * sinc_ch!(ch);
|
||||
}
|
||||
}
|
||||
s
|
||||
} else if dst_channels == 1 {
|
||||
let mut sum = 0.0;
|
||||
for ch in 0..src_channels {
|
||||
sum += sinc_ch!(ch);
|
||||
}
|
||||
sum / src_channels as f32
|
||||
} else {
|
||||
let src_ch = if src_channels == dst_channels {
|
||||
dst_ch
|
||||
} else if src_channels == 1 {
|
||||
0
|
||||
} else {
|
||||
dst_ch % src_channels
|
||||
};
|
||||
sinc_ch!(src_ch)
|
||||
};
|
||||
|
||||
output[output_frame * dst_channels + dst_ch] += sample * gain;
|
||||
@@ -784,6 +917,25 @@ pub struct AudioPoolEntry {
|
||||
pub channels: u32,
|
||||
/// Embedded audio data (for files < 10MB)
|
||||
pub embedded_data: Option<EmbeddedAudioData>,
|
||||
/// Stable media id (UUID string) for the SQLite `.beam` container. When set,
|
||||
/// the audio bytes live in the container's `media` table keyed by this id
|
||||
/// (packed storage). `None` for referenced entries (use `relative_path`) or
|
||||
/// legacy ZIP-loaded entries. Populated by the file_io save/load layer.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub media_id: Option<String>,
|
||||
/// Transient carrier for this entry's serialized waveform-pyramid blob (LBWF
|
||||
/// bytes). Never serialized into project.json — the bytes live in the
|
||||
/// container's `media` table (kind `Waveform`). Set by the file_io save layer
|
||||
/// (in) and load layer (out); `None` everywhere else.
|
||||
#[serde(skip)]
|
||||
pub waveform_blob: Option<Vec<u8>>,
|
||||
/// This entry is a video container's audio track (`relative_path` points at the
|
||||
/// video file). It is always stored as a path reference (never packed/embedded
|
||||
/// — the `VideoClip` already references the file) and reloaded by re-probing
|
||||
/// the video via FFmpeg, so multichannel (5.1/7.1) audio survives the round-trip
|
||||
/// (Symphonia reconstitution would otherwise collapse it).
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub is_video_audio: bool,
|
||||
}
|
||||
|
||||
impl AudioClipPool {
|
||||
@@ -798,6 +950,66 @@ impl AudioClipPool {
|
||||
let mut entries = Vec::new();
|
||||
|
||||
for (index, file) in self.files.iter().enumerate() {
|
||||
// Skip placeholder pool slots: `load_from_serialized` resizes the pool to
|
||||
// `max_index + 1` filled with empty `AudioFile::new(PathBuf::new(), …)` to
|
||||
// cover index gaps (and creates one even when there are no entries at all).
|
||||
// Such a slot has an empty path and no packed media — there's nothing to
|
||||
// persist, and emitting it yields an entry whose empty `relative_path`
|
||||
// resolves to the project directory itself (unreadable on the next save).
|
||||
if file.path.as_os_str().is_empty() && file.packed_media_id.is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Video's audio track: reference the video file (it's also referenced
|
||||
// by the VideoClip) and re-probe it via FFmpeg on load. Never pack or
|
||||
// embed it as audio media — that both wastes space and loses the 5.1+
|
||||
// layout when Symphonia later decodes it.
|
||||
if matches!(file.storage, AudioStorage::VideoAudio { .. }) {
|
||||
let relative_path = pathdiff::diff_paths(&file.path, project_dir)
|
||||
.map(|r| r.to_string_lossy().to_string())
|
||||
.or_else(|| Some(file.path.to_string_lossy().to_string()));
|
||||
entries.push(AudioPoolEntry {
|
||||
pool_index: index,
|
||||
is_video_audio: true,
|
||||
waveform_blob: None,
|
||||
name: file
|
||||
.path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| format!("file_{}", index)),
|
||||
relative_path,
|
||||
duration: file.duration_seconds(),
|
||||
sample_rate: file.sample_rate,
|
||||
channels: file.channels,
|
||||
embedded_data: None,
|
||||
media_id: None,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// Packed-in-container streaming entry: its bytes already live in the
|
||||
// `.beam` media table (kept in place across re-saves). Emit just the
|
||||
// media id — no path, no embedded bytes, nothing to decode.
|
||||
if let Some(media_id) = &file.packed_media_id {
|
||||
entries.push(AudioPoolEntry {
|
||||
pool_index: index,
|
||||
is_video_audio: false,
|
||||
waveform_blob: None,
|
||||
name: file
|
||||
.path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
.unwrap_or_else(|| format!("file_{}", index)),
|
||||
relative_path: None,
|
||||
duration: file.duration_seconds(),
|
||||
sample_rate: file.sample_rate,
|
||||
channels: file.channels,
|
||||
embedded_data: None,
|
||||
media_id: Some(media_id.clone()),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
let file_path = &file.path;
|
||||
let file_path_str = file_path.to_string_lossy();
|
||||
|
||||
@@ -828,6 +1040,8 @@ impl AudioClipPool {
|
||||
|
||||
let entry = AudioPoolEntry {
|
||||
pool_index: index,
|
||||
is_video_audio: false,
|
||||
waveform_blob: None,
|
||||
name: file_path
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().to_string())
|
||||
@@ -837,6 +1051,7 @@ impl AudioClipPool {
|
||||
sample_rate: file.sample_rate,
|
||||
channels: file.channels,
|
||||
embedded_data,
|
||||
media_id: None,
|
||||
};
|
||||
|
||||
entries.push(entry);
|
||||
@@ -960,22 +1175,107 @@ impl AudioClipPool {
|
||||
self.files.clear();
|
||||
eprintln!("📊 [LOAD_SERIALIZED] Clear pool took {:.2}ms", clear_start.elapsed().as_secs_f64() * 1000.0);
|
||||
|
||||
// Find the maximum pool index to determine required size
|
||||
let max_index = entries.iter()
|
||||
.map(|e| e.pool_index)
|
||||
// Size the pool to hold the highest pool_index (slots are addressed by index,
|
||||
// so gaps are filled with placeholders). No entries → length 0, NOT 1: the old
|
||||
// `max().unwrap_or(0) + 1` produced a spurious placeholder for an empty pool.
|
||||
let pool_size = entries.iter()
|
||||
.map(|e| e.pool_index + 1)
|
||||
.max()
|
||||
.unwrap_or(0);
|
||||
|
||||
// Ensure we have space for all entries
|
||||
let resize_start = std::time::Instant::now();
|
||||
self.files.resize(max_index + 1, AudioFile::new(PathBuf::new(), Vec::new(), 2, 44100));
|
||||
eprintln!("📊 [LOAD_SERIALIZED] Resize pool to {} took {:.2}ms", max_index + 1, resize_start.elapsed().as_secs_f64() * 1000.0);
|
||||
self.files.resize(pool_size, AudioFile::new(PathBuf::new(), Vec::new(), 2, 44100));
|
||||
eprintln!("📊 [LOAD_SERIALIZED] Resize pool to {} took {:.2}ms", pool_size, resize_start.elapsed().as_secs_f64() * 1000.0);
|
||||
|
||||
for (i, entry) in entries.iter().enumerate() {
|
||||
let entry_start = std::time::Instant::now();
|
||||
eprintln!("📊 [LOAD_SERIALIZED] Processing entry {}/{}: '{}'", i + 1, entries.len(), entry.name);
|
||||
|
||||
let success = if let Some(ref embedded) = entry.embedded_data {
|
||||
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() {
|
||||
Some(rel) => {
|
||||
let full = if std::path::Path::new(rel).is_absolute() {
|
||||
PathBuf::from(rel)
|
||||
} else {
|
||||
project_dir.join(rel)
|
||||
};
|
||||
if full.exists() {
|
||||
match crate::audio::disk_reader::VideoAudioReader::open(&full) {
|
||||
Ok(reader) => {
|
||||
let file = AudioFile::from_video_audio(
|
||||
full,
|
||||
reader.channels(),
|
||||
reader.sample_rate(),
|
||||
reader.total_frames(),
|
||||
None,
|
||||
);
|
||||
if entry.pool_index < self.files.len() {
|
||||
self.files[entry.pool_index] = file;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("[AudioPool] Failed to reopen video audio {:?}: {}", full, e);
|
||||
false
|
||||
}
|
||||
}
|
||||
} else {
|
||||
eprintln!("[AudioPool] Video file not found for audio: {:?}", full);
|
||||
false
|
||||
}
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
} else if entry.media_id.is_some() && entry.embedded_data.is_none() {
|
||||
// Packed-in-container streaming entry: build a Compressed placeholder
|
||||
// backed by the host blob factory (opened at clip-activation time).
|
||||
// No decode here — playback streams through the disk reader.
|
||||
let media_id = entry.media_id.clone().unwrap();
|
||||
let ext = std::path::Path::new(&entry.name)
|
||||
.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.map(|s| s.to_lowercase());
|
||||
let total_frames = (entry.duration * entry.sample_rate as f64).ceil() as u64;
|
||||
let mut file = AudioFile::from_compressed(
|
||||
PathBuf::from(&entry.name),
|
||||
entry.channels,
|
||||
entry.sample_rate,
|
||||
total_frames,
|
||||
ext,
|
||||
);
|
||||
file.packed_media_id = Some(media_id);
|
||||
if entry.pool_index < self.files.len() {
|
||||
self.files[entry.pool_index] = file;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
} else if let Some(ref embedded) = entry.embedded_data {
|
||||
// Load from embedded data
|
||||
eprintln!("📊 [LOAD_SERIALIZED] Entry has embedded data (format: {})", embedded.format);
|
||||
match Self::load_from_embedded_into_pool(self, entry.pool_index, embedded.clone(), &entry.name) {
|
||||
|
||||
@@ -4,6 +4,8 @@ use super::midi::{MidiClip, MidiClipId, MidiClipInstance, MidiClipInstanceId, Mi
|
||||
use super::midi_pool::MidiClipPool;
|
||||
use super::pool::AudioClipPool;
|
||||
use super::track::{AudioTrack, Metatrack, MidiTrack, RenderContext, TrackId, TrackNode};
|
||||
use crate::tempo_map::TempoMap;
|
||||
use crate::time::{Beats, Seconds};
|
||||
use serde::{Serialize, Deserialize};
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -39,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;
|
||||
@@ -288,9 +295,9 @@ impl Project {
|
||||
&mut self,
|
||||
track_id: TrackId,
|
||||
events: Vec<MidiEvent>,
|
||||
duration: f64,
|
||||
duration: Beats,
|
||||
name: String,
|
||||
external_start: f64,
|
||||
external_start: Beats,
|
||||
) -> Result<(MidiClipId, MidiClipInstanceId), &'static str> {
|
||||
// Verify track exists and is a MIDI track
|
||||
if !matches!(self.tracks.get(&track_id), Some(TrackNode::Midi(_))) {
|
||||
@@ -323,11 +330,11 @@ impl Project {
|
||||
|
||||
/// Legacy method for backwards compatibility - creates clip and instance from old MidiClip format
|
||||
pub fn add_midi_clip(&mut self, track_id: TrackId, clip: MidiClip) -> Result<MidiClipInstanceId, &'static str> {
|
||||
self.add_midi_clip_at(track_id, clip, 0.0)
|
||||
self.add_midi_clip_at(track_id, clip, Beats::ZERO)
|
||||
}
|
||||
|
||||
/// Add a MIDI clip to the pool and create an instance at the given timeline position
|
||||
pub fn add_midi_clip_at(&mut self, track_id: TrackId, clip: MidiClip, start_time: f64) -> Result<MidiClipInstanceId, &'static str> {
|
||||
pub fn add_midi_clip_at(&mut self, track_id: TrackId, clip: MidiClip, start_time: Beats) -> Result<MidiClipInstanceId, &'static str> {
|
||||
// Add the clip to the pool (it already has events and duration)
|
||||
let duration = clip.duration;
|
||||
let clip_id = clip.id;
|
||||
@@ -371,7 +378,8 @@ impl Project {
|
||||
output: &mut [f32],
|
||||
audio_pool: &AudioClipPool,
|
||||
buffer_pool: &mut BufferPool,
|
||||
playhead_seconds: f64,
|
||||
playhead_seconds: Seconds,
|
||||
tempo_map: &TempoMap,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
live_only: bool,
|
||||
@@ -383,7 +391,7 @@ impl Project {
|
||||
// Create initial render context
|
||||
let ctx = RenderContext {
|
||||
live_only,
|
||||
..RenderContext::new(playhead_seconds, sample_rate, channels, output.len())
|
||||
..RenderContext::new(playhead_seconds, tempo_map, sample_rate, channels, output.len())
|
||||
};
|
||||
|
||||
// Render each root track (index-based to avoid clone)
|
||||
@@ -457,7 +465,7 @@ impl Project {
|
||||
let mut track_buffer = buffer_pool.acquire();
|
||||
track_buffer.resize(output.len(), 0.0);
|
||||
track_buffer.fill(0.0);
|
||||
track.render(&mut track_buffer, audio_pool, ctx.playhead_seconds, ctx.sample_rate, ctx.channels);
|
||||
track.render(&mut track_buffer, audio_pool, ctx);
|
||||
// Accumulate peak level for VU metering (max over meter interval)
|
||||
let buffer_peak = track_buffer.iter().map(|s| s.abs()).fold(0.0f32, f32::max);
|
||||
track.peak_level = track.peak_level.max(buffer_peak);
|
||||
@@ -545,7 +553,7 @@ impl Project {
|
||||
let mut graph_output = buffer_pool.acquire();
|
||||
graph_output.resize(output.len(), 0.0);
|
||||
graph_output.fill(0.0);
|
||||
group.audio_graph.process(&mut graph_output, &[], ctx.playhead_seconds);
|
||||
group.audio_graph.process(&mut graph_output, &[], ctx.playhead_beats());
|
||||
|
||||
for (out_sample, graph_sample) in output.iter_mut().zip(graph_output.iter()) {
|
||||
*out_sample += graph_sample * group.volume;
|
||||
@@ -640,7 +648,7 @@ impl Project {
|
||||
pub fn send_midi_note_on(&mut self, track_id: TrackId, note: u8, velocity: u8) {
|
||||
// Queue the MIDI note-on event to the track's live MIDI queue
|
||||
if let Some(TrackNode::Midi(track)) = self.tracks.get_mut(&track_id) {
|
||||
let event = MidiEvent::note_on(0.0, 0, note, velocity);
|
||||
let event = MidiEvent::note_on(Beats::ZERO, 0, note, velocity);
|
||||
track.queue_live_midi(event);
|
||||
}
|
||||
}
|
||||
@@ -649,7 +657,7 @@ impl Project {
|
||||
pub fn send_midi_note_off(&mut self, track_id: TrackId, note: u8) {
|
||||
// Queue the MIDI note-off event to the track's live MIDI queue
|
||||
if let Some(TrackNode::Midi(track)) = self.tracks.get_mut(&track_id) {
|
||||
let event = MidiEvent::note_off(0.0, 0, note, 0);
|
||||
let event = MidiEvent::note_off(Beats::ZERO, 0, note, 0);
|
||||
track.queue_live_midi(event);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/// Audio recording system for capturing microphone input
|
||||
use crate::audio::{ClipId, MidiClipId, TrackId};
|
||||
use crate::io::{WavWriter, WaveformPeak};
|
||||
use crate::time::{Beats, Seconds};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
@@ -18,8 +19,8 @@ pub struct RecordingState {
|
||||
pub sample_rate: u32,
|
||||
/// Number of channels
|
||||
pub channels: u32,
|
||||
/// Timeline start position in seconds
|
||||
pub start_time: f64,
|
||||
/// Timeline start position
|
||||
pub start_time: Beats,
|
||||
/// Total frames recorded
|
||||
pub frames_written: usize,
|
||||
/// Whether recording is currently paused
|
||||
@@ -45,7 +46,7 @@ impl RecordingState {
|
||||
writer: WavWriter,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
start_time: f64,
|
||||
start_time: Beats,
|
||||
_flush_interval_seconds: f64, // No longer used - kept for API compatibility
|
||||
) -> Self {
|
||||
// Calculate frames per waveform peak
|
||||
@@ -130,9 +131,9 @@ impl RecordingState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get current recording duration in seconds
|
||||
pub fn duration(&self) -> f64 {
|
||||
self.frames_written as f64 / self.sample_rate as f64
|
||||
/// Get current recording duration
|
||||
pub fn duration(&self) -> Seconds {
|
||||
Seconds(self.frames_written as f64 / self.sample_rate as f64)
|
||||
}
|
||||
|
||||
/// Finalize the recording and return the temp file path, waveform, and audio data
|
||||
@@ -175,33 +176,23 @@ impl RecordingState {
|
||||
/// Active MIDI note waiting for its noteOff event
|
||||
#[derive(Debug, Clone)]
|
||||
struct ActiveMidiNote {
|
||||
/// MIDI note number (0-127)
|
||||
note: u8,
|
||||
/// Velocity (0-127)
|
||||
velocity: u8,
|
||||
/// Absolute time when note started (seconds)
|
||||
start_time: f64,
|
||||
start_time: Beats,
|
||||
}
|
||||
|
||||
/// State of an active MIDI recording session
|
||||
/// State of an active MIDI recording session.
|
||||
pub struct MidiRecordingState {
|
||||
/// Track being recorded to
|
||||
pub track_id: TrackId,
|
||||
/// MIDI clip ID
|
||||
pub clip_id: MidiClipId,
|
||||
/// Timeline start position in seconds
|
||||
pub start_time: f64,
|
||||
/// Currently active notes (noteOn without matching noteOff)
|
||||
/// Maps note number to ActiveMidiNote
|
||||
pub start_time: Beats,
|
||||
active_notes: HashMap<u8, ActiveMidiNote>,
|
||||
/// Completed notes ready to be added to clip
|
||||
/// Format: (time_offset, note, velocity, duration)
|
||||
pub completed_notes: Vec<(f64, u8, u8, f64)>,
|
||||
/// Completed notes: (time_offset, note, velocity, duration) — all times in beats
|
||||
pub completed_notes: Vec<(Beats, u8, u8, Beats)>,
|
||||
}
|
||||
|
||||
impl MidiRecordingState {
|
||||
/// Create a new MIDI recording state
|
||||
pub fn new(track_id: TrackId, clip_id: MidiClipId, start_time: f64) -> Self {
|
||||
pub fn new(track_id: TrackId, clip_id: MidiClipId, start_time: Beats) -> Self {
|
||||
Self {
|
||||
track_id,
|
||||
clip_id,
|
||||
@@ -211,87 +202,62 @@ impl MidiRecordingState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle a MIDI note on event
|
||||
pub fn note_on(&mut self, note: u8, velocity: u8, absolute_time: f64) {
|
||||
self.active_notes.insert(note, ActiveMidiNote {
|
||||
note,
|
||||
velocity,
|
||||
start_time: absolute_time,
|
||||
});
|
||||
pub fn note_on(&mut self, note: u8, velocity: u8, absolute_time: Beats) {
|
||||
self.active_notes.insert(note, ActiveMidiNote { note, velocity, start_time: absolute_time });
|
||||
}
|
||||
|
||||
/// Handle a MIDI note off event
|
||||
pub fn note_off(&mut self, note: u8, absolute_time: f64) {
|
||||
// Find the matching noteOn
|
||||
pub fn note_off(&mut self, note: u8, absolute_time: Beats) {
|
||||
if let Some(active_note) = self.active_notes.remove(¬e) {
|
||||
// If the note was fully released before the recording start (e.g. during count-in
|
||||
// pre-roll), discard it — only notes still held at the clip start are kept.
|
||||
if absolute_time <= self.start_time {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clamp note start to clip start: notes held across the recording boundary
|
||||
// are treated as starting at the clip position.
|
||||
let note_start = active_note.start_time.max(self.start_time);
|
||||
let time_offset = note_start - self.start_time;
|
||||
let duration = absolute_time - note_start;
|
||||
|
||||
eprintln!("[MIDI_RECORDING_STATE] Completing note {}: note_start={:.3}s, note_end={:.3}s, recording_start={:.3}s, time_offset={:.3}s, duration={:.3}s",
|
||||
note, note_start, absolute_time, self.start_time, time_offset, duration);
|
||||
|
||||
self.completed_notes.push((
|
||||
time_offset,
|
||||
note_start - self.start_time,
|
||||
active_note.note,
|
||||
active_note.velocity,
|
||||
duration,
|
||||
absolute_time - note_start,
|
||||
));
|
||||
}
|
||||
// If no matching noteOn found, ignore the noteOff
|
||||
}
|
||||
|
||||
/// Get all completed notes
|
||||
pub fn get_notes(&self) -> &[(f64, u8, u8, f64)] {
|
||||
pub fn get_notes(&self) -> &[(Beats, u8, u8, Beats)] {
|
||||
&self.completed_notes
|
||||
}
|
||||
|
||||
/// Get the number of completed notes
|
||||
pub fn note_count(&self) -> usize {
|
||||
self.completed_notes.len()
|
||||
}
|
||||
|
||||
/// Get all completed notes plus currently-held notes with a provisional duration.
|
||||
/// Used for live preview during recording so held notes appear immediately.
|
||||
pub fn get_notes_with_active(&self, current_time: f64) -> Vec<(f64, u8, u8, f64)> {
|
||||
pub fn get_notes_with_active(&self, current_time: Beats) -> Vec<(Beats, u8, u8, Beats)> {
|
||||
let mut notes = self.completed_notes.clone();
|
||||
for active in self.active_notes.values() {
|
||||
let note_start = active.start_time.max(self.start_time);
|
||||
let time_offset = note_start - self.start_time;
|
||||
let provisional_dur = (current_time - note_start).max(0.0);
|
||||
notes.push((time_offset, active.note, active.velocity, provisional_dur));
|
||||
notes.push((
|
||||
note_start - self.start_time,
|
||||
active.note,
|
||||
active.velocity,
|
||||
(current_time - note_start).max(Beats::ZERO),
|
||||
));
|
||||
}
|
||||
notes
|
||||
}
|
||||
|
||||
/// Get the note numbers of all currently held (active) notes
|
||||
pub fn active_note_numbers(&self) -> Vec<u8> {
|
||||
self.active_notes.keys().copied().collect()
|
||||
}
|
||||
|
||||
/// Close out all active notes at the given time
|
||||
/// This should be called when stopping recording to end any held notes
|
||||
pub fn close_active_notes(&mut self, end_time: f64) {
|
||||
pub fn close_active_notes(&mut self, end_time: Beats) {
|
||||
let active_notes: Vec<_> = self.active_notes.drain().collect();
|
||||
|
||||
for (_note_num, active_note) in active_notes {
|
||||
let note_start = active_note.start_time.max(self.start_time);
|
||||
let time_offset = note_start - self.start_time;
|
||||
let duration = end_time - note_start;
|
||||
|
||||
self.completed_notes.push((
|
||||
time_offset,
|
||||
note_start - self.start_time,
|
||||
active_note.note,
|
||||
active_note.velocity,
|
||||
duration,
|
||||
end_time - note_start,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
+130
-97
@@ -6,6 +6,8 @@ use super::node_graph::AudioGraph;
|
||||
use super::node_graph::nodes::{AudioInputNode, AudioOutputNode};
|
||||
use super::node_graph::preset::GraphPreset;
|
||||
use super::pool::AudioClipPool;
|
||||
use crate::tempo_map::TempoMap;
|
||||
use crate::time::{Beats, Seconds};
|
||||
use serde::{Serialize, Deserialize};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
|
||||
@@ -23,10 +25,12 @@ pub type Track = AudioTrack;
|
||||
/// Rendering context that carries timing information through the track hierarchy
|
||||
///
|
||||
/// This allows metatracks to transform time for their children (time stretch, offset, etc.)
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct RenderContext {
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RenderContext<'a> {
|
||||
/// Current playhead position in seconds (in transformed time)
|
||||
pub playhead_seconds: f64,
|
||||
pub playhead_seconds: Seconds,
|
||||
/// Tempo map for beat ↔ second conversion
|
||||
pub tempo_map: &'a TempoMap,
|
||||
/// Audio sample rate
|
||||
pub sample_rate: u32,
|
||||
/// Number of channels
|
||||
@@ -41,16 +45,17 @@ pub struct RenderContext {
|
||||
pub live_only: bool,
|
||||
}
|
||||
|
||||
impl RenderContext {
|
||||
/// Create a new render context
|
||||
impl<'a> RenderContext<'a> {
|
||||
pub fn new(
|
||||
playhead_seconds: f64,
|
||||
playhead_seconds: Seconds,
|
||||
tempo_map: &'a TempoMap,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
buffer_size: usize,
|
||||
) -> Self {
|
||||
Self {
|
||||
playhead_seconds,
|
||||
tempo_map,
|
||||
sample_rate,
|
||||
channels,
|
||||
buffer_size,
|
||||
@@ -59,15 +64,21 @@ impl RenderContext {
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the duration of the buffer in seconds
|
||||
pub fn buffer_duration(&self) -> f64 {
|
||||
self.buffer_size as f64 / (self.sample_rate as f64 * self.channels as f64)
|
||||
pub fn buffer_duration(&self) -> Seconds {
|
||||
Seconds(self.buffer_size as f64 / (self.sample_rate as f64 * self.channels as f64))
|
||||
}
|
||||
|
||||
/// Get the end time of the buffer
|
||||
pub fn buffer_end(&self) -> f64 {
|
||||
pub fn buffer_end(&self) -> Seconds {
|
||||
self.playhead_seconds + self.buffer_duration()
|
||||
}
|
||||
|
||||
pub fn playhead_beats(&self) -> Beats {
|
||||
self.tempo_map.seconds_to_beats(self.playhead_seconds)
|
||||
}
|
||||
|
||||
pub fn buffer_end_beats(&self) -> Beats {
|
||||
self.tempo_map.seconds_to_beats(self.buffer_end())
|
||||
}
|
||||
}
|
||||
|
||||
/// Node in the track hierarchy - can be an audio track, MIDI track, or a metatrack
|
||||
@@ -170,14 +181,14 @@ pub struct Metatrack {
|
||||
pub time_stretch: f32,
|
||||
/// Pitch shift in semitones (for future implementation)
|
||||
pub pitch_shift: f32,
|
||||
/// Time offset in seconds (shift content forward/backward in time)
|
||||
pub offset: f64,
|
||||
/// Trim start: offset into the metatrack's internal content (seconds)
|
||||
/// Time offset (shift content forward/backward in time)
|
||||
pub offset: Seconds,
|
||||
/// Trim start: offset into the metatrack's internal content
|
||||
/// Children will see time starting from this point
|
||||
pub trim_start: f64,
|
||||
/// Trim end: offset into the metatrack's internal content (seconds)
|
||||
pub trim_start: Seconds,
|
||||
/// Trim end: offset into the metatrack's internal content
|
||||
/// None means no end trim (play until content ends)
|
||||
pub trim_end: Option<f64>,
|
||||
pub trim_end: Option<Seconds>,
|
||||
/// Automation lanes for this metatrack
|
||||
pub automation_lanes: HashMap<AutomationLaneId, AutomationLane>,
|
||||
next_automation_id: AutomationLaneId,
|
||||
@@ -231,8 +242,8 @@ impl Metatrack {
|
||||
solo: false,
|
||||
time_stretch: 1.0,
|
||||
pitch_shift: 0.0,
|
||||
offset: 0.0,
|
||||
trim_start: 0.0,
|
||||
offset: Seconds::ZERO,
|
||||
trim_start: Seconds::ZERO,
|
||||
trim_end: None,
|
||||
automation_lanes: HashMap::new(),
|
||||
next_automation_id: 0,
|
||||
@@ -252,7 +263,11 @@ impl Metatrack {
|
||||
graph
|
||||
}
|
||||
|
||||
/// Build the explicit subtrack mixing graph: SubtrackInputs → Mixer → AudioOutput.
|
||||
/// Build the default subtrack mixing graph: SubtrackInputs → Mixer → Gain → AudioOutput,
|
||||
/// with an AutomationInput ("Volume", range 0..2) feeding the Gain's CV port.
|
||||
///
|
||||
/// Existing Volume keyframes are preserved across rebuilds so that adding/removing
|
||||
/// a child track doesn't reset the automation.
|
||||
///
|
||||
/// `subtracks` is an ordered list of (backend TrackId, display name) for each child.
|
||||
/// Replaces the current graph and marks `graph_is_default = true`.
|
||||
@@ -262,35 +277,60 @@ impl Metatrack {
|
||||
sample_rate: u32,
|
||||
buffer_size: usize,
|
||||
) {
|
||||
use super::node_graph::nodes::{SubtrackInputsNode, MixerNode};
|
||||
use super::node_graph::nodes::{SubtrackInputsNode, MixerNode, GainNode, AutomationInputNode};
|
||||
use super::node_graph::nodes::AutomationKeyframe;
|
||||
use crate::time::Beats;
|
||||
|
||||
// Preserve existing Volume keyframes before rebuilding.
|
||||
let existing_volume_kfs = self.get_volume_automation_keyframes();
|
||||
|
||||
let n = subtracks.len();
|
||||
let mut graph = AudioGraph::new(sample_rate, buffer_size);
|
||||
|
||||
// SubtrackInputs node (N outputs, one per child)
|
||||
// NOTE: `new()` initialises buffers as zero-length; call `update_subtracks` immediately
|
||||
// to allocate stereo interleaved buffers (buffer_size * 2 samples each).
|
||||
let mut inputs_node = SubtrackInputsNode::new("Subtrack Inputs", subtracks);
|
||||
let subtracks_copy = inputs_node.subtracks().to_vec();
|
||||
inputs_node.update_subtracks(subtracks_copy, buffer_size);
|
||||
let inputs_id = graph.add_node(Box::new(inputs_node));
|
||||
graph.set_node_position(inputs_id, 100.0, 150.0);
|
||||
|
||||
// Mixer node (starts with 1 spare; grows as connections are made)
|
||||
// Mixer node
|
||||
let mixer_node = Box::new(MixerNode::new("Mixer"));
|
||||
let mixer_id = graph.add_node(mixer_node);
|
||||
graph.set_node_position(mixer_id, 350.0, 150.0);
|
||||
graph.set_node_position(mixer_id, 330.0, 150.0);
|
||||
|
||||
// Gain node — group volume control
|
||||
let gain_id = graph.add_node(Box::new(GainNode::new("Volume")));
|
||||
graph.set_node_position(gain_id, 520.0, 150.0);
|
||||
|
||||
// AutomationInput — drives the Gain's CV port
|
||||
let mut auto_node = AutomationInputNode::new("Volume CV");
|
||||
auto_node.set_display_name("Volume".to_string());
|
||||
auto_node.value_min = 0.0;
|
||||
auto_node.value_max = 2.0;
|
||||
auto_node.clear_keyframes();
|
||||
if existing_volume_kfs.is_empty() {
|
||||
auto_node.add_keyframe(AutomationKeyframe::new(Beats::ZERO, 1.0));
|
||||
} else {
|
||||
for kf in existing_volume_kfs {
|
||||
auto_node.add_keyframe(kf);
|
||||
}
|
||||
}
|
||||
let auto_id = graph.add_node(Box::new(auto_node));
|
||||
graph.set_node_position(auto_id, 520.0, 320.0);
|
||||
|
||||
// AudioOutput node
|
||||
let output_node = Box::new(AudioOutputNode::new("Audio Output"));
|
||||
let output_id = graph.add_node(output_node);
|
||||
graph.set_node_position(output_id, 600.0, 150.0);
|
||||
graph.set_node_position(output_id, 720.0, 150.0);
|
||||
|
||||
// Connect SubtrackInputs[i] → Mixer[i] for each subtrack
|
||||
for i in 0..n {
|
||||
let _ = graph.connect(inputs_id, i, mixer_id, i);
|
||||
}
|
||||
let _ = graph.connect(mixer_id, 0, output_id, 0);
|
||||
let _ = graph.connect(mixer_id, 0, gain_id, 0); // Mixer → Gain audio
|
||||
let _ = graph.connect(auto_id, 0, gain_id, 1); // AutomationInput → Gain CV
|
||||
let _ = graph.connect(gain_id, 0, output_id, 0); // Gain → Audio Out
|
||||
graph.set_output_node(Some(output_id));
|
||||
|
||||
self.audio_graph = graph;
|
||||
@@ -298,6 +338,22 @@ impl Metatrack {
|
||||
self.graph_is_default = true;
|
||||
}
|
||||
|
||||
/// Extract Volume AutomationInput keyframes from the current graph (if any),
|
||||
/// so they can be preserved across `set_subtrack_graph` rebuilds.
|
||||
fn get_volume_automation_keyframes(&self) -> Vec<super::node_graph::nodes::AutomationKeyframe> {
|
||||
use super::node_graph::nodes::AutomationInputNode;
|
||||
for idx in self.audio_graph.node_indices() {
|
||||
if let Some(node) = self.audio_graph.get_graph_node(idx) {
|
||||
if node.node.node_type() == "AutomationInput" {
|
||||
if let Some(auto_node) = node.node.as_any().downcast_ref::<AutomationInputNode>() {
|
||||
return auto_node.keyframes().to_vec();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Add a new subtrack port to the existing graph.
|
||||
///
|
||||
/// If `graph_is_default`: also connects the new port to a new Mixer input.
|
||||
@@ -493,7 +549,7 @@ impl Metatrack {
|
||||
}
|
||||
|
||||
/// Evaluate automation at a specific time and return effective parameters
|
||||
pub fn evaluate_automation_at_time(&self, time: f64) -> (f32, f32, f64) {
|
||||
pub fn evaluate_automation_at_time(&self, time: Beats) -> (f32, f32, Seconds) {
|
||||
let mut volume = self.volume;
|
||||
let mut time_stretch = self.time_stretch;
|
||||
let mut offset = self.offset;
|
||||
@@ -517,7 +573,7 @@ impl Metatrack {
|
||||
}
|
||||
ParameterId::TimeOffset => {
|
||||
if let Some(automated_value) = lane.evaluate(time) {
|
||||
offset = automated_value as f64;
|
||||
offset = Seconds(automated_value as f64);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -561,7 +617,7 @@ impl Metatrack {
|
||||
|
||||
/// Check whether this metatrack should produce audio at the given parent time.
|
||||
/// Returns false if the playhead is outside the trim window.
|
||||
pub fn is_active_at_time(&self, parent_playhead: f64) -> bool {
|
||||
pub fn is_active_at_time(&self, parent_playhead: Seconds) -> bool {
|
||||
let local_time = (parent_playhead - self.offset) * self.time_stretch as f64;
|
||||
if local_time < self.trim_start {
|
||||
return false;
|
||||
@@ -580,7 +636,7 @@ impl Metatrack {
|
||||
/// Time stretch affects how fast content plays: 0.5 = half speed, 2.0 = double speed
|
||||
/// Offset shifts content forward/backward in time
|
||||
/// Trim start offsets into the internal content
|
||||
pub fn transform_context(&self, ctx: RenderContext) -> RenderContext {
|
||||
pub fn transform_context<'a>(&self, ctx: RenderContext<'a>) -> RenderContext<'a> {
|
||||
let mut transformed = ctx;
|
||||
|
||||
// Apply transformations in order:
|
||||
@@ -596,7 +652,7 @@ impl Metatrack {
|
||||
let stretched = adjusted_playhead * self.time_stretch as f64;
|
||||
|
||||
// 3. Add trim_start so children see time starting from the trim point
|
||||
// If trim_start=2.0, children start seeing time 2.0 when parent reaches offset
|
||||
// If trim_start=2.0s, children start seeing time 2.0s when parent reaches offset
|
||||
transformed.playhead_seconds = stretched + self.trim_start;
|
||||
|
||||
// Accumulate time stretch for nested metatracks
|
||||
@@ -772,13 +828,13 @@ impl MidiTrack {
|
||||
// Send note-off for all 128 possible MIDI notes to silence the instrument
|
||||
let mut note_offs = Vec::new();
|
||||
for note in 0..128 {
|
||||
note_offs.push(MidiEvent::note_off(0.0, 0, note, 0));
|
||||
note_offs.push(MidiEvent::note_off(Beats::ZERO, 0, note, 0));
|
||||
}
|
||||
|
||||
// Create a silent buffer to process the note-offs
|
||||
let buffer_size = 512 * 2; // stereo
|
||||
let mut silent_buffer = vec![0.0f32; buffer_size];
|
||||
self.instrument_graph.process(&mut silent_buffer, ¬e_offs, 0.0);
|
||||
self.instrument_graph.process(&mut silent_buffer, ¬e_offs, Beats::ZERO);
|
||||
}
|
||||
|
||||
/// Queue a live MIDI event (from virtual keyboard or MIDI controller)
|
||||
@@ -805,17 +861,17 @@ impl MidiTrack {
|
||||
let mut midi_events = Vec::new();
|
||||
|
||||
if !ctx.live_only {
|
||||
let buffer_duration_seconds = output.len() as f64 / (ctx.sample_rate as f64 * ctx.channels as f64);
|
||||
let buffer_end_seconds = ctx.playhead_seconds + buffer_duration_seconds;
|
||||
let playhead_beats = ctx.playhead_beats();
|
||||
let buffer_end_beats = ctx.buffer_end_beats();
|
||||
|
||||
// Collect MIDI events from all clip instances that overlap with current time range
|
||||
// Collect MIDI events from all clip instances that overlap with current beat range
|
||||
let mut currently_active = HashSet::new();
|
||||
for instance in &self.clip_instances {
|
||||
if instance.overlaps_range(ctx.playhead_seconds, buffer_end_seconds) {
|
||||
if instance.overlaps_range(playhead_beats, buffer_end_beats) {
|
||||
currently_active.insert(instance.id);
|
||||
}
|
||||
if let Some(clip) = midi_pool.get_clip(instance.clip_id) {
|
||||
let events = instance.get_events_in_range(clip, ctx.playhead_seconds, buffer_end_seconds);
|
||||
let events = instance.get_events_in_range(clip, playhead_beats, buffer_end_beats);
|
||||
midi_events.extend(events);
|
||||
}
|
||||
}
|
||||
@@ -824,7 +880,7 @@ impl MidiTrack {
|
||||
for prev_id in &self.prev_active_instances {
|
||||
if !currently_active.contains(prev_id) {
|
||||
for note in 0..128u8 {
|
||||
midi_events.push(MidiEvent::note_off(ctx.playhead_seconds, 0, note, 0));
|
||||
midi_events.push(MidiEvent::note_off(playhead_beats, 0, note, 0));
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -836,10 +892,10 @@ impl MidiTrack {
|
||||
midi_events.extend(self.live_midi_queue.drain(..));
|
||||
|
||||
// Generate audio using instrument graph
|
||||
self.instrument_graph.process(output, &midi_events, ctx.playhead_seconds);
|
||||
self.instrument_graph.process(output, &midi_events, ctx.playhead_beats());
|
||||
|
||||
// Evaluate and apply automation (skip automation in live_only mode — no playhead to evaluate at)
|
||||
let effective_volume = if ctx.live_only { self.volume } else { self.evaluate_automation_at_time(ctx.playhead_seconds) };
|
||||
let effective_volume = if ctx.live_only { self.volume } else { self.evaluate_automation_at_time(ctx.playhead_beats()) };
|
||||
|
||||
// Apply track volume
|
||||
for sample in output.iter_mut() {
|
||||
@@ -848,7 +904,7 @@ impl MidiTrack {
|
||||
}
|
||||
|
||||
/// Evaluate automation at a specific time and return the effective volume
|
||||
fn evaluate_automation_at_time(&self, time: f64) -> f32 {
|
||||
fn evaluate_automation_at_time(&self, time: Beats) -> f32 {
|
||||
let mut volume = self.volume;
|
||||
|
||||
// Check for volume automation
|
||||
@@ -1081,12 +1137,9 @@ impl AudioTrack {
|
||||
&mut self,
|
||||
output: &mut [f32],
|
||||
pool: &AudioClipPool,
|
||||
playhead_seconds: f64,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
ctx: RenderContext<'_>,
|
||||
) -> usize {
|
||||
let buffer_duration_seconds = output.len() as f64 / (sample_rate as f64 * channels as f64);
|
||||
let buffer_end_seconds = playhead_seconds + buffer_duration_seconds;
|
||||
let buffer_end = ctx.buffer_end();
|
||||
|
||||
// Split borrow: take clip_render_buffer out to avoid borrow conflict with &self methods
|
||||
let mut clip_buffer = std::mem::take(&mut self.clip_render_buffer);
|
||||
@@ -1096,16 +1149,8 @@ impl AudioTrack {
|
||||
|
||||
// Render all active clip instances into the buffer
|
||||
for clip in &self.clips {
|
||||
// Check if clip overlaps with current buffer time range
|
||||
if clip.external_start < buffer_end_seconds && clip.external_end() > playhead_seconds {
|
||||
rendered += self.render_clip(
|
||||
clip,
|
||||
&mut clip_buffer,
|
||||
pool,
|
||||
playhead_seconds,
|
||||
sample_rate,
|
||||
channels,
|
||||
);
|
||||
if clip.external_start_secs(ctx.tempo_map) < buffer_end && clip.external_end_secs(ctx.tempo_map) > ctx.playhead_seconds {
|
||||
rendered += self.render_clip(clip, &mut clip_buffer, pool, ctx);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1123,13 +1168,13 @@ impl AudioTrack {
|
||||
}
|
||||
|
||||
// Process through the effects graph (this will write to output buffer)
|
||||
self.effects_graph.process(output, &[], playhead_seconds);
|
||||
self.effects_graph.process(output, &[], ctx.playhead_beats());
|
||||
|
||||
// Put the buffer back for reuse next callback
|
||||
self.clip_render_buffer = clip_buffer;
|
||||
|
||||
// Evaluate and apply automation
|
||||
let effective_volume = self.evaluate_automation_at_time(playhead_seconds);
|
||||
let effective_volume = self.evaluate_automation_at_time(ctx.playhead_beats());
|
||||
|
||||
// Apply track volume
|
||||
for sample in output.iter_mut() {
|
||||
@@ -1140,7 +1185,7 @@ impl AudioTrack {
|
||||
}
|
||||
|
||||
/// Evaluate automation at a specific time and return the effective volume
|
||||
fn evaluate_automation_at_time(&self, time: f64) -> f32 {
|
||||
fn evaluate_automation_at_time(&self, time: Beats) -> f32 {
|
||||
let mut volume = self.volume;
|
||||
|
||||
// Check for volume automation
|
||||
@@ -1169,49 +1214,40 @@ impl AudioTrack {
|
||||
clip: &AudioClipInstance,
|
||||
output: &mut [f32],
|
||||
pool: &AudioClipPool,
|
||||
playhead_seconds: f64,
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
ctx: RenderContext<'_>,
|
||||
) -> usize {
|
||||
let buffer_duration_seconds = output.len() as f64 / (sample_rate as f64 * channels as f64);
|
||||
let buffer_end_seconds = playhead_seconds + buffer_duration_seconds;
|
||||
let playhead = ctx.playhead_seconds;
|
||||
let buffer_end = ctx.buffer_end();
|
||||
let tempo_map = ctx.tempo_map;
|
||||
let sample_rate = ctx.sample_rate;
|
||||
let channels = ctx.channels;
|
||||
|
||||
// Determine the time range we need to render (intersection of buffer and clip external bounds)
|
||||
let render_start_seconds = playhead_seconds.max(clip.external_start);
|
||||
let render_end_seconds = buffer_end_seconds.min(clip.external_end());
|
||||
let render_start = playhead.max(clip.external_start_secs(tempo_map));
|
||||
let render_end = buffer_end.min(clip.external_end_secs(tempo_map));
|
||||
|
||||
// If no overlap, return early
|
||||
if render_start_seconds >= render_end_seconds {
|
||||
if render_start >= render_end {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let internal_duration = clip.internal_duration();
|
||||
if internal_duration <= 0.0 {
|
||||
if internal_duration <= Seconds::ZERO {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Calculate combined gain
|
||||
let combined_gain = clip.gain;
|
||||
|
||||
let mut total_rendered = 0;
|
||||
|
||||
// Process the render range sample by sample (or in chunks for efficiency)
|
||||
// For looping clips, we need to handle wrap-around at the loop boundary
|
||||
let samples_per_second = sample_rate as f64 * channels as f64;
|
||||
|
||||
// For now, render in a simpler way - iterate through the timeline range
|
||||
// and use get_content_position for each sample position
|
||||
let output_start_offset = ((render_start_seconds - playhead_seconds) * samples_per_second + 0.5) as usize;
|
||||
let output_end_offset = ((render_end_seconds - playhead_seconds) * samples_per_second + 0.5) as usize;
|
||||
let output_start_offset = ((render_start - playhead).0 * samples_per_second + 0.5) as usize;
|
||||
let output_end_offset = ((render_end - playhead).0 * samples_per_second + 0.5) as usize;
|
||||
|
||||
if output_end_offset > output.len() || output_start_offset > output.len() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// If not looping, we can render in one chunk (more efficient)
|
||||
if !clip.is_looping() {
|
||||
// Simple case: no looping
|
||||
let content_start = clip.get_content_position(render_start_seconds).unwrap_or(clip.internal_start);
|
||||
if !clip.is_looping(tempo_map) {
|
||||
let content_start = clip.get_content_position(render_start, tempo_map).unwrap_or(clip.internal_start);
|
||||
let output_len = output.len();
|
||||
let output_slice = &mut output[output_start_offset..output_end_offset.min(output_len)];
|
||||
|
||||
@@ -1225,23 +1261,20 @@ impl AudioTrack {
|
||||
clip.read_ahead.as_deref(),
|
||||
);
|
||||
} else {
|
||||
// Looping case: need to handle wrap-around at loop boundaries
|
||||
// Render in segments, one per loop iteration
|
||||
let mut timeline_pos = render_start_seconds;
|
||||
// Looping case: handle wrap-around at loop boundaries
|
||||
let mut timeline_pos = render_start;
|
||||
let mut output_offset = output_start_offset;
|
||||
|
||||
while timeline_pos < render_end_seconds && output_offset < output.len() {
|
||||
// Calculate position within the loop
|
||||
let relative_pos = timeline_pos - clip.external_start;
|
||||
let loop_offset = relative_pos % internal_duration;
|
||||
let content_pos = clip.internal_start + loop_offset;
|
||||
while timeline_pos < render_end && output_offset < output.len() {
|
||||
let relative_pos = timeline_pos - clip.external_start_secs(tempo_map);
|
||||
let loop_offset = relative_pos.0 % internal_duration.0;
|
||||
let content_pos = clip.internal_start + Seconds(loop_offset);
|
||||
|
||||
// Calculate how much we can render before hitting the loop boundary
|
||||
let time_to_loop_end = internal_duration - loop_offset;
|
||||
let time_to_render_end = render_end_seconds - timeline_pos;
|
||||
let time_to_loop_end = Seconds(internal_duration.0 - loop_offset);
|
||||
let time_to_render_end = render_end - timeline_pos;
|
||||
let chunk_duration = time_to_loop_end.min(time_to_render_end);
|
||||
|
||||
let chunk_samples = (chunk_duration * samples_per_second) as usize;
|
||||
let chunk_samples = (chunk_duration.0 * samples_per_second) as usize;
|
||||
let chunk_samples = chunk_samples.min(output.len() - output_offset);
|
||||
|
||||
if chunk_samples == 0 {
|
||||
@@ -1262,7 +1295,7 @@ impl AudioTrack {
|
||||
|
||||
total_rendered += rendered;
|
||||
output_offset += chunk_samples;
|
||||
timeline_pos += chunk_duration;
|
||||
timeline_pos = timeline_pos + chunk_duration;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
//! Streaming min/max waveform LOD pyramid.
|
||||
//!
|
||||
//! A waveform pyramid is a tree of zoom levels. **Index = tree depth:**
|
||||
//! `levels[0]` is the **root** (a single texel — the min/max envelope of the
|
||||
//! whole file, lowest resolution); each deeper level is `BRANCH`× finer, and
|
||||
//! `levels.last()` is the **floor** (one texel per `floor_samples_per_texel`
|
||||
//! source frames — the finest *persisted* level). A node's children live at
|
||||
//! `index + 1`, so the residency invariant ("a node is cleared only after its
|
||||
//! children") reads straight off the index.
|
||||
//!
|
||||
//! Below the floor (finer than the floor bucket) is *not* stored; the caller
|
||||
//! re-decodes the source window on demand for true per-sample detail.
|
||||
//!
|
||||
//! The builder is **streaming**: samples are pushed once, in order, and only the
|
||||
//! finest level is accumulated (~`total_frames / floor` texels); the coarser
|
||||
//! levels are derived by repeated `BRANCH:1` min/max reduction in [`finish`].
|
||||
//! This yields the identical pyramid to an in-stream cascade (each parent = the
|
||||
//! min/max of its children) without ever holding the full sample buffer.
|
||||
//!
|
||||
//! **Ragged edges are handled by reducing over available children:** a bucket
|
||||
//! whose group is partial (1..BRANCH children, or `< floor` samples at the floor)
|
||||
//! simply takes the min/max of what's there — no value padding. Padding to a
|
||||
//! regular shape, if ever needed, is a GPU-texture/tile concern, not the data's.
|
||||
//!
|
||||
//! Each texel carries per-channel min/max for up to two channels
|
||||
//! (`Lmin,Lmax,Rmin,Rmax`), matching the GPU waveform texture; mono mirrors the
|
||||
//! left channel into the right.
|
||||
//!
|
||||
//! [`finish`]: WaveformPyramidBuilder::finish
|
||||
|
||||
/// Reduction factor between adjacent pyramid levels.
|
||||
pub const BRANCH: u32 = 4;
|
||||
|
||||
/// Default finest-level resolution (source frames per floor texel). Trades
|
||||
/// on-disk pyramid size against how soon zoom-in must re-decode the source.
|
||||
pub const DEFAULT_FLOOR_SAMPLES_PER_TEXEL: u32 = 256;
|
||||
|
||||
/// One waveform texel: per-channel min/max (stereo; mono duplicates left→right).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Texel {
|
||||
pub l_min: f32,
|
||||
pub l_max: f32,
|
||||
pub r_min: f32,
|
||||
pub r_max: f32,
|
||||
}
|
||||
|
||||
impl Texel {
|
||||
const EMPTY: Texel = Texel {
|
||||
l_min: f32::INFINITY,
|
||||
l_max: f32::NEG_INFINITY,
|
||||
r_min: f32::INFINITY,
|
||||
r_max: f32::NEG_INFINITY,
|
||||
};
|
||||
|
||||
#[inline]
|
||||
fn include_sample(&mut self, l: f32, r: f32) {
|
||||
self.l_min = self.l_min.min(l);
|
||||
self.l_max = self.l_max.max(l);
|
||||
self.r_min = self.r_min.min(r);
|
||||
self.r_max = self.r_max.max(r);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn include_texel(&mut self, c: &Texel) {
|
||||
self.l_min = self.l_min.min(c.l_min);
|
||||
self.l_max = self.l_max.max(c.l_max);
|
||||
self.r_min = self.r_min.min(c.r_min);
|
||||
self.r_max = self.r_max.max(c.r_max);
|
||||
}
|
||||
}
|
||||
|
||||
/// A built min/max LOD pyramid, **root-first**: `levels[0]` is the coarsest
|
||||
/// (whole-file envelope), `levels.last()` is the finest persisted (floor).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct WaveformPyramid {
|
||||
pub floor_samples_per_texel: u32,
|
||||
pub branch: u32,
|
||||
pub channels: u32,
|
||||
pub total_frames: u64,
|
||||
pub levels: Vec<Vec<Texel>>,
|
||||
}
|
||||
|
||||
impl WaveformPyramid {
|
||||
/// Coarsest level — a single texel (whole-file envelope), or empty if no
|
||||
/// samples were pushed.
|
||||
pub fn root(&self) -> &[Texel] {
|
||||
self.levels.first().map_or(&[][..], |v| v)
|
||||
}
|
||||
|
||||
/// Finest persisted level (`floor_samples_per_texel` frames per texel).
|
||||
pub fn floor(&self) -> &[Texel] {
|
||||
self.levels.last().map_or(&[][..], |v| v)
|
||||
}
|
||||
|
||||
/// Number of levels (tree depth + 1).
|
||||
pub fn depth(&self) -> usize {
|
||||
self.levels.len()
|
||||
}
|
||||
|
||||
/// Serialize to a compact binary blob (for persisting in the `.beam`
|
||||
/// container). Header carries `B`/branch/channels/total_frames + per-level
|
||||
/// lengths, then root-first texel data (`f32` min/max).
|
||||
pub fn to_bytes(&self) -> Vec<u8> {
|
||||
let total_texels: usize = self.levels.iter().map(|l| l.len()).sum();
|
||||
let mut out = Vec::with_capacity(32 + self.levels.len() * 4 + total_texels * 16);
|
||||
out.extend_from_slice(b"LBWF");
|
||||
out.extend_from_slice(&1u32.to_le_bytes()); // format version
|
||||
out.extend_from_slice(&self.floor_samples_per_texel.to_le_bytes());
|
||||
out.extend_from_slice(&self.branch.to_le_bytes());
|
||||
out.extend_from_slice(&self.channels.to_le_bytes());
|
||||
out.extend_from_slice(&self.total_frames.to_le_bytes());
|
||||
out.extend_from_slice(&(self.levels.len() as u32).to_le_bytes());
|
||||
for level in &self.levels {
|
||||
out.extend_from_slice(&(level.len() as u32).to_le_bytes());
|
||||
}
|
||||
for level in &self.levels {
|
||||
for t in level {
|
||||
out.extend_from_slice(&t.l_min.to_le_bytes());
|
||||
out.extend_from_slice(&t.l_max.to_le_bytes());
|
||||
out.extend_from_slice(&t.r_min.to_le_bytes());
|
||||
out.extend_from_slice(&t.r_max.to_le_bytes());
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Reconstruct from [`WaveformPyramid::to_bytes`].
|
||||
pub fn from_bytes(data: &[u8]) -> Result<WaveformPyramid, String> {
|
||||
let mut r = ByteReader::new(data);
|
||||
if r.take(4)? != b"LBWF" {
|
||||
return Err("Not a waveform pyramid blob".to_string());
|
||||
}
|
||||
let version = r.u32()?;
|
||||
if version != 1 {
|
||||
return Err(format!("Unsupported waveform pyramid version {}", version));
|
||||
}
|
||||
let floor_samples_per_texel = r.u32()?;
|
||||
let branch = r.u32()?;
|
||||
let channels = r.u32()?;
|
||||
let total_frames = r.u64()?;
|
||||
let num_levels = r.u32()? as usize;
|
||||
let mut level_lens = Vec::with_capacity(num_levels);
|
||||
for _ in 0..num_levels {
|
||||
level_lens.push(r.u32()? as usize);
|
||||
}
|
||||
let mut levels = Vec::with_capacity(num_levels);
|
||||
for &len in &level_lens {
|
||||
let mut level = Vec::with_capacity(len);
|
||||
for _ in 0..len {
|
||||
level.push(Texel {
|
||||
l_min: r.f32()?,
|
||||
l_max: r.f32()?,
|
||||
r_min: r.f32()?,
|
||||
r_max: r.f32()?,
|
||||
});
|
||||
}
|
||||
levels.push(level);
|
||||
}
|
||||
Ok(WaveformPyramid {
|
||||
floor_samples_per_texel,
|
||||
branch,
|
||||
channels,
|
||||
total_frames,
|
||||
levels,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Minimal little-endian byte cursor for [`WaveformPyramid::from_bytes`].
|
||||
struct ByteReader<'a> {
|
||||
data: &'a [u8],
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl<'a> ByteReader<'a> {
|
||||
fn new(data: &'a [u8]) -> Self {
|
||||
Self { data, pos: 0 }
|
||||
}
|
||||
fn take(&mut self, n: usize) -> Result<&'a [u8], String> {
|
||||
let end = self.pos.checked_add(n).ok_or("overflow")?;
|
||||
if end > self.data.len() {
|
||||
return Err("Truncated waveform pyramid blob".to_string());
|
||||
}
|
||||
let s = &self.data[self.pos..end];
|
||||
self.pos = end;
|
||||
Ok(s)
|
||||
}
|
||||
fn u32(&mut self) -> Result<u32, String> {
|
||||
Ok(u32::from_le_bytes(self.take(4)?.try_into().unwrap()))
|
||||
}
|
||||
fn u64(&mut self) -> Result<u64, String> {
|
||||
Ok(u64::from_le_bytes(self.take(8)?.try_into().unwrap()))
|
||||
}
|
||||
fn f32(&mut self) -> Result<f32, String> {
|
||||
Ok(f32::from_le_bytes(self.take(4)?.try_into().unwrap()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Streaming builder for a [`WaveformPyramid`]. See the module docs.
|
||||
pub struct WaveformPyramidBuilder {
|
||||
floor: u32,
|
||||
branch: u32,
|
||||
channels: u32,
|
||||
total_frames: u64,
|
||||
floor_level: Vec<Texel>,
|
||||
acc: Texel,
|
||||
acc_count: u32,
|
||||
}
|
||||
|
||||
impl WaveformPyramidBuilder {
|
||||
pub fn new(channels: u32, floor_samples_per_texel: u32) -> Self {
|
||||
Self {
|
||||
floor: floor_samples_per_texel.max(1),
|
||||
branch: BRANCH,
|
||||
channels: channels.max(1),
|
||||
total_frames: 0,
|
||||
floor_level: Vec::new(),
|
||||
acc: Texel::EMPTY,
|
||||
acc_count: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Pre-reserve the floor `Vec` from an estimated total frame count (e.g. the
|
||||
/// probe's `total_frames`), to avoid reallocations during streaming. Purely a
|
||||
/// hint — the final size is set by the actual number of frames pushed.
|
||||
pub fn reserve_for_frames(&mut self, estimated_frames: u64) {
|
||||
let est_texels = (estimated_frames / self.floor as u64).saturating_add(1);
|
||||
self.floor_level.reserve(est_texels.min(usize::MAX as u64) as usize);
|
||||
}
|
||||
|
||||
/// Push a block of interleaved samples (`channels` per frame). Partial
|
||||
/// trailing frames (fewer than `channels`) are ignored.
|
||||
pub fn push_interleaved(&mut self, samples: &[f32]) {
|
||||
let ch = self.channels as usize;
|
||||
for frame in samples.chunks_exact(ch) {
|
||||
let l = frame[0];
|
||||
let r = if ch >= 2 { frame[1] } else { l };
|
||||
self.push_frame(l, r);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn push_frame(&mut self, l: f32, r: f32) {
|
||||
self.total_frames += 1;
|
||||
self.acc.include_sample(l, r);
|
||||
self.acc_count += 1;
|
||||
if self.acc_count >= self.floor {
|
||||
self.floor_level.push(std::mem::replace(&mut self.acc, Texel::EMPTY));
|
||||
self.acc_count = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/// Flush the trailing partial bucket and reduce up to the root.
|
||||
pub fn finish(mut self) -> WaveformPyramid {
|
||||
if self.acc_count > 0 {
|
||||
self.floor_level.push(self.acc);
|
||||
}
|
||||
|
||||
// Build finest-first by repeated BRANCH:1 reduction until one texel.
|
||||
// The shape is fully determined by the floor texel count; the last group
|
||||
// at each level may be ragged (1..BRANCH children) and reduces over what
|
||||
// it has.
|
||||
let mut levels = vec![std::mem::take(&mut self.floor_level)];
|
||||
let branch = self.branch as usize;
|
||||
while levels.last().map_or(0, |l| l.len()) > 1 {
|
||||
let prev = levels.last().unwrap();
|
||||
let mut next = Vec::with_capacity(prev.len().div_ceil(branch));
|
||||
for chunk in prev.chunks(branch) {
|
||||
let mut t = Texel::EMPTY;
|
||||
for c in chunk {
|
||||
t.include_texel(c);
|
||||
}
|
||||
next.push(t);
|
||||
}
|
||||
levels.push(next);
|
||||
}
|
||||
// Output is root-first (convention B): levels[0] = root, last = floor.
|
||||
levels.reverse();
|
||||
|
||||
WaveformPyramid {
|
||||
floor_samples_per_texel: self.floor,
|
||||
branch: self.branch,
|
||||
channels: self.channels,
|
||||
total_frames: self.total_frames,
|
||||
levels,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Tests live in `daw-backend/tests/waveform_pyramid.rs` (integration tests) so
|
||||
// they build the lib in normal mode, independent of the crate's pre-existing
|
||||
// broken `#[cfg(test)]` unit tests (automation.rs).
|
||||
@@ -6,6 +6,7 @@ use crate::audio::midi::MidiEvent;
|
||||
use crate::audio::buffer_pool::BufferPoolStats;
|
||||
use crate::audio::node_graph::nodes::LoopMode;
|
||||
use crate::io::WaveformPeak;
|
||||
use crate::time::{Beats, Seconds};
|
||||
|
||||
/// Commands sent from UI/control thread to audio thread
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -113,7 +114,7 @@ pub enum Command {
|
||||
|
||||
// Recording commands
|
||||
/// Start recording on a track (track_id, start_time)
|
||||
StartRecording(TrackId, f64),
|
||||
StartRecording(TrackId, Beats),
|
||||
/// Stop the current recording
|
||||
StopRecording,
|
||||
/// Pause the current recording
|
||||
@@ -123,7 +124,7 @@ pub enum Command {
|
||||
|
||||
// MIDI Recording commands
|
||||
/// Start MIDI recording on a track (track_id, clip_id, start_time)
|
||||
StartMidiRecording(TrackId, MidiClipId, f64),
|
||||
StartMidiRecording(TrackId, MidiClipId, Beats),
|
||||
/// Stop the current MIDI recording
|
||||
StopMidiRecording,
|
||||
|
||||
@@ -144,7 +145,8 @@ pub enum Command {
|
||||
SetMetronomeEnabled(bool),
|
||||
/// Set project tempo and time signature (bpm, (numerator, denominator))
|
||||
SetTempo(f32, (u32, u32)),
|
||||
|
||||
/// Replace the entire tempo map (multi-entry variable tempo support)
|
||||
SetTempoMap(crate::TempoMap),
|
||||
// Node graph commands
|
||||
/// Add a node to a track's instrument graph (track_id, node_type, position_x, position_y)
|
||||
GraphAddNode(TrackId, String, f32, f32),
|
||||
@@ -286,7 +288,7 @@ pub enum AudioEvent {
|
||||
/// Recording started (track_id, clip_id, sample_rate, channels)
|
||||
RecordingStarted(TrackId, ClipId, u32, u32),
|
||||
/// Recording progress update (clip_id, current_duration)
|
||||
RecordingProgress(ClipId, f64),
|
||||
RecordingProgress(ClipId, Seconds),
|
||||
/// Recording stopped (clip_id, pool_index, waveform)
|
||||
RecordingStopped(ClipId, usize, Vec<WaveformPeak>),
|
||||
/// Recording error (error_message)
|
||||
@@ -294,8 +296,8 @@ pub enum AudioEvent {
|
||||
/// MIDI recording stopped (track_id, clip_id, note_count)
|
||||
MidiRecordingStopped(TrackId, MidiClipId, usize),
|
||||
/// MIDI recording progress (track_id, clip_id, duration, notes)
|
||||
/// Notes format: (start_time, note, velocity, duration)
|
||||
MidiRecordingProgress(TrackId, MidiClipId, f64, Vec<(f64, u8, u8, f64)>),
|
||||
/// Notes format: (start_time, note, velocity, duration) — all times in beats
|
||||
MidiRecordingProgress(TrackId, MidiClipId, Beats, Vec<(Beats, u8, u8, Beats)>),
|
||||
/// Project has been reset
|
||||
ProjectReset,
|
||||
/// MIDI note started playing (note, velocity)
|
||||
@@ -310,8 +312,8 @@ pub enum AudioEvent {
|
||||
GraphConnectionError(TrackId, String),
|
||||
/// Graph state changed (for full UI sync)
|
||||
GraphStateChanged(TrackId),
|
||||
/// Preset fully loaded (track_id) - emitted after all nodes and samples are loaded
|
||||
GraphPresetLoaded(TrackId),
|
||||
/// Preset fully loaded (track_id, preset_name) - emitted after all nodes and samples are loaded
|
||||
GraphPresetLoaded(TrackId, String),
|
||||
/// Preset has been saved to file (track_id, preset_path)
|
||||
GraphPresetSaved(TrackId, String),
|
||||
/// Script compilation result (track_id, node_id, success, error, ui_declaration, source)
|
||||
@@ -428,8 +430,6 @@ pub enum Query {
|
||||
/// Add a MIDI clip instance to a track synchronously (track_id, instance) - returns instance ID
|
||||
/// The clip must already exist in the MidiClipPool
|
||||
AddMidiClipInstanceSync(TrackId, crate::audio::midi::MidiClipInstance),
|
||||
/// Add an audio file to the pool synchronously (path, data, channels, sample_rate) - returns pool index
|
||||
AddAudioFileSync(String, Vec<f32>, u32, u32),
|
||||
/// Import an audio file synchronously (path) - returns pool index.
|
||||
/// Does the same work as Command::ImportAudio (mmap for PCM, streaming
|
||||
/// setup for compressed) but returns the real pool index in the response.
|
||||
@@ -438,12 +438,20 @@ pub enum Query {
|
||||
/// problem for very large files, switch to async import with event-based
|
||||
/// pool index reconciliation.
|
||||
ImportAudioSync(std::path::PathBuf),
|
||||
/// Add the audio track of a video file as a streaming pool entry (FFmpeg,
|
||||
/// decoded on demand — no extraction). Probes the audio track and returns
|
||||
/// the pool index. Response: `AudioImportedSync`.
|
||||
AddVideoAudioSync(std::path::PathBuf),
|
||||
/// Get raw audio samples from pool (pool_index) - returns (samples, sample_rate, channels)
|
||||
GetPoolAudioSamples(usize),
|
||||
/// Get a clone of the current project for serialization
|
||||
GetProject,
|
||||
/// Set the project (replaces current project state)
|
||||
SetProject(Box<crate::audio::project::Project>),
|
||||
/// Install the host's packed-media byte-source factory (for streaming
|
||||
/// container-packed audio on load). Sent before `SetProject` so bulk
|
||||
/// activation can open packed sources.
|
||||
SetBlobSourceFactory(std::sync::Arc<dyn crate::audio::disk_reader::AudioBlobSourceFactory>),
|
||||
/// Duplicate a MIDI clip in the pool, returning the new clip's ID
|
||||
DuplicateMidiClipSync(MidiClipId),
|
||||
/// Get whether a track's graph is still the auto-generated default
|
||||
@@ -514,10 +522,10 @@ pub enum QueryResponse {
|
||||
AudioExported(Result<(), String>),
|
||||
/// MIDI clip instance added (returns instance ID)
|
||||
MidiClipInstanceAdded(Result<MidiClipInstanceId, String>),
|
||||
/// Audio file added to pool (returns pool index)
|
||||
AudioFileAddedSync(Result<usize, String>),
|
||||
/// Audio file imported to pool (returns pool index)
|
||||
AudioImportedSync(Result<usize, String>),
|
||||
/// Packed-media byte-source factory installed
|
||||
BlobSourceFactorySet(Result<(), String>),
|
||||
/// Raw audio samples from pool (samples, sample_rate, channels)
|
||||
PoolAudioSamples(Result<(Vec<f32>, u32, u32), String>),
|
||||
/// Project retrieved
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
+32
-127
@@ -1,164 +1,69 @@
|
||||
use crate::audio::midi::{MidiClip, MidiClipId, MidiEvent};
|
||||
use crate::time::Beats;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
|
||||
/// Load a MIDI file and convert it to a MidiClip
|
||||
/// Load a MIDI file and convert it to a MidiClip.
|
||||
///
|
||||
/// Event timestamps are stored as beat positions: `tick / ticks_per_beat`.
|
||||
/// Tempo events in the MIDI file only affect wall-clock playback speed — not the
|
||||
/// beat grid — so they are ignored here.
|
||||
pub fn load_midi_file<P: AsRef<Path>>(
|
||||
path: P,
|
||||
clip_id: MidiClipId,
|
||||
_sample_rate: u32,
|
||||
) -> Result<MidiClip, String> {
|
||||
// Read the MIDI file
|
||||
let data = fs::read(path.as_ref()).map_err(|e| format!("Failed to read MIDI file: {}", e))?;
|
||||
|
||||
// Parse with midly
|
||||
let smf = midly::Smf::parse(&data).map_err(|e| format!("Failed to parse MIDI file: {}", e))?;
|
||||
|
||||
// Convert timing to ticks per second
|
||||
let ticks_per_beat = match smf.header.timing {
|
||||
midly::Timing::Metrical(tpb) => tpb.as_int() as f64,
|
||||
midly::Timing::Timecode(fps, subframe) => {
|
||||
// For timecode, calculate equivalent ticks per second
|
||||
// Timecode-based MIDI: treat subframes as ticks per beat
|
||||
(fps.as_f32() * subframe as f32) as f64
|
||||
}
|
||||
};
|
||||
|
||||
// First pass: collect all events with their tick positions and tempo changes
|
||||
#[derive(Debug)]
|
||||
enum RawEvent {
|
||||
Midi {
|
||||
tick: u64,
|
||||
channel: u8,
|
||||
message: midly::MidiMessage,
|
||||
},
|
||||
Tempo {
|
||||
tick: u64,
|
||||
microseconds_per_beat: f64,
|
||||
},
|
||||
}
|
||||
let mut events = Vec::new();
|
||||
let mut max_tick = 0u64;
|
||||
|
||||
let mut raw_events = Vec::new();
|
||||
let mut max_time_ticks = 0u64;
|
||||
|
||||
// Collect all events from all tracks with their absolute tick positions
|
||||
for track in &smf.tracks {
|
||||
let mut current_tick = 0u64;
|
||||
|
||||
for event in track {
|
||||
current_tick += event.delta.as_int() as u64;
|
||||
max_time_ticks = max_time_ticks.max(current_tick);
|
||||
max_tick = max_tick.max(current_tick);
|
||||
|
||||
let timestamp = Beats(current_tick as f64 / ticks_per_beat);
|
||||
|
||||
match event.kind {
|
||||
midly::TrackEventKind::Midi { channel, message } => {
|
||||
raw_events.push(RawEvent::Midi {
|
||||
tick: current_tick,
|
||||
channel: channel.as_int(),
|
||||
message,
|
||||
});
|
||||
}
|
||||
midly::TrackEventKind::Meta(midly::MetaMessage::Tempo(tempo)) => {
|
||||
raw_events.push(RawEvent::Tempo {
|
||||
tick: current_tick,
|
||||
microseconds_per_beat: tempo.as_int() as f64,
|
||||
});
|
||||
}
|
||||
_ => {
|
||||
// Ignore other meta events
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Sort all events by tick position
|
||||
raw_events.sort_by_key(|e| match e {
|
||||
RawEvent::Midi { tick, .. } => *tick,
|
||||
RawEvent::Tempo { tick, .. } => *tick,
|
||||
});
|
||||
|
||||
// Second pass: convert ticks to timestamps with proper tempo tracking
|
||||
let mut events = Vec::new();
|
||||
let mut microseconds_per_beat = 500000.0; // Default: 120 BPM
|
||||
let mut last_tick = 0u64;
|
||||
let mut accumulated_time = 0.0; // Time in seconds
|
||||
|
||||
for raw_event in raw_events {
|
||||
match raw_event {
|
||||
RawEvent::Tempo {
|
||||
tick,
|
||||
microseconds_per_beat: new_tempo,
|
||||
} => {
|
||||
// Update accumulated time up to this tempo change
|
||||
let delta_ticks = tick - last_tick;
|
||||
let delta_time = (delta_ticks as f64 / ticks_per_beat)
|
||||
* (microseconds_per_beat / 1_000_000.0);
|
||||
accumulated_time += delta_time;
|
||||
last_tick = tick;
|
||||
|
||||
// Update tempo for future events
|
||||
microseconds_per_beat = new_tempo;
|
||||
}
|
||||
RawEvent::Midi {
|
||||
tick,
|
||||
channel,
|
||||
message,
|
||||
} => {
|
||||
// Calculate time for this event
|
||||
let delta_ticks = tick - last_tick;
|
||||
let delta_time = (delta_ticks as f64 / ticks_per_beat)
|
||||
* (microseconds_per_beat / 1_000_000.0);
|
||||
accumulated_time += delta_time;
|
||||
last_tick = tick;
|
||||
|
||||
// Store timestamp in seconds (sample-rate independent)
|
||||
let timestamp = accumulated_time;
|
||||
|
||||
match message {
|
||||
midly::MidiMessage::NoteOn { key, vel } => {
|
||||
let velocity = vel.as_int();
|
||||
if velocity > 0 {
|
||||
events.push(MidiEvent::note_on(
|
||||
timestamp,
|
||||
channel,
|
||||
key.as_int(),
|
||||
velocity,
|
||||
));
|
||||
} else {
|
||||
events.push(MidiEvent::note_off(timestamp, channel, key.as_int(), 64));
|
||||
let ch = channel.as_int();
|
||||
match message {
|
||||
midly::MidiMessage::NoteOn { key, vel } => {
|
||||
let velocity = vel.as_int();
|
||||
if velocity > 0 {
|
||||
events.push(MidiEvent::note_on(timestamp, ch, key.as_int(), velocity));
|
||||
} else {
|
||||
events.push(MidiEvent::note_off(timestamp, ch, key.as_int(), 64));
|
||||
}
|
||||
}
|
||||
}
|
||||
midly::MidiMessage::NoteOff { key, vel } => {
|
||||
events.push(MidiEvent::note_off(
|
||||
timestamp,
|
||||
channel,
|
||||
key.as_int(),
|
||||
vel.as_int(),
|
||||
));
|
||||
}
|
||||
midly::MidiMessage::Controller { controller, value } => {
|
||||
let status = 0xB0 | channel;
|
||||
events.push(MidiEvent::new(
|
||||
timestamp,
|
||||
status,
|
||||
controller.as_int(),
|
||||
value.as_int(),
|
||||
));
|
||||
}
|
||||
_ => {
|
||||
// Ignore other MIDI messages
|
||||
midly::MidiMessage::NoteOff { key, vel } => {
|
||||
events.push(MidiEvent::note_off(timestamp, ch, key.as_int(), vel.as_int()));
|
||||
}
|
||||
midly::MidiMessage::Controller { controller, value } => {
|
||||
let status = 0xB0 | ch;
|
||||
events.push(MidiEvent::new(timestamp, status, controller.as_int(), value.as_int()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
_ => {} // Tempo and other meta events don't affect beat positions
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate final clip duration
|
||||
let final_delta_ticks = max_time_ticks - last_tick;
|
||||
let final_delta_time =
|
||||
(final_delta_ticks as f64 / ticks_per_beat) * (microseconds_per_beat / 1_000_000.0);
|
||||
let duration_seconds = accumulated_time + final_delta_time;
|
||||
|
||||
// Create the MIDI clip (content only, positioning happens when creating instance)
|
||||
let clip = MidiClip::new(clip_id, events, duration_seconds, "Imported MIDI".to_string());
|
||||
|
||||
let duration = Beats(max_tick as f64 / ticks_per_beat);
|
||||
let clip = MidiClip::new(clip_id, events, duration, "Imported MIDI".to_string());
|
||||
Ok(clip)
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
|
||||
pub mod audio;
|
||||
pub mod command;
|
||||
pub mod time;
|
||||
pub mod tempo_map;
|
||||
pub mod dsp;
|
||||
pub mod effects;
|
||||
pub mod io;
|
||||
@@ -18,6 +20,8 @@ pub use audio::{
|
||||
TrackNode,
|
||||
};
|
||||
pub use audio::node_graph::{GraphPreset, AudioGraph, PresetMetadata, SerializedConnection, SerializedNode};
|
||||
pub use time::{Beats, Seconds};
|
||||
pub use tempo_map::{TempoEntry, TempoInterpolation, TempoMap, beats_to_seconds_stack, seconds_to_beats_stack};
|
||||
pub use command::{AudioEvent, Command, OscilloscopeData};
|
||||
pub use command::types::AutomationKeyframeData;
|
||||
pub use io::{load_midi_file, AudioFile, WaveformChunk, WaveformChunkKey, WaveformPeak, WavWriter};
|
||||
@@ -90,7 +94,7 @@ impl AudioSystem {
|
||||
// Create input ringbuffer for recording (large buffer for audio samples)
|
||||
// Buffer size: 10 seconds of audio at 48kHz stereo = 48000 * 2 * 10 = 960000 samples
|
||||
let input_buffer_size = (sample_rate * channels * 10) as usize;
|
||||
let (mut input_tx, input_rx) = rtrb::RingBuffer::new(input_buffer_size);
|
||||
let (input_tx, input_rx) = rtrb::RingBuffer::new(input_buffer_size);
|
||||
|
||||
// Create mirror ringbuffer for streaming recorded audio to UI (live waveform)
|
||||
let (mirror_tx, mirror_rx) = rtrb::RingBuffer::new(input_buffer_size);
|
||||
|
||||
@@ -0,0 +1,332 @@
|
||||
//! TempoMap — beats ↔ seconds conversion with variable tempo support.
|
||||
//!
|
||||
//! Positions are stored in **beats** throughout the project; `TempoMap` converts
|
||||
//! between beats and seconds at render / scheduling time.
|
||||
//!
|
||||
//! # Interpolation
|
||||
//! Each `TempoEntry` has an `interpolation` field that controls how the BPM
|
||||
//! changes between that entry and the next:
|
||||
//! - `Step`: BPM is constant from this entry's beat until the next entry. Instant change.
|
||||
//! - `Linear`: BPM linearly interpolates from this entry's BPM to the next entry's BPM
|
||||
//! over the beat range. The seconds calculation uses the exact integral:
|
||||
//! `Δt = (60 / slope) * ln(bpm_end / bpm_start)` where slope = (bpm_end - bpm_start) / span_beats.
|
||||
//!
|
||||
//! # Format
|
||||
//! `entries` is a sorted `Vec<TempoEntry>` where the first entry must always
|
||||
//! have `beat == 0.0`.
|
||||
//!
|
||||
//! # Sequential-access optimisation
|
||||
//! An `AtomicUsize` caches the index of the last segment visited by
|
||||
//! `beats_to_seconds`. When calls are in ascending order (the common case when
|
||||
//! walking events in order) the scan starts from the cached index instead of
|
||||
//! the beginning, giving amortised O(1) behaviour.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use crate::time::{Beats, Seconds};
|
||||
|
||||
/// How the BPM transitions from one `TempoEntry` to the next.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Default)]
|
||||
pub enum TempoInterpolation {
|
||||
/// BPM stays constant from this entry's beat until the next entry (instant change).
|
||||
#[default]
|
||||
Step,
|
||||
/// BPM linearly interpolates from this entry's BPM to the next entry's BPM
|
||||
/// over the beat span between the two entries.
|
||||
Linear,
|
||||
}
|
||||
|
||||
/// A single tempo segment: from `beat` onwards the tempo changes according to `interpolation`.
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct TempoEntry {
|
||||
/// Start of this tempo segment in beats (quarter-note beats).
|
||||
pub beat: f64,
|
||||
/// Tempo at the start of this segment in beats per minute.
|
||||
pub bpm: f64,
|
||||
/// Cumulative seconds elapsed at the start of this segment.
|
||||
/// **Derived** — not serialised; call [`TempoMap::rebuild_seconds`] after any
|
||||
/// mutation or after deserialization.
|
||||
#[serde(skip, default)]
|
||||
pub seconds: f64,
|
||||
/// How the BPM transitions from this entry to the next.
|
||||
#[serde(default)]
|
||||
pub interpolation: TempoInterpolation,
|
||||
}
|
||||
|
||||
/// A piecewise tempo map used to convert between beats and seconds.
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct TempoMap {
|
||||
/// Sorted list of tempo segments. Must always have at least one entry at beat 0.
|
||||
pub entries: Vec<TempoEntry>,
|
||||
/// Sequential-access cache: index of the last segment used by `beats_to_seconds`.
|
||||
#[serde(skip, default)]
|
||||
last_index: AtomicUsize,
|
||||
}
|
||||
|
||||
impl Clone for TempoMap {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
entries: self.entries.clone(),
|
||||
last_index: AtomicUsize::new(self.last_index.load(Ordering::Relaxed)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for TempoMap {
|
||||
fn default() -> Self {
|
||||
Self::constant(120.0)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Internal helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/// Seconds elapsed traversing `span_beats` starting at `bpm_start`.
|
||||
/// If `bpm_end` is `Some` (linear segment) and differs from `bpm_start`,
|
||||
/// uses the exact logarithmic integral.
|
||||
#[inline]
|
||||
fn segment_duration(span_beats: f64, bpm_start: f64, bpm_end: Option<f64>) -> f64 {
|
||||
match bpm_end {
|
||||
None => span_beats * 60.0 / bpm_start,
|
||||
Some(b1) if (b1 - bpm_start).abs() < 1e-9 => span_beats * 60.0 / bpm_start,
|
||||
Some(b1) => {
|
||||
// Linear BPM: BPM(b) = bpm_start + slope * (b - b_start)
|
||||
// Δt = ∫₀^span 60 / BPM(b) db = (60/slope) * ln(b1/bpm_start)
|
||||
let slope = (b1 - bpm_start) / span_beats;
|
||||
(60.0 / slope) * (b1 / bpm_start).ln()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Beats elapsed given `delta_seconds` starting at `bpm_start`.
|
||||
/// If `bpm_end` is `Some` (linear segment) and differs from `bpm_start`,
|
||||
/// uses the exact exponential inverse.
|
||||
#[inline]
|
||||
fn segment_beats(delta_seconds: f64, span_beats: f64, bpm_start: f64, bpm_end: Option<f64>) -> f64 {
|
||||
match bpm_end {
|
||||
None => delta_seconds * bpm_start / 60.0,
|
||||
Some(b1) if (b1 - bpm_start).abs() < 1e-9 => delta_seconds * bpm_start / 60.0,
|
||||
Some(b1) => {
|
||||
// Inverse of the logarithmic integral:
|
||||
// b = b_start + (bpm_start / slope) * (exp(delta_t * slope / 60) - 1)
|
||||
let slope = (b1 - bpm_start) / span_beats;
|
||||
(bpm_start / slope) * ((delta_seconds * slope / 60.0).exp() - 1.0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TempoMap {
|
||||
/// Create a constant-tempo map.
|
||||
pub fn constant(bpm: f64) -> Self {
|
||||
Self {
|
||||
entries: vec![TempoEntry { beat: 0.0, bpm, seconds: 0.0, interpolation: TempoInterpolation::Step }],
|
||||
last_index: AtomicUsize::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuild the `seconds` field on every entry from scratch.
|
||||
/// **Must be called** after any mutation (add/remove/reorder entry) and
|
||||
/// after deserialization.
|
||||
pub fn rebuild_seconds(&mut self) {
|
||||
let mut cumulative = 0.0_f64;
|
||||
let n = self.entries.len();
|
||||
for i in 0..n {
|
||||
self.entries[i].seconds = cumulative;
|
||||
if i + 1 < n {
|
||||
let span = self.entries[i + 1].beat - self.entries[i].beat;
|
||||
let bpm_end = if self.entries[i].interpolation == TempoInterpolation::Linear {
|
||||
Some(self.entries[i + 1].bpm)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
cumulative += segment_duration(span, self.entries[i].bpm, bpm_end);
|
||||
}
|
||||
}
|
||||
self.last_index.store(0, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Return the instantaneous BPM active at `beat`.
|
||||
/// For linear segments, returns the interpolated value at that beat.
|
||||
pub fn bpm_at(&self, beat: Beats) -> f64 {
|
||||
let n = self.entries.len();
|
||||
let idx = self.entries.partition_point(|e| e.beat <= beat.0).saturating_sub(1);
|
||||
let idx = idx.min(n - 1);
|
||||
let entry = &self.entries[idx];
|
||||
if entry.interpolation == TempoInterpolation::Linear && idx + 1 < n {
|
||||
let next = &self.entries[idx + 1];
|
||||
let t = (beat.0 - entry.beat) / (next.beat - entry.beat);
|
||||
entry.bpm + (next.bpm - entry.bpm) * t
|
||||
} else {
|
||||
entry.bpm
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert beats to seconds using the tempo map.
|
||||
///
|
||||
/// Uses the sequential cache: if `beat` is at or after the last cached
|
||||
/// segment, the scan starts there instead of from the beginning.
|
||||
pub fn beats_to_seconds(&self, beat: Beats) -> Seconds {
|
||||
Seconds(self.transform(beat.0))
|
||||
}
|
||||
|
||||
/// Convert seconds to beats using binary search on the cached `seconds` offsets.
|
||||
pub fn seconds_to_beats(&self, seconds: Seconds) -> Beats {
|
||||
Beats(self.inverse_transform(seconds.0))
|
||||
}
|
||||
|
||||
/// Global BPM — the BPM of the first entry (at beat 0).
|
||||
pub fn global_bpm(&self) -> f64 {
|
||||
self.entries[0].bpm
|
||||
}
|
||||
|
||||
/// Set the global BPM (first entry). Rebuilds seconds.
|
||||
pub fn set_global_bpm(&mut self, bpm: f64) {
|
||||
self.entries[0].bpm = bpm;
|
||||
self.rebuild_seconds();
|
||||
}
|
||||
|
||||
/// Convert local beats to parent time units (raw `f64`).
|
||||
///
|
||||
/// At the root level the result is absolute seconds. Inside a nested
|
||||
/// group the result is the *parent group's* beats.
|
||||
pub fn transform(&self, beat: f64) -> f64 {
|
||||
if beat <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let n = self.entries.len();
|
||||
let cached = self.last_index.load(Ordering::Relaxed).min(n.saturating_sub(1));
|
||||
let start = if beat >= self.entries[cached].beat { cached } else { 0 };
|
||||
let mut idx = start;
|
||||
while idx + 1 < n && self.entries[idx + 1].beat <= beat {
|
||||
idx += 1;
|
||||
}
|
||||
self.last_index.store(idx, Ordering::Relaxed);
|
||||
|
||||
let entry = &self.entries[idx];
|
||||
let beat_in_seg = beat - entry.beat;
|
||||
if entry.interpolation == TempoInterpolation::Linear && idx + 1 < n {
|
||||
let next = &self.entries[idx + 1];
|
||||
let span = next.beat - entry.beat;
|
||||
entry.seconds + segment_duration(beat_in_seg, entry.bpm, Some(entry.bpm + (next.bpm - entry.bpm) * beat_in_seg / span))
|
||||
} else {
|
||||
entry.seconds + beat_in_seg * 60.0 / entry.bpm
|
||||
}
|
||||
}
|
||||
|
||||
/// Inverse of [`transform`]: convert parent time units back to local beats.
|
||||
pub fn inverse_transform(&self, parent_time: f64) -> f64 {
|
||||
if parent_time <= 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let n = self.entries.len();
|
||||
let idx = self.entries.partition_point(|e| e.seconds <= parent_time).saturating_sub(1);
|
||||
let idx = idx.min(n - 1);
|
||||
let entry = &self.entries[idx];
|
||||
let delta_t = parent_time - entry.seconds;
|
||||
if entry.interpolation == TempoInterpolation::Linear && idx + 1 < n {
|
||||
let next = &self.entries[idx + 1];
|
||||
let span = next.beat - entry.beat;
|
||||
entry.beat + segment_beats(delta_t, span, entry.bpm, Some(next.bpm))
|
||||
} else {
|
||||
entry.beat + delta_t * entry.bpm / 60.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a `TempoMap` from a list of `(beat, bpm)` keyframes (step interpolation).
|
||||
/// Always inserts a beat-0 entry using the first keyframe's BPM (or 120.0 if empty).
|
||||
pub fn from_keyframes(keyframes: &[(f64, f64)]) -> Self {
|
||||
if keyframes.is_empty() {
|
||||
return Self::constant(120.0);
|
||||
}
|
||||
let mut entries: Vec<TempoEntry> = keyframes
|
||||
.iter()
|
||||
.map(|&(beat, bpm)| TempoEntry { beat, bpm, seconds: 0.0, interpolation: TempoInterpolation::Step })
|
||||
.collect();
|
||||
entries.sort_by(|a, b| a.beat.partial_cmp(&b.beat).unwrap());
|
||||
if entries[0].beat > 0.0 {
|
||||
entries.insert(0, TempoEntry { beat: 0.0, bpm: entries[0].bpm, seconds: 0.0, interpolation: TempoInterpolation::Step });
|
||||
}
|
||||
let mut map = Self { entries, last_index: AtomicUsize::new(0) };
|
||||
map.rebuild_seconds();
|
||||
map
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert local beats through a stack of tempo maps to absolute seconds.
|
||||
pub fn beats_to_seconds_stack(beat: f64, stack: &[&TempoMap]) -> f64 {
|
||||
let mut t = beat;
|
||||
for tm in stack.iter().rev() {
|
||||
t = tm.transform(t);
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
/// Inverse of [`beats_to_seconds_stack`]: absolute seconds → local beats.
|
||||
pub fn seconds_to_beats_stack(seconds: f64, stack: &[&TempoMap]) -> f64 {
|
||||
let mut t = seconds;
|
||||
for tm in stack.iter() {
|
||||
t = tm.inverse_transform(t);
|
||||
}
|
||||
t
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn constant_bpm_round_trip() {
|
||||
let m = TempoMap::constant(120.0);
|
||||
assert!((m.beats_to_seconds(Beats(2.0)).0 - 1.0).abs() < 1e-9);
|
||||
assert!((m.seconds_to_beats(Seconds(1.0)).0 - 2.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn variable_tempo_step() {
|
||||
let m = TempoMap::from_keyframes(&[(0.0, 120.0), (4.0, 60.0)]);
|
||||
// Beat 0-4: 120 BPM → 4 beats = 2 seconds
|
||||
assert!((m.beats_to_seconds(Beats(4.0)).0 - 2.0).abs() < 1e-9, "got {}", m.beats_to_seconds(Beats(4.0)).0);
|
||||
// Beat 4-5: 60 BPM → 1 beat = 1 second
|
||||
assert!((m.beats_to_seconds(Beats(5.0)).0 - 3.0).abs() < 1e-9);
|
||||
assert!((m.seconds_to_beats(Seconds(3.0)).0 - 5.0).abs() < 1e-9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linear_interpolation_round_trip() {
|
||||
// 120→240 BPM over 4 beats: slope = (240-120)/4 = 30 BPM/beat
|
||||
// Δt = (60/30) * ln(240/120) = 2 * ln(2) ≈ 1.386s for beats 0-4
|
||||
let mut m = TempoMap::constant(120.0);
|
||||
m.entries.push(TempoEntry { beat: 4.0, bpm: 240.0, seconds: 0.0, interpolation: TempoInterpolation::Step });
|
||||
m.entries[0].interpolation = TempoInterpolation::Linear;
|
||||
m.rebuild_seconds();
|
||||
|
||||
let expected = 2.0 * std::f64::consts::LN_2;
|
||||
let got = m.beats_to_seconds(Beats(4.0)).0;
|
||||
assert!((got - expected).abs() < 1e-9, "got {got}, expected {expected}");
|
||||
|
||||
// Round-trip
|
||||
let beats_back = m.seconds_to_beats(Seconds(expected)).0;
|
||||
assert!((beats_back - 4.0).abs() < 1e-9, "round-trip got {beats_back}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stack_composition() {
|
||||
let root = TempoMap::constant(120.0);
|
||||
let group = TempoMap::constant(60.0);
|
||||
let stack: Vec<&TempoMap> = vec![&root, &group];
|
||||
let secs = beats_to_seconds_stack(2.0, &stack);
|
||||
assert!((secs - 1.0).abs() < 1e-9, "got {secs}");
|
||||
let beats = seconds_to_beats_stack(1.0, &stack);
|
||||
assert!((beats - 2.0).abs() < 1e-9, "got {beats}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sequential_cache() {
|
||||
let m = TempoMap::constant(120.0);
|
||||
for i in 0..10 {
|
||||
let secs = m.beats_to_seconds(Beats(i as f64));
|
||||
assert!((secs.0 - i as f64 * 0.5).abs() < 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
/// Strongly-typed time units to prevent accidental beats/seconds confusion.
|
||||
///
|
||||
/// Convert between the two using `TempoMap::beats_to_seconds` / `TempoMap::seconds_to_beats`.
|
||||
/// All internal scheduling and clip positions use `Beats`; only audio rendering
|
||||
/// (sample offsets, file seeks) uses `Seconds`.
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::ops::{Add, AddAssign, Div, Mul, Neg, Rem, Sub, SubAssign};
|
||||
|
||||
/// A time position or duration expressed in **beats** (quarter-note beats).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct Beats(pub f64);
|
||||
|
||||
/// A time position or duration expressed in **seconds**.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct Seconds(pub f64);
|
||||
|
||||
impl Beats {
|
||||
pub const ZERO: Self = Self(0.0);
|
||||
|
||||
pub fn max(self, other: Self) -> Self { Self(self.0.max(other.0)) }
|
||||
pub fn min(self, other: Self) -> Self { Self(self.0.min(other.0)) }
|
||||
pub fn abs(self) -> Self { Self(self.0.abs()) }
|
||||
pub fn ceil(self) -> Self { Self(self.0.ceil()) }
|
||||
pub fn floor(self) -> Self { Self(self.0.floor()) }
|
||||
pub fn beats_to_f64(self) -> f64 { self.0 }
|
||||
}
|
||||
|
||||
impl Seconds {
|
||||
pub const ZERO: Self = Self(0.0);
|
||||
|
||||
pub fn max(self, other: Self) -> Self { Self(self.0.max(other.0)) }
|
||||
pub fn min(self, other: Self) -> Self { Self(self.0.min(other.0)) }
|
||||
pub fn abs(self) -> Self { Self(self.0.abs()) }
|
||||
pub fn seconds_to_f64(self) -> f64 { self.0 }
|
||||
}
|
||||
|
||||
// --- Beats arithmetic ---
|
||||
|
||||
impl Add for Beats {
|
||||
type Output = Self;
|
||||
fn add(self, rhs: Self) -> Self { Self(self.0 + rhs.0) }
|
||||
}
|
||||
impl Sub for Beats {
|
||||
type Output = Self;
|
||||
fn sub(self, rhs: Self) -> Self { Self(self.0 - rhs.0) }
|
||||
}
|
||||
impl Mul<f64> for Beats {
|
||||
type Output = Self;
|
||||
fn mul(self, rhs: f64) -> Self { Self(self.0 * rhs) }
|
||||
}
|
||||
impl Div<f64> for Beats {
|
||||
type Output = Self;
|
||||
fn div(self, rhs: f64) -> Self { Self(self.0 / rhs) }
|
||||
}
|
||||
/// Beats / Beats = dimensionless ratio (f64)
|
||||
impl Div<Beats> for Beats {
|
||||
type Output = f64;
|
||||
fn div(self, rhs: Beats) -> f64 { self.0 / rhs.0 }
|
||||
}
|
||||
impl Rem for Beats {
|
||||
type Output = Self;
|
||||
fn rem(self, rhs: Self) -> Self { Self(self.0 % rhs.0) }
|
||||
}
|
||||
impl Neg for Beats {
|
||||
type Output = Self;
|
||||
fn neg(self) -> Self { Self(-self.0) }
|
||||
}
|
||||
impl AddAssign for Beats {
|
||||
fn add_assign(&mut self, rhs: Self) { self.0 += rhs.0; }
|
||||
}
|
||||
impl SubAssign for Beats {
|
||||
fn sub_assign(&mut self, rhs: Self) { self.0 -= rhs.0; }
|
||||
}
|
||||
|
||||
// --- Seconds arithmetic ---
|
||||
|
||||
impl Add for Seconds {
|
||||
type Output = Self;
|
||||
fn add(self, rhs: Self) -> Self { Self(self.0 + rhs.0) }
|
||||
}
|
||||
impl Sub for Seconds {
|
||||
type Output = Self;
|
||||
fn sub(self, rhs: Self) -> Self { Self(self.0 - rhs.0) }
|
||||
}
|
||||
impl Mul<f64> for Seconds {
|
||||
type Output = Self;
|
||||
fn mul(self, rhs: f64) -> Self { Self(self.0 * rhs) }
|
||||
}
|
||||
impl Div<f64> for Seconds {
|
||||
type Output = Self;
|
||||
fn div(self, rhs: f64) -> Self { Self(self.0 / rhs) }
|
||||
}
|
||||
/// Seconds / Seconds = dimensionless ratio (f64)
|
||||
impl Div<Seconds> for Seconds {
|
||||
type Output = f64;
|
||||
fn div(self, rhs: Seconds) -> f64 { self.0 / rhs.0 }
|
||||
}
|
||||
impl Rem for Seconds {
|
||||
type Output = Self;
|
||||
fn rem(self, rhs: Self) -> Self { Self(self.0 % rhs.0) }
|
||||
}
|
||||
impl Neg for Seconds {
|
||||
type Output = Self;
|
||||
fn neg(self) -> Self { Self(-self.0) }
|
||||
}
|
||||
impl AddAssign for Seconds {
|
||||
fn add_assign(&mut self, rhs: Self) { self.0 += rhs.0; }
|
||||
}
|
||||
impl SubAssign for Seconds {
|
||||
fn sub_assign(&mut self, rhs: Self) { self.0 -= rhs.0; }
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Beats {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Seconds {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "{}", self.0)
|
||||
}
|
||||
}
|
||||
@@ -859,7 +859,7 @@ fn execute_command(
|
||||
|
||||
for event in &midi_clip.events {
|
||||
let status = event.status & 0xF0;
|
||||
let time_seconds = event.timestamp as f64 / sample_rate;
|
||||
let time_seconds = event.timestamp.beats_to_f64() / sample_rate;
|
||||
|
||||
match status {
|
||||
0x90 if event.data2 > 0 => {
|
||||
@@ -878,7 +878,7 @@ fn execute_command(
|
||||
}
|
||||
|
||||
// Add to local UI state with note data
|
||||
app.add_clip(track_id, clip_id, start_time, duration, file_path.to_string(), notes);
|
||||
app.add_clip(track_id, clip_id, start_time, duration.beats_to_f64(), file_path.to_string(), notes);
|
||||
app.next_clip_id += 1;
|
||||
|
||||
// Send to audio engine with the start_time (clip content is separate from timeline position)
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
//! Integration test for `CompressedReader::open_source` — decoding a streaming
|
||||
//! audio source from an in-memory byte stream (the packed-in-container path)
|
||||
//! rather than a filesystem path. Proves the `MediaByteSource` adapter feeds
|
||||
//! Symphonia correctly (probe + decode + seekable byte length).
|
||||
|
||||
use std::io::{Cursor, Read, Seek, SeekFrom};
|
||||
|
||||
use daw_backend::audio::disk_reader::{CompressedReader, MediaByteSource};
|
||||
|
||||
/// A `MediaByteSource` over an in-memory buffer (stands in for core's BlobReader).
|
||||
struct VecSource(Cursor<Vec<u8>>);
|
||||
|
||||
impl Read for VecSource {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
self.0.read(buf)
|
||||
}
|
||||
}
|
||||
impl Seek for VecSource {
|
||||
fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
|
||||
self.0.seek(pos)
|
||||
}
|
||||
}
|
||||
impl MediaByteSource for VecSource {
|
||||
fn byte_len(&self) -> u64 {
|
||||
self.0.get_ref().len() as u64
|
||||
}
|
||||
}
|
||||
|
||||
/// Build a minimal PCM16 mono WAV byte buffer holding `frames` samples of a ramp.
|
||||
fn make_wav(sample_rate: u32, frames: u32) -> Vec<u8> {
|
||||
let channels: u16 = 1;
|
||||
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 = frames * block_align 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());
|
||||
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 i in 0..frames {
|
||||
// A ramp from -16000..16000 so values are recognizable.
|
||||
let s = (((i % 1000) as i32 - 500) * 32) as i16;
|
||||
v.extend_from_slice(&s.to_le_bytes());
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_source_decodes_in_memory_wav() {
|
||||
let sample_rate = 8000;
|
||||
let frames = 4096;
|
||||
let bytes = make_wav(sample_rate, frames);
|
||||
|
||||
let src = Box::new(VecSource(Cursor::new(bytes)));
|
||||
let mut reader = CompressedReader::open_source(src, Some("wav"))
|
||||
.expect("open_source should probe the in-memory WAV");
|
||||
|
||||
assert_eq!(reader.sample_rate(), sample_rate);
|
||||
assert_eq!(reader.channels(), 1);
|
||||
|
||||
// Decode the whole stream and count emitted frames.
|
||||
let mut buf = Vec::new();
|
||||
let mut decoded = 0usize;
|
||||
loop {
|
||||
let n = reader.decode_next(&mut buf).expect("decode_next");
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
decoded += n;
|
||||
}
|
||||
// Should recover (approximately) all frames — codec frame counts can round.
|
||||
assert!(
|
||||
(decoded as i64 - frames as i64).abs() < 64,
|
||||
"decoded {} vs expected {}",
|
||||
decoded,
|
||||
frames
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
//! Integration tests for `VideoAudioReader` (FFmpeg streaming audio source).
|
||||
//!
|
||||
//! These build the daw-backend lib in normal mode, so they're independent of
|
||||
//! the crate's pre-existing broken `#[cfg(test)]` unit tests (automation.rs).
|
||||
//! They synthesize a mono 32-bit-float WAV whose sample `i` has value `i/n`, so
|
||||
//! a decoded sample's value identifies its frame index — letting us assert both
|
||||
//! in-order decoding and **sample-accurate seeking** (the property video audio
|
||||
//! needs to stay synced with other clips).
|
||||
|
||||
use daw_backend::audio::disk_reader::{
|
||||
build_waveform_pyramid, CompressedReader, SourceKind, VideoAudioReader,
|
||||
};
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
|
||||
fn write_ramp_wav(path: &Path, n: u32, sample_rate: u32) {
|
||||
let channels = 1u16;
|
||||
let bytes_per_sample = 4u32;
|
||||
let data_size = n * bytes_per_sample;
|
||||
let mut buf: Vec<u8> = 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 * bytes_per_sample).to_le_bytes());
|
||||
buf.extend_from_slice(&((channels as u32 * bytes_per_sample) 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());
|
||||
}
|
||||
let mut f = std::fs::File::create(path).unwrap();
|
||||
f.write_all(&buf).unwrap();
|
||||
}
|
||||
|
||||
/// Stereo ramp: frame `i` has left = `i/n`, right = `0.5 - i/n` (distinct per
|
||||
/// channel), interleaved `[L0,R0,L1,R1,…]`. Exercises the channels>1 path.
|
||||
fn write_stereo_ramp_wav(path: &Path, n: u32, sample_rate: u32) {
|
||||
let channels = 2u16;
|
||||
let bytes_per_sample = 4u32;
|
||||
let data_size = n * channels as u32 * bytes_per_sample;
|
||||
let mut buf: Vec<u8> = 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 * bytes_per_sample).to_le_bytes());
|
||||
buf.extend_from_slice(&((channels as u32 * bytes_per_sample) 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 {
|
||||
let l = i as f32 / n as f32;
|
||||
let r = 0.5 - i as f32 / n as f32;
|
||||
buf.extend_from_slice(&l.to_le_bytes());
|
||||
buf.extend_from_slice(&r.to_le_bytes());
|
||||
}
|
||||
let mut f = std::fs::File::create(path).unwrap();
|
||||
f.write_all(&buf).unwrap();
|
||||
}
|
||||
|
||||
fn temp_path(tag: &str) -> std::path::PathBuf {
|
||||
let mut p = std::env::temp_dir();
|
||||
p.push(format!("lb_videoaudio_test_{}_{}.wav", std::process::id(), tag));
|
||||
p
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_samples_in_order() {
|
||||
let n = 4000u32;
|
||||
let sr = 8000u32;
|
||||
let path = temp_path("seq");
|
||||
write_ramp_wav(&path, n, sr);
|
||||
|
||||
let mut reader = VideoAudioReader::open(&path).unwrap();
|
||||
assert_eq!(reader.channels(), 1);
|
||||
assert_eq!(reader.sample_rate(), sr);
|
||||
// Probe estimate (used by add_video_audio_sync) should be ~n frames.
|
||||
let tf = reader.total_frames() as f64;
|
||||
assert!(
|
||||
(tf - n as f64).abs() < n as f64 * 0.1,
|
||||
"total_frames {} not ~{}",
|
||||
tf, n
|
||||
);
|
||||
|
||||
let mut all = Vec::new();
|
||||
let mut buf = Vec::new();
|
||||
loop {
|
||||
let frames = reader.decode_next(&mut buf).unwrap();
|
||||
if frames == 0 {
|
||||
break;
|
||||
}
|
||||
all.extend_from_slice(&buf);
|
||||
}
|
||||
|
||||
// Allow a couple of priming/flush samples of slack at the very end.
|
||||
assert!(all.len() + 4 >= n as usize, "decoded too few samples: {}", all.len());
|
||||
for (i, &v) in all.iter().enumerate().take(n as usize) {
|
||||
let expected = i as f32 / n as f32;
|
||||
assert!((v - expected).abs() < 1e-3, "sample {} = {}, expected {}", i, v, expected);
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
/// CompressedReader (symphonia) must seek **sample-accurately** too, so compressed
|
||||
/// audio stays frame-synced with video audio. Symphonia decodes WAV via the same
|
||||
/// path; its coarse seek lands on packet boundaries, exercising the decode-discard.
|
||||
#[test]
|
||||
fn compressed_reader_seek_is_sample_accurate() {
|
||||
let n = 4000u32;
|
||||
let sr = 8000u32;
|
||||
let path = temp_path("comp_seek");
|
||||
write_ramp_wav(&path, n, sr);
|
||||
|
||||
let mut reader = CompressedReader::open(&path).unwrap();
|
||||
assert_eq!(reader.channels(), 1);
|
||||
assert_eq!(reader.sample_rate(), sr);
|
||||
|
||||
for &target in &[2000u64, 137, 3500, 0] {
|
||||
let actual = reader.seek(target).unwrap();
|
||||
assert_eq!(actual, target, "seek should report the exact target");
|
||||
|
||||
let mut buf = Vec::new();
|
||||
let mut frames = 0;
|
||||
for _ in 0..128 {
|
||||
frames = reader.decode_next(&mut buf).unwrap();
|
||||
if frames > 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(frames > 0, "no samples after seek to {}", target);
|
||||
let expected = target as f32 / n as f32;
|
||||
assert!(
|
||||
(buf[0] - expected).abs() < 1e-3,
|
||||
"compressed seek to {}: first sample = {}, expected {}",
|
||||
target, buf[0], expected
|
||||
);
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
/// The decode→pyramid bridge should produce an envelope matching the signal,
|
||||
/// through both reader backends (symphonia + ffmpeg), with bounded memory.
|
||||
#[test]
|
||||
fn waveform_pyramid_from_decode_matches_signal() {
|
||||
let n = 5000u32;
|
||||
let sr = 8000u32;
|
||||
let path = temp_path("pyr");
|
||||
write_ramp_wav(&path, n, sr); // ramp 0 .. (n-1)/n, all positive
|
||||
|
||||
for kind in [SourceKind::CompressedAudio, SourceKind::VideoAudio] {
|
||||
let p = build_waveform_pyramid(&path, kind, 256).unwrap();
|
||||
assert_eq!(p.channels, 1);
|
||||
assert_eq!(p.root().len(), 1, "{:?}: root should be one texel", kind);
|
||||
let root = p.root()[0];
|
||||
assert!(root.l_min.abs() < 1e-2, "{:?}: root min {} ~ 0", kind, root.l_min);
|
||||
let expected_max = (n - 1) as f32 / n as f32;
|
||||
assert!(
|
||||
(root.l_max - expected_max).abs() < 1e-2,
|
||||
"{:?}: root max {} ~ {}", kind, root.l_max, expected_max
|
||||
);
|
||||
// Frame count is approximate across decoders (priming/resampler overhead);
|
||||
// the envelope above is the real check. Just confirm it's about right.
|
||||
assert!((p.total_frames as i64 - n as i64).abs() < 128, "{:?}: frames {}", kind, p.total_frames);
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_stereo_interleaved() {
|
||||
let n = 2000u32;
|
||||
let sr = 8000u32;
|
||||
let path = temp_path("stereo");
|
||||
write_stereo_ramp_wav(&path, n, sr);
|
||||
|
||||
let mut reader = VideoAudioReader::open(&path).unwrap();
|
||||
assert_eq!(reader.channels(), 2);
|
||||
|
||||
let mut all = Vec::new();
|
||||
let mut buf = Vec::new();
|
||||
loop {
|
||||
let frames = reader.decode_next(&mut buf).unwrap();
|
||||
if frames == 0 {
|
||||
break;
|
||||
}
|
||||
// Each decode_next returns whole interleaved frames.
|
||||
assert_eq!(buf.len() % 2, 0, "stereo decode returned a partial frame");
|
||||
all.extend_from_slice(&buf);
|
||||
}
|
||||
|
||||
// Interleaved L/R, ~n frames.
|
||||
assert!(all.len() + 8 >= (n * 2) as usize, "decoded too few samples: {}", all.len());
|
||||
for i in 0..n as usize {
|
||||
let l = all[2 * i];
|
||||
let r = all[2 * i + 1];
|
||||
assert!((l - i as f32 / n as f32).abs() < 1e-3, "L[{}]={} expected {}", i, l, i as f32 / n as f32);
|
||||
assert!(
|
||||
(r - (0.5 - i as f32 / n as f32)).abs() < 1e-3,
|
||||
"R[{}]={} expected {}", i, r, 0.5 - i as f32 / n as f32
|
||||
);
|
||||
}
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seek_is_sample_accurate() {
|
||||
let n = 4000u32;
|
||||
let sr = 8000u32;
|
||||
let path = temp_path("seek");
|
||||
write_ramp_wav(&path, n, sr);
|
||||
|
||||
let mut reader = VideoAudioReader::open(&path).unwrap();
|
||||
|
||||
for &target in &[2000u64, 137, 3500, 0] {
|
||||
let actual = reader.seek(target).unwrap();
|
||||
assert_eq!(actual, target);
|
||||
|
||||
// Pull the first non-empty decode after the seek.
|
||||
let mut buf = Vec::new();
|
||||
let mut frames = 0;
|
||||
for _ in 0..64 {
|
||||
frames = reader.decode_next(&mut buf).unwrap();
|
||||
if frames > 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
assert!(frames > 0, "no samples after seek to {}", target);
|
||||
|
||||
let expected = target as f32 / n as f32;
|
||||
assert!(
|
||||
(buf[0] - expected).abs() < 1e-3,
|
||||
"after seek to {}: first sample = {}, expected {}",
|
||||
target,
|
||||
buf[0],
|
||||
expected
|
||||
);
|
||||
// And the next few advance in order.
|
||||
for k in 0..frames.min(8) {
|
||||
let exp = (target as usize + k) as f32 / n as f32;
|
||||
assert!((buf[k] - exp).abs() < 1e-3, "seek {}+{}: {} vs {}", target, k, buf[k], exp);
|
||||
}
|
||||
}
|
||||
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());
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
//! Integration tests for the streaming waveform LOD pyramid builder.
|
||||
//!
|
||||
//! Convention B: `levels[0]` is the root (coarsest), `levels.last()` the floor
|
||||
//! (finest). Tests use the `.root()` / `.floor()` accessors so they don't depend
|
||||
//! on the raw index ordering.
|
||||
|
||||
use daw_backend::audio::waveform_pyramid::{Texel, WaveformPyramid, WaveformPyramidBuilder};
|
||||
|
||||
fn build_mono(samples: &[f32], floor: u32) -> WaveformPyramid {
|
||||
let mut b = WaveformPyramidBuilder::new(1, floor);
|
||||
b.push_interleaved(samples);
|
||||
b.finish()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn floor_level_min_max_per_bucket() {
|
||||
// 8 samples, floor 4 → two floor texels covering [0..4) and [4..8).
|
||||
let s: Vec<f32> = (0..8).map(|i| i as f32).collect();
|
||||
let p = build_mono(&s, 4);
|
||||
assert_eq!(p.floor().len(), 2);
|
||||
assert_eq!(p.floor()[0], Texel { l_min: 0.0, l_max: 3.0, r_min: 0.0, r_max: 3.0 });
|
||||
assert_eq!(p.floor()[1], Texel { l_min: 4.0, l_max: 7.0, r_min: 4.0, r_max: 7.0 });
|
||||
// Root reduces the two floor texels into the envelope [0..8).
|
||||
assert_eq!(p.root().len(), 1);
|
||||
assert_eq!(p.root()[0], Texel { l_min: 0.0, l_max: 7.0, r_min: 0.0, r_max: 7.0 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_trailing_bucket_is_flushed() {
|
||||
// 6 samples, floor 4 → texels [0..4) and a ragged [4..6).
|
||||
let s: Vec<f32> = (0..6).map(|i| i as f32).collect();
|
||||
let p = build_mono(&s, 4);
|
||||
assert_eq!(p.floor().len(), 2);
|
||||
assert_eq!(p.floor()[1], Texel { l_min: 4.0, l_max: 5.0, r_min: 4.0, r_max: 5.0 });
|
||||
assert_eq!(p.total_frames, 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multi_level_envelope_matches_global_min_max() {
|
||||
let s: Vec<f32> = (0..1000).map(|i| ((i as f32) * 0.01).sin()).collect();
|
||||
let g_min = s.iter().cloned().fold(f32::INFINITY, f32::min);
|
||||
let g_max = s.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
|
||||
let p = build_mono(&s, 16);
|
||||
assert_eq!(p.root().len(), 1);
|
||||
assert!((p.root()[0].l_min - g_min).abs() < 1e-6);
|
||||
assert!((p.root()[0].l_max - g_max).abs() < 1e-6);
|
||||
// Every level's overall min/max equals the global (extremes are lossless).
|
||||
for level in &p.levels {
|
||||
let lmin = level.iter().map(|t| t.l_min).fold(f32::INFINITY, f32::min);
|
||||
let lmax = level.iter().map(|t| t.l_max).fold(f32::NEG_INFINITY, f32::max);
|
||||
assert!((lmin - g_min).abs() < 1e-6);
|
||||
assert!((lmax - g_max).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn levels_are_root_first_and_get_finer() {
|
||||
let s: Vec<f32> = (0..1000).map(|i| i as f32).collect();
|
||||
let p = build_mono(&s, 16);
|
||||
// Root first, floor last; strictly finer (more texels) as depth increases.
|
||||
assert_eq!(p.root().len(), 1);
|
||||
assert!(p.depth() >= 3);
|
||||
for w in p.levels.windows(2) {
|
||||
assert!(w[1].len() >= w[0].len(), "deeper level should be finer");
|
||||
}
|
||||
// Floor has ceil(1000/16) = 63 texels.
|
||||
assert_eq!(p.floor().len(), 63);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stereo_channels_tracked_separately() {
|
||||
// L ramps up, R ramps down; interleaved.
|
||||
let n = 64;
|
||||
let mut s = Vec::new();
|
||||
for i in 0..n {
|
||||
s.push(i as f32); // L
|
||||
s.push(-(i as f32)); // R
|
||||
}
|
||||
let mut b = WaveformPyramidBuilder::new(2, 16);
|
||||
b.push_interleaved(&s);
|
||||
let p = b.finish();
|
||||
assert_eq!(p.root().len(), 1);
|
||||
assert_eq!(p.root()[0].l_min, 0.0);
|
||||
assert_eq!(p.root()[0].l_max, (n - 1) as f32);
|
||||
assert_eq!(p.root()[0].r_min, -((n - 1) as f32));
|
||||
assert_eq!(p.root()[0].r_max, 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pyramid_size_is_bounded() {
|
||||
let n = 100_000usize;
|
||||
let s: Vec<f32> = (0..n).map(|i| (i % 7) as f32).collect();
|
||||
let floor = 256u32;
|
||||
let p = build_mono(&s, floor);
|
||||
let total: usize = p.levels.iter().map(|l| l.len()).sum();
|
||||
let floor_texels = (n as u32).div_ceil(floor) as usize;
|
||||
// Geometric bound: < floor_texels * branch/(branch-1) + small per-level slack.
|
||||
let bound = floor_texels * 4 / 3 + p.depth() + 2;
|
||||
assert!(total <= bound, "pyramid too big: {} > {}", total, bound);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bytes_round_trip() {
|
||||
let s: Vec<f32> = (0..3333).map(|i| ((i as f32) * 0.013).sin()).collect();
|
||||
let p = build_mono(&s, 64);
|
||||
let bytes = p.to_bytes();
|
||||
let q = WaveformPyramid::from_bytes(&bytes).unwrap();
|
||||
assert_eq!(p.floor_samples_per_texel, q.floor_samples_per_texel);
|
||||
assert_eq!(p.branch, q.branch);
|
||||
assert_eq!(p.channels, q.channels);
|
||||
assert_eq!(p.total_frames, q.total_frames);
|
||||
assert_eq!(p.levels, q.levels);
|
||||
// Truncated/garbage input is rejected, not panicking.
|
||||
assert!(WaveformPyramid::from_bytes(&bytes[..bytes.len() - 4]).is_err());
|
||||
assert!(WaveformPyramid::from_bytes(b"nope").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pushing_in_arbitrary_chunks_matches() {
|
||||
// The streaming builder must be agnostic to how samples are chunked.
|
||||
let s: Vec<f32> = (0..5000).map(|i| ((i * 13) % 97) as f32 - 48.0).collect();
|
||||
let whole = build_mono(&s, 32);
|
||||
|
||||
let mut b = WaveformPyramidBuilder::new(1, 32);
|
||||
b.reserve_for_frames(5000);
|
||||
for chunk in s.chunks(37) {
|
||||
b.push_interleaved(chunk);
|
||||
}
|
||||
let chunked = b.finish();
|
||||
|
||||
assert_eq!(whole.depth(), chunked.depth());
|
||||
for (a, c) in whole.levels.iter().zip(chunked.levels.iter()) {
|
||||
assert_eq!(a, c);
|
||||
}
|
||||
}
|
||||
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
+487
-146
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
|
||||
@@ -36,6 +41,9 @@ zip = "0.6"
|
||||
chrono = "0.4"
|
||||
base64 = "0.21"
|
||||
pathdiff = "0.2"
|
||||
# .beam container: SQLite database file. `bundled` compiles SQLite from source
|
||||
# (no system dependency); `blob` enables incremental blob I/O for streaming.
|
||||
rusqlite = { version = "0.31", features = ["bundled", "blob"] }
|
||||
|
||||
# Audio encoding for embedded files
|
||||
flacenc = "0.4" # For FLAC encoding (lossless)
|
||||
@@ -70,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).
|
||||
@@ -71,6 +71,15 @@ pub trait Action: Send {
|
||||
/// Get a human-readable description of this action (for UI display)
|
||||
fn description(&self) -> String;
|
||||
|
||||
/// For raster actions that store dirty-rect diffs: the `(layer_id, time)` of the
|
||||
/// keyframe whose full pixels must be resident before `execute`/`rollback` can
|
||||
/// apply the diff. The editor faults the frame in (synchronously) before undo/redo
|
||||
/// so a paged-out clean frame is restored to its container state first. Non-raster
|
||||
/// actions (and full-buffer ones) return `None`.
|
||||
fn raster_resident_hint(&self) -> Option<(Uuid, f64)> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Execute backend operations after document changes
|
||||
///
|
||||
/// Called AFTER execute() succeeds. If this returns an error, execute()
|
||||
@@ -120,6 +129,17 @@ pub trait Action: Send {
|
||||
fn midi_events_after_rollback(&self) -> Option<(u32, &[daw_backend::audio::midi::MidiEvent])> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Return MIDI event data for multiple clips after execute/redo (e.g. BPM change).
|
||||
/// Each element is (midi_clip_id, events). Default: empty.
|
||||
fn all_midi_events_after_execute(&self) -> Vec<(u32, Vec<daw_backend::audio::midi::MidiEvent>)> {
|
||||
Vec::new()
|
||||
}
|
||||
|
||||
/// Return MIDI event data for multiple clips after rollback/undo.
|
||||
fn all_midi_events_after_rollback(&self) -> Vec<(u32, Vec<daw_backend::audio::midi::MidiEvent>)> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
|
||||
/// Action executor that wraps the document and manages undo/redo
|
||||
@@ -279,6 +299,18 @@ impl ActionExecutor {
|
||||
self.undo_stack.last().map(|a| a.description())
|
||||
}
|
||||
|
||||
/// `(layer_id, time)` of the raster keyframe the next undo needs resident, if any.
|
||||
/// The editor faults it in before calling `undo()` so a paged-out clean frame is
|
||||
/// restored to its container state, giving the diff a correct base to apply onto.
|
||||
pub fn peek_undo_raster_hint(&self) -> Option<(Uuid, f64)> {
|
||||
self.undo_stack.last().and_then(|a| a.raster_resident_hint())
|
||||
}
|
||||
|
||||
/// `(layer_id, time)` of the raster keyframe the next redo needs resident, if any.
|
||||
pub fn peek_redo_raster_hint(&self) -> Option<(Uuid, f64)> {
|
||||
self.redo_stack.last().and_then(|a| a.raster_resident_hint())
|
||||
}
|
||||
|
||||
/// Get MIDI cache data from the last action on the undo stack (after redo).
|
||||
/// Returns the notes reflecting execute state.
|
||||
pub fn last_undo_midi_notes(&self) -> Option<(u32, &[(f64, u8, u8, f64)])> {
|
||||
@@ -301,6 +333,16 @@ impl ActionExecutor {
|
||||
self.redo_stack.last().and_then(|a| a.midi_events_after_rollback())
|
||||
}
|
||||
|
||||
/// Get multi-clip MIDI event data from the last undo stack action (after redo).
|
||||
pub fn last_undo_all_midi_events(&self) -> Vec<(u32, Vec<daw_backend::audio::midi::MidiEvent>)> {
|
||||
self.undo_stack.last().map(|a| a.all_midi_events_after_execute()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Get multi-clip MIDI event data from the last redo stack action (after undo).
|
||||
pub fn last_redo_all_midi_events(&self) -> Vec<(u32, Vec<daw_backend::audio::midi::MidiEvent>)> {
|
||||
self.redo_stack.last().map(|a| a.all_midi_events_after_rollback()).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Get the description of the next action to redo
|
||||
pub fn redo_description(&self) -> Option<String> {
|
||||
self.redo_stack.last().map(|a| a.description())
|
||||
|
||||
@@ -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;
|
||||
@@ -208,10 +208,10 @@ impl Action for AddClipInstanceAction {
|
||||
let instance = daw_backend::MidiClipInstance::new(
|
||||
0, // Instance ID will be assigned by backend
|
||||
*midi_clip_id,
|
||||
internal_start,
|
||||
internal_end,
|
||||
external_start,
|
||||
external_duration,
|
||||
daw_backend::Beats(internal_start),
|
||||
daw_backend::Beats(internal_end),
|
||||
daw_backend::Beats(external_start),
|
||||
daw_backend::Beats(external_duration),
|
||||
);
|
||||
|
||||
// Send query to add instance and get instance ID
|
||||
@@ -235,11 +235,22 @@ impl Action for AddClipInstanceAction {
|
||||
}
|
||||
}
|
||||
AudioClipType::Sampled { audio_pool_index } => {
|
||||
// `trim_*` / `clip.duration` are in SECONDS (audio content time),
|
||||
// while `timeline_*` and the backend's `duration` are in BEATS.
|
||||
let internal_start = self.clip_instance.trim_start;
|
||||
let internal_end = self.clip_instance.trim_end.unwrap_or(clip.duration);
|
||||
let effective_duration = self.clip_instance.timeline_duration
|
||||
.unwrap_or(internal_end - internal_start);
|
||||
let start_time = self.clip_instance.timeline_start;
|
||||
// `effective_duration` is in BEATS. When `timeline_duration` is set
|
||||
// it already is; otherwise the clip occupies its natural content
|
||||
// length, so convert that seconds-span to beats at the clip's start
|
||||
// (NOT `internal_end - internal_start`, which is seconds — that was
|
||||
// the seconds-as-beats bug that made clips stop early off 60 BPM).
|
||||
let effective_duration = self.clip_instance.timeline_duration.unwrap_or_else(|| {
|
||||
let tempo_map = document.tempo_map();
|
||||
let content_secs = internal_end - internal_start;
|
||||
tempo_map.inverse_transform(tempo_map.transform(start_time) + content_secs)
|
||||
- start_time
|
||||
});
|
||||
|
||||
let instance_id = controller.add_audio_clip(
|
||||
*backend_track_id,
|
||||
@@ -305,8 +316,11 @@ mod tests {
|
||||
let layer_id = layer.layer.id;
|
||||
document.root_mut().add_child(AnyLayer::Vector(layer));
|
||||
|
||||
// Create a clip instance (using a fake clip_id since we're just testing the action)
|
||||
// Register a vector clip so get_clip_duration succeeds
|
||||
let clip_id = Uuid::new_v4();
|
||||
let clip = crate::clip::VectorClip::with_id(clip_id, "Test Clip", 100.0, 100.0, 5.0);
|
||||
document.vector_clips.insert(clip_id, clip);
|
||||
|
||||
let clip_instance = ClipInstance::new(clip_id);
|
||||
let instance_id = clip_instance.id;
|
||||
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
//! Add a blank raster keyframe at the playhead (the explicit "New Keyframe" command
|
||||
//! for raster layers — mirrors `SetKeyframeAction` for vector, but inserts an empty
|
||||
//! cel rather than copying the current graph).
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct AddRasterKeyframeAction {
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
width: u32,
|
||||
height: u32,
|
||||
/// Id of the keyframe created by the last `execute` (so `rollback` can remove
|
||||
/// exactly that one). `None` if a keyframe already existed at `time` (no-op).
|
||||
created_id: Option<Uuid>,
|
||||
}
|
||||
|
||||
impl AddRasterKeyframeAction {
|
||||
pub fn new(layer_id: Uuid, time: f64, width: u32, height: u32) -> Self {
|
||||
Self { layer_id, time, width, height, created_id: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for AddRasterKeyframeAction {
|
||||
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 rl = match layer {
|
||||
AnyLayer::Raster(rl) => rl,
|
||||
_ => return Err("Not a raster layer".to_string()),
|
||||
};
|
||||
// Inserts a blank cel only if one doesn't already exist at this time.
|
||||
self.created_id = rl.insert_blank_keyframe_at(self.time, self.width, self.height);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
if let Some(id) = self.created_id.take() {
|
||||
if let Some(AnyLayer::Raster(rl)) = document.get_layer_mut(&self.layer_id) {
|
||||
rl.remove_keyframe(id);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
"New keyframe".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,77 @@
|
||||
//! Change BPM / Tempo action
|
||||
//!
|
||||
//! Atomically swaps the document `TempoMap`, sending the new map to the engine.
|
||||
//! All clip and note positions are stored in **beats** so no position rescaling
|
||||
//! is required — only the TempoMap entry changes.
|
||||
|
||||
use crate::action::{Action, BackendContext};
|
||||
use crate::document::Document;
|
||||
use crate::tempo_map::TempoMap;
|
||||
|
||||
/// Action that changes the global BPM by replacing the tempo map.
|
||||
#[derive(Clone)]
|
||||
pub struct ChangeBpmAction {
|
||||
old_map: TempoMap,
|
||||
new_map: TempoMap,
|
||||
}
|
||||
|
||||
impl ChangeBpmAction {
|
||||
/// Build the action from the current document state and a desired new BPM.
|
||||
pub fn new(new_bpm: f64, document: &Document) -> Self {
|
||||
let old_map = document.tempo_map().clone();
|
||||
let mut new_map = old_map.clone();
|
||||
new_map.set_global_bpm(new_bpm);
|
||||
Self { old_map, new_map }
|
||||
}
|
||||
|
||||
/// Build from explicit old/new maps (used when the map already changed in-place,
|
||||
/// e.g., after live drag preview; the caller provides start and end states).
|
||||
pub fn from_maps(old_map: TempoMap, new_map: TempoMap) -> Self {
|
||||
Self { old_map, new_map }
|
||||
}
|
||||
|
||||
pub fn new_bpm(&self) -> f64 { self.new_map.global_bpm() }
|
||||
pub fn old_bpm(&self) -> f64 { self.old_map.global_bpm() }
|
||||
}
|
||||
|
||||
impl Action for ChangeBpmAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
*document.tempo_map_mut() = self.new_map.clone();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
*document.tempo_map_mut() = self.old_map.clone();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
"Change BPM".to_string()
|
||||
}
|
||||
|
||||
fn execute_backend(
|
||||
&mut self,
|
||||
backend: &mut BackendContext,
|
||||
_document: &Document,
|
||||
) -> Result<(), String> {
|
||||
let controller = match backend.audio_controller.as_mut() {
|
||||
Some(c) => c,
|
||||
None => return Ok(()),
|
||||
};
|
||||
controller.set_tempo_map(self.new_map.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback_backend(
|
||||
&mut self,
|
||||
backend: &mut BackendContext,
|
||||
_document: &Document,
|
||||
) -> Result<(), String> {
|
||||
let controller = match backend.audio_controller.as_mut() {
|
||||
Some(c) => c,
|
||||
None => return Ok(()),
|
||||
};
|
||||
controller.set_tempo_map(self.old_map.clone());
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
//! Change FPS action
|
||||
//!
|
||||
//! Atomically changes the document framerate.
|
||||
//! All clip positions are stored in **beats** so no position rescaling is
|
||||
//! required — only the framerate field changes.
|
||||
|
||||
use crate::action::{Action, BackendContext};
|
||||
use crate::document::Document;
|
||||
|
||||
/// Action that changes the document framerate.
|
||||
pub struct ChangeFpsAction {
|
||||
old_fps: f64,
|
||||
new_fps: f64,
|
||||
}
|
||||
|
||||
impl ChangeFpsAction {
|
||||
/// Build the action from old and new framerates.
|
||||
pub fn new(old_fps: f64, new_fps: f64, _document: &Document) -> Self {
|
||||
Self { old_fps, new_fps }
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for ChangeFpsAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
document.framerate = self.new_fps;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
document.framerate = self.old_fps;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
"Change FPS".to_string()
|
||||
}
|
||||
|
||||
fn execute_backend(
|
||||
&mut self,
|
||||
_backend: &mut BackendContext,
|
||||
_document: &Document,
|
||||
) -> Result<(), String> {
|
||||
// FPS does not affect audio scheduling — nothing to do in the backend.
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback_backend(
|
||||
&mut self,
|
||||
_backend: &mut BackendContext,
|
||||
_document: &Document,
|
||||
) -> Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -37,6 +37,9 @@ pub struct DeleteFolderAction {
|
||||
|
||||
/// Asset IDs that were deleted (for DeleteRecursive strategy)
|
||||
deleted_asset_ids: Vec<Uuid>,
|
||||
|
||||
/// Subfolder IDs that were reparented to the deleted folder's parent (for MoveToParent strategy)
|
||||
moved_subfolder_ids: Vec<Uuid>,
|
||||
}
|
||||
|
||||
impl DeleteFolderAction {
|
||||
@@ -55,6 +58,7 @@ impl DeleteFolderAction {
|
||||
removed_folders: Vec::new(),
|
||||
moved_asset_ids: Vec::new(),
|
||||
deleted_asset_ids: Vec::new(),
|
||||
moved_subfolder_ids: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,6 +134,7 @@ impl Action for DeleteFolderAction {
|
||||
for subfolder_id in subfolder_ids {
|
||||
if let Some(subfolder) = tree.folders.get_mut(&subfolder_id) {
|
||||
subfolder.parent_id = parent_id;
|
||||
self.moved_subfolder_ids.push(subfolder_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -259,6 +264,13 @@ impl Action for DeleteFolderAction {
|
||||
tree.add_folder(folder.clone());
|
||||
}
|
||||
|
||||
// Restore reparented subfolders back under the deleted folder
|
||||
for subfolder_id in &self.moved_subfolder_ids {
|
||||
if let Some(subfolder) = tree.folders.get_mut(subfolder_id) {
|
||||
subfolder.parent_id = Some(self.folder_id);
|
||||
}
|
||||
}
|
||||
|
||||
match self.strategy {
|
||||
DeleteStrategy::MoveToParent => {
|
||||
// Restore folder_id for moved assets
|
||||
@@ -312,6 +324,7 @@ impl Action for DeleteFolderAction {
|
||||
self.removed_folders.clear();
|
||||
self.moved_asset_ids.clear();
|
||||
self.deleted_asset_ids.clear();
|
||||
self.moved_subfolder_ids.clear();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -4,11 +4,14 @@
|
||||
//! through the action system.
|
||||
|
||||
pub mod add_clip_instance;
|
||||
pub mod change_bpm;
|
||||
pub mod change_fps;
|
||||
pub mod add_effect;
|
||||
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;
|
||||
@@ -27,15 +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;
|
||||
@@ -43,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;
|
||||
@@ -61,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;
|
||||
@@ -68,5 +82,13 @@ pub use toggle_group_expansion::ToggleGroupExpansionAction;
|
||||
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
|
||||
|
||||
@@ -0,0 +1,242 @@
|
||||
//! Dirty-rect diff for raster undo/redo.
|
||||
//!
|
||||
//! Brush strokes and fills used to store the *entire* before/after RGBA frame in the
|
||||
//! undo stack (~8 MB each at 1080p → up to ~1.6 GB at the 100-action cap). A
|
||||
//! [`RasterDiff`] instead stores only the changed bounding box's pixels before and
|
||||
//! after, which for a typical brush dab is a few tens of KB.
|
||||
//!
|
||||
//! Applying a diff overwrites just the bbox of the keyframe's `raw_pixels`, so the
|
||||
//! buffer **must be resident** (full length `w*h*4`) when `apply_*` runs. The editor
|
||||
//! guarantees this by faulting the target frame in before undo/redo (a clean evicted
|
||||
//! frame's container bytes equal its current logical state, so the restored base is
|
||||
//! 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]> {
|
||||
if buf.len() == n {
|
||||
std::borrow::Cow::Borrowed(buf)
|
||||
} else {
|
||||
std::borrow::Cow::Owned(vec![0u8; n])
|
||||
}
|
||||
}
|
||||
|
||||
/// A minimal before/after record of the region a raster edit changed.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RasterDiff {
|
||||
full_width: u32,
|
||||
full_height: u32,
|
||||
/// Changed bounding box `(x, y, w, h)`; `None` when before == after (no-op).
|
||||
bbox: Option<(u32, u32, u32, u32)>,
|
||||
/// bbox-sized RGBA (`w*h*4`) of the region before the edit.
|
||||
before_region: Vec<u8>,
|
||||
/// bbox-sized RGBA (`w*h*4`) of the region after the edit.
|
||||
after_region: Vec<u8>,
|
||||
/// The pre-edit buffer was blank (empty/unallocated) — i.e. this was the first
|
||||
/// edit on a fresh keyframe. Lets `apply_after` build from a transparent base
|
||||
/// (the commit/redo path often starts with empty `raw_pixels`) and `apply_before`
|
||||
/// restore to blank, instead of requiring a resident base.
|
||||
before_blank: bool,
|
||||
}
|
||||
|
||||
impl RasterDiff {
|
||||
/// Build a diff from full before/after buffers. `after` is expected to be the
|
||||
/// resident post-edit buffer (`width*height*4`); `before` may be empty (a blank
|
||||
/// keyframe's first stroke), treated as fully transparent.
|
||||
pub fn compute(before: &[u8], after: &[u8], width: u32, height: u32) -> Self {
|
||||
let n = width as usize * height as usize * 4;
|
||||
let before_blank = before.len() != n;
|
||||
// Normalize both sides to full length; empty/short ⇒ transparent.
|
||||
let before_full = normalize(before, n);
|
||||
let after_full = normalize(after, n);
|
||||
|
||||
// Find the tight bbox of differing pixels (compare 4-byte texels).
|
||||
let (w, h) = (width as usize, height as usize);
|
||||
let (mut min_x, mut min_y, mut max_x, mut max_y) = (usize::MAX, usize::MAX, 0usize, 0usize);
|
||||
let mut any = false;
|
||||
for y in 0..h {
|
||||
let row = y * w * 4;
|
||||
for x in 0..w {
|
||||
let i = row + x * 4;
|
||||
if before_full[i..i + 4] != after_full[i..i + 4] {
|
||||
any = true;
|
||||
if x < min_x { min_x = x; }
|
||||
if x > max_x { max_x = x; }
|
||||
if y < min_y { min_y = y; }
|
||||
if y > max_y { max_y = y; }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !any {
|
||||
return Self { full_width: width, full_height: height, bbox: None,
|
||||
before_region: Vec::new(), after_region: Vec::new(), before_blank };
|
||||
}
|
||||
|
||||
let bw = max_x - min_x + 1;
|
||||
let bh = max_y - min_y + 1;
|
||||
let crop = |full: &[u8]| -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(bw * bh * 4);
|
||||
for row in 0..bh {
|
||||
let src = ((min_y + row) * w + min_x) * 4;
|
||||
out.extend_from_slice(&full[src..src + bw * 4]);
|
||||
}
|
||||
out
|
||||
};
|
||||
|
||||
Self {
|
||||
full_width: width,
|
||||
full_height: height,
|
||||
bbox: Some((min_x as u32, min_y as u32, bw as u32, bh as u32)),
|
||||
before_region: crop(&before_full),
|
||||
after_region: crop(&after_full),
|
||||
before_blank,
|
||||
}
|
||||
}
|
||||
|
||||
/// Approximate retained size in bytes (the two cropped regions).
|
||||
pub fn byte_size(&self) -> usize {
|
||||
self.before_region.len() + self.after_region.len()
|
||||
}
|
||||
|
||||
/// 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.
|
||||
raw.clear();
|
||||
return;
|
||||
}
|
||||
self.stamp_resident(&self.before_region, raw);
|
||||
}
|
||||
|
||||
/// 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.
|
||||
let n = self.full_width as usize * self.full_height as usize * 4;
|
||||
raw.clear();
|
||||
raw.resize(n, 0);
|
||||
}
|
||||
self.stamp_resident(&self.after_region, raw);
|
||||
}
|
||||
|
||||
/// Stamp a bbox-sized region into `raw`, which must already be full-size. If it
|
||||
/// isn't (a non-blank base that the editor failed to fault in), skip rather than
|
||||
/// resize-and-corrupt — the frame will re-page to its container state.
|
||||
fn stamp_resident(&self, region: &[u8], raw: &mut [u8]) {
|
||||
let n = self.full_width as usize * self.full_height as usize * 4;
|
||||
let (x, y, bw, bh) = match self.bbox {
|
||||
Some(b) => b,
|
||||
None => return,
|
||||
};
|
||||
if raw.len() != n {
|
||||
eprintln!(
|
||||
"⚠️ [RASTER_DIFF] base not resident ({} != {}); skipping undo/redo apply",
|
||||
raw.len(), n
|
||||
);
|
||||
return;
|
||||
}
|
||||
let (x, y, bw, bh) = (x as usize, y as usize, bw as usize, bh as usize);
|
||||
let fw = self.full_width as usize;
|
||||
for row in 0..bh {
|
||||
let dst = ((y + row) * fw + x) * 4;
|
||||
let src = row * bw * 4;
|
||||
raw[dst..dst + bw * 4].copy_from_slice(®ion[src..src + bw * 4]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn solid(w: u32, h: u32, px: [u8; 4]) -> Vec<u8> {
|
||||
px.iter().copied().cycle().take((w * h * 4) as usize).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_reproduces_buffers_exactly() {
|
||||
let (w, h) = (8, 6);
|
||||
let before = solid(w, h, [10, 20, 30, 255]);
|
||||
let mut after = before.clone();
|
||||
// Change a 2x2 region at (3,2).
|
||||
for (dy, dx) in [(0, 0), (0, 1), (1, 0), (1, 1)] {
|
||||
let i = (((2 + dy) * w + (3 + dx)) * 4) as usize;
|
||||
after[i..i + 4].copy_from_slice(&[200, 100, 50, 255]);
|
||||
}
|
||||
let diff = RasterDiff::compute(&before, &after, w, h);
|
||||
assert_eq!(diff.bbox, Some((3, 2, 2, 2)));
|
||||
|
||||
let mut buf = after.clone();
|
||||
diff.apply_before(&mut buf, w, h);
|
||||
assert_eq!(buf, before, "undo must reproduce the pre-edit buffer exactly");
|
||||
diff.apply_after(&mut buf, w, h);
|
||||
assert_eq!(buf, after, "redo must reproduce the post-edit buffer exactly");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blank_before_first_stroke() {
|
||||
let (w, h) = (4, 4);
|
||||
let n = (w * h * 4) as usize;
|
||||
let before: Vec<u8> = Vec::new(); // blank keyframe
|
||||
let mut after = vec![0u8; n];
|
||||
let i = ((1 * w + 1) * 4) as usize;
|
||||
after[i..i + 4].copy_from_slice(&[255, 0, 0, 255]);
|
||||
let diff = RasterDiff::compute(&before, &after, w, h);
|
||||
assert_eq!(diff.bbox, Some((1, 1, 1, 1)));
|
||||
|
||||
// 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, 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, 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, w, h);
|
||||
assert_eq!(buf, after);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_change_is_noop() {
|
||||
let (w, h) = (4, 4);
|
||||
let buf = solid(w, h, [1, 2, 3, 4]);
|
||||
let diff = RasterDiff::compute(&buf, &buf, w, h);
|
||||
assert_eq!(diff.bbox, None);
|
||||
assert_eq!(diff.byte_size(), 0);
|
||||
let mut b = buf.clone();
|
||||
diff.apply_before(&mut b, w, h);
|
||||
assert_eq!(b, buf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn not_resident_base_is_skipped_not_corrupted() {
|
||||
let (w, h) = (4, 4);
|
||||
let before = solid(w, h, [9, 9, 9, 255]);
|
||||
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, w, h); // base not resident
|
||||
assert!(empty.is_empty(), "must not resize/corrupt a non-resident base");
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Raster flood-fill action — records and undoes a paint bucket fill on a RasterLayer.
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::actions::raster_diff::RasterDiff;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use uuid::Uuid;
|
||||
@@ -8,11 +9,13 @@ use uuid::Uuid;
|
||||
pub struct RasterFillAction {
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
buffer_before: Vec<u8>,
|
||||
buffer_after: Vec<u8>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
name: String,
|
||||
diff: RasterDiff,
|
||||
/// Full post-fill buffer, kept only for the first `execute` (commit); see
|
||||
/// `RasterStrokeAction::full_after`.
|
||||
full_after: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl RasterFillAction {
|
||||
@@ -24,7 +27,9 @@ impl RasterFillAction {
|
||||
width: u32,
|
||||
height: u32,
|
||||
) -> Self {
|
||||
Self { layer_id, time, buffer_before, buffer_after, width, height, name: "Flood fill".to_string() }
|
||||
let diff = RasterDiff::compute(&buffer_before, &buffer_after, width, height);
|
||||
Self { layer_id, time, width, height, name: "Flood fill".to_string(),
|
||||
diff, full_after: Some(buffer_after) }
|
||||
}
|
||||
|
||||
pub fn with_description(mut self, name: &str) -> Self {
|
||||
@@ -41,9 +46,17 @@ impl Action for RasterFillAction {
|
||||
AnyLayer::Raster(rl) => rl,
|
||||
_ => return Err("Not a raster layer".to_string()),
|
||||
};
|
||||
let kf = raster.ensure_keyframe_at(self.time, self.width, self.height);
|
||||
kf.raw_pixels = self.buffer_after.clone();
|
||||
let _ = (self.width, self.height);
|
||||
let kf = raster
|
||||
.keyframe_at_mut(self.time)
|
||||
.ok_or_else(|| format!("No raster keyframe at/before t={}", self.time))?;
|
||||
if let Some(full) = self.full_after.take() {
|
||||
kf.raw_pixels = full;
|
||||
} else {
|
||||
self.diff.apply_after(&mut kf.raw_pixels, kf.width, kf.height);
|
||||
}
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -54,13 +67,21 @@ impl Action for RasterFillAction {
|
||||
AnyLayer::Raster(rl) => rl,
|
||||
_ => return Err("Not a raster layer".to_string()),
|
||||
};
|
||||
let kf = raster.ensure_keyframe_at(self.time, self.width, self.height);
|
||||
kf.raw_pixels = self.buffer_before.clone();
|
||||
let _ = (self.width, self.height);
|
||||
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, kf.width, kf.height);
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
self.name.clone()
|
||||
}
|
||||
|
||||
fn raster_resident_hint(&self) -> Option<(Uuid, f64)> {
|
||||
Some((self.layer_id, self.time))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
//! `rollback` → swap in `buffer_before`
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::actions::raster_diff::RasterDiff;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use uuid::Uuid;
|
||||
@@ -16,16 +17,20 @@ use uuid::Uuid;
|
||||
/// Action that records a single brush stroke for undo/redo.
|
||||
///
|
||||
/// The stroke must already be painted into the document's `raw_pixels` before
|
||||
/// this action is executed for the first time.
|
||||
/// this action is executed for the first time. Only the changed bounding box is
|
||||
/// retained (see [`RasterDiff`]) rather than two full frame buffers.
|
||||
pub struct RasterStrokeAction {
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
/// Raw RGBA pixels *before* the stroke (for rollback / undo)
|
||||
buffer_before: Vec<u8>,
|
||||
/// Raw RGBA pixels *after* the stroke (for execute / redo)
|
||||
buffer_after: Vec<u8>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
diff: RasterDiff,
|
||||
/// The full post-stroke buffer, kept ONLY for the first `execute` (the commit),
|
||||
/// which establishes `raw_pixels` exactly like the old code did — robust no matter
|
||||
/// what state the working buffer is in (empty new keyframe, GPU-canvas readback,
|
||||
/// etc.). Taken (dropped) on first execute, so the action sitting in the undo stack
|
||||
/// retains only the small `diff`; redo then replays via the diff.
|
||||
full_after: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl RasterStrokeAction {
|
||||
@@ -33,6 +38,8 @@ impl RasterStrokeAction {
|
||||
///
|
||||
/// * `buffer_before` – raw RGBA pixels captured just before the stroke began.
|
||||
/// * `buffer_after` – raw RGBA pixels captured just after the stroke finished.
|
||||
///
|
||||
/// The full buffers are diffed down to the changed bbox here and then dropped.
|
||||
pub fn new(
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
@@ -41,28 +48,41 @@ impl RasterStrokeAction {
|
||||
width: u32,
|
||||
height: u32,
|
||||
) -> Self {
|
||||
Self { layer_id, time, buffer_before, buffer_after, width, height }
|
||||
let diff = RasterDiff::compute(&buffer_before, &buffer_after, width, height);
|
||||
Self { layer_id, time, width, height, diff, full_after: Some(buffer_after) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for RasterStrokeAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let kf = get_keyframe_mut(document, &self.layer_id, self.time, self.width, self.height)?;
|
||||
kf.raw_pixels = self.buffer_after.clone();
|
||||
if let Some(full) = self.full_after.take() {
|
||||
// First execute (commit): assign the full buffer outright.
|
||||
kf.raw_pixels = full;
|
||||
} else {
|
||||
// Redo: replay via the diff onto the (resident) base.
|
||||
self.diff.apply_after(&mut kf.raw_pixels, kf.width, kf.height);
|
||||
}
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let kf = get_keyframe_mut(document, &self.layer_id, self.time, self.width, self.height)?;
|
||||
kf.raw_pixels = self.buffer_before.clone();
|
||||
self.diff.apply_before(&mut kf.raw_pixels, kf.width, kf.height);
|
||||
kf.texture_dirty = true;
|
||||
kf.dirty = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
"Paint stroke".to_string()
|
||||
}
|
||||
|
||||
fn raster_resident_hint(&self) -> Option<(Uuid, f64)> {
|
||||
Some((self.layer_id, self.time))
|
||||
}
|
||||
}
|
||||
|
||||
fn get_keyframe_mut<'a>(
|
||||
@@ -79,5 +99,10 @@ fn get_keyframe_mut<'a>(
|
||||
AnyLayer::Raster(rl) => rl,
|
||||
_ => return Err("Not a raster layer".to_string()),
|
||||
};
|
||||
Ok(raster.ensure_keyframe_at(time, width, height))
|
||||
let _ = (width, height);
|
||||
// Edit the ACTIVE keyframe (at-or-before `time`); never create one — keyframes
|
||||
// are made explicitly via "New Keyframe".
|
||||
raster
|
||||
.keyframe_at_mut(time)
|
||||
.ok_or_else(|| format!("No raster keyframe at/before t={time}"))
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
@@ -177,10 +179,10 @@ impl Action for RemoveClipInstancesAction {
|
||||
let midi_instance = daw_backend::MidiClipInstance::new(
|
||||
0,
|
||||
*midi_clip_id,
|
||||
internal_start,
|
||||
internal_end,
|
||||
external_start,
|
||||
external_duration,
|
||||
daw_backend::Beats(internal_start),
|
||||
daw_backend::Beats(internal_end),
|
||||
daw_backend::Beats(external_start),
|
||||
daw_backend::Beats(external_duration),
|
||||
);
|
||||
|
||||
let query = Query::AddMidiClipInstanceSync(track_id, midi_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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,8 @@ pub enum LayerProperty {
|
||||
Visible(bool),
|
||||
/// Video layer only: toggle live webcam preview
|
||||
CameraEnabled(bool),
|
||||
/// Rename the layer; sets has_custom_name = true
|
||||
Name(String),
|
||||
}
|
||||
|
||||
/// Stored old value for rollback
|
||||
@@ -33,6 +35,7 @@ enum OldValue {
|
||||
Opacity(f64),
|
||||
Visible(bool),
|
||||
CameraEnabled(bool),
|
||||
Name(String),
|
||||
}
|
||||
|
||||
/// Action that sets a property on one or more layers
|
||||
@@ -101,6 +104,7 @@ impl Action for SetLayerPropertiesAction {
|
||||
};
|
||||
OldValue::CameraEnabled(val)
|
||||
}
|
||||
LayerProperty::Name(_) => OldValue::Name(layer.name().to_string()),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -118,6 +122,10 @@ impl Action for SetLayerPropertiesAction {
|
||||
v.camera_enabled = *c;
|
||||
}
|
||||
}
|
||||
LayerProperty::Name(n) => {
|
||||
layer.set_name(n.clone());
|
||||
layer.set_has_custom_name(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -143,6 +151,10 @@ impl Action for SetLayerPropertiesAction {
|
||||
v.camera_enabled = *c;
|
||||
}
|
||||
}
|
||||
OldValue::Name(n) => {
|
||||
layer.set_name(n.clone());
|
||||
layer.set_has_custom_name(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -206,6 +218,7 @@ impl Action for SetLayerPropertiesAction {
|
||||
LayerProperty::InputGain(_) => "input gain",
|
||||
LayerProperty::Muted(_) => "mute",
|
||||
LayerProperty::Soloed(_) => "solo",
|
||||
LayerProperty::Name(_) => "name",
|
||||
LayerProperty::Locked(_) => "lock",
|
||||
LayerProperty::Opacity(_) => "opacity",
|
||||
LayerProperty::Visible(_) => "visibility",
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user