Compare commits
221
Commits
54d5764bd0
...
release
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
91543202ed | ||
|
|
73104e5803 | ||
|
|
a09b0c1a93 | ||
|
|
421f8fdcc6 | ||
|
|
07b2478a0e | ||
|
|
5e73f7f75d | ||
|
|
8cde113797 | ||
|
|
6924fc0ffe | ||
|
|
c62164c365 | ||
|
|
6629adc7d2 | ||
|
|
a5cdbfd0fd | ||
|
|
16e3d676d6 | ||
|
|
f957b01dcf | ||
|
|
9f67a82e3e | ||
|
|
ddd6e0cdbc | ||
|
|
a94f6004e5 | ||
|
|
a3706dd2c4 | ||
|
|
ba4395602d | ||
|
|
8ed2320dca | ||
|
|
c747126759 | ||
|
|
64bf9bb431 | ||
|
|
b5766672ee | ||
|
|
0050c18623 | ||
|
|
053a77cfa1 | ||
|
|
0eff5f7f33 | ||
|
|
b6f43d2e72 | ||
|
|
8fbb6d65c0 | ||
|
|
6aece26a8b | ||
|
|
ef2b0822bd | ||
|
|
5f09222f3f | ||
|
|
b0e965b1c2 | ||
|
|
6596acb3db | ||
|
|
d6b86a14b1 | ||
|
|
a2839f80b1 | ||
|
|
6e6feaddf5 | ||
|
|
15bdf80ec1 | ||
|
|
6b8a1f1386 | ||
|
|
53ffb7d528 | ||
|
|
c373af461e | ||
|
|
6e361aa30c | ||
|
|
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 | ||
|
|
609b80336b | ||
|
|
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 | ||
|
|
a933fc3ca8 | ||
|
|
e7c239f203 | ||
|
|
7ebd64391c | ||
|
|
05b5bf5f85 | ||
|
|
d6506c2f22 | ||
|
|
5bed2e8adb | ||
|
|
911d896610 | ||
|
|
ecfa192245 | ||
|
|
2bce5e93a6 | ||
|
|
3e4f29c297 | ||
|
|
a00e73c4b3 | ||
|
|
ba897eaea2 | ||
|
|
5917ce7921 | ||
|
|
da65b63bdf | ||
|
|
2564d807a0 | ||
|
|
70ac0cde00 | ||
|
|
5844a0f070 | ||
|
|
ce151ffd61 | ||
|
|
34eee3a620 | ||
|
|
5f0d5354ed | ||
|
|
bf4331eed4 | ||
|
|
273862c882 | ||
|
|
a3f18bdab6 | ||
|
|
2c40858663 | ||
|
|
149760e9c0 | ||
|
|
1cb821f05b | ||
|
|
8223593649 | ||
|
|
83057b754a | ||
|
|
f0929e2b6d | ||
|
|
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 | ||
|
|
327e40026a | ||
|
|
7257cdf9c4 | ||
|
|
d6c6c0d72d | ||
|
|
398457093a | ||
|
|
d7de5ce3f1 | ||
|
|
2a0c7da5ea | ||
|
|
37f4abd1f5 | ||
|
|
a36553ccbb | ||
|
|
47a6569fe0 | ||
|
|
73d5d554c7 | ||
|
|
45955dbbec | ||
|
|
b4e5469b51 | ||
|
|
42679cb02a | ||
|
|
42bdab988d | ||
|
|
e9455c2ef2 | ||
|
|
73fd191a28 | ||
|
|
f79439ced3 | ||
|
|
bfc8be4058 | ||
|
|
25248f5088 | ||
|
|
b6c72f3175 | ||
|
|
6d04143606 | ||
|
|
3f0fcbb626 | ||
|
|
9b9a61f2a0 | ||
|
|
ea47f1d1c8 | ||
|
|
6bbc660019 | ||
|
|
51bed98b0b | ||
|
|
fc82d1e1be | ||
|
|
1871bb713c | ||
|
|
e65aac496c | ||
|
|
3db3eaef67 | ||
|
|
82733268c5 | ||
|
|
c6206b87bd | ||
|
|
822012b17b | ||
|
|
10b69837c3 | ||
|
|
a07b9bae76 |
+95
-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
|
||||
@@ -54,6 +54,27 @@ jobs:
|
||||
with:
|
||||
targets: ${{ matrix.target != '' && matrix.target || '' }}
|
||||
|
||||
# A [patch.crates-io] whose version doesn't satisfy the dependency requirement is silently
|
||||
# IGNORED by cargo: it warns "patch ... was not used in the crate graph" and builds against the
|
||||
# real crates.io crate instead. That's how a stale egui fork got us a `cannot find type
|
||||
# CursorImage` error four minutes into the build, in a file that had nothing to do with the
|
||||
# cause. Fail here instead, with the actual reason.
|
||||
- name: Verify egui fork patch applies
|
||||
shell: bash
|
||||
working-directory: ./lightningbeam-ui
|
||||
run: |
|
||||
unused=$(cargo metadata --format-version 1 2>&1 >/dev/null | grep "was not used in the crate graph" || true)
|
||||
if [ -n "$unused" ]; then
|
||||
echo "::error::The egui fork's [patch.crates-io] entries are being ignored — cargo is building against stock crates.io egui, not the fork."
|
||||
echo "$unused"
|
||||
echo ""
|
||||
echo "The fork's version must SATISFY the requirement in lightningbeam-ui/Cargo.toml."
|
||||
echo "Fork workspace version: $(grep -m1 '^version' ../egui-fork/Cargo.toml)"
|
||||
echo "Required by us: $(grep -m1 '^eframe' Cargo.toml)"
|
||||
exit 1
|
||||
fi
|
||||
echo "egui fork patch applies cleanly."
|
||||
|
||||
- name: Rust cache
|
||||
uses: swatinem/rust-cache@v2
|
||||
with:
|
||||
@@ -62,7 +83,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 +92,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 +110,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 +139,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 +165,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 +175,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 +201,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 +213,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 +237,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 +262,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 +278,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 +332,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 +340,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 +348,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 +368,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 +453,7 @@ jobs:
|
||||
|
||||
release:
|
||||
needs: build
|
||||
runs-on: ubuntu-22.04
|
||||
runs-on: ubuntu-24.04
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
|
||||
+4
-3
@@ -28,8 +28,6 @@ dist-ssr
|
||||
.gitignore
|
||||
|
||||
# Build
|
||||
src-tauri/gen
|
||||
src-tauri/target
|
||||
lightningbeam-core/target
|
||||
daw-backend/target
|
||||
target/
|
||||
@@ -40,4 +38,7 @@ packaging/AppDir/
|
||||
packaging/squashfs-root/
|
||||
|
||||
# Wrapper script (generated, not needed with static FFmpeg)
|
||||
lightningbeam-ui/lightningbeam-editor/debian/
|
||||
lightningbeam-ui/lightningbeam-editor/debian/
|
||||
|
||||
# Personal working notes (not version-controlled)
|
||||
TODO.md
|
||||
+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:
|
||||
|
||||
+132
@@ -1,3 +1,135 @@
|
||||
# 1.0.10-alpha:
|
||||
Changes:
|
||||
- Cycle recording: highlight a range on the timeline ruler (the cycle strip, shown when looping is armed) and the transport loops it. Recording round the loop turns each pass into a separate take you can choose between afterwards, and recording again over the same region adds more takes rather than stacking a second clip on top. Starting playback from outside the region jumps to its start
|
||||
- Takes: a "Take N/M" badge on the clip picks which take plays. Splitting a clip lets each half play a different take, so you can comp a part together from the best bits of several passes. Right-click a clip to delete the take that's playing or to delete all the unused ones; double-click a take in the list to rename it
|
||||
- MIDI cycle recording can either merge every pass into one clip (the default — earlier passes play back as you record, so you can layer a hi-hat over a kick) or keep each pass as a separate take, like audio does. Set it in Preferences → Audio
|
||||
- Painting: every colour-using tool (brush, paint bucket, eyedropper) now shares one Foreground/Background swatch row, and the eyedropper has an explicit toggle for which of the two it fills
|
||||
- Painting: the effect brushes (dodge/burn, sponge, blur, smudge, clone stamp, healing brush, pattern stamp) were stuck on a single fixed brush shape. They now each have their own size, strength, hardness and spacing, and can use any brush from the library
|
||||
- Tablet: stylus barrel buttons now work, with actions you can bind in Preferences (Pan, Eyedropper, or Eraser). Middle-mouse panning added too
|
||||
- Timeline: raster and text layers get an opacity slider; each layer row now shows only the controls that mean anything for it (volume for audio, opacity for raster/text, both for vector and video), and layers gain a visibility (eye) toggle
|
||||
- The stage gains undo/redo buttons, sized for touch and tablet use
|
||||
|
||||
Bugfixes:
|
||||
- Splitting an audio clip made it play back at the wrong length (a clip split at 1 second cut off after half a second at 120 BPM)
|
||||
- Trimmed MIDI clips were the wrong length on the timeline at any tempo other than 60 BPM
|
||||
- The paint bucket always filled with the background colour, whatever the brush was set to
|
||||
- Where an eyedropper sample landed (foreground or background) depended on which colour picker you had opened last
|
||||
- Stylus barrel buttons were silently ignored on Wayland
|
||||
- The opacity slider on a raster layer actually changed its volume, which means nothing on a raster layer
|
||||
- Tool cursors lagged behind the pointer while drawing; they're now drawn by the system rather than into the canvas
|
||||
- Colour picker popups wouldn't close when you dragged on the stage, so drawing left one hanging open, and clicking inside a picker's own hue slider closed it
|
||||
- The toolbar could not be scrolled when the pane was too short to show every tool
|
||||
|
||||
# 1.0.9-alpha:
|
||||
Bugfixes:
|
||||
- Fix audio recording placement: a second recording landed at the wrong spot (and clicking/dragging clips was similarly off) at any tempo other than 60 BPM — recordings now start exactly at the playhead at any tempo
|
||||
- While recording a second audio clip, the live bar showed as a zero-length clip until you stopped; it now grows as you record
|
||||
- MIDI clips were drawn with the wrong length (their end grew too fast) at tempos other than 120 BPM
|
||||
- Recording a MIDI clip didn't mark the project as having unsaved changes, so closing or starting a new file didn't prompt to save
|
||||
- Audio and MIDI recording can now be undone (and redone)
|
||||
|
||||
# 1.0.8-alpha:
|
||||
Changes:
|
||||
- Mobile/touch UI (experimental, testing only — not built or packaged for mobile yet; enabled on desktop with the LB_MOBILE_UI environment variable): work-in-progress phone-friendly interface with a vertical sliding-window pane stack you drag to reveal panes, a new-file intent picker, a selection inspector sheet, a keyboard-primary music surface, a Focus/Patch node editor, long-press context menus, a command palette, and landscape/orientation support
|
||||
- Text layers: add and edit text with a chosen font; non-bundled fonts are embedded in the project so it renders on machines that lack them
|
||||
- Animated GIF export (parallel palette encoding)
|
||||
- Audio tag metadata (title, artist, album, genre, year, track, comment) is written into exports — ID3v2 for MP3, iTunes/MP4 atoms for AAC, Vorbis comments for FLAC, RIFF INFO for WAV — with sensible defaults (year, artist/album remembered between exports)
|
||||
- Lossy WebP image export, so the quality control now actually applies
|
||||
- SVG export now includes text layers, as real font-independent glyph outlines
|
||||
- Crash recovery: the editor autosaves your work to a recovery file in the background and offers to restore it after an unclean shutdown
|
||||
- Prompt to save unsaved changes before starting a new file, opening another, or quitting
|
||||
- Faster saves on painting projects: unchanged raster frames are no longer re-encoded every save
|
||||
|
||||
Bugfixes:
|
||||
- FLAC export previously wrote a WAV file with a .flac extension; it now encodes real (compressed) FLAC
|
||||
- ProRes 422 export always failed; it now encodes 10-bit 4:2:2 correctly
|
||||
- Fix VP8 video export with audio (muxed into WebM instead of an incompatible container)
|
||||
- The WebP "Quality" slider had no effect
|
||||
- Starting a new file now fully resets the audio engine, so instruments and voices from the previous project no longer linger
|
||||
- Fix oscillator/synth phase drift over long playback
|
||||
|
||||
# 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)
|
||||
@@ -58,13 +58,21 @@ Lightningbeam is under active development on the `rust-ui` branch. The project h
|
||||
- ✅ Audio engine with node graph processing
|
||||
- ✅ GPU waveform rendering with mipmaps
|
||||
- ✅ Video decoding integration
|
||||
- 🚧 Export system (in progress)
|
||||
- 🚧 Node editor UI (planned)
|
||||
- 🚧 Piano roll editor (planned)
|
||||
- ✅ Export system (video, image, audio, animated GIF, SVG)
|
||||
- ✅ Node editor UI
|
||||
- 🚧 Piano roll editor (in progress)
|
||||
|
||||
## Getting Started
|
||||
|
||||
### Prerequisites
|
||||
### Download a prebuilt release
|
||||
|
||||
If you don't want to build from source, prebuilt binaries for each release are on the
|
||||
[GitHub releases page](https://github.com/skykooler/lightningbeam/releases). Download the build for
|
||||
your platform and run it directly.
|
||||
|
||||
### Building from source
|
||||
|
||||
#### Prerequisites
|
||||
|
||||
- Rust (stable toolchain via [rustup](https://rustup.rs/))
|
||||
- System dependencies:
|
||||
@@ -74,7 +82,7 @@ Lightningbeam is under active development on the `rust-ui` branch. The project h
|
||||
|
||||
See [docs/BUILDING.md](docs/BUILDING.md) for detailed setup instructions.
|
||||
|
||||
### Building and Running
|
||||
#### Building and Running
|
||||
|
||||
```bash
|
||||
# Clone the repository
|
||||
|
||||
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
+10
@@ -586,6 +586,7 @@ dependencies = [
|
||||
"dasp_rms",
|
||||
"dasp_sample",
|
||||
"dasp_signal",
|
||||
"ffmpeg-blob-io",
|
||||
"ffmpeg-next",
|
||||
"hound",
|
||||
"memmap2",
|
||||
@@ -661,6 +662,15 @@ version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "af9673d8203fcb076b19dfd17e38b3d4ae9f44959416ea532ce72415a6020365"
|
||||
|
||||
[[package]]
|
||||
name = "ffmpeg-blob-io"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"ffmpeg-next",
|
||||
"ffmpeg-sys-next",
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ffmpeg-next"
|
||||
version = "8.0.0"
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -189,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);
|
||||
@@ -214,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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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).
|
||||
|
||||
+752
-174
File diff suppressed because it is too large
Load Diff
+274
-37
@@ -50,6 +50,10 @@ pub struct ExportSettings {
|
||||
pub end_time: Seconds,
|
||||
/// Tempo map for beat-position scheduling
|
||||
pub tempo_map: TempoMap,
|
||||
/// Tag metadata as (ffmpeg-key, value) pairs (e.g. ("title", "…"), ("artist", "…")). Written to
|
||||
/// the container's native tags: ID3v2 (MP3), MP4 atoms (M4A), Vorbis comments (FLAC), RIFF INFO
|
||||
/// (WAV). Empty = no tags.
|
||||
pub metadata: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl Default for ExportSettings {
|
||||
@@ -63,10 +67,26 @@ impl Default for ExportSettings {
|
||||
start_time: Seconds::ZERO,
|
||||
end_time: Seconds(60.0),
|
||||
tempo_map: TempoMap::constant(120.0),
|
||||
metadata: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Set tag metadata on an ffmpeg output context (before `write_header`). FFmpeg maps the standard
|
||||
/// keys to each container's native tags.
|
||||
fn apply_metadata(output: &mut ffmpeg_next::format::context::Output, metadata: &[(String, String)]) {
|
||||
if metadata.is_empty() {
|
||||
return;
|
||||
}
|
||||
let mut dict = ffmpeg_next::Dictionary::new();
|
||||
for (k, v) in metadata {
|
||||
if !v.is_empty() {
|
||||
dict.set(k, v);
|
||||
}
|
||||
}
|
||||
output.set_metadata(dict);
|
||||
}
|
||||
|
||||
/// Export the project to an audio file
|
||||
///
|
||||
/// This performs offline rendering, processing the entire timeline
|
||||
@@ -108,17 +128,21 @@ pub fn export_audio<P: AsRef<Path>>(
|
||||
// Route to appropriate export implementation based on format.
|
||||
// Ensure export mode is disabled even if an error occurs.
|
||||
let result = match settings.format {
|
||||
ExportFormat::Wav | ExportFormat::Flac => {
|
||||
ExportFormat::Wav => {
|
||||
let samples = render_to_memory(project, pool, settings, event_tx.as_mut().map(|tx| &mut **tx))?;
|
||||
// Signal that rendering is done and we're now writing the file
|
||||
if let Some(ref mut tx) = event_tx {
|
||||
let _ = tx.push(AudioEvent::ExportFinalizing);
|
||||
}
|
||||
match settings.format {
|
||||
ExportFormat::Wav => write_wav(&samples, settings, &output_path),
|
||||
ExportFormat::Flac => write_flac(&samples, settings, &output_path),
|
||||
_ => unreachable!(),
|
||||
write_wav(&samples, settings, &output_path)
|
||||
// hound writes no metadata; append a RIFF INFO chunk for tags.
|
||||
.and_then(|_| append_wav_info_chunk(output_path.as_ref(), &settings.metadata))
|
||||
}
|
||||
ExportFormat::Flac => {
|
||||
let samples = render_to_memory(project, pool, settings, event_tx.as_mut().map(|tx| &mut **tx))?;
|
||||
if let Some(ref mut tx) = event_tx {
|
||||
let _ = tx.push(AudioEvent::ExportFinalizing);
|
||||
}
|
||||
export_flac(&samples, settings, &output_path)
|
||||
}
|
||||
ExportFormat::Mp3 => {
|
||||
export_mp3(project, pool, settings, output_path, event_tx)
|
||||
@@ -187,6 +211,7 @@ pub fn render_to_memory(
|
||||
settings.sample_rate,
|
||||
settings.channels,
|
||||
false,
|
||||
None, // export never runs with a recording in flight
|
||||
);
|
||||
|
||||
// Calculate how many samples we actually need from this chunk
|
||||
@@ -273,48 +298,174 @@ fn write_wav<P: AsRef<Path>>(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write FLAC file using hound (FLAC is essentially lossless WAV)
|
||||
fn write_flac<P: AsRef<Path>>(
|
||||
/// Export real FLAC via ffmpeg from already-rendered interleaved f32 samples (Vorbis-comment
|
||||
/// metadata). Replaces the former `write_flac`, which wrote WAV bytes to a `.flac` file. 16-bit
|
||||
/// uses S16; 24-bit uses S32 (ffmpeg's flac encoder emits `bits_per_raw_sample = 24` for S32,
|
||||
/// taking the top 24 bits).
|
||||
fn export_flac<P: AsRef<Path>>(
|
||||
samples: &[f32],
|
||||
settings: &ExportSettings,
|
||||
output_path: P,
|
||||
) -> Result<(), String> {
|
||||
// For now, we'll use hound to write a WAV-like FLAC file
|
||||
// In the future, we could use a dedicated FLAC encoder
|
||||
let spec = hound::WavSpec {
|
||||
channels: settings.channels as u16,
|
||||
sample_rate: settings.sample_rate,
|
||||
bits_per_sample: settings.bit_depth,
|
||||
sample_format: hound::SampleFormat::Int,
|
||||
use ffmpeg_next as ffmpeg;
|
||||
|
||||
ffmpeg::init().map_err(|e| format!("Failed to initialize FFmpeg: {}", e))?;
|
||||
|
||||
let codec = ffmpeg::encoder::find(ffmpeg::codec::Id::FLAC)
|
||||
.ok_or("FLAC encoder not found in this ffmpeg build")?;
|
||||
let mut output = ffmpeg::format::output(&output_path)
|
||||
.map_err(|e| format!("Failed to create output file: {}", e))?;
|
||||
|
||||
let channel_layout = match settings.channels {
|
||||
1 => ffmpeg::channel_layout::ChannelLayout::MONO,
|
||||
2 => ffmpeg::channel_layout::ChannelLayout::STEREO,
|
||||
_ => return Err(format!("Unsupported channel count: {}", settings.channels)),
|
||||
};
|
||||
|
||||
let mut writer = hound::WavWriter::create(output_path, spec)
|
||||
.map_err(|e| format!("Failed to create FLAC file: {}", e))?;
|
||||
// FLAC accepts packed S16 or S32; S32 → 24-bit output.
|
||||
let use_24 = settings.bit_depth >= 24;
|
||||
let sample_fmt = if use_24 {
|
||||
ffmpeg::format::Sample::I32(ffmpeg::format::sample::Type::Packed)
|
||||
} else {
|
||||
ffmpeg::format::Sample::I16(ffmpeg::format::sample::Type::Packed)
|
||||
};
|
||||
|
||||
// Write samples (same as WAV for now)
|
||||
match settings.bit_depth {
|
||||
16 => {
|
||||
for &sample in samples {
|
||||
let clamped = sample.max(-1.0).min(1.0);
|
||||
let pcm_value = (clamped * 32767.0) as i16;
|
||||
writer.write_sample(pcm_value)
|
||||
.map_err(|e| format!("Failed to write sample: {}", e))?;
|
||||
let mut encoder = ffmpeg::codec::Context::new_with_codec(codec)
|
||||
.encoder()
|
||||
.audio()
|
||||
.map_err(|e| format!("Failed to create FLAC encoder: {}", e))?;
|
||||
encoder.set_rate(settings.sample_rate as i32);
|
||||
encoder.set_channel_layout(channel_layout);
|
||||
encoder.set_format(sample_fmt);
|
||||
encoder.set_time_base(ffmpeg::Rational(1, settings.sample_rate as i32));
|
||||
let mut encoder = encoder.open_as(codec)
|
||||
.map_err(|e| format!("Failed to open FLAC encoder: {}", e))?;
|
||||
|
||||
{
|
||||
let mut stream = output.add_stream(codec)
|
||||
.map_err(|e| format!("Failed to add stream: {}", e))?;
|
||||
stream.set_parameters(&encoder);
|
||||
}
|
||||
apply_metadata(&mut output, &settings.metadata);
|
||||
output.write_header()
|
||||
.map_err(|e| format!("Failed to write FLAC header: {}", e))?;
|
||||
|
||||
let channels = settings.channels as usize;
|
||||
let num_frames = samples.len() / channels;
|
||||
let frame_size = if encoder.frame_size() > 0 { encoder.frame_size() as usize } else { 4096 };
|
||||
|
||||
let mut done = 0usize;
|
||||
while done < num_frames {
|
||||
let n = (num_frames - done).min(frame_size);
|
||||
let mut frame = ffmpeg::frame::Audio::new(sample_fmt, n, channel_layout);
|
||||
frame.set_rate(settings.sample_rate);
|
||||
frame.set_pts(Some(done as i64)); // samples; the FLAC muxer requires PTS
|
||||
|
||||
let buf = frame.data_mut(0); // packed interleaved → plane 0
|
||||
let base = done * channels;
|
||||
if use_24 {
|
||||
for i in 0..n * channels {
|
||||
let s = samples[base + i].clamp(-1.0, 1.0);
|
||||
let v = (s as f64 * 2_147_483_647.0) as i32; // full-scale S32; encoder takes top 24
|
||||
buf[i * 4..i * 4 + 4].copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
} else {
|
||||
for i in 0..n * channels {
|
||||
let s = samples[base + i].clamp(-1.0, 1.0);
|
||||
let v = (s * 32767.0) as i16;
|
||||
buf[i * 2..i * 2 + 2].copy_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
}
|
||||
24 => {
|
||||
for &sample in samples {
|
||||
let clamped = sample.max(-1.0).min(1.0);
|
||||
let pcm_value = (clamped * 8388607.0) as i32;
|
||||
writer.write_sample(pcm_value)
|
||||
.map_err(|e| format!("Failed to write sample: {}", e))?;
|
||||
}
|
||||
|
||||
encoder.send_frame(&frame).map_err(|e| format!("Failed to send FLAC frame: {}", e))?;
|
||||
flac_write_packets(&mut encoder, &mut output)?;
|
||||
done += n;
|
||||
}
|
||||
encoder.send_eof().map_err(|e| format!("Failed to flush FLAC encoder: {}", e))?;
|
||||
flac_write_packets(&mut encoder, &mut output)?;
|
||||
output.write_trailer().map_err(|e| format!("Failed to finalize FLAC: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drain encoded FLAC packets and write them (non-interleaved). Skips the trailing empty flush
|
||||
/// packet, which the FLAC muxer otherwise rejects as "Invalid data". Rescales packet ts from the
|
||||
/// encoder time base to the stream's.
|
||||
fn flac_write_packets(
|
||||
encoder: &mut ffmpeg_next::encoder::Audio,
|
||||
output: &mut ffmpeg_next::format::context::Output,
|
||||
) -> Result<(), String> {
|
||||
let mut pkt = ffmpeg_next::Packet::empty();
|
||||
let enc_tb = encoder.time_base();
|
||||
let stream_tb = output.stream(0).map(|s| s.time_base()).unwrap_or(enc_tb);
|
||||
while encoder.receive_packet(&mut pkt).is_ok() {
|
||||
if pkt.size() == 0 {
|
||||
continue;
|
||||
}
|
||||
_ => return Err(format!("Unsupported bit depth: {}", settings.bit_depth)),
|
||||
pkt.set_stream(0);
|
||||
pkt.rescale_ts(enc_tb, stream_tb);
|
||||
pkt.write(output).map_err(|e| format!("Failed to write FLAC packet: {}", e))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Append a RIFF `LIST`/`INFO` metadata chunk to a finished WAV file (hound writes no tags), then
|
||||
/// fix up the top-level RIFF size. Maps ffmpeg-style keys to RIFF INFO sub-chunk IDs. Trailing INFO
|
||||
/// chunks are ignored by players that don't read them.
|
||||
fn append_wav_info_chunk(path: &Path, metadata: &[(String, String)]) -> Result<(), String> {
|
||||
use std::io::{Seek, SeekFrom, Write};
|
||||
|
||||
let riff_id = |key: &str| -> Option<&'static [u8; 4]> {
|
||||
match key {
|
||||
"title" => Some(b"INAM"),
|
||||
"artist" => Some(b"IART"),
|
||||
"album" => Some(b"IPRD"),
|
||||
"genre" => Some(b"IGNR"),
|
||||
"comment" => Some(b"ICMT"),
|
||||
"date" => Some(b"ICRD"),
|
||||
"track" => Some(b"ITRK"),
|
||||
_ => None,
|
||||
}
|
||||
};
|
||||
|
||||
let mut info: Vec<u8> = Vec::new();
|
||||
info.extend_from_slice(b"INFO");
|
||||
for (key, val) in metadata {
|
||||
if val.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some(id) = riff_id(key) else { continue };
|
||||
let mut bytes = val.as_bytes().to_vec();
|
||||
bytes.push(0); // NUL-terminate
|
||||
if bytes.len() % 2 == 1 {
|
||||
bytes.push(0); // pad to even
|
||||
}
|
||||
info.extend_from_slice(id);
|
||||
info.extend_from_slice(&(bytes.len() as u32).to_le_bytes());
|
||||
info.extend_from_slice(&bytes);
|
||||
}
|
||||
if info.len() <= 4 {
|
||||
return Ok(()); // nothing but the "INFO" tag
|
||||
}
|
||||
|
||||
writer.finalize()
|
||||
.map_err(|e| format!("Failed to finalize FLAC file: {}", e))?;
|
||||
let mut list: Vec<u8> = Vec::with_capacity(info.len() + 8);
|
||||
list.extend_from_slice(b"LIST");
|
||||
list.extend_from_slice(&(info.len() as u32).to_le_bytes());
|
||||
list.extend_from_slice(&info);
|
||||
|
||||
let mut f = std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(path)
|
||||
.map_err(|e| format!("Failed to open WAV for tagging: {}", e))?;
|
||||
let end = f.seek(SeekFrom::End(0)).map_err(|e| e.to_string())?;
|
||||
if end % 2 == 1 {
|
||||
f.write_all(&[0]).map_err(|e| e.to_string())?;
|
||||
}
|
||||
f.write_all(&list).map_err(|e| format!("Failed to write WAV tags: {}", e))?;
|
||||
let new_len = f.seek(SeekFrom::End(0)).map_err(|e| e.to_string())?;
|
||||
f.seek(SeekFrom::Start(4)).map_err(|e| e.to_string())?;
|
||||
f.write_all(&((new_len - 8) as u32).to_le_bytes())
|
||||
.map_err(|e| format!("Failed to update RIFF size: {}", e))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -362,6 +513,7 @@ fn export_mp3<P: AsRef<Path>>(
|
||||
stream.set_parameters(&encoder);
|
||||
}
|
||||
|
||||
apply_metadata(&mut output, &settings.metadata);
|
||||
output.write_header()
|
||||
.map_err(|e| format!("Failed to write header: {}", e))?;
|
||||
|
||||
@@ -406,6 +558,7 @@ fn export_mp3<P: AsRef<Path>>(
|
||||
settings.sample_rate,
|
||||
settings.channels,
|
||||
false,
|
||||
None, // export never runs with a recording in flight
|
||||
);
|
||||
|
||||
// Calculate how many samples we need from this chunk
|
||||
@@ -531,6 +684,7 @@ fn export_aac<P: AsRef<Path>>(
|
||||
stream.set_parameters(&encoder);
|
||||
}
|
||||
|
||||
apply_metadata(&mut output, &settings.metadata);
|
||||
output.write_header()
|
||||
.map_err(|e| format!("Failed to write header: {}", e))?;
|
||||
|
||||
@@ -575,6 +729,7 @@ fn export_aac<P: AsRef<Path>>(
|
||||
settings.sample_rate,
|
||||
settings.channels,
|
||||
false,
|
||||
None, // export never runs with a recording in flight
|
||||
);
|
||||
|
||||
// Calculate how many samples we need from this chunk
|
||||
@@ -671,14 +826,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
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -813,4 +993,61 @@ mod tests {
|
||||
assert_eq!(ExportFormat::Wav.extension(), "wav");
|
||||
assert_eq!(ExportFormat::Flac.extension(), "flac");
|
||||
}
|
||||
|
||||
fn tagged_settings(format: ExportFormat) -> ExportSettings {
|
||||
ExportSettings {
|
||||
format,
|
||||
sample_rate: 48000,
|
||||
channels: 2,
|
||||
bit_depth: 24,
|
||||
mp3_bitrate: 192,
|
||||
start_time: Seconds::ZERO,
|
||||
end_time: Seconds(0.2), // tiny render
|
||||
tempo_map: TempoMap::constant(120.0),
|
||||
metadata: vec![
|
||||
("title".to_string(), "Test Title".to_string()),
|
||||
("artist".to_string(), "Test Artist".to_string()),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
/// FLAC export must be a real FLAC container (not WAV bytes) carrying Vorbis-comment tags.
|
||||
#[test]
|
||||
fn flac_export_is_real_flac_with_tags() {
|
||||
let settings = tagged_settings(ExportFormat::Flac);
|
||||
let mut project = Project::new(48000);
|
||||
let pool = AudioPool::new();
|
||||
let path = std::env::temp_dir().join("lb_be_flac_test.flac");
|
||||
|
||||
export_audio(&mut project, &pool, &settings, &path, None).expect("FLAC export failed");
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
|
||||
assert_eq!(&bytes[0..4], b"fLaC", "not real FLAC (got {:?})", &bytes[0..4]);
|
||||
let s = String::from_utf8_lossy(&bytes);
|
||||
assert!(s.contains("Test Title"), "title tag missing from FLAC");
|
||||
assert!(s.contains("Test Artist"), "artist tag missing from FLAC");
|
||||
std::fs::remove_file(&path).ok();
|
||||
}
|
||||
|
||||
/// WAV export keeps a valid RIFF container and gains a LIST/INFO tag chunk with a fixed-up size.
|
||||
#[test]
|
||||
fn wav_export_has_info_chunk() {
|
||||
let settings = tagged_settings(ExportFormat::Wav);
|
||||
let mut project = Project::new(48000);
|
||||
let pool = AudioPool::new();
|
||||
let path = std::env::temp_dir().join("lb_be_wav_test.wav");
|
||||
|
||||
export_audio(&mut project, &pool, &settings, &path, None).expect("WAV export failed");
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
|
||||
assert_eq!(&bytes[0..4], b"RIFF");
|
||||
assert_eq!(&bytes[8..12], b"WAVE");
|
||||
let riff_size = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize;
|
||||
assert_eq!(riff_size, bytes.len() - 8, "RIFF size not fixed up after tagging");
|
||||
let s = String::from_utf8_lossy(&bytes);
|
||||
assert!(s.contains("LIST") && s.contains("INFO") && s.contains("INAM"),
|
||||
"no RIFF INFO chunk");
|
||||
assert!(s.contains("Test Title"), "title not in WAV INFO chunk");
|
||||
std::fs::remove_file(&path).ok();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+332
-34
@@ -4,6 +4,46 @@ 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
|
||||
#[inline]
|
||||
@@ -83,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
|
||||
@@ -98,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 {
|
||||
@@ -112,6 +166,7 @@ impl AudioFile {
|
||||
frames,
|
||||
original_format: None,
|
||||
original_bytes: None,
|
||||
packed_media_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -126,6 +181,7 @@ impl AudioFile {
|
||||
frames,
|
||||
original_format,
|
||||
original_bytes: None,
|
||||
packed_media_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,6 +214,7 @@ impl AudioFile {
|
||||
frames: total_frames,
|
||||
original_format: Some("wav".to_string()),
|
||||
original_bytes: None,
|
||||
packed_media_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -274,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
|
||||
}
|
||||
}
|
||||
@@ -491,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 {
|
||||
@@ -537,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.
|
||||
@@ -582,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)
|
||||
};
|
||||
@@ -606,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;
|
||||
@@ -786,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 {
|
||||
@@ -800,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();
|
||||
|
||||
@@ -830,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())
|
||||
@@ -839,6 +1051,7 @@ impl AudioClipPool {
|
||||
sample_rate: file.sample_rate,
|
||||
channels: file.channels,
|
||||
embedded_data,
|
||||
media_id: None,
|
||||
};
|
||||
|
||||
entries.push(entry);
|
||||
@@ -962,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) {
|
||||
|
||||
@@ -41,6 +41,11 @@ impl Project {
|
||||
}
|
||||
}
|
||||
|
||||
/// The project's system sample rate in Hz.
|
||||
pub fn sample_rate(&self) -> u32 {
|
||||
self.sample_rate
|
||||
}
|
||||
|
||||
/// Generate a new unique track ID
|
||||
fn next_id(&mut self) -> TrackId {
|
||||
let id = self.next_track_id;
|
||||
@@ -378,6 +383,7 @@ impl Project {
|
||||
sample_rate: u32,
|
||||
channels: u32,
|
||||
live_only: bool,
|
||||
recording_midi: Option<(TrackId, MidiClipId)>,
|
||||
) {
|
||||
output.fill(0.0);
|
||||
|
||||
@@ -386,6 +392,7 @@ impl Project {
|
||||
// Create initial render context
|
||||
let ctx = RenderContext {
|
||||
live_only,
|
||||
recording_midi,
|
||||
..RenderContext::new(playhead_seconds, tempo_map, sample_rate, channels, output.len())
|
||||
};
|
||||
|
||||
|
||||
@@ -5,6 +5,61 @@ use crate::time::{Beats, Seconds};
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Cycle-recording bookkeeping attached to a recording that started with a cycle region armed.
|
||||
///
|
||||
/// Takes are sliced **geometrically** at stop, in exact `loop_len_frames` multiples — not at the
|
||||
/// instant the wrap was detected. The playhead advances before the capture block in `process()`, so
|
||||
/// the wrap instant isn't sample-exact against the buffer that was just captured, but the geometry
|
||||
/// is. `wrap_count` therefore only decides *whether* this is a multi-take recording, never where the
|
||||
/// cuts land.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct CycleRecordInfo {
|
||||
/// Where the cycle region starts, in beats. Takes are laid down here, not at the punch-in point.
|
||||
pub loop_start: Beats,
|
||||
/// The cycle region's length in beats — what the take folder records as `recorded_loop_beats`.
|
||||
pub loop_len_beats: Beats,
|
||||
/// One cycle pass, in frames. The take size.
|
||||
pub loop_len_frames: usize,
|
||||
/// Frames between the region start and where capture actually began. Non-zero only for a
|
||||
/// punch-in (record while already rolling); take 1 gets this much silence prepended so it still
|
||||
/// spans the whole region.
|
||||
pub lead_pad_frames: usize,
|
||||
/// How many times the transport wrapped during this recording. Zero normally means the user
|
||||
/// stopped before completing a pass, which stays an ordinary single recording — unless
|
||||
/// `force_takes` says otherwise.
|
||||
pub wrap_count: usize,
|
||||
/// Cut takes even if the transport never wrapped.
|
||||
///
|
||||
/// Set when the region already holds takes: a further recording there is another take, however
|
||||
/// short, and it gets padded out to the region like any partial pass. Without this a run that
|
||||
/// stopped before the loop came round would land as a separate overlapping clip instead of
|
||||
/// joining the take list.
|
||||
///
|
||||
/// The editor decides this at record start, because whether takes already exist is document
|
||||
/// state the engine can't see.
|
||||
pub force_takes: bool,
|
||||
}
|
||||
|
||||
/// Min/max waveform peaks for a finished buffer of interleaved samples.
|
||||
///
|
||||
/// The live recording path builds its peaks incrementally as samples arrive; cycle takes don't
|
||||
/// exist until the recording is sliced at stop, so they get theirs in one pass here.
|
||||
pub fn compute_peaks(samples: &[f32], channels: u32, frames_per_peak: usize) -> Vec<WaveformPeak> {
|
||||
let samples_per_peak = (frames_per_peak * channels.max(1) as usize).max(1);
|
||||
samples
|
||||
.chunks(samples_per_peak)
|
||||
.map(|chunk| {
|
||||
let mut min = 0.0f32;
|
||||
let mut max = 0.0f32;
|
||||
for s in chunk {
|
||||
min = min.min(*s);
|
||||
max = max.max(*s);
|
||||
}
|
||||
WaveformPeak { min, max }
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// State of an active recording session
|
||||
pub struct RecordingState {
|
||||
/// Track being recorded to
|
||||
@@ -35,6 +90,8 @@ pub struct RecordingState {
|
||||
pub frames_per_peak: usize,
|
||||
/// All recorded audio data accumulated in memory (written to disk at finalization)
|
||||
pub audio_data: Vec<f32>,
|
||||
/// Cycle-recording bookkeeping, when a cycle region was armed at record start.
|
||||
pub cycle: Option<CycleRecordInfo>,
|
||||
}
|
||||
|
||||
impl RecordingState {
|
||||
@@ -69,9 +126,69 @@ impl RecordingState {
|
||||
waveform_buffer: Vec::new(),
|
||||
frames_per_peak,
|
||||
audio_data: Vec::new(),
|
||||
cycle: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Slice the recording into cycle takes: one per pass, each spanning the FULL cycle region.
|
||||
///
|
||||
/// Partial passes are padded with silence — the head of take 1 for a punch-in, the tail of the
|
||||
/// last take when the user stops mid-pass — so every take is the same length and aligned to the
|
||||
/// region. That uniformity is what makes comping-via-split work: take 1 on the left half and
|
||||
/// take 3 on the right always line up.
|
||||
///
|
||||
/// Returns `None` if this wasn't a cycle recording or the transport never wrapped (an ordinary
|
||||
/// single recording, which keeps the existing path untouched).
|
||||
pub fn slice_takes(&self) -> Option<Vec<Vec<f32>>> {
|
||||
let cycle = self.cycle?;
|
||||
if (cycle.wrap_count == 0 && !cycle.force_takes) || cycle.loop_len_frames == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let ch = self.channels.max(1) as usize;
|
||||
let take_len = cycle.loop_len_frames * ch;
|
||||
let lead = cycle.lead_pad_frames * ch;
|
||||
|
||||
// The recording as positioned *within the region*: silence for the gap between the region
|
||||
// start and the punch-in, then the captured audio. Slicing this at whole-take boundaries is
|
||||
// the whole trick — take 1 comes out short-by-`lead` at the front, already padded.
|
||||
let virtual_len = lead + self.audio_data.len();
|
||||
let take_count = virtual_len.div_ceil(take_len);
|
||||
|
||||
let mut takes: Vec<Vec<f32>> = Vec::with_capacity(take_count);
|
||||
for i in 0..take_count {
|
||||
let mut take = vec![0.0f32; take_len];
|
||||
let take_begin = i * take_len;
|
||||
for slot in 0..take_len {
|
||||
// Position in the virtual (lead-padded) buffer.
|
||||
let v = take_begin + slot;
|
||||
if v < lead {
|
||||
continue; // still in the punch-in silence
|
||||
}
|
||||
match self.audio_data.get(v - lead) {
|
||||
Some(s) => take[slot] = *s,
|
||||
None => break, // past the end of capture; the rest stays silent
|
||||
}
|
||||
}
|
||||
takes.push(take);
|
||||
}
|
||||
|
||||
// A final take holding only a sliver of real audio is a stop artifact (the user hit stop a
|
||||
// moment after the wrap), not a performance. Drop it — but only if it's actually a PARTIAL
|
||||
// pass, and never the only take. A pass that filled the region is a real take no matter how
|
||||
// short the region is.
|
||||
const MIN_TAKE_SECONDS: f64 = 0.05;
|
||||
if takes.len() > 1 {
|
||||
let last_real_samples = virtual_len - (takes.len() - 1) * take_len;
|
||||
let last_real_seconds = (last_real_samples / ch) as f64 / self.sample_rate as f64;
|
||||
if last_real_samples < take_len && last_real_seconds < MIN_TAKE_SECONDS {
|
||||
takes.pop();
|
||||
}
|
||||
}
|
||||
|
||||
Some(takes)
|
||||
}
|
||||
|
||||
/// Add samples to the accumulation buffer
|
||||
/// Returns true if a flush occurred
|
||||
pub fn add_samples(&mut self, samples: &[f32]) -> Result<bool, std::io::Error> {
|
||||
@@ -189,6 +306,26 @@ pub struct MidiRecordingState {
|
||||
active_notes: HashMap<u8, ActiveMidiNote>,
|
||||
/// Completed notes: (time_offset, note, velocity, duration) — all times in beats
|
||||
pub completed_notes: Vec<(Beats, u8, u8, Beats)>,
|
||||
/// The cycle region's length in beats, if one was armed at record start.
|
||||
///
|
||||
/// A cycle MIDI recording is anchored at the region start (`start_time == loop_start`), which is
|
||||
/// what makes MERGE fall out for free: the transport always wraps back into the region, so every
|
||||
/// note's offset already lands inside `[0, loop_len)` and successive passes overdub onto each
|
||||
/// other with no folding needed.
|
||||
pub cycle_loop_len: Option<Beats>,
|
||||
/// Whether the transport actually came round. Distinct from `cycle_loop_len`, which only says a
|
||||
/// region was armed: the clip only pins to the full region once a pass has completed, so until
|
||||
/// then the bar still grows with the playhead.
|
||||
pub wrapped: bool,
|
||||
/// Cut takes even if the transport never wrapped — see [`CycleRecordInfo::force_takes`].
|
||||
pub force_takes: bool,
|
||||
/// Which cycle pass is currently being recorded (0-based). Bumped at each wrap.
|
||||
current_pass: usize,
|
||||
/// The pass each completed note belongs to, parallel to `completed_notes`.
|
||||
///
|
||||
/// Only meaningful in "separate takes" mode, where each pass becomes its own MIDI clip. Merge
|
||||
/// mode ignores it — all passes fold into one clip, which is the whole point.
|
||||
note_pass: Vec<usize>,
|
||||
}
|
||||
|
||||
impl MidiRecordingState {
|
||||
@@ -199,9 +336,28 @@ impl MidiRecordingState {
|
||||
start_time,
|
||||
active_notes: HashMap::new(),
|
||||
completed_notes: Vec::new(),
|
||||
cycle_loop_len: None,
|
||||
wrapped: false,
|
||||
force_takes: false,
|
||||
current_pass: 0,
|
||||
note_pass: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Record a finished note, tagging it with the pass it was played in.
|
||||
///
|
||||
/// Every completion goes through here so `completed_notes` and `note_pass` can't drift apart.
|
||||
fn push_completed(&mut self, note: &ActiveMidiNote, end_time: Beats) {
|
||||
let note_start = note.start_time.max(self.start_time);
|
||||
self.completed_notes.push((
|
||||
note_start - self.start_time,
|
||||
note.note,
|
||||
note.velocity,
|
||||
end_time - note_start,
|
||||
));
|
||||
self.note_pass.push(self.current_pass);
|
||||
}
|
||||
|
||||
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 });
|
||||
}
|
||||
@@ -211,16 +367,38 @@ impl MidiRecordingState {
|
||||
if absolute_time <= self.start_time {
|
||||
return;
|
||||
}
|
||||
let note_start = active_note.start_time.max(self.start_time);
|
||||
self.completed_notes.push((
|
||||
note_start - self.start_time,
|
||||
active_note.note,
|
||||
active_note.velocity,
|
||||
absolute_time - note_start,
|
||||
));
|
||||
self.push_completed(&active_note, absolute_time);
|
||||
}
|
||||
}
|
||||
|
||||
/// Completed notes grouped by cycle pass — one bucket per pass, in recording order.
|
||||
///
|
||||
/// Used by "separate takes" mode, where each pass becomes its own MIDI clip.
|
||||
///
|
||||
/// An *interior* pass in which nothing was played still yields an empty take, so take N in the
|
||||
/// folder is always pass N on the transport — otherwise the numbering would silently shift and
|
||||
/// "take 3" would stop meaning "the third time round". A *trailing* empty pass is dropped
|
||||
/// though: that's what you get by hitting stop shortly after a wrap, and it's a stop artifact
|
||||
/// rather than a take you played. (Same reasoning as the audio path's short-final-take rule.)
|
||||
pub fn notes_by_pass(&self, passes: usize) -> Vec<Vec<(Beats, u8, u8, Beats)>> {
|
||||
let mut buckets = vec![Vec::new(); passes.max(1)];
|
||||
for (note, &pass) in self.completed_notes.iter().zip(self.note_pass.iter()) {
|
||||
if let Some(bucket) = buckets.get_mut(pass) {
|
||||
bucket.push(*note);
|
||||
}
|
||||
}
|
||||
// Never drop the only take.
|
||||
while buckets.len() > 1 && buckets.last().is_some_and(|b| b.is_empty()) {
|
||||
buckets.pop();
|
||||
}
|
||||
buckets
|
||||
}
|
||||
|
||||
/// How many cycle passes this recording covered (1 if the transport never wrapped).
|
||||
pub fn pass_count(&self) -> usize {
|
||||
self.current_pass + 1
|
||||
}
|
||||
|
||||
pub fn get_notes(&self) -> &[(Beats, u8, u8, Beats)] {
|
||||
&self.completed_notes
|
||||
}
|
||||
@@ -229,18 +407,28 @@ impl MidiRecordingState {
|
||||
self.completed_notes.len()
|
||||
}
|
||||
|
||||
/// The still-held notes, given a provisional duration running to `current_time`.
|
||||
///
|
||||
/// These belong to whatever pass is in progress, so a per-pass view can append them as-is.
|
||||
pub fn active_notes_with_provisional_end(&self, current_time: Beats) -> Vec<(Beats, u8, u8, Beats)> {
|
||||
self.active_notes
|
||||
.values()
|
||||
.map(|active| {
|
||||
let note_start = active.start_time.max(self.start_time);
|
||||
(
|
||||
note_start - self.start_time,
|
||||
active.note,
|
||||
active.velocity,
|
||||
(current_time - note_start).max(Beats::ZERO),
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Get all completed notes plus currently-held notes with a provisional duration.
|
||||
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);
|
||||
notes.push((
|
||||
note_start - self.start_time,
|
||||
active.note,
|
||||
active.velocity,
|
||||
(current_time - note_start).max(Beats::ZERO),
|
||||
));
|
||||
}
|
||||
notes.extend(self.active_notes_with_provisional_end(current_time));
|
||||
notes
|
||||
}
|
||||
|
||||
@@ -252,13 +440,259 @@ impl MidiRecordingState {
|
||||
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);
|
||||
self.completed_notes.push((
|
||||
note_start - self.start_time,
|
||||
active_note.note,
|
||||
active_note.velocity,
|
||||
end_time - note_start,
|
||||
));
|
||||
self.push_completed(&active_note, end_time);
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle a transport cycle wrap during MIDI recording.
|
||||
///
|
||||
/// Note times are stored as offsets from `start_time`, and the playhead jumps *backwards* at a
|
||||
/// wrap — so a note still held across the boundary would otherwise get a nonsensical (negative)
|
||||
/// duration, or never be closed at all. Write its note-off at `region_end` (exactly as
|
||||
/// `close_active_notes` does when recording stops), then re-open it at `region_start` so a key
|
||||
/// the player is still physically holding keeps being captured in the next pass. Mirrors the
|
||||
/// way `handle_start_midi_recording` re-injects already-held notes at the recording start.
|
||||
pub fn wrap_at_cycle(&mut self, region_end: Beats, region_start: Beats) {
|
||||
// Snapshot the held notes (close_active_notes drains them and loses the velocities).
|
||||
let held: Vec<(u8, u8)> = self
|
||||
.active_notes
|
||||
.values()
|
||||
.map(|n| (n.note, n.velocity))
|
||||
.collect();
|
||||
|
||||
// Close first, so a note held across the boundary has its tail attributed to the pass that's
|
||||
// ending; then advance, so the re-opened half belongs to the pass that's beginning.
|
||||
self.close_active_notes(region_end);
|
||||
self.current_pass += 1;
|
||||
|
||||
for (note, velocity) in held {
|
||||
self.note_on(note, velocity, region_start);
|
||||
}
|
||||
|
||||
// A pass has completed, so from here the clip spans the whole region rather than however long
|
||||
// the user happens to hold the record button.
|
||||
self.cycle_loop_len = Some(region_end - region_start);
|
||||
self.wrapped = true;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod cycle_tests {
|
||||
use super::*;
|
||||
|
||||
/// A recording state holding `audio_data`, armed for cycle recording. Mono, 100 Hz, so a frame
|
||||
/// is a sample and 5 frames is 50 ms (exactly the min-take threshold).
|
||||
fn rec_forced(audio: Vec<f32>, loop_len_frames: usize, lead_pad_frames: usize, wraps: usize) -> RecordingState {
|
||||
let mut r = rec(audio, loop_len_frames, lead_pad_frames, wraps);
|
||||
if let Some(c) = r.cycle.as_mut() {
|
||||
c.force_takes = true;
|
||||
}
|
||||
r
|
||||
}
|
||||
|
||||
fn rec(audio: Vec<f32>, loop_len_frames: usize, lead_pad_frames: usize, wraps: usize) -> RecordingState {
|
||||
let mut r = RecordingState::new(
|
||||
0,
|
||||
0,
|
||||
PathBuf::from("/dev/null"),
|
||||
WavWriter::create(&PathBuf::from("/dev/null"), 100, 1).expect("wav writer"),
|
||||
100,
|
||||
1,
|
||||
Beats(0.0),
|
||||
1.0,
|
||||
);
|
||||
r.audio_data = audio;
|
||||
r.cycle = Some(CycleRecordInfo {
|
||||
loop_start: Beats(0.0),
|
||||
loop_len_beats: Beats(4.0),
|
||||
loop_len_frames,
|
||||
lead_pad_frames,
|
||||
wrap_count: wraps,
|
||||
force_takes: false,
|
||||
});
|
||||
r
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_wrap_is_not_a_cycle_recording() {
|
||||
// Stopping before the transport ever wraps stays an ordinary single recording — the whole
|
||||
// point of triggering on the wrap rather than on the cycle region merely existing.
|
||||
let r = rec(vec![1.0; 10], 4, 0, 0);
|
||||
assert!(r.slice_takes().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn force_takes_makes_a_partial_pass_a_take() {
|
||||
// Recording over a region that already holds takes: this run is another take however short
|
||||
// it ran, so it's cut and padded like any partial pass rather than landing as a separate
|
||||
// overlapping clip. Two real frames of an 8-frame region -> one take, silence for the rest.
|
||||
let takes = rec_forced(vec![1.0, 2.0], 8, 0, 0)
|
||||
.slice_takes()
|
||||
.expect("forced takes");
|
||||
assert_eq!(takes.len(), 1);
|
||||
assert_eq!(takes[0], vec![1.0, 2.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn takes_are_cut_at_exact_loop_multiples() {
|
||||
// 12 frames of audio, 4-frame loop, started at the region start => 3 clean takes.
|
||||
let audio: Vec<f32> = (1..=12).map(|i| i as f32).collect();
|
||||
let takes = rec(audio, 4, 0, 2).slice_takes().expect("cycle takes");
|
||||
assert_eq!(takes.len(), 3);
|
||||
assert_eq!(takes[0], vec![1.0, 2.0, 3.0, 4.0]);
|
||||
assert_eq!(takes[1], vec![5.0, 6.0, 7.0, 8.0]);
|
||||
assert_eq!(takes[2], vec![9.0, 10.0, 11.0, 12.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn punch_in_pads_the_head_of_take_one() {
|
||||
// Punched in 2 frames into the region: take 1 gets 2 frames of silence at the FRONT so it
|
||||
// still spans the whole region and lines up with every other take.
|
||||
let audio: Vec<f32> = (1..=10).map(|i| i as f32).collect();
|
||||
let takes = rec(audio, 4, 2, 2).slice_takes().expect("cycle takes");
|
||||
assert_eq!(takes.len(), 3);
|
||||
assert_eq!(takes[0], vec![0.0, 0.0, 1.0, 2.0]);
|
||||
assert_eq!(takes[1], vec![3.0, 4.0, 5.0, 6.0]);
|
||||
assert_eq!(takes[2], vec![7.0, 8.0, 9.0, 10.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stopping_mid_pass_pads_the_tail_of_the_last_take() {
|
||||
// 13 frames, 8-frame loop => the second take holds 5 real frames (50 ms at 100 Hz, right at
|
||||
// the keep threshold) and 3 of silence.
|
||||
let audio: Vec<f32> = (1..=13).map(|i| i as f32).collect();
|
||||
let takes = rec(audio, 8, 0, 1).slice_takes().expect("cycle takes");
|
||||
assert_eq!(takes.len(), 2);
|
||||
assert_eq!(takes[1], vec![9.0, 10.0, 11.0, 12.0, 13.0, 0.0, 0.0, 0.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_take_is_the_same_length() {
|
||||
// Uniform length is the invariant comping-via-split depends on.
|
||||
let audio: Vec<f32> = (1..=23).map(|i| i as f32).collect();
|
||||
let takes = rec(audio, 8, 3, 3).slice_takes().expect("cycle takes");
|
||||
assert!(takes.iter().all(|t| t.len() == 8), "takes must be uniform");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sliver_of_a_final_take_is_dropped() {
|
||||
// Stopped 1 frame (10 ms at 100 Hz) after the wrap — below the 50 ms floor, so that stub of
|
||||
// a take is a stop artifact and goes.
|
||||
let audio: Vec<f32> = (1..=9).map(|i| i as f32).collect();
|
||||
let takes = rec(audio, 8, 0, 1).slice_takes().expect("cycle takes");
|
||||
assert_eq!(takes.len(), 1, "a 10ms tail take should be dropped");
|
||||
assert_eq!(takes[0].len(), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_final_take_is_never_dropped() {
|
||||
// Regression: the sliver rule must only fire on a PARTIAL pass. A pass that filled the
|
||||
// region is a real take however short the region is — an earlier version compared a full
|
||||
// take's duration to the floor and silently ate it.
|
||||
let audio: Vec<f32> = (1..=8).map(|i| i as f32).collect();
|
||||
let takes = rec(audio, 4, 0, 1).slice_takes().expect("cycle takes");
|
||||
assert_eq!(takes.len(), 2, "both passes filled the region");
|
||||
assert_eq!(takes[1], vec![5.0, 6.0, 7.0, 8.0]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod midi_cycle_tests {
|
||||
use super::*;
|
||||
|
||||
/// A MIDI recording anchored at the region start (beat 0), region 4 beats long.
|
||||
fn rec() -> MidiRecordingState {
|
||||
MidiRecordingState::new(0, 0, Beats(0.0))
|
||||
}
|
||||
|
||||
/// One pass of the transport around a 4-beat region.
|
||||
fn wrap(r: &mut MidiRecordingState) {
|
||||
r.wrap_at_cycle(Beats(4.0), Beats(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn notes_are_bucketed_by_the_pass_they_were_played_in() {
|
||||
let mut r = rec();
|
||||
r.note_on(60, 100, Beats(1.0));
|
||||
r.note_off(60, Beats(2.0)); // pass 0
|
||||
wrap(&mut r);
|
||||
r.note_on(62, 100, Beats(1.0));
|
||||
r.note_off(62, Beats(2.0)); // pass 1
|
||||
wrap(&mut r);
|
||||
r.note_on(64, 100, Beats(1.0));
|
||||
r.note_off(64, Beats(2.0)); // pass 2
|
||||
|
||||
assert_eq!(r.pass_count(), 3);
|
||||
let by_pass = r.notes_by_pass(r.pass_count());
|
||||
let pitches: Vec<Vec<u8>> = by_pass
|
||||
.iter()
|
||||
.map(|p| p.iter().map(|n| n.1).collect())
|
||||
.collect();
|
||||
assert_eq!(pitches, vec![vec![60], vec![62], vec![64]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_note_held_across_a_wrap_splits_between_the_two_passes() {
|
||||
// The key is still down at the boundary: the sounding half belongs to the pass that's
|
||||
// ending, and the re-opened half to the pass that's beginning. Getting the pass bump on the
|
||||
// wrong side of close_active_notes would file the whole note under one pass.
|
||||
let mut r = rec();
|
||||
r.note_on(60, 100, Beats(3.0));
|
||||
wrap(&mut r); // still held
|
||||
r.note_off(60, Beats(1.0)); // released 1 beat into the next pass
|
||||
|
||||
assert_eq!(r.pass_count(), 2);
|
||||
let by_pass = r.notes_by_pass(r.pass_count());
|
||||
assert_eq!(by_pass[0].len(), 1, "the held half lands in the pass that ended");
|
||||
assert_eq!(by_pass[1].len(), 1, "the re-opened half lands in the next pass");
|
||||
// Pass 0's half runs from beat 3 to the region end at 4.
|
||||
assert_eq!(by_pass[0][0].0, Beats(3.0));
|
||||
assert_eq!(by_pass[0][0].3, Beats(1.0));
|
||||
// Pass 1's half starts at the region start and runs to the release.
|
||||
assert_eq!(by_pass[1][0].0, Beats(0.0));
|
||||
assert_eq!(by_pass[1][0].3, Beats(1.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_silent_interior_pass_still_yields_an_empty_take() {
|
||||
// Take N in the folder must be pass N on the transport, even if nothing was played — else
|
||||
// the take numbering silently shifts under the user.
|
||||
let mut r = rec();
|
||||
r.note_on(60, 100, Beats(1.0));
|
||||
r.note_off(60, Beats(2.0)); // pass 0
|
||||
wrap(&mut r);
|
||||
wrap(&mut r); // pass 1: played nothing
|
||||
r.note_on(64, 100, Beats(1.0));
|
||||
r.note_off(64, Beats(2.0)); // pass 2
|
||||
|
||||
let by_pass = r.notes_by_pass(r.pass_count());
|
||||
assert_eq!(by_pass.len(), 3);
|
||||
assert_eq!(by_pass[1].len(), 0, "the silent pass is still take 2");
|
||||
assert_eq!(by_pass[2][0].1, 64);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_trailing_empty_pass_is_dropped() {
|
||||
// Hitting stop shortly after a wrap leaves a pass you never played into. That's a stop
|
||||
// artifact, not a take — unlike a silent pass in the middle, which was a deliberate rest.
|
||||
let mut r = rec();
|
||||
r.note_on(60, 100, Beats(1.0));
|
||||
r.note_off(60, Beats(2.0)); // pass 0
|
||||
wrap(&mut r);
|
||||
r.note_on(62, 100, Beats(1.0));
|
||||
r.note_off(62, Beats(2.0)); // pass 1
|
||||
wrap(&mut r); // pass 2 begins... and the user hits stop
|
||||
|
||||
assert_eq!(r.pass_count(), 3);
|
||||
let by_pass = r.notes_by_pass(r.pass_count());
|
||||
assert_eq!(by_pass.len(), 2, "the empty trailing pass is not a take");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_recording_still_yields_one_take() {
|
||||
let mut r = rec();
|
||||
wrap(&mut r);
|
||||
wrap(&mut r);
|
||||
assert_eq!(r.notes_by_pass(r.pass_count()).len(), 1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::automation::{AutomationLane, AutomationLaneId, ParameterId};
|
||||
use super::clip::{AudioClipInstance, AudioClipInstanceId};
|
||||
use super::midi::{MidiClipInstance, MidiClipInstanceId, MidiEvent};
|
||||
use super::midi::{MidiClipId, MidiClipInstance, MidiClipInstanceId, MidiEvent};
|
||||
use super::midi_pool::MidiClipPool;
|
||||
use super::node_graph::AudioGraph;
|
||||
use super::node_graph::nodes::{AudioInputNode, AudioOutputNode};
|
||||
@@ -43,6 +43,13 @@ pub struct RenderContext<'a> {
|
||||
/// Used after pause/stop to route note-off tails through the normal group hierarchy
|
||||
/// without re-triggering notes from clips at the paused position.
|
||||
pub live_only: bool,
|
||||
/// The MIDI recording in progress, if any: (track being recorded to, clip being recorded into).
|
||||
///
|
||||
/// On that track, every OTHER clip is silenced for the duration of the recording. You're playing
|
||||
/// a part into this region — hearing what's already there (a previous take, say) fighting with
|
||||
/// what you're playing now is just noise. The clip being recorded into is exempt, because in
|
||||
/// merge mode that's exactly what you DO want to hear: the overdub you've been building up.
|
||||
pub recording_midi: Option<(TrackId, MidiClipId)>,
|
||||
}
|
||||
|
||||
impl<'a> RenderContext<'a> {
|
||||
@@ -61,6 +68,7 @@ impl<'a> RenderContext<'a> {
|
||||
buffer_size,
|
||||
time_stretch: 1.0,
|
||||
live_only: false,
|
||||
recording_midi: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -864,9 +872,21 @@ impl MidiTrack {
|
||||
let playhead_beats = ctx.playhead_beats();
|
||||
let buffer_end_beats = ctx.buffer_end_beats();
|
||||
|
||||
// While recording into this track, every clip EXCEPT the one being recorded into is
|
||||
// silenced. Otherwise a take folder already sitting in the cycle region would play its
|
||||
// active take underneath you on every pass, fighting the part you're trying to record.
|
||||
// The recording clip itself is exempt: in merge mode that's the overdub monitoring.
|
||||
let muted_clip = match ctx.recording_midi {
|
||||
Some((track_id, clip_id)) if track_id == self.id => Some(clip_id),
|
||||
_ => None,
|
||||
};
|
||||
|
||||
// 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 muted_clip.is_some_and(|recording| instance.clip_id != recording) {
|
||||
continue;
|
||||
}
|
||||
if instance.overlaps_range(playhead_beats, buffer_end_beats) {
|
||||
currently_active.insert(instance.id);
|
||||
}
|
||||
|
||||
@@ -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).
|
||||
@@ -1,3 +1,3 @@
|
||||
pub mod types;
|
||||
|
||||
pub use types::{AudioEvent, Command, MidiClipData, OscilloscopeData, Query, QueryResponse};
|
||||
pub use types::{AudioEvent, Command, MidiClipData, OscilloscopeData, Query, QueryResponse, TrimRange};
|
||||
|
||||
@@ -8,6 +8,21 @@ use crate::audio::node_graph::nodes::LoopMode;
|
||||
use crate::io::WaveformPeak;
|
||||
use crate::time::{Beats, Seconds};
|
||||
|
||||
/// A clip's internal (content) boundaries, tagged with the domain they're measured in.
|
||||
///
|
||||
/// A clip's content time is SECONDS for sampled audio but BEATS for MIDI — the same polymorphism
|
||||
/// `ClipInstance::trim_start`/`trim_end` carry. Passing these as bare `f64`s meant the caller and
|
||||
/// the engine could disagree about the unit with nothing to catch it: an audio trim of "1.0" was
|
||||
/// once stored as `Beats(1.0)` for the clip's external duration, so a 1-second split played back as
|
||||
/// half a second at 120 BPM. Tagging the domain makes that a type error instead of a bug report.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum TrimRange {
|
||||
/// Sampled-audio content time.
|
||||
Seconds { start: Seconds, end: Seconds },
|
||||
/// MIDI content time.
|
||||
Beats { start: Beats, end: Beats },
|
||||
}
|
||||
|
||||
/// Commands sent from UI/control thread to audio thread
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Command {
|
||||
@@ -19,7 +34,7 @@ pub enum Command {
|
||||
/// Pause playback (maintains position)
|
||||
Pause,
|
||||
/// Seek to a specific position in seconds
|
||||
Seek(f64),
|
||||
Seek(Seconds),
|
||||
|
||||
// Track management commands
|
||||
/// Set track volume (0.0 = silence, 1.0 = unity gain)
|
||||
@@ -31,13 +46,12 @@ pub enum Command {
|
||||
|
||||
// Clip management commands
|
||||
/// Move a clip to a new timeline position (track_id, clip_id, new_external_start)
|
||||
MoveClip(TrackId, ClipId, f64),
|
||||
/// Trim a clip's internal boundaries (track_id, clip_id, new_internal_start, new_internal_end)
|
||||
/// This changes which portion of the source content is used
|
||||
TrimClip(TrackId, ClipId, f64, f64),
|
||||
MoveClip(TrackId, ClipId, Beats),
|
||||
/// Trim a clip's internal boundaries — which portion of the source content is used.
|
||||
TrimClip(TrackId, ClipId, TrimRange),
|
||||
/// Extend/shrink a clip's external duration (track_id, clip_id, new_external_duration)
|
||||
/// If duration > internal duration, the clip will loop
|
||||
ExtendClip(TrackId, ClipId, f64),
|
||||
ExtendClip(TrackId, ClipId, Beats),
|
||||
|
||||
// Metatrack management commands
|
||||
/// Create a new metatrack with a name and optional parent group
|
||||
@@ -53,15 +67,15 @@ pub enum Command {
|
||||
SetTimeStretch(TrackId, f32),
|
||||
/// Set metatrack time offset in seconds (track_id, offset)
|
||||
/// Positive = shift content later, negative = shift earlier
|
||||
SetOffset(TrackId, f64),
|
||||
SetOffset(TrackId, Seconds),
|
||||
/// Set metatrack pitch shift in semitones (track_id, semitones) - for future use
|
||||
SetPitchShift(TrackId, f32),
|
||||
/// Set metatrack trim start in seconds (track_id, trim_start)
|
||||
/// Children won't hear content before this point
|
||||
SetTrimStart(TrackId, f64),
|
||||
SetTrimStart(TrackId, Seconds),
|
||||
/// Set metatrack trim end in seconds (track_id, trim_end)
|
||||
/// None means no end trim
|
||||
SetTrimEnd(TrackId, Option<f64>),
|
||||
SetTrimEnd(TrackId, Option<Seconds>),
|
||||
|
||||
// Audio track commands
|
||||
/// Create a new audio track with a name and optional parent group
|
||||
@@ -71,7 +85,8 @@ pub enum Command {
|
||||
AddAudioFile(String, Vec<f32>, u32, u32),
|
||||
/// Add a clip to an audio track (track_id, clip_id, pool_index, start_time, duration, offset)
|
||||
/// The clip_id is pre-assigned by the caller (via EngineController::next_audio_clip_id())
|
||||
AddAudioClip(TrackId, AudioClipInstanceId, usize, f64, f64, f64),
|
||||
/// (track, clip_id, pool_index, start_time [beats], duration [beats], offset [seconds])
|
||||
AddAudioClip(TrackId, AudioClipInstanceId, usize, Beats, Beats, Seconds),
|
||||
|
||||
// MIDI commands
|
||||
/// Create a new MIDI track with a name and optional parent group
|
||||
@@ -79,14 +94,14 @@ pub enum Command {
|
||||
/// Add a MIDI clip to the pool without placing it on a track
|
||||
AddMidiClipToPool(MidiClip),
|
||||
/// Create a new MIDI clip on a track (track_id, start_time, duration)
|
||||
CreateMidiClip(TrackId, f64, f64),
|
||||
CreateMidiClip(TrackId, Beats, Beats),
|
||||
/// Add a MIDI note to a clip (track_id, clip_id, time_offset, note, velocity, duration)
|
||||
AddMidiNote(TrackId, MidiClipId, f64, u8, u8, f64),
|
||||
AddMidiNote(TrackId, MidiClipId, Beats, u8, u8, Beats),
|
||||
/// Add a pre-loaded MIDI clip to a track (track_id, clip, start_time)
|
||||
AddLoadedMidiClip(TrackId, MidiClip, f64),
|
||||
AddLoadedMidiClip(TrackId, MidiClip, Beats),
|
||||
/// Update MIDI clip notes (track_id, clip_id, notes: Vec<(start_time, note, velocity, duration)>)
|
||||
/// NOTE: May need to switch to individual note operations if this becomes slow on clips with many notes
|
||||
UpdateMidiClipNotes(TrackId, MidiClipId, Vec<(f64, u8, u8, f64)>),
|
||||
UpdateMidiClipNotes(TrackId, MidiClipId, Vec<(Beats, u8, u8, Beats)>),
|
||||
/// Replace all events in a MIDI clip (track_id, clip_id, events). Used for CC/pitch bend editing.
|
||||
UpdateMidiClipEvents(TrackId, MidiClipId, Vec<MidiEvent>),
|
||||
/// Remove a MIDI clip instance from a track (track_id, instance_id) - for undo/redo support
|
||||
@@ -102,9 +117,9 @@ pub enum Command {
|
||||
/// Create a new automation lane on a track (track_id, parameter_id)
|
||||
CreateAutomationLane(TrackId, ParameterId),
|
||||
/// Add an automation point to a lane (track_id, lane_id, time, value, curve)
|
||||
AddAutomationPoint(TrackId, AutomationLaneId, f64, f32, CurveType),
|
||||
AddAutomationPoint(TrackId, AutomationLaneId, Beats, f32, CurveType),
|
||||
/// Remove an automation point at a specific time (track_id, lane_id, time, tolerance)
|
||||
RemoveAutomationPoint(TrackId, AutomationLaneId, f64, f64),
|
||||
RemoveAutomationPoint(TrackId, AutomationLaneId, Beats, Beats),
|
||||
/// Clear all automation points from a lane (track_id, lane_id)
|
||||
ClearAutomationLane(TrackId, AutomationLaneId),
|
||||
/// Remove an automation lane (track_id, lane_id)
|
||||
@@ -112,9 +127,24 @@ pub enum Command {
|
||||
/// Enable/disable an automation lane (track_id, lane_id, enabled)
|
||||
SetAutomationLaneEnabled(TrackId, AutomationLaneId, bool),
|
||||
|
||||
// Transport cycle (loop) region
|
||||
/// Set the cycle region the transport loops over, in beats (None clears it).
|
||||
/// Authored in beats so it survives tempo changes.
|
||||
SetLoopRegion(Option<(Beats, Beats)>),
|
||||
/// Enable/disable wrapping at the cycle region's end.
|
||||
SetLoopEnabled(bool),
|
||||
/// How a cycle MIDI recording treats its passes.
|
||||
///
|
||||
/// `false` (default) = MERGE: every pass overdubs into one clip. `true` = SEPARATE TAKES: each
|
||||
/// pass becomes its own MIDI clip, and the editor folds them into a take folder — the same shape
|
||||
/// audio always gets.
|
||||
SetCycleMidiSeparateTakes(bool),
|
||||
|
||||
// Recording commands
|
||||
/// Start recording on a track (track_id, start_time)
|
||||
StartRecording(TrackId, Beats),
|
||||
/// (track, start_time, force_takes — cut takes even if the transport never wraps, because the
|
||||
/// region already holds takes and this is another one)
|
||||
StartRecording(TrackId, Beats, bool),
|
||||
/// Stop the current recording
|
||||
StopRecording,
|
||||
/// Pause the current recording
|
||||
@@ -124,7 +154,8 @@ pub enum Command {
|
||||
|
||||
// MIDI Recording commands
|
||||
/// Start MIDI recording on a track (track_id, clip_id, start_time)
|
||||
StartMidiRecording(TrackId, MidiClipId, Beats),
|
||||
/// (track, clip, start_time, force_takes — see [`Command::StartRecording`])
|
||||
StartMidiRecording(TrackId, MidiClipId, Beats, bool),
|
||||
/// Stop the current MIDI recording
|
||||
StopMidiRecording,
|
||||
|
||||
@@ -236,9 +267,9 @@ pub enum Command {
|
||||
|
||||
// Automation Input Node commands
|
||||
/// Add or update a keyframe on an AutomationInput node (track_id, node_id, time, value, interpolation, ease_out, ease_in)
|
||||
AutomationAddKeyframe(TrackId, u32, f64, f32, String, (f32, f32), (f32, f32)),
|
||||
AutomationAddKeyframe(TrackId, u32, Beats, f32, String, (f32, f32), (f32, f32)),
|
||||
/// Remove a keyframe from an AutomationInput node (track_id, node_id, time)
|
||||
AutomationRemoveKeyframe(TrackId, u32, f64),
|
||||
AutomationRemoveKeyframe(TrackId, u32, Beats),
|
||||
/// Set the display name of an AutomationInput node (track_id, node_id, name)
|
||||
AutomationSetName(TrackId, u32, String),
|
||||
|
||||
@@ -270,7 +301,7 @@ pub enum Command {
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum AudioEvent {
|
||||
/// Current playback position in seconds
|
||||
PlaybackPosition(f64),
|
||||
PlaybackPosition(Seconds),
|
||||
/// Playback has stopped (reached end of audio)
|
||||
PlaybackStopped,
|
||||
/// Audio buffer underrun detected
|
||||
@@ -291,6 +322,35 @@ pub enum AudioEvent {
|
||||
RecordingProgress(ClipId, Seconds),
|
||||
/// Recording stopped (clip_id, pool_index, waveform)
|
||||
RecordingStopped(ClipId, usize, Vec<WaveformPeak>),
|
||||
/// A MIDI recording that wrapped the cycle region at least once, in SEPARATE TAKES mode.
|
||||
///
|
||||
/// One MIDI clip per pass, in recording order. (Merge mode emits the ordinary
|
||||
/// `MidiRecordingStopped` instead — all passes are already folded into the one clip.)
|
||||
MidiCycleRecordingStopped {
|
||||
track_id: TrackId,
|
||||
/// One pool MIDI clip per pass. The first is the clip the recording started on.
|
||||
clip_ids: Vec<MidiClipId>,
|
||||
/// Where the takes sit on the timeline — the cycle region's start.
|
||||
loop_start: Beats,
|
||||
/// The region's length in beats: every take spans exactly this.
|
||||
loop_len_beats: Beats,
|
||||
},
|
||||
/// A recording that wrapped the cycle region at least once, and so became multi-take.
|
||||
///
|
||||
/// Each take spans the full region and they're all the same length (partial passes are padded
|
||||
/// with silence), so the editor can promote the recording clip straight to a take folder.
|
||||
CycleRecordingStopped {
|
||||
clip_id: ClipId,
|
||||
/// One entry per pass: (audio pool index, waveform peaks), in recording order.
|
||||
takes: Vec<(usize, Vec<WaveformPeak>)>,
|
||||
/// Where the takes sit on the timeline — the cycle region's start, not the punch-in point.
|
||||
loop_start: Beats,
|
||||
/// The region's length in beats (what the take folder stores as `recorded_loop_beats`).
|
||||
loop_len_beats: Beats,
|
||||
/// The same length in seconds — the take folder's content duration, which is seconds-domain
|
||||
/// for audio.
|
||||
loop_len_seconds: Seconds,
|
||||
},
|
||||
/// Recording error (error_message)
|
||||
RecordingError(String),
|
||||
/// MIDI recording stopped (track_id, clip_id, note_count)
|
||||
@@ -341,7 +401,7 @@ pub enum AudioEvent {
|
||||
WaveformChunksReady {
|
||||
pool_index: usize,
|
||||
detail_level: u8,
|
||||
chunks: Vec<(u32, (f64, f64), Vec<WaveformPeak>)>,
|
||||
chunks: Vec<(u32, (Seconds, Seconds), Vec<WaveformPeak>)>,
|
||||
},
|
||||
|
||||
/// An audio file has been imported and is ready for playback.
|
||||
@@ -352,7 +412,7 @@ pub enum AudioEvent {
|
||||
path: String,
|
||||
channels: u32,
|
||||
sample_rate: u32,
|
||||
duration: f64,
|
||||
duration: Seconds,
|
||||
format: crate::io::audio_file::AudioFormat,
|
||||
},
|
||||
|
||||
@@ -426,12 +486,10 @@ pub enum Query {
|
||||
/// Export audio to file (settings, output_path)
|
||||
ExportAudio(crate::audio::ExportSettings, std::path::PathBuf),
|
||||
/// Add a MIDI clip to a track synchronously (track_id, clip, start_time) - returns instance ID
|
||||
AddMidiClipSync(TrackId, crate::audio::midi::MidiClip, f64),
|
||||
AddMidiClipSync(TrackId, crate::audio::midi::MidiClip, Beats),
|
||||
/// 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.
|
||||
@@ -440,12 +498,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
|
||||
@@ -465,16 +531,21 @@ pub struct OscilloscopeData {
|
||||
}
|
||||
|
||||
/// MIDI clip data for serialization
|
||||
///
|
||||
/// `Beats`/`Seconds` are `#[serde(transparent)]`, so naming the domain here costs nothing on disk —
|
||||
/// the `.beam` still holds a plain number.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct MidiClipData {
|
||||
pub duration: f64,
|
||||
/// MIDI content length is musical, so beats.
|
||||
pub duration: Beats,
|
||||
pub events: Vec<crate::audio::midi::MidiEvent>,
|
||||
}
|
||||
|
||||
/// Automation keyframe data for serialization
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
|
||||
pub struct AutomationKeyframeData {
|
||||
pub time: f64,
|
||||
/// Automation x-axes are all beats.
|
||||
pub time: Beats,
|
||||
pub value: f32,
|
||||
pub interpolation: String,
|
||||
pub ease_out: (f32, f32),
|
||||
@@ -511,15 +582,15 @@ pub enum QueryResponse {
|
||||
/// Pool waveform data
|
||||
PoolWaveform(Result<Vec<crate::io::WaveformPeak>, String>),
|
||||
/// Pool file info (duration, sample_rate, channels)
|
||||
PoolFileInfo(Result<(f64, u32, u32), String>),
|
||||
PoolFileInfo(Result<(Seconds, u32, u32), String>),
|
||||
/// Audio exported
|
||||
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;
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ pub use audio::{
|
||||
TrackNode,
|
||||
};
|
||||
pub use audio::node_graph::{GraphPreset, AudioGraph, PresetMetadata, SerializedConnection, SerializedNode};
|
||||
pub use time::{Beats, Seconds};
|
||||
pub use time::{Beats, ContentTime, 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;
|
||||
|
||||
@@ -16,6 +16,50 @@ pub struct Beats(pub f64);
|
||||
#[serde(transparent)]
|
||||
pub struct Seconds(pub f64);
|
||||
|
||||
/// A time *inside a clip's own content*, in whatever unit that clip measures content in.
|
||||
///
|
||||
/// Clip content time is domain-polymorphic: SECONDS for sampled audio, video and vector, but BEATS
|
||||
/// for MIDI (musical, so it survives tempo changes). `ClipInstance::trim_start`/`trim_end` are
|
||||
/// content times, and storing them as bare `f64`s is what let a seconds delta get added to a MIDI
|
||||
/// clip's beats trim — splitting a MIDI clip at beat 4 landed at beat 2 at 120 BPM.
|
||||
///
|
||||
/// This type is deliberately a **dead end**: it has no `.to_seconds()`, no `.to_beats()`, and no
|
||||
/// arithmetic with `Seconds` or `Beats`. Content times can be compared and combined with each other
|
||||
/// (that's domain-safe — both operands are in the same clip's domain), but the only way to get a
|
||||
/// real timeline duration out is to resolve it against the clip that knows the domain, via
|
||||
/// `AudioClip::resolve_content_time` / `Document::resolve_content_time`. So a passthrough costs
|
||||
/// nothing, and mixing domains won't compile.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Default, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct ContentTime(pub f64);
|
||||
|
||||
impl ContentTime {
|
||||
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)) }
|
||||
|
||||
/// The raw magnitude, with the domain discarded.
|
||||
///
|
||||
/// Only for code that is *already* working in this clip's content domain (trim arithmetic,
|
||||
/// serialization, drawing a waveform whose x-axis is the clip's own content). If you are about
|
||||
/// to combine this with a timeline position, resolve it against the clip instead.
|
||||
pub fn raw(self) -> f64 { self.0 }
|
||||
}
|
||||
|
||||
impl Add for ContentTime {
|
||||
type Output = Self;
|
||||
fn add(self, rhs: Self) -> Self { Self(self.0 + rhs.0) }
|
||||
}
|
||||
impl Sub for ContentTime {
|
||||
type Output = Self;
|
||||
fn sub(self, rhs: Self) -> Self { Self(self.0 - rhs.0) }
|
||||
}
|
||||
impl Rem for ContentTime {
|
||||
type Output = Self;
|
||||
fn rem(self, rhs: Self) -> Self { Self(self.0 % rhs.0) }
|
||||
}
|
||||
|
||||
impl Beats {
|
||||
pub const ZERO: Self = Self(0.0);
|
||||
|
||||
|
||||
@@ -556,7 +556,7 @@ pub fn run_tui(
|
||||
while let Ok(event) = rx.pop() {
|
||||
match event {
|
||||
AudioEvent::PlaybackPosition(pos) => {
|
||||
app.update_playback_position(pos);
|
||||
app.update_playback_position(pos.seconds_to_f64());
|
||||
}
|
||||
AudioEvent::PlaybackStopped => {
|
||||
app.set_playing(false);
|
||||
@@ -790,7 +790,7 @@ fn execute_command(
|
||||
return Err("Usage: seek <seconds>".to_string());
|
||||
}
|
||||
let pos: f64 = parts[1].parse().map_err(|_| "Invalid position")?;
|
||||
controller.seek(pos);
|
||||
controller.seek(crate::Seconds(pos));
|
||||
app.set_status(format!("Seeked to {:.2}s", pos));
|
||||
}
|
||||
"track" => {
|
||||
@@ -830,7 +830,7 @@ fn execute_command(
|
||||
app.next_clip_id += 1;
|
||||
app.add_clip(track_id, clip_id, start_time, duration, format!("Clip {}", clip_id), Vec::new());
|
||||
|
||||
controller.create_midi_clip(track_id, start_time, duration);
|
||||
controller.create_midi_clip(track_id, crate::Beats(start_time), crate::Beats(duration));
|
||||
app.set_status(format!("Created MIDI clip on track {} at {:.2}s for {:.2}s", track_id, start_time, duration));
|
||||
}
|
||||
"loadmidi" => {
|
||||
@@ -882,7 +882,7 @@ fn execute_command(
|
||||
app.next_clip_id += 1;
|
||||
|
||||
// Send to audio engine with the start_time (clip content is separate from timeline position)
|
||||
controller.add_loaded_midi_clip(track_id, midi_clip, start_time);
|
||||
controller.add_loaded_midi_clip(track_id, midi_clip, crate::Beats(start_time));
|
||||
|
||||
app.set_status(format!("Loaded {} ({} events, {:.2}s) to track {} at {:.2}s",
|
||||
file_path, event_count, duration, track_id, start_time));
|
||||
|
||||
@@ -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
+488
-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"
|
||||
@@ -77,6 +83,15 @@ opt-level = 2
|
||||
[profile.dev.package.cpal]
|
||||
opt-level = 2
|
||||
|
||||
# GIF export: NeuQuant palette quantization is tight numeric loops that are punishingly slow
|
||||
# unoptimized (10–30× in debug). Optimize the encoder crates even in dev builds.
|
||||
[profile.dev.package.gif]
|
||||
opt-level = 3
|
||||
[profile.dev.package.color_quant]
|
||||
opt-level = 3
|
||||
[profile.dev.package.weezl]
|
||||
opt-level = 3
|
||||
|
||||
# Use local egui fork with ibus/Wayland text input fix
|
||||
[patch.crates-io]
|
||||
egui = { path = "../../egui-fork/crates/egui" }
|
||||
|
||||
@@ -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,12 @@ bytemuck = { version = "1.14", features = ["derive"] }
|
||||
kurbo = { workspace = true }
|
||||
vello = { workspace = true }
|
||||
|
||||
# Text layout/shaping (text layers)
|
||||
parley = { workspace = true }
|
||||
# Glyph outline extraction for lossless text→SVG export. Pinned to the version parley resolves
|
||||
# (0.43) so glyph IDs / normalized coords from parley layouts match this outliner.
|
||||
skrifa = "0.43"
|
||||
|
||||
# Image decoding for image fills
|
||||
image = { workspace = true }
|
||||
|
||||
@@ -29,6 +35,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 +44,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 +81,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).
|
||||
@@ -47,6 +47,113 @@ pub struct BackendContext<'a> {
|
||||
// Future: pub video_controller: Option<&'a mut VideoController>,
|
||||
}
|
||||
|
||||
impl BackendContext<'_> {
|
||||
/// Hand a clip instance to the audio engine and record it in the instance→backend map.
|
||||
///
|
||||
/// Take folders are resolved through the instance's `active_take`, so the backend gets whichever
|
||||
/// take is selected. Returns the backend track and instance IDs, or `None` when there's nothing
|
||||
/// to sync yet (a recording in progress, or an empty take folder).
|
||||
///
|
||||
/// Lives here rather than in any one action because more than one action needs it: adding an
|
||||
/// instance, and switching a take folder's active take (which is a remove + re-add, there being
|
||||
/// no in-place pool-swap command). Keeping one implementation keeps the trim/duration
|
||||
/// conversions — the easy thing to get subtly wrong, since `trim_*` is SECONDS while
|
||||
/// `timeline_*` is BEATS — from drifting between copies.
|
||||
pub fn add_clip_instance(
|
||||
&mut self,
|
||||
document: &Document,
|
||||
layer_id: &Uuid,
|
||||
instance: &crate::clip::ClipInstance,
|
||||
) -> Result<Option<(daw_backend::TrackId, BackendClipInstanceId)>, String> {
|
||||
use crate::clip::ResolvedContent;
|
||||
|
||||
let clip = document
|
||||
.get_audio_clip(&instance.clip_id)
|
||||
.ok_or_else(|| format!("Audio clip {} not found", instance.clip_id))?;
|
||||
|
||||
let track_id = *self
|
||||
.layer_to_track_map
|
||||
.get(layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not mapped to backend track", layer_id))?;
|
||||
|
||||
let resolved = instance.resolve(clip);
|
||||
let content = clip.content_duration();
|
||||
let internal_start = instance.trim_start;
|
||||
let internal_end = instance
|
||||
.trim_end
|
||||
.unwrap_or(daw_backend::ContentTime(content.native()));
|
||||
let start_time = instance.timeline_start;
|
||||
|
||||
// How long the clip occupies the timeline, in BEATS. `effective_duration_beats` resolves the
|
||||
// content window in the clip's own domain — beats content carries over directly, wall-clock
|
||||
// content converts at the clip's position — so neither kind can be read as the other here.
|
||||
let effective_duration = instance.effective_duration_beats(content, document.tempo_map());
|
||||
|
||||
let controller = self
|
||||
.audio_controller
|
||||
.as_mut()
|
||||
.ok_or_else(|| "Audio controller not available".to_string())?;
|
||||
|
||||
let backend_id = match resolved {
|
||||
ResolvedContent::Midi { midi_clip_id } => {
|
||||
use daw_backend::command::{Query, QueryResponse};
|
||||
|
||||
// MIDI content time IS beats, so the trims carry straight over.
|
||||
let midi_instance = daw_backend::MidiClipInstance::new(
|
||||
0, // assigned by the backend
|
||||
midi_clip_id,
|
||||
daw_backend::Beats(internal_start.raw()),
|
||||
daw_backend::Beats(internal_end.raw()),
|
||||
start_time,
|
||||
effective_duration,
|
||||
);
|
||||
|
||||
match controller
|
||||
.send_query(Query::AddMidiClipInstanceSync(track_id, midi_instance))?
|
||||
{
|
||||
QueryResponse::MidiClipInstanceAdded(Ok(id)) => BackendClipInstanceId::Midi(id),
|
||||
QueryResponse::MidiClipInstanceAdded(Err(e)) => return Err(e),
|
||||
_ => return Err("Unexpected query response".to_string()),
|
||||
}
|
||||
}
|
||||
ResolvedContent::Audio { audio_pool_index } => {
|
||||
// Sampled-audio content time is SECONDS; the backend's start/duration are BEATS.
|
||||
let id = controller.add_audio_clip(
|
||||
track_id,
|
||||
audio_pool_index,
|
||||
start_time,
|
||||
effective_duration,
|
||||
daw_backend::Seconds(internal_start.raw()),
|
||||
);
|
||||
BackendClipInstanceId::Audio(id)
|
||||
}
|
||||
// Nothing to sync until it has content.
|
||||
ResolvedContent::Recording => return Ok(None),
|
||||
};
|
||||
|
||||
self.clip_instance_to_backend_map
|
||||
.insert(instance.id, backend_id);
|
||||
|
||||
Ok(Some((track_id, backend_id)))
|
||||
}
|
||||
|
||||
/// Remove a clip instance's backend clip and drop it from the instance→backend map.
|
||||
pub fn remove_clip_instance(
|
||||
&mut self,
|
||||
track_id: daw_backend::TrackId,
|
||||
backend_id: BackendClipInstanceId,
|
||||
instance_id: Uuid,
|
||||
) {
|
||||
if let Some(controller) = self.audio_controller.as_mut() {
|
||||
match backend_id {
|
||||
BackendClipInstanceId::Midi(id) => controller.remove_midi_clip(track_id, id),
|
||||
BackendClipInstanceId::Audio(id) => controller.remove_audio_clip(track_id, id),
|
||||
}
|
||||
}
|
||||
self.clip_instance_to_backend_map.remove(&instance_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Action trait for undo/redo operations
|
||||
///
|
||||
/// Each action must be able to execute (apply changes) and rollback (undo changes).
|
||||
@@ -71,6 +178,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()
|
||||
@@ -227,6 +343,24 @@ impl ActionExecutor {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Register an action whose effect has **already been applied** to the document (and backend)
|
||||
/// outside the executor — e.g. a recording, which streams its content into the document live
|
||||
/// over time and can't be applied by a single synchronous `execute()`.
|
||||
///
|
||||
/// Unlike `execute`, this does NOT run `execute()`/`execute_backend()` (the effect is already
|
||||
/// present). It clears the redo stack, bumps the epoch (so the document reads as modified), and
|
||||
/// pushes the action so it becomes undoable: undo runs `rollback`/`rollback_backend` to remove
|
||||
/// the content, redo runs `execute`/`execute_backend` to bring it back. The action must be
|
||||
/// constructed already in its post-execute state (see e.g. `AddClipInstanceAction::already_applied`).
|
||||
pub fn push_applied(&mut self, action: Box<dyn Action>) {
|
||||
self.redo_stack.clear();
|
||||
self.epoch = self.epoch.wrapping_add(1);
|
||||
self.undo_stack.push(action);
|
||||
if self.undo_stack.len() > self.max_undo_depth {
|
||||
self.undo_stack.remove(0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Undo the last action
|
||||
///
|
||||
/// Returns Ok(true) if an action was undone, Ok(false) if undo stack is empty,
|
||||
@@ -238,6 +372,7 @@ impl ActionExecutor {
|
||||
Ok(()) => {
|
||||
// Move to redo stack
|
||||
self.redo_stack.push(action);
|
||||
self.epoch = self.epoch.wrapping_add(1);
|
||||
Ok(true)
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -262,6 +397,7 @@ impl ActionExecutor {
|
||||
Ok(()) => {
|
||||
// Move back to undo stack
|
||||
self.undo_stack.push(action);
|
||||
self.epoch = self.epoch.wrapping_add(1);
|
||||
Ok(true)
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -290,6 +426,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)])> {
|
||||
@@ -423,6 +571,7 @@ impl ActionExecutor {
|
||||
|
||||
// Move to redo stack
|
||||
self.redo_stack.push(action);
|
||||
self.epoch = self.epoch.wrapping_add(1);
|
||||
|
||||
Ok(true)
|
||||
} else {
|
||||
@@ -460,6 +609,7 @@ impl ActionExecutor {
|
||||
|
||||
// Move back to undo stack
|
||||
self.undo_stack.push(action);
|
||||
self.epoch = self.epoch.wrapping_add(1);
|
||||
|
||||
Ok(true)
|
||||
} else {
|
||||
|
||||
@@ -47,6 +47,31 @@ impl AddClipInstanceAction {
|
||||
}
|
||||
}
|
||||
|
||||
/// Construct the action in its **already-applied** state: the clip instance is already in the
|
||||
/// document and its backend clip already exists (e.g. a finished recording). Pair with
|
||||
/// `ActionExecutor::push_applied` so the recording becomes undoable without re-adding anything.
|
||||
/// Undo will `rollback`/`rollback_backend` (removing the clip from doc + backend via the seeded
|
||||
/// ids); redo re-adds it via the normal `execute`/`execute_backend` path.
|
||||
pub fn already_applied(
|
||||
layer_id: Uuid,
|
||||
clip_instance: ClipInstance,
|
||||
backend_track_id: daw_backend::TrackId,
|
||||
backend_id: crate::action::BackendClipInstanceId,
|
||||
) -> Self {
|
||||
let (backend_midi_instance_id, backend_audio_instance_id) = match backend_id {
|
||||
crate::action::BackendClipInstanceId::Midi(id) => (Some(id), None),
|
||||
crate::action::BackendClipInstanceId::Audio(id) => (None, Some(id)),
|
||||
};
|
||||
Self {
|
||||
layer_id,
|
||||
clip_instance,
|
||||
executed: true, // already present in the document
|
||||
backend_track_id: Some(backend_track_id),
|
||||
backend_midi_instance_id,
|
||||
backend_audio_instance_id,
|
||||
}
|
||||
}
|
||||
|
||||
/// Get the ID of the clip instance that will be/was added
|
||||
pub fn clip_instance_id(&self) -> Uuid {
|
||||
self.clip_instance.id
|
||||
@@ -60,13 +85,15 @@ impl AddClipInstanceAction {
|
||||
|
||||
impl Action for AddClipInstanceAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
// Calculate the clip's effective duration
|
||||
let clip_duration = document.get_clip_duration(&self.clip_instance.clip_id)
|
||||
// Calculate the clip's effective duration in BEATS for overlap testing.
|
||||
// `get_clip_duration` is the content length in seconds; the placement span
|
||||
// must be beats (the timeline is beats-domain), so convert via the clip's
|
||||
// typed helper rather than treating the seconds span as beats.
|
||||
// The clip's content duration in ITS OWN domain, so the trims resolve correctly for MIDI.
|
||||
let clip_content = document.clip_trim_duration(&self.clip_instance.clip_id)
|
||||
.ok_or_else(|| format!("Clip {} not found", self.clip_instance.clip_id))?;
|
||||
|
||||
let trim_start = self.clip_instance.trim_start;
|
||||
let trim_end = self.clip_instance.trim_end.unwrap_or(clip_duration);
|
||||
let effective_duration = trim_end - trim_start;
|
||||
let effective_duration = self.clip_instance
|
||||
.effective_duration_beats(clip_content, document.tempo_map());
|
||||
|
||||
// Auto-adjust position for audio/video layers to avoid overlaps
|
||||
let adjusted_start = document.find_nearest_valid_position(
|
||||
@@ -104,7 +131,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 +172,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;
|
||||
@@ -170,101 +197,23 @@ impl Action for AddClipInstanceAction {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Look up the clip from the document
|
||||
let clip = document
|
||||
.get_audio_clip(&self.clip_instance.clip_id)
|
||||
.ok_or_else(|| "Audio clip not found".to_string())?;
|
||||
|
||||
// Look up backend track ID from layer mapping
|
||||
let backend_track_id = backend
|
||||
.layer_to_track_map
|
||||
.get(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not mapped to backend track", self.layer_id))?;
|
||||
|
||||
// Get audio controller
|
||||
let controller = backend
|
||||
.audio_controller
|
||||
.as_mut()
|
||||
.ok_or_else(|| "Audio controller not available".to_string())?;
|
||||
|
||||
// Handle different clip types
|
||||
use crate::clip::AudioClipType;
|
||||
match &clip.clip_type {
|
||||
AudioClipType::Midi { midi_clip_id } => {
|
||||
// Create a MIDI clip instance referencing the existing clip in the backend pool
|
||||
// No need to add to pool again - it was added during MIDI import
|
||||
use daw_backend::command::{Query, QueryResponse};
|
||||
|
||||
// Calculate internal start/end from trim parameters
|
||||
let internal_start = self.clip_instance.trim_start;
|
||||
let internal_end = self.clip_instance.trim_end.unwrap_or(clip.duration);
|
||||
let external_start = self.clip_instance.timeline_start;
|
||||
|
||||
// Calculate external duration (for looping if timeline_duration is set)
|
||||
let external_duration = self.clip_instance.timeline_duration
|
||||
.unwrap_or(internal_end - internal_start);
|
||||
|
||||
// Create MidiClipInstance
|
||||
let instance = daw_backend::MidiClipInstance::new(
|
||||
0, // Instance ID will be assigned by backend
|
||||
*midi_clip_id,
|
||||
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
|
||||
let query = Query::AddMidiClipInstanceSync(*backend_track_id, instance);
|
||||
|
||||
match controller.send_query(query)? {
|
||||
QueryResponse::MidiClipInstanceAdded(Ok(instance_id)) => {
|
||||
self.backend_track_id = Some(*backend_track_id);
|
||||
self.backend_midi_instance_id = Some(instance_id);
|
||||
|
||||
// Add to global clip instance mapping
|
||||
backend.clip_instance_to_backend_map.insert(
|
||||
self.clip_instance.id,
|
||||
crate::action::BackendClipInstanceId::Midi(instance_id)
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
QueryResponse::MidiClipInstanceAdded(Err(e)) => Err(e),
|
||||
_ => Err("Unexpected query response".to_string()),
|
||||
// Add via the shared BackendContext helper — the same one SetActiveTakeAction uses, so
|
||||
// the trim/duration conversions (and take-folder resolution) live in exactly one place.
|
||||
if let Some((track_id, backend_id)) =
|
||||
backend.add_clip_instance(document, &self.layer_id, &self.clip_instance)?
|
||||
{
|
||||
self.backend_track_id = Some(track_id);
|
||||
match backend_id {
|
||||
crate::action::BackendClipInstanceId::Midi(id) => {
|
||||
self.backend_midi_instance_id = Some(id)
|
||||
}
|
||||
crate::action::BackendClipInstanceId::Audio(id) => {
|
||||
self.backend_audio_instance_id = Some(id)
|
||||
}
|
||||
}
|
||||
AudioClipType::Sampled { audio_pool_index } => {
|
||||
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;
|
||||
|
||||
let instance_id = controller.add_audio_clip(
|
||||
*backend_track_id,
|
||||
*audio_pool_index,
|
||||
start_time,
|
||||
effective_duration,
|
||||
internal_start,
|
||||
);
|
||||
|
||||
self.backend_track_id = Some(*backend_track_id);
|
||||
self.backend_audio_instance_id = Some(instance_id);
|
||||
|
||||
// Add to global clip instance mapping
|
||||
backend.clip_instance_to_backend_map.insert(
|
||||
self.clip_instance.id,
|
||||
crate::action::BackendClipInstanceId::Audio(instance_id)
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
AudioClipType::Recording => {
|
||||
// Recording clips are not synced to backend until finalized
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback_backend(&mut self, backend: &mut BackendContext, _document: &Document) -> Result<(), String> {
|
||||
@@ -305,8 +254,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;
|
||||
|
||||
|
||||
@@ -159,7 +159,7 @@ mod tests {
|
||||
fn test_add_effect() {
|
||||
let (mut document, layer_id, def) = create_test_setup();
|
||||
|
||||
let instance = def.create_instance(0.0, 10.0);
|
||||
let instance = def.create_instance(daw_backend::Beats(0.0), daw_backend::Beats(10.0));
|
||||
let instance_id = instance.id;
|
||||
|
||||
let mut action = AddEffectAction::new(layer_id, instance);
|
||||
@@ -181,7 +181,7 @@ mod tests {
|
||||
fn test_add_effect_rollback() {
|
||||
let (mut document, layer_id, def) = create_test_setup();
|
||||
|
||||
let instance = def.create_instance(0.0, 10.0);
|
||||
let instance = def.create_instance(daw_backend::Beats(0.0), daw_backend::Beats(10.0));
|
||||
|
||||
let mut action = AddEffectAction::new(layer_id, instance);
|
||||
action.execute(&mut document).unwrap();
|
||||
@@ -201,19 +201,19 @@ mod tests {
|
||||
let (mut document, layer_id, def) = create_test_setup();
|
||||
|
||||
// Add first effect
|
||||
let instance1 = def.create_instance(0.0, 10.0);
|
||||
let instance1 = def.create_instance(daw_backend::Beats(0.0), daw_backend::Beats(10.0));
|
||||
let id1 = instance1.id;
|
||||
let mut action1 = AddEffectAction::new(layer_id, instance1);
|
||||
action1.execute(&mut document).unwrap();
|
||||
|
||||
// Add second effect
|
||||
let instance2 = def.create_instance(0.0, 10.0);
|
||||
let instance2 = def.create_instance(daw_backend::Beats(0.0), daw_backend::Beats(10.0));
|
||||
let id2 = instance2.id;
|
||||
let mut action2 = AddEffectAction::new(layer_id, instance2);
|
||||
action2.execute(&mut document).unwrap();
|
||||
|
||||
// Insert third effect at index 1 (between first and second)
|
||||
let instance3 = def.create_instance(0.0, 10.0);
|
||||
let instance3 = def.create_instance(daw_backend::Beats(0.0), daw_backend::Beats(10.0));
|
||||
let id3 = instance3.id;
|
||||
let mut action3 = AddEffectAction::at_index(layer_id, instance3, 1);
|
||||
action3.execute(&mut document).unwrap();
|
||||
|
||||
@@ -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,141 @@
|
||||
//! Append freshly-recorded takes to an existing take folder.
|
||||
//!
|
||||
//! Cycle-recording over a region that already holds a take folder should *add* to that folder, not
|
||||
//! drop a second clip on top of it. Otherwise the takes from your second attempt are stranded in a
|
||||
//! separate, overlapping clip and you can't audition them against the first.
|
||||
//!
|
||||
//! The recorded content already exists in the backend pools by the time this runs (the engine put it
|
||||
//! there at stop), so this action only touches the document — plus the one backend clip the instance
|
||||
//! plays, which has to be repointed at the newly-active take.
|
||||
|
||||
use crate::action::{Action, BackendClipInstanceId, BackendContext};
|
||||
use crate::clip::AudioTake;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Action that appends takes to an instance's take list and selects the last of them.
|
||||
pub struct AppendTakesAction {
|
||||
layer_id: Uuid,
|
||||
/// The instance whose take list is being extended (and whose active take changes).
|
||||
instance_id: Uuid,
|
||||
/// The takes to add, in recording order.
|
||||
new_takes: Vec<AudioTake>,
|
||||
|
||||
// Stored during execute for rollback.
|
||||
old_take_count: usize,
|
||||
old_active_take: Option<usize>,
|
||||
executed: bool,
|
||||
}
|
||||
|
||||
impl AppendTakesAction {
|
||||
pub fn new(layer_id: Uuid, instance_id: Uuid, new_takes: Vec<AudioTake>) -> Self {
|
||||
Self {
|
||||
layer_id,
|
||||
instance_id,
|
||||
new_takes,
|
||||
old_take_count: 0,
|
||||
old_active_take: None,
|
||||
executed: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Swap the instance's backend clip to whatever take the document now says is active.
|
||||
///
|
||||
/// Same remove + re-add as `SetActiveTakeAction` — there's no in-place pool-swap command.
|
||||
fn resync(&self, backend: &mut BackendContext, document: &Document) -> Result<(), String> {
|
||||
let instance = document
|
||||
.get_layer(&self.layer_id)
|
||||
.and_then(|l| match l {
|
||||
AnyLayer::Audio(al) => al.clip_instances.iter().find(|ci| ci.id == self.instance_id),
|
||||
_ => None,
|
||||
})
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("Clip instance {} not found", self.instance_id))?;
|
||||
|
||||
let existing: Option<BackendClipInstanceId> = backend
|
||||
.clip_instance_to_backend_map
|
||||
.get(&self.instance_id)
|
||||
.copied();
|
||||
let track_id = backend.layer_to_track_map.get(&self.layer_id).copied();
|
||||
if let (Some(backend_id), Some(track_id)) = (existing, track_id) {
|
||||
backend.remove_clip_instance(track_id, backend_id, self.instance_id);
|
||||
}
|
||||
|
||||
backend.add_clip_instance(document, &self.layer_id, &instance)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for AppendTakesAction {
|
||||
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::Audio(audio_layer) = layer else {
|
||||
return Err("Takes only exist on audio layers".to_string());
|
||||
};
|
||||
let instance = audio_layer
|
||||
.clip_instances
|
||||
.iter_mut()
|
||||
.find(|ci| ci.id == self.instance_id)
|
||||
.ok_or_else(|| format!("Clip instance {} not found", self.instance_id))?;
|
||||
|
||||
// Only record the pre-state on the first execute; a redo must not overwrite it with the
|
||||
// post-state left behind by the previous run.
|
||||
if !self.executed {
|
||||
self.old_take_count = instance.takes.len();
|
||||
self.old_active_take = instance.active_take;
|
||||
}
|
||||
|
||||
// Number the new takes on from what's already there. Existing names are left alone — the
|
||||
// user may well have renamed them, and renumbering would clobber that.
|
||||
let base = instance.takes.len();
|
||||
for (i, take) in self.new_takes.iter().enumerate() {
|
||||
let mut take = take.clone();
|
||||
if take.name.is_empty() {
|
||||
take.name = format!("Take {}", base + i + 1);
|
||||
}
|
||||
instance.takes.push(take);
|
||||
}
|
||||
|
||||
// Land on the take just recorded, GarageBand-style.
|
||||
instance.active_take = Some(instance.takes.len() - 1);
|
||||
self.executed = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
if let Some(AnyLayer::Audio(audio_layer)) = document.get_layer_mut(&self.layer_id) {
|
||||
if let Some(instance) = audio_layer
|
||||
.clip_instances
|
||||
.iter_mut()
|
||||
.find(|ci| ci.id == self.instance_id)
|
||||
{
|
||||
instance.takes.truncate(self.old_take_count);
|
||||
instance.active_take = self.old_active_take;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
format!("Record {} take(s)", self.new_takes.len())
|
||||
}
|
||||
|
||||
fn execute_backend(
|
||||
&mut self,
|
||||
backend: &mut BackendContext,
|
||||
document: &Document,
|
||||
) -> Result<(), String> {
|
||||
self.resync(backend, document)
|
||||
}
|
||||
|
||||
fn rollback_backend(
|
||||
&mut self,
|
||||
backend: &mut BackendContext,
|
||||
document: &Document,
|
||||
) -> Result<(), String> {
|
||||
self.resync(backend, document)
|
||||
}
|
||||
}
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,8 +9,9 @@ use crate::layer::AnyLayer;
|
||||
use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Per-instance loop change: (instance_id, old_timeline_duration, new_timeline_duration, old_loop_before, new_loop_before)
|
||||
pub type LoopEntry = (Uuid, Option<f64>, Option<f64>, Option<f64>, Option<f64>);
|
||||
/// Per-instance loop change: (instance_id, old_timeline_duration, new_timeline_duration, old_loop_before, new_loop_before).
|
||||
/// All durations/offsets are in beats.
|
||||
pub type LoopEntry = (Uuid, Option<daw_backend::Beats>, Option<daw_backend::Beats>, Option<daw_backend::Beats>, Option<daw_backend::Beats>);
|
||||
|
||||
/// Action that changes the loop duration of clip instances
|
||||
pub struct LoopClipInstancesAction {
|
||||
@@ -37,6 +38,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 +63,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 {
|
||||
@@ -88,7 +91,7 @@ impl Action for LoopClipInstancesAction {
|
||||
|
||||
impl LoopClipInstancesAction {
|
||||
fn sync_backend(&self, backend: &mut crate::action::BackendContext, document: &Document, rollback: bool) -> Result<(), String> {
|
||||
use crate::clip::AudioClipType;
|
||||
use crate::clip::ResolvedContent;
|
||||
|
||||
let controller = match backend.audio_controller.as_mut() {
|
||||
Some(c) => c,
|
||||
@@ -125,19 +128,22 @@ impl LoopClipInstancesAction {
|
||||
(new_dur, new_lb)
|
||||
};
|
||||
|
||||
let content_window = {
|
||||
let trim_end = instance.trim_end.unwrap_or(clip.duration);
|
||||
(trim_end - instance.trim_start).max(0.0)
|
||||
};
|
||||
let right_duration = target_duration.unwrap_or(content_window);
|
||||
let left_duration = target_loop_before.unwrap_or(0.0);
|
||||
// Natural content length as a beats span (the fallback when no explicit
|
||||
// timeline_duration is set). Resolved in the clip's own domain, so MIDI's beats
|
||||
// content carries over directly rather than being read as seconds.
|
||||
let content_window_beats = instance.effective_duration_beats(
|
||||
clip.content_duration(),
|
||||
document.tempo_map(),
|
||||
);
|
||||
let right_duration = target_duration.unwrap_or(content_window_beats);
|
||||
let left_duration = target_loop_before.unwrap_or(daw_backend::Beats::ZERO);
|
||||
let external_duration = left_duration + right_duration;
|
||||
let external_start = instance.timeline_start - left_duration;
|
||||
|
||||
let get_backend_clip_id = |inst_id: &Uuid| -> Result<u32, String> {
|
||||
match &clip.clip_type {
|
||||
AudioClipType::Midi { midi_clip_id } => Ok(*midi_clip_id),
|
||||
AudioClipType::Sampled { .. } => {
|
||||
match &instance.resolve(clip) {
|
||||
ResolvedContent::Midi { midi_clip_id } => Ok(*midi_clip_id),
|
||||
ResolvedContent::Audio { .. } => {
|
||||
let backend_id = backend.clip_instance_to_backend_map.get(inst_id)
|
||||
.ok_or_else(|| format!("Clip instance {} not mapped to backend", inst_id))?;
|
||||
match backend_id {
|
||||
@@ -145,7 +151,7 @@ impl LoopClipInstancesAction {
|
||||
_ => Err("Expected audio instance ID for sampled clip".to_string()),
|
||||
}
|
||||
}
|
||||
AudioClipType::Recording => Err("Cannot sync recording clip".to_string()),
|
||||
ResolvedContent::Recording => Err("Cannot sync recording clip".to_string()),
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,419 @@
|
||||
//! Take management: delete and rename the takes on a clip instance.
|
||||
//!
|
||||
//! Takes live on the INSTANCE, so both of these are naturally scoped to the one the user clicked —
|
||||
//! deleting a take from one half of a comped split leaves the other half's list alone.
|
||||
|
||||
use crate::action::{Action, BackendClipInstanceId, BackendContext};
|
||||
use crate::clip::{AudioTake, ClipInstance};
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// The instance a take action targets, looked up mutably.
|
||||
fn instance_mut<'a>(
|
||||
document: &'a mut Document,
|
||||
layer_id: &Uuid,
|
||||
instance_id: &Uuid,
|
||||
) -> Result<&'a mut ClipInstance, String> {
|
||||
let layer = document
|
||||
.get_layer_mut(layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", layer_id))?;
|
||||
let AnyLayer::Audio(audio_layer) = layer else {
|
||||
return Err("Takes only exist on audio layers".to_string());
|
||||
};
|
||||
audio_layer
|
||||
.clip_instances
|
||||
.iter_mut()
|
||||
.find(|ci| ci.id == *instance_id)
|
||||
.ok_or_else(|| format!("Clip instance {} not found", instance_id))
|
||||
}
|
||||
|
||||
/// Swap an instance's backend clip to whatever take the document now says is active.
|
||||
///
|
||||
/// The same remove + re-add as `SetActiveTakeAction` — there's no in-place pool-swap command.
|
||||
fn resync(
|
||||
backend: &mut BackendContext,
|
||||
document: &Document,
|
||||
layer_id: &Uuid,
|
||||
instance_id: &Uuid,
|
||||
) -> Result<(), String> {
|
||||
let instance = document
|
||||
.get_layer(layer_id)
|
||||
.and_then(|l| match l {
|
||||
AnyLayer::Audio(al) => al.clip_instances.iter().find(|ci| ci.id == *instance_id),
|
||||
_ => None,
|
||||
})
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("Clip instance {} not found", instance_id))?;
|
||||
|
||||
let existing: Option<BackendClipInstanceId> = backend
|
||||
.clip_instance_to_backend_map
|
||||
.get(instance_id)
|
||||
.copied();
|
||||
let track_id = backend.layer_to_track_map.get(layer_id).copied();
|
||||
if let (Some(backend_id), Some(track_id)) = (existing, track_id) {
|
||||
backend.remove_clip_instance(track_id, backend_id, *instance_id);
|
||||
}
|
||||
|
||||
backend.add_clip_instance(document, layer_id, &instance)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove a take from an instance's take list.
|
||||
///
|
||||
/// The take's recorded audio/MIDI stays in the backend pool — undo has to be able to put it back,
|
||||
/// and other instances (the other half of a split, say) may still be playing it.
|
||||
pub struct DeleteTakeAction {
|
||||
layer_id: Uuid,
|
||||
instance_id: Uuid,
|
||||
take_index: usize,
|
||||
|
||||
// Stored during execute for rollback.
|
||||
removed: Option<AudioTake>,
|
||||
old_active_take: Option<usize>,
|
||||
}
|
||||
|
||||
impl DeleteTakeAction {
|
||||
pub fn new(layer_id: Uuid, instance_id: Uuid, take_index: usize) -> Self {
|
||||
Self {
|
||||
layer_id,
|
||||
instance_id,
|
||||
take_index,
|
||||
removed: None,
|
||||
old_active_take: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for DeleteTakeAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
|
||||
|
||||
if self.take_index >= instance.takes.len() {
|
||||
return Err(format!("Take {} does not exist", self.take_index + 1));
|
||||
}
|
||||
// An instance with no takes at all would fall back to the clip's own content, which for a
|
||||
// cycle recording is a take we may just have deleted. Refuse rather than strand it.
|
||||
if instance.takes.len() == 1 {
|
||||
return Err("Can't delete the only take".to_string());
|
||||
}
|
||||
|
||||
self.old_active_take = instance.active_take;
|
||||
self.removed = Some(instance.takes.remove(self.take_index));
|
||||
|
||||
// Everything above the removed take shifts down one, so the selection has to move with it.
|
||||
// Deleting the *active* take lands on the one that took its place (or the new last take, if
|
||||
// it was at the end) — that keeps the clip sounding rather than silently picking take 1.
|
||||
let active = instance.active_take.unwrap_or(0);
|
||||
instance.active_take = Some(if active > self.take_index {
|
||||
active - 1
|
||||
} else if active == self.take_index {
|
||||
self.take_index.min(instance.takes.len() - 1)
|
||||
} else {
|
||||
active
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let Some(take) = self.removed.take() else {
|
||||
return Ok(());
|
||||
};
|
||||
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
|
||||
let at = self.take_index.min(instance.takes.len());
|
||||
instance.takes.insert(at, take);
|
||||
instance.active_take = self.old_active_take;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
format!("Delete take {}", self.take_index + 1)
|
||||
}
|
||||
|
||||
fn execute_backend(
|
||||
&mut self,
|
||||
backend: &mut BackendContext,
|
||||
document: &Document,
|
||||
) -> Result<(), String> {
|
||||
resync(backend, document, &self.layer_id, &self.instance_id)
|
||||
}
|
||||
|
||||
fn rollback_backend(
|
||||
&mut self,
|
||||
backend: &mut BackendContext,
|
||||
document: &Document,
|
||||
) -> Result<(), String> {
|
||||
resync(backend, document, &self.layer_id, &self.instance_id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Throw away every take except the one that's playing.
|
||||
///
|
||||
/// The tidy-up once you've picked your keeper. Scoped to this instance, so on a comped split it
|
||||
/// prunes the half you clicked and leaves the other half's alternatives intact.
|
||||
pub struct DeleteUnusedTakesAction {
|
||||
layer_id: Uuid,
|
||||
instance_id: Uuid,
|
||||
|
||||
// Stored during execute for rollback.
|
||||
old_takes: Vec<AudioTake>,
|
||||
old_active_take: Option<usize>,
|
||||
}
|
||||
|
||||
impl DeleteUnusedTakesAction {
|
||||
pub fn new(layer_id: Uuid, instance_id: Uuid) -> Self {
|
||||
Self {
|
||||
layer_id,
|
||||
instance_id,
|
||||
old_takes: Vec::new(),
|
||||
old_active_take: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for DeleteUnusedTakesAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
|
||||
if instance.takes.len() < 2 {
|
||||
return Err("Nothing to delete".to_string());
|
||||
}
|
||||
|
||||
let keep = instance.active_take_index();
|
||||
self.old_takes = instance.takes.clone();
|
||||
self.old_active_take = instance.active_take;
|
||||
|
||||
let kept = instance.takes.remove(keep);
|
||||
instance.takes.clear();
|
||||
instance.takes.push(kept);
|
||||
instance.active_take = Some(0);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
|
||||
instance.takes = std::mem::take(&mut self.old_takes);
|
||||
instance.active_take = self.old_active_take;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
"Delete unused takes".to_string()
|
||||
}
|
||||
|
||||
// The take that plays doesn't change, so the backend clip is already correct.
|
||||
}
|
||||
|
||||
/// Rename a take. Document-only — which take *plays* doesn't change, so the backend is untouched.
|
||||
pub struct RenameTakeAction {
|
||||
layer_id: Uuid,
|
||||
instance_id: Uuid,
|
||||
take_index: usize,
|
||||
new_name: String,
|
||||
old_name: String,
|
||||
}
|
||||
|
||||
impl RenameTakeAction {
|
||||
pub fn new(layer_id: Uuid, instance_id: Uuid, take_index: usize, new_name: String) -> Self {
|
||||
Self {
|
||||
layer_id,
|
||||
instance_id,
|
||||
take_index,
|
||||
new_name,
|
||||
old_name: String::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for RenameTakeAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
|
||||
let take = instance
|
||||
.takes
|
||||
.get_mut(self.take_index)
|
||||
.ok_or_else(|| format!("Take {} does not exist", self.take_index + 1))?;
|
||||
self.old_name = std::mem::replace(&mut take.name, self.new_name.clone());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
|
||||
if let Some(take) = instance.takes.get_mut(self.take_index) {
|
||||
take.name = self.old_name.clone();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
format!("Rename take to \"{}\"", self.new_name)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::clip::TakeContent;
|
||||
use crate::layer::AudioLayer;
|
||||
|
||||
/// A document with one audio layer holding one instance with 4 takes (pools 10..13).
|
||||
fn doc_with_takes() -> (Document, Uuid, Uuid) {
|
||||
let mut document = Document::new("Test");
|
||||
let clip = crate::clip::AudioClip::new_sampled("Cycle rec", 10, 2.0);
|
||||
let clip_id = document.add_audio_clip(clip);
|
||||
|
||||
let mut instance = ClipInstance::new(clip_id);
|
||||
instance.takes = (10..14)
|
||||
.map(|pool| AudioTake {
|
||||
name: format!("Take {}", pool - 9),
|
||||
content: TakeContent::Audio { audio_pool_index: pool },
|
||||
})
|
||||
.collect();
|
||||
let instance_id = instance.id;
|
||||
|
||||
let mut layer = AudioLayer::new("Layer");
|
||||
layer.clip_instances.push(instance);
|
||||
let layer_id = document.root.add_child(AnyLayer::Audio(layer));
|
||||
(document, layer_id, instance_id)
|
||||
}
|
||||
|
||||
fn takes_of(document: &Document, layer_id: &Uuid, instance_id: &Uuid) -> ClipInstance {
|
||||
let AnyLayer::Audio(al) = document.get_layer(layer_id).unwrap() else { panic!() };
|
||||
al.clip_instances.iter().find(|ci| ci.id == *instance_id).unwrap().clone()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_a_take_below_the_active_one_shifts_the_selection_down() {
|
||||
// Everything above the removed take shifts down one, so a selection above it has to move
|
||||
// with it — otherwise the instance silently starts playing a different take.
|
||||
let (mut document, layer_id, instance_id) = doc_with_takes();
|
||||
{
|
||||
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
|
||||
al.clip_instances[0].active_take = Some(3); // playing pool 13
|
||||
}
|
||||
|
||||
DeleteTakeAction::new(layer_id, instance_id, 1)
|
||||
.execute(&mut document)
|
||||
.expect("delete");
|
||||
|
||||
let inst = takes_of(&document, &layer_id, &instance_id);
|
||||
assert_eq!(inst.takes.len(), 3);
|
||||
assert_eq!(inst.active_take, Some(2), "index shifted down with the take");
|
||||
assert_eq!(
|
||||
inst.takes[inst.active_take_index()].content,
|
||||
TakeContent::Audio { audio_pool_index: 13 },
|
||||
"still playing the same take it was",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_the_active_take_lands_on_its_replacement() {
|
||||
// Deleting what you're listening to should hand you the take that took its place, not
|
||||
// silently jump you back to take 1.
|
||||
let (mut document, layer_id, instance_id) = doc_with_takes();
|
||||
{
|
||||
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
|
||||
al.clip_instances[0].active_take = Some(1); // playing pool 11
|
||||
}
|
||||
|
||||
DeleteTakeAction::new(layer_id, instance_id, 1)
|
||||
.execute(&mut document)
|
||||
.expect("delete");
|
||||
|
||||
let inst = takes_of(&document, &layer_id, &instance_id);
|
||||
assert_eq!(inst.active_take, Some(1));
|
||||
assert_eq!(
|
||||
inst.takes[1].content,
|
||||
TakeContent::Audio { audio_pool_index: 12 },
|
||||
"the take that slid into the deleted one's place",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_the_last_take_in_the_list_steps_back() {
|
||||
let (mut document, layer_id, instance_id) = doc_with_takes();
|
||||
{
|
||||
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
|
||||
al.clip_instances[0].active_take = Some(3);
|
||||
}
|
||||
|
||||
DeleteTakeAction::new(layer_id, instance_id, 3)
|
||||
.execute(&mut document)
|
||||
.expect("delete");
|
||||
|
||||
let inst = takes_of(&document, &layer_id, &instance_id);
|
||||
assert_eq!(inst.active_take, Some(2), "there is no take 4 to land on");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_only_take_cannot_be_deleted() {
|
||||
let (mut document, layer_id, instance_id) = doc_with_takes();
|
||||
{
|
||||
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
|
||||
al.clip_instances[0].takes.truncate(1);
|
||||
}
|
||||
assert!(DeleteTakeAction::new(layer_id, instance_id, 0)
|
||||
.execute(&mut document)
|
||||
.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undoing_a_delete_puts_the_take_back_where_it_was() {
|
||||
let (mut document, layer_id, instance_id) = doc_with_takes();
|
||||
{
|
||||
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
|
||||
al.clip_instances[0].active_take = Some(2);
|
||||
}
|
||||
|
||||
let mut action = DeleteTakeAction::new(layer_id, instance_id, 1);
|
||||
action.execute(&mut document).expect("delete");
|
||||
action.rollback(&mut document).expect("undo");
|
||||
|
||||
let inst = takes_of(&document, &layer_id, &instance_id);
|
||||
assert_eq!(inst.takes.len(), 4);
|
||||
assert_eq!(
|
||||
inst.takes[1].content,
|
||||
TakeContent::Audio { audio_pool_index: 11 },
|
||||
"restored at its original index",
|
||||
);
|
||||
assert_eq!(inst.active_take, Some(2), "and the selection with it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deleting_unused_takes_keeps_the_one_thats_playing() {
|
||||
let (mut document, layer_id, instance_id) = doc_with_takes();
|
||||
{
|
||||
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
|
||||
al.clip_instances[0].active_take = Some(2); // pool 12 — the keeper
|
||||
}
|
||||
|
||||
let mut action = DeleteUnusedTakesAction::new(layer_id, instance_id);
|
||||
action.execute(&mut document).expect("prune");
|
||||
|
||||
let inst = takes_of(&document, &layer_id, &instance_id);
|
||||
assert_eq!(inst.takes.len(), 1);
|
||||
assert_eq!(inst.active_take, Some(0));
|
||||
assert_eq!(
|
||||
inst.takes[0].content,
|
||||
TakeContent::Audio { audio_pool_index: 12 },
|
||||
"the take that was playing survives, and nothing else",
|
||||
);
|
||||
|
||||
action.rollback(&mut document).expect("undo");
|
||||
let inst = takes_of(&document, &layer_id, &instance_id);
|
||||
assert_eq!(inst.takes.len(), 4);
|
||||
assert_eq!(inst.active_take, Some(2), "back to what was playing before");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renaming_a_take_round_trips() {
|
||||
let (mut document, layer_id, instance_id) = doc_with_takes();
|
||||
let mut action =
|
||||
RenameTakeAction::new(layer_id, instance_id, 2, "The good one".to_string());
|
||||
|
||||
action.execute(&mut document).expect("rename");
|
||||
assert_eq!(takes_of(&document, &layer_id, &instance_id).takes[2].name, "The good one");
|
||||
|
||||
action.rollback(&mut document).expect("undo");
|
||||
assert_eq!(takes_of(&document, &layer_id, &instance_id).takes[2].name, "Take 3");
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,13 @@ 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_cycle_region;
|
||||
pub mod append_takes;
|
||||
pub mod manage_takes;
|
||||
pub mod set_active_take;
|
||||
pub mod set_document_properties;
|
||||
pub mod set_instance_properties;
|
||||
pub mod set_layer_properties;
|
||||
@@ -29,22 +34,36 @@ 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 set_cycle_region::SetCycleRegionAction;
|
||||
pub use append_takes::AppendTakesAction;
|
||||
pub use manage_takes::{DeleteTakeAction, DeleteUnusedTakesAction, RenameTakeAction};
|
||||
pub use set_active_take::SetActiveTakeAction;
|
||||
pub use add_effect::AddEffectAction;
|
||||
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;
|
||||
@@ -63,6 +82,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;
|
||||
@@ -70,7 +90,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;
|
||||
|
||||
@@ -6,13 +6,15 @@ use crate::action::Action;
|
||||
use crate::clip::ClipInstance;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use daw_backend::Beats;
|
||||
use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Action that moves clip instances to new timeline positions
|
||||
pub struct MoveClipInstancesAction {
|
||||
/// Map of layer IDs to vectors of (clip_instance_id, old_timeline_start, new_timeline_start)
|
||||
layer_moves: HashMap<Uuid, Vec<(Uuid, f64, f64)>>,
|
||||
/// Map of layer IDs to vectors of (clip_instance_id, old_timeline_start, new_timeline_start).
|
||||
/// Timeline positions are in beats.
|
||||
layer_moves: HashMap<Uuid, Vec<(Uuid, Beats, Beats)>>,
|
||||
}
|
||||
|
||||
impl MoveClipInstancesAction {
|
||||
@@ -20,8 +22,8 @@ impl MoveClipInstancesAction {
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `layer_moves` - Map of layer IDs to vectors of (clip_instance_id, old_timeline_start, new_timeline_start)
|
||||
pub fn new(layer_moves: HashMap<Uuid, Vec<(Uuid, f64, f64)>>) -> Self {
|
||||
/// * `layer_moves` - Map of layer IDs to vectors of (clip_instance_id, old_timeline_start, new_timeline_start) in beats
|
||||
pub fn new(layer_moves: HashMap<Uuid, Vec<(Uuid, Beats, Beats)>>) -> Self {
|
||||
Self { layer_moves }
|
||||
}
|
||||
}
|
||||
@@ -42,7 +44,7 @@ impl Action for MoveClipInstancesAction {
|
||||
|
||||
// Check if this instance is in a group
|
||||
if let Some(group) = document.find_group_for_instance(instance_id) {
|
||||
let offset = new_start - old_start;
|
||||
let offset = *new_start - *old_start;
|
||||
|
||||
// Add all group members to the move list
|
||||
for (member_layer_id, member_instance_id) in group.get_members() {
|
||||
@@ -58,6 +60,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) {
|
||||
@@ -76,7 +79,7 @@ impl Action for MoveClipInstancesAction {
|
||||
}
|
||||
|
||||
// Auto-adjust moves to avoid overlaps
|
||||
let mut adjusted_moves: HashMap<Uuid, Vec<(Uuid, f64, f64)>> = HashMap::new();
|
||||
let mut adjusted_moves: HashMap<Uuid, Vec<(Uuid, Beats, Beats)>> = HashMap::new();
|
||||
|
||||
for (layer_id, moves) in &expanded_moves {
|
||||
let layer = document.get_layer(layer_id)
|
||||
@@ -97,12 +100,13 @@ 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, _)| {
|
||||
let group: Vec<(Uuid, Beats, Beats)> = moves.iter().filter_map(|(id, old_start, _)| {
|
||||
let inst = clip_instances.iter().find(|ci| &ci.id == id)?;
|
||||
let dur = document.get_clip_duration(&inst.clip_id)?;
|
||||
let eff = inst.trim_end.unwrap_or(dur) - inst.trim_start;
|
||||
let dur = document.clip_trim_duration(&inst.clip_id)?;
|
||||
let eff = inst.effective_duration_beats(dur, document.tempo_map());
|
||||
Some((*id, *old_start, eff))
|
||||
}).collect();
|
||||
|
||||
@@ -110,7 +114,7 @@ impl Action for MoveClipInstancesAction {
|
||||
let clamped = document.clamp_group_move_offset(layer_id, &group, desired_offset);
|
||||
|
||||
for (instance_id, old_start, _) in moves {
|
||||
adjusted_layer_moves.push((*instance_id, *old_start, (*old_start + clamped).max(0.0)));
|
||||
adjusted_layer_moves.push((*instance_id, *old_start, (*old_start + clamped).max(Beats::ZERO)));
|
||||
}
|
||||
|
||||
adjusted_moves.insert(*layer_id, adjusted_layer_moves);
|
||||
@@ -132,6 +136,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 +164,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
|
||||
@@ -184,7 +190,7 @@ impl Action for MoveClipInstancesAction {
|
||||
|
||||
fn execute_backend(&mut self, backend: &mut crate::action::BackendContext, document: &Document) -> Result<(), String> {
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::clip::AudioClipType;
|
||||
use crate::clip::ResolvedContent;
|
||||
|
||||
// Get audio controller
|
||||
let controller = match backend.audio_controller.as_mut() {
|
||||
@@ -204,9 +210,10 @@ impl Action for MoveClipInstancesAction {
|
||||
if let Some(instance) = vl.clip_instances.iter().find(|ci| ci.id == *instance_id) {
|
||||
// Check if this clip has a metatrack
|
||||
if let Some(&metatrack_id) = backend.layer_to_track_map.get(&instance.clip_id) {
|
||||
controller.set_offset(metatrack_id, *new_start);
|
||||
controller.set_trim_start(metatrack_id, instance.trim_start);
|
||||
controller.set_trim_end(metatrack_id, instance.trim_end);
|
||||
controller.set_offset(metatrack_id, document.tempo_map().beats_to_seconds(*new_start));
|
||||
// A vector clip's content is wall-clock, so its content times ARE seconds.
|
||||
controller.set_trim_start(metatrack_id, daw_backend::Seconds(instance.trim_start.raw()));
|
||||
controller.set_trim_end(metatrack_id, instance.trim_end.map(|t| daw_backend::Seconds(t.raw())));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -240,12 +247,12 @@ impl Action for MoveClipInstancesAction {
|
||||
.ok_or_else(|| format!("Audio clip {} not found", instance.clip_id))?;
|
||||
|
||||
// Handle move based on clip type
|
||||
match &clip.clip_type {
|
||||
AudioClipType::Midi { midi_clip_id } => {
|
||||
match &instance.resolve(clip) {
|
||||
ResolvedContent::Midi { midi_clip_id } => {
|
||||
// For MIDI: move_clip expects the pool clip ID
|
||||
controller.move_clip(*track_id, *midi_clip_id, *new_start);
|
||||
}
|
||||
AudioClipType::Sampled { .. } => {
|
||||
ResolvedContent::Audio { .. } => {
|
||||
// For sampled audio: move_clip expects the instance ID
|
||||
let backend_instance_id = backend.clip_instance_to_backend_map.get(instance_id)
|
||||
.ok_or_else(|| format!("Clip instance {} not mapped to backend", instance_id))?;
|
||||
@@ -257,7 +264,7 @@ impl Action for MoveClipInstancesAction {
|
||||
_ => return Err("Expected audio instance ID for sampled clip".to_string()),
|
||||
}
|
||||
}
|
||||
AudioClipType::Recording => {
|
||||
ResolvedContent::Recording => {
|
||||
// Recording clips cannot be moved - skip
|
||||
}
|
||||
}
|
||||
@@ -269,7 +276,7 @@ impl Action for MoveClipInstancesAction {
|
||||
|
||||
fn rollback_backend(&mut self, backend: &mut crate::action::BackendContext, document: &Document) -> Result<(), String> {
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::clip::AudioClipType;
|
||||
use crate::clip::ResolvedContent;
|
||||
|
||||
// Get audio controller
|
||||
let controller = match backend.audio_controller.as_mut() {
|
||||
@@ -288,9 +295,10 @@ impl Action for MoveClipInstancesAction {
|
||||
for (instance_id, old_start, _new_start) in moves {
|
||||
if let Some(instance) = vl.clip_instances.iter().find(|ci| ci.id == *instance_id) {
|
||||
if let Some(&metatrack_id) = backend.layer_to_track_map.get(&instance.clip_id) {
|
||||
controller.set_offset(metatrack_id, *old_start);
|
||||
controller.set_trim_start(metatrack_id, instance.trim_start);
|
||||
controller.set_trim_end(metatrack_id, instance.trim_end);
|
||||
controller.set_offset(metatrack_id, document.tempo_map().beats_to_seconds(*old_start));
|
||||
// A vector clip's content is wall-clock, so its content times ARE seconds.
|
||||
controller.set_trim_start(metatrack_id, daw_backend::Seconds(instance.trim_start.raw()));
|
||||
controller.set_trim_end(metatrack_id, instance.trim_end.map(|t| daw_backend::Seconds(t.raw())));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -324,12 +332,12 @@ impl Action for MoveClipInstancesAction {
|
||||
.ok_or_else(|| format!("Audio clip {} not found", instance.clip_id))?;
|
||||
|
||||
// Handle move based on clip type (restore old position)
|
||||
match &clip.clip_type {
|
||||
AudioClipType::Midi { midi_clip_id } => {
|
||||
match &instance.resolve(clip) {
|
||||
ResolvedContent::Midi { midi_clip_id } => {
|
||||
// For MIDI: move_clip expects the pool clip ID
|
||||
controller.move_clip(*track_id, *midi_clip_id, *old_start);
|
||||
}
|
||||
AudioClipType::Sampled { .. } => {
|
||||
ResolvedContent::Audio { .. } => {
|
||||
// For sampled audio: move_clip expects the instance ID
|
||||
let backend_instance_id = backend.clip_instance_to_backend_map.get(instance_id)
|
||||
.ok_or_else(|| format!("Clip instance {} not mapped to backend", instance_id))?;
|
||||
@@ -341,7 +349,7 @@ impl Action for MoveClipInstancesAction {
|
||||
_ => return Err("Expected audio instance ID for sampled clip".to_string()),
|
||||
}
|
||||
}
|
||||
AudioClipType::Recording => {
|
||||
ResolvedContent::Recording => {
|
||||
// Recording clips cannot be moved - skip
|
||||
}
|
||||
}
|
||||
@@ -369,15 +377,15 @@ mod tests {
|
||||
let mut vector_layer = VectorLayer::new("Layer 1");
|
||||
|
||||
let mut clip_instance = ClipInstance::new(clip_id);
|
||||
clip_instance.timeline_start = 1.0; // Start at 1 second
|
||||
clip_instance.timeline_start = Beats(1.0); // Start at beat 1
|
||||
let instance_id = clip_instance.id;
|
||||
vector_layer.clip_instances.push(clip_instance);
|
||||
|
||||
let layer_id = document.root.add_child(AnyLayer::Vector(vector_layer));
|
||||
|
||||
// Create move action: move from 1.0 to 5.0 seconds
|
||||
// Create move action: move from beat 1 to beat 5
|
||||
let mut layer_moves = HashMap::new();
|
||||
layer_moves.insert(layer_id, vec![(instance_id, 1.0, 5.0)]);
|
||||
layer_moves.insert(layer_id, vec![(instance_id, Beats(1.0), Beats(5.0))]);
|
||||
|
||||
let mut action = MoveClipInstancesAction::new(layer_moves);
|
||||
|
||||
@@ -391,7 +399,7 @@ mod tests {
|
||||
.iter()
|
||||
.find(|ci| ci.id == instance_id)
|
||||
.unwrap();
|
||||
assert_eq!(instance.timeline_start, 5.0);
|
||||
assert_eq!(instance.timeline_start, Beats(5.0));
|
||||
}
|
||||
|
||||
// Rollback
|
||||
@@ -404,7 +412,7 @@ mod tests {
|
||||
.iter()
|
||||
.find(|ci| ci.id == instance_id)
|
||||
.unwrap();
|
||||
assert_eq!(instance.timeline_start, 1.0);
|
||||
assert_eq!(instance.timeline_start, Beats(1.0));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
@@ -136,85 +138,23 @@ impl Action for RemoveClipInstancesAction {
|
||||
backend: &mut BackendContext,
|
||||
document: &Document,
|
||||
) -> Result<(), String> {
|
||||
use crate::clip::AudioClipType;
|
||||
if backend.audio_controller.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let controller = match backend.audio_controller.as_mut() {
|
||||
Some(c) => c,
|
||||
None => return Ok(()),
|
||||
};
|
||||
|
||||
// Re-add clips that were removed from backend
|
||||
for (layer_id, instance) in &self.saved {
|
||||
let layer = match document.get_layer(layer_id) {
|
||||
Some(l) => l,
|
||||
None => continue,
|
||||
};
|
||||
if !matches!(layer, AnyLayer::Audio(_)) {
|
||||
// Re-add the clips that were removed. `BackendContext::add_clip_instance` is the same
|
||||
// helper the add and split actions use, so the trim/duration conversions (and take-folder
|
||||
// resolution) stay in exactly one place instead of being copied into every action that has
|
||||
// to put a clip back.
|
||||
let saved = std::mem::take(&mut self.saved);
|
||||
for (layer_id, instance) in &saved {
|
||||
if !matches!(document.get_layer(layer_id), Some(AnyLayer::Audio(_))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let track_id = match backend.layer_to_track_map.get(layer_id) {
|
||||
Some(id) => *id,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
let clip = match document.get_audio_clip(&instance.clip_id) {
|
||||
Some(c) => c,
|
||||
None => continue,
|
||||
};
|
||||
|
||||
match &clip.clip_type {
|
||||
AudioClipType::Midi { midi_clip_id } => {
|
||||
use daw_backend::command::{Query, QueryResponse};
|
||||
|
||||
let internal_start = instance.trim_start;
|
||||
let internal_end = instance.trim_end.unwrap_or(clip.duration);
|
||||
let external_start = instance.timeline_start;
|
||||
let external_duration = instance
|
||||
.timeline_duration
|
||||
.unwrap_or(internal_end - internal_start);
|
||||
|
||||
let midi_instance = daw_backend::MidiClipInstance::new(
|
||||
0,
|
||||
*midi_clip_id,
|
||||
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);
|
||||
if let Ok(QueryResponse::MidiClipInstanceAdded(Ok(new_id))) =
|
||||
controller.send_query(query)
|
||||
{
|
||||
backend.clip_instance_to_backend_map.insert(
|
||||
instance.id,
|
||||
BackendClipInstanceId::Midi(new_id),
|
||||
);
|
||||
}
|
||||
}
|
||||
AudioClipType::Sampled { audio_pool_index } => {
|
||||
let internal_start = instance.trim_start;
|
||||
let internal_end = instance.trim_end.unwrap_or(clip.duration);
|
||||
let effective_duration = instance.timeline_duration
|
||||
.unwrap_or(internal_end - internal_start);
|
||||
let start_time = instance.timeline_start;
|
||||
|
||||
let new_id = controller.add_audio_clip(
|
||||
track_id,
|
||||
*audio_pool_index,
|
||||
start_time,
|
||||
effective_duration,
|
||||
internal_start,
|
||||
);
|
||||
backend.clip_instance_to_backend_map.insert(
|
||||
instance.id,
|
||||
BackendClipInstanceId::Audio(new_id),
|
||||
);
|
||||
}
|
||||
AudioClipType::Recording => {}
|
||||
}
|
||||
// A missing track/clip just means there's nothing to restore on the backend.
|
||||
let _ = backend.add_clip_instance(document, layer_id, instance);
|
||||
}
|
||||
self.saved = saved;
|
||||
|
||||
// Clear saved backend IDs
|
||||
self.saved_backend_ids.clear();
|
||||
@@ -236,11 +176,11 @@ mod tests {
|
||||
let mut vector_layer = VectorLayer::new("Layer 1");
|
||||
|
||||
let mut ci1 = ClipInstance::new(clip_id);
|
||||
ci1.timeline_start = 0.0;
|
||||
ci1.timeline_start = daw_backend::Beats::ZERO;
|
||||
let id1 = ci1.id;
|
||||
|
||||
let mut ci2 = ClipInstance::new(clip_id);
|
||||
ci2.timeline_start = 5.0;
|
||||
ci2.timeline_start = daw_backend::Beats(5.0);
|
||||
let id2 = ci2.id;
|
||||
|
||||
vector_layer.clip_instances.push(ci1);
|
||||
|
||||
@@ -134,7 +134,7 @@ mod tests {
|
||||
let (mut document, layer_id, def) = create_test_setup();
|
||||
|
||||
// Add an effect first
|
||||
let instance = def.create_instance(0.0, 10.0);
|
||||
let instance = def.create_instance(daw_backend::Beats(0.0), daw_backend::Beats(10.0));
|
||||
let instance_id = instance.id;
|
||||
|
||||
if let Some(AnyLayer::Effect(el)) = document.get_layer_mut(&layer_id) {
|
||||
@@ -161,7 +161,7 @@ mod tests {
|
||||
let (mut document, layer_id, def) = create_test_setup();
|
||||
|
||||
// Add an effect first
|
||||
let instance = def.create_instance(0.0, 10.0);
|
||||
let instance = def.create_instance(daw_backend::Beats(0.0), daw_backend::Beats(10.0));
|
||||
let instance_id = instance.id;
|
||||
|
||||
if let Some(AnyLayer::Effect(el)) = document.get_layer_mut(&layer_id) {
|
||||
@@ -185,11 +185,11 @@ mod tests {
|
||||
let (mut document, layer_id, def) = create_test_setup();
|
||||
|
||||
// Add three effects
|
||||
let instance1 = def.create_instance(0.0, 10.0);
|
||||
let instance1 = def.create_instance(daw_backend::Beats(0.0), daw_backend::Beats(10.0));
|
||||
let id1 = instance1.id;
|
||||
let instance2 = def.create_instance(0.0, 10.0);
|
||||
let instance2 = def.create_instance(daw_backend::Beats(0.0), daw_backend::Beats(10.0));
|
||||
let id2 = instance2.id;
|
||||
let instance3 = def.create_instance(0.0, 10.0);
|
||||
let instance3 = def.create_instance(daw_backend::Beats(0.0), daw_backend::Beats(10.0));
|
||||
let id3 = instance3.id;
|
||||
|
||||
if let Some(AnyLayer::Effect(el)) = document.get_layer_mut(&layer_id) {
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//! Choose which take of a take-folder clip an instance plays.
|
||||
//!
|
||||
//! The take list lives on the *clip* but the selection lives on the *instance*, so two instances of
|
||||
//! the same folder can play different takes. Splitting a take-folder instance clones it, which is
|
||||
//! what makes comping work: set take 1 on the left half and take 3 on the right, and you've comped.
|
||||
//!
|
||||
//! There's no in-place pool-swap command in the backend, so switching a take means removing the
|
||||
//! instance's backend clip and re-adding it against the new take's audio/MIDI resource. Both halves
|
||||
//! of that go through `BackendContext`, which is also what `AddClipInstanceAction` uses.
|
||||
|
||||
use crate::action::{Action, BackendClipInstanceId, BackendContext};
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Action that points a clip instance at a different take of its take folder.
|
||||
#[derive(Clone)]
|
||||
pub struct SetActiveTakeAction {
|
||||
layer_id: Uuid,
|
||||
instance_id: Uuid,
|
||||
new_take: Option<usize>,
|
||||
old_take: Option<usize>,
|
||||
/// The backend track/clip the instance was on before we swapped, so rollback can undo it.
|
||||
backend_track_id: Option<daw_backend::TrackId>,
|
||||
}
|
||||
|
||||
impl SetActiveTakeAction {
|
||||
pub fn new(layer_id: Uuid, instance_id: Uuid, new_take: usize, old_take: Option<usize>) -> Self {
|
||||
Self {
|
||||
layer_id,
|
||||
instance_id,
|
||||
new_take: Some(new_take),
|
||||
old_take,
|
||||
backend_track_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Point the instance at `take`, mutating the document. Shared by execute and rollback.
|
||||
fn apply(&self, document: &mut Document, take: Option<usize>) -> Result<(), String> {
|
||||
let layer = document
|
||||
.get_layer_mut(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
|
||||
let AnyLayer::Audio(audio_layer) = layer else {
|
||||
return Err("Take folders only exist on audio layers".to_string());
|
||||
};
|
||||
let instance = audio_layer
|
||||
.clip_instances
|
||||
.iter_mut()
|
||||
.find(|ci| ci.id == self.instance_id)
|
||||
.ok_or_else(|| format!("Clip instance {} not found", self.instance_id))?;
|
||||
instance.active_take = take;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Swap the instance's backend clip to whatever take the document now says is active.
|
||||
///
|
||||
/// Called after the document has already been mutated, so re-adding just re-resolves the
|
||||
/// instance — `BackendContext::add_clip_instance` reads `active_take` itself.
|
||||
fn resync(&mut self, backend: &mut BackendContext, document: &Document) -> Result<(), String> {
|
||||
let instance = document
|
||||
.get_layer(&self.layer_id)
|
||||
.and_then(|l| match l {
|
||||
AnyLayer::Audio(al) => al.clip_instances.iter().find(|ci| ci.id == self.instance_id),
|
||||
_ => None,
|
||||
})
|
||||
.cloned()
|
||||
.ok_or_else(|| format!("Clip instance {} not found", self.instance_id))?;
|
||||
|
||||
// Drop the old backend clip first. Its track comes from the map we're about to overwrite,
|
||||
// so read it before add_clip_instance replaces the entry.
|
||||
let existing: Option<BackendClipInstanceId> = backend
|
||||
.clip_instance_to_backend_map
|
||||
.get(&self.instance_id)
|
||||
.copied();
|
||||
let track_id = backend.layer_to_track_map.get(&self.layer_id).copied();
|
||||
if let (Some(backend_id), Some(track_id)) = (existing, track_id) {
|
||||
backend.remove_clip_instance(track_id, backend_id, self.instance_id);
|
||||
}
|
||||
|
||||
let added = backend.add_clip_instance(document, &self.layer_id, &instance)?;
|
||||
self.backend_track_id = added.map(|(track_id, _)| track_id);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for SetActiveTakeAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
self.apply(document, self.new_take)
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
self.apply(document, self.old_take)
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
match self.new_take {
|
||||
Some(i) => format!("Select take {}", i + 1),
|
||||
None => "Select take".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn execute_backend(
|
||||
&mut self,
|
||||
backend: &mut BackendContext,
|
||||
document: &Document,
|
||||
) -> Result<(), String> {
|
||||
self.resync(backend, document)
|
||||
}
|
||||
|
||||
fn rollback_backend(
|
||||
&mut self,
|
||||
backend: &mut BackendContext,
|
||||
document: &Document,
|
||||
) -> Result<(), String> {
|
||||
self.resync(backend, document)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
//! Set the transport cycle (loop) region.
|
||||
//!
|
||||
//! The cycle region is document state (it's saved in the `.beam`), so changing it goes through the
|
||||
//! action system like any other edit: it's undoable and it marks the document modified.
|
||||
//!
|
||||
//! The region is stored in **beats** so it stays put musically across tempo changes. Callers commit
|
||||
//! one action per gesture (e.g. on drag release, or a toggle click) rather than one per frame —
|
||||
//! the timeline previews the drag from its own local state, exactly like a clip drag does.
|
||||
|
||||
use crate::action::{Action, BackendContext};
|
||||
use crate::document::Document;
|
||||
use daw_backend::Beats;
|
||||
|
||||
/// Action that sets the cycle region and/or whether the transport loops over it.
|
||||
#[derive(Clone)]
|
||||
pub struct SetCycleRegionAction {
|
||||
old_region: Option<(Beats, Beats)>,
|
||||
old_enabled: bool,
|
||||
new_region: Option<(Beats, Beats)>,
|
||||
new_enabled: bool,
|
||||
}
|
||||
|
||||
impl SetCycleRegionAction {
|
||||
/// Build from the document's current state and the desired new region/enabled flag.
|
||||
pub fn new(
|
||||
document: &Document,
|
||||
new_region: Option<(Beats, Beats)>,
|
||||
new_enabled: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
old_region: document.cycle_region,
|
||||
old_enabled: document.cycle_enabled,
|
||||
new_region,
|
||||
new_enabled,
|
||||
}
|
||||
}
|
||||
|
||||
/// Toggle looping on/off, leaving the region itself alone.
|
||||
pub fn toggle_enabled(document: &Document) -> Self {
|
||||
Self::new(document, document.cycle_region, !document.cycle_enabled)
|
||||
}
|
||||
|
||||
/// True if this action would not actually change anything (lets callers skip a no-op undo entry).
|
||||
pub fn is_noop(&self) -> bool {
|
||||
self.old_region == self.new_region && self.old_enabled == self.new_enabled
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for SetCycleRegionAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
document.cycle_region = self.new_region;
|
||||
document.cycle_enabled = self.new_enabled;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
document.cycle_region = self.old_region;
|
||||
document.cycle_enabled = self.old_enabled;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
"Set cycle region".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_loop_region(self.new_region);
|
||||
controller.set_loop_enabled(self.new_enabled);
|
||||
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_loop_region(self.old_region);
|
||||
controller.set_loop_enabled(self.old_enabled);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -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,23 @@ 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) {
|
||||
// `start` is a keyframe time in seconds; group_visibility_start returns seconds,
|
||||
// so the fallback must convert the clip's beats start to seconds too.
|
||||
let start = vl
|
||||
.group_visibility_start(clip_id, self.time)
|
||||
.unwrap_or_else(|| document.tempo_map().beats_to_seconds(ci.timeline_start).seconds_to_f64());
|
||||
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 +106,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 +183,86 @@ impl Action for SetKeyframeAction {
|
||||
"New keyframe".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::actions::TransformClipInstancesAction;
|
||||
use crate::clip::ClipInstance;
|
||||
use crate::layer::VectorLayer;
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn x_curve_eval(document: &Document, layer_id: Uuid, instance_id: Uuid, time: f64) -> f64 {
|
||||
let target = AnimationTarget::Object { id: instance_id, property: TransformProperty::X };
|
||||
match document.get_layer(&layer_id) {
|
||||
Some(AnyLayer::Vector(vl)) => vl.layer.animation_data.eval(&target, time, f64::NAN),
|
||||
_ => panic!("no layer"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_keyframe_then_move_does_not_disturb_earlier_frames() {
|
||||
// Group created at frame 0 (clip at x=50), keyframe + move at frame 10 → x=200.
|
||||
// Frame 0 must keep x=50 (the motion-tween first-keyframe bug: it used to become 200).
|
||||
let mut document = Document::new("Test");
|
||||
let mut layer = VectorLayer::new("Layer");
|
||||
let clip_id = Uuid::new_v4();
|
||||
let instance_id = Uuid::new_v4();
|
||||
let mut instance = ClipInstance::with_id(instance_id, clip_id);
|
||||
instance.transform = Transform::with_position(50.0, 50.0);
|
||||
layer.clip_instances.push(instance);
|
||||
// The group's visibility starts at a keyframe at time 0 containing the instance.
|
||||
layer.ensure_keyframe_at(0.0).clip_instance_ids.push(instance_id);
|
||||
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
|
||||
|
||||
// Create a keyframe at frame 10.
|
||||
SetKeyframeAction::new(layer_id, 10.0, vec![instance_id])
|
||||
.execute(&mut document)
|
||||
.unwrap();
|
||||
|
||||
// The new curve must be anchored at the start (two keyframes, both at x=50 so far).
|
||||
assert!((x_curve_eval(&document, layer_id, instance_id, 0.0) - 50.0).abs() < 1e-6);
|
||||
assert!((x_curve_eval(&document, layer_id, instance_id, 10.0) - 50.0).abs() < 1e-6);
|
||||
|
||||
// Move the clip at frame 10 to x=200.
|
||||
let mut transforms = HashMap::new();
|
||||
transforms.insert(
|
||||
instance_id,
|
||||
(Transform::with_position(50.0, 50.0), Transform::with_position(200.0, 200.0)),
|
||||
);
|
||||
TransformClipInstancesAction::new(layer_id, 10.0, transforms)
|
||||
.execute(&mut document)
|
||||
.unwrap();
|
||||
|
||||
// Frame 0 unchanged; frame 10 moved; midpoint tweens.
|
||||
assert!((x_curve_eval(&document, layer_id, instance_id, 0.0) - 50.0).abs() < 1e-6, "frame 0 must stay 50");
|
||||
assert!((x_curve_eval(&document, layer_id, instance_id, 10.0) - 200.0).abs() < 1e-6, "frame 10 must be 200");
|
||||
assert!((x_curve_eval(&document, layer_id, instance_id, 5.0) - 125.0).abs() < 1e-6, "midpoint tweens");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_keyframe_at_clip_start_is_not_double_anchored() {
|
||||
// When the keyframe is created at the clip's own start, there's nothing earlier to
|
||||
// anchor — a single keyframe is correct.
|
||||
let mut document = Document::new("Test");
|
||||
let mut layer = VectorLayer::new("Layer");
|
||||
let clip_id = Uuid::new_v4();
|
||||
let instance_id = Uuid::new_v4();
|
||||
let mut instance = ClipInstance::with_id(instance_id, clip_id);
|
||||
instance.transform = Transform::with_position(10.0, 0.0);
|
||||
layer.clip_instances.push(instance);
|
||||
layer.ensure_keyframe_at(0.0).clip_instance_ids.push(instance_id);
|
||||
let layer_id = document.root_mut().add_child(AnyLayer::Vector(layer));
|
||||
|
||||
SetKeyframeAction::new(layer_id, 0.0, vec![instance_id])
|
||||
.execute(&mut document)
|
||||
.unwrap();
|
||||
|
||||
let target = AnimationTarget::Object { id: instance_id, property: TransformProperty::X };
|
||||
if let Some(AnyLayer::Vector(vl)) = document.get_layer(&layer_id) {
|
||||
let curve = vl.layer.animation_data.get_curve(&target).unwrap();
|
||||
assert_eq!(curve.keyframes.len(), 1, "keyframe at clip start needs no anchor");
|
||||
assert!((curve.eval(0.0) - 10.0).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Set-text-content action
|
||||
//!
|
||||
//! Replaces a text layer's [`TextContent`] (text string, font size, color, family,
|
||||
//! alignment) as one undoable step. Used both by in-place editing (text changes)
|
||||
//! and the info panel (style changes).
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::text_layer::TextContent;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct SetTextContentAction {
|
||||
layer_id: Uuid,
|
||||
new: TextContent,
|
||||
old: Option<TextContent>,
|
||||
}
|
||||
|
||||
impl SetTextContentAction {
|
||||
pub fn new(layer_id: Uuid, new: TextContent) -> Self {
|
||||
Self { layer_id, new, old: None }
|
||||
}
|
||||
|
||||
/// Construct with an explicit `old` value. Used by in-place editing, which mutates
|
||||
/// the document live for preview and then records one undoable step capturing the
|
||||
/// content as it was *before* editing began.
|
||||
pub fn with_old(layer_id: Uuid, old: TextContent, new: TextContent) -> Self {
|
||||
Self { layer_id, new, old: Some(old) }
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for SetTextContentAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let layer = document
|
||||
.get_layer_mut(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
|
||||
let AnyLayer::Text(text_layer) = layer else {
|
||||
return Err("SetTextContentAction target is not a text layer".to_string());
|
||||
};
|
||||
if self.old.is_none() {
|
||||
self.old = Some(text_layer.content.clone());
|
||||
}
|
||||
text_layer.content = self.new.clone();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
let Some(old) = self.old.clone() else { return Ok(()) };
|
||||
let layer = document
|
||||
.get_layer_mut(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
|
||||
if let AnyLayer::Text(text_layer) = layer {
|
||||
text_layer.content = old;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
"Edit text".to_string()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
//! Set the tween type on the keyframe at-or-before a time (e.g. "Add Shape Tween").
|
||||
//!
|
||||
//! The keyframe's `tween_after` controls how the span between it and the next keyframe is
|
||||
//! rendered: `None` holds, `Shape` morphs the geometry (when the two keyframes share
|
||||
//! topology — otherwise rendering falls back to holding).
|
||||
|
||||
use crate::action::Action;
|
||||
use crate::document::Document;
|
||||
use crate::layer::{AnyLayer, TweenType};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct SetTweenAction {
|
||||
layer_id: Uuid,
|
||||
time: f64,
|
||||
new_tween: TweenType,
|
||||
old_tween: Option<TweenType>,
|
||||
}
|
||||
|
||||
impl SetTweenAction {
|
||||
pub fn new(layer_id: Uuid, time: f64, new_tween: TweenType) -> Self {
|
||||
Self { layer_id, time, new_tween, old_tween: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Action for SetTweenAction {
|
||||
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
if let Some(AnyLayer::Vector(vl)) = document.get_layer_mut(&self.layer_id) {
|
||||
if let Some(kf) = vl.keyframe_at_mut(self.time) {
|
||||
self.old_tween = Some(kf.tween_after);
|
||||
kf.tween_after = self.new_tween;
|
||||
} else {
|
||||
return Err("No keyframe at-or-before this time".to_string());
|
||||
}
|
||||
} else {
|
||||
return Err("Not a vector layer".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
|
||||
if let (Some(old), Some(AnyLayer::Vector(vl))) =
|
||||
(self.old_tween, document.get_layer_mut(&self.layer_id))
|
||||
{
|
||||
if let Some(kf) = vl.keyframe_at_mut(self.time) {
|
||||
kf.tween_after = old;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn description(&self) -> String {
|
||||
match self.new_tween {
|
||||
TweenType::Shape => "Add shape tween".to_string(),
|
||||
TweenType::None => "Remove tween".to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use crate::action::{Action, BackendContext};
|
||||
use crate::clip::ClipInstance;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use daw_backend::ContentTime;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Action that splits a clip instance at a specific timeline position
|
||||
@@ -17,17 +18,17 @@ pub struct SplitClipInstanceAction {
|
||||
/// The clip instance to split
|
||||
instance_id: Uuid,
|
||||
|
||||
/// Timeline time where to split (in seconds)
|
||||
split_time: f64,
|
||||
/// Timeline position where to split (in beats)
|
||||
split_time: daw_backend::Beats,
|
||||
|
||||
/// Whether the action has been executed (for rollback)
|
||||
executed: bool,
|
||||
|
||||
// Stored during execute for rollback
|
||||
/// Original trim_end value of the left (original) instance
|
||||
original_trim_end: Option<f64>,
|
||||
/// Original timeline_duration value of the left (original) instance
|
||||
original_timeline_duration: Option<f64>,
|
||||
original_trim_end: Option<ContentTime>,
|
||||
/// Original timeline_duration value of the left (original) instance (beats)
|
||||
original_timeline_duration: Option<daw_backend::Beats>,
|
||||
/// ID of the new (right) instance created by the split
|
||||
new_instance_id: Option<Uuid>,
|
||||
|
||||
@@ -47,8 +48,8 @@ impl SplitClipInstanceAction {
|
||||
///
|
||||
/// * `layer_id` - The ID of the layer containing the clip instance
|
||||
/// * `instance_id` - The ID of the clip instance to split
|
||||
/// * `split_time` - The timeline time (in seconds) where to split
|
||||
pub fn new(layer_id: Uuid, instance_id: Uuid, split_time: f64) -> Self {
|
||||
/// * `split_time` - The timeline position (in beats) where to split
|
||||
pub fn new(layer_id: Uuid, instance_id: Uuid, split_time: daw_backend::Beats) -> Self {
|
||||
Self {
|
||||
layer_id,
|
||||
instance_id,
|
||||
@@ -72,9 +73,9 @@ impl SplitClipInstanceAction {
|
||||
///
|
||||
/// * `layer_id` - The ID of the layer containing the clip instance
|
||||
/// * `instance_id` - The ID of the clip instance to split
|
||||
/// * `split_time` - The timeline time (in seconds) where to split
|
||||
/// * `split_time` - The timeline position (in beats) where to split
|
||||
/// * `new_instance_id` - The UUID to use for the new (right) clip instance
|
||||
pub fn with_new_instance_id(layer_id: Uuid, instance_id: Uuid, split_time: f64, new_instance_id: Uuid) -> Self {
|
||||
pub fn with_new_instance_id(layer_id: Uuid, instance_id: Uuid, split_time: daw_backend::Beats, new_instance_id: Uuid) -> Self {
|
||||
Self {
|
||||
layer_id,
|
||||
instance_id,
|
||||
@@ -114,6 +115,7 @@ impl Action for SplitClipInstanceAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => return Err("Cannot split clip instances on group layers".to_string()),
|
||||
AnyLayer::Raster(_) => return Err("Cannot split clip instances on group layers".to_string()),
|
||||
AnyLayer::Text(_) => return Err("Cannot split clip instances on group layers".to_string()),
|
||||
};
|
||||
|
||||
let instance = clip_instances
|
||||
@@ -121,19 +123,21 @@ impl Action for SplitClipInstanceAction {
|
||||
.find(|ci| ci.id == self.instance_id)
|
||||
.ok_or_else(|| format!("Clip instance {} not found", self.instance_id))?;
|
||||
|
||||
// Get the clip's duration
|
||||
let clip_duration = document
|
||||
.get_clip_duration(&instance.clip_id)
|
||||
// The clip's content duration in its OWN domain — seconds for audio/video/vector, beats for
|
||||
// MIDI. All the content math below is trim-domain, so it has to be done in whichever domain
|
||||
// this clip uses; a seconds duration would silently be added to a MIDI clip's beats trim.
|
||||
let trim_duration = document
|
||||
.clip_trim_duration(&instance.clip_id)
|
||||
.ok_or_else(|| format!("Clip {} not found", instance.clip_id))?;
|
||||
|
||||
// Calculate the effective duration and timeline end (both in beats)
|
||||
let effective_duration = instance.effective_duration(clip_duration, document.tempo_map());
|
||||
let effective_duration = instance.effective_duration(trim_duration, document.tempo_map());
|
||||
let timeline_end = instance.timeline_start + effective_duration;
|
||||
|
||||
// Validate: split_time must be strictly within the clip's timeline span
|
||||
const EPSILON: f64 = 0.001; // 1ms tolerance
|
||||
if self.split_time <= instance.timeline_start + EPSILON
|
||||
|| self.split_time >= timeline_end - EPSILON
|
||||
let epsilon = daw_backend::Beats(0.001); // ~1ms tolerance
|
||||
if self.split_time <= instance.timeline_start + epsilon
|
||||
|| self.split_time >= timeline_end - epsilon
|
||||
{
|
||||
return Err(format!(
|
||||
"Split time {} must be within clip bounds ({} to {})",
|
||||
@@ -145,21 +149,30 @@ impl Action for SplitClipInstanceAction {
|
||||
self.original_trim_end = instance.trim_end;
|
||||
self.original_timeline_duration = instance.timeline_duration;
|
||||
|
||||
// Check if this is a looping clip
|
||||
let is_looping = instance.timeline_duration.is_some();
|
||||
let content_duration = instance.trim_end.unwrap_or(clip_duration) - instance.trim_start;
|
||||
let content_duration = ContentTime(instance.content_window(trim_duration).native());
|
||||
|
||||
// Calculate the split point
|
||||
// Timeline split point (beats).
|
||||
let time_into_clip = self.split_time - instance.timeline_start;
|
||||
let left_duration = time_into_clip;
|
||||
let right_duration = effective_duration - left_duration;
|
||||
|
||||
// Calculate content split time
|
||||
let content_split_time = if is_looping {
|
||||
// How far the split lands into the clip's *content*, expressed in the content domain: beats
|
||||
// content takes the beats delta directly, wall-clock content takes the seconds delta.
|
||||
let tempo_map = document.tempo_map();
|
||||
let time_into_content = ContentTime(match trim_duration {
|
||||
crate::clip::ClipDuration::Beats(_) => time_into_clip.beats_to_f64(),
|
||||
crate::clip::ClipDuration::Seconds(_) => (tempo_map.beats_to_seconds(self.split_time)
|
||||
- tempo_map.beats_to_seconds(instance.timeline_start))
|
||||
.seconds_to_f64(),
|
||||
});
|
||||
|
||||
// Calculate the content split point (content domain).
|
||||
let content_split_time = if is_looping && content_duration > ContentTime::ZERO {
|
||||
// For looping clips, wrap around content
|
||||
instance.trim_start + (time_into_clip % content_duration)
|
||||
instance.trim_start + (time_into_content % content_duration)
|
||||
} else {
|
||||
instance.trim_start + time_into_clip
|
||||
instance.trim_start + time_into_content
|
||||
};
|
||||
|
||||
// Clone the instance for the right side
|
||||
@@ -233,7 +246,7 @@ impl Action for SplitClipInstanceAction {
|
||||
AnyLayer::Group(_) => {
|
||||
return Err("Cannot split clip instances on group layers".to_string());
|
||||
}
|
||||
AnyLayer::Raster(_) => {
|
||||
AnyLayer::Raster(_) | AnyLayer::Text(_) => {
|
||||
return Err("Cannot split clip instances on group layers".to_string());
|
||||
}
|
||||
}
|
||||
@@ -294,8 +307,8 @@ impl Action for SplitClipInstanceAction {
|
||||
AnyLayer::Group(_) => {
|
||||
// Group layers don't have clip instances, nothing to rollback
|
||||
}
|
||||
AnyLayer::Raster(_) => {
|
||||
// Raster layers don't have clip instances, nothing to rollback
|
||||
AnyLayer::Raster(_) | AnyLayer::Text(_) => {
|
||||
// Raster/text layers don't have clip instances, nothing to rollback
|
||||
}
|
||||
}
|
||||
|
||||
@@ -350,112 +363,63 @@ impl Action for SplitClipInstanceAction {
|
||||
.get_audio_clip(&new_instance.clip_id)
|
||||
.ok_or_else(|| "Audio clip not found".to_string())?;
|
||||
|
||||
// Look up backend track ID from layer mapping
|
||||
let backend_track_id = backend
|
||||
use crate::clip::ResolvedContent;
|
||||
if matches!(original_instance.resolve(clip), ResolvedContent::Recording) {
|
||||
return Err("Cannot split a clip that is currently recording".to_string());
|
||||
}
|
||||
|
||||
// A split is: shorten the left half's backend clip, then add the right half as a new one.
|
||||
//
|
||||
// 1. Trim the left (original) instance. `trim_range` tags the bounds with the clip's own
|
||||
// content domain, so a MIDI clip's beats trims can't be sent as seconds.
|
||||
let left_trim = clip.trim_range(
|
||||
original_instance.trim_start,
|
||||
original_instance
|
||||
.trim_end
|
||||
.unwrap_or(ContentTime(clip.content_duration().native())),
|
||||
);
|
||||
let new_instance = new_instance.clone();
|
||||
|
||||
let backend_track_id = *backend
|
||||
.layer_to_track_map
|
||||
.get(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not mapped to backend track", self.layer_id))?;
|
||||
let left_backend_id = backend
|
||||
.clip_instance_to_backend_map
|
||||
.get(&self.instance_id)
|
||||
.copied();
|
||||
|
||||
// Get audio controller
|
||||
let controller = backend
|
||||
.audio_controller
|
||||
.as_mut()
|
||||
.ok_or_else(|| "Audio controller not available".to_string())?;
|
||||
|
||||
// Handle different clip types
|
||||
use crate::clip::AudioClipType;
|
||||
match &clip.clip_type {
|
||||
AudioClipType::Midi { midi_clip_id } => {
|
||||
use daw_backend::command::{Query, QueryResponse};
|
||||
|
||||
// 1. Trim the original (left) instance
|
||||
let orig_internal_start = original_instance.trim_start;
|
||||
let orig_internal_end = original_instance.trim_end.unwrap_or(clip.duration);
|
||||
|
||||
// Look up the original backend instance ID
|
||||
if let Some(crate::action::BackendClipInstanceId::Midi(orig_backend_id)) =
|
||||
backend.clip_instance_to_backend_map.get(&self.instance_id)
|
||||
{
|
||||
controller.trim_clip(*backend_track_id, *orig_backend_id, orig_internal_start, orig_internal_end);
|
||||
{
|
||||
let controller = backend
|
||||
.audio_controller
|
||||
.as_mut()
|
||||
.ok_or_else(|| "Audio controller not available".to_string())?;
|
||||
match left_backend_id {
|
||||
Some(crate::action::BackendClipInstanceId::Midi(id))
|
||||
| Some(crate::action::BackendClipInstanceId::Audio(id)) => {
|
||||
controller.trim_clip(backend_track_id, id, left_trim);
|
||||
}
|
||||
|
||||
// 2. Add the new (right) instance
|
||||
let internal_start = new_instance.trim_start;
|
||||
let internal_end = new_instance.trim_end.unwrap_or(clip.duration);
|
||||
let external_start = new_instance.timeline_start;
|
||||
let external_duration = new_instance
|
||||
.timeline_duration
|
||||
.unwrap_or(internal_end - internal_start);
|
||||
|
||||
let instance = daw_backend::MidiClipInstance::new(
|
||||
0,
|
||||
*midi_clip_id,
|
||||
daw_backend::Beats(internal_start),
|
||||
daw_backend::Beats(internal_end),
|
||||
daw_backend::Beats(external_start),
|
||||
daw_backend::Beats(external_duration),
|
||||
);
|
||||
|
||||
let query = Query::AddMidiClipInstanceSync(*backend_track_id, instance);
|
||||
|
||||
match controller.send_query(query)? {
|
||||
QueryResponse::MidiClipInstanceAdded(Ok(instance_id)) => {
|
||||
self.backend_track_id = Some(*backend_track_id);
|
||||
self.backend_midi_instance_id = Some(instance_id);
|
||||
|
||||
backend.clip_instance_to_backend_map.insert(
|
||||
new_instance_id,
|
||||
crate::action::BackendClipInstanceId::Midi(instance_id),
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
QueryResponse::MidiClipInstanceAdded(Err(e)) => Err(e),
|
||||
_ => Err("Unexpected query response".to_string()),
|
||||
}
|
||||
}
|
||||
AudioClipType::Sampled { audio_pool_index } => {
|
||||
// 1. Trim the original (left) instance
|
||||
let orig_internal_start = original_instance.trim_start;
|
||||
let orig_internal_end = original_instance.trim_end.unwrap_or(clip.duration);
|
||||
|
||||
// Look up the original backend instance ID
|
||||
if let Some(crate::action::BackendClipInstanceId::Audio(orig_backend_id)) =
|
||||
backend.clip_instance_to_backend_map.get(&self.instance_id)
|
||||
{
|
||||
controller.trim_clip(*backend_track_id, *orig_backend_id, orig_internal_start, orig_internal_end);
|
||||
}
|
||||
|
||||
// 2. Add the new (right) instance
|
||||
let internal_start = new_instance.trim_start;
|
||||
let internal_end = new_instance.trim_end.unwrap_or(clip.duration);
|
||||
let effective_duration = new_instance.timeline_duration
|
||||
.unwrap_or(internal_end - internal_start);
|
||||
let start_time = new_instance.timeline_start;
|
||||
|
||||
let instance_id = controller.add_audio_clip(
|
||||
*backend_track_id,
|
||||
*audio_pool_index,
|
||||
start_time,
|
||||
effective_duration,
|
||||
internal_start,
|
||||
);
|
||||
|
||||
self.backend_track_id = Some(*backend_track_id);
|
||||
self.backend_audio_instance_id = Some(instance_id);
|
||||
|
||||
backend.clip_instance_to_backend_map.insert(
|
||||
new_instance_id,
|
||||
crate::action::BackendClipInstanceId::Audio(instance_id),
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
AudioClipType::Recording => {
|
||||
// Recording clips cannot be split
|
||||
Err("Cannot split a clip that is currently recording".to_string())
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Add the right (new) instance via the shared helper — same one AddClipInstanceAction
|
||||
// uses, so the trim/duration conversions live in exactly one place.
|
||||
if let Some((track_id, backend_id)) =
|
||||
backend.add_clip_instance(document, &self.layer_id, &new_instance)?
|
||||
{
|
||||
self.backend_track_id = Some(track_id);
|
||||
match backend_id {
|
||||
crate::action::BackendClipInstanceId::Midi(id) => {
|
||||
self.backend_midi_instance_id = Some(id)
|
||||
}
|
||||
crate::action::BackendClipInstanceId::Audio(id) => {
|
||||
self.backend_audio_instance_id = Some(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rollback_backend(
|
||||
@@ -485,26 +449,28 @@ impl Action for SplitClipInstanceAction {
|
||||
if let Some(instance) = al.clip_instances.iter().find(|ci| ci.id == self.instance_id) {
|
||||
if let Some(clip) = document.get_audio_clip(&instance.clip_id) {
|
||||
let orig_internal_start = instance.trim_start;
|
||||
let orig_internal_end = self.original_trim_end.unwrap_or(clip.duration);
|
||||
let orig_internal_end = self
|
||||
.original_trim_end
|
||||
.unwrap_or(ContentTime(clip.content_duration().native()));
|
||||
|
||||
// Restore based on clip type
|
||||
use crate::clip::AudioClipType;
|
||||
match &clip.clip_type {
|
||||
AudioClipType::Midi { .. } => {
|
||||
use crate::clip::ResolvedContent;
|
||||
match &instance.resolve(clip) {
|
||||
ResolvedContent::Midi { .. } => {
|
||||
if let Some(crate::action::BackendClipInstanceId::Midi(orig_backend_id)) =
|
||||
backend.clip_instance_to_backend_map.get(&self.instance_id)
|
||||
{
|
||||
controller.trim_clip(track_id, *orig_backend_id, orig_internal_start, orig_internal_end);
|
||||
controller.trim_clip(track_id, *orig_backend_id, clip.trim_range(orig_internal_start, orig_internal_end));
|
||||
}
|
||||
}
|
||||
AudioClipType::Sampled { .. } => {
|
||||
ResolvedContent::Audio { .. } => {
|
||||
if let Some(crate::action::BackendClipInstanceId::Audio(orig_backend_id)) =
|
||||
backend.clip_instance_to_backend_map.get(&self.instance_id)
|
||||
{
|
||||
controller.trim_clip(track_id, *orig_backend_id, orig_internal_start, orig_internal_end);
|
||||
controller.trim_clip(track_id, *orig_backend_id, clip.trim_range(orig_internal_start, orig_internal_end));
|
||||
}
|
||||
}
|
||||
AudioClipType::Recording => {
|
||||
ResolvedContent::Recording => {
|
||||
// Recording clips - nothing to rollback
|
||||
}
|
||||
}
|
||||
@@ -539,16 +505,16 @@ mod tests {
|
||||
|
||||
// Create a clip instance at timeline 0, with trim 0-10 (10 seconds)
|
||||
let mut clip_instance = ClipInstance::new(clip_id);
|
||||
clip_instance.timeline_start = 0.0;
|
||||
clip_instance.trim_start = 0.0;
|
||||
clip_instance.trim_end = Some(10.0);
|
||||
clip_instance.timeline_start = daw_backend::Beats::ZERO;
|
||||
clip_instance.trim_start = ContentTime::ZERO;
|
||||
clip_instance.trim_end = Some(ContentTime(10.0));
|
||||
let instance_id = clip_instance.id;
|
||||
vector_layer.clip_instances.push(clip_instance);
|
||||
|
||||
let layer_id = document.root.add_child(AnyLayer::Vector(vector_layer));
|
||||
|
||||
// Split at timeline 5.0
|
||||
let mut action = SplitClipInstanceAction::new(layer_id, instance_id, 5.0);
|
||||
let mut action = SplitClipInstanceAction::new(layer_id, instance_id, daw_backend::Beats(5.0));
|
||||
|
||||
// Execute - this will fail because we don't have a real clip in the document
|
||||
// In a real test, we'd need to add a VectorClip first
|
||||
@@ -558,7 +524,45 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_split_action_description() {
|
||||
let action = SplitClipInstanceAction::new(Uuid::new_v4(), Uuid::new_v4(), 5.0);
|
||||
let action = SplitClipInstanceAction::new(Uuid::new_v4(), Uuid::new_v4(), daw_backend::Beats(5.0));
|
||||
assert_eq!(action.description(), "Split clip instance");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splitting_a_midi_clip_stays_in_the_beats_domain() {
|
||||
// Regression: `trim_start`/`trim_end` are domain-polymorphic — SECONDS for audio/video/
|
||||
// vector, but BEATS for MIDI (the backend takes MIDI trims as `Beats`). Split used to map
|
||||
// the split point into the clip's content in seconds unconditionally, so on a MIDI clip it
|
||||
// added a seconds delta to a beats offset. At anything but 60 BPM the right half started at
|
||||
// the wrong place in the content.
|
||||
//
|
||||
// At 120 BPM, beat 4 is 2 SECONDS in. The right half must trim to beat 4, not "4 seconds"
|
||||
// (= beat 8) and not 2 (the seconds value).
|
||||
let mut document = Document::new("Test");
|
||||
document.set_bpm(120.0);
|
||||
|
||||
// 8-beat MIDI clip at the timeline origin.
|
||||
let clip = crate::clip::AudioClip::new_midi("Midi", 1, daw_backend::Beats(8.0));
|
||||
let clip_id = document.add_audio_clip(clip);
|
||||
|
||||
let mut audio_layer = crate::layer::AudioLayer::new("Layer 1");
|
||||
let mut instance = ClipInstance::new(clip_id);
|
||||
instance.timeline_start = daw_backend::Beats::ZERO;
|
||||
instance.trim_start = ContentTime::ZERO;
|
||||
instance.trim_end = Some(ContentTime(8.0)); // beats
|
||||
let instance_id = instance.id;
|
||||
audio_layer.clip_instances.push(instance);
|
||||
let layer_id = document.root.add_child(AnyLayer::Audio(audio_layer));
|
||||
|
||||
let mut action = SplitClipInstanceAction::new(layer_id, instance_id, daw_backend::Beats(4.0));
|
||||
action.execute(&mut document).expect("split");
|
||||
let new_id = action.new_instance_id().expect("right instance");
|
||||
|
||||
let AnyLayer::Audio(al) = document.get_layer(&layer_id).unwrap() else { panic!() };
|
||||
let right = al.clip_instances.iter().find(|ci| ci.id == new_id).unwrap();
|
||||
let left = al.clip_instances.iter().find(|ci| ci.id == instance_id).unwrap();
|
||||
|
||||
assert_eq!(right.trim_start, ContentTime(4.0), "right half must start 4 BEATS into the content");
|
||||
assert_eq!(left.trim_end, Some(ContentTime(4.0)), "left half must end 4 BEATS into the content");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -101,6 +101,7 @@ impl Action for TransformClipInstancesAction {
|
||||
AnyLayer::Effect(_) => {}
|
||||
AnyLayer::Group(_) => {}
|
||||
AnyLayer::Raster(_) => {}
|
||||
AnyLayer::Text(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -140,6 +141,7 @@ impl Action for TransformClipInstancesAction {
|
||||
AnyLayer::Effect(_) => {}
|
||||
AnyLayer::Group(_) => {}
|
||||
AnyLayer::Raster(_) => {}
|
||||
AnyLayer::Text(_) => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ use crate::action::Action;
|
||||
use crate::clip::ClipInstance;
|
||||
use crate::document::Document;
|
||||
use crate::layer::AnyLayer;
|
||||
use daw_backend::{Beats, ContentTime, Seconds};
|
||||
use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
@@ -31,15 +32,57 @@ pub struct TrimClipInstancesAction {
|
||||
pub struct TrimData {
|
||||
/// For TrimLeft: trim_start value
|
||||
/// For TrimRight: trim_end value (Option because it can be None)
|
||||
pub trim_value: Option<f64>,
|
||||
/// For TrimLeft: timeline_start value (where the clip appears on timeline)
|
||||
///
|
||||
/// A content time — measured in the clip's own domain (seconds for audio/video/vector, beats
|
||||
/// for MIDI), so it must be resolved against the clip before meeting a timeline position.
|
||||
pub trim_value: Option<ContentTime>,
|
||||
/// For TrimLeft: timeline_start value (where the clip appears on timeline, beats)
|
||||
/// For TrimRight: unused (None)
|
||||
pub timeline_start: Option<f64>,
|
||||
pub timeline_start: Option<Beats>,
|
||||
}
|
||||
|
||||
/// A wall-clock gap on the timeline, expressed in a clip's content domain.
|
||||
///
|
||||
/// Trim validation clamps how far a clip may be dragged against the empty space next to it, and that
|
||||
/// space is measured on the timeline (seconds) while the trim lives in the clip's content domain. For
|
||||
/// wall-clock content they're the same number; for MIDI (beats content) the gap has to be converted
|
||||
/// at the clip's position, or a seconds gap silently clamps a beats trim.
|
||||
fn gap_to_content(
|
||||
gap: Seconds,
|
||||
clip_content: crate::clip::ClipDuration,
|
||||
timeline_start: Beats,
|
||||
tempo_map: &crate::tempo_map::TempoMap,
|
||||
) -> ContentTime {
|
||||
match clip_content {
|
||||
crate::clip::ClipDuration::Seconds(_) => ContentTime(gap.seconds_to_f64()),
|
||||
crate::clip::ClipDuration::Beats(_) => {
|
||||
let beats = tempo_map
|
||||
.seconds_to_beats(tempo_map.beats_to_seconds(timeline_start) + gap)
|
||||
- timeline_start;
|
||||
ContentTime(beats.beats_to_f64())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The inverse: a content-domain span as wall-clock seconds at the clip's position.
|
||||
fn content_to_secs(
|
||||
span: ContentTime,
|
||||
clip_content: crate::clip::ClipDuration,
|
||||
timeline_start: Beats,
|
||||
tempo_map: &crate::tempo_map::TempoMap,
|
||||
) -> Seconds {
|
||||
match clip_content {
|
||||
crate::clip::ClipDuration::Seconds(_) => Seconds(span.raw()),
|
||||
crate::clip::ClipDuration::Beats(_) => {
|
||||
tempo_map.beats_to_seconds(timeline_start + Beats(span.raw()))
|
||||
- tempo_map.beats_to_seconds(timeline_start)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TrimData {
|
||||
/// Create TrimData for left trim
|
||||
pub fn left(trim_start: f64, timeline_start: f64) -> Self {
|
||||
pub fn left(trim_start: ContentTime, timeline_start: Beats) -> Self {
|
||||
Self {
|
||||
trim_value: Some(trim_start),
|
||||
timeline_start: Some(timeline_start),
|
||||
@@ -47,7 +90,7 @@ impl TrimData {
|
||||
}
|
||||
|
||||
/// Create TrimData for right trim
|
||||
pub fn right(trim_end: Option<f64>) -> Self {
|
||||
pub fn right(trim_end: Option<ContentTime>) -> Self {
|
||||
Self {
|
||||
trim_value: trim_end,
|
||||
timeline_start: None,
|
||||
@@ -101,6 +144,7 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
if let Some(instance) = clip_instances.iter().find(|ci| ci.id == *member_instance_id) {
|
||||
@@ -138,6 +182,7 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
if let Some(instance) = clip_instances.iter().find(|ci| ci.id == *member_instance_id) {
|
||||
@@ -182,13 +227,15 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
let instance = clip_instances.iter()
|
||||
.find(|ci| &ci.id == instance_id)
|
||||
.ok_or_else(|| format!("Instance {} not found", instance_id))?;
|
||||
|
||||
let clip_duration = document.get_clip_duration(&instance.clip_id)
|
||||
// The clip's content duration in ITS OWN domain, so trims resolve correctly for MIDI.
|
||||
let clip_content = document.clip_trim_duration(&instance.clip_id)
|
||||
.ok_or_else(|| format!("Clip {} not found", instance.clip_id))?;
|
||||
|
||||
let mut clamped_new = new.clone();
|
||||
@@ -200,51 +247,74 @@ impl Action for TrimClipInstancesAction {
|
||||
{
|
||||
// If extending to the left (new_trim < old_trim)
|
||||
if should_validate && new_trim < old_trim {
|
||||
// Find the maximum we can extend left
|
||||
let max_extend = document.find_max_trim_extend_left(
|
||||
layer_id,
|
||||
instance_id,
|
||||
let tempo_map = document.tempo_map();
|
||||
|
||||
// Max leftward extension: the gap's wall-clock span, converted into
|
||||
// the clip's content domain so it can clamp a content-domain trim.
|
||||
let max_extend = gap_to_content(
|
||||
document.find_max_trim_extend_left(
|
||||
layer_id,
|
||||
instance_id,
|
||||
instance.timeline_start,
|
||||
),
|
||||
clip_content,
|
||||
instance.timeline_start,
|
||||
tempo_map,
|
||||
);
|
||||
|
||||
// Calculate how much we want to extend
|
||||
let desired_extend = old_trim - new_trim;
|
||||
|
||||
// Clamp to max allowed
|
||||
let actual_extend = desired_extend.min(max_extend);
|
||||
let clamped_trim_start = old_trim - actual_extend;
|
||||
let clamped_timeline_start = (old_timeline - actual_extend).max(0.0);
|
||||
|
||||
// Move the timeline left by the same span, as wall-clock seconds.
|
||||
let shift = content_to_secs(
|
||||
actual_extend,
|
||||
clip_content,
|
||||
instance.timeline_start,
|
||||
tempo_map,
|
||||
);
|
||||
let clamped_timeline_start = tempo_map
|
||||
.seconds_to_beats(tempo_map.beats_to_seconds(old_timeline) - shift)
|
||||
.max(Beats::ZERO);
|
||||
|
||||
clamped_new = TrimData::left(clamped_trim_start, clamped_timeline_start);
|
||||
}
|
||||
}
|
||||
}
|
||||
TrimType::TrimRight => {
|
||||
let old_trim_end = old.trim_value.unwrap_or(clip_duration);
|
||||
let new_trim_end = new.trim_value.unwrap_or(clip_duration);
|
||||
let content_end = ContentTime(clip_content.native());
|
||||
let old_trim_end = old.trim_value.unwrap_or(content_end);
|
||||
let new_trim_end = new.trim_value.unwrap_or(content_end);
|
||||
|
||||
// If extending to the right (new_trim_end > old_trim_end)
|
||||
if should_validate && new_trim_end > old_trim_end {
|
||||
// Calculate current effective duration
|
||||
let current_effective_duration = old_trim_end - instance.trim_start;
|
||||
let tempo_map = document.tempo_map();
|
||||
|
||||
// Find the maximum we can extend right
|
||||
let max_extend = document.find_max_trim_extend_right(
|
||||
layer_id,
|
||||
instance_id,
|
||||
// How long the clip currently occupies the timeline, in beats. Resolved
|
||||
// in the clip's own domain, so a MIDI clip's beats content isn't run
|
||||
// through the seconds→beats conversion a second time.
|
||||
let current_effective_duration = instance
|
||||
.effective_duration_beats(clip_content, tempo_map);
|
||||
|
||||
// Max rightward extension: the gap's wall-clock span, in content domain.
|
||||
let max_extend = gap_to_content(
|
||||
document.find_max_trim_extend_right(
|
||||
layer_id,
|
||||
instance_id,
|
||||
instance.timeline_start,
|
||||
current_effective_duration,
|
||||
),
|
||||
clip_content,
|
||||
instance.timeline_start,
|
||||
current_effective_duration,
|
||||
tempo_map,
|
||||
);
|
||||
|
||||
// Calculate how much we want to extend
|
||||
let desired_extend = new_trim_end - old_trim_end;
|
||||
|
||||
// Clamp to max allowed
|
||||
let actual_extend = desired_extend.min(max_extend);
|
||||
let clamped_trim_end = old_trim_end + actual_extend;
|
||||
|
||||
// Don't exceed clip duration
|
||||
let final_trim_end = clamped_trim_end.min(clip_duration);
|
||||
// Don't exceed the clip's content.
|
||||
let final_trim_end = clamped_trim_end.min(content_end);
|
||||
|
||||
clamped_new = TrimData::right(Some(final_trim_end));
|
||||
}
|
||||
@@ -275,6 +345,7 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
// Apply trims
|
||||
@@ -315,6 +386,7 @@ impl Action for TrimClipInstancesAction {
|
||||
AnyLayer::Effect(el) => &mut el.clip_instances,
|
||||
AnyLayer::Group(_) => continue,
|
||||
AnyLayer::Raster(_) => continue,
|
||||
AnyLayer::Text(_) => continue,
|
||||
};
|
||||
|
||||
// Restore original trim values
|
||||
@@ -351,7 +423,7 @@ impl Action for TrimClipInstancesAction {
|
||||
|
||||
fn execute_backend(&mut self, backend: &mut crate::action::BackendContext, document: &Document) -> Result<(), String> {
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::clip::AudioClipType;
|
||||
use crate::clip::ResolvedContent;
|
||||
|
||||
// Get audio controller
|
||||
let controller = match backend.audio_controller.as_mut() {
|
||||
@@ -371,9 +443,10 @@ impl Action for TrimClipInstancesAction {
|
||||
if let Some(instance) = vl.clip_instances.iter().find(|ci| ci.id == *instance_id) {
|
||||
if let Some(&metatrack_id) = backend.layer_to_track_map.get(&instance.clip_id) {
|
||||
// Instance already has new values after execute()
|
||||
controller.set_offset(metatrack_id, instance.timeline_start);
|
||||
controller.set_trim_start(metatrack_id, instance.trim_start);
|
||||
controller.set_trim_end(metatrack_id, instance.trim_end);
|
||||
controller.set_offset(metatrack_id, document.tempo_map().beats_to_seconds(instance.timeline_start));
|
||||
// A vector clip's content is wall-clock, so its content times ARE seconds.
|
||||
controller.set_trim_start(metatrack_id, daw_backend::Seconds(instance.trim_start.raw()));
|
||||
controller.set_trim_end(metatrack_id, instance.trim_end.map(|t| daw_backend::Seconds(t.raw())));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -409,27 +482,29 @@ impl Action for TrimClipInstancesAction {
|
||||
// Calculate new internal_start and internal_end for backend
|
||||
// Note: instance already has the new trim values after execute()
|
||||
let internal_start = instance.trim_start;
|
||||
let internal_end = instance.trim_end.unwrap_or(clip.duration);
|
||||
let internal_end = instance
|
||||
.trim_end
|
||||
.unwrap_or(ContentTime(clip.content_duration().native()));
|
||||
|
||||
// Handle trim based on clip type
|
||||
match &clip.clip_type {
|
||||
AudioClipType::Midi { midi_clip_id } => {
|
||||
match &instance.resolve(clip) {
|
||||
ResolvedContent::Midi { midi_clip_id } => {
|
||||
// For MIDI: trim_clip expects the pool clip ID
|
||||
controller.trim_clip(*track_id, *midi_clip_id, internal_start, internal_end);
|
||||
controller.trim_clip(*track_id, *midi_clip_id, clip.trim_range(internal_start, internal_end));
|
||||
}
|
||||
AudioClipType::Sampled { .. } => {
|
||||
ResolvedContent::Audio { .. } => {
|
||||
// For sampled audio: trim_clip expects the instance ID
|
||||
let backend_instance_id = backend.clip_instance_to_backend_map.get(instance_id)
|
||||
.ok_or_else(|| format!("Clip instance {} not mapped to backend", instance_id))?;
|
||||
|
||||
match backend_instance_id {
|
||||
crate::action::BackendClipInstanceId::Audio(audio_id) => {
|
||||
controller.trim_clip(*track_id, *audio_id, internal_start, internal_end);
|
||||
controller.trim_clip(*track_id, *audio_id, clip.trim_range(internal_start, internal_end));
|
||||
}
|
||||
_ => return Err("Expected audio instance ID for sampled clip".to_string()),
|
||||
}
|
||||
}
|
||||
AudioClipType::Recording => {
|
||||
ResolvedContent::Recording => {
|
||||
// Recording clips cannot be trimmed - skip
|
||||
}
|
||||
}
|
||||
@@ -441,7 +516,7 @@ impl Action for TrimClipInstancesAction {
|
||||
|
||||
fn rollback_backend(&mut self, backend: &mut crate::action::BackendContext, document: &Document) -> Result<(), String> {
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::clip::AudioClipType;
|
||||
use crate::clip::ResolvedContent;
|
||||
|
||||
// Get audio controller
|
||||
let controller = match backend.audio_controller.as_mut() {
|
||||
@@ -461,9 +536,10 @@ impl Action for TrimClipInstancesAction {
|
||||
if let Some(instance) = vl.clip_instances.iter().find(|ci| ci.id == *instance_id) {
|
||||
if let Some(&metatrack_id) = backend.layer_to_track_map.get(&instance.clip_id) {
|
||||
// Instance already has old values after rollback()
|
||||
controller.set_offset(metatrack_id, instance.timeline_start);
|
||||
controller.set_trim_start(metatrack_id, instance.trim_start);
|
||||
controller.set_trim_end(metatrack_id, instance.trim_end);
|
||||
controller.set_offset(metatrack_id, document.tempo_map().beats_to_seconds(instance.timeline_start));
|
||||
// A vector clip's content is wall-clock, so its content times ARE seconds.
|
||||
controller.set_trim_start(metatrack_id, daw_backend::Seconds(instance.trim_start.raw()));
|
||||
controller.set_trim_end(metatrack_id, instance.trim_end.map(|t| daw_backend::Seconds(t.raw())));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -497,34 +573,35 @@ impl Action for TrimClipInstancesAction {
|
||||
.ok_or_else(|| format!("Audio clip {} not found", instance.clip_id))?;
|
||||
|
||||
// Calculate old internal_start and internal_end for backend
|
||||
let content_end = ContentTime(clip.content_duration().native());
|
||||
let internal_start = match trim_type {
|
||||
TrimType::TrimLeft => old.trim_value.unwrap_or(0.0),
|
||||
TrimType::TrimLeft => old.trim_value.unwrap_or(ContentTime::ZERO),
|
||||
TrimType::TrimRight => instance.trim_start, // trim_start wasn't changed
|
||||
};
|
||||
let internal_end = match trim_type {
|
||||
TrimType::TrimLeft => instance.trim_end.unwrap_or(clip.duration), // trim_end wasn't changed
|
||||
TrimType::TrimRight => old.trim_value.unwrap_or(clip.duration),
|
||||
TrimType::TrimLeft => instance.trim_end.unwrap_or(content_end), // trim_end wasn't changed
|
||||
TrimType::TrimRight => old.trim_value.unwrap_or(content_end),
|
||||
};
|
||||
|
||||
// Handle trim based on clip type
|
||||
match &clip.clip_type {
|
||||
AudioClipType::Midi { midi_clip_id } => {
|
||||
match &instance.resolve(clip) {
|
||||
ResolvedContent::Midi { midi_clip_id } => {
|
||||
// For MIDI: trim_clip expects the pool clip ID
|
||||
controller.trim_clip(*track_id, *midi_clip_id, internal_start, internal_end);
|
||||
controller.trim_clip(*track_id, *midi_clip_id, clip.trim_range(internal_start, internal_end));
|
||||
}
|
||||
AudioClipType::Sampled { .. } => {
|
||||
ResolvedContent::Audio { .. } => {
|
||||
// For sampled audio: trim_clip expects the instance ID
|
||||
let backend_instance_id = backend.clip_instance_to_backend_map.get(instance_id)
|
||||
.ok_or_else(|| format!("Clip instance {} not mapped to backend", instance_id))?;
|
||||
|
||||
match backend_instance_id {
|
||||
crate::action::BackendClipInstanceId::Audio(audio_id) => {
|
||||
controller.trim_clip(*track_id, *audio_id, internal_start, internal_end);
|
||||
controller.trim_clip(*track_id, *audio_id, clip.trim_range(internal_start, internal_end));
|
||||
}
|
||||
_ => return Err("Expected audio instance ID for sampled clip".to_string()),
|
||||
}
|
||||
}
|
||||
AudioClipType::Recording => {
|
||||
ResolvedContent::Recording => {
|
||||
// Recording clips cannot be trimmed - skip
|
||||
}
|
||||
}
|
||||
@@ -547,12 +624,14 @@ mod tests {
|
||||
|
||||
// Create a clip ID (ClipInstance references clip by ID)
|
||||
let clip_id = uuid::Uuid::new_v4();
|
||||
let clip = crate::clip::VectorClip::with_id(clip_id, "Test Clip", 100.0, 100.0, 10.0);
|
||||
document.vector_clips.insert(clip_id, clip);
|
||||
|
||||
let mut vector_layer = VectorLayer::new("Layer 1");
|
||||
|
||||
let mut clip_instance = ClipInstance::new(clip_id);
|
||||
clip_instance.timeline_start = 0.0;
|
||||
clip_instance.trim_start = 0.0;
|
||||
clip_instance.timeline_start = Beats::ZERO;
|
||||
clip_instance.trim_start = ContentTime::ZERO;
|
||||
let instance_id = clip_instance.id;
|
||||
vector_layer.clip_instances.push(clip_instance);
|
||||
|
||||
@@ -565,8 +644,8 @@ mod tests {
|
||||
vec![(
|
||||
instance_id,
|
||||
TrimType::TrimLeft,
|
||||
TrimData::left(0.0, 0.0),
|
||||
TrimData::left(2.0, 2.0),
|
||||
TrimData::left(ContentTime::ZERO, Beats::ZERO),
|
||||
TrimData::left(ContentTime(2.0), Beats(2.0)),
|
||||
)],
|
||||
);
|
||||
|
||||
@@ -582,8 +661,8 @@ mod tests {
|
||||
.iter()
|
||||
.find(|ci| ci.id == instance_id)
|
||||
.unwrap();
|
||||
assert_eq!(instance.trim_start, 2.0);
|
||||
assert_eq!(instance.timeline_start, 2.0);
|
||||
assert_eq!(instance.trim_start, ContentTime(2.0));
|
||||
assert_eq!(instance.timeline_start, Beats(2.0));
|
||||
}
|
||||
|
||||
// Rollback
|
||||
@@ -596,8 +675,8 @@ mod tests {
|
||||
.iter()
|
||||
.find(|ci| ci.id == instance_id)
|
||||
.unwrap();
|
||||
assert_eq!(instance.trim_start, 0.0);
|
||||
assert_eq!(instance.timeline_start, 0.0);
|
||||
assert_eq!(instance.trim_start, ContentTime::ZERO);
|
||||
assert_eq!(instance.timeline_start, Beats::ZERO);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -607,6 +686,8 @@ mod tests {
|
||||
|
||||
// Create a clip ID (ClipInstance references clip by ID)
|
||||
let clip_id = uuid::Uuid::new_v4();
|
||||
let clip = crate::clip::VectorClip::with_id(clip_id, "Test Clip", 100.0, 100.0, 10.0);
|
||||
document.vector_clips.insert(clip_id, clip);
|
||||
|
||||
let mut vector_layer = VectorLayer::new("Layer 1");
|
||||
|
||||
@@ -625,7 +706,7 @@ mod tests {
|
||||
instance_id,
|
||||
TrimType::TrimRight,
|
||||
TrimData::right(None),
|
||||
TrimData::right(Some(8.0)),
|
||||
TrimData::right(Some(ContentTime(8.0))),
|
||||
)],
|
||||
);
|
||||
|
||||
@@ -641,7 +722,7 @@ mod tests {
|
||||
.iter()
|
||||
.find(|ci| ci.id == instance_id)
|
||||
.unwrap();
|
||||
assert_eq!(instance.trim_end, Some(8.0));
|
||||
assert_eq!(instance.trim_end, Some(ContentTime(8.0)));
|
||||
}
|
||||
|
||||
// Rollback
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
use crate::action::Action;
|
||||
use crate::document::Document;
|
||||
use daw_backend::Beats;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Convert editor-side beats-domain note tuples to the typed backend form.
|
||||
fn notes_to_beats(notes: &[(f64, u8, u8, f64)]) -> Vec<(Beats, u8, u8, Beats)> {
|
||||
notes.iter().map(|&(t, n, v, d)| (Beats(t), n, v, Beats(d))).collect()
|
||||
}
|
||||
|
||||
/// Action to update MIDI notes in a clip (supports undo/redo)
|
||||
///
|
||||
/// Stores the before and after note states. MIDI note data lives in the backend,
|
||||
@@ -49,7 +55,8 @@ impl Action for UpdateMidiNotesAction {
|
||||
.get(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not mapped to backend track", self.layer_id))?;
|
||||
|
||||
controller.update_midi_clip_notes(*track_id, self.midi_clip_id, self.new_notes.clone());
|
||||
// Note times/durations are beats (MIDI content domain); assert that at the typed boundary.
|
||||
controller.update_midi_clip_notes(*track_id, self.midi_clip_id, notes_to_beats(&self.new_notes));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -68,7 +75,7 @@ impl Action for UpdateMidiNotesAction {
|
||||
.get(&self.layer_id)
|
||||
.ok_or_else(|| format!("Layer {} not mapped to backend track", self.layer_id))?;
|
||||
|
||||
controller.update_midi_clip_notes(*track_id, self.midi_clip_id, self.old_notes.clone());
|
||||
controller.update_midi_clip_notes(*track_id, self.midi_clip_id, notes_to_beats(&self.old_notes));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -322,6 +322,20 @@ impl AnimationCurve {
|
||||
}
|
||||
}
|
||||
|
||||
/// True when `time` lies strictly between two keyframes — an in-between frame of a
|
||||
/// tween (not on a keyframe, not in the pre/post-extrapolation tails).
|
||||
pub fn is_tween_inbetween(&self, time: f64, tol: f64) -> bool {
|
||||
if self.keyframes.len() < 2 {
|
||||
return false;
|
||||
}
|
||||
let first = self.keyframes.first().unwrap().time;
|
||||
let last = self.keyframes.last().unwrap().time;
|
||||
if time <= first + tol || time >= last - tol {
|
||||
return false;
|
||||
}
|
||||
!self.keyframes.iter().any(|kf| (kf.time - time).abs() <= tol)
|
||||
}
|
||||
|
||||
/// Extrapolate before the first keyframe
|
||||
fn extrapolate_pre(&self, time: f64, first_kf: &Keyframe) -> f64 {
|
||||
match self.pre_extrapolation {
|
||||
@@ -516,6 +530,17 @@ impl AnimationData {
|
||||
self.curves.remove(target)
|
||||
}
|
||||
|
||||
/// True when the object (e.g. a clip instance) is mid motion-tween at `time` — any of
|
||||
/// its curves has `time` strictly between two keyframes. Used to lock out editing on
|
||||
/// in-between frames (editing there would silently insert a keyframe and disturb the tween).
|
||||
pub fn is_object_tweened_at(&self, id: uuid::Uuid, time: f64) -> bool {
|
||||
const TOL: f64 = 0.001;
|
||||
self.curves.iter().any(|(target, curve)| {
|
||||
matches!(target, AnimationTarget::Object { id: oid, .. } if *oid == id)
|
||||
&& curve.is_tween_inbetween(time, TOL)
|
||||
})
|
||||
}
|
||||
|
||||
/// Evaluate a property at a given time
|
||||
pub fn eval(&self, target: &AnimationTarget, time: f64, default: f64) -> f64 {
|
||||
self.curves
|
||||
@@ -545,3 +570,51 @@ impl AnimationData {
|
||||
(t, opacity)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tween_lock_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn curve_in_between_detection() {
|
||||
let mut c = AnimationCurve::new(
|
||||
AnimationTarget::Object { id: uuid::Uuid::nil(), property: TransformProperty::X },
|
||||
0.0,
|
||||
);
|
||||
c.set_keyframe(Keyframe::linear(0.0, 0.0));
|
||||
c.set_keyframe(Keyframe::linear(10.0, 100.0));
|
||||
|
||||
assert!(c.is_tween_inbetween(5.0, 0.001), "strictly between keyframes");
|
||||
assert!(!c.is_tween_inbetween(0.0, 0.001), "on a keyframe");
|
||||
assert!(!c.is_tween_inbetween(10.0, 0.001), "on a keyframe");
|
||||
assert!(!c.is_tween_inbetween(15.0, 0.001), "past the last keyframe (extrapolation tail)");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_keyframe_is_never_in_between() {
|
||||
let mut c = AnimationCurve::new(
|
||||
AnimationTarget::Object { id: uuid::Uuid::nil(), property: TransformProperty::X },
|
||||
0.0,
|
||||
);
|
||||
c.set_keyframe(Keyframe::linear(10.0, 100.0));
|
||||
assert!(!c.is_tween_inbetween(5.0, 0.001));
|
||||
assert!(!c.is_tween_inbetween(20.0, 0.001));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn object_tweened_when_any_curve_is_in_between() {
|
||||
let id = uuid::Uuid::new_v4();
|
||||
let mut data = AnimationData::new();
|
||||
let mut cx = AnimationCurve::new(
|
||||
AnimationTarget::Object { id, property: TransformProperty::X },
|
||||
0.0,
|
||||
);
|
||||
cx.set_keyframe(Keyframe::linear(0.0, 0.0));
|
||||
cx.set_keyframe(Keyframe::linear(10.0, 100.0));
|
||||
data.set_curve(cx);
|
||||
|
||||
assert!(data.is_object_tweened_at(id, 5.0));
|
||||
assert!(!data.is_object_tweened_at(id, 0.0));
|
||||
assert!(!data.is_object_tweened_at(uuid::Uuid::new_v4(), 5.0), "different object");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,822 @@
|
||||
//! SQLite-backed `.beam` project container.
|
||||
//!
|
||||
//! The `.beam` format is a single SQLite database file. It replaces the older
|
||||
//! ZIP-archive format. SQLite gives us, in one file:
|
||||
//!
|
||||
//! - **Streaming reads** — packed media is split into chunk rows and read on
|
||||
//! demand through [`BlobReader`] (`Read + Seek`), so arbitrary-length audio /
|
||||
//! video never has to be fully decoded into RAM on load.
|
||||
//! - **In-place, crash-safe mutation** — raster frame write-back and re-save are
|
||||
//! transactional `UPDATE`s rather than rewriting a whole archive.
|
||||
//! - **Single-file UX** — behaves like a file on every platform.
|
||||
//!
|
||||
//! ## Media storage
|
||||
//!
|
||||
//! Each media item is one row in `media` plus, when *packed*, N rows in
|
||||
//! `media_chunk`:
|
||||
//!
|
||||
//! - **Packed** (`MediaStorage::Packed`) — bytes live in the database, split
|
||||
//! into [`CHUNK_SIZE`]-byte chunks. Chunking keeps each blob well under
|
||||
//! SQLite's ~2 GB per-blob ceiling and bounds the working set of a streaming
|
||||
//! reader to a single chunk.
|
||||
//! - **Referenced** (`MediaStorage::Referenced`) — only an external path is
|
||||
//! stored; the bytes stay on disk (useful for shared media on a network drive,
|
||||
//! or media too large/volatile to pack). Callers open the path directly.
|
||||
//!
|
||||
//! `project.json` (the serialized `BeamProject`) is stored verbatim in the
|
||||
//! single-row `project_json` table; only the container and media storage change
|
||||
//! relative to the legacy format.
|
||||
|
||||
use rusqlite::blob::Blob;
|
||||
use rusqlite::{Connection, DatabaseName, OpenFlags, OptionalExtension};
|
||||
use std::io::{self, Read, Seek, SeekFrom};
|
||||
use std::path::Path;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Default packed-media chunk size: 4 MiB.
|
||||
///
|
||||
/// Small enough to bound a streaming reader's per-chunk work and any
|
||||
/// whole-chunk buffering, large enough to keep row counts modest (a 1 GB file
|
||||
/// is 256 rows). Comfortably under SQLite's ~2 GB per-blob limit.
|
||||
pub const CHUNK_SIZE: u64 = 4 * 1024 * 1024;
|
||||
|
||||
/// Files at or above this size prompt the user to pick packed vs referenced
|
||||
/// (and the choice is then persisted as the default). Matches SQLite's
|
||||
/// practical large-blob threshold.
|
||||
pub const LARGE_MEDIA_THRESHOLD: u64 = 2 * 1024 * 1024 * 1024;
|
||||
|
||||
/// Kind of media stored in the `media` table.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MediaKind {
|
||||
Audio = 0,
|
||||
Video = 1,
|
||||
Raster = 2,
|
||||
ImageAsset = 3,
|
||||
/// A precomputed waveform LOD pyramid blob for an audio item (keyed by the
|
||||
/// same id as the audio it describes). See `daw_backend::audio::waveform_pyramid`.
|
||||
Waveform = 4,
|
||||
/// A pack of precomputed video thumbnails for a video clip (keyed by a
|
||||
/// sentinel-derived id from the clip id). Opaque blob; format owned by the editor.
|
||||
Thumbnail = 5,
|
||||
/// A low-res PNG proxy of a raster keyframe (keyed by a sentinel-derived id from
|
||||
/// the keyframe id). Decoded eagerly on load and shown while the full-res pixels
|
||||
/// page in, so cold scrubs don't flash blank. See `raster_proxy_media_id`.
|
||||
RasterProxy = 6,
|
||||
/// An embedded font file (TTF/OTF) used by a text layer (keyed by a content hash
|
||||
/// of the bytes so identical fonts dedupe). Registered into the font collection
|
||||
/// on load so documents render faithfully on machines lacking the font.
|
||||
Font = 7,
|
||||
}
|
||||
|
||||
impl MediaKind {
|
||||
fn from_i64(v: i64) -> Option<Self> {
|
||||
match v {
|
||||
0 => Some(Self::Audio),
|
||||
1 => Some(Self::Video),
|
||||
2 => Some(Self::Raster),
|
||||
3 => Some(Self::ImageAsset),
|
||||
4 => Some(Self::Waveform),
|
||||
5 => Some(Self::Thumbnail),
|
||||
6 => Some(Self::RasterProxy),
|
||||
7 => Some(Self::Font),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How a media item's bytes are stored.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MediaStorage {
|
||||
/// Bytes are chunked into `media_chunk` rows inside the database.
|
||||
Packed = 0,
|
||||
/// Only an external path is stored; bytes live on disk.
|
||||
Referenced = 1,
|
||||
}
|
||||
|
||||
impl MediaStorage {
|
||||
fn from_i64(v: i64) -> Option<Self> {
|
||||
match v {
|
||||
0 => Some(Self::Packed),
|
||||
1 => Some(Self::Referenced),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Metadata row for a media item (no bytes).
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MediaInfo {
|
||||
pub id: Uuid,
|
||||
pub kind: MediaKind,
|
||||
/// Original codec / container extension, e.g. `"flac"`, `"mp3"`, `"png"`.
|
||||
pub codec: String,
|
||||
pub storage: MediaStorage,
|
||||
/// Set when `storage == Referenced`.
|
||||
pub ext_path: Option<String>,
|
||||
/// Total byte length of the media payload (packed only; 0 for referenced).
|
||||
pub total_len: u64,
|
||||
// Kind-specific metadata (nullable; meaning depends on `kind`).
|
||||
pub channels: Option<u32>,
|
||||
pub sample_rate: Option<u32>,
|
||||
pub width: Option<u32>,
|
||||
pub height: Option<u32>,
|
||||
}
|
||||
|
||||
/// Optional kind-specific metadata supplied when writing a media item.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct MediaMeta {
|
||||
pub channels: Option<u32>,
|
||||
pub sample_rate: Option<u32>,
|
||||
pub width: Option<u32>,
|
||||
pub height: Option<u32>,
|
||||
}
|
||||
|
||||
/// A `.beam` project container backed by a SQLite database.
|
||||
pub struct BeamArchive {
|
||||
conn: Connection,
|
||||
chunk_size: u64,
|
||||
}
|
||||
|
||||
impl BeamArchive {
|
||||
/// Schema version stored in `meta` under `"schema_version"`.
|
||||
pub const SCHEMA_VERSION: i64 = 1;
|
||||
|
||||
/// Create a new (empty) archive at `path`, replacing any existing file.
|
||||
pub fn create(path: &Path) -> Result<Self, String> {
|
||||
// Remove any existing file so we start from a clean schema.
|
||||
if path.exists() {
|
||||
std::fs::remove_file(path).map_err(|e| format!("Failed to replace {:?}: {}", path, e))?;
|
||||
}
|
||||
let conn = Connection::open(path).map_err(map_sql)?;
|
||||
let mut archive = Self { conn, chunk_size: CHUNK_SIZE };
|
||||
archive.init_schema()?;
|
||||
Ok(archive)
|
||||
}
|
||||
|
||||
/// Open an existing archive for read/write.
|
||||
pub fn open(path: &Path) -> Result<Self, String> {
|
||||
let conn = Connection::open(path).map_err(map_sql)?;
|
||||
let archive = Self { conn, chunk_size: CHUNK_SIZE };
|
||||
archive.verify_schema()?;
|
||||
Ok(archive)
|
||||
}
|
||||
|
||||
/// Quick check: does `path` look like a SQLite database (vs. a legacy ZIP)?
|
||||
/// Reads the 16-byte SQLite header magic. Used to route between the SQLite
|
||||
/// loader and the legacy-ZIP migration path.
|
||||
pub fn is_sqlite(path: &Path) -> bool {
|
||||
use std::io::Read as _;
|
||||
let mut f = match std::fs::File::open(path) {
|
||||
Ok(f) => f,
|
||||
Err(_) => return false,
|
||||
};
|
||||
let mut magic = [0u8; 16];
|
||||
if f.read_exact(&mut magic).is_err() {
|
||||
return false;
|
||||
}
|
||||
&magic == b"SQLite format 3\0"
|
||||
}
|
||||
|
||||
fn init_schema(&mut self) -> Result<(), String> {
|
||||
self.conn
|
||||
.execute_batch(
|
||||
"BEGIN;
|
||||
CREATE TABLE media (
|
||||
id BLOB PRIMARY KEY, -- 16-byte Uuid
|
||||
kind INTEGER NOT NULL,
|
||||
codec TEXT NOT NULL,
|
||||
storage INTEGER NOT NULL,
|
||||
ext_path TEXT,
|
||||
total_len INTEGER NOT NULL DEFAULT 0,
|
||||
channels INTEGER,
|
||||
sample_rate INTEGER,
|
||||
width INTEGER,
|
||||
height INTEGER
|
||||
);
|
||||
CREATE TABLE media_chunk (
|
||||
id INTEGER PRIMARY KEY, -- rowid, for blob_open
|
||||
media_id BLOB NOT NULL,
|
||||
chunk_index INTEGER NOT NULL,
|
||||
bytes BLOB NOT NULL,
|
||||
UNIQUE (media_id, chunk_index)
|
||||
);
|
||||
CREATE TABLE project_json (
|
||||
id INTEGER PRIMARY KEY CHECK (id = 0),
|
||||
data TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE meta (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL
|
||||
);
|
||||
COMMIT;",
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
self.set_meta("schema_version", &Self::SCHEMA_VERSION.to_string())?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify_schema(&self) -> Result<(), String> {
|
||||
let v: Option<String> = self.get_meta("schema_version")?;
|
||||
match v.as_deref().and_then(|s| s.parse::<i64>().ok()) {
|
||||
Some(n) if n <= Self::SCHEMA_VERSION => Ok(()),
|
||||
Some(n) => Err(format!(
|
||||
"Unsupported .beam schema version {} (this build supports up to {})",
|
||||
n,
|
||||
Self::SCHEMA_VERSION
|
||||
)),
|
||||
None => Err("Not a valid .beam archive (missing schema_version)".to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Begin a write transaction grouping multiple media/json writes into one
|
||||
/// atomic, crash-safe commit. Used by saves so unchanged (large) media is
|
||||
/// never rewritten — only dirty rows are touched, in place.
|
||||
pub fn transaction(&mut self) -> Result<BeamTxn<'_>, String> {
|
||||
let tx = self.conn.transaction().map_err(map_sql)?;
|
||||
Ok(BeamTxn { tx, chunk_size: self.chunk_size })
|
||||
}
|
||||
|
||||
// -- meta key/value --------------------------------------------------
|
||||
|
||||
pub fn set_meta(&self, key: &str, value: &str) -> Result<(), String> {
|
||||
set_meta_conn(&self.conn, key, value)
|
||||
}
|
||||
|
||||
pub fn get_meta(&self, key: &str) -> Result<Option<String>, String> {
|
||||
self.conn
|
||||
.query_row("SELECT value FROM meta WHERE key = ?1", [key], |r| r.get(0))
|
||||
.optional()
|
||||
.map_err(map_sql)
|
||||
}
|
||||
|
||||
// -- project.json ----------------------------------------------------
|
||||
|
||||
/// Store the serialized `project.json` (single row).
|
||||
pub fn set_project_json(&self, json: &str) -> Result<(), String> {
|
||||
set_project_json_conn(&self.conn, json)
|
||||
}
|
||||
|
||||
/// Read the serialized `project.json`.
|
||||
pub fn get_project_json(&self) -> Result<String, String> {
|
||||
self.conn
|
||||
.query_row("SELECT data FROM project_json WHERE id = 0", [], |r| r.get(0))
|
||||
.optional()
|
||||
.map_err(map_sql)?
|
||||
.ok_or_else(|| "Archive has no project.json".to_string())
|
||||
}
|
||||
|
||||
// -- media write -----------------------------------------------------
|
||||
|
||||
/// Write a media item whose bytes are packed (chunked) into the database.
|
||||
/// Replaces any existing rows for `id`.
|
||||
pub fn put_media_packed(
|
||||
&mut self,
|
||||
id: Uuid,
|
||||
kind: MediaKind,
|
||||
codec: &str,
|
||||
bytes: &[u8],
|
||||
meta: MediaMeta,
|
||||
) -> Result<(), String> {
|
||||
let tx = self.conn.transaction().map_err(map_sql)?;
|
||||
write_media_packed(&tx, self.chunk_size, id, kind, codec, bytes, meta)?;
|
||||
tx.commit().map_err(map_sql)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Write a media item that references an external file by path (no bytes
|
||||
/// stored). Replaces any existing rows for `id`.
|
||||
pub fn put_media_referenced(
|
||||
&mut self,
|
||||
id: Uuid,
|
||||
kind: MediaKind,
|
||||
codec: &str,
|
||||
ext_path: &str,
|
||||
meta: MediaMeta,
|
||||
) -> Result<(), String> {
|
||||
let tx = self.conn.transaction().map_err(map_sql)?;
|
||||
write_media_referenced(&tx, id, kind, codec, ext_path, meta)?;
|
||||
tx.commit().map_err(map_sql)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// -- media read ------------------------------------------------------
|
||||
|
||||
/// Look up a media item's metadata.
|
||||
pub fn media_info(&self, id: Uuid) -> Result<Option<MediaInfo>, String> {
|
||||
let id_bytes = id.as_bytes().to_vec();
|
||||
self.conn
|
||||
.query_row(
|
||||
"SELECT kind, codec, storage, ext_path, total_len, channels, sample_rate, width, height
|
||||
FROM media WHERE id = ?1",
|
||||
[&id_bytes],
|
||||
|r| {
|
||||
Ok((
|
||||
r.get::<_, i64>(0)?,
|
||||
r.get::<_, String>(1)?,
|
||||
r.get::<_, i64>(2)?,
|
||||
r.get::<_, Option<String>>(3)?,
|
||||
r.get::<_, i64>(4)?,
|
||||
r.get::<_, Option<u32>>(5)?,
|
||||
r.get::<_, Option<u32>>(6)?,
|
||||
r.get::<_, Option<u32>>(7)?,
|
||||
r.get::<_, Option<u32>>(8)?,
|
||||
))
|
||||
},
|
||||
)
|
||||
.optional()
|
||||
.map_err(map_sql)?
|
||||
.map(|(kind, codec, storage, ext_path, total_len, channels, sample_rate, width, height)| {
|
||||
Ok(MediaInfo {
|
||||
id,
|
||||
kind: MediaKind::from_i64(kind)
|
||||
.ok_or_else(|| format!("Unknown media kind {}", kind))?,
|
||||
codec,
|
||||
storage: MediaStorage::from_i64(storage)
|
||||
.ok_or_else(|| format!("Unknown media storage {}", storage))?,
|
||||
ext_path,
|
||||
total_len: total_len.max(0) as u64,
|
||||
channels,
|
||||
sample_rate,
|
||||
width,
|
||||
height,
|
||||
})
|
||||
})
|
||||
.transpose()
|
||||
}
|
||||
|
||||
/// List every media item of a given kind.
|
||||
pub fn media_ids_of_kind(&self, kind: MediaKind) -> Result<Vec<Uuid>, String> {
|
||||
let mut stmt = self
|
||||
.conn
|
||||
.prepare("SELECT id FROM media WHERE kind = ?1")
|
||||
.map_err(map_sql)?;
|
||||
let rows = stmt
|
||||
.query_map([kind as i64], |r| r.get::<_, Vec<u8>>(0))
|
||||
.map_err(map_sql)?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
let bytes = row.map_err(map_sql)?;
|
||||
out.push(uuid_from_bytes(&bytes)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Read an entire packed media item into memory. Convenience for small
|
||||
/// media (raster frames, image assets); large media should stream via
|
||||
/// [`BeamArchive::open_blob_reader`] instead.
|
||||
pub fn read_media_full(&self, id: Uuid) -> Result<Vec<u8>, String> {
|
||||
let info = self
|
||||
.media_info(id)?
|
||||
.ok_or_else(|| format!("Media {} not found", id))?;
|
||||
if info.storage != MediaStorage::Packed {
|
||||
return Err(format!("Media {} is referenced, not packed", id));
|
||||
}
|
||||
let id_bytes = id.as_bytes().to_vec();
|
||||
let mut stmt = self
|
||||
.conn
|
||||
.prepare("SELECT bytes FROM media_chunk WHERE media_id = ?1 ORDER BY chunk_index")
|
||||
.map_err(map_sql)?;
|
||||
let rows = stmt
|
||||
.query_map([&id_bytes], |r| r.get::<_, Vec<u8>>(0))
|
||||
.map_err(map_sql)?;
|
||||
// `total_len` is an untrusted DB field; cap the preallocation so a corrupt/oversized
|
||||
// value can't trigger a multi-GB eager allocation (or, on 32-bit, a truncated `as usize`).
|
||||
// The Vec still grows to fit the actual chunk bytes regardless.
|
||||
const PREALLOC_CAP: u64 = 64 * 1024 * 1024;
|
||||
let mut out = Vec::with_capacity(info.total_len.min(PREALLOC_CAP) as usize);
|
||||
for row in rows {
|
||||
out.extend_from_slice(&row.map_err(map_sql)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Open a streaming reader over a packed media item. The reader owns its own
|
||||
/// SQLite connection (read-only) so it can live on a separate thread (e.g.
|
||||
/// the audio disk reader) independent of this archive handle.
|
||||
pub fn open_blob_reader(&self, db_path: &Path, id: Uuid) -> Result<BlobReader, String> {
|
||||
let info = self
|
||||
.media_info(id)?
|
||||
.ok_or_else(|| format!("Media {} not found", id))?;
|
||||
if info.storage != MediaStorage::Packed {
|
||||
return Err(format!("Media {} is referenced, not packed", id));
|
||||
}
|
||||
BlobReader::open(db_path, id, info.total_len, self.chunk_size)
|
||||
}
|
||||
|
||||
/// Override the chunk size (testing / tuning). Affects subsequent writes.
|
||||
#[doc(hidden)]
|
||||
pub fn set_chunk_size(&mut self, chunk_size: u64) {
|
||||
assert!(chunk_size > 0);
|
||||
self.chunk_size = chunk_size;
|
||||
}
|
||||
}
|
||||
|
||||
/// Streaming reader (`Read + Seek`) over a packed media item's chunk rows.
|
||||
///
|
||||
/// Owns a dedicated read-only SQLite connection so it is independent of the
|
||||
/// writing [`BeamArchive`] handle and can be moved to another thread. Each
|
||||
/// `read` opens a blob handle on the current chunk's row via `blob_open` (no
|
||||
/// per-read query — chunk rowids are resolved once up front) and reads up to the
|
||||
/// chunk boundary; callers that issue many tiny reads should wrap this in a
|
||||
/// `BufReader`.
|
||||
pub struct BlobReader {
|
||||
conn: Connection,
|
||||
chunk_rowids: Vec<i64>,
|
||||
chunk_size: u64,
|
||||
total_len: u64,
|
||||
pos: u64,
|
||||
}
|
||||
|
||||
impl BlobReader {
|
||||
fn open(db_path: &Path, id: Uuid, total_len: u64, chunk_size: u64) -> Result<Self, String> {
|
||||
let conn = Connection::open_with_flags(
|
||||
db_path,
|
||||
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
let id_bytes = id.as_bytes().to_vec();
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT id FROM media_chunk WHERE media_id = ?1 ORDER BY chunk_index")
|
||||
.map_err(map_sql)?;
|
||||
let rows = stmt
|
||||
.query_map([&id_bytes], |r| r.get::<_, i64>(0))
|
||||
.map_err(map_sql)?;
|
||||
let mut chunk_rowids = Vec::new();
|
||||
for row in rows {
|
||||
chunk_rowids.push(row.map_err(map_sql)?);
|
||||
}
|
||||
drop(stmt);
|
||||
Ok(Self { conn, chunk_rowids, chunk_size, total_len, pos: 0 })
|
||||
}
|
||||
|
||||
/// Total length of the media payload in bytes.
|
||||
pub fn len(&self) -> u64 {
|
||||
self.total_len
|
||||
}
|
||||
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.total_len == 0
|
||||
}
|
||||
|
||||
fn chunk_blob(&self, chunk_index: usize) -> io::Result<Blob<'_>> {
|
||||
let rowid = *self
|
||||
.chunk_rowids
|
||||
.get(chunk_index)
|
||||
.ok_or_else(|| io::Error::new(io::ErrorKind::UnexpectedEof, "chunk index out of range"))?;
|
||||
self.conn
|
||||
.blob_open(DatabaseName::Main, "media_chunk", "bytes", rowid, true)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::Other, e))
|
||||
}
|
||||
}
|
||||
|
||||
impl Read for BlobReader {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
if self.pos >= self.total_len || buf.is_empty() {
|
||||
return Ok(0);
|
||||
}
|
||||
let chunk_index = (self.pos / self.chunk_size) as usize;
|
||||
let off_in_chunk = self.pos % self.chunk_size;
|
||||
|
||||
// The chunk's length is derivable from total_len/chunk_size, so we don't
|
||||
// depend on Blob::len(): every chunk but the last is exactly chunk_size.
|
||||
let chunk_start = chunk_index as u64 * self.chunk_size;
|
||||
let chunk_len = (self.total_len - chunk_start).min(self.chunk_size);
|
||||
let avail_in_chunk = (chunk_len - off_in_chunk) as usize;
|
||||
let avail_total = (self.total_len - self.pos) as usize;
|
||||
let want = buf.len().min(avail_in_chunk).min(avail_total);
|
||||
|
||||
// Scope the blob borrow (it borrows `self.conn`) so it ends before we
|
||||
// mutate `self.pos`.
|
||||
let n = {
|
||||
let mut blob = self.chunk_blob(chunk_index)?;
|
||||
blob.seek(SeekFrom::Start(off_in_chunk))?;
|
||||
blob.read(&mut buf[..want])?
|
||||
};
|
||||
self.pos += n as u64;
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
impl Seek for BlobReader {
|
||||
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
|
||||
let new_pos = match pos {
|
||||
SeekFrom::Start(n) => n as i64,
|
||||
SeekFrom::End(n) => self.total_len as i64 + n,
|
||||
SeekFrom::Current(n) => self.pos as i64 + n,
|
||||
};
|
||||
if new_pos < 0 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"seek before start of media",
|
||||
));
|
||||
}
|
||||
// Allow seeking to/past end (reads then return 0), matching File semantics.
|
||||
self.pos = new_pos as u64;
|
||||
Ok(self.pos)
|
||||
}
|
||||
}
|
||||
|
||||
/// A write transaction over a [`BeamArchive`]. All writes are buffered until
|
||||
/// [`BeamTxn::commit`]; dropping without committing rolls back. Lets a save
|
||||
/// touch only the rows that changed, in place, without rewriting unchanged media.
|
||||
pub struct BeamTxn<'a> {
|
||||
tx: rusqlite::Transaction<'a>,
|
||||
chunk_size: u64,
|
||||
}
|
||||
|
||||
impl BeamTxn<'_> {
|
||||
pub fn put_media_packed(
|
||||
&self,
|
||||
id: Uuid,
|
||||
kind: MediaKind,
|
||||
codec: &str,
|
||||
bytes: &[u8],
|
||||
meta: MediaMeta,
|
||||
) -> Result<(), String> {
|
||||
write_media_packed(&self.tx, self.chunk_size, id, kind, codec, bytes, meta)
|
||||
}
|
||||
|
||||
pub fn put_media_referenced(
|
||||
&self,
|
||||
id: Uuid,
|
||||
kind: MediaKind,
|
||||
codec: &str,
|
||||
ext_path: &str,
|
||||
meta: MediaMeta,
|
||||
) -> Result<(), String> {
|
||||
write_media_referenced(&self.tx, id, kind, codec, ext_path, meta)
|
||||
}
|
||||
|
||||
/// Like [`BeamTxn::put_media_packed`] but streams the bytes from a file on
|
||||
/// disk chunk-by-chunk, so an arbitrarily large file is never fully loaded
|
||||
/// into memory. `total_len` is taken from the bytes actually read.
|
||||
pub fn put_media_packed_from_path(
|
||||
&self,
|
||||
id: Uuid,
|
||||
kind: MediaKind,
|
||||
codec: &str,
|
||||
path: &Path,
|
||||
meta: MediaMeta,
|
||||
) -> Result<(), String> {
|
||||
write_media_packed_from_path(&self.tx, self.chunk_size, id, kind, codec, path, meta)
|
||||
}
|
||||
|
||||
pub fn set_project_json(&self, json: &str) -> Result<(), String> {
|
||||
set_project_json_conn(&self.tx, json)
|
||||
}
|
||||
|
||||
pub fn set_meta(&self, key: &str, value: &str) -> Result<(), String> {
|
||||
set_meta_conn(&self.tx, key, value)
|
||||
}
|
||||
|
||||
/// Does a media row with this id already exist?
|
||||
pub fn media_exists(&self, id: Uuid) -> Result<bool, String> {
|
||||
let id_bytes = id.as_bytes().to_vec();
|
||||
let n: i64 = self
|
||||
.tx
|
||||
.query_row("SELECT COUNT(*) FROM media WHERE id = ?1", [&id_bytes], |r| r.get(0))
|
||||
.map_err(map_sql)?;
|
||||
Ok(n > 0)
|
||||
}
|
||||
|
||||
/// Every media id currently in the archive.
|
||||
pub fn all_media_ids(&self) -> Result<Vec<Uuid>, String> {
|
||||
let mut stmt = self.tx.prepare("SELECT id FROM media").map_err(map_sql)?;
|
||||
let rows = stmt.query_map([], |r| r.get::<_, Vec<u8>>(0)).map_err(map_sql)?;
|
||||
let mut out = Vec::new();
|
||||
for row in rows {
|
||||
out.push(uuid_from_bytes(&row.map_err(map_sql)?)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Delete a media row (and its chunks).
|
||||
pub fn delete_media(&self, id: Uuid) -> Result<(), String> {
|
||||
let id_bytes = id.as_bytes().to_vec();
|
||||
self.tx
|
||||
.execute("DELETE FROM media_chunk WHERE media_id = ?1", [&id_bytes])
|
||||
.map_err(map_sql)?;
|
||||
self.tx
|
||||
.execute("DELETE FROM media WHERE id = ?1", [&id_bytes])
|
||||
.map_err(map_sql)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Delete every media row whose id is not in `keep` (orphan cleanup).
|
||||
pub fn retain_media(&self, keep: &std::collections::HashSet<Uuid>) -> Result<usize, String> {
|
||||
let mut removed = 0;
|
||||
for id in self.all_media_ids()? {
|
||||
if !keep.contains(&id) {
|
||||
self.delete_media(id)?;
|
||||
removed += 1;
|
||||
}
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
pub fn commit(self) -> Result<(), String> {
|
||||
self.tx.commit().map_err(map_sql)
|
||||
}
|
||||
}
|
||||
|
||||
// -- shared write helpers (used by both BeamArchive and BeamTxn) --------------
|
||||
|
||||
fn write_media_packed(
|
||||
conn: &Connection,
|
||||
chunk_size: u64,
|
||||
id: Uuid,
|
||||
kind: MediaKind,
|
||||
codec: &str,
|
||||
bytes: &[u8],
|
||||
meta: MediaMeta,
|
||||
) -> Result<(), String> {
|
||||
let id_bytes = id.as_bytes().to_vec();
|
||||
conn.execute("DELETE FROM media WHERE id = ?1", [&id_bytes]).map_err(map_sql)?;
|
||||
conn.execute("DELETE FROM media_chunk WHERE media_id = ?1", [&id_bytes])
|
||||
.map_err(map_sql)?;
|
||||
conn.execute(
|
||||
"INSERT INTO media
|
||||
(id, kind, codec, storage, ext_path, total_len, channels, sample_rate, width, height)
|
||||
VALUES (?1, ?2, ?3, ?4, NULL, ?5, ?6, ?7, ?8, ?9)",
|
||||
rusqlite::params![
|
||||
id_bytes,
|
||||
kind as i64,
|
||||
codec,
|
||||
MediaStorage::Packed as i64,
|
||||
bytes.len() as i64,
|
||||
meta.channels,
|
||||
meta.sample_rate,
|
||||
meta.width,
|
||||
meta.height,
|
||||
],
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
for (chunk_index, chunk) in bytes.chunks(chunk_size as usize).enumerate() {
|
||||
conn.execute(
|
||||
"INSERT INTO media_chunk (media_id, chunk_index, bytes) VALUES (?1, ?2, ?3)",
|
||||
rusqlite::params![id_bytes, chunk_index as i64, chunk],
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_media_packed_from_path(
|
||||
conn: &Connection,
|
||||
chunk_size: u64,
|
||||
id: Uuid,
|
||||
kind: MediaKind,
|
||||
codec: &str,
|
||||
path: &Path,
|
||||
meta: MediaMeta,
|
||||
) -> Result<(), String> {
|
||||
let id_bytes = id.as_bytes().to_vec();
|
||||
conn.execute("DELETE FROM media WHERE id = ?1", [&id_bytes]).map_err(map_sql)?;
|
||||
conn.execute("DELETE FROM media_chunk WHERE media_id = ?1", [&id_bytes])
|
||||
.map_err(map_sql)?;
|
||||
|
||||
let file = std::fs::File::open(path).map_err(|e| format!("Failed to open {:?}: {}", path, e))?;
|
||||
let mut reader = std::io::BufReader::new(file);
|
||||
let mut buf = vec![0u8; chunk_size as usize];
|
||||
let mut chunk_index: i64 = 0;
|
||||
let mut total_len: u64 = 0;
|
||||
|
||||
loop {
|
||||
// Fill `buf` up to chunk_size, tolerating short reads.
|
||||
let mut filled = 0usize;
|
||||
while filled < buf.len() {
|
||||
let n = reader
|
||||
.read(&mut buf[filled..])
|
||||
.map_err(|e| format!("Failed to read {:?}: {}", path, e))?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
filled += n;
|
||||
}
|
||||
if filled == 0 {
|
||||
break;
|
||||
}
|
||||
conn.execute(
|
||||
"INSERT INTO media_chunk (media_id, chunk_index, bytes) VALUES (?1, ?2, ?3)",
|
||||
rusqlite::params![id_bytes, chunk_index, &buf[..filled]],
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
chunk_index += 1;
|
||||
total_len += filled as u64;
|
||||
if filled < buf.len() {
|
||||
break; // reached EOF
|
||||
}
|
||||
}
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO media
|
||||
(id, kind, codec, storage, ext_path, total_len, channels, sample_rate, width, height)
|
||||
VALUES (?1, ?2, ?3, ?4, NULL, ?5, ?6, ?7, ?8, ?9)",
|
||||
rusqlite::params![
|
||||
id_bytes,
|
||||
kind as i64,
|
||||
codec,
|
||||
MediaStorage::Packed as i64,
|
||||
total_len as i64,
|
||||
meta.channels,
|
||||
meta.sample_rate,
|
||||
meta.width,
|
||||
meta.height,
|
||||
],
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_media_referenced(
|
||||
conn: &Connection,
|
||||
id: Uuid,
|
||||
kind: MediaKind,
|
||||
codec: &str,
|
||||
ext_path: &str,
|
||||
meta: MediaMeta,
|
||||
) -> Result<(), String> {
|
||||
let id_bytes = id.as_bytes().to_vec();
|
||||
conn.execute("DELETE FROM media WHERE id = ?1", [&id_bytes]).map_err(map_sql)?;
|
||||
conn.execute("DELETE FROM media_chunk WHERE media_id = ?1", [&id_bytes])
|
||||
.map_err(map_sql)?;
|
||||
conn.execute(
|
||||
"INSERT INTO media
|
||||
(id, kind, codec, storage, ext_path, total_len, channels, sample_rate, width, height)
|
||||
VALUES (?1, ?2, ?3, ?4, ?5, 0, ?6, ?7, ?8, ?9)",
|
||||
rusqlite::params![
|
||||
id_bytes,
|
||||
kind as i64,
|
||||
codec,
|
||||
MediaStorage::Referenced as i64,
|
||||
ext_path,
|
||||
meta.channels,
|
||||
meta.sample_rate,
|
||||
meta.width,
|
||||
meta.height,
|
||||
],
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_project_json_conn(conn: &Connection, json: &str) -> Result<(), String> {
|
||||
conn.execute(
|
||||
"INSERT INTO project_json (id, data) VALUES (0, ?1)
|
||||
ON CONFLICT(id) DO UPDATE SET data = excluded.data",
|
||||
[json],
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_meta_conn(conn: &Connection, key: &str, value: &str) -> Result<(), String> {
|
||||
conn.execute(
|
||||
"INSERT INTO meta (key, value) VALUES (?1, ?2)
|
||||
ON CONFLICT(key) DO UPDATE SET value = excluded.value",
|
||||
rusqlite::params![key, value],
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read a packed media item's full bytes via a fresh **read-only** connection,
|
||||
/// without an open [`BeamArchive`] handle. Returns `Ok(None)` if the item has no
|
||||
/// chunk rows. Used for on-demand raster fault-in: a read-only connection can't
|
||||
/// conflict with an in-place save and needs no long-lived handle.
|
||||
pub fn read_packed_media_readonly(db_path: &Path, id: Uuid) -> Result<Option<Vec<u8>>, String> {
|
||||
let conn = Connection::open_with_flags(
|
||||
db_path,
|
||||
OpenFlags::SQLITE_OPEN_READ_ONLY | OpenFlags::SQLITE_OPEN_NO_MUTEX,
|
||||
)
|
||||
.map_err(map_sql)?;
|
||||
let id_bytes = id.as_bytes().to_vec();
|
||||
let mut stmt = conn
|
||||
.prepare("SELECT bytes FROM media_chunk WHERE media_id = ?1 ORDER BY chunk_index")
|
||||
.map_err(map_sql)?;
|
||||
let rows = stmt
|
||||
.query_map([&id_bytes], |r| r.get::<_, Vec<u8>>(0))
|
||||
.map_err(map_sql)?;
|
||||
let mut out = Vec::new();
|
||||
let mut any = false;
|
||||
for row in rows {
|
||||
out.extend_from_slice(&row.map_err(map_sql)?);
|
||||
any = true;
|
||||
}
|
||||
Ok(if any { Some(out) } else { None })
|
||||
}
|
||||
|
||||
fn map_sql(e: rusqlite::Error) -> String {
|
||||
format!("SQLite error: {}", e)
|
||||
}
|
||||
|
||||
fn uuid_from_bytes(bytes: &[u8]) -> Result<Uuid, String> {
|
||||
let arr: [u8; 16] = bytes
|
||||
.try_into()
|
||||
.map_err(|_| format!("Invalid uuid blob length {}", bytes.len()))?;
|
||||
Ok(Uuid::from_bytes(arr))
|
||||
}
|
||||
|
||||
// Tests live in `tests/beam_archive.rs` (integration tests), so they compile the
|
||||
// library in non-test mode and don't depend on the crate's other `#[cfg(test)]`
|
||||
// modules.
|
||||
@@ -575,6 +575,27 @@ pub fn encode_png(img: &RgbaImage) -> Result<Vec<u8>, String> {
|
||||
Ok(buf.into_inner())
|
||||
}
|
||||
|
||||
/// Long-edge cap (pixels) for raster keyframe proxies — low-res page-in placeholders.
|
||||
pub const RASTER_PROXY_MAX_EDGE: u32 = 192;
|
||||
|
||||
/// Downscale a full RGBA buffer to a low-res proxy PNG (long edge ≤
|
||||
/// `RASTER_PROXY_MAX_EDGE`). Returns `None` on invalid dims/length or encode failure.
|
||||
pub fn encode_raster_proxy_png(raw: &[u8], width: u32, height: u32) -> Option<Vec<u8>> {
|
||||
if width == 0 || height == 0 || raw.len() != (width as usize * height as usize * 4) {
|
||||
return None;
|
||||
}
|
||||
let long = width.max(height);
|
||||
let (pw, ph) = if long <= RASTER_PROXY_MAX_EDGE {
|
||||
(width, height)
|
||||
} else {
|
||||
let s = RASTER_PROXY_MAX_EDGE as f32 / long as f32;
|
||||
(((width as f32 * s).round() as u32).max(1), ((height as f32 * s).round() as u32).max(1))
|
||||
};
|
||||
let img = RgbaImage::from_raw(width, height, raw.to_vec())?;
|
||||
let resized = image::imageops::resize(&img, pw, ph, image::imageops::FilterType::Triangle);
|
||||
encode_png(&resized).ok()
|
||||
}
|
||||
|
||||
/// Decode PNG bytes into an `RgbaImage`
|
||||
pub fn decode_png(data: &[u8]) -> Result<RgbaImage, String> {
|
||||
image::load_from_memory(data)
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
use crate::layer::AnyLayer;
|
||||
use crate::layer_tree::LayerTree;
|
||||
use crate::object::Transform;
|
||||
use daw_backend::{Beats, ContentTime, Seconds};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
use uuid::Uuid;
|
||||
@@ -110,7 +111,7 @@ impl VectorClip {
|
||||
pub fn content_duration_with(&self, framerate: f64, tempo_map: &crate::tempo_map::TempoMap, clip_duration_fn: impl Fn(&Uuid) -> Option<f64>) -> f64 {
|
||||
let frame_duration = 1.0 / framerate;
|
||||
// Work in beats, convert to seconds at the end.
|
||||
let mut last_beats: Option<f64> = None;
|
||||
let mut last_beats: Option<Beats> = None;
|
||||
let mut last_secs: Option<f64> = None;
|
||||
|
||||
for layer_node in self.layers.iter() {
|
||||
@@ -122,21 +123,26 @@ impl VectorClip {
|
||||
AnyLayer::Effect(el) => &el.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
for ci in clip_instances {
|
||||
// Compute end position of this clip instance in beats
|
||||
let end_beats = if let Some(td_beats) = ci.timeline_duration {
|
||||
let end_beats: Beats = if let Some(td_beats) = ci.timeline_duration {
|
||||
ci.timeline_start + td_beats
|
||||
} else if let Some(te) = ci.trim_end {
|
||||
let secs = (te - ci.trim_start).max(0.0);
|
||||
ci.timeline_start + tempo_map.inverse_transform(tempo_map.transform(ci.timeline_start) + secs) - ci.timeline_start
|
||||
// `clip_duration_fn` hands back seconds, so this whole path treats nested
|
||||
// content as wall-clock. That's right for the vector/video/audio clips a vector
|
||||
// clip actually nests; a nested MIDI clip (beats content) would need resolving
|
||||
// against its clip, which this callback can't do. Pre-existing limitation.
|
||||
let secs = (te - ci.trim_start).raw().max(0.0);
|
||||
tempo_map.seconds_to_beats(tempo_map.beats_to_seconds(ci.timeline_start) + Seconds(secs))
|
||||
} else if let Some(clip_dur_secs) = clip_duration_fn(&ci.clip_id) {
|
||||
let secs = (clip_dur_secs - ci.trim_start).max(0.0);
|
||||
ci.timeline_start + tempo_map.inverse_transform(tempo_map.transform(ci.timeline_start) + secs) - ci.timeline_start
|
||||
let secs = (clip_dur_secs - ci.trim_start.raw()).max(0.0);
|
||||
tempo_map.seconds_to_beats(tempo_map.beats_to_seconds(ci.timeline_start) + Seconds(secs))
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
last_beats = Some(last_beats.map_or(end_beats, |t: f64| t.max(end_beats)));
|
||||
last_beats = Some(last_beats.map_or(end_beats, |t: Beats| t.max(end_beats)));
|
||||
}
|
||||
|
||||
// Vector layer keyframes are in seconds
|
||||
@@ -147,7 +153,7 @@ impl VectorClip {
|
||||
}
|
||||
}
|
||||
|
||||
let from_clips = last_beats.map(|b| tempo_map.transform(b));
|
||||
let from_clips = last_beats.map(|b| tempo_map.beats_to_seconds(b).seconds_to_f64());
|
||||
let combined = match (from_clips, last_secs) {
|
||||
(Some(a), Some(b)) => Some(a.max(b)),
|
||||
(Some(a), None) => Some(a),
|
||||
@@ -198,8 +204,10 @@ impl VectorClip {
|
||||
for clip_instance in &vector_layer.clip_instances {
|
||||
// Convert parent clip time (seconds) to nested clip local time (seconds).
|
||||
// timeline_start is in beats; convert to seconds using document BPM.
|
||||
let start_secs = document.tempo_map().transform(clip_instance.timeline_start);
|
||||
let nested_clip_time = ((clip_time - start_secs) * clip_instance.playback_speed) + clip_instance.trim_start;
|
||||
let start_secs = document.tempo_map().beats_to_seconds(clip_instance.timeline_start).seconds_to_f64();
|
||||
// Nested clips here are vector clips, whose content is wall-clock seconds.
|
||||
let nested_clip_time =
|
||||
((clip_time - start_secs) * clip_instance.playback_speed) + clip_instance.trim_start.raw();
|
||||
|
||||
// Look up the nested clip definition
|
||||
let nested_bounds = if let Some(nested_clip) = document.get_vector_clip(&clip_instance.clip_id) {
|
||||
@@ -223,6 +231,17 @@ impl VectorClip {
|
||||
Some(existing) => existing.union(transformed_bounds),
|
||||
});
|
||||
}
|
||||
} else if let AnyLayer::Text(text_layer) = &layer_node.data {
|
||||
// Text layers contribute their box bounds (so a text-only clip is
|
||||
// selectable/draggable, not a degenerate point).
|
||||
let r = Rect::from_origin_size(
|
||||
text_layer.box_origin,
|
||||
(text_layer.box_width, text_layer.box_height),
|
||||
);
|
||||
combined_bounds = Some(match combined_bounds {
|
||||
None => r,
|
||||
Some(existing) => existing.union(r),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -263,9 +282,11 @@ pub struct ImageAsset {
|
||||
/// Image height in pixels
|
||||
pub height: u32,
|
||||
|
||||
/// Embedded image data (for project portability)
|
||||
/// If None, the image will be loaded from path when needed
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
/// Raw image file bytes. NOT serialized to project JSON — persisted as a
|
||||
/// `MediaKind::ImageAsset` row in the `.beam` container (chunked, pageable) and
|
||||
/// read back on load. `default` so new projects (bytes in the container, not JSON)
|
||||
/// deserialize; old projects with base64-embedded `data` still load via deserialize.
|
||||
#[serde(default, skip_serializing)]
|
||||
pub data: Option<Vec<u8>>,
|
||||
|
||||
/// Folder this asset belongs to (None = root of category)
|
||||
@@ -341,6 +362,13 @@ pub struct VideoClip {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub linked_audio_clip_id: Option<Uuid>,
|
||||
|
||||
/// When set, the video bytes are packed into the `.beam` container under this
|
||||
/// media id (== the clip id) and decoded by streaming from the SQLite blob.
|
||||
/// `None` means the video is referenced externally via [`Self::file_path`].
|
||||
/// Reconstructed from the archive on load (see `load_beam_sqlite`).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub media_id: Option<Uuid>,
|
||||
|
||||
/// Folder this clip belongs to (None = root of category)
|
||||
#[serde(default)]
|
||||
pub folder_id: Option<Uuid>,
|
||||
@@ -365,6 +393,7 @@ impl VideoClip {
|
||||
duration,
|
||||
frame_rate,
|
||||
linked_audio_clip_id: None,
|
||||
media_id: None,
|
||||
folder_id: None,
|
||||
}
|
||||
}
|
||||
@@ -445,6 +474,67 @@ pub enum AudioClipType {
|
||||
Recording,
|
||||
}
|
||||
|
||||
/// One take of a cycle recording — see [`ClipInstance::takes`].
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
pub struct AudioTake {
|
||||
/// Display name, e.g. "Take 1". User-editable.
|
||||
pub name: String,
|
||||
/// The recorded content this take points at.
|
||||
pub content: TakeContent,
|
||||
}
|
||||
|
||||
/// What a take actually holds. An instance's takes are all the same kind — one cycle-record session
|
||||
/// captures either audio or MIDI, never a mix.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum TakeContent {
|
||||
/// Sampled audio: index into the audio pool.
|
||||
Audio { audio_pool_index: usize },
|
||||
/// MIDI: backend MIDI clip ID.
|
||||
Midi { midi_clip_id: u32 },
|
||||
}
|
||||
|
||||
/// A clip's content duration, tagged by its native unit.
|
||||
///
|
||||
/// Sampled/recording audio and video measure content in wall-clock **seconds**; MIDI measures
|
||||
/// it in **beats** (tempo-independent musical length). Carrying the domain in the type means a
|
||||
/// duration can't be silently read in the wrong unit.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum ClipDuration {
|
||||
Seconds(Seconds),
|
||||
Beats(Beats),
|
||||
}
|
||||
|
||||
impl ClipDuration {
|
||||
/// Wall-clock seconds. Beats are converted as a length from beat 0 (exact under constant
|
||||
/// tempo; a reasonable approximation otherwise — durations are position-independent here).
|
||||
pub fn to_seconds(self, tempo_map: &daw_backend::TempoMap) -> Seconds {
|
||||
match self {
|
||||
ClipDuration::Seconds(s) => s,
|
||||
ClipDuration::Beats(b) => tempo_map.beats_to_seconds(b),
|
||||
}
|
||||
}
|
||||
|
||||
/// The raw magnitude in the clip's native unit. Use only in code that already works in that
|
||||
/// domain (e.g. trim math, whose values share the clip's native domain).
|
||||
pub fn native(self) -> f64 {
|
||||
match self {
|
||||
ClipDuration::Seconds(s) => s.seconds_to_f64(),
|
||||
ClipDuration::Beats(b) => b.beats_to_f64(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Tag a [`ContentTime`] with *this* duration's domain.
|
||||
///
|
||||
/// Handy when you already hold a clip's content duration (so you know the domain) and need to
|
||||
/// resolve one of its trim bounds, without going back to the clip.
|
||||
pub fn same_domain(self, t: ContentTime) -> ClipDuration {
|
||||
match self {
|
||||
ClipDuration::Seconds(_) => ClipDuration::Seconds(Seconds(t.raw())),
|
||||
ClipDuration::Beats(_) => ClipDuration::Beats(Beats(t.raw())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Audio clip
|
||||
///
|
||||
/// This is compatible with daw-backend's audio system:
|
||||
@@ -458,9 +548,13 @@ pub struct AudioClip {
|
||||
/// Clip name
|
||||
pub name: String,
|
||||
|
||||
/// Duration in seconds
|
||||
/// For sampled audio, this can be set to trim the audio shorter than the source file
|
||||
pub duration: f64,
|
||||
/// Raw content duration in the clip's **native domain** — SECONDS for sampled/recording
|
||||
/// audio, BEATS for MIDI (musical length, tempo-independent). Private on purpose: the domain
|
||||
/// depends on `clip_type`, so all access goes through [`AudioClip::content_duration`] /
|
||||
/// [`AudioClip::set_content_duration`], which keep it type-safe. Stored as a bare `f64`
|
||||
/// because the `.beam` format serializes it as a plain number (serde derives over private
|
||||
/// fields fine); a domain-tagged newtype would change the on-disk shape.
|
||||
duration: f64,
|
||||
|
||||
/// Audio clip type (sampled or MIDI)
|
||||
pub clip_type: AudioClipType,
|
||||
@@ -471,6 +565,34 @@ pub struct AudioClip {
|
||||
}
|
||||
|
||||
impl AudioClip {
|
||||
/// The clip's content duration, tagged with its native domain (seconds for sampled/recording,
|
||||
/// beats for MIDI). This is the only sanctioned way to read the raw `duration` field.
|
||||
pub fn content_duration(&self) -> ClipDuration {
|
||||
if self.is_midi_domain() {
|
||||
ClipDuration::Beats(Beats(self.duration))
|
||||
} else {
|
||||
ClipDuration::Seconds(Seconds(self.duration))
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the content duration. Debug-asserts the value's domain matches the clip type so a
|
||||
/// beats duration can't be stored on a seconds clip (or vice-versa).
|
||||
pub fn set_content_duration(&mut self, duration: ClipDuration) {
|
||||
debug_assert!(
|
||||
matches!(
|
||||
(self.is_midi_domain(), duration),
|
||||
(true, ClipDuration::Beats(_)) | (false, ClipDuration::Seconds(_))
|
||||
),
|
||||
"clip duration domain must match clip type",
|
||||
);
|
||||
self.duration = duration.native();
|
||||
}
|
||||
|
||||
/// Whether this clip's `duration` is measured in beats (MIDI) rather than seconds.
|
||||
fn is_midi_domain(&self) -> bool {
|
||||
matches!(self.clip_type, AudioClipType::Midi { .. })
|
||||
}
|
||||
|
||||
/// Create a new sampled audio clip
|
||||
///
|
||||
/// # Arguments
|
||||
@@ -554,6 +676,73 @@ impl AudioClip {
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The clip's own content, ignoring takes.
|
||||
///
|
||||
/// Callers that are handing content to the backend want [`ClipInstance::resolve`] instead — an
|
||||
/// instance with takes overrides the clip's content with whichever take is active.
|
||||
pub fn resolve(&self) -> ResolvedContent {
|
||||
match &self.clip_type {
|
||||
AudioClipType::Sampled { audio_pool_index } => ResolvedContent::Audio {
|
||||
audio_pool_index: *audio_pool_index,
|
||||
},
|
||||
AudioClipType::Midi { midi_clip_id } => ResolvedContent::Midi {
|
||||
midi_clip_id: *midi_clip_id,
|
||||
},
|
||||
AudioClipType::Recording => ResolvedContent::Recording,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve a content time against this clip's domain.
|
||||
///
|
||||
/// This is the ONLY sanctioned way to turn a [`ContentTime`] into a real duration — the type has
|
||||
/// no `.to_seconds()` of its own precisely so that the clip, which is the one thing that knows
|
||||
/// whether its content is measured in seconds or beats, has to be consulted.
|
||||
pub fn resolve_content_time(&self, t: ContentTime) -> ClipDuration {
|
||||
if self.is_midi_domain() {
|
||||
ClipDuration::Beats(Beats(t.raw()))
|
||||
} else {
|
||||
ClipDuration::Seconds(Seconds(t.raw()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Tag a pair of trim bounds with this clip's content domain, ready for the backend.
|
||||
///
|
||||
/// Building the [`TrimRange`] from the clip means a caller can't reach for the wrong variant:
|
||||
/// the clip is the one thing that knows the domain.
|
||||
pub fn trim_range(&self, start: ContentTime, end: ContentTime) -> daw_backend::command::TrimRange {
|
||||
if self.is_midi_domain() {
|
||||
daw_backend::command::TrimRange::Beats {
|
||||
start: Beats(start.raw()),
|
||||
end: Beats(end.raw()),
|
||||
}
|
||||
} else {
|
||||
daw_backend::command::TrimRange::Seconds {
|
||||
start: Seconds(start.raw()),
|
||||
end: Seconds(end.raw()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this clip's own content is the given audio pool index.
|
||||
pub fn owns_audio_pool_index(&self, pool_index: usize) -> bool {
|
||||
self.audio_pool_index() == Some(pool_index)
|
||||
}
|
||||
|
||||
/// Whether this clip's own content is the given backend MIDI clip ID.
|
||||
pub fn owns_midi_clip_id(&self, id: u32) -> bool {
|
||||
self.midi_clip_id() == Some(id)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a clip instance actually plays, once takes are resolved to the active one.
|
||||
/// Produced by [`ClipInstance::resolve`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum ResolvedContent {
|
||||
Audio { audio_pool_index: usize },
|
||||
Midi { midi_clip_id: u32 },
|
||||
/// A recording in progress (or an empty take folder) — no backend content yet.
|
||||
Recording,
|
||||
}
|
||||
|
||||
/// Unified clip enum for polymorphic handling
|
||||
@@ -625,23 +814,24 @@ pub struct ClipInstance {
|
||||
|
||||
/// When this instance starts on the timeline, in **beats**.
|
||||
/// Default: 0.0
|
||||
pub timeline_start: f64,
|
||||
pub timeline_start: Beats,
|
||||
|
||||
/// How long this instance appears on the timeline, in **beats**.
|
||||
/// If set and longer than the trimmed content, the content will loop.
|
||||
/// Default: None (use trimmed clip duration, no looping)
|
||||
pub timeline_duration: Option<f64>,
|
||||
pub timeline_duration: Option<Beats>,
|
||||
|
||||
/// Trim start: offset into the clip's internal content, in **seconds**.
|
||||
/// - For audio: byte-offset into the audio file
|
||||
/// - For video: seek position in the video file
|
||||
/// - For vector: time offset into the animation
|
||||
/// Trim start: offset into the clip's internal content.
|
||||
///
|
||||
/// A [`ContentTime`] — measured in the CLIP's content domain, which is seconds for sampled
|
||||
/// audio/video/vector but BEATS for MIDI. Resolve it against the clip
|
||||
/// ([`Document::resolve_content_time`]) before combining it with anything on the timeline.
|
||||
/// Default: 0.0
|
||||
pub trim_start: f64,
|
||||
pub trim_start: ContentTime,
|
||||
|
||||
/// Trim end: offset into the clip's internal content, in **seconds**.
|
||||
/// Trim end: offset into the clip's internal content. See [`Self::trim_start`].
|
||||
/// Default: None (use full clip duration)
|
||||
pub trim_end: Option<f64>,
|
||||
pub trim_end: Option<ContentTime>,
|
||||
|
||||
/// Playback speed multiplier
|
||||
/// 1.0 = normal speed, 0.5 = half speed, 2.0 = double speed
|
||||
@@ -657,7 +847,36 @@ pub struct ClipInstance {
|
||||
/// When set, loop iterations are drawn/played before the content start.
|
||||
/// Default: None (no pre-loop)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub loop_before: Option<f64>,
|
||||
pub loop_before: Option<Beats>,
|
||||
|
||||
/// Alternate takes from cycle recording. Empty = an ordinary instance with no takes.
|
||||
///
|
||||
/// The takes live on the INSTANCE, not the clip, so managing them is per-instance: deleting or
|
||||
/// renaming a take on one instance leaves every other instance alone. Splitting clones the list
|
||||
/// along with the rest of the instance, so the two halves get independent take lists — and,
|
||||
/// since they can each select a different take, comping still falls out for free.
|
||||
///
|
||||
/// Every take spans the full cycle region (partial passes are padded with silence at capture
|
||||
/// time), so they're all the same length as the clip's own content. That uniformity is what lets
|
||||
/// a take switch leave the instance's geometry untouched.
|
||||
///
|
||||
/// When non-empty, these OVERRIDE the clip's own content — see [`Self::resolve`].
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub takes: Vec<AudioTake>,
|
||||
|
||||
/// Which of [`Self::takes`] plays. `None` (or a stale index) means take 0.
|
||||
/// Default: None
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub active_take: Option<usize>,
|
||||
|
||||
/// The cycle region's length in beats when these takes were recorded.
|
||||
///
|
||||
/// Audio takes are cut geometrically (by sample count), so they're only meaningful against the
|
||||
/// tempo they were recorded at. Keeping the recorded length lets a future time-stretch/conform
|
||||
/// feature reconcile them if the tempo moves underneath, and lets a new recording tell whether
|
||||
/// it belongs in this take list or a fresh one.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub recorded_loop_beats: Option<Beats>,
|
||||
}
|
||||
|
||||
/// High 64-bit sentinel used to identify UUIDs that encode a backend audio clip instance ID.
|
||||
@@ -709,13 +928,16 @@ impl ClipInstance {
|
||||
transform: Transform::default(),
|
||||
opacity: 1.0,
|
||||
name: None,
|
||||
timeline_start: 0.0,
|
||||
timeline_start: Beats::ZERO,
|
||||
timeline_duration: None,
|
||||
trim_start: 0.0,
|
||||
trim_start: ContentTime::ZERO,
|
||||
trim_end: None,
|
||||
playback_speed: 1.0,
|
||||
gain: 1.0,
|
||||
loop_before: None,
|
||||
takes: Vec::new(),
|
||||
active_take: None,
|
||||
recorded_loop_beats: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -727,13 +949,16 @@ impl ClipInstance {
|
||||
transform: Transform::default(),
|
||||
opacity: 1.0,
|
||||
name: None,
|
||||
timeline_start: 0.0,
|
||||
timeline_start: Beats::ZERO,
|
||||
timeline_duration: None,
|
||||
trim_start: 0.0,
|
||||
trim_start: ContentTime::ZERO,
|
||||
trim_end: None,
|
||||
playback_speed: 1.0,
|
||||
gain: 1.0,
|
||||
loop_before: None,
|
||||
takes: Vec::new(),
|
||||
active_take: None,
|
||||
recorded_loop_beats: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -762,14 +987,14 @@ impl ClipInstance {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set timeline position
|
||||
pub fn with_timeline_start(mut self, timeline_start: f64) -> Self {
|
||||
/// Set timeline position (beats).
|
||||
pub fn with_timeline_start(mut self, timeline_start: Beats) -> Self {
|
||||
self.timeline_start = timeline_start;
|
||||
self
|
||||
}
|
||||
|
||||
/// Set trimming (start and end time within the clip's internal content)
|
||||
pub fn with_trimming(mut self, trim_start: f64, trim_end: Option<f64>) -> Self {
|
||||
pub fn with_trimming(mut self, trim_start: ContentTime, trim_end: Option<ContentTime>) -> Self {
|
||||
self.trim_start = trim_start;
|
||||
self.trim_end = trim_end;
|
||||
self
|
||||
@@ -788,80 +1013,149 @@ impl ClipInstance {
|
||||
}
|
||||
|
||||
/// Set explicit timeline duration (in beats) by directly setting `timeline_duration`.
|
||||
pub fn with_timeline_duration(mut self, duration_beats: f64) -> Self {
|
||||
pub fn with_timeline_duration(mut self, duration_beats: Beats) -> Self {
|
||||
self.timeline_duration = Some(duration_beats);
|
||||
self
|
||||
}
|
||||
|
||||
/// Content window size in seconds: `trim_end - trim_start`.
|
||||
/// The take this instance plays, if it has any.
|
||||
///
|
||||
/// A `None`/stale `active_take` falls back to take 0 — an index can go stale (an undo that
|
||||
/// shrank the list, an old `.beam`), and silently playing the first take beats playing nothing.
|
||||
pub fn active_take(&self) -> Option<&AudioTake> {
|
||||
self.takes
|
||||
.get(self.active_take.unwrap_or(0))
|
||||
.or_else(|| self.takes.first())
|
||||
}
|
||||
|
||||
/// The index [`Self::active_take`] actually resolves to, clamped into range.
|
||||
pub fn active_take_index(&self) -> usize {
|
||||
let i = self.active_take.unwrap_or(0);
|
||||
if i < self.takes.len() { i } else { 0 }
|
||||
}
|
||||
|
||||
/// What this instance plays: its active take if it has takes, otherwise the clip's own content.
|
||||
///
|
||||
/// This is the sanctioned way to ask "what content do I hand the backend for this instance?".
|
||||
/// Takes are never a distinct *case* at the call site — an instance with takes is just an audio
|
||||
/// or MIDI instance whose identity depends on which take is live.
|
||||
pub fn resolve(&self, clip: &AudioClip) -> ResolvedContent {
|
||||
match self.active_take().map(|t| &t.content) {
|
||||
Some(TakeContent::Audio { audio_pool_index }) => ResolvedContent::Audio {
|
||||
audio_pool_index: *audio_pool_index,
|
||||
},
|
||||
Some(TakeContent::Midi { midi_clip_id }) => ResolvedContent::Midi {
|
||||
midi_clip_id: *midi_clip_id,
|
||||
},
|
||||
None => clip.resolve(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The audio pool index this instance plays. See [`Self::resolve`].
|
||||
pub fn resolved_audio_pool_index(&self, clip: &AudioClip) -> Option<usize> {
|
||||
match self.resolve(clip) {
|
||||
ResolvedContent::Audio { audio_pool_index } => Some(audio_pool_index),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The backend MIDI clip ID this instance plays. See [`Self::resolve`].
|
||||
pub fn resolved_midi_clip_id(&self, clip: &AudioClip) -> Option<u32> {
|
||||
match self.resolve(clip) {
|
||||
ResolvedContent::Midi { midi_clip_id } => Some(midi_clip_id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Content window (`trim_end - trim_start`) in the clip's own content domain.
|
||||
/// Used for internal looping calculations.
|
||||
pub fn content_window_secs(&self, clip_duration_secs: f64) -> f64 {
|
||||
let end = self.trim_end.unwrap_or(clip_duration_secs);
|
||||
(end - self.trim_start).max(0.0)
|
||||
pub fn content_window(&self, clip_content: ClipDuration) -> ClipDuration {
|
||||
let end = self.trim_end.map_or(clip_content.native(), |t| t.raw());
|
||||
let window = (end - self.trim_start.raw()).max(0.0);
|
||||
match clip_content {
|
||||
ClipDuration::Beats(_) => ClipDuration::Beats(Beats(window)),
|
||||
ClipDuration::Seconds(_) => ClipDuration::Seconds(Seconds(window)),
|
||||
}
|
||||
}
|
||||
|
||||
/// How long this instance appears on the timeline, in **beats**.
|
||||
///
|
||||
/// If `timeline_duration` is set, returns that (enabling content looping).
|
||||
/// Otherwise converts the content window from seconds to beats using the tempo map.
|
||||
pub fn effective_duration_beats(&self, clip_duration_secs: f64, tempo_map: &crate::tempo_map::TempoMap) -> f64 {
|
||||
/// If `timeline_duration` is set, returns that (enabling content looping). Otherwise the clip
|
||||
/// occupies its content window — converted to beats *in the clip's own domain*:
|
||||
///
|
||||
/// - MIDI content is already beats and is tempo-invariant, so it carries over directly.
|
||||
/// - Wall-clock content (audio/video/vector) is a seconds span, so it converts at the clip's
|
||||
/// position on the timeline.
|
||||
///
|
||||
/// Taking a `ClipDuration` rather than a bare `Seconds` is what keeps those apart: this used to
|
||||
/// take seconds and subtract `trim_start` from it, which for a TRIMMED MIDI clip subtracted a
|
||||
/// beats offset from a seconds duration and got the clip's length wrong.
|
||||
pub fn effective_duration_beats(&self, clip_content: ClipDuration, tempo_map: &crate::tempo_map::TempoMap) -> Beats {
|
||||
if let Some(td) = self.timeline_duration {
|
||||
return td;
|
||||
}
|
||||
let window_secs = self.content_window_secs(clip_duration_secs);
|
||||
let start_secs = tempo_map.transform(self.timeline_start);
|
||||
tempo_map.inverse_transform(start_secs + window_secs) - self.timeline_start
|
||||
match self.content_window(clip_content) {
|
||||
ClipDuration::Beats(b) => b,
|
||||
ClipDuration::Seconds(s) => {
|
||||
let start_secs = tempo_map.beats_to_seconds(self.timeline_start);
|
||||
tempo_map.seconds_to_beats(start_secs + s) - self.timeline_start
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Left edge of the clip's visual extent on the timeline, in **beats**.
|
||||
pub fn effective_start(&self) -> f64 {
|
||||
self.timeline_start - self.loop_before.unwrap_or(0.0)
|
||||
pub fn effective_start(&self) -> Beats {
|
||||
self.timeline_start - self.loop_before.unwrap_or(Beats::ZERO)
|
||||
}
|
||||
|
||||
/// Total visual duration (loop_before + effective_duration), in **beats**.
|
||||
pub fn total_duration(&self, clip_duration_secs: f64, tempo_map: &crate::tempo_map::TempoMap) -> f64 {
|
||||
self.loop_before.unwrap_or(0.0) + self.effective_duration_beats(clip_duration_secs, tempo_map)
|
||||
pub fn total_duration(&self, clip_content: ClipDuration, tempo_map: &crate::tempo_map::TempoMap) -> Beats {
|
||||
self.loop_before.unwrap_or(Beats::ZERO) + self.effective_duration_beats(clip_content, tempo_map)
|
||||
}
|
||||
|
||||
/// Map a playback time (in **seconds**) to clip-local content time (in **seconds**).
|
||||
///
|
||||
/// Returns `None` if the clip instance is not active at `time_secs`.
|
||||
pub fn remap_time_secs(&self, time_secs: f64, clip_duration_secs: f64, tempo_map: &crate::tempo_map::TempoMap) -> Option<f64> {
|
||||
let start_secs = tempo_map.transform(self.timeline_start);
|
||||
let dur_beats = self.effective_duration_beats(clip_duration_secs, tempo_map);
|
||||
let end_secs = tempo_map.transform(self.timeline_start + dur_beats);
|
||||
/// The trim bounds are resolved through `clip_content`'s domain first, so a MIDI clip's beats
|
||||
/// trims are converted rather than read as seconds. Callers are the wall-clock consumers (video
|
||||
/// seek, vector/raster rendering), which want seconds regardless of how the clip stores content.
|
||||
///
|
||||
/// Returns `None` if the clip instance is not active at `time`.
|
||||
pub fn remap_time_secs(&self, time: Seconds, clip_content: ClipDuration, tempo_map: &crate::tempo_map::TempoMap) -> Option<Seconds> {
|
||||
let start_secs = tempo_map.beats_to_seconds(self.timeline_start);
|
||||
let dur_beats = self.effective_duration_beats(clip_content, tempo_map);
|
||||
let end_secs = tempo_map.beats_to_seconds(self.timeline_start + dur_beats);
|
||||
|
||||
if time_secs < start_secs || time_secs >= end_secs {
|
||||
if time < start_secs || time >= end_secs {
|
||||
return None;
|
||||
}
|
||||
|
||||
let relative_secs = time_secs - start_secs;
|
||||
let content_time = relative_secs * self.playback_speed;
|
||||
let content_window = self.content_window_secs(clip_duration_secs);
|
||||
let trim_start_secs = clip_content.same_domain(self.trim_start).to_seconds(tempo_map);
|
||||
let content_time = (time - start_secs) * self.playback_speed;
|
||||
let content_window = self.content_window(clip_content).to_seconds(tempo_map);
|
||||
|
||||
if content_window == 0.0 {
|
||||
return Some(self.trim_start);
|
||||
if content_window == Seconds::ZERO {
|
||||
return Some(trim_start_secs);
|
||||
}
|
||||
|
||||
let looped_time = if content_time > content_window {
|
||||
let looped = if content_time > content_window {
|
||||
content_time % content_window
|
||||
} else {
|
||||
content_time
|
||||
};
|
||||
|
||||
Some(self.trim_start + looped_time)
|
||||
Some(trim_start_secs + looped)
|
||||
}
|
||||
|
||||
/// Alias for `remap_time_secs`.
|
||||
#[inline]
|
||||
pub fn remap_time(&self, time_secs: f64, clip_duration_secs: f64, tempo_map: &crate::tempo_map::TempoMap) -> Option<f64> {
|
||||
self.remap_time_secs(time_secs, clip_duration_secs, tempo_map)
|
||||
pub fn remap_time(&self, time: Seconds, clip_content: ClipDuration, tempo_map: &crate::tempo_map::TempoMap) -> Option<Seconds> {
|
||||
self.remap_time_secs(time, clip_content, tempo_map)
|
||||
}
|
||||
|
||||
/// Alias for `effective_duration_beats`.
|
||||
#[inline]
|
||||
pub fn effective_duration(&self, clip_duration_secs: f64, tempo_map: &crate::tempo_map::TempoMap) -> f64 {
|
||||
self.effective_duration_beats(clip_duration_secs, tempo_map)
|
||||
pub fn effective_duration(&self, clip_content: ClipDuration, tempo_map: &crate::tempo_map::TempoMap) -> Beats {
|
||||
self.effective_duration_beats(clip_content, tempo_map)
|
||||
}
|
||||
|
||||
/// Convert to affine transform
|
||||
@@ -902,7 +1196,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_audio_clip_midi() {
|
||||
let clip = AudioClip::new_midi("Piano Melody", 1, 60.0);
|
||||
let clip = AudioClip::new_midi("Piano Melody", 1, daw_backend::Beats(60.0));
|
||||
assert_eq!(clip.name, "Piano Melody");
|
||||
assert_eq!(clip.duration, 60.0);
|
||||
match &clip.clip_type {
|
||||
@@ -937,8 +1231,8 @@ mod tests {
|
||||
|
||||
assert_eq!(instance.clip_id, clip_id);
|
||||
assert_eq!(instance.opacity, 1.0);
|
||||
assert_eq!(instance.timeline_start, 0.0);
|
||||
assert_eq!(instance.trim_start, 0.0);
|
||||
assert_eq!(instance.timeline_start, Beats::ZERO);
|
||||
assert_eq!(instance.trim_start, ContentTime::ZERO);
|
||||
assert_eq!(instance.trim_end, None);
|
||||
assert_eq!(instance.playback_speed, 1.0);
|
||||
assert_eq!(instance.gain, 1.0);
|
||||
@@ -948,22 +1242,52 @@ mod tests {
|
||||
fn test_clip_instance_trimming() {
|
||||
let clip_id = Uuid::new_v4();
|
||||
let instance = ClipInstance::new(clip_id)
|
||||
.with_trimming(2.0, Some(8.0));
|
||||
.with_trimming(ContentTime(2.0), Some(ContentTime(8.0)));
|
||||
|
||||
assert_eq!(instance.trim_start, 2.0);
|
||||
assert_eq!(instance.trim_end, Some(8.0));
|
||||
assert_eq!(instance.effective_duration(10.0), 6.0);
|
||||
assert_eq!(instance.trim_start, ContentTime(2.0));
|
||||
assert_eq!(instance.trim_end, Some(ContentTime(8.0)));
|
||||
// At 60 BPM the tempo map is identity (1 beat == 1 second), so the
|
||||
// beats-domain effective duration equals the seconds content window.
|
||||
let tempo_map = crate::tempo_map::TempoMap::constant(60.0);
|
||||
let content = ClipDuration::Seconds(Seconds(10.0));
|
||||
assert_eq!(instance.effective_duration(content, &tempo_map), Beats(6.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_clip_instance_no_end_trim() {
|
||||
let clip_id = Uuid::new_v4();
|
||||
let instance = ClipInstance::new(clip_id)
|
||||
.with_trimming(2.0, None);
|
||||
.with_trimming(ContentTime(2.0), None);
|
||||
|
||||
assert_eq!(instance.trim_start, 2.0);
|
||||
assert_eq!(instance.trim_start, ContentTime(2.0));
|
||||
assert_eq!(instance.trim_end, None);
|
||||
assert_eq!(instance.effective_duration(10.0), 8.0);
|
||||
// At 60 BPM the tempo map is identity (1 beat == 1 second).
|
||||
let tempo_map = crate::tempo_map::TempoMap::constant(60.0);
|
||||
let content = ClipDuration::Seconds(Seconds(10.0));
|
||||
assert_eq!(instance.effective_duration(content, &tempo_map), Beats(8.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trimmed_midi_clip_keeps_its_beats_length_across_tempo() {
|
||||
// Regression: `effective_duration_beats` used to take a SECONDS clip duration and subtract
|
||||
// `trim_start` from it. For a TRIMMED MIDI clip that subtracted a beats offset from a
|
||||
// seconds duration, so the clip's timeline length came out wrong at any tempo but 60 BPM.
|
||||
//
|
||||
// MIDI content is beats and tempo-invariant: a clip trimmed to beats 2..6 is 4 beats long
|
||||
// whatever the tempo says.
|
||||
let clip_id = Uuid::new_v4();
|
||||
let instance = ClipInstance::new(clip_id)
|
||||
.with_trimming(ContentTime(2.0), Some(ContentTime(6.0)));
|
||||
let content = ClipDuration::Beats(Beats(8.0));
|
||||
|
||||
for bpm in [60.0, 120.0, 90.0] {
|
||||
let tempo_map = crate::tempo_map::TempoMap::constant(bpm);
|
||||
assert_eq!(
|
||||
instance.effective_duration(content, &tempo_map),
|
||||
Beats(4.0),
|
||||
"a MIDI clip trimmed to beats 2..6 is 4 beats long at {bpm} BPM",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -983,4 +1307,109 @@ mod tests {
|
||||
assert_eq!(instance.playback_speed, 2.0);
|
||||
assert_eq!(instance.gain, 0.8);
|
||||
}
|
||||
|
||||
/// A clip whose own content is pool 10, plus an instance carrying takes over the given pools.
|
||||
fn with_takes(pool_indices: &[usize]) -> (AudioClip, ClipInstance) {
|
||||
let clip = AudioClip::new_sampled("Cycle rec", pool_indices[0], 2.0);
|
||||
let mut instance = ClipInstance::new(clip.id);
|
||||
instance.takes = pool_indices
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, &audio_pool_index)| AudioTake {
|
||||
name: format!("Take {}", i + 1),
|
||||
content: TakeContent::Audio { audio_pool_index },
|
||||
})
|
||||
.collect();
|
||||
instance.recorded_loop_beats = Some(Beats(8.0));
|
||||
(clip, instance)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_take_selects_the_pool_file() {
|
||||
let (clip, mut instance) = with_takes(&[10, 11, 12]);
|
||||
instance.active_take = Some(0);
|
||||
assert_eq!(instance.resolved_audio_pool_index(&clip), Some(10));
|
||||
instance.active_take = Some(2);
|
||||
assert_eq!(instance.resolved_audio_pool_index(&clip), Some(12));
|
||||
// None means take 0.
|
||||
instance.active_take = None;
|
||||
assert_eq!(instance.resolved_audio_pool_index(&clip), Some(10));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_range_take_falls_back_to_the_first() {
|
||||
// An index can go stale (an undo that shrank the list, an old .beam). Playing the first take
|
||||
// beats playing nothing.
|
||||
let (clip, mut instance) = with_takes(&[10, 11]);
|
||||
instance.active_take = Some(99);
|
||||
assert_eq!(instance.resolved_audio_pool_index(&clip), Some(10));
|
||||
assert_eq!(instance.active_take_index(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_instance_without_takes_plays_the_clips_own_content() {
|
||||
let clip = AudioClip::new_sampled("Plain", 42, 2.0);
|
||||
let instance = ClipInstance::new(clip.id);
|
||||
assert!(instance.takes.is_empty());
|
||||
assert_eq!(instance.resolved_audio_pool_index(&clip), Some(42));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn midi_takes_resolve_to_midi_content() {
|
||||
let clip = AudioClip::new_midi("Cycle rec", 7, Beats(4.0));
|
||||
let mut instance = ClipInstance::new(clip.id);
|
||||
instance.takes = vec![AudioTake {
|
||||
name: "Take 1".into(),
|
||||
content: TakeContent::Midi { midi_clip_id: 7 },
|
||||
}];
|
||||
assert_eq!(clip.content_duration(), ClipDuration::Beats(Beats(4.0)));
|
||||
assert_eq!(instance.resolved_midi_clip_id(&clip), Some(7));
|
||||
assert_eq!(instance.resolved_audio_pool_index(&clip), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splitting_gives_each_half_an_independent_take_list() {
|
||||
// Takes live on the INSTANCE, so a split (which clones the instance) hands each half its own
|
||||
// list. Two consequences, both wanted: the halves can select different takes (comping), and
|
||||
// deleting a take from one leaves the other alone.
|
||||
let (clip, left_src) = with_takes(&[10, 11, 12]);
|
||||
let mut left = left_src.clone();
|
||||
let mut right = left_src.clone();
|
||||
right.id = Uuid::new_v4();
|
||||
|
||||
left.active_take = Some(0);
|
||||
right.active_take = Some(2);
|
||||
assert_eq!(left.resolved_audio_pool_index(&clip), Some(10));
|
||||
assert_eq!(right.resolved_audio_pool_index(&clip), Some(12));
|
||||
|
||||
// Delete take 2 (pool 11) from the left half only.
|
||||
left.takes.remove(1);
|
||||
assert_eq!(left.takes.len(), 2);
|
||||
assert_eq!(right.takes.len(), 3, "the other half keeps its own takes");
|
||||
assert_eq!(
|
||||
right.resolved_audio_pool_index(&clip),
|
||||
Some(12),
|
||||
"and its selection still points where it did",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clip_instance_without_active_take_deserializes() {
|
||||
// Back-compat: .beam files written before take folders have no `active_take` field.
|
||||
let json = r#"{
|
||||
"id": "550e8400-e29b-41d4-a716-446655440000",
|
||||
"clip_id": "550e8400-e29b-41d4-a716-446655440001",
|
||||
"transform": {"x": 0.0, "y": 0.0, "rotation": 0.0, "scale_x": 1.0, "scale_y": 1.0, "skew_x": 0.0, "skew_y": 0.0},
|
||||
"opacity": 1.0,
|
||||
"name": null,
|
||||
"timeline_start": 0.0,
|
||||
"timeline_duration": null,
|
||||
"trim_start": 0.0,
|
||||
"trim_end": null,
|
||||
"playback_speed": 1.0,
|
||||
"gain": 1.0
|
||||
}"#;
|
||||
let instance: ClipInstance = serde_json::from_str(json).expect("old instances must load");
|
||||
assert_eq!(instance.active_take, None);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -62,6 +62,7 @@ impl ClipboardLayerType {
|
||||
AnyLayer::Effect(_) => ClipboardLayerType::Effect,
|
||||
AnyLayer::Group(_) => ClipboardLayerType::Vector,
|
||||
AnyLayer::Raster(_) => ClipboardLayerType::Vector,
|
||||
AnyLayer::Text(_) => ClipboardLayerType::Vector,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -449,6 +450,13 @@ fn regen_any_layer(layer: &AnyLayer, id_map: &mut HashMap<Uuid, Uuid>) -> AnyLay
|
||||
nl.layer.id = new_layer_id;
|
||||
AnyLayer::Raster(nl)
|
||||
}
|
||||
AnyLayer::Text(tl) => {
|
||||
let new_layer_id = Uuid::new_v4();
|
||||
id_map.insert(tl.layer.id, new_layer_id);
|
||||
let mut nl = tl.clone();
|
||||
nl.layer.id = new_layer_id;
|
||||
AnyLayer::Text(nl)
|
||||
}
|
||||
AnyLayer::Group(gl) => {
|
||||
let new_layer_id = Uuid::new_v4();
|
||||
id_map.insert(gl.layer.id, new_layer_id);
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
use crate::asset_folder::AssetFolderTree;
|
||||
use crate::clip::{AudioClip, ClipInstance, ImageAsset, VideoClip, VectorClip};
|
||||
use daw_backend::{Beats, Seconds};
|
||||
use crate::effect::EffectDefinition;
|
||||
use crate::layer::{AnyLayer, GroupLayer};
|
||||
use crate::script::ScriptDefinition;
|
||||
@@ -145,6 +146,26 @@ pub enum TimelineMode {
|
||||
Frames,
|
||||
}
|
||||
|
||||
/// How super-white (HDR) values are mapped to the SDR display/export output at the final
|
||||
/// linear→sRGB encode. SDR content sits in [0,1] and is unaffected by either mode.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum HdrOutputMode {
|
||||
/// Hard-clip values above 1.0 (the historical behaviour). SDR-exact; HDR highlights blow out.
|
||||
#[default]
|
||||
Clip,
|
||||
/// Roll highlights above a knee smoothly toward 1.0 to recover detail. Slightly dims near-white.
|
||||
HighlightRolloff,
|
||||
}
|
||||
|
||||
impl HdrOutputMode {
|
||||
pub fn name(&self) -> &'static str {
|
||||
match self {
|
||||
HdrOutputMode::Clip => "Clip",
|
||||
HdrOutputMode::HighlightRolloff => "Highlight rolloff",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Asset category for folder tree access
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AssetCategory {
|
||||
@@ -180,6 +201,17 @@ pub struct Document {
|
||||
#[serde(default)]
|
||||
pub time_signature: TimeSignature,
|
||||
|
||||
/// Transport cycle (loop) region, as `(start, end)` in **beats**.
|
||||
///
|
||||
/// Authored in beats so it stays put musically when the tempo changes. `None` = no region set.
|
||||
/// Saved with the project; `#[serde(default)]` keeps older `.beam` files loading.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub cycle_region: Option<(Beats, Beats)>,
|
||||
|
||||
/// Whether the transport loops over `cycle_region`.
|
||||
#[serde(default)]
|
||||
pub cycle_enabled: bool,
|
||||
|
||||
/// Master track (master bus + tempo automation lane).
|
||||
/// Stored separately from the root layer tree; shown in timeline when
|
||||
/// `show_master_track` is enabled in the editor state.
|
||||
@@ -244,6 +276,10 @@ pub struct Document {
|
||||
#[serde(default)]
|
||||
pub timeline_mode: TimelineMode,
|
||||
|
||||
/// How HDR (super-white) values are mapped to the SDR output at the final encode.
|
||||
#[serde(default)]
|
||||
pub hdr_output_mode: HdrOutputMode,
|
||||
|
||||
/// Current UI layout state (serialized for save/load)
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub ui_layout: Option<LayoutNode>,
|
||||
@@ -272,12 +308,15 @@ impl Default for Document {
|
||||
height: 1080.0,
|
||||
framerate: 60.0,
|
||||
time_signature: TimeSignature::default(),
|
||||
cycle_region: None,
|
||||
cycle_enabled: false,
|
||||
master_layer: {
|
||||
let mut ml = GroupLayer::new_master(120.0);
|
||||
ml.layer.id = uuid::Uuid::new_v4();
|
||||
ml
|
||||
},
|
||||
duration: 10.0,
|
||||
hdr_output_mode: HdrOutputMode::default(),
|
||||
root: GraphicsObject::default(),
|
||||
vector_clips: HashMap::new(),
|
||||
video_clips: HashMap::new(),
|
||||
@@ -413,20 +452,27 @@ impl Document {
|
||||
/// Returns the end time of the last clip instance across all layers,
|
||||
/// or the document's duration if no clips are found.
|
||||
pub fn calculate_timeline_endpoint(&self) -> f64 {
|
||||
let tempo_map = self.tempo_map();
|
||||
// Accumulated in **beats** (as f64, to keep the recursive helper's `Fn(_, f64) -> f64`
|
||||
// signature); converted to seconds once at the return.
|
||||
let mut max_end_time: f64 = 0.0;
|
||||
|
||||
// Helper function to calculate the end time of a clip instance
|
||||
// End position of a clip instance, in **beats**. Its trimmed content window is in seconds
|
||||
// (scaled by playback speed), so convert that seconds span to beats via the tempo map — the
|
||||
// old code added a seconds duration straight onto the beats start.
|
||||
let calculate_instance_end = |instance: &ClipInstance, clip_duration: f64| -> f64 {
|
||||
let effective_duration = if let Some(timeline_duration) = instance.timeline_duration {
|
||||
// Explicit timeline duration set (may include looping)
|
||||
timeline_duration
|
||||
let end_beats: Beats = if let Some(timeline_duration) = instance.timeline_duration {
|
||||
instance.timeline_start + timeline_duration
|
||||
} else {
|
||||
// Calculate from trim points
|
||||
let trim_end = instance.trim_end.unwrap_or(clip_duration);
|
||||
let trimmed_duration = trim_end - instance.trim_start;
|
||||
trimmed_duration / instance.playback_speed // Adjust for playback speed
|
||||
// `clip_duration` arrives as seconds (the recursive helper's signature), so this
|
||||
// path is the wall-clock one; MIDI content would need resolving against its clip.
|
||||
let trim_end = instance.trim_end.map_or(clip_duration, |t| t.raw());
|
||||
let trimmed_secs =
|
||||
((trim_end - instance.trim_start.raw()) / instance.playback_speed).max(0.0);
|
||||
let start_secs = tempo_map.beats_to_seconds(instance.timeline_start);
|
||||
tempo_map.seconds_to_beats(start_secs + Seconds(trimmed_secs))
|
||||
};
|
||||
instance.timeline_start + effective_duration
|
||||
end_beats.beats_to_f64()
|
||||
};
|
||||
|
||||
// Iterate through all layers to find the maximum end time
|
||||
@@ -442,8 +488,10 @@ impl Document {
|
||||
}
|
||||
crate::layer::AnyLayer::Audio(audio_layer) => {
|
||||
for instance in &audio_layer.clip_instances {
|
||||
if let Some(clip) = self.audio_clips.get(&instance.clip_id) {
|
||||
let end_time = calculate_instance_end(instance, clip.duration);
|
||||
// get_clip_duration yields seconds (converting MIDI's beats duration),
|
||||
// which is what the closure expects.
|
||||
if let Some(clip_duration) = self.get_clip_duration(&instance.clip_id) {
|
||||
let end_time = calculate_instance_end(instance, clip_duration.seconds_to_f64());
|
||||
max_end_time = max_end_time.max(end_time);
|
||||
}
|
||||
}
|
||||
@@ -459,13 +507,13 @@ impl Document {
|
||||
crate::layer::AnyLayer::Effect(effect_layer) => {
|
||||
for instance in &effect_layer.clip_instances {
|
||||
if let Some(clip_duration) = self.get_clip_duration(&instance.clip_id) {
|
||||
let end_time = calculate_instance_end(instance, clip_duration);
|
||||
let end_time = calculate_instance_end(instance, clip_duration.seconds_to_f64());
|
||||
max_end_time = max_end_time.max(end_time);
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::layer::AnyLayer::Raster(_) => {
|
||||
// Raster layers don't have clip instances
|
||||
crate::layer::AnyLayer::Raster(_) | crate::layer::AnyLayer::Text(_) => {
|
||||
// Raster and text layers don't have clip instances
|
||||
}
|
||||
crate::layer::AnyLayer::Group(group) => {
|
||||
// Recurse into group children to find their clip instance endpoints
|
||||
@@ -486,8 +534,8 @@ impl Document {
|
||||
}
|
||||
crate::layer::AnyLayer::Audio(al) => {
|
||||
for inst in &al.clip_instances {
|
||||
if let Some(clip) = doc.audio_clips.get(&inst.clip_id) {
|
||||
*max_end = max_end.max(calc_end(inst, clip.duration));
|
||||
if let Some(clip_duration) = doc.get_clip_duration(&inst.clip_id) {
|
||||
*max_end = max_end.max(calc_end(inst, clip_duration.seconds_to_f64()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -501,12 +549,12 @@ impl Document {
|
||||
crate::layer::AnyLayer::Effect(el) => {
|
||||
for inst in &el.clip_instances {
|
||||
if let Some(dur) = doc.get_clip_duration(&inst.clip_id) {
|
||||
*max_end = max_end.max(calc_end(inst, dur));
|
||||
*max_end = max_end.max(calc_end(inst, dur.seconds_to_f64()));
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::layer::AnyLayer::Raster(_) => {
|
||||
// Raster layers don't have clip instances
|
||||
crate::layer::AnyLayer::Raster(_) | crate::layer::AnyLayer::Text(_) => {
|
||||
// Raster and text layers don't have clip instances
|
||||
}
|
||||
crate::layer::AnyLayer::Group(g) => {
|
||||
process_group_children(&g.children, doc, max_end, calc_end);
|
||||
@@ -519,9 +567,10 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
// Return the maximum end time, or document duration if no clips found
|
||||
// Return the max end (converting the beats accumulator to seconds), or the document
|
||||
// duration (already seconds) if no clips were found.
|
||||
if max_end_time > 0.0 {
|
||||
max_end_time
|
||||
tempo_map.beats_to_seconds(Beats(max_end_time)).seconds_to_f64()
|
||||
} else {
|
||||
self.duration
|
||||
}
|
||||
@@ -650,6 +699,29 @@ impl Document {
|
||||
layers
|
||||
}
|
||||
|
||||
/// Get mutable references to all layers across the entire document
|
||||
/// (root + nested groups + inside all vector clips). Mirrors [`all_layers`].
|
||||
pub fn all_layers_mut(&mut self) -> Vec<&mut AnyLayer> {
|
||||
let mut layers: Vec<&mut AnyLayer> = Vec::new();
|
||||
// Iterative walk with an explicit stack of child slices. Group layers are
|
||||
// descended into but not themselves collected (they hold no keyframes).
|
||||
let mut stack: Vec<&mut [AnyLayer]> = vec![&mut self.root.children];
|
||||
while let Some(list) = stack.pop() {
|
||||
for layer in list {
|
||||
match layer {
|
||||
AnyLayer::Group(g) => {
|
||||
stack.push(&mut g.children);
|
||||
}
|
||||
other => layers.push(other),
|
||||
}
|
||||
}
|
||||
}
|
||||
for clip in self.vector_clips.values_mut() {
|
||||
layers.extend(clip.layers.root_data_mut());
|
||||
}
|
||||
layers
|
||||
}
|
||||
|
||||
// === CLIP LIBRARY METHODS ===
|
||||
|
||||
/// Add a vector clip to the library
|
||||
@@ -711,16 +783,18 @@ impl Document {
|
||||
}
|
||||
|
||||
/// Find the document audio clip (UUID + ref) that owns the given backend pool index.
|
||||
/// A take folder owns one pool file per take, so any of them maps back to the folder.
|
||||
pub fn audio_clip_by_pool_index(&self, pool_index: usize) -> Option<(Uuid, &AudioClip)> {
|
||||
self.audio_clips.iter()
|
||||
.find(|(_, c)| c.audio_pool_index() == Some(pool_index))
|
||||
.find(|(_, c)| c.owns_audio_pool_index(pool_index))
|
||||
.map(|(&id, c)| (id, c))
|
||||
}
|
||||
|
||||
/// Find the document audio clip (UUID + ref) that owns the given backend MIDI clip ID.
|
||||
/// As above, a take folder owns one MIDI clip per take.
|
||||
pub fn audio_clip_by_midi_clip_id(&self, midi_clip_id: u32) -> Option<(Uuid, &AudioClip)> {
|
||||
self.audio_clips.iter()
|
||||
.find(|(_, c)| c.midi_clip_id() == Some(midi_clip_id))
|
||||
.find(|(_, c)| c.owns_midi_clip_id(midi_clip_id))
|
||||
.map(|(&id, c)| (id, c))
|
||||
}
|
||||
|
||||
@@ -842,19 +916,94 @@ impl Document {
|
||||
/// Searches through all clip libraries to find the clip and return its duration.
|
||||
/// For effect definitions, returns `EFFECT_DURATION` (f64::MAX) since effects
|
||||
/// have infinite internal duration.
|
||||
pub fn get_clip_duration(&self, clip_id: &Uuid) -> Option<f64> {
|
||||
/// A clip's content duration **in the domain its `trim_start`/`trim_end` are measured in**.
|
||||
///
|
||||
/// Content time is domain-polymorphic exactly like `AudioClip::duration`: SECONDS for sampled
|
||||
/// audio, video and vector, but BEATS for MIDI. Anything doing arithmetic against a trim value —
|
||||
/// mapping a timeline position into the clip's content, say — has to work in that same domain,
|
||||
/// and [`Self::get_clip_duration`] can't tell it which: that one always converts to seconds.
|
||||
///
|
||||
/// Returns `None` for unknown clips.
|
||||
pub fn clip_trim_duration(&self, clip_id: &Uuid) -> Option<crate::clip::ClipDuration> {
|
||||
if let Some(clip) = self.audio_clips.get(clip_id) {
|
||||
return Some(clip.content_duration());
|
||||
}
|
||||
// Everything else measures its content in wall-clock seconds.
|
||||
self.get_clip_duration(clip_id).map(crate::clip::ClipDuration::Seconds)
|
||||
}
|
||||
|
||||
/// Find an existing take folder on `layer_id` that a new cycle recording should be appended to.
|
||||
///
|
||||
/// Cycle-recording over a region that already holds a take folder should ADD to that folder
|
||||
/// rather than drop a second clip on top of it — otherwise the new takes are stranded in a
|
||||
/// separate, overlapping clip and can't be auditioned against the ones already there.
|
||||
///
|
||||
/// "The same region" means the instance starts at `loop_start` and its folder was recorded
|
||||
/// against the same loop length. Matching the length too means resizing the cycle region starts
|
||||
/// a fresh folder rather than appending takes of a different length to an existing one, which
|
||||
/// would break the uniform-take invariant comping depends on.
|
||||
///
|
||||
/// `exclude` is the in-progress recording's own instance, which is on the layer but isn't a
|
||||
/// candidate. Returns the instance id.
|
||||
pub fn take_folder_at(
|
||||
&self,
|
||||
layer_id: &Uuid,
|
||||
loop_start: Beats,
|
||||
loop_len: Beats,
|
||||
exclude: &Uuid,
|
||||
) -> Option<Uuid> {
|
||||
let Some(AnyLayer::Audio(audio_layer)) = self.get_layer(layer_id) else {
|
||||
return None;
|
||||
};
|
||||
const EPS: f64 = 1e-6;
|
||||
audio_layer.clip_instances.iter().find_map(|ci| {
|
||||
if ci.id == *exclude
|
||||
|| ci.takes.is_empty()
|
||||
|| (ci.timeline_start - loop_start).beats_to_f64().abs() > EPS
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let recorded = ci.recorded_loop_beats?;
|
||||
((recorded - loop_len).beats_to_f64().abs() < EPS).then_some(ci.id)
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolve a [`ContentTime`] (a trim bound) against the clip it belongs to.
|
||||
///
|
||||
/// The clip is the only thing that knows whether its content is measured in seconds or beats, so
|
||||
/// this is the sanctioned exit from `ContentTime`. Works for every clip kind, not just audio.
|
||||
/// Returns `None` for unknown clips.
|
||||
pub fn resolve_content_time(
|
||||
&self,
|
||||
clip_id: &Uuid,
|
||||
t: daw_backend::ContentTime,
|
||||
) -> Option<crate::clip::ClipDuration> {
|
||||
if let Some(clip) = self.audio_clips.get(clip_id) {
|
||||
return Some(clip.resolve_content_time(t));
|
||||
}
|
||||
if self.vector_clips.contains_key(clip_id)
|
||||
|| self.video_clips.contains_key(clip_id)
|
||||
|| self.effect_definitions.contains_key(clip_id)
|
||||
{
|
||||
// Wall-clock content.
|
||||
return Some(crate::clip::ClipDuration::Seconds(Seconds(t.raw())));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn get_clip_duration(&self, clip_id: &Uuid) -> Option<Seconds> {
|
||||
if let Some(clip) = self.vector_clips.get(clip_id) {
|
||||
if clip.is_group {
|
||||
Some(clip.duration)
|
||||
Some(Seconds(clip.duration))
|
||||
} else {
|
||||
let tempo_map = self.tempo_map();
|
||||
Some(clip.content_duration_with(self.framerate, tempo_map, |id| {
|
||||
Some(Seconds(clip.content_duration_with(self.framerate, tempo_map, |id| {
|
||||
// Resolve nested clip durations (audio, video, other vector clips)
|
||||
if let Some(vc) = self.vector_clips.get(id) {
|
||||
// Avoid deep recursion — use stored duration for nested vector clips
|
||||
Some(vc.content_duration(self.framerate, tempo_map))
|
||||
} else if let Some(ac) = self.audio_clips.get(id) {
|
||||
Some(ac.duration)
|
||||
Some(ac.content_duration().to_seconds(tempo_map).seconds_to_f64())
|
||||
} else if let Some(vc) = self.video_clips.get(id) {
|
||||
Some(vc.duration)
|
||||
} else if self.effect_definitions.contains_key(id) {
|
||||
@@ -862,23 +1011,25 @@ impl Document {
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}))
|
||||
})))
|
||||
}
|
||||
} else if let Some(clip) = self.video_clips.get(clip_id) {
|
||||
Some(clip.duration)
|
||||
Some(Seconds(clip.duration))
|
||||
} else if let Some(clip) = self.audio_clips.get(clip_id) {
|
||||
Some(clip.duration)
|
||||
// Interpret the clip's native-domain duration as wall-clock seconds (MIDI stores
|
||||
// beats, sampled stores seconds — content_duration keeps that straight).
|
||||
Some(clip.content_duration().to_seconds(self.tempo_map()))
|
||||
} else if self.effect_definitions.contains_key(clip_id) {
|
||||
// Effects have infinite internal duration - their timeline length
|
||||
// is controlled by ClipInstance.trim_end
|
||||
Some(crate::effect::EFFECT_DURATION)
|
||||
Some(Seconds(crate::effect::EFFECT_DURATION))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// Calculate the end time of a clip instance on the timeline
|
||||
pub fn get_clip_instance_end_time(&self, layer_id: &Uuid, instance_id: &Uuid) -> Option<f64> {
|
||||
/// Calculate the end position of a clip instance on the timeline, in **beats**.
|
||||
pub fn get_clip_instance_end_time(&self, layer_id: &Uuid, instance_id: &Uuid) -> Option<Beats> {
|
||||
let layer = self.get_layer(layer_id)?;
|
||||
|
||||
// Find the clip instance
|
||||
@@ -889,16 +1040,13 @@ impl Document {
|
||||
AnyLayer::Effect(effect) => &effect.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
let instance = instances.iter().find(|inst| &inst.id == instance_id)?;
|
||||
let clip_duration = self.get_clip_duration(&instance.clip_id)?;
|
||||
|
||||
let trim_start = instance.trim_start;
|
||||
let trim_end = instance.trim_end.unwrap_or(clip_duration);
|
||||
let effective_duration = trim_end - trim_start;
|
||||
|
||||
Some(instance.timeline_start + effective_duration)
|
||||
// The clip's content duration in ITS OWN domain, so the trims resolve correctly for MIDI.
|
||||
let clip_content = self.clip_trim_duration(&instance.clip_id)?;
|
||||
Some(instance.timeline_start + instance.effective_duration_beats(clip_content, self.tempo_map()))
|
||||
}
|
||||
|
||||
/// Check if a time range overlaps with any existing clip on the layer
|
||||
@@ -909,8 +1057,8 @@ impl Document {
|
||||
pub fn check_overlap_on_layer(
|
||||
&self,
|
||||
layer_id: &Uuid,
|
||||
start_time: f64,
|
||||
end_time: f64,
|
||||
start_time: Beats,
|
||||
end_time: Beats,
|
||||
exclude_instance_ids: &[Uuid],
|
||||
) -> (bool, Option<Uuid>) {
|
||||
let Some(layer) = self.get_layer(layer_id) else {
|
||||
@@ -929,6 +1077,7 @@ impl Document {
|
||||
AnyLayer::Effect(effect) => &effect.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
for instance in instances {
|
||||
@@ -937,13 +1086,14 @@ impl Document {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Calculate instance extent (accounting for loop_before)
|
||||
let Some(clip_duration) = self.get_clip_duration(&instance.clip_id) else {
|
||||
// Calculate instance extent (accounting for loop_before). Content duration in the clip's
|
||||
// own domain, so the trims resolve correctly for MIDI.
|
||||
let Some(clip_content) = self.clip_trim_duration(&instance.clip_id) else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let instance_start = instance.effective_start();
|
||||
let instance_end = instance.timeline_start + instance.effective_duration(clip_duration, self.tempo_map());
|
||||
let instance_end = instance.timeline_start + instance.effective_duration(clip_content, self.tempo_map());
|
||||
|
||||
// Check overlap: start_a < end_b AND start_b < end_a
|
||||
if start_time < instance_end && instance_start < end_time {
|
||||
@@ -962,14 +1112,14 @@ impl Document {
|
||||
pub fn find_nearest_valid_position(
|
||||
&self,
|
||||
layer_id: &Uuid,
|
||||
desired_start: f64,
|
||||
clip_duration: f64,
|
||||
desired_start: Beats,
|
||||
clip_duration: Beats,
|
||||
exclude_instance_ids: &[Uuid],
|
||||
) -> Option<f64> {
|
||||
) -> Option<Beats> {
|
||||
let layer = self.get_layer(layer_id)?;
|
||||
|
||||
// Clamp to timeline start (can't go before 0)
|
||||
let desired_start = desired_start.max(0.0);
|
||||
let desired_start = desired_start.max(Beats::ZERO);
|
||||
|
||||
// Vector layers don't need overlap adjustment, but still respect timeline start
|
||||
if matches!(layer, AnyLayer::Vector(_) | AnyLayer::Group(_)) {
|
||||
@@ -991,15 +1141,16 @@ impl Document {
|
||||
AnyLayer::Vector(_) => return Some(desired_start), // Shouldn't reach here
|
||||
AnyLayer::Group(_) => return Some(desired_start), // Groups don't have own clips
|
||||
AnyLayer::Raster(_) => return Some(desired_start), // Raster layers don't have own clips
|
||||
AnyLayer::Text(_) => return Some(desired_start), // Text layers don't have own clips
|
||||
};
|
||||
|
||||
let mut occupied_ranges: Vec<(f64, f64, Uuid)> = Vec::new();
|
||||
let mut occupied_ranges: Vec<(Beats, Beats, Uuid)> = Vec::new();
|
||||
for instance in instances {
|
||||
if exclude_instance_ids.contains(&instance.id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(clip_dur) = self.get_clip_duration(&instance.clip_id) {
|
||||
if let Some(clip_dur) = self.clip_trim_duration(&instance.clip_id) {
|
||||
let inst_start = instance.effective_start();
|
||||
let inst_end = instance.timeline_start + instance.effective_duration(clip_dur, self.tempo_map());
|
||||
occupied_ranges.push((inst_start, inst_end, instance.id));
|
||||
@@ -1012,7 +1163,7 @@ impl Document {
|
||||
// Find the clip we're overlapping with and try both sides, pick nearest
|
||||
for (occupied_start, occupied_end, _) in &occupied_ranges {
|
||||
if desired_start < *occupied_end && *occupied_start < desired_end {
|
||||
let mut candidates: Vec<f64> = Vec::new();
|
||||
let mut candidates: Vec<Beats> = Vec::new();
|
||||
|
||||
// Try snapping to the right (after this clip)
|
||||
let snap_right = *occupied_end;
|
||||
@@ -1028,8 +1179,8 @@ impl Document {
|
||||
}
|
||||
|
||||
// Try snapping to the left (before this clip)
|
||||
let snap_left = occupied_start - clip_duration;
|
||||
if snap_left >= 0.0 {
|
||||
let snap_left = *occupied_start - clip_duration;
|
||||
if snap_left >= Beats::ZERO {
|
||||
let (overlaps_left, _) = self.check_overlap_on_layer(
|
||||
layer_id,
|
||||
snap_left,
|
||||
@@ -1044,8 +1195,8 @@ impl Document {
|
||||
// Pick the candidate closest to desired_start
|
||||
if !candidates.is_empty() {
|
||||
candidates.sort_by(|a, b| {
|
||||
let dist_a = (a - desired_start).abs();
|
||||
let dist_b = (b - desired_start).abs();
|
||||
let dist_a = (*a - desired_start).abs();
|
||||
let dist_b = (*b - desired_start).abs();
|
||||
dist_a.partial_cmp(&dist_b).unwrap_or(std::cmp::Ordering::Equal)
|
||||
});
|
||||
return Some(candidates[0]);
|
||||
@@ -1055,7 +1206,7 @@ impl Document {
|
||||
|
||||
// If no gap found, try placing at timeline start
|
||||
if occupied_ranges.is_empty() || occupied_ranges[0].0 >= clip_duration {
|
||||
return Some(0.0);
|
||||
return Some(Beats::ZERO);
|
||||
}
|
||||
|
||||
// No valid position found
|
||||
@@ -1067,9 +1218,9 @@ impl Document {
|
||||
pub fn clamp_group_move_offset(
|
||||
&self,
|
||||
layer_id: &Uuid,
|
||||
group: &[(Uuid, f64, f64)], // (instance_id, timeline_start, effective_duration)
|
||||
desired_offset: f64,
|
||||
) -> f64 {
|
||||
group: &[(Uuid, Beats, Beats)], // (instance_id, timeline_start, effective_duration) in beats
|
||||
desired_offset: Beats,
|
||||
) -> Beats {
|
||||
let Some(layer) = self.get_layer(layer_id) else {
|
||||
return desired_offset;
|
||||
};
|
||||
@@ -1086,15 +1237,16 @@ impl Document {
|
||||
AnyLayer::Vector(v) => &v.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
// Collect non-group clip ranges
|
||||
let mut non_group: Vec<(f64, f64)> = Vec::new();
|
||||
// Collect non-group clip ranges (beats)
|
||||
let mut non_group: Vec<(Beats, Beats)> = Vec::new();
|
||||
for inst in instances {
|
||||
if group_ids.contains(&inst.id) {
|
||||
continue;
|
||||
}
|
||||
if let Some(dur) = self.get_clip_duration(&inst.clip_id) {
|
||||
if let Some(dur) = self.clip_trim_duration(&inst.clip_id) {
|
||||
let start = inst.effective_start();
|
||||
let end = inst.timeline_start + inst.effective_duration(dur, self.tempo_map());
|
||||
non_group.push((start, end));
|
||||
@@ -1111,12 +1263,12 @@ impl Document {
|
||||
|
||||
// Check against non-group clips
|
||||
for &(ns, ne) in &non_group {
|
||||
if clamped < 0.0 {
|
||||
if clamped < Beats::ZERO {
|
||||
// Moving left: if non-group clip end is between our destination and current start
|
||||
if ne <= start && ne > start + clamped {
|
||||
clamped = clamped.max(ne - start);
|
||||
}
|
||||
} else if clamped > 0.0 {
|
||||
} else if clamped > Beats::ZERO {
|
||||
// Moving right: if non-group clip start is between our current end and destination
|
||||
if ns >= end && ns < end + clamped {
|
||||
clamped = clamped.min(ns - end);
|
||||
@@ -1132,23 +1284,25 @@ impl Document {
|
||||
///
|
||||
/// Returns the distance to the nearest clip to the left, or the distance to
|
||||
/// timeline start (0.0) if no clips exist to the left.
|
||||
/// Returns the max leftward trim extension as a content-seconds span (the wall-clock
|
||||
/// length of the timeline gap to the previous clip); the trim domain is seconds.
|
||||
pub fn find_max_trim_extend_left(
|
||||
&self,
|
||||
layer_id: &Uuid,
|
||||
instance_id: &Uuid,
|
||||
current_timeline_start: f64,
|
||||
) -> f64 {
|
||||
current_timeline_start: Beats,
|
||||
) -> Seconds {
|
||||
let Some(layer) = self.get_layer(layer_id) else {
|
||||
return current_timeline_start; // No limit if layer not found
|
||||
return self.tempo_map().beats_to_seconds(current_timeline_start); // No limit if layer not found
|
||||
};
|
||||
|
||||
// Only check audio, video, and effect layers
|
||||
if matches!(layer, AnyLayer::Vector(_) | AnyLayer::Group(_)) {
|
||||
return current_timeline_start; // No limit for vector/group layers
|
||||
return self.tempo_map().beats_to_seconds(current_timeline_start); // No limit for vector/group layers
|
||||
};
|
||||
|
||||
// Find the nearest clip to the left
|
||||
let mut nearest_end = 0.0; // Can extend to timeline start by default
|
||||
let mut nearest_end = Beats::ZERO; // Can extend to timeline start by default
|
||||
|
||||
let instances: &[ClipInstance] = match layer {
|
||||
AnyLayer::Audio(audio) => &audio.clip_instances,
|
||||
@@ -1157,6 +1311,7 @@ impl Document {
|
||||
AnyLayer::Vector(vector) => &vector.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
for other in instances {
|
||||
@@ -1165,7 +1320,7 @@ impl Document {
|
||||
}
|
||||
|
||||
// Calculate other clip's extent (accounting for loop_before)
|
||||
if let Some(clip_duration) = self.get_clip_duration(&other.clip_id) {
|
||||
if let Some(clip_duration) = self.clip_trim_duration(&other.clip_id) {
|
||||
let other_end = other.timeline_start + other.effective_duration(clip_duration, self.tempo_map());
|
||||
|
||||
// If this clip is to the left and closer than current nearest
|
||||
@@ -1175,27 +1330,27 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
current_timeline_start - nearest_end
|
||||
self.tempo_map().beats_to_seconds(current_timeline_start) - self.tempo_map().beats_to_seconds(nearest_end)
|
||||
}
|
||||
|
||||
/// Find the maximum amount we can extend a clip to the right without overlapping
|
||||
/// Find the maximum amount we can extend a clip to the right without overlapping.
|
||||
///
|
||||
/// Returns the distance to the nearest clip to the right, or f64::MAX if no
|
||||
/// clips exist to the right.
|
||||
/// Returns the content-seconds span of the timeline gap to the nearest clip on the
|
||||
/// right, or Seconds(f64::MAX) if none. `current_effective_duration` is beats (timeline).
|
||||
pub fn find_max_trim_extend_right(
|
||||
&self,
|
||||
layer_id: &Uuid,
|
||||
instance_id: &Uuid,
|
||||
current_timeline_start: f64,
|
||||
current_effective_duration: f64,
|
||||
) -> f64 {
|
||||
current_timeline_start: Beats,
|
||||
current_effective_duration: Beats,
|
||||
) -> Seconds {
|
||||
let Some(layer) = self.get_layer(layer_id) else {
|
||||
return f64::MAX; // No limit if layer not found
|
||||
return Seconds(f64::MAX); // No limit if layer not found
|
||||
};
|
||||
|
||||
// Only check audio, video, and effect layers
|
||||
if matches!(layer, AnyLayer::Vector(_) | AnyLayer::Group(_)) {
|
||||
return f64::MAX; // No limit for vector/group layers
|
||||
return Seconds(f64::MAX); // No limit for vector/group layers
|
||||
}
|
||||
|
||||
let instances: &[ClipInstance] = match layer {
|
||||
@@ -1205,9 +1360,10 @@ impl Document {
|
||||
AnyLayer::Vector(vector) => &vector.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
let mut nearest_start = f64::MAX;
|
||||
let mut nearest_start = Beats(f64::MAX);
|
||||
let current_end = current_timeline_start + current_effective_duration;
|
||||
|
||||
for other in instances {
|
||||
@@ -1222,10 +1378,11 @@ impl Document {
|
||||
}
|
||||
}
|
||||
|
||||
if nearest_start == f64::MAX {
|
||||
f64::MAX // No clip to the right, can extend freely
|
||||
if nearest_start == Beats(f64::MAX) {
|
||||
Seconds(f64::MAX) // No clip to the right, can extend freely
|
||||
} else {
|
||||
(nearest_start - current_end).max(0.0) // Gap between our end and next clip's start
|
||||
// Gap between our end and next clip's start, as content seconds.
|
||||
(self.tempo_map().beats_to_seconds(nearest_start) - self.tempo_map().beats_to_seconds(current_end)).max(Seconds::ZERO)
|
||||
}
|
||||
}
|
||||
/// Find the maximum amount we can extend loop_before to the left without overlapping.
|
||||
@@ -1235,8 +1392,8 @@ impl Document {
|
||||
&self,
|
||||
layer_id: &Uuid,
|
||||
instance_id: &Uuid,
|
||||
current_effective_start: f64,
|
||||
) -> f64 {
|
||||
current_effective_start: Beats,
|
||||
) -> Beats {
|
||||
let Some(layer) = self.get_layer(layer_id) else {
|
||||
return current_effective_start;
|
||||
};
|
||||
@@ -1252,16 +1409,17 @@ impl Document {
|
||||
AnyLayer::Vector(vector) => &vector.clip_instances,
|
||||
AnyLayer::Group(_) => &[],
|
||||
AnyLayer::Raster(_) => &[],
|
||||
AnyLayer::Text(_) => &[],
|
||||
};
|
||||
|
||||
let mut nearest_end = 0.0;
|
||||
let mut nearest_end = Beats::ZERO;
|
||||
|
||||
for other in instances {
|
||||
if &other.id == instance_id {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(clip_duration) = self.get_clip_duration(&other.clip_id) {
|
||||
if let Some(clip_duration) = self.clip_trim_duration(&other.clip_id) {
|
||||
let other_end = other.timeline_start + other.effective_duration(clip_duration, self.tempo_map());
|
||||
|
||||
if other_end <= current_effective_start && other_end > nearest_end {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user