Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
444b9d93da | ||
|
|
7e1776bb04 | ||
|
|
5cc3770737 | ||
|
|
f4c0a833e6 | ||
|
|
9b3ddeaf56 | ||
|
|
0a0917ac56 | ||
|
|
6a4ec3d372 | ||
|
|
e3286f9094 |
No files matched your search
@@ -22,7 +22,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
plugin: [rivet, patina, anvil, crucible, lathe, temper]
|
||||
plugin: [rivet, patina, anvil, crucible, lathe, temper, weld, knurl]
|
||||
steps:
|
||||
- uses: https://github.com/actions/checkout@v4
|
||||
with:
|
||||
@@ -60,6 +60,8 @@ jobs:
|
||||
cargo run --manifest-path tools/editor-check/Cargo.toml --locked -- target/editor/crucible.png --plugin crucible
|
||||
cargo run --manifest-path tools/editor-check/Cargo.toml --locked -- target/editor/lathe.png --plugin lathe
|
||||
cargo run --manifest-path tools/editor-check/Cargo.toml --locked -- target/editor/temper.png --plugin temper
|
||||
cargo run --manifest-path tools/editor-check/Cargo.toml --locked -- target/editor/weld.png --plugin weld
|
||||
cargo run --manifest-path tools/editor-check/Cargo.toml --locked -- target/editor/knurl.png --plugin knurl
|
||||
- uses: https://github.com/actions/upload-artifact@v3-node20
|
||||
with:
|
||||
name: editor-previews
|
||||
@@ -89,11 +91,13 @@ jobs:
|
||||
python3 scripts/build-plugin.py --plugin crucible --target x86_64-pc-windows-gnu
|
||||
python3 scripts/build-plugin.py --plugin lathe --target x86_64-pc-windows-gnu
|
||||
python3 scripts/build-plugin.py --plugin temper --target x86_64-pc-windows-gnu
|
||||
python3 scripts/build-plugin.py --plugin weld --target x86_64-pc-windows-gnu
|
||||
python3 scripts/build-plugin.py --plugin knurl --target x86_64-pc-windows-gnu
|
||||
python3 scripts/package-windows.py
|
||||
- uses: https://github.com/actions/upload-artifact@v3-node20
|
||||
with:
|
||||
name: rivet-patina-windows-x86_64
|
||||
name: bass-foundry-windows-x86_64
|
||||
path: |
|
||||
dist/rivet-patina-windows-x86_64.zip
|
||||
dist/rivet-patina-windows-x86_64.zip.sha256
|
||||
dist/bass-foundry-windows-x86_64.zip
|
||||
dist/bass-foundry-windows-x86_64.zip.sha256
|
||||
retention-days: 30
|
||||
@@ -1,7 +1,7 @@
|
||||
name: Independent plugin release
|
||||
on:
|
||||
push:
|
||||
tags: ["rivet-v*", "patina-v*", "anvil-v*", "crucible-v*", "lathe-v*", "temper-v*"]
|
||||
tags: ["rivet-v*", "patina-v*", "anvil-v*", "crucible-v*", "lathe-v*", "temper-v*", "weld-v*", "knurl-v*"]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
Generated
+38
@@ -170,6 +170,25 @@ version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "knurl-core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"common-dsp",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "knurl-ui"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"common-dsp",
|
||||
"common-ui",
|
||||
"egui",
|
||||
"knurl-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lathe-core"
|
||||
version = "0.1.0"
|
||||
@@ -526,6 +545,25 @@ version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "weld-core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"crossbeam-queue",
|
||||
"rustfft",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "weld-ui"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"common-ui",
|
||||
"egui",
|
||||
"weld-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
|
||||
+7
-2
@@ -1,7 +1,7 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["plugins/common/ui", "plugins/common/dsp", "plugins/anvil/core", "plugins/anvil/ui", "plugins/lathe/core", "plugins/lathe/ui", "plugins/temper/core", "plugins/temper/ui", "plugins/crucible/core", "plugins/crucible/ui", "plugins/rivet/core", "plugins/rivet/midi", "plugins/rivet/preview", "plugins/rivet/app", "plugins/patina/core", "plugins/patina/render", "plugins/patina/ui"]
|
||||
exclude = ["plugins/rivet/plugin", "tools/editor-check", "plugins/patina/plugin", "plugins/anvil/plugin", "plugins/crucible/plugin", "plugins/lathe/plugin", "plugins/temper/plugin"]
|
||||
members = ["plugins/common/ui", "plugins/common/dsp", "plugins/anvil/core", "plugins/anvil/ui", "plugins/lathe/core", "plugins/lathe/ui", "plugins/temper/core", "plugins/temper/ui", "plugins/weld/core", "plugins/weld/ui", "plugins/knurl/core", "plugins/knurl/ui", "plugins/crucible/core", "plugins/crucible/ui", "plugins/rivet/core", "plugins/rivet/midi", "plugins/rivet/preview", "plugins/rivet/app", "plugins/patina/core", "plugins/patina/render", "plugins/patina/ui"]
|
||||
exclude = ["plugins/rivet/plugin", "tools/editor-check", "plugins/patina/plugin", "plugins/anvil/plugin", "plugins/crucible/plugin", "plugins/lathe/plugin", "plugins/temper/plugin", "plugins/weld/plugin", "plugins/knurl/plugin"]
|
||||
|
||||
[workspace.package]
|
||||
edition = "2021"
|
||||
@@ -24,3 +24,8 @@ opt-level = 2
|
||||
opt-level = 2
|
||||
[profile.dev.package.temper-core]
|
||||
opt-level = 2
|
||||
[profile.dev.package.knurl-core]
|
||||
opt-level = 2
|
||||
|
||||
[profile.dev.package.weld-core]
|
||||
opt-level = 2
|
||||
@@ -1,102 +1,199 @@
|
||||
# Rivet & Patina
|
||||
# Bass Foundry
|
||||
|
||||
Six Rust CLAP plugins for writing, designing and mixing bass music.
|
||||
**Rust CLAP plugins for writing, designing and mixing bass music in FL Studio.**
|
||||
|
||||
| Plugin | Purpose | Guide |
|
||||
| --- | --- | --- |
|
||||
| **Rivet** | Tell a MIDI motif as a story on a storyboard of roles, with joined seams | [Rivet](docs/rivet/README.md) |
|
||||
| **Patina** | Smooth harsh resonances while retaining tone and transient character | [Patina](docs/patina/README.md) |
|
||||
| **Anvil** | Give every bass note the same clean sub: one level, one start phase | [Anvil](docs/anvil/README.md) |
|
||||
| **Crucible** | Capture the last bars, slice them and export clean, key-labelled samples | [Crucible](docs/crucible/README.md) |
|
||||
| **Lathe** | EQ the harmonics of the played note: a cut on harmonic 3 stays on harmonic 3 | [Lathe](docs/lathe/README.md) |
|
||||
| **Temper** | Distort every note the same: level and tone filters follow the note | [Temper](docs/temper/README.md) |
|
||||
Website: [fl.narl.io](https://fl.narl.io)
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
Riddim and dubstep basses change patch on every switch-up. Fixed-frequency tools
|
||||
then act differently on every note: the sub jumps, an EQ cut lands on another
|
||||
harmonic, the distortion gets fizzy on one note and dull on the next. Most plugins
|
||||
in this suite follow the played note, so a setting means the same thing on every
|
||||
note. Each plugin is a separate product with its own version, guide and release.
|
||||
|
||||
## Plugins
|
||||
|
||||
| Plugin | What it does | Load it on | Latency | Docs |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| **[Rivet](docs/rivet/README.md)** | Tells a MIDI motif as a story on a storyboard of roles and joins the seams into one phrase | Channel Rack | none | [Guide](docs/rivet/README.md) · [Changes](docs/rivet/CHANGELOG.md) |
|
||||
| **[Patina](docs/patina/README.md)** | Smooths harsh, ringing resonances while plain harmonic tone and transients pass | Any mixer track | one analysis frame | [Guide](docs/patina/README.md) · [Changes](docs/patina/CHANGELOG.md) |
|
||||
| **[Anvil](docs/anvil/README.md)** | Replaces the sub with a clean mono sine: one level and one start phase on every note | Bass bus | 80 ms | [Guide](docs/anvil/README.md) · [Changes](docs/anvil/CHANGELOG.md) |
|
||||
| **[Crucible](docs/crucible/README.md)** | Records the last bars all the time, then slices, cleans and exports key-labelled samples with one button | End of the chain to resample | none | [Guide](docs/crucible/README.md) · [Changes](docs/crucible/CHANGELOG.md) |
|
||||
| **[Lathe](docs/lathe/README.md)** | EQ with one band on each harmonic of the played note: a cut on harmonic 3 stays on harmonic 3 | Bass, after the synth | ≈ 67 ms | [Guide](docs/lathe/README.md) · [Changes](docs/lathe/CHANGELOG.md) |
|
||||
| **[Temper](docs/temper/README.md)** | Distortion that drives every note the same: level and tone filters follow the note | Bass | ≈ 67 ms + oversampling | [Guide](docs/temper/README.md) · [Changes](docs/temper/CHANGELOG.md) |
|
||||
| **[Weld](docs/weld/README.md)** | Phase-aligns one bass layer to another layer through the sidechain, so the layers sum in the mids instead of cancelling | One layer's track, other layer as sidechain | none | [Guide](docs/weld/README.md) · [Changes](docs/weld/CHANGELOG.md) |
|
||||
| **[Knurl](docs/knurl/README.md)** | Gives every cycle of the note its own level, timing and grit: in-tune subharmonic growl, rattle and fry on every note | Bass | ≈ 71 ms | [Guide](docs/knurl/README.md) · [Changes](docs/knurl/CHANGELOG.md) |
|
||||
|
||||
Plugins with latency report it to the host, so FL Studio compensates the delay.
|
||||
Anvil, Lathe, Temper and Knurl detect pitch from the audio. They can also take the
|
||||
pitch from MIDI.
|
||||
|
||||
The names come from metalwork: a **rivet** joins pieces; **patina** changes a
|
||||
surface while leaving its character; an **anvil** is the solid base everything is
|
||||
struck on; a **crucible** melts material down to be cast again; a **lathe** turns
|
||||
a piece so each cut lands the same all the way round; **tempering** sets how hard
|
||||
and how tough a metal ends up. They share a Rust foundation and keep their own
|
||||
musical purpose, code, documentation, and version. Ideas for further plugins are
|
||||
collected in [docs/ideas.md](docs/ideas.md).
|
||||
surface and keeps its character; an **anvil** is the solid base that everything
|
||||
is struck on; a **crucible** melts material down to be cast again; a **lathe**
|
||||
turns a piece so each cut lands the same all the way round; **tempering** sets
|
||||
how hard and how tough a metal ends up; a **weld** fuses two pieces into one;
|
||||
**knurling** presses a ridged grip pattern into a surface.
|
||||
The suite is the **foundry**: the workshop where the bass gets cast, shaped and
|
||||
finished. Hosts list the plugins under the vendor name *Bass Foundry*.
|
||||
|
||||
## Editors
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td width="50%"><a href="docs/rivet/README.md"><img src="docs/rivet/assets/editor.png" alt="Rivet editor"></a><br><b>Rivet</b>: storyboard composition</td>
|
||||
<td width="50%"><a href="docs/patina/README.md"><img src="docs/patina/assets/editor.png" alt="Patina editor"></a><br><b>Patina</b>: resonance smoothing</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="docs/anvil/README.md"><img src="docs/anvil/assets/editor.png" alt="Anvil editor"></a><br><b>Anvil</b>: sub anchor</td>
|
||||
<td><a href="docs/crucible/README.md"><img src="docs/crucible/assets/editor.png" alt="Crucible editor"></a><br><b>Crucible</b>: resampler</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="docs/lathe/README.md"><img src="docs/lathe/assets/editor.png" alt="Lathe editor"></a><br><b>Lathe</b>: harmonic EQ</td>
|
||||
<td><a href="docs/temper/README.md"><img src="docs/temper/assets/editor.png" alt="Temper editor"></a><br><b>Temper</b>: tracked distortion</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="docs/weld/README.md"><img src="docs/weld/assets/editor.png" alt="Weld editor"></a><br><b>Weld</b>: layer phase alignment</td>
|
||||
<td><a href="docs/knurl/README.md"><img src="docs/knurl/assets/editor.png" alt="Knurl editor"></a><br><b>Knurl</b>: cycle texture</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
The previews are rendered headless from the real editor code by
|
||||
`tools/editor-check`, so they match what the plugin draws.
|
||||
|
||||
## Install
|
||||
|
||||
Download the desired plugin's Windows ZIP from its Gitea release. Extract it
|
||||
and copy its `.clap` file (`Rivet.clap`, `Patina.clap`, `Anvil.clap`,
|
||||
`Crucible.clap`, `Lathe.clap` or `Temper.clap`) into:
|
||||
1. Open the plugin's release on Gitea. Every plugin has its own release tag,
|
||||
for example `lathe-v0.1.0`.
|
||||
2. Download `<plugin>-windows-x86_64-<version>.zip`. You can check it against
|
||||
the `.zip.sha256` file next to it.
|
||||
3. Extract the ZIP and copy the `.clap` file into:
|
||||
|
||||
```text
|
||||
C:\Program Files\Common Files\CLAP\
|
||||
```text
|
||||
C:\Program Files\Common Files\CLAP\
|
||||
```
|
||||
|
||||
4. In FL Studio 2024.1 or newer, open **Options → Manage plugins**, enable
|
||||
**Verify plugins**, and click **Find installed plugins**.
|
||||
5. Load Rivet in the Channel Rack. Load the other plugins in mixer effect slots.
|
||||
|
||||
Keep the font license (`licenses/`) with redistributed packages.
|
||||
|
||||
Every branch and pull-request pipeline also builds a combined Windows preview
|
||||
ZIP, `bass-foundry-windows-x86_64.zip`, in its **windows** job. Use it to test unreleased changes.
|
||||
|
||||
> **Upgrading from an earlier build?** The CLAP IDs changed from
|
||||
> `io.storyboard.*` to `io.narl.bass-foundry.<product>`, so hosts see each
|
||||
> plugin as new. Delete the old `.clap` files, rescan, and add the plugins again
|
||||
> in existing projects. Motif Storyboard and Resonance Compressor are now Rivet
|
||||
> and Patina, and the vendor is "Bass Foundry".
|
||||
|
||||
## Build from source
|
||||
|
||||
You need:
|
||||
|
||||
- Rust stable and Python 3.11 or newer.
|
||||
- For the Windows target on Linux: the `x86_64-pc-windows-gnu` Rust target and
|
||||
MinGW (`x86_64-w64-mingw32-gcc`).
|
||||
- For the native wrapper tests on Linux: pkg-config and the X11/XCB and OpenGL
|
||||
development headers. Rivet's optional standalone also needs ALSA/JACK headers.
|
||||
|
||||
```sh
|
||||
# Tests for all engines, editors and tools
|
||||
cargo test --workspace --locked
|
||||
|
||||
# Formatting, tests and lints for one product, including its CLAP wrapper
|
||||
python3 scripts/check-plugin.py --plugin lathe
|
||||
|
||||
# Windows build, then the ZIPs (all plugins, or --plugin <name>)
|
||||
python3 scripts/build-plugin.py --plugin lathe --target x86_64-pc-windows-gnu
|
||||
python3 scripts/package-windows.py
|
||||
|
||||
# Headless editor preview
|
||||
cargo run --manifest-path tools/editor-check/Cargo.toml -- target/editor/lathe.png --plugin lathe
|
||||
```
|
||||
|
||||
In FL Studio 2024.1 or newer, open **Options → Manage plugins**, enable
|
||||
**Verify plugins**, and **Find installed plugins**. Load Rivet in the Channel Rack;
|
||||
load the others in mixer effect slots.
|
||||
Plugin names for the scripts are `rivet`, `patina`, `anvil`, `crucible`,
|
||||
`lathe`, `temper`, `weld` and `knurl`. Builds go to `dist/<target>/<Name>.clap`. No
|
||||
script installs anything into a DAW. [Development and testing](docs/development.md)
|
||||
has the full command list.
|
||||
|
||||
Normal branch/PR pipelines also provide a combined Windows preview ZIP in the
|
||||
**windows** job. Releases are separate: tags such as `rivet-v0.4.0`,
|
||||
`patina-v0.2.0`, `anvil-v0.1.0`, `crucible-v0.1.0`, `lathe-v0.1.0` and
|
||||
`temper-v0.1.0` publish independently. See [release workflow](docs/releases.md).
|
||||
## Quality checks
|
||||
|
||||
These names replace Motif Storyboard and Resonance Compressor. Their CLAP IDs
|
||||
and saved-state identifiers are preserved; replace old scanned copies and rescan.
|
||||
Every push and pull request runs these checks in CI
|
||||
(`.gitea/workflows/check.yml`):
|
||||
|
||||
- **Engine tests.** Every engine has tests for its signal behaviour and latency
|
||||
against measured targets.
|
||||
- **Realtime safety.** Every audio effect has a test that fails if the audio
|
||||
thread allocates memory.
|
||||
- **Host tests.** Each wrapper is loaded through the exported CLAP ABI, without
|
||||
a DAW. The tests check the ports, the reported latency, state save and load,
|
||||
and processing at 44.1, 48 and 96 kHz.
|
||||
- **Lints.** `rustfmt` and `clippy -D warnings` for every package and wrapper.
|
||||
- **Editor previews.** All editors are rendered headless and kept as CI
|
||||
artifacts.
|
||||
- **Windows builds.** Every `.clap` is cross-compiled and packaged.
|
||||
|
||||
Release ZIPs are deterministic and contain checksums for every file. Things CI
|
||||
cannot check stay manual: FL Studio routing, native window behaviour, and
|
||||
listening.
|
||||
|
||||
## Repository
|
||||
|
||||
```text
|
||||
plugins/
|
||||
catalog.json Product metadata used by build and release tools
|
||||
rivet/
|
||||
core/ Motifs, harmony, variation, history, performance
|
||||
midi/ Standard MIDI import/export
|
||||
app/ Worker jobs and real-time audition control
|
||||
preview/ Offline MIDI/WAV development tool
|
||||
plugin/ CLAP wrapper, editor, optional standalone
|
||||
patina/
|
||||
core/ Spectral detector and attenuation engine
|
||||
ui/ Patina's native editor
|
||||
render/ Offline WAV evaluation
|
||||
plugin/ CLAP audio-effect wrapper
|
||||
anvil/
|
||||
core/ Pitch tracking, crossover and sub oscillator
|
||||
ui/ Anvil's native editor
|
||||
plugin/ CLAP audio-effect wrapper with MIDI input
|
||||
crucible/
|
||||
core/ Input history, capture, slicing, cleanup and export
|
||||
ui/ Crucible's native editor
|
||||
plugin/ CLAP audio-effect wrapper
|
||||
lathe/
|
||||
core/ Harmonic band bank tuned to the tracked note
|
||||
ui/ Lathe's native editor
|
||||
plugin/ CLAP audio-effect wrapper with MIDI input
|
||||
temper/
|
||||
core/ Note-tracked filters, level normalising, oversampled shaper
|
||||
ui/ Temper's native editor
|
||||
plugin/ CLAP audio-effect wrapper with MIDI input
|
||||
catalog.json Product metadata for the build, check and release tools
|
||||
rivet/ core · midi · app · preview · plugin
|
||||
patina/ core · ui · render · plugin
|
||||
anvil/ core · ui · plugin
|
||||
crucible/ core · ui · plugin
|
||||
lathe/ core · ui · plugin
|
||||
temper/ core · ui · plugin
|
||||
weld/ core · ui · plugin
|
||||
knurl/ core · ui · plugin
|
||||
common/
|
||||
ui/ Shared look: palette, embedded fonts, knobs and panels
|
||||
dsp/ Shared filters, note tracking, oversampling, meters, WAV files
|
||||
tools/editor-check/ Headless visual QA for all editors
|
||||
scripts/ Shared build, packaging, release, and analysis tools
|
||||
docs/<plugin>/ Guide, changelog and editor preview per plugin
|
||||
references/ Local reference audio; excluded from distribution
|
||||
ui/ Shared look: palette, embedded fonts, knobs, panels, meters
|
||||
dsp/ Shared filters, pitch tracking, oversampling, meters, WAV files
|
||||
tools/editor-check/ Headless editor renderer for visual QA
|
||||
scripts/ Build, check, packaging, release and analysis tools
|
||||
docs/<plugin>/ Guide, changelog and editor preview for each plugin
|
||||
docs/ideas.md Problems in bass-music production and the plugin ideas for them
|
||||
references/ Local reference audio; never distributed
|
||||
website/ The fl.narl.io site: Astro, nginx container, reads catalog and previews
|
||||
```
|
||||
|
||||
The root Cargo workspace contains the engines and supporting tools. Each CLAP
|
||||
wrapper has an independent workspace and lockfile so SDK dependencies stay
|
||||
separate. [Development and testing](docs/development.md) covers the commands.
|
||||
Each product follows the same split:
|
||||
|
||||
```sh
|
||||
cargo test --workspace --locked
|
||||
python scripts/build-plugin.py --plugin rivet --target x86_64-pc-windows-gnu
|
||||
python scripts/build-plugin.py --plugin patina --target x86_64-pc-windows-gnu
|
||||
python scripts/build-plugin.py --plugin anvil --target x86_64-pc-windows-gnu
|
||||
python scripts/build-plugin.py --plugin crucible --target x86_64-pc-windows-gnu
|
||||
python scripts/build-plugin.py --plugin lathe --target x86_64-pc-windows-gnu
|
||||
python scripts/build-plugin.py --plugin temper --target x86_64-pc-windows-gnu
|
||||
python scripts/package-windows.py
|
||||
```
|
||||
- `core` is the engine. It is plain Rust, does not depend on a plugin SDK, and
|
||||
is tested on its own.
|
||||
- `ui` is the egui editor, built on `common-ui`.
|
||||
- `plugin` is the CLAP wrapper on a pinned NIH-plug revision.
|
||||
|
||||
Windows is the release target. Linux remains useful for tests, cross-compilation,
|
||||
and headless editor previews. FL Studio routing, native window behavior, and
|
||||
artistic listening still require manual checks in the target setup.
|
||||
The root Cargo workspace holds the engines, editors and tools. Each wrapper is
|
||||
its own workspace with its own lockfile, so SDK dependencies stay separate.
|
||||
`plugins/catalog.json` is the single list of products. The scripts and CI read
|
||||
it, so adding a plugin starts there.
|
||||
|
||||
## Releases
|
||||
|
||||
Each plugin is versioned and released on its own. Its version is the `version`
|
||||
in `plugins/<plugin>/plugin/Cargo.toml`. A tag `<plugin>-v<version>`, for example
|
||||
`temper-v0.1.0`, starts the release workflow. The workflow builds, checks and
|
||||
publishes that plugin's Windows ZIP to a Gitea release. See
|
||||
[docs/releases.md](docs/releases.md).
|
||||
|
||||
## Roadmap
|
||||
|
||||
[docs/ideas.md](docs/ideas.md) lists the production problems the suite targets,
|
||||
the released plugins and the ideas for the next ones.
|
||||
|
||||
## License
|
||||
|
||||
ISC, see [LICENSE](LICENSE). The embedded Roboto Condensed fonts are under the
|
||||
SIL Open Font License ([OFL.txt](plugins/common/ui/assets/OFL.txt)).
|
||||
@@ -1,5 +1,11 @@
|
||||
# Anvil changelog
|
||||
|
||||
## 0.2.0
|
||||
|
||||
- Change the CLAP ID to `io.narl.bass-foundry.anvil`. Hosts see this as a new
|
||||
plugin: delete the old `.clap` file, rescan, and add the plugin again in
|
||||
existing projects.
|
||||
|
||||
## 0.1.0
|
||||
|
||||
- Introduce Anvil, a sub anchor for bass music.
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
# Crucible changelog
|
||||
|
||||
## 0.2.0
|
||||
|
||||
- Change the CLAP ID to `io.narl.bass-foundry.crucible`. Hosts see this as a new
|
||||
plugin: delete the old `.clap` file, rescan, and add the plugin again in
|
||||
existing projects.
|
||||
|
||||
## 0.1.0
|
||||
|
||||
- Introduce Crucible, a resampler that always records its input.
|
||||
|
||||
+121
-72
@@ -1,109 +1,158 @@
|
||||
# Development
|
||||
|
||||
Run commands from the repository root. Rust stable and Python **3.11 or newer**
|
||||
are required. Lockfiles are committed for the core workspace, both CLAP wrappers,
|
||||
and the headless editor tool.
|
||||
Run commands from the repository root. You need Rust stable and Python **3.11 or
|
||||
newer**. Lockfiles are committed for the root workspace, every CLAP wrapper and
|
||||
the headless editor tool. Use `--locked` so a build never changes them silently.
|
||||
|
||||
## Product boundaries
|
||||
|
||||
The catalog in [plugins/catalog.json](../plugins/catalog.json) defines product
|
||||
names, wrapper manifests, documentation, internal packages, and distribution
|
||||
licenses. Shared build/check/release tools consume it. Each wrapper's Cargo
|
||||
package version is the authoritative release version.
|
||||
[plugins/catalog.json](../plugins/catalog.json) is the single list of products.
|
||||
For each product it defines the display name, the wrapper manifest, the library
|
||||
name, the documentation folder, the CLAP ID, the internal packages and the
|
||||
licenses to ship. The build, check, package and release scripts and the script
|
||||
tests read it. The version in each wrapper's `Cargo.toml` is the release version.
|
||||
|
||||
The root workspace contains Rivet's core, MIDI, application, and offline preview
|
||||
crates; Patina's core, editor, and renderer; Anvil's and Crucible's core and
|
||||
editor crates; and the shared `common-ui` (palette, fonts, knobs, panels) and
|
||||
`common-dsp` (filters, YIN pitch detection, WAV files) crates. Wrappers under
|
||||
`plugins/<product>/plugin/` remain independent workspaces because they depend on
|
||||
a pinned NIH-plug Git revision. Their host identities and persistence stay separate.
|
||||
Every product has the same split:
|
||||
|
||||
| Folder | Content | Workspace |
|
||||
| --- | --- | --- |
|
||||
| `plugins/<product>/core/` | Engine. Plain Rust, no plugin SDK, tested on its own | root |
|
||||
| `plugins/<product>/ui/` | egui editor, built on `common-ui` | root |
|
||||
| `plugins/<product>/plugin/` | CLAP wrapper on a pinned NIH-plug revision | own |
|
||||
|
||||
Rivet has more crates in the root workspace (`midi`, `app`, `preview`), and
|
||||
Patina has `render` for offline WAV evaluation. The shared crates are:
|
||||
|
||||
- `common-ui`: palette, embedded fonts, header, panels, knobs, meters.
|
||||
- `common-dsp`: filters, YIN pitch tracking, the note tracker used by Anvil,
|
||||
Lathe, Temper and Knurl, 4× oversampling, meters and WAV files.
|
||||
|
||||
The wrappers stay separate workspaces, each with its own lockfile, so the
|
||||
NIH-plug Git dependency stays out of the root workspace. Host identities and
|
||||
saved state are separate for every product.
|
||||
|
||||
The engines run allocation-free on the audio thread. Analysis that is too heavy
|
||||
for the audio thread (Rivet's generation jobs, Weld's cross-spectrum and fit) runs on a worker
|
||||
thread. Data goes to the editor through lock-free queues.
|
||||
|
||||
## Checks
|
||||
|
||||
```sh
|
||||
cargo test --workspace --locked
|
||||
cargo clippy --workspace --all-targets --locked -- -D warnings
|
||||
python scripts/check-plugin.py --plugin rivet
|
||||
python scripts/check-plugin.py --plugin patina
|
||||
python scripts/check-plugin.py --plugin anvil
|
||||
python scripts/check-plugin.py --plugin crucible
|
||||
python scripts/check-plugin.py --plugin lathe
|
||||
python scripts/check-plugin.py --plugin temper
|
||||
python -m unittest discover -s scripts/tests -v
|
||||
python3 scripts/check-plugin.py --plugin <product>
|
||||
python3 -m unittest discover -s scripts/tests -v
|
||||
```
|
||||
|
||||
The product check script checks formatting, tests, and lints that product's
|
||||
packages and wrapper without compiling the other plugin. Offline builds work
|
||||
once dependencies are cached; append `--offline` to manual Cargo commands.
|
||||
Products: `rivet`, `patina`, `anvil`, `crucible`, `lathe`, `temper`, `weld`,
|
||||
`knurl`.
|
||||
|
||||
Native wrapper tests on Linux require pkg-config, X11/XCB, and OpenGL development
|
||||
headers. Rivet's optional standalone also needs ALSA/JACK headers. Gitea installs
|
||||
the headers needed by its check jobs.
|
||||
`check-plugin.py` runs formatting, tests and clippy for one product's packages
|
||||
and its wrapper, without compiling the other products. Run it for every product
|
||||
when you change a shared crate or the root workspace. Offline builds work once
|
||||
the dependencies are cached; add `--offline` to manual Cargo commands.
|
||||
|
||||
The test types are:
|
||||
|
||||
- **Engine tests** (`core/tests/dsp.rs` and similar) measure signal behaviour
|
||||
and latency against fixed targets.
|
||||
- **Realtime tests** (`core/tests/realtime.rs`) install a counting allocator
|
||||
and fail if the audio-thread path allocates.
|
||||
- **Host tests** (`plugin/tests/host.rs`) load the wrapper through the exported
|
||||
CLAP ABI without a DAW. They check the ports, latency, state save and load,
|
||||
and processing at 44.1, 48 and 96 kHz with odd block sizes.
|
||||
- **Script tests** (`scripts/tests/`) cover the catalog, release planning,
|
||||
packaging and the publish client with fake transports. They also fail when a
|
||||
catalog product is missing from a CI workflow.
|
||||
|
||||
The native wrapper tests on Linux need pkg-config and the X11/XCB and OpenGL
|
||||
development headers. Rivet's optional standalone also needs ALSA/JACK headers.
|
||||
The Gitea check jobs install these headers.
|
||||
|
||||
## Windows builds
|
||||
|
||||
On Windows, install Rust and the MSVC build tools. For Linux cross-compilation,
|
||||
install the Rust `x86_64-pc-windows-gnu` target and MinGW's
|
||||
`x86_64-w64-mingw32-gcc`.
|
||||
On Windows, install Rust and the MSVC build tools. To cross-compile on Linux,
|
||||
install the Rust `x86_64-pc-windows-gnu` target and MinGW
|
||||
(`x86_64-w64-mingw32-gcc`).
|
||||
|
||||
```sh
|
||||
python scripts/build-plugin.py --plugin rivet --target x86_64-pc-windows-gnu
|
||||
python scripts/build-plugin.py --plugin patina --target x86_64-pc-windows-gnu
|
||||
python scripts/build-plugin.py --plugin anvil --target x86_64-pc-windows-gnu
|
||||
python scripts/build-plugin.py --plugin crucible --target x86_64-pc-windows-gnu
|
||||
python scripts/build-plugin.py --plugin lathe --target x86_64-pc-windows-gnu
|
||||
python scripts/build-plugin.py --plugin temper --target x86_64-pc-windows-gnu
|
||||
python scripts/package-windows.py
|
||||
python scripts/package-windows.py --plugin rivet
|
||||
python scripts/package-windows.py --plugin patina
|
||||
python3 scripts/build-plugin.py --plugin <product> --target x86_64-pc-windows-gnu
|
||||
python3 scripts/package-windows.py # combined preview ZIP
|
||||
python3 scripts/package-windows.py --plugin <product> # one product's release ZIP
|
||||
```
|
||||
|
||||
Build outputs use `dist/<target>/<Name>.clap`, with docs and
|
||||
licenses retaining their directory structure. `CARGO_TARGET_DIR` is supported
|
||||
for sharing compilation between wrappers. MSVC packaging accepts
|
||||
Builds go to `dist/<target>/<Name>.clap`, with the docs and licenses in the same
|
||||
folder structure. `CARGO_TARGET_DIR` is supported for sharing one build
|
||||
directory between wrappers. MSVC packaging accepts
|
||||
`--target x86_64-pc-windows-msvc`.
|
||||
|
||||
The combined ZIP is `dist/rivet-patina-windows-x86_64.zip`. Individual ZIPs use
|
||||
`<product>-windows-x86_64-<version>.zip`. Each ZIP has internal file checksums and
|
||||
an external `.zip.sha256`. ZIP metadata is deterministic; binaries still depend
|
||||
on the toolchain and build environment. Packaging includes only selected catalog
|
||||
entries, never old binaries left in `dist`.
|
||||
- The combined ZIP is `dist/bass-foundry-windows-x86_64.zip`. It holds every
|
||||
product that has been built.
|
||||
- A product ZIP is `<product>-windows-x86_64-<version>.zip` and holds only that
|
||||
product.
|
||||
|
||||
Linux builds remain available for local development; CI produces Windows release
|
||||
binaries only. Neither build nor packaging installs plugins into a DAW.
|
||||
Every ZIP has a `SHA256SUMS` file inside and a `.zip.sha256` file next to it.
|
||||
ZIP metadata is deterministic; the binaries still depend on the toolchain and
|
||||
the build environment. Packaging takes only the selected catalog entries, never
|
||||
old binaries left in `dist`.
|
||||
|
||||
Linux builds are for local development; CI produces only Windows binaries. No
|
||||
script installs a plugin into a DAW.
|
||||
|
||||
## Editor previews
|
||||
|
||||
```sh
|
||||
cargo run --manifest-path tools/editor-check/Cargo.toml -- /tmp/rivet.png --plugin rivet
|
||||
cargo run --manifest-path tools/editor-check/Cargo.toml -- /tmp/rivet-creative.png --plugin rivet --creative
|
||||
cargo run --manifest-path tools/editor-check/Cargo.toml -- /tmp/patina.png --plugin patina
|
||||
cargo run --manifest-path tools/editor-check/Cargo.toml -- /tmp/patina-compact.png --plugin patina --compact
|
||||
cargo run --manifest-path tools/editor-check/Cargo.toml -- /tmp/anvil.png --plugin anvil
|
||||
cargo run --manifest-path tools/editor-check/Cargo.toml -- /tmp/crucible.png --plugin crucible
|
||||
cargo run --manifest-path tools/editor-check/Cargo.toml -- /tmp/lathe.png --plugin lathe
|
||||
cargo run --manifest-path tools/editor-check/Cargo.toml -- /tmp/temper.png --plugin temper
|
||||
mkdir -p target/editor
|
||||
cargo run --manifest-path tools/editor-check/Cargo.toml -- target/editor/<product>.png --plugin <product>
|
||||
cargo run --manifest-path tools/editor-check/Cargo.toml -- target/editor/rivet-creative.png --plugin rivet --creative
|
||||
cargo run --manifest-path tools/editor-check/Cargo.toml -- target/editor/patina-compact.png --plugin patina --compact
|
||||
```
|
||||
|
||||
Patina also accepts `--silent`, `--delta`, and `--bypass` as render fixtures.
|
||||
The tool compiles actual editor code and software-renders without a display.
|
||||
These checks do not establish native host embedding, keyboard routing, or audible
|
||||
artistic quality. Use the product guides for FL Studio acceptance checks.
|
||||
Patina also accepts `--silent`, `--delta` and `--bypass`. The tool compiles the
|
||||
real editor code, feeds it synthetic analysis data and renders it in software
|
||||
without a display. Copy a checked render to `docs/<product>/assets/editor.png`
|
||||
to update the guide. These renders do not prove native host embedding, keyboard
|
||||
routing or how the plugin sounds; use the FL Studio checks in each product guide.
|
||||
|
||||
## Add a product
|
||||
|
||||
1. Create `plugins/<product>/{core,ui,plugin}`. Copy the wrapper `Cargo.toml`
|
||||
and `Cargo.lock` of a similar product so the NIH-plug revision matches.
|
||||
2. Add `core` and `ui` to the root `members`, the wrapper to `exclude`, and a
|
||||
`[profile.dev.package.<product>-core] opt-level = 2` entry if the tests run
|
||||
heavy DSP.
|
||||
3. Add the product to `plugins/catalog.json` with a new, unique CLAP ID.
|
||||
4. Add it to `.gitea/workflows/check.yml` (check matrix, editor preview,
|
||||
Windows build) and to the tag list in `release.yml`. The script tests fail
|
||||
until you do.
|
||||
5. Add a `--plugin <product>` fixture to `tools/editor-check`.
|
||||
6. Write `docs/<product>/README.md`, `CHANGELOG.md` and `assets/editor.png`, and
|
||||
add the product to the root README.
|
||||
|
||||
## Compatibility and naming
|
||||
|
||||
| Product | Former display name | Preserved CLAP ID |
|
||||
The suite is called **Bass Foundry**; this is the vendor name hosts show. Hosts
|
||||
identify plugins by CLAP ID, so the vendor name does not affect saved projects.
|
||||
|
||||
| Product | Former display name | CLAP ID |
|
||||
| --- | --- | --- |
|
||||
| Rivet | Motif Storyboard | `io.storyboard.motif` |
|
||||
| Patina | Resonance Compressor | `io.storyboard.resonance-compressor` |
|
||||
| Anvil | (new) | `io.storyboard.sub-anchor` |
|
||||
| Crucible | (new) | `io.storyboard.resampler` |
|
||||
| Rivet | Motif Storyboard | `io.narl.bass-foundry.rivet` |
|
||||
| Patina | Resonance Compressor | `io.narl.bass-foundry.patina` |
|
||||
| Anvil | (new) | `io.narl.bass-foundry.anvil` |
|
||||
| Crucible | (new) | `io.narl.bass-foundry.crucible` |
|
||||
| Lathe | (new) | `io.narl.bass-foundry.lathe` |
|
||||
| Temper | (new) | `io.narl.bass-foundry.temper` |
|
||||
| Weld | (new) | `io.narl.bass-foundry.weld` |
|
||||
| Knurl | (new) | `io.narl.bass-foundry.knurl` |
|
||||
|
||||
Rivet retains `story-session-v1` and its session migration support; Patina retains
|
||||
all parameter IDs. No JSON/state migration is introduced by the rename. These
|
||||
historical identifiers and copyright notices intentionally remain in source.
|
||||
Replace old scanned plugin files before rescanning, rather than keeping duplicate
|
||||
CLAP IDs installed. Verify existing-project recall in FL Studio.
|
||||
CLAP IDs use the form `io.narl.bass-foundry.<product>`. Builds tagged before
|
||||
this scheme used `io.storyboard.*` IDs; hosts treat the new IDs as different
|
||||
plugins, so projects saved with those builds need the plugin added again. From now on an ID is frozen: if a product is renamed, its CLAP ID
|
||||
stays. A new plugin gets `io.narl.bass-foundry.<slug>` with its product slug.
|
||||
|
||||
See [release workflow](releases.md) for tagged publishing. Actual Gitea runner
|
||||
execution and FL Studio validation remain separate from local checks.
|
||||
Rivet keeps `story-session-v1` and its session migration. Patina keeps all
|
||||
parameter IDs. The copyright notice keeps its original holder name. Delete old
|
||||
plugin files before rescanning, so FL Studio does not list both builds.
|
||||
|
||||
See [releases](releases.md) for tagged publishing. Runs on the real Gitea runner
|
||||
and checks in FL Studio are separate from the local checks.
|
||||
+109
-8
@@ -1,7 +1,7 @@
|
||||
# Plugin ideas
|
||||
|
||||
A running list of plugin ideas for riddim, dubstep and bass-music sound design.
|
||||
Each entry names the problem first. Entries are grouped as released or idea. Names follow the metalwork theme of Rivet, Patina, Anvil and Crucible.
|
||||
Each entry names the problem first. Entries are grouped as released or idea. Names follow the metalwork theme of the Bass Foundry suite.
|
||||
|
||||
## Problems seen in bass-music production
|
||||
|
||||
@@ -24,6 +24,17 @@ Each entry names the problem first. Entries are grouped as released or idea. Nam
|
||||
lifts the 4th harmonic of one note and the 7th of another; a distortion with
|
||||
a fixed tone filter sounds brighter on low notes than on high notes.
|
||||
10. Layered bass patches partly cancel in the mids, not only in the sub.
|
||||
11. Texture makes a riddim patch: grit, rattle, metal, vowel, noise. It takes long
|
||||
chains (distortion, comb, formant, OTT, resample, repeat), and the result
|
||||
changes from note to note.
|
||||
12. Grit and tone cannot be shaped separately. More distortion for more grit
|
||||
also changes the body, the level and the low end.
|
||||
13. Resampled textures sound printed: a loop of one moment, with no movement
|
||||
inside the note.
|
||||
14. Texture changes inside a note (the switch-up within one held note) need
|
||||
automation lanes or chopping.
|
||||
15. There is no meter for texture. Two switch-ups can sound "the same" without
|
||||
a clear reason, and generic analysers show only level and spectrum.
|
||||
|
||||
## Released
|
||||
|
||||
@@ -56,15 +67,23 @@ Input level is normalised before the shaper, so drive does not depend on how
|
||||
loud the patch is, and the output is gain-matched. Oversampled to keep aliasing
|
||||
(which is never harmonic) out. See [Temper](temper/README.md).
|
||||
|
||||
## Ideas
|
||||
|
||||
### Weld — layer phase alignment (problem 10)
|
||||
|
||||
Takes a second bass layer through the sidechain. Per band, it rotates phase
|
||||
with allpass filters (no added delay) and flips polarity so the layers sum
|
||||
instead of cancel. A display shows how much level the cancellation cost. Anvil
|
||||
solves the sub band; Weld solves the mids. Hardest of the list: phase matching
|
||||
against a moving sidechain.
|
||||
Takes a second bass layer through the sidechain. It fits polarity and a chain
|
||||
of up to four allpass sections to the measured cross-spectrum (no added
|
||||
delay), so the layers sum instead of cancel. A display shows how much level the
|
||||
cancellation cost and how much Weld recovered. Anvil solves the sub band; Weld
|
||||
solves the mids. See [Weld](weld/README.md).
|
||||
|
||||
### Knurl — cycle texture (problems 11, 13)
|
||||
|
||||
Follows the played note and treats every cycle on its own: a repeating level
|
||||
pattern (in-tune subharmonics), random level and timing per cycle, and a noise
|
||||
burst per cycle tuned to the note. Amounts are counted in cycles, so the texture
|
||||
is the same on every note. Slow per-harmonic drift is postponed. See
|
||||
[Knurl](knurl/README.md).
|
||||
|
||||
## Ideas
|
||||
|
||||
### Ballast — switch-up loudness leveller (problem 2)
|
||||
|
||||
@@ -99,3 +118,85 @@ patterns. No name yet.
|
||||
Loudness-matched A/B of a drop against a reference, with sub, low-mid, mid and
|
||||
high energy over time: for example "your sub is 3 dB under the reference in
|
||||
bars 2–4". No name yet.
|
||||
|
||||
## Texture ideas
|
||||
|
||||
These ideas target problems 11–15; Knurl, the first of them, is released above.
|
||||
Most of them reuse the note tracker in
|
||||
`common-dsp`, so a texture setting means the same thing on every note, the same
|
||||
way Lathe and Temper work.
|
||||
|
||||
### Anneal — tone and grit split (problem 12)
|
||||
|
||||
Annealing changes how a metal behaves without changing its shape. Anneal
|
||||
splits the signal into three parts: the harmonic part (energy on the harmonics
|
||||
of the tracked note), the residual noise and grit between the harmonics, and
|
||||
the transients. Each part has a level fader, a drive and a tilt.
|
||||
|
||||
- Turn the grit up 6 dB and keep the body and the sub unchanged.
|
||||
- Take all the grit out of a layer and leave a clean tone for further design.
|
||||
- Listen to each part solo, or send the grit to a second output for its own
|
||||
chain.
|
||||
|
||||
DSP: an STFT with the note tracker; harmonic masks at k·f0, with a width that
|
||||
follows the pitch; a transient mask from spectral flux. Latency is one FFT
|
||||
frame. The display shows the three parts in different colours on Lathe's
|
||||
harmonic strip.
|
||||
|
||||
### Swarf — in-key granular shavings (problems 11, 13)
|
||||
|
||||
Swarf is the shavings that machining leaves. Swarf records the bass itself and
|
||||
sprays short grains of it back as a layer. Grain lengths are whole pitch
|
||||
periods, and every grain is retuned to the note playing now, so the shredded
|
||||
layer stays in key across a riddim line. Controls are density, spray (position
|
||||
spread back in time), grain size in cycles, reverse probability, and a
|
||||
harmonic-only filter for the layer. It is useful for the "shredded metal" top
|
||||
layer, and works on a resample from Crucible as well.
|
||||
|
||||
### Etch — texture imprint (problem 11)
|
||||
|
||||
Etching transfers a pattern onto metal with acid. Etch takes a texture source
|
||||
through the sidechain or from a loaded sample (a metal scrape, a vocal, a field
|
||||
recording) and imprints its fine structure on the bass. The bass keeps its
|
||||
pitch and its harmonic levels; between and on the harmonics, the source's
|
||||
noise, roughness and movement come through. A "harmonic lock" mode samples the
|
||||
source's spectral envelope only at the bass harmonics, so the imprint is always
|
||||
in key. It differs from a vocoder: a vocoder transfers the envelope, and Etch
|
||||
transfers the surface.
|
||||
|
||||
### Chase — talking formants that hit harmonics (problems 11, 14)
|
||||
|
||||
Chasing shapes metal by hammering it from the front. Chase is a formant filter
|
||||
with a 2D vowel pad (a, e, i, o, u, plus "yoi" and "wub" shapes). You draw a
|
||||
path over the pad and sync it to the tempo, or let each MIDI note select a path.
|
||||
The formants stay in Hz, so a vowel stays a vowel on every note. A **snap**
|
||||
control moves each resonant peak onto the nearest harmonic of the tracked
|
||||
note, so a narrow formant never falls into the gap between two harmonics and
|
||||
vanishes on some notes. Gain-matched, so a vowel change does not change the
|
||||
level.
|
||||
|
||||
### Damascus — texture step sequencer (problem 14)
|
||||
|
||||
Damascus steel is folded from layers into a visible pattern. Damascus holds up
|
||||
to four texture slots (for example a formant, a comb, a sample-rate reducer and
|
||||
a Knurl-type rattle) and a tempo-synced step grid that chooses a slot, or a mix
|
||||
of two, per step. Steps have their own crossfade time, so changes can be hard
|
||||
cuts or smears. Each slot is gain-matched, so the steps change texture and not
|
||||
level. Each MIDI note can select its own pattern, which is a texture switch-up
|
||||
inside one held note. This overlaps with the wobble sequencer above; both could
|
||||
become one plugin.
|
||||
|
||||
### Loupe — texture meter (problem 15)
|
||||
|
||||
A loupe is the lens used to inspect engraving. Loupe measures texture per note
|
||||
over time:
|
||||
|
||||
- roughness and fluctuation strength (psychoacoustic models);
|
||||
- harmonic-to-noise ratio, which shows how gritty a sound is;
|
||||
- inharmonicity, which shows how metallic a sound is;
|
||||
- brightness relative to the note (harmonic centroid, not centroid in Hz).
|
||||
|
||||
It places every switch-up of a drop as a point on a texture map. Two patches
|
||||
that sit on the same point are why a drop sounds repetitive. A reference track
|
||||
can be loaded for comparison. Display only, so it is a small build, and it fits
|
||||
with Gauge and Drop compare.
|
||||
@@ -0,0 +1,20 @@
|
||||
# Knurl changelog
|
||||
|
||||
## 0.2.0
|
||||
|
||||
- Change the CLAP ID to `io.narl.bass-foundry.knurl`. Hosts see this as a new
|
||||
plugin: delete the old `.clap` file, rescan, and add the plugin again in
|
||||
existing projects.
|
||||
|
||||
## 0.1.0
|
||||
|
||||
- Introduce Knurl, texture per cycle of the played note.
|
||||
- Step patterns over 1–16 cycles make subharmonics in tune with every note:
|
||||
Off, Double, Triple, Fry, Gallop, Stutter, or a drawn pattern.
|
||||
- Random level and timing per cycle, and a noise burst per cycle tuned to the
|
||||
note (Tone, Position, Length), switchable per step.
|
||||
- Same every note or Free random sequences.
|
||||
- Detect pitch and note starts from the audio with about 71 ms of latency, or
|
||||
follow MIDI notes sent to the effect.
|
||||
- Editor shows the last eight cycles overlaid and the pattern with the playing
|
||||
step.
|
||||
@@ -0,0 +1,86 @@
|
||||
# Knurl
|
||||
|
||||
Knurl gives every cycle of the note its own level, timing and grit. Current
|
||||
version **0.1.0**.
|
||||
|
||||
Knurling presses a ridged pattern into metal. Riddim and dubstep basses get their
|
||||
character the same way, from surface texture: rattle, growl, fry, grit. Usually
|
||||
that texture comes from long chains of distortion, comb filters, formants and
|
||||
resampling, and it changes from note to note. Knurl works on single cycles of the
|
||||
wave instead. It follows the played note and treats each cycle on its own, and
|
||||
every amount is counted in cycles, not in Hz or tempo. So the texture has the
|
||||
same grain on F1 and on C2.
|
||||
|
||||

|
||||
|
||||
## Install on Windows
|
||||
|
||||
Copy `Knurl.clap` into `C:\Program Files\Common Files\CLAP\`. In FL Studio 2024.1
|
||||
or newer, open Options → Manage plugins, enable Verify plugins, and Find installed
|
||||
plugins. Load Knurl in a mixer slot of the bass. Keep the font license with
|
||||
redistributed packages.
|
||||
|
||||
## Work with it
|
||||
|
||||
1. Play the bass. The note readout shows what Knurl tracks; the scope overlays
|
||||
the last eight cycles of the output, so the texture is visible cycle by cycle.
|
||||
2. Choose a **Pattern**. The pattern sets the level of each cycle and repeats:
|
||||
- **Double** (0, −9 dB): every second cycle quieter. This makes a sub-octave
|
||||
growl, exactly in tune, about 8 dB under the fundamental.
|
||||
- **Triple** (0, −12, −12 dB): a growl an octave and a fifth down.
|
||||
- **Fry** (0, −14, −5, −14 dB, the default): an uneven vocal-fry rattle.
|
||||
- **Gallop** and **Stutter**: rhythmic patterns over six and eight cycles.
|
||||
- **Off**: every cycle at full level.
|
||||
3. Draw your own pattern on the bars: drag a bar to set the level of that cycle,
|
||||
double-click to reset it. **Steps** sets the length (1–16 cycles).
|
||||
4. Add surface:
|
||||
- **Level** gives every cycle a random level (standard deviation in dB).
|
||||
- **Time** moves every cycle a little in time (percent of a period): rattle
|
||||
and scrape.
|
||||
- **Grit** adds a short noise burst inside every cycle. **Tone** sets its
|
||||
lowest frequency in harmonics of the note, **Position** where in the cycle
|
||||
it sits, and **Length** how long it is. The squares under the pattern bars
|
||||
switch the burst per step.
|
||||
5. **Edge** sets how soft each step change is. Low values are sharper and
|
||||
buzzier; high values smoother.
|
||||
|
||||
**Random**: **Same every note** (default) restarts every random sequence at each
|
||||
note, so identical notes sound identical, which keeps a riddim line tight.
|
||||
**Free** lets the sequences run on, so every note differs.
|
||||
|
||||
**Mix** blends with the delayed dry signal; **Output** trims the level.
|
||||
|
||||
### Pitch from MIDI
|
||||
|
||||
For basses whose fundamental is unclear (heavy FM, formant or noise patches),
|
||||
select **MIDI** and route the bass's MIDI notes to Knurl. In FL Studio, set the
|
||||
bass channel's MIDI output port and Knurl's input port to the same number.
|
||||
**Gate** sets the input level that counts as a note in AUDIO mode; **Snap to
|
||||
semitone** rounds the detected pitch (turn it off for slides).
|
||||
|
||||
## Timing and limits
|
||||
|
||||
Knurl delays the audio by about 71 ms: 67 ms of pitch-detection lookahead plus
|
||||
4 ms of room for the timing jitter. The delay is reported to the host for delay
|
||||
compensation, so the cycle clock knows every note before its attack leaves the
|
||||
plugin. The cycle clock restarts at every note start, so the pattern always
|
||||
begins with step 1 on the attack. Pitch range is 30–500 Hz, one note at a time.
|
||||
Between notes the effects fade out over 20 ms, so tails stay clean.
|
||||
|
||||
Knurl works per cycle of the tracked pitch; it does not look for cycle borders in
|
||||
the waveform. With a stable pitch that is the same thing. With heavy pitch
|
||||
modulation inside a note the pattern follows the tracked pitch, which can lag a
|
||||
fast bend. Both channels get the same treatment, so the effect is mono-safe.
|
||||
|
||||
## How it works
|
||||
|
||||
A note tracker (shared with Anvil, Lathe and Temper) detects pitch and note
|
||||
starts ahead of the delayed audio. A cycle clock starts at 0 on every note and
|
||||
advances by f0 / sample rate. Each cycle gets its step gain and its random level
|
||||
and time offset from a hash of the cycle number, so the result is deterministic.
|
||||
Step changes are raised-cosine crossfades over the last **Edge** of a cycle;
|
||||
level jitter crossfades over half a cycle and time jitter over the whole cycle,
|
||||
read from the delay line with cubic interpolation. The grit is white noise
|
||||
through a state-variable highpass at **Tone** × f0, shaped by a sin² window and
|
||||
scaled to the input level. There is no nonlinearity, so no oversampling is
|
||||
needed.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 291 KiB |
@@ -1,5 +1,11 @@
|
||||
# Lathe changelog
|
||||
|
||||
## 0.2.0
|
||||
|
||||
- Change the CLAP ID to `io.narl.bass-foundry.lathe`. Hosts see this as a new
|
||||
plugin: delete the old `.clap` file, rescan, and add the plugin again in
|
||||
existing projects.
|
||||
|
||||
## 0.1.0
|
||||
|
||||
- Introduce Lathe, a harmonic EQ for bass sound design.
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
# Patina changelog
|
||||
|
||||
## 0.3.0
|
||||
|
||||
- Change the CLAP ID to `io.narl.bass-foundry.patina`. Hosts see this as a new
|
||||
plugin: delete the old `.clap` file, rescan, and add the plugin again in
|
||||
existing projects.
|
||||
|
||||
## 0.2.0
|
||||
|
||||
- Rebuild the detector so it finds resonant bumps instead of cutting individual
|
||||
|
||||
@@ -116,12 +116,12 @@ not a worst-case multi-instance guarantee.
|
||||
|
||||
## Existing projects and source layout
|
||||
|
||||
The CLAP ID `io.storyboard.resonance-compressor` is unchanged. Version 0.2
|
||||
replaces Amount, Sensitivity, Max cut, Neighborhood, Cut width, and Knee with
|
||||
Depth, Sharpness, and Selectivity, so projects saved with 0.1 load those
|
||||
controls at their defaults. Replace the former plugin file with `Patina.clap` and
|
||||
rescan; avoid two scanned copies with the same ID. Host project recall still
|
||||
needs verification in FL Studio.
|
||||
The CLAP ID is now `io.narl.bass-foundry.patina` (earlier builds used
|
||||
`io.storyboard.resonance-compressor`). Hosts treat Patina as a new plugin, so
|
||||
add it again in projects saved with an earlier build. Version 0.2 replaced
|
||||
Amount, Sensitivity, Max cut, Neighborhood, Cut width, and Knee with Depth,
|
||||
Sharpness, and Selectivity. Delete the old plugin file, place `Patina.clap`, and
|
||||
rescan FL Studio.
|
||||
|
||||
Source is grouped into `plugins/patina/{core,ui,render,plugin}`. See
|
||||
[research](research.md), [development](../development.md), and the
|
||||
|
||||
+35
-33
@@ -1,49 +1,51 @@
|
||||
# Independent plugin releases on Gitea
|
||||
|
||||
Rivet and Patina have independent versions and releases. Workflows live under
|
||||
`.gitea/workflows/`.
|
||||
Every Bass Foundry plugin has its own version and its own release. The
|
||||
workflows are in `.gitea/workflows/`. A plugin's version is the `version` in
|
||||
`plugins/<plugin>/plugin/Cargo.toml`, and its release tag is
|
||||
`<plugin>-v<version>`.
|
||||
|
||||
| Tag | Gitea release | Windows download |
|
||||
| Plugin | Latest tag | Windows download |
|
||||
| --- | --- | --- |
|
||||
| `rivet-v0.3.0` | Rivet 0.3.0 | `rivet-windows-x86_64-0.3.0.zip` |
|
||||
| `patina-v0.1.0` | Patina 0.1.0 | `patina-windows-x86_64-0.1.0.zip` |
|
||||
| Rivet | `rivet-v0.5.0` | `rivet-windows-x86_64-0.5.0.zip` |
|
||||
| Patina | `patina-v0.3.0` | `patina-windows-x86_64-0.3.0.zip` |
|
||||
| Anvil | `anvil-v0.2.0` | `anvil-windows-x86_64-0.2.0.zip` |
|
||||
| Crucible | `crucible-v0.2.0` | `crucible-windows-x86_64-0.2.0.zip` |
|
||||
| Lathe | `lathe-v0.2.0` | `lathe-windows-x86_64-0.2.0.zip` |
|
||||
| Temper | `temper-v0.2.0` | `temper-windows-x86_64-0.2.0.zip` |
|
||||
| Weld | `weld-v0.2.0` | `weld-windows-x86_64-0.2.0.zip` |
|
||||
| Knurl | `knurl-v0.2.0` | `knurl-windows-x86_64-0.2.0.zip` |
|
||||
|
||||
## Make a release
|
||||
|
||||
1. Update the selected wrapper's `Cargo.toml` version and its
|
||||
`docs/<product>/CHANGELOG.md`. The wrapper version determines the release
|
||||
version; internal crate versions can evolve separately.
|
||||
2. Refresh affected lockfiles, run the product check, and commit/push the change.
|
||||
3. Tag the intended commit and push that product's tag.
|
||||
1. Set the new version in the plugin's wrapper `Cargo.toml` and add a section
|
||||
with that version to `docs/<plugin>/CHANGELOG.md`. Internal crate versions
|
||||
can change independently.
|
||||
2. Refresh the affected lockfiles, run the plugin's check, then commit and push.
|
||||
3. Tag the commit and push only that plugin's tag.
|
||||
|
||||
For Rivet:
|
||||
For example, Temper 0.2.0:
|
||||
|
||||
```sh
|
||||
python scripts/check-plugin.py --plugin rivet
|
||||
git tag -a rivet-v0.3.0 -m "Rivet 0.3.0"
|
||||
git push origin rivet-v0.3.0
|
||||
python3 scripts/check-plugin.py --plugin temper
|
||||
git tag -a temper-v0.2.0 -m "Temper 0.2.0"
|
||||
git push origin temper-v0.2.0
|
||||
```
|
||||
|
||||
For Patina:
|
||||
|
||||
```sh
|
||||
python scripts/check-plugin.py --plugin patina
|
||||
git tag -a patina-v0.1.0 -m "Patina 0.1.0"
|
||||
git push origin patina-v0.1.0
|
||||
```
|
||||
|
||||
These are instructions; this change does not create tags or publish a release.
|
||||
Tags must exactly match the selected wrapper version and a changelog section.
|
||||
Wrong product/version tags fail before building or publishing. Cargo prerelease
|
||||
versions such as `patina-v0.2.0-rc.1` are supported and marked as prereleases.
|
||||
The tag must match the wrapper version and a changelog section exactly. A wrong
|
||||
plugin name or version fails in the `plan` job, before anything is built or
|
||||
published. Cargo prerelease versions such as `temper-v0.2.0-rc.1` are supported
|
||||
and published as prereleases.
|
||||
|
||||
## Workflows
|
||||
|
||||
**Check and Windows preview** runs on branch pushes, pull requests, and manual
|
||||
dispatch. It checks both products, renders editor previews, and provides a combined
|
||||
Windows ZIP as an Actions artifact. It never publishes a release.
|
||||
dispatch. It checks every product in a matrix, renders all editor previews, and
|
||||
provides the combined `bass-foundry-windows-x86_64.zip` as an Actions artifact.
|
||||
It never publishes a release.
|
||||
|
||||
**Independent plugin release** runs on `rivet-v*` or `patina-v*` tag pushes:
|
||||
**Independent plugin release** runs when a `<plugin>-v*` tag is pushed, for any
|
||||
plugin in the catalog:
|
||||
|
||||
1. `plan` validates the product/version/changelog and exposes the selected plugin.
|
||||
2. `build` checks and cross-compiles only that plugin, then packages its Windows
|
||||
@@ -106,7 +108,7 @@ The release tag must already exist in Gitea; the publisher does not create tags.
|
||||
The ZIP must contain exactly the selected plugin. Its sidecar and internal file
|
||||
checksums are verified before any release write.
|
||||
|
||||
Choose a plugin's named release/tag rather than assuming the repository's global
|
||||
latest release refers to both products. Package and API behavior are tested with
|
||||
fake transports; an actual runner/tag release on this Gitea instance remains to
|
||||
be verified.
|
||||
Link to a plugin's own release or tag. The repository's "latest release" is
|
||||
only the most recent release of any plugin. Packaging and API behaviour are tested with
|
||||
fake transports. Every tag in the table above was published by this workflow on
|
||||
the project's Gitea instance.
|
||||
@@ -1,5 +1,11 @@
|
||||
# Rivet changelog
|
||||
|
||||
## 0.5.0
|
||||
|
||||
- Change the CLAP ID to `io.narl.bass-foundry.rivet`. Hosts see this as a new
|
||||
plugin: delete the old `.clap` file, rescan, and add the plugin again in
|
||||
existing projects.
|
||||
|
||||
## 0.4.0
|
||||
|
||||
- Storyboard: a timeline of blocks with roles (statement, answer, departure,
|
||||
|
||||
@@ -145,8 +145,8 @@ and silent startup at several sample rates and buffer sizes.
|
||||
|
||||
## Existing projects
|
||||
|
||||
The name, Cargo packages, source paths, and output filename have changed.
|
||||
The CLAP ID `io.storyboard.motif`, `story-session-v1` host field, and session
|
||||
JSON format are preserved. Rescan FL Studio after replacing the old plugin file
|
||||
with `Rivet.clap`; remove the old copy from scanned folders to avoid duplicate
|
||||
instances with the same ID. Project recall still needs a check in the target host.
|
||||
The CLAP ID is now `io.narl.bass-foundry.rivet` (earlier builds used
|
||||
`io.storyboard.motif`). Hosts treat Rivet as a new plugin, so add it again in
|
||||
projects saved with an earlier build. The `story-session-v1` host field and the
|
||||
session JSON format are preserved, so saved sessions still open. Delete the old
|
||||
plugin file, place `Rivet.clap`, and rescan FL Studio.
|
||||
@@ -1,5 +1,11 @@
|
||||
# Temper changelog
|
||||
|
||||
## 0.2.0
|
||||
|
||||
- Change the CLAP ID to `io.narl.bass-foundry.temper`. Hosts see this as a new
|
||||
plugin: delete the old `.clap` file, rescan, and add the plugin again in
|
||||
existing projects.
|
||||
|
||||
## 0.1.0
|
||||
|
||||
- Introduce Temper, a note-tracked distortion for bass sound design.
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# Weld changelog
|
||||
|
||||
## 0.2.0
|
||||
|
||||
- Change the CLAP ID to `io.narl.bass-foundry.weld`. Hosts see this as a new
|
||||
plugin: delete the old `.clap` file, rescan, and add the plugin again in
|
||||
existing projects.
|
||||
|
||||
## 0.1.0
|
||||
|
||||
- Introduce Weld, a phase aligner for layered bass.
|
||||
- Hears the other layer through the sidechain input and fits polarity plus up to
|
||||
four allpass sections, so the layers sum instead of cancelling. No latency;
|
||||
the layer on its own keeps its sound.
|
||||
- Modes: Follow (refits only when clearly better), Learn (measure one take,
|
||||
apply on exit), Hold. The alignment is saved with the project.
|
||||
- Display: level per band against a perfect alignment (lost and won back),
|
||||
phase before and after, recovered dB, cancellation cost, time offset, and
|
||||
warnings for a late layer, unrelated layers and a missing sidechain.
|
||||
- Controls: Mode, Sections, Response, Low, High, Gate, Listen (Layer, Sum,
|
||||
Sum dry), Output, Bypass.
|
||||
@@ -0,0 +1,110 @@
|
||||
# Weld
|
||||
|
||||
Weld fuses two bass layers so they add up instead of cancelling. Current version
|
||||
**0.1.0**.
|
||||
|
||||
Bass patches are layered: a sub, one or more mid growls, a top. Where the layers
|
||||
overlap in the mids, they partly cancel. The causes are a polarity difference, a
|
||||
small time offset between the layers, and the phase shift of the filters and EQs
|
||||
in one chain. The result is a thin, hollow sum that changes with every
|
||||
switch-up. Anvil fixes this for the sub band; Weld fixes it for the mids.
|
||||
|
||||
Weld sits on one layer and hears the other one through the sidechain input. It
|
||||
measures how the two layers line up, then turns the phase of its own layer with
|
||||
a polarity flip and up to four allpass filters. An allpass changes only phase,
|
||||
so the layer on its own sounds the same; only the sum changes. Weld adds no
|
||||
latency.
|
||||
|
||||

|
||||
|
||||
## Install on Windows
|
||||
|
||||
Copy `Weld.clap` into `C:\Program Files\Common Files\CLAP\`. In FL Studio 2024.1
|
||||
or newer, open Options → Manage plugins, enable Verify plugins, and Find installed
|
||||
plugins. Keep the font license with redistributed packages.
|
||||
|
||||
## Set up in FL Studio
|
||||
|
||||
1. Put each layer on its own mixer track. Load Weld on the track of one layer,
|
||||
the main layer.
|
||||
2. Select the other layer's track. Right-click the route arrow under the main
|
||||
layer's track and choose **Sidechain to this track**. The other layer still
|
||||
goes to the master on its own; the sidechain only lets Weld hear it.
|
||||
3. In Weld's plugin wrapper, open the settings (gear icon) and set Weld's
|
||||
sidechain input to that track.
|
||||
4. Play both layers. The SIDECHAIN meter must move. If the display says "No
|
||||
sidechain signal", check step 3.
|
||||
|
||||
## Work with it
|
||||
|
||||
1. Leave **Mode** on **FOLLOW** and play the part where both layers sound. After
|
||||
a second or two, Weld shows its alignment: polarity, and the allpass sections
|
||||
with their frequency and Q.
|
||||
2. Read the display:
|
||||
- **Recovered** is how much level the sum gains, as an average per band
|
||||
between Low and High. **Cancellation cost** is how much a perfect alignment
|
||||
would gain. When the two numbers are close, Weld got nearly everything.
|
||||
- The upper plot shows each band against a perfectly aligned sum (0 dB). Red
|
||||
is what the unprocessed sum loses to cancellation; pink is the part Weld
|
||||
wins back. The white line is the level with Weld.
|
||||
- The lower plot shows the phase of this layer against the other one, before
|
||||
(grey) and after (pink), and Weld's own phase curve (blue). After alignment
|
||||
the pink line sits near 0°.
|
||||
3. Compare by ear: mute the other layer's own route to the master, set
|
||||
**Listen** to **SUM**, then to **SUM DRY**. Set Listen back to **LAYER** and
|
||||
unmute the route for the mix.
|
||||
4. When the alignment is right, switch to **HOLD**. It is saved with the project
|
||||
and comes back when the project opens.
|
||||
|
||||
For one drop or switch-up, use **LEARN**: press it, play the part, then press
|
||||
**HOLD** (or LEARN again). Weld measures the whole take with equal weight and
|
||||
applies the result when Learn ends.
|
||||
|
||||
## Controls
|
||||
|
||||
- **Mode**:
|
||||
- **Follow** keeps measuring and refits only when a new alignment is clearly
|
||||
better (at least 0.3 dB on average), so the filter does not wander.
|
||||
- **Learn** starts a fresh measurement and applies its result when Learn ends.
|
||||
- **Hold** keeps the current alignment. The display keeps measuring.
|
||||
- **Sections** (1–4) is the largest number of allpass sections the fit may use.
|
||||
Weld uses fewer when fewer are enough.
|
||||
- **Response** (0.3–5 s) is the averaging time in Follow. Longer is steadier.
|
||||
- **Low** and **High** set the range the fit listens to. Low defaults to 60 Hz,
|
||||
leaving the sub to Anvil. The allpass still acts below Low, and the display
|
||||
shows that honestly.
|
||||
- **Gate** (−70 to −30 dB): moments where either layer is quieter are not
|
||||
measured, so tails and silence do not pull the fit.
|
||||
- **Listen**: **Layer** outputs this layer, aligned, for the mix. **Sum** outputs
|
||||
this layer aligned plus the sidechain layer. **Sum dry** outputs both
|
||||
unprocessed.
|
||||
- **Output** trims the level; **Bypass** passes this layer unchanged.
|
||||
|
||||
## Limits
|
||||
|
||||
- **A late layer cannot be moved earlier.** An allpass only delays. If the layer
|
||||
Weld sits on is the later one, the display shows "This layer is late" and the
|
||||
offset in ms. Put Weld on the other layer instead.
|
||||
- **Free-running layers cannot be aligned.** Without oscillator retrigger, or
|
||||
with detuned unison, the phase between the layers drifts all the time. Weld
|
||||
marks those bands as *loose* (hatched) and does not fit them. Enable retrigger
|
||||
in the synth if you want Weld to align the layers.
|
||||
- **Delays leave a comb.** A time offset between the layers cancels at regular
|
||||
frequencies. A few allpass sections cannot follow a delay all the way up, so
|
||||
Weld aligns the lower range and moves the higher notches rather than removing
|
||||
them. For a large offset, move the layer in time first.
|
||||
- **One alignment for the whole patch.** Weld does not change the alignment per
|
||||
note. If switch-ups need different alignments, use Follow, or automate Mode.
|
||||
- **The sidechain must arrive.** With no sidechain signal Weld changes nothing.
|
||||
|
||||
## How it works
|
||||
|
||||
Every 256 samples the audio thread hands mono copies of both layers to a worker
|
||||
thread through a lock-free queue. The worker estimates their cross-spectrum
|
||||
(Welch, Hann window, about 11.7 Hz per bin, 50 % overlap) and their coherence.
|
||||
It fits polarity plus up to four second-order allpass sections so that
|
||||
Σ w(f)·Re(S(f)·H(f)) is largest, with w = 1/f so every octave counts, ignoring
|
||||
bins where the layers are not coherent, and with a penalty for any band that
|
||||
would lose more than 1 dB. A new fit fades in over 40 ms after its filters have
|
||||
settled for 40 ms, so there are no clicks. One fit takes about 15 ms on one
|
||||
core, twice per second in Follow.
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 258 KiB |
Generated
+1
-1
@@ -72,7 +72,7 @@ checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04"
|
||||
|
||||
[[package]]
|
||||
name = "anvil"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"anvil-core",
|
||||
"anvil-ui",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "anvil"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
license = "ISC"
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@ impl Default for Anvil {
|
||||
}
|
||||
impl Plugin for Anvil {
|
||||
const NAME: &'static str = "Anvil";
|
||||
const VENDOR: &'static str = "Rivet & Patina";
|
||||
const VENDOR: &'static str = "Bass Foundry";
|
||||
const URL: &'static str = "";
|
||||
const EMAIL: &'static str = "";
|
||||
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
|
||||
@@ -185,7 +185,7 @@ impl Plugin for Anvil {
|
||||
}
|
||||
}
|
||||
impl ClapPlugin for Anvil {
|
||||
const CLAP_ID: &'static str = "io.storyboard.sub-anchor";
|
||||
const CLAP_ID: &'static str = "io.narl.bass-foundry.anvil";
|
||||
const CLAP_DESCRIPTION: Option<&'static str> =
|
||||
Some("Replace the sub with a clean sine at one level and phase for every note");
|
||||
const CLAP_MANUAL_URL: Option<&'static str> = None;
|
||||
|
||||
@@ -61,7 +61,7 @@ fn effect_ports_state_latency_and_audio_lifecycle() {
|
||||
assert_eq!(CStr::from_ptr((*descriptor).name), c"Anvil");
|
||||
assert_eq!(
|
||||
CStr::from_ptr((*descriptor).id),
|
||||
c"io.storyboard.sub-anchor"
|
||||
c"io.narl.bass-foundry.anvil"
|
||||
);
|
||||
assert!(factory.get_plugin_descriptor.unwrap()(factory, 1).is_null());
|
||||
let host = clap_host {
|
||||
|
||||
+38
-6
@@ -6,7 +6,7 @@
|
||||
"library": "rivet",
|
||||
"documentation": "docs/rivet",
|
||||
"standalone": "rivet",
|
||||
"clap_id": "io.storyboard.motif",
|
||||
"clap_id": "io.narl.bass-foundry.rivet",
|
||||
"packages": [
|
||||
"rivet-core",
|
||||
"rivet-midi",
|
||||
@@ -20,7 +20,7 @@
|
||||
"manifest": "plugins/patina/plugin/Cargo.toml",
|
||||
"library": "patina",
|
||||
"documentation": "docs/patina",
|
||||
"clap_id": "io.storyboard.resonance-compressor",
|
||||
"clap_id": "io.narl.bass-foundry.patina",
|
||||
"licenses": {
|
||||
"plugins/common/ui/assets/OFL.txt": "licenses/Roboto-OFL.txt"
|
||||
},
|
||||
@@ -37,7 +37,7 @@
|
||||
"manifest": "plugins/anvil/plugin/Cargo.toml",
|
||||
"library": "anvil",
|
||||
"documentation": "docs/anvil",
|
||||
"clap_id": "io.storyboard.sub-anchor",
|
||||
"clap_id": "io.narl.bass-foundry.anvil",
|
||||
"licenses": {
|
||||
"plugins/common/ui/assets/OFL.txt": "licenses/Roboto-OFL.txt"
|
||||
},
|
||||
@@ -54,7 +54,7 @@
|
||||
"manifest": "plugins/crucible/plugin/Cargo.toml",
|
||||
"library": "crucible",
|
||||
"documentation": "docs/crucible",
|
||||
"clap_id": "io.storyboard.resampler",
|
||||
"clap_id": "io.narl.bass-foundry.crucible",
|
||||
"licenses": {
|
||||
"plugins/common/ui/assets/OFL.txt": "licenses/Roboto-OFL.txt"
|
||||
},
|
||||
@@ -71,7 +71,7 @@
|
||||
"manifest": "plugins/lathe/plugin/Cargo.toml",
|
||||
"library": "lathe",
|
||||
"documentation": "docs/lathe",
|
||||
"clap_id": "io.storyboard.harmonic-eq",
|
||||
"clap_id": "io.narl.bass-foundry.lathe",
|
||||
"licenses": {
|
||||
"plugins/common/ui/assets/OFL.txt": "licenses/Roboto-OFL.txt"
|
||||
},
|
||||
@@ -88,7 +88,7 @@
|
||||
"manifest": "plugins/temper/plugin/Cargo.toml",
|
||||
"library": "temper",
|
||||
"documentation": "docs/temper",
|
||||
"clap_id": "io.storyboard.tracked-distortion",
|
||||
"clap_id": "io.narl.bass-foundry.temper",
|
||||
"licenses": {
|
||||
"plugins/common/ui/assets/OFL.txt": "licenses/Roboto-OFL.txt"
|
||||
},
|
||||
@@ -98,5 +98,37 @@
|
||||
"temper-core",
|
||||
"temper-ui"
|
||||
]
|
||||
},
|
||||
"weld": {
|
||||
"name": "Weld",
|
||||
"description": "Align the phase of a bass layer to a sidechain layer so the two sum instead of cancel",
|
||||
"manifest": "plugins/weld/plugin/Cargo.toml",
|
||||
"library": "weld",
|
||||
"documentation": "docs/weld",
|
||||
"clap_id": "io.narl.bass-foundry.weld",
|
||||
"licenses": {
|
||||
"plugins/common/ui/assets/OFL.txt": "licenses/Roboto-OFL.txt"
|
||||
},
|
||||
"packages": [
|
||||
"common-ui",
|
||||
"weld-core",
|
||||
"weld-ui"
|
||||
]
|
||||
},
|
||||
"knurl": {
|
||||
"name": "Knurl",
|
||||
"description": "Give every cycle of the note its own level, timing and grit",
|
||||
"manifest": "plugins/knurl/plugin/Cargo.toml",
|
||||
"library": "knurl",
|
||||
"documentation": "docs/knurl",
|
||||
"clap_id": "io.narl.bass-foundry.knurl",
|
||||
"licenses": {
|
||||
"plugins/common/ui/assets/OFL.txt": "licenses/Roboto-OFL.txt"
|
||||
},
|
||||
"packages": [
|
||||
"common-ui",
|
||||
"knurl-core",
|
||||
"knurl-ui"
|
||||
]
|
||||
}
|
||||
}
|
||||
Generated
+1
-1
@@ -450,7 +450,7 @@ checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
|
||||
|
||||
[[package]]
|
||||
name = "crucible"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"clap-sys",
|
||||
"crucible-core",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "crucible"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
license = "ISC"
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ impl Default for Crucible {
|
||||
}
|
||||
impl Plugin for Crucible {
|
||||
const NAME: &'static str = "Crucible";
|
||||
const VENDOR: &'static str = "Rivet & Patina";
|
||||
const VENDOR: &'static str = "Bass Foundry";
|
||||
const URL: &'static str = "";
|
||||
const EMAIL: &'static str = "";
|
||||
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
|
||||
@@ -185,7 +185,7 @@ impl Plugin for Crucible {
|
||||
}
|
||||
}
|
||||
impl ClapPlugin for Crucible {
|
||||
const CLAP_ID: &'static str = "io.storyboard.resampler";
|
||||
const CLAP_ID: &'static str = "io.narl.bass-foundry.crucible";
|
||||
const CLAP_DESCRIPTION: Option<&'static str> =
|
||||
Some("Capture the last bars, slice them and export clean, key-labelled samples");
|
||||
const CLAP_MANUAL_URL: Option<&'static str> = None;
|
||||
|
||||
@@ -59,7 +59,10 @@ fn effect_ports_state_latency_and_audio_lifecycle() {
|
||||
let descriptor = factory.get_plugin_descriptor.unwrap()(factory, 0);
|
||||
assert!(!descriptor.is_null());
|
||||
assert_eq!(CStr::from_ptr((*descriptor).name), c"Crucible");
|
||||
assert_eq!(CStr::from_ptr((*descriptor).id), c"io.storyboard.resampler");
|
||||
assert_eq!(
|
||||
CStr::from_ptr((*descriptor).id),
|
||||
c"io.narl.bass-foundry.crucible"
|
||||
);
|
||||
assert!(factory.get_plugin_descriptor.unwrap()(factory, 1).is_null());
|
||||
let host = clap_host {
|
||||
clap_version: CLAP_VERSION,
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "knurl-core"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
common-dsp = { path = "../../common/dsp" }
|
||||
serde = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
serde_json = { workspace = true }
|
||||
@@ -0,0 +1,406 @@
|
||||
//! Knurl: texture per cycle of the played note. A cycle clock follows the tracked pitch and
|
||||
//! restarts at every note; each cycle gets its own step gain (a repeating pattern that
|
||||
//! makes subharmonics), a random level and timing, and a noise burst tuned to the note.
|
||||
//! Every amount is counted in cycles, so the texture has the same grain on every note.
|
||||
//!
|
||||
//! The audio path is delayed by the tracker lookahead plus the timing-jitter headroom, so
|
||||
//! the clock already knows each note when its attack leaves the plugin. Allocation-free
|
||||
//! after `new`; mono-safe (both channels get the same treatment).
|
||||
mod settings;
|
||||
use common_dsp::svf::{Svf, SvfCoef};
|
||||
use common_dsp::tracker::{PitchFollower, Tracker, TrackerConfig};
|
||||
use common_dsp::{coefficient, db_to_gain, hz_to_midi};
|
||||
pub use settings::{Seed, Settings, Source, GRIT_OFF, PATTERNS, STEPS, STEP_MIN};
|
||||
|
||||
/// Cycles kept for the editor's scope, and points per cycle.
|
||||
pub const SCOPE_CYCLES: usize = 8;
|
||||
pub const SCOPE_POINTS: usize = 64;
|
||||
/// Timing jitter can move a cycle by at most this share of the lowest period.
|
||||
const JITTER_HEADROOM: f32 = 0.125;
|
||||
/// Effects fade in and out with the note over this time.
|
||||
const FADE_MS: f32 = 20.;
|
||||
/// The grit filter is retuned this often, in samples.
|
||||
const RETUNE: usize = 16;
|
||||
/// Level follower for scaling the grit to the input.
|
||||
const LEVEL_MS: f32 = 30.;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct AnalyzerFrame {
|
||||
/// Fundamental the clock follows, 0 before the first note.
|
||||
pub hz: f32,
|
||||
/// Sounding note, rounded; None between notes.
|
||||
pub note: Option<u8>,
|
||||
/// Pattern step of the newest cycle.
|
||||
pub step: usize,
|
||||
/// Output of the last `SCOPE_CYCLES` cycles, oldest first, each resampled to
|
||||
/// `SCOPE_POINTS` points.
|
||||
pub scope: [[f32; SCOPE_POINTS]; SCOPE_CYCLES],
|
||||
/// True when the scope holds cycles of a sounding note.
|
||||
pub scope_valid: bool,
|
||||
pub input_db: f32,
|
||||
pub output_db: f32,
|
||||
pub latency: u32,
|
||||
pub sample_rate: f32,
|
||||
}
|
||||
impl Default for AnalyzerFrame {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
hz: 0.,
|
||||
note: None,
|
||||
step: 0,
|
||||
scope: [[0.; SCOPE_POINTS]; SCOPE_CYCLES],
|
||||
scope_valid: false,
|
||||
input_db: -120.,
|
||||
output_db: -120.,
|
||||
latency: 0,
|
||||
sample_rate: 48000.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Deterministic per-cycle randomness: a hash of (stream, note seed, cycle).
|
||||
fn hash(stream: u64, seed: u64, cycle: u64) -> u64 {
|
||||
let mut z = stream
|
||||
.wrapping_mul(0x9E37_79B9_7F4A_7C15)
|
||||
.wrapping_add(seed.wrapping_mul(0xBF58_476D_1CE4_E5B9))
|
||||
.wrapping_add(cycle.wrapping_mul(0x94D0_49BB_1331_11EB));
|
||||
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||
z ^ (z >> 31)
|
||||
}
|
||||
fn uniform(stream: u64, seed: u64, cycle: u64) -> f32 {
|
||||
(hash(stream, seed, cycle) >> 40) as f32 / (1u64 << 24) as f32
|
||||
}
|
||||
/// Approximately normal, clamped to ±3 (sum of four uniforms, unit variance).
|
||||
fn normal(stream: u64, seed: u64, cycle: u64) -> f32 {
|
||||
let s: f32 = (0..4).map(|i| uniform(stream, seed, cycle * 4 + i)).sum();
|
||||
((s - 2.) * 3f32.sqrt()).clamp(-3., 3.)
|
||||
}
|
||||
/// Raised-cosine weight of the next cycle's value: 0 until `1 − width` of the cycle, then
|
||||
/// rising to 1 at the boundary.
|
||||
fn edge(frac: f32, width: f32) -> f32 {
|
||||
let t = ((frac - (1. - width)) / width).clamp(0., 1.);
|
||||
0.5 - 0.5 * (std::f32::consts::PI * t).cos()
|
||||
}
|
||||
|
||||
const LEVEL: u64 = 1;
|
||||
const TIME: u64 = 2;
|
||||
const NOISE: u64 = 3;
|
||||
|
||||
/// What the clock needs, delayed by the jitter headroom so it lines up with the audio.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Pitch {
|
||||
hz: f32,
|
||||
start: bool,
|
||||
sounding: bool,
|
||||
}
|
||||
|
||||
pub struct Engine {
|
||||
rate: f32,
|
||||
channels: usize,
|
||||
settings: Settings,
|
||||
/// Tracker lookahead.
|
||||
lookahead: usize,
|
||||
/// Largest timing offset in samples, either way.
|
||||
headroom: usize,
|
||||
tracker: Tracker,
|
||||
pitch: PitchFollower,
|
||||
pitch_line: Vec<Pitch>,
|
||||
pitch_at: usize,
|
||||
audio: Vec<[f32; 2]>,
|
||||
audio_at: usize,
|
||||
// Cycle clock.
|
||||
phase: f64,
|
||||
cycle: u64,
|
||||
note_seed: u64,
|
||||
notes: u64,
|
||||
noise_at: u64,
|
||||
amount: f32,
|
||||
fade: f32,
|
||||
// Grit.
|
||||
grit_coef: SvfCoef,
|
||||
grit_filter: Svf,
|
||||
countdown: usize,
|
||||
level: f32,
|
||||
level_coef: f32,
|
||||
// Smoothed controls.
|
||||
smooth: f32,
|
||||
mix: f32,
|
||||
output: f32,
|
||||
bypass: f32,
|
||||
fresh: bool,
|
||||
// Editor.
|
||||
scope: [[f32; SCOPE_POINTS]; SCOPE_CYCLES],
|
||||
scope_valid: bool,
|
||||
meter_in: f64,
|
||||
meter_out: f64,
|
||||
meter_count: usize,
|
||||
}
|
||||
|
||||
impl Engine {
|
||||
pub fn new(rate: f32, channels: usize) -> Result<Self, &'static str> {
|
||||
if !(rate.is_finite() && (8000.0..=768000.).contains(&rate)) {
|
||||
return Err("unsupported sample rate");
|
||||
}
|
||||
if !(1..=2).contains(&channels) {
|
||||
return Err("unsupported channel count");
|
||||
}
|
||||
let tracker = Tracker::new(rate, TrackerConfig::BASS);
|
||||
let lookahead = tracker.latency();
|
||||
let headroom = (JITTER_HEADROOM * rate / TrackerConfig::BASS.min_hz).ceil() as usize;
|
||||
let settings = Settings::default();
|
||||
let mut e = Self {
|
||||
rate,
|
||||
channels,
|
||||
settings,
|
||||
lookahead,
|
||||
headroom,
|
||||
tracker,
|
||||
pitch: PitchFollower::default(),
|
||||
pitch_line: vec![Pitch::default(); headroom + 1],
|
||||
pitch_at: 0,
|
||||
// Reads reach `lookahead + 2·headroom` back, plus the interpolation taps.
|
||||
audio: vec![[0.; 2]; lookahead + 2 * headroom + 4],
|
||||
audio_at: 0,
|
||||
phase: 0.,
|
||||
cycle: 0,
|
||||
note_seed: 0,
|
||||
notes: 0,
|
||||
noise_at: 0,
|
||||
amount: 0.,
|
||||
fade: coefficient(rate, FADE_MS),
|
||||
grit_coef: SvfCoef::IDENTITY,
|
||||
grit_filter: Svf::default(),
|
||||
countdown: 0,
|
||||
level: 0.,
|
||||
level_coef: coefficient(rate, LEVEL_MS),
|
||||
smooth: coefficient(rate, 10.),
|
||||
mix: 1.,
|
||||
output: 1.,
|
||||
bypass: 0.,
|
||||
fresh: true,
|
||||
scope: [[0.; SCOPE_POINTS]; SCOPE_CYCLES],
|
||||
scope_valid: false,
|
||||
meter_in: 0.,
|
||||
meter_out: 0.,
|
||||
meter_count: 0,
|
||||
};
|
||||
e.set_settings(settings)?;
|
||||
e.fresh = true;
|
||||
Ok(e)
|
||||
}
|
||||
pub fn latency_samples(&self) -> u32 {
|
||||
(self.lookahead + self.headroom) as u32
|
||||
}
|
||||
pub fn channels(&self) -> usize {
|
||||
self.channels
|
||||
}
|
||||
pub fn settings(&self) -> Settings {
|
||||
self.settings
|
||||
}
|
||||
pub fn set_settings(&mut self, s: Settings) -> Result<(), &'static str> {
|
||||
s.validate()?;
|
||||
self.tracker.set(s.source == Source::Midi, s.gate, false);
|
||||
self.settings = s;
|
||||
if std::mem::take(&mut self.fresh) {
|
||||
self.mix = s.mix * 0.01;
|
||||
self.output = db_to_gain(s.output);
|
||||
self.bypass = f32::from(s.bypass);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn reset(&mut self) {
|
||||
self.audio.fill([0.; 2]);
|
||||
self.pitch_line.fill(Pitch::default());
|
||||
self.pitch = PitchFollower::default();
|
||||
self.tracker.reset();
|
||||
self.grit_filter.reset();
|
||||
self.phase = 0.;
|
||||
self.cycle = 0;
|
||||
self.notes = 0;
|
||||
self.note_seed = 0;
|
||||
self.noise_at = 0;
|
||||
self.amount = 0.;
|
||||
self.level = 0.;
|
||||
self.countdown = 0;
|
||||
self.scope_valid = false;
|
||||
self.fresh = true;
|
||||
}
|
||||
pub fn note_on(&mut self, note: u8) {
|
||||
self.tracker.note_on(note);
|
||||
}
|
||||
pub fn note_off(&mut self, note: u8) {
|
||||
self.tracker.note_off(note);
|
||||
}
|
||||
/// The audio `back` samples (fractional) before the newest one, cubic Hermite.
|
||||
#[inline]
|
||||
fn read(&self, back: f32) -> [f32; 2] {
|
||||
let len = self.audio.len();
|
||||
let whole = back.floor();
|
||||
let t = back - whole;
|
||||
let base = whole as usize;
|
||||
let at = |back: usize| self.audio[(self.audio_at + len - back % len) % len];
|
||||
// y0 is one sample newer than y1; y2 and y3 are older.
|
||||
let (newer, p1, p2, p3) = (at(base.max(1) - 1), at(base), at(base + 1), at(base + 2));
|
||||
let mut out = [0.; 2];
|
||||
for c in 0..2 {
|
||||
let (y0, y1, y2, y3) = (newer[c], p1[c], p2[c], p3[c]);
|
||||
let c1 = 0.5 * (y2 - y0);
|
||||
let c2 = y0 - 2.5 * y1 + 2. * y2 - 0.5 * y3;
|
||||
let c3 = 0.5 * (y3 - y0) + 1.5 * (y1 - y2);
|
||||
out[c] = ((c3 * t + c2) * t + c1) * t + y1;
|
||||
}
|
||||
out
|
||||
}
|
||||
pub fn process_sample(&mut self, x: [f32; 2]) -> [f32; 2] {
|
||||
let mono = if self.channels == 2 {
|
||||
0.5 * (x[0] + x[1])
|
||||
} else {
|
||||
x[0]
|
||||
};
|
||||
let (pitch, snap) = (&mut self.pitch, self.settings.snap);
|
||||
self.tracker.process(mono, |e| pitch.event(snap, e));
|
||||
let (hz, jump) = self.pitch.step(1.);
|
||||
// Tracker events are timed for `lookahead`; the audio leaves `headroom` later.
|
||||
let len = self.pitch_line.len();
|
||||
self.pitch_line[self.pitch_at] = Pitch {
|
||||
hz,
|
||||
start: jump,
|
||||
sounding: self.tracker.sounding(),
|
||||
};
|
||||
self.pitch_at = (self.pitch_at + 1) % len;
|
||||
let p = self.pitch_line[self.pitch_at];
|
||||
|
||||
let len = self.audio.len();
|
||||
self.audio_at = (self.audio_at + 1) % len;
|
||||
self.audio[self.audio_at] = x;
|
||||
let centre = (self.lookahead + self.headroom) as f32;
|
||||
let dry = self.read(centre);
|
||||
|
||||
// Cycle clock.
|
||||
if p.start {
|
||||
self.phase = 0.;
|
||||
self.cycle = 0;
|
||||
self.notes += 1;
|
||||
self.noise_at = 0;
|
||||
self.note_seed = match self.settings.seed {
|
||||
Seed::Same => 0,
|
||||
Seed::Free => self.notes,
|
||||
};
|
||||
self.countdown = 0;
|
||||
}
|
||||
let active = p.sounding && p.hz > 0.;
|
||||
self.amount += (f32::from(active) - self.amount) * self.fade;
|
||||
let s = self.settings;
|
||||
let frac = self.phase.fract() as f32;
|
||||
let c = self.cycle;
|
||||
let seed = self.note_seed;
|
||||
let step = |k: u64| (k % s.steps as u64) as usize;
|
||||
|
||||
// Pattern and level jitter, crossfaded into the next cycle.
|
||||
let w = edge(frac, s.edge * 0.01);
|
||||
let jitter_w = edge(frac, 0.5);
|
||||
let pattern = |k: u64| db_to_gain(s.pattern[step(k)]);
|
||||
let wobble = |k: u64| db_to_gain(s.level_jitter * normal(LEVEL, seed, k));
|
||||
let gain = (pattern(c) * (1. - w) + pattern(c + 1) * w)
|
||||
* (wobble(c) * (1. - jitter_w) + wobble(c + 1) * jitter_w);
|
||||
let gain = 1. + self.amount * (gain - 1.);
|
||||
|
||||
// Timing jitter: an offset per cycle, blended across the whole cycle.
|
||||
let period = if p.hz > 0. { self.rate / p.hz } else { 0. };
|
||||
let shift = |k: u64| normal(TIME, seed, k) * s.time_jitter * 0.01 * period;
|
||||
let tw = edge(frac, 1.);
|
||||
let offset = (shift(c) * (1. - tw) + shift(c + 1) * tw) * self.amount;
|
||||
let offset = offset.clamp(-(self.headroom as f32), self.headroom as f32);
|
||||
let moved = if offset == 0. {
|
||||
dry
|
||||
} else {
|
||||
self.read(centre + offset)
|
||||
};
|
||||
|
||||
// Grit: noise above `tone` harmonics, in a sin² window at `position` of each cycle.
|
||||
let mut grit = 0.;
|
||||
if s.grit > GRIT_OFF && p.hz > 0. && s.grit_steps[step(c)] {
|
||||
if self.countdown == 0 {
|
||||
let f = (s.tone * p.hz).min(0.45 * self.rate);
|
||||
self.grit_coef = SvfCoef::highpass(self.rate, f, std::f32::consts::FRAC_1_SQRT_2);
|
||||
self.countdown = RETUNE;
|
||||
}
|
||||
self.countdown -= 1;
|
||||
self.noise_at = self.noise_at.wrapping_add(1);
|
||||
let n = 2. * uniform(NOISE, seed, self.noise_at) - 1.;
|
||||
let hp = self.grit_filter.process(&self.grit_coef, n * 3f32.sqrt());
|
||||
let d = (frac - s.position * 0.01).rem_euclid(1.);
|
||||
let l = s.length * 0.01;
|
||||
if d < l {
|
||||
let window = (std::f32::consts::PI * d / l).sin().powi(2);
|
||||
grit = hp * window * self.level.sqrt() * db_to_gain(s.grit) * self.amount;
|
||||
}
|
||||
}
|
||||
let m = if self.channels == 2 {
|
||||
0.5 * (dry[0] + dry[1])
|
||||
} else {
|
||||
dry[0]
|
||||
};
|
||||
self.level += (m * m - self.level) * self.level_coef;
|
||||
// Advance the clock.
|
||||
if p.hz > 0. {
|
||||
self.phase += (p.hz / self.rate) as f64;
|
||||
let whole = self.phase.floor() as u64;
|
||||
if whole > 0 {
|
||||
self.phase -= whole as f64;
|
||||
self.cycle += whole;
|
||||
self.scope
|
||||
.rotate_left(whole.min(SCOPE_CYCLES as u64) as usize);
|
||||
self.scope[SCOPE_CYCLES - 1] = [0.; SCOPE_POINTS];
|
||||
}
|
||||
}
|
||||
|
||||
self.mix += (s.mix * 0.01 - self.mix) * self.smooth;
|
||||
self.output += (db_to_gain(s.output) - self.output) * self.smooth;
|
||||
self.bypass += (f32::from(s.bypass) - self.bypass) * self.smooth;
|
||||
let mut out = [0.; 2];
|
||||
for ch in 0..self.channels {
|
||||
let wet = moved[ch] * gain + grit;
|
||||
let mixed = (self.mix * wet + (1. - self.mix) * dry[ch]) * self.output;
|
||||
out[ch] = mixed * (1. - self.bypass) + dry[ch] * self.bypass;
|
||||
}
|
||||
let o = if self.channels == 2 {
|
||||
0.5 * (out[0] + out[1])
|
||||
} else {
|
||||
out[0]
|
||||
};
|
||||
if active {
|
||||
let i = ((frac * SCOPE_POINTS as f32) as usize).min(SCOPE_POINTS - 1);
|
||||
self.scope[SCOPE_CYCLES - 1][i] = o;
|
||||
self.scope_valid = true;
|
||||
}
|
||||
self.meter_in += (m * m) as f64;
|
||||
self.meter_out += (o * o) as f64;
|
||||
self.meter_count += 1;
|
||||
out
|
||||
}
|
||||
/// Editor data; levels are averaged since the previous call.
|
||||
pub fn take_analyzer(&mut self) -> AnalyzerFrame {
|
||||
let n = self.meter_count.max(1) as f64;
|
||||
let db = |p: f64| (10. * (p / n).max(1e-12).log10()).max(-120.) as f32;
|
||||
let mut f = AnalyzerFrame {
|
||||
hz: self.pitch.hz(),
|
||||
note: None,
|
||||
step: (self.cycle % self.settings.steps as u64) as usize,
|
||||
scope: self.scope,
|
||||
scope_valid: self.scope_valid,
|
||||
input_db: db(self.meter_in),
|
||||
output_db: db(self.meter_out),
|
||||
latency: self.latency_samples(),
|
||||
sample_rate: self.rate,
|
||||
};
|
||||
if self.tracker.sounding() && f.hz > 0. {
|
||||
f.note = Some(hz_to_midi(f.hz).round().clamp(0., 127.) as u8);
|
||||
}
|
||||
self.meter_in = 0.;
|
||||
self.meter_out = 0.;
|
||||
self.meter_count = 0;
|
||||
f
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
//! Host-independent controls. Gains in dB; amounts relative to one cycle in percent.
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Pattern steps: one per cycle, repeating.
|
||||
pub const STEPS: usize = 16;
|
||||
pub const STEP_MIN: f32 = -24.;
|
||||
/// Grit at or below this level is off.
|
||||
pub const GRIT_OFF: f32 = -60.;
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
pub enum Source {
|
||||
/// Pitch and note starts are detected from the incoming bass.
|
||||
#[default]
|
||||
Audio,
|
||||
/// Notes come from MIDI note input.
|
||||
Midi,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
pub enum Seed {
|
||||
/// Every note gets the same random sequence, so identical notes sound identical.
|
||||
#[default]
|
||||
Same,
|
||||
/// The random sequences keep running from note to note.
|
||||
Free,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Settings {
|
||||
pub source: Source,
|
||||
/// Gain per pattern step, 0 down to `STEP_MIN`.
|
||||
pub pattern: [f32; STEPS],
|
||||
/// Steps that get a grit burst.
|
||||
pub grit_steps: [bool; STEPS],
|
||||
/// Pattern length in cycles, 1..=STEPS.
|
||||
pub steps: usize,
|
||||
/// Crossfade into the next step, as a share of a cycle.
|
||||
pub edge: f32,
|
||||
/// Random level per cycle, standard deviation in dB.
|
||||
pub level_jitter: f32,
|
||||
/// Random timing per cycle, standard deviation in percent of a period.
|
||||
pub time_jitter: f32,
|
||||
/// Grit burst level relative to the input, dB; `GRIT_OFF` or lower is off.
|
||||
pub grit: f32,
|
||||
/// Grit highpass, in harmonics of the note.
|
||||
pub tone: f32,
|
||||
/// Where in the cycle the grit burst sits, percent.
|
||||
pub position: f32,
|
||||
/// Grit burst length, percent of a cycle.
|
||||
pub length: f32,
|
||||
pub seed: Seed,
|
||||
/// Detection threshold in dBFS for note starts (Audio source).
|
||||
pub gate: f32,
|
||||
/// Round detected pitch to the nearest semitone.
|
||||
pub snap: bool,
|
||||
pub mix: f32,
|
||||
pub output: f32,
|
||||
pub bypass: bool,
|
||||
}
|
||||
|
||||
/// Named step patterns: (name, help, gains). Missing steps are 0 dB.
|
||||
pub const PATTERNS: [(&str, &str, &[f32]); 6] = [
|
||||
("Off", "Every cycle at full level.", &[0.]),
|
||||
(
|
||||
"Double",
|
||||
"Every second cycle quieter: a sub-octave growl.",
|
||||
&[0., -9.],
|
||||
),
|
||||
(
|
||||
"Triple",
|
||||
"One loud cycle, two quiet: a growl an octave and a fifth down.",
|
||||
&[0., -12., -12.],
|
||||
),
|
||||
(
|
||||
"Fry",
|
||||
"Uneven four-cycle pattern: vocal-fry rattle.",
|
||||
&[0., -14., -5., -14.],
|
||||
),
|
||||
(
|
||||
"Gallop",
|
||||
"Loud, quiet, loud, then three quiet: a rolling gallop.",
|
||||
&[0., -18., 0., -18., -18., -18.],
|
||||
),
|
||||
(
|
||||
"Stutter",
|
||||
"Bursts of cycles with gaps: a gated stutter.",
|
||||
&[0., 0., -24., -24., 0., -24., -24., -24.],
|
||||
),
|
||||
];
|
||||
|
||||
impl Settings {
|
||||
/// Applies a named pattern: its gains, its length, grit on every step.
|
||||
pub fn apply_pattern(&mut self, gains: &[f32]) {
|
||||
self.pattern = [0.; STEPS];
|
||||
for (p, g) in self.pattern.iter_mut().zip(gains) {
|
||||
*p = *g;
|
||||
}
|
||||
self.steps = gains.len().clamp(1, STEPS);
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
let mut s = Self {
|
||||
source: Source::Audio,
|
||||
pattern: [0.; STEPS],
|
||||
grit_steps: [true; STEPS],
|
||||
steps: 1,
|
||||
edge: 15.,
|
||||
level_jitter: 1.,
|
||||
time_jitter: 3.,
|
||||
grit: -9.,
|
||||
tone: 12.,
|
||||
position: 10.,
|
||||
length: 12.,
|
||||
seed: Seed::Same,
|
||||
gate: -42.,
|
||||
snap: true,
|
||||
mix: 100.,
|
||||
output: 0.,
|
||||
bypass: false,
|
||||
};
|
||||
s.apply_pattern(PATTERNS[3].2);
|
||||
s
|
||||
}
|
||||
}
|
||||
impl Settings {
|
||||
pub fn validate(&self) -> Result<(), &'static str> {
|
||||
let finite = [
|
||||
self.edge,
|
||||
self.level_jitter,
|
||||
self.time_jitter,
|
||||
self.grit,
|
||||
self.tone,
|
||||
self.position,
|
||||
self.length,
|
||||
self.gate,
|
||||
self.mix,
|
||||
self.output,
|
||||
]
|
||||
.iter()
|
||||
.chain(self.pattern.iter())
|
||||
.all(|v| v.is_finite());
|
||||
if !finite {
|
||||
return Err("non-finite setting");
|
||||
}
|
||||
let ok = self.pattern.iter().all(|g| (STEP_MIN..=0.).contains(g))
|
||||
&& (1..=STEPS).contains(&self.steps)
|
||||
&& (5.0..=50.).contains(&self.edge)
|
||||
&& (0.0..=6.).contains(&self.level_jitter)
|
||||
&& (0.0..=10.).contains(&self.time_jitter)
|
||||
&& (GRIT_OFF..=0.).contains(&self.grit)
|
||||
&& (4.0..=64.).contains(&self.tone)
|
||||
&& (0.0..=100.).contains(&self.position)
|
||||
&& (2.0..=50.).contains(&self.length)
|
||||
&& (-60.0..=-20.).contains(&self.gate)
|
||||
&& (0.0..=100.).contains(&self.mix)
|
||||
&& (-12.0..=12.).contains(&self.output);
|
||||
if ok {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("setting out of range")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
use common_dsp::{midi_to_hz, Saw};
|
||||
use knurl_core::{Engine, Seed, Settings, Source, GRIT_OFF, PATTERNS};
|
||||
|
||||
const RATE: f32 = 48000.;
|
||||
|
||||
/// A tanh saw bass at `note`, as the prototype used.
|
||||
fn bass(note: u8, n: usize) -> Vec<f32> {
|
||||
let mut saw = Saw::new(RATE, midi_to_hz(note as f32));
|
||||
(0..n).map(|_| (2.2 * saw.sample()).tanh() * 0.5).collect()
|
||||
}
|
||||
fn plain() -> Settings {
|
||||
let mut s = Settings {
|
||||
source: Source::Midi,
|
||||
level_jitter: 0.,
|
||||
time_jitter: 0.,
|
||||
grit: GRIT_OFF,
|
||||
..Settings::default()
|
||||
};
|
||||
s.apply_pattern(PATTERNS[0].2);
|
||||
s
|
||||
}
|
||||
/// Runs one held note from sample 0 and returns the output, aligned to the input.
|
||||
fn run(settings: Settings, note: u8, input: &[f32]) -> Vec<f32> {
|
||||
let mut engine = Engine::new(RATE, 1).unwrap();
|
||||
engine.set_settings(settings).unwrap();
|
||||
let latency = engine.latency_samples() as usize;
|
||||
engine.note_on(note);
|
||||
let mut out: Vec<f32> = input
|
||||
.iter()
|
||||
.chain(std::iter::repeat_n(&0., latency))
|
||||
.map(|&x| engine.process_sample([x, 0.])[0])
|
||||
.collect();
|
||||
out.drain(..latency);
|
||||
out
|
||||
}
|
||||
/// Level of the component at `hz` (single-bin DFT with a Hann window), dB.
|
||||
fn level(x: &[f32], hz: f32) -> f64 {
|
||||
let n = x.len();
|
||||
let (mut re, mut im) = (0f64, 0f64);
|
||||
for (i, &v) in x.iter().enumerate() {
|
||||
let w = 0.5 - 0.5 * (std::f64::consts::TAU * i as f64 / n as f64).cos();
|
||||
let a = std::f64::consts::TAU * hz as f64 * i as f64 / RATE as f64;
|
||||
re += w * v as f64 * a.cos();
|
||||
im -= w * v as f64 * a.sin();
|
||||
}
|
||||
10. * (re * re + im * im).max(1e-30).log10()
|
||||
}
|
||||
fn subharmonic(out: &[f32], note: u8, divisor: f32) -> f64 {
|
||||
let f = midi_to_hz(note as f32);
|
||||
let seg = &out[4800..out.len() - 4800];
|
||||
level(seg, f / divisor) - level(seg, f)
|
||||
}
|
||||
fn max_step(x: &[f32]) -> f32 {
|
||||
x.windows(2).map(|w| (w[1] - w[0]).abs()).fold(0., f32::max)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn everything_off_is_the_delayed_input() {
|
||||
let input = bass(29, 24000);
|
||||
let out = run(plain(), 29, &input);
|
||||
assert_eq!(out, input);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn patterns_make_tuned_subharmonics_without_clicks() {
|
||||
let input = bass(29, 48000);
|
||||
let base = run(plain(), 29, &input);
|
||||
assert!(subharmonic(&base, 29, 2.) < -50.);
|
||||
for (pattern, divisor, expected) in [(1, 2., -8.2), (2, 3., -10.7)] {
|
||||
let mut s = plain();
|
||||
s.apply_pattern(PATTERNS[pattern].2);
|
||||
let out = run(s, 29, &input);
|
||||
let sub = subharmonic(&out, 29, divisor);
|
||||
assert!(
|
||||
(sub - expected).abs() < 0.5,
|
||||
"{}: {sub}",
|
||||
PATTERNS[pattern].0
|
||||
);
|
||||
assert!(
|
||||
max_step(&out) <= 1.05 * max_step(&input),
|
||||
"{}",
|
||||
PATTERNS[pattern].0
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_texture_is_the_same_on_every_note() {
|
||||
let mut s = plain();
|
||||
s.apply_pattern(PATTERNS[1].2);
|
||||
let low = run(s, 29, &bass(29, 48000));
|
||||
let high = run(s, 36, &bass(36, 48000));
|
||||
let (a, b) = (subharmonic(&low, 29, 2.), subharmonic(&high, 36, 2.));
|
||||
assert!((a - b).abs() < 0.3, "F1 {a} C2 {b}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_seed_repeats_every_note_and_free_does_not() {
|
||||
for (seed, identical) in [(Seed::Same, true), (Seed::Free, false)] {
|
||||
let s = Settings {
|
||||
source: Source::Midi,
|
||||
seed,
|
||||
..Settings::default()
|
||||
};
|
||||
let mut engine = Engine::new(RATE, 2).unwrap();
|
||||
engine.set_settings(s).unwrap();
|
||||
let latency = engine.latency_samples() as usize;
|
||||
let note = bass(29, 12000);
|
||||
let mut out = Vec::new();
|
||||
let starts = [0, 36000];
|
||||
for i in 0..72000 + latency {
|
||||
if starts.contains(&i) {
|
||||
engine.note_on(29);
|
||||
}
|
||||
if i == starts[0] + 12000 || i == starts[1] + 12000 {
|
||||
engine.note_off(29);
|
||||
}
|
||||
let k = starts
|
||||
.iter()
|
||||
.filter(|&&s| i >= s)
|
||||
.map(|&s| i - s)
|
||||
.min()
|
||||
.unwrap();
|
||||
let x = note.get(k).copied().unwrap_or(0.);
|
||||
out.push(engine.process_sample([x, x])[0]);
|
||||
}
|
||||
let first = &out[latency..latency + 12000];
|
||||
let second = &out[starts[1] + latency..starts[1] + latency + 12000];
|
||||
let largest = first
|
||||
.iter()
|
||||
.zip(second)
|
||||
.map(|(a, b)| (a - b).abs())
|
||||
.fold(0f32, f32::max);
|
||||
if identical {
|
||||
assert!(largest < 1e-4, "{seed:?}: {largest}");
|
||||
} else {
|
||||
assert!(largest > 1e-2, "{seed:?}: {largest}");
|
||||
}
|
||||
assert!(out.iter().all(|v| v.is_finite()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grit_follows_the_input_level_and_stops_with_the_note() {
|
||||
let mut s = plain();
|
||||
s.grit = -6.;
|
||||
let input = bass(29, 24000);
|
||||
let out = run(s, 29, &input);
|
||||
let noise: f64 = out
|
||||
.iter()
|
||||
.zip(&input)
|
||||
.skip(4800)
|
||||
.map(|(o, i)| ((o - i) as f64).powi(2))
|
||||
.sum::<f64>()
|
||||
/ (out.len() - 4800) as f64;
|
||||
let signal: f64 = input
|
||||
.iter()
|
||||
.skip(4800)
|
||||
.map(|v| (*v as f64).powi(2))
|
||||
.sum::<f64>()
|
||||
/ (out.len() - 4800) as f64;
|
||||
let ratio = 10. * (noise / signal).log10();
|
||||
// −6 dB bursts over 12 % of each cycle; the sin² window keeps 3/8 of the power:
|
||||
// −6 + 10·log10(0.12 · 0.375) = −19.5 dB.
|
||||
assert!((ratio + 19.5).abs() < 1.5, "{ratio}");
|
||||
|
||||
// Silence in, silence out: no grit without a note, and no NaN.
|
||||
let mut engine = Engine::new(RATE, 2).unwrap();
|
||||
engine.set_settings(Settings::default()).unwrap();
|
||||
for _ in 0..48000 {
|
||||
let out = engine.process_sample([0., 0.]);
|
||||
assert_eq!(out, [0., 0.]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_source_finds_the_note_and_reports_latency() {
|
||||
let mut s = plain();
|
||||
s.source = Source::Audio;
|
||||
s.apply_pattern(PATTERNS[1].2);
|
||||
let mut engine = Engine::new(RATE, 1).unwrap();
|
||||
engine.set_settings(s).unwrap();
|
||||
let latency = engine.latency_samples() as usize;
|
||||
// About 67 ms of lookahead plus 4.2 ms of jitter headroom.
|
||||
assert!((latency as f32 / RATE - 0.071).abs() < 0.005, "{latency}");
|
||||
let input = bass(29, 48000);
|
||||
let mut out: Vec<f32> = input
|
||||
.iter()
|
||||
.map(|&x| engine.process_sample([x, 0.])[0])
|
||||
.collect();
|
||||
out.drain(..latency);
|
||||
let frame = engine.take_analyzer();
|
||||
assert_eq!(frame.note, Some(29));
|
||||
assert!(frame.scope_valid);
|
||||
let sub = subharmonic(&out[..out.len() - 4800], 29, 2.);
|
||||
assert!(sub > -14., "{sub}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_settings_are_rejected() {
|
||||
let mut engine = Engine::new(RATE, 2).unwrap();
|
||||
for bad in [
|
||||
Settings {
|
||||
steps: 0,
|
||||
..Settings::default()
|
||||
},
|
||||
Settings {
|
||||
edge: 60.,
|
||||
..Settings::default()
|
||||
},
|
||||
Settings {
|
||||
grit: f32::NAN,
|
||||
..Settings::default()
|
||||
},
|
||||
Settings {
|
||||
time_jitter: 11.,
|
||||
..Settings::default()
|
||||
},
|
||||
] {
|
||||
assert!(engine.set_settings(bad).is_err());
|
||||
}
|
||||
let mut s = Settings::default();
|
||||
s.pattern[3] = -30.;
|
||||
assert!(engine.set_settings(s).is_err());
|
||||
assert!(Engine::new(1000., 2).is_err());
|
||||
assert!(Engine::new(48000., 3).is_err());
|
||||
let json = serde_json::to_string(&Settings::default()).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Settings>(&json).unwrap(),
|
||||
Settings::default()
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
use knurl_core::{Engine, Seed, Settings, Source, PATTERNS};
|
||||
use std::{
|
||||
alloc::{GlobalAlloc, Layout, System},
|
||||
cell::Cell,
|
||||
};
|
||||
|
||||
struct CheckedAllocator;
|
||||
thread_local! {
|
||||
static CHECK:Cell<bool>=const {Cell::new(false)};
|
||||
static OPERATIONS:Cell<usize>=const {Cell::new(0)};
|
||||
}
|
||||
fn record() {
|
||||
if CHECK.try_with(Cell::get).unwrap_or(false) {
|
||||
let _ = OPERATIONS.try_with(|n| n.set(n.get() + 1));
|
||||
}
|
||||
}
|
||||
unsafe impl GlobalAlloc for CheckedAllocator {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
record();
|
||||
unsafe { System.alloc(layout) }
|
||||
}
|
||||
unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
|
||||
record();
|
||||
unsafe { System.dealloc(pointer, layout) }
|
||||
}
|
||||
unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, size: usize) -> *mut u8 {
|
||||
record();
|
||||
unsafe { System.realloc(pointer, layout, size) }
|
||||
}
|
||||
}
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: CheckedAllocator = CheckedAllocator;
|
||||
|
||||
#[test]
|
||||
fn notes_patterns_grit_and_jitter_do_not_allocate_or_free() {
|
||||
let mut engine = Engine::new(48000., 2).unwrap();
|
||||
let mut settings = Settings::default();
|
||||
engine.set_settings(settings).unwrap();
|
||||
CHECK.with(|v| v.set(true));
|
||||
for i in 0..96000 {
|
||||
if i % 4800 == 0 {
|
||||
settings.apply_pattern(PATTERNS[(i / 4800) % PATTERNS.len()].2);
|
||||
settings.seed = if i > 48000 { Seed::Free } else { Seed::Same };
|
||||
settings.source = if (i / 4800) % 3 == 0 {
|
||||
Source::Midi
|
||||
} else {
|
||||
Source::Audio
|
||||
};
|
||||
settings.time_jitter = ((i / 4800) % 10) as f32;
|
||||
engine.set_settings(settings).unwrap();
|
||||
engine.note_on(30 + (i / 4800 % 12) as u8);
|
||||
}
|
||||
if i % 4800 == 2400 {
|
||||
engine.note_off(30 + (i / 4800 % 12) as u8);
|
||||
}
|
||||
let t = i as f32 / 48000.;
|
||||
let x = if (i / 2400) % 2 == 0 {
|
||||
(std::f32::consts::TAU * 55. * t).sin() * 0.5
|
||||
} else {
|
||||
0.
|
||||
};
|
||||
std::hint::black_box(engine.process_sample([x, x]));
|
||||
if i % 1600 == 0 {
|
||||
std::hint::black_box(engine.take_analyzer());
|
||||
}
|
||||
}
|
||||
engine.reset();
|
||||
CHECK.with(|v| v.set(false));
|
||||
assert_eq!(OPERATIONS.with(Cell::get), 0);
|
||||
}
|
||||
Generated
+2382
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "knurl"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
license = "ISC"
|
||||
|
||||
[workspace]
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
nih_plug = { git = "https://github.com/robbert-vdh/nih-plug.git", rev = "de421011f41a6d10fc8c7a6084e4f4dee0143683", default-features = false }
|
||||
nih_plug_egui = { git = "https://github.com/robbert-vdh/nih-plug.git", rev = "de421011f41a6d10fc8c7a6084e4f4dee0143683" }
|
||||
knurl-core = { path = "../core" }
|
||||
knurl-ui = { path = "../ui" }
|
||||
crossbeam-queue = "0.3"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
clap-sys = { git = "https://github.com/micahrj/clap-sys.git", rev = "25d7f53fdb6363ad63fbd80049cb7a42a97ac156" }
|
||||
serde_json = "1"
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
strip = "symbols"
|
||||
@@ -0,0 +1,195 @@
|
||||
//! CLAP audio effect. All DSP state is owned by the processing thread.
|
||||
mod params;
|
||||
use crossbeam_queue::ArrayQueue;
|
||||
use knurl_core::{AnalyzerFrame, Engine};
|
||||
use nih_plug::prelude::*;
|
||||
use nih_plug_egui::{create_egui_editor, egui};
|
||||
use params::{KnurlParams, Pattern, GESTURES};
|
||||
use std::sync::Arc;
|
||||
|
||||
struct EditorData {
|
||||
ui: knurl_ui::State,
|
||||
gestures: [bool; GESTURES],
|
||||
}
|
||||
pub struct Knurl {
|
||||
params: Arc<KnurlParams>,
|
||||
analyzer: Arc<ArrayQueue<AnalyzerFrame>>,
|
||||
engine: Option<Engine>,
|
||||
pattern: Pattern,
|
||||
publish_count: usize,
|
||||
publish_interval: usize,
|
||||
}
|
||||
impl Default for Knurl {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
params: Arc::new(KnurlParams::default()),
|
||||
analyzer: Arc::new(ArrayQueue::new(2)),
|
||||
engine: None,
|
||||
pattern: Pattern::default(),
|
||||
publish_count: 0,
|
||||
publish_interval: 1600,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Plugin for Knurl {
|
||||
const NAME: &'static str = "Knurl";
|
||||
const VENDOR: &'static str = "Bass Foundry";
|
||||
const URL: &'static str = "";
|
||||
const EMAIL: &'static str = "";
|
||||
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
|
||||
const AUDIO_IO_LAYOUTS: &'static [AudioIOLayout] = &[
|
||||
AudioIOLayout {
|
||||
main_input_channels: NonZeroU32::new(2),
|
||||
main_output_channels: NonZeroU32::new(2),
|
||||
..AudioIOLayout::const_default()
|
||||
},
|
||||
AudioIOLayout {
|
||||
main_input_channels: NonZeroU32::new(1),
|
||||
main_output_channels: NonZeroU32::new(1),
|
||||
..AudioIOLayout::const_default()
|
||||
},
|
||||
];
|
||||
const MIDI_INPUT: MidiConfig = MidiConfig::Basic;
|
||||
const SAMPLE_ACCURATE_AUTOMATION: bool = false;
|
||||
type SysExMessage = ();
|
||||
type BackgroundTask = ();
|
||||
fn params(&self) -> Arc<dyn Params> {
|
||||
self.params.clone()
|
||||
}
|
||||
fn editor(&mut self, _: AsyncExecutor<Self>) -> Option<Box<dyn Editor>> {
|
||||
let params = self.params.clone();
|
||||
let analyzer = self.analyzer.clone();
|
||||
create_egui_editor(
|
||||
params.editor.clone(),
|
||||
EditorData {
|
||||
ui: knurl_ui::State::default(),
|
||||
gestures: [false; GESTURES],
|
||||
},
|
||||
|ctx, _| knurl_ui::style(ctx),
|
||||
move |ctx, setter, data| {
|
||||
while let Some(frame) = analyzer.pop() {
|
||||
data.ui.accept_frame(frame);
|
||||
}
|
||||
let current = params.pattern();
|
||||
let before = params.settings(¤t);
|
||||
let mut edited = before;
|
||||
nih_plug_egui::resizable_window::ResizableWindow::new("knurl-editor")
|
||||
.min_size(egui::vec2(
|
||||
knurl_ui::WIDTH as f32 - 80.,
|
||||
knurl_ui::HEIGHT as f32 - 40.,
|
||||
))
|
||||
.show(ctx, ¶ms.editor, |ui| {
|
||||
knurl_ui::show(ui, &mut edited, &mut data.ui)
|
||||
});
|
||||
params.apply(
|
||||
setter,
|
||||
&before,
|
||||
&edited,
|
||||
data.ui.gesture_active,
|
||||
&mut data.gestures,
|
||||
);
|
||||
// The scope follows the audio.
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(40));
|
||||
},
|
||||
)
|
||||
}
|
||||
fn initialize(
|
||||
&mut self,
|
||||
layout: &AudioIOLayout,
|
||||
config: &BufferConfig,
|
||||
context: &mut impl InitContext<Self>,
|
||||
) -> bool {
|
||||
let Ok(mut engine) = Engine::new(
|
||||
config.sample_rate,
|
||||
layout.main_input_channels.map_or(0, |v| v.get() as usize),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
let settings = self.params.settings(&self.pattern);
|
||||
self.pattern = Pattern {
|
||||
gains: settings.pattern,
|
||||
grit: settings.grit_steps,
|
||||
};
|
||||
if engine.set_settings(settings).is_err() {
|
||||
return false;
|
||||
}
|
||||
context.set_latency_samples(engine.latency_samples());
|
||||
self.publish_interval = (config.sample_rate / 30.) as usize;
|
||||
self.engine = Some(engine);
|
||||
true
|
||||
}
|
||||
fn reset(&mut self) {
|
||||
if let Some(e) = self.engine.as_mut() {
|
||||
e.reset();
|
||||
}
|
||||
self.publish_count = 0;
|
||||
}
|
||||
fn process(
|
||||
&mut self,
|
||||
buffer: &mut Buffer,
|
||||
_: &mut AuxiliaryBuffers,
|
||||
context: &mut impl ProcessContext<Self>,
|
||||
) -> ProcessStatus {
|
||||
let Some(engine) = self.engine.as_mut() else {
|
||||
return ProcessStatus::Normal;
|
||||
};
|
||||
let settings = self.params.settings(&self.pattern);
|
||||
self.pattern = Pattern {
|
||||
gains: settings.pattern,
|
||||
grit: settings.grit_steps,
|
||||
};
|
||||
let _ = engine.set_settings(settings);
|
||||
let mut next = context.next_event();
|
||||
for (index, mut sample) in buffer.iter_samples().enumerate() {
|
||||
while let Some(event) = next {
|
||||
if event.timing() as usize > index {
|
||||
break;
|
||||
}
|
||||
match event {
|
||||
NoteEvent::NoteOn { note, velocity, .. } if velocity > 0. => {
|
||||
engine.note_on(note)
|
||||
}
|
||||
NoteEvent::NoteOn { note, .. } | NoteEvent::NoteOff { note, .. } => {
|
||||
engine.note_off(note)
|
||||
}
|
||||
NoteEvent::Choke { note, .. } => engine.note_off(note),
|
||||
_ => {}
|
||||
}
|
||||
next = context.next_event();
|
||||
}
|
||||
let x = [
|
||||
*sample.get_mut(0).unwrap(),
|
||||
if engine.channels() == 2 {
|
||||
*sample.get_mut(1).unwrap()
|
||||
} else {
|
||||
0.
|
||||
},
|
||||
];
|
||||
let out = engine.process_sample(x);
|
||||
for (c, value) in sample.into_iter().enumerate() {
|
||||
*value = out[c];
|
||||
}
|
||||
self.publish_count += 1;
|
||||
if self.publish_count >= self.publish_interval {
|
||||
self.analyzer.force_push(engine.take_analyzer());
|
||||
self.publish_count = 0;
|
||||
}
|
||||
}
|
||||
// The lookahead delay and filter tails must drain after input stops.
|
||||
ProcessStatus::KeepAlive
|
||||
}
|
||||
}
|
||||
impl ClapPlugin for Knurl {
|
||||
const CLAP_ID: &'static str = "io.narl.bass-foundry.knurl";
|
||||
const CLAP_DESCRIPTION: Option<&'static str> =
|
||||
Some("Texture per cycle of the played note: patterns, jitter and grit that fit every note");
|
||||
const CLAP_MANUAL_URL: Option<&'static str> = None;
|
||||
const CLAP_SUPPORT_URL: Option<&'static str> = None;
|
||||
const CLAP_FEATURES: &'static [ClapFeature] = &[
|
||||
ClapFeature::AudioEffect,
|
||||
ClapFeature::Distortion,
|
||||
ClapFeature::Stereo,
|
||||
ClapFeature::Mono,
|
||||
];
|
||||
}
|
||||
nih_export_clap!(Knurl);
|
||||
@@ -0,0 +1,255 @@
|
||||
use knurl_core::{Seed, Settings, Source, GRIT_OFF, STEPS, STEP_MIN};
|
||||
use nih_plug::prelude::*;
|
||||
use nih_plug_egui::EguiState;
|
||||
use std::sync::{Arc, RwLock};
|
||||
|
||||
#[derive(Enum, Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub enum SourceParam {
|
||||
#[id = "audio"]
|
||||
Audio,
|
||||
#[id = "midi"]
|
||||
#[name = "MIDI"]
|
||||
Midi,
|
||||
}
|
||||
#[derive(Enum, Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub enum SeedParam {
|
||||
#[id = "same"]
|
||||
#[name = "Same every note"]
|
||||
Same,
|
||||
#[id = "free"]
|
||||
Free,
|
||||
}
|
||||
fn linear(name: &str, v: f32, min: f32, max: f32, unit: &'static str) -> FloatParam {
|
||||
FloatParam::new(name, v, FloatRange::Linear { min, max }).with_unit(unit)
|
||||
}
|
||||
/// Continuous controls, in the order of the gesture slots.
|
||||
const FLOATS: usize = 10;
|
||||
pub const GESTURES: usize = FLOATS;
|
||||
|
||||
/// The drawn pattern: step gains and grit switches. Saved with the project, not automation.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct Pattern {
|
||||
pub gains: [f32; STEPS],
|
||||
pub grit: [bool; STEPS],
|
||||
}
|
||||
impl Default for Pattern {
|
||||
fn default() -> Self {
|
||||
let d = Settings::default();
|
||||
Self {
|
||||
gains: d.pattern,
|
||||
grit: d.grit_steps,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Params)]
|
||||
pub struct KnurlParams {
|
||||
#[persist = "editor"]
|
||||
pub editor: Arc<EguiState>,
|
||||
#[persist = "knurl-pattern"]
|
||||
pub pattern: RwLock<Pattern>,
|
||||
#[id = "source"]
|
||||
pub source: EnumParam<SourceParam>,
|
||||
#[id = "seed"]
|
||||
pub seed: EnumParam<SeedParam>,
|
||||
#[id = "steps"]
|
||||
pub steps: IntParam,
|
||||
#[id = "edge"]
|
||||
pub edge: FloatParam,
|
||||
#[id = "level-jitter"]
|
||||
pub level_jitter: FloatParam,
|
||||
#[id = "time-jitter"]
|
||||
pub time_jitter: FloatParam,
|
||||
#[id = "grit"]
|
||||
pub grit: FloatParam,
|
||||
#[id = "tone"]
|
||||
pub tone: FloatParam,
|
||||
#[id = "position"]
|
||||
pub position: FloatParam,
|
||||
#[id = "length"]
|
||||
pub length: FloatParam,
|
||||
#[id = "gate"]
|
||||
pub gate: FloatParam,
|
||||
#[id = "mix"]
|
||||
pub mix: FloatParam,
|
||||
#[id = "output"]
|
||||
pub output: FloatParam,
|
||||
#[id = "snap"]
|
||||
pub snap: BoolParam,
|
||||
#[id = "bypass"]
|
||||
pub bypass: BoolParam,
|
||||
}
|
||||
impl Default for KnurlParams {
|
||||
fn default() -> Self {
|
||||
let d = Settings::default();
|
||||
Self {
|
||||
editor: EguiState::from_size(knurl_ui::WIDTH, knurl_ui::HEIGHT),
|
||||
pattern: RwLock::new(Pattern::default()),
|
||||
source: EnumParam::new("Pitch source", SourceParam::Audio),
|
||||
seed: EnumParam::new("Random", SeedParam::Same),
|
||||
steps: IntParam::new(
|
||||
"Steps",
|
||||
d.steps as i32,
|
||||
IntRange::Linear {
|
||||
min: 1,
|
||||
max: STEPS as i32,
|
||||
},
|
||||
),
|
||||
edge: linear("Edge", d.edge, 5., 50., " %"),
|
||||
level_jitter: linear("Level jitter", d.level_jitter, 0., 6., " dB"),
|
||||
time_jitter: linear("Time jitter", d.time_jitter, 0., 10., " %"),
|
||||
grit: linear("Grit", d.grit, GRIT_OFF, 0., " dB").with_value_to_string(Arc::new(|v| {
|
||||
if v <= GRIT_OFF {
|
||||
"Off".into()
|
||||
} else {
|
||||
format!("{v:.1}")
|
||||
}
|
||||
})),
|
||||
tone: FloatParam::new(
|
||||
"Tone",
|
||||
d.tone,
|
||||
FloatRange::Skewed {
|
||||
min: 4.,
|
||||
max: 64.,
|
||||
factor: FloatRange::skew_factor(-1.),
|
||||
},
|
||||
)
|
||||
.with_unit(" ×f0"),
|
||||
position: linear("Position", d.position, 0., 100., " %"),
|
||||
length: linear("Length", d.length, 2., 50., " %"),
|
||||
gate: linear("Gate", d.gate, -60., -20., " dB"),
|
||||
mix: linear("Mix", d.mix, 0., 100., " %"),
|
||||
output: linear("Output", d.output, -12., 12., " dB"),
|
||||
snap: BoolParam::new("Snap to semitone", d.snap),
|
||||
bypass: BoolParam::new("Bypass", false).make_bypass(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl KnurlParams {
|
||||
/// Current settings. The pattern falls back to `last` when the editor holds the lock,
|
||||
/// so the audio thread never waits.
|
||||
pub fn settings(&self, last: &Pattern) -> Settings {
|
||||
let pattern = self.pattern.try_read().map(|p| *p).unwrap_or(*last);
|
||||
Settings {
|
||||
source: match self.source.value() {
|
||||
SourceParam::Audio => Source::Audio,
|
||||
SourceParam::Midi => Source::Midi,
|
||||
},
|
||||
pattern: pattern.gains.map(|g| {
|
||||
if g.is_finite() {
|
||||
g.clamp(STEP_MIN, 0.)
|
||||
} else {
|
||||
0.
|
||||
}
|
||||
}),
|
||||
grit_steps: pattern.grit,
|
||||
steps: self.steps.value().clamp(1, STEPS as i32) as usize,
|
||||
edge: self.edge.value(),
|
||||
level_jitter: self.level_jitter.value(),
|
||||
time_jitter: self.time_jitter.value(),
|
||||
grit: self.grit.value(),
|
||||
tone: self.tone.value(),
|
||||
position: self.position.value(),
|
||||
length: self.length.value(),
|
||||
seed: match self.seed.value() {
|
||||
SeedParam::Same => Seed::Same,
|
||||
SeedParam::Free => Seed::Free,
|
||||
},
|
||||
gate: self.gate.value(),
|
||||
snap: self.snap.value(),
|
||||
mix: self.mix.value(),
|
||||
output: self.output.value(),
|
||||
bypass: self.bypass.value(),
|
||||
}
|
||||
}
|
||||
pub fn pattern(&self) -> Pattern {
|
||||
self.pattern.read().map(|p| *p).unwrap_or_default()
|
||||
}
|
||||
fn floats(&self) -> [&FloatParam; FLOATS] {
|
||||
[
|
||||
&self.edge,
|
||||
&self.level_jitter,
|
||||
&self.time_jitter,
|
||||
&self.grit,
|
||||
&self.tone,
|
||||
&self.position,
|
||||
&self.length,
|
||||
&self.gate,
|
||||
&self.mix,
|
||||
&self.output,
|
||||
]
|
||||
}
|
||||
/// Pushes every changed editor value to the host. Continuous controls hold one gesture
|
||||
/// while the pointer is down; switches are set in a single gesture. The pattern is
|
||||
/// stored directly.
|
||||
pub fn apply(
|
||||
&self,
|
||||
setter: &ParamSetter,
|
||||
old: &Settings,
|
||||
new: &Settings,
|
||||
dragging: bool,
|
||||
open: &mut [bool; FLOATS],
|
||||
) {
|
||||
if new.pattern != old.pattern || new.grit_steps != old.grit_steps {
|
||||
if let Ok(mut p) = self.pattern.write() {
|
||||
*p = Pattern {
|
||||
gains: new.pattern,
|
||||
grit: new.grit_steps,
|
||||
};
|
||||
}
|
||||
}
|
||||
let values = [
|
||||
(old.edge, new.edge),
|
||||
(old.level_jitter, new.level_jitter),
|
||||
(old.time_jitter, new.time_jitter),
|
||||
(old.grit, new.grit),
|
||||
(old.tone, new.tone),
|
||||
(old.position, new.position),
|
||||
(old.length, new.length),
|
||||
(old.gate, new.gate),
|
||||
(old.mix, new.mix),
|
||||
(old.output, new.output),
|
||||
];
|
||||
for (i, (p, (a, b))) in self.floats().into_iter().zip(values).enumerate() {
|
||||
if a != b {
|
||||
if !open[i] {
|
||||
open[i] = true;
|
||||
setter.begin_set_parameter(p);
|
||||
}
|
||||
setter.set_parameter(p, b);
|
||||
}
|
||||
if !dragging && open[i] {
|
||||
setter.end_set_parameter(p);
|
||||
open[i] = false;
|
||||
}
|
||||
}
|
||||
fn switch<P: Param>(setter: &ParamSetter, p: &P, v: P::Plain) {
|
||||
setter.begin_set_parameter(p);
|
||||
setter.set_parameter(p, v);
|
||||
setter.end_set_parameter(p);
|
||||
}
|
||||
if new.steps != old.steps {
|
||||
switch(setter, &self.steps, new.steps as i32);
|
||||
}
|
||||
if new.snap != old.snap {
|
||||
switch(setter, &self.snap, new.snap);
|
||||
}
|
||||
if new.bypass != old.bypass {
|
||||
switch(setter, &self.bypass, new.bypass);
|
||||
}
|
||||
if new.source != old.source {
|
||||
let v = match new.source {
|
||||
Source::Audio => SourceParam::Audio,
|
||||
Source::Midi => SourceParam::Midi,
|
||||
};
|
||||
switch(setter, &self.source, v);
|
||||
}
|
||||
if new.seed != old.seed {
|
||||
let v = match new.seed {
|
||||
Seed::Same => SeedParam::Same,
|
||||
Seed::Free => SeedParam::Free,
|
||||
};
|
||||
switch(setter, &self.seed, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
//! Exercise the actual exported CLAP ABI without requiring a GUI or installed DAW.
|
||||
use clap_sys::{
|
||||
audio_buffer::*,
|
||||
events::*,
|
||||
ext::{audio_ports::*, latency::*, state::*},
|
||||
factory::plugin_factory::*,
|
||||
host::*,
|
||||
process::*,
|
||||
stream::*,
|
||||
version::*,
|
||||
};
|
||||
use std::{
|
||||
ffi::{c_char, c_void, CStr},
|
||||
io::{Cursor, Read},
|
||||
ptr,
|
||||
};
|
||||
|
||||
unsafe extern "C" fn extension(_: *const clap_host, _: *const c_char) -> *const c_void {
|
||||
ptr::null()
|
||||
}
|
||||
unsafe extern "C" fn request(_: *const clap_host) {}
|
||||
unsafe extern "C" fn count(_: *const clap_input_events) -> u32 {
|
||||
0
|
||||
}
|
||||
unsafe extern "C" fn event(_: *const clap_input_events, _: u32) -> *const clap_event_header {
|
||||
ptr::null()
|
||||
}
|
||||
unsafe extern "C" fn push(_: *const clap_output_events, _: *const clap_event_header) -> bool {
|
||||
true
|
||||
}
|
||||
unsafe extern "C" fn write(stream: *const clap_ostream, buffer: *const c_void, size: u64) -> i64 {
|
||||
// SAFETY: The test owns the Vec for the entire synchronous save call.
|
||||
let bytes = unsafe { &mut *((*stream).ctx as *mut Vec<u8>) };
|
||||
bytes.extend_from_slice(unsafe {
|
||||
std::slice::from_raw_parts(buffer as *const u8, size as usize)
|
||||
});
|
||||
size as i64
|
||||
}
|
||||
unsafe extern "C" fn read(stream: *const clap_istream, buffer: *mut c_void, size: u64) -> i64 {
|
||||
// SAFETY: The test owns the Cursor; the wrapper supplies writable stream storage.
|
||||
let cursor = unsafe { &mut *((*stream).ctx as *mut Cursor<Vec<u8>>) };
|
||||
cursor
|
||||
.read(unsafe { std::slice::from_raw_parts_mut(buffer as *mut u8, size as usize) })
|
||||
.unwrap() as i64
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn effect_ports_state_latency_and_audio_lifecycle() {
|
||||
// SAFETY: All callbacks, strings, streams, buffers, and the host outlive their
|
||||
// synchronous ABI calls. Activation/processing/destruction follow CLAP order.
|
||||
unsafe {
|
||||
let entry = &knurl::clap_entry;
|
||||
assert!(entry.init.unwrap()(c"knurl.clap".as_ptr()));
|
||||
let factory = entry.get_factory.unwrap()(CLAP_PLUGIN_FACTORY_ID.as_ptr())
|
||||
as *const clap_plugin_factory;
|
||||
assert!(!factory.is_null());
|
||||
let factory = &*factory;
|
||||
assert_eq!(factory.get_plugin_count.unwrap()(factory), 1);
|
||||
let descriptor = factory.get_plugin_descriptor.unwrap()(factory, 0);
|
||||
assert!(!descriptor.is_null());
|
||||
assert_eq!(CStr::from_ptr((*descriptor).name), c"Knurl");
|
||||
assert_eq!(
|
||||
CStr::from_ptr((*descriptor).id),
|
||||
c"io.narl.bass-foundry.knurl"
|
||||
);
|
||||
assert!(factory.get_plugin_descriptor.unwrap()(factory, 1).is_null());
|
||||
let host = clap_host {
|
||||
clap_version: CLAP_VERSION,
|
||||
host_data: ptr::null_mut(),
|
||||
name: c"Storyboard test host".as_ptr(),
|
||||
vendor: c"Tests".as_ptr(),
|
||||
url: c"".as_ptr(),
|
||||
version: c"1.0".as_ptr(),
|
||||
get_extension: Some(extension),
|
||||
request_restart: Some(request),
|
||||
request_process: Some(request),
|
||||
request_callback: Some(request),
|
||||
};
|
||||
let plugin = factory.create_plugin.unwrap()(factory, &host, (*descriptor).id);
|
||||
assert!(!plugin.is_null());
|
||||
let p = &*plugin;
|
||||
assert!(p.init.unwrap()(plugin));
|
||||
let ports = p.get_extension.unwrap()(plugin, CLAP_EXT_AUDIO_PORTS.as_ptr())
|
||||
as *const clap_plugin_audio_ports;
|
||||
assert!(!ports.is_null());
|
||||
assert_eq!((*ports).count.unwrap()(plugin, false), 1);
|
||||
assert_eq!((*ports).count.unwrap()(plugin, true), 1);
|
||||
let latency = p.get_extension.unwrap()(plugin, CLAP_EXT_LATENCY.as_ptr())
|
||||
as *const clap_plugin_latency;
|
||||
assert!(!latency.is_null());
|
||||
let state =
|
||||
p.get_extension.unwrap()(plugin, CLAP_EXT_STATE.as_ptr()) as *const clap_plugin_state;
|
||||
assert!(!state.is_null());
|
||||
let state = &*state;
|
||||
let save = || {
|
||||
let mut bytes = Vec::new();
|
||||
let stream = clap_ostream {
|
||||
ctx: &mut bytes as *mut Vec<u8> as *mut c_void,
|
||||
write: Some(write),
|
||||
};
|
||||
assert!(state.save.unwrap()(plugin, &stream));
|
||||
bytes
|
||||
};
|
||||
let mut envelope: nih_plug::prelude::PluginState =
|
||||
serde_json::from_slice(&save()[8..]).unwrap();
|
||||
use nih_plug::wrapper::state::ParamValue;
|
||||
envelope.params.insert("edge".into(), ParamValue::F32(30.));
|
||||
envelope.params.insert("steps".into(), ParamValue::I32(3));
|
||||
envelope
|
||||
.params
|
||||
.insert("seed".into(), ParamValue::String("free".into()));
|
||||
envelope
|
||||
.params
|
||||
.insert("source".into(), ParamValue::String("midi".into()));
|
||||
// Pitch from MIDI and no note arrives, so the audio check below sees the dry input
|
||||
// even with a pattern set.
|
||||
envelope
|
||||
.params
|
||||
.insert("level-jitter".into(), ParamValue::F32(0.));
|
||||
envelope
|
||||
.params
|
||||
.insert("time-jitter".into(), ParamValue::F32(0.));
|
||||
envelope.params.insert("grit".into(), ParamValue::F32(-60.));
|
||||
let (gains, grit) = ([-6f32; 16], [true; 16]);
|
||||
let mut pattern = serde_json::json!({ "gains": gains, "grit": grit });
|
||||
pattern["grit"][5] = false.into();
|
||||
envelope
|
||||
.fields
|
||||
.insert("knurl-pattern".into(), pattern.to_string());
|
||||
let encoded = serde_json::to_vec(&envelope).unwrap();
|
||||
let mut framed = (encoded.len() as u64).to_le_bytes().to_vec();
|
||||
framed.extend_from_slice(&encoded);
|
||||
let mut bytes = Cursor::new(framed);
|
||||
let stream = clap_istream {
|
||||
ctx: &mut bytes as *mut Cursor<Vec<u8>> as *mut c_void,
|
||||
read: Some(read),
|
||||
};
|
||||
assert!(state.load.unwrap()(plugin, &stream));
|
||||
let restored: nih_plug::prelude::PluginState =
|
||||
serde_json::from_slice(&save()[8..]).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::to_value(&restored.params).unwrap(),
|
||||
serde_json::to_value(&envelope.params).unwrap()
|
||||
);
|
||||
let saved: serde_json::Value =
|
||||
serde_json::from_str(&restored.fields["knurl-pattern"]).unwrap();
|
||||
assert_eq!(saved, pattern);
|
||||
for rate in [44100., 48000., 96000.] {
|
||||
assert!(p.activate.unwrap()(plugin, rate, 1, 512));
|
||||
let delay = (*latency).get.unwrap()(plugin) as usize;
|
||||
// About 67 ms lookahead plus 4.2 ms of timing-jitter headroom.
|
||||
assert!((delay as f64 / rate - 0.071).abs() < 0.01, "{delay}");
|
||||
assert!(p.start_processing.unwrap()(plugin));
|
||||
let total = delay + 9600;
|
||||
let mut position = 0;
|
||||
let (mut energy_in, mut energy_out) = (0f64, 0f64);
|
||||
while position < total {
|
||||
let frames = [1, 127, 512, 31][position % 4].min(total - position);
|
||||
// With no MIDI note and every effect off, a tone passes through unchanged.
|
||||
let tone = |n: usize| {
|
||||
0.25 * (std::f64::consts::TAU * 1000. * n as f64 / rate).sin() as f32
|
||||
};
|
||||
let mut input_left = [0f32; 512];
|
||||
let mut input_right = [0f32; 512];
|
||||
for i in 0..frames {
|
||||
input_left[i] = tone(position + i);
|
||||
input_right[i] = -tone(position + i);
|
||||
}
|
||||
let mut left = [0f32; 512];
|
||||
let mut right = [0f32; 512];
|
||||
let mut in_channels = [input_left.as_mut_ptr(), input_right.as_mut_ptr()];
|
||||
let mut out_channels = [left.as_mut_ptr(), right.as_mut_ptr()];
|
||||
let incoming = clap_audio_buffer {
|
||||
data32: in_channels.as_mut_ptr(),
|
||||
data64: ptr::null_mut(),
|
||||
channel_count: 2,
|
||||
latency: 0,
|
||||
constant_mask: 0,
|
||||
};
|
||||
let mut outgoing_audio = clap_audio_buffer {
|
||||
data32: out_channels.as_mut_ptr(),
|
||||
data64: ptr::null_mut(),
|
||||
channel_count: 2,
|
||||
latency: 0,
|
||||
constant_mask: 0,
|
||||
};
|
||||
let input = clap_input_events {
|
||||
ctx: ptr::null_mut(),
|
||||
size: Some(count),
|
||||
get: Some(event),
|
||||
};
|
||||
let outgoing = clap_output_events {
|
||||
ctx: ptr::null_mut(),
|
||||
try_push: Some(push),
|
||||
};
|
||||
let process = clap_process {
|
||||
steady_time: position as i64,
|
||||
frames_count: frames as u32,
|
||||
transport: ptr::null(),
|
||||
audio_inputs: &incoming,
|
||||
audio_outputs: &mut outgoing_audio,
|
||||
audio_inputs_count: 1,
|
||||
audio_outputs_count: 1,
|
||||
in_events: &input,
|
||||
out_events: &outgoing,
|
||||
};
|
||||
assert_ne!(p.process.unwrap()(plugin, &process), CLAP_PROCESS_ERROR);
|
||||
for i in 0..frames {
|
||||
let n = position + i;
|
||||
if n < delay {
|
||||
assert!(left[i].abs() < 1e-6, "output before the lookahead");
|
||||
} else if n > delay + 4800 {
|
||||
energy_in += (tone(n - delay) as f64).powi(2);
|
||||
energy_out += (left[i] as f64).powi(2) + (right[i] as f64).powi(2);
|
||||
}
|
||||
}
|
||||
position += frames;
|
||||
}
|
||||
let ratio_db = 10. * (energy_out / (2. * energy_in)).log10();
|
||||
assert!(ratio_db.abs() < 0.2, "{ratio_db}");
|
||||
p.stop_processing.unwrap()(plugin);
|
||||
p.deactivate.unwrap()(plugin);
|
||||
}
|
||||
p.destroy.unwrap()(plugin);
|
||||
entry.deinit.unwrap()();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
[package]
|
||||
name = "knurl-ui"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
egui = "0.31.1"
|
||||
knurl-core = { path = "../core" }
|
||||
common-ui = { path = "../../common/ui" }
|
||||
common-dsp = { path = "../../common/dsp" }
|
||||
@@ -0,0 +1,501 @@
|
||||
//! Knurl editor, shared by the CLAP wrapper and the headless renderer.
|
||||
use common_ui::*;
|
||||
use egui::{self, Color32, FontId, Pos2, Rect, RichText, Sense, Stroke, Vec2};
|
||||
use knurl_core::{
|
||||
AnalyzerFrame, Seed, Settings, Source, GRIT_OFF, PATTERNS, SCOPE_CYCLES, SCOPE_POINTS, STEPS,
|
||||
STEP_MIN,
|
||||
};
|
||||
|
||||
pub use common_ui::style;
|
||||
pub const WIDTH: u32 = 1040;
|
||||
pub const HEIGHT: u32 = 650;
|
||||
|
||||
const GRID: Color32 = Color32::from_rgb(24, 26, 30);
|
||||
const TOP: f32 = 316.;
|
||||
|
||||
pub struct State {
|
||||
pub analyzer: AnalyzerFrame,
|
||||
/// True while a pointer button is held, so knob drags become one host gesture.
|
||||
pub gesture_active: bool,
|
||||
pub help: String,
|
||||
}
|
||||
impl Default for State {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
analyzer: AnalyzerFrame::default(),
|
||||
gesture_active: false,
|
||||
help: DEFAULT_HELP.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
const DEFAULT_HELP: &str =
|
||||
"Every cycle of the note gets its own level, timing and grit. Counted in cycles, so it fits every note.";
|
||||
impl State {
|
||||
pub fn accept_frame(&mut self, frame: AnalyzerFrame) {
|
||||
let old = self.analyzer;
|
||||
self.analyzer = frame;
|
||||
self.analyzer.input_db = frame.input_db.max(old.input_db - 3.);
|
||||
self.analyzer.output_db = frame.output_db.max(old.output_db - 3.);
|
||||
// Keep the last scope between notes.
|
||||
if !frame.scope_valid && old.scope_valid {
|
||||
self.analyzer.scope = old.scope;
|
||||
self.analyzer.scope_valid = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
fn hint(r: &egui::Response, state: &mut State, text: &str) {
|
||||
if r.hovered() || r.has_focus() {
|
||||
state.help = text.into();
|
||||
}
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn knob(
|
||||
ui: &mut egui::Ui,
|
||||
state: &mut State,
|
||||
name: &str,
|
||||
value: &mut f32,
|
||||
range: std::ops::RangeInclusive<f32>,
|
||||
default: f32,
|
||||
unit: &str,
|
||||
help: &str,
|
||||
) {
|
||||
ui.vertical_centered(|ui| {
|
||||
let r = rotary(ui, name, value, range, default, unit, 58., ACCENT);
|
||||
hint(&r, state, help);
|
||||
});
|
||||
}
|
||||
|
||||
pub fn show(ui: &mut egui::Ui, settings: &mut Settings, state: &mut State) {
|
||||
backdrop(ui);
|
||||
state.help = DEFAULT_HELP.into();
|
||||
state.gesture_active = ui.input(|i| i.pointer.any_down());
|
||||
ui.add_space(2.);
|
||||
header(ui, "KNURL", "CYCLE TEXTURE", |ui| {
|
||||
let r = ui
|
||||
.selectable_label(settings.bypass, RichText::new("BYPASS").size(13.))
|
||||
.on_hover_text("Crossfade to the delayed dry signal.");
|
||||
if r.clicked() {
|
||||
settings.bypass = !settings.bypass;
|
||||
}
|
||||
ui.separator();
|
||||
for (source, label) in [(Source::Midi, "MIDI"), (Source::Audio, "AUDIO")] {
|
||||
let r = ui.selectable_label(settings.source == source, RichText::new(label).size(13.));
|
||||
if r.clicked() {
|
||||
settings.source = source;
|
||||
}
|
||||
}
|
||||
caption(ui, "PITCH FROM");
|
||||
});
|
||||
ui.add_space(6.);
|
||||
ui.horizontal_top(|ui| {
|
||||
panel(ui, |ui| {
|
||||
ui.set_width(210.);
|
||||
ui.set_min_height(TOP);
|
||||
ui.vertical(|ui| note_panel(ui, settings, state));
|
||||
});
|
||||
ui.add_space(4.);
|
||||
panel(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.vertical(|ui| {
|
||||
let frame = state.analyzer;
|
||||
scope(ui, &frame, 140.);
|
||||
ui.add_space(4.);
|
||||
pattern_editor(ui, settings, state, TOP - 144.);
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.add_space(6.);
|
||||
panel(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.vertical(|ui| controls(ui, settings, state));
|
||||
});
|
||||
ui.separator();
|
||||
ui.label(RichText::new(&state.help).color(MUTED));
|
||||
}
|
||||
|
||||
fn note_panel(ui: &mut egui::Ui, settings: &mut Settings, state: &mut State) {
|
||||
let frame = state.analyzer;
|
||||
caption(ui, "NOTE");
|
||||
let (name, hz) = match frame.note {
|
||||
Some(n) if frame.hz > 0. => (common_dsp::note_name(n), format!("{:.1} Hz", frame.hz)),
|
||||
_ if frame.hz > 0. => ("—".into(), format!("holding {:.1} Hz", frame.hz)),
|
||||
_ => ("—".into(), "no note yet".into()),
|
||||
};
|
||||
ui.label(
|
||||
RichText::new(name)
|
||||
.font(FontId::new(54., egui::FontFamily::Name("medium".into())))
|
||||
.color(if frame.note.is_some() { TEXT } else { DIM }),
|
||||
);
|
||||
ui.label(RichText::new(hz).size(13.).color(MUTED));
|
||||
if frame.hz > 0. {
|
||||
ui.label(
|
||||
RichText::new(format!("one cycle = {:.1} ms", 1000. / frame.hz))
|
||||
.size(12.)
|
||||
.color(DIM),
|
||||
);
|
||||
}
|
||||
ui.add_space(10.);
|
||||
meter(ui, "IN", frame.input_db, STEEL, 110.);
|
||||
meter(ui, "OUT", frame.output_db, ACCENT, 110.);
|
||||
ui.add_space(10.);
|
||||
caption(ui, "RANDOM");
|
||||
ui.horizontal(|ui| {
|
||||
for (seed, label, help) in [
|
||||
(
|
||||
Seed::Same,
|
||||
"SAME EVERY NOTE",
|
||||
"Every note gets the same random sequence: identical notes sound identical.",
|
||||
),
|
||||
(
|
||||
Seed::Free,
|
||||
"FREE",
|
||||
"The random sequences keep running, so every note differs.",
|
||||
),
|
||||
] {
|
||||
let r = ui.selectable_label(settings.seed == seed, RichText::new(label).size(12.));
|
||||
if r.clicked() {
|
||||
settings.seed = seed;
|
||||
}
|
||||
hint(&r, state, help);
|
||||
}
|
||||
});
|
||||
ui.add_space(6.);
|
||||
let r = ui.checkbox(
|
||||
&mut settings.snap,
|
||||
RichText::new("Snap to semitone").size(12.),
|
||||
);
|
||||
hint(
|
||||
&r,
|
||||
state,
|
||||
"Round the detected pitch. Turn it off for slides.",
|
||||
);
|
||||
}
|
||||
|
||||
/// The last cycles of the output, overlaid; the newest is brightest.
|
||||
fn scope(ui: &mut egui::Ui, frame: &AnalyzerFrame, height: f32) {
|
||||
let (outer, _) =
|
||||
ui.allocate_exact_size(Vec2::new(ui.available_width(), height), Sense::hover());
|
||||
let p = ui.painter_at(outer);
|
||||
p.rect_filled(outer, 2., SCREEN);
|
||||
p.text(
|
||||
outer.left_top() + Vec2::new(8., 5.),
|
||||
egui::Align2::LEFT_TOP,
|
||||
format!("LAST {SCOPE_CYCLES} CYCLES, OVERLAID"),
|
||||
FontId::proportional(10.),
|
||||
MUTED,
|
||||
);
|
||||
let plot = Rect::from_min_max(
|
||||
outer.left_top() + Vec2::new(10., 20.),
|
||||
outer.right_bottom() - Vec2::new(10., 8.),
|
||||
);
|
||||
for t in [0.25f32, 0.5, 0.75] {
|
||||
let x = plot.left() + plot.width() * t;
|
||||
p.line_segment(
|
||||
[Pos2::new(x, plot.top()), Pos2::new(x, plot.bottom())],
|
||||
Stroke::new(1.0_f32, GRID),
|
||||
);
|
||||
}
|
||||
p.line_segment(
|
||||
[
|
||||
Pos2::new(plot.left(), plot.center().y),
|
||||
Pos2::new(plot.right(), plot.center().y),
|
||||
],
|
||||
Stroke::new(1.0_f32, EDGE),
|
||||
);
|
||||
if !frame.scope_valid {
|
||||
p.text(
|
||||
plot.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
"play a note",
|
||||
FontId::proportional(12.),
|
||||
DIM,
|
||||
);
|
||||
return;
|
||||
}
|
||||
let peak = frame
|
||||
.scope
|
||||
.iter()
|
||||
.flatten()
|
||||
.fold(1e-6f32, |m, v| m.max(v.abs()));
|
||||
// The newest cycle is still being written; draw the complete ones.
|
||||
for (age, cycle) in frame.scope[..SCOPE_CYCLES - 1].iter().enumerate() {
|
||||
let alpha = 0.2 + 0.8 * age as f32 / (SCOPE_CYCLES - 2) as f32;
|
||||
let color = if age == SCOPE_CYCLES - 2 {
|
||||
ACCENT
|
||||
} else {
|
||||
STEEL.gamma_multiply(alpha * 0.6)
|
||||
};
|
||||
let points: Vec<Pos2> = cycle
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, v)| {
|
||||
Pos2::new(
|
||||
plot.left() + plot.width() * i as f32 / (SCOPE_POINTS - 1) as f32,
|
||||
plot.center().y - plot.height() * 0.48 * v / peak,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
p.add(egui::Shape::line(
|
||||
points,
|
||||
Stroke::new(
|
||||
if age == SCOPE_CYCLES - 2 {
|
||||
2.0_f32
|
||||
} else {
|
||||
1.0
|
||||
},
|
||||
color,
|
||||
),
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn step_y(rect: Rect, db: f32) -> f32 {
|
||||
rect.top() + rect.height() * (db / STEP_MIN).clamp(0., 1.)
|
||||
}
|
||||
|
||||
/// One bar per step: drag to set its level, double-click to reset; the square below a bar
|
||||
/// switches its grit burst.
|
||||
fn pattern_editor(ui: &mut egui::Ui, settings: &mut Settings, state: &mut State, height: f32) {
|
||||
let (outer, response) = ui.allocate_exact_size(
|
||||
Vec2::new(ui.available_width(), height),
|
||||
Sense::click_and_drag(),
|
||||
);
|
||||
let p = ui.painter_at(outer);
|
||||
p.rect_filled(outer, 2., SCREEN);
|
||||
p.text(
|
||||
outer.left_top() + Vec2::new(8., 5.),
|
||||
egui::Align2::LEFT_TOP,
|
||||
"PATTERN: LEVEL PER CYCLE",
|
||||
FontId::proportional(10.),
|
||||
MUTED,
|
||||
);
|
||||
let bars = Rect::from_min_max(
|
||||
outer.left_top() + Vec2::new(34., 22.),
|
||||
Pos2::new(outer.right() - 10., outer.bottom() - 26.),
|
||||
);
|
||||
let toggles_y = outer.bottom() - 16.;
|
||||
let col = bars.width() / STEPS as f32;
|
||||
let column =
|
||||
|x: f32| (((x - bars.left()) / col).floor() as isize).clamp(0, STEPS as isize - 1) as usize;
|
||||
if response.hovered() {
|
||||
state.help = "Drag a bar to set the level of that cycle; double-click resets it. The squares switch grit per step.".into();
|
||||
}
|
||||
if let Some(pos) = response.interact_pointer_pos() {
|
||||
let k = column(pos.x);
|
||||
if pos.y > bars.bottom() + 2. {
|
||||
if response.clicked() {
|
||||
settings.grit_steps[k] = !settings.grit_steps[k];
|
||||
}
|
||||
} else if response.double_clicked() {
|
||||
settings.pattern[k] = 0.;
|
||||
} else if response.dragged() || response.clicked() {
|
||||
let t = ((pos.y - bars.top()) / bars.height()).clamp(0., 1.);
|
||||
let db = t * STEP_MIN;
|
||||
settings.pattern[k] = if db > -0.5 { 0. } else { db.round() };
|
||||
if k >= settings.steps {
|
||||
settings.steps = k + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
for db in [0f32, -6., -12., -18., -24.] {
|
||||
let y = step_y(bars, db);
|
||||
p.line_segment(
|
||||
[Pos2::new(bars.left(), y), Pos2::new(bars.right(), y)],
|
||||
Stroke::new(1.0_f32, GRID),
|
||||
);
|
||||
p.text(
|
||||
Pos2::new(outer.left() + 6., y),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
if db == 0. {
|
||||
"0".into()
|
||||
} else {
|
||||
format!("{db:.0}")
|
||||
},
|
||||
FontId::proportional(10.),
|
||||
DIM,
|
||||
);
|
||||
}
|
||||
let current = state.analyzer.step;
|
||||
let playing = state.analyzer.note.is_some();
|
||||
for k in 0..STEPS {
|
||||
let on = k < settings.steps;
|
||||
let x0 = bars.left() + k as f32 * col + 3.;
|
||||
let x1 = x0 + col - 6.;
|
||||
let top = step_y(bars, settings.pattern[k]);
|
||||
let color = if !on {
|
||||
DIM.gamma_multiply(0.5)
|
||||
} else if playing && k == current {
|
||||
TEXT
|
||||
} else {
|
||||
ACCENT
|
||||
};
|
||||
p.rect_filled(
|
||||
Rect::from_min_max(
|
||||
Pos2::new(x0, top.min(bars.bottom() - 2.)),
|
||||
Pos2::new(x1, bars.bottom()),
|
||||
),
|
||||
1.,
|
||||
color.gamma_multiply(if on { 0.85 } else { 0.4 }),
|
||||
);
|
||||
let grit = settings.grit_steps[k] && settings.grit > GRIT_OFF;
|
||||
let square = Rect::from_center_size(Pos2::new((x0 + x1) / 2., toggles_y), Vec2::splat(9.));
|
||||
if settings.grit_steps[k] {
|
||||
p.rect_filled(square, 1., if grit && on { FOCUS } else { DIM });
|
||||
} else {
|
||||
p.rect_stroke(
|
||||
square,
|
||||
1.,
|
||||
Stroke::new(1.0_f32, DIM),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
}
|
||||
}
|
||||
p.text(
|
||||
Pos2::new(outer.left() + 6., toggles_y),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"grit",
|
||||
FontId::proportional(10.),
|
||||
DIM,
|
||||
);
|
||||
}
|
||||
|
||||
fn controls(ui: &mut egui::Ui, settings: &mut Settings, state: &mut State) {
|
||||
let d = Settings::default();
|
||||
ui.horizontal(|ui| {
|
||||
caption(ui, "PATTERN");
|
||||
for (name, help, gains) in PATTERNS {
|
||||
let selected = settings.steps == gains.len()
|
||||
&& settings.pattern[..gains.len()]
|
||||
.iter()
|
||||
.zip(gains)
|
||||
.all(|(a, b)| a == b);
|
||||
let r = ui.selectable_label(selected, RichText::new(name.to_uppercase()).size(13.));
|
||||
if r.clicked() {
|
||||
settings.apply_pattern(gains);
|
||||
}
|
||||
hint(&r, state, help);
|
||||
}
|
||||
ui.add_space(24.);
|
||||
caption(ui, "STEPS");
|
||||
let minus = ui.button(RichText::new("−").size(14.));
|
||||
if minus.clicked() && settings.steps > 1 {
|
||||
settings.steps -= 1;
|
||||
}
|
||||
ui.label(
|
||||
RichText::new(format!("{:>2}", settings.steps))
|
||||
.monospace()
|
||||
.size(14.)
|
||||
.color(TEXT),
|
||||
);
|
||||
let plus = ui.button(RichText::new("+").size(14.));
|
||||
if plus.clicked() && settings.steps < STEPS {
|
||||
settings.steps += 1;
|
||||
}
|
||||
let help = "Pattern length in cycles. 2 makes a sub-octave, 3 an octave and a fifth down.";
|
||||
hint(&minus, state, help);
|
||||
hint(&plus, state, help);
|
||||
});
|
||||
ui.add_space(4.);
|
||||
ui.columns(10, |c| {
|
||||
knob(
|
||||
&mut c[0],
|
||||
state,
|
||||
"Edge",
|
||||
&mut settings.edge,
|
||||
5. ..=50.,
|
||||
d.edge,
|
||||
" %",
|
||||
"How soft each step change is, as a share of a cycle. Low is sharper and buzzier.",
|
||||
);
|
||||
knob(
|
||||
&mut c[1],
|
||||
state,
|
||||
"Level",
|
||||
&mut settings.level_jitter,
|
||||
0. ..=6.,
|
||||
d.level_jitter,
|
||||
" dB",
|
||||
"Random level per cycle: a rough, living surface.",
|
||||
);
|
||||
knob(
|
||||
&mut c[2],
|
||||
state,
|
||||
"Time",
|
||||
&mut settings.time_jitter,
|
||||
0. ..=10.,
|
||||
d.time_jitter,
|
||||
" %",
|
||||
"Random timing per cycle, in percent of a period: rattle and scrape.",
|
||||
);
|
||||
knob(
|
||||
&mut c[3],
|
||||
state,
|
||||
"Grit",
|
||||
&mut settings.grit,
|
||||
GRIT_OFF..=0.,
|
||||
d.grit,
|
||||
" dB",
|
||||
"Level of the noise burst in each cycle, relative to the input. Fully left is off.",
|
||||
);
|
||||
knob(
|
||||
&mut c[4],
|
||||
state,
|
||||
"Tone",
|
||||
&mut settings.tone,
|
||||
4. ..=64.,
|
||||
d.tone,
|
||||
" ×f0",
|
||||
"Lowest frequency of the grit, in harmonics of the note.",
|
||||
);
|
||||
knob(
|
||||
&mut c[5],
|
||||
state,
|
||||
"Position",
|
||||
&mut settings.position,
|
||||
0. ..=100.,
|
||||
d.position,
|
||||
" %",
|
||||
"Where in the cycle the grit burst sits.",
|
||||
);
|
||||
knob(
|
||||
&mut c[6],
|
||||
state,
|
||||
"Length",
|
||||
&mut settings.length,
|
||||
2. ..=50.,
|
||||
d.length,
|
||||
" %",
|
||||
"Length of the grit burst, as a share of a cycle.",
|
||||
);
|
||||
knob(
|
||||
&mut c[7],
|
||||
state,
|
||||
"Gate",
|
||||
&mut settings.gate,
|
||||
-60. ..=-20.,
|
||||
d.gate,
|
||||
" dB",
|
||||
"Input level that counts as a note (AUDIO). Raise it if tails retrigger.",
|
||||
);
|
||||
knob(
|
||||
&mut c[8],
|
||||
state,
|
||||
"Mix",
|
||||
&mut settings.mix,
|
||||
0. ..=100.,
|
||||
d.mix,
|
||||
" %",
|
||||
"Blend with the delayed dry signal.",
|
||||
);
|
||||
knob(
|
||||
&mut c[9],
|
||||
state,
|
||||
"Output",
|
||||
&mut settings.output,
|
||||
-12. ..=12.,
|
||||
d.output,
|
||||
" dB",
|
||||
"Output trim.",
|
||||
);
|
||||
});
|
||||
}
|
||||
Generated
+1
-1
@@ -861,7 +861,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "lathe"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"clap-sys",
|
||||
"crossbeam-queue",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "lathe"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
license = "ISC"
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ impl Default for Lathe {
|
||||
}
|
||||
impl Plugin for Lathe {
|
||||
const NAME: &'static str = "Lathe";
|
||||
const VENDOR: &'static str = "Rivet & Patina";
|
||||
const VENDOR: &'static str = "Bass Foundry";
|
||||
const URL: &'static str = "";
|
||||
const EMAIL: &'static str = "";
|
||||
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
|
||||
@@ -174,7 +174,7 @@ impl Plugin for Lathe {
|
||||
}
|
||||
}
|
||||
impl ClapPlugin for Lathe {
|
||||
const CLAP_ID: &'static str = "io.storyboard.harmonic-eq";
|
||||
const CLAP_ID: &'static str = "io.narl.bass-foundry.lathe";
|
||||
const CLAP_DESCRIPTION: Option<&'static str> =
|
||||
Some("EQ the harmonics of the played note: a cut on harmonic 3 stays on harmonic 3");
|
||||
const CLAP_MANUAL_URL: Option<&'static str> = None;
|
||||
|
||||
@@ -61,7 +61,7 @@ fn effect_ports_state_latency_and_audio_lifecycle() {
|
||||
assert_eq!(CStr::from_ptr((*descriptor).name), c"Lathe");
|
||||
assert_eq!(
|
||||
CStr::from_ptr((*descriptor).id),
|
||||
c"io.storyboard.harmonic-eq"
|
||||
c"io.narl.bass-foundry.lathe"
|
||||
);
|
||||
assert!(factory.get_plugin_descriptor.unwrap()(factory, 1).is_null());
|
||||
let host = clap_host {
|
||||
|
||||
Generated
+1
-1
@@ -1419,7 +1419,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "patina"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"clap-sys",
|
||||
"crossbeam-queue",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "patina"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
edition = "2021"
|
||||
license = "ISC"
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ impl Default for Patina {
|
||||
}
|
||||
impl Plugin for Patina {
|
||||
const NAME: &'static str = "Patina";
|
||||
const VENDOR: &'static str = "Rivet & Patina";
|
||||
const VENDOR: &'static str = "Bass Foundry";
|
||||
const URL: &'static str = "";
|
||||
const EMAIL: &'static str = "";
|
||||
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
|
||||
@@ -187,7 +187,7 @@ fn store_epoch(ctx: &egui::Context, e: u64) {
|
||||
ctx.data_mut(|d| d.insert_temp(egui::Id::new("reset-epoch"), e));
|
||||
}
|
||||
impl ClapPlugin for Patina {
|
||||
const CLAP_ID: &'static str = "io.storyboard.resonance-compressor";
|
||||
const CLAP_ID: &'static str = "io.narl.bass-foundry.patina";
|
||||
const CLAP_DESCRIPTION: Option<&'static str> =
|
||||
Some("Dynamic resonance attenuation with explicit tone protection");
|
||||
const CLAP_MANUAL_URL: Option<&'static str> = None;
|
||||
|
||||
@@ -61,7 +61,7 @@ fn effect_ports_state_latency_and_audio_lifecycle() {
|
||||
assert_eq!(CStr::from_ptr((*descriptor).name), c"Patina");
|
||||
assert_eq!(
|
||||
CStr::from_ptr((*descriptor).id),
|
||||
c"io.storyboard.resonance-compressor"
|
||||
c"io.narl.bass-foundry.patina"
|
||||
);
|
||||
assert!(factory.get_plugin_descriptor.unwrap()(factory, 1).is_null());
|
||||
let host = clap_host {
|
||||
|
||||
Generated
+1
-1
@@ -2054,7 +2054,7 @@ checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
||||
|
||||
[[package]]
|
||||
name = "rivet"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
dependencies = [
|
||||
"clap-sys",
|
||||
"nih_plug",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "rivet"
|
||||
version = "0.4.0"
|
||||
version = "0.5.0"
|
||||
edition = "2021"
|
||||
license = "ISC"
|
||||
|
||||
|
||||
@@ -66,7 +66,7 @@ impl Default for Rivet {
|
||||
}
|
||||
impl Plugin for Rivet {
|
||||
const NAME: &'static str = "Rivet";
|
||||
const VENDOR: &'static str = "Rivet & Patina";
|
||||
const VENDOR: &'static str = "Bass Foundry";
|
||||
const URL: &'static str = "";
|
||||
const EMAIL: &'static str = "";
|
||||
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
|
||||
@@ -177,7 +177,7 @@ impl Plugin for Rivet {
|
||||
}
|
||||
}
|
||||
impl ClapPlugin for Rivet {
|
||||
const CLAP_ID: &'static str = "io.storyboard.motif";
|
||||
const CLAP_ID: &'static str = "io.narl.bass-foundry.rivet";
|
||||
const CLAP_DESCRIPTION: Option<&'static str> = Some(
|
||||
"Tell a MIDI motif as a story: a storyboard of statement, answer, departure and return",
|
||||
);
|
||||
|
||||
@@ -59,7 +59,10 @@ fn exported_factory_state_and_silent_audio_lifecycle() {
|
||||
let descriptor = factory.get_plugin_descriptor.unwrap()(factory, 0);
|
||||
assert!(!descriptor.is_null());
|
||||
assert_eq!(CStr::from_ptr((*descriptor).name), c"Rivet");
|
||||
assert_eq!(CStr::from_ptr((*descriptor).id), c"io.storyboard.motif");
|
||||
assert_eq!(
|
||||
CStr::from_ptr((*descriptor).id),
|
||||
c"io.narl.bass-foundry.rivet"
|
||||
);
|
||||
assert!(factory.get_plugin_descriptor.unwrap()(factory, 1).is_null());
|
||||
let host = clap_host {
|
||||
clap_version: CLAP_VERSION,
|
||||
|
||||
Generated
+1
-1
@@ -1734,7 +1734,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "temper"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"clap-sys",
|
||||
"crossbeam-queue",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "temper"
|
||||
version = "0.1.0"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
license = "ISC"
|
||||
|
||||
|
||||
@@ -31,7 +31,7 @@ impl Default for Temper {
|
||||
}
|
||||
impl Plugin for Temper {
|
||||
const NAME: &'static str = "Temper";
|
||||
const VENDOR: &'static str = "Rivet & Patina";
|
||||
const VENDOR: &'static str = "Bass Foundry";
|
||||
const URL: &'static str = "";
|
||||
const EMAIL: &'static str = "";
|
||||
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
|
||||
@@ -167,7 +167,7 @@ impl Plugin for Temper {
|
||||
}
|
||||
}
|
||||
impl ClapPlugin for Temper {
|
||||
const CLAP_ID: &'static str = "io.storyboard.tracked-distortion";
|
||||
const CLAP_ID: &'static str = "io.narl.bass-foundry.temper";
|
||||
const CLAP_DESCRIPTION: Option<&'static str> = Some(
|
||||
"Distortion whose drive and tone filters follow the note, so every note distorts the same",
|
||||
);
|
||||
|
||||
@@ -61,7 +61,7 @@ fn effect_ports_state_latency_and_audio_lifecycle() {
|
||||
assert_eq!(CStr::from_ptr((*descriptor).name), c"Temper");
|
||||
assert_eq!(
|
||||
CStr::from_ptr((*descriptor).id),
|
||||
c"io.storyboard.tracked-distortion"
|
||||
c"io.narl.bass-foundry.temper"
|
||||
);
|
||||
assert!(factory.get_plugin_descriptor.unwrap()(factory, 1).is_null());
|
||||
let host = clap_host {
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "weld-core"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
crossbeam-queue = "0.3"
|
||||
rustfft = "6.4"
|
||||
serde = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
rustfft = "6.4"
|
||||
serde_json = { workspace = true }
|
||||
@@ -0,0 +1,429 @@
|
||||
//! The measuring half of Weld. Runs on the worker thread; deterministic, so tests drive
|
||||
//! it directly.
|
||||
//!
|
||||
//! A Welch estimate of the cross-spectrum S = F_A·conj(F_B) and both auto-spectra runs
|
||||
//! over Hann-windowed frames with 50 % overlap. Both layers share one complex FFT
|
||||
//! (A in the real part, B in the imaginary part).
|
||||
use crate::chain::Fit;
|
||||
use crate::fit::{search, Point, Problem};
|
||||
use crate::report::{band_of, curve_frequency, Report, Status, BANDS};
|
||||
use crate::settings::{Mode, Settings};
|
||||
use rustfft::{num_complex::Complex32, Fft, FftPlanner};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Bins below this coherence do not steer the fit.
|
||||
const MIN_COHERENCE: f32 = 0.3;
|
||||
/// Below this mean coherence the layers count as unrelated.
|
||||
const LOOSE_COHERENCE: f32 = 0.3;
|
||||
/// Frames needed before the first fit.
|
||||
const MIN_FRAMES: u32 = 8;
|
||||
/// A new fit replaces the current one only when it gains this much (Follow mode).
|
||||
const FOLLOW_GAIN_DB: f32 = 0.3;
|
||||
const LEARN_GAIN_DB: f32 = 0.1;
|
||||
/// Lag search range and the smallest lag reported as "late".
|
||||
const LAG_RANGE_S: f32 = 0.005;
|
||||
const LATE_S: f32 = 0.0001;
|
||||
const LATE_STRENGTH: f32 = 0.3;
|
||||
/// Report and fit intervals in seconds of analysed audio.
|
||||
const REPORT_S: f32 = 0.25;
|
||||
const FIT_S: f32 = 0.5;
|
||||
/// −90 dBFS: anything quieter on the sidechain counts as no signal.
|
||||
const SILENCE: f32 = 3.2e-5;
|
||||
|
||||
/// What a poll produced.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Update {
|
||||
/// Set when a new alignment was accepted.
|
||||
pub fit: Option<Fit>,
|
||||
pub report: Report,
|
||||
}
|
||||
|
||||
pub struct Analyzer {
|
||||
rate: f32,
|
||||
n: usize,
|
||||
hop: usize,
|
||||
window: Vec<f32>,
|
||||
ring_a: Vec<f32>,
|
||||
ring_b: Vec<f32>,
|
||||
write: usize,
|
||||
filled: usize,
|
||||
since_frame: usize,
|
||||
fft: Arc<dyn Fft<f32>>,
|
||||
ifft: Arc<dyn Fft<f32>>,
|
||||
buf: Vec<Complex32>,
|
||||
scratch: Vec<Complex32>,
|
||||
sab: Vec<Complex32>,
|
||||
saa: Vec<f32>,
|
||||
sbb: Vec<f32>,
|
||||
frames: u32,
|
||||
settings: Settings,
|
||||
current: Fit,
|
||||
since_report: usize,
|
||||
since_fit: usize,
|
||||
finish_learn: bool,
|
||||
side_level: f32,
|
||||
gated: bool,
|
||||
}
|
||||
|
||||
impl Analyzer {
|
||||
pub fn new(rate: f32, fit: Fit) -> Self {
|
||||
// About 11.7 Hz per bin at any rate.
|
||||
let n = ((4096. * rate / 48000.) as usize)
|
||||
.next_power_of_two()
|
||||
.clamp(1024, 65536);
|
||||
let mut planner = FftPlanner::new();
|
||||
let fft = planner.plan_fft_forward(n);
|
||||
let ifft = planner.plan_fft_inverse(n);
|
||||
let scratch_len = fft
|
||||
.get_inplace_scratch_len()
|
||||
.max(ifft.get_inplace_scratch_len());
|
||||
let window = (0..n)
|
||||
.map(|i| 0.5 - 0.5 * (std::f32::consts::TAU * i as f32 / n as f32).cos())
|
||||
.collect();
|
||||
let bins = n / 2 + 1;
|
||||
Self {
|
||||
rate,
|
||||
n,
|
||||
hop: n / 2,
|
||||
window,
|
||||
ring_a: vec![0.; n],
|
||||
ring_b: vec![0.; n],
|
||||
write: 0,
|
||||
filled: 0,
|
||||
since_frame: 0,
|
||||
fft,
|
||||
ifft,
|
||||
buf: vec![Complex32::default(); n],
|
||||
scratch: vec![Complex32::default(); scratch_len],
|
||||
sab: vec![Complex32::default(); bins],
|
||||
saa: vec![0.; bins],
|
||||
sbb: vec![0.; bins],
|
||||
frames: 0,
|
||||
settings: Settings::default(),
|
||||
current: fit.sanitized(rate),
|
||||
since_report: 0,
|
||||
since_fit: 0,
|
||||
finish_learn: false,
|
||||
side_level: 0.,
|
||||
gated: false,
|
||||
}
|
||||
}
|
||||
pub fn fft_size(&self) -> usize {
|
||||
self.n
|
||||
}
|
||||
pub fn current(&self) -> &Fit {
|
||||
&self.current
|
||||
}
|
||||
pub fn frames(&self) -> u32 {
|
||||
self.frames
|
||||
}
|
||||
pub fn set_settings(&mut self, settings: Settings) {
|
||||
let old = self.settings.mode;
|
||||
if settings.mode == Mode::Learn && old != Mode::Learn {
|
||||
self.clear();
|
||||
}
|
||||
if old == Mode::Learn && settings.mode != Mode::Learn {
|
||||
self.finish_learn = true;
|
||||
}
|
||||
self.settings = settings;
|
||||
}
|
||||
/// Forgets the measurement.
|
||||
pub fn clear(&mut self) {
|
||||
self.sab.fill(Complex32::default());
|
||||
self.saa.fill(0.);
|
||||
self.sbb.fill(0.);
|
||||
self.frames = 0;
|
||||
}
|
||||
/// Feeds mono samples of the main layer `a` and the sidechain layer `b`.
|
||||
pub fn push(&mut self, a: &[f32], b: &[f32]) {
|
||||
for (&x, &y) in a.iter().zip(b) {
|
||||
self.ring_a[self.write] = x;
|
||||
self.ring_b[self.write] = y;
|
||||
self.write = (self.write + 1) % self.n;
|
||||
self.filled = (self.filled + 1).min(self.n);
|
||||
self.since_frame += 1;
|
||||
if self.filled == self.n && self.since_frame >= self.hop {
|
||||
self.since_frame = 0;
|
||||
self.frame();
|
||||
}
|
||||
}
|
||||
self.since_report += a.len().min(b.len());
|
||||
self.since_fit += a.len().min(b.len());
|
||||
}
|
||||
fn frame(&mut self) {
|
||||
let n = self.n;
|
||||
let (mut ea, mut eb) = (0f32, 0f32);
|
||||
for i in 0..n {
|
||||
let j = (self.write + i) % n;
|
||||
let (a, b) = (self.ring_a[j], self.ring_b[j]);
|
||||
ea += a * a;
|
||||
eb += b * b;
|
||||
self.buf[i] = Complex32::new(a * self.window[i], b * self.window[i]);
|
||||
}
|
||||
let (ra, rb) = ((ea / n as f32).sqrt(), (eb / n as f32).sqrt());
|
||||
self.side_level = rb;
|
||||
let gate = 10f32.powf(self.settings.gate / 20.);
|
||||
self.gated = ra < gate || rb < gate;
|
||||
if self.gated {
|
||||
return;
|
||||
}
|
||||
self.fft
|
||||
.process_with_scratch(&mut self.buf, &mut self.scratch);
|
||||
self.frames = self.frames.saturating_add(1);
|
||||
let count = 1. / self.frames as f32;
|
||||
let alpha = match self.settings.mode {
|
||||
Mode::Learn => count,
|
||||
_ => {
|
||||
let follow = 1. - (-(self.hop as f32) / (self.settings.response * self.rate)).exp();
|
||||
count.max(follow)
|
||||
}
|
||||
};
|
||||
for k in 0..=n / 2 {
|
||||
let x = self.buf[k];
|
||||
let xc = self.buf[(n - k) % n].conj();
|
||||
let fa = (x + xc) * 0.5;
|
||||
let fb = (x - xc) * Complex32::new(0., -0.5);
|
||||
let old = self.sab[k];
|
||||
self.sab[k] = old + (fa * fb.conj() - old) * alpha;
|
||||
self.saa[k] += (fa.norm_sqr() - self.saa[k]) * alpha;
|
||||
self.sbb[k] += (fb.norm_sqr() - self.sbb[k]) * alpha;
|
||||
}
|
||||
}
|
||||
fn frequency(&self, k: usize) -> f32 {
|
||||
k as f32 * self.rate / self.n as f32
|
||||
}
|
||||
fn coherence(&self, k: usize) -> f32 {
|
||||
let d = self.saa[k] * self.sbb[k];
|
||||
if d > 0. {
|
||||
(self.sab[k].norm_sqr() / d).min(1.)
|
||||
} else {
|
||||
0.
|
||||
}
|
||||
}
|
||||
fn range(&self) -> (f32, f32) {
|
||||
let high = self.settings.high.min(0.45 * self.rate);
|
||||
(self.settings.low.min(high * 0.5), high)
|
||||
}
|
||||
/// Fit points between Low and High: one per bin at the bottom, merged to 1/32 octave
|
||||
/// higher up.
|
||||
fn points(&self) -> Vec<Point> {
|
||||
let (low, high) = self.range();
|
||||
let mut points: Vec<Point> = Vec::new();
|
||||
let mut last = usize::MAX;
|
||||
for k in 1..=self.n / 2 {
|
||||
let f = self.frequency(k);
|
||||
if f < low || f > high {
|
||||
continue;
|
||||
}
|
||||
let slot = (32. * (f / low).log2()) as usize;
|
||||
if slot != last {
|
||||
points.push(Point::new(f, self.rate));
|
||||
last = slot;
|
||||
}
|
||||
let p = points.last_mut().expect("pushed above");
|
||||
if self.coherence(k) >= MIN_COHERENCE {
|
||||
p.fit += self.sab[k];
|
||||
}
|
||||
p.all += self.sab[k];
|
||||
p.power += self.saa[k] + self.sbb[k];
|
||||
}
|
||||
points
|
||||
}
|
||||
/// Produces an update once enough audio has been analysed since the last one.
|
||||
pub fn poll(&mut self) -> Option<Update> {
|
||||
let report_due = self.since_report as f32 >= REPORT_S * self.rate;
|
||||
if !report_due && !self.finish_learn {
|
||||
return None;
|
||||
}
|
||||
self.since_report = 0;
|
||||
let fit_due = self.since_fit as f32 >= FIT_S * self.rate;
|
||||
let mode = self.settings.mode;
|
||||
let threshold = if self.finish_learn {
|
||||
Some(LEARN_GAIN_DB)
|
||||
} else if fit_due && mode == Mode::Follow {
|
||||
Some(FOLLOW_GAIN_DB)
|
||||
} else if fit_due && mode == Mode::Learn {
|
||||
Some(LEARN_GAIN_DB)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if fit_due {
|
||||
self.since_fit = 0;
|
||||
}
|
||||
self.finish_learn = false;
|
||||
Some(self.analyse(threshold))
|
||||
}
|
||||
/// Measures, fits when `threshold` is given (minimum predicted gain in dB over the
|
||||
/// current fit), and reports.
|
||||
pub fn analyse(&mut self, threshold: Option<f32>) -> Update {
|
||||
let points = self.points();
|
||||
let problem = Problem::new(points, self.rate);
|
||||
let (weight, coherent) = problem.points.iter().fold((0., 0.), |(w, c), p| {
|
||||
let x = p.all.norm();
|
||||
(w + p.w * x, c + p.w * x * coherence_of(p))
|
||||
});
|
||||
let mean_coherence = if weight > 0. { coherent / weight } else { 0. };
|
||||
let (lag_ms, lag_strength) = self.lag();
|
||||
let late = lag_ms > LATE_S * 1000. && lag_strength > LATE_STRENGTH;
|
||||
let status = if self.side_level < SILENCE && self.frames == 0 {
|
||||
Status::NoSidechain
|
||||
} else if self.frames < MIN_FRAMES {
|
||||
if self.gated {
|
||||
Status::Quiet
|
||||
} else {
|
||||
Status::Waiting
|
||||
}
|
||||
} else if mean_coherence < LOOSE_COHERENCE || problem.is_empty() {
|
||||
Status::Loose
|
||||
} else if late {
|
||||
Status::Late
|
||||
} else {
|
||||
Status::Aligned
|
||||
};
|
||||
let mut changed = None;
|
||||
if let Some(threshold) = threshold {
|
||||
if matches!(status, Status::Aligned | Status::Late) {
|
||||
let candidate = search(&problem, self.settings.sections, &self.current);
|
||||
let gain = problem.mean_gain(
|
||||
&problem.bands(&self.current),
|
||||
&problem.bands(&candidate.fit),
|
||||
);
|
||||
if gain.is_finite() && gain >= threshold && candidate.fit != self.current {
|
||||
self.current = candidate.fit;
|
||||
changed = Some(candidate.fit);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut report = self.report(status, &problem);
|
||||
report.lag_ms = lag_ms;
|
||||
report.lag_strength = lag_strength;
|
||||
report.changed = changed.is_some();
|
||||
Update {
|
||||
fit: changed,
|
||||
report,
|
||||
}
|
||||
}
|
||||
fn report(&self, status: Status, problem: &Problem) -> Report {
|
||||
let fit = self.current;
|
||||
let mut report = Report {
|
||||
status,
|
||||
fit,
|
||||
frames: self.frames,
|
||||
low: self.range().0,
|
||||
high: self.range().1,
|
||||
..Report::default()
|
||||
};
|
||||
// Display bands over all bins.
|
||||
// Sums per band: before, after, ideal, coherence·power, power.
|
||||
let mut sums = [[0f32; 5]; BANDS];
|
||||
for k in 1..=self.n / 2 {
|
||||
let f = self.frequency(k);
|
||||
if !(20. ..=0.45 * self.rate).contains(&f) {
|
||||
continue;
|
||||
}
|
||||
let (hr, hi) = fit.response(f, self.rate);
|
||||
let s = self.sab[k];
|
||||
let p = self.saa[k] + self.sbb[k];
|
||||
let b = &mut sums[band_of(f)];
|
||||
b[0] += p + 2. * s.re;
|
||||
b[1] += p + 2. * (s * Complex32::new(hr, hi)).re;
|
||||
b[2] += p + 2. * s.norm();
|
||||
b[3] += self.coherence(k) * p;
|
||||
b[4] += p;
|
||||
}
|
||||
for (band, [before, after, ideal, coherent, power]) in report.bands.iter_mut().zip(sums) {
|
||||
if ideal > 1e-12 && power > 0. {
|
||||
band.before = db_ratio(before, ideal);
|
||||
band.after = db_ratio(after, ideal);
|
||||
band.coherence = (coherent / power).clamp(0., 1.);
|
||||
band.valid = true;
|
||||
}
|
||||
}
|
||||
// Phase curve: bins within ±1/24 octave of each point.
|
||||
for (i, point) in report.curve.iter_mut().enumerate() {
|
||||
let f = curve_frequency(i);
|
||||
if f > 0.45 * self.rate {
|
||||
continue;
|
||||
}
|
||||
let lo = ((f * 2f32.powf(-1. / 24.)) * self.n as f32 / self.rate).floor() as usize;
|
||||
let hi = ((f * 2f32.powf(1. / 24.)) * self.n as f32 / self.rate).ceil() as usize;
|
||||
let centre = (f * self.n as f32 / self.rate).round() as usize;
|
||||
let (lo, hi) = (
|
||||
lo.max(1).min(centre.max(1)),
|
||||
hi.min(self.n / 2).max(centre.max(1)),
|
||||
);
|
||||
let (mut s, mut pa, mut pb) = (Complex32::default(), 0f32, 0f32);
|
||||
for k in lo..=hi {
|
||||
s += self.sab[k];
|
||||
pa += self.saa[k];
|
||||
pb += self.sbb[k];
|
||||
}
|
||||
if pa * pb <= 0. {
|
||||
continue;
|
||||
}
|
||||
let (hr, hi) = fit.response(f, self.rate);
|
||||
let h = Complex32::new(hr, hi);
|
||||
point.before = s.arg().to_degrees();
|
||||
point.after = (s * h).arg().to_degrees();
|
||||
point.chain = h.arg().to_degrees();
|
||||
point.coherence = (s.norm_sqr() / (pa * pb)).min(1.);
|
||||
point.valid = true;
|
||||
}
|
||||
// Headline numbers over the fit range, every band weighted the same.
|
||||
if !problem.is_empty() {
|
||||
let before = problem.before_bands();
|
||||
report.cost_db = problem.mean_gain(&before, &problem.ideal_bands());
|
||||
report.recovered_db = problem.mean_gain(&before, &problem.bands(&fit));
|
||||
}
|
||||
report
|
||||
}
|
||||
/// Time offset from the phase transform of the cross-spectrum (GCC-PHAT) between
|
||||
/// Low and High. Returns (ms, strength); positive means this layer is late.
|
||||
fn lag(&mut self) -> (f32, f32) {
|
||||
let n = self.n;
|
||||
let (low, high) = self.range();
|
||||
self.buf.fill(Complex32::default());
|
||||
let mut used = 0usize;
|
||||
for k in 1..n / 2 {
|
||||
let f = self.frequency(k);
|
||||
if f < low || f > high || self.coherence(k) < MIN_COHERENCE {
|
||||
continue;
|
||||
}
|
||||
let s = self.sab[k];
|
||||
let m = s.norm();
|
||||
if m <= 0. {
|
||||
continue;
|
||||
}
|
||||
let u = s / m;
|
||||
self.buf[k] = u;
|
||||
self.buf[n - k] = u.conj();
|
||||
used += 1;
|
||||
}
|
||||
if used < 4 {
|
||||
return (0., 0.);
|
||||
}
|
||||
self.ifft
|
||||
.process_with_scratch(&mut self.buf, &mut self.scratch);
|
||||
let range = (LAG_RANGE_S * self.rate) as isize;
|
||||
let (mut best, mut at) = (0f32, 0isize);
|
||||
for tau in -range..=range {
|
||||
let v = self.buf[tau.rem_euclid(n as isize) as usize].re.abs();
|
||||
if v > best {
|
||||
best = v;
|
||||
at = tau;
|
||||
}
|
||||
}
|
||||
(at as f32 / self.rate * 1000., best / (2 * used) as f32)
|
||||
}
|
||||
}
|
||||
|
||||
fn coherence_of(p: &Point) -> f32 {
|
||||
if p.all.norm() > 0. {
|
||||
p.fit.norm() / p.all.norm()
|
||||
} else {
|
||||
0.
|
||||
}
|
||||
}
|
||||
fn db_ratio(a: f32, b: f32) -> f32 {
|
||||
(10. * (a.max(1e-20) / b.max(1e-20)).log10()).clamp(-40., 40.)
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
//! Polarity plus a cascade of second-order allpass sections. Magnitude is flat by
|
||||
//! construction; only the phase of the main layer changes.
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const MAX_SECTIONS: usize = 4;
|
||||
pub const MIN_FC: f32 = 30.;
|
||||
pub const MIN_Q: f32 = 0.2;
|
||||
pub const MAX_Q: f32 = 4.;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Section {
|
||||
/// Centre frequency in Hz, where the section's phase passes −180°.
|
||||
pub fc: f32,
|
||||
pub q: f32,
|
||||
}
|
||||
impl Default for Section {
|
||||
fn default() -> Self {
|
||||
Self { fc: 1000., q: 0.7 }
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of a fit: what Weld applies to the main layer.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
|
||||
pub struct Fit {
|
||||
/// Invert the main layer.
|
||||
pub flip: bool,
|
||||
/// Number of active sections, 0..=MAX_SECTIONS.
|
||||
pub count: usize,
|
||||
pub sections: [Section; MAX_SECTIONS],
|
||||
}
|
||||
impl Fit {
|
||||
/// The identity: no polarity change, no sections.
|
||||
pub const NONE: Fit = Fit {
|
||||
flip: false,
|
||||
count: 0,
|
||||
sections: [Section { fc: 1000., q: 0.7 }; MAX_SECTIONS],
|
||||
};
|
||||
pub fn active(&self) -> &[Section] {
|
||||
&self.sections[..self.count.min(MAX_SECTIONS)]
|
||||
}
|
||||
/// Clamps every value into the range the filter supports; repairs restored state.
|
||||
pub fn sanitized(mut self, rate: f32) -> Self {
|
||||
self.count = self.count.min(MAX_SECTIONS);
|
||||
let top = max_fc(rate);
|
||||
for s in &mut self.sections {
|
||||
s.fc = if s.fc.is_finite() {
|
||||
s.fc.clamp(MIN_FC, top)
|
||||
} else {
|
||||
1000f32.min(top)
|
||||
};
|
||||
s.q = if s.q.is_finite() {
|
||||
s.q.clamp(MIN_Q, MAX_Q)
|
||||
} else {
|
||||
0.7
|
||||
};
|
||||
}
|
||||
self
|
||||
}
|
||||
/// Complex response at `f` Hz as (re, im).
|
||||
pub fn response(&self, f: f32, rate: f32) -> (f32, f32) {
|
||||
let w = std::f32::consts::TAU * f / rate;
|
||||
let (mut re, mut im) = (if self.flip { -1. } else { 1. }, 0.);
|
||||
for s in self.active() {
|
||||
let c = Coefs::allpass(s.fc, s.q, rate);
|
||||
let (hr, hi) = c.response(w.cos(), w.sin(), (2. * w).cos(), (2. * w).sin());
|
||||
(re, im) = (re * hr - im * hi, re * hi + im * hr);
|
||||
}
|
||||
(re, im)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn max_fc(rate: f32) -> f32 {
|
||||
0.45 * rate
|
||||
}
|
||||
|
||||
/// Normalised allpass coefficients: H(z) = (a2 + a1 z⁻¹ + z⁻²) / (1 + a1 z⁻¹ + a2 z⁻²).
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Coefs {
|
||||
pub a1: f32,
|
||||
pub a2: f32,
|
||||
}
|
||||
impl Coefs {
|
||||
/// RBJ cookbook allpass.
|
||||
pub fn allpass(fc: f32, q: f32, rate: f32) -> Self {
|
||||
let fc = fc.clamp(MIN_FC, max_fc(rate));
|
||||
let q = q.clamp(MIN_Q, MAX_Q);
|
||||
let w = std::f32::consts::TAU * fc / rate;
|
||||
let alpha = w.sin() / (2. * q);
|
||||
let a0 = 1. + alpha;
|
||||
Self {
|
||||
a1: -2. * w.cos() / a0,
|
||||
a2: (1. - alpha) / a0,
|
||||
}
|
||||
}
|
||||
/// Response at z⁻¹ = e^{−jω}, given cos/sin of ω and 2ω.
|
||||
/// For an allpass the numerator is z⁻²·conj(den), so H = z⁻²·conj(den)/den.
|
||||
#[inline]
|
||||
pub fn response(&self, c1: f32, s1: f32, c2: f32, s2: f32) -> (f32, f32) {
|
||||
let x = 1. + self.a1 * c1 + self.a2 * c2;
|
||||
let y = -(self.a1 * s1 + self.a2 * s2);
|
||||
let m = x * x + y * y;
|
||||
// conj(den)/den = conj(den)² / |den|²
|
||||
let (qr, qi) = ((x * x - y * y) / m, -2. * x * y / m);
|
||||
// times z⁻² = c2 − j s2
|
||||
(qr * c2 + qi * s2, qi * c2 - qr * s2)
|
||||
}
|
||||
}
|
||||
|
||||
/// Transposed direct form II state, in f64 so sections near 30 Hz stay quiet.
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
struct State {
|
||||
s1: f64,
|
||||
s2: f64,
|
||||
}
|
||||
|
||||
/// A running chain for up to two channels. Allocation-free.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Chain {
|
||||
fit: Fit,
|
||||
sign: f32,
|
||||
coefs: [(f64, f64); MAX_SECTIONS],
|
||||
state: [[State; MAX_SECTIONS]; 2],
|
||||
}
|
||||
impl Chain {
|
||||
pub fn new(fit: Fit, rate: f32) -> Self {
|
||||
let mut chain = Self {
|
||||
fit: Fit::NONE,
|
||||
sign: 1.,
|
||||
coefs: [(0., 0.); MAX_SECTIONS],
|
||||
state: [[State::default(); MAX_SECTIONS]; 2],
|
||||
};
|
||||
chain.set(fit, rate);
|
||||
chain
|
||||
}
|
||||
pub fn fit(&self) -> &Fit {
|
||||
&self.fit
|
||||
}
|
||||
/// Replaces the coefficients and clears the state.
|
||||
pub fn set(&mut self, fit: Fit, rate: f32) {
|
||||
self.fit = fit.sanitized(rate);
|
||||
self.sign = if self.fit.flip { -1. } else { 1. };
|
||||
for (c, s) in self.coefs.iter_mut().zip(self.fit.active()) {
|
||||
let k = Coefs::allpass(s.fc, s.q, rate);
|
||||
*c = (k.a1 as f64, k.a2 as f64);
|
||||
}
|
||||
self.reset();
|
||||
}
|
||||
pub fn reset(&mut self) {
|
||||
self.state = [[State::default(); MAX_SECTIONS]; 2];
|
||||
}
|
||||
#[inline]
|
||||
pub fn process(&mut self, channel: usize, x: f32) -> f32 {
|
||||
let mut y = (self.sign * x) as f64;
|
||||
for (k, &(a1, a2)) in self.coefs[..self.fit.count].iter().enumerate() {
|
||||
let st = &mut self.state[channel][k];
|
||||
let out = a2 * y + st.s1;
|
||||
st.s1 = a1 * y - a1 * out + st.s2;
|
||||
st.s2 = y - a2 * out;
|
||||
y = out;
|
||||
}
|
||||
y as f32
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
//! Fits polarity plus allpass sections to a measured cross-spectrum.
|
||||
//!
|
||||
//! With S = F_A·conj(F_B), the power of the sum after rotating A by H is
|
||||
//! |A|² + |B|² + 2·Re(S·H). The fit maximises Σ w(f)·Re(S·H) with w = 1/f, so every
|
||||
//! octave counts the same. Flipping polarity negates the sum, so the best polarity is
|
||||
//! the sign of the result and only the sections need searching.
|
||||
use crate::chain::{max_fc, Coefs, Fit, Section, MAX_Q, MAX_SECTIONS, MIN_FC, MIN_Q};
|
||||
use crate::report::{band_of, BANDS, DISPLAY_HIGH, DISPLAY_LOW};
|
||||
|
||||
/// Bands for the loss penalty. Narrower bands make the penalty brittle next to the
|
||||
/// notches of a comb, which a delay between the layers always has.
|
||||
const FINE: usize = 10;
|
||||
fn fine_of(f: f32) -> usize {
|
||||
let t = (f / DISPLAY_LOW).ln() / (DISPLAY_HIGH / DISPLAY_LOW).ln();
|
||||
((t * FINE as f32).max(0.) as usize).min(FINE - 1)
|
||||
}
|
||||
use rustfft::num_complex::Complex32;
|
||||
|
||||
/// One fit point: bins merged over at most 1/32 octave.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct Point {
|
||||
pub c1: f32,
|
||||
pub s1: f32,
|
||||
pub c2: f32,
|
||||
pub s2: f32,
|
||||
/// 1/f weight.
|
||||
pub w: f32,
|
||||
/// Cross-spectrum of the coherent bins only; drives the objective.
|
||||
pub fit: Complex32,
|
||||
/// Cross-spectrum and summed auto-spectra of all bins; drive the predicted levels.
|
||||
pub all: Complex32,
|
||||
pub power: f32,
|
||||
pub band: usize,
|
||||
pub fine: usize,
|
||||
}
|
||||
impl Point {
|
||||
pub fn new(f: f32, rate: f32) -> Self {
|
||||
let w = std::f32::consts::TAU * f / rate;
|
||||
Self {
|
||||
c1: w.cos(),
|
||||
s1: w.sin(),
|
||||
c2: (2. * w).cos(),
|
||||
s2: (2. * w).sin(),
|
||||
w: 1. / f,
|
||||
fit: Complex32::default(),
|
||||
all: Complex32::default(),
|
||||
power: 0.,
|
||||
band: band_of(f),
|
||||
fine: fine_of(f),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Problem {
|
||||
pub points: Vec<Point>,
|
||||
pub rate: f32,
|
||||
/// Σ w·|S| over the coherent bins: the objective of a perfect per-bin alignment.
|
||||
norm: f32,
|
||||
/// Per-band level of the unprocessed sum.
|
||||
before: [f32; BANDS],
|
||||
/// The same in third-octave bands, for the loss penalty.
|
||||
before_fine: [f32; FINE],
|
||||
}
|
||||
|
||||
/// Score of a perfectly aligned sum is 1. Losing more than 1 dB in any band against the
|
||||
/// unprocessed sum costs extra, so a fit cannot win the mids by giving away the top.
|
||||
const LOSS_FREE_DB: f32 = 1.0;
|
||||
const LOSS_WEIGHT: f32 = 0.05;
|
||||
/// The smallest model that reaches this share of the best model's improvement wins.
|
||||
const MODEL_SHARE: f32 = 0.95;
|
||||
/// Improvements below this score never justify another section.
|
||||
const MODEL_FLOOR: f32 = 0.001;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Candidate {
|
||||
pub fit: Fit,
|
||||
pub score: f32,
|
||||
}
|
||||
|
||||
impl Problem {
|
||||
pub fn new(points: Vec<Point>, rate: f32) -> Self {
|
||||
let norm = points.iter().map(|p| p.w * p.fit.norm()).sum::<f32>();
|
||||
let mut before = [0f32; BANDS];
|
||||
let mut before_fine = [0f32; FINE];
|
||||
for p in &points {
|
||||
before[p.band] += p.power + 2. * p.all.re;
|
||||
before_fine[p.fine] += p.power + 2. * p.all.re;
|
||||
}
|
||||
Self {
|
||||
points,
|
||||
rate,
|
||||
norm,
|
||||
before,
|
||||
before_fine,
|
||||
}
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.norm <= 0.
|
||||
}
|
||||
fn coefs(&self, x: &[f32], out: &mut [Coefs; MAX_SECTIONS]) -> (usize, f32) {
|
||||
let k = x.len() / 2;
|
||||
let mut outside = 0.;
|
||||
let (lo_f, hi_f) = (MIN_FC.ln(), max_fc(self.rate).ln());
|
||||
let (lo_q, hi_q) = (MIN_Q.ln(), MAX_Q.ln());
|
||||
for i in 0..k {
|
||||
let (f, q) = (x[2 * i], x[2 * i + 1]);
|
||||
outside +=
|
||||
(lo_f - f).max(0.) + (f - hi_f).max(0.) + (lo_q - q).max(0.) + (q - hi_q).max(0.);
|
||||
out[i] = Coefs::allpass(
|
||||
f.clamp(lo_f, hi_f).exp(),
|
||||
q.clamp(lo_q, hi_q).exp(),
|
||||
self.rate,
|
||||
);
|
||||
}
|
||||
(k, outside)
|
||||
}
|
||||
#[inline]
|
||||
fn response(p: &Point, coefs: &[Coefs]) -> Complex32 {
|
||||
let mut h = Complex32::new(1., 0.);
|
||||
for c in coefs {
|
||||
let (re, im) = c.response(p.c1, p.s1, p.c2, p.s2);
|
||||
h *= Complex32::new(re, im);
|
||||
}
|
||||
h
|
||||
}
|
||||
/// Score and polarity for sections given as [ln fc, ln q, …].
|
||||
fn score(&self, x: &[f32]) -> (f32, bool) {
|
||||
let mut coefs = [Coefs { a1: 0., a2: 0. }; MAX_SECTIONS];
|
||||
let (k, outside) = self.coefs(x, &mut coefs);
|
||||
let coefs = &coefs[..k];
|
||||
let mut j = 0f32;
|
||||
let mut cross = [0f32; FINE];
|
||||
let mut power = [0f32; FINE];
|
||||
for p in &self.points {
|
||||
let h = Self::response(p, coefs);
|
||||
j += p.w * (p.fit * h).re;
|
||||
cross[p.fine] += (p.all * h).re;
|
||||
power[p.fine] += p.power;
|
||||
}
|
||||
let flip = j < 0.;
|
||||
let sign = if flip { -1. } else { 1. };
|
||||
let mut penalty = outside * outside;
|
||||
for b in 0..FINE {
|
||||
let before = self.before_fine[b];
|
||||
if before <= 0. {
|
||||
continue;
|
||||
}
|
||||
let after = (power[b] + 2. * sign * cross[b]).max(before * 1e-6);
|
||||
let loss = 10. * (before / after).log10();
|
||||
if loss > LOSS_FREE_DB {
|
||||
penalty += LOSS_WEIGHT * (loss - LOSS_FREE_DB).powi(2);
|
||||
}
|
||||
}
|
||||
(j.abs() / self.norm - penalty, flip)
|
||||
}
|
||||
fn candidate(&self, x: &[f32]) -> Candidate {
|
||||
let (score, flip) = self.score(x);
|
||||
let mut fit = Fit {
|
||||
flip,
|
||||
count: x.len() / 2,
|
||||
..Fit::NONE
|
||||
};
|
||||
for (i, s) in fit.sections[..fit.count].iter_mut().enumerate() {
|
||||
*s = Section {
|
||||
fc: x[2 * i].exp().clamp(MIN_FC, max_fc(self.rate)),
|
||||
q: x[2 * i + 1].exp().clamp(MIN_Q, MAX_Q),
|
||||
};
|
||||
}
|
||||
Candidate { fit, score }
|
||||
}
|
||||
/// Level of the sum per display band with `fit` applied (sign included).
|
||||
pub fn bands(&self, fit: &Fit) -> [f32; BANDS] {
|
||||
let mut coefs = [Coefs { a1: 0., a2: 0. }; MAX_SECTIONS];
|
||||
for (c, s) in coefs.iter_mut().zip(fit.active()) {
|
||||
*c = Coefs::allpass(s.fc, s.q, self.rate);
|
||||
}
|
||||
let coefs = &coefs[..fit.active().len()];
|
||||
let sign = if fit.flip { -1. } else { 1. };
|
||||
let mut out = [0f32; BANDS];
|
||||
for p in &self.points {
|
||||
out[p.band] += p.power + 2. * sign * (p.all * Self::response(p, coefs)).re;
|
||||
}
|
||||
out
|
||||
}
|
||||
/// Level per display band of a perfectly aligned sum.
|
||||
pub fn ideal_bands(&self) -> [f32; BANDS] {
|
||||
let mut out = [0f32; BANDS];
|
||||
for p in &self.points {
|
||||
out[p.band] += p.power + 2. * p.all.norm();
|
||||
}
|
||||
out
|
||||
}
|
||||
/// Mean change in dB over the bands that carry signal, from `from` to `to`. Every
|
||||
/// band counts the same, so a hollow octave in the mids weighs as much as the sub.
|
||||
pub fn mean_gain(&self, from: &[f32; BANDS], to: &[f32; BANDS]) -> f32 {
|
||||
let total: f32 = self.before.iter().sum();
|
||||
let (mut sum, mut count) = (0f32, 0);
|
||||
for b in 0..BANDS {
|
||||
if self.before[b] > total * 1e-4 && from[b] > 0. {
|
||||
sum += 10. * (to[b].max(from[b] * 1e-6) / from[b]).log10();
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
if count > 0 {
|
||||
sum / count as f32
|
||||
} else {
|
||||
0.
|
||||
}
|
||||
}
|
||||
pub fn before_bands(&self) -> [f32; BANDS] {
|
||||
self.before
|
||||
}
|
||||
/// The frequency where the current sections leave the most cross-energy unaligned,
|
||||
/// smoothed over one third of an octave.
|
||||
fn worst_frequency(&self, x: &[f32]) -> f32 {
|
||||
let mut coefs = [Coefs { a1: 0., a2: 0. }; MAX_SECTIONS];
|
||||
let (k, _) = self.coefs(x, &mut coefs);
|
||||
let (_, flip) = self.score(x);
|
||||
let sign = if flip { -1. } else { 1. };
|
||||
let mut buckets = [0f32; 48];
|
||||
let mut first = None;
|
||||
for p in &self.points {
|
||||
let h = Self::response(p, &coefs[..k]);
|
||||
let residual = p.w * (p.fit.norm() - sign * (p.fit * h).re);
|
||||
let f = 1. / p.w;
|
||||
let low = *first.get_or_insert(f);
|
||||
let i = ((3. * (f / low).log2()) as usize).min(47);
|
||||
buckets[i] += residual;
|
||||
}
|
||||
let low = first.unwrap_or(100.);
|
||||
let best = (0..48)
|
||||
.max_by(|&a, &b| buckets[a].total_cmp(&buckets[b]))
|
||||
.unwrap_or(0);
|
||||
low * 2f32.powf((best as f32 + 0.5) / 3.)
|
||||
}
|
||||
}
|
||||
|
||||
/// Searches 0..=`max_sections` sections, warm-started from `warm`. Deterministic.
|
||||
pub(crate) fn search(problem: &Problem, max_sections: usize, warm: &Fit) -> Candidate {
|
||||
let max_sections = max_sections.min(MAX_SECTIONS);
|
||||
let mut best: Vec<Candidate> = Vec::with_capacity(max_sections + 1);
|
||||
best.push(problem.candidate(&[]));
|
||||
let mut previous: Vec<f32> = Vec::new();
|
||||
for k in 1..=max_sections {
|
||||
let mut seeds: Vec<Vec<f32>> = Vec::new();
|
||||
let worst = problem.worst_frequency(&previous);
|
||||
for f in [worst, worst * 0.4, worst * 2.5] {
|
||||
let mut x = previous.clone();
|
||||
x.extend([f.ln(), 0.7f32.ln()]);
|
||||
seeds.push(x);
|
||||
}
|
||||
if k == 1 {
|
||||
// Low-Q sections high up act like a short delay below their centre.
|
||||
for (f, q) in [
|
||||
(120f32, 0.7f32),
|
||||
(400., 0.7),
|
||||
(1500., 0.7),
|
||||
(3000., 0.5),
|
||||
(6000., 0.5),
|
||||
] {
|
||||
seeds.push(vec![f.ln(), q.ln()]);
|
||||
}
|
||||
}
|
||||
if warm.count == k {
|
||||
seeds.push(
|
||||
warm.active()
|
||||
.iter()
|
||||
.flat_map(|s| [s.fc.ln(), s.q.ln()])
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
let mut top: Option<(Vec<f32>, f32)> = None;
|
||||
for seed in seeds {
|
||||
let (x, value) = nelder_mead(|x| -problem.score(x).0, &seed, 0.35, 120 * k * 2);
|
||||
if top.as_ref().is_none_or(|(_, v)| value < *v) {
|
||||
top = Some((x, value));
|
||||
}
|
||||
}
|
||||
let (x, _) = top.expect("at least one seed");
|
||||
let candidate = problem.candidate(&x);
|
||||
let top = best.iter().map(|c| c.score).fold(f32::MIN, f32::max);
|
||||
let gained = candidate.score - top;
|
||||
let slack = MODEL_FLOOR.max((1. - MODEL_SHARE) * (top - best[0].score));
|
||||
best.push(candidate);
|
||||
previous = x;
|
||||
// A section that adds next to nothing is not worth it; more of them rarely are.
|
||||
if k >= 2 && gained < slack {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let top = best.iter().map(|c| c.score).fold(f32::MIN, f32::max);
|
||||
let slack = MODEL_FLOOR.max((1. - MODEL_SHARE) * (top - best[0].score));
|
||||
*best
|
||||
.iter()
|
||||
.find(|c| c.score >= top - slack)
|
||||
.expect("the best model qualifies")
|
||||
}
|
||||
|
||||
/// Downhill simplex. Returns the best point and its value.
|
||||
fn nelder_mead(
|
||||
mut f: impl FnMut(&[f32]) -> f32,
|
||||
x0: &[f32],
|
||||
step: f32,
|
||||
max_evals: usize,
|
||||
) -> (Vec<f32>, f32) {
|
||||
let n = x0.len();
|
||||
let mut simplex: Vec<(Vec<f32>, f32)> = Vec::with_capacity(n + 1);
|
||||
simplex.push((x0.to_vec(), f(x0)));
|
||||
for i in 0..n {
|
||||
let mut x = x0.to_vec();
|
||||
x[i] += step;
|
||||
let v = f(&x);
|
||||
simplex.push((x, v));
|
||||
}
|
||||
let mut evals = n + 1;
|
||||
let point = |a: &[f32], b: &[f32], t: f32| -> Vec<f32> {
|
||||
a.iter().zip(b).map(|(a, b)| a + t * (b - a)).collect()
|
||||
};
|
||||
while evals < max_evals {
|
||||
simplex.sort_by(|a, b| a.1.total_cmp(&b.1));
|
||||
let spread = simplex[n].1 - simplex[0].1;
|
||||
let size = simplex[1..]
|
||||
.iter()
|
||||
.flat_map(|(x, _)| x.iter().zip(&simplex[0].0).map(|(a, b)| (a - b).abs()))
|
||||
.fold(0f32, f32::max);
|
||||
if spread < 1e-7 && size < 1e-3 {
|
||||
break;
|
||||
}
|
||||
let mut centroid = vec![0f32; n];
|
||||
for (x, _) in &simplex[..n] {
|
||||
for (c, v) in centroid.iter_mut().zip(x) {
|
||||
*c += v / n as f32;
|
||||
}
|
||||
}
|
||||
let worst = simplex[n].clone();
|
||||
let reflected = point(¢roid, &worst.0, -1.);
|
||||
let fr = f(&reflected);
|
||||
evals += 1;
|
||||
if fr < simplex[0].1 {
|
||||
let expanded = point(¢roid, &worst.0, -2.);
|
||||
let fe = f(&expanded);
|
||||
evals += 1;
|
||||
simplex[n] = if fe < fr {
|
||||
(expanded, fe)
|
||||
} else {
|
||||
(reflected, fr)
|
||||
};
|
||||
} else if fr < simplex[n - 1].1 {
|
||||
simplex[n] = (reflected, fr);
|
||||
} else {
|
||||
let contracted = if fr < worst.1 {
|
||||
point(¢roid, &reflected, 0.5)
|
||||
} else {
|
||||
point(¢roid, &worst.0, 0.5)
|
||||
};
|
||||
let fc = f(&contracted);
|
||||
evals += 1;
|
||||
if fc < worst.1.min(fr) {
|
||||
simplex[n] = (contracted, fc);
|
||||
} else {
|
||||
let best = simplex[0].0.clone();
|
||||
for (x, v) in &mut simplex[1..] {
|
||||
*x = point(&best, x, 0.5);
|
||||
*v = f(x);
|
||||
}
|
||||
evals += n;
|
||||
}
|
||||
}
|
||||
}
|
||||
simplex.sort_by(|a, b| a.1.total_cmp(&b.1));
|
||||
simplex.swap_remove(0)
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
//! Weld engine: aligns the phase of the main layer to a sidechain layer so the two sum
|
||||
//! instead of cancelling. The audio thread runs polarity plus an allpass chain and hands
|
||||
//! mono blocks to a worker thread, which measures the cross-spectrum and fits the chain.
|
||||
//! Allocation-free on the audio thread after `new`; zero latency.
|
||||
mod analyzer;
|
||||
mod chain;
|
||||
mod fit;
|
||||
mod report;
|
||||
mod settings;
|
||||
mod worker;
|
||||
pub use analyzer::{Analyzer, Update};
|
||||
pub use chain::{Chain, Fit, Section, MAX_SECTIONS};
|
||||
pub use report::{
|
||||
band_edge, curve_frequency, Band, CurvePoint, Report, Status, BANDS, CURVE, DISPLAY_HIGH,
|
||||
DISPLAY_LOW,
|
||||
};
|
||||
pub use settings::{Listen, Mode, Settings};
|
||||
pub use worker::Worker;
|
||||
|
||||
use crossbeam_queue::ArrayQueue;
|
||||
use std::sync::{
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
/// Samples per block handed to the worker.
|
||||
pub const BLOCK: usize = 256;
|
||||
/// Blocks the queue holds: about 340 ms at 48 kHz.
|
||||
const QUEUE_BLOCKS: usize = 64;
|
||||
/// A new fit runs silently this long before it is faded in, so its filters settle.
|
||||
const WARM_S: f32 = 0.04;
|
||||
/// Crossfade time from the old fit to the new one.
|
||||
const FADE_S: f32 = 0.04;
|
||||
|
||||
/// Mono blocks of both layers, before Weld's processing.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Block {
|
||||
pub a: [f32; BLOCK],
|
||||
pub b: [f32; BLOCK],
|
||||
}
|
||||
|
||||
/// Lock-free queues between one engine and its worker.
|
||||
pub struct Link {
|
||||
pub(crate) blocks: ArrayQueue<Block>,
|
||||
pub(crate) fits: ArrayQueue<Fit>,
|
||||
pub(crate) settings: ArrayQueue<Settings>,
|
||||
dropped: AtomicUsize,
|
||||
}
|
||||
impl Link {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
blocks: ArrayQueue::new(QUEUE_BLOCKS),
|
||||
fits: ArrayQueue::new(4),
|
||||
settings: ArrayQueue::new(1),
|
||||
dropped: AtomicUsize::new(0),
|
||||
}
|
||||
}
|
||||
/// Blocks dropped because the worker fell behind.
|
||||
pub fn dropped(&self) -> usize {
|
||||
self.dropped.load(Ordering::Relaxed)
|
||||
}
|
||||
/// Takes the next block, as the worker does. For tests and offline tools.
|
||||
pub fn pop_block(&self) -> Option<Block> {
|
||||
self.blocks.pop()
|
||||
}
|
||||
/// Takes the latest settings, as the worker does. For tests and offline tools.
|
||||
pub fn pop_settings(&self) -> Option<Settings> {
|
||||
self.settings.pop()
|
||||
}
|
||||
/// Hands a fit to the engine, as the worker does. For tests and offline tools.
|
||||
pub fn push_fit(&self, fit: Fit) {
|
||||
self.fits.force_push(fit);
|
||||
}
|
||||
}
|
||||
|
||||
/// Levels for the editor, published a few times per second by the audio thread.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct AnalyzerFrame {
|
||||
/// RMS of the main input in dBFS since the last frame.
|
||||
pub main_db: f32,
|
||||
/// RMS of the sidechain input in dBFS since the last frame.
|
||||
pub side_db: f32,
|
||||
/// Peak of the sidechain input in dBFS since the last frame.
|
||||
pub side_peak_db: f32,
|
||||
/// True once any sidechain sample above −90 dBFS arrived since activation.
|
||||
pub side_seen: bool,
|
||||
/// Blocks the worker could not take in time, since activation.
|
||||
pub dropped: usize,
|
||||
pub sample_rate: f32,
|
||||
}
|
||||
impl Default for AnalyzerFrame {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
main_db: -120.,
|
||||
side_db: -120.,
|
||||
side_peak_db: -120.,
|
||||
side_seen: false,
|
||||
dropped: 0,
|
||||
sample_rate: 48000.,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn db(power_or_amp: f32, power: bool) -> f32 {
|
||||
let v = power_or_amp.max(1e-12);
|
||||
if power {
|
||||
10. * v.log10()
|
||||
} else {
|
||||
20. * v.log10()
|
||||
}
|
||||
.max(-120.)
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Levels {
|
||||
main: f64,
|
||||
side: f64,
|
||||
peak: f32,
|
||||
count: usize,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
enum Phase {
|
||||
Steady,
|
||||
/// The next chain runs unheard for this many more samples.
|
||||
Warm(usize),
|
||||
/// The next chain fades in over this many more samples.
|
||||
Fade(usize),
|
||||
}
|
||||
|
||||
pub struct Engine {
|
||||
rate: f32,
|
||||
channels: usize,
|
||||
settings: Settings,
|
||||
sent: Option<Settings>,
|
||||
gain: f32,
|
||||
target_gain: f32,
|
||||
gain_coef: f32,
|
||||
fresh: bool,
|
||||
levels: Levels,
|
||||
side_seen: bool,
|
||||
current: Chain,
|
||||
next: Chain,
|
||||
phase: Phase,
|
||||
warm: usize,
|
||||
fade: usize,
|
||||
link: Arc<Link>,
|
||||
block: Block,
|
||||
fill: usize,
|
||||
}
|
||||
impl Engine {
|
||||
pub fn new(rate: f32, channels: usize) -> Result<Self, &'static str> {
|
||||
if !(rate.is_finite() && (8000.0..=768000.).contains(&rate)) {
|
||||
return Err("unsupported sample rate");
|
||||
}
|
||||
if !(1..=2).contains(&channels) {
|
||||
return Err("unsupported channel count");
|
||||
}
|
||||
Ok(Self {
|
||||
rate,
|
||||
channels,
|
||||
settings: Settings::default(),
|
||||
sent: None,
|
||||
gain: 1.,
|
||||
target_gain: 1.,
|
||||
gain_coef: 1. - (-1. / (0.02 * rate)).exp(),
|
||||
fresh: true,
|
||||
levels: Levels::default(),
|
||||
side_seen: false,
|
||||
current: Chain::new(Fit::NONE, rate),
|
||||
next: Chain::new(Fit::NONE, rate),
|
||||
phase: Phase::Steady,
|
||||
warm: ((WARM_S * rate) as usize).max(1),
|
||||
fade: ((FADE_S * rate) as usize).max(1),
|
||||
link: Arc::new(Link::new()),
|
||||
block: Block {
|
||||
a: [0.; BLOCK],
|
||||
b: [0.; BLOCK],
|
||||
},
|
||||
fill: 0,
|
||||
})
|
||||
}
|
||||
pub const fn latency_samples(&self) -> u32 {
|
||||
0
|
||||
}
|
||||
pub fn channels(&self) -> usize {
|
||||
self.channels
|
||||
}
|
||||
pub fn sample_rate(&self) -> f32 {
|
||||
self.rate
|
||||
}
|
||||
pub fn settings(&self) -> &Settings {
|
||||
&self.settings
|
||||
}
|
||||
/// The queues for this engine's worker.
|
||||
pub fn link(&self) -> Arc<Link> {
|
||||
self.link.clone()
|
||||
}
|
||||
/// The alignment heard now (the target one during a crossfade).
|
||||
pub fn fit(&self) -> Fit {
|
||||
match self.phase {
|
||||
Phase::Steady => *self.current.fit(),
|
||||
_ => *self.next.fit(),
|
||||
}
|
||||
}
|
||||
/// Applies `fit` at once, without a crossfade. For restoring saved state.
|
||||
pub fn set_fit(&mut self, fit: Fit) {
|
||||
self.current.set(fit, self.rate);
|
||||
self.phase = Phase::Steady;
|
||||
}
|
||||
pub fn set_settings(&mut self, settings: Settings) -> Result<(), &'static str> {
|
||||
settings.validate()?;
|
||||
self.settings = settings;
|
||||
self.target_gain = 10f32.powf(settings.output / 20.);
|
||||
if self.fresh {
|
||||
self.gain = self.target_gain;
|
||||
self.fresh = false;
|
||||
}
|
||||
if self.sent != Some(settings) {
|
||||
self.link.settings.force_push(settings);
|
||||
self.sent = Some(settings);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn reset(&mut self) {
|
||||
self.gain = self.target_gain;
|
||||
self.levels = Levels::default();
|
||||
self.current.reset();
|
||||
if self.phase != Phase::Steady {
|
||||
std::mem::swap(&mut self.current, &mut self.next);
|
||||
self.current.reset();
|
||||
self.phase = Phase::Steady;
|
||||
}
|
||||
self.fill = 0;
|
||||
}
|
||||
/// One frame of main input `x` and sidechain input `side`. Mono uses index 0 only.
|
||||
#[inline]
|
||||
pub fn process_sample(&mut self, x: [f32; 2], side: [f32; 2]) -> [f32; 2] {
|
||||
let n = self.channels;
|
||||
let (mut m, mut s) = (0f32, 0f32);
|
||||
for c in 0..n {
|
||||
m += x[c];
|
||||
s += side[c];
|
||||
self.levels.peak = self.levels.peak.max(side[c].abs());
|
||||
}
|
||||
m /= n as f32;
|
||||
s /= n as f32;
|
||||
self.levels.main += (m * m) as f64;
|
||||
self.levels.side += (s * s) as f64;
|
||||
self.levels.count += 1;
|
||||
if s.abs() > 3e-5 {
|
||||
self.side_seen = true;
|
||||
}
|
||||
self.feed(m, s);
|
||||
if self.phase == Phase::Steady {
|
||||
if let Some(fit) = self.link.fits.pop() {
|
||||
self.next.set(fit, self.rate);
|
||||
self.phase = Phase::Warm(self.warm);
|
||||
}
|
||||
}
|
||||
let mut aligned = [0f32; 2];
|
||||
let mix = match self.phase {
|
||||
Phase::Steady => None,
|
||||
Phase::Warm(_) => Some(0.),
|
||||
Phase::Fade(left) => Some(1. - left as f32 / self.fade as f32),
|
||||
};
|
||||
for c in 0..n {
|
||||
let a = self.current.process(c, x[c]);
|
||||
aligned[c] = match mix {
|
||||
None => a,
|
||||
Some(t) => {
|
||||
let b = self.next.process(c, x[c]);
|
||||
a + t * (b - a)
|
||||
}
|
||||
};
|
||||
}
|
||||
self.phase = match self.phase {
|
||||
Phase::Steady => Phase::Steady,
|
||||
Phase::Warm(1) => Phase::Fade(self.fade),
|
||||
Phase::Warm(left) => Phase::Warm(left - 1),
|
||||
Phase::Fade(1) => {
|
||||
std::mem::swap(&mut self.current, &mut self.next);
|
||||
Phase::Steady
|
||||
}
|
||||
Phase::Fade(left) => Phase::Fade(left - 1),
|
||||
};
|
||||
self.gain += (self.target_gain - self.gain) * self.gain_coef;
|
||||
if self.settings.bypass {
|
||||
return x;
|
||||
}
|
||||
let mut out = [0.; 2];
|
||||
for c in 0..n {
|
||||
out[c] = self.gain
|
||||
* match self.settings.listen {
|
||||
Listen::Layer => aligned[c],
|
||||
Listen::Sum => aligned[c] + side[c],
|
||||
Listen::SumDry => x[c] + side[c],
|
||||
};
|
||||
}
|
||||
out
|
||||
}
|
||||
#[inline]
|
||||
fn feed(&mut self, a: f32, b: f32) {
|
||||
self.block.a[self.fill] = a;
|
||||
self.block.b[self.fill] = b;
|
||||
self.fill += 1;
|
||||
if self.fill == BLOCK {
|
||||
self.fill = 0;
|
||||
if self.link.blocks.push(self.block).is_err() {
|
||||
self.link.dropped.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Levels since the previous call.
|
||||
pub fn take_analyzer(&mut self) -> AnalyzerFrame {
|
||||
let n = self.levels.count.max(1) as f64;
|
||||
let frame = AnalyzerFrame {
|
||||
main_db: db((self.levels.main / n) as f32, true),
|
||||
side_db: db((self.levels.side / n) as f32, true),
|
||||
side_peak_db: db(self.levels.peak, false),
|
||||
side_seen: self.side_seen,
|
||||
dropped: self.link.dropped(),
|
||||
sample_rate: self.rate,
|
||||
};
|
||||
self.levels = Levels::default();
|
||||
frame
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
//! What the analysis tells the editor. Plain `Copy` data, so it crosses threads through
|
||||
//! a lock-free queue without allocating.
|
||||
use crate::chain::Fit;
|
||||
|
||||
/// Display bands, equally wide on a log axis from `DISPLAY_LOW` to `DISPLAY_HIGH`.
|
||||
pub const BANDS: usize = 10;
|
||||
/// Points of the phase curve.
|
||||
pub const CURVE: usize = 96;
|
||||
pub const DISPLAY_LOW: f32 = 30.;
|
||||
pub const DISPLAY_HIGH: f32 = 12000.;
|
||||
|
||||
/// Index of the display band that contains `f` (clamped to the outer bands).
|
||||
pub fn band_of(f: f32) -> usize {
|
||||
let t = (f / DISPLAY_LOW).ln() / (DISPLAY_HIGH / DISPLAY_LOW).ln();
|
||||
((t * BANDS as f32).max(0.) as usize).min(BANDS - 1)
|
||||
}
|
||||
/// Lower edge of display band `i`; `band_edge(BANDS)` is the top edge.
|
||||
pub fn band_edge(i: usize) -> f32 {
|
||||
DISPLAY_LOW * (DISPLAY_HIGH / DISPLAY_LOW).powf(i as f32 / BANDS as f32)
|
||||
}
|
||||
/// Frequency of curve point `i`.
|
||||
pub fn curve_frequency(i: usize) -> f32 {
|
||||
DISPLAY_LOW * (DISPLAY_HIGH / DISPLAY_LOW).powf(i as f32 / (CURVE - 1) as f32)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub enum Status {
|
||||
/// Not enough measured audio yet.
|
||||
#[default]
|
||||
Waiting,
|
||||
/// The sidechain carries no signal.
|
||||
NoSidechain,
|
||||
/// Both layers play, but one of them is under the gate.
|
||||
Quiet,
|
||||
/// The layers are not related closely enough to align (free-running oscillators,
|
||||
/// different notes, noise).
|
||||
Loose,
|
||||
/// This layer is later than the sidechain layer. An allpass cannot move it earlier.
|
||||
Late,
|
||||
/// Measuring and aligning.
|
||||
Aligned,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
||||
pub struct Band {
|
||||
/// Level of the unprocessed sum relative to a perfectly aligned sum, in dB (≤ 0).
|
||||
pub before: f32,
|
||||
/// Level of the sum with Weld's alignment, relative to a perfect one, in dB (≤ 0).
|
||||
pub after: f32,
|
||||
/// Power-weighted coherence of the two layers, 0..1.
|
||||
pub coherence: f32,
|
||||
/// False when the band carries no measured signal.
|
||||
pub valid: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Default)]
|
||||
pub struct CurvePoint {
|
||||
/// Phase of the main layer relative to the sidechain layer, degrees, ±180.
|
||||
pub before: f32,
|
||||
/// The same with Weld's alignment applied.
|
||||
pub after: f32,
|
||||
/// Phase of Weld's chain, degrees, ±180.
|
||||
pub chain: f32,
|
||||
pub coherence: f32,
|
||||
pub valid: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Report {
|
||||
pub status: Status,
|
||||
/// The alignment currently applied (or about to be).
|
||||
pub fit: Fit,
|
||||
/// True when this report comes with a newly accepted fit.
|
||||
pub changed: bool,
|
||||
pub bands: [Band; BANDS],
|
||||
pub curve: [CurvePoint; CURVE],
|
||||
/// What the cancellation costs between Low and High: aligned sum over unprocessed sum.
|
||||
pub cost_db: f32,
|
||||
/// What Weld wins back between Low and High: aligned-by-Weld sum over unprocessed sum.
|
||||
pub recovered_db: f32,
|
||||
/// Time offset of this layer against the sidechain layer, ms. Positive: this layer
|
||||
/// is late.
|
||||
pub lag_ms: f32,
|
||||
/// How clear the time offset is, 0..1.
|
||||
pub lag_strength: f32,
|
||||
/// Measured frames in the current average.
|
||||
pub frames: u32,
|
||||
pub low: f32,
|
||||
pub high: f32,
|
||||
}
|
||||
impl Default for Report {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
status: Status::Waiting,
|
||||
fit: Fit::NONE,
|
||||
changed: false,
|
||||
bands: [Band::default(); BANDS],
|
||||
curve: [CurvePoint::default(); CURVE],
|
||||
cost_db: 0.,
|
||||
recovered_db: 0.,
|
||||
lag_ms: 0.,
|
||||
lag_strength: 0.,
|
||||
frames: 0,
|
||||
low: 60.,
|
||||
high: 6000.,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
//! Host-independent controls. Gains in dB, frequencies in Hz, times in seconds.
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// What the plugin outputs.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
pub enum Listen {
|
||||
/// The aligned main layer only. The sidechain layer reaches the mix on its own track.
|
||||
#[default]
|
||||
Layer,
|
||||
/// Aligned main layer plus the sidechain layer, to judge the sum in one place.
|
||||
Sum,
|
||||
/// Unprocessed main layer plus the sidechain layer, to compare with `Sum`.
|
||||
SumDry,
|
||||
}
|
||||
|
||||
/// How the alignment is found.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Default)]
|
||||
pub enum Mode {
|
||||
/// Keep measuring and refit when a clearly better alignment shows up.
|
||||
#[default]
|
||||
Follow,
|
||||
/// Measure from the moment Learn starts, with equal weight; the result is applied
|
||||
/// when Learn ends.
|
||||
Learn,
|
||||
/// Keep the current alignment. The display keeps measuring.
|
||||
Hold,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Settings {
|
||||
pub mode: Mode,
|
||||
/// Averaging time of the measurement in Follow mode.
|
||||
pub response: f32,
|
||||
/// Lowest frequency the fit listens to.
|
||||
pub low: f32,
|
||||
/// Highest frequency the fit listens to.
|
||||
pub high: f32,
|
||||
/// Largest number of allpass sections the fit may use.
|
||||
pub sections: usize,
|
||||
/// Frames quieter than this (dBFS RMS) on either layer are not measured.
|
||||
pub gate: f32,
|
||||
pub listen: Listen,
|
||||
pub output: f32,
|
||||
pub bypass: bool,
|
||||
}
|
||||
impl Default for Settings {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
mode: Mode::Follow,
|
||||
response: 1.5,
|
||||
low: 60.,
|
||||
high: 6000.,
|
||||
sections: 4,
|
||||
gate: -50.,
|
||||
listen: Listen::Layer,
|
||||
output: 0.,
|
||||
bypass: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Settings {
|
||||
pub fn validate(&self) -> Result<(), &'static str> {
|
||||
let values = [self.response, self.low, self.high, self.gate, self.output];
|
||||
if values.iter().any(|v| !v.is_finite()) {
|
||||
return Err("non-finite setting");
|
||||
}
|
||||
if (0.3..=5.).contains(&self.response)
|
||||
&& (30.0..=400.).contains(&self.low)
|
||||
&& (1000.0..=12000.).contains(&self.high)
|
||||
&& (1..=crate::chain::MAX_SECTIONS).contains(&self.sections)
|
||||
&& (-70.0..=-30.).contains(&self.gate)
|
||||
&& (-12.0..=12.).contains(&self.output)
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err("setting out of range")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//! The worker thread: takes blocks from the audio thread, runs the analyzer and sends
|
||||
//! accepted fits back. Started and stopped outside the audio thread.
|
||||
use crate::analyzer::Analyzer;
|
||||
use crate::chain::Fit;
|
||||
use crate::report::Report;
|
||||
use crate::Link;
|
||||
use crossbeam_queue::ArrayQueue;
|
||||
use std::{
|
||||
sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
},
|
||||
thread::JoinHandle,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
pub struct Worker {
|
||||
stop: Arc<AtomicBool>,
|
||||
thread: Option<JoinHandle<()>>,
|
||||
}
|
||||
impl Worker {
|
||||
/// Starts the worker for one engine. `on_fit` runs on the worker thread for every
|
||||
/// accepted fit, for example to store it in the plugin state.
|
||||
pub fn spawn(
|
||||
link: Arc<Link>,
|
||||
rate: f32,
|
||||
fit: Fit,
|
||||
reports: Arc<ArrayQueue<Report>>,
|
||||
mut on_fit: impl FnMut(Fit) + Send + 'static,
|
||||
) -> std::io::Result<Self> {
|
||||
let stop = Arc::new(AtomicBool::new(false));
|
||||
let flag = stop.clone();
|
||||
let thread = std::thread::Builder::new()
|
||||
.name("weld-analysis".into())
|
||||
.spawn(move || {
|
||||
let mut analyzer = Analyzer::new(rate, fit);
|
||||
while !flag.load(Ordering::Relaxed) {
|
||||
let mut idle = true;
|
||||
while let Some(settings) = link.settings.pop() {
|
||||
analyzer.set_settings(settings);
|
||||
}
|
||||
while let Some(block) = link.blocks.pop() {
|
||||
idle = false;
|
||||
analyzer.push(&block.a, &block.b);
|
||||
if let Some(update) = analyzer.poll() {
|
||||
if let Some(fit) = update.fit {
|
||||
link.fits.force_push(fit);
|
||||
on_fit(fit);
|
||||
}
|
||||
reports.force_push(update.report);
|
||||
}
|
||||
if flag.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if idle {
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
})?;
|
||||
Ok(Self {
|
||||
stop,
|
||||
thread: Some(thread),
|
||||
})
|
||||
}
|
||||
pub fn stop(&mut self) {
|
||||
self.stop.store(true, Ordering::Relaxed);
|
||||
if let Some(thread) = self.thread.take() {
|
||||
let _ = thread.join();
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Drop for Worker {
|
||||
fn drop(&mut self) {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
use weld_core::{Engine, Listen, Settings};
|
||||
|
||||
fn signal(n: usize, hz: f32) -> f32 {
|
||||
(std::f32::consts::TAU * hz * n as f32 / 48000.).sin() * 0.5
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_output_is_the_main_input_with_zero_latency() {
|
||||
let mut engine = Engine::new(48000., 2).unwrap();
|
||||
engine.set_settings(Settings::default()).unwrap();
|
||||
assert_eq!(engine.latency_samples(), 0);
|
||||
for n in 0..4800 {
|
||||
let x = [signal(n, 110.), -signal(n, 220.)];
|
||||
let out = engine.process_sample(x, [signal(n, 330.), 0.25]);
|
||||
assert_eq!(out, x);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sum_modes_add_the_sidechain() {
|
||||
for listen in [Listen::Sum, Listen::SumDry] {
|
||||
let mut engine = Engine::new(48000., 2).unwrap();
|
||||
engine
|
||||
.set_settings(Settings {
|
||||
listen,
|
||||
..Settings::default()
|
||||
})
|
||||
.unwrap();
|
||||
for n in 0..480 {
|
||||
let x = [signal(n, 110.), signal(n, 120.)];
|
||||
let s = [signal(n, 330.), -signal(n, 90.)];
|
||||
let out = engine.process_sample(x, s);
|
||||
for c in 0..2 {
|
||||
assert!((out[c] - (x[c] + s[c])).abs() < 1e-6);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mono_bypass_and_output_gain() {
|
||||
let mut engine = Engine::new(44100., 1).unwrap();
|
||||
engine
|
||||
.set_settings(Settings {
|
||||
output: -6.,
|
||||
..Settings::default()
|
||||
})
|
||||
.unwrap();
|
||||
let out = engine.process_sample([0.5, 0.], [0., 0.]);
|
||||
assert!((out[0] - 0.5 * 10f32.powf(-6. / 20.)).abs() < 1e-6);
|
||||
assert_eq!(out[1], 0.);
|
||||
engine
|
||||
.set_settings(Settings {
|
||||
bypass: true,
|
||||
..Settings::default()
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(engine.process_sample([0.3, 0.], [0.9, 0.]), [0.3, 0.]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn analyzer_reports_sidechain_presence_and_level() {
|
||||
let mut engine = Engine::new(48000., 2).unwrap();
|
||||
engine.set_settings(Settings::default()).unwrap();
|
||||
for n in 0..4800 {
|
||||
engine.process_sample([signal(n, 100.); 2], [0.; 2]);
|
||||
}
|
||||
let frame = engine.take_analyzer();
|
||||
assert!(!frame.side_seen);
|
||||
assert!(frame.side_db < -100.);
|
||||
assert!((frame.main_db - (-9.03)).abs() < 0.1, "{}", frame.main_db);
|
||||
for n in 0..4800 {
|
||||
engine.process_sample([0.; 2], [signal(n, 100.); 2]);
|
||||
}
|
||||
let frame = engine.take_analyzer();
|
||||
assert!(frame.side_seen);
|
||||
assert!((frame.side_db - (-9.03)).abs() < 0.1);
|
||||
assert!((frame.side_peak_db - (-6.02)).abs() < 0.1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_settings_and_rates_are_rejected() {
|
||||
assert!(Engine::new(0., 2).is_err());
|
||||
assert!(Engine::new(48000., 3).is_err());
|
||||
let mut engine = Engine::new(48000., 2).unwrap();
|
||||
assert!(engine
|
||||
.set_settings(Settings {
|
||||
output: f32::NAN,
|
||||
..Settings::default()
|
||||
})
|
||||
.is_err());
|
||||
let json = serde_json::to_string(&Settings::default()).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Settings>(&json).unwrap(),
|
||||
Settings::default()
|
||||
);
|
||||
}
|
||||
|
||||
use weld_core::{Analyzer, Chain, Fit, Mode, Section, Status};
|
||||
|
||||
fn random_fit(seed: u64) -> Fit {
|
||||
let mut s = seed;
|
||||
let mut rand = move || {
|
||||
s = s
|
||||
.wrapping_mul(6364136223846793005)
|
||||
.wrapping_add(1442695040888963407);
|
||||
(s >> 11) as f32 / (1u64 << 53) as f32
|
||||
};
|
||||
let mut fit = Fit {
|
||||
flip: rand() > 0.5,
|
||||
count: 1 + (rand() * 3.99) as usize,
|
||||
..Fit::NONE
|
||||
};
|
||||
for section in &mut fit.sections {
|
||||
*section = Section {
|
||||
fc: 30. * 600f32.powf(rand()),
|
||||
q: 0.2 * 20f32.powf(rand()),
|
||||
};
|
||||
}
|
||||
fit
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_chain_is_flat_in_magnitude() {
|
||||
for seed in 1..40 {
|
||||
let fit = random_fit(seed);
|
||||
for i in 0..200 {
|
||||
let f = 20. * 1000f32.powf(i as f32 / 199.);
|
||||
let (re, im) = fit.response(f, 48000.);
|
||||
let db = 10. * (re * re + im * im).log10();
|
||||
assert!(db.abs() < 0.01, "{fit:?} at {f} Hz: {db}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_running_chain_matches_its_response() {
|
||||
let fit = random_fit(3);
|
||||
for f in [50f32, 333., 2100., 9000.] {
|
||||
let mut chain = Chain::new(fit, 48000.);
|
||||
let (mut i_sum, mut q_sum, mut energy) = (0f64, 0f64, 0f64);
|
||||
let n = 96000;
|
||||
for k in 0..n {
|
||||
let t = k as f64 / 48000.;
|
||||
let w = std::f64::consts::TAU * f as f64 * t;
|
||||
let y = chain.process(0, w.cos() as f32) as f64;
|
||||
if k > n / 2 {
|
||||
i_sum += y * w.cos();
|
||||
q_sum += -y * w.sin();
|
||||
energy += y * y;
|
||||
}
|
||||
}
|
||||
let m = (n / 2 - 1) as f64;
|
||||
let (re, im) = fit.response(f, 48000.);
|
||||
let measured = (2. * i_sum / m, 2. * q_sum / m);
|
||||
assert!(
|
||||
(measured.0 - re as f64).abs() < 0.01,
|
||||
"{f}: {measured:?} vs {re},{im}"
|
||||
);
|
||||
assert!(
|
||||
(measured.1 - im as f64).abs() < 0.01,
|
||||
"{f}: {measured:?} vs {re},{im}"
|
||||
);
|
||||
assert!((2. * energy / m - 1.).abs() < 0.01);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_impulse_response_starts_at_sample_zero() {
|
||||
let mut chain = Chain::new(random_fit(5), 48000.);
|
||||
let first = chain.process(0, 1.);
|
||||
assert!(first.abs() > 0.01, "{first}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_fit_crossfades_without_clicks() {
|
||||
let mut engine = Engine::new(48000., 2).unwrap();
|
||||
engine.set_settings(Settings::default()).unwrap();
|
||||
let link = engine.link();
|
||||
let x = |n: usize| signal(n, 97.) + 0.3 * signal(n, 1210.);
|
||||
let max_input_step = (1..48000)
|
||||
.map(|n| (x(n) - x(n - 1)).abs())
|
||||
.fold(0f32, f32::max);
|
||||
let mut previous = [0f32; 2];
|
||||
let mut largest = 0f32;
|
||||
for n in 0..48000 {
|
||||
if n == 4800 {
|
||||
link.push_fit(Fit {
|
||||
flip: true,
|
||||
count: 2,
|
||||
sections: [
|
||||
Section { fc: 300., q: 0.7 },
|
||||
Section { fc: 2000., q: 2. },
|
||||
Section::default(),
|
||||
Section::default(),
|
||||
],
|
||||
});
|
||||
}
|
||||
let out = engine.process_sample([x(n), x(n)], [0.; 2]);
|
||||
if n > 0 {
|
||||
largest = largest.max((out[0] - previous[0]).abs());
|
||||
}
|
||||
previous = out;
|
||||
}
|
||||
assert!(
|
||||
largest <= 1.5 * max_input_step,
|
||||
"{largest} vs {max_input_step}"
|
||||
);
|
||||
assert!(engine.fit().flip);
|
||||
assert_eq!(engine.fit().count, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sum_uses_the_aligned_layer_and_sum_dry_the_unprocessed_one() {
|
||||
for listen in [Listen::Sum, Listen::SumDry] {
|
||||
let mut engine = Engine::new(48000., 1).unwrap();
|
||||
engine
|
||||
.set_settings(Settings {
|
||||
listen,
|
||||
..Settings::default()
|
||||
})
|
||||
.unwrap();
|
||||
engine.set_fit(Fit {
|
||||
flip: true,
|
||||
..Fit::NONE
|
||||
});
|
||||
let out = engine.process_sample([0.5, 0.], [0.2, 0.]);
|
||||
let expected = if listen == Listen::Sum { -0.3 } else { 0.7 };
|
||||
assert!((out[0] - expected).abs() < 1e-6, "{listen:?} {out:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocks_reach_the_worker_and_drops_are_counted() {
|
||||
let mut engine = Engine::new(48000., 2).unwrap();
|
||||
engine.set_settings(Settings::default()).unwrap();
|
||||
let link = engine.link();
|
||||
assert!(link.pop_settings().is_some());
|
||||
for n in 0..256 * 70 {
|
||||
engine.process_sample([signal(n, 100.); 2], [signal(n, 100.); 2]);
|
||||
}
|
||||
assert_eq!(link.dropped(), 6);
|
||||
let block = link.pop_block().unwrap();
|
||||
assert!((block.a[10] - signal(10, 100.)).abs() < 1e-6);
|
||||
assert_eq!(block.a, block.b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silence_holds_the_fit_and_produces_no_nan() {
|
||||
let flipped = Fit {
|
||||
flip: true,
|
||||
..Fit::NONE
|
||||
};
|
||||
let mut analyzer = Analyzer::new(48000., flipped);
|
||||
analyzer.set_settings(Settings::default());
|
||||
let zeros = [0f32; 256];
|
||||
let mut last = None;
|
||||
for _ in 0..400 {
|
||||
analyzer.push(&zeros, &zeros);
|
||||
if let Some(update) = analyzer.poll() {
|
||||
assert!(update.fit.is_none());
|
||||
last = Some(update.report);
|
||||
}
|
||||
}
|
||||
let report = last.unwrap();
|
||||
assert_eq!(report.status, Status::NoSidechain);
|
||||
assert_eq!(report.fit, flipped);
|
||||
assert!(report.cost_db.is_finite() && report.recovered_db.is_finite());
|
||||
assert!(report
|
||||
.bands
|
||||
.iter()
|
||||
.all(|b| b.before.is_finite() && b.after.is_finite()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn follow_mode_finds_the_flip_and_then_holds_still() {
|
||||
let mut analyzer = Analyzer::new(48000., Fit::NONE);
|
||||
analyzer.set_settings(Settings {
|
||||
mode: Mode::Follow,
|
||||
..Settings::default()
|
||||
});
|
||||
let a: Vec<f32> = (0..48000 * 6)
|
||||
.map(|n| signal(n, 87.3) + 0.3 * signal(n, 261.9) + 0.1 * signal(n, 611.))
|
||||
.collect();
|
||||
let b: Vec<f32> = a.iter().map(|v| -0.7 * v).collect();
|
||||
let mut accepted = Vec::new();
|
||||
let mut last = None;
|
||||
for (x, y) in a.chunks(256).zip(b.chunks(256)) {
|
||||
analyzer.push(x, y);
|
||||
if let Some(update) = analyzer.poll() {
|
||||
if let Some(fit) = update.fit {
|
||||
accepted.push(fit);
|
||||
}
|
||||
last = Some(update.report);
|
||||
}
|
||||
}
|
||||
assert_eq!(accepted.len(), 1, "{accepted:?}");
|
||||
assert!(accepted[0].flip);
|
||||
let report = last.unwrap();
|
||||
assert_eq!(report.status, Status::Aligned);
|
||||
assert!(report.recovered_db > 10., "{}", report.recovered_db);
|
||||
assert!((report.recovered_db - report.cost_db).abs() < 0.2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn learn_measures_and_applies_on_exit() {
|
||||
let mut analyzer = Analyzer::new(48000., Fit::NONE);
|
||||
let learn = Settings {
|
||||
mode: Mode::Learn,
|
||||
..Settings::default()
|
||||
};
|
||||
analyzer.set_settings(learn);
|
||||
let a: Vec<f32> = (0..48000 * 2)
|
||||
.map(|n| signal(n, 87.3) + 0.3 * signal(n, 261.9))
|
||||
.collect();
|
||||
let b: Vec<f32> = a.iter().map(|v| -v).collect();
|
||||
for (x, y) in a.chunks(256).zip(b.chunks(256)) {
|
||||
analyzer.push(x, y);
|
||||
let _ = analyzer.poll();
|
||||
}
|
||||
analyzer.set_settings(Settings {
|
||||
mode: Mode::Hold,
|
||||
..learn
|
||||
});
|
||||
let update = analyzer.poll().expect("leaving Learn reports at once");
|
||||
assert!(analyzer.current().flip);
|
||||
// Learn may already have applied the flip while measuring.
|
||||
assert!(update.fit.is_none_or(|f| f.flip));
|
||||
// Hold never refits, even when the layers change.
|
||||
let c: Vec<f32> = a.clone();
|
||||
for (x, y) in a.chunks(256).zip(c.chunks(256)) {
|
||||
analyzer.push(x, y);
|
||||
if let Some(update) = analyzer.poll() {
|
||||
assert!(update.fit.is_none());
|
||||
}
|
||||
}
|
||||
assert!(analyzer.current().flip);
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
//! Fit quality on a synthetic saw bass, with targets taken from the prototype.
|
||||
use rustfft::{num_complex::Complex64, FftPlanner};
|
||||
use weld_core::{Analyzer, Chain, Fit, Mode, Settings, Status};
|
||||
|
||||
const RATE: f32 = 48000.;
|
||||
|
||||
/// Two seconds of an F1 saw (60 harmonics, fixed random phases) plus a little noise.
|
||||
fn bass() -> Vec<f32> {
|
||||
let n = 2 * RATE as usize;
|
||||
let mut seed = 1u64;
|
||||
let mut rand = move || {
|
||||
seed = seed
|
||||
.wrapping_mul(6364136223846793005)
|
||||
.wrapping_add(1442695040888963407);
|
||||
(seed >> 11) as f64 / (1u64 << 53) as f64
|
||||
};
|
||||
let phases: Vec<f64> = (0..60).map(|_| rand() * std::f64::consts::TAU).collect();
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let t = i as f64 / RATE as f64;
|
||||
let saw: f64 = (1..60)
|
||||
.map(|k| (std::f64::consts::TAU * k as f64 * 87.3 * t + phases[k]).sin() / k as f64)
|
||||
.sum();
|
||||
(0.3 * saw + 0.015 * (rand() - 0.5)) as f32
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn noise(n: usize, seed: u64) -> Vec<f32> {
|
||||
let mut s = seed;
|
||||
(0..n)
|
||||
.map(|_| {
|
||||
s = s
|
||||
.wrapping_mul(6364136223846793005)
|
||||
.wrapping_add(1442695040888963407);
|
||||
((s >> 11) as f64 / (1u64 << 53) as f64 - 0.5) as f32 * 0.5
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn delay(x: &[f32], samples: isize) -> Vec<f32> {
|
||||
(0..x.len() as isize)
|
||||
.map(|i| {
|
||||
let j = i - samples;
|
||||
if j >= 0 && (j as usize) < x.len() {
|
||||
x[j as usize]
|
||||
} else {
|
||||
0.
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
/// Direct-form biquad, b and a normalised by a0.
|
||||
fn biquad(x: &[f32], b: [f64; 3], a: [f64; 3]) -> Vec<f32> {
|
||||
let (mut x1, mut x2, mut y1, mut y2) = (0f64, 0f64, 0f64, 0f64);
|
||||
x.iter()
|
||||
.map(|&v| {
|
||||
let v = v as f64;
|
||||
let y = (b[0] * v + b[1] * x1 + b[2] * x2 - a[1] * y1 - a[2] * y2) / a[0];
|
||||
(x2, x1, y2, y1) = (x1, v, y1, y);
|
||||
y as f32
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
fn allpass(x: &[f32], fc: f64, q: f64) -> Vec<f32> {
|
||||
let w = std::f64::consts::TAU * fc / RATE as f64;
|
||||
let alpha = w.sin() / (2. * q);
|
||||
let a = [1. + alpha, -2. * w.cos(), 1. - alpha];
|
||||
biquad(x, [a[2], a[1], a[0]], a)
|
||||
}
|
||||
fn highpass(x: &[f32], fc: f64) -> Vec<f32> {
|
||||
let w = std::f64::consts::TAU * fc / RATE as f64;
|
||||
let alpha = w.sin() / (2. * std::f64::consts::FRAC_1_SQRT_2);
|
||||
let c = w.cos();
|
||||
biquad(
|
||||
x,
|
||||
[(1. + c) / 2., -(1. + c), (1. + c) / 2.],
|
||||
[1. + alpha, -2. * c, 1. - alpha],
|
||||
)
|
||||
}
|
||||
fn power_db(x: &[f32]) -> f64 {
|
||||
let skip = x.len() / 4;
|
||||
let p: f64 =
|
||||
x[skip..].iter().map(|&v| (v as f64).powi(2)).sum::<f64>() / (x.len() - skip) as f64;
|
||||
10. * p.max(1e-30).log10()
|
||||
}
|
||||
fn sum(a: &[f32], b: &[f32]) -> Vec<f32> {
|
||||
a.iter().zip(b).map(|(a, b)| a + b).collect()
|
||||
}
|
||||
fn apply(fit: Fit, x: &[f32]) -> Vec<f32> {
|
||||
let mut chain = Chain::new(fit, RATE);
|
||||
x.iter().map(|&v| chain.process(0, v)).collect()
|
||||
}
|
||||
/// Level of A + B when every bin of A is rotated onto B: the best any phase-only
|
||||
/// processing could reach.
|
||||
fn ideal_db(a: &[f32], b: &[f32]) -> f64 {
|
||||
let n = a.len();
|
||||
let mut planner = FftPlanner::<f64>::new();
|
||||
let fft = planner.plan_fft_forward(n);
|
||||
let ifft = planner.plan_fft_inverse(n);
|
||||
let mut fa: Vec<Complex64> = a.iter().map(|&v| Complex64::new(v as f64, 0.)).collect();
|
||||
let mut fb: Vec<Complex64> = b.iter().map(|&v| Complex64::new(v as f64, 0.)).collect();
|
||||
fft.process(&mut fa);
|
||||
fft.process(&mut fb);
|
||||
let mut y: Vec<Complex64> = fa
|
||||
.iter()
|
||||
.zip(&fb)
|
||||
.map(|(a, b)| {
|
||||
let unit = if b.norm() > 1e-12 {
|
||||
b / b.norm()
|
||||
} else {
|
||||
Complex64::new(1., 0.)
|
||||
};
|
||||
unit * a.norm() + b
|
||||
})
|
||||
.collect();
|
||||
ifft.process(&mut y);
|
||||
let out: Vec<f32> = y.iter().map(|v| (v.re / n as f64) as f32).collect();
|
||||
power_db(&out)
|
||||
}
|
||||
/// Power of A+B in octave bands from 60 Hz to 7.7 kHz, after minus before, in dB.
|
||||
fn octave_changes(a: &[f32], aligned: &[f32], b: &[f32]) -> Vec<f64> {
|
||||
let n = a.len();
|
||||
let mut planner = FftPlanner::<f64>::new();
|
||||
let fft = planner.plan_fft_forward(n);
|
||||
let spectrum = |x: Vec<f32>| {
|
||||
let mut v: Vec<Complex64> = x.iter().map(|&s| Complex64::new(s as f64, 0.)).collect();
|
||||
fft.process(&mut v);
|
||||
v
|
||||
};
|
||||
let before = spectrum(sum(a, b));
|
||||
let after = spectrum(sum(aligned, b));
|
||||
(0..7)
|
||||
.map(|o| {
|
||||
let lo = 60. * 2f64.powi(o);
|
||||
let range = |s: &Vec<Complex64>| -> f64 {
|
||||
(0..n / 2)
|
||||
.filter(|&k| {
|
||||
let f = k as f64 * RATE as f64 / n as f64;
|
||||
f >= lo && f < 2. * lo
|
||||
})
|
||||
.map(|k| s[k].norm_sqr())
|
||||
.sum()
|
||||
};
|
||||
10. * (range(&after) / range(&before)).log10()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
struct Outcome {
|
||||
accepted: Option<Fit>,
|
||||
status: Status,
|
||||
lag_ms: f32,
|
||||
before: f64,
|
||||
after: f64,
|
||||
ideal: f64,
|
||||
octaves: Vec<f64>,
|
||||
}
|
||||
fn run(a: &[f32], b: &[f32]) -> Outcome {
|
||||
let mut analyzer = Analyzer::new(RATE, Fit::NONE);
|
||||
analyzer.set_settings(Settings {
|
||||
mode: Mode::Learn,
|
||||
low: 40.,
|
||||
high: 8000.,
|
||||
..Settings::default()
|
||||
});
|
||||
for (x, y) in a.chunks(256).zip(b.chunks(256)) {
|
||||
analyzer.push(x, y);
|
||||
}
|
||||
let update = analyzer.analyse(Some(0.1));
|
||||
let fit = *analyzer.current();
|
||||
let aligned = apply(fit, a);
|
||||
Outcome {
|
||||
accepted: update.fit,
|
||||
status: update.report.status,
|
||||
lag_ms: update.report.lag_ms,
|
||||
before: power_db(&sum(a, b)),
|
||||
after: power_db(&sum(&aligned, b)),
|
||||
ideal: ideal_db(a, b),
|
||||
octaves: octave_changes(a, &aligned, b),
|
||||
}
|
||||
}
|
||||
fn show(name: &str, o: &Outcome) {
|
||||
eprintln!(
|
||||
"{name}: before {:.2} after {:.2} ideal {:.2} fit {:?} status {:?} lag {:.3} octaves {:?}",
|
||||
o.before,
|
||||
o.after,
|
||||
o.ideal,
|
||||
o.accepted.map(|f| (f.flip, f.active().to_vec())),
|
||||
o.status,
|
||||
o.lag_ms,
|
||||
o.octaves
|
||||
.iter()
|
||||
.map(|v| (v * 10.).round() / 10.)
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polarity_flip_needs_no_sections() {
|
||||
let a = bass();
|
||||
let b: Vec<f32> = a.iter().map(|v| -v).collect();
|
||||
let o = run(&a, &b);
|
||||
show("flip", &o);
|
||||
let fit = o.accepted.expect("a fit");
|
||||
assert!(fit.flip);
|
||||
assert_eq!(fit.count, 0);
|
||||
assert!((o.after - o.ideal).abs() < 0.05);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_allpass_is_found_again() {
|
||||
let a = bass();
|
||||
let b = allpass(&a, 400., 0.7);
|
||||
let o = run(&a, &b);
|
||||
show("allpass400", &o);
|
||||
let fit = o.accepted.expect("a fit");
|
||||
assert!(!fit.flip);
|
||||
assert_eq!(fit.count, 1, "{fit:?}");
|
||||
let s = fit.sections[0];
|
||||
assert!((s.fc / 400. - 1.).abs() < 0.05, "{s:?}");
|
||||
assert!((s.q / 0.7 - 1.).abs() < 0.1, "{s:?}");
|
||||
assert!(o.ideal - o.after < 0.1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_late_sidechain_layer_is_caught_up() {
|
||||
let a = bass();
|
||||
for ms in [0.3, 1.0] {
|
||||
let b = delay(&a, (ms * 48.) as isize);
|
||||
let o = run(&a, &b);
|
||||
show(&format!("delay {ms}"), &o);
|
||||
assert!(o.ideal - o.after < 0.3, "{ms}");
|
||||
assert!(o.after > o.before);
|
||||
assert_ne!(o.status, Status::Late);
|
||||
// A delay leaves a comb in the sum: notches at odd multiples of 1/(2·delay).
|
||||
// A few allpass sections cannot follow a delay's phase all the way up, so they
|
||||
// move the notches rather than remove them; one octave may lose some level
|
||||
// while its neighbours gain more.
|
||||
let mean = o.octaves.iter().sum::<f64>() / o.octaves.len() as f64;
|
||||
assert!(mean > 0.4, "{ms} ms: mean octave change {mean}");
|
||||
for (i, v) in o.octaves.iter().enumerate() {
|
||||
assert!(*v > -2., "{ms} ms, octave {i}: {v}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_inverted_highpassed_layer_is_aligned() {
|
||||
let a = bass();
|
||||
let b: Vec<f32> = highpass(&a, 300.).iter().map(|v| -v).collect();
|
||||
let o = run(&a, &b);
|
||||
show("inverted hp300", &o);
|
||||
assert!(o.ideal - o.after < 0.3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_layers_are_left_alone() {
|
||||
let a = bass();
|
||||
let b = noise(a.len(), 7);
|
||||
let o = run(&a, &b);
|
||||
show("unrelated", &o);
|
||||
assert!(o.accepted.is_none());
|
||||
assert_eq!(o.status, Status::Loose);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_late_main_layer_is_reported_and_not_made_worse() {
|
||||
let a = bass();
|
||||
let b = delay(&a, -14);
|
||||
let o = run(&a, &b);
|
||||
show("ahead", &o);
|
||||
assert_eq!(o.status, Status::Late);
|
||||
assert!((o.lag_ms - 14. / 48.).abs() < 0.03, "{}", o.lag_ms);
|
||||
assert!(o.after > o.before - 0.05);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_fit_is_fast() {
|
||||
let a = bass();
|
||||
let b = delay(&a, 48);
|
||||
let mut analyzer = Analyzer::new(RATE, Fit::NONE);
|
||||
analyzer.set_settings(Settings {
|
||||
mode: Mode::Learn,
|
||||
..Settings::default()
|
||||
});
|
||||
for (x, y) in a.chunks(256).zip(b.chunks(256)) {
|
||||
analyzer.push(x, y);
|
||||
}
|
||||
let start = std::time::Instant::now();
|
||||
analyzer.analyse(Some(0.));
|
||||
let elapsed = start.elapsed();
|
||||
eprintln!("fit took {elapsed:?}");
|
||||
let limit = if cfg!(debug_assertions) { 1000 } else { 50 };
|
||||
assert!(elapsed.as_millis() < limit, "{elapsed:?}");
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
use std::{
|
||||
alloc::{GlobalAlloc, Layout, System},
|
||||
cell::Cell,
|
||||
};
|
||||
use weld_core::{Engine, Fit, Listen, Section, Settings};
|
||||
|
||||
struct CheckedAllocator;
|
||||
thread_local! {
|
||||
static CHECK:Cell<bool>=const {Cell::new(false)};
|
||||
static OPERATIONS:Cell<usize>=const {Cell::new(0)};
|
||||
}
|
||||
fn record() {
|
||||
if CHECK.try_with(Cell::get).unwrap_or(false) {
|
||||
let _ = OPERATIONS.try_with(|n| n.set(n.get() + 1));
|
||||
}
|
||||
}
|
||||
unsafe impl GlobalAlloc for CheckedAllocator {
|
||||
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
|
||||
record();
|
||||
unsafe { System.alloc(layout) }
|
||||
}
|
||||
unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
|
||||
record();
|
||||
unsafe { System.dealloc(pointer, layout) }
|
||||
}
|
||||
unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, size: usize) -> *mut u8 {
|
||||
record();
|
||||
unsafe { System.realloc(pointer, layout, size) }
|
||||
}
|
||||
}
|
||||
#[global_allocator]
|
||||
static ALLOCATOR: CheckedAllocator = CheckedAllocator;
|
||||
|
||||
#[test]
|
||||
fn processing_fits_crossfades_and_a_full_queue_do_not_allocate_or_free() {
|
||||
let mut engine = Engine::new(48000., 2).unwrap();
|
||||
let mut settings = Settings::default();
|
||||
engine.set_settings(settings).unwrap();
|
||||
let link = engine.link();
|
||||
let fits: Vec<Fit> = (0..4)
|
||||
.map(|k| Fit {
|
||||
flip: k % 2 == 1,
|
||||
count: k,
|
||||
sections: [Section {
|
||||
fc: 200. * (k + 1) as f32,
|
||||
q: 0.7,
|
||||
}; 4],
|
||||
})
|
||||
.collect();
|
||||
CHECK.with(|v| v.set(true));
|
||||
// Nothing takes blocks, so the queue fills up and later blocks are dropped.
|
||||
for i in 0..96000 {
|
||||
if i % 4800 == 0 {
|
||||
settings.output = ((i / 4800) % 5) as f32 - 2.;
|
||||
settings.listen = [Listen::Layer, Listen::Sum, Listen::SumDry][(i / 4800) % 3];
|
||||
engine.set_settings(settings).unwrap();
|
||||
link.push_fit(fits[(i / 4800) % 4]);
|
||||
}
|
||||
let t = i as f32 / 48000.;
|
||||
let x = (std::f32::consts::TAU * 55. * t).sin() * 0.5;
|
||||
std::hint::black_box(engine.process_sample([x, -x], [x * 0.5, x]));
|
||||
if i % 1600 == 0 {
|
||||
std::hint::black_box(engine.take_analyzer());
|
||||
}
|
||||
}
|
||||
engine.reset();
|
||||
CHECK.with(|v| v.set(false));
|
||||
assert_eq!(OPERATIONS.with(Cell::get), 0);
|
||||
assert!(link.dropped() > 0);
|
||||
}
|
||||
Generated
+2443
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,25 @@
|
||||
[package]
|
||||
name = "weld"
|
||||
version = "0.2.0"
|
||||
edition = "2021"
|
||||
license = "ISC"
|
||||
|
||||
[workspace]
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
|
||||
[dependencies]
|
||||
nih_plug = { git = "https://github.com/robbert-vdh/nih-plug.git", rev = "de421011f41a6d10fc8c7a6084e4f4dee0143683", default-features = false }
|
||||
nih_plug_egui = { git = "https://github.com/robbert-vdh/nih-plug.git", rev = "de421011f41a6d10fc8c7a6084e4f4dee0143683" }
|
||||
weld-core = { path = "../core" }
|
||||
weld-ui = { path = "../ui" }
|
||||
crossbeam-queue = "0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
clap-sys = { git = "https://github.com/micahrj/clap-sys.git", rev = "25d7f53fdb6363ad63fbd80049cb7a42a97ac156" }
|
||||
serde_json = "1"
|
||||
|
||||
[profile.release]
|
||||
lto = "thin"
|
||||
strip = "symbols"
|
||||
@@ -0,0 +1,214 @@
|
||||
//! CLAP audio effect with a sidechain input. The audio thread owns the engine; a worker
|
||||
//! thread, started in `initialize`, measures and fits.
|
||||
mod params;
|
||||
use crossbeam_queue::ArrayQueue;
|
||||
use nih_plug::prelude::*;
|
||||
use nih_plug_egui::{create_egui_editor, egui};
|
||||
use params::{WeldParams, GESTURES};
|
||||
use std::sync::Arc;
|
||||
use weld_core::{AnalyzerFrame, Engine, Report, Worker};
|
||||
|
||||
struct EditorData {
|
||||
ui: weld_ui::State,
|
||||
gestures: [bool; GESTURES],
|
||||
}
|
||||
pub struct Weld {
|
||||
params: Arc<WeldParams>,
|
||||
analyzer: Arc<ArrayQueue<AnalyzerFrame>>,
|
||||
reports: Arc<ArrayQueue<Report>>,
|
||||
engine: Option<Engine>,
|
||||
worker: Option<Worker>,
|
||||
publish_count: usize,
|
||||
publish_interval: usize,
|
||||
}
|
||||
impl Default for Weld {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
params: Arc::new(WeldParams::default()),
|
||||
analyzer: Arc::new(ArrayQueue::new(2)),
|
||||
reports: Arc::new(ArrayQueue::new(2)),
|
||||
engine: None,
|
||||
worker: None,
|
||||
publish_count: 0,
|
||||
publish_interval: 1600,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Plugin for Weld {
|
||||
const NAME: &'static str = "Weld";
|
||||
const VENDOR: &'static str = "Bass Foundry";
|
||||
const URL: &'static str = "";
|
||||
const EMAIL: &'static str = "";
|
||||
const VERSION: &'static str = env!("CARGO_PKG_VERSION");
|
||||
const AUDIO_IO_LAYOUTS: &'static [AudioIOLayout] = &[
|
||||
AudioIOLayout {
|
||||
main_input_channels: NonZeroU32::new(2),
|
||||
main_output_channels: NonZeroU32::new(2),
|
||||
aux_input_ports: &[new_nonzero_u32(2)],
|
||||
..AudioIOLayout::const_default()
|
||||
},
|
||||
AudioIOLayout {
|
||||
main_input_channels: NonZeroU32::new(1),
|
||||
main_output_channels: NonZeroU32::new(1),
|
||||
aux_input_ports: &[new_nonzero_u32(1)],
|
||||
..AudioIOLayout::const_default()
|
||||
},
|
||||
];
|
||||
const SAMPLE_ACCURATE_AUTOMATION: bool = false;
|
||||
type SysExMessage = ();
|
||||
type BackgroundTask = ();
|
||||
fn params(&self) -> Arc<dyn Params> {
|
||||
self.params.clone()
|
||||
}
|
||||
fn editor(&mut self, _: AsyncExecutor<Self>) -> Option<Box<dyn Editor>> {
|
||||
let params = self.params.clone();
|
||||
let analyzer = self.analyzer.clone();
|
||||
let reports = self.reports.clone();
|
||||
create_egui_editor(
|
||||
params.editor.clone(),
|
||||
EditorData {
|
||||
ui: weld_ui::State::default(),
|
||||
gestures: [false; GESTURES],
|
||||
},
|
||||
|ctx, _| weld_ui::style(ctx),
|
||||
move |ctx, setter, data| {
|
||||
while let Some(frame) = analyzer.pop() {
|
||||
data.ui.accept_frame(frame);
|
||||
}
|
||||
while let Some(report) = reports.pop() {
|
||||
data.ui.accept_report(report);
|
||||
}
|
||||
let before = params.settings();
|
||||
let mut edited = before;
|
||||
nih_plug_egui::resizable_window::ResizableWindow::new("weld-editor")
|
||||
.min_size(egui::vec2(
|
||||
weld_ui::WIDTH as f32 - 80.,
|
||||
weld_ui::HEIGHT as f32 - 40.,
|
||||
))
|
||||
.show(ctx, ¶ms.editor, |ui| {
|
||||
weld_ui::show(ui, &mut edited, &mut data.ui)
|
||||
});
|
||||
params.apply(
|
||||
setter,
|
||||
&before,
|
||||
&edited,
|
||||
data.ui.gesture_active,
|
||||
&mut data.gestures,
|
||||
);
|
||||
// Meters follow the audio.
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(40));
|
||||
},
|
||||
)
|
||||
}
|
||||
fn initialize(
|
||||
&mut self,
|
||||
layout: &AudioIOLayout,
|
||||
config: &BufferConfig,
|
||||
context: &mut impl InitContext<Self>,
|
||||
) -> bool {
|
||||
let Ok(mut engine) = Engine::new(
|
||||
config.sample_rate,
|
||||
layout.main_input_channels.map_or(0, |v| v.get() as usize),
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
if engine.set_settings(self.params.settings()).is_err() {
|
||||
return false;
|
||||
}
|
||||
// A restored project starts with its saved alignment, without a crossfade.
|
||||
let fit = self.params.stored_fit().sanitized(config.sample_rate);
|
||||
engine.set_fit(fit);
|
||||
if let Some(mut old) = self.worker.take() {
|
||||
old.stop();
|
||||
}
|
||||
let store = self.params.fit.clone();
|
||||
let Ok(worker) = Worker::spawn(
|
||||
engine.link(),
|
||||
config.sample_rate,
|
||||
fit,
|
||||
self.reports.clone(),
|
||||
move |fit| {
|
||||
if let Ok(mut stored) = store.write() {
|
||||
*stored = fit;
|
||||
}
|
||||
},
|
||||
) else {
|
||||
return false;
|
||||
};
|
||||
self.worker = Some(worker);
|
||||
context.set_latency_samples(engine.latency_samples());
|
||||
self.publish_interval = (config.sample_rate / 30.) as usize;
|
||||
self.engine = Some(engine);
|
||||
true
|
||||
}
|
||||
fn deactivate(&mut self) {
|
||||
if let Some(mut worker) = self.worker.take() {
|
||||
worker.stop();
|
||||
}
|
||||
}
|
||||
fn reset(&mut self) {
|
||||
if let Some(e) = self.engine.as_mut() {
|
||||
e.reset();
|
||||
}
|
||||
self.publish_count = 0;
|
||||
}
|
||||
fn process(
|
||||
&mut self,
|
||||
buffer: &mut Buffer,
|
||||
aux: &mut AuxiliaryBuffers,
|
||||
_: &mut impl ProcessContext<Self>,
|
||||
) -> ProcessStatus {
|
||||
let Some(engine) = self.engine.as_mut() else {
|
||||
return ProcessStatus::Normal;
|
||||
};
|
||||
let _ = engine.set_settings(self.params.settings());
|
||||
// A host that does not connect the sidechain still passes a buffer; treat a
|
||||
// missing one as silence.
|
||||
let side = aux.inputs.first().map(|b| b.as_slice_immutable());
|
||||
let stereo = engine.channels() == 2;
|
||||
for (index, mut sample) in buffer.iter_samples().enumerate() {
|
||||
let x = [
|
||||
*sample.get_mut(0).unwrap(),
|
||||
if stereo {
|
||||
*sample.get_mut(1).unwrap()
|
||||
} else {
|
||||
0.
|
||||
},
|
||||
];
|
||||
let mut s = [0f32; 2];
|
||||
if let Some(side) = side {
|
||||
for (c, value) in s.iter_mut().enumerate().take(side.len().min(2)) {
|
||||
*value = side[c].get(index).copied().unwrap_or(0.);
|
||||
}
|
||||
if !stereo && side.len() > 1 {
|
||||
s[0] = 0.5 * (s[0] + s[1]);
|
||||
}
|
||||
}
|
||||
let out = engine.process_sample(x, s);
|
||||
for (c, value) in sample.into_iter().enumerate() {
|
||||
*value = out[c];
|
||||
}
|
||||
self.publish_count += 1;
|
||||
if self.publish_count >= self.publish_interval {
|
||||
self.analyzer.force_push(engine.take_analyzer());
|
||||
self.publish_count = 0;
|
||||
}
|
||||
}
|
||||
ProcessStatus::Normal
|
||||
}
|
||||
}
|
||||
impl ClapPlugin for Weld {
|
||||
const CLAP_ID: &'static str = "io.narl.bass-foundry.weld";
|
||||
const CLAP_DESCRIPTION: Option<&'static str> = Some(
|
||||
"Align the phase of a bass layer to a sidechain layer so the two sum instead of cancel",
|
||||
);
|
||||
const CLAP_MANUAL_URL: Option<&'static str> = None;
|
||||
const CLAP_SUPPORT_URL: Option<&'static str> = None;
|
||||
const CLAP_FEATURES: &'static [ClapFeature] = &[
|
||||
ClapFeature::AudioEffect,
|
||||
ClapFeature::Utility,
|
||||
ClapFeature::Stereo,
|
||||
ClapFeature::Mono,
|
||||
];
|
||||
}
|
||||
nih_export_clap!(Weld);
|
||||
@@ -0,0 +1,227 @@
|
||||
use nih_plug::prelude::*;
|
||||
use nih_plug_egui::EguiState;
|
||||
use std::sync::{Arc, RwLock};
|
||||
use weld_core::{Fit, Listen, Mode, Settings, MAX_SECTIONS};
|
||||
|
||||
#[derive(Enum, Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub enum ModeParam {
|
||||
#[id = "follow"]
|
||||
Follow,
|
||||
#[id = "learn"]
|
||||
Learn,
|
||||
#[id = "hold"]
|
||||
Hold,
|
||||
}
|
||||
#[derive(Enum, Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub enum ListenParam {
|
||||
#[id = "layer"]
|
||||
Layer,
|
||||
#[id = "sum"]
|
||||
Sum,
|
||||
#[id = "sum-dry"]
|
||||
#[name = "Sum dry"]
|
||||
SumDry,
|
||||
}
|
||||
/// Continuous controls, in the order of the gesture slots.
|
||||
const FLOATS: usize = 5;
|
||||
|
||||
#[derive(Params)]
|
||||
pub struct WeldParams {
|
||||
#[persist = "editor"]
|
||||
pub editor: Arc<EguiState>,
|
||||
/// The applied alignment, so a project reopens with it.
|
||||
#[persist = "weld-fit"]
|
||||
pub fit: Arc<RwLock<Fit>>,
|
||||
#[id = "mode"]
|
||||
pub mode: EnumParam<ModeParam>,
|
||||
#[id = "response"]
|
||||
pub response: FloatParam,
|
||||
#[id = "low"]
|
||||
pub low: FloatParam,
|
||||
#[id = "high"]
|
||||
pub high: FloatParam,
|
||||
#[id = "sections"]
|
||||
pub sections: IntParam,
|
||||
#[id = "gate"]
|
||||
pub gate: FloatParam,
|
||||
#[id = "listen"]
|
||||
pub listen: EnumParam<ListenParam>,
|
||||
#[id = "output"]
|
||||
pub output: FloatParam,
|
||||
#[id = "bypass"]
|
||||
pub bypass: BoolParam,
|
||||
}
|
||||
fn hz(value: f32) -> String {
|
||||
if value >= 1000. {
|
||||
format!("{:.2} kHz", value / 1000.)
|
||||
} else {
|
||||
format!("{value:.0} Hz")
|
||||
}
|
||||
}
|
||||
impl Default for WeldParams {
|
||||
fn default() -> Self {
|
||||
let d = Settings::default();
|
||||
Self {
|
||||
editor: EguiState::from_size(weld_ui::WIDTH, weld_ui::HEIGHT),
|
||||
fit: Arc::new(RwLock::new(Fit::NONE)),
|
||||
mode: EnumParam::new("Mode", ModeParam::Follow),
|
||||
response: FloatParam::new(
|
||||
"Response",
|
||||
d.response,
|
||||
FloatRange::Skewed {
|
||||
min: 0.3,
|
||||
max: 5.,
|
||||
factor: FloatRange::skew_factor(-1.),
|
||||
},
|
||||
)
|
||||
.with_unit(" s")
|
||||
.with_value_to_string(Arc::new(|v| format!("{v:.2}"))),
|
||||
low: FloatParam::new(
|
||||
"Low",
|
||||
d.low,
|
||||
FloatRange::Skewed {
|
||||
min: 30.,
|
||||
max: 400.,
|
||||
factor: FloatRange::skew_factor(-1.5),
|
||||
},
|
||||
)
|
||||
.with_value_to_string(Arc::new(hz)),
|
||||
high: FloatParam::new(
|
||||
"High",
|
||||
d.high,
|
||||
FloatRange::Skewed {
|
||||
min: 1000.,
|
||||
max: 12000.,
|
||||
factor: FloatRange::skew_factor(-1.),
|
||||
},
|
||||
)
|
||||
.with_value_to_string(Arc::new(hz)),
|
||||
sections: IntParam::new(
|
||||
"Sections",
|
||||
d.sections as i32,
|
||||
IntRange::Linear {
|
||||
min: 1,
|
||||
max: MAX_SECTIONS as i32,
|
||||
},
|
||||
),
|
||||
gate: FloatParam::new(
|
||||
"Gate",
|
||||
d.gate,
|
||||
FloatRange::Linear {
|
||||
min: -70.,
|
||||
max: -30.,
|
||||
},
|
||||
)
|
||||
.with_unit(" dB"),
|
||||
listen: EnumParam::new("Listen", ListenParam::Layer),
|
||||
output: FloatParam::new(
|
||||
"Output",
|
||||
d.output,
|
||||
FloatRange::Linear {
|
||||
min: -12.,
|
||||
max: 12.,
|
||||
},
|
||||
)
|
||||
.with_unit(" dB"),
|
||||
bypass: BoolParam::new("Bypass", false).make_bypass(),
|
||||
}
|
||||
}
|
||||
}
|
||||
fn mode_param(mode: Mode) -> ModeParam {
|
||||
match mode {
|
||||
Mode::Follow => ModeParam::Follow,
|
||||
Mode::Learn => ModeParam::Learn,
|
||||
Mode::Hold => ModeParam::Hold,
|
||||
}
|
||||
}
|
||||
fn listen_param(listen: Listen) -> ListenParam {
|
||||
match listen {
|
||||
Listen::Layer => ListenParam::Layer,
|
||||
Listen::Sum => ListenParam::Sum,
|
||||
Listen::SumDry => ListenParam::SumDry,
|
||||
}
|
||||
}
|
||||
impl WeldParams {
|
||||
pub fn settings(&self) -> Settings {
|
||||
Settings {
|
||||
mode: match self.mode.value() {
|
||||
ModeParam::Follow => Mode::Follow,
|
||||
ModeParam::Learn => Mode::Learn,
|
||||
ModeParam::Hold => Mode::Hold,
|
||||
},
|
||||
response: self.response.value(),
|
||||
low: self.low.value(),
|
||||
high: self.high.value(),
|
||||
sections: self.sections.value().clamp(1, MAX_SECTIONS as i32) as usize,
|
||||
gate: self.gate.value(),
|
||||
listen: match self.listen.value() {
|
||||
ListenParam::Layer => Listen::Layer,
|
||||
ListenParam::Sum => Listen::Sum,
|
||||
ListenParam::SumDry => Listen::SumDry,
|
||||
},
|
||||
output: self.output.value(),
|
||||
bypass: self.bypass.value(),
|
||||
}
|
||||
}
|
||||
pub fn stored_fit(&self) -> Fit {
|
||||
self.fit.read().map(|f| *f).unwrap_or(Fit::NONE)
|
||||
}
|
||||
fn floats(&self) -> [&FloatParam; FLOATS] {
|
||||
[
|
||||
&self.response,
|
||||
&self.low,
|
||||
&self.high,
|
||||
&self.gate,
|
||||
&self.output,
|
||||
]
|
||||
}
|
||||
/// Pushes every changed editor value to the host. Continuous controls hold one gesture
|
||||
/// while the pointer is down; switches are set in a single gesture.
|
||||
pub fn apply(
|
||||
&self,
|
||||
setter: &ParamSetter,
|
||||
old: &Settings,
|
||||
new: &Settings,
|
||||
dragging: bool,
|
||||
open: &mut [bool; FLOATS],
|
||||
) {
|
||||
let values = [
|
||||
(old.response, new.response),
|
||||
(old.low, new.low),
|
||||
(old.high, new.high),
|
||||
(old.gate, new.gate),
|
||||
(old.output, new.output),
|
||||
];
|
||||
for (i, (p, (a, b))) in self.floats().into_iter().zip(values).enumerate() {
|
||||
if a != b {
|
||||
if !open[i] {
|
||||
open[i] = true;
|
||||
setter.begin_set_parameter(p);
|
||||
}
|
||||
setter.set_parameter(p, b);
|
||||
}
|
||||
if !dragging && open[i] {
|
||||
setter.end_set_parameter(p);
|
||||
open[i] = false;
|
||||
}
|
||||
}
|
||||
fn switch<P: Param>(setter: &ParamSetter, p: &P, v: P::Plain) {
|
||||
setter.begin_set_parameter(p);
|
||||
setter.set_parameter(p, v);
|
||||
setter.end_set_parameter(p);
|
||||
}
|
||||
if new.bypass != old.bypass {
|
||||
switch(setter, &self.bypass, new.bypass);
|
||||
}
|
||||
if new.mode != old.mode {
|
||||
switch(setter, &self.mode, mode_param(new.mode));
|
||||
}
|
||||
if new.listen != old.listen {
|
||||
switch(setter, &self.listen, listen_param(new.listen));
|
||||
}
|
||||
if new.sections != old.sections {
|
||||
switch(setter, &self.sections, new.sections as i32);
|
||||
}
|
||||
}
|
||||
}
|
||||
pub const GESTURES: usize = FLOATS;
|
||||
@@ -0,0 +1,243 @@
|
||||
//! Exercise the actual exported CLAP ABI without requiring a GUI or installed DAW.
|
||||
use clap_sys::{
|
||||
audio_buffer::*,
|
||||
events::*,
|
||||
ext::{audio_ports::*, latency::*, state::*},
|
||||
factory::plugin_factory::*,
|
||||
host::*,
|
||||
process::*,
|
||||
stream::*,
|
||||
version::*,
|
||||
};
|
||||
use std::{
|
||||
ffi::{c_char, c_void, CStr},
|
||||
io::{Cursor, Read},
|
||||
ptr,
|
||||
};
|
||||
|
||||
unsafe extern "C" fn extension(_: *const clap_host, _: *const c_char) -> *const c_void {
|
||||
ptr::null()
|
||||
}
|
||||
unsafe extern "C" fn request(_: *const clap_host) {}
|
||||
unsafe extern "C" fn count(_: *const clap_input_events) -> u32 {
|
||||
0
|
||||
}
|
||||
unsafe extern "C" fn event(_: *const clap_input_events, _: u32) -> *const clap_event_header {
|
||||
ptr::null()
|
||||
}
|
||||
unsafe extern "C" fn push(_: *const clap_output_events, _: *const clap_event_header) -> bool {
|
||||
true
|
||||
}
|
||||
unsafe extern "C" fn write(stream: *const clap_ostream, buffer: *const c_void, size: u64) -> i64 {
|
||||
// SAFETY: The test owns the Vec for the entire synchronous save call.
|
||||
let bytes = unsafe { &mut *((*stream).ctx as *mut Vec<u8>) };
|
||||
bytes.extend_from_slice(unsafe {
|
||||
std::slice::from_raw_parts(buffer as *const u8, size as usize)
|
||||
});
|
||||
size as i64
|
||||
}
|
||||
unsafe extern "C" fn read(stream: *const clap_istream, buffer: *mut c_void, size: u64) -> i64 {
|
||||
// SAFETY: The test owns the Cursor; the wrapper supplies writable stream storage.
|
||||
let cursor = unsafe { &mut *((*stream).ctx as *mut Cursor<Vec<u8>>) };
|
||||
cursor
|
||||
.read(unsafe { std::slice::from_raw_parts_mut(buffer as *mut u8, size as usize) })
|
||||
.unwrap() as i64
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sidechain_port_state_latency_and_audio_lifecycle() {
|
||||
// SAFETY: All callbacks, strings, streams, buffers, and the host outlive their
|
||||
// synchronous ABI calls. Activation/processing/destruction follow CLAP order.
|
||||
unsafe {
|
||||
let entry = &weld::clap_entry;
|
||||
assert!(entry.init.unwrap()(c"weld.clap".as_ptr()));
|
||||
let factory = entry.get_factory.unwrap()(CLAP_PLUGIN_FACTORY_ID.as_ptr())
|
||||
as *const clap_plugin_factory;
|
||||
assert!(!factory.is_null());
|
||||
let factory = &*factory;
|
||||
assert_eq!(factory.get_plugin_count.unwrap()(factory), 1);
|
||||
let descriptor = factory.get_plugin_descriptor.unwrap()(factory, 0);
|
||||
assert!(!descriptor.is_null());
|
||||
assert_eq!(CStr::from_ptr((*descriptor).name), c"Weld");
|
||||
assert_eq!(
|
||||
CStr::from_ptr((*descriptor).id),
|
||||
c"io.narl.bass-foundry.weld"
|
||||
);
|
||||
let host = clap_host {
|
||||
clap_version: CLAP_VERSION,
|
||||
host_data: ptr::null_mut(),
|
||||
name: c"Storyboard test host".as_ptr(),
|
||||
vendor: c"Tests".as_ptr(),
|
||||
url: c"".as_ptr(),
|
||||
version: c"1.0".as_ptr(),
|
||||
get_extension: Some(extension),
|
||||
request_restart: Some(request),
|
||||
request_process: Some(request),
|
||||
request_callback: Some(request),
|
||||
};
|
||||
let plugin = factory.create_plugin.unwrap()(factory, &host, (*descriptor).id);
|
||||
assert!(!plugin.is_null());
|
||||
let p = &*plugin;
|
||||
assert!(p.init.unwrap()(plugin));
|
||||
let ports = p.get_extension.unwrap()(plugin, CLAP_EXT_AUDIO_PORTS.as_ptr())
|
||||
as *const clap_plugin_audio_ports;
|
||||
assert!(!ports.is_null());
|
||||
// Main input plus the sidechain input; one output.
|
||||
assert_eq!((*ports).count.unwrap()(plugin, true), 2);
|
||||
assert_eq!((*ports).count.unwrap()(plugin, false), 1);
|
||||
let mut info: clap_audio_port_info = std::mem::zeroed();
|
||||
assert!((*ports).get.unwrap()(plugin, 1, true, &mut info));
|
||||
assert_eq!(info.channel_count, 2);
|
||||
assert_eq!(info.flags & CLAP_AUDIO_PORT_IS_MAIN, 0);
|
||||
let latency = p.get_extension.unwrap()(plugin, CLAP_EXT_LATENCY.as_ptr())
|
||||
as *const clap_plugin_latency;
|
||||
assert!(!latency.is_null());
|
||||
let state =
|
||||
p.get_extension.unwrap()(plugin, CLAP_EXT_STATE.as_ptr()) as *const clap_plugin_state;
|
||||
assert!(!state.is_null());
|
||||
let state = &*state;
|
||||
let save = || {
|
||||
let mut bytes = Vec::new();
|
||||
let stream = clap_ostream {
|
||||
ctx: &mut bytes as *mut Vec<u8> as *mut c_void,
|
||||
write: Some(write),
|
||||
};
|
||||
assert!(state.save.unwrap()(plugin, &stream));
|
||||
bytes
|
||||
};
|
||||
let mut envelope: nih_plug::prelude::PluginState =
|
||||
serde_json::from_slice(&save()[8..]).unwrap();
|
||||
use nih_plug::wrapper::state::ParamValue;
|
||||
envelope
|
||||
.params
|
||||
.insert("listen".into(), ParamValue::String("sum".into()));
|
||||
envelope
|
||||
.params
|
||||
.insert("mode".into(), ParamValue::String("hold".into()));
|
||||
envelope
|
||||
.params
|
||||
.insert("sections".into(), ParamValue::I32(2));
|
||||
// A saved alignment that flips polarity.
|
||||
let flipped = weld_core::Fit {
|
||||
flip: true,
|
||||
..weld_core::Fit::NONE
|
||||
};
|
||||
envelope
|
||||
.fields
|
||||
.insert("weld-fit".into(), serde_json::to_string(&flipped).unwrap());
|
||||
let encoded = serde_json::to_vec(&envelope).unwrap();
|
||||
let mut framed = (encoded.len() as u64).to_le_bytes().to_vec();
|
||||
framed.extend_from_slice(&encoded);
|
||||
let mut bytes = Cursor::new(framed);
|
||||
let stream = clap_istream {
|
||||
ctx: &mut bytes as *mut Cursor<Vec<u8>> as *mut c_void,
|
||||
read: Some(read),
|
||||
};
|
||||
assert!(state.load.unwrap()(plugin, &stream));
|
||||
let restored: nih_plug::prelude::PluginState =
|
||||
serde_json::from_slice(&save()[8..]).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::to_value(&restored.params).unwrap(),
|
||||
serde_json::to_value(&envelope.params).unwrap()
|
||||
);
|
||||
let saved: weld_core::Fit = serde_json::from_str(&restored.fields["weld-fit"]).unwrap();
|
||||
assert_eq!(saved, flipped);
|
||||
// Listen = Sum with the restored flip: a sidechain equal to the main input cancels
|
||||
// it from the first sample on. A silent sidechain leaves the level alone. CLAP hosts
|
||||
// pass every port, so the test always passes both (nih_plug reads one port past a
|
||||
// short count).
|
||||
for (rate, with_side, expected_db) in [
|
||||
(44100., true, None),
|
||||
(48000., false, Some(0.)),
|
||||
(96000., true, None),
|
||||
] {
|
||||
assert!(p.activate.unwrap()(plugin, rate, 1, 512));
|
||||
assert_eq!((*latency).get.unwrap()(plugin), 0);
|
||||
assert!(p.start_processing.unwrap()(plugin));
|
||||
let total = 9600;
|
||||
let mut position = 0;
|
||||
let (mut energy_in, mut energy_out) = (0f64, 0f64);
|
||||
while position < total {
|
||||
let frames = [1, 127, 512, 31][position % 4].min(total - position);
|
||||
let tone = |n: usize| {
|
||||
0.25 * (std::f64::consts::TAU * 1000. * n as f64 / rate).sin() as f32
|
||||
};
|
||||
let mut input_left = [0f32; 512];
|
||||
let mut input_right = [0f32; 512];
|
||||
for i in 0..frames {
|
||||
input_left[i] = tone(position + i);
|
||||
input_right[i] = -tone(position + i);
|
||||
}
|
||||
let (mut side_left, mut side_right) = if with_side {
|
||||
(input_left, input_right)
|
||||
} else {
|
||||
([0f32; 512], [0f32; 512])
|
||||
};
|
||||
let mut left = [0f32; 512];
|
||||
let mut right = [0f32; 512];
|
||||
let mut in_channels = [input_left.as_mut_ptr(), input_right.as_mut_ptr()];
|
||||
let mut side_channels = [side_left.as_mut_ptr(), side_right.as_mut_ptr()];
|
||||
let mut out_channels = [left.as_mut_ptr(), right.as_mut_ptr()];
|
||||
let incoming = [
|
||||
clap_audio_buffer {
|
||||
data32: in_channels.as_mut_ptr(),
|
||||
data64: ptr::null_mut(),
|
||||
channel_count: 2,
|
||||
latency: 0,
|
||||
constant_mask: 0,
|
||||
},
|
||||
clap_audio_buffer {
|
||||
data32: side_channels.as_mut_ptr(),
|
||||
data64: ptr::null_mut(),
|
||||
channel_count: 2,
|
||||
latency: 0,
|
||||
constant_mask: 0,
|
||||
},
|
||||
];
|
||||
let mut outgoing_audio = clap_audio_buffer {
|
||||
data32: out_channels.as_mut_ptr(),
|
||||
data64: ptr::null_mut(),
|
||||
channel_count: 2,
|
||||
latency: 0,
|
||||
constant_mask: 0,
|
||||
};
|
||||
let input = clap_input_events {
|
||||
ctx: ptr::null_mut(),
|
||||
size: Some(count),
|
||||
get: Some(event),
|
||||
};
|
||||
let outgoing = clap_output_events {
|
||||
ctx: ptr::null_mut(),
|
||||
try_push: Some(push),
|
||||
};
|
||||
let process = clap_process {
|
||||
steady_time: position as i64,
|
||||
frames_count: frames as u32,
|
||||
transport: ptr::null(),
|
||||
audio_inputs: incoming.as_ptr(),
|
||||
audio_outputs: &mut outgoing_audio,
|
||||
audio_inputs_count: 2,
|
||||
audio_outputs_count: 1,
|
||||
in_events: &input,
|
||||
out_events: &outgoing,
|
||||
};
|
||||
assert_ne!(p.process.unwrap()(plugin, &process), CLAP_PROCESS_ERROR);
|
||||
for i in 0..frames {
|
||||
let n = position + i;
|
||||
energy_in += 2. * (tone(n) as f64).powi(2);
|
||||
energy_out += (left[i] as f64).powi(2) + (right[i] as f64).powi(2);
|
||||
}
|
||||
position += frames;
|
||||
}
|
||||
let ratio_db = 10. * (energy_out / energy_in).log10();
|
||||
match expected_db {
|
||||
Some(db) => assert!((ratio_db - db).abs() < 0.2, "{rate} {with_side} {ratio_db}"),
|
||||
None => assert!(ratio_db < -60., "{rate} {with_side} {ratio_db}"),
|
||||
}
|
||||
p.stop_processing.unwrap()(plugin);
|
||||
p.deactivate.unwrap()(plugin);
|
||||
}
|
||||
p.destroy.unwrap()(plugin);
|
||||
entry.deinit.unwrap()();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
[package]
|
||||
|
||||
name = "weld-ui"
|
||||
version = "0.1.0"
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
|
||||
[dependencies]
|
||||
|
||||
egui = "0.31.1"
|
||||
weld-core = { path = "../core" }
|
||||
common-ui = { path = "../../common/ui" }
|
||||
@@ -0,0 +1,538 @@
|
||||
//! Weld editor, shared by the CLAP wrapper and the headless renderer.
|
||||
use common_ui::*;
|
||||
use egui::{self, Color32, FontId, Pos2, Rect, RichText, Sense, Stroke, Vec2};
|
||||
use weld_core::{
|
||||
band_edge, curve_frequency, AnalyzerFrame, Listen, Mode, Report, Settings, Status, CURVE,
|
||||
DISPLAY_HIGH, DISPLAY_LOW, MAX_SECTIONS,
|
||||
};
|
||||
|
||||
pub use common_ui::style;
|
||||
pub const WIDTH: u32 = 1040;
|
||||
pub const HEIGHT: u32 = 650;
|
||||
|
||||
const GRID: Color32 = Color32::from_rgb(24, 26, 30);
|
||||
const LOSS: Color32 = Color32::from_rgb(170, 40, 52);
|
||||
const LOSS_FLOOR: f32 = -24.;
|
||||
const TOP: f32 = 318.;
|
||||
|
||||
pub struct State {
|
||||
pub analyzer: AnalyzerFrame,
|
||||
pub report: Report,
|
||||
/// True while a pointer button is held, so knob drags become one host gesture.
|
||||
pub gesture_active: bool,
|
||||
pub help: String,
|
||||
}
|
||||
impl Default for State {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
analyzer: AnalyzerFrame::default(),
|
||||
report: Report::default(),
|
||||
gesture_active: false,
|
||||
help: DEFAULT_HELP.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
const DEFAULT_HELP: &str =
|
||||
"Put Weld on one bass layer and send the other layer to its sidechain input.";
|
||||
impl State {
|
||||
pub fn accept_frame(&mut self, frame: AnalyzerFrame) {
|
||||
let old = self.analyzer;
|
||||
self.analyzer = frame;
|
||||
// Meters fall smoothly between frames.
|
||||
self.analyzer.main_db = frame.main_db.max(old.main_db - 3.);
|
||||
self.analyzer.side_db = frame.side_db.max(old.side_db - 3.);
|
||||
self.analyzer.side_peak_db = frame.side_peak_db.max(old.side_peak_db - 3.);
|
||||
}
|
||||
pub fn accept_report(&mut self, report: Report) {
|
||||
self.report = report;
|
||||
}
|
||||
}
|
||||
fn hint(r: &egui::Response, state: &mut State, text: &str) {
|
||||
if r.hovered() || r.has_focus() {
|
||||
state.help = text.into();
|
||||
}
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn knob(
|
||||
ui: &mut egui::Ui,
|
||||
state: &mut State,
|
||||
name: &str,
|
||||
value: &mut f32,
|
||||
range: std::ops::RangeInclusive<f32>,
|
||||
default: f32,
|
||||
unit: &str,
|
||||
help: &str,
|
||||
) {
|
||||
ui.vertical_centered(|ui| {
|
||||
let r = rotary(ui, name, value, range, default, unit, 58., ACCENT);
|
||||
hint(&r, state, help);
|
||||
});
|
||||
}
|
||||
fn big(text: impl Into<String>, size: f32, color: Color32) -> RichText {
|
||||
RichText::new(text)
|
||||
.font(FontId::new(size, egui::FontFamily::Name("medium".into())))
|
||||
.color(color)
|
||||
}
|
||||
fn hz(f: f32) -> String {
|
||||
if f >= 1000. {
|
||||
format!("{:.1} kHz", f / 1000.)
|
||||
} else {
|
||||
format!("{f:.0} Hz")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn show(ui: &mut egui::Ui, settings: &mut Settings, state: &mut State) {
|
||||
backdrop(ui);
|
||||
state.help = DEFAULT_HELP.into();
|
||||
state.gesture_active = ui.input(|i| i.pointer.any_down());
|
||||
ui.add_space(2.);
|
||||
header(ui, "WELD", "LAYER ALIGN", |ui| {
|
||||
let r = ui
|
||||
.selectable_label(settings.bypass, RichText::new("BYPASS").size(13.))
|
||||
.on_hover_text("Pass the main layer through unchanged.");
|
||||
if r.clicked() {
|
||||
settings.bypass = !settings.bypass;
|
||||
}
|
||||
ui.separator();
|
||||
for (listen, label, help) in [
|
||||
(Listen::SumDry, "SUM DRY", "Output this layer unprocessed plus the sidechain layer, to compare with SUM."),
|
||||
(Listen::Sum, "SUM", "Output this layer aligned plus the sidechain layer. Mute the other layer's own send while you listen."),
|
||||
(Listen::Layer, "LAYER", "Output this layer only, aligned. Use this in the mix."),
|
||||
] {
|
||||
let r = ui.selectable_label(settings.listen == listen, RichText::new(label).size(13.));
|
||||
if r.clicked() {
|
||||
settings.listen = listen;
|
||||
}
|
||||
hint(&r, state, help);
|
||||
}
|
||||
caption(ui, "LISTEN");
|
||||
});
|
||||
ui.add_space(6.);
|
||||
ui.horizontal_top(|ui| {
|
||||
panel(ui, |ui| {
|
||||
ui.set_width(250.);
|
||||
ui.set_min_height(TOP);
|
||||
ui.vertical(|ui| summary(ui, settings, state));
|
||||
});
|
||||
ui.add_space(4.);
|
||||
panel(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.vertical(|ui| {
|
||||
let report = state.report;
|
||||
band_plot(ui, &report, 190.);
|
||||
ui.add_space(4.);
|
||||
phase_plot(ui, &report, TOP - 194.);
|
||||
});
|
||||
});
|
||||
});
|
||||
ui.add_space(6.);
|
||||
panel(ui, |ui| {
|
||||
ui.set_width(ui.available_width());
|
||||
ui.vertical(|ui| controls(ui, settings, state));
|
||||
});
|
||||
ui.separator();
|
||||
ui.label(RichText::new(&state.help).color(MUTED));
|
||||
}
|
||||
|
||||
fn status_text(report: &Report, frame: &AnalyzerFrame, mode: Mode) -> (String, Color32) {
|
||||
if !frame.side_seen && frame.side_db < -90. {
|
||||
return (
|
||||
"No sidechain signal. Route the other layer to Weld's sidechain input.".into(),
|
||||
DIM,
|
||||
);
|
||||
}
|
||||
match report.status {
|
||||
Status::NoSidechain => ("The sidechain is silent.".into(), MUTED),
|
||||
Status::Waiting => ("Listening…".into(), MUTED),
|
||||
Status::Quiet => ("One layer is under the gate.".into(), MUTED),
|
||||
Status::Loose => (
|
||||
"Layers unrelated: free-running oscillators or different notes. Enable retrigger.".into(),
|
||||
FOCUS,
|
||||
),
|
||||
Status::Late => (
|
||||
format!(
|
||||
"This layer is {:.2} ms late. Weld cannot move it earlier: put Weld on the other layer.",
|
||||
report.lag_ms
|
||||
),
|
||||
ACCENT,
|
||||
),
|
||||
Status::Aligned => match mode {
|
||||
Mode::Follow => ("Following.".into(), STEEL),
|
||||
Mode::Learn => (format!("Learning… {} frames", report.frames), ACCENT),
|
||||
Mode::Hold => ("Holding the alignment.".into(), STEEL),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn summary(ui: &mut egui::Ui, settings: &Settings, state: &mut State) {
|
||||
let report = state.report;
|
||||
let frame = state.analyzer;
|
||||
caption(ui, "RECOVERED");
|
||||
let measured = matches!(
|
||||
report.status,
|
||||
Status::Aligned | Status::Late | Status::Loose
|
||||
);
|
||||
ui.label(big(
|
||||
if measured {
|
||||
format!("{:+.1} dB", report.recovered_db)
|
||||
} else {
|
||||
"—".into()
|
||||
},
|
||||
44.,
|
||||
if measured { TEXT } else { DIM },
|
||||
));
|
||||
ui.label(
|
||||
RichText::new(if measured {
|
||||
format!(
|
||||
"Cancellation cost {:.1} dB, {}–{}",
|
||||
report.cost_db,
|
||||
hz(report.low),
|
||||
hz(report.high)
|
||||
)
|
||||
} else {
|
||||
"Average per band, between Low and High".into()
|
||||
})
|
||||
.size(12.)
|
||||
.color(MUTED),
|
||||
);
|
||||
ui.add_space(10.);
|
||||
caption(ui, "ALIGNMENT");
|
||||
let fit = report.fit;
|
||||
ui.label(
|
||||
RichText::new(if fit.flip {
|
||||
"Polarity flipped"
|
||||
} else {
|
||||
"Polarity normal"
|
||||
})
|
||||
.size(14.)
|
||||
.color(if fit.flip { ACCENT } else { STEEL }),
|
||||
);
|
||||
if fit.count == 0 {
|
||||
ui.label(RichText::new("No allpass sections").size(13.).color(MUTED));
|
||||
}
|
||||
for s in fit.active() {
|
||||
ui.label(
|
||||
RichText::new(format!("{:>9} Q {:.2}", hz(s.fc), s.q))
|
||||
.monospace()
|
||||
.size(13.)
|
||||
.color(STEEL),
|
||||
);
|
||||
}
|
||||
ui.add_space(10.);
|
||||
let (text, color) = status_text(&report, &frame, settings.mode);
|
||||
ui.label(RichText::new(text).size(13.).color(color));
|
||||
ui.add_space(10.);
|
||||
meter(ui, "MAIN", frame.main_db, STEEL, 150.);
|
||||
meter(ui, "SIDECHAIN", frame.side_db, ACCENT, 150.);
|
||||
if frame.dropped > 0 {
|
||||
ui.label(
|
||||
RichText::new(format!("{} blocks skipped (CPU busy)", frame.dropped))
|
||||
.size(11.)
|
||||
.color(DIM),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn freq_x(rect: Rect, f: f32) -> f32 {
|
||||
let t = (f / DISPLAY_LOW).ln() / (DISPLAY_HIGH / DISPLAY_LOW).ln();
|
||||
rect.left() + rect.width() * t.clamp(0., 1.)
|
||||
}
|
||||
fn frequency_grid(p: &egui::Painter, plot: Rect, labels: bool) {
|
||||
for f in [50f32, 100., 200., 500., 1000., 2000., 5000., 10000.] {
|
||||
let x = freq_x(plot, f);
|
||||
p.line_segment(
|
||||
[Pos2::new(x, plot.top()), Pos2::new(x, plot.bottom())],
|
||||
Stroke::new(1.0_f32, GRID),
|
||||
);
|
||||
if labels {
|
||||
p.text(
|
||||
Pos2::new(x, plot.bottom() + 3.),
|
||||
egui::Align2::CENTER_TOP,
|
||||
if f >= 1000. {
|
||||
format!("{}k", f / 1000.)
|
||||
} else {
|
||||
format!("{f}")
|
||||
},
|
||||
FontId::proportional(10.),
|
||||
DIM,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
fn fit_range(p: &egui::Painter, plot: Rect, report: &Report) {
|
||||
let (a, b) = (freq_x(plot, report.low), freq_x(plot, report.high));
|
||||
p.rect_filled(
|
||||
Rect::from_min_max(Pos2::new(a, plot.top()), Pos2::new(b, plot.bottom())),
|
||||
0.,
|
||||
Color32::from_rgba_unmultiplied(255, 255, 255, 5),
|
||||
);
|
||||
}
|
||||
|
||||
/// Per band: what the unprocessed sum loses against a perfect alignment (red), and the
|
||||
/// part of it Weld wins back (accent).
|
||||
fn band_plot(ui: &mut egui::Ui, report: &Report, height: f32) {
|
||||
let (outer, _) =
|
||||
ui.allocate_exact_size(Vec2::new(ui.available_width(), height), Sense::hover());
|
||||
let p = ui.painter_at(outer);
|
||||
p.rect_filled(outer, 2., SCREEN);
|
||||
let plot = Rect::from_min_max(
|
||||
outer.left_top() + Vec2::new(34., 22.),
|
||||
outer.right_bottom() - Vec2::new(10., 16.),
|
||||
);
|
||||
p.text(
|
||||
outer.left_top() + Vec2::new(8., 5.),
|
||||
egui::Align2::LEFT_TOP,
|
||||
"SUM LEVEL AGAINST A PERFECT ALIGNMENT",
|
||||
FontId::proportional(10.),
|
||||
MUTED,
|
||||
);
|
||||
let legend = [(LOSS, "lost to cancellation"), (ACCENT, "won back by Weld")];
|
||||
let mut x = outer.right() - 10.;
|
||||
for (color, label) in legend.iter().rev() {
|
||||
let galley = p.layout_no_wrap(label.to_string(), FontId::proportional(10.), MUTED);
|
||||
x -= galley.size().x;
|
||||
p.galley(Pos2::new(x, outer.top() + 5.), galley, MUTED);
|
||||
x -= 14.;
|
||||
p.rect_filled(
|
||||
Rect::from_min_size(Pos2::new(x, outer.top() + 7.), Vec2::splat(8.)),
|
||||
1.,
|
||||
*color,
|
||||
);
|
||||
x -= 14.;
|
||||
}
|
||||
fit_range(&p, plot, report);
|
||||
let y = |db: f32| plot.top() + plot.height() * (db / LOSS_FLOOR).clamp(0., 1.);
|
||||
for db in [0., -6., -12., -18., -24.] {
|
||||
let yy = y(db);
|
||||
p.line_segment(
|
||||
[Pos2::new(plot.left(), yy), Pos2::new(plot.right(), yy)],
|
||||
Stroke::new(1.0_f32, if db == 0. { EDGE } else { GRID }),
|
||||
);
|
||||
p.text(
|
||||
Pos2::new(outer.left() + 6., yy),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
if db == 0. {
|
||||
"0".into()
|
||||
} else {
|
||||
format!("{db:.0}")
|
||||
},
|
||||
FontId::proportional(10.),
|
||||
if db == 0. { MUTED } else { DIM },
|
||||
);
|
||||
}
|
||||
frequency_grid(&p, plot, true);
|
||||
for (i, band) in report.bands.iter().enumerate() {
|
||||
if !band.valid {
|
||||
continue;
|
||||
}
|
||||
let (a, b) = (
|
||||
freq_x(plot, band_edge(i)) + 2.,
|
||||
freq_x(plot, band_edge(i + 1)) - 2.,
|
||||
);
|
||||
let top = y(0.);
|
||||
let before = y(band.before);
|
||||
let after = y(band.after.max(band.before));
|
||||
let loose = band.coherence < 0.3;
|
||||
// The whole loss in red, then the recovered part over it in accent.
|
||||
p.rect_filled(
|
||||
Rect::from_min_max(Pos2::new(a, top), Pos2::new(b, before.max(top + 1.))),
|
||||
1.,
|
||||
if loose {
|
||||
LOSS.gamma_multiply(0.35)
|
||||
} else {
|
||||
LOSS
|
||||
},
|
||||
);
|
||||
if after > top + 0.5 {
|
||||
p.rect_filled(
|
||||
Rect::from_min_max(Pos2::new(a, after), Pos2::new(b, before)),
|
||||
0.,
|
||||
if loose {
|
||||
ACCENT.gamma_multiply(0.35)
|
||||
} else {
|
||||
ACCENT
|
||||
},
|
||||
);
|
||||
} else if before > top + 0.5 {
|
||||
p.rect_filled(
|
||||
Rect::from_min_max(Pos2::new(a, top), Pos2::new(b, before)),
|
||||
1.,
|
||||
if loose {
|
||||
ACCENT.gamma_multiply(0.35)
|
||||
} else {
|
||||
ACCENT
|
||||
},
|
||||
);
|
||||
}
|
||||
p.line_segment(
|
||||
[Pos2::new(a, after), Pos2::new(b, after)],
|
||||
Stroke::new(1.5_f32, TEXT),
|
||||
);
|
||||
if loose {
|
||||
// Hatching marks bands where the layers do not hold a stable phase.
|
||||
let mut x = a;
|
||||
while x < b {
|
||||
p.line_segment(
|
||||
[
|
||||
Pos2::new(x, plot.bottom()),
|
||||
Pos2::new((x + 8.).min(b), plot.bottom() - 8.),
|
||||
],
|
||||
Stroke::new(1.0_f32, DIM),
|
||||
);
|
||||
x += 5.;
|
||||
}
|
||||
p.text(
|
||||
Pos2::new((a + b) / 2., plot.bottom() - 12.),
|
||||
egui::Align2::CENTER_BOTTOM,
|
||||
"loose",
|
||||
FontId::proportional(10.),
|
||||
DIM,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Phase of this layer against the sidechain layer, before and after, plus the chain's own
|
||||
/// phase.
|
||||
fn phase_plot(ui: &mut egui::Ui, report: &Report, height: f32) {
|
||||
let (outer, _) =
|
||||
ui.allocate_exact_size(Vec2::new(ui.available_width(), height), Sense::hover());
|
||||
let p = ui.painter_at(outer);
|
||||
p.rect_filled(outer, 2., SCREEN);
|
||||
let plot = Rect::from_min_max(
|
||||
outer.left_top() + Vec2::new(34., 20.),
|
||||
outer.right_bottom() - Vec2::new(10., 6.),
|
||||
);
|
||||
p.text(
|
||||
outer.left_top() + Vec2::new(8., 4.),
|
||||
egui::Align2::LEFT_TOP,
|
||||
"PHASE AGAINST THE SIDECHAIN LAYER",
|
||||
FontId::proportional(10.),
|
||||
MUTED,
|
||||
);
|
||||
let legend = [(DIM, "before"), (ACCENT, "after"), (FOCUS, "Weld's chain")];
|
||||
let mut x = outer.right() - 10.;
|
||||
for (color, label) in legend.iter().rev() {
|
||||
let galley = p.layout_no_wrap(label.to_string(), FontId::proportional(10.), MUTED);
|
||||
x -= galley.size().x;
|
||||
p.galley(Pos2::new(x, outer.top() + 4.), galley, MUTED);
|
||||
x -= 16.;
|
||||
p.line_segment(
|
||||
[
|
||||
Pos2::new(x, outer.top() + 10.),
|
||||
Pos2::new(x + 10., outer.top() + 10.),
|
||||
],
|
||||
Stroke::new(2.0_f32, *color),
|
||||
);
|
||||
x -= 12.;
|
||||
}
|
||||
fit_range(&p, plot, report);
|
||||
let y = |deg: f32| plot.center().y - plot.height() / 2. * (deg / 180.).clamp(-1., 1.);
|
||||
for deg in [-180f32, -90., 0., 90., 180.] {
|
||||
let yy = y(deg);
|
||||
p.line_segment(
|
||||
[Pos2::new(plot.left(), yy), Pos2::new(plot.right(), yy)],
|
||||
Stroke::new(1.0_f32, if deg == 0. { EDGE } else { GRID }),
|
||||
);
|
||||
if deg.abs() < 180. {
|
||||
p.text(
|
||||
Pos2::new(outer.left() + 6., yy),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
format!("{deg:.0}°"),
|
||||
FontId::proportional(10.),
|
||||
if deg == 0. { MUTED } else { DIM },
|
||||
);
|
||||
}
|
||||
}
|
||||
frequency_grid(&p, plot, false);
|
||||
let curve = |pick: fn(&weld_core::CurvePoint) -> f32,
|
||||
color: Color32,
|
||||
width: f32,
|
||||
fade: bool| {
|
||||
let mut previous: Option<(Pos2, f32)> = None;
|
||||
for i in 0..CURVE {
|
||||
let c = report.curve[i];
|
||||
if !c.valid {
|
||||
previous = None;
|
||||
continue;
|
||||
}
|
||||
let v = pick(&c);
|
||||
let pos = Pos2::new(freq_x(plot, curve_frequency(i)), y(v));
|
||||
if let Some((last, last_v)) = previous {
|
||||
// Do not draw the jump where the phase wraps.
|
||||
if (v - last_v).abs() < 180. {
|
||||
let alpha = if fade { 0.25 + 0.75 * c.coherence } else { 1. };
|
||||
p.line_segment([last, pos], Stroke::new(width, color.gamma_multiply(alpha)));
|
||||
}
|
||||
}
|
||||
previous = Some((pos, v));
|
||||
}
|
||||
};
|
||||
curve(|c| c.chain, FOCUS, 1.5, false);
|
||||
curve(|c| c.before, MUTED, 1.5, true);
|
||||
curve(|c| c.after, ACCENT, 2., true);
|
||||
}
|
||||
|
||||
fn controls(ui: &mut egui::Ui, settings: &mut Settings, state: &mut State) {
|
||||
let d = Settings::default();
|
||||
ui.horizontal(|ui| {
|
||||
caption(ui, "MODE");
|
||||
for (mode, label, help) in [
|
||||
(Mode::Follow, "FOLLOW", "Keep measuring and refit when a clearly better alignment shows up."),
|
||||
(Mode::Learn, "LEARN", "Measure from now with equal weight, for example over one drop. Switch to HOLD to keep the result."),
|
||||
(Mode::Hold, "HOLD", "Keep the current alignment. The display keeps measuring. The alignment is saved with the project."),
|
||||
] {
|
||||
let r = ui.selectable_label(settings.mode == mode, RichText::new(label).size(14.));
|
||||
if r.clicked() {
|
||||
settings.mode = if mode == Mode::Learn && settings.mode == Mode::Learn {
|
||||
Mode::Hold
|
||||
} else {
|
||||
mode
|
||||
};
|
||||
}
|
||||
hint(&r, state, help);
|
||||
}
|
||||
ui.add_space(30.);
|
||||
caption(ui, "SECTIONS");
|
||||
let minus = ui.button(RichText::new("−").size(14.));
|
||||
if minus.clicked() && settings.sections > 1 {
|
||||
settings.sections -= 1;
|
||||
}
|
||||
ui.label(RichText::new(format!("{}", settings.sections)).monospace().size(14.).color(TEXT));
|
||||
let plus = ui.button(RichText::new("+").size(14.));
|
||||
if plus.clicked() && settings.sections < MAX_SECTIONS {
|
||||
settings.sections += 1;
|
||||
}
|
||||
let help = "Most allpass sections the fit may use. Fewer is gentler; Weld uses fewer when they are enough.";
|
||||
hint(&minus, state, help);
|
||||
hint(&plus, state, help);
|
||||
});
|
||||
ui.add_space(4.);
|
||||
ui.columns(6, |c| {
|
||||
knob(&mut c[0], state, "Response", &mut settings.response, 0.3..=5., d.response, " s",
|
||||
"Averaging time in FOLLOW. Longer is steadier; shorter follows switch-ups faster.");
|
||||
knob(&mut c[1], state, "Low", &mut settings.low, 30. ..=400., d.low, " Hz",
|
||||
"Lowest frequency the fit listens to. Leave the sub to Anvil.");
|
||||
knob(&mut c[2], state, "High", &mut settings.high, 1000. ..=12000., d.high, " Hz",
|
||||
"Highest frequency the fit listens to.");
|
||||
knob(&mut c[3], state, "Gate", &mut settings.gate, -70. ..=-30., d.gate, " dB",
|
||||
"Moments where either layer is quieter than this are not measured.");
|
||||
knob(&mut c[4], state, "Output", &mut settings.output, -12. ..=12., d.output, " dB",
|
||||
"Output trim.");
|
||||
let report = state.report;
|
||||
c[5].vertical(|ui| {
|
||||
caption(ui, "TIME OFFSET");
|
||||
let clear = report.lag_strength > 0.3;
|
||||
ui.label(big(
|
||||
if clear { format!("{:+.2} ms", report.lag_ms) } else { "—".into() },
|
||||
22.,
|
||||
if clear { TEXT } else { DIM },
|
||||
));
|
||||
ui.label(
|
||||
RichText::new("Positive: this layer is late. Weld can only delay it, so a late layer needs Weld on the other one.")
|
||||
.size(11.)
|
||||
.color(DIM),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -15,6 +15,8 @@ commands = [
|
||||
["cargo", "test", *packages, "--locked"],
|
||||
["cargo", "clippy", *packages, "--all-targets", "--locked", "--", "-D", "warnings"],
|
||||
["cargo", "fmt", "--manifest-path", product["manifest"], "--", "--check"],
|
||||
# Every product has a fixture in the editor renderer; CI checks its formatting too.
|
||||
["cargo", "fmt", "--manifest-path", "tools/editor-check/Cargo.toml", "--", "--check"],
|
||||
["cargo", "test", "--manifest-path", product["manifest"], "--locked"],
|
||||
["cargo", "clippy", "--manifest-path", product["manifest"], "--all-targets", "--locked", "--", "-D", "warnings"],
|
||||
]
|
||||
|
||||
@@ -39,7 +39,7 @@ def package(target="x86_64-pc-windows-gnu", plugin=None, root=ROOT):
|
||||
f"See [{product['name']} guide]({product['documentation']}/README.md).\n"
|
||||
).encode()
|
||||
else:
|
||||
filename = "rivet-patina-windows-x86_64.zip"
|
||||
filename = "bass-foundry-windows-x86_64.zip"
|
||||
payload["README.md"] = (folder / "README.md").read_bytes()
|
||||
checksums = "".join(f"{hashlib.sha256(data).hexdigest()} {name}\n" for name, data in sorted(payload.items()))
|
||||
payload["SHA256SUMS"] = checksums.encode()
|
||||
|
||||
+1
-1
@@ -54,7 +54,7 @@ class Gitea:
|
||||
return self.fetch("GET", url)
|
||||
|
||||
def upload(self, release_id, path):
|
||||
boundary = "rivet-patina-" + uuid.uuid4().hex
|
||||
boundary = "bass-foundry-" + uuid.uuid4().hex
|
||||
body = (
|
||||
f"--{boundary}\r\nContent-Disposition: form-data; name=\"attachment\"; filename=\"{path.name}\"\r\n"
|
||||
"Content-Type: application/octet-stream\r\n\r\n"
|
||||
|
||||
Generated
+40
@@ -158,6 +158,8 @@ dependencies = [
|
||||
"crucible-ui",
|
||||
"egui",
|
||||
"image",
|
||||
"knurl-core",
|
||||
"knurl-ui",
|
||||
"lathe-core",
|
||||
"lathe-ui",
|
||||
"patina-core",
|
||||
@@ -167,6 +169,8 @@ dependencies = [
|
||||
"rivet-midi",
|
||||
"temper-core",
|
||||
"temper-ui",
|
||||
"weld-core",
|
||||
"weld-ui",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -250,6 +254,24 @@ version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
||||
|
||||
[[package]]
|
||||
name = "knurl-core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"common-dsp",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "knurl-ui"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"common-dsp",
|
||||
"common-ui",
|
||||
"egui",
|
||||
"knurl-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lathe-core"
|
||||
version = "0.1.0"
|
||||
@@ -642,6 +664,24 @@ version = "0.9.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||
|
||||
[[package]]
|
||||
name = "weld-core"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"crossbeam-queue",
|
||||
"rustfft",
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "weld-ui"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"common-ui",
|
||||
"egui",
|
||||
"weld-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-link"
|
||||
version = "0.2.1"
|
||||
|
||||
@@ -23,3 +23,7 @@ lathe-core = { path = "../../plugins/lathe/core" }
|
||||
lathe-ui = { path = "../../plugins/lathe/ui" }
|
||||
temper-core = { path = "../../plugins/temper/core" }
|
||||
temper-ui = { path = "../../plugins/temper/ui" }
|
||||
knurl-core = { path = "../../plugins/knurl/core" }
|
||||
knurl-ui = { path = "../../plugins/knurl/ui" }
|
||||
weld-core = { path = "../../plugins/weld/core" }
|
||||
weld-ui = { path = "../../plugins/weld/ui" }
|
||||
@@ -10,8 +10,12 @@ fn main() {
|
||||
.find(|a| a[0] == "--plugin")
|
||||
.map(|a| a[1].as_str())
|
||||
.unwrap_or("rivet");
|
||||
if !["rivet", "patina", "anvil", "crucible", "lathe", "temper"].contains(&plugin) {
|
||||
eprintln!("Use --plugin rivet, patina, anvil, crucible, lathe or temper");
|
||||
if ![
|
||||
"rivet", "patina", "anvil", "crucible", "lathe", "temper", "weld", "knurl",
|
||||
]
|
||||
.contains(&plugin)
|
||||
{
|
||||
eprintln!("Use --plugin rivet, patina, anvil, crucible, lathe, temper, weld or knurl");
|
||||
std::process::exit(2);
|
||||
}
|
||||
let patina = plugin == "patina" || args.iter().any(|arg| arg == "--resonance");
|
||||
@@ -20,7 +24,13 @@ fn main() {
|
||||
let crucible = plugin == "crucible";
|
||||
let lathe = plugin == "lathe";
|
||||
let temper = plugin == "temper";
|
||||
let (width, height) = if temper {
|
||||
let weld = plugin == "weld";
|
||||
let knurl = plugin == "knurl";
|
||||
let (width, height) = if knurl {
|
||||
(knurl_ui::WIDTH, knurl_ui::HEIGHT)
|
||||
} else if weld {
|
||||
(weld_ui::WIDTH, weld_ui::HEIGHT)
|
||||
} else if temper {
|
||||
(temper_ui::WIDTH, temper_ui::HEIGHT)
|
||||
} else if lathe {
|
||||
(lathe_ui::WIDTH, lathe_ui::HEIGHT)
|
||||
@@ -139,6 +149,63 @@ fn main() {
|
||||
}
|
||||
temper_state.accept_frame(engine.take_analyzer());
|
||||
}
|
||||
let mut knurl_settings = knurl_core::Settings::default();
|
||||
let mut knurl_state = knurl_ui::State::default();
|
||||
if knurl {
|
||||
// An F1 saw bass with the default Fry pattern, jitter and grit.
|
||||
let mut engine = knurl_core::Engine::new(48000., 2).unwrap();
|
||||
engine.set_settings(knurl_settings).unwrap();
|
||||
let mut saw = common_dsp::Saw::new(48000., 43.65);
|
||||
for i in 0..36000 {
|
||||
let x = (saw.sample() * 2.2).tanh() * 0.5;
|
||||
engine.process_sample([x, x]);
|
||||
if i % 1600 == 0 {
|
||||
knurl_state.accept_frame(engine.take_analyzer());
|
||||
}
|
||||
}
|
||||
knurl_state.accept_frame(engine.take_analyzer());
|
||||
}
|
||||
let mut weld_settings = weld_core::Settings::default();
|
||||
let mut weld_state = weld_ui::State::default();
|
||||
if weld {
|
||||
// Two layers of an F1 saw bass. The sidechain layer is polarity-flipped and runs
|
||||
// through an allpass at 400 Hz, as an EQ in its chain would leave it. The real
|
||||
// analyzer measures them and its fits go back to the engine, as on the worker.
|
||||
let mut engine = weld_core::Engine::new(48000., 2).unwrap();
|
||||
engine.set_settings(weld_settings).unwrap();
|
||||
let link = engine.link();
|
||||
let mut analyzer = weld_core::Analyzer::new(48000., weld_core::Fit::NONE);
|
||||
let mut other = weld_core::Chain::new(
|
||||
weld_core::Fit {
|
||||
flip: true,
|
||||
count: 1,
|
||||
sections: [weld_core::Section { fc: 400., q: 0.7 }; weld_core::MAX_SECTIONS],
|
||||
},
|
||||
48000.,
|
||||
);
|
||||
let mut saw = common_dsp::Saw::new(48000., 43.65);
|
||||
for i in 0..48000 * 4 {
|
||||
let x = (saw.sample() * 1.6).tanh() * 0.4;
|
||||
let b = 0.8 * other.process(0, x);
|
||||
engine.process_sample([x, x], [b, b]);
|
||||
if i % 1600 == 0 {
|
||||
weld_state.accept_frame(engine.take_analyzer());
|
||||
}
|
||||
while let Some(settings) = link.pop_settings() {
|
||||
analyzer.set_settings(settings);
|
||||
}
|
||||
while let Some(block) = link.pop_block() {
|
||||
analyzer.push(&block.a, &block.b);
|
||||
if let Some(update) = analyzer.poll() {
|
||||
if let Some(fit) = update.fit {
|
||||
link.push_fit(fit);
|
||||
}
|
||||
weld_state.accept_report(update.report);
|
||||
}
|
||||
}
|
||||
}
|
||||
weld_state.accept_frame(engine.take_analyzer());
|
||||
}
|
||||
let mut crucible_settings = crucible_core::Settings {
|
||||
folder: "C:\\Users\\you\\Documents\\Crucible".into(),
|
||||
..Default::default()
|
||||
@@ -227,7 +294,11 @@ fn main() {
|
||||
let session_motif = session.motifs[0].id;
|
||||
shared.replace(session).unwrap();
|
||||
let ctx = egui::Context::default();
|
||||
if temper {
|
||||
if knurl {
|
||||
knurl_ui::style(&ctx);
|
||||
} else if weld {
|
||||
weld_ui::style(&ctx);
|
||||
} else if temper {
|
||||
temper_ui::style(&ctx);
|
||||
} else if lathe {
|
||||
lathe_ui::style(&ctx);
|
||||
@@ -260,7 +331,11 @@ fn main() {
|
||||
},
|
||||
|ui| {
|
||||
egui::CentralPanel::default().show(ui, |ui| {
|
||||
if temper {
|
||||
if knurl {
|
||||
knurl_ui::show(ui, &mut knurl_settings, &mut knurl_state);
|
||||
} else if weld {
|
||||
weld_ui::show(ui, &mut weld_settings, &mut weld_state);
|
||||
} else if temper {
|
||||
temper_ui::show(ui, &mut temper_settings, &mut temper_state);
|
||||
} else if lathe {
|
||||
lathe_ui::show(ui, &mut lathe_settings, &mut lathe_state);
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# Copy to .env and fill in. The container refuses to start while a required value is missing,
|
||||
# so the site never goes live without an Impressum.
|
||||
|
||||
# Public URL of the site, used for canonical links, the sitemap and robots.txt (build time).
|
||||
SITE_URL=https://fl.narl.io
|
||||
|
||||
# Impressum (§ 5 DDG) and controller in the privacy policy. Required.
|
||||
# The address must be one where legal documents can be served: no P.O. box.
|
||||
IMPRESSUM_NAME=Max Mustermann
|
||||
IMPRESSUM_STREET=Musterstraße 1
|
||||
IMPRESSUM_CITY=12345 Musterstadt
|
||||
IMPRESSUM_EMAIL=kontakt@example.org
|
||||
|
||||
# Optional. Defaults to "Deutschland".
|
||||
IMPRESSUM_COUNTRY=Deutschland
|
||||
# Optional. Leave empty to hide the phone line.
|
||||
IMPRESSUM_PHONE=
|
||||
# Optional. Name and address of the hosting provider, if one processes visitor data for you
|
||||
# (Art. 28 GDPR), e.g. "Hetzner Online GmbH, Industriestr. 25, 91710 Gunzenhausen".
|
||||
# Leave empty to hide that paragraph.
|
||||
HOSTER=
|
||||
@@ -0,0 +1,4 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.astro/
|
||||
.env
|
||||
@@ -0,0 +1,30 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
# Build context is the repository root, so the site can read plugins/catalog.json, the
|
||||
# plugin versions and the editor screenshots. Dockerfile.dockerignore keeps the context small.
|
||||
|
||||
FROM node:24-alpine AS build
|
||||
WORKDIR /repo/website
|
||||
COPY website/package.json website/package-lock.json ./
|
||||
RUN npm ci --no-audit --no-fund
|
||||
COPY . /repo
|
||||
ARG SITE_URL=https://fl.narl.io
|
||||
ENV SITE_URL=$SITE_URL
|
||||
RUN npm run build
|
||||
|
||||
FROM nginxinc/nginx-unprivileged:stable-alpine
|
||||
COPY website/docker/nginx.conf /etc/nginx/nginx.conf
|
||||
COPY website/docker/security-headers.conf /etc/nginx/security-headers.conf
|
||||
COPY website/docker/40-legal-notice.sh /docker-entrypoint.d/40-legal-notice.sh
|
||||
COPY --from=build /repo/website/dist /usr/share/nginx/html
|
||||
COPY --from=build /repo/website/dist/impressum/index.html /opt/legal-templates/impressum/index.html
|
||||
COPY --from=build /repo/website/dist/datenschutz/index.html /opt/legal-templates/datenschutz/index.html
|
||||
|
||||
# Only the two legal pages are rewritten at start-up; everything else stays read-only.
|
||||
USER root
|
||||
RUN rm -f /etc/nginx/conf.d/default.conf \
|
||||
&& chown 101:101 /usr/share/nginx/html/impressum/index.html /usr/share/nginx/html/datenschutz/index.html
|
||||
USER 101
|
||||
|
||||
EXPOSE 8080
|
||||
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s \
|
||||
CMD wget -q -O /dev/null http://127.0.0.1:8080/healthz || exit 1
|
||||
@@ -0,0 +1,10 @@
|
||||
# Allowlist for the repository-root build context: only what the site reads.
|
||||
*
|
||||
!website/
|
||||
!plugins/catalog.json
|
||||
!plugins/*/plugin/Cargo.toml
|
||||
!docs/*/assets/editor.png
|
||||
website/node_modules
|
||||
website/dist
|
||||
website/.astro
|
||||
website/.env
|
||||
@@ -0,0 +1,98 @@
|
||||
# Bass Foundry website
|
||||
|
||||
The site at [fl.narl.io](https://fl.narl.io): one static [Astro](https://astro.build) site
|
||||
with a home page, one page per plugin and the legal pages. An unprivileged nginx container
|
||||
serves it behind Traefik.
|
||||
|
||||
The site reads its plugin data from the repository. When a plugin is added or released, the
|
||||
next build picks it up:
|
||||
|
||||
- names, descriptions and CLAP IDs come from `plugins/catalog.json`;
|
||||
- versions come from `plugins/<plugin>/plugin/Cargo.toml`, and the download links point to
|
||||
`<plugin>-v<version>` on Gitea;
|
||||
- editor previews come from `docs/<plugin>/assets/editor.png`.
|
||||
|
||||
The site's own copy for each plugin (role, problem, highlights, where to load it, latency) is in
|
||||
`src/data/plugins.ts`. The build fails if a catalog entry has no copy there. The "On the bench"
|
||||
ideas are copied from `docs/ideas.md`, so update them by hand when that list changes.
|
||||
|
||||
Download links go to the release tag of the version in `Cargo.toml`. Deploy the site after the
|
||||
release is published, not after the version bump, or the link for that plugin is dead until
|
||||
the release exists.
|
||||
|
||||
The site sets no cookies, stores nothing in the browser and loads nothing from third parties.
|
||||
Fonts, images and styles all come from the same server, there is no JavaScript, and nginx
|
||||
writes no access logs. The privacy policy (`src/pages/datenschutz.astro`) says exactly this,
|
||||
so keep the two in step.
|
||||
|
||||
## Development
|
||||
|
||||
```sh
|
||||
cd website
|
||||
npm ci
|
||||
npm run dev # http://localhost:4321/
|
||||
npm run build # astro check, then a static build into dist/
|
||||
npm run preview
|
||||
npm run og # re-renders public/og.png
|
||||
```
|
||||
|
||||
`npm run og` sets its text in Roboto Condensed from `plugins/common/ui/assets`, so no font
|
||||
needs to be installed. The logo is `public/favicon.svg` (copied to `src/assets/logo.svg`): a
|
||||
riveted steel plate with a knurled saw wave.
|
||||
|
||||
The Impressum and the privacy policy contain `%%IMPRESSUM_…%%` placeholders. The container
|
||||
fills them in when it starts, so the operator's name and address never end up in git.
|
||||
|
||||
## Running with Docker
|
||||
|
||||
The build context is the repository root, so the image can read the catalog, the versions and
|
||||
the screenshots. `Dockerfile.dockerignore` keeps the context to those files and `website/`.
|
||||
|
||||
```sh
|
||||
cd website
|
||||
cp .env.example .env # fill in the Impressum details
|
||||
docker compose up -d --build
|
||||
curl -I http://127.0.0.1:8080/
|
||||
```
|
||||
|
||||
| Variable | Required | Used for |
|
||||
| ------------------- | -------- | -------------------------------------------------------------- |
|
||||
| `SITE_URL` | build | Canonical links, sitemap, robots.txt, `og:image`. Rebuild to change. |
|
||||
| `IMPRESSUM_NAME` | yes | Impressum and controller in the privacy policy |
|
||||
| `IMPRESSUM_STREET` | yes | Street and number (no P.O. box) |
|
||||
| `IMPRESSUM_CITY` | yes | Postcode and city |
|
||||
| `IMPRESSUM_EMAIL` | yes | Contact address, written out as HTML entities |
|
||||
| `IMPRESSUM_COUNTRY` | no | Defaults to `Deutschland` |
|
||||
| `IMPRESSUM_PHONE` | no | Hides the phone line when empty |
|
||||
| `HOSTER` | no | Names the hosting provider (Art. 28 GDPR); hidden when empty |
|
||||
|
||||
The container refuses to start while a required variable is missing, so the site cannot go
|
||||
live without an Impressum. The values are escaped and applied to fresh copies of the two pages
|
||||
on every start, so after changing `.env`, recreating the container (`docker compose up -d`) is
|
||||
enough. The container listens on 8080 as user 101 with all capabilities dropped. `/healthz`
|
||||
answers `ok` for health checks.
|
||||
|
||||
### Behind Traefik
|
||||
|
||||
`compose.override.yaml` puts the site on `fl.narl.io`: router labels, the external `narl`
|
||||
network, the `websecure` entry point with the `https_resolver` certificate resolver, and
|
||||
`ports: !reset []` so nothing is published on the host. Docker Compose reads the override file
|
||||
automatically. TLS ends at Traefik. Redirects are relative, so they keep the proxy's scheme and
|
||||
host.
|
||||
|
||||
**If Traefik writes access logs for this router, the privacy policy is wrong.** It promises no
|
||||
access logs. Either turn them off for the router, or edit section 3 of `datenschutz.astro` (both
|
||||
languages): what is logged, why, and for how long.
|
||||
|
||||
## Before going live
|
||||
|
||||
- **Legal texts.** The Impressum and the privacy policy are written for a private,
|
||||
non-commercial project hosted in Germany. They are no substitute for legal advice. Update the
|
||||
"Stand" date when you change them.
|
||||
- **git.narl.io.** The privacy policy says that the downloads and the source code are on
|
||||
git.narl.io and that its own privacy information applies there. If you run that Gitea
|
||||
instance yourself, make sure it has that information.
|
||||
|
||||
## License
|
||||
|
||||
ISC, like the plugins. Roboto Condensed and Inter are under the SIL Open Font License.
|
||||
@@ -0,0 +1,23 @@
|
||||
// @ts-check
|
||||
import { defineConfig } from 'astro/config';
|
||||
import sitemap from '@astrojs/sitemap';
|
||||
|
||||
export default defineConfig({
|
||||
site: process.env.SITE_URL || 'https://fl.narl.io',
|
||||
trailingSlash: 'always',
|
||||
build: {
|
||||
// Everything goes into files under /_astro/ so the CSP can stay at 'self'
|
||||
// without hashes or 'unsafe-inline'.
|
||||
inlineStylesheets: 'never',
|
||||
},
|
||||
vite: {
|
||||
build: { assetsInlineLimit: 0 },
|
||||
// The plugin data and editor screenshots live in the repository above this folder.
|
||||
server: { fs: { allow: ['..'] } },
|
||||
},
|
||||
integrations: [
|
||||
sitemap({
|
||||
filter: (page) => !/\/(impressum|datenschutz)\/$/.test(page),
|
||||
}),
|
||||
],
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
# fl.narl.io behind Traefik on the external "narl" network. TLS ends at Traefik;
|
||||
# the container itself is not published on any host port.
|
||||
services:
|
||||
web:
|
||||
build:
|
||||
args:
|
||||
SITE_URL: https://fl.narl.io
|
||||
ports: !reset []
|
||||
networks:
|
||||
- narl
|
||||
labels:
|
||||
- "traefik.enable=true"
|
||||
- "traefik.docker.network=narl"
|
||||
- "traefik.http.routers.bass-foundry-website.rule=Host(`fl.narl.io`)"
|
||||
- "traefik.http.routers.bass-foundry-website.entrypoints=websecure"
|
||||
- "traefik.http.routers.bass-foundry-website.tls.certresolver=https_resolver"
|
||||
- "traefik.http.services.bass-foundry-website.loadbalancer.server.port=8080"
|
||||
|
||||
networks:
|
||||
narl:
|
||||
external: true
|
||||
@@ -0,0 +1,27 @@
|
||||
# Generic setup: the site on 127.0.0.1:8080. Put the reverse proxy (Traefik labels, networks)
|
||||
# in a compose.override.yaml and drop the port mapping there if the proxy reaches the
|
||||
# container over a Docker network. The build context is the repository root, because the
|
||||
# site reads the plugin catalog, versions and screenshots from it.
|
||||
services:
|
||||
web:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: website/Dockerfile
|
||||
args:
|
||||
SITE_URL: ${SITE_URL:-https://fl.narl.io}
|
||||
image: bass-foundry-website:latest
|
||||
env_file:
|
||||
- path: .env
|
||||
required: false
|
||||
ports:
|
||||
- "127.0.0.1:8080:8080"
|
||||
restart: unless-stopped
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: "1m"
|
||||
max-file: "3"
|
||||
Executable
+74
@@ -0,0 +1,74 @@
|
||||
#!/bin/sh
|
||||
# Fills the Impressum and the privacy policy with the operator's details from the environment.
|
||||
# Runs from the nginx image's /docker-entrypoint.d/ hook on every start. It works from pristine
|
||||
# copies, so changing a variable and restarting the container is enough.
|
||||
set -eu
|
||||
|
||||
HTML=/usr/share/nginx/html
|
||||
TEMPLATES=/opt/legal-templates
|
||||
PAGES="impressum/index.html datenschutz/index.html"
|
||||
|
||||
missing=""
|
||||
for var in IMPRESSUM_NAME IMPRESSUM_STREET IMPRESSUM_CITY IMPRESSUM_EMAIL; do
|
||||
eval "value=\${$var:-}"
|
||||
[ -n "$value" ] || missing="$missing $var"
|
||||
done
|
||||
if [ -n "$missing" ]; then
|
||||
echo "40-legal-notice: missing required variables:$missing" >&2
|
||||
echo "40-legal-notice: refusing to serve the site without an Impressum (see .env.example)" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
case "$IMPRESSUM_EMAIL" in
|
||||
*@*.*) ;;
|
||||
*)
|
||||
echo "40-legal-notice: IMPRESSUM_EMAIL does not look like an email address" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
|
||||
# One line, HTML-escaped.
|
||||
html() {
|
||||
printf '%s' "$1" | tr '\r\n' ' ' |
|
||||
sed -e 's/&/\&/g' -e 's/</\</g' -e 's/>/\>/g' -e 's/"/\"/g' -e "s/'/\'/g"
|
||||
}
|
||||
|
||||
# Every character as a numeric entity, which keeps the address away from naive scrapers.
|
||||
entities() {
|
||||
printf '%s' "$1" | od -An -tu1 | tr -s ' \n' '\n\n' | sed -e '/^$/d' -e 's/.*/\&#&;/' | tr -d '\n'
|
||||
}
|
||||
|
||||
# Escapes a replacement for sed's s|…|…| (backslash, the | delimiter and &).
|
||||
repl() {
|
||||
printf '%s' "$1" | sed -e 's/[\\|&]/\\&/g'
|
||||
}
|
||||
|
||||
script=$(mktemp)
|
||||
trap 'rm -f "$script"' EXIT
|
||||
{
|
||||
echo "s|%%IMPRESSUM_NAME%%|$(repl "$(html "$IMPRESSUM_NAME")")|g"
|
||||
echo "s|%%IMPRESSUM_STREET%%|$(repl "$(html "$IMPRESSUM_STREET")")|g"
|
||||
echo "s|%%IMPRESSUM_CITY%%|$(repl "$(html "$IMPRESSUM_CITY")")|g"
|
||||
echo "s|%%IMPRESSUM_COUNTRY%%|$(repl "$(html "${IMPRESSUM_COUNTRY:-Deutschland}")")|g"
|
||||
echo "s|%%IMPRESSUM_EMAIL%%|$(repl "$(entities "$IMPRESSUM_EMAIL")")|g"
|
||||
for pair in phone:IMPRESSUM_PHONE hoster:HOSTER; do
|
||||
key=${pair%%:*}
|
||||
var=${pair#*:}
|
||||
eval "value=\${$var:-}"
|
||||
if [ -n "$value" ]; then
|
||||
echo "s|%%$var%%|$(repl "$(html "$value")")|g"
|
||||
else
|
||||
echo "s|<p data-optional=\"$key\"[^>]*>[^<]*</p>||g"
|
||||
fi
|
||||
done
|
||||
} >"$script"
|
||||
|
||||
for page in $PAGES; do
|
||||
sed -f "$script" "$TEMPLATES/$page" >"$HTML/$page"
|
||||
if grep -q '%%[A-Z_]*%%' "$HTML/$page"; then
|
||||
echo "40-legal-notice: unfilled placeholder left in $page" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
echo "40-legal-notice: filled in the Impressum and the privacy policy"
|
||||
@@ -0,0 +1,63 @@
|
||||
# The privacy policy (src/pages/datenschutz.astro) promises that no access logs are written.
|
||||
# Keep access_log off and the error log at "crit" unless that text changes with it.
|
||||
worker_processes auto;
|
||||
error_log /dev/stderr crit;
|
||||
pid /tmp/nginx.pid;
|
||||
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
client_body_temp_path /tmp/client_temp;
|
||||
proxy_temp_path /tmp/proxy_temp;
|
||||
fastcgi_temp_path /tmp/fastcgi_temp;
|
||||
uwsgi_temp_path /tmp/uwsgi_temp;
|
||||
scgi_temp_path /tmp/scgi_temp;
|
||||
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
|
||||
access_log off;
|
||||
log_not_found off;
|
||||
server_tokens off;
|
||||
sendfile on;
|
||||
tcp_nopush on;
|
||||
keepalive_timeout 65;
|
||||
charset utf-8;
|
||||
charset_types text/css application/javascript image/svg+xml application/xml text/plain;
|
||||
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_min_length 1024;
|
||||
gzip_types text/css application/javascript image/svg+xml application/xml text/plain application/json;
|
||||
|
||||
server {
|
||||
listen 8080;
|
||||
server_name _;
|
||||
root /usr/share/nginx/html;
|
||||
|
||||
# Relative Location headers, so redirects keep the scheme and host of the reverse proxy.
|
||||
absolute_redirect off;
|
||||
|
||||
error_page 404 /404.html;
|
||||
|
||||
include /etc/nginx/security-headers.conf;
|
||||
add_header Cache-Control "no-cache" always;
|
||||
|
||||
location /_astro/ {
|
||||
include /etc/nginx/security-headers.conf;
|
||||
add_header Cache-Control "public, max-age=31536000, immutable" always;
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location = /healthz {
|
||||
default_type text/plain;
|
||||
return 200 "ok\n";
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri $uri/ =404;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
# Included in every location that sets its own headers, because add_header is not inherited
|
||||
# into a location that has any add_header of its own.
|
||||
add_header Content-Security-Policy "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; font-src 'self'; connect-src 'self'; manifest-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=(), usb=()" always;
|
||||
add_header Cross-Origin-Opener-Policy "same-origin" always;
|
||||
Generated
+5243
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "bass-foundry-website",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"version": "1.0.0",
|
||||
"description": "Website for the Bass Foundry plugin suite",
|
||||
"license": "ISC",
|
||||
"scripts": {
|
||||
"dev": "astro dev",
|
||||
"build": "astro check && astro build",
|
||||
"preview": "astro preview",
|
||||
"check": "astro check",
|
||||
"og": "node scripts/og-image.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@astrojs/sitemap": "^3.7.4",
|
||||
"@fontsource-variable/inter": "^5.3.0",
|
||||
"@fontsource-variable/roboto-condensed": "^5.3.0",
|
||||
"astro": "^7.3.5",
|
||||
"sharp": "^0.35.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@astrojs/check": "^0.9.10",
|
||||
"typescript": "^6.0.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<defs>
|
||||
<linearGradient id="p" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#22252a"/>
|
||||
<stop offset="1" stop-color="#121417"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect x="2" y="2" width="60" height="60" rx="14" fill="url(#p)" stroke="#3a3e45" stroke-width="2"/>
|
||||
<g fill="#5a6069">
|
||||
<circle cx="12" cy="12" r="2.6"/>
|
||||
<circle cx="52" cy="12" r="2.6"/>
|
||||
<circle cx="12" cy="52" r="2.6"/>
|
||||
<circle cx="52" cy="52" r="2.6"/>
|
||||
</g>
|
||||
<path d="M11 42 L24 20 L24 42 L36 29 L36 42 L50 20 L50 42" fill="none" stroke="#ff0160" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 695 B |
Binary file not shown.
|
After Width: | Height: | Size: 235 KiB |
@@ -0,0 +1,82 @@
|
||||
// Renders public/og.png (1200×630), the preview image for link shares: the name, the
|
||||
// waveform from the hero and three editor previews. Run with `npm run og` after the look
|
||||
// changes. The text is set in Roboto Condensed, loaded from the plugins' own font folder.
|
||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
|
||||
const root = new URL('../', import.meta.url);
|
||||
const repo = new URL('../', root);
|
||||
const W = 1200;
|
||||
const H = 630;
|
||||
|
||||
// librsvg finds fonts through fontconfig; point it at the embedded editor fonts.
|
||||
const fonts = await mkdtemp(join(tmpdir(), 'og-fonts-'));
|
||||
await writeFile(
|
||||
join(fonts, 'fonts.conf'),
|
||||
`<?xml version="1.0"?><!DOCTYPE fontconfig SYSTEM "fonts.dtd"><fontconfig>
|
||||
<dir>${new URL('plugins/common/ui/assets/', repo).pathname}</dir><cachedir>${fonts}</cachedir>
|
||||
</fontconfig>`,
|
||||
);
|
||||
process.env.FONTCONFIG_FILE = join(fonts, 'fonts.conf');
|
||||
const { default: sharp } = await import('sharp');
|
||||
|
||||
// Knurl's Fry pattern on a tanh saw, as in src/components/Hero.astro.
|
||||
const pattern = [0, -14, -5, -14].map((db) => 10 ** (db / 20));
|
||||
const points = [];
|
||||
for (let i = 0; i <= 700; i++) {
|
||||
const phase = (i / 700) * 6;
|
||||
const cycle = Math.floor(phase);
|
||||
const frac = phase - cycle;
|
||||
let g = pattern[cycle % 4];
|
||||
if (frac > 0.85) {
|
||||
const t = (frac - 0.85) / 0.15;
|
||||
g += (pattern[(cycle + 1) % 4] - g) * (0.5 - 0.5 * Math.cos(Math.PI * t));
|
||||
}
|
||||
const y = Math.tanh(2.2 * (2 * frac - 1)) / Math.tanh(2.2);
|
||||
points.push(`${(70 + (i / 700) * 1060).toFixed(1)},${(492 - y * g * 68).toFixed(1)}`);
|
||||
}
|
||||
|
||||
const background = Buffer.from(`<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}">
|
||||
<defs>
|
||||
<radialGradient id="glow" cx="0.5" cy="1" r="0.75">
|
||||
<stop offset="0" stop-color="#ff0160" stop-opacity="0.32"/>
|
||||
<stop offset="1" stop-color="#ff0160" stop-opacity="0"/>
|
||||
</radialGradient>
|
||||
<linearGradient id="title" x1="0" y1="0" x2="1" y2="0">
|
||||
<stop offset="0" stop-color="#ff0160"/>
|
||||
<stop offset="0.6" stop-color="#ff5c95"/>
|
||||
<stop offset="1" stop-color="#b8c0cc"/>
|
||||
</linearGradient>
|
||||
<pattern id="grid" width="40" height="40" patternUnits="userSpaceOnUse">
|
||||
<path d="M40 0H0V40" fill="none" stroke="#b8c0cc" stroke-opacity="0.06"/>
|
||||
</pattern>
|
||||
<filter id="blur"><feGaussianBlur stdDeviation="7"/></filter>
|
||||
</defs>
|
||||
<rect width="${W}" height="${H}" fill="#0b0c0e"/>
|
||||
<rect width="${W}" height="${H}" fill="url(#grid)"/>
|
||||
<rect width="${W}" height="${H}" fill="url(#glow)"/>
|
||||
<text x="70" y="118" font-family="Roboto Condensed" font-weight="500" font-size="26" letter-spacing="6" fill="#ff0160">CLAP PLUGINS FOR FL STUDIO</text>
|
||||
<text x="66" y="236" font-family="Roboto Condensed" font-weight="500" font-size="128" fill="#e8e9ec">BASS</text>
|
||||
<text x="66" y="348" font-family="Roboto Condensed" font-weight="500" font-size="128" fill="url(#title)">FOUNDRY</text>
|
||||
<path d="M${points.join('L')}" fill="none" stroke="#ff0160" stroke-width="9" opacity="0.4" filter="url(#blur)"/>
|
||||
<path d="M${points.join('L')}" fill="none" stroke="#ff0160" stroke-width="3" stroke-linejoin="round"/>
|
||||
<text x="70" y="596" font-family="Roboto Condensed" font-size="24" letter-spacing="3" fill="#8c929c">RIDDIM · DUBSTEP · BASS MUSIC — FL.NARL.IO</text>
|
||||
</svg>`);
|
||||
|
||||
const shot = async (name, width) => {
|
||||
const img = sharp(await readFile(new URL(`docs/${name}/assets/editor.png`, repo))).resize(width);
|
||||
const { height } = await img.clone().toBuffer({ resolveWithObject: true }).then((r) => r.info);
|
||||
const mask = Buffer.from(`<svg width="${width}" height="${height}"><rect width="${width}" height="${height}" rx="10"/></svg>`);
|
||||
return img.composite([{ input: mask, blend: 'dest-in' }]).png().toBuffer();
|
||||
};
|
||||
|
||||
await sharp(background)
|
||||
.composite([
|
||||
{ input: await shot('lathe', 430), left: 700, top: 36 },
|
||||
{ input: await shot('knurl', 430), left: 640, top: 116 },
|
||||
])
|
||||
.png({ compressionLevel: 9 })
|
||||
.toFile(new URL('public/og.png', root).pathname);
|
||||
await rm(fonts, { recursive: true });
|
||||
console.log('wrote public/og.png');
|
||||
@@ -0,0 +1,16 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
||||
<defs>
|
||||
<linearGradient id="p" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0" stop-color="#22252a"/>
|
||||
<stop offset="1" stop-color="#121417"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect x="2" y="2" width="60" height="60" rx="14" fill="url(#p)" stroke="#3a3e45" stroke-width="2"/>
|
||||
<g fill="#5a6069">
|
||||
<circle cx="12" cy="12" r="2.6"/>
|
||||
<circle cx="52" cy="12" r="2.6"/>
|
||||
<circle cx="12" cy="52" r="2.6"/>
|
||||
<circle cx="52" cy="52" r="2.6"/>
|
||||
</g>
|
||||
<path d="M11 42 L24 20 L24 42 L36 29 L36 42 L50 20 L50 42" fill="none" stroke="#ff0160" stroke-width="5" stroke-linecap="round" stroke-linejoin="round"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 695 B |
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user