A free and open-source video editor for Windows and Linux, written in Rust: a track-based timeline, effects at every level, OpenFX and VST 3 hosts, studio audio and color.
BananaV 0.2.0
Acaso802be39da1b0
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.ymlindex 1333c9e..829ac45 100644--- a/.github/ISSUE_TEMPLATE/bug_report.yml+++ b/.github/ISSUE_TEMPLATE/bug_report.yml@@ -15,7 +15,7 @@ body:attributes:label: BananaV versiondescription: The package's name, or the commit you built from.- placeholder: BananaV-0.1.0-abc1234-windows-x64+ placeholder: BananaV-0.2.0-windows-x64validations:required: true- type: dropdowndiff --git a/.github/workflows/package.yml b/.github/workflows/package.ymlindex 8b49ca1..efa142a 100644--- a/.github/workflows/package.yml+++ b/.github/workflows/package.yml@@ -4,7 +4,8 @@## - Windows x64 and ARM64: BananaV.exe (the C runtime inside), a README,# the license texts and the third-party notices-# (tools/third_party_notices.py) in a zip;+# (tools/third_party_notices.py), in a zip and in an installer+# (packaging/windows/bananav.iss, Inno Setup), which is tried out here;# - Linux x64 and ARM64: an AppImage, built on Ubuntu 22.04 for every# distribution since (glibc 2.35), with FFmpeg's libraries built here# under the LGPL (packaging/linux/build_ffmpeg.sh), the third-party and@@ -66,11 +67,48 @@ jobs:cp crates/vst3-sys/licenses/vst3-pluginterfaces.txt "dist/$name/VST3-SDK-interfaces-license.txt"python tools/third_party_notices.py "$(rustc -vV | sed -n 's/^host: //p')" > "dist/$name/THIRD-PARTY-NOTICES.txt"echo "NAME=$name" >> "$GITHUB_ENV"+ - name: Installer+ shell: pwsh+ run: |+ $version = (Select-String -Path Cargo.toml -Pattern '^version = "(.*)"').Matches[0].Groups[1].Value+ $iscc = "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe"+ if (-not (Test-Path $iscc)) { choco install innosetup --no-progress -y }+ if (-not (Test-Path $iscc)) {+ Invoke-WebRequest -OutFile innosetup.exe https://jrsoftware.org/download.php/is.exe+ Start-Process -Wait innosetup.exe -ArgumentList '/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/SP-'+ }+ & $iscc /Qp "/DAppVersion=$version" "/DArch=${{ matrix.arch }}" "/DFiles=$PWD\dist\$env:NAME" "/O$PWD\dist-setup" "/F$env:NAME-setup" packaging\windows\bananav.iss+ if ($LASTEXITCODE) { exit $LASTEXITCODE }+ - name: The installer, tried out+ # Installs without a question, starts BananaV for a while, opens+ # nothing else, and takes it all away again.+ shell: pwsh+ run: |+ $setup = Start-Process -Wait -PassThru "dist-setup\$env:NAME-setup.exe" -ArgumentList '/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/TASKS=desktopicon,projects'+ if ($setup.ExitCode) { throw "the installer stopped with $($setup.ExitCode)" }+ $app = "$env:LOCALAPPDATA\Programs\BananaV"+ foreach ($file in "$app\BananaV.exe", "$app\bananav.ico", "$app\LICENSE.txt", "$env:APPDATA\Microsoft\Windows\Start Menu\Programs\BananaV.lnk", "$env:USERPROFILE\Desktop\BananaV.lnk") {+ if (-not (Test-Path $file)) { throw "no $file" }+ }+ $command = (Get-ItemProperty 'HKCU:\Software\Classes\BananaV.Project\shell\open\command').'(default)'+ if ($command -notlike '*BananaV.exe*') { throw "project files open with $command" }+ $running = Start-Process -PassThru "$app\BananaV.exe"+ Start-Sleep 20+ if ($running.HasExited) { Write-Warning "BananaV stopped with exit code $($running.ExitCode)" } else { $running | Stop-Process -Force; "BananaV was still running after 20 s" }+ Start-Process -Wait "$app\unins000.exe" -ArgumentList '/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART'+ foreach ($i in 1..30) { if (-not (Test-Path "$app\BananaV.exe")) { break }; Start-Sleep 1 }+ if (Test-Path "$app\BananaV.exe") { throw "the uninstaller left BananaV.exe" }+ if (Test-Path 'HKCU:\Software\Classes\BananaV.Project') { throw "the uninstaller left the project files' association" }- uses: actions/upload-artifact@v4with:name: ${{ env.NAME }}path: dist/${{ env.NAME }}retention-days: 30+ - uses: actions/upload-artifact@v4+ with:+ name: ${{ env.NAME }}-setup+ path: dist-setup/${{ env.NAME }}-setup.exe+ retention-days: 30linux:name: Linux ${{ matrix.arch }}diff --git a/ATTRIBUTION.md b/ATTRIBUTION.mdindex 18b715b..921b535 100644--- a/ATTRIBUTION.md+++ b/ATTRIBUTION.md@@ -66,6 +66,7 @@ their licenses ask for.| What | Where in BananaV | Author | License ||---|---|---|---|| OpenFX 1.5's C headers (unchanged, the reference `crates/ofx-sys` follows) | `vendor/openfx/` | OpenFX and contributors to the OpenFX project | BSD-3-Clause (`vendor/openfx/LICENSE.md`) |+| Inno Setup 6, the tool that makes the Windows installer (not in the repository; its setup program is inside the installer) | `packaging/windows/bananav.iss`, `.github/workflows/package.yml` | Jordan Russell and Martijn Laan | Inno Setup License || egui_dock 0.21.1, with BananaV's changes | `vendor/egui_dock/` (`BANANAV.md` lists the changes) | Adam Gąsior and contributors | MIT (`vendor/egui_dock/LICENSE`) || egui-winit 0.36.2, with BananaV's change | `vendor/egui-winit/` (`BANANAV.md` lists the change) | Emil Ernerfeldt and contributors | MIT OR Apache-2.0 (`vendor/egui-winit/LICENSE-MIT`) || VST 3's interface declarations, written from the SDK's headers | `crates/vst3-sys/` | Steinberg Media Technologies GmbH | MIT (`crates/vst3-sys/licenses/vst3-pluginterfaces.txt`) |diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9178e65..600ba3f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,50 @@ What changed in each public build of BananaV. The[Releases page](https://github.com/acasoq-web/BananaV/releases) has thedownloads, and each release's notes say how to install it.+## 0.2.0 — 2026-11-04++For Windows and Linux (x64 and ARM64), and the first with an installer for+Windows.++### Highlights++- **51 audio effects.** Equalizers (Modern Equalizer, Track EQ, Graphic, Parametric and Paragraphic EQ), dynamics (Compressor, Gate, Limiter, DeEsser, Multi-Band and Graphic Dynamics, Wave Hammer Surround), reverbs and delays, modulation (Chorus, Flanger, Phaser, Vibrato, Tremolo Pan, Amplitude Modulation), Distortion and Tube Stage, Vocal Strip, Pitch Shift, Time Stretch, Audio Restoration and the Express set, each with its panel and factory presets.+- **Compatible with `.veg` projects.** File › Open, File › Import and File › Export: tracks, events and takes, fades, transitions, audio effects, volumes, Pan/Crop with its masks, keyframes, Track Motion and busses. Import stays marked Experimental while real projects test it.+- **Color correction with LUTs.** Color Grading rebuilt: color wheels, curves, HSL curves, white balance, levels, tone and saturation, with Camera and Look LUTs from `.cube` files and Export LUT.+- **An installer for Windows.** Open it and follow the steps: BananaV goes to the Start menu, no administrator password needed. The zip stays for those who prefer not to install.+- **Pan/Crop rebuilt**, and compared frame by frame with reference renders.+- **Smooth playback.** The graphics card draws from the first frame, and a 1080p60 event with two effects plays at 60 frames a second, evenly, on about one processor core.++### Audio++- Each effect has its own panel, with sliders that reset on a double-click, and those drawn as curves (Graphic EQ, Graphic Dynamics, Distortion, Amplitude Modulation, Vibrato) have a graph editor.+- Pitch Shift, Time Stretch, Gapper/Snipper and Vibrato play on events, their sound made through the whole chain; in a track's or a bus's chain they let the sound through, and the FX window says so.+- Modern Equalizer: eight bands, with minimum and linear phase, oversampling, mid/side and per-channel routing.++### `.veg` projects++- Transitions come in with their settings and their progress envelopes; effect keyframes of every kind (numbers, points, colors, choices, with Bézier handles); effects switched off or placed before the Pan/Crop.+- Volume: each event's gain, Normalize, channels and phase; the tracks' volume, pan, envelopes and sends; the busses' faders, mute, solo, effects and envelopes.+- Video: velocity, Resample mode, Reduce Interlace, Undersample rate, Track Motion with its shadow, glow and 3D box, Parent Motion and compositing children.+- Export writes all of this except audio effect chains. Not imported yet: events of generated media, a transition at an event's end, and pan up and down.++### Color++- Older projects' Color Grading settings go back to their defaults.+- Lift and Gain eyedroppers, a neutral tone picker and a color selector; curve handles with Lock axis and Lock to grid.++### Pan/Crop++- An event's Pan/Crop is a box in its media's pixels; older projects come in as they were.+- Keyframes move along smooth paths with Smoothness; masks follow their keyframes, each with its own path settings.+- The rotation center can be dragged, the presets include the 1:1, 4:3, 16:9 and 1.85:1 shapes, and the menu resizes adjustment events to the project.++### Timeline and performance++- The Sharp curve is now 4p³ − 6p² + 3p in fades, envelopes and keyframes; snapping reaches 7 pixels; Esc stops playback; W and E go to the Trimmer's start and end.+- Peak files beside media (`.sfk`) give their waveforms without reading the sound.+- Effect shaders compile in the background in 6.5 s instead of 63 s, the window paints only when a frame is due, and the Explorer's tree no longer touches the disks every frame.+## 0.1.0 Ultra Alpha 2 — 2026-11-02The second test build, for Windows and Linux (x64 and ARM64), and the firstdiff --git a/CLAUDE.md b/CLAUDE.mdindex f1f1048..a2ffc8a 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -61,7 +61,8 @@ VEGAS Pro; everything the user sees is BananaV's own.`crates/gpu/src/shaders`) draw it alike, and the parity tests comparethem. Kernels compile with Direct3D's old FXC compiler: small, no`switch` over effects, no dynamic indexing of vectors, every thread- through the same rounds around a barrier.+ through the same rounds around a barrier; `var<workgroup>` tables are+ not zeroed (zeroing them cost FXC tens of seconds): write before reading.- **BananaV's own effects are OpenFX plug-ins** (`crates/effects`): theirsettings and on-screen controls described through OpenFX, neverspecial-cased in the interface, and a path on the graphics card@@ -83,8 +84,9 @@ VEGAS Pro; everything the user sees is BananaV's own.`telas_menus`, `telas_pt_br`) draws the interface into `target/telas`;`tools/capture_windows.ps1` captures the OS windows of a BananaV itstarts itself.-- `BV_PREVIEW_TRACE=1`, `BV_FRAME_TRACE=1`, `BV_OFX_TRACE=1` and- `BV_EFFECTS_TRACE=1` print what the preview, the interface, the plug-in- host and BananaV's effects do.+- `BV_PREVIEW_TRACE=1`, `BV_FRAME_TRACE=1`, `BV_GPU_TRACE=1`,+ `BV_OFX_TRACE=1` and `BV_EFFECTS_TRACE=1` print what the preview, the+ interface, the kernels' compiler, the plug-in host and BananaV's effects+ do; `tools/stacks.cs` samples where a running BananaV spends its time.- From Windows, `sh tools/linux_check.sh` runs clippy for Linux; `ghworkflow run package.yml` makes the packages.diff --git a/Cargo.lock b/Cargo.lockindex 4fb6f58..c1c3af0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -431,14 +431,14 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"[[package]]name = "bananav"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-ui-egui",][[package]]name = "bananav-ofx"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-effects","bv-ofx-sys",@@ -527,25 +527,25 @@ checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"[[package]]name = "bv-ac3"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-bitstream",][[package]]name = "bv-bitstream"-version = "0.1.0"+version = "0.2.0"[[package]]name = "bv-color"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-core",][[package]]name = "bv-core"-version = "0.1.0"+version = "0.2.0"dependencies = ["serde","serde_json",@@ -553,22 +553,22 @@ dependencies = [[[package]]name = "bv-cuda"-version = "0.1.0"+version = "0.2.0"dependencies = ["libloading",][[package]]name = "bv-deflate"-version = "0.1.0"+version = "0.2.0"[[package]]name = "bv-dvd"-version = "0.1.0"+version = "0.2.0"[[package]]name = "bv-effects"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-core","bv-lut",@@ -582,7 +582,7 @@ dependencies = [[[package]]name = "bv-engine"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-color","bv-core",@@ -613,14 +613,14 @@ dependencies = [[[package]]name = "bv-flac"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-bitstream",][[package]]name = "bv-gpu"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-color","bv-core",@@ -640,18 +640,18 @@ dependencies = [[[package]]name = "bv-image"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-deflate",][[package]]name = "bv-lut"-version = "0.1.0"+version = "0.2.0"[[package]]name = "bv-media"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-ac3","bv-color",@@ -669,7 +669,7 @@ dependencies = [[[package]]name = "bv-mf"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-bitstream","bv-core",@@ -683,7 +683,7 @@ dependencies = [[[package]]name = "bv-mixer"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-core","bv-media",@@ -695,25 +695,25 @@ dependencies = [[[package]]name = "bv-mp4"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-bitstream",][[package]]name = "bv-mpeg2"-version = "0.1.0"+version = "0.2.0"[[package]]name = "bv-ocio"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-lut",][[package]]name = "bv-ofx"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-core","bv-cuda",@@ -728,11 +728,11 @@ dependencies = [[[package]]name = "bv-ofx-sys"-version = "0.1.0"+version = "0.2.0"[[package]]name = "bv-ofx-testplug"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-cuda","bv-ofx-sys",@@ -740,7 +740,7 @@ dependencies = [[[package]]name = "bv-platform"-version = "0.1.0"+version = "0.2.0"dependencies = ["alsa","bv-core",@@ -752,14 +752,14 @@ dependencies = [[[package]]name = "bv-png"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-deflate",][[package]]name = "bv-prores"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-bitstream","bv-mp4",@@ -767,7 +767,7 @@ dependencies = [[[package]]name = "bv-render"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-color","bv-core",@@ -779,7 +779,7 @@ dependencies = [[[package]]name = "bv-timeline"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-color","bv-core",@@ -790,11 +790,11 @@ dependencies = [[[package]]name = "bv-track"-version = "0.1.0"+version = "0.2.0"[[package]]name = "bv-ui-egui"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-core","bv-engine",@@ -819,7 +819,7 @@ dependencies = [[[package]]name = "bv-vst3"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-vst3-sys","bv-vst3-testplug",@@ -828,29 +828,29 @@ dependencies = [[[package]]name = "bv-vst3-sys"-version = "0.1.0"+version = "0.2.0"[[package]]name = "bv-vst3-testplug"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-vst3-sys",][[package]]name = "bv-wav"-version = "0.1.0"+version = "0.2.0"[[package]]name = "bv-wic"-version = "0.1.0"+version = "0.2.0"dependencies = ["windows",][[package]]name = "bv-zip"-version = "0.1.0"+version = "0.2.0"dependencies = ["bv-deflate",]@@ -4577,7 +4577,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"[[package]]name = "xtask"-version = "0.1.0"+version = "0.2.0"dependencies = ["serde_json",]diff --git a/Cargo.toml b/Cargo.tomlindex 5684475..03958ef 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]exclude = ["vendor"][workspace.package]-version = "0.1.0"+version = "0.2.0"edition = "2024"rust-version = "1.95"license = "GPL-3.0-or-later"diff --git a/README.md b/README.mdindex 89a0144..dc809ff 100644--- a/README.md+++ b/README.md@@ -39,10 +39,11 @@ keyboard. It is written from scratch in Rust: its compositing, audio mixing,color management and most of its file formats are its own code, and theinterface speaks English and Brazilian Portuguese.-> **Early development.** BananaV has not reached 1.0: expect missing features-> and rough edges, and save often. See the [roadmap](docs/ROADMAP.md) for what-> is done and what comes next, and the [changelog](CHANGELOG.md) for what-> changed in each build.+**New in 0.2.0:** 51 audio effects, compatibility with `.veg` projects, color+correction with LUTs, a rebuilt Pan/Crop, smooth playback and an installer for+Windows. BananaV has not reached 1.0, so save often: see the+[changelog](CHANGELOG.md) for what changed in each version and the+[roadmap](docs/ROADMAP.md) for what comes next.## Download@@ -51,11 +52,13 @@ Get the latest version from the| System | Package | How to run ||---|---|---|-| Windows 10 or 11 (x64, ARM64) | `BananaV-…-windows-x64.zip`, `…-windows-arm64.zip` | Unzip and run `BananaV.exe`: nothing to install. |+| Windows 10 or 11 (x64, ARM64) | `BananaV-…-windows-x64-setup.exe`, `…-windows-arm64-setup.exe` | Open the installer and follow the steps: no administrator password needed. |+| Windows, without installing | `BananaV-…-windows-x64.zip`, `…-windows-arm64.zip` | Unzip and run `BananaV.exe`. || Linux, glibc 2.35 or newer (x64, ARM64) | `BananaV-…-linux-x64.AppImage`, `…-linux-arm64.AppImage` | `chmod +x` the AppImage and run it. |-You need a graphics card with Direct3D 12, Vulkan or OpenGL. Each package has-a README with the details and the licenses of what it includes.+You need a graphics card with Direct3D 12, Vulkan or OpenGL. The builds are not+signed yet: if Windows warns you, choose **More info**, then **Run anyway**. Each+package has a README with the details and the licenses of what it includes.## Features@@ -72,11 +75,14 @@ a README with the details and the licenses of what it includes.BananaV's own (blurs, color, light and film looks, lens correction, meshwarp, 360° video, AI/ML-style smoothing, sharpening and dehazing…), mostof them drawn on the graphics card.-- **Color** — a color grading panel (wheels, curves, HSL, LUTs), video scopes,+- **Color** — a color grading panel (wheels, curves, HSL, levels, white+ balance, Camera and Look LUTs from `.cube` files, Export LUT), video scopes,and ACES 1.3 color management through BananaV's own OpenColorIOimplementation.-- **Audio** — a mixing console with busses and assignable effect chains,- volume, pan and effect automation, 5.1 surround panning, auto ducking,+- **Audio** — 51 audio effects of BananaV's own (equalizers, dynamics, reverbs,+ delays, modulation, distortion, pitch and time, restoration), each with its+ panel and factory presets; a mixing console with busses and assignable effect+ chains, volume, pan and effect automation, 5.1 surround panning, auto ducking,loudness meters (EBU R 128), beat and tempo detection.- **Plug-ins** — an OpenFX 1.5 host for video effects, transitions andgenerators, and a VST 3 host for audio effects. BananaV's own video effects@@ -89,8 +95,9 @@ a README with the details and the licenses of what it includes.the computer has), image sequences and audio files; compositing on thegraphics card (through wgpu: Direct3D 12, Vulkan or OpenGL) with theprocessor as the fallback.-- **Interchange** — EDL, Final Cut Pro 7 XML and FCPXML, and OpenTimelineIO- (`.otio`, `.otioz`, `.otiod`).+- **Interchange** — `.veg` projects (tracks, events, transitions, audio effects,+ volumes, Pan/Crop, keyframes and busses), EDL, Final Cut Pro 7 XML and FCPXML,+ and OpenTimelineIO (`.otio`, `.otioz`, `.otiod`).- **Discs and capture** — DVD-Video authoring and burning, Video CDs and audioCDs, with BananaV's own MPEG-2 and MPEG-1 encoders; screen capture ofdisplays, windows, cameras and the computer's sound.diff --git a/crates/effects/src/accel.rs b/crates/effects/src/accel.rsindex 8e0597d..e79e2c3 100644--- a/crates/effects/src/accel.rs+++ b/crates/effects/src/accel.rs@@ -236,9 +236,9 @@ pub fn transition_plan(}/// Color Grading on the card: its Camera LUT, its own steps — `steps`, as-/// `shaders/own_pair.wgsl`'s `grade` reads them: the settings, then the-/// Curves' and the HSL Curves' tables, `entries` long each — and its Look-/// LUT.+/// `shaders/own_pair.wgsl`'s `grade` reads them: the settings, a row each+/// (`entries` rows), then its curves' tables, an entry a row — and its+/// Look LUT.#[derive(Clone, Debug, PartialEq)]pub struct GradePlan {pub camera: Option<GradeLut>,@@ -1827,7 +1827,7 @@ pub fn plan(id: &str, values: Values<'_>, frame: [f64; 2], at: Moment) -> Option} else if is(color_curves::ID) {Some(Plan::Curves(color_curves::tables_of(values)))} else if is(color_grading::ID) {- let grade = color_grading::Settings::of(values).sampled().grade();+ let grade = color_grading::Settings::of(values).grade();Some(Plan::Grade(Box::new(grade.plan())))} else if is(color_corrector::ID) {let c = color_corrector::Corrector::new(&color_corrector::Settings::of(values));diff --git a/crates/effects/src/color_grading.rs b/crates/effects/src/color_grading.rsindex 305325f..5aab570 100644--- a/crates/effects/src/color_grading.rs+++ b/crates/effects/src/color_grading.rs@@ -1,742 +1,349 @@-//! Color Grading: what the Color Grading window works, as VEGAS's Help-//! lays its sections out, in a colorist's order: the Camera LUT (a log-//! recording's decoding: a `.cube` file, or Apple Log's published curve to-//! linear or to Rec. 709), the Color Wheels (Lift, Gamma, Gain and Offset,-//! each a color and a master Y), the RL Color Wheels (Shadows, Midtones-//! and Highlights within two luma thresholds, and an Offset), the-//! Utilities (Levels, Tone, White Balance, HSL), the Curves (Brightness,-//! Red, Green, Blue) and the HSL Curves (Hue vs Hue, Hue vs Saturation,-//! Hue vs Luminance, Saturation vs Saturation, Saturation vs Luminance,-//! Luminance vs Saturation), then the Look LUT; each LUT at its strength.-//! Its parameters are what the window edits.+//! Color Grading: what the Color Grading window works, as VEGAS's Color+//! Grading effect holds it — the same parameters, all of them hidden (the+//! window edits them): each wheel's red, green, blue and Y (and where its+//! point stands, U and V, for the window to draw it again), the RL+//! wheels and their two thresholds, the ten curves as text+//! (`N:x:y:ix:iy:ox:oy:…`), Saturation, Exposure (two: one not on the+//! panel), Brightness, Contrast and its center, Temperature and Tint,+//! Levels, Hue, Sat and Val, and the Camera and Look LUTs (on, file,+//! interpolation, strength). The work is [`crate::grading`]'s.//!-//! The math is BananaV's (the Help describes what each control does, not-//! how): Lift raises the dark end toward its color (x + lift·(1 − x)),-//! Gain scales, Gamma bends (x^(1/gamma)) and Offset adds, each channel by-//! its number with the master Y; the RL wheels add their colors weighed-//! by where the luma stands against the thresholds (soft edges 0.05 wide);-//! Levels remaps the input's black and white points to the output's;-//! Tone adds brightness, scales contrast about its center and saturation-//! about the luma (BT.709), and moves log footage 0.1 a stop; White-//! Balance scales red and blue (temperature) and green (tint); HSL turns-//! the chroma, scales it and adds to the luma; the curves map the luma-//! (Brightness, the color scaled along) and each channel; the HSL curves-//! move the hue, scale the saturation and the value by curves of the-//! hue (wrapping round red), of the saturation and of the value.+//! The wheels' points map to their colors as VEGAS's do: three lines+//! through the middle, at 5° (red), −40° (green) and 65° (blue); a+//! channel goes toward its top the farther the point is from its line on+//! its side (all of it 51 of the wheel's 85 pixels away), toward its+//! bottom on the other ([`wheel_values`]); typed values put the point+//! back about where it gives them ([`wheel_point`]).#![allow(unsafe_code)]-use std::ffi::{CStr, c_char, c_int, c_void};-use std::sync::Arc;+use std::ffi::{CStr, CString, c_char, c_void};use bv_core::curve::CurvePoint;-use bv_lut::{Interpolation, Lut};use bv_ofx_sys::names::*;use bv_ofx_sys::*;use crate::accel::Values;+use crate::grading::{self, Grade, HslCurve, Knot, LutStep, LutTable, Params, Wheel};use crate::ofx::{Fx, Props, is, suites};pub(crate) const ID: &CStr = c"org.bananav.ColorGrading";-/// The parameters.-pub(crate) const CAMERA_LUT: &CStr = c"cameraLut";-pub(crate) const CAMERA_STRENGTH: &CStr = c"cameraStrength";-pub(crate) const CAMERA_TETRAHEDRAL: &CStr = c"cameraTetrahedral";-pub(crate) const CAMERA_ON: &CStr = c"cameraOn";-pub(crate) const LOOK_LUT: &CStr = c"lookLut";-pub(crate) const LOOK_STRENGTH: &CStr = c"lookStrength";-pub(crate) const LOOK_TETRAHEDRAL: &CStr = c"lookTetrahedral";-pub(crate) const LOOK_ON: &CStr = c"lookOn";-/// The Color Wheels and the RL Color Wheels: a color and a master Y each.-pub(crate) const WHEELS: [(&CStr, &CStr); 4] = [- (c"lift", c"liftY"),- (c"gamma", c"gammaY"),- (c"gain", c"gainY"),- (c"offset", c"offsetY"),+/// The Color Wheels' and the RL Color Wheels' names (each wheel's+/// parameters are its name and R, G, B, Y, U or V).+pub const WHEELS: [&str; 4] = ["lift", "gamma", "gain", "offset"];+pub const RL_WHEELS: [&str; 4] = [+ "logWheelShadows",+ "logWheelMidtones",+ "logWheelHighlights",+ "logWheelOffset",];-pub(crate) const RL_WHEELS: [(&CStr, &CStr); 4] = [- (c"shadows", c"shadowsY"),- (c"midtones", c"midtonesY"),- (c"highlights", c"highlightsY"),- (c"rlOffset", c"rlOffsetY"),+/// A wheel's parts: its color, its Y, its point (U across, V up: pixels+/// of an 85-pixel wheel).+pub const PARTS: [&str; 6] = ["R", "G", "B", "Y", "U", "V"];+/// The panel's range of each wheel's color and Y, and where it rests:+/// Lift, Gamma, Gain, Offset; every RL wheel −1 to 1 about 0.+pub const WHEEL_RANGES: [(f64, f64, f64); 4] = [+ (-1.0, 1.0, 0.0),+ (0.0, 5.0, 1.0),+ (0.0, 2.0, 1.0),+ (-1.0, 1.0, 0.0),];-pub(crate) const LOWER: &CStr = c"lowerThreshold";-pub(crate) const UPPER: &CStr = c"upperThreshold";-pub(crate) const IN_BLACK: &CStr = c"inputBlack";-pub(crate) const IN_WHITE: &CStr = c"inputWhite";-pub(crate) const OUT_MIN: &CStr = c"outputMin";-pub(crate) const OUT_MAX: &CStr = c"outputMax";-pub(crate) const BRIGHTNESS: &CStr = c"brightness";-pub(crate) const CONTRAST: &CStr = c"contrast";-pub(crate) const CONTRAST_CENTER: &CStr = c"contrastCenter";-pub(crate) const SATURATION: &CStr = c"saturation";-pub(crate) const LOG_EXPOSURE: &CStr = c"logExposure";-pub(crate) const TEMPERATURE: &CStr = c"temperature";-pub(crate) const TINT: &CStr = c"tint";-pub(crate) const HUE: &CStr = c"hue";-pub(crate) const HSL_SATURATION: &CStr = c"hslSaturation";-pub(crate) const LUMINANCE: &CStr = c"luminance";-pub(crate) const CURVES: &CStr = c"curves";-pub(crate) const HSL_CURVES: &CStr = c"hslCurves";+pub const RL_RANGE: (f64, f64, f64) = (-1.0, 1.0, 0.0);-/// The Curves, in their parameter's order.-pub(crate) const CURVE_NAMES: [&CStr; 4] = [c"Brightness", c"Red", c"Green", c"Blue"];-const CURVE_COLOURS: [[f64; 3]; 4] = [- [0.85, 0.85, 0.85],- [0.80, 0.55, 0.55],- [0.50, 0.75, 0.50],- [0.56, 0.56, 0.85],-];-/// The HSL Curves, in their parameter's order: each maps its input (x,-/// 0–1) to a change (y: 0 none; a hue's −1 to 1 is half a turn either-/// way, a saturation's or a value's −1 to 1 scales it from 0 to 2).-pub(crate) const HSL_CURVE_NAMES: [&CStr; 6] = [- c"Hue vs Hue",- c"Hue vs Saturation",- c"Hue vs Luminance",- c"Saturation vs Saturation",- c"Saturation vs Luminance",- c"Luminance vs Saturation",+/// The curves: red, green, blue, Y; then the HSL Curves.+pub const CURVES: [&str; 10] = [+ "curveR", "curveG", "curveB", "curveY", "curveHvH", "curveHvS", "curveHvL", "curveSvS",+ "curveSvL", "curveLvS",];+pub const HIGH_THRESHOLD: &str = "logWheelHighThreshold";+pub const LOW_THRESHOLD: &str = "logWheelLowThreshold";+pub const SATURATION: &str = "saturationAdjust";+pub const EXPOSURE: &str = "exposureAdjust";+pub const EXPOSURE_LN: &str = "exposureLnAdjust";+pub const BRIGHTNESS: &str = "brightnessAdjust";+pub const CONTRAST: &str = "contrastAdjust";+pub const CONTRAST_CENTER: &str = "contrastCtrAdjust";+pub const TEMPERATURE: &str = "temperatureAdjust";+pub const TINT: &str = "tintAdjust";+pub const IN_MIN: &str = "inMinAdjust";+pub const IN_MAX: &str = "inMaxAdjust";+pub const OUT_MIN: &str = "outMinAdjust";+pub const OUT_MAX: &str = "outMaxAdjust";+pub const HUE: &str = "hueAdjust";+pub const SAT: &str = "satAdjust";+pub const VAL: &str = "valAdjust";+/// The LUTs' rows: 0 the Camera LUT, 1 the Look LUT.+pub const LUT_ENABLE: [&str; 2] = ["lutEnable0", "lutEnable1"];+pub const LUT_FILE: [&str; 2] = ["lutFilename0", "lutFilename1"];+pub const LUT_INTERPOLATION: [&str; 2] = ["lutInterpolation0", "lutInterpolation1"];+pub const LUT_GAIN: [&str; 2] = ["lutGain0", "lutGain1"];/// The Camera LUT's curves BananaV knows (the LUT list's own entries):/// Apple Log decoded to Rec. 709's linear light or to its video.pub const APPLE_LOG_TO_LINEAR: &str = "builtin:apple-log-to-linear";pub const APPLE_LOG_TO_REC709: &str = "builtin:apple-log-to-rec709";-/// How far a stop moves log footage (Log. Exposure).-const LOG_STOP: f32 = 0.1;-/// The RL thresholds' soft edges (half their width).-const SOFT: f32 = 0.05;-/// How far White Balance's temperature and tint scale their channels.-const BALANCE: f32 = 0.25;-/// The entries of each curve's table.-const TABLE: usize = 1024;--/// A LUT row: its file (or a built-in curve), strength, interpolation and-/// whether it applies (LUT Selection).-#[derive(Clone, Debug, PartialEq)]-pub(crate) struct LutRow {- pub file: String,- pub strength: f64,- pub tetrahedral: bool,- pub on: bool,+/// A wheel's parameter.+pub fn wheel_param(wheel: &str, part: &str) -> String {+ format!("{wheel}{part}")}-impl LutRow {- fn active(&self) -> bool {- self.on && self.strength > 0.0 && !self.file.trim().is_empty()- }+fn c(name: &str) -> CString {+ CString::new(name).unwrap_or_default()}-/// The settings at a time.-#[derive(Clone, Debug, PartialEq)]-pub(crate) struct Settings {- pub camera: LutRow,- pub look: LutRow,- /// Lift, Gamma, Gain, Offset: red, green, blue and the master Y.- pub wheels: [[f64; 4]; 4],- /// Shadows, Midtones, Highlights, Offset.- pub rl: [[f64; 4]; 4],- pub thresholds: [f64; 2],- /// Input black and white, output minimum and maximum.- pub levels: [f64; 4],- /// Brightness, contrast, contrast center, saturation, log exposure.- pub tone: [f64; 5],- /// Temperature, tint.- pub balance: [f64; 2],- /// Hue (degrees), saturation, luminance.- pub hsl: [f64; 3],- pub curves: Vec<Vec<CurvePoint>>,- pub hsl_curves: Vec<Vec<CurvePoint>>,-}--/// The wheels' neutral values: Gamma's and Gain's multiply.-const WHEEL_NEUTRAL: [f64; 4] = [0.0, 1.0, 1.0, 0.0];--impl Settings {- /// The settings in `v`, a time's values as the host gives them.- pub(crate) fn of(v: Values<'_>) -> Settings {- let row = |file, strength, tetra, on| LutRow {- file: v.text(file).unwrap_or_default().to_string(),- strength: v.f64(strength, 1.0).clamp(0.0, 1.0),- tetrahedral: v.int(tetra, 1) != 0,- on: v.int(on, 1) != 0,- };- let wheel = |(rgb, y): (&CStr, &CStr), n: f64| {- let [r, g, b] = v.array(rgb, [n; 3]);- [r, g, b, v.f64(y, n)]- };- Settings {- camera: row(CAMERA_LUT, CAMERA_STRENGTH, CAMERA_TETRAHEDRAL, CAMERA_ON),- look: row(LOOK_LUT, LOOK_STRENGTH, LOOK_TETRAHEDRAL, LOOK_ON),- wheels: std::array::from_fn(|i| wheel(WHEELS[i], WHEEL_NEUTRAL[i])),- rl: std::array::from_fn(|i| wheel(RL_WHEELS[i], 0.0)),- thresholds: [v.f64(LOWER, 0.25), v.f64(UPPER, 0.75)],- levels: [- v.f64(IN_BLACK, 0.0),- v.f64(IN_WHITE, 1.0),- v.f64(OUT_MIN, 0.0),- v.f64(OUT_MAX, 1.0),- ],- tone: [- v.f64(BRIGHTNESS, 0.0),- v.f64(CONTRAST, 0.0),- v.f64(CONTRAST_CENTER, 0.5),- v.f64(SATURATION, 1.0),- v.f64(LOG_EXPOSURE, 0.0),- ],- balance: [v.f64(TEMPERATURE, 0.0), v.f64(TINT, 0.0)],- hsl: [- v.f64(HUE, 0.0),- v.f64(HSL_SATURATION, 1.0),- v.f64(LUMINANCE, 0.0),- ],- curves: v.curves(CURVES).map(<[_]>::to_vec).unwrap_or_default(),- hsl_curves: v.curves(HSL_CURVES).map(<[_]>::to_vec).unwrap_or_default(),- }- }-- fn at(fx: Fx, time: f64) -> Settings {- let row = |file, strength, tetra, on| LutRow {- file: fx.param(file).text_at(time),- strength: fx.param(strength).f64_at(time).clamp(0.0, 1.0),- tetrahedral: fx.param(tetra).int_at(time) != 0,- on: fx.param(on).int_at(time) != 0,- };- let wheel = |(rgb, y): (&CStr, &CStr)| {- let [r, g, b] = fx.param(rgb).xyz_at(time);- [r, g, b, fx.param(y).f64_at(time)]- };- let f = |name| fx.param(name).f64_at(time);- // The host's curves, sampled where their points are (their- // handles kept): what `curve` evaluates back.- let sampled = |name, n: usize| -> Vec<Vec<CurvePoint>> {- let p = fx.param(name);- (0..n)- .map(|c| {- (0..=64)- .map(|i| {- let x = i as f64 / 64.0;- CurvePoint {- x,- y: p.curve_at(c as c_int, time, x),- handles: None,- }- })- .collect()- })- .collect()- };- Settings {- camera: row(CAMERA_LUT, CAMERA_STRENGTH, CAMERA_TETRAHEDRAL, CAMERA_ON),- look: row(LOOK_LUT, LOOK_STRENGTH, LOOK_TETRAHEDRAL, LOOK_ON),- wheels: std::array::from_fn(|i| wheel(WHEELS[i])),- rl: std::array::from_fn(|i| wheel(RL_WHEELS[i])),- thresholds: [f(LOWER), f(UPPER)],- levels: [f(IN_BLACK), f(IN_WHITE), f(OUT_MIN), f(OUT_MAX)],- tone: [- f(BRIGHTNESS),- f(CONTRAST),- f(CONTRAST_CENTER),- f(SATURATION),- f(LOG_EXPOSURE),- ],- balance: [f(TEMPERATURE), f(TINT)],- hsl: [f(HUE), f(HSL_SATURATION), f(LUMINANCE)],- curves: sampled(CURVES, CURVE_NAMES.len()),- hsl_curves: sampled(HSL_CURVES, HSL_CURVE_NAMES.len()),- }- }+// The wheels' points.- /// The curves as the host hands them to the render (`Settings::at`):- /// each sampled where its points are by the host's own evaluation, so- /// that the graphics card, which reads the values, draws what the- /// render draws.- pub(crate) fn sampled(mut self) -> Settings {- let sample = |curves: &[Vec<CurvePoint>], n: usize| -> Vec<Vec<CurvePoint>> {- (0..n)- .map(|c| {- let points = curves.get(c).map_or(&[][..], Vec::as_slice);- (0..=64)- .map(|i| {- let x = i as f64 / 64.0;- CurvePoint {- x,- y: bv_core::curve::curve_at(points, x),- handles: None,- }- })- .collect()- })- .collect()- };- self.curves = sample(&self.curves, CURVE_NAMES.len());- self.hsl_curves = sample(&self.hsl_curves, HSL_CURVE_NAMES.len());- self- }-- /// The default settings: nothing changes.- pub(crate) fn neutral() -> Settings {- Settings::of(Values(&[]))- }+/// How far a point is from a channel's line, as a part of the way to its+/// end (51 pixels of the 85).+const REACH: f64 = 85.0 * 0.6;+/// Where each channel's top lies from the middle (degrees, y up): above+/// its line for red, toward the bottom left for green, the bottom right+/// for blue.+const TOWARD: [f64; 3] = [95.0, 230.0, 335.0];- /// Whether the settings change nothing.- pub(crate) fn changes_nothing(&self) -> bool {- let n = Settings::neutral();- !self.camera.active()- && !self.look.active()- && self.wheels == n.wheels- && self.rl == n.rl- && self.levels == n.levels- && self.tone[0] == 0.0- && self.tone[1] == 0.0- && self.tone[3] == 1.0- && self.tone[4] == 0.0- && self.balance == n.balance- && self.hsl == n.hsl- && self- .curves- .iter()- .enumerate()- .all(|(c, p)| curve_is_neutral(p, c, false))- && self.hsl_curves.iter().all(|p| curve_is_neutral(p, 0, true))- }-- /// Ready to color pixels: the LUTs read, the curves as tables.- pub(crate) fn grade(&self) -> Grade {- let table = |points: Option<&Vec<CurvePoint>>, neutral: fn(f64) -> f64, wrap: bool| {- let points = points.filter(|p| !p.is_empty());- (0..TABLE)- .map(|i| {- let x = i as f64 / (TABLE - 1) as f64;- match points {- Some(p) if wrap => wrapped_at(p, x) as f32,- Some(p) => bv_core::curve::curve_at(p, x) as f32,- None => neutral(x) as f32,- }- })- .collect::<Vec<f32>>()- };- let straight = |x: f64| x;- let flat = |_: f64| 0.0;- Grade {- settings: self.clone(),- camera: lut_of(&self.camera),- look: lut_of(&self.look),- curves: std::array::from_fn(|c| table(self.curves.get(c), straight, false)),- hsl_curves: std::array::from_fn(|c| table(self.hsl_curves.get(c), flat, c < 3)),- }- }-}--/// Whether curve `c`'s points change nothing: none, or straight (the-/// Curves) or flat at 0 (the HSL Curves).-fn curve_is_neutral(points: &[CurvePoint], _c: usize, flat: bool) -> bool {- if points.is_empty() {- return true;- }- (0..=16).all(|i| {- let x = i as f64 / 16.0;- let y = bv_core::curve::curve_at(points, x);- if flat {- y.abs() < 1e-6+/// The color a wheel's point (`u` across, `v` up, pixels of an 85-pixel+/// wheel) gives, the wheel's range `(low, high, rest)`.+pub fn wheel_values(u: f64, v: f64, (low, high, rest): (f64, f64, f64)) -> [f64; 3] {+ TOWARD.map(|a| {+ let (s, c) = a.to_radians().sin_cos();+ let d = ((u * c + v * s) / REACH).clamp(-1.0, 1.0);+ if d >= 0.0 {+ rest + (high - rest) * d} else {- (y - x).abs() < 1e-6+ rest + (low - rest) * -d}})}-/// A hue curve at `x`: its points repeated a turn before and after, so it-/// wraps round red.-fn wrapped_at(points: &[CurvePoint], x: f64) -> f64 {- let mut all = Vec::with_capacity(points.len() * 3);- for shift in [-1.0, 0.0, 1.0] {- all.extend(points.iter().map(|p| CurvePoint {- x: p.x + shift,- ..*p- }));+/// About where a wheel's point gives `values` (typed, or set by a+/// picker): the channels' changes added along 185°, −40° and 65°, the+/// sum's length scaled to the wheel and its angle turned about 88.5°+/// (94.79° on Gamma). `gamma` says the wheel is Gamma's.+pub fn wheel_point(values: [f64; 3], (low, high, rest): (f64, f64, f64), gamma: bool) -> [f64; 2] {+ let (mut x, mut y) = (0.0, 0.0);+ for (v, a) in values.iter().zip([185.0f64, -40.0, 65.0]) {+ let (s, c) = a.to_radians().sin_cos();+ x += (v - rest) * c;+ y += (v - rest) * s;}- // A point at 1 is the one at 0 a turn on: once.- all.sort_by(|a, b| a.x.total_cmp(&b.x));- all.dedup_by(|a, b| (a.x - b.x).abs() < 1e-9);- bv_core::curve::curve_at(&all, x)+ let reach = (rest - low).abs().max((high - rest).abs()).max(1e-9);+ let scale = if gamma {+ 85.0 / 3f64.sqrt()+ } else {+ 85.0 / (3.0 * reach * reach).sqrt()+ };+ let r = (x.hypot(y) * scale).min(85.0);+ let turn = if gamma { 94.79 } else { 88.5 };+ let a = (turn - y.atan2(x).to_degrees()).to_radians();+ // The angle counts down the screen: up is the other way.+ [r * a.cos(), -r * a.sin()]}-/// A LUT row's table or curve.-#[derive(Clone)]-pub(crate) enum Table {- Cube(Arc<Lut>, Interpolation),- AppleLog { rec709: bool },-}+// The curves' text as the window writes it.-impl Table {- fn apply(&self, c: [f32; 3]) -> [f32; 3] {- match self {- Table::Cube(lut, how) => lut.apply(c, *how),- Table::AppleLog { rec709 } => apple_log(c, *rec709),- }+impl From<Knot> for CurvePoint {+ fn from(k: Knot) -> CurvePoint {+ CurvePoint::with(+ f64::from(k.x),+ f64::from(k.y),+ [f64::from(k.ix), f64::from(k.iy)],+ [f64::from(k.ox), f64::from(k.oy)],+ )}}-fn lut_of(row: &LutRow) -> Option<(Table, f32)> {- if !row.active() {- return None;- }- let table = match row.file.trim() {- APPLE_LOG_TO_LINEAR => Table::AppleLog { rec709: false },- APPLE_LOG_TO_REC709 => Table::AppleLog { rec709: true },- file => {- let how = if row.tetrahedral {- Interpolation::Tetrahedral- } else {- Interpolation::Linear- };- Table::Cube(crate::lut_filter::table(file)?, how)- }- };- Some((table, row.strength as f32))+fn knot(p: &CurvePoint) -> Knot {+ let (before, after) = p+ .handles+ .map_or(([0.0; 2], [0.0; 2]), |h| (h.before, h.after));+ Knot::new(+ p.x as f32,+ p.y as f32,+ before[0] as f32,+ before[1] as f32,+ after[0] as f32,+ after[1] as f32,+ )}-/// Apple Log (Apple's published curve, Rec. 2020's primaries) decoded:-/// Rec. 709's linear light, or its video (BT.709's curve, clipped at-/// white).-pub(crate) fn apple_log(c: [f32; 3], rec709: bool) -> [f32; 3] {- const R0: f64 = -0.05641088;- const RT: f64 = 0.01;- const C: f64 = 47.28711236;- const B: f64 = 0.00964052;- const G: f64 = 0.08550479;- const D: f64 = 0.69336945;- let linear = |x: f32| {- let x = x as f64;- let pt = C * (RT - R0).powi(2);- if x >= pt {- 2f64.powf((x - D) / G) - B- } else if x >= 0.0 {- (x / C).sqrt() + R0- } else {- R0- }- };- let l = c.map(linear);- // Rec. 2020 to Rec. 709 (both D65).- const M: [[f64; 3]; 3] = [- [1.660_491, -0.587_641, -0.072_850],- [-0.124_551, 1.132_900, -0.008_349],- [-0.018_151, -0.100_579, 1.118_730],- ];- let out: [f64; 3] = std::array::from_fn(|i| M[i][0] * l[0] + M[i][1] * l[1] + M[i][2] * l[2]);- if !rec709 {- return out.map(|v| v as f32);+/// A Color Curve's text from its points: points at x = 0 and x = 1 added+/// when the curve does not reach them, flat (their handles 0.05 long).+pub fn color_curve_text(points: &[CurvePoint]) -> String {+ let mut k: Vec<Knot> = points.iter().map(knot).collect();+ k.sort_by(|a, b| a.x.total_cmp(&b.x));+ if let Some(first) = k.first().copied()+ && first.x > 0.0+ {+ k.insert(0, Knot::new(0.0, first.y, 0.0, 0.0, 0.05, 0.0));}- out.map(|v| {- let v = v.clamp(0.0, 1.0);- let e = if v < 0.018 {- 4.5 * v- } else {- 1.099 * v.powf(0.45) - 0.099- };- e as f32- })-}--/// The settings ready to color pixels.-#[derive(Clone)]-pub(crate) struct Grade {- settings: Settings,- camera: Option<(Table, f32)>,- look: Option<(Table, f32)>,- curves: [Vec<f32>; 4],- hsl_curves: [Vec<f32>; 6],-}--/// BT.709's luma.-fn luma(c: [f32; 3]) -> f32 {- 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2]+ if let Some(last) = k.last().copied()+ && last.x < 1.0+ {+ k.push(Knot::new(1.0, last.y, -0.05, 0.0, 0.0, 0.0));+ }+ grading::curve_text(&k)}-fn smoothstep(a: f32, b: f32, x: f32) -> f32 {- let t = ((x - a) / (b - a).max(1e-6)).clamp(0.0, 1.0);- t * t * (3.0 - 2.0 * t)+/// A hue curve's text from its points (0–1): the last one copied a turn+/// before the first, the first a turn after the last, so that the curve+/// goes round.+pub fn hue_curve_text(points: &[CurvePoint]) -> String {+ let mut k: Vec<Knot> = points.iter().map(knot).collect();+ k.sort_by(|a, b| a.x.total_cmp(&b.x));+ if let (Some(first), Some(last)) = (k.first().copied(), k.last().copied()) {+ k.insert(+ 0,+ Knot {+ x: last.x - 1.0,+ ..last+ },+ );+ k.push(Knot {+ x: first.x + 1.0,+ ..first+ });+ }+ grading::curve_text(&k)}-/// A table's value at `x` (0–1), between its entries; past its ends-/// along their slope (what passes white or black keeps going: a straight-/// curve changes nothing there).-fn at(t: &[f32], x: f32) -> f32 {- let n = t.len() - 1;- if x < 0.0 {- return t[0] + x * (t[1] - t[0]) * n as f32;+/// A curve's points as the window edits them: a hue curve's own (the+/// turn's copies, its first and last, left out), the others' all.+pub fn curve_points(text: &str, hue: bool) -> Vec<CurvePoint> {+ if grading::untouched(text) {+ return Vec::new();}- if x > 1.0 {- return t[n] + (x - 1.0) * (t[n] - t[n - 1]) * n as f32;+ let mut k = grading::parse_curve(text);+ if hue {+ if k.len() >= 3 {+ k = k[1..k.len() - 1].to_vec();+ } else {+ k.retain(|p| (0.0..1.0).contains(&p.x));+ }}- within(t, x)-}--/// A table's value at `x`, held within 0–1.-fn within(t: &[f32], x: f32) -> f32 {- let f = x.clamp(0.0, 1.0) * (t.len() - 1) as f32;- let i = (f as usize).min(t.len() - 2);- let k = f - i as f32;- t[i] + (t[i + 1] - t[i]) * k+ k.into_iter().map(CurvePoint::from).collect()}-/// HSV's hue (0–1), saturation and value.-fn hsv([r, g, b]: [f32; 3]) -> [f32; 3] {- let max = r.max(g).max(b);- let min = r.min(g).min(b);- let d = max - min;- if d <= 1e-7 || max <= 0.0 {- return [0.0, 0.0, max];+/// A curve's values as the effect works them out (its table: 511+/// entries over 0–1), for the window to draw; `None` when untouched.+pub fn curve_table(text: &str) -> Option<Vec<f32>> {+ if grading::untouched(text) {+ return None;}- let h = if max == r {- ((g - b) / d).rem_euclid(6.0)- } else if max == g {- (b - r) / d + 2.0- } else {- (r - g) / d + 4.0- };- [h / 6.0, d / max, max]+ let t = grading::table(&grading::parse_curve(text), 511, 0.0);+ (!t.is_empty()).then_some(t)}-fn from_hsv([h, s, v]: [f32; 3]) -> [f32; 3] {- let h = h.rem_euclid(1.0) * 6.0;- let c = v * s;- let x = c * (1.0 - (h % 2.0 - 1.0).abs());- let m = v - c;- let [r, g, b] = match h as u32 {- 0 => [c, x, 0.0],- 1 => [x, c, 0.0],- 2 => [0.0, c, x],- 3 => [0.0, x, c],- 4 => [x, 0.0, c],- _ => [c, 0.0, x],- };- [r + m, g + m, b + m]+// The settings.++/// A LUT row: its file (or a built-in curve), strength, interpolation and+/// whether it applies.+#[derive(Clone, Debug, PartialEq)]+pub(crate) struct LutRow {+ pub file: String,+ pub gain: f64,+ pub tetrahedral: bool,+ pub on: bool,}-/// The grade's steps, in their order: a picker reads a color where its-/// step begins.-#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]-enum Step {- CameraLut,- Wheels,- RlWheels,- LevelsAndTone,- Balance,- Hsl,- Curves,- HslCurves,- LookLut,+impl LutRow {+ fn step(&self) -> Option<LutStep> {+ if !self.on || self.gain <= 0.001 {+ return None;+ }+ let table = match self.file.trim() {+ APPLE_LOG_TO_LINEAR => LutTable::AppleLog { video: false },+ APPLE_LOG_TO_REC709 => LutTable::AppleLog { video: true },+ file => LutTable::Cube {+ lut: crate::lut_filter::table(file)?,+ tetrahedral: self.tetrahedral,+ },+ };+ Some(LutStep {+ table,+ gain: self.gain,+ })+ }}-impl Step {- const ALL: [Step; 9] = [- Step::CameraLut,- Step::Wheels,- Step::RlWheels,- Step::LevelsAndTone,- Step::Balance,- Step::Hsl,- Step::Curves,- Step::HslCurves,- Step::LookLut,- ];+/// The settings at a time.+#[derive(Clone, Debug, PartialEq)]+pub(crate) struct Settings {+ pub params: Params,+ pub luts: [LutRow; 2],}-impl Grade {- /// What the card draws (`accel::GradePlan`).- pub(crate) fn plan(&self) -> crate::accel::GradePlan {- use crate::accel::GradeLut;- let s = &self.settings;- let f = |v: f64| v as f32;- let on = |b: bool| f32::from(u8::from(b));- let lut = |l: &Option<(Table, f32)>| {- l.as_ref().map(|(t, k)| match t {- Table::Cube(lut, how) => GradeLut::Cube {- lut: lut.clone(),- tetrahedral: *how == Interpolation::Tetrahedral,- strength: *k,- },- Table::AppleLog { rec709 } => GradeLut::AppleLog {- video: *rec709,- strength: *k,- },- })+impl Settings {+ /// The settings from their values by name (`num`, `text`; `None` for+ /// one not given: its default).+ fn read(num: impl Fn(&str) -> Option<f64>, text: impl Fn(&str) -> Option<String>) -> Settings {+ let n = |name: &str, default: f64| num(name).unwrap_or(default);+ let wheel = |name: &str, rest: f64| Wheel {+ rgb: std::array::from_fn(|i| n(&wheel_param(name, PARTS[i]), rest)),+ y: n(&wheel_param(name, "Y"), rest),};- let levels = s.levels.map(f);- let mut steps = vec![[0.0f32; 4]; 16];- for (i, w) in s.wheels.iter().enumerate() {- steps[i] = w.map(f);- }- for (i, w) in s.rl.iter().enumerate() {- steps[4 + i] = w.map(f);- }- steps[8] = [- f(s.thresholds[0]),- f(s.thresholds[1]),- f(s.balance[0]),- f(s.balance[1]),- ];- steps[9] = levels;- steps[10] = [f(s.tone[0]), f(s.tone[1]), f(s.tone[2]), f(s.tone[3])];- steps[11] = [f(s.tone[4]), f(s.hsl[0]), f(s.hsl[1]), f(s.hsl[2])];- steps[12] = [- on(s.rl.iter().any(|w| w.iter().any(|v| *v != 0.0))),- on(self.hsl_curves.iter().any(|t| t.iter().any(|v| *v != 0.0))),- on(levels != [0.0, 1.0, 0.0, 1.0]),- 0.0,- ];- let (c, h) = (&self.curves, &self.hsl_curves);- steps.extend((0..TABLE).map(|k| [c[0][k], c[1][k], c[2][k], c[3][k]]));- steps.extend((0..TABLE).map(|k| [h[0][k], h[1][k], h[2][k], h[3][k]]));- steps.extend((0..TABLE).map(|k| [h[4][k], h[5][k], 0.0, 0.0]));- crate::accel::GradePlan {- camera: lut(&self.camera),- steps,- entries: TABLE as u32,- look: lut(&self.look),+ let p = Params {+ wheels: std::array::from_fn(|i| wheel(WHEELS[i], WHEEL_RANGES[i].2)),+ rl: std::array::from_fn(|i| wheel(RL_WHEELS[i], 0.0)),+ thresholds: [n(LOW_THRESHOLD, 0.25), n(HIGH_THRESHOLD, 0.5)],+ curves: std::array::from_fn(|i| {+ text(CURVES[i]).unwrap_or_else(|| grading::DEFAULT_CURVE.to_string())+ }),+ saturation: n(SATURATION, 1.0),+ exposure: n(EXPOSURE, 0.0),+ exposure_ln: n(EXPOSURE_LN, 0.0),+ brightness: n(BRIGHTNESS, 0.0),+ contrast: n(CONTRAST, 0.0),+ contrast_center: n(CONTRAST_CENTER, 0.5),+ temperature: n(TEMPERATURE, 0.0),+ tint: n(TINT, 0.0),+ levels: [+ n(IN_MIN, 0.0),+ n(IN_MAX, 1.0),+ n(OUT_MIN, 0.0),+ n(OUT_MAX, 1.0),+ ],+ hsl: [n(HUE, 0.0), n(SAT, 1.0), n(VAL, 1.0)],+ };+ let row = |k: usize| LutRow {+ file: text(LUT_FILE[k]).unwrap_or_default(),+ gain: n(LUT_GAIN[k], 1.0).clamp(0.0, 1.0),+ tetrahedral: n(LUT_INTERPOLATION[k], 0.0).round() != 0.0,+ on: n(LUT_ENABLE[k], 0.0) >= 0.5,+ };+ Settings {+ params: p,+ luts: [row(0), row(1)],}}- /// A color through the grade.- pub(crate) fn apply(&self, c: [f32; 3]) -> [f32; 3] {- Step::ALL.into_iter().fold(c, |c, step| self.step(step, c))+ /// The settings in `v`, a time's values as the host gives them.+ pub(crate) fn of(v: Values<'_>) -> Settings {+ Settings::read(+ |name| v.nums(&c(name)).and_then(|n| n.first().copied()),+ |name| v.text(&c(name)).map(str::to_string),+ )}- /// A color through the steps before `end`.- fn before(&self, end: Step, c: [f32; 3]) -> [f32; 3] {- Step::ALL- .into_iter()- .take_while(|step| *step < end)- .fold(c, |c, step| self.step(step, c))+ fn at(fx: Fx, time: f64) -> Settings {+ Settings::read(+ |name| {+ let p = fx.param(&c(name));+ Some(+ if name.starts_with("lutEnable") || name.starts_with("lutInterpolation") {+ f64::from(p.int_at(time))+ } else {+ p.f64_at(time)+ },+ )+ },+ |name| Some(fx.param(&c(name)).text_at(time)),+ )}- /// A color through one step.- fn step(&self, step: Step, mut c: [f32; 3]) -> [f32; 3] {- let s = &self.settings;- match step {- Step::CameraLut | Step::LookLut => {- let lut = if step == Step::CameraLut {- &self.camera- } else {- &self.look- };- if let Some((t, k)) = lut {- let out = t.apply(c);- c = std::array::from_fn(|i| c[i] + (out[i] - c[i]) * k);- }- }- // Color Wheels: Lift, Gain, Gamma, Offset.- Step::Wheels => {- let w = s.wheels.map(|w| w.map(|v| v as f32));- for (i, x) in c.iter_mut().enumerate() {- let lift = w[0][i] + w[0][3];- let gamma = (w[1][i] * w[1][3]).max(0.01);- let gain = w[2][i] * w[2][3];- let offset = w[3][i] + w[3][3];- let mut v = *x + lift * (1.0 - *x);- v *= gain;- if v > 0.0 && gamma != 1.0 {- v = v.powf(1.0 / gamma);- }- *x = v + offset;- }- }- // RL Color Wheels: by where the luma stands.- Step::RlWheels => {- if s.rl.iter().any(|w| w.iter().any(|v| *v != 0.0)) {- let [lo, hi] = s.thresholds.map(|t| t as f32);- let y = luma(c);- let shadows = 1.0 - smoothstep(lo - SOFT, lo + SOFT, y);- let highlights = smoothstep(hi - SOFT, hi + SOFT, y);- let midtones = (1.0 - shadows - highlights).max(0.0);- let r = s.rl.map(|w| w.map(|v| v as f32));- for (i, x) in c.iter_mut().enumerate() {- *x += shadows * (r[0][i] + r[0][3])- + midtones * (r[1][i] + r[1][3])- + highlights * (r[2][i] + r[2][3])- + r[3][i]- + r[3][3];- }- }- }- Step::LevelsAndTone => {- let [in_black, in_white, out_min, out_max] = s.levels.map(|v| v as f32);- if [in_black, in_white, out_min, out_max] != [0.0, 1.0, 0.0, 1.0] {- let span = (in_white - in_black).max(1e-4);- c = c.map(|x| out_min + (x - in_black) / span * (out_max - out_min));- }- let [brightness, contrast, center, saturation, log_exposure] =- s.tone.map(|v| v as f32);- c = c.map(|x| {- (x + brightness + log_exposure * LOG_STOP - center) * (1.0 + contrast) + center- });- if saturation != 1.0 {- let y = luma(c);- c = c.map(|x| y + (x - y) * saturation);- }- }- // White Balance: warmer to the left, greener to the right.- Step::Balance => {- let [temperature, tint] = s.balance.map(|v| v as f32);- if temperature != 0.0 || tint != 0.0 {- c[0] *= 1.0 - BALANCE * temperature;- c[2] *= 1.0 + BALANCE * temperature;- c[1] *= 1.0 + BALANCE * tint;- }- }- // HSL: the chroma turned and scaled about the luma, then the- // luma moved.- Step::Hsl => {- let [hue, hsl_saturation, luminance] = s.hsl.map(|v| v as f32);- if hue != 0.0 || hsl_saturation != 1.0 || luminance != 0.0 {- let y = luma(c);- let (cb, cr) = (c[2] - y, c[0] - y);- let (sin, cos) = hue.to_radians().sin_cos();- let (cb, cr) = (- (cb * cos - cr * sin) * hsl_saturation,- (cb * sin + cr * cos) * hsl_saturation,- );- let y = y + luminance;- let r = y + cr;- let b = y + cb;- let g = (y - 0.2126 * r - 0.0722 * b) / 0.7152;- c = [r, g, b];- }- }- // Curves: the luma through Brightness (the color scaled along),- // then each channel.- Step::Curves => {- let y = luma(c);- let mapped = at(&self.curves[0], y);- if y > 1e-5 {- let k = mapped / y;- c = c.map(|x| x * k);- } else {- c = c.map(|x| x + (mapped - y));- }- for (i, x) in c.iter_mut().enumerate() {- *x = at(&self.curves[i + 1], *x);- }- }- Step::HslCurves => {- if self.hsl_curves.iter().any(|t| t.iter().any(|v| *v != 0.0)) {- let [h, sat, v] = hsv(c.map(|x| x.max(0.0)));- let t = &self.hsl_curves;- let h2 = h + 0.5 * within(&t[0], h);- let sat2 = sat- * (1.0 + within(&t[1], h))- * (1.0 + within(&t[3], sat))- * (1.0 + within(&t[5], v));- let v2 = v * (1.0 + within(&t[2], h) + within(&t[4], sat));- c = from_hsv([h2, sat2.max(0.0), v2.max(0.0)]);- }- }- }- c+ /// Ready to color pixels.+ pub(crate) fn grade(&self) -> Grade {+ Grade::new(&self.params, self.luts[0].step(), self.luts[1].step())}}@@ -746,9 +353,9 @@ impl Grade {/// (the effect's input there) sets.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub enum Picker {- /// Lift's Specify a Black Point: the color becomes black.+ /// Lift's eyedropper.BlackPoint,- /// Gain's Specify a White Point: the color becomes white.+ /// Gain's eyedropper.WhitePoint,/// White Balance's Select Neutral Tone: the color becomes a grey.NeutralTone,@@ -760,9 +367,9 @@ pub enum Picker {/// What `picker` sets, from the colors picked (straight RGB, the effect's/// input: a click's few pixels, or a region's when `region`) and the-/// effect's `values` (those not given at their defaults): the parameters'-/// new values by name. Nothing when the colors say nothing (greys have no-/// hue; black takes no white balance).+/// effect's `values`: the parameters' new values by name. Nothing when+/// the colors say nothing (greys have no hue; black takes no white+/// balance).pub fn pick(values: &[(String, crate::accel::Value)],picker: Picker,@@ -774,105 +381,155 @@ pub fn pick(return Vec::new();}let settings = Settings::of(Values(values));- let grade = settings.grade();let n = colors.len() as f64;- let mean: [f32; 3] =- std::array::from_fn(|i| (colors.iter().map(|c| c[i] as f64).sum::<f64>() / n) as f32);- let named = |name: &CStr| name.to_string_lossy().into_owned();+ let mean: [f64; 3] =+ std::array::from_fn(|i| colors.iter().map(|c| f64::from(c[i])).sum::<f64>() / n);+ let num = |v: f64| Value::Num(vec![v]);match picker {- // Lift takes the color, where the wheels begin, down to 0.- Picker::BlackPoint => {- let c = grade.before(Step::Wheels, mean);- let master = settings.wheels[0][3];- let lift = c.map(|x| {- let x = x as f64;- let whole = if x < 0.999 { -x / (1.0 - x) } else { -1.0 };- (whole - master).clamp(-1.0, 1.0)- });- vec![(named(WHEELS[0].0), Value::Num(lift.to_vec()))]- }- // Gain takes it, lifted, up to 1.- Picker::WhitePoint => {- let c = grade.before(Step::Wheels, mean);- let [lift, _, gain, _] = settings.wheels;- let gain: [f64; 3] = std::array::from_fn(|i| {- let x = c[i] as f64;- let v = (x + (lift[i] + lift[3]) * (1.0 - x)) * gain[3];- (1.0 / v.max(0.25)).min(4.0)+ // VEGAS's eyedroppers: each channel of the color between the+ // wheel's ends — Lift's turned over, Gain's as it is.+ Picker::BlackPoint | Picker::WhitePoint => {+ let w = if picker == Picker::BlackPoint { 0 } else { 2 };+ let range = WHEEL_RANGES[w];+ let (low, high, _) = range;+ let v = mean.map(|x| {+ let x = x.clamp(0.0, 1.0);+ let x = if w == 0 { 1.0 - x } else { x };+ ((low + x * (high - low)) * 1000.0).round() / 1000.0});- vec![(named(WHEELS[2].0), Value::Num(gain.to_vec()))]+ let [u, vv] = wheel_point(v, range, false);+ let mut out: Vec<(String, Value)> = (0..3)+ .map(|i| (wheel_param(WHEELS[w], PARTS[i]), num(v[i])))+ .collect();+ out.push((wheel_param(WHEELS[w], "U"), num(u)));+ out.push((wheel_param(WHEELS[w], "V"), num(vv)));+ out}- // The temperature evens red and blue out, the tint green with them.+ // The temperature and tint that leave the color a grey.Picker::NeutralTone => {- let [r, g, b] = grade.before(Step::Balance, mean).map(|x| x.max(0.0) as f64);- if r + b < 1e-4 || g < 1e-4 {+ let before = before_balance(&settings, mean);+ if before.iter().all(|v| *v < 1e-4) {return Vec::new();}- let k = BALANCE as f64;- let temperature = ((r - b) / (k * (r + b))).clamp(-1.0, 1.0);- let grey = r * (1.0 - k * temperature);- let tint = ((grey / g - 1.0) / k).clamp(-1.0, 1.0);+ let (t, k) = neutral_balance(before);vec![- (named(TEMPERATURE), Value::Num(vec![temperature])),- (named(TINT), Value::Num(vec![tint])),+ (TEMPERATURE.to_string(), num(t)),+ (TINT.to_string(), num(k)),]}- Picker::Selector(n) => {- let n = n.min(HSL_CURVE_NAMES.len() - 1);- let at: Vec<[f32; 3]> = colors+ Picker::Selector(curve) => {+ let curve = curve.min(5);+ let kind = HslCurve::ALL[curve];+ let keys: Vec<f64> = colors.iter()- .map(|&c| hsv(grade.before(Step::HslCurves, c).map(|x| x.max(0.0))))+ .map(|c| selector_key(kind, c.map(f64::from))).collect();- let xs = match n {- 0..=2 => hue_points(&at, region),- 3 | 4 => spread_points(at.iter().map(|c| c[1]), region),- _ => spread_points(at.iter().map(|c| c[2]), region),+ let xs = match kind {+ HslCurve::HueHue | HslCurve::HueSat | HslCurve::HueLum => {+ hue_points(&keys, colors, region)+ }+ _ => spread_points(&keys, region),};if xs.is_empty() {return Vec::new();}- let mut curves = settings.hsl_curves.clone();- curves.resize(HSL_CURVE_NAMES.len(), Vec::new());- let curve = &mut curves[n];+ let hue = curve < 3;+ let text = &settings.params.curves[4 + curve];+ let mut points = curve_points(text, hue);+ let table = curve_table(text);for x in xs {- if curve.iter().any(|p| (p.x - x).abs() < 0.004) {+ if points.iter().any(|p| (p.x - x).abs() < 0.004) {continue;}// Where the curve is already: it keeps its shape.- let y = if n < 3 {- wrapped_at(curve, x)- } else {- bv_core::curve::curve_at(curve, x)- };- curve.push(CurvePoint {- x,- y,- handles: None,- });- curve.sort_by(|a, b| a.x.total_cmp(&b.x));+ let y = table+ .as_ref()+ .map_or(0.5, |t| grading::lookup(t, x).clamp(0.0, 1.0));+ points.push(CurvePoint::new(x, y));+ points.sort_by(|a, b| a.x.total_cmp(&b.x));}- vec![(named(HSL_CURVES), Value::Curves(curves))]+ let points = flat_handles(&points);+ let text = if hue {+ hue_curve_text(&points)+ } else {+ color_curve_text(&points)+ };+ vec![(CURVES[4 + curve].to_string(), Value::Text(text))]}}}-/// The hues (a turn's 0–1) a Color Selector puts points at, from colors'-/// HSV: their mean hue (the saturated weighing more, greys none) and for a-/// region its two ends round it.-fn hue_points(colors: &[[f32; 3]], region: bool) -> Vec<f64> {+/// Points given flat handles, each half the way to its neighbour (at most+/// 0.125): the window's flattened points.+pub fn flat_handles(points: &[CurvePoint]) -> Vec<CurvePoint> {+ (0..points.len())+ .map(|i| {+ let p = points[i];+ if p.handles.is_some() {+ return p;+ }+ let before = i+ .checked_sub(1)+ .map_or(0.125, |j| ((p.x - points[j].x) / 2.0).min(0.125));+ let after = points+ .get(i + 1)+ .map_or(0.125, |q| ((q.x - p.x) / 2.0).min(0.125));+ CurvePoint::with(p.x, p.y, [-before, 0.0], [after, 0.0])+ })+ .collect()+}++/// A color's key on an HSL curve: its hue, saturation or (Luminance vs+/// Saturation) lightness.+fn selector_key(kind: HslCurve, c: [f64; 3]) -> f64 {+ let [h, s, l] = hsl_of(c);+ match kind {+ HslCurve::HueHue | HslCurve::HueSat | HslCurve::HueLum => h,+ HslCurve::SatSat | HslCurve::SatLum => s,+ HslCurve::LumSat => l,+ }+}++fn hsl_of([r, g, b]: [f64; 3]) -> [f64; 3] {+ let lo = r.min(g).min(b);+ let hi = r.max(g).max(b);+ let l = (lo + hi) / 2.0;+ let d = hi - lo;+ if d <= 1e-9 {+ return [0.0, 0.0, l];+ }+ let s = if l > 0.5 {+ d / (2.0 - hi - lo)+ } else {+ d / (hi + lo)+ };+ let h = if hi == r {+ ((g - b) / d).rem_euclid(6.0)+ } else if hi == g {+ (b - r) / d + 2.0+ } else {+ (r - g) / d + 4.0+ };+ [h / 6.0, s, l]+}++/// The hues a Color Selector puts points at: their mean (the saturated+/// weighing more, greys none) and for a region its two ends round it.+fn hue_points(hues: &[f64], colors: &[[f32; 3]], region: bool) -> Vec<f64> {use std::f64::consts::TAU;let (mut x, mut y) = (0.0f64, 0.0f64);- let mut hues = Vec::new();- for &[h, s, _] in colors {+ let mut kept = Vec::new();+ for (&h, c) in hues.iter().zip(colors) {+ let s = hsl_of(c.map(f64::from))[1];if s < 0.02 {continue;}- let (sin, cos) = (h as f64 * TAU).sin_cos();- x += s as f64 * cos;- y += s as f64 * sin;- hues.push(h as f64);+ let (sin, cos) = (h * TAU).sin_cos();+ x += s * cos;+ y += s * sin;+ kept.push(h);}- if hues.is_empty() || x.hypot(y) < 1e-9 {+ if kept.is_empty() || x.hypot(y) < 1e-9 {return Vec::new();}let mean = (y.atan2(x) / TAU).rem_euclid(1.0);@@ -880,8 +537,8 @@ fn hue_points(colors: &[[f32; 3]], region: bool) -> Vec<f64> {return vec![mean];}let off = |h: f64| (h - mean + 0.5).rem_euclid(1.0) - 0.5;- let lo = hues.iter().map(|&h| off(h)).fold(0.0, f64::min);- let hi = hues.iter().map(|&h| off(h)).fold(0.0, f64::max);+ let lo = kept.iter().map(|&h| off(h)).fold(0.0, f64::min);+ let hi = kept.iter().map(|&h| off(h)).fold(0.0, f64::max);if hi - lo < 0.01 {return vec![mean];}@@ -892,10 +549,10 @@ fn hue_points(colors: &[[f32; 3]], region: bool) -> Vec<f64> {]}-/// The saturations or values a Color Selector puts points at: their mean,-/// and for a region the lowest and the highest.-fn spread_points(values: impl Iterator<Item = f32>, region: bool) -> Vec<f64> {- let v: Vec<f64> = values.map(|v| (v as f64).clamp(0.0, 1.0)).collect();+/// The saturations or lightnesses a Color Selector puts points at: their+/// mean, and for a region the lowest and the highest.+fn spread_points(values: &[f64], region: bool) -> Vec<f64> {+ let v: Vec<f64> = values.iter().map(|v| v.clamp(0.0, 1.0)).collect();if v.is_empty() {return Vec::new();}@@ -908,6 +565,57 @@ fn spread_points(values: impl Iterator<Item = f32>, region: bool) -> Vec<f64> {vec![lo, mean, hi]}+/// A color where White Balance takes it: through the Camera LUT and the+/// HSL Curves.+fn before_balance(settings: &Settings, c: [f64; 3]) -> [f64; 3] {+ let mut only = settings.clone();+ only.luts[1].on = false;+ let mut p = Params::default();+ p.curves[4..].clone_from_slice(&settings.params.curves[4..]);+ only.params = p;+ let g = only.grade();+ g.apply(c.map(|v| v as f32)).map(f64::from)+}++/// The temperature and tint (within their ranges) that leave `c` a grey,+/// found by halving steps from the middle.+fn neutral_balance(c: [f64; 3]) -> (f64, f64) {+ let off = |t: f64, k: f64| {+ let m = grading::balance_matrix(t, k);+ let lin = c.map(|v| v.max(0.0).powf(2.4));+ let o: [f64; 3] = std::array::from_fn(|i| {+ (m[i][0] * lin[0] + m[i][1] * lin[1] + m[i][2] * lin[2])+ .max(0.0)+ .powf(1.0 / 2.4)+ });+ let mean = (o[0] + o[1] + o[2]) / 3.0;+ o.iter().map(|v| (v - mean).powi(2)).sum::<f64>()+ };+ let (mut t, mut k) = (0.0f64, 0.0f64);+ let (mut st, mut sk) = (2000.0f64, 50.0f64);+ while st > 0.5 {+ let mut best = (off(t, k), t, k);+ for dt in [-st, 0.0, st] {+ for dk in [-sk, 0.0, sk] {+ let (nt, nk) = (+ (t + dt).clamp(-4000.0, 4000.0),+ (k + dk).clamp(-100.0, 100.0),+ );+ let e = off(nt, nk);+ if e < best.0 {+ best = (e, nt, nk);+ }+ }+ }+ if best.1 == t && best.2 == k {+ st /= 2.0;+ sk /= 2.0;+ }+ (t, k) = (best.1, best.2);+ }+ ((t * 10.0).round() / 10.0, (k * 1000.0).round() / 1000.0)+}+/// The Color Grading's grade with `values` (the parameters set; the/// others at their defaults) as a `.cube` 3D table `size` points a side:/// Export LUT.@@ -915,36 +623,183 @@ pub fn cube(values: &[(String, crate::accel::Value)], size: usize) -> String {let size = size.clamp(2, 129);let grade = Settings::of(Values(values)).grade();let mut out = String::with_capacity(size * size * size * 30 + 100);- out.push_str(- "TITLE \"BananaV Color Grading\"-",- );- out.push_str(&format!(- "LUT_3D_SIZE {size}-"- ));- out.push_str(- "DOMAIN_MIN 0.0 0.0 0.0-DOMAIN_MAX 1.0 1.0 1.0-",- );+ out.push_str("TITLE \"BananaV Color Grading\"\n");+ out.push_str(&format!("LUT_3D_SIZE {size}\n"));+ out.push_str("DOMAIN_MIN 0.0 0.0 0.0\nDOMAIN_MAX 1.0 1.0 1.0\n");let step = 1.0 / (size - 1) as f32;// Red changes fastest, as the format has it.for b in 0..size {for g in 0..size {for r in 0..size {let c = grade.apply([r as f32 * step, g as f32 * step, b as f32 * step]);- out.push_str(&format!(- "{:.6} {:.6} {:.6}-",- c[0], c[1], c[2]- ));+ out.push_str(&format!("{:.6} {:.6} {:.6}\n", c[0], c[1], c[2]));}}}out}+/// Apple Log (Apple's published curve, Rec. 2020's primaries) decoded:+/// Rec. 709's linear light, or its video (BT.709's curve, clipped at+/// white).+pub(crate) fn apple_log(c: [f32; 3], rec709: bool) -> [f32; 3] {+ const R0: f64 = -0.05641088;+ const RT: f64 = 0.01;+ const C: f64 = 47.28711236;+ const B: f64 = 0.00964052;+ const G: f64 = 0.08550479;+ const D: f64 = 0.69336945;+ let linear = |x: f32| {+ let x = f64::from(x);+ let pt = C * (RT - R0).powi(2);+ if x >= pt {+ 2f64.powf((x - D) / G) - B+ } else if x >= 0.0 {+ (x / C).sqrt() + R0+ } else {+ R0+ }+ };+ let l = c.map(linear);+ // Rec. 2020 to Rec. 709 (both D65).+ const M: [[f64; 3]; 3] = [+ [1.660_491, -0.587_641, -0.072_850],+ [-0.124_551, 1.132_900, -0.008_349],+ [-0.018_151, -0.100_579, 1.118_730],+ ];+ let out: [f64; 3] = std::array::from_fn(|i| M[i][0] * l[0] + M[i][1] * l[1] + M[i][2] * l[2]);+ if !rec709 {+ return out.map(|v| v as f32);+ }+ out.map(|v| {+ let v = v.clamp(0.0, 1.0);+ let e = if v < 0.018 {+ 4.5 * v+ } else {+ 1.099 * v.powf(0.45) - 0.099+ };+ e as f32+ })+}++// The card.++impl Grade {+ /// What the card draws (`accel::GradePlan`): `steps` holds the+ /// settings, a row each, then the tables, an entry a row (see+ /// `shaders/own_pair.wgsl`'s `grade`).+ pub(crate) fn plan(&self) -> crate::accel::GradePlan {+ use crate::accel::GradeLut;+ let lut = |s: &Option<LutStep>| {+ s.as_ref().map(|s| match &s.table {+ LutTable::Cube { lut, tetrahedral } => GradeLut::Cube {+ lut: lut.clone(),+ tetrahedral: *tetrahedral,+ strength: s.gain as f32,+ },+ LutTable::AppleLog { video } => GradeLut::AppleLog {+ video: *video,+ strength: s.gain as f32,+ },+ })+ };+ let f = |v: f64| v as f32;+ let on = |b: bool| if b { 1.0 } else { 0.0 };+ let mut rows = vec![[0.0f32; 4]; HEAD];+ let mut tables: Vec<f32> = Vec::new();+ // A table's place (after the head) and length.+ let mut put = |t: &[f32]| -> [f32; 2] {+ let at = tables.len();+ tables.extend_from_slice(t);+ [(HEAD + at) as f32, t.len() as f32]+ };+ rows[0] = [+ on(self.balance.is_some()),+ on(self.levels.is_some()),+ on(self.rl_rgb.is_some()),+ on(self.rl_y.is_some()),+ ];+ rows[1] = [+ on(self.curves_rgb.is_some()),+ on(self.curve_y.is_some()),+ on(self.lift.is_some()),+ self.hsl_curves.len() as f32,+ ];+ rows[2] = [+ self.saturation.map_or(1.0, f),+ self.exposure.map_or(1.0, f),+ self.brightness.map_or(0.0, f),+ on(self.exposure_ln.is_some()),+ ];+ let (k, center) = self.contrast.unwrap_or((0.0, 0.5));+ rows[3] = [+ f(k),+ f(center),+ self.exposure_ln.as_ref().map_or(1.0, |e| f(e.pre)),+ f(self.hsl[0]),+ ];+ rows[4] = [+ f(self.hsl[1]),+ f(self.hsl[2]),+ on(self.cdl[0].is_some()),+ on(self.cdl[1].is_some()),+ ];+ if let Some(m) = &self.balance {+ for (i, row) in m.iter().enumerate() {+ rows[5 + i] = [f(row[0]), f(row[1]), f(row[2]), 0.0];+ }+ }+ if let Some(l) = self.levels {+ rows[8] = l.map(f);+ }+ if let Some(l) = self.lift {+ rows[9] = [f(l[0]), f(l[1]), f(l[2]), 0.0];+ }+ for (i, cdl) in self.cdl.iter().enumerate() {+ if let Some(c) = cdl {+ rows[10 + 3 * i] = [f(c.slope[0]), f(c.slope[1]), f(c.slope[2]), 0.0];+ rows[11 + 3 * i] = [f(c.offset[0]), f(c.offset[1]), f(c.offset[2]), 0.0];+ rows[12 + 3 * i] = [f(c.power[0]), f(c.power[1]), f(c.power[2]), 0.0];+ }+ }+ for (i, (kind, t)) in self.hsl_curves.iter().enumerate() {+ let [at, len] = put(t);+ let k = HslCurve::ALL.iter().position(|c| c == kind).unwrap_or(0);+ rows[16 + i] = [k as f32, at, len, 0.0];+ }+ let none: &[f32] = &[];+ let rl = self.rl_rgb.as_ref();+ let curves = self.curves_rgb.as_ref();+ let listed: [&[f32]; 9] = [+ rl.map_or(none, |t| &t[0]),+ rl.map_or(none, |t| &t[1]),+ rl.map_or(none, |t| &t[2]),+ self.rl_y.as_deref().unwrap_or(none),+ curves.map_or(none, |t| &t[0]),+ curves.map_or(none, |t| &t[1]),+ curves.map_or(none, |t| &t[2]),+ self.curve_y.as_deref().unwrap_or(none),+ self.exposure_ln.as_ref().map_or(none, |e| &e.table),+ ];+ for (i, t) in listed.iter().enumerate() {+ let [at, len] = put(t);+ rows[22 + i] = [at, len, 0.0, 0.0];+ }+ rows.extend(tables.into_iter().map(|v| [v, 0.0, 0.0, 0.0]));+ crate::accel::GradePlan {+ camera: lut(&self.camera),+ steps: rows,+ entries: HEAD as u32,+ look: lut(&self.look),+ }+ }+}++/// The card's settings' rows before the tables.+const HEAD: usize = 32;++// The plug-in.+/// The plug-in's entry point.pub(crate) unsafe extern "C" fn main(action: *const c_char,@@ -952,15 +807,12 @@ pub(crate) unsafe extern "C" fn main(in_args: OfxPropertySetHandle,out_args: OfxPropertySetHandle,) -> OfxStatus {- let Some(s) = suites() else {+ if suites().is_none() {return kOfxStatErrMissingHostFeature;- };+ }let fx = Fx(handle as OfxImageEffectHandle);let (args, out) = (Props(in_args), Props(out_args));if is(action, kOfxActionDescribe) {- if s.parametric.is_none() {- return kOfxStatErrMissingHostFeature;- }describe(fx);kOfxStatOK} else if is(action, kOfxImageEffectActionDescribeInContext) {@@ -970,7 +822,10 @@ pub(crate) unsafe extern "C" fn main(let grade = Settings::at(fx, args.dbl(kOfxPropTime, 0)).grade();crate::colors::render(fx, args, &|c| grade.apply(c))} else if is(action, kOfxImageEffectActionIsIdentity) {- if Settings::at(fx, args.dbl(kOfxPropTime, 0)).changes_nothing() {+ if Settings::at(fx, args.dbl(kOfxPropTime, 0))+ .grade()+ .changes_nothing()+ {out.set_str(kOfxPropName, kOfxImageEffectSimpleSourceClipName);kOfxStatOK} else {@@ -1016,6 +871,23 @@ fn describe(fx: Fx) {);}+/// A parameter's label: its name with its words apart ("liftR": "Lift+/// R").+fn label(name: &str) -> CString {+ let mut s = String::new();+ for (i, ch) in name.chars().enumerate() {+ if i == 0 {+ s.extend(ch.to_uppercase());+ } else {+ if ch.is_ascii_uppercase() || ch.is_ascii_digit() {+ s.push(' ');+ }+ s.push(ch);+ }+ }+ c(&s)+}+fn describe_in_context(fx: Fx) {let comps = [kOfxImageComponentRGBA,@@ -1024,108 +896,105 @@ fn describe_in_context(fx: Fx) {];fx.define_clip(kOfxImageEffectSimpleSourceClipName, &comps);fx.define_clip(kOfxImageEffectOutputClipName, &comps);-- let number = |name: &CStr, label: &CStr, [min, max, default]: [f64; 3]| {- let p = fx.define_param(kOfxParamTypeDouble, name, label);- p.set_dbl(kOfxParamPropDefault, default);- p.set_dbl(kOfxParamPropMin, min);- p.set_dbl(kOfxParamPropMax, max);- p.set_dbl(kOfxParamPropDisplayMin, min);- p.set_dbl(kOfxParamPropDisplayMax, max);- p.set_dbl(kOfxParamPropIncrement, 0.001);- p.set_int(kOfxParamPropDigits, 3);+ // Every parameter hidden: the Color Grading window edits them.+ let hidden = |p: Props| {+ p.set_int(kOfxParamPropSecret, 1);+ p};- let boolean = |name: &CStr, label: &CStr| {- let p = fx.define_param(kOfxParamTypeBoolean, name, label);- p.set_int(kOfxParamPropDefault, 1);- };- let color3 = |name: &CStr, label: &CStr, [min, max, default]: [f64; 3]| {- let p = fx.define_param(kOfxParamTypeDouble3D, name, label);- p.set_dbls(kOfxParamPropDefault, &[default; 3]);- p.set_dbls(kOfxParamPropMin, &[min; 3]);- p.set_dbls(kOfxParamPropMax, &[max; 3]);- p.set_dbls(kOfxParamPropDisplayMin, &[min; 3]);- p.set_dbls(kOfxParamPropDisplayMax, &[max; 3]);- p.set_strs(kOfxParamPropDimensionLabel, &[c"R", c"G", c"B"]);+ // A number: its range, the panel's (shown), its default and its+ // decimals.+ let number =+ |name: &str, [min, max]: [f64; 2], [shown_min, shown_max]: [f64; 2], default: f64| {+ let p = hidden(fx.define_param(kOfxParamTypeDouble, &c(name), &label(name)));+ p.set_dbl(kOfxParamPropDefault, default);+ p.set_dbl(kOfxParamPropMin, min);+ p.set_dbl(kOfxParamPropMax, max);+ p.set_dbl(kOfxParamPropDisplayMin, shown_min);+ p.set_dbl(kOfxParamPropDisplayMax, shown_max);+ p.set_dbl(kOfxParamPropIncrement, 0.001);+ p.set_int(kOfxParamPropDigits, 3);+ };+ let text = |name: &str, default: &str| {+ let p = hidden(fx.define_param(kOfxParamTypeString, &c(name), &label(name)));+ p.set_str(kOfxParamPropDefault, &c(default));+ p.set_int(kOfxParamPropAnimates, 1);+ p};- // The LUTs.- for (file, strength, tetra, on, label) in [- (- CAMERA_LUT,- CAMERA_STRENGTH,- CAMERA_TETRAHEDRAL,- CAMERA_ON,- c"Camera LUT",- ),- (- LOOK_LUT,- LOOK_STRENGTH,- LOOK_TETRAHEDRAL,- LOOK_ON,- c"Look LUT",- ),- ] {- let p = fx.define_param(kOfxParamTypeString, file, label);- p.set_str(kOfxParamPropStringMode, kOfxParamStringIsFilePath);- p.set_str(kOfxParamPropDefault, c"");- number(strength, c"Strength", [0.0, 1.0, 1.0]);- boolean(tetra, c"Tetrahedral Interpolation");- boolean(on, c"LUT Selection");+ for name in CURVES {+ text(name, grading::DEFAULT_CURVE);}- // The wheels: Lift and Offset add, Gamma and Gain multiply.- let wheel_labels = [c"Lift", c"Gamma", c"Gain", c"Offset"];- let wheel_ranges = [- [-1.0, 1.0, 0.0],- [0.1, 4.0, 1.0],- [0.0, 4.0, 1.0],- [-1.0, 1.0, 0.0],- ];- for (i, (rgb, y)) in WHEELS.into_iter().enumerate() {- color3(rgb, wheel_labels[i], wheel_ranges[i]);- number(y, c"Y", wheel_ranges[i]);+ // The wheels: Lift, Gamma, Gain and Offset's own ranges; the RL+ // wheels −1 to 1.+ let limits = [[-1.0, 1.0], [-5.0, 5.0], [0.0, 1000.0], [-1000.0, 1000.0]];+ for (i, wheel) in WHEELS.into_iter().enumerate() {+ let (lo, hi, rest) = WHEEL_RANGES[i];+ for part in ["R", "G", "B", "Y"] {+ number(&wheel_param(wheel, part), limits[i], [lo, hi], rest);+ }+ for part in ["U", "V"] {+ number(&wheel_param(wheel, part), [-85.0, 85.0], [-85.0, 85.0], 0.0);+ }}- let rl_labels = [c"Shadows", c"Midtones", c"Highlights", c"RL Offset"];- for (i, (rgb, y)) in RL_WHEELS.into_iter().enumerate() {- color3(rgb, rl_labels[i], [-1.0, 1.0, 0.0]);- number(y, c"Y", [-1.0, 1.0, 0.0]);+ for wheel in RL_WHEELS {+ for part in ["R", "G", "B", "Y"] {+ number(&wheel_param(wheel, part), [-1.0, 1.0], [-1.0, 1.0], 0.0);+ }+ for part in ["U", "V"] {+ number(&wheel_param(wheel, part), [-85.0, 85.0], [-85.0, 85.0], 0.0);+ }}- number(LOWER, c"Lower Threshold", [0.0, 1.0, 0.25]);- number(UPPER, c"Upper Threshold", [0.0, 1.0, 0.75]);- // The Utilities.- number(IN_BLACK, c"Input Black", [0.0, 1.0, 0.0]);- number(IN_WHITE, c"Input White", [0.0, 1.0, 1.0]);- number(OUT_MIN, c"Output Min", [0.0, 1.0, 0.0]);- number(OUT_MAX, c"Output Max", [0.0, 1.0, 1.0]);- number(BRIGHTNESS, c"Brightness", [-1.0, 1.0, 0.0]);- number(CONTRAST, c"Contrast", [-1.0, 1.0, 0.0]);- number(CONTRAST_CENTER, c"Contrast Center", [0.0, 1.0, 0.5]);- number(SATURATION, c"Saturation", [0.0, 2.0, 1.0]);- number(LOG_EXPOSURE, c"Log. Exposure", [-4.0, 4.0, 0.0]);- number(TEMPERATURE, c"Temperature", [-1.0, 1.0, 0.0]);- number(TINT, c"Tint", [-1.0, 1.0, 0.0]);- number(HUE, c"Hue", [-180.0, 180.0, 0.0]);- number(HSL_SATURATION, c"Sat", [0.0, 2.0, 1.0]);- number(LUMINANCE, c"Luminance", [-1.0, 1.0, 0.0]);- // The Curves: straight; the HSL Curves: flat at 0.- let p = fx.define_param(kOfxParamTypeParametric, CURVES, c"Color Curves");- p.set_int(kOfxParamPropParametricDimension, CURVE_NAMES.len() as c_int);- p.set_strs(kOfxParamPropDimensionLabel, &CURVE_NAMES);- let colours: Vec<f64> = CURVE_COLOURS.iter().flatten().copied().collect();- p.set_dbls(kOfxParamPropParametricUIColour, &colours);- p.set_dbls(kOfxParamPropParametricRange, &[0.0, 1.0]);- p.set_int(kOfxParamPropAnimates, 1);- let curves = fx.param(CURVES);- for c in 0..CURVE_NAMES.len() {- curves.set_curve(c as c_int, 0.0, &[[0.0, 0.0], [1.0, 1.0]]);+ number(HIGH_THRESHOLD, [0.0, 1.0], [0.0, 1.0], 0.5);+ number(LOW_THRESHOLD, [0.0, 1.0], [0.0, 1.0], 0.25);+ number(SATURATION, [0.0, 2.0], [0.0, 2.0], 1.0);+ number(EXPOSURE, [-5.0, 5.0], [-3.0, 3.0], 0.0);+ number(EXPOSURE_LN, [-5.0, 5.0], [-5.0, 5.0], 0.0);+ number(BRIGHTNESS, [-1.0, 1.0], [-1.0, 1.0], 0.0);+ number(CONTRAST, [-1.0, 1.0], [-1.0, 1.0], 0.0);+ number(CONTRAST_CENTER, [0.0, 1.0], [0.0, 1.0], 0.5);+ number(TEMPERATURE, [-4000.0, 4000.0], [-4000.0, 4000.0], 0.0);+ number(TINT, [-100.0, 100.0], [-100.0, 100.0], 0.0);+ number(IN_MIN, [0.0, 1.0], [0.0, 1.0], 0.0);+ number(IN_MAX, [0.0, 1.0], [0.0, 1.0], 1.0);+ number(OUT_MIN, [0.0, 1.0], [0.0, 1.0], 0.0);+ number(OUT_MAX, [0.0, 1.0], [0.0, 1.0], 1.0);+ number(HUE, [0.0, 1.0], [0.0, 1.0], 0.0);+ number(SAT, [0.0, 5.0], [0.0, 2.0], 1.0);+ number(VAL, [0.0, 5.0], [0.0, 2.0], 1.0);+ for k in 0..2 {+ let p = hidden(fx.define_param(+ kOfxParamTypeBoolean,+ &c(LUT_ENABLE[k]),+ &label(LUT_ENABLE[k]),+ ));+ p.set_int(kOfxParamPropDefault, 0);+ let p = text(LUT_FILE[k], "");+ p.set_str(kOfxParamPropStringMode, kOfxParamStringIsFilePath);+ p.set_int(kOfxParamPropAnimates, 0);+ let p = hidden(fx.define_param(+ kOfxParamTypeChoice,+ &c(LUT_INTERPOLATION[k]),+ &label(LUT_INTERPOLATION[k]),+ ));+ p.set_strs(+ kOfxParamPropChoiceOption,+ &[c"Linear (good)", c"Tetrahedral (best)"],+ );+ p.set_int(kOfxParamPropDefault, 0);+ p.set_int(kOfxParamPropAnimates, 0);+ number(LUT_GAIN[k], [0.0, 1.0], [0.0, 1.0], 1.0);}- let p = fx.define_param(kOfxParamTypeParametric, HSL_CURVES, c"HSL Curves");- p.set_int(- kOfxParamPropParametricDimension,- HSL_CURVE_NAMES.len() as c_int,- );- p.set_strs(kOfxParamPropDimensionLabel, &HSL_CURVE_NAMES);- p.set_dbls(kOfxParamPropParametricRange, &[0.0, 1.0]);- p.set_int(kOfxParamPropAnimates, 1);+ // Kept as VEGAS's effect keeps them; BananaV's color handling is the+ // project's.+ let p = hidden(fx.define_param(kOfxParamTypeInteger, c"autoAdjust", c"Auto Adjust"));+ p.set_int(kOfxParamPropDefault, 0);+ let p = hidden(fx.define_param(+ kOfxParamTypeInteger,+ c"cspaceVersion",+ c"Color Space Version",+ ));+ p.set_int(kOfxParamPropDefault, -2);+ text("cspaceName", "").set_int(kOfxParamPropAnimates, 0);+ text("outputTransformCspaceName", "").set_int(kOfxParamPropAnimates, 0);}#[cfg(test)]@@ -1140,226 +1009,391 @@ mod tests {.collect()}- fn near(a: [f32; 3], b: [f32; 3], within: f32) -> bool {- a.iter().zip(b).all(|(x, y)| (x - y).abs() <= within)- }-- #[test]- fn exported_luts_hold_the_grade() {- let num = |v: &[f64]| Value::Num(v.to_vec());- let v = values(&[("gain", num(&[0.5, 1.0, 1.0]))]);- let text = cube(&v, 2);- let lut = Lut::parse(&text).unwrap();- let out = lut.apply([1.0, 1.0, 1.0], Interpolation::Linear);- assert!(near(out, [0.5, 1.0, 1.0], 1e-4), "{out:?}");- assert!(text.starts_with("TITLE"));- }-- #[test]- fn the_default_changes_nothing() {- let s = Settings::neutral();- assert!(s.changes_nothing());- let g = s.grade();- for c in [- [0.1, 0.5, 0.9],- [0.0, 0.0, 0.0],- [1.0, 1.0, 1.0],- [0.3, 0.3, 0.3],- ] {- assert!(near(g.apply(c), c, 1e-3), "{c:?}: {:?}", g.apply(c));- }+ fn num(v: f64) -> Value {+ Value::Num(vec![v])}#[test]- fn wheels_lift_gain_gamma_and_offset() {- let num = |v: &[f64]| Value::Num(v.to_vec());- // Lift: black rises to it, white stays.- let v = values(&[("lift", num(&[0.2, 0.2, 0.2]))]);- let g = Settings::of(Values(&v)).grade();- assert!(near(g.apply([0.0; 3]), [0.2; 3], 1e-3));- assert!(near(g.apply([1.0; 3]), [1.0; 3], 1e-3));- // Gain: scales; Gamma: bends the middle (white and black stay).- let v = values(&[("gain", num(&[0.5, 1.0, 1.0]))]);- let g = Settings::of(Values(&v)).grade();- assert!(near(g.apply([0.8; 3]), [0.4, 0.8, 0.8], 1e-3));- let v = values(&[("gammaY", num(&[2.0]))]);- let g = Settings::of(Values(&v)).grade();- assert!(near(g.apply([0.25; 3]), [0.5; 3], 1e-3));- assert!(near(g.apply([1.0; 3]), [1.0; 3], 1e-3));- // Offset adds everywhere.- let v = values(&[("offsetY", num(&[0.1]))]);- let g = Settings::of(Values(&v)).grade();- assert!(near(g.apply([0.3; 3]), [0.4; 3], 1e-3));+ fn the_wheels_points_give_their_colors_as_vegas() {+ let lift = WHEEL_RANGES[0];+ // Up: red, toward its top.+ let v = wheel_values(0.0, 51.0, lift);+ assert!(v[0] > 0.99 && v[1] < 0.0 && v[2] < 0.0, "{v:?}");+ // The middle: the rest.+ assert_eq!(wheel_values(0.0, 0.0, lift), [0.0; 3]);+ // Down at the left: green; down at the right: blue.+ let a = 230f64.to_radians();+ let v = wheel_values(51.0 * a.cos(), 51.0 * a.sin(), lift);+ assert!(v[1] > 0.99, "{v:?}");+ let a = 335f64.to_radians();+ let v = wheel_values(51.0 * a.cos(), 51.0 * a.sin(), lift);+ assert!(v[2] > 0.99, "{v:?}");+ // Gamma's top is 5, its bottom 0.+ let v = wheel_values(0.0, 51.0, WHEEL_RANGES[1]);+ assert!((v[0] - 5.0).abs() < 0.05 && v[1] < 1.0, "{v:?}");+ // Typed values put the point about where it gives them.+ let [u, w] = wheel_point([0.3, 0.0, 0.0], lift, false);+ assert!(w > 0.0 && u.abs() < w, "{u} {w}");+ let back = wheel_values(u, w, lift);+ assert!((back[0] - 0.3).abs() < 0.05, "{back:?}");}#[test]- fn rl_wheels_keep_to_their_range() {- let num = |v: &[f64]| Value::Num(v.to_vec());- let v = values(&[("shadows", num(&[0.0, 0.0, 0.2]))]);- let g = Settings::of(Values(&v)).grade();- // Dark grays turn blue, bright ones stay.- assert!((g.apply([0.05; 3])[2] - 0.25).abs() < 1e-3);- assert!(near(g.apply([0.9; 3]), [0.9; 3], 1e-3));- let v = values(&[("highlightsY", num(&[-0.1]))]);- let g = Settings::of(Values(&v)).grade();- assert!(near(g.apply([0.9; 3]), [0.8; 3], 1e-3));- assert!(near(g.apply([0.1; 3]), [0.1; 3], 1e-3));+ fn curves_text_round_trips_with_their_ends_and_turns() {+ let points = vec![CurvePoint::new(0.25, 0.4), CurvePoint::new(0.75, 0.6)];+ let text = color_curve_text(&flat_handles(&points));+ let k = grading::parse_curve(&text);+ assert_eq!(k.len(), 4);+ assert_eq!((k[0].x, k[0].y), (0.0, 0.4));+ assert_eq!((k[3].x, k[3].y), (1.0, 0.6));+ // A hue curve keeps its turn: a copy of its last point before 0.+ let text = hue_curve_text(&flat_handles(&points));+ let k = grading::parse_curve(&text);+ assert_eq!(k.len(), 4);+ assert!((k[0].x + 0.25).abs() < 1e-5 && (k[3].x - 1.25).abs() < 1e-5);+ assert_eq!(curve_points(&text, true).len(), 2);}#[test]- fn utilities_levels_tone_balance_and_hsl() {- let num = |v: &[f64]| Value::Num(v.to_vec());- // Levels: the input's 0.1–0.9 stretched to the whole range.- let v = values(&[("inputBlack", num(&[0.1])), ("inputWhite", num(&[0.9]))]);- let g = Settings::of(Values(&v)).grade();- assert!(near(g.apply([0.1; 3]), [0.0; 3], 1e-3));- assert!(near(g.apply([0.9; 3]), [1.0; 3], 1e-3));- // Contrast about its center: the center stays.- let v = values(&[("contrast", num(&[0.5]))]);- let g = Settings::of(Values(&v)).grade();- assert!(near(g.apply([0.5; 3]), [0.5; 3], 1e-3));- assert!(near(g.apply([0.7; 3]), [0.8; 3], 1e-3));- // Saturation 0: the luma's gray.- let v = values(&[("saturation", num(&[0.0]))]);- let g = Settings::of(Values(&v)).grade();- let out = g.apply([0.9, 0.2, 0.1]);- assert!((out[0] - out[1]).abs() < 1e-4 && (out[1] - out[2]).abs() < 1e-4);- // Warmer to the left.- let v = values(&[("temperature", num(&[-0.4]))]);- let g = Settings::of(Values(&v)).grade();- let out = g.apply([0.5; 3]);- assert!(out[0] > 0.5 && out[2] < 0.5);- // Hue: a half turn takes red toward cyan, the luma kept.- let v = values(&[("hue", num(&[180.0]))]);- let g = Settings::of(Values(&v)).grade();- let red = [0.6, 0.2, 0.2];- let out = g.apply(red);- assert!(out[0] < out[1] && out[0] < out[2], "{out:?}");- assert!((luma(out) - luma(red)).abs() < 1e-4);- }-- #[test]- fn curves_and_hsl_curves() {- let p = |x: f64, y: f64| CurvePoint {- x,- y,- handles: None,- };- // The red curve lifted to half at its start.- let curves = vec![- vec![p(0.0, 0.0), p(1.0, 1.0)],- vec![p(0.0, 0.5), p(1.0, 1.0)],- vec![p(0.0, 0.0), p(1.0, 1.0)],- vec![p(0.0, 0.0), p(1.0, 1.0)],- ];- let v = values(&[("curves", Value::Curves(curves))]);- let g = Settings::of(Values(&v)).grade();- assert!(near(g.apply([0.0; 3]), [0.5, 0.0, 0.0], 1e-3));- // Hue vs Saturation: the reds desaturated (wrapping round red),- // the blues kept.- let mut hsl = vec![Vec::new(); 6];- hsl[1] = vec![p(0.0, -1.0), p(0.2, 0.0), p(0.8, 0.0)];- let v = values(&[("hslCurves", Value::Curves(hsl))]);+ fn the_settings_read_their_values_and_default_to_nothing() {+ let s = Settings::of(Values(&[]));+ assert!(s.grade().changes_nothing());+ let v = values(&[+ ("liftR", num(0.3)),+ ("gammaY", num(1.2)),+ ("temperatureAdjust", num(2000.0)),+ (+ "curveR",+ Value::Text(+ "2:0.0:0.08:-0.25:-0.25:0.25:0.25:1.0:1.0:-0.25:-0.25:0.25:0.25:".into(),+ ),+ ),+ ]);let s = Settings::of(Values(&v));- assert!(!s.changes_nothing());+ assert_eq!(s.params.wheels[0].rgb[0], 0.3);+ assert_eq!(s.params.wheels[1].y, 1.2);+ assert_eq!(s.params.temperature, 2000.0);let g = s.grade();- let red = g.apply([0.8, 0.1, 0.1]);- assert!((red[0] - red[1]).abs() < 0.05, "{red:?}");- assert!(near(g.apply([0.1, 0.1, 0.8]), [0.1, 0.1, 0.8], 1e-3));+ assert!(!g.changes_nothing());+ // The red curve lifts black.+ let out = g.apply([0.0; 3]);+ assert!(out[0] > 0.05, "{out:?}");}#[test]- fn pickers_take_the_colors_where_they_should_go() {- let grade = |v: &[(String, Value)]| Settings::of(Values(v)).grade();- let set = |v: &mut Vec<(String, Value)>, new: Vec<(String, Value)>| {- for (name, value) in new {- v.retain(|(n, _)| *n != name);- v.push((name, value));- }+ fn pickers_set_what_vegas_eyedroppers_set() {+ // Lift: each channel between −1 and 1, the color turned over.+ let v = pick(&[], Picker::BlackPoint, &[[0.25, 0.5, 1.0]], false);+ let get = |n: &str| {+ v.iter()+ .find(|(k, _)| k == n)+ .map(|(_, v)| match v {+ Value::Num(x) => x[0],+ _ => f64::NAN,+ })+ .unwrap()};- // A black point: the dark blue-grey picked becomes black.- let dark = [0.1, 0.08, 0.12];- let mut v = Vec::new();- let new = pick(&v, Picker::BlackPoint, &[dark], false);- set(&mut v, new);- assert!(near(grade(&v).apply(dark), [0.0; 3], 1e-4));- // Then a white point, past the lift: the light one becomes white.- let light = [0.8, 0.85, 0.9];- let new = pick(&v, Picker::WhitePoint, &[light], false);- set(&mut v, new);- let g = grade(&v);- assert!(near(g.apply(light), [1.0; 3], 1e-3), "{:?}", g.apply(light));- assert!(near(g.apply(dark), [0.0; 3], 1e-4));- // A neutral tone: the warm grey becomes a grey.- let warm = [0.6, 0.5, 0.42];+ assert!((get("liftR") - 0.5).abs() < 1e-9);+ assert!(get("liftG").abs() < 1e-9);+ assert!((get("liftB") + 1.0).abs() < 1e-9);+ // A grey a white balance tinted made neutral again (warming acts+ // more than cooling: a slight warmth).+ let tinted = values(&[+ ("temperatureAdjust", num(-500.0)),+ ("tintAdjust", num(15.0)),+ ]);+ let warm = Settings::of(Values(&tinted)).grade().apply([0.5; 3]);let v = pick(&[], Picker::NeutralTone, &[warm], false);- let out = grade(&v).apply(warm);+ let out = Settings::of(Values(&v)).grade().apply(warm);assert!(- (out[0] - out[1]).abs() < 1e-4 && (out[1] - out[2]).abs() < 1e-4,- "{out:?}"+ (out[0] - out[1]).abs() < 0.01 && (out[1] - out[2]).abs() < 0.01,+ "{out:?} {v:?}");- // The Color Selector: a red's hue on Hue vs Hue, flat (the curve- // keeps its shape); greys say nothing.+ // The Color Selector: a red's hue on Hue vs Hue, at the curve's+ // rest (0.5); greys say nothing.let v = pick(&[], Picker::Selector(0), &[[0.8, 0.1, 0.1]], false);- let Some((_, Value::Curves(c))) = v.first() else {+ let Some((name, Value::Text(t))) = v.first() else {panic!("{v:?}");};- assert_eq!(c[0].len(), 1);- assert!(c[0][0].x.abs() < 1e-3 || (c[0][0].x - 1.0).abs() < 1e-3);- assert_eq!(c[0][0].y, 0.0);+ assert_eq!(name, "curveHvH");+ let p = curve_points(t, true);+ assert_eq!(p.len(), 1);+ assert!((p[0].y - 0.5).abs() < 1e-5);assert!(pick(&[], Picker::Selector(0), &[[0.5; 3]], false).is_empty());- // A region of oranges to yellows: its two ends and its mean.- let region: Vec<[f32; 3]> = (0..=10)- .map(|i| {- let h = 0.1 + 0.06 * i as f32 / 10.0;- from_hsv([h, 0.8, 0.9])- })- .collect();- let v = pick(&[], Picker::Selector(1), ®ion, true);- let Some((_, Value::Curves(c))) = v.first() else {- panic!("{v:?}");- };- let xs: Vec<f64> = c[1].iter().map(|p| p.x).collect();- assert_eq!(xs.len(), 3, "{xs:?}");- assert!(- (xs[0] - 0.1).abs() < 0.01 && (xs[2] - 0.16).abs() < 0.01,- "{xs:?}"- );- // Added to a curve with a point: on it, where it already is.- let curves = vec![vec![], vec![CurvePoint::new(0.5, 0.3)]];- let v = pick(- &values(&[("hslCurves", Value::Curves(curves))]),- Picker::Selector(1),- &[from_hsv([0.2, 0.8, 0.9])],- false,- );- let Some((_, Value::Curves(c))) = v.first() else {- panic!("{v:?}");- };- assert_eq!(c[1].len(), 2);- assert!(c[1].iter().all(|p| (p.y - 0.3).abs() < 1e-9));}#[test]fn apple_log_decodes_to_video() {- // Apple Log's 18 % grey (its curve at 0.18) back to 0.18 light,- // and to Rec. 709's video of it.+ let near = |a: [f32; 3], b: f32, e: f32| a.iter().all(|v| (v - b).abs() < e);+ // Apple Log's 18 % grey back to 0.18 light, and to Rec. 709's+ // video of it.let grey = 0.08550479 * (0.18f64 + 0.00964052).log2() + 0.69336945;let lin = apple_log([grey as f32; 3], false);- assert!(near(lin, [0.18; 3], 1e-4), "{lin:?}");+ assert!(near(lin, 0.18, 1e-4), "{lin:?}");let video = apple_log([grey as f32; 3], true);let expect = 1.099 * 0.18f32.powf(0.45) - 0.099;- assert!(near(video, [expect; 3], 1e-4), "{video:?}");- // As a Camera LUT at half strength: half way there.+ assert!(near(video, expect, 1e-4), "{video:?}");+ // As the Camera LUT at half strength: half way there.let v = values(&[- ("cameraLut", Value::Text(APPLE_LOG_TO_REC709.into())),- ("cameraStrength", Value::Num(vec![0.5])),+ ("lutEnable0", num(1.0)),+ ("lutFilename0", Value::Text(APPLE_LOG_TO_REC709.into())),+ ("lutGain0", num(0.5)),]);- let g = Settings::of(Values(&v)).grade();- let out = g.apply([grey as f32; 3]);- assert!(- near(out, [(grey as f32 + expect) / 2.0; 3], 1e-3),- "{out:?}"- );+ let out = Settings::of(Values(&v)).grade().apply([grey as f32; 3]);+ assert!(near(out, (grey as f32 + expect) / 2.0, 1e-3), "{out:?}");+ }++ /// The cases VEGAS rendered, in their order: each one's settings by+ /// BananaV's names (LUT files from `BV_GRADING_LUTS`).+ fn rendered_cases(luts: &str) -> Vec<(&'static str, Vec<(String, Value)>)> {+ let t = |s: &str| Value::Text(s.to_string());+ let lut = |file: &str| Value::Text(format!("{luts}/{file}"));+ let case = |name: &'static str, pairs: Vec<(&str, Value)>| {+ let v = pairs.into_iter().map(|(n, v)| (n.to_string(), v)).collect();+ (name, v)+ };+ vec![+ case("none", vec![]),+ case("default", vec![]),+ case(+ "lift",+ vec![+ ("liftR", num(0.3)),+ ("liftG", num(-0.2)),+ ("liftB", num(0.1)),+ ("liftY", num(0.05)),+ ],+ ),+ case(+ "gamma",+ vec![+ ("gammaR", num(1.5)),+ ("gammaG", num(0.7)),+ ("gammaB", num(2.5)),+ ("gammaY", num(1.2)),+ ],+ ),+ case(+ "gain",+ vec![+ ("gainR", num(1.4)),+ ("gainG", num(0.8)),+ ("gainB", num(1.1)),+ ("gainY", num(0.9)),+ ],+ ),+ case(+ "offset",+ vec![+ ("offsetR", num(0.1)),+ ("offsetG", num(-0.05)),+ ("offsetB", num(0.03)),+ ("offsetY", num(0.02)),+ ],+ ),+ case("rl shadows y", vec![("logWheelShadowsY", num(0.5))]),+ case(+ "rl mixed",+ vec![+ ("logWheelShadowsR", num(-0.3)),+ ("logWheelMidtonesG", num(0.4)),+ ("logWheelHighlightsB", num(-0.5)),+ ("logWheelOffsetY", num(0.1)),+ ("logWheelLowThreshold", num(0.2)),+ ("logWheelHighThreshold", num(0.6)),+ ],+ ),+ case(+ "levels",+ vec![+ ("inMinAdjust", num(0.1)),+ ("inMaxAdjust", num(0.9)),+ ("outMinAdjust", num(0.05)),+ ("outMaxAdjust", num(0.95)),+ ],+ ),+ case(+ "tone",+ vec![+ ("exposureLnAdjust", num(1.2)),+ ("brightnessAdjust", num(0.05)),+ ("contrastAdjust", num(0.3)),+ ("contrastCtrAdjust", num(0.4)),+ ("saturationAdjust", num(1.4)),+ ],+ ),+ case(+ "tone down",+ vec![+ ("exposureLnAdjust", num(-2.0)),+ ("contrastAdjust", num(-0.4)),+ ("saturationAdjust", num(0.5)),+ ],+ ),+ case("linear exposure", vec![("exposureAdjust", num(1.0))]),+ case(+ "white balance up",+ vec![+ ("temperatureAdjust", num(2000.0)),+ ("tintAdjust", num(30.0)),+ ],+ ),+ case(+ "white balance down",+ vec![+ ("temperatureAdjust", num(-3000.0)),+ ("tintAdjust", num(-50.0)),+ ],+ ),+ case(+ "hsl",+ vec![+ ("hueAdjust", num(0.1)),+ ("satAdjust", num(1.3)),+ ("valAdjust", num(0.9)),+ ],+ ),+ case(+ "color curves",+ vec![+ (+ "curveY",+ t(+ "3:0.00000:0.00000:-0.25000:-0.25000:0.15000:0.05000:0.50000:0.50000:-0.15000:-0.20000:0.15000:0.20000:1.00000:1.00000:-0.15000:-0.05000:0.25000:0.25000:",+ ),+ ),+ (+ "curveR",+ t(+ "2:0.00000:0.08000:-0.25000:-0.25000:0.25000:0.25000:1.00000:1.00000:-0.25000:-0.25000:0.25000:0.25000:",+ ),+ ),+ (+ "curveB",+ t(+ "2:0.00000:0.00000:-0.25000:-0.25000:0.25000:0.25000:1.00000:0.85000:-0.25000:-0.20000:0.25000:0.25000:",+ ),+ ),+ ],+ ),+ case(+ "hsl curves 1",+ vec![+ (+ "curveHvH",+ t(+ "5:-0.16667:0.50000:-0.12500:0.00000:0.08333:0.00000:0.00000:0.60000:-0.08333:0.00000:0.08333:0.00000:0.16667:0.50000:-0.08333:0.00000:0.12500:0.00000:0.83333:0.50000:-0.12500:0.00000:0.08333:0.00000:1.00000:0.60000:-0.08333:0.00000:0.08333:0.00000",+ ),+ ),+ (+ "curveHvS",+ t(+ "5:-0.50000:0.50000:-0.08333:0.00000:0.12500:0.00000:0.16667:0.50000:-0.12500:0.00000:0.08333:0.00000:0.33333:0.15000:-0.08333:0.00000:0.08333:0.00000:0.50000:0.50000:-0.08333:0.00000:0.12500:0.00000:1.16667:0.50000:-0.12500:0.00000:0.08333:0.00000",+ ),+ ),+ ],+ ),+ case(+ "hsl curves 2",+ vec![+ (+ "curveHvL",+ t(+ "5:-0.16667:0.50000:-0.08333:0.00000:0.12500:0.00000:0.50000:0.50000:-0.12500:0.00000:0.08333:0.00000:0.66667:0.30000:-0.08333:0.00000:0.08333:0.00000:0.83333:0.50000:-0.08333:0.00000:0.12500:0.00000:1.50000:0.50000:-0.12500:0.00000:0.08333:0.00000",+ ),+ ),+ (+ "curveSvL",+ t(+ "3:0.00000:0.50000:0.00000:0.00000:0.12500:0.00000:0.50000:0.60000:-0.12500:0.00000:0.12500:0.00000:1.00000:0.50000:-0.12500:0.00000:0.00000:0.00000:",+ ),+ ),+ (+ "curveLvS",+ t(+ "3:0.00000:0.50000:0.00000:0.00000:0.12500:0.00000:0.80000:0.20000:-0.12500:0.00000:0.10000:0.00000:1.00000:0.50000:-0.10000:0.00000:0.00000:0.00000:",+ ),+ ),+ ],+ ),+ case(+ "look lut",+ vec![+ ("lutEnable1", num(1.0)),+ ("lutFilename1", lut("Look/24.cube")),+ ("lutGain1", num(0.7)),+ ("lutInterpolation1", num(1.0)),+ ],+ ),+ case(+ "camera lut",+ vec![+ ("lutEnable0", num(1.0)),+ ("lutFilename0", lut("Camera/S-Log3_to_REC.709.cube")),+ ("lutGain0", num(1.0)),+ ("lutInterpolation0", num(0.0)),+ ],+ ),+ ]+ }++ /// The grade against VEGAS's own renders of the same cases, an 8-bit+ /// project with the graphics card on (not in the repository):+ /// `BV_GRADING_INPUT` the picture they started from, `BV_GRADING_RENDERS`+ /// a folder of the frames, three a case in the cases' order (the+ /// middle one measured), `BV_GRADING_LUTS` the LUTs' folder. Prints+ /// each case's largest and mean difference in 8-bit levels, with+ /// VEGAS's 8-bit steps and as BananaV renders (in floating point).+ #[test]+ #[ignore = "needs VEGAS's renders"]+ fn matches_vegas_renders() {+ let var = |name: &str| std::env::var(name).unwrap_or_else(|_| panic!("{name}"));+ let read = |path: &std::path::Path| {+ let bytes = std::fs::read(path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));+ bv_png::decode(&bytes).expect("a picture").to_rgba8()+ };+ let input = read(std::path::Path::new(&var("BV_GRADING_INPUT")));+ let mut frames: Vec<_> = std::fs::read_dir(var("BV_GRADING_RENDERS"))+ .expect("the renders")+ .filter_map(|e| e.ok().map(|e| e.path()))+ .filter(|p| p.extension().is_some_and(|x| x.eq_ignore_ascii_case("png")))+ .collect();+ frames.sort();+ let cases = rendered_cases(&var("BV_GRADING_LUTS"));+ assert!(frames.len() >= cases.len() * 3, "{} frames", frames.len());+ let pixels = input.len() / 4;+ // The largest and the mean difference of `grade` from `rendered`.+ let measure = |grade: Option<&Grade>, rendered: &[u8]| {+ let (mut max, mut sum) = (0u8, 0u64);+ for p in 0..pixels {+ let c = [input[p * 4], input[p * 4 + 1], input[p * 4 + 2]];+ let ours = grade.map_or(c, |g| {+ g.apply(c.map(|v| f32::from(v) / 255.0))+ .map(|v| (v * 255.0).round().clamp(0.0, 255.0) as u8)+ });+ let d = (0..3)+ .map(|i| ours[i].abs_diff(rendered[p * 4 + i]))+ .max()+ .unwrap_or(0);+ max = max.max(d);+ sum += u64::from(d);+ }+ (max, sum as f64 / pixels as f64)+ };+ let (mut steps, mut floats) = (0, 0);+ for (k, (name, values)) in cases.iter().enumerate() {+ let rendered = read(&frames[3 * k + 1]);+ let mut grade = Settings::of(Values(values)).grade();+ let none = *name == "none";+ let (a, am) = measure((!none).then_some(&grade), &rendered);+ grade.quantize = true;+ let (b, bm) = measure((!none).then_some(&grade), &rendered);+ eprintln!(+ "{name:20} 8-bit steps: max {b} mean {bm:.3} floating point: max {a} mean {am:.3}"+ );+ steps = steps.max(b);+ floats = floats.max(a);+ }+ assert!(steps <= 1 && floats <= 2, "{steps} {floats}");}}diff --git a/crates/effects/src/grading.rs b/crates/effects/src/grading.rsnew file mode 100644index 0000000..d8ff6f1--- /dev/null+++ b/crates/effects/src/grading.rs@@ -0,0 +1,1256 @@+//! Color Grading's work on a color, as VEGAS's Color Grading does it with+//! the graphics card on (its usual way): the Camera LUT; the HSL Curves,+//! one after another, each keyed on what the one before made; the first+//! part — White Balance, Levels, the RL Color Wheels and the Color+//! Curves —; the second — Lift, then Gain, Offset and Gamma by channel,+//! then by Y —; the third — Saturation, Exposure, Brightness, Contrast and+//! the panel's Exposure — and the HSL, always, after it; the Look LUT.+//! Between the steps the color is held within 0–1, as VEGAS's steps keep+//! it, so that a color taken past white in one step is cut there; the+//! HSL that ends the third part takes it as it is, and a color past white+//! there turns white.+//!+//! The curves — Color Curves', HSL Curves' and the RL Color Wheels' —+//! are Bézier curves made tables (511 entries; 383 for the RL wheels): at+//! each x the curve's parameter comes from a single Newton step off the+//! straight guess more often than not (the step stops once it moves less+//! than the curve's x's sum over 15), so the tables sit a little off the+//! exact curve, as VEGAS's do. The tables are read straight between their+//! entries, the input held within 0–1.++use bv_lut::{Interpolation, Lut};++/// A curve's point: where it is and its handles into and out of it (from+/// the point), as the curves' text holds them.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub struct Knot {+ pub x: f32,+ pub y: f32,+ pub ix: f32,+ pub iy: f32,+ pub ox: f32,+ pub oy: f32,+}++impl Knot {+ pub fn new(x: f32, y: f32, ix: f32, iy: f32, ox: f32, oy: f32) -> Knot {+ Knot {+ x,+ y,+ ix,+ iy,+ ox,+ oy,+ }+ }+}++/// An untouched curve's text: the effect leaves such a curve out.+pub const DEFAULT_CURVE: &str = "2:0.0:0.0:-0.2:0.0:0.2:0.2:1.0:1.0:-0.2:-0.2:0.2:0.0";++/// The points of a curve's text, `N:x:y:ix:iy:ox:oy:…` (as many points as+/// it holds whole).+pub fn parse_curve(text: &str) -> Vec<Knot> {+ let mut parts = text.split(':').filter(|s| !s.is_empty());+ let n = parts+ .next()+ .and_then(|s| s.trim().parse::<usize>().ok())+ .unwrap_or(0);+ let numbers: Vec<f32> = parts+ .map(|s| s.trim().parse::<f64>().unwrap_or(0.0) as f32)+ .collect();+ numbers+ .as_chunks::<6>()+ .0+ .iter()+ .take(n)+ .map(|v| Knot::new(v[0], v[1], v[2], v[3], v[4], v[5]))+ .collect()+}++/// A curve's text for `knots`, five decimals each, as the panel writes it.+pub fn curve_text(knots: &[Knot]) -> String {+ let mut s = format!("{}:", knots.len());+ for k in knots {+ for v in [k.x, k.y, k.ix, k.iy, k.ox, k.oy] {+ s.push_str(&format!("{:.5}:", v));+ }+ }+ s+}++/// Whether a curve's text is the untouched one (or nothing).+pub fn untouched(text: &str) -> bool {+ text.trim().is_empty() || text.trim() == DEFAULT_CURVE+}++/// The parameter at which the Bézier with x control values `x0`…`x3`+/// reaches `x`: Newton's steps off the straight guess, each kept within+/// 0–1, until one moves less than the x's sum over 15 (−1 when none+/// does in a hundred).+fn solve(x0: f64, x1: f64, x2: f64, x3: f64, x: f64) -> f64 {+ let mut t = (x - x0) / (x3 - x0);+ let close = (x0 + x1 + x2 + x3) / 15.0;+ for _ in 0..100 {+ let u = 1.0 - t;+ let f = u * u * u * x0 + 3.0 * t * u * u * x1 + 3.0 * t * t * u * x2 + t * t * t * x3 - x;+ let slope = 6.0 * t * u * (x2 - x1) + 3.0 * u * u * (x1 - x0) + 3.0 * t * t * (x3 - x2);+ let next = t - f / slope;+ if (next - t).abs() < close {+ return next;+ }+ t = next.clamp(0.0, 1.0);+ }+ -1.0+}++fn bezier(y0: f64, y1: f64, y2: f64, y3: f64, t: f64) -> f64 {+ let u = 1.0 - t;+ u * u * u * y0 + 3.0 * u * u * t * y1 + 3.0 * u * t * t * y2 + t * t * t * y3+}++/// One section's value at `x`: the parameter solved on the section's x's+/// (moved by `shift`), the y's at it.+fn section(a: &Knot, b: &Knot, x: f64, shift: f64) -> f64 {+ let (ax, bx) = (f64::from(a.x) + shift, f64::from(b.x) + shift);+ let t = solve(ax, ax + f64::from(a.ox), bx + f64::from(b.ix), bx, x);+ bezier(+ f64::from(a.y),+ f64::from(a.y) + f64::from(a.oy),+ f64::from(b.y) + f64::from(b.iy),+ f64::from(b.y),+ t,+ )+}++/// A curve's table: its value at x = 0, 1/(n − 1), 2/(n − 1)… while x+/// stays within 1 (the steps summed, so the last may fall short), the+/// curve moving on by at most one section an entry; `shift` (the RL+/// Offset wheel) slides the entries by about n·0.9875 times it, the end+/// they leave repeated.+pub(crate) fn table(knots: &[Knot], n: usize, shift: f32) -> Vec<f32> {+ let mut out = Vec::with_capacity(n);+ if knots.len() < 2 {+ return out;+ }+ let step = 1.0 / (n - 1) as f64;+ let (mut i, mut x) = (1usize, 0.0f64);+ loop {+ if f64::from(knots[i].x) < x {+ if i + 1 >= knots.len() {+ break;+ }+ i += 1;+ }+ out.push(section(&knots[i - 1], &knots[i], x, 0.0) as f32);+ x += step;+ if x > 1.0 {+ break;+ }+ }+ if shift.abs() > 1e-6 && !out.is_empty() {+ let v = (-(n as f64) * 0.9875 * f64::from(shift)) as f32;+ let m = if v < 0.0 {+ -(-v).round() as i64+ } else {+ v.round() as i64+ };+ let len = out.len() as i64;+ let old = out.clone();+ for (k, o) in out.iter_mut().enumerate() {+ let from = (k as i64 - m).clamp(0, len - 1);+ *o = old[from as usize];+ }+ }+ out+}++/// A hue curve's table when its points run past 0 and 1 (the turn's+/// copies): the same, its x's moved so that its first point is at 0.+fn turning_table(knots: &[Knot], n: usize) -> Vec<f32> {+ let mut out = Vec::with_capacity(n);+ let d = -f64::from(knots[0].x);+ let step = 1.0 / (n - 1) as f64;+ let (mut i, mut s) = (1usize, d);+ while s <= d + 1.0 {+ if f64::from(knots[i].x) + d < s {+ if i + 1 >= knots.len() {+ return out;+ }+ i += 1;+ }+ out.push(section(&knots[i - 1], &knots[i], s, d) as f32);+ s += step;+ }+ out+}++/// An HSL curve's table (`None` for a curve of fewer than two points):+/// one past 0 and 1 with a single point of its own is a flat line at its+/// height.+fn hsl_table(knots: &[Knot], n: usize) -> Option<Vec<f32>> {+ if knots.len() < 2 {+ return None;+ }+ let past = knots[0].x < 0.0 || knots[knots.len() - 1].x > 1.0;+ let t = if past && knots.len() == 3 {+ let m = knots[1];+ let ends = [+ Knot::new(0.0, m.y, 0.0, 0.0, 0.1, 0.0),+ m,+ Knot::new(1.0, m.y, -0.1, 0.0, 0.0, 0.0),+ ];+ table(&ends, n, 0.0)+ } else if past {+ turning_table(knots, n)+ } else {+ table(knots, n, 0.0)+ };+ (!t.is_empty()).then_some(t)+}++/// A table at `v`: straight between its entries, `v` held within 0–1; no+/// table changes nothing.+pub(crate) fn lookup(t: &[f32], v: f64) -> f64 {+ let n = t.len();+ if n == 0 {+ return v;+ }+ if v.is_nan() || v <= 0.0 {+ return f64::from(t[0]);+ }+ if v >= 1.0 {+ return f64::from(t[n - 1]);+ }+ let p = v * (n - 1) as f64;+ let i = p.floor() as usize;+ let f = p - i as f64;+ if i + 1 < n {+ f64::from(t[i]) + (f64::from(t[i + 1]) - f64::from(t[i])) * f+ } else {+ f64::from(t[i])+ }+}++// The RL Color Wheels: each channel's curve.++fn toward(len: f64, angle: f64) -> (f64, f64) {+ (len * angle.cos(), len * angle.sin())+}++/// The shadows' point(s), below the lower threshold `t`: the black raised+/// to s·t, its handle a third of the way toward (t, t); or, lowered, all+/// below x0 = t − max((s + 1)·t, 0.035) black.+fn shadows(s: f64, t: f64) -> Vec<Knot> {+ let mut k = Vec::new();+ if t == 0.0 {+ return k;+ }+ if s < 0.0 {+ let f = ((s + 1.0) * t).max(0.035);+ let x0 = (t - f) as f32;+ if x0 <= 0.0 {+ return k;+ }+ let third = x0 / 3.0;+ k.push(Knot::new(0.0, 0.0, 0.0, 0.0, third, 0.0));+ let x0d = f64::from(x0);+ let (ox, oy) = toward((t - x0d).hypot(t) / 3.0, t.atan2(t - x0d));+ k.push(Knot::new(x0, 0.0, -third, 0.0, ox as f32, oy as f32));+ } else {+ let y0 = (s * t) as f32;+ let (ox, oy) = toward(+ t.hypot(t - f64::from(y0)) / 3.0,+ (t - f64::from(y0)).atan2(t),+ );+ k.push(Knot::new(0.0, y0, 0.0, 0.0, ox as f32, oy as f32));+ }+ k+}++/// The midtones' point at (t1, t1): its handle in a third of the way back+/// to the point before, its handle out up (brighter), along (none) or+/// across (darker) by m.+fn midtones(k: &mut Vec<Knot>, m: f64, t1: f64, t2: f64) {+ let d = ((t2 - t1) * 0.9875).max(0.0);+ let (mut x, mut ix, mut iy) = (0.0, 0.0, 0.0);+ if let Some(p) = k.last() {+ x = t1;+ let (px, py) = (f64::from(p.x), f64::from(p.y));+ (ix, iy) = toward((px - t1).hypot(py - t1) / 3.0, (py - t1).atan2(px - t1));+ }+ let (ox, oy) = if m > 0.0 {+ (0.0, (d * m).max(1e-6))+ } else if m < 0.0 {+ ((m.abs() * d).max(1e-6), 0.0)+ } else {+ (d / 3.0, d / 3.0)+ };+ k.push(Knot::new(+ x as f32, t1 as f32, ix as f32, iy as f32, ox as f32, oy as f32,+ ));+}++/// The point at the upper threshold (t2, t2), when it is above the lower:+/// its handle in by m, none out.+fn upper(k: &mut Vec<Knot>, m: f64, t1: f64, t2: f64) {+ if t1 >= t2 {+ return;+ }+ let d = (t2 - t1) * 0.9875;+ let (ix, iy) = if m == 0.0 {+ (-(d / 3.0), -(d / 3.0))+ } else if m < 0.0 {+ (0.0, -(m.abs() * d).max(0.035))+ } else {+ (-(m.abs() * d).max(0.035), 0.0)+ };+ k.push(Knot::new(+ t2 as f32, t2 as f32, ix as f32, iy as f32, 0.0, 0.0,+ ));+}++/// The highlights, from the last point to white: (1, 1) as it is; raised,+/// white reached before x = 1 (or the last point's handle out bent toward+/// it when barely); lowered, white brought down. The point before keeps+/// its handle out as it was, but in the slight raise, as VEGAS's curve+/// does.+fn highlights(k: &mut Vec<Knot>, h: f64, t2: f64) {+ if t2 == 1.0 || k.is_empty() {+ return;+ }+ let last = k[k.len() - 1];+ let (lx, ly) = (f64::from(last.x), f64::from(last.y));+ if h == 0.0 {+ k.push(Knot::new(+ 1.0,+ 1.0,+ (lx - 1.0) as f32,+ (ly - 1.0) as f32,+ 0.0,+ 0.0,+ ));+ return;+ }+ let r = 1.0 - ly;+ if h > 0.0 {+ let f = (r * h - 0.035) as f32;+ if r * h < 0.035 {+ let n = k.len();+ k[n - 1].oy = (r / 3.0) as f32;+ k[n - 1].ox = ((1.0 - lx) / 3.0) as f32;+ } else {+ let x6 = 1.0 - f;+ k.push(Knot::new(+ x6,+ 1.0,+ (lx - f64::from(x6)) as f32,+ (ly - 1.0) as f32,+ 1.0 - x6,+ 0.0,+ ));+ }+ k.push(Knot::new(1.0, 1.0, -f.max(1e-6), 0.0, 0.0, 0.0));+ return;+ }+ let end = (1.0 - h.abs() * r) as f32;+ k.push(Knot::new(+ 1.0,+ end,+ (lx - 1.0) as f32,+ (ly - f64::from(end)) as f32,+ 0.0,+ 0.0,+ ));+}++/// An RL channel's curve: its shadows, midtones and highlights within the+/// thresholds.+pub(crate) fn rl_curve(s: f64, m: f64, h: f64, t1: f64, t2: f64) -> Vec<Knot> {+ let mut k = shadows(s, t1);+ midtones(&mut k, m, t1, t2);+ upper(&mut k, m, t1, t2);+ highlights(&mut k, h, t2);+ k+}++// Colors.++/// The Gamma wheel's value made the power's inverse: e^(…) on four+/// stretches (2.78 at 0, 1 at 1, 0.284 at 2…).+pub(crate) fn gamma_scale(g: f64) -> f64 {+ let g = f64::from(g as f32);+ let e = if g > 1.7 {+ g - (2.462 - g * 0.86)+ } else if g < 1.0 {+ if g >= 0.8 {+ g - (1.55 - g * 0.55)+ } else {+ g - (g * 0.1111 + 1.0211)+ }+ } else {+ g - 1.0+ };+ e.exp()+}++/// HSL (hue 0–1, saturation, lightness) of a color.+fn to_hsl(r: f64, g: f64, b: f64) -> [f64; 3] {+ let lo = r.min(g).min(b);+ let hi = r.max(g).max(b);+ let l = (lo + hi) * 0.5;+ if l.is_nan() || l <= 0.0 {+ return [0.0, 0.0, l];+ }+ let d = hi - lo;+ if d.is_nan() || d <= 0.0 {+ return [0.0, d, l];+ }+ let s = d / if l > 0.5 { (2.0 - hi) - lo } else { lo + hi };+ let (dr, dg, db) = ((hi - r) / d, (hi - g) / d, (hi - b) / d);+ let h = if r == hi {+ if g == lo {+ (db + 5.0) / 6.0+ } else {+ (1.0 - dg) / 6.0+ }+ } else if g != hi {+ if r == lo {+ (dg + 3.0) / 6.0+ } else {+ (5.0 - dr) / 6.0+ }+ } else if b == lo {+ (dr + 1.0) / 6.0+ } else {+ (3.0 - db) / 6.0+ };+ [h, s, l]+}++/// A color of HSL `h` (0–1, its whole turns dropped), `s`, `l`.+fn from_hsl(h: f64, s: f64, l: f64) -> [f64; 3] {+ let h = h - h.floor();+ let q = if l > 0.5 {+ (l + s) - l * s+ } else {+ (s + 1.0) * l+ };+ if q <= 0.0 {+ return [0.0; 3];+ }+ let i = (h * 6.0).trunc();+ let p = (l + l) - q;+ let f = (h * 6.0 - i) * (q - p);+ let (down, up) = (q - f, f + p);+ match i as i64 {+ 0 | 6 => [q, up, p],+ 1 => [down, q, p],+ 2 => [p, q, up],+ 3 => [p, down, q],+ 4 => [up, p, q],+ 5 => [q, p, down],+ _ => [0.0; 3],+ }+}++/// HSV (hue 0–1) of a color, as the hue curve's step works it out.+fn to_hsv(r: f64, g: f64, b: f64) -> [f64; 3] {+ let (p0, p1, p2, p3) = if g < b {+ (b, g, -1.0, 2.0 / 3.0)+ } else {+ (g, b, 0.0, -1.0 / 3.0)+ };+ let (q0, q1, q2, q3) = if p0 < r {+ (r, p1, p2, p0)+ } else {+ (p0, p1, p3, r)+ };+ let d = q0 - q3.min(q1);+ let e = 1e-10;+ [(q2 + (q3 - q1) / (6.0 * d + e)).abs(), d / (q0 + e), q0]+}++fn from_hsv(h: f64, s: f64, v: f64) -> [f64; 3] {+ [1.0, 2.0 / 3.0, 1.0 / 3.0].map(|k| {+ let f = h + k;+ let x = ((f - f.floor()) * 6.0 - 3.0).abs() - 1.0;+ v * (1.0 + (x.clamp(0.0, 1.0) - 1.0) * s)+ })+}++/// The lightness L* at which white stands (sRGB, D65): what the+/// lightness steps hold L* within.+const WHITE_L: f64 = 95.580666;++/// L*a*b* (D65) of a color's values (sRGB's curve).+fn to_lab(r: f64, g: f64, b: f64) -> [f64; 3] {+ let lin = |c: f64| {+ if c > 0.04045 {+ ((c + 0.055) / 1.055).abs().powf(2.4)+ } else {+ c / 12.92+ }+ };+ let (r, g, b) = (lin(r), lin(g), lin(b));+ let f = |t: f64| {+ if t > 0.008856 {+ t.abs().powf(0.3333)+ } else {+ 7.787 * t + 16.0 / 116.0+ }+ };+ let fx = f((r * 0.4124 + g * 0.3576 + b * 0.1805) / 0.95047);+ let fy = f(r * 0.2126 + g * 0.7152 + b * 0.0722);+ let fz = f((r * 0.0193 + g * 0.1192 + b * 0.9505) / 1.08883);+ [116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz)]+}++fn from_lab(l: f64, a: f64, bb: f64) -> [f64; 3] {+ let fy = (l + 16.0) / 116.0;+ let (fx, fz) = (a / 500.0 + fy, fy - bb / 200.0);+ let inv = |t: f64| {+ if t * t * t > 0.008856 {+ t * t * t+ } else {+ (t - 16.0 / 116.0) / 7.787+ }+ };+ let (x, y, z) = (inv(fx) * 0.95047, inv(fy), inv(fz) * 1.08883);+ let enc = |t: f64| {+ if t > 0.0031308 {+ 1.055 * t.abs().powf(1.0 / 2.4) - 0.055+ } else {+ 12.92 * t+ }+ };+ [+ enc(x * 3.2406 + y * -1.5372 + z * -0.4986),+ enc(x * -0.9689 + y * 1.8758 + z * 0.0415),+ enc(x * 0.0557 + y * -0.204 + z * 1.057),+ ]+}++// White Balance.++/// Robertson's isotemperature lines: reciprocal megakelvin, u, v, slope.+const ROBERTSON: [[f64; 4]; 31] = [+ [0.0, 0.18006, 0.26352, -0.24341],+ [10.0, 0.18066, 0.26589, -0.25479],+ [20.0, 0.18133, 0.26846, -0.26876],+ [30.0, 0.18208, 0.27119, -0.28539],+ [40.0, 0.18293, 0.27407, -0.30470],+ [50.0, 0.18388, 0.27709, -0.32675],+ [60.0, 0.18494, 0.28021, -0.35156],+ [70.0, 0.18611, 0.28342, -0.37915],+ [80.0, 0.18740, 0.28668, -0.40955],+ [90.0, 0.18880, 0.28997, -0.44278],+ [100.0, 0.19032, 0.29326, -0.47888],+ [125.0, 0.19462, 0.30141, -0.58204],+ [150.0, 0.19962, 0.30921, -0.70471],+ [175.0, 0.20525, 0.31647, -0.84901],+ [200.0, 0.21142, 0.32312, -1.0182],+ [225.0, 0.21807, 0.32909, -1.2168],+ [250.0, 0.22511, 0.33439, -1.4512],+ [275.0, 0.23247, 0.33904, -1.7298],+ [300.0, 0.24010, 0.34308, -2.0637],+ [325.0, 0.24702, 0.34655, -2.4681],+ [350.0, 0.25591, 0.34951, -2.9641],+ [375.0, 0.26400, 0.35200, -3.5814],+ [400.0, 0.27218, 0.35407, -4.3633],+ [425.0, 0.28039, 0.35577, -5.3762],+ [450.0, 0.28863, 0.35714, -6.7262],+ [475.0, 0.29685, 0.35823, -8.5955],+ [500.0, 0.30505, 0.35907, -11.324],+ [525.0, 0.31320, 0.35968, -15.628],+ [550.0, 0.32129, 0.36011, -23.325],+ [575.0, 0.32931, 0.36038, -40.770],+ [600.0, 0.33724, 0.36051, -116.45],+];++/// The chromaticity (x, y) of temperature `cct` (K) and `tint` (a 3000th+/// of the isotherm's normal), by Robertson's method.+pub(crate) fn chromaticity(cct: f64, tint: f64) -> (f64, f64) {+ let mired = 1e6 / cct;+ let mut i = 0;+ while !(mired < ROBERTSON[i + 1][0] || i == 29) {+ i += 1;+ }+ let (lo, hi) = (ROBERTSON[i], ROBERTSON[i + 1]);+ let w = (hi[0] - mired) / (hi[0] - lo[0]);+ let wh = 1.0 - w;+ let (nl, nh) = ((lo[3] * lo[3] + 1.0).sqrt(), (hi[3] * hi[3] + 1.0).sqrt());+ let du = (1.0 / nh) * wh + (1.0 / nl) * w;+ let dv = (hi[3] / nh) * wh + (lo[3] / nl) * w;+ let len = (dv * dv + du * du).sqrt();+ let v = wh * hi[2] + w * lo[2] + (dv / len) * tint * (-1.0 / 3000.0);+ let u = wh * hi[1] + w * lo[1] + (du / len) * tint * (-1.0 / 3000.0);+ let den = (u - v * 4.0) + 2.0;+ ((u * 1.5) / den, v / den)+}++type Matrix = [[f64; 3]; 3];++fn product(a: &Matrix, b: &Matrix) -> Matrix {+ std::array::from_fn(|r| std::array::from_fn(|c| (0..3).map(|k| a[r][k] * b[k][c]).sum()))+}++fn inverse(m: &Matrix) -> Matrix {+ let c = |r: usize, k: usize| {+ let (r1, r2) = ((r + 1) % 3, (r + 2) % 3);+ let (k1, k2) = ((k + 1) % 3, (k + 2) % 3);+ m[r1][k1] * m[r2][k2] - m[r1][k2] * m[r2][k1]+ };+ let det: f64 = (0..3).map(|k| m[0][k] * c(0, k)).sum();+ std::array::from_fn(|r| std::array::from_fn(|k| c(k, r) / det))+}++/// sRGB's (linear) to XYZ.+const RGB_XYZ: Matrix = [+ [0.412456, 0.357576, 0.180437],+ [0.212673, 0.715152, 0.072175],+ [0.019334, 0.119192, 0.950304],+];++/// The cone matrix White Balance adapts with: Bradford's, one term's sign+/// turned, which gives VEGAS's White Balance's colors.+const CONES: Matrix = [+ [0.8951, -0.7502, 0.0389],+ [0.2664, 1.7135, 0.0685],+ [-0.1614, 0.0367, 1.0296],+];++/// White Balance's matrix for `temperature` (K off D65's) and `tint`, as+/// it is applied to the colors' values raised to 2.4: the white the two+/// make over D65's, through the cones, its rows and columns swapped.+pub(crate) fn balance_matrix(temperature: f64, tint: f64) -> Matrix {+ let (x, y) = chromaticity(temperature + 6502.082197, tint + 9.766656463);+ let d: Matrix = [+ [(x / y) / 0.95047, 0.0, 0.0],+ [0.0, 1.0, 0.0],+ [0.0, 0.0, ((1.0 - x - y) / y) / 1.08883],+ ];+ let m = product(+ &product(&product(&product(&RGB_XYZ, &inverse(&CONES)), &d), &CONES),+ &inverse(&RGB_XYZ),+ );+ std::array::from_fn(|r| std::array::from_fn(|c| m[c][r]))+}++// The settings.++/// A wheel's color (red, green, blue) and its Y.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Wheel {+ pub rgb: [f64; 3],+ pub y: f64,+}++impl Wheel {+ pub const fn neutral(v: f64) -> Wheel {+ Wheel { rgb: [v; 3], y: v }+ }++ fn at(&self, v: f64) -> bool {+ self.rgb == [v; 3] && self.y == v+ }+}++/// A LUT row's table: a `.cube` file's, read straight or by tetrahedra,+/// or the Apple Log curve BananaV knows (to Rec. 709's linear light, or+/// to its video).+#[derive(Clone, Debug)]+pub enum LutTable {+ Cube {+ lut: std::sync::Arc<Lut>,+ tetrahedral: bool,+ },+ AppleLog {+ video: bool,+ },+}++/// A LUT row: its table, mixed in by `gain`.+#[derive(Clone, Debug)]+pub struct LutStep {+ pub table: LutTable,+ pub gain: f64,+}++/// Every value Color Grading works with (the curves as their text).+#[derive(Clone, Debug, PartialEq)]+pub struct Params {+ /// Lift, Gamma, Gain, Offset.+ pub wheels: [Wheel; 4],+ /// Shadows, Midtones, Highlights, Offset.+ pub rl: [Wheel; 4],+ /// The lower and the upper threshold.+ pub thresholds: [f64; 2],+ /// Red, green, blue, Y; then Hue vs Hue, Hue vs Saturation, Hue vs+ /// Luminance, Saturation vs Saturation, Saturation vs Luminance,+ /// Luminance vs Saturation.+ pub curves: [String; 10],+ pub saturation: f64,+ /// 2^E (not on the panel).+ pub exposure: f64,+ /// The panel's Exposure.+ pub exposure_ln: f64,+ pub brightness: f64,+ pub contrast: f64,+ pub contrast_center: f64,+ pub temperature: f64,+ pub tint: f64,+ /// Input min and max, output min and max.+ pub levels: [f64; 4],+ /// Hue, saturation, luminance.+ pub hsl: [f64; 3],+}++impl Default for Params {+ fn default() -> Params {+ Params {+ wheels: [+ Wheel::neutral(0.0),+ Wheel::neutral(1.0),+ Wheel::neutral(1.0),+ Wheel::neutral(0.0),+ ],+ rl: [Wheel::neutral(0.0); 4],+ thresholds: [0.25, 0.5],+ curves: std::array::from_fn(|_| DEFAULT_CURVE.to_string()),+ saturation: 1.0,+ exposure: 0.0,+ exposure_ln: 0.0,+ brightness: 0.0,+ contrast: 0.0,+ contrast_center: 0.5,+ temperature: 0.0,+ tint: 0.0,+ levels: [0.0, 1.0, 0.0, 1.0],+ hsl: [0.0, 1.0, 1.0],+ }+ }+}++/// The HSL Curves, in their order.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum HslCurve {+ HueHue,+ HueSat,+ HueLum,+ SatSat,+ SatLum,+ LumSat,+}++impl HslCurve {+ pub const ALL: [HslCurve; 6] = [+ HslCurve::HueHue,+ HslCurve::HueSat,+ HslCurve::HueLum,+ HslCurve::SatSat,+ HslCurve::SatLum,+ HslCurve::LumSat,+ ];+}++/// A CDL step: slope, offset and power per channel.+#[derive(Clone, Copy, Debug, PartialEq)]+pub(crate) struct Cdl {+ pub slope: [f64; 3],+ pub offset: [f64; 3],+ pub power: [f64; 3],+}++impl Cdl {+ fn apply(&self, v: f64, i: usize) -> f64 {+ let x = v * self.slope[i] + self.offset[i];+ if x > 0.0 { x.powf(self.power[i]) } else { x }+ }+}++/// The panel's Exposure: its table and what the color is scaled by+/// before it.+#[derive(Clone, Debug, PartialEq)]+pub(crate) struct ExposureCurve {+ pub table: Vec<f32>,+ pub pre: f64,+}++/// The settings ready to color pixels: what changes nothing is left out.+#[derive(Clone, Debug, Default)]+pub struct Grade {+ pub(crate) camera: Option<LutStep>,+ pub(crate) hsl_curves: Vec<(HslCurve, Vec<f32>)>,+ pub(crate) balance: Option<Matrix>,+ pub(crate) levels: Option<[f64; 4]>,+ pub(crate) rl_rgb: Option<[Vec<f32>; 3]>,+ pub(crate) rl_y: Option<Vec<f32>>,+ pub(crate) curves_rgb: Option<[Vec<f32>; 3]>,+ pub(crate) curve_y: Option<Vec<f32>>,+ pub(crate) lift: Option<[f64; 3]>,+ pub(crate) cdl: [Option<Cdl>; 2],+ pub(crate) saturation: Option<f64>,+ pub(crate) exposure: Option<f64>,+ pub(crate) brightness: Option<f64>,+ /// The contrast's scale and center.+ pub(crate) contrast: Option<(f64, f64)>,+ pub(crate) exposure_ln: Option<ExposureCurve>,+ /// Hue (turns), saturation and luminance: the HSL that ends the third+ /// part.+ pub(crate) hsl: [f64; 3],+ pub(crate) look: Option<LutStep>,+ /// Each step's color made 8-bit as well, as VEGAS's pictures between+ /// its steps are: for measuring against VEGAS.+ pub quantize: bool,+}++/// The tables' entries.+const ENTRIES: usize = 511;+const RL_ENTRIES: usize = 383;++impl Grade {+ /// `p` ready, with the Camera and Look LUTs (each `None` when off).+ pub fn new(p: &Params, camera: Option<LutStep>, look: Option<LutStep>) -> Grade {+ let curves: Vec<Vec<Knot>> = p.curves.iter().map(|t| parse_curve(t)).collect();+ let touched = |i: usize| !untouched(&p.curves[i]);+ let hsl_curves = HslCurve::ALL+ .iter()+ .enumerate()+ .filter(|&(i, _)| touched(4 + i))+ .filter_map(|(i, &kind)| Some((kind, hsl_table(&curves[4 + i], ENTRIES)?)))+ .collect();+ let balance = (p.temperature.abs() > 1e-6 || p.tint.abs() > 1e-6)+ .then(|| balance_matrix(p.temperature, p.tint));+ let levels = {+ let [a, mut b, c, mut d] = p.levels.map(|v| f64::from(v as f32));+ (a != 0.0 || b != 1.0 || c != 0.0 || d != 1.0).then(|| {+ if a == c && b == d && a == b {+ b += if b < 0.5 { -1e-6 } else { 1e-6 };+ } else {+ if (a - b).abs() <= 1e-6 {+ b += 1e-6;+ }+ if (c - d).abs() <= 1e-6 {+ d += 1e-6;+ }+ }+ [a, b, c, d]+ })+ };+ let [t1, t2] = p.thresholds.map(|v| f64::from(v as f32));+ let rl = |w: usize, c: usize| -> f64 {+ let wheel = &p.rl[w];+ f64::from((if c < 3 { wheel.rgb[c] } else { wheel.y }) as f32)+ };+ let rl_table = |c: usize| {+ table(+ &rl_curve(rl(0, c), rl(1, c), rl(2, c), t1, t2),+ RL_ENTRIES,+ rl(3, c) as f32,+ )+ };+ let any_rgb = (0..4).any(|w| (0..3).any(|c| rl(w, c) != 0.0));+ let any_y = (0..4).any(|w| rl(w, 3) != 0.0);+ let [lift, gamma, gain, offset] = p.wheels;+ let gamma_power = |g: f64| {+ let g = if g >= 1e-6 { g } else { 1e-6 };+ f64::from((1.0 / f64::from(gamma_scale(g) as f32)) as f32)+ };+ let first = (!gamma.at(1.0) || !gain.at(1.0) || !offset.at(0.0)).then(|| {+ let mut power = gamma.rgb.map(gamma_power);+ if (power[1] != 1.0 || power[2] != 1.0) && power[0] == 1.0 {+ power[0] = f64::from((power[0] - 1e-6) as f32);+ }+ if power[0] == 4.0 {+ power[0] = f64::from((power[0] + 1e-6) as f32);+ }+ Cdl {+ slope: gain.rgb,+ offset: offset.rgb.map(|o| o + offset.y),+ power,+ }+ });+ let second = (!gamma.at(1.0) || !gain.at(1.0)).then(|| Cdl {+ slope: [gain.y; 3],+ offset: [0.0; 3],+ power: [gamma_power(gamma.y); 3],+ });+ let exposure_ln = (f64::from(p.exposure_ln as f32).abs() > 0.0005).then(|| {+ let f = f64::from((f64::from(p.exposure_ln as f32) + 1.0) as f32);+ let f = if f <= 1.0 {+ f64::from(((f + 4.0) * 0.2) as f32)+ } else {+ f64::from(((f - 1.0) * 1.5 + 1.0) as f32)+ };+ let table = (0..ENTRIES)+ .rev()+ .map(|i| {+ let x = f64::from((i as f64 / ENTRIES as f64) as f32);+ (1.0 - f64::from(x.powf(f) as f32)) as f32+ })+ .collect();+ let pre = if f < 0.45 {+ 1.0 - ((0.45 - f) * 0.36).min(0.36)+ } else {+ 1.0+ };+ ExposureCurve { table, pre }+ });+ Grade {+ camera: camera.filter(|l| l.gain > 0.001),+ hsl_curves,+ balance,+ levels,+ rl_rgb: any_rgb.then(|| [rl_table(0), rl_table(1), rl_table(2)]),+ rl_y: any_y.then(|| rl_table(3)),+ curves_rgb: (touched(0) || touched(1) || touched(2))+ .then(|| std::array::from_fn(|c| table(&curves[c], ENTRIES, 0.0))),+ curve_y: touched(3).then(|| table(&curves[3], ENTRIES, 0.0)),+ lift: (!lift.at(0.0)).then(|| lift.rgb.map(|c| lift.y + c)),+ cdl: [first, second],+ saturation: (p.saturation != 1.0).then(|| f64::from(p.saturation as f32)),+ exposure: (p.exposure != 0.0)+ .then(|| f64::from(2f64.powf(f64::from(p.exposure as f32)) as f32)),+ brightness: (p.brightness.abs() > 0.0).then_some(p.brightness),+ contrast: (p.contrast.abs() > 1e-6).then(|| {+ let k = if p.contrast > 0.0 {+ 1.0 / (1.000001 - p.contrast) - 1.0+ } else {+ p.contrast+ };+ (k, p.contrast_center)+ }),+ exposure_ln,+ hsl: [+ f64::from(p.hsl[0] as f32),+ f64::from(p.hsl[1] as f32),+ f64::from(p.hsl[2] as f32),+ ],+ look: look.filter(|l| l.gain > 0.001),+ quantize: false,+ }+ }++ /// Whether it changes nothing (a color within 0–1).+ pub fn changes_nothing(&self) -> bool {+ self.camera.is_none()+ && self.hsl_curves.is_empty()+ && self.balance.is_none()+ && self.levels.is_none()+ && self.rl_rgb.is_none()+ && self.rl_y.is_none()+ && self.curves_rgb.is_none()+ && self.curve_y.is_none()+ && self.lift.is_none()+ && self.cdl == [None, None]+ && self.saturation.is_none()+ && self.exposure.is_none()+ && self.brightness.is_none()+ && self.contrast.is_none()+ && self.exposure_ln.is_none()+ && self.hsl == [0.0, 1.0, 1.0]+ && self.look.is_none()+ }++ /// A step's end: the color held within 0–1 (and, when measuring, made+ /// 8-bit as VEGAS's steps are: cut to 12 bits, then rounded).+ fn hold(&self, c: &mut [f64; 3]) {+ for v in c.iter_mut() {+ *v = v.clamp(0.0, 1.0);+ if self.quantize {+ *v = ((*v * 4096.0).floor() / 4096.0 * 255.0).round() / 255.0;+ }+ }+ }++ fn lut(&self, step: &Option<LutStep>, c: &mut [f64; 3]) {+ if let Some(l) = step {+ let out = match &l.table {+ LutTable::Cube { lut, tetrahedral } => {+ let how = if *tetrahedral {+ Interpolation::Tetrahedral+ } else {+ Interpolation::Linear+ };+ lut.apply(c.map(|v| v as f32), how)+ }+ LutTable::AppleLog { video } => {+ crate::color_grading::apple_log(c.map(|v| v as f32), *video)+ }+ };+ for (v, o) in c.iter_mut().zip(out) {+ *v += (f64::from(o) - *v) * l.gain;+ }+ self.hold(c);+ }+ }++ /// One HSL Curve on a color: its key from the color as it is.+ fn hsl_curve(kind: HslCurve, t: &[f32], [r, g, b]: [f64; 3]) -> [f64; 3] {+ let hsl = to_hsl(r, g, b);+ match kind {+ HslCurve::HueHue => {+ let [h, s, v] = to_hsv(r, g, b);+ let mut h = h - (lookup(t, h) - 0.5);+ if h < 0.0 {+ h += 1.0;+ }+ if h > 1.0 {+ h -= 1.0;+ }+ from_hsv(h, s, v)+ }+ HslCurve::HueSat | HslCurve::SatSat | HslCurve::LumSat => {+ let key = match kind {+ HslCurve::HueSat => hsl[0],+ HslCurve::SatSat => hsl[1],+ _ => to_lab(r, g, b)[0] / WHITE_L,+ };+ let z = lookup(t, key);+ from_hsl(hsl[0], (hsl[1] * 2.0 * z).clamp(0.0, 1.0), hsl[2])+ }+ HslCurve::HueLum | HslCurve::SatLum => {+ let lab = to_lab(r, g, b);+ let scale = if kind == HslCurve::HueLum {+ let w = lookup(t, hsl[0]);+ let mut weight = 0.0;+ if lab[0] > 30.0 {+ weight = if lab[0] > 60.0 {+ (-1.0 / 35.6) * lab[0] + 2.68+ } else {+ lab[0] / 30.0 - 1.0+ };+ }+ let chroma = if hsl[2] <= 0.5 {+ hsl[1].min(2.0 * hsl[2])+ } else {+ hsl[1].min(2.0 - 2.0 * hsl[2])+ } - 1.0;+ weight *= 1.75 / (1.0 + 18.0 * chroma * chroma);+ 1.0 - (1.0 - (2.25 * w - 0.125)) * weight+ } else {+ 2.0 * lookup(t, hsl[1])+ };+ from_lab((lab[0] * scale).clamp(0.0, WHITE_L), lab[1], lab[2])+ }+ }+ }++ /// A color (values, 0–1 in) through the grade.+ pub fn apply(&self, rgb: [f32; 3]) -> [f32; 3] {+ let mut c = rgb.map(f64::from);+ self.lut(&self.camera, &mut c);+ for (kind, t) in &self.hsl_curves {+ c = Grade::hsl_curve(*kind, t, c);+ self.hold(&mut c);+ }+ // The first part.+ if let Some(m) = &self.balance {+ let lin = c.map(|v| v.max(0.0).powf(2.4));+ c = std::array::from_fn(|i| {+ (m[i][0] * lin[0] + m[i][1] * lin[1] + m[i][2] * lin[2])+ .max(0.0)+ .powf(1.0 / 2.4)+ });+ }+ if let Some([a, b, lo, hi]) = self.levels {+ let k = (hi - lo) / (b - a);+ c = c.map(|v| lo + (v - a) * k);+ }+ if let Some(t) = &self.rl_rgb {+ c = std::array::from_fn(|i| lookup(&t[i], c[i]));+ }+ if let Some(t) = &self.rl_y {+ c = c.map(|v| lookup(t, v));+ }+ if let Some(t) = &self.curves_rgb {+ c = std::array::from_fn(|i| lookup(&t[i], c[i]));+ }+ if let Some(t) = &self.curve_y {+ c = c.map(|v| lookup(t, v));+ }+ self.hold(&mut c);+ // The second.+ if let Some(l) = self.lift {+ c = std::array::from_fn(|i| l[i] + c[i] * (1.0 - l[i]));+ }+ for cdl in self.cdl.iter().flatten() {+ c = std::array::from_fn(|i| cdl.apply(c[i], i));+ }+ self.hold(&mut c);+ // The third, and the HSL after it.+ if let Some(s) = self.saturation {+ let y = 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];+ c = c.map(|v| y + s * (v - y));+ }+ if let Some(k) = self.exposure {+ c = c.map(|v| v * k);+ }+ if let Some(b) = self.brightness {+ c = c.map(|v| v + b);+ }+ if let Some((k, center)) = self.contrast {+ c = c.map(|v| v + k * (v - center));+ }+ if let Some(e) = &self.exposure_ln {+ c = c.map(|v| lookup(&e.table, v * e.pre));+ }+ let [h, s, l] = to_hsl(c[0], c[1], c[2]);+ c = from_hsl(+ h + self.hsl[0],+ (s * self.hsl[1]).clamp(0.0, 1.0),+ (l * self.hsl[2]).clamp(0.0, 1.0),+ );+ self.hold(&mut c);+ self.lut(&self.look, &mut c);+ c.map(|v| v as f32)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn grade(set: impl FnOnce(&mut Params)) -> Grade {+ let mut p = Params::default();+ set(&mut p);+ Grade::new(&p, None, None)+ }++ /// 8-bit values through `g`.+ fn bytes(g: &Grade, c: [u8; 3]) -> [u8; 3] {+ g.apply(c.map(|v| f32::from(v) / 255.0))+ .map(|v| (v * 255.0).round().clamp(0.0, 255.0) as u8)+ }++ fn near(a: [u8; 3], b: [u8; 3], within: u8) -> bool {+ a.iter().zip(b).all(|(x, y)| x.abs_diff(y) <= within)+ }++ #[test]+ fn untouched_it_changes_nothing() {+ let g = grade(|_| {});+ assert!(g.changes_nothing());+ for c in [[0u8, 0, 0], [255, 255, 255], [17, 200, 99], [128, 128, 128]] {+ assert_eq!(bytes(&g, c), c);+ }+ }++ #[test]+ fn curves_read_and_write_their_text() {+ let k = parse_curve(DEFAULT_CURVE);+ assert_eq!(k.len(), 2);+ assert_eq!(k[1], Knot::new(1.0, 1.0, -0.2, -0.2, 0.2, 0.0));+ let text = curve_text(&k);+ assert!(text.starts_with("2:0.00000:0.00000:-0.20000:0.00000:0.20000:0.20000:"));+ assert_eq!(parse_curve(&text), k);+ assert!(untouched(DEFAULT_CURVE) && !untouched(&text));+ // The untouched curve's table is about the straight line: within+ // half an 8-bit step (its Newton step's parameter is not exact).+ let t = table(&k, ENTRIES, 0.0);+ assert!(t.len() >= ENTRIES - 1);+ for (i, v) in t.iter().enumerate() {+ assert!(+ (f64::from(*v) - i as f64 / 510.0).abs() < 0.5 / 255.0,+ "{i}: {v}"+ );+ }+ }++ #[test]+ fn the_gamma_wheel_scales_as_vegas() {+ let close = |a: f64, b: f64, e: f64| (a - b).abs() < e;+ assert!(close(gamma_scale(0.0), 0.360, 0.001));+ assert!(close(gamma_scale(1.0), 1.0, 1e-9));+ assert!(close(gamma_scale(2.0), 3.52, 0.01));+ assert!(close(gamma_scale(5.0), 933.0, 1.0));+ }++ #[test]+ fn white_balance_at_d65_is_neutral_and_warms_or_cools() {+ let (x, y) = chromaticity(6502.082197, 9.766656463);+ assert!(+ (x - 0.31273).abs() < 1e-4 && (y - 0.32902).abs() < 1e-4,+ "{x} {y}"+ );+ let m = balance_matrix(0.0, 0.0);+ for (r, row) in m.iter().enumerate() {+ for (c, v) in row.iter().enumerate() {+ let want = if r == c { 1.0 } else { 0.0 };+ assert!((v - want).abs() < 1e-4, "{m:?}");+ }+ }+ let m = balance_matrix(2000.0, 0.0);+ let diag = [m[0][0], m[1][1], m[2][2]];+ assert!(+ (diag[0] - 0.985).abs() < 0.01+ && (diag[1] - 1.001).abs() < 0.01+ && (diag[2] - 1.243).abs() < 0.01,+ "{diag:?}"+ );+ }++ #[test]+ fn rl_shadows_bend_the_highlights_as_vegas() {+ // Only Shadows Y at 0.5: VEGAS's grey ramp steps in the lights.+ let g = grade(|p| p.rl[0].y = 0.5);+ for (input, out) in [+ (139, 140),+ (140, 145),+ (191, 193),+ (192, 201),+ (227, 228),+ (228, 236),+ ] {+ let got = bytes(&g, [input; 3]);+ assert!(near(got, [out; 3], 1), "{input}: {got:?} not {out}");+ }+ }++ #[test]+ fn linear_exposure_takes_colors_past_white_to_white() {+ let g = grade(|p| p.exposure = 1.0);+ for (input, out) in [+ ([255, 0, 0], [255, 255, 255]),+ ([128, 0, 0], [255, 1, 1]),+ ([191, 96, 48], [255, 234, 223]),+ ] {+ let got = bytes(&g, input);+ assert!(near(got, out, 1), "{input:?}: {got:?} not {out:?}");+ }+ }++ #[test]+ fn hue_turns_and_lightness_curves_hold_white_below_its_l() {+ let g = grade(|p| p.hsl[0] = 1.0 / 3.0);+ assert!(near(bytes(&g, [255, 0, 0]), [0, 255, 0], 1));+ // A lightness curve on: white comes out 242, where the curve is+ // neutral.+ let flat = curve_text(&[+ Knot::new(0.0, 0.5, 0.0, 0.0, 0.25, 0.0),+ Knot::new(1.0, 0.5, -0.25, 0.0, 0.0, 0.0),+ ]);+ let g = grade(|p| p.curves[8] = flat.clone());+ assert!(+ near(bytes(&g, [255; 3]), [242; 3], 1),+ "{:?}",+ bytes(&g, [255; 3])+ );+ }++ #[test]+ fn levels_and_the_panels_exposure() {+ let g = grade(|p| p.levels = [0.1, 0.9, 0.05, 0.95]);+ // 0.5 stays (the middle maps to the middle), the input's ends to the+ // output's.+ assert!(near(bytes(&g, [128; 3]), [128; 3], 1));+ assert!(near(bytes(&g, [26; 3]), [13; 3], 1));+ // Exposure: the dark lifted more than the light, black and white+ // kept.+ let g = grade(|p| p.exposure_ln = 1.0);+ assert!(near(bytes(&g, [255; 3]), [255; 3], 0));+ let mid = bytes(&g, [64; 3])[0];+ assert!(mid > 90, "{mid}");+ }+}diff --git a/crates/effects/src/lib.rs b/crates/effects/src/lib.rsindex 55e383d..d1a4aaf 100644--- a/crates/effects/src/lib.rs+++ b/crates/effects/src/lib.rs@@ -126,6 +126,7 @@ mod glow;mod glsl;mod gradient_map;mod gradient_wipe;+pub mod grading;mod hsl_adjust;mod invert;mod kerning;@@ -233,7 +234,7 @@ static PLUGINS: [Shared; 120] = [// 2.0: Location counts the frame 0–1, VEGAS's way.plugin(crop::ID, 2, 0, crop::main),plugin(color_curves::ID, 1, 0, color_curves::main),- plugin(color_grading::ID, 1, 0, color_grading::main),+ plugin(color_grading::ID, 2, 0, color_grading::main),// 1.1: Offset counts 8-bit steps, VEGAS's way.plugin(color_corrector::ID, 1, 1, color_corrector::main),plugin(cookie_cutter::ID, 1, 0, cookie_cutter::main),diff --git a/crates/engine/src/accel.rs b/crates/engine/src/accel.rsindex 8c4b492..a76a53d 100644--- a/crates/engine/src/accel.rs+++ b/crates/engine/src/accel.rs@@ -156,8 +156,8 @@ impl Accel {GpuChoice::Named(n) => Some(n.as_str()),_ => None,};- let opened = Gpu::open(name).and_then(|g| g.warm_up().map(|()| g));- {+ let opened = Gpu::open(name);+ let gpu = {let mut st = me.state.lock().expect("acceleration");if st.serial != serial {return;@@ -165,12 +165,23 @@ impl Accel {match opened {Ok(g) => {st.status = GpuStatus::Ready(g.adapter().name.clone());- st.gpu = Some(g);+ st.gpu = Some(g.clone());+ Some(g)+ }+ Err(e) => {+ st.status = GpuStatus::Failed(e.to_string());+ None}- Err(e) => st.status = GpuStatus::Failed(e.to_string()),}- }+ };(me.repaint)();+ // Frames draw on the card from now on, waiting only for+ // the kernels they use; the others are compiled meanwhile.+ if let Some(g) = gpu+ && let Err(e) = g.warm_up()+ {+ me.failed(&g, &e);+ }});if spawned.is_err() {self.state.lock().expect("acceleration").status =diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rsindex a3682ae..f5f1c96 100644--- a/crates/engine/src/lib.rs+++ b/crates/engine/src/lib.rs@@ -43,6 +43,9 @@ pub use accel::{DecodeChoice, GpuChoice, GpuStatus, gpu_adapters};pub use audio_sync::{AudioSyncProgress, SyncOutcome};pub use beat_detection::BeatProgress;pub use bv_dvd::write_image as write_dvd_image;+/// The Color Grading effect's parameters, its wheels' points and its+/// curves' text, for the Color Grading window.+pub use bv_effects::color_grading;pub use bv_effects::color_grading::{APPLE_LOG_TO_LINEAR, APPLE_LOG_TO_REC709, Picker as ColorGradingPicker,};@@ -1108,6 +1111,7 @@ impl Engine {effects,path,format,+ tempo: p.settings.tempo,},self.repaint.clone(),));diff --git a/crates/engine/src/live.rs b/crates/engine/src/live.rsindex 707dfca..c5d203e 100644--- a/crates/engine/src/live.rs+++ b/crates/engine/src/live.rs@@ -26,6 +26,8 @@ pub struct LiveRoute {/// The device (empty: the default) and its channels (no input bus).pub input: RecordInput,pub chains: Vec<Vec<Effect>>,+ /// The project's tempo, for effects with tempo sync.+ pub tempo: bv_timeline::Tempo,/// Linear.pub gain: f32,/// −1 left to 1 right.@@ -299,6 +301,7 @@ impl Live {if state.chains.len() != route.chains.len()|| state.route.chains != route.chains|| state.route.input != route.input+ || state.route.tempo != route.tempo{state.chains = route.chains@@ -306,6 +309,7 @@ impl Live {.map(|effects| {let mut c = Chain::default();let list: Vec<&Effect> = effects.iter().collect();+ c.set_tempo(route.tempo);c.sync(&list, rate, channels, false);c})@@ -392,6 +396,7 @@ mod tests {bus: None,},chains: vec![vec![gain.clone()]],+ tempo: bv_timeline::Tempo::default(),gain: 1.0,pan: 0.0,active: true,diff --git a/crates/engine/src/nonrealtime.rs b/crates/engine/src/nonrealtime.rsindex 65a1c15..e89ca28 100644--- a/crates/engine/src/nonrealtime.rs+++ b/crates/engine/src/nonrealtime.rs@@ -71,6 +71,8 @@ pub(crate) struct NrtSource {pub effects: Vec<Effect>,pub path: PathBuf,pub format: NrtFormat,+ /// The project's tempo, for effects with tempo sync.+ pub tempo: bv_timeline::Tempo,}/// Media samples read at a time.@@ -156,6 +158,7 @@ fn run(src: &NrtSource, tick: &mut dyn FnMut(f64) -> bool) -> Result<(), String>effects: &src.effects,path: &src.path,format: src.format,+ tempo: src.tempo,};render(&sound, tick)}@@ -179,6 +182,7 @@ pub fn trim_sound(effects: &[],path,format: NrtFormat::Pcm24,+ tempo: bv_timeline::Tempo::default(),};let result = render(&sound, tick);if result.is_err() {@@ -197,6 +201,7 @@ struct Sound<'a> {effects: &'a [Effect],path: &'a Path,format: NrtFormat,+ tempo: bv_timeline::Tempo,}fn render(src: &Sound<'_>, tick: &mut dyn FnMut(f64) -> bool) -> Result<(), String> {@@ -206,9 +211,6 @@ fn render(src: &Sound<'_>, tick: &mut dyn FnMut(f64) -> bool) -> Result<(), Strilet channels = reader.channels().max(1);let at = |t: Tick| (t.as_seconds_f64() * f64::from(rate)).round() as i64;let (a, b) = (at(src.from), at(src.to));- let mut chain = Chain::default();- let effects: Vec<&Effect> = src.effects.iter().collect();- chain.sync(&effects, rate, channels, false);let file = std::fs::File::create(src.path).map_err(|e| e.to_string())?;let mut w = bv_wav::WavWriter::new(std::io::BufWriter::new(file),@@ -217,19 +219,108 @@ fn render(src: &Sound<'_>, tick: &mut dyn FnMut(f64) -> bool) -> Result<(), Strisrc.format.sample_format(),).map_err(|e| e.to_string())?;- let mut pos = a;- while pos < b {- let n = ((b - pos) as usize).min(BLOCK);- let buf = reader.read(pos, n).map_err(|e| e.to_string())?;- let mut planes: Vec<Vec<f32>> = (0..channels)- .map(|c| {+ // Effects that change the sound's length work on all of it at once:+ // then the sound is gathered first, and the chain runs a stretch at a+ // time between them.+ if src.effects.iter().any(|e| e.kind.works_offline()) {+ let mut planes: Vec<Vec<f32>> = vec![Vec::new(); channels];+ let mut pos = a;+ while pos < b {+ let n = ((b - pos) as usize).min(BLOCK);+ let buf = reader.read(pos, n).map_err(|e| e.to_string())?;+ for (c, plane) in planes.iter_mut().enumerate() {let mut v = buf.channels.get(c).cloned().unwrap_or_default();v.resize(n, 0.0);- v- })- .collect();- chain.process(&mut planes);+ plane.extend_from_slice(&v);+ }+ pos += n as i64;+ if !tick(n as f64 / f64::from(rate) / 2.0) {+ return Err(CANCELED.into());+ }+ }+ let mut stretch: Vec<&Effect> = Vec::new();+ let run = |stretch: &mut Vec<&Effect>, planes: &mut Vec<Vec<f32>>| {+ if stretch.is_empty() {+ return;+ }+ let mut chain = Chain::default();+ chain.set_tempo(src.tempo);+ chain.sync(stretch, rate, channels, false);+ // What the chain holds back comes out, its lateness taken back.+ let late = chain.latency();+ let len = planes.first().map_or(0, Vec::len);+ for p in planes.iter_mut() {+ p.resize(len + late, 0.0);+ }+ let mut at = 0;+ while at < len + late {+ let end = (at + BLOCK).min(len + late);+ let mut part: Vec<Vec<f32>> = planes.iter().map(|p| p[at..end].to_vec()).collect();+ chain.process(&mut part);+ for (p, q) in planes.iter_mut().zip(part) {+ p[at..end].copy_from_slice(&q);+ }+ at = end;+ }+ for p in planes.iter_mut() {+ p.drain(..late);+ }+ stretch.clear();+ };+ for e in src+ .effects+ .iter()+ .filter(|e| e.kind.is_audio() && e.enabled)+ {+ if e.kind.works_offline() {+ run(&mut stretch, &mut planes);+ if let Some(out) = bv_mixer::render_offline(e, rate, std::mem::take(&mut planes)) {+ planes = out;+ }+ } else {+ stretch.push(e);+ }+ }+ run(&mut stretch, &mut planes);w.write_planar(&planes).map_err(|e| e.to_string())?;+ if !tick((b - a) as f64 / f64::from(rate) / 2.0) {+ return Err(CANCELED.into());+ }+ w.finish().map_err(|e| e.to_string())?;+ return Ok(());+ }+ let mut chain = Chain::default();+ let effects: Vec<&Effect> = src.effects.iter().collect();+ chain.set_tempo(src.tempo);+ chain.sync(&effects, rate, channels, false);+ // Effects that answer late (FFT filters): the sound goes on through+ // them that much past its end, and as much is dropped from the start.+ let mut skip = chain.latency();+ let end = b + skip as i64;+ let mut pos = a;+ while pos < end {+ let n = ((end - pos) as usize).min(BLOCK);+ let mut planes: Vec<Vec<f32>> = if pos < b {+ let buf = reader+ .read(pos, n.min((b - pos) as usize))+ .map_err(|e| e.to_string())?;+ (0..channels)+ .map(|c| {+ let mut v = buf.channels.get(c).cloned().unwrap_or_default();+ v.resize(n, 0.0);+ v+ })+ .collect()+ } else {+ vec![vec![0.0; n]; channels]+ };+ chain.process(&mut planes);+ let drop = skip.min(n);+ skip -= drop;+ if drop < n {+ let kept: Vec<Vec<f32>> = planes.iter().map(|p| p[drop..].to_vec()).collect();+ w.write_planar(&kept).map_err(|e| e.to_string())?;+ }pos += n as i64;if !tick(n as f64 / f64::from(rate)) {return Err(CANCELED.into());@@ -238,3 +329,72 @@ fn render(src: &Sound<'_>, tick: &mut dyn FnMut(f64) -> bool) -> Result<(), Striw.finish().map_err(|e| e.to_string())?;Ok(())}++#[cfg(test)]+mod tests {+ use super::*;+ use bv_timeline::{EffectKind, Generator, ProjectSettings};++ /// Through effects that answer late (the Modern Equalizer, oversampled+ /// with its FIR filters), the sound written stays where it was and+ /// whole: their lateness is taken back, with and without an effect+ /// that changes the sound's length in the chain.+ #[test]+ fn late_effects_leave_the_sound_in_place() {+ let settings = ProjectSettings::default();+ let info = MediaInfo::generated(+ Generator::TestTone {+ frequency_hz: 1000.0,+ level_db: -6.0,+ },+ &settings,+ );+ let from = Tick::ZERO;+ let to = Tick::from_seconds_f64(0.25);+ let dir = std::env::temp_dir().join(format!("bv_nrt_late_{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let read = |path: &Path| {+ let mut r = bv_wav::WavReader::new(std::fs::File::open(path).unwrap()).unwrap();+ r.read_planar(0, 12_000).unwrap()+ };+ let plain = dir.join("plain.wav");+ fn sound<'a>(+ info: &'a MediaInfo,+ span: (Tick, Tick),+ effects: &'a [Effect],+ path: &'a Path,+ ) -> Sound<'a> {+ Sound {+ info,+ stream: 0,+ from: span.0,+ to: span.1,+ effects,+ path,+ format: NrtFormat::Float32,+ tempo: bv_timeline::Tempo::default(),+ }+ }+ render(&sound(&info, (from, to), &[], &plain), &mut |_| true).unwrap();+ let reference = read(&plain);+ let eq = Effect::new(EffectKind::ModernEq);+ let mut gapper = Effect::new(EffectKind::GapperSnipper);+ // As long as it was: its gaps off (the effect's own default inserts).+ gapper.enabled = false;+ for (name, chain) in [("eq", vec![eq.clone()]), ("eq_gather", vec![eq, gapper])] {+ let path = dir.join(format!("{name}.wav"));+ render(&sound(&info, (from, to), &chain, &path), &mut |_| true).unwrap();+ let got = read(&path);+ assert_eq!(got[0].len(), reference[0].len(), "{name}");+ let worst = got[0]+ .iter()+ .zip(&reference[0])+ .skip(200)+ .take(11_000)+ .map(|(a, b)| (a - b).abs())+ .fold(0f32, f32::max);+ assert!(worst < 1e-3, "{name}: {worst}");+ }+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rsindex 8748d92..94cfe0d 100644--- a/crates/engine/src/playback.rs+++ b/crates/engine/src/playback.rs@@ -676,6 +676,7 @@ fn mix_loop(stop: Arc<AtomicBool>,) {let mut pool = AudioPool::new();+ pool.set_live(true);let mut threads = (TRACK_BUFFER_MS.load(Ordering::Relaxed) > 0).then(TrackThreads::default);// The metronome's clicks at the project's rate, made once.let mut clicks: Option<ClicksAt> = None;diff --git a/crates/engine/src/plugins.rs b/crates/engine/src/plugins.rsindex df5d197..f42a66b 100644--- a/crates/engine/src/plugins.rs+++ b/crates/engine/src/plugins.rs@@ -816,8 +816,10 @@ impl ClipSource for Temporal {);if let Some(f) = self.framing {let at = self.clip.start + local.unwrap_or(owner);- let tf = self.clip.transform_at(at);- img = bv_render::place_par(&img, frame.0, frame.1, &tf, f.quality, f.par);+ let place = f+ .place+ .at(&self.clip, at, [f64::from(frame.0), f64::from(frame.1)]);+ img = bv_render::place_box(&img, frame.0, frame.1, &place, f.quality);self.chain(&effects,&mut img,@@ -2422,89 +2424,120 @@ pub(crate) mod tests {_ => None,}).expect("a look's table");- let point = |x: f64, y: f64| bv_core::curve::CurvePoint::new(x, y);+ let text = |t: &str| PluginValue::Text(t.to_string());let grading: Vec<(&str, Vec<(&str, PluginValue)>)> = vec![("color grading wheels and tone",vec![- ("lift", num(&[0.05, 0.0, -0.02])),+ ("liftR", num(&[0.05])),+ ("liftB", num(&[-0.02])),("liftY", num(&[0.02])),- ("gamma", num(&[1.1, 1.0, 0.9])),- ("gammaY", num(&[1.05])),- ("gain", num(&[1.05, 1.0, 0.95])),+ ("gammaR", num(&[1.3])),+ ("gammaB", num(&[0.8])),+ ("gammaY", num(&[1.1])),+ ("gainR", num(&[1.05])),+ ("gainB", num(&[0.95])),("gainY", num(&[1.1])),- ("offset", num(&[0.01, 0.0, 0.0])),- ("brightness", num(&[0.03])),- ("contrast", num(&[0.2])),- ("saturation", num(&[1.3])),- ("logExposure", num(&[0.5])),- ("temperature", num(&[0.3])),- ("tint", num(&[-0.2])),- ("hue", num(&[20.0])),- ("hslSaturation", num(&[1.2])),- ("luminance", num(&[0.02])),+ ("offsetR", num(&[0.01])),+ ("offsetY", num(&[-0.01])),+ ("brightnessAdjust", num(&[0.03])),+ ("contrastAdjust", num(&[0.2])),+ ("contrastCtrAdjust", num(&[0.45])),+ ("saturationAdjust", num(&[1.3])),+ ("exposureLnAdjust", num(&[0.5])),+ ("exposureAdjust", num(&[0.2])),+ ("temperatureAdjust", num(&[1200.0])),+ ("tintAdjust", num(&[-20.0])),+ ("hueAdjust", num(&[0.05])),+ ("satAdjust", num(&[1.2])),+ ("valAdjust", num(&[0.95])),],),("color grading rl wheels and levels",vec![- ("shadows", num(&[0.05, 0.0, 0.0])),- ("midtones", num(&[0.0, 0.03, 0.0])),- ("highlights", num(&[0.0, 0.0, 0.04])),- ("rlOffsetY", num(&[0.01])),- ("inputBlack", num(&[0.05])),- ("inputWhite", num(&[0.9])),- ("outputMin", num(&[0.02])),- ("outputMax", num(&[0.95])),+ ("logWheelShadowsR", num(&[0.3])),+ ("logWheelShadowsY", num(&[-0.2])),+ ("logWheelMidtonesG", num(&[0.25])),+ ("logWheelHighlightsB", num(&[-0.4])),+ ("logWheelHighlightsY", num(&[0.3])),+ ("logWheelOffsetY", num(&[0.05])),+ ("logWheelLowThreshold", num(&[0.2])),+ ("logWheelHighThreshold", num(&[0.6])),+ ("inMinAdjust", num(&[0.05])),+ ("inMaxAdjust", num(&[0.9])),+ ("outMinAdjust", num(&[0.02])),+ ("outMaxAdjust", num(&[0.95])),],),("color grading curves",vec![(- "curves",- PluginValue::Curves(vec![- vec![point(0.0, 0.0), point(0.5, 0.6), point(1.0, 1.0)],- vec![point(0.0, 0.05), point(1.0, 0.95)],- vec![point(0.0, 0.0), point(1.0, 1.0)],- vec![point(0.0, 0.0), point(0.3, 0.2), point(1.0, 1.0)],- ]),+ "curveR",+ text("2:0.0:0.08:-0.25:-0.25:0.25:0.25:1.0:1.0:-0.25:-0.25:0.25:0.25:"),),(- "hslCurves",- PluginValue::Curves(vec![- vec![point(0.0, 0.1), point(0.5, -0.2), point(1.0, 0.1)],- vec![point(0.0, 0.0), point(1.0, 0.0)],- vec![point(0.0, 0.0), point(0.6, 0.2), point(1.0, 0.0)],- vec![point(0.0, 0.0), point(1.0, 0.3)],- vec![point(0.0, 0.0), point(1.0, 0.0)],- vec![point(0.0, -0.1), point(1.0, 0.1)],- ]),+ "curveB",+ text("2:0.0:0.0:-0.25:-0.25:0.25:0.25:1.0:0.85:-0.25:-0.2:0.25:0.25:"),+ ),+ (+ "curveY",+ text(+ "3:0.0:0.0:-0.25:-0.25:0.15:0.05:0.5:0.5:-0.15:-0.2:0.15:0.2:1.0:1.0:-0.15:-0.05:0.25:0.25:",+ ),+ ),+ (+ "curveHvH",+ text(+ "5:-0.16667:0.5:-0.125:0.0:0.08333:0.0:0.0:0.6:-0.08333:0.0:0.08333:0.0:0.16667:0.5:-0.08333:0.0:0.125:0.0:0.83333:0.5:-0.125:0.0:0.08333:0.0:1.0:0.6:-0.08333:0.0:0.08333:0.0",+ ),+ ),+ (+ "curveHvL",+ text(+ "5:-0.16667:0.5:-0.08333:0.0:0.125:0.0:0.5:0.5:-0.125:0.0:0.08333:0.0:0.66667:0.3:-0.08333:0.0:0.08333:0.0:0.83333:0.5:-0.08333:0.0:0.125:0.0:1.5:0.5:-0.125:0.0:0.08333:0.0",+ ),+ ),+ (+ "curveSvS",+ text(+ "3:0.0:0.5:0.0:0.0:0.125:0.0:0.5:0.65:-0.125:0.0:0.125:0.0:1.0:0.5:-0.125:0.0:0.0:0.0:",+ ),+ ),+ (+ "curveLvS",+ text(+ "3:0.0:0.5:0.0:0.0:0.125:0.0:0.8:0.2:-0.125:0.0:0.1:0.0:1.0:0.5:-0.1:0.0:0.0:0.0:",+ ),),],),("color grading apple log",vec![+ ("lutEnable0", num(&[1.0])),(- "cameraLut",+ "lutFilename0",PluginValue::Text(bv_effects::color_grading::APPLE_LOG_TO_REC709.into()),),- ("cameraStrength", num(&[0.7])),+ ("lutGain0", num(&[0.7])),],),("color grading looks",vec![+ ("lutEnable0", num(&[1.0])),(- "cameraLut",+ "lutFilename0",PluginValue::Text(bv_effects::color_grading::APPLE_LOG_TO_LINEAR.into()),),- ("cameraStrength", num(&[0.4])),- ("lookLut", PluginValue::Text(look.clone())),- ("lookStrength", num(&[0.8])),- ("lookTetrahedral", num(&[0.0])),- ("contrast", num(&[0.1])),+ ("lutGain0", num(&[0.4])),+ ("lutEnable1", num(&[1.0])),+ ("lutFilename1", PluginValue::Text(look.clone())),+ ("lutGain1", num(&[0.8])),+ ("lutInterpolation1", num(&[1.0])),+ ("contrastAdjust", num(&[0.1])),],),];@@ -2694,8 +2727,9 @@ pub(crate) mod tests {smoothness: 0.0,};let num = |v: &[f64]| PluginValue::Num(v.to_vec());- let c = p.clip_mut(clip).unwrap();- c.transform_keys = vec![key(0.0, -0.4), key(2.0, 0.4)];+ p.set_clip_framing_keys(clip, &[key(0.0, -0.4), key(2.0, 0.4)])+ .unwrap();+let mut runs = Vec::new();for (name, values) in [("fixed", vec![("blurAmount", num(&[12.0]))]),@@ -2778,7 +2812,8 @@ pub(crate) mod tests {smoothness: 0.0,};let num = |v: &[f64]| PluginValue::Num(v.to_vec());- p.clip_mut(clip).unwrap().transform_keys = vec![key(0.0, -0.4), key(2.0, 0.4)];+ p.set_clip_framing_keys(clip, &[key(0.0, -0.4), key(2.0, 0.4)])+ .unwrap();// Histograms of 60 frames, their levels drifting.let counted: Vec<(f64, [Vec<u64>; 3])> = (0..60).map(|f| {@@ -2956,7 +2991,8 @@ pub(crate) mod tests {curve: KeyCurve::default(),smoothness: 0.0,};- p.clip_mut(clip).unwrap().transform_keys = vec![key(0.0, -0.4), key(4.0, 0.4)];+ p.set_clip_framing_keys(clip, &[key(0.0, -0.4), key(4.0, 0.4)])+ .unwrap();let num = |v: &[f64]| PluginValue::Num(v.to_vec());// Frame 31 at half speed: the source's 15.5.let rate = settings.frame_rate.as_f64();diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rsindex 0e3b4e0..1cea7ad 100644--- a/crates/engine/src/preview.rs+++ b/crates/engine/src/preview.rs@@ -948,6 +948,7 @@ impl Worker {self.pool.set_patience(None);let (frame, took, waited) = self.draw(req, t);self.trace_took("ahead", t, frame.exact, took, waited);+ let late;{let mut st = lock(shared);let key = req.key(t);@@ -971,6 +972,9 @@ impl Worker {);}st.keep(&frame);+ // A frame already due shows now; one drawn ahead of its time+ // when the interface paints for it (it does as frames are due).+ late = st.asked.as_ref().is_none_or(|a| frame.time <= a.time);// Still wanted: of the project and size asked for, after what// shows.let wanted = st@@ -987,7 +991,9 @@ impl Worker {}}shared.1.notify_all();- repaint();+ if late {+ repaint();+ }// The events coming within a few seconds get their readers now (a// long recording takes a while to open and to seek in), and their// plug-ins, the other threads' too.diff --git a/crates/engine/src/record.rs b/crates/engine/src/record.rsindex ea09c2b..3544aa3 100644--- a/crates/engine/src/record.rs+++ b/crates/engine/src/record.rs@@ -67,6 +67,8 @@ pub struct RecordTake {/// The effects the signal goes through before it is written (an input/// bus's: a wet recording).pub effects: Vec<bv_timeline::Effect>,+ /// The project's tempo, for effects with tempo sync.+ pub tempo: bv_timeline::Tempo,}/// A file recorded into a track.@@ -264,6 +266,7 @@ impl Recorder {let chain = (!t.effects.is_empty()).then(|| {let mut c = bv_mixer::dsp::Chain::default();let list: Vec<&bv_timeline::Effect> = t.effects.iter().collect();+ c.set_tempo(t.tempo);c.sync(&list, rate, channels, false);c});diff --git a/crates/engine/src/render/smart.rs b/crates/engine/src/render/smart.rsindex c39077e..31c2855 100644--- a/crates/engine/src/render/smart.rs+++ b/crates/engine/src/render/smart.rs@@ -102,7 +102,7 @@ pub(crate) fn unedited(project: &Project, t: Tick, pass: &Passable) -> Option<(Slet plain_event = layer.level >= 1.0&& layer.fade.is_none()&& m.effects.is_empty()- && m.transform.is_identity()+ && m.clip.pan_crop.is_default()&& m.blend.is_none()&& m.deinterlace.is_none()&& m.clip.mask.is_none()diff --git a/crates/engine/src/thumbs.rs b/crates/engine/src/thumbs.rsindex 7d262d5..f0a4b9c 100644--- a/crates/engine/src/thumbs.rs+++ b/crates/engine/src/thumbs.rs@@ -511,6 +511,113 @@ pub(crate) mod peak_files {})}+ /// Media whose other editor's peak file is passed over: Rebuild Audio+ /// Peaks makes BananaV's own.+ static PASSED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());++ /// A DOS date and time (`time << 16 | date`, two seconds apart) as+ /// seconds since 1970.+ pub(crate) fn dos_seconds(v: u32) -> Option<i64> {+ let (time, date) = (i64::from(v >> 16), i64::from(v & 0xFFFF));+ let (year, month, day) = (1980 + (date >> 9), (date >> 5) & 0xF, date & 0x1F);+ if !(1..=12).contains(&month) || day == 0 {+ return None;+ }+ // Days since 1970 of the Gregorian date.+ let y = if month <= 2 { year - 1 } else { year };+ let era = y.div_euclid(400);+ let yoe = y - era * 400;+ let doy = (153 * ((month + 9) % 12) + 2) / 5 + day - 1;+ let days = era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468;+ let (h, m, sec) = (time >> 11, (time >> 5) & 0x3F, (time & 0x1F) * 2);+ Some(days * 86_400 + h * 3600 + m * 60 + sec)+ }++ /// The peak file another editor leaves beside a media file (`tom.wav.sfk`+ /// or `tom.sfk` for `tom.wav`), as BananaV's waveform of `per_second` peaks a+ /// second. Its header of 64 bytes: `SFPK`, version 1, the header's+ /// size, the media's last change in local time as DOS writes it, the+ /// bits of each value (8 or 16), the channels, the samples each peak+ /// covers and the media's samples per channel, then its last change+ /// again in UTC; after it, block by block and channel by channel, the+ /// minimum and the maximum. A file made from another version of the+ /// media, or of other channels, is not used.+ pub(crate) fn read_sfk(+ media: &str,+ rate: u32,+ channels: usize,+ per_second: u32,+ ) -> Option<Waveform> {+ if PASSED.lock().ok()?.iter().any(|m| m == media) || rate == 0 || per_second == 0 {+ return None;+ }+ let data = std::fs::read(format!("{media}.sfk"))+ .or_else(|_| std::fs::read(std::path::Path::new(media).with_extension("sfk")))+ .ok()?;+ let u32_at = |i: usize| -> Option<u32> {+ Some(u32::from_le_bytes(data.get(i..i + 4)?.try_into().ok()?))+ };+ let u64_at = |i: usize| -> Option<u64> {+ Some(u64::from_le_bytes(data.get(i..i + 8)?.try_into().ok()?))+ };+ if data.get(..4)? != b"SFPK" || u32_at(4)? != 1 {+ return None;+ }+ let changed = std::fs::metadata(media)+ .ok()?+ .modified()+ .ok()?+ .duration_since(std::time::UNIX_EPOCH)+ .ok()?+ .as_secs() as i64;+ if (dos_seconds(u32_at(0x24)?)? - changed).abs() > 2 {+ return None;+ }+ let header = u32_at(8)? as usize;+ let width = match u32_at(0x10)? {+ 8 => 1,+ 16 => 2,+ _ => return None,+ };+ let per_peak = u64::from(u32_at(0x18)?);+ let samples = u64_at(0x1C)?;+ if u32_at(0x14)? as usize != channels || channels == 0 || per_peak == 0 {+ return None;+ }+ let blocks = samples.div_ceil(per_peak) as usize;+ let body = data.get(header..header.checked_add(blocks * channels * 2 * width)?)?;+ let value = |i: usize| match width {+ 1 => f32::from(body[i] as i8) / 128.0,+ _ => f32::from(i16::from_le_bytes([body[i], body[i + 1]])) / 32768.0,+ };+ let rate = u64::from(rate);+ let per_second = u64::from(per_second);+ let buckets = (samples * per_second).div_ceil(rate) as usize;+ let mut peaks = vec![Vec::with_capacity(buckets); channels];+ for k in 0..buckets as u64 {+ let from = k * rate / per_second;+ let to = ((k + 1) * rate / per_second).clamp(from + 1, samples.max(from + 1));+ let (b0, b1) = (+ (from / per_peak) as usize,+ (to.div_ceil(per_peak) as usize).min(blocks),+ );+ for (c, p) in peaks.iter_mut().enumerate() {+ let (mut lo, mut hi) = (0.0f32, 0.0f32);+ for b in b0..b1 {+ let at = (b * channels + c) * 2 * width;+ lo = lo.min(value(at));+ hi = hi.max(value(at + width));+ }+ p.push((lo, hi));+ }+ }+ Some(Waveform {+ per_second: per_second as u32,+ peaks,+ repeats: false,+ })+ }+/// Writes the peak file, unless the preferences say not to (or the/// folder takes no files: the waveform then lives in memory only).pub(crate) fn write(media: &str, stream: u16, w: &Waveform) {@@ -553,11 +660,17 @@ pub(crate) mod peak_files {}}- /// Deletes a media file's peak files (they are made anew).+ /// Deletes a media file's peak files (they are made anew, another+ /// editor's beside it passed over).pub(crate) fn delete(media: &str) {for stream in 0..16 {let _ = std::fs::remove_file(path(media, stream));}+ if let Ok(mut passed) = PASSED.lock()+ && !passed.iter().any(|m| m == media)+ {+ passed.push(media.to_string());+ }}}@@ -570,6 +683,12 @@ fn compute_waveform(info: &MediaInfo, stream: u16) -> Option<Waveform> {if let Some(w) = file.and_then(|f| peak_files::read(f, stream)) {return Some(w);}+ // The first stream's peaks another editor left beside the file.+ if let (Some(f), Some(a), 0) = (file, info.audio.as_ref(), stream)+ && let Some(w) = peak_files::read_sfk(f, a.sample_rate.0, a.channels.into(), PER_SECOND)+ {+ return Some(w);+ }let w = compute_peaks(info, stream, PER_SECOND)?;if let Some(f) = file {peak_files::write(f, stream, &w);@@ -653,6 +772,106 @@ mod tests {let _ = std::fs::remove_dir_all(&dir);}+ #[test]+ fn dos_stamps_read_as_seconds_since_1970() {+ // 2026-11-03 14:53:26, as the other editor wrote it in UTC.+ assert_eq!(peak_files::dos_seconds(0x76AD_5D63), Some(1_793_717_606));+ // 1980-01-01 00:00:00, DOS's first day.+ assert_eq!(peak_files::dos_seconds(0x0000_0021), Some(315_532_800));+ assert_eq!(peak_files::dos_seconds(0), None, "no month");+ }++ #[test]+ fn another_editors_peaks_are_read_beside_the_media() {+ let dir = std::env::temp_dir().join(format!("bananav-sfk-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let media = dir.join("tone.wav");+ std::fs::write(&media, [0u8; 64]).unwrap();+ // The media changed at 2026-11-03 14:53:26 UTC.+ let when = std::time::UNIX_EPOCH + std::time::Duration::from_secs(1_793_717_606);+ std::fs::File::options()+ .write(true)+ .open(&media)+ .unwrap()+ .set_modified(when)+ .unwrap();+ // One second of 48 kHz stereo, a peak every 256 samples: 188 blocks,+ // block b reaching -10 b and 10 b + the channel.+ let sfk = |stamp: u32, channels: u32| {+ let mut d = Vec::new();+ d.extend_from_slice(b"SFPK");+ for v in [1u32, 0x40, 0x5EAD_5D63, 16, channels, 256] {+ d.extend_from_slice(&v.to_le_bytes());+ }+ d.extend_from_slice(&48_000u64.to_le_bytes());+ d.extend_from_slice(&stamp.to_le_bytes());+ d.resize(0x40, 0);+ for b in 0..188i16 {+ for c in 0..channels as i16 {+ d.extend_from_slice(&(-10 * b).to_le_bytes());+ d.extend_from_slice(&(10 * b + c).to_le_bytes());+ }+ }+ d+ };+ let path = dir.join("tone.sfk");+ std::fs::write(&path, sfk(0x76AD_5D63, 2)).unwrap();+ let name = media.to_string_lossy().to_string();+ let w = peak_files::read_sfk(&name, 48_000, 2, 100).expect("read");+ assert_eq!(+ (w.per_second, w.peaks.len(), w.peaks[0].len()),+ (100, 2, 100)+ );+ let v = |n: i16| f32::from(n) / 32768.0;+ // The first hundredth (480 samples) spans blocks 0 and 1.+ assert_eq!(w.peaks[0][0], (v(-10), v(10)));+ assert_eq!(w.peaks[1][0], (v(-10), v(11)));+ // The last ends with block 187.+ assert_eq!(w.peaks[0][99], (v(-1870), v(1870)));+ // Named after the whole file, as the other editor names them too.+ std::fs::remove_file(&path).unwrap();+ let whole = dir.join("tone.wav.sfk");+ std::fs::write(&whole, sfk(0x76AD_5D63, 2)).unwrap();+ assert!(peak_files::read_sfk(&name, 48_000, 2, 100).is_some());+ std::fs::remove_file(&whole).unwrap();+ std::fs::write(&path, sfk(0x76AD_5D63, 2)).unwrap();+ // Another channel count, or another version of the media: not used.+ assert!(peak_files::read_sfk(&name, 48_000, 1, 100).is_none());+ std::fs::write(&path, sfk(0x76AD_5D73, 2)).unwrap();+ assert!(peak_files::read_sfk(&name, 48_000, 2, 100).is_none());+ // Rebuild Audio Peaks passes it over.+ std::fs::write(&path, sfk(0x76AD_5D63, 2)).unwrap();+ peak_files::delete(&name);+ assert!(peak_files::read_sfk(&name, 48_000, 2, 100).is_none());+ let _ = std::fs::remove_dir_all(&dir);+ }++ /// `BV_SFK_SAMPLE`: a folder with `tom.wav` and the `tom.sfk` another+ /// editor made of it; their peaks agree.+ #[test]+ #[ignore]+ fn another_editors_peaks_match_the_sound() {+ let dir = std::path::PathBuf::from(std::env::var("BV_SFK_SAMPLE").expect("BV_SFK_SAMPLE"));+ let wav = dir.join("tom.wav").to_string_lossy().to_string();+ let info = crate::Engine::probe_file(&wav).expect("probe");+ let a = info.audio.expect("audio");+ let from_sfk =+ peak_files::read_sfk(&wav, a.sample_rate.0, a.channels.into(), 100).expect("sfk");+ let computed = compute_peaks(&info, 0, 100).expect("peaks");+ assert_eq!(from_sfk.peaks.len(), computed.peaks.len());+ for (s, c) in from_sfk.peaks.iter().zip(&computed.peaks) {+ assert_eq!(s.len(), c.len());+ for (x, y) in s.iter().zip(c) {+ // The blocks a hundredth spans reach a little past it.+ assert!(x.0 <= y.0 + 1e-4 && x.1 >= y.1 - 1e-4, "{x:?} {y:?}");+ assert!(+ (x.0 - y.0).abs() < 0.05 && (x.1 - y.1).abs() < 0.05,+ "{x:?} {y:?}"+ );+ }+ }+ }+#[test]fn thumbnail_heights_come_in_steps() {assert_eq!(thumb_height(10), 24);diff --git a/crates/engine/src/track_mix.rs b/crates/engine/src/track_mix.rsindex fa54402..d6bc6f0 100644--- a/crates/engine/src/track_mix.rs+++ b/crates/engine/src/track_mix.rs@@ -33,6 +33,8 @@ impl Worker {.name("bv-track-mix".into()).spawn(move || {let mut pool = AudioPool::new();+ // Playing: what takes long is made on threads of its own.+ pool.set_live(true);while let Ok((project, start, frames, delays)) = rx.recv() {let out =bv_mixer::mix_track(&project, track, start, frames, &delays, &mut pool);diff --git a/crates/engine/tests/pan_crop_renders.rs b/crates/engine/tests/pan_crop_renders.rsnew file mode 100644index 0000000..0ff0b88--- /dev/null+++ b/crates/engine/tests/pan_crop_renders.rs@@ -0,0 +1,210 @@+//! BananaV's Pan/Crop measured against another program's renders: the projects+//! of the folder `BV_PANCROP_SAMPLES` (its `vegas/geometria.veg`, with the+//! frames it rendered in `vegas/geometria`, and its `mascaras.veg`, frames in+//! `vegas/mascaras`), read and drawn here frame by frame.+//!+//! `BV_PANCROP_SAMPLES=<folder> cargo test -p bv-engine --test pan_crop_renders -- --ignored --nocapture`+//!+//! `BV_PANCROP_OUT=<folder>` saves each case's worst frame, doubled up with+//! its difference.++#![allow(clippy::print_stdout)]++use std::path::{Path, PathBuf};+use std::sync::Arc;+use std::time::{Duration, Instant};++use bv_core::Tick;+use bv_engine::Engine;+use bv_timeline::veg;+use bv_timeline::{MediaInfo, Project, ProjectSettings};++/// The project of a `.veg`, its media found where it says.+fn project(path: &Path) -> Project {+ let doc = veg::read(&std::fs::read(path).expect("the project")).expect("reads");+ let found: Vec<Option<MediaInfo>> = doc+ .media+ .iter()+ .map(|m| Engine::probe_file(&m.path).ok())+ .collect();+ assert!(+ found.iter().all(Option::is_some),+ "media missing: {:?}",+ doc.media+ );+ veg::build(&doc, &found, &ProjectSettings::default(), &|_, _| None).project+}++/// The frame at `t`, over black, RGB.+fn frame(engine: &mut Engine, t: Tick, (w, h): (u32, u32)) -> Vec<u8> {+ engine.request_preview(t, w, h);+ let start = Instant::now();+ loop {+ if let Some(f) = engine.preview_frame()+ && f.exact+ && f.time == t+ && (f.width, f.height) == (w, h)+ {+ return f+ .rgba+ .as_chunks::<4>()+ .0+ .iter()+ .flat_map(|p| {+ let a = u32::from(p[3]);+ [0, 1, 2].map(|c| ((u32::from(p[c]) * a + 127) / 255) as u8)+ })+ .collect();+ }+ assert!(start.elapsed() < Duration::from_secs(120), "drawn in time");+ std::thread::sleep(Duration::from_millis(2));+ }+}++fn rendered(folder: &Path, f: usize) -> Option<(Vec<u8>, u32, u32)> {+ let bytes = std::fs::read(folder.join(format!("quadros_{f:06}.png"))).ok()?;+ let image = bv_png::decode(&bytes).expect("a picture");+ let rgba = image.to_rgba8();+ let rgb = rgba+ .as_chunks::<4>()+ .0+ .iter()+ .flat_map(|p| [p[0], p[1], p[2]])+ .collect();+ Some((rgb, image.width, image.height))+}++#[derive(Default)]+struct Tally {+ frames: u32,+ sum: u64,+ values: u64,+ worst: u8,+ /// Pixels black in one picture and not in the other.+ swapped: u64,+ /// Pixels more than two levels off, and the same.+ far: u64,+ same: u64,+}++/// A project's events one by one against the frames rendered from it.+fn compare(project: &Project, folder: &Path, save: Option<&Path>, tag: &str) -> Vec<Tally> {+ let mut engine = Engine::new(Arc::new(|| {}));+ engine.set_project(project);+ let rate = project.settings.frame_rate;+ let size = (project.settings.width, project.settings.height);+ let mut clips: Vec<_> = project+ .clips()+ .map(|(_, c)| (c.start, c.duration))+ .collect();+ clips.sort_by_key(|c| c.0);+ let mut out = Vec::new();+ for (index, (start, duration)) in clips.into_iter().enumerate() {+ let mut tally = Tally::default();+ let first = rate.frame_at(start);+ let last = rate.frame_at(start + duration);+ let mut worst_frame = (0u64, Vec::new(), Vec::new());+ for f in first..last {+ let Some((real, w, h)) = rendered(folder, f as usize) else {+ continue;+ };+ assert_eq!((w, h), size);+ let ours = frame(&mut engine, rate.frame_start(f), size);+ tally.frames += 1;+ let mut sum = 0u64;+ for (a, b) in real.as_chunks::<3>().0.iter().zip(ours.as_chunks::<3>().0) {+ let mut far = false;+ let mut same = true;+ for k in 0..3 {+ let d = a[k].abs_diff(b[k]);+ sum += u64::from(d);+ tally.values += 1;+ tally.worst = tally.worst.max(d);+ far |= d > 2;+ same &= d == 0;+ }+ tally.far += u64::from(far);+ tally.same += u64::from(same);+ let black = |p: &[u8]| p.iter().all(|&v| v < 8);+ tally.swapped += u64::from(black(a) != black(b));+ }+ tally.sum += sum;+ if std::env::var_os("BV_PANCROP_FRAMES").is_some() {+ println!(+ " event {index} frame {f}: {:.3}",+ sum as f64 / real.len() as f64+ );+ }+ if sum >= worst_frame.0 {+ worst_frame = (sum, real, ours);+ }+ }+ if let (Some(dir), true) = (save, tally.frames > 0) {+ let (_, real, ours) = &worst_frame;+ let mut rgba = Vec::with_capacity(real.len() / 3 * 4);+ for (a, b) in real.as_chunks::<3>().0.iter().zip(ours.as_chunks::<3>().0) {+ for k in 0..3 {+ rgba.push(a[k].abs_diff(b[k]).saturating_mul(8));+ }+ rgba.push(255);+ }+ let png = bv_png::encode_rgba8(size.0, size.1, &rgba, 6);+ let _ = std::fs::create_dir_all(dir);+ let _ = std::fs::write(dir.join(format!("{tag}_{index:02}.png")), png);+ }+ out.push(tally);+ }+ out+}++#[test]+#[ignore = "needs the folder of renders"]+fn draws_as_its_renders_show() {+ let Some(dir) = std::env::var_os("BV_PANCROP_SAMPLES").map(PathBuf::from) else {+ println!("BV_PANCROP_SAMPLES not set");+ return;+ };+ let save = std::env::var_os("BV_PANCROP_OUT").map(PathBuf::from);+ // The picture's cases.+ let p = project(&dir.join("vegas").join("geometria.veg"));+ let tallies = compare(+ &p,+ &dir.join("vegas").join("geometria"),+ save.as_deref(),+ "geometry",+ );+ println!("geometry: event, frames, mean, worst, swapped, far pixels");+ let mut worst_mean = 0.0f64;+ let mut swapped = 0;+ for (i, t) in tallies.iter().enumerate() {+ let mean = t.sum as f64 / t.values.max(1) as f64;+ println!(+ " {i:2} {:3} {mean:.3} {:3} {:5} {:6}",+ t.frames, t.worst, t.swapped, t.far+ );+ worst_mean = worst_mean.max(mean);+ swapped += t.swapped;+ }+ println!("geometry: worst mean {worst_mean:.3}, swapped {swapped}");+ // The masks' cases: on a white picture, the mask itself.+ let p = project(&dir.join("mascaras.veg"));+ let tallies = compare(+ &p,+ &dir.join("vegas").join("mascaras"),+ save.as_deref(),+ "mask",+ );+ println!("masks: event, frames, mean, worst, pixels the same (of 230400 each)");+ let mut exact = true;+ for (i, t) in tallies.iter().enumerate() {+ let mean = t.sum as f64 / t.values.max(1) as f64;+ println!(+ " {i:2} {:3} {mean:.4} {:3} {:8}",+ t.frames, t.worst, t.same+ );+ exact &= t.worst == 0;+ }+ println!("masks: all exact: {exact}");+ assert!(worst_mean < 1.0, "the picture lands where it did");+ assert!(exact, "the masks come out the same");+}diff --git a/crates/gpu/Cargo.toml b/crates/gpu/Cargo.tomlindex e2949e8..4915474 100644--- a/crates/gpu/Cargo.toml+++ b/crates/gpu/Cargo.toml@@ -33,6 +33,7 @@ windows = { version = "0.62", features = ["Win32_Graphics_Direct3D12","Win32_Graphics_Dxgi_Common","Win32_Security",+ "Win32_System_Threading",] }[dev-dependencies]diff --git a/crates/gpu/src/compositor.rs b/crates/gpu/src/compositor.rsindex b60e023..31b25da 100644--- a/crates/gpu/src/compositor.rs+++ b/crates/gpu/src/compositor.rs@@ -7,6 +7,7 @@ use std::sync::Arc;use bv_core::{ImageRgbaF32, PixelFormat, PlaneData, TransferCharacteristic, VideoFrame};use bv_media::{Ask, Picture, VideoPool, Want};use bv_timeline::fx::grade;+use bv_timeline::pancrop::Placement;use bv_timeline::scene::{CardPicture, EventLayer, FrameScene, Framing, MediaLayer, PluginCall, Plugins, TrackContent,fit_rect_par,@@ -933,7 +934,7 @@ impl Compositor {framed_at: 0,media_size: (img.w, img.h),media_fx_scale: 1.0,- par: 1.0,+ place: m.place,quality: m.quality,};for (k, e) in m.effects.iter().enumerate() {@@ -1103,7 +1104,6 @@ impl Compositor {self.mix(enc, &next, &img, k);src = img;}- let tf = &m.transform;// The media's effects work on its own picture, on pixels that// show; then the event's Pan/Crop frames it, and the event's// effects work on the framed picture (VEGAS's default: Pan/Crop@@ -1112,10 +1112,9 @@ impl Compositor {let (src, media_fx_scale) = if framed_at == 0 {(src, 1.0)} else {- let mut src = self.reduce_for_display(enc, scene, &src, tf.scale, m.par);- let (pw, ph) = scene.project_size;- let fit = fit_rect_par(src.w, src.h, m.par, pw, ph);- let fx_scale = src.h as f32 / (fit.h * tf.scale.max(1e-4));+ let mut src = self.reduce_for_display(enc, &src, &m.placement);+ let per_line = m.placement.picture_per_pixel(src.w, src.h).1;+ let fx_scale = (per_line as f32 * scene.scale).max(1e-4);for (k, e) in m.effects[..framed_at].iter().enumerate() {match scene.media_call(m, k, fx_scale, None) {Some(call) => self.plugin(enc, scene, &call, &mut src),@@ -1125,7 +1124,13 @@ impl Compositor {}(src, fx_scale)};- let mut img = self.place(enc, &src, (scene.width, scene.height), tf, m.quality, m.par);+ let mut img = self.place_box(+ enc,+ &src,+ (scene.width, scene.height),+ &m.placement,+ m.quality,+ );// Reduce Interlace Flicker: on the framed picture, before the// event's effects.if m.clip.reduce_flicker {@@ -1144,7 +1149,8 @@ impl Compositor {// kept on the card while they do not change.let mask = m.mask_picture(src.w, src.h).map(|c| {let up = self.upload(Some(owner.rotate_left(17) ^ 0x6d61_736b), &c);- self.place(enc, &up, (scene.width, scene.height), tf, m.quality, m.par)+ let hard = m.placement.hard();+ self.place_box(enc, &up, (scene.width, scene.height), &hard, m.quality)});let unaffected = match &mask {Some(_) if m.clip.mask.as_ref().is_some_and(|k| k.apply_to_fx) => {@@ -1156,7 +1162,7 @@ impl Compositor {framed_at,media_size: (src.w, src.h),media_fx_scale,- par: m.par,+ place: m.place,quality: m.quality,};// The event's picture before its effects, kept for those that@@ -1364,18 +1370,12 @@ impl Compositor {fn reduce_for_display(&mut self,enc: &mut wgpu::CommandEncoder,- scene: &FrameScene<'_>,src: &Img,- scale: f32,- par: f32,+ place: &Placement,) -> Img {- let fit = fit_rect_par(src.w, src.h, par, scene.width, scene.height);let mut img = src.clone();let mut halved = false;- while img.w as f32 >= fit.w * scale * 2.0- && img.h as f32 >= fit.h * scale * 2.0- && img.w > 1- {+ while place.reduces(img.w, img.h) && img.w > 1 {img = self.half(enc, &img);halved = true;}@@ -1397,6 +1397,69 @@ impl Compositor {out}+ /// `src`, a picture of the media, where a Pan/Crop places it on a `w` ×+ /// `h` frame (as `bv_render::place_box`).+ fn place_box(+ &mut self,+ enc: &mut wgpu::CommandEncoder,+ src: &Img,+ (w, h): (u32, u32),+ place: &Placement,+ quality: RenderQuality,+ ) -> Img {+ let out = self.image(w, h);+ if place.empty {+ return self.transparent(enc, w, h);+ }+ // Large reductions go through 2 × 2 averages first (Good and Best).+ let mut s = src.clone();+ if matches!(quality, RenderQuality::Good | RenderQuality::Best) {+ while place.reduces(s.w, s.h) && s.w > 1 {+ s = self.half(enc, &s);+ }+ }+ let (m, _) = place.in_picture([f64::from(s.w), f64::from(s.h)]);+ let (kx, ky) = (+ f64::from(s.w) / place.media[0],+ f64::from(s.h) / place.media[1],+ );+ let lines = place.crop_lines();+ let limits = [lines[0] * kx, lines[1] * ky, lines[2] * kx, lines[3] * ky];+ let b = place.to_box.unwrap_or_default();+ let mut p = Params::sized(w, h).with_f(&[+ m[0] as f32,+ m[1] as f32,+ m[2] as f32,+ m[3] as f32,+ m[4] as f32,+ m[5] as f32,+ b[0] as f32,+ b[1] as f32,+ b[2] as f32,+ b[3] as f32,+ b[4] as f32,+ b[5] as f32,+ limits[0] as f32,+ limits[1] as f32,+ limits[2] as f32,+ limits[3] as f32,+ ]);+ (p.sw, p.sh) = (s.w, s.h);+ p.i = place.pixels((w, h));+ p.j[0] = match quality {+ RenderQuality::Draft => 0,+ RenderQuality::Preview | RenderQuality::Good => 1,+ RenderQuality::Best => 2,+ };+ let k = if place.to_box.is_some() {+ K::PlaceSoft+ } else {+ K::PlaceHard+ };+ self.kernel(enc, k, p, &[&s.buf, &out.buf], Grid::Pixels(w, h));+ out+ }+/// `src` placed in a `w` × `h` layer, framed by `tf` (as/// `bv_render::place_with`).fn place(@@ -1671,20 +1734,9 @@ impl Compositor {Grid::Pixels(w, h),);}- // Audio effects do not touch the picture; plug-ins' go through- // `plugin`.- EffectKind::Gain- | EffectKind::Eq3- | EffectKind::HighPass- | EffectKind::LowPass- | EffectKind::Compressor- | EffectKind::Limiter- | EffectKind::NoiseGate- | EffectKind::Delay- | EffectKind::Reverb- | EffectKind::ModernEq- | EffectKind::Vst- | EffectKind::Plugin => {}+ // Audio effects do not touch the picture (all of them); plug-ins'+ // go through `plugin`.+ _ => {}}}diff --git a/crates/gpu/src/compositor/own.rs b/crates/gpu/src/compositor/own.rsindex abdbcc9..e6da37c 100644--- a/crates/gpu/src/compositor/own.rs+++ b/crates/gpu/src/compositor/own.rs@@ -577,32 +577,83 @@ impl Compositor {Some(out)}- /// One of Color Grading's LUTs over `img`.+ /// LUT Filter's pass: `img`'s straight colors through `lut`, mixed+ /// with the picture by `strength`; `hold` keeps the colors within 0–1+ /// before and after (Color Grading's LUTs).+ fn lut_pass(+ &mut self,+ enc: &mut wgpu::CommandEncoder,+ lut: &bv_lut::Lut,+ tetrahedral: bool,+ strength: f32,+ hold: bool,+ img: &mut Img,+ ) {+ let (w, h) = (img.w, img.h);+ if strength <= 0.0 {+ return;+ }+ // The shaper's entries, then the lattice's.+ let mut entries: Vec<f32> = Vec::with_capacity(lut_entries(lut) * 4);+ let none = (Vec::new(), [0.0; 3], [1.0; 3]);+ let (shaper, s_lo, s_hi) = lut+ .shaper+ .as_ref()+ .map_or(none.clone(), |t| (t.entries.clone(), t.min, t.max));+ let (cube, c_lo, c_hi) = lut+ .cube+ .as_ref()+ .map_or(none, |t| (t.entries.clone(), t.min, t.max));+ for e in shaper.iter().chain(&cube) {+ entries.extend_from_slice(&[e[0], e[1], e[2], 0.0]);+ }+ if entries.is_empty() {+ return;+ }+ let table = self.buffer(entries.len() as u64 * 4);+ self.gpu+ .queue+ .write_buffer(&table, 0, bytemuck::cast_slice(&entries));+ let mut p = Params::sized(w, h).with_f(&[+ s_lo[0], s_lo[1], s_lo[2], s_hi[0], s_hi[1], s_hi[2], c_lo[0], c_lo[1], c_lo[2],+ c_hi[0], c_hi[1], c_hi[2], strength,+ ]);+ p.j = [+ shaper.len() as u32,+ lut.cube.as_ref().map_or(0, |t| t.size as u32),+ u32::from(tetrahedral),+ u32::from(hold),+ ];+ p.sw = (entries.len() / 4) as u32;+ p.sh = 1;+ self.kernel(+ enc,+ K::LutFilter,+ p,+ &[&table, &img.buf],+ Grid::Pixels(w, h),+ );+ }++ /// One of Color Grading's LUTs over `img`, the colors held within 0–1+ /// before and after it.fn grade_lut(&mut self,enc: &mut wgpu::CommandEncoder,lut: Option<&accel::GradeLut>,img: &mut Img,- full: [f64; 2],- scale: f64,) {match lut {Some(accel::GradeLut::Cube {lut,tetrahedral,strength,- }) => {- let plan = Plan::Lut {- lut: Some(lut.clone()),- tetrahedral: *tetrahedral,- strength: *strength,- };- self.own(enc, &plan, img, full, scale);- }+ }) => self.lut_pass(enc, lut, *tetrahedral, *strength, true, img),Some(accel::GradeLut::AppleLog { video, strength }) => {let (w, h) = (img.w, img.h);let mut p = Params::sized(w, h).with_f(&[*strength]);p.j[0] = u32::from(*video);+ p.j[1] = 1;self.kernel(enc, K::AppleLog, p, &[&img.buf], Grid::Pixels(w, h));}None => {}@@ -674,7 +725,7 @@ impl Compositor {self.kernel(enc, K::CookieCutter, p, &[&img.buf], Grid::Pixels(w, h));}Plan::Grade(g) => {- self.grade_lut(enc, g.camera.as_ref(), img, full, scale);+ self.grade_lut(enc, g.camera.as_ref(), img);let table = self.buffer(g.steps.len() as u64 * 16);self.gpu.queue@@ -683,7 +734,7 @@ impl Compositor {p.sw = g.entries;p.sh = 1;self.kernel(enc, K::Grade, p, &[&table, &img.buf], Grid::Pixels(w, h));- self.grade_lut(enc, g.look.as_ref(), img, full, scale);+ self.grade_lut(enc, g.look.as_ref(), img);}Plan::Curves(tables) => {// The three tables side by side: entry k's red, green and@@ -2023,50 +2074,9 @@ impl Compositor {tetrahedral,strength,} => {- let Some(lut) = lut else { return };- if *strength <= 0.0 {- return;+ if let Some(lut) = lut {+ self.lut_pass(enc, lut, *tetrahedral, *strength, false, img);}- // The shaper's entries, then the lattice's.- let mut entries: Vec<f32> = Vec::with_capacity(lut_entries(lut) * 4);- let none = (Vec::new(), [0.0; 3], [1.0; 3]);- let (shaper, s_lo, s_hi) = lut- .shaper- .as_ref()- .map_or(none.clone(), |t| (t.entries.clone(), t.min, t.max));- let (cube, c_lo, c_hi) = lut- .cube- .as_ref()- .map_or(none, |t| (t.entries.clone(), t.min, t.max));- for e in shaper.iter().chain(&cube) {- entries.extend_from_slice(&[e[0], e[1], e[2], 0.0]);- }- if entries.is_empty() {- return;- }- let table = self.buffer(entries.len() as u64 * 4);- self.gpu- .queue- .write_buffer(&table, 0, bytemuck::cast_slice(&entries));- let mut p = Params::sized(w, h).with_f(&[- s_lo[0], s_lo[1], s_lo[2], s_hi[0], s_hi[1], s_hi[2], c_lo[0], c_lo[1],- c_lo[2], c_hi[0], c_hi[1], c_hi[2], *strength,- ]);- p.j = [- shaper.len() as u32,- lut.cube.as_ref().map_or(0, |t| t.size as u32),- *tetrahedral as u32,- 0,- ];- p.sw = (entries.len() / 4) as u32;- p.sh = 1;- self.kernel(- enc,- K::LutFilter,- p,- &[&table, &img.buf],- Grid::Pixels(w, h),- );}}}diff --git a/crates/gpu/src/kernels.rs b/crates/gpu/src/kernels.rsindex a0b3973..0693507 100644--- a/crates/gpu/src/kernels.rs+++ b/crates/gpu/src/kernels.rs@@ -2,7 +2,7 @@//! how one is run on images in buffers.use std::collections::HashMap;-use std::sync::Mutex;+use std::sync::{Arc, Mutex, OnceLock};use wgpu::util::DeviceExt;@@ -110,6 +110,8 @@ pub(crate) enum K {GlowBright,CopyInto,Place,+ PlaceHard,+ PlaceSoft,HalfSize,Composite,Rotate,@@ -296,7 +298,7 @@ pub(crate) enum K {}impl K {- pub const ALL: [K; 196] = [+ pub const ALL: [K; 198] = [K::Fill,K::Scale,K::ToVideoGamma,@@ -313,6 +315,8 @@ impl K {K::GlowBright,K::CopyInto,K::Place,+ K::PlaceHard,+ K::PlaceSoft,K::HalfSize,K::Composite,K::Rotate,@@ -507,12 +511,12 @@ impl K {| KitBlackRestore | KitChannelBlend | KitMaskGenerator | KitBroadcastColors| KitLabAdjust | KitColorMatch | KitSoftTone | KitVignette | KitCheckerboard| KitTestPattern | KitNoiseTexture | KitFlickerAdd => Sig::InPlace,- CopyInto | Place | HalfSize | Composite | Rotate | Mirror | FlickerFilter- | InterpolateFields | Blend | BoxH | BoxV | BlockAverage | BlockFill | Sharpen- | AddGlow | Curves | FieldAlpha | FieldBoxH | FieldBoxV | PixelRows | PixelCells- | PixelFill | LutFilter | EqualizeRows | EqualizeTotal | EqualizeApply- | PictureInPicture | UnsharpMask | Overlay | AcesRrt | AcesOdt | Grade- | BezierMasking | KitSpherize | KitOffsetWrap | KitTinyPlanet | KitDeform+ CopyInto | Place | PlaceHard | PlaceSoft | HalfSize | Composite | Rotate | Mirror+ | FlickerFilter | InterpolateFields | Blend | BoxH | BoxV | BlockAverage+ | BlockFill | Sharpen | AddGlow | Curves | FieldAlpha | FieldBoxH | FieldBoxV+ | PixelRows | PixelCells | PixelFill | LutFilter | EqualizeRows | EqualizeTotal+ | EqualizeApply | PictureInPicture | UnsharpMask | Overlay | AcesRrt | AcesOdt+ | Grade | BezierMasking | KitSpherize | KitOffsetWrap | KitTinyPlanet | KitDeform| KitConvolution | KitQuickBlur | KitBumpMap | KitLensCorrection | KitStabilize| KitStabilizeBlur | KitSmartEnhance | KitGuidedLow | KitGuidedOp | KitGuidedMean| KitDehazeDark | KitKeyMask | KitKeyApply | KitChromaUv | KitChromaApply@@ -558,6 +562,8 @@ impl K {GlowBright => "glow_bright",CopyInto => "copy_into",Place => "place",+ PlaceHard => "place_hard",+ PlaceSoft => "place_soft",HalfSize => "half_size",Composite => "composite",Rotate => "rotate",@@ -803,11 +809,14 @@ pub(crate) enum Grid {}/// The shaders, compiled once per device; pipelines are made the first-/// time a kernel runs.+/// time a kernel runs, or by `Gpu::warm_up` before that.pub(crate) struct Kernels {modules: HashMap<Sig, wgpu::ShaderModule>,layouts: HashMap<Sig, (wgpu::BindGroupLayout, wgpu::PipelineLayout)>,- pipelines: Mutex<HashMap<K, wgpu::ComputePipeline>>,+ /// Each kernel's own cell: the compiler (a kernel may take seconds)+ /// runs outside the map's lock, so a frame waits for the kernels it+ /// uses and for no other.+ pipelines: Mutex<HashMap<K, Arc<OnceLock<wgpu::ComputePipeline>>>>,/// Kernels made at run time, by their source (`None`: not valid WGSL),/// the last ones kept.made: Mutex<Vec<(String, Option<wgpu::ComputePipeline>)>>,@@ -964,20 +973,31 @@ impl Kernels {}pub fn pipeline(&self, device: &wgpu::Device, k: K) -> wgpu::ComputePipeline {- let mut map = self.pipelines.lock().expect("pipelines");- map.entry(k)- .or_insert_with(|| {- let sig = k.sig();- device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {- label: Some(k.entry()),- layout: Some(&self.layouts[&sig].1),- module: &self.modules[&sig],- entry_point: Some(k.entry()),- compilation_options: Default::default(),- cache: None,- })+ let cell = self+ .pipelines+ .lock()+ .expect("pipelines")+ .entry(k)+ .or_default()+ .clone();+ cell.get_or_init(|| {+ let sig = k.sig();+ device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {+ label: Some(k.entry()),+ layout: Some(&self.layouts[&sig].1),+ module: &self.modules[&sig],+ entry_point: Some(k.entry()),+ // The kernels write their `var<workgroup>` tables before+ // reading them; zeroing them first, an element at a time+ // for FXC, costs tens of seconds to compile.+ compilation_options: wgpu::PipelineCompilationOptions {+ zero_initialize_workgroup_memory: false,+ ..Default::default()+ },+ cache: None,})- .clone()+ })+ .clone()}/// Records kernel `k` on `buffers` (in binding order after thediff --git a/crates/gpu/src/lib.rs b/crates/gpu/src/lib.rsindex baae590..6827c79 100644--- a/crates/gpu/src/lib.rs+++ b/crates/gpu/src/lib.rs@@ -13,11 +13,24 @@ mod compositor;mod kernels;mod shared;-use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};use std::sync::{Arc, Mutex, OnceLock};pub use compositor::{Compositor, Output, Rendered, draws};+/// This thread gives way to the others: the work it does can wait.+#[allow(unsafe_code)]+fn lower_priority() {+ #[cfg(windows)]+ // SAFETY: GetCurrentThread's handle always stands for this thread.+ unsafe {+ use windows::Win32::System::Threading::{+ GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_BELOW_NORMAL,+ };+ let _ = SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_BELOW_NORMAL);+ }+}+/// Why the graphics card could not do it (the processor then does).#[derive(Clone, Debug, PartialEq, Eq)]pub enum GpuError {@@ -232,17 +245,40 @@ impl Gpu {}/// Compiles every kernel now (they are compiled the first time they- /// run otherwise): a first frame then shows without waiting. The first- /// kernel the card refuses, if any.+ /// run otherwise), on a few threads of low priority: frames draw on+ /// meanwhile, each waiting only for the kernels it uses, and later+ /// ones find them ready. The first kernel the card refuses, if any.+ /// `BV_GPU_TRACE=1` prints each one's time.pub fn warm_up(&self) -> Result<(), GpuError> {- for k in kernels::K::ALL {- let scope = self.device.push_error_scope(wgpu::ErrorFilter::Validation);- self.kernels.pipeline(&self.device, k);- if let Some(e) = pollster::block_on(scope.pop()) {- return Err(GpuError::Failed(format!("{}: {e}", k.entry())));+ let trace = std::env::var_os("BV_GPU_TRACE").is_some();+ let next = AtomicUsize::new(0);+ let work = || -> Result<(), GpuError> {+ lower_priority();+ while let Some(&k) = kernels::K::ALL.get(next.fetch_add(1, Ordering::Relaxed)) {+ let start = std::time::Instant::now();+ let scope = self.device.push_error_scope(wgpu::ErrorFilter::Validation);+ self.kernels.pipeline(&self.device, k);+ if let Some(e) = pollster::block_on(scope.pop()) {+ return Err(GpuError::Failed(format!("{}: {e}", k.entry())));+ }+ if trace {+ eprintln!("kernel {}: {} ms", k.entry(), start.elapsed().as_millis());+ }}+ Ok(())+ };+ let threads = std::thread::available_parallelism().map_or(1, |n| (n.get() / 3).clamp(1, 4));+ let start = std::time::Instant::now();+ let done = std::thread::scope(|s| {+ let workers: Vec<_> = (0..threads).map(|_| s.spawn(work)).collect();+ workers+ .into_iter()+ .try_for_each(|w| w.join().unwrap_or(Ok(())))+ });+ if trace {+ eprintln!("every kernel in {} ms", start.elapsed().as_millis());}- Ok(())+ done}/// The card in use.diff --git a/crates/gpu/src/shaders/own_inplace.wgsl b/crates/gpu/src/shaders/own_inplace.wgslindex 3b7b728..045b2f1 100644--- a/crates/gpu/src/shaders/own_inplace.wgsl+++ b/crates/gpu/src/shaders/own_inplace.wgsl@@ -673,7 +673,8 @@ fn add_noise(@builtin(global_invocation_id) id: vec3<u32>) {// Color Grading's Apple Log (`color_grading::apple_log`) on `img` (`w` ×// `h`, changed in place): the straight colors, Apple Log, decoded to-// Rec. 709's linear light — or (j.x) its video —, mixed in by f 0.+// Rec. 709's linear light — or (j.x) its video —, mixed in by f 0; j.y+// holds the colors within 0–1 before and after.fn apple_log_linear(x: f32) -> f32 {let r0 = -0.05641088;let c = 47.28711236;@@ -699,7 +700,10 @@ fn apple_log(@builtin(global_invocation_id) id: vec3<u32>) {img[o] = vec4<f32>(0.0, 0.0, 0.0, a);return;}- let c = px.xyz / a;+ var c = px.xyz / a;+ if P.j.y != 0u {+ c = clamp(c, vec3<f32>(0.0), vec3<f32>(1.0));+ }let l = vec3<f32>(apple_log_linear(c.x), apple_log_linear(c.y), apple_log_linear(c.z));var v = vec3<f32>(1.660491 * l.x - 0.587641 * l.y - 0.072850 * l.z,@@ -710,7 +714,10 @@ fn apple_log(@builtin(global_invocation_id) id: vec3<u32>) {let k = clamp(v, vec3<f32>(0.0), vec3<f32>(1.0));v = vec3<f32>(bt709_encode(k.x), bt709_encode(k.y), bt709_encode(k.z));}- let res = c + (v - c) * pf(0u);+ var res = c + (v - c) * pf(0u);+ if P.j.y != 0u {+ res = clamp(res, vec3<f32>(0.0), vec3<f32>(1.0));+ }img[o] = vec4<f32>(res * a, a);}diff --git a/crates/gpu/src/shaders/own_pair.wgsl b/crates/gpu/src/shaders/own_pair.wgslindex ea69bbf..2e093df 100644--- a/crates/gpu/src/shaders/own_pair.wgsl+++ b/crates/gpu/src/shaders/own_pair.wgsl@@ -222,7 +222,9 @@ fn pixel_fill(@builtin(global_invocation_id) id: vec3<u32>) {// LUT Filter: a table's 1D shaper (`j.x` entries of `src`, over f 0–2 to// f 3–5) and its lattice (`j.y`³ entries after them, red changing-// fastest, over f 6–8 to f 9–11), as `bv-lut` applies them.+// fastest, over f 6–8 to f 9–11), as `bv-lut` applies them; `j.z` reads+// it by tetrahedra, `j.w` holds the colors within 0–1 before and after+// (Color Grading's LUTs).fn lut_unit(v: vec3<f32>, lo: vec3<f32>, hi: vec3<f32>) -> vec3<f32> {let t = (v - lo) / max(hi - lo, vec3<f32>(1e-12));return clamp(t, vec3<f32>(0.0), vec3<f32>(1.0));@@ -318,7 +320,10 @@ fn lut_filter(@builtin(global_invocation_id) id: vec3<u32>) {dst[o] = vec4<f32>(0.0, 0.0, 0.0, a);return;}- let c = px.xyz / a;+ var c = px.xyz / a;+ if P.j.w != 0u {+ c = clamp(c, vec3<f32>(0.0), vec3<f32>(1.0));+ }var v = c;if P.j.x > 0u {v = lut_shaper(v);@@ -326,7 +331,10 @@ fn lut_filter(@builtin(global_invocation_id) id: vec3<u32>) {if P.j.y > 0u {v = lut_cube(v);}- let out = c + (v - c) * pf(12u);+ var out = c + (v - c) * pf(12u);+ if P.j.w != 0u {+ out = clamp(out, vec3<f32>(0.0), vec3<f32>(1.0));+ }dst[o] = vec4<f32>(out * a, a);}@@ -497,201 +505,346 @@ fn overlay(@builtin(global_invocation_id) id: vec3<u32>) {dst[o] = over(src[u32(sy) * P.sw + u32(sx)], dst[o]);}-// Color Grading's own steps (`color_grading.rs`' `Grade::step`, from the-// Color Wheels to the HSL Curves; its LUTs are passes of their own) on-// `dst` (`w` × `h`, changed in place), the straight colors: `src` holds-// the settings, then the tables (`sw` entries each) —-// 0–3 the Color Wheels (Lift, Gamma, Gain, Offset: r, g, b, master),-// 4–7 the RL Color Wheels (Shadows, Midtones, Highlights, Offset),-// 8 the RL thresholds (x, y) and White Balance's temperature and tint-// (z, w), 9 Levels (in black, in white, out min, out max), 10 Tone-// (brightness, contrast, center, saturation), 11 Log exposure and HSL-// (hue, saturation, luminance), 12 switches (x: the RL wheels, y: the HSL-// Curves, z: Levels); from 16 the Curves' tables (Brightness, Red, Green,-// Blue), then the HSL Curves' (0–3, then 4–5).+// Color Grading (`grading.rs`' `Grade::apply`, between its LUTs, which+// are passes of their own) on `dst` (`w` × `h`, changed in place): the+// straight colors, held within 0–1 first. `src` holds the settings, a+// row each, then the tables, an entry a row (x):+// 0 switches: White Balance, Levels, the RL wheels by channel, by Y;+// 1 switches: the Color Curves by channel, by Y, Lift; the HSL Curves'+// count (w);+// 2 Saturation (1: none), Exposure's scale, Brightness, whether the+// panel's Exposure is on;+// 3 Contrast's scale and center, the panel's Exposure's scale before its+// table, the HSL's hue;+// 4 the HSL's saturation and luminance, whether each CDL is on;+// 5–7 White Balance's matrix, a row each; 8 Levels (in min, in max, out+// min, out max); 9 Lift; 10–12 the first CDL's slope, offset and power,+// 13–15 the second's;+// 16–21 the HSL Curves in their order: which (x: Hue vs Hue … Luminance+// vs Saturation), where its table starts (y) and its length (z);+// 22–30 where each table starts (x) and its length (y): the RL wheels'+// red, green, blue and Y, the Color Curves' red, green, blue and Y, the+// panel's Exposure's.++const GRADE_WHITE_L: f32 = 95.580666;++fn grade_hold(c: vec3<f32>) -> vec3<f32> {+ return clamp(c, vec3<f32>(0.0), vec3<f32>(1.0));+}++// A table (`n` entries from `at`) at `v`: straight between its entries,+// `v` held within 0–1; no table changes nothing.+fn grade_lookup(at: u32, n: u32, v: f32) -> f32 {+ if n == 0u {+ return v;+ }+ if !(v > 0.0) {+ return src[at].x;+ }+ if v >= 1.0 {+ return src[at + n - 1u].x;+ }+ let p = v * f32(n - 1u);+ let i = u32(floor(p));+ let f = p - f32(i);+ if i + 1u < n {+ let a = src[at + i].x;+ return a + (src[at + i + 1u].x - a) * f;+ }+ return src[at + i].x;+}-const GRADE_TABLES: u32 = 16u;+// Table `k` of rows 22–30 at `v`.+fn grade_table(k: u32, v: f32) -> f32 {+ let d = src[22u + k];+ return grade_lookup(u32(d.x), u32(d.y), v);+}-fn grade_component(v: vec4<f32>, c: u32) -> f32 {- if c == 0u {- return v.x;+fn grade_to_hsl(c: vec3<f32>) -> vec3<f32> {+ let lo = min(min(c.x, c.y), c.z);+ let hi = max(max(c.x, c.y), c.z);+ let l = (lo + hi) * 0.5;+ if !(l > 0.0) {+ return vec3<f32>(0.0, 0.0, l);}- if c == 1u {- return v.y;+ let d = hi - lo;+ if !(d > 0.0) {+ return vec3<f32>(0.0, d, l);}- if c == 2u {- return v.z;- }- return v.w;-}--// Table `c` of the group from `base` (`P.sw` entries) at x, held within-// 0–1.-fn grade_within(base: u32, c: u32, x: f32) -> f32 {- let n = P.sw;- let f = clamp(x, 0.0, 1.0) * f32(n - 1u);- let i = min(u32(f), n - 2u);- let k = f - f32(i);- let a = grade_component(src[base + i], c);- return a + (grade_component(src[base + i + 1u], c) - a) * k;-}--// The same, past its ends along their slope.-fn grade_at(base: u32, c: u32, x: f32) -> f32 {- let n = P.sw;- let last = f32(n - 1u);- if x < 0.0 {- let t0 = grade_component(src[base], c);- return t0 + x * (grade_component(src[base + 1u], c) - t0) * last;- }- if x > 1.0 {- let tn = grade_component(src[base + n - 1u], c);- return tn + (x - 1.0) * (tn - grade_component(src[base + n - 2u], c)) * last;- }- return grade_within(base, c, x);-}--fn grade_smoothstep(a: f32, b: f32, x: f32) -> f32 {- let t = clamp((x - a) / max(b - a, 1e-6), 0.0, 1.0);- return t * t * (3.0 - 2.0 * t);-}--fn grade_hsv(c: vec3<f32>) -> vec3<f32> {- let mx = max(max(c.x, c.y), c.z);- let mn = min(min(c.x, c.y), c.z);- let d = mx - mn;- if d <= 1e-7 || mx <= 0.0 {- return vec3<f32>(0.0, 0.0, mx);- }- var h = (c.x - c.y) / d + 4.0;- if mx == c.x {- let q = (c.y - c.z) / d;- h = q - 6.0 * floor(q / 6.0);- } else if mx == c.y {- h = (c.z - c.x) / d + 2.0;- }- return vec3<f32>(h / 6.0, d / mx, mx);-}--fn grade_from_hsv(hsv: vec3<f32>) -> vec3<f32> {- let h = (hsv.x - floor(hsv.x)) * 6.0;- let c = hsv.z * hsv.y;- let x = c * (1.0 - abs(h - 2.0 * trunc(h / 2.0) - 1.0));- let m = hsv.z - c;- let sector = u32(h);- var rgb = vec3<f32>(c, 0.0, x);- if sector == 0u {- rgb = vec3<f32>(c, x, 0.0);- } else if sector == 1u {- rgb = vec3<f32>(x, c, 0.0);- } else if sector == 2u {- rgb = vec3<f32>(0.0, c, x);- } else if sector == 3u {- rgb = vec3<f32>(0.0, x, c);- } else if sector == 4u {- rgb = vec3<f32>(x, 0.0, c);- }- return rgb + vec3<f32>(m);-}--fn grade_luma(c: vec3<f32>) -> f32 {- return 0.2126 * c.x + 0.7152 * c.y + 0.0722 * c.z;-}--// The grade's steps from the Color Wheels to the HSL Curves.-fn grade_steps(color: vec3<f32>) -> vec3<f32> {- var c = color;- // Color Wheels: Lift, Gain, Gamma, Offset.- let lift = src[0u].xyz + vec3<f32>(src[0u].w);- let gamma = max(src[1u].xyz * src[1u].w, vec3<f32>(0.01));- let gain = src[2u].xyz * src[2u].w;- let offset = src[3u].xyz + vec3<f32>(src[3u].w);- var v = (c + lift * (vec3<f32>(1.0) - c)) * gain;- if v.x > 0.0 && gamma.x != 1.0 {- v.x = pow(v.x, 1.0 / gamma.x);- }- if v.y > 0.0 && gamma.y != 1.0 {- v.y = pow(v.y, 1.0 / gamma.y);- }- if v.z > 0.0 && gamma.z != 1.0 {- v.z = pow(v.z, 1.0 / gamma.z);- }- c = v + offset;- // RL Color Wheels: by where the luma stands.- let sw = src[12u];- if sw.x != 0.0 {- let lo = src[8u].x;- let hi = src[8u].y;- let y = grade_luma(c);- let shadows = 1.0 - grade_smoothstep(lo - 0.05, lo + 0.05, y);- let highlights = grade_smoothstep(hi - 0.05, hi + 0.05, y);- let midtones = max(1.0 - shadows - highlights, 0.0);- c += shadows * (src[4u].xyz + vec3<f32>(src[4u].w))- + midtones * (src[5u].xyz + vec3<f32>(src[5u].w))- + highlights * (src[6u].xyz + vec3<f32>(src[6u].w))- + src[7u].xyz- + vec3<f32>(src[7u].w);- }- // Levels and Tone.- if sw.z != 0.0 {- let l = src[9u];- let span = max(l.y - l.x, 1e-4);- c = vec3<f32>(l.z) + (c - vec3<f32>(l.x)) / span * (l.w - l.z);- }- let tone = src[10u];- let more = src[11u];- c = (c + vec3<f32>(tone.x + more.x * 0.1 - tone.z)) * (1.0 + tone.y) + vec3<f32>(tone.z);- if tone.w != 1.0 {- let y = grade_luma(c);- c = vec3<f32>(y) + (c - vec3<f32>(y)) * tone.w;- }- // White Balance.- let temperature = src[8u].z;- let tint = src[8u].w;- if temperature != 0.0 || tint != 0.0 {- c.x *= 1.0 - 0.25 * temperature;- c.z *= 1.0 + 0.25 * temperature;- c.y *= 1.0 + 0.25 * tint;- }- // HSL: the chroma turned and scaled about the luma, the luma moved.- if more.y != 0.0 || more.z != 1.0 || more.w != 0.0 {- let y = grade_luma(c);- let cb = c.z - y;- let cr = c.x - y;- let s = sin(radians(more.y));- let k = cos(radians(more.y));- let cb2 = (cb * k - cr * s) * more.z;- let cr2 = (cb * s + cr * k) * more.z;- let y2 = y + more.w;- let r = y2 + cr2;- let b = y2 + cb2;- c = vec3<f32>(r, (y2 - 0.2126 * r - 0.0722 * b) / 0.7152, b);- }- // Curves: the luma through Brightness, then each channel.- let y = grade_luma(c);- let mapped = grade_at(GRADE_TABLES, 0u, y);- if y > 1e-5 {- c = c * (mapped / y);- } else {- c = c + vec3<f32>(mapped - y);+ var s = d / (lo + hi);+ if l > 0.5 {+ s = d / ((2.0 - hi) - lo);+ }+ let dr = (hi - c.x) / d;+ let dg = (hi - c.y) / d;+ let db = (hi - c.z) / d;+ var h = (3.0 - db) / 6.0;+ if c.x == hi {+ if c.y == lo {+ h = (db + 5.0) / 6.0;+ } else {+ h = (1.0 - dg) / 6.0;+ }+ } else if c.y != hi {+ if c.x == lo {+ h = (dg + 3.0) / 6.0;+ } else {+ h = (5.0 - dr) / 6.0;+ }+ } else if c.z == lo {+ h = (dr + 1.0) / 6.0;+ }+ return vec3<f32>(h, s, l);+}++fn grade_from_hsl(hsl: vec3<f32>) -> vec3<f32> {+ let h = hsl.x - floor(hsl.x);+ let s = hsl.y;+ let l = hsl.z;+ var q = (s + 1.0) * l;+ if l > 0.5 {+ q = (l + s) - l * s;+ }+ if q <= 0.0 {+ return vec3<f32>(0.0);+ }+ let i = trunc(h * 6.0);+ let p = (l + l) - q;+ let f = (h * 6.0 - i) * (q - p);+ let down = q - f;+ let up = f + p;+ let k = u32(i);+ if k == 1u {+ return vec3<f32>(down, q, p);+ }+ if k == 2u {+ return vec3<f32>(p, q, up);+ }+ if k == 3u {+ return vec3<f32>(p, down, q);+ }+ if k == 4u {+ return vec3<f32>(up, p, q);+ }+ if k == 5u {+ return vec3<f32>(q, p, down);+ }+ if k == 0u || k == 6u {+ return vec3<f32>(q, up, p);+ }+ return vec3<f32>(0.0);+}++fn grade_to_hsv(c: vec3<f32>) -> vec3<f32> {+ var p = vec4<f32>(c.y, c.z, 0.0, -1.0 / 3.0);+ if c.y < c.z {+ p = vec4<f32>(c.z, c.y, -1.0, 2.0 / 3.0);+ }+ var q = vec4<f32>(p.x, p.y, p.w, c.x);+ if p.x < c.x {+ q = vec4<f32>(c.x, p.y, p.z, p.x);+ }+ let d = q.x - min(q.w, q.y);+ let e = 1e-10;+ return vec3<f32>(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x);+}++fn grade_from_hsv(c: vec3<f32>) -> vec3<f32> {+ let f = vec3<f32>(c.x) + vec3<f32>(1.0, 2.0 / 3.0, 1.0 / 3.0);+ let x = abs((f - floor(f)) * 6.0 - vec3<f32>(3.0)) - vec3<f32>(1.0);+ let k = clamp(x, vec3<f32>(0.0), vec3<f32>(1.0)) - vec3<f32>(1.0);+ return c.z * (vec3<f32>(1.0) + k * c.y);+}++fn grade_linear(c: f32) -> f32 {+ if c > 0.04045 {+ return pow(abs((c + 0.055) / 1.055), 2.4);+ }+ return c / 12.92;+}++fn grade_lab_f(t: f32) -> f32 {+ if t > 0.008856 {+ return pow(abs(t), 0.3333);+ }+ return 7.787 * t + 16.0 / 116.0;+}++fn grade_to_lab(c: vec3<f32>) -> vec3<f32> {+ let r = grade_linear(c.x);+ let g = grade_linear(c.y);+ let b = grade_linear(c.z);+ let fx = grade_lab_f((r * 0.4124 + g * 0.3576 + b * 0.1805) / 0.95047);+ let fy = grade_lab_f(r * 0.2126 + g * 0.7152 + b * 0.0722);+ let fz = grade_lab_f((r * 0.0193 + g * 0.1192 + b * 0.9505) / 1.08883);+ return vec3<f32>(116.0 * fy - 16.0, 500.0 * (fx - fy), 200.0 * (fy - fz));+}++fn grade_lab_inverse(t: f32) -> f32 {+ let t3 = t * t * t;+ if t3 > 0.008856 {+ return t3;+ }+ return (t - 16.0 / 116.0) / 7.787;+}++fn grade_encode(t: f32) -> f32 {+ if t > 0.0031308 {+ return 1.055 * pow(abs(t), 1.0 / 2.4) - 0.055;}- c = vec3<f32>(- grade_at(GRADE_TABLES, 1u, c.x),- grade_at(GRADE_TABLES, 2u, c.y),- grade_at(GRADE_TABLES, 3u, c.z),+ return 12.92 * t;+}++fn grade_from_lab(lab: vec3<f32>) -> vec3<f32> {+ let fy = (lab.x + 16.0) / 116.0;+ let fx = lab.y / 500.0 + fy;+ let fz = fy - lab.z / 200.0;+ let x = grade_lab_inverse(fx) * 0.95047;+ let y = grade_lab_inverse(fy);+ let z = grade_lab_inverse(fz) * 1.08883;+ return vec3<f32>(+ grade_encode(x * 3.2406 + y * -1.5372 + z * -0.4986),+ grade_encode(x * -0.9689 + y * 1.8758 + z * 0.0415),+ grade_encode(x * 0.0557 + y * -0.204 + z * 1.057),);- // HSL Curves.- if sw.y != 0.0 {- let hsv = grade_hsv(max(c, vec3<f32>(0.0)));- let a = GRADE_TABLES + P.sw;- let b = a + P.sw;- let h2 = hsv.x + 0.5 * grade_within(a, 0u, hsv.x);- let s2 = hsv.y * (1.0 + grade_within(a, 1u, hsv.x)) * (1.0 + grade_within(a, 3u, hsv.y))- * (1.0 + grade_within(b, 1u, hsv.z));- let v2 = hsv.z * (1.0 + grade_within(a, 2u, hsv.x) + grade_within(b, 0u, hsv.y));- c = grade_from_hsv(vec3<f32>(h2, max(s2, 0.0), max(v2, 0.0)));+}++// One HSL Curve (`kind`, its table `n` entries from `at`) on a color: its+// key from the color as it is.+fn grade_hsl_curve(kind: u32, at: u32, n: u32, c: vec3<f32>) -> vec3<f32> {+ if kind == 0u {+ let hsv = grade_to_hsv(c);+ var h = hsv.x - (grade_lookup(at, n, hsv.x) - 0.5);+ if h < 0.0 {+ h += 1.0;+ }+ if h > 1.0 {+ h -= 1.0;+ }+ return grade_from_hsv(vec3<f32>(h, hsv.y, hsv.z));+ }+ let hsl = grade_to_hsl(c);+ if kind == 1u || kind == 3u || kind == 5u {+ var key = hsl.x;+ if kind == 3u {+ key = hsl.y;+ } else if kind == 5u {+ key = grade_to_lab(c).x / GRADE_WHITE_L;+ }+ let z = grade_lookup(at, n, key);+ return grade_from_hsl(vec3<f32>(hsl.x, clamp(hsl.y * 2.0 * z, 0.0, 1.0), hsl.z));+ }+ let lab = grade_to_lab(c);+ var scale = 0.0;+ if kind == 2u {+ let w = grade_lookup(at, n, hsl.x);+ var weight = 0.0;+ if lab.x > 60.0 {+ weight = (-1.0 / 35.6) * lab.x + 2.68;+ } else if lab.x > 30.0 {+ weight = lab.x / 30.0 - 1.0;+ }+ var chroma = min(hsl.y, 2.0 - 2.0 * hsl.z) - 1.0;+ if hsl.z <= 0.5 {+ chroma = min(hsl.y, 2.0 * hsl.z) - 1.0;+ }+ weight *= 1.75 / (1.0 + 18.0 * chroma * chroma);+ scale = 1.0 - (1.0 - (2.25 * w - 0.125)) * weight;+ } else {+ scale = 2.0 * grade_lookup(at, n, hsl.y);}- return c;+ return grade_from_lab(vec3<f32>(clamp(lab.x * scale, 0.0, GRADE_WHITE_L), lab.y, lab.z));+}++fn grade_cdl_one(v: f32, slope: f32, offset: f32, power: f32) -> f32 {+ let x = v * slope + offset;+ if x > 0.0 {+ return pow(x, power);+ }+ return x;+}++// The CDL whose slope, offset and power are rows `row` to `row` + 2.+fn grade_cdl(row: u32, c: vec3<f32>) -> vec3<f32> {+ let s = src[row].xyz;+ let o = src[row + 1u].xyz;+ let p = src[row + 2u].xyz;+ return vec3<f32>(+ grade_cdl_one(c.x, s.x, o.x, p.x),+ grade_cdl_one(c.y, s.y, o.y, p.y),+ grade_cdl_one(c.z, s.z, o.z, p.z),+ );+}++fn grade_color(color: vec3<f32>) -> vec3<f32> {+ var c = grade_hold(color);+ let s0 = src[0u];+ let s1 = src[1u];+ let s2 = src[2u];+ let s3 = src[3u];+ let s4 = src[4u];+ // The HSL Curves, each keyed on what the one before made.+ let curves = u32(s1.w);+ for (var k = 0u; k < curves; k++) {+ let d = src[16u + k];+ c = grade_hold(grade_hsl_curve(u32(d.x), u32(d.y), u32(d.z), c));+ }+ // The first part: White Balance, Levels, the RL wheels, the Color+ // Curves.+ if s0.x != 0.0 {+ let lin = pow(max(c, vec3<f32>(0.0)), vec3<f32>(2.4));+ let m = vec3<f32>(dot(src[5u].xyz, lin), dot(src[6u].xyz, lin), dot(src[7u].xyz, lin));+ c = pow(max(m, vec3<f32>(0.0)), vec3<f32>(1.0 / 2.4));+ }+ if s0.y != 0.0 {+ let l = src[8u];+ c = vec3<f32>(l.z) + (c - vec3<f32>(l.x)) * ((l.w - l.z) / (l.y - l.x));+ }+ if s0.z != 0.0 {+ c = vec3<f32>(grade_table(0u, c.x), grade_table(1u, c.y), grade_table(2u, c.z));+ }+ if s0.w != 0.0 {+ c = vec3<f32>(grade_table(3u, c.x), grade_table(3u, c.y), grade_table(3u, c.z));+ }+ if s1.x != 0.0 {+ c = vec3<f32>(grade_table(4u, c.x), grade_table(5u, c.y), grade_table(6u, c.z));+ }+ if s1.y != 0.0 {+ c = vec3<f32>(grade_table(7u, c.x), grade_table(7u, c.y), grade_table(7u, c.z));+ }+ c = grade_hold(c);+ // The second: Lift, then Gain, Offset and Gamma by channel, then by Y.+ if s1.z != 0.0 {+ let l = src[9u].xyz;+ c = l + c * (vec3<f32>(1.0) - l);+ }+ if s4.z != 0.0 {+ c = grade_cdl(10u, c);+ }+ if s4.w != 0.0 {+ c = grade_cdl(13u, c);+ }+ c = grade_hold(c);+ // The third, and the HSL after it.+ if s2.x != 1.0 {+ let y = dot(vec3<f32>(0.2126, 0.7152, 0.0722), c);+ c = vec3<f32>(y) + s2.x * (c - vec3<f32>(y));+ }+ c = c * s2.y + vec3<f32>(s2.z);+ if s3.x != 0.0 {+ c = c + s3.x * (c - vec3<f32>(s3.y));+ }+ if s2.w != 0.0 {+ let e = c * s3.z;+ c = vec3<f32>(grade_table(8u, e.x), grade_table(8u, e.y), grade_table(8u, e.z));+ }+ let hsl = grade_to_hsl(c);+ c = grade_from_hsl(vec3<f32>(+ hsl.x + s3.w,+ clamp(hsl.y * s4.x, 0.0, 1.0),+ clamp(hsl.z * s4.y, 0.0, 1.0),+ ));+ return grade_hold(c);}@compute @workgroup_size(16, 16)@@ -706,7 +859,7 @@ fn grade(@builtin(global_invocation_id) id: vec3<u32>) {dst[o] = vec4<f32>(0.0, 0.0, 0.0, a);return;}- dst[o] = vec4<f32>(grade_steps(px.xyz / a) * a, a);+ dst[o] = vec4<f32>(grade_color(px.xyz / a) * a, a);}// Bézier Masking (`bv-effects`'s plug-in, the same math as its render):diff --git a/crates/gpu/src/shaders/pair.wgsl b/crates/gpu/src/shaders/pair.wgslindex 3aa87e1..0d990d9 100644--- a/crates/gpu/src/shaders/pair.wgsl+++ b/crates/gpu/src/shaders/pair.wgsl@@ -132,6 +132,185 @@ fn place(@builtin(global_invocation_id) id: vec3<u32>) {}}+// A pixel of the source, the edge's past its edges.+fn held(x: i32, y: i32) -> vec4<f32> {+ let cx = clamp(x, 0, i32(P.sw) - 1);+ let cy = clamp(y, 0, i32(P.sh) - 1);+ return src[u32(cy) * P.sw + u32(cx)];+}++// A pixel of the source for a turned or mirrored picture: past its left and+// bottom edges nothing, past its others one pixel more of the edge's and then+// nothing.+fn open(x: i32, y: i32) -> vec4<f32> {+ if x < 0 || y >= i32(P.sh) || x > i32(P.sw) || y < -1 {+ return vec4<f32>(0.0);+ }+ return held(x, y);+}++fn mix_four(a: vec4<f32>, b: vec4<f32>, c: vec4<f32>, d: vec4<f32>, fx: f32, fy: f32) -> vec4<f32> {+ let top = vec4<f32>(a.x + (b.x - a.x) * fx, a.y + (b.y - a.y) * fx, a.z + (b.z - a.z) * fx, a.w + (b.w - a.w) * fx);+ let bottom = vec4<f32>(c.x + (d.x - c.x) * fx, c.y + (d.y - c.y) * fx, c.z + (d.z - c.z) * fx, c.w + (d.w - c.w) * fx);+ return vec4<f32>(+ top.x + (bottom.x - top.x) * fy,+ top.y + (bottom.y - top.y) * fy,+ top.z + (bottom.z - top.z) * fy,+ top.w + (bottom.w - top.w) * fy,+ );+}++fn bilinear_held(u: f32, v: f32) -> vec4<f32> {+ let x0 = floor(u);+ let y0 = floor(v);+ let x = i32(x0);+ let y = i32(y0);+ return mix_four(held(x, y), held(x + 1, y), held(x, y + 1), held(x + 1, y + 1), u - x0, v - y0);+}++fn bilinear_open(u: f32, v: f32) -> vec4<f32> {+ let x0 = floor(u);+ let y0 = floor(v);+ let x = i32(x0);+ let y = i32(y0);+ return mix_four(open(x, y), open(x + 1, y), open(x, y + 1), open(x + 1, y + 1), u - x0, v - y0);+}++fn bicubic_held(u: f32, v: f32) -> vec4<f32> {+ let x0 = floor(u);+ let y0 = floor(v);+ let wx = catmull_rom(u - x0);+ let wy = catmull_rom(v - y0);+ let xi = i32(x0);+ let yi = i32(y0);+ var o = vec4<f32>(0.0);+ for (var j = 0; j < 4; j++) {+ for (var i = 0; i < 4; i++) {+ let p = held(xi - 1 + i, yi - 1 + j);+ let k = wx[i] * wy[j];+ o = vec4<f32>(o.x + p.x * k, o.y + p.y * k, o.z + p.z * k, o.w + p.w * k);+ }+ }+ return vec4<f32>(max(o.x, 0.0), max(o.y, 0.0), max(o.z, 0.0), clamp(o.w, 0.0, 1.0));+}++// A picture of the media where a Pan/Crop places it, without a turn or a+// mirror: `f[0..6]` from the frame to the picture, `i` the pixels it reaches,+// its edges hard. `j.x` 0 nearest, 1 bilinear, 2 bicubic.+@compute @workgroup_size(16, 16)+fn place_hard(@builtin(global_invocation_id) id: vec3<u32>) {+ let o = out_index(id);+ if o < 0 {+ return;+ }+ let px = i32(id.x);+ let py = i32(id.y);+ if px < P.i.x || py < P.i.y || px >= P.i.z || py >= P.i.w {+ dst[o] = vec4<f32>(0.0);+ return;+ }+ let cx = f32(id.x) + 0.5;+ let cy = f32(id.y) + 0.5;+ let u = pf(0u) * cx + pf(1u) * cy + pf(2u) - 0.5;+ let v = pf(3u) * cx + pf(4u) * cy + pf(5u) - 0.5;+ switch P.j.x {+ case 0u: {+ dst[o] = held(i32(rround(u)), i32(rround(v)));+ }+ case 2u: {+ dst[o] = bicubic_held(u, v);+ }+ default: {+ dst[o] = bilinear_held(u, v);+ }+ }+}++// How much of a unit pixel lies on the inner side of a line `d` from its+// middle, the line's normal `(nx, ny)`.+fn line_share(d: f32, nx: f32, ny: f32) -> f32 {+ let a = max(nx, ny);+ let b = min(nx, ny);+ let reach = (a + b) * 0.5;+ if d >= reach {+ return 1.0;+ }+ if d <= -reach {+ return 0.0;+ }+ let m = abs(d);+ if m <= (a - b) * 0.5 {+ return 0.5 + d / a;+ }+ let r = reach - m;+ let corner = r * r / (2.0 * a * b);+ if d > 0.0 {+ return 1.0 - corner;+ }+ return corner;+}++// How much of a pixel lies between two lines: where `v` (changing by+// `(gx, gy)` a pixel) is `lo` and `hi`.+fn between_share(v: f32, gx: f32, gy: f32, lo: f32, hi: f32) -> f32 {+ let l = sqrt(gx * gx + gy * gy);+ if l <= 0.0 {+ return 1.0;+ }+ let nx = abs(gx) / l;+ let ny = abs(gy) / l;+ return min(line_share((v - lo) / l, nx, ny), line_share((hi - v) / l, nx, ny));+}++// The same for a turned or mirrored picture: `f[6..12]` from the frame to the+// box's own place (0–1 each way), `f[12..16]` what a crop leaves of the+// picture; both their edges as soft as the pixels they cross.+@compute @workgroup_size(16, 16)+fn place_soft(@builtin(global_invocation_id) id: vec3<u32>) {+ let o = out_index(id);+ if o < 0 {+ return;+ }+ let px = i32(id.x);+ let py = i32(id.y);+ if px < P.i.x || py < P.i.y || px >= P.i.z || py >= P.i.w {+ dst[o] = vec4<f32>(0.0);+ return;+ }+ let cx = f32(id.x) + 0.5;+ let cy = f32(id.y) + 0.5;+ let uc = pf(0u) * cx + pf(1u) * cy + pf(2u);+ let vc = pf(3u) * cx + pf(4u) * cy + pf(5u);+ // Measured as sixteen bands a line do, each at its top.+ let cy_edge = cy - 0.03125;+ let a = pf(6u) * cx + pf(7u) * cy_edge + pf(8u);+ let b = pf(9u) * cx + pf(10u) * cy_edge + pf(11u);+ let ue = pf(0u) * cx + pf(1u) * cy_edge + pf(2u);+ let ve = pf(3u) * cx + pf(4u) * cy_edge + pf(5u);+ let share = min(+ min(between_share(a, pf(6u), pf(7u), 0.0, 1.0), between_share(b, pf(9u), pf(10u), 0.0, 1.0)),+ min(+ between_share(ue, pf(0u), pf(1u), pf(12u), pf(14u)),+ between_share(ve, pf(3u), pf(4u), pf(13u), pf(15u)),+ ),+ );+ if share <= 0.0 {+ dst[o] = vec4<f32>(0.0);+ return;+ }+ let u = uc - 0.5;+ let v = vc - 0.5;+ var picture = vec4<f32>(0.0);+ if P.j.x == 0u {+ picture = open(i32(rround(u)), i32(rround(v)));+ } else if P.j.x == 2u && u >= 1.0 && v >= 1.0 && u <= f32(P.sw) - 3.0 && v <= f32(P.sh) - 3.0 {+ picture = bicubic_held(u, v);+ } else {+ picture = bilinear_open(u, v);+ }+ dst[o] = vec4<f32>(picture.x * share, picture.y * share, picture.z * share, picture.w * share);+}+// Half the size, each pixel the average of 2 × 2.@compute @workgroup_size(16, 16)fn half_size(@builtin(global_invocation_id) id: vec3<u32>) {diff --git a/crates/gpu/tests/parity.rs b/crates/gpu/tests/parity.rsindex cfa1bf7..c081029 100644--- a/crates/gpu/tests/parity.rs+++ b/crates/gpu/tests/parity.rs@@ -445,7 +445,7 @@ fn pan_crop_masks() {let s = Tick::from_seconds;let (mut p, bars, _) = bars_and_gradient();let info = p.media(p.clip(bars).unwrap().media).unwrap().video.unwrap();- let (w, h) = (info.width as f32, info.height as f32);+ let (w, h) = (info.width as f64, info.height as f64);let mut oval = MaskPath::oval([0.1 * w, 0.1 * h], [0.8 * w, 0.9 * h]);oval.feather = MaskFeather::Both;oval.feather_pct = 4.0;@@ -458,13 +458,17 @@ fn pan_crop_masks() {};mask.add_path(oval);mask.add_path(hole);+ p.set_clip_framing(+ bars,+ &Transform {+ scale: 0.8,+ rotation_deg: 10.0,+ x: 0.05,+ ..Transform::default()+ },+ )+ .unwrap();let event = p.clip_mut(bars).unwrap();- event.transform = Transform {- scale: 0.8,- rotation_deg: 10.0,- x: 0.05,- ..Transform::default()- };event.mask = Some(mask.clone());check(&mut c, "pan/crop masks cutting", &p, s(1), TOL);let event = p.clip_mut(bars).unwrap();@@ -521,7 +525,7 @@ fn framing_and_qualities() {let v = p.tracks[0].id;let bars = media(&mut p, Generator::Checkerboard { size: 7 });let id = p.insert_media(bars, Tick::ZERO, Some(v), None).unwrap()[0];- p.clip_mut(id).unwrap().transform = *tf;+ p.set_clip_framing(id, tf).unwrap();check(&mut c, &format!("{quality:?} {name}"), &p, Tick::ZERO, TOL);}}@@ -565,13 +569,16 @@ fn framing_and_qualities() {let v = p.tracks[0].id;let bars = media(&mut p, Generator::Checkerboard { size: 3 });let id = p.insert_media(bars, Tick::ZERO, Some(v), None).unwrap()[0];- let clip = p.clip_mut(id).unwrap();- clip.reduce_flicker = true;- clip.transform = Transform {- scale: 0.7,- y: 0.1,- ..Transform::default()- };+ p.clip_mut(id).unwrap().reduce_flicker = true;+ p.set_clip_framing(+ id,+ &Transform {+ scale: 0.7,+ y: 0.1,+ ..Transform::default()+ },+ )+ .unwrap();check(&mut c, "reduce interlace flicker", &p, Tick::ZERO, TOL);}diff --git a/crates/gpu/tests/warmup.rs b/crates/gpu/tests/warmup.rsnew file mode 100644index 0000000..e786262--- /dev/null+++ b/crates/gpu/tests/warmup.rs@@ -0,0 +1,23 @@+//! How long the graphics card takes to compile every kernel, each one's+//! time with `BV_GPU_TRACE=1`:+//! `cargo test -p bv-gpu --test warmup -- --ignored --nocapture`.++#![allow(clippy::print_stdout)]++use std::time::Instant;++use bv_gpu::Gpu;++#[test]+#[ignore = "measures the card"]+fn every_kernel_compiles_in_time() {+ let start = Instant::now();+ let Ok(g) = Gpu::open(None) else {+ println!("no graphics card: skipped");+ return;+ };+ println!("opened {:?} in {:?}", g.adapter().name, start.elapsed());+ let start = Instant::now();+ g.warm_up().expect("every kernel compiles");+ println!("every kernel in {:?}", start.elapsed());+}diff --git a/crates/mixer/src/dsp.rs b/crates/mixer/src/dsp.rsindex 6e544e1..edd164a 100644--- a/crates/mixer/src/dsp.rs+++ b/crates/mixer/src/dsp.rs@@ -5,7 +5,7 @@//! Cada efeito guarda estado entre blocos; a mixagem recria o estado quando//! a leitura pula (busca) para não "vazar" som de outro lugar.-use bv_timeline::{Effect, EffectKind};+use bv_timeline::{Effect, EffectKind, Tempo};fn db(x: f32) -> f32 {10f32.powf(x / 20.0)@@ -32,8 +32,6 @@ pub(crate) enum Shape {Peak,HighPass,LowPass,- /// Constant 0 dB peak.- BandPass,}pub(crate) fn design(shape: Shape, rate: f32, freq: f32, q: f32, gain_db: f32) -> Coeffs {@@ -89,7 +87,6 @@ pub(crate) fn design(shape: Shape, rate: f32, freq: f32, q: f32, gain_db: f32) --2.0 * cos,1.0 - alpha,),- Shape::BandPass => (alpha, 0.0, -alpha, 1.0 + alpha, -2.0 * cos, 1.0 - alpha),};Coeffs {b0: b0 / a0,@@ -261,7 +258,8 @@ enum State {damp: f32,mix: f32,},- ModernEq(Box<crate::modern_eq::Eq>),+ /// One of the effects that follow VEGAS's ([`crate::fx`]).+ Own(Box<dyn crate::fx::Own>),#[cfg(not(target_family = "wasm"))]Vst(Box<crate::vst::Run>),}@@ -294,6 +292,14 @@ pub struct Processor {impl Processor {pub fn new(e: &Effect, rate: u32, channels: usize) -> Processor {+ if let Some(own) = crate::fx::make(e, rate, channels) {+ return Processor {+ kind: e.kind,+ params: e.params.clone(),+ vst: None,+ state: State::Own(own),+ };+ }let r = rate as f32;let p = |i: usize| e.param(i);let state = match e.kind {@@ -366,9 +372,6 @@ impl Processor {mix: p(2),}}- EffectKind::ModernEq => {- State::ModernEq(Box::new(crate::modern_eq::Eq::new(e, rate, channels)))- }// A plug-in that cannot load lets the sound through.#[cfg(not(target_family = "wasm"))]EffectKind::Vst => match e@@ -400,12 +403,20 @@ impl Processor {self.kind == e.kind && self.params == e.params && self.vst == vst_key(e)}- /// How many samples late its output comes: a VST 3 plug-in's latency- /// (BananaV's own effects answer at once).+ /// The project's tempo, for the effects with tempo sync.+ pub fn keep_time(&mut self, tempo: &Tempo) {+ if let State::Own(own) = &mut self.state {+ own.keep_time(tempo);+ }+ }++ /// How many samples late its output comes: a VST 3 plug-in's latency,+ /// or that of one of BananaV's own effects working in blocks (FFTs).pub fn latency(&self) -> usize {match &self.state {#[cfg(not(target_family = "wasm"))]State::Vst(run) => run.latency(),+ State::Own(own) => own.latency(),#[cfg(test)]State::Gain(_) => FAKE_LATENCY.with(std::cell::Cell::get),_ => 0,@@ -421,8 +432,15 @@ impl Processor {/// Takes `e`'s values while it runs, keeping what it holds — filters'/// memory, envelopes, delay lines and reverb tails — so that values/// that change as it plays (FX automation, a slider dragged) do not- /// click; the Modern Equalizer starts again.+ /// click.pub fn retune(&mut self, e: &Effect, rate: u32, channels: usize) {+ if let State::Own(own) = &mut self.state+ && self.kind == e.kind+ {+ own.set(&crate::fx::params_of(e));+ self.params = e.params.clone();+ return;+ }let fresh = Processor::new(e, rate, channels);match (&mut self.state, fresh.state) {(State::Gain(g), State::Gain(n)) => *g = n,@@ -529,6 +547,7 @@ impl Processor {pub fn process(&mut self, channels: &mut [Vec<f32>]) {let n = channels.first().map_or(0, Vec::len);match &mut self.state {+ State::Own(own) => own.process(channels),State::Gain(g) => {for ch in channels.iter_mut() {for s in ch.iter_mut() {@@ -628,7 +647,6 @@ impl Processor {}}}- State::ModernEq(eq) => eq.process(channels),#[cfg(not(target_family = "wasm"))]State::Vst(run) => run.process(channels),}@@ -645,6 +663,8 @@ pub struct Chain {slots: Vec<usize>,rate: u32,channels: usize,+ /// The project's tempo, for the effects that keep time with it.+ tempo: Tempo,}impl Chain {@@ -699,7 +719,11 @@ impl Chain {p.follow(e);p}- _ => Processor::new(e, rate, channels),+ _ => {+ let mut p = Processor::new(e, rate, channels);+ p.keep_time(&self.tempo);+ p+ }};(p, e.enabled)})@@ -712,6 +736,16 @@ impl Chain {self.procs.is_empty()}+ /// The project's tempo (the effects with tempo sync follow it).+ pub fn set_tempo(&mut self, tempo: Tempo) {+ if tempo != self.tempo {+ self.tempo = tempo;+ for (p, _) in &mut self.procs {+ p.keep_time(&tempo);+ }+ }+ }+/// Zera o estado (depois de uma busca).pub fn reset(&mut self) {self.procs.clear();diff --git a/crates/mixer/src/fft.rs b/crates/mixer/src/fft.rsindex ec7698e..1be7369 100644--- a/crates/mixer/src/fft.rs+++ b/crates/mixer/src/fft.rs@@ -93,6 +93,85 @@ pub fn fft(data: &mut [Complex], inverse: bool) {}}+/// A transform of one length made ready once — its twiddles and the+/// order its input is read in — for the effects that run it on every+/// block.+#[derive(Clone, Debug, Default)]+pub struct Plan {+ twiddles: Vec<Complex>,+ order: Vec<u32>,+}++impl Plan {+ /// For `n` points, a power of two.+ pub fn new(n: usize) -> Plan {+ assert!(n.is_power_of_two(), "the FFT's length is a power of two");+ let bits = n.trailing_zeros();+ let order = (0..n)+ .map(|i| {+ if n < 2 {+ 0+ } else {+ (i.reverse_bits() >> (usize::BITS - bits)) as u32+ }+ })+ .collect();+ let twiddles = (0..n / 2)+ .map(|k| {+ let a = -std::f64::consts::TAU * k as f64 / n as f64;+ Complex::new(a.cos(), a.sin())+ })+ .collect();+ Plan { twiddles, order }+ }++ pub fn len(&self) -> usize {+ self.order.len()+ }++ pub fn is_empty(&self) -> bool {+ self.order.is_empty()+ }++ /// [`fft`] on `data`, as long as the plan.+ pub fn run(&self, data: &mut [Complex], inverse: bool) {+ let n = data.len();+ assert_eq!(n, self.len(), "the data is as long as the plan");+ if n < 2 {+ return;+ }+ for (i, &j) in self.order.iter().enumerate() {+ let j = j as usize;+ if j > i {+ data.swap(i, j);+ }+ }+ let mut len = 2;+ while len <= n {+ let half = len / 2;+ let step = n / len;+ for block in data.chunks_exact_mut(len) {+ let (a, b) = block.split_at_mut(half);+ for (k, (u, v)) in a.iter_mut().zip(b.iter_mut()).enumerate() {+ let w = self.twiddles[k * step];+ let w = if inverse { w.conj() } else { w };+ let t = *v * w;+ *v = *u - t;+ *u = *u + t;+ }+ }+ len <<= 1;+ }+ if inverse {+ let s = 1.0 / n as f64;+ for d in data {+ d.re *= s;+ d.im *= s;+ }+ }+ }+}+/// The spectrum of real signal `x`, padded with zeros to `n` (a power of/// two).pub fn spectrum(x: &[f64], n: usize) -> Vec<Complex> {diff --git a/crates/mixer/src/fx/delays.rs b/crates/mixer/src/fx/delays.rsnew file mode 100644index 0000000..57bde82--- /dev/null+++ b/crates/mixer/src/fx/delays.rs@@ -0,0 +1,416 @@+//! Simple Delay and Multi-Tap Delay, as VEGAS's.+//!+//! Simple Delay: a line a channel as long as the delay. What+//! leaves the line is the echo; with Multiple delays it also goes back in,+//! scaled so the echoes fall 30 dB in the decay time (a comb filter).+//! Changing the delay's length starts the lines again, silent.++use bv_timeline::Tempo;+use bv_timeline::audio_fx::{multi_tap_delay as mt, simple_delay as sd, tempo};++use super::{Own, Ramp, db_gain};++/// Added and taken away again where a fed-back signal fades, so it ends+/// at 0 instead of lingering as a denormal number (slow on processors).+const FLUSH: f32 = 1e-18;++#[derive(Debug)]+pub(crate) struct SimpleDelay {+ rate: f64,+ params: Vec<f32>,+ tempo: Tempo,+ dry: Ramp,+ wet: Ramp,+ /// What goes back into the line each time round (0: one echo).+ feedback: f32,+ /// A line a channel, each `len` long.+ lines: Vec<Vec<f32>>,+ len: usize,+ /// Where the lines are read and written.+ at: usize,+}++impl SimpleDelay {+ pub(crate) fn new(rate: u32) -> SimpleDelay {+ SimpleDelay {+ rate: rate.max(1) as f64,+ params: Vec::new(),+ tempo: Tempo::default(),+ dry: Ramp::new(0.5),+ wet: Ramp::new(0.5),+ feedback: 0.0,+ lines: Vec::new(),+ len: 2,+ at: 0,+ }+ }++ fn param(&self, i: usize) -> f32 {+ self.params+ .get(i)+ .copied()+ .unwrap_or_else(|| sd::PARAMS[i].default)+ }++ /// A time in seconds, or a note of the tempo times a multiplier.+ fn seconds(&self, time: usize, sync: usize, note: usize, multiplier: usize) -> f64 {+ let spec = &sd::PARAMS;+ if self.param(sync) >= 0.5 {+ let m = &spec[multiplier];+ tempo::seconds(self.param(note), &self.tempo)+ * self.param(multiplier).clamp(m.min, m.max) as f64+ } else {+ let t = &spec[time];+ self.param(time).clamp(t.min, t.max) as f64+ }+ }++ fn update(&mut self) {+ let delay = self.seconds(sd::TIME, sd::SYNC, sd::NOTE, sd::MULTIPLIER);+ let len = ((delay * self.rate).round() as usize).max(2);+ let decay = self.seconds(+ sd::DECAY,+ sd::DECAY_SYNC,+ sd::DECAY_NOTE,+ sd::DECAY_MULTIPLIER,+ );+ // How many times round the line the decay time lasts.+ let rounds = decay * self.rate / len as f64;+ self.feedback = if self.param(sd::MULTIPLE) >= 0.5 && rounds >= 0.1 {+ // −30 dB after the decay time.+ 10f64.powf(-1.5 / rounds) as f32+ } else {+ 0.0+ };+ if len != self.len {+ self.len = len;+ for line in &mut self.lines {+ line.clear();+ line.resize(len, 0.0);+ }+ self.at = 0;+ }+ self.dry.set(db_gain(self.param(sd::DRY), -80.0));+ self.wet.set(db_gain(self.param(sd::WET), -80.0));+ }+}++impl Own for SimpleDelay {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ self.update();+ }++ fn keep_time(&mut self, tempo: &Tempo) {+ self.tempo = *tempo;+ self.update();+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let (dry, dry_step) = self.dry.block(n);+ let (wet, wet_step) = self.wet.block(n);+ let len = self.len;+ if self.lines.len() != channels.len() {+ self.lines.resize_with(channels.len(), || vec![0.0; len]);+ }+ let g = self.feedback;+ let mut end = self.at;+ for (ch, line) in channels.iter_mut().zip(self.lines.iter_mut()) {+ let mut at = self.at;+ let mut i = 0;+ while i < n {+ // Up to the line's end: nothing read here was written in+ // this stretch, so its samples go together (vectorized).+ let m = (len - at).min(n - i);+ let base = i as f32;+ let samples = ch[i..i + m].iter_mut().zip(line[at..at + m].iter_mut());+ for (k, (x, d)) in samples.enumerate() {+ let t = base + k as f32;+ let echo = *d;+ *d = (*x + g * echo + FLUSH) - FLUSH;+ *x = (dry + dry_step * t) * *x + (wet + wet_step * t) * echo;+ }+ i += m;+ at += m;+ if at == len {+ at = 0;+ }+ }+ end = at;+ }+ self.at = end;+ }+}++/// Each tap's fixed nudge (ms) and share of the modulation's swing.+const TAP_NUDGE: [f32; 8] = [0.123, 0.377, -0.411, 0.095, -0.301, -0.253, 0.457, 0.179];+const TAP_SWING: [f32; 8] = [0.7, 0.9, 0.4, 0.6, 0.8, 0.9, 0.1, 0.9];++/// The line's room: the longest tap and its nudge, a little more.+const MULTI_TAP_SECONDS: f64 = 2.6;++/// Multi-Tap Delay, as VEGAS's: the channels at the input gain (darkened+/// by the low-pass when on) go, averaged, into one line, with the taps'+/// sums fed back (the feedback over the taps' total level when that is+/// more than 1, so the loop never runs away). Each tap reads it at its+/// time, a little nudged, shortened by a sine swing (one for all taps,+/// each its own share of it), and plays at its gain on its side of the+/// stereo picture; the taps' sums go out through the low-pass too.+#[derive(Debug)]+pub(crate) struct MultiTapDelay {+ rate: f32,+ params: Vec<f32>,+ line: Vec<f32>,+ mask: usize,+ at: usize,+ phase: f64,+ /// The input's and the two sums' low-pass memories.+ lows: [f32; 4],+}++impl MultiTapDelay {+ pub(crate) fn new(rate: u32) -> MultiTapDelay {+ let fs = rate.max(1) as f64;+ let n = ((MULTI_TAP_SECONDS * fs) as usize).next_power_of_two();+ MultiTapDelay {+ rate: fs as f32,+ params: Vec::new(),+ line: vec![0.0; n],+ mask: n - 1,+ at: 0,+ phase: 0.0,+ lows: [0.0; 4],+ }+ }++ fn p(&self, i: usize) -> f32 {+ let s = &mt::PARAMS[i];+ self.params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+ }++ /// The line `d` samples back (1 the newest), between samples.+ fn read(&self, d: f32) -> f32 {+ let d = d.max(1.0);+ let whole = d.floor();+ let part = d - whole;+ let i = whole as usize;+ let a = self.line[(self.at + self.line.len() - (i - 1)) & self.mask];+ let b = self.line[(self.at + self.line.len() - i) & self.mask];+ a + (b - a) * part+ }+}++impl Own for MultiTapDelay {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let fs = self.rate;+ let input = db_gain(self.p(mt::INPUT), -80.0);+ let dry = db_gain(self.p(mt::DRY), -80.0);+ let wet = db_gain(self.p(mt::WET), -80.0);+ let p = if self.p(mt::LOW_PASS) >= 0.5 {+ (-std::f32::consts::TAU * self.p(mt::LOW_FREQ) / fs).exp()+ } else {+ 0.0+ };+ let count = self.p(mt::TAPS).round() as usize;+ let depth = self.p(mt::DEPTH) * 3e-5 * fs;+ let step = std::f64::consts::TAU * self.p(mt::RATE) as f64 / fs as f64;+ // Each tap: its delay (samples), swing, and levels to the left and+ // right (its pan, −1 to 1, is positive to the left).+ let taps: Vec<(f32, f32, f32, f32)> = (0..count)+ .map(|k| {+ let at = mt::TAP + k * mt::PER_TAP;+ let g = self.p(at + mt::GAIN);+ let pan = -self.p(at + mt::PAN);+ let (left, right) = if pan <= 0.0 {+ (g, (pan + 1.0) * g)+ } else {+ ((1.0 - pan) * g, g)+ };+ let delay = (self.p(at + mt::DELAY) + TAP_NUDGE[k]) * fs / 1000.0;+ (delay, depth * TAP_SWING[k], left, right)+ })+ .collect();+ let total: f32 = taps.iter().map(|t| t.2.abs().max(t.3.abs())).sum();+ let feedback = self.p(mt::FEEDBACK) / total.max(1.0);+ let stereo = channels.len() >= 2;+ let [mut low_l, mut low_r, mut out_l, mut out_r] = self.lows;+ for i in 0..n {+ let swing = (self.phase.sin() + 1.0) as f32;+ self.phase = (self.phase + step) % std::f64::consts::TAU;+ let (mut sum_l, mut sum_r) = (0.0, 0.0);+ for &(delay, depth, left, right) in &taps {+ let tap = self.read(delay - swing * depth);+ sum_l += left * tap;+ sum_r += right * tap;+ }+ let x_l = channels[0][i];+ let x_r = if stereo { channels[1][i] } else { x_l };+ low_l = (1.0 - p) * input * x_l + p * low_l;+ low_r = (1.0 - p) * input * x_r + p * low_r;+ let into = if stereo {+ ((sum_l + sum_r) * feedback + low_l + low_r) / 2.0+ } else {+ (sum_l + sum_r) / 2.0 * feedback + low_l+ };+ self.at = (self.at + 1) & self.mask;+ self.line[self.at] = ((into + FLUSH) - FLUSH).clamp(-16_777_216.0, 16_777_216.0);+ out_l = (1.0 - p) * sum_l + p * out_l;+ out_r = (1.0 - p) * sum_r + p * out_r;+ if stereo {+ channels[0][i] = dry * input * x_l + wet * out_l;+ channels[1][i] = dry * input * x_r + wet * out_r;+ for ch in channels.iter_mut().skip(2) {+ ch[i] *= dry * input;+ }+ } else {+ channels[0][i] = dry * input * x_l + wet * (out_l + out_r) / 2.0;+ }+ }+ self.lows = [low_l, low_r, out_l, out_r];+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn delay(values: &[(usize, f32)]) -> SimpleDelay {+ let mut d = SimpleDelay::new(48_000);+ let mut p: Vec<f32> = sd::PARAMS.iter().map(|s| s.default).collect();+ for &(i, v) in values {+ p[i] = v;+ }+ d.set(&p);+ d+ }++ fn click(n: usize) -> Vec<f32> {+ let mut v = vec![0.0; n];+ v[0] = 1.0;+ v+ }++ #[test]+ fn one_echo_after_the_delay() {+ let mut d = delay(&[(sd::DRY, 0.0), (sd::WET, -6.0), (sd::TIME, 0.25)]);+ let mut ch = vec![click(30_000)];+ d.process(&mut ch);+ let out = &ch[0];+ assert!((out[0] - 1.0).abs() < 1e-6);+ // 250 ms at 48 kHz, −6 dB; nothing more.+ assert!((out[12_000] - 0.501).abs() < 1e-3, "{}", out[12_000]);+ assert!(out[1..12_000].iter().all(|s| *s == 0.0));+ assert!(out[12_001..].iter().all(|s| *s == 0.0));+ }++ #[test]+ fn feedback_falls_30_db_in_the_decay_time() {+ // 250 ms delay, 1 s decay: each echo 0.0316^0.25 of the one before+ // (about 7.5 dB down).+ let mut d = delay(&[+ (sd::DRY, -80.0),+ (sd::WET, 0.0),+ (sd::TIME, 0.25),+ (sd::MULTIPLE, 1.0),+ (sd::DECAY, 1.0),+ ]);+ let mut ch = [click(61_000)];+ // In blocks of an odd length, across the line's end.+ for block in ch[0].chunks_mut(1_000) {+ let mut b = vec![block.to_vec()];+ d.process(&mut b);+ block.copy_from_slice(&b[0]);+ }+ let out = &ch[0];+ assert_eq!(out[0], 0.0);+ let ratio = out[24_000] / out[12_000];+ assert!((ratio - 0.031_622_8f32.powf(0.25)).abs() < 1e-4, "{ratio}");+ // −30 dB after the decay time (four echoes on).+ let db = 20.0 * (out[60_000] / out[12_000]).log10();+ assert!((db + 30.0).abs() < 0.1, "{db}");+ }++ #[test]+ fn tempo_sync_takes_a_note_of_the_tempo() {+ // An eighth note at 120 BPM: 250 ms.+ let mut d = delay(&[+ (sd::DRY, -80.0),+ (sd::WET, 0.0),+ (sd::SYNC, 1.0),+ (sd::NOTE, 10.0),+ ]);+ let mut ch = vec![click(20_000)];+ d.process(&mut ch);+ assert!((ch[0][12_000] - 1.0).abs() < 1e-6);+ // At 60 BPM, twice as late.+ d.keep_time(&Tempo {+ beats_per_minute: 60.0,+ ..Tempo::default()+ });+ let mut ch = vec![click(30_000)];+ d.process(&mut ch);+ assert!((ch[0][24_000] - 1.0).abs() < 1e-6);+ }++ fn multi_tap(values: &[(usize, f32)]) -> MultiTapDelay {+ let mut d = MultiTapDelay::new(48_000);+ let mut p: Vec<f32> = mt::PARAMS.iter().map(|s| s.default).collect();+ for &(i, v) in values {+ p[i] = v;+ }+ d.set(&p);+ d+ }++ #[test]+ fn a_tap_comes_at_its_time_on_its_side() {+ // One tap, 100 ms (and its nudge, 0.123 ms), all the way left.+ let mut d = multi_tap(&[(mt::DRY, -80.0), (mt::WET, 0.0), (mt::TAP + mt::PAN, 1.0)]);+ let mut x = vec![click(9_600), click(9_600)];+ d.process(&mut x);+ let at = (100.123f32 * 48.0).round() as usize;+ let left: f32 = x[0][at - 2..at + 3].iter().sum();+ let right: f32 = x[1][at - 2..at + 3].iter().sum();+ assert!((left - 1.0).abs() < 0.01, "{left}");+ assert!(right.abs() < 1e-6, "{right}");+ assert!(x[0][..at - 2].iter().all(|s| s.abs() < 1e-6));+ }++ #[test]+ fn multi_tap_feedback_is_shared_by_the_taps() {+ // Two taps at full gain, 150 % feedback: 75 % each way round.+ let mut d = multi_tap(&[+ (mt::DRY, -80.0),+ (mt::WET, 0.0),+ (mt::FEEDBACK, 1.5),+ (mt::TAPS, 2.0),+ (mt::TAP + mt::DELAY, 10.0),+ (mt::TAP + mt::PER_TAP + mt::DELAY, 500.0),+ ]);+ let mut x = vec![click(4_000)];+ d.process(&mut x);+ // The first tap's echo, then its echo of itself 10 ms later.+ let one = (10.123f32 * 48.0).round() as usize;+ let first: f32 = x[0][one - 2..one + 3].iter().sum();+ let again: f32 = x[0][2 * one - 3..2 * one + 4].iter().sum();+ assert!((again / first - 0.75).abs() < 0.03, "{first} {again}");+ }++ #[test]+ fn dry_and_delay_out_at_their_lowest_are_silent() {+ let mut d = delay(&[(sd::DRY, -80.0), (sd::WET, -80.0)]);+ let mut ch = vec![vec![0.5f32; 10_000]];+ d.process(&mut ch);+ assert!(ch[0].iter().all(|s| *s == 0.0));+ }+}diff --git a/crates/mixer/src/fx/dither.rs b/crates/mixer/src/fx/dither.rsnew file mode 100644index 0000000..47ba17a--- /dev/null+++ b/crates/mixer/src/fx/dither.rs@@ -0,0 +1,272 @@+//! Dither, as VEGAS's: the sound rounded (to the nearest, ties to even) to+//! the steps of a bit depth, a little noise added first so the rounding's+//! error turns into a steady hiss instead of distortion. Noise shaping+//! feeds the rounding errors back so that hiss moves up, where it is+//! heard less: by one sample (a high-pass contour) or along the ear's+//! equal loudness contour (the published E-weighted filter of Lipshitz,+//! Vanderkooy and Wannamaker, five taps). The result stays a float+//! signal, holding only the levels of that depth.+//!+//! The noise comes from a counter run through a hash, so a block's noise+//! is made at once (vectorized); the rounding with shaping goes sample by+//! sample, as its errors feed back.++use bv_timeline::audio_fx::dither;++use super::Own;++/// Equal loudness contour's error feedback, newest error first.+const CONTOUR: [f64; 5] = [2.033, -2.165, 1.959, -1.590, 0.6149];++#[derive(Debug)]+pub(crate) struct Dither {+ /// Steps of the depth in each unit of the signal: 2^(bits − 1).+ steps: f64,+ noise: usize,+ shaping: usize,+ /// Each channel's last rounding errors, newest first.+ errors: Vec<[f64; 5]>,+ /// Each channel's last uniform number (the high-pass triangular noise).+ last: Vec<f64>,+ /// The noise generator's counter.+ count: u32,+ /// One block's noise (kept, not made again each time).+ buf: Vec<f64>,+}++impl Default for Dither {+ fn default() -> Dither {+ Dither {+ steps: 32768.0,+ noise: 1,+ shaping: 0,+ errors: Vec::new(),+ last: Vec::new(),+ count: 0,+ buf: Vec::new(),+ }+ }+}++/// A well-mixed 32-bit hash (a counter's next random number).+fn hash(mut x: u32) -> u32 {+ x ^= x >> 16;+ x = x.wrapping_mul(0x7feb_352d);+ x ^= x >> 15;+ x = x.wrapping_mul(0x846c_a68b);+ x ^= x >> 16;+ x+}++/// A uniform number in (−½, ½) from counter `c` of stream `s`.+fn uniform(c: u32, s: u32) -> f64 {+ hash(c ^ s.wrapping_mul(0x9e37_79b9)) as f64 / 4_294_967_296.0 - 0.5+}++impl Dither {+ /// Channel `ch`'s noise for the next `n` samples, in steps, into `buf`.+ fn noise(&mut self, ch: usize, n: usize) {+ let c0 = self.count;+ let s = ch as u32 * 4;+ self.buf.clear();+ self.buf.resize(n, 0.0);+ let at = |k: usize| c0.wrapping_add(k as u32);+ match self.noise {+ // Half rectangular: ±¼ step.+ 1 => {+ for (k, d) in self.buf.iter_mut().enumerate() {+ *d = 0.5 * uniform(at(k), s);+ }+ }+ // Rectangular: ±½ step.+ 2 => {+ for (k, d) in self.buf.iter_mut().enumerate() {+ *d = uniform(at(k), s);+ }+ }+ // Triangular: two uniforms, ±1 step.+ 3 => {+ for (k, d) in self.buf.iter_mut().enumerate() {+ *d = uniform(at(k), s) + uniform(at(k), s + 1);+ }+ }+ // High-pass triangular: each uniform less the one before.+ 4 => {+ let mut last = self.last[ch];+ for (k, d) in self.buf.iter_mut().enumerate() {+ let u = uniform(at(k), s);+ *d = u - last;+ last = u;+ }+ self.last[ch] = last;+ }+ // Gaussian: four uniforms, scaled to a deviation of ½ step.+ 5 => {+ for (k, d) in self.buf.iter_mut().enumerate() {+ let sum = uniform(at(k), s)+ + uniform(at(k), s + 1)+ + uniform(at(k), s + 2)+ + uniform(at(k), s + 3);+ *d = sum * 0.866_025_4;+ }+ }+ _ => {}+ }+ }+}++impl Own for Dither {+ fn set(&mut self, params: &[f32]) {+ let pick = |i: usize, top: usize| {+ params+ .get(i)+ .copied()+ .unwrap_or(dither::PARAMS[i].default)+ .round()+ .clamp(0.0, top as f32) as usize+ };+ let bits = dither::BITS[pick(dither::DEPTH, dither::BITS.len() - 1)];+ self.steps = 2f64.powi(bits as i32 - 1);+ self.noise = pick(dither::NOISE, 5);+ self.shaping = pick(dither::SHAPING, 2);+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ self.errors.resize(channels.len(), [0.0; 5]);+ self.last.resize(channels.len(), 0.0);+ let q = self.steps;+ for (c, ch) in channels.iter_mut().enumerate() {+ self.noise(c, n);+ let e = &mut self.errors[c];+ match self.shaping {+ 0 => {+ for (x, d) in ch.iter_mut().zip(self.buf.iter()) {+ *x = ((*x as f64 * q + d).round_ties_even() / q) as f32;+ }+ }+ 1 => {+ for (x, d) in ch.iter_mut().zip(self.buf.iter()) {+ let v = *x as f64 * q - e[0];+ let r = (v + d).round_ties_even();+ e[0] = r - v;+ *x = (r / q) as f32;+ }+ }+ _ => {+ for (x, d) in ch.iter_mut().zip(self.buf.iter()) {+ let fed: f64 = CONTOUR.iter().zip(e.iter()).map(|(c, e)| c * e).sum();+ let v = *x as f64 * q - fed;+ let r = (v + d).round_ties_even();+ e.copy_within(0..4, 1);+ e[0] = r - v;+ *x = (r / q) as f32;+ }+ }+ }+ }+ self.count = self.count.wrapping_add(n as u32);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn dither(depth: f32, noise: f32, shaping: f32) -> Dither {+ let mut d = Dither::default();+ d.set(&[depth, noise, shaping]);+ d+ }++ fn sine(n: usize, amp: f32) -> Vec<f32> {+ (0..n)+ .map(|i| amp * (i as f32 * std::f32::consts::TAU * 1000.0 / 48_000.0).sin())+ .collect()+ }++ #[test]+ fn every_sample_lands_on_a_step_of_the_depth() {+ for (depth, bits) in [(0.0, 8), (1.0, 12), (2.0, 16)] {+ for noise in 0..6 {+ for shaping in 0..3 {+ let mut d = dither(depth, noise as f32, shaping as f32);+ let mut ch = vec![sine(4800, 0.5), sine(4800, 0.25)];+ d.process(&mut ch);+ let q = 2f32.powi(bits - 1);+ for s in ch.iter().flatten() {+ let v = s * q;+ assert!((v - v.round()).abs() < 1e-3, "{bits} bits: {s}");+ }+ }+ }+ }+ }++ #[test]+ fn without_noise_it_rounds_to_the_nearest_step() {+ let mut d = dither(0.0, 0.0, 0.0);+ let mut ch = vec![vec![0.3f32, -0.3, 1.0 / 256.0]];+ d.process(&mut ch);+ let q = 128.0;+ assert_eq!(ch[0][0], (0.3f32 * q).round() / q);+ assert_eq!(ch[0][1], (-0.3f32 * q).round() / q);+ // Ties go to the even step.+ assert_eq!(ch[0][2], 0.0);+ }++ #[test]+ fn noise_has_the_type_s_spread() {+ // On silence at 8 bits, the result is the noise rounded: rectangular+ // (±½ step) rounds to 0 or ±1 step, triangular reaches ±1.+ for (noise, most) in [(2.0, 1.0), (3.0, 1.0), (1.0, 0.0)] {+ let mut d = dither(0.0, noise, 0.0);+ let mut ch = vec![vec![0.0f32; 48_000]];+ d.process(&mut ch);+ let top = ch[0].iter().fold(0f32, |m, s| m.max(s.abs())) * 128.0;+ assert!(top <= most + 1e-6, "{noise}: {top}");+ }+ // Its mean is 0 and its power about a step's twelfth (rectangular).+ let mut d = dither(0.0, 2.0, 0.0);+ let mut ch = vec![vec![0.3f32 / 128.0; 48_000]];+ d.process(&mut ch);+ let mean = ch[0].iter().map(|s| *s as f64).sum::<f64>() / 48_000.0 * 128.0;+ assert!((mean - 0.3).abs() < 0.02, "{mean}");+ }++ /// The power of `x` in the band `lo..hi` (a part of the rate), by a+ /// plain DFT on a few bins.+ fn band_power(x: &[f32], lo: f64, hi: f64) -> f64 {+ let n = x.len();+ let mut sum = 0.0;+ let bins = ((lo * n as f64) as usize)..((hi * n as f64) as usize);+ for k in bins.step_by(7) {+ let (mut re, mut im) = (0.0, 0.0);+ for (i, s) in x.iter().enumerate() {+ let a = std::f64::consts::TAU * (k * i) as f64 / n as f64;+ re += *s as f64 * a.cos();+ im -= *s as f64 * a.sin();+ }+ sum += re * re + im * im;+ }+ sum+ }++ #[test]+ fn shaping_moves_the_noise_up() {+ let error = |shaping: f32| {+ let mut d = dither(0.0, 3.0, shaping);+ let x: Vec<f32> = sine(8192, 0.3);+ let mut ch = vec![x.clone()];+ d.process(&mut ch);+ let e: Vec<f32> = ch[0].iter().zip(&x).map(|(y, x)| y - x).collect();+ (band_power(&e, 0.02, 0.1), band_power(&e, 0.4, 0.5))+ };+ let (low_flat, high_flat) = error(0.0);+ for shaping in [1.0, 2.0] {+ let (low, high) = error(shaping);+ assert!(low < low_flat * 0.5, "{shaping}: {low} vs {low_flat}");+ assert!(high > high_flat * 2.0, "{shaping}: {high} vs {high_flat}");+ }+ }+}diff --git a/crates/mixer/src/fx/dynamics.rs b/crates/mixer/src/fx/dynamics.rsnew file mode 100644index 0000000..eb408ef--- /dev/null+++ b/crates/mixer/src/fx/dynamics.rs@@ -0,0 +1,621 @@+//! Noise Gate, Track Noise Gate, Track Compressor and Multi-Band+//! Dynamics, as VEGAS's.+//!+//! The gates: the sound let through+//! while it is above a threshold. The gate opens once the level has stayed+//! above the threshold for the attack time and closes once it has stayed+//! under 0.85 of it (about 1.4 dB lower, so it does not chatter) for the+//! release time; every channel opens and closes together, by the loudest,+//! a millisecond at a time. Its gain glides toward open while opening (by+//! the attack) and open (in 15 ms), and toward shut while closing and+//! closed (by the release): nine tenths of the way in that time, sample by+//! sample.++use bv_timeline::audio_fx::{gate, multi_band_dynamics as mb, track_compressor as tc};++use super::eq::Section;+use super::{Own, db_gain};++/// The threshold at −80 dB, the gates' lowest (−Inf.).+const FLOOR: f32 = 3.0517e-5;+/// Under this the gain is 0.+const SHUT: f32 = 0.0002;++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+enum Phase {+ Closed,+ /// Above the threshold, waiting out the attack.+ Opening,+ Open,+ /// Under the closing threshold, waiting out the release.+ Closing,+}++#[derive(Debug)]+pub(crate) struct Gate {+ rate: f32,+ open_at: f32,+ attack: usize,+ release: usize,+ /// What is left of the way to its target after a sample, while+ /// opening, open, and closing.+ keep: [f32; 3],+ phase: Phase,+ count: usize,+ gain: f32,+ /// One stretch's gains (kept, not made again each time).+ gains: Vec<f32>,+}++impl Gate {+ pub(crate) fn new(rate: u32) -> Gate {+ Gate {+ rate: rate.max(1) as f32,+ open_at: FLOOR,+ attack: 0,+ release: 0,+ keep: [0.0; 3],+ phase: Phase::Closed,+ count: 0,+ gain: 0.0,+ gains: Vec::new(),+ }+ }++ /// What is left of the way after a sample when a tenth is left after+ /// `ms` (none at 0).+ fn keep(&self, ms: f32) -> f32 {+ if ms <= 0.0 {+ 0.0+ } else {+ 0.1f32.powf(1000.0 / (ms * self.rate))+ }+ }++ /// One stretch's level: the phase it leaves the gate in.+ fn follow(&mut self, level: f32, len: usize) {+ let close_at = 0.85 * self.open_at;+ self.phase = match self.phase {+ Phase::Closed if level >= self.open_at => {+ self.count = len;+ Phase::Opening+ }+ Phase::Opening if level <= close_at => Phase::Closed,+ Phase::Opening => {+ self.count += len;+ if self.count >= self.attack {+ Phase::Open+ } else {+ Phase::Opening+ }+ }+ Phase::Open if level <= close_at => {+ self.count = len;+ Phase::Closing+ }+ Phase::Closing if level >= self.open_at => Phase::Open,+ Phase::Closing => {+ self.count += len;+ if self.count >= self.release {+ Phase::Closed+ } else {+ Phase::Closing+ }+ }+ phase => phase,+ };+ }+}++impl Own for Gate {+ fn set(&mut self, params: &[f32]) {+ let p = |i: usize, d: f32| params.get(i).copied().unwrap_or(d);+ let db = p(gate::THRESHOLD, -80.0);+ self.open_at = if db <= -80.0 {+ FLOOR+ } else {+ 10f32.powf(db / 20.0)+ };+ let attack = p(gate::ATTACK, 3.0).max(0.0);+ let release = p(gate::RELEASE, 100.0).max(1.0);+ self.attack = (attack / 1000.0 * self.rate) as usize;+ self.release = (release / 1000.0 * self.rate) as usize;+ self.keep = [self.keep(attack), self.keep(15.0), self.keep(release)];+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let ms = ((self.rate / 1000.0).round() as usize).max(1);+ let mut at = 0;+ while at < n {+ let end = (at + ms).min(n);+ let level = channels+ .iter()+ .map(|ch| ch[at..end].iter().fold(0f32, |m, s| m.max(s.abs())))+ .fold(0f32, f32::max);+ self.follow(level, end - at);+ let (keep, target) = match self.phase {+ Phase::Closed => (self.keep[2], 0.0),+ Phase::Opening => (self.keep[0], 1.0),+ Phase::Open => (self.keep[1], 1.0),+ // Held open until it closes.+ Phase::Closing => (self.keep[2], 1.0),+ };+ // The gain at each sample of the stretch, then on every channel.+ let gains = &mut self.gains;+ gains.clear();+ let mut g = self.gain;+ for _ in at..end {+ g = target + (g - target) * keep;+ if g < SHUT && target == 0.0 {+ g = 0.0;+ }+ gains.push(g);+ }+ for ch in channels.iter_mut() {+ for (s, g) in ch[at..end].iter_mut().zip(gains.iter()) {+ *s *= g;+ }+ }+ self.gain = g;+ at = end;+ }+ }+}++/// Track Compressor, as VEGAS's: the sound at the input gain, its level+/// followed by a detector that moves nine tenths of the way in the attack+/// time going up and in the release time going down (every channel by+/// the loudest), and above the threshold brought down to+/// `t·(level/t)^(1/ratio)` (from 500:1 a limiter). A threshold above+/// −3 dB is worked 3 dB lower inside, the gains moved to match. Auto gain+/// compensation gives back 70 % of what the curve takes at full scale;+/// smooth saturation rounds the curve's corner over 6 dB.+#[derive(Debug)]+pub(crate) struct TrackCompressor {+ rate: f32,+ input: f32,+ output: f32,+ threshold: f32,+ /// `1 / ratio − 1`: the gain's slope above the threshold, in log terms.+ slope: f32,+ limit: bool,+ soft: bool,+ attack: f32,+ release: f32,+ level: f32,+}++impl TrackCompressor {+ pub(crate) fn new(rate: u32) -> TrackCompressor {+ TrackCompressor {+ rate: rate.max(1) as f32,+ input: 1.0,+ output: 1.0,+ threshold: 1.0,+ slope: 0.0,+ limit: false,+ soft: false,+ attack: 0.0,+ release: 0.0,+ level: 0.0,+ }+ }++ /// What is left of the way after a sample when a tenth is left after+ /// `ms` (0: at once).+ fn keep(&self, ms: f32) -> f32 {+ let n = self.rate * ms / 1000.0;+ if n < 1.0 { 0.0 } else { 0.1f32.powf(1.0 / n) }+ }++ /// The gain at detected level `e`.+ fn gain(&self, e: f32) -> f32 {+ let t = self.threshold;+ if self.soft {+ // The corner rounded over 6 dB (3 either side of the threshold).+ let over = 20.0 * (e.max(1e-9) / t).log10();+ let cut = if over <= -3.0 {+ 0.0+ } else if over < 3.0 {+ self.slope * (over + 3.0).powi(2) / 12.0+ } else {+ self.slope * over+ };+ return 10f32.powf(cut / 20.0);+ }+ if e <= t {+ 1.0+ } else if self.limit {+ t / e+ } else {+ (e / t).powf(self.slope)+ }+ }+}++impl Own for TrackCompressor {+ fn set(&mut self, params: &[f32]) {+ let p = |i: usize| {+ let s = &tc::PARAMS[i];+ params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+ };+ let mut input = db_gain(p(tc::INPUT), -60.0);+ let mut output = db_gain(p(tc::OUTPUT), -60.0);+ let db = p(tc::THRESHOLD);+ let mut t = 10f32.powf(db / 20.0).max(1e-3);+ if db > -3.0 {+ // Worked 3 dB under full scale, the gains moved to match.+ let d = 10f32.powf((-3.0 - db) / 20.0);+ input *= d;+ output /= d;+ t *= d;+ }+ let ratio = p(tc::RATIO);+ self.limit = ratio >= 500.0;+ self.slope = if self.limit { -1.0 } else { 1.0 / ratio - 1.0 };+ if p(tc::AUTO_GAIN) >= 0.5 {+ // 70 % of the cut at full scale given back.+ let full = t.powf(-self.slope);+ output /= full.powf(0.7);+ }+ self.input = input;+ self.output = output;+ self.threshold = t;+ self.soft = p(tc::SMOOTH) >= 0.5;+ self.attack = self.keep(p(tc::ATTACK));+ self.release = self.keep(p(tc::RELEASE));+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let (gi, go) = (self.input, self.output);+ let mut e = self.level;+ for i in 0..n {+ let peak = channels.iter().fold(0f32, |m, c| m.max((c[i] * gi).abs()));+ let keep = if peak > e { self.attack } else { self.release };+ e = peak + (e - peak) * keep;+ let g = gi * self.gain(e) * go;+ for c in channels.iter_mut() {+ c[i] *= g;+ }+ }+ self.level = e;+ }+}++/// One band of Multi-Band Dynamics: its filter, fixed gain, compression+/// and each channel's filter memory and level.+#[derive(Debug)]+struct Band {+ filter: Section,+ gain: f32,+ threshold: f32,+ slope: f32,+ attack: f32,+ release: f32,+ solo: bool,+ memory: Vec<[f32; 4]>,+ level: Vec<f32>,+}++/// Multi-Band Dynamics, as VEGAS's: each band picked out of the sound (a+/// low-pass for a low shelf, a band-pass for a band, a high-pass for a+/// high shelf), its level followed (nine tenths of the way in the attack+/// going up, the release going down; every channel by the loudest with+/// stereo sync), compressed above its threshold by its amount, raised or+/// lowered by its gain, and put back in place of what it was; the rest of+/// the sound goes through as it is. A soloed band plays alone (with the+/// other soloed ones); a bypassed one is left out.+#[derive(Debug)]+pub(crate) struct MultiBand {+ rate: f32,+ output: f32,+ sync: bool,+ bands: Vec<Band>,+ /// What the bands change, a channel (kept, not made again each time),+ /// and one sample's band on each channel.+ add: Vec<Vec<f32>>,+ picked: Vec<f32>,+}++impl MultiBand {+ pub(crate) fn new(rate: u32) -> MultiBand {+ MultiBand {+ rate: rate.max(1) as f32,+ output: 1.0,+ sync: true,+ bands: Vec::new(),+ add: Vec::new(),+ picked: Vec::new(),+ }+ }++ fn keep(&self, ms: f32) -> f32 {+ let n = self.rate * ms / 1000.0;+ if n < 1.0 { 0.0 } else { 0.1f32.powf(1.0 / n) }+ }+}++impl Own for MultiBand {+ fn set(&mut self, params: &[f32]) {+ let p = |i: usize| {+ let s = &mb::PARAMS[i];+ params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+ };+ self.output = 10f32.powf(p(mb::OUTPUT) / 20.0);+ self.sync = p(mb::SYNC) >= 0.5;+ let fs = self.rate as f64;+ let mut bands = Vec::new();+ for b in 0..4 {+ let at = mb::BANDS + b * mb::PER_BAND;+ if p(at + mb::BYPASS) >= 0.5 {+ continue;+ }+ let hz = p(at + mb::CENTER) as f64;+ let filter = match p(at + mb::TYPE).round() as i32 {+ 0 => Section::pass(hz, false, fs),+ 2 => Section::pass(hz, true, fs),+ _ => Section::band(hz, p(at + mb::WIDTH) as f64, fs),+ };+ let ratio = p(at + mb::AMOUNT);+ bands.push(Band {+ filter,+ gain: 10f32.powf(p(at + mb::GAIN) / 20.0),+ threshold: 10f32.powf(p(at + mb::THRESHOLD) / 20.0).max(1.0 / 32768.0),+ slope: 1.0 / ratio - 1.0,+ attack: self.keep(p(at + mb::ATTACK)),+ release: self.keep(p(at + mb::RELEASE)),+ solo: p(at + mb::SOLO) >= 0.5,+ memory: Vec::new(),+ level: Vec::new(),+ });+ }+ // Keep each band's memory while its filter stays.+ for (new, old) in bands.iter_mut().zip(self.bands.iter_mut()) {+ if new.filter == old.filter {+ new.memory = std::mem::take(&mut old.memory);+ new.level = std::mem::take(&mut old.level);+ }+ }+ self.bands = bands;+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let count = channels.len();+ let soloing = self.bands.iter().any(|b| b.solo);+ let (output, sync) = (self.output, self.sync);+ // What each band changes, added up: on the sound, or alone.+ let (add, picked) = (&mut self.add, &mut self.picked);+ add.resize_with(count, Vec::new);+ for a in add.iter_mut() {+ a.clear();+ a.resize(n, 0.0);+ }+ picked.resize(count, 0.0);+ for band in &mut self.bands {+ band.memory.resize(count, [0.0; 4]);+ band.level.resize(count, 0.0);+ if soloing && !band.solo {+ continue;+ }+ for i in 0..n {+ for (c, ch) in channels.iter().enumerate() {+ picked[c] = band.filter.run(ch[i], &mut band.memory[c]);+ }+ let loudest = picked.iter().fold(0f32, |m, v| m.max(v.abs()));+ for c in 0..count {+ let peak = if sync { loudest } else { picked[c].abs() };+ let e = &mut band.level[c];+ let keep = if peak > *e { band.attack } else { band.release };+ *e = peak + (*e - peak) * keep;+ let squeeze = if *e > band.threshold {+ (*e / band.threshold).powf(band.slope)+ } else {+ 1.0+ };+ let g = band.gain * squeeze;+ add[c][i] += if soloing { g } else { g - 1.0 } * picked[c];+ }+ }+ }+ for (ch, add) in channels.iter_mut().zip(add.iter()) {+ for (x, a) in ch.iter_mut().zip(add.iter()) {+ *x = output * if soloing { *a } else { *x + a };+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn tone(level: f32, n: usize) -> Vec<f32> {+ (0..n)+ .map(|i| level * (i as f32 * 0.3).sin().signum())+ .collect()+ }++ fn gate(threshold: f32, attack: f32, release: f32) -> Gate {+ let mut g = Gate::new(48_000);+ g.set(&[threshold, attack, release]);+ g+ }++ #[test]+ fn quiet_sound_stays_shut() {+ let mut g = gate(-20.0, 3.0, 100.0);+ let mut ch = vec![tone(0.05, 4800)];+ g.process(&mut ch);+ assert!(ch[0].iter().all(|s| s.abs() < 1e-6));+ }++ #[test]+ fn loud_sound_opens_after_the_attack() {+ let mut g = gate(-20.0, 10.0, 100.0);+ let mut ch = vec![tone(0.5, 4800)];+ g.process(&mut ch);+ // Nine tenths of the way open after the attack (10 ms), all the way+ // by 60 ms.+ let at = |i: usize| ch[0][i].abs() / 0.5;+ assert!(at(48) < 0.5, "{}", at(48));+ assert!((at(480) - 0.9).abs() < 0.05, "{}", at(480));+ assert!(ch[0][2880..].iter().all(|s| (s.abs() - 0.5).abs() < 1e-3));+ }++ #[test]+ fn it_closes_after_the_release() {+ let mut g = gate(-20.0, 1.0, 10.0);+ let mut ch = vec![tone(0.5, 4800)];+ g.process(&mut ch);+ // Then quiet: held open for the release (10 ms), then gliding shut —+ // a tenth left after another 10 ms — and silent once under −74 dB.+ let mut ch = vec![tone(0.01, 9600)];+ g.process(&mut ch);+ assert!((ch[0][100].abs() - 0.01).abs() < 1e-4, "{}", ch[0][100]);+ // Shut from the stretch where the hold ran out (432), a tenth left+ // 480 samples later.+ let tenth = ch[0][432 + 480].abs() / 0.01;+ assert!((tenth - 0.1).abs() < 0.03, "{tenth}");+ assert!(ch[0][4800..].iter().all(|s| s.abs() < 1e-9));+ }++ fn compressor(values: &[(usize, f32)]) -> TrackCompressor {+ let mut c = TrackCompressor::new(48_000);+ let mut p: Vec<f32> = tc::PARAMS.iter().map(|s| s.default).collect();+ for &(i, v) in values {+ p[i] = v;+ }+ c.set(&p);+ c+ }++ fn settled(c: &mut TrackCompressor, level: f32) -> f32 {+ let mut ch = vec![tone(level, 48_000)];+ c.process(&mut ch);+ ch[0][47_000..].iter().fold(0f32, |m, s| m.max(s.abs()))+ }++ #[test]+ fn the_compressor_follows_its_curve_above_the_threshold() {+ // 2:1 from −18 dB, no makeup: −6 dB in comes out at −12 dB.+ let mut c = compressor(&[+ (tc::THRESHOLD, -18.0),+ (tc::RATIO, 2.0),+ (tc::AUTO_GAIN, 0.0),+ ]);+ let out = 20.0 * settled(&mut c, 0.501).log10();+ assert!((out + 12.0).abs() < 0.3, "{out}");+ // Below the threshold it is left alone.+ let mut c = compressor(&[+ (tc::THRESHOLD, -18.0),+ (tc::RATIO, 2.0),+ (tc::AUTO_GAIN, 0.0),+ ]);+ assert!((settled(&mut c, 0.05) - 0.05).abs() < 1e-4);+ }++ #[test]+ fn auto_gain_gives_back_most_of_the_cut_and_500_limits() {+ // 2:1 from −18 dB: 9 dB off at full scale, 70 % of it back.+ let mut c = compressor(&[(tc::THRESHOLD, -18.0), (tc::RATIO, 2.0)]);+ let out = 20.0 * settled(&mut c, 0.501).log10();+ assert!((out - (-12.0 + 0.7 * 9.0)).abs() < 0.3, "{out}");+ // A limiter holds the threshold.+ let mut c = compressor(&[+ (tc::THRESHOLD, -12.0),+ (tc::RATIO, 500.0),+ (tc::AUTO_GAIN, 0.0),+ ]);+ let out = 20.0 * settled(&mut c, 0.9).log10();+ assert!((out + 12.0).abs() < 0.3, "{out}");+ }++ #[test]+ fn neutral_settings_change_nothing() {+ let mut c = compressor(&[]);+ let x = tone(0.7, 4800);+ let mut ch = vec![x.clone()];+ c.process(&mut ch);+ assert!(ch[0].iter().zip(&x).all(|(a, b)| (a - b).abs() < 1e-6));+ }++ fn multi_band(values: &[(usize, f32)]) -> MultiBand {+ let mut m = MultiBand::new(48_000);+ let mut p: Vec<f32> = mb::PARAMS.iter().map(|s| s.default).collect();+ for &(i, v) in values {+ p[i] = v;+ }+ m.set(&p);+ m+ }++ fn sine(hz: f32, level: f32, n: usize) -> Vec<f32> {+ (0..n)+ .map(|i| level * (std::f32::consts::TAU * hz * i as f32 / 48_000.0).sin())+ .collect()+ }++ fn db_of(m: &mut MultiBand, hz: f32, level: f32) -> f32 {+ let mut ch = vec![sine(hz, level, 48_000)];+ m.process(&mut ch);+ let tail = &ch[0][24_000..];+ let power = tail.iter().map(|s| s * s).sum::<f32>() / tail.len() as f32;+ 10.0 * (2.0 * power).log10()+ }++ #[test]+ fn multi_band_defaults_change_nothing() {+ let mut m = multi_band(&[]);+ for hz in [60.0, 200.0, 3000.0] {+ assert!((db_of(&mut m, hz, 0.5) - 20.0 * 0.5f32.log10()).abs() < 0.05);+ }+ }++ #[test]+ fn a_band_s_gain_and_compression_touch_only_it() {+ // Band 1 a band at 1 kHz, −12 dB.+ let g = mb::BANDS + mb::GAIN;+ let mut m = multi_band(&[(mb::BANDS + mb::CENTER, 1000.0), (g, -12.0)]);+ assert!(+ (db_of(&mut m, 1000.0, 1.0) + 12.0).abs() < 0.5,+ "{}",+ db_of(&mut m, 1000.0, 1.0)+ );+ assert!(db_of(&mut m, 100.0, 1.0).abs() < 0.5);+ // Compressed 4:1 above −30 dB: a loud tone there comes down, a+ // quiet one stays.+ let mut m = multi_band(&[+ (mb::BANDS + mb::CENTER, 5000.0),+ (mb::BANDS + mb::THRESHOLD, -30.0),+ (mb::BANDS + mb::AMOUNT, 4.0),+ ]);+ let loud = db_of(&mut m, 5000.0, 0.5);+ assert!(loud < -12.0, "{loud}");+ let mut m = multi_band(&[+ (mb::BANDS + mb::CENTER, 5000.0),+ (mb::BANDS + mb::THRESHOLD, -30.0),+ (mb::BANDS + mb::AMOUNT, 4.0),+ ]);+ let quiet = db_of(&mut m, 5000.0, 0.01);+ assert!((quiet + 40.0).abs() < 0.5, "{quiet}");+ }++ #[test]+ fn channels_open_together_by_the_loudest() {+ let mut g = gate(-20.0, 1.0, 100.0);+ let mut ch = vec![tone(0.5, 4800), tone(0.01, 4800)];+ g.process(&mut ch);+ assert!((ch[1][4000].abs() - 0.01).abs() < 1e-4);+ }+}diff --git a/crates/mixer/src/fx/eq.rs b/crates/mixer/src/fx/eq.rsnew file mode 100644index 0000000..bdc1572--- /dev/null+++ b/crates/mixer/src/fx/eq.rs@@ -0,0 +1,389 @@+//! Track EQ and Paragraphic EQ, as VEGAS's.+//!+//! Track EQ: four bands in a row, each a low shelf, a peak/notch or a+//! high shelf. A shelf is one to four first-order sections at its+//! frequency (6 to 24 dB an octave), the gain shared among them; a band+//! is a second-order peak as wide as its bandwidth in octaves. Each+//! channel can be left out (the others go through untouched).+//!+//! Paragraphic EQ: four bands in a row, each adding its band-pass, raised+//! or lowered by its gain, to the sound; then optional low and high+//! shelves (a second-order low- or high-pass added the same way); the+//! result at the wet level with the untouched sound at the dry level.++use bv_timeline::audio_fx::{paragraphic_eq as pq, track_eq as te};++use super::{Own, db_gain};++/// Added and taken away again on filter memories, so a fading signal ends+/// at 0 instead of lingering as a denormal number.+const FLUSH: f32 = 1e-18;++/// A filter section of up to the second order:+/// `y = b0·x + b1·x₁ + b2·x₂ − a1·y₁ − a2·y₂`.+#[derive(Clone, Copy, Debug, Default, PartialEq)]+pub(crate) struct Section {+ b: [f32; 3],+ a: [f32; 2],+}++impl Section {+ /// `(n0 + n1·z⁻¹ + n2·z⁻²) / (d0 + d1·z⁻¹ + d2·z⁻²)`.+ pub(crate) fn new(n: [f64; 3], d: [f64; 3]) -> Section {+ Section {+ b: [+ (n[0] / d[0]) as f32,+ (n[1] / d[0]) as f32,+ (n[2] / d[0]) as f32,+ ],+ a: [(d[1] / d[0]) as f32, (d[2] / d[0]) as f32],+ }+ }++ /// A first-order shelf at `hz`, `db` at the lows (`high`: at the highs).+ pub(crate) fn shelf(hz: f64, db: f64, high: bool, fs: f64) -> Section {+ let k = (std::f64::consts::PI * (hz / fs).min(0.49)).tan();+ let v = 10f64.powf(db / 20.0);+ // Its analog form on a frequency of 1 (the corner):+ // low (s + A)/(s + B), high (A·s + 1)/(B·s + 1); A over B the gain.+ let (a, b) = if v >= 1.0 { (v, 1.0) } else { (1.0, 1.0 / v) };+ if high {+ Section::new([a + k, k - a, 0.0], [b + k, k - b, 0.0])+ } else {+ Section::new(+ [1.0 + a * k, a * k - 1.0, 0.0],+ [1.0 + b * k, b * k - 1.0, 0.0],+ )+ }+ }++ /// A second-order peak at `hz`, `db` at its top, `octaves` wide.+ pub(crate) fn peak(hz: f64, db: f64, octaves: f64, fs: f64) -> Section {+ let w = std::f64::consts::TAU * (hz / fs).min(0.49);+ let (s, c) = w.sin_cos();+ let alpha = s * (std::f64::consts::LN_2 / 2.0 * octaves * w / s).sinh();+ let a = 10f64.powf(db / 40.0);+ Section::new(+ [1.0 + alpha * a, -2.0 * c, 1.0 - alpha * a],+ [1.0 + alpha / a, -2.0 * c, 1.0 - alpha / a],+ )+ }++ /// A second-order band-pass at `hz` (0 dB at its top), `octaves` wide.+ pub(crate) fn band(hz: f64, octaves: f64, fs: f64) -> Section {+ let w = std::f64::consts::TAU * (hz / fs).min(0.49);+ let (s, c) = w.sin_cos();+ let alpha = s * (std::f64::consts::LN_2 / 2.0 * octaves * w / s).sinh();+ Section::new([alpha, 0.0, -alpha], [1.0 + alpha, -2.0 * c, 1.0 - alpha])+ }++ /// A second-order low-pass (or high-pass) at `hz`, Butterworth.+ pub(crate) fn pass(hz: f64, high: bool, fs: f64) -> Section {+ let w = std::f64::consts::TAU * (hz / fs).min(0.49);+ let (s, c) = w.sin_cos();+ let alpha = s / std::f64::consts::SQRT_2;+ let d = [1.0 + alpha, -2.0 * c, 1.0 - alpha];+ if high {+ Section::new([(1.0 + c) / 2.0, -(1.0 + c), (1.0 + c) / 2.0], d)+ } else {+ Section::new([(1.0 - c) / 2.0, 1.0 - c, (1.0 - c) / 2.0], d)+ }+ }++ /// `x` through the section with memory `m` (`x₁, x₂, y₁, y₂`).+ #[inline]+ pub(crate) fn run(&self, x: f32, m: &mut [f32; 4]) -> f32 {+ let y = self.b[0] * x + self.b[1] * m[0] + self.b[2] * m[1]+ - self.a[0] * m[2]+ - self.a[1] * m[3];+ let y = (y + FLUSH) - FLUSH;+ *m = [x, m[0], y, m[2]];+ y+ }+}++#[derive(Debug)]+pub(crate) struct TrackEq {+ rate: f64,+ /// The sections in their order, all channels alike.+ sections: Vec<Section>,+ /// Which channels it works on.+ channels: [bool; 6],+ /// Each channel's sections' memories.+ memory: Vec<Vec<[f32; 4]>>,+}++impl TrackEq {+ pub(crate) fn new(rate: u32) -> TrackEq {+ TrackEq {+ rate: rate.max(1) as f64,+ sections: Vec::new(),+ channels: [true; 6],+ memory: Vec::new(),+ }+ }+}++impl Own for TrackEq {+ fn set(&mut self, params: &[f32]) {+ let p = |i: usize| {+ let s = &te::PARAMS[i];+ params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max) as f64+ };+ let mut sections = Vec::new();+ for band in 0..4 {+ let at = band * te::PER_BAND;+ if p(at + te::ENABLE) < 0.5 {+ continue;+ }+ let (hz, db) = (p(at + te::FREQUENCY), p(at + te::GAIN));+ match p(at + te::MODE).round() as i32 {+ 1 => sections.push(Section::peak(hz, db, p(at + te::BANDWIDTH), self.rate)),+ mode => {+ let count = p(at + te::ROLLOFF).round() as usize + 1;+ for _ in 0..count {+ let share = db / count as f64;+ sections.push(Section::shelf(hz, share, mode == 2, self.rate));+ }+ }+ }+ }+ if sections != self.sections {+ self.memory.clear();+ }+ self.sections = sections;+ for (k, on) in self.channels.iter_mut().enumerate() {+ *on = p(te::CHANNELS + k) >= 0.5;+ }+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let count = channels.len();+ self.memory+ .resize_with(count, || vec![[0.0; 4]; self.sections.len()]);+ for (c, ch) in channels.iter_mut().enumerate() {+ // BananaV's 5.1 order is L R C LFE Ls Rs; the switches' is L R C+ // Ls Rs LFE.+ let switch = [0, 1, 2, 5, 3, 4].get(c).copied().unwrap_or(c % 2);+ if !self.channels[switch] {+ continue;+ }+ for (s, m) in self.sections.iter().zip(self.memory[c].iter_mut()) {+ for x in ch.iter_mut() {+ *x = s.run(*x, m);+ }+ }+ }+ }+}++#[derive(Debug)]+pub(crate) struct ParagraphicEq {+ rate: f64,+ dry: f32,+ wet: f32,+ /// The bands (band-pass, how much of it is added) then the shelves+ /// (low- or high-pass, likewise).+ parts: Vec<(Section, f32)>,+ memory: Vec<Vec<[f32; 4]>>,+ /// One block's untouched sound, a channel.+ dry_copy: Vec<f32>,+}++impl ParagraphicEq {+ pub(crate) fn new(rate: u32) -> ParagraphicEq {+ ParagraphicEq {+ rate: rate.max(1) as f64,+ dry: 0.0,+ wet: 1.0,+ parts: Vec::new(),+ memory: Vec::new(),+ dry_copy: Vec::new(),+ }+ }+}++impl Own for ParagraphicEq {+ fn set(&mut self, params: &[f32]) {+ let p = |i: usize| {+ let s = &pq::PARAMS[i];+ params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max) as f64+ };+ self.dry = db_gain(p(pq::DRY) as f32, -25.0);+ self.wet = db_gain(p(pq::WET) as f32, -99.0);+ let mut parts = Vec::new();+ for band in 0..4 {+ let at = pq::BANDS + band * pq::PER_BAND;+ let more = 10f64.powf(p(at + pq::GAIN) / 20.0) - 1.0;+ let section = Section::band(p(at + pq::CENTER), p(at + pq::WIDTH), self.rate);+ parts.push((section, more as f32));+ }+ for (enable, high) in [(pq::LOW_SHELF, false), (pq::HIGH_SHELF, true)] {+ if p(enable) >= 0.5 {+ let more = 10f64.powf(p(enable + 2) / 20.0) - 1.0;+ parts.push((Section::pass(p(enable + 1), high, self.rate), more as f32));+ }+ }+ if parts.len() != self.parts.len() {+ self.memory.clear();+ }+ self.parts = parts;+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let count = channels.len();+ let parts = self.parts.len();+ self.memory.resize_with(count, || vec![[0.0; 4]; parts]);+ for (ch, memory) in channels.iter_mut().zip(self.memory.iter_mut()) {+ self.dry_copy.clear();+ self.dry_copy.extend_from_slice(ch);+ for ((s, more), m) in self.parts.iter().zip(memory.iter_mut()) {+ for x in ch.iter_mut() {+ *x += more * s.run(*x, m);+ }+ }+ let (dry, wet) = (self.dry, self.wet);+ for (x, d) in ch.iter_mut().zip(self.dry_copy.iter()) {+ *x = dry * d + wet * *x;+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn sine(hz: f32, n: usize) -> Vec<f32> {+ (0..n)+ .map(|i| (std::f32::consts::TAU * hz * i as f32 / 48_000.0).sin())+ .collect()+ }++ /// The level (dB) a sine at `hz` comes out at, once settled.+ fn level(fx: &mut dyn Own, hz: f32) -> f32 {+ let mut ch = vec![sine(hz, 48_000)];+ fx.process(&mut ch);+ let tail = &ch[0][24_000..];+ let power = tail.iter().map(|s| s * s).sum::<f32>() / tail.len() as f32;+ 10.0 * (2.0 * power).log10()+ }++ fn track_eq(values: &[(usize, f32)]) -> TrackEq {+ let mut e = TrackEq::new(48_000);+ let mut p: Vec<f32> = te::PARAMS.iter().map(|s| s.default).collect();+ for &(i, v) in values {+ p[i] = v;+ }+ e.set(&p);+ e+ }++ #[test]+ fn track_eq_at_0_db_leaves_the_sound_alone() {+ let mut e = track_eq(&[]);+ for hz in [50.0, 1000.0, 12_000.0] {+ assert!(+ level(&mut e, hz).abs() < 0.05,+ "{hz}: {}",+ level(&mut e, hz)+ );+ }+ }++ #[test]+ fn track_eq_peaks_and_shelves() {+ // Band 3 (a peak at 1 kHz) at −15 dB.+ let at = 2 * te::PER_BAND;+ let mut e = track_eq(&[(at + te::GAIN, -15.0)]);+ assert!(+ (level(&mut e, 1000.0) + 15.0).abs() < 0.3,+ "{}",+ level(&mut e, 1000.0)+ );+ assert!(level(&mut e, 100.0).abs() < 0.5);+ // Band 4 (a high shelf at 5 kHz, 12 dB an octave) at +6 dB.+ let at = 3 * te::PER_BAND;+ let mut e = track_eq(&[(at + te::GAIN, 6.0)]);+ assert!(+ (level(&mut e, 18_000.0) - 6.0).abs() < 0.5,+ "{}",+ level(&mut e, 18_000.0)+ );+ assert!(level(&mut e, 200.0).abs() < 0.3);+ // Band 1 (a low shelf at 100 Hz) at −12 dB, 24 dB an octave.+ let mut e = track_eq(&[(te::GAIN, -12.0), (te::ROLLOFF, 3.0)]);+ assert!(+ (level(&mut e, 20.0) + 12.0).abs() < 1.0,+ "{}",+ level(&mut e, 20.0)+ );+ assert!(level(&mut e, 2000.0).abs() < 0.3);+ }++ #[test]+ fn track_eq_leaves_out_the_channels_switched_off() {+ let at = 2 * te::PER_BAND;+ let mut e = track_eq(&[(at + te::GAIN, -15.0), (te::CHANNELS + 1, 0.0)]);+ let x = sine(1000.0, 4800);+ let mut ch = vec![x.clone(), x.clone()];+ e.process(&mut ch);+ assert_eq!(ch[1], x);+ assert_ne!(ch[0], x);+ }++ fn paragraphic(values: &[(usize, f32)]) -> ParagraphicEq {+ let mut e = ParagraphicEq::new(48_000);+ let mut p: Vec<f32> = pq::PARAMS.iter().map(|s| s.default).collect();+ for &(i, v) in values {+ p[i] = v;+ }+ e.set(&p);+ e+ }++ #[test]+ fn paragraphic_bands_and_shelves() {+ // Its defaults: no change.+ let mut e = paragraphic(&[]);+ assert!(level(&mut e, 1000.0).abs() < 0.05);+ // Band 3 at −15 dB: 1 kHz down 15 dB.+ let at = pq::BANDS + 2 * pq::PER_BAND;+ let mut e = paragraphic(&[(at + pq::GAIN, -15.0)]);+ assert!(+ (level(&mut e, 1000.0) + 15.0).abs() < 0.3,+ "{}",+ level(&mut e, 1000.0)+ );+ assert!(level(&mut e, 100.0).abs() < 0.5);+ // A low shelf at 250 Hz, +4 dB.+ let mut e = paragraphic(&[+ (pq::LOW_SHELF, 1.0),+ (pq::LOW_SHELF + 1, 250.0),+ (pq::LOW_SHELF + 2, 4.0),+ ]);+ assert!(+ (level(&mut e, 30.0) - 4.0).abs() < 0.3,+ "{}",+ level(&mut e, 30.0)+ );+ assert!(level(&mut e, 5000.0).abs() < 0.3);+ // The dry sound mixed back: wet off, dry at 0 dB.+ let mut e = paragraphic(&[(pq::DRY, 0.0), (pq::WET, -25.0), (at + pq::GAIN, -15.0)]);+ let wet = 10f32.powf(-25.0 / 20.0);+ let expect = 20.0 * (1.0 + wet * 10f32.powf(-15.0 / 20.0)).log10();+ assert!(+ (level(&mut e, 1000.0) - expect).abs() < 0.3,+ "{}",+ level(&mut e, 1000.0)+ );+ }+}diff --git a/crates/mixer/src/fx/express.rs b/crates/mixer/src/fx/express.rsnew file mode 100644index 0000000..5c9876a--- /dev/null+++ b/crates/mixer/src/fx/express.rs@@ -0,0 +1,625 @@+//! The Express effects, as VEGAS's: small versions of the full ones, most+//! mixed with the untouched sound by a "… / Original" control (see+//! [`Mixed`]).+//!+//! Express Delay: a comb, each echo the decay's share of the one before.+//! Express Distortion: past a knee the sound follows the slew's slope+//! (soft, or harder with hard clipping), the faintest sound is thinned+//! out, a short comb (half the distortion's tenths of a millisecond back)+//! colours it, and it may move only so fast from sample to sample.+//! Express Equalization: a low shelf at 300 Hz, a band at 400 Hz 2.5+//! octaves wide and a high shelf at 500 Hz (−25 dB takes each out).+//! Express Stutter: the sound on for its length and off for the silence's,+//! each sounding stretch faded in and out over an eighth of it; with Add+//! space the second channel runs half a round on. Express Amplitude+//! Modulation: the level follows a smooth wave, its bottom at 1 − depth.++use bv_timeline::audio_fx::{+ express_amplitude_modulation as xam, express_delay as xd, express_distortion as xdi,+ express_equalization as xeq, express_stutter as xs,+};++use super::eq::Section;+use super::{Own, Ramp};++/// Added and taken away again on fed-back state, so a fading signal ends+/// at 0 instead of lingering as a denormal number.+const FLUSH: f32 = 1e-18;++/// An effect mixed with the sound it was given: `mix` of what it makes,+/// the rest of the sound as it came. Its own values come from the+/// effect's through `map`.+#[derive(Debug)]+pub(crate) struct Mixed<T> {+ inner: T,+ map: fn(&[f32]) -> Vec<f32>,+ mix_at: usize,+ mix: Ramp,+ dry: Vec<Vec<f32>>,+}++impl<T: Own> Mixed<T> {+ pub(crate) fn new(inner: T, map: fn(&[f32]) -> Vec<f32>, mix_at: usize) -> Mixed<T> {+ Mixed {+ inner,+ map,+ mix_at,+ mix: Ramp::new(1.0),+ dry: Vec::new(),+ }+ }+}++impl<T: Own> Own for Mixed<T> {+ fn set(&mut self, params: &[f32]) {+ self.mix.set(+ params+ .get(self.mix_at)+ .copied()+ .unwrap_or(1.0)+ .clamp(0.0, 1.0),+ );+ self.inner.set(&(self.map)(params));+ }++ fn keep_time(&mut self, tempo: &bv_timeline::Tempo) {+ self.inner.keep_time(tempo);+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ self.dry.resize_with(channels.len(), Vec::new);+ for (d, ch) in self.dry.iter_mut().zip(channels.iter()) {+ d.clear();+ d.extend_from_slice(ch);+ }+ self.inner.process(channels);+ let (start, step) = self.mix.block(n);+ for (ch, dry) in channels.iter_mut().zip(self.dry.iter()) {+ for (i, (x, d)) in ch.iter_mut().zip(dry.iter()).enumerate() {+ let m = start + step * i as f32;+ *x = m * *x + (1.0 - m) * d;+ }+ }+ }+}++/// The values as they are (for an inner effect that reads the same ones).+pub(crate) fn same(params: &[f32]) -> Vec<f32> {+ params.to_vec()+}++/// A value of `params`, its default when missing, in its range.+fn value(params: &[f32], specs: &[bv_timeline::ParamSpec], i: usize) -> f32 {+ let s = &specs[i];+ params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+}++/// Express Delay's echo alone.+#[derive(Debug)]+pub(crate) struct ExpressDelay {+ rate: f32,+ lines: Vec<Vec<f32>>,+ len: usize,+ at: usize,+ feedback: f32,+}++impl ExpressDelay {+ pub(crate) fn new(rate: u32) -> ExpressDelay {+ ExpressDelay {+ rate: rate.max(1) as f32,+ lines: Vec::new(),+ len: 1,+ at: 0,+ feedback: 0.0,+ }+ }+}++impl Own for ExpressDelay {+ fn set(&mut self, params: &[f32]) {+ let ms = value(params, xd::PARAMS, xd::DELAY);+ let len = ((ms * self.rate / 1000.0).round() as usize).max(1);+ if len != self.len {+ self.len = len;+ for l in &mut self.lines {+ l.clear();+ l.resize(len, 0.0);+ }+ self.at = 0;+ }+ self.feedback = value(params, xd::PARAMS, xd::DECAY);+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let len = self.len;+ self.lines.resize_with(channels.len(), || vec![0.0; len]);+ let g = self.feedback;+ let mut end = self.at;+ for (ch, line) in channels.iter_mut().zip(self.lines.iter_mut()) {+ let mut at = self.at;+ let mut i = 0;+ while i < n {+ // Up to the line's end, nothing read was written here.+ let m = (len - at).min(n - i);+ for (x, d) in ch[i..i + m].iter_mut().zip(line[at..at + m].iter_mut()) {+ let echo = *d;+ *d = (*x + g * echo + FLUSH) - FLUSH;+ *x = echo;+ }+ i += m;+ at += m;+ if at == len {+ at = 0;+ }+ }+ end = at;+ }+ self.at = end;+ }+}++/// Express Distortion's distorted sound alone.+#[derive(Debug, Default)]+pub(crate) struct ExpressDistortion {+ slope: f32,+ knee: f32,+ gain: f32,+ quiet: f32,+ back: usize,+ step: f32,+ /// Each channel's last 500 samples and its last output.+ lines: Vec<Vec<f32>>,+ at: usize,+ last: Vec<f32>,+}++impl Own for ExpressDistortion {+ fn set(&mut self, params: &[f32]) {+ let p = |i| value(params, xdi::PARAMS, i);+ let d = p(xdi::DISTORTION).min(0.999);+ let slew = p(xdi::SLEW);+ if p(xdi::HARD) >= 0.5 {+ self.slope = 1.0 - 0.95 * slew;+ self.knee = 0.5 * self.slope + 0.5;+ self.gain = 1.0;+ } else {+ // The slew's thousandths, 1 to 1000, on a log scale: 1 to 0.02.+ self.slope = 1.0 - 0.98 * (slew * 1000.0).max(1.0).log10() / 3.0;+ self.knee = self.slope;+ self.gain = 1.0 / ((1.0 - self.slope) * self.slope + self.slope);+ }+ self.quiet = (1.0 - d) * 0.01;+ self.back = ((p(xdi::DISTORTION) * 500.0).round() as usize).min(499);+ self.step = 1.0 - 0.9 * d;+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let count = channels.len();+ self.lines.resize_with(count, || vec![0.0; 500]);+ self.last.resize(count, 0.0);+ let at0 = self.at;+ for (c, ch) in channels.iter_mut().enumerate() {+ let line = &mut self.lines[c];+ let mut last = self.last[c];+ let mut at = at0;+ for x in ch.iter_mut() {+ let v = *x;+ let t = self.knee;+ let mut y = if v > t {+ t + (v - t) * self.slope+ } else if v < -t {+ -t + (v + t) * self.slope+ } else {+ v+ };+ if v.abs() < self.quiet {+ y *= v.abs() / 0.01;+ }+ y *= self.gain;+ line[at] = y;+ if self.back > 0 {+ y = (y + line[(at + 500 - self.back) % 500]) / 2.0;+ }+ at = (at + 1) % 500;+ y = y.clamp(last - self.step, last + self.step);+ last = y;+ *x = y;+ }+ self.last[c] = last;+ if c + 1 == count {+ self.at = at;+ }+ }+ }+}++/// Express Equalization's equalized sound alone.+#[derive(Debug)]+pub(crate) struct ExpressEq {+ rate: f64,+ /// Each part (a filter and how much of it is added).+ parts: [(Section, f32); 3],+ memory: Vec<[[f32; 4]; 3]>,+}++impl ExpressEq {+ pub(crate) fn new(rate: u32) -> ExpressEq {+ let fs = rate.max(1) as f64;+ ExpressEq {+ rate: fs,+ parts: [+ (Section::pass(300.0, false, fs), 0.0),+ (Section::band(400.0, 2.5, fs), 0.0),+ (Section::pass(500.0, true, fs), 0.0),+ ],+ memory: Vec::new(),+ }+ }+}++impl Own for ExpressEq {+ fn set(&mut self, params: &[f32]) {+ let more = |i| {+ let db = value(params, xeq::PARAMS, i);+ if db <= -25.0 {+ -1.0+ } else {+ 10f32.powf(db / 20.0) - 1.0+ }+ };+ let _ = self.rate;+ self.parts[0].1 = more(xeq::BASS);+ self.parts[1].1 = more(xeq::MID);+ self.parts[2].1 = more(xeq::TREBLE);+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ self.memory.resize(channels.len(), [[0.0; 4]; 3]);+ for (ch, memory) in channels.iter_mut().zip(self.memory.iter_mut()) {+ for ((s, more), m) in self.parts.iter().zip(memory.iter_mut()) {+ for x in ch.iter_mut() {+ *x += more * s.run(*x, m);+ }+ }+ }+ }+}++/// Express Stutter's gated sound alone.+#[derive(Debug)]+pub(crate) struct ExpressStutter {+ rate: f32,+ sound: usize,+ silence: usize,+ space: bool,+ /// Where in the round the first channel is.+ at: usize,+}++impl ExpressStutter {+ pub(crate) fn new(rate: u32) -> ExpressStutter {+ ExpressStutter {+ rate: rate.max(1) as f32,+ sound: 1,+ silence: 1,+ space: false,+ at: 0,+ }+ }++ /// The gain `at` samples into a round: the sound faded in and out+ /// over an eighth of it, then silence.+ fn gain(&self, at: usize) -> f32 {+ if at >= self.sound {+ return 0.0;+ }+ let edge = (self.sound as f32 * 0.125).max(1.0);+ let from_end = (self.sound - at) as f32;+ (at as f32 / edge).min(from_end / edge).min(1.0)+ }+}++impl Own for ExpressStutter {+ fn set(&mut self, params: &[f32]) {+ let ms = |i| value(params, xs::PARAMS, i) * self.rate / 1000.0;+ self.sound = (ms(xs::SOUND).round() as usize).max(1);+ self.silence = (ms(xs::SILENCE).round() as usize).max(1);+ self.space = value(params, xs::PARAMS, xs::SPACE) >= 0.5;+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let round = self.sound + self.silence;+ let start = self.at % round;+ for (c, ch) in channels.iter_mut().enumerate() {+ let shift = if self.space && c % 2 == 1 {+ round / 2+ } else {+ 0+ };+ for (i, x) in ch.iter_mut().enumerate() {+ *x *= self.gain((start + shift + i) % round);+ }+ }+ self.at = (start + n) % round;+ }+}++/// Express Amplitude Modulation's wave: a smooth one, as its presets+/// draw it (time 0–1000, level 0 at the top to −100 at the bottom).+const AM_WAVE: [(f32, f32); 12] = [+ (0.0, -50.0),+ (125.0, -12.0),+ (188.0, -3.0),+ (250.0, 0.0),+ (313.0, -3.0),+ (375.0, -12.0),+ (625.0, -88.0),+ (688.0, -97.0),+ (750.0, -100.0),+ (813.0, -97.0),+ (875.0, -88.0),+ (1000.0, -50.0),+];++/// Express Amplitude Modulation's modulated sound alone.+#[derive(Debug)]+pub(crate) struct ExpressAm {+ rate: f32,+ /// The wave's level over a round, 1001 steps, as gains.+ gains: Vec<f32>,+ step: f32,+ phase: f32,+}++impl ExpressAm {+ pub(crate) fn new(rate: u32) -> ExpressAm {+ ExpressAm {+ rate: rate.max(1) as f32,+ gains: vec![1.0; 1001],+ step: 0.0,+ phase: 0.0,+ }+ }+}++impl Own for ExpressAm {+ fn set(&mut self, params: &[f32]) {+ let depth = value(params, xam::PARAMS, xam::DEPTH);+ let hz = value(params, xam::PARAMS, xam::RATE);+ self.step = 1000.0 / (self.rate / hz).max(1.0);+ for (t, g) in self.gains.iter_mut().enumerate() {+ let t = t as f32;+ let k = AM_WAVE+ .partition_point(|p| p.0 <= t)+ .clamp(1, AM_WAVE.len() - 1);+ let ((t0, v0), (t1, v1)) = (AM_WAVE[k - 1], AM_WAVE[k]);+ let v = v0 + (v1 - v0) * ((t - t0) / (t1 - t0)).clamp(0.0, 1.0);+ // A linear depth: the bottom of the wave at 1 − depth.+ *g = (1.0 - depth).max(0.0).powf(-v / 100.0);+ }+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let start = self.phase;+ for ch in channels.iter_mut() {+ let mut phase = start;+ for x in ch.iter_mut() {+ *x *= self.gains[(phase as usize).min(1000)];+ phase += self.step;+ if phase >= 1000.0 {+ phase -= 1000.0;+ }+ }+ }+ self.phase = (start + self.step * n as f32) % 1000.0;+ }+}++/// An effect that reads its values through `map` (the Express versions+/// of the full effects, their other values fixed).+#[derive(Debug)]+pub(crate) struct Mapped<T> {+ inner: T,+ map: fn(&[f32]) -> Vec<f32>,+}++impl<T: Own> Mapped<T> {+ pub(crate) fn new(inner: T, map: fn(&[f32]) -> Vec<f32>) -> Mapped<T> {+ Mapped { inner, map }+ }+}++impl<T: Own> Own for Mapped<T> {+ fn set(&mut self, params: &[f32]) {+ self.inner.set(&(self.map)(params));+ }++ fn keep_time(&mut self, tempo: &bv_timeline::Tempo) {+ self.inner.keep_time(tempo);+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ self.inner.process(channels);+ }++ fn latency(&self) -> usize {+ self.inner.latency()+ }+}++/// Express Chorus as the full Chorus: 0 dB in, dry and chorus, no+/// feedback nor cut, a 20 ms delay.+pub(crate) fn chorus_values(params: &[f32]) -> Vec<f32> {+ use bv_timeline::audio_fx::{chorus as co, express_chorus as xc};+ let p = |i| value(params, xc::PARAMS, i);+ let mut v: Vec<f32> = co::PARAMS.iter().map(|s| s.default).collect();+ v[co::INPUT] = 0.0;+ v[co::DRY] = 0.0;+ v[co::WET] = 0.0;+ v[co::INVERT] = 0.0;+ v[co::INVERT_FEEDBACK] = 0.0;+ v[co::SIZE] = p(xc::SIZE);+ v[co::RATE] = p(xc::RATE);+ v[co::DEPTH] = p(xc::DEPTH);+ v[co::FEEDBACK] = 0.0;+ v[co::DELAY] = 20.0;+ v[co::ATTENUATE] = 0.0;+ v[co::SYNC] = 0.0;+ v+}++/// Express Flange/Wah-Wah as the full one: wet only (the mix does the+/// rest), the wah's centre at 500 Hz and its resonance at 75 %.+pub(crate) fn flange_values(params: &[f32]) -> Vec<f32> {+ use bv_timeline::audio_fx::{express_flange_wah_wah as xf, flange_wah_wah as fw};+ let p = |i| value(params, xf::PARAMS, i);+ let mut v: Vec<f32> = fw::PARAMS.iter().map(|s| s.default).collect();+ v[fw::EFFECT] = if p(xf::EFFECT) >= 0.5 { 2.0 } else { 0.0 };+ v[fw::DRY] = -80.0;+ v[fw::WET] = 0.0;+ v[fw::RATE] = p(xf::RATE);+ v[fw::DEPTH] = p(xf::DEPTH);+ v[fw::CENTER] = 500.0;+ v[fw::RESONANCE] = 0.75;+ v[fw::SYNC] = 0.0;+ v+}++/// Express Dynamics as the Track Compressor: no gains, its top ratio a+/// limiter.+pub(crate) fn dynamics_values(params: &[f32]) -> Vec<f32> {+ use bv_timeline::audio_fx::{express_dynamics as xy, track_compressor as tc};+ let p = |i| value(params, xy::PARAMS, i);+ let mut v: Vec<f32> = tc::PARAMS.iter().map(|s| s.default).collect();+ v[tc::INPUT] = 0.0;+ v[tc::OUTPUT] = 0.0;+ v[tc::THRESHOLD] = p(xy::THRESHOLD);+ let ratio = p(xy::RATIO);+ v[tc::RATIO] = if ratio >= 50.0 { 500.0 } else { ratio };+ v[tc::ATTACK] = p(xy::ATTACK);+ v[tc::RELEASE] = p(xy::RELEASE);+ v[tc::AUTO_GAIN] = p(xy::AUTO_GAIN);+ v[tc::SMOOTH] = 0.0;+ v+}++/// Express Reverb as the full Reverb: its room, the size setting the+/// decay (0.5 to 5 s) and the liveliness the pre-delay (0 to 200 ms),+/// the reverb at −24 dB and the early reflections at −16 dB.+pub(crate) fn reverb_values(params: &[f32]) -> Vec<f32> {+ use bv_timeline::audio_fx::{express_reverb as xr, reverb as rv};+ let p = |i| value(params, xr::PARAMS, i);+ let mut v: Vec<f32> = rv::PARAMS.iter().map(|s| s.default).collect();+ v[rv::MODE] = p(xr::ROOM);+ v[rv::DRY] = -80.0;+ v[rv::WET] = -24.0;+ v[rv::EARLY] = -16.0;+ v[rv::STYLE] = 2.0;+ v[rv::DECAY] = 0.5 + 4.5 * p(xr::SIZE);+ v[rv::PREDELAY] = 200.0 * p(xr::LIVELINESS);+ v+}++#[cfg(test)]+mod tests {+ use super::*;+ use bv_timeline::audio_fx::express_noise_gate as xg;++ fn with(specs: &[bv_timeline::ParamSpec], values: &[(usize, f32)]) -> Vec<f32> {+ let mut p: Vec<f32> = specs.iter().map(|s| s.default).collect();+ for &(i, v) in values {+ p[i] = v;+ }+ p+ }++ #[test]+ fn the_mix_shares_the_sound_and_the_echo() {+ let mut d = Mixed::new(ExpressDelay::new(48_000), same, xd::MIX);+ d.set(&with(xd::PARAMS, &[(xd::DELAY, 10.0), (xd::MIX, 0.5)]));+ let mut x = vec![vec![0.0f32; 2_000]];+ x[0][0] = 1.0;+ d.process(&mut x);+ assert!((x[0][0] - 0.5).abs() < 1e-6);+ assert!((x[0][480] - 0.5).abs() < 1e-6, "{}", x[0][480]);+ // Fed back by the decay: each echo that share of the one before.+ let mut d = Mixed::new(ExpressDelay::new(48_000), same, xd::MIX);+ d.set(&with(+ xd::PARAMS,+ &[(xd::DELAY, 10.0), (xd::DECAY, 0.5), (xd::MIX, 1.0)],+ ));+ let mut x = vec![vec![0.0f32; 2_000]];+ x[0][0] = 1.0;+ d.process(&mut x);+ assert!((x[0][960] / x[0][480] - 0.5).abs() < 1e-6);+ }++ #[test]+ fn the_stutter_switches_the_sound_off_and_on() {+ let mut s = Mixed::new(ExpressStutter::new(48_000), same, xs::MIX);+ s.set(&with(+ xs::PARAMS,+ &[(xs::SOUND, 10.0), (xs::SILENCE, 10.0), (xs::MIX, 1.0)],+ ));+ let mut x = vec![vec![1.0f32; 1_920]];+ s.process(&mut x);+ // Sounding in the middle of the first 10 ms, silent in the next.+ assert!((x[0][240] - 1.0).abs() < 1e-6);+ assert!(x[0][480..960].iter().all(|v| *v == 0.0));+ assert!((x[0][960 + 240] - 1.0).abs() < 1e-6);+ }++ #[test]+ fn amplitude_modulation_follows_its_wave() {+ let mut m = Mixed::new(ExpressAm::new(48_000), same, xam::MIX);+ m.set(&with(+ xam::PARAMS,+ &[(xam::RATE, 1.0), (xam::DEPTH, 0.5), (xam::MIX, 1.0)],+ ));+ let mut x = vec![vec![1.0f32; 48_000]];+ m.process(&mut x);+ // The top of the wave a quarter round in, its bottom (1 − depth)+ // three quarters in.+ assert!((x[0][12_000] - 1.0).abs() < 1e-3, "{}", x[0][12_000]);+ assert!((x[0][36_000] - 0.5).abs() < 1e-3, "{}", x[0][36_000]);+ }++ #[test]+ fn express_eq_at_0_db_and_cutting_the_bass() {+ let level = |values: &[(usize, f32)], hz: f32| {+ let mut e = Mixed::new(ExpressEq::new(48_000), same, xeq::MIX);+ e.set(&with(xeq::PARAMS, values));+ let mut x = vec![+ (0..48_000)+ .map(|i| (std::f32::consts::TAU * hz * i as f32 / 48_000.0).sin())+ .collect::<Vec<f32>>(),+ ];+ e.process(&mut x);+ let tail = &x[0][24_000..];+ 10.0 * (2.0 * tail.iter().map(|s| s * s).sum::<f32>() / tail.len() as f32).log10()+ };+ assert!(level(&[], 1000.0).abs() < 0.05);+ // Taking the low-pass away leaves a gentle slope: well down by 30 Hz.+ assert!(level(&[(xeq::BASS, -25.0)], 30.0) < -12.0);+ assert!(level(&[(xeq::BASS, -25.0)], 8000.0).abs() < 0.5);+ }++ #[test]+ fn express_noise_gate_reads_the_noise_gate_s_values() {+ assert_eq!(xg::PARAMS.len(), 3);+ let mut g = super::super::dynamics::Gate::new(48_000);+ g.set(&with(xg::PARAMS, &[]));+ let mut x = vec![vec![0.01f32; 4_800]];+ g.process(&mut x);+ assert!(x[0].iter().all(|v| v.abs() < 1e-6));+ }+}diff --git a/crates/mixer/src/fx/filters.rs b/crates/mixer/src/fx/filters.rsnew file mode 100644index 0000000..33e1283--- /dev/null+++ b/crates/mixer/src/fx/filters.rs@@ -0,0 +1,295 @@+//! Smooth/Enhance and Resonant Filter, as VEGAS's.+//!+//! Smooth/Enhance: a first-order filter a channel, `y = (1 − p)·x ± p·y₁`+//! with `p = e^(−2π·f)`, `f` a part of the sampling rate; smoothing puts+//! the pole at `+p` (a low pass), enhancing at `−p` with a gain after it+//! (the lows back near 0 dB, the highs raised).+//!+//! Resonant Filter: a state-variable filter (Chamberlin's), its low-,+//! band- and high-pass at once, run three times a sample so that it stays+//! steady near the top of the band; the fourth order is two in a row.++use bv_timeline::audio_fx::{resonant_filter as rf, smooth_enhance};++use super::{Own, Ramp};++/// Each `Operation`'s cutoff (a part of the rate), whether it enhances,+/// and its gain after the filter: −5 to −1 smooth, 1 to 5 enhance.+const STEPS: [(f32, bool, f32); 10] = [+ (0.008, false, 1.0),+ (0.02, false, 1.0),+ (0.06, false, 1.0),+ (0.15, false, 1.0),+ (0.25, false, 1.0),+ (0.2, true, 1.78),+ (0.15, true, 2.5),+ (0.1, true, 3.1),+ (0.08, true, 4.0),+ (0.05, true, 5.6),+];++/// Below this the filter's memory is 0 (no denormal numbers).+const TINY: f32 = 2e-11;++#[derive(Debug, Default)]+pub(crate) struct SmoothEnhance {+ /// The filter's `a`, `b` and gain; none at 0.+ coefs: Option<(f32, f32, f32)>,+ /// Each channel's last output before the gain.+ memory: Vec<f32>,+}++impl Own for SmoothEnhance {+ fn set(&mut self, params: &[f32]) {+ let k = params+ .get(smooth_enhance::OPERATION)+ .copied()+ .unwrap_or(0.0)+ .round()+ .clamp(-5.0, 5.0) as i32;+ self.coefs = match k {+ 0 => None,+ k => {+ let (f, enhance, gain) = STEPS[if k < 0 {+ (k + 5) as usize+ } else {+ (k + 4) as usize+ }];+ let p = (-std::f32::consts::TAU * f).exp();+ Some((1.0 - p, if enhance { -p } else { p }, gain))+ }+ };+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let Some((a, b, gain)) = self.coefs else {+ return;+ };+ self.memory.resize(channels.len(), 0.0);+ for (ch, y1) in channels.iter_mut().zip(self.memory.iter_mut()) {+ // A recursion along time: each channel on its own.+ let mut y = *y1;+ for s in ch.iter_mut() {+ y = a * *s + b * y;+ if y.abs() < TINY {+ y = 0.0;+ }+ *s = y * gain;+ }+ *y1 = y;+ }+ }+}++/// Added and taken away again on the filters' memory, so a fading+/// signal ends at 0 instead of lingering as a denormal number.+const FLUSH: f32 = 1e-18;++#[derive(Debug)]+pub(crate) struct ResonantFilter {+ rate: f32,+ /// Its frequency (Hz), damping and wet part, gliding over a block.+ freq: Ramp,+ damping: Ramp,+ wet: Ramp,+ /// 0 low-pass, 1 band-pass, 2 high-pass.+ kind: usize,+ fourth: bool,+ /// Each channel's two sections' low-pass and band-pass memories.+ state: Vec<[f32; 4]>,+}++impl ResonantFilter {+ pub(crate) fn new(rate: u32) -> ResonantFilter {+ ResonantFilter {+ rate: rate.max(1) as f32,+ freq: Ramp::new(20_000.0),+ damping: Ramp::new(std::f32::consts::SQRT_2),+ wet: Ramp::new(1.0),+ kind: 0,+ fourth: false,+ state: Vec::new(),+ }+ }+}++/// The filter's frequency coefficient at `hz` and sampling rate `rate`:+/// three steps a sample.+fn coef(rate: f32, hz: f32) -> f32 {+ 2.0 * (std::f32::consts::PI * (hz / (3.0 * rate)).clamp(0.0, 0.1512)).sin()+}++/// One sample through a section (its low-pass and band-pass memories),+/// three steps; its low-, band- and high-pass.+#[inline(always)]+fn section(x: f32, f: f32, q: f32, low: &mut f32, band: &mut f32) -> [f32; 3] {+ let mut high = 0.0;+ for _ in 0..3 {+ *low += f * *band;+ high = x - *low - q * *band;+ *band += f * high;+ }+ *low = (*low + FLUSH) - FLUSH;+ *band = (*band + FLUSH) - FLUSH;+ [*low, *band, high]+}++impl Own for ResonantFilter {+ fn set(&mut self, params: &[f32]) {+ let p = |i: usize| params.get(i).copied().unwrap_or(rf::PARAMS[i].default);+ self.freq.set(p(rf::FREQUENCY).clamp(1.0, 96_000.0));+ // 0 %: a damping of √2 (no peak); 100 %: 0.04 (a peak 28 dB high).+ let res = p(rf::RESONANCE).clamp(0.0, 1.0);+ self.damping+ .set(1.0 / (res * 24.2929 + std::f32::consts::FRAC_1_SQRT_2));+ self.wet.set(p(rf::MIX).clamp(0.0, 1.0));+ self.kind = p(rf::TYPE).round().clamp(0.0, 2.0) as usize;+ self.fourth = p(rf::ORDER) >= 0.5;+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let (f0, f_step) = self.freq.block(n);+ let (q0, q_step) = self.damping.block(n);+ let (w0, w_step) = self.wet.block(n);+ self.state.resize(channels.len(), [0.0; 4]);+ let (rate, kind, fourth) = (self.rate, self.kind, self.fourth);+ let fixed = coef(rate, f0);+ for (ch, st) in channels.iter_mut().zip(self.state.iter_mut()) {+ let [mut l1, mut b1, mut l2, mut b2] = *st;+ for (i, x) in ch.iter_mut().enumerate() {+ let t = i as f32;+ // A frequency moving within the block: its coefficient+ // worked out again at every sample, so a sweep is smooth.+ let f = if f_step == 0.0 {+ fixed+ } else {+ coef(rate, f0 + f_step * t)+ };+ let q = q0 + q_step * t;+ let mut y = section(*x, f, q, &mut l1, &mut b1)[kind];+ if fourth {+ y = section(y, f, q, &mut l2, &mut b2)[kind];+ }+ let w = w0 + w_step * t;+ *x = w * y + (1.0 - w) * *x;+ }+ *st = [l1, b1, l2, b2];+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ /// The response at DC and at half the rate, from a steady signal and+ /// one alternating every sample.+ fn ends(k: f32) -> (f32, f32) {+ let mut f = SmoothEnhance::default();+ f.set(&[k]);+ let mut dc = vec![vec![1.0f32; 4000]];+ f.process(&mut dc);+ let mut f = SmoothEnhance::default();+ f.set(&[k]);+ let mut nyq = vec![+ (0..4000)+ .map(|i| if i % 2 == 0 { 1.0 } else { -1.0 })+ .collect(),+ ];+ f.process(&mut nyq);+ (dc[0][3999], nyq[0][3999].abs())+ }++ #[test]+ fn smoothing_keeps_the_lows_and_cuts_the_highs() {+ let (dc, top) = ends(-5.0);+ assert!((dc - 1.0).abs() < 1e-4, "{dc}");+ let p = (-std::f32::consts::TAU * 0.008).exp();+ assert!((top - (1.0 - p) / (1.0 + p)).abs() < 1e-4, "{top}");+ // About −32 dB at half the rate.+ assert!((20.0 * top.log10() + 32.0).abs() < 1.0, "{top}");+ }++ #[test]+ fn enhancing_raises_the_highs_by_its_gain() {+ // 1: −0.08 dB in the lows, +5 dB at half the rate.+ let (dc, top) = ends(1.0);+ assert!((20.0 * dc.log10() + 0.08).abs() < 0.05, "{dc}");+ assert!((20.0 * top.log10() - 5.0).abs() < 0.05, "{top}");+ // 5: +15 dB.+ let (_, top) = ends(5.0);+ assert!((20.0 * top.log10() - 15.0).abs() < 0.05, "{top}");+ }++ fn sine(hz: f32, n: usize) -> Vec<f32> {+ (0..n)+ .map(|i| (std::f32::consts::TAU * hz * i as f32 / 48_000.0).sin())+ .collect()+ }++ /// The level (dB) a sine at `hz` comes out at, once settled.+ fn level(params: &[f32], hz: f32) -> f32 {+ let mut f = ResonantFilter::new(48_000);+ f.set(params);+ let mut ch = vec![sine(hz, 48_000)];+ f.process(&mut ch);+ // Its amplitude from its power (a sampled sine's peak can miss it).+ let tail = &ch[0][24_000..];+ let power = tail.iter().map(|s| s * s).sum::<f32>() / tail.len() as f32;+ 10.0 * (2.0 * power).log10()+ }++ #[test]+ fn low_pass_keeps_the_lows_and_rings_at_its_frequency() {+ // 1 kHz, no resonance: 0 dB well below, −3 dB at it, falling above.+ let flat = [1000.0, 0.0, 1.0, 0.0, 0.0];+ assert!(level(&flat, 100.0).abs() < 0.2);+ assert!(+ (level(&flat, 1000.0) + 3.0).abs() < 0.5,+ "{}",+ level(&flat, 1000.0)+ );+ assert!(level(&flat, 8000.0) < -30.0);+ // Full resonance: a peak of about 28 dB at the frequency.+ let ringing = [1000.0, 1.0, 1.0, 0.0, 0.0];+ assert!(+ (level(&ringing, 1000.0) - 28.0).abs() < 1.0,+ "{}",+ level(&ringing, 1000.0)+ );+ // The fourth order falls about twice as steeply.+ let fourth = [1000.0, 0.0, 1.0, 0.0, 1.0];+ assert!(level(&fourth, 3000.0) < 1.9 * level(&flat, 3000.0));+ }++ #[test]+ fn band_and_high_pass_choose_their_output() {+ let band = [1000.0, 0.0, 1.0, 1.0, 0.0];+ assert!(level(&band, 1000.0) > level(&band, 100.0) + 15.0);+ assert!(level(&band, 1000.0) > level(&band, 10_000.0) + 15.0);+ let high = [1000.0, 0.0, 1.0, 2.0, 0.0];+ assert!(level(&high, 8000.0).abs() < 0.5);+ assert!(level(&high, 100.0) < -30.0);+ }++ #[test]+ fn wet_dry_blends_back_the_sound() {+ // Dry only: the sound as it was.+ let mut f = ResonantFilter::new(48_000);+ f.set(&[200.0, 1.0, 0.0, 0.0, 0.0]);+ let x = sine(5000.0, 4800);+ let mut ch = vec![x.clone()];+ f.process(&mut ch);+ assert!(ch[0].iter().zip(&x).all(|(a, b)| (a - b).abs() < 1e-6));+ }++ #[test]+ fn zero_leaves_the_sound_alone() {+ let mut f = SmoothEnhance::default();+ f.set(&[0.0]);+ let mut ch = vec![vec![0.3f32, -0.7, 0.1]];+ f.process(&mut ch);+ assert_eq!(ch[0], [0.3, -0.7, 0.1]);+ }+}diff --git a/crates/mixer/src/fx/fir.rs b/crates/mixer/src/fx/fir.rsnew file mode 100644index 0000000..7b93d3b--- /dev/null+++ b/crates/mixer/src/fx/fir.rs@@ -0,0 +1,428 @@+//! The EQs applied as FIR filters through FFTs, as VEGAS's: Parametric EQ+//! and Express Graphic EQ. Each draws a frequency response bin by bin —+//! the Parametric EQ a shelf, a band-pass or a notch/boost with straight+//! ramps at its edges; the Express Graphic EQ ten bands an octave apart,+//! joined by straight lines in dB along the octaves — times the output+//! gain. [`Fir`] makes it a linear-phase FIR filter half the FFT long+//! (windowed) and applies it through FFTs, half an FFT of sound at a time+//! (overlap-add). Two channels share each transform, one as its real part+//! and the other as its imaginary, the filter being the same on both. A+//! new response takes over at the next half FFT.++use bv_timeline::audio_fx::{express_graphic_eq as geq, graphic_eq as ge, parametric_eq as pe};++use crate::fft::{Complex, Plan};++use super::Own;++/// How far past a band's edge its ramp goes (a ratio of frequencies).+const EDGE: f64 = 1.2;++/// A linear-phase FIR filter applied through FFTs.+#[derive(Debug)]+pub(crate) struct Fir {+ rate: f64,+ size: usize,+ plan: Plan,+ /// The filter's spectrum, `size` bins.+ filter: Vec<Complex>,+ /// Each channel's sound gathered in this half, its sound due out in+ /// this half, and what the last transform left for the next.+ input: Vec<Vec<f32>>,+ output: Vec<Vec<f32>>,+ tail: Vec<Vec<f32>>,+ /// Where in the half the next sample goes.+ at: usize,+ work: Vec<Complex>,+}++impl Fir {+ pub(crate) fn new(rate: u32) -> Fir {+ Fir {+ rate: rate.max(1) as f64,+ size: 0,+ plan: Plan::default(),+ filter: Vec::new(),+ input: Vec::new(),+ output: Vec::new(),+ tail: Vec::new(),+ at: 0,+ work: Vec::new(),+ }+ }++ /// An FFT `size` long: another length starts the sound in flight again.+ fn resize(&mut self, size: usize) {+ if size != self.size {+ self.size = size;+ self.plan = Plan::new(size);+ for v in [&mut self.input, &mut self.output, &mut self.tail] {+ v.clear();+ }+ self.at = 0;+ }+ }++ /// The filter for `response`, a linear gain at each frequency (Hz).+ fn design(&mut self, response: impl Fn(f64) -> f64) {+ let n = self.size;+ let taps = n / 2;+ // The zero-phase response (real and even), back to time.+ let mut w: Vec<Complex> = (0..n)+ .map(|k| {+ let bin = k.min(n - k) as f64;+ Complex::new(response(bin * self.rate / n as f64), 0.0)+ })+ .collect();+ self.plan.run(&mut w, true);+ // Half an FFT of taps centred on the middle one, through a+ // Blackman window: linear phase, `taps / 2` samples late.+ let mut h = vec![Complex::ZERO; n];+ for (m, t) in h.iter_mut().take(taps).enumerate() {+ let x = (m as f64 - (taps / 2) as f64) / (taps / 2) as f64;+ let window = 0.42+ + 0.5 * (std::f64::consts::PI * x).cos()+ + 0.08 * (std::f64::consts::TAU * x).cos();+ t.re = w[(m + n - taps / 2) % n].re * window;+ }+ self.plan.run(&mut h, false);+ self.filter = h;+ }++ /// The gathered half through the filter, two channels at a time.+ fn convolve(&mut self) {+ let n = self.size;+ let half = n / 2;+ let count = self.input.len();+ for a in (0..count).step_by(2) {+ let b = (a + 1 < count).then_some(a + 1);+ self.work.clear();+ self.work.resize(n, Complex::ZERO);+ for (k, w) in self.work.iter_mut().take(half).enumerate() {+ w.re = self.input[a][k] as f64;+ w.im = b.map_or(0.0, |b| self.input[b][k] as f64);+ }+ self.plan.run(&mut self.work, false);+ for (w, h) in self.work.iter_mut().zip(self.filter.iter()) {+ *w = *w * *h;+ }+ self.plan.run(&mut self.work, true);+ let (now, next) = self.work.split_at(half);+ for k in 0..half {+ self.output[a][k] = now[k].re as f32 + self.tail[a][k];+ self.tail[a][k] = next[k].re as f32;+ }+ if let Some(b) = b {+ for k in 0..half {+ self.output[b][k] = now[k].im as f32 + self.tail[b][k];+ self.tail[b][k] = next[k].im as f32;+ }+ }+ }+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let half = self.size / 2;+ for v in [&mut self.input, &mut self.output, &mut self.tail] {+ v.resize_with(channels.len(), || vec![0.0; half]);+ }+ let mut i = 0;+ while i < n {+ let m = (half - self.at).min(n - i);+ let span = self.at..self.at + m;+ for (c, ch) in channels.iter_mut().enumerate() {+ let samples = &mut ch[i..i + m];+ self.input[c][span.clone()].copy_from_slice(samples);+ samples.copy_from_slice(&self.output[c][span.clone()]);+ }+ self.at += m;+ i += m;+ if self.at == half {+ self.convolve();+ self.at = 0;+ }+ }+ }++ fn latency(&self) -> usize {+ // Half an FFT gathered, then the filter's own half of its taps.+ self.size / 2 + self.size / 4+ }+}++#[derive(Debug)]+pub(crate) struct ParametricEq {+ fir: Fir,+}++impl ParametricEq {+ pub(crate) fn new(rate: u32) -> ParametricEq {+ ParametricEq {+ fir: Fir::new(rate),+ }+ }+}++/// Parametric EQ's response with values `p` at sampling rate `fs`: its+/// linear gain at `hz` (before the output gain).+fn parametric(p: &impl Fn(usize) -> f32, fs: f64, hz: f64) -> f64 {+ let amount = 10f64.powf(p(pe::AMOUNT) as f64 / 20.0);+ let f = (p(pe::FREQUENCY) as f64).clamp(1.0, 0.47 * fs);+ let r = 2f64.powf(p(pe::WIDTH) as f64);+ let ramp = |x: f64, (x0, g0): (f64, f64), (x1, g1): (f64, f64)| {+ g0 + (g1 - g0) * ((x - x0) / (x1 - x0)).clamp(0.0, 1.0)+ };+ match p(pe::STYLE).round() as i32 {+ // A low shelf: the amount below `f / r`, nothing above `f · r`.+ 0 => ramp(hz, (f / r, amount), (f * r, 1.0)),+ // A high shelf: the other way round.+ 1 => ramp(hz, (f / r, 1.0), (f * r, amount)),+ // The bands: half the width each side of `f`.+ style => {+ let s = r.sqrt();+ let (lo, hi) = (f / s, f * s);+ let (inside, outside) = if style == 2 {+ (1.0, amount)+ } else {+ (amount, 1.0)+ };+ if hz < lo {+ ramp(hz, (lo / EDGE, outside), (lo, inside))+ } else {+ ramp(hz, (hi, inside), (hi * EDGE, outside))+ }+ }+ }+}++impl Own for ParametricEq {+ fn set(&mut self, params: &[f32]) {+ let p = |i: usize| {+ let s = &pe::PARAMS[i];+ params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+ };+ let accuracy = p(pe::ACCURACY).round().clamp(0.0, 2.0) as usize;+ self.fir.resize(pe::FFT[accuracy]);+ let out = 10f64.powf(p(pe::OUTPUT) as f64 / 20.0);+ let fs = self.fir.rate;+ self.fir.design(|hz| parametric(&p, fs, hz) * out);+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ self.fir.process(channels);+ }++ fn latency(&self) -> usize {+ self.fir.latency()+ }+}++/// Express Graphic EQ: each band's gain at its centre, straight lines in+/// dB between them along the octaves, flat past the ends; a band at its+/// lowest (−60 dB) is silence.+#[derive(Debug)]+pub(crate) struct ExpressGraphicEq {+ fir: Fir,+}++impl ExpressGraphicEq {+ pub(crate) fn new(rate: u32) -> ExpressGraphicEq {+ ExpressGraphicEq {+ fir: Fir::new(rate),+ }+ }+}++impl Own for ExpressGraphicEq {+ fn set(&mut self, params: &[f32]) {+ let p = |i: usize| {+ let s = &geq::PARAMS[i];+ params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+ };+ let accuracy = p(geq::ACCURACY).round().clamp(0.0, 2.0) as usize;+ self.fir.resize(pe::FFT[accuracy]);+ let gains: Vec<(f64, f64)> = geq::CENTERS+ .iter()+ .enumerate()+ .map(|(k, hz)| ((*hz as f64).log2(), p(geq::BANDS + k) as f64))+ .collect();+ let out = p(geq::OUTPUT) as f64;+ self.fir.design(|hz| {+ let x = hz.max(1.0).log2();+ let at = gains.partition_point(|g| g.0 <= x);+ let db = if at == 0 {+ gains[0].1+ } else if at == gains.len() {+ gains[gains.len() - 1].1+ } else {+ let ((x0, g0), (x1, g1)) = (gains[at - 1], gains[at]);+ g0 + (g1 - g0) * (x - x0) / (x1 - x0)+ };+ if db <= -60.0 {+ 0.0+ } else {+ 10f64.powf((db + out) / 20.0)+ }+ });+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ self.fir.process(channels);+ }++ fn latency(&self) -> usize {+ self.fir.latency()+ }+}++/// Graphic EQ: the drawn response, straight lines in dB along the octaves+/// (flat past its ends), its bottom (−60 dB) silence, times the output+/// gain.+#[derive(Debug)]+pub(crate) struct GraphicEq {+ fir: Fir,+}++impl GraphicEq {+ pub(crate) fn new(rate: u32) -> GraphicEq {+ GraphicEq {+ fir: Fir::new(rate),+ }+ }+}++impl Own for GraphicEq {+ fn set(&mut self, params: &[f32]) {+ let p = |i: usize| {+ let s = &ge::PARAMS[i];+ params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+ };+ let accuracy = p(ge::ACCURACY).round().clamp(0.0, 2.0) as usize;+ self.fir.resize(pe::FFT[accuracy]);+ let curve: Vec<(f32, f32)> = super::graphs::points(params, ge::PARAMS, ge::GRAPH)+ .into_iter()+ .map(|(hz, db)| (hz.max(1.0).log2(), db))+ .collect();+ let out = p(ge::OUTPUT) as f64;+ self.fir.design(|hz| {+ let db = super::graphs::along(&curve, (hz.max(1.0) as f32).log2()) as f64;+ if db <= -60.0 {+ 0.0+ } else {+ 10f64.powf((db + out) / 20.0)+ }+ });+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ self.fir.process(channels);+ }++ fn latency(&self) -> usize {+ self.fir.latency()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn eq(values: [f32; 6]) -> ParametricEq {+ let mut e = ParametricEq::new(48_000);+ e.set(&values);+ e+ }++ /// The level (dB) a sine at `hz` comes out at, once through.+ fn level(e: &mut ParametricEq, hz: f32) -> f32 {+ let n = 48_000;+ let x: Vec<f32> = (0..n)+ .map(|i| (std::f32::consts::TAU * hz * i as f32 / 48_000.0).sin())+ .collect();+ let mut ch = [x.clone(), x];+ for block in 0..(n / 1000) {+ let mut b: Vec<Vec<f32>> = ch+ .iter()+ .map(|c| c[block * 1000..(block + 1) * 1000].to_vec())+ .collect();+ e.process(&mut b);+ for (c, part) in ch.iter_mut().zip(b) {+ c[block * 1000..(block + 1) * 1000].copy_from_slice(&part);+ }+ }+ // Its amplitude from its power (a sampled sine's peak can miss it).+ let tail = &ch[1][24_000..];+ let power = tail.iter().map(|s| s * s).sum::<f32>() / tail.len() as f32;+ 10.0 * (2.0 * power).log10()+ }++ #[test]+ fn its_latency_is_three_quarters_of_the_fft() {+ let mut e = eq([0.0, 0.0, 3.0, 1000.0, 1.0, 1.0]);+ assert_eq!(e.latency(), 768);+ // A click comes out that late, whole (an amount of 0 dB).+ let mut x = vec![vec![0.0f32; 4096]];+ x[0][0] = 1.0;+ e.process(&mut x);+ let (at, peak) = x[0].iter().enumerate().fold((0, 0f32), |(i, m), (k, s)| {+ if s.abs() > m { (k, s.abs()) } else { (i, m) }+ });+ assert_eq!(at, 768);+ assert!((peak - 1.0).abs() < 0.01, "{peak}");+ }++ #[test]+ fn a_notch_cuts_its_band_and_leaves_the_rest() {+ // "Remove frequencies around 1500 Hz by 25 dB".+ let mut e = eq([0.0, -25.0, 3.0, 1500.0, 1.0, 2.0]);+ assert!(+ (level(&mut e, 1500.0) + 25.0).abs() < 1.0,+ "{}",+ level(&mut e, 1500.0)+ );+ assert!(level(&mut e, 200.0).abs() < 0.5);+ assert!(level(&mut e, 8000.0).abs() < 0.5);+ }++ #[test]+ fn a_band_pass_keeps_its_band() {+ // "Phone line effect": 400 to 1600 Hz kept, the rest 25 dB down.+ let mut e = eq([0.0, -25.0, 2.0, 800.0, 2.0, 1.0]);+ assert!(level(&mut e, 800.0).abs() < 0.5);+ assert!((level(&mut e, 5000.0) + 25.0).abs() < 1.5);+ assert!(+ (level(&mut e, 100.0) + 25.0).abs() < 3.0,+ "{}",+ level(&mut e, 100.0)+ );+ }++ #[test]+ fn shelves_and_output_gain() {+ // "Hiss removal": above 6 kHz · √2 down 40 dB, the lows alone.+ let mut e = eq([0.0, -40.0, 1.0, 6000.0, 0.5, 2.0]);+ assert!((level(&mut e, 12_000.0) + 40.0).abs() < 2.0);+ assert!(level(&mut e, 1000.0).abs() < 0.5);+ // A low shelf, and −6 dB of output on everything.+ let mut e = eq([-6.0, -15.0, 0.0, 400.0, 0.5, 2.0]);+ assert!(+ (level(&mut e, 100.0) + 21.0).abs() < 1.0,+ "{}",+ level(&mut e, 100.0)+ );+ assert!((level(&mut e, 5000.0) + 6.0).abs() < 0.5);+ }+}diff --git a/crates/mixer/src/fx/graphs.rs b/crates/mixer/src/fx/graphs.rsnew file mode 100644index 0000000..ce1e5e4--- /dev/null+++ b/crates/mixer/src/fx/graphs.rs@@ -0,0 +1,507 @@+//! The effects drawn on a graph, as VEGAS's: Amplitude Modulation (a+//! wave), Distortion (a level curve a half of the wave), Graphic Dynamics+//! (a level curve, a block of 20 ms at a time) — Graphic EQ's response is+//! `fir`'s.++use bv_timeline::Tempo;+use bv_timeline::audio_fx::{+ amplitude_modulation as am, distortion as ds, graphic_dynamics as gd, tempo,+};++use super::{Own, db_gain};++/// Added and taken away again on fed-back state, so a fading signal ends+/// at 0 instead of lingering as a denormal number.+const FLUSH: f32 = 1e-18;++/// A graph's points from an effect's values: the count at `at`, then+/// `(x, y)` pairs, sorted by x.+pub(crate) fn points(+ params: &[f32],+ specs: &[bv_timeline::ParamSpec],+ at: usize,+) -> Vec<(f32, f32)> {+ let value = |i: usize| params.get(i).copied().unwrap_or(specs[i].default);+ let count = value(at).round().clamp(0.0, specs[at].max) as usize;+ let mut p: Vec<(f32, f32)> = (0..count)+ .map(|k| (value(at + 1 + 2 * k), value(at + 2 + 2 * k)))+ .collect();+ p.sort_by(|a, b| a.0.total_cmp(&b.0));+ p+}++/// The straight-line curve through `points` at `x` (flat past its ends).+pub(crate) fn along(points: &[(f32, f32)], x: f32) -> f32 {+ let Some(first) = points.first() else {+ return 0.0;+ };+ let k = points.partition_point(|p| p.0 <= x);+ if k == 0 {+ return first.1;+ }+ if k == points.len() {+ return points[k - 1].1;+ }+ let ((x0, y0), (x1, y1)) = (points[k - 1], points[k]);+ if x1 <= x0 {+ y1+ } else {+ y0 + (y1 - y0) * (x - x0) / (x1 - x0)+ }+}++/// A level curve (input dB to output dB, −84 the bottom) as linear gains+/// every 0.1 dB from −84 to 0: the output less the input; a stretch whose+/// output is −84 dB at both ends is silence.+pub(crate) fn level_gains(points: &[(f32, f32)]) -> Vec<f32> {+ (0..=840)+ .map(|k| {+ let l = -84.0 + k as f32 / 10.0;+ let j = points.partition_point(|p| p.0 <= l);+ let silent =+ j > 0 && j < points.len() && points[j - 1].1 <= -84.0 && points[j].1 <= -84.0;+ if silent || (points.len() == 1 && points[0].1 <= -84.0) {+ 0.0+ } else {+ 10f32.powf((along(points, l) - l) / 20.0)+ }+ })+ .collect()+}++/// The gain of `gains` (from [`level_gains`]) at sample value `x`.+fn level_gain(gains: &[f32], x: f32) -> f32 {+ let a = x.abs();+ let l = if a < 1.0 / 32768.0 {+ -84.0+ } else {+ (20.0 * a.log10()).clamp(-84.0, 0.0)+ };+ let at = (l + 84.0) * 10.0;+ let k = (at as usize).min(839);+ let part = at - k as f32;+ gains[k] + (gains[k + 1] - gains[k]) * part+}++#[derive(Debug)]+pub(crate) struct AmplitudeModulation {+ rate: f64,+ params: Vec<f32>,+ tempo: Tempo,+ /// The wave's gains over a round, 1001 steps.+ gains: Vec<f32>,+ /// Where in the round it is, 0–1000.+ phase: f64,+ lows: Vec<f32>,+}++impl AmplitudeModulation {+ pub(crate) fn new(rate: u32) -> AmplitudeModulation {+ AmplitudeModulation {+ rate: rate.max(1) as f64,+ params: Vec::new(),+ tempo: Tempo::default(),+ gains: vec![1.0; 1001],+ phase: 0.0,+ lows: Vec::new(),+ }+ }++ fn p(&self, i: usize) -> f32 {+ let s = &am::PARAMS[i];+ self.params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+ }+}++impl Own for AmplitudeModulation {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ let mut wave = points(params, am::PARAMS, am::GRAPH);+ if self.p(am::BLEND) >= 0.5 && wave.len() >= 2 {+ // The seam smoothed: both ends at their average, the curve kept+ // from 5 % into the round and from 5 % before its end.+ let ends = (wave[0].1 + wave[wave.len() - 1].1) / 2.0;+ let (near, far) = (along(&wave, 50.0), along(&wave, 950.0));+ let mut blended = vec![(0.0, ends), (50.0, near)];+ blended.extend(wave.iter().copied().filter(|p| p.0 > 50.0 && p.0 < 950.0));+ blended.extend([(950.0, far), (1000.0, ends)]);+ wave = blended;+ }+ let depth = self.p(am::AMPLITUDE).abs();+ for (t, g) in self.gains.iter_mut().enumerate() {+ let v = along(&wave, t as f32).clamp(-100.0, 0.0);+ // 0 at the top is 0 dB, −100 at the bottom the amplitude.+ *g = 10f32.powf(v / 100.0 * depth / 20.0);+ }+ }++ fn keep_time(&mut self, tempo: &Tempo) {+ self.tempo = *tempo;+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let fs = self.rate;+ let samples = if self.p(am::SYNC) >= 0.5 {+ tempo::seconds(self.p(am::PERIOD), &self.tempo) * self.p(am::MULTIPLIER) as f64 * fs+ } else {+ (fs / self.p(am::FREQUENCY) as f64).trunc()+ };+ let step = 1000.0 / samples.max(1.0);+ let dry = db_gain(self.p(am::DRY), -80.0);+ let wet = db_gain(self.p(am::WET), -80.0);+ let p = if self.p(am::LOW_PASS) >= 0.5 {+ (-std::f32::consts::TAU * self.p(am::LOW_FREQ) / fs as f32).exp()+ } else {+ 0.0+ };+ // The right channel behind by the stereo pan (half a round at 100 %).+ let behind = 5.0 * self.p(am::PAN) as f64 * 100.0;+ self.lows.resize(channels.len(), 0.0);+ let stereo = channels.len() == 2;+ for (c, (ch, low)) in channels.iter_mut().zip(self.lows.iter_mut()).enumerate() {+ let mut phase = self.phase + if stereo && c == 1 { behind } else { 0.0 };+ for x in ch.iter_mut() {+ let g = self.gains[(phase.rem_euclid(1000.0) as usize).min(1000)];+ let mut w = (1.0 - p) * wet * g * *x + p * *low;+ if w.abs() < 2e-11 {+ w = 0.0;+ }+ *low = w;+ *x = w + dry * *x;+ phase += step;+ }+ }+ self.phase = (self.phase + step * n as f64).rem_euclid(1000.0);+ }+}++#[derive(Debug)]+pub(crate) struct Distortion {+ rate: f32,+ /// The positive and negative halves' gains (see [`level_gains`]).+ gains: [Vec<f32>; 2],+ slew: Option<f32>,+ low_pass: f32,+ dry: f32,+ wet: f32,+ /// The slew limiter's last two outputs, one pair for all channels:+ /// the channels' samples go through it in turn, so in stereo the two+ /// sides pull on each other.+ last: [f32; 2],+ lows: Vec<f32>,+}++impl Distortion {+ pub(crate) fn new(rate: u32) -> Distortion {+ Distortion {+ rate: rate.max(1) as f32,+ gains: [vec![1.0; 841], vec![1.0; 841]],+ slew: None,+ low_pass: 0.0,+ dry: 0.0,+ wet: 1.0,+ last: [0.0; 2],+ lows: Vec::new(),+ }+ }+}++impl Own for Distortion {+ fn set(&mut self, params: &[f32]) {+ let p = |i: usize| {+ let s = &ds::PARAMS[i];+ params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+ };+ self.gains = [+ level_gains(&points(params, ds::PARAMS, ds::POSITIVE)),+ level_gains(&points(params, ds::PARAMS, ds::NEGATIVE)),+ ];+ self.slew = (p(ds::SLEW) >= 0.5).then(|| 0.0005 * p(ds::SLEW_RATE));+ let fc = p(ds::LOW_FREQ);+ self.low_pass = if p(ds::LOW_PASS) >= 0.5 && fc <= self.rate / 2.0 {+ (-std::f32::consts::TAU * fc / self.rate).exp()+ } else {+ 0.0+ };+ self.dry = db_gain(p(ds::DRY), -60.0);+ self.wet = db_gain(p(ds::WET), -60.0);+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ self.lows.resize(channels.len(), 0.0);+ let p = self.low_pass;+ let [mut s1, mut s2] = self.last;+ for i in 0..n {+ for (ch, low) in channels.iter_mut().zip(self.lows.iter_mut()) {+ let x = ch[i];+ let half = if x >= 0.0 { 0 } else { 1 };+ let shaped = x * level_gain(&self.gains[half], x);+ let s = match self.slew {+ Some(rho) => {+ // The change of slope held within ±rho.+ let d = s1 - s2;+ let s = s1 + (shaped - s1).clamp(d - rho, d + rho);+ s2 = s1;+ s1 = s;+ s+ }+ None => shaped,+ };+ *low = (p * *low + (1.0 - p) * s + FLUSH) - FLUSH;+ ch[i] = self.wet * *low + self.dry * x;+ }+ }+ self.last = [s1, s2];+ }+}++/// Graphic Dynamics: a block of 20 ms gathered (one block late), its peak+/// (every channel by the loudest with sync) read on the level curve, the+/// gain moving toward it nine tenths of the way in the attack (going+/// down) or release (going up) time, then laid on the block in a straight+/// line over that time (at most the block).+#[derive(Debug)]+pub(crate) struct GraphicDynamics {+ rate: f32,+ block: usize,+ gains: Vec<f32>,+ attack: (f32, usize),+ release: (f32, usize),+ output: f32,+ sync: bool,+ /// Each channel's smoothed gain and the gain last laid on its sound.+ gain: Vec<f32>,+ applied: Vec<f32>,+ /// Each channel's block being gathered, and the one going out.+ gathering: Vec<Vec<f32>>,+ going: Vec<Vec<f32>>,+ at: usize,+}++impl GraphicDynamics {+ pub(crate) fn new(rate: u32) -> GraphicDynamics {+ let fs = rate.max(1) as f32;+ GraphicDynamics {+ rate: fs,+ block: ((0.02 * fs) as usize).max(1),+ gains: vec![1.0; 841],+ attack: (1.0, 0),+ release: (1.0, 0),+ output: 1.0,+ sync: true,+ gain: Vec::new(),+ applied: Vec::new(),+ gathering: Vec::new(),+ going: Vec::new(),+ at: 0,+ }+ }++ /// A time's share of the way a block (all of it up to a block) and its+ /// length in samples (at most a block).+ fn timing(&self, ms: f32) -> (f32, usize) {+ let t = ms / 1000.0;+ let share = if t <= 0.02 {+ 1.0+ } else {+ 1.0 - 0.1f32.powf(0.02 / t)+ };+ (share, ((t * self.rate) as usize).min(self.block))+ }++ /// The gathered block's gains worked out and laid on it.+ fn finish_block(&mut self) {+ let peaks: Vec<f32> = self+ .gathering+ .iter()+ .map(|b| b.iter().fold(0f32, |m, s| m.max(s.abs())))+ .collect();+ let loudest = peaks.iter().fold(0f32, |m, p| m.max(*p));+ for (c, own) in peaks.iter().enumerate() {+ let peak = if self.sync { loudest } else { *own };+ let target = level_gain(&self.gains, peak);+ let g = &mut self.gain[c];+ let (share, ramp) = if target < *g {+ self.attack+ } else {+ self.release+ };+ *g = (share * target + (1.0 - share) * *g).min(50.0);+ let mut out = (*g * self.output).min(5000.0);+ if out < 0.0002 {+ out = 0.0;+ }+ let from = self.applied[c];+ for (k, s) in self.gathering[c].iter_mut().enumerate() {+ let t = if ramp == 0 || k >= ramp {+ 1.0+ } else {+ k as f32 / ramp as f32+ };+ *s *= from + (out - from) * t;+ }+ self.applied[c] = out;+ }+ std::mem::swap(&mut self.gathering, &mut self.going);+ }+}++impl Own for GraphicDynamics {+ fn set(&mut self, params: &[f32]) {+ let p = |i: usize| {+ let s = &gd::PARAMS[i];+ params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+ };+ self.gains = level_gains(&points(params, gd::PARAMS, gd::GRAPH));+ self.attack = self.timing(p(gd::ATTACK));+ self.release = self.timing(p(gd::RELEASE));+ let auto = if p(gd::AUTO_GAIN) >= 0.5 { 0.98 } else { 1.0 };+ self.output = 10f32.powf(p(gd::OUTPUT) / 20.0) * auto;+ self.sync = p(gd::SYNC) >= 0.5;+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let count = channels.len();+ let block = self.block;+ if self.gathering.len() != count {+ self.gathering = vec![vec![0.0; block]; count];+ self.going = vec![vec![0.0; block]; count];+ self.gain = vec![1.0; count];+ self.applied = vec![1.0; count];+ self.at = 0;+ }+ let mut i = 0;+ while i < n {+ let m = (block - self.at).min(n - i);+ for (c, ch) in channels.iter_mut().enumerate() {+ let span = self.at..self.at + m;+ self.gathering[c][span.clone()].copy_from_slice(&ch[i..i + m]);+ ch[i..i + m].copy_from_slice(&self.going[c][span]);+ }+ self.at += m;+ i += m;+ if self.at == block {+ self.finish_block();+ self.at = 0;+ }+ }+ }++ fn latency(&self) -> usize {+ self.block+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn with(specs: &[bv_timeline::ParamSpec], values: &[(usize, f32)]) -> Vec<f32> {+ let mut p: Vec<f32> = specs.iter().map(|s| s.default).collect();+ for &(i, v) in values {+ p[i] = v;+ }+ p+ }++ /// A graph's values: its count and points from `at`.+ fn curve(at: usize, pts: &[(f32, f32)]) -> Vec<(usize, f32)> {+ let mut v = vec![(at, pts.len() as f32)];+ for (k, (x, y)) in pts.iter().enumerate() {+ v.push((at + 1 + 2 * k, *x));+ v.push((at + 2 + 2 * k, *y));+ }+ v+ }++ #[test]+ fn level_curves_give_gains_and_silence() {+ // 2:1 above −18 dB: at 0 dB in, −9 dB out.+ let g = level_gains(&[(-84.0, -84.0), (-18.0, -18.0), (0.0, -9.0)]);+ assert!((level_gain(&g, 1.0) - 10f32.powf(-9.0 / 20.0)).abs() < 1e-4);+ assert!((level_gain(&g, 0.01) - 1.0).abs() < 1e-4);+ // A gate: −84 dB out below −50 dB in.+ let g = level_gains(&[(-84.0, -84.0), (-50.0, -84.0), (-49.9, -49.9), (0.0, 0.0)]);+ assert_eq!(level_gain(&g, 0.001), 0.0);+ assert!((level_gain(&g, 0.5) - 1.0).abs() < 1e-4);+ }++ #[test]+ fn amplitude_modulation_follows_its_wave_down_to_the_amplitude() {+ // A square wave: 0 dB the first half, the amplitude (−48 dB) after.+ let mut values = curve(+ am::GRAPH,+ &[(0.0, 0.0), (500.0, 0.0), (501.0, -100.0), (1000.0, -100.0)],+ );+ values.extend([(am::DRY, -80.0), (am::WET, 0.0), (am::FREQUENCY, 1.0)]);+ let mut m = AmplitudeModulation::new(48_000);+ m.set(&with(am::PARAMS, &values));+ let mut x = vec![vec![1.0f32; 48_000]];+ m.process(&mut x);+ assert!((x[0][10_000] - 1.0).abs() < 1e-4);+ assert!(+ (x[0][40_000] - 10f32.powf(-48.0 / 20.0)).abs() < 1e-4,+ "{}",+ x[0][40_000]+ );+ // Its default: a flat wave at −50, a steady −24 dB.+ let mut m = AmplitudeModulation::new(48_000);+ m.set(&with(am::PARAMS, &[]));+ let mut x = vec![vec![1.0f32; 4_800]];+ m.process(&mut x);+ assert!((x[0][2_000] - 10f32.powf(-24.0 / 20.0)).abs() < 1e-4);+ }++ #[test]+ fn distortion_shapes_each_half_on_its_curve() {+ // The positive half 2:1 above −18 dB, the negative left straight.+ let mut values = curve(ds::POSITIVE, &[(-84.0, -84.0), (-18.0, -18.0), (0.0, -9.0)]);+ values.extend([(ds::DRY, -60.0), (ds::WET, 0.0)]);+ let mut d = Distortion::new(48_000);+ d.set(&with(ds::PARAMS, &values));+ let mut x = vec![vec![1.0f32, -1.0, 0.05]];+ d.process(&mut x);+ assert!(+ (x[0][0] - 10f32.powf(-9.0 / 20.0)).abs() < 1e-4,+ "{}",+ x[0][0]+ );+ assert!((x[0][1] + 1.0).abs() < 1e-4);+ assert!((x[0][2] - 0.05).abs() < 1e-4);+ }++ #[test]+ fn graphic_dynamics_limits_a_block_late() {+ // A limiter at −12 dB, instant.+ let mut values = curve(gd::GRAPH, &[(-84.0, -84.0), (-12.0, -12.0), (0.0, -12.0)]);+ values.extend([(gd::ATTACK, 0.0), (gd::RELEASE, 0.0)]);+ let mut g = GraphicDynamics::new(48_000);+ g.set(&with(gd::PARAMS, &values));+ assert_eq!(g.latency(), 960);+ let mut x = vec![vec![1.0f32; 9_600]];+ g.process(&mut x);+ // The first block out is the silence before the sound; then −12 dB.+ assert!(x[0][..960].iter().all(|s| *s == 0.0));+ let want = 10f32.powf(-12.0 / 20.0);+ assert!(+ x[0][2_000..].iter().all(|s| (s - want).abs() < 1e-3),+ "{}",+ x[0][2_000]+ );+ }+}diff --git a/crates/mixer/src/fx/hammer.rs b/crates/mixer/src/fx/hammer.rsnew file mode 100644index 0000000..b2fd777--- /dev/null+++ b/crates/mixer/src/fx/hammer.rs@@ -0,0 +1,276 @@+//! Wave Hammer Surround, as VEGAS's: a compressor and a volume maximizer+//! in a row, each steered by the channels chosen for its control signal+//! and working on the channels chosen to be affected.+//!+//! The compressor reads the level by its peak or its power (RMS), moving+//! by the attack and release (smart release lets it come back sooner+//! after a short burst), a little ahead of the sound (longer with the+//! longer look-ahead); above the threshold it brings the level down by+//! the ratio (50:1 a limiter), its corner rounded over 6 dB. Auto gain+//! compensation gives back 70 % of what it takes at full scale; smooth+//! saturation rounds off what still goes past full scale. The maximizer+//! holds the peaks (seen ahead) at its threshold and brings the result up+//! to its output level.++use bv_timeline::audio_fx::wave_hammer as wh;++use super::Own;++/// BananaV's 5.1 order (L R C LFE Ls Rs) to the switches' (L R C Ls Rs+/// LFE).+const SWITCH: [usize; 6] = [0, 1, 2, 5, 3, 4];++#[derive(Debug)]+pub(crate) struct WaveHammer {+ rate: f32,+ params: Vec<f32>,+ /// The sound held back for the look-ahead, a line a channel.+ lines: Vec<Vec<f32>>,+ at: usize,+ level: f32,+ /// How long the level has been rising (samples), for smart release.+ rising: usize,+ max_gain: f32,+}++impl WaveHammer {+ pub(crate) fn new(rate: u32) -> WaveHammer {+ WaveHammer {+ rate: rate.max(1) as f32,+ params: Vec::new(),+ lines: Vec::new(),+ at: 0,+ level: 0.0,+ rising: 0,+ max_gain: 1.0,+ }+ }++ fn p(&self, i: usize) -> f32 {+ let s = &wh::PARAMS[i];+ self.params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+ }++ fn keep(&self, ms: f32) -> f32 {+ let n = self.rate * ms / 1000.0;+ if n < 1.0 { 0.0 } else { 0.1f32.powf(1.0 / n) }+ }++ /// How far ahead it reads, in samples: the compressor's and the+ /// maximizer's look-ahead, the longer of the two.+ fn ahead(&self) -> usize {+ let ms = |longer: bool| if longer { 5.0f32 } else { 1.5 };+ let comp = if self.p(wh::BYPASS) < 0.5 {+ ms(self.p(wh::LOOK_AHEAD) >= 0.5)+ } else {+ 0.0+ };+ let max = if self.p(wh::MAX_BYPASS) < 0.5 {+ ms(self.p(wh::MAX_LOOK_AHEAD) >= 0.5)+ } else {+ 0.0+ };+ (comp.max(max) * self.rate / 1000.0).round() as usize+ }+}++/// The compressor's gain at level `e` over threshold `t` (both linear),+/// `slope` = 1/ratio − 1, the corner rounded over ±3 dB.+fn squeeze(e: f32, t: f32, slope: f32) -> f32 {+ let over = 20.0 * (e.max(1e-9) / t).log10();+ let cut = if over <= -3.0 {+ 0.0+ } else if over < 3.0 {+ slope * (over + 3.0).powi(2) / 12.0+ } else {+ slope * over+ };+ 10f32.powf(cut / 20.0)+}++impl Own for WaveHammer {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let count = channels.len();+ let ahead = self.ahead();+ let room = ahead + 1;+ if self.lines.len() != count || self.lines.first().map_or(0, Vec::len) != room {+ self.lines = vec![vec![0.0; room]; count];+ self.at = 0;+ }+ let switch = |c: usize, at: usize| {+ let k = if count == 6 { SWITCH[c] } else { c.min(5) };+ self.p(at + k) >= 0.5+ };+ let control: Vec<bool> = (0..count).map(|c| switch(c, wh::CONTROL)).collect();+ let affect: Vec<bool> = (0..count).map(|c| switch(c, wh::AFFECT)).collect();+ let compress = self.p(wh::BYPASS) < 0.5;+ let maximize = self.p(wh::MAX_BYPASS) < 0.5;+ let rms = self.p(wh::RMS) >= 0.5;+ let t = 10f32.powf(self.p(wh::THRESHOLD) / 20.0);+ let ratio = self.p(wh::RATIO);+ let slope = if ratio >= 50.0 {+ -1.0+ } else {+ 1.0 / ratio - 1.0+ };+ let mut out = 10f32.powf(self.p(wh::OUTPUT) / 20.0);+ if self.p(wh::AUTO_GAIN) >= 0.5 {+ out /= t.powf(-slope).powf(0.7);+ }+ let smooth = self.p(wh::SMOOTH) >= 0.5;+ let attack = self.keep(self.p(wh::ATTACK));+ let release = self.keep(self.p(wh::RELEASE));+ let smart = self.keep(self.p(wh::RELEASE) * (1.0 - 0.75 * self.p(wh::SMART) / 100.0));+ let ceiling = 10f32.powf(self.p(wh::MAX_THRESHOLD) / 20.0);+ let lift = 10f32.powf(self.p(wh::MAX_OUTPUT) / 20.0) / ceiling;+ let max_release = self.keep(self.p(wh::MAX_RELEASE));+ let mut e = self.level;+ let mut rising = self.rising;+ let mut mg = self.max_gain;+ for i in 0..n {+ // What comes in now is what the detectors see ahead.+ let mut peak = 0f32;+ let mut power = 0f32;+ let mut seen = 0usize;+ for (c, ch) in channels.iter().enumerate() {+ if control[c] {+ peak = peak.max(ch[i].abs());+ power += ch[i] * ch[i];+ seen += 1;+ }+ }+ let now = if rms {+ (power / seen.max(1) as f32).sqrt()+ } else {+ peak+ };+ let keep = if now > e {+ rising += 1;+ attack+ } else if rising > 0 && rising < (0.05 * self.rate) as usize {+ // A short burst: let go sooner.+ rising = 0;+ smart+ } else {+ rising = 0;+ release+ };+ e = now + (e - now) * keep;+ let comp = if compress {+ squeeze(e, t, slope) * out+ } else {+ 1.0+ };+ let max_target = if maximize && peak * comp > ceiling {+ ceiling / (peak * comp)+ } else {+ 1.0+ };+ mg = if max_target < mg {+ max_target+ } else {+ max_target + (mg - max_target) * max_release+ };+ let gain = comp * if maximize { mg * lift } else { 1.0 };+ let at = self.at;+ for (c, ch) in channels.iter_mut().enumerate() {+ let line = &mut self.lines[c];+ line[at] = ch[i];+ // Written `ahead` samples ago (now, with no look-ahead).+ let late = line[(at + 1) % room];+ let mut y = if affect[c] { late * gain } else { late };+ if smooth && compress && y.abs() > 0.9 {+ // Past −0.9 dB, rounded off toward full scale.+ let s = y.signum();+ y = s * (0.9 + 0.1 * ((y.abs() - 0.9) / 0.1).tanh());+ }+ ch[i] = y;+ }+ self.at = (at + 1) % room;+ }+ self.level = e;+ self.rising = rising;+ self.max_gain = mg;+ }++ fn latency(&self) -> usize {+ self.ahead()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn hammer(values: &[(usize, f32)]) -> WaveHammer {+ let mut h = WaveHammer::new(48_000);+ let mut p: Vec<f32> = wh::PARAMS.iter().map(|s| s.default).collect();+ for &(i, v) in values {+ p[i] = v;+ }+ h.set(&p);+ h+ }++ fn tone(level: f32, n: usize) -> Vec<f32> {+ (0..n)+ .map(|i| level * (std::f32::consts::TAU * 440.0 * i as f32 / 48_000.0).sin())+ .collect()+ }++ fn settled(h: &mut WaveHammer, level: f32) -> f32 {+ let mut ch = vec![tone(level, 48_000), tone(level, 48_000)];+ h.process(&mut ch);+ ch[0][40_000..].iter().fold(0f32, |m, s| m.max(s.abs()))+ }++ #[test]+ fn the_compressor_brings_loud_sound_down() {+ // 4:1 from −12 dB, peak scan, no saturation: −2 dB in, −9.5 out.+ let mut h = hammer(&[(wh::RMS, 0.0), (wh::SMOOTH, 0.0), (wh::MAX_BYPASS, 1.0)]);+ let out = 20.0 * settled(&mut h, 10f32.powf(-2.0 / 20.0)).log10();+ assert!((out + 9.5).abs() < 0.5, "{out}");+ }++ #[test]+ fn the_maximizer_holds_peaks_and_lifts_to_its_level() {+ // Only the maximizer: peaks held at −6 dB, then lifted to −1 dB.+ let mut h = hammer(&[+ (wh::BYPASS, 1.0),+ (wh::MAX_THRESHOLD, -6.0),+ (wh::MAX_OUTPUT, -1.0),+ ]);+ let out = 20.0 * settled(&mut h, 1.0).log10();+ assert!((out + 1.0).abs() < 0.3, "{out}");+ assert_eq!(h.latency(), 72);+ }++ #[test]+ fn channels_left_out_are_untouched() {+ let mut h = hammer(&[+ (wh::RMS, 0.0),+ (wh::SMOOTH, 0.0),+ (wh::MAX_BYPASS, 1.0),+ (wh::AFFECT + 1, 0.0),+ ]);+ let mut ch = vec![tone(0.9, 4_800), tone(0.9, 4_800)];+ h.process(&mut ch);+ let lat = h.latency();+ let right = tone(0.9, 4_800);+ assert!(+ ch[1][lat..]+ .iter()+ .zip(&right)+ .all(|(a, b)| (a - b).abs() < 1e-6)+ );+ }+}diff --git a/crates/mixer/src/fx/mod.rs b/crates/mixer/src/fx/mod.rsnew file mode 100644index 0000000..b2a5198--- /dev/null+++ b/crates/mixer/src/fx/mod.rs@@ -0,0 +1,201 @@+//! BananaV's audio effects that follow VEGAS's (their parameters and+//! presets are `bv_timeline::audio_fx`'s): each one a state that takes its+//! values while it plays and processes blocks in place.+//!+//! Every block's loops run over plain slices with no branch inside, so+//! that the compiler turns them into vector instructions (SSE2 or AVX on+//! x86-64, NEON on ARM): the effects' "acceleration". Values that change+//! between blocks (FX automation, a slider dragged) ramp over the next+//! block instead of jumping, so they never click.++use bv_timeline::{Effect, EffectKind, Tempo, audio_fx};++use express::Mixed;++mod delays;+mod dither;+mod dynamics;+mod eq;+mod express;+mod filters;+mod fir;+mod graphs;+mod hammer;+mod modulation;+pub(crate) mod offline;+mod restoration;+mod reverb;+mod studio;+mod studio2;+mod utility;++/// An audio effect's state, ready to process.+pub(crate) trait Own: Send + std::fmt::Debug {+ /// Takes new values while it plays, keeping what it holds (filters'+ /// memory, delay lines…).+ fn set(&mut self, params: &[f32]);+ /// Processes one block in place: a buffer a channel, all as long.+ fn process(&mut self, channels: &mut [Vec<f32>]);+ /// How many samples late its output comes.+ fn latency(&self) -> usize {+ 0+ }+ /// The project's tempo, for those that keep time with it.+ fn keep_time(&mut self, _tempo: &Tempo) {}+}++/// The state of `e` when it is one of these effects.+pub(crate) fn make(e: &Effect, rate: u32, channels: usize) -> Option<Box<dyn Own>> {+ let mut own: Box<dyn Own> = match e.kind {+ EffectKind::ModernEq => Box::new(crate::modern_eq::Eq::new(rate, channels)),+ EffectKind::Volume => Box::new(utility::Volume::default()),+ EffectKind::Pan => Box::new(utility::Pan::default()),+ EffectKind::SmoothEnhance => Box::new(filters::SmoothEnhance::default()),+ EffectKind::NoiseGateFx | EffectKind::TrackNoiseGate => Box::new(dynamics::Gate::new(rate)),+ EffectKind::SimpleDelay => Box::new(delays::SimpleDelay::new(rate)),+ EffectKind::Dither => Box::new(dither::Dither::default()),+ EffectKind::ResonantFilter => Box::new(filters::ResonantFilter::new(rate)),+ EffectKind::ParametricEq => Box::new(fir::ParametricEq::new(rate)),+ EffectKind::Chorus => Box::new(modulation::Chorus::new(rate)),+ EffectKind::FlangeWahWah => Box::new(modulation::FlangeWahWah::new(rate)),+ EffectKind::ReverbFx => Box::new(reverb::ReverbFx::new(rate)),+ EffectKind::TrackCompressor => Box::new(dynamics::TrackCompressor::new(rate)),+ EffectKind::TrackEq => Box::new(eq::TrackEq::new(rate)),+ EffectKind::ParagraphicEq => Box::new(eq::ParagraphicEq::new(rate)),+ EffectKind::MultiTapDelay => Box::new(delays::MultiTapDelay::new(rate)),+ EffectKind::MultiBandDynamics => Box::new(dynamics::MultiBand::new(rate)),+ EffectKind::ExpressDelay => Box::new(Mixed::new(+ express::ExpressDelay::new(rate),+ express::same,+ audio_fx::express_delay::MIX,+ )),+ EffectKind::ExpressDistortion => Box::new(Mixed::new(+ express::ExpressDistortion::default(),+ express::same,+ audio_fx::express_distortion::MIX,+ )),+ EffectKind::ExpressEqualization => Box::new(Mixed::new(+ express::ExpressEq::new(rate),+ express::same,+ audio_fx::express_equalization::MIX,+ )),+ EffectKind::ExpressNoiseGate => Box::new(dynamics::Gate::new(rate)),+ EffectKind::ExpressChorus => Box::new(Mixed::new(+ modulation::Chorus::new(rate),+ express::chorus_values,+ audio_fx::express_chorus::MIX,+ )),+ EffectKind::ExpressFlangeWahWah => Box::new(Mixed::new(+ modulation::FlangeWahWah::express(rate),+ express::flange_values,+ audio_fx::express_flange_wah_wah::MIX,+ )),+ EffectKind::ExpressDynamics => Box::new(express::Mapped::new(+ dynamics::TrackCompressor::new(rate),+ express::dynamics_values,+ )),+ EffectKind::ExpressStutter => Box::new(Mixed::new(+ express::ExpressStutter::new(rate),+ express::same,+ audio_fx::express_stutter::MIX,+ )),+ EffectKind::ExpressAmplitudeModulation => Box::new(Mixed::new(+ express::ExpressAm::new(rate),+ express::same,+ audio_fx::express_amplitude_modulation::MIX,+ )),+ EffectKind::ExpressGraphicEq => Box::new(fir::ExpressGraphicEq::new(rate)),+ EffectKind::AmplitudeModulation => Box::new(graphs::AmplitudeModulation::new(rate)),+ EffectKind::GraphicDynamics => Box::new(graphs::GraphicDynamics::new(rate)),+ EffectKind::Distortion => Box::new(graphs::Distortion::new(rate)),+ EffectKind::GraphicEq => Box::new(fir::GraphicEq::new(rate)),+ EffectKind::WaveHammer => Box::new(hammer::WaveHammer::new(rate)),+ EffectKind::StudioGate => Box::new(studio::Gate::new(rate)),+ EffectKind::DeEsser => Box::new(studio::DeEsser::new(rate)),+ EffectKind::StudioLimiter => Box::new(studio::Limiter::new(rate)),+ EffectKind::TremoloPan => Box::new(studio::TremoloPan::new(rate)),+ EffectKind::TubeStage => Box::new(studio::TubeStage::new(rate)),+ EffectKind::VocalStrip => Box::new(studio::VocalStrip::new(rate)),+ EffectKind::StudioCompressor => Box::new(studio2::Compressor::new(rate)),+ EffectKind::Phaser => Box::new(studio2::Phaser::new(rate)),+ EffectKind::ChorusFlanger => Box::new(studio2::ChorusFlanger::new(rate)),+ EffectKind::StudioReverb => Box::new(studio2::StudioReverb::new(rate)),+ EffectKind::StereoDelay => Box::new(studio2::StereoDelay::new(rate)),+ EffectKind::ExpressReverb => Box::new(Mixed::new(+ reverb::ReverbFx::new(rate),+ express::reverb_values,+ audio_fx::express_reverb::MIX,+ )),+ EffectKind::ExpressAudioRestoration => Box::new(restoration::Restoration::new(rate)),+ _ => return None,+ };+ own.set(¶ms_of(e));+ Some(own)+}++/// Every parameter of `e`, defaults for those it lacks.+pub(crate) fn params_of(e: &Effect) -> Vec<f32> {+ (0..e.kind.params().len()).map(|i| e.param(i)).collect()+}++/// A level in dB as a linear gain, `floor` and below silence.+pub(crate) fn db_gain(db: f32, floor: f32) -> f32 {+ if db <= floor {+ 0.0+ } else {+ 10f32.powf(db / 20.0)+ }+}++/// A value that moves to its new target over the next block: its value+/// at each sample of a block `n` long goes from where it was to `to`.+#[derive(Clone, Copy, Debug)]+pub(crate) struct Ramp {+ now: f32,+ to: f32,+ fresh: bool,+}++impl Ramp {+ pub(crate) fn new(v: f32) -> Ramp {+ Ramp {+ now: v,+ to: v,+ fresh: true,+ }+ }++ /// The value it goes to; the first one it starts at.+ pub(crate) fn set(&mut self, v: f32) {+ self.to = v;+ if self.fresh {+ self.now = v;+ self.fresh = false;+ }+ }++ /// Its start and step for a block `n` long, then at its target.+ pub(crate) fn block(&mut self, n: usize) -> (f32, f32) {+ let start = self.now;+ let step = if n > 0 {+ (self.to - start) / n as f32+ } else {+ 0.0+ };+ self.now = self.to;+ (start, step)+ }+}++/// `buf` times a gain going from `start` by `step` a sample.+pub(crate) fn gain_ramp(buf: &mut [f32], start: f32, step: f32) {+ if step == 0.0 {+ for s in buf.iter_mut() {+ *s *= start;+ }+ return;+ }+ for (i, s) in buf.iter_mut().enumerate() {+ *s *= start + step * i as f32;+ }+}diff --git a/crates/mixer/src/fx/modulation.rs b/crates/mixer/src/fx/modulation.rsnew file mode 100644index 0000000..7ad8b83--- /dev/null+++ b/crates/mixer/src/fx/modulation.rs@@ -0,0 +1,497 @@+//! Chorus and Flange/Wah-wah, as VEGAS's.+//!+//! Chorus: one to three stages in a row, each a delay line read at a+//! sine-modulated time (its own rate: 1, 0.8117 and 1.1323 times the+//! period), optionally darkened by a one-pole low-pass, fed back, and+//! added to what goes through. The first stage takes the sound at the+//! input gain and keeps it at the dry level; in stereo its copy comes at+//! 0.81 (left) and 0.855 (right) of the chorus level squared, the later+//! stages' at 0.9 and 0.95 of it; in mono 0.9, 0.81 and 0.729 of it.+//!+//! Flange: a delay swinging around 1 ms by the depth, fed back by half,+//! its copy at 0.9 of the wet level (on two channels or more, of its+//! square, times each channel's own factor). Phaser and wah-wah: a+//! second-order all-pass whose frequency sweeps up and down in a straight+//! line (in Hz) over the depth's range of octaves, its resonance a Q; the+//! phaser averages it with the sound, the wah-wah takes it from the sound+//! (a band-pass).++use bv_timeline::Tempo;+use bv_timeline::audio_fx::{chorus as co, flange_wah_wah as fw, tempo};++use super::{Own, db_gain};++/// Added and taken away again on fed-back state, so a fading signal ends+/// at 0 instead of lingering as a denormal number.+const FLUSH: f32 = 1e-18;++/// A delay line read between its samples (by straight lines).+#[derive(Clone, Debug)]+struct Line {+ buf: Vec<f32>,+ mask: usize,+ /// Where the newest sample is.+ at: usize,+}++impl Line {+ fn new(len: usize) -> Line {+ let n = len.max(4).next_power_of_two();+ Line {+ buf: vec![0.0; n],+ mask: n - 1,+ at: 0,+ }+ }++ /// The sound `d` samples back (1 is the newest), between samples.+ #[inline]+ fn read(&self, d: f32) -> f32 {+ let whole = d.floor();+ let part = d - whole;+ let i = whole as usize;+ let a = self.buf[self.at.wrapping_sub(i - 1) & self.mask];+ let b = self.buf[self.at.wrapping_sub(i) & self.mask];+ a + (b - a) * part+ }++ #[inline]+ fn write(&mut self, x: f32) {+ self.at = (self.at + 1) & self.mask;+ self.buf[self.at] = x;+ }+}++/// Each chorus stage's period, a part of the modulation's.+const STAGE_PERIODS: [f64; 3] = [1.0, 0.8117, 1.1323];++/// A value of `params`, its default when missing.+fn param(params: &[f32], specs: &[bv_timeline::ParamSpec], i: usize) -> f32 {+ params+ .get(i)+ .copied()+ .unwrap_or(specs[i].default)+ .clamp(specs[i].min, specs[i].max)+}++/// A modulation's period in samples: `1 / rate`, or with tempo sync its+/// note times the multiplier.+fn period(rate: f64, sync: bool, note: f32, multiplier: f32, tempo: &Tempo, fs: f64) -> f64 {+ let seconds = if sync {+ tempo::seconds(note, tempo) * multiplier as f64+ } else {+ 1.0 / rate.max(1e-6)+ };+ (seconds * fs).max(1.0)+}++#[derive(Debug)]+pub(crate) struct Chorus {+ rate: f64,+ params: Vec<f32>,+ tempo: Tempo,+ /// Each stage's line a channel.+ lines: Vec<Vec<Line>>,+ /// Each stage's low-pass memory a channel.+ lows: Vec<Vec<f32>>,+ /// Each stage's place in its modulation, 0–1.+ phases: [f64; 3],+ /// How many stages ran last.+ used: usize,+ /// One block's delays (samples), a stage.+ delays: Vec<f32>,+}++impl Chorus {+ pub(crate) fn new(rate: u32) -> Chorus {+ Chorus {+ rate: rate.max(1) as f64,+ params: Vec::new(),+ tempo: Tempo::default(),+ lines: Vec::new(),+ lows: Vec::new(),+ phases: [0.0; 3],+ used: 0,+ delays: Vec::new(),+ }+ }++ fn p(&self, i: usize) -> f32 {+ param(&self.params, co::PARAMS, i)+ }+}++impl Own for Chorus {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ }++ fn keep_time(&mut self, tempo: &Tempo) {+ self.tempo = *tempo;+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let fs = self.rate;+ let count = channels.len();+ // Up to twice the longest delay, with room to read between samples.+ let room = (0.2 * fs) as usize + 4;+ if self.lines.len() != 3 || self.lines[0].len() != count {+ self.lines = vec![vec![Line::new(room); count]; 3];+ self.lows = vec![vec![0.0; count]; 3];+ }+ let stages = self.p(co::SIZE).round().clamp(1.0, 3.0) as usize;+ let input = db_gain(self.p(co::INPUT), -60.0);+ let dry = db_gain(self.p(co::DRY), -60.0);+ let mut wet = db_gain(self.p(co::WET), -60.0);+ if self.p(co::INVERT) >= 0.5 {+ wet = -wet;+ }+ let mut feedback = self.p(co::FEEDBACK);+ if self.p(co::INVERT_FEEDBACK) >= 0.5 {+ feedback = -feedback;+ }+ let base = self.p(co::DELAY) as f64 * fs / 1000.0;+ let swing = self.p(co::DEPTH) as f64 * base;+ let cutoff = self.p(co::CUTOFF) as f64;+ let low_pass = (self.p(co::ATTENUATE) >= 0.5 && cutoff < fs / 2.0)+ .then(|| (-std::f64::consts::TAU * cutoff / fs).exp() as f32);+ let samples = period(+ self.p(co::RATE) as f64,+ self.p(co::SYNC) >= 0.5,+ self.p(co::PERIOD),+ self.p(co::MULTIPLIER),+ &self.tempo,+ fs,+ );+ for (k, factor) in STAGE_PERIODS.iter().enumerate().take(stages) {+ // This stage's delays over the block, the same on every channel.+ let step = 1.0 / (samples * factor);+ let mut phase = self.phases[k];+ self.delays.clear();+ for _ in 0..n {+ let d = base + swing * (std::f64::consts::TAU * phase).sin();+ self.delays.push(d.max(1.0) as f32);+ phase = (phase + step).fract();+ }+ self.phases[k] = phase;+ for (c, ch) in channels.iter_mut().enumerate() {+ let level = match (count, k) {+ (1, k) => 0.9f32.powi(k as i32 + 1) * wet,+ (_, 0) => [0.81, 0.855][c % 2] * wet * wet,+ _ => [0.9, 0.95][c % 2] * wet,+ };+ let line = &mut self.lines[k][c];+ let low = &mut self.lows[k][c];+ for (x, d) in ch.iter_mut().zip(self.delays.iter()) {+ let into = if k == 0 { *x * input } else { *x };+ let late = line.read(*d);+ let y = match low_pass {+ Some(p) => {+ *low = (1.0 - p) * late + p * *low;+ *low+ }+ None => late,+ };+ line.write((into + feedback * y + FLUSH) - FLUSH);+ *x = if k == 0 { dry * into } else { into } + level * y;+ }+ }+ }+ // Stages left out start again silent when they come back.+ for k in stages..self.used {+ self.lines[k] = vec![Line::new(room); count];+ self.lows[k] = vec![0.0; count];+ }+ self.used = stages;+ }+}++/// The flange's wet level on each channel, two channels or more.+const FLANGE_CHANNELS: [f32; 16] = [+ 0.9, 0.95, 0.7, 0.9, 0.8, 1.0, 1.0, 0.7, 0.7, 1.0, 0.8, 1.0, 1.0, 0.8, 0.9, 0.7,+];++#[derive(Debug)]+pub(crate) struct FlangeWahWah {+ rate: f64,+ params: Vec<f32>,+ tempo: Tempo,+ lines: Vec<Line>,+ /// Each channel's all-pass memories.+ state: Vec<[f32; 2]>,+ /// The place in the modulation (or the sweep's round trip), 0–1.+ phase: f64,+ /// One block's delays, or the all-pass's two coefficients.+ a: Vec<f32>,+ b: Vec<f32>,+ /// Express Flange/Wah-Wah's flange levels: 0.9 and 0.95 of the wet+ /// level on the left and right (not of its square).+ express: bool,+}++impl FlangeWahWah {+ pub(crate) fn new(rate: u32) -> FlangeWahWah {+ FlangeWahWah {+ rate: rate.max(1) as f64,+ params: Vec::new(),+ tempo: Tempo::default(),+ lines: Vec::new(),+ state: Vec::new(),+ phase: 0.0,+ a: Vec::new(),+ b: Vec::new(),+ express: false,+ }+ }++ pub(crate) fn express(rate: u32) -> FlangeWahWah {+ FlangeWahWah {+ express: true,+ ..FlangeWahWah::new(rate)+ }+ }++ fn p(&self, i: usize) -> f32 {+ param(&self.params, fw::PARAMS, i)+ }+}++impl Own for FlangeWahWah {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ }++ fn keep_time(&mut self, tempo: &Tempo) {+ self.tempo = *tempo;+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let fs = self.rate;+ let count = channels.len();+ let dry = db_gain(self.p(fw::DRY), -80.0);+ let wet = db_gain(self.p(fw::WET), -80.0);+ let depth = self.p(fw::DEPTH) as f64;+ let step = 1.0+ / period(+ self.p(fw::RATE) as f64,+ self.p(fw::SYNC) >= 0.5,+ self.p(fw::PERIOD),+ self.p(fw::MULTIPLIER),+ &self.tempo,+ fs,+ );+ let mut phase = self.phase;+ self.a.clear();+ self.b.clear();+ let effect = self.p(fw::EFFECT).round() as i32;+ if effect == 0 {+ // Flange: about 1 ms, swinging by the depth.+ if self.lines.len() != count {+ self.lines = vec![Line::new((0.005 * fs) as usize + 4); count];+ }+ let base = fs / 1000.0;+ for _ in 0..n {+ let d = base + depth * base * (std::f64::consts::TAU * phase).sin();+ self.a.push(d.max(1.0) as f32);+ phase = (phase + step).fract();+ }+ for (c, ch) in channels.iter_mut().enumerate() {+ let level = if count == 1 {+ 0.9 * wet+ } else if self.express {+ [0.9, 0.95][c % 2] * wet+ } else {+ 0.9 * wet * wet * FLANGE_CHANNELS[c % 16]+ };+ let line = &mut self.lines[c];+ for (x, d) in ch.iter_mut().zip(self.a.iter()) {+ let late = line.read(*d);+ line.write((*x + 0.5 * late + FLUSH) - FLUSH);+ *x = dry * *x + level * late;+ }+ }+ } else {+ // Phaser and wah-wah: the sweep's range, `k` either side of the+ // centre (an octave at 50 %), and its Q.+ let pct = depth * 100.0;+ let mut spread = 1.0 + 0.002 * (pct - 50.0).powi(2);+ if pct > 50.0 {+ spread = 1.0 / spread;+ }+ let k = 2f64.powf(1.0 / spread);+ let res = self.p(fw::RESONANCE) as f64 * 100.0;+ let mut q = 1.0 + 0.008 * (res - 50.0).powi(2);+ if res < 50.0 {+ q = 1.0 / q;+ }+ let centre = self.p(fw::CENTER) as f64 / fs;+ let (lo, hi) = (centre / k, (centre * k).min(0.5));+ for _ in 0..n {+ // Up and back in a straight line, once a period.+ let there = 1.0 - (2.0 * phase - 1.0).abs();+ let f = lo + (hi - lo) * there;+ let r = (-std::f64::consts::PI * f / q).exp();+ self.a+ .push((2.0 * r * (std::f64::consts::TAU * f).cos()) as f32);+ self.b.push((r * r) as f32);+ phase = (phase + step).fract();+ }+ self.state.resize(count, [0.0; 2]);+ let phaser = effect == 1;+ for (ch, st) in channels.iter_mut().zip(self.state.iter_mut()) {+ let [mut v1, mut v2] = *st;+ for ((x, a1), a2) in ch.iter_mut().zip(self.a.iter()).zip(self.b.iter()) {+ let mut v = *x + a1 * v1 - a2 * v2;+ if v.abs() < 2e-11 {+ v = 0.0;+ }+ let all = a2 * v - a1 * v1 + v2;+ v2 = v1;+ v1 = v;+ let e = if phaser { (*x + all) * 0.5 } else { *x - all };+ *x = dry * *x + wet * e;+ }+ *st = [v1, v2];+ }+ }+ self.phase = phase;+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn chorus(values: &[(usize, f32)]) -> Chorus {+ let mut c = Chorus::new(48_000);+ let mut p: Vec<f32> = co::PARAMS.iter().map(|s| s.default).collect();+ for &(i, v) in values {+ p[i] = v;+ }+ c.set(&p);+ c+ }++ fn flange(values: &[(usize, f32)]) -> FlangeWahWah {+ let mut f = FlangeWahWah::new(48_000);+ let mut p: Vec<f32> = fw::PARAMS.iter().map(|s| s.default).collect();+ for &(i, v) in values {+ p[i] = v;+ }+ f.set(&p);+ f+ }++ fn sine(hz: f32, n: usize) -> Vec<f32> {+ (0..n)+ .map(|i| (std::f32::consts::TAU * hz * i as f32 / 48_000.0).sin())+ .collect()+ }++ fn rms(x: &[f32]) -> f32 {+ (x.iter().map(|s| s * s).sum::<f32>() / x.len() as f32).sqrt()+ }++ #[test]+ fn a_chorus_click_comes_back_after_its_delay() {+ // One stage, no depth to speak of, 10 ms, mono: the dry click, then+ // its copy 480 samples on at 0.9 of the chorus level.+ let mut c = chorus(&[+ (co::SIZE, 1.0),+ (co::DEPTH, 0.01),+ (co::DELAY, 10.0),+ (co::DRY, 0.0),+ (co::WET, 0.0),+ ]);+ let mut x = vec![vec![0.0f32; 2000]];+ x[0][0] = 1.0;+ c.process(&mut x);+ assert!((x[0][0] - 1.0).abs() < 1e-6);+ let copy: f32 = x[0][470..490].iter().sum();+ assert!((copy - 0.9).abs() < 0.02, "{copy}");+ assert!(x[0][1..460].iter().all(|s| s.abs() < 1e-6));+ }++ #[test]+ fn stereo_first_stage_takes_the_chorus_level_squared() {+ let mut c = chorus(&[+ (co::SIZE, 1.0),+ (co::DEPTH, 0.01),+ (co::DELAY, 10.0),+ (co::DRY, -60.0),+ (co::WET, -6.0),+ ]);+ let mut x = vec![vec![0.0f32; 2000], vec![0.0f32; 2000]];+ x[0][0] = 1.0;+ x[1][0] = 1.0;+ c.process(&mut x);+ let w = 10f32.powf(-6.0 / 20.0);+ let left: f32 = x[0][470..490].iter().sum();+ let right: f32 = x[1][470..490].iter().sum();+ assert!((left - 0.81 * w * w).abs() < 0.01, "{left}");+ assert!((right - 0.855 * w * w).abs() < 0.01, "{right}");+ }++ #[test]+ fn the_flange_s_dry_and_wet_levels() {+ // Dry only: the sound as it was.+ let mut f = flange(&[(fw::DRY, 0.0), (fw::WET, -80.0)]);+ let x = sine(440.0, 4800);+ let mut ch = vec![x.clone()];+ f.process(&mut ch);+ assert!(ch[0].iter().zip(&x).all(|(a, b)| (a - b).abs() < 1e-6));+ // Wet only, a low tone: the 1 ms copy fed back by half, at 0.9 —+ // about 0.9 / (1 − 0.5) = 1.8 times the tone.+ let mut f = flange(&[(fw::DRY, -80.0), (fw::WET, 0.0), (fw::DEPTH, 0.01)]);+ let mut ch = vec![sine(20.0, 48_000)];+ f.process(&mut ch);+ let level = rms(&ch[0][24_000..]) / rms(&sine(20.0, 24_000));+ assert!((level - 1.8).abs() < 0.05, "{level}");+ }++ #[test]+ fn the_wah_wah_is_a_band_pass_on_its_sweep() {+ // Depth 1 %: a sweep of almost nothing around 1 kHz, Q 1.+ let wah = |hz: f32| {+ let mut f = flange(&[+ (fw::EFFECT, 2.0),+ (fw::DRY, -80.0),+ (fw::WET, 0.0),+ (fw::DEPTH, 0.01),+ (fw::CENTER, 1000.0),+ (fw::RESONANCE, 0.5),+ (fw::RATE, 0.001),+ ]);+ let mut ch = vec![sine(hz, 48_000)];+ f.process(&mut ch);+ rms(&ch[0][24_000..]) / rms(&sine(hz, 24_000))+ };+ let (at, low, high) = (wah(1000.0), wah(100.0), wah(10_000.0));+ assert!(at > 1.5, "{at}");+ assert!(low < 0.4 && high < 0.4, "{low} {high}");+ }++ #[test]+ fn the_phaser_notches_where_the_all_pass_turns_half_round() {+ // A still sweep at 1 kHz: its all-pass turns 180° there, so the+ // phaser's average cancels.+ let phaser = |hz: f32| {+ let mut f = flange(&[+ (fw::EFFECT, 1.0),+ (fw::DRY, -80.0),+ (fw::WET, 0.0),+ (fw::DEPTH, 0.01),+ (fw::CENTER, 1000.0),+ (fw::RESONANCE, 0.5),+ (fw::RATE, 0.001),+ ]);+ let mut ch = vec![sine(hz, 48_000)];+ f.process(&mut ch);+ rms(&ch[0][24_000..]) / rms(&sine(hz, 24_000))+ };+ assert!(phaser(1000.0) < 0.2, "{}", phaser(1000.0));+ assert!(phaser(50.0) > 0.9);+ }+}diff --git a/crates/mixer/src/fx/offline.rs b/crates/mixer/src/fx/offline.rsnew file mode 100644index 0000000..38dbec3--- /dev/null+++ b/crates/mixer/src/fx/offline.rs@@ -0,0 +1,352 @@+//! The effects that change the sound's length, as VEGAS's: Time Stretch+//! (and its Express version), Pitch Shift, Gapper/Snipper and Vibrato.+//! They work on the whole sound at once (Non-Real-Time Event FX); in a+//! playing chain they let the sound through.++use bv_timeline::audio_fx::{+ gapper_snipper as gs, pitch_shift as ps, time_stretch as ts, vibrato as vb,+};+use bv_timeline::{Effect, EffectKind};++use super::graphs::{along, points};++/// The sound through `e` when it is one of these effects: a buffer a+/// channel, the result's length its own.+pub fn render(e: &Effect, rate: u32, channels: Vec<Vec<f32>>) -> Option<Vec<Vec<f32>>> {+ let params = super::params_of(e);+ let fs = rate.max(1) as f64;+ Some(match e.kind {+ EffectKind::TimeStretch | EffectKind::ExpressTimeStretch => {+ let p = |i: usize| value(¶ms, ts::PARAMS, i);+ let window = ts::WINDOWS[p(ts::MODE).round().clamp(0.0, 18.0) as usize];+ channels_map(channels, |x| {+ stretch(&x, p(ts::LENGTH) as f64 / 100.0, window, fs)+ })+ }+ EffectKind::GapperSnipper => {+ let p = |i: usize| value(¶ms, gs::PARAMS, i);+ gap_snip(+ channels,+ p(gs::FREQUENCY) as f64,+ p(gs::LENGTH) as f64,+ p(gs::FADE) as f64,+ p(gs::EFFECT) >= 0.5,+ fs,+ )+ }+ EffectKind::PitchShift => {+ let p = |i: usize| value(¶ms, ps::PARAMS, i);+ let ratio = 2f64.powf((p(ps::SEMITONES) as f64 + p(ps::CENTS) as f64 / 100.0) / 12.0);+ let points_used = [2, 9, 15][p(ps::ACCURACY).round().clamp(1.0, 3.0) as usize - 1];+ let anti_alias = p(ps::ANTI_ALIAS) >= 0.5 && ratio > 1.1;+ let keep = p(ps::PRESERVE) >= 0.5;+ let window = ts::WINDOWS[p(ps::MODE).round().clamp(0.0, 18.0) as usize];+ channels_map(channels, |x| {+ let x = if anti_alias {+ low_pass(&x, 0.5 / ratio * 0.95)+ } else {+ x+ };+ let shifted = resample(&x, ratio, points_used);+ if keep {+ stretch(&shifted, ratio, window, fs)+ } else {+ shifted+ }+ })+ }+ EffectKind::Vibrato => {+ let p = |i: usize| value(¶ms, vb::PARAMS, i);+ let mut wave = points(¶ms, vb::PARAMS, vb::GRAPH);+ if p(vb::BLEND) >= 0.5 && wave.len() >= 2 {+ let ends = (wave[0].1 + wave[wave.len() - 1].1) / 2.0;+ let (near, far) = (along(&wave, 50.0), along(&wave, 950.0));+ let mut blended = vec![(0.0, ends), (50.0, near)];+ blended.extend(wave.iter().copied().filter(|q| q.0 > 50.0 && q.0 < 950.0));+ blended.extend([(950.0, far), (1000.0, ends)]);+ wave = blended;+ }+ let semitones = p(vb::SEMITONES) as f64;+ let speeds: Vec<f64> = (0..1000)+ .map(|t| {+ 2f64.powf(+ along(&wave, t as f32).clamp(-100.0, 100.0) as f64 / 100.0 * semitones+ / 12.0,+ )+ })+ .collect();+ let cycle = (fs / p(vb::FREQUENCY) as f64).trunc().max(1.0);+ let gain = if p(vb::OUTPUT) <= -80.0 {+ 0.0+ } else {+ 10f64.powf(p(vb::OUTPUT) as f64 / 20.0)+ };+ channels_map(channels, |x| vary(&x, &speeds, cycle, gain))+ }+ _ => return None,+ })+}++fn value(params: &[f32], specs: &[bv_timeline::ParamSpec], i: usize) -> f32 {+ let s = &specs[i];+ params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+}++fn channels_map(channels: Vec<Vec<f32>>, f: impl Fn(Vec<f32>) -> Vec<f32>) -> Vec<Vec<f32>> {+ channels.into_iter().map(f).collect()+}++/// `x` lengthened `factor` times (or shortened below 1) without a change+/// of pitch: windows of `window_ms` laid down with half of them+/// overlapping, each taken where it best continues what was laid before+/// (within a third of a window), joined by straight crossfades.+pub(crate) fn stretch(x: &[f32], factor: f64, window_ms: f64, fs: f64) -> Vec<f32> {+ let w = ((window_ms / 1000.0 * fs) as usize).max(16);+ let hop_out = w / 2;+ let hop_in = hop_out as f64 / factor;+ let search = w / 3;+ let len = (x.len() as f64 * factor).round() as usize;+ let mut out = vec![0f32; len + w];+ let mut weight = vec![0f32; len + w];+ let at = |i: isize| -> f32 {+ if i < 0 || i as usize >= x.len() {+ 0.0+ } else {+ x[i as usize]+ }+ };+ let mut k = 0usize;+ let mut prev_end: Option<isize> = None;+ while k * hop_out < len {+ let nominal = (k as f64 * hop_in) as isize;+ // The start that best follows on from the last window's tail.+ let start = match prev_end {+ None => nominal,+ Some(tail) => {+ let mut best = nominal;+ let mut best_score = f32::MIN;+ let span = hop_out.min(256);+ let step = (search / 64).max(1);+ let mut d = -(search as isize);+ while d <= search as isize {+ let s = nominal + d;+ let score: f32 = (0..span as isize)+ .step_by(2)+ .map(|j| at(s + j) * at(tail + j))+ .sum();+ if score > best_score {+ best_score = score;+ best = s;+ }+ d += step as isize;+ }+ best+ }+ };+ let o = k * hop_out;+ for j in 0..w {+ // A triangle: straight fades in and out over the overlap.+ let g = if j < hop_out {+ j as f32 / hop_out as f32+ } else {+ (w - j) as f32 / (w - hop_out) as f32+ };+ out[o + j] += g * at(start + j as isize);+ weight[o + j] += g;+ }+ prev_end = Some(start + hop_out as isize);+ k += 1;+ }+ out.truncate(len);+ for (o, wt) in out.iter_mut().zip(weight) {+ if wt > 1e-6 {+ *o /= wt;+ }+ }+ out+}++/// `x` read `ratio` times as fast (higher and shorter above 1), between+/// its samples by `taps` points (2: straight lines; more: a windowed sinc).+pub(crate) fn resample(x: &[f32], ratio: f64, taps: usize) -> Vec<f32> {+ let len = (x.len() as f64 / ratio).floor() as usize;+ let half = (taps / 2) as isize;+ (0..len)+ .map(|i| {+ let pos = i as f64 * ratio;+ let base = pos.floor() as isize;+ let frac = pos - base as f64;+ if taps <= 2 {+ let a = x.get(base as usize).copied().unwrap_or(0.0);+ let b = x.get(base as usize + 1).copied().unwrap_or(0.0);+ return a + (b - a) * frac as f32;+ }+ let mut sum = 0.0;+ for k in (1 - half)..=half {+ let t = k as f64 - frac;+ let s = x.get((base + k) as usize).copied().unwrap_or(0.0) as f64;+ let sinc = if t.abs() < 1e-9 {+ 1.0+ } else {+ (std::f64::consts::PI * t).sin() / (std::f64::consts::PI * t)+ };+ let win = 0.5 + 0.5 * (std::f64::consts::PI * t / (half as f64 + 1.0)).cos();+ sum += s * sinc * win;+ }+ sum as f32+ })+ .collect()+}++/// A low-pass at `cutoff` (a part of the rate), eight second-order+/// sections in a row, run forward.+fn low_pass(x: &[f32], cutoff: f64) -> Vec<f32> {+ let w = std::f64::consts::TAU * cutoff.clamp(0.001, 0.49);+ let (s, c) = w.sin_cos();+ let alpha = s / std::f64::consts::SQRT_2;+ let a0 = 1.0 + alpha;+ let (b0, b1, a1, a2) = (+ (1.0 - c) / 2.0 / a0,+ (1.0 - c) / a0,+ -2.0 * c / a0,+ (1.0 - alpha) / a0,+ );+ let mut y: Vec<f64> = x.iter().map(|v| *v as f64).collect();+ for _ in 0..8 {+ let (mut x1, mut x2, mut y1, mut y2) = (0.0, 0.0, 0.0, 0.0);+ for v in y.iter_mut() {+ let out = b0 * *v + b1 * x1 + b0 * x2 - a1 * y1 - a2 * y2;+ x2 = x1;+ x1 = *v;+ y2 = y1;+ y1 = out;+ *v = out;+ }+ }+ y.into_iter().map(|v| v as f32).collect()+}++/// Gapper/Snipper: each period of the sound (faded in and out over its+/// edges, a share of the period) is followed by an event's length of+/// silence (the gapper) or loses the event's length that follows (the+/// snipper).+pub(crate) fn gap_snip(+ channels: Vec<Vec<f32>>,+ freq: f64,+ length: f64,+ fade: f64,+ snip: bool,+ fs: f64,+) -> Vec<Vec<f32>> {+ let period = ((fs / freq.max(1e-4)).trunc() as usize).max(1);+ let event = ((fs * length).trunc() as usize).max(1);+ let edge = ((fade * period as f64 / 100.0).trunc() as usize).max(1);+ channels+ .into_iter()+ .map(|x| {+ let mut out = Vec::with_capacity(x.len());+ let mut i = 0;+ while i < x.len() {+ let take = (period + 1).min(x.len() - i);+ for j in 0..take {+ let g = if j < edge {+ j as f32 / edge as f32+ } else if j + edge > period {+ (period + 1 - j) as f32 / edge as f32+ } else {+ 1.0+ };+ out.push(x[i + j] * g.min(1.0));+ }+ i += take;+ if snip {+ i += event;+ } else if i < x.len() {+ out.extend(std::iter::repeat_n(0.0, event));+ }+ }+ out+ })+ .collect()+}++/// Vibrato: the sound read at a speed that follows its wave (`speeds`, a+/// round of 1000 steps lasting `cycle` samples of the result), between+/// its samples by straight lines, at `gain`; it ends when the sound does.+pub(crate) fn vary(x: &[f32], speeds: &[f64], cycle: f64, gain: f64) -> Vec<f32> {+ let mut out = Vec::with_capacity(x.len());+ let mut pos = 0.0f64;+ let mut phase = 0.0f64;+ let step = 1000.0 / cycle;+ while (pos as usize) + 1 < x.len() {+ let i = pos as usize;+ let frac = (pos - i as f64) as f32;+ out.push(((x[i] + (x[i + 1] - x[i]) * frac) as f64 * gain) as f32);+ pos += speeds[(phase as usize).min(speeds.len() - 1)];+ phase += step;+ if phase >= 1000.0 {+ phase -= 1000.0;+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ fn sine(hz: f64, n: usize) -> Vec<f32> {+ (0..n)+ .map(|i| (std::f64::consts::TAU * hz * i as f64 / 48_000.0).sin() as f32)+ .collect()+ }++ /// The frequency of `x` from its zero crossings.+ fn pitch(x: &[f32]) -> f64 {+ let crossings = x.windows(2).filter(|w| w[0] <= 0.0 && w[1] > 0.0).count();+ crossings as f64 * 48_000.0 / x.len() as f64+ }++ #[test]+ fn stretching_changes_the_length_and_keeps_the_pitch() {+ let x = sine(440.0, 48_000);+ let y = stretch(&x, 1.5, 100.0, 48_000.0);+ assert_eq!(y.len(), 72_000);+ let p = pitch(&y[4_800..67_200]);+ assert!((p - 440.0).abs() < 8.0, "{p}");+ }++ #[test]+ fn resampling_raises_the_pitch_and_shortens() {+ let x = sine(440.0, 48_000);+ let y = resample(&x, 2.0, 9);+ assert_eq!(y.len(), 24_000);+ let p = pitch(&y[1_000..23_000]);+ assert!((p - 880.0).abs() < 8.0, "{p}");+ }++ #[test]+ fn the_gapper_inserts_and_the_snipper_cuts() {+ let x = vec![vec![1.0f32; 48_000]];+ let g = gap_snip(x.clone(), 10.0, 0.05, 10.0, false, 48_000.0);+ // Ten periods of 4801 samples, each with 2400 of silence after it+ // (but the last).+ assert!(g[0].len() > 48_000 + 9 * 2_400 - 10, "{}", g[0].len());+ let s = gap_snip(x, 10.0, 0.05, 10.0, true, 48_000.0);+ assert!(s[0].len() < 48_000 * 2 / 3 + 4_801, "{}", s[0].len());+ }++ #[test]+ fn a_flat_vibrato_an_octave_up_halves_the_length() {+ let x = sine(440.0, 48_000);+ let speeds = vec![2.0; 1000];+ let y = vary(&x, &speeds, 48_000.0, 1.0);+ assert!((y.len() as i32 - 24_000).abs() <= 1, "{}", y.len());+ let p = pitch(&y[1_000..23_000]);+ assert!((p - 880.0).abs() < 8.0, "{p}");+ }+}diff --git a/crates/mixer/src/fx/restoration.rs b/crates/mixer/src/fx/restoration.rsnew file mode 100644index 0000000..9342d19--- /dev/null+++ b/crates/mixer/src/fx/restoration.rs@@ -0,0 +1,331 @@+//! Express Audio Restoration, as VEGAS's: clicks taken out and the+//! steady hiss turned down, for old recordings.+//!+//! Clicks: where the sound's curvature (its second difference) jumps far+//! above its usual size — the more removal, the lower the bar — and is+//! back to it a millisecond later (a note starting stays high), the few+//! milliseconds around it are drawn again in a straight line between the+//! good sound either side.+//!+//! Hiss: the sound in overlapping windows (2048 samples, a quarter apart)+//! through FFTs; each band's level, smoothed over a few windows, has its+//! quietest of the last second and a half or so taken, twice that being+//! its noise (about its mean); the band is lowered where it+//! barely rises above that noise (a spectral subtraction, one and a half+//! times the noise taken away), down to the reduction at most; bands+//! below the noise floor count as noise, bands under "affect frequencies+//! above" are left alone; the gains glide from window to window by the+//! attack and release speeds.++use bv_timeline::audio_fx::express_audio_restoration as ar;++use crate::fft::{Complex, Plan};++use super::Own;++const SIZE: usize = 2048;+const HOP: usize = SIZE / 4;+/// The quietest level is kept for stretches of this many windows, the+/// last [`STRETCHES`] of them.+const STRETCH: usize = 16;+const STRETCHES: usize = 8;++#[derive(Debug)]+pub(crate) struct Restoration {+ rate: f32,+ params: Vec<f32>,+ plan: Plan,+ window: Vec<f32>,+ /// Each channel: its input gathered, its output going out (overlap-+ /// added), each band's noise and gain, the click detector's state.+ input: Vec<Vec<f32>>,+ output: Vec<Vec<f32>>,+ level: Vec<Vec<f32>>,+ /// Each band's quietest level in the stretch under way and in the+ /// last ones (each channel), how many windows the stretch has had,+ /// and where the next past one goes.+ quietest: Vec<Vec<f32>>,+ past: Vec<Vec<[f32; STRETCHES]>>,+ windows: usize,+ stretch: usize,+ /// How many windows have gone by since the start (the first ones,+ /// partly before the sound, are not looked at for the noise).+ seen: usize,+ gains: Vec<Vec<f32>>,+ curvature: Vec<f32>,+ at: usize,+ /// Each channel's newest sound, held while clicks are looked for.+ pre: Vec<Vec<f32>>,+ pre_at: usize,+ frame: Vec<Complex>,+}++impl Restoration {+ pub(crate) fn new(rate: u32) -> Restoration {+ let window = (0..SIZE)+ .map(|i| {+ // A Hann window's square root, on both sides: their product+ // a Hann, which sums to 2 at a quarter's overlap.+ let h = 0.5 - 0.5 * (std::f32::consts::TAU * i as f32 / SIZE as f32).cos();+ h.sqrt()+ })+ .collect();+ Restoration {+ rate: rate.max(1) as f32,+ params: Vec::new(),+ plan: Plan::new(SIZE),+ window,+ input: Vec::new(),+ output: Vec::new(),+ level: Vec::new(),+ quietest: Vec::new(),+ past: Vec::new(),+ windows: 0,+ stretch: 0,+ seen: 0,+ gains: Vec::new(),+ curvature: Vec::new(),+ at: 0,+ pre: Vec::new(),+ pre_at: 0,+ frame: Vec::new(),+ }+ }++ fn p(&self, i: usize) -> f32 {+ let s = &ar::PARAMS[i];+ self.params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+ }++ /// One window of channel `c` (its last SIZE input samples) through the+ /// noise reduction, overlap-added into its output.+ fn window_out(&mut self, c: usize) {+ let reduce = self.p(ar::REDUCTION);+ let floor_gain = if reduce >= 100.0 {+ 0.0+ } else {+ 10f32.powf(-reduce / 20.0)+ };+ let floor_db = self.p(ar::FLOOR);+ let floor = if floor_db <= -96.0 {+ 0.0+ } else {+ (0.25 * 10f32.powf(floor_db / 20.0) * SIZE as f32 / 4.0).powi(2)+ };+ let from = (self.p(ar::ABOVE) / self.rate * SIZE as f32) as usize;+ let attack = (100.0 - self.p(ar::ATTACK)) / 100.0;+ let release = (100.0 - self.p(ar::RELEASE)) / 100.0;+ let start = self.at;+ let input = &self.input[c];+ self.frame.clear();+ self.frame.extend(+ (0..SIZE)+ .map(|i| Complex::new((input[(start + i) % SIZE] * self.window[i]) as f64, 0.0)),+ );+ self.plan.run(&mut self.frame, false);+ let level = &mut self.level[c];+ let quietest = &mut self.quietest[c];+ let past = &self.past[c];+ let gains = &mut self.gains[c];+ for k in 0..=SIZE / 2 {+ let power = (self.frame[k].re.powi(2) + self.frame[k].im.powi(2)) as f32;+ let l = &mut level[k];+ *l = if *l == 0.0 {+ power+ } else {+ 0.8 * *l + 0.2 * power+ };+ if self.seen >= SIZE / HOP {+ quietest[k] = quietest[k].min(*l);+ }+ let noise = 2.0 * past[k].iter().fold(quietest[k], |m, &v| m.min(v));+ // Nothing known of the noise yet: the band is left alone.+ let target = if k < from || reduce <= 0.0 || !noise.is_finite() {+ 1.0+ } else if power <= floor {+ floor_gain+ } else {+ (1.0 - 1.5 * noise / power.max(1e-20))+ .max(0.0)+ .sqrt()+ .max(floor_gain)+ };+ let keep = if target < gains[k] { attack } else { release };+ gains[k] = target + (gains[k] - target) * keep;+ let g = gains[k] as f64;+ self.frame[k].re *= g;+ self.frame[k].im *= g;+ if k > 0 && k < SIZE / 2 {+ self.frame[SIZE - k].re *= g;+ self.frame[SIZE - k].im *= g;+ }+ }+ self.plan.run(&mut self.frame, true);+ let out = &mut self.output[c];+ for i in 0..SIZE {+ out[(start + i) % SIZE] += self.frame[i].re as f32 * self.window[i] * 0.5;+ }+ }+}++impl Own for Restoration {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let count = channels.len();+ let span = ((0.002 * self.rate) as usize).max(2);+ let held = 4 * span + 4;+ if self.input.len() != count || self.pre.first().map_or(0, Vec::len) != held {+ self.input = vec![vec![0.0; SIZE]; count];+ self.output = vec![vec![0.0; SIZE]; count];+ self.level = vec![vec![0.0; SIZE / 2 + 1]; count];+ self.quietest = vec![vec![f32::MAX; SIZE / 2 + 1]; count];+ self.past = vec![vec![[f32::MAX; STRETCHES]; SIZE / 2 + 1]; count];+ self.windows = 0;+ self.stretch = 0;+ self.seen = 0;+ self.gains = vec![vec![1.0; SIZE / 2 + 1]; count];+ self.curvature = vec![0.0; count];+ self.pre = vec![vec![0.0; held]; count];+ self.at = 0;+ self.pre_at = 0;+ }+ let n = channels.first().map_or(0, Vec::len);+ let amount = self.p(ar::CLICKS);+ // The click bar: how far above its usual size the curvature must go.+ let bar = 10f32.powf((22.0 - amount) / 18.0);+ let fade = 1.0 - 1.0 / (0.05 * self.rate);+ for i in 0..n {+ for (c, ch) in channels.iter_mut().enumerate() {+ // The newest sound waits a little, so a click is mended+ // whole before it goes on.+ let pre = &mut self.pre[c];+ pre[self.pre_at] = ch[i];+ let back = |pre: &[f32], k: usize| pre[(self.pre_at + held - k) % held];+ let bend = |pre: &[f32], k: usize| {+ (back(pre, k) - 2.0 * back(pre, k + 1) + back(pre, k + 2)).abs()+ };+ let curve = bend(pre, span);+ let usual = self.curvature[c];+ let limit = bar * usual * 4.0;+ // A click is short: the sound just after it (the newest+ // half span) bends as usual again; a note starting does not.+ let after = (0..span / 2).map(|k| bend(pre, k)).sum::<f32>() / (span / 2) as f32;+ let click = usual > 0.0 && curve > limit && after < limit * 0.25;+ if click {+ // Mended: a straight line across the samples around it.+ let (a, b) = (back(pre, 2 * span + 2), back(pre, 0));+ for k in 1..=(2 * span + 1) {+ let t = k as f32 / (2 * span + 2) as f32;+ let pos = (self.pre_at + held - (2 * span + 2) + k) % held;+ pre[pos] = a + (b - a) * t;+ }+ } else {+ self.curvature[c] = curve + (usual - curve) * fade;+ }+ let leaving = pre[(self.pre_at + 1) % held];+ self.input[c][self.at] = leaving;+ let out = &mut self.output[c];+ ch[i] = out[self.at];+ out[self.at] = 0.0;+ }+ self.pre_at = (self.pre_at + 1) % held;+ self.at = (self.at + 1) % SIZE;+ if self.at.is_multiple_of(HOP) {+ for c in 0..count {+ self.window_out(c);+ }+ // A stretch ends: its quietest levels join the past ones.+ self.seen += 1;+ self.windows += 1;+ if self.windows == STRETCH {+ self.windows = 0;+ for (now, past) in self.quietest.iter_mut().zip(&mut self.past) {+ for (q, p) in now.iter_mut().zip(past.iter_mut()) {+ p[self.stretch] = *q;+ *q = f32::MAX;+ }+ }+ self.stretch = (self.stretch + 1) % STRETCHES;+ }+ }+ }+ }++ fn latency(&self) -> usize {+ let span = ((0.002 * self.rate) as usize).max(2);+ SIZE + 4 * span + 3+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn restore(values: &[(usize, f32)]) -> Restoration {+ let mut r = Restoration::new(48_000);+ let mut p: Vec<f32> = ar::PARAMS.iter().map(|s| s.default).collect();+ for &(i, v) in values {+ p[i] = v;+ }+ r.set(&p);+ r+ }++ #[test]+ fn with_nothing_to_do_the_sound_comes_through_late() {+ let mut r = restore(&[(ar::REDUCTION, 0.0), (ar::CLICKS, 1.0)]);+ let x: Vec<f32> = (0..24_000)+ .map(|i| 0.5 * (std::f32::consts::TAU * 440.0 * i as f32 / 48_000.0).sin())+ .collect();+ let mut ch = vec![x.clone()];+ r.process(&mut ch);+ let lat = r.latency();+ for i in 6_000..20_000 {+ assert!(+ (ch[0][i] - x[i - lat]).abs() < 1e-3,+ "{i}: {} {}",+ ch[0][i],+ x[i - lat]+ );+ }+ }++ #[test]+ fn hiss_comes_down_and_a_click_goes() {+ // Quiet noise alone: turned well down.+ let mut r = restore(&[(ar::REDUCTION, 30.0), (ar::ABOVE, 100.0)]);+ let mut seed = 1u32;+ let noise: Vec<f32> = (0..96_000)+ .map(|_| {+ seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);+ (seed as f32 / u32::MAX as f32 - 0.5) * 0.02+ })+ .collect();+ let mut ch = vec![noise.clone()];+ r.process(&mut ch);+ let power = |x: &[f32]| x.iter().map(|s| s * s).sum::<f32>() / x.len() as f32;+ let before = power(&noise[72_000..]);+ let after = power(&ch[0][72_000..]);+ assert!(after < before / 4.0, "{before} {after}");+ // A click on a quiet tone: mended.+ let mut r = restore(&[(ar::REDUCTION, 0.0), (ar::CLICKS, 20.0)]);+ let mut x: Vec<f32> = (0..24_000)+ .map(|i| 0.1 * (std::f32::consts::TAU * 200.0 * i as f32 / 48_000.0).sin())+ .collect();+ x[12_000] += 0.9;+ let mut ch = vec![x];+ r.process(&mut ch);+ let lat = r.latency();+ let worst = ch[0][12_000 + lat - 200..12_000 + lat + 200]+ .iter()+ .fold(0f32, |m, s| m.max(s.abs()));+ assert!(worst < 0.3, "{worst}");+ }+}diff --git a/crates/mixer/src/fx/reverb.rs b/crates/mixer/src/fx/reverb.rsnew file mode 100644index 0000000..ac84cd4--- /dev/null+++ b/crates/mixer/src/fx/reverb.rs@@ -0,0 +1,451 @@+//! Reverb, as VEGAS's: the channels' average, darkened and thinned as+//! asked, feeds eight to ten comb filters in parallel (each mode's own+//! delays), each fed back through the same low-pass and falling 60 dB in+//! the decay time; the first two have twins, a little shorter and longer,+//! that make the right side, so the room opens in stereo. Three early+//! reflections (each style's times, levels and places) come from the+//! sound itself; the combs' sound comes after the pre-delay.++use bv_timeline::audio_fx::reverb as rv;++use super::{Own, db_gain};++/// Each mode's combs: how many, and their delays in milliseconds.+const MODES: [(usize, [f32; 10]); 19] = [+ (+ 10,+ [23.6, 47.1, 25.5, 27.5, 29.7, 34.5, 32.1, 37.3, 40.4, 19.9],+ ),+ (+ 8,+ [23.2, 18.5, 20.6, 16.0, 26.5, 29.3, 13.0, 33.5, 0.0, 0.0],+ ),+ (+ 10,+ [53.7, 67.6, 41.1, 72.9, 84.3, 49.6, 45.9, 57.8, 62.5, 78.7],+ ),+ (+ 10,+ [13.5, 25.0, 28.4, 12.0, 15.8, 17.8, 10.7, 19.7, 9.4, 22.0],+ ),+ (+ 10,+ [54.2, 28.7, 21.0, 49.3, 44.4, 35.9, 12.3, 66.5, 40.3, 60.1],+ ),+ (+ 10,+ [70.5, 46.5, 52.8, 39.7, 76.9, 58.5, 64.3, 31.6, 90.8, 83.5],+ ),+ (+ 10,+ [46.5, 89.9, 53.0, 58.8, 83.1, 70.5, 3901.7, 76.4, 64.7, 31.6],+ ),+ (+ 9,+ [25.0, 34.8, 29.5, 37.5, 32.1, 22.7, 40.5, 43.8, 47.1, 0.0],+ ),+ (+ 10,+ [33.0, 35.3, 44.2, 38.2, 62.8, 30.4, 41.5, 47.5, 51.6, 56.5],+ ),+ (+ 10,+ [13.4, 24.4, 11.9, 10.3, 4.5, 15.2, 20.3, 8.5, 17.2, 6.5],+ ),+ (10, [31.7, 21.9, 5.0, 27.3, 11.4, 16.0, 6.6, 9.7, 8.2, 13.3]),+ (10, [13.3, 20.3, 12.0, 10.6, 4.7, 14.8, 17.0, 9.1, 6.6, 8.0]),+ (+ 10,+ [21.1, 66.4, 28.7, 49.3, 44.4, 36.0, 12.3, 40.3, 54.3, 60.0],+ ),+ (+ 10,+ [41.0, 45.8, 49.6, 53.8, 57.8, 62.5, 67.6, 72.9, 78.7, 84.2],+ ),+ (+ 10,+ [37.1, 45.9, 62.8, 53.7, 57.8, 17.3, 67.6, 73.0, 78.7, 84.2],+ ),+ (+ 9,+ [50.1, 62.8, 53.9, 25.8, 17.2, 67.8, 73.6, 93.9, 84.2, 0.0],+ ),+ (9, [31.7, 15.0, 11.5, 36.0, 19.1, 5.4, 9.4, 26.4, 7.4, 0.0]),+ (10, [3.1, 18.4, 12.9, 11.1, 5.0, 15.5, 6.5, 9.5, 21.7, 7.9]),+ (+ 10,+ [29.8, 12.8, 49.7, 20.8, 25.3, 43.0, 16.0, 4.6, 9.1, 36.5],+ ),+];++/// The twins of the first two combs, parts of their delays.+const TWINS: [f32; 2] = [0.93, 1.06];++/// Each style's three reflections: time (ms), level and place (−1 left+/// to 1 right).+const STYLES: [[(f32, f32, f32); 3]; 10] = [+ [(6.1, 0.46, -0.72), (17.0, -0.60, 0.71), (29.2, 0.21, -0.06)],+ [(8.2, 0.56, 0.70), (20.0, -0.60, -0.70), (53.2, 0.18, 0.16)],+ [(11.1, -0.47, -0.76), (17.0, 0.60, 1.00), (29.5, 0.28, 0.35)],+ [+ (16.0, 0.79, 0.64),+ (30.1, -0.80, -1.00),+ (55.0, 0.40, -0.26),+ ],+ [+ (20.0, 1.00, 0.25),+ (29.0, -0.50, -0.29),+ (49.0, 0.40, -0.25),+ ],+ [+ (36.5, 1.00, 0.25),+ (47.1, -0.50, -0.29),+ (62.0, 0.40, -0.25),+ ],+ [(8.2, 0.56, 0.50), (20.0, -0.60, 0.70), (53.2, 0.18, 0.26)],+ [+ (8.2, 0.56, -0.50),+ (20.0, -0.60, -0.70),+ (53.2, 0.18, -0.26),+ ],+ [(16.0, 0.79, 0.80), (30.1, -0.80, 0.90), (55.0, 0.40, 0.25)],+ [+ (16.0, 0.79, -0.80),+ (30.1, -0.80, -0.90),+ (55.0, 0.40, -0.25),+ ],+];++/// What each reflection's time gains, in milliseconds.+const NUDGE: [f32; 3] = [0.051, 0.151, 0.078];++/// Added and taken away again on fed-back state, so a fading signal ends+/// at 0 instead of lingering as a denormal number.+const FLUSH: f32 = 1e-18;++/// A comb filter: a line, the low-pass in its loop, its gain per round.+#[derive(Clone, Debug)]+struct Comb {+ line: Vec<f32>,+ at: usize,+ low: f32,+ gain: f32,+ ms: f32,+}++impl Comb {+ fn new(ms: f32, fs: f32) -> Comb {+ Comb {+ line: vec![0.0; ((ms * fs / 1000.0).round() as usize).max(1)],+ at: 0,+ low: 0.0,+ gain: 0.0,+ ms,+ }+ }++ /// The block `input` through the comb, added to `out`.+ fn run(&mut self, input: &[f32], out: &mut [f32], p: f32) {+ let len = self.line.len();+ let (g, mut low, mut at) = (self.gain, self.low, self.at);+ for (x, o) in input.iter().zip(out.iter_mut()) {+ let y = self.line[at];+ low = (p * low + (1.0 - p) * y + FLUSH) - FLUSH;+ self.line[at] = g * (*x + low);+ at += 1;+ if at == len {+ at = 0;+ }+ *o += y;+ }+ self.low = low;+ self.at = at;+ }+}++/// A plain delay line, `len` long.+#[derive(Clone, Debug, Default)]+struct Delay {+ line: Vec<f32>,+ at: usize,+}++impl Delay {+ fn new(len: usize) -> Delay {+ Delay {+ line: vec![0.0; len.max(1)],+ at: 0,+ }+ }++ /// Writes `x`; what was written `back` samples before it (1 the last).+ fn push(&mut self, x: f32) {+ self.at = (self.at + 1) % self.line.len();+ self.line[self.at] = x;+ }++ fn back(&self, back: usize) -> f32 {+ let n = self.line.len();+ self.line[(self.at + n - back.min(n - 1)) % n]+ }+}++#[derive(Debug)]+pub(crate) struct ReverbFx {+ rate: f32,+ params: Vec<f32>,+ mode: usize,+ /// The mode's combs, then the two twins.+ combs: Vec<Comb>,+ /// The averaged sound, as the combs take it after the pre-delay.+ pre: Delay,+ /// The averaged sound, for the early reflections.+ early: Delay,+ /// The input's low-pass memory and its bass filter's state.+ low: f32,+ bass: [f32; 4],+ /// One block's averaged sound, its pre-delayed copy, and the left,+ /// right and shared combs' sums.+ mono: Vec<f32>,+ late: Vec<f32>,+ sums: [Vec<f32>; 3],+}++impl ReverbFx {+ pub(crate) fn new(rate: u32) -> ReverbFx {+ let fs = rate.max(1) as f32;+ ReverbFx {+ rate: fs,+ params: Vec::new(),+ mode: usize::MAX,+ combs: Vec::new(),+ pre: Delay::new((0.2 * fs) as usize + 2),+ early: Delay::new((0.07 * fs) as usize + 2),+ low: 0.0,+ bass: [0.0; 4],+ mono: Vec::new(),+ late: Vec::new(),+ sums: Default::default(),+ }+ }++ fn p(&self, i: usize) -> f32 {+ self.params+ .get(i)+ .copied()+ .unwrap_or(rv::PARAMS[i].default)+ .clamp(rv::PARAMS[i].min, rv::PARAMS[i].max)+ }+}++impl Own for ReverbFx {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ let mode = self.p(rv::MODE).round() as usize;+ if mode != self.mode {+ // Another room: its combs start silent.+ self.mode = mode;+ let (n, delays) = MODES[mode.min(MODES.len() - 1)];+ self.combs = delays[..n]+ .iter()+ .map(|&ms| Comb::new(ms, self.rate))+ .collect();+ for (k, twin) in TWINS.iter().enumerate() {+ self.combs.push(Comb::new(delays[k] * twin, self.rate));+ }+ }+ // −60 dB after the decay time: each round loses its share.+ let decay = self.p(rv::DECAY);+ for c in &mut self.combs {+ c.gain = 10f32.powf(-3.0 * c.ms / 1000.0 / decay);+ }+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let count = channels.len();+ if n == 0 || count == 0 {+ return;+ }+ let fs = self.rate;+ let dry = db_gain(self.p(rv::DRY), -80.0);+ let wet = db_gain(self.p(rv::WET), -80.0);+ let early = db_gain(self.p(rv::EARLY), -80.0);+ // The high cut (one pole), on the input and in the combs' loops.+ let p = if self.p(rv::HIGH) >= 0.5 {+ (-2.0 * std::f32::consts::TAU * self.p(rv::HIGH_FREQ) / fs).exp()+ } else {+ 0.0+ };+ // The bass cut: a second-order low-pass whose output is taken away.+ let bass = (self.p(rv::BASS) >= 0.5).then(|| {+ let w = std::f32::consts::TAU * self.p(rv::BASS_FREQ).min(0.45 * fs) / fs;+ let (s, c) = w.sin_cos();+ let alpha = s / std::f32::consts::SQRT_2;+ let a0 = 1.0 + alpha;+ let b = (1.0 - c) / 2.0 / a0;+ [b, 2.0 * b, b, -2.0 * c / a0, (1.0 - alpha) / a0]+ });+ let pre = (self.p(rv::PREDELAY) / 1000.0 * fs).round() as usize;+ self.mono.clear();+ self.late.clear();+ let mut low = self.low;+ for i in 0..n {+ let m = channels.iter().map(|c| c[i]).sum::<f32>() / count as f32;+ low = (p * low + (1.0 - p) * m + FLUSH) - FLUSH;+ let mut x = low;+ if let Some([b0, b1, b2, a1, a2]) = bass {+ let [x1, x2, y1, y2] = self.bass;+ let y = (b0 * x + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2 + FLUSH) - FLUSH;+ self.bass = [x, x1, y, y1];+ x -= y;+ }+ self.mono.push(x);+ self.pre.push(x);+ self.late+ .push(if pre == 0 { x } else { self.pre.back(pre) });+ }+ self.low = low;+ // The combs: the first two (left), their twins (right), the rest+ // (both).+ let shared = self.combs.len() - 2;+ for s in &mut self.sums {+ s.clear();+ s.resize(n, 0.0);+ }+ for (k, comb) in self.combs.iter_mut().enumerate() {+ let side = if k < 2 {+ 0+ } else if k >= shared {+ 1+ } else {+ 2+ };+ comb.run(&self.late, &mut self.sums[side], p);+ }+ let style = STYLES[(self.p(rv::STYLE).round() as usize).min(STYLES.len() - 1)];+ let taps: Vec<usize> = style+ .iter()+ .zip(NUDGE)+ .map(|((ms, _, _), nudge)| ((ms + nudge) / 1000.0 * fs).round() as usize)+ .collect();+ for i in 0..n {+ self.early.push(self.mono[i]);+ let (mut left, mut right) = (0.0, 0.0);+ for ((_, level, place), back) in style.iter().zip(&taps) {+ let tap = level * self.early.back(*back);+ let to_right = (place + 1.0) / 2.0;+ left += tap * (1.0 - to_right);+ right += tap * to_right;+ }+ for (c, ch) in channels.iter_mut().enumerate() {+ let (combs, reflections) = if count == 1 {+ (self.sums[0][i] + self.sums[2][i], left + right)+ } else if c % 2 == 0 {+ (self.sums[0][i] + self.sums[2][i], left)+ } else {+ (self.sums[1][i] + self.sums[2][i], right)+ };+ ch[i] = dry * ch[i] + wet * combs + early * reflections;+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn reverb(values: &[(usize, f32)]) -> ReverbFx {+ let mut r = ReverbFx::new(48_000);+ let mut p: Vec<f32> = rv::PARAMS.iter().map(|s| s.default).collect();+ for &(i, v) in values {+ p[i] = v;+ }+ r.set(&p);+ r+ }++ fn energy(x: &[f32]) -> f32 {+ x.iter().map(|s| s * s).sum()+ }++ #[test]+ fn its_tail_falls_60_db_in_the_decay_time() {+ // Mono, combs only, no cuts: a click's tail, 1 s apart, 60 dB down.+ let mut r = reverb(&[+ (rv::DRY, -80.0),+ (rv::WET, 0.0),+ (rv::EARLY, -80.0),+ (rv::DECAY, 1.0),+ (rv::PREDELAY, 0.0),+ (rv::BASS, 0.0),+ (rv::HIGH, 0.0),+ ]);+ let mut x = [vec![0.0f32; 144_000]];+ x[0][0] = 1.0;+ for block in x[0].chunks_mut(4_800) {+ let mut b = vec![block.to_vec()];+ r.process(&mut b);+ block.copy_from_slice(&b[0]);+ }+ let first = energy(&x[0][24_000..48_000]);+ let later = energy(&x[0][72_000..96_000]);+ let db = 10.0 * (later / first).log10();+ assert!((db + 60.0).abs() < 4.0, "{db}");+ }++ #[test]+ fn the_pre_delay_holds_the_tail_back() {+ let mut r = reverb(&[+ (rv::DRY, -80.0),+ (rv::WET, 0.0),+ (rv::EARLY, -80.0),+ (rv::PREDELAY, 100.0),+ (rv::BASS, 0.0),+ (rv::HIGH, 0.0),+ ]);+ let mut x = vec![vec![0.0f32; 9_600]];+ x[0][0] = 1.0;+ r.process(&mut x);+ // Nothing before 100 ms plus the shortest comb.+ assert!(x[0][..4_800].iter().all(|s| *s == 0.0));+ assert!(energy(&x[0][4_800..]) > 0.0);+ }++ #[test]+ fn the_early_reflections_and_the_stereo_sides() {+ // Early only, style 1: 6.151 ms (295 samples), 46 %, 72 % left.+ let mut r = reverb(&[+ (rv::DRY, -80.0),+ (rv::WET, -80.0),+ (rv::EARLY, 0.0),+ (rv::STYLE, 0.0),+ (rv::BASS, 0.0),+ (rv::HIGH, 0.0),+ ]);+ let mut x = vec![vec![0.0f32; 4_800], vec![0.0f32; 4_800]];+ x[0][0] = 1.0;+ x[1][0] = 1.0;+ r.process(&mut x);+ let at = 295;+ assert!((x[0][at] - 0.46 * 0.86).abs() < 1e-4, "{}", x[0][at]);+ assert!((x[1][at] - 0.46 * 0.14).abs() < 1e-4, "{}", x[1][at]);+ // The combs: the left and the right differ.+ let mut r = reverb(&[(rv::DRY, -80.0), (rv::WET, 0.0), (rv::EARLY, -80.0)]);+ let mut x = vec![vec![0.0f32; 9_600], vec![0.0f32; 9_600]];+ x[0][0] = 1.0;+ x[1][0] = 1.0;+ r.process(&mut x);+ assert!(x[0].iter().zip(&x[1]).any(|(a, b)| (a - b).abs() > 1e-3));+ }++ #[test]+ fn dry_only_leaves_the_sound_alone() {+ let mut r = reverb(&[(rv::DRY, 0.0), (rv::WET, -80.0), (rv::EARLY, -80.0)]);+ let x: Vec<f32> = (0..4800).map(|i| (i as f32 * 0.01).sin()).collect();+ let mut ch = vec![x.clone()];+ r.process(&mut ch);+ assert_eq!(ch[0], x);+ }+}diff --git a/crates/mixer/src/fx/studio.rs b/crates/mixer/src/fx/studio.rsnew file mode 100644index 0000000..39ef380--- /dev/null+++ b/crates/mixer/src/fx/studio.rs@@ -0,0 +1,838 @@+//! BananaV's versions of the studio set (Gate, DeEsser, Limiter, Tremolo+//! Pan, Tube Stage, Vocal Strip, …), built from what their controls do.+//! Every one takes the sound at its input gain and gives it back at its+//! output gain.++use bv_timeline::audio_fx::{+ efx_deesser as ed, efx_gate as eg, efx_limiter as el, efx_tremolo_pan as et,+ efx_tube_stage as tu, efx_vocal_strip as ev,+};++use super::Own;+use super::eq::Section;++/// Added and taken away again on fed-back state, so a fading signal ends+/// at 0 instead of lingering as a denormal number.+const FLUSH: f32 = 1e-18;++/// A one-pole follower's coefficient for a time in milliseconds.+fn follow(ms: f32, fs: f32) -> f32 {+ let n = ms / 1000.0 * fs;+ if n < 1.0 { 0.0 } else { (-1.0 / n).exp() }+}++fn db(v: f32) -> f32 {+ 10f32.powf(v / 20.0)+}++/// Gate: the level (of the side chain: the sound itself, filtered when+/// asked) followed up by the attack and down by the release; below the+/// threshold the sound comes down by the range (with the soft knee over+/// 12 dB), held open a while after the level falls, the gain itself+/// gliding through two more followers; the sound a little late, so the+/// gate is open when a note starts.+#[derive(Debug)]+pub(crate) struct Gate {+ rate: f32,+ params: Vec<f32>,+ side: Option<Section>,+ high_pass: Option<Section>,+ level: f32,+ held: usize,+ gains: [f32; 2],+ /// Each channel's filters' memories: side chain, input high-pass.+ memory: Vec<[[f32; 4]; 2]>,+ lines: Vec<Vec<f32>>,+ at: usize,+}++impl Gate {+ pub(crate) fn new(rate: u32) -> Gate {+ Gate {+ rate: rate.max(1) as f32,+ params: Vec::new(),+ side: None,+ high_pass: None,+ level: 0.0,+ held: 0,+ gains: [1.0; 2],+ memory: Vec::new(),+ lines: Vec::new(),+ at: 0,+ }+ }++ fn p(&self, i: usize) -> f32 {+ let s = &eg::PARAMS[i];+ self.params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+ }++ fn ahead(&self) -> usize {+ (self.p(eg::LOOK_AHEAD) / 1000.0 * self.rate).round() as usize+ }+}++impl Own for Gate {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ let fs = self.rate as f64;+ let hz = self.p(eg::FILTER) as f64;+ self.side = match self.p(eg::FILTER_TYPE).round() as i32 {+ 1 => Some(Section::pass(hz, true, fs)),+ 2 => Some(Section::band(hz, 1.0, fs)),+ 3 => Some(Section::pass(hz, false, fs)),+ _ => None,+ };+ let hp = self.p(eg::INPUT_HIGH_PASS) as f64;+ self.high_pass = (hp >= 1.0).then(|| Section::pass(hp, true, fs));+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let count = channels.len();+ let fs = self.rate;+ let input = db(self.p(eg::INPUT));+ let output = db(self.p(eg::OUTPUT));+ let threshold = self.p(eg::THRESHOLD);+ let range = self.p(eg::RANGE);+ let floor = if range >= 90.0 { 0.0 } else { db(-range) };+ let soft = self.p(eg::SOFT_KNEE) >= 0.5;+ let up = follow(self.p(eg::ATTACK), fs);+ let down = follow(self.p(eg::RELEASE), fs);+ let hold = ([10.0, 50.0, 150.0][self.p(eg::HOLD).round().clamp(0.0, 2.0) as usize] / 1000.0+ * fs) as usize;+ let listen = self.p(eg::LISTEN) >= 0.5;+ let ahead = self.ahead();+ let room = ahead + 1;+ if self.lines.len() != count || self.lines.first().map_or(0, Vec::len) != room {+ self.lines = vec![vec![0.0; room]; count];+ self.memory = vec![[[0.0; 4]; 2]; count];+ self.at = 0;+ }+ for i in 0..n {+ let mut peak = 0f32;+ for (c, ch) in channels.iter_mut().enumerate() {+ let mut x = ch[i] * input;+ if let Some(hp) = &self.high_pass {+ x = hp.run(x, &mut self.memory[c][1]);+ }+ ch[i] = x;+ let s = match &self.side {+ Some(f) => f.run(x, &mut self.memory[c][0]),+ None => x,+ };+ if listen {+ ch[i] = s;+ }+ peak = peak.max(s.abs());+ }+ let c = if peak > self.level { up } else { down };+ self.level = (peak + (self.level - peak) * c + FLUSH) - FLUSH;+ let l = 20.0 * self.level.max(1e-9).log10();+ let mut target = if l >= threshold {+ self.held = hold;+ 1.0+ } else if self.held > 0 {+ self.held -= 1;+ 1.0+ } else if soft && l > threshold - 12.0 {+ db(-range * (threshold - l) / 12.0).max(floor)+ } else {+ floor+ };+ if listen {+ target = 1.0;+ }+ for g in self.gains.iter_mut() {+ let c = if target > *g { up } else { down };+ *g = target + (*g - target) * c;+ target = *g;+ }+ let gain = self.gains[1] * output;+ let at = self.at;+ for (c, ch) in channels.iter_mut().enumerate() {+ let line = &mut self.lines[c];+ line[at] = ch[i];+ ch[i] = line[(at + 1) % room] * gain;+ }+ self.at = (at + 1) % room;+ }+ }++ fn latency(&self) -> usize {+ self.ahead()+ }+}++/// DeEsser: no threshold to set — the level of a band around its+/// frequency (Q its width) is compared with the whole sound's; where the+/// band stands out, that band is turned down, up to the reduction (the+/// share, doubled and rounded off, of how much it stands out). Listen+/// plays the band alone.+#[derive(Debug)]+pub(crate) struct DeEsser {+ rate: f32,+ params: Vec<f32>,+ band: Section,+ memory: Vec<[f32; 4]>,+ /// The band's and the whole sound's followed levels.+ levels: [f32; 2],+}++impl DeEsser {+ pub(crate) fn new(rate: u32) -> DeEsser {+ DeEsser {+ rate: rate.max(1) as f32,+ params: Vec::new(),+ band: Section::default(),+ memory: Vec::new(),+ levels: [0.0; 2],+ }+ }++ fn p(&self, i: usize) -> f32 {+ let s = &ed::PARAMS[i];+ self.params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+ }+}++impl Own for DeEsser {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ // Q to octaves: a narrow Q (2) is about two thirds of an octave.+ let q = self.p(ed::Q) as f64;+ let octaves = (2.0 / std::f64::consts::LN_2) * (1.0 / (2.0 * q)).asinh();+ self.band = Section::band(self.p(ed::FREQUENCY) as f64, octaves, self.rate as f64);+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ self.memory.resize(channels.len(), [0.0; 4]);+ let input = db(self.p(ed::INPUT));+ let output = db(self.p(ed::OUTPUT));+ let reduction = self.p(ed::REDUCTION);+ let listen = self.p(ed::LISTEN) >= 0.5;+ let up = follow(1.0, self.rate);+ let down = follow(60.0, self.rate);+ for i in 0..n {+ let (mut band, mut whole) = (0f32, 0f32);+ let mut bands = [0f32; 8];+ for (c, ch) in channels.iter_mut().enumerate() {+ let x = ch[i] * input;+ ch[i] = x;+ let b = self.band.run(x, &mut self.memory[c]);+ if c < 8 {+ bands[c] = b;+ }+ band = band.max(b.abs());+ whole = whole.max(x.abs());+ }+ for (level, now) in self.levels.iter_mut().zip([band, whole]) {+ let c = if now > *level { up } else { down };+ *level = (now + (*level - now) * c + FLUSH) - FLUSH;+ }+ // How much the band stands out: its share of the whole.+ let share = (self.levels[0] / self.levels[1].max(1e-9)).min(1.0);+ let m = (2.0 * share).min(1.0);+ let m = (2.0 - m) * m;+ let cut = db(-m * reduction) - 1.0;+ for (c, ch) in channels.iter_mut().enumerate() {+ let b = if c < 8 { bands[c] } else { 0.0 };+ ch[i] = output * if listen { b } else { ch[i] + cut * b };+ }+ }+ }+}++/// Limiter: the sound (its lows cut below the input low cut) held under+/// the threshold — 0.99 of it — by a gain that drops at once on what it+/// sees ahead (the attack's look-ahead) and comes back by the release,+/// slower the longer and harder it has been working when adaptive; the+/// level read between the peak and the power by Peak vs. RMS, the side+/// chain's lows cut first. Auto makeup brings the threshold back to full+/// scale; then the clip gain pushes it into the clipper (shape 0 a cubic+/// curve, 1 straight up to the limit) and the output gain sets the top.+#[derive(Debug)]+pub(crate) struct Limiter {+ rate: f32,+ params: Vec<f32>,+ input_cut: Option<Section>,+ side_cut: Option<Section>,+ memory: Vec<[[f32; 4]; 2]>,+ lines: Vec<Vec<f32>>,+ at: usize,+ gain: f32,+ power: f32,+ /// How long it has been holding the level down (samples).+ working: f32,+ /// The gains the sound in the line asks for: the gain never rises+ /// above the least of them, so nothing in the line gets past.+ targets: Vec<f32>,+}++impl Limiter {+ pub(crate) fn new(rate: u32) -> Limiter {+ Limiter {+ rate: rate.max(1) as f32,+ params: Vec::new(),+ input_cut: None,+ side_cut: None,+ memory: Vec::new(),+ lines: Vec::new(),+ at: 0,+ gain: 1.0,+ power: 0.0,+ working: 0.0,+ targets: Vec::new(),+ }+ }++ fn p(&self, i: usize) -> f32 {+ let s = &el::PARAMS[i];+ self.params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+ }++ fn ahead(&self) -> usize {+ (self.p(el::ATTACK) / 1000.0 * self.rate).round() as usize+ }+}++/// The clipper: `v` past the limit of 1 held there; `shape` 0 a cubic+/// curve 1.5·(v − v³/3), 1 straight.+fn clip(v: f32, shape: f32) -> f32 {+ let v = v.clamp(-1.0, 1.0);+ (v - v * v * v / 3.0) * 1.5 * (1.0 - shape) + v * shape+}++impl Own for Limiter {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ let fs = self.rate as f64;+ let cut = |hz: f32| (hz >= 1.0).then(|| Section::pass(hz as f64, true, fs));+ self.input_cut = cut(self.p(el::INPUT_LOW_CUT));+ self.side_cut = cut(self.p(el::SIDE_LOW_CUT));+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let count = channels.len();+ let ahead = self.ahead();+ let room = ahead + 1;+ if self.lines.len() != count || self.lines.first().map_or(0, Vec::len) != room {+ self.lines = vec![vec![0.0; room]; count];+ self.memory = vec![[[0.0; 4]; 2]; count];+ self.targets = vec![1.0; room];+ self.at = 0;+ }+ let input = db(self.p(el::INPUT));+ let output = db(self.p(el::OUTPUT));+ let ceiling = 0.99 * db(self.p(el::THRESHOLD));+ let makeup = if self.p(el::MAKEUP) >= 0.5 {+ 1.0 / db(self.p(el::THRESHOLD))+ } else {+ 1.0+ };+ let push = db(self.p(el::CLIP_GAIN));+ let shape = self.p(el::CLIP_SHAPE);+ let mix = self.p(el::PEAK_RMS);+ let adaptive = self.p(el::ADAPTIVE);+ let release_ms = self.p(el::RELEASE);+ let rms = follow(10.0, self.rate);+ for i in 0..n {+ let mut peak = 0f32;+ let mut power = 0f32;+ for (c, ch) in channels.iter_mut().enumerate() {+ let mut x = ch[i] * input;+ if let Some(f) = &self.input_cut {+ x = f.run(x, &mut self.memory[c][0]);+ }+ ch[i] = x;+ let s = match &self.side_cut {+ Some(f) => f.run(x, &mut self.memory[c][1]),+ None => x,+ };+ peak = peak.max(s.abs());+ power += s * s;+ }+ self.power =+ power / count.max(1) as f32 + (self.power - power / count.max(1) as f32) * rms;+ let level = peak * (1.0 - mix) + self.power.sqrt() * std::f32::consts::SQRT_2 * mix;+ self.targets[self.at] = if level > ceiling {+ ceiling / level+ } else {+ 1.0+ };+ let target = self.targets.iter().fold(1f32, |m, t| m.min(*t));+ if target < self.gain {+ self.gain = target;+ self.working += 1.0;+ } else {+ // Adaptive: up to four times slower after a long, hard stretch.+ let busy = (self.working / self.rate).min(1.0) * adaptive;+ let back = follow(release_ms * (1.0 + 3.0 * busy), self.rate);+ self.gain = target + (self.gain - target) * back;+ self.working = (self.working - 4.0).max(0.0);+ }+ let g = self.gain * makeup * push;+ let at = self.at;+ for (c, ch) in channels.iter_mut().enumerate() {+ let line = &mut self.lines[c];+ line[at] = ch[i];+ ch[i] = clip(line[(at + 1) % room] * g, shape) * output;+ }+ self.at = (at + 1) % room;+ }+ }++ fn latency(&self) -> usize {+ self.ahead()+ }+}++/// Tremolo Pan: an oscillator a side (the right one moved on by the phase,+/// half a round at 100 %), its corners softened by a one-pole follower,+/// shaped from a sine toward a square by a rational curve and rounded by+/// a gentle saturation; each side's level 1 − depth + depth·the oscillator+/// (at full depth the trough turns the sound over).+#[derive(Debug)]+pub(crate) struct TremoloPan {+ rate: f32,+ params: Vec<f32>,+ tempo: bv_timeline::Tempo,+ phase: f64,+ smooth: [f32; 2],+}++impl TremoloPan {+ pub(crate) fn new(rate: u32) -> TremoloPan {+ TremoloPan {+ rate: rate.max(1) as f32,+ params: Vec::new(),+ tempo: bv_timeline::Tempo::default(),+ phase: 0.0,+ smooth: [0.0; 2],+ }+ }++ fn p(&self, i: usize) -> f32 {+ let s = &et::PARAMS[i];+ self.params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+ }+}++impl Own for TremoloPan {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ }++ fn keep_time(&mut self, tempo: &bv_timeline::Tempo) {+ self.tempo = *tempo;+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let input = db(self.p(et::INPUT));+ let output = db(self.p(et::OUTPUT));+ let hz = if self.p(et::SYNC) >= 0.5 {+ 1.0 / bv_timeline::audio_fx::tempo::seconds(self.p(et::NOTE), &self.tempo)+ } else {+ self.p(et::RATE) as f64+ };+ let step = hz / self.rate as f64;+ let offset = 0.5 * self.p(et::PHASE) as f64;+ let kappa = 1.0 - 1.0 / (0.49 * self.p(et::SHAPE) + 0.5);+ let depth = self.p(et::DEPTH);+ // The corners softened over about a fiftieth of a round.+ let soften = 1.0+ - (-std::f32::consts::TAU * (hz as f32 * 50.0).min(self.rate / 4.0) / self.rate).exp();+ let start = self.phase;+ for (c, ch) in channels.iter_mut().enumerate() {+ let side = c.min(1);+ let mut phase = start + if side == 1 { offset } else { 0.0 };+ let s = &mut self.smooth[side];+ for x in ch.iter_mut() {+ let sine = (std::f64::consts::TAU * phase).sin() as f32;+ *s += (sine - *s) * soften;+ let a = s.abs();+ let g = s.signum() * a / ((a - 1.0) * kappa + a).max(1e-9);+ let g = (0.87 * g).clamp(-1.0, 1.0);+ let g = ((2.0 - g.abs()) * g).clamp(-1.0, 1.0);+ *x *= input * (1.0 - depth + depth * g) * output;+ phase += step;+ }+ }+ self.phase = (start + step * n as f64).fract();+ }+}++/// Tube Stage: the pre EQ (a tilt around 80 Hz), then one or two triode+/// stages — the grid resting halfway up the plate's curve, less a little+/// of its own low-passed output (the cathode), the curve cut off below 0+/// and saturated past 1, the coupling's DC taken away — driven by the+/// gain (class AB a little straighter), then the post EQ (a tilt around+/// 350 Hz); twice the rate inside when oversampling.+#[derive(Debug)]+pub(crate) struct TubeStage {+ rate: f32,+ params: Vec<f32>,+ /// Each channel's: two stages' cathode and coupling memories, the+ /// EQs' memories, and the last input (for oversampling).+ state: Vec<([f32; 4], [[f32; 4]; 2], f32)>,+ pre: Section,+ post: Section,+}++impl TubeStage {+ pub(crate) fn new(rate: u32) -> TubeStage {+ TubeStage {+ rate: rate.max(1) as f32,+ params: Vec::new(),+ state: Vec::new(),+ pre: Section::default(),+ post: Section::default(),+ }+ }++ fn p(&self, i: usize) -> f32 {+ let s = &tu::PARAMS[i];+ self.params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+ }+}++/// The plate's current at grid voltage `v`: none below 0, `v³·(2 − v³)`+/// up to 1, all of it past 1.+fn plate(v: f32) -> f32 {+ let v = v.clamp(0.0, 1.0);+ let c = v * v * v;+ c * (2.0 - c)+}++/// Where the grid rests (its bias) on the plate's curve.+const REST: f32 = 0.5;++/// One triode stage at sampling rate `fs`: `x` in, its cathode and+/// coupling memories in `m`; small sounds come out as loud as they went+/// in, louder ones bend on the curve.+fn triode(x: f32, drive: f32, soft: f32, m: &mut [f32], fs: f32) -> f32 {+ let cathode = 1.0 - (-std::f32::consts::TAU * 20.0 / fs).exp();+ let coupling = 1.0 - (-std::f32::consts::TAU * 10.0 / fs).exp();+ let curve = |v: f32| plate(v) * (1.0 - soft) + v.clamp(0.0, 1.0) * soft;+ // The curve's slope at rest: 3v²·(2 − 2v³), and 1 where straight.+ let slope = 3.0 * REST * REST * (2.0 - 2.0 * REST.powi(3)) * (1.0 - soft) + soft;+ let grid = REST + 0.5 * (x * drive - m[0]);+ let y = (curve(grid) - curve(REST)) / (0.5 * slope);+ m[0] += (y * 0.05 - m[0]) * cathode;+ m[1] += (y - m[1]) * coupling;+ y - m[1]+}++impl Own for TubeStage {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ let fs = self.rate as f64;+ // The EQs: −1 to 1 a tilt of ±6 dB around their frequencies.+ self.pre = Section::shelf(80.0, -6.0 * self.p(tu::PRE_EQ) as f64, false, fs);+ self.post = Section::shelf(350.0, 6.0 * self.p(tu::POST_EQ) as f64, true, fs);+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ self.state+ .resize(channels.len(), ([0.0; 4], [[0.0; 4]; 2], 0.0));+ let input = db(self.p(tu::INPUT));+ let output = db(self.p(tu::OUTPUT));+ let drive = db(self.p(tu::DRIVE));+ let stages = self.p(tu::STAGES).round().clamp(1.0, 2.0) as usize;+ let soft = if self.p(tu::CLASS) >= 0.5 { 0.18 } else { 0.0 };+ let over = self.p(tu::OVERSAMPLE) >= 0.5;+ let fs = if over { 2.0 * self.rate } else { self.rate };+ for (ch, (tubes, eqs, last)) in channels.iter_mut().zip(self.state.iter_mut()) {+ for x in ch.iter_mut() {+ let v = self.pre.run(*x * input, &mut eqs[0]);+ let mut run = |v: f32| {+ let mut y = v;+ for s in 0..stages {+ y = triode(+ y,+ if s == 0 { drive } else { 1.0 },+ soft,+ &mut tubes[2 * s..2 * s + 2],+ fs,+ );+ }+ y+ };+ let y = if over {+ // Twice the rate: halfway from the last input, then the+ // input, averaged back down.+ let half = run((*last + v) / 2.0);+ let full = run(v);+ (half + full) / 2.0+ } else {+ run(v)+ };+ *last = v;+ *x = self.post.run(y, &mut eqs[1]) * output;+ }+ }+ }+}++/// Vocal Strip: a voice's chain — a high-pass at its frequency; a gate+/// that turns the sound well down (24 dB) below its threshold (off at its+/// lowest); the de-esser's band at its frequency, turned down by up to+/// its amount where it stands out; a compressor whose amount sets both+/// how far it squeezes (the threshold comes down by half the amount, at+/// 4:1) and, with auto makeup, how much it gives back, its release slower+/// as the adaptive setting rises; and a tilt of ±6 dB around 1 kHz.+#[derive(Debug)]+pub(crate) struct VocalStrip {+ rate: f32,+ params: Vec<f32>,+ high_pass: Section,+ band: Section,+ tilt: [Section; 2],+ /// Each channel's filters' memories: high-pass, band, tilt low, tilt+ /// high.+ memory: Vec<[[f32; 4]; 4]>,+ gate: f32,+ gate_gain: f32,+ levels: [f32; 2],+ comp: f32,+ /// One sample's de-esser band on each channel.+ bands: Vec<f32>,+}++impl VocalStrip {+ pub(crate) fn new(rate: u32) -> VocalStrip {+ VocalStrip {+ rate: rate.max(1) as f32,+ params: Vec::new(),+ high_pass: Section::default(),+ band: Section::default(),+ tilt: [Section::default(); 2],+ memory: Vec::new(),+ gate: 0.0,+ gate_gain: 1.0,+ levels: [0.0; 2],+ comp: 0.0,+ bands: Vec::new(),+ }+ }++ fn p(&self, i: usize) -> f32 {+ let s = &ev::PARAMS[i];+ self.params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+ }+}++impl Own for VocalStrip {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ let fs = self.rate as f64;+ self.high_pass = Section::pass(self.p(ev::HIGH_PASS) as f64, true, fs);+ self.band = Section::band(self.p(ev::DEESS_FREQUENCY) as f64, 1.5, fs);+ let tone = 6.0 * self.p(ev::TONE) as f64;+ self.tilt = [+ Section::shelf(1000.0, -tone / 2.0, false, fs),+ Section::shelf(1000.0, tone / 2.0, true, fs),+ ];+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ self.memory.resize(channels.len(), [[0.0; 4]; 4]);+ let fs = self.rate;+ let input = db(self.p(ev::INPUT));+ let output = db(self.p(ev::OUTPUT));+ let gate_at = self.p(ev::GATE);+ let gate_on = gate_at > -90.0;+ let gate_at = db(gate_at);+ let deess = self.p(ev::DEESSER);+ let amount = self.p(ev::COMPRESSION);+ let threshold = db(-amount / 2.0);+ let makeup = if self.p(ev::MAKEUP) >= 0.5 {+ db(amount / 2.0 * 0.75 * 0.7)+ } else {+ 1.0+ };+ let attack = follow(self.p(ev::ATTACK), fs);+ let release = follow(80.0 * (1.0 + self.p(ev::ADAPTIVE) / 2.0), fs);+ let (gate_up, gate_down) = (follow(1.0, fs), follow(100.0, fs));+ let (band_up, band_down) = (follow(1.0, fs), follow(60.0, fs));+ self.bands.resize(channels.len(), 0.0);+ for i in 0..n {+ let (mut peak, mut band_peak) = (0f32, 0f32);+ for (c, ch) in channels.iter_mut().enumerate() {+ let m = &mut self.memory[c];+ let x = self.high_pass.run(ch[i] * input, &mut m[0]);+ let b = self.band.run(x, &mut m[1]);+ self.bands[c] = b;+ ch[i] = x;+ peak = peak.max(x.abs());+ band_peak = band_peak.max(b.abs());+ }+ // The gate.+ let c = if peak > self.gate { gate_up } else { gate_down };+ self.gate = peak + (self.gate - peak) * c;+ let gate_target = if !gate_on || self.gate >= gate_at {+ 1.0+ } else {+ db(-24.0)+ };+ let c = if gate_target > self.gate_gain {+ gate_up+ } else {+ gate_down+ };+ self.gate_gain = gate_target + (self.gate_gain - gate_target) * c;+ // The de-esser.+ for (level, now) in self.levels.iter_mut().zip([band_peak, peak]) {+ let c = if now > *level { band_up } else { band_down };+ *level = (now + (*level - now) * c + FLUSH) - FLUSH;+ }+ let share = (self.levels[0] / self.levels[1].max(1e-9)).min(1.0);+ let m = (2.0 * share).min(1.0);+ let cut = db(-(2.0 - m) * m * deess) - 1.0;+ // The compressor, on the gated, de-essed level.+ let level = peak * self.gate_gain;+ let c = if level > self.comp { attack } else { release };+ self.comp = (level + (self.comp - level) * c + FLUSH) - FLUSH;+ let squeeze = if amount > 0.0 && self.comp > threshold {+ (self.comp / threshold).powf(0.25 - 1.0)+ } else {+ 1.0+ };+ let g = self.gate_gain * squeeze * makeup * output;+ for (c, ch) in channels.iter_mut().enumerate() {+ let m = &mut self.memory[c];+ let x = (ch[i] + cut * self.bands[c]) * g;+ let low = self.tilt[0].run(x, &mut m[2]);+ ch[i] = self.tilt[1].run(low, &mut m[3]);+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn with(specs: &[bv_timeline::ParamSpec], values: &[(usize, f32)]) -> Vec<f32> {+ let mut p: Vec<f32> = specs.iter().map(|s| s.default).collect();+ for &(i, v) in values {+ p[i] = v;+ }+ p+ }++ fn sine(hz: f32, level: f32, n: usize) -> Vec<f32> {+ (0..n)+ .map(|i| level * (std::f32::consts::TAU * hz * i as f32 / 48_000.0).sin())+ .collect()+ }++ /// The level (dB) of the second half of `fx`'s output for a sine.+ fn level(fx: &mut dyn Own, hz: f32, amp: f32) -> f32 {+ let mut ch = vec![sine(hz, amp, 48_000), sine(hz, amp, 48_000)];+ fx.process(&mut ch);+ let tail = &ch[0][24_000..];+ 10.0 * (2.0 * tail.iter().map(|s| s * s).sum::<f32>() / tail.len() as f32).log10()+ }++ #[test]+ fn the_gate_lowers_quiet_sound_by_its_range() {+ let mut g = Gate::new(48_000);+ g.set(&with(+ eg::PARAMS,+ &[+ (eg::THRESHOLD, -30.0),+ (eg::RANGE, 20.0),+ (eg::RELEASE, 10.0),+ ],+ ));+ let quiet = level(&mut g, 1000.0, 0.01);+ assert!((quiet - (-40.0 - 20.0)).abs() < 1.0, "{quiet}");+ let mut g = Gate::new(48_000);+ g.set(&with(+ eg::PARAMS,+ &[(eg::THRESHOLD, -30.0), (eg::RANGE, 20.0)],+ ));+ let loud = level(&mut g, 1000.0, 0.5);+ assert!((loud - 20.0 * 0.5f32.log10()).abs() < 0.5, "{loud}");+ }++ #[test]+ fn the_deesser_turns_down_its_band_only() {+ let mut d = DeEsser::new(48_000);+ d.set(&with(ed::PARAMS, &[(ed::REDUCTION, 12.0)]));+ let hiss = level(&mut d, 7000.0, 0.5);+ assert!(hiss < 20.0 * 0.5f32.log10() - 6.0, "{hiss}");+ let mut d = DeEsser::new(48_000);+ d.set(&with(ed::PARAMS, &[(ed::REDUCTION, 12.0)]));+ let low = level(&mut d, 200.0, 0.5);+ assert!((low - 20.0 * 0.5f32.log10()).abs() < 1.0, "{low}");+ }++ #[test]+ fn the_limiter_holds_its_threshold() {+ let mut l = Limiter::new(48_000);+ l.set(&with(+ el::PARAMS,+ &[(el::THRESHOLD, -12.0), (el::MAKEUP, 0.0), (el::OUTPUT, 0.0)],+ ));+ let mut ch = vec![sine(200.0, 1.0, 48_000)];+ l.process(&mut ch);+ let peak = ch[0][24_000..].iter().fold(0f32, |m, s| m.max(s.abs()));+ assert!(peak <= 0.99 * 10f32.powf(-12.0 / 20.0) + 1e-3, "{peak}");+ assert!(peak > 0.2, "{peak}");+ }++ #[test]+ fn tremolo_moves_the_level_and_tube_stage_starts_clean() {+ let mut t = TremoloPan::new(48_000);+ t.set(&with(et::PARAMS, &[(et::RATE, 2.0), (et::DEPTH, 0.5)]));+ let mut ch = vec![vec![1.0f32; 48_000]];+ t.process(&mut ch);+ let (lo, hi) = ch[0]+ .iter()+ .fold((f32::MAX, f32::MIN), |(a, b), s| (a.min(*s), b.max(*s)));+ assert!(lo < 0.2 && hi > 0.8, "{lo} {hi}");+ // Tube Stage at its defaults: a quiet tone comes out about as loud.+ let mut s = TubeStage::new(48_000);+ s.set(&with(tu::PARAMS, &[]));+ let out = level(&mut s, 1000.0, 0.01);+ assert!((out + 40.0).abs() < 1.5, "{out}");+ }++ #[test]+ fn vocal_strip_at_its_defaults_leaves_a_voice_alone() {+ let mut v = VocalStrip::new(48_000);+ v.set(&with(ev::PARAMS, &[]));+ let out = level(&mut v, 300.0, 0.3);+ assert!((out - 20.0 * 0.3f32.log10()).abs() < 0.5, "{out}");+ }+}diff --git a/crates/mixer/src/fx/studio2.rs b/crates/mixer/src/fx/studio2.rsnew file mode 100644index 0000000..a51fc2e--- /dev/null+++ b/crates/mixer/src/fx/studio2.rs@@ -0,0 +1,766 @@+//! BananaV's versions of the rest of the studio set: Compressor, Phaser,+//! Chorus/Flanger, Studio Reverb and Stereo Delay, built from what their+//! controls do.++use bv_timeline::Tempo;+use bv_timeline::audio_fx::{+ efx_chorus_flanger as ec, efx_compressor as ek, efx_phaser as ep, efx_reverb as er,+ efx_stereo_delay as es, tempo,+};++use super::Own;+use super::eq::Section;++/// Added and taken away again on fed-back state, so a fading signal ends+/// at 0 instead of lingering as a denormal number.+const FLUSH: f32 = 1e-18;++fn db(v: f32) -> f32 {+ 10f32.powf(v / 20.0)+}++/// A one-pole follower's coefficient for a time in milliseconds.+fn follow(ms: f32, fs: f32) -> f32 {+ let n = ms / 1000.0 * fs;+ if n < 1.0 { 0.0 } else { (-1.0 / n).exp() }+}++/// A one-pole low-pass's coefficient for a frequency.+fn one_pole(hz: f32, fs: f32) -> f32 {+ 1.0 - (-std::f32::consts::TAU * hz.min(fs * 0.49) / fs).exp()+}++/// `(2 − |v|)·v` held within ±1: a gentle parabolic saturation.+fn soft(v: f32) -> f32 {+ let v = v.clamp(-1.0, 1.0);+ (2.0 - v.abs()) * v+}++/// The oscillator's shape: a sine with a straighter middle.+fn lfo_shape(s: f32) -> f32 {+ 0.33 * s.powi(7) + 0.67 * s+}++/// A value of `params` in range, its default when missing.+fn value(params: &[f32], specs: &[bv_timeline::ParamSpec], i: usize) -> f32 {+ let s = &specs[i];+ params+ .get(i)+ .copied()+ .unwrap_or(s.default)+ .clamp(s.min, s.max)+}++/// A delay line read between its samples.+#[derive(Clone, Debug)]+struct Line {+ buf: Vec<f32>,+ mask: usize,+ at: usize,+}++impl Line {+ fn new(len: usize) -> Line {+ let n = len.max(4).next_power_of_two();+ Line {+ buf: vec![0.0; n],+ mask: n - 1,+ at: 0,+ }+ }++ /// The sound `d` samples back (1 the newest), between samples.+ fn read(&self, d: f32) -> f32 {+ let d = d.clamp(1.0, (self.buf.len() - 2) as f32);+ let whole = d.floor();+ let part = d - whole;+ let i = whole as usize;+ let a = self.buf[(self.at + self.buf.len() - (i - 1)) & self.mask];+ let b = self.buf[(self.at + self.buf.len() - i) & self.mask];+ a + (b - a) * part+ }++ fn write(&mut self, x: f32) {+ self.at = (self.at + 1) & self.mask;+ self.buf[self.at] = x;+ }+}++/// Compressor: the side chain (the sound, filtered when asked) read+/// after the gain already applied — a feedback compressor, as the classic+/// FET designs — its level followed by the attack and three releases (the+/// adaptive setting spreading them: a short burst lets go fast, a long+/// passage slowly); above the threshold the gain comes down by the ratio+/// over a 6 dB knee; auto makeup gives back half of what it takes at full+/// scale; the mix blends in the untouched sound (parallel compression);+/// the soft clip rounds off what goes past full scale.+#[derive(Debug)]+pub(crate) struct Compressor {+ rate: f32,+ params: Vec<f32>,+ side: Option<Section>,+ memory: Vec<[f32; 4]>,+ /// The attack follower and the three release followers.+ levels: [f32; 3],+ gain: f32,+}++impl Compressor {+ pub(crate) fn new(rate: u32) -> Compressor {+ Compressor {+ rate: rate.max(1) as f32,+ params: Vec::new(),+ side: None,+ memory: Vec::new(),+ levels: [0.0; 3],+ gain: 1.0,+ }+ }++ fn p(&self, i: usize) -> f32 {+ value(&self.params, ek::PARAMS, i)+ }+}++impl Own for Compressor {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ let fs = self.rate as f64;+ let hz = self.p(ek::FILTER) as f64;+ self.side = match self.p(ek::FILTER_TYPE).round() as i32 {+ 1 => Some(Section::pass(hz, true, fs)),+ 2 => Some(Section::band(hz, 1.0, fs)),+ 3 => Some(Section::pass(hz, false, fs)),+ _ => None,+ };+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ self.memory.resize(channels.len(), [0.0; 4]);+ let fs = self.rate;+ let input = self.p(ek::INPUT);+ let output = db(self.p(ek::OUTPUT));+ let threshold = self.p(ek::THRESHOLD);+ let slope = 1.0 / self.p(ek::RATIO) - 1.0;+ let makeup = if self.p(ek::MAKEUP) >= 0.5 {+ db(-threshold * -slope / 2.0)+ } else {+ 1.0+ };+ let attack = follow(self.p(ek::ATTACK), fs);+ let release = self.p(ek::RELEASE);+ let spread = 1.0 + self.p(ek::ADAPTIVE);+ let releases = [+ follow(release / spread, fs),+ follow(release, fs),+ follow(release * spread, fs),+ ];+ let mix = self.p(ek::MIX);+ let clip = self.p(ek::SOFT_CLIP) >= 0.5;+ let listen = self.p(ek::LISTEN) >= 0.5;+ for i in 0..n {+ let mut peak = 0f32;+ for (c, ch) in channels.iter_mut().enumerate() {+ let x = ch[i] * input;+ ch[i] = x;+ let s = match &self.side {+ Some(f) => f.run(x, &mut self.memory[c]),+ None => x,+ };+ if listen {+ ch[i] = s;+ }+ peak = peak.max(s.abs());+ }+ // Read after the gain: the feedback.+ let seen = peak * self.gain;+ for (level, rel) in self.levels.iter_mut().zip(releases) {+ let c = if seen > *level { attack } else { rel };+ *level = (seen + (*level - seen) * c + FLUSH) - FLUSH;+ }+ let e = self.levels.iter().fold(0f32, |m, l| m.max(*l));+ let over = 20.0 * e.max(1e-9).log10() - threshold;+ let cut = if over <= -3.0 {+ 0.0+ } else if over < 3.0 {+ slope * (over + 3.0).powi(2) / 12.0+ } else {+ slope * over+ };+ // The gain read off the level after it (the feedback): it+ // settles where that level sits on the curve.+ self.gain = db(cut).min(1.0);+ for ch in channels.iter_mut() {+ if listen {+ continue;+ }+ let x = ch[i];+ let mut y = mix * x * self.gain * makeup + (1.0 - mix) * x;+ if clip {+ let v = y.clamp(-1.0, 1.0);+ y = 1.5 * (v - v * v * v / 3.0) * 0.98855;+ }+ ch[i] = y * output;+ }+ }+ }+}++/// Phaser: an oscillator a side (the right one moved on by the phase+/// offset), shaped straighter in its middle, sweeps 4, 8 or 12 first-order+/// all-pass stages up and down from the centre frequency (by up to eleven+/// times each way at full depth); what comes out of them, its lows and+/// highs trimmed, goes back in by the feedback; the stages' sound (its DC+/// taken away) is mixed with the sound itself, and the notches appear+/// where the two cancel.+#[derive(Debug)]+pub(crate) struct Phaser {+ rate: f32,+ params: Vec<f32>,+ phase: f64,+ /// Each channel: the stages' memories (input, output), the feedback's+ /// two low-passes, the DC blocker, the last chain output.+ state: Vec<(Vec<[f32; 2]>, [f32; 3], f32)>,+}++impl Phaser {+ pub(crate) fn new(rate: u32) -> Phaser {+ Phaser {+ rate: rate.max(1) as f32,+ params: Vec::new(),+ phase: 0.0,+ state: Vec::new(),+ }+ }++ fn p(&self, i: usize) -> f32 {+ value(&self.params, ep::PARAMS, i)+ }+}++impl Own for Phaser {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let fs = self.rate;+ let stages = [4, 8, 12][self.p(ep::MODE).round().clamp(0.0, 2.0) as usize];+ if self.state.len() != channels.len()+ || self.state.first().map_or(0, |s| s.0.len()) != stages+ {+ self.state = vec![(vec![[0.0; 2]; stages], [0.0; 3], 0.0); channels.len()];+ }+ let input = self.p(ep::INPUT);+ let output = self.p(ep::OUTPUT);+ let step = self.p(ep::RATE) as f64 / fs as f64;+ let depth = self.p(ep::DEPTH);+ let offset = self.p(ep::PHASE) as f64 * 0.5;+ let feedback = self.p(ep::FEEDBACK);+ let centre = self.p(ep::CENTER);+ let mix = self.p(ep::MIX);+ let (lp1, lp2, dc) = (one_pole(5000.0, fs), one_pole(50.0, fs), one_pole(20.0, fs));+ let start = self.phase;+ for (c, ch) in channels.iter_mut().enumerate() {+ let side = if c % 2 == 1 { offset } else { 0.0 };+ let (chain, filters, last) = &mut self.state[c];+ let mut a = 0.0;+ for (i, x) in ch.iter_mut().enumerate() {+ // The sweep, worked out every 16 samples.+ if i % 16 == 0 {+ let t = start + side + step * i as f64;+ let s = (std::f64::consts::TAU * t).sin() as f32;+ let v = lfo_shape(s);+ let e = 10.0 * depth * v.abs();+ let f = if v >= 0.0 {+ centre * (1.0 + e)+ } else {+ centre / (1.0 + e)+ };+ let t = (std::f32::consts::PI * f.clamp(0.1, fs * 0.49) / fs).tan();+ a = (t - 1.0) / (t + 1.0);+ }+ let dry = *x * input;+ filters[0] += (*last - filters[0]) * lp1;+ filters[1] += (filters[0] - filters[1]) * lp2;+ let back = filters[0] - filters[1];+ let mut u = soft((feedback * back + 0.25 * dry) / 2.0);+ for st in chain.iter_mut() {+ let y = a * u + st[0] - a * st[1];+ st[0] = u;+ st[1] = (y + FLUSH) - FLUSH;+ u = st[1];+ }+ *last = u;+ filters[2] += (u - filters[2]) * dc;+ let wet = 4.0 * (u - filters[2]);+ *x = (mix * wet + (1.0 - mix) * dry) * output;+ }+ }+ self.phase = (start + step * n as f64).fract();+ }+}++/// Chorus/Flanger: three voices a side, each a delay line read at a time+/// its own oscillator swings (the voices a third of a round apart, the+/// right side moved on by the phase offset); a chorus sits around 7 ms, a+/// flanger near 0.5 ms, an ensemble wider around 10 ms. Each voice feeds+/// back on itself (rounded off), the voices' sum has its lows cut, and+/// the mix blends it with the sound.+#[derive(Debug)]+pub(crate) struct ChorusFlanger {+ rate: f32,+ params: Vec<f32>,+ phase: f64,+ /// Each channel's three lines, their smoothed delays, and the low cut's+ /// memory.+ voices: Vec<([Line; 3], [f32; 3], f32)>,+}++impl ChorusFlanger {+ pub(crate) fn new(rate: u32) -> ChorusFlanger {+ ChorusFlanger {+ rate: rate.max(1) as f32,+ params: Vec::new(),+ phase: 0.0,+ voices: Vec::new(),+ }+ }++ fn p(&self, i: usize) -> f32 {+ value(&self.params, ec::PARAMS, i)+ }+}++impl Own for ChorusFlanger {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let fs = self.rate;+ let room = (0.05 * fs) as usize;+ if self.voices.len() != channels.len() {+ let line = Line::new(room);+ self.voices = vec![([line.clone(), line.clone(), line], [1.0; 3], 0.0); channels.len()];+ }+ // Each mode's middle and swing, in milliseconds.+ let (base, swing) = [(7.0, 5.0), (0.5, 4.0), (10.0, 8.0)]+ [self.p(ec::MODE).round().clamp(0.0, 2.0) as usize];+ let input = self.p(ec::INPUT);+ let output = self.p(ec::OUTPUT);+ let step = self.p(ec::RATE) as f64 / fs as f64;+ let depth = self.p(ec::DEPTH);+ let offset = self.p(ec::PHASE) as f64 * 0.5;+ let feedback = self.p(ec::FEEDBACK);+ let cut = one_pole(self.p(ec::LOW_CUT), fs);+ let mix = self.p(ec::MIX);+ let (wet_gain, dry_gain) = (+ (mix * std::f32::consts::FRAC_PI_2).sin(),+ (mix * std::f32::consts::FRAC_PI_2).cos(),+ );+ let glide = one_pole(30.0, fs);+ let start = self.phase;+ for (c, ch) in channels.iter_mut().enumerate() {+ let side = if c % 2 == 1 { offset } else { 0.0 };+ let (lines, delays, low) = &mut self.voices[c];+ for (i, x) in ch.iter_mut().enumerate() {+ let dry = *x * input;+ let mut sum = 0.0;+ for (k, (line, d)) in lines.iter_mut().zip(delays.iter_mut()).enumerate() {+ let t = start + side + k as f64 / 3.0 + step * i as f64;+ let v = (lfo_shape((std::f64::consts::TAU * t).sin() as f32) + 1.0) / 2.0;+ // Toward the top of the swing more slowly than a sine.+ let r = v / (v - 2.0303 * (v - 1.0));+ let target = ((r * depth * swing + base) * fs / 1000.0).max(1.0);+ *d += (target - *d) * glide;+ let late = line.read(*d);+ line.write((soft((dry + feedback * late) / 2.0) * 2.0 + FLUSH) - FLUSH);+ sum += late;+ }+ let wet = sum / 3.0;+ *low += (wet - *low) * cut;+ *x = (wet_gain * (wet - *low) + dry_gain * dry) * output;+ }+ }+ self.phase = (start + step * n as f64).fract();+ }+}++/// Studio Reverb: the sound (its lows cut, after the pre-delay) through+/// four diffusers, then a tank of two loops — each a modulated diffuser,+/// a delay, a damping low-pass and a decaying diffuser, feeding the other+/// — tapped at several points for the left and the right; the mode sets+/// the tank's size and brightness (plate, room, hall, vintage plate), the+/// time how long it rings, the modulation how much the loops drift.+#[derive(Debug)]+pub(crate) struct StudioReverb {+ rate: f32,+ params: Vec<f32>,+ pre: Line,+ diffusers: Vec<Line>,+ tank: Vec<Line>,+ low: f32,+ damp: [f32; 2],+ phase: f64,+ scale: f32,+}++/// The diffusers' and the tank's lengths at 29.8 kHz (ms × 29.8): the+/// published plate topology's proportions, scaled by the rate and size.+const DIFFUSE: [f32; 4] = [142.0, 107.0, 379.0, 277.0];+const TANK: [f32; 8] = [672.0, 4453.0, 1800.0, 3720.0, 908.0, 4217.0, 2656.0, 3163.0];++impl StudioReverb {+ pub(crate) fn new(rate: u32) -> StudioReverb {+ StudioReverb {+ rate: rate.max(1) as f32,+ params: Vec::new(),+ pre: Line::new(1),+ diffusers: Vec::new(),+ tank: Vec::new(),+ low: 0.0,+ damp: [0.0; 2],+ phase: 0.0,+ scale: 0.0,+ }+ }++ fn p(&self, i: usize) -> f32 {+ value(&self.params, er::PARAMS, i)+ }+}++/// A diffuser (an all-pass on a line): `x` in with gain `g`, `d` samples.+fn diffuse(line: &mut Line, x: f32, g: f32, d: f32) -> f32 {+ let late = line.read(d);+ let v = x - g * late;+ line.write((v + FLUSH) - FLUSH);+ late + g * v+}++impl Own for StudioReverb {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ let mode = self.p(er::MODE).round() as usize;+ let room = [1.0, 0.6, 1.6, 1.2][mode.min(3)];+ let scale = self.rate / 29_800.0 * room * (0.3 + 1.2 * self.p(er::SIZE));+ if (scale - self.scale).abs() > 1e-6 {+ self.scale = scale;+ self.diffusers = DIFFUSE+ .iter()+ .map(|l| Line::new((l * scale) as usize + 8))+ .collect();+ self.tank = TANK+ .iter()+ .map(|l| Line::new((l * scale) as usize + 100))+ .collect();+ self.pre = Line::new((0.26 * self.rate) as usize);+ }+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let count = channels.len();+ if count == 0 {+ return;+ }+ let fs = self.rate;+ let s = self.scale;+ let input = self.p(er::INPUT);+ let output = self.p(er::OUTPUT);+ let mix = self.p(er::MIX);+ let decay = 0.2 + 0.78 * self.p(er::TIME);+ let u = (1.0 - self.p(er::DAMPING)).clamp(0.0001, 0.99999);+ let fc = 20_000.0 * u / (u - 1.2222 * (u - 1.0)) + 500.0;+ let damp = one_pole(fc, fs);+ let diffusion = self.p(er::DIFFUSION);+ let (g1, g2) = (0.75 * diffusion, 0.625 * diffusion);+ let swing = 16.0 * self.p(er::MODULATION) * s;+ let pre = (self.p(er::PREDELAY) / 1000.0 * fs).max(1.0);+ let cut = one_pole(self.p(er::LOW_CUT), fs);+ let step = 1.0 / fs as f64;+ for i in 0..n {+ let x = channels.iter().map(|c| c[i]).sum::<f32>() / count as f32 * input;+ self.pre.write(x);+ let mut v = self.pre.read(pre);+ self.low += (v - self.low) * cut;+ v -= self.low;+ for (k, line) in self.diffusers.iter_mut().enumerate() {+ v = diffuse(line, v, if k < 2 { g1 } else { g2 }, DIFFUSE[k] * s);+ }+ let wobble = (std::f64::consts::TAU * self.phase).sin() as f32 * swing;+ self.phase = (self.phase + step).fract();+ // The two loops, each fed by the other's end.+ for side in 0..2 {+ let other = self.tank[if side == 0 { 7 } else { 3 }]+ .read(TANK[if side == 0 { 7 } else { 3 }] * s);+ let into = v + decay * other;+ let base = 4 * side;+ let a = diffuse(&mut self.tank[base], into, -0.7, TANK[base] * s + wobble);+ self.tank[base + 1].write(a);+ let b = self.tank[base + 1].read(TANK[base + 1] * s);+ self.damp[side] += (b - self.damp[side]) * damp;+ let c = diffuse(+ &mut self.tank[base + 2],+ self.damp[side] * decay,+ 0.5,+ TANK[base + 2] * s,+ );+ self.tank[base + 3].write(c);+ }+ // Taps across both loops for each side.+ let t = |k: usize, f: f32| self.tank[k].read(TANK[k] * s * f);+ let left = 0.6+ * (t(5, 0.06) + t(5, 0.68) - t(6, 0.48) + t(7, 0.47)+ - t(1, 0.47)+ - t(2, 0.04)+ - t(3, 0.27));+ let right = 0.6+ * (t(1, 0.08) + t(1, 0.61) - t(2, 0.66) + t(3, 0.89)+ - t(5, 0.47)+ - t(6, 0.07)+ - t(7, 0.08));+ for (c, ch) in channels.iter_mut().enumerate() {+ let wet = if count == 1 {+ (left + right) / 2.0+ } else if c % 2 == 0 {+ left+ } else {+ right+ };+ ch[i] = (mix * wet + (1.0 - mix) * ch[i] * input) * output;+ }+ }+ }+}++/// Stereo Delay: each side's delay in milliseconds or a note of the+/// tempo, its time gliding when changed; the echo fed back through the+/// damping (a low-pass from 18 kHz down to 1 kHz) and the low cut. Analog+/// darkens the line and rounds it off; the bucket brigade narrows its band+/// by its stages, squeezes before the line and opens after it (the+/// compander), lets its clock drift and adds its noise. The mix blends+/// the echoes with the sound.+#[derive(Debug)]+pub(crate) struct StereoDelay {+ rate: f32,+ params: Vec<f32>,+ tempo: Tempo,+ lines: Vec<Line>,+ /// Each side's gliding delay, its loop's low-pass and low cut, and+ /// its band limit's memory.+ state: Vec<[f32; 4]>,+ drift: f64,+ noise: u32,+}++impl StereoDelay {+ pub(crate) fn new(rate: u32) -> StereoDelay {+ StereoDelay {+ rate: rate.max(1) as f32,+ params: Vec::new(),+ tempo: Tempo::default(),+ lines: Vec::new(),+ state: Vec::new(),+ drift: 0.0,+ noise: 0x1234_5678,+ }+ }++ fn p(&self, i: usize) -> f32 {+ value(&self.params, es::PARAMS, i)+ }+}++impl Own for StereoDelay {+ fn set(&mut self, params: &[f32]) {+ self.params = params.to_vec();+ }++ fn keep_time(&mut self, tempo: &Tempo) {+ self.tempo = *tempo;+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let fs = self.rate;+ if self.lines.len() != channels.len() {+ self.lines = vec![Line::new((4.2 * fs) as usize); channels.len()];+ self.state = vec![[0.0; 4]; channels.len()];+ }+ let mode = self.p(es::MODE).round() as i32;+ let input = self.p(es::INPUT);+ let output = self.p(es::OUTPUT);+ let synced = self.p(es::SYNC) >= 0.5;+ let times: [f32; 2] =+ [(es::LEFT, es::LEFT_NOTE), (es::RIGHT, es::RIGHT_NOTE)].map(|(ms, note)| {+ let seconds = if synced {+ tempo::seconds(self.p(note), &self.tempo) as f32+ } else {+ self.p(ms) / 1000.0+ };+ (seconds * fs).clamp(1.0, 4.1 * fs)+ });+ let feedback = self.p(es::FEEDBACK);+ let damp = one_pole(18_000.0 * 0.0556f32.powf(self.p(es::DAMPING)), fs);+ let cut = one_pole(self.p(es::LOW_CUT), fs);+ let mix = self.p(es::MIX);+ let stages = self.p(es::STAGES);+ let band = one_pole(+ if mode == 2 {+ 12_000.0 / stages+ } else {+ 9_000.0+ },+ fs,+ );+ let squeeze = 1.0 + self.p(es::COMPANDER) / 5.0;+ let drift = self.p(es::DRIFT);+ let noise = if mode == 2 {+ db(self.p(es::NOISE))+ } else {+ 0.0+ };+ let glide = one_pole(5.0, fs);+ let start = self.drift;+ for (c, ch) in channels.iter_mut().enumerate() {+ let line = &mut self.lines[c];+ let st = &mut self.state[c];+ let target = times[c % 2];+ if st[0] < 1.0 {+ st[0] = target;+ }+ let mut phase = start;+ for x in ch.iter_mut() {+ let dry = *x * input;+ st[0] += (target - st[0]) * glide;+ let wobble = if mode == 2 {+ 1.0 + 0.01 * drift * (std::f64::consts::TAU * phase).sin() as f32+ } else {+ 1.0+ };+ phase = (phase + 0.7 / fs as f64).fract();+ let mut echo = line.read(st[0] * wobble);+ if mode >= 1 {+ st[3] += (echo - st[3]) * band;+ echo = st[3];+ }+ if mode == 2 {+ // The compander: what was squeezed going in opens out+ // (and the line's noise with it, pushed down).+ echo = echo.signum() * echo.abs().min(1.0).powf(squeeze);+ }+ st[1] += (echo - st[1]) * damp;+ st[2] += (st[1] - st[2]) * cut;+ let back = st[1] - st[2];+ let mut into = dry + feedback * back;+ if mode >= 1 {+ into = soft(into * 0.53) / 0.53;+ }+ if mode == 2 {+ self.noise ^= self.noise << 13;+ self.noise ^= self.noise >> 17;+ self.noise ^= self.noise << 5;+ into = into.signum() * into.abs().min(1.0).powf(squeeze.recip())+ + noise * (self.noise as f32 / u32::MAX as f32 - 0.5);+ }+ line.write((into + FLUSH) - FLUSH);+ *x = (mix * echo + (1.0 - mix) * dry) * output;+ }+ }+ self.drift = (start + 0.7 * n as f64 / fs as f64).fract();+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn with(specs: &[bv_timeline::ParamSpec], values: &[(usize, f32)]) -> Vec<f32> {+ let mut p: Vec<f32> = specs.iter().map(|s| s.default).collect();+ for &(i, v) in values {+ p[i] = v;+ }+ p+ }++ fn sine(hz: f32, level: f32, n: usize) -> Vec<f32> {+ (0..n)+ .map(|i| level * (std::f32::consts::TAU * hz * i as f32 / 48_000.0).sin())+ .collect()+ }++ fn peak(x: &[f32]) -> f32 {+ x.iter().fold(0f32, |m, s| m.max(s.abs()))+ }++ #[test]+ fn the_compressor_squeezes_loud_sound() {+ let mut c = Compressor::new(48_000);+ c.set(&with(+ ek::PARAMS,+ &[(ek::THRESHOLD, -20.0), (ek::RATIO, 10.0)],+ ));+ let mut ch = vec![sine(200.0, 0.9, 48_000)];+ c.process(&mut ch);+ let out = 20.0 * peak(&ch[0][24_000..]).log10();+ assert!(out < -6.0 && out > -20.0, "{out}");+ // Mixed all dry, nothing changes.+ let mut c = Compressor::new(48_000);+ c.set(&with(ek::PARAMS, &[(ek::THRESHOLD, -20.0), (ek::MIX, 0.0)]));+ let x = sine(200.0, 0.5, 4_800);+ let mut ch = vec![x.clone()];+ c.process(&mut ch);+ assert!(ch[0].iter().zip(&x).all(|(a, b)| (a - b).abs() < 1e-5));+ }++ #[test]+ fn the_modulation_effects_stay_bounded_and_change_the_sound() {+ let x = sine(440.0, 0.5, 24_000);+ let mut fx: Vec<Box<dyn Own>> = vec![+ Box::new(Phaser::new(48_000)),+ Box::new(ChorusFlanger::new(48_000)),+ Box::new(StudioReverb::new(48_000)),+ Box::new(StereoDelay::new(48_000)),+ ];+ let specs = [ep::PARAMS, ec::PARAMS, er::PARAMS, es::PARAMS];+ for (f, s) in fx.iter_mut().zip(specs) {+ f.set(&with(s, &[]));+ let mut ch = vec![x.clone(), x.clone()];+ f.process(&mut ch);+ assert!(ch.iter().flatten().all(|v| v.is_finite() && v.abs() < 4.0));+ assert!(ch[0].iter().zip(&x).any(|(a, b)| (a - b).abs() > 1e-3));+ }+ }++ #[test]+ fn the_stereo_delay_echoes_at_its_time() {+ let mut d = StereoDelay::new(48_000);+ d.set(&with(+ es::PARAMS,+ &[+ (es::SYNC, 0.0),+ (es::LEFT, 100.0),+ (es::RIGHT, 100.0),+ (es::MIX, 1.0),+ (es::FEEDBACK, 0.0),+ ],+ ));+ let mut x = vec![vec![0.0f32; 9_600], vec![0.0f32; 9_600]];+ x[0][0] = 1.0;+ d.process(&mut x);+ let at = x[0]+ .iter()+ .enumerate()+ .fold(+ (0, 0f32),+ |(i, m), (k, s)| if s.abs() > m { (k, s.abs()) } else { (i, m) },+ )+ .0;+ assert!((at as i32 - 4_800).abs() <= 2, "{at}");+ }+}diff --git a/crates/mixer/src/fx/utility.rs b/crates/mixer/src/fx/utility.rsnew file mode 100644index 0000000..9762337--- /dev/null+++ b/crates/mixer/src/fx/utility.rs@@ -0,0 +1,146 @@+//! Volume and Pan, as VEGAS's: a linear gain, and a balance that moves+//! one channel into the other (the channels' sum kept).++use bv_timeline::audio_fx::{pan, volume};++use super::{Own, Ramp, gain_ramp};++/// Volume: every sample of every channel times one gain, 0 to 2.+#[derive(Debug)]+pub(crate) struct Volume {+ gain: Ramp,+}++impl Default for Volume {+ fn default() -> Volume {+ Volume {+ gain: Ramp::new(1.0),+ }+ }+}++impl Own for Volume {+ fn set(&mut self, params: &[f32]) {+ self.gain.set(+ params+ .get(volume::GAIN)+ .copied()+ .unwrap_or(1.0)+ .clamp(0.0, 2.0),+ );+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let (start, step) = self.gain.block(n);+ for ch in channels.iter_mut() {+ gain_ramp(ch, start, step);+ }+ }+}++/// Pan: on a stereo pair, `p` from −1 to 1, positive to the left — the+/// left takes `p` of the right and the right keeps 1 − `p` of itself;+/// below 0 the other way round. Other layouts pass as they are.+#[derive(Debug)]+pub(crate) struct Pan {+ pan: Ramp,+}++impl Default for Pan {+ fn default() -> Pan {+ Pan {+ pan: Ramp::new(0.0),+ }+ }+}++impl Own for Pan {+ fn set(&mut self, params: &[f32]) {+ self.pan.set(+ params+ .get(pan::PAN)+ .copied()+ .unwrap_or(0.0)+ .clamp(-1.0, 1.0),+ );+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let n = channels.first().map_or(0, Vec::len);+ let (start, step) = self.pan.block(n);+ let [l, r] = channels else {+ return;+ };+ let n = n.min(l.len()).min(r.len());+ // Each sample's own pan: the ramp's, unrolled into two branch-free+ // lines — max(p, 0) of the right to the left, max(−p, 0) of the+ // left to the right — so the loop vectorizes.+ for i in 0..n {+ let p = start + step * i as f32;+ let to_left = p.max(0.0);+ let to_right = (-p).max(0.0);+ let (a, b) = (l[i], r[i]);+ l[i] = a * (1.0 - to_right) + b * to_left;+ r[i] = b * (1.0 - to_left) + a * to_right;+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn volume_scales_by_its_gain() {+ let mut v = Volume::default();+ v.set(&[0.5]);+ let mut ch = vec![vec![1.0f32; 8], vec![-0.5; 8]];+ v.process(&mut ch);+ assert!(ch[0].iter().all(|&s| (s - 0.5).abs() < 1e-6));+ assert!(ch[1].iter().all(|&s| (s + 0.25).abs() < 1e-6));+ }++ #[test]+ fn volume_ramps_to_a_new_gain_without_a_jump() {+ let mut v = Volume::default();+ v.set(&[1.0]);+ let mut ch = vec![vec![1.0f32; 4]];+ v.process(&mut ch);+ v.set(&[0.0]);+ let mut ch = vec![vec![1.0f32; 4]];+ v.process(&mut ch);+ assert_eq!(ch[0], [1.0, 0.75, 0.5, 0.25]);+ let mut ch = vec![vec![1.0f32; 4]];+ v.process(&mut ch);+ assert_eq!(ch[0], [0.0; 4]);+ }++ #[test]+ fn pan_moves_one_channel_into_the_other_keeping_their_sum() {+ for p in [-1.0f32, -0.5, 0.0, 0.25, 1.0] {+ let mut pan = Pan::default();+ pan.set(&[p]);+ let mut ch = vec![vec![0.6f32; 16], vec![-0.2; 16]];+ pan.process(&mut ch);+ let (l, r) = (ch[0][5], ch[1][5]);+ assert!((l + r - 0.4).abs() < 1e-6, "{p}: {l} {r}");+ if p >= 0.0 {+ assert!((l - (0.6 + p * -0.2)).abs() < 1e-6);+ assert!((r - (1.0 - p) * -0.2).abs() < 1e-6);+ } else {+ assert!((l - (1.0 + p) * 0.6).abs() < 1e-6);+ assert!((r - (-0.2 - p * 0.6)).abs() < 1e-6);+ }+ }+ }++ #[test]+ fn pan_leaves_other_layouts_alone() {+ let mut pan = Pan::default();+ pan.set(&[1.0]);+ let mut ch = vec![vec![0.3f32; 4]];+ pan.process(&mut ch);+ assert_eq!(ch[0], [0.3; 4]);+ }+}diff --git a/crates/mixer/src/lib.rs b/crates/mixer/src/lib.rsindex 4badf4e..c0cc6eb 100644--- a/crates/mixer/src/lib.rs+++ b/crates/mixer/src/lib.rs@@ -8,9 +8,23 @@ pub mod align;pub mod beats;pub mod dsp;pub mod fft;+mod fx;++/// `channels` (a buffer a channel, all of the sound) through `e` when it+/// is one of the effects that change the sound's length+/// ([`bv_timeline::EffectKind::works_offline`]): the result, its length its+/// own.+pub fn render_offline(+ e: &bv_timeline::Effect,+ rate: u32,+ channels: Vec<Vec<f32>>,+) -> Option<Vec<Vec<f32>>> {+ fx::offline::render(e, rate, channels)+}pub mod loudness;pub mod meters;pub mod modern_eq;+mod prerender;mod stretch;#[cfg(not(target_family = "wasm"))]mod vst;@@ -294,6 +308,11 @@ pub struct AudioPool {hardware: Vec<(u8, AudioBuffer)>,/// Plug-in delay compensation's delay lines (see [`Delays`]).lines: HashMap<DelayKey, DelayLine>,+ /// The project's tempo, for the effects with tempo sync.+ tempo: bv_timeline::Tempo,+ /// The sounds of events whose effects change the sound's length, made+ /// through their chains ([`prerender`]).+ prerenders: prerender::Prerenders,}/// How far ahead of the frame's time each bus's and chain's input plays@@ -327,6 +346,7 @@ impl Delays {/// `project`'s [`Delays`], its busses' and chains' effects' latencies/// asked of `pool` (where [`finish_mix`] runs them).pub fn delays(project: &Project, pool: &mut AudioPool) -> Delays {+ pool.tempo = project.settings.tempo;let rate = project.settings.sample_rate;let channels = project.settings.channels.channel_count();let mut total = HashMap::new();@@ -405,6 +425,14 @@ impl AudioPool {AudioPool::default()}+ /// Mixes while playing: the sounds of events whose effects change the+ /// sound's length are made on threads of their own (the last one made+ /// plays meanwhile) instead of at once.+ pub fn set_live(&mut self, live: bool) {+ // The web build has no threads of its own: there, at once.+ self.prerenders.live = live && !cfg!(target_family = "wasm");+ }+/// The reader event `owner` reads `info`'s audio stream `stream` with:/// its own; else one no event used in this block (the latest used: at/// a cut the next event goes on where the last one stopped); else a new@@ -471,6 +499,7 @@ impl AudioPool {self.block += 1;let block = self.block;self.readers.retain(|s| block - s.used <= IDLE_BLOCKS);+ self.prerenders.forget_old(block);if !self.stretch.is_empty() {let readers = &self.readers;self.stretch@@ -488,6 +517,7 @@ impl AudioPool {self.meters.clear();self.stretch.clear();self.lines.clear();+ self.prerenders.clear();}/// Adds `src` (the block from sample `at`) to `dst` `delay` samples@@ -688,6 +718,7 @@ impl AudioPool {.fx.entry(key).or_insert_with(|| (dsp::Chain::default(), i64::MIN));+ entry.0.set_tempo(self.tempo);entry.0.sync(effects, rate, channels, keep);entry.0.latency()}@@ -716,6 +747,7 @@ impl AudioPool {if entry.1 != s0 {entry.0.reset();}+ entry.0.set_tempo(self.tempo);entry.0.sync(effects, rate, channels.len(), keep);let owner = match key {FxKey::Clip(c) => modern_eq::TapOwner::Clip(c),@@ -791,6 +823,40 @@ fn quick_fade() -> Tick {}/// Primeira amostra cujo início é ≥ `t`.+/// `src` (event `clip`'s sound from project sample `s0`) through its fades+/// in, out and with its neighbours (and the quick fades at its edges).+fn fade_clip(+ project: &Project,+ track: &bv_timeline::Track,+ clip: &Clip,+ rate: SampleRate,+ s0: i64,+ src: &mut [Vec<f32>],+) {+ let n = src.first().map_or(0, Vec::len);+ let (fade_in, fade_out) = track.effective_fades(clip, project.auto_crossfade);+ let q_len = quick_fade();+ let quick = project.quick_fades && q_len > Tick::ZERO && (fade_in < q_len || fade_out < q_len);+ if fade_in > Tick::ZERO || fade_out > Tick::ZERO || quick {+ let gains: Vec<f32> = (0..n)+ .map(|i| {+ let t = rate.sample_start(s0 + i as i64);+ let q = if quick {+ quick_fade_gain(clip, fade_in, fade_out, t, q_len)+ } else {+ 1.0+ };+ fade_gain(clip, fade_in, fade_out, t) * q+ })+ .collect();+ for ch in src.iter_mut() {+ for (s, g) in ch.iter_mut().zip(&gains) {+ *s *= g;+ }+ }+ }+}+fn first_sample_at_or_after(rate: SampleRate, t: Tick) -> i64 {let s = rate.sample_at(t);if rate.sample_start(s) < t { s + 1 } else { s }@@ -1011,6 +1077,7 @@ fn add_track(pool: &mut AudioPool,sums: &mut Sums,) -> Option<Vec<f32>> {+ pool.tempo = project.settings.tempo;let rate = project.settings.sample_rate;let layout = project.settings.channels;// FX automation: the effects as their envelopes have them now.@@ -1089,6 +1156,34 @@ fn add_track(info.effects.iter().chain(&clip.effects).collect()};let channels = info.audio.map_or(0, |a| usize::from(a.channels));+ // Effects that change its length: it plays its sound made+ // through its whole chain (see `prerender`), once made.+ let made = if effects.iter().any(|e| e.enabled && e.kind.works_offline()) {+ let block = pool.block;+ pool.prerenders+ .sound(info, clip, &effects, rate, quality, pool.tempo, block)+ } else {+ None+ };+ if let Some(made) = made {+ let from = (s0 - first_sample_at_or_after(rate, clip.start)).max(0) as usize;+ let n = (s1 - s0) as usize;+ let mut src: Vec<Vec<f32>> = made+ .iter()+ .map(|m| {+ let mut v = vec![0.0f32; n];+ if from < m.len() {+ let k = (m.len() - from).min(n);+ v[..k].copy_from_slice(&m[from..from + k]);+ }+ v+ })+ .collect();+ fade_clip(project, track, clip, rate, s0, &mut src);+ add_mapped(&mut bus, &src, (s0 - start) as usize, clip.level);+ any = true;+ continue;+ }let late = if effects.is_empty() || channels == 0 {0} else {@@ -1153,28 +1248,7 @@ fn add_track(&mut src,);}- let (fade_in, fade_out) = track.effective_fades(clip, project.auto_crossfade);- let q_len = quick_fade();- let quick =- project.quick_fades && q_len > Tick::ZERO && (fade_in < q_len || fade_out < q_len);- if fade_in > Tick::ZERO || fade_out > Tick::ZERO || quick {- let gains: Vec<f32> = (0..n)- .map(|i| {- let t = rate.sample_start(s0 + i as i64);- let q = if quick {- quick_fade_gain(clip, fade_in, fade_out, t, q_len)- } else {- 1.0- };- fade_gain(clip, fade_in, fade_out, t) * q- })- .collect();- for ch in &mut src {- for (s, g) in ch.iter_mut().zip(&gains) {- *s *= g;- }- }- }+ fade_clip(project, track, clip, rate, s0, &mut src);add_mapped(&mut bus, &src, (s0 - start) as usize, clip.level);any = true;}@@ -2875,6 +2949,34 @@ mod tests {}}+ /// An event with Pitch Shift — an effect that changes the sound's+ /// length — plays its sound made through its chain: a 500 Hz tone an+ /// octave up comes out at 1 kHz, the event as long as it was, silent+ /// once the shortened sound ends.+ #[test]+ fn length_changing_effects_play_from_the_events_made_sound() {+ use bv_timeline::audio_fx::pitch_shift as ps;+ let mut p = Project::new(ProjectSettings::default());+ let a = p.tracks[1].id;+ let m = tone(&mut p, 500.0, -6.0);+ p.insert_media(m, Tick::ZERO, None, Some(a)).unwrap();+ let id = p.tracks[1].clips[0].id;+ let length = p.tracks[1].clips[0].duration;+ let mut e = Effect::new(bv_timeline::EffectKind::PitchShift);+ e.set_param(ps::SEMITONES, 12.0);+ p.clip_mut(id).unwrap().effects.push(e);+ let mut pool = AudioPool::new();+ let buf = mix(&p, 0, 48_000, &mut pool);+ let ch = &buf.channels[0];+ let crossings = ch.windows(2).filter(|w| w[0] < 0.0 && w[1] >= 0.0).count();+ assert!((995..=1005).contains(&crossings), "{crossings}");+ // Past half its length the shortened sound has ended.+ let late = first_sample_at_or_after(SampleRate::HZ_48000, length) * 3 / 4;+ let quiet = mix(&p, late, 4800, &mut pool);+ let peak = quiet.channels[0].iter().fold(0f32, |m, s| m.max(s.abs()));+ assert!(peak < 1e-4, "{peak}");+ }+#[test]fn reamostragem_mantem_a_frequencia() {for quality in AudioQuality::ALL {diff --git a/crates/mixer/src/modern_eq.rs b/crates/mixer/src/modern_eq.rsindex 1078823..b302506 100644--- a/crates/mixer/src/modern_eq.rs+++ b/crates/mixer/src/modern_eq.rs@@ -1,27 +1,48 @@-//! The Modern Equalizer, as VEGAS's Help describes it: up to eight bands —-//! high pass, low pass, low and high shelving, band pass and peaking —,-//! the passes 6 to 36 dB an octave (the others a fixed 12), each on both+//! The Modern Equalizer, as VEGAS's: up to eight bands — a high or low+//! pass of 6, 12, 24 or 36 dB an octave, a low or high shelf of 6 or 12, a+//! peak, a band pass of 6, 12 or 18 or a band stop —, each on both//! channels or on the left, the right, the middle or the sides alone; then//! Mono Below (the sides high-passed, for a mono low end), Stereo Width-//! (the sides scaled) and Output Gain; Global Scale scales every band's-//! gain (below 0 a boost becomes a cut). Butterworth sections from the RBJ-//! cookbook's biquads (`dsp.rs`); [`band_db`] and [`total_db`] give the-//! curves the interface draws.+//! (the sides scaled) and Output Gain. Global Scale scales every band's+//! gain (below 0 a boost becomes a cut).+//!+//! A band is minimum phase — the cookbook's second-order sections, the+//! steeper slopes two or three alike in a row (all with the band's Q), the+//! 6 dB passes and shelves first order — or linear phase: the curves of a+//! routing's linear-phase bands multiplied into one response with no+//! phase, cut to an FIR filter as long as Linear Phase Quality says and+//! applied through FFTs ([`Linear`]). Frequency, gain and Q glide to new+//! values in 50 ms, the sections redesigned sample by sample meanwhile; a+//! band fades in or out as long when turned on or off (or reshaped: out+//! as it was, in as it is), and a new linear-phase filter crossfades from+//! the old. Oversampled, the bands run at 2, 4 or 8 times the rate between+//! half-band FIR filters ([`Oversampler`]). [`band_curve`] and+//! [`total_curve`] give the curves the interface draws.use std::collections::VecDeque;+use std::f64::consts::{PI, TAU};use std::sync::Mutex;use std::time::Instant;use bv_timeline::Effect;/// How many bands it has; its global parameters (Global Scale, Mono/// Below, Stereo Width, Output Gain) and each band's (in use, on, type,-/// frequency, gain, Q, slope, routing), as the model lays them out.-pub use bv_timeline::fx::modern_eq::{BANDS, GLOBALS, OVERSAMPLING, PER_BAND};+/// frequency, gain, Q, slope, routing), as the model lays them out; after+/// them Oversampling, each band's phase and Linear Phase Quality.+pub use bv_timeline::fx::modern_eq::{BANDS, GLOBALS, OVERSAMPLING, PER_BAND, QUALITY, model};-use crate::dsp::{Biquad, Coeffs, Shape, design};+use crate::fft::{Complex, Plan};+use crate::fx::Own;-/// Mono Below's filter is off under this frequency (its slider's start).-pub const MONO_BELOW_OFF: f32 = 10.0;+/// Mono Below is off at its slider's start.+pub const MONO_BELOW_OFF: f32 = 20.0;++/// How long values glide to new ones and a band fades in or out (s).+const GLIDE: f64 = 0.05;++/// Added and taken away again: what is smaller than its last digit goes,+/// before it slows the filters' memory down.+const FLUSH: f64 = 1e-30;/// A band's shape.#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -32,21 +53,23 @@ pub enum BandType {HighShelf,BandPass,Peaking,+ BandStop,}impl BandType {/// In the order of the Filter Type buttons.- pub const ALL: [BandType; 6] = [+ pub const ALL: [BandType; 7] = [BandType::HighPass,BandType::LowPass,BandType::LowShelf,BandType::HighShelf,BandType::BandPass,BandType::Peaking,+ BandType::BandStop,];fn of(v: f32) -> BandType {- BandType::ALL[(v.round().max(0.0) as usize).min(5)]+ BandType::ALL[(v.round().max(0.0) as usize).min(BandType::ALL.len() - 1)]}fn index(self) -> f32 {@@ -62,10 +85,22 @@ impl BandType {BandType::HighShelf => "High Shelving",BandType::BandPass => "Band Pass",BandType::Peaking => "Peaking",+ BandType::BandStop => "Band Stop",+ }+ }++ /// The slopes it comes in (dB an octave).+ pub fn slopes(self) -> &'static [u8] {+ match self {+ BandType::HighPass | BandType::LowPass => &[6, 12, 24, 36],+ BandType::LowShelf | BandType::HighShelf => &[6, 12],+ BandType::BandPass => &[6, 12, 18],+ BandType::Peaking => &[12],+ BandType::BandStop => &[6],}}- /// Whether it has a gain (the passes have none).+ /// Whether it has a gain (the passes and the stop have none).pub fn has_gain(self) -> bool {matches!(self,@@ -73,17 +108,9 @@ impl BandType {)}- /// Whether its slope can be picked (the others' is 12 dB an octave).+ /// Whether its slope can be picked.pub fn has_slope(self) -> bool {- matches!(- self,- BandType::HighPass | BandType::LowPass | BandType::BandPass- )- }-- /// Whether its Q sets its width.- pub fn has_q(self) -> bool {- matches!(self, BandType::Peaking | BandType::BandPass)+ self.slopes().len() > 1}}@@ -138,9 +165,13 @@ pub struct Band {pub freq: f32,pub gain_db: f32,pub q: f32,- /// dB an octave: 6, 12, 18, 24, 30 or 36 (the passes').+ /// dB an octave as last picked (a multiple of 6): its type keeps the+ /// nearest it comes in ([`Band::steepness`]).pub slope: u8,pub route: Route,+ /// Linear phase (an FIR filter shared with the other linear-phase+ /// bands), or minimum phase (its own sections).+ pub linear: bool,}impl Band {@@ -149,15 +180,38 @@ impl Band {self.used && self.on}- /// Its order as it filters: its slope's for the passes, 12 dB an- /// octave's for the others.- fn order(&self) -> usize {- if self.kind.has_slope() {- usize::from(self.slope / 6).clamp(1, 6)- } else {- 2+ /// Its slope (dB an octave): the one picked if its type comes in it,+ /// else the nearest that it does, the steeper on a tie.+ pub fn steepness(&self) -> u8 {+ let picked = i32::from(self.slope);+ self.kind+ .slopes()+ .iter()+ .copied()+ .min_by_key(|&s| ((i32::from(s) - picked).abs(), -i32::from(s)))+ .unwrap_or(12)+ }++ /// The type and slope it filters with: linear phase has no 6 dB+ /// shelves (they are 12 dB ones there).+ fn shape(&self) -> (BandType, u8) {+ let slope = self.steepness();+ match self.kind {+ BandType::LowShelf | BandType::HighShelf if self.linear => (self.kind, 12),+ kind => (kind, slope),}}++ /// Whether its Q shapes it (the first-order passes and shelves have+ /// none).+ pub fn has_q(&self) -> bool {+ let (kind, slope) = self.shape();+ !(slope == 6+ && matches!(+ kind,+ BandType::HighPass | BandType::LowPass | BandType::LowShelf | BandType::HighShelf+ ))+ }}/// The equalizer's settings.@@ -165,16 +219,19 @@ impl Band {pub struct Settings {/// Global Scale: every band's gain times this (−2 to 2).pub scale: f32,- /// Mono Below: the sides high-passed here (Hz; off under+ /// Mono Below: the sides high-passed here (Hz, 20 to 200; off at/// [`MONO_BELOW_OFF`]).pub mono_below: f32,- /// Stereo Width: the sides times this (0 to 2).+ /// Stereo Width: the sides times this (0 to 1).pub width: f32,pub output_db: f32,pub bands: [Band; BANDS],/// Oversampling: the bands run at this many times the rate (1, 2, 4/// or 8), so their curves keep their shape near the top.pub oversampling: u8,+ /// Linear Phase Quality (0 to 4): how long the linear-phase filter is+ /// ([`Linear::taps`]).+ pub quality: u8,}/// Where band `b`'s parameters start.@@ -184,12 +241,16 @@ pub fn band_at(b: usize) -> usize {impl Settings {pub fn of(e: &Effect) -> Settings {- let p = |i: usize| e.param(i);+ Settings::read(|i| e.param(i))+ }++ /// The settings that parameter values `p` (by index) make.+ fn read(p: impl Fn(usize) -> f32) -> Settings {Settings {scale: (p(0) / 100.0).clamp(-2.0, 2.0),- mono_below: p(1).max(0.0),- width: (p(2) / 100.0).clamp(0.0, 2.0),- output_db: p(3),+ mono_below: p(1).clamp(MONO_BELOW_OFF, 200.0),+ width: (p(2) / 100.0).clamp(0.0, 1.0),+ output_db: p(3).clamp(-24.0, 24.0),bands: std::array::from_fn(|b| {let at = band_at(b);Band {@@ -201,9 +262,11 @@ impl Settings {q: p(at + 5).clamp(0.05, 30.0),slope: ((p(at + 6) / 6.0).round().clamp(1.0, 6.0) * 6.0) as u8,route: Route::of(p(at + 7)),+ linear: p(model(b)) >= 0.5,}}),oversampling: 1 << (p(OVERSAMPLING).round().clamp(0.0, 3.0) as u8),+ quality: p(QUALITY).round().clamp(0.0, 4.0) as u8,}}@@ -223,128 +286,242 @@ impl Settings {e.set_param(at + 5, band.q);e.set_param(at + 6, f32::from(band.slope));e.set_param(at + 7, band.route.index());+ e.set_param(model(b), f32::from(u8::from(band.linear)));}e.set_param(OVERSAMPLING,f32::from(self.oversampling.max(1).trailing_zeros() as u8),);+ e.set_param(QUALITY, f32::from(self.quality.min(4)));}/// Whether Mono Below filters the sides.pub fn mono_below_on(&self) -> bool {- self.mono_below >= MONO_BELOW_OFF+ self.mono_below > MONO_BELOW_OFF + 0.01}}-/// The Qs of a Butterworth filter of `order` (1 to 6) as second-order-/// sections, and whether it also has a first-order one (odd orders).-fn butterworth(order: usize) -> (bool, Vec<f32>) {- let n = order.max(1);- let odd = n % 2 == 1;- let qs = (0..n / 2)- .map(|k| {- // Each pair of poles' angle from the negative real axis.- let phi = if odd {- std::f32::consts::PI * (k + 1) as f32 / n as f32- } else {- std::f32::consts::PI * (2 * k + 1) as f32 / (2 * n) as f32- };- 1.0 / (2.0 * phi.cos())- })- .collect();- (odd, qs)+/// A second-order section's coefficients (`a0` being 1).+#[derive(Clone, Copy, Debug, PartialEq)]+struct Coeffs {+ b0: f64,+ b1: f64,+ b2: f64,+ a1: f64,+ a2: f64,}-/// A first-order low or high pass (`high`) at `f`.-fn first_order(high: bool, rate: f32, f: f32) -> Coeffs {- let k = (std::f32::consts::PI * f.clamp(10.0, rate * 0.49) / rate).tan();- let a1 = (k - 1.0) / (k + 1.0);- let b0 = if high { 1.0 } else { k } / (1.0 + k);- Coeffs {- b0,- b1: if high { -b0 } else { b0 },- b2: 0.0,- a1,- a2: 0.0,+impl Coeffs {+ /// Its power gain at the angle whose cosine is `c1` (`c2` twice its).+ fn power(&self, c1: f64, c2: f64) -> f64 {+ let num = self.b0 * self.b0+ + self.b1 * self.b1+ + self.b2 * self.b2+ + 2.0 * (self.b0 * self.b1 + self.b1 * self.b2) * c1+ + 2.0 * self.b0 * self.b2 * c2;+ let den = 1.0+ + self.a1 * self.a1+ + self.a2 * self.a2+ + 2.0 * (self.a1 + self.a1 * self.a2) * c1+ + 2.0 * self.a2 * c2;+ num / den.max(1e-300)}}-/// A Butterworth pass of `order` at `f`, as sections.-fn pass(high: bool, order: usize, rate: f32, f: f32) -> Vec<Coeffs> {- let shape = if high {- Shape::HighPass- } else {- Shape::LowPass- };- let (odd, qs) = butterworth(order);- let mut v: Vec<Coeffs> = qs.iter().map(|&q| design(shape, rate, f, q, 0.0)).collect();- if odd {- v.push(first_order(high, rate, f));+/// A band's filter of `kind` and `slope` at `fs` — `freq`, `gain_db` (the+/// scale applied) and `q` —: a section and how many alike in a row.+fn design(kind: BandType, slope: u8, fs: f64, freq: f64, gain_db: f64, q: f64) -> (Coeffs, usize) {+ let f = freq.clamp(1.0, 0.5 * fs);+ let q = q.max(0.01);+ let k = (PI * f / fs).tan();+ let a = 10f64.powf(gain_db / 40.0);+ // The cookbook's angle (2 Hz at least) and its bandwidth term.+ let (sw, cw) = (TAU * f.max(2.0) / fs).sin_cos();+ let alpha = sw / (2.0 * q);+ // The resonant passes' and the stop's denominator.+ let d = k * k * q + k + q;+ let (a1, a2) = (2.0 * q * (k * k - 1.0) / d, (k * k * q - k + q) / d);+ let steps = |per: u8| usize::from(slope / per).clamp(1, 3);+ match kind {+ BandType::LowPass | BandType::HighPass if slope <= 6 => {+ let n = 1.0 / (k + 1.0);+ let (b0, b1) = if kind == BandType::LowPass {+ (k * n, k * n)+ } else {+ (n, -n)+ };+ let c = Coeffs {+ b0,+ b1,+ b2: 0.0,+ a1: (k - 1.0) * n,+ a2: 0.0,+ };+ (c, 1)+ }+ BandType::LowPass => {+ let b0 = k * k * q / d;+ (+ Coeffs {+ b0,+ b1: 2.0 * b0,+ b2: b0,+ a1,+ a2,+ },+ steps(12),+ )+ }+ BandType::HighPass => {+ let b0 = q / d;+ (+ Coeffs {+ b0,+ b1: -2.0 * b0,+ b2: b0,+ a1,+ a2,+ },+ steps(12),+ )+ }+ BandType::BandStop => {+ let b0 = (k * k + 1.0) * q / d;+ (+ Coeffs {+ b0,+ b1: a1,+ b2: b0,+ a1,+ a2,+ },+ 1,+ )+ }+ // Its gain at the middle is Q (Q² and Q³ two and three alike).+ BandType::BandPass => {+ let n = 1.0 / (1.0 + alpha);+ let b0 = 0.5 * sw * n;+ (+ Coeffs {+ b0,+ b1: 0.0,+ b2: -b0,+ a1: -2.0 * cw * n,+ a2: (1.0 - alpha) * n,+ },+ steps(6),+ )+ }+ BandType::Peaking => {+ let n = 1.0 / (1.0 + alpha / a);+ (+ Coeffs {+ b0: (1.0 + alpha * a) * n,+ b1: -2.0 * cw * n,+ b2: (1.0 - alpha * a) * n,+ a1: -2.0 * cw * n,+ a2: (1.0 - alpha / a) * n,+ },+ 1,+ )+ }+ // First order: the whole gain below (or above) the corner, the+ // corner moved by the gain's square root so that the middle of the+ // change (in dB) stays at the band's frequency; the tangent's+ // series in place of the tangent.+ BandType::LowShelf | BandType::HighShelf if slope <= 6 => {+ let low = kind == BandType::LowShelf;+ let corner = if low { f / a } else { f * a }.clamp(fs / 24_576.0, fs / 2.125);+ let w = PI * corner / fs;+ let t = w + w.powi(3) / 3.0 + 2.0 * w.powi(5) / 15.0;+ let a1 = (t - 1.0) / (t + 1.0);+ let (b0, b1) = if low {+ let m = (a * a - 1.0) * t / (t + 1.0);+ (1.0 + m, a1 + m)+ } else {+ let m = (a * a - 1.0) / (t + 1.0);+ (1.0 + m, a1 - m)+ };+ (+ Coeffs {+ b0,+ b1,+ b2: 0.0,+ a1,+ a2: 0.0,+ },+ 1,+ )+ }+ BandType::LowShelf | BandType::HighShelf => {+ let beta = sw * a.sqrt() / q;+ let (p, m) = (a + 1.0, a - 1.0);+ let c = if kind == BandType::LowShelf {+ let n = 1.0 / (p + m * cw + beta);+ Coeffs {+ b0: a * (p - m * cw + beta) * n,+ b1: 2.0 * a * (m - p * cw) * n,+ b2: a * (p - m * cw - beta) * n,+ a1: -2.0 * (m + p * cw) * n,+ a2: (p + m * cw - beta) * n,+ }+ } else {+ let n = 1.0 / (p - m * cw + beta);+ Coeffs {+ b0: a * (p + m * cw + beta) * n,+ b1: -2.0 * a * (m + p * cw) * n,+ b2: a * (p + m * cw - beta) * n,+ a1: 2.0 * (m - p * cw) * n,+ a2: (p - m * cw - beta) * n,+ }+ };+ (c, 1)+ }}- v}-/// The sections band `b` is made of at `rate`, its gain times `scale`.-fn sections(b: &Band, scale: f32, rate: f32) -> Vec<Coeffs> {- match b.kind {- BandType::HighPass | BandType::LowPass => {- pass(b.kind == BandType::HighPass, b.order(), rate, b.freq)- }- // A section for each 6 dB an octave of its sides, each wider so- // that together they keep the band's width (half power where one- // alone of Q would have it).- BandType::BandPass => {- let n = b.order();- let q = b.q * (2f32.powf(1.0 / n as f32) - 1.0).sqrt();- vec![design(Shape::BandPass, rate, b.freq, q.max(0.05), 0.0); n]- }- BandType::LowShelf => vec![design(- Shape::LowShelf,- rate,- b.freq,- 0.707,- b.gain_db * scale,- )],- BandType::HighShelf => vec![design(- Shape::HighShelf,- rate,- b.freq,- 0.707,- b.gain_db * scale,- )],- BandType::Peaking => vec![design(Shape::Peak, rate, b.freq, b.q, b.gain_db * scale)],- }-}--/// A section's gain (dB) at `f`.-fn section_db(c: &Coeffs, rate: f32, f: f32) -> f32 {- let w = std::f64::consts::TAU * f64::from(f) / f64::from(rate);- let (s1, c1) = w.sin_cos();- let (s2, c2) = (2.0 * w).sin_cos();- let [b0, b1, b2, a1, a2] = [c.b0, c.b1, c.b2, c.a1, c.a2].map(f64::from);- let nr = b0 + b1 * c1 + b2 * c2;- let ni = -(b1 * s1 + b2 * s2);- let dr = 1.0 + a1 * c1 + a2 * c2;- let di = -(a1 * s1 + a2 * s2);- let power = (nr * nr + ni * ni) / (dr * dr + di * di).max(1e-30);- (10.0 * power.max(1e-24).log10()) as f32+/// Band `b`'s filter at `fs` with Global Scale's `scale`.+fn band_filter(b: &Band, scale: f32, fs: f64) -> (Coeffs, usize) {+ let (kind, slope) = b.shape();+ design(+ kind,+ slope,+ fs,+ f64::from(b.freq),+ f64::from(b.gain_db * scale),+ f64::from(b.q),+ )}-/// The gains (dB) at `freqs` of sections in a row.-fn curve(secs: &[Coeffs], rate: f32, freqs: &[f32]) -> Vec<f32> {+/// The power gain at each of `freqs` (Hz) of `count` sections `c` in a+/// row, at `fs`.+fn powers(c: &Coeffs, count: usize, fs: f64, freqs: &[f32]) -> Vec<f64> {freqs.iter()- .map(|&f| secs.iter().map(|c| section_db(c, rate, f)).sum())+ .map(|&f| {+ let w = TAU * f64::from(f) / fs;+ c.power(w.cos(), (2.0 * w).cos()).powi(count as i32)+ }).collect()}+fn to_db(power: f64) -> f32 {+ (10.0 * power.max(1e-24).log10()) as f32+}+/// Band `b`'s own curve: its gain (dB) at each of `freqs`, Global Scale's/// `scale` applied; 0 when it does nothing.pub fn band_curve(b: &Band, scale: f32, rate: f32, freqs: &[f32]) -> Vec<f32> {if !b.active() {return vec![0.0; freqs.len()];}- curve(§ions(b, scale, rate), rate, freqs)+ let fs = f64::from(rate);+ let (c, count) = band_filter(b, scale, fs);+ powers(&c, count, fs, freqs)+ .into_iter()+ .map(to_db)+ .collect()}/// [`band_curve`] at one frequency.@@ -352,18 +529,26 @@ pub fn band_db(b: &Band, scale: f32, rate: f32, f: f32) -> f32 {band_curve(b, scale, rate, &[f])[0]}-/// Mono Below's slope: 24 dB an octave.-const MONO_BELOW_ORDER: usize = 4;+/// Mono Below's filter on the sides: a second-order Butterworth high pass.+fn mono_below_filter(fs: f64, freq: f64) -> Coeffs {+ design(+ BandType::HighPass,+ 12,+ fs,+ freq,+ 0.0,+ std::f64::consts::FRAC_1_SQRT_2,+ )+ .0+}/// Mono Below's curve on the sides (dB at each of `freqs`); `None` when it/// is off.pub fn mono_below_curve(s: &Settings, rate: f32, freqs: &[f32]) -> Option<Vec<f32>> {s.mono_below_on().then(|| {- curve(- &pass(true, MONO_BELOW_ORDER, rate, s.mono_below),- rate,- freqs,- )+ let fs = f64::from(rate);+ let c = mono_below_filter(fs, f64::from(s.mono_below));+ powers(&c, 1, fs, freqs).into_iter().map(to_db).collect()})}@@ -389,156 +574,964 @@ pub fn total_db(s: &Settings, rate: f32, f: f32) -> f32 {total_curve(s, rate, &[f])[0]}-/// The equalizer running: each band's sections with their state, Mono-/// Below's filter, the width and the output gain; oversampled, the filters-/// that take the sound up to the higher rate and back.-#[derive(Clone, Debug)]-pub(crate) struct Eq {- bands: Vec<(Route, Vec<Biquad>)>,- mono_below: Vec<Biquad>,- width: f32,- gain: f32,- factor: usize,- up: Vec<Biquad>,- down: Vec<Biquad>,+/// A value gliding in a straight line to the last one it was sent.+#[derive(Clone, Copy, Debug)]+struct Glide {+ now: f64,+ target: f64,+ step: f64,+ left: u32,}-/// The order of the filters around oversampling.-const OVERSAMPLE_ORDER: usize = 8;+impl Glide {+ fn at(v: f64) -> Glide {+ Glide {+ now: v,+ target: v,+ step: 0.0,+ left: 0,+ }+ }-impl Eq {- pub(crate) fn new(e: &Effect, rate: u32, channels: usize) -> Eq {- let s = Settings::of(e);- let factor = usize::from(s.oversampling.max(1));- let r = (rate as usize * factor) as f32;- let n = channels.max(2);- // Around oversampling: what is above the sound's own top cut away- // going up and coming back down.- let guard = || -> Vec<Biquad> {- if factor == 1 {- return Vec::new();- }- pass(false, OVERSAMPLE_ORDER, r, rate as f32 * 0.45)- .into_iter()- .map(|c| Biquad::new(c, n))- .collect()+ /// Toward `v` in `steps` samples, the whole way again from where it is.+ fn to(&mut self, v: f64, steps: u32) {+ if v == self.target {+ return;+ }+ self.target = v;+ if steps == 0 {+ self.now = v;+ self.left = 0;+ } else {+ self.left = steps;+ self.step = (v - self.now) / f64::from(steps);+ }+ }++ fn moving(&self) -> bool {+ self.left > 0+ }++ /// The next sample's value.+ fn next(&mut self) -> f64 {+ if self.left > 0 {+ self.left -= 1;+ self.now = if self.left == 0 {+ self.target+ } else {+ self.now + self.step+ };+ }+ self.now+ }+}++/// One sample through a section (`m` its memory), the second direct form.+#[inline]+fn tick(c: &Coeffs, m: &mut [f64; 2], x: f64) -> f64 {+ let w = x - c.a1 * m[0] - c.a2 * m[1] + FLUSH - FLUSH;+ let y = c.b0 * w + c.b1 * m[0] + c.b2 * m[1];+ m[1] = m[0];+ m[0] = w;+ y+}++/// What a minimum-phase band filters with while it lasts.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+struct Shape {+ kind: BandType,+ slope: u8,+ route: Route,+}++impl Shape {+ fn of(b: &Band) -> Shape {+ let (kind, slope) = b.shape();+ Shape {+ kind,+ slope,+ route: b.route,+ }+ }+}++/// A minimum-phase band at work.+#[derive(Debug)]+struct Run {+ shape: Shape,+ /// Its next shape, taken once it has faded out.+ next: Option<Shape>,+ /// Whether it is to be heard (on, in use, minimum phase).+ heard: bool,+ freq: Glide,+ gain: Glide,+ q: Glide,+ /// How much of it is heard (0 to 1).+ wet: Glide,+ coeffs: Coeffs,+ count: usize,+ /// Each slot's sections' memory.+ memory: Vec<[[f64; 2]; 3]>,+}++impl Run {+ fn new(b: &Band, scale: f32, fs: f64) -> Run {+ let heard = b.active() && !b.linear;+ let mut run = Run {+ shape: Shape::of(b),+ next: None,+ heard,+ freq: Glide::at(f64::from(b.freq)),+ gain: Glide::at(f64::from(b.gain_db * scale)),+ q: Glide::at(f64::from(b.q)),+ wet: Glide::at(if heard { 1.0 } else { 0.0 }),+ coeffs: band_filter(b, scale, fs).0,+ count: 1,+ memory: Vec::new(),};- Eq {- bands: s- .bands- .iter()- .filter(|b| b.active())- .map(|b| {- let secs = sections(b, s.scale, r)- .into_iter()- .map(|c| Biquad::new(c, n))- .collect();- (b.route, secs)- })- .collect(),- mono_below: if s.mono_below_on() {- pass(true, MONO_BELOW_ORDER, r, s.mono_below)- .into_iter()- .map(|c| Biquad::new(c, 1))- .collect()+ run.redesign(fs);+ run+ }++ fn redesign(&mut self, fs: f64) {+ (self.coeffs, self.count) = design(+ self.shape.kind,+ self.shape.slope,+ fs,+ self.freq.now,+ self.gain.now,+ self.q.now,+ );+ }++ /// Band `b`'s new values: frequency, gain and Q glide there in `steps`+ /// samples; a new shape waits for the band to fade out.+ fn follow(&mut self, b: &Band, scale: f32, fs: f64, steps: u32) {+ self.heard = b.active() && !b.linear;+ let shape = Shape::of(b);+ if shape != self.shape {+ if self.silent() {+ self.shape = shape;+ self.next = None;+ self.redesign(fs);} else {- Vec::new()- },- width: s.width,- gain: 10f32.powf(s.output_db / 20.0),- factor,- up: guard(),- down: guard(),+ self.next = Some(shape);+ }+ } else {+ self.next = None;}+ self.freq.to(f64::from(b.freq), steps);+ self.gain.to(f64::from(b.gain_db * scale), steps);+ self.q.to(f64::from(b.q), steps);+ if !self.freq.moving() && !self.gain.moving() && !self.q.moving() {+ self.redesign(fs);+ }+ let wet = if self.heard && self.next.is_none() {+ 1.0+ } else {+ 0.0+ };+ self.wet.to(wet, steps);+ }++ /// Faded out, with nothing waiting: it changes nothing.+ fn silent(&self) -> bool {+ self.wet.now == 0.0 && !self.wet.moving()}- /// Processes the channels (planar) in place: the first two are the- /// left and the right; oversampled, at the higher rate in between.- pub(crate) fn process(&mut self, channels: &mut [Vec<f32>]) {- if self.factor <= 1 {- self.process_at_rate(channels);+ /// `slots` (as long each) through the band.+ fn process(&mut self, slots: &mut [&mut [f64]], fs: f64, steps: u32) {+ if self.silent() && self.next.is_none() {return;}- let k = self.factor;- let mut high: Vec<Vec<f32>> = channels+ if self.memory.len() < slots.len() {+ self.memory.resize(slots.len(), [[0.0; 2]; 3]);+ }+ let n = slots.first().map_or(0, |s| s.len());+ let gliding = self.freq.moving() || self.gain.moving() || self.q.moving();+ if !gliding && !self.wet.moving() && self.wet.now == 1.0 {+ // At rest: the sections, a slot at a time.+ let count = self.count;+ for (slot, memory) in slots.iter_mut().zip(&mut self.memory) {+ for m in memory.iter_mut().take(count) {+ for v in slot.iter_mut() {+ *v = tick(&self.coeffs, m, *v);+ }+ }+ }+ return;+ }+ for i in 0..n {+ if self.freq.moving() || self.gain.moving() || self.q.moving() {+ self.freq.next();+ self.gain.next();+ self.q.next();+ self.redesign(fs);+ }+ let wet = self.wet.next();+ for (slot, memory) in slots.iter_mut().zip(&mut self.memory) {+ let x = slot[i];+ let mut y = x;+ for m in memory.iter_mut().take(self.count) {+ y = tick(&self.coeffs, m, y);+ }+ slot[i] = x + wet * (y - x);+ }+ if wet == 0.0 && !self.wet.moving() {+ // Faded out: its memory goes, a waiting shape comes in.+ self.memory.fill([[0.0; 2]; 3]);+ if let Some(shape) = self.next.take() {+ self.shape = shape;+ self.redesign(fs);+ if self.heard {+ self.wet.to(1.0, steps);+ }+ } else {+ return;+ }+ }+ }+ }+}++/// A half-band low pass of `4n + 3` taps: those an odd number of samples+/// from its middle (`h[2i − m]` for `i` in `0..=m`), the middle one a half+/// and the others nothing.+#[derive(Debug)]+struct HalfBand {+ taps: Vec<f64>,+ m: usize,+}++fn bessel_i0(x: f64) -> f64 {+ let half = x / 2.0;+ let (mut sum, mut term) = (1.0, 1.0);+ for k in 1..300 {+ term *= (half / k as f64).powi(2);+ sum += term;+ if term < 1e-17 * sum {+ break;+ }+ }+ sum+}++impl HalfBand {+ /// Through Kaiser's window: from `0.5 − tw` of the higher rate's half+ /// to `0.5 + tw` it falls `atten` dB.+ fn new(tw: f64, atten: f64) -> HalfBand {+ let beta = if atten > 50.0 {+ 0.1102 * (atten - 8.7)+ } else if atten >= 21.0 {+ 0.5842 * (atten - 21.0).powf(0.4) + 0.07886 * (atten - 21.0)+ } else {+ 0.0+ };+ let estimate = ((atten - 7.95) / (2.285 * 2.0 * tw * PI)).ceil() as usize + 1;+ let n = estimate.saturating_sub(3).div_ceil(4);+ let m = 2 * n + 1;+ let i0 = bessel_i0(beta);+ let mut taps: Vec<f64> = (0..=m)+ .map(|i| {+ let k = 2.0 * i as f64 - m as f64;+ let r = k / m as f64;+ let window = bessel_i0(beta * (1.0 - r * r).max(0.0).sqrt()) / i0;+ (PI * k / 2.0).sin() / (PI * k) * window+ })+ .collect();+ // They add up to a half: nothing changes at 0 Hz.+ let sum: f64 = taps.iter().sum();+ for t in &mut taps {+ *t *= 0.5 / sum;+ }+ HalfBand { taps, m }+ }++ /// The taps' sum over the samples `at − 2·i·stride` (`i` in `0..=m`),+ /// paired from both ends.+ #[inline]+ fn dot(&self, v: &[f64], at: usize, stride: usize) -> f64 {+ let m = self.m;+ (0..m.div_ceil(2))+ .map(|i| self.taps[i] * (v[at - i * stride] + v[at - (m - i) * stride]))+ .sum()+ }++ /// `x` at twice the rate into `out`; `history` the last `m` samples+ /// before it.+ fn up(&self, x: &[f64], history: &mut Vec<f64>, out: &mut Vec<f64>) {+ let m = self.m;+ history.resize(m, 0.0);+ let mut v = std::mem::take(history);+ v.extend_from_slice(x);+ out.clear();+ for j in 0..x.len() {+ let at = m + j;+ out.push(2.0 * self.dot(&v, at, 1));+ out.push(v[at - (m - 1) / 2]);+ }+ history.extend_from_slice(&v[v.len() - m..]);+ }++ /// `x` (an even count) at half the rate into `out`; `history` the last+ /// `2m` samples before it.+ fn down(&self, x: &[f64], history: &mut Vec<f64>, out: &mut Vec<f64>) {+ let m = self.m;+ history.resize(2 * m, 0.0);+ let mut v = std::mem::take(history);+ v.extend_from_slice(x);+ out.clear();+ for j in 0..x.len() / 2 {+ let at = 2 * m + 2 * j;+ out.push(0.5 * v[at - m] + self.dot(&v, at, 2));+ }+ history.extend_from_slice(&v[v.len() - 2 * m..]);+ }+}++/// The bands' rate doubled stage by stage and halved back, each stage two+/// half-band filters: going up, a transition a tenth of the half wide and+/// 80, 70, 60 dB down (the first 5 % wide and 90 dB down); coming down,+/// 12 % and 65, 55, 45 dB (the first 6 % and 75 dB).+#[derive(Debug)]+struct Oversampler {+ stages: Vec<(HalfBand, HalfBand)>,+ /// Each stage's and channel's history, going up and coming down.+ up: Vec<Vec<Vec<f64>>>,+ down: Vec<Vec<Vec<f64>>>,+}++impl Oversampler {+ fn new(factor: usize) -> Oversampler {+ let stages: Vec<(HalfBand, HalfBand)> = (0..factor.max(1).trailing_zeros())+ .map(|i| {+ let first = i == 0;+ let i = f64::from(i);+ (+ HalfBand::new(if first { 0.05 } else { 0.10 }, 90.0 - 10.0 * i),+ HalfBand::new(if first { 0.06 } else { 0.12 }, 75.0 - 10.0 * i),+ )+ })+ .collect();+ let count = stages.len();+ Oversampler {+ stages,+ up: vec![Vec::new(); count],+ down: vec![Vec::new(); count],+ }+ }++ /// How late its output comes, in samples of the top rate.+ fn delay(&self) -> usize {+ let count = self.stages.len();+ self.stages.iter().enumerate()- .map(|(c, ch)| {- let mut v = Vec::with_capacity(ch.len() * k);- for &x in ch {- for j in 0..k {- let s = if j == 0 { x * k as f32 } else { 0.0 };- v.push(self.up.iter_mut().fold(s, |y, f| f.process(c, y)));- }+ .map(|(i, (up, down))| (up.m + down.m) << (count - 1 - i))+ .sum()+ }++ /// Channel `c`'s `x` at the top rate, into `out`.+ fn raise(&mut self, c: usize, x: &[f32], out: &mut Vec<f64>) {+ out.clear();+ out.extend(x.iter().map(|&v| f64::from(v)));+ let mut next = Vec::new();+ for (s, (up, _)) in self.stages.iter().enumerate() {+ if self.up[s].len() <= c {+ self.up[s].resize(c + 1, Vec::new());+ }+ up.up(out, &mut self.up[s][c], &mut next);+ std::mem::swap(out, &mut next);+ }+ }++ /// Channel `c`'s `x` from the top rate back down, into `out`.+ fn lower(&mut self, c: usize, x: &mut Vec<f64>, out: &mut [f32]) {+ let mut next = Vec::new();+ for (s, (_, down)) in self.stages.iter().enumerate().rev() {+ if self.down[s].len() <= c {+ self.down[s].resize(c + 1, Vec::new());+ }+ down.down(x, &mut self.down[s][c], &mut next);+ std::mem::swap(x, &mut next);+ }+ for (o, &v) in out.iter_mut().zip(x.iter()) {+ *o = v as f32;+ }+ }+}++/// A linear-phase band as its filter is made: its shape, routing and+/// values (its gain scaled).+#[derive(Clone, Copy, Debug, PartialEq)]+struct Key {+ shape: Shape,+ freq: f64,+ gain: f64,+ q: f64,+}++/// One set of linear-phase filters' spectra: for the left and the right,+/// what each hears of itself and of the other (the middle's and sides'+/// bands make each heard in the other), and the other channels' filter;+/// with one channel, `ll` is its. With what the last block left for the+/// next, each channel.+#[derive(Clone, Debug)]+struct Filters {+ ll: Vec<Complex>,+ lr: Option<Vec<Complex>>,+ rl: Option<Vec<Complex>>,+ rr: Vec<Complex>,+ rest: Vec<Complex>,+ tails: Vec<Vec<f64>>,+}++/// The linear-phase bands at work: their curves multiplied (a routing's+/// alike into one), sampled at about twice the rate's count of points,+/// back in time centred and cut to [`Linear::taps`] taps, and applied+/// through FFTs half an FFT of sound at a time; a new filter, made when a+/// block ends and no fade is running, fades in from the old over its+/// quality's time.+#[derive(Debug)]+struct Linear {+ fs: f64,+ quality: u8,+ channels: usize,+ taps: usize,+ half: usize,+ plan: Plan,+ /// The transform the curves go back to time through.+ design: Plan,+ now: Filters,+ old: Option<Filters>,+ fade: usize,+ fade_len: usize,+ made: Vec<Key>,+ wanted: Vec<Key>,+ input: Vec<Vec<f64>>,+ output: Vec<Vec<f64>>,+ /// The last block's spectra, each channel: a new filter starts with+ /// what it would have left.+ last: Vec<Vec<Complex>>,+ at: usize,+}++/// The power of two nearest to `x`.+fn nearest_power_of_two(x: f64) -> usize {+ let below = 1usize << (x.max(1.0).log2().floor() as u32);+ if x - below as f64 <= (2 * below) as f64 - x {+ below+ } else {+ 2 * below+ }+}++impl Linear {+ /// How long its filter is at `fs` for Linear Phase Quality `quality`:+ /// 1024, 2048, 4096 or 8192 taps at 44.1 kHz (an odd count), or the+ /// longest the curve's sampling allows.+ fn taps(fs: f64, quality: u8) -> usize {+ if quality >= 4 {+ return nearest_power_of_two(2.0 * fs) / 2 - 1;+ }+ let taps = (f64::from(1024u32 << quality) * fs / 44_100.0) as usize;+ (taps - usize::from(taps.is_multiple_of(2))).max(3)+ }++ /// How long a new filter takes to fade in (s), by quality.+ const FADES: [f64; 5] = [0.05, 0.075, 0.15, 0.25, 0.5];++ fn new(fs: f64, quality: u8, channels: usize, keys: Vec<Key>) -> Linear {+ let quality = quality.min(4);+ let taps = Linear::taps(fs, quality);+ let half = taps.next_power_of_two();+ let points = if quality >= 4 {+ nearest_power_of_two(2.0 * fs)+ } else {+ nearest_power_of_two(2.0 * fs).min((16 * taps).next_power_of_two().max(1024))+ };+ let channels = channels.max(1);+ let mut l = Linear {+ fs,+ quality,+ channels,+ taps,+ half,+ plan: Plan::new(2 * half),+ design: Plan::new(points),+ now: Filters {+ ll: Vec::new(),+ lr: None,+ rl: None,+ rr: Vec::new(),+ rest: Vec::new(),+ tails: vec![vec![0.0; half]; channels],+ },+ old: None,+ fade: 0,+ fade_len: (Linear::FADES[usize::from(quality)] * fs) as usize,+ made: Vec::new(),+ wanted: keys,+ input: vec![vec![0.0; half]; channels],+ output: vec![vec![0.0; half]; channels],+ last: vec![vec![Complex::ZERO; 2 * half]; channels],+ at: 0,+ };+ l.now = l.filters(&l.wanted);+ l.made = l.wanted.clone();+ l+ }++ /// How late its output comes (samples of its rate).+ fn delay(&self) -> usize {+ self.half + (self.taps - 1) / 2+ }++ /// The filter for `response` (a gain at each of the design's first+ /// half of points and the middle one), as a spectrum.+ fn kernel(&self, response: &[f64]) -> Vec<Complex> {+ let n = self.design.len();+ let mut w: Vec<Complex> = (0..n)+ .map(|k| Complex::new(response[k.min(n - k)], 0.0))+ .collect();+ self.design.run(&mut w, true);+ let middle = (self.taps - 1) / 2;+ let mut h = vec![Complex::ZERO; 2 * self.half];+ for (j, t) in h.iter_mut().take(self.taps.min(n)).enumerate() {+ t.re = w[(j + n - middle) % n].re;+ }+ self.plan.run(&mut h, false);+ h+ }++ /// The filters `keys` make.+ fn filters(&self, keys: &[Key]) -> Filters {+ let n = self.design.len();+ let bins = n / 2 + 1;+ let cos: Vec<(f64, f64)> = (0..bins)+ .map(|k| {+ let w = TAU * k as f64 / n as f64;+ (w.cos(), (2.0 * w).cos())+ })+ .collect();+ // Each routing's curve, in the order of `Route::ALL`.+ let mut curves = vec![vec![1.0f64; bins]; Route::ALL.len()];+ for key in keys {+ let (c, count) = design(+ key.shape.kind,+ key.shape.slope,+ self.fs,+ key.freq,+ key.gain,+ key.q,+ );+ let r = key.shape.route.index() as usize;+ for (g, &(c1, c2)) in curves[r].iter_mut().zip(&cos) {+ *g *= c.power(c1, c2).powi(count as i32).sqrt();+ }+ }+ let [stereo, left, right, mid, side] = [0, 1, 2, 3, 4].map(|r| &curves[r]);+ let of = |f: &dyn Fn(usize) -> f64| -> Vec<f64> { (0..bins).map(f).collect() };+ let tails = vec![vec![0.0; self.half]; self.channels];+ if self.channels == 1 {+ let ll = self.kernel(&of(&|k| stereo[k] * left[k] * right[k] * mid[k]));+ return Filters {+ rr: ll.clone(),+ rest: ll.clone(),+ ll,+ lr: None,+ rl: None,+ tails,+ };+ }+ // Left and right from the middle and the sides: each hears the+ // two's mean of itself and their half difference of the other.+ let same = |k: usize| 0.5 * (mid[k] + side[k]);+ let cross = |k: usize| 0.5 * (mid[k] - side[k]);+ let crossed = (0..bins).any(|k| cross(k).abs() > 1e-12);+ Filters {+ ll: self.kernel(&of(&|k| same(k) * left[k] * stereo[k])),+ rr: self.kernel(&of(&|k| same(k) * right[k] * stereo[k])),+ lr: crossed.then(|| self.kernel(&of(&|k| cross(k) * right[k] * stereo[k]))),+ rl: crossed.then(|| self.kernel(&of(&|k| cross(k) * left[k] * stereo[k]))),+ rest: if self.channels > 2 {+ self.kernel(stereo)+ } else {+ Vec::new()+ },+ tails,+ }+ }++ /// The block whose spectra (each channel's) are `x` through `f`: each+ /// channel's half of sound due out; `f`'s tails kept for the next.+ fn apply(plan: &Plan, half: usize, f: &mut Filters, x: &[Vec<Complex>]) -> Vec<Vec<f64>> {+ let times = |k: &[Complex], v: &[Complex]| -> Vec<Complex> {+ k.iter().zip(v).map(|(&a, &b)| a * b).collect()+ };+ let add = |mut a: Vec<Complex>, k: &Option<Vec<Complex>>, v: &[Complex]| {+ if let Some(k) = k {+ for ((y, &a2), &b) in a.iter_mut().zip(k.iter()).zip(v) {+ *y = *y + a2 * b;+ }+ }+ a+ };+ let count = x.len();+ (0..count)+ .map(|c| {+ let mut y = match (count, c) {+ (1, _) => times(&f.ll, &x[0]),+ (_, 0) => add(times(&f.ll, &x[0]), &f.lr, &x[1]),+ (_, 1) => add(times(&f.rr, &x[1]), &f.rl, &x[0]),+ _ => times(&f.rest, &x[c]),+ };+ plan.run(&mut y, true);+ let tail = &mut f.tails[c];+ let out = (0..half).map(|k| y[k].re + tail[k]).collect();+ for (t, v) in tail.iter_mut().zip(&y[half..]) {+ *t = v.re;+ }+ out+ })+ .collect()+ }++ /// The gathered half through the filters.+ fn block(&mut self) {+ let half = self.half;+ let spectra: Vec<Vec<Complex>> = self+ .input+ .iter()+ .map(|x| {+ let mut v = vec![Complex::ZERO; 2 * half];+ for (s, &x) in v.iter_mut().zip(x) {+ s.re = x;}+ self.plan.run(&mut v, false);v}).collect();- self.process_at_rate(&mut high);- for (c, (ch, v)) in channels.iter_mut().zip(&high).enumerate() {- for (i, out) in ch.iter_mut().enumerate() {- let mut y = 0.0;- for j in 0..k {- y = self- .down- .iter_mut()- .fold(v[i * k + j], |y, f| f.process(c, y));+ if self.old.is_none() && self.made != self.wanted {+ // The new filter, primed with what the last block would have+ // left it; the old one fades out.+ let mut new = self.filters(&self.wanted);+ Linear::apply(&self.plan, half, &mut new, &self.last);+ self.old = Some(std::mem::replace(&mut self.now, new));+ self.made = self.wanted.clone();+ self.fade = self.fade_len;+ }+ let mut out = Linear::apply(&self.plan, half, &mut self.now, &spectra);+ if let Some(old) = &mut self.old {+ let before = Linear::apply(&self.plan, half, old, &spectra);+ let len = self.fade_len.max(1) as f64;+ let mut fade = self.fade;+ for k in 0..half {+ let t = 1.0 - fade as f64 / len;+ for (o, b) in out.iter_mut().zip(&before) {+ o[k] = b[k] + t * (o[k] - b[k]);}- *out = y;+ fade = fade.saturating_sub(1);+ }+ self.fade = fade;+ if fade == 0 {+ self.old = None;+ }+ }+ self.output = out;+ self.last = spectra;+ }++ /// `channels` at its rate through it, its delay late.+ fn process(&mut self, channels: &mut [Vec<f64>]) {+ let n = channels.first().map_or(0, Vec::len);+ let mut i = 0;+ while i < n {+ let m = (self.half - self.at).min(n - i);+ let span = self.at..self.at + m;+ for (c, ch) in channels.iter_mut().enumerate().take(self.channels) {+ let samples = &mut ch[i..i + m];+ self.input[c][span.clone()].copy_from_slice(samples);+ samples.copy_from_slice(&self.output[c][span.clone()]);+ }+ self.at += m;+ i += m;+ if self.at == self.half {+ self.block();+ self.at = 0;}}}+}++/// Mono Below and Stereo Width at work on the left and the right: the+/// sides high-passed (faded in and out as it is turned on and off) and+/// scaled.+#[derive(Debug)]+struct Sides {+ on: Glide,+ freq: Glide,+ width: Glide,+ coeffs: Coeffs,+ memory: [f64; 2],+}- fn process_at_rate(&mut self, channels: &mut [Vec<f32>]) {- fn run(secs: &mut [Biquad], slot: usize, x: f32) -> f32 {- secs.iter_mut().fold(x, |v, s| s.process(slot, v))+impl Sides {+ fn new(s: &Settings, fs: f64) -> Sides {+ let freq = f64::from(s.mono_below);+ Sides {+ on: Glide::at(if s.mono_below_on() { 1.0 } else { 0.0 }),+ freq: Glide::at(freq),+ width: Glide::at(f64::from(s.width)),+ coeffs: mono_below_filter(fs, freq),+ memory: [0.0; 2],}+ }++ fn follow(&mut self, s: &Settings, fs: f64, steps: u32) {+ self.on.to(if s.mono_below_on() { 1.0 } else { 0.0 }, steps);+ self.freq.to(f64::from(s.mono_below), steps);+ self.width.to(f64::from(s.width), steps);+ if !self.freq.moving() {+ self.coeffs = mono_below_filter(fs, self.freq.now);+ }+ }++ fn process(&mut self, l: &mut [f64], r: &mut [f64], fs: f64) {+ let idle = |g: &Glide, v: f64| g.now == v && !g.moving();+ if idle(&self.on, 0.0) && idle(&self.width, 1.0) {+ self.memory = [0.0; 2];+ return;+ }+ let k = std::f64::consts::FRAC_1_SQRT_2;+ for (l, r) in l.iter_mut().zip(r.iter_mut()) {+ if self.freq.moving() {+ self.coeffs = mono_below_filter(fs, self.freq.next());+ }+ let on = self.on.next();+ let width = self.width.next();+ let m = (*l + *r) * k;+ let mut s = (*l - *r) * k;+ if on > 0.0 {+ let high = tick(&self.coeffs, &mut self.memory, s);+ s += on * (high - s);+ } else {+ self.memory = [0.0; 2];+ }+ s *= width;+ *l = (m + s) * k;+ *r = (m - s) * k;+ }+ }+}++/// The equalizer running: oversampled, its bands, its linear-phase+/// filters, a delay that makes its lateness whole samples of the rate,+/// Mono Below and Stereo Width at the top rate; the output gain after.+#[derive(Debug)]+pub(crate) struct Eq {+ rate: u32,+ channels: usize,+ settings: Option<Settings>,+ factor: usize,+ over: Oversampler,+ runs: Vec<Run>,+ linear: Option<Linear>,+ sides: Sides,+ gain: Glide,+ /// The delay's lines, each channel, and how long.+ lines: Vec<VecDeque<f64>>,+ pad: usize,+ high: Vec<Vec<f64>>,+}++impl Eq {+ pub(crate) fn new(rate: u32, channels: usize) -> Eq {+ let s = Settings::read(|i| {+ bv_timeline::EffectKind::ModernEq+ .params()+ .get(i)+ .map_or(0.0, |p| p.default)+ });+ let fs = f64::from(rate.max(1));+ Eq {+ rate: rate.max(1),+ channels: channels.max(1),+ settings: None,+ factor: 1,+ over: Oversampler::new(1),+ runs: Vec::new(),+ linear: None,+ sides: Sides::new(&s, fs),+ gain: Glide::at(1.0),+ lines: Vec::new(),+ pad: 0,+ high: Vec::new(),+ }+ }++ /// The bands' rate.+ fn fs(&self) -> f64 {+ f64::from(self.rate) * self.factor as f64+ }++ /// The linear-phase bands of `s` that are heard, as their filters are+ /// made.+ fn keys(s: &Settings) -> Vec<Key> {+ s.bands+ .iter()+ .filter(|b| b.active() && b.linear)+ .map(|b| Key {+ shape: Shape::of(b),+ freq: f64::from(b.freq),+ gain: f64::from(b.gain_db * s.scale),+ q: f64::from(b.q),+ })+ .collect()+ }++ /// The linear-phase filters `s` wants: none when no band in use is+ /// linear phase.+ fn want_linear(&mut self, s: &Settings) {+ if !s.bands.iter().any(|b| b.used && b.linear) {+ self.linear = None;+ } else {+ let keys = Eq::keys(s);+ match &mut self.linear {+ Some(l) if l.quality == s.quality && l.channels == self.channels => l.wanted = keys,+ _ => self.linear = Some(Linear::new(self.fs(), s.quality, self.channels, keys)),+ }+ }+ // Late by whole samples of the rate.+ let late = self.over.delay() + self.linear.as_ref().map_or(0, Linear::delay);+ let pad = (self.factor - late % self.factor) % self.factor;+ if pad != self.pad || self.lines.len() != self.channels {+ self.pad = pad;+ self.lines = vec![VecDeque::from(vec![0.0; pad]); self.channels];+ }+ }++ /// Everything anew for `s`: its rate, its bands where they are.+ fn rebuild(&mut self, s: &Settings) {+ self.factor = usize::from(s.oversampling.max(1));+ let fs = self.fs();+ self.over = Oversampler::new(self.factor);+ self.runs = s.bands.iter().map(|b| Run::new(b, s.scale, fs)).collect();+ self.sides = Sides::new(s, fs);+ self.gain = Glide::at(10f64.powf(f64::from(s.output_db) / 20.0));+ self.linear = None;+ self.lines.clear();+ self.want_linear(s);+ }+}++impl Own for Eq {+ fn set(&mut self, params: &[f32]) {+ let s = Settings::read(|i| params.get(i).copied().unwrap_or(0.0));+ let fresh = self+ .settings+ .is_none_or(|old| old.oversampling != s.oversampling);+ if fresh {+ self.rebuild(&s);+ } else {+ let fs = self.fs();+ let steps = (GLIDE * fs) as u32;+ for (run, b) in self.runs.iter_mut().zip(&s.bands) {+ run.follow(b, s.scale, fs, steps);+ }+ self.sides.follow(&s, fs, steps);+ self.gain.to(+ 10f64.powf(f64::from(s.output_db) / 20.0),+ (GLIDE * f64::from(self.rate)) as u32,+ );+ self.want_linear(&s);+ }+ self.settings = Some(s);+ }++ fn process(&mut self, channels: &mut [Vec<f32>]) {+ let Some(s) = self.settings else {+ return;+ };let n = channels.first().map_or(0, Vec::len);- let stereo = channels.len() >= 2;- let sides = stereo && (!self.mono_below.is_empty() || (self.width - 1.0).abs() > 1e-6);- for i in 0..n {- for (route, secs) in &mut self.bands {- match (*route, stereo) {- (Route::Stereo, _) => {- for (c, ch) in channels.iter_mut().enumerate() {- ch[i] = run(secs, c, ch[i]);- }- }- (Route::Left, true) => channels[0][i] = run(secs, 0, channels[0][i]),- (Route::Right, true) => channels[1][i] = run(secs, 1, channels[1][i]),- (Route::Mid | Route::Side, true) => {- let (l, r) = (channels[0][i], channels[1][i]);- let (mut m, mut s) = ((l + r) * 0.5, (l - r) * 0.5);- if *route == Route::Mid {- m = run(secs, 0, m);- } else {- s = run(secs, 1, s);- }- channels[0][i] = m + s;- channels[1][i] = m - s;- }- // One channel is the left, the right and the middle; it- // has no sides.- (Route::Side, false) => {}- (_, false) => channels[0][i] = run(secs, 0, channels[0][i]),- }+ if n == 0 {+ return;+ }+ if channels.len() != self.channels {+ self.channels = channels.len();+ self.rebuild(&s);+ }+ let fs = self.fs();+ let steps = (GLIDE * fs) as u32;+ let mut high = std::mem::take(&mut self.high);+ high.resize_with(channels.len(), Vec::new);+ for (c, ch) in channels.iter().enumerate() {+ self.over.raise(c, ch, &mut high[c]);+ }+ // The minimum-phase bands, in order.+ let stereo = high.len() >= 2;+ let k = std::f64::consts::FRAC_1_SQRT_2;+ let mid_side = |high: &mut [Vec<f64>]| {+ let (l, r) = high.split_at_mut(1);+ for (l, r) in l[0].iter_mut().zip(r[0].iter_mut()) {+ (*l, *r) = ((*l + *r) * k, (*l - *r) * k);}- if sides {- let (l, r) = (channels[0][i], channels[1][i]);- let m = (l + r) * 0.5;- let s = run(&mut self.mono_below, 0, (l - r) * 0.5) * self.width;- channels[0][i] = m + s;- channels[1][i] = m - s;+ };+ for run in &mut self.runs {+ if run.silent() && run.next.is_none() {+ continue;+ }+ match (run.shape.route, stereo) {+ (Route::Stereo, _) => {+ let mut slots: Vec<&mut [f64]> =+ high.iter_mut().map(Vec::as_mut_slice).collect();+ run.process(&mut slots, fs, steps);+ }+ (Route::Right, true) => run.process(&mut [&mut high[1][..]], fs, steps),+ (Route::Mid | Route::Side, true) => {+ mid_side(&mut high);+ let at = usize::from(run.shape.route == Route::Side);+ run.process(&mut [&mut high[at][..]], fs, steps);+ mid_side(&mut high);+ }+ // One channel has no sides.+ (Route::Side, false) => {}+ _ => run.process(&mut [&mut high[0][..]], fs, steps),}}- if (self.gain - 1.0).abs() > 1e-7 {- for ch in channels.iter_mut() {+ if let Some(l) = &mut self.linear {+ l.process(&mut high);+ }+ if self.pad > 0 {+ for (ch, line) in high.iter_mut().zip(&mut self.lines) {for v in ch.iter_mut() {- *v *= self.gain;+ line.push_back(*v);+ *v = line.pop_front().unwrap_or(0.0);+ }+ }+ }+ if stereo {+ let (l, r) = high.split_at_mut(1);+ self.sides.process(&mut l[0], &mut r[0], fs);+ }+ for (c, ch) in channels.iter_mut().enumerate() {+ self.over.lower(c, &mut high[c], ch);+ }+ self.high = high;+ if self.gain.moving() || self.gain.now != 1.0 {+ for i in 0..n {+ let g = self.gain.next() as f32;+ for ch in channels.iter_mut() {+ ch[i] *= g;}}}}++ fn latency(&self) -> usize {+ (self.over.delay() + self.linear.as_ref().map_or(0, Linear::delay) + self.pad)+ / self.factor.max(1)+ }}// The editor's watch: its FFT analyzer and peak meters.@@ -725,6 +1718,7 @@ mod tests {fn eq(set: impl FnOnce(&mut Settings)) -> Effect {let mut e = Effect::new(EffectKind::ModernEq);let mut s = Settings::of(&e);+ s.oversampling = 1;set(&mut s);s.write(&mut e);e@@ -737,66 +1731,29 @@ mod tests {kind,freq,gain_db,- q: 1.0,+ q: std::f32::consts::FRAC_1_SQRT_2,slope: 12,route: Route::Stereo,+ linear: false,}}- #[test]- fn oversampled_it_sounds_as_its_curves_say() {- // A peak at 18 kHz: oversampled, its curve near the top keeps its- // shape, and the sound follows it (a tone at the peak boosted by- // about its gain), Off as before.- for over in [1u8, 4] {- let e = eq(|s| {- s.bands[0] = band(BandType::Peaking, 18_000.0, 6.0);- s.oversampling = over;- });- assert_eq!(Settings::of(&e).oversampling, over);- let [l, _] = gain_at(&e, 18_000.0, [1.0, 1.0]);- assert!((l - 6.0).abs() < 0.6, "{over}: {l}");- // Lower down, nothing.- let [l, _] = gain_at(&e, 1_000.0, [1.0, 1.0]);- assert!(l.abs() < 0.2, "{over}: {l}");- }- }-- #[test]- fn the_analyzer_finds_a_tone_and_its_peaks() {- let tone = sine(1_000.0, 8192);- let freqs = [500.0, 1_000.0, 4_000.0];- let db = spectrum_db(&tone, RATE, &freqs);- // A 0.25 sine: about −12 dB at 1 kHz, far less elsewhere.- assert!((db[1] + 12.0).abs() < 1.5, "{db:?}");- assert!(db[0] < db[1] - 30.0 && db[2] < db[1] - 30.0, "{db:?}");- // The watch: what the mixer notes comes back once.- // (A chain no other test has.)- let owner = TapOwner::Chain(bv_timeline::FxChainId(987_654));- watch(Some((owner, 2)));- assert_eq!(watched_in(owner), Some(2));- assert_eq!(watched_in(TapOwner::Master), None);- let input = vec![tone.clone(), tone.clone()];- let output = vec![tone.iter().map(|v| v * 2.0).collect::<Vec<_>>(); 2];- note(RATE, &input, &output);- let a = take_analysis(&freqs).expect("heard");- assert!((a.peaks[0] - 0.25).abs() < 1e-3 && (a.peaks[1] - 0.5).abs() < 1e-3);- assert!(take_analysis(&freqs).is_none());- watch(None);- assert_eq!(watched_in(owner), None);+ fn running(e: &Effect, channels: usize) -> Eq {+ let mut q = Eq::new(RATE, channels);+ q.set(&crate::fx::params_of(e));+ q}/// The change (dB) `e` makes on a tone of `f` on each side, the tone/// on the left and the right times `sides`.fn gain_at(e: &Effect, f: f32, sides: [f32; 2]) -> [f32; 2] {- let x = sine(f, RATE as usize / 2);+ let x = sine(f, RATE as usize);let mut ch = vec![x.iter().map(|v| v * sides[0]).collect::<Vec<_>>(),x.iter().map(|v| v * sides[1]).collect(),];let before = [level_db(&ch[0]), level_db(&ch[1])];- let mut q = Eq::new(e, RATE, 2);- q.process(&mut ch);+ running(e, 2).process(&mut ch);[level_db(&ch[0]) - before[0], level_db(&ch[1]) - before[1]]}@@ -806,37 +1763,163 @@ mod tests {s.bands[2] = Band {route: Route::Side,slope: 24,+ linear: true,..band(BandType::HighPass, 120.0, 0.0)};- s.width = 1.5;+ s.bands[5] = band(BandType::BandStop, 3000.0, 0.0);+ s.width = 0.5;+ s.quality = 3;+ s.mono_below = 90.0;});let s = Settings::of(&e);assert_eq!(s.bands[2].kind, BandType::HighPass);assert_eq!(s.bands[2].route, Route::Side);- assert_eq!(s.bands[2].slope, 24);+ assert_eq!(s.bands[2].steepness(), 24);+ assert!(s.bands[2].linear && !s.bands[1].linear);+ assert_eq!(s.bands[5].kind, BandType::BandStop);+ assert_eq!((s.quality, s.mono_below), (3, 90.0));assert!(!s.bands[0].used && s.bands[0].on);- assert!((s.width - 1.5).abs() < 1e-6);- // A new one changes nothing.+ assert!((s.width - 0.5).abs() < 1e-6);+ // A new one changes nothing, oversampled twice.let flat = Settings::of(&Effect::new(EffectKind::ModernEq));assert!(flat.bands.iter().all(|b| !b.active()));+ assert_eq!(flat.oversampling, 2);+ assert!(!flat.mono_below_on());assert_eq!(total_db(&flat, RATE as f32, 1000.0), 0.0);}#[test]- fn butterworth_poles() {- let (odd, qs) = butterworth(3);- assert!(odd && (qs[0] - 1.0).abs() < 1e-5, "{qs:?}");- let (odd, qs) = butterworth(4);- assert!(!odd && (qs[0] - 0.5412).abs() < 1e-3 && (qs[1] - 1.3066).abs() < 1e-3);- let (_, qs) = butterworth(6);- assert!((qs[2] - 1.9319).abs() < 1e-3, "{qs:?}");+ fn slopes_snap_to_those_the_type_comes_in() {+ let with = |kind, slope| {+ Band {+ slope,+ ..band(kind, 1000.0, 0.0)+ }+ .steepness()+ };+ assert_eq!(with(BandType::HighPass, 18), 24);+ assert_eq!(with(BandType::LowPass, 30), 36);+ assert_eq!(with(BandType::BandPass, 36), 18);+ assert_eq!(with(BandType::LowShelf, 24), 12);+ assert_eq!(with(BandType::HighShelf, 6), 6);+ assert_eq!(with(BandType::Peaking, 6), 12);+ assert_eq!(with(BandType::BandStop, 24), 6);+ // Linear phase has no 6 dB shelves; the 6 dB passes have no Q.+ let shelf = Band {+ slope: 6,+ linear: true,+ ..band(BandType::LowShelf, 1000.0, 6.0)+ };+ assert_eq!(shelf.shape(), (BandType::LowShelf, 12));+ assert!(shelf.has_q());+ assert!(+ !Band {+ slope: 6,+ ..band(BandType::HighPass, 1000.0, 0.0)+ }+ .has_q()+ );}#[test]- fn a_peak_boosts_its_frequency_and_the_passes_cut_by_their_slopes() {- let e = eq(|s| s.bands[0] = band(BandType::Peaking, 1000.0, 6.0));- let g = gain_at(&e, 1000.0, [1.0, 1.0]);- assert!((g[0] - 6.0).abs() < 0.2, "{g:?}");+ fn the_curves_are_the_cookbooks() {+ let fs = RATE as f32;+ let at = |b: Band, f: f32| band_db(&b, 1.0, fs, f);+ // Passes with Q 0.707: 3 dB down at their frequency at 12 dB an+ // octave, 6 and 9 dB two and three alike; an octave below, about+ // their slope down.+ for (slope, down) in [(12u8, 3.0f32), (24, 6.0), (36, 9.0)] {+ let b = Band {+ slope,+ ..band(BandType::HighPass, 1000.0, 0.0)+ };+ assert!(+ (at(b, 1000.0) + down).abs() < 0.1,+ "{slope}: {}",+ at(b, 1000.0)+ );+ let octave = at(b, 250.0) - at(b, 500.0);+ assert!((octave + f32::from(slope)).abs() < 1.5, "{slope}: {octave}");+ }+ // First order: 3 dB at the frequency, 6 dB an octave.+ let b = Band {+ slope: 6,+ ..band(BandType::LowPass, 1000.0, 0.0)+ };+ assert!((at(b, 1000.0) + 3.01).abs() < 0.05);+ assert!((at(b, 2000.0) - at(b, 4000.0) - 6.0).abs() < 1.0);+ // A resonant pass: Q 2 stands 6 dB up at its frequency.+ let b = Band {+ q: 2.0,+ ..band(BandType::LowPass, 1000.0, 0.0)+ };+ assert!((at(b, 1000.0) - 6.02).abs() < 0.05);+ // A band pass's middle is Q (Q² and Q³ for two and three alike).+ for (slope, power) in [(6u8, 1), (12, 2), (18, 3)] {+ let b = Band {+ slope,+ q: 2.0,+ ..band(BandType::BandPass, 1000.0, 0.0)+ };+ let want = 20.0 * 2f32.log10() * power as f32;+ assert!(+ (at(b, 1000.0) - want).abs() < 0.05,+ "{slope}: {}",+ at(b, 1000.0)+ );+ }+ // A peak: its gain at its frequency.+ let b = Band {+ q: 1.0,+ ..band(BandType::Peaking, 1000.0, 6.0)+ };+ assert!((at(b, 1000.0) - 6.0).abs() < 0.01);+ assert!(at(b, 50.0).abs() < 0.1);+ // A band stop: nothing left at its frequency.+ let b = band(BandType::BandStop, 1000.0, 0.0);+ assert!(at(b, 1000.0) < -60.0 && at(b, 100.0).abs() < 0.3);+ // Shelves: the whole gain at the far end; a 12 dB one half (in+ // dB) at its frequency, a 6 dB one too, its corner moved so.+ for slope in [12u8, 6] {+ let b = Band {+ slope,+ ..band(BandType::LowShelf, 1000.0, 12.0)+ };+ assert!((at(b, 20.0) - 12.0).abs() < 0.3, "{slope}: {}", at(b, 20.0));+ assert!(+ (at(b, 1000.0) - 6.0).abs() < 0.3,+ "{slope}: {}",+ at(b, 1000.0)+ );+ assert!(at(b, 18_000.0).abs() < 0.5, "{slope}: {}", at(b, 18_000.0));+ let b = Band {+ slope,+ ..band(BandType::HighShelf, 1000.0, -12.0)+ };+ assert!(+ (at(b, 20_000.0) + 12.0).abs() < 0.6,+ "{slope}: {}",+ at(b, 20_000.0)+ );+ assert!(at(b, 30.0).abs() < 0.3);+ }+ // Global Scale scales the gain; below 0 a boost becomes a cut.+ let b = Band {+ q: 1.0,+ ..band(BandType::Peaking, 1000.0, 6.0)+ };+ assert!((band_db(&b, -1.0, fs, 1000.0) + 6.0).abs() < 0.01);+ }++ #[test]+ fn it_sounds_as_its_curves_say() {+ let e = eq(|s| {+ s.bands[0] = Band {+ q: 1.0,+ ..band(BandType::Peaking, 1000.0, 6.0)+ }+ });+ assert!((gain_at(&e, 1000.0, [1.0, 1.0])[0] - 6.0).abs() < 0.2);assert!(gain_at(&e, 100.0, [1.0, 1.0])[0].abs() < 0.3);// A bypassed band does nothing.let off = eq(|s| {@@ -846,57 +1929,126 @@ mod tests {}});assert!(gain_at(&off, 1000.0, [1.0, 1.0])[0].abs() < 0.01);- // A high pass at 1 kHz: an octave below, its slope down.- for slope in [6u8, 12, 18, 24, 36] {+ // Oversampled, a peak near the top keeps its shape and the sound+ // follows it.+ for over in [2u8, 4, 8] {let e = eq(|s| {s.bands[0] = Band {- slope,- ..band(BandType::HighPass, 1000.0, 0.0)- }+ q: 1.0,+ ..band(BandType::Peaking, 18_000.0, 6.0)+ };+ s.oversampling = over;});- let down = gain_at(&e, 500.0, [1.0, 1.0])[0];- assert!(- (down + f32::from(slope)).abs() < 2.5,- "{slope} dB/oct: {down}"- );- // At its frequency 3 dB down; well above it, nothing.- let at = gain_at(&e, 1000.0, [1.0, 1.0])[0];- assert!((at + 3.0).abs() < 0.5, "{slope}: {at}");- assert!(gain_at(&e, 8000.0, [1.0, 1.0])[0].abs() < 0.3);- }- // A band pass: nothing taken at its frequency, its sides steeper- // with its slope, its width kept.- let bp = |slope| {- eq(|s| {- s.bands[0] = Band {- slope,- q: 2.0,- ..band(BandType::BandPass, 1000.0, 0.0)- }- })- };- for slope in [6u8, 24] {- let s = Settings::of(&bp(slope));- let at = total_db(&s, RATE as f32, 1000.0);- assert!(at.abs() < 0.05, "{slope}: {at}");- // Half power about a third of an octave away (Q 2).- let edge = total_db(&s, RATE as f32, 1000.0 * 2f32.powf(0.36));- assert!((edge + 3.0).abs() < 0.6, "{slope}: {edge}");+ let [l, _] = gain_at(&e, 18_000.0, [1.0, 1.0]);+ assert!((l - 6.0).abs() < 0.6, "{over}: {l}");+ let [l, _] = gain_at(&e, 1_000.0, [1.0, 1.0]);+ assert!(l.abs() < 0.2, "{over}: {l}");+ }+ }++ #[test]+ fn oversampling_is_transparent_and_as_late_as_it_says() {+ for over in [1u8, 2, 4, 8] {+ let e = eq(|s| s.oversampling = over);+ let mut q = running(&e, 1);+ let late = q.latency();+ let mut x = vec![0.0f32; 4096];+ x[100] = 1.0;+ let mut ch = vec![x];+ q.process(&mut ch);+ let peak = ch[0]+ .iter()+ .enumerate()+ .max_by(|a, b| a.1.abs().total_cmp(&b.1.abs()))+ .map(|(i, _)| i);+ assert_eq!(peak, Some(100 + late), "{over}");+ // A tone well inside the band comes through whole.+ let g = gain_at(&e, 5_000.0, [1.0, 1.0])[0];+ assert!(g.abs() < 0.02, "{over}: {g}");+ }+ assert_eq!(running(&eq(|s| s.oversampling = 2), 1).latency(), 49);+ }++ #[test]+ fn values_glide_without_a_click() {+ // A peak's gain jumps from 0 to 12 dB as a tone plays: the sound+ // gets there in 50 ms, smoothly.+ let e0 = eq(|s| {+ s.bands[0] = Band {+ q: 1.0,+ ..band(BandType::Peaking, 1000.0, 0.0)+ }+ });+ let e1 = eq(|s| {+ s.bands[0] = Band {+ q: 1.0,+ ..band(BandType::Peaking, 1000.0, 12.0)+ }+ });+ let mut q = running(&e0, 1);+ let x = sine(1000.0, 24_000);+ let mut a = vec![x[..12_000].to_vec()];+ q.process(&mut a);+ q.set(&crate::fx::params_of(&e1));+ let mut b = vec![x[12_000..].to_vec()];+ q.process(&mut b);+ let out: Vec<f32> = a[0].iter().chain(&b[0]).copied().collect();+ let jump = out+ .windows(2)+ .map(|w| (w[1] - w[0]).abs())+ .fold(0f32, f32::max);+ // A 1 kHz sine of 0.25 · 4 moves at most about 0.13 a sample.+ assert!(jump < 0.15, "{jump}");+ let late = level_db(&out[12_000 + 4_800..]) - level_db(&x[..12_000]);+ assert!((late - 12.0).abs() < 0.3, "{late}");+ }++ #[test]+ fn linear_phase_bands_sound_alike_and_ring_both_ways() {+ let e = eq(|s| {+ s.bands[0] = Band {+ linear: true,+ q: 1.0,+ ..band(BandType::Peaking, 1000.0, 6.0)+ };+ s.quality = 0;+ });+ let g = gain_at(&e, 1000.0, [1.0, 1.0]);+ assert!((g[0] - 6.0).abs() < 0.3, "{g:?}");+ assert!(gain_at(&e, 100.0, [1.0, 1.0])[0].abs() < 0.3);+ // Its impulse response is even about its middle: linear phase.+ let mut q = running(&e, 1);+ let late = q.latency();+ let mut x = vec![0.0f32; 16_384];+ x[1000] = 1.0;+ let mut ch = vec![x];+ q.process(&mut ch);+ let mid = 1000 + late;+ for k in 1..200 {+ let (a, b) = (ch[0][mid - k], ch[0][mid + k]);+ assert!((a - b).abs() < 1e-4, "{k}: {a} {b}");}- let far = |slope| total_db(&Settings::of(&bp(slope)), RATE as f32, 125.0);- assert!(far(24) < far(6) - 30.0, "{} {}", far(6), far(24));- // The curve the interface draws agrees with what is heard.- let s = Settings::of(&eq(|s| s.bands[0] = band(BandType::Peaking, 1000.0, 6.0)));- assert!((total_db(&s, RATE as f32, 1000.0) - 6.0).abs() < 0.05);+ // A side band of linear phase leaves a centered tone alone.+ let e = eq(|s| {+ s.bands[0] = Band {+ linear: true,+ route: Route::Side,+ q: 1.0,+ ..band(BandType::Peaking, 1000.0, -24.0)+ };+ s.quality = 0;+ });+ let centered = gain_at(&e, 1000.0, [1.0, 1.0]);+ assert!(centered[0].abs() < 0.05, "{centered:?}");+ assert!(gain_at(&e, 1000.0, [1.0, 0.0])[0] < -3.0);}#[test]fn routing_mid_side_width_and_scale() {- // A cut of the sides leaves a centered tone alone; a tone on the- // left only is half sides and changes.let e = eq(|s| {s.bands[0] = Band {route: Route::Side,+ q: 1.0,..band(BandType::Peaking, 1000.0, -24.0)}});@@ -906,10 +2058,10 @@ mod tests {"{centered:?}");assert!(gain_at(&e, 1000.0, [1.0, 0.0])[0] < -3.0);- // A left band leaves the right channel alone.let e = eq(|s| {s.bands[0] = Band {route: Route::Left,+ q: 1.0,..band(BandType::Peaking, 1000.0, 6.0)}});@@ -922,7 +2074,10 @@ mod tests {// Global Scale −100 %: the boost becomes a cut; 200 % doubles it.let scaled = |scale| {eq(|s| {- s.bands[0] = band(BandType::Peaking, 1000.0, 6.0);+ s.bands[0] = Band {+ q: 1.0,+ ..band(BandType::Peaking, 1000.0, 6.0)+ };s.scale = scale;})};@@ -930,12 +2085,12 @@ mod tests {assert!((gain_at(&scaled(2.0), 1000.0, [1.0, 1.0])[0] - 12.0).abs() < 0.3);// Mono Below: low sides go, the middle stays.let e = eq(|s| s.mono_below = 200.0);- assert!(gain_at(&e, 60.0, [1.0, -1.0])[0] < -30.0);+ assert!(gain_at(&e, 30.0, [1.0, -1.0])[0] < -15.0);assert!(gain_at(&e, 60.0, [1.0, 1.0])[0].abs() < 0.05);- assert!(gain_at(&e, 2000.0, [1.0, -1.0])[0].abs() < 0.1);+ assert!(gain_at(&e, 4000.0, [1.0, -1.0])[0].abs() < 0.1);let s = Settings::of(&e);- let curve = mono_below_curve(&s, RATE as f32, &[60.0, 2000.0]).unwrap();- assert!(curve[0] < -30.0 && curve[1].abs() < 0.1, "{curve:?}");+ let curve = mono_below_curve(&s, RATE as f32, &[30.0, 4000.0]).unwrap();+ assert!(curve[0] < -15.0 && curve[1].abs() < 0.1, "{curve:?}");// Output gain.let e = eq(|s| s.output_db = -6.0);assert!((gain_at(&e, 1000.0, [1.0, 1.0])[0] + 6.0).abs() < 0.01);@@ -943,28 +2098,57 @@ mod tests {#[test]fn one_channel_and_surround() {- // Mono: a side band does nothing, the others apply.let mut ch = vec![sine(1000.0, 24_000)];let before = level_db(&ch[0]);let e = eq(|s| {s.bands[0] = Band {route: Route::Side,+ q: 1.0,..band(BandType::Peaking, 1000.0, -12.0)};s.bands[1] = Band {route: Route::Mid,+ q: 1.0,..band(BandType::Peaking, 1000.0, 6.0)};});- Eq::new(&e, RATE, 1).process(&mut ch);+ running(&e, 1).process(&mut ch);assert!((level_db(&ch[0]) - before - 6.0).abs() < 0.2);- // 5.1: a stereo band on every channel, each with its own state.let x = sine(1000.0, 24_000);let mut six = vec![x.clone(); 6];- let e = eq(|s| s.bands[0] = band(BandType::Peaking, 1000.0, 6.0));- Eq::new(&e, RATE, 6).process(&mut six);+ let e = eq(|s| {+ s.bands[0] = Band {+ q: 1.0,+ ..band(BandType::Peaking, 1000.0, 6.0)+ }+ });+ running(&e, 6).process(&mut six);for c in &six {assert!((level_db(c) - level_db(&x) - 6.0).abs() < 0.2);}}++ #[test]+ fn the_analyzer_finds_a_tone_and_its_peaks() {+ let tone = sine(1_000.0, 8192);+ let freqs = [500.0, 1_000.0, 4_000.0];+ let db = spectrum_db(&tone, RATE, &freqs);+ // A 0.25 sine: about −12 dB at 1 kHz, far less elsewhere.+ assert!((db[1] + 12.0).abs() < 1.5, "{db:?}");+ assert!(db[0] < db[1] - 30.0 && db[2] < db[1] - 30.0, "{db:?}");+ // The watch: what the mixer notes comes back once.+ // (A chain no other test has.)+ let owner = TapOwner::Chain(bv_timeline::FxChainId(987_654));+ watch(Some((owner, 2)));+ assert_eq!(watched_in(owner), Some(2));+ assert_eq!(watched_in(TapOwner::Master), None);+ let input = vec![tone.clone(), tone.clone()];+ let output = vec![tone.iter().map(|v| v * 2.0).collect::<Vec<_>>(); 2];+ note(RATE, &input, &output);+ let a = take_analysis(&freqs).expect("heard");+ assert!((a.peaks[0] - 0.25).abs() < 1e-3 && (a.peaks[1] - 0.5).abs() < 1e-3);+ assert!(take_analysis(&freqs).is_none());+ watch(None);+ assert_eq!(watched_in(owner), None);+ }}diff --git a/crates/mixer/src/prerender.rs b/crates/mixer/src/prerender.rsnew file mode 100644index 0000000..95e2ace--- /dev/null+++ b/crates/mixer/src/prerender.rs@@ -0,0 +1,244 @@+//! Events whose effects change the sound's length — Time Stretch, Pitch+//! Shift, Gapper/Snipper, Vibrato… — play, as VEGAS's do, their sound+//! made through the whole chain: the event's sound is gathered and runs+//! through its media's and its own effects all at once, as Non-Real-Time+//! Event FX makes it, and the event plays that from its start, keeping its+//! length (what the effects made past its end is cut, what they did not+//! make is silence). While it plays the sound is made on a thread of its+//! own, the newest one made playing meanwhile; elsewhere (a render) at+//! once.++use std::collections::HashMap;+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::{Arc, Mutex};++use bv_core::{SampleRate, Tick};+use bv_timeline::{AudioQuality, Clip, ClipId, Effect, MediaInfo, Tempo};++use crate::{apply_switches, dsp, first_sample_at_or_after, loop_segments, read_clip, stretch};++/// How much sound is read, and goes through the chain, at a time.+const BLOCK: usize = 4096;++/// Blocks an event may go unasked before its sound is let go.+const KEPT_FOR: u64 = 2_000;++/// A sound being made: where it lands, and the flag that stops it.+type Job = (Arc<Mutex<Option<Arc<Sound>>>>, Arc<AtomicBool>);++/// An event's sound through its chain: a buffer a channel, from its start.+pub(crate) type Sound = Vec<Vec<f32>>;++/// What an event's sound is made of: the media, the event (its place on+/// the timeline, its fades and its level left out: they come after), the+/// effects, the rate, the resampling and the tempo.+#[derive(Clone, Debug, PartialEq)]+struct Key {+ media: MediaInfo,+ clip: Clip,+ effects: Vec<Effect>,+ rate: SampleRate,+ quality: AudioQuality,+ tempo: Tempo,+}++#[derive(Debug, Default)]+struct Made {+ key: Option<Key>,+ /// The newest sound finished (it plays while a newer one is made).+ ready: Option<Arc<Sound>>,+ job: Option<Job>,+ /// The block it was last asked for in.+ seen: u64,+}++/// The events' sounds made through their chains.+#[derive(Debug, Default)]+pub(crate) struct Prerenders {+ made: HashMap<ClipId, Made>,+ /// Made on threads of their own (while playing), or at once.+ pub(crate) live: bool,+}++impl Prerenders {+ /// `clip`'s sound through `effects` (its media's and its own), made+ /// anew when what it is made of changed; `None` while none was made.+ #[allow(clippy::too_many_arguments)]+ pub(crate) fn sound(+ &mut self,+ media: &MediaInfo,+ clip: &Clip,+ effects: &[&Effect],+ rate: SampleRate,+ quality: AudioQuality,+ tempo: Tempo,+ block: u64,+ ) -> Option<Arc<Sound>> {+ let mut placeless = clip.clone();+ placeless.start = Tick::ZERO;+ placeless.fade_in = Tick::ZERO;+ placeless.fade_out = Tick::ZERO;+ placeless.level = 1.0;+ let mut media = media.clone();+ media.markers.clear();+ let key = Key {+ media,+ clip: placeless,+ effects: effects.iter().map(|e| (*e).clone()).collect(),+ rate,+ quality,+ tempo,+ };+ let made = self.made.entry(clip.id).or_default();+ made.seen = block;+ if made.key.as_ref() != Some(&key) {+ if let Some((_, stop)) = made.job.take() {+ stop.store(true, Ordering::Relaxed);+ }+ made.key = Some(key.clone());+ let slot = Arc::new(Mutex::new(None));+ let stop = Arc::new(AtomicBool::new(false));+ let (to, flag) = (slot.clone(), stop.clone());+ let work = move || {+ if let Some(sound) = render(&key, &flag)+ && let Ok(mut s) = to.lock()+ {+ *s = Some(Arc::new(sound));+ }+ };+ if self.live {+ let started = std::thread::Builder::new()+ .name("bv-event-fx".into())+ .spawn(work);+ if started.is_err() {+ made.key = None;+ return made.ready.clone();+ }+ } else {+ work();+ }+ made.job = Some((slot, stop));+ }+ let done = made+ .job+ .as_ref()+ .and_then(|(slot, _)| slot.try_lock().ok().and_then(|s| s.clone()));+ if let Some(sound) = done {+ made.ready = Some(sound);+ made.job = None;+ }+ made.ready.clone()+ }++ /// Lets go of the sounds of events not asked for in a while.+ pub(crate) fn forget_old(&mut self, block: u64) {+ self.made.retain(|_, m| {+ let keep = block.saturating_sub(m.seen) < KEPT_FOR;+ if !keep && let Some((_, stop)) = &m.job {+ stop.store(true, Ordering::Relaxed);+ }+ keep+ });+ }++ pub(crate) fn clear(&mut self) {+ self.forget_old(u64::MAX);+ }+}++/// The sound `key` makes: the event read as it plays, its channel+/// switches, then its effects — those between the length-changing ones a+/// stretch at a time, their lateness taken back — each on all of it.+/// `None` when stopped or unreadable.+fn render(key: &Key, stop: &AtomicBool) -> Option<Sound> {+ let (media, clip, rate) = (&key.media, &key.clip, key.rate);+ let mut reader = bv_media::open_audio_stream(media, clip.audio_stream).ok()?;+ let channels = usize::from(media.audio?.channels).max(1);+ let s0 = first_sample_at_or_after(rate, clip.start);+ let s1 = first_sample_at_or_after(rate, clip.end());+ let keep_pitch = ((clip.preserve_pitch && (clip.rate - 1.0).abs() > 1e-9) || clip.pitch != 0.0)+ && clip.reverse.is_none()+ && clip.velocity().is_none();+ let mut shifts = stretch::Shifts::default();+ let mut planes: Sound = vec![Vec::with_capacity((s1 - s0).max(0) as usize); channels];+ let mut pos = s0;+ while pos < s1 {+ if stop.load(Ordering::Relaxed) {+ return None;+ }+ let n = ((s1 - pos) as usize).min(BLOCK);+ let mut part = vec![vec![0.0f32; n]; channels];+ for (a, b, shift) in loop_segments(clip, rate, pos, pos + n as i64, media.duration) {+ let len = (b - a) as usize;+ let got = if keep_pitch {+ stretch::read(reader.as_mut(), &mut shifts, clip, rate, a, len, shift)+ } else {+ read_clip(reader.as_mut(), clip, rate, a, len, key.quality, shift)+ };+ let Ok(got) = got else {+ continue;+ };+ for (d, g) in part.iter_mut().zip(&got) {+ for (o, v) in d[(a - pos) as usize..].iter_mut().zip(g) {+ *o = *v;+ }+ }+ }+ apply_switches(clip, &mut part);+ for (p, q) in planes.iter_mut().zip(part) {+ p.extend_from_slice(&q);+ }+ pos += n as i64;+ }+ let mut stretch: Vec<&Effect> = Vec::new();+ for e in key+ .effects+ .iter()+ .filter(|e| e.kind.is_audio() && e.enabled)+ {+ if stop.load(Ordering::Relaxed) {+ return None;+ }+ if e.kind.works_offline() {+ through(&mut stretch, &mut planes, rate.0, key.tempo);+ if let Some(out) = crate::fx::offline::render(e, rate.0, std::mem::take(&mut planes)) {+ planes = out;+ }+ } else {+ stretch.push(e);+ }+ }+ through(&mut stretch, &mut planes, rate.0, key.tempo);+ Some(planes)+}++/// `planes` through the real-time effects gathered in `effects` (then+/// emptied), as long as they were: what the chain holds back comes out+/// and its lateness is taken back.+fn through(effects: &mut Vec<&Effect>, planes: &mut Sound, rate: u32, tempo: Tempo) {+ if effects.is_empty() {+ return;+ }+ let mut chain = dsp::Chain::default();+ chain.set_tempo(tempo);+ chain.sync(effects, rate, planes.len(), false);+ let late = chain.latency();+ let len = planes.first().map_or(0, Vec::len);+ for p in planes.iter_mut() {+ p.resize(len + late, 0.0);+ }+ let mut at = 0;+ while at < len + late {+ let end = (at + BLOCK).min(len + late);+ let mut part: Sound = planes.iter().map(|p| p[at..end].to_vec()).collect();+ chain.process(&mut part);+ for (p, q) in planes.iter_mut().zip(part) {+ p[at..end].copy_from_slice(&q);+ }+ at = end;+ }+ for p in planes.iter_mut() {+ p.drain(..late);+ }+ effects.clear();+}diff --git a/crates/ofx/src/value.rs b/crates/ofx/src/value.rsindex 135bdc3..171d4a3 100644--- a/crates/ofx/src/value.rs+++ b/crates/ofx/src/value.rs@@ -193,7 +193,8 @@ pub enum Interp {Slow,#[default]Smooth,- /// The S turned around: fast at both ends, slow in the middle.+ /// The S turned around: fast at both ends, level in the middle+ /// (4t³ − 6t² + 3t, as VEGAS's).Sharp,/// Keeps the key's value until the next key.Hold,@@ -215,9 +216,7 @@ impl Interp {Interp::Fast => 1.0 - (1.0 - t) * (1.0 - t),Interp::Slow => t * t,Interp::Smooth => t * t * (3.0 - 2.0 * t),- // The smoothstep's inverse, exact at the ends.- Interp::Sharp if t <= 0.0 || t >= 1.0 => t,- Interp::Sharp => 0.5 - ((1.0 - 2.0 * t).asin() / 3.0).sin(),+ Interp::Sharp => t * (3.0 + t * (4.0 * t - 6.0)),Interp::Hold => 0.0,// Without handles, a straight line.Interp::Bezier | Interp::BezierSplit => t,diff --git a/crates/render/src/effects.rs b/crates/render/src/effects.rsindex a1705b8..e61eb74 100644--- a/crates/render/src/effects.rs+++ b/crates/render/src/effects.rs@@ -270,18 +270,8 @@ pub fn apply(img: &mut ImageRgbaF32, e: &Effect, scale: f32) {}// Audio effects do not touch the picture; plug-ins' go through the// scene's plug-ins (`plugin`).- EffectKind::Gain- | EffectKind::Eq3- | EffectKind::HighPass- | EffectKind::LowPass- | EffectKind::Compressor- | EffectKind::Limiter- | EffectKind::NoiseGate- | EffectKind::Delay- | EffectKind::Reverb- | EffectKind::ModernEq- | EffectKind::Vst- | EffectKind::Plugin => {}+ // (the audio effects, all of them).+ _ => {}}}diff --git a/crates/render/src/layer.rs b/crates/render/src/layer.rsindex 76a1fc1..3ad2fb3 100644--- a/crates/render/src/layer.rs+++ b/crates/render/src/layer.rs@@ -2,6 +2,7 @@//! (posição, escala, rotação, corte) e amostragem bilinear.use bv_core::ImageRgbaF32;+use bv_timeline::pancrop::Placement;use bv_timeline::scene::fit_rect_par;use bv_timeline::{RenderQuality, Transform};@@ -335,6 +336,158 @@ pub fn place_par(out}+/// A pixel of `src`, the edge's past its edges.+#[inline]+fn held(src: &ImageRgbaF32, x: i64, y: i64) -> [f32; 4] {+ let x = x.clamp(0, src.width as i64 - 1);+ let y = y.clamp(0, src.height as i64 - 1);+ src.data[(y * src.width as i64 + x) as usize]+}++/// A pixel of `src` for a turned or mirrored picture, as VEGAS's renders show:+/// past its left and bottom edges nothing, past its others one pixel more of+/// the edge's and then nothing.+#[inline]+fn open(src: &ImageRgbaF32, x: i64, y: i64) -> [f32; 4] {+ if x < 0 || y >= src.height as i64 || x > src.width as i64 || y < -1 {+ [0.0; 4]+ } else {+ held(src, x, y)+ }+}++#[inline]+fn bilinear_by(+ src: &ImageRgbaF32,+ u: f32,+ v: f32,+ tex: impl Fn(&ImageRgbaF32, i64, i64) -> [f32; 4],+) -> [f32; 4] {+ let (x0, y0) = (u.floor(), v.floor());+ let (fx, fy) = (u - x0, v - y0);+ let (x, y) = (x0 as i64, y0 as i64);+ let (a, b) = (tex(src, x, y), tex(src, x + 1, y));+ let (c, d) = (tex(src, x, y + 1), tex(src, x + 1, y + 1));+ std::array::from_fn(|i| {+ let top = a[i] + (b[i] - a[i]) * fx;+ let bottom = c[i] + (d[i] - c[i]) * fx;+ top + (bottom - top) * fy+ })+}++#[inline]+fn bicubic_held(src: &ImageRgbaF32, u: f32, v: f32) -> [f32; 4] {+ let (x0, y0) = (u.floor(), v.floor());+ let (wx, wy) = (catmull_rom(u - x0), catmull_rom(v - y0));+ let (x0, y0) = (x0 as i64, y0 as i64);+ let mut out = [0.0f32; 4];+ for (j, ky) in wy.iter().enumerate() {+ for (i, kx) in wx.iter().enumerate() {+ let p = held(src, x0 - 1 + i as i64, y0 - 1 + j as i64);+ let k = kx * ky;+ for c in 0..4 {+ out[c] += p[c] * k;+ }+ }+ }+ // The negative lobes may overshoot: keep a valid premultiplied pixel.+ out[3] = out[3].clamp(0.0, 1.0);+ for c in &mut out[..3] {+ *c = c.max(0.0);+ }+ out+}++/// `src` (a picture of the media, of any size) where a Pan/Crop places it on+/// a frame `w` × `h`: its edges hard without a turn or a mirror, else as soft+/// as the pixels they cross. The card's `place_hard` and `place_soft` kernels+/// do the same.+pub fn place_box(+ src: &ImageRgbaF32,+ w: u32,+ h: u32,+ place: &Placement,+ quality: RenderQuality,+) -> ImageRgbaF32 {+ let mut out = ImageRgbaF32::transparent(w, h);+ if place.empty {+ return out;+ }+ let [x0, y0, x1, y1] = place.pixels((w, h));+ let (x0, x1) = (x0 as usize, x1 as usize);+ let (y0, y1) = (y0 as usize, y1 as usize);+ let (mut m, _) = place.in_picture([f64::from(src.width), f64::from(src.height)]);+ // A pixel for a pixel: as it is.+ let whole = |v: f64| (v - v.round()).abs() < 1e-9;+ if place.to_box.is_none()+ && m[0] == 1.0+ && m[1] == 0.0+ && m[3] == 0.0+ && m[4] == 1.0+ && whole(m[2])+ && whole(m[5])+ {+ let (dx, dy) = (m[2].round() as i64, m[5].round() as i64);+ par::for_each_row(&mut out.data, w as usize, |y, row| {+ if y >= y0 && y < y1 {+ for (x, px) in row.iter_mut().enumerate().take(x1).skip(x0) {+ *px = held(src, x as i64 + dx, y as i64 + dy);+ }+ }+ });+ return out;+ }+ // Large reductions go through 2 × 2 averages first (Good and Best).+ let mut reduced;+ let mut src = src;+ if matches!(quality, RenderQuality::Good | RenderQuality::Best) {+ while m[0].hypot(m[1]) >= 2.0 && m[3].hypot(m[4]) >= 2.0 && src.width > 1 {+ reduced = half_size(src);+ src = &reduced;+ m = place+ .in_picture([f64::from(src.width), f64::from(src.height)])+ .0;+ }+ }+ let [ux, uy, u0, vx, vy, v0] = m.map(|v| v as f32);+ let (sw, sh) = (src.width as f32, src.height as f32);+ let soft = place.soft_edges();+ par::for_each_pixel(&mut out.data, w as usize, |x, y, px| {+ if x < x0 || x >= x1 || y < y0 || y >= y1 {+ return;+ }+ let (cx, cy) = (x as f32 + 0.5, y as f32 + 0.5);+ let u = ux * cx + uy * cy + u0 - 0.5;+ let v = vx * cx + vy * cy + v0 - 0.5;+ match &soft {+ None => {+ *px = match quality {+ RenderQuality::Draft => held(src, u.round() as i64, v.round() as i64),+ RenderQuality::Preview | RenderQuality::Good => bilinear_by(src, u, v, held),+ RenderQuality::Best => bicubic_held(src, u, v),+ };+ }+ Some(edges) => {+ let c = edges.share(x as f64 + 0.5, y as f64 + 0.5) as f32;+ if c <= 0.0 {+ return;+ }+ let picture = match quality {+ RenderQuality::Draft => open(src, u.round() as i64, v.round() as i64),+ RenderQuality::Best+ if u >= 1.0 && v >= 1.0 && u <= sw - 3.0 && v <= sh - 3.0 =>+ {+ bicubic_held(src, u, v)+ }+ _ => bilinear_by(src, u, v, open),+ };+ *px = picture.map(|p| p * c);+ }+ }+ });+ out+}+#[cfg(test)]mod tests {use super::*;diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rsindex 40a5d47..0f31469 100644--- a/crates/render/src/lib.rs+++ b/crates/render/src/lib.rs@@ -28,7 +28,7 @@ pub use bv_color::convert::set_threads;pub use bv_media::VideoPool;pub use bv_timeline::scene::{Rect, fit_rect, fit_rect_par};pub use layer::place_par;-pub use layer::{place, place_with};+pub use layer::{place, place_box, place_with};/// Cor mostrada no lugar de mídia que não pôde ser lida ("mídia offline").pub const OFFLINE: [f32; 4] = [0.25, 0.0, 0.02, 1.0];@@ -685,7 +685,7 @@ fn adjusted(scene: &FrameScene<'_>, m: &MediaLayer<'_>, below: &ImageRgbaF32) ->framed_at: 0,media_size: (img.width, img.height),media_fx_scale: 1.0,- par: 1.0,+ place: m.place,quality: m.quality,};for (k, e) in m.effects.iter().enumerate() {@@ -757,7 +757,6 @@ fn media_layer(}src = Arc::new(img);}- let tf = &m.transform;// The media's effects work on its own picture; then the event's// Pan/Crop frames it, and the event's effects work on the framed// picture (VEGAS's default: Pan/Crop first in the event's chain).@@ -765,11 +764,10 @@ fn media_layer(let (src, media_fx_scale) = if framed_at == 0 {(src, 1.0)} else {- let mut src = reduce_for_display(scene, &src, tf.scale, m.par);+ let mut src = reduce_for_display(&src, &m.placement);// Effect sizes are in the project's pixels: in the source's here.- let (pw, ph) = scene.project_size;- let fit = fit_rect_par(src.width, src.height, m.par, pw, ph);- let fx_scale = src.height as f32 / (fit.h * tf.scale.max(1e-4));+ let per_line = m.placement.picture_per_pixel(src.width, src.height).1;+ let fx_scale = (per_line as f32 * scene.scale).max(1e-4);for (k, e) in m.effects[..framed_at].iter().enumerate() {match scene.media_call(m, k, fx_scale, None) {Some(call) => effects::plugin(scene, &call, &mut src),@@ -779,7 +777,7 @@ fn media_layer(}(Arc::new(src), fx_scale)};- let mut img = layer::place_par(&src, scene.width, scene.height, tf, m.quality, m.par);+ let mut img = layer::place_box(&src, scene.width, scene.height, &m.placement, m.quality);// Reduce Interlace Flicker: on the framed picture, before the event's// effects.if m.clip.reduce_flicker {@@ -788,9 +786,15 @@ fn media_layer(// Its Pan/Crop masks, framed as the picture is: they cut what shows of// it, or (Apply to FX) keep its effects inside them, the picture// without them elsewhere.- let mask = m- .mask_picture(src.width, src.height)- .map(|c| layer::place_par(&c, scene.width, scene.height, tf, m.quality, m.par));+ let mask = m.mask_picture(src.width, src.height).map(|c| {+ layer::place_box(+ &c,+ scene.width,+ scene.height,+ &m.placement.hard(),+ m.quality,+ )+ });let unaffected = mask.as_ref().filter(|_| m.clip.mask.as_ref().is_some_and(|k| k.apply_to_fx))@@ -799,7 +803,7 @@ fn media_layer(framed_at,media_size: (src.width, src.height),media_fx_scale,- par: m.par,+ place: m.place,quality: m.quality,};for (k, e) in m.effects.iter().enumerate().skip(framed_at) {@@ -869,18 +873,9 @@ pub fn offline_color(scene: &FrameScene<'_>) -> [f32; 4] {/// Halves the source while it is more than twice the size it shows at, so/// effects do not work on pixels nobody sees.-fn reduce_for_display(- scene: &FrameScene<'_>,- src: &ImageRgbaF32,- scale: f32,- par: f32,-) -> ImageRgbaF32 {- let fit = fit_rect_par(src.width, src.height, par, scene.width, scene.height);+fn reduce_for_display(src: &ImageRgbaF32, place: &bv_timeline::pancrop::Placement) -> ImageRgbaF32 {let mut img = src.clone();- while img.width as f32 >= fit.w * scale * 2.0- && img.height as f32 >= fit.h * scale * 2.0- && img.width > 1- {+ while place.reduces(img.width, img.height) && img.width > 1 {img = layer::half_size(&img);}img@@ -1452,7 +1447,7 @@ mod tests {);let (w, h) = info.video- .map(|v| (v.width as f32, v.height as f32))+ .map(|v| (f64::from(v.width), f64::from(v.height))).unwrap();let m = p.add_media(info);let id = p.insert_media(m, Tick::ZERO, Some(v), None).unwrap()[0];@@ -1503,9 +1498,15 @@ mod tests {&p.settings,));let clip = p.insert_media(m, Tick::ZERO, Some(v), None).unwrap()[0];- let c = p.clip_mut(clip).unwrap();- c.transform.scale = 0.5;- c.transform.x = -0.25;+ p.set_clip_framing(+ clip,+ &bv_timeline::Transform {+ scale: 0.5,+ x: -0.25,+ ..bv_timeline::Transform::default()+ },+ )+ .unwrap();let alpha = |p: &Project, x: u32| {render_frame_on(p, Tick::ZERO, 32, 18, &mut VideoPool::new(), [0.0; 4]).pixel(x, 9)[3]};diff --git a/crates/timeline/src/audio_fx.rs b/crates/timeline/src/audio_fx.rsnew file mode 100644index 0000000..3c8b5fa--- /dev/null+++ b/crates/timeline/src/audio_fx.rs@@ -0,0 +1,3296 @@+//! BananaV's audio effects that follow VEGAS's: each one's parameters — in+//! the order its processing reads them, with VEGAS's ranges and defaults —+//! and its factory presets. The processing is `bv_mixer`'s `fx`.++use crate::fx::{Graph, OFF, ON, ParamSpec, Show, at_least, either, join};++/// A factory preset: its name and every parameter's value, in order.+pub type Preset = (&'static str, &'static [f32]);++/// The factory presets of `k`, when it is one of these effects.+pub fn presets(k: crate::EffectKind) -> Option<&'static [Preset]> {+ use crate::EffectKind as K;+ Some(match k {+ K::Volume => volume::PRESETS,+ K::Pan => pan::PRESETS,+ K::SmoothEnhance => smooth_enhance::PRESETS,+ K::NoiseGateFx => noise_gate::PRESETS,+ K::TrackNoiseGate => track_noise_gate::PRESETS,+ K::SimpleDelay => simple_delay::PRESETS,+ K::Dither => dither::PRESETS,+ K::ResonantFilter => resonant_filter::PRESETS,+ K::ParametricEq => parametric_eq::PRESETS,+ K::Chorus => chorus::PRESETS,+ K::FlangeWahWah => flange_wah_wah::PRESETS,+ K::ReverbFx => reverb::PRESETS,+ K::TrackCompressor => track_compressor::PRESETS,+ K::TrackEq => track_eq::PRESETS,+ K::ParagraphicEq => paragraphic_eq::PRESETS,+ K::MultiTapDelay => multi_tap_delay::PRESETS,+ K::MultiBandDynamics => multi_band_dynamics::PRESETS,+ K::ExpressDelay => express_delay::PRESETS,+ K::ExpressDistortion => express_distortion::PRESETS,+ K::ExpressEqualization => express_equalization::PRESETS,+ K::ExpressNoiseGate => express_noise_gate::PRESETS,+ K::ExpressChorus => express_chorus::PRESETS,+ K::ExpressFlangeWahWah => express_flange_wah_wah::PRESETS,+ K::ExpressDynamics => express_dynamics::PRESETS,+ K::ExpressStutter => express_stutter::PRESETS,+ K::ExpressAmplitudeModulation => express_amplitude_modulation::PRESETS,+ K::ExpressGraphicEq => express_graphic_eq::PRESETS,+ K::ExpressReverb => express_reverb::PRESETS,+ K::AmplitudeModulation => amplitude_modulation::PRESETS,+ K::GraphicDynamics => graphic_dynamics::PRESETS,+ K::Distortion => distortion::PRESETS,+ K::GraphicEq => graphic_eq::PRESETS,+ K::WaveHammer => wave_hammer::PRESETS,+ K::StudioGate => efx_gate::PRESETS,+ K::DeEsser => efx_deesser::PRESETS,+ K::StudioLimiter => efx_limiter::PRESETS,+ K::TremoloPan => efx_tremolo_pan::PRESETS,+ K::TubeStage => efx_tube_stage::PRESETS,+ K::VocalStrip => efx_vocal_strip::PRESETS,+ K::StudioCompressor => efx_compressor::PRESETS,+ K::Phaser => efx_phaser::PRESETS,+ K::ChorusFlanger => efx_chorus_flanger::PRESETS,+ K::StudioReverb => efx_reverb::PRESETS,+ K::StereoDelay => efx_stereo_delay::PRESETS,+ K::TimeStretch => time_stretch::PRESETS,+ K::ExpressTimeStretch => express_time_stretch::PRESETS,+ K::PitchShift => pitch_shift::PRESETS,+ K::GapperSnipper => gapper_snipper::PRESETS,+ K::Vibrato => vibrato::PRESETS,+ K::ExpressAudioRestoration => express_audio_restoration::PRESETS,+ _ => return None,+ })+}++/// Volume: one linear gain, 0 to 2 (+6.02 dB), shown in dB.+pub mod volume {+ use super::*;++ pub const GAIN: usize = 0;++ pub const PARAMS: &[ParamSpec] = &[ParamSpec::num("Volume", 0.0, 2.0, 1.0)+ .show(Show::GainDb)+ .decimals(2)];++ pub const PRESETS: &[Preset] = &[];+}++/// Pan: a stereo balance that moves one channel into the other, −1 to 1,+/// positive to the left.+pub mod pan {+ use super::*;++ pub const PAN: usize = 0;++ pub const PARAMS: &[ParamSpec] = &[ParamSpec::num("Pan", -1.0, 1.0, 0.0).show(Show::Pan)];++ pub const PRESETS: &[Preset] = &[];+}++/// Smooth/Enhance: one first-order filter a channel, `Operation` from −5+/// (smoothest) to 5 (most enhanced), 0 nothing.+pub mod smooth_enhance {+ use super::*;++ pub const OPERATION: usize = 0;++ pub const PARAMS: &[ParamSpec] = &[ParamSpec::num("Operation", -5.0, 5.0, 0.0).decimals(0)];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[0.0]),+ ("Boost high frequencies", &[3.0]),+ ];+}++/// The noise gates' parameters, in dB and milliseconds.+pub mod gate {+ pub const THRESHOLD: usize = 0;+ pub const ATTACK: usize = 1;+ pub const RELEASE: usize = 2;+}++/// Noise Gate: silence below a threshold, opened after the attack and+/// closed after the release.+pub mod noise_gate {+ use super::*;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Threshold level", -80.0, 0.0, -20.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Attack time", 1.0, 500.0, 3.0)+ .unit("ms")+ .decimals(0)+ .log(),+ ParamSpec::num("Release time", 1.0, 5000.0, 100.0)+ .unit("ms")+ .decimals(0)+ .log(),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[-20.0, 3.0, 100.0]),+ ("Strong beats only", &[-6.0, 1.0, 300.0]),+ ("Long decay time", &[-38.0, 10.0, 1000.0]),+ ("Noise gate 1", &[-60.0, 10.0, 500.0]),+ ("Noise gate 2", &[-32.0, 1.0, 500.0]),+ ("Slow attack", &[-40.0, 300.0, 1000.0]),+ ("Slow attack (ACX)", &[-40.0, 300.0, 2500.0]),+ ];+}++/// Track Noise Gate: the same gate, its attack from 0 ms.+pub mod track_noise_gate {+ use super::*;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Threshold level", -80.0, 0.0, -80.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Attack time", 0.0, 500.0, 3.0)+ .unit("ms")+ .decimals(0),+ ParamSpec::num("Release time", 1.0, 5000.0, 100.0)+ .unit("ms")+ .decimals(0)+ .log(),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[-80.0, 3.0, 100.0]),+ ("Strong beats only", &[-6.0, 1.0, 300.0]),+ ("Long decay time", &[-38.0, 10.0, 1000.0]),+ ("Noise gate 1", &[-60.0, 10.0, 500.0]),+ ("Noise gate 2", &[-32.0, 1.0, 500.0]),+ ("Slow attack", &[-40.0, 300.0, 1000.0]),+ ("Slow attack (ACX)", &[-40.0, 300.0, 2500.0]),+ ];+}++/// Tempo sync: times that follow the project's tempo, a note (or+/// measures) times a multiplier.+pub mod tempo {+ use crate::Tempo;++ /// The notes a time can follow, shortest first.+ pub const NOTES: &[&str] = &[+ "64th Note Triplet",+ "64th Note",+ "Dotted 64th Note",+ "32nd Note Triplet",+ "32nd Note",+ "Dotted 32nd Note",+ "16th Note Triplet",+ "16th Note",+ "Dotted 16th Note",+ "8th Note Triplet",+ "8th Note",+ "Dotted 8th Note",+ "Quarter Note Triplet",+ "Quarter Note",+ "Dotted Quarter Note",+ "Half Note Triplet",+ "Half Note",+ "Dotted Half Note",+ ];++ /// [`NOTES`] and the measure, last.+ pub const NOTES_OR_MEASURE: &[&str] = &[+ "64th Note Triplet",+ "64th Note",+ "Dotted 64th Note",+ "32nd Note Triplet",+ "32nd Note",+ "Dotted 32nd Note",+ "16th Note Triplet",+ "16th Note",+ "Dotted 16th Note",+ "8th Note Triplet",+ "8th Note",+ "Dotted 8th Note",+ "Quarter Note Triplet",+ "Quarter Note",+ "Dotted Quarter Note",+ "Half Note Triplet",+ "Half Note",+ "Dotted Half Note",+ "Measures",+ ];++ /// The place of the quarter note, the default.+ pub const QUARTER: f32 = 13.0;+ /// The place of the measure in [`NOTES_OR_MEASURE`].+ pub const MEASURE: f32 = 18.0;++ /// Each note's length in quarter notes.+ const QUARTERS: [f64; 18] = [+ 1.0 / 24.0,+ 1.0 / 16.0,+ 3.0 / 32.0,+ 1.0 / 12.0,+ 1.0 / 8.0,+ 3.0 / 16.0,+ 1.0 / 6.0,+ 1.0 / 4.0,+ 3.0 / 8.0,+ 1.0 / 3.0,+ 1.0 / 2.0,+ 3.0 / 4.0,+ 2.0 / 3.0,+ 1.0,+ 3.0 / 2.0,+ 4.0 / 3.0,+ 2.0,+ 3.0,+ ];++ /// How long note `note` of [`NOTES_OR_MEASURE`] lasts at `tempo`, in+ /// seconds (past the notes, a measure).+ pub fn seconds(note: f32, tempo: &Tempo) -> f64 {+ let per_beat = tempo.beat_note.max(1) as f64;+ // A quarter note: a beat, times 4 over the note that gets the beat.+ let quarter = 60.0 / tempo.beats_per_minute.max(1e-3) * per_beat / 4.0;+ let quarters = match QUARTERS.get(note.round().max(0.0) as usize) {+ Some(&q) => q,+ None => tempo.beats_per_measure.max(1) as f64 * 4.0 / per_beat,+ };+ quarter * quarters+ }+}++/// Simple Delay: one echo, or many (fed back) fading by the decay time;+/// each time in seconds or a note of the project's tempo.+pub mod simple_delay {+ use super::*;++ pub const DRY: usize = 0;+ pub const WET: usize = 1;+ pub const TIME: usize = 2;+ pub const SYNC: usize = 3;+ pub const MULTIPLIER: usize = 4;+ pub const NOTE: usize = 5;+ pub const MULTIPLE: usize = 6;+ pub const DECAY: usize = 7;+ pub const DECAY_SYNC: usize = 8;+ pub const DECAY_MULTIPLIER: usize = 9;+ pub const DECAY_NOTE: usize = 10;++ const TIMED: &[(u8, u32)] = &[(SYNC as u8, OFF)];+ const SYNCED: &[(u8, u32)] = &[(SYNC as u8, ON)];+ const FED_BACK: &[(u8, u32)] = &[(MULTIPLE as u8, ON)];+ const DECAY_TIMED: &[(u8, u32)] = &[(MULTIPLE as u8, ON), (DECAY_SYNC as u8, OFF)];+ const DECAY_SYNCED: &[(u8, u32)] = &[(MULTIPLE as u8, ON), (DECAY_SYNC as u8, ON)];++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Dry out", -80.0, 0.0, -6.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Delay out", -80.0, 0.0, -6.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Delay time", 0.001, 5.0, 0.1)+ .unit("s")+ .decimals(3)+ .log()+ .when(TIMED),+ ParamSpec::switch("Tempo sync delay", 0.0),+ ParamSpec::num("Delay multiplier", 0.001, 4.0, 1.0)+ .decimals(3)+ .log()+ .when(SYNCED),+ ParamSpec::choice("Delay note", 0.0, tempo::NOTES, tempo::QUARTER).when(SYNCED),+ ParamSpec::switch("Multiple delays (feedback)", 0.0),+ ParamSpec::num("Decay time", 0.1, 20.0, 0.1)+ .unit("s")+ .decimals(1)+ .log()+ .when(DECAY_TIMED),+ ParamSpec::switch("Tempo sync decay", 0.0).when(FED_BACK),+ ParamSpec::num("Decay multiplier", 0.001, 32.0, 1.0)+ .decimals(3)+ .log()+ .when(DECAY_SYNCED),+ ParamSpec::choice("Decay note", 0.0, tempo::NOTES_OR_MEASURE, tempo::MEASURE)+ .when(DECAY_SYNCED),+ ];++ pub const PRESETS: &[Preset] = &[+ (+ "Default all parameters",+ &[-6.0, -6.0, 0.1, 0.0, 1.0, 13.0, 0.0, 0.1, 0.0, 1.0, 18.0],+ ),+ (+ "Echo chamber",+ &[-9.0, -3.0, 0.4, 0.0, 1.0, 13.0, 1.0, 2.0, 0.0, 1.0, 18.0],+ ),+ (+ "Slap-back echo",+ &[-9.0, -12.0, 0.4, 0.0, 1.0, 13.0, 0.0, 2.0, 0.0, 1.0, 18.0],+ ),+ (+ "Grand Canyon",+ &[-4.0, -14.0, 1.0, 0.0, 1.0, 13.0, 1.0, 3.0, 0.0, 1.0, 18.0],+ ),+ (+ "Shift selection forwards (select one channel only)",+ &[-80.0, 0.0, 1.0, 0.0, 1.0, 13.0, 0.0, 2.0, 0.0, 1.0, 18.0],+ ),+ (+ "Pseudo-stereo (select one channel only)",+ &[-80.0, 0.0, 0.01, 0.0, 1.0, 13.0, 0.0, 0.1, 0.0, 1.0, 18.0],+ ),+ ];+}++/// Dither: the sound rounded to the levels of a bit depth, with a little+/// noise added first so the rounding's error is noise, not distortion,+/// and that noise moved where it is heard least.+pub mod dither {+ use super::*;++ pub const DEPTH: usize = 0;+ pub const NOISE: usize = 1;+ pub const SHAPING: usize = 2;++ /// Each depth's bits, in the order of its options.+ pub const BITS: [u32; 7] = [8, 12, 16, 18, 20, 24, 32];++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::choice(+ "Quantization depth",+ 0.0,+ &[+ "8 bit", "12 bit", "16 bit", "18 bit", "20 bit", "24 bit", "32 bit",+ ],+ 2.0,+ ),+ ParamSpec::choice(+ "Dither type",+ 0.0,+ &[+ "None",+ "Half Rectangular",+ "Rectangular",+ "Triangular",+ "Highpass Triangular",+ "Gaussian",+ ],+ 1.0,+ ),+ ParamSpec::choice(+ "Noise shaping",+ 0.0,+ &["Off", "High-pass contour", "Equal loudness contour"],+ 0.0,+ ),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[2.0, 1.0, 0.0]),+ ("Dither for 8-bit (low sample rate)", &[0.0, 3.0, 0.0]),+ ("Dither for 8-bit", &[0.0, 4.0, 1.0]),+ ("Dither for 16-bit (low sample rate)", &[2.0, 3.0, 2.0]),+ ("Dither for 16-bit", &[2.0, 4.0, 2.0]),+ ];+}++/// Resonant Filter: a low-, band- or high-pass with a resonance that+/// rings at its frequency, of the second or fourth order.+pub mod resonant_filter {+ use super::*;++ pub const FREQUENCY: usize = 0;+ pub const RESONANCE: usize = 1;+ pub const MIX: usize = 2;+ pub const TYPE: usize = 3;+ pub const ORDER: usize = 4;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Frequency", 20.0, 20000.0, 20000.0)+ .unit("Hz")+ .decimals(0)+ .log(),+ ParamSpec::num("Resonance", 0.0, 1.0, 0.0)+ .show(Show::Percent)+ .decimals(1),+ ParamSpec::num("Wet / Dry", 0.0, 1.0, 1.0)+ .show(Show::Percent)+ .decimals(1),+ ParamSpec::choice(+ "Filter type",+ 0.0,+ &["Low Pass", "Band Pass", "High Pass"],+ 0.0,+ ),+ ParamSpec::choice("Filter order", 0.0, &["Second", "Fourth"], 0.0),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[20000.0, 0.0, 1.0, 0.0, 0.0]),+ ("Bass Hum", &[135.0, 0.9, 1.0, 1.0, 1.0]),+ ("Big Boom Maker", &[60.0, 1.0, 1.0, 0.0, 0.0]),+ ("Chest Punch", &[150.0, 0.75, 1.0, 0.0, 0.0]),+ ("Ear Sugar", &[5750.0, 0.333, 1.0, 1.0, 0.0]),+ ("Hank on Escape Route", &[880.0, 0.25, 1.0, 1.0, 1.0]),+ ("High Howl", &[1500.0, 1.0, 1.0, 0.0, 0.0]),+ ("High Pierce", &[3600.0, 1.0, 1.0, 0.0, 0.0]),+ ("Light Chime", &[900.0, 0.75, 1.0, 0.0, 0.0]),+ ("Low Howl", &[150.0, 1.0, 1.0, 0.0, 0.0]),+ ("Mid Howl", &[500.0, 1.0, 1.0, 0.0, 0.0]),+ ("Muffler", &[350.0, 0.0, 1.0, 0.0, 0.0]),+ ("PipSqueaking", &[6000.0, 1.0, 1.0, 2.0, 1.0]),+ ("Ringing Chime", &[900.0, 1.0, 1.0, 1.0, 0.0]),+ ("Rumbly Growl", &[75.0, 0.5, 1.0, 0.0, 1.0]),+ ("Slicing Vocals", &[3000.0, 0.05, 1.0, 1.0, 1.0]),+ (+ "Teenage Late-Night Radio by the Bed",+ &[1500.0, 0.2, 1.0, 2.0, 0.0],+ ),+ ];+}++/// Parametric EQ: one shelf, band-pass or notch/boost, drawn as a+/// frequency response and applied as a long FIR filter through FFTs —+/// the longer, the finer in the lows.+pub mod parametric_eq {+ use super::*;++ pub const OUTPUT: usize = 0;+ pub const AMOUNT: usize = 1;+ pub const STYLE: usize = 2;+ pub const FREQUENCY: usize = 3;+ pub const WIDTH: usize = 4;+ pub const ACCURACY: usize = 5;++ /// Each accuracy's FFT length, in the order of its options.+ pub const FFT: [usize; 3] = [256, 1024, 4096];++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Output gain", -60.0, 20.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Amount", -60.0, 20.0, -4.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::choice(+ "Filter style",+ 0.0,+ &[+ "Low-frequency shelf",+ "High-frequency shelf",+ "Band-pass",+ "Band-notch/boost",+ ],+ 2.0,+ ),+ ParamSpec::num("Frequency", 20.0, 20000.0, 650.0)+ .unit("Hz")+ .decimals(0)+ .log(),+ ParamSpec::num("Width", 0.1, 5.0, 1.0)+ .unit("oct.")+ .decimals(1),+ ParamSpec::choice(+ "Accuracy",+ 0.0,+ &[+ "Low (fast, good for high bands)",+ "Medium (great for mid and high bands)",+ "High (slow, great for all bands)",+ ],+ 1.0,+ ),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[0.0, -4.0, 2.0, 650.0, 1.0, 1.0]),+ ("200 Hz high-pass", &[0.0, -15.0, 0.0, 200.0, 0.4, 2.0]),+ (+ "Hiss removal (cut frequencies above 6 kHz by 40 dB)",+ &[0.0, -40.0, 1.0, 6000.0, 0.5, 2.0],+ ),+ ("Phone line effect", &[0.0, -25.0, 2.0, 800.0, 2.0, 1.0]),+ (+ "Remove frequencies around 1500 Hz by 25 dB",+ &[0.0, -25.0, 3.0, 1500.0, 1.0, 2.0],+ ),+ ];+}++/// Chorus: one to three modulated delays in a row, each adding its copy+/// of the sound slightly out of tune and late.+pub mod chorus {+ use super::*;++ pub const INPUT: usize = 0;+ pub const DRY: usize = 1;+ pub const WET: usize = 2;+ pub const INVERT: usize = 3;+ pub const INVERT_FEEDBACK: usize = 4;+ pub const SIZE: usize = 5;+ pub const RATE: usize = 6;+ pub const DEPTH: usize = 7;+ pub const FEEDBACK: usize = 8;+ pub const DELAY: usize = 9;+ pub const ATTENUATE: usize = 10;+ pub const CUTOFF: usize = 11;+ pub const SYNC: usize = 12;+ pub const MULTIPLIER: usize = 13;+ pub const PERIOD: usize = 14;++ const FREE: &[(u8, u32)] = &[(SYNC as u8, OFF)];+ const SYNCED: &[(u8, u32)] = &[(SYNC as u8, ON)];+ const CUT: &[(u8, u32)] = &[(ATTENUATE as u8, ON)];++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Input gain", -60.0, 0.0, 0.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Dry out", -60.0, 0.0, -6.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Chorus out", -60.0, 0.0, -4.4)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::switch("Invert chorus phase", 0.0),+ ParamSpec::switch("Invert feedback phase", 0.0),+ ParamSpec::num("Chorus size", 1.0, 3.0, 3.0).decimals(0),+ ParamSpec::num("Modulation rate", 0.001, 20.0, 0.8)+ .unit("Hz")+ .decimals(3)+ .log()+ .when(FREE),+ ParamSpec::num("Modulation depth", 0.01, 1.0, 0.03)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Feedback", 0.0, 1.0, 0.0)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Chorus out delay", 0.1, 100.0, 40.0)+ .unit("ms")+ .decimals(1)+ .log(),+ ParamSpec::switch("Attenuate high frequencies", 0.0),+ ParamSpec::num("Attenuation frequency", 100.0, 10000.0, 5000.0)+ .unit("Hz")+ .decimals(0)+ .log()+ .when(CUT),+ ParamSpec::switch("Tempo sync", 0.0),+ ParamSpec::num("Period multiplier", 0.001, 32.0, 1.0)+ .decimals(3)+ .log()+ .when(SYNCED),+ ParamSpec::choice(+ "Modulation period",+ 0.0,+ tempo::NOTES_OR_MEASURE,+ tempo::MEASURE,+ )+ .when(SYNCED),+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[0.0, -6.0, -4.4, 0.0, 0.0, 3.0, 0.8, 0.03, 0.0, 40.0, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Fast flange 1", &[0.0, -3.4, -3.4, 0.0, 0.0, 1.0, 0.7, 1.0, 0.32, 1.2, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Fast flange 2", &[0.0, -5.7, -5.7, 0.0, 0.0, 1.0, 2.3, 0.16, 0.7, 5.0, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Slow flange 1", &[0.0, -4.9, -5.7, 0.0, 0.0, 1.0, 0.5, 0.75, 0.5, 0.8, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Slow flange 2", &[-2.0, -8.0, -4.4, 0.0, 0.0, 1.0, 0.5, 1.0, 0.6, 1.2, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Slow flange 3", &[0.0, -8.0, -3.1, 0.0, 0.0, 1.0, 0.7, 0.8, 0.2, 0.5, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Slow flange 4", &[0.0, -4.4, -3.1, 0.0, 0.0, 1.0, 0.2, 0.75, 0.0, 0.6, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Chorus/vibrato 1", &[0.0, -3.7, -3.7, 0.0, 0.0, 1.0, 0.5, 1.0, 0.57, 10.0, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Chorus/vibrato 2", &[0.0, -3.7, -6.9, 0.0, 0.0, 1.0, 7.0, 0.08, 0.37, 29.2, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Chorus 1", &[0.0, -6.0, -4.4, 0.0, 0.0, 3.0, 0.8, 0.03, 0.0, 40.0, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Chorus 2", &[0.0, -6.0, -6.0, 0.0, 0.0, 2.0, 0.5, 0.08, 0.15, 30.0, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Chorus 3", &[0.0, -6.0, -6.0, 0.0, 0.0, 3.0, 0.5, 0.08, 0.16, 40.5, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Chorus 4", &[0.0, -4.9, -5.2, 0.0, 0.0, 2.0, 0.5, 0.26, 0.26, 9.0, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Chorus 5", &[0.0, -4.9, -7.7, 0.0, 0.0, 2.0, 2.1, 0.12, 0.37, 29.2, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Cheap TV", &[-2.0, 0.0, 0.0, 1.0, 0.0, 2.0, 0.1, 1.0, 0.0, 0.1, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Echo-vibrato 1", &[0.0, -9.2, -14.0, 0.0, 0.0, 2.0, 6.0, 0.08, 0.15, 100.0, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Echo-vibrato 2", &[0.0, -9.2, -6.0, 0.0, 0.0, 1.0, 6.0, 0.05, 0.0, 100.0, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Echo-vibrato 3", &[0.0, -9.2, -8.0, 0.0, 0.0, 3.0, 20.0, 0.01, 0.5, 100.0, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Echo-vibrato 4", &[0.0, -9.2, -6.0, 0.0, 0.0, 1.0, 20.0, 0.01, 0.5, 100.0, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Vibrato-verb 1", &[0.0, -9.2, -14.0, 0.0, 0.0, 1.0, 5.0, 0.01, 0.6, 100.0, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Vibrato-verb 2", &[0.0, -9.2, -9.1, 0.0, 0.0, 3.0, 7.0, 0.01, 0.5, 100.0, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Vibrato-verb 3", &[0.0, -9.2, -6.0, 0.0, 0.0, 3.0, 5.6, 0.03, 0.6, 100.0, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ("Hard flange", &[-2.0, -3.1, -3.1, 0.0, 0.0, 1.0, 0.5, 0.75, 0.9, 0.8, 0.0, 5000.0, 0.0, 1.0, 18.0]),+ ];+}++/// Flange/Wah-wah: a flange (a short modulated delay fed back), a phaser+/// (an all-pass swept up and down, mixed with the sound) or a wah-wah+/// (the same sweep as a band-pass).+pub mod flange_wah_wah {+ use super::*;++ pub const EFFECT: usize = 0;+ pub const DRY: usize = 1;+ pub const WET: usize = 2;+ pub const RATE: usize = 3;+ pub const DEPTH: usize = 4;+ pub const CENTER: usize = 5;+ pub const RESONANCE: usize = 6;+ pub const SYNC: usize = 7;+ pub const MULTIPLIER: usize = 8;+ pub const PERIOD: usize = 9;++ const FREE: &[(u8, u32)] = &[(SYNC as u8, OFF)];+ const SYNCED: &[(u8, u32)] = &[(SYNC as u8, ON)];++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::choice("Effect", 0.0, &["Flange", "Phaser", "Wah-wah"], 0.0),+ ParamSpec::num("Dry out", -80.0, 12.0, -80.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Wet out", -80.0, 12.0, 0.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Rate", 0.001, 20.0, 10.0)+ .unit("Hz")+ .decimals(3)+ .log()+ .when(FREE),+ ParamSpec::num("Depth", 0.01, 1.0, 0.1)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Center frequency", 100.0, 5000.0, 100.0)+ .unit("Hz")+ .decimals(0)+ .log(),+ ParamSpec::num("Resonance", 0.01, 1.0, 0.01)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::switch("Tempo sync", 0.0),+ ParamSpec::num("Period multiplier", 0.001, 32.0, 1.0)+ .decimals(3)+ .log()+ .when(SYNCED),+ ParamSpec::choice("Period", 0.0, tempo::NOTES_OR_MEASURE, tempo::MEASURE).when(SYNCED),+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[0.0, -80.0, 0.0, 10.0, 0.1, 100.0, 0.01, 0.0, 1.0, 18.0]),+ ("Phaser 1", &[1.0, -80.0, 0.0, 0.5, 0.5, 1000.0, 0.5, 0.0, 1.0, 18.0]),+ ("Phaser 2", &[1.0, -80.0, 0.0, 4.5, 0.5, 1000.0, 0.5, 0.0, 1.0, 18.0]),+ ("Phaser 3", &[1.0, -80.0, 0.0, 10.0, 0.5, 2000.0, 0.4, 0.0, 1.0, 18.0]),+ ("Wah-wah 1", &[2.0, -80.0, 0.0, 1.0, 0.5, 1000.0, 0.5, 0.0, 1.0, 18.0]),+ ("Wah-wah 2", &[2.0, -80.0, 0.0, 2.0, 0.5, 1000.0, 0.8, 0.0, 1.0, 18.0]),+ ("Wah-wah 3", &[2.0, -15.0, 0.0, 0.2, 0.5, 500.0, 1.0, 0.0, 1.0, 18.0]),+ ("Wah-wah 4", &[2.0, -80.0, 0.0, 0.5, 0.7, 3000.0, 0.5, 0.0, 1.0, 18.0]),+ ("Wah-wah 5", &[2.0, -80.0, 0.0, 10.0, 0.5, 2000.0, 0.5, 0.0, 1.0, 18.0]),+ ("1 Hz flange", &[0.0, -5.0, -6.0, 1.0, 0.85, 100.0, 0.01, 0.0, 1.0, 18.0]),+ ("Fast flange", &[0.0, -6.0, -6.0, 5.0, 0.5, 100.0, 0.01, 0.0, 1.0, 18.0]),+ ("Slow flange", &[0.0, -3.0, -2.0, 0.1, 1.0, 100.0, 0.01, 0.0, 1.0, 18.0]),+ ("Slow flange 2", &[0.0, -2.5, -2.5, 0.5, 0.85, 100.0, 0.01, 0.0, 1.0, 18.0]),+ ("Warble 1", &[0.0, -5.0, -5.0, 20.0, 0.85, 100.0, 0.01, 0.0, 1.0, 18.0]),+ ("Warble 2", &[0.0, -5.0, -5.0, 20.0, 0.2, 100.0, 0.01, 0.0, 1.0, 18.0]),+ ];+}++/// Reverb: a room of comb filters (19 of them, by mode) with three early+/// reflections (10 styles), its decay time, pre-delay and bass and high+/// cuts.+pub mod reverb {+ use super::*;++ pub const MODE: usize = 0;+ pub const DRY: usize = 1;+ pub const WET: usize = 2;+ pub const EARLY: usize = 3;+ pub const STYLE: usize = 4;+ pub const DECAY: usize = 5;+ pub const PREDELAY: usize = 6;+ pub const BASS: usize = 7;+ pub const BASS_FREQ: usize = 8;+ pub const HIGH: usize = 9;+ pub const HIGH_FREQ: usize = 10;++ const BASS_CUT: &[(u8, u32)] = &[(BASS as u8, ON)];+ const HIGH_CUT: &[(u8, u32)] = &[(HIGH as u8, ON)];++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::choice(+ "Reverberation mode",+ 0.0,+ &[+ "Rich Hall",+ "Wide Open Hall",+ "Concert Hall",+ "Deep Hall",+ "Long Hall",+ "Medium Hall 1",+ "Medium Hall 2",+ "Warm Space",+ "Cavernous Space",+ "Bright Corridor",+ "Bright Small Room",+ "Bright Medium Room",+ "Medium Room",+ "Subtle Ambience",+ "Live Ambience",+ "Warm Ambience",+ "Plate 1",+ "Plate 2 Ringy",+ "Metal Tank",+ ],+ 0.0,+ ),+ ParamSpec::num("Dry out", -80.0, 0.0, 0.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Reverb out", -80.0, 0.0, -35.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Early out", -80.0, 0.0, -20.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::choice(+ "Early reflection style",+ 0.0,+ &[+ "Mode 1 - 6 ms",+ "Mode 2 - 8 ms",+ "Mode 3 - 10 ms",+ "Mode 4 - 16 ms",+ "Mode 5 - 20 ms",+ "Mode 6 - 36 ms",+ "Mode 7 - 8 ms pan right",+ "Mode 8 - 8 ms pan left",+ "Mode 9 - 16 ms pan right",+ "Mode 10 - 16 ms pan left",+ ],+ 3.0,+ ),+ ParamSpec::num("Decay time", 0.5, 5.0, 2.5)+ .unit("s")+ .decimals(1),+ ParamSpec::num("Pre-delay", 0.0, 200.0, 30.0)+ .unit("ms")+ .decimals(0),+ ParamSpec::switch("Attenuate bass frequencies", 1.0),+ ParamSpec::num("Bass attenuation frequency", 10.0, 5000.0, 20.0)+ .unit("Hz")+ .decimals(0)+ .log()+ .when(BASS_CUT),+ ParamSpec::switch("Attenuate high frequencies", 1.0),+ ParamSpec::num("High attenuation frequency", 100.0, 15000.0, 12000.0)+ .unit("Hz")+ .decimals(0)+ .log()+ .when(HIGH_CUT),+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[0.0, 0.0, -35.0, -20.0, 3.0, 2.5, 30.0, 1.0, 20.0, 1.0, 12000.0]),+ ("Bright hall", &[0.0, 0.0, -35.0, -20.0, 3.0, 2.5, 30.0, 1.0, 20.0, 1.0, 12000.0]),+ ("Cathedral", &[8.0, 0.0, -24.0, -20.0, 5.0, 3.0, 70.0, 1.0, 20.0, 1.0, 7000.0]),+ ("Dense room", &[10.0, 0.0, -25.0, -20.0, 1.0, 0.6, 1.0, 1.0, 20.0, 1.0, 5000.0]),+ ("Long hall", &[4.0, 0.0, -35.0, -30.0, 2.0, 2.5, 60.0, 1.0, 20.0, 1.0, 5000.0]),+ ("Medium hall", &[2.0, 0.0, -30.0, -30.0, 1.0, 1.2, 5.0, 1.0, 20.0, 1.0, 5000.0]),+ ("Medium room", &[13.0, 0.0, -20.0, -80.0, 0.0, 0.5, 1.0, 1.0, 20.0, 1.0, 5000.0]),+ ("Metal tank", &[18.0, 0.0, -16.0, -20.0, 5.0, 2.5, 10.0, 1.0, 400.0, 1.0, 3000.0]),+ ("Plate", &[16.0, 0.0, -35.0, -20.0, 3.0, 2.0, 15.0, 1.0, 20.0, 0.0, 5000.0]),+ ("Sewer", &[18.0, 0.0, -16.0, -20.0, 3.0, 2.0, 15.0, 1.0, 20.0, 1.0, 10000.0]),+ ("Small hall", &[2.0, 0.0, -24.0, -20.0, 1.0, 1.0, 10.0, 1.0, 20.0, 1.0, 8000.0]),+ ("Very long hall", &[4.0, 0.0, -41.8, -30.0, 5.0, 5.0, 45.0, 1.0, 100.0, 1.0, 10000.0]),+ ];+}++/// Track Compressor: a compressor (to a limiter) with input and output+/// gains, automatic gain compensation and a rounded corner.+pub mod track_compressor {+ use super::*;++ pub const INPUT: usize = 0;+ pub const OUTPUT: usize = 1;+ pub const THRESHOLD: usize = 2;+ pub const RATIO: usize = 3;+ pub const ATTACK: usize = 4;+ pub const RELEASE: usize = 5;+ pub const AUTO_GAIN: usize = 6;+ pub const SMOOTH: usize = 7;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Input gain", -60.0, 20.0, 0.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Output gain", -60.0, 20.0, 0.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Threshold", -60.0, 0.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Amount (x:1)", 1.0, 500.0, 1.0)+ .decimals(1)+ .log(),+ ParamSpec::num("Attack", 0.0, 500.0, 15.0)+ .unit("ms")+ .decimals(0),+ ParamSpec::num("Release", 0.0, 5000.0, 250.0)+ .unit("ms")+ .decimals(0),+ ParamSpec::switch("Auto gain compensation", 1.0),+ ParamSpec::switch("Smooth saturation", 0.0),+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[0.0, 0.0, 0.0, 1.0, 15.0, 250.0, 1.0, 0.0]),+ ("Soft Limiter", &[0.0, 0.0, -6.0, 25.0, 0.0, 250.0, 0.0, 1.0]),+ ("1.5:1 compression starting at -24 dB", &[0.0, 0.0, -24.0, 1.5, 15.0, 250.0, 0.0, 1.0]),+ ("2:1 compression starting at -18 dB", &[0.0, 0.0, -18.0, 2.0, 15.0, 250.0, 1.0, 0.0]),+ ("3:1 compression starting at -15 dB", &[0.0, 0.0, -15.0, 3.0, 15.0, 250.0, 1.0, 1.0]),+ ("6:1 compression starting at -12 dB", &[0.0, 0.0, -12.0, 6.0, 15.0, 250.0, 1.0, 1.0]),+ ("10:1 compression starting at -9 dB", &[0.0, 0.0, -9.0, 10.0, 15.0, 250.0, 1.0, 1.0]),+ ("Limit levels to -6 dB (hard limiter)", &[0.0, 0.0, -6.0, 50.0, 0.0, 250.0, 0.0, 0.0]),+ ("2:1 compression starting at -18 dB (ACX)", &[0.0, 0.0, -18.0, 2.0, 15.0, 250.0, 1.0, 0.0]),+ ];+}++/// Track EQ: four bands (low shelf, band or high shelf, each switched on+/// or off), and the channels it works on.+pub mod track_eq {+ use super::*;++ pub const ENABLE: usize = 0;+ pub const MODE: usize = 1;+ pub const FREQUENCY: usize = 2;+ pub const GAIN: usize = 3;+ pub const BANDWIDTH: usize = 4;+ pub const ROLLOFF: usize = 5;+ /// Each band's parameters, from its place times this.+ pub const PER_BAND: usize = 6;+ /// The channels' switches: left, right, centre, left and right+ /// surround, LFE.+ pub const CHANNELS: usize = 4 * PER_BAND;++ const MODES: &[&str] = &["Low Shelf", "Band", "High Shelf"];+ const ROLLOFFS: &[&str] = &["6 dB/oct.", "12 dB/oct.", "18 dB/oct.", "24 dB/oct."];++ /// A band's parameters, its place `b` (from 0), its default frequency,+ /// mode and rolloff.+ const fn band(+ b: usize,+ group: &'static str,+ hz: f32,+ mode: f32,+ rolloff: f32,+ ) -> [ParamSpec; PER_BAND] {+ // Each band's own conditions.+ let (on, peak, shelf) = (BAND_ON[b], PEAK[b], SHELF[b]);+ [+ ParamSpec::switch("Enable", 1.0).group(group),+ ParamSpec::choice("Mode", 0.0, MODES, mode).when(on),+ ParamSpec::num("Frequency", 20.0, 20000.0, hz)+ .unit("Hz")+ .decimals(0)+ .log()+ .when(on),+ ParamSpec::num("Gain", -25.0, 15.0, 0.0)+ .unit("dB")+ .decimals(1)+ .when(on),+ ParamSpec::num("Bandwidth", 0.1, 4.0, 1.0)+ .unit("oct.")+ .decimals(1)+ .when(peak),+ ParamSpec::choice("Rolloff", 0.0, ROLLOFFS, rolloff).when(shelf),+ ]+ }++ const fn on(b: usize) -> (u8, u32) {+ ((b * PER_BAND + ENABLE) as u8, ON)+ }++ const fn mode(b: usize, mask: u32) -> (u8, u32) {+ ((b * PER_BAND + MODE) as u8, mask)+ }++ const BAND_ON: [&[(u8, u32)]; 4] = [&[on(0)], &[on(1)], &[on(2)], &[on(3)]];+ const PEAK: [&[(u8, u32)]; 4] = [+ &[on(0), mode(0, either(1, 1))],+ &[on(1), mode(1, either(1, 1))],+ &[on(2), mode(2, either(1, 1))],+ &[on(3), mode(3, either(1, 1))],+ ];+ const SHELF: [&[(u8, u32)]; 4] = [+ &[on(0), mode(0, either(0, 2))],+ &[on(1), mode(1, either(0, 2))],+ &[on(2), mode(2, either(0, 2))],+ &[on(3), mode(3, either(0, 2))],+ ];++ const B1: [ParamSpec; PER_BAND] = band(0, "Band 1", 100.0, 0.0, 1.0);+ const B2: [ParamSpec; PER_BAND] = band(1, "Band 2", 300.0, 1.0, 0.0);+ const B3: [ParamSpec; PER_BAND] = band(2, "Band 3", 1000.0, 1.0, 0.0);+ const B4: [ParamSpec; PER_BAND] = band(3, "Band 4", 5000.0, 2.0, 1.0);++ pub const PARAMS: &[ParamSpec] = &[+ B1[0],+ B1[1],+ B1[2],+ B1[3],+ B1[4],+ B1[5],+ B2[0],+ B2[1],+ B2[2],+ B2[3],+ B2[4],+ B2[5],+ B3[0],+ B3[1],+ B3[2],+ B3[3],+ B3[4],+ B3[5],+ B4[0],+ B4[1],+ B4[2],+ B4[3],+ B4[4],+ B4[5],+ ParamSpec::switch("Left", 1.0).group("Channels"),+ ParamSpec::switch("Right", 1.0),+ ParamSpec::switch("Center", 1.0),+ ParamSpec::switch("Left surround", 1.0),+ ParamSpec::switch("Right surround", 1.0),+ ParamSpec::switch("LFE", 1.0),+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[1.0, 0.0, 100.0, 0.0, 1.0, 1.0, 1.0, 1.0, 300.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1000.0, 0.0, 1.0, 0.0, 1.0, 2.0, 5000.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]),+ ("15 dB notch centered at 1000 Hz", &[0.0, 0.0, 100.0, 0.0, 1.0, 0.0, 0.0, 1.0, 300.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1000.0, -15.0, 1.0, 0.0, 0.0, 2.0, 5000.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]),+ ("60 Hz hum notch using four stacked filters", &[1.0, 1.0, 60.0, -25.0, 0.3, 0.0, 1.0, 1.0, 60.0, -25.0, 0.3, 0.0, 1.0, 1.0, 60.0, -25.0, 0.3, 0.0, 1.0, 1.0, 60.0, -25.0, 0.3, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]),+ ("Add air (3 dB peak at 15 kHz)", &[0.0, 1.0, 100.0, 0.0, 1.0, 0.0, 0.0, 1.0, 300.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1000.0, 0.0, 1.0, 0.0, 1.0, 1.0, 15000.0, 3.0, 0.7, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]),+ ("Add air (boost above 16k by 6 dB)", &[0.0, 0.0, 100.0, 0.0, 1.0, 0.0, 0.0, 1.0, 300.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1000.0, 0.0, 1.0, 0.0, 1.0, 2.0, 16000.0, 6.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]),+ ("Anti-DTMF Talkoff", &[1.0, 1.0, 1209.0, -25.0, 0.3, 0.0, 1.0, 1.0, 1336.0, -25.0, 0.3, 0.0, 1.0, 1.0, 1447.0, -25.0, 0.3, 0.0, 1.0, 1.0, 1633.0, -25.0, 0.3, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]),+ ("Boost bass frequencies below 250 Hz by 4 dB", &[1.0, 0.0, 250.0, 4.0, 1.0, 0.0, 0.0, 1.0, 300.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1000.0, 0.0, 1.0, 0.0, 0.0, 2.0, 5000.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]),+ ("Boost frequencies above 7 kHz", &[0.0, 0.0, 100.0, 0.0, 1.0, 0.0, 0.0, 1.0, 300.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1000.0, 0.0, 1.0, 0.0, 1.0, 2.0, 7000.0, 3.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]),+ ("Fletcher-Munson curve (low volume compensation)", &[1.0, 0.0, 200.0, 6.0, 1.0, 0.0, 0.0, 1.0, 300.0, 0.0, 1.0, 0.0, 1.0, 1.0, 4000.0, -12.0, 1.0, 0.0, 1.0, 2.0, 8000.0, 6.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]),+ ("Hiss cut (cut above 8 kHz by 6 dB)", &[0.0, 0.0, 100.0, 0.0, 1.0, 0.0, 0.0, 1.0, 300.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1000.0, 0.0, 1.0, 0.0, 1.0, 2.0, 8000.0, -6.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]),+ ("Remove low rumble below 80 Hz", &[1.0, 0.0, 80.0, -25.0, 1.0, 0.0, 0.0, 1.0, 300.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1000.0, 0.0, 1.0, 0.0, 0.0, 2.0, 5000.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]),+ ("Remove very low and inaudible frequencies below 20 Hz", &[1.0, 0.0, 20.0, -25.0, 1.0, 0.0, 0.0, 1.0, 300.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1000.0, 0.0, 1.0, 0.0, 0.0, 2.0, 5000.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]),+ ];+}++/// Paragraphic EQ: four peak/notch bands and optional low and high+/// shelves, wet and dry.+pub mod paragraphic_eq {+ use super::*;++ pub const DRY: usize = 0;+ pub const WET: usize = 1;+ /// The bands' first parameter, each band's from its place times+ /// [`PER_BAND`] after it.+ pub const BANDS: usize = 2;+ pub const GAIN: usize = 0;+ pub const WIDTH: usize = 1;+ pub const CENTER: usize = 2;+ pub const PER_BAND: usize = 3;+ /// Each shelf's switch, then its frequency and gain.+ pub const LOW_SHELF: usize = BANDS + 4 * PER_BAND;+ pub const HIGH_SHELF: usize = LOW_SHELF + 3;++ const LOW_ON: &[(u8, u32)] = &[(LOW_SHELF as u8, ON)];+ const HIGH_ON: &[(u8, u32)] = &[(HIGH_SHELF as u8, ON)];++ const fn band(group: &'static str, hz: f32) -> [ParamSpec; PER_BAND] {+ [+ ParamSpec::num("Gain", -25.0, 25.0, 0.0)+ .unit("dB")+ .decimals(1)+ .group(group),+ ParamSpec::num("Width", 0.3, 2.5, 1.0)+ .unit("oct.")+ .decimals(1),+ ParamSpec::num("Center", 20.0, 15000.0, hz)+ .unit("Hz")+ .decimals(0)+ .log(),+ ]+ }++ const B1: [ParamSpec; PER_BAND] = band("Band 1", 100.0);+ const B2: [ParamSpec; PER_BAND] = band("Band 2", 300.0);+ const B3: [ParamSpec; PER_BAND] = band("Band 3", 1000.0);+ const B4: [ParamSpec; PER_BAND] = band("Band 4", 5000.0);++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Dry out", -25.0, 25.0, -25.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Wet out", -25.0, 25.0, 0.0)+ .unit("dB")+ .decimals(1),+ B1[0],+ B1[1],+ B1[2],+ B2[0],+ B2[1],+ B2[2],+ B3[0],+ B3[1],+ B3[2],+ B4[0],+ B4[1],+ B4[2],+ ParamSpec::switch("Enable low shelf", 0.0).group("Low shelf"),+ ParamSpec::num("Frequency", 20.0, 20000.0, 300.0)+ .unit("Hz")+ .decimals(0)+ .log()+ .when(LOW_ON),+ ParamSpec::num("Gain", -25.0, 25.0, 0.0)+ .unit("dB")+ .decimals(1)+ .when(LOW_ON),+ ParamSpec::switch("Enable high shelf", 0.0).group("High shelf"),+ ParamSpec::num("Frequency", 20.0, 20000.0, 500.0)+ .unit("Hz")+ .decimals(0)+ .log()+ .when(HIGH_ON),+ ParamSpec::num("Gain", -25.0, 25.0, 0.0)+ .unit("dB")+ .decimals(1)+ .when(HIGH_ON),+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[-25.0, 0.0, 0.0, 1.0, 100.0, 0.0, 1.0, 300.0, 0.0, 1.0, 1000.0, 0.0, 1.0, 5000.0, 0.0, 300.0, 0.0, 0.0, 500.0, 0.0]),+ ("15 dB notch centered at 1000 Hz", &[-25.0, 0.0, 0.0, 1.0, 100.0, 0.0, 1.0, 300.0, -15.0, 1.0, 1000.0, 0.0, 1.0, 5000.0, 0.0, 300.0, 0.0, 0.0, 300.0, 0.0]),+ ("60 Hz hum notch using four stacked filters", &[-25.0, 0.0, -25.0, 0.3, 60.0, -25.0, 0.3, 60.0, -25.0, 0.3, 60.0, -25.0, 0.3, 60.0, 0.0, 300.0, 0.0, 0.0, 300.0, 0.0]),+ ("Add air (3 dB peak at 15 kHz)", &[-25.0, 0.0, 0.0, 1.0, 100.0, 0.0, 1.0, 300.0, 0.0, 1.0, 1000.0, 3.0, 0.7, 15000.0, 0.0, 300.0, 0.0, 0.0, 300.0, 0.0]),+ ("Add air (boost above 16k by 6 dB)", &[-25.0, 0.0, 0.0, 1.0, 100.0, 0.0, 1.0, 300.0, 0.0, 1.0, 1000.0, 0.0, 1.0, 5000.0, 0.0, 300.0, 0.0, 1.0, 16000.0, 6.0]),+ ("Anti-DTMF talk-off", &[-25.0, 0.0, -25.0, 0.3, 1209.0, -25.0, 0.3, 1336.0, -25.0, 0.3, 1447.0, -25.0, 0.3, 1633.0, 0.0, 300.0, 0.0, 0.0, 300.0, 0.0]),+ ("Boost bass frequencies below 250 Hz by 4 dB", &[-25.0, 0.0, 0.0, 1.0, 100.0, 0.0, 1.0, 300.0, 0.0, 1.0, 1000.0, 0.0, 1.0, 5000.0, 1.0, 250.0, 4.0, 0.0, 300.0, 0.0]),+ ("Boost frequencies above 7 kHz", &[-25.0, 0.0, 0.0, 1.0, 100.0, 0.0, 1.0, 300.0, 0.0, 1.0, 1000.0, 0.0, 1.0, 5000.0, 0.0, 300.0, 0.0, 1.0, 7000.0, 3.0]),+ ("Fletcher-Munson curve (low volume compensation)", &[-25.0, 0.0, 0.0, 1.0, 100.0, 0.0, 1.0, 300.0, -12.0, 1.0, 4000.0, 0.0, 1.0, 5000.0, 1.0, 200.0, 6.0, 1.0, 8000.0, 6.0]),+ ("Hiss cut (cut above 8 kHz by 6 dB)", &[-25.0, 0.0, 0.0, 1.0, 100.0, 0.0, 1.0, 300.0, 0.0, 1.0, 1000.0, 0.0, 1.0, 5000.0, 0.0, 300.0, 0.0, 1.0, 8000.0, -6.0]),+ ("Remove low rumble below 80 Hz", &[-25.0, 0.0, 0.0, 1.0, 100.0, 0.0, 1.0, 300.0, 0.0, 1.0, 1000.0, 0.0, 1.0, 5000.0, 1.0, 80.0, -25.0, 0.0, 300.0, 0.0]),+ ("Remove very low and inaudible frequencies below 20 Hz", &[-25.0, 0.0, 0.0, 1.0, 100.0, 0.0, 1.0, 300.0, 0.0, 1.0, 1000.0, 0.0, 1.0, 5000.0, 1.0, 20.0, -25.0, 0.0, 300.0, 0.0]),+ ];+}++/// Multi-Tap Delay: up to eight taps of one delay line, each with its+/// time, level and place, the line fed back, modulated and darkened.+pub mod multi_tap_delay {+ use super::*;++ pub const INPUT: usize = 0;+ pub const DRY: usize = 1;+ pub const WET: usize = 2;+ pub const RATE: usize = 3;+ pub const DEPTH: usize = 4;+ pub const FEEDBACK: usize = 5;+ pub const LOW_PASS: usize = 6;+ pub const LOW_FREQ: usize = 7;+ pub const TAPS: usize = 8;+ /// The taps' first parameter, each tap's from its place times+ /// [`PER_TAP`] after it.+ pub const TAP: usize = 9;+ pub const GAIN: usize = 0;+ pub const DELAY: usize = 1;+ pub const PAN: usize = 2;+ pub const PER_TAP: usize = 3;++ const LOW_ON: &[(u8, u32)] = &[(LOW_PASS as u8, ON)];++ /// Tap `k`'s parameters (from 1): live while there are `k` taps or more.+ const fn tap(k: usize, group: &'static str, ms: f32) -> [ParamSpec; PER_TAP] {+ let when = WHEN[k - 1];+ [+ ParamSpec::num("Tap gain", -1.0, 1.0, 1.0)+ .show(Show::Percent)+ .decimals(0)+ .group(group)+ .when(when),+ ParamSpec::num("Delay", 1.0, 2500.0, ms)+ .unit("ms")+ .decimals(0)+ .log()+ .when(when),+ ParamSpec::num("Pan", -1.0, 1.0, 0.0)+ .show(Show::Pan)+ .when(when),+ ]+ }++ const WHEN: [&[(u8, u32)]; 8] = [+ &[(TAPS as u8, at_least(1))],+ &[(TAPS as u8, at_least(2))],+ &[(TAPS as u8, at_least(3))],+ &[(TAPS as u8, at_least(4))],+ &[(TAPS as u8, at_least(5))],+ &[(TAPS as u8, at_least(6))],+ &[(TAPS as u8, at_least(7))],+ &[(TAPS as u8, at_least(8))],+ ];++ const T1: [ParamSpec; PER_TAP] = tap(1, "Tap 1", 100.0);+ const T2: [ParamSpec; PER_TAP] = tap(2, "Tap 2", 1.0);+ const T3: [ParamSpec; PER_TAP] = tap(3, "Tap 3", 1.0);+ const T4: [ParamSpec; PER_TAP] = tap(4, "Tap 4", 1.0);+ const T5: [ParamSpec; PER_TAP] = tap(5, "Tap 5", 1.0);+ const T6: [ParamSpec; PER_TAP] = tap(6, "Tap 6", 1.0);+ const T7: [ParamSpec; PER_TAP] = tap(7, "Tap 7", 1.0);+ const T8: [ParamSpec; PER_TAP] = tap(8, "Tap 8", 1.0);++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Input gain", -80.0, 0.0, 0.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Dry out", -80.0, 0.0, -6.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Wet out", -80.0, 0.0, -6.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Mod. rate", 0.1, 10.0, 0.1)+ .unit("Hz")+ .decimals(1)+ .log(),+ ParamSpec::num("Mod. depth", 0.0, 1.0, 0.0)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Feedback", 0.0, 1.5, 0.0)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::switch("Low-pass", 0.0),+ ParamSpec::num("Low-pass start frequency", 100.0, 20000.0, 5000.0)+ .unit("Hz")+ .decimals(0)+ .log()+ .when(LOW_ON),+ ParamSpec::num("Number of taps", 1.0, 8.0, 1.0).decimals(0),+ T1[0],+ T1[1],+ T1[2],+ T2[0],+ T2[1],+ T2[2],+ T3[0],+ T3[1],+ T3[2],+ T4[0],+ T4[1],+ T4[2],+ T5[0],+ T5[1],+ T5[2],+ T6[0],+ T6[1],+ T6[2],+ T7[0],+ T7[1],+ T7[2],+ T8[0],+ T8[1],+ T8[2],+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[0.0, -6.0, -6.0, 0.1, 0.0, 0.0, 0.0, 5000.0, 1.0, 1.0, 100.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0]),+ ("Small room 1", &[0.0, -9.2, -2.5, 1.5, 0.05, 0.3, 0.0, 5000.0, 6.0, -0.48, 17.0, 0.24, 0.16, 40.0, -0.18, -0.11, 85.0, 0.14, 0.05, 197.0, 0.38, -0.02, 275.0, 0.06, 0.01, 309.0, 0.38, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0]),+ ("Small hall 1", &[0.0, -1.4, -3.7, 1.5, 0.1, 0.4, 0.0, 5000.0, 8.0, 0.39, 34.0, 0.0, 0.21, 57.0, -0.15, -0.08, 113.0, -0.26, -0.17, 135.0, -0.69, -0.11, 174.0, -0.31, 0.12, 214.0, -0.64, 0.05, 281.0, -0.39, 0.03, 348.0, -0.5]),+ ("Chorus-echo", &[0.0, -14.0, 0.0, 0.1, 0.0, 0.0, 0.0, 5000.0, 8.0, -0.26, 6.0, 0.24, 0.25, 13.0, -0.18, -0.6, 19.0, 0.14, 0.57, 33.0, 0.38, -0.24, 101.0, 0.06, 0.1, 163.0, 0.38, -0.24, 191.0, 0.0, 0.28, 207.0, 0.18]),+ ("Chorus-reverse verb 2", &[0.0, -80.0, 0.0, 0.1, 0.0, 0.0, 0.0, 5000.0, 5.0, 0.12, 1.0, 0.24, -0.17, 12.0, -0.18, 0.37, 20.0, 0.14, -0.42, 32.0, -0.2, 0.52, 40.0, 0.22, -0.49, 57.0, 0.0, 0.66, 85.0, -0.56, -0.85, 113.0, 0.44]),+ ("Chorus-reverse verb 3", &[0.0, -26.0, -3.1, 0.1, 0.0, 0.0, 0.0, 5000.0, 5.0, 0.09, 14.0, -0.38, -0.11, 32.0, -0.59, 0.14, 59.0, -0.43, -0.24, 86.0, -0.6, 0.28, 113.0, -0.39, -0.35, 126.0, -0.5, 0.64, 144.0, -0.56, -0.85, 162.0, -0.33]),+ ("Chorus-reverse verb 1", &[0.0, -80.0, -3.1, 0.1, 0.0, 0.0, 0.0, 5000.0, 5.0, 0.05, 1.0, 0.24, -0.11, 12.0, -0.18, 0.14, 23.0, 0.14, -0.24, 29.0, -0.2, 0.28, 37.0, 0.22, -0.35, 44.0, 0.0, 0.64, 56.0, -0.56, -0.85, 65.0, 0.44]),+ ("Low-frequency verb", &[0.0, -4.4, 0.0, 0.1, 0.0, 0.7, 1.0, 500.0, 8.0, 0.35, 17.0, 0.24, -0.24, 187.0, -0.18, 0.1, 323.0, 0.14, -0.08, 361.0, -0.2, -0.05, 399.0, 0.22, -0.02, 427.0, 0.0, 0.01, 473.0, -0.56, -0.01, 500.0, 0.0]),+ ("Chorus-verb", &[0.0, -10.5, -6.0, 0.1, 0.0, 0.03, 0.0, 5000.0, 8.0, 0.35, 3.0, 0.24, -0.31, 7.0, -0.18, 0.37, 13.0, 0.14, -0.4, 19.0, -0.2, 0.3, 27.0, 0.22, -0.35, 33.0, 0.0, 0.34, 41.0, -0.56, -0.51, 53.0, 0.44]),+ ("Stadium", &[0.0, -6.0, 0.0, 1.5, 0.05, 0.4, 1.0, 2000.0, 2.0, 0.54, 366.0, 0.24, -0.1, 500.0, -0.18, 0.05, 500.0, 0.14, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0]),+ ("Medium hall 1", &[0.0, -9.2, -6.0, 1.0, 0.1, 0.4, 1.0, 4500.0, 5.0, -0.58, 71.0, 0.3, -0.28, 177.0, -0.31, -0.12, 315.0, 0.18, 0.05, 374.0, 0.12, -0.05, 424.0, -0.2, 0.04, 432.0, -0.28, 0.11, 453.0, 0.22, -0.09, 500.0, 0.0]),+ ("Large hall 2", &[0.0, -1.4, -9.1, 2.0, 0.15, 0.4, 1.0, 4500.0, 6.0, -0.51, 100.0, 0.3, -0.41, 130.0, -0.31, -0.22, 185.0, 0.18, -0.32, 269.0, 0.12, -0.09, 424.0, -0.2, 0.04, 437.0, -0.28, 0.11, 453.0, 0.22, -0.09, 500.0, 0.0]),+ ("Large hall 1", &[0.0, -9.2, -6.0, 1.0, 0.1, 0.6, 1.0, 4500.0, 8.0, 0.54, 90.0, -0.38, -0.14, 108.0, -0.59, 0.13, 212.0, -0.43, 0.05, 306.0, -0.65, -0.06, 361.0, -0.55, 0.05, 468.0, 0.0, -0.02, 482.0, 0.0, 0.05, 500.0, 0.0]),+ ("Large hall 3", &[0.0, -9.2, -6.0, 1.0, 0.1, 0.5, 1.0, 4500.0, 5.0, -0.58, 100.0, 0.3, -0.28, 177.0, -0.31, -0.12, 315.0, 0.18, 0.11, 403.0, 0.12, -0.05, 474.0, -0.2, 0.04, 432.0, -0.28, 0.11, 453.0, 0.22, -0.09, 500.0, 0.0]),+ ("Medium hall 2", &[0.0, -9.2, -6.0, 1.0, 0.1, 0.4, 1.0, 3500.0, 5.0, -0.58, 63.0, 0.3, -0.22, 177.0, -0.31, -0.05, 315.0, 0.18, 0.04, 403.0, 0.12, -0.05, 474.0, -0.2, 0.04, 432.0, -0.28, 0.11, 453.0, 0.22, -0.09, 500.0, 0.0]),+ ("Cathedral 1", &[0.0, -4.4, -4.4, 1.0, 0.05, 1.0, 1.0, 4000.0, 5.0, 0.3, 191.0, 0.2, -0.24, 227.0, -0.18, -0.15, 249.0, 0.28, -0.06, 267.0, 0.0, -0.02, 291.0, -0.06, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0]),+ ("Cathedral 2", &[0.0, -4.4, -2.0, 1.0, 0.1, 1.0, 1.0, 850.0, 4.0, -0.32, 191.0, 0.24, -0.24, 269.0, -0.18, -0.05, 428.0, 0.28, -0.06, 500.0, 0.0, -0.02, 291.0, -0.06, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0]),+ ("Cathedral 3", &[0.0, -2.0, -3.7, 1.0, 0.1, 0.7, 1.0, 4000.0, 5.0, -0.32, 311.0, 0.24, -0.24, 369.0, -0.18, -0.05, 483.0, 0.28, -0.06, 500.0, 0.0, 0.24, 119.0, -0.06, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0]),+ ("Large hall 4", &[0.0, -2.0, -3.7, 1.0, 0.1, 0.8, 1.0, 4000.0, 5.0, -0.32, 119.0, 0.24, -0.19, 311.0, -0.18, -0.09, 369.0, 0.28, -0.09, 461.0, 0.0, -0.06, 500.0, -0.06, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0]),+ ("Small hall 2", &[0.0, 0.0, -4.4, 1.0, 0.15, 0.5, 1.0, 1000.0, 7.0, -0.5, 31.0, 0.3, -0.12, 110.0, -0.31, -0.09, 151.0, 0.18, -0.09, 206.0, 0.12, -0.09, 231.0, -0.2, -0.05, 336.0, -0.28, -0.01, 500.0, 0.22, -0.09, 500.0, 0.0]),+ ("Small room 2", &[0.0, -9.2, -10.5, 0.1, 0.0, 0.15, 1.0, 2500.0, 5.0, 1.0, 27.0, -0.38, -0.21, 101.0, -0.59, 0.08, 193.0, -0.43, -0.05, 240.0, -0.65, 0.03, 302.0, -0.55, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0, -1.0, 1.0, 0.0]),+ ("Tapped delay 1", &[0.0, 0.0, -8.0, 2.0, 0.0, 0.0, 1.0, 4500.0, 8.0, -0.91, 17.0, 0.24, 0.16, 47.0, -0.18, 0.77, 89.0, 0.14, -0.58, 164.0, 0.38, 0.73, 240.0, 0.06, -0.68, 332.0, 0.38, 0.7, 416.0, 0.0, -0.64, 500.0, 0.0]),+ ("Tapped delay 2", &[0.0, 0.0, -8.0, 2.0, 0.0, 0.15, 1.0, 4000.0, 8.0, -0.91, 17.0, 0.24, 0.16, 47.0, -0.18, 0.77, 89.0, 0.14, -0.58, 164.0, 0.38, 0.73, 240.0, 0.06, -0.68, 332.0, 0.38, 0.7, 416.0, 0.0, -0.64, 500.0, 0.0]),+ ("Tapped delay, stereo pan", &[0.0, 0.0, -8.0, 2.0, 0.0, 0.15, 1.0, 4000.0, 8.0, -0.91, 17.0, 1.0, 0.6, 72.0, -1.0, 0.4, 118.0, 1.0, -0.35, 181.0, -1.0, 0.31, 240.0, 1.0, -0.19, 332.0, -1.0, 0.14, 416.0, 1.0, -0.09, 500.0, -1.0]),+ ("Channel delay for stereo simulation", &[0.0, -80.0, 0.0, 1.0, 0.0, 0.0, 0.0, 4500.0, 2.0, 1.0, 1.0, 1.0, 1.0, 15.0, -1.0, 0.13, 212.0, -0.43, 0.05, 306.0, -0.65, -0.06, 361.0, -0.55, 0.05, 468.0, 0.0, -0.02, 482.0, 0.0, 0.05, 500.0, 0.0]),+ ];+}++/// Multi-Band Dynamics: four bands (a low shelf, a band or a high shelf),+/// each compressed on its own and raised or lowered, the rest of the+/// sound left as it is.+pub mod multi_band_dynamics {+ use super::*;++ pub const OUTPUT: usize = 0;+ pub const SYNC: usize = 1;+ /// The bands' first parameter, each band's from its place times+ /// [`PER_BAND`] after it.+ pub const BANDS: usize = 2;+ pub const BYPASS: usize = 0;+ pub const SOLO: usize = 1;+ pub const TYPE: usize = 2;+ pub const CENTER: usize = 3;+ pub const WIDTH: usize = 4;+ pub const THRESHOLD: usize = 5;+ pub const AMOUNT: usize = 6;+ pub const GAIN: usize = 7;+ pub const ATTACK: usize = 8;+ pub const RELEASE: usize = 9;+ pub const PER_BAND: usize = 10;++ const TYPES: &[&str] = &["Low-shelf", "Band-notch", "High-shelf"];++ const fn live(b: usize) -> (u8, u32) {+ ((BANDS + b * PER_BAND + BYPASS) as u8, OFF)+ }++ const ON_: [&[(u8, u32)]; 4] = [&[live(0)], &[live(1)], &[live(2)], &[live(3)]];+ const BAND_: [&[(u8, u32)]; 4] = [+ &[live(0), ((BANDS + TYPE) as u8, either(1, 1))],+ &[live(1), ((BANDS + PER_BAND + TYPE) as u8, either(1, 1))],+ &[live(2), ((BANDS + 2 * PER_BAND + TYPE) as u8, either(1, 1))],+ &[live(3), ((BANDS + 3 * PER_BAND + TYPE) as u8, either(1, 1))],+ ];++ const fn band(b: usize, group: &'static str, hz: f32, bypass: f32) -> [ParamSpec; PER_BAND] {+ let (on, width) = (ON_[b], BAND_[b]);+ [+ ParamSpec::switch("Bypass", bypass).group(group),+ ParamSpec::switch("Solo", 0.0).when(on),+ ParamSpec::choice("Type", 0.0, TYPES, 1.0).when(on),+ ParamSpec::num("Center", 50.0, 15000.0, hz)+ .unit("Hz")+ .decimals(0)+ .log()+ .when(on),+ ParamSpec::num("Width", 0.3, 3.0, 1.0)+ .unit("oct.")+ .decimals(1)+ .when(width),+ ParamSpec::num("Threshold", -60.0, 0.0, 0.0)+ .unit("dB")+ .decimals(1)+ .when(on),+ ParamSpec::num("Amount (x:1)", 1.0, 50.0, 1.0)+ .decimals(1)+ .log()+ .when(on),+ ParamSpec::num("Gain", -25.0, 25.0, 0.0)+ .unit("dB")+ .decimals(1)+ .when(on),+ ParamSpec::num("Attack", 0.0, 500.0, 1.0)+ .unit("ms")+ .decimals(1)+ .when(on),+ ParamSpec::num("Release", 0.0, 5000.0, 100.0)+ .unit("ms")+ .decimals(0)+ .when(on),+ ]+ }++ const B1: [ParamSpec; PER_BAND] = band(0, "Band 1", 200.0, 0.0);+ const B2: [ParamSpec; PER_BAND] = band(1, "Band 2", 1000.0, 1.0);+ const B3: [ParamSpec; PER_BAND] = band(2, "Band 3", 4000.0, 1.0);+ const B4: [ParamSpec; PER_BAND] = band(3, "Band 4", 10000.0, 1.0);++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Output gain", -25.0, 25.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::switch("Stereo sync channels", 1.0),+ B1[0],+ B1[1],+ B1[2],+ B1[3],+ B1[4],+ B1[5],+ B1[6],+ B1[7],+ B1[8],+ B1[9],+ B2[0],+ B2[1],+ B2[2],+ B2[3],+ B2[4],+ B2[5],+ B2[6],+ B2[7],+ B2[8],+ B2[9],+ B3[0],+ B3[1],+ B3[2],+ B3[3],+ B3[4],+ B3[5],+ B3[6],+ B3[7],+ B3[8],+ B3[9],+ B4[0],+ B4[1],+ B4[2],+ B4[3],+ B4[4],+ B4[5],+ B4[6],+ B4[7],+ B4[8],+ B4[9],+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[0.0, 1.0, 0.0, 0.0, 1.0, 200.0, 1.0, 0.0, 1.0, 0.0, 1.0, 100.0, 1.0, 0.0, 1.0, 1000.0, 1.0, 0.0, 1.0, 0.0, 1.0, 100.0, 1.0, 0.0, 1.0, 4000.0, 1.0, 0.0, 1.0, 0.0, 1.0, 100.0, 1.0, 0.0, 1.0, 10000.0, 1.0, 0.0, 1.0, 0.0, 1.0, 100.0]),+ ("Anti-DTMF talk-off", &[0.0, 1.0, 0.0, 0.0, 1.0, 1209.0, 0.7, -25.0, 30.0, 0.0, 1.0, 100.0, 0.0, 0.0, 1.0, 1336.0, 0.7, -25.0, 30.0, 0.0, 1.0, 100.0, 0.0, 0.0, 1.0, 1477.0, 0.7, -25.0, 30.0, 0.0, 1.0, 100.0, 0.0, 0.0, 1.0, 1633.0, 0.7, -25.0, 30.0, 0.0, 1.0, 100.0]),+ ("Reduce loud plosives", &[0.0, 1.0, 0.0, 0.0, 0.0, 500.0, 1.0, -15.0, 32.0, 0.0, 1.0, 100.0, 1.0, 0.0, 0.0, 1000.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1000.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1000.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0]),+ ("Reduce loud sibilants (de-esser)", &[0.0, 1.0, 0.0, 0.0, 1.0, 5000.0, 1.0, -30.0, 25.0, 2.0, 1.0, 100.0, 1.0, 0.0, 0.0, 1000.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1000.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1000.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0]),+ ("Reduce plosives and sibilants", &[0.0, 1.0, 0.0, 0.0, 0.0, 600.0, 2.0, -15.0, 40.0, 0.0, 1.0, 100.0, 0.0, 0.0, 1.0, 5000.0, 1.0, -32.0, 20.0, 2.0, 1.0, 100.0, 1.0, 0.0, 0.0, 1000.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1000.0, 1.0, 0.0, 1.0, 0.0, 0.0, 0.0]),+ ];+}++/// Express Delay: an echo fed back by a share of itself, mixed with the+/// sound.+pub mod express_delay {+ use super::*;++ pub const DELAY: usize = 0;+ pub const DECAY: usize = 1;+ pub const MIX: usize = 2;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Delay", 0.0, 1000.0, 250.0)+ .unit("ms")+ .decimals(1),+ ParamSpec::num("Decay", 0.0, 0.9, 0.0)+ .show(Show::Percent)+ .decimals(1),+ ParamSpec::num("Delay / Original", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(1),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[250.0, 0.0, 0.5]),+ ("1/2 second delay", &[500.0, 0.0, 0.5]),+ ("Phased", &[3.0, 0.0, 0.5]),+ ("Robot", &[10.0, 0.9, 1.0]),+ ("Echo chamber", &[250.0, 0.5, 0.35]),+ ("Grand canyon", &[1000.0, 0.25, 0.25]),+ ("Dreamscape", &[100.0, 0.7, 0.4]),+ ];+}++/// Express Distortion: saturation past a knee set by the slew, a short+/// comb and a limit on how fast the sound may move, mixed with it.+pub mod express_distortion {+ use super::*;++ pub const DISTORTION: usize = 0;+ pub const SLEW: usize = 1;+ pub const HARD: usize = 2;+ pub const MIX: usize = 3;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Distortion", 0.0, 1.0, 0.0)+ .show(Show::Percent)+ .decimals(1),+ ParamSpec::num("Slew", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(1),+ ParamSpec::switch("Enable hard clipping", 0.0),+ ParamSpec::num("Distortion / Original", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(1),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[0.0, 0.5, 0.0, 0.5]),+ ("Mangle", &[0.0, 1.0, 1.0, 1.0]),+ ("Fuzz", &[1.0, 0.75, 0.0, 0.5]),+ ("Gristle", &[0.75, 0.25, 1.0, 0.5]),+ ("Spaced", &[0.05, 0.0, 0.0, 1.0]),+ ];+}++/// Express Equalization: bass, mid and treble (−25 dB cuts them out),+/// mixed with the sound.+pub mod express_equalization {+ use super::*;++ pub const BASS: usize = 0;+ pub const MID: usize = 1;+ pub const TREBLE: usize = 2;+ pub const MIX: usize = 3;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Bass", -25.0, 12.0, 0.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Mid", -25.0, 12.0, 0.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Treble", -25.0, 12.0, 0.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("EQ / Original", 0.0, 1.0, 1.0)+ .show(Show::Percent)+ .decimals(1),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[0.0, 0.0, 0.0, 1.0]),+ ("Bass only", &[0.0, -25.0, -25.0, 1.0]),+ ("Bass boost", &[12.0, 0.0, 0.0, 1.0]),+ ("Contour (drop middle)", &[6.0, -25.0, 6.0, 1.0]),+ ("Treble only", &[-25.0, -25.0, 6.0, 1.0]),+ ("Treble boost", &[0.0, 0.0, 12.0, 1.0]),+ ];+}++/// Express Noise Gate: the Noise Gate with its three controls.+pub mod express_noise_gate {+ use super::*;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Threshold", -80.0, 0.0, -20.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Attack", 1.0, 500.0, 3.0)+ .unit("ms")+ .decimals(0)+ .log(),+ ParamSpec::num("Release", 1.0, 5000.0, 100.0)+ .unit("ms")+ .decimals(0)+ .log(),+ ];++ pub const PRESETS: &[Preset] = noise_gate::PRESETS;+}++/// Express Chorus: one to three modulated 20 ms delays in a row, mixed+/// with the sound.+pub mod express_chorus {+ use super::*;++ pub const SIZE: usize = 0;+ pub const RATE: usize = 1;+ pub const DEPTH: usize = 2;+ pub const MIX: usize = 3;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::choice("Size", 1.0, &["1", "2", "3"], 1.0),+ ParamSpec::num("Rate", 0.001, 20.0, 0.1)+ .unit("Hz")+ .decimals(3)+ .log(),+ ParamSpec::num("Depth", 0.01, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Chorus / Original", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(1),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[1.0, 0.1, 0.5, 0.5]),+ ("Wacky 1", &[1.0, 4.0, 0.5, 1.0]),+ ("Wacky 2", &[1.0, 1.0, 0.5, 1.0]),+ ("Wacky 3", &[3.0, 5.0, 0.1, 0.75]),+ ("Wacky 4", &[2.0, 10.0, 0.5, 1.0]),+ ("Slow light chorus", &[1.0, 0.15, 0.25, 0.5]),+ ("Slow medium chorus", &[2.0, 0.3, 0.25, 0.5]),+ ("Slow heavy chorus", &[3.0, 0.3, 0.4, 0.75]),+ ("Fast light chorus", &[1.0, 5.0, 0.03, 0.4]),+ ("Fast medium chorus", &[2.0, 5.0, 0.05, 0.5]),+ ("Fast heavy chorus", &[3.0, 4.0, 0.07, 0.75]),+ ("Guitar", &[3.0, 4.0, 0.01, 1.0]),+ ];+}++/// Express Flange/Wah-Wah: the full one's flange or wah-wah (centre+/// 500 Hz, resonance 75 %), mixed with the sound.+pub mod express_flange_wah_wah {+ use super::*;++ pub const EFFECT: usize = 0;+ pub const RATE: usize = 1;+ pub const DEPTH: usize = 2;+ pub const MIX: usize = 3;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::choice("Effect", 0.0, &["Flange", "Wah-Wah"], 0.0),+ ParamSpec::num("Rate", 0.001, 20.0, 1.0)+ .unit("Hz")+ .decimals(3)+ .log(),+ ParamSpec::num("Depth", 0.01, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Effect / Original", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(1),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[0.0, 1.0, 0.5, 0.5]),+ ("Bouncing flange", &[0.0, 1.0, 0.5, 0.5]),+ ("Slow flange", &[0.0, 0.2, 0.8, 0.5]),+ ("Mad flange", &[0.0, 20.0, 1.0, 1.0]),+ ("Tremolo flange", &[0.0, 15.0, 0.25, 0.5]),+ ("Bouncing wah", &[1.0, 1.0, 0.5, 0.5]),+ ("Slow wah", &[1.0, 0.2, 0.8, 0.5]),+ ("Mad wah", &[1.0, 20.0, 1.0, 1.0]),+ ("Tremolo wah", &[1.0, 15.0, 0.25, 0.5]),+ ];+}++/// Express Dynamics: a compressor (to a limiter at its top ratio).+pub mod express_dynamics {+ use super::*;++ pub const THRESHOLD: usize = 0;+ pub const RATIO: usize = 1;+ pub const ATTACK: usize = 2;+ pub const RELEASE: usize = 3;+ pub const AUTO_GAIN: usize = 4;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Threshold", -80.0, -0.1, -20.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Ratio (x:1)", 1.0, 50.0, 1.0)+ .decimals(1)+ .log(),+ ParamSpec::num("Attack", 0.0, 500.0, 1.0)+ .unit("ms")+ .decimals(1),+ ParamSpec::num("Release", 0.0, 5000.0, 500.0)+ .unit("ms")+ .decimals(1),+ ParamSpec::switch("Auto gain compensate", 0.0),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[-20.0, 1.0, 1.0, 500.0, 0.0]),+ ("Limit levels to -6 dB", &[-6.0, 50.0, 1.0, 500.0, 0.0]),+ (+ "Maximize volume (-12 dB limiter with gain compensation)",+ &[-12.0, 50.0, 5.0, 100.0, 1.0],+ ),+ (+ "2:1 compression starting at -18 dB",+ &[-18.0, 2.0, 1.0, 500.0, 1.0],+ ),+ (+ "3:1 compression starting at -15 dB",+ &[-15.0, 3.0, 1.0, 500.0, 1.0],+ ),+ (+ "2:1 compression starting at -18 dB (ACX)",+ &[-18.0, 2.0, 1.0, 500.0, 1.0],+ ),+ ];+}++/// Express Stutter: the sound switched on and off in a rhythm (soft+/// edges), the second channel's rhythm moved on with Add space, mixed+/// with the sound.+pub mod express_stutter {+ use super::*;++ pub const SILENCE: usize = 0;+ pub const SOUND: usize = 1;+ pub const SPACE: usize = 2;+ pub const MIX: usize = 3;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Silence", 0.01, 200.0, 1.0)+ .unit("ms")+ .decimals(2)+ .log(),+ ParamSpec::num("Sound", 0.01, 200.0, 1.0)+ .unit("ms")+ .decimals(2)+ .log(),+ ParamSpec::switch("Add space", 0.0),+ ParamSpec::num("Stutter / Original", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(1),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[1.0, 1.0, 0.0, 0.5]),+ ("Crystal ball", &[20.0, 35.0, 1.0, 1.0]),+ ("Gravel", &[30.0, 20.0, 0.0, 0.75]),+ ("Low bell", &[1.0, 6.0, 1.0, 0.65]),+ ("Walkie-talkie", &[1.0, 1.0, 1.0, 0.5]),+ ];+}++/// Express Amplitude Modulation: the sound's level following a smooth+/// wave at the rate, as deep as the depth, mixed with the sound.+pub mod express_amplitude_modulation {+ use super::*;++ pub const RATE: usize = 0;+ pub const DEPTH: usize = 1;+ pub const MIX: usize = 2;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Rate", 0.1, 5000.0, 1.0)+ .unit("Hz")+ .decimals(1)+ .log(),+ ParamSpec::num("Depth", 0.0, 1.0, 1.0)+ .show(Show::Percent)+ .decimals(1),+ ParamSpec::num("Modulation / Original", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(1),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[1.0, 1.0, 0.5]),+ ("Slow modulation", &[2.0, 0.5, 0.75]),+ ("Fast modulation", &[15.0, 0.75, 1.0]),+ ("440 Hz noise", &[440.0, 1.0, 1.0]),+ ];+}++/// Express Graphic EQ: ten bands an octave apart, drawn as one response+/// and applied as a linear-phase FIR filter through FFTs.+pub mod express_graphic_eq {+ use super::*;++ /// The bands' gains, from the lowest.+ pub const BANDS: usize = 0;+ pub const OUTPUT: usize = 10;+ pub const ACCURACY: usize = 11;++ /// Each band's centre (Hz).+ pub const CENTERS: [f32; 10] = [+ 28.0, 56.0, 113.0, 225.0, 450.0, 900.0, 1800.0, 3600.0, 7200.0, 15000.0,+ ];++ const fn band(name: &'static str) -> ParamSpec {+ ParamSpec::num(name, -60.0, 24.0, 0.0)+ .show(Show::Db)+ .decimals(1)+ }++ pub const PARAMS: &[ParamSpec] = &[+ band("28 Hz"),+ band("56 Hz"),+ band("113 Hz"),+ band("225 Hz"),+ band("450 Hz"),+ band("900 Hz"),+ band("1.8 kHz"),+ band("3.6 kHz"),+ band("7.2 kHz"),+ band("15 kHz"),+ ParamSpec::num("Output gain", -60.0, 20.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::choice(+ "Accuracy",+ 0.0,+ &[+ "Low (fast, good for high bands)",+ "Medium (great for mid and high bands)",+ "High (slow, great for all bands)",+ ],+ 1.0,+ ),+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]),+ ("Boost bass around 125 Hz by 6 dB", &[0.0, 1.5, 6.0, 1.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0]),+ ("Boost high frequencies above 4 kHz by 6 dB", &[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.0, 6.0, 6.0, 6.0, 0.0, 2.0]),+ ("Boost mid-range around 1 kHz by 6 dB", &[0.0, 0.0, 0.0, 0.0, 4.0, 6.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0]),+ ("Cut high frequencies above 4 kHz by 12 dB", &[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -6.0, -12.0, -12.0, 0.0, 1.0]),+ ("Cut low frequencies below 125 Hz by 60 dB", &[-60.0, -60.0, -10.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0]),+ ("Cut mid-range around 1 kHz by 6 dB", &[0.0, 0.0, 0.0, 0.0, -4.0, -6.0, -4.0, 0.0, 0.0, 0.0, 0.0, 1.0]),+ ];+}++/// Express Reverb: the Reverb's rooms, its size setting the decay and its+/// liveliness the pre-delay, mixed with the sound.+pub mod express_reverb {+ use super::*;++ pub const ROOM: usize = 0;+ pub const SIZE: usize = 1;+ pub const LIVELINESS: usize = 2;+ pub const MIX: usize = 3;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec {+ name: "Room type",+ ..reverb::PARAMS[reverb::MODE]+ },+ ParamSpec::num("Room size", 0.0, 1.0, 0.1667)+ .show(Show::Percent)+ .decimals(1),+ ParamSpec::num("Liveliness", 0.0, 1.0, 0.15)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Reverb / Original", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(1),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[0.0, 0.1667, 0.15, 0.5]),+ ("Dream-verb", &[8.0, 1.0, 0.0, 1.0]),+ ("Indoor olympic-size pool", &[4.0, 1.0, 0.8, 0.75]),+ ("Hospital hallway", &[5.0, 0.6111, 0.35, 0.4]),+ ("Small metal room", &[9.0, 0.1667, 0.15, 1.0]),+ ("Small night club", &[7.0, 0.0556, 0.3, 0.5]),+ ];+}++/// Amplitude Modulation: the level following a wave drawn on a graph+/// (from 0 dB at its top to the amplitude at its bottom), at a frequency+/// or a note of the tempo, the right channel up to half a round behind.+pub mod amplitude_modulation {+ use super::*;++ pub const DRY: usize = 0;+ pub const WET: usize = 1;+ pub const AMPLITUDE: usize = 2;+ /// The wave's point count, its points after it.+ pub const GRAPH: usize = 3;+ pub const BLEND: usize = GRAPH + 1 + WAVE.params();+ pub const FREQUENCY: usize = BLEND + 1;+ pub const PAN: usize = BLEND + 2;+ pub const LOW_PASS: usize = BLEND + 3;+ pub const LOW_FREQ: usize = BLEND + 4;+ pub const SYNC: usize = BLEND + 5;+ pub const MULTIPLIER: usize = BLEND + 6;+ pub const PERIOD: usize = BLEND + 7;++ /// A round of the wave (0 to 1000), its level from 0 (top) to −100.+ pub const WAVE: Graph = Graph {+ points: 32,+ x: (0.0, 1000.0),+ y: (-100.0, 0.0),+ log_x: false,+ pinned_ends: true,+ x_unit: "",+ y_unit: "",+ };++ const FREE: &[(u8, u32)] = &[(SYNC as u8, OFF)];+ const SYNCED: &[(u8, u32)] = &[(SYNC as u8, ON)];+ const CUT: &[(u8, u32)] = &[(LOW_PASS as u8, ON)];++ const HEAD: [ParamSpec; 4] = [+ ParamSpec::num("Dry out", -80.0, 0.0, -80.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Wet out", -80.0, 24.0, 0.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Amplitude", -80.0, 0.0, -48.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::graph("Graph", WAVE, 2.0),+ ];+ const POINTS: [ParamSpec; 64] = WAVE.point_params(&[(0.0, -50.0), (1000.0, -50.0)]);+ const TAIL: [ParamSpec; 8] = [+ ParamSpec::switch("Blend graph edges", 0.0),+ ParamSpec::num("Mod. freq.", 0.001, 5000.0, 1.0)+ .unit("Hz")+ .decimals(3)+ .log()+ .when(FREE),+ ParamSpec::num("Stereo pan", 0.0, 1.0, 0.0)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::switch("Low-pass", 0.0),+ ParamSpec::num("Low-pass start frequency", 100.0, 10000.0, 400.0)+ .unit("Hz")+ .decimals(0)+ .log()+ .when(CUT),+ ParamSpec::switch("Tempo sync", 0.0),+ ParamSpec::num("Period multiplier", 0.001, 32.0, 1.0)+ .decimals(3)+ .log()+ .when(SYNCED),+ ParamSpec::choice(+ "Modulation period",+ 0.0,+ tempo::NOTES_OR_MEASURE,+ tempo::MEASURE,+ )+ .when(SYNCED),+ ];+ const FRONT: [ParamSpec; 68] = join(HEAD, POINTS);+ const ALL: [ParamSpec; 76] = join(FRONT, TAIL);++ pub const PARAMS: &[ParamSpec] = &ALL;++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[-80.0, 0.0, -48.0, 2.0, 0.0, -50.0, 1000.0, -50.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, 1.0, 0.0, 0.0, 400.0, 0.0, 1.0, 18.0]),+ ("Triangle 1", &[-80.0, 0.0, -48.0, 4.0, 0.0, -50.0, 250.0, 0.0, 750.0, -100.0, 1000.0, -50.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, 1.0, 0.0, 0.0, 400.0, 0.0, 1.0, 18.0]),+ ("Sine", &[-80.0, 0.0, -48.0, 12.0, 0.0, -50.0, 125.0, -12.0, 188.0, -3.0, 250.0, 0.0, 313.0, -3.0, 375.0, -12.0, 625.0, -88.0, 688.0, -97.0, 750.0, -100.0, 813.0, -97.0, 875.0, -88.0, 1000.0, -50.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, 1.0, 0.0, 0.0, 400.0, 0.0, 1.0, 18.0]),+ ("Sine out of phase", &[-80.0, 0.0, -48.0, 12.0, 0.0, -50.0, 125.0, -12.0, 188.0, -3.0, 250.0, 0.0, 313.0, -3.0, 375.0, -12.0, 625.0, -88.0, 688.0, -97.0, 750.0, -100.0, 813.0, -97.0, 875.0, -88.0, 1000.0, -50.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 1.0, 5.0, 1.0, 0.0, 400.0, 0.0, 1.0, 18.0]),+ ("Soft square", &[-80.0, 0.0, -48.0, 6.0, 0.0, -50.0, 50.0, 0.0, 450.0, 0.0, 550.0, -100.0, 950.0, -100.0, 1000.0, -50.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, 5.0, 0.0, 0.0, 400.0, 0.0, 1.0, 18.0]),+ ("Hard square", &[-80.0, 0.0, -48.0, 4.0, 0.0, 0.0, 500.0, 0.0, 501.0, -100.0, 1000.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, 5.0, 0.0, 0.0, 400.0, 0.0, 1.0, 18.0]),+ ("Wacky", &[-80.0, 0.0, -48.0, 14.0, 0.0, -50.0, 90.0, -25.0, 125.0, -20.0, 160.0, -25.0, 340.0, -70.0, 375.0, -75.0, 410.0, -70.0, 590.0, -10.0, 625.0, -5.0, 660.0, -10.0, 840.0, -90.0, 875.0, -95.0, 910.0, -90.0, 1000.0, -50.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, 6.5, 0.25, 0.0, 400.0, 0.0, 1.0, 18.0]),+ ("Sawtooth 1", &[-80.0, 0.0, -48.0, 2.0, 0.0, -50.0, 1000.0, 0.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, 1.0, 0.0, 0.0, 400.0, 0.0, 0.001, 0.0]),+ ("Sawtooth 2", &[-80.0, 0.0, -48.0, 2.0, 0.0, -100.0, 1000.0, 0.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, 1.0, 0.0, 0.0, 400.0, 0.0, 0.001, 0.0]),+ ];+}++/// Graphic Dynamics: the level, a block of 20 ms at a time, through an+/// input/output curve drawn on a graph (compression, limiting, gating),+/// the gain moving by the attack and release.+pub mod graphic_dynamics {+ use super::*;++ /// The curve's point count, its points after it.+ pub const GRAPH: usize = 0;+ pub const ATTACK: usize = GRAPH + 1 + CURVE.params();+ pub const RELEASE: usize = ATTACK + 1;+ pub const OUTPUT: usize = ATTACK + 2;+ pub const AUTO_GAIN: usize = ATTACK + 3;+ pub const SYNC: usize = ATTACK + 4;++ /// Input level (dB) to output level (dB), −84 dB the bottom (−Inf.).+ pub const CURVE: Graph = Graph {+ points: 16,+ x: (-84.0, 0.0),+ y: (-84.0, 0.0),+ log_x: false,+ pinned_ends: true,+ x_unit: "dB",+ y_unit: "dB",+ };++ const HEAD: [ParamSpec; 1] = [ParamSpec::graph("Graph", CURVE, 3.0)];+ const POINTS: [ParamSpec; 32] =+ CURVE.point_params(&[(-84.0, -84.0), (-24.0, -24.0), (0.0, 0.0)]);+ const TAIL: [ParamSpec; 5] = [+ ParamSpec::num("Attack", 0.0, 500.0, 1.0)+ .unit("ms")+ .decimals(1),+ ParamSpec::num("Release", 0.0, 5000.0, 500.0)+ .unit("ms")+ .decimals(1),+ ParamSpec::num("Output gain", -25.0, 25.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::switch("Auto gain compensate", 0.0),+ ParamSpec::switch("Sync channel gains", 1.0),+ ];+ const FRONT: [ParamSpec; 33] = join(HEAD, POINTS);+ const ALL: [ParamSpec; 38] = join(FRONT, TAIL);++ pub const PARAMS: &[ParamSpec] = &ALL;++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[3.0, -84.0, -84.0, -24.0, -24.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 1.0, 500.0, 0.0, 0.0, 1.0]),+ ("Compressor/Gate", &[4.0, -84.0, -84.0, -61.4, -84.0, -15.0, -15.0, 0.0, -11.9, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 1.0, 500.0, 0.0, 1.0, 1.0]),+ ("Mute levels below -35 dB (hard noise gate)", &[4.0, -84.0, -84.0, -35.1, -84.0, -35.0, -35.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 1.0, 500.0, 0.0, 0.0, 1.0]),+ ("Limit levels to -6 dB (hard limiter)", &[3.0, -84.0, -84.0, -6.0, -6.0, 0.0, -6.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 1.0, 500.0, 0.0, 0.0, 1.0]),+ ("Soft limiter", &[4.0, -84.0, -84.0, -12.2, -12.4, -5.7, -7.8, 0.0, -6.8, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 1.0, 500.0, 0.0, 0.0, 1.0]),+ ("Maximize volume (-12 dB limiter with gain compensation)", &[3.0, -84.0, -84.0, -12.0, -12.0, 0.0, -12.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 5.0, 100.0, 0.0, 1.0, 0.0]),+ ("2:1 compression starting at -18 dB", &[3.0, -84.0, -84.0, -18.0, -18.0, 0.0, -9.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 1.0, 500.0, 0.0, 1.0, 1.0]),+ ("3:1 compression starting at -15 dB", &[3.0, -84.0, -84.0, -15.0, -15.0, 0.0, -10.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 1.0, 500.0, 0.0, 1.0, 1.0]),+ ("Soft knee compressor/gate (-24 dB threshold)", &[7.0, -84.0, -84.0, -45.6, -84.0, -41.9, -56.2, -33.4, -36.1, -24.0, -23.8, -11.0, -15.0, 0.0, -11.9, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 1.0, 500.0, 0.0, 1.0, 1.0]),+ ("Soft noise gate below -36 dB", &[6.0, -84.0, -84.0, -55.7, -84.0, -51.5, -67.2, -44.3, -49.0, -33.8, -34.1, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 1.0, 1000.0, 0.0, 0.0, 1.0]),+ ("2:1 compression starting at -18 dB (ACX)", &[3.0, -84.0, -84.0, -18.0, -18.0, 0.0, -9.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 1.0, 500.0, 0.0, 1.0, 1.0]),+ ];+}++/// Distortion: each sample's level (in dB) through an input/output curve+/// drawn on a graph — one for the positive half of the wave, one for the+/// negative — then optionally slowed in its changes of slope and darkened,+/// mixed dry and wet.+pub mod distortion {+ use super::*;++ pub const DRY: usize = 0;+ pub const WET: usize = 1;+ /// The positive half's curve: its point count, its points after it.+ pub const POSITIVE: usize = 2;+ /// The negative half's.+ pub const NEGATIVE: usize = POSITIVE + 1 + CURVE.params();+ pub const SLEW: usize = NEGATIVE + 1 + CURVE.params();+ pub const SLEW_RATE: usize = SLEW + 1;+ pub const LOW_PASS: usize = SLEW + 2;+ pub const LOW_FREQ: usize = SLEW + 3;++ /// Input level (dB) to output level (dB), −84 dB the bottom (−Inf.).+ pub const CURVE: Graph = Graph {+ points: 32,+ x: (-84.0, 0.0),+ y: (-84.0, 0.0),+ log_x: false,+ pinned_ends: true,+ x_unit: "dB",+ y_unit: "dB",+ };++ const SLEWED: &[(u8, u32)] = &[(SLEW as u8, ON)];+ const CUT: &[(u8, u32)] = &[(LOW_PASS as u8, ON)];++ const HEAD: [ParamSpec; 2] = [+ ParamSpec::num("Dry out", -60.0, 0.0, -60.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("Wet out", -60.0, 24.0, 0.0)+ .show(Show::Db)+ .decimals(1),+ ];+ const LINE: [(f32, f32); 2] = [(-84.0, -84.0), (0.0, 0.0)];+ const POS_HEAD: [ParamSpec; 1] = [ParamSpec::graph("Positive half", CURVE, 2.0)];+ const NEG_HEAD: [ParamSpec; 1] = [ParamSpec::graph("Negative half", CURVE, 2.0)];+ const POINTS: [ParamSpec; 64] = CURVE.point_params(&LINE);+ const TAIL: [ParamSpec; 4] = [+ ParamSpec::switch("Slew rate", 0.0),+ ParamSpec::num("Slew amount", 1.0, 100.0, 100.0)+ .decimals(0)+ .when(SLEWED),+ ParamSpec::switch("Low-pass", 0.0),+ ParamSpec::num("Low-pass start frequency", 100.0, 10000.0, 400.0)+ .unit("Hz")+ .decimals(0)+ .log()+ .when(CUT),+ ];+ const A: [ParamSpec; 3] = join(HEAD, POS_HEAD);+ const B: [ParamSpec; 67] = join(A, POINTS);+ const C: [ParamSpec; 68] = join(B, NEG_HEAD);+ #[allow(clippy::large_const_arrays)]+ const D: [ParamSpec; 132] = join(C, POINTS);+ #[allow(clippy::large_const_arrays)]+ const ALL: [ParamSpec; 136] = join(D, TAIL);++ pub const PARAMS: &[ParamSpec] = &ALL;++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[-60.0, 0.0, 2.0, -84.0, -84.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 2.0, -84.0, -84.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 0.0, 100.0, 0.0, 400.0]),+ ("2:1 Compression starting at -18 dB", &[-60.0, 0.0, 3.0, -84.0, -84.0, -18.0, -18.0, 0.0, -9.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 3.0, -84.0, -84.0, -18.0, -18.0, 0.0, -9.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 0.0, 100.0, 0.0, 400.0]),+ ("Soft noise gate", &[-60.0, 0.0, 6.0, -84.0, -84.0, -50.0, -84.0, -45.4, -60.0, -40.6, -46.0, -36.0, -36.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 6.0, -84.0, -84.0, -50.0, -84.0, -45.4, -60.0, -40.6, -46.0, -36.0, -36.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 0.0, 100.0, 0.0, 400.0]),+ ("Fuzz 1", &[-60.0, 0.0, 5.0, -84.0, -84.0, -44.0, -34.0, -24.0, -34.0, -24.0, -14.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 5.0, -84.0, -84.0, -44.0, -34.0, -24.0, -34.0, -24.0, -14.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 0.0, 100.0, 0.0, 400.0]),+ ("Fuzz 2", &[-60.0, 0.0, 5.0, -84.0, -84.0, -44.0, -34.0, -24.0, -34.0, -24.0, -14.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 5.0, -84.0, -84.0, -34.0, -44.0, -24.0, -34.0, -14.0, -24.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 0.0, 100.0, 0.0, 400.0]),+ ("Wet slew", &[-60.0, 0.0, 2.0, -84.0, -84.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 2.0, -84.0, -84.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 1.0, 5.0, 0.0, 400.0]),+ ("Slight chip fuzz", &[-60.0, 0.0, 2.0, -84.0, -84.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 2.0, -84.0, -84.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 1.0, 25.0, 0.0, 400.0]),+ ("Transistor 1", &[-60.0, 0.0, 4.0, -84.0, -84.0, -42.0, -66.0, -18.0, -18.0, 0.0, -8.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 4.0, -84.0, -84.0, -42.0, -66.0, -18.0, -18.0, 0.0, -8.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 0.0, 100.0, 0.0, 400.0]),+ ("Transistor 2", &[-60.0, 0.0, 4.0, -84.0, -84.0, -36.0, -72.0, -18.0, -18.0, 0.0, -12.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 4.0, -84.0, -84.0, -36.0, -72.0, -18.0, -18.0, 0.0, -12.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 0.0, 100.0, 0.0, 400.0]),+ ("Lil' Warmer", &[-60.0, 0.0, 3.0, -84.0, -84.0, -30.0, -24.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 3.0, -84.0, -84.0, -18.0, -24.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 0.0, 100.0, 0.0, 400.0]),+ ("Tube 1", &[-5.0, -1.0, 5.0, -84.0, -84.0, -71.0, -60.0, -54.0, -38.0, -30.0, -24.0, 0.0, -12.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 5.0, -84.0, -84.0, -71.0, -60.0, -54.0, -38.0, -30.0, -24.0, 0.0, -12.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 0.0, 100.0, 0.0, 400.0]),+ ("Boost positive signal", &[-60.0, -5.0, 4.0, -84.0, -84.0, -29.0, -29.0, -29.0, -10.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 4.0, -84.0, -84.0, -29.0, -29.0, -29.0, -10.0, 0.0, 0.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, -84.0, 0.0, 100.0, 0.0, 400.0]),+ ];+}++/// Graphic EQ: a frequency response drawn on a graph (straight lines in+/// dB along the octaves), applied as a linear-phase FIR filter through+/// FFTs.+pub mod graphic_eq {+ use super::*;++ /// The response's point count, its points after it.+ pub const GRAPH: usize = 0;+ pub const OUTPUT: usize = GRAPH + 1 + RESPONSE.params();+ pub const ACCURACY: usize = OUTPUT + 1;++ /// Frequency (Hz, on octaves) to gain (dB), −60 dB the bottom (−Inf.).+ pub const RESPONSE: Graph = Graph {+ points: 32,+ x: (20.0, 20000.0),+ y: (-60.0, 24.0),+ log_x: true,+ pinned_ends: true,+ x_unit: "Hz",+ y_unit: "dB",+ };++ const HEAD: [ParamSpec; 1] = [ParamSpec::graph("Graph", RESPONSE, 2.0)];+ const POINTS: [ParamSpec; 64] = RESPONSE.point_params(&[(20.0, 0.0), (20000.0, 0.0)]);+ const TAIL: [ParamSpec; 2] = [+ ParamSpec::num("Output gain", -60.0, 20.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::choice(+ "Accuracy",+ 0.0,+ &[+ "Low (fast, good for high bands)",+ "Medium (great for mid and high bands)",+ "High (slow, great for all bands)",+ ],+ 1.0,+ ),+ ];+ const FRONT: [ParamSpec; 65] = join(HEAD, POINTS);+ const ALL: [ParamSpec; 67] = join(FRONT, TAIL);++ pub const PARAMS: &[ParamSpec] = &ALL;++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[2.0, 20.0, 0.0, 20000.0, 0.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 0.0, 1.0]),+ ("Roll-off frequencies below 120 Hz", &[3.0, 20.0, -60.0, 120.0, 0.0, 20000.0, 0.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 0.0, 1.0]),+ ("Boost bass around 80 Hz by 6 dB", &[6.0, 20.0, 0.0, 36.4, 0.0, 43.5, 6.015, 126.8, 6.015, 151.5, 0.0, 20000.0, 0.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 0.0, 1.0]),+ ("Boost high frequencies above 7 kHz by 6 dB", &[4.0, 20.0, 0.0, 6402.4, 0.0, 6999.3, 6.015, 20000.0, 6.015, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 0.0, 1.0]),+ ("Boost mid-range around 1 kHz by 6 dB", &[6.0, 20.0, 0.0, 693.0, 0.0, 828.2, 6.015, 1183.0, 6.015, 1413.9, 0.0, 20000.0, 0.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 0.0, 1.0]),+ ("Boost upper three octaves", &[3.0, 20.0, 0.0, 2650.1, 0.0, 20000.0, 7.6078, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 0.0, 1.0]),+ ("Gentle high-frequency boost", &[3.0, 20.0, 0.0, 630.7, 0.0, 20000.0, 4.6507, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 0.0, 1.0]),+ ("Notch frequencies around 450 Hz", &[6.0, 20.0, 0.0, 309.1, 0.0, 369.5, -60.0, 527.7, -60.0, 630.7, 0.0, 20000.0, 0.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 20.0, -60.0, 0.0, 1.0]),+ ];+}++/// Wave Hammer Surround: a compressor and a volume maximizer (a+/// look-ahead limiter brought up to its output level), each with its own+/// bypass, the channels that steer it and those it works on.+pub mod wave_hammer {+ use super::*;++ pub const BYPASS: usize = 0;+ pub const THRESHOLD: usize = 1;+ pub const RATIO: usize = 2;+ pub const OUTPUT: usize = 3;+ pub const RMS: usize = 4;+ pub const AUTO_GAIN: usize = 5;+ pub const LOOK_AHEAD: usize = 6;+ pub const SMOOTH: usize = 7;+ pub const ATTACK: usize = 8;+ pub const RELEASE: usize = 9;+ pub const SMART: usize = 10;+ pub const MAX_BYPASS: usize = 11;+ pub const MAX_THRESHOLD: usize = 12;+ pub const MAX_OUTPUT: usize = 13;+ pub const MAX_LOOK_AHEAD: usize = 14;+ pub const MAX_RELEASE: usize = 15;+ /// The six channels that steer it (left, right, centre, left and+ /// right surround, LFE), then the six it works on.+ pub const CONTROL: usize = 16;+ pub const AFFECT: usize = 22;++ const COMPRESSING: &[(u8, u32)] = &[(BYPASS as u8, OFF)];+ const MAXIMIZING: &[(u8, u32)] = &[(MAX_BYPASS as u8, OFF)];++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::switch("Bypass compressor", 0.0).group("Compressor"),+ ParamSpec::num("Threshold", -60.0, 0.0, -12.0)+ .unit("dB")+ .decimals(1)+ .when(COMPRESSING),+ ParamSpec::num("Ratio (x:1)", 1.0, 50.0, 4.0)+ .decimals(1)+ .log()+ .when(COMPRESSING),+ ParamSpec::num("Output gain", -30.0, 30.0, 0.0)+ .unit("dB")+ .decimals(1)+ .when(COMPRESSING),+ ParamSpec::choice("Scan mode", 0.0, &["Peak", "RMS"], 1.0).when(COMPRESSING),+ ParamSpec::switch("Auto gain compensate", 0.0).when(COMPRESSING),+ ParamSpec::switch("Use longer look-ahead", 0.0).when(COMPRESSING),+ ParamSpec::switch("Smooth saturation", 1.0).when(COMPRESSING),+ ParamSpec::num("Attack time", 0.0, 500.0, 2.0)+ .unit("ms")+ .decimals(1)+ .when(COMPRESSING),+ ParamSpec::num("Release time", 0.0, 1000.0, 100.0)+ .unit("ms")+ .decimals(1)+ .when(COMPRESSING),+ ParamSpec::num("Smart release", 0.0, 100.0, 0.0)+ .decimals(0)+ .when(COMPRESSING),+ ParamSpec::switch("Bypass volume maximizer", 0.0).group("Volume maximizer"),+ ParamSpec::num("Threshold", -60.0, 0.0, 0.0)+ .unit("dB")+ .decimals(1)+ .when(MAXIMIZING),+ ParamSpec::num("Output level", -30.0, 0.0, 0.0)+ .unit("dB")+ .decimals(1)+ .when(MAXIMIZING),+ ParamSpec::switch("Use longer look-ahead", 0.0).when(MAXIMIZING),+ ParamSpec::num("Release time", 0.0, 1000.0, 100.0)+ .unit("ms")+ .decimals(1)+ .when(MAXIMIZING),+ ParamSpec::switch("L", 1.0).group("Channels to use for the control signal"),+ ParamSpec::switch("R", 1.0),+ ParamSpec::switch("C", 1.0),+ ParamSpec::switch("Ls", 1.0),+ ParamSpec::switch("Rs", 1.0),+ ParamSpec::switch("LFE", 0.0),+ ParamSpec::switch("L", 1.0).group("Channels to affect"),+ ParamSpec::switch("R", 1.0),+ ParamSpec::switch("C", 1.0),+ ParamSpec::switch("Ls", 1.0),+ ParamSpec::switch("Rs", 1.0),+ ParamSpec::switch("LFE", 0.0),+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[0.0, -12.0, 4.0, 0.0, 1.0, 0.0, 0.0, 1.0, 2.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]),+ ("Deep compression", &[0.0, -35.0, 8.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 100.0, 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]),+ ("Medium compression", &[0.0, -20.0, 2.0, 0.0, 1.0, 1.0, 0.0, 0.0, 1.0, 25.0, 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]),+ ("Master for 16-bit", &[0.0, -6.0, 1.5, 0.0, 1.0, 1.0, 0.0, 1.0, 150.0, 150.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]),+ ("Voice", &[0.0, -10.0, 5.0, 0.0, 1.0, 1.0, 0.0, 0.0, 5.0, 50.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]),+ ("Guitar", &[0.0, -20.0, 5.0, -6.0, 1.0, 1.0, 0.0, 0.0, 15.0, 15.0, 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]),+ ("Bass", &[0.0, -20.0, 6.0, -6.0, 1.0, 1.0, 0.0, 0.0, 40.0, 80.0, 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]),+ ("Smooth compression", &[0.0, -8.0, 3.5, 0.0, 1.0, 1.0, 0.0, 1.0, 10.0, 1000.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]),+ ("Drums", &[0.0, -10.0, 3.5, 0.0, 0.0, 1.0, 0.0, 1.0, 3.0, 150.0, 0.0, 0.0, 0.0, 0.0, 0.0, 20.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]),+ ("Limit at 6 dB and maximize", &[1.0, -6.0, 50.0, 0.0, 1.0, 0.0, 0.0, 1.0, 2.0, 100.0, 0.0, 0.0, -6.0, 0.0, 0.0, 100.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]),+ ("Bypass", &[1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0, 2.0, 100.0, 0.0, 1.0, 0.0, 0.0, 0.0, 100.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]),+ ("Guitar distortion 1", &[0.0, -30.0, 10.0, -10.0, 0.0, 1.0, 0.0, 0.0, 3.0, 5.0, 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]),+ ("Guitar distortion 2", &[0.0, -35.0, 20.0, -10.0, 1.0, 1.0, 1.0, 1.0, 0.3, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]),+ ("Guitar distortion 3 (fuzzy)", &[0.0, -35.0, 20.0, -10.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 100.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0]),+ ];+}++/// Gate: below the threshold the sound is lowered by the range (all the+/// way at 90 dB), opened and closed smoothly, held a while, steered by a+/// filtered copy of itself and seen a little ahead.+pub mod efx_gate {+ use super::*;++ pub const INPUT: usize = 0;+ pub const OUTPUT: usize = 1;+ pub const THRESHOLD: usize = 2;+ pub const RANGE: usize = 3;+ pub const ATTACK: usize = 4;+ pub const RELEASE: usize = 5;+ pub const HOLD: usize = 6;+ pub const SOFT_KNEE: usize = 7;+ pub const LOOK_AHEAD: usize = 8;+ pub const FILTER_TYPE: usize = 9;+ pub const FILTER: usize = 10;+ pub const LISTEN: usize = 11;+ pub const INPUT_HIGH_PASS: usize = 12;++ const FILTERED: &[(u8, u32)] = &[(FILTER_TYPE as u8, !1)];++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Input", -24.0, 24.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Output", -24.0, 24.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Threshold", -90.0, 0.0, -24.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Range", 0.0, 90.0, 12.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Attack", 0.05, 100.0, 0.05)+ .unit("ms")+ .decimals(2)+ .log(),+ ParamSpec::num("Release", 10.0, 2500.0, 250.0)+ .unit("ms")+ .decimals(0)+ .log(),+ ParamSpec::choice("Hold", 0.0, &["Short", "Medium", "Long"], 1.0),+ ParamSpec::switch("Soft knee", 0.0),+ ParamSpec::num("Look ahead", 0.0, 5.0, 0.5)+ .unit("ms")+ .decimals(2),+ ParamSpec::choice(+ "Side chain filter",+ 0.0,+ &["Off", "High-pass", "Band-pass", "Low-pass"],+ 1.0,+ )+ .group("Side chain"),+ ParamSpec::num("Filter frequency", 20.0, 10000.0, 20.0)+ .unit("Hz")+ .decimals(0)+ .log()+ .when(FILTERED),+ ParamSpec::switch("Listen to the side chain", 0.0),+ ParamSpec::num("Input high-pass", 0.0, 500.0, 20.0)+ .unit("Hz")+ .decimals(0),+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default", &[0.0, 0.0, -24.0, 12.0, 0.05, 250.29, 1.0, 0.0, 0.5, 1.0, 20.0, 0.0, 20.0]),+ ("Attack Enhancer 6dB Kick", &[0.0, 6.0, -12.01, 6.0, 0.05, 80.12, 0.0, 0.0, 0.5, 3.0, 135.06, 0.0, 20.0]),+ ("Attack Enhancer 6dB Snare", &[0.0, 6.0, -12.01, 6.0, 0.05, 80.12, 0.0, 0.0, 0.5, 2.0, 806.47, 0.0, 20.0]),+ ("Delete Breath", &[0.0, 0.0, -16.98, 49.9, 0.87, 126.57, 2.0, 1.0, 0.5, 0.0, 2670.94, 0.0, 20.0]),+ ("Snare Cleanup", &[0.0, 0.0, -27.4, 16.04, 0.05, 118.99, 1.0, 0.0, 0.5, 2.0, 276.19, 0.0, 20.0]),+ ("Try On Drums", &[0.0, 0.0, -27.4, 14.49, 0.05, 109.3, 1.0, 1.0, 0.5, 2.0, 1079.53, 0.0, 20.0]),+ ("Voiceover Gate", &[0.0, 0.0, -40.96, 21.79, 4.99, 69.55, 1.0, 0.0, 0.5, 1.0, 60.06, 0.0, 20.0]),+ ("Vox Cleanup", &[0.0, 0.0, -43.49, 25.96, 5.43, 210.11, 2.0, 1.0, 0.5, 2.0, 821.31, 0.0, 20.0]),+ ];+}++/// DeEsser: the hiss of "s" sounds turned down when a band around its+/// frequency stands out from the rest of the sound.+pub mod efx_deesser {+ use super::*;++ pub const INPUT: usize = 0;+ pub const OUTPUT: usize = 1;+ pub const FREQUENCY: usize = 2;+ pub const REDUCTION: usize = 3;+ pub const Q: usize = 4;+ pub const LISTEN: usize = 5;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Input", -24.0, 24.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Output", -24.0, 24.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Frequency", 2000.0, 12000.0, 7000.0)+ .unit("Hz")+ .decimals(0)+ .log(),+ ParamSpec::num("Reduction", 0.0, 36.0, 6.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Filter Q", 0.1, 2.0, 0.18).decimals(2).log(),+ ParamSpec::switch("Listen", 0.0),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default", &[0.0, 0.0, 7000.0, 6.0, 0.18, 0.0]),+ ("Female Vox", &[0.0, 0.0, 8000.0, 9.3, 0.18, 0.0]),+ ("Male Vox", &[0.0, 0.0, 5950.0, 7.6, 0.18, 0.0]),+ ];+}++/// Limiter: the sound held under its threshold (seen ahead, by its peak+/// or its power), brought back up when asked, then pushed into a clipper+/// whose shape runs from soft to hard.+pub mod efx_limiter {+ use super::*;++ pub const INPUT: usize = 0;+ pub const OUTPUT: usize = 1;+ pub const THRESHOLD: usize = 2;+ pub const RELEASE: usize = 3;+ pub const CLIP_GAIN: usize = 4;+ pub const ATTACK: usize = 5;+ pub const ADAPTIVE: usize = 6;+ pub const PEAK_RMS: usize = 7;+ pub const MAKEUP: usize = 8;+ pub const INPUT_LOW_CUT: usize = 9;+ pub const SIDE_LOW_CUT: usize = 10;+ pub const CLIP_SHAPE: usize = 11;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Input", -24.0, 24.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Output", -24.0, 0.0, -0.1)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Threshold", -30.0, 0.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Release", 1.0, 1000.0, 10.0)+ .unit("ms")+ .decimals(1)+ .log(),+ ParamSpec::num("Clip gain", -12.0, 12.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Attack", 1.0, 100.0, 1.0)+ .unit("ms")+ .decimals(1)+ .log()+ .group("Tweak"),+ ParamSpec::num("Adaptive release", 0.0, 1.0, 1.0)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Peak vs. RMS", 0.0, 1.0, 0.0)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::switch("Auto makeup", 1.0),+ ParamSpec::num("Input low cut", 0.0, 100.0, 0.0)+ .unit("Hz")+ .decimals(0),+ ParamSpec::num("Side chain low cut", 0.0, 500.0, 0.0)+ .unit("Hz")+ .decimals(0),+ ParamSpec::num("Clip shape", 0.0, 1.0, 1.0)+ .show(Show::Percent)+ .decimals(0),+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default", &[0.0, -0.1, 0.0, 10.0, 0.0, 1.0, 1.0, 0.0, 1.0, 0.0, 0.0, 1.0]),+ ("Default - no AutoMakeup", &[0.0, -0.1, 0.0, 10.0, 0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0]),+ ("Classical Limiter (Transparent)", &[0.0, -0.1, 0.0, 205.05, 0.0, 1.0, 1.0, 0.0, 1.0, 25.0, 0.0, 0.85]),+ ("Dance Limiter (Loud)", &[0.0, -0.1, 0.0, 7.01, 0.0, 1.43, 0.65, 0.1, 1.0, 20.0, 49.7, 0.85]),+ ("Dance Limiter (Moderate)", &[0.0, -0.1, 0.0, 12.19, 0.0, 1.21, 0.86, 0.0, 1.0, 20.0, 20.14, 0.86]),+ ("Dance Limiter (Tight Bass)", &[0.0, -0.1, 0.0, 19.68, 0.0, 5.0, 0.91, 0.16, 1.0, 40.0, 60.77, 0.96]),+ ("Drum Buss Fattener +6dB", &[0.0, -0.1, -3.0, 15.43, 3.0, 7.03, 0.5, 0.2, 1.0, 20.0, 39.65, 0.67]),+ ("HipHop Limiter +6dB (Tight Bass)", &[0.0, -0.1, -6.0, 5.05, 0.0, 2.81, 0.39, 0.22, 1.0, 21.88, 39.65, 0.75]),+ ("Pop Maximizer +6dB (Transparent)", &[0.0, -0.1, -6.0, 34.64, 0.0, 1.0, 1.0, 0.0, 1.0, 15.0, 25.18, 0.85]),+ ("Rock Clipper +6dB (Soft Transients)", &[0.0, -0.1, -3.0, 10.38, 3.0, 1.96, 0.81, 0.21, 1.0, 20.0, 65.22, 0.41]),+ ("Rock Maximizer +6dB", &[0.0, -0.1, -6.0, 5.16, 0.0, 10.46, 0.75, 0.2, 1.0, 20.0, 49.7, 0.76]),+ ];+}++/// Tremolo Pan: the level of each side following an oscillator from a+/// sine toward a square; the right side's oscillator moved on by the phase+/// (half a round: an auto-pan).+pub mod efx_tremolo_pan {+ use super::*;++ pub const INPUT: usize = 0;+ pub const OUTPUT: usize = 1;+ pub const RATE: usize = 2;+ pub const SHAPE: usize = 3;+ pub const PHASE: usize = 4;+ pub const DEPTH: usize = 5;+ pub const SYNC: usize = 6;+ pub const NOTE: usize = 7;++ const FREE: &[(u8, u32)] = &[(SYNC as u8, OFF)];+ const SYNCED: &[(u8, u32)] = &[(SYNC as u8, ON)];++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Input", -24.0, 24.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Output", -24.0, 24.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Rate", 0.2, 2850.0, 1.0)+ .unit("Hz")+ .decimals(2)+ .log()+ .when(FREE),+ ParamSpec::num("Shape", 0.0, 1.0, 0.0)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Phase", 0.0, 1.0, 0.0)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Depth", 0.0, 1.0, 1.0)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::switch("Tempo sync", 0.0),+ ParamSpec::choice("Note", 0.0, tempo::NOTES_OR_MEASURE, tempo::QUARTER).when(SYNCED),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default", &[0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 13.0]),+ ("440 Hz noise", &[0.0, 0.0, 440.0, 0.0, 0.0, 1.0, 0.0, 13.0]),+ (+ "Fast modulation",+ &[0.0, 0.0, 5.28, 0.75, 0.0, 1.0, 0.0, 13.0],+ ),+ (+ "Slow modulation",+ &[0.0, 0.0, 1.4, 0.5, 0.0, 1.0, 0.0, 13.0],+ ),+ ];+}++/// Tube Stage: one or two triode stages (class A or AB) driven by the+/// gain, an EQ before and after, and the stages run at twice the rate+/// when oversampling.+pub mod efx_tube_stage {+ use super::*;++ pub const INPUT: usize = 0;+ pub const OUTPUT: usize = 1;+ pub const PRE_EQ: usize = 2;+ pub const DRIVE: usize = 3;+ pub const POST_EQ: usize = 4;+ pub const OVERSAMPLE: usize = 5;+ pub const STAGES: usize = 6;+ pub const CLASS: usize = 7;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Input", -24.0, 24.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Output", -24.0, 24.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Pre EQ", -1.0, 1.0, 0.0).decimals(2),+ ParamSpec::num("Drive", 0.0, 24.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Post EQ", -1.0, 1.0, 0.0).decimals(2),+ ParamSpec::switch("Oversample", 1.0),+ ParamSpec::choice("Stages", 1.0, &["1", "2"], 1.0),+ ParamSpec::choice("Class", 0.0, &["A", "AB"], 0.0),+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default", &[0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 0.0]),+ ("Aggressive Bassdrum", &[10.08, -16.8, -0.57, 18.36, -0.57, 1.0, 1.0, 0.0]),+ ("Reamp", &[0.0, -9.36, 0.47, 11.87, -0.22, 1.0, 2.0, 1.0]),+ ("Bluesguitar", &[18.72, -22.56, -0.11, 0.91, 0.32, 1.0, 1.0, 0.0]),+ ("Bring Forward", &[5.28, -8.4, 0.29, 5.74, 0.32, 0.0, 1.0, 1.0]),+ ("Crunchy Guitar", &[18.72, -22.56, 0.18, 7.67, 0.28, 1.0, 1.0, 0.0]),+ ("Dirty Drums", &[10.08, -12.0, -0.22, 9.99, 0.36, 1.0, 1.0, 0.0]),+ ("Fatten", &[14.16, -19.2, -0.55, 13.11, 0.59, 0.0, 1.0, 1.0]),+ ("Loud Neighbours", &[5.28, -13.2, -1.0, 7.67, -1.0, 1.0, 1.0, 1.0]),+ ("Lush Mix", &[5.76, -10.08, -0.39, 11.32, 0.34, 0.0, 2.0, 1.0]),+ ("Megaphone", &[0.0, -15.12, 0.56, 15.15, 0.67, 1.0, 2.0, 0.0]),+ ("More Presence", &[5.28, -8.4, 0.48, 8.33, 0.43, 0.0, 2.0, 0.0]),+ ("Old Radio", &[5.52, -10.56, 0.02, 9.99, 0.0, 1.0, 2.0, 0.0]),+ ("Older Radio", &[5.52, -13.68, -0.5, 12.49, -0.27, 1.0, 2.0, 0.0]),+ ("Rhythm Guitar", &[9.36, -22.56, 0.22, 24.0, -0.46, 1.0, 2.0, 0.0]),+ ("Rough Vocals", &[11.04, -15.84, -0.26, 9.25, 0.21, 1.0, 2.0, 0.0]),+ ("Tube Fryer", &[0.0, -7.68, 1.0, 8.33, -0.33, 1.0, 2.0, 0.0]),+ ("Vintage Organ Toolkit", &[8.88, -16.32, -0.62, 6.87, 0.2, 1.0, 1.0, 0.0]),+ ("Warm Tube Preamp", &[0.0, -5.04, 0.26, 6.67, -0.27, 1.0, 2.0, 0.0]),+ ("Tube console - Master Buss", &[0.0, -5.28, 0.19, 5.93, -0.07, 1.0, 2.0, 1.0]),+ ("Tube console - place on every mixer channel", &[0.0, -0.96, 0.19, 1.94, -0.07, 1.0, 2.0, 1.0]),+ ];+}++/// Vocal Strip: a voice's chain in one — a high-pass, a gate, a de-esser,+/// a compressor and a tone tilt.+pub mod efx_vocal_strip {+ use super::*;++ pub const INPUT: usize = 0;+ pub const OUTPUT: usize = 1;+ pub const HIGH_PASS: usize = 2;+ pub const GATE: usize = 3;+ pub const DEESSER: usize = 4;+ pub const COMPRESSION: usize = 5;+ pub const TONE: usize = 6;+ pub const DEESS_FREQUENCY: usize = 7;+ pub const ATTACK: usize = 8;+ pub const ADAPTIVE: usize = 9;+ pub const MAKEUP: usize = 10;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Input", -24.0, 24.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Output", -24.0, 24.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("High-pass", 20.0, 500.0, 20.0)+ .unit("Hz")+ .decimals(0)+ .log(),+ ParamSpec::num("Gate", -90.0, 0.0, -90.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::num("De-esser", 0.0, 36.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Compression", 0.0, 48.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Tone", -1.0, 1.0, 0.0).decimals(2),+ ParamSpec::num("De-ess frequency", 4000.0, 12000.0, 7000.0)+ .unit("Hz")+ .decimals(0)+ .log()+ .group("Tweak"),+ ParamSpec::num("Compressor attack", 0.2, 10.0, 0.7)+ .unit("ms")+ .decimals(1)+ .log(),+ ParamSpec::num("Compressor adaptive release", 0.0, 10.0, 4.0).decimals(1),+ ParamSpec::switch("Compressor auto makeup", 1.0),+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default", &[0.0, 0.0, 20.0, -90.0, 0.0, 0.0, 0.0, 7000.0, 0.7, 4.0, 1.0]),+ ("Vocal with de-squeak", &[0.0, 0.0, 50.0, -90.0, 18.36, 7.92, 0.16, 7000.0, 0.7, 4.0, 1.0]),+ ("Vocal", &[0.0, 0.0, 50.0, -90.0, 0.0, 7.92, 0.16, 7000.0, 0.7, 4.0, 1.0]),+ ("Bass Guitar channel", &[0.0, 0.0, 20.0, -90.0, 0.0, 11.28, 0.4, 7000.0, 0.7, 4.0, 1.0]),+ ("Breakbeats", &[0.0, 3.0, 50.0, -30.02, 9.0, 10.05, 0.25, 7000.0, 0.7, 4.0, 1.0]),+ ("Vocal (strong)", &[0.0, 0.0, 20.0, -90.0, 0.0, 14.64, 0.35, 7000.0, 0.7, 4.0, 1.0]),+ ("Vocal (gated)", &[0.0, 0.0, 57.9, -49.42, 0.0, 10.32, 0.53, 7000.0, 0.7, 4.0, 1.0]),+ ("Commercial", &[0.0, 4.8, 119.0, -37.73, 16.02, 32.16, 0.5, 7000.0, 0.7, 4.0, 1.0]),+ ("Female Rock", &[0.0, 4.0, 120.09, -42.36, 15.3, 24.96, 0.51, 7000.0, 0.7, 4.0, 1.0]),+ ("Female Up-Front", &[0.0, 3.12, 129.03, -27.31, 15.8, 30.24, 0.29, 7000.0, 1.45, 2.25, 1.0]),+ ("Female Voiceover Soft", &[6.0, 6.0, 79.65, -58.32, 10.8, 23.04, 0.25, 7000.0, 0.7, 4.0, 1.0]),+ ("Female Voiceover", &[0.0, 2.16, 100.02, -39.23, 10.08, 24.0, 0.41, 7000.0, 0.7, 4.0, 1.0]),+ ("Male Rap vocal", &[0.0, 0.0, 50.0, -90.0, 7.74, 15.36, 0.33, 5840.0, 0.7, 4.0, 1.0]),+ ("Male Rock", &[0.0, 3.6, 79.62, -43.0, 12.04, 28.56, 0.46, 6320.0, 1.5, 1.7, 1.0]),+ ("Male vocal", &[0.0, 0.0, 49.26, -90.0, 6.84, 13.44, 0.14, 6440.0, 0.7, 4.0, 1.0]),+ ("Male Voiceover", &[0.0, 2.4, 109.81, -45.2, 12.96, 24.96, 0.51, 6120.0, 0.7, 2.32, 1.0]),+ ("Rap", &[0.0, 2.0, 79.65, -42.02, 15.12, 30.7, 0.51, 5600.0, 0.7, 1.7, 1.0]),+ ("Talkback Drum Treatment", &[0.0, 3.12, 150.02, -90.0, 0.0, 24.0, -0.69, 4680.0, 0.2, 0.3, 1.0]),+ ("Vintage Vox Channel", &[5.04, 4.32, 129.03, -40.79, 6.3, 21.84, 0.19, 6800.0, 4.05, 5.34, 1.0]),+ ];+}++/// Compressor: a feedback compressor (its gain steers its own detector),+/// a three-speed release that follows the material, parallel mix, soft+/// clip, and a filtered side chain.+pub mod efx_compressor {+ use super::*;++ pub const INPUT: usize = 0;+ pub const OUTPUT: usize = 1;+ pub const THRESHOLD: usize = 2;+ pub const RATIO: usize = 3;+ pub const ATTACK: usize = 4;+ pub const RELEASE: usize = 5;+ pub const ADAPTIVE: usize = 6;+ pub const MAKEUP: usize = 7;+ pub const SOFT_CLIP: usize = 8;+ pub const MIX: usize = 9;+ pub const FILTER_TYPE: usize = 10;+ pub const FILTER: usize = 11;+ pub const LISTEN: usize = 12;++ const FILTERED: &[(u8, u32)] = &[(FILTER_TYPE as u8, !1)];++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Input", 0.0, 1.0, 1.0)+ .show(Show::GainDb)+ .decimals(1),+ ParamSpec::num("Output", -24.0, 24.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Threshold", -40.0, 0.0, 0.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Ratio (x:1)", 1.0, 20.0, 5.75)+ .decimals(1)+ .log(),+ ParamSpec::num("Attack", 0.1, 100.0, 3.16)+ .unit("ms")+ .decimals(2)+ .log(),+ ParamSpec::num("Release", 10.0, 2000.0, 141.4)+ .unit("ms")+ .decimals(0)+ .log(),+ ParamSpec::num("Adaptive release", 0.0, 10.0, 2.3)+ .decimals(1)+ .group("Tweak"),+ ParamSpec::switch("Auto makeup", 0.0),+ ParamSpec::switch("Soft clip", 0.0),+ ParamSpec::num("Mix", 0.0, 1.0, 1.0)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::choice(+ "Side chain filter",+ 0.0,+ &["Off", "High-pass", "Band-pass", "Low-pass"],+ 1.0,+ )+ .group("Side chain"),+ ParamSpec::num("Filter frequency", 20.0, 10000.0, 20.0)+ .unit("Hz")+ .decimals(0)+ .log()+ .when(FILTERED),+ ParamSpec::switch("Listen to the side chain", 0.0),+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default", &[1.0, 0.0, 0.0, 5.75, 3.1623, 141.4, 2.3, 0.0, 0.0, 1.0, 1.0, 20.0, 0.0]),+ ("FET style 1", &[1.0, 3.84, -9.2667, 11.45, 0.1413, 952.5, 2.3, 0.0, 0.0, 1.0, 1.0, 20.0, 0.0]),+ ("FET - 1-Parallel compression - Female vocal", &[1.0, 1.92, -9.2667, 5.9743, 0.2723, 348.1, 2.3, 0.0, 1.0, 0.7562, 1.0, 20.0, 0.0]),+ ("FET style 2", &[1.0, 3.84, -11.27, 11.45, 0.1, 10.0, 2.3, 0.0, 0.0, 1.0, 1.0, 20.0, 0.0]),+ ("FET - Drum buss", &[1.0, 6.0, -14.47, 14.3, 0.1514, 17.91, 2.3, 0.0, 1.0, 1.0, 0.0, 20.0, 0.0]),+ ("FET - Parallel Comp. Drum buss", &[1.0, 6.24, -16.87, 14.3, 0.1514, 17.91, 2.3, 0.0, 1.0, 0.6625, 0.0, 20.0, 0.0]),+ ("FET - Parallel compression - Hairy", &[1.0, 3.6, -10.6, 20.0, 0.1, 10.0, 2.3, 0.0, 1.0, 0.9125, 1.0, 20.0, 0.0]),+ ("Bus Comp - Drums NY Style", &[1.0, 15.02, -25.78, 20.0, 0.1, 89.25, 2.3, 0.0, 0.0, 1.0, 1.0, 182.3, 0.0]),+ ("Bus Comp - snare enhancement", &[1.0, 4.387, -12.43, 20.0, 1.0469, 34.92, 2.3, 0.0, 0.0, 1.0, 1.0, 182.3, 0.0]),+ ("Bus Comp - snare enhancement 2", &[1.0, 17.6, -40.0, 3.2313, 15.73, 212.9, 2.3, 0.0, 0.0, 1.0, 1.0, 182.3, 0.0]),+ ("Classic Program Limiter", &[1.0, 0.0, -4.0, 20.0, 0.1719, 13.1, 3.0, 1.0, 1.0, 1.0, 1.0, 272.0, 0.0]),+ ("Acoustic Guitar", &[1.0, 3.2773, -12.728, 4.3057, 15.49, 74.15, 2.3, 0.0, 0.0, 1.0, 1.0, 20.0, 0.0]),+ ("Bass Guitar", &[1.0, 3.2773, -13.33, 5.5161, 10.85, 502.9, 2.3, 0.0, 0.0, 1.0, 1.0, 20.0, 0.0]),+ ("Drums", &[1.0, 4.4474, -8.5518, 6.2066, 0.5068, 45.9, 2.3, 0.0, 0.0, 1.0, 1.0, 20.0, 0.0]),+ ("Electric Guitar", &[1.0, 0.0, -9.3978, 1.7886, 0.2079, 31.45, 2.3, 0.0, 0.0, 1.0, 1.0, 20.0, 0.0]),+ ("Master Mixdown", &[1.0, 1.05, -7.113, 1.6097, 0.1312, 36.542, 2.3, 0.0, 0.0, 1.0, 1.0, 20.0, 0.0]),+ ("OverCompressed Vocals", &[1.0, 9.0152, -21.93, 17.99, 0.6415, 16.84, 2.3, 0.0, 0.0, 1.0, 1.0, 20.0, 0.0]),+ ("Premastering", &[1.0, 0.0, -7.113, 1.6008, 0.1705, 182.5, 2.3, 0.0, 0.0, 1.0, 1.0, 20.0, 0.0]),+ ("Vocals", &[1.0, 3.9787, -13.33, 2.2777, 0.1172, 16.0, 2.3, 0.0, 0.0, 1.0, 1.0, 20.0, 0.0]),+ ("Drum Buss Ambience & Fatness", &[1.0, 4.9148, -13.15, 11.73, 0.2335, 34.48, 2.3, 0.0, 1.0, 1.0, 1.0, 242.9, 0.0]),+ ("Drum Buss Ambience", &[1.0, 4.9148, -13.15, 11.73, 0.2335, 34.48, 2.3, 0.0, 1.0, 1.0, 1.0, 242.9, 0.0]),+ ("Drum Slammer", &[1.0, 4.9148, -22.55, 13.98, 0.1653, 34.48, 2.3, 0.0, 0.0, 1.0, 1.0, 126.5, 0.0]),+ ("Extreme Guitar Compression", &[1.0, 8.3636, -20.875, 7.0159, 1.4974, 484.4, 2.3, 0.0, 0.0, 1.0, 1.0, 77.0, 0.0]),+ ("Fat Kick", &[1.0, 2.64, -10.2, 3.6011, 3.1623, 397.4, 2.3, 0.0, 0.0, 1.0, 0.0, 20.0, 0.0]),+ ("Hot Master", &[1.0, 4.8, -13.2, 1.4275, 5.8884, 18.39, 2.3, 0.0, 1.0, 1.0, 1.0, 807.1, 0.0]),+ ("Peak Stop", &[1.0, 0.0, 0.0, 20.0, 0.1, 10.0, 2.3, 0.0, 1.0, 1.0, 0.0, 20.0, 0.0]),+ ("Reggae Guitar Strong", &[1.0, 5.8498, -13.22, 3.5303, 7.2066, 110.9, 2.3, 0.0, 0.0, 1.0, 1.0, 20.0, 0.0]),+ ("Sequencer Compression", &[1.0, 5.76, -14.931, 12.9, 0.5248, 44.4, 2.3, 0.0, 0.0, 1.0, 1.0, 178.0, 0.0]),+ ("Synth Bass Compression", &[1.0, 4.7383, -14.931, 10.18, 3.3114, 79.77, 2.3, 0.0, 0.0, 1.0, 1.0, 121.7, 0.0]),+ ("Vintage VCA style", &[1.0, 1.68, -10.6, 8.6613, 3.6308, 693.1, 2.3, 0.0, 0.0, 1.0, 1.0, 20.0, 0.0]),+ ("Parallel Compression - Glue", &[1.0, 3.6, -16.6, 5.8455, 0.1567, 85.49, 2.3, 0.0, 1.0, 0.7375, 1.0, 20.0, 0.0]),+ ("Parallel Kick Compression", &[1.0, 1.92, -11.2, 11.55, 0.1567, 83.26, 2.3, 0.0, 1.0, 0.7188, 1.0, 20.0, 0.0]),+ ("Parallel Overhead Drum Compression", &[1.0, 3.6, -16.6, 11.55, 0.1567, 95.05, 2.3, 0.0, 1.0, 0.7375, 1.0, 20.0, 0.0]),+ ];+}++/// Phaser: four, eight or twelve all-pass stages swept around a centre+/// by an oscillator (the right side's moved on by the phase), fed back,+/// mixed with the sound.+pub mod efx_phaser {+ use super::*;++ pub const MODE: usize = 0;+ pub const INPUT: usize = 1;+ pub const OUTPUT: usize = 2;+ pub const RATE: usize = 3;+ pub const DEPTH: usize = 4;+ pub const PHASE: usize = 5;+ pub const FEEDBACK: usize = 6;+ pub const CENTER: usize = 7;+ pub const MIX: usize = 8;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::choice("Stages", 0.0, &["4", "8", "12"], 0.0),+ ParamSpec::num("Input", 0.0, 1.0, 1.0)+ .show(Show::GainDb)+ .decimals(1),+ ParamSpec::num("Output", 0.0, 1.0, 1.0)+ .show(Show::GainDb)+ .decimals(1),+ ParamSpec::num("Rate", 0.01, 15.0, 3.008)+ .unit("Hz")+ .decimals(2)+ .log(),+ ParamSpec::num("Depth", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Phase offset", 0.0, 1.0, 0.0)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Feedback", 0.0, 1.0, 0.0)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Center frequency", 50.0, 5000.0, 850.0)+ .unit("Hz")+ .decimals(0)+ .log(),+ ParamSpec::num("Mix", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(0),+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default", &[0.0, 1.0, 1.0, 3.008, 0.5, 0.0, 0.0, 850.0, 0.5]),+ ("4 Stage Feedback", &[0.0, 1.0, 0.5, 0.01, 0.0, 0.0, 1.0, 850.0, 1.0]),+ ("Bad Experience", &[2.0, 1.0, 1.0, 5.0316, 0.65, 0.0, 0.225, 850.0, 1.0]),+ ("Drum Resonator", &[1.0, 1.0, 0.725, 10.66, 0.2676, 0.0, 0.8836, 581.8, 0.6525]),+ ("Fast Vibrato", &[0.0, 1.0, 1.0, 14.21, 0.4534, 0.1676, 0.0, 421.4, 1.0]),+ ("Fat Synth", &[2.0, 1.0, 1.0, 5.8154, 0.9231, 0.0837, 0.5, 603.7, 0.6]),+ ("Full Power", &[0.0, 1.0, 0.5, 15.0, 1.0, 0.0, 1.0, 850.0, 1.0]),+ ("Guitar Stereo Swirl", &[0.0, 1.0, 1.0, 8.8998, 0.915, 0.25, 0.0, 850.0, 0.5]),+ ("Monovibe", &[0.0, 1.0, 1.0, 4.0573, 0.915, 0.0, 0.07, 850.0, 0.5]),+ ("Mushroomed Drums", &[2.0, 1.0, 0.705, 5.5962, 0.5253, 0.1356, 1.0, 850.0, 0.67]),+ ("Phasing pad", &[1.0, 1.0, 1.0, 0.7838, 0.2586, 0.0, 0.3921, 850.0, 0.5946]),+ ("Spring Fx", &[1.0, 1.0, 1.0, 13.117, 0.5061, 0.0, 0.6691, 850.0, 0.615]),+ ("Synth Pad Liquid", &[1.0, 1.0, 1.0, 4.5463, 0.55, 1.0, 0.0, 394.0, 0.385]),+ ("Synth Pad Mover", &[1.0, 1.0, 1.0, 1.5547, 1.0, 0.25, 0.205, 403.0, 0.575]),+ ("Under Water", &[0.0, 1.0, 0.685, 8.5303, 0.91, 0.0, 0.504, 850.0, 0.8]),+ ];+}++/// Chorus/Flanger: three modulated voices a side (a chorus, a flanger or+/// a wide ensemble), fed back, their lows cut, mixed with the sound.+pub mod efx_chorus_flanger {+ use super::*;++ pub const MODE: usize = 0;+ pub const INPUT: usize = 1;+ pub const OUTPUT: usize = 2;+ pub const RATE: usize = 3;+ pub const DEPTH: usize = 4;+ pub const PHASE: usize = 5;+ pub const FEEDBACK: usize = 6;+ pub const LOW_CUT: usize = 7;+ pub const MIX: usize = 8;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::choice("Mode", 0.0, &["Chorus", "Flanger", "Ensemble"], 0.0),+ ParamSpec::num("Input", 0.0, 1.0, 1.0)+ .show(Show::GainDb)+ .decimals(1),+ ParamSpec::num("Output", 0.0, 1.0, 1.0)+ .show(Show::GainDb)+ .decimals(1),+ ParamSpec::num("Rate", 0.01, 15.0, 0.993)+ .unit("Hz")+ .decimals(2)+ .log(),+ ParamSpec::num("Depth", 0.0, 1.0, 0.25)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Phase offset", 0.0, 1.0, 0.25)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Feedback", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Low cut", 20.0, 1000.0, 20.0)+ .unit("Hz")+ .decimals(0)+ .log(),+ ParamSpec::num("Mix", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(0),+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default", &[0.0, 1.0, 1.0, 0.9929, 0.25, 0.25, 0.5, 20.0, 0.5]),+ ("Acoustic Guitar", &[0.0, 1.0, 1.0, 1.0697, 0.3171, 0.0556, 0.4412, 64.55, 0.5]),+ ("Chorus Classic Bass", &[0.0, 1.0, 1.0, 0.8642, 0.372, 0.0, 0.4519, 199.8, 0.5]),+ ("Chorus Fx Any Direction", &[0.0, 1.0, 1.0, 15.0, 0.2075, 0.5, 0.5491, 20.0, 0.71]),+ ("Chorus Vocal Spread", &[0.0, 1.0, 1.0, 0.548, 0.2944, 0.5, 0.63, 90.0, 0.4899]),+ ("Flanger Pad Enhancer", &[1.0, 1.0, 1.0, 0.2571, 0.6719, 0.6665, 0.45, 50.04, 0.5]),+ ("Heavy Stereo Chorus Fx", &[0.0, 1.0, 0.175, 0.01, 1.0, 0.0, 1.0, 20.0, 1.0]),+ ("Heavy Stereo Flanger Fx", &[1.0, 1.0, 0.175, 0.01, 1.0, 0.0, 1.0, 20.0, 1.0]),+ ("Keys Shimmering", &[2.0, 1.0, 1.0, 1.0697, 0.6487, 0.474, 0.6762, 90.0, 0.595]),+ ("Lush And Wide Open", &[2.0, 1.0, 1.0, 0.8364, 0.6905, 0.5, 0.25, 20.0, 0.5]),+ ("Reggae Guitar Chorus", &[0.0, 1.0, 1.0, 0.6109, 0.3971, 0.0, 0.6129, 20.0, 0.3396]),+ ("Electric Piano Chorus", &[0.0, 1.0, 1.0, 0.4925, 0.25, 0.5, 0.7, 50.04, 0.31]),+ ("Stereo Ensemble", &[2.0, 1.0, 1.0, 0.657, 0.6538, 1.0, 0.2391, 90.0, 0.81]),+ ("Strong Guitar Chorus", &[0.0, 1.0, 1.0, 0.4694, 0.7418, 0.0, 0.6129, 45.26, 0.3333]),+ ("Vox Alien Warble", &[2.0, 1.0, 0.94, 4.7682, 0.5563, 1.0, 0.775, 74.96, 0.82]),+ ("Vox Chorus", &[0.0, 1.0, 1.0, 0.3233, 0.5791, 1.0, 0.26, 60.38, 0.5]),+ ("Vox Vibrato Mono", &[1.0, 1.0, 0.94, 7.505, 0.6719, 0.0, 0.225, 50.04, 1.0]),+ ("Vox Vibrato Stereo", &[1.0, 1.0, 0.94, 7.505, 0.6719, 1.0, 0.225, 50.04, 1.0]),+ ("Subtle movement for pads", &[0.0, 1.0, 1.0, 2.138, 0.2109, 0.0556, 0.6403, 39.6, 0.6706]),+ ("Try on Drums at 120 BPM - use mix and depth", &[1.0, 1.0, 0.8099, 0.2008, 1.0, 0.0, 0.9425, 20.0, 0.1532]),+ ("Vox Ensemble Warm + Decoupled", &[2.0, 1.0, 0.94, 0.1454, 0.3427, 1.0, 0.125, 200.1, 0.87]),+ ];+}++/// Studio Reverb: a plate, a room, a hall or a vintage plate, made of+/// diffusers and delay lines tapped for its stereo, with its size, time,+/// damping and gentle modulation, pre-delay, diffusion and low cut, mixed+/// with the sound.+pub mod efx_reverb {+ use super::*;++ pub const MODE: usize = 0;+ pub const INPUT: usize = 1;+ pub const OUTPUT: usize = 2;+ pub const SIZE: usize = 3;+ pub const TIME: usize = 4;+ pub const DAMPING: usize = 5;+ pub const MODULATION: usize = 6;+ pub const PREDELAY: usize = 7;+ pub const DIFFUSION: usize = 8;+ pub const LOW_CUT: usize = 9;+ pub const MIX: usize = 10;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::choice(+ "Mode",+ 0.0,+ &["Plate", "Room", "Hall", "Vintage plate"],+ 1.0,+ ),+ ParamSpec::num("Input", 0.0, 1.0, 1.0)+ .show(Show::GainDb)+ .decimals(1),+ ParamSpec::num("Output", 0.0, 1.0, 1.0)+ .show(Show::GainDb)+ .decimals(1),+ ParamSpec::num("Size", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Time", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Damping", 0.0, 1.0, 0.25)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Modulation", 0.0, 1.0, 0.25)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Pre-delay", 0.0, 250.0, 4.55)+ .unit("ms")+ .decimals(1)+ .group("Tweak"),+ ParamSpec::num("Diffusion", 0.1, 1.0, 1.0)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Low cut", 50.0, 1000.0, 100.0)+ .unit("Hz")+ .decimals(0)+ .log(),+ ParamSpec::num("Mix", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(0),+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default", &[1.0, 1.0, 1.0, 0.5, 0.5, 0.25, 0.25, 4.5469, 1.0, 100.0, 0.5]),+ ("Cathedral", &[2.0, 1.0, 1.0, 0.75, 0.545, 0.3721, 0.3658, 14.24, 0.838, 138.2, 0.31]),+ ("Central Station", &[2.0, 1.0, 1.0, 0.905, 0.505, 0.7195, 0.6008, 31.54, 0.829, 253.6, 0.335]),+ ("Classic Snare Plate - wet", &[3.0, 0.995, 1.0, 0.145, 0.3535, 0.2979, 0.55, 4.6021, 1.0, 230.2, 1.0]),+ ("Classic Vocal Plate", &[3.0, 1.0, 1.0, 0.5, 0.4685, 0.3876, 0.355, 12.52, 1.0, 147.3, 0.22]),+ ("Drum Plate", &[0.0, 1.0, 1.0, 0.2628, 0.3577, 0.0941, 0.4819, 2.3006, 1.0, 151.9, 0.5]),+ ("Intimate Room", &[1.0, 1.0, 1.0, 0.1229, 0.1324, 0.5158, 0.367, 3.2772, 1.0, 184.6, 0.2454]),+ ("Large Concert Hall", &[2.0, 1.0, 1.0, 0.5714, 0.4126, 0.36, 0.3382, 24.87, 0.8155, 104.7, 0.2612]),+ ("Light Guitar Plate", &[0.0, 1.0, 1.0, 0.6561, 0.4267, 0.5056, 0.3085, 3.5266, 1.0, 154.3, 0.1999]),+ ("Living Room", &[1.0, 1.0, 1.0, 0.48, 0.24, 0.5791, 0.1358, 9.0206, 0.6085, 127.3, 0.28]),+ ("Reverb Drum Room", &[1.0, 1.0, 1.0, 0.2572, 0.0602, 0.0, 0.174, 3.5266, 1.0, 100.0, 0.2026]),+ ("Reverb Empty Hall", &[2.0, 1.0, 1.0, 0.6219, 0.6385, 0.4145, 0.355, 37.5, 0.478, 131.6, 0.1542]),+ ("Reverb Vocal Ambient Room", &[1.0, 1.0, 1.0, 1.0, 0.0, 0.4145, 0.1808, 6.4229, 0.8605, 136.0, 0.0984]),+ ("Reverb Vocal Hall", &[2.0, 1.0, 1.0, 1.0, 0.2416, 0.25, 0.0, 17.97, 1.0, 100.0, 0.1542]),+ ("SlapBack", &[1.0, 1.0, 1.0, 0.8, 0.455, 0.1024, 0.1808, 25.83, 0.433, 200.0, 0.1]),+ ("Small Club", &[2.0, 1.0, 1.0, 0.385, 0.25, 0.6719, 0.3158, 16.81, 0.856, 154.3, 0.2]),+ ("Small Hall", &[2.0, 1.0, 1.0, 0.335, 0.34, 0.3287, 0.3408, 10.17, 0.4431, 361.2, 0.405]),+ ("Soupe Du Jour", &[2.0, 1.0, 1.0, 0.615, 0.87, 0.5345, 0.5358, 25.108, 0.91, 395.1, 0.62]),+ ("Very Large & Rich", &[2.0, 1.0, 0.955, 0.88, 0.695, 0.0263, 0.5258, 43.62, 1.0, 147.3, 0.315]),+ ("Very Light Guitar Room", &[1.0, 1.0, 1.0, 0.3194, 0.4699, 0.5322, 0.3477, 11.85, 0.712, 142.7, 0.0838]),+ ("Vox Decoupler", &[1.0, 1.0, 1.0, 0.3879, 0.0574, 0.3687, 0.587, 0.0, 0.7885, 136.0, 0.2304]),+ ];+}++/// Stereo Delay: a delay a side (in milliseconds or notes of the tempo),+/// fed back through damping and a low cut, digital, analog (darker) or a+/// bucket-brigade line (its stages, compander, clock drift and noise),+/// mixed with the sound.+pub mod efx_stereo_delay {+ use super::*;++ pub const MODE: usize = 0;+ pub const INPUT: usize = 1;+ pub const OUTPUT: usize = 2;+ pub const LEFT: usize = 3;+ pub const RIGHT: usize = 4;+ pub const SYNC: usize = 5;+ pub const LEFT_NOTE: usize = 6;+ pub const RIGHT_NOTE: usize = 7;+ pub const FEEDBACK: usize = 8;+ pub const DAMPING: usize = 9;+ pub const LOW_CUT: usize = 10;+ pub const MIX: usize = 11;+ pub const STAGES: usize = 12;+ pub const COMPANDER: usize = 13;+ pub const DRIFT: usize = 14;+ pub const NOISE: usize = 15;++ const FREE: &[(u8, u32)] = &[(SYNC as u8, OFF)];+ const SYNCED: &[(u8, u32)] = &[(SYNC as u8, ON)];+ const BUCKETS: &[(u8, u32)] = &[(MODE as u8, 1 << 2)];++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::choice("Mode", 0.0, &["Digital", "Analog", "Bucket brigade"], 0.0),+ ParamSpec::num("Input", 0.0, 1.0, 1.0)+ .show(Show::GainDb)+ .decimals(1),+ ParamSpec::num("Output", 0.0, 1.0, 1.0)+ .show(Show::GainDb)+ .decimals(1),+ ParamSpec::num("Delay left", 13.9, 4108.0, 148.6)+ .unit("ms")+ .decimals(0)+ .log()+ .when(FREE),+ ParamSpec::num("Delay right", 13.9, 4108.0, 148.6)+ .unit("ms")+ .decimals(0)+ .log()+ .when(FREE),+ ParamSpec::switch("Tempo sync", 1.0),+ ParamSpec::choice("Left note", 0.0, tempo::NOTES, 9.0).when(SYNCED),+ ParamSpec::choice("Right note", 0.0, tempo::NOTES, 9.0).when(SYNCED),+ ParamSpec::num("Feedback", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Damping", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Feedback low cut", 10.0, 1000.0, 29.7)+ .unit("Hz")+ .decimals(0)+ .log(),+ ParamSpec::num("Mix", 0.0, 1.0, 0.5)+ .show(Show::Percent)+ .decimals(0),+ ParamSpec::num("Stages", 1.0, 4.0, 3.0)+ .decimals(0)+ .group("Bucket brigade")+ .when(BUCKETS),+ ParamSpec::num("Compander", 0.0, 10.0, 5.0)+ .decimals(1)+ .when(BUCKETS),+ ParamSpec::num("Clock drift", 0.0, 1.0, 0.021)+ .show(Show::Percent)+ .decimals(1)+ .when(BUCKETS),+ ParamSpec::num("Noise", -100.0, -40.0, -100.0)+ .show(Show::Db)+ .decimals(1)+ .when(BUCKETS),+ ];++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default", &[0.0, 1.0, 1.0, 148.6, 148.6, 1.0, 9.0, 9.0, 0.5, 0.5, 29.67, 0.5, 3.0, 5.0, 0.0208, -100.0]),+ ("1984 Shack Reverb", &[2.0, 1.0, 1.0, 92.53, 92.53, 0.0, 5.0, 5.0, 0.72, 0.19, 164.4, 1.0, 2.0, 5.0625, 0.0, -60.0]),+ ("Analog Dual Delay", &[1.0, 1.0, 1.0, 576.4, 376.3, 1.0, 13.0, 11.0, 0.765, 0.755, 10.0, 0.365, 4.0, 5.0, 0.0, -80.0]),+ ("Analog Feedback", &[1.0, 1.0, 0.73, 383.5, 92.53, 1.0, 11.0, 5.0, 0.855, 0.43, 10.0, 0.825, 4.0, 5.0, 0.01, -60.0]),+ ("Analog SlapBack", &[1.0, 1.0, 1.0, 92.53, 92.53, 0.0, 5.0, 5.0, 0.6878, 0.6893, 10.0, 0.5, 2.0, 5.0, 0.0, -60.0]),+ ("Analog Slow SlapBack", &[1.0, 1.0, 1.0, 13.9, 30.82, 1.0, 0.0, 1.0, 0.3, 0.27, 10.0, 0.34, 3.0, 5.0, 0.1, -60.0]),+ ("BBD Voice Doubler", &[2.0, 1.0, 0.955, 37.96, 37.96, 0.0, 3.0, 3.0, 0.48, 0.0, 231.1, 0.3, 1.0, 6.45, 0.5, -60.0]),+ ("Both Sides Of The Story", &[1.0, 1.0, 0.705, 148.6, 148.6, 1.0, 9.0, 9.0, 0.4219, 0.33, 10.0, 1.0, 4.0, 5.0, 0.01, -60.0]),+ ("Broaden", &[1.0, 1.0, 0.52, 13.9, 13.9, 1.0, 0.0, 0.0, 0.3967, 0.2659, 10.0, 1.0, 4.0, 5.0, 0.01, -60.0]),+ ("Bucket Brigade In Space", &[2.0, 1.0, 1.0, 35.86, 35.86, 1.0, 1.0, 1.0, 0.0612, 0.22, 185.3, 0.385, 3.0, 8.9, 0.3427, -55.4]),+ ("Delay Analog Old Tape", &[1.0, 1.0, 1.0, 512.3, 495.8, 1.0, 13.0, 13.0, 0.7504, 0.4765, 10.0, 0.5, 4.0, 5.0, 0.0, -80.0]),+ ("Delay Digital Ping Pong", &[0.0, 1.0, 1.0, 238.7, 238.7, 1.0, 10.0, 10.0, 0.3615, 0.0, 10.0, 0.2148, 4.0, 5.0, 0.0, -80.0]),+ ("Delay Digital Robot", &[0.0, 1.0, 1.0, 52.88, 40.99, 0.0, 2.0, 3.0, 0.896, 0.0, 10.0, 0.2572, 4.0, 5.0, 0.0, -80.0]),+ ("Delay Digital Vocal Slap", &[0.0, 1.0, 1.0, 13.9, 13.9, 1.0, 0.0, 0.0, 0.4765, 0.0, 10.0, 0.1566, 4.0, 5.0, 0.0, -80.0]),+ ("Dub Delay", &[2.0, 1.0, 1.0, 92.53, 92.53, 1.0, 5.0, 5.0, 0.8612, 0.695, 245.3, 1.0, 3.0, 7.4, 0.0338, -57.0]),+ ("Endless MonoDelay", &[1.0, 1.0, 0.38, 446.3, 529.3, 1.0, 13.0, 13.0, 0.925, 0.0, 10.0, 1.0, 4.0, 5.0, 0.0, -80.0]),+ ("Endless PingPong", &[1.0, 1.0, 0.38, 446.3, 683.7, 1.0, 13.0, 15.0, 0.06, 0.07, 70.39, 0.89, 4.0, 5.0, 0.01, -60.0]),+ ("Groove Analog", &[1.0, 1.0, 1.0, 232.1, 127.7, 0.0, 10.0, 7.0, 0.885, 0.07, 84.29, 0.775, 3.0, 5.0, 0.1, -60.0]),+ ("Groove Digital", &[0.0, 1.0, 1.0, 39.8, 127.7, 1.0, 3.0, 7.0, 0.885, 0.07, 10.0, 0.775, 4.0, 5.0, 0.0, -80.0]),+ ("Krankmachine", &[2.0, 1.0, 1.0, 148.6, 35.86, 1.0, 9.0, 1.0, 0.93, 0.145, 310.1, 0.55, 3.0, 8.55, 0.2143, -48.2]),+ ("Longest PingPong", &[1.0, 1.0, 1.0, 3085.7, 1432.0, 1.0, 17.0, 17.0, 0.37, 0.0, 10.0, 0.5, 4.0, 5.0, 0.0, -80.0]),+ ("Mid Delay", &[1.0, 1.0, 0.5, 148.6, 148.6, 1.0, 9.0, 9.0, 0.4219, 0.33, 10.0, 1.0, 4.0, 5.0, 0.01, -60.0]),+ ("Ping Pong Delay for Pads", &[1.0, 1.0, 1.0, 135.1, 161.9, 1.0, 7.0, 9.0, 0.3149, 0.8689, 120.7, 0.5024, 4.0, 5.0, 0.0, -80.0]),+ ("PingPong", &[0.0, 1.0, 1.0, 452.7, 323.5, 0.0, 13.0, 12.0, 0.4289, 0.2864, 10.0, 0.5, 4.0, 5.0, 0.0, -80.0]),+ ("ShortDelay", &[0.0, 1.0, 0.58, 13.9, 13.96, 1.0, 0.0, 0.0, 0.3967, 0.2659, 10.0, 1.0, 4.0, 5.0, 0.01, -60.0]),+ ("SimpleDelay", &[0.0, 1.0, 1.0, 989.4, 1589.3, 1.0, 16.0, 17.0, 0.585, 0.33, 10.0, 0.5, 4.0, 5.0, 0.01, -60.0]),+ ("Sweet Echo 1-8 Dot.", &[0.0, 1.0, 1.0, 225.5, 207.1, 1.0, 11.0, 11.0, 0.23, 0.0, 10.0, 0.115, 4.0, 5.0, 0.0, -80.0]),+ ("Sweet Echo Tripl.", &[0.0, 1.0, 1.0, 398.3, 101.7, 1.0, 11.0, 5.0, 0.23, 0.0, 10.0, 0.115, 4.0, 5.0, 0.0, -80.0]),+ ("Sweet Echo", &[0.0, 1.0, 1.0, 610.2, 267.5, 1.0, 15.0, 10.0, 0.23, 0.0, 10.0, 0.115, 4.0, 5.0, 0.0, -80.0]),+ ("Synth Arp 8th 16th BBD", &[2.0, 1.0, 1.0, 148.6, 35.86, 1.0, 9.0, 1.0, 0.28, 0.08, 45.651, 0.44, 3.0, 0.0, 0.0, -80.0]),+ ("Synth Arp 8th BBD", &[2.0, 1.0, 1.0, 148.6, 148.6, 1.0, 9.0, 9.0, 0.28, 0.08, 45.651, 0.44, 4.0, 0.0, 0.0, -80.0]),+ ("TripHop Triplets", &[1.0, 1.0, 0.715, 383.5, 383.5, 1.0, 11.0, 11.0, 0.905, 0.5868, 200.2, 1.0, 4.0, 5.0, 0.01, -60.0]),+ ("TripleDelay", &[1.0, 1.0, 0.705, 383.5, 383.5, 1.0, 11.0, 11.0, 0.905, 0.5868, 10.0, 1.0, 4.0, 5.0, 0.01, -60.0]),+ ("Vox BBD Slapback", &[2.0, 1.0, 1.0, 148.6, 92.53, 0.0, 9.0, 5.0, 0.7712, 0.22, 192.6, 0.255, 2.0, 7.05, 0.01, -55.4]),+ ("100% Mono Digidelay 1-16", &[0.0, 1.0, 1.0, 44.6, 33.56, 1.0, 7.0, 7.0, 0.5, 0.0, 10.0, 1.0, 4.0, 5.0, 0.0, -80.0]),+ ("100% Mono Digidelay 1-16 Tripl.", &[0.0, 1.0, 1.0, 24.547, 23.86, 1.0, 6.0, 6.0, 0.5, 0.0, 10.0, 1.0, 4.0, 5.0, 0.0, -80.0]),+ ("Analog Mono 1-4 Tripl.", &[1.0, 1.0, 1.0, 365.7, 317.3, 1.0, 12.0, 12.0, 0.665, 0.775, 10.0, 0.335, 3.0, 5.0, 0.0, -60.0]),+ ("Analog Mono 1-8", &[1.0, 1.0, 1.0, 135.2, 151.5, 1.0, 10.0, 10.0, 0.665, 0.775, 10.0, 0.335, 3.0, 5.0, 0.0, -60.0]),+ ("Analog Mono 1-8 Dot.", &[1.0, 1.0, 1.0, 190.2, 190.2, 1.0, 11.0, 11.0, 0.665, 0.775, 10.0, 0.335, 3.0, 5.0, 0.0, -60.0]),+ ("Analog Mono 1-8 Tripl.", &[1.0, 1.0, 1.0, 96.11, 114.0, 1.0, 9.0, 9.0, 0.665, 0.775, 10.0, 0.335, 3.0, 5.0, 0.0, -60.0]),+ ("Analog MonoDelay 124ms", &[1.0, 1.0, 1.0, 131.4, 131.4, 0.0, 7.0, 7.0, 0.8, 0.06, 10.0, 0.38, 3.0, 5.0, 0.0, -60.0]),+ ("Analog MonoDelay 251ms", &[1.0, 1.0, 1.0, 238.7, 238.7, 0.0, 10.0, 10.0, 0.805, 0.19, 10.0, 0.38, 4.0, 5.0, 0.0, -60.0]),+ ("Analog MonoDelay 343ms", &[1.0, 1.0, 1.0, 326.4, 326.4, 0.0, 12.0, 12.0, 0.8, 0.06, 10.0, 0.38, 4.0, 5.0, 0.0, -60.0]),+ ("Analog MonoDelay 433ms", &[1.0, 1.0, 1.0, 421.6, 421.6, 0.0, 11.0, 11.0, 0.825, 0.19, 10.0, 0.38, 4.0, 5.0, 0.0, -60.0]),+ ("Analog PingPong 1-2", &[1.0, 1.0, 1.0, 1473.3, 1604.4, 1.0, 16.0, 16.0, 0.335, 0.78, 10.0, 0.5, 4.0, 5.0, 0.0, -80.0]),+ ("Analog PingPong 1-4", &[1.0, 1.0, 1.0, 529.3, 514.5, 1.0, 13.0, 13.0, 0.335, 0.78, 10.0, 0.5, 4.0, 5.0, 0.0, -80.0]),+ ("Analog PingPong 1-4 Dot.", &[1.0, 1.0, 1.0, 961.7, 788.1, 1.0, 14.0, 14.0, 0.335, 0.78, 10.0, 0.5, 4.0, 5.0, 0.0, -80.0]),+ ("Analog PingPong 1-4 Tripl.", &[1.0, 1.0, 1.0, 345.5, 446.3, 1.0, 12.0, 12.0, 0.335, 0.78, 10.0, 0.5, 4.0, 5.0, 0.0, -80.0]),+ ("Analog PingPong 1-8", &[1.0, 1.0, 1.0, 127.7, 127.7, 1.0, 10.0, 10.0, 0.335, 0.78, 10.0, 0.5, 4.0, 5.0, 0.0, -80.0]),+ ("Analog PingPong 1-8 Dot.", &[1.0, 1.0, 1.0, 238.7, 245.6, 1.0, 11.0, 11.0, 0.335, 0.78, 10.0, 0.5, 4.0, 5.0, 0.0, -80.0]),+ ("Analog PingPong 1-8 Tripl.", &[1.0, 1.0, 1.0, 76.55, 81.03, 1.0, 9.0, 9.0, 0.335, 0.78, 10.0, 0.5, 4.0, 5.0, 0.0, -80.0]),+ ("Analog PingPong 644ms", &[1.0, 1.0, 1.0, 683.7, 683.7, 0.0, 15.0, 15.0, 0.275, 0.07, 10.0, 1.0, 4.0, 5.0, 0.0, -80.0]),+ ("Analog PingPong 1-16", &[1.0, 1.0, 1.0, 37.6, 35.53, 1.0, 7.0, 7.0, 0.335, 0.78, 10.0, 0.5, 3.0, 5.0, 0.1, -60.0]),+ ("Analog PingPong 1-16 Dot.", &[1.0, 1.0, 1.0, 47.21, 49.972, 1.0, 8.0, 8.0, 0.335, 0.78, 10.0, 0.5, 3.0, 5.0, 0.1, -60.0]),+ ("Analog PingPong 120ms", &[1.0, 1.0, 1.0, 127.7, 127.7, 0.0, 7.0, 7.0, 0.34, 0.255, 10.0, 0.38, 3.0, 5.0, 0.1, -60.0]),+ ("Analog PingPong 134ms", &[1.0, 1.0, 1.0, 139.1, 139.1, 0.0, 7.0, 7.0, 0.34, 0.255, 10.0, 0.38, 3.0, 5.0, 0.1, -60.0]),+ ("Analog PlingPlong", &[1.0, 1.0, 1.0, 326.4, 317.3, 0.0, 12.0, 12.0, 0.805, 0.185, 10.0, 0.69, 4.0, 5.0, 0.0, -80.0]),+ ("Digidelay 1-4", &[0.0, 1.0, 1.0, 514.5, 645.9, 1.0, 13.0, 13.0, 0.5, 0.0, 10.0, 1.0, 4.0, 5.0, 0.0, -80.0]),+ ("Digidelay 1-4 Tripl.", &[0.0, 1.0, 1.0, 365.7, 326.4, 1.0, 12.0, 12.0, 0.5, 0.0, 10.0, 1.0, 4.0, 5.0, 0.0, -80.0]),+ ("Digidelay 1-4 dot.", &[0.0, 1.0, 1.0, 989.4, 858.3, 1.0, 14.0, 14.0, 0.5, 0.0, 10.0, 1.0, 4.0, 5.0, 0.0, -80.0]),+ ("Digidelay 1-8", &[0.0, 1.0, 1.0, 174.6, 174.6, 1.0, 10.0, 10.0, 0.5, 0.0, 10.0, 1.0, 4.0, 5.0, 0.0, -80.0]),+ ("Digidelay 1-8 Tripl.", &[0.0, 1.0, 1.0, 104.7, 101.7, 1.0, 9.0, 9.0, 0.5, 0.0, 10.0, 1.0, 4.0, 5.0, 0.0, -80.0]),+ ("Digidelay 1-8 dot.", &[0.0, 1.0, 1.0, 238.7, 238.7, 1.0, 11.0, 11.0, 0.5, 0.0, 10.0, 1.0, 4.0, 5.0, 0.0, -80.0]),+ ];+}++/// Time Stretch: the sound made longer or shorter (50 to 500 %) without+/// a change of pitch, its windows sized for the material; it changes the+/// sound's length, so it works through Non-Real-Time Event FX.+pub mod time_stretch {+ use super::*;++ pub const MODE: usize = 0;+ pub const LENGTH: usize = 1;++ /// The modes' names, in order.+ pub const MODES: &[&str] = &[+ "A01. Music 1 (minimum flange, may echo)",+ "A02. Music 2",+ "A03. Music 3 (less echo)",+ "A04. Music 4 (fast, good for bass)",+ "A05. Music 5",+ "A06. Music 6",+ "A07. Speech 1",+ "A08. Speech 2",+ "A09. Speech 3 (fast)",+ "A10. Solo instruments 1",+ "A11. Solo instruments 2",+ "A12. Solo instruments 3",+ "A13. Solo instruments 4 (less echo)",+ "A14. Solo instruments 5",+ "A15. Solo instruments 6",+ "A16. Solo instruments 7 (fast)",+ "A17. Drums, unpitched (minimum echo)",+ "A18. Drums (better for toms)",+ "A19. Drums (tiny echo)",+ ];++ /// Each mode's window, in milliseconds.+ pub const WINDOWS: [f64; 19] = [+ 300.0, 275.0, 150.0, 220.0, 190.0, 150.0, 90.0, 78.0, 80.0, 150.0, 130.0, 110.0, 75.0,+ 90.0, 85.0, 95.0, 50.0, 70.0, 50.0,+ ];++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::choice("Mode", 0.0, MODES, 0.0),+ ParamSpec::num("Final length", 50.0, 500.0, 100.0)+ .unit("%")+ .decimals(1)+ .log(),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[0.0, 100.0]),+ ("Time expand 110 % of original", &[0.0, 110.0]),+ ("Time compress 85 % of original", &[0.0, 85.0]),+ ];+}++/// Express Time Stretch: the same, in the Express set.+pub mod express_time_stretch {+ use super::*;++ pub const PARAMS: &[ParamSpec] = time_stretch::PARAMS;+ pub const PRESETS: &[Preset] = time_stretch::PRESETS;+}++/// Pitch Shift: the sound raised or lowered by semitones and cents —+/// faster or slower like a tape, or keeping its length (then stretched+/// back as Time Stretch does).+pub mod pitch_shift {+ use super::*;++ pub const SEMITONES: usize = 0;+ pub const CENTS: usize = 1;+ pub const ACCURACY: usize = 2;+ pub const ANTI_ALIAS: usize = 3;+ pub const PRESERVE: usize = 4;+ pub const MODE: usize = 5;++ const KEPT: &[(u8, u32)] = &[(PRESERVE as u8, ON)];++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Semitones", -50.0, 50.0, 0.0).decimals(0),+ ParamSpec::num("Cents", -100.0, 100.0, 0.0).decimals(1),+ ParamSpec::num("Accuracy", 1.0, 3.0, 2.0).decimals(0),+ ParamSpec::switch("Apply an anti-alias filter during pitch shift", 0.0),+ ParamSpec::switch("Preserve duration", 0.0),+ ParamSpec::choice("Mode", 0.0, time_stretch::MODES, 0.0).when(KEPT),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[0.0, 0.0, 2.0, 0.0, 0.0, 0.0]),+ ("Fifth down", &[-7.0, 0.0, 2.0, 0.0, 0.0, 0.0]),+ ("Fifth up", &[7.0, 0.0, 2.0, 0.0, 0.0, 0.0]),+ ("Third down", &[-4.0, 0.0, 2.0, 0.0, 0.0, 0.0]),+ ("Third up", &[4.0, 0.0, 2.0, 0.0, 0.0, 0.0]),+ ];+}++/// Gapper/Snipper: silences inserted into the sound (the gapper) or+/// stretches of it cut out (the snipper), so many times a second, their+/// edges faded.+pub mod gapper_snipper {+ use super::*;++ pub const EFFECT: usize = 0;+ pub const FREQUENCY: usize = 1;+ pub const LENGTH: usize = 2;+ pub const FADE: usize = 3;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::choice("Effect", 0.0, &["Gapper (insert)", "Snipper (cut)"], 0.0),+ ParamSpec::num("Frequency of events", 0.0001, 1000.0, 20.0)+ .unit("Hz")+ .decimals(4)+ .log(),+ ParamSpec::num("Length of one event", 0.0001, 1.0, 0.075)+ .unit("s")+ .decimals(4)+ .log(),+ ParamSpec::num("Fade edges of each event", 0.0, 50.0, 15.0)+ .unit("%")+ .decimals(0),+ ];++ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[0.0, 20.0, 0.075, 15.0]),+ ("Chopper 1", &[0.0, 20.0, 0.075, 15.0]),+ ("Chopper 2", &[0.0, 10.0, 0.05, 15.0]),+ ("Distort 1", &[0.0, 1000.0, 0.001, 15.0]),+ ("Distort 2", &[0.0, 90.0, 0.01, 15.0]),+ ("Fast & distorted 1", &[1.0, 200.0, 0.005, 15.0]),+ ("Fast & distorted 2", &[1.0, 1000.0, 0.001, 30.0]),+ ("Very fast clipper", &[1.0, 350.0, 0.01, 5.0]),+ ];+}++/// Vibrato: the sound read faster and slower, like a tape, following a+/// wave drawn on a graph (up to the semitones each way); its length+/// changes with it.+pub mod vibrato {+ use super::*;++ pub const SEMITONES: usize = 0;+ pub const FREQUENCY: usize = 1;+ pub const OUTPUT: usize = 2;+ /// The wave's point count, its points after it.+ pub const GRAPH: usize = 3;+ pub const BLEND: usize = GRAPH + 1 + WAVE.params();++ /// A round (0 to 1000), the speed from −100 (the semitones down) to+ /// 100 (up).+ pub const WAVE: Graph = Graph {+ points: 32,+ x: (0.0, 1000.0),+ y: (-100.0, 100.0),+ log_x: false,+ pinned_ends: true,+ x_unit: "",+ y_unit: "",+ };++ const HEAD: [ParamSpec; 4] = [+ ParamSpec::num("Semitones", 0.01, 24.0, 12.0).decimals(2),+ ParamSpec::num("Modulation freq.", 0.001, 1000.0, 1.0)+ .unit("Hz")+ .decimals(3)+ .log(),+ ParamSpec::num("Output gain", -80.0, 24.0, 0.0)+ .show(Show::Db)+ .decimals(1),+ ParamSpec::graph("Graph", WAVE, 2.0),+ ];+ const POINTS: [ParamSpec; 64] = WAVE.point_params(&[(0.0, 0.0), (1000.0, 0.0)]);+ const TAIL: [ParamSpec; 1] = [ParamSpec::switch("Blend graph edges", 0.0)];+ const FRONT: [ParamSpec; 68] = join(HEAD, POINTS);+ const ALL: [ParamSpec; 69] = join(FRONT, TAIL);++ pub const PARAMS: &[ParamSpec] = &ALL;++ #[rustfmt::skip]+ pub const PRESETS: &[Preset] = &[+ ("Default all parameters", &[12.0, 1.0, 0.0, 2.0, 0.0, 0.0, 1000.0, 0.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0]),+ ("Pitch shift octave up", &[12.0, 1.0, 0.0, 2.0, 0.0, 100.0, 1000.0, 100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0]),+ ("Pitch shift octave down", &[12.0, 1.0, 0.0, 2.0, 0.0, -100.0, 1000.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0]),+ ("Vibrato 1", &[12.0, 5.0, 0.0, 4.0, 0.0, 0.0, 250.0, 100.0, 750.0, -100.0, 1000.0, 0.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0]),+ ("Vibrato 2", &[12.0, 9.0, 0.0, 8.0, 0.0, 0.0, 200.0, 90.0, 250.0, 100.0, 300.0, 90.0, 700.0, -90.0, 750.0, -100.0, 800.0, -90.0, 1000.0, 0.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0]),+ ("Vibrato 3", &[12.0, 9.0, 0.0, 6.0, 0.0, 0.0, 50.0, 100.0, 450.0, 100.0, 550.0, -100.0, 950.0, -100.0, 1000.0, 0.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0]),+ ("Weird 1", &[12.0, 9.0, 0.0, 13.0, 0.0, 0.0, 50.0, 90.0, 100.0, 100.0, 150.0, 90.0, 350.0, -70.0, 400.0, -80.0, 450.0, -70.0, 600.0, 20.0, 650.0, 30.0, 700.0, 40.0, 800.0, 70.0, 850.0, 60.0, 1000.0, 0.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0]),+ ("Triangle", &[6.0, 9.0, 0.0, 2.0, 0.0, -100.0, 500.0, 100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0, -100.0, 0.0]),+ ];+}++/// Express Audio Restoration: clicks taken out and the steady hiss of an+/// old recording turned down.+pub mod express_audio_restoration {+ use super::*;++ pub const CLICKS: usize = 0;+ pub const REDUCTION: usize = 1;+ pub const ABOVE: usize = 2;+ pub const ATTACK: usize = 3;+ pub const RELEASE: usize = 4;+ pub const FLOOR: usize = 5;++ pub const PARAMS: &[ParamSpec] = &[+ ParamSpec::num("Click removal amount", 1.0, 20.0, 10.0).decimals(0),+ ParamSpec::num("Reduce noise by", 0.0, 100.0, 12.0)+ .unit("dB")+ .decimals(1),+ ParamSpec::num("Affect frequencies above", 100.0, 10000.0, 100.0)+ .unit("Hz")+ .decimals(0)+ .log(),+ ParamSpec::num("Attack speed", 1.0, 20.0, 10.0).decimals(0),+ ParamSpec::num("Release speed", 1.0, 20.0, 10.0).decimals(0),+ ParamSpec::num("Noise floor", -96.0, -40.0, -60.0)+ .show(Show::Db)+ .decimals(1),+ ];++ pub const PRESETS: &[Preset] = &[];+}++#[cfg(test)]+mod tests {+ use crate::EffectKind;+ use crate::fx::ParamKind;++ #[test]+ fn every_preset_holds_a_value_in_range_for_every_parameter() {+ for k in EffectKind::AUDIO {+ let Some(list) = super::presets(k) else {+ continue;+ };+ let specs = k.params();+ for (name, values) in list {+ assert_eq!(values.len(), specs.len(), "{k:?} {name}");+ for (v, s) in values.iter().zip(specs) {+ assert!(+ (s.min..=s.max).contains(v),+ "{k:?} {name}: {} = {v}",+ s.name+ );+ if s.kind == ParamKind::Choice || s.kind == ParamKind::Toggle {+ assert_eq!(v.fract(), 0.0, "{k:?} {name}: {}", s.name);+ }+ }+ }+ }+ }++ #[test]+ fn defaults_sit_in_range_and_choices_name_every_value() {+ for k in EffectKind::AUDIO {+ for s in k.params() {+ assert!((s.min..=s.max).contains(&s.default), "{k:?} {}", s.name);+ if s.kind == ParamKind::Choice {+ assert_eq!(+ s.options.len() as f32,+ s.max - s.min + 1.0,+ "{k:?} {}",+ s.name+ );+ }+ }+ }+ }+}diff --git a/crates/timeline/src/edit.rs b/crates/timeline/src/edit.rsindex 06be169..31b4377 100644--- a/crates/timeline/src/edit.rs+++ b/crates/timeline/src/edit.rs@@ -7,7 +7,6 @@ use std::collections::HashMap;use bv_core::{Tick, TimeRange};-use crate::fx::Transform;use crate::model::{ChannelMap, Clip, ClipId, GroupId, MediaId, MediaInfo, MediaSource, NewEvents, Project,TRACK_PALETTE, Track, TrackId, TrackKind,@@ -744,68 +743,113 @@ impl Project {self.trim_end(id, start + duration)}- /// Define o enquadramento no instante `t` da timeline. Sem quadros-chave,- /// no início do clipe, muda o valor fixo; em outro instante, cria a- /// animação (um quadro-chave no início com o valor atual e outro em `t`).- /// Com quadros-chave, cria ou atualiza o de `t`.- pub fn set_clip_transform_at(&mut self, id: ClipId, t: Tick, value: Transform) -> Result<()> {- self.set_clip_transform_at_as(id, t, value, (crate::fx::KeyCurve::Smooth, 0.0))- }-- /// [`Self::set_clip_transform_at`], new keyframes as the editor's- /// settings say (Options › Preferences › External Control & Automation:- /// "New video motion keyframes", "Pan/Crop default smoothness"): the- /// curve of the first ones (later ones take the curve of the keyframe- /// before them) and their smoothness.- pub fn set_clip_transform_at_as(+ /// What event `id`'s Pan/Crop lands on (`None`: no such event, or its+ /// media is gone).+ pub fn clip_place_in(&self, id: ClipId) -> Option<crate::pancrop::PlaceIn> {+ let c = self.clip(id)?;+ let info = self.media(c.media)?;+ Some(crate::pancrop::place_in(+ &self.settings,+ info,+ c.pan_crop.keep_aspect,+ c.pan_crop.fill,+ ))+ }++ /// The box of event `id`'s Pan/Crop at `t` on the timeline.+ pub fn clip_box_at(&self, id: ClipId, t: Tick) -> Option<crate::pancrop::PanCropKey> {+ let place = self.clip_place_in(id)?;+ let c = self.clip(id)?;+ Some(c.box_at(t, place.media, place.media_aspect))+ }++ /// Event `id`'s Pan/Crop box at `t` on the timeline becomes `value`,+ /// as [`crate::pancrop::PanCrop::set_at`] says; new keyframes as the+ /// editor's settings say (Options › Preferences › External Control &+ /// Automation: "New video motion keyframes", "Pan/Crop default+ /// smoothness"): the curve of the first ones (later ones take the curve+ /// of the keyframe before them) and their smoothness, 0–100.+ pub fn set_clip_box_at(&mut self,id: ClipId,t: Tick,- value: Transform,+ value: crate::pancrop::PanCropKey,(curve, smoothness): (crate::fx::KeyCurve, f32),) -> Result<()> {let rate = self.settings.frame_rate;+ let place = self.clip_place_in(id).ok_or(EditError::UnknownClip(id))?;let c = self.clip_mut(id).ok_or(EditError::UnknownClip(id))?;let offset = (rate.snap_nearest(t) - c.start).clamp(Tick::ZERO, c.duration);- let key =- |at: Tick, value: Transform, curve: crate::fx::KeyCurve| crate::fx::TransformKey {- at,- value,- curve,- smoothness,- };- if c.transform_keys.is_empty() {- if offset == Tick::ZERO {- c.transform = value;- return Ok(());- }- c.transform_keys.push(key(Tick::ZERO, c.transform, curve));- }- match c.transform_keys.iter_mut().find(|k| k.at == offset) {- Some(k) => k.value = value,- None => {- let before = c- .transform_keys- .iter()- .rev()- .find(|k| k.at < offset)- .map_or(curve, |k| k.curve);- c.transform_keys.push(key(offset, value, before));- c.transform_keys.sort_by_key(|k| k.at);- }- }- c.transform = c.transform_keys[0].value;+ c.pan_crop.set_at(+ offset,+ value,+ place.media,+ (curve, f64::from(smoothness / 100.0)),+ );Ok(())}- /// Remove o quadro-chave em `offset` (a partir do início do clipe).- pub fn remove_transform_key(&mut self, id: ClipId, offset: Tick) -> Result<()> {+ /// Event `id` framed by `tf` (where a fitted picture goes, how much+ /// zoomed and turned) all along.+ pub fn set_clip_framing(&mut self, id: ClipId, tf: &crate::fx::Transform) -> Result<()> {+ let place = self.clip_place_in(id).ok_or(EditError::UnknownClip(id))?;+ let key = crate::pancrop::key_from_transform(tf, &place);let c = self.clip_mut(id).ok_or(EditError::UnknownClip(id))?;- c.transform_keys.retain(|k| k.at != offset);- if c.transform_keys.len() == 1 {- c.transform = c.transform_keys[0].value;- c.transform_keys.clear();- }+ c.pan_crop = crate::pancrop::PanCrop::holding(+ key,+ place.media,+ c.pan_crop.keep_aspect,+ c.pan_crop.fill,+ );+ Ok(())+ }++ /// Event `id` framed by `keys` (what [`Self::set_clip_framing`] takes,+ /// over time).+ pub fn set_clip_framing_keys(+ &mut self,+ id: ClipId,+ keys: &[crate::fx::TransformKey],+ ) -> Result<()> {+ let place = self.clip_place_in(id).ok_or(EditError::UnknownClip(id))?;+ let c = self.clip_mut(id).ok_or(EditError::UnknownClip(id))?;+ c.pan_crop.ensure_size(place.media);+ c.pan_crop.keys = keys+ .iter()+ .map(|k| crate::pancrop::PanCropKey {+ at: k.at,+ curve: k.curve,+ smoothness: f64::from(k.smoothness / 100.0),+ ..crate::pancrop::key_from_transform(&k.value, &place)+ })+ .collect();+ Ok(())+ }++ /// Event `id`'s box at `t` on the timeline becomes the one `tf` shows.+ pub fn set_clip_transform_at(+ &mut self,+ id: ClipId,+ t: Tick,+ tf: crate::fx::Transform,+ ) -> Result<()> {+ let place = self.clip_place_in(id).ok_or(EditError::UnknownClip(id))?;+ let key = crate::pancrop::key_from_transform(&tf, &place);+ self.set_clip_box_at(id, t, key, (crate::fx::KeyCurve::Smooth, 0.0))+ }++ /// Event `id`'s box at `t` as the closest framing: where a fitted+ /// picture goes, how much zoomed and turned.+ pub fn clip_transform_at(&self, id: ClipId, t: Tick) -> Option<crate::fx::Transform> {+ let place = self.clip_place_in(id)?;+ let key = self.clip_box_at(id, t)?;+ Some(crate::pancrop::transform_from_key(&key, &place))+ }++ /// Event `id`'s Pan/Crop keyframe at `offset` (from its start) gone.+ pub fn remove_clip_box_key(&mut self, id: ClipId, offset: Tick) -> Result<()> {+ let c = self.clip_mut(id).ok_or(EditError::UnknownClip(id))?;+ c.pan_crop.remove_key(offset);Ok(())}@@ -1029,21 +1073,10 @@ impl Project {curve: crate::fx::KeyCurve::Linear,});}- right.transform_keys.clear();- if !left.transform_keys.is_empty() {- // A metade da direita começa no valor do corte; a da- // esquerda termina nele.- let mut tmp = left.clone();- rebase_keys(&mut tmp, cut);- right.transform_keys = tmp.transform_keys;- let at_cut = left.transform_at(at);- left.transform_keys.retain(|k| k.at < cut);- left.transform_keys.push(crate::fx::TransformKey::new(- cut,- at_cut,- crate::fx::KeyCurve::Linear,- ));- }+ // A metade da direita começa no valor do corte; a da esquerda+ // termina nele.+ let size = left.pan_crop.own_size();+ right.pan_crop = left.pan_crop.split_at(cut, size, 1.0);// Its masks' shapes too: the right half's start with those at// the cut.if let Some(m) = &mut left.mask {@@ -1155,27 +1188,8 @@ pub(crate) fn rebase_keys(c: &mut Clip, delta: Tick) {if let Some(m) = &mut c.mask {m.rebase(delta);}- if c.transform_keys.is_empty() {- return;- }- let before = c.transform_keys.iter().rev().find(|k| k.at <= delta);- let first = crate::fx::TransformKey {- at: Tick::ZERO,- value: c.transform_at(c.start + delta),- curve: before.map_or(crate::fx::KeyCurve::Smooth, |k| k.curve),- smoothness: before.map_or(0.0, |k| k.smoothness),- };- let mut keys: Vec<_> = c- .transform_keys- .iter()- .filter(|k| k.at > delta)- .map(|k| crate::fx::TransformKey {- at: k.at - delta,- ..*k- })- .collect();- keys.insert(0, first);- c.transform_keys = keys;+ let size = c.pan_crop.own_size();+ c.pan_crop.rebase(delta, size, 1.0);}/// The event's own envelopes when its start moves `delta` later in it@@ -1762,31 +1776,28 @@ mod tests {#[test]fn quadros_chave_do_enquadramento() {let (mut p, _, _, cv, _) = setup();- let zoom = Transform {+ let zoom = crate::fx::Transform {scale: 2.0,- ..Transform::default()+ ..crate::fx::Transform::default()};p.set_clip_transform_at(cv, s(4), zoom).unwrap();- let c = p.clip(cv).unwrap().clone();- assert_eq!(c.transform_keys.len(), 2);- assert_eq!(c.transform_at(Tick::ZERO).scale, 1.0);- assert!((c.transform_at(s(4)).scale - 2.0).abs() < 1e-3);- assert!((c.transform_at(s(9)).scale - 2.0).abs() < 1e-3);- let mid = c.transform_at(s(2)).scale;+ let scale = |p: &Project, id: ClipId, t: Tick| p.clip_transform_at(id, t).unwrap().scale;+ assert_eq!(p.clip(cv).unwrap().pan_crop.keys.len(), 2);+ assert_eq!(scale(&p, cv, Tick::ZERO), 1.0);+ assert!((scale(&p, cv, s(4)) - 2.0).abs() < 1e-3);+ assert!((scale(&p, cv, s(9)) - 2.0).abs() < 1e-3);+ let mid = scale(&p, cv, s(2));assert!(mid > 1.0 && mid < 2.0, "{mid}");// Dividir no meio mantém a animação contínua dos dois lados.let right = p.split(cv, s(2)).unwrap()[0];- let l = p.clip(cv).unwrap().clone();- let r = p.clip(right).unwrap().clone();- assert!((l.transform_at(s(2) - Tick(1)).scale - mid).abs() < 1e-3);- assert!((r.transform_at(s(2)).scale - mid).abs() < 1e-3);- assert!((r.transform_at(s(4)).scale - 2.0).abs() < 1e-3);+ assert!((scale(&p, cv, s(2) - Tick(1)) - mid).abs() < 1e-3);+ assert!((scale(&p, right, s(2)) - mid).abs() < 1e-3);+ assert!((scale(&p, right, s(4)) - 2.0).abs() < 1e-3);// Aparar o início re-baseia os quadros-chave.p.trim_start(right, s(3)).unwrap();- let r = p.clip(right).unwrap();- assert_eq!(r.transform_keys[0].at, Tick::ZERO);- assert!((r.transform_at(s(4)).scale - 2.0).abs() < 1e-3);- p.remove_transform_key(right, s(1)).unwrap();+ assert_eq!(p.clip(right).unwrap().pan_crop.keys[0].at, Tick::ZERO);+ assert!((scale(&p, right, s(4)) - 2.0).abs() < 1e-3);+ p.remove_clip_box_key(right, s(1)).unwrap();p.check_invariants().unwrap();}diff --git a/crates/timeline/src/fx.rs b/crates/timeline/src/fx.rsindex 15926da..5a13e5b 100644--- a/crates/timeline/src/fx.rs+++ b/crates/timeline/src/fx.rs@@ -16,6 +16,31 @@ pub enum ParamKind {Toggle,/// Este e os dois parâmetros seguintes formam uma cor sRGB (R, G, B).Color,+ /// One of [`ParamSpec::options`]: the value `min` is the first, each+ /// next one a whole number more.+ Choice,+ /// Data an effect's own editor keeps (a graph's points…): never shown+ /// as a control nor automated.+ Data,+ /// A graph's point count ([`ParamSpec::graph`]): its points follow it+ /// as [`ParamKind::Data`], and the panel draws and edits them.+ Graph,+}++/// How a value is shown and typed.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Show {+ /// As it is, with [`ParamSpec::unit`].+ Value,+ /// A linear gain, shown in dB (0 as −Inf.).+ GainDb,+ /// A part (0–1, or more), shown as a percentage.+ Percent,+ /// A pan, −1 to 1, positive to the left: shown as "50.0 % L" or+ /// "50.0 % R", its slider's left the left.+ Pan,+ /// A level in dB, its lowest value shown as −Inf. (silence).+ Db,}#[derive(Clone, Copy, Debug, PartialEq)]@@ -25,9 +50,213 @@ pub struct ParamSpec {pub max: f32,pub default: f32,pub kind: ParamKind,+ /// What follows the number ("Hz", "ms"…).+ pub unit: &'static str,+ /// How many decimals the number shows.+ pub decimals: u8,+ /// A [`ParamKind::Choice`]'s options, in the order of their values.+ pub options: &'static [&'static str],+ /// Its slider moves on a logarithmic scale (frequencies, times).+ pub log: bool,+ pub show: Show,+ /// The heading it begins in its effect's panel ("": the one before's).+ pub group: &'static str,+ /// A [`ParamKind::Graph`]'s axes and size.+ pub graph: Option<Graph>,+ /// What it waits on: its control is greyed out unless each parameter+ /// named (by its place) holds one of the values its mask lets through+ /// (bit `v` for the whole value `v`: [`ON`], [`OFF`], [`either`]).+ pub when: &'static [(u8, u32)],+}++/// A graph an effect's panel draws and edits ([`ParamKind::Graph`]): its+/// axes and how many points it holds.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Graph {+ /// The most points it holds.+ pub points: u8,+ /// Its axes' ranges: x left to right, y bottom to top.+ pub x: (f32, f32),+ pub y: (f32, f32),+ /// The x axis on a logarithmic scale (frequencies).+ pub log_x: bool,+ /// The first and last points stay at the ends of the x axis.+ pub pinned_ends: bool,+ /// What follows each axis's numbers ("dB", "Hz"…).+ pub x_unit: &'static str,+ pub y_unit: &'static str,}impl ParamSpec {+ /// A graph of up to `g.points` points: this parameter holds how many+ /// it has (`count`), the [`Graph::params`] after it each point's x and+ /// y.+ pub const fn graph(name: &'static str, g: Graph, count: f32) -> ParamSpec {+ ParamSpec {+ kind: ParamKind::Graph,+ graph: Some(g),+ decimals: 0,+ ..ParamSpec::num(name, 2.0, g.points as f32, count)+ }+ }+}++impl Graph {+ /// How many parameters it takes after its count: x and y a point.+ pub const fn params(&self) -> usize {+ 2 * self.points as usize+ }++ /// Its points' parameters (after the count), the first ones+ /// `defaults`, the rest at the start of each axis.+ pub const fn point_params<const N: usize>(&self, defaults: &[(f32, f32)]) -> [ParamSpec; N] {+ let mut out = [ParamSpec::data("", 0.0, 0.0, 0.0); N];+ let mut k = 0;+ while k < N / 2 {+ let (x, y) = if k < defaults.len() {+ defaults[k]+ } else {+ (self.x.0, self.y.0)+ };+ out[2 * k] = ParamSpec::data("", self.x.0, self.x.1, x);+ out[2 * k + 1] = ParamSpec::data("", self.y.0, self.y.1, y);+ k += 1;+ }+ out+ }+}++/// `a` then `b`, `C` long (its length, `A + B`, said where it is used).+pub const fn join<const A: usize, const B: usize, const C: usize>(+ a: [ParamSpec; A],+ b: [ParamSpec; B],+) -> [ParamSpec; C] {+ assert!(A + B == C, "the joined list is as long as its parts");+ let mut out = [ParamSpec::data("", 0.0, 0.0, 0.0); C];+ let mut i = 0;+ while i < A {+ out[i] = a[i];+ i += 1;+ }+ while i < C {+ out[i] = b[i - A];+ i += 1;+ }+ out+}++/// A [`ParamSpec::when`] mask: the switch on.+pub const ON: u32 = 1 << 1;+/// A [`ParamSpec::when`] mask: the switch off.+pub const OFF: u32 = 1 << 0;++/// A [`ParamSpec::when`] mask: a choice at `a` or at `b`.+pub const fn either(a: u32, b: u32) -> u32 {+ (1 << a) | (1 << b)+}++/// A [`ParamSpec::when`] mask: a whole number `v` or more.+pub const fn at_least(v: u32) -> u32 {+ !((1 << v) - 1)+}++impl ParamSpec {+ /// A number from `min` to `max`.+ pub const fn num(name: &'static str, min: f32, max: f32, default: f32) -> ParamSpec {+ ParamSpec {+ name,+ min,+ max,+ default,+ kind: ParamKind::Slider,+ unit: "",+ decimals: 2,+ options: &[],+ log: false,+ show: Show::Value,+ group: "",+ graph: None,+ when: &[],+ }+ }++ /// A switch, off (0) or on (1).+ pub const fn switch(name: &'static str, default: f32) -> ParamSpec {+ ParamSpec {+ kind: ParamKind::Toggle,+ ..ParamSpec::num(name, 0.0, 1.0, default)+ }+ }++ /// One of `options`, numbered from `first`.+ pub const fn choice(+ name: &'static str,+ first: f32,+ options: &'static [&'static str],+ default: f32,+ ) -> ParamSpec {+ ParamSpec {+ kind: ParamKind::Choice,+ options,+ decimals: 0,+ ..ParamSpec::num(name, first, first + options.len() as f32 - 1.0, default)+ }+ }++ /// Data for the effect's own editor, from `min` to `max`.+ pub const fn data(name: &'static str, min: f32, max: f32, default: f32) -> ParamSpec {+ ParamSpec {+ kind: ParamKind::Data,+ ..ParamSpec::num(name, min, max, default)+ }+ }++ pub const fn unit(self, unit: &'static str) -> ParamSpec {+ ParamSpec { unit, ..self }+ }++ pub const fn decimals(self, decimals: u8) -> ParamSpec {+ ParamSpec { decimals, ..self }+ }++ pub const fn log(self) -> ParamSpec {+ ParamSpec { log: true, ..self }+ }++ pub const fn show(self, show: Show) -> ParamSpec {+ ParamSpec { show, ..self }+ }++ pub const fn group(self, group: &'static str) -> ParamSpec {+ ParamSpec { group, ..self }+ }++ pub const fn when(self, when: &'static [(u8, u32)]) -> ParamSpec {+ ParamSpec { when, ..self }+ }++ /// Whether its control is live with the effect's values `param`+ /// (each parameter it waits on at a value it lets through).+ pub fn live(&self, param: impl Fn(usize) -> f32) -> bool {+ self.when.iter().all(|&(i, mask)| {+ let v = param(i as usize).round();+ (0.0..32.0).contains(&v) && mask & (1 << v as u32) != 0+ })+ }++ /// Whether it is a control of the effect's panel (not data).+ pub fn shown(&self) -> bool {+ self.kind != ParamKind::Data+ }++ /// Whether FX automation can follow it.+ pub fn automatable(&self) -> bool {+ matches!(+ self.kind,+ ParamKind::Slider | ParamKind::Toggle | ParamKind::Choice+ )+ }+/// Where `v` sits in the parameter's range, 0–1 (what FX automation's/// envelopes hold).pub fn to_unit(&self, v: f32) -> f32 {@@ -45,38 +274,24 @@ impl ParamSpec {match self.kind {ParamKind::Toggle if u >= 0.5 => self.max,ParamKind::Toggle => self.min,+ ParamKind::Choice => (self.min + u * (self.max - self.min)).round(),_ => self.min + u * (self.max - self.min),}}}const fn slider(name: &'static str, min: f32, max: f32, default: f32) -> ParamSpec {- ParamSpec {- name,- min,- max,- default,- kind: ParamKind::Slider,- }+ ParamSpec::num(name, min, max, default)}const fn toggle(name: &'static str, default: f32) -> ParamSpec {- ParamSpec {- name,- min: 0.0,- max: 1.0,- default,- kind: ParamKind::Toggle,- }+ ParamSpec::switch(name, default)}const fn color(name: &'static str, default: f32) -> ParamSpec {ParamSpec {- name,- min: 0.0,- max: 1.0,- default,kind: ParamKind::Color,+ ..ParamSpec::num(name, 0.0, 1.0, default)}}@@ -112,6 +327,109 @@ pub enum EffectKind {/// of them, the middle or the sides; the parameters are/// [`modern_eq`]'s.ModernEq,+ /// VEGAS's Volume: a linear gain ([`crate::audio_fx::volume`]).+ Volume,+ /// VEGAS's Pan: one channel moved into the other ([`crate::audio_fx::pan`]).+ Pan,+ /// VEGAS's Smooth/Enhance ([`crate::audio_fx::smooth_enhance`]).+ SmoothEnhance,+ /// VEGAS's Noise Gate ([`crate::audio_fx::noise_gate`]); `NoiseGate`+ /// is BananaV's older one.+ NoiseGateFx,+ /// VEGAS's Track Noise Gate ([`crate::audio_fx::track_noise_gate`]).+ TrackNoiseGate,+ /// VEGAS's Simple Delay ([`crate::audio_fx::simple_delay`]).+ SimpleDelay,+ /// VEGAS's Dither ([`crate::audio_fx::dither`]).+ Dither,+ /// VEGAS's Resonant Filter ([`crate::audio_fx::resonant_filter`]).+ ResonantFilter,+ /// VEGAS's Parametric EQ ([`crate::audio_fx::parametric_eq`]).+ ParametricEq,+ /// VEGAS's Chorus ([`crate::audio_fx::chorus`]).+ Chorus,+ /// VEGAS's Flange/Wah-wah ([`crate::audio_fx::flange_wah_wah`]).+ FlangeWahWah,+ /// VEGAS's Reverb ([`crate::audio_fx::reverb`]); `Reverb` is+ /// BananaV's older one.+ ReverbFx,+ /// VEGAS's Track Compressor ([`crate::audio_fx::track_compressor`]).+ TrackCompressor,+ /// VEGAS's Track EQ ([`crate::audio_fx::track_eq`]).+ TrackEq,+ /// VEGAS's Paragraphic EQ ([`crate::audio_fx::paragraphic_eq`]).+ ParagraphicEq,+ /// VEGAS's Multi-Tap Delay ([`crate::audio_fx::multi_tap_delay`]).+ MultiTapDelay,+ /// VEGAS's Multi-Band Dynamics ([`crate::audio_fx::multi_band_dynamics`]).+ MultiBandDynamics,+ /// VEGAS's Delay of the Express set ([`crate::audio_fx::express_delay`]).+ ExpressDelay,+ /// VEGAS's Distortion of the Express set ([`crate::audio_fx::express_distortion`]).+ ExpressDistortion,+ /// VEGAS's Equalization of the Express set ([`crate::audio_fx::express_equalization`]).+ ExpressEqualization,+ /// VEGAS's Noise Gate of the Express set ([`crate::audio_fx::express_noise_gate`]).+ ExpressNoiseGate,+ /// VEGAS's Chorus of the Express set ([`crate::audio_fx::express_chorus`]).+ ExpressChorus,+ /// VEGAS's Flange/Wah-Wah of the Express set ([`crate::audio_fx::express_flange_wah_wah`]).+ ExpressFlangeWahWah,+ /// VEGAS's Dynamics of the Express set ([`crate::audio_fx::express_dynamics`]).+ ExpressDynamics,+ /// VEGAS's Stutter of the Express set ([`crate::audio_fx::express_stutter`]).+ ExpressStutter,+ /// VEGAS's Amplitude Modulation of the Express set ([`crate::audio_fx::express_amplitude_modulation`]).+ ExpressAmplitudeModulation,+ /// VEGAS's Graphic EQ of the Express set ([`crate::audio_fx::express_graphic_eq`]).+ ExpressGraphicEq,+ /// VEGAS's Reverb of the Express set ([`crate::audio_fx::express_reverb`]).+ ExpressReverb,+ /// VEGAS's Audio Restoration of the Express set+ /// ([`crate::audio_fx::express_audio_restoration`]).+ ExpressAudioRestoration,+ /// VEGAS's Amplitude Modulation ([`crate::audio_fx::amplitude_modulation`]).+ AmplitudeModulation,+ /// VEGAS's Graphic Dynamics ([`crate::audio_fx::graphic_dynamics`]).+ GraphicDynamics,+ /// VEGAS's Distortion ([`crate::audio_fx::distortion`]).+ Distortion,+ /// VEGAS's Graphic EQ ([`crate::audio_fx::graphic_eq`]).+ GraphicEq,+ /// VEGAS's Wave Hammer Surround ([`crate::audio_fx::wave_hammer`]).+ WaveHammer,+ /// the studio set's Gate ([`crate::audio_fx::efx_gate`]).+ StudioGate,+ /// the studio set's DeEsser ([`crate::audio_fx::efx_deesser`]).+ DeEsser,+ /// the studio set's Limiter; `Limiter` is BananaV's older one ([`crate::audio_fx::efx_limiter`]).+ StudioLimiter,+ /// the studio set's Tremolo Pan ([`crate::audio_fx::efx_tremolo_pan`]).+ TremoloPan,+ /// the studio set's Tube Stage ([`crate::audio_fx::efx_tube_stage`]).+ TubeStage,+ /// the studio set's Vocal Strip ([`crate::audio_fx::efx_vocal_strip`]).+ VocalStrip,+ /// the studio set's Compressor; `Compressor` is BananaV's older one ([`crate::audio_fx::efx_compressor`]).+ StudioCompressor,+ /// the studio set's Phaser ([`crate::audio_fx::efx_phaser`]).+ Phaser,+ /// the studio set's Chorus/Flanger ([`crate::audio_fx::efx_chorus_flanger`]).+ ChorusFlanger,+ /// the studio set's Reverb ([`crate::audio_fx::efx_reverb`]).+ StudioReverb,+ /// the studio set's Stereo Delay ([`crate::audio_fx::efx_stereo_delay`]).+ StereoDelay,+ /// VEGAS's Time Stretch ([`crate::audio_fx::time_stretch`]).+ TimeStretch,+ /// VEGAS's Time Stretch of the Express set ([`crate::audio_fx::express_time_stretch`]).+ ExpressTimeStretch,+ /// VEGAS's Pitch Shift ([`crate::audio_fx::pitch_shift`]).+ PitchShift,+ /// VEGAS's Gapper/Snipper ([`crate::audio_fx::gapper_snipper`]).+ GapperSnipper,+ /// VEGAS's Vibrato ([`crate::audio_fx::vibrato`]).+ Vibrato,/// A plug-in's effect (OpenFX): what it is lives in [`Effect::plugin`].Plugin,/// A VST 3 plug-in's audio effect: what it is lives in [`Effect::vst`].@@ -119,21 +437,154 @@ pub enum EffectKind {}impl EffectKind {- pub const AUDIO: [EffectKind; 10] = [- EffectKind::Gain,- EffectKind::Eq3,+ pub const AUDIO: [EffectKind; 51] = [+ EffectKind::Volume,+ EffectKind::Pan,+ EffectKind::SmoothEnhance,+ EffectKind::NoiseGateFx,+ EffectKind::TrackNoiseGate,+ EffectKind::SimpleDelay,+ EffectKind::Dither,+ EffectKind::ResonantFilter,+ EffectKind::ParametricEq,+ EffectKind::Chorus,+ EffectKind::FlangeWahWah,+ EffectKind::ReverbFx,+ EffectKind::TrackCompressor,+ EffectKind::TrackEq,+ EffectKind::ParagraphicEq,+ EffectKind::MultiTapDelay,+ EffectKind::MultiBandDynamics,+ EffectKind::ExpressDelay,+ EffectKind::ExpressDistortion,+ EffectKind::ExpressEqualization,+ EffectKind::ExpressNoiseGate,+ EffectKind::ExpressChorus,+ EffectKind::ExpressFlangeWahWah,+ EffectKind::ExpressDynamics,+ EffectKind::ExpressStutter,+ EffectKind::ExpressAmplitudeModulation,+ EffectKind::ExpressGraphicEq,+ EffectKind::ExpressReverb,+ EffectKind::ExpressAudioRestoration,+ EffectKind::AmplitudeModulation,+ EffectKind::GraphicDynamics,+ EffectKind::Distortion,+ EffectKind::GraphicEq,+ EffectKind::WaveHammer,+ EffectKind::StudioGate,+ EffectKind::DeEsser,+ EffectKind::StudioLimiter,+ EffectKind::TremoloPan,+ EffectKind::TubeStage,+ EffectKind::VocalStrip,+ EffectKind::StudioCompressor,+ EffectKind::Phaser,+ EffectKind::ChorusFlanger,+ EffectKind::StudioReverb,+ EffectKind::StereoDelay,+ EffectKind::TimeStretch,+ EffectKind::ExpressTimeStretch,+ EffectKind::PitchShift,+ EffectKind::GapperSnipper,+ EffectKind::Vibrato,EffectKind::ModernEq,- EffectKind::HighPass,- EffectKind::LowPass,- EffectKind::Compressor,- EffectKind::Limiter,- EffectKind::NoiseGate,- EffectKind::Delay,- EffectKind::Reverb,];+ /// Whether it changes the sound's length (or needs all of it at once):+ /// then it works through Non-Real-Time Event FX, and a playing chain+ /// lets the sound through it.+ pub fn works_offline(self) -> bool {+ matches!(+ self,+ EffectKind::TimeStretch+ | EffectKind::ExpressTimeStretch+ | EffectKind::PitchShift+ | EffectKind::GapperSnipper+ | EffectKind::Vibrato+ )+ }++ /// Whether it works on sound: those offered and those only older+ /// projects have (the compiler asks for every new kind here).pub fn is_audio(self) -> bool {- EffectKind::AUDIO.contains(&self) || self == EffectKind::Vst+ match self {+ EffectKind::Gain+ | EffectKind::Eq3+ | EffectKind::HighPass+ | EffectKind::LowPass+ | EffectKind::Compressor+ | EffectKind::Limiter+ | EffectKind::NoiseGate+ | EffectKind::Delay+ | EffectKind::Reverb+ | EffectKind::ModernEq+ | EffectKind::Volume+ | EffectKind::Pan+ | EffectKind::SmoothEnhance+ | EffectKind::NoiseGateFx+ | EffectKind::TrackNoiseGate+ | EffectKind::SimpleDelay+ | EffectKind::Dither+ | EffectKind::ResonantFilter+ | EffectKind::ParametricEq+ | EffectKind::Chorus+ | EffectKind::FlangeWahWah+ | EffectKind::ReverbFx+ | EffectKind::TrackCompressor+ | EffectKind::TrackEq+ | EffectKind::ParagraphicEq+ | EffectKind::MultiTapDelay+ | EffectKind::MultiBandDynamics+ | EffectKind::ExpressDelay+ | EffectKind::ExpressDistortion+ | EffectKind::ExpressEqualization+ | EffectKind::ExpressNoiseGate+ | EffectKind::ExpressChorus+ | EffectKind::ExpressFlangeWahWah+ | EffectKind::ExpressDynamics+ | EffectKind::ExpressStutter+ | EffectKind::ExpressAmplitudeModulation+ | EffectKind::ExpressGraphicEq+ | EffectKind::ExpressReverb+ | EffectKind::ExpressAudioRestoration+ | EffectKind::AmplitudeModulation+ | EffectKind::GraphicDynamics+ | EffectKind::Distortion+ | EffectKind::GraphicEq+ | EffectKind::WaveHammer+ | EffectKind::StudioGate+ | EffectKind::DeEsser+ | EffectKind::StudioLimiter+ | EffectKind::TremoloPan+ | EffectKind::TubeStage+ | EffectKind::VocalStrip+ | EffectKind::StudioCompressor+ | EffectKind::Phaser+ | EffectKind::ChorusFlanger+ | EffectKind::StudioReverb+ | EffectKind::StereoDelay+ | EffectKind::TimeStretch+ | EffectKind::ExpressTimeStretch+ | EffectKind::PitchShift+ | EffectKind::GapperSnipper+ | EffectKind::Vibrato+ | EffectKind::Vst => true,+ EffectKind::BrightnessContrast+ | EffectKind::ColorGrade+ | EffectKind::Levels+ | EffectKind::BlackAndWhite+ | EffectKind::Sepia+ | EffectKind::Invert+ | EffectKind::GaussianBlur+ | EffectKind::Sharpen+ | EffectKind::Vignette+ | EffectKind::Mirror+ | EffectKind::Pixelate+ | EffectKind::ChromaKey+ | EffectKind::Glow+ | EffectKind::Plugin => false,+ }}/// The video effects offered: the Color Grading panel's. The others@@ -164,12 +615,62 @@ impl EffectKind {EffectKind::Eq3 => "3-Band EQ",EffectKind::HighPass => "High-Pass",EffectKind::LowPass => "Low-Pass",- EffectKind::Compressor => "Compressor",- EffectKind::Limiter => "Limiter",- EffectKind::NoiseGate => "Noise gate",+ EffectKind::Compressor => "Compressor (legacy)",+ EffectKind::Limiter => "Limiter (legacy)",+ EffectKind::NoiseGate => "Noise gate (legacy)",EffectKind::Delay => "Delay (Echo)",- EffectKind::Reverb => "Reverb",+ EffectKind::Reverb => "Reverb (legacy)",EffectKind::ModernEq => "Modern Equalizer",+ EffectKind::Volume => "Volume",+ EffectKind::Pan => "Pan",+ EffectKind::SmoothEnhance => "Smooth/Enhance",+ EffectKind::NoiseGateFx => "Noise Gate",+ EffectKind::TrackNoiseGate => "Track Noise Gate",+ EffectKind::SimpleDelay => "Simple Delay",+ EffectKind::Dither => "Dither",+ EffectKind::ResonantFilter => "Resonant Filter",+ EffectKind::ParametricEq => "Parametric EQ",+ EffectKind::Chorus => "Chorus",+ EffectKind::FlangeWahWah => "Flange/Wah-wah",+ EffectKind::ReverbFx => "Reverb",+ EffectKind::TrackCompressor => "Track Compressor",+ EffectKind::TrackEq => "Track EQ",+ EffectKind::ParagraphicEq => "Paragraphic EQ",+ EffectKind::MultiTapDelay => "Multi-Tap Delay",+ EffectKind::MultiBandDynamics => "Multi-Band Dynamics",+ EffectKind::ExpressDelay => "Express Delay",+ EffectKind::ExpressDistortion => "Express Distortion",+ EffectKind::ExpressEqualization => "Express Equalization",+ EffectKind::ExpressNoiseGate => "Express Noise Gate",+ EffectKind::ExpressChorus => "Express Chorus",+ EffectKind::ExpressFlangeWahWah => "Express Flange/Wah-Wah",+ EffectKind::ExpressDynamics => "Express Dynamics",+ EffectKind::ExpressStutter => "Express Stutter",+ EffectKind::ExpressAmplitudeModulation => "Express Amplitude Modulation",+ EffectKind::ExpressGraphicEq => "Express Graphic EQ",+ EffectKind::ExpressReverb => "Express Reverb",+ EffectKind::ExpressAudioRestoration => "Express Audio Restoration",+ EffectKind::AmplitudeModulation => "Amplitude Modulation",+ EffectKind::GraphicDynamics => "Graphic Dynamics",+ EffectKind::Distortion => "Distortion",+ EffectKind::GraphicEq => "Graphic EQ",+ EffectKind::WaveHammer => "Wave Hammer Surround",+ EffectKind::StudioGate => "Gate",+ EffectKind::DeEsser => "DeEsser",+ EffectKind::StudioLimiter => "Limiter",+ EffectKind::TremoloPan => "Tremolo Pan",+ EffectKind::TubeStage => "Tube Stage",+ EffectKind::VocalStrip => "Vocal Strip",+ EffectKind::StudioCompressor => "Compressor",+ EffectKind::Phaser => "Phaser",+ EffectKind::ChorusFlanger => "Chorus/Flanger",+ EffectKind::StudioReverb => "Studio Reverb",+ EffectKind::StereoDelay => "Stereo Delay",+ EffectKind::TimeStretch => "Time Stretch",+ EffectKind::ExpressTimeStretch => "Express Time Stretch",+ EffectKind::PitchShift => "Pitch Shift",+ EffectKind::GapperSnipper => "Gapper/Snipper",+ EffectKind::Vibrato => "Vibrato",EffectKind::Plugin => "Plug-in",EffectKind::Vst => "VST 3 Plug-in",}@@ -193,6 +694,51 @@ impl EffectKind {| EffectKind::LowPass => "Equalization",EffectKind::Compressor | EffectKind::Limiter | EffectKind::NoiseGate => "Dynamics",EffectKind::Delay | EffectKind::Reverb => "Ambience",+ EffectKind::Volume | EffectKind::Pan => "Utility",+ EffectKind::SmoothEnhance => "Equalization",+ EffectKind::NoiseGateFx | EffectKind::TrackNoiseGate => "Dynamics",+ EffectKind::SimpleDelay => "Ambience",+ EffectKind::Dither => "Utility",+ EffectKind::ResonantFilter | EffectKind::ParametricEq => "Equalization",+ EffectKind::Chorus | EffectKind::FlangeWahWah => "Modulation",+ EffectKind::ReverbFx => "Ambience",+ EffectKind::TrackCompressor => "Dynamics",+ EffectKind::TrackEq | EffectKind::ParagraphicEq => "Equalization",+ EffectKind::MultiTapDelay => "Ambience",+ EffectKind::MultiBandDynamics => "Dynamics",+ EffectKind::ExpressDelay => "Ambience",+ EffectKind::ExpressDistortion => "Distortion",+ EffectKind::ExpressEqualization => "Equalization",+ EffectKind::ExpressNoiseGate => "Dynamics",+ EffectKind::ExpressChorus => "Modulation",+ EffectKind::ExpressFlangeWahWah => "Modulation",+ EffectKind::ExpressDynamics => "Dynamics",+ EffectKind::ExpressStutter => "Modulation",+ EffectKind::ExpressAmplitudeModulation => "Modulation",+ EffectKind::ExpressGraphicEq => "Equalization",+ EffectKind::ExpressReverb => "Ambience",+ EffectKind::ExpressAudioRestoration => "Utility",+ EffectKind::AmplitudeModulation => "Modulation",+ EffectKind::GraphicDynamics => "Dynamics",+ EffectKind::Distortion => "Distortion",+ EffectKind::GraphicEq => "Equalization",+ EffectKind::WaveHammer => "Dynamics",+ EffectKind::StudioGate => "Dynamics",+ EffectKind::DeEsser => "Dynamics",+ EffectKind::StudioLimiter => "Dynamics",+ EffectKind::TremoloPan => "Modulation",+ EffectKind::TubeStage => "Distortion",+ EffectKind::VocalStrip => "Dynamics",+ EffectKind::StudioCompressor => "Dynamics",+ EffectKind::Phaser => "Modulation",+ EffectKind::ChorusFlanger => "Modulation",+ EffectKind::StudioReverb => "Ambience",+ EffectKind::StereoDelay => "Ambience",+ EffectKind::TimeStretch => "Pitch and time",+ EffectKind::ExpressTimeStretch => "Pitch and time",+ EffectKind::PitchShift => "Pitch and time",+ EffectKind::GapperSnipper => "Pitch and time",+ EffectKind::Vibrato => "Pitch and time",EffectKind::Plugin => "Plug-ins",EffectKind::Vst => "VST3",}@@ -339,6 +885,60 @@ impl EffectKind {P}EffectKind::ModernEq => &MODERN_EQ,+ EffectKind::Volume => crate::audio_fx::volume::PARAMS,+ EffectKind::Pan => crate::audio_fx::pan::PARAMS,+ EffectKind::SmoothEnhance => crate::audio_fx::smooth_enhance::PARAMS,+ EffectKind::NoiseGateFx => crate::audio_fx::noise_gate::PARAMS,+ EffectKind::TrackNoiseGate => crate::audio_fx::track_noise_gate::PARAMS,+ EffectKind::SimpleDelay => crate::audio_fx::simple_delay::PARAMS,+ EffectKind::Dither => crate::audio_fx::dither::PARAMS,+ EffectKind::ResonantFilter => crate::audio_fx::resonant_filter::PARAMS,+ EffectKind::ParametricEq => crate::audio_fx::parametric_eq::PARAMS,+ EffectKind::Chorus => crate::audio_fx::chorus::PARAMS,+ EffectKind::FlangeWahWah => crate::audio_fx::flange_wah_wah::PARAMS,+ EffectKind::ReverbFx => crate::audio_fx::reverb::PARAMS,+ EffectKind::TrackCompressor => crate::audio_fx::track_compressor::PARAMS,+ EffectKind::TrackEq => crate::audio_fx::track_eq::PARAMS,+ EffectKind::ParagraphicEq => crate::audio_fx::paragraphic_eq::PARAMS,+ EffectKind::MultiTapDelay => crate::audio_fx::multi_tap_delay::PARAMS,+ EffectKind::MultiBandDynamics => crate::audio_fx::multi_band_dynamics::PARAMS,+ EffectKind::ExpressDelay => crate::audio_fx::express_delay::PARAMS,+ EffectKind::ExpressDistortion => crate::audio_fx::express_distortion::PARAMS,+ EffectKind::ExpressEqualization => crate::audio_fx::express_equalization::PARAMS,+ EffectKind::ExpressNoiseGate => crate::audio_fx::express_noise_gate::PARAMS,+ EffectKind::ExpressChorus => crate::audio_fx::express_chorus::PARAMS,+ EffectKind::ExpressFlangeWahWah => crate::audio_fx::express_flange_wah_wah::PARAMS,+ EffectKind::ExpressDynamics => crate::audio_fx::express_dynamics::PARAMS,+ EffectKind::ExpressStutter => crate::audio_fx::express_stutter::PARAMS,+ EffectKind::ExpressAmplitudeModulation => {+ crate::audio_fx::express_amplitude_modulation::PARAMS+ }+ EffectKind::ExpressGraphicEq => crate::audio_fx::express_graphic_eq::PARAMS,+ EffectKind::ExpressReverb => crate::audio_fx::express_reverb::PARAMS,+ EffectKind::ExpressAudioRestoration => {+ crate::audio_fx::express_audio_restoration::PARAMS+ }+ EffectKind::AmplitudeModulation => crate::audio_fx::amplitude_modulation::PARAMS,+ EffectKind::GraphicDynamics => crate::audio_fx::graphic_dynamics::PARAMS,+ EffectKind::Distortion => crate::audio_fx::distortion::PARAMS,+ EffectKind::GraphicEq => crate::audio_fx::graphic_eq::PARAMS,+ EffectKind::WaveHammer => crate::audio_fx::wave_hammer::PARAMS,+ EffectKind::StudioGate => crate::audio_fx::efx_gate::PARAMS,+ EffectKind::DeEsser => crate::audio_fx::efx_deesser::PARAMS,+ EffectKind::StudioLimiter => crate::audio_fx::efx_limiter::PARAMS,+ EffectKind::TremoloPan => crate::audio_fx::efx_tremolo_pan::PARAMS,+ EffectKind::TubeStage => crate::audio_fx::efx_tube_stage::PARAMS,+ EffectKind::VocalStrip => crate::audio_fx::efx_vocal_strip::PARAMS,+ EffectKind::StudioCompressor => crate::audio_fx::efx_compressor::PARAMS,+ EffectKind::Phaser => crate::audio_fx::efx_phaser::PARAMS,+ EffectKind::ChorusFlanger => crate::audio_fx::efx_chorus_flanger::PARAMS,+ EffectKind::StudioReverb => crate::audio_fx::efx_reverb::PARAMS,+ EffectKind::StereoDelay => crate::audio_fx::efx_stereo_delay::PARAMS,+ EffectKind::TimeStretch => crate::audio_fx::time_stretch::PARAMS,+ EffectKind::ExpressTimeStretch => crate::audio_fx::express_time_stretch::PARAMS,+ EffectKind::PitchShift => crate::audio_fx::pitch_shift::PARAMS,+ EffectKind::GapperSnipper => crate::audio_fx::gapper_snipper::PARAMS,+ EffectKind::Vibrato => crate::audio_fx::vibrato::PARAMS,// Its plug-in describes them.EffectKind::Plugin | EffectKind::Vst => &[],}@@ -356,9 +956,9 @@ pub mod modern_eq {pub const BANDS: usize = 8;pub const PER_BAND: usize = 8;/// A band's, from its first: in use (added), on, type (High Pass, Low- /// Pass, Low Shelving, High Shelving, Band Pass, Peaking), frequency,- /// gain, Q, slope (dB an octave) and routing (Stereo, Left, Right,- /// Mid, Side).+ /// Pass, Low Shelving, High Shelving, Band Pass, Peaking, Band Stop),+ /// frequency, gain, Q, slope (dB an octave) and routing (Stereo, Left,+ /// Right, Mid, Side).pub const USED: usize = 0;pub const ON: usize = 1;pub const TYPE: usize = 2;@@ -375,8 +975,14 @@ pub mod modern_eq {/// Oversampling (Off, 2×, 4×, 8×: 0 to 3), after the bands.pub const OVERSAMPLING: usize = at(BANDS, 0);+ /// Band `b`'s phase (0 minimum, 1 linear), after Oversampling.+ pub const fn model(b: usize) -> usize {+ OVERSAMPLING + 1 + b+ }+ /// Linear Phase Quality (0 to 4: how long the linear-phase filter is).+ pub const QUALITY: usize = model(BANDS);/// How many parameters it has.- pub const COUNT: usize = OVERSAMPLING + 1;+ pub const COUNT: usize = QUALITY + 1;}/// A Modern Equalizer band's parameters; where a band at rest sits.@@ -385,7 +991,7 @@ macro_rules! eq_band {[toggle(concat!("Band ", $n), 0.0),toggle(concat!("Band ", $n, " On"), 1.0),- slider(concat!("Band ", $n, " Type"), 0.0, 5.0, 5.0),+ slider(concat!("Band ", $n, " Type"), 0.0, 6.0, 5.0),slider(concat!("Band ", $n, " Frequency (Hz)"),20.0,@@ -402,8 +1008,8 @@ macro_rules! eq_band {const MODERN_EQ_GLOBALS: [ParamSpec; modern_eq::GLOBALS] = [slider("Global Scale (%)", -200.0, 200.0, 100.0),- slider("Mono Below (Hz)", 0.0, 1000.0, 0.0),- slider("Stereo Width (%)", 0.0, 200.0, 100.0),+ slider("Mono Below (Hz)", 20.0, 200.0, 20.0),+ slider("Stereo Width (%)", 0.0, 100.0, 100.0),slider("Output Gain (dB)", -24.0, 24.0, 0.0),];@@ -418,9 +1024,22 @@ const MODERN_EQ_BANDS: [[ParamSpec; modern_eq::PER_BAND]; modern_eq::BANDS] = [eq_band!("8", 16_000.0),];+/// Each band's phase: minimum (0) or linear (1).+const MODERN_EQ_MODELS: [ParamSpec; modern_eq::BANDS] = [+ toggle("Band 1 Linear Phase", 0.0),+ toggle("Band 2 Linear Phase", 0.0),+ toggle("Band 3 Linear Phase", 0.0),+ toggle("Band 4 Linear Phase", 0.0),+ toggle("Band 5 Linear Phase", 0.0),+ toggle("Band 6 Linear Phase", 0.0),+ toggle("Band 7 Linear Phase", 0.0),+ toggle("Band 8 Linear Phase", 0.0),+];+const MODERN_EQ: [ParamSpec; modern_eq::COUNT] = {let mut out = [MODERN_EQ_GLOBALS[0]; modern_eq::COUNT];- out[modern_eq::OVERSAMPLING] = slider("Oversampling", 0.0, 3.0, 0.0);+ out[modern_eq::OVERSAMPLING] = slider("Oversampling", 0.0, 3.0, 1.0);+ out[modern_eq::QUALITY] = slider("Linear Phase Quality", 0.0, 4.0, 2.0);let mut i = 0;while i < modern_eq::GLOBALS {out[i] = MODERN_EQ_GLOBALS[i];@@ -433,6 +1052,7 @@ const MODERN_EQ: [ParamSpec; modern_eq::COUNT] = {out[modern_eq::at(b, p)] = MODERN_EQ_BANDS[b][p];p += 1;}+ out[modern_eq::model(b)] = MODERN_EQ_MODELS[b];b += 1;}out@@ -986,8 +1606,8 @@ pub enum FadeCurve {/// (`scene::video_curve`).#[default]Smooth,- /// The S turned around, as VEGAS's picture of it: fast at both ends,- /// slow in the middle (the smoothstep's inverse).+ /// The S turned around, as VEGAS's: fast at both ends, level in the+ /// middle — 4p³ − 6p² + 3p, its slopes 3, 0 and 3.Sharp,}@@ -1001,9 +1621,7 @@ impl FadeCurve {FadeCurve::Fast => 1.0 - (1.0 - p) * (1.0 - p),FadeCurve::Slow => p * p,FadeCurve::Smooth => (p * std::f32::consts::FRAC_PI_2).sin(),- // Exact at the ends.- FadeCurve::Sharp if p <= 0.0 || p >= 1.0 => p,- FadeCurve::Sharp => 0.5 - ((1.0 - 2.0 * p).asin() / 3.0).sin(),+ FadeCurve::Sharp => p * (3.0 + p * (4.0 * p - 6.0)),}}@@ -1526,13 +2144,15 @@ mod tests {let a = FadeCurve::Smooth.eval(1.0 - p);let b = FadeCurve::Smooth.eval(p);assert!((a * a + b * b - 1.0).abs() < 1e-6);- // Sharp is the S turned around: the smoothstep's inverse, fast at- // both ends and slow in the middle.- for p in [0.1f32, 0.3, 0.5, 0.8] {- let s = p * p * (3.0 - 2.0 * p);- assert!((FadeCurve::Sharp.eval(s) - p).abs() < 1e-5, "{p}");- }- assert!(FadeCurve::Sharp.eval(0.25) > 0.25 && FadeCurve::Sharp.eval(0.75) < 0.75);+ // Sharp is the S turned around, VEGAS's 4p³ − 6p² + 3p: fast at+ // both ends, level in the middle.+ let sharp = |p: f32| FadeCurve::Sharp.eval(p);+ assert_eq!(sharp(0.5), 0.5);+ assert!((sharp(0.25) - 0.4375).abs() < 1e-6);+ assert!((sharp(0.75) - 0.5625).abs() < 1e-6);+ let slope = |p: f32| (sharp(p + 1e-3) - sharp(p - 1e-3)) / 2e-3;+ assert!(slope(0.5).abs() < 1e-3);+ assert!((sharp(1e-3) / 1e-3 - 3.0).abs() < 1e-2);}#[test]diff --git a/crates/timeline/src/lib.rs b/crates/timeline/src/lib.rsindex 9a7473a..9dc5b96 100644--- a/crates/timeline/src/lib.rs+++ b/crates/timeline/src/lib.rs@@ -9,6 +9,7 @@//! começa depois cobre o anterior. No áudio, tudo que se sobrepõe é somado.mod arrange;+pub mod audio_fx;pub mod bins;pub mod busses;pub mod caption_files;@@ -28,6 +29,7 @@ pub mod input_busses;pub mod interchange;mod markers;pub mod mask;+mod mask_raster;mod model;pub mod motion;pub mod motion_tracks;@@ -35,6 +37,7 @@ mod multicam;pub mod nesting;pub mod notes;pub mod otio;+pub mod pancrop;pub mod prerender;mod ripple;pub mod scene;@@ -45,6 +48,7 @@ pub mod surround;pub mod tags;pub mod takes;pub mod track_groups;+pub mod veg;pub mod video_bus;pub mod xmeml;mod xml;@@ -64,8 +68,9 @@ pub use ducking::{DuckLevels, Ducking};pub use edit::EditError;pub use envelope::{Envelope, EnvelopeKind, EnvelopeOwner, EnvelopePoint};pub use fx::{- Direction, Effect, EffectKind, FadeCurve, KeyCurve, KeyHandles, ParamKind, ParamSpec, PluginFx,- PluginKey, PluginParam, PluginValue, Transform, TransformKey, Transition, VstFx,+ Direction, Effect, EffectKind, FadeCurve, Graph, KeyCurve, KeyHandles, ParamKind, ParamSpec,+ PluginFx, PluginKey, PluginParam, PluginValue, Show, Transform, TransformKey, Transition,+ VstFx,};pub use history::{Gesture, History};pub use input_busses::{InputBus, InputBusId, InputMonitor, MAX_INPUT_BUSSES};diff --git a/crates/timeline/src/mask.rs b/crates/timeline/src/mask.rsindex 465cc57..b891642 100644--- a/crates/timeline/src/mask.rs+++ b/crates/timeline/src/mask.rs@@ -18,19 +18,22 @@ use crate::fx::KeyCurve;/// tangents' ends from it, toward the anchor before and the one after.#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]pub struct MaskAnchor {- pub at: [f32; 2],+ pub at: [f64; 2],#[serde(default)]- pub before: [f32; 2],+ pub before: [f64; 2],#[serde(default)]- pub after: [f32; 2],+ pub after: [f64; 2],/// Its tangents turn apart (Split Tangents); else they stay in line.#[serde(default, skip_serializing_if = "std::ops::Not::not")]pub split: bool,+ /// In line, they are also as long as each other.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub even: bool,}impl MaskAnchor {/// A corner: no tangents.- pub fn corner(at: [f32; 2]) -> MaskAnchor {+ pub fn corner(at: [f64; 2]) -> MaskAnchor {MaskAnchor {at,..MaskAnchor::default()@@ -104,24 +107,31 @@ pub struct MaskPath {pub anti_alias: bool,/// How much of what it masks goes (0–1).#[serde(default = "one")]- pub opacity: f32,+ pub opacity: f64,#[serde(default)]pub feather: MaskFeather,/// How far its edge softens: a percentage of the media's shorter side.#[serde(default)]- pub feather_pct: f32,+ pub feather_pct: f64,+ /// Whether it closes; an open path masks nothing.+ #[serde(default = "yes", skip_serializing_if = "is_yes")]+ pub closed: bool,+}++fn is_yes(v: &bool) -> bool {+ *v}fn yes() -> bool {true}-fn one() -> f32 {+fn one() -> f64 {1.0}/// The kappa that makes four cubic Béziers a circle.-const KAPPA: f32 = 0.552_284_8;+const KAPPA: f64 = 0.552_284_749_830_793_6;impl MaskPath {/// A path of `anchors`, positive, anti-aliased, opaque, not feathered.@@ -133,11 +143,12 @@ impl MaskPath {opacity: 1.0,feather: MaskFeather::None,feather_pct: 0.0,+ closed: true,}}/// A rectangle from corner `a` to corner `b`.- pub fn rectangle(a: [f32; 2], b: [f32; 2]) -> MaskPath {+ pub fn rectangle(a: [f64; 2], b: [f64; 2]) -> MaskPath {let (x0, x1) = (a[0].min(b[0]), a[0].max(b[0]));let (y0, y1) = (a[1].min(b[1]), a[1].max(b[1]));MaskPath::new(@@ -149,16 +160,17 @@ impl MaskPath {/// A rectangle from `a` to `b` with its corners rounded by `r` (a/// part, 0–½, of its shorter side).- pub fn rounded(a: [f32; 2], b: [f32; 2], r: f32) -> MaskPath {+ pub fn rounded(a: [f64; 2], b: [f64; 2], r: f64) -> MaskPath {let (x0, x1) = (a[0].min(b[0]), a[0].max(b[0]));let (y0, y1) = (a[1].min(b[1]), a[1].max(b[1]));let r = r.clamp(0.0, 0.5) * (x1 - x0).min(y1 - y0);let k = r * KAPPA;- let side = |at: [f32; 2], before: [f32; 2], after: [f32; 2]| MaskAnchor {+ let side = |at: [f64; 2], before: [f64; 2], after: [f64; 2]| MaskAnchor {at,before,after,split: true,+ even: false,};MaskPath::new(vec![side([x0 + r, y0], [-k, 0.0], [0.0, 0.0]),@@ -173,15 +185,16 @@ impl MaskPath {}/// An oval filling the box from `a` to `b`.- pub fn oval(a: [f32; 2], b: [f32; 2]) -> MaskPath {+ pub fn oval(a: [f64; 2], b: [f64; 2]) -> MaskPath {let c = [(a[0] + b[0]) / 2.0, (a[1] + b[1]) / 2.0];let (rx, ry) = ((b[0] - a[0]).abs() / 2.0, (b[1] - a[1]).abs() / 2.0);let (kx, ky) = (rx * KAPPA, ry * KAPPA);- let smooth = |at: [f32; 2], t: [f32; 2]| MaskAnchor {+ let smooth = |at: [f64; 2], t: [f64; 2]| MaskAnchor {at,before: [-t[0], -t[1]],after: t,split: false,+ even: true,};MaskPath::new(vec![smooth([c[0], c[1] - ry], [kx, 0.0]),@@ -193,7 +206,7 @@ impl MaskPath {/// The upper half of the oval filling the box from `a` to `b` (its/// flat side the box's middle line).- pub fn half_oval(a: [f32; 2], b: [f32; 2]) -> MaskPath {+ pub fn half_oval(a: [f64; 2], b: [f64; 2]) -> MaskPath {let (x0, x1) = (a[0].min(b[0]), a[0].max(b[0]));let (y0, y1) = (a[1].min(b[1]), a[1].max(b[1]));let (rx, ry) = ((x1 - x0) / 2.0, y1 - y0);@@ -205,24 +218,27 @@ impl MaskPath {before: [0.0, 0.0],after: [0.0, -ky],split: true,+ even: false,},MaskAnchor {at: [cx, y0],before: [-kx, 0.0],after: [kx, 0.0],split: false,+ even: true,},MaskAnchor {at: [x1, y1],before: [0.0, -ky],after: [0.0, 0.0],split: true,+ even: false,},])}/// Its anchors' bounding box (`None` without anchors).- pub fn bounds(&self) -> Option<([f32; 2], [f32; 2])> {+ pub fn bounds(&self) -> Option<([f64; 2], [f64; 2])> {bounds(&self.anchors)}}@@ -259,7 +275,7 @@ pub fn offset_polygon(poly: &[[f64; 2]], d: f64) -> Vec<[f64; 2]> {}/// `anchors`' bounding box.-pub fn bounds(anchors: &[MaskAnchor]) -> Option<([f32; 2], [f32; 2])> {+pub fn bounds(anchors: &[MaskAnchor]) -> Option<([f64; 2], [f64; 2])> {let first = anchors.first()?.at;Some(anchors.iter().fold((first, first), |(lo, hi), a| {(@@ -278,6 +294,144 @@ pub struct MaskKey {pub shapes: Vec<Vec<MaskAnchor>>,#[serde(default)]pub curve: KeyCurve,+ /// Each path's settings here, in the paths' order, where they have their+ /// own (none: the path's all along).+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub looks: Vec<MaskLook>,+}++/// A path's settings at a keyframe.+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]+pub struct MaskLook {+ pub mode: MaskMode,+ pub anti_alias: bool,+ pub opacity: f64,+ pub feather: MaskFeather,+ pub feather_pct: f64,+}++impl MaskLook {+ fn of(p: &MaskPath) -> MaskLook {+ MaskLook {+ mode: p.mode,+ anti_alias: p.anti_alias,+ opacity: p.opacity,+ feather: p.feather,+ feather_pct: p.feather_pct,+ }+ }++ fn on(&self, p: &MaskPath) -> MaskPath {+ MaskPath {+ mode: self.mode,+ anti_alias: self.anti_alias,+ opacity: self.opacity,+ feather: self.feather,+ feather_pct: self.feather_pct,+ ..p.clone()+ }+ }+}++/// An angle a little under a half turn each way: the short way round.+fn short_way(d: f64) -> f64 {+ use std::f64::consts::{PI, TAU};+ if d > PI {+ d - TAU+ } else if d < -PI {+ d + TAU+ } else {+ d+ }+}++fn lerp(a: f64, b: f64, u: f64) -> f64 {+ (b - a) * u + a+}++fn lerp2(a: [f64; 2], b: [f64; 2], u: f64) -> [f64; 2] {+ [lerp(a[0], b[0], u), lerp(a[1], b[1], u)]+}++/// A tangent as its direction back to the anchor and its length.+fn polar(t: [f64; 2]) -> (f64, f64) {+ ((-t[1]).atan2(-t[0]), t[0].hypot(t[1]))+}++/// An anchor between two keyframes, `u` of the way: its point straight, its+/// tangents turning and growing the short way round when they have lengths.+fn anchor_between(a: &MaskAnchor, b: &MaskAnchor, u: f64) -> MaskAnchor {+ if u <= 0.0 {+ return *a;+ }+ if u >= 1.0 {+ return *b;+ }+ let at = lerp2(a.at, b.at, u);+ let bare = |k: &MaskAnchor| {+ k.before[0].abs() < 1e-9+ && k.before[1].abs() < 1e-9+ && k.after[0].abs() < 1e-9+ && k.after[1].abs() < 1e-9+ };+ let (split, even) = match (bare(a), bare(b)) {+ (true, true) => {+ return MaskAnchor {+ at,+ before: [0.0; 2],+ after: [0.0; 2],+ split: false,+ even: false,+ };+ }+ (true, false) | (false, true) => {+ let k = if bare(a) { b } else { a };+ return MaskAnchor {+ at,+ before: lerp2(a.before, b.before, u),+ after: lerp2(a.after, b.after, u),+ split: k.split,+ even: k.even,+ };+ }+ _ => (a.split || b.split, a.even && b.even && !a.split && !b.split),+ };+ let (t1, l1) = polar(a.before);+ let (t2, l2) = polar(b.before);+ let mut way = None;+ let before = if l1 < 1e-9 || l2 < 1e-9 || (t1 - t2).abs() < 0.001 {+ lerp2(a.before, b.before, u)+ } else {+ let th = short_way(t2 - t1) * u + t1;+ let l = lerp(l1, l2, u);+ let (s, c) = th.sin_cos();+ way = Some((c, s));+ [-l * c, -l * s]+ };+ let (t3, l3) = polar(a.after);+ let (t4, l4) = polar(b.after);+ let after = if l3 < 1e-9 || l4 < 1e-9 || (t3 - t4).abs() < 0.001 {+ lerp2(a.after, b.after, u)+ } else if even {+ [-before[0], -before[1]]+ } else {+ let (c, s) = match way {+ Some((c, s)) if !split => (-c, -s),+ _ => {+ let (s, c) = (short_way(t4 - t3) * u + t3).sin_cos();+ (c, s)+ }+ };+ let l = lerp(l3, l4, u);+ [-l * c, -l * s]+ };+ MaskAnchor {+ at,+ before,+ after,+ split,+ even,+ }}/// An event's masks: the Pan/Crop window's Mask row.@@ -307,52 +461,96 @@ impl PanCropMask {.any(|p| p.mode != MaskMode::Disabled && p.anchors.len() >= 2)}- /// The paths' shapes at `local` (from the event's start): their own- /// without keyframes, else from the keyframes — anchor by anchor as- /// far as the curve goes where both keyframes have as many, else the- /// one before's.- pub fn shapes_at(&self, local: Tick) -> Vec<Vec<MaskAnchor>> {- let own = || self.paths.iter().map(|p| p.anchors.clone()).collect();- let (Some(first), Some(last)) = (self.keys.first(), self.keys.last()) else {- return own();+ /// The paths as they are `t` (in the box's unit of time) after the+ /// event's start: their own without keyframes, else as far between the+ /// keyframes as the curve says.+ pub fn paths_at_units(&self, t: i64) -> Vec<MaskPath> {+ let when = |k: &MaskKey| crate::pancrop::units_near(k.at);+ let Some(first) = self.keys.first() else {+ return self.paths.clone();};- let fit = |s: &[Vec<MaskAnchor>]| {- let mut v = s.to_vec();- v.resize_with(self.paths.len(), Vec::new);- v.truncate(self.paths.len());- v+ let held = |k: &MaskKey| -> Vec<MaskPath> {+ self.paths+ .iter()+ .enumerate()+ .map(|(i, p)| {+ let mut p = k.looks.get(i).map_or_else(|| p.clone(), |l| l.on(p));+ if let Some(s) = k.shapes.get(i) {+ p.anchors.clone_from(s);+ } else {+ p.anchors.clear();+ }+ p+ })+ .collect()};- if local <= first.at {- return fit(&first.shapes);+ let i = self.keys.partition_point(|k| when(k) <= t);+ if i == 0 {+ return held(first);}- if local >= last.at {- return fit(&last.shapes);+ let a = &self.keys[i - 1];+ if when(a) == t || i == self.keys.len() {+ return held(a);}- let i = self.keys.partition_point(|k| k.at <= local);- let (a, b) = (&self.keys[i - 1], &self.keys[i]);- let span = (b.at - a.at).0.max(1) as f32;- let f = a.curve.eval((local - a.at).0 as f32 / span);- let mix = |x: f32, y: f32| x + (y - x) * f;- let mix2 = |x: [f32; 2], y: [f32; 2]| [mix(x[0], y[0]), mix(x[1], y[1])];- let shapes = a- .shapes- .iter()- .enumerate()- .map(|(p, sa)| match b.shapes.get(p) {- Some(sb) if sb.len() == sa.len() && a.curve != KeyCurve::Hold => sa- .iter()- .zip(sb)- .map(|(x, y)| MaskAnchor {- at: mix2(x.at, y.at),- before: mix2(x.before, y.before),- after: mix2(x.after, y.after),- split: x.split,- })- .collect(),- _ => sa.clone(),+ let b = &self.keys[i];+ let span = (when(b) - when(a)) as f64;+ let u = if span > 0.0 {+ crate::pancrop::ease(a.curve, (t - when(a)) as f64 / span)+ } else {+ 0.0+ };+ let (from, to) = (held(a), held(b));+ from.into_iter()+ .zip(to)+ .map(|(mut p, q)| {+ if p.anchors.is_empty() || q.anchors.is_empty() {+ return p;+ }+ p.opacity = lerp(p.opacity, q.opacity, u).clamp(0.0, 1.0);+ p.feather_pct = lerp(p.feather_pct, q.feather_pct, u);+ if p.anchors.len() == q.anchors.len() {+ p.anchors = p+ .anchors+ .iter()+ .zip(&q.anchors)+ .map(|(x, y)| anchor_between(x, y, u))+ .collect();+ }+ p})- .collect::<Vec<_>>();- fit(&shapes)+ .collect()+ }++ /// The paths' shapes at `local` (from the event's start).+ pub fn shapes_at(&self, local: Tick) -> Vec<Vec<MaskAnchor>> {+ self.paths_at_units(crate::pancrop::units_floor(local))+ .into_iter()+ .map(|p| p.anchors)+ .collect()+ }++ /// Path `i`'s settings at `local` become `path`'s: all along, without+ /// keyframes that have their own; else at the keyframe there, made when+ /// there is none.+ pub fn set_look_at(&mut self, local: Tick, i: usize, path: &MaskPath) {+ if self.keys.iter().all(|k| k.looks.is_empty()) {+ if let Some(p) = self.paths.get_mut(i) {+ *p = MaskLook::of(path).on(p);+ }+ return;+ }+ if !self.keys.iter().any(|k| k.at == local) {+ self.add_key(local);+ }+ let own: Vec<MaskLook> = self.paths.iter().map(MaskLook::of).collect();+ if let Some(k) = self.keys.iter_mut().find(|k| k.at == local) {+ if k.looks.len() < own.len() {+ k.looks.extend_from_slice(&own[k.looks.len()..]);+ }+ if let Some(l) = k.looks.get_mut(i) {+ *l = MaskLook::of(path);+ }+ }}/// The paths' shapes at `local` become `shapes`: their own without@@ -381,6 +579,7 @@ impl PanCropMask {at: local,shapes,curve,+ looks: Vec::new(),},);}@@ -396,6 +595,7 @@ impl PanCropMask {at: Tick::ZERO,shapes: shapes.clone(),curve: KeyCurve::Smooth,+ looks: Vec::new(),});}self.set_shapes_at(local, shapes);@@ -423,14 +623,14 @@ impl PanCropMask {/// Path `i`'s shape at `local` through `map` (a move, a scale, a flip:/// any affine map of the media's pixels), its tangents with it.- pub fn map_path_at(&mut self, local: Tick, i: usize, map: impl Fn([f32; 2]) -> [f32; 2]) {+ pub fn map_path_at(&mut self, local: Tick, i: usize, map: impl Fn([f64; 2]) -> [f64; 2]) {let mut shapes = self.shapes_at(local);let Some(shape) = shapes.get_mut(i) else {return;};for a in shape.iter_mut() {let at = map(a.at);- let end = |t: [f32; 2]| {+ let end = |t: [f64; 2]| {let p = map([a.at[0] + t[0], a.at[1] + t[1]]);[p[0] - at[0], p[1] - at[1]]};@@ -439,6 +639,7 @@ impl PanCropMask {before: end(a.before),after: end(a.after),split: a.split,+ even: a.even,};}self.set_shapes_at(local, shapes);@@ -479,7 +680,7 @@ impl PanCropMask {/// An anchor put on path `path`'s segment from its anchor `index` to the/// next, `t` (0–1) of the way along it, the curve kept as it was — in/// its shape at every keyframe too, as far along.- pub fn split_segment(&mut self, path: usize, index: usize, t: f32) {+ pub fn split_segment(&mut self, path: usize, index: usize, t: f64) {let Some(p) = self.paths.get_mut(path) else {return;};@@ -514,7 +715,7 @@ impl PanCropMask {/// A copy of path `i` (its shape at every keyframe too), moved by/// `offset`, added last; its index.- pub fn duplicate_path(&mut self, i: usize, offset: [f32; 2]) -> Option<usize> {+ pub fn duplicate_path(&mut self, i: usize, offset: [f64; 2]) -> Option<usize> {let mut path = self.paths.get(i)?.clone();let shift = |s: &[MaskAnchor]| -> Vec<MaskAnchor> {s.iter()@@ -566,6 +767,7 @@ impl PanCropMask {at: Tick::ZERO,shapes: m.paths.iter().map(|p| p.anchors.clone()).collect(),curve: KeyCurve::Smooth,+ looks: Vec::new(),};let mut out = a.clone();if out.keys.is_empty() {@@ -601,9 +803,15 @@ impl PanCropMask {/// A new path, its shape the same at every keyframe.pub fn add_path(&mut self, path: MaskPath) {+ let look = MaskLook::of(&path);+ let paths = self.paths.len();for k in &mut self.keys {- k.shapes.resize_with(self.paths.len(), Vec::new);+ k.shapes.resize_with(paths, Vec::new);k.shapes.push(path.anchors.clone());+ if !k.looks.is_empty() {+ k.looks.resize(paths, look);+ k.looks.push(look);+ }}self.paths.push(path);}@@ -618,6 +826,9 @@ impl PanCropMask {if i < k.shapes.len() {k.shapes.remove(i);}+ if i < k.looks.len() {+ k.looks.remove(i);+ }}}@@ -636,6 +847,12 @@ impl PanCropMask {.rev().find(|k| k.at <= delta).map_or(KeyCurve::Smooth, |k| k.curve),+ looks: self+ .keys+ .iter()+ .rev()+ .find(|k| k.at <= delta)+ .map_or_else(Vec::new, |k| k.looks.clone()),};let mut keys: Vec<MaskKey> = self.keys@@ -659,30 +876,34 @@ impl PanCropMask {if !self.keys.is_empty() {let shapes = self.shapes_at(cut);self.keys.retain(|k| k.at < cut);+ let looks = self.keys.last().map_or_else(Vec::new, |k| k.looks.clone());self.keys.push(MaskKey {at: cut,shapes,curve: KeyCurve::Linear,+ looks,});}right}- /// What [`PanCropMask::coverage`] at `local` depends on, with `sizes`- /// (the picture's and the media's): equal for equal coverages.- pub fn fingerprint(&self, local: Tick, sizes: [u32; 4]) -> u64 {+ /// What [`PanCropMask::coverage`] `t` (in the box's unit of time) after+ /// the event's start depends on, with `sizes` (the picture's and the+ /// media's): equal for equal coverages.+ pub fn fingerprint(&self, t: i64, sizes: [u32; 4]) -> u64 {use std::hash::{Hash, Hasher};use std::mem::discriminant;let mut h = std::collections::hash_map::DefaultHasher::new();sizes.hash(&mut h);- for (path, anchors) in self.paths.iter().zip(self.shapes_at(local)) {+ for path in self.paths_at_units(t) {discriminant(&path.mode).hash(&mut h);discriminant(&path.feather).hash(&mut h);path.anti_alias.hash(&mut h);+ path.closed.hash(&mut h);path.opacity.to_bits().hash(&mut h);path.feather_pct.to_bits().hash(&mut h);- anchors.len().hash(&mut h);- for a in anchors {+ path.anchors.len().hash(&mut h);+ for a in &path.anchors {for v in a.at.iter().chain(&a.before).chain(&a.after) {v.to_bits().hash(&mut h);}@@ -691,95 +912,47 @@ impl PanCropMask {h.finish()}- /// How much of each pixel of a `w` × `h` picture of the media the- /// masks keep at `local` (0–1, rows from the top): the media's pixels- /// times `scale` are the picture's, `short` the media's shorter side- /// (what the feather counts from). Positive paths add what is inside- /// them (starting from nothing, or from everything when there are- /// none), negative ones take it away, each as far as its opacity says.- pub fn coverage(- &self,- local: Tick,- w: usize,- h: usize,- scale: [f64; 2],- short: f64,- ) -> Vec<f32> {- let shapes = self.shapes_at(local);- let used: Vec<(&MaskPath, &Vec<MaskAnchor>)> = self- .paths- .iter()- .zip(&shapes)- .filter(|(p, s)| p.mode != MaskMode::Disabled && s.len() >= 2)- .collect();- let base = if used.iter().any(|(p, _)| p.mode == MaskMode::Positive) {- 0.0- } else {- 1.0- };- let mut keep = vec![base; w * h];- let px = (scale[0] + scale[1]) / 2.0;- for (path, anchors) in used {- let outline: Vec<[f64; 2]> = polygon(anchors)- .into_iter()- .map(|p| [p[0] * scale[0] - 0.5, p[1] * scale[1] - 0.5])- .collect();- let feather = match path.feather {- MaskFeather::None => 0.0,- _ => path.feather_pct.max(0.0) as f64 / 100.0 * short * px,- };- let opacity = path.opacity.clamp(0.0, 1.0);- shape_coverage(- &outline,- w,- h,- feather,- path.feather,- path.anti_alias,- |i, c| {- let c = c * opacity;- keep[i] = match path.mode {- MaskMode::Positive => keep[i] + c - keep[i] * c,- _ => keep[i] * (1.0 - c),- };- },- );- }- keep+ /// How much of each pixel of a `w` × `h` picture of the media the masks+ /// keep `t` (in the box's unit of time) after the event's start (0–1, rows+ /// from the top), in 8-bit steps: the media's pixels times `scale`+ /// are the picture's, `aspect` wide. The first path starts from nothing,+ /// or from everything when it is negative; each adds what is inside it or+ /// takes it away, as far as its opacity says.+ pub fn coverage(&self, t: i64, w: usize, h: usize, scale: [f64; 2], aspect: f64) -> Vec<f32> {+ crate::mask_raster::alpha(&self.paths_at_units(t), w, h, scale, aspect)+ .into_iter()+ .map(|v| f32::from(v) / 255.0)+ .collect()}}/// The point `t` (0–1) of the way along the segment of `anchors` from its/// anchor `i` to the next.-pub fn segment_point(anchors: &[MaskAnchor], i: usize, t: f32) -> [f32; 2] {+pub fn segment_point(anchors: &[MaskAnchor], i: usize, t: f64) -> [f64; 2] {let n = anchors.len();let (a, b) = (anchors[i % n], anchors[(i + 1) % n]);let p = [- [a.at[0] as f64, a.at[1] as f64],- [(a.at[0] + a.after[0]) as f64, (a.at[1] + a.after[1]) as f64],- [- (b.at[0] + b.before[0]) as f64,- (b.at[1] + b.before[1]) as f64,- ],- [b.at[0] as f64, b.at[1] as f64],+ a.at,+ [a.at[0] + a.after[0], a.at[1] + a.after[1]],+ [b.at[0] + b.before[0], b.at[1] + b.before[1]],+ b.at,];- let q = bezier(&p, t as f64);- [q[0] as f32, q[1] as f32]+ bezier(&p, t)}/// Splits the segment of `anchors` from anchor `i` to the next at `t`/// (de Casteljau's): the new anchor's tangents and its neighbors' make the/// same curve; a straight segment stays straight, the anchor a corner.-fn split_in(anchors: &mut Vec<MaskAnchor>, i: usize, t: f32) {+fn split_in(anchors: &mut Vec<MaskAnchor>, i: usize, t: f64) {let n = anchors.len();if n < 2 || i >= n {return;}let j = (i + 1) % n;let (a, b) = (anchors[i], anchors[j]);- let lerp = |p: [f32; 2], q: [f32; 2]| [p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t];- let add = |p: [f32; 2], d: [f32; 2]| [p[0] + d[0], p[1] + d[1]];- let sub = |p: [f32; 2], q: [f32; 2]| [p[0] - q[0], p[1] - q[1]];+ let lerp = |p: [f64; 2], q: [f64; 2]| [p[0] + (q[0] - p[0]) * t, p[1] + (q[1] - p[1]) * t];+ let add = |p: [f64; 2], d: [f64; 2]| [p[0] + d[0], p[1] + d[1]];+ let sub = |p: [f64; 2], q: [f64; 2]| [p[0] - q[0], p[1] - q[1]];let (p0, p1, p2, p3) = (a.at, add(a.at, a.after), add(b.at, b.before), b.at);let (q0, q1, q2) = (lerp(p0, p1), lerp(p1, p2), lerp(p2, p3));let (r0, r1) = (lerp(q0, q1), lerp(q1, q2));@@ -792,6 +965,7 @@ fn split_in(anchors: &mut Vec<MaskAnchor>, i: usize, t: f32) {before: sub(r0, s),after: sub(r1, s),split: false,+ even: false,}};anchors[i].after = sub(q0, p0);@@ -805,17 +979,13 @@ fn split_in(anchors: &mut Vec<MaskAnchor>, i: usize, t: f32) {pub fn polygon(anchors: &[MaskAnchor]) -> Vec<[f64; 2]> {let n = anchors.len();let mut out = Vec::with_capacity(n * 24);- let f = |p: [f32; 2]| [p[0] as f64, p[1] as f64];for i in 0..n {let (a, b) = (anchors[i], anchors[(i + 1) % n]);let p = [- f(a.at),- [(a.at[0] + a.after[0]) as f64, (a.at[1] + a.after[1]) as f64],- [- (b.at[0] + b.before[0]) as f64,- (b.at[1] + b.before[1]) as f64,- ],- f(b.at),+ a.at,+ [a.at[0] + a.after[0], a.at[1] + a.after[1]],+ [b.at[0] + b.before[0], b.at[1] + b.before[1]],+ b.at,];let straight = a.after == [0.0; 2] && b.before == [0.0; 2];let steps = if straight { 1 } else { 24 };@@ -836,215 +1006,6 @@ fn bezier(p: &[[f64; 2]; 4], t: f64) -> [f64; 2] {]}-/// One shape's coverage of a `w` × `h` picture (its outline in the-/// picture's pixels, their middles at whole numbers), handed pixel by-/// pixel to `put` (index, 0–1) where it is not 0: inside 1, outside 0, its-/// edge softened over `feather` pixels the way `style` says, or with-/// `anti_alias` each edge pixel as much as the shape covers it (four rows-/// of samples, the spans' overlaps across). Only the shape's bounding box-/// (and its feather) is worked out.-fn shape_coverage(- outline: &[[f64; 2]],- w: usize,- h: usize,- feather: f64,- style: MaskFeather,- anti_alias: bool,- mut put: impl FnMut(usize, f32),-) {- if outline.len() < 3 || w == 0 || h == 0 {- return;- }- let soft = if feather >= 1.0 { feather } else { 0.0 };- let reach = soft + 3.0;- let (lo, hi) = outline.iter().fold(- ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]),- |(lo, hi), p| {- (- [lo[0].min(p[0]), lo[1].min(p[1])],- [hi[0].max(p[0]), hi[1].max(p[1])],- )- },- );- let x0 = (lo[0] - reach).floor().clamp(0.0, w as f64) as usize;- let y0 = (lo[1] - reach).floor().clamp(0.0, h as f64) as usize;- let x1 = (hi[0] + reach).ceil().clamp(0.0, w as f64) as usize;- let y1 = (hi[1] + reach).ceil().clamp(0.0, h as f64) as usize;- if x1 <= x0 || y1 <= y0 {- return;- }- let (bw, bh) = (x1 - x0, y1 - y0);- let at = |x: usize, y: usize| (y + y0) * w + x + x0;- // Where the outline's edges cross the line `fy` (even-odd pairs, the- // box's x).- let crossings = |fy: f64, xs: &mut Vec<f64>| {- xs.clear();- for i in 0..outline.len() {- let (a, b) = (outline[i], outline[(i + 1) % outline.len()]);- if (a[1] <= fy) != (b[1] <= fy) {- let t = (fy - a[1]) / (b[1] - a[1]);- xs.push(a[0] + t * (b[0] - a[0]) - x0 as f64);- }- }- xs.sort_by(|a, b| a.total_cmp(b));- };- let mut xs = Vec::new();- if soft <= 0.0 && anti_alias {- let mut row = vec![0.0f64; bw];- for y in 0..bh {- row.fill(0.0);- for sub in [-0.375, -0.125, 0.125, 0.375] {- crossings((y + y0) as f64 + sub, &mut xs);- for pair in xs.chunks(2) {- if let [xa, xb] = pair {- let from = (xa + 0.5).floor().max(0.0) as usize;- let to = ((xb + 0.5).ceil().max(0.0) as usize).min(bw);- for (x, v) in row.iter_mut().enumerate().take(to).skip(from) {- let px = x as f64;- let o = (xb.min(px + 0.5) - xa.max(px - 0.5)).max(0.0);- *v += o / 4.0;- }- }- }- }- for (x, v) in row.iter().enumerate() {- if *v > 0.0 {- put(at(x, y), v.min(1.0) as f32);- }- }- }- return;- }- // Each row's middle: inside or not (rows on the processor's threads).- let mut inside = vec![false; bw * bh];- bv_color::par_rows(&mut inside, bw, |y, row| {- let mut xs = Vec::new();- crossings((y + y0) as f64, &mut xs);- for pair in xs.chunks(2) {- if let [xa, xb] = pair {- let from = xa.ceil().max(0.0) as usize;- let to = (xb.floor() + 1.0).clamp(0.0, bw as f64) as usize;- for v in &mut row[from.min(bw)..to.max(from.min(bw))] {- *v = true;- }- }- }- });- if soft <= 0.0 {- for y in 0..bh {- for x in 0..bw {- if inside[y * bw + x] {- put(at(x, y), 1.0);- }- }- }- return;- }- // Feathered: by the signed distance to the edge (inside positive), in- // pixels.- let outside_d = distance(&inside, bw, bh, true, reach);- let inside_d = distance(&inside, bw, bh, false, reach);- let mut soft_cover = vec![0.0f32; bw * bh];- bv_color::par_rows(&mut soft_cover, bw, |y, row| {- for (x, out) in row.iter_mut().enumerate() {- let i = y * bw + x;- let d = if inside[i] {- inside_d[i] - 0.5- } else {- 0.5 - outside_d[i]- };- *out = match style {- MaskFeather::In => smooth(0.0, soft, d),- MaskFeather::Out => smooth(-soft, 0.0, d),- MaskFeather::Both | MaskFeather::None => smooth(-soft / 2.0, soft / 2.0, d),- } as f32;- }- });- for (i, &c) in soft_cover.iter().enumerate() {- if c > 0.0 {- put(at(i % bw, i / bw), c);- }- }-}--fn smooth(e0: f64, e1: f64, x: f64) -> f64 {- let t = ((x - e0) / (e1 - e0).max(1e-9)).clamp(0.0, 1.0);- t * t * (3.0 - 2.0 * t)-}--/// Each pixel's distance (pixels, up to `reach`) to the nearest pixel of-/// the other side: to an inside one from outside (`from_outside`), else to-/// an outside one (the box's edges count as outside). Felzenszwalb and-/// Huttenlocher's exact transform, a column then a row at a time.-fn distance(inside: &[bool], w: usize, h: usize, from_outside: bool, reach: f64) -> Vec<f64> {- if w == 0 || h == 0 {- return Vec::new();- }- let far = reach * reach + 1.0;- // Down each column first, the columns kept as rows (the picture- // turned), then along each row: rows on the processor's threads.- let mut columns = vec![0.0f64; w * h];- bv_color::par_rows(&mut columns, h, |x, out| {- let line: Vec<f64> = (0..h)- .map(|y| {- if inside[y * w + x] == from_outside {- 0.0- } else {- far- }- })- .collect();- transform_1d(&line, out);- });- let mut f = vec![0.0f64; w * h];- bv_color::par_rows(&mut f, w, |y, out| {- let line: Vec<f64> = (0..w).map(|x| columns[x * h + y]).collect();- transform_1d(&line, out);- for v in out.iter_mut() {- *v = v.sqrt().min(reach);- }- });- f-}--/// The squared distance transform of a sampled function: the lower-/// envelope of the parabolas rooted at each sample.-fn transform_1d(f: &[f64], d: &mut [f64]) {- let n = f.len();- if n == 0 {- return;- }- let mut v = vec![0usize; n];- let mut z = vec![0.0f64; n + 1];- let mut k = 0usize;- z[0] = f64::NEG_INFINITY;- z[1] = f64::INFINITY;- for q in 1..n {- let s = loop {- let p = v[k];- let s = ((f[q] + (q * q) as f64) - (f[p] + (p * p) as f64)) / (2 * (q - p)) as f64;- // z[0] is minus infinity: k never goes below 0.- if s <= z[k] {- k -= 1;- } else {- break s;- }- };- k += 1;- v[k] = q;- z[k] = s;- z[k + 1] = f64::INFINITY;- }- k = 0;- for (q, out) in d.iter_mut().enumerate() {- while z[k + 1] < q as f64 {- k += 1;- }- let dq = q as f64 - v[k] as f64;- *out = dq * dq + f[v[k]];- }-}-#[cfg(test)]mod tests {use super::*;@@ -1086,30 +1047,31 @@ mod tests {};m.add_path(MaskPath::rectangle([10.25, 10.0], [30.0, 20.0]));assert!(m.active());- let c = m.coverage(Tick::ZERO, 40, 30, [1.0, 1.0], 30.0);+ let c = m.coverage(0, 40, 30, [1.0, 1.0], 1.0);let at = |c: &[f32], x: usize, y: usize| c[y * 40 + x];assert!(at(&c, 20, 15) > 0.99 && at(&c, 2, 2) < 0.01);// Anti-aliased: the edge pixel as much as it is covered.- assert!((at(&c, 10, 15) - 0.75).abs() < 1e-3, "{}", at(&c, 10, 15));+ assert!((at(&c, 10, 15) - 0.75).abs() < 3e-3, "{}", at(&c, 10, 15));assert!(at(&c, 9, 15) < 1e-6);m.paths[0].mode = MaskMode::Negative;- let c = m.coverage(Tick::ZERO, 40, 30, [1.0, 1.0], 30.0);+ let c = m.coverage(0, 40, 30, [1.0, 1.0], 1.0);assert!(at(&c, 20, 15) < 0.01 && at(&c, 2, 2) > 0.99);// Half opacity: half of it goes.m.paths[0].opacity = 0.5;- let c = m.coverage(Tick::ZERO, 40, 30, [1.0, 1.0], 30.0);- assert!((at(&c, 20, 15) - 0.5).abs() < 1e-3);+ let c = m.coverage(0, 40, 30, [1.0, 1.0], 1.0);+ assert!((at(&c, 20, 15) - 0.5).abs() < 3e-3);let mut o = PanCropMask {enabled: true,..PanCropMask::default()};o.add_path(MaskPath::oval([0.0, 0.0], [40.0, 30.0]));- let c = o.coverage(Tick::ZERO, 40, 30, [1.0, 1.0], 30.0);+ let c = o.coverage(0, 40, 30, [1.0, 1.0], 1.0);assert!(at(&c, 20, 15) > 0.99 && at(&c, 1, 1) < 0.01);// At half the picture's size, the same shape.- let c = o.coverage(Tick::ZERO, 20, 15, [0.5, 0.5], 30.0);+ let c = o.coverage(0, 20, 15, [0.5, 0.5], 1.0);assert!(c[7 * 20 + 10] > 0.99 && c[0] < 0.01);- // Feathered out by a tenth of 100 pixels: 10 pixels outside.+ // Feathered out by a tenth of 100 pixels: softening outside it, the+ // middle whole.let mut f = PanCropMask {enabled: true,..PanCropMask::default()@@ -1118,11 +1080,11 @@ mod tests {r.feather = MaskFeather::Out;r.feather_pct = 10.0;f.add_path(r);- let c = f.coverage(Tick::ZERO, 100, 100, [1.0, 1.0], 100.0);+ let c = f.coverage(0, 100, 100, [1.0, 1.0], 1.0);let row = |x: usize| c[50 * 100 + x];assert!(row(50) > 0.99 && row(45) > 0.99, "inside whole");assert!(row(35) > 0.05 && row(35) < 0.95, "softening outside");- assert!(row(25) < 0.01, "nothing past the feather");+ assert!(row(10) < 0.01, "nothing far past the feather");// Disabled or off: nothing masked.f.paths[0].mode = MaskMode::Disabled;assert!(!f.active());@@ -1132,6 +1094,70 @@ mod tests {assert!(!g.active());}+ /// A keyframe's own settings: its opacity and feather go from one to the+ /// next, its other settings hold.+ #[test]+ fn a_keyframes_settings_go_with_it() {+ let mut m = PanCropMask {+ enabled: true,+ ..PanCropMask::default()+ };+ m.add_path(MaskPath::rectangle([0.0, 0.0], [10.0, 10.0]));+ m.add_key(Tick::ZERO);+ m.set_key_curve(Tick::ZERO, KeyCurve::Linear);+ m.add_key(s(2));+ m.keys[1].looks = vec![MaskLook {+ mode: MaskMode::Negative,+ anti_alias: true,+ opacity: 0.5,+ feather: MaskFeather::Both,+ feather_pct: 20.0,+ }];+ let at = |t: Tick| m.paths_at_units(crate::pancrop::units_floor(t)).remove(0);+ let mid = at(s(1));+ assert!((mid.opacity - 0.75).abs() < 1e-9);+ assert!((mid.feather_pct - 10.0).abs() < 1e-9);+ assert_eq!(mid.mode, MaskMode::Positive);+ let end = at(s(2));+ assert_eq!(end.mode, MaskMode::Negative);+ assert_eq!(end.opacity, 0.5);+ }++ /// Tangents between keyframes turn the short way round, keeping their+ /// lengths' mean, not straight through the anchor.+ #[test]+ fn tangents_turn_between_keyframes() {+ let a = MaskAnchor {+ at: [0.0, 0.0],+ before: [-10.0, 0.0],+ after: [10.0, 0.0],+ split: false,+ even: false,+ };+ let b = MaskAnchor {+ at: [4.0, 0.0],+ before: [0.0, -10.0],+ after: [0.0, 10.0],+ split: false,+ even: false,+ };+ let m = anchor_between(&a, &b, 0.5);+ assert_eq!(m.at, [2.0, 0.0]);+ let k = 10.0 * std::f64::consts::FRAC_1_SQRT_2;+ assert!(+ (m.before[0] + k).abs() < 1e-9 && (m.before[1] + k).abs() < 1e-9,+ "{m:?}"+ );+ // In line with it.+ assert!(+ (m.after[0] - k).abs() < 1e-9 && (m.after[1] - k).abs() < 1e-9,+ "{m:?}"+ );+ // No tangents on either: none.+ let c = MaskAnchor::corner([0.0, 0.0]);+ assert_eq!(anchor_between(&c, &c, 0.5).after, [0.0; 2]);+ }+/// An event's masks through edits: a cut gives each half the shapes/// where they were, trimming its start keeps them on the media, and the/// halves join back into one.@@ -1274,12 +1300,14 @@ mod tests {before: [0.0, 0.0],after: [0.0, 40.0],split: false,+ even: false,};let b = MaskAnchor {at: [100.0, 0.0],before: [0.0, 40.0],after: [0.0, -10.0],split: false,+ even: false,};let c = MaskAnchor::corner([50.0, -60.0]);let mut m = PanCropMask {@@ -1287,14 +1315,14 @@ mod tests {paths: vec![MaskPath::new(vec![a, b, c])],..PanCropMask::default()};- let curve: Vec<[f32; 2]> = (0..=10)- .map(|k| segment_point(&m.paths[0].anchors, 0, k as f32 / 10.0))+ let curve: Vec<[f64; 2]> = (0..=10)+ .map(|k| segment_point(&m.paths[0].anchors, 0, f64::from(k) / 10.0)).collect();m.split_segment(0, 0, 0.3);let s = &m.paths[0].anchors;assert_eq!(s.len(), 4);for (k, got) in curve.iter().enumerate() {- let t = k as f32 / 10.0;+ let t = k as f64 / 10.0;let want = if t <= 0.3 {segment_point(s, 0, t / 0.3)} else {diff --git a/crates/timeline/src/mask_raster.rs b/crates/timeline/src/mask_raster.rsnew file mode 100644index 0000000..941276f--- /dev/null+++ b/crates/timeline/src/mask_raster.rs@@ -0,0 +1,749 @@+//! A Pan/Crop mask's 8-bit picture, the same as VEGAS's rendered frames pixel by+//! pixel (`pan_crop_renders` checks it): its paths' curves cut+//! into pieces going one way down, those followed line by line (sixteen+//! bands a line with anti-aliasing) and filled from one crossing to the next;+//! a feather is a recursive Gaussian over the filled path, a one-way one+//! bent by a curve; the paths then add up or take away, each as far as its+//! opacity says.++use crate::mask::{MaskAnchor, MaskFeather, MaskMode, MaskPath};++/// A cubic of the path, a piece going one way down (or a straight line).+#[derive(Clone, Copy, Debug)]+struct Piece {+ p0: [f64; 2],+ p3: [f64; 2],+ a: [f64; 2],+ b: [f64; 2],+ c: [f64; 2],+ /// Drawn upward along the path: put the other way round here.+ reversed: bool,+}++/// Rounds to the nearest whole number, ties to the even one.+fn nearest(x: f64) -> f64 {+ x.round_ties_even()+}++fn clamp8(v: f64) -> f64 {+ v.clamp(0.0, 255.0)+}++/// The rounding of a value about to be a pixel's.+fn to_level(v: f64) -> u8 {+ nearest(clamp8(v) + 1.5e-8) as u8+}++const NEAR_HALF: f64 = 0.499_999_985;++fn lerp2(a: [f64; 2], b: [f64; 2], t: f64) -> [f64; 2] {+ [(b[0] - a[0]) * t + a[0], (b[1] - a[1]) * t + a[1]]+}++fn straight(p: &[[f64; 2]; 4]) -> bool {+ (p[0][0] - p[1][0]).abs() < 1e-6+ && (p[0][1] - p[1][1]).abs() < 1e-6+ && (p[2][0] - p[3][0]).abs() < 1e-6+ && (p[2][1] - p[3][1]).abs() < 1e-6+}++/// A cubic's power form: `a t³ + b t² + c t + p0`.+fn cubic(p: &[[f64; 2]; 4]) -> ([f64; 2], [f64; 2], [f64; 2]) {+ let c = [(p[1][0] - p[0][0]) * 3.0, (p[1][1] - p[0][1]) * 3.0];+ let b = [+ (p[2][0] - p[1][0]) * 3.0 - c[0],+ (p[2][1] - p[1][1]) * 3.0 - c[1],+ ];+ let a = [+ p[3][0] - c[0] - b[0] - p[0][0],+ p[3][1] - c[1] - b[1] - p[0][1],+ ];+ (a, b, c)+}++/// Where a cubic of power form `(a, b, c)` turns back, inside (0, 1), in order.+fn turning_points(a: f64, b: f64, c: f64) -> Vec<f64> {+ let inside = |t: f64| t > 0.0 && t < 1.0;+ let mut out = Vec::new();+ if a == 0.0 {+ if b != 0.0 && c != 0.0 {+ let t = c / (b * -2.0);+ if inside(t) {+ out.push(t);+ }+ }+ } else if c == 0.0 {+ if b != 0.0 {+ let t = (b * -2.0) / (a * 3.0);+ if inside(t) {+ out.push(t);+ }+ }+ } else {+ let d = b * b - a * 3.0 * c;+ if d > 0.0 {+ let m = if a >= 0.0 { -b } else { b };+ let q = d.sqrt();+ for t in [(m - q) / (a.abs() * 3.0), (m + q) / (a.abs() * 3.0)] {+ if inside(t) {+ out.push(t);+ }+ }+ }+ }+ out+}++fn split(p: &[[f64; 2]; 4], t: f64) -> ([[f64; 2]; 4], [[f64; 2]; 4]) {+ let (ab, bc, cd) = (+ lerp2(p[0], p[1], t),+ lerp2(p[1], p[2], t),+ lerp2(p[2], p[3], t),+ );+ let (abc, bcd) = (lerp2(ab, bc, t), lerp2(bc, cd, t));+ let m = lerp2(abc, bcd, t);+ ([p[0], ab, abc, m], [m, bcd, cd, p[3]])+}++/// The pieces of a segment.+fn pieces_of(p: [[f64; 2]; 4], out: &mut Vec<Piece>) {+ let mut push = |q: [[f64; 2]; 4]| {+ let reversed = q[0][1] > q[3][1];+ let o = if reversed {+ [q[3], q[2], q[1], q[0]]+ } else {+ q+ };+ let (a, b, c) = if straight(&q) {+ ([0.0; 2], [0.0; 2], [o[3][0] - o[0][0], o[3][1] - o[0][1]])+ } else {+ cubic(&o)+ };+ out.push(Piece {+ p0: o[0],+ p3: o[3],+ a,+ b,+ c,+ reversed,+ });+ };+ if straight(&p) {+ push(p);+ return;+ }+ let (a, b, c) = cubic(&p);+ let turns = turning_points(a[1], b[1], c[1]);+ match turns.as_slice() {+ [t] => {+ let (l, r) = split(&p, *t);+ push(l);+ push(r);+ }+ [t0, t1] => {+ let (first, rest) = split(&p, *t0);+ let (second, third) = split(&rest, (t1 - t0) / (1.0 - t0));+ push(first);+ push(second);+ push(third);+ }+ _ => push(p),+ }+}++/// Pieces in a row going the same way down.+#[derive(Clone, Debug)]+struct Group {+ pieces: Vec<Piece>,+ top: f64,+ base: f64,+}++/// A path's groups, in the picture's pixels, by where they start down.+fn groups_of(anchors: &[MaskAnchor], scale: [f64; 2]) -> Vec<Group> {+ let n = anchors.len();+ let at = |p: [f64; 2]| [p[0] * scale[0], p[1] * scale[1]];+ let mut pieces = Vec::with_capacity(n * 3);+ for i in 0..n {+ let (a, b) = (&anchors[i], &anchors[(i + 1) % n]);+ pieces_of(+ [+ at(a.at),+ at([a.at[0] + a.after[0], a.at[1] + a.after[1]]),+ at([b.at[0] + b.before[0], b.at[1] + b.before[1]]),+ at(b.at),+ ],+ &mut pieces,+ );+ }+ // From where one way begins.+ for _ in 0..pieces.len() {+ if pieces[0].reversed == pieces[pieces.len() - 1].reversed {+ pieces.rotate_left(1);+ } else {+ break;+ }+ }+ let mut groups: Vec<Group> = pieces+ .chunk_by(|a, b| a.reversed == b.reversed)+ .map(|run| {+ let mut g = run.to_vec();+ if g[0].reversed {+ g.reverse();+ }+ Group {+ top: g[0].p0[1],+ base: g[g.len() - 1].p3[1],+ pieces: g,+ }+ })+ .collect();+ groups.sort_by(|a, b| a.top.total_cmp(&b.top));+ groups+}++/// Where a piece that goes one way down is at `y`.+fn along(s: &Piece, y: f64) -> f64 {+ let t = if s.a[1] == 0.0 && s.b[1] == 0.0 {+ if s.c[1] == 0.0 {+ 0.0+ } else {+ (y - s.p0[1]) / s.c[1]+ }+ } else {+ let (mut lo, mut hi) = (0.0f64, 1.0f64);+ for _ in 0..60 {+ let m = (lo + hi) * 0.5;+ if ((s.a[1] * m + s.b[1]) * m + s.c[1]) * m + s.p0[1] < y {+ lo = m;+ } else {+ hi = m;+ }+ }+ (lo + hi) * 0.5+ };+ ((s.a[0] * t + s.b[0]) * t + s.c[0]) * t + s.p0[0]+}++/// Where a group crosses the band `[y0, y1)`, measured at its middle; `None`+/// when it does not.+fn crossing(g: &Group, y0: f64, y1: f64) -> Option<f64> {+ let y = (y0 + y1) * 0.5;+ if g.top > y {+ return (g.top < y1).then(|| g.pieces[0].p0[0]);+ }+ if y > g.base {+ return (y0 < g.base).then(|| g.pieces[g.pieces.len() - 1].p3[0]);+ }+ let mut i = 0;+ while i + 1 < g.pieces.len() && g.pieces[i].p3[1] < y {+ i += 1;+ }+ let s = &g.pieces[i];+ if y - s.p0[1] < 0.001 {+ return Some(s.p0[0]);+ }+ if s.p3[1] - y < 0.001 {+ return Some(s.p3[0]);+ }+ (s.p0[1] < y && y < s.p3[1]).then(|| along(s, y))+}++fn whole(v: f64, w: usize) -> usize {+ v.clamp(0.0, w as f64) as usize+}++/// A line without anti-aliasing: each pair of crossings filled.+fn plain_line(row: &mut [u8], xs: &[f64]) {+ let w = row.len();+ for pair in xs.as_chunks::<2>().0 {+ let a = nearest(pair[0] + 1.5e-8);+ if w as f64 <= a {+ return;+ }+ let from = whole(a, w);+ let to = whole(nearest(pair[1] + 1.5e-8), w);+ if from < to {+ row[from..to].fill(255);+ }+ }+}++/// A group's crossings of a line's sixteen bands.+#[derive(Clone, Copy)]+struct Bands {+ x: [f64; 16],+ seen: [bool; 16],+ min: f64,+ max: f64,+ count: u32,+}++/// A line whose groups do not overlap across and all cross its sixteen bands:+/// the coverage summed before it is rounded, the middle whole.+fn fast_line(row: &mut [u8], groups: &[Bands]) {+ let w = row.len();+ let dv = 255.0 / 16.0;+ for pair in groups.as_chunks::<2>().0 {+ let (l, r) = (&pair[0], &pair[1]);+ let a = nearest(l.min - NEAR_HALF);+ if w as f64 <= a {+ return;+ }+ let from = whole(a, w);+ let end = whole(nearest(r.max + NEAR_HALF), w);+ let lead = whole(nearest(l.max + NEAR_HALF).max(from as f64), end);+ let middle = whole(nearest(r.min - NEAR_HALF).max(lead as f64), end);+ for (p, v) in row.iter_mut().enumerate().take(lead).skip(from) {+ let (q, q1) = (p as f64, p as f64 + 1.0);+ let mut sum = 0.0;+ for k in 0..16 {+ if l.x[k] < q1 {+ sum += r.x[k].min(q1) - if l.x[k] <= q { q } else { l.x[k] };+ }+ }+ *v = to_level(sum * dv);+ }+ if lead < middle {+ row[lead..middle].fill(255);+ }+ for (p, v) in row.iter_mut().enumerate().take(end).skip(middle) {+ let (q, q1) = (p as f64, p as f64 + 1.0);+ let mut sum = 0.0;+ for k in 0..16 {+ if q < r.x[k] {+ sum += (if q1 <= r.x[k] { q1 } else { r.x[k] }) - q.max(l.x[k]);+ }+ }+ *v = to_level(sum * dv);+ }+ }+}++/// One of a line's sixteen bands added to it.+fn add_band(row: &mut [u8], xs: &[f64]) {+ let w = row.len();+ let dv = 255.0 / 16.0;+ for pair in xs.as_chunks::<2>().0 {+ let (x0, x1) = (pair[0], pair[1]);+ let a = nearest(x0 - NEAR_HALF);+ if w as f64 <= a {+ break;+ }+ let from = whole(a, w);+ let lead = whole(nearest(x0 + NEAR_HALF).max(from as f64), w);+ let end = whole(nearest(x1 + NEAR_HALF), w);+ let middle = whole(nearest(x1 - NEAR_HALF), end);+ let mut p = from;+ while p < lead {+ let c = (x1.min(p as f64 + 1.0) - x0) * dv + f64::from(row[p]);+ row[p] = to_level(c);+ p += 1;+ }+ while p < middle {+ row[p] = row[p].saturating_add(16);+ p += 1;+ }+ while p < end {+ let c = (x1 - (p as f64).max(x0)) * dv + f64::from(row[p]);+ row[p] = to_level(c);+ p += 1;+ }+ }+}++/// One line of an anti-aliased path.+fn smooth_line(row: &mut [u8], groups: &[Group], l: usize) {+ let line = l as f64;+ let mut seen: Vec<Bands> = Vec::with_capacity(groups.len());+ for g in groups {+ if line > g.base || line + 1.0 < g.top {+ continue;+ }+ let mut b = Bands {+ x: [0.0; 16],+ seen: [false; 16],+ min: f64::INFINITY,+ max: f64::NEG_INFINITY,+ count: 0,+ };+ for k in 0..16 {+ let y0 = line + k as f64 / 16.0;+ if let Some(x) = crossing(g, y0, y0 + 1.0 / 16.0) {+ b.x[k] = x;+ b.seen[k] = true;+ b.count += 1;+ b.min = b.min.min(x);+ b.max = b.max.max(x);+ }+ }+ if b.count > 0 {+ seen.push(b);+ }+ }+ if seen.len() < 2 {+ return;+ }+ seen.sort_by(|a, b| a.min.total_cmp(&b.min));+ let apart = seen.iter().all(|b| b.count == 16) && seen.windows(2).all(|p| p[1].min >= p[0].max);+ if apart {+ fast_line(row, &seen);+ return;+ }+ let mut xs = Vec::with_capacity(seen.len());+ for k in 0..16 {+ xs.clear();+ xs.extend(seen.iter().filter(|b| b.seen[k]).map(|b| b.x[k]));+ if xs.len() > 1 {+ xs.sort_by(f64::total_cmp);+ add_band(row, &xs);+ }+ }+}++/// A recursive Gaussian of the fourth order (Deriche's), forward and back.+struct Gaussian {+ n: [f64; 5],+ d: [f64; 5],+ m: [f64; 5],+ bp: [f64; 5],+ bm: [f64; 5],+}++impl Gaussian {+ /// For a blur reaching `r` pixels, where its tail is a level of 255.+ fn new(r: f64) -> Gaussian {+ let s = (-(r * r) / (2.0 * (1.0f64 / 255.0).ln())).sqrt().max(0.6);+ let k = s * 2.506_628_274_63;+ let (a0, a1) = (f64::from(1.6803f32) / k, f64::from(-0.6803f32) / k);+ let (c0, c1) = (f64::from(3.735f32) / k, f64::from(-0.2598f32) / k);+ let (b0, b1) = (f64::from(-1.783f32) / s, f64::from(-1.723f32) / s);+ let (w0, w1) = (f64::from(0.6318f32) / s, f64::from(1.997f32) / s);+ let (sin0, cos0) = w0.sin_cos();+ let (sin1, cos1) = w1.sin_cos();+ let (e0, e1) = (b0.exp(), b1.exp());+ let both = (b0 + b1).exp();+ let (e00, e11) = ((b0 + b0).exp(), (b1 + b1).exp());+ let f = sin1 * c1;+ let g = sin0 * c0;+ let n = [+ a1 + a0,+ (g - cos0 * (a1 + a1 + a0)) * e0 + (f - cos1 * (a0 + a0 + a1)) * e1,+ (cos1 * (a1 + a0) * cos0 - cos1 * c0 * sin0 - cos0 * c1 * sin1) * (both * 2.0)+ + e00 * a1+ + e11 * a0,+ (f - cos1 * a1) * (b0 + b0 + b1).exp() + (g - cos0 * a0) * (b1 + b1 + b0).exp(),+ 0.0,+ ];+ let d = [+ 0.0,+ (cos1 * e1 + cos0 * e0) * -2.0,+ cos1 * 4.0 * cos0 * both + e11 + e00,+ ((b0 + b0 + b1).exp() * cos1 + (b1 + b1 + b0).exp() * cos0) * -2.0,+ (b0 + b1 + b0 + b1).exp(),+ ];+ let m = [+ 0.0,+ n[1] - n[0] * d[1],+ n[2] - n[0] * d[2],+ n[3] - n[0] * d[3],+ n[4] - n[0] * d[4],+ ];+ let sum: f64 = d.iter().sum::<f64>() + 1.0;+ let (kp, km) = if sum.abs() >= 1e-15 {+ (n.iter().sum::<f64>() / sum, m.iter().sum::<f64>() / sum)+ } else {+ (1.0, 1.0)+ };+ Gaussian {+ n,+ d,+ m,+ bp: d.map(|v| v * kp),+ bm: d.map(|v| v * km),+ }+ }++ /// One line through it: `x(i)` in, `out(i, value)` out; its edges held.+ fn run(+ &self,+ n: usize,+ x: impl Fn(usize) -> f64,+ y: &mut [f64],+ z: &mut [f64],+ mut out: impl FnMut(usize, f64),+ ) {+ if n == 0 {+ return;+ }+ let (first, last) = (x(0), x(n - 1));+ for j in 0..n {+ let (mut p, mut q) = (0.0, 0.0);+ let reach = j.min(5);+ for k in 0..reach {+ p += x(j - k) * self.n[k] - self.d[k] * y[j - k];+ q += x(n - 1 - j + k) * self.m[k] - self.d[k] * z[j - k];+ }+ for k in reach..5 {+ p += (self.n[k] - self.bp[k]) * first;+ q += (self.m[k] - self.bm[k]) * last;+ }+ y[j] = if p.abs() <= 1e-15 { 0.0 } else { p };+ z[j] = if q.abs() <= 1e-15 { 0.0 } else { q };+ }+ for j in 0..n {+ out(j, z[n - 1 - j] + y[j]);+ }+ }+}++/// How a one-way feather bends what its blur leaves, going out of the shape:+/// measured on VEGAS's renders; into it, the same turned round.+#[rustfmt::skip]+const ONE_WAY: [u8; 129] = [+ 0, 1, 3, 6, 9, 12, 16, 20, 24, 29, 33, 38, 42, 47, 52, 56, 61, 66, 71, 75, 80, 84, 89, 93, 98,+ 102, 106, 111, 115, 119, 123, 127, 130, 134, 138, 141, 145, 148, 151, 155, 158, 161, 164, 167,+ 170, 172, 175, 178, 180, 183, 185, 188, 190, 192, 194, 196, 198, 201, 202, 204, 206, 208, 210,+ 211, 213, 214, 216, 217, 219, 220, 222, 223, 224, 225, 227, 228, 229, 230, 231, 232, 233, 234,+ 235, 236, 236, 237, 238, 239, 239, 240, 241, 242, 242, 243, 243, 244, 245, 245, 246, 246, 247,+ 247, 247, 248, 248, 249, 249, 249, 250, 250, 250, 251, 251, 251, 252, 252, 252, 252, 253, 253,+ 253, 253, 253, 254, 254, 254, 254, 254, 255,+];++fn bent_out(v: u8) -> u8 {+ ONE_WAY.get(usize::from(v)).copied().unwrap_or(255)+}++fn bent_in(v: u8) -> u8 {+ 255 - bent_out(255 - v)+}++/// A filled path feathered in place.+fn feather(buf: &mut [u8], w: usize, h: usize, style: MaskFeather, radius: [f64; 2]) {+ let (mut rx, mut ry) = (radius[0].abs(), radius[1].abs());+ let bend: Option<fn(u8) -> u8> = match style {+ MaskFeather::In => Some(bent_in),+ MaskFeather::Out => Some(bent_out),+ _ => None,+ };+ if bend.is_some() {+ rx += rx;+ ry += ry;+ }+ let longest = w.max(h);+ let across = Gaussian::new(rx);+ let mut blurred = vec![0.0f32; w * h];+ bv_color::par_rows(&mut blurred, w, |l, row| {+ let (mut y, mut z) = (vec![0.0; longest], vec![0.0; longest]);+ let line = &buf[l * w..(l + 1) * w];+ across.run(+ w,+ |i| f64::from(line[i]),+ &mut y,+ &mut z,+ |j, v| row[j] = v as f32,+ );+ });+ let down = Gaussian::new(ry);+ let (mut y, mut z) = (vec![0.0; longest], vec![0.0; longest]);+ for c in 0..w {+ down.run(+ h,+ |i| f64::from(blurred[i * w + c]),+ &mut y,+ &mut z,+ |j, v| {+ let q = to_level(v);+ buf[j * w + c] = bend.map_or(q, |b| b(q));+ },+ );+ }+}++/// One path filled into `buf`, zero before.+fn fill_path(+ buf: &mut [u8],+ w: usize,+ h: usize,+ path: &MaskPath,+ scale: [f64; 2],+ radius: [f64; 2],+) {+ let groups = groups_of(&path.anchors, scale);+ let smooth = path.anti_alias;+ bv_color::par_rows(buf, w, |l, row| {+ if smooth {+ smooth_line(row, &groups, l);+ } else {+ let line = l as f64;+ let mut xs: Vec<f64> = groups+ .iter()+ .filter(|g| line <= g.base && line + 1.0 >= g.top)+ .filter_map(|g| crossing(g, line, line + 1.0))+ .collect();+ if xs.len() > 1 {+ xs.sort_by(f64::total_cmp);+ plain_line(row, &xs);+ }+ }+ });+ if path.feather != MaskFeather::None && path.feather_pct > 0.0 {+ feather(buf, w, h, path.feather, radius);+ }+}++/// `paths`, in order, on a picture `w` × `h` of the media, whose pixels are+/// its own times `scale` and `aspect` wide: how much of each pixel they keep,+/// 0–255.+pub(crate) fn alpha(+ paths: &[MaskPath],+ w: usize,+ h: usize,+ scale: [f64; 2],+ aspect: f64,+) -> Vec<u8> {+ let mut out = vec![0u8; w * h];+ let mut first = true;+ let mut scratch = Vec::new();+ let shorter = w.min(h) as f64;+ for path in paths {+ if !path.closed || path.anchors.len() < 2 || path.mode == MaskMode::Disabled {+ continue;+ }+ let negative = path.mode == MaskMode::Negative;+ let opacity = path.opacity;+ if !(opacity > 0.0 || (first && negative)) {+ continue;+ }+ let apart = !first || negative;+ if first && negative {+ out.fill(255);+ }+ if opacity > 0.0 {+ let r = shorter * path.feather_pct / 100.0;+ let radius = if aspect > 1.0 {+ [r / aspect, r]+ } else {+ [r, r * aspect]+ };+ if apart {+ scratch.clear();+ scratch.resize(w * h, 0u8);+ fill_path(&mut scratch, w, h, path, scale, radius);+ let signed = if negative && opacity < 1.0 {+ -opacity+ } else {+ opacity+ };+ for (o, t) in out.iter_mut().zip(&scratch) {+ *o = if opacity >= 1.0 {+ if negative {+ o.saturating_sub(*t)+ } else {+ o.saturating_add(*t)+ }+ } else {+ to_level(f64::from(*t) * signed + f64::from(*o))+ };+ }+ } else {+ fill_path(&mut out, w, h, path, scale, radius);+ if opacity < 1.0 {+ for o in &mut out {+ *o = nearest(f64::from(*o) * opacity + 1.5e-8) as u8;+ }+ }+ }+ }+ first = false;+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_one_way_curves_are_each_others_turned_round() {+ assert_eq!(bent_out(0), 0);+ assert_eq!(bent_out(64), 213);+ assert_eq!(bent_out(128), 255);+ assert_eq!(bent_out(255), 255);+ assert_eq!(bent_in(255), 255);+ assert_eq!(bent_in(254), 254);+ assert_eq!(bent_in(100), 0);+ }++ #[test]+ fn a_rectangle_fills_as_far_as_it_covers() {+ let mut p = MaskPath::rectangle([10.25, 10.0], [30.0, 20.0]);+ let c = alpha(std::slice::from_ref(&p), 40, 30, [1.0, 1.0], 1.0);+ let at = |c: &[u8], x: usize, y: usize| c[y * 40 + x];+ assert_eq!(at(&c, 20, 15), 255);+ assert_eq!(at(&c, 2, 2), 0);+ // 0.75 of a pixel: 191.25.+ assert_eq!(at(&c, 10, 15), 191);+ assert_eq!(at(&c, 9, 15), 0);+ // Without anti-aliasing, whole or nothing.+ p.anti_alias = false;+ let c = alpha(&[p], 40, 30, [1.0, 1.0], 1.0);+ assert_eq!(at(&c, 10, 15), 255);+ assert_eq!(at(&c, 9, 15), 0);+ }++ #[test]+ fn a_gaussian_keeps_a_flat_line_flat() {+ let g = Gaussian::new(10.0);+ let (mut y, mut z) = (vec![0.0; 64], vec![0.0; 64]);+ let mut out = vec![0.0; 64];+ g.run(64, |_| 200.0, &mut y, &mut z, |j, v| out[j] = v);+ for v in out {+ assert!((v - 200.0).abs() < 0.1, "{v}");+ }+ }++ #[test]+ fn a_negative_path_cuts_what_is_inside_it_alone() {+ let mut p = MaskPath::rectangle([10.0, 10.0], [30.0, 20.0]);+ p.mode = MaskMode::Negative;+ let c = alpha(&[p], 40, 30, [1.0, 1.0], 1.0);+ assert_eq!(c[15 * 40 + 20], 0);+ assert_eq!(c[2 * 40 + 2], 255);+ }++ #[test]+ fn paths_add_up_and_take_away() {+ let a = MaskPath::rectangle([0.0, 0.0], [20.0, 30.0]);+ let mut b = MaskPath::rectangle([5.0, 5.0], [15.0, 25.0]);+ b.mode = MaskMode::Negative;+ let c = alpha(&[a.clone(), b], 40, 30, [1.0, 1.0], 1.0);+ assert_eq!(c[15 * 40 + 10], 0, "the hole");+ assert_eq!(c[15 * 40 + 2], 255, "around the hole");+ let d = MaskPath::rectangle([20.0, 0.0], [40.0, 30.0]);+ let c = alpha(&[a, d], 40, 30, [1.0, 1.0], 1.0);+ assert_eq!(c[15 * 40 + 30], 255, "the second one added");+ }++ #[test]+ fn half_an_opacity_is_half_a_level() {+ let mut p = MaskPath::rectangle([0.0, 0.0], [40.0, 30.0]);+ p.opacity = 0.5;+ let c = alpha(&[p], 40, 30, [1.0, 1.0], 1.0);+ // 127.5, its tie to the even number with what the rounding adds.+ assert_eq!(c[0], 128);+ }++ #[test]+ fn a_curve_is_cut_where_it_turns_back() {+ // An oval's two sides: two groups a line.+ let o = MaskPath::oval([0.0, 0.0], [40.0, 30.0]);+ let g = groups_of(&o.anchors, [1.0, 1.0]);+ assert_eq!(g.len(), 2);+ assert_eq!((g[0].top, g[0].base), (0.0, 30.0));+ // Crossing it at its middle line: its sides.+ let xs: Vec<f64> = g.iter().filter_map(|g| crossing(g, 15.0, 15.0)).collect();+ assert_eq!(xs.len(), 2);+ assert!(xs.iter().any(|x| x.abs() < 1e-6) && xs.iter().any(|x| (x - 40.0).abs() < 1e-6));+ }+}diff --git a/crates/timeline/src/model.rs b/crates/timeline/src/model.rsindex ff75843..9d81242 100644--- a/crates/timeline/src/model.rs+++ b/crates/timeline/src/model.rs@@ -2,6 +2,7 @@ use bv_core::{ChannelLayout, FrameRate, SampleRate, Tick, TimeRange};use serde::{Deserialize, Serialize};use crate::fx::{Effect, FadeCurve, PluginFx, Transform, TransformKey, Transition};+use crate::pancrop::{PanCrop, PanCropKey};#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]#[serde(transparent)]@@ -585,11 +586,15 @@ pub struct Clip {/// default: the Pan/Crop first.#[serde(default, skip_serializing_if = "is_zero_usize")]pub pan_crop_at: usize,- #[serde(default)]- pub transform: Transform,- /// Quadros-chave do enquadramento (vazio = `transform` fixo).- #[serde(default)]- pub transform_keys: Vec<TransformKey>,+ /// Its Pan/Crop: which part of its media goes to the frame, over time.+ #[serde(default, skip_serializing_if = "PanCrop::is_unset")]+ pub pan_crop: PanCrop,+ /// The framing a project saved before the Pan/Crop's box had+ /// (`Project::from_json` brings it in).+ #[serde(default, rename = "transform", skip_serializing)]+ pub(crate) old_framing: Option<Transform>,+ #[serde(default, rename = "transform_keys", skip_serializing)]+ pub(crate) old_framing_keys: Vec<TransformKey>,/// Its Pan/Crop masks (the Pan/Crop window's Mask row): shapes on its/// media that cut what shows of it, or keep its effects inside them.#[serde(default, skip_serializing_if = "Option::is_none")]@@ -734,8 +739,9 @@ impl Clip {transition_bypass: false,effects: Vec::new(),pan_crop_at: 0,- transform: Transform::default(),- transform_keys: Vec::new(),+ pan_crop: PanCrop::default(),+ old_framing: None,+ old_framing_keys: Vec::new(),mask: None,muted: false,locked: false,@@ -905,9 +911,10 @@ impl Clip {}}- /// Enquadramento no instante `t` da timeline (com quadros-chave).- pub fn transform_at(&self, t: Tick) -> Transform {- crate::fx::transform_at(&self.transform_keys, &self.transform, t - self.start)+ /// Its Pan/Crop's box at `t` on the timeline, in a media of `media`+ /// pixels `aspect` wide.+ pub fn box_at(&self, t: Tick, media: [f64; 2], aspect: f64) -> PanCropKey {+ self.pan_crop.at_time(t, self.start, media, aspect)}/// How many times higher its sound plays: its pitch change, and its@@ -2620,9 +2627,50 @@ impl Project {p.upgrade_notes();p.upgrade_plugin_fx();p.upgrade_fade_outs();+ p.upgrade_pan_crops();Ok(p)}+ /// Events saved before the Pan/Crop's box: the box each framing shows.+ fn upgrade_pan_crops(&mut self) {+ let Project {+ tracks,+ media,+ settings,+ ..+ } = self;+ for c in tracks.iter_mut().flat_map(|t| t.clips.iter_mut()) {+ let framing = c.old_framing.take();+ let keys = std::mem::take(&mut c.old_framing_keys);+ let Some(info) = media.iter().find(|m| m.id == c.media) else {+ continue;+ };+ let mut place = crate::pancrop::place_in(settings, info, true, true);+ let framing = framing.unwrap_or_default();+ if keys.is_empty() && framing == Transform::default() {+ continue;+ }+ place.keep_aspect = keys.first().map_or(&framing, |k| &k.value).keeps_aspect();+ place.fill = keys.first().map_or(&framing, |k| &k.value).fill_frame;+ let key = |k: &TransformKey| PanCropKey {+ at: k.at,+ curve: k.curve,+ smoothness: f64::from(k.smoothness / 100.0),+ ..crate::pancrop::key_from_transform(&k.value, &place)+ };+ c.pan_crop = PanCrop {+ size: [place.media[0] as u32, place.media[1] as u32],+ keep_aspect: place.keep_aspect,+ fill: place.fill,+ keys: if keys.is_empty() {+ vec![crate::pancrop::key_from_transform(&framing, &place)]+ } else {+ keys.iter().map(key).collect()+ },+ };+ }+ }+/// Projects saved before format 2 named a fade-out by its fade-in/// turned around in time; VEGAS, and BananaV since, by how it begins:/// their Fast and Slow swap, so each keeps its shape.diff --git a/crates/timeline/src/pancrop.rs b/crates/timeline/src/pancrop.rsnew file mode 100644index 0000000..2e5249a--- /dev/null+++ b/crates/timeline/src/pancrop.rs@@ -0,0 +1,1733 @@+//! An event's Pan/Crop, as VEGAS's: a box over its media — its size, its+//! middle, its angle and where it turns, all in the media's pixels, keyframed+//! with a curve and a smoothness — that says which part of the media goes to+//! the frame. The smaller the box, the larger that part shows; a width or+//! height below zero mirrors it. Maintain aspect ratio and Stretch to fill+//! frame say where it lands ([`place`]).+//!+//! Without a turn or a mirror a rectangle of the media goes to a rectangle+//! of the frame, its edges hard; turned or mirrored, a parallelogram, its+//! edges as soft as the pixels they cross.++use bv_core::{TICKS_PER_SECOND, Tick};+use serde::{Deserialize, Serialize};++use crate::fx::{KeyCurve, Transform};++/// The box at a keyframe, times from the event's start.+#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]+pub struct PanCropKey {+ pub at: Tick,+ /// How it goes to the next keyframe.+ #[serde(default)]+ pub curve: KeyCurve,+ /// Its size, in the media's pixels; negative: mirrored.+ pub width: f64,+ pub height: f64,+ /// Its middle.+ pub center: [f64; 2],+ /// Its turn, in radians.+ #[serde(default)]+ pub angle: f64,+ /// Where it turns.+ pub pivot: [f64; 2],+ /// How much the way of the pivot curves through this keyframe, 0–1 (0:+ /// straight lines between keyframes).+ #[serde(default)]+ pub smoothness: f64,+ /// What the Properties panel's crop sliders take off the media: its+ /// left, right, top and bottom, as parts of its size.+ #[serde(default, skip_serializing_if = "no_crop")]+ pub crop: [f32; 4],+}++fn no_crop(c: &[f32; 4]) -> bool {+ *c == [0.0; 4]+}++fn yes() -> bool {+ true+}++fn is_yes(v: &bool) -> bool {+ *v+}++/// An event's Pan/Crop.+#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]+pub struct PanCrop {+ /// The media's size its keyframes count in: another size when it opens+ /// (or another take shows), they are scaled to it.+ #[serde(default)]+ pub size: [u32; 2],+ /// Maintain aspect ratio: what shows keeps its proportions in the frame+ /// (off: stretched to it).+ #[serde(default = "yes", skip_serializing_if = "is_yes")]+ pub keep_aspect: bool,+ /// Stretch to fill frame: the box becomes the frame (off: the picture+ /// stays where it is, the box only crops it).+ #[serde(default = "yes", skip_serializing_if = "is_yes")]+ pub fill: bool,+ /// In time order; none: the whole media all along.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub keys: Vec<PanCropKey>,+}++impl Default for PanCrop {+ fn default() -> PanCrop {+ PanCrop {+ size: [0; 2],+ keep_aspect: true,+ fill: true,+ keys: Vec::new(),+ }+ }+}++/// 100 ns steps in a second: the unit the box's times are worked out in, a+/// frame's time cut down to it.+const UNITS: i128 = 10_000_000;++pub(crate) fn units_floor(t: Tick) -> i64 {+ (t.0 as i128 * UNITS).div_euclid(TICKS_PER_SECOND as i128) as i64+}++pub(crate) fn units_near(t: Tick) -> i64 {+ let d = TICKS_PER_SECOND as i128;+ ((t.0 as i128 * UNITS + d / 2).div_euclid(d)) as i64+}++/// A time from the event's start in the box's unit.+pub fn local_units(t: Tick) -> i64 {+ units_floor(t)+}++/// A keyframe curve's shape at `u` (0–1 of the way to the next keyframe).+pub fn ease(curve: KeyCurve, u: f64) -> f64 {+ match curve {+ KeyCurve::Hold => {+ if u < 1.0 {+ 0.0+ } else {+ 1.0+ }+ }+ KeyCurve::Slow => u * u,+ KeyCurve::Fast => 1.0 - (1.0 - u) * (1.0 - u),+ KeyCurve::Smooth => u * u * (3.0 - 2.0 * u),+ KeyCurve::Sharp => u * (u * (4.0 * u - 6.0) + 3.0),+ KeyCurve::Linear | KeyCurve::Bezier | KeyCurve::BezierSplit => u,+ }+}++fn lerp(a: f64, b: f64, u: f64) -> f64 {+ a + (b - a) * u+}++/// `a`'s cosine and sine, near 0 and ±1 exactly those.+fn cos_sin(a: f64) -> (f64, f64) {+ let (s, c) = a.sin_cos();+ if c.abs() < 1e-6 {+ (0.0, if s >= 0.0 { 1.0 } else { -1.0 })+ } else if s.abs() < 1e-6 {+ (if c >= 0.0 { 1.0 } else { -1.0 }, 0.0)+ } else {+ (c, s)+ }+}++/// The corners of a box: top left, top right, bottom right, bottom left.+pub type Corners = [[f64; 2]; 4];++impl PanCropKey {+ /// The box over all of a media of size `media`.+ pub fn whole(media: [f64; 2]) -> PanCropKey {+ PanCropKey {+ at: Tick::ZERO,+ curve: KeyCurve::Linear,+ width: media[0],+ height: media[1],+ center: [media[0] / 2.0, media[1] / 2.0],+ angle: 0.0,+ pivot: [media[0] / 2.0, media[1] / 2.0],+ smoothness: 0.0,+ crop: [0.0; 4],+ }+ }++ /// Whether it is the box [`Self::whole`] makes, wherever it is in time.+ pub fn is_whole(&self, media: [f64; 2]) -> bool {+ let w = PanCropKey::whole(media);+ self.width == w.width+ && self.height == w.height+ && self.center == w.center+ && self.angle == 0.0+ && self.pivot == w.pivot+ && no_crop(&self.crop)+ }++ /// Its corners.+ pub fn corners(&self) -> Corners {+ let (c, s) = cos_sin(self.angle);+ let (c, s) = (c / 2.0, s / 2.0);+ let [x, y] = self.center;+ let (w, h) = (self.width, self.height);+ [+ [x - (w * c - h * s), y - (w * s + h * c)],+ [x + (w * c + h * s), y + (w * s - h * c)],+ [x + (w * c - h * s), y + (w * s + h * c)],+ [x - (w * c + h * s), y - (w * s - h * c)],+ ]+ }++ /// Turned `by` radians more about its pivot.+ pub fn turned(&self, by: f64) -> PanCropKey {+ let (c, s) = cos_sin(by);+ let (dx, dy) = (+ self.center[0] - self.pivot[0],+ self.center[1] - self.pivot[1],+ );+ PanCropKey {+ angle: self.angle + by,+ center: [+ dx * c - dy * s + self.pivot[0],+ dy * c + dx * s + self.pivot[1],+ ],+ ..*self+ }+ }++ /// Moved, its pivot with it.+ pub fn moved(&self, by: [f64; 2]) -> PanCropKey {+ PanCropKey {+ center: [self.center[0] + by[0], self.center[1] + by[1]],+ pivot: [self.pivot[0] + by[0], self.pivot[1] + by[1]],+ ..*self+ }+ }++ /// Its size and its middle's distance from its pivot scaled.+ pub fn scaled(&self, by: [f64; 2]) -> PanCropKey {+ PanCropKey {+ width: self.width * by[0],+ height: self.height * by[1],+ center: [+ (self.center[0] - self.pivot[0]) * by[0] + self.pivot[0],+ (self.center[1] - self.pivot[1]) * by[1] + self.pivot[1],+ ],+ ..*self+ }+ }++ /// The menu's Center: moved so that its pivot is the media's middle.+ pub fn centered(&self, media: [f64; 2]) -> PanCropKey {+ self.moved([+ media[0] / 2.0 - self.pivot[0],+ media[1] / 2.0 - self.pivot[1],+ ])+ }++ /// The menu's Flip Horizontal: mirrored about its pivot, its turn+ /// mirrored too.+ pub fn flipped_h(&self) -> PanCropKey {+ PanCropKey {+ width: -self.width,+ center: [2.0 * self.pivot[0] - self.center[0], self.center[1]],+ angle: reflected(self.angle),+ ..*self+ }+ }++ /// The menu's Flip Vertical.+ pub fn flipped_v(&self) -> PanCropKey {+ PanCropKey {+ height: -self.height,+ center: [self.center[0], 2.0 * self.pivot[1] - self.center[1]],+ angle: reflected(self.angle),+ ..*self+ }+ }++ /// The menu's Match Output Aspect and Match Source Aspect: the shape+ /// `ratio` (width over height), as large as fits what it was; signs kept.+ pub fn matched(&self, ratio: f64) -> PanCropKey {+ let (w, h) = (self.width.abs(), self.height.abs());+ let (nw, nh) = if w < h * ratio {+ (w, w / ratio)+ } else {+ (h * ratio, h)+ };+ PanCropKey {+ width: nw.copysign(self.width),+ height: nh.copysign(self.height),+ ..*self+ }+ }++ /// The same box in a media of `to` pixels instead of `from`.+ fn rescaled(&self, from: [f64; 2], to: [f64; 2]) -> PanCropKey {+ let (x, y) = (to[0] / from[0], to[1] / from[1]);+ PanCropKey {+ width: self.width * x,+ height: self.height * y,+ center: [self.center[0] * x, self.center[1] * y],+ pivot: [self.pivot[0] * x, self.pivot[1] * y],+ ..*self+ }+ }+}++/// A turn as a mirror leaves it.+fn reflected(a: f64) -> f64 {+ use std::f64::consts::{FRAC_PI_2, PI, TAU};+ let m = a.abs();+ let mut k = (m / TAU).round() * TAU;+ let rest = m - k;+ if rest > FRAC_PI_2 {+ k += if rest > 3.0 * FRAC_PI_2 { TAU } else { PI };+ }+ (k - (m - k)) * if a < 0.0 { -1.0 } else { 1.0 }+}++/// A point of the pivot's way: when, where, how smooth.+#[derive(Clone, Copy)]+struct WayPoint {+ t: f64,+ at: [f64; 2],+ tension: f64,+}++/// A handle of the way through `p1`, from what comes before and after it.+fn handle(p0: &WayPoint, p1: &WayPoint, p2: &WayPoint) -> [f64; 2] {+ let d1 = (p1.at[0] - p0.at[0]).hypot(p1.at[1] - p0.at[1]);+ let d2 = (p2.at[0] - p1.at[0]).hypot(p2.at[1] - p1.at[1]);+ if d1 == 0.0 && d2 == 0.0 {+ return p1.at;+ }+ const K: f64 = 0.5;+ let (fa, fb) = if d2 <= d1 {+ ((d2 / d1) * K + 1.0, K)+ } else {+ (K + 1.0, (d1 / d2) * K)+ };+ [0, 1].map(|i| {+ let a = p0.at[i] + (p1.at[i] - p0.at[i]) * fa;+ let b = p1.at[i] + (p2.at[i] - p1.at[i]) * fb;+ (a + b) * 0.5+ })+}++/// A handle pulled toward a third of the straight way, as little as its+/// tension is high.+fn tensed(handle: [f64; 2], from: &WayPoint, to: &WayPoint) -> [f64; 2] {+ if from.tension >= 1.0 {+ return handle;+ }+ [0, 1].map(|i| {+ let line = from.at[i] + (to.at[i] - from.at[i]) / 3.0;+ line + (handle[i] - line) * from.tension+ })+}++/// The pivot's way at `u` between keyframes `i` and `i + 1` of `points`.+fn way_at(points: &[WayPoint], i: usize, u: f64) -> [f64; 2] {+ let last = points.len() - 1;+ let p0 = &points[i.saturating_sub(1)];+ let p1 = &points[i];+ let p2 = &points[(i + 1).min(last)];+ let p3 = &points[(i + 2).min(last)];+ let c1 = tensed(handle(p0, p1, p2), p1, p2);+ let c2 = tensed(handle(p3, p2, p1), p2, p1);+ [0, 1].map(|k| {+ let ab = lerp(p1.at[k], c1[k], u);+ let bc = lerp(c1[k], c2[k], u);+ let cd = lerp(c2[k], p2.at[k], u);+ lerp(lerp(ab, bc, u), lerp(bc, cd, u), u)+ })+}++impl PanCrop {+ /// Whether it has nothing to save: as a new event's.+ pub fn is_unset(&self) -> bool {+ self.keys.is_empty() && self.keep_aspect && self.fill+ }++ /// A Pan/Crop that holds `key` all along.+ pub fn holding(key: PanCropKey, media: [f64; 2], keep_aspect: bool, fill: bool) -> PanCrop {+ PanCrop {+ size: [media[0] as u32, media[1] as u32],+ keep_aspect,+ fill,+ keys: vec![PanCropKey {+ at: Tick::ZERO,+ ..key+ }],+ }+ }++ /// Whether it changes nothing: the whole media all along, as usual.+ pub fn is_default(&self) -> bool {+ self.fill+ && self.keep_aspect+ && match self.keys.as_slice() {+ [] => true,+ [k] => k.at == Tick::ZERO && k.is_whole([self.size[0] as f64, self.size[1] as f64]),+ _ => false,+ }+ }++ /// The media's size its keyframes count in.+ pub fn own_size(&self) -> [f64; 2] {+ [+ f64::from(self.size[0].max(1)),+ f64::from(self.size[1].max(1)),+ ]+ }++ /// Its keyframes in a media of size `media`.+ fn keys_in(&self, media: [f64; 2]) -> std::borrow::Cow<'_, [PanCropKey]> {+ let from = [f64::from(self.size[0]), f64::from(self.size[1])];+ if from[0] <= 0.0 || from[1] <= 0.0 || from == media {+ std::borrow::Cow::Borrowed(&self.keys)+ } else {+ std::borrow::Cow::Owned(self.keys.iter().map(|k| k.rescaled(from, media)).collect())+ }+ }++ /// The box `local` after the event's start: as far between its+ /// keyframes as their curve says, turned back to no angle while it+ /// goes and on again to the angle there, its pivot on the spline+ /// through theirs (`aspect`: how wide the media's pixels are, as the+ /// box turns in real proportions).+ pub fn at(&self, local: Tick, media: [f64; 2], aspect: f64) -> PanCropKey {+ self.at_units(units_floor(local), media, aspect)+ }++ /// [`Self::at`] at timeline time `t` of an event starting at `start`:+ /// the frame's time cut down to the box's unit, as the box is worked+ /// out.+ pub fn at_time(&self, t: Tick, start: Tick, media: [f64; 2], aspect: f64) -> PanCropKey {+ self.at_units(units_floor(t) - units_near(start), media, aspect)+ }++ fn at_units(&self, t: i64, media: [f64; 2], aspect: f64) -> PanCropKey {+ let keys = self.keys_in(media);+ let keys: &[PanCropKey] = &keys;+ let Some(first) = keys.first() else {+ return PanCropKey::whole(media);+ };+ let when = |k: &PanCropKey| units_near(k.at);+ let i = keys.partition_point(|k| when(k) <= t);+ if i == 0 {+ return PanCropKey {+ at: Tick::ZERO,+ ..*first+ };+ }+ let a = &keys[i - 1];+ if when(a) == t || i == keys.len() {+ return *a;+ }+ let b = &keys[i];+ let wide = aspect != 0.0 && aspect != 1.0;+ let in_wide = |k: &PanCropKey| {+ if wide {+ PanCropKey {+ width: k.width * aspect,+ center: [k.center[0] * aspect, k.center[1]],+ pivot: [k.pivot[0] * aspect, k.pivot[1]],+ ..*k+ }+ } else {+ *k+ }+ };+ let (ka, kb) = (in_wide(a), in_wide(b));+ let span = (when(b) - when(a)) as f64;+ let u = if span > 0.0 {+ ease(a.curve, (t - when(a)) as f64 / span)+ } else {+ 0.0+ };+ let (flat_a, flat_b) = (ka.turned(-ka.angle), kb.turned(-kb.angle));+ let mut now = PanCropKey {+ at: a.at,+ curve: a.curve,+ width: lerp(ka.width, kb.width, u),+ height: lerp(ka.height, kb.height, u),+ center: [+ lerp(flat_a.center[0], flat_b.center[0], u),+ lerp(flat_a.center[1], flat_b.center[1], u),+ ],+ angle: 0.0,+ pivot: [+ lerp(ka.pivot[0], kb.pivot[0], u),+ lerp(ka.pivot[1], kb.pivot[1], u),+ ],+ smoothness: lerp(ka.smoothness, kb.smoothness, u),+ crop: std::array::from_fn(|c| {+ lerp(f64::from(a.crop[c]), f64::from(b.crop[c]), u) as f32+ }),+ };+ now = now.turned(lerp(ka.angle, kb.angle, u));+ // The pivot on its spline, the box staying where it is from it.+ let points: Vec<WayPoint> = keys+ .iter()+ .map(|k| {+ let k = in_wide(k);+ WayPoint {+ t: when(&k) as f64,+ at: k.pivot,+ tension: k.smoothness,+ }+ })+ .collect();+ let way = way_at(&points, i - 1, u);+ debug_assert!(points[i - 1].t <= points[i].t);+ now.center = [+ now.center[0] + way[0] - now.pivot[0],+ now.center[1] + way[1] - now.pivot[1],+ ];+ now.pivot = way;+ if wide {+ now.width /= aspect;+ now.center[0] /= aspect;+ now.pivot[0] /= aspect;+ }+ now+ }++ /// The box at `at` (from the event's start) becomes `value`: without+ /// keyframes, at the start, what it holds all along; elsewhere the+ /// animation starts (a keyframe at the start with the box there, and+ /// this one); with keyframes, the one at `at`, made when there is none,+ /// with the curve of the one before. New keyframes get `new`, their+ /// curve when they are the first and their smoothness.+ pub fn set_at(&mut self, at: Tick, value: PanCropKey, media: [f64; 2], new: (KeyCurve, f64)) {+ self.ensure_size(media);+ let (curve, smoothness) = new;+ if self.keys.is_empty() {+ if at == Tick::ZERO {+ self.keys.push(PanCropKey {+ at,+ curve,+ smoothness,+ ..value+ });+ return;+ }+ self.keys.push(PanCropKey {+ curve,+ smoothness,+ ..PanCropKey::whole(media)+ });+ }+ match self.keys.iter_mut().find(|k| k.at == at) {+ Some(k) => {+ *k = PanCropKey {+ at,+ curve: k.curve,+ smoothness: k.smoothness,+ ..value+ };+ }+ None => {+ let before = self+ .keys+ .iter()+ .rev()+ .find(|k| k.at < at)+ .map_or(curve, |k| k.curve);+ let i = self.keys.partition_point(|k| k.at < at);+ self.keys.insert(+ i,+ PanCropKey {+ at,+ curve: before,+ smoothness,+ ..value+ },+ );+ }+ }+ }++ /// The keyframe at `at` gone; the last one left holds all along.+ pub fn remove_key(&mut self, at: Tick) {+ self.keys.retain(|k| k.at != at);+ if let [only] = self.keys.as_mut_slice() {+ only.at = Tick::ZERO;+ }+ }++ /// Records the media's size its keyframes count in, scaling them from+ /// another one they counted in.+ pub fn ensure_size(&mut self, media: [f64; 2]) {+ let keys = self.keys_in(media).into_owned();+ self.keys = keys;+ self.size = [media[0] as u32, media[1] as u32];+ }++ /// The event's start moved `delta` later in it: the box there is the+ /// first keyframe's, the later ones `delta` earlier.+ pub fn rebase(&mut self, delta: Tick, media: [f64; 2], aspect: f64) {+ if self.keys.is_empty() {+ return;+ }+ let before = self.keys.iter().rev().find(|k| k.at <= delta).copied();+ let first = PanCropKey {+ at: Tick::ZERO,+ curve: before.map_or(KeyCurve::Linear, |k| k.curve),+ ..self.at(delta, media, aspect)+ };+ let mut keys: Vec<PanCropKey> = self+ .keys+ .iter()+ .filter(|k| k.at > delta)+ .map(|k| PanCropKey {+ at: k.at - delta,+ ..*k+ })+ .collect();+ keys.insert(0, first);+ self.keys = keys;+ }++ /// The event cut at `cut` (from its start): this one keeps what is+ /// before (a keyframe at the cut ending it), the other half starts with+ /// the box at the cut.+ pub fn split_at(&mut self, cut: Tick, media: [f64; 2], aspect: f64) -> PanCrop {+ let mut right = self.clone();+ right.rebase(cut, media, aspect);+ if !self.keys.is_empty() {+ let there = self.at(cut, media, aspect);+ self.keys.retain(|k| k.at < cut);+ self.keys.push(PanCropKey {+ at: cut,+ curve: KeyCurve::Linear,+ ..there+ });+ }+ right+ }++ /// `next` follows this one, `offset` after its start (joining an event+ /// back after a cut).+ pub fn joined(&mut self, next: &PanCrop, offset: Tick, media: [f64; 2]) {+ if self.keys.is_empty() && next.keys.is_empty() {+ return;+ }+ if self.keys.is_empty() {+ self.keys.push(PanCropKey::whole(media));+ }+ let tail = if next.keys.is_empty() {+ vec![PanCropKey::whole(media)]+ } else {+ next.keys_in(media).into_owned()+ };+ // The keyframe a cut left at its end gives way to the next one's+ // first.+ self.keys.retain(|k| k.at < offset);+ self.keys.extend(tail.into_iter().map(|k| PanCropKey {+ at: k.at + offset,+ ..k+ }));+ }+}++/// What a box's place depends on besides itself.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct PlaceIn {+ /// The media's size, and how wide its pixels are.+ pub media: [f64; 2],+ pub media_aspect: f64,+ /// The project's frame, and how wide its pixels are.+ pub frame: [f64; 2],+ pub frame_aspect: f64,+ pub keep_aspect: bool,+ pub fill: bool,+ /// How much a project's Adjust source media enlarges the picture.+ pub adjust: f64,+}++/// What an event of media `info` lands on in a project of `settings`.+pub fn place_in(+ settings: &crate::model::ProjectSettings,+ info: &crate::model::MediaInfo,+ keep_aspect: bool,+ fill: bool,+) -> PlaceIn {+ let frame = [f64::from(settings.width), f64::from(settings.height)];+ let (media, media_aspect) = info.video.map_or((frame, 1.0), |v| {+ (+ [f64::from(v.width), f64::from(v.height)],+ f64::from(v.pixel_aspect.ratio()),+ )+ });+ let frame_aspect = f64::from(settings.pixel_aspect.ratio());+ let adjust = match info.video {+ Some(v) if settings.adjust_source => f64::from(crate::scene::adjust_factor(+ v.width,+ v.height,+ v.pixel_aspect.ratio() / settings.pixel_aspect.ratio(),+ settings.width,+ settings.height,+ )),+ _ => 1.0,+ };+ PlaceIn {+ media,+ media_aspect,+ frame,+ frame_aspect,+ keep_aspect,+ fill,+ adjust,+ }+}++impl PlaceIn {+ /// Where event `clip`'s picture lands at `t` on the timeline, on a frame+ /// of `size` pixels.+ pub fn at(&self, clip: &crate::model::Clip, t: Tick, size: [f64; 2]) -> Placement {+ let key = clip.box_at(t, self.media, self.media_aspect);+ place(&key, self).on_frame(self.frame, size)+ }+}++/// Where a picture of the media lands on a frame.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Placement {+ /// From a point of the frame (pixels from its top left corner) to the+ /// media's: `[ux, uy, u0, vx, vy, v0]`.+ pub to_media: [f64; 6],+ /// What it may reach of the frame: left, top, right, bottom. A pixel+ /// outside goes, whole.+ pub clip: [f64; 4],+ /// Turned or mirrored: from a point of the frame to the box's own place+ /// (0–1 each way), as `to_media`. Its edges are as soft as the pixels+ /// they cross.+ pub to_box: Option<[f64; 6]>,+ /// The part of the media it shows: left, top, right, bottom.+ pub limits: [f64; 4],+ /// The size `to_media` and `limits` count in.+ pub media: [f64; 2],+ /// Without a turn or a mirror: the rectangle of the media and the one of+ /// the frame it goes to, each left, top, right, bottom.+ pub rect: Option<([f64; 4], [f64; 4])>,+ /// Nothing of it shows.+ pub empty: bool,+}++/// `v` in fixed point, the box's way through a rectangle's numbers.+const FIXED: f64 = 16384.0;++fn fixed(v: f64) -> f64 {+ (v * FIXED).trunc()+}++/// Where its box lands: the rectangle path, or the parallelogram's when it is+/// turned or mirrored.+pub fn place(key: &PanCropKey, s: &PlaceIn) -> Placement {+ let par = if s.media_aspect > 0.0 {+ s.media_aspect+ } else {+ 1.0+ };+ let adjusted;+ let key = if s.adjust != 1.0 && s.adjust > 0.0 {+ adjusted = PanCropKey {+ width: key.width / s.adjust,+ height: key.height / s.adjust,+ ..*key+ };+ &adjusted+ } else {+ key+ };+ let corners = if par == 1.0 || key.angle == 0.0 {+ key.corners()+ } else {+ let mut c = PanCropKey {+ width: key.width * par,+ center: [key.center[0] * par, key.center[1]],+ pivot: [key.pivot[0] * par, key.pivot[1]],+ ..*key+ }+ .corners();+ for p in &mut c {+ p[0] /= par;+ }+ c+ };+ let [tl, tr, _, bl] = corners;+ if key.angle.abs() <= 1e-8 && tl[0] < tr[0] && tl[1] < bl[1] {+ rectangle(&corners, key, s, par)+ } else {+ parallelogram(&corners, key, s, par)+ }+}++fn limits_of(key: &PanCropKey, media: [f64; 2]) -> [f64; 4] {+ let [l, r, t, b] = key.crop.map(|c| f64::from(c.clamp(0.0, 1.0)));+ [+ l * media[0],+ t * media[1],+ (1.0 - r) * media[0],+ (1.0 - b) * media[1],+ ]+}++fn nothing(s: &PlaceIn) -> Placement {+ Placement {+ to_media: [0.0; 6],+ clip: [0.0; 4],+ to_box: None,+ limits: [0.0; 4],+ media: s.media,+ rect: None,+ empty: true,+ }+}++/// How much of a frame `w` × `h` a `width` × `height` picture of pixels+/// `ratio` times as wide takes, kept in shape: its width and height there.+fn fitted(width: f64, height: f64, ratio: f64, w: f64, h: f64) -> (f64, f64) {+ let wide = ratio * width;+ let shape = wide / height;+ if h / height <= w / wide {+ (shape * h, h)+ } else {+ (w, w / shape)+ }+}++fn rectangle(corners: &Corners, key: &PanCropKey, s: &PlaceIn, par: f64) -> Placement {+ let [w, h] = s.media;+ let [ow, oh] = s.frame;+ let ratio = par / s.frame_aspect;+ let xs = corners.map(|c| c[0]);+ let ys = corners.map(|c| c[1]);+ let min = |v: [f64; 4]| v.into_iter().fold(f64::INFINITY, f64::min);+ let max = |v: [f64; 4]| v.into_iter().fold(f64::NEG_INFINITY, f64::max);+ // The media's rectangle, the frame's it goes to and what it may reach,+ // all in fixed point.+ let from = [+ fixed(min(xs)),+ fixed(min(ys)),+ fixed(max(xs)),+ fixed(max(ys)),+ ];+ let frame = [0.0, 0.0, ow * FIXED, oh * FIXED];+ let (mut to, clip);+ if !s.keep_aspect {+ if s.fill {+ to = frame;+ clip = frame;+ } else {+ to = [+ (from[0] * (ow / w)).trunc(),+ (from[1] * (oh / h)).trunc(),+ (from[2] * (ow / w)).trunc(),+ (from[3] * (oh / h)).trunc(),+ ];+ clip = frame;+ }+ } else if s.fill {+ // The box fitted in the frame, in its middle.+ let (bw, bh) = ((from[2] - from[0]) / FIXED, (from[3] - from[1]) / FIXED);+ let (fw, fh) = fitted(bw, bh, ratio, ow, oh);+ to = [+ fixed((ow - fw) * 0.5),+ fixed((oh - fh) * 0.5),+ fixed((ow + fw) * 0.5),+ fixed((oh + fh) * 0.5),+ ];+ clip = to;+ } else {+ // The whole media fitted in the frame, the box where it is in it.+ let (fw, fh) = fitted(w, h, ratio, ow, oh);+ let (ox, oy) = ((ow - fw) * 0.5, (oh - fh) * 0.5);+ to = [+ fixed(from[0] * (fw / w) / FIXED + ox),+ fixed(from[1] * (fh / h) / FIXED + oy),+ fixed(from[2] * (fw / w) / FIXED + ox),+ fixed(from[3] * (fh / h) / FIXED + oy),+ ];+ clip = [fixed(ox), fixed(oy), fixed(ox + fw), fixed(oy + fh)];+ }+ // What of the box is off the media leaves it, and as much of the frame's.+ let limits = limits_of(key, s.media);+ let cut = [+ from[0].max((limits[0] * FIXED).ceil()),+ from[1].max((limits[1] * FIXED).ceil()),+ from[2].min((limits[2] * FIXED).floor()),+ from[3].min((limits[3] * FIXED).floor()),+ ];+ if cut != from {+ let ex = (to[2] - to[0]) / (from[2] - from[0]);+ let ey = (to[3] - to[1]) / (from[3] - from[1]);+ to = [+ (to[0] - (from[0] - cut[0]) * ex).trunc(),+ (to[1] - (from[1] - cut[1]) * ey).trunc(),+ (to[2] - (from[2] - cut[2]) * ex).trunc(),+ (to[3] - (from[3] - cut[3]) * ey).trunc(),+ ];+ }+ if to[2] <= to[0] || to[3] <= to[1] || cut[2] <= cut[0] || cut[3] <= cut[1] {+ return nothing(s);+ }+ let ex = (cut[2] - cut[0]) / (to[2] - to[0]);+ let ey = (cut[3] - cut[1]) / (to[3] - to[1]);+ Placement {+ to_media: [+ ex,+ 0.0,+ (cut[0] - to[0] * ex) / FIXED,+ 0.0,+ ey,+ (cut[1] - to[1] * ey) / FIXED,+ ],+ clip: [+ clip[0].max(to[0]) / FIXED,+ clip[1].max(to[1]) / FIXED,+ clip[2].min(to[2]) / FIXED,+ clip[3].min(to[3]) / FIXED,+ ],+ to_box: None,+ limits,+ media: s.media,+ rect: Some((cut.map(|v| v / FIXED), to.map(|v| v / FIXED))),+ empty: false,+ }+}++fn parallelogram(corners: &Corners, key: &PanCropKey, s: &PlaceIn, par: f64) -> Placement {+ let [w, h] = s.media;+ let [ow, oh] = s.frame;+ let ratio = par / s.frame_aspect;+ let map =+ |sx: f64, sy: f64, ox: f64, oy: f64| corners.map(|c| [c[0] * sx + ox, c[1] * sy + oy]);+ let (to, clip): (Corners, [f64; 4]) = match (s.keep_aspect, s.fill) {+ (false, true) => (+ [[0.0, 0.0], [ow, 0.0], [ow, oh], [0.0, oh]],+ [0.0, 0.0, ow, oh],+ ),+ // The picture stays still; only what crops it turns.+ (false, false) => (map(ow / w, oh / h, 0.0, 0.0), [0.0, 0.0, ow, oh]),+ (true, false) => {+ let (fw, fh) = fitted(w, h, ratio, ow, oh);+ let (ox, oy) = ((ow - fw) * 0.5, (oh - fh) * 0.5);+ (map(fw / w, fh / h, ox, oy), [ox, oy, ox + fw, oy + fh])+ }+ (true, true) => {+ let [tl, tr, _, bl] = *corners;+ let side = (((tl[0] - tr[0]) * par).hypot(tl[1] - tr[1])) / s.frame_aspect;+ let down = ((tl[0] - bl[0]) * par).hypot(tl[1] - bl[1]);+ if side < 1e-6 || down < 1e-6 {+ return nothing(s);+ }+ let (fx, fy) = (ow / side, oh / down);+ let (mut x0, mut x1, mut y0, mut y1) = (0.0, ow, 0.0, oh);+ if fy <= fx {+ let m = (fy / fx) * (ow * 0.5);+ (x0, x1) = (ow * 0.5 - m, ow * 0.5 + m);+ } else {+ let m = (fx / fy) * (oh * 0.5);+ (y0, y1) = (oh * 0.5 - m, oh * 0.5 + m);+ }+ ([[x0, y0], [x1, y0], [x1, y1], [x0, y1]], [x0, y0, x1, y1])+ }+ };+ let [q, qr, _, ql] = to;+ let (ux, uy) = (qr[0] - q[0], qr[1] - q[1]);+ let (vx, vy) = (ql[0] - q[0], ql[1] - q[1]);+ let det = ux * vy - uy * vx;+ if det.abs() < 1e-9 {+ return nothing(s);+ }+ // From the frame to the box's own place...+ let (ax, ay) = (vy / det, -vx / det);+ let (bx, by) = (-uy / det, ux / det);+ let a0 = -(ax * q[0] + ay * q[1]);+ let b0 = -(bx * q[0] + by * q[1]);+ // ...and on to the media.+ let [tl, tr, _, bl] = *corners;+ let (sx, sy) = (tr[0] - tl[0], tr[1] - tl[1]);+ let (dx, dy) = (bl[0] - tl[0], bl[1] - tl[1]);+ Placement {+ to_media: [+ sx * ax + dx * bx,+ sx * ay + dx * by,+ tl[0] + sx * a0 + dx * b0,+ sy * ax + dy * bx,+ sy * ay + dy * by,+ tl[1] + sy * a0 + dy * b0,+ ],+ clip,+ to_box: Some([ax, ay, a0, bx, by, b0]),+ limits: limits_of(key, s.media),+ media: s.media,+ rect: None,+ empty: false,+ }+}++impl Placement {+ /// The same place on a frame of `size` pixels instead of `from`.+ pub fn on_frame(&self, from: [f64; 2], size: [f64; 2]) -> Placement {+ let (x, y) = (from[0] / size[0], from[1] / size[1]);+ let scale = |m: [f64; 6]| [m[0] * x, m[1] * y, m[2], m[3] * x, m[4] * y, m[5]];+ Placement {+ to_media: scale(self.to_media),+ clip: [+ self.clip[0] / x,+ self.clip[1] / y,+ self.clip[2] / x,+ self.clip[3] / y,+ ],+ to_box: self.to_box.map(scale),+ rect: self+ .rect+ .map(|(from, to)| (from, [to[0] / x, to[1] / y, to[2] / x, to[3] / y])),+ ..*self+ }+ }++ /// `to_media` and `limits` for a picture of the media `size` big, as a+ /// picture is read: without a turn or a mirror, the pixels at a+ /// rectangle's ends land on the pixels at the other's ends.+ pub fn in_picture(&self, size: [f64; 2]) -> ([f64; 6], [f64; 4]) {+ let (x, y) = (size[0] / self.media[0], size[1] / self.media[1]);+ let m = self.to_media;+ let limits = [+ self.limits[0] * x,+ self.limits[1] * y,+ self.limits[2] * x,+ self.limits[3] * y,+ ];+ let Some((from, to)) = self.rect else {+ return (+ [m[0] * x, m[1] * x, m[2] * x, m[3] * y, m[4] * y, m[5] * y],+ limits,+ );+ };+ // How far a pixel of the frame goes in the picture, and where the+ // first one is there.+ let across = |lo: f64, hi: f64, at: f64, end: f64, k: f64| {+ let (s, d) = ((hi - lo) * k, end - at);+ if s > 1.0 && d > 1.0 {+ let step = (s - 1.0) / (d - 1.0);+ (step, lo * k + 0.5 - (at + 0.5) * step)+ } else {+ let step = s / d.max(1e-9);+ (step, lo * k - at * step)+ }+ };+ let (ux, u0) = across(from[0], from[2], to[0], to[2], x);+ let (vy, v0) = across(from[1], from[3], to[1], to[3], y);+ ([ux, 0.0, u0, 0.0, vy, v0], limits)+ }++ /// How many of the media's pixels go across a pixel of the frame, each+ /// way.+ pub fn media_per_pixel(&self) -> (f64, f64) {+ let m = self.to_media;+ (m[0].hypot(m[1]), m[3].hypot(m[4]))+ }++ /// How many of a `w` × `h` picture's pixels go across a pixel of the+ /// frame, each way.+ pub fn picture_per_pixel(&self, w: u32, h: u32) -> (f64, f64) {+ let (x, y) = self.media_per_pixel();+ (+ x * f64::from(w) / self.media[0],+ y * f64::from(h) / self.media[1],+ )+ }++ /// Whether half of a `w` × `h` picture would still cover the frame's+ /// pixels.+ pub fn reduces(&self, w: u32, h: u32) -> bool {+ if self.empty {+ return false;+ }+ let (x, y) = self.picture_per_pixel(w, h);+ x >= 2.0 && y >= 2.0+ }++ /// How large a picture of the media has to be for a pixel of it to+ /// show as at most a pixel of the frame.+ pub fn size_needed(&self) -> (u32, u32) {+ if self.empty {+ return (1, 1);+ }+ let (x, y) = self.media_per_pixel();+ (+ (self.media[0] / x.max(1e-6)).ceil().max(1.0) as u32,+ (self.media[1] / y.max(1e-6)).ceil().max(1.0) as u32,+ )+ }++ /// Where a point of the media lands on the frame.+ pub fn on_frame_point(&self, p: [f64; 2]) -> [f64; 2] {+ let m = self.to_media;+ let det = m[0] * m[4] - m[1] * m[3];+ if det == 0.0 {+ return [0.0; 2];+ }+ let (du, dv) = (p[0] - m[2], p[1] - m[5]);+ [(du * m[4] - dv * m[1]) / det, (dv * m[0] - du * m[3]) / det]+ }++ /// The pixels of the frame it may reach, from its size: left, top,+ /// right, bottom (a pixel counts by its middle).+ pub fn pixels(&self, size: (u32, u32)) -> [i32; 4] {+ if self.empty {+ return [0; 4];+ }+ let first = |v: f64, n: u32| ((v - 0.5).ceil().max(0.0) as i64).min(i64::from(n)) as i32;+ [+ first(self.clip[0], size.0),+ first(self.clip[1], size.1),+ first(self.clip[2], size.0),+ first(self.clip[3], size.1),+ ]+ }++ /// The same place with hard edges: for what goes with a picture, whose+ /// own edges already soften (its mask).+ pub fn hard(&self) -> Placement {+ Placement {+ to_box: None,+ ..*self+ }+ }++ /// Its soft edges, when it has them.+ pub fn soft_edges(&self) -> Option<SoftEdges> {+ let b = self.to_box?;+ let m = self.to_media;+ let axis = |g: [f64; 3], lo: f64, hi: f64| {+ let len = g[0].hypot(g[1]);+ SoftAxis {+ g,+ lo,+ hi,+ len,+ nx: g[0].abs() / len.max(1e-300),+ ny: g[1].abs() / len.max(1e-300),+ }+ };+ // The media's own edges are in how its picture is read; a crop's are+ // lines like the box's.+ let [l, t, r, d] = self.crop_lines();+ Some(SoftEdges([+ axis([b[0], b[1], b[2]], 0.0, 1.0),+ axis([b[3], b[4], b[5]], 0.0, 1.0),+ axis([m[0], m[1], m[2]], l, r),+ axis([m[3], m[4], m[5]], t, d),+ ]))+ }++ /// What a crop leaves of the media (left, top, right, bottom): all there+ /// is, far beyond its edges, without one.+ pub fn crop_lines(&self) -> [f64; 4] {+ const FAR: f64 = 1e7;+ let [l, t, r, b] = self.limits;+ [+ if l > 0.0 { l } else { -FAR },+ if t > 0.0 { t } else { -FAR },+ if r < self.media[0] { r } else { FAR },+ if b < self.media[1] { b } else { FAR },+ ]+ }++ /// How much of a frame pixel `(x, y)` the picture covers.+ pub fn coverage(&self, x: f64, y: f64) -> f64 {+ let (cx, cy) = (x + 0.5, y + 0.5);+ if cx < self.clip[0] || cx >= self.clip[2] || cy < self.clip[1] || cy >= self.clip[3] {+ return 0.0;+ }+ self.soft_edges().map_or(1.0, |e| e.share(cx, cy))+ }+}++#[derive(Clone, Copy, Debug)]+struct SoftAxis {+ g: [f64; 3],+ lo: f64,+ hi: f64,+ len: f64,+ nx: f64,+ ny: f64,+}++/// A turned or mirrored picture's edges: the box's and the media's, each two+/// lines on the frame.+#[derive(Clone, Copy, Debug)]+pub struct SoftEdges([SoftAxis; 4]);++impl SoftEdges {+ /// How much of the pixel whose middle is `(x, y)` is inside them, its+ /// edge's coverage over sixteen bands a line, each at its top.+ pub fn share(&self, x: f64, y: f64) -> f64 {+ let y = y - 1.0 / 32.0;+ let mut c = 1.0f64;+ for a in &self.0 {+ if a.len <= 0.0 {+ continue;+ }+ let v = a.g[0] * x + a.g[1] * y + a.g[2];+ let (lo, hi) = ((v - a.lo) / a.len, (a.hi - v) / a.len);+ if lo < 1.0 {+ c = c.min(half_plane(lo, a.nx, a.ny));+ }+ if hi < 1.0 {+ c = c.min(half_plane(hi, a.nx, a.ny));+ }+ }+ c+ }+}++/// How much of a unit pixel lies on the inner side of a line `d` from its+/// middle, the line's normal `(nx, ny)` (a unit vector, both not negative).+pub fn half_plane(d: f64, nx: f64, ny: f64) -> f64 {+ let (a, b) = if nx >= ny { (nx, ny) } else { (ny, nx) };+ let reach = (a + b) * 0.5;+ if d >= reach {+ return 1.0;+ }+ if d <= -reach {+ return 0.0;+ }+ let flat = (a - b) * 0.5;+ if d.abs() <= flat {+ return 0.5 + d / a;+ }+ let corner = (reach - d.abs()) * (reach - d.abs()) / (2.0 * a * b);+ if d > 0.0 { 1.0 - corner } else { corner }+}++/// The box a framing of the older kind shows: a picture fitted in the frame,+/// moved, zoomed, turned and mirrored. Projects and presets saved with it+/// come in through here, and the Properties panel's sliders show the box so.+pub fn key_from_transform(tf: &Transform, s: &PlaceIn) -> PanCropKey {+ let [mw, mh] = s.media;+ let [ow, oh] = s.frame;+ let ratio = s.media_aspect / s.frame_aspect;+ // The frame's pixels per media pixel: fitted, zoomed, stretched.+ let (fw, _) = fitted(mw, mh, ratio, ow, oh);+ let kx = fw / mw * f64::from(tf.scale.max(1e-4));+ let ky = kx / ratio.max(1e-6) * f64::from(tf.stretch.max(1e-4));+ let (fx, fy) = (+ if tf.flip_h { -1.0 } else { 1.0 },+ if tf.flip_v { -1.0 } else { 1.0 },+ );+ let turn = -f64::from(tf.rotation_deg).to_radians();+ let (sin, cos) = turn.sin_cos();+ let (tx, ty) = (f64::from(tf.x) * ow, -f64::from(tf.y) * oh);+ let center = [+ mw / 2.0 - fx * (tx * cos - ty * sin) / kx,+ mh / 2.0 - fy * (tx * sin + ty * cos) / ky,+ ];+ let angle = turn * fx * fy;+ let (width, height) = (fx * ow / kx, fy * oh / ky);+ // Where it turned: from its middle, in parts of its size, on its axes.+ let (px, py) = (+ f64::from(tf.pivot[0]) * width.abs() * f64::from(tf.box_size[0]),+ f64::from(tf.pivot[1]) * height.abs() * f64::from(tf.box_size[1]),+ );+ let (sa, ca) = angle.sin_cos();+ PanCropKey {+ at: Tick::ZERO,+ curve: KeyCurve::Linear,+ width,+ height,+ center,+ angle,+ pivot: [center[0] + px * ca - py * sa, center[1] + px * sa + py * ca],+ smoothness: 0.0,+ crop: [tf.crop_left, tf.crop_right, tf.crop_top, tf.crop_bottom],+ }+}++/// The framing of the older kind closest to a box: [`key_from_transform`]+/// the other way round.+pub fn transform_from_key(key: &PanCropKey, s: &PlaceIn) -> Transform {+ let [mw, mh] = s.media;+ let [ow, oh] = s.frame;+ let ratio = s.media_aspect / s.frame_aspect;+ let (fw, _) = fitted(mw, mh, ratio, ow, oh);+ let fit = fw / mw;+ let (w, h) = (key.width.abs().max(1e-6), key.height.abs().max(1e-6));+ let (kx, ky) = if !s.fill {+ (fit, fit / ratio.max(1e-6))+ } else if s.keep_aspect {+ let k = fitted(w, h, ratio, ow, oh).0 / w;+ (k, k / ratio.max(1e-6))+ } else {+ (ow / w, oh / h)+ };+ let (fx, fy) = (+ if key.width < 0.0 { -1.0 } else { 1.0 },+ if key.height < 0.0 { -1.0 } else { 1.0 },+ );+ let turn = key.angle * fx * fy;+ let (sin, cos) = turn.sin_cos();+ let rx = (mw / 2.0 - key.center[0]) * kx * fx;+ let ry = (mh / 2.0 - key.center[1]) * ky * fy;+ let (tx, ty) = (rx * cos + ry * sin, -rx * sin + ry * cos);+ Transform {+ x: (tx / ow) as f32,+ y: (-ty / oh) as f32,+ scale: (kx / fit) as f32,+ stretch: (ky / (kx / ratio.max(1e-6))) as f32,+ rotation_deg: (-turn).to_degrees() as f32,+ crop_left: key.crop[0],+ crop_right: key.crop[1],+ crop_top: key.crop[2],+ crop_bottom: key.crop[3],+ flip_h: key.width < 0.0,+ flip_v: key.height < 0.0,+ ..Transform::default()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ const MEDIA: [f64; 2] = [64.0, 36.0];++ /// A box of another shape than the frame's keeps the picture's shape:+ /// the frame shows it whole, with nothing beside it stretched.+ #[test]+ fn a_box_of_its_own_shape_shows_whole() {+ let s = sizes(true, true);+ let square = PanCropKey::whole(s.media).matched(1.0);+ assert_eq!((square.width, square.height), (300.0, 300.0));+ assert_eq!(square.center, [200.0, 150.0]);+ let wide = PanCropKey::whole(s.media).matched(16.0 / 9.0);+ assert_eq!(wide.width, 400.0);+ assert!((wide.height - 225.0).abs() < 1e-9);+ let on = place(&square, &s);+ // 1:1 in a 640×360 frame: as tall as the frame, as wide as tall.+ let (_, dest) = on.rect.expect("a straight box");+ assert!((dest[2] - dest[0] - 360.0).abs() < 1e-6, "{dest:?}");+ assert!((dest[3] - dest[1] - 360.0).abs() < 1e-6, "{dest:?}");+ }++ fn sizes(keep_aspect: bool, fill: bool) -> PlaceIn {+ PlaceIn {+ media: [400.0, 300.0],+ media_aspect: 1.0,+ frame: [640.0, 360.0],+ frame_aspect: 1.0,+ keep_aspect,+ fill,+ adjust: 1.0,+ }+ }++ fn close(a: f64, b: f64) -> bool {+ (a - b).abs() < 1e-6+ }++ #[test]+ fn the_box_moves_scales_and_turns_as_its_commands_say() {+ let k = PanCropKey::whole(MEDIA);+ assert_eq!(k.corners()[0], [0.0, 0.0]);+ assert_eq!(k.corners()[2], [64.0, 36.0]);+ // Both middles move.+ let m = k.moved([10.0, 5.0]);+ assert_eq!((m.center, m.pivot), ([42.0, 23.0], [42.0, 23.0]));+ // Its size and how far its middle is from its pivot.+ let s = k.scaled([0.5, 0.25]);+ assert_eq!((s.width, s.height), (32.0, 9.0));+ let t = k.turned(0.5);+ assert_eq!(t.angle, 0.5);+ assert_eq!(t.center, k.center);+ // Turned about a pivot off its middle, the middle goes round it.+ let off = PanCropKey {+ pivot: [10.0, 20.0],+ ..k+ };+ let t = off.turned(std::f64::consts::FRAC_PI_2);+ assert!(close(t.center[0], 10.0 - (18.0 - 20.0)));+ assert!(close(t.center[1], 20.0 + (32.0 - 10.0)));+ }++ #[test]+ fn the_curves_have_their_shapes() {+ assert_eq!(ease(KeyCurve::Linear, 0.25), 0.25);+ assert_eq!(ease(KeyCurve::Hold, 0.99), 0.0);+ assert_eq!(ease(KeyCurve::Hold, 1.0), 1.0);+ assert_eq!(ease(KeyCurve::Slow, 0.5), 0.25);+ assert_eq!(ease(KeyCurve::Fast, 0.5), 0.75);+ assert_eq!(ease(KeyCurve::Smooth, 0.5), 0.5);+ assert_eq!(ease(KeyCurve::Sharp, 0.5), 0.5);+ assert!(close(+ ease(KeyCurve::Sharp, 0.25),+ 0.25 * (0.25 - 1.5 + 3.0)+ ));+ }++ fn two_keys(smoothness: f64) -> PanCrop {+ let a = PanCropKey {+ smoothness,+ ..PanCropKey::whole(MEDIA)+ };+ let second = PanCropKey {+ at: Tick::from_seconds(1),+ smoothness,+ ..a.moved([20.0, 0.0])+ };+ let third = PanCropKey {+ at: Tick::from_seconds(2),+ smoothness,+ ..second.moved([0.0, 20.0])+ };+ PanCrop {+ size: [64, 36],+ keys: vec![a, second, third],+ ..PanCrop::default()+ }+ }++ #[test]+ fn between_keyframes_the_box_goes_straight_without_smoothness() {+ let p = two_keys(0.0);+ let half = Tick(TICKS_PER_SECOND / 2);+ let k = p.at(half, MEDIA, 1.0);+ assert!(close(k.center[0], 42.0), "{:?}", k.center);+ assert!(close(k.center[1], 18.0), "{:?}", k.center);+ assert!(close(k.pivot[0], 42.0));+ }++ #[test]+ fn smoothness_curves_the_way_and_keeps_the_keyframes() {+ let straight = two_keys(0.0);+ let smooth = two_keys(1.0);+ let half = Tick::from_seconds(1) + Tick(TICKS_PER_SECOND / 2);+ let (a, b) = (straight.at(half, MEDIA, 1.0), smooth.at(half, MEDIA, 1.0));+ assert!(close(a.center[0], 52.0));+ // Past the corner, the curve leans out of the straight way.+ assert!(b.center[0] > a.center[0] + 0.5, "{:?}", b.center);+ // On a keyframe there is no difference.+ let on = Tick::from_seconds(1);+ assert_eq!(+ straight.at(on, MEDIA, 1.0).center,+ smooth.at(on, MEDIA, 1.0).center+ );+ }++ #[test]+ fn a_turn_goes_round_the_pivot_between_keyframes() {+ let a = PanCropKey::whole(MEDIA);+ let b = PanCropKey {+ at: Tick::from_seconds(1),+ ..a.turned(1.0)+ };+ let p = PanCrop {+ size: [64, 36],+ keys: vec![a, b],+ ..PanCrop::default()+ };+ let k = p.at(Tick(TICKS_PER_SECOND / 2), MEDIA, 1.0);+ assert!(close(k.angle, 0.5));+ assert!(close(k.center[0], 32.0) && close(k.center[1], 18.0));+ }++ #[test]+ fn a_time_before_the_first_keyframe_or_past_the_last_holds_it() {+ let p = two_keys(0.0);+ assert_eq!(p.at(Tick::ZERO, MEDIA, 1.0).center, [32.0, 18.0]);+ assert_eq!(p.at(Tick::from_seconds(9), MEDIA, 1.0).center, [52.0, 38.0]);+ }++ #[test]+ fn another_media_size_scales_the_keyframes() {+ let p = two_keys(0.0);+ let k = p.at(Tick::from_seconds(1), [128.0, 72.0], 1.0);+ assert_eq!((k.width, k.height), (128.0, 72.0));+ assert_eq!(k.center, [104.0, 36.0]);+ }++ #[test]+ fn the_whole_media_lands_fitted_in_the_frame() {+ let s = sizes(true, true);+ let p = place(&PanCropKey::whole(s.media), &s);+ assert!(p.to_box.is_none());+ assert_eq!(p.clip, [80.0, 0.0, 560.0, 360.0]);+ assert!(close(p.to_media[0], 400.0 / 480.0));+ assert!(close(p.to_media[2], -80.0 * 400.0 / 480.0));+ assert!(close(p.to_media[4], 300.0 / 360.0));+ // Not keeping its shape, it fills the frame.+ let s = sizes(false, true);+ let p = place(&PanCropKey::whole(s.media), &s);+ assert_eq!(p.clip, [0.0, 0.0, 640.0, 360.0]);+ assert!(close(p.to_media[0], 400.0 / 640.0));+ }++ #[test]+ fn without_filling_the_box_only_crops_where_the_picture_is() {+ let s = sizes(true, false);+ let k = PanCropKey::whole(s.media).scaled([0.5, 0.5]);+ let p = place(&k, &s);+ // The media fitted at x 80, 1.2 frame pixels each; the box in its middle.+ assert_eq!(p.clip, [200.0, 90.0, 440.0, 270.0]);+ assert!(close(p.to_media[0], 1.0 / 1.2));+ assert!(close(p.to_media[0] * 200.0 + p.to_media[2], 100.0));+ }++ #[test]+ fn what_is_off_the_media_leaves_the_frame_too() {+ let s = sizes(true, true);+ let k = PanCropKey::whole(s.media)+ .scaled([1.5, 1.5])+ .moved([150.0, 100.0]);+ // A box of 600 x 450 from (50, 25), fitted: 480 x 360, so 0.8 frame+ // pixels each; the media ends 350 x 275 into it.+ let p = place(&k, &s);+ assert_eq!(p.clip, [80.0, 0.0, 360.0, 220.0]);+ // That frame pixel shows the box's corner.+ assert!(close(p.to_media[0] * 80.0 + p.to_media[2], 50.0));+ assert!(close(p.to_media[4] * 0.0 + p.to_media[5], 25.0));+ }++ #[test]+ fn a_box_off_the_media_shows_nothing() {+ let s = sizes(true, true);+ let k = PanCropKey::whole(s.media).moved([1000.0, 0.0]);+ assert!(place(&k, &s).empty);+ }++ #[test]+ fn a_turned_box_goes_to_the_frames_rectangle() {+ let s = sizes(true, true);+ let k = PanCropKey::whole(s.media).turned(0.5);+ let p = place(&k, &s);+ let b = p.to_box.expect("a parallelogram");+ assert!(+ close(p.clip[0], 80.0) && close(p.clip[2], 560.0),+ "{:?}",+ p.clip+ );+ // The frame's rectangle's corner is the box's.+ let tl = k.corners()[0];+ let m = p.to_media;+ assert!(close(m[0] * 80.0 + m[2], tl[0]), "{m:?} {tl:?}");+ assert!(close(m[3] * 80.0 + m[5], tl[1]), "{m:?} {tl:?}");+ assert!(close(b[0] * 80.0 + b[2], 0.0));+ assert!(close(b[3] * 80.0 + b[5], 0.0));+ // Well inside it covers the pixel; past the clip, nothing.+ assert_eq!(p.coverage(320.0, 180.0), 1.0);+ assert_eq!(p.coverage(60.0, 2.0), 0.0);+ }++ #[test]+ fn without_filling_a_turned_box_turns_only_its_outline() {+ let s = sizes(true, false);+ let k = PanCropKey::whole(s.media).scaled([0.7, 0.7]).turned(0.5);+ let p = place(&k, &s);+ let m = p.to_media;+ // The picture stays still: no cross terms.+ assert!(m[1].abs() < 1e-9 && m[3].abs() < 1e-9, "{m:?}");+ assert!(close(m[0], 1.0 / 1.2) && close(m[4], 1.0 / 1.2));+ }++ #[test]+ fn a_mirrored_box_reads_the_media_backward() {+ let s = sizes(true, true);+ let k = PanCropKey::whole(s.media).flipped_h();+ assert_eq!(k.width, -400.0);+ let p = place(&k, &s);+ assert!(p.to_box.is_some());+ assert!(close(p.to_media[0], -400.0 / 480.0), "{:?}", p.to_media);+ assert!(close(p.to_media[0] * 80.0 + p.to_media[2], 400.0));+ }++ #[test]+ fn flipping_twice_gives_the_box_back() {+ let k = PanCropKey {+ pivot: [10.0, 20.0],+ ..PanCropKey::whole(MEDIA).turned(0.3)+ };+ let back = k.flipped_h().flipped_h();+ assert!(close(back.width, k.width));+ assert!(close(back.center[0], k.center[0]));+ assert!(close(back.angle, k.angle), "{} {}", back.angle, k.angle);+ }++ #[test]+ fn matching_an_aspect_keeps_what_fits() {+ let k = PanCropKey::whole([300.0, 300.0]).matched(16.0 / 9.0);+ assert!(close(k.width, 300.0));+ assert!(close(k.height, 300.0 * 9.0 / 16.0));+ let k = PanCropKey {+ width: -100.0,+ ..PanCropKey::whole([300.0, 300.0])+ }+ .matched(1.0);+ assert_eq!((k.width, k.height), (-100.0, 100.0));+ }++ #[test]+ fn a_line_cuts_a_pixel_by_its_area() {+ // Square on: as far as it goes.+ assert_eq!(half_plane(0.0, 1.0, 0.0), 0.5);+ assert_eq!(half_plane(0.25, 1.0, 0.0), 0.75);+ assert_eq!(half_plane(1.0, 1.0, 0.0), 1.0);+ assert_eq!(half_plane(-1.0, 1.0, 0.0), 0.0);+ // Along the diagonal, a triangle's area.+ let n = std::f64::consts::FRAC_1_SQRT_2;+ assert!(close(half_plane(0.0, n, n), 0.5));+ assert!(close(half_plane(-n / 2.0, n, n), 0.125));+ assert!(close(half_plane(n / 2.0, n, n), 0.875));+ }++ #[test]+ fn an_older_framing_lands_where_it_did() {+ // Moved, zoomed: the point of the frame's middle.+ let s = sizes(true, true);+ let tf = Transform {+ x: 0.25,+ y: 0.1,+ scale: 2.0,+ ..Transform::default()+ };+ let k = key_from_transform(&tf, &s);+ // A frame-shaped box: 640 / 2.4 pixels of the media wide.+ assert!(close(k.width, 640.0 / 2.4));+ assert!(close(k.height, 360.0 / 2.4));+ // The picture's middle is 0.25 of the frame right and 0.1 up: the+ // frame's middle shows what is left of and below the media's.+ assert!(close(k.center[0], 200.0 - 160.0 / 2.4));+ assert!(close(k.center[1], 150.0 + 36.0 / 2.4));+ let p = place(&k, &s);+ let m = p.to_media;+ let near = |a: f64, b: f64| (a - b).abs() < 1e-3;+ assert!(near(m[0] * 320.0 + m[2], k.center[0]));+ // The picture's old place on the frame.+ assert!(near(m[0] * (320.0 + 160.0) + m[2], 200.0));+ // Back again.+ let back = transform_from_key(&k, &s);+ assert!((back.x - 0.25).abs() < 1e-5 && (back.y - 0.1).abs() < 1e-5);+ assert!((back.scale - 2.0).abs() < 1e-5);+ assert!((back.stretch - 1.0).abs() < 1e-5);+ }++ #[test]+ fn an_older_turn_and_mirror_come_back() {+ let s = sizes(true, true);+ for (flip_h, flip_v) in [(false, false), (true, false), (false, true), (true, true)] {+ let tf = Transform {+ x: 0.1,+ y: -0.2,+ scale: 1.5,+ rotation_deg: 30.0,+ flip_h,+ flip_v,+ ..Transform::default()+ };+ let k = key_from_transform(&tf, &s);+ let back = transform_from_key(&k, &s);+ assert!((back.rotation_deg - 30.0).abs() < 1e-3, "{back:?}");+ assert!((back.x - 0.1).abs() < 1e-5, "{back:?}");+ assert!((back.y + 0.2).abs() < 1e-5, "{back:?}");+ assert_eq!((back.flip_h, back.flip_v), (flip_h, flip_v));+ }+ }++ #[test]+ fn splitting_and_joining_keep_the_box_in_time() {+ let mut left = two_keys(0.0);+ let whole = left.clone();+ let cut = Tick(TICKS_PER_SECOND / 2);+ let right = left.split_at(cut, MEDIA, 1.0);+ assert_eq!(left.keys.last().unwrap().at, cut);+ assert_eq!(right.keys[0].at, Tick::ZERO);+ let at = |p: &PanCrop, t: Tick| p.at(t, MEDIA, 1.0).center;+ assert_eq!(at(&right, Tick::ZERO), at(&whole, cut));+ assert_eq!(+ at(&right, Tick::from_seconds(1) - cut),+ at(&whole, Tick::from_seconds(1))+ );+ let mut joined = left.clone();+ joined.joined(&right, cut, MEDIA);+ assert_eq!(+ at(&joined, Tick::from_seconds(2)),+ at(&whole, Tick::from_seconds(2))+ );+ }++ #[test]+ fn setting_the_box_makes_keyframes_as_needed() {+ let mut p = PanCrop::default();+ let k = PanCropKey::whole(MEDIA).moved([3.0, 0.0]);+ let new = (KeyCurve::Smooth, 0.25);+ // At the start, what it holds all along.+ p.set_at(Tick::ZERO, k, MEDIA, new);+ assert_eq!(p.keys.len(), 1);+ assert_eq!(p.keys[0].curve, KeyCurve::Smooth);+ assert_eq!(p.keys[0].smoothness, 0.25);+ assert_eq!(p.size, [64, 36]);+ // Elsewhere, the animation.+ let second = Tick::from_seconds(1);+ p.set_at(second, k.moved([4.0, 0.0]), MEDIA, new);+ assert_eq!(p.keys.len(), 2);+ assert_eq!(p.keys[1].at, second);+ // On a keyframe, that one; its curve stays.+ p.keys[1].curve = KeyCurve::Hold;+ p.set_at(second, k, MEDIA, new);+ assert_eq!(p.keys.len(), 2);+ assert_eq!(p.keys[1].curve, KeyCurve::Hold);+ p.remove_key(second);+ assert_eq!(p.keys.len(), 1);+ }++ #[test]+ fn an_empty_pan_crop_changes_nothing() {+ let p = PanCrop::default();+ assert!(p.is_default());+ assert_eq!(p.at(Tick::ZERO, MEDIA, 1.0), PanCropKey::whole(MEDIA));+ let holding = PanCrop::holding(PanCropKey::whole(MEDIA), MEDIA, true, true);+ assert!(holding.is_default());+ let moved = PanCrop::holding(+ PanCropKey::whole(MEDIA).moved([1.0, 0.0]),+ MEDIA,+ true,+ true,+ );+ assert!(!moved.is_default());+ }++ #[test]+ fn a_frame_on_another_scale_keeps_the_place() {+ let s = sizes(true, true);+ let p = place(&PanCropKey::whole(s.media), &s);+ let half = p.on_frame(s.frame, [320.0, 180.0]);+ assert_eq!(half.clip, [40.0, 0.0, 280.0, 180.0]);+ // The same media point.+ let (a, b) = (p.to_media, half.to_media);+ assert!(close(a[0] * 320.0 + a[2], b[0] * 160.0 + b[2]));+ // A picture of half the size: its pixels at the ends land on the+ // frame's.+ let (m, l) = p.in_picture([200.0, 150.0]);+ assert!(close(m[0], 199.0 / 479.0));+ assert!(close(m[0] * 80.5 + m[2], 0.5));+ assert!(close(m[0] * 559.5 + m[2], 199.5));+ assert_eq!(l, [0.0, 0.0, 200.0, 150.0]);+ assert_eq!(p.size_needed(), (480, 360));+ }++ #[test]+ fn a_frames_time_is_cut_down_to_the_boxs_unit() {+ // 5 / 30 s from an event starting at 3 / 30 s.+ let frame = |f: i64| Tick(f * TICKS_PER_SECOND / 30);+ assert_eq!(units_floor(frame(5)), 1_666_666);+ assert_eq!(units_near(frame(3)), 1_000_000);+ }+}diff --git a/crates/timeline/src/prerender.rs b/crates/timeline/src/prerender.rsindex d73e7d6..18dac77 100644--- a/crates/timeline/src/prerender.rs+++ b/crates/timeline/src/prerender.rs@@ -120,8 +120,7 @@ impl Project {.is_some_and(|m| m.effects.iter().all(|e| !e.enabled));c.effects.iter().all(|e| !e.enabled)&& media_fx- && c.transform.is_identity()- && c.transform_keys.is_empty()+ && c.pan_crop.is_default()&& !c.mask.as_ref().is_some_and(|m| m.active())&& c.level >= 1.0&& c.fade_in == Tick::ZEROdiff --git a/crates/timeline/src/ripple.rs b/crates/timeline/src/ripple.rsindex 0faf535..2371aa2 100644--- a/crates/timeline/src/ripple.rs+++ b/crates/timeline/src/ripple.rs@@ -5,7 +5,6 @@use bv_core::{Tick, TimeRange};use crate::edit::{EditError, clamp_fades};-use crate::fx::TransformKey;use crate::model::{ClipId, Project, TrackId, TrackKind};type Result<T> = std::result::Result<T, EditError>;@@ -382,31 +381,12 @@ impl Project {if let Some(mask) = crate::mask::PanCropMask::joined(&a.mask, &b.mask, offset) {a.mask = mask;}- if !a.transform_keys.is_empty() || !b.transform_keys.is_empty() {- if a.transform_keys.is_empty() {- a.transform_keys.push(TransformKey::new(- Tick::ZERO,- a.transform,- Default::default(),- ));- }- let tail: Vec<TransformKey> = if b.transform_keys.is_empty() {- vec![TransformKey::new(- Tick::ZERO,- b.transform,- Default::default(),- )]- } else {- b.transform_keys.clone()- };- // The key that split() left at the cut is replaced by b's first one.- a.transform_keys.retain(|k| k.at < offset);- a.transform_keys- .extend(tail.into_iter().map(|k| TransformKey {- at: k.at + offset,- ..k- }));- }+ let size = if a.pan_crop.size[0] > 0 {+ a.pan_crop.own_size()+ } else {+ b.pan_crop.own_size()+ };+ a.pan_crop.joined(&b.pan_crop, offset, size);a.duration += b.duration;a.fade_out = b.fade_out;a.fade_out_curve = b.fade_out_curve;diff --git a/crates/timeline/src/scene.rs b/crates/timeline/src/scene.rsindex 1711743..edcee55 100644--- a/crates/timeline/src/scene.rs+++ b/crates/timeline/src/scene.rs@@ -9,7 +9,7 @@use bv_core::{FrameRate, ImageRgbaF32, Tick};-use crate::fx::{Effect, FadeCurve, PluginFx, Transform, Transition};+use crate::fx::{Effect, FadeCurve, PluginFx, Transition};use crate::model::{Clip, ClipId, MediaId, MediaInfo, Project, RenderQuality, Track, TrackId};/// What an effect belongs to.@@ -94,13 +94,13 @@ pub struct FxSource<'a> {/// first in the event's chain): the media's own effects (the chain's/// first `framed_at`) work on its picture, `media_size` big, their sizes/// scaled by `media_fx_scale`; then the event's Pan/Crop places it in the-/// frame, its pixels `par` times as wide as the frame's, at `quality`.+/// frame as `place` says, at `quality`.#[derive(Clone, Copy, Debug, PartialEq)]pub struct Framing {pub framed_at: usize,pub media_size: (u32, u32),pub media_fx_scale: f32,- pub par: f32,+ pub place: crate::pancrop::PlaceIn,pub quality: RenderQuality,}@@ -442,7 +442,10 @@ pub struct MediaLayer<'a> {/// The size the picture shows at: a reader may give a reduced picture/// as long as it covers this.pub min_size: (u32, u32),- pub transform: Transform,+ /// Where its Pan/Crop puts it on the frame drawn, and what that depends+ /// on besides the box.+ pub placement: crate::pancrop::Placement,+ pub place: crate::pancrop::PlaceIn,pub quality: RenderQuality,/// The media's effects, then the event's (enabled video ones).pub effects: Vec<SceneFx<'a>>,@@ -496,7 +499,10 @@ impl MediaLayer<'_> {static KEPT: Mutex<Kept> = Mutex::new(Vec::new());let mask = self.clip.mask.as_ref().filter(|k| k.active())?;let (mw, mh) = self.info.video.map_or((w, h), |v| (v.width, v.height));- let key = mask.fingerprint(self.local, [w, h, mw, mh]);+ // The frame's time cut down to the box's unit, as the box's.+ let t = crate::pancrop::units_floor(self.clip.start + self.local)+ - crate::pancrop::units_near(self.clip.start);+ let key = mask.fingerprint(t, [w, h, mw, mh]);let found = KEPT.lock().ok().and_then(|kept| {kept.iter().find(|(k, _)| *k == key)@@ -506,7 +512,7 @@ impl MediaLayer<'_> {return found;}let scale = [w as f64 / mw.max(1) as f64, h as f64 / mh.max(1) as f64];- let keep = mask.coverage(self.local, w as usize, h as usize, scale, mw.min(mh) as f64);+ let keep = mask.coverage(t, w as usize, h as usize, scale, self.place.media_aspect);let picture = Arc::new(bv_core::ImageRgbaF32 {width: w,height: h,@@ -1006,30 +1012,27 @@ fn event_layer<'a>() -> EventLayer<'a> {let source = project.media(clip.media).and_then(|info| {let time = media_time(clip, info, t)?;- let mut transform = clip.transform_at(t);let par = info.video.map_or(1.0, |v| v.pixel_aspect.ratio())/ project.settings.pixel_aspect.ratio();- // Adjust source media to better match project or render settings:- // the picture enlarged to fill the frame (as a Pan/Crop would).- let s = &project.settings;- if s.adjust_source- && let Some(v) = info.video- {- transform.scale *= adjust_factor(v.width, v.height, par, s.width, s.height);- }+ let place = crate::pancrop::place_in(+ &project.settings,+ info,+ clip.pan_crop.keep_aspect,+ clip.pan_crop.fill,+ );+ let placement = place.at(clip, t, [f64::from(width), f64::from(height)]);// The size the media shows at, in its own pixels: the reader may// give less.- let min_size = info.video.map_or((u32::MAX, u32::MAX), |v| {- let fit = fit_rect_par(v.width, v.height, par, width, height);- let s = transform.scale.max(0.05);- ((fit.w / par * s).ceil() as u32, (fit.h * s).ceil() as u32)- });+ let min_size = info+ .video+ .map_or((u32::MAX, u32::MAX), |_| placement.size_needed());Some(MediaLayer {info,clip,time,min_size,- transform,+ placement,+ place,par,quality: project.settings.render_quality,effects: chain(info, clip),@@ -1681,15 +1684,17 @@ mod tests {info.video.as_mut().unwrap().height = 486;let m = p.add_media(info);p.insert_media(m, Tick::ZERO, Some(v), None).unwrap();+ // How many of the frame's pixels a line of the media takes.let scale = |p: &Project| {event_layer(p, &p.tracks[0].clips[0], Tick::ZERO, 720, 480).source- .map(|m| m.transform.scale)+ .map(|m| 1.0 / m.placement.media_per_pixel().1)};assert!(p.settings.adjust_source, "on for new projects");- assert!((scale(&p).unwrap() - 486.0 / 480.0).abs() < 1e-4);+ let fitted = 480.0 / 486.0;+ assert!((scale(&p).unwrap() - fitted * 486.0 / 480.0).abs() < 2e-3);p.settings.adjust_source = false;- assert!((scale(&p).unwrap() - 1.0).abs() < 1e-6);+ assert!((scale(&p).unwrap() - fitted).abs() < 1e-4);}#[test]diff --git a/crates/timeline/src/veg/audio.rs b/crates/timeline/src/veg/audio.rsnew file mode 100644index 0000000..756154c--- /dev/null+++ b/crates/timeline/src/veg/audio.rs@@ -0,0 +1,1113 @@+//! The other editor's audio plug-ins that BananaV has as its own effects:+//! each one's class and BananaV's effect, and how its settings read into+//! the effect's parameters. Three families of settings:+//!+//! - DirectX: a record of 4-byte numbers after their format's GUID, the+//! parameter being a number ÷ `div` × `mul` + `add` ([`PLUGINS`]), and the+//! graphs' points in the records of [`graphs`];+//! - the studio effects: a program of normalized values, big-endian+//! ([`STUDIO`]);+//! - the Modern Equalizer: its state, as text ([`modern_eq`]).++use super::riff::Guid;+use crate::fx::{Effect, EffectKind};++/// How a record keeps a number.+#[derive(Clone, Copy, Debug)]+enum Number {+ /// 4 bytes, whole.+ Whole,+ /// 4 bytes, with a point.+ Point,+ /// 8 bytes, with a point.+ Double,+}++/// Where a record keeps one of BananaV's parameters.+#[derive(Clone, Copy, Debug)]+struct Field {+ param: u8,+ at: u16,+ number: Number,+ div: f32,+ mul: f32,+ add: f32,+}++/// A whole number's field.+const fn i(param: u8, at: u16, div: f32, mul: f32, add: f32) -> Field {+ Field {+ param,+ at,+ number: Number::Whole,+ div,+ mul,+ add,+ }+}++/// A field of a number with a point.+const fn f(param: u8, at: u16, div: f32, mul: f32, add: f32) -> Field {+ Field {+ param,+ at,+ number: Number::Point,+ div,+ mul,+ add,+ }+}++/// A field of a long number with a point.+const fn d(param: u8, at: u16, div: f32, mul: f32, add: f32) -> Field {+ Field {+ param,+ at,+ number: Number::Double,+ div,+ mul,+ add,+ }+}++/// A plug-in BananaV has: its class, BananaV's effect, its bypass+/// switch's byte (on when not 0) and its fields. A graph's plug-in has+/// none: [`graphs`] reads its record.+struct Plugin {+ class: Guid,+ kind: EffectKind,+ bypass: Option<u16>,+ fields: &'static [Field],+}++#[rustfmt::skip]+const PLUGINS: &[Plugin] = &[+ // Volume+ Plugin {+ class: Guid::parse("EE38CA88-D78E-4BFB-B05E-577892730C83"),+ kind: EffectKind::Volume,+ bypass: None,+ fields: &[f(0, 0, 1.0, 1.0, 0.0)],+ },+ // Pan+ Plugin {+ class: Guid::parse("EB6213DB-08FF-4510-9F8D-3058B0ECE4C6"),+ kind: EffectKind::Pan,+ bypass: None,+ fields: &[f(0, 0, 1.0, 1.0, 0.0)],+ },+ // ExpressFX Audio Restoration+ Plugin {+ class: Guid::parse("0000000C-0F56-11D2-9887-00A0C969725B"),+ kind: EffectKind::ExpressAudioRestoration,+ bypass: None,+ fields: &[+ i(0, 0, 1.0, 1.0, 0.0),+ i(1, 4, 10.0, 1.0, 0.0),+ i(2, 8, 1.0, 1.0, 0.0),+ i(3, 12, 1.0, 1.0, 0.0),+ i(4, 16, 1.0, 1.0, 0.0),+ i(5, 20, 10.0, 1.0, 0.0),+ ],+ },+ // Amplitude Modulation+ Plugin {+ class: Guid::parse("FDB0D300-6F82-11D0-AEBC-00A0C9053912"),+ kind: EffectKind::AmplitudeModulation,+ bypass: Some(292),+ fields: &[+ ],+ },+ // Chorus+ Plugin {+ class: Guid::parse("28D9F1E0-6ECC-11D0-AEBC-00A0C9053912"),+ kind: EffectKind::Chorus,+ bypass: Some(48),+ fields: &[+ i(0, 0, 10.0, 1.0, 0.0),+ i(1, 4, 10.0, 1.0, 0.0),+ i(2, 8, 10.0, 1.0, 0.0),+ i(3, 20, 1.0, 1.0, 0.0),+ i(4, 44, 1.0, 1.0, 0.0),+ i(5, 12, 1.0, 1.0, 0.0),+ i(6, 28, 1000.0, 1.0, 0.0),+ i(7, 32, 100.0, 1.0, 0.0),+ i(8, 16, 100.0, 1.0, 0.0),+ i(9, 24, 10.0, 1.0, 0.0),+ i(10, 36, 1.0, 1.0, 0.0),+ i(11, 40, 1.0, 1.0, 0.0),+ i(12, 60, 1.0, 1.0, 0.0),+ i(13, 56, 1000.0, 1.0, 0.0),+ i(14, 52, 1.0, 1.0, 0.0),+ ],+ },+ // Distortion+ Plugin {+ class: Guid::parse("39224540-6F92-11D0-AEBC-00A0C9053912"),+ kind: EffectKind::Distortion,+ bypass: Some(552),+ fields: &[+ ],+ },+ // Dither+ Plugin {+ class: Guid::parse("260DF3E1-AC77-11D2-9E93-00C04F68BE44"),+ kind: EffectKind::Dither,+ bypass: None,+ fields: &[+ i(0, 0, 1.0, 1.0, 0.0),+ i(1, 4, 1.0, 1.0, 0.0),+ i(2, 8, 1.0, 1.0, 0.0),+ ],+ },+ // ExpressFX Amplitude Modulation+ Plugin {+ class: Guid::parse("00000005-0F56-11D2-9887-00A0C969725B"),+ kind: EffectKind::ExpressAmplitudeModulation,+ bypass: None,+ fields: &[+ i(0, 20, 10.0, 1.0, 0.0),+ i(1, 16, 1000.0, 1.0, 0.0),+ i(2, 32, 1000.0, 1.0, 0.0),+ ],+ },+ // ExpressFX Chorus+ Plugin {+ class: Guid::parse("00000000-0F56-11D2-9887-00A0C969725B"),+ kind: EffectKind::ExpressChorus,+ bypass: None,+ fields: &[+ i(0, 0, 1.0, 1.0, 0.0),+ i(1, 4, 1000.0, 1.0, 0.0),+ i(2, 8, 100.0, 1.0, 0.0),+ i(3, 12, 1000.0, 1.0, 0.0),+ ],+ },+ // ExpressFX Delay+ Plugin {+ class: Guid::parse("00000001-0F56-11D2-9887-00A0C969725B"),+ kind: EffectKind::ExpressDelay,+ bypass: None,+ fields: &[+ i(0, 4, 10.0, 1.0, 0.0),+ i(1, 8, 1000.0, 1.0, 0.0),+ i(2, 0, 1000.0, 1.0, 0.0),+ ],+ },+ // ExpressFX Distortion+ Plugin {+ class: Guid::parse("00000002-0F56-11D2-9887-00A0C969725B"),+ kind: EffectKind::ExpressDistortion,+ bypass: None,+ fields: &[+ i(0, 0, 1000.0, 1.0, 0.0),+ i(1, 4, 1000.0, 1.0, 0.0),+ i(2, 8, 1.0, 1.0, 0.0),+ i(3, 12, 1000.0, 1.0, 0.0),+ ],+ },+ // ExpressFX Dynamics+ Plugin {+ class: Guid::parse("00000008-0F56-11D2-9887-00A0C969725B"),+ kind: EffectKind::ExpressDynamics,+ bypass: None,+ fields: &[+ i(0, 0, 10.0, 1.0, 0.0),+ i(1, 4, 10.0, 1.0, 0.0),+ i(2, 8, 10.0, 1.0, 0.0),+ i(3, 12, 10.0, 1.0, 0.0),+ i(4, 16, 1.0, 1.0, 0.0),+ ],+ },+ // ExpressFX Equalization+ Plugin {+ class: Guid::parse("00000003-0F56-11D2-9887-00A0C969725B"),+ kind: EffectKind::ExpressEqualization,+ bypass: None,+ fields: &[+ i(0, 8, 10.0, 1.0, 0.0),+ i(1, 4, 10.0, 1.0, 0.0),+ i(2, 12, 10.0, 1.0, 0.0),+ i(3, 0, 1000.0, 1.0, 0.0),+ ],+ },+ // ExpressFX Flange/Wah-Wah+ Plugin {+ class: Guid::parse("00000004-0F56-11D2-9887-00A0C969725B"),+ kind: EffectKind::ExpressFlangeWahWah,+ bypass: None,+ fields: &[+ i(0, 0, 2.0, 1.0, 0.0),+ i(1, 12, 1000.0, 1.0, 0.0),+ i(2, 16, 100.0, 1.0, 0.0),+ i(3, 28, 1000.0, 1.0, 0.0),+ ],+ },+ // ExpressFX Graphic EQ+ Plugin {+ class: Guid::parse("00000009-0F56-11D2-9887-00A0C969725B"),+ kind: EffectKind::ExpressGraphicEq,+ bypass: None,+ fields: &[+ i(0, 4, 10.0, 1.0, 0.0),+ i(1, 8, 10.0, 1.0, 0.0),+ i(2, 12, 10.0, 1.0, 0.0),+ i(3, 16, 10.0, 1.0, 0.0),+ i(4, 20, 10.0, 1.0, 0.0),+ i(5, 24, 10.0, 1.0, 0.0),+ i(6, 28, 10.0, 1.0, 0.0),+ i(7, 32, 10.0, 1.0, 0.0),+ i(8, 36, 10.0, 1.0, 0.0),+ i(9, 40, 10.0, 1.0, 0.0),+ i(10, 44, 10.0, 1.0, 0.0),+ i(11, 0, 1.0, 1.0, 0.0),+ ],+ },+ // ExpressFX Noise Gate+ Plugin {+ class: Guid::parse("0000000A-0F56-11D2-9887-00A0C969725B"),+ kind: EffectKind::ExpressNoiseGate,+ bypass: None,+ fields: &[+ i(0, 8, 10.0, 1.0, 0.0),+ i(1, 0, 1.0, 1.0, 0.0),+ i(2, 4, 1.0, 1.0, 0.0),+ ],+ },+ // ExpressFX Reverb+ Plugin {+ class: Guid::parse("00000006-0F56-11D2-9887-00A0C969725B"),+ kind: EffectKind::ExpressReverb,+ bypass: None,+ fields: &[+ i(0, 12, 1.0, 1.0, 0.0),+ i(1, 20, 90.0, 1.0, -0.1111111),+ i(2, 24, 200.0, 1.0, 0.0),+ i(3, 44, 1000.0, 1.0, 0.0),+ ],+ },+ // ExpressFX Stutter+ Plugin {+ class: Guid::parse("00000007-0F56-11D2-9887-00A0C969725B"),+ kind: EffectKind::ExpressStutter,+ bypass: None,+ fields: &[+ i(0, 0, 100.0, 1.0, 0.0),+ i(1, 4, 100.0, 1.0, 0.0),+ i(2, 8, 1.0, 1.0, 0.0),+ i(3, 12, 1000.0, 1.0, 0.0),+ ],+ },+ // ExpressFX Time Stretch+ Plugin {+ class: Guid::parse("0000000B-0F56-11D2-9887-00A0C969725B"),+ kind: EffectKind::ExpressTimeStretch,+ bypass: None,+ fields: &[+ i(0, 8, 1.0, 1.0, 0.0),+ d(1, 0, 100.0, 1.0, 0.0),+ ],+ },+ // Flange/Wah-wah+ Plugin {+ class: Guid::parse("F09F6980-7845-11D0-AEBC-00A0C9053912"),+ kind: EffectKind::FlangeWahWah,+ bypass: Some(28),+ fields: &[+ i(0, 0, 1.0, 1.0, 0.0),+ i(1, 4, 10.0, 1.0, 0.0),+ i(2, 8, 10.0, 1.0, 0.0),+ i(3, 12, 1000.0, 1.0, 0.0),+ i(4, 16, 100.0, 1.0, 0.0),+ i(5, 20, 1.0, 1.0, 0.0),+ i(6, 24, 100.0, 1.0, 0.0),+ i(7, 40, 1.0, 1.0, 0.0),+ i(8, 36, 1000.0, 1.0, 0.0),+ i(9, 32, 1.0, 1.0, 0.0),+ ],+ },+ // Gapper/Snipper+ Plugin {+ class: Guid::parse("3F901A20-79BE-11D0-AEBC-00A0C9053912"),+ kind: EffectKind::GapperSnipper,+ bypass: None,+ fields: &[+ i(0, 12, 1.0, 1.0, 0.0),+ i(1, 0, 10000.0, 1.0, 0.0),+ i(2, 4, 10000.0, 1.0, 0.0),+ i(3, 8, 1.0, 1.0, 0.0),+ ],+ },+ // Graphic Dynamics+ Plugin {+ class: Guid::parse("F3B8E880-B4E0-11D0-AEBC-00A0C9053912"),+ kind: EffectKind::GraphicDynamics,+ bypass: Some(160),+ fields: &[+ ],+ },+ // Graphic EQ+ Plugin {+ class: Guid::parse("8B7226EE-4584-11D1-B4CB-00A0C9270A10"),+ kind: EffectKind::GraphicEq,+ bypass: None,+ fields: &[+ ],+ },+ // Multi-Band Dynamics+ Plugin {+ class: Guid::parse("026D0AA0-9BB9-11D0-AEBC-00A0C9053912"),+ kind: EffectKind::MultiBandDynamics,+ bypass: Some(208),+ fields: &[+ i(0, 0, 10.0, 1.0, 0.0),+ i(1, 132, 1.0, 1.0, 0.0),+ i(2, 136, 1.0, 1.0, 0.0),+ i(3, 192, 1.0, 1.0, 0.0),+ i(4, 20, 1.0, 1.0, 0.0),+ i(5, 116, 1.0, 1.0, 0.0),+ i(6, 100, 10.0, 1.0, 0.0),+ i(7, 4, 10.0, 1.0, 0.0),+ i(8, 36, 10.0, 1.0, 0.0),+ i(9, 84, 10.0, 1.0, 0.0),+ i(10, 52, 10.0, 1.0, 0.0),+ i(11, 68, 10.0, 1.0, 0.0),+ i(12, 140, 1.0, 1.0, 0.0),+ i(13, 196, 1.0, 1.0, 0.0),+ i(14, 24, 1.0, 1.0, 0.0),+ i(15, 120, 1.0, 1.0, 0.0),+ i(16, 104, 10.0, 1.0, 0.0),+ i(17, 8, 10.0, 1.0, 0.0),+ i(18, 40, 10.0, 1.0, 0.0),+ i(19, 88, 10.0, 1.0, 0.0),+ i(20, 56, 10.0, 1.0, 0.0),+ i(21, 72, 10.0, 1.0, 0.0),+ i(22, 144, 1.0, 1.0, 0.0),+ i(23, 200, 1.0, 1.0, 0.0),+ i(24, 28, 1.0, 1.0, 0.0),+ i(25, 124, 1.0, 1.0, 0.0),+ i(26, 108, 10.0, 1.0, 0.0),+ i(27, 12, 10.0, 1.0, 0.0),+ i(28, 44, 10.0, 1.0, 0.0),+ i(29, 92, 10.0, 1.0, 0.0),+ i(30, 60, 10.0, 1.0, 0.0),+ i(31, 76, 10.0, 1.0, 0.0),+ i(32, 148, 1.0, 1.0, 0.0),+ i(33, 204, 1.0, 1.0, 0.0),+ i(34, 32, 1.0, 1.0, 0.0),+ i(35, 128, 1.0, 1.0, 0.0),+ i(36, 112, 10.0, 1.0, 0.0),+ i(37, 16, 10.0, 1.0, 0.0),+ i(38, 48, 10.0, 1.0, 0.0),+ i(39, 96, 10.0, 1.0, 0.0),+ i(40, 64, 10.0, 1.0, 0.0),+ i(41, 80, 10.0, 1.0, 0.0),+ ],+ },+ // Multi-Tap Delay+ Plugin {+ class: Guid::parse("7298A3E0-78EE-11D0-AEBC-00A0C9053912"),+ kind: EffectKind::MultiTapDelay,+ bypass: None,+ fields: &[+ i(0, 112, 10.0, 1.0, 0.0),+ i(1, 104, 10.0, 1.0, 0.0),+ i(2, 100, 10.0, 1.0, 0.0),+ i(3, 128, 10.0, 1.0, 0.0),+ i(4, 124, 100.0, 1.0, 0.0),+ i(5, 108, 100.0, 1.0, 0.0),+ i(6, 116, 1.0, 1.0, 0.0),+ i(7, 120, 1.0, 1.0, 0.0),+ i(8, 96, 1.0, 1.0, 0.0),+ i(9, 32, 100.0, 1.0, 0.0),+ i(10, 0, 1.0, 1.0, 0.0),+ i(11, 64, -100.0, 1.0, 0.0),+ i(12, 36, 100.0, 1.0, 0.0),+ i(13, 4, 1.0, 1.0, 0.0),+ i(14, 68, -100.0, 1.0, 0.0),+ i(15, 40, 100.0, 1.0, 0.0),+ i(16, 8, 1.0, 1.0, 0.0),+ i(17, 72, -100.0, 1.0, 0.0),+ i(18, 44, 100.0, 1.0, 0.0),+ i(19, 12, 1.0, 1.0, 0.0),+ i(20, 76, -100.0, 1.0, 0.0),+ i(21, 48, 100.0, 1.0, 0.0),+ i(22, 16, 1.0, 1.0, 0.0),+ i(23, 80, -100.0, 1.0, 0.0),+ i(24, 52, 100.0, 1.0, 0.0),+ i(25, 20, 1.0, 1.0, 0.0),+ i(26, 84, -100.0, 1.0, 0.0),+ i(27, 56, 100.0, 1.0, 0.0),+ i(28, 24, 1.0, 1.0, 0.0),+ i(29, 88, -100.0, 1.0, 0.0),+ i(30, 60, 100.0, 1.0, 0.0),+ i(31, 28, 1.0, 1.0, 0.0),+ i(32, 92, -100.0, 1.0, 0.0),+ ],+ },+ // Noise Gate+ Plugin {+ class: Guid::parse("B97C0F23-196D-11D1-B99B-00A0C9053912"),+ kind: EffectKind::NoiseGateFx,+ bypass: None,+ fields: &[+ i(0, 8, 10.0, 1.0, 0.0),+ i(1, 0, 1.0, 1.0, 0.0),+ i(2, 4, 1.0, 1.0, 0.0),+ ],+ },+ // Paragraphic EQ+ Plugin {+ class: Guid::parse("D616F3E0-D622-11CE-AAC5-0020AF0B99A3"),+ kind: EffectKind::ParagraphicEq,+ bypass: None,+ fields: &[+ i(0, 0, 10.0, 1.0, 0.0),+ i(1, 4, 10.0, 1.0, 0.0),+ i(2, 8, 10.0, 1.0, 0.0),+ i(3, 24, 10.0, 1.0, 0.0),+ i(4, 40, 1.0, 1.0, 0.0),+ i(5, 8, 10.0, 1.0, 0.0),+ i(6, 24, 10.0, 1.0, 0.0),+ i(7, 44, 1.0, 1.0, 0.0),+ i(8, 16, 10.0, 1.0, 0.0),+ i(9, 24, 10.0, 1.0, 0.0),+ i(10, 48, 1.0, 1.0, 0.0),+ i(11, 20, 10.0, 1.0, 0.0),+ i(12, 36, 10.0, 1.0, 0.0),+ i(13, 52, 1.0, 1.0, 0.0),+ i(14, 56, 1.0, 1.0, 0.0),+ i(15, 64, 1.0, 1.0, 0.0),+ i(16, 72, 10.0, 1.0, 0.0),+ i(17, 60, 1.0, 1.0, 0.0),+ i(18, 68, 1.0, 1.0, 0.0),+ i(19, 76, 10.0, 1.0, 0.0),+ ],+ },+ // Parametric EQ+ Plugin {+ class: Guid::parse("A8448720-96FD-11D0-AEBC-00A0C9053912"),+ kind: EffectKind::ParametricEq,+ bypass: None,+ fields: &[+ i(0, 16, 10.0, 1.0, 0.0),+ i(1, 12, 10.0, 1.0, 0.0),+ i(2, 0, 1.0, 1.0, 0.0),+ i(3, 4, 1.0, 1.0, 0.0),+ i(4, 8, 10.0, 1.0, 0.0),+ i(5, 20, 1.0, 1.0, 0.0),+ ],+ },+ // Pitch Shift+ Plugin {+ class: Guid::parse("ED1B4100-93BE-11D0-AEBC-00A0C9053912"),+ kind: EffectKind::PitchShift,+ bypass: None,+ fields: &[+ i(0, 0, 1.0, 1.0, 0.0),+ i(1, 4, 1.0, 1.0, 0.0),+ i(2, 8, 1.0, 1.0, 0.0),+ i(3, 32, 1.0, 1.0, 0.0),+ i(4, 12, 1.0, 1.0, 0.0),+ i(5, 16, 1.0, 1.0, 0.0),+ ],+ },+ // Resonant Filter+ Plugin {+ class: Guid::parse("A6A78627-D619-48BF-AD26-0C6B44B5C7D8"),+ kind: EffectKind::ResonantFilter,+ bypass: None,+ fields: &[+ f(0, 0, 1.0, 1.0, 0.0),+ f(1, 4, 100.0, 1.0, 0.0),+ f(2, 20, 100.0, 1.0, 0.0),+ f(3, 8, 1.0, 1.0, 0.0),+ f(4, 12, 1.0, 1.0, 0.0),+ ],+ },+ // Reverb+ Plugin {+ class: Guid::parse("607682E0-6E21-11D0-AEBC-00A0C9053912"),+ kind: EffectKind::ReverbFx,+ bypass: Some(44),+ fields: &[+ i(0, 12, 1.0, 1.0, 0.0),+ i(1, 0, 10.0, 1.0, 0.0),+ i(2, 4, 10.0, 1.0, 0.0),+ i(3, 8, 10.0, 1.0, 0.0),+ i(4, 16, 1.0, 1.0, 0.0),+ i(5, 20, 10.0, 1.0, 0.0),+ i(6, 24, 1.0, 1.0, 0.0),+ i(7, 28, 1.0, 1.0, 0.0),+ i(8, 32, 1.0, 1.0, 0.0),+ i(9, 36, 1.0, 1.0, 0.0),+ i(10, 40, 1.0, 1.0, 0.0),+ ],+ },+ // Simple Delay+ Plugin {+ class: Guid::parse("54F29260-79B1-11D0-AEBC-00A0C9053912"),+ kind: EffectKind::SimpleDelay,+ bypass: Some(20),+ fields: &[+ i(0, 16, 10.0, 1.0, 0.0),+ i(1, 12, 10.0, 1.0, 0.0),+ i(2, 4, 1000.0, 1.0, 0.0),+ i(3, 32, 1.0, 1.0, 0.0),+ i(4, 28, 1000.0, 1.0, 0.0),+ i(5, 24, 1.0, 1.0, 0.0),+ i(6, 0, 1.0, 1.0, 0.0),+ i(7, 8, 10.0, 1.0, 0.0),+ i(8, 44, 1.0, 1.0, 0.0),+ i(9, 40, 1000.0, 1.0, 0.0),+ i(10, 36, 1.0, 1.0, 0.0),+ ],+ },+ // Smooth/Enhance+ Plugin {+ class: Guid::parse("9E3E4540-8339-11D0-AEBC-00A0C9053912"),+ kind: EffectKind::SmoothEnhance,+ bypass: Some(4),+ fields: &[+ i(0, 0, 1.0, 1.0, 0.0),+ ],+ },+ // Time Stretch+ Plugin {+ class: Guid::parse("B97C0F22-196D-11D1-B99B-00A0C9053912"),+ kind: EffectKind::TimeStretch,+ bypass: None,+ fields: &[+ i(0, 8, 1.0, 1.0, 0.0),+ d(1, 0, 100.0, 1.0, 0.0),+ ],+ },+ // Track Compressor+ Plugin {+ class: Guid::parse("23C9F225-40EC-11D2-9D36-00C04F8EDC1E"),+ kind: EffectKind::TrackCompressor,+ bypass: None,+ fields: &[+ f(0, 0, 1.0, 1.0, 0.0),+ f(1, 4, 1.0, 1.0, 0.0),+ f(2, 8, 1.0, 1.0, 0.0),+ f(3, 12, 1.0, 1.0, 0.0),+ f(4, 16, 1.0, 1.0, 0.0),+ f(5, 20, 1.0, 1.0, 0.0),+ i(6, 24, 1.0, 1.0, 0.0),+ i(7, 28, 1.0, 1.0, 0.0),+ ],+ },+ // Track EQ+ Plugin {+ class: Guid::parse("8CB69A0A-10E8-11D2-9B89-00104B8D13C2"),+ kind: EffectKind::TrackEq,+ bypass: Some(100),+ fields: &[+ i(0, 80, 1.0, 1.0, 0.0),+ i(1, 48, 1.0, 1.0, -1.0),+ i(2, 32, 1.0, 1.0, 0.0),+ i(3, 0, 10.0, 1.0, 0.0),+ i(4, 16, 10.0, 1.0, 0.0),+ i(5, 64, 1.0, 1.0, -1.0),+ i(6, 84, 1.0, 1.0, 0.0),+ i(7, 52, 1.0, 1.0, -1.0),+ i(8, 36, 1.0, 1.0, 0.0),+ i(9, 4, 10.0, 1.0, 0.0),+ i(10, 20, 10.0, 1.0, 0.0),+ i(11, 68, 1.0, 1.0, -1.0),+ i(12, 88, 1.0, 1.0, 0.0),+ i(13, 56, 1.0, 1.0, -1.0),+ i(14, 40, 1.0, 1.0, 0.0),+ i(15, 8, 10.0, 1.0, 0.0),+ i(16, 24, 10.0, 1.0, 0.0),+ i(17, 72, 1.0, 1.0, -1.0),+ i(18, 92, 1.0, 1.0, 0.0),+ i(19, 60, 1.0, 1.0, -1.0),+ i(20, 44, 1.0, 1.0, 0.0),+ i(21, 12, 10.0, 1.0, 0.0),+ i(22, 28, 10.0, 1.0, 0.0),+ i(23, 76, 1.0, 1.0, -1.0),+ i(24, 104, 1.0, 1.0, 0.0),+ i(25, 108, 1.0, 1.0, 0.0),+ i(26, 112, 1.0, 1.0, 0.0),+ i(27, 116, 1.0, 1.0, 0.0),+ i(28, 120, 1.0, 1.0, 0.0),+ i(29, 124, 1.0, 1.0, 0.0),+ ],+ },+ // Track Noise Gate+ Plugin {+ class: Guid::parse("869419DD-501F-11D3-8CDC-00C04F6B8E4C"),+ kind: EffectKind::TrackNoiseGate,+ bypass: Some(12),+ fields: &[+ i(0, 8, 10.0, 1.0, 0.0),+ i(1, 0, 1.0, 1.0, 0.0),+ i(2, 4, 1.0, 1.0, 0.0),+ ],+ },+ // Wave Hammer Surround+ Plugin {+ class: Guid::parse("8010C341-6D4C-4390-B828-E4D246C3DDB2"),+ kind: EffectKind::WaveHammer,+ bypass: None,+ fields: &[+ i(0, 0, 1.0, 1.0, 0.0),+ i(1, 8, 10.0, 1.0, 0.0),+ i(2, 16, 10.0, 1.0, 0.0),+ i(3, 12, 10.0, 1.0, 0.0),+ i(4, 40, 1.0, 1.0, 0.0),+ i(5, 32, 1.0, 1.0, 0.0),+ i(6, 28, 1.0, 1.0, 0.0),+ i(7, 44, 1.0, 1.0, 0.0),+ i(8, 20, 10.0, 1.0, 0.0),+ i(9, 24, 10.0, 1.0, 0.0),+ i(10, 36, 1.0, 1.0, 0.0),+ i(11, 4, 1.0, 1.0, 0.0),+ i(12, 48, 10.0, 1.0, 0.0),+ i(13, 52, 10.0, 1.0, 0.0),+ i(14, 60, 1.0, 1.0, 0.0),+ i(15, 56, 10.0, 1.0, 0.0),+ i(16, 88, 1.0, 1.0, 0.0),+ i(17, 92, 1.0, 1.0, 0.0),+ i(18, 96, 1.0, 1.0, 0.0),+ i(19, 100, 1.0, 1.0, 0.0),+ i(20, 104, 1.0, 1.0, 0.0),+ i(21, 108, 1.0, 1.0, 0.0),+ i(22, 112, 1.0, 1.0, 0.0),+ i(23, 116, 1.0, 1.0, 0.0),+ i(24, 120, 1.0, 1.0, 0.0),+ i(25, 124, 1.0, 1.0, 0.0),+ i(26, 128, 1.0, 1.0, 0.0),+ i(27, 132, 1.0, 1.0, 0.0),+ ],+ },+ // Vibrato+ Plugin {+ class: Guid::parse("D6802BA0-A056-11D0-AEBC-00A0C9053912"),+ kind: EffectKind::Vibrato,+ bypass: Some(276),+ fields: &[+ ],+ },+];++/// A studio effect: its class, BananaV's effect, and for each parameter+/// the place of its value in the program and where its range's middle+/// falls (0.5 being a straight line).+struct Studio {+ class: Guid,+ kind: EffectKind,+ fields: &'static [(u8, u8, f32)],+}++#[rustfmt::skip]+const STUDIO: &[Studio] = &[+ // Chorus/Flanger+ Studio { class: Guid::parse("4D583231-8A7A-478E-024A-0007E95D36FA"), kind: EffectKind::ChorusFlanger, fields: &[+ (0, 1, 0.5), (1, 3, 0.5), (2, 4, 0.5), (3, 5, 0.125), (4, 6, 0.25), (5, 7, 0.25), (6, 8, 0.5), (7, 20, 0.125), (8, 9, 0.5),+ ] },+ // Compressor+ Studio { class: Guid::parse("4D583237-3C15-7005-024A-0007E95D36FA"), kind: EffectKind::StudioCompressor, fields: &[+ (0, 3, 0.5), (1, 4, 0.5), (2, 6, 0.5), (3, 7, 0.25), (4, 8, 0.03065), (5, 9, 0.066), (6, 20, 0.25), (7, 21, 0.5), (8, 11, 0.5), (9, 22, 0.5), (10, 15, 0.5), (11, 5, 0.1), (12, 10, 0.5),+ ] },+ // DeEsser+ Studio { class: Guid::parse("4D583238-1767-B5FF-024A-0007E95D36FA"), kind: EffectKind::DeEsser, fields: &[+ (0, 3, 0.5), (1, 4, 0.5), (2, 5, 0.5), (3, 6, 0.5), (4, 20, 0.1), (5, 10, 0.5),+ ] },+ // Gate+ Studio { class: Guid::parse("4D583239-72C1-E1B5-024A-0007E95D36FA"), kind: EffectKind::StudioGate, fields: &[+ (0, 3, 0.5), (1, 4, 0.5), (2, 6, 0.7333), (3, 7, 0.1333), (4, 8, 0.0995), (5, 9, 0.0965), (6, 17, 0.5), (7, 11, 0.5), (8, 20, 0.1), (9, 15, 0.5), (10, 5, 0.1), (11, 10, 0.5), (12, 21, 0.1),+ ] },+ // Limiter+ Studio { class: Guid::parse("4D583241-CEE4-D900-024A-0007E95D36FA"), kind: EffectKind::StudioLimiter, fields: &[+ (0, 3, 0.5), (1, 4, 0.875), (2, 5, 0.6), (3, 6, 0.049), (4, 7, 0.5), (5, 20, 0.1), (6, 21, 0.5), (7, 22, 0.5), (8, 23, 0.5), (9, 24, 0.5), (10, 25, 0.2), (11, 26, 0.5),+ ] },+ // Phaser+ Studio { class: Guid::parse("4D583232-8725-70EB-024A-0007E95D36FA"), kind: EffectKind::Phaser, fields: &[+ (0, 1, 0.5), (1, 3, 0.5), (2, 4, 0.5), (3, 5, 0.5), (4, 6, 0.5), (5, 7, 0.25), (6, 8, 0.5), (7, 20, 0.2), (8, 9, 0.5),+ ] },+ // Studio Reverb+ Studio { class: Guid::parse("4D583233-BDF1-E94D-024A-0007E95D36FA"), kind: EffectKind::StudioReverb, fields: &[+ (0, 1, 0.5), (1, 3, 0.5), (2, 4, 0.5), (3, 5, 0.5), (4, 6, 0.5), (5, 7, 0.25), (6, 8, 0.5), (7, 20, 0.15), (8, 21, 0.5), (9, 22, 0.25), (10, 9, 0.5),+ ] },+ // Stereo Delay+ Studio { class: Guid::parse("4D583234-D195-D4C0-024A-0007E95D36FA"), kind: EffectKind::StereoDelay, fields: &[+ (0, 1, 0.5), (1, 3, 0.5), (2, 4, 0.5), (3, 5, 0.04545), (4, 6, 0.04545), (5, 10, 0.5), (8, 8, 0.5), (9, 7, 0.5), (10, 20, 0.2), (11, 9, 0.5), (12, 22, 0.5), (13, 23, 0.5), (14, 24, 0.25), (15, 21, 0.3333),+ ] },+ // Tremolo Pan+ Studio { class: Guid::parse("4D583332-97F3-37C3-024A-0007E95D36FA"), kind: EffectKind::TremoloPan, fields: &[+ (0, 3, 0.5), (1, 4, 0.5), (2, 5, 0.00214), (3, 6, 0.5), (4, 7, 0.25), (5, 8, 0.25),+ ] },+ // Tube Stage+ Studio { class: Guid::parse("4D583242-9D12-E479-024A-0007E95D36FA"), kind: EffectKind::TubeStage, fields: &[+ (0, 3, 0.5), (1, 4, 0.5), (2, 5, 0.5), (3, 6, 0.5), (4, 7, 0.5), (5, 10, 0.5), (6, 15, 0.5), (7, 16, 0.5),+ ] },+ // Vocal Strip+ Studio { class: Guid::parse("4D583330-F3CB-88E9-024A-0007E95D36FA"), kind: EffectKind::VocalStrip, fields: &[+ (0, 3, 0.5), (1, 4, 0.5), (2, 5, 0.1667), (3, 6, 0.7333), (4, 7, 0.5), (5, 8, 0.5), (6, 9, 0.5), (7, 20, 0.5), (8, 22, 0.25), (9, 23, 0.25), (10, 21, 0.5),+ ] },+];++/// The Modern Equalizer's class.+const MODERN_EQ: Guid = Guid::parse("F6A7FB77-7DD2-857C-034A-0007E95D36FA");++/// A studio effect's parameter from its normalized value: a straight line+/// bent so the value's middle lands at `middle` of the range.+fn studio_value(n: f32, middle: f32, min: f32, max: f32) -> f32 {+ let below = (1.0 - 1.0 / middle) * (n - 1.0) + n;+ let share = if below.abs() < 1e-9 { 0.0 } else { n / below };+ min + (max - min) * share+}++/// The note nearest a delay of `ms`, at the tempo the plug-in's default+/// program was made for.+fn nearest_note(ms: f32) -> f32 {+ let tempo = crate::Tempo::default();+ (0..crate::audio_fx::tempo::NOTES.len())+ .map(|n| n as f32)+ .min_by(|a, b| {+ let off = |note: f32| {+ (crate::audio_fx::tempo::seconds(note, &tempo) * 1000.0 - f64::from(ms)).abs()+ };+ off(*a).total_cmp(&off(*b))+ })+ .unwrap_or(crate::audio_fx::tempo::QUARTER)+}++/// A studio effect's program read into its parameters (`CcnK`, its size,+/// `FxCk`, two versions and the id, how many values at 24, the program's+/// name, the values at 56). Left as it is if the program keeps something+/// else (a whole bank, or the plug-in's own data).+fn studio(s: &Studio, program: &[u8]) -> Effect {+ let mut e = Effect::new(s.kind);+ if program.get(..4) != Some(b"CcnK") || program.get(8..12) != Some(b"FxCk") {+ return e;+ }+ let count = program+ .get(24..28)+ .and_then(|b| b.try_into().ok())+ .map_or(0, u32::from_be_bytes) as usize;+ let value = |k: usize| -> Option<f32> {+ if k >= count {+ return None;+ }+ let at = 56 + 4 * k;+ Some(f32::from_be_bytes(+ program.get(at..at + 4)?.try_into().ok()?,+ ))+ };+ let specs = s.kind.params();+ for &(param, place, middle) in s.fields {+ let (Some(n), Some(spec)) = (value(place as usize), specs.get(param as usize)) else {+ continue;+ };+ // The drive goes down as far as up in the plug-in, BananaV's from+ // nothing.+ let (min, max) = match (s.kind, param) {+ (EffectKind::TubeStage, 3) => (-spec.max, spec.max),+ _ => (spec.min, spec.max),+ };+ let v = studio_value(n, middle, min, max);+ if v.is_finite() {+ e.set_param(param as usize, v.clamp(spec.min, spec.max));+ }+ }+ if s.kind == EffectKind::StereoDelay {+ // The delays' notes are not kept: the nearest to their times.+ e.set_param(6, nearest_note(e.params[3]));+ e.set_param(7, nearest_note(e.params[4]));+ }+ if let Some(on) = value(0) {+ e.enabled = on >= 0.5;+ }+ e+}++/// A graph's points into its parameters: how many at `at`, the pairs+/// after it, those it does not use left as they are.+fn graph(e: &mut Effect, at: usize, room: usize, points: impl Iterator<Item = (f32, f32)>) {+ let mut count = 0;+ for (n, (x, y)) in points.take(room).enumerate() {+ e.set_param(at + 1 + 2 * n, x);+ e.set_param(at + 2 + 2 * n, y);+ count = n + 1;+ }+ e.set_param(at, count as f32);+}++/// The graphic EQ's graph: positions 0 to 10000 on a log axis of about+/// 17.84 Hz to 22.3 kHz.+fn eq_position_hz(p: f32) -> f32 {+ (17.84 * 1250f32.powf(p / 10_000.0)).clamp(20.0, 20_000.0)+}++/// The graphic EQ's graph: levels where 0 is 0 dB, 202 is +6 dB and −500+/// the bottom (silence), as (a^0.49 − 1)·500 of the amplitude a.+fn eq_level_db(v: f32) -> f32 {+ let a = v / 500.0 + 1.0;+ if a <= 0.0 {+ return -60.0;+ }+ (20.0 * a.powf(1.0 / 0.49).log10()).max(-60.0)+}++/// The records of the plug-ins with graphs, in their fields.+fn graphs(e: &mut Effect, record: &[u8]) {+ let r = |k: usize| -> f32 {+ record+ .get(4 * k..4 * k + 4)+ .and_then(|b| b.try_into().ok())+ .map_or(0.0, |b| i32::from_le_bytes(b) as f32)+ };+ let put = |e: &mut Effect, param: usize, v: f32| {+ let spec = e.kind.params().get(param).copied();+ if let (Some(spec), true) = (spec, v.is_finite()) {+ e.set_param(param, v.clamp(spec.min, spec.max));+ }+ };+ let count = |k: usize| r(k).max(0.0) as usize;+ match e.kind {+ EffectKind::Vibrato => {+ graph(+ e,+ 3,+ 32,+ (0..count(4)).map(|k| (r(5 + 2 * k), r(6 + 2 * k))),+ );+ put(e, 0, r(1) / 100.0);+ put(e, 1, r(2) / 1000.0);+ put(e, 2, r(3) / 10.0);+ put(e, 68, r(0));+ }+ EffectKind::AmplitudeModulation => {+ graph(+ e,+ 3,+ 32,+ (0..count(8)).map(|k| (r(9 + 2 * k), r(10 + 2 * k))),+ );+ put(e, 0, r(7) / 10.0);+ put(e, 1, r(6) / 10.0);+ put(e, 2, r(4) / 10.0);+ put(e, 68, r(3));+ put(e, 69, r(5) / 1000.0);+ put(e, 70, r(2) / 100.0);+ put(e, 71, r(1));+ put(e, 72, r(0));+ put(e, 73, r(76));+ put(e, 74, (r(75) / 1000.0).max(0.001));+ put(e, 75, r(74));+ }+ EffectKind::GraphicDynamics => {+ let points = (0..count(37)).map(|k| (r(5 + 2 * k) / 10.0, r(6 + 2 * k) / 10.0));+ graph(e, 0, 16, points);+ put(e, 33, r(1) / 10.0);+ put(e, 34, r(2) / 10.0);+ put(e, 35, r(0) / 10.0);+ put(e, 36, r(3));+ put(e, 37, r(4));+ }+ EffectKind::Distortion => {+ let half = |from: usize, n: usize| {+ let r = &r;+ (0..n).map(move |k| (r(from + 2 * k) / 10.0, r(from + 1 + 2 * k) / 10.0))+ };+ graph(e, 2, 32, half(9, count(8)));+ graph(e, 67, 32, half(74, count(73)));+ put(e, 0, r(2) / 10.0);+ put(e, 1, r(3) / 10.0);+ put(e, 132, r(4));+ put(e, 133, r(5));+ put(e, 134, r(0));+ put(e, 135, r(1));+ }+ EffectKind::GraphicEq => {+ let points = (0..count(149))+ .map(|k| (eq_position_hz(r(21 + 2 * k)), eq_level_db(r(22 + 2 * k))));+ graph(e, 0, 32, points);+ put(e, 65, r(150) / 10.0);+ put(e, 66, r(0));+ }+ _ => {}+ }+}++/// A DirectX plug-in's record read into its parameters.+fn directx(p: &Plugin, record: &[u8]) -> Effect {+ let word = |at: u16, n: usize| record.get(at as usize..at as usize + n);+ let specs = p.kind.params();+ let mut e = Effect::new(p.kind);+ for fl in p.fields {+ let Some(spec) = specs.get(fl.param as usize) else {+ continue;+ };+ let raw = match fl.number {+ Number::Whole => word(fl.at, 4)+ .and_then(|b| b.try_into().ok())+ .map(|b| i32::from_le_bytes(b) as f32),+ Number::Point => word(fl.at, 4)+ .and_then(|b| b.try_into().ok())+ .map(f32::from_le_bytes),+ Number::Double => word(fl.at, 8)+ .and_then(|b| b.try_into().ok())+ .map(|b| f64::from_le_bytes(b) as f32),+ };+ let Some(raw) = raw else {+ continue;+ };+ let v = raw / fl.div * fl.mul + fl.add;+ if v.is_finite() {+ e.set_param(fl.param as usize, v.clamp(spec.min, spec.max));+ }+ }+ if p.fields.is_empty() {+ graphs(&mut e, record);+ }+ if let Some(on) = p+ .bypass+ .and_then(|at| word(at, 4))+ .and_then(|b| b.try_into().ok())+ {+ e.enabled = i32::from_le_bytes(on) == 0;+ }+ e+}++/// The letters of the Modern Equalizer's state, a number each.+const STATE_LETTERS: &[u8; 64] =+ b".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";++/// The state's bytes, kept as letters of 6 bits each, the lowest first.+fn state_bytes(size: usize, letters: &[u8]) -> Vec<u8> {+ let mut out = vec![0u8; size.min(1 << 24)];+ let mut bit = 0usize;+ for c in letters {+ let Some(v) = STATE_LETTERS.iter().position(|x| x == c) else {+ continue;+ };+ for k in 0..6 {+ if (v >> k) & 1 != 0+ && let Some(b) = out.get_mut(bit >> 3)+ {+ *b |= 1 << (bit & 7);+ }+ bit += 1;+ }+ }+ out+}++/// A value of the state's text: `<param_{name} val="…"/>`.+fn state_value<'a>(text: &'a str, name: &str) -> Option<&'a str> {+ let at = text.find(&format!("<param_{name} val=\""))? + name.len() + 13;+ let rest = text.get(at..)?;+ rest.get(..rest.find('"')?)+}++/// The file's band type as BananaV's type and slope.+fn eq_band_type(t: i32) -> Option<(f32, f32)> {+ Some(match t {+ 0 => (1.0, 6.0),+ 1 => (1.0, 12.0),+ 2 => (1.0, 24.0),+ 3 => (1.0, 36.0),+ 4 => (2.0, 6.0),+ 5 => (2.0, 12.0),+ 6 => (5.0, 12.0),+ 7 => (4.0, 6.0),+ 8 => (4.0, 12.0),+ 9 => (4.0, 18.0),+ 10 => (6.0, 6.0),+ 11 => (3.0, 6.0),+ 12 => (3.0, 12.0),+ 13 => (0.0, 6.0),+ 14 => (0.0, 12.0),+ 15 => (0.0, 24.0),+ 16 => (0.0, 36.0),+ _ => return None,+ })+}++/// The Modern Equalizer's settings: `VC2!`, the size, and its state as a+/// text that holds, between `<IComponent>`s, the state's bytes as+/// `size.letters`; the bytes being `VC2!`, the size, and the values.+fn modern_eq(settings: &[u8]) -> Effect {+ use crate::fx::modern_eq as m;+ let mut e = Effect::new(EffectKind::ModernEq);+ let Some(body) = settings.get(8..) else {+ return e;+ };+ let text = String::from_utf8_lossy(body);+ let inner = (|| {+ let from = text.find("<IComponent>")? + "<IComponent>".len();+ let rest = &text[from..];+ let rest = &rest[..rest.find("</IComponent>")?];+ let dot = rest.find('.')?;+ let size: usize = rest[..dot].trim().parse().ok()?;+ let bytes = state_bytes(size, &rest.as_bytes()[dot + 1..]);+ Some(String::from_utf8_lossy(&bytes).into_owned())+ })();+ let Some(state) = inner else {+ return e;+ };+ let number = |name: &str| -> Option<f32> { state_value(&state, name)?.parse().ok() };+ let switch = |name: &str| -> Option<bool> { Some(state_value(&state, name)? == "true") };+ let specs = EffectKind::ModernEq.params();+ let put = |e: &mut Effect, param: usize, v: Option<f32>| {+ if let (Some(v), Some(spec)) = (v.filter(|v| v.is_finite()), specs.get(param)) {+ e.set_param(param, v.clamp(spec.min, spec.max));+ }+ };+ put(+ &mut e,+ m::GLOBAL_SCALE,+ number("globalScale").map(|v| v * 100.0),+ );+ put(&mut e, m::MONO_BELOW, number("globalMonoBelowFreq"));+ put(+ &mut e,+ m::STEREO_WIDTH,+ number("globalStereoWidth").map(|v| v * 100.0),+ );+ put(&mut e, m::OUTPUT_GAIN, number("globalGain"));+ put(&mut e, m::OVERSAMPLING, number("oversampling"));+ for b in 0..m::BANDS {+ let band = |p: &str| format!("b{b:02}_{p}");+ let on = |v: bool| f32::from(u8::from(v));+ put(&mut e, m::at(b, m::USED), switch(&band("enabled")).map(on));+ put(+ &mut e,+ m::at(b, m::ON),+ switch(&band("bypassed")).map(|v| on(!v)),+ );+ if let Some((kind, slope)) = number(&band("type")).and_then(|t| eq_band_type(t as i32)) {+ put(&mut e, m::at(b, m::TYPE), Some(kind));+ put(&mut e, m::at(b, m::SLOPE), Some(slope));+ }+ put(&mut e, m::at(b, m::FREQUENCY), number(&band("freq")));+ put(&mut e, m::at(b, m::GAIN), number(&band("gain")));+ put(&mut e, m::at(b, m::Q), number(&band("q")));+ put(&mut e, m::at(b, m::ROUTING), number(&band("mode")));+ put(&mut e, m::model(b), number(&band("model")));+ }+ if switch("bypass") == Some(true) {+ e.enabled = false;+ }+ e+}++/// BananaV's effect for an audio plug-in of a chain, its settings (from+/// their format's GUID or their program's mark) read into its parameters;+/// `None` for a plug-in BananaV does not have.+pub(super) fn effect(class: Guid, settings: &[u8]) -> Option<Effect> {+ if let Some(s) = STUDIO.iter().find(|s| s.class == class) {+ return Some(studio(s, settings));+ }+ if class == MODERN_EQ {+ return Some(modern_eq(settings));+ }+ let p = PLUGINS.iter().find(|p| p.class == class)?;+ Some(directx(p, settings.get(16..).unwrap_or(&[])))+}diff --git a/crates/timeline/src/veg/build.rs b/crates/timeline/src/veg/build.rsnew file mode 100644index 0000000..904f54a--- /dev/null+++ b/crates/timeline/src/veg/build.rs@@ -0,0 +1,857 @@+//! The project a read `.veg` makes, once its media are found.++use std::collections::HashMap;++use bv_core::{FrameRate, SampleRate, Tick, TimeRange};++use super::read::{DocEnvelope, DocMedia, DocMotion, DocMotionKey, Document};+use super::*;+use crate::bins::{BinId, MediaBin};+use crate::busses::SendTo;+use crate::cd::{CdIndex, CdTrack};+use crate::commands::CommandMarker;+use crate::envelope::{Envelope, EnvelopeKind, EnvelopePoint};+use crate::fx::{Effect, Transform, TransformKey};+use crate::model::{+ AudioStreamInfo, Clip, ClipId, CompositeMode, Generator, GroupId, MarkerId, MediaId, MediaInfo,+ MediaSource, PixelAspect, PixelFormat, Project, ProjectSettings, RulerFormat, Summary, Tempo,+ TrackKind, VideoStreamInfo,+};+use crate::motion::{Halo, HaloKey, HaloLook, TrackMotion};+use crate::space::{Box3d, Box3dKey};+use crate::takes::Take;++/// A project made from a `.veg`, and what it could not bring in.+#[derive(Clone, Debug)]+pub struct Imported {+ pub project: Project,+ /// The media files that were not found (their names): their events+ /// stay, offline.+ pub missing: Vec<String>,+ /// Events of media BananaV does not make (the project's generated+ /// media) and events without a take.+ pub skipped_events: usize,+ /// Effects of plug-ins BananaV does not have, envelopes it has no+ /// place for, audio effects BananaV does not have (or whose chain it+ /// could not read) left out.+ pub effects_left: usize,+ pub envelopes_left: usize,+ pub audio_fx_left: usize,+ /// The transitions of events' fades out: BananaV's stand at the+ /// entrances.+ pub transitions_left: usize,+}++/// BananaV's effects for an audio chain's plug-ins, counting those it does+/// not have (and a chain it could not read) in `left`.+fn audio_fx(chain: &[super::read::DocAudioFx], unread: bool, left: &mut usize) -> Vec<Effect> {+ *left += usize::from(unread);+ chain+ .iter()+ .filter_map(|x| {+ let mut e = super::audio::effect(x.class, &x.settings);+ *left += usize::from(e.is_none());+ if let Some(e) = e.as_mut().filter(|_| x.bypass) {+ e.enabled = false;+ }+ e+ })+ .collect()+}++/// The rate a file's frames per second stand for: NTSC's 1000/1001 rates+/// exactly, whole ones as they are.+fn frame_rate(fps: f64) -> Option<FrameRate> {+ if !(fps.is_finite() && fps > 0.5 && fps < 1000.0) {+ return None;+ }+ let ntsc = (fps * 1.001).round();+ if (ntsc * 1000.0 / 1001.0 - fps).abs() < 1e-4 && (fps - fps.round()).abs() > 1e-3 {+ return Some(FrameRate::new(ntsc as u32 * 1000, 1001));+ }+ if (fps - fps.round()).abs() < 1e-6 {+ return Some(FrameRate::new(fps.round() as u32, 1));+ }+ Some(FrameRate::new((fps * 1000.0).round() as u32, 1000))+}++/// A time of the file as its frame's when it is that, within the file's+/// step.+fn on_frame(t: Tick, rate: FrameRate) -> Tick {+ let near = rate.snap_nearest(t);+ if (near - t).abs() <= ticks(1) {+ near+ } else {+ t+ }+}++/// The settings of the file's project: `base`'s with its frame, rate,+/// pixel format, sample rate, tempo and ruler.+fn settings_of(doc: &Document, base: &ProjectSettings) -> ProjectSettings {+ let s = &doc.settings;+ let mut out = *base;+ if s.width > 0 && s.height > 0 {+ out.width = s.width;+ out.height = s.height;+ }+ if let Some(rate) = frame_rate(s.frame_rate) {+ out.frame_rate = rate;+ }+ out.pixel_format = match s.pixel_format {+ 32 => PixelFormat::Float32Full,+ _ => PixelFormat::Full8Bit,+ };+ if (s.pixel_aspect - 1.0).abs() > 1e-4 && s.pixel_aspect > 0.0 {+ out.pixel_aspect = PixelAspect {+ num: (s.pixel_aspect * 10_000.0).round() as u32,+ den: 10_000,+ };+ }+ if (8_000..=384_000).contains(&s.sample_rate) {+ out.sample_rate = SampleRate(s.sample_rate);+ }+ if s.beats_per_minute.is_finite() && s.beats_per_minute > 0.0 {+ out.tempo = Tempo {+ beats_per_minute: s.beats_per_minute,+ beats_per_measure: u32::from(s.beats_per_measure.clamp(1, 32)),+ beat_note: match s.beat_note {+ 1 | 2 | 4 | 8 | 16 | 32 => u32::from(s.beat_note),+ _ => 4,+ },+ };+ }+ out.ruler_format = match s.timecode {+ 7 => Some(RulerFormat::Smpte30),+ 8 => Some(RulerFormat::SmpteDrop),+ 9 => Some(RulerFormat::SmpteEbu),+ _ => None,+ };+ out+}++/// The compositing modes the file numbers (Add 1, Source Alpha 4 and 3D+/// Source Alpha 12 measured; Subtract and Multiply between them, in VEGAS's+/// list).+fn composite_mode(n: u32) -> CompositeMode {+ match n {+ 1 => CompositeMode::Add,+ 2 => CompositeMode::Subtract,+ 3 => CompositeMode::MultiplyMask,+ 12 => CompositeMode::ThreeDSourceAlpha,+ _ => CompositeMode::SourceAlpha,+ }+}++pub(crate) fn composite_number(m: CompositeMode) -> u32 {+ match m {+ CompositeMode::Add => 1,+ CompositeMode::Subtract => 2,+ CompositeMode::MultiplyMask => 3,+ CompositeMode::ThreeDSourceAlpha => 12,+ _ => 4,+ }+}++/// A file's linear gain in dB.+fn decibels(gain: f64) -> f32 {+ if gain > 0.0 {+ (20.0 * gain.log10()) as f32+ } else {+ -120.0+ }+}++/// A Track Motion's keyframe as a framing of the frame-sized picture: the+/// file measures from half the frame's height (where) and from its height+/// (how big), and in radians.+fn motion_framing(k: &DocMotionKey, aspect: f64) -> Transform {+ let scale = k.size[0] / aspect;+ Transform {+ x: (k.position[0] / (2.0 * aspect)) as f32,+ y: (k.position[1] / 2.0) as f32,+ scale: scale as f32,+ stretch: if scale.abs() > 1e-9 {+ (k.size[1] / scale) as f32+ } else {+ 1.0+ },+ rotation_deg: k.rotation[2].to_degrees() as f32,+ pivot: [+ (k.pivot[0] / (2.0 * k.size[0]).abs().max(1e-9)) as f32,+ (k.pivot[1] / (2.0 * k.size[1]).abs().max(1e-9)) as f32,+ ],+ ..Transform::default()+ }+}++/// The same keyframe as a box in space, for a 3D track.+fn motion_box(k: &DocMotionKey, aspect: f64) -> Box3d {+ Box3d {+ x: (k.position[0] / (2.0 * aspect)) as f32,+ y: (k.position[1] / 2.0) as f32,+ z: (k.position[2] / (2.0 * aspect)) as f32,+ width: (k.size[0] / aspect) as f32,+ height: k.size[1] as f32,+ rotation: k.rotation.map(|r| r.to_degrees() as f32),+ ..Box3d::default()+ }+}++/// A shadow's or a glow's keyframe as its look.+fn motion_look(k: &DocMotionKey, aspect: f64) -> HaloLook {+ let [blue, green, red, alpha] = k.color;+ HaloLook {+ x: (k.position[0] / (2.0 * aspect)) as f32,+ y: (k.position[1] / 2.0) as f32,+ size: k.size[0] as f32,+ blur: k.blur as f32,+ intensity: k.intensity as f32,+ color: [red, green, blue, alpha],+ }+}++/// A list of keyframes into a shadow or a glow, on when `on`.+fn motion_halo(keys: &[DocMotionKey], on: bool, aspect: f64, rate: FrameRate, was: Halo) -> Halo {+ let Some(first) = keys.first().filter(|_| on) else {+ return was;+ };+ let mut h = was;+ h.on = true;+ h.look = motion_look(first, aspect);+ if keys.len() > 1 {+ h.keys = keys+ .iter()+ .map(|k| HaloKey {+ at: on_frame(ticks(k.at.max(0)), rate),+ value: motion_look(k, aspect),+ curve: super::pancrop::curve(k.curve as u32),+ })+ .collect();+ }+ h+}++/// A track's motion from the file; `None` while it leaves the picture+/// where it is, without a shadow or a glow.+fn track_motion(m: &DocMotion, three_d: bool, rate: FrameRate) -> Option<TrackMotion> {+ let aspect = if m.aspect > 1e-6 { m.aspect } else { 1.0 };+ let (shadow_on, glow_on) = (m.flags & 8 != 0, m.flags & 0x10 != 0);+ let mut out = TrackMotion::default();+ let plain = Transform::default();+ let flat = out.space;+ if let Some(first) = m.moves.first() {+ if three_d {+ out.space = motion_box(first, aspect);+ if m.moves.len() > 1 {+ out.space_keys = m+ .moves+ .iter()+ .map(|k| Box3dKey {+ at: on_frame(ticks(k.at.max(0)), rate),+ value: motion_box(k, aspect),+ curve: super::pancrop::curve(k.curve as u32),+ })+ .collect();+ }+ } else {+ out.transform = motion_framing(first, aspect);+ if m.moves.len() > 1 {+ out.keys = m+ .moves+ .iter()+ .map(|k| {+ let mut key = TransformKey::new(+ on_frame(ticks(k.at.max(0)), rate),+ motion_framing(k, aspect),+ super::pancrop::curve(k.curve as u32),+ );+ key.smoothness = (k.smoothness * 100.0) as f32;+ key+ })+ .collect();+ }+ }+ }+ let near = |a: f32, b: f32| (a - b).abs() < 1e-4;+ let still = out.keys.is_empty()+ && out.space_keys.is_empty()+ && near(out.transform.x, plain.x)+ && near(out.transform.y, plain.y)+ && near(out.transform.scale, plain.scale)+ && near(out.transform.stretch, plain.stretch)+ && near(out.transform.rotation_deg, plain.rotation_deg)+ && out.space == flat;+ if still && !shadow_on && !glow_on {+ return None;+ }+ out.shadow = motion_halo(&m.shadow, shadow_on, aspect, rate, out.shadow);+ out.glow = motion_halo(&m.glow, glow_on, aspect, rate, out.glow);+ Some(out)+}++/// A file's envelope kind on a track, as BananaV's (`None`: one it has no+/// place for): volume, pan, a bus's send (A is 3), the compositing level,+/// the fade to color and the mute.+fn envelope_kind(n: i32, kind: TrackKind, busses: &[crate::busses::BusId]) -> Option<EnvelopeKind> {+ match (n, kind) {+ (0, TrackKind::Audio) => Some(EnvelopeKind::Volume),+ (1, TrackKind::Audio) => Some(EnvelopeKind::Pan),+ (3..=28, TrackKind::Audio) => busses+ .get((n - 3) as usize)+ .map(|&b| EnvelopeKind::Send(SendTo::Bus(b))),+ (29, TrackKind::Video) => Some(EnvelopeKind::CompositeLevel),+ (30, TrackKind::Video) => Some(EnvelopeKind::FadeToColor),+ (31, _) => Some(EnvelopeKind::Mute),+ _ => None,+ }+}++fn envelope(e: &DocEnvelope, kind: EnvelopeKind) -> Option<Envelope> {+ let mut points: Vec<EnvelopePoint> = e+ .points+ .iter()+ .filter(|p| p.1.is_finite())+ .map(|&(at, value, curve)| EnvelopePoint {+ at: ticks(at.max(0)),+ value,+ curve: key_curve(curve),+ })+ .collect();+ points.sort_by_key(|p| p.at);+ points.dedup_by_key(|p| p.at);+ if points.is_empty() {+ return None;+ }+ let mut env = Envelope::new(kind);+ env.points = points;+ Some(env)+}++/// The media `m` stands for: the file found, or an offline one where the+/// project says it is, its streams the ones its events use.+fn media_info(+ m: &DocMedia,+ found: Option<MediaInfo>,+ used: (bool, bool),+ reach: Tick,+ s: &ProjectSettings,+) -> MediaInfo {+ if let Some(f) = found {+ return f;+ }+ let name = m+ .path+ .rsplit(['\\', '/'])+ .next()+ .unwrap_or(&m.path)+ .to_string();+ let mut info = MediaInfo::generated(Generator::ColorBars, s);+ info.source = MediaSource::File {+ path: m.path.clone(),+ };+ info.name = name;+ info.video = used.0.then_some(VideoStreamInfo {+ width: s.width,+ height: s.height,+ frame_rate: s.frame_rate,+ pixel_aspect: Default::default(),+ field_order: Default::default(),+ spherical: false,+ full_range: false,+ reading: Default::default(),+ });+ info.audio = used.1.then_some(AudioStreamInfo {+ sample_rate: s.sample_rate,+ channels: s.channels.channel_count() as u16,+ });+ info.still = false;+ info.duration = reach.max(s.frame_rate.frame_duration());+ info+}++/// An audio event's channels from the file's number: as they are, one+/// side switched off, mixed to one or swapped (the rest, a side muted, has no+/// place here).+fn event_channels(n: u32) -> crate::model::ChannelMap {+ use crate::model::ChannelMap as C;+ match n {+ 1001 => C::RightOnly,+ 1002 => C::LeftOnly,+ 1005 => C::Combine,+ 1006 => C::Swap,+ _ => C::Both,+ }+}++/// A video event's resample mode from its switches: the project's, the+/// flow's, or the frames mixed or not.+fn video_resample(flags: u32) -> Option<crate::model::ResampleMode> {+ use crate::model::ResampleMode as R;+ if flags & 0x200 != 0 {+ None+ } else if flags & 0x800 != 0 {+ Some(R::OpticalFlow)+ } else if flags & 0x480 != 0 {+ Some(R::FrameBlend)+ } else {+ Some(R::Disable)+ }+}++/// A transition's progress envelope that says nothing: straight from 0 to 1.+fn progress_is_straight(e: &DocEnvelope) -> bool {+ matches!(e.points.as_slice(),+ [(0, a, 1), (1_000_000, b, _)] if a.abs() < 1e-6 && (b - 1.0).abs() < 1e-6)+}++/// Makes the project. `found[i]` is `doc.media[i]` probed (`None`: not+/// found); `effect` turns another program's effect into BananaV's+/// (`None`: no plug-in of its own for it), at the project's frame rate, in+/// which its keyframes count.+pub fn build(+ doc: &Document,+ found: &[Option<MediaInfo>],+ base: &ProjectSettings,+ effect: &dyn Fn(&DocEffect, FrameRate) -> Option<Effect>,+) -> Imported {+ let settings = settings_of(doc, base);+ let mut p = Project::new(settings);+ p.tracks.clear();+ let mut out = Imported {+ project: Project::new(settings),+ missing: Vec::new(),+ skipped_events: 0,+ effects_left: 0,+ envelopes_left: 0,+ audio_fx_left: 0,+ transitions_left: 0,+ };+ let rate = p.settings.frame_rate;+ let fx = |list: &[&DocEffect], left: &mut usize| -> Vec<Effect> {+ list.iter()+ .filter_map(|e| {+ let mut made = effect(e, rate);+ match &mut made {+ Some(m) => m.enabled = m.enabled && !e.bypass,+ None => *left += 1,+ }+ made+ })+ .collect()+ };++ // How each media is used: on which kinds of tracks, how far into it.+ let index: HashMap<u32, usize> = doc+ .media+ .iter()+ .enumerate()+ .map(|(i, m)| (m.id, i))+ .collect();+ let mut used = vec![(false, false); doc.media.len()];+ let mut reach = vec![Tick::ZERO; doc.media.len()];+ for t in &doc.tracks {+ for e in &t.events {+ for take in &e.takes {+ if let Some(&i) = index.get(&take.media) {+ if t.kind == VIDEO {+ used[i].0 = true;+ } else {+ used[i].1 = true;+ }+ reach[i] = reach[i].max(ticks(take.offset.max(0) + take.remain.max(0)));+ }+ }+ }+ }+ let mut media: HashMap<u32, MediaId> = HashMap::new();+ for (i, m) in doc.media.iter().enumerate() {+ if m.generated {+ continue;+ }+ let probed = found.get(i).cloned().flatten();+ if probed.is_none() {+ out.missing.push(+ m.path+ .rsplit(['\\', '/'])+ .next()+ .unwrap_or(&m.path)+ .to_string(),+ );+ }+ let info = media_info(m, probed, used[i], reach[i], &p.settings);+ media.insert(m.id, p.add_media(info));+ }++ // The busses, A to Z, before the tracks send to them.+ for _ in 0..doc.busses.min(26) {+ p.add_bus();+ }+ let busses: Vec<_> = p.busses.iter().map(|b| b.id).collect();++ // Each group's events, by their ids.+ let mut groups: HashMap<u64, GroupId> = HashMap::new();+ for members in doc.groups.iter().filter(|m| m.len() > 1) {+ let g = GroupId(p.alloc_id());+ for &id in members {+ groups.insert(id, g);+ }+ }++ let mut order = Vec::new();+ for t in &doc.tracks {+ let kind = match t.kind {+ AUDIO => TrackKind::Audio,+ VIDEO => TrackKind::Video,+ _ => continue,+ };+ let id = p.add_track(kind);+ order.push(id);+ let mut clips = Vec::new();+ for e in &t.events {+ let active = if (0..e.takes.len() as i32).contains(&e.active) {+ e.active as usize+ } else {+ 0+ };+ let Some(take) = e.takes.get(active) else {+ out.skipped_events += 1;+ continue;+ };+ let Some(&m) = media.get(&take.media) else {+ out.skipped_events += 1;+ continue;+ };+ // The file's 100 ns steps round a frame's time: on the frame's+ // again, or a cut lands a frame late.+ let start = on_frame(ticks(e.start), rate);+ let duration = (on_frame(ticks(e.start + e.length.max(1)), rate) - start).max(ticks(1));+ let mut c = Clip::new(ClipId(p.alloc_id()), m, start, duration);+ c.source_in = ticks(take.offset);+ c.muted = e.muted;+ c.rate = e.speed;+ c.level = if kind == TrackKind::Video {+ e.level.min(1.0)+ } else {+ e.level+ };+ c.fade_in = ticks(e.fade_in.max(0)).min(duration);+ c.fade_out = ticks(e.fade_out.max(0)).min(duration);+ c.fade_in_curve = fade_curve(e.curves[0]);+ c.fade_out_curve = fade_curve(e.curves[1]);+ c.group = groups.get(&e.id).copied();+ if kind == TrackKind::Audio && e.pitch.abs() > 1e-9 {+ c.pitch = e.pitch as f32;+ }+ // Its takes, the active one's place theirs start from.+ let takes: Vec<Take> = e+ .takes+ .iter()+ .filter_map(|k| {+ Some(Take {+ media: *media.get(&k.media)?,+ offset: ticks(k.offset) - ticks(take.offset),+ name: (!k.name.is_empty()).then(|| k.name.clone()),+ none: false,+ })+ })+ .collect();+ if takes.len() > 1 {+ c.active_take = takes+ .iter()+ .position(|k| k.media == m && k.offset == Tick::ZERO)+ .unwrap_or(0);+ c.takes = takes;+ }+ // Those that work before its Pan/Crop first, as its chain has them.+ let (before, after): (Vec<&DocEffect>, Vec<&DocEffect>) =+ e.effects.iter().partition(|x| x.before_pan_crop);+ c.effects = fx(&before, &mut out.effects_left);+ c.pan_crop_at = c.effects.len();+ c.effects.extend(fx(&after, &mut out.effects_left));+ c.effects.extend(audio_fx(+ &e.audio_fx,+ e.audio_unread,+ &mut out.audio_fx_left,+ ));+ for env in &e.envelopes {+ let made = (env.kind == VELOCITY && kind == TrackKind::Video)+ .then(|| envelope(env, EnvelopeKind::Velocity))+ .flatten();+ match made {+ Some(made) => c.envelopes.push(made),+ None => out.envelopes_left += 1,+ }+ }+ match kind {+ TrackKind::Video => {+ if let Some(pan_crop) = &e.pan_crop {+ c.pan_crop = pan_crop.clone();+ }+ c.pan_crop.keep_aspect = e.keep_aspect;+ c.mask.clone_from(&e.mask);+ c.undersample = e.undersample as f32;+ c.reduce_flicker = e.video_flags & 0x100 != 0;+ c.resample = video_resample(e.video_flags);+ if let Some(t) = &e.transition_in {+ match effect(t, rate).and_then(|x| x.plugin) {+ Some(made) => {+ c.transition_fx = Some(made);+ c.transition_bypass = t.bypass;+ }+ None => out.effects_left += 1,+ }+ }+ out.transitions_left += usize::from(e.transition_out.is_some());+ // Its progress over the fade: the file's places are its+ // parts of a million.+ if let Some(env) = &e.progress_in+ && e.transition_in.is_some()+ && !progress_is_straight(env)+ {+ let across = DocEnvelope {+ kind: env.kind,+ points: env+ .points+ .iter()+ .map(|&(place, value, curve)| {+ let share = place as f64 / 1_000_000.0;+ let at = (e.fade_in.max(0) as f64 * share).round() as i64;+ (at, value, curve)+ })+ .collect(),+ };+ c.envelopes+ .extend(envelope(&across, EnvelopeKind::TransitionProgress));+ }+ }+ TrackKind::Audio => {+ c.normalize = e.normalize;+ c.invert_phase = e.invert_phase;+ c.channels = event_channels(e.channels);+ }+ }+ clips.push(c);+ }+ clips.sort_by_key(|c| (c.start, c.id.0));+ let track_fx: Vec<&DocEffect> = t.effects.iter().collect();+ let mut effects = fx(&track_fx, &mut out.effects_left);+ effects.extend(audio_fx(+ &t.audio_fx,+ t.audio_unread,+ &mut out.audio_fx_left,+ ));+ let mut envelopes = Vec::new();+ for e in &t.envelopes {+ match envelope_kind(e.kind, kind, &busses).and_then(|k| envelope(e, k)) {+ Some(env) => envelopes.push(env),+ None => out.envelopes_left += 1,+ }+ }+ if let Ok(track) = p.track_mut(id) {+ track.name = t.name.clone();+ track.muted = t.muted;+ match kind {+ TrackKind::Audio => {+ track.level = t.volume;+ track.pan = t.pan;+ track.invert_phase = t.invert_phase;+ for (k, &gain) in t.sends.iter().enumerate() {+ if let (Some(&bus), true) = (busses.get(k), gain.is_finite() && gain > 0.0)+ {+ track.sends.push(crate::busses::Send {+ to: SendTo::Bus(bus),+ gain_db: decibels(f64::from(gain)),+ pre_volume: false,+ link_pan: true,+ held: 1.0,+ });+ }+ }+ }+ TrackKind::Video => {+ track.level = t.composite_level;+ track.composite_mode = composite_mode(t.composite_mode);+ track.composite_depth = t.composite_depth;+ let three_d = track.composite_mode == CompositeMode::ThreeDSourceAlpha;+ track.motion = t+ .motion+ .as_ref()+ .and_then(|m| track_motion(m, three_d, rate));+ track.parent_motion = t+ .parent_motion+ .as_ref()+ .and_then(|m| track_motion(m, false, rate));+ }+ }+ track.clips = clips;+ track.effects = effects;+ // A send's envelope rides on its send.+ for e in &envelopes {+ if let EnvelopeKind::Send(to) = e.kind+ && !track.sends.iter().any(|s| s.to == to)+ {+ track.sends.push(crate::busses::Send {+ to,+ gain_db: 0.0,+ pre_volume: false,+ link_pan: true,+ held: 1.0,+ });+ }+ }+ track.envelopes = envelopes;+ }+ }+ // The tracks in the file's order.+ p.tracks+ .sort_by_key(|t| order.iter().position(|&o| o == t.id));++ // The mixer's busses: their faders, switches, effects and envelopes.+ for b in &doc.bus_list {+ match b.id {+ 2 => {+ p.master.gain_db = decibels(b.gain);+ p.master.muted = b.muted;+ p.master_fx = audio_fx(&b.effects, false, &mut out.audio_fx_left);+ out.envelopes_left += b.envelopes.len();+ }+ id if id >= 3 && id != 5 && id != 7 => {+ let Some(bus) = p.busses.get_mut(id as usize - 3) else {+ continue;+ };+ let c = &mut bus.channel;+ c.gain_db = decibels(b.gain);+ c.muted = b.muted;+ c.solo = b.solo;+ c.effects = audio_fx(&b.effects, false, &mut out.audio_fx_left);+ let default = format!("Bus {}", crate::busses::bus_letter(id as usize - 3));+ if !b.name.is_empty() && b.name != default {+ c.name.clone_from(&b.name);+ }+ for e in &b.envelopes {+ let made = match e.kind {+ 0 => envelope(e, EnvelopeKind::Volume),+ 1 => envelope(e, EnvelopeKind::Pan),+ 31 => envelope(e, EnvelopeKind::Mute),+ _ => None,+ };+ match made {+ Some(made) => c.envelopes.push(made),+ None => out.envelopes_left += 1,+ }+ }+ }+ _ => {}+ }+ }++ for m in &doc.markers {+ let name = m.label.clone();+ if m.region {+ let id = p.add_region(TimeRange::new(ticks(m.time), ticks(m.length.max(0))));+ if let Some(r) = p.regions.iter_mut().find(|r| r.id == id) {+ r.name = name;+ }+ } else {+ let id = p.add_marker(ticks(m.time));+ if let Some(k) = p.markers.iter_mut().find(|k| k.id == id) {+ k.name = name;+ }+ }+ }+ for c in &doc.commands {+ let id = MarkerId(p.alloc_id());+ p.commands.push(CommandMarker {+ id,+ time: ticks(c.time),+ command: command_in(&c.command),+ parameter: c.parameter.clone(),+ comment: c.comment.clone(),+ });+ }+ for c in &doc.cd {+ let id = MarkerId(p.alloc_id());+ if c.index {+ p.cd_indices.push(CdIndex {+ id,+ time: ticks(c.time),+ });+ } else {+ p.cd_tracks.push(CdTrack {+ id,+ range: TimeRange::new(ticks(c.time), ticks(c.length.max(0))),+ name: c.name.clone(),+ protect: false,+ emphasis: false,+ isrc: String::new(),+ });+ }+ }+ let [title, artist, engineer, copyright, comments] = doc.summary.clone();+ p.summary = Summary {+ title,+ artist,+ engineer,+ copyright,+ comments,+ };+ let ids: Vec<BinId> = doc.bins.iter().map(|_| BinId(p.alloc_id())).collect();+ p.bins = doc+ .bins+ .iter()+ .zip(&ids)+ .map(|(b, &id)| MediaBin {+ id,+ name: b.name.clone(),+ parent: b.parent.map(|i| ids[i]),+ media: b+ .media+ .iter()+ .filter_map(|m| media.get(m).copied())+ .collect(),+ })+ .collect();+ let output_fx: Vec<&DocEffect> = doc.output_fx.iter().collect();+ p.video_output_fx = fx(&output_fx, &mut out.effects_left);+ // The video bus's: the fade to color over everything, its motion blur+ // and its supersampling.+ for e in &doc.envelopes {+ let made = match e.kind {+ 30 => envelope(e, EnvelopeKind::FadeToColor),+ 32 => envelope(e, EnvelopeKind::MotionBlur),+ 33 => envelope(e, EnvelopeKind::Supersampling),+ _ => None,+ };+ match made {+ Some(made) => p.video_bus.envelopes.push(made),+ None => out.envelopes_left += 1,+ }+ }+ out.project = p;+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn frame_rates_come_back_exact() {+ assert_eq!(frame_rate(30.0), Some(FrameRate::new(30, 1)));+ assert_eq!(frame_rate(25.0), Some(FrameRate::new(25, 1)));+ assert_eq!(+ frame_rate(29.970_029_970_029_97),+ Some(FrameRate::new(30_000, 1001))+ );+ assert_eq!(+ frame_rate(23.976_023_976),+ Some(FrameRate::new(24_000, 1001))+ );+ assert_eq!(+ frame_rate(59.940_059_94),+ Some(FrameRate::new(60_000, 1001))+ );+ assert_eq!(frame_rate(0.0), None);+ }+}diff --git a/crates/timeline/src/veg/mod.rs b/crates/timeline/src/veg/mod.rsnew file mode 100644index 0000000..a348814--- /dev/null+++ b/crates/timeline/src/veg/mod.rs@@ -0,0 +1,277 @@+//! `.veg` projects (VEGAS Pro's): read into a [`Document`] — the+//! project's settings, media, tracks and their events with their takes,+//! fades, envelopes and effects, markers, regions, command markers, the+//! audio CD layout, groups, busses, bins and summary — that [`build`]+//! makes a BananaV project of once the caller found its media; and+//! written from a project ([`write`]) as VEGAS Pro 23 writes its own, so+//! that it opens them.+//!+//! The file is Sony Wave64's RIFF of 64 bits ([`riff`]): a tree of chunks+//! named by GUIDs, each structure in them starting with its own size, so+//! a reader takes what it knows of a longer one and a shorter one leaves+//! the rest at its defaults. Times are counted in 100 ns, text is UTF-16.+//! What BananaV has no place for (generated media, say) is left out and+//! counted.+//!+//! Everything here is bytes in, bytes out; reading and writing files and+//! probing the media are the caller's.++mod audio;+mod build;+mod pancrop;+mod read;+mod riff;+#[cfg(test)]+mod tests;+mod write;++pub use build::{Imported, build};+pub use read::{DocMedia, Document, read};+pub use riff::VegError;+pub use write::{WriteOptions, write};++/// A plug-in parameter's value as the file holds it.+#[derive(Clone, Debug, PartialEq)]+pub enum ParamValue {+ Number(f64),+ /// A whole number: an integer, a choice, a switch.+ Integer(i64),+ /// Two numbers or more: a point, a color.+ Numbers(Vec<f64>),+ /// A text: a file's path, a curve's points…+ Text(String),+}++/// A keyframe of an effect's parameter: its frame from the effect's start,+/// its interpolation (the file's numbers), its value and, for each number+/// that has them, its handles as they are kept: where the one toward the+/// keyframe before is (frame, value), then the one toward the next.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct DocKey {+ pub frame: f64,+ pub interpolation: i32,+ pub value: Vec<f64>,+ pub handles: Vec<[f64; 4]>,+}++/// An effect as another program's plug-in has it: its id+/// (`com.vegascreativesoftware:sepia`), its preset's name and its+/// parameters; or, for a plug-in of the file's own kind, its class and its+/// preset's name alone.+#[derive(Clone, Debug, Default, PartialEq)]+pub struct DocEffect {+ pub plugin: String,+ pub preset: String,+ pub params: Vec<(String, ParamValue)>,+ /// The parameters that change over time.+ pub keys: Vec<(String, Vec<DocKey>)>,+ pub bypass: bool,+ /// An event's: it works before its Pan/Crop.+ pub before_pan_crop: bool,+ /// It is a transition.+ pub transition: bool,+ /// The class of a plug-in of the file's own kind, and its settings'+ /// record.+ pub native: Option<String>,+ pub native_data: Vec<u8>,+}++use bv_core::{TICKS_PER_SECOND, Tick};+use riff::Guid;++/// 100 ns steps in a second, the file's unit of time.+const UNITS: i64 = 10_000_000;++/// A time of the file as BananaV's ticks.+fn ticks(units: i64) -> Tick {+ Tick((units as i128 * TICKS_PER_SECOND as i128 / UNITS as i128) as i64)+}++/// BananaV's ticks as the file's 100 ns, rounded.+fn units(t: Tick) -> i64 {+ let n = t.0 as i128 * UNITS as i128;+ let d = TICKS_PER_SECOND as i128;+ (if n >= 0 {+ (n + d / 2) / d+ } else {+ (n - d / 2) / d+ }) as i64+}++/// The file's type for a VEGAS Pro project, and its version: VEGAS Pro+/// 23's (2026's is 0x170000).+const PROJECT: Guid = Guid::parse("46C429EF-904A-11D2-8722-00C04F8EDB8A");+const VERSION: u32 = 0x16_0000;++// The chunks, as the file names them.+const HEADER: Guid = Guid::parse("B28F2D5A-230F-11D2-86AF-00C04F8EDB8A");+const FOUR_LIST: Guid = Guid::parse("2CCCB9D8-DEDD-46AC-853D-1916A99A9A02");+const FOUR: Guid = Guid::parse("5E8A8C39-DA6B-4499-B0B2-3663709E1CE4");+const OUTPUT_FX: Guid = Guid::parse("6697A914-7B18-11D2-8713-00C04F8EDB8A");+const PROJECT_ENVELOPES: Guid = Guid::parse("F0CA0912-3506-496F-BDBF-7807976210D2");+const MEDIA_LIST: Guid = Guid::parse("B28F2D5B-230F-11D2-86AF-00C04F8EDB8A");+const MEDIA: Guid = Guid::parse("B28F2D5D-230F-11D2-86AF-00C04F8EDB8A");+const GROUPS: Guid = Guid::parse("B8E73E18-7F4C-456B-93CD-6866B95E5F2B");+const GROUP: Guid = Guid::parse("E901E132-C677-4604-AC9D-DB0B87B4EEBD");+const TRACKS: Guid = Guid::parse("4D6C0747-2316-11D2-86B0-00C04F8EDB8A");+const TRACK: Guid = Guid::parse("4D6C0748-2316-11D2-86B0-00C04F8EDB8A");+/// A track's header, and the type of the list of its events.+const TRACK_HEADER: Guid = Guid::parse("4D6C0749-2316-11D2-86B0-00C04F8EDB8A");+const EVENT: Guid = Guid::parse("4D6C074A-2316-11D2-86B0-00C04F8EDB8A");+const EVENT_HEADER: Guid = Guid::parse("168D206A-2321-11D2-86B0-00C04F8EDB8A");+const TAKE: Guid = Guid::parse("168D206D-2321-11D2-86B0-00C04F8EDB8A");+const EVENT_ENVELOPES: Guid = Guid::parse("84701B5A-6863-11D2-86FD-00C04F8EDB8A");+const ENVELOPES_HEADER: Guid = Guid::parse("84701B5B-6863-11D2-86FD-00C04F8EDB8A");+const ENVELOPE: Guid = Guid::parse("84701B5C-6863-11D2-86FD-00C04F8EDB8A");+const TRACK_ENVELOPES: Guid = Guid::parse("84701B5D-6863-11D2-86FD-00C04F8EDB8A");+/// An audio event's properties: a list of a chunk of the same GUID.+const AUDIO_EVENT: Guid = Guid::parse("D54AD82A-EFA7-4C24-8C0C-316427A5F209");+const VIDEO_EVENT_LIST: Guid = Guid::parse("FC2B3BCE-7985-11D2-8711-00C04F8EDB8A");+const VIDEO_EVENT: Guid = Guid::parse("FC2B3BCF-7985-11D2-8711-00C04F8EDB8A");+const VIDEO_EVENT_ENVELOPES_1: Guid = Guid::parse("3277F926-B5D3-40A1-8203-0EE5FA443F4A");+const EVENT_FX: Guid = Guid::parse("1AF0E4E4-6E7F-11D2-8705-00C04F8EDB8A");+const TRACK_FX: Guid = Guid::parse("1AF0E4E5-6E7F-11D2-8705-00C04F8EDB8A");+const EFFECT: Guid = Guid::parse("1AF0E4E6-6E7F-11D2-8705-00C04F8EDB8A");+const PAN_CROP: Guid = Guid::parse("884BACFF-74EB-456C-88F3-739E8390BD07");+const AUDIO_TRACK_LIST: Guid = Guid::parse("69D46C26-7F0B-11D2-8717-00C04F8EDB8A");+const AUDIO_TRACK: Guid = Guid::parse("69D46C27-7F0B-11D2-8717-00C04F8EDB8A");+const AUDIO_TRACK_FX: Guid = Guid::parse("F79298F4-5695-4B17-9DDB-19A0912D39F3");+const AUDIO_EVENT_FX: Guid = Guid::parse("B66A95CE-5946-48AB-A4F4-F88C95ACDC1D");+const VIDEO_TRACK_LIST: Guid = Guid::parse("69D46C28-7F0B-11D2-8717-00C04F8EDB8A");+const VIDEO_TRACK: Guid = Guid::parse("69D46C29-7F0B-11D2-8717-00C04F8EDB8A");+const TRACK_LIST_B5707E20: Guid = Guid::parse("B5707E20-7A06-4E83-B961-4DE58141220A");+const TRACK_FX_2: Guid = Guid::parse("20E4E6B9-4EEE-4D5A-9EDF-2E7AAC9672F4");+const SUMMARY_LIST: Guid = Guid::parse("925F94BC-525A-11D2-86DC-00C04F8EDB8A");+const SUMMARY: Guid = Guid::parse("71234F1D-5257-11D2-86DC-00C04F8EDB8A");+const MARKERS: Guid = Guid::parse("90020EF4-392D-11D2-86C7-00C04F8EDB8A");+const COMMANDS: Guid = Guid::parse("90020EF5-392D-11D2-86C7-00C04F8EDB8A");+const CD_LAYOUT: Guid = Guid::parse("90020EF7-392D-11D2-86C7-00C04F8EDB8A");+const MARKER: Guid = Guid::parse("ABF76256-392D-11D2-86C7-00C04F8EDB8A");+const MIXER: Guid = Guid::parse("220D2BE4-7FD3-11D2-8718-00C04F8EDB8A");+const MIXER_SETTINGS: Guid = Guid::parse("F1FF1C46-A61A-4BCC-BCF3-2477D138DB8A");+const BUS: Guid = Guid::parse("72B8749D-14AB-4588-94A9-39343AEEF7CC");+const BINS: Guid = Guid::parse("CA8CAF30-CB40-4C9C-992C-659CB76624BA");+const TREE_ITEM: Guid = Guid::parse("CA8CAF31-CB40-4C9C-992C-659CB76624BA");+const TREE_DATA: Guid = Guid::parse("CA8CAF32-CB40-4C9C-992C-659CB76624BA");+const LIST_1F0900B5: Guid = Guid::parse("1F0900B5-DC84-4743-81CB-087744404598");+const TIMELINES: Guid = Guid::parse("AA585C13-5A89-4B7C-A288-CDDD1066DACF");+/// The folders and file options: a list of a chunk of the same GUID.+const FOLDERS: Guid = Guid::parse("C5EA942E-91F9-4AD0-ACCC-72C090E71969");++/// The property sets closing a track's header, an event's header and an+/// audio file's entry.+const TRACK_PROPERTIES: Guid = Guid::parse("ADE0C7D1-1991-12EF-4573-2BEF2100B10A");+const EVENT_PROPERTIES: Guid = Guid::parse("F44FC1AB-6C91-4B8E-A3FC-0F4DB7B18C08");+const AUDIO_MEDIA_PROPERTIES: Guid = Guid::parse("612CCA25-92BB-4C55-8408-7BDA2F15BD27");+/// An OpenFX plug-in's effect.+const OFX_HOST: Guid = Guid::parse("A2FC1A41-01F6-460E-AE5A-2BE4AF57B92E");+const TRACK_MOTION_LIST: Guid = Guid::parse("D24DF987-1842-4A39-B079-9E4379485A38");+const PARENT_MOTION_LIST: Guid = Guid::parse("B12F5229-C44C-413E-84BD-A6EFF5746218");+const TRACK_MOTION: Guid = Guid::parse("CD6915D8-117A-45D6-8CCD-BE37A6C3BC9D");+/// A transition's progress envelope's kind.+const TRANSITION_PROGRESS: i32 = 200;+/// An event's velocity envelope's kind.+const VELOCITY: i32 = 202;++/// The kinds of tracks and events, as the file counts them.+const AUDIO: u32 = 2;+const VIDEO: u32 = 3;++/// Command markers' commands as the file spells them (BananaV's list+/// has `Text` for `TEXT`, `Scott EOM` for `SCOTT EOM`…).+const COMMAND_NAMES: [&str; 14] = [+ "TEXT",+ "URL",+ "Title",+ "Author",+ "Copyright",+ "WMClosedCaption",+ "WMTextBodytext",+ "WMTextHeadline",+ "SCOTT EOM",+ "SCOTT Cue In",+ "608CC1",+ "608CC2",+ "608CC3",+ "608CC4",+];++/// A command as BananaV's list spells it (one not in it as it is).+fn command_in(name: &str) -> String {+ crate::commands::COMMANDS+ .iter()+ .find(|c| c.eq_ignore_ascii_case(name))+ .map_or_else(|| name.to_string(), |c| (*c).to_string())+}++/// A command as the file spells it.+fn command_out(name: &str) -> &str {+ COMMAND_NAMES+ .iter()+ .find(|c| c.eq_ignore_ascii_case(name))+ .copied()+ .unwrap_or(name)+}++/// The fades' and envelopes' curves, as the file numbers them.+fn fade_curve(n: i32) -> crate::fx::FadeCurve {+ use crate::fx::FadeCurve;+ match n {+ 2 => FadeCurve::Fast,+ -2 => FadeCurve::Slow,+ 4 => FadeCurve::Smooth,+ -4 => FadeCurve::Sharp,+ _ => FadeCurve::Linear,+ }+}++fn fade_curve_number(c: crate::fx::FadeCurve) -> i32 {+ use crate::fx::FadeCurve;+ match c {+ FadeCurve::Linear => 1,+ FadeCurve::Fast => 2,+ FadeCurve::Slow => -2,+ FadeCurve::Smooth => 4,+ FadeCurve::Sharp => -4,+ }+}++fn key_curve(n: i32) -> crate::fx::KeyCurve {+ use crate::fx::KeyCurve;+ match n {+ 0 => KeyCurve::Hold,+ 2 => KeyCurve::Fast,+ -2 => KeyCurve::Slow,+ 4 => KeyCurve::Smooth,+ -4 => KeyCurve::Sharp,+ _ => KeyCurve::Linear,+ }+}++/// A keyframe's curve from an effect parameter's interpolation number (the+/// choices, switches and whole numbers have none: they hold).+pub fn interpolation_curve(n: i32) -> crate::fx::KeyCurve {+ use crate::fx::KeyCurve;+ match n {+ 1 => KeyCurve::Linear,+ 2 => KeyCurve::Fast,+ 3 => KeyCurve::Slow,+ 4 => KeyCurve::Smooth,+ 5 => KeyCurve::Sharp,+ 7 | 9 => KeyCurve::Bezier,+ 8 | 10 => KeyCurve::BezierSplit,+ _ => KeyCurve::Hold,+ }+}++fn key_curve_number(c: crate::fx::KeyCurve) -> i32 {+ use crate::fx::KeyCurve;+ match c {+ KeyCurve::Hold => 0,+ KeyCurve::Fast => 2,+ KeyCurve::Slow => -2,+ KeyCurve::Smooth => 4,+ KeyCurve::Sharp => -4,+ KeyCurve::Linear | KeyCurve::Bezier | KeyCurve::BezierSplit => 1,+ }+}diff --git a/crates/timeline/src/veg/pancrop.rs b/crates/timeline/src/veg/pancrop.rsnew file mode 100644index 0000000..be8a31a--- /dev/null+++ b/crates/timeline/src/veg/pancrop.rs@@ -0,0 +1,520 @@+//! An event's Pan/Crop as a `.veg` keeps it: a chunk holding a RIFF of 32 bits+//! (four letters, a size of 4 bytes, its data, each chunk starting on a+//! multiple of 4): its settings, then the box's keyframes and the masks'.++use super::read::{f64_at, i32_at, i64_at, u32_at};+use super::{ticks, units};+use crate::fx::KeyCurve;+use crate::mask::{MaskAnchor, MaskFeather, MaskKey, MaskLook, MaskMode, MaskPath, PanCropMask};+use crate::pancrop::{PanCrop, PanCropKey};++/// A chunk of the inner RIFF.+struct Inner<'a> {+ name: [u8; 4],+ /// A list's type, for lists.+ kind: Option<[u8; 4]>,+ data: &'a [u8],+}++/// The chunks in `b`, one after the other.+fn chunks(b: &[u8]) -> Vec<Inner<'_>> {+ let mut out = Vec::new();+ let mut at = 0usize;+ while at + 8 <= b.len() {+ let name: [u8; 4] = b[at..at + 4].try_into().expect("4 bytes");+ if name == [0; 4] {+ break;+ }+ let size = u32_at(b, at + 4) as usize;+ let Some(end) = at.checked_add(8).and_then(|v| v.checked_add(size)) else {+ break;+ };+ let Some(data) = b.get(at + 8..end) else {+ break;+ };+ if &name == b"LIST" && data.len() >= 4 {+ out.push(Inner {+ name,+ kind: Some(data[..4].try_into().expect("4 bytes")),+ data: &data[4..],+ });+ } else {+ out.push(Inner {+ name,+ kind: None,+ data,+ });+ }+ at = end.next_multiple_of(4);+ }+ out+}++fn list<'a>(all: &'a [Inner<'a>], kind: &[u8; 4]) -> Option<&'a [u8]> {+ all.iter()+ .find(|c| c.kind.as_ref() == Some(kind))+ .map(|c| c.data)+}++fn block<'a>(all: &'a [Inner<'a>], name: &[u8; 4]) -> Option<&'a [u8]> {+ all.iter()+ .find(|c| c.kind.is_none() && &c.name == name)+ .map(|c| c.data)+}++/// The keyframes' curves, as the file numbers them.+pub(super) fn curve(n: u32) -> KeyCurve {+ match n {+ 1 => KeyCurve::Hold,+ 2 => KeyCurve::Slow,+ 3 => KeyCurve::Fast,+ 4 => KeyCurve::Smooth,+ 5 => KeyCurve::Sharp,+ _ => KeyCurve::Linear,+ }+}++pub(super) fn curve_number(c: KeyCurve) -> u32 {+ match c {+ KeyCurve::Hold => 1,+ KeyCurve::Slow => 2,+ KeyCurve::Fast => 3,+ KeyCurve::Smooth => 4,+ KeyCurve::Sharp => 5,+ KeyCurve::Linear | KeyCurve::Bezier | KeyCurve::BezierSplit => 0,+ }+}++/// An anchor's tangents' kind, as the file numbers it: no tangents, split, in+/// line, in line and as long.+const NO_TANGENTS: i32 = -1;+const SPLIT: i32 = 0;+const IN_LINE: i32 = 1;+const EVEN: i32 = 2;++fn anchor(b: &[u8]) -> Option<(i64, MaskAnchor)> {+ if b.len() < 0x40 {+ return None;+ }+ let at = [f64_at(b, 0x08), f64_at(b, 0x10)];+ let before = [f64_at(b, 0x18) - at[0], f64_at(b, 0x20) - at[1]];+ let after = [f64_at(b, 0x28) - at[0], f64_at(b, 0x30) - at[1]];+ let kind = i32_at(b, 0x38);+ Some((+ i64_at(b, 0),+ MaskAnchor {+ at,+ before,+ after,+ split: kind == SPLIT,+ even: kind == EVEN,+ },+ ))+}++/// A path of a keyframe of the file.+struct FilePath {+ id: i64,+ closed: bool,+ look: MaskLook,+ anchors: Vec<(i64, MaskAnchor)>,+}++fn path(b: &[u8]) -> Option<FilePath> {+ let all = chunks(b);+ let h = block(&all, b"PTHB")?;+ if h.len() < 0x2C {+ return None;+ }+ let flags = u32_at(h, 0x18);+ let feather_amount = f64_at(h, 0x10);+ // Files of an older kind leave these below zero.+ let mode = match i32_at(h, 0x28) {+ m if m < 0 => (flags >> 2 & 1) as i32 + 1,+ m => m,+ };+ let opacity = match f64_at(h, 0x20) {+ o if o < 0.0 => 1.0,+ o => o.clamp(0.0, 1.0),+ };+ let feather = match i32_at(h, 0x1C) {+ k if k < 0 => {+ if feather_amount >= 0.0 {+ 2+ } else {+ 1+ }+ }+ k => k,+ };+ let anchors = list(&all, b"ANCL")+ .map(|l| {+ chunks(l)+ .iter()+ .filter(|c| &c.name == b"ANCP")+ .filter_map(|c| anchor(c.data))+ .collect()+ })+ .unwrap_or_default();+ Some(FilePath {+ id: i64_at(h, 0),+ closed: flags & 1 != 0,+ look: MaskLook {+ mode: match mode {+ 0 => MaskMode::Disabled,+ 2 => MaskMode::Negative,+ _ => MaskMode::Positive,+ },+ anti_alias: flags & 2 != 0,+ opacity,+ feather: match feather {+ 1 => MaskFeather::In,+ 2 => MaskFeather::Out,+ 3 => MaskFeather::Both,+ _ => MaskFeather::None,+ },+ feather_pct: feather_amount.abs().min(0.5) * 100.0,+ },+ anchors,+ })+}++/// The masks of the file's keyframes: its paths by their ids, in the order+/// they first come, their anchors in each keyframe by theirs.+fn masks(all: &[Inner<'_>], on: bool, apply_to_fx: bool) -> Option<PanCropMask> {+ struct FileKey {+ at: i64,+ curve: u32,+ paths: Vec<FilePath>,+ }+ let file: Vec<FileKey> = chunks(list(all, b"MSKL")?)+ .iter()+ .filter(|c| c.kind.as_ref() == Some(b"MSKK"))+ .filter_map(|c| {+ let inner = chunks(c.data);+ let h = block(&inner, b"MSKB")?;+ let paths = list(&inner, b"PTHL").map_or_else(Vec::new, |l| {+ chunks(l)+ .iter()+ .filter(|p| p.kind.as_ref() == Some(b"PATH"))+ .filter_map(|p| path(p.data))+ .collect()+ });+ Some(FileKey {+ at: i64_at(h, 0),+ curve: u32_at(h, 0x10),+ paths,+ })+ })+ .collect();+ let mut ids: Vec<i64> = Vec::new();+ for p in file.iter().flat_map(|k| &k.paths) {+ if !ids.contains(&p.id) {+ ids.push(p.id);+ }+ }+ if ids.is_empty() && !on {+ return None;+ }+ // Each path's own settings, its anchors' order: as it first comes.+ let first = |id: i64| file.iter().flat_map(|k| &k.paths).find(|p| p.id == id);+ let paths: Vec<MaskPath> = ids+ .iter()+ .filter_map(|&id| {+ let p = first(id)?;+ Some(MaskPath {+ anchors: p.anchors.iter().map(|a| a.1).collect(),+ mode: p.look.mode,+ anti_alias: p.look.anti_alias,+ opacity: p.look.opacity,+ feather: p.look.feather,+ feather_pct: p.look.feather_pct,+ closed: p.closed,+ })+ })+ .collect();+ let order = |id: i64, own: &FilePath| -> Vec<MaskAnchor> {+ // By the first keyframe's anchors, when this one has them all.+ let Some(lead) = first(id) else {+ return Vec::new();+ };+ let same = lead.anchors.len() == own.anchors.len()+ && lead+ .anchors+ .iter()+ .all(|a| own.anchors.iter().any(|b| b.0 == a.0));+ if same {+ lead.anchors+ .iter()+ .filter_map(|a| own.anchors.iter().find(|b| b.0 == a.0))+ .map(|a| a.1)+ .collect()+ } else {+ own.anchors.iter().map(|a| a.1).collect()+ }+ };+ let keys: Vec<MaskKey> = file+ .iter()+ .map(|k| {+ let found = |id: i64| k.paths.iter().find(|p| p.id == id);+ MaskKey {+ at: ticks(k.at),+ curve: curve(k.curve),+ shapes: ids+ .iter()+ .map(|&id| found(id).map_or_else(Vec::new, |p| order(id, p)))+ .collect(),+ looks: ids+ .iter()+ .zip(&paths)+ .map(|(&id, own)| found(id).map_or_else(|| look_of(own), |p| p.look))+ .collect(),+ }+ })+ .collect();+ Some(PanCropMask {+ enabled: on,+ apply_to_fx,+ paths,+ keys,+ })+}++fn look_of(p: &MaskPath) -> MaskLook {+ MaskLook {+ mode: p.mode,+ anti_alias: p.anti_alias,+ opacity: p.opacity,+ feather: p.feather,+ feather_pct: p.feather_pct,+ }+}++/// A chunk of the inner RIFF, read: the box, and the masks when it has any.+pub(super) fn read(b: &[u8]) -> Option<(PanCrop, Option<PanCropMask>)> {+ let top = chunks(b);+ let root = top.iter().find(|c| c.kind.as_ref() == Some(b"EPCP"))?;+ let all = chunks(root.data);+ let s = block(&all, b"EPCS")?;+ let flags = u32_at(s, 0);+ let size = [u32_at(s, 0x2C), u32_at(s, 0x30)];+ let keys: Vec<PanCropKey> = list(&all, b"POSL")+ .map(|l| {+ chunks(l)+ .iter()+ .filter(|c| &c.name == b"POSK" && c.data.len() >= 0x54)+ .map(|c| {+ let k = c.data;+ PanCropKey {+ at: ticks(i64_at(k, 0)),+ curve: curve(u32_at(k, 0x10)),+ width: f64_at(k, 0x14),+ height: f64_at(k, 0x1C),+ center: [f64_at(k, 0x24), f64_at(k, 0x2C)],+ angle: f64_at(k, 0x34),+ pivot: [f64_at(k, 0x3C), f64_at(k, 0x44)],+ smoothness: f64_at(k, 0x4C),+ crop: [0.0; 4],+ }+ })+ .collect()+ })+ .unwrap_or_default();+ let mask_on = block(&all, b"KFRS").is_some_and(|k| u32_at(k, 0) != 0);+ Some((+ PanCrop {+ size,+ keep_aspect: flags & 1 != 0,+ fill: flags & 2 != 0,+ keys,+ },+ masks(&all, mask_on, flags & 4 != 0),+ ))+}++/// The same chunks written.+struct Out(Vec<u8>);++impl Out {+ fn block(&mut self, name: &[u8; 4], data: &[u8]) {+ self.0.extend_from_slice(name);+ self.0.extend_from_slice(&(data.len() as u32).to_le_bytes());+ self.0.extend_from_slice(data);+ self.0.resize(self.0.len().next_multiple_of(4), 0);+ }++ fn list(&mut self, kind: &[u8; 4], body: impl FnOnce(&mut Out)) {+ self.0.extend_from_slice(b"LIST");+ let at = self.0.len();+ self.0.extend_from_slice(&[0; 4]);+ self.0.extend_from_slice(kind);+ body(self);+ let size = (self.0.len() - at - 4) as u32;+ self.0[at..at + 4].copy_from_slice(&size.to_le_bytes());+ self.0.resize(self.0.len().next_multiple_of(4), 0);+ }+}++fn number(b: &mut [u8], at: usize, v: f64) {+ b[at..at + 8].copy_from_slice(&v.to_le_bytes());+}++fn whole(b: &mut [u8], at: usize, v: u32) {+ b[at..at + 4].copy_from_slice(&v.to_le_bytes());+}++fn long(b: &mut [u8], at: usize, v: i64) {+ b[at..at + 8].copy_from_slice(&v.to_le_bytes());+}++/// A path's anchors at a keyframe, written.+fn path_out(o: &mut Out, id: i64, closed: bool, look: &MaskLook, shape: &[MaskAnchor]) {+ o.list(b"PATH", |o| {+ let mut h = [0u8; 0x2C];+ long(&mut h, 0, id);+ long(&mut h, 8, shape.len() as i64 + 1);+ number(&mut h, 0x10, look.feather_pct / 100.0);+ whole(+ &mut h,+ 0x18,+ u32::from(closed)+ | u32::from(look.anti_alias) << 1+ | u32::from(look.mode == MaskMode::Negative) << 2,+ );+ whole(+ &mut h,+ 0x1C,+ match look.feather {+ MaskFeather::None => 0,+ MaskFeather::In => 1,+ MaskFeather::Out => 2,+ MaskFeather::Both => 3,+ },+ );+ number(&mut h, 0x20, look.opacity);+ whole(+ &mut h,+ 0x28,+ match look.mode {+ MaskMode::Disabled => 0,+ MaskMode::Positive => 1,+ MaskMode::Negative => 2,+ },+ );+ o.block(b"PTHB", &h);+ o.list(b"ANCL", |o| {+ for (k, a) in shape.iter().enumerate() {+ let mut p = [0u8; 0x40];+ long(&mut p, 0, k as i64 + 1);+ number(&mut p, 0x08, a.at[0]);+ number(&mut p, 0x10, a.at[1]);+ number(&mut p, 0x18, a.at[0] + a.before[0]);+ number(&mut p, 0x20, a.at[1] + a.before[1]);+ number(&mut p, 0x28, a.at[0] + a.after[0]);+ number(&mut p, 0x30, a.at[1] + a.after[1]);+ let bare = a.before == [0.0; 2] && a.after == [0.0; 2];+ let kind = if bare {+ NO_TANGENTS+ } else if a.split {+ SPLIT+ } else if a.even {+ EVEN+ } else {+ IN_LINE+ };+ whole(&mut p, 0x38, kind as u32);+ o.block(b"ANCP", &p);+ }+ });+ });+}++/// What the Pan/Crop chunk holds for an event's Pan/Crop and masks: `None`+/// when it is as a new event's, which has none.+pub(super) fn write(+ p: &PanCrop,+ mask: Option<&PanCropMask>,+ media: [u32; 2],+ fallback: &[PanCropKey],+) -> Option<Vec<u8>> {+ let masked = mask.is_some_and(|m| !m.paths.is_empty() || m.enabled);+ if p.is_default() && !masked {+ return None;+ }+ let mut o = Out(Vec::new());+ o.list(b"EPCP", |o| {+ let mut s = vec![0u8; 0x23C];+ whole(+ &mut s,+ 0,+ u32::from(p.keep_aspect)+ | u32::from(p.fill) << 1+ | u32::from(mask.is_some_and(|m| m.apply_to_fx)) << 2,+ );+ number(&mut s, 0x04, 1.0);+ whole(&mut s, 0x1C, 16);+ long(&mut s, 0x20, mask.map_or(1, |m| m.paths.len() as i64 + 1));+ whole(&mut s, 0x28, 1);+ whole(&mut s, 0x2C, media[0]);+ whole(&mut s, 0x30, media[1]);+ o.block(b"EPCS", &s);+ let mut k = [0u8; 8];+ whole(&mut k, 0, u32::from(mask.is_some_and(|m| m.enabled)));+ o.block(b"KFRS", &k);+ o.list(b"POSL", |o| {+ let keys = if p.keys.is_empty() { fallback } else { &p.keys };+ for key in keys {+ let mut b = [0u8; 0x54];+ long(&mut b, 0, units(key.at));+ whole(&mut b, 0x10, curve_number(key.curve));+ number(&mut b, 0x14, key.width);+ number(&mut b, 0x1C, key.height);+ number(&mut b, 0x24, key.center[0]);+ number(&mut b, 0x2C, key.center[1]);+ number(&mut b, 0x34, key.angle);+ number(&mut b, 0x3C, key.pivot[0]);+ number(&mut b, 0x44, key.pivot[1]);+ number(&mut b, 0x4C, key.smoothness);+ o.block(b"POSK", &b);+ }+ });+ o.list(b"MSKL", |o| {+ let empty;+ let m = match mask {+ Some(m) => m,+ None => {+ empty = PanCropMask::default();+ &empty+ }+ };+ let own: Vec<MaskKey>;+ let keys: &[MaskKey] = if m.keys.is_empty() {+ own = vec![MaskKey {+ at: bv_core::Tick::ZERO,+ shapes: m.paths.iter().map(|p| p.anchors.clone()).collect(),+ curve: KeyCurve::Linear,+ looks: Vec::new(),+ }];+ &own+ } else {+ &m.keys+ };+ for key in keys {+ o.list(b"MSKK", |o| {+ let mut b = [0u8; 0x14];+ long(&mut b, 0, units(key.at));+ whole(&mut b, 0x10, curve_number(key.curve));+ o.block(b"MSKB", &b);+ o.list(b"PTHL", |o| {+ for (i, path) in m.paths.iter().enumerate() {+ let look = key.looks.get(i).copied().unwrap_or_else(|| look_of(path));+ let shape = key.shapes.get(i).map_or(&[][..], |s| &s[..]);+ path_out(o, i as i64 + 1, path.closed, &look, shape);+ }+ });+ });+ }+ });+ });+ Some(o.0)+}diff --git a/crates/timeline/src/veg/read.rs b/crates/timeline/src/veg/read.rsnew file mode 100644index 0000000..221d71f--- /dev/null+++ b/crates/timeline/src/veg/read.rs@@ -0,0 +1,1090 @@+//! A `.veg` read: its chunks' structures decoded into a [`Document`].++use super::riff::{self, Chunk, VegError};+use super::*;++/// A media of the project: a file (its path as the project has it) or a+/// generated one (`META:\…`), by the id its takes use.+#[derive(Clone, Debug, PartialEq)]+pub struct DocMedia {+ pub id: u32,+ pub path: String,+ pub generated: bool,+}++/// The project's settings.+#[derive(Clone, Debug, Default, PartialEq)]+pub(crate) struct DocSettings {+ pub width: u32,+ pub height: u32,+ pub frame_rate: f64,+ /// 28: 8-bit full range; 32: 32-bit floating point full range.+ pub pixel_format: u32,+ pub pixel_aspect: f64,+ /// The ruler's timecode: 7 SMPTE 30, 8 drop frame, 9 EBU.+ pub timecode: u32,+ pub beats_per_minute: f64,+ pub beats_per_measure: u16,+ pub beat_note: u16,+ pub sample_rate: u32,+ pub prerender_folder: String,+ pub recorded_folder: String,+}++#[derive(Clone, Debug, PartialEq)]+pub(crate) struct DocTake {+ pub media: u32,+ pub stream: u32,+ /// Where it starts in its media.+ pub offset: i64,+ /// How much of its media is left after that.+ pub remain: i64,+ pub name: String,+}++#[derive(Clone, Debug, PartialEq)]+pub(crate) struct DocEnvelope {+ pub kind: i32,+ /// Time, value, curve to the next.+ pub points: Vec<(i64, f32, i32)>,+}++#[derive(Clone, Debug, PartialEq)]+pub(crate) struct DocEvent {+ pub id: u64,+ pub start: i64,+ pub length: i64,+ pub muted: bool,+ pub name: String,+ pub speed: f64,+ pub fade_in: i64,+ pub fade_out: i64,+ pub curves: [i32; 2],+ /// Its level (the gain its fades go to and come from): its volume, a+ /// video event's opacity.+ pub level: f32,+ /// Which of `takes` plays (−1: none).+ pub active: i32,+ pub takes: Vec<DocTake>,+ /// Audio: its pitch change, in semitones.+ pub pitch: f64,+ pub envelopes: Vec<DocEnvelope>,+ pub effects: Vec<DocEffect>,+ /// Audio: its effects' chain, and whether a chain could not be read.+ pub audio_fx: Vec<DocAudioFx>,+ pub audio_unread: bool,+ /// Its Pan/Crop, when it has one of its own, and its masks.+ pub pan_crop: Option<crate::pancrop::PanCrop>,+ pub mask: Option<crate::mask::PanCropMask>,+ /// Video: its Pan/Crop's Maintain aspect ratio, kept apart from it.+ pub keep_aspect: bool,+ /// Video: its switches' word.+ pub video_flags: u32,+ /// Video: the share of its frames it shows.+ pub undersample: f64,+ /// Video: the transitions of its fade in and of its fade out, and+ /// their progress envelopes.+ pub transition_in: Option<DocEffect>,+ pub transition_out: Option<DocEffect>,+ pub progress_in: Option<DocEnvelope>,+ /// Audio: the gain Normalize gave it, when it is on.+ pub normalize: Option<f32>,+ /// Audio: how its channels play (1000 as they are, 1005 mixed to one).+ pub channels: u32,+ pub invert_phase: bool,+}++/// A keyframe of a Track Motion: its curve and time (100 ns), and in the+/// file's terms (half the height's and the height's parts, radians) where+/// it turns around, where it is, its size and its rotation.+#[derive(Clone, Debug, Default, PartialEq)]+pub(crate) struct DocMotionKey {+ pub curve: i32,+ pub at: i64,+ pub pivot: [f64; 3],+ pub position: [f64; 3],+ pub size: [f64; 3],+ pub rotation: [f64; 3],+ pub smoothness: f64,+ /// A shadow's or a glow's: blue, green, red, alpha.+ pub color: [f32; 4],+ pub blur: f64,+ pub intensity: f64,+}++/// A track's motion: its switches' word, the project's shape it was made+/// for (1 in a parent's) and its three lists of keyframes.+#[derive(Clone, Debug, Default, PartialEq)]+pub(crate) struct DocMotion {+ pub flags: u32,+ pub aspect: f64,+ pub moves: Vec<DocMotionKey>,+ pub shadow: Vec<DocMotionKey>,+ pub glow: Vec<DocMotionKey>,+}++/// An audio bus of the mixer: which (2 the Master, 7 the Preview, 3 on the+/// ones made), its fader's gain, its switches, its name, its effects and+/// its envelopes.+#[derive(Clone, Debug, Default, PartialEq)]+pub(crate) struct DocBus {+ pub id: u32,+ pub name: String,+ pub gain: f64,+ pub muted: bool,+ pub solo: bool,+ pub effects: Vec<DocAudioFx>,+ pub envelopes: Vec<DocEnvelope>,+}++/// An audio plug-in of a chain: its class (a DirectX plug-in's CLSID), its+/// name and its settings (their format's GUID, then the plug-in's own).+#[derive(Clone, Debug, PartialEq)]+pub(crate) struct DocAudioFx {+ pub class: riff::Guid,+ pub name: String,+ pub settings: Vec<u8>,+ pub bypass: bool,+}++#[derive(Clone, Debug, PartialEq)]+pub(crate) struct DocTrack {+ pub kind: u32,+ pub name: String,+ pub muted: bool,+ pub volume: f32,+ pub pan: f32,+ /// Video: its compositing mode (4 Source Alpha) and level.+ pub composite_mode: u32,+ pub composite_level: f32,+ /// Audio: its polarity reversed.+ pub invert_phase: bool,+ /// Audio: its send to each bus, as a linear gain (0: none).+ pub sends: Vec<f32>,+ /// Video: how far in it is among compositing children.+ pub composite_depth: u8,+ /// Video: its Track Motion and its Parent Motion.+ pub motion: Option<DocMotion>,+ pub parent_motion: Option<DocMotion>,+ pub events: Vec<DocEvent>,+ pub envelopes: Vec<DocEnvelope>,+ pub effects: Vec<DocEffect>,+ /// Audio: its effects' chain (a new track's has three), and whether+ /// it could not be read.+ pub audio_fx: Vec<DocAudioFx>,+ pub audio_unread: bool,+}++#[derive(Clone, Debug, PartialEq)]+pub(crate) struct DocMarker {+ pub time: i64,+ pub length: i64,+ pub number: u32,+ pub region: bool,+ pub label: String,+}++#[derive(Clone, Debug, PartialEq)]+pub(crate) struct DocCommand {+ pub time: i64,+ pub comment: String,+ pub command: String,+ pub parameter: String,+}++#[derive(Clone, Debug, PartialEq)]+pub(crate) struct DocCd {+ pub time: i64,+ pub length: i64,+ pub index: bool,+ pub name: String,+}++#[derive(Clone, Debug, PartialEq)]+pub(crate) struct DocBin {+ pub name: String,+ pub parent: Option<usize>,+ pub media: Vec<u32>,+}++/// A project read from a `.veg`, its media still to be found (see+/// [`super::build`]).+#[derive(Clone, Debug, Default, PartialEq)]+pub struct Document {+ /// Its format's version (0x160000: VEGAS Pro 23; 0x170000: 2026).+ pub version: u32,+ pub media: Vec<DocMedia>,+ pub(crate) settings: DocSettings,+ pub(crate) tracks: Vec<DocTrack>,+ pub(crate) markers: Vec<DocMarker>,+ pub(crate) commands: Vec<DocCommand>,+ pub(crate) cd: Vec<DocCd>,+ /// Each group's events.+ pub(crate) groups: Vec<Vec<u64>>,+ /// Title, artist, engineer, copyright, comments.+ pub(crate) summary: [String; 5],+ /// The audio busses made besides the Master.+ pub(crate) busses: usize,+ /// The mixer's busses as the file keeps them.+ pub(crate) bus_list: Vec<DocBus>,+ pub(crate) bins: Vec<DocBin>,+ pub(crate) output_fx: Vec<DocEffect>,+ pub(crate) envelopes: Vec<DocEnvelope>,+}++// Little-endian numbers at an offset; 0 past the end.+fn u16_at(b: &[u8], at: usize) -> u16 {+ b.get(at..at + 2)+ .map_or(0, |s| u16::from_le_bytes([s[0], s[1]]))+}++pub(crate) fn u32_at(b: &[u8], at: usize) -> u32 {+ b.get(at..at + 4)+ .map_or(0, |s| u32::from_le_bytes(s.try_into().expect("4 bytes")))+}++pub(super) fn i32_at(b: &[u8], at: usize) -> i32 {+ u32_at(b, at) as i32+}++fn u64_at(b: &[u8], at: usize) -> u64 {+ b.get(at..at + 8)+ .map_or(0, |s| u64::from_le_bytes(s.try_into().expect("8 bytes")))+}++pub(super) fn i64_at(b: &[u8], at: usize) -> i64 {+ u64_at(b, at) as i64+}++fn f32_at(b: &[u8], at: usize) -> f32 {+ f32::from_bits(u32_at(b, at))+}++pub(super) fn f64_at(b: &[u8], at: usize) -> f64 {+ f64::from_bits(u64_at(b, at))+}++fn guid_at(b: &[u8], at: usize) -> Option<riff::Guid> {+ b.get(at..at.checked_add(16)?)+ .map(|s| riff::Guid(s.try_into().expect("16 bytes")))+}++/// The plug-ins of an audio effects chain. After its header — its kind,+/// a version, a plug-in's class and name, two numbers, the sound's format+/// (a `WAVEFORMATEX` and what it adds) and a number — their count and a+/// number, then each its class, a number, its name, its class again, its+/// settings' size twice and its settings. `None` where they do not fit.+pub(super) fn audio_chain(b: &[u8]) -> Option<Vec<DocAudioFx>> {+ let name = u32_at(b, 0x24) as usize;+ if b.len() < 0x28 || name > 1024 {+ return None;+ }+ let format = 0x28 + name + 8;+ let mut at = format + 18 + usize::from(u16_at(b, format + 16)) + 4;+ let count = u32_at(b, at) as usize;+ at += 8;+ let mut out = Vec::new();+ for _ in 0..count.min(256) {+ let class = guid_at(b, at)?;+ let bypass = u32_at(b, at + 16) != 0;+ let len = u32_at(b, at + 20) as usize;+ if len > 1024 {+ return None;+ }+ let name = text_at(b, at + 24, len);+ let p = at + 24 + len;+ if guid_at(b, p)? != class {+ return None;+ }+ let size = u32_at(b, p + 16) as usize;+ let settings = b.get(p + 24..p + 24 + size)?.to_vec();+ out.push(DocAudioFx {+ class,+ name,+ settings,+ bypass,+ });+ at = p + 24 + size;+ }+ Some(out)+}++/// UTF-16 text of `bytes` bytes at `at`, up to its zero.+fn text_at(b: &[u8], at: usize, bytes: usize) -> String {+ let end = at.saturating_add(bytes).min(b.len());+ let units: Vec<u16> = b+ .get(at..end)+ .unwrap_or(&[])+ .as_chunks::<2>()+ .0+ .iter()+ .map(|c| u16::from_le_bytes(*c))+ .take_while(|&c| c != 0)+ .collect();+ String::from_utf16_lossy(&units)+}++/// Texts one after the other from `at`, each `lens[i]` bytes; where they+/// end.+fn texts_at(b: &[u8], at: usize, lens: &[u32]) -> (Vec<String>, usize) {+ let mut at = at;+ let mut out = Vec::with_capacity(lens.len());+ for &n in lens {+ out.push(text_at(b, at, n as usize));+ at += n as usize;+ }+ (out, at)+}++/// A list of tags (`u32` 8, `u32` n, then each a four-letter code, a+/// `u32` byte count and its text).+fn tags(b: &[u8]) -> Vec<([u8; 4], String)> {+ let n = u32_at(b, 4) as usize;+ let mut at = u32_at(b, 0) as usize;+ let mut out = Vec::new();+ for _ in 0..n.min(4096) {+ if at + 8 > b.len() {+ break;+ }+ let code = [b[at], b[at + 1], b[at + 2], b[at + 3]];+ let len = u32_at(b, at + 4) as usize;+ out.push((code, text_at(b, at + 8, len)));+ at += 8 + len;+ }+ out+}++fn settings(header: &[u8], mixer: Option<&[u8]>) -> DocSettings {+ let cb = u32_at(header, 0) as usize;+ let lens = [0x3C, 0x40, 0x44, 0x6C].map(|o| u32_at(header, o));+ let (_, after) = texts_at(header, cb, &lens);+ let items = u32_at(header, 0x38) as usize;+ let mut s = DocSettings {+ frame_rate: f64_at(header, 0x10),+ timecode: u32_at(header, 0x08),+ beats_per_minute: f64_at(header, 0x18),+ beat_note: u16_at(header, 0x28),+ beats_per_measure: u16_at(header, 0x2A),+ sample_rate: 48_000,+ pixel_format: 28,+ pixel_aspect: 1.0,+ ..Default::default()+ };+ // The first video item is the project's.+ if items > 0 && u32_at(header, after) == 0x358 {+ let item = &header[after..];+ s.width = u32_at(item, 0x04);+ s.height = u32_at(item, 0x08);+ s.pixel_format = u32_at(item, 0x0C);+ let fps = f64_at(item, 0x38);+ if fps > 0.0 {+ s.frame_rate = fps;+ }+ let aspect = f64_at(item, 0x40);+ if aspect > 0.0 {+ s.pixel_aspect = aspect;+ }+ }+ if let Some(m) = mixer+ && m.len() >= 0x6E8+ {+ let rate = u32_at(m, 0x6E4);+ if rate > 0 {+ s.sample_rate = rate;+ }+ }+ s+}++fn media(b: &[u8]) -> DocMedia {+ let cb = u32_at(b, 0) as usize;+ let path = text_at(b, cb, u32_at(b, 0x24) as usize);+ DocMedia {+ id: u32_at(b, 0x3C),+ generated: path.to_ascii_uppercase().starts_with("META:\\"),+ path,+ }+}++/// An envelope (its structure, then its points) and where it ends.+fn envelope(b: &[u8]) -> (DocEnvelope, usize) {+ let cb = u32_at(b, 0) as usize;+ let n = u32_at(b, 0x18) as usize;+ let size = match u32_at(b, 0x34) as usize {+ 0 => 0x38,+ s => s.max(0x10),+ };+ let points: Vec<_> = (0..n.min(1 << 20))+ .map(|k| cb + k * size)+ .take_while(|&at| at + 0x10 <= b.len())+ .map(|at| (i64_at(b, at), f32_at(b, at + 8), i32_at(b, at + 0x0C)))+ .collect();+ let end = cb + points.len() * size;+ (+ DocEnvelope {+ kind: i32_at(b, 8),+ points,+ },+ end,+ )+}++/// The envelopes of a list (its header, then one chunk each).+fn envelopes(list: Option<&Chunk<'_>>) -> Vec<DocEnvelope> {+ list.map_or_else(Vec::new, |l| {+ l.blocks(ENVELOPE).map(|c| envelope(c.data).0).collect()+ })+}++/// An effect's body from `at` (a filter's chunk, a transition inside its+/// event's) and where it ends: an OpenFX plug-in's, or one of the file's own+/// kind, known by its class and its preset's name.+fn effect_at(b: &[u8], at: usize) -> Option<(DocEffect, usize)> {+ let cb = u32_at(b, at) as usize;+ if cb == 0x38 {+ let name = u32_at(b, at + 0x34) as usize;+ let size = u32_at(b, at + 0x14) as usize;+ let keys = u32_at(b, at + 0x18) as usize;+ let mut end = at + 0x38 + name + size;+ for _ in 0..keys.min(1 << 16) {+ if u32_at(b, end) != 0x1C {+ break;+ }+ end += 0x1C + u32_at(b, end + 0x18) as usize;+ }+ return Some((+ DocEffect {+ native: guid_at(b, at + 4).map(|g| format!("{g:?}")),+ native_data: b+ .get(at + 0x38 + name..at + 0x38 + name + size)+ .unwrap_or(&[])+ .to_vec(),+ preset: text_at(b, at + 0x38, name),+ ..Default::default()+ },+ end.min(b.len()),+ ));+ }+ if !(0x30..=0x100).contains(&cb) || b.get(at + 4..at + 20) != Some(&OFX_HOST.0[..]) {+ return None;+ }+ let (t, after) = texts_at(b, at + cb, &[u32_at(b, at + 0x28), u32_at(b, at + 0x2C)]);+ // `{Svfx:com.vegascreativesoftware:sepia}`: the id inside.+ let plugin = t[0]+ .trim_start_matches('{')+ .trim_end_matches('}')+ .split_once(':')+ .map_or_else(|| t[0].clone(), |(_, id)| id.to_string());+ let flags = u32_at(b, at + 0x20);+ let mut fx = DocEffect {+ plugin,+ preset: t[1].clone(),+ bypass: flags & 1 != 0,+ before_pan_crop: flags & 0x80 != 0,+ transition: u32_at(b, at + 0x14) == 5,+ ..Default::default()+ };+ let mut end = after;+ if after + 8 <= b.len() {+ end = after + 8 + u32_at(b, after) as usize;+ let n = u32_at(b, after + 4) as usize;+ let (params, keys) = params_with_keys(b, after + 8, n);+ fx.params = params;+ fx.keys = keys;+ }+ Some((fx, end.min(b.len())))+}++/// An effect's chunk; `None` for one this reader cannot place.+fn effect(b: &[u8]) -> Option<DocEffect> {+ effect_at(b, 0).map(|(fx, _)| fx)+}++/// How a parameter's value and keyframes are kept: the value's bytes, a+/// keyframe's bytes, and how many numbers have handles.+const PARAM_SHAPES: [(usize, usize, usize); 6] = [+ (4, 16, 0),+ (8, 52, 1),+ (16, 92, 2),+ (24, 132, 3),+ (24, 36, 0),+ (32, 44, 0),+];++/// A value of `bytes` bytes: a whole number in 4, else numbers of 8.+fn numbers_at(b: &[u8], at: usize, bytes: usize) -> Vec<f64> {+ if bytes == 4 {+ return vec![f64::from(i32_at(b, at))];+ }+ (0..bytes / 8).map(|k| f64_at(b, at + 8 * k)).collect()+}++/// A parameter's body of `size` bytes: its value (`None` if it is not one+/// this reader knows) and its keyframes.+fn param_body(b: &[u8], at: usize, size: usize) -> (Option<ParamValue>, Vec<DocKey>) {+ if at + size > b.len() || size < 4 {+ return (None, Vec::new());+ }+ // A text: its bytes, the text with its end, no keyframes.+ let len = u32_at(b, at) as usize;+ if len >= 2+ && len.is_multiple_of(2)+ && len + 8 == size+ && b[at + 4 + len - 1] == 0+ && b[at + 4 + len - 2] == 0+ && u32_at(b, at + size - 4) == 0+ {+ return (Some(ParamValue::Text(text_at(b, at + 4, len))), Vec::new());+ }+ let mut keys = Vec::new();+ let mut value_bytes = None;+ for (value, key, handled) in PARAM_SHAPES {+ if value + 4 > size {+ continue;+ }+ let n = u32_at(b, at + value) as usize;+ if n == 0 || value + 4 + n * key != size {+ continue;+ }+ value_bytes = Some(value);+ for k in 0..n {+ let p = at + value + 4 + k * key;+ let values = p + 12;+ let anchors = values + value;+ keys.push(DocKey {+ frame: f64_at(b, p),+ interpolation: i32_at(b, p + 8),+ value: numbers_at(b, values, value),+ handles: (0..handled)+ .map(|c| {+ let one = |group: usize| f64_at(b, anchors + group * value + c * 8);+ [one(0), one(1), one(2), one(3)]+ })+ .collect(),+ });+ }+ break;+ }+ if value_bytes.is_none() && u32_at(b, at + size - 4) == 0 {+ value_bytes = Some(size - 4);+ }+ let value = value_bytes.and_then(|bytes| match bytes {+ 4 => Some(ParamValue::Integer(i64::from(i32_at(b, at)))),+ 8 => Some(ParamValue::Number(f64_at(b, at))),+ n if n > 8 && n.is_multiple_of(8) => Some(ParamValue::Numbers(numbers_at(b, at, n))),+ _ => None,+ });+ (value, keys)+}++/// An effect's parameters, by their names, and their keyframes.+type ParamsAndKeys = (Vec<(String, ParamValue)>, Vec<(String, Vec<DocKey>)>);++/// The `n` parameters of an effect from `at`, and the keyframes of those+/// that have them.+fn params_with_keys(b: &[u8], mut at: usize, n: usize) -> ParamsAndKeys {+ let mut params = Vec::new();+ let mut keys = Vec::new();+ for _ in 0..n.min(4096) {+ let size = u32_at(b, at) as usize;+ let len = u32_at(b, at + 4) as usize;+ let value_at = at + 8 + len;+ if len == 0+ || !len.is_multiple_of(2)+ || len > 512+ || size > 1 << 24+ || value_at + size > b.len()+ {+ break;+ }+ let name = text_at(b, at + 8, len);+ if name.is_empty() || !name.chars().all(|c| c.is_ascii_graphic() || c == ' ') {+ break;+ }+ let (value, its_keys) = param_body(b, value_at, size);+ if !its_keys.is_empty() {+ keys.push((name.clone(), its_keys));+ }+ if let Some(v) = value {+ params.push((name, v));+ }+ at = value_at + size;+ }+ (params, keys)+}++/// The `n` parameters of an effect from `at`.+#[cfg(test)]+pub(super) fn params_at(b: &[u8], at: usize, n: usize) -> Vec<(String, ParamValue)> {+ params_with_keys(b, at, n).0+}++fn effects(list: Option<&Chunk<'_>>) -> Vec<DocEffect> {+ list.map_or_else(Vec::new, |l| {+ l.blocks(EFFECT).filter_map(|c| effect(c.data)).collect()+ })+}++fn take(b: &[u8]) -> DocTake {+ let cb = u32_at(b, 0) as usize;+ DocTake {+ media: u32_at(b, 0x24),+ stream: u32_at(b, 0x08),+ offset: i64_at(b, 0x10),+ remain: i64_at(b, 0x18),+ name: text_at(b, cb, u32_at(b, 0x20) as usize),+ }+}++fn event(list: &Chunk<'_>) -> Option<DocEvent> {+ let h = list.block(EVENT_HEADER)?.data;+ let cb = u32_at(h, 0) as usize;+ let (name, after) = texts_at(h, cb, &[u32_at(h, 0x24)]);+ let mut e = DocEvent {+ id: u64_at(h, 0x40),+ start: i64_at(h, 0x10),+ length: i64_at(h, 0x18),+ muted: u32_at(h, 0x04) & 2 != 0,+ name: name[0].clone(),+ speed: f64_at(h, 0x28),+ fade_in: 0,+ fade_out: 0,+ curves: [1, 1],+ level: 1.0,+ active: i32_at(h, 0x20),+ takes: list.blocks(TAKE).map(|c| take(c.data)).collect(),+ pitch: 0.0,+ envelopes: envelopes(list.list(EVENT_ENVELOPES)),+ effects: effects(list.list(EVENT_FX)),+ audio_fx: Vec::new(),+ audio_unread: false,+ pan_crop: None,+ mask: None,+ keep_aspect: true,+ video_flags: 0x201,+ undersample: 1.0,+ transition_in: None,+ transition_out: None,+ progress_in: None,+ normalize: None,+ channels: 1000,+ invert_phase: false,+ };+ if let Some((box_, mask)) = list+ .block(PAN_CROP)+ .and_then(|c| super::pancrop::read(c.data))+ {+ e.pan_crop = Some(box_);+ e.mask = mask;+ }+ if let Some(l) = list.list(AUDIO_EVENT_FX) {+ match l.block(AUDIO_EVENT_FX).and_then(|c| audio_chain(c.data)) {+ Some(chain) => e.audio_fx = chain,+ None => e.audio_unread = true,+ }+ }+ if !(e.speed.is_finite() && e.speed > 0.0) {+ e.speed = 1.0;+ }+ if u32_at(h, after) == 0x48 {+ let level = f32_at(h, after + 0x0C);+ if level.is_finite() && level >= 0.0 {+ e.level = level;+ }+ if u32_at(h, 0x04) & 0x200 != 0 {+ e.normalize = Some(f32_at(h, after + 0x10)).filter(|g| g.is_finite() && *g > 0.0);+ }+ e.curves = [i32_at(h, after + 0x14), i32_at(h, after + 0x18)];+ e.fade_in = i64_at(h, after + 0x28);+ e.fade_out = i64_at(h, after + 0x30);+ }+ if let Some(a) = list.list(AUDIO_EVENT).and_then(|l| l.block(AUDIO_EVENT)) {+ let pitch = f64_at(a.data, 0x14);+ if pitch.is_finite() {+ e.pitch = pitch;+ }+ e.channels = u32_at(a.data, 0x04);+ e.invert_phase = u32_at(a.data, 0x08) & 1 != 0;+ }+ if let Some(v) = list.list(VIDEO_EVENT_LIST) {+ if let Some(h) = v.block(VIDEO_EVENT) {+ let b = h.data;+ e.video_flags = u32_at(b, 0x04);+ e.keep_aspect = e.video_flags & 1 != 0;+ let rate = f64_at(b, 0x78);+ if rate.is_finite() && rate > 0.0 && rate <= 1.0 {+ e.undersample = rate;+ }+ // The transitions after its structure: the fade in's, the fade out's.+ let mut at = u32_at(b, 0) as usize;+ for (n, place) in [+ (u32_at(b, 0x70), &mut e.transition_in),+ (u32_at(b, 0x74), &mut e.transition_out),+ ] {+ for k in 0..n.min(16) {+ let Some((fx, end)) = effect_at(b, at) else {+ break;+ };+ at = end;+ if k == 0 {+ *place = Some(fx);+ }+ }+ }+ }+ // Their progress: of the fade in. The fade out has no place of its own.+ e.progress_in = envelopes(v.list(VIDEO_EVENT_ENVELOPES_1))+ .into_iter()+ .find(|x| x.kind == TRANSITION_PROGRESS);+ }+ Some(e)+}++fn track(list: &Chunk<'_>) -> Option<DocTrack> {+ let h = list.block(TRACK_HEADER)?.data;+ let cb = u32_at(h, 0) as usize;+ let name = text_at(h, cb, u32_at(h, 0x10) as usize);+ let mut t = DocTrack {+ kind: u32_at(h, 0x0C),+ name,+ muted: u32_at(h, 0x04) & 1 != 0,+ volume: 1.0,+ pan: 0.0,+ composite_mode: 4,+ composite_level: 1.0,+ invert_phase: false,+ sends: Vec::new(),+ composite_depth: 0,+ motion: list+ .list(TRACK_MOTION_LIST)+ .and_then(|l| l.block(TRACK_MOTION))+ .map(|c| motion(c.data)),+ parent_motion: list+ .list(PARENT_MOTION_LIST)+ .and_then(|l| l.block(TRACK_MOTION))+ .map(|c| motion(c.data)),+ events: list+ .list(TRACK_HEADER)+ .map_or_else(Vec::new, |l| l.lists(EVENT).filter_map(event).collect()),+ envelopes: envelopes(list.list(TRACK_ENVELOPES)),+ effects: effects(list.list(TRACK_FX)),+ audio_fx: Vec::new(),+ audio_unread: false,+ };+ if let Some(l) = list.list(AUDIO_TRACK_FX) {+ match l.block(AUDIO_TRACK_FX).and_then(|c| audio_chain(c.data)) {+ Some(chain) => t.audio_fx = chain,+ None => t.audio_unread = true,+ }+ }+ t.effects.extend(effects(list.list(TRACK_FX_2)));+ if let Some(a) = list+ .list(AUDIO_TRACK_LIST)+ .and_then(|l| l.block(AUDIO_TRACK))+ {+ let (v, p) = (f32_at(a.data, 0x0C), f32_at(a.data, 0x10));+ if v.is_finite() && v >= 0.0 {+ t.volume = v;+ }+ if p.is_finite() {+ t.pan = p.clamp(-1.0, 1.0);+ }+ t.invert_phase = u32_at(a.data, 0x1FC) != 0;+ t.sends = (0..26).map(|k| f32_at(a.data, 0x124 + 8 * k)).collect();+ }+ if let Some(v) = list+ .list(VIDEO_TRACK_LIST)+ .and_then(|l| l.block(VIDEO_TRACK))+ {+ t.composite_mode = u32_at(v.data, 0x64);+ t.composite_depth = u32_at(v.data, 0xAC).min(16) as u8;+ let level = f32_at(v.data, 0x68);+ if level.is_finite() {+ t.composite_level = level.clamp(0.0, 1.0);+ }+ }+ Some(t)+}++/// A track's motion chunk: its structure, then three lists of keyframes.+pub(super) fn motion(b: &[u8]) -> DocMotion {+ let mut m = DocMotion {+ flags: u32_at(b, 4),+ aspect: f64_at(b, 0x14),+ ..Default::default()+ };+ let lists = (u32_at(b, 0x1C) as usize).min(3);+ let mut at = u32_at(b, 0) as usize;+ for l in 0..lists {+ let n = u32_at(b, at) as usize;+ at += 4;+ let mut keys = Vec::new();+ for _ in 0..n.min(1 << 16) {+ let size = u32_at(b, at) as usize;+ if size < 0xB8 || at + size > b.len() {+ break;+ }+ let three = |o: usize| {+ [+ f64_at(b, at + o),+ f64_at(b, at + o + 8),+ f64_at(b, at + o + 16),+ ]+ };+ let mut k = DocMotionKey {+ curve: i32_at(b, at + 4),+ at: i64_at(b, at + 8),+ pivot: three(0x10),+ position: three(0x30),+ size: three(0x50),+ rotation: three(0x70),+ ..Default::default()+ };+ if size >= 0xDC {+ k.smoothness = f64_at(b, at + 0xB0);+ } else {+ k.color = [0, 4, 8, 12].map(|o| f32_at(b, at + 0xB0 + o));+ k.blur = f64_at(b, at + 0xC0);+ k.intensity = f64_at(b, at + 0xC8);+ k.smoothness = f64_at(b, at + 0xD0);+ }+ keys.push(k);+ at += size;+ }+ match l {+ 0 => m.moves = keys,+ 1 => m.shadow = keys,+ _ => m.glow = keys,+ }+ }+ m+}++/// A bus's chunk: a number, its structure of 200 bytes (which, its fader, its+/// switches, how long its texts are, how many items its list has), the+/// bytes of the rest, its texts, then blocks with their sizes: two, the+/// list (its last item its envelopes), its effects' chain and one more.+fn bus(b: &[u8]) -> Option<DocBus> {+ if u32_at(b, 0) != 200 || b.len() < 212 {+ return None;+ }+ let s = 4usize;+ let (t, mut at) = texts_at(+ b,+ s + 200 + 4,+ &[0x7C, 0x80, 0x84, 0x9C].map(|o| u32_at(b, s + o)),+ );+ let items = u32_at(b, s + 0x88) as usize;+ let id = u32_at(b, s + 8);+ let block = |at: &mut usize, numbered: bool| -> Option<(usize, usize)> {+ if numbered {+ *at += 4;+ }+ let n = usize::try_from(u64_at(b, *at)).ok()?;+ *at += 8;+ let from = *at;+ *at = at.checked_add(n)?;+ (*at <= b.len()).then_some((from, n))+ };+ let mut d = DocBus {+ id,+ name: t.get(1).cloned().unwrap_or_default(),+ gain: f64_at(b, s + 0x14),+ muted: u32_at(b, 0x5C) != 0,+ solo: u32_at(b, 0x60) != 0,+ ..Default::default()+ };+ block(&mut at, true)?;+ block(&mut at, true)?;+ let mut last = None;+ for _ in 0..items.min(1 << 16) {+ last = Some(block(&mut at, false)?);+ }+ if id != 5 {+ let (from, n) = block(&mut at, true)?;+ if n >= 40 {+ d.effects = audio_chain(&b[from..from + n]).unwrap_or_default();+ }+ }+ // The last item: a number, its properties, the envelopes' header, how+ // many and the envelopes.+ if let Some((from, n)) = last+ && n >= 4 + 0x23C + 0x4C+ {+ let item = &b[from..from + n];+ let mut p = 4 + 0x23C + 0x4C;+ for _ in 0..u32_at(item, 4 + 0x23C + 0x48).min(64) {+ let Some(rest) = item.get(p..) else {+ break;+ };+ if rest.len() < 0x4C {+ break;+ }+ let (e, end) = envelope(rest);+ d.envelopes.push(e);+ p += end;+ }+ }+ Some(d)+}++/// A marker's chunk: time, length, number, flags, its two texts and its+/// four-letter type (0 without).+fn marker(b: &[u8]) -> (i64, i64, u32, u32, String, String, u32) {+ let cb = u32_at(b, 0) as usize;+ let (t, _) = texts_at(b, cb, &[u32_at(b, 0x20), u32_at(b, 0x24)]);+ let kind = if cb >= 0x30 { u32_at(b, 0x28) } else { 0 };+ (+ i64_at(b, 0x08),+ i64_at(b, 0x10),+ u32_at(b, 0x18),+ u32_at(b, 0x1C),+ t[0].clone(),+ t[1].clone(),+ kind,+ )+}++/// The bins under `list`, their parent `parent`, into `out`.+fn bins(list: &Chunk<'_>, parent: Option<usize>, out: &mut Vec<DocBin>, depth: u32) {+ if depth > 32 {+ return;+ }+ for item in list.lists(TREE_ITEM) {+ let Some(d) = item.block(TREE_DATA) else {+ continue;+ };+ let b = d.data;+ let cb = u32_at(b, 0) as usize;+ match u32_at(b, 0x14) {+ // A bin, its items under it.+ 1 => {+ out.push(DocBin {+ name: text_at(b, cb, u32_at(b, 0x04) as usize),+ parent,+ media: Vec::new(),+ });+ let me = out.len() - 1;+ if let Some(kids) = item.list(BINS) {+ bins(kids, Some(me), out, depth + 1);+ }+ }+ // A media in its bin.+ 2 => {+ if let Some(p) = parent {+ out[p].media.push(u32_at(b, 0x0C));+ }+ }+ _ => {}+ }+ }+}++/// Reads a project file.+pub fn read(file: &[u8]) -> Result<Document, VegError> {+ let root = riff::parse(file)?;+ if root.guid != PROJECT {+ return Err(VegError::NotProject);+ }+ let header = root+ .block(HEADER)+ .ok_or(VegError::Damaged("no header"))?+ .data;+ let mixer = root.list(MIXER);+ let mixer_settings = mixer.and_then(|m| m.block(MIXER_SETTINGS));+ let bus_list = mixer.map_or_else(Vec::new, |m| {+ m.blocks(BUS).filter_map(|c| bus(c.data)).collect()+ });+ let mut doc = Document {+ version: u32_at(header, 0x04),+ settings: settings(header, mixer_settings.map(|c| c.data)),+ media: root.list(MEDIA_LIST).map_or_else(Vec::new, |l| {+ l.blocks(MEDIA).map(|c| media(c.data)).collect()+ }),+ tracks: root+ .list(TRACKS)+ .map_or_else(Vec::new, |l| l.lists(TRACK).filter_map(track).collect()),+ output_fx: effects(root.list(OUTPUT_FX)),+ envelopes: envelopes(root.list(PROJECT_ENVELOPES)),+ busses: mixer_settings.map_or(0, |c| u32_at(c.data, 0x228) as usize),+ bus_list,+ ..Default::default()+ };+ // The project's folders (File › Properties).+ if let Some(f) = root.list(FOLDERS).and_then(|l| l.block(FOLDERS)) {+ for (code, value) in tags(f.data) {+ match &code {+ b"ppre" => doc.settings.prerender_folder = value,+ b"prec" => doc.settings.recorded_folder = value,+ _ => {}+ }+ }+ }+ if let Some(s) = root.list(SUMMARY_LIST).and_then(|l| l.block(SUMMARY)) {+ for (code, value) in tags(s.data) {+ let i = match &code {+ b"INAM" => 0,+ b"IART" => 1,+ b"IENG" => 2,+ b"ICOP" => 3,+ b"ICMT" => 4,+ _ => continue,+ };+ doc.summary[i] = value;+ }+ }+ if let Some(l) = root.list(MARKERS) {+ for c in l.blocks(MARKER) {+ let (time, length, number, flags, label, _, _) = marker(c.data);+ doc.markers.push(DocMarker {+ time,+ length,+ number,+ region: flags & 1 != 0,+ label,+ });+ }+ }+ if let Some(l) = root.list(COMMANDS) {+ for c in l.blocks(MARKER) {+ let (time, _, _, _, comment, what, _) = marker(c.data);+ let (command, parameter) = what+ .split_once(':')+ .map_or((what.clone(), String::new()), |(a, b)| {+ (a.to_string(), b.to_string())+ });+ doc.commands.push(DocCommand {+ time,+ comment,+ command,+ parameter,+ });+ }+ }+ if let Some(l) = root.list(CD_LAYOUT) {+ for c in l.blocks(MARKER) {+ let (time, length, _, flags, name, _, kind) = marker(c.data);+ doc.cd.push(DocCd {+ time,+ length,+ index: kind == u32::from_le_bytes(*b"cdng") || flags & 1 == 0,+ name,+ });+ }+ }+ if let Some(l) = root.list(GROUPS) {+ for c in l.blocks(GROUP) {+ let n = u32_at(c.data, 0x08) as usize;+ let ids = (0..n.min(1 << 16))+ .map(|k| 0x10 + k * 8)+ .take_while(|&at| at + 8 <= c.data.len())+ .map(|at| u64_at(c.data, at))+ .collect();+ doc.groups.push(ids);+ }+ }+ if let Some(l) = root.list(BINS) {+ bins(l, None, &mut doc.bins, 0);+ }+ Ok(doc)+}diff --git a/crates/timeline/src/veg/riff.rs b/crates/timeline/src/veg/riff.rsnew file mode 100644index 0000000..281fe27--- /dev/null+++ b/crates/timeline/src/veg/riff.rs@@ -0,0 +1,264 @@+//! The container of `.veg` files: Wave64, the RIFF of 64 bits. Each+//! chunk is a GUID of 16 bytes (the first three fields little-endian, as+//! Windows writes GUIDs), a size of 8 (the 24 bytes of this header+//! included) and its data; every chunk starts on a multiple of 8 bytes+//! from the file's start, the zeros that pad it to there counted in its+//! size. The file is one `riff` chunk (its type's GUID, then chunks); a+//! `list` chunk is its type's GUID and its chunks.++use std::fmt;++/// A GUID as the file holds it.+#[derive(Clone, Copy, PartialEq, Eq, Hash)]+pub(crate) struct Guid(pub [u8; 16]);++impl Guid {+ /// The GUID written `AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE`.+ pub const fn parse(s: &str) -> Guid {+ const fn hex(c: u8) -> u8 {+ match c {+ b'0'..=b'9' => c - b'0',+ b'a'..=b'f' => c - b'a' + 10,+ b'A'..=b'F' => c - b'A' + 10,+ _ => panic!("not a GUID"),+ }+ }+ let b = s.as_bytes();+ // The text's byte pairs in the file's order.+ const ORDER: [usize; 16] = [6, 4, 2, 0, 11, 9, 16, 14, 19, 21, 24, 26, 28, 30, 32, 34];+ let mut out = [0u8; 16];+ let mut k = 0;+ while k < 16 {+ let i = ORDER[k];+ out[k] = (hex(b[i]) << 4) | hex(b[i + 1]);+ k += 1;+ }+ Guid(out)+ }+}++impl fmt::Debug for Guid {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ let b = &self.0;+ write!(+ f,+ "{:02X}{:02X}{:02X}{:02X}-{:02X}{:02X}-{:02X}{:02X}-{:02X}{:02X}-",+ b[3], b[2], b[1], b[0], b[5], b[4], b[7], b[6], b[8], b[9]+ )?;+ b[10..].iter().try_for_each(|x| write!(f, "{x:02X}"))+ }+}++pub(crate) const RIFF: Guid = Guid::parse("66666972-912E-11CF-A5D6-28DB04C10000");+pub(crate) const LIST: Guid = Guid::parse("7473696C-912F-11CF-A5D6-28DB04C10000");++/// A chunk read: its GUID — a list's or the file's type for those —, its+/// data (after a list's type) and, for lists, its chunks.+#[derive(Clone, Debug)]+pub(crate) struct Chunk<'a> {+ pub guid: Guid,+ pub list: bool,+ pub data: &'a [u8],+ pub kids: Vec<Chunk<'a>>,+}++impl<'a> Chunk<'a> {+ /// Its chunks that are plain chunks of `guid`.+ pub fn blocks(&self, guid: Guid) -> impl Iterator<Item = &Chunk<'a>> {+ self.kids.iter().filter(move |c| !c.list && c.guid == guid)+ }++ /// Its first plain chunk of `guid`.+ pub fn block(&self, guid: Guid) -> Option<&Chunk<'a>> {+ self.blocks(guid).next()+ }++ /// Its lists of type `guid`.+ pub fn lists(&self, guid: Guid) -> impl Iterator<Item = &Chunk<'a>> {+ self.kids.iter().filter(move |c| c.list && c.guid == guid)+ }++ /// Its first list of type `guid`.+ pub fn list(&self, guid: Guid) -> Option<&Chunk<'a>> {+ self.lists(guid).next()+ }+}++/// Why a file is not a project.+#[derive(Clone, Debug, PartialEq)]+pub enum VegError {+ /// Not a Wave64 `riff`, or a chunk that does not fit.+ NotRiff,+ /// A `riff` of another kind than a project.+ NotProject,+ /// Its parts do not fit together.+ Damaged(&'static str),+}++impl fmt::Display for VegError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ match self {+ VegError::NotRiff => write!(f, "not a .veg file"),+ VegError::NotProject => write!(f, "not a project"),+ VegError::Damaged(what) => write!(f, "damaged ({what})"),+ }+ }+}++fn u64_at(b: &[u8], at: usize) -> Option<u64> {+ b.get(at..at + 8)+ .map(|s| u64::from_le_bytes(s.try_into().expect("8 bytes")))+}++fn guid_at(b: &[u8], at: usize) -> Option<Guid> {+ b.get(at..at + 16)+ .map(|s| Guid(s.try_into().expect("16 bytes")))+}++/// The chunks of `file[start..end]` (the 8-byte steps count from the+/// file's start).+fn chunks(file: &[u8], start: usize, end: usize, depth: u32) -> Result<Vec<Chunk<'_>>, VegError> {+ if depth > 64 {+ return Err(VegError::Damaged("too deep"));+ }+ let mut out = Vec::new();+ let mut at = start;+ while at + 24 <= end {+ let guid = guid_at(file, at).ok_or(VegError::NotRiff)?;+ let size = u64_at(file, at + 16).ok_or(VegError::NotRiff)? as usize;+ if size < 24 || at.checked_add(size).is_none_or(|e| e > end) {+ return Err(VegError::Damaged("a chunk's size"));+ }+ let body = at + 24;+ let stop = at + size;+ let chunk = if guid == RIFF || guid == LIST {+ let kind = guid_at(file, body).ok_or(VegError::Damaged("a list's type"))?;+ Chunk {+ guid: kind,+ list: true,+ data: &file[body + 16..stop],+ kids: chunks(file, body + 16, stop, depth + 1)?,+ }+ } else {+ Chunk {+ guid,+ list: false,+ data: &file[body..stop],+ kids: Vec::new(),+ }+ };+ out.push(chunk);+ at = (stop + 7) & !7;+ }+ Ok(out)+}++/// The file's `riff` chunk (its type the list's GUID).+pub(crate) fn parse(file: &[u8]) -> Result<Chunk<'_>, VegError> {+ if file.len() < 40 || guid_at(file, 0) != Some(RIFF) {+ return Err(VegError::NotRiff);+ }+ // The size some writers leave short: the file's end is the riff's.+ let size = (u64_at(file, 16).unwrap_or(0) as usize).clamp(40, file.len());+ let kind = guid_at(file, 24).ok_or(VegError::NotRiff)?;+ Ok(Chunk {+ guid: kind,+ list: true,+ data: &file[40..size],+ kids: chunks(file, 40, size, 0)?,+ })+}++/// A file being written: chunks opened and closed in order.+#[derive(Default)]+pub(crate) struct Writer {+ pub out: Vec<u8>,+ /// Where each chunk still open starts.+ open: Vec<usize>,+}++impl Writer {+ /// A `riff` file of type `kind`, its chunks to come.+ pub fn new(kind: Guid) -> Writer {+ let mut w = Writer::default();+ w.begin(RIFF);+ w.out.extend_from_slice(&kind.0);+ w+ }++ /// Opens a chunk of `guid` (its size written when it closes).+ pub fn begin(&mut self, guid: Guid) {+ debug_assert_eq!(self.out.len() % 8, 0);+ self.open.push(self.out.len());+ self.out.extend_from_slice(&guid.0);+ self.out.extend_from_slice(&24u64.to_le_bytes());+ }++ /// Opens a list of type `kind`.+ pub fn begin_list(&mut self, kind: Guid) {+ self.begin(LIST);+ self.out.extend_from_slice(&kind.0);+ }++ /// Closes the chunk opened last: zeros to the next multiple of 8, its+ /// size (with them).+ pub fn end(&mut self) {+ let start = self.open.pop().expect("a chunk open");+ while !self.out.len().is_multiple_of(8) {+ self.out.push(0);+ }+ let size = (self.out.len() - start) as u64;+ self.out[start + 16..start + 24].copy_from_slice(&size.to_le_bytes());+ }++ /// A whole chunk of `guid` holding `data`.+ pub fn block(&mut self, guid: Guid, data: &[u8]) {+ self.begin(guid);+ self.out.extend_from_slice(data);+ self.end();+ }++ /// The file, its `riff` closed.+ pub fn finish(mut self) -> Vec<u8> {+ while !self.open.is_empty() {+ self.end();+ }+ self.out+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn guids_read_as_windows_writes_them() {+ let g = Guid::parse("66666972-912E-11CF-A5D6-28DB04C10000");+ assert_eq!(&g.0[..4], b"riff");+ assert_eq!(format!("{g:?}"), "66666972-912E-11CF-A5D6-28DB04C10000");+ }++ #[test]+ fn chunks_pad_to_eight_bytes_and_nest() {+ let kind = Guid::parse("46C429EF-904A-11D2-8722-00C04F8EDB8A");+ let a = Guid::parse("B28F2D5A-230F-11D2-86AF-00C04F8EDB8A");+ let l = Guid::parse("4D6C0747-2316-11D2-86B0-00C04F8EDB8A");+ let mut w = Writer::new(kind);+ w.block(a, &[1; 36]);+ w.begin_list(l);+ w.block(a, &[2; 3]);+ w.end();+ let file = w.finish();+ // 24 + 36 = 60, padded to 64, as the format has it.+ assert_eq!(u64::from_le_bytes(file[56..64].try_into().unwrap()), 64);+ assert_eq!(file.len() % 8, 0);+ let root = parse(&file).unwrap();+ assert_eq!(root.guid, kind);+ assert_eq!(root.kids.len(), 2);+ assert_eq!(root.kids[0].data.len(), 40);+ assert_eq!(&root.kids[0].data[..36], &[1; 36]);+ let list = root.list(l).unwrap();+ assert_eq!(list.block(a).unwrap().data[..3], [2; 3]);+ assert!(parse(b"not a riff at all, not at all, not at all").is_err());+ }+}diff --git a/crates/timeline/src/veg/tests.rs b/crates/timeline/src/veg/tests.rsnew file mode 100644index 0000000..0468eee--- /dev/null+++ b/crates/timeline/src/veg/tests.rs@@ -0,0 +1,1281 @@+//! A project through a `.veg` and back.++use bv_core::{Tick, TimeRange};++use super::*;+use crate::envelope::{Envelope, EnvelopeKind, EnvelopePoint};+use crate::fx::{FadeCurve, KeyCurve};+use crate::model::{+ AudioStreamInfo, Clip, ClipId, CompositeMode, GroupId, MediaInfo, MediaSource, Project,+ ProjectSettings, Summary, TrackKind, VideoStreamInfo,+};++fn ms(n: i64) -> Tick {+ Tick::from_timescale(n, 1000)+}++fn file(path: &str, video: bool, audio: bool, seconds: i64) -> MediaInfo {+ let s = ProjectSettings::default();+ let mut m = MediaInfo::generated(crate::model::Generator::ColorBars, &s);+ m.source = MediaSource::File {+ path: path.to_string(),+ };+ m.name = path.rsplit('\\').next().unwrap().to_string();+ m.duration = Tick::from_seconds(seconds);+ m.still = false;+ m.video = video.then_some(VideoStreamInfo {+ width: 1280,+ height: 720,+ frame_rate: s.frame_rate,+ pixel_aspect: Default::default(),+ field_order: Default::default(),+ spherical: false,+ full_range: false,+ reading: Default::default(),+ });+ m.audio = audio.then_some(AudioStreamInfo {+ sample_rate: s.sample_rate,+ channels: 2,+ });+ m+}++/// A project with most of what a `.veg` holds.+fn project() -> Project {+ let mut p = Project::new(ProjectSettings::default());+ p.tracks.clear();+ let clip = p.add_media(file("C:\\media\\clip.mp4", true, true, 20));+ let tone = p.add_media(file("C:\\media\\tone.wav", false, true, 10));+ let take2 = p.add_media(file("C:\\media\\take two.wav", false, true, 10));+ let v = p.add_track(TrackKind::Video);+ let a = p.add_track(TrackKind::Audio);+ let group = GroupId(p.alloc_id());+ {+ let t = p.track_mut(v).unwrap();+ t.name = "Picture".into();+ t.level = 0.5;+ t.composite_mode = CompositeMode::Add;+ let mut c = Clip::new(+ ClipId(9001),+ clip,+ Tick::from_seconds(1),+ Tick::from_seconds(2),+ );+ c.source_in = ms(250);+ c.fade_in = ms(500);+ c.fade_in_curve = FadeCurve::Smooth;+ c.level = 0.75;+ c.group = Some(group);+ t.clips.push(c);+ }+ {+ let t = p.track_mut(a).unwrap();+ t.name = "Sound".into();+ t.muted = true;+ t.level = 0.5;+ t.pan = -0.5;+ let mut c = Clip::new(+ ClipId(9002),+ tone,+ Tick::from_seconds(1),+ Tick::from_seconds(2),+ );+ c.fade_out = ms(750);+ c.fade_out_curve = FadeCurve::Slow;+ c.fade_in_curve = FadeCurve::Fast;+ c.rate = 2.0;+ c.pitch = 3.0;+ c.level = 0.25;+ c.muted = true;+ c.group = Some(group);+ c.takes = vec![+ crate::takes::Take {+ media: tone,+ offset: Tick::ZERO,+ name: Some("First".into()),+ none: false,+ },+ crate::takes::Take {+ media: take2,+ offset: Tick::from_seconds(1),+ name: None,+ none: false,+ },+ ];+ t.clips.push(c);+ let mut env = Envelope::new(EnvelopeKind::Volume);+ env.points = vec![+ EnvelopePoint {+ at: Tick::ZERO,+ value: 1.0,+ curve: KeyCurve::Smooth,+ },+ EnvelopePoint {+ at: Tick::from_seconds(2),+ value: 0.5,+ curve: KeyCurve::Fast,+ },+ ];+ t.envelopes.push(env);+ }+ let m = p.add_marker(ms(1500));+ p.markers.iter_mut().find(|k| k.id == m).unwrap().name = "Mark".into();+ let r = p.add_region(TimeRange::new(Tick::from_seconds(2), Tick::from_seconds(1)));+ p.regions.iter_mut().find(|k| k.id == r).unwrap().name = "Region".into();+ let id = crate::model::MarkerId(p.alloc_id());+ p.commands.push(crate::commands::CommandMarker {+ id,+ time: Tick::from_seconds(3),+ command: "Text".into(),+ parameter: "Hello".into(),+ comment: "A note".into(),+ });+ p.summary = Summary {+ title: "Title".into(),+ artist: "Artist".into(),+ engineer: "Engineer".into(),+ copyright: "Copyright".into(),+ comments: "Comments".into(),+ };+ p.add_bus();+ let bin = crate::bins::BinId(p.alloc_id());+ p.bins.push(crate::bins::MediaBin {+ id: bin,+ name: "Bin".into(),+ parent: None,+ media: vec![tone],+ });+ p+}++fn options() -> WriteOptions<'static> {+ WriteOptions {+ path: "C:\\projects\\test.veg".into(),+ documents: "C:\\Users\\someone\\Documents".into(),+ effect: &|_| None,+ }+}++#[test]+fn a_project_comes_back_from_a_veg() {+ let p = project();+ let bytes = write(&p, &options());+ let doc = read(&bytes).expect("it reads");+ assert_eq!(doc.version, VERSION);+ assert_eq!(doc.media.len(), 3);+ assert_eq!(doc.media[0].path, "C:\\media\\clip.mp4");+ let found: Vec<Option<MediaInfo>> = p.media.iter().cloned().map(Some).collect();+ let back = build(&doc, &found, &ProjectSettings::default(), &|_, _| None).project;+ assert_eq!(back.tracks.len(), 2);+ let (v, a) = (&back.tracks[0], &back.tracks[1]);+ assert_eq!((v.kind, v.name.as_str()), (TrackKind::Video, "Picture"));+ assert_eq!((v.level, v.composite_mode), (0.5, CompositeMode::Add));+ assert_eq!(+ (a.kind, a.name.as_str(), a.muted),+ (TrackKind::Audio, "Sound", true)+ );+ assert_eq!((a.level, a.pan), (0.5, -0.5));+ let c = &v.clips[0];+ assert_eq!(+ (c.start, c.duration),+ (Tick::from_seconds(1), Tick::from_seconds(2))+ );+ assert_eq!(c.source_in, ms(250));+ assert_eq!((c.fade_in, c.fade_in_curve), (ms(500), FadeCurve::Smooth));+ // The events' levels: a picture's opacity, a sound's volume.+ assert_eq!((c.level, a.clips[0].level), (0.75, 0.25));+ let d = &a.clips[0];+ assert!(d.muted);+ assert_eq!(d.rate, 2.0);+ assert_eq!(d.pitch, 3.0);+ assert_eq!((d.fade_out, d.fade_out_curve), (ms(750), FadeCurve::Slow));+ assert_eq!(d.fade_in_curve, FadeCurve::Fast);+ // Its takes: both, the first active, its name kept.+ assert_eq!(d.takes.len(), 2);+ assert_eq!(d.takes[0].name.as_deref(), Some("First"));+ assert_eq!(d.takes[1].offset, Tick::from_seconds(1));+ // The two events grouped again.+ assert!(c.group.is_some() && c.group == d.group);+ // The volume envelope's points and curves.+ let env = &a.envelopes[0];+ assert_eq!(env.kind, EnvelopeKind::Volume);+ assert_eq!(env.points.len(), 2);+ assert_eq!(+ (env.points[1].at, env.points[1].value),+ (Tick::from_seconds(2), 0.5)+ );+ assert_eq!(env.points[1].curve, KeyCurve::Fast);+ // Markers, regions, commands, summary, busses, bins.+ assert_eq!(back.markers[0].name, "Mark");+ assert_eq!(back.markers[0].time, ms(1500));+ assert_eq!(back.regions[0].name, "Region");+ assert_eq!(back.regions[0].range.duration, Tick::from_seconds(1));+ // The file spells Text as TEXT; BananaV's list as Text.+ assert_eq!(doc.commands[0].command, "TEXT");+ assert_eq!(back.commands[0].command, "Text");+ assert_eq!(back.commands[0].parameter, "Hello");+ assert_eq!(back.commands[0].comment, "A note");+ assert_eq!(back.summary, p.summary);+ assert_eq!(back.busses.len(), 1);+ assert_eq!(back.bins[0].name, "Bin");+ assert_eq!(back.bins[0].media.len(), 1);+ back.check_invariants().expect("a sound project");+}++#[test]+fn effects_keep_parameters_of_every_size() {+ // Records as the files have them: the value's size, the name's, the+ // name, the value and 4 bytes.+ let record = |size: u32, name: &str, value: &[u8]| {+ let n: Vec<u8> = name+ .encode_utf16()+ .chain([0])+ .flat_map(u16::to_le_bytes)+ .collect();+ let mut r = size.to_le_bytes().to_vec();+ r.extend_from_slice(&(n.len() as u32).to_le_bytes());+ r.extend_from_slice(&n);+ r.extend_from_slice(value);+ r+ };+ let numbers = |v: &[f64]| -> Vec<u8> {+ v.iter()+ .flat_map(|x| x.to_le_bytes())+ .chain([0; 4])+ .collect()+ };+ let mut b = Vec::new();+ b.extend(record(0x14, "Mid", &numbers(&[103.5, 0.5])));+ // A text: passed over.+ b.extend(record(6, "Label", b"abc\0\0\0"));+ b.extend(record(+ 8,+ "Mode",+ &[&(-2i32).to_le_bytes()[..], &[0; 4]].concat(),+ ));+ b.extend(record(12, "Gain", &numbers(&[1.5])));+ b.extend(record(0x24, "Tint", &numbers(&[0.1, 0.2, 0.3, 1.0])));+ // Not a name: the end.+ b.extend(record(12, "\u{1}", &numbers(&[9.0])));+ let p = read::params_at(&b, 0, 6);+ assert_eq!(+ p,+ [+ ("Mid".to_string(), ParamValue::Numbers(vec![103.5, 0.5])),+ ("Mode".to_string(), ParamValue::Integer(-2)),+ ("Gain".to_string(), ParamValue::Number(1.5)),+ (+ "Tint".to_string(),+ ParamValue::Numbers(vec![0.1, 0.2, 0.3, 1.0])+ ),+ ]+ );+ // And written as they were read.+ let mut p2 = project();+ let e = crate::fx::Effect::plugin(crate::fx::PluginFx {+ id: "com.vegascreativesoftware:colorcorrector".into(),+ version: [1, 0],+ name: String::new(),+ params: Default::default(),+ });+ p2.tracks[0].effects.push(e);+ let doc_fx = DocEffect {+ plugin: "com.vegascreativesoftware:colorcorrector".into(),+ preset: String::new(),+ params: p.clone(),+ ..Default::default()+ };+ let o = WriteOptions {+ effect: &|_| Some(doc_fx.clone()),+ ..options()+ };+ let back = read(&write(&p2, &o)).expect("it reads");+ assert_eq!(back.tracks[0].effects[0].params, p);+}++#[test]+fn times_go_to_hundreds_of_nanoseconds_and_back() {+ for t in [Tick::ZERO, ms(250), Tick::from_seconds(3600)] {+ assert_eq!(ticks(units(t)), t);+ }+ assert_eq!(units(Tick::from_seconds(1)), UNITS);+}++#[test]+fn what_is_not_a_project_is_refused() {+ assert_eq!(read(b"RIFF....WAVEfmt "), Err(VegError::NotRiff));+ let mut w = riff::Writer::new(riff::Guid::parse("00000000-0000-0000-0000-000000000001"));+ w.block(HEADER, &[0; 8]);+ assert_eq!(read(&w.finish()), Err(VegError::NotProject));+}++/// The chunks of a file as paths of their GUIDs (lists by their types).+fn paths(file: &[u8]) -> Vec<String> {+ fn walk(c: &riff::Chunk<'_>, path: &str, out: &mut Vec<String>) {+ for k in &c.kids {+ let name = format!("{}{:?}", if k.list { "L:" } else { "" }, k.guid);+ let p = format!("{path}/{}", &name[..name.len().min(10)]);+ out.push(p.clone());+ walk(k, &p, out);+ }+ }+ let root = riff::parse(file).expect("a riff");+ let mut out = Vec::new();+ walk(&root, "", &mut out);+ out+}++/// VEGAS Pro 23's own sample projects (not in the repository:+/// `BV_VEG_SAMPLES`, the folder of `00_vazio.veg` … `39_dois_takes.veg`,+/// each a new project with one thing changed): each read as the sample+/// says, made a project, and written back with the same chunks as VEGAS's+/// but the audio tracks' effect chains, which BananaV leaves out.+#[test]+#[ignore = "needs VEGAS's sample projects"]+fn vegas_samples_read_and_write_back() {+ let dir = std::path::PathBuf::from(std::env::var("BV_VEG_SAMPLES").expect("BV_VEG_SAMPLES"));+ let open = |name: &str| {+ let bytes = std::fs::read(dir.join(format!("{name}.veg"))).expect(name);+ let doc = read(&bytes).unwrap_or_else(|e| panic!("{name}: {e}"));+ (bytes, doc)+ };+ let s = |t: f64| (t * UNITS as f64).round() as i64;+ let (_, d) = open("02_video_1280x720");+ assert_eq!((d.settings.width, d.settings.height), (1280, 720));+ let (_, d) = open("03_video_25fps");+ assert_eq!((d.settings.frame_rate, d.settings.timecode), (25.0, 9));+ assert_eq!(open("04_video_32bits").1.settings.pixel_format, 32);+ assert_eq!(open("05_audio_44100").1.settings.sample_rate, 44_100);+ let (_, d) = open("06_resumo");+ assert!(d.summary.iter().all(|t| !t.is_empty()), "{:?}", d.summary);+ let (_, d) = open("07_regua");+ assert_eq!(+ (d.settings.beats_per_minute, d.settings.beats_per_measure),+ (90.0, 3)+ );+ let (_, d) = open("10_duas_trilhas");+ let names: Vec<_> = d.tracks.iter().map(|t| (t.kind, t.name.as_str())).collect();+ assert_eq!(+ names,+ [(VIDEO, "TRILHA_VIDEO_1"), (AUDIO, "TRILHA_AUDIO_1")]+ );+ let (_, d) = open("13_evento_video");+ let e = &d.tracks[0].events[0];+ assert_eq!((e.start, e.length), (s(1.0), s(2.0)));+ assert_eq!(e.curves, [4, 4]);+ let (_, d) = open("17_take_offset");+ assert_eq!(d.tracks[0].events[0].takes[0].offset, s(0.25));+ let (_, d) = open("18_nomes");+ let e = &d.tracks[0].events[0];+ assert_eq!(+ (e.name.as_str(), e.takes[0].name.as_str()),+ ("EVENTO_XYZ", "TAKE_XYZ")+ );+ let (_, d) = open("19_fades");+ let e = &d.tracks[0].events[0];+ assert_eq!(+ (e.fade_in, e.fade_out, e.curves),+ (s(0.5), s(0.75), [2, -2])+ );+ assert!(open("20_evento_mudo").1.tracks[0].events[0].muted);+ assert_eq!(open("21_velocidade").1.tracks[0].events[0].speed, 2.0);+ // A new audio track's three effects, each BananaV's own.+ let (_, d) = open("09_trilha_audio");+ let chain = &d.tracks[0].audio_fx;+ assert_eq!(chain.len(), 3);+ assert!(+ chain+ .iter()+ .all(|x| audio::effect(x.class, &x.settings).is_some())+ );+ let (_, d) = open("22_volume_pan");+ assert_eq!((d.tracks[0].volume, d.tracks[0].pan), (0.5, -0.5));+ assert!(open("23_mute_solo").1.tracks[0].muted);+ let (_, d) = open("24_marcador");+ assert_eq!(+ (d.markers[0].time, d.markers[0].label.as_str()),+ (s(1.5), "MARCADOR_1")+ );+ let (_, d) = open("25_regiao");+ let r = &d.markers[0];+ assert!(r.region && r.time == s(2.0) && r.length == s(1.0) && r.label == "REGIAO_1");+ let (_, d) = open("26_comando");+ let c = &d.commands[0];+ assert_eq!(+ (c.command.as_str(), c.parameter.as_str(), c.comment.as_str()),+ ("TEXT", "PARAMETRO_CMD", "COMENTARIO_CMD")+ );+ let (_, d) = open("27_envelope_volume");+ let env = &d.tracks[0].envelopes[0];+ assert_eq!(env.kind, 0);+ assert_eq!(env.points, [(0, 1.0, 4), (s(2.0), 0.5, 4)]);+ let (_, d) = open("28_fx_trilha_video");+ assert_eq!(+ d.tracks[0].effects[0].plugin,+ "com.vegascreativesoftware:sepia"+ );+ assert_eq!(d.tracks[0].effects[0].params.len(), 3);+ let (_, d) = open("29_fx_evento_video");+ let fx = &d.tracks[0].events[0].effects[0];+ assert_eq!(fx.plugin, "com.vegascreativesoftware:brightnessandcontrast");+ assert_eq!(+ fx.params[0],+ ("Brightness".to_string(), ParamValue::Number(0.25))+ );+ assert_eq!(open("30_barramento").1.busses, 1);+ let (_, d) = open("31_bin");+ assert_eq!(+ (d.bins[0].name.as_str(), d.bins[0].media.len()),+ ("BIN_XYZ", 1)+ );+ let (_, d) = open("33_composicao");+ assert_eq!(+ (d.tracks[0].composite_mode, d.tracks[0].composite_level),+ (1, 0.5)+ );+ let (_, d) = open("36_grupo");+ assert_eq!(+ d.groups,+ [vec![0x3000_0000_0000_0001, 0x2000_0000_0000_0002]]+ );+ assert_eq!(open("37_tom").1.tracks[0].events[0].pitch, 3.0);+ let (_, d) = open("38_faixa_cd");+ assert_eq!(d.cd.len(), 2);+ assert!(!d.cd[0].index && d.cd[1].index);+ let (_, d) = open("39_dois_takes");+ let e = &d.tracks[0].events[0];+ assert_eq!(+ (e.active, e.takes.len(), e.takes[1].name.as_str()),+ (1, 2, "TAKE_2")+ );++ // Every sample made a project and written back: VEGAS's chunks, but+ // what BananaV leaves out.+ let left_out = [+ "L:F79298F4",+ "L:B66A95CE",+ "884BACFF",+ "L:B5707E20",+ // The progress of a transition at an event's end.+ "L:EF72046C",+ ];+ let mut names: Vec<_> = std::fs::read_dir(&dir)+ .expect("the samples")+ .filter_map(|e| e.ok()?.file_name().into_string().ok())+ .filter(|n| n.ends_with(".veg"))+ .collect();+ names.sort();+ // Effects kept as the plug-ins they are, both ways.+ let keep_fx = |e: &DocEffect, _: bv_core::FrameRate| {+ let params = e+ .params+ .iter()+ .map(|(n, v)| {+ // Whole numbers ride as text, to come back as they went.+ let value = match v {+ ParamValue::Number(x) => crate::fx::PluginValue::Num(vec![*x]),+ ParamValue::Integer(x) => crate::fx::PluginValue::Text(x.to_string()),+ ParamValue::Numbers(v) => crate::fx::PluginValue::Num(v.clone()),+ ParamValue::Text(t) => crate::fx::PluginValue::Text(t.clone()),+ };+ (+ n.clone(),+ crate::fx::PluginParam {+ value,+ keys: Vec::new(),+ },+ )+ })+ .collect();+ Some(crate::fx::Effect::plugin(crate::fx::PluginFx {+ id: e.plugin.clone(),+ version: [1, 0],+ name: e.preset.clone(),+ params,+ }))+ };+ let back_fx = |e: &crate::fx::Effect| {+ let fx = e.plugin.as_ref()?;+ let params = fx+ .params+ .iter()+ .filter_map(|(n, p)| {+ let value = match &p.value {+ crate::fx::PluginValue::Text(x) => match x.parse() {+ Ok(whole) => ParamValue::Integer(whole),+ Err(_) => ParamValue::Text(x.clone()),+ },+ crate::fx::PluginValue::Num(v) => match v.as_slice() {+ [x] => ParamValue::Number(*x),+ v => ParamValue::Numbers(v.to_vec()),+ },+ _ => return None,+ };+ Some((n.clone(), value))+ })+ .collect();+ Some(DocEffect {+ plugin: fx.id.clone(),+ preset: fx.name.clone(),+ params,+ ..Default::default()+ })+ };+ let mut report = Vec::new();+ for name in &names {+ let (bytes, doc) = open(name.trim_end_matches(".veg"));+ let found = vec![None; doc.media.len()];+ let made = build(&doc, &found, &ProjectSettings::default(), &keep_fx);+ made.project+ .check_invariants()+ .unwrap_or_else(|e| panic!("{name}: {e:?}"));+ let options = WriteOptions {+ effect: &back_fx,+ ..options()+ };+ let ours = write(&made.project, &options);+ // The structures BananaV writes as VEGAS does, byte for byte.+ let blocks = |file: &[u8], guid: riff::Guid| -> Vec<Vec<u8>> {+ fn all<'a>(c: &riff::Chunk<'a>, g: riff::Guid, out: &mut Vec<&'a [u8]>) {+ for k in &c.kids {+ if !k.list && k.guid == g {+ out.push(k.data);+ }+ all(k, g, out);+ }+ }+ let root = riff::parse(file).expect("a riff");+ let mut out = Vec::new();+ all(&root, guid, &mut out);+ out.into_iter().map(<[u8]>::to_vec).collect()+ };+ for (what, g) in [+ ("mixer", MIXER_SETTINGS),+ ("audio track", AUDIO_TRACK),+ ("video track", VIDEO_TRACK),+ ("video event", VIDEO_EVENT),+ ("audio event", AUDIO_EVENT),+ ("four numbers", FOUR),+ ("summary", SUMMARY),+ ("envelopes' header", ENVELOPES_HEADER),+ ("envelope", ENVELOPE),+ ("group", GROUP),+ ("marker", MARKER),+ ] {+ let (a, b) = (blocks(&bytes, g), blocks(&ours, g));+ for (k, (x, y)) in a.iter().zip(&b).enumerate() {+ // A CD index's name: BananaV's indices have none.+ let cd_index = g == MARKER && x.first() == Some(&0x30);+ // What is not written: the chains' place in their owners,+ // the transitions at events' ends (and what the plug-ins'+ // settings are in another order), a track's pan up and down.+ // A point keeps only its start: after it, what its memory had.+ let ignored = |i: usize| match what {+ "audio track" => (0x304..0x308).contains(&i) || (0x14..0x1C).contains(&i),+ "audio event" => (0x24..0x28).contains(&i),+ "video event" => i >= 0x90 || (0x74..0x78).contains(&i),+ "envelope" => i >= 0x4C && (i - 0x4C) % 0x38 >= 0x10,+ _ => false,+ };+ if x != y && !cd_index {+ let at: Vec<String> = (0..x.len().max(y.len()))+ .filter(|&i| x.get(i) != y.get(i) && !ignored(i))+ .take(12)+ .map(|i| format!("{i:#x}"))+ .collect();+ if at.is_empty() {+ continue;+ }+ report.push(format!("{name}: {what} #{k} differs at {}", at.join(", ")));+ }+ }+ }+ // Track Motion: BananaV keeps its numbers shorter, without a 3D+ // box's depth.+ let (a, b) = (blocks(&bytes, TRACK_MOTION), blocks(&ours, TRACK_MOTION));+ assert_eq!(a.len(), b.len(), "{name}: track motions");+ for (x, y) in a.iter().zip(&b) {+ let (x, y) = (read::motion(x), read::motion(y));+ assert_eq!(x.flags, y.flags, "{name}: track motion's switches");+ for (l, m) in [+ (&x.moves, &y.moves),+ (&x.shadow, &y.shadow),+ (&x.glow, &y.glow),+ ] {+ assert_eq!(l.len(), m.len(), "{name}: track motion's keys");+ for (p, q) in l.iter().zip(m.iter()) {+ assert_eq!((p.curve, p.at), (q.curve, q.at), "{name}: track motion");+ let close = |u: f64, v: f64| (u - v).abs() < 1e-5;+ let all = [+ (p.position[0], q.position[0]),+ (p.position[1], q.position[1]),+ (p.position[2], q.position[2]),+ (p.size[0], q.size[0]),+ (p.size[1], q.size[1]),+ (p.rotation[0], q.rotation[0]),+ (p.rotation[1], q.rotation[1]),+ (p.rotation[2], q.rotation[2]),+ (p.smoothness, q.smoothness),+ (p.blur, q.blur),+ (p.intensity, q.intensity),+ ];+ assert!(+ all.iter().all(|&(u, v)| close(u, v)),+ "{name}: track motion {p:?} {q:?}"+ );+ assert_eq!(p.color, q.color, "{name}: a halo's color");+ }+ }+ }+ if std::env::var_os("BV_VEG_SHOW").is_some() {+ for (what, g) in [+ ("header", HEADER),+ ("media", MEDIA),+ ("track header", TRACK_HEADER),+ ("event header", EVENT_HEADER),+ ("take", TAKE),+ ("bus", BUS),+ ("tree data", TREE_DATA),+ ] {+ let (a, b) = (blocks(&bytes, g), blocks(&ours, g));+ for (k, (x, y)) in a.iter().zip(&b).enumerate() {+ let at: Vec<String> = (0..x.len().max(y.len()))+ .filter(|&i| x.get(i) != y.get(i))+ .take(16)+ .map(|i| format!("{i:#x}"))+ .collect();+ if !at.is_empty() {+ eprintln!(+ " {name}: {what} #{k} ({} vs {} B): {}",+ x.len(),+ y.len(),+ at.join(", ")+ );+ }+ }+ }+ }+ let read_back = read(&ours).unwrap_or_else(|e| panic!("{name} written: {e}"));+ // The effects come back as they went (their parameters by name).+ let fx = |d: &Document| -> Vec<(String, Vec<(String, ParamValue)>)> {+ d.tracks+ .iter()+ .flat_map(|t| {+ t.effects+ .iter()+ .chain(t.events.iter().flat_map(|e| &e.effects))+ })+ .map(|e| {+ let mut p = e.params.clone();+ p.sort_by(|a, b| a.0.cmp(&b.0));+ (e.plugin.clone(), p)+ })+ .collect()+ };+ assert_eq!(fx(&read_back), fx(&doc), "{name}");+ assert_eq!(read_back.tracks.len(), doc.tracks.len(), "{name}");+ let keep = |p: &String| !left_out.iter().any(|l| p.contains(l));+ let theirs: Vec<String> = paths(&bytes).into_iter().filter(keep).collect();+ let mine: Vec<String> = paths(&ours).into_iter().filter(keep).collect();+ if theirs != mine {+ let only_theirs: Vec<_> = theirs.iter().filter(|p| !mine.contains(p)).collect();+ let only_mine: Vec<_> = mine.iter().filter(|p| !theirs.contains(p)).collect();+ report.push(format!(+ "{name}: VEGAS's only {only_theirs:?}; ours only {only_mine:?}"+ ));+ }+ }+ eprintln!("{}", report.join("\n"));+ assert!(report.is_empty(), "{} samples differ", report.len());+}++/// An audio effects chain as the files hold one: its header, then each+/// plug-in's class, name and settings (a format's GUID, then `fields`).+fn chain(fx: &[(&str, &str, Vec<u8>)]) -> Vec<u8> {+ let text = |s: &str| -> Vec<u8> {+ s.encode_utf16()+ .chain([0])+ .flat_map(u16::to_le_bytes)+ .collect()+ };+ let guid = |s: &str| riff::Guid::parse(s).0.to_vec();+ let u32s = |v: &[u32]| -> Vec<u8> { v.iter().flat_map(|x| x.to_le_bytes()).collect() };+ let mut b = guid("B4128601-702E-11D1-8253-00009290DD44");+ b.extend(u32s(&[3]));+ b.extend(guid("3873D131-2D0F-11D3-87C0-00C04F8EF35F"));+ let first = text("Track Compressor");+ b.extend(u32s(&[first.len() as u32]));+ b.extend(first);+ b.extend(u32s(&[1_000_000, 0]));+ // The sound's format: float, stereo, 48 kHz.+ b.extend([3, 0, 2, 0]);+ b.extend(u32s(&[48_000, 384_000]));+ b.extend([8, 0, 32, 0, 0, 0]);+ b.extend(u32s(&[0, fx.len() as u32, 32]));+ for (class, name, fields) in fx {+ let n = text(name);+ b.extend(guid(class));+ b.extend(u32s(&[0, n.len() as u32]));+ b.extend(n);+ b.extend(guid(class));+ let size = 16 + fields.len() as u32;+ b.extend(u32s(&[size, size]));+ b.extend(guid("C400F99B-0C6E-444C-8F20-98DB216BE56E"));+ b.extend(fields);+ }+ b.extend([0; 6]);+ b+}++#[test]+fn audio_chains_bring_their_effects() {+ use crate::fx::EffectKind;+ let ints = |v: &[i32]| -> Vec<u8> { v.iter().flat_map(|x| x.to_le_bytes()).collect() };+ const GATE: &str = "869419DD-501F-11D3-8CDC-00C04F6B8E4C";+ const EQ: &str = "8CB69A0A-10E8-11D2-9B89-00104B8D13C2";+ const COMPRESSOR: &str = "23C9F225-40EC-11D2-9D36-00C04F8EDC1E";+ // A new track's three, the EQ's third band down 6 dB, the compressor+ // at 4:1 from -12 dB, and a plug-in BananaV does not have.+ let mut eq = vec![+ 0, 0, -60, 0, 10, 10, 10, 10, 100, 300, 1000, 5000, 1, 2, 2, 3,+ ];+ eq.extend([2, 1, 1, 2, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 1, -1]);+ let mut compressor: Vec<u8> = [0.0f32, 0.0, -12.0, 4.0, 15.0, 250.0]+ .iter()+ .flat_map(|x| x.to_le_bytes())+ .collect();+ compressor.extend(ints(&[1, 0, 0, 0, -1]));+ let b = chain(&[+ (GATE, "Track Noise Gate", ints(&[3, 100, -800, 0, -1])),+ (EQ, "Track EQ", ints(&eq)),+ (COMPRESSOR, "Track Compressor", compressor),+ (+ "00000000-1111-2222-3333-444444444444",+ "Elsewhere",+ ints(&[1]),+ ),+ ]);+ let fx = read::audio_chain(&b).expect("it reads");+ assert_eq!(fx.len(), 4);+ assert_eq!(fx[1].name, "Track EQ");+ let effect = |k: usize| audio::effect(fx[k].class, &fx[k].settings);+ let gate = effect(0).expect("the gate");+ assert_eq!(gate.kind, EffectKind::TrackNoiseGate);+ assert_eq!(gate.params, [-80.0, 3.0, 100.0]);+ assert!(gate.enabled);+ let eq = effect(1).expect("the EQ");+ assert_eq!(eq.kind, EffectKind::TrackEq);+ use crate::audio_fx::track_eq::{BANDWIDTH, FREQUENCY, GAIN, MODE, PER_BAND, ROLLOFF};+ let band = |b: usize, p: usize| eq.params[b * PER_BAND + p];+ assert_eq!(+ [0, 1, 2, 3].map(|b| band(b, FREQUENCY)),+ [100.0, 300.0, 1000.0, 5000.0]+ );+ // Low shelf, two bands, high shelf; 12 dB/oct. shelves.+ assert_eq!([0, 1, 2, 3].map(|b| band(b, MODE)), [0.0, 1.0, 1.0, 2.0]);+ assert_eq!((band(0, ROLLOFF), band(3, ROLLOFF)), (1.0, 1.0));+ assert_eq!((band(2, GAIN), band(1, BANDWIDTH)), (-6.0, 1.0));+ let c = effect(2).expect("the compressor");+ use crate::audio_fx::track_compressor::{AUTO_GAIN, RATIO, SMOOTH, THRESHOLD};+ assert_eq!(+ (+ c.params[THRESHOLD],+ c.params[RATIO],+ c.params[AUTO_GAIN],+ c.params[SMOOTH]+ ),+ (-12.0, 4.0, 1.0, 0.0)+ );+ assert!(effect(3).is_none(), "not BananaV's");+ // A bypassed gate comes in off; a chain cut short does not read.+ let off = chain(&[(GATE, "Track Noise Gate", ints(&[3, 100, -800, 1, -1]))]);+ let fx = read::audio_chain(&off).unwrap();+ assert!(!audio::effect(fx[0].class, &fx[0].settings).unwrap().enabled);+ assert!(read::audio_chain(&b[..b.len() / 2]).is_none());+}++/// The plug-ins of the audio samples (`BV_VEG_SAMPLES2`, the folder of+/// `a01_…veg` … `a51_…veg` and their `log.txt`, each a track with one+/// plug-in at its last preset): each read as BananaV's factory preset of the+/// name the log gives, or its default when the log gives none.+#[test]+#[ignore = "needs VEGAS's sample projects"]+fn audio_samples_read_as_their_presets() {+ use crate::fx::{Effect, EffectKind};+ let dir = std::path::PathBuf::from(std::env::var("BV_VEG_SAMPLES2").expect("BV_VEG_SAMPLES2"));+ let log = std::fs::read(dir.join("log.txt")).expect("log");+ let log = String::from_utf8_lossy(&log).into_owned();+ let chosen = |case: &str| -> String {+ let at = log.find(&format!("{case}: ")).expect(case);+ log[at..]+ .lines()+ .find_map(|l| l.trim().strip_prefix("escolhido: "))+ .unwrap_or("-")+ .trim_start_matches("[Sys] ")+ .to_string()+ };+ // A graph's count and first point: the points past the count are not kept.+ let graphs = |k: EffectKind| -> &[(usize, usize)] {+ match k {+ EffectKind::Vibrato | EffectKind::AmplitudeModulation => &[(3, 32)],+ EffectKind::GraphicDynamics => &[(0, 16)],+ EffectKind::Distortion => &[(2, 32), (67, 32)],+ EffectKind::GraphicEq => &[(0, 32)],+ _ => &[],+ }+ };+ let mut names: Vec<_> = std::fs::read_dir(&dir)+ .expect("folder")+ .filter_map(|e| e.ok()?.file_name().into_string().ok())+ .filter(|n| n.starts_with('a') && n.ends_with(".veg"))+ .collect();+ names.sort();+ let (mut checked, mut wrong, mut no_row) = (0, Vec::new(), Vec::new());+ for name in &names {+ let case = name.trim_end_matches(".veg");+ let bytes = std::fs::read(dir.join(name)).expect(name);+ let doc = read(&bytes).unwrap_or_else(|e| panic!("{name}: {e}"));+ let x = doc+ .tracks+ .iter()+ .rev()+ .find_map(|t| t.audio_fx.last())+ .unwrap_or_else(|| panic!("{name}: no chain"));+ let e = super::audio::effect(x.class, &x.settings)+ .unwrap_or_else(|| panic!("{name}: {} left out", x.name));+ let preset = chosen(case);+ let row = crate::audio_fx::presets(e.kind)+ .unwrap_or(&[])+ .iter()+ .find(|(n, _)| *n == preset || (preset == "-" && *n == "Default"))+ .map(|(_, r)| r.to_vec())+ .or_else(|| (preset == "-").then(|| Effect::new(e.kind).params.clone()));+ let Some(row) = row else {+ no_row.push(format!("{case}: {preset}: {:?}", e.params));+ continue;+ };+ let mut left_out = std::collections::BTreeSet::new();+ for &(at, room) in graphs(e.kind) {+ let n = row[at].round() as usize;+ left_out.extend((at + 1 + 2 * n)..(at + 1 + 2 * room));+ }+ checked += 1;+ for (i, (&a, &b)) in e.params.iter().zip(&row).enumerate() {+ if left_out.contains(&i) {+ continue;+ }+ // The plug-in itself goes no lower than −15 dB of the preset's −25.+ if e.kind == EffectKind::TrackEq && i == 3 && a == -15.0 {+ continue;+ }+ // A band the preset leaves off has no settings of its own.+ if e.kind == EffectKind::MultiBandDynamics+ && i >= 2+ && row[2 + (i - 2) / 10 * 10] == 1.0+ {+ continue;+ }+ if (a - b).abs() > 0.02 + 0.005 * b.abs() {+ wrong.push(format!(+ "{case}: {preset}: {i} {}: read {a}, the preset {b}",+ e.kind.params()[i].name+ ));+ }+ }+ }+ eprintln!("{checked} of {} checked", names.len());+ for line in &no_row {+ eprintln!("no row: {line}");+ }+ for line in &wrong {+ eprintln!("WRONG {line}");+ }+ assert!(wrong.is_empty(), "{} wrong", wrong.len());+}++/// What a project's editing leaves in the file, read from the samples+/// (`BV_VEG_SAMPLES`, the folder of `58_transicao_in.veg` … and of+/// `master_6db.veg` above it), each with one thing changed.+#[test]+#[ignore = "needs VEGAS's sample projects"]+fn edits_read_as_the_samples_say() {+ use crate::envelope::EnvelopeKind as K;+ let dir = std::path::PathBuf::from(std::env::var("BV_VEG_SAMPLES").expect("BV_VEG_SAMPLES"));+ let kept = |e: &DocEffect, _: bv_core::FrameRate| {+ let mut params = std::collections::BTreeMap::new();+ for (n, v) in &e.params {+ let value = match v {+ ParamValue::Number(x) => crate::fx::PluginValue::Num(vec![*x]),+ ParamValue::Integer(x) => crate::fx::PluginValue::Num(vec![*x as f64]),+ ParamValue::Numbers(v) => crate::fx::PluginValue::Num(v.clone()),+ ParamValue::Text(t) => crate::fx::PluginValue::Text(t.clone()),+ };+ params.insert(+ n.clone(),+ crate::fx::PluginParam {+ value,+ keys: Vec::new(),+ },+ );+ }+ Some(crate::fx::Effect::plugin(crate::fx::PluginFx {+ id: e.native.clone().unwrap_or_else(|| e.plugin.clone()),+ version: [1, 0],+ name: e.preset.clone(),+ params,+ }))+ };+ let doc = |name: &str| {+ let bytes = std::fs::read(dir.join(format!("{name}.veg"))).expect(name);+ read(&bytes).unwrap_or_else(|e| panic!("{name}: {e}"))+ };+ let open = |name: &str| {+ let d = doc(name);+ let found = vec![None; d.media.len()];+ build(&d, &found, &ProjectSettings::default(), &kept)+ };+ let second = |t: f64| ticks((t * UNITS as f64).round() as i64);+ let near = |a: f32, b: f32, what: &str| assert!((a - b).abs() < 1e-3, "{what}: {a} is not {b}");++ // Transitions: at the fade in, its plug-in and its settings.+ let m = open("58_transicao_in");+ let c = m.project.clips().next().unwrap().1;+ assert!(c.transition_fx.is_some(), "58");+ assert_eq!(m.transitions_left, 0, "58");+ assert_eq!(open("59_transicao_out").transitions_left, 1, "59");+ let d = doc("62_transicao_parametro");+ let t = d+ .tracks+ .iter()+ .flat_map(|t| &t.events)+ .find_map(|e| e.transition_out.as_ref())+ .expect("62");+ assert!(t.transition, "62");+ let feather = t+ .params+ .iter()+ .find(|(n, _)| n == "Transition")+ .expect("Transition");+ assert_eq!(feather.1, ParamValue::Number(0.3), "62");+ // The crossfade: on the second event.+ let m = open("60_crossfade");+ let clips: Vec<_> = m.project.clips().map(|(_, c)| c).collect();+ assert_eq!(clips.len(), 2, "60");+ assert!(+ clips[0].transition_fx.is_none() && clips[1].transition_fx.is_some(),+ "60"+ );+ assert_eq!(clips[0].fade_out, second(1.0), "60");+ assert_eq!(clips[1].fade_in, second(1.0), "60");+ // Its progress: 0, then 0.25 half way, then 1, over the fade.+ let m = open("61_transicao_envelope");+ let c = m.project.clips().next().unwrap().1;+ let env = c.envelope(K::TransitionProgress).expect("61");+ assert_eq!(env.points.len(), 3, "61");+ near(env.points[1].value, 0.25, "61");+ assert_eq!(env.points[1].at, Tick(c.fade_in.0 / 2), "61");++ // Audio chains: in the event, in the track, on or off, the master's.+ let m = open("63_fx_evento_audio");+ let c = m.project.clips().next().unwrap().1;+ assert_eq!(c.effects.len(), 1, "63");+ assert_eq!(c.effects[0].kind, crate::fx::EffectKind::ReverbFx, "63");+ near(c.effects[0].params[2], -35.0, "63");+ let m = open("64_fx_trilha_audio");+ let kinds: Vec<_> = m.project.tracks[0].effects.iter().map(|e| e.kind).collect();+ assert_eq!(kinds.len(), 4, "64");+ assert_eq!(kinds[0], crate::fx::EffectKind::TrackNoiseGate, "64");+ assert_eq!(kinds[3], crate::fx::EffectKind::ReverbFx, "64");+ let m = open("66_fx_bypass");+ let on: Vec<_> = m.project.tracks[0]+ .effects+ .iter()+ .map(|e| e.enabled)+ .collect();+ assert_eq!(on, [false, true, true], "66");+ let m = open("68_fx_mestre");+ assert_eq!(m.project.master_fx.len(), 1, "68");+ assert_eq!(+ m.project.master_fx[0].kind,+ crate::fx::EffectKind::ReverbFx,+ "68"+ );+ assert_eq!(m.audio_fx_left, 0, "68");++ // An audio event's switches.+ let c = open("70_evento_normalize")+ .project+ .clips()+ .next()+ .unwrap()+ .1+ .clone();+ assert_eq!(c.normalize, Some(0.5), "70");+ assert!(+ open("71_evento_fase")+ .project+ .clips()+ .next()+ .unwrap()+ .1+ .invert_phase,+ "71"+ );+ assert_eq!(+ open("72_evento_canais")+ .project+ .clips()+ .next()+ .unwrap()+ .1+ .channels,+ crate::model::ChannelMap::Combine,+ "72"+ );+ near(+ open("56_fade_ganho_audio")+ .project+ .clips()+ .next()+ .unwrap()+ .1+ .level,+ 0.75,+ "56",+ );++ // A track's phase, its envelopes by their kinds, their curves.+ assert!(open("73_trilha_fase").project.tracks[0].invert_phase, "73");+ let m = open("74_trilha_pan_env");+ let envs = &m.project.tracks[0].envelopes;+ assert_eq!(envs.len(), 1, "74");+ assert_eq!(envs[0].kind, K::Pan, "74");+ near(envs[0].points[1].value, -0.5, "74");+ let m = open("27_envelope_volume");+ assert_eq!(m.project.tracks[0].envelopes[0].kind, K::Volume, "27");+ let m = open("75_env_curvas");+ let curves: Vec<_> = m.project.tracks[0].envelopes[0]+ .points+ .iter()+ .map(|p| p.curve)+ .collect();+ assert_eq!(curves.len(), 7, "75");+ let m = open("93_env_composicao");+ assert_eq!(+ m.project.tracks[0].envelopes[0].kind,+ K::CompositeLevel,+ "93"+ );+ let m = open("77_send_bus");+ assert!(+ matches!(m.project.tracks[0].envelopes[0].kind, K::Send(_)),+ "77"+ );+ assert_eq!(m.envelopes_left, 0, "77");++ // An event's velocity.+ let m = open("92_env_velocidade");+ let c = m.project.clips().next().unwrap().1;+ let env = c.envelope(K::Velocity).expect("92");+ assert_eq!(env.points.len(), 2, "92");+ near(env.points[1].value, 2.0, "92");+ assert_eq!(env.points[1].at, second(1.0), "92");++ // The busses: faders, switches.+ let m = open("../master_6db");+ near(m.project.master.gain_db, -6.0, "master");+ let m = open("97_bus_so_solo");+ assert_eq!(m.project.busses.len(), 1, "97");+ assert!(+ m.project.busses[0].channel.solo && !m.project.busses[0].channel.muted,+ "97"+ );+ let m = open("98_bus_so_mudo");+ assert!(+ m.project.busses[0].channel.muted && !m.project.busses[0].channel.solo,+ "98"+ );++ // A video event's switches.+ assert!(+ open("50_evento_interlace")+ .project+ .clips()+ .next()+ .unwrap()+ .1+ .reduce_flicker,+ "50"+ );+ assert_eq!(+ open("51_evento_resample")+ .project+ .clips()+ .next()+ .unwrap()+ .1+ .resample,+ Some(crate::model::ResampleMode::Disable),+ "51"+ );+ near(+ open("52_evento_undersample")+ .project+ .clips()+ .next()+ .unwrap()+ .1+ .undersample,+ 0.5,+ "52",+ );++ // An effect's keyframes: frames, interpolations and values.+ let d = doc("80_ofx_kf_double");+ let fx = d+ .tracks+ .iter()+ .flat_map(|t| &t.events)+ .flat_map(|e| &e.effects)+ .next()+ .expect("80");+ let (_, keys) = fx.keys.iter().find(|(n, _)| n == "Brightness").expect("80");+ let got: Vec<_> = keys+ .iter()+ .map(|k| (k.frame, k.interpolation, k.value[0]))+ .collect();+ assert_eq!(+ got,+ [+ (0.0, 1, 0.1),+ (15.0, 2, 0.2),+ (30.0, 3, 0.3),+ (45.0, 4, 0.4),+ (60.0, 6, 0.5)+ ],+ "80"+ );+ // Colors, points and choices too.+ let d = doc("81_ofx_kf_border");+ let fx = d+ .tracks+ .iter()+ .flat_map(|t| &t.events)+ .flat_map(|e| &e.effects)+ .next()+ .expect("81");+ let of = |name: &str| &fx.keys.iter().find(|(n, _)| n == name).expect(name).1;+ assert_eq!(of("color")[0].value.len(), 4, "81");+ assert_eq!(of("color_rgb")[0].value.len(), 3, "81");+ assert_eq!(of("Type")[0].value.len(), 1, "81");+ let d = doc("82_ofx_kf_bumpmap");+ let fx = d+ .tracks+ .iter()+ .flat_map(|t| &t.events)+ .flat_map(|e| &e.effects)+ .next()+ .expect("82");+ let of = |name: &str| &fx.keys.iter().find(|(n, _)| n == name).expect(name).1;+ assert_eq!(of("LocationSrc")[0].handles.len(), 3, "82");+ assert_eq!(of("LocationDst")[0].handles.len(), 2, "82");+ // The chain's order and switches.+ let d = doc("90_fx_antes_pancrop");+ let fx = d+ .tracks+ .iter()+ .flat_map(|t| &t.events)+ .flat_map(|e| &e.effects)+ .next()+ .expect("90");+ assert!(fx.before_pan_crop, "90");+ let c = open("90_fx_antes_pancrop")+ .project+ .clips()+ .next()+ .unwrap()+ .1+ .clone();+ assert_eq!(c.pan_crop_at, 1, "90");+ let c = open("91_fx_video_bypass")+ .project+ .clips()+ .next()+ .unwrap()+ .1+ .clone();+ assert!(!c.effects[0].enabled, "91");+ // A text.+ let d = doc("95_ofx_texto");+ let fx = d+ .tracks+ .iter()+ .flat_map(|t| &t.events)+ .flat_map(|e| &e.effects)+ .next()+ .expect("95");+ assert!(+ fx.params+ .iter()+ .any(|(_, v)| matches!(v, ParamValue::Text(_))),+ "95"+ );++ // Track Motion: where, how big, turned, over time.+ let m = open("83_tm_kf");+ let tm = m.project.tracks[0].motion.as_ref().expect("83");+ assert_eq!(tm.keys.len(), 2, "83");+ let k = &tm.keys[1];+ assert_eq!(k.at, second(1.0), "83");+ near(k.value.x, 10.0 / 640.0, "83");+ near(k.value.y, 20.0 / 360.0, "83");+ near(k.value.scale, 0.5, "83");+ near(k.value.stretch, 1.0, "83");+ near(k.value.rotation_deg, 0.5, "83");+ let m = open("85_tm_glow");+ let tm = m.project.tracks[0].motion.as_ref().expect("85");+ assert!(tm.glow.on && !tm.shadow.on, "85");+ assert_eq!(tm.glow.keys.len(), 2, "85");+ near(tm.glow.keys[1].value.intensity, 0.0075, "85");+ near(tm.glow.keys[1].value.color[0], 10.0 / 255.0, "85");+ let m = open("86_tm_sombra");+ let tm = m.project.tracks[0].motion.as_ref().expect("86");+ assert!(tm.shadow.on && !tm.glow.on, "86");+ let m = open("87_tm_3d");+ let t = &m.project.tracks[0];+ assert_eq!(t.composite_mode, CompositeMode::ThreeDSourceAlpha, "87");+ let tm = t.motion.as_ref().expect("87");+ assert_eq!(tm.space_keys.len(), 2, "87");+ near(tm.space_keys[1].value.z, 100.0 / 640.0, "87");+ near(tm.space_keys[1].value.rotation[1], 0.5, "87");+ let m = open("88_tm_pai");+ assert!(m.project.tracks[0].parent_motion.is_some(), "88");+}++/// The Pan/Crops of another program's projects (`BV_PANCROP_SAMPLES`, the+/// folder of `mascaras.veg` and `vegas/geometria.veg`): each written and read+/// again as it was, and as long as the file's.+#[test]+#[ignore = "needs VEGAS's sample projects"]+fn pan_crop_chunks_read_and_write_back() {+ let dir = std::path::PathBuf::from(std::env::var("BV_PANCROP_SAMPLES").expect("the folder"));+ let mut written = 0;+ for file in ["mascaras.veg", "vegas/geometria.veg"] {+ let bytes = std::fs::read(dir.join(file)).expect(file);+ let doc = read(&bytes).unwrap_or_else(|e| panic!("{file}: {e}"));+ let events = doc.tracks.iter().flat_map(|t| &t.events);+ for e in events {+ let Some(box_) = &e.pan_crop else {+ continue;+ };+ let chunk = pancrop::write(box_, e.mask.as_ref(), box_.size, &[])+ .unwrap_or_else(|| panic!("{file} {}: its chunk", e.start));+ let (again, mask) = pancrop::read(&chunk).expect("it reads");+ assert_eq!(&again, box_, "{file} {}", e.start);+ assert_eq!(mask, e.mask, "{file} {}", e.start);+ written += 1;+ }+ }+ eprintln!("{written} chunks");+ assert!(written >= 40, "{written} chunks");+}diff --git a/crates/timeline/src/veg/write.rs b/crates/timeline/src/veg/write.rsnew file mode 100644index 0000000..19cebed--- /dev/null+++ b/crates/timeline/src/veg/write.rs@@ -0,0 +1,1392 @@+//! A project written as a `.veg`: the chunks in the order VEGAS Pro 23+//! writes them, each structure with VEGAS's own defaults where BananaV has+//! nothing to say (the values a new project's have), so that it opens it.+//! What this does not write of BananaV's (its audio effects' chains,+//! generated media…) is left out.++use std::collections::HashMap;++use bv_core::Tick;++use super::build::composite_number;+use super::riff::{Guid, Writer};+use super::*;+use crate::envelope::EnvelopeKind;+use crate::fx::Effect;+use crate::model::{+ ChannelMap, Clip, MediaId, MediaInfo, MediaSource, PixelFormat, Project, ResampleMode,+ RulerFormat, TrackKind,+};++/// What the file is written with besides the project.+pub struct WriteOptions<'a> {+ /// Where it goes: the path its header holds.+ pub path: String,+ /// The user's documents folder (the header's).+ pub documents: String,+ /// Each of BananaV's effects as another program's plug-in (`None`: it+ /// has none, and the effect is left out).+ pub effect: &'a dyn Fn(&Effect) -> Option<DocEffect>,+}++impl std::fmt::Debug for WriteOptions<'_> {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("WriteOptions")+ .field("path", &self.path)+ .field("documents", &self.documents)+ .finish_non_exhaustive()+ }+}++/// A structure being filled: zeros, then the values at their places.+struct Data(Vec<u8>);++impl Data {+ fn new(size: usize) -> Data {+ Data(vec![0; size])+ }++ fn u16(&mut self, at: usize, v: u16) -> &mut Data {+ self.0[at..at + 2].copy_from_slice(&v.to_le_bytes());+ self+ }++ fn u32(&mut self, at: usize, v: u32) -> &mut Data {+ self.0[at..at + 4].copy_from_slice(&v.to_le_bytes());+ self+ }++ fn i32(&mut self, at: usize, v: i32) -> &mut Data {+ self.u32(at, v as u32)+ }++ fn u64(&mut self, at: usize, v: u64) -> &mut Data {+ self.0[at..at + 8].copy_from_slice(&v.to_le_bytes());+ self+ }++ fn i64(&mut self, at: usize, v: i64) -> &mut Data {+ self.u64(at, v as u64)+ }++ fn f32(&mut self, at: usize, v: f32) -> &mut Data {+ self.u32(at, v.to_bits())+ }++ fn f64(&mut self, at: usize, v: f64) -> &mut Data {+ self.u64(at, v.to_bits())+ }++ /// `v` every `step` bytes from `from` to `to` (included).+ fn run(&mut self, from: usize, to: usize, step: usize, v: u32) -> &mut Data {+ for at in (from..=to).step_by(step) {+ self.u32(at, v);+ }+ self+ }++ fn bytes(&mut self, at: usize, b: &[u8]) -> &mut Data {+ self.0[at..at + b.len()].copy_from_slice(b);+ self+ }++ /// Appends `s` as UTF-16 with its zero (nothing for an empty `s` when+ /// `none_if_empty`); its bytes.+ fn text(&mut self, s: &str, none_if_empty: bool) -> u32 {+ if s.is_empty() && none_if_empty {+ return 0;+ }+ let before = self.0.len();+ for u in s.encode_utf16().chain(std::iter::once(0)) {+ self.0.extend_from_slice(&u.to_le_bytes());+ }+ (self.0.len() - before) as u32+ }++ fn push(&mut self, b: &[u8]) {+ self.0.extend_from_slice(b);+ }+}++/// UTF-16 bytes of `s` with its zero.+fn utf16(s: &str) -> Vec<u8> {+ s.encode_utf16()+ .chain(std::iter::once(0))+ .flat_map(u16::to_le_bytes)+ .collect()+}++/// A list of tags: `u32` 8, `u32` n, each its code, its byte count and+/// its text (with its zero).+fn tags(items: &[(&[u8; 4], &str)]) -> Vec<u8> {+ let mut d = Data::new(8);+ d.u32(0, 8).u32(4, items.len() as u32);+ for (code, value) in items {+ let t = utf16(value);+ d.push(&code[..]);+ d.push(&(t.len() as u32).to_le_bytes());+ d.push(&t);+ }+ d.0+}++/// The project's header: its settings, its path, two folders and its+/// three video items (the project's, then two VEGAS keeps at HD).+fn header(p: &Project, o: &WriteOptions<'_>) -> Vec<u8> {+ let s = &p.settings;+ let fps = s.frame_rate.as_f64();+ let timecode = match s.ruler_format {+ Some(RulerFormat::SmpteDrop) => 8,+ Some(RulerFormat::SmpteEbu) => 9,+ _ if (fps - 25.0).abs() < 1e-6 => 9,+ _ if (fps - 29.97).abs() < 1e-2 || (fps - 59.94).abs() < 1e-2 => 8,+ _ => 7,+ };+ let mut d = Data::new(0xB8);+ d.u32(0x00, 0xB8)+ .u32(0x04, VERSION)+ .u32(0x08, timecode)+ .u32(0x0C, 48_000)+ .f64(0x10, fps)+ .f64(0x18, s.tempo.beats_per_minute)+ .u16(0x28, s.tempo.beat_note as u16)+ .u16(0x2A, s.tempo.beats_per_measure as u16)+ .u32(0x2C, 0x40)+ .u32(0x38, 3)+ .u32(0x60, 1)+ .u32(0x70, 1)+ .u32(0x74, 1)+ .u32(0x78, 0x78)+ .u32(0x7C, 1)+ .u32(0xB0, 1);+ let path = d.text(+ if o.path.is_empty() {+ "Untitled"+ } else {+ &o.path+ },+ false,+ );+ let documents = d.text(&o.documents, false);+ let data = d.text(&p.prerender_folder, false);+ let fourth = d.text("", false);+ d.u32(0x3C, path)+ .u32(0x40, documents)+ .u32(0x44, data)+ .u32(0x6C, fourth);+ let float = matches!(+ s.pixel_format,+ PixelFormat::Float32Full | PixelFormat::Float32VideoLevels+ );+ let pixel_aspect = s.pixel_aspect.num as f64 / s.pixel_aspect.den.max(1) as f64;+ for k in 0..3 {+ let (w, h, f, fl) = if k == 0 {+ (s.width, s.height, fps, float)+ } else {+ (1920, 1080, 30_000.0 / 1001.0, false)+ };+ let mut item = Data::new(0x358);+ item.u32(0x00, 0x358)+ .u32(0x04, w)+ .u32(0x08, h)+ .u32(0x0C, if fl { 32 } else { 28 })+ .run(0x10, 0x20, 4, 3)+ .u32(0x28, 0x40)+ .u32(0x2C, u32::MAX)+ .u32(0x30, u32::from(k > 0))+ .f64(0x38, f)+ .f64(0x40, if k == 0 { pixel_aspect } else { 1.0 })+ .f64(0x48, if k > 0 || fl { 1.0 } else { 0.0 })+ .run(0xA0, 0xAC, 4, 1f32.to_bits())+ .f32(0xBC, 1.0)+ .f32(0xC8, 1.0)+ .f32(0xCC, 1.0)+ .f64(0xD8, 30_000.0 / 1001.0)+ .u32(0xE0, 1)+ .f64(0xE8, 0.1)+ .u32(0xF4, 1)+ .u32(0x104, 0x44)+ .f32(0x118, 1.0)+ .u32(0x120, 2)+ .u32(0x134, 1)+ .run(0x180, 0x1B0, 0x0C, 1)+ .bytes(0x2BC, b"ACES")+ .bytes(0x2FC, b"sRGB")+ .u32(0x33C, 2)+ .u32(0x340, 1)+ .u32(0x350, u32::from(k > 0 || fl));+ d.push(&item.0);+ }+ d.0+}++/// A media's entry: its path, its streams and, with sound, its sound's+/// channels.+fn media_entry(m: &MediaInfo, id: u32) -> Option<Vec<u8>> {+ let MediaSource::File { path } = &m.source else {+ return None;+ };+ let audio = m.audio.iter().chain(&m.extra_audio).count();+ let video = usize::from(m.video.is_some());+ let mut d = Data::new(0x80);+ d.u32(0x00, 0x80)+ .u32(0x18, 1)+ .u32(0x20, if video > 0 { 3 } else { 1 })+ .u32(0x30, u32::MAX)+ .u32(0x38, (audio + video) as u32)+ .u32(0x3C, id)+ .u32(0x48, u32::from(audio > 0))+ .f64(0x68, 1.0)+ .u32(0x70, u32::MAX)+ .u64(0x78, u64::MAX);+ let bytes = d.text(path, false);+ d.u32(0x24, bytes);+ for k in 0..video + audio {+ let mut s = Data::new(0x98);+ s.u32(0x00, 0x98).u32(0x0C, 1);+ if k < video {+ s.u32(0x04, VIDEO).f64(0x38, 1.0).u64(0x8C, u64::MAX);+ } else {+ s.u32(0x04, AUDIO);+ }+ d.push(&s.0);+ }+ if let Some(a) = m.audio {+ let mut props = Data::new(0x1C + 0x14);+ props+ .u32(0x00, 0x1C)+ .u32(0x04, 100)+ .bytes(0x08, &AUDIO_MEDIA_PROPERTIES.0)+ .u32(0x18, 0x14)+ .u32(0x1C, u32::from(a.channels))+ .u32(0x20, 1)+ .u32(0x28, 8);+ d.push(&props.0);+ }+ Some(d.0)+}++/// An effect's chunk, as an OpenFX plug-in's.+/// A parameter's value, how many keyframes it has, and its keyframes: a+/// frame, an interpolation, the value and, for the numbers that have them,+/// their handles.+fn param_body(value: &ParamValue, keys: &[DocKey]) -> Vec<u8> {+ let mut b = Vec::new();+ match value {+ ParamValue::Number(v) => b.extend_from_slice(&v.to_le_bytes()),+ ParamValue::Integer(v) => b.extend_from_slice(&(*v as i32).to_le_bytes()),+ ParamValue::Numbers(v) => v.iter().for_each(|x| b.extend_from_slice(&x.to_le_bytes())),+ ParamValue::Text(t) => {+ let units: Vec<u8> = t+ .encode_utf16()+ .chain([0])+ .flat_map(u16::to_le_bytes)+ .collect();+ b.extend_from_slice(&(units.len() as u32).to_le_bytes());+ b.extend_from_slice(&units);+ }+ }+ b.extend_from_slice(&(keys.len() as u32).to_le_bytes());+ for k in keys {+ b.extend_from_slice(&k.frame.to_le_bytes());+ b.extend_from_slice(&k.interpolation.to_le_bytes());+ match value {+ ParamValue::Integer(_) => {+ let whole = k.value.first().copied().unwrap_or(0.0).round() as i32;+ b.extend_from_slice(&whole.to_le_bytes());+ }+ _ => k+ .value+ .iter()+ .for_each(|x| b.extend_from_slice(&x.to_le_bytes())),+ }+ // Each of the four, for every number.+ for group in 0..4 {+ for h in &k.handles {+ b.extend_from_slice(&h[group].to_le_bytes());+ }+ }+ }+ b+}++fn effect_chunk(e: &DocEffect) -> Vec<u8> {+ let mut d = Data::new(0x30);+ d.u32(0x00, 0x30)+ .bytes(0x04, &OFX_HOST.0)+ .u32(0x14, if e.transition { 5 } else { 2 })+ .u32(0x18, 1)+ .u32(+ 0x20,+ 0x400 | u32::from(e.bypass) | if e.before_pan_crop { 0x80 } else { 0 },+ );+ let id = d.text(&format!("{{Svfx:{}}}", e.plugin), false);+ let preset = d.text(+ if e.preset.is_empty() {+ "(Default)"+ } else {+ &e.preset+ },+ false,+ );+ d.u32(0x28, id).u32(0x2C, preset);+ let mut params = Vec::new();+ for (name, value) in &e.params {+ let n = utf16(name);+ let keys = e+ .keys+ .iter()+ .find(|(k, _)| k == name)+ .map_or(&[][..], |(_, k)| &k[..]);+ let body = param_body(value, keys);+ params.extend_from_slice(&(body.len() as u32).to_le_bytes());+ params.extend_from_slice(&(n.len() as u32).to_le_bytes());+ params.extend_from_slice(&n);+ params.extend_from_slice(&body);+ }+ d.push(&(params.len() as u32).to_le_bytes());+ d.push(&(e.params.len() as u32).to_le_bytes());+ d.push(¶ms);+ d.0+}++/// A list of effects: those switched off in it too, the first `before`+/// working before the event's Pan/Crop.+fn effects(w: &mut Writer, list: Guid, fx: &[Effect], before: usize, o: &WriteOptions<'_>) {+ w.begin_list(list);+ for (i, e) in fx.iter().enumerate() {+ if let Some(mut doc) = (o.effect)(e) {+ doc.bypass = !e.enabled;+ doc.before_pan_crop = i < before;+ w.block(EFFECT, &effect_chunk(&doc));+ }+ }+ w.end();+}++/// An envelope to write: its number, its range's bottom, top and rest, and+/// its points.+type EnvelopeOut = (i32, (f32, f32, f32), Vec<(i64, f32, i32)>);++/// A list of an event's envelopes: its header (the event's start and how+/// far its envelopes' places go), then each.+fn event_envelopes(w: &mut Writer, list: Guid, (start, length): (i64, i64), items: &[EnvelopeOut]) {+ w.begin_list(list);+ let mut head = Data::new(0x48);+ head.u32(0x00, 0x48)+ .i64(0x08, start)+ .i64(0x10, length)+ .u32(0x40, 1);+ w.block(ENVELOPES_HEADER, &head.0);+ for (number, range, points) in items {+ w.block(ENVELOPE, &envelope_chunk(*number, *range, points));+ }+ w.end();+}++/// A keyframe of a Track Motion's list: its curve and time, the picture's+/// where it turns around, where it is, its size and its rotation, each as+/// x, y, z and 1.+fn motion_key(+ size: u32,+ curve: u32,+ at: i64,+ [pivot, position, extent, rotation]: [[f64; 3]; 4],+) -> Data {+ let mut d = Data::new(size as usize);+ d.u32(0x00, size).u32(0x04, curve).i64(0x08, at);+ for (from, v) in [+ (0x10, pivot),+ (0x30, position),+ (0x50, extent),+ (0x70, rotation),+ ] {+ for (k, x) in v.into_iter().chain([1.0]).enumerate() {+ d.f64(from + 8 * k, x);+ }+ }+ d.f64(0x90, 1.0);+ d+}++/// A move's keyframe.+fn move_key(curve: u32, at: i64, parts: [[f64; 3]; 4], smoothness: f64) -> Vec<u8> {+ let mut d = motion_key(0xDC, curve, at, parts);+ d.f64(0xB0, smoothness).f64(0xCC, -1.0).f64(0xD4, 1.0);+ d.0+}++/// A shadow's or a glow's keyframe.+fn halo_key(+ curve: u32,+ at: i64,+ parts: [[f64; 3]; 4],+ color: [f32; 4],+ blur: f64,+ intensity: f64,+) -> Vec<u8> {+ let mut d = motion_key(0xD8, curve, at, parts);+ let [red, green, blue, alpha] = color;+ for (k, x) in [blue, green, red, alpha].into_iter().enumerate() {+ d.f32(0xB0 + 4 * k, x);+ }+ d.f64(0xC0, blur).f64(0xC8, intensity);+ d.0+}++/// A track's motion chunk: its switches, the project's shape it is made for,+/// and its three lists: the file measures from half the height (where) and+/// from the height (how big), and in radians.+fn motion_chunk(+ m: &crate::motion::TrackMotion,+ aspect: f64,+ three_d: bool,+ parent: bool,+) -> Vec<u8> {+ use crate::fx::{KeyCurve, Transform};+ use crate::motion::{Halo, HaloLook};+ let number = |c: KeyCurve| super::pancrop::curve_number(c);+ let framing = |t: &Transform| -> [[f64; 3]; 4] {+ let (w, h) = (+ f64::from(t.scale) * aspect,+ f64::from(t.scale) * f64::from(t.stretch),+ );+ [+ [+ f64::from(t.pivot[0]) * 2.0 * w.abs(),+ f64::from(t.pivot[1]) * 2.0 * h.abs(),+ 0.0,+ ],+ [f64::from(t.x) * 2.0 * aspect, f64::from(t.y) * 2.0, 0.0],+ [w, h, if parent { 1.0 } else { 0.05 }],+ [0.0, 0.0, f64::from(t.rotation_deg).to_radians()],+ ]+ };+ let spatial = |b: &crate::space::Box3d| -> [[f64; 3]; 4] {+ [+ [0.0; 3],+ [+ f64::from(b.x) * 2.0 * aspect,+ f64::from(b.y) * 2.0,+ f64::from(b.z) * 2.0 * aspect,+ ],+ [f64::from(b.width) * aspect, f64::from(b.height), 0.05],+ b.rotation.map(|r| f64::from(r).to_radians()),+ ]+ };+ let mut moves: Vec<Vec<u8>> = Vec::new();+ if three_d && !m.space_keys.is_empty() {+ for k in &m.space_keys {+ moves.push(move_key(+ number(k.curve),+ units(k.at),+ spatial(&k.value),+ 0.0,+ ));+ }+ } else if three_d {+ moves.push(move_key(0, 0, spatial(&m.space), 0.0));+ } else if m.keys.is_empty() {+ moves.push(move_key(0, 0, framing(&m.transform), 0.0));+ } else {+ for k in &m.keys {+ moves.push(move_key(+ number(k.curve),+ units(k.at),+ framing(&k.value),+ f64::from(k.smoothness) / 100.0,+ ));+ }+ }+ let look_parts = |l: &HaloLook, rest_z: f64| -> [[f64; 3]; 4] {+ [+ [0.0; 3],+ [f64::from(l.x) * 2.0 * aspect, f64::from(l.y) * 2.0, 0.0],+ [f64::from(l.size), f64::from(l.size), rest_z],+ [0.0; 3],+ ]+ };+ // Off, it stands as a new track's has it.+ let halo = |h: &Halo, unused: Vec<u8>| -> Vec<Vec<u8>> {+ if !h.on {+ return vec![unused];+ }+ let one = |l: &HaloLook, curve: u32, at: i64| {+ halo_key(+ curve,+ at,+ look_parts(l, 1.0),+ l.color,+ f64::from(l.blur),+ f64::from(l.intensity),+ )+ };+ if h.keys.is_empty() {+ vec![one(&h.look, 0, 0)]+ } else {+ h.keys+ .iter()+ .map(|k| one(&k.value, number(k.curve), units(k.at)))+ .collect()+ }+ };+ let shadow = halo(+ &m.shadow,+ halo_key(+ 0,+ 0,+ [[0.0; 3], [0.05, -0.05, 0.0], [1.0, 1.0, 1.0], [0.0; 3]],+ [0.0, 0.0, 0.0, 1.0],+ 0.05,+ 0.0,+ ),+ );+ let glow = halo(+ &m.glow,+ halo_key(+ 0,+ 0,+ [[0.0; 3], [0.0; 3], [1.05, 1.05, 1.0], [0.0; 3]],+ [1.0, 1.0, 0.0, 1.0],+ 0.05,+ 0.0,+ ),+ );+ let flags = 1u32+ | if parent { 4 } else { 0 }+ | if m.shadow.on { 8 } else { 0 }+ | if m.glow.on { 0x10 } else { 0 };+ let mut d = Data::new(0x24);+ d.u32(0x00, 0x24)+ .u32(0x04, flags)+ .u32(0x08, 1)+ .f64(0x14, aspect)+ .u32(0x1C, 3);+ for list in [moves, shadow, glow] {+ d.push(&(list.len() as u32).to_le_bytes());+ for k in list {+ d.push(&k);+ }+ }+ d.0+}++/// A file's envelope number for BananaV's kind on a track, and its+/// range's top and its default.+fn envelope_number(+ kind: EnvelopeKind,+ busses: &[crate::busses::BusId],+) -> Option<(i32, f32, f32, f32)> {+ use crate::busses::SendTo;+ match kind {+ EnvelopeKind::Volume => Some((0, 0.0, 2.0, 1.0)),+ EnvelopeKind::Pan => Some((1, -1.0, 1.0, 0.0)),+ EnvelopeKind::Send(SendTo::Bus(b)) => {+ let i = busses.iter().position(|&x| x == b)?;+ (i < 26).then_some((3 + i as i32, 0.0, 2.0, 1.0))+ }+ EnvelopeKind::CompositeLevel => Some((29, 0.0, 1.0, 1.0)),+ EnvelopeKind::FadeToColor => Some((30, -1.0, 1.0, 0.0)),+ _ => None,+ }+}++fn envelope_chunk(number: i32, range: (f32, f32, f32), points: &[(i64, f32, i32)]) -> Vec<u8> {+ let mut d = Data::new(0x4C);+ d.u32(0x00, 0x4C)+ .i32(0x08, number)+ .f32(0x0C, range.0)+ .f32(0x10, range.1)+ .f32(0x14, range.2)+ .u32(0x18, points.len() as u32)+ .u32(0x20, u32::MAX)+ .u32(0x34, 0x38)+ .run(0x38, 0x40, 4, u32::MAX)+ .u32(0x44, 1);+ for &(at, value, curve) in points {+ let mut pt = Data::new(0x38);+ pt.i64(0x00, at).f32(0x08, value).i32(0x0C, curve);+ d.push(&pt.0);+ }+ d.0+}++/// A track's or an event's property set: its size, 100, its GUID, its+/// items' size and one item.+fn properties(guid: Guid, item: &[u8]) -> Vec<u8> {+ let mut d = Data::new(0x1C);+ d.u32(0x00, 0x1C)+ .u32(0x04, 100)+ .bytes(0x08, &guid.0)+ .u32(0x18, item.len() as u32);+ d.push(item);+ d.0+}++/// Rounds a CD's time to its frames (588 samples at 44.1 kHz), as VEGAS+/// writes the CD layout's.+fn cd_time(t: Tick) -> i64 {+ let u = units(t).max(0);+ let samples = (u as f64 * 1e-7 * 44_100.0 + 0.5).floor() as i64;+ let frames = (samples + 294) / 588;+ (frames * 588 * UNITS + 22_050) / 44_100+}++/// A marker's chunk: time, length, number, flags, its two texts (and its+/// type with the 0x30 layout).+fn marker_chunk(+ time: i64,+ length: i64,+ number: u32,+ flags: u32,+ a: &str,+ b: &str,+ kind: Option<&[u8; 4]>,+) -> Vec<u8> {+ let size = if kind.is_some() { 0x30 } else { 0x28 };+ let mut d = Data::new(size);+ d.u32(0x00, size as u32)+ .i64(0x08, time)+ .i64(0x10, length)+ .u32(0x18, number)+ .u32(0x1C, flags);+ if let Some(k) = kind {+ d.bytes(0x28, &k[..]);+ }+ let first = d.text(a, true);+ let second = d.text(b, true);+ d.u32(0x20, first).u32(0x24, second);+ d.0+}++/// The name a take has without one of its own: its media file's, without+/// its extension.+fn stem(m: &MediaInfo) -> String {+ let name = match &m.source {+ MediaSource::File { path } => path.rsplit(['\\', '/']).next().unwrap_or(path),+ _ => &m.name,+ };+ name.rsplit_once('.').map_or(name, |(a, _)| a).to_string()+}++struct Ids {+ media: HashMap<MediaId, u32>,+ event: u64,+ track: u32,+}++#[allow(clippy::too_many_arguments)]+fn event(+ w: &mut Writer,+ p: &Project,+ c: &Clip,+ kind: TrackKind,+ ids: &mut Ids,+ group: u32,+ o: &WriteOptions<'_>,+) {+ let media_of = |m: MediaId| p.media.iter().find(|x| x.id == m);+ let takes = c.take_list();+ if takes.iter().all(|t| !ids.media.contains_key(&t.media)) {+ return;+ }+ let file_kind = if kind == TrackKind::Video {+ VIDEO+ } else {+ AUDIO+ };+ ids.event += 1;+ let id = (u64::from(file_kind) << 60) | ids.event;+ w.begin_list(EVENT);+ let mut h = Data::new(0x60);+ h.u32(0x00, 0x60)+ .u32(+ 0x04,+ 0x3001_0100+ | if c.muted { 2 } else { 0 }+ | if c.normalize.is_some() { 0x200 } else { 0 },+ )+ .u32(0x08, file_kind)+ .i64(0x10, units(c.start))+ .i64(0x18, units(c.duration))+ .i32(0x20, c.active_take() as i32)+ .f64(0x28, c.rate)+ .u32(0x3C, u32::MAX)+ .u64(0x40, id)+ .u32(0x48, group)+ .u32(0x4C, 2)+ .u32(0x50, 1);+ // The fades: their curves (and the pair the other way round), lengths.+ let (curve_in, curve_out) = (+ fade_curve_number(c.fade_in_curve),+ fade_curve_number(c.fade_out_curve),+ );+ let mut fades = Data::new(0x48);+ fades+ .u32(0x00, 0x48)+ .f32(0x0C, c.level)+ .f32(0x10, c.normalize.unwrap_or(1.0))+ .i32(0x14, curve_in)+ .i32(0x18, curve_out)+ .i32(0x1C, curve_out)+ .i32(0x20, curve_in)+ .i64(0x28, units(c.fade_in))+ .i64(0x30, units(c.fade_out));+ h.push(&fades.0);+ // The list of ids after the fades (empty), and the property set.+ let mut ids_list = Data::new(0x10);+ ids_list.u32(0x00, 0x10);+ h.push(&ids_list.0);+ h.push(&properties(EVENT_PROPERTIES, &[0; 4]));+ w.block(EVENT_HEADER, &h.0);+ for t in &takes {+ let Some(&mid) = ids.media.get(&t.media) else {+ continue;+ };+ let Some(m) = media_of(t.media) else {+ continue;+ };+ let at = c.source_in + t.offset;+ // A picture lasts as long as VEGAS gives one (5 s), or the event.+ let length = if m.still {+ (at + c.duration).max(Tick::from_seconds(5))+ } else {+ m.duration+ };+ let mut d = Data::new(0x2A);+ d.u32(0x00, 0x2A)+ .u32(0x04, 7)+ .u32(+ 0x08,+ if kind == TrackKind::Audio {+ c.audio_stream as u32+ } else {+ 0+ },+ )+ .i64(0x10, units(at))+ .i64(0x18, units(length - at).max(0))+ .u32(0x24, mid);+ let name = t.name.clone().unwrap_or_else(|| stem(m));+ let bytes = d.text(&name, false);+ d.u32(0x20, bytes);+ w.block(TAKE, &d.0);+ }+ if let Some(env) = c+ .envelope(EnvelopeKind::Velocity)+ .filter(|_| kind == TrackKind::Video)+ {+ let points = env+ .points+ .iter()+ .map(|p| (units(p.at), p.value, key_curve_number(p.curve)))+ .collect();+ event_envelopes(+ w,+ EVENT_ENVELOPES,+ (units(c.start), units(c.duration)),+ &[(VELOCITY, (-1.0, 10.0, 1.0), points)],+ );+ }+ match kind {+ TrackKind::Audio => {+ let mut a = Data::new(0x28);+ a.u32(0x00, 0x28)+ .u32(+ 0x04,+ match c.channels {+ ChannelMap::Both => 1000,+ ChannelMap::RightOnly => 1001,+ ChannelMap::LeftOnly => 1002,+ ChannelMap::Combine => 1005,+ ChannelMap::Swap => 1006,+ },+ )+ .u32(0x08, 8 | u32::from(c.invert_phase))+ .u32(0x0C, 2)+ .u32(0x10, 1)+ .f64(0x14, f64::from(c.pitch));+ w.begin_list(AUDIO_EVENT);+ w.block(AUDIO_EVENT, &a.0);+ w.end();+ }+ TrackKind::Video => {+ let resample = match c.resample {+ None => 0x200,+ Some(ResampleMode::Disable) => 0,+ Some(ResampleMode::FrameBlend) => 0x80,+ Some(ResampleMode::OpticalFlow) => 0x800,+ };+ let transition = c.transition_fx.as_ref().and_then(|fx| {+ let mut doc = (o.effect)(&Effect::plugin((**fx).clone()))?;+ doc.transition = true;+ doc.bypass = c.transition_bypass;+ // Where it is along the transition, first as the file has it.+ doc.params.retain(|(n, _)| n != "Transition");+ doc.params+ .insert(0, ("Transition".to_string(), ParamValue::Number(0.0)));+ Some(effect_chunk(&doc))+ });+ let mut v = Data::new(0x90);+ v.u32(0x00, 0x90)+ .u32(+ 0x04,+ u32::from(c.pan_crop.keep_aspect)+ | resample+ | if c.reduce_flicker { 0x100 } else { 0 },+ )+ .f64(0x08, 1.0)+ .f64(0x10, 1.0)+ .u32(0x70, u32::from(transition.is_some()))+ .f64(0x78, f64::from(c.undersample))+ .f64(0x88, 1.0);+ if let Some(t) = &transition {+ v.push(t);+ }+ w.begin_list(VIDEO_EVENT_LIST);+ w.block(VIDEO_EVENT, &v.0);+ if let (Some(env), true) = (+ c.envelope(EnvelopeKind::TransitionProgress),+ transition.is_some() && c.fade_in > Tick::ZERO,+ ) {+ let length = c.fade_in.0 as f64;+ let points = env+ .points+ .iter()+ .map(|p| {+ let place = (p.at.0 as f64 / length * 1_000_000.0).round() as i64;+ (place, p.value, key_curve_number(p.curve))+ })+ .collect();+ event_envelopes(+ w,+ VIDEO_EVENT_ENVELOPES_1,+ (units(c.start), 1_000_000),+ &[(TRANSITION_PROGRESS, (0.0, 1.0, 0.5), points)],+ );+ }+ w.end();+ if c.effects.iter().any(|e| (o.effect)(e).is_some()) {+ effects(w, EVENT_FX, &c.effects, c.pan_crop_at, o);+ }+ // Its Pan/Crop, when it is not a new event's.+ let size = media_of(c.media)+ .and_then(|m| m.video.as_ref())+ .map_or(c.pan_crop.size, |v| [v.width, v.height]);+ let whole = [crate::pancrop::PanCropKey::whole([+ f64::from(size[0]),+ f64::from(size[1]),+ ])];+ if let Some(b) = super::pancrop::write(&c.pan_crop, c.mask.as_ref(), size, &whole) {+ w.block(PAN_CROP, &b);+ }+ }+ }+ w.end();+}++fn track(+ w: &mut Writer,+ p: &Project,+ index: usize,+ ids: &mut Ids,+ groups: &HashMap<crate::model::GroupId, u32>,+ o: &WriteOptions<'_>,+) {+ let t = &p.tracks[index];+ let file_kind = if t.kind == TrackKind::Video {+ VIDEO+ } else {+ AUDIO+ };+ ids.track += 1;+ w.begin_list(TRACK);+ let mut h = Data::new(0x38);+ h.u32(0x00, 0x38)+ .u32(0x04, 0x0020_0000 | u32::from(t.muted))+ .u32(0x08, 0x44)+ .u32(0x0C, file_kind)+ .u32(0x14, index as u32)+ .u32(0x1C, ids.track)+ .u32(0x20, if t.kind == TrackKind::Video { 2 } else { 1 })+ .u32(0x24, 2)+ .u32(0x30, 1);+ let name = h.text(&t.name, true);+ h.u32(0x10, name);+ let mut item = Data::new(0x11C);+ item.u32(0x118, 0x7F00);+ h.push(&properties(TRACK_PROPERTIES, &item.0));+ w.block(TRACK_HEADER, &h.0);+ if !t.clips.is_empty() {+ w.begin_list(TRACK_HEADER);+ for c in &t.clips {+ let group = c.group.and_then(|g| groups.get(&g).copied()).unwrap_or(0);+ event(w, p, c, t.kind, ids, group, o);+ }+ w.end();+ }+ let busses: Vec<_> = p.busses.iter().map(|b| b.id).collect();+ let envelopes: Vec<_> = t+ .envelopes+ .iter()+ .filter_map(|e| Some((envelope_number(e.kind, &busses)?, e)))+ .collect();+ if !envelopes.is_empty() {+ w.begin_list(TRACK_ENVELOPES);+ let mut head = Data::new(0x48);+ head.u32(0x00, 0x48).u32(0x14, 0x2000_0000).u32(0x40, 1);+ w.block(ENVELOPES_HEADER, &head.0);+ for ((number, lo, hi, default), e) in envelopes {+ let points: Vec<(i64, f32, i32)> = e+ .points+ .iter()+ .map(|p| (units(p.at), p.value, key_curve_number(p.curve)))+ .collect();+ w.block(+ ENVELOPE,+ &envelope_chunk(number, (lo, hi, default), &points),+ );+ }+ w.end();+ }+ match t.kind {+ TrackKind::Audio => {+ let mut a = Data::new(0x310);+ let sends = |k: usize| {+ p.busses.get(k).and_then(|b| {+ t.sends+ .iter()+ .find(|s| s.to == crate::busses::SendTo::Bus(b.id))+ })+ };+ a.u32(0x00, 0x310)+ .u32(0x04, u32::MAX)+ .f32(0x0C, t.level)+ .f32(0x10, t.pan)+ .f32(0x18, 1.0)+ .u32(0x1FC, u32::from(t.invert_phase))+ .run(0x20, 0x118, 8, 6)+ .run(0x120, 0x1E8, 8, 1)+ .u32(0x200, 0x37)+ .f32(0x204, 1.0)+ .run(0x210, 0x2FC, 4, 1f32.to_bits())+ .u32(0x304, 3)+ .u32(0x308, 8);+ for k in 0..p.busses.len().min(26) {+ if let Some(send) = sends(k) {+ let gain = 10f32.powf(send.gain_db / 20.0);+ a.f32(0x124 + 8 * k, gain);+ }+ }+ w.begin_list(AUDIO_TRACK_LIST);+ w.block(AUDIO_TRACK, &a.0);+ w.end();+ }+ TrackKind::Video => {+ let has_fx = t.effects.iter().any(|e| (o.effect)(e).is_some());+ // Over its children, among a parent's.+ let depth = t.composite_depth;+ let parent = p+ .tracks+ .get(index + 1)+ .is_some_and(|n| n.kind == TrackKind::Video && n.composite_depth > depth);+ let mut v = Data::new(0xB4);+ v.u32(0x00, 0xB4)+ .u32(+ 0x0C,+ if parent { 0x40 } else { 0 } | if depth > 0 { 0x20 } else { 0 },+ )+ .u32(0xAC, u32::from(depth))+ .run(0x30, 0x3C, 4, 1f32.to_bits())+ .f32(0x4C, 1.0)+ .u32(0x64, composite_number(t.composite_mode))+ .f32(0x68, t.level)+ .u32(0x80, 4)+ .f32(0x84, 1.0)+ .u32(0xA0, u32::from(has_fx))+ .f32(0xA4, 1.0);+ w.begin_list(VIDEO_TRACK_LIST);+ w.block(VIDEO_TRACK, &v.0);+ w.end();+ let three_d = t.composite_mode == crate::model::CompositeMode::ThreeDSourceAlpha;+ let aspect = p.settings.width as f64 * f64::from(p.settings.pixel_aspect.ratio())+ / p.settings.height.max(1) as f64;+ if let Some(m) = &t.motion {+ w.begin_list(TRACK_MOTION_LIST);+ w.block(TRACK_MOTION, &motion_chunk(m, aspect, three_d, false));+ w.end();+ }+ if let Some(m) = &t.parent_motion {+ w.begin_list(PARENT_MOTION_LIST);+ w.block(TRACK_MOTION, &motion_chunk(m, 1.0, false, true));+ w.end();+ }+ effects(w, TRACK_FX, &t.effects, 0, o);+ w.begin_list(TRACK_LIST_B5707E20);+ w.end();+ w.begin_list(TRACK_FX_2);+ w.end();+ }+ }+ w.end();+}++/// The Preview bus's, the Master's and a made bus's records: a structure+/// of 0xC8 bytes, then (from 0xC8) a 0 and the rest's size, the device's+/// and the bus's names and VEGAS's defaults of its settings.+fn bus(kind: u32, name: &str, letter_bus: bool) -> Vec<u8> {+ let mut d = Data::new(0xC8);+ d.u32(0x00, 0xC8)+ .u32(0x04, 0x7800_0005)+ .u32(0x08, 0xC8)+ .u32(0x0C, kind)+ .run(0x1C, 0x54, 8, 0x3FF0_0000);+ let (device, label) = (utf16(""), utf16(name));+ d.u32(0x80, device.len() as u32)+ .u32(0x84, label.len() as u32)+ .u32(0x88, 2)+ .u32(0xA0, label.len() as u32);+ match kind {+ // The Preview bus.+ 7 => {+ d.u32(0x14, u32::MAX)+ .u32(0x94, u32::MAX)+ .u32(0x98, 0xFFFF_FFFE);+ }+ // The Master.+ 2 => {+ d.u32(0x8C, 1).u32(0x90, 1).u32(0x94, 1);+ }+ _ => {+ d.u32(0x10, 0x8000_0000)+ .u32(0x14, 1)+ .f32(0x6C, 1.0)+ .f32(0x74, 1.0)+ .u32(0x78, 0x37)+ .u32(0x8C, 1)+ .u32(0x98, 0xFFFF_FFFE)+ .u32(0xA4, 0x8000_0000);+ }+ }+ let mut rest = Vec::new();+ rest.extend_from_slice(&device);+ rest.extend_from_slice(&label);+ rest.extend_from_slice(&[0, 0]);+ rest.extend_from_slice(&label);+ if kind == 7 {+ rest.extend_from_slice(&[0; 48]);+ } else {+ let mut tail = Data::new(784);+ tail.u32(0x18, 0x2D8)+ .u32(0x20, 3)+ .u32(0x24, 0x23C)+ .u32(0x28, 4)+ .u32(0x30, 0x44)+ .f32(0x34, 1.0)+ .f32(0x44, 1.0)+ .f32(0x48, 1.0)+ .u32(0x4C, 2)+ .u32(0x260, 0x48)+ .u32(0x2AC, 0x48);+ if letter_bus {+ tail.run(0xA0, 0xFC, 4, 1f32.to_bits())+ .run(0x160, 0x1DC, 4, 1f32.to_bits());+ }+ rest.extend_from_slice(&tail.0);+ }+ d.push(&0u32.to_le_bytes());+ d.push(&(rest.len() as u32).to_le_bytes());+ d.push(&rest);+ d.0+}++/// A bus's fader (twice, as a linear gain) and switches, at their places.+fn bus_settings(b: &mut [u8], gain_db: f32, muted: bool, solo: bool) {+ let gain = 10f64.powf(f64::from(gain_db) / 20.0);+ b[0x18..0x20].copy_from_slice(&gain.to_le_bytes());+ b[0x20..0x28].copy_from_slice(&gain.to_le_bytes());+ b[0x5C..0x60].copy_from_slice(&u32::from(muted).to_le_bytes());+ b[0x60..0x64].copy_from_slice(&u32::from(solo).to_le_bytes());+}++fn mixer(w: &mut Writer, p: &Project) {+ w.begin_list(MIXER);+ let mut m = Data::new(0x7F8);+ m.u32(0x00, 4)+ .u32(0x04, 0x7EC)+ .u32(0x08, 0x7EC)+ .u32(0x0C, 1)+ .u32(0x10, 2)+ .u32(0x220, 1)+ .u32(0x228, p.busses.len().min(26) as u32)+ .run(0x25C, 0x2D8, 4, 0x8000_0000)+ .u32(0x6E0, 1)+ .u32(0x6E4, p.settings.sample_rate.0)+ .u32(0x6E8, 0x10);+ w.block(MIXER_SETTINGS, &m.0);+ w.block(BUS, &bus(7, "Preview", false));+ let mut master = bus(2, "Master", false);+ bus_settings(&mut master, p.master.gain_db, p.master.muted, false);+ w.block(BUS, &master);+ for (k, b) in p.busses.iter().take(26).enumerate() {+ let letter = (b'A' + k as u8) as char;+ let name = if b.channel.name.is_empty() {+ format!("Bus {letter}")+ } else {+ b.channel.name.clone()+ };+ let mut made = bus(3, &name, true);+ bus_settings(+ &mut made,+ b.channel.gain_db,+ b.channel.muted,+ b.channel.solo,+ );+ w.block(BUS, &made);+ }+ w.end();+}++/// A tree item's data: its name, its id, what it is (1: a folder, 2: a+/// media, `media` its id).+fn tree_data(name: &str, id: u32, kind: u32, media: u32) -> Vec<u8> {+ let mut d = Data::new(0x38);+ d.u32(0x00, 0x38).u32(0x14, kind).u32(0x2C, u32::MAX);+ if kind == 2 {+ d.u32(0x08, 2).u32(0x0C, media).f64(0x24, 1.0);+ } else {+ d.u32(0x08, id)+ .u32(0x18, u32::from(name != "Main Timeline"));+ }+ let bytes = d.text(name, true);+ d.u32(0x04, bytes);+ d.0+}++fn bins(+ w: &mut Writer,+ p: &Project,+ parent: Option<crate::bins::BinId>,+ ids: &Ids,+ next: &mut u32,+) {+ for b in p.bins.iter().filter(|b| b.parent == parent) {+ *next += 1;+ w.begin_list(TREE_ITEM);+ w.block(TREE_DATA, &tree_data(&b.name, *next, 1, 0));+ let kids = p.bins.iter().any(|k| k.parent == Some(b.id));+ let media: Vec<u32> = b+ .media+ .iter()+ .filter_map(|m| ids.media.get(m).copied())+ .collect();+ if kids || !media.is_empty() {+ w.begin_list(BINS);+ bins(w, p, Some(b.id), ids, next);+ for m in media {+ w.begin_list(TREE_ITEM);+ w.block(TREE_DATA, &tree_data("", 0, 2, m));+ w.end();+ }+ w.end();+ }+ w.end();+ }+}++/// Writes `p` as a `.veg`.+pub fn write(p: &Project, o: &WriteOptions<'_>) -> Vec<u8> {+ let mut w = Writer::new(PROJECT);+ w.block(HEADER, &header(p, o));+ let mut four = Data::new(0x24);+ four.u32(0x00, 0x24)+ .f64(0x04, 50f64.to_radians())+ .f64(0x0C, 1.0);+ w.begin_list(FOUR_LIST);+ w.block(FOUR, &four.0);+ w.end();+ if p.video_output_fx.iter().any(|e| (o.effect)(e).is_some()) {+ effects(&mut w, OUTPUT_FX, &p.video_output_fx, 0, o);+ }+ let mut ids = Ids {+ media: HashMap::new(),+ event: 0,+ track: 0,+ };+ let entries: Vec<(u32, Vec<u8>)> = p+ .media+ .iter()+ .enumerate()+ .filter_map(|(i, m)| {+ let id = 20 + i as u32;+ let e = media_entry(m, id)?;+ ids.media.insert(m.id, id);+ Some((id, e))+ })+ .collect();+ if !entries.is_empty() {+ w.begin_list(MEDIA_LIST);+ for (_, e) in &entries {+ w.block(MEDIA, e);+ }+ w.end();+ }+ // The groups, numbered from 1, of the events written.+ let mut groups: HashMap<crate::model::GroupId, u32> = HashMap::new();+ let mut members: Vec<Vec<u64>> = Vec::new();+ {+ let mut n = 0u64;+ for t in &p.tracks {+ let kind = if t.kind == TrackKind::Video {+ VIDEO+ } else {+ AUDIO+ };+ for c in &t.clips {+ if c.take_list()+ .iter()+ .all(|k| !ids.media.contains_key(&k.media))+ {+ continue;+ }+ n += 1;+ if let Some(g) = c.group {+ let k = *groups.entry(g).or_insert_with(|| {+ members.push(Vec::new());+ members.len() as u32+ });+ members[k as usize - 1].push((u64::from(kind) << 60) | n);+ }+ }+ }+ }+ if members.iter().any(|m| m.len() > 1) {+ w.begin_list(GROUPS);+ for (k, m) in members.iter().enumerate() {+ let mut g = Data::new(0x10);+ g.u32(0x00, 0x10)+ .u32(0x04, k as u32 + 1)+ .u32(0x08, m.len() as u32);+ for id in m {+ g.push(&id.to_le_bytes());+ }+ w.block(GROUP, &g.0);+ }+ w.end();+ }+ if !p.tracks.is_empty() {+ w.begin_list(TRACKS);+ for i in 0..p.tracks.len() {+ track(&mut w, p, i, &mut ids, &groups, o);+ }+ w.end();+ }+ let s = &p.summary;+ w.begin_list(SUMMARY_LIST);+ w.block(+ SUMMARY,+ &tags(&[+ (b"IENG", &s.engineer),+ (b"INAM", &s.title),+ (b"IART", &s.artist),+ (b"ICOP", &s.copyright),+ (b"ICMT", &s.comments),+ ]),+ );+ w.end();+ // Markers and regions share their numbers, in time order.+ let mut marks: Vec<(i64, i64, bool, &str)> = p+ .markers+ .iter()+ .map(|m| (units(m.time), 0, false, m.name.as_str()))+ .chain(p.regions.iter().map(|r| {+ (+ units(r.range.start),+ units(r.range.duration),+ true,+ r.name.as_str(),+ )+ }))+ .collect();+ marks.sort_by_key(|m| (m.0, m.2));+ if !marks.is_empty() {+ w.begin_list(MARKERS);+ for (n, (time, length, region, name)) in marks.iter().enumerate() {+ let chunk = marker_chunk(+ *time,+ *length,+ n as u32 + 1,+ u32::from(*region),+ name,+ "",+ None,+ );+ w.block(MARKER, &chunk);+ }+ w.end();+ }+ if !p.commands.is_empty() {+ w.begin_list(COMMANDS);+ for c in &p.commands {+ let what = format!("{}:{}", command_out(&c.command), c.parameter);+ w.block(+ MARKER,+ &marker_chunk(units(c.time), 0, 0, 0, &c.comment, &what, None),+ );+ }+ w.end();+ }+ if !p.cd_tracks.is_empty() || !p.cd_indices.is_empty() {+ w.begin_list(CD_LAYOUT);+ for t in &p.cd_tracks {+ let start = cd_time(t.range.start);+ let end = cd_time(t.range.start + t.range.duration);+ w.block(+ MARKER,+ &marker_chunk(start, end - start, 0, 1, &t.name, "", None),+ );+ }+ for i in &p.cd_indices {+ let mut chunk = marker_chunk(cd_time(i.time), 0, 0, 0, "", "", Some(b"cdng"));+ let mut extra = Data::new(20);+ extra.u32(0, 1);+ chunk.extend_from_slice(&extra.0);+ w.block(MARKER, &chunk);+ }+ w.end();+ }+ mixer(&mut w, p);+ let mut next = 0x100;+ if !p.bins.is_empty() {+ w.begin_list(BINS);+ bins(&mut w, p, None, &ids, &mut next);+ w.end();+ }+ w.begin_list(LIST_1F0900B5);+ w.end();+ w.begin_list(TIMELINES);+ w.begin_list(TREE_ITEM);+ w.block(TREE_DATA, &tree_data("Main Timeline", next + 1, 1, 0));+ w.end();+ w.end();+ let folders: Vec<(&[u8; 4], &str)> = [+ b"pmed", b"pgmu", b"prmd", b"prnd", b"ppre", b"prec", b"pcap", b"pavc", b"pvob", b"pcdx",+ b"pgtm", b"ppix", b"pmix", b"ptak", b"pblu", b"pvcd", b"pppt", b"ppsp", b"pmul", b"pdao",+ b"fmed", b"fgmu", b"frmd", b"frnd", b"fpre", b"frec", b"fdim", b"fblu", b"nblu", b"pmng",+ ]+ .into_iter()+ .map(|code| {+ let value = match code {+ b"ppre" => p.prerender_folder.as_str(),+ b"prec" => p.recorded_folder.as_str(),+ b"pmng" => "0",+ _ => "",+ };+ (code, value)+ })+ .collect();+ w.begin_list(FOLDERS);+ w.block(FOLDERS, &tags(&folders));+ w.end();+ w.finish()+}diff --git a/crates/timeline/src/xmeml/tests.rs b/crates/timeline/src/xmeml/tests.rsindex 9388da3..b7408ca 100644--- a/crates/timeline/src/xmeml/tests.rs+++ b/crates/timeline/src/xmeml/tests.rs@@ -798,7 +798,14 @@ fn what_the_format_cannot_say_is_counted() {let a = file(&mut p, r"C:\a.mp4", 0);let ids = p.insert_media(a, Tick::ZERO, Some(v), None).unwrap();p.trim_end(ids[0], s(2)).unwrap();- p.clip_mut(ids[0]).unwrap().transform.scale = 1.5;+ p.set_clip_framing(+ ids[0],+ &crate::fx::Transform {+ scale: 1.5,+ ..crate::fx::Transform::default()+ },+ )+ .unwrap();let bars = p.add_media(MediaInfo::generated(Generator::ColorBars, &p.settings));let bs = p.insert_media(bars, s(3), Some(v), None).unwrap();p.trim_end(bs[0], s(4)).unwrap();diff --git a/crates/timeline/src/xmeml/write.rs b/crates/timeline/src/xmeml/write.rsindex 4cf58d9..3f95c66 100644--- a/crates/timeline/src/xmeml/write.rs+++ b/crates/timeline/src/xmeml/write.rs@@ -286,8 +286,7 @@ impl<'a> Writer<'a> {/// Whether the format says all event `c` does.fn whole(&self, c: &Clip) -> bool {c.effects.is_empty()- && c.transform.is_identity()- && c.transform_keys.is_empty()+ && c.pan_crop.is_default()&& c.mask.is_none()&& c.freeze.is_none()&& c.reverse.is_none()diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rsindex 9f1cb23..c653f8b 100644--- a/crates/ui-egui/src/app.rs+++ b/crates/ui-egui/src/app.rs@@ -1234,6 +1234,19 @@ impl BananaApp {}}+ /// While playing, how long until the window paints again: when the+ /// project's next frame is due (drawn ahead, it shows then), and a 60th+ /// of a second at most, for the needle and the meters. Painting more+ /// often than that would draw the same window again, taking the+ /// processor and the card from what shows.+ fn until_next_picture(&self) -> Duration {+ let rate = self.frame_rate();+ let pos = self.playhead.unwrap_or(self.cursor);+ let next = rate.frame_start(rate.frame_at(pos) + 1);+ let wait = (next - pos).as_seconds_f64() / self.play_rate.abs().max(0.1);+ Duration::from_secs_f64((wait + 0.001).clamp(0.002, 1.0 / 60.0))+ }+/// The timeline's playback: looping in the loop region when Loop/// Playback is on, else on past the project's end until stopped (as/// VEGAS's).@@ -2100,7 +2113,9 @@ impl BananaApp {pub(crate) fn open_file(&mut self, path: PathBuf) {use crate::media_files::{FileKind, kind_of};match kind_of(&path) {- Some(FileKind::Project | FileKind::Timeline) => self.open_path(path),+ Some(FileKind::Project | FileKind::Timeline | FileKind::VegProject) => {+ self.open_path(path)+ }_ => {if let Some(&id) = self.import_paths(std::slice::from_ref(&path)).first() {self.place_media(id, self.cursor, None);@@ -2111,9 +2126,16 @@ impl BananaApp {/// Opens a project file, or an OpenTimelineIO timeline as a new one.pub(crate) fn open_path(&mut self, path: PathBuf) {- if crate::media_files::kind_of(&path) == Some(crate::media_files::FileKind::Timeline) {- crate::otio_ui::open(self, path);- return;+ match crate::media_files::kind_of(&path) {+ Some(crate::media_files::FileKind::Timeline) => {+ crate::otio_ui::open(self, path);+ return;+ }+ Some(crate::media_files::FileKind::VegProject) => {+ crate::veg_ui::open(self, &path);+ return;+ }+ _ => {}}let loaded = std::fs::read_to_string(&path).map_err(|e| e.to_string())@@ -2333,7 +2355,8 @@ impl BananaApp {self.enter_key();}if pressed(none, Key::Escape) {- if self.engine.is_recording() {+ // Esc stops, as VEGAS's Transport.Stop: the edit cursor stays.+ if self.engine.is_recording() || self.is_playing() || self.scrub_rate != 0.0 {self.stop();} else if self.timeline.edge_trim.is_some() {// Out of edge-trimming or Expanded Edit Mode.@@ -3247,6 +3270,31 @@ impl BananaApp {self.console.selected = None;}+ /// The first audio event with an effect `k` at its defaults and its FX+ /// window open, for the captures of the audio effects' panels. Whether+ /// there was an audio event.+ pub fn audio_effect_for_review(&mut self, k: bv_timeline::EffectKind) -> bool {+ let Some(clip) = self+ .project()+ .tracks+ .iter()+ .filter(|t| t.kind == TrackKind::Audio)+ .flat_map(|t| t.clips.iter())+ .map(|c| c.id)+ .next()+ else {+ return false;+ };+ self.modify(|p| {+ if let Some(c) = p.clip_mut(clip) {+ c.effects.push(bv_timeline::Effect::new(k));+ }+ });+ self.select_clip(clip, false);+ self.open_clip_window("fx-audio");+ true+ }+/// Equalizer of a few bands — a high pass, a peak on the middle, a high/// shelf on the sides, a bypassed notch — Mono Below on, and its FX/// window open. Whether there was an audio event.@@ -3274,8 +3322,9 @@ impl BananaApp {q,slope: 24,route,+ linear: false,};- s.bands[0] = band(BandType::HighPass, 70.0, 0.0, 1.0, Route::Stereo);+ s.bands[0] = band(BandType::HighPass, 70.0, 0.0, 0.707, Route::Stereo);s.bands[1] = band(BandType::Peaking, 450.0, 4.5, 1.2, Route::Mid);s.bands[2] = band(BandType::HighShelf, 7000.0, -5.0, 1.0, Route::Side);s.bands[3] = Band {@@ -3832,22 +3881,27 @@ impl BananaApp {return false;};let rate = self.project().settings.frame_rate;- let keys: Vec<bv_timeline::TransformKey> = (0..5)+ let Some(place) = self.project().clip_place_in(id) else {+ return false;+ };+ let keys: Vec<bv_timeline::pancrop::PanCropKey> = (0..5).map(|i| {- let at = rate.snap_floor(Tick(c.duration.0 * i / 6));let value = bv_timeline::Transform {x: 0.05 * i as f32,scale: 1.0 + 0.1 * i as f32,rotation_deg: 4.0 * i as f32,..bv_timeline::Transform::default()};- bv_timeline::TransformKey::new(at, value, bv_timeline::KeyCurve::Linear)+ bv_timeline::pancrop::PanCropKey {+ at: rate.snap_floor(Tick(c.duration.0 * i / 6)),+ ..bv_timeline::pancrop::key_from_transform(&value, &place)+ }}).collect();self.modify(|p| {if let Some(c) = p.clip_mut(id) {- c.transform = keys[0].value;- c.transform_keys = keys.clone();+ c.pan_crop.ensure_size(place.media);+ c.pan_crop.keys = keys.clone();}});self.pan_crop_properties_for_review(true);@@ -3991,7 +4045,9 @@ impl BananaApp {if let Some(pos) = self.engine.position() {self.playhead = Some(pos);}- ctx.request_repaint();+ // egui takes a frame's predicted time off the delay.+ let predicted = Duration::try_from_secs_f32(ctx.input(|i| i.predicted_dt));+ ctx.request_repaint_after(self.until_next_picture() + predicted.unwrap_or_default());} else {self.playhead = None;}@@ -4070,10 +4126,12 @@ impl BananaApp {}self.vu.update(self.engine.take_vu_levels(), std::time::Instant::now());- if self.meters.active()- || self.track_meters.values().any(MeterState::active)- || self.strip_meters.values().any(MeterState::active)- || self.vu.active()+ // (While playing the window paints more often than that anyway.)+ if !self.is_playing()+ && (self.meters.active()+ || self.track_meters.values().any(MeterState::active)+ || self.strip_meters.values().any(MeterState::active)+ || self.vu.active()){ctx.request_repaint_after(Duration::from_millis(33));}@@ -4416,7 +4474,7 @@ impl eframe::App for BananaApp {fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {let start = std::time::Instant::now();self.frame(ui);- frame_trace(start);+ frame_trace(ui.ctx(), start, self.preview.shown.map(|k| k.1));}/// Remembers the project open now, for the next start, and deletes the@@ -4455,9 +4513,9 @@ fn follow_host_window() {/// `BV_FRAME_TRACE=1`: each frame of the main window on the standard error,/// how long after the last one it started and how long it took (the-/// dialogs' windows, drawn inside it, included), to find out what slows-/// the interface down.-fn frame_trace(start: std::time::Instant) {+/// dialogs' windows, drawn inside it, included), the preview's picture and+/// what asked for the frame, to find out what slows the interface down.+fn frame_trace(ctx: &egui::Context, start: std::time::Instant, shown: Option<Tick>) {static TRACE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();static LAST: std::sync::Mutex<Option<std::time::Instant>> = std::sync::Mutex::new(None);if !*TRACE.get_or_init(|| std::env::var_os("BV_FRAME_TRACE").is_some_and(|v| v == "1")) {@@ -4467,7 +4525,17 @@ fn frame_trace(start: std::time::Instant) {let Ok(mut last) = LAST.lock() else { return };let since = last.map_or(0.0, |l| start.duration_since(l).as_secs_f64() * 1000.0);*last = Some(start);- eprintln!("frame +{since:.1} ms, took {took:.1} ms");+ // The picture showing, and what asked for this frame.+ let shown = shown.map_or(-1.0, Tick::as_seconds_f64);+ let causes: Vec<String> = ctx+ .repaint_causes()+ .iter()+ .map(ToString::to_string)+ .collect();+ eprintln!(+ "frame +{since:.1} ms, took {took:.1} ms, showing {shown:.3} s, asked by {}",+ causes.join(" ")+ );}/// Junta pedidos feitos durante o quadro (ex.: o menu "⋯" abrindo uma janeladiff --git a/crates/ui-egui/src/app/actions.rs b/crates/ui-egui/src/app/actions.rsindex 447efa2..aaac686 100644--- a/crates/ui-egui/src/app/actions.rs+++ b/crates/ui-egui/src/app/actions.rs@@ -232,8 +232,7 @@ impl BananaApp {c.fade_in_curve = src.fade_in_curve;c.fade_out_curve = src.fade_out_curve;if kind == TrackKind::Video {- c.transform = src.transform;- c.transform_keys = src.transform_keys.clone();+ c.pan_crop = src.pan_crop.clone();c.transition = src.transition;// Its velocity and transition progress envelopes.c.envelopes = src.envelopes.clone();@@ -1040,44 +1039,21 @@ impl BananaApp {/// fill the output frame.pub(crate) fn toggle_maintain_aspect(&mut self) {let keep = self- .all_selected(Some(TrackKind::Video), |c| c.transform.keeps_aspect())+ .all_selected(Some(TrackKind::Video), |c| c.pan_crop.keep_aspect).unwrap_or(true);let ids = self.selected_of(TrackKind::Video);self.set_maintain_aspect(&ids, !keep);}/// Maintain Aspect Ratio on video events `ids` (`keep`), or off: their- /// media stretched to fill the output frame. The switch is kept in- /// their framing (`Transform::keep_aspect`, Pan/Crop's Source).+ /// media stretched to fill the output frame (Pan/Crop's Source).pub(crate) fn set_maintain_aspect(&mut self, ids: &[ClipId], keep: bool) {let ids = ids.to_vec();- let s = self.project().settings;self.modify(|p| {for id in ids {- let Some(v) = p- .clip(id)- .and_then(|c| p.media(c.media))- .and_then(|m| m.video)- else {- continue;- };- let Some(c) = p.clip_mut(id) else { continue };- if keep {- c.transform.scale = 1.0;- c.transform.stretch = 1.0;- } else {- // Fill: scale to the width, stretch the height to match.- let (sx, sy) = (- s.width as f32 / v.width as f32,- s.height as f32 / v.height as f32,- );- let fit = sx.min(sy);- c.transform.scale = sx / fit;- c.transform.stretch = sy / sx;+ if let Some(c) = p.clip_mut(id) {+ c.pan_crop.keep_aspect = keep;}- c.transform.keep_aspect = Some(keep);- c.transform.box_size = [1.0; 2];- c.transform_keys.clear();}});}@@ -1352,9 +1328,13 @@ pub(crate) fn fill_frame(p: &mut bv_timeline::Project, ids: &[ClipId]) {let par = v.pixel_aspect.ratio() / s.pixel_aspect.ratio();let sx = s.width as f32 / (v.width as f32 * par).max(1.0);let sy = s.height as f32 / (v.height as f32).max(1.0);- if let Some(c) = p.clip_mut(id) {- c.transform.scale = sx.max(sy) / sx.min(sy).max(1e-6);- }+ let _ = p.set_clip_framing(+ id,+ &bv_timeline::Transform {+ scale: sx.max(sy) / sx.min(sy).max(1e-6),+ ..bv_timeline::Transform::default()+ },+ );}}@@ -1601,11 +1581,8 @@ mod tests {// 4:3 in a 16:9 frame: enlarged to fill its width.let s = p.settings;let fill = (s.width as f32 / 640.0) / (s.height as f32 / 480.0);- assert!(- (c.transform.scale - fill).abs() < 1e-4,- "{}",- c.transform.scale- );+ let scale = p.clip_transform_at(c.id, c.start).unwrap().scale;+ assert!((scale - fill).abs() < 1e-4, "{scale}");}}// A still image lasts as long as asked.diff --git a/crates/ui-egui/src/app/more_actions.rs b/crates/ui-egui/src/app/more_actions.rsindex e8cab28..8ff2c69 100644--- a/crates/ui-egui/src/app/more_actions.rs+++ b/crates/ui-egui/src/app/more_actions.rs@@ -906,11 +906,13 @@ impl BananaApp {s.width as f32 / v.width as f32,s.height as f32 / v.height as f32,);- if let Some(c) = p.clip_mut(id) {- c.transform.scale = sx.max(sy) / sx.min(sy);- c.transform.stretch = 1.0;- c.transform_keys.clear();- }+ let _ = p.set_clip_framing(+ id,+ &bv_timeline::Transform {+ scale: sx.max(sy) / sx.min(sy),+ ..bv_timeline::Transform::default()+ },+ );}});}diff --git a/crates/ui-egui/src/clip_windows.rs b/crates/ui-egui/src/clip_windows.rsindex 165d438..9753b18 100644--- a/crates/ui-egui/src/clip_windows.rs+++ b/crates/ui-egui/src/clip_windows.rs@@ -398,8 +398,7 @@ impl ClipWindows {c.pan_crop_at = src.pan_crop_at;}if o.framing && kind == TrackKind::Video {- c.transform = src.transform;- c.transform_keys = src.transform_keys.clone();+ c.pan_crop = src.pan_crop.clone();}if o.fades {c.fade_in = src.fade_in.min(c.duration);diff --git a/crates/ui-egui/src/commands.rs b/crates/ui-egui/src/commands.rsindex 11cb361..ff49b21 100644--- a/crates/ui-egui/src/commands.rs+++ b/crates/ui-egui/src/commands.rs@@ -37,6 +37,7 @@ pub enum Cmd {ImportProjectMedia,ImportEdl,ImportOtio,+ ImportVeg,ImportXml,ImportFcpxml,/// File › Import › Closed Captioning.@@ -48,6 +49,7 @@ pub enum Cmd {ExportFcpxml,ExportEdl,ExportOtio,+ ExportVeg,Properties,Exit,// Edit@@ -383,6 +385,7 @@ pub(crate) fn all() -> Vec<Cmd> {ImportProjectMedia,ImportEdl,ImportOtio,+ ImportVeg,ImportXml,ImportFcpxml,ImportClosedCaptioning,@@ -393,6 +396,7 @@ pub(crate) fn all() -> Vec<Cmd> {ExportFcpxml,ExportEdl,ExportOtio,+ ExportVeg,Properties,Exit,Undo,@@ -689,6 +693,7 @@ impl Cmd {ImportProjectMedia => tr("Project Media…"),ImportEdl => tr("EDL Text File (*.edl, *.txt)…"),ImportOtio => "OpenTimelineIO (*.otio, *.otioz)…",+ ImportVeg => tr("VEG Project (Experimental) (*.veg)…"),ImportXml => "Final Cut Pro 7/DaVinci Resolve (*.xml)…",ImportClosedCaptioning => tr("Closed Captioning…"),ImportFcpxml => "Final Cut Pro X (*.fcpxml)…",@@ -700,6 +705,7 @@ impl Cmd {ExportFcpxml => "Final Cut Pro X (*.fcpxml)…",ExportEdl => tr("EDL Text File (*.edl)…"),ExportOtio => "OpenTimelineIO (*.otio, *.otioz, *.otiod)…",+ ExportVeg => tr("VEG Project (*.veg)…"),Properties => tr("Properties…"),Exit => tr("Exit"),Undo => {@@ -1226,7 +1232,7 @@ impl Cmd {.all_selected(Some(TrackKind::Audio), |c| c.normalize.is_some()).unwrap_or(false),MaintainAspect => app- .all_selected(Some(TrackKind::Video), |c| c.transform.keeps_aspect())+ .all_selected(Some(TrackKind::Video), |c| c.pan_crop.keep_aspect).unwrap_or(true),AllFrames => app.all_selected(Some(TrackKind::Video), |c| c.all_frames)@@ -1437,6 +1443,7 @@ impl Cmd {ImportProjectMedia => crate::interchange_ui::import_project_media(app),ImportEdl => crate::interchange_ui::import_edl(app),ImportOtio => app.request(Pending::ImportOtio),+ ImportVeg => crate::veg_ui::import(app),ImportXml => app.request(Pending::ImportFcp(false)),ImportClosedCaptioning => app.import_closed_captioning(),ImportFcpxml => app.request(Pending::ImportFcp(true)),@@ -1453,6 +1460,7 @@ impl Cmd {}ExportEdl => crate::interchange_ui::export(app, crate::interchange_ui::Format::Edl),ExportOtio => crate::otio_ui::export(app),+ ExportVeg => crate::veg_ui::export(app),Properties => app.open_project_settings(),Exit => app.request(Pending::Exit),Undo => app.undo(),diff --git a/crates/ui-egui/src/event_properties.rs b/crates/ui-egui/src/event_properties.rsindex 7aeae86..a68c795 100644--- a/crates/ui-egui/src/event_properties.rs+++ b/crates/ui-egui/src/event_properties.rs@@ -98,7 +98,7 @@ impl EventPropertiesDialog {take_name: p.take_name(clip, c.active_take()).unwrap_or_default(),muted: c.muted,locked: c.locked,- keep_aspect: c.transform.keeps_aspect(),+ keep_aspect: c.pan_crop.keep_aspect,reduce_flicker: c.reduce_flicker,past_end,resample: c.resample,diff --git a/crates/ui-egui/src/external_monitor.rs b/crates/ui-egui/src/external_monitor.rsindex 2956648..94f3859 100644--- a/crates/ui-egui/src/external_monitor.rs+++ b/crates/ui-egui/src/external_monitor.rs@@ -11,9 +11,7 @@ use bv_core::{Tick, TimeRange};use bv_timeline::OutputRotation;use crate::app::BananaApp;-use crate::egui::{- self, Color32, ColorImage, Key, Rect, TextureHandle, TextureOptions, pos2, vec2,-};+use crate::egui::{self, Color32, Key, Rect, TextureHandle, TextureOptions, pos2, vec2};use crate::i18n::tr;use crate::preferences::preview_display;@@ -330,7 +328,7 @@ impl BananaApp {.then(|| fit((fw, fh), room)),};let (rgba, w, h) = prepare(&f.rgba, f.width, f.height, how);- let image = ColorImage::from_rgba_unmultiplied([w as usize, h as usize], &rgba);+ let image = crate::tabs::preview::frame_image([w as usize, h as usize], &rgba);match &mut ext.texture {Some(tex) => tex.set(image, TextureOptions::LINEAR),None => {diff --git a/crates/ui-egui/src/fmt.rs b/crates/ui-egui/src/fmt.rsindex c8cf1cb..8806b81 100644--- a/crates/ui-egui/src/fmt.rs+++ b/crates/ui-egui/src/fmt.rs@@ -229,7 +229,10 @@ pub fn parse_grouped(s: &str) -> Option<f64> {}/// [`drag`] showing [`num_grouped`].-pub fn drag_grouped<'a>(value: &'a mut f32, decimals: usize) -> crate::egui::DragValue<'a> {+pub fn drag_grouped<'a, N: crate::egui::emath::Numeric>(+ value: &'a mut N,+ decimals: usize,+) -> crate::egui::DragValue<'a> {crate::egui::DragValue::new(value).custom_formatter(move |v, _| num_grouped(v, decimals)).custom_parser(parse_grouped)diff --git a/crates/ui-egui/src/fx_window.rs b/crates/ui-egui/src/fx_window.rsindex 39f3f5d..454c3a6 100644--- a/crates/ui-egui/src/fx_window.rs+++ b/crates/ui-egui/src/fx_window.rs@@ -9,7 +9,7 @@ use crate::i18n::{tr, trc};use bv_core::{FrameRate, Tick};use bv_timeline::{Clip, ClipId, Effect, EffectKind, KeyCurve, MediaId, MediaInfo, Project, TrackId, TrackKind,- Transform, TransformKey,+ Transform,};use crate::app::BananaApp;@@ -24,6 +24,7 @@ use crate::pancrop_keys::KeyRow;use crate::presets::{self, Presets};use crate::tabs::properties;use crate::theme;+use bv_timeline::pancrop::{self as framing, PanCropKey, PlaceIn};/// A área de trabalho do Pan/Crop é clara e pontilhada.pub(crate) const WS_BG: Color32 = Color32::from_gray(236);@@ -329,10 +330,28 @@ enum Axis {#[derive(Clone, Copy, Debug)]enum Drag {- Move { vp: Viewport, from: Pos2 },- Resize { vp: Viewport, sx: f32, sy: f32 },- Rotate { vp: Viewport, from: f32 },- View { offset: Vec2, from: Pos2 },+ Move {+ vp: Viewport,+ from: Pos2,+ },+ Resize {+ vp: Viewport,+ sx: f32,+ sy: f32,+ },+ Rotate {+ vp: Viewport,+ from: f32,+ },+ /// The small circle where the box turns: only that moves.+ Pivot {+ at: (f32, f32),+ from: Pos2,+ },+ View {+ offset: Vec2,+ from: Pos2,+ },}#[derive(Clone, Copy, Debug, PartialEq)]@@ -351,6 +370,7 @@ enum MenuAction {FlipV,MatchOutput,MatchSource,+ FitAdjustment,}#[derive(Debug)]@@ -442,6 +462,17 @@ impl Space {)}+ /// [`Self::screen`] of a point in the numbers masks keep.+ pub(crate) fn screen64(&self, p: (f64, f64)) -> Pos2 {+ self.screen((p.0 as f32, p.1 as f32))+ }++ /// [`Self::media`] in the numbers masks keep.+ pub(crate) fn media64(&self, s: Pos2) -> (f64, f64) {+ let (x, y) = self.media(s);+ (f64::from(x), f64::from(y))+ }+pub(crate) fn media(&self, s: Pos2) -> (f32, f32) {((s.x - self.center.x) / self.k + self.src.0 / 2.0,@@ -473,6 +504,8 @@ impl PanEditor {enum PresetValue {Params(Vec<f32>),Pan(Transform),+ /// A Pan/Crop's box of its own shape (a framing keeps the frame's).+ PanBox(PanCropKey),/// An OFX plug-in's values.Plugin(crate::presets::PluginValues),/// A VST 3 effect's values and states.@@ -496,10 +529,11 @@ struct PanCtx<'a> {info: Option<&'a MediaInfo>,/// Instante editado (na timeline).t: Tick,- tf: Transform,+ /// The box there, and what its place depends on.+ key: PanCropKey,+ place: PlaceIn,vp: Viewport,src: (f32, f32),- out: (f32, f32),}/// What the FX window takes its size from: the chain, the node shown and@@ -1072,6 +1106,7 @@ impl FxWindow {chain: &[Effect],presets: &mut Presets,) -> f32 {+ let mut pan_box = None;let (current, owner, is_default) = match self.node {Node::PanCrop => {let FxTarget::Clip(id) = self.target else {@@ -1080,8 +1115,14 @@ impl FxWindow {let Some(c) = project.clip(id) else {return 0.0;};- let tf = c.transform_at(c.start + self.pan.pos);- (PresetValue::Pan(tf), PresetOwner::PanCrop, tf.is_identity())+ let Some(place) = project.clip_place_in(id) else {+ return 0.0;+ };+ let key = c.box_at(c.start + self.pan.pos, place.media, place.media_aspect);+ let tf = framing::transform_from_key(&key, &place);+ let whole = key.is_whole(place.media);+ pan_box = Some(key);+ (PresetValue::Pan(tf), PresetOwner::PanCrop, whole)}Node::Effect(i) => match chain.get(i) {// A plug-in at its defaults has no values of its own.@@ -1107,8 +1148,19 @@ impl FxWindow {None => return 0.0,},};+ let same_box = |v: &PresetValue| match (v, &pan_box) {+ (PresetValue::PanBox(a), Some(b)) => {+ let close = |x: f64, y: f64| (x - y).abs() < 1e-6;+ close(a.width, b.width)+ && close(a.height, b.height)+ && close(a.center[0], b.center[0])+ && close(a.center[1], b.center[1])+ && close(a.angle, b.angle)+ }+ _ => false,+ };let shown = match &self.preset {- Some((name, v)) if *v == current => name.clone(),+ Some((name, v)) if *v == current || same_box(v) => name.clone(),_ if is_default => tr("(Default)").to_string(),// A plug-in's preset, however it came (a Video FX tile): its// name.@@ -1165,10 +1217,24 @@ impl FxWindow {pick = Some((tr("(Default)").into(), default));}let mut items: Vec<(String, PresetValue)> = match &owner {- PresetOwner::PanCrop => presets::builtin_pan_crop()- .into_iter()- .map(|(n, tf)| (n.to_string(), PresetValue::Pan(tf)))- .collect(),+ PresetOwner::PanCrop => {+ // The shapes first: as large as fits in the media.+ let shapes = match self.target {+ FxTarget::Clip(id) => project.clip_place_in(id),+ _ => None,+ };+ let shapes = shapes.iter().flat_map(|place| {+ presets::PAN_CROP_SHAPES.iter().map(move |&(name, shape)| {+ let r = shape / place.media_aspect.max(1e-6);+ let key = PanCropKey::whole(place.media).matched(r);+ (tr(name).to_string(), PresetValue::PanBox(key))+ })+ });+ let rest = presets::builtin_pan_crop()+ .into_iter()+ .map(|(n, tf)| (n.to_string(), PresetValue::Pan(tf)));+ shapes.chain(rest).collect()+ }PresetOwner::Effect(k) => presets::builtin(*k).into_iter().map(|(n, pairs)| {@@ -1309,7 +1375,19 @@ impl FxWindow {{let (t, tf) = (c.start + self.pan.pos, *tf);let new = app.settings.prefs.new_motion_keys();- app.edit(|p| p.set_clip_transform_at_as(id, t, tf, new));+ if let Some(place) = project.clip_place_in(id) {+ let key = framing::key_from_transform(&tf, &place);+ app.edit(|p| p.set_clip_box_at(id, t, key, new));+ }+ }+ }+ (Node::PanCrop, PresetValue::PanBox(key)) => {+ if let FxTarget::Clip(id) = self.target+ && let Some(c) = project.clip(id)+ {+ let (t, key) = (c.start + self.pan.pos, *key);+ let new = app.settings.prefs.new_motion_keys();+ app.edit(|p| p.set_clip_box_at(id, t, key, new));}}(Node::Effect(i), PresetValue::Params(v)) => {@@ -1551,6 +1629,20 @@ impl FxWindow {}});ui.add_space(6.0);+ if e.kind.works_offline() {+ // On an event (or its media) the event plays+ // its sound made through the whole chain; a+ // track's or a bus's sound cannot change length.+ let on_event = matches!(target, FxTarget::Clip(_) | FxTarget::Media(..));+ crate::tabs::hint(+ ui,+ if on_event {+ tr("It changes the sound's length: the event plays its sound made through the whole chain, ready a moment after each change, and keeps its own length.")+ } else {+ tr("It changes the sound's length, so it works in an event's chain; here the sound goes through it unchanged.")+ },+ );+ }crate::tabs::hint(ui,&trf!(@@ -1630,20 +1722,24 @@ impl FxWindow {}self.pan.pos = self.pan.pos.clamp(Tick::ZERO, last);let t = clip.start + self.pan.pos;- let tf = clip.transform_at(t);+ let Some(place) = project.clip_place_in(id) else {+ return;+ };+ let key = clip.box_at(t, place.media, place.media_aspect);let pc = PanCtx {clip,info,t,- tf,- vp: pancrop::viewport_of(&tf, src, out),+ key,+ place,+ vp: Viewport::of(&key),src,- out,};let strip_h = crate::pancrop_keys::height();let body_h = (ui.available_height() - strip_h - 8.0).max(200.0);- let mut new_tf = None;+ let mut new_box = None;+ let mut new_source = None;// The Mask row picked: the masks' tools, properties and workspace.let mut new_mask = None;let masks = self.pan.row == KeyRow::Mask;@@ -1678,7 +1774,7 @@ impl FxWindow {.properties(ui, clip.mask.as_ref(), self.pan.pos);self.workspace_section(ui);} else {- new_tf = self.properties(ui, app, &pc);+ (new_box, new_source) = self.properties(ui, app, &pc);}});});@@ -1686,18 +1782,27 @@ impl FxWindow {ui.add_space(4.0 + 3.0);}let size = vec2(ui.available_width(), body_h);- if let Some(nt) = self.workspace(ui, app, &pc, size, &mut new_mask) {- new_tf = Some(nt);+ if let Some(k) = self.workspace(ui, app, &pc, size, &mut new_mask) {+ new_box = Some(k);}});app.settings.pan_crop_properties = properties;ui.add_space(4.0);self.key_strip(ui, app, clip, rate);- if let Some(nt) = new_tf {+ if let Some(k) = new_box {let key = egui::Id::new(("pancrop", id, self.gesture));let new = app.settings.prefs.new_motion_keys();app.modify_merged(key, |p| {- let _ = p.set_clip_transform_at_as(id, t, nt, new);+ let _ = p.set_clip_box_at(id, t, k, new);+ });+ }+ if let Some((keep, fill)) = new_source {+ let key = egui::Id::new(("pancrop-origem", id, self.gesture));+ app.modify_merged(key, |p| {+ if let Some(c) = p.clip_mut(id) {+ c.pan_crop.keep_aspect = keep;+ c.pan_crop.fill = fill;+ }});}if let Some(m) = new_mask {@@ -1796,17 +1901,17 @@ impl FxWindow {/// The properties beside the workspace, as VEGAS's grid lists them:/// the box's Position, its Rotation (the angle and where it turns),/// the keyframe's interpolation, the Source settings and the- /// Workspace. The new framing, when it changed.+ /// Workspace. The new box and the new Source settings, when they+ /// changed.fn properties(&mut self,ui: &mut egui::Ui,app: &mut BananaApp,pc: &PanCtx<'_>,- ) -> Option<Transform> {+ ) -> (Option<PanCropKey>, Option<(bool, bool)>) {let mut vp = pc.vp;- let tf = pc.tf;- let mut pivot = tf.pivot;- let (mut keep, mut fill) = (tf.keeps_aspect(), tf.fill_frame);+ let mut key = pc.key;+ let (mut keep, mut fill) = (pc.place.keep_aspect, pc.place.fill);let lock = self.pan.lock_aspect;let src = pc.src;section(ui, &mut self.pan.sections[0], tr("Position"), |ui| {@@ -1857,28 +1962,33 @@ impl FxWindow {.range(-360.0..=360.0),);if r.changed() {- vp = pancrop::turned(&vp, pivot, angle);+ let by = f64::from(angle).to_radians() - key.angle;+ key = key.turned(by);}- let mut at = pancrop::pivot_point(&vp, pivot);- let was = at;- prop(- ui,- tr("X Center"),- crate::fmt::drag_grouped(&mut at.0, 1).speed(1.0),- );- prop(- ui,- tr("Y Center"),- crate::fmt::drag_grouped(&mut at.1, 1).speed(1.0),+ let (mut x, mut y) = (key.pivot[0] as f32, key.pivot[1] as f32);+ let (rx, ry) = (+ prop(+ ui,+ tr("X Center"),+ crate::fmt::drag_grouped(&mut x, 1).speed(1.0),+ ),+ prop(+ ui,+ tr("Y Center"),+ crate::fmt::drag_grouped(&mut y, 1).speed(1.0),+ ),);- if at != was {- pivot = pancrop::pivot_of(&vp, at);+ if rx.changed() {+ key.pivot[0] = f64::from(x);+ }+ if ry.changed() {+ key.pivot[1] = f64::from(y);}});});// The keyframe at the cursor or the one before it (the first one,// made when changed, before there are any).- let keys = &pc.clip.transform_keys;+ let keys = &pc.clip.pan_crop.keys;let key_idx = keys.iter().rposition(|k| k.at <= self.pan.pos);let mut smooth_edit = None;section(@@ -1887,7 +1997,7 @@ impl FxWindow {tr("Keyframe interpolation"),|ui| {prop_grid(ui, "pc-interpolacao", |ui| {- let mut s = key_idx.map_or(0.0, |i| keys[i].smoothness);+ let mut s = key_idx.map_or(0.0, |i| (keys[i].smoothness * 100.0) as f32);let r = prop(ui,tr("Smoothness"),@@ -1912,20 +2022,11 @@ impl FxWindow {});});self.workspace_section(ui);- let settings = pivot != tf.pivot || keep != tf.keeps_aspect() || fill != tf.fill_frame;- (vp != pc.vp || settings).then(|| {- let base = Transform {- pivot,- keep_aspect: if keep != tf.keeps_aspect() {- Some(keep)- } else {- tf.keep_aspect- },- fill_frame: fill,- ..tf- };- pancrop::transform_for(&vp, &base, pc.src, pc.out)- })+ let new_box = vp.onto(&pc.vp, &key);+ (+ (new_box != pc.key).then_some(new_box),+ ((keep, fill) != (pc.place.keep_aspect, pc.place.fill)).then_some((keep, fill)),+ )}/// The properties' Workspace section (both rows have it), as VEGAS's:@@ -1992,7 +2093,7 @@ impl FxWindow {pc: &PanCtx<'_>,size: Vec2,new_mask: &mut Option<Option<bv_timeline::mask::PanCropMask>>,- ) -> Option<Transform> {+ ) -> Option<PanCropKey> {let (rect, resp) = ui.allocate_exact_size(size, Sense::click_and_drag());// The Mask row picked: the masks' tools work here, not the F's.let masks = self.pan.row == KeyRow::Mask;@@ -2007,9 +2108,9 @@ impl FxWindow {let mut changed = false;// The box turns about its pivot (Rotation's X and Y Center): the// pointer's angle round it.- let pivot = pc.tf.pivot;- let round_pivot =- |v: &Viewport, p: Pos2| (p - sp.screen(pancrop::pivot_point(v, pivot))).angle();+ let pivot = (pc.key.pivot[0] as f32, pc.key.pivot[1] as f32);+ let round_pivot = |p: Pos2| (p - sp.screen(pivot)).angle();+ let mut result = None;// Vista: roda do mouse e ferramenta de zoom.if resp.hovered()@@ -2042,9 +2143,12 @@ impl FxWindow {} else if !masks && resp.drag_started_by(PointerButton::Primary) {match hit(&sp, &vp, o, true) {Hit::Handle(sx, sy) => Some(Drag::Resize { vp, sx, sy }),+ _ if (sp.screen(pivot) - o).length() <= 7.0 => {+ Some(Drag::Pivot { at: pivot, from: o })+ }Hit::Rotate => Some(Drag::Rotate {vp,- from: round_pivot(&vp, o),+ from: round_pivot(o),}),Hit::Inside => Some(Drag::Move { vp, from: o }),Hit::Outside => None,@@ -2083,7 +2187,11 @@ impl FxWindow {vp.cx = (vp.cx / gx).round() * gx;vp.cy = (vp.cy / gy).round() * gy;}- changed = true;+ // The pivot goes with it.+ result = Some(pc.key.moved([+ f64::from(vp.cx) - pc.key.center[0],+ f64::from(vp.cy) - pc.key.center[1],+ ]));}Drag::Resize { vp: v0, sx, sy } => {let l = local(&sp, &v0, p);@@ -2095,12 +2203,24 @@ impl FxWindow {changed = true;}Drag::Rotate { vp: v0, from } => {- let mut a = v0.angle_deg + (round_pivot(&v0, p) - from).to_degrees();+ let mut a = v0.angle_deg + (round_pivot(p) - from).to_degrees();+ // Turned on from where it is, however far round it went.+ a += ((vp.angle_deg - a) / 360.0).round() * 360.0;if shift {a = (a / 15.0).round() * 15.0;}- vp = pancrop::turned(&v0, pivot, wrap180(a));- changed = true;+ result = Some(pc.key.turned(f64::from(a).to_radians() - pc.key.angle));+ }+ Drag::Pivot { at, from } => {+ let (mut x, mut y) =+ (at.0 + (p.x - from.x) / sp.k, at.1 + (p.y - from.y) / sp.k);+ if self.pan.snap {+ x = (x / gx).round() * gx;+ y = (y / gy).round() * gy;+ }+ let mut k = pc.key;+ k.pivot = [f64::from(x), f64::from(y)];+ result = Some(k);}}}@@ -2137,6 +2257,7 @@ impl FxWindow {// Menu do botão direito.let mut action = None;+ let adjustment = pc.info.is_some_and(MediaInfo::is_adjustment);let menu = if masks { None } else { Some(&resp) };menu.map(|resp| {resp.context_menu(|ui| {@@ -2153,44 +2274,43 @@ impl FxWindow {item(ui, tr("Flip Vertical"), MenuAction::FlipV);item(ui, tr("Match Output Aspect"), MenuAction::MatchOutput);item(ui, tr("Match Source Aspect"), MenuAction::MatchSource);+ if adjustment {+ item(+ ui,+ tr("Resize Adjustment Event to Project"),+ MenuAction::FitAdjustment,+ );+ }})});- let out = pc.out;- let mut result = None;+ let place = &pc.place;match action {- Some(MenuAction::Reset) => result = Some(Transform::default()),- Some(MenuAction::Center) => {- vp.cx = src.0 / 2.0;- vp.cy = src.1 / 2.0;- changed = true;- }- Some(MenuAction::FlipH) => {- let base = Transform {- flip_h: !pc.tf.flip_h,- ..pc.tf- };- result = Some(pancrop::transform_for(&vp, &base, src, out));- }- Some(MenuAction::FlipV) => {- let base = Transform {- flip_v: !pc.tf.flip_v,- ..pc.tf- };- result = Some(pancrop::transform_for(&vp, &base, src, out));- }- // The box's shape the frame's or the media's, its width kept.+ Some(MenuAction::Reset) => result = Some(PanCropKey::whole(place.media)),+ Some(MenuAction::Center) => result = Some(pc.key.centered(place.media)),+ Some(MenuAction::FlipH) => result = Some(pc.key.flipped_h()),+ Some(MenuAction::FlipV) => result = Some(pc.key.flipped_v()),+ // The shape of the frame or of the media, as large as fits.Some(MenuAction::MatchOutput) => {- vp.h = vp.w * out.1 / out.0;- changed = true;+ let r = (place.frame[0] * place.frame_aspect)+ / (place.frame[1] * place.media_aspect.max(1e-6));+ result = Some(pc.key.matched(r));}Some(MenuAction::MatchSource) => {- vp.h = vp.w * src.1 / src.0;- changed = true;+ result = Some(pc.key.matched(place.media[0] / place.media[1]));+ }+ Some(MenuAction::FitAdjustment) => {+ let id = pc.clip.id;+ app.modify(|p| {+ let _ = p.resize_adjustment_to_project(id);+ });}None => {}}if changed && result.is_none() {- result = Some(pancrop::transform_for(&vp, &pc.tf, src, out));+ result = Some(vp.onto(&pc.vp, &pc.key));+ }+ if let Some(k) = &result {+ vp = Viewport::of(k);}// Desenho (com o estado já atualizado).@@ -2261,7 +2381,7 @@ impl FxWindow {}},}- let tf = &pc.tf;+ let [crop_left, crop_right, crop_top, crop_bottom] = pc.key.crop;let shade = Color32::from_black_alpha(120);let crop = |u0: f32, v0: f32, u1: f32, v1: f32| {Rect::from_min_max(@@ -2270,24 +2390,21 @@ impl FxWindow {)};for (on, r) in [- (tf.crop_left > 0.0, crop(0.0, 0.0, tf.crop_left, 1.0)),- (- tf.crop_right > 0.0,- crop(1.0 - tf.crop_right, 0.0, 1.0, 1.0),- ),- (tf.crop_top > 0.0, crop(0.0, 0.0, 1.0, tf.crop_top)),- (- tf.crop_bottom > 0.0,- crop(0.0, 1.0 - tf.crop_bottom, 1.0, 1.0),- ),+ (crop_left > 0.0, crop(0.0, 0.0, crop_left, 1.0)),+ (crop_right > 0.0, crop(1.0 - crop_right, 0.0, 1.0, 1.0)),+ (crop_top > 0.0, crop(0.0, 0.0, 1.0, crop_top)),+ (crop_bottom > 0.0, crop(0.0, 1.0 - crop_bottom, 1.0, 1.0)),] {if on {painter.rect_filled(r, 0.0, shade);}}if masks {- let n = self.pan.grid.max(1.0);- let grid = self.pan.snap.then_some([src.0 / n, src.1 / n]);+ let n = f64::from(self.pan.grid.max(1.0));+ let grid = self+ .pan+ .snap+ .then_some([f64::from(src.0) / n, f64::from(src.1) / n]);let normal = self.pan.tool == Tool::Normal;*new_mask = self.pan.mask.workspace(ui,@@ -2300,7 +2417,10 @@ impl FxWindow {normal,);} else {- paint_f_box(&painter, &sp, &vp, tf, true);+ let shown = result.as_ref().unwrap_or(&pc.key);+ let flips = (shown.width < 0.0, shown.height < 0.0);+ let turns = (shown.pivot[0] as f32, shown.pivot[1] as f32);+ paint_f_box(&painter, &sp, &vp, flips, turns, true);}self.pan.view = Some((sp, vp));result@@ -2312,8 +2432,11 @@ impl FxWindow {/// what it asked for: the needle, the row, Sync Cursor, the masks on/// or off, the rows' new keyframes.fn key_strip(&mut self, ui: &mut egui::Ui, app: &mut BananaApp, clip: &Clip, rate: FrameRate) {+ let place = app.project().clip_place_in(clip.id);let cx = crate::pancrop_keys::StripCtx {clip,+ media: place.map_or([1.0; 2], |p| p.media),+ aspect: place.map_or(1.0, |p| p.media_aspect),rate,pos: self.pan.pos,row: self.pan.row,@@ -2346,12 +2469,13 @@ impl FxWindow {}if let Some((keys, drag)) = answer.keys {let set = move |p: &mut Project| {+ let media = p.clip_place_in(id).map(|place| place.media);let Some(c) = p.clip_mut(id) else { return };- if keys.position != c.transform_keys {- if let Some(first) = keys.position.first() {- c.transform = first.value;+ if keys.position != c.pan_crop.keys {+ c.pan_crop.keys = keys.position.clone();+ if let Some(m) = media {+ c.pan_crop.size = [m[0] as u32, m[1] as u32];}- c.transform_keys = keys.position.clone();}if let Some(m) = c.mask.as_mut()&& (!m.keys.is_empty() || !keys.mask.is_empty())@@ -2381,13 +2505,19 @@ impl FxWindow {let key = egui::Id::new(("qc-suavidade", id, at.0));let (curve, _) = app.settings.prefs.new_motion_keys();app.modify_merged(key, |p| {+ let media = p.clip_place_in(id).map(|place| place.media);let Some(c) = p.clip_mut(id) else { return };- if c.transform_keys.is_empty() {- c.transform_keys- .push(TransformKey::new(Tick::ZERO, c.transform, curve));+ if c.pan_crop.keys.is_empty()+ && let Some(m) = media+ {+ c.pan_crop.ensure_size(m);+ c.pan_crop.keys.push(PanCropKey {+ curve,+ ..PanCropKey::whole(m)+ });}- if let Some(k) = c.transform_keys.iter_mut().find(|k| k.at == at) {- k.smoothness = s.clamp(0.0, 100.0);+ if let Some(k) = c.pan_crop.keys.iter_mut().find(|k| k.at == at) {+ k.smoothness = f64::from(s.clamp(0.0, 100.0) / 100.0);}});}@@ -4047,7 +4177,8 @@ pub(crate) fn paint_f_box(painter: &Painter,sp: &Space,vp: &Viewport,- tf: &Transform,+ flips: (bool, bool),+ turns: (f32, f32),rotation: bool,) {// Unturned, on the pixels' middles: a pixel wide and sharp.@@ -4084,8 +4215,8 @@ pub(crate) fn paint_f_box(let s = vp.w.min(vp.h);let (fw, fh) = (0.54 * s, 0.81 * s);let (flip_x, flip_y) = (- if tf.flip_h { -1.0 } else { 1.0 },- if tf.flip_v { -1.0 } else { 1.0 },+ if flips.0 { -1.0 } else { 1.0 },+ if flips.1 { -1.0 } else { 1.0 },);let f: Vec<Pos2> = F_SHAPE.iter()@@ -4101,7 +4232,7 @@ pub(crate) fn paint_f_box(ants(painter, &f);// The small circle where the box turns: its middle, or its pivot// (Rotation's X and Y Center).- let turns = sp.screen(pancrop::pivot_point(vp, tf.pivot));+ let turns = sp.screen(turns);let middle: Vec<Pos2> = (0..=24).map(|i| turns + Vec2::angled(i as f32 / 24.0 * std::f32::consts::TAU) * 4.0).collect();@@ -4204,6 +4335,29 @@ mod tests {assert!(target.chain(app.project()).is_none());}+ /// A preset of a shape: the box of that shape, as large as fits, where+ /// the box was; not the frame's shape a framing would keep.+ #[test]+ fn a_shape_preset_gives_its_box() {+ let mut app = BananaApp::new(egui::Context::default());+ app.load_demo();+ let p = app.project().clone();+ let id = p+ .clips()+ .find(|(t, _)| t.kind == TrackKind::Video)+ .map(|(_, c)| c.id)+ .expect("a video event");+ let place = p.clip_place_in(id).expect("its place");+ let key = PanCropKey::whole(place.media).matched(1.0 / place.media_aspect);+ assert!(key.width < place.media[0]);+ let mut w = FxWindow::new(FxTarget::Clip(id), Node::PanCrop);+ w.apply_preset(&mut app, &p, &[], &PresetValue::PanBox(key));+ let c = app.project().clip(id).expect("the event");+ let now = c.box_at(c.start, place.media, place.media_aspect);+ assert_eq!((now.width, now.height), (key.width, key.height));+ assert_eq!(now.center, key.center);+ }+#[test]fn buttons_move_through_the_chain_the_pan_crop_among_them() {use bv_timeline::EffectKind;@@ -4598,9 +4752,10 @@ mod tests {frame(&ctx, &mut app, Vec::new());let c = app.project().clip(id).expect("clipe").clone();// O cursor está no meio do clipe: virou animação com dois quadros-chave.- assert_eq!(c.transform_keys.len(), 2, "{:?}", c.transform_keys);- assert_eq!(c.transform_at(c.start).scale, 1.0);- let tf = c.transform_at(app.cursor);+ assert_eq!(c.pan_crop.keys.len(), 2, "{:?}", c.pan_crop.keys);+ let at = |t: Tick| app.project().clip_transform_at(id, t).expect("clipe");+ assert_eq!(at(c.start).scale, 1.0);+ let tf = at(app.cursor);let expected = vp.w / (vp.w + 2.0 * 60.0 / sp.k);assert!((tf.scale - expected).abs() < 0.02,@@ -4612,7 +4767,8 @@ mod tests {app.project().clip(id).expect("clipe")- .transform_keys+ .pan_crop+ .keys.is_empty());}@@ -4655,13 +4811,13 @@ mod tests {let m = c.mask.expect("masks made");assert!(m.enabled && m.active(), "{m:?}");let (lo, hi) = m.paths[0].bounds().expect("a path");- let near = |a: f32, b: f32| (a - b).abs() < sp.src.0 * 0.01;+ let near = |a: f64, b: f64| (a - b).abs() < f64::from(sp.src.0) * 0.01;assert!(- near(lo[0], sp.src.0 * 0.25) && near(hi[0], sp.src.0 * 0.75),+ near(lo[0], f64::from(sp.src.0) * 0.25) && near(hi[0], f64::from(sp.src.0) * 0.75),"{lo:?} {hi:?}");assert!(- near(lo[1], sp.src.1 * 0.25) && near(hi[1], sp.src.1 * 0.5),+ near(lo[1], f64::from(sp.src.1) * 0.25) && near(hi[1], f64::from(sp.src.1) * 0.5),"{lo:?} {hi:?}");app.undo();@@ -4737,20 +4893,20 @@ mod tests {let on = segment_point(&was[0], 1, 0.37);// Clicked 3 pixels off the line, across it.let ahead = segment_point(&was[0], 1, 0.38);- let along = (sp.screen((ahead[0], ahead[1])) - sp.screen((on[0], on[1]))).normalized();- let p = sp.screen((on[0], on[1])) + vec2(-along.y, along.x) * 3.0;+ let along = (sp.screen64((ahead[0], ahead[1])) - sp.screen64((on[0], on[1]))).normalized();+ let p = sp.screen64((on[0], on[1])) + vec2(-along.y, along.x) * 3.0;click_at(&ctx, &mut app, p);let now = shapes(&app, id);assert_eq!(now[0].len(), was[0].len() + 1, "an anchor added");let a = now[0][2];- let target = sp.media(p);+ let target = sp.media64(p);// The point of the curve nearest the click.- let dist = |q: [f32; 2]| (q[0] - target.0).hypot(q[1] - target.1);+ let dist = |q: [f64; 2]| (q[0] - target.0).hypot(q[1] - target.1);let nearest = (0..=4000)- .map(|k| segment_point(&was[0], 1, k as f32 / 4000.0))+ .map(|k| segment_point(&was[0], 1, f64::from(k) / 4000.0)).min_by(|x, y| dist(*x).total_cmp(&dist(*y))).expect("points");- let px = 1.0 / sp.k;+ let px = 1.0 / f64::from(sp.k);assert!((a.at[0] - nearest[0]).abs() < px && (a.at[1] - nearest[1]).abs() < px,"{:?} {nearest:?}",@@ -4759,11 +4915,11 @@ mod tests {// The curve kept: its two halves run along the old segment.for seg in [1, 2] {for k in 1..10 {- let q = segment_point(&now[0], seg, k as f32 / 10.0);+ let q = segment_point(&now[0], seg, f64::from(k) / 10.0);let off = (0..=400)- .map(|j| segment_point(&was[0], 1, j as f32 / 400.0))+ .map(|j| segment_point(&was[0], 1, f64::from(j) / 400.0)).map(|w| (w[0] - q[0]).hypot(w[1] - q[1]))- .fold(f32::MAX, f32::min);+ .fold(f64::MAX, f64::min);assert!(off < 1.0, "{seg} {k}: {off}");}}@@ -4789,7 +4945,7 @@ mod tests {let (id, sp) = masked(&ctx, &mut app, tool);let was = shapes(&app, id)[0][1];assert!(was.after != [0.0; 2], "curved");- let p = sp.screen((was.at[0], was.at[1]));+ let p = sp.screen64((was.at[0], was.at[1]));click_at(&ctx, &mut app, p);let corner = shapes(&app, id)[0][1];assert_eq!(@@ -4814,24 +4970,31 @@ mod tests {let ctx = egui::Context::default();let mut app = BananaApp::new(ctx.clone());let (id, sp) = masked(&ctx, &mut app, MaskTool::AddAnchor);- let (w, h) = sp.src;+ let (w, h) = (f64::from(sp.src.0), f64::from(sp.src.1));let spots = [(0.85, 0.1), (0.95, 0.1), (0.9, 0.3)];for (x, y) in spots {- click_at(&ctx, &mut app, sp.screen((x * w, y * h)));+ click_at(&ctx, &mut app, sp.screen64((x * w, y * h)));for _ in 0..30 {frame(&ctx, &mut app, Vec::new());}}- click_at(&ctx, &mut app, sp.screen((spots[0].0 * w, spots[0].1 * h)));+ click_at(+ &ctx,+ &mut app,+ sp.screen64((spots[0].0 * w, spots[0].1 * h)),+ );let now = shapes(&app, id);assert_eq!(now.len(), 3, "a new path");assert_eq!(now[2].len(), 3, "{:?}", now[2]);for (a, (x, y)) in now[2].iter().zip(spots) {assert_eq!((a.before, a.after), ([0.0; 2], [0.0; 2]), "a corner");- assert!((a.at[0] - x * w).abs() < 1.0 / sp.k && (a.at[1] - y * h).abs() < 1.0 / sp.k);+ assert!(+ (a.at[0] - x * w).abs() < 1.0 / f64::from(sp.k)+ && (a.at[1] - y * h).abs() < 1.0 / f64::from(sp.k)+ );}// Closed: the next click starts another path.- click_at(&ctx, &mut app, sp.screen((0.86 * w, 0.92 * h)));+ click_at(&ctx, &mut app, sp.screen64((0.86 * w, 0.92 * h)));assert_eq!(shapes(&app, id).len(), 4);}@@ -4845,10 +5008,10 @@ mod tests {let mut app = BananaApp::new(ctx.clone());let (id, sp) = masked(&ctx, &mut app, MaskTool::Normal);let was = shapes(&app, id);- let (w, h) = sp.src;+ let (w, h) = (f64::from(sp.src.0), f64::from(sp.src.1));let (from, to) = (- sp.screen((0.05 * w, 0.05 * h)),- sp.screen((0.47 * w, 0.55 * h)),+ sp.screen64((0.05 * w, 0.05 * h)),+ sp.screen64((0.47 * w, 0.55 * h)),);drag_from(&ctx, &mut app, from, to);let r = Rect::from_two_pos(from, to);@@ -4858,7 +5021,7 @@ mod tests {.flat_map(|(i, s)| {s.iter().enumerate()- .filter(|(_, a)| r.contains(sp.screen((a.at[0], a.at[1]))))+ .filter(|(_, a)| r.contains(sp.screen64((a.at[0], a.at[1])))).map(move |(k, _)| (i, k))}).collect();@@ -4875,7 +5038,7 @@ mod tests {// One of them dragged: all move alike.let (gp, ga) = inside[0];let g = was[gp][ga].at;- let from = sp.screen((g[0], g[1]));+ let from = sp.screen64((g[0], g[1]));drag_from(&ctx, &mut app, from, from + vec2(30.0, 12.0));let now = shapes(&app, id);let d = [now[gp][ga].at[0] - g[0], now[gp][ga].at[1] - g[1]];@@ -4903,7 +5066,7 @@ mod tests {let (id, sp) = masked(&ctx, &mut app, MaskTool::Normal);let was = shapes(&app, id);let q = bv_timeline::mask::segment_point(&was[0], 0, 0.5);- let p = sp.screen((q[0], q[1]));+ let p = sp.screen64((q[0], q[1]));click_at(&ctx, &mut app, p);assert_eq!(mask_editor(&app).selected, Some(0));assert!(!mask_editor(&app).box_shows(), "one click: no box");@@ -4939,7 +5102,7 @@ mod tests {frame(&ctx, &mut app, Vec::new());let now = bv_timeline::mask::segment_point(&shapes(&app, id)[0], 0, 0.5);assert!(- (now[1] - (q[1] - 24.0 / sp.k)).abs() < 0.5 / sp.k,+ (now[1] - (q[1] - 24.0 / f64::from(sp.k))).abs() < 0.5 / f64::from(sp.k),"{now:?} {q:?}");}@@ -4954,11 +5117,14 @@ mod tests {let v = vp();let corner = box_point(&sp, &v, 1.0, 1.0);assert_eq!(hit(&sp, &v, corner, true), Hit::Handle(1.0, 1.0));- assert_eq!(hit(&sp, &v, sp.screen((450.0, 520.0)), true), Hit::Inside);- assert_eq!(hit(&sp, &v, sp.screen((900.0, 900.0)), true), Hit::Outside);+ assert_eq!(hit(&sp, &v, sp.screen64((450.0, 520.0)), true), Hit::Inside);+ assert_eq!(+ hit(&sp, &v, sp.screen64((900.0, 900.0)), true),+ Hit::Outside+ );// Round the box, up to its circle (0.55 of its diagonal, as VEGAS's),// it turns.- let round = sp.screen((500.0, 630.0));+ let round = sp.screen64((500.0, 630.0));assert_eq!(hit(&sp, &v, round, true), Hit::Rotate);assert_eq!(hit(&sp, &v, round, false), Hit::Outside);let ring = sp.screen((500.0 + 0.55 * 400f32.hypot(200.0), 500.0));diff --git a/crates/ui-egui/src/grading_curves.rs b/crates/ui-egui/src/grading_curves.rsindex 898accd..281dc1c 100644--- a/crates/ui-egui/src/grading_curves.rs+++ b/crates/ui-egui/src/grading_curves.rs@@ -5,14 +5,21 @@//! on —, or, the column wide enough (the pinned curves' left border//! dragged), side by side, each on its own graph. A graph zooms (its//! buttons in its corner, the mouse wheel, Num + and Num −; Num 5 resets-//! it) and pans when zoomed (Num 8, 6, 4 and 2). A double-click on a curve adds a point; points drag (the-//! ends: the shadows and the highlights); Page Up and Page Down pick the-//! next or the previous point, the arrows move it, Shift with them its-//! left tangent and Ctrl+Shift its right one; a point's menu locks or-//! unlocks its tangents and deletes it; the yellow handles of the point-//! picked shape the curve without moving it.+//! it) and pans when zoomed (Num 8, 6, 4 and 2). Every point has its+//! handles, as VEGAS's: a curve starts straight, its two ends' handles a+//! quarter along it; a double-click adds a point where it is, its handles+//! along the line between its neighbours and theirs turned toward it+//! ([`add_dot`]); a double-click on a point makes its handles level+//! ([`flatten`]). Points drag (the ends: the shadows and the highlights);+//! Page Up and Page Down pick the next or the previous point, the arrows+//! move it, Shift with them its left tangent and Ctrl+Shift its right+//! one; the menu locks or unlocks a point's tangents, resets it to the+//! diagonal, smooths the curve, shows the picked point's tangents or+//! all, locks the points' axis (up and down only) or to the grid, and+//! deletes a point; the yellow handles shape the curve without moving+//! it.-use bv_core::curve::{self, CurvePoint};+use bv_core::curve::{self, CurvePoint, Handles};use crate::egui::{self, Color32, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2};use crate::i18n::tr;@@ -120,8 +127,14 @@ pub struct GradingCurves {pub(crate) views: [View; 5],/// A drag under way: its curve, what it took and the curve as it was.drag: Option<(usize, Grip, Vec<CurvePoint>)>,- /// The point a menu is open for.- menu: Option<(usize, usize)>,+ /// The menu open, and the point it is for.+ menu: Option<Option<(usize, usize)>>,+ /// Every point's tangents shown, else the picked point's.+ pub all_tangents: bool,+ /// Points move up and down only (Lock axis), or onto the grid's lines+ /// near them (Lock to grid).+ pub lock_axis: bool,+ pub lock_grid: bool,}impl Default for GradingCurves {@@ -132,19 +145,153 @@ impl Default for GradingCurves {views: [View::default(); 5],drag: None,menu: None,+ all_tangents: false,+ lock_axis: false,+ lock_grid: false,}}}-/// Curve `c` as edited: no points stand for the straight line.+/// Curve `c` as edited: no points stand for the straight line VEGAS's+/// curves start as — its ends' handles a quarter along it.fn points(c: &[CurvePoint]) -> Vec<CurvePoint> {if c.is_empty() {- vec![CurvePoint::new(0.0, 0.0), CurvePoint::new(1.0, 1.0)]+ let h = ([-0.25, -0.25], [0.25, 0.25]);+ vec![+ CurvePoint::with(0.0, 0.0, h.0, h.1),+ CurvePoint::with(1.0, 1.0, h.0, h.1),+ ]} else {c.to_vec()}}+/// Point `i`'s neighbours' x (`wrap`: a hue curve's, its ends' a turn+/// round); `None` past an end.+fn neighbours(c: &[CurvePoint], i: usize, wrap: bool) -> (Option<f64>, Option<f64>) {+ let n = c.len();+ let before = if i > 0 {+ Some(c[i - 1].x)+ } else if wrap {+ Some(c[n - 1].x - 1.0)+ } else {+ None+ };+ let after = if i + 1 < n {+ Some(c[i + 1].x)+ } else if wrap {+ Some(c[0].x + 1.0)+ } else {+ None+ };+ (before, after)+}++/// Point `i`'s handles made level, as VEGAS's double-click on a point+/// makes them: each half the way to its neighbour, at most 0.125 (`wrap`:+/// a hue curve's, its ends' neighbours a turn round).+pub(crate) fn flatten(c: &mut [CurvePoint], i: usize, wrap: bool) {+ let x = c[i].x;+ let (before, after) = neighbours(c, i, wrap);+ let half = |gap: Option<f64>| gap.map_or(0.125, |g| g.clamp(0.0, 0.25) / 2.0);+ c[i].handles = Some(Handles {+ before: [-half(before.map(|b| x - b)), 0.0],+ after: [half(after.map(|a| a - x)), 0.0],+ split: false,+ });+}++/// `c` with a point added at `at`, as VEGAS's double-click adds one: its+/// handles along the line from the point before it to the one after —+/// in, half the way to the next; out, half the way from the one before —+/// and theirs toward it, half the way. Where it went.+pub(crate) fn add_dot(c: &[CurvePoint], at: [f64; 2], wrap: bool) -> (Vec<CurvePoint>, usize) {+ let mut out = c.to_vec();+ let n = c.len();+ let i = c.partition_point(|p| p.x < at[0]);+ let prev = if i > 0 {+ Some((i - 1, [c[i - 1].x, c[i - 1].y]))+ } else if wrap && n > 0 {+ Some((n - 1, [c[n - 1].x - 1.0, c[n - 1].y]))+ } else {+ None+ };+ let next = if i < n {+ Some((i, [c[i].x, c[i].y]))+ } else if wrap && n > 0 {+ Some((0, [c[0].x + 1.0, c[0].y]))+ } else {+ None+ };+ let mut p = CurvePoint::new(at[0], at[1]);+ if let (Some((_, a)), Some((_, b))) = (prev, next)+ && b[0] - a[0] > 1e-9+ {+ let slope = (b[1] - a[1]) / (b[0] - a[0]);+ let (din, dout) = ((at[0] - b[0]) / 2.0, (at[0] - a[0]) / 2.0);+ p.handles = Some(Handles {+ before: [din, din * slope],+ after: [dout, dout * slope],+ split: false,+ });+ }+ out.insert(i, p);+ let toward = |from: [f64; 2]| [(at[0] - from[0]) / 2.0, (at[1] - from[1]) / 2.0];+ // The neighbours' places in `out`, past the point added.+ let shifted = |k: usize| if k >= i { k + 1 } else { k };+ if let Some((k, a)) = prev {+ let k = shifted(k);+ let mut h = curve::handles(&out, k);+ h.after = toward(a);+ out[k].handles = Some(h);+ }+ if let Some((k, b)) = next {+ let k = shifted(k);+ let mut h = curve::handles(&out, k);+ h.before = toward(b);+ out[k].handles = Some(h);+ }+ if out[i].handles.is_none() {+ flatten(&mut out, i, wrap);+ }+ (out, i)+}++/// Every point given smooth handles: along the line from the point+/// before it to the one after, a third of the way to each (an end's+/// level).+pub(crate) fn smooth(c: &mut [CurvePoint], wrap: bool) {+ let old = c.to_vec();+ let n = old.len() as isize;+ let y_at = |k: isize| old[k.rem_euclid(n) as usize].y;+ for i in 0..old.len() {+ let x = old[i].x;+ let (before, after) = neighbours(&old, i, wrap);+ let slope = match (before, after) {+ (Some(b), Some(a)) if a - b > 1e-9 => {+ (y_at(i as isize + 1) - y_at(i as isize - 1)) / (a - b)+ }+ _ => 0.0,+ };+ let third = |gap: f64| gap.max(0.0) / 3.0;+ let din = before.map_or(0.0, |b| third(x - b));+ let dout = after.map_or(0.0, |a| third(a - x));+ c[i].handles = Some(Handles {+ before: [-din, -din * slope],+ after: [dout, dout * slope],+ split: false,+ });+ }+}++/// `p` near one of the grid's lines (its quarters) put on it.+pub(crate) fn to_grid(p: [f64; 2]) -> [f64; 2] {+ p.map(|v| {+ let q = (v * 4.0).round() / 4.0;+ if (v - q).abs() < 0.03 { q } else { v }+ })+}+/// The curves with curve `k` given `c`.fn with(curves: &[Vec<CurvePoint>], k: usize, c: Vec<CurvePoint>) -> Vec<Vec<CurvePoint>> {let mut out = curves.to_vec();@@ -382,11 +529,18 @@ fn graph(painter.rect_filled(r, 1.0, if on { color } else { theme::panel_dark() });painter.rect_stroke(r, 1.0, Stroke::new(1.2, color), egui::StrokeKind::Inside);}- // The picked point's handles (an end has none toward the side).- if let Some((pk, i)) = picked- && pk == k- && i < c.len()- {+ // The picked point's handles, or every point's (an end has none+ // toward the side).+ let tangents: Vec<usize> = if view.all_tangents {+ (0..c.len()).collect()+ } else {+ picked+ .filter(|&(pk, i)| pk == k && i < c.len())+ .map(|(_, i)| i)+ .into_iter()+ .collect()+ };+ for i in tangents {let h = curve::handles(&c, i);let base = [c[i].x, c[i].y];let at = to_screen(base);@@ -445,10 +599,18 @@ fn graph(if resp.dragged()&& let (Some((k, grip, base)), Some(p)) = (&view.drag, resp.interact_pointer_pos()){- let at = to_curve(p);+ let mut at = to_curve(p);let mut c = base.clone();match *grip {- Grip::Point(i) => move_point(&mut c, i, at),+ Grip::Point(i) => {+ if view.lock_grid {+ at = to_grid(at);+ }+ if view.lock_axis {+ at[0] = c[i].x;+ }+ move_point(&mut c, i, at)+ }Grip::Before(i) => crate::ofx_curves::move_handle(&mut c, i, false, at),Grip::After(i) => crate::ofx_curves::move_handle(&mut c, i, true, at),}@@ -467,67 +629,111 @@ fn graph(None => None,};}- // A double-click adds a point to the curve nearest it (the picked- // one's first).+ // A double-click on a point makes its handles level; elsewhere it adds+ // a point there to the curve nearest it (the picked one's first).if resp.double_clicked()&& let Some(p) = resp.interact_pointer_pos()- && !matches!(hit(p), Some((_, Grip::Point(_)))){- let at = to_curve(p);- let x = at[0].clamp(0.0, 1.0);- let nearest = order.iter().rev().copied().min_by(|&a, &b| {- let d = |k: usize| {+ if let Some((k, Grip::Point(i))) = hit(p) {+ let mut c = points(curves.get(k).map_or(&[][..], Vec::as_slice));+ flatten(&mut c, i, false);+ view.picked = Some((k, i));+ out = Some(with(curves, k, c));+ } else {+ let at = to_curve(p);+ let at = [at[0].clamp(0.0, 1.0), at[1].clamp(0.0, 1.0)];+ let nearest = order.iter().rev().copied().min_by(|&a, &b| {+ let d = |k: usize| {+ let c = points(curves.get(k).map_or(&[][..], Vec::as_slice));+ (curve::curve_at(&c, at[0]) - at[1]).abs()+ };+ d(a).total_cmp(&d(b))+ });+ if let Some(k) = nearest {let c = points(curves.get(k).map_or(&[][..], Vec::as_slice));- (curve::curve_at(&c, x) - at[1]).abs()- };- d(a).total_cmp(&d(b))- });- if let Some(k) = nearest {- let c = points(curves.get(k).map_or(&[][..], Vec::as_slice));- let added = crate::ofx_curves::add_point(&c, x);- view.picked = added- .iter()- .position(|q| (q.x - x).abs() < 1e-9)- .map(|i| (k, i));- out = Some(with(curves, k, added));+ let (added, i) = add_dot(&c, at, false);+ view.picked = Some((k, i));+ out = Some(with(curves, k, added));+ }}}- // A point's menu: Lock Tangents, Delete.+ // The menu: a point's (Lock Tangents, Reset, Delete) when one is under+ // the pointer; the curve's and the graph's.if resp.secondary_clicked()&& let Some(p) = resp.interact_pointer_pos(){- view.menu = match hit(p) {- Some((k, Grip::Point(i))) => {- view.picked = Some((k, i));- Some((k, i))- }- _ => None,+ let point = match hit(p) {+ Some((k, Grip::Point(i))) => Some((k, i)),+ _ => view.picked,};+ if let Some(pk) = point {+ view.picked = Some(pk);+ }+ view.menu = Some(point);}- if let Some((k, i)) = view.menu {- let c = points(curves.get(k).map_or(&[][..], Vec::as_slice));+ if let Some(point) = view.menu {resp.context_menu(|ui| {- if i >= c.len() {+ let curve_of = |k: usize| points(curves.get(k).map_or(&[][..], Vec::as_slice));+ if let Some((k, i)) = point+ && i < curve_of(k).len()+ {+ let c = curve_of(k);+ let locked = !curve::handles(&c, i).split;+ if crate::menus::toggle_item(ui, tr("Lock Tangents"), locked) {+ let mut c = c.clone();+ crate::ofx_curves::lock_handles(&mut c, i, !locked);+ out = Some(with(curves, k, c));+ }+ // Back on the diagonal, its handles level.+ if crate::menus::item(ui, tr("Reset")) {+ let mut c = c.clone();+ let x = c[i].x;+ move_point(&mut c, i, [x, x]);+ flatten(&mut c, i, false);+ out = Some(with(curves, k, c));+ ui.close();+ }+ if crate::menus::item(ui, tr("Smooth curves")) {+ let mut c = c.clone();+ smooth(&mut c, false);+ out = Some(with(curves, k, c));+ ui.close();+ }+ ui.separator();+ }+ if crate::menus::check_item(ui, tr("All tangents"), view.all_tangents, true, "") {+ view.all_tangents = true;ui.close();- return;}- let locked = !curve::handles(&c, i).split;- if crate::menus::toggle_item(ui, tr("Lock Tangents"), locked) {- let mut c = c.clone();- crate::ofx_curves::lock_handles(&mut c, i, !locked);- out = Some(with(curves, k, c));+ if crate::menus::check_item(ui, tr("Selected tangents"), !view.all_tangents, true, "") {+ view.all_tangents = false;+ ui.close();}- let end = i == 0 || i + 1 == c.len();- if ui- .add_enabled(!end, egui::Button::new(tr("Delete")))- .clicked()- {- let mut c = c.clone();- c.remove(i);- view.picked = None;- out = Some(with(curves, k, c));+ if crate::menus::toggle_item(ui, tr("Lock axis"), view.lock_axis) {+ view.lock_axis = !view.lock_axis;+ ui.close();+ }+ if crate::menus::toggle_item(ui, tr("Lock to grid"), view.lock_grid) {+ view.lock_grid = !view.lock_grid;ui.close();}+ if let Some((k, i)) = point+ && i < curve_of(k).len()+ {+ let c = curve_of(k);+ ui.separator();+ let end = i == 0 || i + 1 == c.len();+ if ui+ .add_enabled(!end, egui::Button::new(tr("Delete")))+ .clicked()+ {+ let mut c = c.clone();+ c.remove(i);+ view.picked = None;+ out = Some(with(curves, k, c));+ ui.close();+ }+ }});}// The mouse wheel zooms about the pointer.@@ -689,6 +895,32 @@ mod tests {assert_eq!(View::default().zoomed(1000.0, [0.5, 0.5]).zoom, ZOOM_MAX);}+ #[test]+ fn points_are_added_and_levelled_as_vegass() {+ // The straight line: a point added at (0.5, 0.7) takes handles+ // along the line between its neighbours, theirs turned to it.+ let c = points(&[]);+ let (added, i) = add_dot(&c, [0.5, 0.7], false);+ assert_eq!(i, 1);+ let h = curve::handles(&added, 1);+ assert!((h.before[0] + 0.25).abs() < 1e-9 && (h.before[1] + 0.25).abs() < 1e-9);+ assert!((h.after[0] - 0.25).abs() < 1e-9 && (h.after[1] - 0.25).abs() < 1e-9);+ let first = curve::handles(&added, 0).after;+ assert!((first[0] - 0.25).abs() < 1e-9 && (first[1] - 0.35).abs() < 1e-9);+ let last = curve::handles(&added, 2).before;+ assert!((last[0] + 0.25).abs() < 1e-9 && (last[1] + 0.15).abs() < 1e-9);+ // Level: half the way to each neighbour, at most 0.125.+ let mut c = added;+ flatten(&mut c, 1, false);+ let h = curve::handles(&c, 1);+ assert_eq!((h.before, h.after), ([-0.125, 0.0], [0.125, 0.0]));+ // A hue curve's single point: its neighbours a turn round.+ let mut one = vec![CurvePoint::new(0.3, 0.5)];+ flatten(&mut one, 0, true);+ assert_eq!(curve::handles(&one, 0).after, [0.125, 0.0]);+ assert_eq!(to_grid([0.26, 0.6]), [0.25, 0.6]);+ }+#[test]fn points_stay_between_their_neighbours() {let mut c = points(&[]);diff --git a/crates/ui-egui/src/history_label.rs b/crates/ui-egui/src/history_label.rsindex 7856d67..577a84c 100644--- a/crates/ui-egui/src/history_label.rs+++ b/crates/ui-egui/src/history_label.rs@@ -65,9 +65,9 @@ pub fn describe(before: &Project, after: &Project) -> &'static str {if o == c {continue;}- let label = if o.transform_keys != c.transform_keys {+ let label = if o.pan_crop.keys.len() != c.pan_crop.keys.len() {tr("Event Pan/Crop Position Keyframe")- } else if o.transform != c.transform {+ } else if o.pan_crop != c.pan_crop {tr("Event Pan/Crop")} else if o.effects != c.effects {tr("Event FX")diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rsindex 66e3d4e..b99fabc 100644--- a/crates/ui-egui/src/i18n/pt_br.rs+++ b/crates/ui-egui/src/i18n/pt_br.rs@@ -36,6 +36,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("(Untitled)", "(Sem título)"),("+ Add Effect", "+ Adicionar efeito"),("-90 Degrees", "-90 graus"),+ ("-Inf.", "-Inf."),("0 clamps at the value; higher bends toward it.","0 corta no valor; maior se curva até ele.",@@ -51,10 +52,21 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["0: o mesmo grão para todas as cores; 1: cada cor com o seu.",),("0° (original)", "0° (original)"),+ ("1 Hz flange", "Flange de 1 Hz"),("1 leaves the text's size as it is; more enlarges it, less shrinks it (about the anchor point).","1 mantém o tamanho do texto; mais o aumenta, menos o diminui (em torno do ponto de ancoragem).",),+ (+ "1.5:1 compression starting at -24 dB",+ "Compressão de 1,5:1 a partir de -24 dB",+ ),+ ("1.8 kHz", "1,8 kHz"),+ (+ "1.85:1 Academy aspect ratio",+ "Taxa de proporção 1.85:1 Academy",+ ),+ ("1/2 second delay", "Delay de 1/2 segundo"),("10 bit scale", "Escala de 10 bits"),("10 min Full HD at 30 fps ≈ {} GB",@@ -66,19 +78,65 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("100% Black and White", "100% preto e branco"),("100% Inversion", "100% de inversão"),+ ("100% Mono Digidelay 1-16", "Delay digital 100% mono 1-16"),+ (+ "100% Mono Digidelay 1-16 Tripl.",+ "Delay digital 100% mono 1-16 tercina",+ ),("105mm (23 elements)", "105 mm (23 elementos)"),("105mm Prime Lens", "Lente principal 105 mm"),+ (+ "10:1 compression starting at -9 dB",+ "Compressão de 10:1 a partir de -9 dB",+ ),+ ("12 bit", "12 bits"),+ ("12 dB/oct.", "12 dB/oit."),+ (+ "15 dB notch centered at 1000 Hz",+ "Corte de 15 dB centrado em 1000 Hz",+ ),+ ("16 bit", "16 bits"),("16-bit PCM", "PCM de 16 bits"),+ (+ "16:9 Widescreen TV aspect ratio",+ "Taxa de proporção da TV: 16:9 Widescreen",+ ),("16th", "Semicolcheia"),+ ("16th Note", "Semicolcheia"),+ ("16th Note Triplet", "Tercina de semicolcheia"),+ ("18 bit", "18 bits"),+ ("18 dB/oct.", "18 dB/oit."),("180 Degrees", "180 graus"),("180° (inverted)", "180° (invertido)"),+ ("1984 Shack Reverb", "Reverb de barraco 1984"),+ ("1:1 Square aspect ratio", "Taxa de proporção quadrada 1:1"),+ ("20 bit", "20 bits"),+ ("200 Hz high-pass", "Passa-altas em 200 Hz"),+ ("2000 Hz Notch", "Corte estreito em 2000 Hz"),+ ("2000 Hz Resonance", "Ressonância em 2000 Hz"),+ ("24 bit", "24 bits"),+ ("24 dB/oct.", "24 dB/oit."),("24-bit PCM", "PCM de 24 bits"),("25%", "25%"),("25% Black and White", "25% preto e branco"),+ (+ "2:1 compression starting at -18 dB",+ "Compressão de 2:1 a partir de -18 dB",+ ),+ (+ "2:1 Compression starting at -18 dB",+ "Compressão de 2:1 a partir de -18 dB",+ ),+ (+ "2:1 compression starting at -18 dB (ACX)",+ "Compressão de 2:1 a partir de -18 dB (ACX)",+ ),("2D Glow", "Brilho 2D"),("2D Shadow", "Sombra 2D"),("3-Band EQ", "Equalizador de 3 bandas"),+ ("3.6 kHz", "3,6 kHz"),("30 Degrees Light", "30 graus leve"),+ ("32 bit", "32 bits"),("32 bit (IEEE float)", "32 bits (ponto flutuante IEEE)"),("32 Bit (IEEE Float)", "32 Bits (ponto flutuante IEEE)"),("32 bit float", "32 bits flutuante"),@@ -92,6 +150,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Ponto flutuante 32 bits (níveis de vídeo)",),("32nd", "Fusa"),+ ("32nd Note", "Fusa"),+ ("32nd Note Triplet", "Tercina de fusa"),("35mm (9 elements)", "35 mm (9 elementos)"),("35mm Lens", "Lente 35 mm"),("360 Output", "Saída 360°"),@@ -105,21 +165,43 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["360° View: turn on 360 Output in Project Properties' Advanced tab first.","Visualização 360°: ligue antes a Saída 360° na aba Avançado das Propriedades do projeto.",),+ (+ "3:1 compression starting at -15 dB",+ "Compressão de 3:1 a partir de -15 dB",+ ),("3D Blinds", "Persianas 3D"),("3D Cascade", "Cascata 3D"),("3D Effects", "Efeitos 3D"),("3D Fly In/Out", "Voo 3D para dentro/fora"),("3D Shuffle", "Embaralhar 3D"),("3D Source Alpha", "Alfa da origem 3D"),+ ("4 Stage Feedback", "Realimentação de 4 estágios"),("40%", "40%"),("440 Hz (A) −12 dBFS", "440 Hz (lá) −12 dBFS"),+ ("440 Hz noise", "Ruído de 440 Hz"),("45 Degrees", "45 graus"),+ (+ "4:3 Standard TV aspect ratio",+ "Taxa de proporção da TV: 4:3 Standard",+ ),("5.1 Surround", "Surround 5.1"),("50%", "50%"),("50% Black and White", "50% preto e branco"),+ ("6 dB/oct.", "6 dB/oit."),("60 Degrees Extreme", "60 graus extremo"),+ (+ "60 Hz hum notch using four stacked filters",+ "Corte do zumbido de 60 Hz com quatro filtros empilhados",+ ),("60%", "60%"),("60% Inversion", "60% de inversão"),+ ("64th Note", "Semifusa"),+ ("64th Note Triplet", "Tercina de semifusa"),+ (+ "6:1 compression starting at -12 dB",+ "Compressão de 6:1 a partir de -12 dB",+ ),+ ("7.2 kHz", "7,2 kHz"),("7.5 IRE Setup", "Setup de 7,5 IRE"),("7.5 IRE setup", "Configuração 7,5 IRE"),("70-300mm (16 elements)", "70-300 mm (16 elementos)"),@@ -127,8 +209,11 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("75%", "75%"),("75% Black and White", "75% preto e branco"),("75% Inversion", "75% de inversão"),+ ("8 bit", "8 bits"),("8-bit (full range)", "8 bits (faixa completa)"),("8th", "Colcheia"),+ ("8th Note", "Colcheia"),+ ("8th Note Triplet", "Tercina de colcheia"),("90 Degrees", "90 graus"),("90° clockwise", "90° no sentido horário"),("90° counterclockwise", "90° no sentido anti-horário"),@@ -157,6 +242,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["A change to either event changes both.","Mudar um dos eventos muda os dois.",),+ (+ "A chorus, flanger or wide ensemble of three voices a side.",+ "Um coro, flanger ou ensemble largo de três vozes por lado.",+ ),("A circle opens from the middle onto the next picture.","Um círculo se abre do meio para a próxima imagem.",@@ -181,6 +270,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["A color of the picture that should be gray: pick it with the eyedropper.","Uma cor da imagem que deveria ser cinza: escolha-a com o conta-gotas.",),+ (+ "A compressor and a volume maximizer for mastering, up to 5.1.",+ "Um compressor e um maximizador de volume para masterização, até 5.1.",+ ),("A crossfade with a zoom, pixelation or blur that peaks halfway and resolves into the next picture.","Uma fusão com zoom, pixelização ou desfoque que chega ao máximo no meio e se resolve na próxima imagem.",@@ -201,6 +294,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["A filter package has this name: OK replaces it.","Já existe um pacote de filtros com este nome: OK o substitui.",),+ (+ "A frequency response you draw, accurate down to the lows.",+ "Uma resposta de frequência que você desenha, precisa até nos graves.",+ ),("A glow screened in by the highlights' brightness: the highlights soften.","Um brilho misturado pela claridade das luzes altas: as luzes altas suavizam.",@@ -221,6 +318,14 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["A line each: begin a title with a space, part two columns with a tab, begin a comment with //; quotation marks keep spaces.","Uma linha cada: comece um título com um espaço, separe duas colunas com Tab, comece um comentário com //; aspas mantêm os espaços.",),+ (+ "A low-, band- or high-pass filter that can ring at its frequency.",+ "Um filtro passa-baixas, passa-banda ou passa-altas que pode ressoar na sua frequência.",+ ),+ (+ "A musical compressor with parallel mix, soft clip and side-chain filter.",+ "Um compressor musical com mistura paralela, clip suave e filtro de side chain.",+ ),("A nested project's sound can't be edited in an audio editor.","O som de um projeto aninhado não pode ser editado num editor de áudio.",@@ -245,10 +350,39 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["A plain text file gives each line a title five seconds long, from the project's start. With times, each line holds the start, the end, the length and the text (tabs in a .txt file, commas in a .csv one), in the ruler's format.","Num arquivo de texto simples, cada linha vira um título de cinco segundos a partir do início do projeto. Com tempos, cada linha traz o início, o fim, a duração e o texto (separados por tabulação num .txt e por vírgula num .csv), no formato da régua.",),+ (+ "A plate, room or hall, with size, time and damping.",+ "Uma placa, sala ou salão, com tamanho, tempo e amortecimento.",+ ),("A project can't be nested in itself","Um projeto não pode ser aninhado nele mesmo",),+ (+ "A quick chorus: one to three modulated copies of the sound.",+ "Um coro rápido: de uma a três cópias moduladas do som.",+ ),+ (+ "A quick compressor, up to a limiter.",+ "Um compressor rápido, até um limitador.",+ ),+ (+ "A quick distortion, from warm to mangled.",+ "Uma distorção rápida, do quente ao triturado.",+ ),+ (+ "A quick echo, fed back by a share of itself.",+ "Um eco rápido, realimentado por uma parte de si mesmo.",+ ),+ ("A quick flange or wah-wah.", "Um flange ou wah-wah rápido."),+ (+ "A quick reverb: a room, its size and how lively it is.",+ "Uma reverb rápida: uma sala, o tamanho dela e quão viva ela é.",+ ),+ (+ "A room's reverberation: 19 spaces, early reflections and pre-delay.",+ "A reverberação de um ambiente: 19 espaços, primeiras reflexões e pré-atraso.",+ ),("A round area around each pixel; else a rectangle.","Uma área redonda em volta de cada pixel; senão, um retângulo.",@@ -287,6 +421,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["A subclip needs a part of its media at least a frame long.","Um subclipe precisa de uma parte da mídia de pelo menos um quadro.",),+ (+ "A sweeping flange, phaser or wah-wah.",+ "Um flange, phaser ou wah-wah que varre as frequências.",+ ),("A tile's height, a part of the frame's height (unless Square).","A altura de um bloco, uma parte da altura do quadro (a menos que Quadrado).",@@ -295,7 +433,52 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["A tile's width, a part of the frame's width.","A largura de um ladrilho, uma parte da largura do quadro.",),+ (+ "A tremolo, or an auto-pan when the sides move apart.",+ "Um tremolo, ou um auto-pan quando os lados se separam.",+ ),+ (+ "A voice's chain in one: high-pass, gate, de-esser, compressor and tone.",+ "A cadeia de uma voz numa só: passa-altas, portão, de-esser, compressor e tom.",+ ),("A weight of the matrix.", "Um peso da matriz."),+ (+ "A01. Music 1 (minimum flange, may echo)",+ "A01. Música 1 (flange mínimo, pode ecoar)",+ ),+ ("A02. Music 2", "A02. Música 2"),+ ("A03. Music 3 (less echo)", "A03. Música 3 (menos eco)"),+ (+ "A04. Music 4 (fast, good for bass)",+ "A04. Música 4 (rápido, bom para graves)",+ ),+ ("A05. Music 5", "A05. Música 5"),+ ("A06. Music 6", "A06. Música 6"),+ ("A07. Speech 1", "A07. Fala 1"),+ ("A08. Speech 2", "A08. Fala 2"),+ ("A09. Speech 3 (fast)", "A09. Fala 3 (rápido)"),+ ("A10. Solo instruments 1", "A10. Instrumentos solo 1"),+ ("A11. Solo instruments 2", "A11. Instrumentos solo 2"),+ ("A12. Solo instruments 3", "A12. Instrumentos solo 3"),+ (+ "A13. Solo instruments 4 (less echo)",+ "A13. Instrumentos solo 4 (menos eco)",+ ),+ ("A14. Solo instruments 5", "A14. Instrumentos solo 5"),+ ("A15. Solo instruments 6", "A15. Instrumentos solo 6"),+ (+ "A16. Solo instruments 7 (fast)",+ "A16. Instrumentos solo 7 (rápido)",+ ),+ (+ "A17. Drums, unpitched (minimum echo)",+ "A17. Bateria sem afinação (eco mínimo)",+ ),+ (+ "A18. Drums (better for toms)",+ "A18. Bateria (melhor para tons)",+ ),+ ("A19. Drums (tiny echo)", "A19. Bateria (eco pequeno)"),("AAC Audio", "Áudio AAC"),("AAC audio in an MPEG-4 file (.m4a).",@@ -323,6 +506,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Absolute Frames", "Quadros absolutos"),("Accent:", "Acento:"),("Accessed: {}", "Acessado: {}"),+ ("Accuracy", "Precisão"),("Accurate", "Precisa"),("ACES color space:", "Espaço de cor ACES:"),(@@ -330,6 +514,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["O ACES precisa do formato de pixel ponto flutuante 32 bits (faixa completa).",),("ACES version:", "Versão do ACES:"),+ ("Acoustic Guitar", "Violão"),("Action safe area (%):", "Área segura de ação (%):"),("Action:", "Ação:"),("Activate", "Ativar"),@@ -348,6 +533,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Active Take Information", "Informação de tomada ativa"),("Active Take Name", "Nome da tomada ativa"),("Active take name:", "Nome da tomada ativa:"),+ ("Adaptive release", "Liberação adaptativa"),("Add", "Adicionar"),("Add ->", "Adicionar ->"),("Add 50Hz Flicker", "Adicionar cintilação de 50Hz"),@@ -364,6 +550,14 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Add Across Time", "Adicionar ao longo do tempo"),("Add Across Tracks", "Adicionar em trilhas"),+ (+ "Add air (3 dB peak at 15 kHz)",+ "Dar ar (pico de 3 dB em 15 kHz)",+ ),+ (+ "Add air (boost above 16k by 6 dB)",+ "Dar ar (reforço de 6 dB acima de 16k)",+ ),("Add as CD Track", "Adicionar como faixa de CD"),("Add as Takes", "Adicionar como takes"),(@@ -404,6 +598,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Add Noise", "Adicionar ruído"),("Add path", "Adicionar caminho"),("Add Point", "Adicionar ponto"),+ ("Add space", "Abrir o estéreo"),("Add tags", "Adicionar tags"),("Add to Favorites", "Adicionar aos favoritos"),("Add to hue", "Somar à matiz"),@@ -525,6 +720,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Preferências avançadas de sincronização",),("Advanced…", "Avançado…"),+ ("Affect frequencies above", "Afetar frequências acima de"),("Affected Tracks", "Trilhas afetadas"),("Affected Tracks, Markers, and Regions",@@ -535,6 +731,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Aged tones of an old photograph.","Tons envelhecidos de fotografia antiga.",),+ ("Aggressive Bassdrum", "Bumbo agressivo"),("AI Assistant (Early Access)","Assistente de IA (acesso antecipado)",@@ -551,9 +748,12 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("AI Smoothen", "Suavização por IA"),("AI Smoothen.", "Suavização por IA."),("AI/ML", "IA/ML"),- ("Air", "Ar"),("Alignment:", "Alinhamento:"),("All", "Todos"),+ (+ "All bands use the same global band model",+ "Todas as bandas usam o mesmo modelo global",+ ),("All edits were undone (Redo brings them back).","Todas as edições foram desfeitas (Refazer as traz de volta).",@@ -647,6 +847,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Ambient Red Spotlight", "Foco vermelho ambiente"),("Amount", "Quantidade"),+ ("Amount (x:1)", "Quantidade (x:1)"),("Amount of correction", "Quantidade de correção"),("Amount of time to insert at the cursor:",@@ -654,6 +855,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Amount:", "Quantidade:"),("Amplitude", "Amplitude"),+ ("Amplitude Modulation", "Modulação de amplitude"),("An area must move less than this (a percentage of the frame's width a frame) to be blurred.","Uma área precisa se mover menos que isto (uma porcentagem da largura do quadro por quadro) para ser desfocada.",@@ -666,6 +868,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["An audio effect from a VST 3 plug-in.","Um efeito de áudio de um plug-in VST 3.",),+ (+ "An echo, or many fading away, its time in seconds or in notes of the tempo.",+ "Um eco, ou vários sumindo aos poucos, com o tempo em segundos ou em notas do andamento.",+ ),("An edge sweeps across the picture at any angle, revealing the next one; feather it for a softer change.","Uma beirada varre a imagem em qualquer ângulo, revelando a próxima; suavize-a para uma troca mais leve.",@@ -686,6 +892,47 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["An OpenTimelineIO bundle is still being packed or unpacked.","Um pacote OpenTimelineIO ainda está sendo empacotado ou desempacotado.",),+ ("Analog", "Analógico"),+ ("Analog Dual Delay", "Delay duplo analógico"),+ ("Analog Feedback", "Realimentação analógica"),+ ("Analog Mono 1-4 Tripl.", "Mono analógico 1-4 tercina"),+ ("Analog Mono 1-8", "Mono analógico 1-8"),+ ("Analog Mono 1-8 Dot.", "Mono analógico 1-8 pontuada"),+ ("Analog Mono 1-8 Tripl.", "Mono analógico 1-8 tercina"),+ ("Analog MonoDelay 124ms", "Delay mono analógico 124 ms"),+ ("Analog MonoDelay 251ms", "Delay mono analógico 251 ms"),+ ("Analog MonoDelay 343ms", "Delay mono analógico 343 ms"),+ ("Analog MonoDelay 433ms", "Delay mono analógico 433 ms"),+ ("Analog PingPong 1-16", "Pingue-pongue analógico 1-16"),+ (+ "Analog PingPong 1-16 Dot.",+ "Pingue-pongue analógico 1-16 pontuada",+ ),+ ("Analog PingPong 1-2", "Pingue-pongue analógico 1-2"),+ ("Analog PingPong 1-4", "Pingue-pongue analógico 1-4"),+ (+ "Analog PingPong 1-4 Dot.",+ "Pingue-pongue analógico 1-4 pontuada",+ ),+ (+ "Analog PingPong 1-4 Tripl.",+ "Pingue-pongue analógico 1-4 tercina",+ ),+ ("Analog PingPong 1-8", "Pingue-pongue analógico 1-8"),+ (+ "Analog PingPong 1-8 Dot.",+ "Pingue-pongue analógico 1-8 pontuada",+ ),+ (+ "Analog PingPong 1-8 Tripl.",+ "Pingue-pongue analógico 1-8 tercina",+ ),+ ("Analog PingPong 120ms", "Pingue-pongue analógico 120 ms"),+ ("Analog PingPong 134ms", "Pingue-pongue analógico 134 ms"),+ ("Analog PingPong 644ms", "Pingue-pongue analógico 644 ms"),+ ("Analog PlingPlong", "Plim-plom analógico"),+ ("Analog SlapBack", "Slapback analógico"),+ ("Analog Slow SlapBack", "Slapback analógico lento"),("Analysis Mode", "Modo de análise"),("Analysis Window", "Janela de análise"),("Analyze Motion", "Analisar movimento"),@@ -720,6 +967,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Outro número coloca os portais em outros lugares.",),("Anti alias", "Antisserrilhado"),+ ("Anti-DTMF talk-off", "Anti-DTMF (talk-off)"),+ ("Anti-DTMF Talkoff", "Anti-DTMF (talk-off)"),("Any condition", "Qualquer condição"),("Any hue: pick its color", "Qualquer matiz: escolha a cor"),("Aperture grill", "Grelha de abertura"),@@ -730,6 +979,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Apple ProRes em QuickTime: um codec de edição de qualidade constante. Codificador próprio do BananaV.",),("Apply", "Aplicar"),+ (+ "Apply an anti-alias filter during pitch shift",+ "Aplicar um filtro anti-alias ao mudar o tom",+ ),("Apply Blue Light Artifact Fix","Aplicar correção de artefatos de luz azul",@@ -783,7 +1036,21 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("at {}", "em {}"),("ATSC A 85 Mode", "Modo ATSC A 85"),("ATSC A/85", "ATSC A/85"),+ ("Attack", "Ataque"),("Attack (ms)", "Ataque (ms)"),+ (+ "Attack Enhancer 6dB Kick",+ "Realçar o ataque do bumbo (6 dB)",+ ),+ (+ "Attack Enhancer 6dB Snare",+ "Realçar o ataque da caixa (6 dB)",+ ),+ ("Attack speed", "Velocidade de ataque"),+ ("Attack time", "Tempo de ataque"),+ ("Attenuate bass frequencies", "Atenuar os graves"),+ ("Attenuate high frequencies", "Atenuar os agudos"),+ ("Attenuation frequency", "Frequência de atenuação"),("Attributes:", "Atributos:"),("Attributes: {}", "Atributos: {}"),("Audio", "Áudio"),@@ -842,10 +1109,13 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Auto Ducking Controls…", "Controles do ducking automático…"),("Auto Ducking Listener", "Ouvinte do ducking automático"),("Auto Ducking: {}", "Ducking automático: {}"),+ ("Auto gain compensate", "Compensar o ganho automaticamente"),+ ("Auto gain compensation", "Compensação automática de ganho"),("Auto Hide Docking Area","Ocultar automaticamente a área de encaixe",),+ ("Auto makeup", "Ganho de compensação automático"),("Auto Modes", "Modos automáticos"),("Auto Normalize", "Normalizar automaticamente"),("Auto normalize", "Normalização automática"),@@ -936,6 +1206,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Background Maximum Scale", "Fundo com escala máxima"),("Background No Blur", "Fundo sem desfoque"),("Backward", "Para trás"),+ ("Bad Experience", "Experiência ruim"),("Bad Sync", "Má sincronização"),("Balance (-3 dB center)", "Balanço (centro em -3 dB)"),("Balance (-6 dB center)", "Balanço (centro em -6 dB)"),@@ -991,15 +1262,77 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["As janelas do BananaV sempre esperam a atualização da tela: sem rasgos na imagem.",),("BananaV, version {}.{}", "BananaV, versão {}.{}"),+ ("Band", "Banda"),+ ("Band 1", "Banda 1"),+ ("Band 2", "Banda 2"),+ ("Band 3", "Banda 3"),+ ("Band 4", "Banda 4"),("Band Pass", "Passa-banda"),+ ("Band Stop", "Rejeita-banda"),+ (+ "Band uses a linear phase model",+ "A banda usa um modelo de fase linear",+ ),+ (+ "Band uses a minimum phase model",+ "A banda usa um modelo de fase mínima",+ ),("Band {}", "Banda {}"),+ ("Band-notch", "Banda"),+ ("Band-notch/boost", "Corte/reforço de banda"),+ ("Band-pass", "Passa-banda"),+ ("Bands: Band Pass 12 dB", "Bandas: passa-banda 12 dB"),+ ("Bands: Band Pass 18 dB", "Bandas: passa-banda 18 dB"),+ ("Bands: Band Pass 6 dB", "Bandas: passa-banda 6 dB"),+ ("Bands: Bell Notch", "Bandas: entalhe em sino"),+ ("Bands: High Pass 12 dB", "Bandas: passa-altas 12 dB"),+ ("Bands: High Pass 24 dB", "Bandas: passa-altas 24 dB"),+ ("Bands: High Pass 36 dB", "Bandas: passa-altas 36 dB"),+ ("Bands: High Pass 6 dB", "Bandas: passa-altas 6 dB"),+ (+ "Bands: Low + High Pass 12 dB",+ "Bandas: passa-baixas + passa-altas 12 dB",+ ),+ (+ "Bands: Low + High Pass 24 dB",+ "Bandas: passa-baixas + passa-altas 24 dB",+ ),+ (+ "Bands: Low + High Pass 36 dB",+ "Bandas: passa-baixas + passa-altas 36 dB",+ ),+ (+ "Bands: Low + High Pass 6 dB",+ "Bandas: passa-baixas + passa-altas 6 dB",+ ),+ (+ "Bands: Low + High Shelf",+ "Bandas: prateleiras de graves + agudos",+ ),+ ("Bands: Low Pass 12 dB", "Bandas: passa-baixas 12 dB"),+ ("Bands: Low Pass 24 dB", "Bandas: passa-baixas 24 dB"),+ ("Bands: Low Pass 36 dB", "Bandas: passa-baixas 36 dB"),+ ("Bands: Low Pass 6 dB", "Bandas: passa-baixas 6 dB"),+ ("Bands: Wide Bell", "Bandas: sino largo"),+ ("Bandwidth", "Largura de banda"),("Bank <", "Banco <"),("Bank >", "Banco >"),("Bar", "Barra"),("Barn Door", "Porta de celeiro"),("Bars", "Barras"),("Basic", "Básico"),+ ("Bass", "Graves"),+ (+ "Bass attenuation frequency",+ "Frequência de atenuação dos graves",+ ),("Bass Boost", "Graves reforçados"),+ ("Bass boost", "Reforço de graves"),+ ("Bass Guitar", "Baixo"),+ ("Bass Guitar channel", "Canal de baixo"),+ ("Bass Hum", "Zumbido grave"),+ ("Bass only", "Só graves"),+ ("BBD Voice Doubler", "Dobrador de voz BBD"),("Beat Detection", "Detecção de batidas"),("Beats per measure:", "Batidas por compasso:"),("Beats per minute:", "Batidas por minuto:"),@@ -1015,6 +1348,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Bevel", "Chanfro"),("Beveled", "Chanfrada"),("Bias", "Viés"),+ ("Big Boom Maker", "Fábrica de estrondos"),("Bit depth", "Profundidade de bits"),("Bit depth:", "Profundidade de bits:"),("Bit rate control:", "Controle da taxa de bits:"),@@ -1039,6 +1373,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Blend", "Mesclar"),("Blend amount", "Quantidade da mistura"),("Blend fields", "Mesclar campos"),+ ("Blend graph edges", "Suavizar as pontas do gráfico"),("Blend mixes the two frames around each one made; Nearest Frame takes the nearer one, moved along the motion.","Misturar combina os dois quadros em volta de cada um criado; Quadro mais próximo usa o mais próximo, movido ao longo do movimento.",@@ -1075,6 +1410,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Blues and yellows toward blue (left) or yellow (right).","Azuis e amarelos puxados para o azul (esquerda) ou o amarelo (direita).",),+ ("Bluesguitar", "Guitarra blues"),("Blur", "Desfoque"),("Blur %", "Desfoque %"),("Blur Amount", "Quantidade de desfoque"),@@ -1088,13 +1424,48 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Bold", "Negrito"),("Boost", "Reforço"),+ (+ "Boost bass around 125 Hz by 6 dB",+ "Reforçar 6 dB os graves perto de 125 Hz",+ ),+ (+ "Boost bass around 80 Hz by 6 dB",+ "Reforçar 6 dB os graves perto de 80 Hz",+ ),+ (+ "Boost bass frequencies below 250 Hz by 4 dB",+ "Reforçar 4 dB os graves abaixo de 250 Hz",+ ),+ (+ "Boost frequencies above 7 kHz",+ "Reforçar as frequências acima de 7 kHz",+ ),+ ("Boost high frequencies", "Realçar as frequências altas"),+ (+ "Boost high frequencies above 4 kHz by 6 dB",+ "Reforçar 6 dB os agudos acima de 4 kHz",+ ),+ (+ "Boost high frequencies above 7 kHz by 6 dB",+ "Reforçar 6 dB os agudos acima de 7 kHz",+ ),+ (+ "Boost mid-range around 1 kHz by 6 dB",+ "Reforçar 6 dB os médios perto de 1 kHz",+ ),("Boost Mids", "Realçar os meios-tons"),("Boost Midtones", "Realçar tons médios"),+ ("Boost positive signal", "Reforçar o lado positivo"),+ (+ "Boost upper three octaves",+ "Reforçar as três oitavas de cima",+ ),("Border", "Borda"),("Border color", "Cor da borda"),("Border size", "Tamanho da borda"),("Borders", "Margens"),("Both", "Ambos"),+ ("Both Sides Of The Story", "Os dois lados da história"),("Bottom", "Inferior"),("Bottom Center", "Inferior central"),("Bottom Left", "Inferior esquerdo"),@@ -1138,13 +1509,19 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Bottom…", "Inferior…"),("Bounce", "Quique"),("Bounces", "Quiques"),+ ("Bouncing flange", "Flange saltitante"),+ ("Bouncing wah", "Wah saltitante"),("Bound radius", "Raio de limite"),("Bow Tie Horizontal", "Gravata-borboleta horizontal"),("Bow Tie Vertical", "Gravata-borboleta vertical"),("Box", "Caixa"),("Box (asymmetric)", "Caixa (assimétrica)"),("Bright Center", "Centro brilhante"),+ ("Bright Corridor", "Corredor brilhante"),+ ("Bright hall", "Salão brilhante"),("Bright Light", "Luz brilhante"),+ ("Bright Medium Room", "Sala média brilhante"),+ ("Bright Small Room", "Sala pequena brilhante"),("Brighten", "Clarear"),("Brighten Brights", "Clarear os claros"),(@@ -1158,6 +1535,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Brightness and Contrast", "Brilho e contraste"),("Brightness:", "Brilho:"),("Brilliance", "Fulgor"),+ ("Bring Forward", "Trazer para a frente"),("Brings the brightness along with the colors; cleared, only the colors are matched.","Leva o brilho junto com as cores; desmarcado, só as cores são igualadas.",@@ -1168,8 +1546,11 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Broadcast Colors", "Cores de transmissão"),("Broadcast Wave Format…", "Formato Wave de transmissão…"),+ ("Broaden", "Alargar"),("Browse", "Procurar"),("Browse…", "Escolher…"),+ ("Bucket brigade", "Bucket brigade"),+ ("Bucket Brigade In Space", "Bucket brigade no espaço"),("Buffer underrun protection","Proteção contra falta de dados no buffer",@@ -1208,6 +1589,18 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Burning the disc in {}…", "Gravando o disco em {}…"),("Burning was canceled.", "A gravação foi cancelada."),("Bus", "Barramento"),+ (+ "Bus Comp - Drums NY Style",+ "Comp. de bus - bateria estilo NY",+ ),+ (+ "Bus Comp - snare enhancement",+ "Comp. de bus - realce da caixa",+ ),+ (+ "Bus Comp - snare enhancement 2",+ "Comp. de bus - realce da caixa 2",+ ),("Bus FX", "FX do barramento"),("Bus Tracks", "Trilhas de barramento"),("Bus {}", "Barramento {}"),@@ -1223,11 +1616,13 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Bypass", "Ignorar"),("Bypass All Audio FX", "Ignorar todos os FX de áudio"),("Bypass Color Grading", "Ignorar a matização de cores"),+ ("Bypass compressor", "Ignorar o compressor"),("Bypass FX", "Ignorar FX"),("Bypass FX and Envelopes", "Ignorar FX e envelopes"),("Bypass FX Automation", "Ignorar a automação FX"),("Bypass Hover Scrub", "Ignorar a varredura sob o ponteiro"),("Bypass Motion Blur", "Ignorar desfoque de movimento"),+ ("Bypass volume maximizer", "Ignorar o maximizador de volume"),("Bypass Zoom", "Ignorar o zoom"),("Bypass {}", "Ignorar {}"),("Bypassed", "Ignorado"),@@ -1262,6 +1657,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Categoria: {}. Clique com o botão direito no nó da cadeia para reordenar, desativar ou remover.",),("Cathedral", "Catedral"),+ ("Cathedral 1", "Catedral 1"),+ ("Cathedral 2", "Catedral 2"),+ ("Cathedral 3", "Catedral 3"),+ ("Cavernous Space", "Espaço cavernoso"),("CD Index", "Índice de CD"),("CD Quality Audio", "Áudio com qualidade de CD"),("CD Settings", "Configurações de CD"),@@ -1271,6 +1670,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Center", "Centro"),("Center and LFE", "Centro e LFE"),("Center burst", "Explosão central"),+ ("Center frequency", "Frequência central"),("Center image", "Centralizar imagem"),("Center Left", "Centro à esquerda"),("Center Mask, Glint", "Máscara central, brilho"),@@ -1283,6 +1683,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Center:", "Centro:"),("Centered", "Centralizado"),("Centered On Cut", "Centralizado no corte"),+ ("Central Station", "Estação central"),+ ("Cents", "Cents"),("Chain: {}", "Cadeia: {}"),("Chalk Scribbles", "Rabiscos a giz"),(@@ -1315,6 +1717,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Channel Bank Up", "Banco de canais acima"),("Channel Blend", "Mistura de canais"),("Channel count", "Número de canais"),+ (+ "Channel delay for stereo simulation",+ "Atraso de canal para simular estéreo",+ ),("Channel List", "Lista de canais"),("Channel Mapping", "Mapeamento de canais"),("Channel mapping:", "Mapeamento de canais:"),@@ -1328,6 +1734,11 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Channel {} Solo", "Solo do canal {}"),("Channel:", "Canal:"),("Channels", "Canais"),+ ("Channels to affect", "Canais afetados"),+ (+ "Channels to use for the control signal",+ "Canais que comandam",+ ),("Channels {}/{}", "Canais {}/{}"),("Channels {}–{}", "Canais {}–{}"),("Channels:", "Canais:"),@@ -1335,6 +1746,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Channels…", "Canais…"),("Chapters.{}", "Capítulos.{}"),("Charcoal Scribbles", "Rabiscos a carvão"),+ ("Cheap TV", "TV barata"),("Check for Software Updates…","Verifique se há atualizações do software…",@@ -1352,6 +1764,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Padrões xadrez e listrados: ladrilhos de duas cores, com bordas nítidas ou misturadas.",),("Checkerboard", "Xadrez"),+ ("Chest Punch", "Soco no peito"),("Choose a color: it goes to the cursor.","Escolha uma cor: ela vai para o cursor.",@@ -1379,6 +1792,29 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Choose the MIDI output for timecode in Options › Preferences › Sync.","Escolha a saída MIDI do código de tempo em Opções › Preferências › Sincronização.",),+ ("Chopper 1", "Picotador 1"),+ ("Chopper 2", "Picotador 2"),+ ("Chorus", "Coro"),+ ("Chorus / Original", "Coro / original"),+ ("Chorus 1", "Coro 1"),+ ("Chorus 2", "Coro 2"),+ ("Chorus 3", "Coro 3"),+ ("Chorus 4", "Coro 4"),+ ("Chorus 5", "Coro 5"),+ ("Chorus Classic Bass", "Coro clássico de baixo"),+ ("Chorus Fx Any Direction", "Coro em todas as direções"),+ ("Chorus out", "Saída do coro"),+ ("Chorus out delay", "Atraso da saída do coro"),+ ("Chorus size", "Tamanho do coro"),+ ("Chorus Vocal Spread", "Coro para abrir a voz"),+ ("Chorus-echo", "Coro-eco"),+ ("Chorus-reverse verb 1", "Coro-reverb invertida 1"),+ ("Chorus-reverse verb 2", "Coro-reverb invertida 2"),+ ("Chorus-reverse verb 3", "Coro-reverb invertida 3"),+ ("Chorus-verb", "Coro-reverb"),+ ("Chorus/Flanger", "Coro/flanger"),+ ("Chorus/vibrato 1", "Coro/vibrato 1"),+ ("Chorus/vibrato 2", "Coro/vibrato 2"),("Chroma", "Croma"),("Chroma Blur", "Desfoque de croma"),("Chroma Keyer", "Chroma Key"),@@ -1409,7 +1845,18 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Circular", "Circular"),("Circular area processing", "Processamento de área circular"),("Clamp to Edge", "Prender na borda"),+ ("Class", "Classe"),("Classic", "Clássico"),+ ("Classic Program Limiter", "Limitador de programa clássico"),+ (+ "Classic Snare Plate - wet",+ "Placa clássica de caixa - só efeito",+ ),+ ("Classic Vocal Plate", "Placa clássica de voz"),+ (+ "Classical Limiter (Transparent)",+ "Limitador clássico (transparente)",+ ),("Clean Project Media", "Limpar mídia de projeto"),("Clean Up Prerendered Video", "Limpar vídeo pré-renderizado"),("Clear", "Limpar"),@@ -1451,6 +1898,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Click a media file (Project Media or Explorer) to open it here.","Clique numa mídia (Mídia do projeto ou Explorador) para abri-la aqui.",),+ ("Click removal amount", "Quantidade de remoção de cliques"),("Click the Video Preview, or drag a rectangle over it","Clique na pré-visualização de vídeo ou arraste um retângulo sobre ela",@@ -1471,12 +1919,15 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Clip Buttons", "Botões dos clipes"),("Clip Controls", "Controles do clipe"),("Clip Effects", "Efeitos do clipe"),+ ("Clip gain", "Ganho do clipper"),("Clip Headers", "Cabeçalhos dos clipes"),("Clip Length — {}", "Duração do clipe — {}"),("Clip Length…", "Duração do clipe…"),("Clip Light", "Luz do clipe"),+ ("Clip shape", "Forma do clipper"),("Clipboard", "Área de transferência"),("Clock", "Relógio"),+ ("Clock drift", "Desvio do clock"),("Clock Wipe", "Relógio"),("Clockwise", "Sentido horário"),("Clockwise, Blend In", "Sentido horário, mesclado"),@@ -1645,6 +2096,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Comment", "Comentário"),("Comment:", "Comentário:"),("Comments:", "Comentários:"),+ ("Commercial", "Comercial"),+ ("Compander", "Compander"),("Company: {}", "Empresa: {}"),("Composite", "Composto"),("Composite Level", "Nível composto"),@@ -1662,11 +2115,28 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Compress Horizontally", "Comprimir horizontalmente"),("Compress Vertically", "Comprimir verticalmente"),("Compressed", "Compactado"),+ ("Compression", "Compressão"),+ (+ "Compression, limiting or gating drawn as an input/output curve.",+ "Compressão, limitação ou portão desenhados como uma curva de entrada/saída.",+ ),+ ("Compressor (legacy)", "Compressor (antigo)"),+ (+ "Compressor adaptive release",+ "Liberação adaptativa do compressor",+ ),+ ("Compressor attack", "Ataque do compressor"),+ (+ "Compressor auto makeup",+ "Compensação automática do compressor",+ ),+ ("Compressor/Gate", "Compressor/portão"),("Computer RGB to Studio RGB","RGB de computador para RGB de estúdio",),("Computer sound", "Som do computador"),+ ("Concert Hall", "Sala de concertos"),("Configure Generic Control", "Configurar controle genérico"),("Configure Mackie Control", "Configurar Mackie Control"),(@@ -1690,9 +2160,9 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Contents", "Sumário"),("Contents and Index", "Sumário e índice"),+ ("Contour (drop middle)", "Contorno (sem médios)"),("Contours", "Contornos"),("Contrast", "Contraste"),- ("Contrast Center", "Centro do contraste"),("Contrast center", "Centro do contraste"),("Contrast Center:", "Centro do contraste:"),("Contrast:", "Contraste:"),@@ -2069,6 +2539,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Cross Zoom A/B", "Zoom cruzado A/B"),("Cross Zoom A/B Slow", "Zoom cruzado A/B lento"),("Cross Zoom B Only", "Zoom cruzado só em B"),+ ("Crunchy Guitar", "Guitarra crocante"),+ ("Crystal ball", "Bola de cristal"),("Ctrl+{} has no Quick Tag yet: type a tag in Add Tags and press Ctrl+Shift+{}.","Ctrl+{} ainda não tem tag rápida: digite uma tag em Adicionar tags e pressione Ctrl+Shift+{}.",@@ -2128,6 +2600,18 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Cut All", "Cortar tudo"),("Cut away all but section", "Recortar tudo menos a forma"),("Cut away section", "Recortar a forma"),+ (+ "Cut high frequencies above 4 kHz by 12 dB",+ "Cortar 12 dB os agudos acima de 4 kHz",+ ),+ (+ "Cut low frequencies below 125 Hz by 60 dB",+ "Cortar 60 dB os graves abaixo de 125 Hz",+ ),+ (+ "Cut mid-range around 1 kHz by 6 dB",+ "Cortar 6 dB os médios perto de 1 kHz",+ ),("Cut, copy, and delete grouped events","Recortar, copiar e excluir eventos agrupados",@@ -2145,6 +2629,12 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Cyan Spotlight", "Foco ciano"),("Cycles", "Ciclos"),("Damping", "Amortecimento"),+ ("Dance Limiter (Loud)", "Limitador dance (alto)"),+ ("Dance Limiter (Moderate)", "Limitador dance (moderado)"),+ (+ "Dance Limiter (Tight Bass)",+ "Limitador dance (grave firme)",+ ),("Dark", "Escuro"),("Darken", "Escurecer"),("Darken Mids", "Escurecer os meios-tons"),@@ -2157,16 +2647,30 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Darker, More Contrast", "Mais escuro, mais contraste"),("Date", "Data"),("Date Modified", "Data de modificação"),+ ("De-ess frequency", "Frequência do de-esser"),+ ("De-esser", "De-esser"),("Deactivate Software on This Computer…","Desativar software neste equipamento…",),+ ("Decay", "Decaimento"),+ ("Decay multiplier", "Multiplicador do decaimento"),+ ("Decay note", "Nota do decaimento"),+ ("Decay time", "Tempo de decaimento"),("December", "dezembro"),("Decoder: {}", "Decodificador: {}"),("Decrease Gamma", "Diminuir gama"),+ ("Deep compression", "Compressão profunda"),+ ("Deep Hall", "Salão profundo"),+ ("DeEsser", "De-esser"),("Default", "Padrão"),("Default (ACES2065-1)", "Padrão (ACES2065-1)"),+ (+ "Default - no AutoMakeup",+ "Padrão - sem compensação automática",+ ),("Default All", "Restaurar tudo"),+ ("Default all parameters", "Todos os parâmetros no padrão"),("Default audio recording device:","Dispositivo padrão de gravação de áudio:",@@ -2198,12 +2702,25 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Defocus", "Desfocar"),("Deform", "Deformar"),("Deinterlace method:", "Método de desentrelaçamento:"),+ ("Delay", "Atraso"),("Delay (Echo)", "Atraso (eco)"),+ ("Delay / Original", "Delay / original"),+ ("Delay Analog Old Tape", "Delay analógico de fita velha"),+ ("Delay Digital Ping Pong", "Delay digital pingue-pongue"),+ ("Delay Digital Robot", "Delay digital robô"),+ ("Delay Digital Vocal Slap", "Delay digital slap de voz"),+ ("Delay left", "Delay esquerdo"),+ ("Delay multiplier", "Multiplicador do delay"),+ ("Delay note", "Nota do delay"),+ ("Delay out", "Saída do delay"),+ ("Delay right", "Delay direito"),+ ("Delay time", "Tempo do delay"),("Delete", "Apagar"),("Delete Active", "Eliminar ativo"),("Delete All", "Eliminar tudo"),("Delete Band", "Excluir banda"),("Delete Bin", "Excluir compartimento"),+ ("Delete Breath", "Apagar a respiração"),("Delete Event", "Excluir evento"),("Delete Filter Package", "Apagar pacote de filtros"),("Delete Keyframe", "Excluir quadro-chave"),@@ -2230,6 +2747,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Delete Video Proxy", "Excluir proxy de vídeo"),("Delete…", "Apagar…"),("Denoise", "Redução de ruído"),+ ("Dense room", "Sala densa"),("Deprecated Features", "Recursos obsoletos"),("Deprecated Features:", "Recursos obsoletos:"),("Depth", "Profundidade"),@@ -2294,6 +2812,13 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Difference", "Diferença"),("Difference Squared", "Diferença ao quadrado"),("Diffusion", "Difusão"),+ ("Digidelay 1-4", "Delay digital 1-4"),+ ("Digidelay 1-4 dot.", "Delay digital 1-4 pontuada"),+ ("Digidelay 1-4 Tripl.", "Delay digital 1-4 tercina"),+ ("Digidelay 1-8", "Delay digital 1-8"),+ ("Digidelay 1-8 dot.", "Delay digital 1-8 pontuada"),+ ("Digidelay 1-8 Tripl.", "Delay digital 1-8 tercina"),+ ("Digital", "Digital"),("Dim / Overlays", "Atenuar / Sobreposições"),("Dim Output", "Atenuar a saída"),("DIN PPM", "PPM DIN"),@@ -2301,6 +2826,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Directional", "Direcional"),("Directional Scale", "Escala direcional"),("Directional Warp", "Revelação diagonal distorcida"),+ ("Dirty Drums", "Bateria suja"),("Disable", "Desativar"),("Disable FFT Analyzer", "Desativar o analisador FFT"),("Disable Peak Meters", "Desativar os medidores de pico"),@@ -2329,11 +2855,26 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Display {}", "Tela {}"),("Dissolve", "Dissolver"),+ ("Distort 1", "Distorcer 1"),+ ("Distort 2", "Distorcer 2"),+ ("Distortion", "Distorção"),+ ("Distortion / Original", "Distorção / original"),("Distortion Center", "Centro de distorção"),("Distorts images", "Distorce imagens"),("Distribute Blue", "Distribuir azul"),("Distribute Green", "Distribuir verde"),("Distribute Red", "Distribuir vermelho"),+ ("Dither for 16-bit", "Dither para 16 bits"),+ (+ "Dither for 16-bit (low sample rate)",+ "Dither para 16 bits (taxa de amostragem baixa)",+ ),+ ("Dither for 8-bit", "Dither para 8 bits"),+ (+ "Dither for 8-bit (low sample rate)",+ "Dither para 8 bits (taxa de amostragem baixa)",+ ),+ ("Dither type", "Tipo de dither"),("Divider Width", "Largura da divisória"),("Divisions", "Divisões"),(@@ -2366,6 +2907,12 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Dots of each cell's color, black dots, or three inks a little apart, as an offset press prints.","Pontos da cor de cada célula, pontos pretos, ou três tintas um pouco afastadas, como numa impressão offset.",),+ ("Dotted 16th Note", "Semicolcheia pontuada"),+ ("Dotted 32nd Note", "Fusa pontuada"),+ ("Dotted 64th Note", "Semifusa pontuada"),+ ("Dotted 8th Note", "Colcheia pontuada"),+ ("Dotted Half Note", "Mínima pontuada"),+ ("Dotted Quarter Note", "Semínima pontuada"),("Double Circles", "Círculos duplos"),("Double Click event edge to toggle Expanded Edit Mode",@@ -2453,12 +3000,12 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Drag to move the channel", "Arraste para mover o canal"),(- "Drag to resize the keyframe controller",- "Arraste para mudar a altura do controlador de quadros-chave",+ "Drag to move the color (Ctrl: finer) · double-click: reset · right double-click: jump there · mouse wheel: move it (Alt: across, Shift: out and in, Shift+Alt: round)",+ "Arraste para mover a cor (Ctrl: mais fino) · duplo clique: redefine · duplo clique com o botão direito: pula para lá · roda do mouse: move (Alt: na horizontal, Shift: para fora e para dentro, Shift+Alt: em volta)",),(- "Drag to shift the color (Ctrl: finer) · double-click resets",- "Arraste para deslocar a cor (Ctrl: mais fino) · duplo clique redefine",+ "Drag to resize the keyframe controller",+ "Arraste para mudar a altura do controlador de quadros-chave",),("Drag to show more or fewer sends",@@ -2480,6 +3027,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Draws the curve on the preview: a press adds an anchor, a drag its tangents, a click on the first anchor closes it.","Desenha a curva na pré-visualização: um clique adiciona uma âncora, arrastar puxa as tangentes, um clique na primeira âncora fecha a curva.",),+ ("Dream-verb", "Reverb de sonho"),+ ("Dreamscape", "Paisagem de sonho"),("Dreamy", "Sonho"),("Dreamy Zoom", "Zoom de sonho"),("Drip Scale", "Escorrimento"),@@ -2511,11 +3060,23 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Drop Shadow With Upper Left Light","Sombra projetada com luz no alto à esquerda",),+ ("Drum Buss Ambience", "Ambiência do bus de bateria"),+ (+ "Drum Buss Ambience & Fatness",+ "Ambiência e peso do bus de bateria",+ ),+ ("Drum Buss Fattener +6dB", "Engordar o bus de bateria +6 dB"),+ ("Drum Plate", "Placa de bateria"),+ ("Drum Resonator", "Ressonador de bateria"),+ ("Drum Slammer", "Esmagador de bateria"),+ ("Drums", "Bateria"),+ ("Dry out", "Saída seca"),("Dual", "Dentro e fora"),("Dual Fish Eye Stitching","Stitching de olho de peixe duplo",),+ ("Dub Delay", "Delay dub"),("Duplicate", "Duplicar"),("Duplicate Track", "Duplicar trilha"),("Dust", "Poeira"),@@ -2577,6 +3138,9 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Each version's downloads and what changed in it, and where to tell us about a problem.","Os downloads de cada versão e o que mudou nela, e onde nos contar um problema.",),+ ("Ear Sugar", "Açúcar para os ouvidos"),+ ("Early out", "Saída das primeiras reflexões"),+ ("Early reflection style", "Estilo das primeiras reflexões"),("EBU PPM", "PPM EBU"),("EBU R 128", "EBU R 128"),("EBU R 128 Mode", "Modo EBU R 128"),@@ -2584,6 +3148,11 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["EBU R 128 reference: −23 LUFS (difference {} LU).","Referência EBU R 128: −23 LUFS (diferença {} LU).",),+ ("Echo chamber", "Câmara de eco"),+ ("Echo-vibrato 1", "Eco-vibrato 1"),+ ("Echo-vibrato 2", "Eco-vibrato 2"),+ ("Echo-vibrato 3", "Eco-vibrato 3"),+ ("Echo-vibrato 4", "Eco-vibrato 4"),("Edge", "Na borda"),("Edge blending", "Mistura das bordas"),("Edge Filling", "Preenchimento das bordas"),@@ -2636,6 +3205,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Arquivo de texto EDL (*.edl, *.txt)…",),("Effect", "Efeito"),+ ("Effect / Original", "Efeito / original"),("Effect only", "Apenas o efeito"),("Effect settings", "Configurações do efeito"),("Effect: {}", "Efeito: {}"),@@ -2651,6 +3221,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Eject when done", "Ejetar ao terminar"),("Elapsed: {}", "Decorrido: {}"),("Elasticity", "Elasticidade"),+ ("Electric Guitar", "Guitarra"),+ ("Electric Piano Chorus", "Coro de piano elétrico"),("Elevation", "Elevação"),("Ellipse", "Elipse"),("Elliptical", "Elíptico"),@@ -2679,16 +3251,19 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Ativar o caminho direto de importação pela GPU",),("Enable enhancement", "Habilitar aprimoramento"),+ ("Enable hard clipping", "Corte duro"),("Enable Hardware Decoding for supported formats","Ativar a decodificação por hardware nos formatos suportados",),+ ("Enable high shelf", "Ativar a prateleira de agudos"),("Enable Hover Scrub", "Ativar scrub ao passar o mouse"),("Enable joystick support", "Ativar o suporte a joystick"),("Enable looping on events by default","Ativar o loop nos eventos por padrão",),+ ("Enable low shelf", "Ativar a prateleira de graves"),("Enable low-pass filter on LFE (surround projects only)","Ativar filtro passa-baixa no LFE (só projetos surround)",@@ -2763,6 +3338,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Encrypted", "Criptografado"),("End", "Fim"),("End to end", "Fim a fim"),+ ("Endless MonoDelay", "Delay mono sem fim"),+ ("Endless PingPong", "Pingue-pongue sem fim"),("ends with", "termina com"),("Engineer:", "Engenheiro:"),(@@ -2773,6 +3350,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Enhances detail (unsharp mask).","Realça detalhes (máscara de nitidez).",),+ ("Ensemble", "Ensemble"),("Enter a lens model name to search for.","Digite o nome de um modelo de lente para procurar.",@@ -2799,6 +3377,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Envelope Point", "Ponto de envelope"),("Envelope Type:", "Tipo de envelope:"),("Envelope: {}", "Envelope: {}"),+ ("EQ / Original", "EQ / original"),+ ("Equal loudness contour", "Contorno de igual audibilidade"),("Equalization", "Equalização"),("Equalize Histogram", "Equalizar histograma"),("Erase RW disc", "Apagar disco RW"),@@ -2811,6 +3391,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Estimated file size:", "Tamanho estimado do arquivo:"),("Estimated Properties", "Propriedades estimadas"),("Even spacing", "Espaçamento uniforme"),+ (+ "Evens out the level, from gentle compression to a limiter.",+ "Iguala o nível, de uma compressão suave até um limitador.",+ ),("Event", "Evento"),("Event Buttons", "Botões de evento"),("Event Channels", "Canais do evento"),@@ -2891,6 +3475,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Exportar regiões como legendas",),("Export Text", "Exportar texto"),+ ("Export VEG Project", "Exportar projeto VEG"),("Export XML (Final Cut Pro 7 / DaVinci Resolve)","Exportar XML (Final Cut Pro 7 / DaVinci Resolve)",@@ -2901,6 +3486,22 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Exposure, contrast, saturation, white balance and lift/gamma/gain wheels.","Exposição, contraste, saturação, balanço de branco e rodas lift/gamma/gain.",),+ (+ "Express Amplitude Modulation",+ "Modulação de amplitude rápida",+ ),+ ("Express Audio Restoration", "Restauração de áudio Express"),+ ("Express Chorus", "Coro rápido"),+ ("Express Delay", "Delay rápido"),+ ("Express Distortion", "Distorção rápida"),+ ("Express Dynamics", "Dinâmica rápida"),+ ("Express Equalization", "Equalização rápida"),+ ("Express Flange/Wah-Wah", "Flange/Wah-Wah rápido"),+ ("Express Graphic EQ", "EQ gráfico rápido"),+ ("Express Noise Gate", "Portão de ruído rápido"),+ ("Express Reverb", "Reverb rápida"),+ ("Express Stutter", "Gaguejo rápido"),+ ("Express Time Stretch", "Esticar o tempo rápido"),("Extended VU", "VU estendido"),("Extensions", "Extensões"),("Exterior effect", "Efeito exterior"),@@ -2917,6 +3518,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Extract Audio from CD…", "Extrair áudio do CD…"),("Extreme", "Extremo"),("Extreme Blur", "Desfoque extremo"),+ (+ "Extreme Guitar Compression",+ "Compressão extrema de guitarra",+ ),("Extremely Conservative", "Extremamente conservador"),("Extremely Conservative - 7.5 Setup",@@ -2925,6 +3530,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Fade", "Esmaecer"),("Fade Colors", "Cores do fade"),("Fade Edge", "Borda do esmaecimento"),+ (+ "Fade edges of each event",+ "Suavizar as bordas de cada trecho",+ ),("Fade in", "Fade de entrada"),("Fade out", "Fade de saída"),("Fade range", "Faixa da transição"),@@ -2954,12 +3563,25 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Far Y position", "Posição Y distante"),("Far Z position", "Posição Z distante"),("Fast", "Rápida"),+ ("Fast & distorted 1", "Rápido e distorcido 1"),+ ("Fast & distorted 2", "Rápido e distorcido 2"),("Fast Fade", "Fade rápido"),+ ("Fast flange", "Flange rápido"),+ ("Fast flange 1", "Flange rápido 1"),+ ("Fast flange 2", "Flange rápido 2"),("Fast Forward", "Avançar"),+ ("Fast heavy chorus", "Coro forte e rápido"),+ ("Fast light chorus", "Coro leve e rápido"),+ ("Fast medium chorus", "Coro médio e rápido"),+ ("Fast modulation", "Modulação rápida"),+ ("Fast Vibrato", "Vibrato rápido"),("Faster or more accurate tracking.","Rastreamento mais rápido ou mais preciso.",),+ ("Fat Kick", "Bumbo gordo"),+ ("Fat Synth", "Synth gordo"),+ ("Fatten", "Engordar"),("Favor audio sync when playing Variable Frame rate (VFR) media","Priorizar a sincronia do áudio ao tocar mídia de taxa de quadros variável (VFR)",@@ -2984,6 +3606,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Feather type", "Tipo de suavização"),("February", "fevereiro"),("Feedback", "Realimentação"),+ ("Feedback low cut", "Corte de graves da realimentação"),("Feet & Frames 16mm (40 fpf)", "Pés e quadros 16mm (40 fpf)"),("Feet & Frames 35mm (16 fpf)", "Pés e quadros 35mm (16 fpf)"),(@@ -2996,11 +3619,33 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Pés e quadros 35mm (16 fpf)",),("Feet and Frames 35mm (16fpf)", "Pés e quadros 35mm (16fpf)"),+ ("Female Rock", "Rock feminino"),+ ("Female Up-Front", "Voz feminina à frente"),+ ("Female Voiceover", "Locução feminina"),+ ("Female Voiceover Soft", "Locução feminina suave"),+ ("Female Vox", "Voz feminina"),("Fence", "Cerca"),+ (+ "FET - 1-Parallel compression - Female vocal",+ "FET - compressão paralela - voz feminina",+ ),+ ("FET - Drum buss", "FET - bus de bateria"),+ (+ "FET - Parallel Comp. Drum buss",+ "FET - comp. paralela do bus de bateria",+ ),+ (+ "FET - Parallel compression - Hairy",+ "FET - compressão paralela - peluda",+ ),+ ("FET style 1", "Estilo FET 1"),+ ("FET style 2", "Estilo FET 2"),("Field of view", "Campo de visão"),("Field order", "Ordem dos campos"),("Field order:", "Ordem dos campos:"),("Fifteen Tilted Blinds", "Quinze persianas inclinadas"),+ ("Fifth down", "Quinta abaixo"),+ ("Fifth up", "Quinta acima"),("File", "Arquivo"),("File Format Properties…",@@ -3032,7 +3677,9 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Film's grain, gray or colored.","O grão do filme, cinza ou colorido.",),+ ("Filter frequency", "Frequência do filtro"),("Filter Graph", "Gráfico de filtros"),+ ("Filter order", "Ordem do filtro"),("Filter package deleted: {}","Pacote de filtros apagado: {}",@@ -3043,9 +3690,13 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Filter package: {}", "Pacote de filtros: {}"),("Filter Packages", "Pacotes de filtros"),+ ("Filter Q", "Q do filtro"),+ ("Filter style", "Estilo do filtro"),("Filter the templates", "Filtrar os modelos"),+ ("Filter type", "Tipo de filtro"),("Filter Type:", "Tipo de filtro:"),("Filter:", "Filtro:"),+ ("Final length", "Duração final"),("Find Edges", "Encontrar bordas"),("Finding the beats…", "Procurando as batidas…"),("Finding the tempo…", "Procurando o andamento…"),@@ -3075,9 +3726,17 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Forma fixa mantém as proporções do quadro, Paralelogramo fixo muda cada lado e inclina, Forma livre prende cada canto.",),("FLAC Audio", "Áudio FLAC"),+ ("Flange", "Flange"),+ ("Flange/Wah-wah", "Flange/Wah-wah"),+ ("Flanger", "Flanger"),+ ("Flanger Pad Enhancer", "Realce de pad com flanger"),("Flash", "Flash"),("Flat", "Plano"),("Flat Horizon", "Horizonte plano"),+ (+ "Fletcher-Munson curve (low volume compensation)",+ "Curva de Fletcher-Munson (compensação de volume baixo)",+ ),("Flicker", "Cintilação"),("Flicker Control", "Controle de cintilação"),("Flicker Frequency", "Frequência da cintilação"),@@ -3158,6 +3817,14 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Para a frente: a próxima imagem aparece primeiro dentro da estrela. Inverso: primeiro fora dela.",),("Found Lenses", "Lentes encontradas"),+ (+ "Four bands, each a low shelf, a peak or a high shelf.",+ "Quatro bandas, cada uma uma prateleira de graves, um pico ou uma prateleira de agudos.",+ ),+ (+ "Four bands, each compressed on its own: tames plosives, sibilants or a boomy low end.",+ "Quatro bandas, cada uma comprimida à parte: doma plosivas, sibilantes ou graves embolados.",+ ),("Four Circles, Out, White Border","Quatro círculos, para fora, borda branca",@@ -3168,7 +3835,12 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Quatro losangos, para fora, borda vermelha",),("Four Panes", "Quatro painéis"),+ (+ "Four peak or notch bands, with low and high shelves.",+ "Quatro bandas de pico ou corte, com prateleiras de graves e de agudos.",+ ),("Four Way Split", "Divisão em quatro"),+ ("Fourth", "Quarta"),("Fractal - smooth", "Fractal - suave"),("Fractal - turbulent", "Fractal - turbulento"),("Frame", "Quadro"),@@ -3210,6 +3882,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Freeze motion", "Movimento congelado"),("Frequency", "Frequência"),("Frequency (Hz)", "Frequência (Hz)"),+ ("Frequency of events", "Frequência dos trechos"),("Frequency:", "Frequência:"),("Friday", "sexta-feira"),("From In", "Desde dentro"),@@ -3217,6 +3890,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Front (L/R)", "Frente (L/R)"),("Full", "Cheia"),("Full Frame", "Quadros inteiros"),+ ("Full Power", "Força total"),("Full-frame message generation:","Envio de mensagens de quadro completo:",@@ -3227,6 +3901,9 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Fullscreen (4:3)", "Tela cheia (4:3)"),("Function", "Função"),+ ("Fuzz", "Fuzz"),+ ("Fuzz 1", "Fuzz 1"),+ ("Fuzz 2", "Fuzz 2"),("FX Automation", "Automação FX"),("FX Automation Chooser", "Seletor de automação FX"),(@@ -3248,6 +3925,9 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Gamma B", "Gama B"),("Gamma G", "Gama G"),("Gamma R", "Gama R"),+ ("Gapper (insert)", "Gapper (inserir)"),+ ("Gapper/Snipper", "Inserir/cortar trechos"),+ ("Gate", "Portão"),("Gaussian", "Gaussiano"),("Gaussian (asymmetric)", "Gaussiano (assimétrico)"),("Gaussian Blur", "Desfoque gaussiano"),@@ -3281,6 +3961,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Generic control mapping", "Mapeamento de controle genérico"),("Generic VST editor", "Editor VST genérico"),("Gentle", "Suave"),+ ("Gentle high-frequency boost", "Reforço suave dos agudos"),("Get Media from the Web", "Obter mídia da Web"),("Getting Started", "Começando"),("Gigabytes", "Gigabytes"),@@ -3334,7 +4015,12 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Grain over the picture.", "Granulação sobre a imagem."),("Grainy", "Granulado"),+ ("Grand Canyon", "Grand Canyon"),+ ("Grand canyon", "Grand Canyon"),("Granularity", "Granularidade"),+ ("Graph", "Gráfico"),+ ("Graphic Dynamics", "Dinâmica gráfica"),+ ("Graphic EQ", "EQ gráfico"),("Grate", "Grelha"),("Gravel", "Cascalho"),("Gray", "Cinza"),@@ -3370,6 +4056,9 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Grid size in Y", "Tamanho da grade em Y"),("Grid Spacing", "Espaçamento de Grade"),("Grid spacing", "Espaçamento da grade"),+ ("Gristle", "Áspero"),+ ("Groove Analog", "Groove analógico"),+ ("Groove Digital", "Groove digital"),("Group", "Agrupar"),("Group / ungroup", "Agrupar / desagrupar"),("Group Events", "Agrupar eventos"),@@ -3386,10 +4075,14 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Groups the visualization parameters.","Agrupa os parâmetros de visualização.",),+ ("Guitar", "Guitarra"),+ ("Guitar distortion 1", "Distorção de guitarra 1"),+ ("Guitar distortion 2", "Distorção de guitarra 2"),(- "Guitar: Mids Up, Highs Tamed",- "Guitarra: médios acima, agudos suavizados",+ "Guitar distortion 3 (fuzzy)",+ "Distorção de guitarra 3 (fuzz)",),+ ("Guitar Stereo Swirl", "Redemoinho estéreo de guitarra"),("H.264 video and AAC audio in MP4: plays everywhere. Encoded by the processor or by a graphics card (NVENC, AMD, Quick Sync).","Vídeo H.264 e áudio AAC em MP4: toca em qualquer lugar. Codificado pelo processador ou por uma placa de vídeo (NVENC, AMD, Quick Sync).",@@ -3398,12 +4091,18 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Half", "Mínima"),("Half Film", "Meio filme"),("Half float (16 bit)", "Meio flutuante (16 bits)"),+ ("Half Note", "Mínima"),+ ("Half Note Triplet", "Tercina de mínima"),("Half NTSC", "Meio NTSC"),("Half PAL", "Meio PAL"),+ ("Half Rectangular", "Meio retangular"),("Half Saturation", "Metade da saturação"),("Hall", "Salão"),+ ("Hank on Escape Route", "Hank na rota de fuga"),+ ("Hard flange", "Flange forte"),("Hard Flash", "Flash forte"),("Hard Light", "Luz forte"),+ ("Hard square", "Quadrada dura"),("Hardware decoder to use:","Decodificador de hardware a usar:",@@ -3422,6 +4121,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Heavy Contrast", "Contraste forte"),("Heavy Stabilization", "Estabilização forte"),+ ("Heavy Stereo Chorus Fx", "Coro estéreo pesado"),+ ("Heavy Stereo Flanger Fx", "Flanger estéreo pesado"),("Height", "Altura"),("Height (Region of Interest)", "Altura (ROI)"),("Height 1", "Altura 1"),@@ -3453,27 +4154,57 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Hide Tangents", "Ocultar tangentes"),("High", "Altos"),("High (dB)", "Agudos (dB)"),+ (+ "High (slow, great for all bands)",+ "Alta (lenta, ótima para todas as bandas)",+ ),+ (+ "High attenuation frequency",+ "Frequência de atenuação dos agudos",+ ),("High Contrast", "Alto contraste"),("High Extrusion", "Extrusão alta"),("High Freq. (Hz)", "Freq. agudos (Hz)"),+ ("High Howl", "Uivo agudo"),("High in", "Entrada alta"),("High out", "Saída alta"),("High Pass", "Passa-altas"),+ ("High Pierce", "Agudo penetrante"),("High Precision", "Alta precisão"),("High quality zoom.", "Zoom de alta qualidade"),("High Sensitivity", "Sensibilidade elevada"),+ ("High Shelf", "Prateleira de agudos"),+ ("High shelf", "Prateleira de agudos"),("High Shelving", "Prateleira de agudos"),("High threshold", "Limite superior"),("High trim", "Corte superior"),+ ("High-frequency shelf", "Prateleira de agudos"),("High-Pass", "Passa-altas"),+ ("High-pass", "Passa-altas"),+ ("High-pass contour", "Contorno passa-altas"),+ ("High-shelf", "Prateleira de agudos"),("Higher: also splits on soft scene changes.","Mais alta: divide também em mudanças suaves de cena.",),+ ("Highest", "Máxima"),("Highlight", "Destaque"),("Highlight Motion Blur Area", "Destacar a área desfocada"),("Highlight Shadows", "Realçar sombras"),("Highlights", "Realces"),+ ("Highpass Triangular", "Triangular passa-altas"),+ (+ "HipHop Limiter +6dB (Tight Bass)",+ "Limitador hip-hop +6 dB (grave firme)",+ ),+ (+ "Hiss cut (cut above 8 kHz by 6 dB)",+ "Corte de chiado (6 dB acima de 8 kHz)",+ ),+ (+ "Hiss removal (cut frequencies above 6 kHz by 40 dB)",+ "Remover chiado (cortar 40 dB acima de 6 kHz)",+ ),("Histogram", "Histograma"),("Histogram Cut-Off", "Corte do histograma"),("Histogram Equalization", "Equalização de histograma"),@@ -3532,7 +4263,9 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Horizontal: the doors move across the frame. Vertical: up and down.","Horizontal: as portas se movem de um lado ao outro do quadro. Vertical: para cima e para baixo.",),+ ("Hospital hallway", "Corredor de hospital"),("Host Command", "Comando"),+ ("Hot Master", "Master quente"),("How big the flare's elements are.","O tamanho dos elementos do reflexo.",@@ -4464,6 +5197,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Import Text", "Importar texto"),("Import to:", "Importar para:"),+ ("Import VEG Project", "Importar projeto VEG"),("Import XML (Final Cut Pro 7 / DaVinci Resolve)","Importar XML (Final Cut Pro 7 / DaVinci Resolve)",@@ -4505,6 +5239,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Incremental Save", "Salvar gradualmente"),("Index", "Índice"),("Index {}", "Índice {}"),+ ("Indoor olympic-size pool", "Piscina olímpica coberta"),("Infrared", "Infravermelho"),("Initialize Tangents", "Inicializar tangentes"),("Inner", "Por dentro"),@@ -4537,10 +5272,13 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Input device:", "Dispositivo de entrada:"),("Input end", "Fim da entrada"),+ ("Input gain", "Ganho de entrada"),+ ("Input high-pass", "Passa-altas na entrada"),("Input level of the effects chain","Nível de entrada da cadeia de efeitos",),+ ("Input low cut", "Corte de graves na entrada"),("Input monitor", "Monitorar a entrada"),("Input Monitor Mode", "Modo de monitoramento de entrada"),(@@ -4594,6 +5332,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Insert/Remove Envelope", "Inserir/remover envelope"),("Inserts", "Inserções"),+ (+ "Inserts silences into the sound or cuts bits out of it.",+ "Insere silêncios no som ou corta pedaços dele.",+ ),("Inside", "Dentro"),("Installed Version", "Versão instalada"),("Integrated", "Integrada"),@@ -4631,6 +5373,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Interpolate fields", "Interpolar campos"),("Interpolation", "Interpolação"),+ ("Intimate Room", "Sala íntima"),("Invalid interval.", "Intervalo inválido."),("Invalid layout: {}", "Layout inválido: {}"),(@@ -4638,8 +5381,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Arquivo de preferências inválido: {}",),("Invert", "Inverter"),+ ("Invert chorus phase", "Inverter a fase do coro"),("Invert Color", "Inverter cor"),("Invert data source", "Inverter a origem dos dados"),+ ("Invert feedback phase", "Inverter a fase da realimentação"),("Invert Luminance", "Inverter luminância"),("Invert Luminosity", "Inverter luminosidade"),("Invert mask", "Inverter máscara"),@@ -4660,6 +5405,14 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("is greater than", "é maior que"),("is less than", "é menor que"),("is not", "não é"),+ (+ "It changes the sound's length, so it works in an event's chain; here the sound goes through it unchanged.",+ "Ele muda a duração do som, por isso funciona na cadeia de um evento; aqui o som passa por ele sem mudar.",+ ),+ (+ "It changes the sound's length: the event plays its sound made through the whole chain, ready a moment after each change, and keeps its own length.",+ "Ele muda a duração do som: o evento toca o som feito pela cadeia inteira, pronto um instante depois de cada mudança, e mantém a própria duração.",+ ),("Italic", "Itálico"),("Item Style", "Estilo do item"),(@@ -4730,7 +5483,9 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Intervalo entre quadros-chave (quadros):",),("Keyframe of {} at {}", "Quadro-chave de {} em {}"),+ ("Keys Shimmering", "Teclados cintilantes"),("Keystone", "Pilar"),+ ("Krankmachine", "Krankmachine"),("LAB Adjust", "Ajuste LAB"),("Label…", "Rótulo…"),("Lanes", "Faixas"),@@ -4740,6 +5495,11 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Large blocks (censoring, retro style).","Blocos grandes (censura, estilo retrô).",),+ ("Large Concert Hall", "Sala de concertos grande"),+ ("Large hall 1", "Salão grande 1"),+ ("Large hall 2", "Salão grande 2"),+ ("Large hall 3", "Salão grande 3"),+ ("Large hall 4", "Salão grande 4"),("Large Tiles", "Ladrilhos grandes"),("Large Title", "Título grande"),("Last image:", "Última imagem:"),@@ -4781,7 +5541,9 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Left", "Esquerda"),("Left Aligned", "Alinhado à esquerda"),("Left fisheye", "Olho de peixe esquerdo"),+ ("Left note", "Nota esquerda"),("Left Only", "Apenas lado esquerdo"),+ ("Left surround", "Surround esquerdo"),("Left to Right", "Da esquerda para a direita"),("Left, Small Loop, Yellow Light",@@ -4810,6 +5572,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Length", "Duração"),("Length (seconds)", "Duração (segundos)"),("Length of each image", "Duração de cada imagem"),+ ("Length of one event", "Duração de um trecho"),("Length:", "Duração:"),("Lenient", "Permissivo"),("Lenient - 7.5 Setup", "Permissivo - Configuração 7,5"),@@ -4831,6 +5594,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Level:", "Nível:"),("Level: {} %", "Nível: {} %"),("Levels", "Níveis"),+ ("LFE", "LFE"),("LFE Only", "Somente LFE"),("LFE Only: everything into the low-frequency channel",@@ -4848,7 +5612,9 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Mistura leve, pixels repetidos em volta",),("Light Blur", "Desfoque leve"),+ ("Light Chime", "Sino leve"),("Light color", "Cor da luz"),+ ("Light Guitar Plate", "Placa leve de guitarra"),("Light Intensity", "Intensidade da luz"),("Light Location", "Posição da luz"),("Light Noise Reduction", "Redução de ruído leve"),@@ -4874,22 +5640,36 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Lights near the frame's edges burst less, in percent.","As luzes perto das bordas do quadro explodem menos, em porcentagem.",),+ ("Lil' Warmer", "Aquecedorzinho"),+ ("Limit at 6 dB and maximize", "Limitar em 6 dB e maximizar"),("Limit hue", "Limitar matiz"),+ ("Limit levels to -6 dB", "Limitar os níveis a -6 dB"),+ (+ "Limit levels to -6 dB (hard limiter)",+ "Limitar os níveis a -6 dB (limitador forte)",+ ),("Limit luminance", "Limitar luminância"),("Limit saturation", "Limitar saturação"),("Limited", "Limitada"),("Limited (default)", "Limitada (padrão)"),("Limiter", "Limitador"),+ ("Limiter (legacy)", "Limitador (antigo)"),("Line Spacing", "Espaçamento entre linhas"),("Line sync", "Sincronização em linha"),("Linear", "Linear"),("Linear (good)", "Linear (boa)"),("Linear Blur", "Desfoque linear"),("Linear Fade", "Fade linear"),+ ("Linear Phase Quality", "Qualidade da fase linear"),("Linear Wipe", "Varredura linear"),("Link to Main Track Pan", "Ligar ao pan principal da trilha"),("List", "Lista"),+ ("Listen", "Ouvir"),+ ("Listen to the side chain", "Ouvir o side chain"),("Listening…", "Escutando…"),+ ("Live Ambience", "Ambiente ao vivo"),+ ("Liveliness", "Vivacidade"),+ ("Living Room", "Sala de estar"),("Load", "Carregar"),("Locate", "Localizar"),("Location", "Local"),@@ -4909,6 +5689,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Travar o tamanho da grade em X e Y",),("Lock Tangents", "Travar tangentes"),+ ("Lock to grid", "Travar na grade"),("Locked", "Travado"),("Log Plugin loading:",@@ -4917,13 +5698,18 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Log Reads:", "Registrar as leituras:"),("Log Renders:", "Registrar as renderizações:"),("Log saved to {}", "Registro salvo em {}"),- ("Log. Exposure", "Exposição log."),("Log. Exposure:", "Exposição log.:"),("Logarithmic VU", "VU logarítmico"),+ ("Long", "Longo"),+ ("Long decay time", "Decaimento longo"),("Long Echo", "Eco longo"),+ ("Long Hall", "Salão longo"),+ ("Long hall", "Salão longo"),+ ("Longest PingPong", "Pingue-pongue mais longo"),("Longitude", "Longitude"),("Look", "Visual"),("Look Again", "Procurar de novo"),+ ("Look ahead", "Olhar à frente"),("Look LUT", "LUT de look"),("Look modification transform:",@@ -4950,6 +5736,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Lossless compressed audio. BananaV's own encoder.","Áudio comprimido sem perdas. Codificador próprio do BananaV.",),+ ("Loud Neighbours", "Vizinhos barulhentos"),+ ("Loudness", "Loudness"),("Loudness configuration", "Configuração de loudness"),("Loudness Log", "Registro de intensidade de som"),(@@ -4963,8 +5751,16 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Loudness Scale", "Escala de sonoridade"),("Low", "Baixos"),("Low (dB)", "Graves (dB)"),+ (+ "Low (fast, good for high bands)",+ "Baixa (rápida, boa para bandas agudas)",+ ),+ ("Low bell", "Sino grave"),+ ("Low cut", "Corte de graves"),+ ("Low Cut Filter 100 Hz", "Filtro de corte de graves 100 Hz"),("Low Extrusion", "Extrusão baixa"),("Low Freq. (Hz)", "Freq. graves (Hz)"),+ ("Low Howl", "Uivo grave"),("Low in", "Entrada baixa"),("Low Light", "Luz fraca"),("Low out", "Saída baixa"),@@ -4973,16 +5769,27 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["As partes baixas altas e as altas baixas.",),("Low Pass", "Passa-baixas"),+ ("Low Pass 500 Hz", "Passa-baixas 500 Hz"),("Low Quality Color Film", "Filme com baixa qualidade de cor"),("Low Sensitivity", "Sensibilidade baixa"),+ ("Low Shelf", "Prateleira de graves"),+ ("Low shelf", "Prateleira de graves"),("Low Shelving", "Prateleira de graves"),("Low threshold", "Limite inferior"),("Low trim", "Corte inferior"),+ ("Low-frequency shelf", "Prateleira de graves"),+ ("Low-frequency verb", "Reverb de graves"),("Low-Pass", "Passa-baixas"),+ ("Low-pass", "Passa-baixas"),("Low-pass filter quality:","Qualidade do filtro passa-baixa:",),+ (+ "Low-pass start frequency",+ "Frequência inicial do passa-baixas",+ ),+ ("Low-shelf", "Prateleira de graves"),("Lower field first", "Campo inferior primeiro"),("Lower Left, Scaled, No Angle, Opaque",@@ -4993,7 +5800,6 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Inferior direito, reduzido, sem ângulo, opaco",),("Lower Third", "Terço inferior"),- ("Lower Threshold", "Limiar inferior"),("Lower, the lines are torn across, as with a bad line sync.","Mais baixo, as linhas se deslocam de lado, como numa sincronização de linha ruim.",@@ -5003,6 +5809,11 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Menor, a imagem rola, como com o ajuste de estabilidade desregulado.",),("Lower-Left Spotlight", "Holofote inferior esquerdo"),+ (+ "Lowers the sound below the threshold, smoothly and quickly.",+ "Abaixa o som abaixo do limiar, de forma suave e rápida.",+ ),+ ("Lowest", "Mínima"),("Lows, mids and highs, with adjustable frequencies.","Graves, médios e agudos, com frequências ajustáveis.",@@ -5019,9 +5830,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Luminance vs Saturation", "Luminância × saturação"),("Luminance/R/G/B", "Luminância/R/G/B"),("Luminance:", "Luminância:"),+ ("Lush And Wide Open", "Encorpado e bem aberto"),+ ("Lush Mix", "Mixagem encorpada"),("LUT exported to {}", "LUT exportada para {}"),("LUT Filter", "Filtro LUT"),- ("LUT Selection", "Seleção da LUT"),("LUT Selection: apply or remove the LUT","Seleção da LUT: aplica ou tira a LUT",@@ -5030,6 +5842,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("LUTs", "LUTs"),("Mackie Control", "Mackie Control"),("Mackie Control Extender", "Mackie Control Extender"),+ ("Mad flange", "Flange maluco"),+ ("Mad wah", "Wah maluco"),("Magenta", "Magenta"),("Magnitude", "Magnitude"),("Main Timeline", "Linha do tempo principal"),@@ -5082,9 +5896,23 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Disponibilizar estes dispositivos para saída MIDI:",),("Makes bright areas glow.", "Faz as áreas claras brilharem."),+ (+ "Makes the sound longer or shorter without changing its pitch.",+ "Deixa o som mais longo ou mais curto sem mudar o tom.",+ ),+ (+ "Makes the sound louder without going over the top, then clips it gently.",+ "Deixa o som mais alto sem passar do topo e depois corta com suavidade.",+ ),("Making the disc image…", "Criando a imagem do disco…"),("Making the proxy of {}: {}%", "Criando o proxy de {}: {}%"),("Making the proxy of {}…", "Criando o proxy de {}…"),+ ("Male Rap vocal", "Rap masculino"),+ ("Male Rock", "Rock masculino"),+ ("Male vocal", "Voz masculina"),+ ("Male Voiceover", "Locução masculina"),+ ("Male Vox", "Voz masculina"),+ ("Mangle", "Triturar"),("Many Crooked Blinds", "Muitas persianas tortas"),("Marble - heavy grain", "Mármore - grão grosso"),("Marble - light grain", "Mármore - grão fino"),@@ -5158,6 +5986,16 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Master Bus Properties", "Propriedades do bus principal"),("Master Display:", "Monitor de referência:"),("Master Fader", "Fader do Master"),+ ("Master for 16-bit", "Master para 16 bits"),+ ("Master Mixdown", "Mixagem final"),+ ("Master: Mid/Side", "Master: meio/lados"),+ (+ "Master: Mid/Side Wide Radio Bass",+ "Master: meio/lados, graves de rádio amplos",+ ),+ ("Master: Mid/Side, Basic", "Master: meio/lados, básico"),+ ("Master: Smiley Face", "Master: curva sorriso"),+ ("Master: Smooth Top End", "Master: agudos suaves"),("Match brightness", "Igualar o brilho"),("Match Media Video Settings",@@ -5191,6 +6029,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Max zoom", "Zoom máximo"),("Maximal Magnitude", "Magnitude máxima"),("Maximize", "Maximizar"),+ (+ "Maximize volume (-12 dB limiter with gain compensation)",+ "Maximizar o volume (limitador de -12 dB com compensação de ganho)",+ ),("Maximum", "Máximo"),("Maximum bit rate (Mb/s):", "Taxa de bits máxima (Mb/s):"),("Maximum Blur", "Desfoque máximo"),@@ -5233,7 +6075,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("May", "maio"),("Mean: {}", "Média: {}"),("Measured length", "Duração medida"),- ("Measures", "Medidas"),+ ("Measures", "Compassos"),("Measures & Beats", "Compassos e tempos"),("Measuring each frame's brightness…",@@ -5268,10 +6110,22 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Median", "Mediana"),("Media…", "Mídia…"),("Medium", "Médio"),+ (+ "Medium (great for mid and high bands)",+ "Média (ótima para bandas médias e agudas)",+ ),("Medium Blur", "Desfoque médio"),+ ("Medium compression", "Compressão média"),+ ("Medium hall", "Salão médio"),+ ("Medium Hall 1", "Salão médio 1"),+ ("Medium hall 1", "Salão médio 1"),+ ("Medium Hall 2", "Salão médio 2"),+ ("Medium hall 2", "Salão médio 2"),("Medium Horizontal", "Médio horizontal"),("Medium Pinch", "Apertar médio"),("Medium Punch", "Inflar médio"),+ ("Medium Room", "Sala média"),+ ("Medium room", "Sala média"),("Medium Sphere In", "Esfera média para dentro"),("Medium Sphere Out", "Esfera média para fora"),("Medium Stabilization", "Estabilização média"),@@ -5285,12 +6139,15 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Medium Vertical", "Médio vertical"),("Megabytes", "Megabytes"),+ ("Megaphone", "Megafone"),("Memory Usage:", "Uso de memória:"),("Memory: {}", "Memória: {}"),("Mesh", "Malha"),("Mesh Behavior", "Comportamento da malha"),("Mesh point refers to", "O ponto da malha se refere a"),("Mesh Warp", "Distorção em malha"),+ ("Metal Tank", "Tanque de metal"),+ ("Metal tank", "Tanque de metal"),("Meter Layout", "Layout dos medidores"),("Meters", "Medidores"),("Meters / Values", "Medidores / Valores"),@@ -5301,7 +6158,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Microscopic Threads 2", "Fios microscópicos 2"),("Mid", "Médios"),("Mid (dB)", "Médios (dB)"),+ ("Mid Boost", "Reforço de médios"),+ ("Mid Delay", "Delay médio"),("Mid Freq. (Hz)", "Freq. médios (Hz)"),+ ("Mid Howl", "Uivo médio"),("Mid Width (Q)", "Largura médios (Q)"),("Middle", "Meio"),(@@ -5343,7 +6203,13 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Espelha na horizontal e/ou vertical.",),("Mix", "Mistura"),+ (+ "Mix: Mid/Side More Clarity",+ "Mixagem: meio/lados, mais clareza",+ ),("Mixdown", "Mixagem"),+ ("Mixed", "Misto"),+ ("Mixed band models", "Modelos de banda misturados"),("Mixer", "Mesa de mistura"),("Mixer Preview Fader",@@ -5351,7 +6217,20 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Mixing audio", "Mixando áudio"),("Mixing Console", "Console de mixagem"),+ ("Mod. depth", "Profundidade da mod."),+ ("Mod. freq.", "Freq. da mod."),+ ("Mod. rate", "Taxa da mod."),("Mode", "Modo"),+ ("Mode 1 - 6 ms", "Modo 1 - 6 ms"),+ ("Mode 10 - 16 ms pan left", "Modo 10 - 16 ms à esquerda"),+ ("Mode 2 - 8 ms", "Modo 2 - 8 ms"),+ ("Mode 3 - 10 ms", "Modo 3 - 10 ms"),+ ("Mode 4 - 16 ms", "Modo 4 - 16 ms"),+ ("Mode 5 - 20 ms", "Modo 5 - 20 ms"),+ ("Mode 6 - 36 ms", "Modo 6 - 36 ms"),+ ("Mode 7 - 8 ms pan right", "Modo 7 - 8 ms à direita"),+ ("Mode 8 - 8 ms pan left", "Modo 8 - 8 ms à esquerda"),+ ("Mode 9 - 16 ms pan right", "Modo 9 - 16 ms à direita"),("Mode:", "Modo:"),("Model", "Modelo"),("Moderate", "Moderado"),@@ -5364,11 +6243,16 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Modern Equalizer", "Equalizador moderno"),("Modified {}", "Modificado em {}"),("Modified: {}", "Modificado: {}"),+ ("Modulation", "Modulação"),+ ("Modulation / Original", "Modulação / original"),+ ("Modulation depth", "Profundidade de modulação"),+ ("Modulation freq.", "Freq. de modulação"),+ ("Modulation period", "Período de modulação"),+ ("Modulation rate", "Taxa de modulação"),("Momentary", "Momentânea"),("Monday", "segunda-feira"),("Mondrian", "Mondrian"),("Mono", "Mono"),- ("Mono Bass (150 Hz)", "Graves em mono (150 Hz)"),("Mono Below", "Mono abaixo de"),("Mono Below (Hz)", "Mono abaixo de (Hz)"),("Mono Left", "Mono esquerdo"),@@ -5376,11 +6260,13 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Mono {}", "Mono {}"),("Monochromatic", "Monocromático"),("Monochrome", "Monocromático"),+ ("Monovibe", "Monovibe"),("Moonlight", "Luar"),("More", "Mais"),("More Blue", "Mais azul"),("More Contrast", "Mais contraste"),("More Green", "Mais verde"),+ ("More Presence", "Mais presença"),("More Red", "Mais vermelho"),("More Yellow", "Mais amarelo"),("Morning Sunrise", "Nascer do sol"),@@ -5480,6 +6366,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Move Track", "Mover trilha"),("Move Up", "Mover para cima"),+ (+ "Moves a stereo sound left or right, blending one channel into the other.",+ "Leva um som estéreo para a esquerda ou para a direita, misturando um canal no outro.",+ ),("Moves pixels across the other way.","Move os pixels na horizontal no outro sentido.",@@ -5517,6 +6407,9 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["MPEG-2 for DVD and Blu-ray authoring.","MPEG-2 para autoria de DVD e Blu-ray.",),+ ("Muffler", "Abafador"),+ ("Multi-Band Dynamics", "Dinâmica multibanda"),+ ("Multi-Tap Delay", "Delay de várias saídas"),("Multicamera", "Multicâmera"),("Multicamera Audio Sync",@@ -5524,6 +6417,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Multicamera editing", "Edição multicâmera"),("Multimedia", "Multimídia"),+ (+ "Multiple delays (feedback)",+ "Vários delays (realimentação)",+ ),("Multiplies the light of what the limits pick.","Multiplica a luz do que os limites escolhem.",@@ -5538,6 +6435,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Multipurpose slider: the bus or assignable FX it sends to","Controle multiuso: o barramento ou o FX atribuível que recebe o envio",),+ ("Mushroomed Drums", "Bateria cogumelada"),("Music", "Músicas"),("Mute", "Silenciar"),("Mute All Audio", "Silenciar todo o áudio"),@@ -5552,6 +6450,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Mute Assignable FX", "Silenciar FX atribuível"),("Mute Bus", "Silenciar barramento"),+ (+ "Mute levels below -35 dB (hard noise gate)",+ "Silenciar abaixo de -35 dB (portão de ruído duro)",+ ),("Mute the master", "Silenciar o mestre"),("Mute the video output", "Silenciar a saída de vídeo"),("Mute Track", "Silenciar trilha"),@@ -5584,6 +6486,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Nearest Frame", "Quadro mais próximo"),("Negative", "Negativo"),+ ("Negative half", "Metade negativa"),("Negative Shadows", "Sombras negativas"),("Neon", "Neon"),(@@ -5751,10 +6654,16 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Noir", "Noir"),("Noise", "Ruído"),+ ("Noise floor", "Patamar de ruído"),+ ("Noise Gate", "Portão de ruído"),+ ("Noise gate (legacy)", "Portão de ruído (antigo)"),+ ("Noise gate 1", "Portão de ruído 1"),+ ("Noise gate 2", "Portão de ruído 2"),("Noise level", "Nível de ruído"),("Noise parameters", "Parâmetros de ruído"),("Noise Reduction", "Redução de ruído"),("Noise sensitivity", "Sensibilidade ao ruído"),+ ("Noise shaping", "Modelagem de ruído"),("Noise spread as a bell curve: stronger, with more specks far from the picture's colors. Unchecked, it is spread evenly.","Ruído distribuído em curva de sino: mais forte, com mais pontos longe das cores da imagem. Desmarcado, ele se distribui por igual.",@@ -5801,6 +6710,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Ainda não disponível no BananaV",),("Not supported ({})", "Não suportado ({})"),+ (+ "Notch frequencies around 450 Hz",+ "Cortar as frequências perto de 450 Hz",+ ),("Note", "Nota"),("Note Default Color", "Cor padrão da nota"),("Note that gets one beat:", "Figura que vale uma batida:"),@@ -5832,12 +6745,14 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Number of stereo busses:", "Número de barramentos estéreo:"),("Number of Takes", "Número de tomadas"),+ ("Number of taps", "Número de saídas"),("Number of times to paste:", "Número de vezes a colar:"),("Numbers use the language's decimal separator (1.5 or 1,5).","Os números usam o separador decimal do idioma (1.5 ou 1,5).",),("Ocean", "Oceano"),+ ("oct.", "oit."),("Octagon", "Octógono"),("October", "outubro"),("Off", "Desligado"),@@ -5861,6 +6776,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Old Film", "Filme antigo"),("Old Newspaper", "Jornal antigo"),("Old Photographs", "Fotografias antigas"),+ ("Old Radio", "Rádio antigo"),+ ("Older Radio", "Rádio mais antigo"),("Omnidirectional", "Omnidirecional"),("On", "Ligado"),(@@ -5888,6 +6805,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["One picture splits into four parts that open onto the other or close over it.","Uma imagem se divide em quatro partes que se abrem para a outra ou se fecham sobre ela.",),+ (+ "One shelf, band-pass or notch, accurate down to the lows.",+ "Uma prateleira, passa-banda ou corte, preciso até nos graves.",+ ),("One Vertical Blind", "Uma persiana vertical"),("Only 32-bit floating point (full range) can composite in linear light; the other formats composite in video gamma.",@@ -5905,10 +6826,6 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Only the glints, on nothing, without the picture.","Só os brilhos, sobre nada, sem a imagem.",),- (- "Only the passes have a slope to pick; the others' is 12 dB/oct.",- "Só os passa-altas, passa-baixas e passa-banda têm inclinação a escolher; a dos outros é 12 dB/oit.",- ),("Only the rays, on nothing, without the picture.","Só os raios, sobre nada, sem a imagem.",@@ -6022,10 +6939,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Output device:", "Dispositivo de saída:"),("Output end", "Fim da saída"),("Output Gain", "Ganho de saída"),+ ("Output gain", "Ganho de saída"),("Output Gain (dB)", "Ganho de saída (dB)"),- ("Output Max", "Saída máx."),+ ("Output level", "Nível de saída"),("Output Meter", "Medidor de saída"),- ("Output Min", "Saída mín."),("Output rotation:", "Rotação da saída:"),("Output start", "Início da saída"),("Output White", "Branco de saída"),@@ -6040,6 +6957,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Over Black", "Sobre preto"),("Over Exposure", "Superexposição"),+ ("OverCompressed Vocals", "Voz supercomprimida"),("Overlap (transition)", "Sobreposição (transição)"),("Overlay", "Sobrepor"),("Overlays", "Sobreposições"),@@ -6047,6 +6965,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Override project settings when prerendering video","Substituir as configurações do projeto ao pré-renderizar vídeo",),+ ("Oversample", "Superamostragem"),("Oversampling", "Sobreamostragem"),("Packing {}", "Empacotando {}"),("Page Loop", "Página em laço"),@@ -6072,6 +6991,13 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Pan:", "Pan:"),("Paper angle", "Ângulo do papel"),("Paper opacity", "Opacidade do papel"),+ ("Paragraphic EQ", "EQ paragráfico"),+ ("Parallel Compression - Glue", "Compressão paralela - cola"),+ ("Parallel Kick Compression", "Compressão paralela do bumbo"),+ (+ "Parallel Overhead Drum Compression",+ "Compressão paralela dos overheads",+ ),("Parameter", "Parâmetro"),("Parameter {}", "Parâmetro {}"),("Parameter:", "Parâmetro:"),@@ -6080,6 +7006,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Parameters to control with envelopes:","Parâmetros a controlar com envelopes:",),+ ("Parametric EQ", "EQ paramétrico"),("Parent Composite Mode", "Modo de composição do pai"),("Parent Composite Mode:", "Modo de composição do pai:"),("Parent Composite Mode: {}", "Modo de composição do pai: {}"),@@ -6111,13 +7038,28 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Região de controle dos medidores de pico",),("Peak Reduction:", "Redução nos picos:"),+ ("Peak Stop", "Corte de picos"),+ ("Peak vs. RMS", "Pico ou RMS"),("Peaking", "Pico"),("Peel angle", "Ângulo da página"),("Peel opacity", "Opacidade da página"),("Pentagon", "Pentágono"),("Performance", "Desempenho"),+ ("Period", "Período"),+ ("Period multiplier", "Multiplicador do período"),("Perlin", "Perlin"),("Perspective", "Perspectiva"),+ ("Phase", "Fase"),+ ("Phase offset", "Deslocamento de fase"),+ ("Phase:", "Fase:"),+ ("Phased", "Defasado"),+ ("Phaser", "Phaser"),+ ("Phaser 1", "Phaser 1"),+ ("Phaser 2", "Phaser 2"),+ ("Phaser 3", "Phaser 3"),+ ("Phasing pad", "Pad com phasing"),+ ("Phone", "Telefone"),+ ("Phone line effect", "Efeito de linha telefônica"),("Phosphorescence", "Fosforescência"),("Pick a color from the screen", "Pegar uma cor da tela"),(@@ -6166,8 +7108,15 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Pin", "Fixar"),("Pin Wheel", "Cata-vento"),("Pinch/Punch", "Apertar/Inflar"),+ ("Ping Pong Delay for Pads", "Delay pingue-pongue para pads"),+ ("PingPong", "Pingue-pongue"),+ ("PipSqueaking", "Guinchinhos"),+ ("Pitch and time", "Tom e tempo"),("Pitch Bend", "Pitch Bend"),("Pitch change (semitones):", "Mudança de tom (semitons):"),+ ("Pitch Shift", "Mudar o tom"),+ ("Pitch shift octave down", "Uma oitava abaixo"),+ ("Pitch shift octave up", "Uma oitava acima"),("Pixel aspect ratio:", "Proporção de pixel:"),("Pixel color morph", "Transformação de cor por pixel"),("Pixel format:", "Formato de pixel:"),@@ -6190,6 +7139,9 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Placeholder", "Espaço reservado"),("Plaid", "Xadrez"),("Plasma", "Plasma"),+ ("Plate", "Placa"),+ ("Plate 1", "Placa 1"),+ ("Plate 2 Ringy", "Placa 2 ressonante"),("Play", "Reproduzir"),("Play (Space)", "Tocar (Espaço)"),("Play / Pause", "Reproduzir / pausar"),@@ -6243,6 +7195,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Aponte aqui para mostrar a área de encaixe",),("Points", "Pontas"),+ (+ "Pop Maximizer +6dB (Transparent)",+ "Maximizador pop +6 dB (transparente)",+ ),("Pop-up, Bottom Right", "Pop-up, inferior direito"),("Port", "Porta"),("Portals", "Portais"),@@ -6256,6 +7212,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Position Y", "Posição Y"),("Position:", "Posição:"),("Positive", "Positiva"),+ ("Positive half", "Metade positiva"),+ ("Post EQ", "EQ depois"),("Post Fader Insert FX: the effects after the volume","FX de inserção pós-fader: os efeitos depois do volume",@@ -6265,12 +7223,14 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Post-Edit Ripple", "Pós-edição de ondulação"),("Power", "Potência"),("Power Kaleido", "Caleidoscópio intenso"),+ ("Pre EQ", "EQ antes"),("Pre Fader Insert FX: the effects before the volume","FX de inserção pré-fader: os efeitos antes do volume",),("Pre FX", "Pré-FX"),("Pre Volume", "Pré-volume"),+ ("Pre-delay", "Pré-atraso"),("Precision", "Precisão"),("Precision:", "Precisão:"),("Preferences", "Preferências"),@@ -6281,6 +7241,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Preferences imported.", "Preferências importadas."),("Preferences…", "Preferências…"),("Preferred audio editor:", "Editor de áudio preferido:"),+ ("Premastering", "Pré-masterização"),("Premultiplied", "Pré-multiplicado"),("Premultiplied (dirty)", "Pré-multiplicado (sujo)"),("Preparing", "Preparando"),@@ -6294,6 +7255,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Prerendering video: part {} of {} ({}%)","Pré-renderizando o vídeo: parte {} de {} ({}%)",),+ ("Preserve duration", "Manter a duração"),("Preserve luminosity", "Preservar luminosidade"),("Preserve pitch when stretched", "Manter o tom ao esticar"),(@@ -6391,6 +7353,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Provides adjustments for Stereoscopic 3D media.","Forneça ajustes para a mídia do Estereoscópico 3D.",),+ (+ "Pseudo-stereo (select one channel only)",+ "Pseudoestéreo (selecione só um canal)",+ ),("Puffy Clouds", "Nuvens fofas"),("Pure Blue Screen", "Tela azul pura"),("Pure Green Screen", "Tela verde pura"),@@ -6450,10 +7416,17 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Q", "Q"),("Quality", "Qualidade"),("Quality:", "Qualidade:"),+ ("Quantization depth", "Profundidade de quantização"),("Quantize to Frames", "Ativar Quantizar em quadros"),("Quarter", "Semínima"),+ ("Quarter Note", "Semínima"),+ ("Quarter Note Triplet", "Tercina de semínima"),("Quarter Note Triplets", "Tercinas de semínima"),("Quarter Notes", "Semínimas"),+ (+ "Quick bass, mid and treble.",+ "Graves, médios e agudos rápidos.",+ ),("Quick Blur", "Desfoque rápido"),("Quick Fade Audio Edits",@@ -6487,14 +7460,24 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Raise the sensitivity for fewer markers.","Aumente a sensibilidade para ter menos marcadores.",),+ (+ "Raises or lowers the pitch, like a tape or keeping the length.",+ "Sobe ou desce o tom, como uma fita ou mantendo a duração.",+ ),+ (+ "Raises or lowers the volume, up to 6 dB.",+ "Aumenta ou diminui o volume, em até 6 dB.",+ ),("Raises or lowers the volume.", "Aumenta ou reduz o volume."),("Ramp", "Rampa"),("Random pattern seed", "Semente do padrão aleatório"),("Random Squares", "Quadrados aleatórios"),("Randomness", "Aleatoriedade"),("Range", "Alcance"),+ ("Rate", "Taxa"),("Rate: {}", "Taxa: {}"),("Ratio", "Razão"),+ ("Ratio (x:1)", "Razão (x:1)"),("RAW Processor:", "Processador RAW:"),("Rays", "Raios"),(@@ -6594,11 +7577,21 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Reduce interlace flicker","Reduzir cintilação de entrelaçamento",),+ ("Reduce loud plosives", "Reduzir plosivas fortes"),+ (+ "Reduce loud sibilants (de-esser)",+ "Reduzir sibilantes fortes (de-esser)",+ ),("Reduce Minor Color Noise", "Reduzir ruído leve de cor"),+ ("Reduce noise by", "Reduzir o ruído em"),("Reduce Oversaturated Colors","Reduzir cores supersaturadas",),+ (+ "Reduce plosives and sibilants",+ "Reduzir plosivas e sibilantes",+ ),("Reduces color noise.", "Reduz o ruído de cor."),("Reduces luminance and color noise.",@@ -6640,6 +7633,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Reflection", "Reflexo"),("Refresh", "Atualizar"),("Refresh Storyboard", "Atualizar roteiro"),+ ("Reggae Guitar Chorus", "Coro de guitarra reggae"),+ ("Reggae Guitar Strong", "Guitarra reggae forte"),("Region", "Região"),("Region / CD Track", "Região / Faixa de CD"),("Region {}", "Região {}"),@@ -6647,7 +7642,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Regions", "Regiões"),("Regions/markers: {}", "Regiões/marcadores: {}"),("Rejoin Events", "Reunir eventos"),+ ("Release", "Liberação"),("Release (ms)", "Liberação (ms)"),+ ("Release speed", "Velocidade de liberação"),+ ("Release time", "Tempo de liberação"),("Reload Selected Layout", "Recarregar layout selecionado"),("Remaining: -{}", "Restante: -{}"),(@@ -6669,6 +7667,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Remover a mídia atual do histórico da Unidade de corte",),("Remove Envelope", "Remover envelope"),+ (+ "Remove frequencies around 1500 Hz by 25 dB",+ "Cortar 25 dB perto de 1500 Hz",+ ),("Remove From", "Remover de"),("Remove from Current Bin", "Remover do compartimento atual"),("Remove from Favorites", "Remover dos favoritos"),@@ -6682,6 +7684,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Remove from the capture list","Remover da lista de captura",),+ (+ "Remove low rumble below 80 Hz",+ "Remover o ronco abaixo de 80 Hz",+ ),("Remove Media", "Remover mídia"),("Remove path", "Remover caminho"),("Remove Rumble (80 Hz)", "Tirar ronco (80 Hz)"),@@ -6698,6 +7704,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Remove the condition", "Remover a condição"),("Remove the region", "Remover a região"),("Remove the tag", "Remover a tag"),+ (+ "Remove very low and inaudible frequencies below 20 Hz",+ "Remover as frequências muito graves e inaudíveis abaixo de 20 Hz",+ ),("Remove vignetting", "Remover vinheta"),("Remove Wind (150 Hz)", "Tirar vento (150 Hz)"),("Remove Yellow Cast", "Remover tom amarelado"),@@ -6795,6 +7805,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Reset to Defaults", "Restaurar padrões"),("Reset View (Num 5)", "Redefinir a vista (Num 5)"),("Resets the mesh.", "Redefine a malha."),+ (+ "Reshapes the wave along curves you draw, each half on its own.",+ "Remodela a onda por curvas que você desenha, cada metade por si.",+ ),("Resize Adjustment Event to Project","Redimensionar evento de ajuste ao projeto",@@ -6811,8 +7825,9 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Resolution:", "Resolução:"),("Resolution: {0} x {1} px", "Resolução: {0} x {1} px"),("Resolve Note", "Resolver nota"),+ ("Resonance", "Ressonância"),("Resonance (Q)", "Ressonância (Q)"),- ("Resonance Notch (1 kHz)", "Corte de ressonância (1 kHz)"),+ ("Resonant Filter", "Filtro ressonante"),("Restore", "Restaurar"),("Restore Down", "Restaurar Tamanho"),(@@ -6832,6 +7847,14 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Reveals", "Revelações"),("Reverb", "Reverberação"),+ ("Reverb (legacy)", "Reverb (antigo)"),+ ("Reverb / Original", "Reverb / original"),+ ("Reverb Drum Room", "Reverb de sala de bateria"),+ ("Reverb Empty Hall", "Reverb de salão vazio"),+ ("Reverb out", "Saída da reverb"),+ ("Reverb Vocal Ambient Room", "Reverb de ambiente para voz"),+ ("Reverb Vocal Hall", "Reverb de salão para voz"),+ ("Reverberation mode", "Modo de reverberação"),("Reverse", "Inverter"),("Reverse Event Background color",@@ -6841,10 +7864,14 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("RGB Parade", "Parada RGB"),("RGB: {}", "RGB: {}"),("RGBA -> BGRA", "RGBA -> BGRA"),+ ("Rhythm Guitar", "Guitarra base"),+ ("Rich Hall", "Salão rico"),("Ridges", "Sulcos"),("Right", "Direita"),("Right fisheye", "Olho de peixe direito"),+ ("Right note", "Nota direita"),("Right Only", "Apenas lado direito"),+ ("Right surround", "Surround direito"),("Right to Left", "Da direita para a esquerda"),("Right-Left, Hard Edge",@@ -6854,15 +7881,28 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Right-Left, Soft Edge","Da direita para a esquerda, borda suave",),+ ("Ringing Chime", "Sino ressoando"),("Rings", "Anéis"),("Ripple", "Ondulação"),("RL Color Wheels", "Rodas de cor RL"),- ("RL Offset", "Offset RL"),+ ("Robot", "Robô"),+ (+ "Rock Clipper +6dB (Soft Transients)",+ "Clipper rock +6 dB (transientes suaves)",+ ),+ ("Rock Maximizer +6dB", "Maximizador rock +6 dB"),("Roll angle", "Ângulo do rolo"),("Roll opacity", "Opacidade do rolo"),+ (+ "Roll-off frequencies below 120 Hz",+ "Atenuar abaixo de 120 Hz",+ ),("Rolling shutter correction", "Correção do Rolling shutter"),+ ("Rolloff", "Inclinação"),+ ("Room", "Sala"),("Room ambience.", "Ambiência de sala."),("Room Size", "Tamanho da sala"),+ ("Room size", "Tamanho da sala"),("Rotate 90°", "Girar 90°"),("Rotate 90° Clockwise", "Girar 90° no sentido horário"),(@@ -6877,11 +7917,16 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Rotation Angle", "Ângulo"),("Rotation:", "Rotação:"),("Rotations", "Voltas"),+ ("Rough Vocals", "Voz rasgada"),("Round 50%", "Redondo 50%"),("Round Extreme Horizontal", "Redondo extremo horizontal"),("Round Max", "Redondo máx."),("Round Noise Reduction", "Redução de ruído redonda"),("Roundness", "Arredondamento"),+ (+ "Rounds the sound to a bit depth with a little noise, so it stays clean.",+ "Arredonda o som para uma profundidade de bits com um pouco de ruído, para ele continuar limpo.",+ ),("Row 1", "Linha 1"),("Row 2", "Linha 2"),("Row 3", "Linha 3"),@@ -6896,7 +7941,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Ruler Time Format", "Formato de régua"),("Ruler time format:", "Formato de tempo da régua:"),- ("Rumble Remover", "Removedor de ronco"),+ ("Rumbly Growl", "Rosnado retumbante"),("Run Script…", "Executar script…"),("Safe Areas", "Áreas de segurança"),("Sample peak", "Pico de amostra"),@@ -6907,7 +7952,6 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Sampling rate: {} Hz", "Taxa de amostragem: {} Hz"),("Samsung Log to Linear", "Samsung Log para linear"),("Samsung Log to REC.709", "Samsung Log para REC.709"),- ("Sat", "Sat"),("Sat:", "Sat:"),("Saturate Greens", "Saturar os verdes"),("Saturation", "Saturação"),@@ -7008,6 +8052,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Saves what the chain's enabled effects do to colors as a .cube LUT: leave out those that are not about color (blurs, masks, vignettes)","Salva como LUT .cube o que os efeitos ligados da cadeia fazem com as cores: deixe de fora os que não são de cor (desfoques, máscaras, vinhetas)",),+ ("Sawtooth 1", "Dente de serra 1"),+ ("Sawtooth 2", "Dente de serra 2"),("Scale", "Escala"),("Scale & Location", "Escala e local"),("Scale About Center", "Redimensionar a partir do centro"),@@ -7025,6 +8071,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Multiplica a saturação das cores: 0 é cinza, 2 é o dobro.",),("Scaling", "Dimensionamento"),+ ("Scan mode", "Modo de leitura"),("Scan phasing", "Digitalização faseada"),("Scan type: {}", "Tipo de varredura: {}"),("Scene detection: {}", "Detecção de cenas: {}"),@@ -7067,6 +8114,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Search Results", "Resultados da pesquisa"),("Searching the folders…", "Procurando nas pastas…"),("Search…", "Procurar…"),+ ("Second", "Segunda"),("Seconds", "Segundos"),("Seed", "Semente"),("Seesaw", "Gangorra"),@@ -7236,6 +8284,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Escolhe a cor do preenchimento.",),("Select…", "Selecionar…"),+ ("Semitones", "Semitons"),("Send (Post Volume); right-click: Pre or Post Volume","Envio (pós-volume); clique direito: pré ou pós-volume",@@ -7264,6 +8313,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Separator", "Separador"),("Sepia", "Sépia"),("September", "setembro"),+ ("Sequencer Compression", "Compressão de sequenciador"),("Set All to {}", "Igualar todas ao {}"),("Set as project tempo", "Definir como andamento do projeto"),("Set Audio Mode", "Definir modo de áudio"),@@ -7336,6 +8386,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Settings", "Configurações"),("Seven Horizontal Blinds", "Sete persianas horizontais"),+ ("Sewer", "Esgoto"),("Shade Corrected", "Sombra corrigida"),("Shadow", "Sombra"),("Shadow Blur", "Desfoque da sombra"),@@ -7360,6 +8411,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Shear", "Inclinação"),("Shear Horizontally", "Inclinar horizontalmente"),("Shear Vertically", "Inclinar verticalmente"),+ (+ "Shift selection forwards (select one channel only)",+ "Atrasar a seleção (selecione só um canal)",+ ),("Shift+Space", "Shift+Espaço"),("Shift+wheel", "Shift+roda"),("Shininess", "Lustro"),@@ -7379,6 +8434,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Shortcuts saved in the \"Custom\" map.","Atalhos salvos no mapa \"Personalizado\".",),+ ("ShortDelay", "Delay curto"),("Show All", "Mostrar tudo"),("Show All Channels", "Mostrar todos os canais"),("Show all channels", "Mostrar todos os canais"),@@ -7530,17 +8586,30 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Desligar o computador quando a renderização terminar",),("Side by Side", "Lado a lado"),+ ("Side chain filter", "Filtro do side chain"),+ ("Side chain low cut", "Corte de graves no side chain"),("Side-by-Side", "Lado a lado"),("Significant color differences exist in your source and target images. Color matching may not work as expected.","Há diferenças de cor grandes entre as imagens de origem e de destino. A correspondência de cores pode não sair como esperado.",),+ ("Silence", "Silêncio"),("Silences background noise in the pauses.","Silencia o ruído de fundo nas pausas.",),+ (+ "Silences the sound while it stays below the threshold.",+ "Silencia o som enquanto ele fica abaixo do limiar.",+ ),+ (+ "Silences the track while it stays below the threshold.",+ "Silencia a trilha enquanto ela fica abaixo do limiar.",+ ),("Simple", "Simples"),("Simple 4 Point", "4 pontos simples"),+ ("Simple Delay", "Delay simples"),+ ("SimpleDelay", "Delay simples"),("Simulate device aspect ratio","Simular a proporção do dispositivo",@@ -7549,6 +8618,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Simulate Device Aspect Ratio","Simular proporção do dispositivo",),+ ("Sine", "Seno"),+ ("Sine out of phase", "Seno fora de fase"),("Single Pane", "Painel único"),("Six Way Split", "Divisão em seis"),("Sixteenth Note Triplets", "Tercinas de semicolcheia"),@@ -7569,6 +8640,12 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Slants the picture: its right side lower than its left by this part of its width.","Inclina a imagem: o lado direito fica mais baixo que o esquerdo nesta proporção da largura dela.",),+ ("Slap-back echo", "Eco curto (slap-back)"),+ ("SlapBack", "Slapback"),+ ("Slew", "Variação"),+ ("Slew amount", "Quanto limitar a variação"),+ ("Slew rate", "Limitar a variação"),+ ("Slicing Vocals", "Vocais cortantes"),("Slide", "Deslizar"),("Slide amount", "Quantidade de deslize"),("Slide down", "Deslizar para baixo"),@@ -7638,6 +8715,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Apresentação de slides: escolha as imagens",),("Slideshow…", "Apresentação de slides…"),+ ("Slight chip fuzz", "Fuzz de chip leve"),("Slip All Takes", "Ignorar todas as tomadas"),("Slip Event Media", "Deslizar mídia do evento"),("Slip Tool", "Ferramenta para ignorar"),@@ -7645,20 +8723,42 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Sloped Blinds", "Persianas inclinadas"),("Slot Machine", "Caça-níquel"),("Slow", "Lenta"),+ ("Slow attack", "Ataque lento"),+ ("Slow attack (ACX)", "Ataque lento (ACX)"),("Slow Fade", "Fade lento"),+ ("Slow flange", "Flange lento"),+ ("Slow flange 1", "Flange lento 1"),+ ("Slow flange 2", "Flange lento 2"),+ ("Slow flange 3", "Flange lento 3"),+ ("Slow flange 4", "Flange lento 4"),+ ("Slow heavy chorus", "Coro forte e lento"),+ ("Slow light chorus", "Coro leve e lento"),+ ("Slow medium chorus", "Coro médio e lento"),+ ("Slow modulation", "Modulação lenta"),("Slow Motion", "Câmera lenta"),+ ("Slow wah", "Wah lento"),("Slows the video down (or speeds it up) smoothly: the frames between the media's are made along the optical flow.","Desacelera (ou acelera) o vídeo suavemente: os quadros entre os da mídia são feitos ao longo do fluxo óptico.",),("Small", "Pequeno"),+ ("Small Club", "Clube pequeno"),+ ("Small hall", "Salão pequeno"),+ ("Small Hall", "Salão pequeno"),+ ("Small hall 1", "Salão pequeno 1"),+ ("Small hall 2", "Salão pequeno 2"),+ ("Small metal room", "Sala de metal pequena"),+ ("Small night club", "Boate pequena"),("Small Room", "Sala pequena"),+ ("Small room 1", "Sala pequena 1"),+ ("Small room 2", "Sala pequena 2"),("Small Tiles", "Ladrilhos pequenos"),("Smart adaptive (GPU only)","Adaptativo inteligente (só GPU)",),("Smart Bins", "Compartimentos inteligentes"),+ ("Smart release", "Liberação inteligente"),("Smart Split", "Dividir inteligente"),("Smart split default length (frames):",@@ -7670,9 +8770,12 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Smooth and thin automation data after recording or drawing","Suavizar e reduzir os dados de automação depois de gravar ou desenhar",),+ ("Smooth compression", "Compressão suave"),("Smooth curves", "Curvas suaves"),("Smooth Fade", "Fade suave"),("Smooth motion", "Movimento suave"),+ ("Smooth saturation", "Saturação suave"),+ ("Smooth/Enhance", "Suavizar/Realçar"),("Smoothing", "Suavização"),("Smoothing Parameters", "Parâmetros de suavização"),(@@ -7753,24 +8856,44 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Snapping", "Alinhamento"),("Snapshot copied.", "Snapshot copiado."),("Snapshot saved to {}", "Snapshot salvo em {}"),+ ("Snare Cleanup", "Limpar a caixa"),+ ("Snipper (cut)", "Snipper (cortar)"),("Snow, as with poor reception.","Chuvisco, como com uma recepção ruim.",),("Social Media", "Redes sociais"),("Soft", "Suave"),+ ("Soft clip", "Clip suave"),("Soft Clouds", "Nuvens suaves"),("Soft Contrast", "Contraste suave"),("Soft Diagonal", "Diagonal suave"),("Soft Edge", "Borda suave"),("Soft Flash", "Flash suave"),("Soft Grain", "Granulado suave"),+ ("Soft knee", "Joelho suave"),+ (+ "Soft knee compressor/gate (-24 dB threshold)",+ "Compressor/portão de joelho suave (limiar de -24 dB)",+ ),+ ("Soft Limiter", "Limitador suave"),+ ("Soft limiter", "Limitador suave"),("Soft Moderate Contrast", "Contraste suave moderado"),+ ("Soft noise gate", "Portão de ruído suave"),+ (+ "Soft noise gate below -36 dB",+ "Portão de ruído suave abaixo de -36 dB",+ ),("Soft Oval", "Oval suave"),("Soft Shadow", "Sombra suave"),+ ("Soft square", "Quadrada suave"),("Soft, even blur.", "Desfoque suave e uniforme."),("Soften", "Suavizar"),("Soften edges", "Atenuar bordas"),+ (+ "Softens the highs (smooth) or brings them forward (enhance).",+ "Suaviza os agudos (suavizar) ou os traz para a frente (realçar).",+ ),("Softer, finer contrast, with a vignette around the picture if wanted.","Contraste mais suave e refinado, com uma vinheta ao redor da imagem, se quiser.",@@ -7816,7 +8939,9 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Sort Trimmer History","Ordenar histórico da Unidade de corte",),+ ("Sound", "Som"),("Sound files", "Arquivos de som"),+ ("Soupe Du Jour", "Sopa do dia"),("Source", "Origem"),("Source Alpha", "Alfa da origem"),("Source channel", "Canal de origem"),@@ -7827,6 +8952,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Space", "Espaço"),("Space Above", "Espaço acima"),("Space Below", "Espaço abaixo"),+ ("Spaced", "Espaçado"),("Spacing", "Espaçamento"),("Sparkle", "Cintilar"),("Sparkling Light Rays", "Raios de luz reluzentes"),@@ -7912,6 +9038,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Spotlight Up (flat)", "Holofote para cima (plano)"),("Spotlight with Feather", "Foco com esbatimento"),("Spread", "Amplitude"),+ ("Spring Fx", "Mola"),("Square", "Quadrado"),("Square (1:1)", "Quadrado (1:1)"),("Square Aspect", "Proporção quadrada"),@@ -7970,6 +9097,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Stabilization options", "Suavização"),("Stabilize", "Estabilizar"),("Stabilizes video motion", "Estabiliza o movimento do vídeo"),+ ("Stadium", "Estádio"),+ ("Stages", "Estágios"),("Stagger", "Escalonamento"),("Standard (13 elements)", "Padrão (13 elementos)"),(@@ -8017,6 +9146,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Steps", "Passos"),("Stereo", "Estéreo"),("stereo", "estéreo"),+ ("Stereo Delay", "Delay estéreo"),+ ("Stereo Ensemble", "Ensemble estéreo"),+ ("Stereo pan", "Panorâmica estéreo"),+ ("Stereo sync channels", "Sincronizar os canais estéreo"),("Stereo Viewer", "Visor estéreo"),("Stereo Width", "Largura estéreo"),("Stereo Width (%)", "Largura estéreo (%)"),@@ -8056,22 +9189,29 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Strobe", "Estroboscópio"),("Strong", "Forte"),+ ("Strong beats only", "Só as batidas fortes"),("Strong Circular", "Circular forte"),+ ("Strong Guitar Chorus", "Coro forte de guitarra"),("Strong Proportional", "Proporcional forte"),("Strong Radial", "Radial forte"),("Strong, Warm", "Forte, quente"),+ ("Studio Reverb", "Reverb de estúdio"),("Studio RGB (16 to 235)", "RGB de estúdio (16 a 235)"),("Studio RGB to Computer RGB","RGB de estúdio para RGB de computador",),+ ("Stutter / Original", "Gaguejo / original"),("Style", "Estilo"),("Styles", "Estilos"),+ ("Sub Bass", "Subgraves"),("Subclip {} added to Project Media.","Subclipe {} adicionado à Mídia do projeto.",),("Subtle", "Sutil"),+ ("Subtle Ambience", "Ambiente sutil"),+ ("Subtle movement for pads", "Movimento sutil para pads"),("Subtract", "Subtrair"),("Subtractive Crossfade", "Transição subtrativa"),("Subtractive crossfade", "Transição subtrativa"),@@ -8127,6 +9267,13 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Trocar os arquivos de vídeo ao renderizar",),("Swaps the picture and the map.", "Troca a imagem e o mapa."),+ (+ "Sweeping notches of 4, 8 or 12 stages, with feedback.",+ "Entalhes que varrem as frequências, de 4, 8 ou 12 estágios, com realimentação.",+ ),+ ("Sweet Echo", "Eco doce"),+ ("Sweet Echo 1-8 Dot.", "Eco doce 1-8 pontuada"),+ ("Sweet Echo Tripl.", "Eco doce Tripl."),("Swirl", "Redemoinho"),("Switch between two settings to compare them",@@ -8141,7 +9288,12 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Switches the mode between smoothing motion ('Static Camera' is disabled) and fixing motion ('Static Camera' is enabled).","Alterna entre suavizar o movimento ('Câmera estática' desligada) e fixar o movimento ('Câmera estática' ligada).",),+ (+ "Switches the sound on and off in a fast rhythm.",+ "Liga e desliga o som num ritmo rápido.",+ ),("Sync", "Sincronização"),+ ("Sync channel gains", "Sincronizar os ganhos dos canais"),("Sync Cursor", "Sincronizar cursor"),("Sync Date/Timestamp to Align Events",@@ -8174,6 +9326,14 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Synchronize", "Sincronizar"),("Synchronizing audio…", "Sincronizando o áudio…"),+ (+ "Synth Arp 8th 16th BBD",+ "Arpejo de synth colcheia/semicolcheia BBD",+ ),+ ("Synth Arp 8th BBD", "Arpejo de synth colcheia BBD"),+ ("Synth Bass Compression", "Compressão de baixo synth"),+ ("Synth Pad Liquid", "Pad de synth líquido"),+ ("Synth Pad Mover", "Pad de synth em movimento"),("System", "Sistema"),("Tag", "Tag"),("Tagged Media", "Tags"),@@ -8194,6 +9354,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Takes a light's cast away: the color that should be gray, or the light's temperature and tint.","Tira a cor de uma luz da imagem: a cor que deveria ser cinza, ou a temperatura e o matiz da luz.",),+ (+ "Takes clicks and crackle out and turns the steady hiss of old recordings down.",+ "Tira cliques e estalos e abaixa o chiado constante de gravações antigas.",+ ),("Takes the settings a properties file (.xml) keeps: the effect, the position, the background and the styles.","Usa as configurações que um arquivo de propriedades (.xml) guarda: o efeito, a posição, o fundo e os estilos.",@@ -8242,12 +9406,39 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Talk with other BananaV users and share your work.","Converse com outros usuários do BananaV e compartilhe seus trabalhos.",),+ (+ "Talkback Drum Treatment",+ "Tratamento de bateria (talkback)",+ ),+ (+ "Tames the hiss of \"s\" sounds in a voice.",+ "Doma o chiado dos sons de \"s\" numa voz.",+ ),+ ("Tap 1", "Saída 1"),+ ("Tap 2", "Saída 2"),+ ("Tap 3", "Saída 3"),+ ("Tap 4", "Saída 4"),+ ("Tap 5", "Saída 5"),+ ("Tap 6", "Saída 6"),+ ("Tap 7", "Saída 7"),+ ("Tap 8", "Saída 8"),+ ("Tap gain", "Ganho da saída"),("Tape Name", "Nome da fita"),("Tape name:", "Nome da fita:"),+ ("Tapped delay 1", "Delay com saídas 1"),+ ("Tapped delay 2", "Delay com saídas 2"),+ (+ "Tapped delay, stereo pan",+ "Delay com saídas, panorâmica estéreo",+ ),("Target", "Destino"),("Target Image", "Imagem de destino"),("Teal", "Azul-petróleo"),("Teal and Orange", "Azul-petróleo e laranja"),+ (+ "Teenage Late-Night Radio by the Bed",+ "Rádio de adolescente na cabeceira de madrugada",+ ),("Telephone", "Telefone"),("Temperature", "Temperatura"),("Temperature:", "Temperatura:"),@@ -8255,8 +9446,15 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Template view", "Exibição dos modelos"),("Template:", "Modelo:"),("Tempo Detection", "Detecção de andamento"),+ ("Tempo sync", "Sincronizar ao andamento"),+ ("Tempo sync decay", "Decaimento no andamento"),+ ("Tempo sync delay", "Delay no andamento"),("Temporal blend", "Mistura temporal"),("Temporary files folder:", "Pasta de arquivos temporários:"),+ (+ "Ten bands an octave apart, from 28 Hz to 15 kHz.",+ "Dez bandas a uma oitava uma da outra, de 28 Hz a 15 kHz.",+ ),("Test first, then burn CDs","Testar primeiro e depois gravar CDs",@@ -9158,6 +10356,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["The pictures slide aside and change places.","As imagens deslizam para os lados e trocam de lugar.",),+ (+ "The pitch wavers along a wave you draw, like a tape speeding up and slowing down.",+ "O tom oscila numa onda que você desenha, como uma fita acelerando e freando.",+ ),("The pixel's own weight.", "O peso do próprio pixel."),("The plug-in could not be loaded: {}",@@ -9560,10 +10762,22 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["The vignette's width, in percent of the frame's.","A largura da vinheta, em porcentagem da do quadro.",),+ (+ "The volume follows a wave you draw, slow (tremolo) or fast (ring tones).",+ "O volume segue uma onda que você desenha, lenta (tremolo) ou rápida (timbres de anel).",+ ),+ (+ "The volume rises and falls in a smooth wave (tremolo).",+ "O volume sobe e desce numa onda suave (tremolo).",+ ),("The VST 3 effects chosen here are offered as audio plug-ins; VST 2 plug-ins are listed only.","Os efeitos VST 3 escolhidos aqui são oferecidos como plug-ins de áudio; os plug-ins VST 2 são só listados.",),+ (+ "The warmth and grit of a tube preamp.",+ "O calor e a aspereza de um pré-amplificador valvulado.",+ ),("The weights scaled to add up to 1.","Os pesos escalados para somar 1.",@@ -9609,10 +10823,16 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["These files were recorded:","Estes arquivos foram gravados:",),+ (+ "Thickens the sound with slightly detuned, delayed copies of itself.",+ "Encorpa o som com cópias dele mesmo, um pouco desafinadas e atrasadas.",+ ),("Thin", "Rarear"),("Thin All Points", "Rarear todos os pontos"),("Thin Selected Points", "Rarear os pontos selecionados"),+ ("Third down", "Terça abaixo"),("Third Party", "Terceiros"),+ ("Third up", "Terça acima"),("Thirty-Second Note Triplets", "Tercinas de fusa"),("Thirty-Second Notes", "Fusas"),(@@ -9656,6 +10876,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["This file keeps no path to the project it was rendered from.","Este arquivo não guarda o caminho do projeto de onde foi renderizado.",),+ (+ "This filter type comes in one slope only.",+ "Este tipo de filtro tem uma só inclinação.",+ ),("This format has no audio.", "Este formato não tem áudio."),("This format has no video.", "Este formato não tem vídeo."),(@@ -9731,6 +10955,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Threshold blend", "Mistura do limiar"),("Threshold Dissolve", "Dissolução por limiar"),("Threshold dissolve", "Dissolução por limiar"),+ ("Threshold level", "Nível do limiar"),("Thresholded Optical Flow Field","Campo de fluxo óptico limiarizado",@@ -9752,6 +10977,14 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Tempo (timecode ou segundos):",),("Time at Cursor", "Tempo no cursor"),+ (+ "Time compress 85 % of original",+ "Comprimir o tempo para 85% do original",+ ),+ (+ "Time expand 110 % of original",+ "Expandir o tempo para 110% do original",+ ),("Time Fmt / Zero", "Formato de tempo / Zero"),("Time Format", "Formato de tempo"),(@@ -9765,6 +10998,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Time selection envelope fades (ms):","Fades de envelope na seleção de tempo (ms):",),+ ("Time Stretch", "Esticar o tempo"),("Time Stretch/Compress Tool","Ferramenta de compressão/expansão de tempo",@@ -9906,7 +11140,9 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Track Colors", "Cores das trilhas"),("Track Composite Level", "Nível composto da trilha"),+ ("Track Compressor", "Compressor da trilha"),("Track Display Color", "Cor de exibição da trilha"),+ ("Track EQ", "EQ da trilha"),("Track fade bottom:", "Fade da trilha embaixo:"),("Track Fade to Color", "Transição da trilha para cor"),("Track fade top:", "Fade da trilha em cima:"),@@ -9925,6 +11161,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Track Motion: {}", "Movimento da trilha: {}"),("Track Motion…", "Movimento da trilha…"),("Track Mute", "Trilha silenciada"),+ ("Track Noise Gate", "Portão de ruído da trilha"),("Track one frame backward", "Rastrear um quadro para trás"),("Track one frame forward",@@ -9955,6 +11192,8 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Transfer the motion to an effect","Transferir o movimento para um efeito",),+ ("Transistor 1", "Transistor 1"),+ ("Transistor 2", "Transistor 2"),("Transition", "Transição"),("Transition in", "Transição de entrada"),("Transition Progress", "Progresso de transição"),@@ -9977,7 +11216,15 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Transparent background", "Fundo transparente"),("Transport", "Transporte"),("TranzPort Driver", "Driver TranzPort"),+ ("Treble", "Agudos"),+ ("Treble boost", "Reforço de agudos"),+ ("Treble Boost", "Reforço de agudos"),+ ("Treble only", "Só agudos"),+ ("Tremolo flange", "Flange tremolo"),+ ("Tremolo Pan", "Tremolo pan"),+ ("Tremolo wah", "Wah tremolo"),("Triangle", "Triângulo"),+ ("Triangle 1", "Triângulo 1"),("Triangle Cut Out, Blue Border","Triângulo recortado, borda azul",@@ -10033,12 +11280,30 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Trimmer on External Monitor","Unidade de corte no monitor externo",),+ ("TripHop Triplets", "Tercinas trip-hop"),+ ("TripleDelay", "Delay triplo"),("True Peak Blocking Filter","Filtro de bloqueio de pico verdadeiro",),("True Peak Range", "Alcance de pico verdadeiro"),("True Peaks", "Picos reais"),+ ("Try On Drums", "Teste na bateria"),+ (+ "Try on Drums at 120 BPM - use mix and depth",+ "Teste na bateria a 120 BPM - use mistura e profundidade",+ ),+ ("Tube 1", "Válvula 1"),+ (+ "Tube console - Master Buss",+ "Console valvulado - bus master",+ ),+ (+ "Tube console - place on every mixer channel",+ "Console valvulado - em cada canal do mixer",+ ),+ ("Tube Fryer", "Fritadeira valvulada"),+ ("Tube Stage", "Estágio valvulado"),("Tuesday", "terça-feira"),("Tumble In", "Cair rodopiando"),("Tungsten Light Corrected", "Luz de tungstênio corrigida"),@@ -10089,8 +11354,13 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Turns the window, in degrees.", "Gira a janela, em graus."),("TV Look", "Visual de TV"),("TV Simulator", "Simulador de TV"),+ ("Tweak", "Ajuste fino"),("Twist", "Torção"),("Two Columns Style", "Estilo de duas colunas"),+ (+ "Two delays, digital, analog or bucket brigade, in ms or notes of the tempo.",+ "Dois delays, digital, analógico ou bucket brigade, em ms ou notas do andamento.",+ ),("Two doors open from the middle, or close from the edges, onto the next picture.","Duas portas se abrem do meio, ou se fecham a partir das bordas, sobre a próxima imagem.",@@ -10126,6 +11396,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Áudio sem compressão em Wave64, para arquivos de qualquer tamanho.",),("Undefined", "Indefinida"),+ ("Under Water", "Debaixo d'água"),("Undersample rate:", "Taxa de subamostragem:"),("Undo", "Desfazer"),("Undo / redo", "Desfazer / refazer"),@@ -10160,6 +11431,10 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Up to eight bands drawn on a graph, on both channels, one of them, the middle or the sides.","Até oito bandas desenhadas num gráfico, nos dois canais, em um deles, no meio ou nos lados.",),+ (+ "Up to eight echoes of one delay line, each with its own time, level and side.",+ "Até oito ecos de uma linha de atraso, cada um com seu tempo, nível e lado.",+ ),("Up to five masks — rectangles, ovals, diamonds or Bézier curves — that cut the picture out, or keep the effects before it inside them.","Até cinco máscaras — retângulos, ovais, losangos ou curvas Bézier — que recortam a imagem, ou mantêm dentro delas os efeitos anteriores.",@@ -10181,7 +11456,6 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Upper Right, Scaled, No Angle, Opaque","Superior direito, reduzido, sem ângulo, opaco",),- ("Upper Threshold", "Limiar superior"),("Upper-Right Glow", "Brilho superior direito"),("Upside Down", "De cabeça para baixo"),(@@ -10232,6 +11506,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Usar o ganho de envio de trilha antigo",),("Use linear scrub range", "Usar faixa de percurso linear"),+ ("Use longer look-ahead", "Olhar mais à frente"),("Use Media Frame Rate", "Usar taxa de quadros da mídia"),("Use motion compensation", "Usar compensação de movimento"),("Use Project Frame Rate", "Usar taxa de quadros do projeto"),@@ -10309,6 +11584,13 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Vectorscope/Waveform/Histogram","Vetorscópio/Forma de onda/Histograma",),+ ("VEG Project", "Projeto VEG"),+ ("VEG Project (*.veg)", "Projeto VEG (*.veg)"),+ ("VEG Project (*.veg)…", "Projeto VEG (*.veg)…"),+ (+ "VEG Project (Experimental) (*.veg)…",+ "Projeto VEG (Experimental) (*.veg)…",+ ),("Velocity", "Velocidade"),("Vendor", "Fabricante"),("Venetian Blinds", "Persianas"),@@ -10361,7 +11643,18 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Very Bright", "Muito claro"),("Very Dark", "Muito escuro"),+ ("Very fast clipper", "Cortador muito rápido"),+ ("Very Large & Rich", "Muito grande e rico"),+ ("Very Light Guitar Room", "Sala muito leve para guitarra"),+ ("Very long hall", "Salão muito longo"),("Very Old Film", "Filme muito antigo"),+ ("Vibrato", "Vibrato"),+ ("Vibrato 1", "Vibrato 1"),+ ("Vibrato 2", "Vibrato 2"),+ ("Vibrato 3", "Vibrato 3"),+ ("Vibrato-verb 1", "Vibrato-reverb 1"),+ ("Vibrato-verb 2", "Vibrato-reverb 2"),+ ("Vibrato-verb 3", "Vibrato-reverb 3"),("Video", "Vídeo"),("Video Bus Track", "Trilha de barramento de vídeo"),("Video Channels", "Canais de vídeo"),@@ -10458,10 +11751,20 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[),("Vintage", "Vintage"),("Vintage Mode", "Modo vintage"),+ ("Vintage Organ Toolkit", "Órgão vintage"),+ ("Vintage plate", "Placa vintage"),+ ("Vintage VCA style", "Estilo VCA vintage"),+ ("Vintage Vox Channel", "Canal de voz vintage"),("Visible Outer Ring", "Anel externo visível"),("Visualization", "Visualização"),+ ("Vocal", "Voz"),+ ("Vocal (gated)", "Voz (com portão)"),+ ("Vocal (strong)", "Voz (forte)"),+ ("Vocal Strip", "Canal de voz"),+ ("Vocal with de-squeak", "Voz sem chiado"),+ ("Vocals", "Voz"),("Voice", "Voz"),- ("Voice Clarity", "Clareza da voz"),+ ("Voiceover Gate", "Portão de locução"),("Vol:", "Vol:"),("Volume", "Volume"),(@@ -10469,8 +11772,20 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Volume (duplo clique: 0 dB; Ctrl+arrastar: ajuste fino)",),("Volume Down", "Diminuir volume"),+ ("Volume maximizer", "Maximizador de volume"),("Volume Mute", "Desativar som"),("Volume Up", "Aumentar volume"),+ ("Vox Alien Warble", "Voz alienígena trêmula"),+ ("Vox BBD Slapback", "Slapback BBD de voz"),+ ("Vox Chorus", "Coro de voz"),+ ("Vox Cleanup", "Limpar a voz"),+ ("Vox Decoupler", "Desacoplador de voz"),+ (+ "Vox Ensemble Warm + Decoupled",+ "Ensemble de voz quente e desacoplado",+ ),+ ("Vox Vibrato Mono", "Vibrato de voz mono"),+ ("Vox Vibrato Stereo", "Vibrato de voz estéreo"),("VST 3 Plug-in", "Plug-in VST 3"),("VST Effects", "Efeitos VST"),("VST search folders:", "Pastas de busca de VST:"),@@ -10480,6 +11795,18 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["VU Meters Control Region","Região de controle dos medidores VU",),+ ("Wacky", "Maluca"),+ ("Wacky 1", "Maluco 1"),+ ("Wacky 2", "Maluco 2"),+ ("Wacky 3", "Maluco 3"),+ ("Wacky 4", "Maluco 4"),+ ("Wah-wah", "Wah-wah"),+ ("Wah-Wah", "Wah-Wah"),+ ("Wah-wah 1", "Wah-wah 1"),+ ("Wah-wah 2", "Wah-wah 2"),+ ("Wah-wah 3", "Wah-wah 3"),+ ("Wah-wah 4", "Wah-wah 4"),+ ("Wah-wah 5", "Wah-wah 5"),("Wait for the files being copied, or cancel them.","Espere os arquivos que estão sendo copiados, ou cancele a cópia.",@@ -10489,12 +11816,17 @@ pub(super) const ENTRIES: &[(&str, &str)] = &["Aguarde as formas de onda terminarem de ser calculadas.",),("Wait for vertical sync", "Esperar a sincronização vertical"),+ ("Walkie-talkie", "Walkie-talkie"),+ ("Warble 1", "Trinado 1"),+ ("Warble 2", "Trinado 2"),("Warm", "Quente"),+ ("Warm Ambience", "Ambiente quente"),("Warm Colors", "Cores quentes"),("Warm Light", "Luz quente"),+ ("Warm Space", "Espaço quente"),("Warm Summer", "Verão quente"),+ ("Warm Tube Preamp", "Pré valvulado quente"),("Warm Vignette", "Vinheta quente"),- ("Warmth", "Calor"),("Warn if creating a nested timeline may adversely affect the project","Avisar se criar uma linha do tempo aninhada puder prejudicar o projeto",@@ -10522,8 +11854,12 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("Web & Streaming", "Web e streaming"),("Website", "Site"),("Wednesday", "quarta-feira"),+ ("Weird 1", "Estranho 1"),("Welcome Screen", "Tela de boas-vindas"),("Welcome to BananaV", "Boas-vindas ao BananaV"),+ ("Wet / Dry", "Molhado / seco"),+ ("Wet out", "Saída com efeito"),+ ("Wet slew", "Variação limitada"),("What a click on the curve does: move, add an anchor, delete one, or add one whose tangents are split.","O que um clique na curva faz: mover, adicionar uma âncora, apagar uma ou adicionar uma com as tangentes separadas.",@@ -10789,10 +12125,7 @@ pub(super) const ENTRIES: &[(&str, &str)] = &[("White Wash", "Lavagem branca"),("Whole", "Semibreve"),("Wide", "Larga"),- (- "Wide Drums, Centered Snare",- "Bateria larga, caixa no centro",- ),+ ("Wide Open Hall", "Salão bem aberto"),("Wider channels", "Canais mais largos"),("Widescreen (16:9)", "Widescreen (16:9)"),("Width", "Largura"),@@ -11111,6 +12444,7 @@ pub(super) const CONTEXT: &[(&str, &str, &str)] = &[("quality", "Low", "Baixa"),("quality", "Medium", "Média"),("quality", "High", "Alta"),+ ("phase", "Minimum", "Mínima"),("meter", "Out", "Saída"),];@@ -11335,6 +12669,14 @@ pub(super) const PLURALS: &[(&str, &str, &[&str])] = &["{} storyboard cells",&["{} célula de roteiro", "{} células de roteiro"],),+ (+ "{} transition at an event's end was left out.",+ "{} transitions at events' ends were left out.",+ &[+ "{} transição no fim de um evento ficou de fora.",+ "{} transições no fim de eventos ficaram de fora.",+ ],+ ),("{} unused media file removed from the project.","{} unused media files removed from the project.",@@ -11591,4 +12933,41 @@ pub(super) const PLURALS: &[(&str, &str, &[&str])] = &["As trilhas selecionadas têm {0} eventos. Excluir as trilhas e os eventos?",],),+ (+ "Project opened: {} event.",+ "Project opened: {} events.",+ &["Projeto aberto: {} evento.", "Projeto aberto: {} eventos."],+ ),+ (+ "{} audio effect was left out.",+ "{} audio effects were left out.",+ &[+ "{} efeito de áudio ficou de fora.",+ "{} efeitos de áudio ficaram de fora.",+ ],+ ),+ (+ "{} effect has no plug-in in BananaV.",+ "{} effects have no plug-in in BananaV.",+ &[+ "{} efeito não tem plug-in no BananaV.",+ "{} efeitos não têm plug-in no BananaV.",+ ],+ ),+ (+ "{} envelope was left out.",+ "{} envelopes were left out.",+ &[+ "{} envelope ficou de fora.",+ "{} envelopes ficaram de fora.",+ ],+ ),+ (+ "{} event of generated media was left out.",+ "{} events of generated media were left out.",+ &[+ "{} evento de mídia gerada ficou de fora.",+ "{} eventos de mídia gerada ficaram de fora.",+ ],+ ),];diff --git a/crates/ui-egui/src/keymap.rs b/crates/ui-egui/src/keymap.rsindex 2a92129..c9327ce 100644--- a/crates/ui-egui/src/keymap.rs+++ b/crates/ui-egui/src/keymap.rs@@ -1221,8 +1221,8 @@ const EXPLORER: &[(&str, &[&str], Action)] = cmds! {const TRIMMER: &[(&str, &[&str], Action)] = cmds! {"CursorTo.Center" => [] Soon;"CursorTo.CycleTimeSelection" => [] Soon;- "CursorTo.End" => ["Ctrl+End"] X(Extra::Trimmer(TrimmerOp::End));- "CursorTo.Home" => ["Ctrl+Home"] X(Extra::Trimmer(TrimmerOp::Start));+ "CursorTo.End" => ["E", "Ctrl+End"] X(Extra::Trimmer(TrimmerOp::End));+ "CursorTo.Home" => ["W", "Ctrl+Home"] X(Extra::Trimmer(TrimmerOp::Start));"CursorTo.LeftByFrame" => ["Alt+Left"] X(Extra::Trimmer(TrimmerOp::Frame(-1)));"CursorTo.LeftByGrid" => [] Soon;"CursorTo.LeftByMarker" => ["Ctrl+Left"] X(Extra::Trimmer(TrimmerOp::MarkerStep(-1)));@@ -1732,6 +1732,7 @@ fn global_id(cmd: Cmd) -> String {| Cmd::ImportProjectMedia| Cmd::ImportEdl| Cmd::ImportOtio+ | Cmd::ImportVeg| Cmd::ImportXml| Cmd::ImportFcpxml| Cmd::ImportClosedCaptioning@@ -1743,6 +1744,7 @@ fn global_id(cmd: Cmd) -> String {| Cmd::ExportFcpxml| Cmd::ExportEdl| Cmd::ExportOtio+ | Cmd::ExportVeg| Cmd::Properties| Cmd::Exit => "File",Cmd::Toolbardiff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex add3cd4..9809cc7 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -103,6 +103,7 @@ mod track_defaults;mod track_motion;mod transition_window;mod transport_buttons;+mod veg_ui;mod view360;mod vst;mod vst_ui;diff --git a/crates/ui-egui/src/media_files.rs b/crates/ui-egui/src/media_files.rsindex fe73534..50cce77 100644--- a/crates/ui-egui/src/media_files.rs+++ b/crates/ui-egui/src/media_files.rs@@ -17,6 +17,8 @@ pub(crate) enum FileKind {/// `.otiod` bundle is a folder), Final Cut Pro 7's XML (`.xml`) or/// FCPXML (`.fcpxml`).Timeline,+ /// Another editor's project (`.veg`).+ VegProject,}/// What a file is, by its extension (`None`: nothing BananaV opens).@@ -29,6 +31,8 @@ pub(crate) fn kind_of(path: &Path) -> Option<FileKind> {let ext = ext.as_str();if ext == "bvproj" {Some(FileKind::Project)+ } else if ext == "veg" {+ Some(FileKind::VegProject)} else if matches!(ext, "otio" | "otioz" | "otiod" | "xml" | "fcpxml") {Some(FileKind::Timeline)} else if VIDEO_EXTENSIONS.contains(&ext) {@@ -71,11 +75,12 @@ pub(crate) fn media_filters(d: rfd::FileDialog) -> rfd::FileDialog {/// File › Open's filters: projects, timelines and media together first/// (VEGAS's Open opens both), then each kind.pub(crate) fn open_filters(d: rfd::FileDialog) -> rfd::FileDialog {- let mut all = vec!["bvproj", "otio", "otioz", "xml", "fcpxml"];+ let mut all = vec!["bvproj", "veg", "otio", "otioz", "xml", "fcpxml"];all.extend(all_media());let d = d.add_filter(tr("All Project and Media Files"), &all).add_filter(tr("BananaV Project"), &["bvproj"])+ .add_filter(tr("VEG Project (*.veg)"), &["veg"]).add_filter("OpenTimelineIO (*.otio, *.otioz)", &["otio", "otioz"]).add_filter("Final Cut Pro 7/DaVinci Resolve (*.xml)", &["xml"]).add_filter("Final Cut Pro X (*.fcpxml)", &["fcpxml"])diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex c7f5048..c4c5d67 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -237,6 +237,7 @@ fn file_menu(ui: &mut Ui, app: &mut BananaApp) {cmd(ui, app, Cmd::ImportFcpxml);cmd(ui, app, Cmd::ImportEdl);cmd(ui, app, Cmd::ImportOtio);+ cmd(ui, app, Cmd::ImportVeg);cmd(ui, app, Cmd::ImportDvdCamcorder);cmd(ui, app, Cmd::ImportBwf);cmd(ui, app, Cmd::ImportClosedCaptioning);@@ -249,6 +250,7 @@ fn file_menu(ui: &mut Ui, app: &mut BananaApp) {cmd(ui, app, Cmd::ExportFcpxml);cmd(ui, app, Cmd::ExportEdl);cmd(ui, app, Cmd::ExportOtio);+ cmd(ui, app, Cmd::ExportVeg);});if item(ui, tr("Screen Capture…")) {app.open_screen_capture();diff --git a/crates/ui-egui/src/modern_eq.rs b/crates/ui-egui/src/modern_eq.rsindex b045ceb..663b180 100644--- a/crates/ui-egui/src/modern_eq.rs+++ b/crates/ui-egui/src/modern_eq.rs@@ -222,9 +222,10 @@ fn new_band(kind: BandType, freq: f32, gain_db: f32) -> Band {} else {0.0},- q: 1.0,+ q: std::f32::consts::FRAC_1_SQRT_2,slope: 12,route: Route::Stereo,+ linear: false,}}@@ -248,7 +249,10 @@ fn type_at(freq: f32) -> BandType {/// slot; which (none when all eight are in use).fn add_at(s: &mut Settings, freq: f32, db: f32) -> Option<usize> {let b = s.bands.iter().position(|b| !b.used)?;- s.bands[b] = new_band(type_at(freq), freq, db);+ s.bands[b] = Band {+ linear: s.bands[b].linear,+ ..new_band(type_at(freq), freq, db)+ };Some(b)}@@ -268,7 +272,10 @@ fn add_free(s: &mut Settings) -> Option<usize> {.windows(2).map(|w| (w[0], w[1])).max_by(|x, y| (x.1 - x.0).total_cmp(&(y.1 - y.0)))?;- s.bands[b] = new_band(BandType::Peaking, ((lo + hi) / 2.0).exp(), 0.0);+ s.bands[b] = Band {+ linear: s.bands[b].linear,+ ..new_band(BandType::Peaking, ((lo + hi) / 2.0).exp(), 0.0)+ };Some(b)}@@ -399,6 +406,40 @@ fn top_bar(ui: &mut Ui, view: &mut View, e: &mut Effect, id: egui::Id) {}}});+ // The bands' phase all at once: "Mixed" while they differ.+ ui.add_space(12.0);+ ui.label(tr("Phase:"));+ let now = Settings::of(e);+ let used: Vec<&Band> = now.bands.iter().filter(|b| b.used).collect();+ let linear = !used.is_empty() && used.iter().all(|b| b.linear);+ let mixed = !linear && used.iter().any(|b| b.linear);+ let shown = if mixed {+ tr("Mixed")+ } else if linear {+ tr("Linear")+ } else {+ trc("phase", "Minimum")+ };+ egui::ComboBox::from_id_salt(id.with("phase"))+ .width(84.0)+ .selected_text(shown)+ .show_ui(ui, |ui| {+ for (to, name) in [(false, trc("phase", "Minimum")), (true, tr("Linear"))] {+ if ui.selectable_label(!mixed && linear == to, name).clicked() {+ let mut s = Settings::of(e);+ for b in &mut s.bands {+ b.linear = to;+ }+ s.write(e);+ }+ }+ })+ .response+ .on_hover_text(if mixed {+ tr("Mixed band models")+ } else {+ tr("All bands use the same global band model")+ });let settings = icon_button_ex(ui, Icon::Settings, tr("Settings"), false, true);egui::Popup::menu(&settings).show(|ui| {if menus::toggle_item(ui, tr("Show Tooltips"), view.tooltips) {@@ -422,6 +463,23 @@ fn top_bar(ui: &mut Ui, view: &mut View, e: &mut Effect, id: egui::Id) {}}});+ // How long the linear-phase bands' filter is (and how late).+ menus::sub(ui, tr("Linear Phase Quality"), true, |ui| {+ let now = Settings::of(e).quality;+ for (k, name) in [+ (0u8, tr("Lowest")),+ (1, trc("quality", "Low")),+ (2, trc("quality", "Medium")),+ (3, trc("quality", "High")),+ (4, tr("Highest")),+ ] {+ if menus::check_item(ui, name, now == k, true, "") {+ let mut s = Settings::of(e);+ s.quality = k;+ s.write(e);+ }+ }+ });});});}@@ -449,7 +507,7 @@ fn graph(ui: &mut Ui, view: &mut View, s: &mut Settings, rate: f32, id: egui::Idlet wheel = ui.input(|i| i.smooth_scroll_delta.y);if wheel != 0.0&& let Some(b) = hovered- && s.bands[b].kind.has_q()+ && s.bands[b].has_q(){let band = &mut s.bands[b];band.q = (band.q * (wheel * 0.004).exp()).clamp(0.1, 30.0);@@ -598,13 +656,16 @@ fn band_text(b: usize, band: &Band) -> String {if band.kind.has_gain() {parts.push(text(Unit::Db, band.gain_db, false));}- if band.kind.has_q() {+ if band.has_q() {parts.push(format!("Q {}", text(Unit::Plain, band.q, false)));}if band.kind.has_slope() {- parts.push(trf!("{} dB/oct", band.slope));+ parts.push(trf!("{} dB/oct", band.steepness()));}parts.push(route_name(band.route).to_string());+ if band.linear {+ parts.push(tr("Linear").to_string());+ }parts.join(" · ")}@@ -951,20 +1012,14 @@ fn band_controls(ui: &mut Ui, view: &mut View, s: &mut Settings, id: egui::Id) {}ui.add_space(8.0);ui.add_enabled_ui(band.kind.has_slope(), |ui| {+ let now = band.steepness();egui::ComboBox::from_id_salt(id.with(("slope", b))).width(96.0)- .selected_text(trf!(- "{} dB/oct",- if band.kind.has_slope() {- band.slope- } else {- 12- }- ))+ .selected_text(trf!("{} dB/oct", now)).show_ui(ui, |ui| {- for slope in [6u8, 12, 18, 24, 30, 36] {+ for &slope in band.kind.slopes() {if ui- .selectable_label(band.slope == slope, trf!("{} dB/oct", slope))+ .selectable_label(now == slope, trf!("{} dB/oct", slope)).clicked(){band.slope = slope;@@ -973,11 +1028,29 @@ fn band_controls(ui: &mut Ui, view: &mut View, s: &mut Settings, id: egui::Id) {}).response.on_hover_text(tr("Slope"))- .on_disabled_hover_text(tr(- "Only the passes have a slope to pick; the others' is 12 dB/oct.",- ));+ .on_disabled_hover_text(tr("This filter type comes in one slope only."));});});+ ui.horizontal(|ui| {+ ui.label(tr("Phase:"));+ ui.spacing_mut().item_spacing.x = 2.0;+ for (linear, name, tip) in [+ (+ false,+ trc("phase", "Minimum"),+ tr("Band uses a minimum phase model"),+ ),+ (true, tr("Linear"), tr("Band uses a linear phase model")),+ ] {+ if ui+ .selectable_label(band.linear == linear, name)+ .on_hover_text(tip)+ .clicked()+ {+ band.linear = linear;+ }+ }+ });ui.horizontal(|ui| {ui.label(tr("Channel Routing:"));ui.spacing_mut().item_spacing.x = 2.0;@@ -998,7 +1071,8 @@ fn band_controls(ui: &mut Ui, view: &mut View, s: &mut Settings, id: egui::Id) {ui.horizontal(|ui| {Knob::FREQUENCY.show(ui, &mut band.freq, true);Knob::GAIN.show(ui, &mut band.gain_db, band.kind.has_gain());- Knob::Q.show(ui, &mut band.q, band.kind.has_q());+ let has_q = band.has_q();+ Knob::Q.show(ui, &mut band.q, has_q);});});}@@ -1083,7 +1157,7 @@ enum Unit {/// A value as a knob writes it (`off`: under Mono Below's start, "Off").fn text(unit: Unit, v: f32, off: bool) -> String {- if off && v < eq::MONO_BELOW_OFF {+ if off && v <= eq::MONO_BELOW_OFF {return tr("Off").to_string();}let v = f64::from(v);@@ -1100,7 +1174,7 @@ fn text(unit: Unit, v: f32, off: bool) -> String {fn read(unit: Unit, typed: &str, off: bool) -> Option<f64> {let t = typed.trim().to_lowercase();if off && (t == "off" || t == tr("Off").to_lowercase()) {- return Some(0.0);+ return Some(f64::from(eq::MONO_BELOW_OFF));}let v = crate::fmt::parse(&t)?;Some(if unit == Unit::Hz && t.contains('k') {@@ -1122,7 +1196,7 @@ struct Knob {bipolar: bool,default: f32,unit: Unit,- /// Its start is "Off": the value 0 (Mono Below).+ /// Its start is "Off": its least value (Mono Below's 20 Hz).off: bool,}@@ -1173,19 +1247,19 @@ impl Knob {const MONO_BELOW: Knob = Knob {name: "Mono Below",min: eq::MONO_BELOW_OFF,- max: 1000.0,+ max: 200.0,log: true,bipolar: false,- default: 0.0,+ default: eq::MONO_BELOW_OFF,unit: Unit::Hz,off: true,};const WIDTH: Knob = Knob {name: "Stereo Width",min: 0.0,- max: 200.0,+ max: 100.0,log: false,- bipolar: true,+ bipolar: false,default: 100.0,unit: Unit::Percent,off: false,@@ -1203,7 +1277,7 @@ impl Knob {/// How far round (0 to 1) value `v` turns it.fn turn(&self, v: f32) -> f32 {- if self.off && v < eq::MONO_BELOW_OFF {+ if self.off && v <= self.min {return 0.0;}let t = if self.log {@@ -1224,7 +1298,7 @@ impl Knob {let mut t = t.clamp(0.0, 1.0);if self.off {if t < OFF_T {- return 0.0;+ return self.min;}t = (t - OFF_T) / (1.0 - OFF_T);}@@ -1403,12 +1477,13 @@ mod tests {assert!((k.turn(632.46) - 0.5).abs() < 1e-3);assert!((k.value(0.5) - 632.46).abs() < 0.1);let m = Knob::MONO_BELOW;- assert_eq!(m.turn(0.0), 0.0);- assert_eq!(m.value(0.02), 0.0);- assert!((m.value(1.0) - 1000.0).abs() < 1e-2);+ assert_eq!(m.turn(20.0), 0.0);+ assert_eq!(m.value(0.02), 20.0);+ assert!((m.value(1.0) - 200.0).abs() < 1e-2);assert!((m.value(m.turn(120.0)) - 120.0).abs() < 1e-2);+ assert_eq!(text(Unit::Hz, 20.0, true), tr("Off"));assert_eq!(read(Unit::Hz, "2,5 kHz", false), Some(2500.0));- assert_eq!(read(Unit::Hz, "off", true), Some(0.0));+ assert_eq!(read(Unit::Hz, "off", true), Some(20.0));assert_eq!(read(Unit::Db, "−6 dB", false), Some(-6.0));}}diff --git a/crates/ui-egui/src/multicam.rs b/crates/ui-egui/src/multicam.rsindex f2b060e..7545d1d 100644--- a/crates/ui-egui/src/multicam.rs+++ b/crates/ui-egui/src/multicam.rs@@ -99,13 +99,16 @@ pub(crate) fn tiles(p: &Project, clip: ClipId) -> Option<(Project, Vec<Tile>)> {e.rate = c.rate;e.looped = c.looped;e.hold_last = c.hold_last;- e.transform = Transform {+ }+ let _ = out.set_clip_framing(+ id,+ &Transform {scale,x: area.center().x - 0.5,y: area.center().y - 0.5,..Transform::default()- };- }+ },+ );}}// Only video tracks draw.diff --git a/crates/ui-egui/src/ofx.rs b/crates/ui-egui/src/ofx.rsindex d80fd32..b13fa41 100644--- a/crates/ui-egui/src/ofx.rs+++ b/crates/ui-egui/src/ofx.rs@@ -19,9 +19,10 @@ use bv_ofx::{ChangeReason, Context, Instance, Mark, ParamInfo, ParamType, PenAction, PluginInfo, Setup,Severity, Value, View,};+use bv_timeline::pancrop::Placement;use bv_timeline::{ClipId, Effect, Generator, KeyCurve, MediaId, MediaSource, PluginFx, PluginKey, PluginParam,- Project, Transform,+ Project,};use crate::app::BananaApp;@@ -593,27 +594,16 @@ pub fn frame_map(w: u32, h: u32) -> Affine {Affine::from_fn(|[x, y]| [x / w, (h - y) / h])}-/// An event's picture, `src` pixels (`par` times as wide as the frame's),-/// placed in a frame of `frame` pixels by `tf` — as the compositors place-/// it (`bv_render::layer::place_par`).-pub fn event_map(src: (u32, u32), par: f32, tf: &Transform, frame: (u32, u32)) -> Affine {+/// An event's picture, `src` pixels, placed by its Pan/Crop on a frame of+/// `frame` pixels — as the compositors place it (`bv_render::place_box`).+pub fn event_map(src: (u32, u32), place: &Placement, frame: (u32, u32)) -> Affine {let (sw, sh) = (src.0.max(1) as f64, src.1.max(1) as f64);let (w, h) = (frame.0.max(1) as f64, frame.1.max(1) as f64);- let fit = bv_timeline::scene::fit_rect_par(src.0.max(1), src.1.max(1), par, frame.0, frame.1);- let scale = tf.scale.max(1e-4) as f64;- let kx = fit.w as f64 * scale / sw;- let ky = fit.h as f64 * scale * tf.stretch.max(1e-3) as f64 / sh;- let fx = if tf.flip_h { -1.0 } else { 1.0 };- let fy = if tf.flip_v { -1.0 } else { 1.0 };- let (sin, cos) = (-(tf.rotation_deg as f64).to_radians()).sin_cos();- let (cx, cy) = (w / 2.0 + tf.x as f64 * w, h / 2.0 - tf.y as f64 * h);+ let (mx, my) = (place.media[0] / sw, place.media[1] / sh);Affine::from_fn(|[x, y]| {- // Down from the top, from the picture's middle, framed.- let rx = (x - sw / 2.0) * kx * fx;- let ry = (sh - y - sh / 2.0) * ky * fy;- let dx = rx * cos + ry * sin;- let dy = -rx * sin + ry * cos;- [(dx + cx) / w, (dy + cy) / h]+ // Down from the top, in the media's pixels.+ let at = place.on_frame_point([x * mx, (sh - y) * my]);+ [at[0] / w, at[1] / h]})}@@ -624,9 +614,12 @@ fn clip_map(p: &Project, clip: &bv_timeline::Clip, t: Tick) -> Affine {let Some(v) = p.media(clip.media).and_then(|m| m.video) else {return frame_map(s.width, s.height);};- let par = v.pixel_aspect.ratio() / s.pixel_aspect.ratio();let at = t.clamp(clip.start, clip.end());- event_map((v.width, v.height), par, &clip.transform_at(at), frame)+ let Some(place) = p.clip_place_in(clip.id) else {+ return frame_map(s.width, s.height);+ };+ let placed = place.at(clip, at, [f64::from(s.width), f64::from(s.height)]);+ event_map((v.width, v.height), &placed, frame)}/// A parameter's value now, from the effect or its plug-in's default.@@ -3638,6 +3631,7 @@ mod tests {#[test]fn canonical_points_land_where_the_compositor_draws_them() {+ use bv_timeline::pancrop::{self, PlaceIn};// A 1920×1080 frame shown whole: the middle is the middle, y up.let near =|a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9;@@ -3645,11 +3639,21 @@ mod tests {assert!(near(m.apply([960.0, 540.0]), [0.5, 0.5]));assert!(near(m.apply([0.0, 0.0]), [0.0, 1.0]));// A 640×480 picture in it (pillarboxed), moved right a tenth.- let tf = Transform {+ let tf = bv_timeline::Transform {x: 0.1,- ..Transform::default()+ ..bv_timeline::Transform::default()};- let m = event_map((640, 480), 1.0, &tf, (1920, 1080));+ let in_frame = PlaceIn {+ media: [640.0, 480.0],+ media_aspect: 1.0,+ frame: [1920.0, 1080.0],+ frame_aspect: 1.0,+ keep_aspect: true,+ fill: true,+ adjust: 1.0,+ };+ let place = pancrop::place(&pancrop::key_from_transform(&tf, &in_frame), &in_frame);+ let m = event_map((640, 480), &place, (1920, 1080));let mid = m.apply([320.0, 240.0]);// (The transform holds f32s: 0.1 is a little more.)assert!(@@ -3669,6 +3673,7 @@ mod tests {#[test]fn the_map_follows_the_compositor_through_pan_crop() {+ use bv_timeline::pancrop::{self, PlaceIn};// A spot in a 64×36 picture, placed turned, moved, smaller and// mirrored: the compositor draws it where the map says.let (sw, sh) = (64u32, 36u32);@@ -3678,16 +3683,26 @@ mod tests {*src.pixel_mut(x, y) = [1.0; 4];}}- let tf = Transform {+ let tf = bv_timeline::Transform {x: 0.1,y: -0.05,scale: 0.8,rotation_deg: 30.0,flip_h: true,- ..Transform::default()+ ..bv_timeline::Transform::default()};let (w, h) = (192u32, 108u32);- let out = bv_render::place_par(&src, w, h, &tf, bv_timeline::RenderQuality::Best, 1.0);+ let in_frame = PlaceIn {+ media: [f64::from(sw), f64::from(sh)],+ media_aspect: 1.0,+ frame: [f64::from(w), f64::from(h)],+ frame_aspect: 1.0,+ keep_aspect: true,+ fill: true,+ adjust: 1.0,+ };+ let place = pancrop::place(&pancrop::key_from_transform(&tf, &in_frame), &in_frame);+ let out = bv_render::place_box(&src, w, h, &place, bv_timeline::RenderQuality::Best);let (mut sx, mut sy, mut n) = (0.0, 0.0, 0.0);for y in 0..h {for x in 0..w {@@ -3701,7 +3716,7 @@ mod tests {let (cx, cy) = (sx / n, sy / n);// The spot's middle, (40.5, 10.5) down from the top, in canonical// coordinates.- let m = event_map((sw, sh), 1.0, &tf, (w, h));+ let m = event_map((sw, sh), &place, (w, h));let [nx, ny] = m.apply([40.5, sh as f64 - 10.5]);let (px, py) = (nx * w as f64, ny * h as f64);assert!(diff --git a/crates/ui-egui/src/pancrop.rs b/crates/ui-egui/src/pancrop.rsindex 111599d..fc62853 100644--- a/crates/ui-egui/src/pancrop.rs+++ b/crates/ui-egui/src/pancrop.rs@@ -1,14 +1,8 @@-//! Conversão entre o enquadramento do renderer ([`Transform`]: onde a mídia-//! fica no quadro) e a janela de visão do Pan/Crop (o "F": que parte da-//! mídia aparece), em pixels da mídia.-//!-//! O renderer leva um ponto `p` da mídia ao quadro por-//! `P = C + T + R(θ)·K·F·(p − S)`, com `S` o centro da mídia, `C` o centro do-//! quadro, `T` o deslocamento, `K` a escala (encaixe × zoom × esticar), `F`-//! os espelhamentos e `R(θ)` a rotação. A janela de visão é a imagem inversa-//! do quadro inteiro: o retângulo da mídia que cai dentro dele.+//! A box of the Pan/Crop and Track Motion workspaces as they draw and drag+//! it: its middle, its size and its angle, in numbers the screen's geometry+//! works with.-use bv_timeline::Transform;+use bv_timeline::pancrop::PanCropKey;#[derive(Clone, Copy, Debug, PartialEq)]pub struct Viewport {@@ -22,101 +16,47 @@ pub struct Viewport {pub angle_deg: f32,}-fn fit(src: (f32, f32), out: (f32, f32)) -> f32 {- (out.0 / src.0).min(out.1 / src.1)-}-pub(crate) fn rot(v: (f32, f32), deg: f32) -> (f32, f32) {let (s, c) = deg.to_radians().sin_cos();(v.0 * c - v.1 * s, v.0 * s + v.1 * c)}-/// The box the framing shows: what the frame shows, as much of it as the-/// box's size says (`Transform::box_size`).-pub fn viewport_of(tf: &Transform, src: (f32, f32), out: (f32, f32)) -> Viewport {- let f = fit(src, out);- let kx = f * tf.scale.max(1e-4);- let ky = kx * tf.stretch.max(1e-4);- let t = (tf.x * out.0, -tf.y * out.1);- let back = rot(t, -tf.rotation_deg);- let (fx, fy) = (- if tf.flip_h { -1.0 } else { 1.0 },- if tf.flip_v { -1.0 } else { 1.0 },- );- Viewport {- cx: src.0 / 2.0 - fx * back.0 / kx,- cy: src.1 / 2.0 - fy * back.1 / ky,- w: out.0 / kx * tf.box_size[0].max(1e-4),- h: out.1 / ky * tf.box_size[1].max(1e-4),- angle_deg: -tf.rotation_deg,- }-}--/// The framing that shows box `vp` as `base`'s Source settings say, as-/// VEGAS's: its picture filling the frame — stretched to it, or keeping-/// its proportions with what is around the box filling the rest — or,-/// not filling it, a pixel of the media a pixel of the frame. The crops,-/// flips and the box's settings come from `base`.-pub fn transform_for(- vp: &Viewport,- base: &Transform,- src: (f32, f32),- out: (f32, f32),-) -> Transform {- let f = fit(src, out);- let (w, h) = (vp.w.max(1e-3), vp.h.max(1e-3));- let (kx, ky) = if !base.fill_frame {- (1.0, 1.0)- } else if base.keeps_aspect() {- let k = (out.0 / w).min(out.1 / h);- (k, k)- } else {- (out.0 / w, out.1 / h)- };- let theta = -vp.angle_deg;- let (fx, fy) = (- if base.flip_h { -1.0 } else { 1.0 },- if base.flip_v { -1.0 } else { 1.0 },- );- let d = (- fx * kx * (vp.cx - src.0 / 2.0),- fy * ky * (vp.cy - src.1 / 2.0),- );- let r = rot(d, theta);- Transform {- x: -r.0 / out.0,- y: r.1 / out.1,- scale: kx / f,- stretch: ky / kx,- rotation_deg: theta,- box_size: [w * kx / out.0, h * ky / out.1],- ..*base+impl Viewport {+ /// A Pan/Crop's box (its mirrors aside: its size counts from them).+ pub fn of(key: &PanCropKey) -> Viewport {+ Viewport {+ cx: key.center[0] as f32,+ cy: key.center[1] as f32,+ w: key.width.abs() as f32,+ h: key.height.abs() as f32,+ angle_deg: key.angle.to_degrees() as f32,+ }}-}--/// Where the box turns (Rotation › X Center and Y Center), in the media's-/// pixels.-pub fn pivot_point(vp: &Viewport, pivot: [f32; 2]) -> (f32, f32) {- let d = rot((pivot[0] * vp.w, pivot[1] * vp.h), vp.angle_deg);- (vp.cx + d.0, vp.cy + d.1)-}-/// The pivot at `at` (the media's pixels), as `Transform::pivot` keeps it.-pub fn pivot_of(vp: &Viewport, at: (f32, f32)) -> [f32; 2] {- let l = rot((at.0 - vp.cx, at.1 - vp.cy), -vp.angle_deg);- [l.0 / vp.w.max(1e-3), l.1 / vp.h.max(1e-3)]-}--/// The box turned to `angle_deg` about its pivot: its middle goes round-/// it, the pivot stays where it is.-pub fn turned(vp: &Viewport, pivot: [f32; 2], angle_deg: f32) -> Viewport {- let p = pivot_point(vp, pivot);- let d = rot((vp.cx - p.0, vp.cy - p.1), angle_deg - vp.angle_deg);- Viewport {- cx: p.0 + d.0,- cy: p.1 + d.1,- angle_deg,- ..*vp+ /// `key` with what makes this box differ from `was`: its size, with the+ /// mirrors it has, its middle, its pivot following when it was there,+ /// its angle. What did not change stays exactly as it was.+ pub fn onto(&self, was: &Viewport, key: &PanCropKey) -> PanCropKey {+ let mut k = *key;+ if self.w != was.w {+ k.width = f64::from(self.w).copysign(key.width);+ }+ if self.h != was.h {+ k.height = f64::from(self.h).copysign(key.height);+ }+ if self.cx != was.cx {+ k.center[0] = f64::from(self.cx);+ }+ if self.cy != was.cy {+ k.center[1] = f64::from(self.cy);+ }+ if self.angle_deg != was.angle_deg {+ k.angle = f64::from(self.angle_deg).to_radians();+ }+ if key.pivot == key.center {+ k.pivot = k.center;+ }+ k}}@@ -124,165 +64,51 @@ pub fn turned(vp: &Viewport, pivot: [f32; 2], angle_deg: f32) -> Viewport {mod tests {use super::*;- fn close(a: &Transform, b: &Transform) -> bool {- let e = |x: f32, y: f32| (x - y).abs() < 1e-3;- e(a.x, b.x)- && e(a.y, b.y)- && e(a.scale, b.scale)- && e(a.stretch, b.stretch)- && e(a.rotation_deg, b.rotation_deg)- && a.flip_h == b.flip_h- && a.flip_v == b.flip_v- }+ const MEDIA: [f64; 2] = [1280.0, 720.0];#[test]- fn padrao_mostra_a_midia_inteira() {- // Mídia 1280×720 num projeto 1920×1080: o F é a mídia toda.- let vp = viewport_of(&Transform::default(), (1280.0, 720.0), (1920.0, 1080.0));- assert!((vp.w - 1280.0).abs() < 1e-3 && (vp.h - 720.0).abs() < 1e-3);- assert!((vp.cx - 640.0).abs() < 1e-3 && (vp.cy - 360.0).abs() < 1e-3);- }-- #[test]- fn zoom_de_2x_encolhe_o_f() {- let tf = Transform {- scale: 2.0,- ..Transform::default()- };- let vp = viewport_of(&tf, (1280.0, 720.0), (1280.0, 720.0));- assert!((vp.w - 640.0).abs() < 1e-3);+ fn the_whole_media_is_its_box() {+ let v = Viewport::of(&PanCropKey::whole(MEDIA));+ assert_eq!((v.w, v.h), (1280.0, 720.0));+ assert_eq!((v.cx, v.cy), (640.0, 360.0));+ assert_eq!(v.angle_deg, 0.0);}#[test]- fn ida_e_volta() {- let cases = [- Transform::default(),- Transform {- x: 0.2,- y: -0.1,- scale: 1.7,- rotation_deg: 30.0,- ..Transform::default()- },- Transform {- x: -0.3,- y: 0.25,- scale: 0.6,- rotation_deg: -75.0,- flip_h: true,- stretch: 1.4,- ..Transform::default()- },- Transform {- x: 0.05,- scale: 3.0,- rotation_deg: 180.0,- flip_v: true,- ..Transform::default()- },- ];- for tf in cases {- for (src, out) in [- ((1280.0, 720.0), (1920.0, 1080.0)),- ((640.0, 480.0), (1920.0, 1080.0)),- ] {- let vp = viewport_of(&tf, src, out);- let back = transform_for(&vp, &tf, src, out);- assert!(close(&tf, &back), "{tf:?}\n{back:?}");- }- }- }-- fn same_box(a: &Viewport, b: &Viewport) -> bool {- let e = |x: f32, y: f32| (x - y).abs() < 1e-2;- e(a.cx, b.cx) && e(a.cy, b.cy) && e(a.w, b.w) && e(a.h, b.h) && e(a.angle_deg, b.angle_deg)- }-- /// Source › Maintain aspect ratio, as VEGAS's: a box narrower than the- /// frame keeps its picture's proportions (the frame shows more than the- /// box); off, the picture stretches to fill it. Either way the box comes- /// back as it was.- #[test]- fn a_box_of_another_shape_keeps_its_picture_s_proportions() {- let (src, out) = ((1920.0, 1080.0), (1920.0, 1080.0));- let mut vp = viewport_of(&Transform::default(), src, out);- vp.w *= 0.5;- let kept = transform_for(&vp, &Transform::default(), src, out);- assert!((kept.stretch - 1.0).abs() < 1e-4, "{kept:?}");- assert!((kept.box_size[0] - 0.5).abs() < 1e-4 && (kept.box_size[1] - 1.0).abs() < 1e-4);- assert!(same_box(&viewport_of(&kept, src, out), &vp));- let stretched = Transform {- keep_aspect: Some(false),- ..Transform::default()- };- let tf = transform_for(&vp, &stretched, src, out);- assert!((tf.stretch - 0.5).abs() < 1e-4, "{tf:?}");- assert_eq!(tf.box_size, [1.0; 2]);- assert!(same_box(&viewport_of(&tf, src, out), &vp));- // Projects from before the setting: stretched ones stay stretched.- let old = Transform {- stretch: 1.4,- ..Transform::default()- };- assert!(!old.keeps_aspect() && Transform::default().keeps_aspect());- }-- /// Source › Stretch to fill frame off: a pixel of the media a pixel of- /// the frame, whatever the box's size.- #[test]- fn not_filling_the_frame_shows_the_media_at_its_own_size() {- let (src, out) = ((640.0, 480.0), (1920.0, 1080.0));- let base = Transform {- fill_frame: false,- ..Transform::default()- };- let vp = Viewport {- cx: 320.0,- cy: 240.0,- w: 640.0,- h: 480.0,- angle_deg: 0.0,+ fn mirrors_stay_out_of_its_size_and_come_back() {+ let k = PanCropKey {+ width: -640.0,+ ..PanCropKey::whole(MEDIA)};- let tf = transform_for(&vp, &base, src, out);- // The fit is 2.25: a scale of 1 ⁄ 2.25 is the media's own size.- assert!((tf.scale - 1.0 / 2.25).abs() < 1e-4, "{tf:?}");- assert!(same_box(&viewport_of(&tf, src, out), &vp));+ let v = Viewport::of(&k);+ assert_eq!(v.w, 640.0);+ let mut w = v;+ w.w = 320.0;+ assert_eq!(w.onto(&v, &k).width, -320.0);}- /// Rotation's X and Y Center: the box turns about them, and they stay- /// where they are.#[test]- fn the_box_turns_about_its_pivot() {- let vp = Viewport {- cx: 960.0,- cy: 540.0,- w: 1920.0,- h: 1080.0,- angle_deg: 0.0,+ fn only_what_changed_changes() {+ let k = PanCropKey {+ center: [100.123_456_789, 200.0],+ pivot: [7.0, 8.0],+ ..PanCropKey::whole(MEDIA)};- let pivot = pivot_of(&vp, (0.0, 0.0));- assert!((pivot[0] + 0.5).abs() < 1e-4 && (pivot[1] + 0.5).abs() < 1e-4);- let t = turned(&vp, pivot, 90.0);- let p = pivot_point(&t, pivot);- assert!(p.0.abs() < 1e-2 && p.1.abs() < 1e-2, "{p:?}");- assert!((t.angle_deg - 90.0).abs() < 1e-4);- // Its middle went round the corner.- assert!(- (t.cx - (-540.0)).abs() < 1e-2 && (t.cy - 960.0).abs() < 1e-2,- "{t:?}"- );- // About its middle, it stays put.- let m = turned(&vp, [0.0; 2], 30.0);- assert!((m.cx - 960.0).abs() < 1e-3 && (m.cy - 540.0).abs() < 1e-3);+ let v = Viewport::of(&k);+ assert_eq!(v.onto(&v, &k), k);+ let mut w = v;+ w.cy = 210.0;+ let moved = w.onto(&v, &k);+ assert_eq!(moved.center, [100.123_456_789, 210.0]);+ assert_eq!(moved.pivot, [7.0, 8.0]);}#[test]- fn mover_o_f_para_a_direita_desloca_a_imagem_para_a_esquerda() {- let src = (1000.0, 1000.0);- let out = (1000.0, 1000.0);- let mut vp = viewport_of(&Transform::default(), src, out);- vp.cx += 100.0;- let tf = transform_for(&vp, &Transform::default(), src, out);- assert!((tf.x + 0.1).abs() < 1e-4, "{tf:?}");+ fn a_pivot_in_the_middle_follows_it() {+ let k = PanCropKey::whole(MEDIA);+ let v = Viewport::of(&k);+ let mut w = v;+ w.cx = 700.0;+ assert_eq!(w.onto(&v, &k).pivot, [700.0, 360.0]);}}diff --git a/crates/ui-egui/src/pancrop_keys.rs b/crates/ui-egui/src/pancrop_keys.rsindex e2f71a9..24ad5ee 100644--- a/crates/ui-egui/src/pancrop_keys.rs+++ b/crates/ui-egui/src/pancrop_keys.rs@@ -16,7 +16,8 @@ use std::collections::BTreeSet;use bv_core::{FrameRate, Tick, timecode};use bv_timeline::mask::MaskKey;-use bv_timeline::{Clip, KeyCurve, TransformKey};+use bv_timeline::pancrop::PanCropKey;+use bv_timeline::{Clip, KeyCurve};use crate::egui::{self, Align, Align2, Color32, FontId, Layout, Pos2, Rect, RichText, Sense, Shape, Stroke, Ui,@@ -68,7 +69,7 @@ trait Timed: Clone {fn set_curve(&mut self, curve: KeyCurve);}-impl Timed for TransformKey {+impl Timed for PanCropKey {fn at(&self) -> Tick {self.at}@@ -96,7 +97,7 @@ impl Timed for MaskKey {/// event's start).#[derive(Clone, Debug, Default, PartialEq)]pub(crate) struct Keys {- pub position: Vec<TransformKey>,+ pub position: Vec<PanCropKey>,pub mask: Vec<MaskKey>,}@@ -104,7 +105,7 @@ pub(crate) struct Keys {/// first one taken, its value.#[derive(Clone, Debug)]pub(crate) enum Copied {- Position(TransformKey),+ Position(PanCropKey),Mask(MaskKey),}@@ -121,17 +122,21 @@ impl Keys {/// The event's keyframes. A row without any whose value is set (the/// framing; masks that have paths) shows that value as one at the/// start, VEGAS's first keyframe: it is made when edited.- pub(crate) fn of(clip: &Clip, curve: KeyCurve) -> Keys {- let position = if clip.transform_keys.is_empty() {- vec![TransformKey::new(Tick::ZERO, clip.transform, curve)]+ pub(crate) fn of(clip: &Clip, media: [f64; 2], curve: KeyCurve) -> Keys {+ let position = if clip.pan_crop.keys.is_empty() {+ vec![PanCropKey {+ curve,+ ..PanCropKey::whole(media)+ }]} else {- clip.transform_keys.clone()+ clip.pan_crop.keys.clone()};let mask = match &clip.mask {Some(m) if m.keys.is_empty() && !m.paths.is_empty() => vec![MaskKey {at: Tick::ZERO,shapes: m.paths.iter().map(|p| p.anchors.clone()).collect(),curve: KeyCurve::Smooth,+ looks: Vec::new(),}],Some(m) => m.keys.clone(),None => Vec::new(),@@ -254,7 +259,7 @@ impl Keys {match c {Copied::Position(k) => {keys.position.retain(|x| x.at != t);- keys.position.push(TransformKey { at: t, ..*k });+ keys.position.push(PanCropKey { at: t, ..*k });}Copied::Mask(k) => {keys.mask.retain(|x| x.at != t);@@ -371,6 +376,9 @@ impl Default for KeyStrip {/// What the controller shows and edits this frame.pub(crate) struct StripCtx<'a> {pub clip: &'a Clip,+ /// Its media's size, and how wide its pixels are.+ pub media: [f64; 2],+ pub aspect: f64,pub rate: FrameRate,/// The needle, from the event's start.pub pos: Tick,@@ -453,7 +461,7 @@ impl KeyStrip {let rate = cx.rate;let dur = clip.duration.max(Tick(1));let last = (clip.duration - rate.frame_duration()).max(Tick::ZERO);- let keys = Keys::of(clip, cx.curve);+ let keys = Keys::of(clip, cx.media, cx.curve);// Keyframes picked that are gone (undone, say) are no longer.let all = keys.all();self.picked.retain(|k| all.contains(k));@@ -1042,7 +1050,7 @@ impl KeyStrip {can_make && !has,tr("Create Keyframe at Cursor"),) {- answer.keys = Some((made_at(&keys, clip, row, pos), None));+ answer.keys = Some((made_at(&keys, clip, (cx.media, cx.aspect), row, pos), None));}if button(&mut bar,@@ -1101,7 +1109,7 @@ impl KeyStrip {match a {MenuAction::Copy | MenuAction::CopyKeys | MenuAction::Cut | MenuAction::CutKeys => {self.clipboard = if picked.is_empty() && matches!(a, MenuAction::CopyKeys) {- value_at(keys, cx.clip, cx.row, cx.pos)+ value_at(keys, cx.clip, (cx.media, cx.aspect), cx.row, cx.pos)} else {keys.copied(&picked)};@@ -1300,7 +1308,13 @@ enum MenuAction {/// `row`'s value at `pos` as one keyframe copied (Ctrl+C with nothing/// picked: the framing or the masks' shapes there).-fn value_at(keys: &Keys, clip: &Clip, row: KeyRow, pos: Tick) -> Vec<(Tick, Copied)> {+fn value_at(+ keys: &Keys,+ clip: &Clip,+ (media, aspect): ([f64; 2], f64),+ row: KeyRow,+ pos: Tick,+) -> Vec<(Tick, Copied)> {let curve = |times: Vec<(Tick, KeyCurve)>| {times.into_iter()@@ -1311,11 +1325,11 @@ fn value_at(keys: &Keys, clip: &Clip, row: KeyRow, pos: Tick) -> Vec<(Tick, Copimatch row {KeyRow::Position => vec![(Tick::ZERO,- Copied::Position(TransformKey::new(- Tick::ZERO,- clip.transform_at(clip.start + pos),- curve(keys.times(row)),- )),+ Copied::Position(PanCropKey {+ at: Tick::ZERO,+ curve: curve(keys.times(row)),+ ..clip.box_at(clip.start + pos, media, aspect)+ }),)],KeyRow::Mask => clip.mask@@ -1327,6 +1341,7 @@ fn value_at(keys: &Keys, clip: &Clip, row: KeyRow, pos: Tick) -> Vec<(Tick, Copiat: Tick::ZERO,shapes: m.shapes_at(pos),curve: curve(keys.times(row)),+ looks: Vec::new(),}),)]})@@ -1336,29 +1351,23 @@ fn value_at(keys: &Keys, clip: &Clip, row: KeyRow, pos: Tick) -> Vec<(Tick, Copi/// The rows with a keyframe made in `row` at `pos`, holding its value/// there (the curve of the one before).-fn made_at(keys: &Keys, clip: &Clip, row: KeyRow, pos: Tick) -> Keys {- let made = value_at(keys, clip, row, pos);+fn made_at(keys: &Keys, clip: &Clip, media: ([f64; 2], f64), row: KeyRow, pos: Tick) -> Keys {+ let made = value_at(keys, clip, media, row, pos);keys.pasted(&made, pos, clip.duration).0}#[cfg(test)]mod tests {use super::*;- use bv_timeline::Transform;fn keys(times: &[i64]) -> Keys {Keys {position: times.iter()- .map(|&t| {- TransformKey::new(- Tick(t),- Transform {- x: t as f32,- ..Transform::default()- },- KeyCurve::Linear,- )+ .map(|&t| PanCropKey {+ at: Tick(t),+ center: [t as f64, 0.0],+ ..PanCropKey::whole([640.0, 360.0])}).collect(),mask: Vec::new(),@@ -1382,7 +1391,7 @@ mod tests {assert_eq!(times(&moved), [20, 30]);assert_eq!(went, pick(&[20, 30]));// The one at 20 was the first's: x 0 now.- assert_eq!(moved.position[0].value.x, 0.0);+ assert_eq!(moved.position[0].center[0], 0.0);let (copied, _) = k.moved(&pick(&[10]), Tick(5), true);assert_eq!(times(&copied), [0, 10, 15, 20, 30]);}diff --git a/crates/ui-egui/src/pancrop_mask.rs b/crates/ui-egui/src/pancrop_mask.rsindex 6d87f5a..14394a4 100644--- a/crates/ui-egui/src/pancrop_mask.rs+++ b/crates/ui-egui/src/pancrop_mask.rs@@ -43,14 +43,14 @@ enum MaskDrag {/// The picked path moved (all of its anchors).Path {path: usize,- from: (f32, f32),+ from: (f64, f64),shapes: Vec<Vec<MaskAnchor>>,},/// The anchors picked moved together, `grabbed` (the one under the/// pointer) snapping.Anchors {grabbed: AnchorRef,- from: (f32, f32),+ from: (f64, f64),shapes: Vec<Vec<MaskAnchor>>,},/// An anchor's tangent's end: the one after it, or before; `alone`,@@ -66,28 +66,28 @@ enum MaskDrag {/// the box), from where the drag began.Rotate {path: usize,- center: (f32, f32),- from: (f32, f32),+ center: (f64, f64),+ from: (f64, f64),shapes: Vec<Vec<MaskAnchor>>,},/// The picked path scaled about the corner of its box opposite the/// one dragged.Scale {path: usize,- fixed: (f32, f32),- corner: (f32, f32),+ fixed: (f64, f64),+ corner: (f64, f64),shapes: Vec<Vec<MaskAnchor>>,},/// A rectangle or an oval being drawn from where the drag began.- Shape { tool: MaskTool, from: (f32, f32) },+ Shape { tool: MaskTool, from: (f64, f64) },/// The picked path's segment from its anchor `segment` bent from the/// point `t` of the way along it: that point follows the pointer, the/// anchors' tangents round it (curved anchors stay curved).Bend {path: usize,segment: usize,- t: f32,- from: (f32, f32),+ t: f64,+ from: (f64, f64),shapes: Vec<Vec<MaskAnchor>>,},/// A rectangle picking the anchors inside it, from `from` (the@@ -103,7 +103,7 @@ enum MaskDrag {/// keys held.struct Press {o: Pos2,- at: (f32, f32),+ at: (f64, f64),primary: bool,double: bool,mods: egui::Modifiers,@@ -288,7 +288,11 @@ impl MaskEditor {m.map_path_at(local, i, |p| [p[0] + to[0] - c[0], p[1] + to[1] - c[1]]);}}- let p = &mut m.paths[i];+ // As they are here: a keyframe may have its own.+ let units = bv_timeline::pancrop::local_units(local);+ let shown = m.paths_at_units(units).swap_remove(i);+ let mut edited = shown.clone();+ let p = &mut edited;section(ui, &mut self.sections[2], tr("Path"), |ui| {prop_grid(ui, "pcm-caminho", |ui| {let modes: Vec<(MaskMode, &str)> =@@ -332,6 +336,9 @@ impl MaskEditor {ui.end_row();});});+ if edited != shown {+ m.set_look_at(local, i, &edited);+ }(m != before).then_some(Some(m))}@@ -349,7 +356,7 @@ impl MaskEditor {sp: &Space,mask: Option<&PanCropMask>,local: Tick,- grid: Option<[f32; 2]>,+ grid: Option<[f64; 2]>,interactive: bool,) -> Option<Option<PanCropMask>> {let mut m = editable(mask);@@ -358,7 +365,7 @@ impl MaskEditor {self.forget_gone(&shapes);let pointer = ui.input(|i| i.pointer.interact_pos());let mods = ui.input(|i| i.modifiers);- let snap = |p: (f32, f32)| match grid {+ let snap = |p: (f64, f64)| match grid {Some([gx, gy]) if gx > 0.0 && gy > 0.0 => {((p.0 / gx).round() * gx, (p.1 / gy).round() * gy)}@@ -380,7 +387,7 @@ impl MaskEditor {if let Some(o) = press {let h = Press {o,- at: sp.media(o),+ at: sp.media64(o),primary,double: interactive && resp.double_clicked(),mods,@@ -417,7 +424,7 @@ impl MaskEditor {&& resp.dragged()&& let (Some(d), Some(p)) = (self.drag.clone(), pointer){- let at = sp.media(p);+ let at = sp.media64(p);match d {MaskDrag::Path {path,@@ -491,14 +498,14 @@ impl MaskEditor {mut shapes,} => {// Shift: in steps of 15°.- let angle = |q: (f32, f32)| (q.1 - center.1).atan2(q.0 - center.0);+ let angle = |q: (f64, f64)| (q.1 - center.1).atan2(q.0 - center.0);let mut a = angle(at) - angle(from);if mods.shift {- let step = 15f32.to_radians();+ let step = 15f64.to_radians();a = (a / step).round() * step;}let (s, c) = a.sin_cos();- let turn = |v: [f32; 2]| [v[0] * c - v[1] * s, v[0] * s + v[1] * c];+ let turn = |v: [f64; 2]| [v[0] * c - v[1] * s, v[0] * s + v[1] * c];for x in &mut shapes[path] {let r = turn([x.at[0] - center.0, x.at[1] - center.1]);x.at = [center.0 + r[0], center.1 + r[1]];@@ -513,7 +520,7 @@ impl MaskEditor {corner,mut shapes,} => {- let span = |a: f32, b: f32| if (b - a).abs() < 1e-3 { 1e-3 } else { b - a };+ let span = |a: f64, b: f64| if (b - a).abs() < 1e-3 { 1e-3 } else { b - a };let mut sx = (at.0 - fixed.0) / span(fixed.0, corner.0);let mut sy = (at.1 - fixed.1) / span(fixed.1, corner.1);if mods.shift {@@ -554,7 +561,7 @@ impl MaskEditor {let mut picked = base;for (i, s) in shapes.iter().enumerate() {for (k, a) in s.iter().enumerate() {- if r.contains(sp.screen((a.at[0], a.at[1]))) {+ if r.contains(sp.screen64((a.at[0], a.at[1]))) {picked.insert((i, k));}}@@ -573,7 +580,7 @@ impl MaskEditor {}if resp.drag_stopped() {if let (Some(MaskDrag::Shape { tool, from }), Some(p)) = (self.drag.take(), pointer) {- let path = drawn_shape(tool, from, snap(sp.media(p)), mods);+ let path = drawn_shape(tool, from, snap(sp.media64(p)), mods);if path.bounds().is_some_and(|(lo, hi)| hi[0] - lo[0] >= 2.0 && hi[1] - lo[1] >= 2.0)@@ -633,7 +640,7 @@ impl MaskEditor {_ if self.corner_at(sp, &shapes, p).is_some() => CursorIcon::ResizeNwSe,MaskTool::SplitTangent if on_line() => CursorIcon::Cell,MaskTool::Normal if on_line() => CursorIcon::Grab,- _ if path_at(&shapes, sp.media(p)).is_some() => CursorIcon::Move,+ _ if path_at(&shapes, sp.media64(p)).is_some() => CursorIcon::Move,_ => CursorIcon::Default,};if icon == CursorIcon::None {@@ -654,7 +661,9 @@ impl MaskEditor {&& let Some(i) = self.selected&& let Some(edit) = self.path_bar(ui, sp, &m, local, i){- let p = &mut m.paths[i];+ // As it is here: a keyframe may have its own.+ let units = bv_timeline::pancrop::local_units(local);+ let mut p = m.paths_at_units(units).swap_remove(i);match edit {PathEdit::Mode(mode) => p.mode = mode,// A second click on the feather in use: none.@@ -666,6 +675,7 @@ impl MaskEditor {}}}+ m.set_look_at(local, i, &p);}(m != before).then(|| (!m.paths.is_empty() || m.enabled).then_some(m))}@@ -866,7 +876,7 @@ impl MaskEditor {shapes: &[Vec<MaskAnchor>],m: &mut PanCropMask,local: Tick,- corner: (f32, f32),+ corner: (f64, f64),) {let corner = MaskAnchor::corner([corner.0, corner.1]);if let Some(d) = self.drawing@@ -928,7 +938,7 @@ impl MaskEditor {local: Tick,path: usize,segment: usize,- t: f32,+ t: f64,primary: bool,) {m.split_segment(path, segment, t);@@ -1024,7 +1034,7 @@ impl MaskEditor {let near = |path: usize| {shapes[path].iter()- .position(|a| sp.screen((a.at[0], a.at[1])).distance(p) <= GRAB)+ .position(|a| sp.screen64((a.at[0], a.at[1])).distance(p) <= GRAB).map(|i| (path, i))};if let Some(found) = self.selected.and_then(near) {@@ -1047,7 +1057,7 @@ impl MaskEditor {.into_iter().find(|(_, t)| {*t != [0.0; 2]- && sp.screen((a.at[0] + t[0], a.at[1] + t[1])).distance(p) <= GRAB+ && sp.screen64((a.at[0] + t[0], a.at[1] + t[1])).distance(p) <= GRAB}).map(|(after, _)| (after, path, i))})@@ -1061,7 +1071,7 @@ impl MaskEditor {sp: &Space,shapes: &[Vec<MaskAnchor>],p: Pos2,- ) -> Option<(usize, usize, f32)> {+ ) -> Option<(usize, usize, f64)> {let on = |path: usize| {let open = self.drawing == Some(path);segment_hit(sp, &shapes[path], p, open).map(|(s, t)| (path, s, t))@@ -1074,12 +1084,12 @@ impl MaskEditor {/// The picked path's rotation handle under `p`, while its box shows:/// its box's middle (in the media), what it turns about.- fn rotate_at(&self, sp: &Space, shapes: &[Vec<MaskAnchor>], p: Pos2) -> Option<(f32, f32)> {+ fn rotate_at(&self, sp: &Space, shapes: &[Vec<MaskAnchor>], p: Pos2) -> Option<(f64, f64)> {if !self.boxed {return None;}let (lo, hi) = mask::bounds(shapes.get(self.selected?)?)?;- let b = Rect::from_min_max(sp.screen((lo[0], lo[1])), sp.screen((hi[0], hi[1])));+ let b = Rect::from_min_max(sp.screen64((lo[0], lo[1])), sp.screen64((hi[0], hi[1])));let knob = pos2(b.center().x, b.top()) - vec2(0.0, ROTATE_ARM);(knob.distance(p) <= GRAB).then_some(((lo[0] + hi[0]) / 2.0, (lo[1] + hi[1]) / 2.0))}@@ -1091,7 +1101,7 @@ impl MaskEditor {sp: &Space,shapes: &[Vec<MaskAnchor>],p: Pos2,- ) -> Option<((f32, f32), (f32, f32))> {+ ) -> Option<((f64, f64), (f64, f64))> {if !self.boxed {return None;}@@ -1102,7 +1112,7 @@ impl MaskEditor {((hi[0], hi[1]), (lo[0], lo[1])),((lo[0], hi[1]), (hi[0], lo[1])),] {- if sp.screen(c).distance(p) <= GRAB {+ if sp.screen64(c).distance(p) <= GRAB {return Some((o, c));}}@@ -1114,7 +1124,7 @@ impl MaskEditor {shapes[d].len() >= 3&& shapes[d].first()- .is_some_and(|a| sp.screen((a.at[0], a.at[1])).distance(p) <= GRAB)+ .is_some_and(|a| sp.screen64((a.at[0], a.at[1])).distance(p) <= GRAB)}/// The workspace's menu in the Mask row. Its tangents' items work on@@ -1196,6 +1206,7 @@ impl MaskEditor {before: [-t[0], -t[1]],after: t,split: false,+ even: true,}});}@@ -1242,7 +1253,12 @@ impl MaskEditor {) {let media = Rect::from_min_max(sp.screen((0.0, 0.0)), sp.screen(sp.src));if m.active() {- let tex = self.shade(ui.ctx(), m, local, sp.src);+ let tex = self.shade(+ ui.ctx(),+ m,+ local,+ (f64::from(sp.src.0), f64::from(sp.src.1)),+ );painter.image(tex,media,@@ -1260,7 +1276,7 @@ impl MaskEditor {// (In: inside it, Out: outside, Both: half each way).if path.feather != MaskFeather::None && path.feather_pct > 0.0 && s.len() >= 2 {let short = sp.src.0.min(sp.src.1) as f64;- let d = path.feather_pct as f64 / 100.0 * short;+ let d = path.feather_pct / 100.0 * short;let poly = mask::polygon(s);let reach: &[f64] = match path.feather {MaskFeather::In => &[-d],@@ -1270,7 +1286,7 @@ impl MaskEditor {for &k in reach {let mut pts: Vec<Pos2> = mask::offset_polygon(&poly, k).into_iter()- .map(|q| sp.screen((q[0] as f32, q[1] as f32)))+ .map(|q| sp.screen64((q[0], q[1]))).collect();if let Some(&first) = pts.first() {pts.push(first);@@ -1288,7 +1304,8 @@ impl MaskEditor {&& self.boxed&& let Some((lo, hi)) = mask::bounds(s){- let b = Rect::from_min_max(sp.screen((lo[0], lo[1])), sp.screen((hi[0], hi[1])));+ let b =+ Rect::from_min_max(sp.screen64((lo[0], lo[1])), sp.screen64((hi[0], hi[1])));// The rotation handle above the box.let top = pos2(b.center().x, b.top());let knob = top - vec2(0.0, ROTATE_ARM);@@ -1324,17 +1341,17 @@ impl MaskEditor {if !self.anchors.contains(&(i, k)) {continue;}- let c = sp.screen((a.at[0], a.at[1]));+ let c = sp.screen64((a.at[0], a.at[1]));for t in [a.before, a.after] {if t != [0.0; 2] {- let e = sp.screen((a.at[0] + t[0], a.at[1] + t[1]));+ let e = sp.screen64((a.at[0] + t[0], a.at[1] + t[1]));painter.line_segment([c, e], Stroke::new(1.0, yellow));painter.circle(e, 3.5, Color32::WHITE, Stroke::new(1.0, Color32::BLACK));}}}for (k, a) in s.iter().enumerate() {- let c = sp.screen((a.at[0], a.at[1]));+ let c = sp.screen64((a.at[0], a.at[1]));let r = Rect::from_center_size(c, vec2(6.0, 6.0));let (fill, edge) = if self.anchors.contains(&(i, k)) {(crate::theme::banana(), Color32::WHITE)@@ -1372,9 +1389,11 @@ impl MaskEditor {local: Tick,i: usize,) -> Option<PathEdit> {- let (lo, hi) = mask::bounds(m.shapes_at(local).get(i)?)?;- let path = m.paths.get(i)?;- let b = Rect::from_min_max(sp.screen((lo[0], lo[1])), sp.screen((hi[0], hi[1])));+ let units = bv_timeline::pancrop::local_units(local);+ let paths = m.paths_at_units(units);+ let path = paths.get(i)?;+ let (lo, hi) = mask::bounds(&path.anchors)?;+ let b = Rect::from_min_max(sp.screen64((lo[0], lo[1])), sp.screen64((hi[0], hi[1])));let bar = Rect::from_min_size(pos2(b.center().x - 82.0, b.bottom() + 10.0),vec2(164.0, 26.0),@@ -1418,7 +1437,7 @@ impl MaskEditor {ctx: &egui::Context,m: &PanCropMask,local: Tick,- src: (f32, f32),+ src: (f64, f64),) -> egui::TextureId {use std::hash::{Hash, Hasher};let mut h = std::collections::hash_map::DefaultHasher::new();@@ -1434,8 +1453,7 @@ impl MaskEditor {((src.0 * k).round() as usize).max(1),((src.1 * k).round() as usize).max(1),);- let short = src.0.min(src.1) as f64;- let keep = m.coverage(local, w, h, [k as f64, k as f64], short);+ let keep = m.coverage(bv_timeline::pancrop::local_units(local), w, h, [k, k], 1.0);let pixels: Vec<Color32> = keep.iter().map(|c| Color32::from_black_alpha(((1.0 - c.clamp(0.0, 1.0)) * 150.0) as u8))@@ -1471,7 +1489,7 @@ impl crate::app::BananaApp {.clip(id).and_then(|c| self.project().media(c.media)).and_then(|m| m.video)- .map(|v| (v.width as f32, v.height as f32));+ .map(|v| (f64::from(v.width), f64::from(v.height)));let Some((w, h)) = size else {return false;};@@ -1502,20 +1520,20 @@ impl crate::app::BananaApp {/// anchor it starts at and how far along it (0–1) its point nearest `p`/// is — found among samples, then narrowed down between the samples next/// to it. `open`: the path is being drawn, its closing segment not there.-fn segment_hit(sp: &Space, shape: &[MaskAnchor], p: Pos2, open: bool) -> Option<(usize, f32)> {+fn segment_hit(sp: &Space, shape: &[MaskAnchor], p: Pos2, open: bool) -> Option<(usize, f64)> {const SAMPLES: usize = 64;let n = shape.len();if n < 2 {return None;}- let dist = |i: usize, t: f32| {+ let dist = |i: usize, t: f64| {let q = mask::segment_point(shape, i, t);- sp.screen((q[0], q[1])).distance(p)+ sp.screen64((q[0], q[1])).distance(p)};- let mut best: Option<(usize, f32, f32)> = None;+ let mut best: Option<(usize, f64, f32)> = None;for i in 0..if open { n - 1 } else { n } {for k in 0..=SAMPLES {- let t = k as f32 / SAMPLES as f32;+ let t = k as f64 / SAMPLES as f64;let d = dist(i, t);if best.is_none_or(|(_, _, bd)| d < bd) {best = Some((i, t, d));@@ -1523,7 +1541,7 @@ fn segment_hit(sp: &Space, shape: &[MaskAnchor], p: Pos2, open: bool) -> Option<}}let (i, t, _) = best?;- let step = 1.0 / SAMPLES as f32;+ let step = 1.0 / SAMPLES as f64;let (mut lo, mut hi) = ((t - step).max(0.0), (t + step).min(1.0));for _ in 0..40 {let (a, b) = (lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0);@@ -1567,7 +1585,7 @@ fn toggle_corner(shape: &mut [MaskAnchor], i: usize) {/// stretched by how much each pulls that point (the cubic's own weights);/// at a curved anchor the tangent on the other side turns along, keeping/// its length, so the curve stays smooth there.-fn bend(shape: &mut [MaskAnchor], segment: usize, t: f32, by: [f32; 2]) {+fn bend(shape: &mut [MaskAnchor], segment: usize, t: f64, by: [f64; 2]) {let n = shape.len();if n < 2 {return;@@ -1580,7 +1598,7 @@ fn bend(shape: &mut [MaskAnchor], segment: usize, t: f32, by: [f32; 2]) {let (mut a, mut b) = (shape[segment], shape[j]);a.after = [a.after[0] + w1 * by[0], a.after[1] + w1 * by[1]];b.before = [b.before[0] + w2 * by[0], b.before[1] + w2 * by[1]];- let turn = |other: [f32; 2], this: [f32; 2]| {+ let turn = |other: [f64; 2], this: [f64; 2]| {let (l, tl) = (other[0].hypot(other[1]), this[0].hypot(this[1]));if l == 0.0 || tl == 0.0 {other@@ -1599,7 +1617,7 @@ fn bend(shape: &mut [MaskAnchor], segment: usize, t: f32, by: [f32; 2]) {}/// A move `d` (media pixels), held along its longer axis with Shift.-fn axis(d: (f32, f32), mods: egui::Modifiers) -> (f32, f32) {+fn axis(d: (f64, f64), mods: egui::Modifiers) -> (f64, f64) {match mods.shift {true if d.0.abs() > d.1.abs() => (d.0, 0.0),true => (0.0, d.1),@@ -1608,14 +1626,14 @@ fn axis(d: (f32, f32), mods: egui::Modifiers) -> (f32, f32) {}/// The topmost path whose inside has `p` (media pixels).-fn path_at(shapes: &[Vec<MaskAnchor>], p: (f32, f32)) -> Option<usize> {+fn path_at(shapes: &[Vec<MaskAnchor>], p: (f64, f64)) -> Option<usize> {(0..shapes.len()).rev().find(|&i| {let poly = mask::polygon(&shapes[i]);let n = poly.len();if n < 3 {return false;}- let (x, y) = (p.0 as f64, p.1 as f64);+ let (x, y) = p;let mut inside = false;for k in 0..n {let (a, b) = (poly[k], poly[(k + 1) % n]);@@ -1630,7 +1648,7 @@ fn path_at(shapes: &[Vec<MaskAnchor>], p: (f32, f32)) -> Option<usize> {/// The shape a Rectangle or Oval drag draws from `a` to `b` (media/// pixels): Shift a square or a circle, Ctrl from its middle, Alt a/// rectangle's corners rounded or half an oval.-fn drawn_shape(tool: MaskTool, a: (f32, f32), b: (f32, f32), mods: egui::Modifiers) -> MaskPath {+fn drawn_shape(tool: MaskTool, a: (f64, f64), b: (f64, f64), mods: egui::Modifiers) -> MaskPath {let (mut dx, mut dy) = (b.0 - a.0, b.1 - a.1);if mods.shift {let s = dx.abs().max(dy.abs());@@ -1657,7 +1675,7 @@ fn dashed(painter: &Painter, sp: &Space, anchors: &[MaskAnchor], dim: bool, open}let mut pts: Vec<Pos2> = mask::polygon(anchors).into_iter()- .map(|q| sp.screen((q[0] as f32, q[1] as f32)))+ .map(|q| sp.screen64((q[0], q[1]))).collect();if open {// Its last segment, back to the first anchor, not drawn yet: the@@ -1697,9 +1715,9 @@ mod tests {MaskAnchor::corner([120.0, 0.0]),];toggle_corner(&mut s, 1);- let third = 60f32.hypot(30.0) / 3.0;+ let third = 60f64.hypot(30.0) / 3.0;let near =- |a: [f32; 2], b: [f32; 2]| (a[0] - b[0]).abs() < 1e-3 && (a[1] - b[1]).abs() < 1e-3;+ |a: [f64; 2], b: [f64; 2]| (a[0] - b[0]).abs() < 1e-3 && (a[1] - b[1]).abs() < 1e-3;assert!(near(s[1].before, [-third, 0.0]) && near(s[1].after, [third, 0.0]),"{:?}",@@ -1720,6 +1738,7 @@ mod tests {before: [-10.0, 0.0],after: [10.0, 0.0],split: false,+ even: false,},MaskAnchor::corner([100.0, 0.0]),MaskAnchor::corner([50.0, 80.0]),diff --git a/crates/ui-egui/src/presets.rs b/crates/ui-egui/src/presets.rsindex 754a230..b4a9cf4 100644--- a/crates/ui-egui/src/presets.rs+++ b/crates/ui-egui/src/presets.rs@@ -94,30 +94,39 @@ fn looks_in_place(text: &str) -> String {/// The factory presets of BananaV's own plug-in `id`: their names (in/// the interface's language) and values.pub fn builtin_plugin(id: &str) -> Vec<(String, PluginValues)> {+ bv_engine::plugins::own_presets(id)+ .into_iter()+ .map(|p| (tr(p.name).to_string(), plugin_values(p.values)))+ .collect()+}++/// The values of the factory preset of `id` whose name (as the code has it,+/// not translated) passes `wanted`.+pub fn builtin_plugin_named(id: &str, wanted: impl Fn(&str) -> bool) -> Option<PluginValues> {+ bv_engine::plugins::own_presets(id)+ .into_iter()+ .find(|p| wanted(p.name))+ .map(|p| plugin_values(p.values))+}++fn plugin_values(values: Vec<(&'static str, bv_engine::plugins::PresetValue)>) -> PluginValues {use bv_engine::plugins::PresetValue;use bv_timeline::PluginValue;- bv_engine::plugins::own_presets(id)+ values.into_iter()- .map(|p| {- let values = p- .values- .into_iter()- .map(|(name, v)| {- let value = match v {- PresetValue::Num(n) => PluginValue::Num(n),- PresetValue::Curves(c) => PluginValue::Curves(c),- PresetValue::Text(t) => PluginValue::Text(looks_in_place(&t)),- };- (- name.to_string(),- PluginParam {- value,- keys: Vec::new(),- },- )- })- .collect();- (tr(p.name).to_string(), values)+ .map(|(name, v)| {+ let value = match v {+ PresetValue::Num(n) => PluginValue::Num(n),+ PresetValue::Curves(c) => PluginValue::Curves(c),+ PresetValue::Text(t) => PluginValue::Text(looks_in_place(&t)),+ };+ (+ name.to_string(),+ PluginParam {+ value,+ keys: Vec::new(),+ },+ )}).collect()}@@ -125,6 +134,13 @@ pub fn builtin_plugin(id: &str) -> Vec<(String, PluginValues)> {/// Predefinições de fábrica: (nome, pares índice→valor sobre o padrão).pub fn builtin(k: EffectKind) -> Vec<(&'static str, Vec<(usize, f32)>)> {use bv_timeline::fx::grade::*;+ // The audio effects that follow VEGAS's: their presets name every value.+ if let Some(list) = bv_timeline::audio_fx::presets(k) {+ return list+ .iter()+ .map(|(name, values)| (tr(name), values.iter().copied().enumerate().collect()))+ .collect();+ }match k {EffectKind::ColorGrade => vec![(tr("Warm"), vec![(TEMPERATURE, 0.35), (TINT, 0.05)]),@@ -212,30 +228,6 @@ pub fn builtin(k: EffectKind) -> Vec<(&'static str, Vec<(usize, f32)>)> {}}-/// A Modern Equalizer band's values in a factory preset: band `b` in use,-/// its type (`eq_type`), frequency, gain, Q, slope and routing-/// (`eq_route`).-fn eq_band(- b: usize,- kind: f32,- freq: f32,- gain: f32,- q: f32,- slope: f32,- route: f32,-) -> Vec<(usize, f32)> {- use bv_timeline::fx::modern_eq::*;- vec![- (at(b, USED), 1.0),- (at(b, TYPE), kind),- (at(b, FREQUENCY), freq),- (at(b, GAIN), gain),- (at(b, Q), q),- (at(b, SLOPE), slope),- (at(b, ROUTING), route),- ]-}-/// The Modern Equalizer's band types and routings, as its parameters/// count them.mod eq_type {@@ -243,6 +235,7 @@ mod eq_type {pub const LOW_PASS: f32 = 1.0;pub const LOW_SHELF: f32 = 2.0;pub const HIGH_SHELF: f32 = 3.0;+ pub const BAND_PASS: f32 = 4.0;pub const PEAK: f32 = 5.0;}mod eq_route {@@ -251,76 +244,645 @@ mod eq_route {pub const SIDE: f32 = 4.0;}-/// The Modern Equalizer's factory presets: the uses its Help gives (a-/// voice's rumble, a guitar's mids and highs, a resonance, mid/side drums)-/// and everyday ones.+/// One of the Modern Equalizer's factory presets: Global Scale (%), Mono+/// Below (Hz), Stereo Width (%), Output Gain (dB) and Oversampling's+/// choice; then its eight bands, each in use and on — type, slope (dB an+/// octave), frequency, gain, Q and routing.+fn eq_preset(globals: [f32; 5], bands: [(f32, f32, f32, f32, f32, f32); 8]) -> Vec<(usize, f32)> {+ use bv_timeline::fx::modern_eq::*;+ let mut v = vec![+ (GLOBAL_SCALE, globals[0]),+ (MONO_BELOW, globals[1]),+ (STEREO_WIDTH, globals[2]),+ (OUTPUT_GAIN, globals[3]),+ (OVERSAMPLING, globals[4]),+ ];+ for (b, (kind, slope, freq, gain, q, route)) in bands.into_iter().enumerate() {+ v.extend([+ (at(b, USED), 1.0),+ (at(b, ON), 1.0),+ (at(b, TYPE), kind),+ (at(b, SLOPE), slope),+ (at(b, FREQUENCY), freq),+ (at(b, GAIN), gain),+ (at(b, Q), q),+ (at(b, ROUTING), route),+ ]);+ }+ v+}++/// The Modern Equalizer's factory presets, VEGAS's: each sets all eight+/// bands.fn modern_eq() -> Vec<(&'static str, Vec<(usize, f32)>)> {- use bv_timeline::fx::modern_eq::{MONO_BELOW, STEREO_WIDTH};use eq_route::*;use eq_type::*;vec![(- tr("Rumble Remover"),- eq_band(0, HIGH_PASS, 80.0, 0.0, 1.0, 24.0, STEREO),+ tr("Flat"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (LOW_SHELF, 12.0, 100.0, 0.0, 0.714, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 505.779, -0.0691643, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 2000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 5000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 6000.0, 0.0, 0.707, STEREO),+ (HIGH_SHELF, 12.0, 9931.17, -0.0691643, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("2000 Hz Notch"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (LOW_SHELF, 12.0, 100.0, 0.0, 0.714, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 2000.0, -20.0, 10.0, STEREO),+ (PEAK, 12.0, 5000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 6000.0, 0.0, 0.707, STEREO),+ (HIGH_SHELF, 12.0, 10_000.0, 0.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("2000 Hz Resonance"),+ eq_preset(+ [100.0, 20.0, 100.0, -13.0, 1.0],+ [+ (LOW_SHELF, 12.0, 100.0, 0.0, 0.714066, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 2000.0, 20.0, 10.0, STEREO),+ (PEAK, 12.0, 2000.0, 20.0, 10.0, STEREO),+ (PEAK, 12.0, 5000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 6000.0, 0.0, 0.707, STEREO),+ (HIGH_SHELF, 12.0, 10_000.0, 0.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Bass Boost"),+ eq_preset(+ [100.0, 20.0, 100.0, -3.0, 1.0],+ [+ (PEAK, 12.0, 100.0, 10.0, 0.714066, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 2000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 5000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 6000.0, 0.0, 0.707, STEREO),+ (HIGH_SHELF, 12.0, 10_000.0, 0.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Loudness"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (LOW_SHELF, 12.0, 100.0, 6.0, 0.707, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 2000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 5000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 6000.0, 0.0, 0.707, STEREO),+ (HIGH_SHELF, 12.0, 16_000.0, 4.0, 0.5, STEREO),+ ],+ ),+ ),+ (+ tr("Low Cut Filter 100 Hz"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (HIGH_PASS, 12.0, 100.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 2000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 5000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 6000.0, 0.0, 0.707, STEREO),+ (HIGH_SHELF, 12.0, 10_000.0, 0.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Low Pass 500 Hz"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (LOW_SHELF, 12.0, 100.0, 0.0, 0.714066, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (LOW_PASS, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 2000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 5000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 6000.0, 0.0, 0.707, STEREO),+ (LOW_PASS, 12.0, 500.0, 0.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Mid Boost"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (LOW_SHELF, 12.0, 100.0, 0.0, 0.714066, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 6.0, 0.707, STEREO),+ (PEAK, 12.0, 2000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 5000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 6000.0, 0.0, 0.707, STEREO),+ (HIGH_SHELF, 12.0, 10_000.0, 0.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Phone"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (HIGH_PASS, 12.0, 790.0, 10.0, 0.714066, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 2000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 5000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 6000.0, 0.0, 0.707, STEREO),+ (LOW_PASS, 12.0, 3000.0, 0.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Sub Bass"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (PEAK, 12.0, 30.0, 10.0, 0.714066, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 2000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 5000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 6000.0, 0.0, 0.707, STEREO),+ (HIGH_SHELF, 12.0, 10_000.0, 0.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Treble Boost"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (LOW_SHELF, 12.0, 100.0, 0.0, 0.714066, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 2000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 5000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 6000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 16_000.0, 10.0, 0.5, STEREO),+ ],+ ),+ ),+ (+ tr("Bands: Bell Notch"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (PEAK, 12.0, 100.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 817.997, -12.0, 10.0, STEREO),+ (PEAK, 12.0, 2000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 4000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 817.997, -12.0, 10.0, STEREO),+ (PEAK, 12.0, 10_000.0, 0.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Bands: Wide Bell"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (PEAK, 12.0, 100.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 817.997, 2.0, 0.382329, STEREO),+ (PEAK, 12.0, 2000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 4000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 817.997, 2.0, 0.382329, STEREO),+ (PEAK, 12.0, 10_000.0, 0.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Bands: Band Pass 6 dB"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (PEAK, 12.0, 100.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (BAND_PASS, 6.0, 800.0, 0.0, 1.0, STEREO),+ (PEAK, 12.0, 2000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 4000.0, 0.0, 0.707, STEREO),+ (BAND_PASS, 6.0, 800.0, 0.0, 1.0, STEREO),+ (PEAK, 12.0, 10_000.0, 0.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Bands: Band Pass 12 dB"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (PEAK, 12.0, 100.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (BAND_PASS, 12.0, 800.0, 0.0, 1.0, STEREO),+ (PEAK, 12.0, 2000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 4000.0, 0.0, 0.707, STEREO),+ (BAND_PASS, 12.0, 800.0, 0.0, 1.0, STEREO),+ (PEAK, 12.0, 10_000.0, 0.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Bands: Band Pass 18 dB"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (PEAK, 12.0, 100.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (BAND_PASS, 18.0, 800.0, 0.0, 1.0, STEREO),+ (PEAK, 12.0, 2000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 4000.0, 0.0, 0.707, STEREO),+ (BAND_PASS, 18.0, 800.0, 0.0, 1.0, STEREO),+ (PEAK, 12.0, 10_000.0, 0.0, 0.707, STEREO),+ ],+ ),),(- tr("Voice Clarity"),- [- eq_band(0, HIGH_PASS, 90.0, 0.0, 1.0, 18.0, STEREO),- eq_band(1, PEAK, 250.0, -3.0, 1.2, 12.0, STEREO),- eq_band(2, PEAK, 3000.0, 3.0, 1.0, 12.0, STEREO),- eq_band(3, HIGH_SHELF, 10_000.0, 2.0, 1.0, 12.0, STEREO),- ]- .concat(),+ tr("Bands: High Pass 6 dB"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (HIGH_PASS, 6.0, 30.4626, 0.0, 0.767937, STEREO),+ (PEAK, 12.0, 104.28, 2.10131, 1.11575, STEREO),+ (LOW_SHELF, 12.0, 59.8715, -0.943626, 0.707, STEREO),+ (PEAK, 12.0, 300.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 400.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 600.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 800.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ ],+ ),),(- tr("Guitar: Mids Up, Highs Tamed"),- [- eq_band(0, PEAK, 800.0, 3.0, 0.8, 12.0, STEREO),- eq_band(1, PEAK, 3500.0, -3.0, 2.0, 12.0, STEREO),- eq_band(2, LOW_PASS, 14_000.0, 0.0, 1.0, 12.0, STEREO),- ]- .concat(),+ tr("Bands: High Pass 12 dB"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (HIGH_PASS, 12.0, 30.4626, 0.0, 0.767937, STEREO),+ (PEAK, 12.0, 104.28, 2.10131, 1.11575, STEREO),+ (LOW_SHELF, 12.0, 59.8715, -0.943626, 0.707, STEREO),+ (PEAK, 12.0, 300.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 400.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 600.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 800.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ ],+ ),),(- tr("Resonance Notch (1 kHz)"),- eq_band(0, PEAK, 1000.0, -12.0, 8.0, 12.0, STEREO),+ tr("Bands: High Pass 24 dB"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (HIGH_PASS, 24.0, 30.4626, 0.0, 0.767937, STEREO),+ (PEAK, 12.0, 104.28, 2.10131, 1.11575, STEREO),+ (LOW_SHELF, 12.0, 59.8715, -0.943626, 0.707, STEREO),+ (PEAK, 12.0, 300.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 400.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 600.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 800.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ ],+ ),),(- tr("Wide Drums, Centered Snare"),- [- eq_band(0, PEAK, 200.0, 2.0, 1.5, 12.0, MID),- eq_band(1, HIGH_SHELF, 6000.0, 3.0, 1.0, 12.0, SIDE),- vec![(MONO_BELOW, 120.0), (STEREO_WIDTH, 120.0)],- ]- .concat(),+ tr("Bands: High Pass 36 dB"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (HIGH_PASS, 36.0, 30.4626, 0.0, 0.767937, STEREO),+ (PEAK, 12.0, 104.28, 2.10131, 1.11575, STEREO),+ (LOW_SHELF, 12.0, 59.8715, -0.943626, 0.707, STEREO),+ (PEAK, 12.0, 300.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 400.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 600.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 800.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ ],+ ),),- (tr("Mono Bass (150 Hz)"), vec![(MONO_BELOW, 150.0)]),(- tr("Telephone"),- [- eq_band(0, HIGH_PASS, 400.0, 0.0, 1.0, 24.0, STEREO),- eq_band(1, LOW_PASS, 3400.0, 0.0, 1.0, 24.0, STEREO),- eq_band(2, PEAK, 1500.0, 4.0, 1.0, 12.0, STEREO),- ]- .concat(),+ tr("Bands: Low + High Pass 6 dB"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (HIGH_PASS, 6.0, 30.4626, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 100.0, 0.0, 0.707, STEREO),+ (LOW_SHELF, 12.0, 59.8715, -0.943626, 0.707, STEREO),+ (PEAK, 12.0, 300.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 400.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 600.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 800.0, 0.0, 0.707, STEREO),+ (LOW_PASS, 6.0, 18_000.0, -3.38905, 0.707, STEREO),+ ],+ ),),(- tr("Warmth"),- [- eq_band(0, LOW_SHELF, 150.0, 3.0, 1.0, 12.0, STEREO),- eq_band(1, PEAK, 3000.0, -1.5, 1.0, 12.0, STEREO),- ]- .concat(),+ tr("Bands: Low + High Pass 12 dB"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (HIGH_PASS, 12.0, 30.4626, 0.0, 0.767937, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 2000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 4000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 6000.0, 0.0, 0.707, STEREO),+ (LOW_PASS, 12.0, 18_000.0, 0.0, 0.707, STEREO),+ ],+ ),),(- tr("Air"),- eq_band(0, HIGH_SHELF, 12_000.0, 4.0, 1.0, 12.0, STEREO),+ tr("Bands: Low + High Pass 24 dB"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (HIGH_PASS, 24.0, 30.4626, 0.0, 0.767937, STEREO),+ (PEAK, 12.0, 100.0, 0.0, 0.707, STEREO),+ (LOW_SHELF, 12.0, 59.8715, -0.943626, 0.707, STEREO),+ (PEAK, 12.0, 300.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 400.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 600.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 800.0, 0.0, 0.707, STEREO),+ (LOW_PASS, 24.0, 18_000.0, -3.80403, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Bands: Low + High Pass 36 dB"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (HIGH_PASS, 36.0, 30.4626, 0.0, 0.767937, STEREO),+ (PEAK, 12.0, 100.0, 0.0, 0.707, STEREO),+ (LOW_SHELF, 12.0, 59.8715, -0.943626, 0.707, STEREO),+ (PEAK, 12.0, 300.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 400.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 600.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 800.0, 0.0, 0.707, STEREO),+ (LOW_PASS, 36.0, 18_000.0, -4.08069, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Bands: Low Pass 6 dB"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (LOW_SHELF, 12.0, 100.0, 0.0, 0.767937, STEREO),+ (PEAK, 12.0, 100.0, 0.0, 0.707, STEREO),+ (LOW_SHELF, 12.0, 59.8715, -0.943626, 0.707, STEREO),+ (PEAK, 12.0, 300.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 400.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 600.0, 0.0, 0.707, STEREO),+ (LOW_SHELF, 12.0, 817.997, -12.0, 10.0, STEREO),+ (LOW_PASS, 6.0, 17_800.0, -6.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Bands: Low Pass 12 dB"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (LOW_SHELF, 12.0, 100.0, 0.0, 0.767937, STEREO),+ (PEAK, 12.0, 100.0, 0.0, 0.707, STEREO),+ (LOW_SHELF, 12.0, 59.8715, -0.943626, 0.707, STEREO),+ (PEAK, 12.0, 300.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 400.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 600.0, 0.0, 0.707, STEREO),+ (LOW_SHELF, 12.0, 817.997, -12.0, 10.0, STEREO),+ (LOW_PASS, 12.0, 17_800.0, -6.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Bands: Low Pass 24 dB"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (LOW_SHELF, 12.0, 100.0, 0.0, 0.767937, STEREO),+ (PEAK, 12.0, 100.0, 0.0, 0.707, STEREO),+ (LOW_SHELF, 12.0, 59.8715, -0.943626, 0.707, STEREO),+ (PEAK, 12.0, 300.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 400.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 600.0, 0.0, 0.707, STEREO),+ (LOW_SHELF, 12.0, 817.997, -12.0, 10.0, STEREO),+ (LOW_PASS, 24.0, 17_800.0, -6.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Bands: Low Pass 36 dB"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (LOW_SHELF, 12.0, 100.0, 0.0, 0.767937, STEREO),+ (PEAK, 12.0, 100.0, 0.0, 0.707, STEREO),+ (LOW_SHELF, 12.0, 59.8715, -0.943626, 0.707, STEREO),+ (PEAK, 12.0, 300.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 400.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 600.0, 0.0, 0.707, STEREO),+ (LOW_SHELF, 12.0, 817.997, -12.0, 10.0, STEREO),+ (LOW_PASS, 36.0, 17_800.0, -6.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Bands: Low + High Shelf"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (LOW_SHELF, 12.0, 100.0, 0.0, 0.767937, STEREO),+ (PEAK, 12.0, 100.0, 0.0, 0.707, STEREO),+ (LOW_SHELF, 12.0, 59.8715, -0.943626, 0.707, STEREO),+ (PEAK, 12.0, 300.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 400.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 600.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 800.0, 0.0, 0.707, STEREO),+ (HIGH_SHELF, 12.0, 10_000.0, 0.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Drums"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (HIGH_PASS, 24.0, 28.8747, 0.0, 0.809353, STEREO),+ (LOW_SHELF, 12.0, 59.87, -0.900002, 0.707, STEREO),+ (PEAK, 12.0, 104.28, 2.10131, 1.11575, STEREO),+ (PEAK, 12.0, 726.891, 1.59078, 0.707, STEREO),+ (PEAK, 12.0, 2000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 4000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 5320.0, 2.6, 0.587, STEREO),+ (LOW_PASS, 24.0, 19_300.0, 0.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Master: Mid/Side"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (LOW_SHELF, 12.0, 31.0103, -5.48515, 0.544715, SIDE),+ (PEAK, 12.0, 87.5096, 0.613861, 1.16713, MID),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ (HIGH_SHELF, 12.0, 2030.0, 1.0, 0.65, MID),+ (PEAK, 12.0, 4000.0, 0.0, 0.707, STEREO),+ (HIGH_SHELF, 12.0, 7580.0, 2.4, 0.571, SIDE),+ (PEAK, 12.0, 10_000.0, 0.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Master: Mid/Side, Basic"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (LOW_SHELF, 12.0, 31.0103, -5.48515, 0.544715, SIDE),+ (PEAK, 12.0, 180.7, -0.700001, 1.066, MID),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ (HIGH_SHELF, 12.0, 2030.0, 1.0, 0.65, MID),+ (PEAK, 12.0, 4000.0, 0.0, 0.707, STEREO),+ (HIGH_SHELF, 12.0, 7580.0, 2.4, 0.571, SIDE),+ (PEAK, 12.0, 10_000.0, 0.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Master: Mid/Side Wide Radio Bass"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (PEAK, 12.0, 43.5764, 0.0, 0.707, SIDE),+ (PEAK, 12.0, 100.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 300.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 400.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 600.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 800.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1018.57, 0.0594063, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Master: Smiley Face"),+ eq_preset(+ [100.0, 78.0877, 100.0, 0.0, 1.0],+ [+ (PEAK, 12.0, 49.688, 1.05, 0.707, STEREO),+ (PEAK, 12.0, 251.149, -0.918591, 0.703296, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ (HIGH_SHELF, 12.0, 2750.0, 1.1, 0.511, STEREO),+ (PEAK, 12.0, 4000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 6000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 10_000.0, 0.0, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Master: Smooth Top End"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (PEAK, 12.0, 100.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 100.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 300.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 400.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 600.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 800.0, 0.0, 0.707, STEREO),+ (HIGH_SHELF, 12.0, 20_000.0, 1.4, 0.25, STEREO),+ ],+ ),+ ),+ (+ tr("Mix: Mid/Side More Clarity"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (PEAK, 12.0, 100.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 200.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ (HIGH_SHELF, 12.0, 1720.0, 1.0, 0.713, MID),+ (PEAK, 12.0, 600.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 800.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1018.57, 0.0594063, 0.707, STEREO),+ ],+ ),+ ),+ (+ tr("Vocal"),+ eq_preset(+ [100.0, 20.0, 100.0, 0.0, 1.0],+ [+ (HIGH_PASS, 12.0, 43.5106, 0.0, 0.707, STEREO),+ (LOW_SHELF, 12.0, 104.28, -1.93069, 0.711529, STEREO),+ (PEAK, 12.0, 500.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 1000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 2000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 4000.0, 0.0, 0.707, STEREO),+ (PEAK, 12.0, 5320.0, 1.1, 0.707, STEREO),+ (HIGH_SHELF, 12.0, 9300.0, 2.9, 0.534, STEREO),+ ],+ ),),]}/// Predefinições de fábrica do Pan/Crop.+/// The Pan/Crop's presets of a shape: their names and their widths over+/// their heights, on screen.+pub const PAN_CROP_SHAPES: [(&str, f64); 4] = [+ ("1:1 Square aspect ratio", 1.0),+ ("4:3 Standard TV aspect ratio", 4.0 / 3.0),+ ("16:9 Widescreen TV aspect ratio", 16.0 / 9.0),+ ("1.85:1 Academy aspect ratio", 1.85),+];+pub fn builtin_pan_crop() -> Vec<(&'static str, Transform)> {let d = Transform::default();vec![diff --git a/crates/ui-egui/src/recording.rs b/crates/ui-egui/src/recording.rsindex b262018..c30273f 100644--- a/crates/ui-egui/src/recording.rs+++ b/crates/ui-egui/src/recording.rs@@ -318,6 +318,7 @@ impl BananaApp {start: from,broadcast_wave,effects,+ tempo: self.project().settings.tempo,});}let bits = self.project().settings.bit_depth as u16;@@ -565,6 +566,7 @@ impl BananaApp {gain: t.level,pan: t.pan,active,+ tempo: p.settings.tempo,});}for b in p.input_busses.iter().filter(|b| b.to_master && !b.muted) {@@ -578,6 +580,7 @@ impl BananaApp {gain: 10f32.powf(b.gain_db / 20.0),pan: b.pan,active: true,+ tempo: p.settings.tempo,});}let db = |d: f32| 10f32.powf(d / 20.0);@@ -604,6 +607,7 @@ impl BananaApp {gain: volume * db(s.gain_db) * db(c.input_db) * db(c.channel.gain_db),pan: c.channel.pan,active: true,+ tempo: p.settings.tempo,});}}diff --git a/crates/ui-egui/src/tabs/color.rs b/crates/ui-egui/src/tabs/color.rsindex e91009b..fcfd07b 100644--- a/crates/ui-egui/src/tabs/color.rs+++ b/crates/ui-egui/src/tabs/color.rs@@ -32,7 +32,9 @@ use crate::egui::{use crate::fx_window::FxTarget;use crate::icons::Icon;use crate::theme;+use bv_core::curve::CurvePoint;use bv_engine::ColorGradingPicker as Picker;+use bv_engine::color_grading as cg;/// The Color Grading effect's identifier.pub(crate) const ID: &str = "org.bananav.ColorGrading";@@ -97,24 +99,49 @@ const GROUPS: [(&str, Section, &[&str]); 5] = [const ITEM_PARAMS: [&[&[&str]]; 5] = [&[&[- "cameraLut",- "cameraStrength",- "cameraTetrahedral",- "cameraOn",+ "lutEnable0",+ "lutFilename0",+ "lutInterpolation0",+ "lutGain0",+ ],+ &[+ "lutEnable1",+ "lutFilename1",+ "lutInterpolation1",+ "lutGain1",],- &["lookLut", "lookStrength", "lookTetrahedral", "lookOn"],],&[- &["lift", "liftY"],- &["gamma", "gammaY"],- &["gain", "gainY"],- &["offset", "offsetY"],+ &["liftR", "liftG", "liftB", "liftY"],+ &["gammaR", "gammaG", "gammaB", "gammaY"],+ &["gainR", "gainG", "gainB", "gainY"],+ &["offsetR", "offsetG", "offsetB", "offsetY"],],&[- &["shadows", "shadowsY"],- &["midtones", "midtonesY"],- &["highlights", "highlightsY"],- &["rlOffset", "rlOffsetY"],+ &[+ "logWheelShadowsR",+ "logWheelShadowsG",+ "logWheelShadowsB",+ "logWheelShadowsY",+ ],+ &[+ "logWheelMidtonesR",+ "logWheelMidtonesG",+ "logWheelMidtonesB",+ "logWheelMidtonesY",+ ],+ &[+ "logWheelHighlightsR",+ "logWheelHighlightsG",+ "logWheelHighlightsB",+ "logWheelHighlightsY",+ ],+ &[+ "logWheelOffsetR",+ "logWheelOffsetG",+ "logWheelOffsetB",+ "logWheelOffsetY",+ ],],&[UTILITIES[0].1,@@ -122,29 +149,38 @@ const ITEM_PARAMS: [&[&[&str]]; 5] = [UTILITIES[2].1,UTILITIES[3].1,],- &[&["curves"], &["hslCurves"]],+ &[+ &COLOR_CURVES,+ &[+ "curveHvH", "curveHvS", "curveHvL", "curveSvS", "curveSvL", "curveLvS",+ ],+ ],];/// The Utilities' blocks: their titles and parameters.const UTILITIES: [(&str, &[&str]); 4] = [("Levels",- &["inputBlack", "inputWhite", "outputMin", "outputMax"],+ &["inMinAdjust", "inMaxAdjust", "outMinAdjust", "outMaxAdjust"],),("Tone",&[- "brightness",- "contrast",- "contrastCenter",- "saturation",- "logExposure",+ "brightnessAdjust",+ "contrastAdjust",+ "contrastCtrAdjust",+ "saturationAdjust",+ "exposureLnAdjust",],),- ("White Balance", &["temperature", "tint"]),- ("HSL", &["hue", "hslSaturation", "luminance"]),+ ("White Balance", &["temperatureAdjust", "tintAdjust"]),+ ("HSL", &["hueAdjust", "satAdjust", "valAdjust"]),];+/// The Color Curves' texts, as the editor lists them: Brightness, Red,+/// Green, Blue.+const COLOR_CURVES: [&str; 4] = ["curveY", "curveR", "curveG", "curveB"];+/// The navigation's width and a row of it, as VEGAS's.const NAV_WIDTH: f32 = 186.0;const NAV_ROW: f32 = 26.0;@@ -155,19 +191,25 @@ const BOX: egui::Vec2 = vec2(48.0, 22.0);/// The RL Color Wheels' Threshold column.const THRESHOLD_WIDTH: f32 = 66.0;-/// The wheels' parameters (a color and a master Y), names and neutral-/// values: the Color Wheels, then the RL Color Wheels.-const WHEELS: [(&str, &str, &str, f64); 8] = [- ("lift", "liftY", "Lift", 0.0),- ("gamma", "gammaY", "Gamma", 1.0),- ("gain", "gainY", "Gain", 1.0),- ("offset", "offsetY", "Offset", 0.0),- ("shadows", "shadowsY", "Shadows", 0.0),- ("midtones", "midtonesY", "Midtones", 0.0),- ("highlights", "highlightsY", "Highlights", 0.0),- ("rlOffset", "rlOffsetY", "Offset", 0.0),+/// The wheels' parameters' stems (each its R, G, B, Y, U and V) and+/// names: the Color Wheels, then the RL Color Wheels.+const WHEELS: [(&str, &str); 8] = [+ ("lift", "Lift"),+ ("gamma", "Gamma"),+ ("gain", "Gain"),+ ("offset", "Offset"),+ ("logWheelShadows", "Shadows"),+ ("logWheelMidtones", "Midtones"),+ ("logWheelHighlights", "Highlights"),+ ("logWheelOffset", "Offset"),];+/// Wheel `i`'s range, as the panel's: its low and high ends, and where it+/// rests.+fn wheel_range(i: usize) -> (f64, f64, f64) {+ cg::WHEEL_RANGES.get(i).copied().unwrap_or(cg::RL_RANGE)+}+/// The HSL Curves, as the type menu lists them.const HSL_KINDS: [&str; 6] = ["Hue vs Hue",@@ -280,7 +322,7 @@ struct Cx {fn new_fx() -> PluginFx {PluginFx {id: ID.to_string(),- version: [1, 0],+ version: [2, 0],name: "Color Grading".to_string(),params: Default::default(),}@@ -302,11 +344,6 @@ impl Cx {self.value(name).num(0)}- fn rgb(&self, name: &str) -> [f64; 3] {- let v = self.value(name);- [v.num(0), v.num(1), v.num(2)]- }-fn text(&self, name: &str) -> String {self.value(name).text().to_string()}@@ -437,6 +474,15 @@ fn set(app: &mut BananaApp, cx: &Cx, values: &[(&str, Value)], key: egui::Id) {app.modify_merged(key, move |p| t.set_chain(p, chain));}+/// [`set`] with the parameters' names made as it runs.+fn set_named(app: &mut BananaApp, cx: &Cx, values: &[(String, Value)], key: egui::Id) {+ let values: Vec<(&str, Value)> = values+ .iter()+ .map(|(n, v)| (n.as_str(), v.clone()))+ .collect();+ set(app, cx, &values, key);+}+/// Changes the effect in the chain (bypass, reset); nothing when it is not/// there.fn change_effect(app: &mut BananaApp, cx: &Cx, f: impl FnOnce(&mut Effect)) {@@ -1009,8 +1055,102 @@ fn label_at(ui: &egui::Ui, at: Pos2, text: &str, align: Align2) {.text(at, align, text, FontId::proportional(12.5), theme::text());}+/// A number's box as VEGAS's: typed (a comma or a point) and kept to three+/// decimals within `(lo, hi)`, the mouse wheel over it adding a hundredth+/// a notch (Ctrl: a thousandth). Whether it changed `value`.+fn number_box(+ ui: &mut egui::Ui,+ rect: Rect,+ value: &mut f64,+ (lo, hi): (f64, f64),+ short: bool,+) -> bool {+ let mut v = *value;+ let field = if short {+ short_field(&mut v)+ } else {+ field(&mut v)+ };+ let resp = ui.put(rect, field.range(lo..=hi));+ let mut changed = resp.changed();+ if resp.hovered() {+ let (notches, ctrl) = ui.input(|i| crate::widgets::wheel_notches(&i.events));+ if notches != 0.0 {+ v += f64::from(notches) * if ctrl { 0.001 } else { 0.01 };+ ui.input_mut(|i| i.smooth_scroll_delta = egui::Vec2::ZERO);+ changed = true;+ }+ }+ if changed {+ *value = (v.clamp(lo, hi) * 1000.0).round() / 1000.0;+ }+ changed+}++/// A slider's handling, as VEGAS's sliders do it: the knob dragged (with+/// Ctrl a thirty-second as fast), a click beside it a tenth that way, a+/// double-click the default, the mouse wheel a hundredth a notch (Ctrl: a+/// thousandth). `along(p)`: how far along the slider a point is (0–1 from+/// its low end); `on_knob(p)`: whether the knob is there. Whether `value`+/// changed.+fn slide(+ ui: &egui::Ui,+ resp: &egui::Response,+ value: &mut f64,+ (lo, hi): (f64, f64),+ default: f64,+ along: impl Fn(Pos2) -> f64,+ on_knob: impl Fn(Pos2) -> bool,+) -> bool {+ let span = (hi - lo).max(1e-12);+ let before = *value;+ // The drag's value, not held within the ends: the knob comes back+ // with the pointer.+ let id = resp.id.with("slide");+ if resp.drag_started() {+ let grabbed = ui.input(|i| i.pointer.press_origin()).is_some_and(&on_knob);+ ui.data_mut(|d| d.insert_temp(id, grabbed.then_some(*value)));+ }+ if resp.dragged()+ && let Some(Some(mut v)) = ui.data(|d| d.get_temp::<Option<f64>>(id))+ && let Some(p) = resp.interact_pointer_pos()+ {+ let moved = along(p) - along(p - resp.drag_delta());+ let k = if ui.input(|i| i.modifiers.ctrl) {+ 1.0 / 32.0+ } else {+ 1.0+ };+ v += moved * span * k;+ ui.data_mut(|d| d.insert_temp(id, Some(v)));+ *value = v;+ }+ if resp.clicked()+ && let Some(p) = resp.interact_pointer_pos()+ && !on_knob(p)+ {+ *value += if lo + along(p) * span > *value {+ 0.1+ } else {+ -0.1+ };+ }+ if resp.double_clicked() {+ *value = default;+ }+ if resp.hovered() {+ let (notches, ctrl) = ui.input(|i| crate::widgets::wheel_notches(&i.events));+ if notches != 0.0 {+ *value += f64::from(notches) * if ctrl { 0.001 } else { 0.01 };+ ui.input_mut(|i| i.smooth_scroll_delta = egui::Vec2::ZERO);+ }+ }+ *value = value.clamp(lo, hi);+ *value != before+}+/// A slider across `rect` as VEGAS's: a groove — or a band through-/// `colors` — and a light knob; a double-click puts it at `default`.+/// `colors` — and a light knob, handled as [`slide`] says.fn h_slider(ui: &mut egui::Ui,rect: Rect,@@ -1023,21 +1163,25 @@ fn h_slider(let mut resp = ui.interact(rect, id, Sense::click_and_drag());let track = rect.shrink2(vec2(5.0, 0.0));let span = (hi - lo).max(1e-12);- if resp.dragged()- && let Some(p) = resp.interact_pointer_pos()- {- *value = lo + f64::from(((p.x - track.left()) / track.width()).clamp(0.0, 1.0)) * span;- resp.mark_changed();- }- if resp.double_clicked() {- *value = default;+ let y = rect.center().y;+ let knob = |v: f64| {+ let x = track.left() + ((v - lo) / span).clamp(0.0, 1.0) as f32 * track.width();+ Rect::from_center_size(pos2(x, y), vec2(9.0, 15.0))+ };+ let at = knob(*value);+ if slide(+ ui,+ &resp,+ value,+ (lo, hi),+ default,+ |p| f64::from((p.x - track.left()) / track.width()),+ |p| at.expand(2.0).contains(p),+ ) {resp.mark_changed();}- let y = rect.center().y;band(ui.painter(), track.x_range(), y, colors);- let x = track.left() + ((*value - lo) / span).clamp(0.0, 1.0) as f32 * track.width();- let knob = Rect::from_center_size(pos2(x, y), vec2(9.0, 15.0));- crate::widgets::paint_knob(ui.painter(), knob, resp.hovered() || resp.dragged());+ crate::widgets::paint_knob(ui.painter(), knob(*value), resp.hovered() || resp.dragged());resp}@@ -1094,18 +1238,28 @@ fn slider_row(cx.default_of(name).num(0),colors,);- let mut typed = v;- let typed_now = ui- .put(bx, short_field(&mut typed).range(min..=max))- .changed();- let value = if typed_now { typed } else { v };- if (value - cx.num(name)).abs() > 1e-12 {- set(app, cx, &[(name, Value::Num(vec![value]))], id);+ number_box(ui, bx, &mut v, (min, max), true);+ if (v - cx.num(name)).abs() > 1e-12 {+ set(app, cx, &[(name, Value::Num(vec![v]))], id);+ }+}++/// Which of two knobs (`knobs`: their places) the pointer at `p` takes:+/// the one under it, else the nearer (`near`: how far each is).+fn which_knob(p: Pos2, knobs: [Rect; 2], near: impl Fn(Rect) -> f32) -> usize {+ let on = knobs.map(|k| k.expand(2.0).contains(p));+ match on {+ [true, _] => 0,+ [false, true] => 1,+ _ => usize::from(near(knobs[1]) < near(knobs[0])),}}/// Levels' Input or Output row: the low end's box, a black-to-white band-/// with both ends' knobs (the nearer one dragged), the high end's box.+/// with both ends' knobs, the high end's box. Each end is handled as+/// VEGAS's sliders handle theirs ([`slide`]: the knob under the pointer,+/// or beside them the nearer, takes the drag, the click and the mouse+/// wheel); a double-click puts both at their defaults.#[allow(clippy::too_many_arguments)]fn range_row(ui: &mut egui::Ui,@@ -1127,29 +1281,43 @@ fn range_row(let (min, max) = cx.range(lo_p);let span = (max - min).max(1e-12);let (lo0, hi0) = (cx.num(lo_p), cx.num(hi_p));- let (mut lo, mut hi) = (lo0, hi0);+ let mut pair = [lo0, hi0];+ let defaults = [cx.default_of(lo_p).num(0), cx.default_of(hi_p).num(0)];let id = egui::Id::new(("cg-range", lo_p));let resp = ui.interact(rect, id, Sense::click_and_drag());let track = rect.shrink2(vec2(5.0, 0.0));let x_of = |v: f64| track.left() + ((v - min) / span).clamp(0.0, 1.0) as f32 * track.width();- let v_of =- |x: f32| min + f64::from(((x - track.left()) / track.width()).clamp(0.0, 1.0)) * span;- if resp.drag_started()- && let Some(p) = resp.interact_pointer_pos()- {- // The nearer knob follows the drag.- let high = (p.x - x_of(hi)).abs() < (p.x - x_of(lo)).abs();- ui.data_mut(|d| d.insert_temp(id, high));- }- if resp.dragged()- && let Some(p) = resp.interact_pointer_pos()- {- let v = v_of(p.x);- if ui.data(|d| d.get_temp::<bool>(id)).unwrap_or(false) {- hi = v.max(lo);- } else {- lo = v.min(hi);- }+ let knob = |v: f64| Rect::from_center_size(pos2(x_of(v), y), vec2(9.0, 15.0));+ // The end the pointer took, kept while it drags.+ let end = id.with("end");+ let k = if resp.dragged() && !resp.drag_started() {+ ui.data(|d| d.get_temp::<usize>(end)).unwrap_or(0)+ } else {+ let at = ui.input(|i| i.pointer.press_origin().or(i.pointer.hover_pos()));+ let k = at.map_or(0, |p| {+ which_knob(p, [knob(pair[0]), knob(pair[1])], |r| {+ (p.x - r.center().x).abs()+ })+ });+ ui.data_mut(|d| d.insert_temp(end, k));+ k+ };+ let grabbed = knob(pair[k]);+ slide(+ ui,+ &resp,+ &mut pair[k],+ (min, max),+ defaults[k],+ |p| f64::from((p.x - track.left()) / track.width()),+ |p| grabbed.expand(2.0).contains(p),+ );+ if resp.double_clicked() {+ pair = defaults;+ } else if k == 0 {+ pair[0] = pair[0].min(pair[1]);+ } else {+ pair[1] = pair[1].max(pair[0]);}band(ui.painter(),@@ -1157,27 +1325,12 @@ fn range_row(y,&[Color32::BLACK, Color32::WHITE],);- for v in [lo, hi] {- let knob = Rect::from_center_size(pos2(x_of(v), y), vec2(9.0, 15.0));- crate::widgets::paint_knob(ui.painter(), knob, resp.hovered() || resp.dragged());- }- let (mut lo_typed, mut hi_typed) = (lo, hi);- if ui- .put(lo_box, short_field(&mut lo_typed).range(min..=max))- .changed()- {- lo = lo_typed;- }- if ui- .put(hi_box, short_field(&mut hi_typed).range(min..=max))- .changed()- {- hi = hi_typed;- }- if resp.double_clicked() {- lo = cx.default_of(lo_p).num(0);- hi = cx.default_of(hi_p).num(0);+ for v in pair {+ crate::widgets::paint_knob(ui.painter(), knob(v), resp.hovered() || resp.dragged());}+ number_box(ui, lo_box, &mut pair[0], (min, max), true);+ number_box(ui, hi_box, &mut pair[1], (min, max), true);+ let [lo, hi] = pair;if (lo - lo0).abs() > 1e-12 || (hi - hi0).abs() > 1e-12 {set(app,@@ -1224,64 +1377,67 @@ fn lut_entries(camera: bool) -> Vec<(String, String, bool)> {/// row; its table in a box — its picture, its name, the arrows to the one/// before or after; a click lists them —; its Strength.fn lut_column(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, k: usize, rect: Rect) {- let (title, prefix, camera) = [- (tr("Camera LUT"), "camera", true),- (tr("Look LUT"), "look", false),- ][k];+ let (title, camera) = [(tr("Camera LUT"), true), (tr("Look LUT"), false)][k];let (file_p, strength_p, tetra_p, on_p) = (- format!("{prefix}Lut"),- format!("{prefix}Strength"),- format!("{prefix}Tetrahedral"),- format!("{prefix}On"),+ cg::LUT_FILE[k],+ cg::LUT_GAIN[k],+ cg::LUT_INTERPOLATION[k],+ cg::LUT_ENABLE[k],);+ // A table picked: its file, and the LUT on (as VEGAS's list does).+ let pick = |file: String| {+ let on = if file.is_empty() { 0.0 } else { 1.0 };+ [(file_p, Value::Text(file)), (on_p, Value::Num(vec![on]))]+ };let (mut bar, mut body) = column(ui, rect, title, false);if crate::widgets::icon_button(&mut bar, Icon::Folder, tr("Browse")).clicked()&& let Some(path) = rfd::FileDialog::new().add_filter(tr("Cube LUT"), &["cube"]).pick_file(){- let key = egui::Id::new(("cg-lut-file", prefix));- set(- app,- cx,- &[(&file_p, Value::Text(path.to_string_lossy().into_owned()))],- key,- );+ let key = egui::Id::new(("cg-lut-file", k));+ set(app, cx, &pick(path.to_string_lossy().into_owned()), key);}if reset_button(&mut bar) {- let key = egui::Id::new(("cg-lut-reset", prefix));- set(app, cx, &[(&file_p, Value::Text(String::new()))], key);+ let key = egui::Id::new(("cg-lut-reset", k));+ let values: Vec<(&str, Value)> = [file_p, on_p, tetra_p, strength_p]+ .into_iter()+ .map(|n| (n, cx.default_of(n)))+ .collect();+ set(app, cx, &values, key);}- let on = cx.num(&on_p) != 0.0;+ // Lit while a table is picked and left off.+ let on = cx.num(on_p) != 0.0;+ let bypassed = !on && !cx.text(file_p).is_empty();if crate::widgets::icon_toggle(&mut bar,Icon::BypassFx,- !on,+ bypassed,tr("LUT Selection: apply or remove the LUT"),).clicked(){- let key = egui::Id::new(("cg-lut-on", prefix));+ let key = egui::Id::new(("cg-lut-on", k));set(app,cx,- &[(&on_p, Value::Num(vec![if on { 0.0 } else { 1.0 }]))],+ &[(on_p, Value::Num(vec![if on { 0.0 } else { 1.0 }]))],key,);}- let tetra = cx.num(&tetra_p) != 0.0;+ let tetra = cx.num(tetra_p) != 0.0;if crate::widgets::icon_toggle(&mut bar, Icon::Grid, tetra, tr("Tetrahedral Interpolation")).clicked(){- let key = egui::Id::new(("cg-lut-tetra", prefix));+ let key = egui::Id::new(("cg-lut-tetra", k));set(app,cx,- &[(&tetra_p, Value::Num(vec![if tetra { 0.0 } else { 1.0 }]))],+ &[(tetra_p, Value::Num(vec![if tetra { 0.0 } else { 1.0 }]))],key,);}- let file = cx.text(&file_p);+ let file = cx.text(file_p);let entries = lut_entries(camera);let at = entries.iter()@@ -1342,8 +1498,8 @@ fn lut_column(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, k: usize, rect: R(boxr.right() - 30.0 - thumb.right() - 12.0).max(10.0),);// The list, and the arrows to the entry before or after.- let pick = Rect::from_min_max(boxr.min, pos2(boxr.right() - 26.0, boxr.bottom()));- let list = body.interact(pick, egui::Id::new(("cg-lut-box", prefix)), Sense::click());+ let list_rect = Rect::from_min_max(boxr.min, pos2(boxr.right() - 26.0, boxr.bottom()));+ let list = body.interact(list_rect, egui::Id::new(("cg-lut-box", k)), Sense::click());let mut chosen: Option<String> = None;egui::Popup::menu(&list).show(|ui| {for (name, f, enabled) in &entries {@@ -1367,11 +1523,7 @@ fn lut_column(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, k: usize, rect: R(false, pos2(boxr.right() - 14.0, boxr.bottom() - 15.0)),] {let r = Rect::from_center_size(center, vec2(20.0, 22.0));- let b = body.interact(- r,- egui::Id::new(("cg-lut-step", prefix, up)),- Sense::click(),- );+ let b = body.interact(r, egui::Id::new(("cg-lut-step", k, up)), Sense::click());let c = if b.hovered() {theme::text_strong()} else {@@ -1401,8 +1553,8 @@ fn lut_column(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, k: usize, rect: Rif let Some(f) = chosen&& f != file{- let key = egui::Id::new(("cg-lut-pick", prefix));- set(app, cx, &[(&file_p, Value::Text(f))], key);+ let key = egui::Id::new(("cg-lut-pick", k));+ set(app, cx, &pick(f), key);}let row = Rect::from_min_max(pos2(rect.left(), boxr.bottom() + 3.0),@@ -1414,145 +1566,200 @@ fn lut_column(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, k: usize, rect: Rapp,cx,row,- &strength_p,+ strength_p,tr("Strength:"),label_w,&[],);}+/// The color a wheel's offsets from where it rests show: their hue, as+/// bright as it goes (none: a light grey).+fn offset_color(o: [f64; 3]) -> Color32 {+ let m = (o[0] + o[1] + o[2]) / 3.0;+ let c = o.map(|v| v - m);+ let s = c.iter().fold(0.0f64, |a, v| a.max(v.abs()));+ if s < 1e-9 {+ return Color32::from_gray(200);+ }+ let [r, g, b] = c.map(|v| ((0.5 + 0.5 * v / s).clamp(0.0, 1.0) * 255.0).round() as u8);+ Color32::from_rgb(r, g, b)+}++/// Wheel `stem`'s color `rgb` and point `dot`, as its parameters hold+/// them.+fn wheel_settings(stem: &str, rgb: [f64; 3], dot: [f64; 2]) -> Vec<(String, Value)> {+ let mut v: Vec<(String, Value)> = (0..3)+ .map(|k| {+ (+ cg::wheel_param(stem, cg::PARTS[k]),+ Value::Num(vec![rgb[k]]),+ )+ })+ .collect();+ v.push((cg::wheel_param(stem, "U"), Value::Num(vec![dot[0]])));+ v.push((cg::wheel_param(stem, "V"), Value::Num(vec![dot[1]])));+ v+}+/// A wheel's column, as VEGAS's: its title, its picker (Lift's black/// point, Gain's white point) and Reset; the wheel, beside it R, G and B-/// over the Y slider and Y. Or, shown as sliders, R, G, B and Y side by-/// side.+/// over the Y slider and Y — the boxes left out when the column is small,+/// as VEGAS's are. Or, shown as sliders, R, G, B and Y side by side. The+/// wheel's point gives its color as VEGAS's does+/// (`color_grading::wheel_values`); a color typed puts the point about+/// where it gives it.fn wheel_column(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, i: usize, rect: Rect) {- let (rgb, y, name, neutral) = WHEELS[i];+ let (stem, name) = WHEELS[i];+ let range = wheel_range(i);+ let (min, max, rest) = range;+ let param = |part: &str| cg::wheel_param(stem, part);let (mut bar, mut body) = column(ui, rect, tr(name), true);let picker = match i {0 => Some((Picker::BlackPoint, tr("Specify a Black Point"))),2 => Some((Picker::WhitePoint, tr("Specify a White Point"))),_ => None,};+ let key = egui::Id::new(("cg-wheel", i));if reset_button(&mut bar) {- let key = egui::Id::new(("cg-wheel-reset", i));- set(- app,- cx,- &[(rgb, cx.default_of(rgb)), (y, cx.default_of(y))],- key,- );+ // The color and Y at their defaults, the point in the middle.+ let all: Vec<(String, Value)> = cg::PARTS+ .iter()+ .map(|p| (param(p), cx.default_of(¶m(p))))+ .collect();+ set_named(app, cx, &all, key.with("reset"));}if let Some((picker, tip)) = picker {picker_button(&mut bar, app, cx, picker, tip);}- let values = cx.rgb(rgb);- let master = cx.num(y);- let (min, max) = cx.range(rgb);- let key = egui::Id::new(("cg-wheel", i));+ let rgb: [f64; 3] = std::array::from_fn(|k| cx.num(¶m(cg::PARTS[k])));+ let master = cx.num(¶m("Y"));+ let dot = [cx.num(¶m("U")), cx.num(¶m("V"))];+ // A color typed or slid: the point about where it gives it.+ let typed = |rgb: [f64; 3]| wheel_settings(stem, rgb, cg::wheel_point(rgb, range, i == 1));let inner = body.max_rect();if app.color_panel.sliders[i] {- body.add_space(6.0);- body.horizontal(|ui| {- ui.add_space(12.0);- let mut v = [values[0], values[1], values[2], master];- let mut changed = false;- let high = (inner.height() - 60.0).max(40.0);- for (k, label) in [tr("Red"), tr("Green"), tr("Blue"), "Y"]- .into_iter()- .enumerate()- {- ui.vertical(|ui| {- ui.spacing_mut().slider_width = high;- let r = ui.add(- egui::Slider::new(&mut v[k], min..=max)- .vertical()- .show_value(false),- );- if r.double_clicked() {- v[k] = neutral;- }- changed |= r.changed() || r.double_clicked();- changed |= ui- .add_sized(BOX, field(&mut v[k]).range(min..=max))- .changed();- ui.label(RichText::new(label).size(11.0));- });- }- if changed {- set(- app,- cx,- &[- (rgb, Value::Num(vec![v[0], v[1], v[2]])),- (y, Value::Num(vec![v[3]])),- ],- key,- );+ // R, G, B and Y side by side, each its slider over its box.+ let w = inner.width() / 4.0;+ let mut v = [rgb[0], rgb[1], rgb[2], master];+ let mut changed = [false; 4];+ for (k, label) in [tr("Red"), tr("Green"), tr("Blue"), "Y"]+ .into_iter()+ .enumerate()+ {+ let x = inner.left() + w * (k as f32 + 0.5);+ let label_y = inner.bottom() - 10.0;+ let bx = Rect::from_center_size(pos2(x, label_y - 16.0 - BOX.y / 2.0), BOX);+ let slider = Rect::from_min_max(+ pos2(x - 10.0, inner.top() + 8.0),+ pos2(x + 10.0, bx.top() - 8.0),+ );+ if slider.height() > 24.0 {+ let id = key.with(("slider", k));+ changed[k] |=+ y_slider(&mut body, slider, id, &mut v[k], (min, max), rest).changed();}- });+ changed[k] |= number_box(&mut body, bx, &mut v[k], (min, max), false);+ label_at(&body, pos2(x, label_y), label, Align2::CENTER_CENTER);+ }+ if changed[..3].contains(&true) {+ set_named(app, cx, &typed([v[0], v[1], v[2]]), key);+ }+ if changed[3] {+ set(+ app,+ cx,+ &[(¶m("Y"), Value::Num(vec![v[3]]))],+ key.with("y"),+ );+ }return;}- // R, G and B down the right, Y at the bottom, its slider between.- let fx = inner.right() - 4.0 - BOX.x;- let label_x = fx - 22.0;- let mut v = values;- let mut typed = false;- for (k, label) in ["R:", "G:", "B:"].into_iter().enumerate() {- let r = Rect::from_min_size(pos2(fx, inner.top() + 3.0 + k as f32 * 28.0), BOX);+ // The boxes go when the column is too small for them and a wheel, as+ // VEGAS's do.+ let boxes = rect.width() >= 190.0 && rect.height() >= 150.0;+ let mut m = master;+ let mut y_changed = false;+ let room_right = if boxes {+ // R, G and B down the right, Y at the bottom, its slider between.+ let fx = inner.right() - 4.0 - BOX.x;+ let label_x = fx - 22.0;+ let mut v = rgb;+ let mut typed_now = false;+ for (k, label) in ["R:", "G:", "B:"].into_iter().enumerate() {+ let r = Rect::from_min_size(pos2(fx, inner.top() + 3.0 + k as f32 * 28.0), BOX);+ label_at(+ &body,+ pos2(label_x, r.center().y),+ label,+ Align2::LEFT_CENTER,+ );+ typed_now |= number_box(&mut body, r, &mut v[k], (min, max), false);+ }+ if typed_now {+ set_named(app, cx, &typed(v), key);+ }+ let y_box = Rect::from_min_size(pos2(fx, inner.bottom() - 8.0 - BOX.y), BOX);label_at(&body,- pos2(label_x, r.center().y),- label,+ pos2(label_x, y_box.center().y),+ "Y:",Align2::LEFT_CENTER,);- typed |= body.put(r, field(&mut v[k]).range(min..=max)).changed();- }- if typed {- set(app, cx, &[(rgb, Value::Num(v.to_vec()))], key);- }- let y_box = Rect::from_min_size(pos2(fx, inner.bottom() - 8.0 - BOX.y), BOX);- label_at(- &body,- pos2(label_x, y_box.center().y),- "Y:",- Align2::LEFT_CENTER,- );- let mut m = master;- let mut changed = body.put(y_box, field(&mut m).range(min..=max)).changed();- let slider = Rect::from_min_max(- pos2(- fx + BOX.x / 2.0 - 10.0,- inner.top() + 3.0 + 2.0 * 28.0 + BOX.y + 14.0,- ),- pos2(fx + BOX.x / 2.0 + 10.0, y_box.top() - 6.0),- );- if slider.height() > 24.0 {- changed |= y_slider(- &mut body,- slider,+ y_changed |= number_box(&mut body, y_box, &mut m, (min, max), false);+ let slider = Rect::from_min_max(+ pos2(+ fx + BOX.x / 2.0 - 10.0,+ inner.top() + 3.0 + 2.0 * 28.0 + BOX.y + 14.0,+ ),+ pos2(fx + BOX.x / 2.0 + 10.0, y_box.top() - 6.0),+ );+ if slider.height() > 24.0 {+ let id = key.with("y");+ y_changed |= y_slider(&mut body, slider, id, &mut m, (min, max), rest).changed();+ }+ label_x - 18.0+ } else {+ // Only the Y slider, at the right.+ let slider = Rect::from_min_max(+ pos2(inner.right() - 24.0, inner.top() + 8.0),+ pos2(inner.right() - 4.0, inner.bottom() - 8.0),+ );+ if slider.height() > 24.0 {+ let id = key.with("y");+ y_changed |= y_slider(&mut body, slider, id, &mut m, (min, max), rest).changed();+ }+ slider.left() - 6.0+ };+ if y_changed && (m - master).abs() > 1e-12 {+ set(+ app,+ cx,+ &[(¶m("Y"), Value::Num(vec![m]))],key.with("y"),- &mut m,- (min, max),- neutral,- )- .changed();- }- if changed && (m - master).abs() > 1e-12 {- set(app, cx, &[(y, Value::Num(vec![m]))], key.with("y"));+ );}// The wheel, as big as the room left of the numbers lets it be.- let room = Rect::from_min_max(inner.min, pos2(label_x - 18.0, inner.max.y));+ let room = Rect::from_min_max(inner.min, pos2(room_right, inner.max.y));let d = (room.width() - 18.0).min(room.height() - 22.0).max(60.0);let wheel = Rect::from_center_size(room.center(), vec2(d, d));- let mut o = values.map(|v| (v - neutral) as f32);- if body- .put(wheel, |ui: &mut egui::Ui| {- crate::widgets::grading_wheel(ui, &mut o, d)- })- .changed()- {- let v = o.map(|x| f64::from(x) + neutral);- set(app, cx, &[(rgb, Value::Num(v.to_vec()))], key);+ let color_at =+ |p: [f64; 2]| offset_color(cg::wheel_values(p[0], p[1], range).map(|v| v - rest));+ let mut change = None;+ body.put(wheel, |ui: &mut egui::Ui| {+ let (resp, c) = crate::widgets::grading_wheel(ui, d, dot, &color_at);+ change = c;+ resp+ });+ match change {+ Some(crate::widgets::WheelChange::Moved(p)) => {+ let v = cg::wheel_values(p[0], p[1], range);+ set_named(app, cx, &wheel_settings(stem, v, p), key);+ }+ Some(crate::widgets::WheelChange::Reset) => {+ set_named(app, cx, &wheel_settings(stem, [rest; 3], [0.0; 2]), key);+ }+ None => {}}if let Some((picker, _)) = picker {// Over the wheel's corner, kept off the numbers.@@ -1567,8 +1774,8 @@ fn wheel_column(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, i: usize, rect:}}-/// A wheel's Y slider, as VEGAS's: lit from the bottom up to its knob, a-/// mark where it is neutral; a double-click puts it there.+/// A vertical slider as VEGAS's wheels' Y: lit from the bottom up to its+/// knob, a mark where it rests; handled as [`slide`] says.fn y_slider(ui: &mut egui::Ui,rect: Rect,@@ -1581,17 +1788,20 @@ fn y_slider(let track = rect.shrink2(vec2(0.0, 5.0));let span = (hi - lo).max(1e-12);let y_of = |v: f64| track.bottom() - ((v - lo) / span).clamp(0.0, 1.0) as f32 * track.height();- if resp.dragged()- && let Some(p) = resp.interact_pointer_pos()- {- *value = lo + f64::from(((track.bottom() - p.y) / track.height()).clamp(0.0, 1.0)) * span;- resp.mark_changed();- }- if resp.double_clicked() {- *value = neutral;+ let x = rect.center().x;+ let knob = |v: f64| Rect::from_center_size(pos2(x, y_of(v)), vec2(14.0, 9.0));+ let grabbed = knob(*value);+ if slide(+ ui,+ &resp,+ value,+ (lo, hi),+ neutral,+ |p| f64::from((track.bottom() - p.y) / track.height()),+ |p| grabbed.expand(2.0).contains(p),+ ) {resp.mark_changed();}- let x = rect.center().x;let at = y_of(*value);let painter = ui.painter();painter.line_segment(@@ -1607,7 +1817,7 @@ fn y_slider([pos2(x - 7.0, n), pos2(x + 7.0, n)],Stroke::new(1.0, theme::text_dim()),);- let knob = Rect::from_center_size(pos2(x, at), vec2(14.0, 9.0));+ let knob = knob(*value);painter.rect_filled(knob,2.0,@@ -1634,25 +1844,26 @@ fn threshold_column(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, rect: Rect)let small = vec2(40.0, BOX.y);let hi_box = Rect::from_min_size(pos2(rect.left() + 12.0, inner.top() + 3.0), small);let lo_box = Rect::from_min_size(pos2(rect.left() + 12.0, inner.bottom() - 57.0), small);- let (lo0, hi0) = (cx.num("lowerThreshold"), cx.num("upperThreshold"));- let (mut lo, mut hi) = (lo0, hi0);- body.put(hi_box, short_field(&mut hi).range(0.0..=1.0));- body.put(lo_box, short_field(&mut lo).range(0.0..=1.0));+ let names = [cg::LOW_THRESHOLD, cg::HIGH_THRESHOLD];+ let before = names.map(|n| cx.num(n));+ let mut pair = before;+ number_box(&mut body, hi_box, &mut pair[1], (0.0, 1.0), true);+ number_box(&mut body, lo_box, &mut pair[0], (0.0, 1.0), true);let slider = Rect::from_min_max(pos2(rect.left() + 12.0, hi_box.bottom() + 8.0),pos2(rect.left() + 52.0, lo_box.top() - 8.0),);if slider.height() > 30.0 {- thresholds(&mut body, slider, &mut lo, &mut hi);+ let defaults = names.map(|n| cx.default_of(n).num(0));+ thresholds(&mut body, slider, &mut pair, defaults);}- if (lo - lo0).abs() > 1e-12 || (hi - hi0).abs() > 1e-12 {- let lo = lo.min(hi);+ if pair != before {set(app,cx,&[- ("lowerThreshold", Value::Num(vec![lo])),- ("upperThreshold", Value::Num(vec![hi])),+ (names[0], Value::Num(vec![pair[0]])),+ (names[1], Value::Num(vec![pair[1]])),],egui::Id::new("cg-thresholds"),);@@ -1672,30 +1883,47 @@ fn threshold_column(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, rect: Rect)}}-/// The two thresholds on one vertical slider, as VEGAS's: the upper one's-/// knob on the left of the line, the lower one's on its right; each-/// dragged.-fn thresholds(ui: &mut egui::Ui, rect: Rect, lo: &mut f64, hi: &mut f64) -> bool {- let resp = ui.interact(- rect,- egui::Id::new("cg-threshold-slider"),- Sense::click_and_drag(),- );+/// The two thresholds (`pair`: the lower, the upper) on one vertical+/// slider, as VEGAS's: the upper one's knob on the left of the line, the+/// lower one's on its right; each handled as [`slide`] says (the knob+/// under the pointer, or the nearer, takes it), a double-click putting+/// both at `defaults`.+fn thresholds(ui: &mut egui::Ui, rect: Rect, pair: &mut [f64; 2], defaults: [f64; 2]) -> bool {+ let id = egui::Id::new("cg-threshold-slider");+ let resp = ui.interact(rect, id, Sense::click_and_drag());let track = rect.shrink2(vec2(0.0, 6.0));- let y_of = |v: f64| track.bottom() - v as f32 * track.height();+ let y_of = |v: f64| track.bottom() - v.clamp(0.0, 1.0) as f32 * track.height();let x = rect.center().x;- let mut changed = false;- if resp.dragged()- && let Some(p) = resp.interact_pointer_pos()- {- let v = f64::from(((track.bottom() - p.y) / track.height()).clamp(0.0, 1.0));- // The nearer knob follows.- if (v - *lo).abs() <= (v - *hi).abs() {- *lo = v.min(*hi);- } else {- *hi = v.max(*lo);- }- changed = true;+ let knob = |k: usize, v: f64| {+ let dx = if k == 1 { -7.0 } else { 7.0 };+ Rect::from_center_size(pos2(x + dx, y_of(v)), vec2(14.0, 9.0))+ };+ let before = *pair;+ let end = id.with("end");+ let k = if resp.dragged() && !resp.drag_started() {+ ui.data(|d| d.get_temp::<usize>(end)).unwrap_or(0)+ } else {+ let at = ui.input(|i| i.pointer.press_origin().or(i.pointer.hover_pos()));+ let k = at.map_or(0, |p| {+ which_knob(p, [knob(0, pair[0]), knob(1, pair[1])], |r| {+ (p.y - r.center().y).abs()+ })+ });+ ui.data_mut(|d| d.insert_temp(end, k));+ k+ };+ let grabbed = knob(k, pair[k]);+ slide(+ ui,+ &resp,+ &mut pair[k],+ (0.0, 1.0),+ defaults[k],+ |p| f64::from((track.bottom() - p.y) / track.height()),+ |p| grabbed.expand(2.0).contains(p),+ );+ if resp.double_clicked() {+ *pair = defaults;}let painter = ui.painter();painter.line_segment(@@ -1703,11 +1931,11 @@ fn thresholds(ui: &mut egui::Ui, rect: Rect, lo: &mut f64, hi: &mut f64) -> boolStroke::new(1.5, theme::text_dim()),);painter.line_segment(- [pos2(x, y_of(*hi)), pos2(x, y_of(*lo))],+ [pos2(x, y_of(pair[1])), pos2(x, y_of(pair[0]))],Stroke::new(2.0, theme::knob()),);- for (v, dx) in [(*hi, -7.0), (*lo, 7.0)] {- let knob = Rect::from_center_size(pos2(x + dx, y_of(v)), vec2(14.0, 9.0));+ for (k, v) in pair.iter().enumerate() {+ let knob = knob(k, *v);painter.rect_filled(knob, 2.0, theme::knob());painter.hline(knob.x_range().shrink(3.0),@@ -1718,7 +1946,7 @@ fn thresholds(ui: &mut egui::Ui, rect: Rect, lo: &mut f64, hi: &mut f64) -> boolresp.on_hover_text(tr("The lower and upper thresholds of the shadows, midtones and highlights",));- changed+ *pair != before}/// A Utilities block's height: its title and its rows.@@ -1809,7 +2037,7 @@ fn utility(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, k: usize, rect: Rectrow(0, 36.0),input,w,- ("inputBlack", "inputWhite"),+ ("inMinAdjust", "inMaxAdjust"),);range_row(&mut body,@@ -1818,16 +2046,16 @@ fn utility(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, k: usize, rect: Rectrow(1, 36.0),output,w,- ("outputMin", "outputMax"),+ ("outMinAdjust", "outMaxAdjust"),);}1 => {let rows = [- ("brightness", tr("Brightness:")),- ("contrast", tr("Contrast:")),- ("contrastCenter", tr("Contrast Center:")),- ("saturation", tr("Saturation:")),- ("logExposure", tr("Log. Exposure:")),+ ("brightnessAdjust", tr("Brightness:")),+ ("contrastAdjust", tr("Contrast:")),+ ("contrastCtrAdjust", tr("Contrast Center:")),+ ("saturationAdjust", tr("Saturation:")),+ ("exposureLnAdjust", tr("Log. Exposure:")),];let labels: Vec<&str> = rows.iter().map(|r| r.1).collect();let w = labels_end(&body, &labels, 128.0);@@ -1845,12 +2073,12 @@ fn utility(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, k: usize, rect: Rectapp,cx,row(0, 28.0),- "temperature",+ "temperatureAdjust",t,w,&temperature,);- slider_row(&mut body, app, cx, row(1, 28.0), "tint", n, w, &tint);+ slider_row(&mut body, app, cx, row(1, 28.0), "tintAdjust", n, w, &tint);let mut note = body.new_child(UiBuilder::new().max_rect(row(2, 28.0).shrink2(vec2(20.0, 2.0)))@@ -1870,14 +2098,14 @@ fn utility(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, k: usize, rect: Rect];let (h, sat, lum) = (tr("Hue:"), tr("Sat:"), tr("Luminance:"));let w = labels_end(&body, &[h, sat, lum], 112.0);- slider_row(&mut body, app, cx, row(0, 28.0), "hue", h, w, &hues);+ slider_row(&mut body, app, cx, row(0, 28.0), "hueAdjust", h, w, &hues);let grey_red = [Color32::from_gray(128), rgb(220, 40, 40)];slider_row(&mut body,app,cx,row(1, 28.0),- "hslSaturation",+ "satAdjust",sat,w,&grey_red,@@ -1888,7 +2116,7 @@ fn utility(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, k: usize, rect: Rectapp,cx,row(2, 28.0),- "luminance",+ "valAdjust",lum,w,&black_white,@@ -1908,25 +2136,25 @@ fn curves_column(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, k: usize, rect/// The Color Curves column: Reset and Select Curves on its title row;/// Brightness, Red, Green and Blue in one graph, or side by side when the-/// column is wide (`grading_curves.rs`).+/// column is wide (`grading_curves.rs`). Each curve is kept as its text,+/// as VEGAS's is.fn color_curves(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, rect: Rect) {let (mut bar, mut body) = column(ui, rect, tr("Color Curves"), false);- let Some(info) = cx.info("curves").cloned() else {- return;- };let id = egui::Id::new("cg-curves");if reset_button(&mut bar) {- set(app, cx, &[("curves", cx.default_of("curves"))], id);+ let values: Vec<(&str, Value)> = COLOR_CURVES+ .iter()+ .map(|n| (*n, cx.default_of(n)))+ .collect();+ set(app, cx, &values, id);}- let mut curves = match cx.value("curves") {- Value::Curves(c) => c,- _ => Vec::new(),- };- curves.resize(info.curves.max(1) as usize, Vec::new());- let labels: Vec<String> = info- .dimension_labels+ let curves: Vec<Vec<CurvePoint>> = COLOR_CURVES.iter()- .map(|l| tr(l).to_string())+ .map(|n| cg::curve_points(&cx.text(n), false))+ .collect();+ let labels: Vec<String> = [tr("Brightness"), tr("Red"), tr("Green"), tr("Blue")]+ .into_iter()+ .map(str::to_string).collect();let mut graph = body.new_child(UiBuilder::new()@@ -1937,8 +2165,52 @@ fn color_curves(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, rect: Rect) {let out = crate::grading_curves::editor(&mut graph, &mut view, id, &curves, &labels, &mut bar);app.color_panel.curves = view;if let Some(c) = out {- set(app, cx, &[("curves", Value::Curves(c))], id);+ let values: Vec<(&str, Value)> = COLOR_CURVES+ .iter()+ .zip(c.iter().zip(&curves))+ .filter(|(_, (new, old))| new != old)+ .map(|(n, (new, _))| (*n, curve_value(cx, n, new, false)))+ .collect();+ if !values.is_empty() {+ set(app, cx, &values, id);+ }+ }+}++/// A curve's value from its points: its text as VEGAS's panel writes it+/// (`hue`: a hue curve's, round the turn), every point given handles; no+/// points, the untouched text.+fn curve_value(cx: &Cx, name: &str, points: &[CurvePoint], hue: bool) -> Value {+ if points.is_empty() {+ return cx.default_of(name);+ }+ let points = cg::flat_handles(points);+ Value::Text(if hue {+ cg::hue_curve_text(&points)+ } else {+ cg::color_curve_text(&points)+ })+}++/// An HSL curve's point as the editor has it — 0 where the curve changes+/// nothing, −1 to 1 — from the effect's (0.5 there, 0 to 1).+fn to_editor(mut p: CurvePoint) -> CurvePoint {+ p.y = 2.0 * p.y - 1.0;+ if let Some(h) = &mut p.handles {+ h.before[1] *= 2.0;+ h.after[1] *= 2.0;+ }+ p+}++/// The effect's point of the editor's.+fn from_editor(mut p: CurvePoint) -> CurvePoint {+ p.y = (p.y + 1.0) / 2.0;+ if let Some(h) = &mut p.handles {+ h.before[1] /= 2.0;+ h.after[1] /= 2.0;}+ p}/// The HSL Curves: the type picked, its spectrum, its points (a@@ -1959,15 +2231,14 @@ fn hsl_curves(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, column_rect: Rect.layout(Layout::left_to_right(Align::Center)),);let ui = &mut body;- let mut all = match cx.value("hslCurves") {- Value::Curves(c) => c,- _ => Vec::new(),- };- all.resize(HSL_KINDS.len(), Vec::new());let kind = app.color_panel.hsl.kind.min(HSL_KINDS.len() - 1);- let mut curve = all[kind].clone();- let mut changed = false;+ let name = cg::CURVES[4 + kind];let hue_axis = kind < 3;+ let mut curve: Vec<CurvePoint> = cg::curve_points(&cx.text(name), hue_axis)+ .into_iter()+ .map(to_editor)+ .collect();+ let mut changed = false;let selecting = app.color_panel.picking@@ -2032,15 +2303,18 @@ fn hsl_curves(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, column_rect: RectColor32::from_rgb(r, g, b),);if resp.on_hover_text(name).clicked() {- let x = h as f64;- let y = hsl_at(&curve, x, hue_axis);- curve.push(bv_core::curve::CurvePoint {- x,- y,- handles: None,- });+ // As VEGAS's: the color and its two neighbours, where the+ // curve changes nothing, their handles level.+ let x = f64::from(h);+ for d in [0.0, 1.0 / 6.0, -1.0 / 6.0] {+ let at = (x + d).rem_euclid(1.0);+ if !curve.iter().any(|p| distance(p.x, at, true) < 1e-3) {+ curve.push(CurvePoint::new(at, 0.0));+ }+ }curve.sort_by(|a, b| a.x.total_cmp(&b.x));- view.picked = curve.iter().position(|p| (p.x - x).abs() < 1e-9);+ level_new(&mut curve, true);+ view.picked = curve.iter().position(|p| distance(p.x, x, true) < 1e-3);changed = true;}}@@ -2056,15 +2330,15 @@ fn hsl_curves(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, column_rect: Rectif let Some(i) = view.picked.filter(|&i| i < curve.len()) {head.add_space(6.0);let mut x = curve[i].x;- let mut y = curve[i].y;+ let mut y = (curve[i].y + 1.0) / 2.0;changed |= head.add_sized(BOX, field(&mut x).speed(0.002).range(0.0..=1.0)).changed();changed |= head- .add_sized(BOX, field(&mut y).speed(0.002).range(-1.0..=1.0))+ .add_sized(BOX, field(&mut y).speed(0.002).range(0.0..=1.0)).changed();curve[i].x = x;- curve[i].y = y;+ curve[i].y = 2.0 * y - 1.0;}let width = (ui.available_width() - 8.0).max(160.0);let height = (ui.available_height() - if hue_axis { 20.0 } else { 6.0 }).max(80.0);@@ -2286,19 +2560,14 @@ fn hsl_curves(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, column_rect: Rect{match near(&curve, p) {Some(i) => {- curve.remove(i);- view.picked = None;+ crate::grading_curves::flatten(&mut curve, i, hue_axis);+ view.picked = Some(i);}None => {- let (x, _) = from_screen(p);- let y = hsl_at(&curve, x, hue_axis);- curve.push(bv_core::curve::CurvePoint {- x,- y,- handles: None,- });- curve.sort_by(|a, b| a.x.total_cmp(&b.x));- view.picked = curve.iter().position(|q| (q.x - x).abs() < 1e-9);+ let (x, y) = from_screen(p);+ let (added, i) = crate::grading_curves::add_dot(&curve, [x, y], hue_axis);+ curve = added;+ view.picked = Some(i);}}changed = true;@@ -2386,9 +2655,9 @@ fn hsl_curves(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, column_rect: Rectchanged = true;ui.close();}- // Its tangents worked out again: a gradual start and end.+ // The curve's tangents worked out again: smooth.if crate::menus::item(ui, tr("Smooth curves")) {- curve[i].handles = None;+ crate::grading_curves::smooth(&mut curve, hue_axis);changed = true;ui.close();}@@ -2409,7 +2678,7 @@ fn hsl_curves(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, column_rect: Rectui.separator();if ui.button(tr("Reset")).clicked() {curve[i].y = 0.0;- curve[i].handles = None;+ crate::grading_curves::flatten(&mut curve, i, hue_axis);changed = true;ui.close();}@@ -2443,12 +2712,9 @@ fn hsl_curves(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, column_rect: Rectapp.color_panel.hue_picker = None;if let Some(x) = hue_of(c).filter(|_| hue_axis) {let y = hsl_at(&curve, x, true);- curve.push(bv_core::curve::CurvePoint {- x,- y,- handles: None,- });+ curve.push(CurvePoint::new(x, y));curve.sort_by(|a, b| a.x.total_cmp(&b.x));+ level_new(&mut curve, true);app.color_panel.hsl.picked = curve.iter().position(|p| (p.x - x).abs() < 1e-9);changed = true;}@@ -2456,13 +2722,9 @@ fn hsl_curves(ui: &mut egui::Ui, app: &mut BananaApp, cx: &Cx, column_rect: Rect}}if changed {- all[kind] = curve;- set(- app,- cx,- &[("hslCurves", Value::Curves(all))],- egui::Id::new("cg-hsl"),- );+ let points: Vec<CurvePoint> = curve.into_iter().map(from_editor).collect();+ let value = curve_value(cx, name, &points, hue_axis);+ set(app, cx, &[(name, value)], egui::Id::new("cg-hsl"));}if toggle_selector {if selecting {@@ -2697,15 +2959,13 @@ fn apply_pick(app: &mut BananaApp, cx: &Cx, picker: Picker, colors: &[[f32; 3]],return;}if let Picker::Selector(n) = picker {- let before: Vec<f64> = match cx.value("hslCurves") {- Value::Curves(c) => c- .get(n)- .map_or_else(Vec::new, |c| c.iter().map(|p| p.x).collect()),- _ => Vec::new(),- };- if let Some((_, Value::Curves(c))) = new.iter().find(|(name, _)| name == "hslCurves")- && let Some(curve) = c.get(n)- {+ let name = cg::CURVES[4 + n.min(5)];+ let before: Vec<f64> = cg::curve_points(&cx.text(name), n < 3)+ .iter()+ .map(|p| p.x)+ .collect();+ if let Some((_, Value::Text(t))) = new.iter().find(|(k, _)| k == name) {+ let curve = cg::curve_points(t, n < 3);let added: Vec<usize> = (0..curve.len()).filter(|&i| !before.iter().any(|x| (x - curve[i].x).abs() < 1e-9)).collect();@@ -2760,7 +3020,7 @@ pub(crate) fn scope_limits(app: &BananaApp) -> Option<[f64; 2]> {return None;}let cx = context(app)?;- Some([cx.num("lowerThreshold"), cx.num("upperThreshold")])+ Some([cx.num(cg::LOW_THRESHOLD), cx.num(cg::HIGH_THRESHOLD)])}/// Opens the panel at `level` (the event's, the track's, the media's or@@ -2806,37 +3066,34 @@ pub(crate) fn grade_for_review(app: &mut BananaApp) {let Some(cx) = context(app) else {return;};- let p = |x: f64, y: f64| bv_core::curve::CurvePoint {- x,- y,- handles: None,- };- let straight = vec![p(0.0, 0.0), p(1.0, 1.0)];- let mut hsl = vec![Vec::new(); 6];- hsl[1] = vec![p(0.0, -0.4), p(0.33, 0.3), p(0.66, 0.0)];+ let mut values: Vec<(String, Value)> = Vec::new();+ for (i, rgb) in [+ (0, [0.06, 0.02, -0.03]),+ (2, [1.08, 1.0, 0.94]),+ (4, [-0.02, 0.0, 0.05]),+ ] {+ let (stem, _) = WHEELS[i];+ let dot = cg::wheel_point(rgb, wheel_range(i), false);+ values.extend(wheel_settings(stem, rgb, dot));+ }+ let red = cg::color_curve_text(&cg::flat_handles(&[+ CurvePoint::new(0.0, 0.0),+ CurvePoint::new(0.5, 0.58),+ CurvePoint::new(1.0, 1.0),+ ]));+ let hue_sat = cg::hue_curve_text(&cg::flat_handles(&[+ CurvePoint::new(0.0, 0.3),+ CurvePoint::new(0.33, 0.65),+ CurvePoint::new(0.66, 0.5),+ ]));+ values.extend([+ ("gammaY".to_string(), Value::Num(vec![1.1])),+ ("contrastAdjust".to_string(), Value::Num(vec![0.15])),+ ("curveR".to_string(), Value::Text(red)),+ ("curveHvS".to_string(), Value::Text(hue_sat)),+ ]);app.color_panel.hsl.kind = 1;- set(- app,- &cx,- &[- ("lift", Value::Num(vec![0.06, 0.02, -0.03])),- ("gain", Value::Num(vec![1.08, 1.0, 0.94])),- ("gammaY", Value::Num(vec![1.1])),- ("shadows", Value::Num(vec![-0.02, 0.0, 0.05])),- ("contrast", Value::Num(vec![0.15])),- (- "curves",- Value::Curves(vec![- straight.clone(),- vec![p(0.0, 0.0), p(0.5, 0.58), p(1.0, 1.0)],- straight.clone(),- straight,- ]),- ),- ("hslCurves", Value::Curves(hsl)),- ],- egui::Id::new("cg-review"),- );+ set_named(app, &cx, &values, egui::Id::new("cg-review"));}/// A color's hue (a turn's 0–1); greys have none.@@ -2857,6 +3114,16 @@ fn hue_of([r, g, b, _]: [u8; 4]) -> Option<f64> {Some(h / 6.0)}+/// The points of `c` without handles given level ones, as VEGAS's new+/// points have (`wrap`: a hue curve's).+fn level_new(c: &mut [CurvePoint], wrap: bool) {+ for i in 0..c.len() {+ if c[i].handles.is_none() {+ crate::grading_curves::flatten(c, i, wrap);+ }+ }+}+/// An HSL curve at `x`: a hue curve wraps round red (its points a turn/// before and after too), as the effect reads it.fn hsl_at(curve: &[bv_core::curve::CurvePoint], x: f64, wrap: bool) -> f64 {@@ -2900,7 +3167,7 @@ mod tests {return;};assert!(cx.index.is_none());- assert_eq!(cx.num("gain"), 1.0);+ assert_eq!(cx.num("gainR"), 1.0);set(&mut app,&cx,@@ -2977,11 +3244,11 @@ mod tests {assert!(cx.index.is_some() && cx.effect_key().is_some());assert!(app.ofx.watch_held);apply_pick(&mut app, &cx, Picker::BlackPoint, &[[0.1, 0.1, 0.1]], false);- let lift = context(&app).unwrap().rgb("lift");- assert!(- lift.iter().all(|l| (l + 0.1 / 0.9).abs() < 1e-4),- "{lift:?}"- );+ // VEGAS's: each channel between Lift's ends, the color turned over.+ let cx = context(&app).unwrap();+ let lift = ["liftR", "liftG", "liftB"].map(|n| cx.num(n));+ assert!(lift.iter().all(|l| (l - 0.8).abs() < 1e-9), "{lift:?}");+ assert!(cx.num("liftU") != 0.0, "the point follows the color");end_frame(&mut app);assert!(app.color_panel.picking.is_none() && !app.ofx.watch_held);app.color_panel.level = Level::VideoOutput;diff --git a/crates/ui-egui/src/tabs/effects.rs b/crates/ui-egui/src/tabs/effects.rsindex 80283df..526d208 100644--- a/crates/ui-egui/src/tabs/effects.rs+++ b/crates/ui-egui/src/tabs/effects.rs@@ -48,6 +48,107 @@ pub fn description(k: EffectKind) -> &'static str {EffectKind::ModernEq => tr("Up to eight bands drawn on a graph, on both channels, one of them, the middle or the sides.",),+ EffectKind::Volume => tr("Raises or lowers the volume, up to 6 dB."),+ EffectKind::Pan => {+ tr("Moves a stereo sound left or right, blending one channel into the other.")+ }+ EffectKind::SmoothEnhance => {+ tr("Softens the highs (smooth) or brings them forward (enhance).")+ }+ EffectKind::NoiseGateFx => tr("Silences the sound while it stays below the threshold."),+ EffectKind::TrackNoiseGate => tr("Silences the track while it stays below the threshold."),+ EffectKind::SimpleDelay => {+ tr("An echo, or many fading away, its time in seconds or in notes of the tempo.")+ }+ EffectKind::Dither => {+ tr("Rounds the sound to a bit depth with a little noise, so it stays clean.")+ }+ EffectKind::ResonantFilter => {+ tr("A low-, band- or high-pass filter that can ring at its frequency.")+ }+ EffectKind::ParametricEq => tr("One shelf, band-pass or notch, accurate down to the lows."),+ EffectKind::Chorus => {+ tr("Thickens the sound with slightly detuned, delayed copies of itself.")+ }+ EffectKind::FlangeWahWah => tr("A sweeping flange, phaser or wah-wah."),+ EffectKind::ReverbFx => {+ tr("A room's reverberation: 19 spaces, early reflections and pre-delay.")+ }+ EffectKind::TrackCompressor => {+ tr("Evens out the level, from gentle compression to a limiter.")+ }+ EffectKind::TrackEq => tr("Four bands, each a low shelf, a peak or a high shelf."),+ EffectKind::ParagraphicEq => tr("Four peak or notch bands, with low and high shelves."),+ EffectKind::MultiTapDelay => {+ tr("Up to eight echoes of one delay line, each with its own time, level and side.")+ }+ EffectKind::MultiBandDynamics => tr(+ "Four bands, each compressed on its own: tames plosives, sibilants or a boomy low end.",+ ),+ EffectKind::ExpressDelay => tr("A quick echo, fed back by a share of itself."),+ EffectKind::ExpressDistortion => tr("A quick distortion, from warm to mangled."),+ EffectKind::ExpressEqualization => tr("Quick bass, mid and treble."),+ EffectKind::ExpressNoiseGate => {+ tr("Silences the sound while it stays below the threshold.")+ }+ EffectKind::ExpressChorus => {+ tr("A quick chorus: one to three modulated copies of the sound.")+ }+ EffectKind::ExpressFlangeWahWah => tr("A quick flange or wah-wah."),+ EffectKind::ExpressDynamics => tr("A quick compressor, up to a limiter."),+ EffectKind::ExpressStutter => tr("Switches the sound on and off in a fast rhythm."),+ EffectKind::ExpressAmplitudeModulation => {+ tr("The volume rises and falls in a smooth wave (tremolo).")+ }+ EffectKind::ExpressGraphicEq => tr("Ten bands an octave apart, from 28 Hz to 15 kHz."),+ EffectKind::ExpressReverb => tr("A quick reverb: a room, its size and how lively it is."),+ EffectKind::ExpressAudioRestoration => {+ tr("Takes clicks and crackle out and turns the steady hiss of old recordings down.")+ }+ EffectKind::AmplitudeModulation => {+ tr("The volume follows a wave you draw, slow (tremolo) or fast (ring tones).")+ }+ EffectKind::GraphicDynamics => {+ tr("Compression, limiting or gating drawn as an input/output curve.")+ }+ EffectKind::Distortion => {+ tr("Reshapes the wave along curves you draw, each half on its own.")+ }+ EffectKind::GraphicEq => tr("A frequency response you draw, accurate down to the lows."),+ EffectKind::WaveHammer => {+ tr("A compressor and a volume maximizer for mastering, up to 5.1.")+ }+ EffectKind::StudioGate => tr("Lowers the sound below the threshold, smoothly and quickly."),+ EffectKind::DeEsser => tr("Tames the hiss of \"s\" sounds in a voice."),+ EffectKind::StudioLimiter => {+ tr("Makes the sound louder without going over the top, then clips it gently.")+ }+ EffectKind::TremoloPan => tr("A tremolo, or an auto-pan when the sides move apart."),+ EffectKind::TubeStage => tr("The warmth and grit of a tube preamp."),+ EffectKind::StudioCompressor => {+ tr("A musical compressor with parallel mix, soft clip and side-chain filter.")+ }+ EffectKind::Phaser => tr("Sweeping notches of 4, 8 or 12 stages, with feedback."),+ EffectKind::ChorusFlanger => {+ tr("A chorus, flanger or wide ensemble of three voices a side.")+ }+ EffectKind::StudioReverb => tr("A plate, room or hall, with size, time and damping."),+ EffectKind::StereoDelay => {+ tr("Two delays, digital, analog or bucket brigade, in ms or notes of the tempo.")+ }+ EffectKind::TimeStretch | EffectKind::ExpressTimeStretch => {+ tr("Makes the sound longer or shorter without changing its pitch.")+ }+ EffectKind::PitchShift => {+ tr("Raises or lowers the pitch, like a tape or keeping the length.")+ }+ EffectKind::GapperSnipper => tr("Inserts silences into the sound or cuts bits out of it."),+ EffectKind::Vibrato => {+ tr("The pitch wavers along a wave you draw, like a tape speeding up and slowing down.")+ }+ EffectKind::VocalStrip => {+ tr("A voice's chain in one: high-pass, gate, de-esser, compressor and tone.")+ }EffectKind::Plugin => tr("An effect from an OFX plug-in."),EffectKind::Vst => tr("An audio effect from a VST 3 plug-in."),}diff --git a/crates/ui-egui/src/tabs/explorer.rs b/crates/ui-egui/src/tabs/explorer.rsindex 3db4d97..8be41b2 100644--- a/crates/ui-egui/src/tabs/explorer.rs+++ b/crates/ui-egui/src/tabs/explorer.rs@@ -14,7 +14,8 @@use crate::i18n::tr;use std::collections::{HashMap, HashSet};use std::path::{Path, PathBuf};-use std::time::SystemTime;+use std::sync::mpsc::{Receiver, TryRecvError, channel};+use std::time::{Duration, Instant, SystemTime};use crate::app::{BananaApp, MediaDrag};use crate::dock::Tab;@@ -76,9 +77,10 @@ pub struct ExplorerState {all_files: bool,view: View,sort: SortBy,- /// The tree: its root open, the folders open in it, the folders found- /// in each (read when opened).+ /// The tree: its root open, its first level, the folders open in it,+ /// the folders found in each (read when opened).root_open: bool,+ roots: TreeRoots,open: HashSet<PathBuf>,folders: HashMap<PathBuf, Vec<PathBuf>>,/// Views › Regions and Summary: panels about the selected file at the@@ -116,7 +118,7 @@ fn file_glyph(p: &Path) -> Glyph {Some(FileKind::Image) => Glyph::Icon(Icon::FileImage),Some(FileKind::Video) => Glyph::Icon(Icon::FileVideo),Some(FileKind::Project) => Glyph::Logo,- Some(FileKind::Timeline) | None => Glyph::Icon(Icon::File),+ Some(FileKind::Timeline | FileKind::VegProject) | None => Glyph::Icon(Icon::File),}}@@ -140,6 +142,7 @@ fn type_text(e: &Entry) -> String {Some(FileKind::Audio) => tr("Audio").into(),Some(FileKind::Image) => tr("Image").into(),Some(FileKind::Project) => tr("BananaV project").into(),+ Some(FileKind::VegProject) => tr("VEG Project").into(),Some(FileKind::Timeline)if e.path.extension()@@ -191,6 +194,91 @@ fn drives() -> Vec<PathBuf> {}}+/// A line of the tree's first level: its name, folder and icon.+type TreeRoot = (String, PathBuf, Icon);++/// The tree's first level: the favorites that exist, the user's folders and+/// the drives.+fn read_roots(favorites: &[PathBuf]) -> Vec<TreeRoot> {+ let mut nodes: Vec<TreeRoot> = favorites+ .iter()+ .filter(|p| p.is_dir())+ .map(|p| (node_name(p), p.clone(), Icon::StarFilled))+ .collect();+ nodes.extend(+ places()+ .into_iter()+ .map(|(n, p)| (n.to_string(), p, Icon::Folder)),+ );+ nodes.extend(+ drives()+ .into_iter()+ .map(|d| (d.display().to_string(), d, Icon::Disc)),+ );+ nodes+}++/// The tree's first level, read on a thread of its own every few seconds:+/// frames never touch the disks for it (a disk asleep or a network drive+/// would hold them up).+#[derive(Debug, Default)]+struct TreeRoots {+ nodes: Vec<TreeRoot>,+ /// The favorites they were read for, and when.+ favorites: Vec<PathBuf>,+ read_at: Option<Instant>,+ reading: Option<Receiver<Vec<TreeRoot>>>,+}++impl TreeRoots {+ const EVERY: Duration = Duration::from_secs(5);++ /// The first level as last read; a new reading starts when it is time+ /// (the interface repaints when it brings something new).+ fn nodes(&mut self, ctx: &egui::Context, favorites: &[PathBuf]) -> &[TreeRoot] {+ if let Some(reading) = &self.reading {+ match reading.try_recv() {+ Ok(nodes) => {+ self.nodes = nodes;+ self.reading = None;+ }+ Err(TryRecvError::Disconnected) => self.reading = None,+ Err(TryRecvError::Empty) => {}+ }+ }+ let due =+ self.favorites != favorites || self.read_at.is_none_or(|t| t.elapsed() >= Self::EVERY);+ if due && self.reading.is_none() {+ self.read_at = Some(Instant::now());+ self.favorites = favorites.to_vec();+ let (tx, rx) = channel();+ let (ctx, list, known) = (ctx.clone(), favorites.to_vec(), self.nodes.clone());+ let spawned = std::thread::Builder::new()+ .name("bv-explorer-roots".into())+ .spawn(move || {+ let nodes = read_roots(&list);+ let new = nodes != known;+ let _ = tx.send(nodes);+ if new {+ ctx.request_repaint();+ }+ });+ if spawned.is_ok() {+ // The first time, disks that answer quickly show at once.+ match rx.recv_timeout(Duration::from_millis(if self.nodes.is_empty() {+ 100+ } else {+ 0+ })) {+ Ok(nodes) => self.nodes = nodes,+ Err(_) => self.reading = Some(rx),+ }+ }+ }+ &self.nodes+ }+}+/// Folders and files to leave out: hidden and the system's.fn hidden(name: &str) -> bool {name.starts_with('.') || name.starts_with('$')@@ -217,6 +305,7 @@ impl ExplorerState {view: View::Details,sort: SortBy::Name,root_open: true,+ roots: TreeRoots::default(),open: HashSet::new(),folders: HashMap::new(),show_regions: false,@@ -369,6 +458,15 @@ impl ExplorerState {.collect()}+ /// Whether `p`, picked, is a file: as the folder's list read says, the+ /// disk asked only for what is not in it.+ fn is_file(&self, p: &Path) -> bool {+ self.entries+ .iter()+ .find(|e| e.path == p)+ .map_or_else(|| p.is_file(), |e| !e.is_dir)+ }+/// The folders inside `dir` (read once, when its node opens).fn subfolders(&mut self, dir: &Path) -> &[PathBuf] {self.folders.entry(dir.to_path_buf()).or_insert_with(|| {@@ -528,7 +626,11 @@ enum Act {/// its places at the end; Refresh, Auto Preview and Views.fn toolbar(ui: &mut Ui, app: &mut BananaApp) {// Previews: the selected file alone through the preview bus.- let file = app.explorer.selected.clone().filter(|p| p.is_file());+ let file = app+ .explorer+ .selected+ .clone()+ .filter(|p| app.explorer.is_file(p));let previewing = app.previewing();let auto = app.settings.explorer_auto_preview;let favorites = app.settings.explorer_favorites.clone();@@ -634,7 +736,7 @@ fn toolbar(ui: &mut Ui, app: &mut BananaApp) {}// Add to Favorites: the folder picked, or the one open.let folder = picked- .filter(|p| p.is_dir())+ .filter(|p| !st.is_file(p)).unwrap_or_else(|| st.dir.clone());let fav = favorites.contains(&folder);if crate::widgets::icon_toggle(ui, Icon::Star, fav, tr("Add to Favorites")).clicked() {@@ -815,21 +917,7 @@ fn tree_ui(ui: &mut Ui, st: &mut ExplorerState, favorites: &[PathBuf]) {if !st.root_open {return;}- let mut nodes: Vec<(String, PathBuf, Icon)> = favorites- .iter()- .filter(|p| p.is_dir())- .map(|p| (node_name(p), p.clone(), Icon::StarFilled))- .collect();- nodes.extend(- places()- .into_iter()- .map(|(n, p)| (n.to_string(), p, Icon::Folder)),- );- nodes.extend(- drives()- .into_iter()- .map(|d| (d.display().to_string(), d, Icon::Disc)),- );+ let nodes = st.roots.nodes(ui.ctx(), favorites).to_vec();for (name, path, icon) in nodes {folder_node(ui, st, 1, name, path, icon);}@@ -1482,7 +1570,11 @@ impl BananaApp {/// The selected file's media information (read once).fn selected_info(app: &mut BananaApp) -> Option<(PathBuf, MediaInfo)> {- let path = app.explorer.selected.clone().filter(|p| p.is_file())?;+ let path = app+ .explorer+ .selected+ .clone()+ .filter(|p| app.explorer.is_file(p))?;if let Some(info) = app.explorer.probes.get(&path) {return info.clone().map(|i| (path, i));}diff --git a/crates/ui-egui/src/tabs/preview.rs b/crates/ui-egui/src/tabs/preview.rsindex c55b41c..8f402d7 100644--- a/crates/ui-egui/src/tabs/preview.rs+++ b/crates/ui-egui/src/tabs/preview.rs@@ -119,7 +119,7 @@ const WHOLE: [f32; 4] = [0.0, 0.0, 1.0, 1.0];pub struct PreviewState {texture: Option<TextureHandle>,- shown: Option<(u64, Tick, u32, u32)>,+ pub(crate) shown: Option<(u64, Tick, u32, u32)>,/// Overlays (the # button), and which: the grid, the safe areas, the/// closed captioning channels (CC1 to CC4), one channel of the picture.pub(crate) overlays: bool,@@ -283,10 +283,7 @@ fn paint_split({let key = (f.generation, f.time, f.width, f.height);if app.preview.sides_shown[i] != Some(key) {- let image = ColorImage::from_rgba_unmultiplied(- [f.width as usize, f.height as usize],- &f.rgba,- );+ let image = frame_image([f.width as usize, f.height as usize], &f.rgba);match &mut app.preview.sides[i] {Some(t) => t.set(image, TextureOptions::LINEAR),None => {@@ -1221,8 +1218,7 @@ pub fn ui(ui: &mut egui::Ui, app: &mut BananaApp) {if let Some(f) = rendered.or(frame).filter(|_| !hold) {let key = (f.generation, f.time, f.width, f.height);if app.preview.shown != Some(key) || app.preview.repeats != view_360 {- let image =- ColorImage::from_rgba_unmultiplied([f.width as usize, f.height as usize], &f.rgba);+ let image = frame_image([f.width as usize, f.height as usize], &f.rgba);// Draft shows the pixels as they are; the 360° View's frame// repeats across (its left and right edges meet).let options = match (quality.level == RenderQuality::Draft, view_360) {@@ -1550,10 +1546,40 @@ fn status_ui(ui: &mut egui::Ui, app: &mut BananaApp, full: Rect, status_h: f32,}}+/// A frame as an image for the screen. Almost every frame is opaque: no+/// color then needs working out, the pixels are copied.+pub(crate) fn frame_image(size: [usize; 2], rgba: &[u8]) -> ColorImage {+ let opaque = rgba+ .as_chunks::<4>()+ .0+ .chunks(1024)+ .all(|c| c.iter().fold(255u8, |a, p| a & p[3]) == 255);+ if opaque {+ ColorImage::from_rgba_premultiplied(size, rgba)+ } else {+ ColorImage::from_rgba_unmultiplied(size, rgba)+ }+}+#[cfg(test)]mod tests {use super::*;+ #[test]+ fn frames_come_out_with_their_colors() {+ let opaque = [10, 20, 30, 255, 40, 50, 60, 255];+ let image = frame_image([2, 1], &opaque);+ assert_eq!(image.pixels[1], Color32::from_rgb(40, 50, 60));+ // A pixel seen through gets its color multiplied.+ let through = [10, 20, 30, 255, 200, 100, 50, 128];+ let image = frame_image([2, 1], &through);+ assert_eq!(image.pixels[0], Color32::from_rgb(10, 20, 30));+ assert_eq!(+ image.pixels[1],+ Color32::from_rgba_unmultiplied(200, 100, 50, 128)+ );+ }+#[test]fn the_zoom_steps_five_percent_and_comes_back_centered() {let mut p = PreviewState::default();diff --git a/crates/ui-egui/src/tabs/properties.rs b/crates/ui-egui/src/tabs/properties.rsindex 67d954c..a50e82b 100644--- a/crates/ui-egui/src/tabs/properties.rs+++ b/crates/ui-egui/src/tabs/properties.rs@@ -50,7 +50,13 @@ pub fn ui(ui: &mut egui::Ui, app: &mut BananaApp) {} else {clip.start};- let framing = clip.transform_at(at);+ let place = project.clip_place_in(id);+ let shown = place.map(|place| clip.box_at(at, place.media, place.media_aspect));+ let framing = place+ .zip(shown)+ .map_or_else(Transform::default, |(place, key)| {+ bv_timeline::pancrop::transform_from_key(&key, &place)+ });let mut tf = framing;let mut conform = false;@@ -218,7 +224,7 @@ pub fn ui(ui: &mut egui::Ui, app: &mut BananaApp) {if ui.small_button(tr("Open Pan/Crop…")).clicked() {app.clip_windows.pan_crop = Some(id);}- if !clip.transform_keys.is_empty() {+ if clip.pan_crop.keys.len() > 1 {super::hint(ui, tr("Animated: edits the keyframe at the cursor."));}});@@ -251,11 +257,20 @@ pub fn ui(ui: &mut egui::Ui, app: &mut BananaApp) {apply_clip(app, key, id, c);}}- if tf != framing {+ if tf != framing+ && let (Some(place), Some(was)) = (place, shown)+ {+ // The box as the sliders say, what they do not show as it was: the+ // pivot where it is from its middle.+ let mut now = bv_timeline::pancrop::key_from_transform(&tf, &place);+ now.pivot = [+ now.center[0] + was.pivot[0] - was.center[0],+ now.center[1] + was.pivot[1] - was.center[1],+ ];let key = ui.id().with(("enquadramento", id.0));let new = app.settings.prefs.new_motion_keys();app.modify_merged(key, |p| {- let _ = p.set_clip_transform_at_as(id, at, tf, new);+ let _ = p.set_clip_box_at(id, at, now, new);});}}@@ -469,6 +484,12 @@ pub fn params(ui: &mut egui::Ui, e: &mut Effect) {let mut i = 0;while i < specs.len() {let spec = specs[i];+ group_heading(ui, &spec);+ // Greyed out while a switch it waits on is not as it wants.+ let live = spec.live(|k| e.param(k));+ let label = |ui: &mut egui::Ui| {+ ui.add_enabled(live, egui::Label::new(tr(spec.name)));+ };match spec.kind {ParamKind::Color => {ui.label(tr(spec.name));@@ -488,22 +509,61 @@ pub fn params(ui: &mut egui::Ui, e: &mut Effect) {continue;}ParamKind::Toggle => {- ui.label(tr(spec.name));- let mut on = e.param(i) >= 0.5;- if crate::widgets::checkbox(ui, &mut on, "").changed() {- e.set_param(i, on as u8 as f32);- }+ label(ui);+ ui.add_enabled_ui(live, |ui| {+ let mut on = e.param(i) >= 0.5;+ if crate::widgets::checkbox(ui, &mut on, "").changed() {+ e.set_param(i, on as u8 as f32);+ }+ });}ParamKind::Slider => {- ui.label(tr(spec.name));- let mut v = e.param(i);- let r = ui.add(crate::fmt::slider(&mut v, spec.min..=spec.max, 2, ""));- if r.double_clicked() {- v = spec.default;- }- if v != e.param(i) {- e.set_param(i, v);+ label(ui);+ ui.add_enabled_ui(live, |ui| {+ let mut v = e.param(i);+ let r = param_slider(ui, &spec, &mut v);+ if r.double_clicked()+ || crate::widgets::bar_double_clicked(ui, &r, true)+ {+ v = spec.default;+ }+ if v != e.param(i) {+ e.set_param(i, v);+ }+ });+ }+ ParamKind::Choice => {+ label(ui);+ ui.add_enabled_ui(live, |ui| {+ let mut v = e.param(i);+ let at = (v - spec.min).round().max(0.0) as usize;+ let shown = spec.options.get(at).map_or("", |o| tr(o));+ egui::ComboBox::from_id_salt(("param-choice", e.kind, i))+ .selected_text(shown)+ .show_ui(ui, |ui| {+ for (k, o) in spec.options.iter().enumerate() {+ let value = spec.min + k as f32;+ ui.selectable_value(&mut v, value, tr(o));+ }+ });+ if v != e.param(i) {+ e.set_param(i, v);+ }+ });+ }+ ParamKind::Data => {+ i += 1;+ continue;+ }+ ParamKind::Graph => {+ let points = spec.graph.map_or(0, |g| g.params());+ label(ui);+ if let Some(g) = spec.graph {+ ui.vertical(|ui| graph_editor(ui, e, i, &g));}+ ui.end_row();+ i += 1 + points;+ continue;}}ui.end_row();@@ -511,3 +571,258 @@ pub fn params(ui: &mut egui::Ui, e: &mut Effect) {}});}++/// A graph's points as its effect holds them: `count` at `at`, then+/// `(x, y)` pairs.+fn graph_points(e: &Effect, at: usize) -> Vec<(f32, f32)> {+ let count = e.param(at).round().max(0.0) as usize;+ (0..count)+ .map(|k| (e.param(at + 1 + 2 * k), e.param(at + 2 + 2 * k)))+ .collect()+}++fn set_graph_points(e: &mut Effect, at: usize, points: &[(f32, f32)]) {+ e.set_param(at, points.len() as f32);+ for (k, (x, y)) in points.iter().enumerate() {+ e.set_param(at + 1 + 2 * k, *x);+ e.set_param(at + 2 + 2 * k, *y);+ }+}++/// A graph parameter's editor: its points joined by straight lines; drag+/// a point to move it (the first and last stay at the ends when pinned),+/// double-click the background to add one, right-click a point to take it+/// away (never below two).+fn graph_editor(ui: &mut egui::Ui, e: &mut Effect, at: usize, g: &bv_timeline::Graph) {+ let width = ui.available_width().clamp(240.0, 520.0);+ let (rect, background) = ui.allocate_exact_size(egui::vec2(width, 160.0), egui::Sense::click());+ let painter = ui.painter_at(rect);+ let visuals = ui.visuals();+ painter.rect_filled(rect, 2.0, visuals.extreme_bg_color);+ let stroke = egui::Stroke::new(1.0, visuals.weak_text_color().gamma_multiply(0.35));+ for k in 1..4 {+ let t = k as f32 / 4.0;+ painter.hline(rect.x_range(), rect.top() + t * rect.height(), stroke);+ painter.vline(rect.left() + t * rect.width(), rect.y_range(), stroke);+ }+ let (x0, x1) = g.x;+ let (y0, y1) = g.y;+ let to_unit_x = |x: f32| {+ if g.log_x && x0 > 0.0 {+ (x.max(x0) / x0).ln() / (x1 / x0).ln()+ } else {+ (x - x0) / (x1 - x0)+ }+ };+ let from_unit_x = |u: f32| {+ if g.log_x && x0 > 0.0 {+ x0 * (x1 / x0).powf(u)+ } else {+ x0 + u * (x1 - x0)+ }+ };+ // The curve drawn a little inside, so the points at its ends show whole.+ let plot = rect.shrink(6.0);+ let to_screen = |(x, y): (f32, f32)| {+ egui::pos2(+ plot.left() + to_unit_x(x).clamp(0.0, 1.0) * plot.width(),+ plot.bottom() - ((y - y0) / (y1 - y0)).clamp(0.0, 1.0) * plot.height(),+ )+ };+ let from_screen = |p: egui::Pos2| {+ let u = ((p.x - plot.left()) / plot.width()).clamp(0.0, 1.0);+ let v = ((plot.bottom() - p.y) / plot.height()).clamp(0.0, 1.0);+ (from_unit_x(u), y0 + v * (y1 - y0))+ };+ let mut points = graph_points(e, at);+ let mut changed = false;+ let line: Vec<egui::Pos2> = points.iter().map(|p| to_screen(*p)).collect();+ painter.add(egui::Shape::line(+ line.clone(),+ egui::Stroke::new(2.0, visuals.selection.bg_fill),+ ));+ let last = points.len().saturating_sub(1);+ let mut remove = None;+ for (k, pos) in line.iter().enumerate() {+ let id = ui.id().with(("graph-point", at, k));+ let r = ui.interact(+ egui::Rect::from_center_size(*pos, egui::vec2(12.0, 12.0)),+ id,+ egui::Sense::click_and_drag(),+ );+ let hot = r.hovered() || r.dragged();+ painter.circle_filled(+ *pos,+ if hot { 5.0 } else { 4.0 },+ visuals.strong_text_color(),+ );+ if r.dragged()+ && let Some(p) = r.interact_pointer_pos()+ {+ let (mut x, y) = from_screen(p);+ // Between its neighbours; the ends stay put when pinned.+ let lo = if k == 0 { x0 } else { points[k - 1].0 };+ let hi = if k == last { x1 } else { points[k + 1].0 };+ x = x.clamp(lo, hi);+ if g.pinned_ends && (k == 0 || k == last) {+ x = points[k].0;+ }+ points[k] = (x, y);+ changed = true;+ }+ if r.secondary_clicked() && points.len() > 2 && !(g.pinned_ends && (k == 0 || k == last)) {+ remove = Some(k);+ }+ let axis = |v: f32, unit: &str| {+ let v = crate::fmt::num(v as f64, 1);+ if unit.is_empty() {+ v+ } else {+ format!("{v} {}", tr(unit))+ }+ };+ r.on_hover_text(format!(+ "{}, {}",+ axis(points[k].0, g.x_unit),+ axis(points[k].1, g.y_unit)+ ));+ }+ if let Some(k) = remove {+ points.remove(k);+ changed = true;+ }+ if background.double_clicked()+ && points.len() < g.points as usize+ && let Some(p) = background.interact_pointer_pos()+ {+ let new = from_screen(p);+ let k = points.partition_point(|q| q.0 <= new.0);+ points.insert(k, new);+ changed = true;+ }+ if changed {+ set_graph_points(e, at, &points);+ }+}++/// A heading row when `spec` begins a group of its effect's panel.+fn group_heading(ui: &mut egui::Ui, spec: &bv_timeline::ParamSpec) {+ if !spec.group.is_empty() && spec.shown() {+ ui.label(egui::RichText::new(tr(spec.group)).strong());+ ui.end_row();+ }+}++/// The lowest gain a dB field shows before −Inf.+const FLOOR_DB: f32 = -96.0;++/// A number parameter's slider, its value shown as `spec` says: as it is+/// with its unit, a linear gain in dB, a part as a percentage, or a pan.+pub fn param_slider(+ ui: &mut egui::Ui,+ spec: &bv_timeline::ParamSpec,+ v: &mut f32,+) -> egui::Response {+ use bv_timeline::Show;+ let decimals = spec.decimals as usize;+ match spec.show {+ Show::Value => {+ let unit = if spec.unit.is_empty() {+ String::new()+ } else {+ format!(" {}", tr(spec.unit))+ };+ let mut slider = crate::fmt::slider(v, spec.min..=spec.max, decimals, &unit)+ .logarithmic(spec.log && spec.min > 0.0);+ if decimals == 0 {+ slider = slider.step_by(1.0);+ }+ ui.add(slider)+ }+ Show::Db => {+ let floor = spec.min;+ ui.add(+ egui::Slider::new(v, spec.min..=spec.max)+ .custom_formatter(move |d, _| {+ if d <= floor as f64 {+ format!("{} dB", tr("-Inf."))+ } else {+ format!("{} dB", crate::fmt::num(d, decimals))+ }+ })+ .custom_parser(move |s| {+ if s.trim().to_lowercase().contains("inf") {+ Some(floor as f64)+ } else {+ crate::fmt::parse(s)+ }+ }),+ )+ }+ Show::Percent => {+ let mut p = *v * 100.0;+ let r = ui.add(crate::fmt::slider(+ &mut p,+ spec.min * 100.0..=spec.max * 100.0,+ decimals,+ " %",+ ));+ *v = p / 100.0;+ r+ }+ Show::GainDb => {+ let top = 20.0 * spec.max.max(1e-6).log10();+ let mut db = if *v > 0.0 {+ (20.0 * v.log10()).max(FLOOR_DB)+ } else {+ FLOOR_DB+ };+ let r = ui.add(+ egui::Slider::new(&mut db, FLOOR_DB..=top)+ .custom_formatter(move |d, _| {+ if d <= FLOOR_DB as f64 {+ format!("{} dB", tr("-Inf."))+ } else {+ format!("{} dB", crate::fmt::num(d, decimals))+ }+ })+ .custom_parser(|s| {+ if s.trim().to_lowercase().contains("inf") {+ Some(FLOOR_DB as f64)+ } else {+ crate::fmt::parse(s)+ }+ }),+ );+ if r.changed() {+ *v = if db <= FLOOR_DB {+ 0.0+ } else {+ 10f32.powf(db / 20.0).clamp(spec.min, spec.max)+ };+ }+ r+ }+ Show::Pan => {+ // Shown the other way round: the slider's left is the left.+ let mut d = -*v * 100.0;+ let r = ui.add(+ egui::Slider::new(&mut d, -100.0..=100.0)+ .custom_formatter(move |d, _| {+ if d.abs() < 0.05 {+ tr("Center").to_string()+ } else if d < 0.0 {+ format!("{} % L", crate::fmt::num(-d, 1))+ } else {+ format!("{} % R", crate::fmt::num(d, 1))+ }+ })+ .custom_parser(crate::fmt::parse),+ );+ if r.changed() {+ *v = (-d / 100.0).clamp(spec.min, spec.max);+ }+ r+ }+ }+}diff --git a/crates/ui-egui/src/tabs/trimmer.rs b/crates/ui-egui/src/tabs/trimmer.rsindex c73a1f6..e3bd9db 100644--- a/crates/ui-egui/src/tabs/trimmer.rs+++ b/crates/ui-egui/src/tabs/trimmer.rs@@ -1152,7 +1152,7 @@ fn take_frame(ui: &egui::Ui, st: &mut TrimmerState, engine: &bv_engine::Engine)if st.shown == Some(key) {return;}- let img = ColorImage::from_rgba_unmultiplied([f.width as usize, f.height as usize], &f.rgba);+ let img = super::preview::frame_image([f.width as usize, f.height as usize], &f.rgba);match &mut st.texture {Some(t) => t.set(img, TextureOptions::LINEAR),None => {diff --git a/crates/ui-egui/src/timeline/lanes.rs b/crates/ui-egui/src/timeline/lanes.rsindex cbb072b..a8f6ec1 100644--- a/crates/ui-egui/src/timeline/lanes.rs+++ b/crates/ui-egui/src/timeline/lanes.rs@@ -4518,25 +4518,52 @@ pub(super) fn paint_grid(/// it longest; events of other speeds are left alone.pub(crate) fn sync_offsets(project: &Project) -> std::collections::HashMap<ClipId, Tick> {use std::collections::HashMap;- let mut by_media: HashMap<bv_timeline::MediaId, Vec<(TrackKind, &bv_timeline::Clip)>> =- HashMap::new();+ type Events<'a> = Vec<&'a bv_timeline::Clip>;+ // Each media's video events and audio events.+ let mut by_media: HashMap<bv_timeline::MediaId, (Events<'_>, Events<'_>)> = HashMap::new();for (t, c) in project.clips() {if c.freeze.is_none() {- by_media.entry(c.media).or_default().push((t.kind, c));+ let (video, audio) = by_media.entry(c.media).or_default();+ match t.kind {+ TrackKind::Video => video.push(c),+ TrackKind::Audio => audio.push(c),+ }}}// Where the media's start falls on the timeline.let origin = |c: &bv_timeline::Clip| c.start - c.to_timeline(c.source_in);let half_frame = Tick(project.settings.frame_rate.frame_duration().0 / 2);let mut out = HashMap::new();- for events in by_media.values() {- for &(kind, c) in events {- let partner = events- .iter()- .filter(|(k, o)| *k != kind && o.rate == c.rate)- .map(|(_, o)| (o, c.end().min(o.end()) - c.start.max(o.start)))- .filter(|(_, overlap)| *overlap > Tick::ZERO)- .max_by_key(|(_, overlap)| *overlap);+ // Drawn every frame, and one long recording may be cut into thousands+ // of events: only the partners that overlap are looked at. By their+ // starts, with how far the ones so far reach, those that can overlap+ // an event are found going back from where it ends.+ let mut match_with = |events: &[&bv_timeline::Clip], others: &mut Events<'_>| {+ others.sort_by_key(|o| o.start);+ let mut reach = Tick::ZERO;+ let reaches: Vec<Tick> = others+ .iter()+ .map(|o| {+ reach = reach.max(o.end());+ reach+ })+ .collect();+ for c in events {+ let mut partner: Option<(&bv_timeline::Clip, Tick)> = None;+ let until = others.partition_point(|o| o.start < c.end());+ for i in (0..until).rev() {+ if reaches[i] <= c.start {+ break;+ }+ let o = others[i];+ let overlap = c.end().min(o.end()) - c.start.max(o.start);+ if o.rate == c.rate+ && overlap > Tick::ZERO+ && partner.is_none_or(|(_, longest)| overlap > longest)+ {+ partner = Some((o, overlap));+ }+ }if let Some((o, _)) = partner {let d = origin(c) - origin(o);if d.abs() >= half_frame {@@ -4544,6 +4571,10 @@ pub(crate) fn sync_offsets(project: &Project) -> std::collections::HashMap<ClipI}}}+ };+ for (video, audio) in by_media.values_mut() {+ match_with(video, audio);+ match_with(audio, video);}out}@@ -5182,7 +5213,7 @@ pub(crate) fn paint(ClipButton::Generated => (Icon::Generator, ON_EVENT),ClipButton::PanCrop => (Icon::PanCrop,- if clip.transform.is_identity() {+ if clip.pan_crop.is_default() {ON_EVENT} else {theme::banana()@@ -5734,7 +5765,7 @@ mod edge_tests {// A 5 s event from 2 s: edges at 2 s and 7 s.p.insert_media(m, Tick::from_seconds(2), Some(v), None).unwrap();- // 1 s = 100 px: 8 px of snap are 80 ms.+ // 1 s = 100 px: 7 px of snap are 70 ms.let mut view = TimelineView {ticks_per_px: Tick::SECOND.0 as f64 / 100.0,..TimelineView::default()@@ -5743,10 +5774,11 @@ mod edge_tests {let near = Tick::from_seconds_f64(6.95);assert_eq!(view.snap_cursor(&app, &p, near), Tick::from_seconds(7));assert!(view.snap_line.is_some(), "the snap line shows");- // Too far: just onto a frame.- let far = Tick::from_seconds_f64(6.5);+ // Too far (8 px): just onto a frame.let rate = p.settings.frame_rate;- assert_eq!(view.snap_cursor(&app, &p, far), rate.snap_floor(far));+ for far in [6.92, 6.5].map(Tick::from_seconds_f64) {+ assert_eq!(view.snap_cursor(&app, &p, far), rate.snap_floor(far));+ }// Snapping off: no snap.app.snapping = false;assert_eq!(view.snap_cursor(&app, &p, near), rate.snap_floor(near));@@ -5941,6 +5973,36 @@ mod edge_tests {assert_eq!(sync_text(-r30.frame_start(15), r30), "-0:15");}+ #[test]+ fn events_out_of_sync_are_matched_with_their_longest_overlap() {+ use bv_timeline::{Clip, ClipId, Generator, MediaInfo};+ let mut p = Project::default();+ let m = p.add_media(MediaInfo::generated(Generator::ColorBars, &p.settings));+ let s = |n: i64| Tick::from_seconds(n);+ let clip = |id: u64, start: i64, length: i64, from: i64| {+ let mut c = Clip::new(ClipId(id), m, s(start), s(length));+ c.source_in = s(from);+ c+ };+ // A long video event from 0 s, then shorter ones it reaches over.+ p.tracks[0].clips = vec![+ clip(901, 0, 100, 0),+ clip(902, 10, 5, 10),+ clip(903, 20, 5, 20),+ ];+ // The first audio event overlaps only the long one, 3 s off; the+ // second overlaps the long one by 10 s and a short one by 5 s: the+ // long one is its partner, and it is 5 s off.+ p.tracks[1].clips = vec![clip(904, 50, 10, 53), clip(905, 15, 10, 20)];+ let offsets = sync_offsets(&p);+ assert_eq!(offsets[&ClipId(904)], s(-3));+ assert_eq!(offsets[&ClipId(905)], s(-5));+ // The long video event's longest overlap is the second audio event's+ // (as long as the first's: either is its partner).+ assert!([s(3), s(5)].contains(&offsets[&ClipId(901)]));+ assert_eq!(offsets[&ClipId(903)], s(5));+ }+/// The demo at 100 pixels a second, and where `secs` is on `track`.fn demo_view() -> (BananaApp, TimelineView, Layout) {let mut app = BananaApp::new(egui::Context::default());diff --git a/crates/ui-egui/src/timeline/mod.rs b/crates/ui-egui/src/timeline/mod.rsindex 6842d04..6e8c7a3 100644--- a/crates/ui-egui/src/timeline/mod.rs+++ b/crates/ui-egui/src/timeline/mod.rs@@ -745,7 +745,8 @@ impl TimelineView {extra: &[(Tick, SnapKind)],to_cursor: bool,) -> Tick {- const SNAP_PX: f64 = 8.0;+ // How near a point draws what moves, as VEGAS's: 7 pixels.+ const SNAP_PX: f64 = 7.0;self.snap_line = None;// Shift: off when it is on, on when it is off.if app.snapping != self.snap_override {diff --git a/crates/ui-egui/src/track_motion.rs b/crates/ui-egui/src/track_motion.rsindex 63126bc..61f7752 100644--- a/crates/ui-egui/src/track_motion.rs+++ b/crates/ui-egui/src/track_motion.rs@@ -803,10 +803,17 @@ impl TrackMotionWindow {painter.add(Shape::convex_polygon(corners, fill, Stroke::NONE));}let active = if halo_look.is_some() { picture } else { vp };- fxw::paint_f_box(&painter, &sp, &active, tf, rotation);+ fxw::paint_f_box(+ &painter,+ &sp,+ &active,+ (tf.flip_h, tf.flip_v),+ (active.cx, active.cy),+ rotation,+ );if halo_look.is_some() {// The halo's own box, dashed, its handles.- fxw::paint_f_box(&painter, &sp, &vp, &Transform::default(), false);+ fxw::paint_f_box(&painter, &sp, &vp, (false, false), (vp.cx, vp.cy), false);}}diff --git a/crates/ui-egui/src/veg_ui.rs b/crates/ui-egui/src/veg_ui.rsnew file mode 100644index 0000000..4f0c6e9--- /dev/null+++ b/crates/ui-egui/src/veg_ui.rs@@ -0,0 +1,670 @@+//! File › Import and File › Export › VEG Project (`.veg`), and File › Open+//! of its files: another editor's project read as a new, unsaved BananaV+//! project — its media found where it says (or beside it), its video+//! effects BananaV's own of the same names (or the same plug-ins+//! installed) — and a project written as one ([`bv_timeline::veg`]).++use std::collections::BTreeMap;+use std::path::{Path, PathBuf};++use bv_core::{FrameRate, TICKS_PER_SECOND, Tick};+use bv_engine::Engine;+use bv_timeline::veg::{self, DocEffect, DocKey, ParamValue};+use bv_timeline::{+ Effect, KeyCurve, KeyHandles, MediaInfo, PluginFx, PluginKey, PluginParam, PluginValue,+};++use crate::app::BananaApp;+use crate::i18n::tr;++/// The id a `.veg` gives BananaV's own effects' twins.+const VEG_PLUGINS: &str = "com.vegascreativesoftware:";++/// A name without its spaces, signs and case: "Brightness and Contrast"+/// and `brightnessandcontrast` are one.+fn plain(s: &str) -> String {+ s.chars()+ .filter(char::is_ascii_alphanumeric)+ .collect::<String>()+ .to_ascii_lowercase()+}++/// How many numbers a parameter of type `ty` holds (`None`: not numbers).+fn dimensions(ty: bv_ofx::ParamType) -> Option<usize> {+ use bv_ofx::ParamType as T;+ Some(match ty {+ T::Integer | T::Double | T::Boolean | T::Choice => 1,+ T::Double2D | T::Integer2D => 2,+ T::Rgb | T::Double3D | T::Integer3D => 3,+ T::Rgba => 4,+ _ => return None,+ })+}++/// The transitions the file keeps in its own kind, by their classes: known+/// by their presets' names.+const NATIVE_TRANSITIONS: [(&str, &str); 7] = [+ (+ "5856937C-3603-4378-83CF-889423820F39",+ "org.bananav.Portals",+ ),+ (+ "BF8EF6DA-4ED5-4F9C-B549-919490F88B2F",+ "org.bananav.VenetianBlinds",+ ),+ (+ "F4D82040-D40F-44AD-BB24-6AAB29DC21F1",+ "org.bananav.Cascade3D",+ ),+ (+ "573FA5A1-F314-4539-9BB1-77FA92D4E7CD",+ "org.bananav.FlyInOut3D",+ ),+ (+ "E38B2B4A-BA99-4F67-B533-1997297850DD",+ "org.bananav.Shuffle3D",+ ),+ (+ "C843A552-AAEB-411C-8481-CF4C52A336E3",+ "org.bananav.Blinds3D",+ ),+ (+ "E97A8331-D099-440D-AAC5-9B7CC856AE9F",+ "org.bananav.GradientWipe",+ ),+];++/// A time in frames at `rate`.+fn frames_time(frames: f64, rate: FrameRate) -> Tick {+ Tick((frames * TICKS_PER_SECOND as f64 / rate.as_f64()).round() as i64)+}++/// A parameter's numbers as it holds them: a color with its alpha, as+/// many as it has.+fn fitted(mut v: Vec<f64>, ty: bv_ofx::ParamType) -> Vec<f64> {+ if v.len() == 3 && ty == bv_ofx::ParamType::Rgba {+ v.push(1.0);+ }+ if let Some(n) = dimensions(ty) {+ v.truncate(n);+ }+ v+}++/// A parameter's keyframes from the file's, their frames from the effect's+/// start.+fn plugin_keys(keys: &[DocKey], ty: bv_ofx::ParamType, rate: FrameRate) -> Vec<PluginKey> {+ keys.iter()+ .map(|k| {+ let curve = veg::interpolation_curve(k.interpolation);+ let mut key = PluginKey::new(+ frames_time(k.frame, rate),+ PluginValue::Num(fitted(k.value.clone(), ty)),+ curve,+ );+ if matches!(curve, KeyCurve::Bezier | KeyCurve::BezierSplit) {+ key.handles = k+ .handles+ .iter()+ .zip(&k.value)+ .map(|(h, v)| KeyHandles {+ before: (frames_time(h[0] - k.frame, rate), h[1] - v),+ after: (frames_time(h[2] - k.frame, rate), h[3] - v),+ })+ .collect();+ }+ key+ })+ .collect()+}++/// What a record of the file's own kind says of plug-in `id`'s parameters:+/// its 4-byte whole numbers, its numbers with a point and its colors, one+/// after the other, each plug-in with its own (the Gradient Wipe's holds its+/// picture's place among the other program's, which BananaV has not).+fn native_settings(id: &str, d: &[u8]) -> Vec<(&'static str, Vec<f64>)> {+ let bytes = |at: usize, n: usize| d.get(at..at + n);+ let whole = |at: usize| {+ bytes(at, 4)+ .and_then(|b| b.try_into().ok())+ .map(|b| f64::from(i32::from_le_bytes(b)))+ };+ let long = |at: usize| {+ bytes(at, 8)+ .and_then(|b| b.try_into().ok())+ .map(f64::from_le_bytes)+ };+ let fields: Vec<(&'static str, Option<Vec<f64>>)> = {+ let w = |name: &'static str, at: usize| (name, whole(at).map(|v| vec![v]));+ let f = |name: &'static str, at: usize| (name, long(at).map(|v| vec![v]));+ match id {+ "org.bananav.Portals" => {+ let channel = |at: usize| {+ bytes(at, 4)+ .and_then(|b| b.try_into().ok())+ .map(|b| f64::from(f32::from_le_bytes(b)))+ };+ // Blue, green and red, as this file's colors go.+ let color = (|| Some(vec![channel(48)?, channel(44)?, channel(40)?]))();+ vec![+ w("seed", 0),+ w("squares", 4),+ f("maxTransparency", 8),+ f("maxOffset", 16),+ f("maxScale", 24),+ f("borderSize", 32),+ ("borderColor", color),+ ]+ }+ "org.bananav.VenetianBlinds" => {+ vec![f("blinds", 0), f("angle", 8), f("feather", 16)]+ }+ "org.bananav.Cascade3D" => vec![+ w("divisions", 0),+ w("direction", 4),+ f("twist", 8),+ f("specularLight", 16),+ ],+ "org.bananav.Blinds3D" => vec![+ w("divisions", 0),+ w("extraSpins", 4),+ f("stagger", 8),+ f("specularLight", 16),+ w("direction", 24),+ ],+ "org.bananav.FlyInOut3D" => vec![+ f("farX", 0),+ f("farY", 8),+ f("farZ", 16),+ f("rotationsX", 24),+ f("rotationsY", 32),+ f("rotationsZ", 40),+ f("specularLight", 48),+ w("direction", 56),+ ],+ "org.bananav.Shuffle3D" => vec![f("specularLight", 0)],+ "org.bananav.GradientWipe" => vec![f("thresholdBlend", 40)],+ _ => Vec::new(),+ }+ };+ fields+ .into_iter()+ .filter_map(|(name, v)| Some((name, v?)))+ .collect()+}++/// The plug-in for one of the file's own kind: BananaV's of its class, at+/// what its record says, or at its preset of that name when it says nothing.+fn native_effect(class: &str, preset: &str, data: &[u8]) -> Option<Effect> {+ let known = bv_ofx::registry().known();+ let id = NATIVE_TRANSITIONS+ .iter()+ .find(|(c, _)| c.eq_ignore_ascii_case(class))?+ .1;+ let info = known.iter().find(|i| i.identifier == id)?;+ let mut params = crate::presets::builtin_plugin_named(id, |name| plain(name) == plain(preset))+ .unwrap_or_default();+ for (name, value) in native_settings(id, data) {+ params.insert(+ name.to_string(),+ PluginParam {+ value: PluginValue::Num(value),+ keys: Vec::new(),+ },+ );+ }+ Some(Effect::plugin(PluginFx {+ id: info.identifier.clone(),+ version: info.version,+ name: info.label.clone(),+ params,+ }))+}++/// The plug-in a `.veg`'s effect stands for: the same one installed, else+/// BananaV's own of its name; its parameters by their names, with their+/// keyframes.+fn effect_in(e: &DocEffect, rate: FrameRate) -> Option<Effect> {+ if let Some(class) = &e.native {+ return native_effect(class, &e.preset, &e.native_data);+ }+ let known = bv_ofx::registry().known();+ let short = e.plugin.rsplit(':').next().unwrap_or(&e.plugin);+ let names = [short, short.strip_suffix("Transition").unwrap_or(short)];+ let same = |i: &&std::sync::Arc<bv_ofx::PluginInfo>| {+ let last = i.identifier.rsplit('.').next().unwrap_or_default();+ i.identifier.starts_with("org.bananav.")+ && names+ .iter()+ .any(|n| plain(&i.label) == plain(n) || plain(last) == plain(n))+ };+ let info = known+ .iter()+ .find(|i| i.identifier == e.plugin)+ .or_else(|| known.iter().find(same))?;+ let context = if e.transition {+ bv_ofx::Context::Transition+ } else {+ bv_ofx::Context::Filter+ };+ let described = info.context(context).or_else(|| info.described.first())?;+ let find = |name: &str| {+ described+ .params+ .iter()+ .find(|p| plain(&p.name) == plain(name) || plain(&p.label) == plain(name))+ };+ let mut params = BTreeMap::new();+ for (name, value) in &e.params {+ let Some(p) = find(name) else {+ continue;+ };+ // The host moves it along the transition.+ if p.name == bv_engine::plugins::TRANSITION_PARAM {+ continue;+ }+ let value = match value {+ ParamValue::Text(t) => PluginValue::Text(t.clone()),+ _ if dimensions(p.ty).is_none() => continue,+ ParamValue::Number(x) => PluginValue::Num(fitted(vec![*x], p.ty)),+ ParamValue::Integer(x) => PluginValue::Num(fitted(vec![*x as f64], p.ty)),+ ParamValue::Numbers(v) => PluginValue::Num(fitted(v.clone(), p.ty)),+ };+ params.insert(+ p.name.clone(),+ PluginParam {+ value,+ keys: Vec::new(),+ },+ );+ }+ for (name, keys) in &e.keys {+ let Some(p) = find(name).filter(|p| dimensions(p.ty).is_some()) else {+ continue;+ };+ if let Some(param) = params.get_mut(&p.name) {+ param.keys = plugin_keys(keys, p.ty, rate);+ }+ }+ Some(Effect::plugin(PluginFx {+ id: info.identifier.clone(),+ version: info.version,+ name: info.label.clone(),+ params,+ }))+}++/// A curve's number among a parameter's interpolations.+fn interpolation_number(c: KeyCurve) -> i32 {+ match c {+ KeyCurve::Linear => 1,+ KeyCurve::Fast => 2,+ KeyCurve::Slow => 3,+ KeyCurve::Smooth => 4,+ KeyCurve::Sharp => 5,+ KeyCurve::Hold => 6,+ KeyCurve::Bezier => 9,+ KeyCurve::BezierSplit => 10,+ }+}++/// A parameter's keyframes as the file keeps them: the numbers with a+/// point have handles, a tenth of a frame away unless they were set.+fn keys_out(keys: &[PluginKey], ty: Option<bv_ofx::ParamType>, rate: FrameRate) -> Vec<DocKey> {+ use bv_ofx::ParamType as T;+ let frames = |t: Tick| t.0 as f64 * rate.as_f64() / TICKS_PER_SECOND as f64;+ let handled = matches!(ty, Some(T::Double | T::Double2D | T::Double3D));+ let whole = matches!(ty, Some(T::Integer | T::Boolean | T::Choice));+ keys.iter()+ .filter_map(|k| {+ let PluginValue::Num(v) = &k.value else {+ return None;+ };+ let frame = frames(k.at);+ Some(DocKey {+ frame,+ interpolation: if whole {+ 0+ } else {+ interpolation_number(k.curve)+ },+ value: match v.as_slice() {+ // A color without its alpha, as the file's colors are.+ [r, g, b, _] => vec![*r, *g, *b],+ v => v.to_vec(),+ },+ handles: if handled {+ v.iter()+ .enumerate()+ .map(|(c, x)| match k.handles.get(c) {+ Some(h) => [+ frame + frames(h.before.0),+ x + h.before.1,+ frame + frames(h.after.0),+ x + h.after.1,+ ],+ None => [frame - 0.1, *x, frame + 0.1, *x],+ })+ .collect()+ } else {+ Vec::new()+ },+ })+ })+ .collect()+}++/// An effect as a `.veg` holds it: BananaV's own as their twins of the+/// same name, other makers' plug-ins as they are; the parameters that+/// are numbers by their names (an effect's first letter upper case).+/// `None` for the transitions the file keeps in its own kind.+fn effect_out(e: &Effect, rate: FrameRate) -> Option<DocEffect> {+ let fx = e.plugin.as_ref()?;+ if NATIVE_TRANSITIONS.iter().any(|(_, id)| *id == fx.id) {+ return None;+ }+ let known = bv_ofx::registry().known();+ let info = known.iter().find(|i| i.identifier == fx.id);+ let plugin = match (fx.id.as_str(), info) {+ ("org.bananav.WarpFlow", _) => "de.magix:WarpFlowTransition".to_string(),+ ("org.bananav.GLTransition", _) => "de.magix:glTransition".to_string(),+ (id, Some(i)) if id.starts_with("org.bananav.") => {+ format!("{VEG_PLUGINS}{}", plain(&i.label))+ }+ _ => fx.id.clone(),+ };+ let ty = |name: &str| {+ info.and_then(|i| i.described.first())+ .and_then(|d| d.params.iter().find(|p| p.name == name))+ .map(|p| p.ty)+ };+ let integer = |name: &str| {+ use bv_ofx::ParamType;+ matches!(+ ty(name),+ Some(ParamType::Integer | ParamType::Boolean | ParamType::Choice)+ )+ };+ let mut params = Vec::new();+ let mut keys = Vec::new();+ for (name, p) in &fx.params {+ let PluginValue::Num(v) = &p.value else {+ continue;+ };+ let value = match v.as_slice() {+ [x] if integer(name) => ParamValue::Integer(x.round() as i64),+ [x] => ParamValue::Number(*x),+ // A color without its alpha, as the file's colors are.+ [r, g, b, _] => ParamValue::Numbers(vec![*r, *g, *b]),+ [] => continue,+ v => ParamValue::Numbers(v.to_vec()),+ };+ let mut n = name.clone();+ if let Some(first) = n.get(..1) {+ let upper = first.to_ascii_uppercase();+ n.replace_range(..1, &upper);+ }+ if !p.keys.is_empty() {+ keys.push((n.clone(), keys_out(&p.keys, ty(name), rate)));+ }+ params.push((n, value));+ }+ Some(DocEffect {+ plugin,+ preset: String::new(),+ params,+ keys,+ ..Default::default()+ })+}++/// A media file where the project says, else beside the project.+fn locate(path: &str, beside: &Path) -> PathBuf {+ let p = PathBuf::from(path);+ if p.exists() {+ return p;+ }+ let name = path.rsplit(['\\', '/']).next().unwrap_or(path);+ let near = beside.join(name);+ if near.exists() { near } else { p }+}++/// File › Import › VEG Project.+pub(crate) fn import(app: &mut BananaApp) {+ let Some(path) = rfd::FileDialog::new()+ .set_title(tr("Import VEG Project"))+ .add_filter(tr("VEG Project"), &["veg"])+ .add_filter(tr("All Files"), &["*"])+ .pick_file()+ else {+ return;+ };+ open(app, &path);+}++/// Opens `path` as a new, unsaved project, saying what did not come in.+pub(crate) fn open(app: &mut BananaApp, path: &Path) {+ let doc = match std::fs::read(path)+ .map_err(|e| e.to_string())+ .and_then(|bytes| veg::read(&bytes).map_err(|e| e.to_string()))+ {+ Ok(doc) => doc,+ Err(e) => {+ app.report_error(trf!("Could not open the project: {}", e));+ return;+ }+ };+ let beside = path.parent().unwrap_or(Path::new("."));+ let found: Vec<Option<MediaInfo>> = doc+ .media+ .iter()+ .map(|m| {+ if m.generated || m.path.to_ascii_lowercase().ends_with(".veg") {+ return None;+ }+ let at = locate(&m.path, beside);+ Engine::probe_file(&at.to_string_lossy()).ok()+ })+ .collect();+ let base = app.blank_project().settings;+ let imported = veg::build(&doc, &found, &base, &effect_in);+ let events = imported.project.clips().count();+ app.open_imported(imported.project);+ app.settings.touch_recent(path);+ let mut message = trn!(+ events,+ "Project opened: {} event.",+ "Project opened: {} events.",+ events+ );+ let mut add = |text: String| {+ message.push_str(" · ");+ message.push_str(&text);+ };+ let missing = imported.missing.len();+ if missing > 0 {+ let mut names = imported.missing[..missing.min(3)].join(", ");+ if missing > 3 {+ names.push_str(", …");+ }+ add(trn!(+ missing,+ "{} media file was not found: {}.",+ "{} media files were not found: {}.",+ missing,+ names+ ));+ }+ let left = [+ (+ imported.skipped_events,+ trn!(+ imported.skipped_events,+ "{} event of generated media was left out.",+ "{} events of generated media were left out.",+ imported.skipped_events+ ),+ ),+ (+ imported.effects_left,+ trn!(+ imported.effects_left,+ "{} effect has no plug-in in BananaV.",+ "{} effects have no plug-in in BananaV.",+ imported.effects_left+ ),+ ),+ (+ imported.audio_fx_left,+ trn!(+ imported.audio_fx_left,+ "{} audio effect was left out.",+ "{} audio effects were left out.",+ imported.audio_fx_left+ ),+ ),+ (+ imported.envelopes_left,+ trn!(+ imported.envelopes_left,+ "{} envelope was left out.",+ "{} envelopes were left out.",+ imported.envelopes_left+ ),+ ),+ (+ imported.transitions_left,+ trn!(+ imported.transitions_left,+ "{} transition at an event's end was left out.",+ "{} transitions at events' ends were left out.",+ imported.transitions_left+ ),+ ),+ ];+ let mut any = missing > 0;+ for (n, text) in left {+ if n > 0 {+ add(text);+ any = true;+ }+ }+ if any {+ app.report_error(message);+ } else {+ app.notify(message);+ }+}++/// The user's documents folder, as the file's header keeps one.+fn documents() -> String {+ std::env::var_os("USERPROFILE")+ .map(|h| {+ PathBuf::from(h)+ .join("Documents")+ .to_string_lossy()+ .into_owned()+ })+ .unwrap_or_default()+}++/// File › Export › VEG Project.+pub(crate) fn export(app: &mut BananaApp) {+ let stem = app+ .project_path+ .as_ref()+ .and_then(|p| p.file_stem())+ .map_or_else(+ || tr("Untitled").to_string(),+ |s| s.to_string_lossy().into_owned(),+ );+ let Some(path) = rfd::FileDialog::new()+ .set_title(tr("Export VEG Project"))+ .add_filter(tr("VEG Project"), &["veg"])+ .set_file_name(format!("{stem}.veg"))+ .save_file()+ else {+ return;+ };+ let rate = app.project().settings.frame_rate;+ let options = veg::WriteOptions {+ path: path.to_string_lossy().into_owned(),+ documents: documents(),+ effect: &|e| effect_out(e, rate),+ };+ let bytes = veg::write(app.project(), &options);+ match std::fs::write(&path, bytes) {+ Ok(()) => app.notify(trf!("Exported to {}", path.display())),+ Err(e) => app.report_error(trf!("Could not export: {}", e)),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn names_meet_without_spaces_or_case() {+ assert_eq!(plain("Brightness and Contrast"), "brightnessandcontrast");+ assert_eq!(plain("HSL Adjust"), "hsladjust");+ assert_eq!(plain("{Svfx:sepia}"), "svfxsepia");+ }++ /// The transitions of the samples (`BV_VEG_SAMPLES2`, the folder of+ /// `t01_…veg` … `t27_…veg`): each comes in as BananaV's own, its settings+ /// by their names.+ #[test]+ #[ignore = "needs VEGAS's sample projects"]+ fn the_samples_transitions_come_in() {+ let dir = PathBuf::from(std::env::var("BV_VEG_SAMPLES2").expect("BV_VEG_SAMPLES2"));+ bv_engine::plugins::register_own();+ let mut names: Vec<_> = std::fs::read_dir(&dir)+ .expect("folder")+ .filter_map(|e| e.ok()?.file_name().into_string().ok())+ .filter(|n| n.starts_with('t') && n.ends_with(".veg"))+ .collect();+ names.sort();+ let (mut came, mut wrong) = (0, Vec::new());+ for name in &names {+ let bytes = std::fs::read(dir.join(name)).expect("sample");+ let doc = veg::read(&bytes).expect("reads");+ let found = vec![None; doc.media.len()];+ let made = veg::build(&doc, &found, &Default::default(), &effect_in);+ let fx = made+ .project+ .clips()+ .find_map(|(_, c)| c.transition_fx.clone());+ match fx {+ Some(fx) => {+ came += 1;+ let read: Vec<String> = fx+ .params+ .iter()+ .map(|(k, v)| format!("{k}={:?}", v.value))+ .collect();+ eprintln!("{name}: {} {}", fx.id, read.join(", "));+ }+ None => wrong.push(name.clone()),+ }+ assert_eq!(made.effects_left, 0, "{name}");+ }+ eprintln!("{came} of {} came in; not: {wrong:?}", names.len());+ assert!(wrong.is_empty());+ }++ #[test]+ fn media_are_found_beside_the_project() {+ let dir = std::env::temp_dir().join(format!("bv-veg-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ std::fs::write(dir.join("clip.wav"), b"x").unwrap();+ assert_eq!(+ locate("D:\\elsewhere\\clip.wav", &dir),+ dir.join("clip.wav")+ );+ assert_eq!(+ locate("D:\\elsewhere\\gone.wav", &dir),+ PathBuf::from("D:\\elsewhere\\gone.wav")+ );+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/crates/ui-egui/src/vst_ui.rs b/crates/ui-egui/src/vst_ui.rsindex 55f093f..7c61c02 100644--- a/crates/ui-egui/src/vst_ui.rs+++ b/crates/ui-egui/src/vst_ui.rs@@ -447,7 +447,9 @@ pub(crate) fn page(slider = slider.step_by(1.0 / f64::from(p.steps));}let r = ui.add_sized([220.0, 18.0], slider);- if r.double_clicked() {+ if r.double_clicked()+ || crate::widgets::bar_double_clicked(ui, &r, false)+ {x = p.default;}if x != value {diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rsindex 5df2bad..9370a23 100644--- a/crates/ui-egui/src/widgets.rs+++ b/crates/ui-egui/src/widgets.rs@@ -55,6 +55,25 @@ fn check_style(ui: &mut Ui) {}}+/// Whether `slider`'s bar was double-clicked this frame, to put its+/// default back as VEGAS's sliders do: egui's slider senses drags only, so+/// its response never says it was clicked. `value_shown`: its number box+/// is part of the response, after the bar.+pub fn bar_double_clicked(ui: &Ui, slider: &Response, value_shown: bool) -> bool {+ let mut bar = slider.rect;+ if value_shown {+ bar.set_width(ui.spacing().slider_width.min(bar.width()));+ }+ ui.is_enabled()+ && slider.contains_pointer()+ && ui.input(|i| {+ let primary = egui::PointerButton::Primary;+ // A third click soon after counts too (egui counts it apart).+ (i.pointer.button_double_clicked(primary) || i.pointer.button_triple_clicked(primary))+ && i.pointer.interact_pos().is_some_and(|p| bar.contains(p))+ })+}+/// A check box with a clearly visible box.pub fn checkbox(ui: &mut Ui, checked: &mut bool, text: impl Into<egui::WidgetText>) -> Response {ui.scope(|ui| {@@ -531,74 +550,174 @@ pub(crate) fn hue_rgb(angle: f32) -> [f32; 3] {}}-/// Converte o deslocamento RGB numa posição no plano de croma (raio 1 = 0,5).-pub(crate) fn offset_to_point(o: [f32; 3]) -> (f32, f32) {- let m = (o[0] + o[1] + o[2]) / 3.0;- let c = [o[0] - m, o[1] - m, o[2] - m];- let x = c[0] - 0.5 * (c[1] + c[2]);- let y = 0.866_025_4 * (c[1] - c[2]);- (x / 0.5, y / 0.5)-}+/// A Color Grading wheel's radius in its points' units: VEGAS's wheels+/// are 170 pixels across, and their points are kept in those pixels.+pub(crate) const WHEEL_RADIUS: f64 = 85.0;-pub(crate) fn point_to_offset(x: f32, y: f32, master: f32) -> [f32; 3] {- // Inversa exata de `offset_to_point` (com a restrição de média zero).- let r = (x * x + y * y).sqrt();- let (x, y) = if r > 1.0 { (x / r, y / r) } else { (x, y) };- let c0 = x / 1.5;- let d = y / 0.866_025_4;- let c = [c0, (-c0 + d) / 2.0, (-c0 - d) / 2.0];- c.map(|v| v * 0.5 + master)+/// What happened to a Color Grading wheel.+#[derive(Clone, Copy, Debug, PartialEq)]+pub(crate) enum WheelChange {+ /// Its point moved (across, up: pixels of an 85-pixel wheel).+ Moved([f64; 2]),+ /// A double-click: the point back in the middle, the color at its+ /// default.+ Reset,}-/// Where a wheel's point (`offset_to_point`'s plane) shows on the screen,-/// from its middle in radii (y down): the plane turned a quarter, red up,-/// as VEGAS's wheels and the vectorscope have it.-fn wheel_screen((x, y): (f32, f32)) -> egui::Vec2 {- vec2(-y, -x)+/// `p` kept within the wheel: past its edge, on it, the same way round.+fn on_wheel(p: [f64; 2]) -> [f64; 2] {+ let r = p[0].hypot(p[1]);+ if r > WHEEL_RADIUS {+ [p[0] / r * WHEEL_RADIUS, p[1] / r * WHEEL_RADIUS]+ } else {+ p+ }}-/// The point of the plane at a screen offset from a wheel's middle, in-/// radii.-fn wheel_plane(d: egui::Vec2) -> (f32, f32) {- (-d.y, -d.x)+/// The mouse wheel's notches over a widget this frame, and the keys held+/// with them (Ctrl, Alt, Shift).+fn notches_with_keys(events: &[egui::Event]) -> (f32, egui::Modifiers) {+ let mut notches = 0.0;+ let mut keys = egui::Modifiers::NONE;+ for e in events {+ if let egui::Event::MouseWheel {+ unit,+ delta,+ modifiers,+ ..+ } = e+ {+ // Shift may turn the wheel sideways: either way counts.+ let d = if delta.y != 0.0 { delta.y } else { delta.x };+ notches += match unit {+ egui::MouseWheelUnit::Line | egui::MouseWheelUnit::Page => d,+ egui::MouseWheelUnit::Point => d / 40.0,+ };+ keys |= *modifiers;+ }+ }+ (notches, keys)}-/// A wheel as VEGAS 23 draws its own: a dark ball — lighter in the middle-/// — in a ring of hues, red at the top; its crosshair, the ball's meridian-/// through the point and its equator; the point, and a line to it in its-/// color. Dragging moves the color (its mean kept), a double-click brings-/// it back to the middle. `size` is the ring's outer diameter.-pub(crate) fn grading_wheel(ui: &mut Ui, offset: &mut [f32; 3], size: f32) -> Response {- let (rect, mut resp) = ui.allocate_exact_size(vec2(size, size), Sense::click_and_drag());+/// A Color Grading wheel as VEGAS's, `size` across: a dark ball — lighter+/// in the middle — in a ring of the colors its point gives (`color_at`: a+/// point's color), its crosshair, the ball's meridian through the point+/// and its equator; the point (`dot`: across, up, pixels of an 85-pixel+/// wheel), and a line to it in its color. As VEGAS's: dragging the wheel+/// moves the point a twentieth of the way the pointer goes, dragging the+/// point itself a thirty-second (the pointer hidden meanwhile), Ctrl ten+/// times finer; a double-click puts it back in the middle, a right+/// double-click where the pointer is; the mouse wheel moves it a pixel a+/// notch (Ctrl: a tenth) — up and down, Alt across five times as far,+/// Shift out and in, Shift and Alt round five degrees —, and the arrow+/// keys a pixel (Ctrl: a tenth), with Shift out and in and round a degree.+pub(crate) fn grading_wheel(+ ui: &mut Ui,+ size: f32,+ dot: [f64; 2],+ color_at: &dyn Fn([f64; 2]) -> Color32,+) -> (Response, Option<WheelChange>) {+ let (rect, resp) = ui.allocate_exact_size(vec2(size, size), Sense::click_and_drag());let center = rect.center();let radius = size / 2.0 - 5.0;- let master = (offset[0] + offset[1] + offset[2]) / 3.0;- if resp.dragged()+ let scale = radius / WHEEL_RADIUS as f32;+ let screen = |p: [f64; 2]| center + vec2(p[0] as f32, -(p[1] as f32)) * scale;+ let mut change = None;+ let mut to = dot;+ let id = resp.id;+ if resp.clicked() || resp.drag_started() {+ resp.request_focus();+ }+ // Dragging: the point itself or the wheel.+ if resp.drag_started() {+ let from = ui.input(|i| i.pointer.press_origin()).unwrap_or(center);+ let on_dot = from.distance(screen(dot)) <= 7.0;+ ui.data_mut(|d| d.insert_temp(id, on_dot));+ }+ if resp.dragged() {+ let on_dot = ui.data(|d| d.get_temp::<bool>(id)).unwrap_or(false);+ let mut k = if on_dot { 1.0 / 32.0 } else { 1.0 / 20.0 };+ if ui.input(|i| i.modifiers.ctrl) {+ k *= 0.1;+ }+ let d = resp.drag_delta();+ if d != egui::Vec2::ZERO {+ to = on_wheel([to[0] + f64::from(d.x) * k, to[1] - f64::from(d.y) * k]);+ }+ if on_dot {+ ui.ctx().set_cursor_icon(egui::CursorIcon::None);+ }+ }+ if resp.double_clicked() {+ change = Some(WheelChange::Reset);+ }+ if resp.double_clicked_by(egui::PointerButton::Secondary)&& let Some(p) = resp.interact_pointer_pos(){- // Ctrl: finer.- let fine = ui.input(|i| i.modifiers.ctrl);- let (x, y) = if fine {- let (x0, y0) = offset_to_point(*offset);- let (dx, dy) = wheel_plane(resp.drag_delta() / radius * 0.25);- (x0 + dx, y0 + dy)- } else {- wheel_plane((p - center) / radius)- };- *offset = point_to_offset(x, y, master);- resp.mark_changed();+ let d = (p - center) / scale;+ to = on_wheel([f64::from(d.x), -f64::from(d.y)]);}- if resp.double_clicked() {- *offset = [master; 3];- resp.mark_changed();+ // The mouse wheel over it.+ if resp.hovered() {+ let (n, keys) = ui.input(|i| notches_with_keys(&i.events));+ if n != 0.0 {+ let n = f64::from(n);+ let step = if keys.ctrl || keys.command { 0.1 } else { 1.0 };+ let (r, a) = (to[0].hypot(to[1]), to[1].atan2(to[0]));+ to = on_wheel(match (keys.shift, keys.alt) {+ (true, true) => {+ let a = a + (5.0 * n).to_radians();+ [r * a.cos(), r * a.sin()]+ }+ (true, false) => {+ let r = (r + n * step).max(0.0);+ [r * a.cos(), r * a.sin()]+ }+ (false, true) => [to[0] + n * step * 5.0, to[1]],+ // Rolled up, the point goes down, as VEGAS's.+ (false, false) => [to[0], to[1] - n * step],+ });+ ui.input_mut(|i| i.smooth_scroll_delta = egui::Vec2::ZERO);+ }+ }+ // The arrow keys, while it has the focus.+ if resp.has_focus() {+ ui.memory_mut(|m| {+ m.set_focus_lock_filter(+ id,+ egui::EventFilter {+ horizontal_arrows: true,+ vertical_arrows: true,+ ..Default::default()+ },+ );+ });+ let (dx, dy, keys) = ui.input(|i| {+ let k = |key| f64::from(u8::from(i.key_pressed(key)));+ (+ k(egui::Key::ArrowRight) - k(egui::Key::ArrowLeft),+ k(egui::Key::ArrowUp) - k(egui::Key::ArrowDown),+ i.modifiers,+ )+ });+ if dx != 0.0 || dy != 0.0 {+ let step = if keys.ctrl || keys.command { 0.1 } else { 1.0 };+ to = on_wheel(if keys.shift {+ let r = (to[0].hypot(to[1]) + dy * step).max(0.0);+ let a = to[1].atan2(to[0]) - dx.to_radians();+ [r * a.cos(), r * a.sin()]+ } else {+ [to[0] + dx * step, to[1] + dy * step]+ });+ }}- // The joystick moves the point of the wheel under the pointer (its y- // up, the screen's down).+ // The joystick moves the point of the wheel under the pointer.if let Some(v) = joystick_push(ui, &resp) {- let (x, y) = offset_to_point(*offset);- let (dx, dy) = wheel_plane(vec2(v.x, -v.y) * 0.8);- *offset = point_to_offset(x + dx, y + dy, master);- resp.mark_changed();+ let k = 0.8 * WHEEL_RADIUS;+ to = on_wheel([to[0] + f64::from(v.x) * k, to[1] - f64::from(v.y) * k]);+ }+ if change.is_none() && to != dot {+ change = Some(WheelChange::Moved(to));}let painter = ui.painter();let gray = Color32::from_gray;@@ -623,21 +742,15 @@ pub(crate) fn grading_wheel(ui: &mut Ui, offset: &mut [f32; 3], size: f32) -> Re[center - vec2(0.0, radius), center + vec2(0.0, radius)],dark,);- // The point, within the ring.- let (x, y) = offset_to_point(*offset);- let r = (x * x + y * y).sqrt();- let (x, y) = if r > 1.0 { (x / r, y / r) } else { (x, y) };- let r = r.min(1.0);- let point = center + wheel_screen((x, y)) * radius;- let c = hue_rgb(y.atan2(x));- let hue = Color32::from_rgb(- (c[0] * 255.0) as u8,- (c[1] * 255.0) as u8,- (c[2] * 255.0) as u8,- );+ // The point, and the ball turned toward it.+ let shown = match change {+ Some(WheelChange::Moved(p)) => p,+ Some(WheelChange::Reset) => [0.0; 2],+ None => dot,+ };+ let point = screen(shown);+ let r = (shown[0].hypot(shown[1]) / WHEEL_RADIUS).min(1.0) as f32;if r > 0.01 {- // The ball turned toward the point: its equator, and the meridian- // through the point.let u = (point - center) / (r * radius);let v = vec2(-u.y, u.x);let ellipse = |minor: f32| -> Vec<egui::Pos2> {@@ -653,7 +766,8 @@ pub(crate) fn grading_wheel(ui: &mut Ui, offset: &mut [f32; 3], size: f32) -> ReStroke::new(1.0, gray(20)),));painter.add(egui::Shape::line(ellipse(r), Stroke::new(1.0, gray(150))));- // The line to the point, fading toward the middle.+ // The line to the point in its color, fading toward the middle.+ let color = color_at(shown);let steps = 10;for k in 0..steps {let (t0, t1) = (k as f32 / steps as f32, (k + 1) as f32 / steps as f32);@@ -663,30 +777,25 @@ pub(crate) fn grading_wheel(ui: &mut Ui, offset: &mut [f32; 3], size: f32) -> Recenter + (point - center) * t0,center + (point - center) * t1,],- Stroke::new(2.5, hue.gamma_multiply(a)),+ Stroke::new(2.5, color.gamma_multiply(a)),);}}- // The ring of hues: each hue where its point would be.+ // The ring: each color where the point gives it.for i in 0..n {let a0 = i as f32 / n as f32 * std::f32::consts::TAU;let a1 = (i + 1) as f32 / n as f32 * std::f32::consts::TAU;- let mid = (a0 + a1) / 2.0;- let (px, py) = wheel_plane(vec2(mid.cos(), -mid.sin()));- let c = hue_rgb(py.atan2(px));- let color = Color32::from_rgb(- (c[0] * 255.0) as u8,- (c[1] * 255.0) as u8,- (c[2] * 255.0) as u8,- );+ let mid = f64::from((a0 + a1) / 2.0);+ let color = color_at([mid.cos() * WHEEL_RADIUS, mid.sin() * WHEEL_RADIUS]);let at = |a: f32| center + vec2(a.cos(), -a.sin()) * (radius + 2.5);painter.line_segment([at(a0), at(a1)], Stroke::new(5.0, color));}painter.circle_filled(point, 5.0, gray(246));painter.circle_stroke(point, 5.0, Stroke::new(1.0, gray(90)));- resp.on_hover_text(tr(- "Drag to shift the color (Ctrl: finer) · double-click resets",- ))+ let resp = resp.on_hover_text(tr(+ "Drag to move the color (Ctrl: finer) · double-click: reset · right double-click: jump there · mouse wheel: move it (Alt: across, Shift: out and in, Shift+Alt: round)",+ ));+ (resp, change)}/// Icon button painted in its own color (e.g. a red "delete" cross).@@ -970,51 +1079,35 @@ mod tests {assert_eq!(joystick_dead_zone(vec2(0.1, -0.05)), egui::Vec2::ZERO);let full = joystick_dead_zone(vec2(1.0, 0.0));assert!((full.x - 1.0).abs() < 1e-6 && full.y == 0.0);- let mut offset = [0.0f32; 3];- let mut harness = egui_kittest::Harness::new_ui(|ui| {+ let dot = std::cell::Cell::new([0.0f64; 2]);+ let wheel = |ui: &mut Ui| {ui.ctx().data_mut(|d| d.insert_temp(egui::Id::new(JOYSTICK), vec2(1.0, 0.0)));- grading_wheel(ui, &mut offset, 100.0);- });+ let grey = |_: [f64; 2]| Color32::GRAY;+ if let (_, Some(WheelChange::Moved(p))) = grading_wheel(ui, 100.0, dot.get(), &grey) {+ dot.set(p);+ }+ };+ let mut harness = egui_kittest::Harness::new_ui(wheel);// Not under the pointer: nothing moves.harness.run_steps(3);drop(harness);- assert_eq!(offset, [0.0; 3]);- let mut harness = egui_kittest::Harness::new_ui(|ui| {- ui.ctx()- .data_mut(|d| d.insert_temp(egui::Id::new(JOYSTICK), vec2(1.0, 0.0)));- grading_wheel(ui, &mut offset, 100.0);- });+ assert_eq!(dot.get(), [0.0; 2]);+ let mut harness = egui_kittest::Harness::new_ui(wheel);harness.hover_at(pos2(50.0, 50.0));harness.run_steps(5);drop(harness);- // Right on the screen, red up: the plane's y down.- let d = wheel_screen(offset_to_point(offset));- assert!(d.x > 0.0 && d.y.abs() < 1e-3, "pushed right: {d:?}");+ // Right on the screen; kept on the wheel.+ let [x, y] = dot.get();+ assert!(x > 0.0 && y.abs() < 1e-6, "pushed right: {x} {y}");+ assert!(x.hypot(y) <= WHEEL_RADIUS + 1e-9);}#[test]- fn the_wheel_shows_red_at_the_top() {- // Red's point is up; the screen and the plane go both ways.- let red = offset_to_point([0.5, 0.0, 0.0]);- let d = wheel_screen(red);- assert!(d.y < 0.0 && d.x.abs() < 1e-6, "{d:?}");- let (x, y) = wheel_plane(d);- assert!((x - red.0).abs() < 1e-6 && (y - red.1).abs() < 1e-6);- }-- #[test]- fn roda_de_cor_ida_e_volta() {- for (x, y) in [(0.5, 0.0), (0.0, -0.8), (-0.3, 0.4), (0.0, 0.0)] {- let o = point_to_offset(x, y, 0.1);- let (bx, by) = offset_to_point(o);- assert!(- (bx - x).abs() < 1e-3 && (by - y).abs() < 1e-3,- "({x},{y}) → ({bx},{by})"- );- let m = (o[0] + o[1] + o[2]) / 3.0;- assert!((m - 0.1).abs() < 1e-5, "o brilho médio fica no master");- }+ fn a_wheels_point_stays_on_it() {+ assert_eq!(on_wheel([30.0, -40.0]), [30.0, -40.0]);+ let [x, y] = on_wheel([300.0, 400.0]);+ assert!((x - 51.0).abs() < 1e-9 && (y - 68.0).abs() < 1e-9);}#[test]diff --git a/crates/ui-egui/tests/telas.rs b/crates/ui-egui/tests/telas.rsindex ae948cd..a35f83d 100644--- a/crates/ui-egui/tests/telas.rs+++ b/crates/ui-egui/tests/telas.rs@@ -3806,11 +3806,11 @@ fn pancrop_como_o_vegas() {// At the cursor, inside the event: a keyframe there.let c = h.state().clip_by_id_for_review(event).expect("the event");let angle = c- .transform_keys+ .pan_crop+ .keys.iter()- .map(|k| k.value.rotation_deg)- .chain([c.transform.rotation_deg])- .fold(0.0f32, |m, a| if a.abs() > m.abs() { a } else { m });+ .map(|k| k.angle.to_degrees())+ .fold(0.0f64, |m, a| if a.abs() > m.abs() { a } else { m });assert!(angle.abs() > 1.0, "turned {angle}");snap(&mut h, "pancrop_girado");h.get_by_label("Show Properties").click();@@ -3875,7 +3875,7 @@ fn pancrop_quadros_chave_como_o_vegas() {};let curves = |h: &Harness<'_, BananaApp>| -> Vec<KeyCurve> {let c = h.state().clip_by_id_for_review(event).expect("the event");- c.transform_keys.iter().map(|k| k.curve).collect()+ c.pan_crop.keys.iter().map(|k| k.curve).collect()};// A click picks one, Ctrl and a click another; their menu's curve is// both's.@@ -3922,9 +3922,9 @@ fn pancrop_quadros_chave_como_o_vegas() {drag(&mut h, first, first + egui::vec2(60.0, 0.0), None);let c = h.state().clip_by_id_for_review(event).expect("the event");assert!(- c.transform_keys[0].at > bv_core::Tick::ZERO,+ c.pan_crop.keys[0].at > bv_core::Tick::ZERO,"{:?}",- c.transform_keys+ c.pan_crop.keys);snap(&mut h, "pancrop_quadros_chave_primeiro");// The Mask row's properties.@@ -7285,3 +7285,118 @@ fn captura_alcas_padrao() {}}}++/// The panels of the audio effects that follow VEGAS's, each on the demo's+/// audio event at its defaults: `painel_audio_<name>.png`.+/// `BV_AUDIO_PANELS` (names, comma-separated) draws only those.+#[test]+#[ignore = "renders images for visual review"]+fn captura_paineis_audio() {+ let only = std::env::var("BV_AUDIO_PANELS").ok();+ for k in bv_timeline::EffectKind::AUDIO {+ if bv_timeline::audio_fx::presets(k).is_none() {+ continue;+ }+ if let Some(only) = &only+ && !only.split(',').any(|n| n.trim() == k.name())+ {+ continue;+ }+ let mut app = new_app();+ app.load_demo();+ assert!(app.audio_effect_for_review(k), "{k:?}");+ let mut h = Harness::builder()+ .with_size(egui::vec2(1600.0, 960.0))+ .with_pixels_per_point(1.0)+ .wgpu()+ .build_ui_state(+ |ui, app: &mut BananaApp| {+ apply_theme(ui.ctx());+ app.frame(ui);+ },+ app,+ );+ settle(&mut h);+ let name: String = k+ .name()+ .to_lowercase()+ .chars()+ .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })+ .collect();+ snap(&mut h, &format!("painel_audio_{name}"));+ }+}++/// Two clicks, a frame apart each press and release, as a hand makes them.+fn double_click_slowly(h: &mut Harness<'_, BananaApp>, at: egui::Pos2) {+ h.event(egui::Event::PointerMoved(at));+ h.step();+ for _ in 0..2 {+ for pressed in [true, false] {+ h.event(egui::Event::PointerButton {+ pos: at,+ button: egui::PointerButton::Primary,+ pressed,+ modifiers: egui::Modifiers::NONE,+ });+ h.step();+ }+ }+ settle(h);+}++/// A slider's bar double-clicked puts the parameter's default back, as+/// VEGAS's sliders do: in the audio effects' panels, whatever the slider+/// shows (a gain in dB, a pan, a level in dB, a time).+#[test]+fn double_clicking_a_sliders_bar_puts_its_default_back() {+ for (k, count) in [+ (bv_timeline::EffectKind::Volume, 1),+ (bv_timeline::EffectKind::Pan, 1),+ (bv_timeline::EffectKind::StudioGate, 3),+ ] {+ let mut app = new_app();+ app.load_demo();+ assert!(app.audio_effect_for_review(k), "{k:?}");+ let mut h = Harness::builder()+ .with_size(egui::vec2(1600.0, 960.0))+ .with_pixels_per_point(1.0)+ .with_step_dt(1.0 / 60.0)+ .build_ui_state(+ |ui, app: &mut BananaApp| {+ apply_theme(ui.ctx());+ app.frame(ui);+ },+ app,+ );+ settle(&mut h);+ let params = |h: &Harness<'_, BananaApp>| {+ let clip = h.state().clip_for_review().expect("the event");+ let e = clip+ .effects+ .iter()+ .find(|e| e.kind == k)+ .expect("the effect");+ (0..k.params().len())+ .map(|i| e.param(i))+ .collect::<Vec<f32>>()+ };+ let defaults: Vec<f32> = k.params().iter().map(|p| p.default).collect();+ // The panel's sliders, from the top (the window's own ones below).+ let mut bars: Vec<egui::Rect> = h+ .query_all_by_role(egui::accesskit::Role::Slider)+ .map(|n| n.rect())+ .filter(|r| r.top() < 700.0)+ .collect();+ bars.sort_by(|a, b| a.top().total_cmp(&b.top()));+ assert!(bars.len() >= count, "{k:?}: {} sliders", bars.len());+ for bar in &bars[..count] {+ let off = egui::pos2(bar.left() + bar.width() * 0.15, bar.center().y);+ click_at(&mut h, off);+ settle(&mut h);+ assert_ne!(params(&h), defaults, "{k:?}: a click moves it");+ double_click_slowly(&mut h, off);+ assert_eq!(params(&h), defaults, "{k:?}: a double-click puts it back");+ }+ }+}diff --git a/crates/ui-egui/tests/telas_menus.rs b/crates/ui-egui/tests/telas_menus.rsindex 99ee911..d23d251 100644--- a/crates/ui-egui/tests/telas_menus.rs+++ b/crates/ui-egui/tests/telas_menus.rs@@ -473,6 +473,43 @@ fn captura_curvas_de_fade() {snap(&mut h, "fade_ancoras");}+/// File › Import and File › Export, VEG projects among the formats.+#[test]+#[ignore = "renders images for visual review"]+fn captura_menu_arquivo() {+ let mut app = BananaApp::new(egui::Context::default());+ set_language(Language::English);+ app.load_demo();+ app.welcome_for_review("closed");+ let mut h = harness(app);+ settle(&mut h);+ // The menu bar's File, at the window's top.+ let file = h+ .get_all_by_label("File")+ .map(|n| n.rect().center())+ .find(|at| at.y < 40.0)+ .expect("File");+ click_with(&mut h, file, egui::PointerButton::Primary);+ for (submenu, name) in [+ ("Import", "arquivo_importar"),+ ("Export", "arquivo_exportar"),+ ] {+ hover(&mut h, submenu);+ assert!(+ h.query_all_by_label_contains("VEG Project")+ .next()+ .is_some(),+ "{submenu}'s VEG Project"+ );+ snap(&mut h, name);+ }+ click_with(+ &mut h,+ egui::pos2(1500.0, 19.0),+ egui::PointerButton::Primary,+ );+}+/// Media let go with the right mouse button: Add Across Time, Add Across/// Tracks, Add as Takes, Video Only and Audio Only (open), Cancel.#[test]diff --git a/docs/ROADMAP.md b/docs/ROADMAP.mdindex 74787d8..0502aea 100644--- a/docs/ROADMAP.md+++ b/docs/ROADMAP.md@@ -1244,8 +1244,15 @@ items move up to Done.points, Select Neutral Tone, the HSL Curves' Color Selector), ShowLimits on Scopes, the Video Output level, More's Bézier Mask, SamsungLog, the Color Curves' dark look and side by side, dragging the hue- spectrum, and VEGAS's own math once prints measure it. (The graphics- card kernel came with audit pack 139.)+ spectrum. (The graphics card kernel came with audit pack 139.) Since+ 2.0 the effect holds VEGAS's Color Grading's own parameters (each+ wheel's color, Y and point; the curves as VEGAS's text) and works as+ VEGAS's does with the graphics card on — its steps in their order,+ the color held within 0–1 between them —, measured against VEGAS's own+ renders of 20 cases: within one 8-bit level (two in the chained HSL+ Curves), and with VEGAS's 8-bit steps within a level in a few pixels;+ the wheels' points, the sliders, the boxes and the curves' points+ behave as VEGAS's panel's. Older projects' Color Grading values reset.- **Adjust source media (audit pack 65)** — as VEGAS 2026's Help describesit ("Setting project properties"): File › Properties › Video's "Adjustsource media to better match project or render settings", on for new@@ -1274,7 +1281,9 @@ items move up to Done.LUT Filter's kernel (or Apple Log's curve) and its own steps — theColor Wheels, the RL Color Wheels, Levels and Tone, White Balance, HSL,the Curves and the HSL Curves — in one kernel; a test compares them with- the processor.+ the processor. Since 2.0 the kernel works VEGAS's steps (the HSL Curves+ chained, the RL wheels' and the curves' tables, the CDLs, the HSL+ always), the LUTs' passes holding the colors within 0–1.- **The transitions on the graphics card (audit pack 138)** — BananaV's 24own transitions (the wipes, the irises and stars, Push, Slide, Squeeze,Split, Swap, Zoom, Spiral, Flash, Dissolve, Cross Effect, Portals, the 3D@@ -2427,6 +2436,92 @@ items move up to Done.counted 24 points short, so the last button ran under the icons). Thescroll buttons' look and place are BananaV's own until a print showsVEGAS's.+- **VEG projects, imported and exported** — File › Import and File ›+ Export › VEG Project, and File › Open of `.veg` files: the project's+ settings (frame size and rate, sample rate, the ruler's timecode,+ tempo), its media (where the project says, else beside it, else+ offline), the video and audio tracks (names, volume and pan, mute,+ compositing mode and level), the events with their takes, fades and+ fade curves, speed, pitch and mute, the groups, the tracks' envelopes+ (volume, pan, bus sends, composite level, fade to color), video effects+ by their names (BananaV's own, or the same plug-ins installed),+ markers, regions, command markers, the CD layout, the summary and the+ project's comments, busses and bins. Read from the 40 test projects+ VEGAS saved, every field they were made to show, and written back with+ VEGAS's chunks in its order and its default structures. Since then: the+ effects' parameters of every size (the Color Corrector's wheels, two+ numbers each), the events' levels (volume, opacity), and the audio+ effects of the tracks' and events' chains that BananaV has — 20 of+ VEGAS's DirectX ones, among them a new track's Track Noise Gate, Track+ EQ and Track Compressor, their settings read field by field; File ›+ Import calls it experimental. Left out, and counted when a project+ opens: generated media's events, the other audio effects (the graphs',+ the Express ones, Wave Hammer, other makers'), transitions, Pan/Crop,+ the events' envelopes. Still to see: VEGAS opening a project BananaV+ wrote, and the settings of every audio effect checked against projects+ VEGAS saved with each one at a preset.+- **Smooth again** — the kernels' compilation (63 s in a release build, one+ after another, and a minute or two with the processor busy) kept the+ preview on the processor after every start: now the card draws as soon+ as it opens, the kernels compile apart in parallel (6.5 s), and the three+ slowest fell from 49 s to under 1 s (their `var<workgroup>` tables no+ longer zeroed). A 1080p60 event with two effects plays at 60 pictures a+ second, evenly, using about one core where it took eight at 15. The+ window paints when frames are due instead of as often as the screen+ allows (140 times a second), the Explorer's tree no longer touches the+ disks every frame, frames reach the screen without a conversion per+ pixel, and matching events out of sync no longer compares every pair+ each frame (a long recording cut into thousands of events).+- **A Windows installer (0.2.0)** — `packaging/windows/bananav.iss` (Inno+ Setup, built and tried out by `package.yml` on x64 and ARM64): for one+ user, without an administrator password, in English or Brazilian+ Portuguese by the system's language; a Start menu shortcut, a desktop one+ and `.bvproj` files opening in BananaV if wanted, BananaV started at the+ end, and an uninstaller that leaves settings and projects. The website's+ Windows download is the installer; the zip stays on the Releases page.+- **The timeline's details, from VEGAS's default keyboard map and curves**+ — the Sharp curve is VEGAS's 4p³ − 6p² + 3p in fades, envelopes and+ keyframes (it was the smoothstep's inverse); snapping reaches 7+ pixels, as VEGAS's; Esc stops playback, the edit cursor staying; the+ Trimmer's W and E go to its start and end; the peak files VEGAS leaves+ beside media (`.sfk`: the minimum and maximum of every 256 samples)+ give their waveforms without reading the sound — not one of another+ version of the file, and not after Rebuild Audio Peaks.+- **Pan/Crop rebuilt, checked against VEGAS's renders** — an event's Pan/Crop is now a+ box in its media's pixels (width, height, center, angle, pivot, curve,+ smoothness), as the file keeps it; between keyframes the size, angle+ and pivot move in a straight line, the center's turning undone around it+ and the pivot on an X-spline with the smoothness as its tension. Output:+ Maintain aspect ratio and Stretch to fill, hard edges and a Catmull-Rom+ whose end pixels land on each other for a straight box, soft edges for a+ turned or mirrored one, on the processor and on the card. Masks: 16 bands a+ line, a recursive Gaussian, a curve for one-way feathers. Checked+ through the `.veg` reader against VEGAS's renders, frame by frame:+ geometry, 28 cases: 0.060/255 at worst on average, the 17 straight boxes+ at most one level off anywhere, the 11 turned or mirrored ones 7 to 19+ levels on a few pixels of their edges (about 0.2% of the frame over 2+ levels); masks, 19 cases: identical pixel by pixel. The window: the pivot dragged, each+ keyframe's own look of a path, the aspect ratio presets (1:1, 4:3, 16:9,+ 1.85:1), Resize Adjustment Event to Project in its menu.+- **VEG: what an edit leaves** — the reader now brings transitions (27 of+ 27: 20 by their parameters, 7 of the file's own kind by the record of+ their settings), their progress envelopes, the 51 audio effects at their+ settings (39 DirectX ones including the graphs', 11 studio ones, the+ Modern Equalizer) with their bypass, keyframes of every effect parameter+ (numbers, points, colors, choices, with Bézier handles) and texts,+ effects before the Pan/Crop or switched off, velocity, normalize, channels+ and phase of events, Resample, Reduce Interlace and Undersample, Track+ Motion, its shadow, glow and 3D box, Parent Motion and compositing+ children, the track's phase and sends, and the busses' faders, mutes,+ solos, effects and envelopes. An old mistake fixed: an envelope's kind was+ read and written at the wrong byte, so every envelope was a volume one.+ Export writes all of it but the audio chains: its structures are VEGAS's+ byte for byte on the samples, and it reads back the same. Checked on+ VEGAS's own sample projects (`BV_VEG_SAMPLES`, `BV_VEG_SAMPLES2`). Not+ brought in: a transition at an event's end (BananaV's stand at entrances,+ counted when a project opens), the Gradient Wipe's own pictures, pan up and+ down and center level, effect automation (no sample has it). Still to+ see: VEGAS opening what BananaV wrote.## In progressdiff --git a/docs/STANDARDS.md b/docs/STANDARDS.mdindex 25a4f56..16db530 100644--- a/docs/STANDARDS.md+++ b/docs/STANDARDS.md@@ -83,6 +83,7 @@ What hosting OFX takes (and how BananaV does it):|---|---|---|| **EDL** (CMX 3600 cut lists). | De facto standard, free. | **Done** (import and export). || **Final Cut Pro 7 XML**. | Documented by Apple, free to read and write. | **Done** (import and export: Final Cut Pro 7's, DaVinci Resolve's, Premiere's and VEGAS's files — cuts, crossfades and fades, stereo pairs and a file's streams, links, opacity and gain, speeds, titles, colors, nested sequences, markers; Pan/Crop still to come; FCPXML too). |+| **VEG projects** (`.veg`): VEGAS's project files. | No published specification: read and written from what the files themselves hold, for interoperability (none of VEGAS's code or assets). | **Done, awaiting review** (import and export: settings, media, tracks, events with takes and fades, envelopes, video effects by their names with their keyframes, transitions, Pan/Crop and masks, Track Motion, markers, regions, command markers, the CD layout, the summary, busses and bins; import too: the audio effects' chains; export of those chains still to come). || **OpenTimelineIO** (OTIO, Academy Software Foundation): `.otio`, and the bundles `.otioz` and `.otiod`. | Apache-2.0; the file format is a published specification. | **Done** (import and export, written from the specification, no OTIO code): timelines to and from DaVinci Resolve (18.5+), Premiere Pro (25.6+) and Kdenlive — cuts, timing, crossfades and fades, speeds, markers; BananaV's own projects whole through its metadata. |AAF, which VEGAS also imports and exports, has a license of its own: seediff --git a/docs/architecture.md b/docs/architecture.mdindex acde79c..f7bcd3b 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -207,6 +207,68 @@ layers (`cargo xtask layers` enforces it):or a timeline dropped on the window opens as with File › Open — aproject dropped on the timeline is nested instead (media dropped go tothe project).+- The graphics card is usable as soon as it opens (`accel.rs`): frames draw+ on it while `Gpu::warm_up` compiles the kernels on a few threads of low+ priority, each frame waiting only for the kernels it uses (`Kernels::+ pipeline`: a cell each, the compiler outside the map's lock). The window+ paints while playing when the project's next frame is due+ (`until_next_picture`, 60 times a second at least), not as often as the+ screen allows; the preview's thread wakes it only for a frame already+ late. What the Explorer's tree shows of the disks is read on a thread of+ its own (`TreeRoots`): no frame touches a disk.+- An event's Pan/Crop (`bv_timeline::pancrop`): a box in its media's pixels+ over time (`PanCropKey`: width and height, negative when mirrored, center,+ angle, where it turns, smoothness; `Clip::pan_crop`), the file's terms, kept+ on the model so nothing rounds it. `PanCrop::at_time` interpolates at the+ 100 ns the frame's time truncates to: size, angle, pivot and smoothness in a+ straight line, the center's rotation undone before the line and done again+ after, the pivot along an X-spline whose tension is the smoothness.+ `place_in` then `place()` give a `Placement` of the frame: a turned or+ mirrored box a parallelogram of its corners, with soft edges (coverage by+ 16 bands) and the media's edges read as the renderers' `held`/`open` do; a+ straight one a rectangle in fixed point with hard edges, and at Best a+ Catmull-Rom whose rectangle's end pixels land on each other+ (`Placement::in_picture`). `bv_render::layer::place_box` and the card's+ `place_hard`/`place_soft` draw it. Projects saved before come in through+ `Project::upgrade_pan_crops`. Measured frame by frame against another+ program's renders through the `.veg` reader (`bv-engine`'s+ `pan_crop_renders`).+- VEG projects (File › Import and File › Export › VEG Project, and File ›+ Open of `.veg` files): `bv_timeline::veg` reads and writes the format+ from what its files hold — Wave64's RIFF of 64 bits (`riff.rs`: chunks+ named by GUIDs, their sizes counting their 24-byte headers, each on a+ multiple of 8 bytes from the file's start) — into a document+ (`read.rs`: the header's settings, the media, the tracks with their+ events, takes, fades and curves, envelopes, the effects, transitions,+ Pan/Crops and masks, the tracks' motions, markers, regions, command+ markers, the CD layout, groups, the summary's texts, the mixer's busses+ and bins; times in hundreds of nanoseconds, `ticks` and `units`) that+ `build.rs` makes a project of once the caller found the media+ (`Imported` counts what stayed out: generated media's events, effects+ without a plug-in, envelopes BananaV has no place for, transitions at+ events' ends), and back (`write.rs`, in the chunks' order and with the+ default structures the format's own files have). An envelope's kind is+ at its structure's byte 8; a transition's progress places count parts of+ a million of its fade. An effect's parameters are records of their+ value's size followed by their keyframes (`read::param_body`: the sizes+ tell a value's and a keyframe's kind apart; keyframes in frames from the+ effect's start, handles as absolute frames and values) or a text; the+ file's own kind of effect, its seven transitions (`DocEffect::native`),+ is a class, a preset's name and a plain record of its settings, which+ `veg_ui::native_settings` reads. The audio effects' chains are their+ plug-ins' classes, names, bypass switches and settings+ (`read::audio_chain`), and `audio.rs` turns the 51 BananaV has into its+ effects: DirectX records field by field (a number's byte, whole, with a+ point or long, and how it becomes the parameter), graphs by their counts+ and points (`graphs`), the studio effects' programs of normalized values+ (`studio`: a bent line by where each range's middle falls), the Modern+ Equalizer's state (`modern_eq`: its text holds its bytes as letters of+ 6 bits). `pancrop.rs` reads and writes the Pan/Crop's chunk, a RIFF of+ 32 bits inside the block. `veg_ui.rs` is the interface's side: media+ where the project says or beside it, the video effects and transitions+ BananaV's own of the same names or the same plug-ins installed+ (`effect_in`, `effect_out`), and the+ status line saying what did not come in.- Nested projects (VEGAS's "Nesting projects"): a project file is media(`bv_media`'s `nested.rs`: its length, its output's picture when it hasvideo events, stereo sound when it has audio events, its markers and@@ -387,14 +449,16 @@ layers (`cargo xtask layers` enforces it):`bv_timeline::mask` — closed Bézier paths in the media's pixels, eachpositive, negative or disabled with its opacity, feather andanti-aliasing, their shapes keyframed anchor by anchor, kept through- cuts, trims and joins; `PanCropMask::coverage` is the exact rasterizer,- its rows and distance transform on the processor's threads,- `bv_color::par_rows`)+ cuts, trims and joins; `mask_raster.rs` is the rasterizer, checked+ pixel by pixel against rendered frames: paths cut into monotone pieces, 16+ bands a line with their coverage summed by groups, even-odd, a 4th-order+ recursive Gaussian on 32-bit floats for the feather, each path combined+ with those before)reach both renderers as `MediaLayer::mask_picture`, the masks' coverageat the picture's size — the last two kept by `PanCropMask::fingerprint`,so masks that do not change are worked out once, and kept on the card- too — framed as the picture is (`place_par`, the card's- `place`): after the event's framed effects it cuts the picture, or with+ too — framed as the picture is (`place_box`, the card's+ `place_hard` and `place_soft`): after the event's framed effects it cuts the picture, or withApply to FX mixes the picture without them and with them (the card's`blend` kernel's modes 101 and 102, then Add). The Pan/Crop window'sMask row (`pancrop_keys::KeyRow`) gives its toolbar, properties and@@ -845,9 +909,16 @@ layers (`cargo xtask layers` enforces it):Event FX is `nonrealtime_ui.rs`, on the engine's `nonrealtime.rs`: themedia samples an event plays (between the media times of its start andend; not reversed or frozen) through its audio effects- (`bv_mixer::dsp::Chain`) into a new WAV file, in the background, which- joins the project as the event's new take (`Project::add_take`), the- effects taken off the event as asked; Auto Ducking is+ (`bv_mixer::dsp::Chain`, their lateness taken back; the effects that+ change the sound's length — `EffectKind::works_offline` — on all of it+ at once through `bv_mixer::render_offline`) into a new WAV file, in the+ background, which joins the project as the event's new take+ (`Project::add_take`), the effects taken off the event as asked. While+ it plays, an event whose chain has such an effect plays its sound made+ through the whole chain the same way (`bv_mixer`'s `prerender.rs`: made+ on a thread of its own when the pool mixes live — `AudioPool::set_live`+ — the last one made playing meanwhile, at once when rendering), as long+ as the event; Auto Ducking is`bv_timeline::ducking` — a controller track's reductions(`Track::ducking`: Floor Reduction while it sounds, Peak Reduction moreas it gets louder) and listener tracks (`Track::duck_listener`); each of@@ -1101,19 +1172,37 @@ layers (`cargo xtask layers` enforces it):Crop, `crop.rs` (VEGAS's: each pixel kept, times Opacity, when itscorner is inside the window — no smoothing —, the window turnedclockwise by Angle), Color Curves, `color_curves.rs`, Color Grading,- `color_grading.rs` (the Color Grading window's effect, as VEGAS's Help- lays the window's sections out — a Camera LUT (a `.cube` file, or- Apple Log's published curve to linear or to Rec. 709), the Color- Wheels' Lift, Gamma, Gain and Offset (a color and a master Y each), the- RL Color Wheels within two luma thresholds, Levels, Tone, White- Balance, HSL, the Curves (Brightness, Red, Green, Blue) and the HSL- Curves (hue ones wrapping round red), then a Look LUT, each LUT at its- strength; BananaV's math until the user's prints measure VEGAS's;- `cube` bakes a grade into a `.cube` file, `Engine::color_grading_cube`,- and `pick` works out what the pickers set from the colors picked,- `Engine::color_grading_pick`; on the card its LUTs are LUT Filter's- kernel or Apple Log's, `apple_log`, and its own steps the `grade` kernel- on a buffer of its settings and tables, `accel::GradePlan`) — the panel is `tabs/color.rs`, laid out as VEGAS 23's (the user's+ `color_grading.rs` (the Color Grading window's effect, version 2.0:+ VEGAS's Color Grading's own parameters — each wheel's red, green, blue+ and Y and its point, U and V; the RL wheels and their thresholds; the+ ten curves as VEGAS's text, `N:x:y:ix:iy:ox:oy:…`; Levels, Tone, White+ Balance, HSL; the Camera and Look LUTs (on, file — or Apple Log's+ published curve to linear or Rec. 709 —, interpolation, strength) —,+ all hidden, the window edits them; its work is `grading.rs`, as VEGAS's+ with the graphics card on: the Camera LUT, the HSL Curves one after+ another (each keyed on what the one before made), White Balance+ (Robertson's isotemperature lines and a cone matrix between the values+ raised to 2.4 and back), Levels, the RL wheels' and the Color Curves'+ tables (Bézier curves sampled with a single Newton step, as VEGAS's),+ Lift, two CDLs (Gain, Offset and Gamma by channel, then by Y),+ Saturation, Exposure, Brightness, Contrast, the panel's Exposure and+ the HSL always, then the Look LUT, the color held within 0–1 between+ the steps; `Grade::quantize` makes the steps 8-bit as VEGAS's are (cut+ to 12 bits, then rounded) for measuring: the ignored+ `matches_vegas_renders` compares the grade with VEGAS's own renders of+ 20 cases, `BV_GRADING_INPUT`, `BV_GRADING_RENDERS`, `BV_GRADING_LUTS`+ (within a level in a few pixels; as BananaV renders, in floating+ point, within one, two in the chained HSL Curves); `wheel_values` and+ `wheel_point` turn a wheel's point into its color and back, as VEGAS's+ panel does; `cube` bakes a grade into a `.cube` file,+ `Engine::color_grading_cube`, and `pick` works out what the pickers set+ from the colors picked — Lift's and Gain's channels between their ends+ as VEGAS's eyedroppers, a white balance that leaves the color grey, the+ Color Selector's points —, `Engine::color_grading_pick`; on the card+ its LUTs are LUT Filter's kernel or Apple Log's, `apple_log`, holding+ the colors within 0–1, and its own steps the `grade` kernel on a buffer+ of its settings, a row each, and its tables, `accel::GradePlan`) — the+ panel is `tabs/color.rs`, laid out as VEGAS 23's (the user'sprints): its header the FX level's menu — event, track, media, videooutput; the event's, track's and media's menus and the Video Preview'sopen it there — and what it grades, Bypass Color Grading, Reset All,@@ -1135,11 +1224,23 @@ layers (`cargo xtask layers` enforces it):the cursor through`ofx::value_now`/`set_now`, the effect added by the first change; thewheel is `widgets::grading_wheel`, drawn as VEGAS's (a shaded ball in a- ring of hues, red at the top as on the vectorscope — `wheel_screen` —,- its crosshair, the ball's meridian through the point and its equator);- the HSL Curves' editor has VEGAS's- tangents' handles, point menu and arrow keys (`ofx_curves`'- `move_handle`, `lock_handles`); the pickers — Lift's black point,+ ring of the colors its point gives, red at the top as on the+ vectorscope, its crosshair, the ball's meridian through the point and+ its equator) and handled as VEGAS's (`WheelChange`: the wheel dragged+ at a twentieth of the pointer, the point itself at a thirty-second,+ Ctrl ten times finer; a double-click resets it, a right double-click+ jumps; the mouse wheel moves it up and down, with Alt across, Shift out+ and in, Shift and Alt round; the arrow keys too), its point given in+ VEGAS's 85-pixel units; the sliders and boxes are VEGAS's (`slide`: the+ knob dragged, a click beside it a tenth, a double-click the default,+ the mouse wheel a hundredth, Ctrl a thousandth; `number_box`, three+ decimals); every curve point has handles, as VEGAS's+ (`grading_curves`' `add_dot`: a double-click adds one along its+ neighbours' line, `flatten`: on a point makes its handles level,+ `smooth`), the HSL Curves 0.5 where they change nothing; the HSL Curves'+ editor has VEGAS's tangents' handles, point menu and arrow keys+ (`ofx_curves`' `move_handle`, `lock_handles`), its swatches add a color+ and its two neighbours; the pickers — Lift's black point,Gain's white point, Select Neutral Tone, the HSL Curves' ColorSelector — wait for a click or a rectangle on the Video Preview(`pick_on_preview`, the color under the pointer read out) and read the@@ -2867,8 +2968,9 @@ layers (`cargo xtask layers` enforces it):checks with `--cfg bv_no_ffmpeg`. `LINUX_TARGET=aarch64-unknown-linux-gnu`checks ARM64.- Packages: `gh workflow run package.yml` makes, as the run's artifacts- (nothing is published), zips for Windows x64 and ARM64 (the C runtime- inside) and AppImages for Linux x64 and ARM64, built on Ubuntu 22.04+ (nothing is published), zips and installers for Windows x64 and ARM64 (the+ C runtime inside; `packaging/windows/bananav.iss`, Inno Setup, the installer+ tried out on the runner) and AppImages for Linux x64 and ARM64, built on Ubuntu 22.04with an FFmpeg built under the LGPL (`packaging/linux/build_ffmpeg.sh`:no x264 or x265 while BananaV's license is open). The icon is BananaV'sofficial logo (`packaging/icons`: `bananav-icon.svg`, the rounded icon;diff --git a/docs/testing.md b/docs/testing.mdindex 0ad5bc6..1b3b276 100644--- a/docs/testing.md+++ b/docs/testing.md@@ -33,6 +33,32 @@ with the user's prints and the graphics card's parity tests.and `BV_PREVIEW_TRACE`, and `APPDATA` and `LOCALAPPDATA` pointing tocopies, it measures the interface and the preview without touching theuser's settings.+- Why it feels slow: `BV_FRAME_TRACE=1` gives each frame of the window (how+ long after the last one, how long it took, the preview's picture, what+ asked for it), `BV_PREVIEW_TRACE=1` each frame drawn, `BV_GPU_TRACE=1` each+ kernel's compile time (`cargo test --release -p bv-gpu --test warmup --+ --ignored --nocapture`: a debug build compiles kernels without+ optimizing them, far faster than a release build does).+ `tools/stacks.cs` samples the threads of a running BananaV, its first+ lines telling how to build it and a copy with symbols. While playing, the+ window should paint about 60 times a second, its pictures evenly apart,+ and a frame's time stay well under that: compare with these (Ryzen+ 16 threads, RTX 4070, a 1080p60 H.264 event with two effects):+ 60.0 pictures a second, 16.2–17.1 ms apart, none skipped, a little over+ a processor core in all. Measure with BananaV in front and nobody using+ the computer: with another window in front or the screen locked the same+ build gives 15–50 pictures a second.+- Against another program's files, none of them in the repository:+ `BV_VEG_SAMPLES=<first samples' folder> BV_VEG_SAMPLES2=<second samples'+ folder> BV_PANCROP_SAMPLES=<Pan/Crop cases' folder> cargo test -p bv-timeline+ --lib veg::+ -- --include-ignored` reads each sample as it says and writes it back,+ structure by structure; `BV_VEG_SAMPLES2=… cargo test -p bv-ui-egui --lib+ the_samples_transitions -- --ignored` brings its 27 transitions in;+ `BV_PANCROP_SAMPLES=<folder> BV_PANCROP_OUT=<folder> cargo test -p bv-engine+ --test pan_crop_renders -- --ignored --nocapture > out.txt` draws its+ Pan/Crop cases and compares them with the program's renders, frame by+ frame (`BV_PANCROP_FRAMES=1` lists each frame).- Media oracles: ffmpeg/ffprobe on PATH (development only; on Linux theytest FFmpeg's backend too, and `bv-mf --test ffmpeg` checks it withoutthem: a movie written and read back). Fixtures live indiff --git a/packaging/icons/README.md b/packaging/icons/README.mdindex 3959e7a..c2dde96 100644--- a/packaging/icons/README.md+++ b/packaging/icons/README.md@@ -8,6 +8,7 @@ The official logo (the banana and the V), in three versions:| `bananav-logo.svg` | The logo on its dark square (square corners). || `bananav-logo-transparent.svg` | The logo alone, on a transparent background. The interface draws it (toolbar, welcome screen, Explorer): `crates/ui-egui/src/icons/logo.rs` has its paths. || `bananav.png` | `bananav-icon.svg` at 256 × 256 pixels, corners transparent. The AppImage (`.github/workflows/package.yml`) and the main window (`window_icon` in `crates/ui-egui/src/lib.rs`) use it. |+| `bananav.ico` | `bananav.png` at sizes from 16 to 256 pixels. The Windows installer and its shortcuts use it (`packaging/windows/bananav.iss`). |`bananav.png` is the icon's SVG rendered at 256 px (for example by a browser,on a transparent background): render it again if the icon changes. If the logodiff --git a/packaging/icons/bananav.ico b/packaging/icons/bananav.iconew file mode 100644index 0000000..3150d6aBinary files /dev/null and b/packaging/icons/bananav.ico differdiff --git a/packaging/icons/bananav.ico.attribution b/packaging/icons/bananav.ico.attributionnew file mode 100644index 0000000..37f1c10--- /dev/null+++ b/packaging/icons/bananav.ico.attribution@@ -0,0 +1,10 @@+asset: bananav.ico+title: BananaV's application icon, sixteen to 256 pixels+author: @acasoq-web, BananaV's owner+source: original work+license: GPL-3.0-or-later+license-file: LICENSE+added: 2026-11-04 by @acasoq-web+notes: bananav.png at each size. Used by the Windows installer and its+ shortcuts (packaging/windows/bananav.iss).+ The name and the logo as marks: TRADEMARKS.md (draft).diff --git a/packaging/linux/README.txt b/packaging/linux/README.txtindex e7cb4c1..d5a4a46 100644--- a/packaging/linux/README.txt+++ b/packaging/linux/README.txt@@ -1,12 +1,8 @@BananaV — video editor (Linux)==============================-ULTRA ALPHA BUILD-- This is a very early test build. Expect missing features, bugs and- crashes. Do not use it for important work, keep copies of your media- and projects, and expect projects saved now not to open in later builds.-- Tell us what breaks: https://discord.gg/vtC7Yasz98- Website: https://bananav-editor.github.io/+- Help and community: https://discord.gg/vtC7Yasz98Make the AppImage executable (chmod +x BananaV-*.AppImage) and run it.Nothing to install.@@ -37,8 +33,7 @@ LicenseFree Software Foundation, either version 3 of the License, or (at youroption) any later version (LICENSE.txt, beside this file). It comeswith ABSOLUTELY NO WARRANTY.-- Its source code will be published at https://github.com/acasoq-web/BananaV- soon, with the first public release.+- Its source code is at https://github.com/acasoq-web/BananaV.- The open-source libraries it is built with, and their licenses, are inTHIRD-PARTY-NOTICES.txt; the system libraries the AppImage carries, andtheirs, in SYSTEM-LIBRARIES-NOTICES.txt, beside this file.diff --git a/packaging/windows/README.txt b/packaging/windows/README.txtindex 55e85a2..1fca035 100644--- a/packaging/windows/README.txt+++ b/packaging/windows/README.txt@@ -1,16 +1,14 @@BananaV — video editor (Windows)================================-ULTRA ALPHA BUILD-- This is a very early test build. Expect missing features, bugs and- crashes. Do not use it for important work, keep copies of your media- and projects, and expect projects saved now not to open in later builds.-- Tell us what breaks: https://discord.gg/vtC7Yasz98- Website: https://bananav-editor.github.io/+- Help and community: https://discord.gg/vtC7Yasz98-Run BananaV.exe. Nothing to install: it runs from any folder. The build-is not signed yet, so Windows may warn about an unknown publisher the-first time ("More info", then "Run anyway").+The installer (BananaV-...-setup.exe) puts BananaV in your Start menu, with+no administrator password, and Settings > Apps uninstalls it. The zip needs+no installation: unpack it anywhere and run BananaV.exe. The builds are not+signed yet, so Windows may warn about an unknown publisher the first time+("More info", then "Run anyway").Requirements- Windows 10 or 11: the x64 package on Intel and AMD processors, the ARM64@@ -32,8 +30,7 @@ LicenseFree Software Foundation, either version 3 of the License, or (at youroption) any later version (LICENSE.txt, beside this file). It comeswith ABSOLUTELY NO WARRANTY.-- Its source code will be published at https://github.com/acasoq-web/BananaV- soon, with the first public release.+- Its source code is at https://github.com/acasoq-web/BananaV.- The open-source libraries it is built with, and their licenses, are inTHIRD-PARTY-NOTICES.txt, beside this file.diff --git a/packaging/windows/bananav.iss b/packaging/windows/bananav.issnew file mode 100644index 0000000..37d0fe4--- /dev/null+++ b/packaging/windows/bananav.iss@@ -0,0 +1,83 @@+; BananaV's Windows installer (Inno Setup 6). For one user, no administrator+; needed: it goes to %LOCALAPPDATA%\Programs\BananaV, with a shortcut in the+; Start menu, one on the desktop if wanted, and BananaV's project files opening+; in it. Uninstalling leaves the user's settings and projects where they are.+;+; Built by .github/workflows/package.yml:+; ISCC /DAppVersion=0.2.0 /DArch=x64 /DFiles=<folder of the zip's files>+; /O<output folder> /F<file name> packaging\windows\bananav.iss++#ifndef AppVersion+ #define AppVersion "0.0.0"+#endif+#ifndef Arch+ #define Arch "x64"+#endif+#ifndef Files+ #error Say where the files are: /DFiles=<folder>+#endif++[Setup]+; The installation's identity: updates find it by this, so it never changes.+AppId={{6DEA8E75-09B5-4CBD-8BDF-E7AA3C85FFD5}+AppName=BananaV+AppVersion={#AppVersion}+AppVerName=BananaV {#AppVersion}+AppPublisher=BananaV+AppPublisherURL=https://bananav-editor.github.io/+AppSupportURL=https://discord.gg/vtC7Yasz98+AppUpdatesURL=https://github.com/acasoq-web/BananaV/releases+VersionInfoVersion={#AppVersion}+DefaultDirName={autopf}\BananaV+DefaultGroupName=BananaV+DisableProgramGroupPage=yes+DisableDirPage=auto+PrivilegesRequired=lowest+MinVersion=10.0+#if Arch == "arm64"+ArchitecturesAllowed=arm64+ArchitecturesInstallIn64BitMode=arm64+#else+ArchitecturesAllowed=x64compatible+ArchitecturesInstallIn64BitMode=x64compatible+#endif+SetupIconFile=..\icons\bananav.ico+UninstallDisplayIcon={app}\bananav.ico+UninstallDisplayName=BananaV+WizardStyle=modern+WizardImageFile=wizard-large.bmp+WizardSmallImageFile=wizard-small.bmp+Compression=lzma2/max+SolidCompression=yes+ChangesAssociations=yes+CloseApplications=yes+RestartApplications=no++[Languages]+Name: "english"; MessagesFile: "compiler:Default.isl"+Name: "brazilianportuguese"; MessagesFile: "compiler:Languages\BrazilianPortuguese.isl"++[CustomMessages]+english.OpenProjects=Open BananaV projects (.bvproj) with BananaV+brazilianportuguese.OpenProjects=Abrir projetos do BananaV (.bvproj) com o BananaV++[Tasks]+Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"+Name: "projects"; Description: "{cm:OpenProjects}"; GroupDescription: "{cm:AdditionalIcons}"++[Files]+Source: "{#Files}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs+Source: "..\icons\bananav.ico"; DestDir: "{app}"; Flags: ignoreversion++[Icons]+Name: "{autoprograms}\BananaV"; Filename: "{app}\BananaV.exe"; IconFilename: "{app}\bananav.ico"+Name: "{autodesktop}\BananaV"; Filename: "{app}\BananaV.exe"; IconFilename: "{app}\bananav.ico"; Tasks: desktopicon++[Registry]+Root: HKA; Subkey: "Software\Classes\.bvproj"; ValueType: string; ValueName: ""; ValueData: "BananaV.Project"; Flags: uninsdeletevalue; Tasks: projects+Root: HKA; Subkey: "Software\Classes\BananaV.Project"; ValueType: string; ValueName: ""; ValueData: "BananaV Project"; Flags: uninsdeletekey; Tasks: projects+Root: HKA; Subkey: "Software\Classes\BananaV.Project\DefaultIcon"; ValueType: string; ValueName: ""; ValueData: "{app}\bananav.ico"; Tasks: projects+Root: HKA; Subkey: "Software\Classes\BananaV.Project\shell\open\command"; ValueType: string; ValueName: ""; ValueData: """{app}\BananaV.exe"" ""%1"""; Tasks: projects++[Run]+Filename: "{app}\BananaV.exe"; Description: "{cm:LaunchProgram,BananaV}"; Flags: nowait postinstall skipifsilentdiff --git a/packaging/windows/wizard-large.bmp b/packaging/windows/wizard-large.bmpnew file mode 100644index 0000000..93b9bc0Binary files /dev/null and b/packaging/windows/wizard-large.bmp differdiff --git a/packaging/windows/wizard-large.bmp.attribution b/packaging/windows/wizard-large.bmp.attributionnew file mode 100644index 0000000..fd14630--- /dev/null+++ b/packaging/windows/wizard-large.bmp.attribution@@ -0,0 +1,9 @@+asset: wizard-large.bmp+title: BananaV's logo on its dark color, for the Windows installer's pages+author: @acasoq-web, BananaV's owner+source: original work+license: GPL-3.0-or-later+license-file: LICENSE+added: 2026-11-04 by @acasoq-web+notes: ../icons/bananav.png on the icon's dark color. Used by bananav.iss.+ The name and the logo as marks: TRADEMARKS.md (draft).diff --git a/packaging/windows/wizard-small.bmp b/packaging/windows/wizard-small.bmpnew file mode 100644index 0000000..192567dBinary files /dev/null and b/packaging/windows/wizard-small.bmp differdiff --git a/packaging/windows/wizard-small.bmp.attribution b/packaging/windows/wizard-small.bmp.attributionnew file mode 100644index 0000000..2bec72c--- /dev/null+++ b/packaging/windows/wizard-small.bmp.attribution@@ -0,0 +1,9 @@+asset: wizard-small.bmp+title: BananaV's logo on its dark color, for the Windows installer's pages+author: @acasoq-web, BananaV's owner+source: original work+license: GPL-3.0-or-later+license-file: LICENSE+added: 2026-11-04 by @acasoq-web+notes: ../icons/bananav.png on the icon's dark color. Used by bananav.iss.+ The name and the logo as marks: TRADEMARKS.md (draft).diff --git a/site/assets/i18n.js b/site/assets/i18n.jsindex 0309c6e..ad107c7 100644--- a/site/assets/i18n.js+++ b/site/assets/i18n.js@@ -4,6 +4,35 @@// and a button to the language menu in index.html.window.BANANAV_I18N = {"pt-BR": {+ // BananaV 0.2.0.+ "BananaV 0.2.0 is out, with a Windows installer": "O BananaV 0.2.0 saiu, com instalador para Windows",+ "audio effects, with their panels and presets": "efeitos de áudio, com seus painéis e presets",+ "What's new in 0.2.0": "Novidades da versão 0.2.0",+ "Audio effects, .veg projects, color correction with LUTs, and an installer that does the work for you.": "Efeitos de áudio, projetos .veg, correção de cor com LUTs e um instalador que faz tudo por você.",+ "51 audio effects": "51 efeitos de áudio",+ "Equalizers, compressors, reverbs, delays, modulation and restoration, each with its panel and factory presets.": "Equalizadores, compressores, reverbs, delays, modulação e restauração, cada um com seu painel e presets de fábrica.",+ "Compatible with .veg projects": "Compatível com projetos .veg",+ "Open .veg projects with their tracks, transitions, audio effects, volumes, Pan/Crop and keyframes, and export your work to .veg.": "Abra projetos .veg com trilhas, transições, efeitos de áudio, volumes, Panorâmica/Recorte e quadros-chave, e exporte o seu trabalho para .veg.",+ "Color correction with LUTs": "Correção de cor com LUTs",+ "Color Grading rebuilt: wheels, curves, HSL, white balance and levels, with Camera and Look LUTs from .cube files, and Export LUT to take your grade anywhere.": "Matização de cores refeita: rodas, curvas, HSL, balanço de branco e níveis, com LUTs de câmera e de look em arquivos .cube, e Exportar LUT para levar a sua cor para qualquer lugar.",+ "An installer for Windows": "Instalador para Windows",+ "Download it, open it and follow the steps: BananaV goes to your Start menu, no administrator password needed.": "Baixe, abra e siga os passos: o BananaV vai para o menu Iniciar, sem pedir senha de administrador.",+ "Pan/Crop rebuilt": "Panorâmica/Recorte refeito",+ "Position, rotation, smooth paths and masks redone, and compared frame by frame with reference renders.": "Posição, rotação, caminhos suaves e máscaras refeitos, e comparados quadro a quadro com renders de referência.",+ "Smooth playback": "Reprodução lisa",+ "The graphics card draws from the first frame: 1080p at 60 frames a second, evenly, on about one processor core.": "A placa de vídeo desenha desde o primeiro quadro: 1080p a 60 quadros por segundo, sem engasgos, usando cerca de um núcleo do processador.",+ "51 audio effects of its own, a mixing console with busses and effects chains, VST 3 plug-ins, 5.1 surround panning, loudness meters and auto ducking.": "51 efeitos de áudio próprios, console de mixagem com barramentos e cadeias de efeitos, plug-ins VST 3, panorama surround 5.1, medidores de loudness e ducking automático.",+ ".veg projects, OpenTimelineIO, EDL and XML timelines in and out, closed captions and subtitles, and renders to MP4, MOV, ProRes and more.": "Projetos .veg, timelines OpenTimelineIO, EDL e XML de ida e volta, legendas, e renderização para MP4, MOV, ProRes e mais.",+ "BananaV 0.2.0 is out for Windows and Linux, and its source code is on GitHub.": "O BananaV 0.2.0 saiu para Windows e Linux, e o código-fonte está no GitHub.",+ "Windows 10 and 11. An installer: open it and follow the steps, no administrator password needed. It is not signed yet: if Windows warns you, choose More info, then Run anyway.": "Windows 10 e 11. Um instalador: abra e siga os passos, sem pedir senha de administrador. Ele ainda não é assinado: se o Windows avisar, clique em Mais informações e depois em Executar assim mesmo.",+ "Prefer no installation? Get the zip": "Prefere sem instalar? Baixe o zip",+ "Download the installer": "Baixar o instalador",+ "The installer is for Intel and AMD processors, most computers. ARM64 is for Snapdragon and other ARM ones.": "O instalador é para processadores Intel e AMD, a maioria dos computadores. ARM64 é para Snapdragon e outros ARM.",+ "November 4, 2026": "4 de novembro de 2026",+ "BananaV 0.2.0": "BananaV 0.2.0",+ "51 audio effects, compatibility with .veg projects, color correction with LUTs, a rebuilt Pan/Crop and smooth playback, now with an installer for Windows.": "51 efeitos de áudio, compatibilidade com projetos .veg, correção de cor com LUTs, Panorâmica/Recorte refeito e reprodução lisa, agora com instalador para Windows.",+ "The second test build, and the source code": "A segunda versão de teste, e o código-fonte",+ "The first test build": "A primeira versão de teste",// The redesign: what's new, the numbers, the tour, support."An event's effects window with Vignette and Swirl, the swirl's center as a handle on the Video Preview": "A janela de efeitos de um evento com Vinheta e Redemoinho, o centro do redemoinho como alça na pré-visualização","Chain effects on any event, track or the output, and drag their handles right on the preview.": "Encadeie efeitos em qualquer evento, trilha ou na saída, e arraste as alças direto na pré-visualização.",@@ -12,30 +41,14 @@ window.BANANAV_I18N = {"A strip for every track, bus and effects chain, and automation envelopes right on the timeline.": "Um canal para cada trilha, barramento e cadeia de efeitos, e envelopes de automação direto na timeline.","Tour": "Tour","New": "Novo",- "Ultra Alpha 2 is out, and the source code is public": "A Ultra Alpha 2 saiu, e o código-fonte agora é público","Download for free": "Baixar grátis","Windows & Linux · x64 & ARM64 · GPL v3 · No account, no watermark, no subscription": "Windows e Linux · x64 e ARM64 · GPL v3 · Sem conta, sem marca d'água, sem assinatura","BananaV's main window: the effects chooser with Add Noise's presets, the Video Preview, the Master Bus and the timeline": "A janela principal do BananaV: a lista de efeitos com os presets do Adicionar ruído, a pré-visualização, o barramento mestre e a timeline","BananaV in numbers": "O BananaV em números","built-in effects, transitions and generators": "efeitos, transições e geradores próprios",- "GL transitions, and your own GLSL": "transições GL, e o seu próprio GLSL","plug-in hosts for video and audio": "hosts de plug-ins para vídeo e áudio","color management, 32-bit float": "gerenciamento de cor, 32 bits de ponto flutuante",- "What's new in Ultra Alpha 2": "Novidades da Ultra Alpha 2","A big step forward": "Um grande passo à frente",- "More than 175 changes since the first build, and BananaV's source code is now on GitHub for everyone.": "Mais de 175 mudanças desde a primeira versão, e o código-fonte do BananaV agora está no GitHub para todos.",- "About a hundred effects remade": "Uns cem efeitos refeitos",- "New panels, presets and math, and most of them on the graphics card.": "Painéis, presets e cálculos novos, e a maioria rodando na placa de vídeo.",- "Tracking and stabilization": "Rastreamento e estabilização",- "Motion tracking, video and 360° stabilization, slow motion by optical flow.": "Rastreamento de movimento, estabilização de vídeo e 360°, câmera lenta por fluxo óptico.",- "3D compositing": "Composição 3D",- "Tracks as cards in space, with Track Motion in 3D, views and a trackball.": "Trilhas como cartões no espaço, com Movimento da trilha em 3D, vistas e trackball.",- "DVD and CD": "DVD e CD",- "DVD-Video authoring and burning, Video CDs and audio CDs, with BananaV's own encoders.": "Autoria e gravação de DVD-Video, Video CD e CD de áudio, com codificadores do próprio BananaV.",- "Studio audio": "Áudio de estúdio",- "A redesigned Mixing Console, plug-in delay compensation and VST 3 automation.": "Console de mixagem redesenhado, compensação de latência dos plug-ins e automação de VST 3.",- "Open source": "Código aberto",- "The whole code is on GitHub under the GPL: read it, build it, improve it.": "Todo o código está no GitHub, sob a GPL: leia, compile, melhore.","Read everything that changed": "Veja tudo o que mudou","More than a hundred video effects, transitions and generators on media, events, tracks and the output, with presets you can preview. Add OpenFX plug-ins too.": "Mais de cem efeitos de vídeo, transições e geradores em mídias, eventos, trilhas e na saída, com presets que você vê antes de usar. Use também plug-ins OpenFX.","Take a tour": "Faça um tour",@@ -71,30 +84,17 @@ window.BANANAV_I18N = {"It's free and always will be. If it helps you, a small donation keeps it going.": "Ele é gratuito e sempre será. Se te ajuda, uma pequena doação mantém o projeto vivo.","Close": "Fechar",- // The Ultra Alpha build.- "Ultra Alpha 2 · the second test build, and the source code": "Ultra Alpha 2 · a segunda versão de teste, e o código-fonte",- "Ultra Alpha 2 is out for Windows and Linux, and BananaV's source code is on GitHub.":- "A Ultra Alpha 2 saiu para Windows e Linux, e o código-fonte do BananaV está no GitHub.","An AppImage for any distribution since 2022: make the file executable and run it. No installation needed.":"Um AppImage para qualquer distribuição de 2022 em diante: torne o arquivo executável e abra. Não precisa instalar.","x64 for Intel and AMD processors, ARM64 for ARM ones.": "x64 para processadores Intel e AMD, ARM64 para os ARM.",- "This is a very early test build.": "Esta é uma versão de teste muito inicial.",- "Expect missing features, bugs and crashes. Don't use it for important work, keep copies of your media and projects, and expect projects saved now not to open in later builds. Tell us what breaks on":- "Espere recursos faltando, bugs e travamentos. Não use em trabalhos importantes, guarde cópias das suas mídias e projetos, e saiba que projetos salvos agora podem não abrir nas próximas versões. Conte o que quebrou no",- "Windows 10 and 11. A zip: unpack it and run BananaV.exe. The build is not signed yet: if Windows warns you, choose More info, then Run anyway.":- "Windows 10 e 11. Um zip: descompacte e abra o BananaV.exe. A versão ainda não é assinada: se o Windows avisar, clique em Mais informações e depois em Executar assim mesmo.",- "x64 for Intel and AMD processors, ARM64 for Snapdragon and other ARM ones.":- "x64 para processadores Intel e AMD, ARM64 para Snapdragon e outros ARM.","Build it yourself with Rust's cargo: the source code is on GitHub, under the GPL.":"Compile você mesmo com o cargo do Rust: o código-fonte está no GitHub, sob a GPL.","Build from source": "Compilar o código","November 2, 2026": "2 de novembro de 2026",- "Ultra Alpha 2, and the source code": "A Ultra Alpha 2, e o código-fonte","The second test build brings DVD authoring, motion tracking and stabilization, 3D compositing, studio audio and about a hundred effects and transitions remade. And BananaV's source code is now public on GitHub.":"A segunda versão de teste traz autoria de DVD, rastreamento e estabilização de movimento, composição 3D, áudio de estúdio e uns cem efeitos e transições refeitos. E o código-fonte do BananaV agora é público no GitHub.","Read what changed": "Veja o que mudou","October 23, 2026": "23 de outubro de 2026",- "The first Ultra Alpha build": "A primeira versão Ultra Alpha","The first build of BananaV is out for Windows and Linux, x64 and ARM64: a very early test build to try the editor and tell us what breaks.":"A primeira versão do BananaV saiu para Windows e Linux, x64 e ARM64: uma versão de teste bem inicial para experimentar o editor e contar o que quebrou.",@@ -157,14 +157,10 @@ window.BANANAV_I18N = {"32-bit floating point compositing, ACES 1.3 color management, a color grading panel with wheels, curves and LUTs, and video scopes.":"Composição em ponto flutuante de 32 bits, gerenciamento de cor ACES 1.3, um painel de correção de cor com rodas, curvas e LUTs, e escopos de vídeo.","Professional audio": "Áudio profissional",- "A mixing console with busses and effects chains, VST 3 plug-ins, 5.1 surround panning, loudness meters and auto ducking.":- "Um console de mixagem com barramentos e cadeias de efeitos, plug-ins VST 3, panorâmica surround 5.1, medidores de loudness e ducking automático.","Fast on your graphics card": "Rápido na sua placa de vídeo","Compositing on the GPU, hardware decoding, and hardware encoders when your computer has them. Proxies and prerendering for heavy projects.":"Composição na GPU, decodificação por hardware e codificadores por hardware quando o seu computador tem. Proxies e pré-renderização para projetos pesados.","Works with others": "Conversa com outros programas",- "OpenTimelineIO, EDL and XML timelines in and out, closed captions and subtitles, and renders to MP4, MOV, ProRes and more.":- "Timelines OpenTimelineIO, EDL e XML na entrada e na saída, closed captions e legendas, e renderização para MP4, MOV, ProRes e mais.","Your language": "O seu idioma","The interface speaks English and Brazilian Portuguese, with more languages to come from the community.":"A interface fala inglês e português do Brasil, e mais idiomas virão com a comunidade.",diff --git a/site/assets/style.css b/site/assets/style.cssindex 79f6a22..c483e45 100644--- a/site/assets/style.css+++ b/site/assets/style.css@@ -231,12 +231,6 @@ a.card { text-decoration: none; display: block; }@keyframes fade { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }/* Downloads */-.alpha { display: flex; gap: 18px; align-items: flex-start; margin: -16px 0 28px; padding: 20px 22px; border-radius: var(--radius);- border: 1px solid color-mix(in srgb, var(--yellow) 50%, transparent); background: color-mix(in srgb, var(--yellow) 9%, var(--surface)); }-.alpha p { color: var(--muted); font-size: 16px; }-.alpha strong { color: var(--text); }-.alpha a { color: var(--accent-text); }-.alpha-tag { flex: none; background: var(--yellow); color: var(--on-accent); font-weight: 800; font-size: 13px; letter-spacing: .08em; text-transform: uppercase; padding: 6px 12px; border-radius: 999px; }.downloads { display: grid; grid-template-columns: repeat(3, 1fr); gap: 18px; }.dl { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); padding: 32px 28px; display: flex; flex-direction: column; gap: 12px; transition: border-color .2s ease; }.dl:hover { border-color: color-mix(in srgb, var(--yellow) 40%, var(--line)); }@@ -362,7 +356,6 @@ a.card { text-decoration: none; display: block; }.highlights { grid-template-columns: repeat(2, 1fr); }.downloads, .news { grid-template-columns: 1fr; }.support-inner { grid-template-columns: 1fr; gap: 36px; padding: 64px 24px; }- .alpha { flex-direction: column; }}@media (max-width: 560px) {diff --git a/site/index.html b/site/index.htmlindex 7885425..e3377d9 100644--- a/site/index.html+++ b/site/index.html@@ -73,9 +73,9 @@<div class="glow glow-a" aria-hidden="true"></div><div class="glow glow-b" aria-hidden="true"></div><div class="hero-text">- <a class="eyebrow" href="https://github.com/acasoq-web/BananaV/releases/tag/v0.1.0-ultra-alpha.2" rel="noopener">+ <a class="eyebrow" href="https://github.com/acasoq-web/BananaV/releases/tag/v0.2.0" rel="noopener"><span class="badge-new">New</span>- <span>Ultra Alpha 2 is out, and the source code is public</span>+ <span>BananaV 0.2.0 is out, with a Windows installer</span><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 6l6 6-6 6"/></svg></a><h1>Edit freely.<br><span class="accent">Meet BananaV.</span></h1>@@ -102,7 +102,7 @@<section class="stats" aria-label="BananaV in numbers"><ul><li><strong>120+</strong><span>built-in effects, transitions and generators</span></li>- <li><strong>62</strong><span>GL transitions, and your own GLSL</span></li>+ <li><strong>51</strong><span>audio effects, with their panels and presets</span></li><li><strong>OFX + VST 3</strong><span>plug-in hosts for video and audio</span></li><li><strong>ACES 1.3</strong><span>color management, 32-bit float</span></li></ul>@@ -111,43 +111,43 @@<!-- What the latest build brings. --><section class="section" id="new"><div class="section-head">- <p class="kicker">What's new in Ultra Alpha 2</p>+ <p class="kicker">What's new in 0.2.0</p><h2>A big step forward</h2>- <p>More than 175 changes since the first build, and BananaV's source code is now on GitHub for everyone.</p>+ <p>Audio effects, .veg projects, color correction with LUTs, and an installer that does the work for you.</p></div><div class="highlights"><article class="hl">- <span class="hl-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M12 3.5l1.9 4.6 4.6 1.9-4.6 1.9L12 16.5l-1.9-4.6L5.5 10l4.6-1.9z"/><path d="M18 15.5l.8 1.9 1.9.8-1.9.8L18 21l-.8-1.9-1.9-.8 1.9-.8z"/></svg></span>- <h3>About a hundred effects remade</h3>- <p>New panels, presets and math, and most of them on the graphics card.</p>+ <span class="hl-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M6 4v16M12 4v16M18 4v16"/><rect x="4" y="13" width="4" height="2.5" rx="1"/><rect x="10" y="7" width="4" height="2.5" rx="1"/><rect x="16" y="10.5" width="4" height="2.5" rx="1"/></svg></span>+ <h3>51 audio effects</h3>+ <p>Equalizers, compressors, reverbs, delays, modulation and restoration, each with its panel and factory presets.</p></article><article class="hl">- <span class="hl-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M12 3.5v3M12 17.5v3M3.5 12h3M17.5 12h3"/></svg></span>- <h3>Tracking and stabilization</h3>- <p>Motion tracking, video and 360° stabilization, slow motion by optical flow.</p>+ <span class="hl-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M7 7.5h11.5l-3-3M17 16.5H5.5l3 3"/></svg></span>+ <h3>Compatible with .veg projects</h3>+ <p>Open .veg projects with their tracks, transitions, audio effects, volumes, Pan/Crop and keyframes, and export your work to .veg.</p></article><article class="hl">- <span class="hl-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M4 8.5 12 4l8 4.5v7L12 20l-8-4.5Z"/><path d="M4 8.5 12 13l8-4.5M12 13v7"/></svg></span>- <h3>3D compositing</h3>- <p>Tracks as cards in space, with Track Motion in 3D, views and a trackball.</p>+ <span class="hl-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M12 3.5v17M12 12l6-6"/></svg></span>+ <h3>Color correction with LUTs</h3>+ <p>Color Grading rebuilt: wheels, curves, HSL, white balance and levels, with Camera and Look LUTs from .cube files, and Export LUT to take your grade anywhere.</p></article><article class="hl">- <span class="hl-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><circle cx="12" cy="12" r="2.5"/></svg></span>- <h3>DVD and CD</h3>- <p>DVD-Video authoring and burning, Video CDs and audio CDs, with BananaV's own encoders.</p>+ <span class="hl-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M12 4v11M7 10.5l5 5 5-5M5 19.5h14"/></svg></span>+ <h3>An installer for Windows</h3>+ <p>Download it, open it and follow the steps: BananaV goes to your Start menu, no administrator password needed.</p></article><article class="hl">- <span class="hl-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M6 4v16M12 4v16M18 4v16"/><rect x="4" y="13" width="4" height="2.5" rx="1"/><rect x="10" y="7" width="4" height="2.5" rx="1"/><rect x="16" y="10.5" width="4" height="2.5" rx="1"/></svg></span>- <h3>Studio audio</h3>- <p>A redesigned Mixing Console, plug-in delay compensation and VST 3 automation.</p>+ <span class="hl-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M7 3.5V17h13.5M3.5 7H17v13.5"/></svg></span>+ <h3>Pan/Crop rebuilt</h3>+ <p>Position, rotation, smooth paths and masks redone, and compared frame by frame with reference renders.</p></article><article class="hl">- <span class="hl-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M8.5 7 3.5 12l5 5M15.5 7l5 5-5 5M13.5 5l-3 14"/></svg></span>- <h3>Open source</h3>- <p>The whole code is on GitHub under the GPL: read it, build it, improve it.</p>+ <span class="hl-icon" aria-hidden="true"><svg viewBox="0 0 24 24"><path d="M8 5.5v13l10.5-6.5z"/></svg></span>+ <h3>Smooth playback</h3>+ <p>The graphics card draws from the first frame: 1080p at 60 frames a second, evenly, on about one processor core.</p></article></div>- <p class="more"><a href="https://github.com/acasoq-web/BananaV/releases/tag/v0.1.0-ultra-alpha.2" rel="noopener">Read everything that changed</a></p>+ <p class="more"><a href="https://github.com/acasoq-web/BananaV/releases/tag/v0.2.0" rel="noopener">Read everything that changed</a></p></section><!-- Features: what the editor does, as cards. -->@@ -182,7 +182,7 @@<article class="card"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M6 4v16M12 4v16M18 4v16"/><rect x="4" y="13" width="4" height="2.5" rx="1"/><rect x="10" y="7" width="4" height="2.5" rx="1"/><rect x="16" y="10.5" width="4" height="2.5" rx="1"/></svg><h3>Professional audio</h3>- <p>A mixing console with busses and effects chains, VST 3 plug-ins, 5.1 surround panning, loudness meters and auto ducking.</p>+ <p>51 audio effects of its own, a mixing console with busses and effects chains, VST 3 plug-ins, 5.1 surround panning, loudness meters and auto ducking.</p></article><article class="card"><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="5" y="5" width="14" height="14" rx="2.5"/><rect x="9" y="9" width="6" height="6" rx="1"/><path d="M9 2.5V5M15 2.5V5M9 19v2.5M15 19v2.5M2.5 9H5M2.5 15H5M19 9h2.5M19 15h2.5"/></svg>@@ -192,7 +192,7 @@<article class="card"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 7.5h11.5l-3-3M17 16.5H5.5l3 3"/></svg><h3>Works with others</h3>- <p>OpenTimelineIO, EDL and XML timelines in and out, closed captions and subtitles, and renders to MP4, MOV, ProRes and more.</p>+ <p>.veg projects, OpenTimelineIO, EDL and XML timelines in and out, closed captions and subtitles, and renders to MP4, MOV, ProRes and more.</p></article><article class="card"><svg viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="8.5"/><path d="M3.5 12h17M12 3.5c2.5 2.4 3.5 5.2 3.5 8.5s-1 6.1-3.5 8.5c-2.5-2.4-3.5-5.2-3.5-8.5s1-6.1 3.5-8.5Z"/></svg>@@ -245,39 +245,33 @@<div class="section-head center"><p class="kicker">Download</p><h2>Get BananaV</h2>- <p>Ultra Alpha 2 is out for Windows and Linux, and BananaV's source code is on GitHub.</p>- </div>- <div class="alpha" role="note">- <span class="alpha-tag">Ultra Alpha</span>- <p><strong>This is a very early test build.</strong> Expect missing features, bugs and crashes.- Don't use it for important work, keep copies of your media and projects,- and expect projects saved now not to open in later builds.- Tell us what breaks on <a href="https://discord.gg/vtC7Yasz98">Discord</a>.</p>+ <p>BananaV 0.2.0 is out for Windows and Linux, and its source code is on GitHub.</p></div><div class="downloads"><article class="dl"><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3.5" y="4.5" width="17" height="12" rx="2"/><path d="M9 20h6M12 16.5V20"/></svg><h3>Windows</h3>- <p>Windows 10 and 11. A zip: unpack it and run BananaV.exe. The build is not signed yet: if Windows warns you, choose More info, then Run anyway.</p>+ <p>Windows 10 and 11. An installer: open it and follow the steps, no administrator password needed. It is not signed yet: if Windows warns you, choose More info, then Run anyway.</p><div class="dl-buttons">- <a class="btn btn-primary" data-download href="https://github.com/acasoq-web/BananaV/releases/download/v0.1.0-ultra-alpha.2/BananaV-0.1.0-ultra-alpha.2-windows-x64.zip">+ <a class="btn btn-primary" data-download href="https://github.com/acasoq-web/BananaV/releases/download/v0.2.0/BananaV-0.2.0-windows-x64-setup.exe"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4v11M7 10.5l5 5 5-5M5 19.5h14"/></svg>- x64+ Download the installer</a>- <a class="btn btn-ghost" data-download href="https://github.com/acasoq-web/BananaV/releases/download/v0.1.0-ultra-alpha.2/BananaV-0.1.0-ultra-alpha.2-windows-arm64.zip">ARM64</a>+ <a class="btn btn-ghost" data-download href="https://github.com/acasoq-web/BananaV/releases/download/v0.2.0/BananaV-0.2.0-windows-arm64-setup.exe">ARM64</a></div>- <p class="dl-note">x64 for Intel and AMD processors, ARM64 for Snapdragon and other ARM ones.</p>+ <p class="dl-note">The installer is for Intel and AMD processors, most computers. ARM64 is for Snapdragon and other ARM ones.</p>+ <p class="dl-note"><a href="https://github.com/acasoq-web/BananaV/releases/tag/v0.2.0" rel="noopener">Prefer no installation? Get the zip</a></p></article><article class="dl"><svg viewBox="0 0 24 24" aria-hidden="true"><rect x="3.5" y="4.5" width="17" height="12" rx="2"/><path d="M7.5 9l2.5 2-2.5 2M12 13h4.5M9 20h6M12 16.5V20"/></svg><h3>Linux</h3><p>An AppImage for any distribution since 2022: make the file executable and run it. No installation needed.</p><div class="dl-buttons">- <a class="btn btn-primary" data-download href="https://github.com/acasoq-web/BananaV/releases/download/v0.1.0-ultra-alpha.2/BananaV-0.1.0-ultra-alpha.2-linux-x64.AppImage">+ <a class="btn btn-primary" data-download href="https://github.com/acasoq-web/BananaV/releases/download/v0.2.0/BananaV-0.2.0-linux-x64.AppImage"><svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 4v11M7 10.5l5 5 5-5M5 19.5h14"/></svg>x64</a>- <a class="btn btn-ghost" data-download href="https://github.com/acasoq-web/BananaV/releases/download/v0.1.0-ultra-alpha.2/BananaV-0.1.0-ultra-alpha.2-linux-arm64.AppImage">ARM64</a>+ <a class="btn btn-ghost" data-download href="https://github.com/acasoq-web/BananaV/releases/download/v0.2.0/BananaV-0.2.0-linux-arm64.AppImage">ARM64</a></div><p class="dl-note">x64 for Intel and AMD processors, ARM64 for ARM ones.</p></article>@@ -381,14 +375,19 @@<a class="btn btn-ghost small" href="https://github.com/acasoq-web/BananaV/releases" rel="noopener">See all releases</a></div><div class="news">+ <article class="post">+ <time datetime="2026-11-04">November 4, 2026</time>+ <h3>BananaV 0.2.0</h3>+ <p>51 audio effects, compatibility with .veg projects, color correction with LUTs, a rebuilt Pan/Crop and smooth playback, now with an installer for Windows. <a href="https://github.com/acasoq-web/BananaV/releases/tag/v0.2.0">Read what changed</a>.</p>+ </article><article class="post"><time datetime="2026-11-02">November 2, 2026</time>- <h3>Ultra Alpha 2, and the source code</h3>+ <h3>The second test build, and the source code</h3><p>The second test build brings DVD authoring, motion tracking and stabilization, 3D compositing, studio audio and about a hundred effects and transitions remade. And BananaV's source code is now public on GitHub. <a href="https://github.com/acasoq-web/BananaV/releases/tag/v0.1.0-ultra-alpha.2">Read what changed</a>.</p></article><article class="post"><time datetime="2026-10-23">October 23, 2026</time>- <h3>The first Ultra Alpha build</h3>+ <h3>The first test build</h3><p>The first build of BananaV is out for Windows and Linux, x64 and ARM64: a very early test build to try the editor and tell us what breaks.</p></article><article class="post">diff --git a/tools/stacks.cs b/tools/stacks.csnew file mode 100644index 0000000..26bfab8--- /dev/null+++ b/tools/stacks.cs@@ -0,0 +1,205 @@+// A small sampling profiler for Windows: which threads of a running process+// use the processor, and where. No debugger needed; the symbols come from the+// PDBs beside the executable.+//+// csc -nologo -platform:x64 -out:stacks.exe tools\stacks.cs+// stacks.exe <pid> <folder of the PDB> [seconds to measure] [threads] [stacks per thread]+//+// STACK_DUMP=<file> appends every stack seen, "count<TAB>thread<TAB>frame;frame;…".+//+// For full symbols, profile a copy built with them, in a folder of its own+// (no link-time optimization: a minute to rebuild after a change):+//+// CARGO_PROFILE_RELEASE_DEBUG=line-tables-only CARGO_PROFILE_RELEASE_LTO=off \+// CARGO_PROFILE_RELEASE_CODEGEN_UNITS=16 CARGO_TARGET_DIR=<a folder> \+// cargo build --release -p bananav+using System;+using System.Collections.Generic;+using System.Diagnostics;+using System.Linq;+using System.Runtime.InteropServices;+using System.Threading;++static class Stacks+{+ [DllImport("kernel32")] static extern IntPtr OpenThread(uint access, bool inherit, uint id);+ [DllImport("kernel32")] static extern uint SuspendThread(IntPtr thread);+ [DllImport("kernel32")] static extern uint ResumeThread(IntPtr thread);+ [DllImport("kernel32")] static extern bool GetThreadContext(IntPtr thread, IntPtr context);+ [DllImport("kernel32")] static extern bool CloseHandle(IntPtr handle);+ [DllImport("kernel32")] static extern IntPtr OpenProcess(uint access, bool inherit, uint id);+ [DllImport("kernel32", CharSet = CharSet.Unicode)] static extern IntPtr LoadLibrary(string name);+ [DllImport("kernel32", CharSet = CharSet.Ansi)] static extern IntPtr GetProcAddress(IntPtr module, string name);+ [DllImport("kernel32", CharSet = CharSet.Unicode)] static extern int GetThreadDescription(IntPtr thread, out IntPtr description);+ [DllImport("kernel32")] static extern IntPtr LocalFree(IntPtr memory);+ [DllImport("dbghelp", CharSet = CharSet.Unicode, EntryPoint = "SymInitializeW")] static extern bool SymInitialize(IntPtr process, string path, bool invade);+ [DllImport("dbghelp")] static extern uint SymSetOptions(uint options);+ [DllImport("dbghelp")] static extern bool StackWalk64(uint machine, IntPtr process, IntPtr thread, IntPtr frame, IntPtr context, IntPtr read, IntPtr tables, IntPtr bases, IntPtr translate);+ [DllImport("dbghelp")] static extern bool SymFromAddr(IntPtr process, ulong address, out ulong displacement, IntPtr symbol);++ const uint THREAD_ALL = 0x1FFFFF, THREAD_QUERY_LIMITED = 0x1000, PROCESS_ALL = 0x1FFFFF;+ // SYMOPT_UNDNAME, SYMOPT_DEFERRED_LOADS, SYMOPT_LOAD_LINES.+ const uint SYM_OPTIONS = 0x2 | 0x4 | 0x10;+ // IMAGE_FILE_MACHINE_AMD64.+ const uint MACHINE = 0x8664;+ // CONTEXT (x64): its size, ContextFlags, Rsp, Rbp, Rip; CONTEXT_FULL.+ const int CONTEXT_SIZE = 1232, CONTEXT_FLAGS = 0x30, CONTEXT_RSP = 0x98, CONTEXT_RBP = 0xA0, CONTEXT_RIP = 0xF8, CONTEXT_FULL = 0x10000B;+ // STACKFRAME64: AddrPC, AddrFrame, AddrStack (offset, then its mode: flat).+ const int FRAME_SIZE = 512, FRAME_PC = 0, FRAME_BASE = 32, FRAME_STACK = 48, ADDRESS_MODE = 12, MODE_FLAT = 3;+ // SYMBOL_INFO: its size, MaxNameLen, Name.+ const int SYMBOL_STRUCT = 88, SYMBOL_MAX_NAME = 80, SYMBOL_NAME = 84, NAME_ROOM = 400;++ static string ThreadName(uint id)+ {+ IntPtr thread = OpenThread(THREAD_QUERY_LIMITED, false, id);+ if (thread == IntPtr.Zero) return "";+ IntPtr text;+ string name = "";+ if (GetThreadDescription(thread, out text) >= 0 && text != IntPtr.Zero)+ {+ name = Marshal.PtrToStringUni(text);+ LocalFree(text);+ }+ CloseHandle(thread);+ return name;+ }++ static List<string> Stack(IntPtr process, uint id, IntPtr contextMemory, IntPtr frame, IntPtr symbol, IntPtr tables, IntPtr bases, ProcessModule[] modules)+ {+ var frames = new List<string>();+ IntPtr thread = OpenThread(THREAD_ALL, false, id);+ if (thread == IntPtr.Zero) return frames;+ if (SuspendThread(thread) == 0xFFFFFFFF)+ {+ CloseHandle(thread);+ return frames;+ }+ try+ {+ // CONTEXT aligned to 16 bytes.+ IntPtr context = new IntPtr((contextMemory.ToInt64() + 15) & ~15L);+ for (int i = 0; i < CONTEXT_SIZE; i++) Marshal.WriteByte(context, i, 0);+ Marshal.WriteInt32(context, CONTEXT_FLAGS, CONTEXT_FULL);+ if (!GetThreadContext(thread, context)) return frames;+ for (int i = 0; i < FRAME_SIZE; i++) Marshal.WriteByte(frame, i, 0);+ Marshal.WriteInt64(frame, FRAME_PC, Marshal.ReadInt64(context, CONTEXT_RIP));+ Marshal.WriteInt32(frame, FRAME_PC + ADDRESS_MODE, MODE_FLAT);+ Marshal.WriteInt64(frame, FRAME_BASE, Marshal.ReadInt64(context, CONTEXT_RBP));+ Marshal.WriteInt32(frame, FRAME_BASE + ADDRESS_MODE, MODE_FLAT);+ Marshal.WriteInt64(frame, FRAME_STACK, Marshal.ReadInt64(context, CONTEXT_RSP));+ Marshal.WriteInt32(frame, FRAME_STACK + ADDRESS_MODE, MODE_FLAT);+ for (int depth = 0; depth < 64; depth++)+ {+ if (!StackWalk64(MACHINE, process, thread, frame, context, IntPtr.Zero, tables, bases, IntPtr.Zero)) break;+ ulong pc = (ulong)Marshal.ReadInt64(frame, FRAME_PC);+ if (pc == 0) break;+ Marshal.WriteInt32(symbol, 0, SYMBOL_STRUCT);+ Marshal.WriteInt32(symbol, SYMBOL_MAX_NAME, NAME_ROOM);+ ulong displacement;+ string name = SymFromAddr(process, pc, out displacement, symbol)+ ? Marshal.PtrToStringAnsi(new IntPtr(symbol.ToInt64() + SYMBOL_NAME))+ : "?";+ string module = "?";+ foreach (var m in modules)+ {+ long start = m.BaseAddress.ToInt64();+ if ((long)pc >= start && (long)pc < start + m.ModuleMemorySize)+ {+ module = m.ModuleName;+ break;+ }+ }+ frames.Add(module + "!" + name);+ }+ }+ finally+ {+ ResumeThread(thread);+ CloseHandle(thread);+ }+ return frames;+ }++ static void Main(string[] args)+ {+ uint pid = uint.Parse(args[0]);+ string symbols = args[1];+ double seconds = args.Length > 2 ? double.Parse(args[2]) : 3;+ int top = args.Length > 3 ? int.Parse(args[3]) : 4;+ int samples = args.Length > 4 ? int.Parse(args[4]) : 40;+ var target = Process.GetProcessById((int)pid);+ IntPtr process = OpenProcess(PROCESS_ALL, false, pid);+ SymSetOptions(SYM_OPTIONS);+ if (!SymInitialize(process, symbols, true)) Console.WriteLine("SymInitialize failed");+ IntPtr help = LoadLibrary("dbghelp.dll");+ IntPtr tables = GetProcAddress(help, "SymFunctionTableAccess64"), bases = GetProcAddress(help, "SymGetModuleBase64");++ // Each thread's processor time over the seconds asked for.+ var before = new Dictionary<int, double>();+ target.Refresh();+ foreach (ProcessThread t in target.Threads)+ {+ try { before[t.Id] = t.TotalProcessorTime.TotalMilliseconds; } catch { }+ }+ var clock = Stopwatch.StartNew();+ Thread.Sleep((int)(seconds * 1000));+ target.Refresh();+ double elapsed = clock.Elapsed.TotalMilliseconds;+ var rows = new List<Tuple<int, double>>();+ foreach (ProcessThread t in target.Threads)+ {+ try+ {+ double b;+ before.TryGetValue(t.Id, out b);+ rows.Add(Tuple.Create(t.Id, (t.TotalProcessorTime.TotalMilliseconds - b) / elapsed));+ }+ catch { }+ }+ rows.Sort((x, y) => y.Item2.CompareTo(x.Item2));+ Console.WriteLine("threads {0}, total {1:F2} cores", rows.Count, rows.Sum(r => r.Item2));+ foreach (var r in rows.Take(Math.Max(top, 12)))+ Console.WriteLine(" {0,6} {1,6:F3} {2}", r.Item1, r.Item2, ThreadName((uint)r.Item1));++ // The busiest threads' stacks.+ var modules = target.Modules.Cast<ProcessModule>().ToArray();+ IntPtr contextMemory = Marshal.AllocHGlobal(CONTEXT_SIZE + 16), frame = Marshal.AllocHGlobal(FRAME_SIZE), symbol = Marshal.AllocHGlobal(SYMBOL_NAME + NAME_ROOM + 1);+ string dump = Environment.GetEnvironmentVariable("STACK_DUMP");+ foreach (var r in rows.Take(top))+ {+ if (r.Item2 < 0.02) continue;+ Console.WriteLine();+ Console.WriteLine("=== thread {0} [{1}] {2:F3} cores", r.Item1, ThreadName((uint)r.Item1), r.Item2);+ var topFrames = new Dictionary<string, int>();+ var everywhere = new Dictionary<string, int>();+ var stacks = new Dictionary<string, int>();+ for (int k = 0; k < samples; k++)+ {+ var stack = Stack(process, (uint)r.Item1, contextMemory, frame, symbol, tables, bases, modules);+ if (stack.Count > 0)+ {+ int c;+ topFrames.TryGetValue(stack[0], out c);+ topFrames[stack[0]] = c + 1;+ foreach (var f in stack.Distinct())+ {+ everywhere.TryGetValue(f, out c);+ everywhere[f] = c + 1;+ }+ string key = string.Join(";", stack);+ stacks.TryGetValue(key, out c);+ stacks[key] = c + 1;+ }+ Thread.Sleep(25);+ }+ Console.WriteLine(" top frames:");+ foreach (var kv in topFrames.OrderByDescending(x => x.Value).Take(10))+ Console.WriteLine(" {0,3} {1}", kv.Value, kv.Key);+ Console.WriteLine(" on the stack:");+ foreach (var kv in everywhere.OrderByDescending(x => x.Value).Take(24))+ Console.WriteLine(" {0,3} {1}", kv.Value, kv.Key);+ if (!string.IsNullOrEmpty(dump))+ System.IO.File.AppendAllLines(dump, stacks.Select(kv => kv.Value + "\t" + r.Item1 + "\t" + kv.Key));+ }+ }+}